@pyric/cli 0.1.0-alpha.16 → 0.1.0-alpha.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +42 -12
- package/dist/assurance/.generated/conformance-verdicts.d.ts +80 -72
- package/dist/assurance/.generated/conformance-verdicts.d.ts.map +1 -1
- package/dist/assurance/.generated/conformance-verdicts.js +80 -72
- package/dist/assurance/.generated/conformance-verdicts.js.map +1 -1
- package/dist/bridge/server/bridge.d.ts.map +1 -1
- package/dist/bridge/server/bridge.js +4 -2
- package/dist/bridge/server/bridge.js.map +1 -1
- package/dist/bridge/server/peer.d.ts.map +1 -1
- package/dist/bridge/server/peer.js +1 -0
- package/dist/bridge/server/peer.js.map +1 -1
- package/dist/cli/database-rules.d.ts.map +1 -1
- package/dist/cli/database-rules.js +6 -4
- package/dist/cli/database-rules.js.map +1 -1
- package/dist/cli/dev-runner.d.ts +9 -0
- package/dist/cli/dev-runner.d.ts.map +1 -1
- package/dist/cli/dev-runner.js +18 -0
- package/dist/cli/dev-runner.js.map +1 -1
- package/dist/cli/serve.d.ts.map +1 -1
- package/dist/cli/serve.js +62 -6
- package/dist/cli/serve.js.map +1 -1
- package/dist/cli/verify.js +2 -2
- package/dist/cli/verify.js.map +1 -1
- package/dist/conformance/.generated/can-i-use-browser.d.ts.map +1 -1
- package/dist/conformance/.generated/can-i-use-browser.js +1 -1
- package/dist/conformance/.generated/can-i-use-browser.js.map +1 -1
- package/dist/conformance/.generated/can-i-use.d.ts.map +1 -1
- package/dist/conformance/.generated/can-i-use.js +1 -1
- package/dist/conformance/.generated/can-i-use.js.map +1 -1
- package/dist/conformance/.generated/conformance-docs.d.ts.map +1 -1
- package/dist/conformance/.generated/conformance-docs.js +1 -1
- package/dist/conformance/.generated/conformance-docs.js.map +1 -1
- package/dist/functions-rtdb/child.d.ts +1 -0
- package/dist/functions-rtdb/child.d.ts.map +1 -1
- package/dist/functions-rtdb/child.js +11 -1
- package/dist/functions-rtdb/child.js.map +1 -1
- package/dist/functions-rtdb/development-runtime.d.ts +1 -0
- package/dist/functions-rtdb/development-runtime.d.ts.map +1 -1
- package/dist/functions-rtdb/development-runtime.js +1 -0
- package/dist/functions-rtdb/development-runtime.js.map +1 -1
- package/dist/next/client-aliases.d.ts +11 -0
- package/dist/next/client-aliases.d.ts.map +1 -0
- package/dist/next/client-aliases.js +38 -0
- package/dist/next/client-aliases.js.map +1 -0
- package/dist/next/dev-rewrites.d.ts +9 -0
- package/dist/next/dev-rewrites.d.ts.map +1 -0
- package/dist/next/dev-rewrites.js +53 -0
- package/dist/next/dev-rewrites.js.map +1 -0
- package/dist/next/guard.d.ts +15 -0
- package/dist/next/guard.d.ts.map +1 -0
- package/dist/next/guard.js +52 -0
- package/dist/next/guard.js.map +1 -0
- package/dist/next/index.d.ts +12 -0
- package/dist/next/index.d.ts.map +1 -0
- package/dist/next/index.js +11 -0
- package/dist/next/index.js.map +1 -0
- package/dist/next/runtime-env.d.ts +7 -0
- package/dist/next/runtime-env.d.ts.map +1 -0
- package/dist/next/runtime-env.js +13 -0
- package/dist/next/runtime-env.js.map +1 -0
- package/dist/next/server-external-packages.d.ts +10 -0
- package/dist/next/server-external-packages.d.ts.map +1 -0
- package/dist/next/server-external-packages.js +34 -0
- package/dist/next/server-external-packages.js.map +1 -0
- package/dist/next/target-url.d.ts +11 -0
- package/dist/next/target-url.d.ts.map +1 -0
- package/dist/next/target-url.js +36 -0
- package/dist/next/target-url.js.map +1 -0
- package/dist/next/turbopack-config.d.ts +9 -0
- package/dist/next/turbopack-config.d.ts.map +1 -0
- package/dist/next/turbopack-config.js +39 -0
- package/dist/next/turbopack-config.js.map +1 -0
- package/dist/next/types.d.ts +40 -0
- package/dist/next/types.d.ts.map +1 -0
- package/dist/next/types.js +5 -0
- package/dist/next/types.js.map +1 -0
- package/dist/next/webpack-config.d.ts +11 -0
- package/dist/next/webpack-config.d.ts.map +1 -0
- package/dist/next/webpack-config.js +51 -0
- package/dist/next/webpack-config.js.map +1 -0
- package/dist/next/with-pyric.d.ts +22 -0
- package/dist/next/with-pyric.d.ts.map +1 -0
- package/dist/next/with-pyric.js +49 -0
- package/dist/next/with-pyric.js.map +1 -0
- package/dist/register/app-bridge.d.ts +9 -0
- package/dist/register/app-bridge.d.ts.map +1 -0
- package/dist/register/app-bridge.js +56 -0
- package/dist/register/app-bridge.js.map +1 -0
- package/dist/register/hooks.d.ts.map +1 -1
- package/dist/register/hooks.js +6 -1
- package/dist/register/hooks.js.map +1 -1
- package/dist/register/index.js +1 -1
- package/dist/register/index.js.map +1 -1
- package/dist/register/mapping.d.ts +3 -1
- package/dist/register/mapping.d.ts.map +1 -1
- package/dist/register/mapping.js +41 -5
- package/dist/register/mapping.js.map +1 -1
- package/dist/remote/index.d.ts.map +1 -1
- package/dist/remote/index.js +5 -3
- package/dist/remote/index.js.map +1 -1
- package/dist/rtdb/rules-json.d.ts +12 -0
- package/dist/rtdb/rules-json.d.ts.map +1 -1
- package/dist/rtdb/rules-json.js +98 -0
- package/dist/rtdb/rules-json.js.map +1 -1
- package/dist/serve/bundler.d.ts.map +1 -1
- package/dist/serve/bundler.js +2 -0
- package/dist/serve/bundler.js.map +1 -1
- package/dist/serve/discovery.d.ts +4 -4
- package/dist/serve/discovery.d.ts.map +1 -1
- package/dist/serve/discovery.js +59 -38
- package/dist/serve/discovery.js.map +1 -1
- package/dist/serve/entries/app-ai-passthrough.d.ts +8 -0
- package/dist/serve/entries/app-ai-passthrough.d.ts.map +1 -0
- package/dist/serve/entries/app-ai-passthrough.js +59 -0
- package/dist/serve/entries/app-ai-passthrough.js.map +1 -0
- package/dist/serve/entries/auth-helper-core.js +9 -7
- package/dist/serve/entries/auth-helper-core.js.map +1 -1
- package/dist/serve/entries/auth.d.ts +1 -0
- package/dist/serve/entries/auth.d.ts.map +1 -1
- package/dist/serve/entries/auth.js +1 -0
- package/dist/serve/entries/auth.js.map +1 -1
- package/dist/serve/entries/bridge-url.d.ts.map +1 -1
- package/dist/serve/entries/bridge-url.js +7 -2
- package/dist/serve/entries/bridge-url.js.map +1 -1
- package/dist/serve/entries/database.d.ts +1 -0
- package/dist/serve/entries/database.d.ts.map +1 -1
- package/dist/serve/entries/database.js +1 -0
- package/dist/serve/entries/database.js.map +1 -1
- package/dist/serve/entries/firestore.d.ts +1 -0
- package/dist/serve/entries/firestore.d.ts.map +1 -1
- package/dist/serve/entries/firestore.js +1 -0
- package/dist/serve/entries/firestore.js.map +1 -1
- package/dist/serve/entries/init.d.ts.map +1 -1
- package/dist/serve/entries/init.js +4 -2
- package/dist/serve/entries/init.js.map +1 -1
- package/dist/serve/entries/runtime.js +23 -0
- package/dist/serve/entries/runtime.js.map +1 -1
- package/dist/serve/entries/storage.d.ts +2 -0
- package/dist/serve/entries/storage.d.ts.map +1 -1
- package/dist/serve/entries/storage.js +9 -2
- package/dist/serve/entries/storage.js.map +1 -1
- package/dist/serve/html-injection.d.ts +3 -1
- package/dist/serve/html-injection.d.ts.map +1 -1
- package/dist/serve/html-injection.js +27 -1
- package/dist/serve/html-injection.js.map +1 -1
- package/dist/serve/rules.js +2 -2
- package/dist/serve/rules.js.map +1 -1
- package/dist/serve/runtime/chip-config.d.ts +1 -1
- package/dist/serve/runtime/chip-config.d.ts.map +1 -1
- package/dist/serve/runtime/chip-config.js +16 -8
- package/dist/serve/runtime/chip-config.js.map +1 -1
- package/dist/serve/runtime/chip.d.ts.map +1 -1
- package/dist/serve/runtime/chip.js +24 -3
- package/dist/serve/runtime/chip.js.map +1 -1
- package/dist/serve/runtime/status.d.ts +1 -0
- package/dist/serve/runtime/status.d.ts.map +1 -1
- package/dist/serve/runtime/status.js +71 -13
- package/dist/serve/runtime/status.js.map +1 -1
- package/dist/serve/sandbox-session.d.ts +1 -0
- package/dist/serve/sandbox-session.d.ts.map +1 -1
- package/dist/serve/sandbox-session.js +30 -2
- package/dist/serve/sandbox-session.js.map +1 -1
- package/dist/serve/site-ui/_astro/_slug_.C6QfVOxJ.css +1 -0
- package/dist/serve/site-ui/_astro/_studio_.B6b_G1ev.css +1 -0
- package/dist/serve/site-ui/_astro/app.B7pBzz5N.js +11 -0
- package/dist/serve/site-ui/_astro/app.boex5SnQ.js +1 -0
- package/dist/serve/site-ui/_astro/{chess-showcase.CnoxIle5.js → chess-showcase.DDqE-QGe.js} +1 -1
- package/dist/serve/site-ui/_astro/{example-runtime.R1d96L6-.js → example-runtime.B0byNQOl.js} +1 -1
- package/dist/serve/site-ui/_astro/index.uwPvjH_1.js +1 -0
- package/dist/serve/site-ui/_astro/reads.Dh3z0fJy.js +1 -0
- package/dist/serve/site-ui/_astro/sandbox-controls.C2IqtoSw.js +1252 -0
- package/dist/serve/site-ui/_astro/{seed.EyI3VYEu.js → seed.CCmj00su.js} +1 -1
- package/dist/serve/site-ui/auth/index.html +2 -2
- package/dist/serve/site-ui/docs/_rhythm/index.html +1 -1
- package/dist/serve/site-ui/docs/agent/set-up-your-agent/index.html +48 -13
- package/dist/serve/site-ui/docs/agent/set-up-your-agent.md +74 -11
- package/dist/serve/site-ui/docs/agent/watch-and-review/index.html +1 -1
- package/dist/serve/site-ui/docs/agent/work-with-an-agent/index.html +1 -1
- package/dist/serve/site-ui/docs/ai-compat/index.html +85 -85
- package/dist/serve/site-ui/docs/ai-compat.md +84 -84
- package/dist/serve/site-ui/docs/api-reference/index.html +3 -1
- package/dist/serve/site-ui/docs/api-reference.md +2 -0
- package/dist/serve/site-ui/docs/app-compat/index.html +28 -28
- package/dist/serve/site-ui/docs/app-compat.md +27 -27
- package/dist/serve/site-ui/docs/auth-compat/index.html +122 -122
- package/dist/serve/site-ui/docs/auth-compat.md +121 -121
- package/dist/serve/site-ui/docs/build/ai-logic/index.html +19 -2
- package/dist/serve/site-ui/docs/build/ai-logic.md +28 -0
- package/dist/serve/site-ui/docs/build/authentication/index.html +1 -1
- package/dist/serve/site-ui/docs/build/cloud-firestore/index.html +1 -1
- package/dist/serve/site-ui/docs/build/cloud-messaging/index.html +1 -1
- package/dist/serve/site-ui/docs/build/cloud-storage/index.html +1 -1
- package/dist/serve/site-ui/docs/build/realtime-database/index.html +1 -1
- package/dist/serve/site-ui/docs/conformance-scores/index.html +25 -10
- package/dist/serve/site-ui/docs/conformance-scores.md +23 -8
- package/dist/serve/site-ui/docs/create-pyric-reference-api/index.html +6 -6
- package/dist/serve/site-ui/docs/create-pyric-reference-api.md +5 -5
- package/dist/serve/site-ui/docs/database-compat/index.html +200 -448
- package/dist/serve/site-ui/docs/database-compat.md +198 -461
- package/dist/serve/site-ui/docs/examples/chess/index.html +2 -2
- package/dist/serve/site-ui/docs/examples/index.html +1 -1
- package/dist/serve/site-ui/docs/firestore-compat/index.html +186 -195
- package/dist/serve/site-ui/docs/firestore-compat.md +184 -195
- package/dist/serve/site-ui/docs/functions-rtdb-compat/index.html +15 -15
- package/dist/serve/site-ui/docs/functions-rtdb-compat.md +14 -14
- package/dist/serve/site-ui/docs/get-started/how-the-swap-works/index.html +1 -1
- package/dist/serve/site-ui/docs/get-started/nextjs/index.html +57 -0
- package/dist/serve/site-ui/docs/get-started/nextjs.md +86 -0
- package/dist/serve/site-ui/docs/get-started/start-building/index.html +38 -9
- package/dist/serve/site-ui/docs/get-started/start-building.md +62 -7
- package/dist/serve/site-ui/docs/get-started/vite/index.html +26 -0
- package/dist/serve/site-ui/docs/get-started/vite.md +45 -0
- package/dist/serve/site-ui/docs/index.json +711 -111
- package/dist/serve/site-ui/docs/messaging-compat/index.html +56 -56
- package/dist/serve/site-ui/docs/messaging-compat.md +55 -55
- package/dist/serve/site-ui/docs/observe/resolve-runtime-status/index.html +1 -1
- package/dist/serve/site-ui/docs/observe/see-whats-happening/index.html +1 -1
- package/dist/serve/site-ui/docs/observe/shape-your-data/index.html +1 -1
- package/dist/serve/site-ui/docs/overview/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-admin-app-reference-api/index.html +39 -13
- package/dist/serve/site-ui/docs/pyric-admin-app-reference-api.md +28 -2
- package/dist/serve/site-ui/docs/pyric-admin-auth-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-admin-database-reference-api/index.html +38 -6
- package/dist/serve/site-ui/docs/pyric-admin-database-reference-api.md +43 -0
- package/dist/serve/site-ui/docs/pyric-admin-firestore-reference-api/index.html +9 -1
- package/dist/serve/site-ui/docs/pyric-admin-firestore-reference-api.md +8 -0
- package/dist/serve/site-ui/docs/pyric-admin-messaging-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-admin-storage-reference-api/index.html +27 -4
- package/dist/serve/site-ui/docs/pyric-admin-storage-reference-api.md +23 -0
- package/dist/serve/site-ui/docs/pyric-ai-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-ai-scripting-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-app-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-auth-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-assurance-browser-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-assurance-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-bridge-client-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-bridge-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-conformance-browser-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-conformance-docs-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-conformance-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-credentials-node-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-discover-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-next-reference-api/index.html +123 -0
- package/dist/serve/site-ui/docs/pyric-cli-next-reference-api.md +99 -0
- package/dist/serve/site-ui/docs/pyric-cli-register-app-bridge-reference-api/index.html +127 -0
- package/dist/serve/site-ui/docs/pyric-cli-register-app-bridge-reference-api.md +174 -0
- package/dist/serve/site-ui/docs/pyric-cli-register-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-remote-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-serve-worker-reference-api/index.html +570 -326
- package/dist/serve/site-ui/docs/pyric-cli-serve-worker-reference-api.md +198 -6
- package/dist/serve/site-ui/docs/pyric-cli-verify-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-cli-vite-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-database-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-firestore-reference-api/index.html +2971 -627
- package/dist/serve/site-ui/docs/pyric-firestore-reference-api.md +2873 -517
- package/dist/serve/site-ui/docs/pyric-messaging-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-messaging-sw-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-rules-reference-api/index.html +43 -3
- package/dist/serve/site-ui/docs/pyric-rules-reference-api.md +8 -0
- package/dist/serve/site-ui/docs/pyric-sandbox-database-reference-api/index.html +26 -2
- package/dist/serve/site-ui/docs/pyric-sandbox-database-reference-api.md +24 -0
- package/dist/serve/site-ui/docs/pyric-sandbox-firestore-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-sandbox-reference-api/index.html +77 -9
- package/dist/serve/site-ui/docs/pyric-sandbox-reference-api.md +28 -13
- package/dist/serve/site-ui/docs/pyric-storage-reference-api/index.html +240 -63
- package/dist/serve/site-ui/docs/pyric-storage-reference-api.md +164 -5
- package/dist/serve/site-ui/docs/pyric-ui-agents-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-ui-auth-hooks-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-ui-auth-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-ui-events-hooks-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-ui-events-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-ui-firestore-hooks-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-ui-firestore-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-ui-primitives-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-ui-rtdb-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-ui-rules-hooks-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-ui-rules-reference-api/index.html +1 -10
- package/dist/serve/site-ui/docs/pyric-ui-rules-reference-api.md +0 -9
- package/dist/serve/site-ui/docs/pyric-ui-storage-hooks-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-ui-storage-reference-api/index.html +2 -1
- package/dist/serve/site-ui/docs/pyric-ui-storage-reference-api.md +1 -0
- package/dist/serve/site-ui/docs/pyric-ui-traffic-hooks-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/pyric-ui-traffic-reference-api/index.html +1 -1
- package/dist/serve/site-ui/docs/rules-compat/index.html +87 -79
- package/dist/serve/site-ui/docs/rules-compat.md +86 -78
- package/dist/serve/site-ui/docs/secure/audit-your-rules/index.html +1 -1
- package/dist/serve/site-ui/docs/secure/firestore-rules-limits/index.html +1 -1
- package/dist/serve/site-ui/docs/secure/read-a-denial/index.html +1 -1
- package/dist/serve/site-ui/docs/secure/rtdb-rules-in-typescript/index.html +1 -1
- package/dist/serve/site-ui/docs/secure/rules-standard-library/index.html +1 -1
- package/dist/serve/site-ui/docs/secure/secure-it-with-rules/index.html +1 -1
- package/dist/serve/site-ui/docs/secure/simulate-and-lint/index.html +1 -1
- package/dist/serve/site-ui/docs/secure/write-a-rules-test-suite/index.html +1 -1
- package/dist/serve/site-ui/docs/ship/ship-to-production/index.html +1 -1
- package/dist/serve/site-ui/docs/ship/test-in-node/index.html +1 -1
- package/dist/serve/site-ui/docs/storage-compat/index.html +119 -125
- package/dist/serve/site-ui/docs/storage-compat.md +118 -124
- package/dist/serve/site-ui/docs/trust/how-we-know-it-matches-firebase/index.html +1 -1
- package/dist/serve/site-ui/docs/trust/rules-standard-library/index.html +1 -1
- package/dist/serve/site-ui/docs/trust/storage-rules-stdlib-research/index.html +1 -1
- package/dist/serve/site-ui/docs/trust/versioning-and-compatibility/index.html +1 -1
- package/dist/serve/site-ui/docs/tutorial/index.html +2 -1
- package/dist/serve/site-ui/docs/tutorial.md +2 -0
- package/dist/serve/site-ui/examples/chess/index.html +1 -1
- package/dist/serve/site-ui/examples/firestore-first-write/index.html +1 -1
- package/dist/serve/site-ui/firestore/index.html +2 -2
- package/dist/serve/site-ui/index.html +2 -2
- package/dist/serve/site-ui/llms.txt +8 -4
- package/dist/serve/site-ui/rtdb/index.html +2 -2
- package/dist/serve/site-ui/settings/index.html +2 -2
- package/dist/serve/site-ui/storage/index.html +2 -2
- package/dist/serve/site-ui/traffic/index.html +2 -2
- package/dist/serve/vite-ai-config.d.ts +4 -1
- package/dist/serve/vite-ai-config.d.ts.map +1 -1
- package/dist/serve/vite-ai-config.js +83 -19
- package/dist/serve/vite-ai-config.js.map +1 -1
- package/dist/serve/vite-functions-development.d.ts.map +1 -1
- package/dist/serve/vite-functions-development.js +1 -0
- package/dist/serve/vite-functions-development.js.map +1 -1
- package/dist/serve/vite-generation-rules-watch.d.ts.map +1 -1
- package/dist/serve/vite-generation-rules-watch.js +61 -14
- package/dist/serve/vite-generation-rules-watch.js.map +1 -1
- package/dist/serve/vite-module-swap.d.ts +4 -1
- package/dist/serve/vite-module-swap.d.ts.map +1 -1
- package/dist/serve/vite-module-swap.js +106 -21
- package/dist/serve/vite-module-swap.js.map +1 -1
- package/dist/serve/vite-plugin.d.ts.map +1 -1
- package/dist/serve/vite-plugin.js +45 -5
- package/dist/serve/vite-plugin.js.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/resumable.d.ts +30 -0
- package/dist/serve/worker/client/resumable.d.ts.map +1 -0
- package/dist/serve/worker/client/resumable.js +416 -0
- package/dist/serve/worker/client/resumable.js.map +1 -0
- package/dist/serve/worker/client/rtdb-references.d.ts.map +1 -1
- package/dist/serve/worker/client/rtdb-references.js +4 -1
- package/dist/serve/worker/client/rtdb-references.js.map +1 -1
- package/dist/serve/worker/client/storage.d.ts +16 -2
- package/dist/serve/worker/client/storage.d.ts.map +1 -1
- package/dist/serve/worker/client/storage.js +57 -6
- package/dist/serve/worker/client/storage.js.map +1 -1
- package/dist/serve/worker/host/rules.d.ts.map +1 -1
- package/dist/serve/worker/host/rules.js +2 -1
- package/dist/serve/worker/host/rules.js.map +1 -1
- package/dist/serve/worker/index.d.ts +1 -1
- package/dist/serve/worker/index.d.ts.map +1 -1
- package/dist/serve/worker/index.js +1 -1
- package/dist/serve/worker/index.js.map +1 -1
- package/dist/serve/worker/serve-init.d.ts.map +1 -1
- package/dist/serve/worker/serve-init.js +31 -0
- package/dist/serve/worker/serve-init.js.map +1 -1
- package/package.json +15 -4
- package/src/assurance/.generated/conformance-verdicts.ts +80 -72
- package/src/bridge/server/bridge.ts +5 -2
- package/src/bridge/server/peer.ts +2 -1
- package/src/cli/cli.test.ts +14 -0
- package/src/cli/database-rules.ts +6 -4
- package/src/cli/dev-runner.ts +21 -0
- package/src/cli/serve.ts +63 -5
- package/src/cli/verify.ts +2 -2
- package/src/conformance/.generated/can-i-use-browser.ts +1 -1
- package/src/conformance/.generated/can-i-use.ts +1 -1
- package/src/conformance/.generated/conformance-docs.ts +1 -1
- package/src/functions-rtdb/child.ts +12 -1
- package/src/functions-rtdb/development-runtime.ts +2 -0
- package/src/next/client-aliases.ts +39 -0
- package/src/next/dev-rewrites.ts +77 -0
- package/src/next/guard.ts +61 -0
- package/src/next/index.ts +16 -0
- package/src/next/runtime-env.ts +18 -0
- package/src/next/server-external-packages.ts +43 -0
- package/src/next/target-url.ts +46 -0
- package/src/next/turbopack-config.ts +54 -0
- package/src/next/types.ts +47 -0
- package/src/next/webpack-config.ts +71 -0
- package/src/next/with-pyric.ts +58 -0
- package/src/register/app-bridge.ts +79 -0
- package/src/register/hooks.ts +6 -1
- package/src/register/index.ts +1 -1
- package/src/register/mapping.ts +50 -4
- package/src/remote/index.ts +7 -5
- package/src/rtdb/rules-json.ts +110 -0
- package/src/serve/bundler.ts +2 -0
- package/src/serve/discovery.ts +65 -44
- package/src/serve/entries/app-ai-passthrough.ts +83 -0
- package/src/serve/entries/auth-helper-core.ts +9 -7
- package/src/serve/entries/auth.ts +1 -0
- package/src/serve/entries/bridge-url.ts +9 -2
- package/src/serve/entries/database.ts +1 -0
- package/src/serve/entries/firestore.ts +1 -0
- package/src/serve/entries/init.ts +5 -2
- package/src/serve/entries/runtime.ts +25 -0
- package/src/serve/entries/storage.ts +12 -1
- package/src/serve/html-injection.ts +26 -1
- package/src/serve/rules.ts +2 -2
- package/src/serve/runtime/chip-config.ts +19 -6
- package/src/serve/runtime/chip.ts +24 -3
- package/src/serve/runtime/status.ts +76 -13
- package/src/serve/sandbox-session.ts +31 -2
- package/src/serve/vite-ai-config.ts +86 -19
- package/src/serve/vite-functions-development.ts +1 -0
- package/src/serve/vite-generation-rules-watch.ts +67 -15
- package/src/serve/vite-module-swap.ts +121 -21
- package/src/serve/vite-plugin.ts +44 -6
- package/src/serve/vite-sandbox-generation.ts +1 -1
- package/src/serve/worker/client/resumable.ts +506 -0
- package/src/serve/worker/client/rtdb-references.ts +4 -1
- package/src/serve/worker/client/storage.ts +77 -7
- package/src/serve/worker/host/rules.ts +2 -1
- package/src/serve/worker/index.ts +4 -0
- package/src/serve/worker/serve-init.ts +30 -0
- package/dist/serve/site-ui/_astro/_slug_.BoKXYrnu.css +0 -1
- package/dist/serve/site-ui/_astro/_studio_.BtYpqe1A.css +0 -1
- package/dist/serve/site-ui/_astro/app.4HeLP_FA.js +0 -109
- package/dist/serve/site-ui/_astro/app.BgSnCR5G.js +0 -1
- package/dist/serve/site-ui/_astro/index.BJiOemMX.js +0 -1
- package/dist/serve/site-ui/_astro/reads.BrKNdKAa.js +0 -1
- package/dist/serve/site-ui/_astro/sandbox-controls.BTb3EbQp.js +0 -1153
|
@@ -0,0 +1,1252 @@
|
|
|
1
|
+
var Eo=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function ju(t){if(Object.prototype.hasOwnProperty.call(t,"__esModule"))return t;var e=t.default;if(typeof e=="function"){var n=function r(){return this instanceof r?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};n.prototype=e.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(t).forEach(function(r){var s=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(n,r,s.get?s:{enumerable:!0,get:function(){return t[r]}})}),n}function je(t){const e=t||"";return function(){throw new Error("this method "+e+" is abstract! (it has no implementation in class "+this.constructor.name+")")}}function Lt(t,e){if(!t)throw new Error(e||"Assertion failed")}function Ss(t,e,n){let r;Object.defineProperty(t,e,{get(){return r||(r=n.call(this)),r}})}function ko(t,e){const n=[];for(;e-- >0;)n.push(t());return n}function Oo(t,e){return new Array(e+1).join(t)}function Vr(t,e){return ko(()=>t,e)}function _s(t){const e=[];for(let n=0;n<t.length;n++){const r=t[n];t.lastIndexOf(r)!==n&&e.indexOf(r)<0&&e.push(r)}return e}function Co(t){const e=[];return t.forEach(n=>{e.indexOf(n)<0&&e.push(n)}),e}function Ut(t){const e=t[0];return e===e.toUpperCase()}function To(t){return!Ut(t)}function Ro(t,e,n){return t.length<e?Oo(" ",e-t.length)+t:t}function Qt(){this.strings=[]}Qt.prototype.append=function(t){this.strings.push(t)};Qt.prototype.contents=function(){return this.strings.join("")};const ns=t=>String.fromCodePoint(parseInt(t,16));function No(t){if(t.charAt(0)==="\\")switch(t.charAt(1)){case"b":return"\b";case"f":return"\f";case"n":return`
|
|
2
|
+
`;case"r":return"\r";case"t":return" ";case"v":return"\v";case"x":return ns(t.slice(2,4));case"u":return t.charAt(2)==="{"?ns(t.slice(3,-1)):ns(t.slice(2,6));default:return t.charAt(1)}else return t}function di(t){if(t==null)return String(t);const e=Object.prototype.toString.call(t);try{let n;return t.constructor&&t.constructor.name?n=t.constructor.name:e.indexOf("[object ")===0?n=e.slice(8,-1):n=typeof t,n+": "+JSON.stringify(String(t))}catch{return e}}function Lo(t,e="unexpected null value"){if(t==null)throw new Error(e);return t}const Pu=Object.freeze(Object.defineProperty({__proto__:null,StringBuffer:Qt,abstract:je,assert:Lt,checkNotNull:Lo,copyWithoutDuplicates:Co,defineLazyProperty:Ss,getDuplicates:_s,isLexical:To,isSyntactic:Ut,padLeft:Ro,repeat:Vr,repeatFn:ko,repeatStr:Oo,unescapeCodePoint:No,unexpectedObjToString:di},Symbol.toStringTag,{value:"Module"})),Fo=t=>new RegExp(String.raw`\p{${t}}`,"u"),As=Object.fromEntries(["Cc","Cf","Cn","Co","Cs","Ll","Lm","Lo","Lt","Lu","Mc","Me","Mn","Nd","Nl","No","Pc","Pd","Pe","Pf","Pi","Po","Ps","Sc","Sk","Sm","So","Zl","Zp","Zs"].map(t=>[t,Fo(t)]));As.Ltmo=/\p{Lt}|\p{Lm}|\p{Lo}/u;const zi=Object.fromEntries(["XID_Start","XID_Continue","White_Space"].map(t=>[t,Fo(t)]));class V{constructor(){if(this.constructor===V)throw new Error("PExpr cannot be instantiated -- it's abstract")}withSource(e){return e&&(this.source=e.trimmed()),this}}const Te=Object.create(V.prototype),Re=Object.create(V.prototype);class ke extends V{constructor(e){super(),this.obj=e}}class Ne extends V{constructor(e,n){super(),this.from=e,this.to=n,this.matchCodePoint=e.length>1||n.length>1}}class Le extends V{constructor(e){super(),this.index=e}}class be extends V{constructor(e){super(),this.terms=e}}class Wr extends be{constructor(e,n,r){const s=e.rules[n].body;super([r,s]),this.superGrammar=e,this.name=n,this.body=r}}class Hr extends be{constructor(e,n,r,s){const i=e.rules[n].body;super([...r,i,...s]),this.superGrammar=e,this.ruleName=n,this.expansionPos=r.length}}class Ae extends V{constructor(e){super(),this.factors=e}}class Pe extends V{constructor(e){super(),this.expr=e}}class Yt extends Pe{}class vn extends Pe{}class wt extends Pe{}Yt.prototype.operator="*";vn.prototype.operator="+";wt.prototype.operator="?";Yt.prototype.minNumMatches=0;vn.prototype.minNumMatches=1;wt.prototype.minNumMatches=0;Yt.prototype.maxNumMatches=Number.POSITIVE_INFINITY;vn.prototype.maxNumMatches=Number.POSITIVE_INFINITY;wt.prototype.maxNumMatches=1;class Ie extends V{constructor(e){super(),this.expr=e}}class $e extends V{constructor(e){super(),this.expr=e}}class Be extends V{constructor(e){super(),this.expr=e}}class X extends V{constructor(e,n=[]){super(),this.ruleName=e,this.args=n}isSyntactic(){return Ut(this.ruleName)}toMemoKey(){return this._memoKey||Object.defineProperty(this,"_memoKey",{value:this.toString()}),this._memoKey}}class Ee extends V{constructor(e){if(super(),this.categoryOrProp=e,e in As)this.pattern=As[e];else if(e in zi)this.pattern=zi[e];else throw new Error(`Invalid Unicode category or property name: ${JSON.stringify(e)}`)}}function de(t,e){let n;return e?(n=new Error(e.getLineAndColumnMessage()+t),n.shortMessage=t,n.interval=e):n=new Error(t),n}function xs(){return de("Interval sources don't match")}function $u(t){const e=new Error;return Object.defineProperty(e,"message",{enumerable:!0,get(){return t.message}}),Object.defineProperty(e,"shortMessage",{enumerable:!0,get(){return"Expected "+t.getExpectedText()}}),e.interval=t.getInterval(),e}function qu(t,e,n){const r=e?`Grammar ${t} is not declared in namespace '${e}'`:"Undeclared grammar "+t;return de(r,n)}function Uu(t,e){return de("Grammar "+t.name+" is already declared in this namespace")}function Bu(t){return de(`Grammar '${t.name}' does not support incremental parsing`)}function Do(t,e,n){return de("Rule "+t+" is not declared in grammar "+e,n)}function zu(t,e,n){return de("Cannot override rule "+t+" because it is not declared in "+e,n)}function Vu(t,e,n){return de("Cannot extend rule "+t+" because it is not declared in "+e,n)}function Vi(t,e,n,r){let s="Duplicate declaration for rule '"+t+"' in grammar '"+e+"'";return e!==n&&(s+=" (originally declared in '"+n+"')"),de(s,r)}function Mo(t,e,n,r){return de("Wrong number of parameters for rule "+t+" (expected "+e+", got "+n+")",r)}function Wu(t,e,n,r){return de("Wrong number of arguments for rule "+t+" (expected "+e+", got "+n+")",r)}function Wi(t,e,n){return de("Duplicate parameter names in rule "+t+": "+e.join(", "),n)}function Hu(t,e){return de("Invalid parameter to rule "+t+": "+e+" has arity "+e.getArity()+", but parameter expressions must have arity 1",e.source)}const Gu="NOTE: A _syntactic rule_ is a rule whose name begins with a capital letter. See https://ohmjs.org/d/svl for more details.";function Ku(t,e){return de("Cannot apply syntactic rule "+t+" from here (inside a lexical context)",e.source)}function Zu(t){const{ruleName:e}=t;return de(`applySyntactic is for syntactic rules, but '${e}' is a lexical rule. `+Gu,t.source)}function Ju(t){return de("applySyntactic is not required here (in a syntactic context)",t.source)}function Hi(t,e){return de("Incorrect argument type: expected "+t,e.source)}function Qu(t){return de("'...' can appear at most once in a rule body",t.source)}function Yu(t){const e=t._node;Lt(e&&e.isNonterminal()&&e.ctorName==="escapeChar_unicodeCodePoint");const n=t.children.slice(1,-1).map(s=>s.source),r=n[0].coverageWith(...n.slice(1));return de(`U+${r.contents} is not a valid Unicode code point`,r)}function jo(t,e){const n=e.length>0?e[e.length-1].args:[];let s="Nullable expression "+t.expr.substituteParams(n)+" is not allowed inside '"+t.operator+"' (possible infinite loop)";if(e.length>0){const i=e.map(a=>new X(a.ruleName,a.args)).join(`
|
|
3
|
+
`);s+=`
|
|
4
|
+
Application stack (most recent application last):
|
|
5
|
+
`+i}return de(s,t.expr.source)}function Po(t,e,n,r){return de("Rule "+t+" involves an alternation which has inconsistent arity (expected "+e+", got "+n+")",r.source)}function Xu(t){const e=t.map(n=>n.message);return de(["Errors:"].concat(e).join(`
|
|
6
|
+
- `),t[0].interval)}function el(t,e,n,r){let s=r.slice(0,-1).map(c=>{const u=" "+c[0].name+" > "+c[1];return c.length===3?u+" for '"+c[2]+"'":u}).join(`
|
|
7
|
+
`);s+=`
|
|
8
|
+
`+e+" > "+t;let i="";t==="_iter"&&(i=[`
|
|
9
|
+
NOTE: as of Ohm v16, there is no default action for iteration nodes — see `," https://ohmjs.org/d/dsa for details."].join(`
|
|
10
|
+
`));const a=[`Missing semantic action for '${t}' in ${n} '${e}'.${i}`,"Action stack (most recent call last):",s].join(`
|
|
11
|
+
`),o=de(a);return o.name="missingSemanticAction",o}function tl(t){if(t.length===1)throw t[0];if(t.length>1)throw Xu(t)}function nl(t){let e=0;return t.map(r=>{const s=r.toString();return e=Math.max(e,s.length),s}).map(r=>Ro(r,e))}function Gi(t,e,n){const r=t.length,s=t.slice(0,n),i=t.slice(n+e.length);return(s+e+i).substr(0,r)}function rl(...t){const e=this,{offset:n}=e,{repeatStr:r}=Pu,s=new Qt;s.append("Line "+e.lineNum+", col "+e.colNum+`:
|
|
12
|
+
`);const i=nl([e.prevLine==null?0:e.lineNum-1,e.lineNum,e.nextLine==null?0:e.lineNum+1]),a=(d,l,p)=>{s.append(p+i[d]+" | "+l+`
|
|
13
|
+
`)};e.prevLine!=null&&a(0,e.prevLine," "),a(1,e.line,"> ");const o=e.line.length;let c=r(" ",o+1);for(let d=0;d<t.length;++d){let l=t[d][0],p=t[d][1];Lt(l>=0&&l<=p,"range start must be >= 0 and <= end");const y=n-e.colNum+1;l=Math.max(0,l-y),p=Math.min(p-y,o),c=Gi(c,r("~",p-l),l)}const u=2+i[1].length+3;return s.append(r(" ",u)),c=Gi(c,"^",e.colNum-1),s.append(c.replace(/ +$/,"")+`
|
|
14
|
+
`),e.nextLine!=null&&a(2,e.nextLine," "),s.contents()}let Is=[];function $o(t){Is.push(t)}function sl(t){Is.forEach(e=>{e(t)}),Is=null}function hi(t,e){let n=1,r=1,s=0,i=0,a=null,o=null,c=-1;for(;s<e;){const l=t.charAt(s++);l===`
|
|
15
|
+
`?(n++,r=1,c=i,i=s):l!=="\r"&&r++}let u=t.indexOf(`
|
|
16
|
+
`,i);if(u===-1)u=t.length;else{const l=t.indexOf(`
|
|
17
|
+
`,u+1);a=l===-1?t.slice(u):t.slice(u,l),a=a.replace(/^\r?\n/,"").replace(/\r$/,"")}c>=0&&(o=t.slice(c,i).replace(/\r?\n$/,""));const d=t.slice(i,u).replace(/\r$/,"");return{offset:e,lineNum:n,colNum:r,line:d,prevLine:o,nextLine:a,toString:rl}}function fi(t,e,...n){return hi(t,e).toString(...n)}const Ki=(()=>{let t=0;return e=>""+e+t++})();class Ce{constructor(e,n,r){Object.defineProperty(this,"_sourceString",{value:e,configurable:!1,enumerable:!1,writable:!1}),this.startIdx=n,this.endIdx=r}get sourceString(){return this._sourceString}get contents(){return this._contents===void 0&&(this._contents=this.sourceString.slice(this.startIdx,this.endIdx)),this._contents}get length(){return this.endIdx-this.startIdx}coverageWith(...e){return Ce.coverage(...e,this)}collapsedLeft(){return new Ce(this.sourceString,this.startIdx,this.startIdx)}collapsedRight(){return new Ce(this.sourceString,this.endIdx,this.endIdx)}getLineAndColumn(){return hi(this.sourceString,this.startIdx)}getLineAndColumnMessage(){const e=[this.startIdx,this.endIdx];return fi(this.sourceString,this.startIdx,e)}minus(e){if(this.sourceString!==e.sourceString)throw xs();return this.startIdx===e.startIdx&&this.endIdx===e.endIdx?[]:this.startIdx<e.startIdx&&e.endIdx<this.endIdx?[new Ce(this.sourceString,this.startIdx,e.startIdx),new Ce(this.sourceString,e.endIdx,this.endIdx)]:this.startIdx<e.endIdx&&e.endIdx<this.endIdx?[new Ce(this.sourceString,e.endIdx,this.endIdx)]:this.startIdx<e.startIdx&&e.startIdx<this.endIdx?[new Ce(this.sourceString,this.startIdx,e.startIdx)]:[this]}relativeTo(e){if(this.sourceString!==e.sourceString)throw xs();return Lt(this.startIdx>=e.startIdx&&this.endIdx<=e.endIdx,"other interval does not cover this one"),new Ce(this.sourceString,this.startIdx-e.startIdx,this.endIdx-e.startIdx)}trimmed(){const{contents:e}=this,n=this.startIdx+e.match(/^\s*/)[0].length,r=this.endIdx-e.match(/\s*$/)[0].length;return new Ce(this.sourceString,n,r)}subInterval(e,n){const r=this.startIdx+e;return new Ce(this.sourceString,r,r+n)}}Ce.coverage=function(t,...e){let{startIdx:n,endIdx:r}=t;for(const s of e){if(s.sourceString!==t.sourceString)throw xs();n=Math.min(n,s.startIdx),r=Math.max(r,s.endIdx)}return new Ce(t.sourceString,n,r)};const il=65535,al=1114111;class Gr{constructor(e){this.source=e,this.pos=0,this.examinedLength=0}atEnd(){const e=this.pos>=this.source.length;return this.examinedLength=Math.max(this.examinedLength,this.pos+1),e}next(){const e=this.source[this.pos++];return this.examinedLength=Math.max(this.examinedLength,this.pos),e}nextCharCode(){const e=this.next();return e&&e.charCodeAt(0)}nextCodePoint(){const e=this.source.slice(this.pos++).codePointAt(0);return e>il&&(this.pos+=1),this.examinedLength=Math.max(this.examinedLength,this.pos),e}matchString(e,n){let r;if(n){for(r=0;r<e.length;r++){const s=this.next(),i=e[r];if(s==null||s.toUpperCase()!==i.toUpperCase())return!1}return!0}for(r=0;r<e.length;r++)if(this.next()!==e[r])return!1;return!0}sourceSlice(e,n){return this.source.slice(e,n)}interval(e,n){return new Ce(this.source,e,n||this.pos)}}class qo{constructor(e,n,r,s,i,a,o){this.matcher=e,this.input=n,this.startExpr=r,this._cst=s,this._cstOffset=i,this._rightmostFailurePosition=a,this._rightmostFailures=o,this.failed()&&(Ss(this,"message",function(){const c="Expected "+this.getExpectedText();return fi(this.input,this.getRightmostFailurePosition())+c}),Ss(this,"shortMessage",function(){const c="expected "+this.getExpectedText(),u=hi(this.input,this.getRightmostFailurePosition());return"Line "+u.lineNum+", col "+u.colNum+": "+c}))}succeeded(){return!!this._cst}failed(){return!this.succeeded()}getRightmostFailurePosition(){return this._rightmostFailurePosition}getRightmostFailures(){if(!this._rightmostFailures){this.matcher.setInput(this.input);const e=this.matcher._match(this.startExpr,{tracing:!1,positionToRecordFailures:this.getRightmostFailurePosition()});this._rightmostFailures=e.getRightmostFailures()}return this._rightmostFailures}toString(){return this.succeeded()?"[match succeeded]":"[match failed at position "+this.getRightmostFailurePosition()+"]"}getExpectedText(){if(this.succeeded())throw new Error("cannot get expected text of a successful MatchResult");const e=new Qt;let n=this.getRightmostFailures();n=n.filter(r=>!r.isFluffy());for(let r=0;r<n.length;r++)r>0&&(r===n.length-1?e.append(n.length>2?", or ":" or "):e.append(", ")),e.append(n[r].toString());return e.contents()}getInterval(){const e=this.getRightmostFailurePosition();return new Ce(this.input,e,e)}}class ol{constructor(){this.applicationMemoKeyStack=[],this.memo={},this.maxExaminedLength=0,this.maxRightmostFailureOffset=-1,this.currentLeftRecursion=void 0}isActive(e){return this.applicationMemoKeyStack.indexOf(e.toMemoKey())>=0}enter(e){this.applicationMemoKeyStack.push(e.toMemoKey())}exit(){this.applicationMemoKeyStack.pop()}startLeftRecursion(e,n){n.isLeftRecursion=!0,n.headApplication=e,n.nextLeftRecursion=this.currentLeftRecursion,this.currentLeftRecursion=n;const{applicationMemoKeyStack:r}=this,s=r.indexOf(e.toMemoKey())+1,i=r.slice(s);n.isInvolved=function(a){return i.indexOf(a)>=0},n.updateInvolvedApplicationMemoKeys=function(){for(let a=s;a<r.length;a++){const o=r[a];this.isInvolved(o)||i.push(o)}}}endLeftRecursion(){this.currentLeftRecursion=this.currentLeftRecursion.nextLeftRecursion}shouldUseMemoizedResult(e){if(!e.isLeftRecursion)return!0;const{applicationMemoKeyStack:n}=this;for(let r=0;r<n.length;r++){const s=n[r];if(e.isInvolved(s))return!1}return!0}memoize(e,n){return this.memo[e]=n,this.maxExaminedLength=Math.max(this.maxExaminedLength,n.examinedLength),this.maxRightmostFailureOffset=Math.max(this.maxRightmostFailureOffset,n.rightmostFailureOffset),n}clearObsoleteEntries(e,n){if(e+this.maxExaminedLength<=n)return;const{memo:r}=this;this.maxExaminedLength=0,this.maxRightmostFailureOffset=-1,Object.keys(r).forEach(s=>{const i=r[s];e+i.examinedLength>n?delete r[s]:(this.maxExaminedLength=Math.max(this.maxExaminedLength,i.examinedLength),this.maxRightmostFailureOffset=Math.max(this.maxRightmostFailureOffset,i.rightmostFailureOffset))})}}const cl="✗",ul="✓",ll="⋅",dl="⇒",hl="␉",fl="␊",pl="␍",Es={succeeded:1,isRootNode:2,isImplicitSpaces:4,isMemoized:8,isHeadOfLeftRecursion:16,terminatesLR:32};function ml(t){return Vr(" ",t).join("")}function gl(t,e,n){const r=Uo(t.slice(e,e+n));return r.length<n?r+Vr(" ",n-r.length).join(""):r}function Uo(t){return typeof t=="string"?t.replace(/ /g,ll).replace(/\t/g,hl).replace(/\n/g,fl).replace(/\r/g,pl):String(t)}class It{constructor(e,n,r,s,i,a,o){this.input=e,this.pos=this.pos1=n,this.pos2=r,this.source=new Ce(e,n,r),this.expr=s,this.bindings=a,this.children=o||[],this.terminatingLREntry=null,this._flags=i?Es.succeeded:0}get displayString(){return this.expr.toDisplayString()}clone(){return this.cloneWithExpr(this.expr)}cloneWithExpr(e){const n=new It(this.input,this.pos,this.pos2,e,this.succeeded,this.bindings,this.children);return n.isHeadOfLeftRecursion=this.isHeadOfLeftRecursion,n.isImplicitSpaces=this.isImplicitSpaces,n.isMemoized=this.isMemoized,n.isRootNode=this.isRootNode,n.terminatesLR=this.terminatesLR,n.terminatingLREntry=this.terminatingLREntry,n}recordLRTermination(e,n){this.terminatingLREntry=new It(this.input,this.pos,this.pos2,this.expr,!1,[n],[e]),this.terminatingLREntry.terminatesLR=!0}walk(e,n){let r=e;typeof r=="function"&&(r={enter:r});function s(i,a,o){let c=!0;r.enter&&r.enter.call(n,i,a,o)===It.prototype.SKIP&&(c=!1),c&&(i.children.forEach(u=>{s(u,i,o+1)}),r.exit&&r.exit.call(n,i,a,o))}this.isRootNode?this.children.forEach(i=>{s(i,null,0)}):s(this,null,0)}toString(){const e=new Qt;return this.walk((n,r,s)=>{if(!n)return this.SKIP;if(n.expr.constructor.name!=="Alt"){if(e.append(gl(n.input,n.pos,10)+ml(s*2+1)),e.append((n.succeeded?ul:cl)+" "+n.displayString),n.isHeadOfLeftRecursion&&e.append(" (LR)"),n.succeeded){const a=Uo(n.source.contents);e.append(" "+dl+" "),e.append(typeof a=="string"?'"'+a+'"':a)}e.append(`
|
|
18
|
+
`)}}),e.contents()}}It.prototype.SKIP={};Object.keys(Es).forEach(t=>{const e=Es[t];Object.defineProperty(It.prototype,t,{get(){return(this._flags&e)!==0},set(n){n?this._flags|=e:this._flags&=~e}})});V.prototype.allowsSkippingPrecedingSpace=je("allowsSkippingPrecedingSpace");Te.allowsSkippingPrecedingSpace=Re.allowsSkippingPrecedingSpace=X.prototype.allowsSkippingPrecedingSpace=ke.prototype.allowsSkippingPrecedingSpace=Ne.prototype.allowsSkippingPrecedingSpace=Ee.prototype.allowsSkippingPrecedingSpace=function(){return!0};be.prototype.allowsSkippingPrecedingSpace=Pe.prototype.allowsSkippingPrecedingSpace=Be.prototype.allowsSkippingPrecedingSpace=$e.prototype.allowsSkippingPrecedingSpace=Ie.prototype.allowsSkippingPrecedingSpace=Le.prototype.allowsSkippingPrecedingSpace=Ae.prototype.allowsSkippingPrecedingSpace=function(){return!1};let In;$o(t=>{In=t});let lr;V.prototype.assertAllApplicationsAreValid=function(t,e){lr=0,this._assertAllApplicationsAreValid(t,e)};V.prototype._assertAllApplicationsAreValid=je("_assertAllApplicationsAreValid");Te._assertAllApplicationsAreValid=Re._assertAllApplicationsAreValid=ke.prototype._assertAllApplicationsAreValid=Ne.prototype._assertAllApplicationsAreValid=Le.prototype._assertAllApplicationsAreValid=Ee.prototype._assertAllApplicationsAreValid=function(t,e){};Be.prototype._assertAllApplicationsAreValid=function(t,e){lr++,this.expr._assertAllApplicationsAreValid(t,e),lr--};be.prototype._assertAllApplicationsAreValid=function(t,e){for(let n=0;n<this.terms.length;n++)this.terms[n]._assertAllApplicationsAreValid(t,e)};Ae.prototype._assertAllApplicationsAreValid=function(t,e){for(let n=0;n<this.factors.length;n++)this.factors[n]._assertAllApplicationsAreValid(t,e)};Pe.prototype._assertAllApplicationsAreValid=Ie.prototype._assertAllApplicationsAreValid=$e.prototype._assertAllApplicationsAreValid=function(t,e){this.expr._assertAllApplicationsAreValid(t,e)};X.prototype._assertAllApplicationsAreValid=function(t,e,n=!1){const r=e.rules[this.ruleName],s=Ut(t)&&lr===0;if(!r)throw Do(this.ruleName,e.name,this.source);if(!n&&Ut(this.ruleName)&&!s)throw Ku(this.ruleName,this);const i=this.args.length,a=r.formals.length;if(i!==a)throw Wu(this.ruleName,a,i,this.source);const o=In&&r===In.rules.applySyntactic;if(In&&r===In.rules.caseInsensitive&&!(this.args[0]instanceof ke))throw Hi('a Terminal (e.g. "abc")',this.args[0]);if(o){const u=this.args[0];if(!(u instanceof X))throw Hi("a syntactic rule application",u);if(!Ut(u.ruleName))throw Zu(u);if(s)throw Ju(this)}this.args.forEach(u=>{if(u._assertAllApplicationsAreValid(t,e,o),u.getArity()!==1)throw Hu(this.ruleName,u)})};V.prototype.assertChoicesHaveUniformArity=je("assertChoicesHaveUniformArity");Te.assertChoicesHaveUniformArity=Re.assertChoicesHaveUniformArity=ke.prototype.assertChoicesHaveUniformArity=Ne.prototype.assertChoicesHaveUniformArity=Le.prototype.assertChoicesHaveUniformArity=Be.prototype.assertChoicesHaveUniformArity=Ee.prototype.assertChoicesHaveUniformArity=function(t){};be.prototype.assertChoicesHaveUniformArity=function(t){if(this.terms.length===0)return;const e=this.terms[0].getArity();for(let n=0;n<this.terms.length;n++){const r=this.terms[n];r.assertChoicesHaveUniformArity();const s=r.getArity();if(e!==s)throw Po(t,e,s,r)}};Wr.prototype.assertChoicesHaveUniformArity=function(t){const e=this.terms[0].getArity(),n=this.terms[1].getArity();if(e!==n)throw Po(t,n,e,this.terms[0])};Ae.prototype.assertChoicesHaveUniformArity=function(t){for(let e=0;e<this.factors.length;e++)this.factors[e].assertChoicesHaveUniformArity(t)};Pe.prototype.assertChoicesHaveUniformArity=function(t){this.expr.assertChoicesHaveUniformArity(t)};Ie.prototype.assertChoicesHaveUniformArity=function(t){};$e.prototype.assertChoicesHaveUniformArity=function(t){this.expr.assertChoicesHaveUniformArity(t)};X.prototype.assertChoicesHaveUniformArity=function(t){};V.prototype.assertIteratedExprsAreNotNullable=je("assertIteratedExprsAreNotNullable");Te.assertIteratedExprsAreNotNullable=Re.assertIteratedExprsAreNotNullable=ke.prototype.assertIteratedExprsAreNotNullable=Ne.prototype.assertIteratedExprsAreNotNullable=Le.prototype.assertIteratedExprsAreNotNullable=Ee.prototype.assertIteratedExprsAreNotNullable=function(t){};be.prototype.assertIteratedExprsAreNotNullable=function(t){for(let e=0;e<this.terms.length;e++)this.terms[e].assertIteratedExprsAreNotNullable(t)};Ae.prototype.assertIteratedExprsAreNotNullable=function(t){for(let e=0;e<this.factors.length;e++)this.factors[e].assertIteratedExprsAreNotNullable(t)};Pe.prototype.assertIteratedExprsAreNotNullable=function(t){if(this.expr.assertIteratedExprsAreNotNullable(t),this.expr.isNullable(t))throw jo(this,[])};wt.prototype.assertIteratedExprsAreNotNullable=Ie.prototype.assertIteratedExprsAreNotNullable=$e.prototype.assertIteratedExprsAreNotNullable=Be.prototype.assertIteratedExprsAreNotNullable=function(t){this.expr.assertIteratedExprsAreNotNullable(t)};X.prototype.assertIteratedExprsAreNotNullable=function(t){this.args.forEach(e=>{e.assertIteratedExprsAreNotNullable(t)})};class pi{constructor(e){this.matchLength=e}get ctorName(){throw new Error("subclass responsibility")}numChildren(){return this.children?this.children.length:0}childAt(e){if(this.children)return this.children[e]}indexOfChild(e){return this.children.indexOf(e)}hasChildren(){return this.numChildren()>0}hasNoChildren(){return!this.hasChildren()}onlyChild(){if(this.numChildren()!==1)throw new Error("cannot get only child of a node of type "+this.ctorName+" (it has "+this.numChildren()+" children)");return this.firstChild()}firstChild(){if(this.hasNoChildren())throw new Error("cannot get first child of a "+this.ctorName+" node, which has no children");return this.childAt(0)}lastChild(){if(this.hasNoChildren())throw new Error("cannot get last child of a "+this.ctorName+" node, which has no children");return this.childAt(this.numChildren()-1)}childBefore(e){const n=this.indexOfChild(e);if(n<0)throw new Error("Node.childBefore() called w/ an argument that is not a child");if(n===0)throw new Error("cannot get child before first child");return this.childAt(n-1)}childAfter(e){const n=this.indexOfChild(e);if(n<0)throw new Error("Node.childAfter() called w/ an argument that is not a child");if(n===this.numChildren()-1)throw new Error("cannot get child after last child");return this.childAt(n+1)}isTerminal(){return!1}isNonterminal(){return!1}isIteration(){return!1}isOptional(){return!1}}class Xt extends pi{get ctorName(){return"_terminal"}isTerminal(){return!0}get primitiveValue(){throw new Error("The `primitiveValue` property was removed in Ohm v17.")}}class yl extends pi{constructor(e,n,r,s){super(s),this.ruleName=e,this.children=n,this.childOffsets=r}get ctorName(){return this.ruleName}isNonterminal(){return!0}isLexical(){return To(this.ctorName)}isSyntactic(){return Ut(this.ctorName)}}class Bo extends pi{constructor(e,n,r,s){super(r),this.children=e,this.childOffsets=n,this.optional=s}get ctorName(){return"_iter"}isIteration(){return!0}isOptional(){return this.optional}}V.prototype.eval=je("eval");Te.eval=function(t){const{inputStream:e}=t,n=e.pos,r=e.nextCodePoint();return r!==void 0?(t.pushBinding(new Xt(String.fromCodePoint(r).length),n),!0):(t.processFailure(n,this),!1)};Re.eval=function(t){const{inputStream:e}=t,n=e.pos;return e.atEnd()?(t.pushBinding(new Xt(0),n),!0):(t.processFailure(n,this),!1)};ke.prototype.eval=function(t){const{inputStream:e}=t,n=e.pos;return e.matchString(this.obj)?(t.pushBinding(new Xt(this.obj.length),n),!0):(t.processFailure(n,this),!1)};Ne.prototype.eval=function(t){const{inputStream:e}=t,n=e.pos,r=this.matchCodePoint?e.nextCodePoint():e.nextCharCode();return r!==void 0&&this.from.codePointAt(0)<=r&&r<=this.to.codePointAt(0)?(t.pushBinding(new Xt(String.fromCodePoint(r).length),n),!0):(t.processFailure(n,this),!1)};Le.prototype.eval=function(t){return t.eval(t.currentApplication().args[this.index])};Be.prototype.eval=function(t){t.enterLexifiedContext();const e=t.eval(this.expr);return t.exitLexifiedContext(),e};be.prototype.eval=function(t){for(let e=0;e<this.terms.length;e++)if(t.eval(this.terms[e]))return!0;return!1};Ae.prototype.eval=function(t){for(let e=0;e<this.factors.length;e++){const n=this.factors[e];if(!t.eval(n))return!1}return!0};Pe.prototype.eval=function(t){const{inputStream:e}=t,n=e.pos,r=this.getArity(),s=[],i=[];for(;s.length<r;)s.push([]),i.push([]);let a=0,o=n,c;for(;a<this.maxNumMatches&&t.eval(this.expr);){if(e.pos===o)throw jo(this,t._applicationStack);o=e.pos,a++;const p=t._bindings.splice(t._bindings.length-r,r),y=t._bindingOffsets.splice(t._bindingOffsets.length-r,r);for(c=0;c<p.length;c++)s[c].push(p[c]),i[c].push(y[c])}if(a<this.minNumMatches)return!1;let u=t.posToOffset(n),d=0;if(a>0){const p=s[r-1],y=i[r-1],b=y[y.length-1]+p[p.length-1].matchLength;u=i[0][0],d=b-u}const l=this instanceof wt;for(c=0;c<s.length;c++)t._bindings.push(new Bo(s[c],i[c],d,l)),t._bindingOffsets.push(u);return!0};Ie.prototype.eval=function(t){const{inputStream:e}=t,n=e.pos;t.pushFailuresInfo();const r=t.eval(this.expr);return t.popFailuresInfo(),r?(t.processFailure(n,this),!1):(e.pos=n,!0)};$e.prototype.eval=function(t){const{inputStream:e}=t,n=e.pos;return t.eval(this.expr)?(e.pos=n,!0):!1};X.prototype.eval=function(t){const e=t.currentApplication(),n=e?e.args:[],r=this.substituteParams(n),s=t.getCurrentPosInfo();if(s.isActive(r))return r.handleCycle(t);const i=r.toMemoKey(),a=s.memo[i];if(a&&s.shouldUseMemoizedResult(a)){if(t.hasNecessaryInfo(a))return t.useMemoizedResult(t.inputStream.pos,a);delete s.memo[i]}return r.reallyEval(t)};X.prototype.handleCycle=function(t){const e=t.getCurrentPosInfo(),{currentLeftRecursion:n}=e,r=this.toMemoKey();let s=e.memo[r];return n&&n.headApplication.toMemoKey()===r?s.updateInvolvedApplicationMemoKeys():s||(s=e.memoize(r,{matchLength:0,examinedLength:0,value:!1,rightmostFailureOffset:-1}),e.startLeftRecursion(this,s)),t.useMemoizedResult(t.inputStream.pos,s)};X.prototype.reallyEval=function(t){const{inputStream:e}=t,n=e.pos,r=t.getCurrentPosInfo(),s=t.grammar.rules[this.ruleName],{body:i}=s,{description:a}=s;t.enterApplication(r,this),a&&t.pushFailuresInfo();const o=e.examinedLength;e.examinedLength=0;let c=this.evalOnce(i,t);const u=r.currentLeftRecursion,d=this.toMemoKey(),l=u&&u.headApplication.toMemoKey()===d;let p;t.doNotMemoize?t.doNotMemoize=!1:l?(c=this.growSeedResult(i,t,n,u,c),r.endLeftRecursion(),p=u,p.examinedLength=e.examinedLength-n,p.rightmostFailureOffset=t._getRightmostFailureOffset(),r.memoize(d,p)):(!u||!u.isInvolved(d))&&(p=r.memoize(d,{matchLength:e.pos-n,examinedLength:e.examinedLength-n,value:c,failuresAtRightmostPosition:t.cloneRecordedFailures(),rightmostFailureOffset:t._getRightmostFailureOffset()}));const y=!!c;if(a&&(t.popFailuresInfo(),y||t.processFailure(n,this),p&&(p.failuresAtRightmostPosition=t.cloneRecordedFailures(),p.rightmostFailureOffset=t._getRightmostFailureOffset())),t.isTracing()&&p){const b=t.getTraceEntry(n,this,y,y?[c]:[]);l&&(Lt(b.terminatingLREntry!=null||!y),b.isHeadOfLeftRecursion=!0),p.traceEntry=b}return e.examinedLength=Math.max(e.examinedLength,o),t.exitApplication(r,c),y};X.prototype.evalOnce=function(t,e){const{inputStream:n}=e,r=n.pos;if(e.eval(t)){const s=t.getArity(),i=e._bindings.splice(e._bindings.length-s,s),a=e._bindingOffsets.splice(e._bindingOffsets.length-s,s),o=n.pos-r;return new yl(this.ruleName,i,a,o)}else return!1};X.prototype.growSeedResult=function(t,e,n,r,s){if(!s)return!1;const{inputStream:i}=e;for(;;){if(r.matchLength=i.pos-n,r.value=s,r.failuresAtRightmostPosition=e.cloneRecordedFailures(),e.isTracing()){const a=e.trace[e.trace.length-1];r.traceEntry=new It(e.input,n,i.pos,this,!0,[s],[a.clone()])}if(i.pos=n,s=this.evalOnce(t,e),i.pos-n<=r.matchLength)break;e.isTracing()&&e.trace.splice(-2,1)}return e.isTracing()&&r.traceEntry.recordLRTermination(e.trace.pop(),s),i.pos=n+r.matchLength,r.value};Ee.prototype.eval=function(t){const{inputStream:e}=t,n=e.pos,r=e.nextCodePoint();if(r!==void 0&&r<=al){const s=String.fromCodePoint(r);if(this.pattern.test(s))return t.pushBinding(new Xt(s.length),n),!0}return t.processFailure(n,this),!1};V.prototype.getArity=je("getArity");Te.getArity=Re.getArity=ke.prototype.getArity=Ne.prototype.getArity=Le.prototype.getArity=X.prototype.getArity=Ee.prototype.getArity=function(){return 1};be.prototype.getArity=function(){return this.terms.length===0?0:this.terms[0].getArity()};Ae.prototype.getArity=function(){let t=0;for(let e=0;e<this.factors.length;e++)t+=this.factors[e].getArity();return t};Pe.prototype.getArity=function(){return this.expr.getArity()};Ie.prototype.getArity=function(){return 0};$e.prototype.getArity=Be.prototype.getArity=function(){return this.expr.getArity()};function tt(t,e){const n={};if(t.source&&e){const r=t.source.relativeTo(e);n.sourceInterval=[r.startIdx,r.endIdx]}return n}V.prototype.outputRecipe=je("outputRecipe");Te.outputRecipe=function(t,e){return["any",tt(this,e)]};Re.outputRecipe=function(t,e){return["end",tt(this,e)]};ke.prototype.outputRecipe=function(t,e){return["terminal",tt(this,e),this.obj]};Ne.prototype.outputRecipe=function(t,e){return["range",tt(this,e),this.from,this.to]};Le.prototype.outputRecipe=function(t,e){return["param",tt(this,e),this.index]};be.prototype.outputRecipe=function(t,e){return["alt",tt(this,e)].concat(this.terms.map(n=>n.outputRecipe(t,e)))};Wr.prototype.outputRecipe=function(t,e){return this.terms[0].outputRecipe(t,e)};Hr.prototype.outputRecipe=function(t,e){const n=this.terms.slice(0,this.expansionPos),r=this.terms.slice(this.expansionPos+1);return["splice",tt(this,e),n.map(s=>s.outputRecipe(t,e)),r.map(s=>s.outputRecipe(t,e))]};Ae.prototype.outputRecipe=function(t,e){return["seq",tt(this,e)].concat(this.factors.map(n=>n.outputRecipe(t,e)))};Yt.prototype.outputRecipe=vn.prototype.outputRecipe=wt.prototype.outputRecipe=Ie.prototype.outputRecipe=$e.prototype.outputRecipe=Be.prototype.outputRecipe=function(t,e){return[this.constructor.name.toLowerCase(),tt(this,e),this.expr.outputRecipe(t,e)]};X.prototype.outputRecipe=function(t,e){return["app",tt(this,e),this.ruleName,this.args.map(n=>n.outputRecipe(t,e))]};Ee.prototype.outputRecipe=function(t,e){return["unicodeChar",tt(this,e),this.categoryOrProp]};V.prototype.introduceParams=je("introduceParams");Te.introduceParams=Re.introduceParams=ke.prototype.introduceParams=Ne.prototype.introduceParams=Le.prototype.introduceParams=Ee.prototype.introduceParams=function(t){return this};be.prototype.introduceParams=function(t){return this.terms.forEach((e,n,r)=>{r[n]=e.introduceParams(t)}),this};Ae.prototype.introduceParams=function(t){return this.factors.forEach((e,n,r)=>{r[n]=e.introduceParams(t)}),this};Pe.prototype.introduceParams=Ie.prototype.introduceParams=$e.prototype.introduceParams=Be.prototype.introduceParams=function(t){return this.expr=this.expr.introduceParams(t),this};X.prototype.introduceParams=function(t){const e=t.indexOf(this.ruleName);if(e>=0){if(this.args.length>0)throw new Error("Parameterized rules cannot be passed as arguments to another rule.");return new Le(e).withSource(this.source)}else return this.args.forEach((n,r,s)=>{s[r]=n.introduceParams(t)}),this};V.prototype.isNullable=function(t){return this._isNullable(t,Object.create(null))};V.prototype._isNullable=je("_isNullable");Te._isNullable=Ne.prototype._isNullable=Le.prototype._isNullable=vn.prototype._isNullable=Ee.prototype._isNullable=function(t,e){return!1};Re._isNullable=function(t,e){return!0};ke.prototype._isNullable=function(t,e){return typeof this.obj=="string"?this.obj==="":!1};be.prototype._isNullable=function(t,e){return this.terms.length===0||this.terms.some(n=>n._isNullable(t,e))};Ae.prototype._isNullable=function(t,e){return this.factors.every(n=>n._isNullable(t,e))};Yt.prototype._isNullable=wt.prototype._isNullable=Ie.prototype._isNullable=$e.prototype._isNullable=function(t,e){return!0};Be.prototype._isNullable=function(t,e){return this.expr._isNullable(t,e)};X.prototype._isNullable=function(t,e){const n=this.toMemoKey();if(!Object.prototype.hasOwnProperty.call(e,n)){const{body:r}=t.rules[this.ruleName],s=r.substituteParams(this.args);e[n]=!1,e[n]=s._isNullable(t,e)}return e[n]};V.prototype.substituteParams=je("substituteParams");Te.substituteParams=Re.substituteParams=ke.prototype.substituteParams=Ne.prototype.substituteParams=Ee.prototype.substituteParams=function(t){return this};Le.prototype.substituteParams=function(t){return Lo(t[this.index])};be.prototype.substituteParams=function(t){return new be(this.terms.map(e=>e.substituteParams(t)))};Ae.prototype.substituteParams=function(t){return new Ae(this.factors.map(e=>e.substituteParams(t)))};Pe.prototype.substituteParams=Ie.prototype.substituteParams=$e.prototype.substituteParams=Be.prototype.substituteParams=function(t){return new this.constructor(this.expr.substituteParams(t))};X.prototype.substituteParams=function(t){if(this.args.length===0)return this;{const e=this.args.map(n=>n.substituteParams(t));return new X(this.ruleName,e)}};function Zi(t){return/^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(t)}function mi(t){const e=Object.create(null);t.forEach(n=>{e[n]=(e[n]||0)+1}),Object.keys(e).forEach(n=>{if(e[n]<=1)return;let r=1;t.forEach((s,i)=>{s===n&&(t[i]=s+"_"+r++)})})}V.prototype.toArgumentNameList=je("toArgumentNameList");Te.toArgumentNameList=function(t,e){return["any"]};Re.toArgumentNameList=function(t,e){return["end"]};ke.prototype.toArgumentNameList=function(t,e){return typeof this.obj=="string"&&/^[_a-zA-Z0-9]+$/.test(this.obj)?["_"+this.obj]:["$"+t]};Ne.prototype.toArgumentNameList=function(t,e){let n=this.from+"_to_"+this.to;return Zi(n)||(n="_"+n),Zi(n)||(n="$"+t),[n]};be.prototype.toArgumentNameList=function(t,e){const n=this.terms.map(i=>i.toArgumentNameList(t,!0)),r=[],s=n[0].length;for(let i=0;i<s;i++){const a=[];for(let c=0;c<this.terms.length;c++)a.push(n[c][i]);const o=Co(a);r.push(o.join("_or_"))}return e||mi(r),r};Ae.prototype.toArgumentNameList=function(t,e){let n=[];return this.factors.forEach(r=>{const s=r.toArgumentNameList(t,!0);n=n.concat(s),t+=s.length}),e||mi(n),n};Pe.prototype.toArgumentNameList=function(t,e){const n=this.expr.toArgumentNameList(t,e).map(r=>r[r.length-1]==="s"?r+"es":r+"s");return e||mi(n),n};wt.prototype.toArgumentNameList=function(t,e){return this.expr.toArgumentNameList(t,e).map(n=>"opt"+n[0].toUpperCase()+n.slice(1))};Ie.prototype.toArgumentNameList=function(t,e){return[]};$e.prototype.toArgumentNameList=Be.prototype.toArgumentNameList=function(t,e){return this.expr.toArgumentNameList(t,e)};X.prototype.toArgumentNameList=function(t,e){return[this.ruleName]};Ee.prototype.toArgumentNameList=function(t,e){return["$"+t]};Le.prototype.toArgumentNameList=function(t,e){return["param"+this.index]};V.prototype.toDisplayString=je("toDisplayString");be.prototype.toDisplayString=Ae.prototype.toDisplayString=function(){return this.source?this.source.trimmed().contents:"["+this.constructor.name+"]"};Te.toDisplayString=Re.toDisplayString=Pe.prototype.toDisplayString=Ie.prototype.toDisplayString=$e.prototype.toDisplayString=Be.prototype.toDisplayString=ke.prototype.toDisplayString=Ne.prototype.toDisplayString=Le.prototype.toDisplayString=function(){return this.toString()};X.prototype.toDisplayString=function(){if(this.args.length>0){const t=this.args.map(e=>e.toDisplayString());return this.ruleName+"<"+t.join(",")+">"}else return this.ruleName};Ee.prototype.toDisplayString=function(){return"Unicode ["+this.categoryOrProp+"] character"};function bl(t){return t==="description"||t==="string"||t==="code"}class ze{constructor(e,n,r){if(!bl(r))throw new Error("invalid Failure type: "+r);this.pexpr=e,this.text=n,this.type=r,this.fluffy=!1}getPExpr(){return this.pexpr}getText(){return this.text}getType(){return this.type}isDescription(){return this.type==="description"}isStringTerminal(){return this.type==="string"}isCode(){return this.type==="code"}isFluffy(){return this.fluffy}makeFluffy(){this.fluffy=!0}clearFluffy(){this.fluffy=!1}subsumes(e){return this.getText()===e.getText()&&this.type===e.type&&(!this.isFluffy()||this.isFluffy()&&e.isFluffy())}toString(){return this.type==="string"?JSON.stringify(this.getText()):this.getText()}clone(){const e=new ze(this.pexpr,this.text,this.type);return this.isFluffy()&&e.makeFluffy(),e}toKey(){return this.toString()+"#"+this.type}}V.prototype.toFailure=je("toFailure");Te.toFailure=function(t){return new ze(this,"any object","description")};Re.toFailure=function(t){return new ze(this,"end of input","description")};ke.prototype.toFailure=function(t){return new ze(this,this.obj,"string")};Ne.prototype.toFailure=function(t){return new ze(this,JSON.stringify(this.from)+".."+JSON.stringify(this.to),"code")};Ie.prototype.toFailure=function(t){const e=this.expr===Te?"nothing":"not "+this.expr.toFailure(t);return new ze(this,e,"description")};$e.prototype.toFailure=function(t){return this.expr.toFailure(t)};X.prototype.toFailure=function(t){let{description:e}=t.rules[this.ruleName];return e||(e=(/^[aeiouAEIOU]/.test(this.ruleName)?"an":"a")+" "+this.ruleName),new ze(this,e,"description")};Ee.prototype.toFailure=function(t){return new ze(this,"a Unicode ["+this.categoryOrProp+"] character","description")};be.prototype.toFailure=function(t){const n="("+this.terms.map(r=>r.toFailure(t)).join(" or ")+")";return new ze(this,n,"description")};Ae.prototype.toFailure=function(t){const n="("+this.factors.map(r=>r.toFailure(t)).join(" ")+")";return new ze(this,n,"description")};Pe.prototype.toFailure=function(t){const e="("+this.expr.toFailure(t)+this.operator+")";return new ze(this,e,"description")};V.prototype.toString=je("toString");Te.toString=function(){return"any"};Re.toString=function(){return"end"};ke.prototype.toString=function(){return JSON.stringify(this.obj)};Ne.prototype.toString=function(){return JSON.stringify(this.from)+".."+JSON.stringify(this.to)};Le.prototype.toString=function(){return"$"+this.index};Be.prototype.toString=function(){return"#("+this.expr.toString()+")"};be.prototype.toString=function(){return this.terms.length===1?this.terms[0].toString():"("+this.terms.map(t=>t.toString()).join(" | ")+")"};Ae.prototype.toString=function(){return this.factors.length===1?this.factors[0].toString():"("+this.factors.map(t=>t.toString()).join(" ")+")"};Pe.prototype.toString=function(){return this.expr+this.operator};Ie.prototype.toString=function(){return"~"+this.expr};$e.prototype.toString=function(){return"&"+this.expr};X.prototype.toString=function(){if(this.args.length>0){const t=this.args.map(e=>e.toString());return this.ruleName+"<"+t.join(",")+">"}else return this.ruleName};Ee.prototype.toString=function(){return"\\p{"+this.categoryOrProp+"}"};class gi extends V{constructor(e){super(),this.obj=e}_getString(e){const n=e.currentApplication().args[this.obj.index];return Lt(n instanceof ke,"expected a Terminal expression"),n.obj}allowsSkippingPrecedingSpace(){return!0}eval(e){const{inputStream:n}=e,r=n.pos,s=this._getString(e);return n.matchString(s,!0)?(e.pushBinding(new Xt(s.length),r),!0):(e.processFailure(r,this),!1)}getArity(){return 1}substituteParams(e){return new gi(this.obj.substituteParams(e))}toDisplayString(){return this.obj.toDisplayString()+" (case-insensitive)"}toFailure(e){return new ze(this,this.obj.toFailure(e)+" (case-insensitive)","description")}_isNullable(e,n){return this.obj._isNullable(e,n)}}let zo;$o(t=>{zo=t.rules.applySyntactic.body});const rs=new X("spaces");class vl{constructor(e,n,r){this.matcher=e,this.startExpr=n,this.grammar=e.grammar,this.input=e.getInput(),this.inputStream=new Gr(this.input),this.memoTable=e._memoTable,this.userData=void 0,this.doNotMemoize=!1,this._bindings=[],this._bindingOffsets=[],this._applicationStack=[],this._posStack=[0],this.inLexifiedContextStack=[!1],this.rightmostFailurePosition=-1,this._rightmostFailurePositionStack=[],this._recordedFailuresStack=[],r!==void 0&&(this.positionToRecordFailures=r,this.recordedFailures=Object.create(null))}posToOffset(e){return e-this._posStack[this._posStack.length-1]}enterApplication(e,n){this._posStack.push(this.inputStream.pos),this._applicationStack.push(n),this.inLexifiedContextStack.push(!1),e.enter(n),this._rightmostFailurePositionStack.push(this.rightmostFailurePosition),this.rightmostFailurePosition=-1}exitApplication(e,n){const r=this._posStack.pop();this._applicationStack.pop(),this.inLexifiedContextStack.pop(),e.exit(),this.rightmostFailurePosition=Math.max(this.rightmostFailurePosition,this._rightmostFailurePositionStack.pop()),n&&this.pushBinding(n,r)}enterLexifiedContext(){this.inLexifiedContextStack.push(!0)}exitLexifiedContext(){this.inLexifiedContextStack.pop()}currentApplication(){return this._applicationStack[this._applicationStack.length-1]}inSyntacticContext(){const e=this.currentApplication();return e?e.isSyntactic()&&!this.inLexifiedContext():this.startExpr.factors[0].isSyntactic()}inLexifiedContext(){return this.inLexifiedContextStack[this.inLexifiedContextStack.length-1]}skipSpaces(){return this.pushFailuresInfo(),this.eval(rs),this.popBinding(),this.popFailuresInfo(),this.inputStream.pos}skipSpacesIfInSyntacticContext(){return this.inSyntacticContext()?this.skipSpaces():this.inputStream.pos}maybeSkipSpacesBefore(e){return e.allowsSkippingPrecedingSpace()&&e!==rs?this.skipSpacesIfInSyntacticContext():this.inputStream.pos}pushBinding(e,n){this._bindings.push(e),this._bindingOffsets.push(this.posToOffset(n))}popBinding(){this._bindings.pop(),this._bindingOffsets.pop()}numBindings(){return this._bindings.length}truncateBindings(e){for(;this._bindings.length>e;)this.popBinding()}getCurrentPosInfo(){return this.getPosInfo(this.inputStream.pos)}getPosInfo(e){let n=this.memoTable[e];return n||(n=this.memoTable[e]=new ol),n}processFailure(e,n){if(this.rightmostFailurePosition=Math.max(this.rightmostFailurePosition,e),this.recordedFailures&&e===this.positionToRecordFailures){const r=this.currentApplication();r&&(n=n.substituteParams(r.args)),this.recordFailure(n.toFailure(this.grammar),!1)}}recordFailure(e,n){const r=e.toKey();this.recordedFailures[r]?this.recordedFailures[r].isFluffy()&&!e.isFluffy()&&this.recordedFailures[r].clearFluffy():this.recordedFailures[r]=n?e.clone():e}recordFailures(e,n){Object.keys(e).forEach(r=>{this.recordFailure(e[r],n)})}cloneRecordedFailures(){if(!this.recordedFailures)return;const e=Object.create(null);return Object.keys(this.recordedFailures).forEach(n=>{e[n]=this.recordedFailures[n].clone()}),e}getRightmostFailurePosition(){return this.rightmostFailurePosition}_getRightmostFailureOffset(){return this.rightmostFailurePosition>=0?this.posToOffset(this.rightmostFailurePosition):-1}getMemoizedTraceEntry(e,n){const r=this.memoTable[e];if(r&&n instanceof X){const s=r.memo[n.toMemoKey()];if(s&&s.traceEntry){const i=s.traceEntry.cloneWithExpr(n);return i.isMemoized=!0,i}}return null}getTraceEntry(e,n,r,s){if(n instanceof X){const i=this.currentApplication(),a=i?i.args:[];n=n.substituteParams(a)}return this.getMemoizedTraceEntry(e,n)||new It(this.input,e,this.inputStream.pos,n,r,s,this.trace)}isTracing(){return!!this.trace}hasNecessaryInfo(e){return this.trace&&!e.traceEntry?!1:this.recordedFailures&&this.inputStream.pos+e.rightmostFailureOffset===this.positionToRecordFailures?!!e.failuresAtRightmostPosition:!0}useMemoizedResult(e,n){this.trace&&this.trace.push(n.traceEntry);const r=this.inputStream.pos+n.rightmostFailureOffset;return this.rightmostFailurePosition=Math.max(this.rightmostFailurePosition,r),this.recordedFailures&&this.positionToRecordFailures===r&&n.failuresAtRightmostPosition&&this.recordFailures(n.failuresAtRightmostPosition,!0),this.inputStream.examinedLength=Math.max(this.inputStream.examinedLength,n.examinedLength+e),n.value?(this.inputStream.pos+=n.matchLength,this.pushBinding(n.value,e),!0):!1}eval(e){const{inputStream:n}=this,r=this._bindings.length,s=this.userData;let i;this.recordedFailures&&(i=this.recordedFailures,this.recordedFailures=Object.create(null));const a=n.pos,o=this.maybeSkipSpacesBefore(e);let c;this.trace&&(c=this.trace,this.trace=[]);const u=e.eval(this);if(this.trace){const d=this._bindings.slice(r),l=this.getTraceEntry(o,e,u,d);l.isImplicitSpaces=e===rs,l.isRootNode=e===this.startExpr,c.push(l),this.trace=c}return u?this.recordedFailures&&n.pos===this.positionToRecordFailures&&Object.keys(this.recordedFailures).forEach(d=>{this.recordedFailures[d].makeFluffy()}):(n.pos=a,this.truncateBindings(r),this.userData=s),this.recordedFailures&&this.recordFailures(i,!1),e===zo&&this.skipSpaces(),u}getMatchResult(){this.grammar._setUpMatchState(this),this.eval(this.startExpr);let e;this.recordedFailures&&(e=Object.keys(this.recordedFailures).map(r=>this.recordedFailures[r]));const n=this._bindings[0];return n&&(n.grammar=this.grammar),new qo(this.matcher,this.input,this.startExpr,n,this._bindingOffsets[0],this.rightmostFailurePosition,e)}getTrace(){this.trace=[];const e=this.getMatchResult(),n=this.trace[this.trace.length-1];return n.result=e,n}pushFailuresInfo(){this._rightmostFailurePositionStack.push(this.rightmostFailurePosition),this._recordedFailuresStack.push(this.recordedFailures)}popFailuresInfo(){this.rightmostFailurePosition=this._rightmostFailurePositionStack.pop(),this.recordedFailures=this._recordedFailuresStack.pop()}}class wl{constructor(e){this.grammar=e,this._memoTable=[],this._input="",this._isMemoTableStale=!1}_resetMemoTable(){this._memoTable=[],this._isMemoTableStale=!1}getInput(){return this._input}setInput(e){return this._input!==e&&this.replaceInputRange(0,this._input.length,e),this}replaceInputRange(e,n,r){const s=this._input,i=this._memoTable;if(e<0||e>s.length||n<0||n>s.length||e>n)throw new Error("Invalid indices: "+e+" and "+n);this._input=s.slice(0,e)+r+s.slice(n),this._input!==s&&i.length>0&&(this._isMemoTableStale=!0);const a=i.slice(n);i.length=e;for(let o=0;o<r.length;o++)i.push(void 0);for(const o of a)i.push(o);for(let o=0;o<e;o++){const c=i[o];c&&c.clearObsoleteEntries(o,e)}return this}match(e,n={incremental:!0}){return this._match(this._getStartExpr(e),{incremental:n.incremental,tracing:!1})}trace(e,n={incremental:!0}){return this._match(this._getStartExpr(e),{incremental:n.incremental,tracing:!0})}_match(e,n={}){const r={tracing:!1,incremental:!0,positionToRecordFailures:void 0,...n};if(!r.incremental)this._resetMemoTable();else if(this._isMemoTableStale&&!this.grammar.supportsIncrementalParsing)throw Bu(this.grammar);const s=new vl(this,e,r.positionToRecordFailures);return r.tracing?s.getTrace():s.getMatchResult()}_getStartExpr(e){const n=e||this.grammar.defaultStartRule;if(!n)throw new Error("Missing start rule argument -- the grammar has no default start rule.");const r=this.grammar.parseApplication(n);return new Ae([r,Re])}}const En=[],ks=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);class Ji{constructor(e,n,r){this._node=e,this.source=n,this._baseInterval=r,e.isNonterminal()&&Lt(n===r),this._childWrappers=[]}_forgetMemoizedResultFor(e){delete this._node[this._semantics.attributeKeys[e]],this.children.forEach(n=>{n._forgetMemoizedResultFor(e)})}child(e){if(!(0<=e&&e<this._node.numChildren()))return;let n=this._childWrappers[e];if(!n){const r=this._node.childAt(e),s=this._node.childOffsets[e],i=this._baseInterval.subInterval(s,r.matchLength),a=r.isNonterminal()?i:this._baseInterval;n=this._childWrappers[e]=this._semantics.wrap(r,i,a)}return n}_children(){for(let e=0;e<this._node.numChildren();e++)this.child(e);return this._childWrappers}isIteration(){return this._node.isIteration()}isTerminal(){return this._node.isTerminal()}isNonterminal(){return this._node.isNonterminal()}isSyntactic(){return this.isNonterminal()&&this._node.isSyntactic()}isLexical(){return this.isNonterminal()&&this._node.isLexical()}isOptional(){return this._node.isOptional()}iteration(e){const n=e||[],r=n.map(a=>a._node),s=new Bo(r,[],-1,!1),i=this._semantics.wrap(s,null,null);return i._childWrappers=n,i}get children(){return this._children()}get ctorName(){return this._node.ctorName}get numChildren(){return this._node.numChildren()}get sourceString(){return this.source.contents}}class Ue{constructor(e,n){const r=this;if(this.grammar=e,this.checkedActionDicts=!1,this.Wrapper=class extends(n?n.Wrapper:Ji){constructor(s,i,a){super(s,i,a),r.checkActionDictsIfHaventAlready(),this._semantics=r}toString(){return"[semantics wrapper for "+r.grammar.name+"]"}},this.super=n,n){if(!(e.equals(this.super.grammar)||e._inheritsFrom(this.super.grammar)))throw new Error("Cannot extend a semantics for grammar '"+this.super.grammar.name+"' for use with grammar '"+e.name+"' (not a sub-grammar)");this.operations=Object.create(this.super.operations),this.attributes=Object.create(this.super.attributes),this.attributeKeys=Object.create(null);for(const s in this.attributes)Object.defineProperty(this.attributeKeys,s,{value:Ki(s)})}else this.operations=Object.create(null),this.attributes=Object.create(null),this.attributeKeys=Object.create(null)}toString(){return"[semantics for "+this.grammar.name+"]"}checkActionDictsIfHaventAlready(){this.checkedActionDicts||(this.checkActionDicts(),this.checkedActionDicts=!0)}checkActionDicts(){let e;for(e in this.operations)this.operations[e].checkActionDict(this.grammar);for(e in this.attributes)this.attributes[e].checkActionDict(this.grammar)}toRecipe(e){function n(s){return s.super!==Ue.BuiltInSemantics._getSemantics()}let r=`(function(g) {
|
|
19
|
+
`;if(n(this)){r+=" var semantics = "+this.super.toRecipe(!0)+"(g";const s=this.super.grammar;let i=this.grammar;for(;i!==s;)r+=".superGrammar",i=i.superGrammar;r+=`);
|
|
20
|
+
`,r+=" return g.extendSemantics(semantics)"}else r+=" return g.createSemantics()";return["Operation","Attribute"].forEach(s=>{const i=this[s.toLowerCase()+"s"];Object.keys(i).forEach(a=>{const{actionDict:o,formals:c,builtInDefault:u}=i[a];let d=a;c.length>0&&(d+="("+c.join(", ")+")");let l;n(this)&&this.super[s.toLowerCase()+"s"][a]?l="extend"+s:l="add"+s,r+=`
|
|
21
|
+
.`+l+"("+JSON.stringify(d)+", {";const p=[];Object.keys(o).forEach(y=>{if(o[y]!==u){let b=o[y].toString().trim();b=b.replace(/^.*\(/,"function("),p.push(`
|
|
22
|
+
`+JSON.stringify(y)+": "+b)}}),r+=p.join(",")+`
|
|
23
|
+
})`})}),r+=`;
|
|
24
|
+
})`,e||(r=`(function() {
|
|
25
|
+
var grammar = this.fromRecipe(`+this.grammar.toRecipe()+`);
|
|
26
|
+
var semantics = `+r+`(grammar);
|
|
27
|
+
return semantics;
|
|
28
|
+
});
|
|
29
|
+
`),r}addOperationOrAttribute(e,n,r){const s=e+"s",i=Qi(n,e),{name:a}=i,{formals:o}=i;this.assertNewName(a,e);const c=Sl(e,a,l),u={_default:c};Object.keys(r).forEach(p=>{u[p]=r[p]});const d=e==="operation"?new Mn(a,o,u,c):new Os(a,u,c);d.checkActionDict(this.grammar),this[s][a]=d;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 b=Object.create(null);for(const[C,I]of Object.entries(p)){const E=y.formals[C];b[E]=I}const w=this.args;this.args=b;const R=y.execute(this._semantics,this);return this.args=w,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:Ki(a)}))}extendOperationOrAttribute(e,n,r){const s=e+"s";if(Qi(n,"attribute"),!(this.super&&n in this.super[s]))throw new Error("Cannot extend "+e+" '"+n+"': did not inherit an "+e+" with that name");if(ks(this[s],n))throw new Error("Cannot extend "+e+" '"+n+"' again");const i=this[s][n].formals,a=this[s][n].actionDict,o=Object.create(a);Object.keys(r).forEach(c=>{o[c]=r[c]}),this[s][n]=e==="operation"?new Mn(n,i,o):new Os(n,o),this[s][n].checkActionDict(this.grammar)}assertNewName(e,n){if(ks(Ji.prototype,e))throw new Error("Cannot add "+n+" '"+e+"': that's a reserved name");if(e in this.operations)throw new Error("Cannot add "+n+" '"+e+"': an operation with that name already exists");if(e in this.attributes)throw new Error("Cannot add "+n+" '"+e+"': an attribute with that name already exists")}wrap(e,n,r){const s=r||n;return e instanceof this.Wrapper?e:new this.Wrapper(e,n,s)}}function Qi(t,e){if(!Ue.prototypeGrammar)return Lt(t.indexOf("(")===-1),{name:t,formals:[]};const n=Ue.prototypeGrammar.match(t,e==="operation"?"OperationSignature":"AttributeSignature");if(n.failed())throw new Error(n.message);return Ue.prototypeGrammarSemantics(n).parse()}function Sl(t,e,n){return function(...r){const i=(this._semantics.operations[e]||this._semantics.attributes[e]).formals.map(a=>this.args[a]);if(!this.isIteration()&&r.length===1)return n.apply(r[0],i);throw el(this.ctorName,e,t,En)}}Ue.createSemantics=function(t,e){const n=new Ue(t,e!==void 0?e:Ue.BuiltInSemantics._getSemantics()),r=function(i){if(!(i instanceof qo))throw new TypeError("Semantics expected a MatchResult, but got "+di(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 Gr(i.input);return n.wrap(a,o.interval(i._cstOffset,i.input.length))};return r.addOperation=function(s,i){return n.addOperationOrAttribute("operation",s,i),r},r.extendOperation=function(s,i){return n.extendOperationOrAttribute("operation",s,i),r},r.addAttribute=function(s,i){return n.addOperationOrAttribute("attribute",s,i),r},r.extendAttribute=function(s,i){return n.extendOperationOrAttribute("attribute",s,i),r},r._getActionDict=function(s){const i=n.operations[s]||n.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},r._remove=function(s){let i;return s in n.operations?(i=n.operations[s],delete n.operations[s]):s in n.attributes&&(i=n.attributes[s],delete n.attributes[s]),delete n.Wrapper.prototype[s],i},r.getOperationNames=function(){return Object.keys(n.operations)},r.getAttributeNames=function(){return Object.keys(n.attributes)},r.getGrammar=function(){return n.grammar},r.toRecipe=function(s){return n.toRecipe(s)},r.toString=n.toString.bind(n),r._getSemantics=function(){return n},r};class Mn{constructor(e,n,r,s){this.name=e,this.formals=n,this.actionDict=r,this.builtInDefault=s}checkActionDict(e){e._checkTopDownActionDict(this.typeName,this.name,this.actionDict)}execute(e,n){try{const{ctorName:r}=n._node;let s=this.actionDict[r];return s?(En.push([this,r]),s.apply(n,n._children())):n.isNonterminal()&&(s=this.actionDict._nonterminal,s)?(En.push([this,"_nonterminal",r]),s.apply(n,n._children())):(En.push([this,"default action",r]),this.actionDict._default.apply(n,n._children()))}finally{En.pop()}}}Mn.prototype.typeName="operation";class Os extends Mn{constructor(e,n,r){super(e,[],n,r)}execute(e,n){const r=n._node,s=e.attributeKeys[this.name];return ks(r,s)||(r[s]=Mn.prototype.execute.call(this,e,n)),r[s]}}Os.prototype.typeName="attribute";const Yi=["_iter","_terminal","_nonterminal","_default"];function Xi(t){return Object.keys(t.rules).sort().map(e=>t.rules[e])}const _l=t=>t.replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029");let Vo,Wo;class De{constructor(e,n,r,s){if(this.name=e,this.superGrammar=n,this.rules=r,s){if(!(s in r))throw new Error("Invalid start rule: '"+s+"' is not a rule in grammar '"+e+"'");this.defaultStartRule=s}this._matchStateInitializer=void 0,this.supportsIncrementalParsing=!0}matcher(){return new wl(this)}isBuiltIn(){return this===De.ProtoBuiltInRules||this===De.BuiltInRules}equals(e){if(this===e)return!0;if(e==null||this.name!==e.name||this.defaultStartRule!==e.defaultStartRule||!(this.superGrammar===e.superGrammar||this.superGrammar.equals(e.superGrammar)))return!1;const n=Xi(this),r=Xi(e);return n.length===r.length&&n.every((s,i)=>s.description===r[i].description&&s.formals.join(",")===r[i].formals.join(",")&&s.body.toString()===r[i].body.toString())}match(e,n){const r=this.matcher();return r.replaceInputRange(0,0,e),r.match(n)}trace(e,n){const r=this.matcher();return r.replaceInputRange(0,0,e),r.trace(n)}createSemantics(){return Ue.createSemantics(this)}extendSemantics(e){return Ue.createSemantics(this,e._getSemantics())}_checkTopDownActionDict(e,n,r){const s=[];for(const i in r){const a=r[i];if(!Yi.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 d;i==="_iter"||i==="_nonterminal"?d=`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.`:d=`expected ${u}, got ${c}`,s.push(`Semantic action '${i}' has the wrong arity: ${d}`)}}if(s.length>0){const i=s.map(o=>"- "+o),a=new Error([`Found errors in the action dictionary of the '${n}' ${e}:`,...i].join(`
|
|
30
|
+
`));throw a.problems=s,a}}_topDownActionArity(e){return Yi.includes(e)?0:this.rules[e].body.getArity()}_inheritsFrom(e){let n=this.superGrammar;for(;n;){if(n.equals(e,!0))return!0;n=n.superGrammar}return!1}toRecipe(e=void 0){const n={};this.source&&(n.source=this.source.contents);let r=null;this.defaultStartRule&&(r=this.defaultStartRule);const s={};Object.keys(this.rules).forEach(o=>{const c=this.rules[o],{body:u}=c,d=!this.superGrammar||!this.superGrammar.rules[o];let l;d?l="define":l=u instanceof Wr?"extend":"override";const p={};if(c.source&&this.source){const w=c.source.relativeTo(this.source);p.sourceInterval=[w.startIdx,w.endIdx]}const y=d?c.description:null,b=u.outputRecipe(c.formals,this.source);s[o]=[l,p,y,c.formals,b]});let i="null";e?i=e:this.superGrammar&&!this.superGrammar.isBuiltIn()&&(i=this.superGrammar.toRecipe());const a=[...["grammar",n,this.name].map(JSON.stringify),i,...[r,s].map(JSON.stringify)];return _l(`[${a.join(",")}]`)}toOperationActionDictionaryTemplate(){return this._toOperationOrAttributeActionDictionaryTemplate()}toAttributeActionDictionaryTemplate(){return this._toOperationOrAttributeActionDictionaryTemplate()}_toOperationOrAttributeActionDictionaryTemplate(){const e=new Qt;e.append("{");let n=!0;for(const r in this.rules){const{body:s}=this.rules[r];n?n=!1:e.append(","),e.append(`
|
|
31
|
+
`),e.append(" "),this.addSemanticActionTemplate(r,s,e)}return e.append(`
|
|
32
|
+
}`),e.contents()}addSemanticActionTemplate(e,n,r){r.append(e),r.append(": function(");const s=this._topDownActionArity(e);r.append(Vr("_",s).join(", ")),r.append(`) {
|
|
33
|
+
`),r.append(" }")}parseApplication(e){let n;if(e.indexOf("<")===-1)n=new X(e);else{const s=Vo.match(e,"Base_application");n=Wo(s,{})}if(!(n.ruleName in this.rules))throw Do(n.ruleName,this.name);const{formals:r}=this.rules[n.ruleName];if(r.length!==n.args.length){const{source:s}=this.rules[n.ruleName];throw Mo(n.ruleName,r.length,n.args.length,s)}return n}_setUpMatchState(e){this._matchStateInitializer&&this._matchStateInitializer(e)}}De.ProtoBuiltInRules=new De("ProtoBuiltInRules",void 0,{any:{body:Te,formals:[],description:"any character",primitive:!0},end:{body:Re,formals:[],description:"end of input",primitive:!0},caseInsensitive:{body:new gi(new Le(0)),formals:["str"],primitive:!0},lower:{body:new Ee("Ll"),formals:[],description:"a lowercase letter",primitive:!0},upper:{body:new Ee("Lu"),formals:[],description:"an uppercase letter",primitive:!0},unicodeLtmo:{body:new Ee("Ltmo"),formals:[],description:"a Unicode character in Lt, Lm, or Lo",primitive:!0},spaces:{body:new Yt(new X("space")),formals:[]},space:{body:new Ne("\0"," "),formals:[],description:"a space"}});De.initApplicationParser=function(t,e){Vo=t,Wo=e};class ea{constructor(e){this.name=e}sourceInterval(e,n){return this.source.subInterval(e,n-e)}ensureSuperGrammar(){return this.superGrammar||this.withSuperGrammar(this.name==="BuiltInRules"?De.ProtoBuiltInRules:De.BuiltInRules),this.superGrammar}ensureSuperGrammarRuleForOverriding(e,n){const r=this.ensureSuperGrammar().rules[e];if(!r)throw zu(e,this.superGrammar.name,n);return r}installOverriddenOrExtendedRule(e,n,r,s){const i=_s(n);if(i.length>0)throw Wi(e,i,s);const a=this.ensureSuperGrammar().rules[e],o=a.formals,c=o?o.length:0;if(n.length!==c)throw Mo(e,c,n.length,s);return this.install(e,n,r,a.description,s)}install(e,n,r,s,i,a=!1){return this.rules[e]={body:r.introduceParams(n),formals:n,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 Gr(e).interval(0,e.length),this}build(){const e=new De(this.name,this.ensureSuperGrammar(),this.rules,this.defaultStartRule);e._matchStateInitializer=e.superGrammar._matchStateInitializer,e.supportsIncrementalParsing=e.superGrammar.supportsIncrementalParsing;const n=[];let r=!1;return Object.keys(e.rules).forEach(s=>{const{body:i}=e.rules[s];try{i.assertChoicesHaveUniformArity(s)}catch(a){n.push(a)}try{i.assertAllApplicationsAreValid(s,e)}catch(a){n.push(a),r=!0}}),r||Object.keys(e.rules).forEach(s=>{const{body:i}=e.rules[s];try{i.assertIteratedExprsAreNotNullable(e,[])}catch(a){n.push(a)}}),n.length>0&&tl(n),this.source&&(e.source=this.source),e}define(e,n,r,s,i,a){if(this.ensureSuperGrammar(),this.superGrammar.rules[e])throw Vi(e,this.name,this.superGrammar.name,i);if(this.rules[e])throw Vi(e,this.name,this.name,i);const o=_s(n);if(o.length>0)throw Wi(e,o,i);return this.install(e,n,r,s,i,a)}override(e,n,r,s,i){return this.ensureSuperGrammarRuleForOverriding(e,i),this.installOverriddenOrExtendedRule(e,n,r,i),this}extend(e,n,r,s,i){if(!this.ensureSuperGrammar().rules[e])throw Vu(e,this.superGrammar.name,i);const o=new Wr(this.superGrammar,e,r);return o.source=r.source,this.installOverriddenOrExtendedRule(e,n,o,i),this}}class dr{constructor(e){this.currentDecl=null,this.currentRuleName=null,this.options=e||{}}newGrammar(e){return new ea(e)}grammar(e,n,r,s,i){const a=new ea(n);return r&&a.withSuperGrammar(r instanceof De?r:this.fromRecipe(r)),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],d=c[1],l=c[2],p=c[3],y=this.fromRecipe(c[4]);let b;a.source&&d&&d.sourceInterval&&(b=a.source.subInterval(d.sourceInterval[0],d.sourceInterval[1]-d.sourceInterval[0])),a[u](o,p,y,l,b)}),this.currentRuleName=this.currentDecl=null,a.build()}terminal(e){return new ke(e)}range(e,n){return new Ne(e,n)}param(e){return new Le(e)}alt(...e){let n=[];for(let r of e)r instanceof V||(r=this.fromRecipe(r)),r instanceof be?n=n.concat(r.terms):n.push(r);return n.length===1?n[0]:new be(n)}seq(...e){let n=[];for(let r of e)r instanceof V||(r=this.fromRecipe(r)),r instanceof Ae?n=n.concat(r.factors):n.push(r);return n.length===1?n[0]:new Ae(n)}star(e){return e instanceof V||(e=this.fromRecipe(e)),new Yt(e)}plus(e){return e instanceof V||(e=this.fromRecipe(e)),new vn(e)}opt(e){return e instanceof V||(e=this.fromRecipe(e)),new wt(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 $e(e)}lex(e){return e instanceof V||(e=this.fromRecipe(e)),new Be(e)}app(e,n){return n&&n.length>0&&(n=n.map(function(r){return r instanceof V?r:this.fromRecipe(r)},this)),new X(e,n)}splice(e,n){return new Hr(this.currentDecl.superGrammar,this.currentRuleName,e.map(r=>this.fromRecipe(r)),n.map(r=>this.fromRecipe(r)))}fromRecipe(e){const n=e[0]==="grammar"?e.slice(1):e.slice(2),r=this[e[0]](...n),s=e[1];return s&&s.sourceInterval&&this.currentDecl&&r.withSource(this.currentDecl.sourceInterval(...s.sourceInterval)),r}}function yi(t){return typeof t=="function"?t.call(new dr):(typeof t=="string"&&(t=JSON.parse(t)),new dr().fromRecipe(t))}const bi=yi(["grammar",{source:`BuiltInRules {
|
|
34
|
+
|
|
35
|
+
alnum (an alpha-numeric character)
|
|
36
|
+
= letter
|
|
37
|
+
| digit
|
|
38
|
+
|
|
39
|
+
letter (a letter)
|
|
40
|
+
= lower
|
|
41
|
+
| upper
|
|
42
|
+
| unicodeLtmo
|
|
43
|
+
|
|
44
|
+
digit (a digit)
|
|
45
|
+
= "0".."9"
|
|
46
|
+
|
|
47
|
+
hexDigit (a hexadecimal digit)
|
|
48
|
+
= digit
|
|
49
|
+
| "a".."f"
|
|
50
|
+
| "A".."F"
|
|
51
|
+
|
|
52
|
+
ListOf<elem, sep>
|
|
53
|
+
= NonemptyListOf<elem, sep>
|
|
54
|
+
| EmptyListOf<elem, sep>
|
|
55
|
+
|
|
56
|
+
NonemptyListOf<elem, sep>
|
|
57
|
+
= elem (sep elem)*
|
|
58
|
+
|
|
59
|
+
EmptyListOf<elem, sep>
|
|
60
|
+
= /* nothing */
|
|
61
|
+
|
|
62
|
+
listOf<elem, sep>
|
|
63
|
+
= nonemptyListOf<elem, sep>
|
|
64
|
+
| emptyListOf<elem, sep>
|
|
65
|
+
|
|
66
|
+
nonemptyListOf<elem, sep>
|
|
67
|
+
= elem (sep elem)*
|
|
68
|
+
|
|
69
|
+
emptyListOf<elem, sep>
|
|
70
|
+
= /* nothing */
|
|
71
|
+
|
|
72
|
+
// Allows a syntactic rule application within a lexical context.
|
|
73
|
+
applySyntactic<app> = app
|
|
74
|
+
}`},"BuiltInRules",null,null,{alnum:["define",{sourceInterval:[18,78]},"an alpha-numeric character",[],["alt",{sourceInterval:[60,78]},["app",{sourceInterval:[60,66]},"letter",[]],["app",{sourceInterval:[73,78]},"digit",[]]]],letter:["define",{sourceInterval:[82,142]},"a letter",[],["alt",{sourceInterval:[107,142]},["app",{sourceInterval:[107,112]},"lower",[]],["app",{sourceInterval:[119,124]},"upper",[]],["app",{sourceInterval:[131,142]},"unicodeLtmo",[]]]],digit:["define",{sourceInterval:[146,177]},"a digit",[],["range",{sourceInterval:[169,177]},"0","9"]],hexDigit:["define",{sourceInterval:[181,254]},"a hexadecimal digit",[],["alt",{sourceInterval:[219,254]},["app",{sourceInterval:[219,224]},"digit",[]],["range",{sourceInterval:[231,239]},"a","f"],["range",{sourceInterval:[246,254]},"A","F"]]],ListOf:["define",{sourceInterval:[258,336]},null,["elem","sep"],["alt",{sourceInterval:[282,336]},["app",{sourceInterval:[282,307]},"NonemptyListOf",[["param",{sourceInterval:[297,301]},0],["param",{sourceInterval:[303,306]},1]]],["app",{sourceInterval:[314,336]},"EmptyListOf",[["param",{sourceInterval:[326,330]},0],["param",{sourceInterval:[332,335]},1]]]]],NonemptyListOf:["define",{sourceInterval:[340,388]},null,["elem","sep"],["seq",{sourceInterval:[372,388]},["param",{sourceInterval:[372,376]},0],["star",{sourceInterval:[377,388]},["seq",{sourceInterval:[378,386]},["param",{sourceInterval:[378,381]},1],["param",{sourceInterval:[382,386]},0]]]]],EmptyListOf:["define",{sourceInterval:[392,434]},null,["elem","sep"],["seq",{sourceInterval:[438,438]}]],listOf:["define",{sourceInterval:[438,516]},null,["elem","sep"],["alt",{sourceInterval:[462,516]},["app",{sourceInterval:[462,487]},"nonemptyListOf",[["param",{sourceInterval:[477,481]},0],["param",{sourceInterval:[483,486]},1]]],["app",{sourceInterval:[494,516]},"emptyListOf",[["param",{sourceInterval:[506,510]},0],["param",{sourceInterval:[512,515]},1]]]]],nonemptyListOf:["define",{sourceInterval:[520,568]},null,["elem","sep"],["seq",{sourceInterval:[552,568]},["param",{sourceInterval:[552,556]},0],["star",{sourceInterval:[557,568]},["seq",{sourceInterval:[558,566]},["param",{sourceInterval:[558,561]},1],["param",{sourceInterval:[562,566]},0]]]]],emptyListOf:["define",{sourceInterval:[572,682]},null,["elem","sep"],["seq",{sourceInterval:[685,685]}]],applySyntactic:["define",{sourceInterval:[685,710]},null,["app"],["param",{sourceInterval:[707,710]},0]]}]);De.BuiltInRules=bi;sl(De.BuiltInRules);const vi=yi(["grammar",{source:`Ohm {
|
|
75
|
+
|
|
76
|
+
Grammars
|
|
77
|
+
= Grammar*
|
|
78
|
+
|
|
79
|
+
Grammar
|
|
80
|
+
= ident SuperGrammar? "{" Rule* "}"
|
|
81
|
+
|
|
82
|
+
SuperGrammar
|
|
83
|
+
= "<:" ident
|
|
84
|
+
|
|
85
|
+
Rule
|
|
86
|
+
= ident Formals? ruleDescr? "=" RuleBody -- define
|
|
87
|
+
| ident Formals? ":=" OverrideRuleBody -- override
|
|
88
|
+
| ident Formals? "+=" RuleBody -- extend
|
|
89
|
+
|
|
90
|
+
RuleBody
|
|
91
|
+
= "|"? NonemptyListOf<TopLevelTerm, "|">
|
|
92
|
+
|
|
93
|
+
TopLevelTerm
|
|
94
|
+
= Seq caseName -- inline
|
|
95
|
+
| Seq
|
|
96
|
+
|
|
97
|
+
OverrideRuleBody
|
|
98
|
+
= "|"? NonemptyListOf<OverrideTopLevelTerm, "|">
|
|
99
|
+
|
|
100
|
+
OverrideTopLevelTerm
|
|
101
|
+
= "..." -- superSplice
|
|
102
|
+
| TopLevelTerm
|
|
103
|
+
|
|
104
|
+
Formals
|
|
105
|
+
= "<" ListOf<ident, ","> ">"
|
|
106
|
+
|
|
107
|
+
Params
|
|
108
|
+
= "<" ListOf<Seq, ","> ">"
|
|
109
|
+
|
|
110
|
+
Alt
|
|
111
|
+
= NonemptyListOf<Seq, "|">
|
|
112
|
+
|
|
113
|
+
Seq
|
|
114
|
+
= Iter*
|
|
115
|
+
|
|
116
|
+
Iter
|
|
117
|
+
= Pred "*" -- star
|
|
118
|
+
| Pred "+" -- plus
|
|
119
|
+
| Pred "?" -- opt
|
|
120
|
+
| Pred
|
|
121
|
+
|
|
122
|
+
Pred
|
|
123
|
+
= "~" Lex -- not
|
|
124
|
+
| "&" Lex -- lookahead
|
|
125
|
+
| Lex
|
|
126
|
+
|
|
127
|
+
Lex
|
|
128
|
+
= "#" Base -- lex
|
|
129
|
+
| Base
|
|
130
|
+
|
|
131
|
+
Base
|
|
132
|
+
= ident Params? ~(ruleDescr? "=" | ":=" | "+=") -- application
|
|
133
|
+
| oneCharTerminal ".." oneCharTerminal -- range
|
|
134
|
+
| terminal -- terminal
|
|
135
|
+
| "(" Alt ")" -- paren
|
|
136
|
+
|
|
137
|
+
ruleDescr (a rule description)
|
|
138
|
+
= "(" ruleDescrText ")"
|
|
139
|
+
|
|
140
|
+
ruleDescrText
|
|
141
|
+
= (~")" any)*
|
|
142
|
+
|
|
143
|
+
caseName
|
|
144
|
+
= "--" (~"\\n" space)* name (~"\\n" space)* ("\\n" | &"}")
|
|
145
|
+
|
|
146
|
+
name (a name)
|
|
147
|
+
= nameFirst nameRest*
|
|
148
|
+
|
|
149
|
+
nameFirst
|
|
150
|
+
= "_"
|
|
151
|
+
| letter
|
|
152
|
+
|
|
153
|
+
nameRest
|
|
154
|
+
= "_"
|
|
155
|
+
| alnum
|
|
156
|
+
|
|
157
|
+
ident (an identifier)
|
|
158
|
+
= name
|
|
159
|
+
|
|
160
|
+
terminal
|
|
161
|
+
= "\\"" terminalChar* "\\""
|
|
162
|
+
|
|
163
|
+
oneCharTerminal
|
|
164
|
+
= "\\"" terminalChar "\\""
|
|
165
|
+
|
|
166
|
+
terminalChar
|
|
167
|
+
= escapeChar
|
|
168
|
+
| ~"\\\\" ~"\\"" ~"\\n" "\\u{0}".."\\u{10FFFF}"
|
|
169
|
+
|
|
170
|
+
escapeChar (an escape sequence)
|
|
171
|
+
= "\\\\\\\\" -- backslash
|
|
172
|
+
| "\\\\\\"" -- doubleQuote
|
|
173
|
+
| "\\\\\\'" -- singleQuote
|
|
174
|
+
| "\\\\b" -- backspace
|
|
175
|
+
| "\\\\n" -- lineFeed
|
|
176
|
+
| "\\\\r" -- carriageReturn
|
|
177
|
+
| "\\\\t" -- tab
|
|
178
|
+
| "\\\\u{" hexDigit hexDigit? hexDigit?
|
|
179
|
+
hexDigit? hexDigit? hexDigit? "}" -- unicodeCodePoint
|
|
180
|
+
| "\\\\u" hexDigit hexDigit hexDigit hexDigit -- unicodeEscape
|
|
181
|
+
| "\\\\x" hexDigit hexDigit -- hexEscape
|
|
182
|
+
|
|
183
|
+
space
|
|
184
|
+
+= comment
|
|
185
|
+
|
|
186
|
+
comment
|
|
187
|
+
= "//" (~"\\n" any)* &("\\n" | end) -- singleLine
|
|
188
|
+
| "/*" (~"*/" any)* "*/" -- multiLine
|
|
189
|
+
|
|
190
|
+
tokens = token*
|
|
191
|
+
|
|
192
|
+
token = caseName | comment | ident | operator | punctuation | terminal | any
|
|
193
|
+
|
|
194
|
+
operator = "<:" | "=" | ":=" | "+=" | "*" | "+" | "?" | "~" | "&"
|
|
195
|
+
|
|
196
|
+
punctuation = "<" | ">" | "," | "--"
|
|
197
|
+
}`},"Ohm",null,"Grammars",{Grammars:["define",{sourceInterval:[9,32]},null,[],["star",{sourceInterval:[24,32]},["app",{sourceInterval:[24,31]},"Grammar",[]]]],Grammar:["define",{sourceInterval:[36,83]},null,[],["seq",{sourceInterval:[50,83]},["app",{sourceInterval:[50,55]},"ident",[]],["opt",{sourceInterval:[56,69]},["app",{sourceInterval:[56,68]},"SuperGrammar",[]]],["terminal",{sourceInterval:[70,73]},"{"],["star",{sourceInterval:[74,79]},["app",{sourceInterval:[74,78]},"Rule",[]]],["terminal",{sourceInterval:[80,83]},"}"]]],SuperGrammar:["define",{sourceInterval:[87,116]},null,[],["seq",{sourceInterval:[106,116]},["terminal",{sourceInterval:[106,110]},"<:"],["app",{sourceInterval:[111,116]},"ident",[]]]],Rule_define:["define",{sourceInterval:[131,181]},null,[],["seq",{sourceInterval:[131,170]},["app",{sourceInterval:[131,136]},"ident",[]],["opt",{sourceInterval:[137,145]},["app",{sourceInterval:[137,144]},"Formals",[]]],["opt",{sourceInterval:[146,156]},["app",{sourceInterval:[146,155]},"ruleDescr",[]]],["terminal",{sourceInterval:[157,160]},"="],["app",{sourceInterval:[162,170]},"RuleBody",[]]]],Rule_override:["define",{sourceInterval:[188,248]},null,[],["seq",{sourceInterval:[188,235]},["app",{sourceInterval:[188,193]},"ident",[]],["opt",{sourceInterval:[194,202]},["app",{sourceInterval:[194,201]},"Formals",[]]],["terminal",{sourceInterval:[214,218]},":="],["app",{sourceInterval:[219,235]},"OverrideRuleBody",[]]]],Rule_extend:["define",{sourceInterval:[255,305]},null,[],["seq",{sourceInterval:[255,294]},["app",{sourceInterval:[255,260]},"ident",[]],["opt",{sourceInterval:[261,269]},["app",{sourceInterval:[261,268]},"Formals",[]]],["terminal",{sourceInterval:[281,285]},"+="],["app",{sourceInterval:[286,294]},"RuleBody",[]]]],Rule:["define",{sourceInterval:[120,305]},null,[],["alt",{sourceInterval:[131,305]},["app",{sourceInterval:[131,170]},"Rule_define",[]],["app",{sourceInterval:[188,235]},"Rule_override",[]],["app",{sourceInterval:[255,294]},"Rule_extend",[]]]],RuleBody:["define",{sourceInterval:[309,362]},null,[],["seq",{sourceInterval:[324,362]},["opt",{sourceInterval:[324,328]},["terminal",{sourceInterval:[324,327]},"|"]],["app",{sourceInterval:[329,362]},"NonemptyListOf",[["app",{sourceInterval:[344,356]},"TopLevelTerm",[]],["terminal",{sourceInterval:[358,361]},"|"]]]]],TopLevelTerm_inline:["define",{sourceInterval:[385,408]},null,[],["seq",{sourceInterval:[385,397]},["app",{sourceInterval:[385,388]},"Seq",[]],["app",{sourceInterval:[389,397]},"caseName",[]]]],TopLevelTerm:["define",{sourceInterval:[366,418]},null,[],["alt",{sourceInterval:[385,418]},["app",{sourceInterval:[385,397]},"TopLevelTerm_inline",[]],["app",{sourceInterval:[415,418]},"Seq",[]]]],OverrideRuleBody:["define",{sourceInterval:[422,491]},null,[],["seq",{sourceInterval:[445,491]},["opt",{sourceInterval:[445,449]},["terminal",{sourceInterval:[445,448]},"|"]],["app",{sourceInterval:[450,491]},"NonemptyListOf",[["app",{sourceInterval:[465,485]},"OverrideTopLevelTerm",[]],["terminal",{sourceInterval:[487,490]},"|"]]]]],OverrideTopLevelTerm_superSplice:["define",{sourceInterval:[522,543]},null,[],["terminal",{sourceInterval:[522,527]},"..."]],OverrideTopLevelTerm:["define",{sourceInterval:[495,562]},null,[],["alt",{sourceInterval:[522,562]},["app",{sourceInterval:[522,527]},"OverrideTopLevelTerm_superSplice",[]],["app",{sourceInterval:[550,562]},"TopLevelTerm",[]]]],Formals:["define",{sourceInterval:[566,606]},null,[],["seq",{sourceInterval:[580,606]},["terminal",{sourceInterval:[580,583]},"<"],["app",{sourceInterval:[584,602]},"ListOf",[["app",{sourceInterval:[591,596]},"ident",[]],["terminal",{sourceInterval:[598,601]},","]]],["terminal",{sourceInterval:[603,606]},">"]]],Params:["define",{sourceInterval:[610,647]},null,[],["seq",{sourceInterval:[623,647]},["terminal",{sourceInterval:[623,626]},"<"],["app",{sourceInterval:[627,643]},"ListOf",[["app",{sourceInterval:[634,637]},"Seq",[]],["terminal",{sourceInterval:[639,642]},","]]],["terminal",{sourceInterval:[644,647]},">"]]],Alt:["define",{sourceInterval:[651,685]},null,[],["app",{sourceInterval:[661,685]},"NonemptyListOf",[["app",{sourceInterval:[676,679]},"Seq",[]],["terminal",{sourceInterval:[681,684]},"|"]]]],Seq:["define",{sourceInterval:[689,704]},null,[],["star",{sourceInterval:[699,704]},["app",{sourceInterval:[699,703]},"Iter",[]]]],Iter_star:["define",{sourceInterval:[719,736]},null,[],["seq",{sourceInterval:[719,727]},["app",{sourceInterval:[719,723]},"Pred",[]],["terminal",{sourceInterval:[724,727]},"*"]]],Iter_plus:["define",{sourceInterval:[743,760]},null,[],["seq",{sourceInterval:[743,751]},["app",{sourceInterval:[743,747]},"Pred",[]],["terminal",{sourceInterval:[748,751]},"+"]]],Iter_opt:["define",{sourceInterval:[767,783]},null,[],["seq",{sourceInterval:[767,775]},["app",{sourceInterval:[767,771]},"Pred",[]],["terminal",{sourceInterval:[772,775]},"?"]]],Iter:["define",{sourceInterval:[708,794]},null,[],["alt",{sourceInterval:[719,794]},["app",{sourceInterval:[719,727]},"Iter_star",[]],["app",{sourceInterval:[743,751]},"Iter_plus",[]],["app",{sourceInterval:[767,775]},"Iter_opt",[]],["app",{sourceInterval:[790,794]},"Pred",[]]]],Pred_not:["define",{sourceInterval:[809,824]},null,[],["seq",{sourceInterval:[809,816]},["terminal",{sourceInterval:[809,812]},"~"],["app",{sourceInterval:[813,816]},"Lex",[]]]],Pred_lookahead:["define",{sourceInterval:[831,852]},null,[],["seq",{sourceInterval:[831,838]},["terminal",{sourceInterval:[831,834]},"&"],["app",{sourceInterval:[835,838]},"Lex",[]]]],Pred:["define",{sourceInterval:[798,862]},null,[],["alt",{sourceInterval:[809,862]},["app",{sourceInterval:[809,816]},"Pred_not",[]],["app",{sourceInterval:[831,838]},"Pred_lookahead",[]],["app",{sourceInterval:[859,862]},"Lex",[]]]],Lex_lex:["define",{sourceInterval:[876,892]},null,[],["seq",{sourceInterval:[876,884]},["terminal",{sourceInterval:[876,879]},"#"],["app",{sourceInterval:[880,884]},"Base",[]]]],Lex:["define",{sourceInterval:[866,903]},null,[],["alt",{sourceInterval:[876,903]},["app",{sourceInterval:[876,884]},"Lex_lex",[]],["app",{sourceInterval:[899,903]},"Base",[]]]],Base_application:["define",{sourceInterval:[918,979]},null,[],["seq",{sourceInterval:[918,963]},["app",{sourceInterval:[918,923]},"ident",[]],["opt",{sourceInterval:[924,931]},["app",{sourceInterval:[924,930]},"Params",[]]],["not",{sourceInterval:[932,963]},["alt",{sourceInterval:[934,962]},["seq",{sourceInterval:[934,948]},["opt",{sourceInterval:[934,944]},["app",{sourceInterval:[934,943]},"ruleDescr",[]]],["terminal",{sourceInterval:[945,948]},"="]],["terminal",{sourceInterval:[951,955]},":="],["terminal",{sourceInterval:[958,962]},"+="]]]]],Base_range:["define",{sourceInterval:[986,1041]},null,[],["seq",{sourceInterval:[986,1022]},["app",{sourceInterval:[986,1001]},"oneCharTerminal",[]],["terminal",{sourceInterval:[1002,1006]},".."],["app",{sourceInterval:[1007,1022]},"oneCharTerminal",[]]]],Base_terminal:["define",{sourceInterval:[1048,1106]},null,[],["app",{sourceInterval:[1048,1056]},"terminal",[]]],Base_paren:["define",{sourceInterval:[1113,1168]},null,[],["seq",{sourceInterval:[1113,1124]},["terminal",{sourceInterval:[1113,1116]},"("],["app",{sourceInterval:[1117,1120]},"Alt",[]],["terminal",{sourceInterval:[1121,1124]},")"]]],Base:["define",{sourceInterval:[907,1168]},null,[],["alt",{sourceInterval:[918,1168]},["app",{sourceInterval:[918,963]},"Base_application",[]],["app",{sourceInterval:[986,1022]},"Base_range",[]],["app",{sourceInterval:[1048,1056]},"Base_terminal",[]],["app",{sourceInterval:[1113,1124]},"Base_paren",[]]]],ruleDescr:["define",{sourceInterval:[1172,1231]},"a rule description",[],["seq",{sourceInterval:[1210,1231]},["terminal",{sourceInterval:[1210,1213]},"("],["app",{sourceInterval:[1214,1227]},"ruleDescrText",[]],["terminal",{sourceInterval:[1228,1231]},")"]]],ruleDescrText:["define",{sourceInterval:[1235,1266]},null,[],["star",{sourceInterval:[1255,1266]},["seq",{sourceInterval:[1256,1264]},["not",{sourceInterval:[1256,1260]},["terminal",{sourceInterval:[1257,1260]},")"]],["app",{sourceInterval:[1261,1264]},"any",[]]]]],caseName:["define",{sourceInterval:[1270,1338]},null,[],["seq",{sourceInterval:[1285,1338]},["terminal",{sourceInterval:[1285,1289]},"--"],["star",{sourceInterval:[1290,1304]},["seq",{sourceInterval:[1291,1302]},["not",{sourceInterval:[1291,1296]},["terminal",{sourceInterval:[1292,1296]},`
|
|
198
|
+
`]],["app",{sourceInterval:[1297,1302]},"space",[]]]],["app",{sourceInterval:[1305,1309]},"name",[]],["star",{sourceInterval:[1310,1324]},["seq",{sourceInterval:[1311,1322]},["not",{sourceInterval:[1311,1316]},["terminal",{sourceInterval:[1312,1316]},`
|
|
199
|
+
`]],["app",{sourceInterval:[1317,1322]},"space",[]]]],["alt",{sourceInterval:[1326,1337]},["terminal",{sourceInterval:[1326,1330]},`
|
|
200
|
+
`],["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]},`
|
|
201
|
+
`]],["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]},`
|
|
202
|
+
`]],["app",{sourceInterval:[2424,2427]},"any",[]]]],["lookahead",{sourceInterval:[2430,2443]},["alt",{sourceInterval:[2432,2442]},["terminal",{sourceInterval:[2432,2436]},`
|
|
203
|
+
`],["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]},"--"]]]}]),ss=Object.create(V.prototype);function ta(t,e){for(const n in t)if(n===e)return!0;return!1}function Ho(t,e,n,r){const s=new dr(r);let i,a,o,c=!1;return(n||vi).createSemantics().addOperation("visit",{Grammars(l){return l.children.map(p=>p.visit())},Grammar(l,p,y,b,w){const R=l.visit();i=s.newGrammar(R),p.child(0)&&p.child(0).visit(),b.children.map(I=>I.visit());const C=i.build();if(C.source=this.source.trimmed(),ta(e,R))throw Uu(C);return e[R]=C,C},SuperGrammar(l,p){const y=p.visit();if(y==="null")i.withSuperGrammar(null);else{if(!e||!ta(e,y))throw qu(y,e,p.source);i.withSuperGrammar(e[y])}},Rule_define(l,p,y,b,w){a=l.visit(),o=p.children.map(E=>E.visit())[0]||[],!i.defaultStartRule&&i.ensureSuperGrammar()!==De.ProtoBuiltInRules&&i.withDefaultStartRule(a);const R=w.visit(),C=y.children.map(E=>E.visit())[0],I=this.source.trimmed();return i.define(a,o,R,C,I)},Rule_override(l,p,y,b){a=l.visit(),o=p.children.map(C=>C.visit())[0]||[];const w=this.source.trimmed();i.ensureSuperGrammarRuleForOverriding(a,w),c=!0;const R=b.visit();return c=!1,i.override(a,o,R,null,w)},Rule_extend(l,p,y,b){a=l.visit(),o=p.children.map(C=>C.visit())[0]||[];const w=b.visit(),R=this.source.trimmed();return i.extend(a,o,w,null,R)},RuleBody(l,p){return s.alt(...p.visit()).withSource(this.source)},OverrideRuleBody(l,p){const y=p.visit(),b=y.indexOf(ss);if(b>=0){const w=y.slice(0,b),R=y.slice(b+1);return R.forEach(C=>{if(C===ss)throw Qu(C)}),new Hr(i.superGrammar,a,w,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(),b=l.visit(),w=this.source.trimmed(),R=!(i.superGrammar&&i.superGrammar.rules[y]);c&&!R?i.override(y,o,b,null,w):i.define(y,o,b,null,w);const C=o.map(I=>s.app(I));return s.app(y,C).withSource(b.source)},OverrideTopLevelTerm_superSplice(l){return ss},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(b=>b.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,b,w){return y.visit()},name(l,p){return this.sourceString},nameFirst(l){},nameRest(l){},terminal(l,p,y){return p.children.map(b=>b.visit()).join("")},oneCharTerminal(l,p,y){return p.visit()},escapeChar(l){try{return No(this.sourceString)}catch(p){throw p instanceof RangeError&&p.message.startsWith("Invalid code point ")?Yu(l):p}},NonemptyListOf(l,p,y){return[l.visit()].concat(y.children.map(b=>b.visit()))},EmptyListOf(){return[]},_terminal(){return this.sourceString}})(t).visit()}const Al=yi(["grammar",{source:`OperationsAndAttributes {
|
|
204
|
+
|
|
205
|
+
AttributeSignature =
|
|
206
|
+
name
|
|
207
|
+
|
|
208
|
+
OperationSignature =
|
|
209
|
+
name Formals?
|
|
210
|
+
|
|
211
|
+
Formals
|
|
212
|
+
= "(" ListOf<name, ","> ")"
|
|
213
|
+
|
|
214
|
+
name (a name)
|
|
215
|
+
= nameFirst nameRest*
|
|
216
|
+
|
|
217
|
+
nameFirst
|
|
218
|
+
= "_"
|
|
219
|
+
| letter
|
|
220
|
+
|
|
221
|
+
nameRest
|
|
222
|
+
= "_"
|
|
223
|
+
| alnum
|
|
224
|
+
|
|
225
|
+
}`},"OperationsAndAttributes",null,"AttributeSignature",{AttributeSignature:["define",{sourceInterval:[29,58]},null,[],["app",{sourceInterval:[54,58]},"name",[]]],OperationSignature:["define",{sourceInterval:[62,100]},null,[],["seq",{sourceInterval:[87,100]},["app",{sourceInterval:[87,91]},"name",[]],["opt",{sourceInterval:[92,100]},["app",{sourceInterval:[92,99]},"Formals",[]]]]],Formals:["define",{sourceInterval:[104,143]},null,[],["seq",{sourceInterval:[118,143]},["terminal",{sourceInterval:[118,121]},"("],["app",{sourceInterval:[122,139]},"ListOf",[["app",{sourceInterval:[129,133]},"name",[]],["terminal",{sourceInterval:[135,138]},","]]],["terminal",{sourceInterval:[140,143]},")"]]],name:["define",{sourceInterval:[147,187]},"a name",[],["seq",{sourceInterval:[168,187]},["app",{sourceInterval:[168,177]},"nameFirst",[]],["star",{sourceInterval:[178,187]},["app",{sourceInterval:[178,186]},"nameRest",[]]]]],nameFirst:["define",{sourceInterval:[191,223]},null,[],["alt",{sourceInterval:[207,223]},["terminal",{sourceInterval:[207,210]},"_"],["app",{sourceInterval:[217,223]},"letter",[]]]],nameRest:["define",{sourceInterval:[227,257]},null,[],["alt",{sourceInterval:[242,257]},["terminal",{sourceInterval:[242,245]},"_"],["app",{sourceInterval:[252,257]},"alnum",[]]]]}]);xl(De.BuiltInRules);Il(Al);function xl(t){const e={empty(){return this.iteration()},nonEmpty(n,r,s){return this.iteration([n].concat(s.children))},self(...n){return this}};Ue.BuiltInSemantics=Ue.createSemantics(t,null).addOperation("asIteration",{emptyListOf:e.empty,nonemptyListOf:e.nonEmpty,EmptyListOf:e.empty,NonemptyListOf:e.nonEmpty,_iter:e.self})}function Il(t){Ue.prototypeGrammarSemantics=t.createSemantics().addOperation("parse",{AttributeSignature(e){return{name:e.parse(),formals:[]}},OperationSignature(e,n){return{name:e.parse(),formals:n.children.map(r=>r.parse())[0]||[]}},Formals(e,n,r){return n.asIteration().children.map(s=>s.parse())},name(e,n){return this.sourceString}}),Ue.prototypeGrammar=t}function El(t){let e=0;const n=[0],r=()=>n[n.length-1],s={},i=/( *).*(?:$|\r?\n|\r)/g;let a;for(;(a=i.exec(t))!=null;){const[o,c]=a;if(o.length===0)break;const u=c.length,d=r(),l=e+u;if(u>d)n.push(u),s[l]=1;else if(u<d){const p=n.length;for(;r()!==u;)n.pop();s[l]=-1*(p-n.length)}e+=o.length}return n.length>1&&(s[e]=1-n.length),s}const Go="an indented block",Ko="a dedent",na=1114112;class kl extends Gr{constructor(e){super(e.input),this.state=e}_indentationAt(e){return this.state.userData[e]||0}atEnd(){return super.atEnd()&&this._indentationAt(this.pos)===0}next(){if(this._indentationAt(this.pos)!==0){this.examinedLength=Math.max(this.examinedLength,this.pos);return}return super.next()}nextCharCode(){return this._indentationAt(this.pos)!==0?(this.examinedLength=Math.max(this.examinedLength,this.pos),na):super.nextCharCode()}nextCodePoint(){return this._indentationAt(this.pos)!==0?(this.examinedLength=Math.max(this.examinedLength,this.pos),na):super.nextCodePoint()}}class ra extends V{constructor(e=!0){super(),this.isIndent=e}allowsSkippingPrecedingSpace(){return!0}eval(e){const{inputStream:n}=e,r=e.userData;e.doNotMemoize=!0;const s=n.pos,i=this.isIndent?1:-1;return(r[s]||0)*i>0?(e.userData=Object.create(r),e.userData[s]-=i,e.pushBinding(new Xt(0),s),!0):(e.processFailure(s,this),!1)}getArity(){return 1}_assertAllApplicationsAreValid(e,n){}_isNullable(e,n){return!1}assertChoicesHaveUniformArity(e){}assertIteratedExprsAreNotNullable(e){}introduceParams(e){return this}substituteParams(e){return this}toString(){return this.isIndent?"indent":"dedent"}toDisplayString(){return this.toString()}toFailure(e){const n=this.isIndent?Go:Ko;return new ze(this,n,"description")}}const Ol=new X("indent"),Cl=new X("dedent"),Tl=new Hr(bi,"any",[Ol,Cl],[]),Rl=new dr().newGrammar("IndentationSensitive").withSuperGrammar(bi).define("indent",[],new ra(!0),Go,void 0,!0).define("dedent",[],new ra(!1),Ko,void 0,!0).extend("any",[],Tl,"any character",void 0).build();Object.assign(Rl,{_matchStateInitializer(t){t.userData=El(t.input),t.inputStream=new kl(t)},supportsIncrementalParsing:!1});De.initApplicationParser(vi,Ho);const Nl=t=>!!t.constructor&&typeof t.constructor.isBuffer=="function"&&t.constructor.isBuffer(t);function Ll(t,e,n){const r=vi.match(t,"Grammars");if(r.failed())throw $u(r);return Ho(r,e,void 0,n)}function Fl(t,e,n){const r=Dl(t,e,n),s=Object.keys(r);if(s.length===0)throw new Error("Missing grammar definition");if(s.length>1){const a=r[s[1]].source;throw new Error(fi(a.sourceString,a.startIdx)+"Found more than one grammar definition -- use ohm.grammars() instead.")}return r[s[0]]}function Dl(t,e,n){const r=Object.create({});if(typeof t!="string")if(Nl(t))t=t.toString();else throw new TypeError("Expected string as first argument, got "+di(t));return Ll(t,r,n),r}function Zo(t,e){return Fl(t,e)}const Ml=`FirestoreRules {
|
|
226
|
+
// === Top-level ===
|
|
227
|
+
// Syntactic rules (capitalized) auto-skip spaces between terms.
|
|
228
|
+
// Lexical rules (lowercase) do NOT skip spaces.
|
|
229
|
+
|
|
230
|
+
// Two accepted orderings. Real \`firestore.rules\` files put
|
|
231
|
+
// \`rules_version\` at line 1 (Firebase convention), so the
|
|
232
|
+
// \`versionFirst\` branch matches that natural shape. The
|
|
233
|
+
// \`importsFirst\` branch keeps legacy samples that put \`import\`
|
|
234
|
+
// declarations above the version line working. The semantic
|
|
235
|
+
// action below normalizes both into the same AST shape, so
|
|
236
|
+
// downstream code doesn't have to care which path matched.
|
|
237
|
+
// Declaration order is STRICT: imports, then functions (#347 probe,
|
|
238
|
+
// 2026-07-17): the production Rules Test API rejects \`import\` after a
|
|
239
|
+
// \`function\` ("Unexpected 'import'") and any declaration before
|
|
240
|
+
// \`rules_version\` ("Unexpected 'rules_version'"), under both
|
|
241
|
+
// rules_version '2' and '2+modules'. Pinned by
|
|
242
|
+
// test/rules/corpus/invalid/009-/010-.
|
|
243
|
+
RulesFile = RulesVersion? ImportDecl* FunctionDef* ServiceBlock -- versionFirst
|
|
244
|
+
| ImportDecl* RulesVersion FunctionDef* ServiceBlock -- importsFirst
|
|
245
|
+
|
|
246
|
+
ImportDecl = "import" "{" ListOf<ident, ","> ","? "}" "from" string ";"
|
|
247
|
+
|
|
248
|
+
RulesVersion = "rules_version" "=" string ";"
|
|
249
|
+
|
|
250
|
+
ServiceBlock = "service" serviceName "{" FunctionDef* DocumentsMatch FunctionDef* "}"
|
|
251
|
+
|
|
252
|
+
DocumentsMatch = "match" matchPath "{" MatchBody "}"
|
|
253
|
+
|
|
254
|
+
MatchBody = MatchBodyItem*
|
|
255
|
+
|
|
256
|
+
MatchBodyItem
|
|
257
|
+
= FunctionDef
|
|
258
|
+
| MatchBlock
|
|
259
|
+
| AllowStatement
|
|
260
|
+
|
|
261
|
+
MatchBlock = "match" matchPath "{" MatchBody "}"
|
|
262
|
+
|
|
263
|
+
// === Statements ===
|
|
264
|
+
|
|
265
|
+
AllowStatement = "allow" OperationList ":" "if" Expr ";"
|
|
266
|
+
|
|
267
|
+
OperationList = Operation ("," Operation)*
|
|
268
|
+
|
|
269
|
+
FunctionDef = "export"? "function" ident "(" ParameterList ")" "{" FunctionBody "}"
|
|
270
|
+
|
|
271
|
+
ParameterList = ListOf<ident, ",">
|
|
272
|
+
|
|
273
|
+
FunctionBody = LetBinding* ReturnStatement
|
|
274
|
+
|
|
275
|
+
LetBinding = "let" ident "=" Expr ";"
|
|
276
|
+
|
|
277
|
+
ReturnStatement = "return" Expr ";"
|
|
278
|
+
|
|
279
|
+
// === Lexical: operations and service name ===
|
|
280
|
+
|
|
281
|
+
Operation
|
|
282
|
+
= "read" ~identChar
|
|
283
|
+
| "write" ~identChar
|
|
284
|
+
| "get" ~identChar
|
|
285
|
+
| "list" ~identChar
|
|
286
|
+
| "create" ~identChar
|
|
287
|
+
| "update" ~identChar
|
|
288
|
+
| "delete" ~identChar
|
|
289
|
+
|
|
290
|
+
serviceName = letter (letter | ".")*
|
|
291
|
+
|
|
292
|
+
// === Lexical: match paths ===
|
|
293
|
+
|
|
294
|
+
matchPath = "/" matchPathSegment ("/" matchPathSegment)*
|
|
295
|
+
|
|
296
|
+
matchPathSegment
|
|
297
|
+
= "{" matchWildcard "}" -- wildcard
|
|
298
|
+
| pathIdent -- literal
|
|
299
|
+
|
|
300
|
+
matchWildcard
|
|
301
|
+
= identStart identChar* "=" "**" -- recursive
|
|
302
|
+
| identStart identChar* -- single
|
|
303
|
+
|
|
304
|
+
pathIdent = (letter | digit | "_" | "-" | ".")+
|
|
305
|
+
|
|
306
|
+
// === Expressions ===
|
|
307
|
+
|
|
308
|
+
Expr = Ternary
|
|
309
|
+
|
|
310
|
+
Ternary
|
|
311
|
+
= LogicalOr "?" Ternary ":" Ternary -- ternary
|
|
312
|
+
| LogicalOr
|
|
313
|
+
|
|
314
|
+
LogicalOr
|
|
315
|
+
= LogicalOr "||" LogicalAnd -- or
|
|
316
|
+
| LogicalAnd
|
|
317
|
+
|
|
318
|
+
LogicalAnd
|
|
319
|
+
= LogicalAnd "&&" InIsExpr -- and
|
|
320
|
+
| InIsExpr
|
|
321
|
+
|
|
322
|
+
InIsExpr
|
|
323
|
+
= Equality in Equality -- in
|
|
324
|
+
| Equality is typeName -- is
|
|
325
|
+
| Equality
|
|
326
|
+
|
|
327
|
+
in = "in" ~identChar
|
|
328
|
+
is = "is" ~identChar
|
|
329
|
+
|
|
330
|
+
Equality
|
|
331
|
+
= Equality "==" Comparison -- eq
|
|
332
|
+
| Equality "!=" Comparison -- neq
|
|
333
|
+
| Comparison
|
|
334
|
+
|
|
335
|
+
Comparison
|
|
336
|
+
= Comparison ">=" Additive -- gte
|
|
337
|
+
| Comparison "<=" Additive -- lte
|
|
338
|
+
| Comparison ">" Additive -- gt
|
|
339
|
+
| Comparison "<" Additive -- lt
|
|
340
|
+
| Additive
|
|
341
|
+
|
|
342
|
+
Additive
|
|
343
|
+
= Additive "+" Multiplicative -- add
|
|
344
|
+
| Additive "-" Multiplicative -- sub
|
|
345
|
+
| Multiplicative
|
|
346
|
+
|
|
347
|
+
Multiplicative
|
|
348
|
+
= Multiplicative "*" UnaryExpr -- mul
|
|
349
|
+
| Multiplicative "/" UnaryExpr -- div
|
|
350
|
+
| Multiplicative "%" UnaryExpr -- mod
|
|
351
|
+
| UnaryExpr
|
|
352
|
+
|
|
353
|
+
UnaryExpr
|
|
354
|
+
= "!" UnaryExpr -- not
|
|
355
|
+
| "-" UnaryExpr -- neg
|
|
356
|
+
| PostfixExpr
|
|
357
|
+
|
|
358
|
+
PostfixExpr
|
|
359
|
+
= PostfixExpr "." memberName "(" ListOf<Expr, ","> ")" -- methodCall
|
|
360
|
+
| PostfixExpr "." memberName -- memberAccess
|
|
361
|
+
| PostfixExpr "[" Expr ":" Expr "]" -- sliceAccess
|
|
362
|
+
| PostfixExpr "[" Expr "]" -- bracketAccess
|
|
363
|
+
| Primary
|
|
364
|
+
|
|
365
|
+
memberName = identStart identChar*
|
|
366
|
+
|
|
367
|
+
Primary
|
|
368
|
+
= "(" Expr ")" -- paren
|
|
369
|
+
| PathLiteral -- path
|
|
370
|
+
| ListLiteral -- list
|
|
371
|
+
| MapLiteral -- map
|
|
372
|
+
| ident "(" ListOf<Expr, ","> ")" -- functionCall
|
|
373
|
+
| literal
|
|
374
|
+
| ident
|
|
375
|
+
|
|
376
|
+
// === Path literals ===
|
|
377
|
+
|
|
378
|
+
PathLiteral = "/" PathLitSegment ("/" PathLitSegment)*
|
|
379
|
+
|
|
380
|
+
PathLitSegment
|
|
381
|
+
= "$(" Expr ")" -- interpolation
|
|
382
|
+
| "{" ident "}" -- captureRef
|
|
383
|
+
| "(" pathIdent ")" -- parenLiteral
|
|
384
|
+
| pathIdent -- literal
|
|
385
|
+
|
|
386
|
+
// === Literals ===
|
|
387
|
+
|
|
388
|
+
literal
|
|
389
|
+
= number
|
|
390
|
+
| string
|
|
391
|
+
| bool
|
|
392
|
+
| null
|
|
393
|
+
|
|
394
|
+
number
|
|
395
|
+
= digit+ "." digit+ -- float
|
|
396
|
+
| digit+ -- int
|
|
397
|
+
|
|
398
|
+
string
|
|
399
|
+
= "'" singleStringChar* "'" -- single
|
|
400
|
+
| "\\"" doubleStringChar* "\\"" -- double
|
|
401
|
+
|
|
402
|
+
singleStringChar
|
|
403
|
+
= "\\\\" stringEscapeChar -- escape
|
|
404
|
+
| ~"\\\\" ~"'" any -- char
|
|
405
|
+
|
|
406
|
+
doubleStringChar
|
|
407
|
+
= "\\\\" stringEscapeChar -- escape
|
|
408
|
+
| ~"\\\\" ~"\\"" any -- char
|
|
409
|
+
|
|
410
|
+
// Valid escape characters following a backslash. Anything else is rejected
|
|
411
|
+
// at parse time to match production semantics — production Firestore Rules
|
|
412
|
+
// raises a syntax error on unknown escapes (e.g. \`\\d\`, \`\\.\`). Keeping the
|
|
413
|
+
// sim strict here prevents over-permissive acceptance that masks model
|
|
414
|
+
// output that would crash at deploy.
|
|
415
|
+
stringEscapeChar = "\\\\" | "'" | "\\"" | "n" | "r" | "t" | "/"
|
|
416
|
+
|
|
417
|
+
ListLiteral = "[" ListOf<Expr, ","> ","? "]"
|
|
418
|
+
|
|
419
|
+
MapLiteral = "{" ListOf<MapEntry, ","> ","? "}"
|
|
420
|
+
|
|
421
|
+
MapEntry = (string | ident) ":" Expr
|
|
422
|
+
|
|
423
|
+
bool
|
|
424
|
+
= "true" ~identChar -- true
|
|
425
|
+
| "false" ~identChar -- false
|
|
426
|
+
|
|
427
|
+
null = "null" ~identChar
|
|
428
|
+
|
|
429
|
+
typeName
|
|
430
|
+
= "string" ~identChar
|
|
431
|
+
| "int" ~identChar
|
|
432
|
+
| "float" ~identChar
|
|
433
|
+
| "number" ~identChar
|
|
434
|
+
| "bool" ~identChar
|
|
435
|
+
| "list" ~identChar
|
|
436
|
+
| "map" ~identChar
|
|
437
|
+
| "timestamp" ~identChar
|
|
438
|
+
| "path" ~identChar
|
|
439
|
+
| "bytes" ~identChar
|
|
440
|
+
| "duration" ~identChar
|
|
441
|
+
| "latlng" ~identChar
|
|
442
|
+
| "reference" ~identChar
|
|
443
|
+
|
|
444
|
+
ident = ~keyword identStart identChar*
|
|
445
|
+
|
|
446
|
+
keyword
|
|
447
|
+
= ("true" | "false" | "null" | "in" | "is" | "if" | "return" | "let") ~identChar
|
|
448
|
+
|
|
449
|
+
identStart = letter | "_"
|
|
450
|
+
|
|
451
|
+
identChar = alnum | "_"
|
|
452
|
+
|
|
453
|
+
// === Whitespace and comments ===
|
|
454
|
+
|
|
455
|
+
space += comment
|
|
456
|
+
|
|
457
|
+
comment
|
|
458
|
+
= "//" (~"\\n" any)* &("\\n" | end) -- singleLine
|
|
459
|
+
| "/*" (~"*/" any)* "*/" -- multiLine
|
|
460
|
+
}
|
|
461
|
+
`,Jo=Zo(Ml),Qo=Jo.createSemantics();Qo.addOperation("toAST",{RulesFile_versionFirst(t,e,n,r){return{imports:e.children.map(s=>s.toAST()),version:t.children.length>0?t.children[0].toAST():"1",functions:n.children.map(s=>s.toAST()),service:r.toAST()}},RulesFile_importsFirst(t,e,n,r){return{imports:t.children.map(s=>s.toAST()),version:e.toAST(),functions:n.children.map(s=>s.toAST()),service:r.toAST()}},ImportDecl(t,e,n,r,s,i,a,o){const{lineNum:c,colNum:u}=t.source.getLineAndColumn();return{functions:n.asIteration().children.map(d=>d.sourceString),module:a.toAST().value,loc:{line:c,col:u}}},RulesVersion(t,e,n,r){return n.toAST().value},ServiceBlock(t,e,n,r,s,i,a){const{lineNum:o,colNum:c}=t.source.getLineAndColumn();return{name:e.sourceString,functions:[...r.children.map(u=>u.toAST()),...i.children.map(u=>u.toAST())],match:s.toAST(),loc:{line:o,col:c}}},DocumentsMatch(t,e,n,r,s){const{lineNum:i,colNum:a}=t.source.getLineAndColumn();return{...r.toAST(),path:ia(e.sourceString),loc:{line:i,col:a}}},MatchBody(t){const e=[],n=[],r=[];for(const s of t.children){const i=s.toAST();i._kind==="function"?e.push(i):i._kind==="allow"?n.push(i):i._kind==="match"&&r.push(i)}return{functions:e,allows:n,children:r}},MatchBodyItem(t){return t.toAST()},MatchBlock(t,e,n,r,s){const{functions:i,allows:a,children:o}=r.toAST(),{lineNum:c,colNum:u}=t.source.getLineAndColumn();return{_kind:"match",path:ia(e.sourceString),functions:i,allows:a,children:o,loc:{line:c,col:u}}},AllowStatement(t,e,n,r,s,i){const{lineNum:a,colNum:o}=t.source.getLineAndColumn();return{_kind:"allow",operations:e.toAST(),condition:s.toAST(),loc:{line:a,col:o}}},OperationList(t,e,n){return[t.toAST(),...n.children.map(r=>r.toAST())]},Operation(t){return t.sourceString},FunctionDef(t,e,n,r,s,i,a,o,c){const{lets:u,expr:d}=o.toAST(),{lineNum:l,colNum:p}=e.source.getLineAndColumn();let y=!1;return t.sourceString.trim()==="export"&&(y=!0),{_kind:"function",name:n.sourceString,parameters:s.toAST(),exported:y,lets:u,body:d,loc:{line:l,col:p}}},ParameterList(t){return t.asIteration().children.map(e=>e.sourceString)},FunctionBody(t,e){return{lets:t.children.map(n=>n.toAST()),expr:e.toAST()}},LetBinding(t,e,n,r,s){const{lineNum:i,colNum:a}=t.source.getLineAndColumn();return{name:e.sourceString,value:r.toAST(),loc:{line:i,col:a}}},ReturnStatement(t,e,n){return e.toAST()},Expr(t){return t.toAST()},Ternary_ternary(t,e,n,r,s){return{type:"ternary",condition:t.toAST(),consequent:n.toAST(),alternate:s.toAST()}},LogicalOr_or(t,e,n){return{type:"binaryOp",op:"||",left:t.toAST(),right:n.toAST()}},LogicalAnd_and(t,e,n){return{type:"binaryOp",op:"&&",left:t.toAST(),right:n.toAST()}},InIsExpr_in(t,e,n){return{type:"inExpr",element:t.toAST(),collection:n.toAST()}},InIsExpr_is(t,e,n){return{type:"isExpr",value:t.toAST(),typeName:n.sourceString}},Equality_eq(t,e,n){return{type:"binaryOp",op:"==",left:t.toAST(),right:n.toAST()}},Equality_neq(t,e,n){return{type:"binaryOp",op:"!=",left:t.toAST(),right:n.toAST()}},Comparison_gte(t,e,n){return{type:"binaryOp",op:">=",left:t.toAST(),right:n.toAST()}},Comparison_lte(t,e,n){return{type:"binaryOp",op:"<=",left:t.toAST(),right:n.toAST()}},Comparison_gt(t,e,n){return{type:"binaryOp",op:">",left:t.toAST(),right:n.toAST()}},Comparison_lt(t,e,n){return{type:"binaryOp",op:"<",left:t.toAST(),right:n.toAST()}},Additive_add(t,e,n){return{type:"binaryOp",op:"+",left:t.toAST(),right:n.toAST()}},Additive_sub(t,e,n){return{type:"binaryOp",op:"-",left:t.toAST(),right:n.toAST()}},Multiplicative_mul(t,e,n){return{type:"binaryOp",op:"*",left:t.toAST(),right:n.toAST()}},Multiplicative_div(t,e,n){return{type:"binaryOp",op:"/",left:t.toAST(),right:n.toAST()}},Multiplicative_mod(t,e,n){return{type:"binaryOp",op:"%",left:t.toAST(),right:n.toAST()}},UnaryExpr_not(t,e){return{type:"unaryOp",op:"!",operand:e.toAST()}},UnaryExpr_neg(t,e){return{type:"unaryOp",op:"-",operand:e.toAST()}},PostfixExpr_methodCall(t,e,n,r,s,i){return{type:"methodCall",object:t.toAST(),method:n.sourceString,args:s.asIteration().children.map(a=>a.toAST())}},PostfixExpr_memberAccess(t,e,n){return{type:"memberAccess",object:t.toAST(),property:n.sourceString}},PostfixExpr_bracketAccess(t,e,n,r){return{type:"bracketAccess",object:t.toAST(),index:n.toAST()}},PostfixExpr_sliceAccess(t,e,n,r,s,i){return{type:"sliceAccess",object:t.toAST(),start:n.toAST(),end:s.toAST()}},Primary_paren(t,e,n){return e.toAST()},Primary_path(t){return t.toAST()},Primary_list(t){return t.toAST()},Primary_map(t){return t.toAST()},Primary_functionCall(t,e,n,r){return{type:"functionCall",name:t.sourceString,args:n.asIteration().children.map(s=>s.toAST())}},PathLiteral(t,e,n,r){const s=[e.toAST()];for(const i of r.children)s.push(i.toAST());return{type:"pathLiteral",raw:this.sourceString,segments:s}},PathLitSegment_interpolation(t,e,n){return e.toAST()},PathLitSegment_captureRef(t,e,n){return`{${e.sourceString}}`},PathLitSegment_parenLiteral(t,e,n){return`(${e.sourceString})`},PathLitSegment_literal(t){return t.sourceString},ListLiteral(t,e,n,r){return{type:"listLiteral",elements:e.asIteration().children.map(s=>s.toAST())}},MapLiteral(t,e,n,r){return{type:"mapLiteral",entries:e.asIteration().children.map(s=>s.toAST())}},MapEntry(t,e,n){return{key:t.toAST(),value:n.toAST()}},literal(t){return t.toAST()},number_float(t,e,n){return{type:"literal",value:parseFloat(this.sourceString),raw:this.sourceString}},number_int(t){return{type:"literal",value:parseInt(this.sourceString,10),raw:this.sourceString}},string_single(t,e,n){return{type:"literal",value:sa(e.sourceString),raw:this.sourceString}},string_double(t,e,n){return{type:"literal",value:sa(e.sourceString),raw:this.sourceString}},bool_true(t){return{type:"literal",value:!0,raw:"true"}},bool_false(t){return{type:"literal",value:!1,raw:"false"}},null(t){return{type:"literal",value:null,raw:"null"}},ident(t,e){return{type:"identifier",name:this.sourceString}},_nonterminal(...t){return t.length===1?t[0].toAST():t.map(e=>e.toAST())},_terminal(){return this.sourceString}});function sa(t){let e="";for(let n=0;n<t.length;n++){const r=t[n];if(r!=="\\"||n===t.length-1){e+=r;continue}switch(t[n+1]){case"\\":e+="\\",n++;break;case"'":e+="'",n++;break;case'"':e+='"',n++;break;case"n":e+=`
|
|
462
|
+
`,n++;break;case"r":e+="\r",n++;break;case"t":e+=" ",n++;break;case"/":e+="/",n++;break;default:e+=r}}return e}function ia(t){const e=[],n=t.split("/").filter(Boolean);for(const r of n)if(r.startsWith("{")&&r.endsWith("}")){const s=r.slice(1,-1);s.endsWith("=**")?e.push({type:"recursive",name:s.slice(0,-3)}):e.push({type:"wildcard",name:s})}else e.push({type:"literal",value:r});return{raw:t,segments:e}}function jl(t,e){const n=t.getRightmostFailurePosition?.()??0,r=t.getExpectedText?.()??"";let s=1,i=-1;for(let u=0;u<n&&u<e.length;u++)e.charCodeAt(u)===10&&(s++,i=u);const a=n-i;let o=e.indexOf(`
|
|
463
|
+
`,n);o===-1&&(o=e.length);const c=e.slice(n,Math.min(o,n+40));return{line:s,column:a,offset:n,expected:r,actual:c,message:t.message??"Parse error"}}function wi(t){const e=hr(t);return e.ok?e.ast:null}function hr(t){const e=t.trim();if(!e)return{ok:!1,error:{line:1,column:1,offset:0,expected:"",actual:"",message:"Empty rules file"}};const n=Jo.match(e);if(!n.succeeded())return{ok:!1,error:jl(n,e)};const r=Qo(n).toAST(),s=t.length-t.trimStart().length;let i=0;for(let o=0;o<s;o++)t.charCodeAt(o)===10&&i++;return i>0&&Pl(r,i),{ok:!0,ast:r}}function rt(t,e){t!==void 0&&(t.line=t.line+e)}function nr(t,e){rt(t.loc,e);for(const n of t.lets)rt(n.loc,e),rt(n.value.loc,e);rt(t.body.loc,e)}function Pl(t,e){rt(t.loc,e);for(const a of t.imports)rt(a.loc,e);if(t.functions!==void 0)for(const a of t.functions)nr(a,e);if(rt(t.service.loc,e),t.service.functions!==void 0)for(const a of t.service.functions)nr(a,e);const s=[t.service.match];let i=s.length;for(;i>0;){const a=s.pop();rt(a.loc,e);for(const o of a.functions)nr(o,e);for(const o of a.allows)rt(o.loc,e),rt(o.condition.loc,e);for(const o of a.children)s.push(o);i=s.length}}function $l(t,e){t.loc!==void 0&&(t.loc.file=e);for(const s of t.lets)s.loc!==void 0&&(s.loc.file=e),s.value.loc!==void 0&&(s.value.loc.file=e);t.body.loc!==void 0&&(t.body.loc.file=e)}function ql(t,e){const n=`rules_version = '2';
|
|
464
|
+
service cloud.firestore {
|
|
465
|
+
match /databases/{db}/documents {
|
|
466
|
+
${t}
|
|
467
|
+
}
|
|
468
|
+
}`,r=wi(n);if(r===null)return null;const i=r.service.match.functions;for(const a of i)nr(a,-3),e!==void 0&&$l(a,e);return i}const Yo={"||":2,"&&":3,"==":5,"!=":5,">":6,"<":6,">=":6,"<=":6,"+":7,"-":7,"*":8,"/":8,"%":8};function Ul(t){switch(t.type){case"ternary":return 1;case"binaryOp":return Yo[t.op]??0;case"inExpr":return 4;case"isExpr":return 4;case"unaryOp":return 9;default:return 100}}function Bl(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`${Ke(t.object,10)}.${t.property}`;case"methodCall":return`${Ke(t.object,10)}.${t.method}(${t.args.map(e=>ve(e)).join(", ")})`;case"bracketAccess":return`${Ke(t.object,10)}[${ve(t.index)}]`;case"sliceAccess":return`${Ke(t.object,10)}[${ve(t.start)}:${ve(t.end)}]`;case"binaryOp":{const e=Yo[t.op]??0,n=Ke(t.left,e),r=Ke(t.right,e+1);return`${n} ${t.op} ${r}`}case"unaryOp":return`${t.op}${Ke(t.operand,9)}`;case"ternary":return`${Ke(t.condition,2)} ? ${ve(t.consequent)} : ${ve(t.alternate)}`;case"inExpr":return`${Ke(t.element,5)} in ${Ke(t.collection,5)}`;case"isExpr":return`${Ke(t.value,5)} is ${t.typeName}`;case"listLiteral":return t.elements.length===0?"[]":`[${t.elements.map(e=>ve(e)).join(", ")}]`;case"mapLiteral":return t.entries.length===0?"{}":`{${t.entries.map(e=>`${ve(e.key)}: ${ve(e.value)}`).join(", ")}}`;case"pathLiteral":return"/"+t.segments.map(e=>typeof e=="string"?e:`$(${ve(e)})`).join("/");case"functionCall":return`${t.name}(${t.args.map(e=>ve(e)).join(", ")})`}}function Ke(t,e){const n=Bl(t);return Ul(t)<e?`(${n})`:n}function ve(t){return Ke(t,0)}function zl(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 fr(t){return" ".repeat(t)}function dn(t,e,n,r){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};r!==void 0&&(o.expression=r),n.push(o)}}function Cs(t,e,n,r){const s=fr(e),i=fr(e+2),a=t.parameters.join(", ");let o="";t.exported===!0&&(o="export ");const u=n.length+1;n.push(`${s}${o}function ${t.name}(${a}) {`),dn(t.loc,u,r);for(const l of t.lets){const p=n.length+1;n.push(`${i}let ${l.name} = ${ve(l.value)};`),dn(l.loc,p,r)}const d=n.length+1;n.push(`${i}return ${ve(t.body)};`),dn(t.body.loc,d,r),n.push(`${s}}`)}function Vl(t,e,n,r){const s=fr(e),i=t.operations.join(", "),a=ve(t.condition),o=n.length+1;n.push(`${s}allow ${i}: if ${a};`),dn(t.loc,o,r,a)}function Xo(t,e,n,r){const s=fr(e),i=e+2,a=n.length+1;n.push(`${s}match ${zl(t.path)} {`),dn(t.loc,a,r);for(const o of t.functions)Cs(o,i,n,r);for(const o of t.allows)Vl(o,i,n,r);for(const o of t.children)Xo(o,i,n,r);n.push(`${s}}`)}function Ts(t){const e=[],n=[];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)Cs(o,0,e,n);const s=e.length+1;if(e.push(`service ${t.service.name} {`),dn(t.service.loc,s,n),t.service.functions!==void 0)for(const o of t.service.functions)Cs(o,2,e,n);const a=t.service.match;return Xo(a,2,e,n),e.push("}"),e.push(""),{resolved:e.join(`
|
|
469
|
+
`),sourceMap:n}}function aa(t){return Ts(t).resolved}const rr=new Set(["get","exists","getAfter","debug"]);function pr(t,e){return t.type!=="binaryOp"||t.op!==e?0:1+pr(t.right,e)}function Rs(t){let e={op:"",depth:0};function n(s){if(s.type==="binaryOp"){const i=pr(s,"&&"),a=pr(s,"||");i>e.depth&&(e={op:"&&",depth:i}),a>e.depth&&(e={op:"||",depth:a}),n(s.left),n(s.right)}else r(s)}function r(s){switch(s.type){case"unaryOp":n(s.operand);break;case"methodCall":n(s.object),s.args.forEach(n);break;case"memberAccess":n(s.object);break;case"bracketAccess":n(s.object),n(s.index);break;case"ternary":n(s.condition),n(s.consequent),n(s.alternate);break;case"inExpr":n(s.element),n(s.collection);break;case"isExpr":n(s.value);break;case"listLiteral":s.elements.forEach(n);break;case"mapLiteral":s.entries.forEach(i=>{n(i.key),n(i.value)});break;case"functionCall":s.args.forEach(n);break}}return n(t),e}function oe(t){let e=1;switch(t.type){case"binaryOp":e+=oe(t.left)+oe(t.right);break;case"unaryOp":e+=oe(t.operand);break;case"methodCall":e+=oe(t.object);for(const n of t.args)e+=oe(n);break;case"memberAccess":e+=oe(t.object);break;case"bracketAccess":e+=oe(t.object)+oe(t.index);break;case"ternary":e+=oe(t.condition)+oe(t.consequent)+oe(t.alternate);break;case"inExpr":e+=oe(t.element)+oe(t.collection);break;case"isExpr":e+=oe(t.value);break;case"listLiteral":for(const n of t.elements)e+=oe(n);break;case"mapLiteral":for(const n of t.entries)e+=oe(n.key)+oe(n.value);break;case"functionCall":for(const n of t.args)e+=oe(n);break;case"pathLiteral":for(const n of t.segments)typeof n!="string"&&(e+=oe(n));break}return e}function ae(t){switch(t.type){case"literal":return`L:${t.raw}`;case"identifier":return`I:${t.name}`;case"memberAccess":return`M:${ae(t.object)}.${t.property}`;case"methodCall":return`MC:${ae(t.object)}.${t.method}(${t.args.map(ae).join(",")})`;case"bracketAccess":return`B:${ae(t.object)}[${ae(t.index)}]`;case"binaryOp":return`BO:${ae(t.left)}${t.op}${ae(t.right)}`;case"unaryOp":return`UO:${t.op}${ae(t.operand)}`;case"ternary":return`T:${ae(t.condition)}?${ae(t.consequent)}:${ae(t.alternate)}`;case"inExpr":return`IN:${ae(t.element)}in${ae(t.collection)}`;case"isExpr":return`IS:${ae(t.value)}is${t.typeName}`;case"listLiteral":return`LL:[${t.elements.map(ae).join(",")}]`;case"mapLiteral":return`ML:{${t.entries.map(e=>ae(e.key)+":"+ae(e.value)).join(",")}}`;case"functionCall":return`FC:${t.name}(${t.args.map(ae).join(",")})`;case"pathLiteral":return`PL:${t.raw}`;case"sliceAccess":return`SL:${ae(t.object)}[${ae(t.start)}:${ae(t.end)}]`;default:{const e=t;throw new Error(`expressionFingerprint: unhandled type ${e.type}`)}}}function ec(t){return t.type==="binaryOp"&&t.op==="&&"?ec(t.left):t}function tc(t){const e=new Map,n=new Set(t.map(s=>s.name));function r(s){const i=[],a=o=>{switch(o.type){case"functionCall":n.has(o.name)&&!rr.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(...r(s.body));for(const a of s.lets)i.push(...r(a.value));e.set(s.name,[...new Set(i)])}return e}function Si(t,e,n=new Set){if(n.has(t))return 0;n.add(t);const r=e.get(t)||[];if(r.length===0)return 1;let s=0;for(const i of r)s=Math.max(s,Si(i,e,new Set(n)));return 1+s}function nc(t,e,n=new Set){let r=0;const s=i=>{switch(i.type){case"functionCall":if(i.name==="get"||i.name==="exists")r++;else if(e.has(i.name)&&!n.has(i.name)){n.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),r}function Wl(t,e){const n=new Map,r=s=>{switch(s.type){case"functionCall":e.has(s.name)&&n.set(s.name,(n.get(s.name)??0)+1),s.args.forEach(r);break;case"binaryOp":r(s.left),r(s.right);break;case"unaryOp":r(s.operand);break;case"methodCall":r(s.object),s.args.forEach(r);break;case"memberAccess":r(s.object);break;case"bracketAccess":r(s.object),r(s.index);break;case"ternary":r(s.condition),r(s.consequent),r(s.alternate);break;case"inExpr":r(s.element),r(s.collection);break;case"isExpr":r(s.value);break;case"listLiteral":s.elements.forEach(r);break;case"mapLiteral":s.entries.forEach(i=>{r(i.key),r(i.value)});break}};return r(t),n}function rc(t,e,n=new Set){if(n.has(t))return!1;n.add(t);const r=e.get(t);if(!r)return!1;const s=i=>{switch(i.type){case"functionCall":return i.name==="get"||i.name==="exists"?!0:e.has(i.name)?rc(i.name,e,n):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(r.body)||r.lets.some(i=>s(i.value))}function Ns(t,e,n=new Set){const r=s=>{switch(s.type){case"memberAccess":return s.property==="time"&&s.object.type==="identifier"&&s.object.name==="request"?!0:r(s.object);case"bracketAccess":return s.object.type==="identifier"&&s.object.name==="request"&&s.index.type==="literal"&&s.index.value==="time"?!0:r(s.object)||r(s.index);case"functionCall":if(e.has(s.name)&&!n.has(s.name)){n.add(s.name);const i=e.get(s.name);if(Ns(i.body,e,n)||i.lets.some(a=>Ns(a.value,e,n)))return!0}return s.args.some(r);case"binaryOp":return r(s.left)||r(s.right);case"unaryOp":return r(s.operand);case"methodCall":return r(s.object)||s.args.some(r);case"ternary":return r(s.condition)||r(s.consequent)||r(s.alternate);case"inExpr":return r(s.element)||r(s.collection);case"isExpr":return r(s.value);case"listLiteral":return s.elements.some(r);case"mapLiteral":return s.entries.some(i=>r(i.key)||r(i.value));default:return!1}};return r(t)}function sc(t){const e=[...t.functions];for(const n of t.children)e.push(...sc(n));return e}function ic(t){const e=[];for(const n of t.allows)e.push({rule:n,path:t.path.raw,matchFunctions:t.functions});for(const n of t.children){const r=ic(n);for(const s of r)s.matchFunctions=[...t.functions,...s.matchFunctions];e.push(...r)}return e}const Ls={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()`"},ft={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`"},Hl=new Set(["abs","ceil","floor","round","sqrt","pow","isNaN"]),Gl=[{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"}],Kl=new Set(["size","keys","values","lower","upper","trim","hasAll","hasAny","hasOnly","toSet","toUtf8"]),Zl=[{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 Jl(t){const e=[],n=t.replace(/\/\/[^\n]*/g,"").replace(/\/\*[\s\S]*?\*\//g,"");for(const r of Zl)r.pattern.test(n)&&e.push({rule:"INVALID_OPERATOR",severity:"error",message:r.message});return e}function ac(t,e){const n=t.path.raw;for(const r of t.functions){const s={matchPath:n,functionName:r.name};he(r.body,s,e);for(const i of r.lets)he(i.value,s,e)}for(let r=0;r<t.allows.length;r++)he(t.allows[r].condition,{matchPath:n,ruleIndex:r},e);for(const r of t.children)ac(r,e)}function he(t,e,n){switch(n(t,e),t.type){case"binaryOp":he(t.left,e,n),he(t.right,e,n);break;case"unaryOp":he(t.operand,e,n);break;case"methodCall":he(t.object,e,n),t.args.forEach(r=>he(r,e,n));break;case"memberAccess":he(t.object,e,n);break;case"bracketAccess":he(t.object,e,n),he(t.index,e,n);break;case"ternary":he(t.condition,e,n),he(t.consequent,e,n),he(t.alternate,e,n);break;case"inExpr":he(t.element,e,n),he(t.collection,e,n);break;case"isExpr":he(t.value,e,n);break;case"listLiteral":t.elements.forEach(r=>he(r,e,n));break;case"mapLiteral":t.entries.forEach(r=>{he(r.key,e,n),he(r.value,e,n)});break;case"functionCall":t.args.forEach(r=>he(r,e,n));break}}function Ql(t,e){return e?!1:t.type==="functionCall"&&t.name==="debug"}function Yl(t){return t.type==="methodCall"&&!!Ls[t.method]}function Xl(t){return t.type!=="methodCall"||t.object.type!=="identifier"||t.object.name!=="math"?!1:!Hl.has(t.method)}function ed(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 td(t){return t.type!=="methodCall"||t.object.type!=="identifier"?!1:!!ft[t.object.name]}function nd(t){return t.type==="functionCall"&&!!ft[t.name]}function rd(t){return t.type==="identifier"&&!!ft[t.name]}function sd(t){if(t.type!=="memberAccess"||t.object.type!=="identifier")return;const e=t.object.name,n=t.property;return Gl.find(r=>r.receiver===e&&r.property===n)}function id(t){return t.type==="memberAccess"&&t.property==="length"&&t.object.type==="methodCall"}function ad(t){return t.type!=="memberAccess"||!Kl.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 od(t,e={}){const n=[],r=new Set;function s(i,a,o,c){const u=`${i}|${a}|${o.matchPath||""}|${o.functionName||""}|${o.ruleIndex??""}`;r.has(u)||(r.add(u),n.push(c))}return ac(t.service.match,(i,a)=>{if(Ql(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."}),Yl(i)&&i.type==="methodCall"&&s("HALLUCINATED_METHOD",i.method,a,{rule:"HALLUCINATED_METHOD",severity:"error",message:`\`.${i.method}()\` does not exist in Firestore rules. ${Ls[i.method]}`,location:a,fix:Ls[i.method]}),Xl(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."}),ed(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}(...)\`.`}),td(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. ${ft[c]}`,location:a,fix:ft[c]})}nd(i)&&i.type==="functionCall"&&s("HALLUCINATED_GLOBAL",i.name,a,{rule:"HALLUCINATED_GLOBAL",severity:"error",message:`\`${i.name}()\` does not exist in Firestore rules. ${ft[i.name]}`,location:a,fix:ft[i.name]}),rd(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. ${ft[i.name]}`,location:a,fix:ft[i.name]});const o=sd(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(id(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 d=u[1];s("INVALID_PATH_INTERPOLATION",`${i.raw}|${d}`,a,{rule:"INVALID_PATH_INTERPOLATION",severity:"error",message:`\`{${d}}\` 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 \`{${d}}\` with \`$(${d})\` in path \`${i.raw}\`.`,location:a,fix:`Replace \`{${d}}\` with \`$(${d})\` inside the path argument.`})}ad(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}()\`.`})}),n}const ge={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 cd(t,e){t.length>ge.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 ud(t,e){for(const n of t)n.lets.length>ge.LET_LIMIT&&e.push({rule:"LET_LIMIT",severity:"error",message:`Function '${n.name}' has ${n.lets.length} let bindings. Limit is ${ge.LET_LIMIT}.`,location:{functionName:n.name},fix:"Inline some let expressions into the return statement, or split the function."})}function ld(t,e){for(const n of t){const r=Rs(n.body);for(const s of n.lets){const i=Rs(s.value);i.depth>r.depth&&(r.depth=i.depth,r.op=i.op)}r.depth>=ge.CHAIN_DEPTH_LIMIT?e.push({rule:"CHAIN_DEPTH",severity:"error",message:`Function '${n.name}' has a ${r.op} chain of depth ${r.depth}. Limit is ${ge.CHAIN_DEPTH_LIMIT}.`,location:{functionName:n.name},fix:"Split into nested groups: 'a && b && c && d' → '(a && b) && (c && d)' to halve chain depth."}):r.depth>=ge.CHAIN_DEPTH_ERROR?e.push({rule:"CHAIN_DEPTH",severity:"error",message:`Function '${n.name}' has a ${r.op} chain of depth ${r.depth}. Limit is ${ge.CHAIN_DEPTH_LIMIT}. Approaching failure.`,location:{functionName:n.name},fix:"Split the chain into nested groups to reduce depth."}):r.depth>=ge.CHAIN_DEPTH_WARN&&e.push({rule:"CHAIN_DEPTH",severity:"warning",message:`Function '${n.name}' has a ${r.op} chain of depth ${r.depth}. Limit is ${ge.CHAIN_DEPTH_LIMIT}.`,location:{functionName:n.name}})}}function dd(t,e){const n=new Map;for(let r=0;r<t.length;r++){const s=t[r];if(!s.rule.operations.some(o=>o==="update"||o==="write"))continue;const i=ae(ec(s.rule.condition)),a=s.path;n.has(a)||n.set(a,[]),n.get(a).push({index:r,gate:i,ops:s.rule.operations})}for(const[r,s]of n){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 '${r}' share the same gate expression. This may cause cross-rule budget exhaustion. Rules: ${o.join(", ")}.`,location:{matchPath:r},fix:"Assign unique moveType or discriminator values so each rule has a unique first expression."})}}function hd(t,e){let n=oe(t);const r=new Set;function s(i){if(i.type==="functionCall"&&e.has(i.name)&&!r.has(i.name)){r.add(i.name);const a=e.get(i.name);n+=oe(a.body);for(const o of a.lets)n+=oe(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:n,callCount:r.size}}function fd(t,e,n){const r=new Map;for(const s of e)r.set(s.name,s);for(let s=0;s<t.length;s++){const{totalExprs:i,callCount:a}=hd(t[s].rule.condition,r),o=pr(t[s].rule.condition,"||"),c=o>5?.3:o>2?.5:1,u=Math.round(i*c),d=a<=ge.RUNTIME_BUDGET.low.calls?ge.RUNTIME_BUDGET.low:a<=ge.RUNTIME_BUDGET.mid.calls?ge.RUNTIME_BUDGET.mid:ge.RUNTIME_BUDGET.high;u>=d.warn&&n.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 pd(t,e,n){const r=tc(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=Si(c.name,r);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>=ge.CALL_DEPTH_ERROR?n.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>=ge.CALL_DEPTH_WARN&&n.push({rule:"CALL_DEPTH",severity:"warning",message:`Rule #${i} has a function call chain of depth ${a}.`,location:{ruleIndex:i}})}}function md(t,e,n){const r=new Map;for(const s of e)r.set(s.name,s);for(let s=0;s<t.length;s++){const i=nc(t[s].rule.condition,r);i>=ge.GET_COUNT_ERROR?n.push({rule:"GET_COUNT",severity:"error",message:`Rule #${s} may invoke ${i} get()/exists() calls. Limit is ${ge.GET_COUNT_ERROR}.`,location:{ruleIndex:s},fix:"Cache get() results via a config() wrapper function. Same-path calls are cached by Firestore."}):i>=ge.GET_COUNT_WARN&&n.push({rule:"GET_COUNT",severity:"warning",message:`Rule #${s} invokes ${i} get()/exists() calls. Limit is ${ge.GET_COUNT_ERROR}.`,location:{ruleIndex:s}})}}function gd(t,e,n){const r=new Map;for(const i of e)r.set(i.name,i);const s=new Set(e.map(i=>i.name));for(let i=0;i<t.length;i++){const a=Wl(t[i].rule.condition,s);for(const[o,c]of a)c>=2&&rc(o,r)&&n.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 yd(t,e,n,r){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++)Ns(t[o].rule.condition,s)&&i.add(o);if(i.size===0)return;function a(o,c){const u=o.split("/").filter(Boolean),d=c.split("/").filter(Boolean);if(u.length!==d.length)return!1;for(let l=0;l<u.length;l++){const p=u[l];if(!(p.startsWith("{")&&p.endsWith("}"))&&p!==d[l])return!1}return!0}for(const o of n)if(!o.requestTime)for(const c of i)a(t[c].path,o.path)&&r.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 Tn(t){if(t.type==="literal"&&typeof t.value=="boolean")return t.value;if(t.type==="binaryOp"){const e=Tn(t.left),n=Tn(t.right);if(t.op==="&&")return e===!1||n===!1?!1:e===!0&&n===!0?!0:null;if(t.op==="||")return e===!0||n===!0?!0:e===!1&&n===!1?!1:null}if(t.type==="unaryOp"&&t.op==="!"){const e=Tn(t.operand);return e===null?null:!e}return null}const bd=new Set(["write","create","update","delete"]);function vd(t,e){for(let n=0;n<t.length;n++){const r=t[n];if(Tn(r.rule.condition)!==!0||!r.rule.operations.some(a=>bd.has(a)))continue;const i=r.rule.operations.join(", ");e.push({rule:"PERMISSIVE_RULE",severity:"warning",message:`allow ${i} at ${r.path} resolves to a constant true predicate — this disables write security for the matched paths. If you reached for \`if true\` to escape a denial you don't understand, narrow the predicate to the specific request shape instead (auth identity, affected fields via diff, status transitions).`,location:{ruleIndex:n,matchPath:r.path},fix:"Replace the always-true predicate with a request-shape check (e.g. request.auth != null && request.resource.data.ownerId == request.auth.uid)."})}}function oc(t,e){if(t.path.segments.some(r=>r.type==="recursive"))for(let r=0;r<t.allows.length;r++)Tn(t.allows[r].condition)===!0&&e.push({rule:"RECURSIVE_WILDCARD_OPEN",severity:"error",message:`Recursive wildcard match (${t.path.raw}) with an always-true predicate exposes every document under this prefix. This is the Firebase open-rules anti-pattern — never ship it.`,location:{ruleIndex:r,matchPath:t.path.raw},fix:"Either narrow the match path to specific collections, or replace `if true` with a real predicate (auth identity, ownership, role)."});for(const r of t.children)oc(r,e)}function wd(t){return t.type==="literal"?t.value??"":t.type==="wildcard"?"{*}":t.type==="recursive"?"{**}":""}function Sd(t){return t.map(wd).join("/")}function Fs(t,e){const n=Sd(t.path.segments),r=e?`${e}/${n}`:n,s=[{block:t,normalizedPath:r}];for(const i of t.children)s.push(...Fs(i,r));return s}function se(t){switch(t.type){case"literal":return t.raw;case"identifier":return t.name;case"memberAccess":return`${se(t.object)}.${t.property}`;case"methodCall":return`${se(t.object)}.${t.method}(${t.args.map(se).join(",")})`;case"bracketAccess":return`${se(t.object)}[${se(t.index)}]`;case"sliceAccess":return`${se(t.object)}[${se(t.start)}:${se(t.end)}]`;case"binaryOp":return`(${se(t.left)}${t.op}${se(t.right)})`;case"unaryOp":return`(${t.op}${se(t.operand)})`;case"ternary":return`(${se(t.condition)}?${se(t.consequent)}:${se(t.alternate)})`;case"inExpr":return`(${se(t.element)} in ${se(t.collection)})`;case"isExpr":return`(${se(t.value)} is ${t.typeName})`;case"listLiteral":return`[${t.elements.map(se).join(",")}]`;case"mapLiteral":return`{${t.entries.map(e=>`${se(e.key)}:${se(e.value)}`).join(",")}}`;case"pathLiteral":return t.raw;case"functionCall":return`${t.name}(${t.args.map(se).join(",")})`}}function mr(t){return t.type==="binaryOp"&&t.op==="&&"?[...mr(t.left),...mr(t.right)]:[t]}function _d(t,e,n){const r=Fs(t,""),s=Fs(e,""),i=new Map;for(const{block:a,normalizedPath:o}of r)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&&n.push({rule:"RULES_WEAKENED",severity:"warning",message:`Match block removed: ${o}`,location:{matchPath:o}});continue}for(const u of a.allows){const d=[...u.operations].sort().join(","),l=c.allows.find(w=>[...w.operations].sort().join(",")===d),p=u.operations.join(", ");if(!l){n.push({rule:"RULES_WEAKENED",severity:"warning",message:`Allow rule removed: ${o} allow ${p}`,location:{matchPath:o}});continue}const y=mr(u.condition).map(se),b=new Set(mr(l.condition).map(se));for(const w of y)b.has(w)||n.push({rule:"RULES_WEAKENED",severity:"warning",message:`Predicate removed from ${o} allow ${p}: ${w}`,location:{matchPath:o}})}}}function Ds(t,e={}){const n=[];n.push(...Jl(t)),cd(t,n);const r=hr(t);if(!r.ok)return{warnings:n,metrics:{sourceSize:t.length,functionCount:0,allowRuleCount:0,maxChainDepth:0,maxChainOp:"",maxLetBindings:0,maxLetBindingsFunction:"",maxCallDepth:0,maxEstimatedExpressions:0,getCallCount:0},parseError:r.error};const s=r.ast,i=sc(s.service.match),a=ic(s.service.match);if(ld(i,n),ud(i,n),dd(a,n),fd(a,i,n),pd(a,i,n),md(a,i,n),gd(a,i,n),n.push(...od(s,{allowDebug:e.allowDebug||!!(e.testCases&&e.testCases.length>0)})),vd(a,n),oc(s.service.match,n),e.testCases&&e.testCases.length>0&&yd(a,i,e.testCases,n),e.previousSource){const b=hr(e.previousSource);b.ok&&_d(s.service.match,b.ast.service.match,n)}let o={depth:0,op:""},c={count:0,fn:""};for(const b of i){const w=Rs(b.body);w.depth>o.depth&&(o={depth:w.depth,op:w.op}),b.lets.length>c.count&&(c={count:b.lets.length,fn:b.name})}const u=tc(i);let d=0;for(const b of i){const w=Si(b.name,u);w>d&&(d=w)}const l=new Map;for(const b of i)l.set(b.name,b);let p=0,y=0;for(const b of a){const w=nc(b.rule.condition,l);w>y&&(y=w)}return{warnings:n,metrics:{sourceSize:t.length,functionCount:i.length,allowRuleCount:a.length,maxChainDepth:o.depth,maxChainOp:o.op,maxLetBindings:c.count,maxLetBindingsFunction:c.fn,maxCallDepth:d,maxEstimatedExpressions:p,getCallCount:y}}}const cc={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(cc).sort());const Ad={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:[]},uc=["exists","existsAfter","get","getAfter"],xd=["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"],Id={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"]},lc={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"]},Ed=["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"],kd=["get","hasAll","keys","matches","size","split"],Od={get:["map"],hasAll:["set"],keys:["map"],matches:["string"],size:["list","map","string"],split:["string"]},dc={duration:["value"],firestore:["exists","get"],timestamp:["date","value"]},Cd=new Set(Ed),Td=["request.auth.token","request.resource.metadata","resource.metadata"];function Rd(t,e){if(e.length===1)return!0;if(t==="firebase.storage"){const n=e.join(".");return Cd.has(n)||Td.some(r=>n.startsWith(`${r}.`))}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 gr(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 Nd(t,e){if(!e||e==="unknown-ambient")return null;const n=e.join(".");return n==="request.resource"||n==="resource"?"resource":n==="request.auth"||n==="request.auth.token"||t==="cloud.firestore"&&(n==="request.resource.data"||n==="resource.data"||n==="request.query")||n==="request.resource.metadata"||n==="resource.metadata"?"map":n==="request.auth.uid"||n==="request.method"||n==="request.resource.contentType"||n==="resource.contentType"||t==="firebase.storage"&&(n.startsWith("request.resource.metadata.")||n.startsWith("resource.metadata."))?"string":n==="request.path"?"path":n==="request.time"||n==="resource.timeCreated"||n==="resource.updated"?"timestamp":["request.resource.size","resource.size","resource.generation","resource.metageneration"].includes(n)?"number":null}function oa(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 Ld=new Set(uc),Fd=Object.fromEntries(Object.entries(lc).map(([t,e])=>[t,new Set(e)])),Dd=Object.fromEntries(Object.entries(dc).map(([t,e])=>[t,new Set(e)]));function lt(t,e){return t.some(n=>_e(n,e)!==null)?"unknown-ambient":null}function hc(t,e,n){const r=n.declarations?.get(t),s=new Map(r?.aliases),i=new Map(r?.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:r?.functions??n.functions,service:n.service,stack:new Set([...n.stack,t.name]),declarations:n.declarations}}function hn(t,e){return{expression:t,provenance:_e(t,e),receiverType:fe(t,e)}}function _e(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 n=_e(t.object,e);return n==="unknown-ambient"?n:n?[...n,t.property]:null}if(t.type==="bracketAccess"){const n=_e(t.object,e);return!n||n==="unknown-ambient"?n:t.index.type==="literal"&&typeof t.index.value=="string"?[...n,t.index.value]:[...n,"*"]}if(t.type==="ternary"){const n=_e(t.consequent,e),r=_e(t.alternate,e);return!n&&!r?null:Array.isArray(n)&&Array.isArray(r)&&n.join(".")===r.join(".")?n:"unknown-ambient"}if(t.type==="functionCall"){const n=e.functions.get(t.name),r=t.args.map(i=>hn(i,e));if(!n&&Ld.has(t.name))return null;if(!n||e.stack.has(n.name))return r.some(({provenance:i})=>i!==null)?"unknown-ambient":null;const s=hc(n,r,e);for(const i of n.lets){const a=hn(i.value,s);s.aliases.set(i.name,a.provenance),s.receiverTypes.set(i.name,a.receiverType)}return _e(n.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 lt([t.object,...t.args],e);case"sliceAccess":return lt([t.object,t.start,t.end],e);case"binaryOp":return lt([t.left,t.right],e);case"unaryOp":return lt([t.operand],e);case"inExpr":return lt([t.element,t.collection],e);case"isExpr":return lt([t.value],e);case"listLiteral":return lt(t.elements,e);case"mapLiteral":return lt(t.entries.flatMap(({key:n,value:r})=>[n,r]),e);case"pathLiteral":return lt(t.segments.filter(n=>typeof n!="string"),e);default:return null}}function fe(t,e){const n=Nd(e.service,_e(t,e));if(n)return n;switch(t.type){case"identifier":{const r=e.receiverTypes.get(t.name);return r||((e.service==="cloud.firestore"?Fd:Dd)[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 r=fe(t.object,e);if(r==="mixed")return"mixed";if(t.property==="data"&&r==="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?fe(s.value,e):null}return null}case"bracketAccess":{const r=fe(t.object,e);if(r==="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?fe(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?fe(a.value,e):null}if(r==="string")return"string";const s=_e(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 r=fe(t.object,e);return r==="mixed"?"mixed":r==="list"||r==="string"?r:null}case"methodCall":{const r=oa(t);if(t.object.type==="identifier"&&r)return r;if(t.method==="get"){const s=_e(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?fe(o.value,e):i?fe(i,e):null}return i&&fe(i,e)?"mixed":null}return oa(t)}case"binaryOp":{const r=fe(t.left,e),s=fe(t.right,e);return t.op==="+"&&(r==="string"||s==="string")?"string":["==","!=","<","<=",">",">=","&&","||"].includes(t.op)?"boolean":["+","-","*","/","%"].includes(t.op)&&r==="number"&&s==="number"?"number":null}case"unaryOp":return t.op==="!"?"boolean":t.op==="-"&&fe(t.operand,e)==="number"?"number":null;case"inExpr":case"isExpr":return"boolean";case"ternary":{const r=fe(t.consequent,e),s=fe(t.alternate,e);return!r&&!s?null:r===s?r:"mixed"}case"functionCall":{const r=e.functions.get(t.name);if(!r&&e.service==="cloud.firestore"){if(t.name==="get"||t.name==="getAfter")return"document";if(t.name==="exists")return"boolean"}if(!r||e.stack.has(r.name))return null;const s=hc(r,t.args.map(i=>hn(i,e)),e);for(const i of r.lets){const a=hn(i.value,s);s.aliases.set(i.name,a.provenance),s.receiverTypes.set(i.name,a.receiverType)}return fe(r.body,s)}default:return null}}function Md(t){return t.match(/^\.\/stdlib\/(.+?)(?:\.rules)?$/)?.[1]??t}function jd(t,e,n){const r=Md(e),s=cc[r];return s?s.includes(t)?null:`Function '${n}' from module '${e}' is not compatible with service '${t}'`:null}function Pd(t){throw new Error(`Unhandled Rules expression: ${JSON.stringify(t)}`)}const $d=new Set(uc),qd=new Set(xd),Ud=Object.fromEntries(Object.entries(lc).map(([t,e])=>[t,new Set(e)])),Bd=new Set(kd),zd=Object.fromEntries(Object.entries(dc).map(([t,e])=>[t,new Set(e)]));function yr(t,e){return t==="unknown-ambient"?"binding '<derived ambient value>'":t&&!Rd(e,t)?`binding '${t.join(".")}'`:null}function Vd(t,e,n,r,s){if(e!=="get"&&e!=="keys"&&e!=="values")return null;const i=_e(t,s);if(i==="unknown-ambient")return"binding '<derived ambient value>'";if(!i)return null;if(e==="get"){const a=n[0];if(a?.type==="literal"&&typeof a.value=="string")return yr([...i,a.value],r);if(!gr(r,i))return`binding '${i.join(".")}.get(...)'`}return(e==="keys"||e==="values")&&!gr(r,i)?`binding '${i.join(".")}.${e}()'`:null}function Wd(t,e,n,r){const s=_e(t,r),i=fe(t,r);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=fe(c,r);return u==="map"||u==="list"||u==="document"?`method '.${e}()' has an unresolved projected receiver`:null}const o=(n==="cloud.firestore"?Id:Od)[e];return o?.includes(i)?null:`method '.${e}()' requires ${o?.join("|")??"an accepted"} receiver, got ${i}`}function Hd(t,e,n,r){const s=_e(e,r);return s==="unknown-ambient"?"binding '<derived ambient value>'":s?t.type==="literal"&&typeof t.value=="string"?yr([...s,t.value],n):gr(n,s)?null:`binding '<value> in ${s.join(".")}'`:null}function ca(t,e,n){const r=s=>{switch(s.type){case"memberAccess":{const i=yr(_e(s,n),e);return i||r(s.object)}case"functionCall":{const i=n.functions.get(s.name);if(!i&&e==="firebase.storage")return`function '${s.name}()'`;if(!i&&!$d.has(s.name))return`function '${s.name}()'`;for(const a of s.args){const o=r(a);if(o)return o}if(i&&!n.stack.has(i.name)){const a=new Map,o=new Map;i.parameters.forEach((u,d)=>{const l=s.args[d];a.set(u,l?_e(l,n):null),o.set(u,l?fe(l,n):null)});const c=fc(i,e,{aliases:a,receiverTypes:o,functions:n.functions,service:e,stack:new Set([...n.stack,i.name])});if(c)return c}return null}case"methodCall":{if(s.object.type==="identifier"&&!n.aliases.has(s.object.name)){const u=(e==="cloud.firestore"?Ud:zd)[s.object.name];if(u){if(!u.has(s.method))return`method '${s.object.name}.${s.method}()'`;for(const d of s.args){const l=r(d);if(l)return l}return null}return s.object.name==="firestore"?`method 'firestore.${s.method}()'`:`namespace '${s.object.name}'`}if(!(e==="cloud.firestore"?qd:Bd).has(s.method))return`method '.${s.method}()'`;const a=Wd(s.object,s.method,e,n);if(a)return a;const o=Vd(s.object,s.method,s.args,e,n);return o||(r(s.object)??s.args.map(r).find(Boolean)??null)}case"binaryOp":return r(s.left)??r(s.right);case"unaryOp":return r(s.operand);case"bracketAccess":{const i=_e(s.object,n);if(i==="unknown-ambient")return"binding '<derived ambient value>[...]'";const a=s.index.type==="literal"&&typeof s.index.value=="string";if(i&&!a)return gr(e,i)?r(s.object)??r(s.index):`binding '${i.join(".")}[...]'`;const o=yr(_e(s,n),e);return o||(r(s.object)??r(s.index))}case"sliceAccess":return r(s.object)??r(s.start)??r(s.end);case"ternary":return r(s.condition)??r(s.consequent)??r(s.alternate);case"inExpr":return Hd(s.element,s.collection,e,n)??r(s.element)??r(s.collection);case"isExpr":return r(s.value);case"listLiteral":return s.elements.map(r).find(Boolean)??null;case"mapLiteral":for(const i of s.entries){const a=r(i.key)??r(i.value);if(a)return a}return null;case"pathLiteral":for(const i of s.segments)if(typeof i!="string"){const a=r(i);if(a)return a}return null;case"literal":return null;case"identifier":return s.name==="request"||s.name==="resource"||n.aliases.has(s.name)?null:`identifier '${s.name}'`;default:return Pd(s)}};return r(t)}function fc(t,e,n){const r=new Map(n.aliases),s=new Map(n.receiverTypes),i={...n,aliases:r,receiverTypes:s};for(const a of t.lets){const o=ca(a.value,e,i);if(o)return o;r.set(a.name,_e(a.value,i)),s.set(a.name,fe(a.value,i))}return ca(t.body,e,i)}function Gd(t,e,n=new Map([[t.name,t]]),r=[]){const s={aliases:new Map,receiverTypes:new Map,functions:n,service:e,stack:new Set([t.name])};return fc(t,e,{aliases:new Map(t.parameters.map((i,a)=>[i,a<r.length?r[a]?.provenance??null:null])),receiverTypes:new Map(t.parameters.map((i,a)=>[i,r[a]?fe(r[a].expression,s)??r[a].receiverType??null:null])),functions:n,service:e,stack:new Set([t.name])})}function Kd(t){throw new Error(`Unhandled Rules expression: ${JSON.stringify(t)}`)}function Zd(t){return t.replace(/^\.\.\//,"_").replace(/^\.\//,"").replace(/[.\/-]/g,"_")}function re(t,e){switch(t.type){case"functionCall":{const n=e.get(t.name)??t.name,r=t.args.map(s=>re(s,e));return n===t.name&&r.every((s,i)=>s===t.args[i])?t:{...t,name:n,args:r}}case"binaryOp":{const n=re(t.left,e),r=re(t.right,e);return n===t.left&&r===t.right?t:{...t,left:n,right:r}}case"unaryOp":{const n=re(t.operand,e);return n===t.operand?t:{...t,operand:n}}case"methodCall":{const n=re(t.object,e),r=t.args.map(s=>re(s,e));return n===t.object&&r.every((s,i)=>s===t.args[i])?t:{...t,object:n,args:r}}case"memberAccess":{const n=re(t.object,e);return n===t.object?t:{...t,object:n}}case"bracketAccess":{const n=re(t.object,e),r=re(t.index,e);return n===t.object&&r===t.index?t:{...t,object:n,index:r}}case"sliceAccess":{const n=re(t.object,e),r=re(t.start,e),s=re(t.end,e);return n===t.object&&r===t.start&&s===t.end?t:{...t,object:n,start:r,end:s}}case"ternary":{const n=re(t.condition,e),r=re(t.consequent,e),s=re(t.alternate,e);return n===t.condition&&r===t.consequent&&s===t.alternate?t:{...t,condition:n,consequent:r,alternate:s}}case"inExpr":{const n=re(t.element,e),r=re(t.collection,e);return n===t.element&&r===t.collection?t:{...t,element:n,collection:r}}case"isExpr":{const n=re(t.value,e);return n===t.value?t:{...t,value:n}}case"listLiteral":{const n=t.elements.map(r=>re(r,e));return n.every((r,s)=>r===t.elements[s])?t:{...t,elements:n}}case"mapLiteral":{const n=t.entries.map(r=>{const s=re(r.key,e),i=re(r.value,e);return s===r.key&&i===r.value?r:{key:s,value:i}});return n.every((r,s)=>r===t.entries[s])?t:{...t,entries:n}}case"pathLiteral":{const n=t.segments.map(r=>typeof r=="string"?r:re(r,e));return n.every((r,s)=>r===t.segments[s])?t:{...t,segments:n}}case"literal":case"identifier":return t;default:return Kd(t)}}function Jd(t,e){const n=Zd(e),r=new Map;for(const s of t)s.exported||r.set(s.name,`${n}__${s.name}`);return r.size===0?t:t.map(s=>{const i=re(s.body,r),a=s.lets.map(c=>{const u=re(c.value,r);return u===c.value?c:{...c,value:u}}),o=s.exported?s.name:r.get(s.name)??s.name;return i===s.body&&a===s.lets&&o===s.name?s:{...s,name:o,body:i,lets:a}})}function Qd(t){throw new Error(`Unhandled Rules expression: ${JSON.stringify(t)}`)}function _i(t){const e=[],n=r=>{switch(r.type){case"functionCall":e.push(r),r.args.forEach(n);break;case"binaryOp":n(r.left),n(r.right);break;case"unaryOp":n(r.operand);break;case"methodCall":n(r.object),r.args.forEach(n);break;case"memberAccess":n(r.object);break;case"bracketAccess":n(r.object),n(r.index);break;case"sliceAccess":n(r.object),n(r.start),n(r.end);break;case"ternary":n(r.condition),n(r.consequent),n(r.alternate);break;case"inExpr":n(r.element),n(r.collection);break;case"isExpr":n(r.value);break;case"listLiteral":r.elements.forEach(n);break;case"mapLiteral":r.entries.forEach(({key:s,value:i})=>{n(s),n(i)});break;case"pathLiteral":r.segments.forEach(s=>{typeof s!="string"&&n(s)});break;case"literal":case"identifier":break;default:Qd(r)}};return n(t),e}function Yd(t){return{expression:t.expression,provenance:t.provenance,receiverType:!t.receiverType||t.receiverType==="mixed"?"unknown":t.receiverType}}function Xd(t,e){const n=[],r=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:r}),a=(l,p,y)=>{if(y.has(l.name))return;const b=r.get(l);if(!b)return;const w=new Map(b.aliases),R=new Map(b.receiverTypes);l.parameters.forEach((I,E)=>{w.set(I,p[E]?.provenance??null),R.set(I,p[E]?.receiverType??null)});const C=i({aliases:w,receiverTypes:R,functions:b.functions},new Set([...y,l.name]));for(const I of l.lets){o(I.value,C);const E=hn(I.value,C);C.aliases.set(I.name,E.provenance),C.receiverTypes.set(I.name,E.receiverType)}o(l.body,C)},o=(l,p)=>{for(const y of _i(l)){const b=y.args.map(R=>hn(R,p));y.name===e&&n.push({arguments:b.map(Yd)});const w=p.functions.get(y.name);w&&a(w,b,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??[])r.set(l,{aliases:new Map,receiverTypes:new Map,functions:c});for(const l of t.service.functions??[])r.set(l,{aliases:new Map,receiverTypes:new Map,functions:u});const d=(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 b=new Map(p.functions),w={aliases:p.aliases,receiverTypes:y,functions:b};for(const C of l.functions)b.set(C.name,C),r.set(C,w);const R=i(w);for(const{condition:C}of l.allows)o(C,R);l.children.forEach(C=>d(C,w))};return d(t.service.match,{aliases:new Map,receiverTypes:new Map,functions:u}),n}function Dt(t){return _i(t).map(({name:e})=>e)}function eh(t,e){return[...t.values()].flatMap(r=>[...r.lets.map(({value:s})=>s),r.body]).flatMap(_i).filter(({name:r})=>r===e).map(({args:r})=>r)}function th(t,e,n){const r=ql(t,e);return r===null?{success:!1,error:{code:"PARSE_FAILED",message:`Failed to parse module '${e}'`}}:{success:!0,functions:r,bundled:n}}function ua(t){return t.startsWith("./")||t.startsWith("../")}function Ms(t){return/^\.\/stdlib\/([A-Za-z0-9_-]+(?:\/[A-Za-z0-9_-]+)*)\.rules$/.exec(t)?.[1]??null}function nh(t,e,n,r=new Set){if(n?.modules&&Object.prototype.hasOwnProperty.call(n.modules,e))return th(n.modules[e],e,r.has(e));if(ua(e)&&n?.basePath){const i=`${n.basePath}/${e}${e.endsWith(".rules")?"":".rules"}`;if(!Ms(e))return{success:!1,error:{code:"UNKNOWN_MODULE",message:`Module '${e}' not found at ${i}`}}}return Ms(e)?{success:!1,error:{code:"UNKNOWN_MODULE",message:`Module '${e}' not found`}}:ua(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 rh(t,e,n,r=new Set){const s=hr(e);if(!s.ok){const{line:F,column:z,message:ee}=s.error;return{success:!1,error:{code:"PARSE_FAILED",message:`Failed to parse source at line ${F}, col ${z}: ${ee}`}}}const i=s.ast;let a="firestore.rules";const o=i.version==="2+modules";if(o&&(a="firestore.modules.rules"),n!==void 0&&n.sourceFile!==void 0&&n.sourceFile!==""&&(a=n.sourceFile),sh(i,a),o===!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 F=Ts(i),z=JSON.stringify(F.sourceMap);return{success:!0,data:{resolved:`${F.resolved}// @pyric-source-map: ${z}
|
|
470
|
+
`,modules:[],bundledModules:[],evidenceIds:[],sourceMap:F.sourceMap}}}const l=i.imports.find(F=>F.functions.length===0);if(l)return{success:!1,error:{code:"UNKNOWN_FUNCTION",message:`Import from '${l.module}' must request at least one function`}};const p=new Map,y=new Map,b=new Map,w=new Map,R=[],C=[],I=new Map;for(const F of i.imports){const z=nh(t,F.module,n,r);if(!z.success)return{success:!1,error:z.error};R.includes(F.module)||R.push(F.module),z.bundled&&!C.includes(F.module)&&C.push(F.module);const ee=new Set,Oe=z.functions.find(Z=>ee.has(Z.name)?!0:(ee.add(Z.name),!1));if(Oe)return{success:!1,error:{code:"DUPLICATE_FUNCTION",message:`Module '${F.module}' defines duplicate function '${Oe.name}'`}};const Y=z.functions.find(Z=>rr.has(Z.name));if(Y)return{success:!1,error:{code:"DUPLICATE_FUNCTION",message:`Function '${Y.name}' from module '${F.module}' conflicts with a Rules builtin`}};const Ve=new Set;for(const Z of z.functions)Z.exported||Ve.add(Z.name);I.set(F.module,Ve);const ts=Jd(z.functions,F.module),Bi=new Set;for(const Z of ts){if(Bi.has(Z.name))return{success:!1,error:{code:"DUPLICATE_FUNCTION",message:`Module '${F.module}' defines conflicting function name '${Z.name}'`}};Bi.add(Z.name)}const Mu=new Set(ts.filter(Z=>Z.exported).map(Z=>Z.name));for(const Z of ts){const Ft=w.get(Z.name);if(Ft&&Ft!==F.module)return{success:!1,error:{code:"DUPLICATE_FUNCTION",message:`Function '${Z.name}' from module '${F.module}' conflicts with module '${Ft}'`}};if(w.set(Z.name,F.module),y.set(Z.name,Z),Z.exported){if(p.has(Z.name)&&b.get(Z.name)!==F.module)return{success:!1,error:{code:"DUPLICATE_FUNCTION",message:`Function '${Z.name}' exported by both '${b.get(Z.name)}' and '${F.module}'`}};p.set(Z.name,Z),b.set(Z.name,F.module)}}for(const Z of F.functions){if(!Mu.has(Z))return{success:!1,error:{code:"UNKNOWN_FUNCTION",message:I.get(F.module)?.has(Z)?`Function '${Z}' in module '${F.module}' is not exported`:`Function '${Z}' not found in module '${F.module}'`}};if(i.service.name==="cloud.firestore"||i.service.name==="firebase.storage"){const Ft=z.bundled?jd(i.service.name,F.module,Z):null;if(Ft)return{success:!1,error:{code:"INCOMPATIBLE_FUNCTION",message:Ft}}}}}const E=new Set(i.imports.flatMap(F=>F.functions)),N=[],q=new Set,S=[],k={cycle:null};function _(F){if(k.cycle)return;const z=S.indexOf(F);if(z>=0){k.cycle=[...S.slice(z),F];return}if(q.has(F))return;const ee=y.get(F);if(!ee)return;S.push(F);const Oe=Dt(ee.body);for(const Y of ee.lets)Oe.push(...Dt(Y.value));for(const Y of Oe)y.has(Y)&&!rr.has(Y)&&_(Y);S.pop(),!k.cycle&&(q.add(F),N.push({...ee,exported:!1}))}for(const F of i.imports)for(const z of F.functions)_(z);if(k.cycle)return{success:!1,error:{code:"CIRCULAR_DEPENDENCY",message:`Recursive module function dependency: ${k.cycle.join(" -> ")}`}};for(const F of N){const z=w.get(F.name),Oe=[...F.lets.flatMap(({value:Y})=>Dt(Y)),...Dt(F.body)].find(Y=>{const Ve=w.get(Y);return Ve&&Ve!==z&&!E.has(Y)});if(Oe)return{success:!1,error:{code:"UNKNOWN_FUNCTION",message:`Function '${F.name}' in module '${z}' cannot call '${Oe}' from another module`}}}const v=new Set(N.map(F=>F.name)),A=new Map((i.functions??[]).map(F=>[F.name,F])),x=new Set((i.service.functions??[]).map(F=>F.name)),f=(F,z)=>F.flatMap(Dt).find(ee=>p.has(ee)&&!v.has(ee)&&!z.has(ee))??null,h=F=>F.flatMap(z=>[...z.lets.map(({value:ee})=>ee),z.body]),g=new Set(A.keys());let m=f(h(i.functions??[]),g);const j=new Set([...g,...x]);m??=f(h(i.service.functions??[]),j);const O=(F,z)=>{const ee=new Set([...z,...F.functions.map(Y=>Y.name)]),Oe=[...h(F.functions),...F.allows.map(({condition:Y})=>Y)];return f(Oe,ee)??F.children.map(Y=>O(Y,ee)).find(Boolean)??null};if(m??=O(i.service.match,j),m)return{success:!1,error:{code:"UNKNOWN_FUNCTION",message:`Source calls function '${m}' from module '${b.get(m)}' without importing it`}};const T=(F,z)=>{if(z.has(F.name))return!1;const ee=new Set([...z,F.name]);return[...F.lets.flatMap(({value:Y})=>Dt(Y)),...Dt(F.body)].some(Y=>{const Ve=A.get(Y);return Ve?T(Ve,ee):v.has(Y)||x.has(Y)})},D=[...A.values()].find(F=>T(F,new Set));if(D)return{success:!1,error:{code:"INCOMPATIBLE_FUNCTION",message:`Global function '${D.name}' cannot call a service-scoped function`}};if(i.service.name==="firebase.storage"||i.service.name==="cloud.firestore"){const F=new Map(N.map(z=>[z.name,z]));for(const z of N){const ee=[...Xd(i,z.name),...eh(F,z.name).map(Y=>({arguments:Y.map(Ve=>({expression:Ve,provenance:null,receiverType:"unknown"}))}))],Oe=ee.length>0?ee:[{arguments:[]}];for(const{arguments:Y}of Oe){const Ve=Gd(z,i.service.name,y,Y);if(Ve)return{success:!1,error:{code:"INCOMPATIBLE_FUNCTION",message:`Function '${z.name}' requires unsupported ${Ve} for service '${i.service.name}'`}}}}}const Q=new Set([...(i.functions??[]).map(F=>F.name),...(i.service.functions??[]).map(F=>F.name)]),Fe=F=>{F.functions.forEach(z=>Q.add(z.name)),F.children.forEach(Fe)};Fe(i.service.match);const Ge=[...Q].find(F=>rr.has(F));if(Ge)return{success:!1,error:{code:"DUPLICATE_FUNCTION",message:`Source function '${Ge}' conflicts with a Rules builtin`}};for(const F of N)if(Q.has(F.name))return{success:!1,error:{code:"DUPLICATE_FUNCTION",message:`Imported function '${F.name}' conflicts with a function defined in the source`}};i.service.functions=[...N,...i.service.functions??[]],i.version="2",i.imports=[];const rn=new Set,An=i.service.name==="firebase.storage"?"storage-rules#":"firestore-rules#";for(const F of C){const z=Ms(F)??F,ee=Ad[z]??[];for(const Oe of ee)Oe.startsWith(An)&&rn.add(Oe)}const St=Ts(i),Du=JSON.stringify(St.sourceMap);return{success:!0,data:{resolved:`${St.resolved}// @pyric-source-map: ${Du}
|
|
471
|
+
`,modules:R,bundledModules:C,evidenceIds:[...rn].sort(),sourceMap:St.sourceMap}}}function sh(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 pc(t,e,n,r,s){if(e===void 0)return;let a=e,o=1;n!==void 0&&(o=n);let u="firestore.rules";r!==void 0&&r!==""&&(u=r);let l;s!==void 0&&(l=s);const y="// @pyric-source-map: ",b=t.indexOf(y);if(b!==-1){const E=b+y.length,N=t.indexOf(`
|
|
472
|
+
`,E);let q="";N!==-1?q=t.slice(E,N).trim():q=t.slice(E).trim();try{const k=JSON.parse(q);if(Array.isArray(k)){for(const v of k)if(v.generatedLine===a){a=v.authoredLine,o=v.authoredCol,u=v.authoredFile,v.expression!==void 0&&(l=v.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 le=Symbol.for("pyric.RulesValue.NO_OP");class ne{field(e){return null}callMethod(e,n){return le}binaryOp(e,n){return le}}function ye(t,e){if(Object.is(t,e))return!0;if(t instanceof ne)return t.equals(e);if(e instanceof ne)return e.equals(t);if(t instanceof pe||e instanceof pe)return t instanceof pe&&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)=>ye(s,e[i]));if(!la(t)||!la(e))return!1;const n=Object.keys(t),r=Object.keys(e);return n.length!==r.length?!1:n.every(s=>s in e&&ye(t[s],e[s]))}function la(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}class pe{items;constructor(e){this.items=[];for(const n of e)this.items.some(r=>ye(r,n))||this.items.push(n)}hasOnly(e){const n=e instanceof pe?e.toArray():e;return this.items.every(r=>n.some(s=>ye(r,s)))}equals(e){return!(e instanceof pe)||e.items.length!==this.items.length?!1:this.items.every(n=>e.items.some(r=>ye(n,r)))}hasAll(e){const n=e instanceof pe?e.toArray():e;for(const r of n)if(!this.items.some(s=>ye(s,r)))return!1;return!0}hasAny(e){const n=e instanceof pe?e.toArray():e;for(const r of n)if(this.items.some(s=>ye(s,r)))return!0;return!1}size(){return this.items.length}toArray(){return[...this.items]}difference(e){const n=e.toArray(),r=[];for(const s of this.items)n.some(i=>ye(s,i))||r.push(s);return new pe(r)}union(e){const n=e.toArray();return new pe([...this.items,...n])}intersection(e){const n=e.toArray(),r=[];for(const s of this.items)n.some(i=>ye(s,i))&&r.push(s);return new pe(r)}}class Rn{before;after;constructor(e,n){this.before=e,this.after=n}addedKeys(){const e=[];for(const n of Object.keys(this.after))n in this.before||e.push(n);return new pe(e)}removedKeys(){const e=[];for(const n of Object.keys(this.before))n in this.after||e.push(n);return new pe(e)}changedKeys(){const e=[];for(const n of Object.keys(this.after))n in this.before&&!ye(this.before[n],this.after[n])&&e.push(n);return new pe(e)}affectedKeys(){const e=[],n=new Set([...Object.keys(this.before),...Object.keys(this.after)]);for(const r of n)(!(r in this.before)||!(r in this.after)||!ye(this.before[r],this.after[r]))&&e.push(r);return new pe(e)}unchangedKeys(){const e=[];for(const n of Object.keys(this.before))n in this.after&&ye(this.before[n],this.after[n])&&e.push(n);return new pe(e)}}const ih=/^\{([A-Za-z_][A-Za-z0-9_]*)\}$/;class st extends ne{typeName="path";segments;bindings;constructor(e,n={}){super(),this.segments=e,this.bindings=n}static fromString(e){const n=e.startsWith("/")?e.slice(1):e;return n.length===0?new st([]):new st(n.split("/"))}bind(e){const n=[],r={...this.bindings};for(const s of this.segments){const i=s.match(ih);if(!i){n.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);n.push(c),r[a]=c}else n.push(s)}return new st(n,r)}valueOf(){return NaN}toString(){return"/"+this.segments.join("/")}toJSON(){return{__type:"path",segments:[...this.segments]}}equals(e){if(!(e instanceof st)||this.segments.length!==e.segments.length)return!1;for(let n=0;n<this.segments.length;n++)if(this.segments[n]!==e.segments[n])return!1;return!0}field(e){if(/^\d+$/.test(e)){const n=Number(e);return n<0||n>=this.segments.length?null:this.segments[n]}return e in this.bindings?this.bindings[e]:null}callMethod(e,n){switch(e){case"bind":{const r=n[0];if(r==null||typeof r!="object"||Array.isArray(r)||r instanceof ne)throw new TypeError(`Path.bind() requires a Map argument, got ${r===null?"null":typeof r}`);return this.bind(r)}default:return le}}}class ce extends ne{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 ce?this.value===e.value:typeof e=="number"?this.value===e:!1}binaryOp(e,n){const r=n instanceof ce?n.value:typeof n=="number"?n:void 0;if(r===void 0)return le;const s=this.value;switch(e){case"+":return new ce(s+r);case"-":return new ce(s-r);case"*":return new ce(s*r);case"/":return new ce(s/r);case"%":return new ce(s%r);case"<":return s<r;case"<=":return s<=r;case">":return s>r;case">=":return s>=r;default:return le}}}class G extends Error{expr;constructor(e,n){super(e),this.expr=n,this.name="EvalError"}}class Ot extends G{constructor(e,n){super(e,n),this.name="UnsupportedError"}}class ah{entries=[];parents=[];frames=[];capture(e,n){const r=this.entries.length,s=this.parents.length>0?this.parents[this.parents.length-1]:null,i={source:ve(e),kind:e.type,parent:s};this.stampFrame(i),this.entries.push(i),this.parents.push(r);try{const a=n();return this.entries[r].value=a,a}catch(a){throw this.entries[r].error=a instanceof Error?a.message:String(a),a}finally{this.parents.pop()}}skip(e){const n=this.parents.length>0?this.parents[this.parents.length-1]:null,r={source:ve(e),kind:e.type,parent:n,skipped:!0};this.stampFrame(r),this.entries.push(r)}enterFrame(e){this.frames.push(e)}exitFrame(){this.frames.pop()}markEntryAsLetBinding(e,n){e<0||e>=this.entries.length||(this.entries[e].letBinding={name:n})}stampFrame(e){this.frames.length!==0&&(e.inlinedFrom={name:this.frames[this.frames.length-1]})}}function oh(t,e,n,r){const i=p=>p*Math.PI/180,a=i(t),o=i(n),c=i(n-t),u=i(r-e),d=Math.sin(c/2)**2+Math.cos(a)*Math.cos(o)*Math.sin(u/2)**2;return 6371e3*(2*Math.atan2(Math.sqrt(d),Math.sqrt(1-d)))}class ot extends ne{typeName="latlng";lat;lng;constructor(e,n){super(),this.lat=e,this.lng=n}valueOf(){return NaN}toString(){return`${this.lat},${this.lng}`}toJSON(){return{__type:"latlng",lat:this.lat,lng:this.lng}}equals(e){return e instanceof ot&&this.lat===e.lat&&this.lng===e.lng}callMethod(e,n){switch(e){case"latitude":return this.lat;case"longitude":return this.lng;case"distance":{const r=n[0];if(!(r instanceof ot))throw new TypeError(`latlng.distance() requires a LatLng argument, got ${typeof r}`);return oh(this.lat,this.lng,r.lat,r.lng)}default:return le}}}const un=1e9,da={w:10080*60,d:1440*60,h:3600,m:60,s:1};function ch(t,e){let n=t+Math.trunc(e/un),r=e%un;return n>0&&r<0?(n-=1,r+=un):n<0&&r>0&&(n+=1,r-=un),{seconds:n,nanos:r}}class we extends ne{typeName="duration";seconds;nanos;constructor(e,n){super();const r=ch(e,n);this.seconds=r.seconds,this.nanos=r.nanos}static fromValue(e,n){if(n in da)return new we(e*da[n],0);if(n==="ms"){const r=Math.trunc(e/1e3),s=e-r*1e3;return new we(r,s*1e6)}if(n==="ns"){const r=Math.trunc(e/un),s=e-r*un;return new we(r,s)}throw new Error(`Unknown duration unit '${n}' (expected one of: w, d, h, m, s, ms, ns)`)}static fromTime(e,n,r,s){return new we(e*3600+n*60+r,s)}static abs(e){return new we(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,n=Math.abs(this.seconds),r=Math.abs(this.nanos);return`${e?"-":""}${n}.${r.toString().padStart(9,"0")}s`}toJSON(){return{__type:"duration",seconds:this.seconds,nanos:this.nanos}}equals(e){return e instanceof we&&this.seconds===e.seconds&&this.nanos===e.nanos}callMethod(e,n){switch(e){case"seconds":return this.seconds;case"nanos":return this.nanos;default:return le}}binaryOp(e,n){if(!(n instanceof we))return le;switch(e){case"+":return new we(this.seconds+n.seconds,this.nanos+n.nanos);case"-":return new we(this.seconds-n.seconds,this.nanos-n.nanos);case"<":return this.compareTo(n)<0;case"<=":return this.compareTo(n)<=0;case">":return this.compareTo(n)>0;case">=":return this.compareTo(n)>=0;default:return le}}compareTo(e){return this.seconds!==e.seconds?this.seconds-e.seconds:this.nanos-e.nanos}}const ha=1e9,uh=864e5,is=86400;function lh(t,e){const n=Math.floor(e/ha);return{seconds:t+n,nanos:e-n*ha}}let xe=class dt extends ne{typeName="timestamp";seconds;nanos;constructor(e,n){super();const r=lh(e,n);this.seconds=r.seconds,this.nanos=r.nanos}static fromMillis(e){const n=Math.floor(e/1e3),r=e-n*1e3;return new dt(n,r*1e6)}static fromYMD(e,n,r){return dt.fromMillis(Date.UTC(e,n-1,r))}static fromIsoString(e){return dt.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(),n=this.nanos.toString().padStart(9,"0");return e.replace(/\.\d{3}Z$/,`.${n}Z`)}toJSON(){return{__type:"timestamp",seconds:this.seconds,nanos:this.nanos}}equals(e){return e instanceof dt&&this.seconds===e.seconds&&this.nanos===e.nanos}callMethod(e,n){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 r=this.asDate().getUTCDay();return r===0?7:r}case"dayOfYear":{const r=this.asDate(),s=Date.UTC(r.getUTCFullYear(),0,1);return Math.floor((this.toMillis()-s)/uh)+1}case"date":return dt.fromYMD(this.asDate().getUTCFullYear(),this.asDate().getUTCMonth()+1,this.asDate().getUTCDate());case"time":{const r=(this.seconds%is+is)%is,s=Math.floor(r/3600),i=Math.floor(r%3600/60),a=r%60;return we.fromTime(s,i,a,this.nanos)}default:return le}}asDate(){return new Date(this.toMillis())}binaryOp(e,n){if(n instanceof dt)switch(e){case"-":return new we(this.seconds-n.seconds,this.nanos-n.nanos);case"<":return this.compareTo(n)<0;case"<=":return this.compareTo(n)<=0;case">":return this.compareTo(n)>0;case">=":return this.compareTo(n)>=0;default:return le}if(n instanceof we)switch(e){case"+":return new dt(this.seconds+n.seconds,this.nanos+n.nanos);case"-":return new dt(this.seconds-n.seconds,this.nanos-n.nanos);default:return le}return le}compareTo(e){return this.seconds!==e.seconds?this.seconds-e.seconds:this.nanos-e.nanos}};const fa="0123456789ABCDEF";function dh(t){let e="";for(let n=0;n<t.length;n++){const r=t[n];e+=fa[r>>>4]+fa[r&15]}return e}function hh(t){let e="";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_")}function fh(t,e){const n=Math.min(t.length,e.length);for(let r=0;r<n;r++)if(t[r]!==e[r])return t[r]<e[r]?-1:1;return t.length===e.length?0:t.length<e.length?-1:1}let We=class kn extends ne{typeName="bytes";data;constructor(e){super(),this.data=e}static fromUtf8(e){return new kn(new TextEncoder().encode(e))}static fromHex(e){if(e.length%2!==0)throw new Error(`Invalid hex string length: ${e.length}`);const n=new Uint8Array(e.length/2);for(let r=0;r<n.length;r++)n[r]=parseInt(e.substr(r*2,2),16);return new kn(n)}size(){return this.data.length}toBase64(){return hh(this.data)}toHexString(){return dh(this.data)}valueOf(){return this.data.length}toString(){return this.toBase64()}toJSON(){return{__type:"bytes",base64:this.toBase64()}}equals(e){if(!(e instanceof kn)||this.data.length!==e.data.length)return!1;for(let n=0;n<this.data.length;n++)if(this.data[n]!==e.data[n])return!1;return!0}callMethod(e,n){switch(e){case"size":return this.size();case"toBase64":return this.toBase64();case"toHexString":return this.toHexString()}return le}binaryOp(e,n){if(!(n instanceof kn))return le;const r=fh(this.data,n.data);switch(e){case"<":return r<0;case"<=":return r<=0;case">":return r>0;case">=":return r>=0}return le}};function Nn(t){return t.replace(/\$\(database\)/g,"(default)").replace(/^\/databases\/\(default\)\/documents\//,"")}function js(t,e){const n=t.split("/").filter(Boolean);return{data:e,id:n.at(-1)??"",__name__:new st(["databases","(default)","documents",...n])}}function pa(t,e){const n=Nn(t);let r=e.mockDocuments.get(n);if(!r&&e.getDoc){const s=e.getDoc(n);s&&(e.mockDocuments.set(n,s),r=s)}if(r)return e.identitylessFunctionMocks?.has(n)?{data:r}:js(n,r);throw new G(`get() of non-existent document '${n}' (guard with exists() first)`)}function ma(t,e){const n=Nn(t);if(e.mockDocuments.has(n))return!0;if(e.getDoc){const r=e.getDoc(n);if(r)return e.mockDocuments.set(n,r),!0}return!1}var as={exports:{}};const ph={},mh=Object.freeze(Object.defineProperty({__proto__:null,default:ph},Symbol.toStringTag,{value:"Module"})),br=ju(mh);/**
|
|
473
|
+
* [js-md5]{@link https://github.com/emn178/js-md5}
|
|
474
|
+
*
|
|
475
|
+
* @namespace md5
|
|
476
|
+
* @version 0.8.3
|
|
477
|
+
* @author Chen, Yi-Cyuan [emn178@gmail.com]
|
|
478
|
+
* @copyright Chen, Yi-Cyuan 2014-2023
|
|
479
|
+
* @license MIT
|
|
480
|
+
*/var ga;function gh(){return ga||(ga=1,(function(t){(function(){var e="input is invalid type",n="finalize already called",r=typeof window=="object",s=r?window:{};s.JS_MD5_NO_WINDOW&&(r=!1);var i=!r&&typeof self=="object",a=!s.JS_MD5_NO_NODE_JS&&typeof process=="object"&&process.versions&&process.versions.node;a?s=Eo: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(""),d=[128,32768,8388608,-2147483648],l=[0,8,16,24],p=["hex","array","digest","buffer","arrayBuffer","base64"],y="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),b=[],w;if(c){var R=new ArrayBuffer(68);w=new Uint8Array(R),b=new Uint32Array(R)}var C=Array.isArray;(s.JS_MD5_NO_NODE_JS||!C)&&(C=function(f){return Object.prototype.toString.call(f)==="[object Array]"});var I=ArrayBuffer.isView;c&&(s.JS_MD5_NO_ARRAY_BUFFER_IS_VIEW||!I)&&(I=function(f){return typeof f=="object"&&f.buffer&&f.buffer.constructor===ArrayBuffer});var E=function(f){var h=typeof f;if(h==="string")return[f,!0];if(h!=="object"||f===null)throw new Error(e);if(c&&f.constructor===ArrayBuffer)return[new Uint8Array(f),!1];if(!C(f)&&!I(f))throw new Error(e);return[f,!1]},N=function(f){return function(h){return new v(!0).update(h)[f]()}},q=function(){var f=N("hex");a&&(f=S(f)),f.create=function(){return new v},f.update=function(m){return f.create().update(m)};for(var h=0;h<p.length;++h){var g=p[h];f[g]=N(g)}return f},S=function(f){var h=br,g=br.Buffer,m;g.from&&!s.JS_MD5_NO_BUFFER_FROM?m=g.from:m=function(O){return new g(O)};var j=function(O){if(typeof O=="string")return h.createHash("md5").update(O,"utf8").digest("hex");if(O==null)throw new Error(e);return O.constructor===ArrayBuffer&&(O=new Uint8Array(O)),C(O)||I(O)||O.constructor===g?h.createHash("md5").update(m(O)).digest("hex"):f(O)};return j},k=function(f){return function(h,g){return new A(h,!0).update(g)[f]()}},_=function(){var f=k("hex");f.create=function(m){return new A(m)},f.update=function(m,j){return f.create(m).update(j)};for(var h=0;h<p.length;++h){var g=p[h];f[g]=k(g)}return f};function v(f){if(f)b[0]=b[16]=b[1]=b[2]=b[3]=b[4]=b[5]=b[6]=b[7]=b[8]=b[9]=b[10]=b[11]=b[12]=b[13]=b[14]=b[15]=0,this.blocks=b,this.buffer8=w;else if(c){var h=new ArrayBuffer(68);this.buffer8=new Uint8Array(h),this.blocks=new Uint32Array(h)}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}v.prototype.update=function(f){if(this.finalized)throw new Error(n);var h=E(f);f=h[0];for(var g=h[1],m,j=0,O,T=f.length,D=this.blocks,Q=this.buffer8;j<T;){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(O=this.start;j<T&&O<64;++j)m=f.charCodeAt(j),m<128?Q[O++]=m:m<2048?(Q[O++]=192|m>>>6,Q[O++]=128|m&63):m<55296||m>=57344?(Q[O++]=224|m>>>12,Q[O++]=128|m>>>6&63,Q[O++]=128|m&63):(m=65536+((m&1023)<<10|f.charCodeAt(++j)&1023),Q[O++]=240|m>>>18,Q[O++]=128|m>>>12&63,Q[O++]=128|m>>>6&63,Q[O++]=128|m&63);else for(O=this.start;j<T&&O<64;++j)m=f.charCodeAt(j),m<128?D[O>>>2]|=m<<l[O++&3]:m<2048?(D[O>>>2]|=(192|m>>>6)<<l[O++&3],D[O>>>2]|=(128|m&63)<<l[O++&3]):m<55296||m>=57344?(D[O>>>2]|=(224|m>>>12)<<l[O++&3],D[O>>>2]|=(128|m>>>6&63)<<l[O++&3],D[O>>>2]|=(128|m&63)<<l[O++&3]):(m=65536+((m&1023)<<10|f.charCodeAt(++j)&1023),D[O>>>2]|=(240|m>>>18)<<l[O++&3],D[O>>>2]|=(128|m>>>12&63)<<l[O++&3],D[O>>>2]|=(128|m>>>6&63)<<l[O++&3],D[O>>>2]|=(128|m&63)<<l[O++&3]);else if(c)for(O=this.start;j<T&&O<64;++j)Q[O++]=f[j];else for(O=this.start;j<T&&O<64;++j)D[O>>>2]|=f[j]<<l[O++&3];this.lastByteIndex=O,this.bytes+=O-this.start,O>=64?(this.start=O-64,this.hash(),this.hashed=!0):this.start=O}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this},v.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var f=this.blocks,h=this.lastByteIndex;f[h>>>2]|=d[h&3],h>=56&&(this.hashed||this.hash(),f[0]=f[16],f[16]=f[1]=f[2]=f[3]=f[4]=f[5]=f[6]=f[7]=f[8]=f[9]=f[10]=f[11]=f[12]=f[13]=f[14]=f[15]=0),f[14]=this.bytes<<3,f[15]=this.hBytes<<3|this.bytes>>>29,this.hash()}},v.prototype.hash=function(){var f,h,g,m,j,O,T=this.blocks;this.first?(f=T[0]-680876937,f=(f<<7|f>>>25)-271733879<<0,m=(-1732584194^f&2004318071)+T[1]-117830708,m=(m<<12|m>>>20)+f<<0,g=(-271733879^m&(f^-271733879))+T[2]-1126478375,g=(g<<17|g>>>15)+m<<0,h=(f^g&(m^f))+T[3]-1316259209,h=(h<<22|h>>>10)+g<<0):(f=this.h0,h=this.h1,g=this.h2,m=this.h3,f+=(m^h&(g^m))+T[0]-680876936,f=(f<<7|f>>>25)+h<<0,m+=(g^f&(h^g))+T[1]-389564586,m=(m<<12|m>>>20)+f<<0,g+=(h^m&(f^h))+T[2]+606105819,g=(g<<17|g>>>15)+m<<0,h+=(f^g&(m^f))+T[3]-1044525330,h=(h<<22|h>>>10)+g<<0),f+=(m^h&(g^m))+T[4]-176418897,f=(f<<7|f>>>25)+h<<0,m+=(g^f&(h^g))+T[5]+1200080426,m=(m<<12|m>>>20)+f<<0,g+=(h^m&(f^h))+T[6]-1473231341,g=(g<<17|g>>>15)+m<<0,h+=(f^g&(m^f))+T[7]-45705983,h=(h<<22|h>>>10)+g<<0,f+=(m^h&(g^m))+T[8]+1770035416,f=(f<<7|f>>>25)+h<<0,m+=(g^f&(h^g))+T[9]-1958414417,m=(m<<12|m>>>20)+f<<0,g+=(h^m&(f^h))+T[10]-42063,g=(g<<17|g>>>15)+m<<0,h+=(f^g&(m^f))+T[11]-1990404162,h=(h<<22|h>>>10)+g<<0,f+=(m^h&(g^m))+T[12]+1804603682,f=(f<<7|f>>>25)+h<<0,m+=(g^f&(h^g))+T[13]-40341101,m=(m<<12|m>>>20)+f<<0,g+=(h^m&(f^h))+T[14]-1502002290,g=(g<<17|g>>>15)+m<<0,h+=(f^g&(m^f))+T[15]+1236535329,h=(h<<22|h>>>10)+g<<0,f+=(g^m&(h^g))+T[1]-165796510,f=(f<<5|f>>>27)+h<<0,m+=(h^g&(f^h))+T[6]-1069501632,m=(m<<9|m>>>23)+f<<0,g+=(f^h&(m^f))+T[11]+643717713,g=(g<<14|g>>>18)+m<<0,h+=(m^f&(g^m))+T[0]-373897302,h=(h<<20|h>>>12)+g<<0,f+=(g^m&(h^g))+T[5]-701558691,f=(f<<5|f>>>27)+h<<0,m+=(h^g&(f^h))+T[10]+38016083,m=(m<<9|m>>>23)+f<<0,g+=(f^h&(m^f))+T[15]-660478335,g=(g<<14|g>>>18)+m<<0,h+=(m^f&(g^m))+T[4]-405537848,h=(h<<20|h>>>12)+g<<0,f+=(g^m&(h^g))+T[9]+568446438,f=(f<<5|f>>>27)+h<<0,m+=(h^g&(f^h))+T[14]-1019803690,m=(m<<9|m>>>23)+f<<0,g+=(f^h&(m^f))+T[3]-187363961,g=(g<<14|g>>>18)+m<<0,h+=(m^f&(g^m))+T[8]+1163531501,h=(h<<20|h>>>12)+g<<0,f+=(g^m&(h^g))+T[13]-1444681467,f=(f<<5|f>>>27)+h<<0,m+=(h^g&(f^h))+T[2]-51403784,m=(m<<9|m>>>23)+f<<0,g+=(f^h&(m^f))+T[7]+1735328473,g=(g<<14|g>>>18)+m<<0,h+=(m^f&(g^m))+T[12]-1926607734,h=(h<<20|h>>>12)+g<<0,j=h^g,f+=(j^m)+T[5]-378558,f=(f<<4|f>>>28)+h<<0,m+=(j^f)+T[8]-2022574463,m=(m<<11|m>>>21)+f<<0,O=m^f,g+=(O^h)+T[11]+1839030562,g=(g<<16|g>>>16)+m<<0,h+=(O^g)+T[14]-35309556,h=(h<<23|h>>>9)+g<<0,j=h^g,f+=(j^m)+T[1]-1530992060,f=(f<<4|f>>>28)+h<<0,m+=(j^f)+T[4]+1272893353,m=(m<<11|m>>>21)+f<<0,O=m^f,g+=(O^h)+T[7]-155497632,g=(g<<16|g>>>16)+m<<0,h+=(O^g)+T[10]-1094730640,h=(h<<23|h>>>9)+g<<0,j=h^g,f+=(j^m)+T[13]+681279174,f=(f<<4|f>>>28)+h<<0,m+=(j^f)+T[0]-358537222,m=(m<<11|m>>>21)+f<<0,O=m^f,g+=(O^h)+T[3]-722521979,g=(g<<16|g>>>16)+m<<0,h+=(O^g)+T[6]+76029189,h=(h<<23|h>>>9)+g<<0,j=h^g,f+=(j^m)+T[9]-640364487,f=(f<<4|f>>>28)+h<<0,m+=(j^f)+T[12]-421815835,m=(m<<11|m>>>21)+f<<0,O=m^f,g+=(O^h)+T[15]+530742520,g=(g<<16|g>>>16)+m<<0,h+=(O^g)+T[2]-995338651,h=(h<<23|h>>>9)+g<<0,f+=(g^(h|~m))+T[0]-198630844,f=(f<<6|f>>>26)+h<<0,m+=(h^(f|~g))+T[7]+1126891415,m=(m<<10|m>>>22)+f<<0,g+=(f^(m|~h))+T[14]-1416354905,g=(g<<15|g>>>17)+m<<0,h+=(m^(g|~f))+T[5]-57434055,h=(h<<21|h>>>11)+g<<0,f+=(g^(h|~m))+T[12]+1700485571,f=(f<<6|f>>>26)+h<<0,m+=(h^(f|~g))+T[3]-1894986606,m=(m<<10|m>>>22)+f<<0,g+=(f^(m|~h))+T[10]-1051523,g=(g<<15|g>>>17)+m<<0,h+=(m^(g|~f))+T[1]-2054922799,h=(h<<21|h>>>11)+g<<0,f+=(g^(h|~m))+T[8]+1873313359,f=(f<<6|f>>>26)+h<<0,m+=(h^(f|~g))+T[15]-30611744,m=(m<<10|m>>>22)+f<<0,g+=(f^(m|~h))+T[6]-1560198380,g=(g<<15|g>>>17)+m<<0,h+=(m^(g|~f))+T[13]+1309151649,h=(h<<21|h>>>11)+g<<0,f+=(g^(h|~m))+T[4]-145523070,f=(f<<6|f>>>26)+h<<0,m+=(h^(f|~g))+T[11]-1120210379,m=(m<<10|m>>>22)+f<<0,g+=(f^(m|~h))+T[2]+718787259,g=(g<<15|g>>>17)+m<<0,h+=(m^(g|~f))+T[9]-343485551,h=(h<<21|h>>>11)+g<<0,this.first?(this.h0=f+1732584193<<0,this.h1=h-271733879<<0,this.h2=g-1732584194<<0,this.h3=m+271733878<<0,this.first=!1):(this.h0=this.h0+f<<0,this.h1=this.h1+h<<0,this.h2=this.h2+g<<0,this.h3=this.h3+m<<0)},v.prototype.hex=function(){this.finalize();var f=this.h0,h=this.h1,g=this.h2,m=this.h3;return u[f>>>4&15]+u[f&15]+u[f>>>12&15]+u[f>>>8&15]+u[f>>>20&15]+u[f>>>16&15]+u[f>>>28&15]+u[f>>>24&15]+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[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]},v.prototype.toString=v.prototype.hex,v.prototype.digest=function(){this.finalize();var f=this.h0,h=this.h1,g=this.h2,m=this.h3;return[f&255,f>>>8&255,f>>>16&255,f>>>24&255,h&255,h>>>8&255,h>>>16&255,h>>>24&255,g&255,g>>>8&255,g>>>16&255,g>>>24&255,m&255,m>>>8&255,m>>>16&255,m>>>24&255]},v.prototype.array=v.prototype.digest,v.prototype.arrayBuffer=function(){this.finalize();var f=new ArrayBuffer(16),h=new Uint32Array(f);return h[0]=this.h0,h[1]=this.h1,h[2]=this.h2,h[3]=this.h3,f},v.prototype.buffer=v.prototype.arrayBuffer,v.prototype.base64=function(){for(var f,h,g,m="",j=this.array(),O=0;O<15;)f=j[O++],h=j[O++],g=j[O++],m+=y[f>>>2]+y[(f<<4|h>>>4)&63]+y[(h<<2|g>>>6)&63]+y[g&63];return f=j[O],m+=y[f>>>2]+y[f<<4&63]+"==",m};function A(f,h){var g,m=E(f);if(f=m[0],m[1]){var j=[],O=f.length,T=0,D;for(g=0;g<O;++g)D=f.charCodeAt(g),D<128?j[T++]=D:D<2048?(j[T++]=192|D>>>6,j[T++]=128|D&63):D<55296||D>=57344?(j[T++]=224|D>>>12,j[T++]=128|D>>>6&63,j[T++]=128|D&63):(D=65536+((D&1023)<<10|f.charCodeAt(++g)&1023),j[T++]=240|D>>>18,j[T++]=128|D>>>12&63,j[T++]=128|D>>>6&63,j[T++]=128|D&63);f=j}f.length>64&&(f=new v(!0).update(f).array());var Q=[],Fe=[];for(g=0;g<64;++g){var Ge=f[g]||0;Q[g]=92^Ge,Fe[g]=54^Ge}v.call(this,h),this.update(Fe),this.oKeyPad=Q,this.inner=!0,this.sharedMemory=h}A.prototype=new v,A.prototype.finalize=function(){if(v.prototype.finalize.call(this),this.inner){this.inner=!1;var f=this.array();v.call(this,this.sharedMemory),this.update(this.oKeyPad),this.update(f),v.prototype.finalize.call(this)}};var x=q();x.md5=x,x.md5.hmac=_(),o?t.exports=x:s.md5=x})()})(as)),as.exports}var yh=gh(),os={exports:{}};/**
|
|
481
|
+
* [js-sha256]{@link https://github.com/emn178/js-sha256}
|
|
482
|
+
*
|
|
483
|
+
* @version 0.11.1
|
|
484
|
+
* @author Chen, Yi-Cyuan [emn178@gmail.com]
|
|
485
|
+
* @copyright Chen, Yi-Cyuan 2014-2025
|
|
486
|
+
* @license MIT
|
|
487
|
+
*/var ya;function bh(){return ya||(ya=1,(function(t){(function(){var e="input is invalid type",n=typeof window=="object",r=n?window:{};r.JS_SHA256_NO_WINDOW&&(n=!1);var s=!n&&typeof self=="object",i=!r.JS_SHA256_NO_NODE_JS&&typeof process=="object"&&process.versions&&process.versions.node&&process.type!="renderer";i?r=Eo:s&&(r=self);var a=!r.JS_SHA256_NO_COMMON_JS&&!0&&t.exports,o=!r.JS_SHA256_NO_ARRAY_BUFFER&&typeof ArrayBuffer<"u",c="0123456789abcdef".split(""),u=[-2147483648,8388608,32768,128],d=[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=[];(r.JS_SHA256_NO_NODE_JS||!Array.isArray)&&(Array.isArray=function(S){return Object.prototype.toString.call(S)==="[object Array]"}),o&&(r.JS_SHA256_NO_ARRAY_BUFFER_IS_VIEW||!ArrayBuffer.isView)&&(ArrayBuffer.isView=function(S){return typeof S=="object"&&S.buffer&&S.buffer.constructor===ArrayBuffer});var b=function(S,k){return function(_){return new E(k,!0).update(_)[S]()}},w=function(S){var k=b("hex",S);i&&(k=R(k,S)),k.create=function(){return new E(S)},k.update=function(A){return k.create().update(A)};for(var _=0;_<p.length;++_){var v=p[_];k[v]=b(v,S)}return k},R=function(S,k){var _=br,v=br.Buffer,A=k?"sha224":"sha256",x;v.from&&!r.JS_SHA256_NO_BUFFER_FROM?x=v.from:x=function(h){return new v(h)};var f=function(h){if(typeof h=="string")return _.createHash(A).update(h,"utf8").digest("hex");if(h==null)throw new Error(e);return h.constructor===ArrayBuffer&&(h=new Uint8Array(h)),Array.isArray(h)||ArrayBuffer.isView(h)||h.constructor===v?_.createHash(A).update(x(h)).digest("hex"):S(h)};return f},C=function(S,k){return function(_,v){return new N(_,k,!0).update(v)[S]()}},I=function(S){var k=C("hex",S);k.create=function(A){return new N(A,S)},k.update=function(A,x){return k.create(A).update(x)};for(var _=0;_<p.length;++_){var v=p[_];k[v]=C(v,S)}return k};function E(S,k){k?(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}E.prototype.update=function(S){if(!this.finalized){var k,_=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);k=!0}for(var v,A=0,x,f=S.length,h=this.blocks;A<f;){if(this.hashed&&(this.hashed=!1,h[0]=this.block,this.block=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),k)for(x=this.start;A<f&&x<64;++A)h[x>>>2]|=S[A]<<d[x++&3];else for(x=this.start;A<f&&x<64;++A)v=S.charCodeAt(A),v<128?h[x>>>2]|=v<<d[x++&3]:v<2048?(h[x>>>2]|=(192|v>>>6)<<d[x++&3],h[x>>>2]|=(128|v&63)<<d[x++&3]):v<55296||v>=57344?(h[x>>>2]|=(224|v>>>12)<<d[x++&3],h[x>>>2]|=(128|v>>>6&63)<<d[x++&3],h[x>>>2]|=(128|v&63)<<d[x++&3]):(v=65536+((v&1023)<<10|S.charCodeAt(++A)&1023),h[x>>>2]|=(240|v>>>18)<<d[x++&3],h[x>>>2]|=(128|v>>>12&63)<<d[x++&3],h[x>>>2]|=(128|v>>>6&63)<<d[x++&3],h[x>>>2]|=(128|v&63)<<d[x++&3]);this.lastByteIndex=x,this.bytes+=x-this.start,x>=64?(this.block=h[16],this.start=x-64,this.hash(),this.hashed=!0):this.start=x}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}},E.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var S=this.blocks,k=this.lastByteIndex;S[16]=this.block,S[k>>>2]|=u[k&3],this.block=S[16],k>=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()}},E.prototype.hash=function(){var S=this.h0,k=this.h1,_=this.h2,v=this.h3,A=this.h4,x=this.h5,f=this.h6,h=this.h7,g=this.blocks,m,j,O,T,D,Q,Fe,Ge,rn,An,St;for(m=16;m<64;++m)D=g[m-15],j=(D>>>7|D<<25)^(D>>>18|D<<14)^D>>>3,D=g[m-2],O=(D>>>17|D<<15)^(D>>>19|D<<13)^D>>>10,g[m]=g[m-16]+j+g[m-7]+O<<0;for(St=k&_,m=0;m<64;m+=4)this.first?(this.is224?(Ge=300032,D=g[0]-1413257819,h=D-150054599<<0,v=D+24177077<<0):(Ge=704751109,D=g[0]-210244248,h=D-1521486534<<0,v=D+143694565<<0),this.first=!1):(j=(S>>>2|S<<30)^(S>>>13|S<<19)^(S>>>22|S<<10),O=(A>>>6|A<<26)^(A>>>11|A<<21)^(A>>>25|A<<7),Ge=S&k,T=Ge^S&_^St,Fe=A&x^~A&f,D=h+O+Fe+l[m]+g[m],Q=j+T,h=v+D<<0,v=D+Q<<0),j=(v>>>2|v<<30)^(v>>>13|v<<19)^(v>>>22|v<<10),O=(h>>>6|h<<26)^(h>>>11|h<<21)^(h>>>25|h<<7),rn=v&S,T=rn^v&k^Ge,Fe=h&A^~h&x,D=f+O+Fe+l[m+1]+g[m+1],Q=j+T,f=_+D<<0,_=D+Q<<0,j=(_>>>2|_<<30)^(_>>>13|_<<19)^(_>>>22|_<<10),O=(f>>>6|f<<26)^(f>>>11|f<<21)^(f>>>25|f<<7),An=_&v,T=An^_&S^rn,Fe=f&h^~f&A,D=x+O+Fe+l[m+2]+g[m+2],Q=j+T,x=k+D<<0,k=D+Q<<0,j=(k>>>2|k<<30)^(k>>>13|k<<19)^(k>>>22|k<<10),O=(x>>>6|x<<26)^(x>>>11|x<<21)^(x>>>25|x<<7),St=k&_,T=St^k&v^An,Fe=x&f^~x&h,D=A+O+Fe+l[m+3]+g[m+3],Q=j+T,A=S+D<<0,S=D+Q<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+S<<0,this.h1=this.h1+k<<0,this.h2=this.h2+_<<0,this.h3=this.h3+v<<0,this.h4=this.h4+A<<0,this.h5=this.h5+x<<0,this.h6=this.h6+f<<0,this.h7=this.h7+h<<0},E.prototype.hex=function(){this.finalize();var S=this.h0,k=this.h1,_=this.h2,v=this.h3,A=this.h4,x=this.h5,f=this.h6,h=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[k>>>28&15]+c[k>>>24&15]+c[k>>>20&15]+c[k>>>16&15]+c[k>>>12&15]+c[k>>>8&15]+c[k>>>4&15]+c[k&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[v>>>28&15]+c[v>>>24&15]+c[v>>>20&15]+c[v>>>16&15]+c[v>>>12&15]+c[v>>>8&15]+c[v>>>4&15]+c[v&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[x>>>28&15]+c[x>>>24&15]+c[x>>>20&15]+c[x>>>16&15]+c[x>>>12&15]+c[x>>>8&15]+c[x>>>4&15]+c[x&15]+c[f>>>28&15]+c[f>>>24&15]+c[f>>>20&15]+c[f>>>16&15]+c[f>>>12&15]+c[f>>>8&15]+c[f>>>4&15]+c[f&15];return this.is224||(g+=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]),g},E.prototype.toString=E.prototype.hex,E.prototype.digest=function(){this.finalize();var S=this.h0,k=this.h1,_=this.h2,v=this.h3,A=this.h4,x=this.h5,f=this.h6,h=this.h7,g=[S>>>24&255,S>>>16&255,S>>>8&255,S&255,k>>>24&255,k>>>16&255,k>>>8&255,k&255,_>>>24&255,_>>>16&255,_>>>8&255,_&255,v>>>24&255,v>>>16&255,v>>>8&255,v&255,A>>>24&255,A>>>16&255,A>>>8&255,A&255,x>>>24&255,x>>>16&255,x>>>8&255,x&255,f>>>24&255,f>>>16&255,f>>>8&255,f&255];return this.is224||g.push(h>>>24&255,h>>>16&255,h>>>8&255,h&255),g},E.prototype.array=E.prototype.digest,E.prototype.arrayBuffer=function(){this.finalize();var S=new ArrayBuffer(this.is224?28:32),k=new DataView(S);return k.setUint32(0,this.h0),k.setUint32(4,this.h1),k.setUint32(8,this.h2),k.setUint32(12,this.h3),k.setUint32(16,this.h4),k.setUint32(20,this.h5),k.setUint32(24,this.h6),this.is224||k.setUint32(28,this.h7),S};function N(S,k,_){var v,A=typeof S;if(A==="string"){var x=[],f=S.length,h=0,g;for(v=0;v<f;++v)g=S.charCodeAt(v),g<128?x[h++]=g:g<2048?(x[h++]=192|g>>>6,x[h++]=128|g&63):g<55296||g>=57344?(x[h++]=224|g>>>12,x[h++]=128|g>>>6&63,x[h++]=128|g&63):(g=65536+((g&1023)<<10|S.charCodeAt(++v)&1023),x[h++]=240|g>>>18,x[h++]=128|g>>>12&63,x[h++]=128|g>>>6&63,x[h++]=128|g&63);S=x}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 E(k,!0).update(S).array());var m=[],j=[];for(v=0;v<64;++v){var O=S[v]||0;m[v]=92^O,j[v]=54^O}E.call(this,k,_),this.update(j),this.oKeyPad=m,this.inner=!0,this.sharedMemory=_}N.prototype=new E,N.prototype.finalize=function(){if(E.prototype.finalize.call(this),this.inner){this.inner=!1;var S=this.array();E.call(this,this.is224,this.sharedMemory),this.update(this.oKeyPad),this.update(S),E.prototype.finalize.call(this)}};var q=w();q.sha256=q,q.sha224=w(!0),q.sha256.hmac=I(),q.sha224.hmac=I(!0),a?t.exports=q:(r.sha256=q.sha256,r.sha224=q.sha224)})()})(os)),os.exports}var vh=bh();function wh(t){if(t instanceof We)return t;if(typeof t=="string")return We.fromUtf8(t);throw new G(`hashing.* requires Bytes or String, got ${typeof t}`)}function Sh(t,e){const n=wh(e[0]);switch(t){case"md5":return new We(new Uint8Array(yh.md5.arrayBuffer(n.data)));case"sha256":return new We(new Uint8Array(vh.sha256.arrayBuffer(n.data)));case"crc32":{const r=Ah(n.data);return new We(ba(r))}case"crc32c":{const r=Ih(n.data);return new We(ba(r))}}throw new Ot(`Unknown hashing method '${t}'`)}function ba(t){return new Uint8Array([t&255,t>>>8&255,t>>>16&255,t>>>24&255])}const _h=(()=>{const t=new Uint32Array(256);for(let e=0;e<256;e++){let n=e;for(let r=0;r<8;r++)n=n&1?3988292384^n>>>1:n>>>1;t[e]=n>>>0}return t})();function Ah(t){let e=4294967295;for(let n=0;n<t.length;n++)e=_h[(e^t[n])&255]^e>>>8;return(e^4294967295)>>>0}const xh=(()=>{const t=new Uint32Array(256);for(let e=0;e<256;e++){let n=e;for(let r=0;r<8;r++)n=n&1?2197175160^n>>>1:n>>>1;t[e]=n>>>0}return t})();function Ih(t){let e=4294967295;for(let n=0;n<t.length;n++)e=xh[(e^t[n])&255]^e>>>8;return(e^4294967295)>>>0}function Eh(t){if(typeof t=="number")return Math.trunc(t);if(t instanceof ce)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 kh(t){if(t instanceof ce)return t;if(typeof t=="number")return new ce(t);if(typeof t=="string"){const e=t.trim();if(/^[+-]?(\d+\.?\d*|\.\d+)$/.test(e))return new ce(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 Oh(t,e,n,r){switch(t){case"get":{const a=String(H(e[0],n,r));return pa(a,n)}case"exists":{const a=String(H(e[0],n,r));return ma(a,n)}case"getAfter":{const a=H(e[0],n,r),o=String(a);if(o===n.afterStatePath.toString()){if(n.afterState===null)throw new G(`getAfter() of non-existent document '${o}' (guard with existsAfter() first)`);return js(Nn(o),n.afterState)}const c=Nn(o);if(n.batchProjection?.has(c)){const u=n.batchProjection.get(c);if(u===null)throw new G(`getAfter() of non-existent document '${o}' (guard with existsAfter() first)`);return js(c,u)}return pa(o,n)}case"existsAfter":{const a=H(e[0],n,r),o=String(a);if(o===n.afterStatePath.toString())return n.existsAfter;const c=Nn(o);return n.batchProjection?.has(c)?n.batchProjection.get(c)!==null:ma(o,n)}case"debug":return H(e[0],n,r);case"string":return String(H(e[0],n,r));case"int":return Eh(H(e[0],n,r));case"float":return kh(H(e[0],n,r));case"path":{const a=H(e[0],n,r);if(typeof a=="string")return st.fromString(a);throw new G(`path() requires a string argument, got ${typeof a}`)}}const s=n.functions.get(t);if(!s)throw new G(`Unknown function: ${t}`);const i={...r};for(let a=0;a<s.parameters.length;a++)i[s.parameters[a]]=H(e[a],n,r);n.trace?.enterFrame(t);try{for(const a of s.lets){const o=n.trace?n.trace.entries.length:-1;i[a.name]=H(a.value,n,i),o>=0&&n.trace?.markEntryAsLetBinding(o,a.name)}return H(s.body,n,i)}finally{n.trace?.exitFrame()}}function Ch(t,e,n,r,s){if(t.type==="identifier"){const o=t.name;if(va(o)&&!(o in s)&&!(o in r.pathVariables)){const c=n.map(u=>H(u,r,s));return Rh(o,e,c)}if(!va(o)&&!(o in s)&&!(o in r.pathVariables)&&!Ph(o))throw new Ot(`Unknown namespace or method '${o}.${e}()'`)}const i=H(t,r,s),a=n.map(o=>H(o,r,s));if(i instanceof ne){const o=i.callMethod(e,a);if(o===le)throw new Ot(`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 Rn(o,i);throw new G("diff() requires a map argument")}if(typeof i=="function")return i(...a);if(i instanceof pe)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 pe))throw new G(`Unsupported operation: set.${e} requires a Set argument`);return i[e](o)}}if(i instanceof Rn)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 Rn(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 ne)return u;const y=String(p);if(!Object.hasOwn(l,y))return u;l=l[y]}return l}const d=String(c);return Object.hasOwn(o,d)?o[d]:u}}}if(Array.isArray(i))switch(e){case"size":return i.length;case"hasAll":return a[0].every(o=>i.some(c=>ye(c,o)));case"hasAny":return a[0].some(o=>i.some(c=>ye(c,o)));case"hasOnly":{const o=a[0];return i.every(c=>o.some(u=>ye(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=>ye(c,u)))}case"toSet":return new pe(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(cs(String(a[0]),"g"));case"matches":return cs(`^(?:${String(a[0])})$`).test(i);case"replace":return i.replace(cs(String(a[0]),"g"),String(a[1]));case"toUtf8":return We.fromUtf8(i)}throw new G(`Unknown method '${e}' on ${typeof i}`)}function cs(t,e=""){try{return new RegExp(t,e)}catch(n){throw new G(`Invalid regex '${t}': ${n.message}`)}}const Th=new Set(["math","timestamp","duration","latlng","hashing"]);function va(t){return Th.has(t)}function Rh(t,e,n){const r=t==="hashing"?n:n.map(Nh);switch(t){case"math":return Fh(e,r);case"timestamp":return Dh(e,r);case"duration":return Mh(e,r);case"latlng":return Lh(e,r);case"hashing":return Sh(e,n)}throw new Ot(`Unknown namespace '${t}'`)}function Nh(t){return t instanceof ce?t.value:t}function Lh(t,e){switch(t){case"value":{const[n,r]=e;return new ot(n,r)}}throw new Ot(`Unknown latlng method '${t}'`)}function Fh(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 Dh(t,e){switch(t){case"date":{const[n,r,s]=e;return xe.fromYMD(n,r,s)}case"value":return xe.fromMillis(e[0])}throw new Ot(`Unknown timestamp method '${t}'`)}function Mh(t,e){switch(t){case"value":try{return we.fromValue(e[0],e[1])}catch(n){throw new G(n.message)}case"time":{const[n,r,s,i]=e;return we.fromTime(n,r,s,i)}case"abs":{const n=e[0];if(!(n instanceof we))throw new G(`duration.abs() requires a Duration argument, got ${typeof n}`);return we.abs(n)}}throw new Ot(`Unknown duration method '${t}'`)}function H(t,e,n={}){return e.trace?e.trace.capture(t,()=>wa(t,e,n)):wa(t,e,n)}function wa(t,e,n){switch(t.type){case"literal":return typeof t.value=="number"&&t.raw.includes(".")?new ce(t.value):t.value;case"identifier":return jh(t.name,e,n);case"binaryOp":return $h(t.op,t.left,t.right,e,n);case"unaryOp":{if(t.op==="!")return!H(t.operand,e,n);if(t.op==="-"){const r=H(t.operand,e,n);return r instanceof ce?new ce(-r.value):-r}throw new G(`Unknown unary op: ${t.op}`,t)}case"ternary":{const r=On(H(t.condition,e,n),t.condition);return H(r?t.consequent:t.alternate,e,n)}case"memberAccess":{const r=H(t.object,e,n);if(r==null)throw new G(`Property '${t.property}' accessed on ${r===null?"null":"undefined"} value`,t);if(r instanceof ne)return r.field(t.property);if(r instanceof Rn)switch(t.property){case"addedKeys":return()=>r.addedKeys();case"removedKeys":return()=>r.removedKeys();case"changedKeys":return()=>r.changedKeys();case"affectedKeys":return()=>r.affectedKeys();case"unchangedKeys":return()=>r.unchangedKeys()}if(r instanceof pe)switch(t.property){case"size":return()=>r.size()}if(Object.hasOwn(r,t.property))return r[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 r=H(t.object,e,n),s=H(t.index,e,n);if(r==null)throw new G(`Index access on ${r===null?"null":"undefined"} value`,t);if(r instanceof ne)return r.field(String(s));const i=String(s);return Object.hasOwn(r,i)?r[i]:null}case"sliceAccess":{const r=H(t.object,e,n),s=H(t.start,e,n),i=H(t.end,e,n);if(r==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 r=="string"||Array.isArray(r)){if(i>r.length)throw new G(`Slice end ${i} exceeds length ${r.length}`);return r.slice(s,i)}throw new G(`Slice not supported on ${typeof r}`)}case"inExpr":{const r=H(t.element,e,n),s=H(t.collection,e,n);return s==null?!1:Array.isArray(s)?s.some(i=>ye(i,r)):typeof s=="object"?Object.hasOwn(s,String(r)):!1}case"isExpr":{const r=H(t.value,e,n);switch(t.typeName){case"string":return typeof r=="string";case"int":return r instanceof ne?!1:typeof r=="number";case"float":return r instanceof ce;case"number":return r instanceof ce?!0:r instanceof ne?!1:typeof r=="number";case"bool":return typeof r=="boolean";case"null":return r===null;case"list":return Array.isArray(r);case"map":return r instanceof ne||r instanceof Rn||r instanceof pe?!1:typeof r=="object"&&r!==null&&!Array.isArray(r);default:return r instanceof ne?r.typeName===t.typeName:!1}}case"listLiteral":return t.elements.map(r=>H(r,e,n));case"mapLiteral":{const r={};for(const s of t.entries){const i=String(H(s.key,e,n));r[i]=H(s.value,e,n)}return r}case"functionCall":return Oh(t.name,t.args,e,n);case"methodCall":return Ch(t.object,t.method,t.args,e,n);case"pathLiteral":{const r=[];for(const s of t.segments)typeof s=="string"?r.push(s):r.push(String(H(s,e,n)));return new st(r)}default:throw new G(`Unknown expression type: ${t.type}`,t)}}function jh(t,e,n){if(t in n)return n[t];if(t in e.pathVariables)return e.pathVariables[t];switch(t){case"request":return e.request;case"resource":if(e.resource===null)throw new 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 Ph(t){return t==="request"||t==="resource"||t==="true"||t==="false"||t==="null"}function $h(t,e,n,r,s){if(t==="&&"){let o,c;try{o=On(H(e,r,s),e)}catch(l){c=l}if(c===void 0&&o===!1)return r.trace?.skip(n),!1;let u,d;try{u=On(H(n,r,s),n)}catch(l){d=l}if(d===void 0&&u===!1)return!1;if(c!==void 0)throw c;if(d!==void 0)throw d;return u}if(t==="||"){let o,c;try{o=On(H(e,r,s),e)}catch(l){c=l}if(c===void 0&&o===!0)return r.trace?.skip(n),!0;let u,d;try{u=On(H(n,r,s),n)}catch(l){d=l}if(d===void 0&&u===!0)return!0;if(c!==void 0)throw c;if(d!==void 0)throw d;return u}const i=H(e,r,s),a=H(n,r,s);if(t!=="=="&&t!=="!="){if(i instanceof ne){const o=i.binaryOp(t,a);if(o!==le)return o}if(typeof i=="number"&&a instanceof ce){const o=new ce(i).binaryOp(t,a);if(o!==le)return o}if(a instanceof ne&&(t==="+"||t==="*")){const o=a.binaryOp(t,i);if(o!==le)return o}if((t!=="+"||typeof i!="string"&&typeof a!="string")&&(i instanceof ne||a instanceof ne)){const o=i instanceof ne?i.typeName:typeof i,c=a instanceof ne?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||ye(i,a);case"!=":return!(i===a||ye(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 ne)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 On(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 qh=new Set(["__proto__","prototype","constructor"]);function vr(t){if(qh.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 mc(t,e){const n={...t};for(const[r,s]of Object.entries(e)){vr(r);const i=Object.hasOwn(n,r)?n[r]:void 0;s!==null&&typeof s=="object"&&!Array.isArray(s)&&i!==null&&typeof i=="object"&&!Array.isArray(i)?n[r]=mc(i,s):n[r]=s}return n}function Uh(t,e,n){let r=t;for(let i=0;i<e.length-1;i++){const a=e[i];vr(a);const o=Object.hasOwn(r,a)?r[a]:void 0;(o===null||typeof o!="object"||Array.isArray(o))&&(r[a]={}),r=r[a]}const s=e[e.length-1];vr(s),r[s]=n}function Bh(t,e){const n={...t};for(const[r,s]of Object.entries(e))r.includes(".")?Uh(n,r.split("."),s):(vr(r),n[r]=s);return n}function zh(t,e,n){switch(t.kind){case"create":return n;case"set":return t.merge?mc(e??{},n):n;case"update":return Bh(e??{},n);case"delete":return null}}function gc(t){if(t===null||typeof t!="object"||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function Vh(t){return typeof t=="object"&&t!==null&&t.__type==="serverTimestamp"}function yc(t,e){const n={};for(const[r,s]of Object.entries(t))Vh(s)?n[r]=e:gc(s)?n[r]=yc(s,e):n[r]=s;return n}function Pt(t){return typeof t=="number"&&!Number.isInteger(t)?new ce(t):Array.isArray(t)?t.map(Pt):gc(t)?t.__type==="float"&&typeof t.value=="number"?new ce(t.value):Object.fromEntries(Object.entries(t).map(([e,n])=>[e,Pt(n)])):t}function Sa(t){if(t.method==="list")return{limit:t.query?.limit??null,offset:t.query?.offset??null,orderBy:t.query?.orderBy??null}}function sr(t){return`/${t.path.segments.map(n=>n.type==="literal"?n.value:n.type==="wildcard"?`{${n.name}}`:`{${n.name}=**}`).join("/")}`}function wr(t,e,n,r){const s=[...n,...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 r?.push({...t.loc?{line:t.loc.line}:{},blockPath:sr(t),matchedSegments:c,totalSegments:i.length,bindings:a,matched:!1,reason:u}),[];const d=e.slice(c);if(d.length===0)return r?.push({...t.loc?{line:t.loc.line}:{},blockPath:sr(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 wr(p,d,s,r))y.pathVariables={...a,...y.pathVariables},y.candidateVariables=[...o,...y.candidateVariables],l.push(y);return r?.push({...t.loc?{line:t.loc.line}:{},blockPath:sr(t),matchedSegments:c,totalSegments:i.length,bindings:a,...l.length>0?{matched:!0}:{matched:!1,reason:"no-matching-child"}}),l}class Wh{attempts=[];push(e){this.attempts.push(e)}}function Hh(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 Gh(t,e,n,r){const s=Hh(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 d=n.trace;for(const{rule:p,index:y}of o){const b=Kh(p,y,r),w=new ah;n.trace=w;try{const R=H(p.condition,n);if(b.expressionTrace=w.entries,!!R)return b.verdict="ALLOW",i.push(b),n.trace=d,{decision:"ALLOW",trace:i,notes:a};b.verdict="DENY",i.push(b)}catch(R){b.expressionTrace=w.entries,R instanceof Ot?(u=!0,b.verdict="UNSUPPORTED",b.message=R.message):(b.verdict="ERROR",R instanceof Error?b.message=R.message:b.message=String(R)),i.push(b)}}n.trace=d;let l="DENY";return u&&(l="UNSUPPORTED"),{decision:l,trace:i,notes:a}}function Kh(t,e,n){const r=ve(t.condition),s={ruleIndex:e,operations:[...t.operations],verdict:"DENY",conditionText:r};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}`),n!==void 0){const u=pc(n,a.line,a.col,a.file,r);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 Zh(t,e,n,r,s){const i=new Map;for(const I of e)i.set(I.name,I);const a=new Map,o=new Set;if(t.functionMocks)for(const I of t.functionMocks)I.function==="get"&&typeof I.result=="object"&&I.result!==null?(a.set(I.path,Pt(I.result)),o.add(I.path)):I.function==="exists"&&I.result===!0&&(a.set(I.path,{}),o.add(I.path));const c=t.requestTime?xe.fromIsoString(t.requestTime):xe.fromMillis(Date.now()),d=["databases","(default)","documents",...(t.path.startsWith("/")?t.path.slice(1):t.path).split("/").filter(Boolean)],l=new st(d,n),p=Pt(t.data??{}),y=t.resource===void 0||t.resource===null?null:Pt(t.resource);let b,w;if(t.writeMode)b=zh(t.writeMode,y,p),w=b!==null;else switch(t.method){case"create":case"update":b=p,w=!0;break;case"delete":b=null,w=!1;break;case"get":case"list":default:b=y,w=y!==null;break}const R=b!==null?Pt(yc(b,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,...Sa(t)?{query:Sa(t)}:{},time:c},resource:t.method==="create"||y===null?null:{data:Pt(y)},mockDocuments:a,identitylessFunctionMocks:o,getDoc:r,pathVariables:n,functions:i,database:"(default)",afterStatePath:l,afterState:R,existsAfter:w,...s?{batchProjection:s}:{}}}class Jh{simulate(e,n,r){if(!e||e.trim().length===0)return{success:!1,error:{code:"PARSE_FAILED",message:"Empty rules source — call setRules(sandbox, rules) from pyric/sandbox/firestore before operating, or initialize without rules to use the open-by-default ruleset. See pyric/sandbox docs.",recoverable:!0}};const s=wi(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 d of s.service.match.path.segments)d.type==="wildcard"&&(u[d.name]="(default)");for(const d of n){const l=d.path.split("/").filter(Boolean),p=[...s.functions??[],...s.service.functions??[],...s.service.match.functions];let y=[];const b=new Wh;for(const h of s.service.match.children)y.push(...wr(h,l,p,b));let w=!1;const R=y.length===0,C=d.method==="list";if(R&&C){const h=[...l,"__hypothetical_doc__"];for(const m of s.service.match.children)y.push(...wr(m,h,p,b));y.length>0&&(w=!0)}const I={requestPath:d.path,attempts:b.attempts};if(y.length===0){const h=d.expectation==="DENY"?"PASSED":"FAILED";h==="PASSED"?a++:o++,i.push({description:d.description,expectation:d.expectation,state:h,decision:"DENY",trace:[],notes:[`No match block found for path '${d.path}'`],pathResolution:I});continue}let N="DENY";const q=[],S=[];let k=!1,_;for(const h of y){const g={...u,...h.pathVariables},m=Zh(d,h.functions,g,r?.getDoc,r?.batchProjection),j=sr(h.block),O=Gh(h.block,d.method,m,e);for(const Q of O.trace)Q.matchPath=j;if(q.push(...O.trace),S.push(...O.notes),O.decision==="ALLOW"){N="ALLOW",_=j;break}O.decision==="UNSUPPORTED"&&(k=!0)}N!=="ALLOW"&&k&&(N="UNSUPPORTED"),N==="ALLOW"&&_!==void 0&&S.push(`Allowed by match block '${_}'`),w===!0&&S.push(`list on collection path '${d.path}' evaluated against the document-level match block (document wildcard hypothetical, resource undefined) — emulator-faithful`);let f;N==="UNSUPPORTED"?(f="UNSUPPORTED",c++):N===d.expectation?(f="PASSED",a++):(f="FAILED",o++),i.push({description:d.description,expectation:d.expectation,state:f,decision:N,trace:q,notes:S,pathResolution:I})}return{success:!0,data:{passed:a,failed:o,unsupported:c,results:i}}}}function Qh(t,e,n=new Map,r){if(Sr(t,n))return{provable:!0,reason:"list rule does not depend on per-document data; every doc is equally readable"};const s=Xh(t,n,r);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==="=="&&rf(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:Yh(o,c),residual:{missing:o,mismatched:c}}}function Yh(t,e){const n=[];if(t.length>0){const r=t.map(s=>`resource.data.${s.field} == ${s.fromAuthUid?"request.auth.uid":JSON.stringify(s.expectedValue)}`).join(", ");n.push(`the query has no matching where(...) equality for [${r}]`)}if(e.length>0){const r=e.map(s=>`resource.data.${s.field} == ${JSON.stringify(s.expectedValue)} but the query pins ${JSON.stringify(s.actualValue)}`).join(", ");n.push(`the query where(...) value does not match [${r}]`)}return`${n.join("; ")} — prod rejects the query ("rules are not filters")`}function Sr(t,e=new Map,n=new Set){const r=s=>{switch(s.type){case"literal":return!0;case"identifier":return s.name!=="resource";case"memberAccess":return r(s.object);case"bracketAccess":return r(s.object)&&r(s.index);case"sliceAccess":return r(s.object)&&r(s.start)&&r(s.end);case"binaryOp":return r(s.left)&&r(s.right);case"unaryOp":return r(s.operand);case"ternary":return r(s.condition)&&r(s.consequent)&&r(s.alternate);case"inExpr":return r(s.element)&&r(s.collection);case"isExpr":return r(s.value);case"listLiteral":return s.elements.every(r);case"mapLiteral":return s.entries.every(i=>r(i.key)&&r(i.value));case"pathLiteral":return s.segments.every(i=>typeof i=="string"||r(i));case"methodCall":return r(s.object)&&s.args.every(r);case"functionCall":{if(!s.args.every(r))return!1;const i=e.get(s.name);if(!i)return!0;if(n.has(s.name))return!1;const a=new Set(n).add(s.name);return Sr(i.body,e,a)&&i.lets.every(o=>Sr(o.value,e,a))}default:return!1}};return r(t)}function Xh(t,e,n){const r=[],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 b=i.args[y];b&&u.set(p,b)});for(const p of c.lets)u.set(p.name,_a(p.value,u));const d=_a(c.body,u),l=new Set(a).add(i.name);return s(d,l)}const o=ef(i,n);return o?(r.push(o),!0):Sr(i,e)};return s(t,new Set)?{ok:!0,required:r}:{ok:!1}}function ef(t,e){if(t.type!=="binaryOp"||t.op!=="==")return null;const n=(r,s)=>{const i=nf(r);return i===null?null:s.type==="literal"?{field:i,value:s.value,fromAuthUid:!1}:e!==void 0&&tf(s)?{field:i,value:e,fromAuthUid:!0}:null};return n(t.left,t.right)??n(t.right,t.left)}function tf(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 _a(t,e){const n=r=>{switch(r.type){case"identifier":return e.get(r.name)??r;case"literal":return r;case"memberAccess":return{...r,object:n(r.object)};case"methodCall":return{...r,object:n(r.object),args:r.args.map(n)};case"bracketAccess":return{...r,object:n(r.object),index:n(r.index)};case"sliceAccess":return{...r,object:n(r.object),start:n(r.start),end:n(r.end)};case"binaryOp":return{...r,left:n(r.left),right:n(r.right)};case"unaryOp":return{...r,operand:n(r.operand)};case"ternary":return{...r,condition:n(r.condition),consequent:n(r.consequent),alternate:n(r.alternate)};case"inExpr":return{...r,element:n(r.element),collection:n(r.collection)};case"isExpr":return{...r,value:n(r.value)};case"listLiteral":return{...r,elements:r.elements.map(n)};case"mapLiteral":return{...r,entries:r.entries.map(s=>({key:n(s.key),value:n(s.value)}))};case"pathLiteral":return{...r,segments:r.segments.map(s=>typeof s=="string"?s:n(s))};case"functionCall":return{...r,args:r.args.map(n)}}};return n(t)}function nf(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 rf(t,e){return t===e}class zt extends ne{typeName="reference";path;constructor(e){super(),this.path=sf(e)}static fromResourceName(e){return new zt(bc(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 zt?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,n){return le}}function sf(t){let e=bc(t);return e.startsWith("/")&&(e=e.slice(1)),e.endsWith("/")&&(e=e.slice(0,-1)),e}function bc(t){const e="/documents/",n=t.indexOf(e);return n===-1?t:t.slice(n+e.length)}class en extends ne{typeName="vector";value;constructor(e){if(super(),!Array.isArray(e))throw new TypeError("Vector: value must be a number[]");for(let n=0;n<e.length;n++)if(typeof e[n]!="number")throw new TypeError(`Vector: element at index ${n} is not a number (got ${typeof e[n]})`);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 en)||e.value.length!==this.value.length)return!1;for(let n=0;n<this.value.length;n++)if(e.value[n]!==this.value[n])return!1;return!0}callMethod(e,n){return le}}var J;(function(t){t.assertEqual=s=>{};function e(s){}t.assertIs=e;function n(s){throw new Error}t.assertNever=n,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 r(s,i=" | "){return s.map(a=>typeof a=="string"?`'${a}'`:a).join(i)}t.joinValues=r,t.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(J||(J={}));var Aa;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(Aa||(Aa={}));const P=J.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),At=t=>{switch(typeof t){case"undefined":return P.undefined;case"string":return P.string;case"number":return Number.isNaN(t)?P.nan:P.number;case"boolean":return P.boolean;case"function":return P.function;case"bigint":return P.bigint;case"symbol":return P.symbol;case"object":return Array.isArray(t)?P.array:t===null?P.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?P.promise:typeof Map<"u"&&t instanceof Map?P.map:typeof Set<"u"&&t instanceof Set?P.set:typeof Date<"u"&&t instanceof Date?P.date:P.object;default:return P.unknown}},L=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 bt extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){const n=e||function(i){return i.message},r={_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)r._errors.push(n(a));else{let o=r,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(n(a))):o[u]=o[u]||{_errors:[]},o=o[u],c++}}};return s(this),r}static assert(e){if(!(e instanceof bt))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=n=>n.message){const n={},r=[];for(const s of this.issues)if(s.path.length>0){const i=s.path[0];n[i]=n[i]||[],n[i].push(e(s))}else r.push(e(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}bt.create=t=>new bt(t);const Ps=(t,e)=>{let n;switch(t.code){case L.invalid_type:t.received===P.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case L.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,J.jsonStringifyReplacer)}`;break;case L.unrecognized_keys:n=`Unrecognized key(s) in object: ${J.joinValues(t.keys,", ")}`;break;case L.invalid_union:n="Invalid input";break;case L.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${J.joinValues(t.options)}`;break;case L.invalid_enum_value:n=`Invalid enum value. Expected ${J.joinValues(t.options)}, received '${t.received}'`;break;case L.invalid_arguments:n="Invalid function arguments";break;case L.invalid_return_type:n="Invalid function return type";break;case L.invalid_date:n="Invalid date";break;case L.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:J.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case L.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case L.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case L.custom:n="Invalid input";break;case L.invalid_intersection_types:n="Intersection results could not be merged";break;case L.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case L.not_finite:n="Number must be finite";break;default:n=e.defaultError,J.assertNever(t)}return{message:n}};let af=Ps;function of(){return af}const cf=t=>{const{data:e,path:n,errorMaps:r,issueData:s}=t,i=[...n,...s.path||[]],a={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let o="";const c=r.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 M(t,e){const n=of(),r=cf({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===Ps?void 0:Ps].filter(s=>!!s)});t.common.issues.push(r)}class Me{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){const r=[];for(const s of n){if(s.status==="aborted")return U;s.status==="dirty"&&e.dirty(),r.push(s.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){const r=[];for(const s of n){const i=await s.key,a=await s.value;r.push({key:i,value:a})}return Me.mergeObjectSync(e,r)}static mergeObjectSync(e,n){const r={};for(const s of n){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)&&(r[i.value]=a.value)}return{status:e.value,value:r}}}const U=Object.freeze({status:"aborted"}),Cn=t=>({status:"dirty",value:t}),Ze=t=>({status:"valid",value:t}),xa=t=>t.status==="aborted",Ia=t=>t.status==="dirty",fn=t=>t.status==="valid",_r=t=>typeof Promise<"u"&&t instanceof Promise;var $;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})($||($={}));class ct{constructor(e,n,r,s){this._cachedPath=[],this.parent=e,this.data=n,this._path=r,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const Ea=(t,e)=>{if(fn(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new bt(t.common.issues);return this._error=n,this._error}}};function W(t){if(!t)return{};const{errorMap:e,invalid_type_error:n,required_error:r,description:s}=t;if(e&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(a,o)=>{const{message:c}=t;return a.code==="invalid_enum_value"?{message:c??o.defaultError}:typeof o.data>"u"?{message:c??r??o.defaultError}:a.code!=="invalid_type"?{message:o.defaultError}:{message:c??n??o.defaultError}},description:s}}class K{get description(){return this._def.description}_getType(e){return At(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:At(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Me,ctx:{common:e.parent.common,data:e.data,parsedType:At(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const n=this._parse(e);if(_r(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){const n=this._parse(e);return Promise.resolve(n)}parse(e,n){const r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){const r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:At(e)},s=this._parseSync({data:e,path:r.path,parent:r});return Ea(r,s)}"~validate"(e){const n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:At(e)};if(!this["~standard"].async)try{const r=this._parseSync({data:e,path:[],parent:n});return fn(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(r=>fn(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(e,n){const r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){const r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:At(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await(_r(s)?s:Promise.resolve(s));return Ea(r,i)}refine(e,n){const r=s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n;return this._refinement((s,i)=>{const a=e(s),o=()=>i.addIssue({code:L.custom,...r(s)});return typeof Promise<"u"&&a instanceof Promise?a.then(c=>c?!0:(o(),!1)):a?!0:(o(),!1)})}refinement(e,n){return this._refinement((r,s)=>e(r)?!0:(s.addIssue(typeof n=="function"?n(r,s):n),!1))}_refinement(e){return new Ht({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:n=>this["~validate"](n)}}optional(){return gt.create(this,this._def)}nullable(){return Gt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return it.create(this)}promise(){return Cr.create(this,this._def)}or(e){return Ir.create([this,e],this._def)}and(e){return Er.create(this,e,this._def)}transform(e){return new Ht({...W(this._def),schema:this,typeName:B.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const n=typeof e=="function"?e:()=>e;return new Tr({...W(this._def),innerType:this,defaultValue:n,typeName:B.ZodDefault})}brand(){return new _c({typeName:B.ZodBranded,type:this,...W(this._def)})}catch(e){const n=typeof e=="function"?e:()=>e;return new Rr({...W(this._def),innerType:this,catchValue:n,typeName:B.ZodCatch})}describe(e){const n=this.constructor;return new n({...this._def,description:e})}pipe(e){return xi.create(this,e)}readonly(){return Nr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const uf=/^c[^\s-]{8,}$/i,lf=/^[0-9a-z]+$/,df=/^[0-9A-HJKMNP-TV-Z]{26}$/i,hf=/^[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,ff=/^[a-z0-9_-]{21}$/i,pf=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,mf=/^[-+]?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)?)??$/,gf=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,yf="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let us;const bf=/^(?:(?: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])$/,vf=/^(?:(?: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])$/,wf=/^(([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]))$/,Sf=/^(([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])$/,_f=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Af=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,vc="((\\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])))",xf=new RegExp(`^${vc}$`);function wc(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);const n=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function If(t){return new RegExp(`^${wc(t)}$`)}function Ef(t){let e=`${vc}T${wc(t)}`;const n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function kf(t,e){return!!((e==="v4"||!e)&&bf.test(t)||(e==="v6"||!e)&&wf.test(t))}function Of(t,e){if(!pf.test(t))return!1;try{const[n]=t.split(".");if(!n)return!1;const r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),s=JSON.parse(atob(r));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function Cf(t,e){return!!((e==="v4"||!e)&&vf.test(t)||(e==="v6"||!e)&&Sf.test(t))}class pt extends K{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==P.string){const i=this._getOrReturnCtx(e);return M(i,{code:L.invalid_type,expected:P.string,received:i.parsedType}),U}const r=new Me;let s;for(const i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),M(s,{code:L.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),M(s,{code:L.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.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?M(s,{code:L.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):o&&M(s,{code:L.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")gf.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"email",code:L.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")us||(us=new RegExp(yf,"u")),us.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"emoji",code:L.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")hf.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"uuid",code:L.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")ff.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"nanoid",code:L.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")uf.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"cuid",code:L.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")lf.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"cuid2",code:L.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")df.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"ulid",code:L.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),M(s,{validation:"url",code:L.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"regex",code:L.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),M(s,{code:L.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.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),M(s,{code:L.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),M(s,{code:L.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?Ef(i).test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{code:L.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?xf.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{code:L.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?If(i).test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{code:L.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?mf.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"duration",code:L.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?kf(e.data,i.version)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"ip",code:L.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?Of(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"jwt",code:L.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?Cf(e.data,i.version)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"cidr",code:L.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?_f.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"base64",code:L.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?Af.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"base64url",code:L.invalid_string,message:i.message}),r.dirty()):J.assertNever(i);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(s=>e.test(s),{validation:n,code:L.invalid_string,...$.errToObj(r)})}_addCheck(e){return new pt({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...$.errToObj(e)})}url(e){return this._addCheck({kind:"url",...$.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...$.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...$.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...$.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...$.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...$.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...$.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...$.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...$.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...$.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...$.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...$.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,...$.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,...$.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...$.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...$.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...$.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...$.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...$.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...$.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...$.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...$.errToObj(n)})}nonempty(e){return this.min(1,$.errToObj(e))}trim(){return new pt({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new pt({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new pt({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}}pt.create=t=>new pt({checks:[],typeName:B.ZodString,coerce:t?.coerce??!1,...W(t)});function Tf(t,e){const n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,s=n>r?n:r,i=Number.parseInt(t.toFixed(s).replace(".","")),a=Number.parseInt(e.toFixed(s).replace(".",""));return i%a/10**s}class pn 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)!==P.number){const i=this._getOrReturnCtx(e);return M(i,{code:L.invalid_type,expected:P.number,received:i.parsedType}),U}let r;const s=new Me;for(const i of this._def.checks)i.kind==="int"?J.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),M(r,{code:L.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),M(r,{code:L.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)&&(r=this._getOrReturnCtx(e,r),M(r,{code:L.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?Tf(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),M(r,{code:L.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),M(r,{code:L.not_finite,message:i.message}),s.dirty()):J.assertNever(i);return{status:s.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,$.toString(n))}gt(e,n){return this.setLimit("min",e,!1,$.toString(n))}lte(e,n){return this.setLimit("max",e,!0,$.toString(n))}lt(e,n){return this.setLimit("max",e,!1,$.toString(n))}setLimit(e,n,r,s){return new pn({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:$.toString(s)}]})}_addCheck(e){return new pn({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:$.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:$.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:$.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:$.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:$.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:$.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:$.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:$.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:$.toString(e)})}get minValue(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&J.isInteger(e.value))}get isFinite(){let e=null,n=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(n)&&Number.isFinite(e)}}pn.create=t=>new pn({checks:[],typeName:B.ZodNumber,coerce:t?.coerce||!1,...W(t)});class jn 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)!==P.bigint)return this._getInvalidInput(e);let r;const s=new Me;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),M(r,{code:L.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)&&(r=this._getOrReturnCtx(e,r),M(r,{code:L.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),M(r,{code:L.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):J.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){const n=this._getOrReturnCtx(e);return M(n,{code:L.invalid_type,expected:P.bigint,received:n.parsedType}),U}gte(e,n){return this.setLimit("min",e,!0,$.toString(n))}gt(e,n){return this.setLimit("min",e,!1,$.toString(n))}lte(e,n){return this.setLimit("max",e,!0,$.toString(n))}lt(e,n){return this.setLimit("max",e,!1,$.toString(n))}setLimit(e,n,r,s){return new jn({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:$.toString(s)}]})}_addCheck(e){return new jn({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:$.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:$.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:$.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:$.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:$.toString(n)})}get minValue(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}}jn.create=t=>new jn({checks:[],typeName:B.ZodBigInt,coerce:t?.coerce??!1,...W(t)});class $s extends K{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==P.boolean){const r=this._getOrReturnCtx(e);return M(r,{code:L.invalid_type,expected:P.boolean,received:r.parsedType}),U}return Ze(e.data)}}$s.create=t=>new $s({typeName:B.ZodBoolean,coerce:t?.coerce||!1,...W(t)});class Ar extends K{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==P.date){const i=this._getOrReturnCtx(e);return M(i,{code:L.invalid_type,expected:P.date,received:i.parsedType}),U}if(Number.isNaN(e.data.getTime())){const i=this._getOrReturnCtx(e);return M(i,{code:L.invalid_date}),U}const r=new Me;let s;for(const i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),M(s,{code:L.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),M(s,{code:L.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):J.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Ar({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:$.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:$.toString(n)})}get minDate(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}}Ar.create=t=>new Ar({checks:[],coerce:t?.coerce||!1,typeName:B.ZodDate,...W(t)});class ka extends K{_parse(e){if(this._getType(e)!==P.symbol){const r=this._getOrReturnCtx(e);return M(r,{code:L.invalid_type,expected:P.symbol,received:r.parsedType}),U}return Ze(e.data)}}ka.create=t=>new ka({typeName:B.ZodSymbol,...W(t)});class qs extends K{_parse(e){if(this._getType(e)!==P.undefined){const r=this._getOrReturnCtx(e);return M(r,{code:L.invalid_type,expected:P.undefined,received:r.parsedType}),U}return Ze(e.data)}}qs.create=t=>new qs({typeName:B.ZodUndefined,...W(t)});class xr extends K{_parse(e){if(this._getType(e)!==P.null){const r=this._getOrReturnCtx(e);return M(r,{code:L.invalid_type,expected:P.null,received:r.parsedType}),U}return Ze(e.data)}}xr.create=t=>new xr({typeName:B.ZodNull,...W(t)});class Oa extends K{constructor(){super(...arguments),this._any=!0}_parse(e){return Ze(e.data)}}Oa.create=t=>new Oa({typeName:B.ZodAny,...W(t)});class Us extends K{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ze(e.data)}}Us.create=t=>new Us({typeName:B.ZodUnknown,...W(t)});class Ct extends K{_parse(e){const n=this._getOrReturnCtx(e);return M(n,{code:L.invalid_type,expected:P.never,received:n.parsedType}),U}}Ct.create=t=>new Ct({typeName:B.ZodNever,...W(t)});class Ca extends K{_parse(e){if(this._getType(e)!==P.undefined){const r=this._getOrReturnCtx(e);return M(r,{code:L.invalid_type,expected:P.void,received:r.parsedType}),U}return Ze(e.data)}}Ca.create=t=>new Ca({typeName:B.ZodVoid,...W(t)});class it extends K{_parse(e){const{ctx:n,status:r}=this._processInputParams(e),s=this._def;if(n.parsedType!==P.array)return M(n,{code:L.invalid_type,expected:P.array,received:n.parsedType}),U;if(s.exactLength!==null){const a=n.data.length>s.exactLength.value,o=n.data.length<s.exactLength.value;(a||o)&&(M(n,{code:a?L.too_big:L.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}),r.dirty())}if(s.minLength!==null&&n.data.length<s.minLength.value&&(M(n,{code:L.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&n.data.length>s.maxLength.value&&(M(n,{code:L.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((a,o)=>s.type._parseAsync(new ct(n,a,n.path,o)))).then(a=>Me.mergeArray(r,a));const i=[...n.data].map((a,o)=>s.type._parseSync(new ct(n,a,n.path,o)));return Me.mergeArray(r,i)}get element(){return this._def.type}min(e,n){return new it({...this._def,minLength:{value:e,message:$.toString(n)}})}max(e,n){return new it({...this._def,maxLength:{value:e,message:$.toString(n)}})}length(e,n){return new it({...this._def,exactLength:{value:e,message:$.toString(n)}})}nonempty(e){return this.min(1,e)}}it.create=(t,e)=>new it({type:t,minLength:null,maxLength:null,exactLength:null,typeName:B.ZodArray,...W(e)});function an(t){if(t instanceof me){const e={};for(const n in t.shape){const r=t.shape[n];e[n]=gt.create(an(r))}return new me({...t._def,shape:()=>e})}else return t instanceof it?new it({...t._def,type:an(t.element)}):t instanceof gt?gt.create(an(t.unwrap())):t instanceof Gt?Gt.create(an(t.unwrap())):t instanceof Vt?Vt.create(t.items.map(e=>an(e))):t}class me 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(),n=J.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==P.object){const u=this._getOrReturnCtx(e);return M(u,{code:L.invalid_type,expected:P.object,received:u.parsedType}),U}const{status:r,ctx:s}=this._processInputParams(e),{shape:i,keys:a}=this._getCached(),o=[];if(!(this._def.catchall instanceof Ct&&this._def.unknownKeys==="strip"))for(const u in s.data)a.includes(u)||o.push(u);const c=[];for(const u of a){const d=i[u],l=s.data[u];c.push({key:{status:"valid",value:u},value:d._parse(new ct(s,l,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof Ct){const u=this._def.unknownKeys;if(u==="passthrough")for(const d of o)c.push({key:{status:"valid",value:d},value:{status:"valid",value:s.data[d]}});else if(u==="strict")o.length>0&&(M(s,{code:L.unrecognized_keys,keys:o}),r.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const u=this._def.catchall;for(const d of o){const l=s.data[d];c.push({key:{status:"valid",value:d},value:u._parse(new ct(s,l,s.path,d)),alwaysSet:d in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const u=[];for(const d of c){const l=await d.key,p=await d.value;u.push({key:l,value:p,alwaysSet:d.alwaysSet})}return u}).then(u=>Me.mergeObjectSync(r,u)):Me.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(e){return $.errToObj,new me({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{const s=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:$.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new me({...this._def,unknownKeys:"strip"})}passthrough(){return new me({...this._def,unknownKeys:"passthrough"})}extend(e){return new me({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new me({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:B.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new me({...this._def,catchall:e})}pick(e){const n={};for(const r of J.objectKeys(e))e[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new me({...this._def,shape:()=>n})}omit(e){const n={};for(const r of J.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new me({...this._def,shape:()=>n})}deepPartial(){return an(this)}partial(e){const n={};for(const r of J.objectKeys(this.shape)){const s=this.shape[r];e&&!e[r]?n[r]=s:n[r]=s.optional()}return new me({...this._def,shape:()=>n})}required(e){const n={};for(const r of J.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof gt;)i=i._def.innerType;n[r]=i}return new me({...this._def,shape:()=>n})}keyof(){return Sc(J.objectKeys(this.shape))}}me.create=(t,e)=>new me({shape:()=>t,unknownKeys:"strip",catchall:Ct.create(),typeName:B.ZodObject,...W(e)});me.strictCreate=(t,e)=>new me({shape:()=>t,unknownKeys:"strict",catchall:Ct.create(),typeName:B.ZodObject,...W(e)});me.lazycreate=(t,e)=>new me({shape:t,unknownKeys:"strip",catchall:Ct.create(),typeName:B.ZodObject,...W(e)});class Ir extends K{_parse(e){const{ctx:n}=this._processInputParams(e),r=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 n.common.issues.push(...o.ctx.common.issues),o.result;const a=i.map(o=>new bt(o.ctx.common.issues));return M(n,{code:L.invalid_union,unionErrors:a}),U}if(n.common.async)return Promise.all(r.map(async i=>{const a={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:a}),ctx:a}})).then(s);{let i;const a=[];for(const c of r){const u={...n,common:{...n.common,issues:[]},parent:null},d=c._parseSync({data:n.data,path:n.path,parent:u});if(d.status==="valid")return d;d.status==="dirty"&&!i&&(i={result:d,ctx:u}),u.common.issues.length&&a.push(u.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;const o=a.map(c=>new bt(c));return M(n,{code:L.invalid_union,unionErrors:o}),U}}get options(){return this._def.options}}Ir.create=(t,e)=>new Ir({options:t,typeName:B.ZodUnion,...W(e)});const ht=t=>t instanceof zs?ht(t.schema):t instanceof Ht?ht(t.innerType()):t instanceof Or?[t.value]:t instanceof Wt?t.options:t instanceof Vs?J.objectValues(t.enum):t instanceof Tr?ht(t._def.innerType):t instanceof qs?[void 0]:t instanceof xr?[null]:t instanceof gt?[void 0,...ht(t.unwrap())]:t instanceof Gt?[null,...ht(t.unwrap())]:t instanceof _c||t instanceof Nr?ht(t.unwrap()):t instanceof Rr?ht(t._def.innerType):[];class Ai extends K{_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==P.object)return M(n,{code:L.invalid_type,expected:P.object,received:n.parsedType}),U;const r=this.discriminator,s=n.data[r],i=this.optionsMap.get(s);return i?n.common.async?i._parseAsync({data:n.data,path:n.path,parent:n}):i._parseSync({data:n.data,path:n.path,parent:n}):(M(n,{code:L.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),U)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){const s=new Map;for(const i of n){const a=ht(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 Ai({typeName:B.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:s,...W(r)})}}function Bs(t,e){const n=At(t),r=At(e);if(t===e)return{valid:!0,data:t};if(n===P.object&&r===P.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=Bs(t[o],e[o]);if(!c.valid)return{valid:!1};a[o]=c.data}return{valid:!0,data:a}}else if(n===P.array&&r===P.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=Bs(a,o);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return n===P.date&&r===P.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}class Er extends K{_parse(e){const{status:n,ctx:r}=this._processInputParams(e),s=(i,a)=>{if(xa(i)||xa(a))return U;const o=Bs(i.value,a.value);return o.valid?((Ia(i)||Ia(a))&&n.dirty(),{status:n.value,value:o.data}):(M(r,{code:L.invalid_intersection_types}),U)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([i,a])=>s(i,a)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}Er.create=(t,e,n)=>new Er({left:t,right:e,typeName:B.ZodIntersection,...W(n)});class Vt extends K{_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==P.array)return M(r,{code:L.invalid_type,expected:P.array,received:r.parsedType}),U;if(r.data.length<this._def.items.length)return M(r,{code:L.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),U;!this._def.rest&&r.data.length>this._def.items.length&&(M(r,{code:L.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const i=[...r.data].map((a,o)=>{const c=this._def.items[o]||this._def.rest;return c?c._parse(new ct(r,a,r.path,o)):null}).filter(a=>!!a);return r.common.async?Promise.all(i).then(a=>Me.mergeArray(n,a)):Me.mergeArray(n,i)}get items(){return this._def.items}rest(e){return new Vt({...this._def,rest:e})}}Vt.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Vt({items:t,typeName:B.ZodTuple,rest:null,...W(e)})};class kr extends K{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==P.object)return M(r,{code:L.invalid_type,expected:P.object,received:r.parsedType}),U;const s=[],i=this._def.keyType,a=this._def.valueType;for(const o in r.data)s.push({key:i._parse(new ct(r,o,r.path,o)),value:a._parse(new ct(r,r.data[o],r.path,o)),alwaysSet:o in r.data});return r.common.async?Me.mergeObjectAsync(n,s):Me.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof K?new kr({keyType:e,valueType:n,typeName:B.ZodRecord,...W(r)}):new kr({keyType:pt.create(),valueType:e,typeName:B.ZodRecord,...W(n)})}}class Ta extends K{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==P.map)return M(r,{code:L.invalid_type,expected:P.map,received:r.parsedType}),U;const s=this._def.keyType,i=this._def.valueType,a=[...r.data.entries()].map(([o,c],u)=>({key:s._parse(new ct(r,o,r.path,[u,"key"])),value:i._parse(new ct(r,c,r.path,[u,"value"]))}));if(r.common.async){const o=new Map;return Promise.resolve().then(async()=>{for(const c of a){const u=await c.key,d=await c.value;if(u.status==="aborted"||d.status==="aborted")return U;(u.status==="dirty"||d.status==="dirty")&&n.dirty(),o.set(u.value,d.value)}return{status:n.value,value:o}})}else{const o=new Map;for(const c of a){const u=c.key,d=c.value;if(u.status==="aborted"||d.status==="aborted")return U;(u.status==="dirty"||d.status==="dirty")&&n.dirty(),o.set(u.value,d.value)}return{status:n.value,value:o}}}}Ta.create=(t,e,n)=>new Ta({valueType:e,keyType:t,typeName:B.ZodMap,...W(n)});class Pn extends K{_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==P.set)return M(r,{code:L.invalid_type,expected:P.set,received:r.parsedType}),U;const s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(M(r,{code:L.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),n.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&(M(r,{code:L.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());const i=this._def.valueType;function a(c){const u=new Set;for(const d of c){if(d.status==="aborted")return U;d.status==="dirty"&&n.dirty(),u.add(d.value)}return{status:n.value,value:u}}const o=[...r.data.values()].map((c,u)=>i._parse(new ct(r,c,r.path,u)));return r.common.async?Promise.all(o).then(c=>a(c)):a(o)}min(e,n){return new Pn({...this._def,minSize:{value:e,message:$.toString(n)}})}max(e,n){return new Pn({...this._def,maxSize:{value:e,message:$.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}}Pn.create=(t,e)=>new Pn({valueType:t,minSize:null,maxSize:null,typeName:B.ZodSet,...W(e)});class zs extends K{get schema(){return this._def.getter()}_parse(e){const{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}zs.create=(t,e)=>new zs({getter:t,typeName:B.ZodLazy,...W(e)});class Or extends K{_parse(e){if(e.data!==this._def.value){const n=this._getOrReturnCtx(e);return M(n,{received:n.data,code:L.invalid_literal,expected:this._def.value}),U}return{status:"valid",value:e.data}}get value(){return this._def.value}}Or.create=(t,e)=>new Or({value:t,typeName:B.ZodLiteral,...W(e)});function Sc(t,e){return new Wt({values:t,typeName:B.ZodEnum,...W(e)})}class Wt extends K{_parse(e){if(typeof e.data!="string"){const n=this._getOrReturnCtx(e),r=this._def.values;return M(n,{expected:J.joinValues(r),received:n.parsedType,code:L.invalid_type}),U}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const n=this._getOrReturnCtx(e),r=this._def.values;return M(n,{received:n.data,code:L.invalid_enum_value,options:r}),U}return Ze(e.data)}get options(){return this._def.values}get enum(){const e={};for(const n of this._def.values)e[n]=n;return e}get Values(){const e={};for(const n of this._def.values)e[n]=n;return e}get Enum(){const e={};for(const n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return Wt.create(e,{...this._def,...n})}exclude(e,n=this._def){return Wt.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}}Wt.create=Sc;class Vs extends K{_parse(e){const n=J.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==P.string&&r.parsedType!==P.number){const s=J.objectValues(n);return M(r,{expected:J.joinValues(s),received:r.parsedType,code:L.invalid_type}),U}if(this._cache||(this._cache=new Set(J.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const s=J.objectValues(n);return M(r,{received:r.data,code:L.invalid_enum_value,options:s}),U}return Ze(e.data)}get enum(){return this._def.values}}Vs.create=(t,e)=>new Vs({values:t,typeName:B.ZodNativeEnum,...W(e)});class Cr extends K{unwrap(){return this._def.type}_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==P.promise&&n.common.async===!1)return M(n,{code:L.invalid_type,expected:P.promise,received:n.parsedType}),U;const r=n.parsedType===P.promise?n.data:Promise.resolve(n.data);return Ze(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}}Cr.create=(t,e)=>new Cr({type:t,typeName:B.ZodPromise,...W(e)});class Ht 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:n,ctx:r}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:a=>{M(r,a),a.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){const a=s.transform(r.data,i);if(r.common.async)return Promise.resolve(a).then(async o=>{if(n.value==="aborted")return U;const c=await this._def.schema._parseAsync({data:o,path:r.path,parent:r});return c.status==="aborted"?U:c.status==="dirty"||n.value==="dirty"?Cn(c.value):c});{if(n.value==="aborted")return U;const o=this._def.schema._parseSync({data:a,path:r.path,parent:r});return o.status==="aborted"?U:o.status==="dirty"||n.value==="dirty"?Cn(o.value):o}}if(s.type==="refinement"){const a=o=>{const c=s.refinement(o,i);if(r.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(r.common.async===!1){const o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?U:(o.status==="dirty"&&n.dirty(),a(o.value),{status:n.value,value:o.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>o.status==="aborted"?U:(o.status==="dirty"&&n.dirty(),a(o.value).then(()=>({status:n.value,value:o.value}))))}if(s.type==="transform")if(r.common.async===!1){const a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!fn(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:n.value,value:o}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>fn(a)?Promise.resolve(s.transform(a.value,i)).then(o=>({status:n.value,value:o})):U);J.assertNever(s)}}Ht.create=(t,e,n)=>new Ht({schema:t,typeName:B.ZodEffects,effect:e,...W(n)});Ht.createWithPreprocess=(t,e,n)=>new Ht({schema:e,effect:{type:"preprocess",transform:t},typeName:B.ZodEffects,...W(n)});class gt extends K{_parse(e){return this._getType(e)===P.undefined?Ze(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}gt.create=(t,e)=>new gt({innerType:t,typeName:B.ZodOptional,...W(e)});class Gt extends K{_parse(e){return this._getType(e)===P.null?Ze(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Gt.create=(t,e)=>new Gt({innerType:t,typeName:B.ZodNullable,...W(e)});class Tr extends K{_parse(e){const{ctx:n}=this._processInputParams(e);let r=n.data;return n.parsedType===P.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}Tr.create=(t,e)=>new Tr({innerType:t,typeName:B.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...W(e)});class Rr extends K{_parse(e){const{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return _r(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new bt(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new bt(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Rr.create=(t,e)=>new Rr({innerType:t,typeName:B.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...W(e)});class Ra extends K{_parse(e){if(this._getType(e)!==P.nan){const r=this._getOrReturnCtx(e);return M(r,{code:L.invalid_type,expected:P.nan,received:r.parsedType}),U}return{status:"valid",value:e.data}}}Ra.create=t=>new Ra({typeName:B.ZodNaN,...W(t)});class _c extends K{_parse(e){const{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}}class xi extends K{_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?U:i.status==="dirty"?(n.dirty(),Cn(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{const s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?U:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(e,n){return new xi({in:e,out:n,typeName:B.ZodPipeline})}}class Nr extends K{_parse(e){const n=this._def.innerType._parse(e),r=s=>(fn(s)&&(s.value=Object.freeze(s.value)),s);return _r(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}}Nr.create=(t,e)=>new Nr({innerType:t,typeName:B.ZodReadonly,...W(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 qe=pt.create,Na=pn.create,$n=$s.create,Ac=xr.create,mt=Us.create;Ct.create;const xc=it.create,He=me.create,Kr=Ir.create,Rf=Ai.create;Er.create;Vt.create;const Tt=kr.create,Yn=Or.create,mn=Wt.create;Cr.create;gt.create;Gt.create;const Nf=["get","list","create","update","delete"],Lf=He({uid:qe(),token:Tt(mt()).optional()}),Ff=He({function:mn(["get","exists"]).describe("Firestore function to mock"),path:qe().describe('Document path, e.g. "users/alice"'),result:Kr([Tt(mt()),$n()]).describe("Document data for get, boolean for exists")}),Df=Rf("kind",[He({kind:Yn("create")}),He({kind:Yn("set"),merge:$n()}),He({kind:Yn("update")}),He({kind:Yn("delete")})]),Mf=He({limit:Na().optional(),offset:Na().optional(),orderBy:qe().optional()});He({description:qe().describe("Human-readable description of what this test verifies"),expectation:mn(["ALLOW","DENY"]).describe("Expected outcome"),method:mn(Nf).describe("Firestore method to test"),path:qe().describe('Document path, e.g. "users/alice"'),auth:Kr([Lf,Ac()]).optional().describe("Auth context; null or omitted for unauthenticated"),data:Tt(mt()).optional().describe("request.resource.data for write operations"),resource:Tt(mt()).optional().describe("Existing document data (resource.data)"),functionMocks:xc(Ff).optional().describe("Mock get()/exists() calls in rules"),query:Mf.optional().describe("request.query payload (list ops only): limit/offset/orderBy."),requestTime:qe().optional().describe("Override for request.time (ISO-8601). Defaults to wallclock."),writeMode:Df.optional().describe("Optional write-mode override; controls update merge semantics and getAfter() projection.")});function Kt(t){if(t.decision==="UNSUPPORTED")return;const n=t.decision==="ALLOW";let r="deny",s;if(n)r="allow",s=t.trace.find(C=>C.verdict==="ALLOW");else if(r="deny",s=t.trace.find(I=>I.verdict==="DENY"?!0:I.verdict==="ERROR"),s===void 0){const I=t.trace.length;I>0&&(s=t.trace[I-1])}if(s===void 0)return;const a={verdict:r};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 b=a.line!==void 0,w=a.expression!==void 0,R=a.expressionTrace!==void 0;if(b||w||R)return a}function Se(t){const e=[];for(const n of t.notes)e.push(n);for(const n of t.trace){const r=n.operations.join(","),s=`Rule #${n.ruleIndex} (${r})`;n.verdict==="ALLOW"?e.push(`${s} → ALLOW`):n.verdict==="DENY"?e.push(`${s} → deny`):n.verdict==="UNSUPPORTED"?e.push(`${s} → unsupported: ${n.message??""}`):e.push(`${s} → error: ${n.message??""}`)}return e.push(`Simulated: ${t.decision}`),e}He({function:mn(["get","exists"]).describe("Cross-service Firestore function to mock"),path:qe().describe('Firestore document path in collection/doc form, e.g. "users/alice"'),result:Kr([Tt(mt()),$n()]).describe("Document fields for get, boolean for exists")});const jf={atomic:`// @pyric-services cloud.firestore
|
|
488
|
+
// Atomic module — cross-document integrity for BATCH writes, via the
|
|
489
|
+
// get()/getAfter() pair. Firestore evaluates every write in a batch
|
|
490
|
+
// against rules, and getAfter() returns another document's POST-BATCH
|
|
491
|
+
// state — so a rule can require "this write is only valid if a
|
|
492
|
+
// companion write happened in the same atomic batch".
|
|
493
|
+
//
|
|
494
|
+
// All semantics live-verified against a production database: companion
|
|
495
|
+
// visibility, solo-write denial, wrong-delta denial, single-use consumption
|
|
496
|
+
// incl. replay denial, and out-of-batch getAfter() falling back to current
|
|
497
|
+
// state.
|
|
498
|
+
//
|
|
499
|
+
// Explicit-param design: pass BOTH states of the companion doc —
|
|
500
|
+
// \`get(path).data\` (pre-batch) and \`getAfter(path).data\` (post-batch).
|
|
501
|
+
//
|
|
502
|
+
// import { companionChangedBy, consumedFlag } from 'atomic';
|
|
503
|
+
//
|
|
504
|
+
// // Denormalized counter: creating a task REQUIRES the team's
|
|
505
|
+
// // taskCount to have been incremented in the same batch:
|
|
506
|
+
// match /teams/{teamId}/tasks/{taskId} {
|
|
507
|
+
// function teamBefore() {
|
|
508
|
+
// return get(/databases/$(database)/documents/teams/$(teamId)).data;
|
|
509
|
+
// }
|
|
510
|
+
// function teamAfter() {
|
|
511
|
+
// return getAfter(/databases/$(database)/documents/teams/$(teamId)).data;
|
|
512
|
+
// }
|
|
513
|
+
// allow create: if companionChangedBy(teamBefore(), teamAfter(), 'taskCount', 1);
|
|
514
|
+
// }
|
|
515
|
+
//
|
|
516
|
+
// // Single-use invite: the join is valid only when the invite was
|
|
517
|
+
// // consumed (false -> true) IN THIS BATCH — replays deny because
|
|
518
|
+
// // the pre-batch state is already true:
|
|
519
|
+
// allow update: if consumedFlag(inviteBefore(), inviteAfter(), 'used');
|
|
520
|
+
//
|
|
521
|
+
// NOTE (simulator): in-batch companion semantics cannot be expressed
|
|
522
|
+
// in the simulator or the Rules Test API mock surface — the simulator
|
|
523
|
+
// treats cross-doc getAfter() as get(). These function BODIES are
|
|
524
|
+
// simulator-tested with explicit values; the getAfter() WIRING is the
|
|
525
|
+
// live v1 scope's job. Companion writes need their own allow rules too —
|
|
526
|
+
// every write in a batch is evaluated.
|
|
527
|
+
|
|
528
|
+
// The companion doc's field changed by EXACTLY n in this batch.
|
|
529
|
+
// before/after are the SAME doc's get()/getAfter() data.
|
|
530
|
+
export function companionChangedBy(before, after, field, n) {
|
|
531
|
+
return after[field] == before[field] + n;
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
// A single-use flag was consumed IN THIS BATCH: pre-batch false,
|
|
535
|
+
// post-batch true. Replays deny (pre-batch is already true), and a
|
|
536
|
+
// solo write denies (getAfter == get, so false != true).
|
|
537
|
+
export function consumedFlag(before, after, flagField) {
|
|
538
|
+
return before[flagField] == false && after[flagField] == true;
|
|
539
|
+
}
|
|
540
|
+
`,auth:`// @pyric-services cloud.firestore,firebase.storage
|
|
541
|
+
// @pyric-evidence storage-rules#125,firestore-rules#189
|
|
542
|
+
export function isAuthenticated() {
|
|
543
|
+
return request.auth != null;
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
export function isOwner(userId) {
|
|
547
|
+
return isAuthenticated() && request.auth.uid == userId;
|
|
548
|
+
}
|
|
549
|
+
`,content:`// @pyric-services cloud.firestore
|
|
550
|
+
// Content module for author-owned documents — the most common
|
|
551
|
+
// Firebase app shape (posts, notes, docs, comments, tasks).
|
|
552
|
+
//
|
|
553
|
+
// Convention: documents carry an author field (a UID string) and
|
|
554
|
+
// usually a status field ('draft' | 'published' | ...). Field names
|
|
555
|
+
// are parameters, not conventions — pass yours.
|
|
556
|
+
//
|
|
557
|
+
// Usage:
|
|
558
|
+
// import { validAuthorCreate, isAuthor, canReadContent, notDeleted } from 'content';
|
|
559
|
+
// import { onlyFieldsChanged } from 'lifecycle';
|
|
560
|
+
//
|
|
561
|
+
// match /posts/{postId} {
|
|
562
|
+
// // Create: author is the signed-in user.
|
|
563
|
+
// allow create: if validAuthorCreate('author');
|
|
564
|
+
// // Read: published to everyone, drafts to the author only.
|
|
565
|
+
// allow read: if canReadContent('status', 'author') && notDeleted();
|
|
566
|
+
// // Update: author edits content fields; authorship immutable.
|
|
567
|
+
// allow update: if isAuthor('author') && onlyFieldsChanged(['title', 'body', 'status']);
|
|
568
|
+
// allow delete: if isAuthor('author');
|
|
569
|
+
// }
|
|
570
|
+
|
|
571
|
+
// Create guard: signed in, and the incoming doc's author field is the
|
|
572
|
+
// caller. Use on \`create\` (reads request.resource).
|
|
573
|
+
export function validAuthorCreate(authorField) {
|
|
574
|
+
return request.auth != null
|
|
575
|
+
&& request.resource.data[authorField] == request.auth.uid;
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
// The caller is the EXISTING document's author. Use on update/delete
|
|
579
|
+
// (reads resource).
|
|
580
|
+
export function isAuthor(authorField) {
|
|
581
|
+
return request.auth != null
|
|
582
|
+
&& resource.data[authorField] == request.auth.uid;
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
// Read visibility: published content is public; anything else is
|
|
586
|
+
// visible to its author only. Works for get; for list queries the
|
|
587
|
+
// client must filter (rules are not filters — a bare collection query
|
|
588
|
+
// will be denied unless it proves status == 'published').
|
|
589
|
+
export function canReadContent(statusField, authorField) {
|
|
590
|
+
return resource.data[statusField] == 'published'
|
|
591
|
+
|| (request.auth != null && resource.data[authorField] == request.auth.uid);
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
// Soft-delete guard: the document is not marked deleted. Reads the
|
|
595
|
+
// EXISTING doc; a doc without the field passes — bracket access is
|
|
596
|
+
// the null-on-miss idiom (dotted access of a missing key ERRORS).
|
|
597
|
+
export function notDeleted() {
|
|
598
|
+
return resource.data['deleted'] != true;
|
|
599
|
+
}
|
|
600
|
+
`,counters:`// @pyric-services cloud.firestore
|
|
601
|
+
// Counters module for denormalized numeric integrity.
|
|
602
|
+
//
|
|
603
|
+
// The recurring shape: a client-maintained count (likes, votes, moves,
|
|
604
|
+
// quantities) that rules must keep honest — it may only change by a
|
|
605
|
+
// known step, or stay within known bounds. Generalizes the
|
|
606
|
+
// state-module's moveIncremented() (hardcoded to moveCount) to any
|
|
607
|
+
// field.
|
|
608
|
+
//
|
|
609
|
+
// Usage:
|
|
610
|
+
// import { incrementedBy, changedBy, boundedNumber } from 'counters';
|
|
611
|
+
//
|
|
612
|
+
// // A like toggle: likeCount moves by exactly ±1:
|
|
613
|
+
// allow update: if changedBy('likeCount', -1, 1);
|
|
614
|
+
//
|
|
615
|
+
// // A move counter: strictly +1 per move:
|
|
616
|
+
// allow update: if incrementedBy('moveCount', 1);
|
|
617
|
+
//
|
|
618
|
+
// // A rating: any write keeps it in [1, 5]:
|
|
619
|
+
// allow write: if boundedNumber('rating', 1, 5);
|
|
620
|
+
|
|
621
|
+
// The field changed by EXACTLY n relative to the existing document.
|
|
622
|
+
// n may be negative (decrement). Update rules only (needs resource).
|
|
623
|
+
export function incrementedBy(field, n) {
|
|
624
|
+
return request.resource.data[field] == resource.data[field] + n;
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
// The field's delta is within [min, max] (inclusive) — and it is NOT
|
|
628
|
+
// required to change (delta 0 passes when min <= 0 <= max).
|
|
629
|
+
export function changedBy(field, min, max) {
|
|
630
|
+
return request.resource.data[field] - resource.data[field] >= min
|
|
631
|
+
&& request.resource.data[field] - resource.data[field] <= max;
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
// The incoming value is a number within [min, max] (inclusive).
|
|
635
|
+
// Works on create and update. Missing field reads null (dynamic
|
|
636
|
+
// access) and fails the type check rather than erroring.
|
|
637
|
+
export function boundedNumber(field, min, max) {
|
|
638
|
+
return (request.resource.data[field] is int || request.resource.data[field] is float)
|
|
639
|
+
&& request.resource.data[field] >= min
|
|
640
|
+
&& request.resource.data[field] <= max;
|
|
641
|
+
}
|
|
642
|
+
`,geometry:`// @pyric-services cloud.firestore
|
|
643
|
+
// Geometry module for movement game validation via config document lookup.
|
|
644
|
+
//
|
|
645
|
+
// Caller must pass the config document data as an explicit parameter.
|
|
646
|
+
// The config doc is read via get() and cached per request — define a
|
|
647
|
+
// config() function in your rules and pass its result to these functions.
|
|
648
|
+
//
|
|
649
|
+
// Config doc schema:
|
|
650
|
+
// moves[pieceType][fromCell][toCell] = true
|
|
651
|
+
// jumps[pieceType][fromCell][toCell] = capturedCellName
|
|
652
|
+
//
|
|
653
|
+
// Usage:
|
|
654
|
+
// import { validSimpleMove, validJumpMove } from 'geometry';
|
|
655
|
+
//
|
|
656
|
+
// function config() {
|
|
657
|
+
// return get(/databases/$(database)/documents/gameConfig/checkers).data;
|
|
658
|
+
// }
|
|
659
|
+
//
|
|
660
|
+
// allow update: if validSimpleMove(config())
|
|
661
|
+
// && piecePlaced() && moveIntegrity();
|
|
662
|
+
//
|
|
663
|
+
// allow update: if validJumpMove(config())
|
|
664
|
+
// && captureValid() && captureDecrement() && moveIntegrity();
|
|
665
|
+
|
|
666
|
+
// Validate a simple (non-capture) move via config document lookup.
|
|
667
|
+
// Uses 3-level dynamic nesting: cfg.moves[piece][from][to].
|
|
668
|
+
// piece comes from resource.data (pre-write board) so client can't fake it.
|
|
669
|
+
export function validSimpleMove(cfg) {
|
|
670
|
+
let mf = request.resource.data.moveFrom;
|
|
671
|
+
let mt = request.resource.data.moveTo;
|
|
672
|
+
let piece = resource.data[mf];
|
|
673
|
+
return cfg.moves[piece][mf][mt] == true;
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
// Validate a jump (capture) move via config document lookup.
|
|
677
|
+
// cfg.jumps[piece][from][to] returns the expected captured cell name.
|
|
678
|
+
// Caller must separately verify the captured piece is an opponent piece.
|
|
679
|
+
export function validJumpMove(cfg) {
|
|
680
|
+
let mf = request.resource.data.moveFrom;
|
|
681
|
+
let mt = request.resource.data.moveTo;
|
|
682
|
+
let cap = request.resource.data.captured;
|
|
683
|
+
let piece = resource.data[mf];
|
|
684
|
+
return cfg.jumps[piece][mf][mt] == cap;
|
|
685
|
+
}
|
|
686
|
+
`,joining:`// @pyric-services cloud.firestore
|
|
687
|
+
// Joining module — how membership CHANGES, safely. The connective
|
|
688
|
+
// tissue between content/spaces: spaces gates children behind a
|
|
689
|
+
// members field; joining lets users enter and leave that field
|
|
690
|
+
// WITHOUT an admin backend, with no privilege escalation.
|
|
691
|
+
//
|
|
692
|
+
// Convention: a MAP-shaped members field (uid -> role) on the parent
|
|
693
|
+
// doc. Compose with lifecycle's onlyFieldsChanged so a join/leave
|
|
694
|
+
// write can't touch anything else:
|
|
695
|
+
//
|
|
696
|
+
// import { onlyAddedSelf, onlyRemovedSelf } from 'joining';
|
|
697
|
+
// import { onlyFieldsChanged } from 'lifecycle';
|
|
698
|
+
// import { isSpaceMember, hasSpaceRole } from 'spaces';
|
|
699
|
+
//
|
|
700
|
+
// match /teams/{teamId} {
|
|
701
|
+
// allow read: if isSpaceMember(resource.data);
|
|
702
|
+
//
|
|
703
|
+
// // Open self-service join (public team) at a fixed role, and
|
|
704
|
+
// // self-service leave — nothing else about the doc may change:
|
|
705
|
+
// allow update: if onlyFieldsChanged(['members'])
|
|
706
|
+
// && (onlyAddedSelf('members', 'editor') || onlyRemovedSelf('members'));
|
|
707
|
+
// // Admins manage the doc freely:
|
|
708
|
+
// allow update: if hasSpaceRole(resource.data, 'admin');
|
|
709
|
+
// }
|
|
710
|
+
//
|
|
711
|
+
// Every guarantee here is production-verified against the live Rules Test API:
|
|
712
|
+
// the field-level map diff is reliable; the empty no-op diff DENIES (set
|
|
713
|
+
// equality, not hasOnly — hasOnly on an empty set passes); role escalation via
|
|
714
|
+
// CHANGING an existing entry denies; adding or removing anyone else denies.
|
|
715
|
+
|
|
716
|
+
// The write adds EXACTLY the caller to the members map, at EXACTLY
|
|
717
|
+
// \`role\`, changing and removing nobody. Update rules only.
|
|
718
|
+
export function onlyAddedSelf(membersField, role) {
|
|
719
|
+
let diff = request.resource.data[membersField].diff(resource.data[membersField]);
|
|
720
|
+
return request.auth != null
|
|
721
|
+
&& diff.addedKeys() == [request.auth.uid].toSet()
|
|
722
|
+
&& diff.changedKeys().size() == 0
|
|
723
|
+
&& diff.removedKeys().size() == 0
|
|
724
|
+
&& request.resource.data[membersField][request.auth.uid] == role;
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
// The write removes EXACTLY the caller from the members map, adding
|
|
728
|
+
// and changing nobody. Self-service leave. Update rules only.
|
|
729
|
+
export function onlyRemovedSelf(membersField) {
|
|
730
|
+
let diff = request.resource.data[membersField].diff(resource.data[membersField]);
|
|
731
|
+
return request.auth != null
|
|
732
|
+
&& diff.removedKeys() == [request.auth.uid].toSet()
|
|
733
|
+
&& diff.addedKeys().size() == 0
|
|
734
|
+
&& diff.changedKeys().size() == 0;
|
|
735
|
+
}
|
|
736
|
+
`,lifecycle:`// @pyric-services cloud.firestore
|
|
737
|
+
// Lifecycle module for field immutability and timestamp enforcement.
|
|
738
|
+
//
|
|
739
|
+
// Common pattern: certain fields must never change after document creation
|
|
740
|
+
// (createdBy, createdAt, authorId).
|
|
741
|
+
//
|
|
742
|
+
// Usage:
|
|
743
|
+
// import { fieldUnchanged, immutableFields, isServerTimestamp } from 'lifecycle';
|
|
744
|
+
//
|
|
745
|
+
// // Single field:
|
|
746
|
+
// allow update: if fieldUnchanged('createdBy');
|
|
747
|
+
//
|
|
748
|
+
// // Multiple fields (replaces chained fieldUnchanged calls):
|
|
749
|
+
// allow update: if immutableFields(['createdBy', 'createdAt', 'authorId']);
|
|
750
|
+
//
|
|
751
|
+
// // The dual: users may edit title/body but NOTHING else:
|
|
752
|
+
// allow update: if onlyFieldsChanged(['title', 'body']);
|
|
753
|
+
//
|
|
754
|
+
// allow create: if isServerTimestamp('createdAt');
|
|
755
|
+
|
|
756
|
+
// Ensure a field's value is identical between existing and incoming document.
|
|
757
|
+
// Use on update rules to enforce immutability.
|
|
758
|
+
export function fieldUnchanged(field) {
|
|
759
|
+
return resource.data[field] == request.resource.data[field];
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
// Ensure multiple fields are unchanged between existing and incoming document.
|
|
763
|
+
// Uses MapDiff — one expression instead of N chained fieldUnchanged() calls.
|
|
764
|
+
export function immutableFields(fields) {
|
|
765
|
+
return request.resource.data.diff(resource.data).unchangedKeys().hasAll(fields);
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
// Ensure a field is set to the server timestamp.
|
|
769
|
+
// Use on create or update rules to enforce server-side time.
|
|
770
|
+
export function isServerTimestamp(field) {
|
|
771
|
+
return request.resource.data[field] == request.time;
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
// The dual of immutableFields: every changed field is in the allowed
|
|
775
|
+
// list (fields NOT listed are implicitly immutable). Top-level keys
|
|
776
|
+
// only — nested-map diffs are unreliable in production; flatten the
|
|
777
|
+
// schema instead of reaching for a nested diff.
|
|
778
|
+
export function onlyFieldsChanged(fields) {
|
|
779
|
+
return request.resource.data.diff(resource.data).affectedKeys().hasOnly(fields);
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
// Exactly n top-level fields changed in this write. n == 1 is the
|
|
783
|
+
// board-integrity / edit-one-field-per-write guard (Pattern 5,
|
|
784
|
+
// generalized beyond games).
|
|
785
|
+
export function nFieldsChanged(n) {
|
|
786
|
+
return request.resource.data.diff(resource.data).affectedKeys().size() == n;
|
|
787
|
+
}
|
|
788
|
+
`,lobby:`// @pyric-services cloud.firestore
|
|
789
|
+
// Lobby module for 2-participant coordination.
|
|
790
|
+
//
|
|
791
|
+
// Convention: documents must have these fields:
|
|
792
|
+
// host: string (creator's UID)
|
|
793
|
+
// guest: string ('' when waiting, joiner's UID when joined)
|
|
794
|
+
// status: 'waiting' | 'playing' | 'ready' (or any active state)
|
|
795
|
+
//
|
|
796
|
+
// Usage:
|
|
797
|
+
// import { validCreate, validJoin, canCancel } from 'lobby';
|
|
798
|
+
//
|
|
799
|
+
// allow create: if validCreate();
|
|
800
|
+
// allow update: if validJoin();
|
|
801
|
+
// allow delete: if canCancel();
|
|
802
|
+
|
|
803
|
+
// Is this a waiting lobby with an open seat?
|
|
804
|
+
function isWaiting() {
|
|
805
|
+
return resource.data.status == 'waiting'
|
|
806
|
+
&& resource.data.guest == '';
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
// Create: caller is host, seat empty, status waiting
|
|
810
|
+
export function validCreate() {
|
|
811
|
+
return request.auth != null
|
|
812
|
+
&& request.resource.data.host == request.auth.uid
|
|
813
|
+
&& request.resource.data.guest == ''
|
|
814
|
+
&& request.resource.data.status == 'waiting';
|
|
815
|
+
}
|
|
816
|
+
|
|
817
|
+
// Join: fill empty seat, transition to next status, no self-join
|
|
818
|
+
export function validJoin() {
|
|
819
|
+
return request.auth != null
|
|
820
|
+
&& isWaiting()
|
|
821
|
+
&& request.resource.data.guest == request.auth.uid
|
|
822
|
+
&& request.auth.uid != resource.data.host
|
|
823
|
+
&& request.resource.data.status == 'playing'
|
|
824
|
+
&& request.resource.data.host == resource.data.host;
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
// Cancel: only host, only while waiting
|
|
828
|
+
export function canCancel() {
|
|
829
|
+
return request.auth != null
|
|
830
|
+
&& resource.data.status == 'waiting'
|
|
831
|
+
&& request.auth.uid == resource.data.host;
|
|
832
|
+
}
|
|
833
|
+
`,membership:`// @pyric-services cloud.firestore,firebase.storage
|
|
834
|
+
// @pyric-evidence storage-rules#125,firestore-rules#189
|
|
835
|
+
// Membership module for role-based and claims-based access control.
|
|
836
|
+
//
|
|
837
|
+
// Two access patterns:
|
|
838
|
+
// 1. Custom claims on auth token (0 get() calls, set server-side)
|
|
839
|
+
// 2. Member maps on documents (0 get() calls on the doc itself)
|
|
840
|
+
//
|
|
841
|
+
// Usage:
|
|
842
|
+
// import { hasClaim, hasClaimRole, isMemberOf, hasRole } from 'membership';
|
|
843
|
+
//
|
|
844
|
+
// // Workspace access via custom claims
|
|
845
|
+
// allow read: if hasClaim('workspace_id');
|
|
846
|
+
// allow write: if hasClaimRole('workspace_role', 'admin');
|
|
847
|
+
//
|
|
848
|
+
// // Project access via member map on document
|
|
849
|
+
// allow read: if isMemberOf(resource.data.members);
|
|
850
|
+
// allow update: if hasRole(resource.data.members, 'admin');
|
|
851
|
+
|
|
852
|
+
// Check if the auth token has a non-null value for a claim key.
|
|
853
|
+
export function hasClaim(claim) {
|
|
854
|
+
return request.auth != null
|
|
855
|
+
&& request.auth.token[claim] != null;
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
// Check if the auth token has a specific value for a claim key.
|
|
859
|
+
export function hasClaimRole(claim, role) {
|
|
860
|
+
return request.auth != null
|
|
861
|
+
&& request.auth.token[claim] == role;
|
|
862
|
+
}
|
|
863
|
+
|
|
864
|
+
// Check if the caller's UID exists as a key in a members map.
|
|
865
|
+
export function isMemberOf(membersMap) {
|
|
866
|
+
return request.auth != null
|
|
867
|
+
&& request.auth.uid in membersMap;
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
// Check if the caller has a specific role in a members map.
|
|
871
|
+
export function hasRole(membersMap, role) {
|
|
872
|
+
return request.auth != null
|
|
873
|
+
&& membersMap[request.auth.uid] == role;
|
|
874
|
+
}
|
|
875
|
+
`,spaces:`// @pyric-services cloud.firestore
|
|
876
|
+
// Spaces module — cross-document membership gating for shared spaces
|
|
877
|
+
// (teams, rooms, groups, projects, parties). The second-most-common
|
|
878
|
+
// app shape after author-owned content: a PARENT document defines who
|
|
879
|
+
// may touch its children.
|
|
880
|
+
//
|
|
881
|
+
// Explicit-param design (like geometry): the caller reads the parent
|
|
882
|
+
// doc ONCE via a helper and passes its data in. Define the helper in
|
|
883
|
+
// your rules — get() is cached per request, so every function below
|
|
884
|
+
// can share one read (of the 10-get budget):
|
|
885
|
+
//
|
|
886
|
+
// import { isSpaceMember, hasSpaceRole, validMemberCreate } from 'spaces';
|
|
887
|
+
//
|
|
888
|
+
// match /spaces/{spaceId}/tasks/{taskId} {
|
|
889
|
+
// function space() {
|
|
890
|
+
// return get(/databases/$(database)/documents/spaces/$(spaceId)).data;
|
|
891
|
+
// }
|
|
892
|
+
// allow read: if isSpaceMember(space());
|
|
893
|
+
// allow create: if validMemberCreate(space(), 'author');
|
|
894
|
+
// allow delete: if hasSpaceRole(space(), 'admin');
|
|
895
|
+
// }
|
|
896
|
+
//
|
|
897
|
+
// Members field shapes verified against the production engine:
|
|
898
|
+
// list: members: ['uidA', 'uidB'] → isSpaceMember only
|
|
899
|
+
// map: members: { uidA: 'admin', ... } → isSpaceMember + hasSpaceRole
|
|
900
|
+
// A missing members field, a non-member uid, or a missing parent doc
|
|
901
|
+
// (get() of a missing doc errors) all fail CLOSED.
|
|
902
|
+
|
|
903
|
+
// The caller is in the space's members field. \`in\` covers both
|
|
904
|
+
// shapes: list membership and map keys.
|
|
905
|
+
export function isSpaceMember(spaceData) {
|
|
906
|
+
return request.auth != null && request.auth.uid in spaceData.members;
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
// The caller's role in a MAP-shaped members field equals \`role\`.
|
|
910
|
+
// List-shaped members carry no roles — this denies on them.
|
|
911
|
+
export function hasSpaceRole(spaceData, role) {
|
|
912
|
+
return request.auth != null && spaceData.members[request.auth.uid] == role;
|
|
913
|
+
}
|
|
914
|
+
|
|
915
|
+
// Member-gated authored create: the caller is a member AND the
|
|
916
|
+
// incoming child doc's author field is the caller. The "post a
|
|
917
|
+
// message / add a task" guard.
|
|
918
|
+
export function validMemberCreate(spaceData, authorField) {
|
|
919
|
+
return isSpaceMember(spaceData)
|
|
920
|
+
&& request.resource.data[authorField] == request.auth.uid;
|
|
921
|
+
}
|
|
922
|
+
`,state:`// @pyric-services cloud.firestore
|
|
923
|
+
// Game state machine helpers.
|
|
924
|
+
//
|
|
925
|
+
// Convention: documents must have these fields:
|
|
926
|
+
// status: 'waiting' | 'playing' | 'won' | 'draw'
|
|
927
|
+
// moveCount: number
|
|
928
|
+
// host: string (UID)
|
|
929
|
+
// guest: string (UID)
|
|
930
|
+
//
|
|
931
|
+
// Usage:
|
|
932
|
+
// import { isPlaying, moveIncremented, participantsUnchanged } from 'state';
|
|
933
|
+
//
|
|
934
|
+
// allow update: if isPlaying() && moveIncremented() && participantsUnchanged();
|
|
935
|
+
|
|
936
|
+
// Is the game actively in play?
|
|
937
|
+
export function isPlaying() {
|
|
938
|
+
return resource.data.status == 'playing';
|
|
939
|
+
}
|
|
940
|
+
|
|
941
|
+
// Did moveCount increment by exactly 1?
|
|
942
|
+
export function moveIncremented() {
|
|
943
|
+
return request.resource.data.moveCount == resource.data.moveCount + 1;
|
|
944
|
+
}
|
|
945
|
+
|
|
946
|
+
// Are host and guest unchanged? (prevents mid-game identity swap)
|
|
947
|
+
export function participantsUnchanged() {
|
|
948
|
+
return request.resource.data.host == resource.data.host
|
|
949
|
+
&& request.resource.data.guest == resource.data.guest;
|
|
950
|
+
}
|
|
951
|
+
`,"storage/metadata":`// @pyric-services firebase.storage
|
|
952
|
+
// @pyric-evidence storage-rules#132
|
|
953
|
+
// Storage custom-metadata policies. Custom metadata is a flat string map.
|
|
954
|
+
|
|
955
|
+
export function hasRequiredMetadata(keys) {
|
|
956
|
+
return request.resource.metadata.keys().hasAll(keys);
|
|
957
|
+
}
|
|
958
|
+
|
|
959
|
+
export function metadataString(key, min, max) {
|
|
960
|
+
return request.resource.metadata[key] is string
|
|
961
|
+
&& request.resource.metadata[key].size() >= min
|
|
962
|
+
&& request.resource.metadata[key].size() <= max;
|
|
963
|
+
}
|
|
964
|
+
|
|
965
|
+
export function incomingMetadataOwner(key) {
|
|
966
|
+
return request.auth != null
|
|
967
|
+
&& request.resource.metadata[key] == request.auth.uid;
|
|
968
|
+
}
|
|
969
|
+
|
|
970
|
+
export function existingMetadataOwner(key) {
|
|
971
|
+
return request.auth != null
|
|
972
|
+
&& resource.metadata[key] == request.auth.uid;
|
|
973
|
+
}
|
|
974
|
+
`,"storage/objects":`// @pyric-services firebase.storage
|
|
975
|
+
// @pyric-evidence storage-rules#132
|
|
976
|
+
// Storage operation identity. Use request.method rather than null checks:
|
|
977
|
+
// production treats missing resource/request.resource bindings as errors.
|
|
978
|
+
|
|
979
|
+
export function isCreate() {
|
|
980
|
+
return request.method == 'create';
|
|
981
|
+
}
|
|
982
|
+
|
|
983
|
+
export function isUpdate() {
|
|
984
|
+
return request.method == 'update';
|
|
985
|
+
}
|
|
986
|
+
|
|
987
|
+
export function isDelete() {
|
|
988
|
+
return request.method == 'delete';
|
|
989
|
+
}
|
|
990
|
+
`,"storage/time":`// @pyric-services firebase.storage
|
|
991
|
+
// @pyric-evidence storage-rules#132
|
|
992
|
+
// Freshness checks over server-owned Storage object timestamps. Boundaries are
|
|
993
|
+
// strict: equality with the deadline is not "within" the window.
|
|
994
|
+
|
|
995
|
+
export function createdWithin(seconds) {
|
|
996
|
+
return request.time < resource.timeCreated + duration.value(seconds, 's');
|
|
997
|
+
}
|
|
998
|
+
|
|
999
|
+
export function updatedWithin(seconds) {
|
|
1000
|
+
return request.time < resource.updated + duration.value(seconds, 's');
|
|
1001
|
+
}
|
|
1002
|
+
`,"storage/uploads":`// @pyric-services firebase.storage
|
|
1003
|
+
// @pyric-evidence storage-rules#132
|
|
1004
|
+
// Storage upload request primitives. These inspect declared object metadata;
|
|
1005
|
+
// MIME helpers do not inspect or authenticate the uploaded bytes.
|
|
1006
|
+
|
|
1007
|
+
export function sizeAtMost(maxBytes) {
|
|
1008
|
+
return request.resource.size <= maxBytes;
|
|
1009
|
+
}
|
|
1010
|
+
|
|
1011
|
+
export function sizeBetween(minBytes, maxBytes) {
|
|
1012
|
+
return request.resource.size >= minBytes
|
|
1013
|
+
&& request.resource.size <= maxBytes;
|
|
1014
|
+
}
|
|
1015
|
+
|
|
1016
|
+
export function contentTypeMatches(pattern) {
|
|
1017
|
+
return request.resource.contentType.matches(pattern);
|
|
1018
|
+
}
|
|
1019
|
+
|
|
1020
|
+
export function contentTypeIsOneOf(types) {
|
|
1021
|
+
return request.resource.contentType in types;
|
|
1022
|
+
}
|
|
1023
|
+
`,timing:`// @pyric-services cloud.firestore
|
|
1024
|
+
// Timing module for cooldown / rate-limit enforcement.
|
|
1025
|
+
//
|
|
1026
|
+
// Rules CAN rate-limit (contrary to a common assumption — jrpg
|
|
1027
|
+
// FINDINGS F-004): compare request.time against a stored server
|
|
1028
|
+
// timestamp. Pair with lifecycle's isServerTimestamp on the SAME
|
|
1029
|
+
// write so the stored timestamp cannot be forged by the client:
|
|
1030
|
+
//
|
|
1031
|
+
// import { cooldownElapsed } from 'timing';
|
|
1032
|
+
// import { isServerTimestamp } from 'lifecycle';
|
|
1033
|
+
//
|
|
1034
|
+
// // At most one move every 2 seconds:
|
|
1035
|
+
// allow update: if cooldownElapsed('lastMoveAt', 2)
|
|
1036
|
+
// && isServerTimestamp('lastMoveAt');
|
|
1037
|
+
|
|
1038
|
+
// The stored timestamp is more than \`seconds\` old (strict). Update
|
|
1039
|
+
// rules only — needs \`resource\`. The field must be a Timestamp; a
|
|
1040
|
+
// missing field errors, which denies (fail-closed).
|
|
1041
|
+
export function cooldownElapsed(field, seconds) {
|
|
1042
|
+
return request.time > resource.data[field] + duration.value(seconds, 's');
|
|
1043
|
+
}
|
|
1044
|
+
`,transitions:`// @pyric-services cloud.firestore
|
|
1045
|
+
// Transitions module for state machine enforcement.
|
|
1046
|
+
//
|
|
1047
|
+
// Validates that a field transitions from one known value to another.
|
|
1048
|
+
// Use to enforce valid status flows (e.g., open -> in_progress -> completed).
|
|
1049
|
+
//
|
|
1050
|
+
// Usage:
|
|
1051
|
+
// import { validTransition, statusIs, newStatusIs } from 'transitions';
|
|
1052
|
+
//
|
|
1053
|
+
// // Only allow open -> in_progress
|
|
1054
|
+
// allow update: if validTransition('status', 'open', 'in_progress');
|
|
1055
|
+
//
|
|
1056
|
+
// // Allow update only when currently active
|
|
1057
|
+
// allow update: if statusIs('status', 'active');
|
|
1058
|
+
//
|
|
1059
|
+
// // Compound: multiple valid transitions via OR
|
|
1060
|
+
// allow update: if validTransition('status', 'open', 'in_progress')
|
|
1061
|
+
// || validTransition('status', 'in_progress', 'completed')
|
|
1062
|
+
// || validTransition('status', 'completed', 'archived');
|
|
1063
|
+
|
|
1064
|
+
// Check that a field transitions from one value to another.
|
|
1065
|
+
export function validTransition(field, from, to) {
|
|
1066
|
+
return resource.data[field] == from
|
|
1067
|
+
&& request.resource.data[field] == to;
|
|
1068
|
+
}
|
|
1069
|
+
|
|
1070
|
+
// Check the current (existing) value of a field.
|
|
1071
|
+
export function statusIs(field, value) {
|
|
1072
|
+
return resource.data[field] == value;
|
|
1073
|
+
}
|
|
1074
|
+
|
|
1075
|
+
// Check the incoming (new) value of a field.
|
|
1076
|
+
export function newStatusIs(field, value) {
|
|
1077
|
+
return request.resource.data[field] == value;
|
|
1078
|
+
}
|
|
1079
|
+
`,turns:`// @pyric-services cloud.firestore
|
|
1080
|
+
// Turn enforcement for 2-participant games/sessions.
|
|
1081
|
+
//
|
|
1082
|
+
// Convention: documents must have these fields:
|
|
1083
|
+
// host: string (UID)
|
|
1084
|
+
// guest: string (UID)
|
|
1085
|
+
// currentTurn: 'host' | 'guest'
|
|
1086
|
+
//
|
|
1087
|
+
// Usage:
|
|
1088
|
+
// import { isMyTurn, turnFlipped } from 'turns';
|
|
1089
|
+
//
|
|
1090
|
+
// allow update: if isMyTurn() && turnFlipped();
|
|
1091
|
+
|
|
1092
|
+
// Is the caller the participant whose turn it is?
|
|
1093
|
+
export function isMyTurn() {
|
|
1094
|
+
return (resource.data.currentTurn == 'host'
|
|
1095
|
+
&& request.auth.uid == resource.data.host)
|
|
1096
|
+
|| (resource.data.currentTurn == 'guest'
|
|
1097
|
+
&& request.auth.uid == resource.data.guest);
|
|
1098
|
+
}
|
|
1099
|
+
|
|
1100
|
+
// Did the turn alternate?
|
|
1101
|
+
export function turnFlipped() {
|
|
1102
|
+
return (resource.data.currentTurn == 'host'
|
|
1103
|
+
&& request.resource.data.currentTurn == 'guest')
|
|
1104
|
+
|| (resource.data.currentTurn == 'guest'
|
|
1105
|
+
&& request.resource.data.currentTurn == 'host');
|
|
1106
|
+
}
|
|
1107
|
+
`,validation:`// @pyric-services cloud.firestore
|
|
1108
|
+
// Validation module for document field shape and value checks.
|
|
1109
|
+
//
|
|
1110
|
+
// Usage:
|
|
1111
|
+
// import { hasRequired, hasOnly, validString, isOneOf } from 'validation';
|
|
1112
|
+
//
|
|
1113
|
+
// allow create: if hasRequired(['title', 'status'])
|
|
1114
|
+
// && validString('title', 1, 100)
|
|
1115
|
+
// && isOneOf('status', ['draft', 'published']);
|
|
1116
|
+
|
|
1117
|
+
export function hasRequired(fields) {
|
|
1118
|
+
return request.resource.data.keys().hasAll(fields);
|
|
1119
|
+
}
|
|
1120
|
+
|
|
1121
|
+
export function hasOnly(fields) {
|
|
1122
|
+
return request.resource.data.keys().hasOnly(fields);
|
|
1123
|
+
}
|
|
1124
|
+
|
|
1125
|
+
// Incoming field is a string with size in [min, max] (inclusive).
|
|
1126
|
+
// Uses dynamic access, so a MISSING field reads as null (not an
|
|
1127
|
+
// error) and fails the \`is string\` check — safe on optional fields.
|
|
1128
|
+
export function validString(field, min, max) {
|
|
1129
|
+
return request.resource.data[field] is string
|
|
1130
|
+
&& request.resource.data[field].size() >= min
|
|
1131
|
+
&& request.resource.data[field].size() <= max;
|
|
1132
|
+
}
|
|
1133
|
+
|
|
1134
|
+
// Enum check: the incoming field value is one of the allowed values.
|
|
1135
|
+
// (\`in\` on a list — NOT \`.includes()\`, which does not exist in rules.)
|
|
1136
|
+
export function isOneOf(field, values) {
|
|
1137
|
+
return request.resource.data[field] in values;
|
|
1138
|
+
}
|
|
1139
|
+
`};function Pf(){const t={};for(const[e,n]of Object.entries(jf))t[e]=n,t[`./stdlib/${e}.rules`]=n;return t}const Ic=Pf(),$f=new Set(Object.keys(Ic));function Yg(t,e){const n=Object.entries(e?.modules??{}),r=Object.fromEntries(n),s=new Set(n.map(([a])=>a)),i=new Set([...$f].filter(a=>!s.has(a)));return rh(null,t,{...e,modules:{...Ic,...r}},i)}const qf=`RtdbExpr {
|
|
1140
|
+
Expr = Ternary
|
|
1141
|
+
|
|
1142
|
+
Ternary
|
|
1143
|
+
= Logical "?" Ternary ":" Ternary -- ternary
|
|
1144
|
+
| Logical
|
|
1145
|
+
|
|
1146
|
+
Logical
|
|
1147
|
+
= Logical "&&" Comparison -- and
|
|
1148
|
+
| Logical "||" Comparison -- or
|
|
1149
|
+
| Comparison
|
|
1150
|
+
|
|
1151
|
+
Comparison
|
|
1152
|
+
= Comparison "===" Additive -- strictEq
|
|
1153
|
+
| Comparison "!==" Additive -- strictNeq
|
|
1154
|
+
| Comparison ">=" Additive -- gte
|
|
1155
|
+
| Comparison "<=" Additive -- lte
|
|
1156
|
+
| Comparison ">" Additive -- gt
|
|
1157
|
+
| Comparison "<" Additive -- lt
|
|
1158
|
+
| Comparison "==" Additive -- looseEq
|
|
1159
|
+
| Comparison "!=" Additive -- looseNeq
|
|
1160
|
+
| Additive
|
|
1161
|
+
|
|
1162
|
+
Additive
|
|
1163
|
+
= Additive "+" Multiplicative -- add
|
|
1164
|
+
| Additive "-" Multiplicative -- sub
|
|
1165
|
+
| Multiplicative
|
|
1166
|
+
|
|
1167
|
+
Multiplicative
|
|
1168
|
+
= Multiplicative "*" UnaryExpr -- mul
|
|
1169
|
+
| Multiplicative "/" UnaryExpr -- div
|
|
1170
|
+
| Multiplicative "%" UnaryExpr -- mod
|
|
1171
|
+
| UnaryExpr
|
|
1172
|
+
|
|
1173
|
+
UnaryExpr
|
|
1174
|
+
= "!" UnaryExpr -- not
|
|
1175
|
+
| "-" UnaryExpr -- neg
|
|
1176
|
+
| CallExpr
|
|
1177
|
+
|
|
1178
|
+
CallExpr
|
|
1179
|
+
= CallExpr "." ident "(" ListOf<Expr, ","> ")" -- methodCall
|
|
1180
|
+
| CallExpr "." ident -- memberAccess
|
|
1181
|
+
| CallExpr "[" Expr "]" -- indexAccess
|
|
1182
|
+
| Primary
|
|
1183
|
+
|
|
1184
|
+
Primary
|
|
1185
|
+
= "(" Expr ")" -- paren
|
|
1186
|
+
| Array
|
|
1187
|
+
| literal
|
|
1188
|
+
| ident
|
|
1189
|
+
|
|
1190
|
+
Array = "[" ListOf<Expr, ","> "]"
|
|
1191
|
+
|
|
1192
|
+
literal
|
|
1193
|
+
= number
|
|
1194
|
+
| string
|
|
1195
|
+
| regex
|
|
1196
|
+
| bool
|
|
1197
|
+
| null
|
|
1198
|
+
|
|
1199
|
+
number
|
|
1200
|
+
= digit+ "." digit+ -- float
|
|
1201
|
+
| digit+ -- int
|
|
1202
|
+
|
|
1203
|
+
string
|
|
1204
|
+
= "\\"" doubleStringChar* "\\"" -- double
|
|
1205
|
+
| "'" singleStringChar* "'" -- single
|
|
1206
|
+
|
|
1207
|
+
doubleStringChar
|
|
1208
|
+
= "\\\\" any -- escape
|
|
1209
|
+
| ~"\\"" any -- char
|
|
1210
|
+
|
|
1211
|
+
singleStringChar
|
|
1212
|
+
= "\\\\" any -- escape
|
|
1213
|
+
| ~"'" any -- char
|
|
1214
|
+
|
|
1215
|
+
regex = "/" regexBody "/" regexFlags
|
|
1216
|
+
|
|
1217
|
+
regexBody = regexChar+
|
|
1218
|
+
|
|
1219
|
+
regexChar
|
|
1220
|
+
= "\\\\" any -- escape
|
|
1221
|
+
| ~("/" | "\\n") any -- char
|
|
1222
|
+
|
|
1223
|
+
regexFlags = alnum*
|
|
1224
|
+
|
|
1225
|
+
bool
|
|
1226
|
+
= "true" ~identChar -- true
|
|
1227
|
+
| "false" ~identChar -- false
|
|
1228
|
+
|
|
1229
|
+
null = "null" ~identChar
|
|
1230
|
+
|
|
1231
|
+
ident = "$"? identStart identChar*
|
|
1232
|
+
|
|
1233
|
+
identStart = letter | "_"
|
|
1234
|
+
|
|
1235
|
+
identChar = alnum | "_" | "$"
|
|
1236
|
+
}
|
|
1237
|
+
`;let La;function Ec(){return La??=Zo(qf),La}function Uf(t){return Ec().match(t.trim())}function Bf(){return Ec().createSemantics()}function zf(t){return typeof t=="object"&&t!==null&&t.__type==="serverTimestamp"}const Vf={name:"date-to-timestamp",convert(t){return t instanceof Date?xe.fromMillis(t.getTime()):Je}},Wf={name:"server-timestamp-sentinel",convert(t,e){return zf(t)?e.serverTime instanceof xe?e.serverTime:xe.fromMillis(Date.now()):Je}};function Hf(t){if(t===null||typeof t!="object"||t instanceof xe)return!1;const e=t;return typeof e.seconds=="number"&&typeof e.nanoseconds=="number"&&typeof e.toMillis=="function"}const Gf={name:"user-timestamp-to-rules-timestamp",convert(t){return Hf(t)?new xe(t.seconds,t.nanoseconds):Je}};function Fa(t){return typeof t=="object"&&t!==null&&"isEqual"in t&&typeof t.isEqual=="function"}function Ws(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function Da(t){if(typeof t!="object"||t===null||Ws(t))return;const e=t;if(typeof e.seconds=="number"){const n=typeof e.nanoseconds=="number"?e.nanoseconds:e.nanos;if(typeof n=="number")return{kind:"timestamp",seconds:e.seconds,nanoseconds:n}}if(e.data instanceof Uint8Array)return{kind:"bytes",values:Array.from(e.data)};if(typeof e.toUint8Array=="function")return{kind:"bytes",values:Array.from(e.toUint8Array())};if(typeof e.latitude=="number"&&typeof e.longitude=="number")return{kind:"geo-point",latitude:e.latitude,longitude:e.longitude};if(typeof e.lat=="number"&&typeof e.lng=="number")return{kind:"geo-point",latitude:e.lat,longitude:e.lng};if(typeof e.path=="string")return{kind:"reference",path:e.path};if(e.typeName==="vector"&&Array.isArray(e.value))return{kind:"vector",values:e.value};if(typeof e.toArray=="function")return{kind:"vector",values:e.toArray()}}function Ye(t,e){if(Object.is(t,e))return!0;const n=Da(t),r=Da(e);if(n!==void 0||r!==void 0){if(n===void 0||r===void 0||n.kind!==r.kind)return!1;switch(n.kind){case"timestamp":return r.kind==="timestamp"&&n.seconds===r.seconds&&n.nanoseconds===r.nanoseconds;case"bytes":return r.kind==="bytes"&&n.values.length===r.values.length&&n.values.every((a,o)=>a===r.values[o]);case"vector":return r.kind==="vector"&&n.values.length===r.values.length&&n.values.every((a,o)=>a===r.values[o]);case"geo-point":return r.kind==="geo-point"&&n.latitude===r.latitude&&n.longitude===r.longitude;case"reference":return r.kind==="reference"&&n.path===r.path}}if(Fa(t))return t.isEqual(e);if(Fa(e))return e.isEqual(t);if(Array.isArray(t)||Array.isArray(e))return!Array.isArray(t)||!Array.isArray(e)||t.length!==e.length?!1:t.every((a,o)=>Ye(a,e[o]));if(!Ws(t)||!Ws(e))return!1;const s=Object.keys(t),i=Object.keys(e);return s.length!==i.length?!1:s.every(a=>a in e&&Ye(t[a],e[a]))}function Kf(t){return typeof t=="object"&&t!==null&&t.__type==="increment"&&typeof t.value=="number"}function Zf(t){return typeof t=="object"&&t!==null&&t.__type==="arrayUnion"&&Array.isArray(t.values)}function Jf(t){return typeof t=="object"&&t!==null&&t.__type==="arrayRemove"&&Array.isArray(t.values)}function Qf(t){return typeof t=="object"&&t!==null&&t.__type==="deleteField"}function Ii(t){if(t.prior===null)return;if(t.fieldPath==="")return t.prior;let e=t.prior;for(const n of t.fieldPath.split(".")){const r=/^([^\[]*)/.exec(n),s=r?r[1]:n;if(s){if(typeof e!="object"||e===null)return;e=e[s]}const i=/\[(\d+)\]/g;let a;for(;(a=i.exec(n))!==null;){if(!Array.isArray(e))return;e=e[Number(a[1])]}}return e}const Yf={name:"increment-sentinel",convert(t,e){if(!Kf(t))return Je;const n=Ii(e);return(typeof n=="number"?n:0)+t.value}},Xf={name:"array-union-sentinel",convert(t,e){if(!Zf(t))return Je;const n=Ii(e),r=Array.isArray(n)?n.slice():[];for(const s of t.values)r.some(a=>Ye(a,s))||r.push(s);return r}},ep={name:"array-remove-sentinel",convert(t,e){if(!Jf(t))return Je;const n=Ii(e);return Array.isArray(n)?n.filter(r=>!t.values.some(s=>Ye(r,s))):[]}},tp={name:"delete-field-sentinel",convert(t){return Qf(t)?at:Je}},Ma=Symbol.for("pyric.firestore.query-value-registry"),ja=globalThis,qn=ja[Ma]??(ja[Ma]=new WeakMap),Pa=Symbol.for("pyric.firestore.query-value-execution-registry"),$a=globalThis,Lr=$a[Pa]??($a[Pa]=new WeakMap),qa=Symbol.for("pyric.firestore.query-value-owner-registry"),Ua=globalThis,Fr=Ua[qa]??(Ua[qa]=new WeakMap);function tn(t,e,n=()=>t){qn.set(t,e),Lr.set(t,n)}function kc(t){return qn.get(t)}function np(t){return Fr.get(t)}function rp(t){return Lr.get(t)?.()??t}function sp(t,e){const n=qn.get(t),r=Lr.get(t);n!==void 0&&qn.set(e,n),r!==void 0&&Lr.set(e,r);const s=Fr.get(t);s!==void 0&&Fr.set(e,s)}const Hs=Symbol.for("pyric.firestore.reference-query-value");class ip{path;[Hs]=!0;constructor(e){this.path=e}isEqual(e){return typeof e=="object"&&e!==null&&Hs in e&&e.path===this.path}}function ap(t){const e=qn.get(t);if(typeof e!="object"||e===null||!(Hs in e))return;const n=e.path;return typeof n=="string"?n:void 0}function Ei(t,e,n,r=t){tn(t,new ip(e),()=>r),Fr.set(t,n)}function op(t){if(t===null||typeof t!="object"||t instanceof zt)return!1;const e=t;return typeof e.path=="string"&&typeof e.id=="string"&&e._path!==void 0&&e._firestore!==void 0}const cp={name:"document-reference",convert(t){if(typeof t=="object"&&t!==null){const e=ap(t);if(e!==void 0)return new zt(e)}return op(t)?new zt(t.path):Je}};function up(t){return Array.isArray(t)&&t.every(e=>typeof e=="number")}function lp(t){if(t===null||typeof t!="object"||t instanceof en)return null;const e=t;return up(e._values)&&typeof e.toArray=="function"?e._values:null}const dp={name:"vector-value",convert(t){const e=lp(t);return e===null?Je:new en(e)}};function hp(t){if(t===null||typeof t!="object"||t instanceof We)return!1;const e=t;return typeof e.toBase64=="function"&&typeof e.toUint8Array=="function"&&typeof e.isEqual=="function"}function fp(t){if(t===null||typeof t!="object"||t instanceof ot)return!1;const e=t;return typeof e.latitude=="number"&&typeof e.longitude=="number"&&typeof e.isEqual=="function"}const pp={name:"fb-bytes-to-rules-bytes",convert(t){return hp(t)?new We(t.toUint8Array()):Je}},mp={name:"fb-geopoint-to-rules-latlng",convert(t){return fp(t)?new ot(t.latitude,t.longitude):Je}},Je=Symbol("value-resolver:KEEP"),at=Symbol("value-resolver:DELETE_MARKER"),Gs=[];function Qe(t){Gs.some(e=>e.name===t.name)||Gs.push(t)}function nt(t,e){const n={};for(const[r,s]of Object.entries(t))n[r]=Ks(s,{...e,fieldPath:r});return n}function Ks(t,e){for(const n of Gs){const r=n.convert(t,e);if(r!==Je)return r}if(Array.isArray(t))return t.map((n,r)=>Ks(n,{...e,fieldPath:`${e.fieldPath}[${r}]`}));if(nn(t)){const n={};for(const[r,s]of Object.entries(t)){const i=e.fieldPath?`${e.fieldPath}.${r}`:r;n[r]=Ks(s,{...e,fieldPath:i})}return n}return t}function nn(t){if(t===null||typeof t!="object")return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function $t(t){const e={},n=[];for(const[r,s]of Object.entries(t)){if(s===at){n.push(r);continue}e[r]=Dr(s)}return{writes:e,deletedKeys:n}}function Dr(t){if(t!==at){if(Array.isArray(t))return t.filter(e=>e!==at).map(Dr);if(nn(t)){const e={};for(const[n,r]of Object.entries(t))r!==at&&(e[n]=Dr(r));return e}return t}}function gp(){Qe(Vf),Qe(Wf),Qe(Gf),Qe(Yf),Qe(Xf),Qe(ep),Qe(tp),Qe(cp),Qe(dp),Qe(pp),Qe(mp)}function Oc(t){return t.split(".")}const yp=new Set(["__proto__","prototype","constructor"]);function Ba(t){if(yp.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 ki(t){const e={};for(const[n,r]of Object.entries(t))e[n]=Cc(r);return e}function Cc(t){return Array.isArray(t)?t.map(Cc):nn(t)?ki(t):t}function Tc(t,e,n){let r=t;for(let i=0;i<e.length-1;i++){const a=e[i];Ba(a);const o=Object.hasOwn(r,a)?r[a]:void 0;nn(o)||(r[a]={}),r=r[a]}const s=e[e.length-1];Ba(s),n===at?delete r[s]:r[s]=Dr(n)}function za(t,e){const n=ki(t);for(const[r,s]of Object.entries(e)){if(s!==at&&Mr(s))throw new Rc;Tc(n,Oc(r),s)}return n}class Rc extends Error{constructor(){super("FieldValue.delete() can only appear at the top level of your update data"),this.name="DeleteFieldNestedError"}}function Mr(t){return t===at?!0:Array.isArray(t)?t.some(Mr):nn(t)?Object.values(t).some(Mr):!1}function bp(t){for(const e of Object.values(t))if(e!==at&&Mr(e))throw new Rc}function Zs(t,e,n){const r=ki(t),s=[];if(n!==void 0)for(const i of n){const a=Oc(i),o=vp(e,a);o!==Nc&&s.push({segments:a,value:o})}else Lc(e,[],s);for(const{segments:i,value:a}of s)Tc(r,i,a);return r}const Nc=Symbol("field-merge:ABSENT");function vp(t,e){let n=t;for(const r of e){if(!nn(n)||!Object.hasOwn(n,r))return Nc;n=n[r]}return n}function Lc(t,e,n){const r=Object.keys(t);if(r.length===0&&e.length>0){n.push({segments:e,value:{}});return}for(const s of r){const i=t[s],a=[...e,s];nn(i)&&i!==at?Lc(i,a,n):n.push({segments:a,value:i})}}function wp(t,e){const n={};for(const r of e)Object.prototype.hasOwnProperty.call(t,r)&&(n[r]=t[r]);return n}class ls{documents;versions=new Map;nextVersion=1;constructor(e={},n){this.documents=n??new Map;for(const[r,s]of Object.entries(e)){const i=nt({...s},{path:r,method:"seed",prior:null}),{writes:a}=$t(i);this.documents.set(r,a),this.bumpVersion(r)}}get(e){return this.documents.get(e)??null}version(e){return this.versions.get(e)??0}currentVersion(){return this.nextVersion-1}exists(e){return this.documents.has(e)}scan(e,n={}){const r=e===""||e.endsWith("/")?e:e+"/",s=n.projection?c=>wp(c,n.projection):c=>c,i=[],a=new Set,o=[];for(const[c,u]of this.documents){if(r!==""&&!c.startsWith(r))continue;if(!n.directOnly){i.push({path:c,data:s(u)});continue}const d=c.slice(r.length),l=d.indexOf("/");if(l===-1)i.push({path:c,data:s(u)}),a.add(d);else if(n.phantoms){const p=d.slice(0,l);p.length>0&&!o.includes(p)&&o.push(p)}}if(n.directOnly&&n.phantoms)for(const c of o)a.has(c)||i.push({path:r+c,data:{},phantom:!0});return i}list(e){return this.scan(e,{directOnly:!0,phantoms:!0})}listRootCollections(){const e=new Set,n=[];for(const r of this.documents.keys()){const s=r.split("/",1)[0];s.length!==0&&(e.has(s)||(e.add(s),n.push(s)))}return n}listSubcollections(e){const n=e.endsWith("/")?e:e+"/",r=new Set,s=[];for(const i of this.documents.keys()){if(!i.startsWith(n))continue;const o=i.slice(n.length).split("/",1)[0];o.length!==0&&(r.has(o)||(r.add(o),s.push(o)))}return s}snapshot(){const e={};for(const[n,r]of this.documents)e[n]={...r};return e}size(){return this.documents.size}create(e,n){if(this.documents.has(e))return{success:!1,error:`Document '${e}' already exists`};let r;try{const s=nt({...n},{path:e,method:"create",prior:null});r=$t(s).writes}catch(s){return{success:!1,error:s.message}}return this.documents.set(e,r),this.bumpVersion(e),{success:!0}}update(e,n){const r=this.documents.get(e);if(!r)return{success:!1,error:`Document '${e}' does not exist`};let s;try{const i=nt({...n},{path:e,method:"update",prior:r});s=za(r,i)}catch(i){return{success:!1,error:i.message}}return this.documents.set(e,s),this.bumpVersion(e),{success:!0,priorData:{...r}}}setMerge(e,n,r){const s=this.documents.has(e)?{...this.documents.get(e)}:null,i=nt({...n},{path:e,method:"set",prior:s}),a=Zs(s??{},i,r);return this.documents.set(e,a),this.bumpVersion(e),{success:!0,priorData:s,created:s===null}}set(e,n){const r=this.documents.has(e)?{...this.documents.get(e)}:null,s=nt({...n},{path:e,method:"set",prior:r}),{writes:i}=$t(s);return this.documents.set(e,i),this.bumpVersion(e),{success:!0,priorData:r,created:r===null}}delete(e){const n=this.documents.get(e);return n?(this.documents.delete(e),this.bumpVersion(e),{success:!0,priorData:{...n}}):{success:!1,error:`Document '${e}' does not exist`}}applyBatch(e){const n=[];for(let s=0;s<e.length;s++){const i=e[s];switch(i.method){case"create":this.documents.has(i.path)&&n.push({index:s,error:`Document '${i.path}' already exists`});break;case"update":this.documents.has(i.path)||n.push({index:s,error:`Document '${i.path}' does not exist`});break}}if(n.length>0)return{success:!1,errors:n};const r=new Map;for(const s of e)r.has(s.path)||r.set(s.path,this.documents.has(s.path)?{...this.documents.get(s.path)}:null);for(const s of e){switch(s.method){case"create":{const i=nt({...s.data},{path:s.path,method:"create",prior:null}),{writes:a}=$t(i);this.documents.set(s.path,a);break}case"update":{const i=this.documents.get(s.path),a=nt({...s.data},{path:s.path,method:"update",prior:i});this.documents.set(s.path,za(i,a));break}case"set":{const i=r.get(s.path)??null,a=nt({...s.data},{path:s.path,method:"set",prior:i}),{writes:o}=$t(a);this.documents.set(s.path,o);break}case"delete":this.documents.delete(s.path);break}this.bumpVersion(s.path)}return{success:!0,priorStates:r}}restore(e){const n=new Set([...this.documents.keys(),...Object.keys(e)]);this.documents.clear();for(const[r,s]of Object.entries(e))this.documents.set(r,{...s});for(const r of n)this.bumpVersion(r)}restorePaths(e){for(const[n,r]of Object.entries(e))r===null?this.documents.delete(n):this.documents.set(n,{...r}),this.bumpVersion(n)}bumpVersion(e){this.versions.set(e,this.nextVersion++)}}class Sp{base;overlay=new Map;tombstones=new Set;baseCache=new Map;cleared=!1;constructor(e){this.base=e}inBase(e){return Object.prototype.hasOwnProperty.call(this.base,e)}baseDoc(e){let n=this.baseCache.get(e);return n===void 0&&(n=structuredClone(this.base[e]),this.baseCache.set(e,n)),n}get(e){if(this.overlay.has(e))return this.overlay.get(e);if(!(this.cleared||this.tombstones.has(e)))return this.inBase(e)?this.baseDoc(e):void 0}set(e,n){this.overlay.set(e,n),this.tombstones.delete(e)}has(e){return this.overlay.has(e)?!0:this.cleared||this.tombstones.has(e)?!1:this.inBase(e)}delete(e){const n=this.has(e);return this.overlay.delete(e),!this.cleared&&this.inBase(e)&&this.tombstones.add(e),n}clear(){this.overlay.clear(),this.tombstones.clear(),this.baseCache.clear(),this.cleared=!0}get size(){let e=0;for(const n of this)e++;return e}*keys(){for(const[e]of this)yield e}*[Symbol.iterator](){const e=new Set;if(!this.cleared)for(const n of Object.keys(this.base))this.tombstones.has(n)||(e.add(n),yield[n,this.overlay.has(n)?this.overlay.get(n):this.baseDoc(n)]);for(const[n,r]of this.overlay)e.has(n)||(yield[n,r])}}class _p{events=[];nextId=1;undoneEvents=[];append(e,n=!1){const r={...e,id:this.nextId++,timestamp:new Date().toISOString()};return this.events.push(r),n||(this.undoneEvents=[]),r}getEvents(){return[...this.events]}getWriteEvents(){return this.events.filter(e=>e.allowed&&e.method!=="get"&&e.method!=="list")}lastWriteEvent(){const e=this.getWriteEvents();return e.length>0?e[e.length-1]:null}popLastWrite(){for(let e=this.events.length-1;e>=0;e--){const n=this.events[e];if(!n.aborted&&n.allowed&&n.method!=="get"&&n.method!=="list")return this.events.splice(e,1),this.undoneEvents.push(n),n}return null}popLastUndo(){return this.undoneEvents.pop()??null}size(){return this.events.length}clear(){this.events=[],this.undoneEvents=[],this.nextId=1}}function Ap(t){return new Date(t.toMillis()).toISOString()}class Wn extends Error{method;path;debugMessages;constructor(e,n,r,s){super(e),this.method=n,this.path=r,this.debugMessages=s,this.name="SimulatorUnsupportedError"}}function Hn(t,e,n){const r=n.filter(i=>i.includes("unsupported:")).map(i=>i.replace(/^.*unsupported:\s*/,"")).join("; "),s=r?` Reason(s): ${r}.`:"";return`Simulator cannot decide ${t} on ${e} — the rule uses a feature the local simulator does not yet implement.${s} Verify this rule against production using TestFirestoreRulesHandler, or file a sim-gap entry in REBUILD_PLAN.md.`}function xp(t=""){return{description:t,expectation:"ALLOW",state:"PASSED",decision:"ALLOW",trace:[],notes:["admin lens — rules bypassed (Studio Gap #2)"]}}const Ip=`rules_version = '2';
|
|
1238
|
+
service cloud.firestore {
|
|
1239
|
+
match /databases/{database}/documents {
|
|
1240
|
+
match /{document=**} {
|
|
1241
|
+
allow read, write: if true;
|
|
1242
|
+
}
|
|
1243
|
+
}
|
|
1244
|
+
}
|
|
1245
|
+
`;class Mt{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 n of this.subscribers)try{const r=n(...e);this.swallowAsyncRejections&&r&&typeof r.then=="function"&&r.catch(()=>{})}catch{}}clear(){this.subscribers.clear()}}class Ep{denial=new Mt;request=new Mt(!0);write=new Mt(!0);delivery=new Mt;suppressed=new Mt;lifecycle=new Mt;snapshotError=new Mt;clear(){this.denial.clear(),this.request.clear(),this.write.clear(),this.delivery.clear(),this.suppressed.clear(),this.lifecycle.clear(),this.snapshotError.clear()}}class kp{currentTrigger;run(e,n){const r=this.currentTrigger;this.currentTrigger=e;try{return n()}finally{this.currentTrigger=r}}current(){return this.currentTrigger}}class ue extends Error{code;simError;constructor(e){super(e.message),this.name="FirestoreError",this.code=e.code,this.simError=e}}const Va=Symbol.for("pyric.firestore.activity-value-registry"),Wa=globalThis,Fc=Wa[Va]??(Wa[Va]=new WeakMap);function Dc(){let t=2166136261,e=2654435769,n=2246822507,r=3266489909;const s=i=>{t=Math.imul(t^i,16777619),e=Math.imul(e^i,2246822507),n=Math.imul(n^i,3266489909),r=Math.imul(r^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,n,r].map(i=>(i>>>0).toString(16).padStart(8,"0")).join("")}}function Oi(...t){const e=Dc();for(const n of t)e.update(n);return e.finish()}function Op(t){return{type:"string-digest",length:t.length,digest:Oi("string\0",t)}}function Zt(t,...e){return{type:`${t}-digest`,digest:Oi(`${t}\0`,...e)}}function Cp(t){return{type:"bytes-digest",length:t.byteLength,digest:Oi("bytes\0",t)}}function Ha(t){const e=Dc(),n=(...s)=>{for(const i of s)e.update(i)},r=s=>{if(s===null){n("null;");return}switch(typeof s){case"string":n(`s${s.length}:`,s,";");return;case"number":n(`n${Object.is(s,-0)?"-0":String(s)};`);return;case"boolean":n(s?"b1;":"b0;");return;case"undefined":n("u;");return;case"bigint":n(`i${s.toString()};`);return;case"object":break;default:n(`x${typeof s};`);return}if(Array.isArray(s)){n(`a${s.length}[`);for(const o of s)r(o);n("];");return}const i=s,a=Object.keys(i).sort();n(`o${a.length}{`);for(const o of a)n(`k${o.length}:`,o,"="),r(i[o]);n("};")};return r(t),{type:"wire-value-digest",digest:e.finish()}}function ut(t,e){Fc.set(t,e)}function Tp(t){return Fc.get(t)}class Rp{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 xt{seconds;nanoseconds;constructor(e,n){this.seconds=e,this.nanoseconds=n,ut(this,Zt("timestamp",String(e),"\0",String(n))),tn(this,Object.freeze({type:"timestamp",seconds:e,nanoseconds:n}),()=>new xt(e,n))}static now(){return xt.fromMillis(Date.now())}static fromDate(e){return xt.fromMillis(e.getTime())}static fromMillis(e){const n=Math.floor(e/1e3),r=Math.floor((e-n*1e3)*1e6);return new xt(n,r)}toDate(){return new Date(this.toMillis())}toMillis(){return this.seconds*1e3+this.nanoseconds/1e6}isEqual(e){return e.seconds===this.seconds&&e.nanoseconds===this.nanoseconds}toString(){return`Timestamp(seconds=${this.seconds}, nanoseconds=${this.nanoseconds})`}toJSON(){return{type:"firestore/timestamp/1.0",seconds:this.seconds,nanoseconds:this.nanoseconds}}valueOf(){const n=this.seconds- -62135596800,r=String(n).padStart(12,"0"),s=String(this.nanoseconds).padStart(9,"0");return`${r}.${s}`}}function Js(t){return t instanceof xe?new xt(t.seconds,t.nanos):t instanceof We||t instanceof ot||t instanceof en?t:Array.isArray(t)?t.map(Js):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).map(([e,n])=>[e,Js(n)])):t}function Gn(t){return Js(t)}const Np=/[*~/[\]]/,Lp=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class jr{_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((n,r)=>{if(typeof n!="string")throw new Error(`Element at index ${r} is not a valid string.`);if(n.length===0)throw new Error(`Element at index ${r} should not be an empty string.`)}),this._internalPath={segments:[...e],offset:0,len:e.length}}static DOCUMENT_ID=new jr("__name__");static documentId(){return jr.DOCUMENT_ID}isEqual(e){const n=Mc(e),r=this._internalPath.segments;return r.length===n.length&&r.every((s,i)=>s===n[i])}toString(){return this._internalPath.segments.map(e=>Lp.test(e)?e:`\`${e.replace(/\\/g,"\\\\").replace(/`/g,"\\`")}\``).join(".")}}function xn(t){return new Error(`Value for argument "field" is not a valid field path. ${t}`)}function Mc(t){if(t instanceof jr)return t._internalPath.segments;if(typeof t=="object"&&t!==null){const e=t._internalPath;if(Array.isArray(e?.segments)&&e.segments.every(n=>typeof n=="string"))return[...e.segments]}if(t===void 0)throw xn("The path cannot be omitted.");if(typeof t!="string")throw xn("Paths can only be specified as strings or via a FieldPath object.");if(t.includes(".."))throw xn('Paths must not contain ".." in them.');if(t.startsWith(".")||t.endsWith("."))throw xn('Paths must not start or end with ".".');if(t.length===0||Np.test(t))throw xn(`Paths can't be empty and must not contain
|
|
1246
|
+
"*~/[]".`);return t.split(".")}function Fp(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function wn(t,e){const n=Mc(e);let r=t;for(const s of n){if(!Fp(r))return;r=Object.prototype.hasOwnProperty.call(r,s)?r[s]:void 0}return r}const gn=Object.freeze({hasPendingWrites:!1,fromCache:!1}),Ga=Object.freeze({hasPendingWrites:!0,fromCache:!1});function jc(t){const e=t.lastIndexOf("/");return e===-1?t:t.slice(e+1)}function on(t,e,n=gn){const r={id:jc(t),path:t},s=e!==null,i=s?Gn(e):void 0;return{id:r.id,ref:r,metadata:n,exists:()=>s,data:()=>i,get:a=>wn(i,a)}}function Pc(t,e,n=gn){const r={id:jc(t),path:t},s=Gn(e);return{id:r.id,ref:r,metadata:n,exists:()=>!0,data:()=>s,get:i=>wn(s,i)}}function cn(t,e,n,r,s=gn){const i=e.map(u=>Pc(u.path,u.data,s)),a=r?Dp(r,e,i,s):i.map((u,d)=>({type:"added",doc:u,oldIndex:-1,newIndex:d}));let o=null,c=null;return{query:t,metadata:s,size:i.length,empty:i.length===0,docs:i,forEach(u){for(const d of i)u(d)},docChanges(u){const d=!!u?.includeMetadataChanges;if(d&&n.excludesMetadataChanges)throw new Error("To include metadata changes with your document changes, you must also pass { includeMetadataChanges: true } to onSnapshot().");return d?(c||(c=a.slice()),c):(o||(o=a.slice()),o)}}}function Dp(t,e,n,r=gn){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:Pc(c.path,c.data,r),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:n[o],oldIndex:-1,newIndex:o});else{const d=t[u].data;JSON.stringify(d)!==JSON.stringify(c.data)&&a.push({type:"modified",doc:n[o],oldIndex:u,newIndex:o})}}return a}function Ka(t,e){return t===null&&e===null?!0:t===null||e===null?!1:JSON.stringify(t)===JSON.stringify(e)}function Mp(t,e){const n=`${e}/`;for(const r of t){if(!r.startsWith(n))continue;const s=r.slice(n.length);if(s.length>0&&!s.includes("/"))return!0}return!1}let ds=0;function Ln(){return ds=ds+1>>>0,`req-${ds.toString(36)}-${Math.random().toString(36).slice(2,7)}`}function jp(t,e){const n=e==="allow";let r;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(n&&i[3]==="ALLOW")return a;r=a}return r}function Zr(t){const e={kind:"request",id:Ln(),at:t.at,evalMs:t.evalMs,method:t.method,path:t.path,auth:t.auth?{uid:t.auth.uid,...t.auth.token?{token:t.auth.token}:{}}:null,result:t.result,reasons:t.debugMessages,origin:t.origin};t.resourceData!==void 0&&(e.request={resourceData:t.resourceData}),t.resourceBefore!==void 0&&(e.resourceBefore=t.resourceBefore),t.resourceAfter!==void 0&&(e.resourceAfter=t.resourceAfter);const n=jp(t.debugMessages,t.result);return n&&(e.matchedRule=n),t.result!=="unsupported"&&t.evaluatedRule&&(e.evaluatedRule=t.evaluatedRule),t.groupId!==void 0&&(e.groupId=t.groupId,t.origin==="batch"?e.groupKind="batch":t.origin==="transaction"&&(e.groupKind="transaction")),t.triggeredBy!==void 0&&(e.triggeredBy=t.triggeredBy),t.detail!==void 0&&(e.detail=t.detail),t.provenance!==void 0&&Object.assign(e,t.provenance),e}class Pp{events;triggerScope;host;snapshotListeners=new Map;nextListenerId=0;deliveryQueue=[];deliveryScheduled=!1;constructor(e,n,r){this.events=e,this.triggerScope=n,this.host=r}emitSnapshotDelivery(e){if(!this.events.delivery.hasSubscribers)return;const n={kind:"snapshot_delivery",id:Ln().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(n)}emitSnapshotSuppressed(e){if(!this.events.suppressed.hasSubscribers)return;const n={kind:"snapshot_suppressed",id:Ln().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(n)}emitLifecycle(e){if(!this.events.lifecycle.hasSubscribers)return;const n={kind:e.phase,id:Ln().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(n)}emitSnapshotError(e,n,r){this.events.snapshotError.emit(e,n,r)}addSnapshotListener(e,n,r={},s=null,i,a=!1,o=!1,c){const u=String(this.nextListenerId++),d={id:u,target:e,callback:n,auth:s,bypassRules:o,followsCurrentUser:a,...c?{authScope:c}:{},options:r,currentSnapshot:void 0,errored:!1,...i?{errorCallback:i}:{}};return this.snapshotListeners.set(u,d),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(d)}),()=>{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=on(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 n=this.host.silentReadCollection(e.target.collection,e.auth,e.target.constraints,e.bypassRules);if(!n.allowed){this.markErrored(e,n.error);return}const r=cn({path:e.target.collection},n.docs,{excludesMetadataChanges:!e.options.includeMetadataChanges});e.currentSnapshot=r,e.currentDocs=n.docs;try{e.callback(r)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"query",collection:e.target.collection},auth:e.auth,addedCount:n.docs.length,modifiedCount:0,removedCount:0,size:n.docs.length,sample:{docs:n.docs.map(s=>({path:s.path,data:s.data}))}})}scheduleDelivery(e){this.deliveryQueue.push(e),!this.deliveryScheduled&&(this.deliveryScheduled=!0,queueMicrotask(()=>this.drainDeliveries()))}scheduleTriggeredDelivery(e,n){this.scheduleDelivery(()=>this.triggerScope.run(e,n))}drainDeliveries(){for(this.deliveryScheduled=!1;this.deliveryQueue.length>0;)this.deliveryQueue.shift()()}flushListeners(){this.drainDeliveries()}notifyListenersForPaths(e){if(e.size===0||this.snapshotListeners.size===0)return;const n=this.triggerScope.current(),r=Array.from(this.snapshotListeners.values());for(const s of r)this.scheduleTriggeredDelivery(n,()=>{this.snapshotListeners.has(s.id)&&(s.errored||(s.target.kind==="doc"?this.notifyDocListener(s,e):this.notifyQueryListener(s,e)))})}notifyDocListener(e,n){if(e.target.kind!=="doc"||!n.has(e.target.path))return;const r=this.host.silentReadDoc(e.target.path,e.auth,e.bypassRules);if(!r.allowed){this.markErrored(e,r.error);return}const s=e.currentDocData??null;if(Ka(s,r.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=on(i,r.data,Ga);e.currentSnapshot=a,e.currentDocData=r.data;const o=s!==null,c=r.data!==null,u=!o&&c?1:0,d=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:d,size:c?1:0,sample:{docs:[{path:i,data:r.data}]},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),this.scheduleDocMetadataAck(e,i,r.data)}scheduleDocMetadataAck(e,n,r){e.options.includeMetadataChanges&&this.scheduleTriggeredDelivery(this.triggerScope.current(),()=>{if(!this.snapshotListeners.has(e.id)||e.errored)return;const s=on(n,r,gn);e.currentSnapshot=s;try{e.callback(s)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"doc",path:n},auth:e.auth,addedCount:0,modifiedCount:0,removedCount:0,size:r!==null?1:0,sample:{docs:[{path:n,data:r}]},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}})})}notifyQueryListener(e,n){if(e.target.kind!=="query"||!Mp(n,e.target.collection))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 s=e.target.collection,i=e.currentDocs??[],a=cn({path:s},r.docs,{excludesMetadataChanges:!e.options.includeMetadataChanges},i,Ga),o=a.docChanges();if(o.length===0){if(e.options.includeMetadataChanges){e.currentSnapshot=a,e.currentDocs=r.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:r.docs.length,sample:{docs:r.docs.map(l=>({path:l.path,data:l.data}))},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),this.scheduleQueryMetadataAck(e,s,r.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=r.docs;let c=0,u=0,d=0;for(const l of o)l.type==="added"?c++:l.type==="modified"?u++:l.type==="removed"&&d++;try{e.callback(a)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"query",collection:s},auth:e.auth,addedCount:c,modifiedCount:u,removedCount:d,size:r.docs.length,sample:{docs:r.docs.map(l=>({path:l.path,data:l.data}))},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),this.scheduleQueryMetadataAck(e,s,r.docs)}scheduleQueryMetadataAck(e,n,r){e.options.includeMetadataChanges&&this.scheduleTriggeredDelivery(this.triggerScope.current(),()=>{if(!this.snapshotListeners.has(e.id)||e.errored)return;const s=cn({path:n},r,{excludesMetadataChanges:!1},r,gn);e.currentSnapshot=s;try{e.callback(s)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"query",collection:n},auth:e.auth,addedCount:0,modifiedCount:0,removedCount:0,size:r.length,sample:{docs:r.map(i=>({path:i.path,data:i.data}))},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}})})}markErrored(e,n){if(e.errored=!0,this.emitSnapshotError(n,e.target,e.id),!!e.errorCallback)try{e.errorCallback(n)}catch{}}reEvaluateAllListeners(){if(this.snapshotListeners.size===0)return;const e=Array.from(this.snapshotListeners.values());for(const n of e)this.snapshotListeners.has(n.id)&&(n.target.kind==="doc"?this.reEvaluateDocListener(n):this.reEvaluateQueryListener(n))}reevaluateLiveListeners(e,n){if(this.snapshotListeners.size===0)return;const r=Array.from(this.snapshotListeners.values());for(const s of r)s.followsCurrentUser&&s.authScope===n&&this.snapshotListeners.has(s.id)&&(s.auth=e,s.target.kind==="doc"?this.reEvaluateDocListener(s):this.reEvaluateQueryListener(s))}reEvaluateDocListener(e){if(e.target.kind!=="doc")return;const n=this.host.silentReadDoc(e.target.path,e.auth,e.bypassRules);if(!n.allowed){if(e.errored)return;this.markErrored(e,n.error);return}if(e.errored){e.errored=!1;const i=on(e.target.path,n.data);e.currentSnapshot=i,e.currentDocData=n.data;try{e.callback(i)}catch{}return}const r=e.currentDocData??null;if(Ka(r,n.data))return;const s=on(e.target.path,n.data);e.currentSnapshot=s,e.currentDocData=n.data;try{e.callback(s)}catch{}}reEvaluateQueryListener(e){if(e.target.kind!=="query")return;const n=this.host.silentReadCollection(e.target.collection,e.auth,e.target.constraints,e.bypassRules);if(!n.allowed){if(e.errored)return;this.markErrored(e,n.error);return}if(e.errored){e.errored=!1;const a=cn({path:e.target.collection},n.docs,{excludesMetadataChanges:!e.options.includeMetadataChanges});e.currentSnapshot=a,e.currentDocs=n.docs;try{e.callback(a)}catch{}return}const r=e.currentDocs??[],s=cn({path:e.target.collection},n.docs,{excludesMetadataChanges:!e.options.includeMetadataChanges},r);if(s.docChanges().length!==0){e.currentSnapshot=s,e.currentDocs=n.docs;try{e.callback(s)}catch{}}}getSnapshotListenerCount(){return this.snapshotListeners.size}dispose(){this.snapshotListeners.clear(),this.deliveryQueue.length=0,this.deliveryScheduled=!1}}class $p{eventLog;host;constructor(e,n){this.eventLog=e,this.host=n}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 n=e.type==="batch"&&e.operations?e.operations.map(o=>o.path):e.path?[e.path]:[],r=!!e.snapshot,s=r?void 0:this.host.capturePriors(n),i=r?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 qp{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:wi(this.currentSource)}),this.parsedCache.ast}}function te(t,e,n){const r={code:t,message:e};return n!==void 0&&(n.request!==void 0&&(r.request=n.request),n.resource!==void 0&&(r.resource=n.resource),n.remediation!==void 0&&(r.remediation=n.remediation),n.query!==void 0&&(r.query=n.query),n.rule!==void 0&&(r.rule=n.rule)),r}function Jr(t,e,n){const r=t.get(e.path),s=e.method==="set"?r!==null?"update":"create":e.method;let i=e.data;if(e.method==="get"||e.method==="list")i=void 0;else if(e.method==="update"&&r&&e.data){const{writes:a,deletedKeys:o}=$t(e.data),c={...r,...a};for(const u of o)delete c[u];i=c}else e.data&&(i=$t(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:r??void 0,...n?{requestTime:Ap(n)}:{}}}function $c(t,e,n,r,s,i){if(s){const a=r.map(o=>xp(o.description));return{success:!0,data:{passed:a.length,failed:0,unsupported:0,results:a}}}return n.simulate(e.source,r,{getDoc:a=>t.get(a),...i?{batchProjection:i}:{}})}class Up{events;rules;simulator;host;eventLog;constructor(e,n,r,s,i){this.events=e,this.rules=n,this.simulator=r,this.host=s,this.eventLog=i}get state(){return this.host.state}emitRequest(e){this.events.request.hasSubscribers&&this.events.request.emit(Zr(e))}emitDenial(e){this.events.denial.emit(e)}execute(e){const{method:n,path:r,auth:s,bypassRules:i}=e;let a;i===!0&&(a={admin:!0});const c=xe.fromMillis(Date.now()),u=Jr(this.state,e,c),d=Date.now(),l=performance.now(),p=$c(this.state,this.rules,this.simulator,[u],i),y=performance.now()-l;let b=null;if(s!==void 0&&s!==null&&(b={uid:s.uid}),p.success===!0===!1){const h=this.eventLog.append({type:"single",method:n,path:r,auth:b,allowed:!1,debugMessages:[`Simulation error: ${p.error.message}`]}),g={at:d,evalMs:y,method:n,path:r,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:h}}const I=p.data.results[0];if(I.state==="UNSUPPORTED"){const h={at:d,evalMs:y,method:n,path:r,auth:s,result:"unsupported",debugMessages:Se(I),origin:"user"};throw a!==void 0&&(h.detail=a),this.emitRequest(h),new Wn(Hn(n,r,Se(I)),n,r,Se(I))}const N=I.state==="PASSED";let q;N&&(n==="get"?q=this.state.get(r):q=this.state.list(r));const S=this.eventLog.append({type:"single",method:n,path:r,auth:b,allowed:N,debugMessages:Se(I)}),k={allowed:N,debugMessages:Se(I),event:S};N&&(k.data=q);const _=Kt(I);if(N===!1){const g={request:{method:n,path:r,auth:s}};if(n==="get"){const O=this.state.get(r),T=O!==null;g.resource={data:O,exists:T}}_!==void 0&&(g.rule=_),k.error=te("permission-denied",`${n} ${r} denied by rules`,g),this.emitDenial(k.error)}let v="deny";N&&(v="allow");const A={at:d,evalMs:y,method:n,path:r,auth:s,result:v,debugMessages:Se(I),evaluatedRule:_,origin:"user"};if(n==="get"){const h=this.state.get(r),g=h!==null;A.resourceBefore={data:h,exists:g}}return a!==void 0&&(A.detail=a),this.emitRequest(A),k}}function qc(t){const e=new Map,n=new Set;for(const r of t)e.has(r.name)&&n.add(r.name),e.set(r.name,r);return{functions:e,ambiguousNames:n}}function Uc(t,e,n,r=Bp){const s=new Set;return{pathInvariant:!ir(t,e,n,r,new Set,new Set,s),requiredFunctions:s}}function ir(t,e,n,r,s,i,a){const o=c=>ir(c,e,n,r,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"?!Za.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"&&Za.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)||r.has(t.name))return!0;const c=n.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),d=new Set(c.parameters);for(const l of c.lets){if(ir(l.value,e,n,r,d,u,a))return!0;d.add(l.name)}return ir(c.body,e,n,r,d,u,a)}}}const Za=new Set(["auth","method","query","time"]),Bp=new Set;function zp(t){if(!t)return null;const e=[...t.functions??[],...t.service.functions??[],...t.service.match.functions],n=new Set,r=t.service.match.children.flatMap(i=>{const a=Vp(i,e,n);return a?[a]:[]});if(r.length===0)return null;const s=i=>i?.filter(a=>n.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:r}}}}function Vp(t,e,n){const r=t.path.segments[0];if(t.path.segments.length!==1||r?.type!=="recursive")return null;const s=qc([...e,...t.functions]),i=t.allows.filter(a=>{if(!a.operations.some(c=>c==="list"||c==="read"))return!1;const o=Uc(a.condition,new Set([r.name]),s.functions,s.ambiguousNames);if(o.pathInvariant)for(const c of o.requiredFunctions)n.add(c);return o.pathInvariant});return i.length===0?null:{...t,functions:t.functions.filter(a=>n.has(a.name)),allows:i,children:[]}}function Wp(t,e,n,r,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(...wr(w,a,o));if(c.length===0)return{kind:"no-rule"};const d=[],l=new Set;let p=0;for(const w of c){const R=qc(w.functions),C=R.functions;for(const I of w.block.allows){if(I.operations.some(_=>_==="list"?!0:_==="read")===!1)continue;if(p++,Uc(I.condition,new Set(w.candidateVariables),C,R.ambiguousNames).pathInvariant===!0===!1){d.push({reason:"list rule depends on the candidate document path",residual:{missing:[],mismatched:[]},rule:I});continue}const S=Qh(I.condition,r,C,n?.uid);S.provable===!0?l.add(I):d.push({reason:S.reason,residual:S.residual,rule:I})}}if(p===0)return{kind:"no-rule"};if(l.size===0){const w=d[0];let R="list rule depends on per-document data the query cannot guarantee",C={missing:[],mismatched:[]},I;if(w!==void 0&&(R=w.reason,C=w.residual,w.rule!==void 0)){const k=w.rule,_=ve(k.condition);if(I={verdict:"deny",expression:_},k.loc!==void 0){const A=k.loc;let x="";s!==void 0&&(x=s);const h=pc(x,A.line,A.col,A.file,_);h!==void 0?(I.line=h.line,I.col=h.col,I.column=h.col,I.file=h.file,I.citation=h.citation,h.expression!==void 0&&(I.expression=h.expression)):(I.line=A.line,I.col=A.col,I.column=A.col,A.file!==void 0?(I.file=A.file,I.citation=`${A.file}:${A.line}:${A.col}`):(I.file="firestore.rules",I.citation=`firestore.rules:${A.line}:${A.col}`))}}const N={kind:"unprovable",reason:R,residual:C};return I!==void 0&&(N.rule=I),N}return{kind:"provable",evaluationAst:Hp(t,l),syntheticResource:Gp(r)}}function Hp(t,e){const n=r=>({...r,allows:r.allows.filter(s=>e.has(s)),children:r.children.map(n)});return{...t,service:{...t.service,match:n(t.service.match)}}}function Gp(t){const e={};for(const n of t.where??[])n.op==="=="&&(e[n.field]=n.value);return e}function Kp(t){const e=[];for(const r of t.missing)r.fromAuthUid?e.push(` .where('${r.field}', '==', request.auth.uid) // request.auth.uid is ${JSON.stringify(r.expectedValue)}`):e.push(` .where('${r.field}', '==', ${JSON.stringify(r.expectedValue)})`);for(const r of t.mismatched)e.push(` .where('${r.field}', '==', ${JSON.stringify(r.expectedValue)}) // the query pins ${JSON.stringify(r.actualValue)}, but the rule requires ${JSON.stringify(r.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:
|
|
1247
|
+
${e.join(`
|
|
1248
|
+
`)}`}function Zp(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 Jp{events;rules;simulator;host;constructor(e,n,r,s){this.events=e,this.rules=n,this.simulator=r,this.host=s}authorize(e){const{path:n,auth:r,constraints:s,origin:i,triggeredBy:a}=e,o=Zp(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,d=e.timing?.requestTime??(e.bypassRules?void 0:xe.fromMillis(Date.now())),l=e.timing?.at??Date.now();if(e.bypassRules)return this.emitRequest({at:l,evalMs:0,method:"list",path:n,auth:r,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?zp(p):p;if(e.collectionGroup&&!y){const v=`list ${n} 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:n,auth:r,result:"deny",debugMessages:[v],origin:i,...u?{detail:u}:{},...a?{triggeredBy:a}:{}});const A=te("permission-denied",v,{request:{method:"list",path:n,auth:r},query:s});return this.emitUserDenial(i,A),{allowed:!1,error:A}}const b=`${n}/__listPlaceholder__`,w=performance.now(),R=Wp(y,b,r,s,this.rules.source);if(R.kind==="unprovable"){const v=`list ${n} denied: the query is statically unprovable for every possible result (rules are not filters), so the whole query is rejected — ${R.reason}`,A=Kp(R.residual),x={at:l,evalMs:performance.now()-w,method:"list",path:n,auth:r,result:"deny",debugMessages:[v],origin:i};u!==void 0&&(x.detail=u),a!==void 0&&(x.triggeredBy=a),this.emitRequest(x);const g={request:{method:"list",path:n,auth:r},query:s};A!==void 0&&A!==""&&(g.remediation=A),R.rule!==void 0&&(g.rule=R.rule);const O=te("permission-denied",v,g);return this.emitUserDenial(i,O),{allowed:!1,error:O}}const I=R.kind==="provable"?aa(R.evaluationAst):e.collectionGroup?aa(y):this.rules.source,E=Jr(this.host.state,{method:"list",path:b,auth:r},d);this.applyProof(E,R,s);const N=this.simulator.simulate(I,[E],{getDoc:v=>this.host.state.get(v)}),q=performance.now()-w;if(!N.success)return this.emitRequest({at:l,evalMs:q,method:"list",path:n,auth:r,result:"deny",debugMessages:[`Simulation error: ${N.error.message}`],origin:i,...u?{detail:u}:{},...a?{triggeredBy:a}:{}}),{allowed:!1,error:te("permission-denied",`list ${n} simulator error`,{request:{method:"list",path:n,auth:r}})};const S=N.data.results[0],k=Se(S);if(S.state==="UNSUPPORTED")throw this.emitRequest({at:l,evalMs:q,method:"list",path:n,auth:r,result:"unsupported",debugMessages:k,origin:i,...u?{detail:u}:{},...a?{triggeredBy:a}:{}}),new Wn(Hn("list",n,k),"list",n,k);if(S.state!=="PASSED"){const v=Kt(S),A={at:l,evalMs:q,method:"list",path:n,auth:r,result:"deny",debugMessages:k,evaluatedRule:v,origin:i};u!==void 0&&(A.detail=u),a!==void 0&&(A.triggeredBy=a),this.emitRequest(A);const h={request:{method:"list",path:n,auth:r}};v!==void 0&&(h.rule=v);const m=te("permission-denied",`list ${n} denied by rules`,h);return this.emitUserDenial(i,m),{allowed:!1,error:m}}return this.emitRequest({at:l,evalMs:q,method:"list",path:n,auth:r,result:"allow",debugMessages:k,evaluatedRule:Kt(S),origin:i,...u?{detail:u}:{},...a?{triggeredBy:a}:{}}),{allowed:!0}}applyProof(e,n,r){n.kind==="provable"&&(e.resource=n.syntheticResource),(r.limit!=null||r.offset!=null||r.orderBy!=null)&&(e.query={...r.limit!=null?{limit:r.limit}:{},...r.offset!=null?{offset:r.offset}:{},...r.orderBy!=null?{orderBy:r.orderBy}:{}})}emitRequest(e){this.events.request.hasSubscribers&&this.events.request.emit(Zr(e))}emitUserDenial(e,n){e==="user"&&this.events.denial.emit(n)}}function Qp(t,e,n){if(e<=0)return[];const r=[];for(const s of t)r.length<e?Ja(r,s,n):n(s,r[r.length-1])<0&&(r.pop(),Ja(r,s,n));return r}function Ja(t,e,n){let r=0,s=t.length;for(;r<s;){const i=r+s>>1;n(e,t[i])<0?s=i:r=i+1}t.splice(r,0,e)}function Yp(t){return typeof t.seconds=="number"&&(typeof t.nanos=="number"||typeof t.nanoseconds=="number")}function Xp(t){return typeof t.latitude=="number"&&typeof t.longitude=="number"}function em(t){return t.data instanceof Uint8Array}function tm(t){return typeof t.path=="string"}function Pr(t){if(t==null)return 0;const e=typeof t;if(e==="boolean")return 1;if(e==="number"||e==="bigint")return 2;if(e==="string")return 4;if(Array.isArray(t))return 8;if(e==="object"){const n=t;return Yp(n)?3:em(n)?5:Xp(n)?7:tm(n)?6:9}return 9}function Qa(t){const e=typeof t.nanos=="number"?t.nanos:t.nanoseconds??0;return[t.seconds,e]}function nm(t,e){const n=Number.isNaN(t),r=Number.isNaN(e);return n&&r?0:n?-1:r?1:t<e?-1:t>e?1:0}function Ya(t,e){return t<e?-1:t>e?1:0}function Rt(t,e){const n=Pr(t),r=Pr(e);if(n!==r)return n<r?-1:1;switch(n){case 0:return 0;case 1:return t===e?0:t?1:-1;case 2:return nm(Number(t),Number(e));case 3:{const[s,i]=Qa(t),[a,o]=Qa(e);return s!==a?s<a?-1:1:i<o?-1:i>o?1:0}case 4:return Ya(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 Ya(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=Rt(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 d=Rt(s[a[u]],i[o[u]]);if(d!==0)return d}return a.length<o.length?-1:a.length>o.length?1:0}default:return 0}}function rm(t){const e=t.kind;if(e==="collection"){const n=t.path;return Object.freeze({kind:e,path:n})}if(e==="collection-group"){const n=t.collectionId;return Object.freeze({kind:e,collectionId:n})}throw new ue({code:"invalid-argument",message:`Unknown query scope kind: ${String(e)}`})}function Xa(t){const e=u=>{const d=u.kind;if(d==="where"){const p=u.field,y=u.op,b=u.value;return Object.freeze({kind:d,field:p,op:y,value:b})}if(d!=="and"&&d!=="or")throw new ue({code:"invalid-argument",message:`Unknown query filter kind: ${String(d)}`});const l=u.filters;return Object.freeze({kind:d,filters:Object.freeze(Array.from(l,e))})},n=u=>{if(u===void 0)return;const d=u.values,l=u.inclusive,p=u.fromSnapshot;return Object.freeze({values:Object.freeze(Array.from(d)),inclusive:l,fromSnapshot:p})},r=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(r,e)),orders:Object.freeze(Array.from(s,u=>{const d=u.field,l=u.direction;return Object.freeze({field:d,direction:l})})),limitCount:i,limitFromEnd:a,start:n(o),end:n(c)})}function eo(t){const e=[],n=r=>{if(r.kind==="where"){if(r.field===Et)return;const s=r.value;(s===null||typeof s=="string"||typeof s=="number"||typeof s=="boolean")&&e.push(Object.freeze({field:r.field,op:r.op,value:s}));return}r.kind==="and"&&r.filters.forEach(n)};return t.filters.forEach(n),Object.freeze({where:Object.freeze(e),limit:t.limitCount??null,offset:null,orderBy:t.orders.length>0?t.orders[0].field:null})}function sm(t,e){if(e.kind==="collection")return t.scan(e.path,{directOnly:!0});const n=[];for(const[r,s]of Object.entries(t.snapshot())){const i=r.split("/").filter(a=>a.length>0);i.length>0&&i.length%2===0&&i[i.length-2]===e.collectionId&&n.push({path:r,data:s})}return n}const Et="__name__",im=new Set(["<","<=",">",">=","!=","not-in"]);function Qs(t,e){return e===Et?{path:t.path}:t.data[e]}function Ci(t){return t.kind==="where"?im.has(t.op)?[t.field]:[]:t.filters.flatMap(Ci)}function am(t){return Ci(t).length>0}function Qr(t,e){return Pr(t)===Pr(e)}function om(t,e){return Qr(t,e)&&Rt(t,e)<0}function cm(t,e){return Qr(t,e)&&Rt(t,e)<=0}function um(t,e){return Qr(t,e)&&Rt(t,e)>0}function lm(t,e){return Qr(t,e)&&Rt(t,e)>=0}function dm(t,e,n){const r=t!==void 0;switch(e){case"==":return r&&Ye(t,n);case"!=":return r&&t!==null&&!Ye(t,n);case"<":return r&&om(t,n);case"<=":return r&&cm(t,n);case">":return r&&um(t,n);case">=":return r&&lm(t,n);case"in":return r&&Array.isArray(n)&&n.some(s=>Ye(t,s));case"not-in":return!Array.isArray(n)||n.some(s=>s===null)?!1:r&&t!==null&&!n.some(s=>Ye(t,s));case"array-contains":return Array.isArray(t)&&t.some(s=>Ye(s,n));case"array-contains-any":return Array.isArray(t)&&Array.isArray(n)&&n.some(s=>t.some(i=>Ye(i,s)))}}function hm(t,e){if(e===Et){const n=t.path.split("/");return n[n.length-1]??t.path}return t.data[e]}function Bc(t){if(Array.isArray(t))return t.map(Bc);if(t&&typeof t=="object"){const e=t;if(typeof e.id=="string")return e.id;if(typeof e.path=="string"){const n=e.path.split("/");return n[n.length-1]??e.path}}return t}function Ys(t,e){if(e.kind==="where"){const n=hm(t,e.field),r=e.field===Et?Bc(e.value):e.value;return dm(n,e.op,r)}return e.kind==="and"?e.filters.every(n=>Ys(t,n)):e.filters.some(n=>Ys(t,n))}function fm(t,e){return t.filter(n=>e.every(r=>Ys(n,r)))}function to(t,e,n){for(let r=0;r<e.length;r++){const s=Rt(Qs(t,n[r].field),e[r]);if(s!==0)return n[r].direction==="desc"?-s:s}return 0}function pm(t,e,n,r){return t.filter(s=>{if(n){const i=to(s,n.values,e);if(n.inclusive?i<0:i<=0)return!1}if(r){const i=to(s,r.values,e);if(r.inclusive?i>0:i>=0)return!1}return!0})}function zc(t,e){return t.filter(n=>e.every(r=>r.field===Et||n.data[r.field]!==void 0))}function Vc(t){return(e,n)=>{for(const r of t){const s=Rt(Qs(e,r.field),Qs(n,r.field));if(s!==0)return r.direction==="desc"?-s:s}return 0}}function mm(t,e){return e.length===0?t:zc(t,e).sort(Vc(e))}function Wc(t){const e=[...t.orders],n=new Set(e.map(s=>s.field)),r=t.orders.length>0?t.orders[t.orders.length-1].direction:"asc";for(const s of t.filters)for(const i of Ci(s))i!==Et&&!n.has(i)&&(n.add(i),e.push({field:i,direction:r}));return n.has(Et)||e.push({field:Et,direction:r}),e}function hs(t,e){let n=fm(t,[...e.filters]);const r=Wc(e),s=e.orders.length>0||e.start!==void 0||e.end!==void 0||e.filters.some(am);if(s&&e.limitCount!==void 0&&!e.limitFromEnd&&e.start===void 0&&e.end===void 0)return Qp(zc(n,r),e.limitCount,Vc(r));if(s&&(n=mm(n,r)),e.start||e.end){for(const i of[e.start,e.end])if(i&&!i.fromSnapshot&&i.values.length>e.orders.length)throw new ue({code:"invalid-argument",message:"Too many arguments provided to a cursor (startAt / startAfter / endAt / endBefore). The number of cursor values must be less than or equal to the number of orderBy() clauses."});n=pm(n,r,e.start,e.end)}if(e.limitCount!==void 0)if(e.limitFromEnd){if(e.orders.length===0)throw new ue({code:"unimplemented",message:"limitToLast() queries require at least one orderBy clause."});n=n.slice(-e.limitCount)}else n=n.slice(0,e.limitCount);return n}class gm{events;triggerScope;rules;simulator;host;operationReader;listAuthorizer;constructor(e,n,r,s,i,a){this.events=e,this.triggerScope=n,this.rules=r,this.simulator=s,this.host=i,this.operationReader=new Up(e,r,s,i,a),this.listAuthorizer=new Jp(e,r,s,i)}get state(){return this.host.state}emitRequest(e){this.events.request.hasSubscribers&&this.events.request.emit(Zr(e))}execute(e){return this.operationReader.execute(e)}silentReadDoc(e,n,r=!1){if(r){const E=this.state.get(e);return this.emitRequest({at:Date.now(),evalMs:0,method:"get",path:e,auth:n,result:"allow",debugMessages:["admin lens — rules bypassed"],origin:"listener",resourceBefore:{data:E,exists:E!==null},detail:{admin:!0},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),{allowed:!0,data:E}}const s=xe.fromMillis(Date.now()),i=Jr(this.state,{method:"get",path:e,auth:n},s),a=Date.now(),o=performance.now(),c=this.simulator.simulate(this.rules.source,[i],{getDoc:E=>this.state.get(E)}),u=performance.now()-o;if(!c.success)return this.emitRequest({at:a,evalMs:u,method:"get",path:e,auth:n,result:"deny",debugMessages:[`Simulation error: ${c.error.message}`],origin:"listener",...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),{allowed:!1,error:te("permission-denied",`get ${e} simulator error`,{request:{method:"get",path:e,auth:n}})};const d=c.data.results[0];if(d.state==="UNSUPPORTED")throw this.emitRequest({at:a,evalMs:u,method:"get",path:e,auth:n,result:"unsupported",debugMessages:Se(d),origin:"listener",...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),new Wn(Hn("get",e,Se(d)),"get",e,Se(d));const l=d.state==="PASSED",p=this.state.get(e),y=Kt(d);let b="deny";l&&(b="allow");const w=p!==null,R={at:a,evalMs:u,method:"get",path:e,auth:n,result:b,debugMessages:Se(d),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 E={request:{method:"get",path:e,auth:n},resource:{data:p,exists:w}};return y!==void 0&&(E.rule=y),{allowed:!1,error:te("permission-denied",`get ${e} denied by rules`,E)}}return{allowed:!0,data:p}}silentReadCollection(e,n,r,s=!1){if(typeof r=="function")return{allowed:!1,error:te("invalid-argument","Callable query constraints are no longer executable; pass an immutable QueryConstraintPlan.")};const i=r?Xa(r.execution):void 0,a=i?eo(i):{},o={requestTime:xe.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?hs(p,i):p,b=this.listAuthorizer.authorize({path:e,auth:n,constraints:a,bypassRules:s,...r?.activityQuery?{activityQuery:r.activityQuery}:{},origin:"listener",...c?{triggeredBy:c}:{},timing:o});return b.allowed?{allowed:!0,docs:y}:b}const u=this.listAuthorizer.authorize({path:e,auth:n,constraints:a,...r?.activityQuery?{activityQuery:r.activityQuery}:{},origin:"listener",...c?{triggeredBy:c}:{},timing:o});if(!u.allowed)return u;const d=this.state.list(e).filter(p=>!p.phantom).map(p=>({path:p.path,data:p.data}));return{allowed:!0,docs:i?hs(d,i):d}}runQuery(e){const n=rm(e.scope),r=Xa(e.execution),s=e.auth,i=e.bypassRules,a=e.activityQuery,o=sm(this.state,n),c=n.kind==="collection"?n.path:n.collectionId,u=eo(r),d=this.listAuthorizer.authorize({path:c,collectionGroup:n.kind==="collection-group",auth:s,constraints:u,bypassRules:i,...a!==void 0?{activityQuery:a}:{},origin:"user"});return d.allowed?{allowed:!0,docs:hs(o,r)}:d}}const no="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",ro=20;function Ti(){const t=new Uint8Array(ro);globalThis.crypto.getRandomValues(t);let e="";for(let n=0;n<ro;n++)e+=no[t[n]%no.length];return e}function Hc(t,e=""){const n=[],r=new WeakSet;return s(t,e),n;function s(i,a){if(i==null||typeof i!="object"||r.has(i)||(r.add(i),kc(i)!==void 0))return;if(Array.isArray(i)){i.forEach((u,d)=>s(u,`${a}[${d}]`));return}const o=i,c=ym(o);if(c){n.push({field:a,kind:c});return}for(const[u,d]of Object.entries(o)){const l=a?`${a}.${u}`:u;s(d,l)}}}function ym(t){const e=t.__type;return e==="serverTimestamp"?"serverTimestamp":e==="increment"?"increment":e==="arrayUnion"?"arrayUnion":e==="arrayRemove"?"arrayRemove":e==="deleteField"?"delete":null}gp();class bm{host;rules;simulator;eventLog;events;triggerScope;constructor(e,n,r,s,i,a){this.host=e,this.rules=n,this.simulator=r,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(Zr(e))}emitWrite(e){this.events.write.hasSubscribers&&this.events.write.emit({kind:"write",id:Ln().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 n={};for(const r of e){const s=this.state.get(r);n[r]=s?{...s}:null}return n}runSimulate(e,n,r){return $c(this.state,this.rules,this.simulator,e,n,r)}isReadOnlyMethod(e){return e==="get"||e==="list"}resolvePriorDocumentState(e,n,r){return n.has(e)?n.get(e)??null:r.exists(e)?r.get(e)??null:null}computeProjectedUpdate(e,n){return e===null?null:Zs(e,n??{})}computeProjectedOverwrite(e,n){return Zs(e??{},n??{})}buildBatchProjection(e){const n=new Map;for(const r of e){if(this.isReadOnlyMethod(r.method))continue;if(r.method==="delete"){n.set(r.path,null);continue}const s=this.resolvePriorDocumentState(r.path,n,this.state);if(r.method==="update"){const i=this.computeProjectedUpdate(s,r.data);n.set(r.path,i)}else{const i=this.computeProjectedOverwrite(s,r.data);n.set(r.path,i)}}return n}buildTestCase(e,n){return Jr(this.state,e,n)}notify(e,n,r){this.triggerScope.run({method:e,path:n},()=>this.host.notifyListenersForPaths(r))}}class Gc{runtime;constructor(e){this.runtime=e}prepare(e,n){const r=xe.fromMillis(Date.now()),s=[];for(let i=0;i<e.length;i++){const a=e[i];try{const o=a.data?nt({...a.data},{path:a.path,method:a.method,prior:this.runtime.state.get(a.path),serverTime:r}):a.data;s.push({method:a.method,path:a.path,data:o})}catch(o){const c=o.message,u=te("invalid-argument",c),d=n.snapshot[a.path]??null,l={at:Date.now(),evalMs:0,method:a.ruleMethod,path:a.path,auth:n.auth,result:"deny",debugMessages:[`FieldValue resolve error: ${c}`],...this.includesRequestData(n,a)?{resourceData:a.preData}:{},resourceBefore:{data:d,exists:d!==null},origin:n.origin,groupId:n.groupId,...n.bypassRules?{detail:{admin:!0}}:{},...n.provenance?{provenance:n.provenance}:{}};return{index:i,input:a,message:c,error:u,request:l}}}return{context:n,inputs:e,resolvedOps:s,serverTime:r}}evaluateAndApply(e){const{context:n,inputs:r,resolvedOps:s,serverTime:i}=e,a=s.map((l,p)=>{const y=r[p];return this.runtime.buildTestCase({method:y.ruleMethod,path:l.path,auth:n.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=r[l],y=n.snapshot[p.path]??null,b=Date.now(),w=performance.now(),R=this.runtime.runSimulate([a[l]],n.bypassRules,o),C=performance.now()-w;if(!R.success){const k=te("invalid-argument",R.error.message);c.push({path:p.path,method:p.ruleMethod,allowed:!1,debugMessages:[R.error.message],error:k,request:this.request(e,p,y,b,C,"deny",[`Simulation error: ${R.error.message}`])}),u=!1;continue}const I=R.data.results[0],E=Se(I);if(I.state==="UNSUPPORTED")throw this.runtime.emitRequest(this.request(e,p,y,b,C,"unsupported",E)),new Wn(Hn(p.ruleMethod,p.path,E),p.ruleMethod,p.path,E);const N=I.state==="PASSED";let q="deny";N&&(q="allow");const S={path:p.path,method:p.ruleMethod,allowed:N,debugMessages:E,request:this.request(e,p,y,b,C,q,E)};if(N===!1){const k=Kt(I),_=y!==null,v={request:{method:p.ruleMethod,path:p.path,auth:n.auth},resource:{data:y,exists:_}};this.includesRequestData(n,p)&&(v.request.resourceData=p.preData),k!==void 0&&(v.rule=k),S.error=te("permission-denied",`${p.ruleMethod} ${p.path} denied by rules`,v),this.runtime.emitDenial(S.error),u=!1}c.push(S)}let d=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];d=te(y?.method==="create"?"already-exists":"not-found",p.error);const b=c[p.index];b&&(b.allowed=!1,b.error=d)}}}return{...e,outcomes:c,allowed:u,structuralError:d}}emitAndNotify(e){const{context:n,inputs:r,outcomes:s,serverTime:i}=e;for(let a=0;a<s.length;a++){const o=s[a],c=r[a],u=e.allowed&&o.allowed,d=n.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:d,exists:d!==null},this.runtime.emitRequest(o.request),u){const l=c.preData?Hc(c.preData):void 0;this.runtime.emitWrite({method:c.ruleMethod,path:c.path,auth:n.auth,...c.ruleMethod!=="delete"&&c.preData?{data:c.preData}:{},priorState:d,nextState:c.ruleMethod==="delete"?null:this.runtime.state.get(c.path),groupId:n.groupId,groupKind:n.origin,...l&&l.length>0?{sentinels:l}:{},requestTime:i,...n.bypassRules?{detail:{admin:!0}}:{},...n.provenance?{provenance:n.provenance}:{}})}}e.allowed&&this.runtime.notify(n.origin,r[0]?.path??"",new Set(r.map(a=>a.path)))}request(e,n,r,s,i,a,o){const{context:c}=e;return{at:s,evalMs:i,method:n.ruleMethod,path:n.path,auth:c.auth,result:a,debugMessages:o,...this.includesRequestData(c,n)?{resourceData:n.preData}:{},resourceBefore:{data:r,exists:r!==null},origin:c.origin,groupId:c.groupId,...c.bypassRules?{detail:{admin:!0}}:{},...c.provenance?{provenance:c.provenance}:{}}}includesRequestData(e,n){return n.preData!==void 0&&(e.origin==="batch"||n.ruleMethod!=="delete")}}class vm{runtime;pipeline;constructor(e){this.runtime=e,this.pipeline=new Gc(e)}batch(e,n,r){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:n,bypassRules:r,snapshot:s});if(!("resolvedOps"in o)){const p=this.runtime.eventLog.append({type:"batch",method:"batch",path:"",auth:n?{uid:n.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}:{}})),d=this.runtime.eventLog.append({type:"batch",method:"batch",path:"",auth:n?{uid:n.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??te("permission-denied","Batch denied")),{allowed:c.allowed,results:u,event:d,...l?{error:l}:{}}}}const Xs="Firestore transactions require all reads to be executed before all writes.";class Kc extends Error{simError;constructor(){super(Xs),this.name="ReadAfterWriteError",this.simError=te("failed-precondition",Xs)}}class so extends Error{constructor(){super("A document read in the transaction changed before commit."),this.name="RetryableTransactionConflictError"}}class Zc extends Error{simError=te("failed-precondition","Transaction failed all retries.");constructor(){super("Transaction failed all retries."),this.name="TransactionAttemptsExhaustedError"}}class wm{versionReader;reader;reads=[];writes=[];readVersions=new Map;writeStarted=!1;constructor(e,n=()=>0){this.versionReader=n,this.reader=e}get(e){this.assertReadsAllowed();const n=this.reader(e);this.readVersions.has(e)||this.readVersions.set(e,this.versionReader(e)),this.reads.push({path:e,data:n});const r=n===null?null:structuredClone(n);return{path:e,exists:r!==null,data:()=>r===null?void 0:r}}getAll(...e){return this.assertReadsAllowed(),e.map(n=>this.get(n))}set(e,n){this.queue({method:"set",path:e,data:n})}create(e,n){this.queue({method:"create",path:e,data:n})}update(e,n){this.queue({method:"update",path:e,data:n})}delete(e){this.queue({method:"delete",path:e})}consume(){return{reads:this.reads,writes:this.writes,readVersions:this.readVersions}}hadWrites(){return this.writeStarted}queue(e){this.writeStarted=!0,this.writes.push(e)}assertReadsAllowed(){if(this.writeStarted)throw new Kc}}class Sm extends Error{path;secondMethod;constructor(e,n){super(`Queued ${n} 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=n}}function _m(t){const e=new Map;for(const n of t){const r=e.get(n.path);if(r===void 0){e.set(n.path,Am(n));continue}if(r.method==="delete")throw new Sm(n.path,n.method);e.set(n.path,xm(r,n))}return Array.from(e.values())}function Am(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 xm(t,e){switch(e.method){case"delete":return{method:"delete",path:e.path};case"set":{const n=fs(e);return{method:"set",path:e.path,data:n}}case"update":{const n=fs(e),s={...t.data??{},...n};return{method:t.method,path:e.path,data:s}}case"create":{const n=fs(e),s={...t.data??{},...n};return{method:"create",path:e.path,data:s}}}}function fs(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 Im{runtime;pipeline;constructor(e){this.runtime=e,this.pipeline=new Gc(e)}transaction(e,n){return this.runAttempt(e,n,1)}runAttempt(e,n,r){const s=this.runtime.state.snapshot(),i=this.runtime.state.currentVersion(),a=new Map(Object.keys(s).map(d=>[d,this.runtime.state.version(d)])),o=d=>s[d]??null,c=new wm(o,d=>{const l=a.get(d);if(l!==void 0)return l;const p=this.runtime.state.version(d);return p<=i?p:-1});let u;try{u=e(c)}catch(d){throw this.logAbortedTransaction(c,n.auth,d),d}if(u!==null&&typeof u?.then=="function")return u.then(d=>{try{return this.commitTransaction(c,s,n,d)}catch(l){return this.retryOrThrow(l,e,n,r)}},d=>{throw this.logAbortedTransaction(c,n.auth,d),d});try{return this.commitTransaction(c,s,n,u)}catch(d){return this.retryOrThrow(d,e,n,r)}}retryOrThrow(e,n,r,s){if(!(e instanceof so))throw e;const i=r.maxAttempts??5;if(s>=i)throw new Zc;return this.runAttempt(n,r,s+1)}commitTransaction(e,n,r,s){const{reads:i,writes:a,readVersions:o}=e.consume();for(const[E,N]of o)if(this.runtime.state.version(E)!==N)throw new so;const c=r.auth;if(a.length===0){const E=this.runtime.eventLog.append({type:"transaction",method:"transaction",path:"",auth:c?{uid:c.uid}:null,allowed:!0,reads:i.map(N=>({path:N.path,data:N.data})),operations:[],snapshot:n,debugMessages:["Transaction committed (read-only — no writes queued)"]});return{allowed:!0,reads:[...i],writes:[],returnValue:s,event:E}}let u;try{u=_m(a)}catch(E){const N=E;throw this.runtime.eventLog.append({type:"transaction",method:"transaction",path:"",auth:c?{uid:c.uid}:null,allowed:!1,aborted:!0,reads:i.map(q=>({path:q.path,data:q.data})),error:{name:N.name,message:N.message,code:"failed-precondition"},debugMessages:[`Transaction aborted at merge: ${N.message}`]}),E}const d=Object.fromEntries(u.map(E=>[E.path,n[E.path]??null])),l=u.map(E=>{const N=E.method==="set"?this.runtime.state.get(E.path)!==null?"update":"create":E.method;return{...E,ruleMethod:N,preData:E.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:r.bypassRules,provenance:r.provenance,snapshot:d});if(!("resolvedOps"in y)){const E=this.runtime.eventLog.append({type:"transaction",method:"transaction",path:"",auth:c?{uid:c.uid}:null,allowed:!1,reads:i.map(N=>({path:N.path,data:N.data})),operations:u.map(N=>({method:N.method,path:N.path,data:N.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((N,q)=>({path:N.path,method:N.ruleMethod,allowed:!1,debugMessages:q===y.index?[y.message]:[],...q===y.index?{error:y.error}:{}})),returnValue:s,event:E,error:y.error}}const b=this.pipeline.evaluateAndApply(y),w=b.outcomes.map(E=>({path:E.path,method:E.method,allowed:E.allowed,debugMessages:E.debugMessages,...E.error?{error:E.error}:{}})),R=this.runtime.eventLog.append({type:"transaction",method:"transaction",path:"",auth:c?{uid:c.uid}:null,allowed:b.allowed,reads:i.map(E=>({path:E.path,data:E.data})),operations:b.resolvedOps.map((E,N)=>({method:E.method,path:E.path,data:E.data,allowed:w[N]?.allowed??!1})),snapshot:b.allowed?n:void 0,debugMessages:b.allowed?["Transaction committed"]:["Transaction rolled back — one or more operations denied"]});this.pipeline.emitAndNotify(b);let C;b.allowed||(C=b.structuralError??w.find(E=>E.error)?.error??te("permission-denied","Transaction denied"));const I={allowed:b.allowed,reads:[...i],writes:w,returnValue:s,event:R,...C?{error:C}:{}};return r.readOnly&&e.hadWrites()&&(I.readOnlyViolation=!0),I}logAbortedTransaction(e,n,r){const s=r,{reads:i}=e.consume();this.runtime.eventLog.append({type:"transaction",method:"transaction",path:"",auth:n?{uid:n.uid}:null,allowed:!1,aborted:!0,reads:i.map(a=>({path:a.path,data:a.data})),error:{name:r.name,message:r.message,...s.code!==void 0?{code:String(s.code)}:{}},debugMessages:[`Transaction aborted: ${r.message}`]})}}class Em{runtime;batches;transactions;constructor(e,n,r,s,i,a){this.runtime=new bm(e,n,r,s,i,a),this.batches=new vm(this.runtime),this.transactions=new Im(this.runtime)}capturePriors(e){return this.runtime.capturePriors(e)}applyWrite(e,n,r,s){if(s!==void 0&&s!==!1&&(e==="create"||e==="update")){const i=s===!0?void 0:s.mergeFields;return this.runtime.state.setMerge(n,r??{},i),null}switch(e){case"create":{const i=this.runtime.state.create(n,r??{});return i.success?null:te("already-exists",i.error??`Document '${n}' already exists`)}case"update":{const i=this.runtime.state.update(n,r??{});return i.success?null:te("not-found",i.error??`Document '${n}' does not exist`)}case"set":return this.runtime.state.set(n,r??{}),null;case"delete":return this.runtime.state.delete(n),null;default:return null}}execute(e){const{method:n,path:r,auth:s,data:i,autoId:a,requestTime:o,merge:c,bypassRules:u}=e,d=u?{admin:!0}:void 0,l=this.runtime.capturePriors([r]),p=o??xe.fromMillis(Date.now());let y;try{y=i&&nt({...i},{path:r,method:n,prior:this.runtime.state.get(r),serverTime:p}),n==="update"&&y&&bp(y)}catch(A){const x=A.message,f=this.runtime.eventLog.append({type:"single",method:n,path:r,auth:s?{uid:s.uid}:null,data:i,allowed:!1,priorDocs:l,debugMessages:[`FieldValue resolve error: ${x}`]});return this.runtime.emitRequest({at:Date.now(),evalMs:0,method:n,path:r,auth:s,result:"deny",debugMessages:[`FieldValue resolve error: ${x}`],...y?{resourceData:y}:i?{resourceData:i}:{},resourceBefore:{data:l[r]??null,exists:(l[r]??null)!==null},origin:"user",...d?{detail:d}:{}}),{allowed:!1,debugMessages:[x],event:f,error:te("invalid-argument",x)}}const b=this.runtime.buildTestCase({...e,data:y},p),w=Date.now(),R=performance.now(),C=this.runtime.runSimulate([b],u),I=performance.now()-R;if(!C.success){const A=this.runtime.eventLog.append({type:"single",method:n,path:r,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:I,method:n,path:r,auth:s,result:"deny",debugMessages:[`Simulation error: ${C.error.message}`],...i?{resourceData:i}:{},resourceBefore:{data:l[r]??null,exists:(l[r]??null)!==null},origin:"user",...d?{detail:d}:{}}),{allowed:!1,debugMessages:[C.error.message],event:A,error:te("invalid-argument",C.error.message)}}const E=C.data.results[0];if(E.state==="UNSUPPORTED")throw this.runtime.emitRequest({at:w,evalMs:I,method:n,path:r,auth:s,result:"unsupported",debugMessages:Se(E),...i?{resourceData:i}:{},resourceBefore:{data:l[r]??null,exists:(l[r]??null)!==null},origin:"user",...d?{detail:d}:{}}),new Wn(Hn(n,r,Se(E)),n,r,Se(E));let N=E.state==="PASSED",q=null;N&&(q=this.applyWrite(n,r,y,c),q&&(N=!1));const S=this.runtime.eventLog.append({type:"single",method:n,path:r,auth:s?{uid:s.uid}:null,data:y,allowed:N,priorDocs:N?l:void 0,debugMessages:Se(E)}),k={allowed:N,debugMessages:Se(E),event:S};if(N===!1){let A=!1;if(q!==void 0&&q!==null&&(A=!0),A)k.error=q;else{let f=null;const h=l[r];h!==void 0&&(f=h);let m=n;n==="set"&&(f!==null?m="update":m="create");const O=Kt(E),D={request:{method:m,path:r,auth:s},resource:{data:f,exists:f!==null}};i!==void 0&&(D.request.resourceData=i),O!==void 0&&(D.rule=O),k.error=te("permission-denied",`${n} ${r} denied by rules`,D),this.runtime.emitDenial(k.error)}}const _=l[r]??null,v=N?this.runtime.state.get(r):_;if(this.runtime.emitRequest({at:w,evalMs:I,method:n,path:r,auth:s,result:N?"allow":"deny",debugMessages:Se(E),evaluatedRule:Kt(E),...i?{resourceData:i}:{},resourceBefore:{data:_,exists:_!==null},...n!=="delete"?{resourceAfter:{data:v,exists:v!==null}}:{resourceAfter:{data:null,exists:!1}},origin:"user",...d?{detail:d}:{}}),N){const A=i?Hc(i):void 0,x=a&&n==="create"?r.split("/").pop():void 0;this.runtime.emitWrite({method:n,path:r,auth:s,...n!=="delete"&&i?{data:i}:{},priorState:_,nextState:n==="delete"?null:v,...A&&A.length>0?{sentinels:A}:{},...x?{autoId:x}:{},requestTime:p,...d?{detail:d}:{}})}return N&&this.runtime.notify(n,r,new Set([r])),k}createWithAutoId(e,n,r,s){const i=e.endsWith("/")?e.slice(0,-1):e,a=Ti(),o=`${i}/${a}`,c=this.execute({method:"create",path:o,auth:r,data:n,autoId:!0,bypassRules:s});return{path:o,result:c}}batch(e,n,r){return this.batches.batch(e,n,r)}transaction(e,n){return this.transactions.transaction(e,n)}}class io{state;eventLog;history;simulator;rules;seedSnapshot;events=new Ep;triggerScope=new kp;reads;writes;listeners;constructor(){this.state=new ls,this.eventLog=new _p;const e=this;this.simulator=new Jh,this.rules=new qp(Ip),this.reads=new gm(this.events,this.triggerScope,this.rules,this.simulator,{get state(){return e.state}},this.eventLog),this.listeners=new Pp(this.events,this.triggerScope,this.reads),this.writes=new Em({get state(){return e.state},notifyListenersForPaths:n=>e.listeners.notifyListenersForPaths(n)},this.rules,this.simulator,this.eventLog,this.events,this.triggerScope),this.history=new $p(this.eventLog,{get state(){return e.state},capturePriors:n=>this.writes.capturePriors(n),applyWrite:(n,r,s,i)=>this.writes.applyWrite(n,r,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,n,r={},s=null,i,a=!1,o=!1,c){return this.listeners.addSnapshotListener(e,n,r,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 ls({},new Sp(e.baseDocuments)):new ls(e.documents??{}),this.seedSnapshot=e.baseDocuments??this.state.snapshot(),this.eventLog.clear(),Ds(e.rules)}deployRules(e){const n=Ds(e);return this.rules.set(e),this.listeners.reEvaluateAllListeners(),n}reevaluateLiveListeners(e,n){this.listeners.reevaluateLiveListeners(e,n)}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,n){this.state.set(e,n??{}),this.listeners.notifyListenersForPaths(new Set([e]))}adminDeleteDocument(e){const n=this.state.delete(e);return n.success&&this.listeners.notifyListenersForPaths(new Set([e])),{deleted:n.success}}execute(e){return e.method==="get"||e.method==="list"?this.reads.execute(e):this.writes.execute(e)}createWithAutoId(e,n,r,s){return this.writes.createWithAutoId(e,n,r,s)}batch(e,n,r){return this.writes.batch(e,n,r)}transaction(e,n){return this.writes.transaction(e,n)}undo(){return this.history.undo()}redo(){return this.history.redo()}getEvents(){return this.history.getEvents()}getEventCount(){return this.history.getEventCount()}}class ie extends Error{code;denialContext;remediation;constructor(e,n,r){const s=typeof e=="object",i=s?e.code:e,a=s?e.message:n,o=s?e.denialContext:r,c=s?e.remediation:void 0,u=c!==void 0?`${a}
|
|
1249
|
+
|
|
1250
|
+
Remediation:
|
|
1251
|
+
${c}`:a;super(u),this.name="SandboxError",this.code=i,o!==void 0&&(this.denialContext=o),c!==void 0&&(this.remediation=c)}}function ei(t){return t.kind==="request"||t.kind==="operation"||t.kind==="listener"&&t.phase==="errored"}function Kn(t){const e=Object.freeze({...t.source}),n=Object.freeze({...t.authLens});return Object.freeze({source:e,authLens:n,...t.planId===void 0?{}:{planId:t.planId}})}function Ri(t){const e=Kn(t);return{actor:e.source,authLens:e.authLens,operationContext:e,...e.planId===void 0?{}:{planId:e.planId}}}function ao(t){const e=t?.operationContext?.source;if(e&&e.kind!=="unattributed")return e;if(t?.actor&&t.actor.kind!=="unattributed")return t.actor}function Ni(t,e){const n=t?.operationContext?.source??t?.actor,r=e?.operationContext?.source??e?.actor;return Kn({source:ao(t)??ao(e)??n??r??{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 km(t){return Ni(void 0,t)}function Om(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 n=e.toLowerCase();return n==="permission_denied"||n==="permission-denied"||n==="auth/permission-denied"}function Jc(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"}:Om(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 Cm(t){if(t===null)return null;let e;return t.token!==void 0&&(e=Qc(t.token)),Object.freeze({uid:t.uid,...e===void 0?{}:{token:e}})}function Qc(t){const e={};for(const[n,r]of Object.entries(t))e[n]=Yc(r);return Object.freeze(e)}function Yc(t){return Array.isArray(t)?Object.freeze(t.map(Yc)):t&&typeof t=="object"?Qc(t):t}function Xg(t){if(!ei(t))return null;let e="listen",n;t.kind==="request"||t.kind==="operation"?(e=t.method,t.path!==void 0&&(n=t.path)):t.kind==="listener"&&(e="listen",t.target.path!==void 0&&(n=t.target.path));let r="firestore";return t.service!==void 0&&(r=t.service),Object.freeze({id:t.id,at:t.at,eventKind:t.kind,service:r,method:e,...n===void 0?{}:{path:n},auth:Cm(t.auth),result:t.result,context:km(t),rules:Object.freeze({...Jc(t)})})}function oo(t){return t===null?{mode:"anon"}:t.token===void 0?{mode:"as",uid:t.uid}:{mode:"as",uid:t.uid,token:t.token}}class Zn{sandbox;auth;constructor(e,n,r){this.sandbox=e,this.auth=n,this.operationContext=Kn(r??{source:{kind:"unattributed"},authLens:oo(n)})}operationContext;withAuth(e){return ti(e),new Zn(this.sandbox,e,{source:this.operationContext.source,authLens:oo(e),...this.operationContext.planId===void 0?{}:{planId:this.operationContext.planId}})}}function Li(t,e){return new Zn(t.sandbox,t.auth,e)}function ti(t){if(t===null)return;if(t===void 0)throw new ie({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(`
|
|
1252
|
+
`)});if(typeof t!="object")throw new ie("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 ie("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 ie("invalid-argument","withAuth() requires `token` (when present) to be a plain object.")}function Tm(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),n=e.length%4===0?"":"=".repeat(4-e.length%4),r=atob(e+n),s=new Uint8Array(r.length);for(let i=0;i<r.length;i++)s[i]=r.charCodeAt(i);return s}function Rm(t){const e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return n}function Fi(t){return ni(t,!0)}function ni(t,e){if(t===null||typeof t!="object")return t;if(Array.isArray(t)){const a=t.map(o=>ni(o,!1));return e&&ut(a,Ha(t)),a}const n=t,r=a=>(e&&ut(a,Ha(t)),a),s=(a,o)=>(tn(a,Object.freeze(o),()=>a),r(a));if(n.__type__==="__vector__"&&Array.isArray(n.value)){const a=Object.freeze(n.value.slice());return s(new en(a),{type:"vector",values:a})}if(typeof n.__type=="string")switch(n.__type){case"timestamp":return s(new xe(n.seconds,n.nanos),{type:"timestamp",seconds:n.seconds,nanoseconds:n.nanos});case"bytes":{const a=Tm(n.base64);return s(new We(a),{type:"bytes",values:Object.freeze(Array.from(a))})}case"latlng":return s(new ot(n.lat,n.lng),{type:"geo-point",latitude:n.lat,longitude:n.lng});case"duration":return r(new we(n.seconds,n.nanos));case"reference":return r(new zt(n.path));case"path":return r(new st(n.segments))}if(typeof n.type=="string")switch(n.type){case"firestore/timestamp/1.0":{const a=n.seconds,o=n.nanoseconds;return s(new xe(a,o),{type:"timestamp",seconds:a,nanoseconds:o})}case"firestore/bytes/1.0":{const a=Rm(n.bytes);return s(new We(a),{type:"bytes",values:Object.freeze(Array.from(a))})}case"firestore/geoPoint/1.0":return s(new ot(n.latitude,n.longitude),{type:"geo-point",latitude:n.latitude,longitude:n.longitude})}const i={};for(const[a,o]of Object.entries(n))i[a]=ni(o,!1);return r(i)}class Xn extends Error{constructor(e){super(e),this.name="PersistenceSchemaError"}}function Nm(t){let e;try{e=JSON.parse(t)}catch(s){throw new Xn(`Persisted blob is not valid JSON: ${s.message}`)}if(typeof e!="object"||e===null)throw new Xn("Persisted blob is not an object");if(e.version!==1&&e.version!==2)throw new Xn(`Persisted blob has version ${String(e.version)}, expected 1 or 2`);if(typeof e.firestore!="object"||e.firestore===null)throw new Xn("Persisted blob has no firestore field");const n={};for(const[s,i]of Object.entries(e.firestore))n[s]=Fi(i);const r=e.services!==void 0&&typeof e.services=="object"&&e.services!==null?e.services:{};return{firestore:n,services:r}}const Lm=3,Fm=256,ri="meta";function Dm(t){let e=2166136261;for(let n=0;n<t.length;n++)e^=t.charCodeAt(n),e=e+((e<<1)+(e<<4)+(e<<7)+(e<<8)+(e<<24))>>>0;return(e%Fm).toString(16).padStart(2,"0")}function Mm(t){return JSON.parse(JSON.stringify(t))}function Xc(t){const e=JSON.stringify(t);let n=2166136261;for(let r=0;r<e.length;r++)n^=e.charCodeAt(r),n=Math.imul(n,16777619)>>>0;return n}function eu(t,e,n){const r=new Map;r.set(ri,{version:Lm,savedAt:n,services:e});for(const[s,i]of Object.entries(t)){const a=Dm(s);let o=r.get(a);o||(o={docs:{}},r.set(a,o)),o.docs[s]=Mm(i)}for(const[s,i]of r)s!==ri&&(i.checksum=Xc(i.docs));return r}const tu="pyric-v3-records";function ey(t){return JSON.stringify({format:tu,records:Object.fromEntries(t)})}function ty(t){let e;try{e=JSON.parse(t)}catch{return new Map}const n=e;return n&&typeof n=="object"&&n.format===tu&&typeof n.records=="object"&&n.records!==null?new Map(Object.entries(n.records)):nu(t)??new Map}function nu(t){let e;try{e=Nm(t)}catch{return null}return eu(e.firestore,e.services,0)}function jm(t){const e={};let n={};for(const[r,s]of t){if(r===ri){const a=s;a&&typeof a.services=="object"&&a.services!==null&&(n=a.services);continue}const i=s;if(!(!i||typeof i.docs!="object"||i.docs===null)){if(typeof i.checksum=="number"&&Xc(i.docs)!==i.checksum){console.warn(`[sandbox/persistence] checksum mismatch for bucket '${r}'; skipping corrupt bucket`);continue}for(const[a,o]of Object.entries(i.docs))e[a]=Fi(o)}}return{firestore:e,services:n}}const yn="snapshots";function co(){const t=new Map,e=n=>{let r=t.get(n);return r||(r=new Map,t.set(n,r)),r};return{async getRecord(n,r){const s=t.get(n)?.get(r);return s===void 0?null:structuredClone(s)},async listRecords(n){return[...t.get(n)?.keys()??[]]},async putRecords(n,r){const s=e(n);for(const[i,a]of r)s.set(i,structuredClone(a))},async deleteRecords(n,r){const s=t.get(n);if(s)for(const i of r)s.delete(i)},async clear(n){t.delete(n)}}}function ru(t){return new Promise((e,n)=>{const r=indexedDB.open(t,1);r.onupgradeneeded=()=>{const s=r.result;s.objectStoreNames.contains(yn)||s.createObjectStore(yn)},r.onsuccess=()=>e(r.result),r.onerror=()=>n(r.error??new Error(`Failed to open IndexedDB '${t}'`)),r.onblocked=()=>n(new Error(`IndexedDB open blocked for '${t}'`))})}function ps(t,e,n){return ru(t).then(r=>new Promise((s,i)=>{const a=r.transaction(yn,e),o=a.objectStore(yn),c=n(o);let u=null;c&&(c.onsuccess=()=>{u=c.result??null},c.onerror=()=>i(c.error)),a.oncomplete=()=>{r.close(),s(u)},a.onerror=()=>{r.close(),i(a.error)},a.onabort=()=>{r.close(),i(a.error??new Error("IndexedDB transaction aborted"))}}))}function uo(t,e){return ru(t).then(n=>new Promise((r,s)=>{const i=n.transaction(yn,"readwrite");e(i.objectStore(yn)),i.oncomplete=()=>{n.close(),r()},i.onerror=()=>{n.close(),s(i.error)},i.onabort=()=>{n.close(),s(i.error??new Error("IndexedDB transaction aborted"))}}))}function Pm(){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 ps(t,"readonly",r=>r.get(e))??null},async listRecords(t){return(await ps(t,"readonly",n=>n.getAllKeys())??[]).map(n=>String(n))},async putRecords(t,e){await uo(t,n=>{for(const[r,s]of e)n.put(s,r)})},async deleteRecords(t,e){await uo(t,n=>{for(const r of e)n.delete(r)})},async clear(t){await ps(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 $m=250,lo="pyric:sandbox:auth-session";function ms(t){return t==="auth"||t==="auth-session:[DEFAULT]"?lo:`${lo}:${encodeURIComponent(t)}`}function su(t){const e=JSON.stringify(t);let n=2166136261;for(let r=0;r<e.length;r++)n^=e.charCodeAt(r),n=Math.imul(n,16777619)>>>0;return n}function qm(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 Um(t){return t.injectedBackend?t.injectedBackend:(t.backend??"indexedDB")==="memory"||typeof indexedDB>"u"?co():Pm()}async function Bm(t,e){const n={...e,flushIntervalMs:e.flushIntervalMs??$m,backend:e.backend??"indexedDB"},r=Um(n),s=new Map,i=await zm(t,r,n.key,s);let a=null,o=!1;const c=new Map,u=async()=>{if(o)return;const _=t.snapshot(),v=eu(_.firestore,_.services,Date.now()),A=new Map,x=new Map;for(const[h,g]of v){const m=su(g);x.set(h,m),s.get(h)!==m&&A.set(h,g)}const f=[...s.keys()].filter(h=>!v.has(h));A.size>0&&await r.putRecords(n.key,A),f.length>0&&await r.deleteRecords(n.key,f),s.clear();for(const[h,g]of x)s.set(h,g)};let d=Promise.resolve();const l=()=>(a&&(clearTimeout(a),a=null),d=d.then(u,u),d),p=()=>{o||a||(a=setTimeout(()=>{a=null,l().catch(_=>{if(qm(_)){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()})},n.flushIntervalMs))},y=(_,v)=>{if(!v.subscribe||c.has(_))return;const A=v.subscribe(()=>{p()});c.set(_,A)},b=new Map,w=new Map,R=(_,v)=>{if(!n.sessionStorage)return;const{local:A,session:x}=n.sessionStorage,f=ms(_),h=v.currentUid(),g=v.mode();if(h===null||g==="NONE"){A.removeItem(f),x.removeItem(f);return}const m=JSON.stringify({uid:h});g==="LOCAL"?(x.removeItem(f),A.setItem(f,m)):(A.removeItem(f),x.setItem(f,m))},C=_=>{if(!n.sessionStorage)return null;const v=ms(_);for(const[A,x]of[["LOCAL",n.sessionStorage.local],["SESSION",n.sessionStorage.session]]){const f=x.getItem(v);if(f)try{const h=JSON.parse(f);if(typeof h?.uid=="string")return{uid:h.uid,mode:A}}catch{x.removeItem(v)}}return null},I=_=>{if(!n.sessionStorage)return;const v=ms(_);n.sessionStorage.local.removeItem(v),n.sessionStorage.session.removeItem(v)},E=(_,v,A)=>{if(A.session)try{A.session.restore(v.uid,v.mode),w.delete(_)}catch(x){console.warn(`[sandbox/persistence] session restore for uid '${v.uid}' failed — clearing stored session:`,x),I(_),w.delete(_)}},N=(_,v)=>{if(!n.sessionStorage||!v.session||b.has(_))return;const A=v.session;b.set(_,A.subscribe(()=>R(_,A)))},q=(_,v)=>{if(!v.session)return;const A=w.get(_)??C(_);A&&E(_,A,v)};if(t instanceof Nt){for(const[_,v]of t.getServiceRegistry())y(_,v),q(_,v),N(_,v);t.setServiceRegistrationHook((_,v)=>{if(i!==null&&_ in i)try{v.restore(i[_])}catch(x){console.warn(`[sandbox/persistence] late-restore for service '${_}' failed:`,x)}const A=C(_);A&&w.set(_,A),q(_,v),y(_,v),N(_,v),p()}),t.setServiceUnregistrationHook(_=>{c.get(_)?.(),c.delete(_),b.get(_)?.(),b.delete(_),w.delete(_),p()})}const S=t.onEvent(_=>{Vm(_)&&p()}),k=()=>{l().catch(()=>{})};return typeof window<"u"&&window.addEventListener("beforeunload",k),{options:n,flush:l,async clear(){a&&(clearTimeout(a),a=null),await r.clear(n.key),s.clear()},dispose(){if(!o){o=!0,a&&(clearTimeout(a),a=null),S();for(const _ of c.values())_();c.clear();for(const _ of b.values())_();b.clear(),t instanceof Nt&&(t.setServiceRegistrationHook(null),t.setServiceUnregistrationHook(null)),typeof window<"u"&&window.removeEventListener("beforeunload",k)}}}}async function zm(t,e,n,r){let s;try{s=await e.listRecords(n)}catch(d){return console.warn("[sandbox/persistence] backend list failed:",d),null}if(s.length===0)return null;const i=[];for(const d of s)try{const l=await e.getRecord(n,d);l!==null&&i.push([d,l])}catch(l){console.warn(`[sandbox/persistence] failed to read persisted record '${d}':`,l)}const a=[],o=[];let c=null;for(const[d,l]of i)if(typeof l=="string"){const p=nu(l);p&&(o.push(d),c=p)}else a.push([d,l]);if(c){try{await e.putRecords(n,c),o.length>0&&await e.deleteRecords(n,o)}catch(d){console.warn("[sandbox/persistence] v2 migration write failed:",d)}for(const[d,l]of c)a.push([d,l])}for(const[d,l]of a)r.set(d,su(l));const u=jm(a);for(const[d,l]of Object.entries(u.firestore))t.admin.setDocument(d,l);if(t instanceof Nt){const d=t.getServiceRegistry();for(const[l,p]of Object.entries(u.services)){const y=d.get(l);if(y)try{y.restore(p)}catch(b){console.warn(`[sandbox/persistence] service '${l}' restore failed — Firestore state is intact; auth users may need to be re-created:`,b)}}}return u.services}function Vm(t){return t.kind==="write"||t.kind==="session_boundary"}function Wm(t){return typeof t=="object"&&t!==null&&typeof t.kind=="string"&&typeof t.origin=="string"}let Hm=0;function Gm(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`tab-${crypto.randomUUID()}`:`tab-${++Hm}-${typeof performance<"u"?performance.now().toFixed(3):String(Date.now())}`}function Km(t,e={}){let n,r=!1;if(e.channel)n=e.channel,r=!1;else if(typeof BroadcastChannel<"u")n=new BroadcastChannel("pyric:tabsync"),r=!0;else return()=>{};const s=e.originId??Gm();let i=!1,a=!1;const o=t.onEvent(l=>{if(l.kind!=="write"||i)return;const p={kind:"write",origin:s,event:l};n.postMessage(p)}),c=l=>{if(!Wm(l.data))return;const p=l.data;if(p.origin!==s){if(p.kind==="write")d(p.event);else if(p.kind==="hello"){const y={kind:"state",origin:s,to:p.origin,snapshot:t.snapshot()};n.postMessage(y)}else if(p.kind==="state"){if(p.to!==s||a)return;if(Object.keys(Xe(t).snapshot()).length>0){a=!0;return}i=!0;try{for(const[b,w]of Object.entries(p.snapshot.firestore))t.admin.setDocument(b,w)}finally{i=!1}a=!0}}};n.addEventListener("message",c);const u={kind:"hello",origin:s};return n.postMessage(u),()=>{o(),n.removeEventListener("message",c),r&&n.close()};function d(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 Zm(t,e){const n={...t};n.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=ei(n)||t.operationContext!==void 0?Ni(e,s):Jm(t,e);return n.operationContext=i,n.actor=i.source,n.authLens=i.authLens,i.planId!==void 0&&(n.planId=i.planId),e?.activity!==void 0&&(n.activity={...n.activity,...e.activity}),ei(n)&&(n.rulesDisposition=Object.freeze({...Jc(n)})),n}function Jm(t,e){return Kn({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 Qm(t,e){if(!t)return e;if(!e)return t;if(e.operationContext!==void 0)return iu(t,e);if(!(t.operationContext!==void 0||t.actor!==void 0||t.authLens!==void 0||t.planId!==void 0||e.actor!==void 0||e.authLens!==void 0||e.planId!==void 0))return{...t,...e};const r=Kn({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:r,actor:r.source,authLens:r.authLens,...r.planId===void 0?{}:{planId:r.planId}}}function iu(t,e){if(!t)return e;if(!e)return t;if(!(t.operationContext!==void 0||t.actor!==void 0||t.authLens!==void 0||t.planId!==void 0||e.operationContext!==void 0||e.actor!==void 0||e.authLens!==void 0||e.planId!==void 0))return{...t,...e};const r=Ni(t,e);return{...t,...e,operationContext:r,actor:r.source,authLens:r.authLens,...r.planId===void 0?{}:{planId:r.planId}}}let Ym=1;function Bt(){const t=(Ym++).toString(36),e=Math.random().toString(36).slice(2,7);return`sbe-${t}-${e}`}class Nt{_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 Nt(new io)}getEnv(){return this._env}withAuth(e){return ti(e),new Zn(this,e)}attachToEnv(){this.envUnsubs.push(this._env.onRequest(e=>{this.emitEvent(e)})),this.envUnsubs.push(this._env.onWrite(e=>{this.emitEvent(e)})),this.envUnsubs.push(this._env.onSnapshotDelivery(e=>this.emitEvent(e))),this.envUnsubs.push(this._env.onSnapshotSuppressed(e=>this.emitEvent(e))),this.envUnsubs.push(this._env.onListenerLifecycle(e=>this.emitEvent(e))),this.envUnsubs.push(this._env.onSnapshotError((e,n,r)=>{const s={kind:"listener_errored",id:Bt(),at:Date.now(),listenerId:r,target:n.kind==="doc"?{kind:"doc",path:n.path}:{kind:"query",collection:n.collection},auth:e.request?.auth??null,error:{code:"permission-denied",message:e.message}};this.emitEvent(s)}))}emitEvent(e,n){const r=iu(this.ambientProvenance,n);this.dispatch(Zm(e,r))}runWithProvenance(e,n){const r=this.ambientProvenance;this.ambientProvenance=Qm(r,e);try{return n()}finally{this.ambientProvenance=r}}dispatch(e){if(this.eventHistory.push(e),this.dispatchedCount++,this.eventSubs.size!==0)for(const n of this.eventSubs)try{const r=n(e);r&&typeof r.then=="function"&&r.catch(()=>{})}catch{}}emitInternal(e,n){this.emitEvent(e,n)}onEvent(e){return this.eventSubs.add(e),()=>{this.eventSubs.delete(e)}}history(){return[...this.eventHistory]}primeEventHistory(e){return this.eventHistory.length>0||e.length===0?0:(this.eventHistory.push(...e),e.length)}get admin(){return{getDocument:e=>this._env.getDocument(e),listDocuments:e=>this._env.listDocuments(e),setDocument:(e,n)=>this._env.adminSetDocument(e,n),deleteDocument:e=>this._env.adminDeleteDocument(e)}}reset(){const e={kind:"session_boundary",id:Bt(),at:Date.now(),phase:"reset",priorOpCount:this.dispatchedCount};this.emitEvent(e),this.eventHistory=[],this._currentUser!==null&&(this._currentUser=null,this.notifyCurrentUserSubs(null));for(const n of this.envUnsubs)n();this.envUnsubs=[],this._env.dispose(),this._env=new io,this.attachToEnv()}async resetAll(){this.reset();const e=[],n=[];for(const[r,s]of this.serviceRegistry)s.reset&&n.push(Promise.resolve().then(()=>s.reset()).catch(i=>{e.push(`${r}: ${i instanceof Error?i.message:String(i)}`)}));return await Promise.all(n),{errors:e}}dispose(){const e={kind:"session_boundary",id:Bt(),at:Date.now(),phase:"dispose",priorOpCount:this.dispatchedCount};this.emitEvent(e);for(const n of this.envUnsubs)n();this.envUnsubs=[],this._env.dispose(),this.persistence&&(this.persistence.dispose(),this.persistence=null),this.serviceRegistry.clear(),this._onServiceRegistered=null,this._onServiceUnregistered=null,this.eventSubs.clear(),this.currentUserSubs.clear()}snapshot(){const e={};for(const[n,r]of this.serviceRegistry)e[n]=r.snapshot();return{firestore:this._env.snapshot(),services:e}}loadSnapshot(e){this.reset();for(const[n,r]of Object.entries(e.firestore))this._env.adminSetDocument(n,r);for(const[n,r]of this.serviceRegistry)if(n in e.services)try{r.restore(e.services[n])}catch(s){console.warn(`[sandbox] loadSnapshot: service '${n}' restore failed — Firestore is intact; that service's state may be incomplete:`,s)}}get currentUser(){return this._currentUser}set currentUser(e){ti(e),!Xm(this._currentUser,e)&&(this._currentUser=e,this.notifyCurrentUserSubs(e))}onCurrentUserChanged(e){return this.currentUserSubs.add(e),()=>{this.currentUserSubs.delete(e)}}notifyCurrentUserSubs(e){if(this._env.reevaluateLiveListeners(e),this.currentUserSubs.size!==0)for(const n of this.currentUserSubs)try{const r=n(e);r&&typeof r.then=="function"&&r.catch(()=>{})}catch{}}async enablePersistence(e){if(this.persistence){if(this.persistence.options.key!==e.key)throw new ie("failed-precondition",`Persistence already enabled with key '${this.persistence.options.key}'; cannot re-enable with key '${e.key}'. Dispose and recreate the sandbox.`);return}if(this.enablePersistencePromise)return this.enablePersistencePromise;this.enablePersistencePromise=(async()=>{const n=await Bm(this,e);this.persistence=n})();try{await this.enablePersistencePromise}finally{this.enablePersistencePromise=null}}enableTabSync(e){return Km(this,e)}async flush(){if(!this.persistence)throw new ie("failed-precondition","flush() called before enablePersistence()");await this.persistence.flush()}async clearPersistence(){this.persistence&&await this.persistence.clear()}registerPersistableService(e,n){if(this.serviceRegistry.has(e))throw new ie("failed-precondition",`registerPersistableService: a service named '${e}' is already registered on this sandbox. Each service name must be unique — the auth package registers 'auth' exactly once per sandbox.`);return this.serviceRegistry.set(e,n),this._onServiceRegistered&&this._onServiceRegistered(e,n),()=>{this.serviceRegistry.get(e)===n&&(this.serviceRegistry.delete(e),this._onServiceUnregistered?.(e))}}setServiceRegistrationHook(e){this._onServiceRegistered=e}setServiceUnregistrationHook(e){this._onServiceUnregistered=e}getServiceRegistry(){return this.serviceRegistry}}function Xm(t,e){if(t===e)return!0;if(t===null||e===null||t.uid!==e.uid)return!1;const n=t.token===void 0?void 0:JSON.stringify(t.token),r=e.token===void 0?void 0:JSON.stringify(e.token);return n===r}function Xe(t){if(!(t instanceof Nt))throw new ie("invalid-argument","Sandbox handle was not produced by initializeSandbox(); custom Sandbox implementations are not supported.");return t.getEnv()}function ny(t,e,n){if(!(t instanceof Nt))throw new ie("invalid-argument","Sandbox handle was not produced by initializeSandbox(); custom Sandbox implementations are not supported.");t.emitInternal(e,n)}function ry(t){return{kind:"service_mutation",id:Bt(),at:Date.now(),...t}}function sy(t){const{at:e,...n}=t;return{kind:"operation",id:Bt(),at:e??Date.now(),...n}}function iy(t){const{at:e,...n}=t;return{kind:"commit",id:Bt(),at:e??Date.now(),...n}}function ay(t){const{at:e,...n}=t;return{kind:"listener",id:Bt(),at:e??Date.now(),...n}}function oy(){return Nt.createRoot()}const eg=Symbol.for("pyric.remote.sandbox");function Di(t){return t!=null&&t[eg]===!0}const tg={read:new Set(["auth","data","root","now"]),write:new Set(["auth","data","newData","root","now"]),validate:new Set(["auth","data","newData","root","now"])},ng=new Set(["val","exists","hasChild","hasChildren","isString","isNumber","isBoolean","child","parent","getPriority"]),rg=new Set(["matches","contains","beginsWith","endsWith","replace","toLowerCase","toUpperCase","length"]),sg=new Set([...ng,...rg]);let Fn=[],ar="read",au=new Set,gs;function ig(){if(gs)return gs;const t=Bf();return t.addOperation("validate",{_nonterminal(...e){e.forEach(n=>n.validate())},_iter(...e){e.forEach(n=>n.validate())},_terminal(){},CallExpr_methodCall(e,n,r,s,i,a){e.validate();const o=r.sourceString;sg.has(o)||Fn.push({code:"UNKNOWN_METHOD",message:`Unknown method '${o}'`}),i.asIteration().children.forEach(c=>c.validate())},CallExpr_memberAccess(e,n,r){e.validate()},CallExpr_indexAccess(e,n,r,s){e.validate(),r.validate()},ident(e,n,r){const s=this.sourceString;if(e.sourceString==="$")return;const a=tg[ar];a&&(!a.has(s)&&!au.has(s)&&Fn.push({code:"UNKNOWN_IDENTIFIER",message:`Identifier '${s}' is not allowed in '${ar}' context`}),s==="newData"&&ar==="read"&&Fn.push({code:"NEWDATA_IN_READ",message:"'newData' is not available in 'read' context"}))}}),gs=t,t}function cy(t,e,n=[]){const r=Uf(t);return r.failed()?[]:(Fn=[],ar=e,au=new Set(n.map(s=>s.startsWith("$")?s.slice(1):s)),ig()(r).validate(),[...Fn])}const uy=He({operation:mn(["read","write","validate"]),path:qe().min(1).startsWith("/"),auth:Kr([He({uid:qe(),token:Tt(mt())}),Ac()]),mockData:Tt(mt()),newData:mt().optional(),updates:xc(He({path:qe().min(1).startsWith("/"),value:mt()})).optional()});mn(["INVALID_INPUT","NO_MATCHING_RULE","EVALUATION_ERROR"]);He({allowed:$n(),unsupported:$n().optional(),matchedPath:qe(),matchedRule:qe(),reason:qe(),pathVariableBindings:Tt(qe())});const ho="-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz";let fo=0;const jt=new Array(12).fill(0);function ly(t=Date.now()){const e=t===fo;fo=t;const n=new Array(8);let r=t;for(let i=7;i>=0;i--)n[i]=ho.charAt(r%64),r=Math.floor(r/64);if(r!==0)throw new Error("RTDB push-id: timestamp overflow.");let s=n.join("");if(e){let i;for(i=11;i>=0&&jt[i]===63;i--)jt[i]=0;if(i<0)for(let a=0;a<12;a++)jt[a]=Math.floor(Math.random()*64);else jt[i]=(jt[i]??0)+1}else for(let i=0;i<12;i++)jt[i]=Math.floor(Math.random()*64);for(let i=0;i<12;i++)s+=ho.charAt(jt[i]);if(s.length!==20)throw new Error(`RTDB push-id: bad length ${s.length}.`);return s}function Un(t){return t.replace(/^\/+|\/+$/g,"").split("/")}function ou(t){return Un(t).length%2===0&&Un(t).length>0}function Mi(t){return Un(t).length%2===1}function Yr(t){const e=Un(t);return e[e.length-1]??""}function cu(t){return Un(t).slice(0,-1).join("/")}function uu(t,e){const n=e!==void 0,r=n?Gn(e):void 0;return{id:t.id,ref:t,exists:n,data:()=>n?r:void 0,get:s=>wn(r,s)}}const po=new WeakMap;let ag=1;function mo(t){let e=po.get(t);return e===void 0&&(e=ag++,po.set(t,e)),e}function $r(t){if(t===null||typeof t=="boolean")return t;if(typeof t=="string")return Op(t);if(typeof t>"u")return{type:"undefined"};if(typeof t=="bigint")return Zt("bigint",t.toString());if(typeof t=="number"){const n=Number.isNaN(t)?"NaN":t===1/0?"Infinity":t===-1/0?"-Infinity":Object.is(t,-0)?"-0":String(t);return Zt("number",n)}if(typeof t!="object"&&typeof t!="function")return{type:typeof t,value:String(t)};const e=Tp(t);if(e!==void 0)return e;try{if(Array.isArray(t))return{type:"array",id:mo(t)}}catch{}return{type:"opaque-object",id:mo(t)}}function _t(t){return new ue({code:"invalid-argument",message:t})}function si(t,e,n,r=!1,s=!1){if(t===null||typeof t=="string"||typeof t=="boolean")return{comparison:t,execution:t};if(typeof t=="number")return{comparison:t,execution:t};if(typeof t>"u"||typeof t=="bigint"||typeof t=="function"||typeof t=="symbol")throw _t(`Unsupported Firestore query value: ${typeof t}.`);if(typeof t!="object")throw _t("Unsupported Firestore query value.");const i=kc(t);if(i!==void 0){const o=np(t);if(o!==void 0&&n!==void 0&&o!==n)throw _t("Document reference belongs to a different Firestore database.");return{comparison:{type:"registered-firestore-value",value:i},execution:rp(t)}}if(t instanceof Date){const o=t.getTime();if(!Number.isFinite(o))throw _t("Invalid Date query value.");const c=Math.floor(o/1e3),u=Object.freeze({seconds:c,nanoseconds:Math.floor((o-c*1e3)*1e6)}),d={type:"timestamp",...u};return tn(u,d,()=>Object.freeze({...u})),{comparison:{type:"registered-firestore-value",value:d},execution:u}}if(t instanceof Uint8Array){const o=t.slice();return{comparison:{type:"bytes",values:Array.from(o)},execution:o}}if(e.has(t))throw _t("Cyclic query operands are not Firestore values.");const a=Object.getPrototypeOf(t);if(a!==Object.prototype&&a!==null&&!Array.isArray(t))throw _t("Firestore query maps must be plain objects.");e.add(t);try{if(Array.isArray(t)){if(s&&!r)throw _t("Nested arrays are not supported.");const u=t.map(l=>si(l,e,n,r,!0)),d=u.map(l=>l.execution);return ut(d,$r(t)),{comparison:{type:"array",values:u.map(l=>l.comparison)},execution:d}}const o=Object.keys(t).sort().map(u=>({key:u,captured:si(t[u],e,n,r,!1)})),c=Object.fromEntries(o.map(({key:u,captured:d})=>[u,d.execution]));return ut(c,$r(t)),{comparison:{type:"map",entries:o.map(({key:u,captured:d})=>[u,d.comparison])},execution:c}}finally{e.delete(t)}}function lu(t,e,n=!1){try{const r=si(t,new Set,e,n);return Object.freeze({kind:"canonical",value:r.comparison,executionValue:r.execution})}catch(r){if(r instanceof ue)throw r;const s=r instanceof Error?r.message:String(r);throw _t(`Invalid Firestore query value: ${s}`)}}function du(t,e){return Ye(t.value,e.value)}function or(t,e){if(t.kind==="where"){const n="comparisonValue"in t?t.comparisonValue:lu(t.value,e,t.op==="in"||t.op==="not-in");return Object.freeze({kind:"where",field:t.field,op:t.op,value:n.executionValue,comparisonValue:n})}return Object.freeze({kind:t.kind,filters:Object.freeze(t.filters.map(n=>or(n,e)))})}function er(t,e,n,r){const s=t.map(i=>lu(i,r));return Object.freeze({values:Object.freeze(s.map(i=>i.executionValue)),comparisonValues:Object.freeze(s),inclusive:e,fromSnapshot:n})}function hu(t,e){return t.length!==e.length?!1:t.every((n,r)=>{const s=e[r];return n.kind!==s.kind?!1:n.kind==="where"&&s.kind==="where"?n.field===s.field&&n.op===s.op&&du(n.comparisonValue,s.comparisonValue):n.kind!=="where"&&s.kind!=="where"&&hu(n.filters,s.filters)})}function go(t,e){return t===void 0||e===void 0?t===e:t.inclusive===e.inclusive&&t.comparisonValues.length===e.comparisonValues.length&&t.comparisonValues.every((n,r)=>du(n,e.comparisonValues[r]))}function og(t,e){return t.kind!==e.kind?!1:t.kind==="collection"&&e.kind==="collection"?t.path===e.path:t.kind==="collection-group"&&e.kind==="collection-group"&&t.collectionId===e.collectionId}function fu(t){return t.kind==="where"?Object.freeze({kind:t.kind,field:t.field,op:t.op,value:t.value}):Object.freeze({kind:t.kind,filters:Object.freeze(t.filters.map(fu))})}function yo(t){if(t!==void 0)return Object.freeze({values:t.values,inclusive:t.inclusive,fromSnapshot:t.fromSnapshot})}function cg(t,e){return hu(t.filters,e.filters)&&t.orders.length===e.orders.length&&t.orders.every((n,r)=>{const s=e.orders[r];return n.field===s.field&&n.direction===s.direction})&&t.limitCount===e.limitCount&&t.limitFromEnd===e.limitFromEnd&&go(t.start,e.start)&&go(t.end,e.end)}const pu="__name__";function bo(t,e){const n=t.data();if(n===void 0)throw new ue({code:"not-found",message:`Snapshot-based cursors require an existing document — got an empty snapshot for ${t.id??"<unknown>"}.`});return e.map(r=>r.field===pu?t.ref:n[r.field])}class Bn{env;auth;collectionPath;clauses;orders;limitCount;limitFromEnd;start;end;bypassRules;documentRef;constructor(e){this.env=e.env,this.auth=e.auth,this.collectionPath=e.collectionPath,this.documentRef=e.documentRef,this.clauses=Object.freeze((e.clauses??[]).map(n=>or(n))),this.orders=Object.freeze((e.orders??[]).map(n=>Object.freeze({...n}))),this.limitCount=e.limitCount,this.limitFromEnd=e.limitFromEnd??!1,this.start=e.start===void 0?void 0:Object.freeze({...e.start,values:Object.freeze(e.start.comparisonValues.map(n=>n.executionValue)),comparisonValues:e.start.comparisonValues}),this.end=e.end===void 0?void 0:Object.freeze({...e.end,values:Object.freeze(e.end.comparisonValues.map(n=>n.executionValue)),comparisonValues:e.end.comparisonValues}),this.bypassRules=e.bypassRules??!1}where(e,n,r){return this.clone({clauses:[...this.clauses,or({kind:"where",field:e,op:n,value:r})]})}applyFilter(e){return this.clone({clauses:[...this.clauses,or(e)]})}orderBy(e,n="asc"){return this.clone({orders:[...this.orders,{field:e,direction:n}]})}limit(e){return this.clone({limitCount:e,limitFromEnd:!1})}limitToLast(e){return this.clone({limitCount:e,limitFromEnd:!0})}startCursor(e,n){return this.clone({start:er(this.normalizeExplicitCursorValues(e),n,!1)})}endCursor(e,n){return this.clone({end:er(this.normalizeExplicitCursorValues(e),n,!1)})}startCursorFromSnapshot(e,n){return this.clone({start:er(bo(e,this.normalizedOrders()),n,!0)})}endCursorFromSnapshot(e,n){return this.clone({end:er(bo(e,this.normalizedOrders()),n,!0)})}isStructurallyEqual(e){return e instanceof Bn?this.env===e.env&&this.bypassRules===e.bypassRules&&og(this.queryScope(),e.queryScope())&&cg(this.comparableExecutionSpec(),e.comparableExecutionSpec()):!1}clone(e){return new Bn({env:this.env,auth:this.auth,collectionPath:this.collectionPath,documentRef:this.documentRef,clauses:e.clauses??this.clauses,orders:e.orders??this.orders,limitCount:"limitCount"in e?e.limitCount:this.limitCount,limitFromEnd:e.limitFromEnd??this.limitFromEnd,start:"start"in e?e.start:this.start,end:"end"in e?e.end:this.end,bypassRules:this.bypassRules})}queryScope(){return{kind:"collection",path:this.collectionPath}}readQueryRows(e){const n=e?.auth!==void 0?e.auth:this.auth;let r;try{r=this.env.runQuery({scope:this.queryScope(),auth:n,execution:this.executionSpec(),bypassRules:this.bypassRules,activityQuery:this.activityQuery()})}catch(s){const i=s?.simError;throw i?new ue(i):s}if(!r.allowed)throw new ue(r.error);return r.docs}activityQuery(){const e=r=>r.kind==="where"?{kind:"where",field:r.field,op:r.op,value:$r(r.value)}:{kind:r.kind,filters:r.filters.map(e)},n=r=>r===void 0?null:{values:r.values.map(s=>$r(s)),inclusive:r.inclusive,fromSnapshot:r.fromSnapshot};return{scope:this.activityScope(),filters:this.clauses.map(e),orderBy:this.orders.map(r=>({...r})),limit:this.limitCount??null,limitFromEnd:this.limitFromEnd,start:n(this.start),end:n(this.end)}}activityScope(){return{kind:"collection"}}normalizedOrders(){return Wc(this.executionSpec())}normalizeExplicitCursorValues(e){const n=this.orders;return e.map((r,s)=>{if(n[s]?.field!==pu)return r;if(typeof r!="string")throw new ue({code:"invalid-argument",message:"Expected a string for a document ID cursor value."});const i=r.includes("/")?r:`${this.collectionPath}/${r}`;return this.documentRef(i)})}executionSpec(){const e={filters:Object.freeze(this.clauses.map(fu)),orders:this.orders,limitCount:this.limitCount,limitFromEnd:this.limitFromEnd,start:yo(this.start),end:yo(this.end)};return Object.freeze(e)}comparableExecutionSpec(){return{filters:this.clauses,orders:this.orders,limitCount:this.limitCount,limitFromEnd:this.limitFromEnd,start:this.start,end:this.end}}snapshotConstraints(){return Object.freeze({execution:this.executionSpec(),activityQuery:this.activityQuery()})}async get(e){const r=this.readQueryRows(e).map(s=>{const i=this.documentRef(s.path),a=Gn(s.data);return{id:i.id,ref:i,exists:!0,data:()=>a,get:o=>wn(a,o)}});return{size:r.length,empty:r.length===0,docs:r,forEach(s){r.forEach(s)}}}async aggregate(e,n){const r=this.readQueryRows(n),s={};for(const i of Object.keys(e))s[i]=lg(e[i],r);return{data:()=>s}}}function ug(t,e){if(!e.includes("."))return t[e];let n=t;for(const r of e.split(".")){if(typeof n!="object"||n===null||Array.isArray(n))return;n=n[r]}return n}function lg(t,e){if(t.kind==="count")return e.length;let n=0,r=0;for(const s of e){const i=ug(s.data,t.field);typeof i=="number"&&Number.isFinite(i)&&(n+=i,r++)}return t.kind==="sum"?n:r===0?null:n/r}function sn(t,e){if(t.error)throw new ue(t.error);const n=t.debugMessages.length>0?t.debugMessages.join("; "):"(no debug message)";throw new ue(te("permission-denied",`${e}: ${n}`))}class dg{env;auth;bypassRules;collectionRef;id;path;constructor(e,n,r,s=!1,i){this.env=e,this.auth=n,this.bypassRules=s,this.collectionRef=i,this.path=r,this.id=Yr(r),ut(this,Zt("reference",r)),Ei(this,r,e)}get parent(){return this.collectionRef(cu(this.path))}collection(e){return this.collectionRef(`${this.path}/${e}`)}async get(e){const n=this.env.execute({method:"get",path:this.path,auth:e?.auth!==void 0?e.auth:this.auth,bypassRules:this.bypassRules});n.allowed||sn(n,"get denied");const r=n.data===void 0||n.data===null?void 0:n.data;return uu(this,r)}async set(e,n){const r=n?.auth!==void 0?n.auth:this.auth;if(n?.mergeFields!==void 0){const i=n.mergeFields.map(u=>String(u)),o=this.env.getDocument(this.path)===null?"create":"update",c=this.env.execute({method:o,path:this.path,data:e,auth:r,merge:{mergeFields:i},bypassRules:this.bypassRules});c.allowed||sn(c,`set denied (as ${o})`);return}if(n?.merge===!0){const a=this.env.getDocument(this.path)===null?"create":"update",o=this.env.execute({method:a,path:this.path,data:e,auth:r,merge:!0,bypassRules:this.bypassRules});o.allowed||sn(o,`set denied (as ${a})`);return}const s=this.env.execute({method:"set",path:this.path,data:e,auth:r,bypassRules:this.bypassRules});s.allowed||sn(s,"set denied")}async update(e,n){const r=this.env.execute({method:"update",path:this.path,data:e,auth:n?.auth!==void 0?n.auth:this.auth,bypassRules:this.bypassRules});r.allowed||sn(r,"update denied")}async delete(e){const n=this.env.execute({method:"delete",path:this.path,auth:e?.auth!==void 0?e.auth:this.auth,bypassRules:this.bypassRules});n.allowed||sn(n,"delete denied")}}function qr(t,e,n,r){return new dg(t,e,n,r,s=>new mu(t,e,s,r))}class mu extends Bn{id;path;constructor(e,n,r,s=!1){super({env:e,auth:n,collectionPath:r,bypassRules:s,documentRef:i=>qr(e,n,i,s)}),this.path=r,this.id=Yr(r)}doc(e){const n=e??Ti();return qr(this.env,this.auth,`${this.path}/${n}`,this.bypassRules)}async add(e,n){const r=this.doc();return await r.set(e,n),r}}class ji extends Bn{collectionId;constructor(e){super({...e,collectionPath:"",documentRef:n=>qr(e.env,e.auth,n,e.bypassRules??!1)}),this.collectionId=e.collectionId}clone(e){return new ji({env:this.env,auth:this.auth,collectionId:this.collectionId,clauses:e.clauses??this.clauses,orders:e.orders??this.orders,limitCount:"limitCount"in e?e.limitCount:this.limitCount,limitFromEnd:e.limitFromEnd??this.limitFromEnd,start:"start"in e?e.start:this.start,end:"end"in e?e.end:this.end,bypassRules:this.bypassRules})}queryScope(){return{kind:"collection-group",collectionId:this.collectionId}}activityScope(){return{kind:"collection-group"}}}class hg{env;auth;bypassRules;ops=[];constructor(e,n,r=!1){this.env=e,this.auth=n,this.bypassRules=r}set(e,n){const s=this.env.getDocument(e.path)===null?"create":"update";return this.ops.push({method:s,path:e.path,data:n}),this}update(e,n){return this.ops.push({method:"update",path:e.path,data:n}),this}delete(e){return this.ops.push({method:"delete",path:e.path}),this}async commit(e){if(this.ops.length===0)return;const n=this.env.batch(this.ops,e?.auth!==void 0?e.auth:this.auth,this.bypassRules);if(n.allowed)return;if(n.error)throw new ue(n.error);const s=n.results.find(i=>!i.allowed)?.debugMessages.join("; ")??"batch denied";throw new ue(te("permission-denied",`batch failed: ${s}`))}}function fg(t){return typeof t.where=="function"}class pg{simTx;constructor(e){this.simTx=e}async get(e){if(fg(e)){const s=await e.get();return s.size>0&&this.simTx.getAll(...s.docs.map(i=>i.ref.path)),s}const r=this.simTx.get(e.path).data();return uu(e,r)}set(e,n){return this.simTx.set(e.path,n),this}update(e,n){return this.simTx.update(e.path,n),this}delete(e){return this.simTx.delete(e.path),this}}class mg{env;auth;bypassRules;provenance;constructor(e,n,r=!1,s){this.env=e,this.auth=n,this.bypassRules=r,this.provenance=s}collection(e){if(!Mi(e))throw new ue(te("invalid-argument",`collection path must have an odd number of segments: ${e}`));return new mu(this.env,this.auth,e,this.bypassRules)}doc(e){if(!ou(e))throw new ue(te("invalid-argument",`document path must have an even number of segments: ${e}`));return qr(this.env,this.auth,e,this.bypassRules)}collectionGroup(e){if(e.length===0||e.includes("/"))throw new ue(te("invalid-argument",`collection group id must be a single non-empty segment with no '/': ${e}`));return new ji({env:this.env,auth:this.auth,collectionId:e,bypassRules:this.bypassRules})}batch(){return new hg(this.env,this.auth,this.bypassRules)}async runTransaction(e,n){let r;try{r=await this.env.transaction(s=>{const i=new pg(s);return e(i)},{auth:n?.auth!==void 0?n.auth:this.auth,bypassRules:this.bypassRules,provenance:this.provenance,maxAttempts:n?.maxAttempts})}catch(s){throw s instanceof Kc?new ue(s.simError):s instanceof Zc?new ue(s.simError):s}if(!r.allowed){if(r.error)throw new ue(r.error);const i=r.writes.find(a=>!a.allowed)?.debugMessages.join("; ")??"transaction denied at commit";throw new ue(te("permission-denied",`transaction failed: ${i}`))}return r.returnValue}}function gg(t,e){return new mg(t,e?.auth??null,e?.bypassRules??!1,e?.provenance)}const gu=Symbol("pyric/sandbox/context"),yu=Symbol("pyric/sandbox/bypassRules");let ii=null;function yg(t){ii=t}function bg(t){const e=t;return typeof e.path=="string"&&e.path.length>0||typeof e.collectionPath=="string"&&e.collectionPath.length>0}function vg(t){const e=t.trim();if(!e)return[];const n=e.indexOf(": ");if(n!==-1){const s=e.slice(n+2).trim().split("; ").map(i=>i.trim()).filter(i=>i.length>0);if(s.length>0)return s}return[e]}function vo(t,e){if(t instanceof ue===!1)return t;const r=t.code;if(r==="permission-denied"===!1)return new ie(r,t.message);const i={auth:e.auth,reasons:vg(t.message)},a=t.simError;if(a!==void 0){if(a.request!==void 0){const y=a.request;i.request={method:y.method,path:y.path},y.resourceData!==void 0&&(i.request.resourceData=y.resourceData)}if(a.resource!==void 0&&(i.resource={data:a.resource.data,exists:a.resource.exists}),a.query!==void 0&&(i.query=a.query),a.rule!==void 0&&(i.rule=a.rule),a.remediation!==void 0)return new ie({code:r,message:t.message,denialContext:i,remediation:a.remediation})}return new ie(r,t.message,i)}function Ur(t,e,n=!1){return new Proxy(t,{get(r,s,i){if(s===gu)return e;if(s===yu)return n;if(s==="onSnapshot"&&ii!==null&&!(s in r)&&bg(r))return(...o)=>ii(i,...o);const a=Reflect.get(r,s,i);return typeof a!="function"?a:function(...o){let c;try{const u=()=>a.apply(r,o);c=e.sandbox.runWithProvenance?.(Ri(e.operationContext),u)??u()}catch(u){throw vo(u,e)}return c instanceof Promise?c.then(u=>u&&typeof u=="object"?Ur(u,e,n):u).catch(u=>{throw vo(u,e)}):c&&typeof c=="object"?Ur(c,e,n):c}}})}function bu(t,e=!1){if(Di(t.sandbox))throw new Error("pyric/sandbox/admin-firestore: internal — a remote sandbox context reached the local engine builder; remote dispatch should have handled it. Please report this.");const n=()=>gg(Xe(t.sandbox),{auth:t.auth,bypassRules:e,provenance:Ri(t.operationContext)});return{collection(r){return n().collection(r)},doc(r){return n().doc(r)},collectionGroup(r){return n().collectionGroup(r)},batch(){return n().batch()},runTransaction(r,s){return n().runTransaction(r,s)},setRules(r){return Xe(t.sandbox).deployRules(r)},seed(r){const s=Xe(t.sandbox);return s.seed({rules:s.getRules(),documents:r?.documents??{}})},snapshot(){return Xe(t.sandbox).snapshot()}}}function ai(t){if(t instanceof ie)return t;if(t!==null&&typeof t=="object"){const e=t;if(typeof e.code=="string"&&typeof e.message=="string"){const n=e.denialContext!==null&&typeof e.denialContext=="object"?e.denialContext:void 0;return new ie(e.code,e.message,n)}}return t}function yt(t){return new ie("invalid-argument",t)}async function et(t,e){try{return await t.sandbox.channel.op({...e,actAs:t.lens})}catch(n){throw ai(n)}}const wg=new Set(["serverTimestamp","increment","arrayUnion","arrayRemove","deleteField"]);function Sg(t){return t!==null&&typeof t=="object"&&typeof t.__type=="string"&&wg.has(t.__type)}function _g(t){switch(t.__type){case"serverTimestamp":return{__sentinel:"serverTimestamp"};case"increment":return{__sentinel:"increment",n:t.value};case"arrayUnion":return{__sentinel:"arrayUnion",values:t.values.map(vt)};case"arrayRemove":return{__sentinel:"arrayRemove",values:t.values.map(vt)};case"deleteField":return{__sentinel:"deleteField"}}}function vt(t){if(t===null||typeof t!="object")return t;if(Sg(t))return _g(t);if(t instanceof xt)return t.toJSON();if(t instanceof Date)return xt.fromDate(t).toJSON();if(Array.isArray(t))return t.map(vt);const e=Object.getPrototypeOf(t);if(e!==Object.prototype&&e!==null){const r=t.toJSON;if(typeof r=="function")return r.call(t);throw yt(`remote Firestore: cannot serialize a ${e.constructor?.name??"class"} instance for the wire — use plain data, Timestamp, Date, or FieldValue sentinels.`)}const n={};for(const[r,s]of Object.entries(t))n[r]=vt(s);return n}function Jt(t){return vt(t)}function oi(t){return Fi(JSON.parse(t.json))}function vu(t){return Gn(oi(t))}function wu(t,e){const n=e.exists&&e.data?vu(e.data):void 0;return{id:t.id,ref:t,exists:e.exists,data:()=>n,get:r=>wn(n,r)}}function Su(t,e){const n=e.docs.map(r=>{const s=r.path??r.id,i=Br(t,s),a=r.data?vu(r.data):{};return{id:i.id,ref:i,exists:!0,data:()=>a,get:o=>wn(a,o)}});return{size:n.length,empty:n.length===0,docs:n,forEach(r){n.forEach(s=>r(s))}}}const Pi=Symbol("pyric/sandbox/admin-firestore/remoteSnapshotRegistrar");function Ag(t){if(t===null||typeof t!="object")return;const e=t[Pi];return typeof e=="function"?e:void 0}let ci=null;function xg(t){ci=t}function _u(...t){if(ci===null)throw new ie("failed-precondition","remote Firestore: onSnapshot is not wired yet — import pyric-admin/firestore (or pyric/sandbox/admin-firestore) before subscribing.");return ci(this,...t)}function Au(t,e,n,r,s){const i=n.includeMetadataChanges!==!0;let a,o;try{o=t.sandbox.channel.subscribe({target:e,actAs:t.lens},c=>{if(!r)return;const u=c;if(Array.isArray(u.docs)){const d=u.docs.map(y=>({path:y.path??y.id,data:y.data?oi(y.data):{}})),l=e.__ref==="query"?e.source.__ref==="group"?e.source.collectionId:e.source.path:e.__ref==="group"?e.collectionId:e.path,p=cn({path:l},d,{excludesMetadataChanges:i},a);a=d,r(p)}else if(typeof u.id=="string"){const d=u.path??u.id,l=u.exists&&u.data?oi(u.data):null;r(on(d,l))}},c=>{const u=ai(c);s?s(u):console.error("pyric remote Firestore: uncaught onSnapshot error:",u)})}catch(c){throw ai(c)}return o}const xu=Symbol("pyric/sandbox/admin-firestore/remoteQueryState");function Ig(t){if(!(t===null||typeof t!="object"))return t[xu]}function Iu(t){return t.kind==="where"?(Eu(t.op),{kind:"where",field:t.field,op:t.op,value:vt(t.value)}):{kind:t.kind,filters:t.filters.map(Iu)}}const Eg=new Set(["<","<=","==","!=",">=",">","in","not-in","array-contains","array-contains-any"]);function Eu(t){if(!Eg.has(t))throw yt(`invalid where operator: ${String(t)}`)}function cr(t){const e=[...t.filters];for(const n of t.orders)e.push({kind:"orderBy",field:n.field,direction:n.direction});return t.start&&e.push({kind:t.start.inclusive?"startAt":"startAfter",values:t.start.values.map(vt)}),t.end&&e.push({kind:t.end.inclusive?"endAt":"endBefore",values:t.end.values.map(vt)}),t.limitCount!==void 0&&e.push(t.limitFromEnd?{kind:"limitToLast",n:t.limitCount}:{kind:"limit",n:t.limitCount}),e.length===0?t.source:{__ref:"query",source:t.source,constraints:e}}function wo(t,e,n){if(e.length===0)throw yt(`${n}(snapshot) on a remote sandbox requires at least one explicit orderBy() clause — the relay protocol has no document-key cursor.`);if(e.some(s=>s.field==="__name__"))throw yt(`${n}(snapshot) on a remote sandbox does not support orderBy('__name__') — the relay protocol has no document-key cursor, and __name__ is not a data field a value cursor can carry. Order by a real document field instead.`);const r=t.data();if(r===void 0)throw new ie("not-found",`Snapshot-based cursors require an existing document — got an empty snapshot for ${t.id??"<unknown>"}.`);return e.map(s=>r[s.field])}function $i(t,e){const n=s=>$i(t,{...e,...s});return{[xu]:e,where(s,i,a){return Eu(i),n({filters:[...e.filters,{kind:"where",field:s,op:i,value:vt(a)}]})},applyFilter(s){return n({filters:[...e.filters,Iu(s)]})},orderBy(s,i="asc"){return n({orders:[...e.orders,{field:s,direction:i}]})},limit(s){return n({limitCount:s,limitFromEnd:!1})},limitToLast(s){return n({limitCount:s,limitFromEnd:!0})},startCursor(s,i){return n({start:{values:[...s],inclusive:i}})},endCursor(s,i){return n({end:{values:[...s],inclusive:i}})},startCursorFromSnapshot(s,i){return n({start:{values:wo(s,e.orders,i?"startAt":"startAfter"),inclusive:i}})},endCursorFromSnapshot(s,i){return n({end:{values:wo(s,e.orders,i?"endAt":"endBefore"),inclusive:i}})},async get(s){ur(e);const i=await et(t,{method:"getDocs",source:cr(e)});return Su(t,i)},async aggregate(s){ur(e);const i=await et(t,{method:"aggregate",source:cr(e),spec:s});return{data:()=>i.data}},[Pi]:(s,i,a)=>(ur(e),Au(t,cr(e),s,i,a)),onSnapshot:_u}}function ur(t){if(t.limitFromEnd&&t.orders.length===0)throw yt("limitToLast() queries require at least one orderBy clause.")}function ui(t,e){const n=$i(t,{source:{__ref:"collection",path:e},filters:[],orders:[],limitFromEnd:!1});return Object.assign(Object.create(Object.getPrototypeOf(n)),n,{id:Yr(e),path:e,doc(s){const i=s??Ti();return Br(t,`${e}/${i}`)},async add(s,i){const a=await et(t,{method:"addDoc",collectionPath:e,data:Jt(s)});return Br(t,a.path)}})}function Br(t,e){const n={id:Yr(e),path:e,get parent(){return ui(t,cu(e))},collection(r){const s=`${e}/${r}`;if(!Mi(s))throw yt(`collection path must have an odd number of segments: ${s}`);return ui(t,s)},async get(r){const s=await et(t,{method:"getDoc",path:e});return wu(n,s)},async set(r,s){await et(t,{method:"setDoc",path:e,data:Jt(r),...So(s)?{options:So(s)}:{}})},async update(r,s){await et(t,{method:"updateDoc",path:e,data:Jt(r)})},async delete(r){await et(t,{method:"deleteDoc",path:e})},[Pi]:(r,s,i)=>Au(t,{__ref:"doc",path:e},r,s,i),onSnapshot:_u};return n}function So(t){if(!t)return;const e={};return t.merge!==void 0&&(e.merge=t.merge),t.mergeFields!==void 0&&(e.mergeFields=[...t.mergeFields]),e.merge!==void 0||e.mergeFields!==void 0?e:void 0}function kg(t){const e=[];let n=!1;const r={set(i,a){return s(),e.push({method:"set",path:i.path,data:Jt(a)}),r},update(i,a){return s(),e.push({method:"update",path:i.path,data:Jt(a)}),r},delete(i){return s(),e.push({method:"delete",path:i.path}),r},async commit(i){s(),n=!0,await et(t,{method:"batchCommit",writes:e})}};function s(){if(n)throw new ie("failed-precondition","WriteBatch has already been committed.")}return r}const Og=5;async function Cg(t,e,n=Og){for(let r=0;r<n;r++){const s=[],i=[],a=()=>{if(i.length>0)throw new ie("failed-precondition",Xs)},o={get(l){a();const p=Ig(l);return p!==void 0?u(p):c(l)},set(l,p){return i.push({method:"set",path:l.path,data:Jt(p)}),o},update(l,p){return i.push({method:"update",path:l.path,data:Jt(p)}),o},delete(l){return i.push({method:"delete",path:l.path}),o}};async function c(l){const p=await et(t,{method:"getDoc",path:l.path});return s.push({path:p.path??l.path,data:p.exists&&p.data?p.data:null}),wu(l,p)}async function u(l){ur(l);const p=await et(t,{method:"getDocs",source:cr(l)});for(const y of p.docs)s.push({path:y.path??y.id,data:y.data??null});return Su(t,p)}const d=await e(o);try{return await et(t,{method:"txnCommit",reads:s,writes:i}),d}catch(l){if(l instanceof ie&&l.code==="aborted")continue;throw l}}throw new ie("aborted",`Transaction failed after ${n} attempts due to repeated conflicts. Another writer is concurrently updating the same documents.`)}function ys(t,e){return new ie("unimplemented",`SandboxFirestore.${t} is not available on a remote sandbox — its return value is synchronous and the data lives in the browser worker. ${e}`)}function ku(t,e){const n={sandbox:t,lens:e};return{collection(r){if(!Mi(r))throw yt(`collection path must have an odd number of segments: ${r}`);return ui(n,r)},doc(r){if(!ou(r))throw yt(`document path must have an even number of segments: ${r}`);return Br(n,r)},collectionGroup(r){if(r.length===0||r.includes("/"))throw yt(`collection group id must be a single non-empty segment with no '/': ${r}`);return $i(n,{source:{__ref:"group",collectionId:r},filters:[],orders:[],limitFromEnd:!1})},batch(){return kg(n)},runTransaction(r,s){return Cg(n,r,s?.maxAttempts)},setRules(){throw ys("setRules","Deploy rules asynchronously through the relay instead: `await sandbox.channel.op({ method: 'setFirestoreRules', source })`.")},seed(){throw ys("seed","The relay has no atomic seed op; write seed docs through this handle (`db.doc(path).set(data)` / `db.batch()`), or drive `sandbox.channel.op({ method: 'admin.setDocument', path, data })` per document.")},snapshot(){throw ys("snapshot","Read the worker state asynchronously instead: `await sandbox.channel.op({ method: 'admin.readState' })`.")}}}const _o=new WeakMap;function Ou(t){const e=_o.get(t);if(e)return e;const n=Di(t.sandbox)?ku(t.sandbox,Tg(t.auth)):Ur(bu(t),t);return _o.set(t,n),n}function Tg(t){return t==null?{mode:"anon"}:t.token===void 0?{mode:"as",uid:t.uid}:{mode:"as",uid:t.uid,token:t.token}}const Ao=new WeakMap;function Rg(t){const e=Ng(t)?t:t.withAuth(null),n=Ao.get(e);if(n)return n;const r=e.operationContext.authLens.mode==="admin"?e:Li(e,{source:e.operationContext.source,authLens:{mode:"admin"},...e.operationContext.planId===void 0?{}:{planId:e.operationContext.planId}}),s=Di(r.sandbox)?ku(r.sandbox,{mode:"admin"}):Ur(bu(r,!0),r,!0);return Ao.set(e,s),s}function Ng(t){return t!==null&&typeof t=="object"&&"sandbox"in t&&typeof t.withAuth=="function"}const tr=Symbol("pyric/firestore/followsCurrentUser"),bs=Symbol("pyric/firestore/authSessionScope");function Lg(t){if(t===null||typeof t!="object")return null;const e=t;return typeof e.path=="string"&&e.path.length>0?e.path:typeof e.collectionPath=="string"&&e.collectionPath.length>0?e.collectionPath:null}function Fg(t){if(t!==null&&typeof t=="object"){const e=t.snapshotConstraints;if(typeof e=="function")return e.call(t)}}function Dg(t){if(t===null||typeof t!="object")return!1;const e=t;return typeof e.path=="string"&&e.path.length>0&&e.parent!==void 0&&e.parent!==null}function Cu(t,e,n,r,s){let i={},a,o;if(typeof e=="object"&&e!==null&&typeof e.next!="function"&&typeof e.error!="function"&&typeof e.complete!="function"){if(i=e,typeof n=="function")a=n,o=r;else if(typeof n=="object"&&n!==null){const C=n;a=C.next,o=C.error}}else if(typeof e=="function")a=e,o=n;else if(typeof e=="object"&&e!==null){const C=e;a=C.next,o=C.error}if(!a&&!o)throw new TypeError("onSnapshot: missing handler. Provide a callback, or an observer with a `next` and/or `error` method.");const u=Ag(t);if(u){if(i[tr]===!0)throw new ie("unimplemented","onSnapshot: live (follows-current-user) listeners are not supported on a remote sandbox — remote listeners are frozen to the identity of the context that created the ref.");return u(i,a,o)}const d=Mg(t),l=Xe(d.sandbox);let p;if(Dg(t))p={kind:"doc",path:t.path};else{const C=Lg(t);if(C===null)throw new TypeError("onSnapshot: could not determine the collection path for this Query. Pass a CollectionReference or a Query produced by `.where`/`.orderBy`/`.limit` on a CollectionReference obtained from `getFirestore(ctx)`.");const I=Fg(t);p={kind:"query",collection:C,constraints:I}}const y=i[tr]===!0,b=i[bs],w=t[yu]===!0;if(tr in i){const{[tr]:C,...I}=i;i=I}if(bs in i){const{[bs]:C,...I}=i;i=I}const R=()=>l.addSnapshotListener(p,a??(()=>{}),i,d.auth,o,y,w,b);return d.sandbox.runWithProvenance?.(Ri(d.operationContext),R)??R()}function Mg(t){if(t===null||typeof t!="object")throw new TypeError("onSnapshot: reference must be a DocumentReference or Query.");const e=t[gu];if(!e)throw new TypeError("onSnapshot: reference was not produced by a sandbox context — pass a ref obtained from `getFirestore(ctx)`.");return e}yg(Cu);xg(Cu);class qt{bytes;constructor(e){this.bytes=e,ut(this,Cp(e)),tn(this,Object.freeze({type:"bytes",values:Object.freeze(Array.from(e))}),()=>new qt(e.slice()))}static fromBase64String(e){const n=atob(e),r=new Uint8Array(n.length);for(let s=0;s<n.length;s+=1)r[s]=n.charCodeAt(s);return new qt(r)}static fromUint8Array(e){return new qt(e.slice())}toBase64(){let e="";for(const n of this.bytes)e+=String.fromCharCode(n);return btoa(e)}toUint8Array(){return this.bytes.slice()}toString(){return`Bytes(base64: ${this.toBase64()})`}isEqual(e){return e instanceof qt&&this.bytes.length===e.bytes.length&&this.bytes.every((n,r)=>n===e.bytes[r])}toJSON(){return{type:"firestore/bytes/1.0",bytes:this.toBase64()}}static fromJSON(e){const n=e;if(n.type!=="firestore/bytes/1.0"||typeof n.bytes!="string")throw new TypeError("Invalid Bytes JSON value.");return qt.fromBase64String(n.bytes)}}class Dn{lat;lng;constructor(e,n){if(this.lat=e,this.lng=n,!Number.isFinite(e)||e<-90||e>90)throw new TypeError("Latitude must be a number between -90 and 90.");if(!Number.isFinite(n)||n<-180||n>180)throw new TypeError("Longitude must be a number between -180 and 180.");ut(this,Zt("geo-point",String(e),"\0",String(n))),tn(this,Object.freeze({type:"geo-point",latitude:e,longitude:n}),()=>new Dn(e,n))}get latitude(){return this.lat}get longitude(){return this.lng}isEqual(e){return e instanceof Dn&&this.lat===e.lat&&this.lng===e.lng}toJSON(){return{latitude:this.lat,longitude:this.lng,type:"firestore/geoPoint/1.0"}}static fromJSON(e){const n=e;if(n.type!=="firestore/geoPoint/1.0"||typeof n.latitude!="number"||typeof n.longitude!="number")throw new TypeError("Invalid GeoPoint JSON value.");return new Dn(n.latitude,n.longitude)}}class ln{_values;constructor(e){this._values=e,tn(this,Object.freeze({type:"vector",values:Object.freeze(e.slice())}),()=>new ln(e.slice()))}static create(e){if(!e.every(n=>typeof n=="number"))throw new TypeError("Vector values must be numbers.");return new ln(e.slice())}toArray(){return this._values.slice()}isEqual(e){const n=e instanceof ln?e._values:void 0;return n!==void 0&&this._values.length===n.length&&this._values.every((r,s)=>r===n[s])}toJSON(){return{type:"firestore/vectorValue/1.0",vectorValues:this.toArray()}}static fromJSON(e){const n=e;if(n.type!=="firestore/vectorValue/1.0"||!Array.isArray(n.vectorValues)||!n.vectorValues.every(r=>typeof r=="number"))throw new TypeError("Invalid VectorValue JSON value.");return ln.create(n.vectorValues)}}function jg(t=[]){return ln.create(t)}function dy(){return Rp.serverTimestamp()}const kt=Symbol("pyric/firestore/target");function Jn(t){return t.kind==="sandbox"?t.db:t.getDb()}const Xr=new WeakMap;function Pg(t,e){return Xr.set(t,e),t}const Qn=new WeakMap;function $g(t,e,n){return Xr.set(t,e),Qn.set(t,n),t}function qi(t,e){const n=_n(e);if(t.kind==="sandbox")return n;const r=Qn.get(n);if(!r)throw new TypeError("pyric/firestore: live ref missing rebuild closure — was it produced by a factory in this package?");return r(Jn(t))}function qg(t,e){const n=_n(e);if(t.kind==="sandbox")return n;const r=Qn.get(n);if(!r)throw new TypeError("pyric/firestore: live collection ref missing rebuild closure.");return r(Jn(t))}function hy(t,e){const n=_n(e);if(t.kind==="sandbox")return n;const r=Qn.get(n);if(!r)throw new TypeError("pyric/firestore: live query missing rebuild closure.");return r(Jn(t))}function zn(t,e,n){return e.kind==="sandbox-live"?$g(t,e,n):Pg(t,e)}function fy(t){const e=_n(t),n=Qn.get(e);return n||(()=>e)}function Sn(t){const e=Ug(t);return e.assertUsable?.(),e}function Ug(t){let e;if(kt in t?e=t[kt]:e=Xr.get(t),!e)throw new TypeError("pyric/firestore: unrecognized reference — was it produced by a factory in this package?");return e}const Tu=new WeakMap,Ru=new WeakMap;function Ui(t){return Tu.get(t)}function _n(t){return Ru.get(t)??t}function Nu(t,e,n){const r={id:t.id??"",path:t.path??""};return Tu.set(r,n),Ru.set(r,t),Xr.set(r,e),r}function Bg(t){return t instanceof en?Array.from(t.value):null}function li(t){if(t instanceof We)return qt.fromUint8Array(t.data);if(t instanceof ot)return new Dn(t.lat,t.lng);const e=Bg(t);if(e)return jg(e);if(Array.isArray(t))return t.map(li);if(t!==null&&typeof t=="object"){const n=Object.getPrototypeOf(t);if(n===Object.prototype||n===null){const r={};for(const[s,i]of Object.entries(t))r[s]=li(i);return r}}return t}function py(t){if(t!==void 0)return li(t)}class bn extends Error{code;customData;name="FirebaseError";constructor(e,n,r){super(n),this.code=e,this.customData=r,Object.setPrototypeOf(this,new.target.prototype)}}Object.defineProperty(bn,"name",{value:"FirebaseError"});let zr;function my(t){zr=t}function Lu(t){return zr?.resolve(t,!1)}function zg(){if(!zr)throw new TypeError("No default sandbox app registry is installed - import and initialize pyric/app before calling a service factory without an app.");return zr.defaultApp()}function Vg(t){if(t===void 0)return Vg(zg());const e=Lu(t);if(e)return e.service("firestore/default",()=>{const{sandbox:n,session:r}=e,s=vs();e.onDelete(s.terminate);const i=e.authScope;i&&s.own(r.onCurrentUserChanged(o=>{Xe(n).reevaluateLiveListeners(o,i)}));const a={kind:"sandbox-live",sandbox:n,getDb:xo(n,()=>r.currentUser),authScope:i,...s};return{[kt]:a,app:t}});if(Fu(t)){const r={kind:"sandbox",db:Ou(t),sandbox:t.sandbox,...vs()};return{[kt]:r}}if(Hg(t)){const n={kind:"sandbox-live",sandbox:t,getDb:xo(t),...vs()};return{[kt]:n}}throw new TypeError("pyric/firestore is a sandbox-only mirror. Package resolution must leave firebase/firestore unchanged for production; activate pyric dev or @pyric/cli/register before importing to select the sandbox.")}function vs(){let t=!1;const e=new Set;return{own(n){return t?(n(),()=>{}):(e.add(n),()=>e.delete(n))},assertUsable(){if(t)throw new bn("failed-precondition","The client has already been terminated.")},terminate(){if(!t){t=!0;for(const n of e)n();e.clear()}}}}function Wg(t){const e=Lu(t);if(e){e.assertAlive();const a=e.sandbox;return Wg(Li(a.withAuth(null),{source:{kind:"app"},authLens:{mode:"admin"}}))}const n=Fu(t)?t:t.withAuth(null),r=n.sandbox,i={kind:"sandbox",db:Rg(n),sandbox:r};return{[kt]:i}}function Fu(t){return t instanceof Zn}function Hg(t){if(t===null||typeof t!="object")return!1;const e=t;return typeof e.withAuth=="function"&&typeof e.onCurrentUserChanged=="function"&&"currentUser"in e&&"admin"in e}function xo(t,e=()=>t.currentUser){return()=>{const n=Li(t.withAuth(e()),{source:{kind:"app"},authLens:{mode:"app-session"}});return Ou(n)}}class Gg{started=!1;networkEnabled=!0;persistenceMode;pending=new Set;cachedPaths=new Set;cachedQueries=new WeakSet;syncObservers=new Set;syncScheduled=!1;markStarted(){this.started=!0}enablePersistence(e){if(this.started||this.persistenceMode!==void 0)throw new bn("failed-precondition","Firestore has already been started and persistence can no longer be enabled.");this.persistenceMode=e,this.started=!0}disableNetwork(){this.started=!0,this.networkEnabled=!1}async enableNetwork(){this.started=!0,this.networkEnabled=!0;for(const e of this.pending)e.localDone&&e.resolve(e.value);await Promise.all([...this.pending].map(e=>e.promise))}runWrite(e,n){if(this.started=!0,n&&this.cachedPaths.add(n),this.networkEnabled)return e();let r,s;const i=new Promise((o,c)=>{r=o,s=c}),a={path:n,promise:i,localDone:!1,resolve:r,reject:s};return this.pending.add(a),e().then(o=>{a.localDone=!0,a.value=o,this.networkEnabled&&a.resolve(o)},o=>a.reject(o)),i.then(()=>this.pending.delete(a),()=>this.pending.delete(a)),i}waitForPendingWrites(){this.started=!0;const e=[...this.pending].map(n=>n.promise);return Promise.all(e).then(()=>{})}cachePath(e){this.started=!0,this.cachedPaths.add(e)}assertPathCached(e){if(this.started=!0,!this.cachedPaths.has(e))throw new bn("unavailable","Failed to get document from cache. (However, this document may exist on the server.)")}cacheQuery(e){this.started=!0,this.cachedQueries.add(e)}hasCachedQuery(e){return this.started=!0,this.cachedQueries.has(e)||this.cachedPaths.size>0}snapshotMetadata(e){return Object.freeze({fromCache:!this.networkEnabled,hasPendingWrites:[...this.pending].some(n=>n.path===e)})}querySnapshotMetadata(){return Object.freeze({fromCache:!this.networkEnabled,hasPendingWrites:this.pending.size>0})}addSnapshotsInSyncObserver(e){return this.syncObservers.add(e),e(),()=>this.syncObservers.delete(e)}notifySnapshotDelivered(){this.syncScheduled||this.syncObservers.size===0||(this.syncScheduled=!0,queueMicrotask(()=>{this.syncScheduled=!1;for(const e of[...this.syncObservers])e()}))}}const Io=new WeakMap;function Vn(t){let e=Io.get(t);return e||(e=new Gg,Io.set(t,e)),e}function ws(t,e,n){return ut(t,Zt("reference",e)),Ei(t,e,n),t}function gy(t,...e){const n=Sn(t),r=kt in t,s=r?void 0:Ui(t),i=Jn(n);if(r){if(e.length===0)throw new TypeError("doc(db, path) requires at least one path segment.");const d=e.join("/"),l=i.doc(d),p=zn(l,n,y=>y.doc(d));return ws(p,d,n)}const a=_n(t),o=e.length===0?a.doc():a.doc(e.join("/")),c=o.path,u=zn(o,n,d=>d.doc(c));if(s){const d=Nu(u,n,s);return ws(d,c,n)}return ws(u,c,n)}function yy(t,...e){const n=Sn(t),r=kt in t;if(e.length===0)throw new TypeError("collection() requires at least one path segment.");if(r){const c=e.join("/"),u=Jn(n).collection(c);return zn(u,n,d=>d.collection(c))}const s=_n(t),i=e.join("/"),a=s.collection(i),o=a.path;return zn(a,n,c=>c.collection(o))}function Kg(t){return t instanceof Error&&"code"in t&&typeof t.code=="string"}function Zg(t){if(t instanceof bn||!Kg(t))return t;const e={};t.denialContext!==void 0&&(e.denialContext=t.denialContext),t.remediation!==void 0&&(e.remediation=t.remediation);const n=new bn(t.code,t.message,Object.keys(e).length===0?void 0:e);return t.denialContext!==void 0&&Object.assign(n,{denialContext:t.denialContext}),t.remediation!==void 0&&Object.assign(n,{remediation:t.remediation}),n}async function es(t){try{return await t()}catch(e){throw Zg(e)}}async function by(t,e,n){const r=Sn(t),s=Ui(t),i=s?s.toFirestore(e):e;return Vn(r).runWrite(()=>es(()=>qi(r,t).set(i,n)),t.path)}async function vy(t,e){const n=Sn(t);return Vn(n).runWrite(()=>es(()=>qi(n,t).update(e)),t.path)}async function wy(t){const e=Sn(t);return Vn(e).runWrite(()=>es(()=>qi(e,t).delete()),t.path)}async function Sy(t,e){const n=Sn(t),r=Ui(t),s=r?r.toFirestore(e):e,i=await Vn(n).runWrite(async()=>{const c=await es(()=>qg(n,t).add(s));return Vn(n).cachePath(c.path),c}),a=i.path,o=zn(i,n,c=>c.doc(a));if(ut(o,Zt("reference",a)),Ei(o,a,n,o),r){const c=Nu(o,n,r);return sp(o,c),c}return o}function _y(t,e){return Xe(t).deployRules(e)}function Ay(t,e){const n=Xe(t);return n.seed({rules:n.getRules(),documents:e})}function xy(t){return Xe(t).snapshot()}function Iy(t,e={}){const n=e.recentEventLimit??10,r=Xe(t),s=r.getRules(),i=s?Ds(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=r.snapshot(),u={};for(const w of Object.keys(c)){const R=w.split("/")[0]??"";R&&(u[R]=(u[R]??0)+1)}const d=t.history(),l=[];for(const w of d){const R=w.kind==="request",C=w.kind==="operation",I=w.kind==="listener";(R||C||I&&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(-n).map(w=>{let R="";if(w.path!==void 0)R=String(w.path);else{const N=w.target;N!==void 0&&N.path!==void 0&&(R=String(N.path))}let C="listen";w.method!==void 0&&(C=String(w.method));let I="error";if(w.result!==void 0)I=String(w.result);else{const N=w.error;N!==void 0&&N.code==="PERMISSION_DENIED"&&(I="deny")}let E=null;return w.auth!==void 0&&(E=w.auth),{path:R,method:C,result:I,auth:E}}),b=p.slice(-n).map(w=>{let R="";if(w.path!==void 0)R=String(w.path);else{const N=w.target;N!==void 0&&N.path!==void 0&&(R=String(N.path))}let C="listen";w.method!==void 0&&(C=String(w.method));let I=null;w.auth!==void 0&&(I=w.auth);let E;return typeof w.debugMessage=="string"&&(E=w.debugMessage),{path:R,method:C,auth:I,debugMessage:E}});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:d.length,recentDenials:b,recentRequests:y}}}export{Or as $,Vn as A,_n as B,Qn as C,bs as D,bn as E,tr as F,yy as G,Sy as H,vy as I,wy as J,ty as K,ey as L,my as M,Fi as N,hr as O,Ni as P,Ri as Q,ce as R,uy as S,Li as T,Zn as U,gt as V,pt as W,pn as X,$s as Y,me as Z,Wt as _,Ay as a,Ir as a0,Xe as a1,Wg as a2,co as a3,zg as a4,Lu as a5,ie as a6,Xg as a7,ei as a8,xt as a9,Dn as aa,qt as ab,Pg as ac,py as ad,Ru as ae,Ei as af,du as ag,qi as ah,hy as ai,dy as aj,by as b,xy as c,gy as d,oy as e,Bf as f,Vg as g,ny as h,Iy as i,ry as j,sy as k,iy as l,Uf as m,ay as n,ly as o,Ui as p,fy as q,Yg as r,_y as s,Sn as t,Zg as u,cy as v,Jn as w,zn as x,Nu as y,lu as z};
|