@pyric/cli 0.1.0-alpha.14 → 0.1.0-alpha.16

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.
Files changed (606) hide show
  1. package/dist/assurance/.generated/conformance-verdicts.d.ts +120 -75
  2. package/dist/assurance/.generated/conformance-verdicts.d.ts.map +1 -1
  3. package/dist/assurance/.generated/conformance-verdicts.js +120 -75
  4. package/dist/assurance/.generated/conformance-verdicts.js.map +1 -1
  5. package/dist/bridge/client/dispatch.js +1 -1
  6. package/dist/bridge/client/dispatch.js.map +1 -1
  7. package/dist/cli/serve.d.ts +1 -1
  8. package/dist/cli/serve.d.ts.map +1 -1
  9. package/dist/cli/serve.js +207 -284
  10. package/dist/cli/serve.js.map +1 -1
  11. package/dist/cli/service-command-records/database-rules-generate.d.ts +4 -0
  12. package/dist/cli/service-command-records/database-rules-generate.d.ts.map +1 -0
  13. package/dist/cli/service-command-records/database-rules-generate.js +3 -0
  14. package/dist/cli/service-command-records/database-rules-generate.js.map +1 -0
  15. package/dist/cli/service-command-records/database-rules-lint.d.ts +4 -0
  16. package/dist/cli/service-command-records/database-rules-lint.d.ts.map +1 -0
  17. package/dist/cli/service-command-records/database-rules-lint.js +3 -0
  18. package/dist/cli/service-command-records/database-rules-lint.js.map +1 -0
  19. package/dist/cli/service-command-records/database-rules-simulate.d.ts +4 -0
  20. package/dist/cli/service-command-records/database-rules-simulate.d.ts.map +1 -0
  21. package/dist/cli/service-command-records/database-rules-simulate.js +3 -0
  22. package/dist/cli/service-command-records/database-rules-simulate.js.map +1 -0
  23. package/dist/cli/service-command-records/database-rules-validate.d.ts +4 -0
  24. package/dist/cli/service-command-records/database-rules-validate.d.ts.map +1 -0
  25. package/dist/cli/service-command-records/database-rules-validate.js +3 -0
  26. package/dist/cli/service-command-records/database-rules-validate.js.map +1 -0
  27. package/dist/cli/service-command-records/firestore-indexes-generate.d.ts +4 -0
  28. package/dist/cli/service-command-records/firestore-indexes-generate.d.ts.map +1 -0
  29. package/dist/cli/service-command-records/firestore-indexes-generate.js +3 -0
  30. package/dist/cli/service-command-records/firestore-indexes-generate.js.map +1 -0
  31. package/dist/cli/service-command-records/firestore-rules-lint.d.ts +4 -0
  32. package/dist/cli/service-command-records/firestore-rules-lint.d.ts.map +1 -0
  33. package/dist/cli/service-command-records/firestore-rules-lint.js +3 -0
  34. package/dist/cli/service-command-records/firestore-rules-lint.js.map +1 -0
  35. package/dist/cli/service-command-records/firestore-rules-resolve.d.ts +4 -0
  36. package/dist/cli/service-command-records/firestore-rules-resolve.d.ts.map +1 -0
  37. package/dist/cli/service-command-records/firestore-rules-resolve.js +3 -0
  38. package/dist/cli/service-command-records/firestore-rules-resolve.js.map +1 -0
  39. package/dist/cli/service-command-records/firestore-rules-simulate.d.ts +4 -0
  40. package/dist/cli/service-command-records/firestore-rules-simulate.d.ts.map +1 -0
  41. package/dist/cli/service-command-records/firestore-rules-simulate.js +3 -0
  42. package/dist/cli/service-command-records/firestore-rules-simulate.js.map +1 -0
  43. package/dist/cli/service-command-records/firestore-rules-validate.d.ts +4 -0
  44. package/dist/cli/service-command-records/firestore-rules-validate.d.ts.map +1 -0
  45. package/dist/cli/service-command-records/firestore-rules-validate.js +3 -0
  46. package/dist/cli/service-command-records/firestore-rules-validate.js.map +1 -0
  47. package/dist/cli/service-command-records/storage-rules-lint.d.ts +4 -0
  48. package/dist/cli/service-command-records/storage-rules-lint.d.ts.map +1 -0
  49. package/dist/cli/service-command-records/storage-rules-lint.js +3 -0
  50. package/dist/cli/service-command-records/storage-rules-lint.js.map +1 -0
  51. package/dist/cli/service-command-records/storage-rules-simulate.d.ts +4 -0
  52. package/dist/cli/service-command-records/storage-rules-simulate.d.ts.map +1 -0
  53. package/dist/cli/service-command-records/storage-rules-simulate.js +3 -0
  54. package/dist/cli/service-command-records/storage-rules-simulate.js.map +1 -0
  55. package/dist/cli/service-commands.d.ts +7 -0
  56. package/dist/cli/service-commands.d.ts.map +1 -1
  57. package/dist/cli/service-commands.generated.d.ts +35 -0
  58. package/dist/cli/service-commands.generated.d.ts.map +1 -0
  59. package/dist/cli/service-commands.generated.js +25 -0
  60. package/dist/cli/service-commands.generated.js.map +1 -0
  61. package/dist/cli/service-commands.js +23 -40
  62. package/dist/cli/service-commands.js.map +1 -1
  63. package/dist/conformance/.generated/can-i-use-browser.d.ts.map +1 -1
  64. package/dist/conformance/.generated/can-i-use-browser.js +1 -1
  65. package/dist/conformance/.generated/can-i-use-browser.js.map +1 -1
  66. package/dist/conformance/.generated/can-i-use.d.ts.map +1 -1
  67. package/dist/conformance/.generated/can-i-use.js +1 -1
  68. package/dist/conformance/.generated/can-i-use.js.map +1 -1
  69. package/dist/conformance/.generated/conformance-docs.d.ts.map +1 -1
  70. package/dist/conformance/.generated/conformance-docs.js +1 -1
  71. package/dist/conformance/.generated/conformance-docs.js.map +1 -1
  72. package/dist/functions-rtdb/development-runtime.d.ts +63 -0
  73. package/dist/functions-rtdb/development-runtime.d.ts.map +1 -0
  74. package/dist/functions-rtdb/development-runtime.js +244 -0
  75. package/dist/functions-rtdb/development-runtime.js.map +1 -0
  76. package/dist/serve/bridge-mount.d.ts +32 -2
  77. package/dist/serve/bridge-mount.d.ts.map +1 -1
  78. package/dist/serve/bridge-mount.js +232 -18
  79. package/dist/serve/bridge-mount.js.map +1 -1
  80. package/dist/serve/bundler.d.ts +2 -18
  81. package/dist/serve/bundler.d.ts.map +1 -1
  82. package/dist/serve/bundler.js +7 -35
  83. package/dist/serve/bundler.js.map +1 -1
  84. package/dist/serve/entries/app-client.d.ts.map +1 -1
  85. package/dist/serve/entries/app-client.js +5 -5
  86. package/dist/serve/entries/app-client.js.map +1 -1
  87. package/dist/serve/entries/auth-helper-core.d.ts +32 -6
  88. package/dist/serve/entries/auth-helper-core.d.ts.map +1 -1
  89. package/dist/serve/entries/auth-helper-core.js +82 -24
  90. package/dist/serve/entries/auth-helper-core.js.map +1 -1
  91. package/dist/serve/entries/auth.d.ts.map +1 -1
  92. package/dist/serve/entries/auth.js +6 -4
  93. package/dist/serve/entries/auth.js.map +1 -1
  94. package/dist/serve/entries/database.d.ts +28 -0
  95. package/dist/serve/entries/database.d.ts.map +1 -1
  96. package/dist/serve/entries/database.js +95 -26
  97. package/dist/serve/entries/database.js.map +1 -1
  98. package/dist/serve/entries/init.d.ts.map +1 -1
  99. package/dist/serve/entries/init.js +21 -12
  100. package/dist/serve/entries/init.js.map +1 -1
  101. package/dist/serve/html-injection.d.ts +5 -0
  102. package/dist/serve/html-injection.d.ts.map +1 -0
  103. package/dist/serve/html-injection.js +59 -0
  104. package/dist/serve/html-injection.js.map +1 -0
  105. package/dist/serve/namespace.d.ts +6 -22
  106. package/dist/serve/namespace.d.ts.map +1 -1
  107. package/dist/serve/namespace.js +23 -145
  108. package/dist/serve/namespace.js.map +1 -1
  109. package/dist/serve/runtime/worker-replacement.d.ts +1 -2
  110. package/dist/serve/runtime/worker-replacement.d.ts.map +1 -1
  111. package/dist/serve/sandbox-session.d.ts +78 -0
  112. package/dist/serve/sandbox-session.d.ts.map +1 -0
  113. package/dist/serve/sandbox-session.js +171 -0
  114. package/dist/serve/sandbox-session.js.map +1 -0
  115. package/dist/serve/server.d.ts +5 -2
  116. package/dist/serve/server.d.ts.map +1 -1
  117. package/dist/serve/server.js +21 -5
  118. package/dist/serve/server.js.map +1 -1
  119. package/dist/serve/site-tree.d.ts +8 -0
  120. package/dist/serve/site-tree.d.ts.map +1 -0
  121. package/dist/serve/site-tree.js +113 -0
  122. package/dist/serve/site-tree.js.map +1 -0
  123. package/dist/serve/site-ui/_astro/RulesCodeEditor.CzwHdCi9.js +23 -0
  124. package/dist/serve/site-ui/_astro/_example_.jevZ7OdV.css +1 -0
  125. package/dist/serve/site-ui/_astro/_slug_.BoKXYrnu.css +1 -0
  126. package/dist/serve/site-ui/_astro/_studio_.BtYpqe1A.css +1 -0
  127. package/dist/serve/site-ui/_astro/app.4HeLP_FA.js +109 -0
  128. package/dist/serve/site-ui/_astro/app.BgSnCR5G.js +1 -0
  129. package/dist/serve/site-ui/_astro/app.BsFsMjn0.css +1 -0
  130. package/dist/serve/site-ui/_astro/chess-showcase.CnoxIle5.js +1 -0
  131. package/dist/serve/site-ui/_astro/chess-source-explorer.C5k9c5yK.js +1 -0
  132. package/dist/serve/site-ui/_astro/chess-v2.CFHmd3UL.js +354 -0
  133. package/dist/serve/site-ui/_astro/client.D2ORs4B-.js +25 -0
  134. package/dist/serve/site-ui/_astro/example-runtime.R1d96L6-.js +291 -0
  135. package/dist/serve/site-ui/_astro/index.BJiOemMX.js +1 -0
  136. package/dist/serve/site-ui/_astro/index.DBy5LfQW.js +9 -0
  137. package/dist/serve/site-ui/_astro/index.DNyk7q8W.js +9 -0
  138. package/dist/serve/site-ui/_astro/jsx-runtime.D_zvdyIk.js +9 -0
  139. package/dist/serve/site-ui/_astro/reads.BrKNdKAa.js +1 -0
  140. package/dist/serve/site-ui/_astro/sandbox-controls.BTb3EbQp.js +1153 -0
  141. package/dist/serve/site-ui/_astro/seed.EyI3VYEu.js +20 -0
  142. package/dist/serve/site-ui/auth/index.html +11 -0
  143. package/dist/serve/site-ui/docs/_rhythm/index.html +100 -0
  144. package/dist/serve/site-ui/docs/agent/set-up-your-agent/index.html +43 -0
  145. package/dist/serve/site-ui/docs/agent/watch-and-review/index.html +26 -0
  146. package/dist/serve/site-ui/docs/agent/work-with-an-agent/index.html +70 -0
  147. package/dist/serve/{docs-ui → site-ui}/docs/ai-compat/index.html +3 -3
  148. package/dist/serve/site-ui/docs/api-reference/index.html +68 -0
  149. package/dist/serve/{docs-ui → site-ui}/docs/app-compat/index.html +3 -3
  150. package/dist/serve/{docs-ui → site-ui}/docs/auth-compat/index.html +3 -3
  151. package/dist/serve/site-ui/docs/build/ai-logic/index.html +64 -0
  152. package/dist/serve/site-ui/docs/build/authentication/index.html +66 -0
  153. package/dist/serve/site-ui/docs/build/cloud-firestore/index.html +84 -0
  154. package/dist/serve/site-ui/docs/build/cloud-messaging/index.html +71 -0
  155. package/dist/serve/site-ui/docs/build/cloud-storage/index.html +66 -0
  156. package/dist/serve/{docs-ui → site-ui}/docs/build/cloud-storage.md +2 -2
  157. package/dist/serve/site-ui/docs/build/realtime-database/index.html +67 -0
  158. package/dist/serve/site-ui/docs/conformance-scores/index.html +50 -0
  159. package/dist/serve/{docs-ui → site-ui}/docs/conformance-scores.md +3 -3
  160. package/dist/serve/site-ui/docs/create-pyric-reference-api/index.html +531 -0
  161. package/dist/serve/{docs-ui → site-ui}/docs/database-compat/index.html +211 -168
  162. package/dist/serve/{docs-ui → site-ui}/docs/database-compat.md +208 -170
  163. package/dist/serve/site-ui/docs/examples/chess/index.html +384 -0
  164. package/dist/serve/site-ui/docs/examples/chess.md +57 -0
  165. package/dist/serve/site-ui/docs/examples/index.html +3 -0
  166. package/dist/serve/site-ui/docs/examples.md +4 -0
  167. package/dist/serve/{docs-ui → site-ui}/docs/firestore-compat/index.html +55 -91
  168. package/dist/serve/{docs-ui → site-ui}/docs/firestore-compat.md +52 -88
  169. package/dist/serve/site-ui/docs/functions-rtdb-compat/index.html +73 -0
  170. package/dist/serve/site-ui/docs/get-started/how-the-swap-works/index.html +29 -0
  171. package/dist/serve/site-ui/docs/get-started/start-building/index.html +33 -0
  172. package/dist/serve/{docs-ui → site-ui}/docs/index.json +595 -26
  173. package/dist/serve/site-ui/docs/messaging-compat/index.html +324 -0
  174. package/dist/serve/{docs-ui → site-ui}/docs/messaging-compat.md +71 -1
  175. package/dist/serve/site-ui/docs/observe/resolve-runtime-status/index.html +28 -0
  176. package/dist/serve/site-ui/docs/observe/see-whats-happening/index.html +74 -0
  177. package/dist/serve/site-ui/docs/observe/shape-your-data/index.html +45 -0
  178. package/dist/serve/site-ui/docs/overview/index.html +17 -0
  179. package/dist/serve/site-ui/docs/pyric-admin-app-reference-api/index.html +186 -0
  180. package/dist/serve/{docs-ui → site-ui}/docs/pyric-admin-auth-reference-api/index.html +4 -4
  181. package/dist/serve/{docs-ui → site-ui}/docs/pyric-admin-database-reference-api/index.html +4 -4
  182. package/dist/serve/{docs-ui → site-ui}/docs/pyric-admin-firestore-reference-api/index.html +318 -202
  183. package/dist/serve/{docs-ui → site-ui}/docs/pyric-admin-firestore-reference-api.md +154 -27
  184. package/dist/serve/{docs-ui → site-ui}/docs/pyric-admin-messaging-reference-api/index.html +5 -5
  185. package/dist/serve/site-ui/docs/pyric-admin-storage-reference-api/index.html +318 -0
  186. package/dist/serve/{docs-ui → site-ui}/docs/pyric-ai-reference-api/index.html +5 -5
  187. package/dist/serve/site-ui/docs/pyric-ai-scripting-reference-api/index.html +160 -0
  188. package/dist/serve/site-ui/docs/pyric-app-reference-api/index.html +425 -0
  189. package/dist/serve/{docs-ui → site-ui}/docs/pyric-auth-reference-api/index.html +6 -6
  190. package/dist/serve/{docs-ui → site-ui}/docs/pyric-auth-reference-api.md +1 -1
  191. package/dist/serve/site-ui/docs/pyric-cli-assurance-browser-reference-api/index.html +60 -0
  192. package/dist/serve/{docs-ui → site-ui}/docs/pyric-cli-assurance-reference-api/index.html +4 -4
  193. package/dist/serve/{docs-ui → site-ui}/docs/pyric-cli-bridge-client-reference-api/index.html +4 -4
  194. package/dist/serve/site-ui/docs/pyric-cli-bridge-reference-api/index.html +507 -0
  195. package/dist/serve/site-ui/docs/pyric-cli-conformance-browser-reference-api/index.html +258 -0
  196. package/dist/serve/site-ui/docs/pyric-cli-conformance-docs-reference-api/index.html +51 -0
  197. package/dist/serve/site-ui/docs/pyric-cli-conformance-reference-api/index.html +308 -0
  198. package/dist/serve/site-ui/docs/pyric-cli-credentials-node-reference-api/index.html +68 -0
  199. package/dist/serve/{docs-ui → site-ui}/docs/pyric-cli-discover-reference-api/index.html +4 -4
  200. package/dist/serve/site-ui/docs/pyric-cli-register-reference-api/index.html +11 -0
  201. package/dist/serve/{docs-ui → site-ui}/docs/pyric-cli-remote-reference-api/index.html +4 -4
  202. package/dist/serve/{docs-ui → site-ui}/docs/pyric-cli-serve-worker-reference-api/index.html +1186 -1384
  203. package/dist/serve/{docs-ui → site-ui}/docs/pyric-cli-serve-worker-reference-api.md +817 -1291
  204. package/dist/serve/{docs-ui → site-ui}/docs/pyric-cli-verify-reference-api/index.html +4 -4
  205. package/dist/serve/site-ui/docs/pyric-cli-vite-reference-api/index.html +126 -0
  206. package/dist/serve/{docs-ui → site-ui}/docs/pyric-cli-vite-reference-api.md +1 -1
  207. package/dist/serve/site-ui/docs/pyric-database-reference-api/index.html +2641 -0
  208. package/dist/serve/{docs-ui → site-ui}/docs/pyric-database-reference-api.md +1055 -158
  209. package/dist/serve/{docs-ui → site-ui}/docs/pyric-firestore-reference-api/index.html +311 -249
  210. package/dist/serve/{docs-ui → site-ui}/docs/pyric-firestore-reference-api.md +72 -54
  211. package/dist/serve/site-ui/docs/pyric-messaging-reference-api/index.html +509 -0
  212. package/dist/serve/site-ui/docs/pyric-messaging-sw-reference-api/index.html +182 -0
  213. package/dist/serve/{docs-ui → site-ui}/docs/pyric-rules-reference-api/index.html +7 -26
  214. package/dist/serve/{docs-ui → site-ui}/docs/pyric-rules-reference-api.md +13 -23
  215. package/dist/serve/site-ui/docs/pyric-sandbox-database-reference-api/index.html +121 -0
  216. package/dist/serve/site-ui/docs/pyric-sandbox-firestore-reference-api/index.html +203 -0
  217. package/dist/serve/{docs-ui → site-ui}/docs/pyric-sandbox-reference-api/index.html +26 -5
  218. package/dist/serve/{docs-ui → site-ui}/docs/pyric-sandbox-reference-api.md +22 -22
  219. package/dist/serve/{docs-ui → site-ui}/docs/pyric-storage-reference-api/index.html +5 -15
  220. package/dist/serve/{docs-ui → site-ui}/docs/pyric-storage-reference-api.md +0 -13
  221. package/dist/serve/site-ui/docs/pyric-ui-agents-reference-api/index.html +639 -0
  222. package/dist/serve/site-ui/docs/pyric-ui-auth-hooks-reference-api/index.html +100 -0
  223. package/dist/serve/{docs-ui → site-ui}/docs/pyric-ui-auth-reference-api/index.html +4 -4
  224. package/dist/serve/site-ui/docs/pyric-ui-events-hooks-reference-api/index.html +24 -0
  225. package/dist/serve/{docs-ui → site-ui}/docs/pyric-ui-events-reference-api/index.html +4 -4
  226. package/dist/serve/site-ui/docs/pyric-ui-firestore-hooks-reference-api/index.html +136 -0
  227. package/dist/serve/{docs-ui → site-ui}/docs/pyric-ui-firestore-reference-api/index.html +7 -7
  228. package/dist/serve/{docs-ui → site-ui}/docs/pyric-ui-firestore-reference-api.md +4 -4
  229. package/dist/serve/{docs-ui → site-ui}/docs/pyric-ui-primitives-reference-api/index.html +4 -4
  230. package/dist/serve/{docs-ui → site-ui}/docs/pyric-ui-rtdb-reference-api/index.html +4 -4
  231. package/dist/serve/site-ui/docs/pyric-ui-rules-hooks-reference-api/index.html +16 -0
  232. package/dist/serve/{docs-ui → site-ui}/docs/pyric-ui-rules-reference-api/index.html +4 -4
  233. package/dist/serve/site-ui/docs/pyric-ui-storage-hooks-reference-api/index.html +176 -0
  234. package/dist/serve/{docs-ui → site-ui}/docs/pyric-ui-storage-reference-api/index.html +10 -11
  235. package/dist/serve/{docs-ui → site-ui}/docs/pyric-ui-storage-reference-api.md +7 -8
  236. package/dist/serve/site-ui/docs/pyric-ui-traffic-hooks-reference-api/index.html +188 -0
  237. package/dist/serve/{docs-ui → site-ui}/docs/pyric-ui-traffic-reference-api/index.html +4 -4
  238. package/dist/serve/{docs-ui → site-ui}/docs/rules-compat/index.html +87 -57
  239. package/dist/serve/{docs-ui → site-ui}/docs/rules-compat.md +84 -54
  240. package/dist/serve/site-ui/docs/secure/audit-your-rules/index.html +51 -0
  241. package/dist/serve/site-ui/docs/secure/firestore-rules-limits/index.html +106 -0
  242. package/dist/serve/site-ui/docs/secure/read-a-denial/index.html +41 -0
  243. package/dist/serve/site-ui/docs/secure/rtdb-rules-in-typescript/index.html +67 -0
  244. package/dist/serve/site-ui/docs/secure/rules-standard-library/index.html +159 -0
  245. package/dist/serve/{docs-ui → site-ui}/docs/secure/rules-standard-library.md +2 -2
  246. package/dist/serve/site-ui/docs/secure/secure-it-with-rules/index.html +47 -0
  247. package/dist/serve/site-ui/docs/secure/simulate-and-lint/index.html +95 -0
  248. package/dist/serve/site-ui/docs/secure/write-a-rules-test-suite/index.html +82 -0
  249. package/dist/serve/site-ui/docs/ship/ship-to-production/index.html +37 -0
  250. package/dist/serve/site-ui/docs/ship/test-in-node/index.html +75 -0
  251. package/dist/serve/{docs-ui → site-ui}/docs/storage-compat/index.html +8 -8
  252. package/dist/serve/{docs-ui → site-ui}/docs/storage-compat.md +5 -5
  253. package/dist/serve/site-ui/docs/trust/how-we-know-it-matches-firebase/index.html +132 -0
  254. package/dist/serve/site-ui/docs/trust/rules-standard-library/index.html +861 -0
  255. package/dist/serve/site-ui/docs/trust/rules-standard-library.md +344 -0
  256. package/dist/serve/site-ui/docs/trust/storage-rules-stdlib-research/index.html +582 -0
  257. package/dist/serve/site-ui/docs/trust/storage-rules-stdlib-research.md +448 -0
  258. package/dist/serve/site-ui/docs/trust/versioning-and-compatibility/index.html +14 -0
  259. package/dist/serve/{docs-ui → site-ui}/docs/tutorial/index.html +4 -4
  260. package/dist/serve/{docs-ui → site-ui}/docs/tutorial.md +1 -1
  261. package/dist/serve/site-ui/examples/chess/index.html +2 -0
  262. package/dist/serve/site-ui/examples/firestore-first-write/index.html +2 -0
  263. package/dist/serve/site-ui/firestore/index.html +11 -0
  264. package/dist/serve/site-ui/index.html +11 -0
  265. package/dist/serve/{docs-ui → site-ui}/llms.txt +6 -2
  266. package/dist/serve/site-ui/rtdb/index.html +11 -0
  267. package/dist/serve/site-ui/settings/index.html +11 -0
  268. package/dist/serve/site-ui/storage/index.html +11 -0
  269. package/dist/serve/site-ui/studio-routes.json +1 -0
  270. package/dist/serve/site-ui/traffic/index.html +11 -0
  271. package/dist/serve/standalone-assets.d.ts +4 -10
  272. package/dist/serve/standalone-assets.d.ts.map +1 -1
  273. package/dist/serve/standalone-assets.js +8 -21
  274. package/dist/serve/standalone-assets.js.map +1 -1
  275. package/dist/serve/vite-functions-development.d.ts +29 -0
  276. package/dist/serve/vite-functions-development.d.ts.map +1 -0
  277. package/dist/serve/vite-functions-development.js +150 -0
  278. package/dist/serve/vite-functions-development.js.map +1 -0
  279. package/dist/serve/vite-generation-bridge.d.ts +17 -0
  280. package/dist/serve/vite-generation-bridge.d.ts.map +1 -0
  281. package/dist/serve/vite-generation-bridge.js +47 -0
  282. package/dist/serve/vite-generation-bridge.js.map +1 -0
  283. package/dist/serve/vite-generation-functions.d.ts +35 -0
  284. package/dist/serve/vite-generation-functions.d.ts.map +1 -0
  285. package/dist/serve/vite-generation-functions.js +46 -0
  286. package/dist/serve/vite-generation-functions.js.map +1 -0
  287. package/dist/serve/vite-generation-middleware.d.ts +10 -0
  288. package/dist/serve/vite-generation-middleware.d.ts.map +1 -0
  289. package/dist/serve/vite-generation-middleware.js +40 -0
  290. package/dist/serve/vite-generation-middleware.js.map +1 -0
  291. package/dist/serve/vite-generation-rules-watch.d.ts +8 -0
  292. package/dist/serve/vite-generation-rules-watch.d.ts.map +1 -0
  293. package/dist/serve/vite-generation-rules-watch.js +33 -0
  294. package/dist/serve/vite-generation-rules-watch.js.map +1 -0
  295. package/dist/serve/vite-module-swap.d.ts +16 -0
  296. package/dist/serve/vite-module-swap.d.ts.map +1 -0
  297. package/dist/serve/vite-module-swap.js +96 -0
  298. package/dist/serve/vite-module-swap.js.map +1 -0
  299. package/dist/serve/vite-page-runtime.d.ts +29 -0
  300. package/dist/serve/vite-page-runtime.d.ts.map +1 -0
  301. package/dist/serve/vite-page-runtime.js +71 -0
  302. package/dist/serve/vite-page-runtime.js.map +1 -0
  303. package/dist/serve/vite-plugin.d.ts +44 -4
  304. package/dist/serve/vite-plugin.d.ts.map +1 -1
  305. package/dist/serve/vite-plugin.js +62 -864
  306. package/dist/serve/vite-plugin.js.map +1 -1
  307. package/dist/serve/vite-sandbox-generation.d.ts +57 -0
  308. package/dist/serve/vite-sandbox-generation.d.ts.map +1 -0
  309. package/dist/serve/vite-sandbox-generation.js +178 -0
  310. package/dist/serve/vite-sandbox-generation.js.map +1 -0
  311. package/dist/serve/worker/client/disconnect.d.ts.map +1 -1
  312. package/dist/serve/worker/client/disconnect.js +2 -0
  313. package/dist/serve/worker/client/disconnect.js.map +1 -1
  314. package/dist/serve/worker/client/handles.d.ts +5 -0
  315. package/dist/serve/worker/client/handles.d.ts.map +1 -1
  316. package/dist/serve/worker/client/handles.js.map +1 -1
  317. package/dist/serve/worker/client/pagehide.d.ts +13 -0
  318. package/dist/serve/worker/client/pagehide.d.ts.map +1 -0
  319. package/dist/serve/worker/client/pagehide.js +19 -0
  320. package/dist/serve/worker/client/pagehide.js.map +1 -0
  321. package/dist/serve/worker/client/rtdb-admin.d.ts +8 -0
  322. package/dist/serve/worker/client/rtdb-admin.d.ts.map +1 -0
  323. package/dist/serve/worker/client/rtdb-admin.js +39 -0
  324. package/dist/serve/worker/client/rtdb-admin.js.map +1 -0
  325. package/dist/serve/worker/client/rtdb-connection-lifecycle.d.ts +15 -0
  326. package/dist/serve/worker/client/rtdb-connection-lifecycle.d.ts.map +1 -0
  327. package/dist/serve/worker/client/rtdb-connection-lifecycle.js +45 -0
  328. package/dist/serve/worker/client/rtdb-connection-lifecycle.js.map +1 -0
  329. package/dist/serve/worker/client/rtdb-controls.d.ts +6 -0
  330. package/dist/serve/worker/client/rtdb-controls.d.ts.map +1 -0
  331. package/dist/serve/worker/client/rtdb-controls.js +8 -0
  332. package/dist/serve/worker/client/rtdb-controls.js.map +1 -0
  333. package/dist/serve/worker/client/rtdb-listeners.d.ts +24 -0
  334. package/dist/serve/worker/client/rtdb-listeners.d.ts.map +1 -0
  335. package/dist/serve/worker/client/rtdb-listeners.js +262 -0
  336. package/dist/serve/worker/client/rtdb-listeners.js.map +1 -0
  337. package/dist/serve/worker/client/rtdb-reads.d.ts +4 -0
  338. package/dist/serve/worker/client/rtdb-reads.d.ts.map +1 -0
  339. package/dist/serve/worker/client/rtdb-reads.js +11 -0
  340. package/dist/serve/worker/client/rtdb-reads.js.map +1 -0
  341. package/dist/serve/worker/client/rtdb-references.d.ts +19 -0
  342. package/dist/serve/worker/client/rtdb-references.d.ts.map +1 -0
  343. package/dist/serve/worker/client/rtdb-references.js +63 -0
  344. package/dist/serve/worker/client/rtdb-references.js.map +1 -0
  345. package/dist/serve/worker/client/rtdb-snapshots.d.ts +20 -0
  346. package/dist/serve/worker/client/rtdb-snapshots.d.ts.map +1 -0
  347. package/dist/serve/worker/client/rtdb-snapshots.js +64 -0
  348. package/dist/serve/worker/client/rtdb-snapshots.js.map +1 -0
  349. package/dist/serve/worker/client/rtdb-transactions.d.ts +14 -0
  350. package/dist/serve/worker/client/rtdb-transactions.d.ts.map +1 -0
  351. package/dist/serve/worker/client/rtdb-transactions.js +34 -0
  352. package/dist/serve/worker/client/rtdb-transactions.js.map +1 -0
  353. package/dist/serve/worker/client/rtdb-writes.d.ts +8 -0
  354. package/dist/serve/worker/client/rtdb-writes.d.ts.map +1 -0
  355. package/dist/serve/worker/client/rtdb-writes.js +65 -0
  356. package/dist/serve/worker/client/rtdb-writes.js.map +1 -0
  357. package/dist/serve/worker/client.d.ts +0 -2
  358. package/dist/serve/worker/client.d.ts.map +1 -1
  359. package/dist/serve/worker/client.js +0 -2
  360. package/dist/serve/worker/client.js.map +1 -1
  361. package/dist/serve/worker/entry.js +2 -2
  362. package/dist/serve/worker/entry.js.map +1 -1
  363. package/dist/serve/worker/host/dispatch.d.ts +2 -0
  364. package/dist/serve/worker/host/dispatch.d.ts.map +1 -1
  365. package/dist/serve/worker/host/dispatch.js +24 -2
  366. package/dist/serve/worker/host/dispatch.js.map +1 -1
  367. package/dist/serve/worker/host/rtdb.d.ts +6 -2
  368. package/dist/serve/worker/host/rtdb.d.ts.map +1 -1
  369. package/dist/serve/worker/host/rtdb.js +224 -2
  370. package/dist/serve/worker/host/rtdb.js.map +1 -1
  371. package/dist/serve/worker/host/studio.d.ts.map +1 -1
  372. package/dist/serve/worker/host/studio.js +2 -0
  373. package/dist/serve/worker/host/studio.js.map +1 -1
  374. package/dist/serve/worker/host/subscriptions.d.ts.map +1 -1
  375. package/dist/serve/worker/host/subscriptions.js +3 -3
  376. package/dist/serve/worker/host/subscriptions.js.map +1 -1
  377. package/dist/serve/worker/host.d.ts +1 -1
  378. package/dist/serve/worker/host.d.ts.map +1 -1
  379. package/dist/serve/worker/host.js +1 -1
  380. package/dist/serve/worker/host.js.map +1 -1
  381. package/dist/serve/worker/index.d.ts +16 -1
  382. package/dist/serve/worker/index.d.ts.map +1 -1
  383. package/dist/serve/worker/index.js +17 -4
  384. package/dist/serve/worker/index.js.map +1 -1
  385. package/dist/serve/worker/protocol.d.ts +57 -0
  386. package/dist/serve/worker/protocol.d.ts.map +1 -1
  387. package/dist/serve/worker/protocol.js.map +1 -1
  388. package/dist/serve/worker/rtdb-value-equality.d.ts +3 -0
  389. package/dist/serve/worker/rtdb-value-equality.d.ts.map +1 -0
  390. package/dist/serve/worker/rtdb-value-equality.js +18 -0
  391. package/dist/serve/worker/rtdb-value-equality.js.map +1 -0
  392. package/dist/serve/worker/serve-init.js +2 -2
  393. package/dist/serve/worker/serve-init.js.map +1 -1
  394. package/dist/serve/worker/service-worker-relay.js +2 -2
  395. package/dist/serve/worker/service-worker-relay.js.map +1 -1
  396. package/package.json +7 -5
  397. package/src/assurance/.generated/conformance-verdicts.ts +120 -75
  398. package/src/bridge/client/dispatch.ts +1 -1
  399. package/src/cli/serve.ts +215 -307
  400. package/src/cli/service-command-records/database-rules-generate.ts +3 -0
  401. package/src/cli/service-command-records/database-rules-lint.ts +3 -0
  402. package/src/cli/service-command-records/database-rules-simulate.ts +3 -0
  403. package/src/cli/service-command-records/database-rules-validate.ts +3 -0
  404. package/src/cli/service-command-records/firestore-indexes-generate.ts +3 -0
  405. package/src/cli/service-command-records/firestore-rules-lint.ts +3 -0
  406. package/src/cli/service-command-records/firestore-rules-resolve.ts +3 -0
  407. package/src/cli/service-command-records/firestore-rules-simulate.ts +3 -0
  408. package/src/cli/service-command-records/firestore-rules-validate.ts +3 -0
  409. package/src/cli/service-command-records/storage-rules-lint.ts +3 -0
  410. package/src/cli/service-command-records/storage-rules-simulate.ts +3 -0
  411. package/src/cli/service-commands.generated.ts +27 -0
  412. package/src/cli/service-commands.test.ts +43 -0
  413. package/src/cli/service-commands.ts +36 -51
  414. package/src/conformance/.generated/can-i-use-browser.ts +1 -1
  415. package/src/conformance/.generated/can-i-use.ts +1 -1
  416. package/src/conformance/.generated/conformance-docs.ts +1 -1
  417. package/src/functions-rtdb/development-runtime.ts +299 -0
  418. package/src/serve/bridge-mount.ts +253 -19
  419. package/src/serve/bundler.ts +8 -34
  420. package/src/serve/entries/app-client.ts +5 -4
  421. package/src/serve/entries/auth-helper-core.ts +117 -30
  422. package/src/serve/entries/auth.ts +8 -4
  423. package/src/serve/entries/database.ts +180 -57
  424. package/src/serve/entries/init.ts +30 -20
  425. package/src/serve/html-injection.ts +65 -0
  426. package/src/serve/namespace.ts +26 -169
  427. package/src/serve/runtime/worker-replacement.ts +1 -1
  428. package/src/serve/sandbox-session.ts +233 -0
  429. package/src/serve/server.ts +20 -5
  430. package/src/serve/site-tree.ts +146 -0
  431. package/src/serve/standalone-assets.ts +9 -26
  432. package/src/serve/vite-functions-development.ts +201 -0
  433. package/src/serve/vite-generation-bridge.ts +66 -0
  434. package/src/serve/vite-generation-functions.ts +78 -0
  435. package/src/serve/vite-generation-middleware.ts +56 -0
  436. package/src/serve/vite-generation-rules-watch.ts +37 -0
  437. package/src/serve/vite-module-swap.ts +119 -0
  438. package/src/serve/vite-page-runtime.ts +100 -0
  439. package/src/serve/vite-plugin.ts +78 -883
  440. package/src/serve/vite-sandbox-generation.ts +255 -0
  441. package/src/serve/worker/client/disconnect.ts +3 -1
  442. package/src/serve/worker/client/handles.ts +5 -0
  443. package/src/serve/worker/client/pagehide.ts +31 -0
  444. package/src/serve/worker/client/rtdb-admin.ts +74 -0
  445. package/src/serve/worker/client/rtdb-connection-lifecycle.ts +52 -0
  446. package/src/serve/worker/client/rtdb-controls.ts +8 -0
  447. package/src/serve/worker/client/rtdb-listeners.ts +337 -0
  448. package/src/serve/worker/client/rtdb-reads.ts +12 -0
  449. package/src/serve/worker/client/rtdb-references.ts +85 -0
  450. package/src/serve/worker/client/rtdb-snapshots.ts +118 -0
  451. package/src/serve/worker/client/rtdb-transactions.ts +51 -0
  452. package/src/serve/worker/client/rtdb-writes.ts +74 -0
  453. package/src/serve/worker/client.ts +0 -2
  454. package/src/serve/worker/entry.ts +2 -2
  455. package/src/serve/worker/host/dispatch.ts +22 -2
  456. package/src/serve/worker/host/rtdb.ts +243 -2
  457. package/src/serve/worker/host/studio.ts +2 -0
  458. package/src/serve/worker/host/subscriptions.ts +8 -4
  459. package/src/serve/worker/host.ts +1 -1
  460. package/src/serve/worker/index.ts +58 -10
  461. package/src/serve/worker/protocol.ts +23 -2
  462. package/src/serve/worker/rtdb-value-equality.ts +17 -0
  463. package/src/serve/worker/serve-init.ts +2 -2
  464. package/src/serve/worker/service-worker-relay.ts +2 -2
  465. package/dist/serve/docs-ui/_astro/_slug_.DUci-duz.css +0 -1
  466. package/dist/serve/docs-ui/docs/_rhythm/index.html +0 -100
  467. package/dist/serve/docs-ui/docs/agent/set-up-your-agent/index.html +0 -43
  468. package/dist/serve/docs-ui/docs/agent/watch-and-review/index.html +0 -26
  469. package/dist/serve/docs-ui/docs/agent/work-with-an-agent/index.html +0 -70
  470. package/dist/serve/docs-ui/docs/api-reference/index.html +0 -68
  471. package/dist/serve/docs-ui/docs/build/ai-logic/index.html +0 -64
  472. package/dist/serve/docs-ui/docs/build/authentication/index.html +0 -66
  473. package/dist/serve/docs-ui/docs/build/cloud-firestore/index.html +0 -70
  474. package/dist/serve/docs-ui/docs/build/cloud-messaging/index.html +0 -71
  475. package/dist/serve/docs-ui/docs/build/cloud-storage/index.html +0 -66
  476. package/dist/serve/docs-ui/docs/build/realtime-database/index.html +0 -67
  477. package/dist/serve/docs-ui/docs/conformance-scores/index.html +0 -50
  478. package/dist/serve/docs-ui/docs/create-pyric-reference-api/index.html +0 -531
  479. package/dist/serve/docs-ui/docs/functions-rtdb-compat/index.html +0 -73
  480. package/dist/serve/docs-ui/docs/get-started/how-the-swap-works/index.html +0 -29
  481. package/dist/serve/docs-ui/docs/get-started/start-building/index.html +0 -33
  482. package/dist/serve/docs-ui/docs/messaging-compat/index.html +0 -265
  483. package/dist/serve/docs-ui/docs/observe/resolve-runtime-status/index.html +0 -28
  484. package/dist/serve/docs-ui/docs/observe/see-whats-happening/index.html +0 -74
  485. package/dist/serve/docs-ui/docs/observe/shape-your-data/index.html +0 -45
  486. package/dist/serve/docs-ui/docs/overview/index.html +0 -17
  487. package/dist/serve/docs-ui/docs/pyric-admin-app-reference-api/index.html +0 -186
  488. package/dist/serve/docs-ui/docs/pyric-admin-storage-reference-api/index.html +0 -318
  489. package/dist/serve/docs-ui/docs/pyric-ai-scripting-reference-api/index.html +0 -160
  490. package/dist/serve/docs-ui/docs/pyric-app-reference-api/index.html +0 -425
  491. package/dist/serve/docs-ui/docs/pyric-cli-assurance-browser-reference-api/index.html +0 -60
  492. package/dist/serve/docs-ui/docs/pyric-cli-bridge-reference-api/index.html +0 -507
  493. package/dist/serve/docs-ui/docs/pyric-cli-conformance-browser-reference-api/index.html +0 -258
  494. package/dist/serve/docs-ui/docs/pyric-cli-conformance-docs-reference-api/index.html +0 -51
  495. package/dist/serve/docs-ui/docs/pyric-cli-conformance-reference-api/index.html +0 -308
  496. package/dist/serve/docs-ui/docs/pyric-cli-credentials-node-reference-api/index.html +0 -68
  497. package/dist/serve/docs-ui/docs/pyric-cli-register-reference-api/index.html +0 -11
  498. package/dist/serve/docs-ui/docs/pyric-cli-vite-reference-api/index.html +0 -126
  499. package/dist/serve/docs-ui/docs/pyric-database-reference-api/index.html +0 -1852
  500. package/dist/serve/docs-ui/docs/pyric-messaging-reference-api/index.html +0 -509
  501. package/dist/serve/docs-ui/docs/pyric-messaging-sw-reference-api/index.html +0 -182
  502. package/dist/serve/docs-ui/docs/pyric-sandbox-database-reference-api/index.html +0 -121
  503. package/dist/serve/docs-ui/docs/pyric-sandbox-firestore-reference-api/index.html +0 -203
  504. package/dist/serve/docs-ui/docs/pyric-ui-agents-reference-api/index.html +0 -639
  505. package/dist/serve/docs-ui/docs/pyric-ui-auth-hooks-reference-api/index.html +0 -100
  506. package/dist/serve/docs-ui/docs/pyric-ui-events-hooks-reference-api/index.html +0 -24
  507. package/dist/serve/docs-ui/docs/pyric-ui-firestore-hooks-reference-api/index.html +0 -136
  508. package/dist/serve/docs-ui/docs/pyric-ui-rules-hooks-reference-api/index.html +0 -16
  509. package/dist/serve/docs-ui/docs/pyric-ui-storage-hooks-reference-api/index.html +0 -176
  510. package/dist/serve/docs-ui/docs/pyric-ui-traffic-hooks-reference-api/index.html +0 -188
  511. package/dist/serve/docs-ui/docs/secure/audit-your-rules/index.html +0 -51
  512. package/dist/serve/docs-ui/docs/secure/firestore-rules-limits/index.html +0 -106
  513. package/dist/serve/docs-ui/docs/secure/read-a-denial/index.html +0 -41
  514. package/dist/serve/docs-ui/docs/secure/rtdb-rules-in-typescript/index.html +0 -67
  515. package/dist/serve/docs-ui/docs/secure/rules-standard-library/index.html +0 -159
  516. package/dist/serve/docs-ui/docs/secure/secure-it-with-rules/index.html +0 -47
  517. package/dist/serve/docs-ui/docs/secure/simulate-and-lint/index.html +0 -95
  518. package/dist/serve/docs-ui/docs/secure/write-a-rules-test-suite/index.html +0 -82
  519. package/dist/serve/docs-ui/docs/ship/ship-to-production/index.html +0 -37
  520. package/dist/serve/docs-ui/docs/ship/test-in-node/index.html +0 -75
  521. package/dist/serve/docs-ui/docs/trust/how-we-know-it-matches-firebase/index.html +0 -132
  522. package/dist/serve/docs-ui/docs/trust/versioning-and-compatibility/index.html +0 -14
  523. package/dist/serve/docs-ui/index.html +0 -1
  524. package/dist/serve/studio-ui/assets/RulesCodeEditor-BDlH-5lp.js +0 -23
  525. package/dist/serve/studio-ui/assets/index-Bf9SSE8L.js +0 -1218
  526. package/dist/serve/studio-ui/assets/index-BlSGru_r.css +0 -1
  527. package/dist/serve/studio-ui/assets/seed-D_UjxfOU.js +0 -20
  528. package/dist/serve/studio-ui/index.html +0 -32
  529. package/dist/serve/worker/client/rtdb.d.ts +0 -36
  530. package/dist/serve/worker/client/rtdb.d.ts.map +0 -1
  531. package/dist/serve/worker/client/rtdb.js +0 -241
  532. package/dist/serve/worker/client/rtdb.js.map +0 -1
  533. package/src/serve/worker/client/rtdb.ts +0 -311
  534. /package/dist/serve/{docs-ui → site-ui}/404.html +0 -0
  535. /package/dist/serve/{docs-ui → site-ui}/_astro/_slug_.CXh9yTP1.css +0 -0
  536. /package/dist/serve/{docs-ui → site-ui}/docs/_rhythm.md +0 -0
  537. /package/dist/serve/{docs-ui → site-ui}/docs/agent/set-up-your-agent.md +0 -0
  538. /package/dist/serve/{docs-ui → site-ui}/docs/agent/watch-and-review.md +0 -0
  539. /package/dist/serve/{docs-ui → site-ui}/docs/agent/work-with-an-agent.md +0 -0
  540. /package/dist/serve/{docs-ui → site-ui}/docs/ai-compat.md +0 -0
  541. /package/dist/serve/{docs-ui → site-ui}/docs/api-reference.md +0 -0
  542. /package/dist/serve/{docs-ui → site-ui}/docs/app-compat.md +0 -0
  543. /package/dist/serve/{docs-ui → site-ui}/docs/auth-compat.md +0 -0
  544. /package/dist/serve/{docs-ui → site-ui}/docs/build/ai-logic.md +0 -0
  545. /package/dist/serve/{docs-ui → site-ui}/docs/build/authentication.md +0 -0
  546. /package/dist/serve/{docs-ui → site-ui}/docs/build/cloud-firestore.md +0 -0
  547. /package/dist/serve/{docs-ui → site-ui}/docs/build/cloud-messaging.md +0 -0
  548. /package/dist/serve/{docs-ui → site-ui}/docs/build/realtime-database.md +0 -0
  549. /package/dist/serve/{docs-ui → site-ui}/docs/create-pyric-reference-api.md +0 -0
  550. /package/dist/serve/{docs-ui → site-ui}/docs/functions-rtdb-compat.md +0 -0
  551. /package/dist/serve/{docs-ui → site-ui}/docs/get-started/how-the-swap-works.md +0 -0
  552. /package/dist/serve/{docs-ui → site-ui}/docs/get-started/start-building.md +0 -0
  553. /package/dist/serve/{docs-ui → site-ui}/docs/index.html +0 -0
  554. /package/dist/serve/{docs-ui → site-ui}/docs/observe/resolve-runtime-status.md +0 -0
  555. /package/dist/serve/{docs-ui → site-ui}/docs/observe/see-whats-happening.md +0 -0
  556. /package/dist/serve/{docs-ui → site-ui}/docs/observe/shape-your-data.md +0 -0
  557. /package/dist/serve/{docs-ui → site-ui}/docs/overview.md +0 -0
  558. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-admin-app-reference-api.md +0 -0
  559. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-admin-auth-reference-api.md +0 -0
  560. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-admin-database-reference-api.md +0 -0
  561. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-admin-messaging-reference-api.md +0 -0
  562. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-admin-storage-reference-api.md +0 -0
  563. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-ai-reference-api.md +0 -0
  564. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-ai-scripting-reference-api.md +0 -0
  565. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-app-reference-api.md +0 -0
  566. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-cli-assurance-browser-reference-api.md +0 -0
  567. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-cli-assurance-reference-api.md +0 -0
  568. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-cli-bridge-client-reference-api.md +0 -0
  569. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-cli-bridge-reference-api.md +0 -0
  570. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-cli-conformance-browser-reference-api.md +0 -0
  571. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-cli-conformance-docs-reference-api.md +0 -0
  572. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-cli-conformance-reference-api.md +0 -0
  573. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-cli-credentials-node-reference-api.md +0 -0
  574. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-cli-discover-reference-api.md +0 -0
  575. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-cli-register-reference-api.md +0 -0
  576. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-cli-remote-reference-api.md +0 -0
  577. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-cli-verify-reference-api.md +0 -0
  578. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-messaging-reference-api.md +0 -0
  579. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-messaging-sw-reference-api.md +0 -0
  580. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-sandbox-database-reference-api.md +0 -0
  581. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-sandbox-firestore-reference-api.md +0 -0
  582. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-ui-agents-reference-api.md +0 -0
  583. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-ui-auth-hooks-reference-api.md +0 -0
  584. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-ui-auth-reference-api.md +0 -0
  585. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-ui-events-hooks-reference-api.md +0 -0
  586. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-ui-events-reference-api.md +0 -0
  587. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-ui-firestore-hooks-reference-api.md +0 -0
  588. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-ui-primitives-reference-api.md +0 -0
  589. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-ui-rtdb-reference-api.md +0 -0
  590. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-ui-rules-hooks-reference-api.md +0 -0
  591. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-ui-rules-reference-api.md +0 -0
  592. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-ui-storage-hooks-reference-api.md +0 -0
  593. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-ui-traffic-hooks-reference-api.md +0 -0
  594. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-ui-traffic-reference-api.md +0 -0
  595. /package/dist/serve/{docs-ui → site-ui}/docs/secure/audit-your-rules.md +0 -0
  596. /package/dist/serve/{docs-ui → site-ui}/docs/secure/firestore-rules-limits.md +0 -0
  597. /package/dist/serve/{docs-ui → site-ui}/docs/secure/read-a-denial.md +0 -0
  598. /package/dist/serve/{docs-ui → site-ui}/docs/secure/rtdb-rules-in-typescript.md +0 -0
  599. /package/dist/serve/{docs-ui → site-ui}/docs/secure/secure-it-with-rules.md +0 -0
  600. /package/dist/serve/{docs-ui → site-ui}/docs/secure/simulate-and-lint.md +0 -0
  601. /package/dist/serve/{docs-ui → site-ui}/docs/secure/write-a-rules-test-suite.md +0 -0
  602. /package/dist/serve/{docs-ui → site-ui}/docs/ship/ship-to-production.md +0 -0
  603. /package/dist/serve/{docs-ui → site-ui}/docs/ship/test-in-node.md +0 -0
  604. /package/dist/serve/{docs-ui → site-ui}/docs/trust/how-we-know-it-matches-firebase.md +0 -0
  605. /package/dist/serve/{docs-ui → site-ui}/docs/trust/versioning-and-compatibility.md +0 -0
  606. /package/dist/serve/{studio-ui → site-ui}/pyric-logo.svg +0 -0
@@ -0,0 +1,1153 @@
1
+ var oo=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function pu(t){if(Object.prototype.hasOwnProperty.call(t,"__esModule"))return t;var e=t.default;if(typeof e=="function"){var r=function n(){return this instanceof n?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};r.prototype=e.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(t).forEach(function(n){var s=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(r,n,s.get?s:{enumerable:!0,get:function(){return t[n]}})}),r}function De(t){const e=t||"";return function(){throw new Error("this method "+e+" is abstract! (it has no implementation in class "+this.constructor.name+")")}}function It(t,e){if(!t)throw new Error(e||"Assertion failed")}function us(t,e,r){let n;Object.defineProperty(t,e,{get(){return n||(n=r.call(this)),n}})}function co(t,e){const r=[];for(;e-- >0;)r.push(t());return r}function uo(t,e){return new Array(e+1).join(t)}function Fn(t,e){return co(()=>t,e)}function ls(t){const e=[];for(let r=0;r<t.length;r++){const n=t[r];t.lastIndexOf(n)!==r&&e.indexOf(n)<0&&e.push(n)}return e}function lo(t){const e=[];return t.forEach(r=>{e.indexOf(r)<0&&e.push(r)}),e}function Nt(t){const e=t[0];return e===e.toUpperCase()}function ho(t){return!Nt(t)}function fo(t,e,r){return t.length<e?uo(" ",e-t.length)+t:t}function Bt(){this.strings=[]}Bt.prototype.append=function(t){this.strings.push(t)};Bt.prototype.contents=function(){return this.strings.join("")};const Vn=t=>String.fromCodePoint(parseInt(t,16));function po(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 Vn(t.slice(2,4));case"u":return t.charAt(2)==="{"?Vn(t.slice(3,-1)):Vn(t.slice(2,6));default:return t.charAt(1)}else return t}function Zs(t){if(t==null)return String(t);const e=Object.prototype.toString.call(t);try{let r;return t.constructor&&t.constructor.name?r=t.constructor.name:e.indexOf("[object ")===0?r=e.slice(8,-1):r=typeof t,r+": "+JSON.stringify(String(t))}catch{return e}}function mo(t,e="unexpected null value"){if(t==null)throw new Error(e);return t}const mu=Object.freeze(Object.defineProperty({__proto__:null,StringBuffer:Bt,abstract:De,assert:It,checkNotNull:mo,copyWithoutDuplicates:lo,defineLazyProperty:us,getDuplicates:ls,isLexical:ho,isSyntactic:Nt,padLeft:fo,repeat:Fn,repeatFn:co,repeatStr:uo,unescapeCodePoint:po,unexpectedObjToString:Zs},Symbol.toStringTag,{value:"Module"})),go=t=>new RegExp(String.raw`\p{${t}}`,"u"),ds=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,go(t)]));ds.Ltmo=/\p{Lt}|\p{Lm}|\p{Lo}/u;const Ci=Object.fromEntries(["XID_Start","XID_Continue","White_Space"].map(t=>[t,go(t)]));class z{constructor(){if(this.constructor===z)throw new Error("PExpr cannot be instantiated -- it's abstract")}withSource(e){return e&&(this.source=e.trimmed()),this}}const Te=Object.create(z.prototype),Re=Object.create(z.prototype);class Oe extends z{constructor(e){super(),this.obj=e}}class Ne extends z{constructor(e,r){super(),this.from=e,this.to=r,this.matchCodePoint=e.length>1||r.length>1}}class Fe extends z{constructor(e){super(),this.index=e}}class be extends z{constructor(e){super(),this.terms=e}}class Ln extends be{constructor(e,r,n){const s=e.rules[r].body;super([n,s]),this.superGrammar=e,this.name=r,this.body=n}}class jn extends be{constructor(e,r,n,s){const i=e.rules[r].body;super([...n,i,...s]),this.superGrammar=e,this.ruleName=r,this.expansionPos=n.length}}class Ae extends z{constructor(e){super(),this.factors=e}}class Me extends z{constructor(e){super(),this.expr=e}}class zt extends Me{}class ar extends Me{}class mt extends Me{}zt.prototype.operator="*";ar.prototype.operator="+";mt.prototype.operator="?";zt.prototype.minNumMatches=0;ar.prototype.minNumMatches=1;mt.prototype.minNumMatches=0;zt.prototype.maxNumMatches=Number.POSITIVE_INFINITY;ar.prototype.maxNumMatches=Number.POSITIVE_INFINITY;mt.prototype.maxNumMatches=1;class ke extends z{constructor(e){super(),this.expr=e}}class Pe extends z{constructor(e){super(),this.expr=e}}class qe extends z{constructor(e){super(),this.expr=e}}class X extends z{constructor(e,r=[]){super(),this.ruleName=e,this.args=r}isSyntactic(){return Nt(this.ruleName)}toMemoKey(){return this._memoKey||Object.defineProperty(this,"_memoKey",{value:this.toString()}),this._memoKey}}class Ee extends z{constructor(e){if(super(),this.categoryOrProp=e,e in ds)this.pattern=ds[e];else if(e in Ci)this.pattern=Ci[e];else throw new Error(`Invalid Unicode category or property name: ${JSON.stringify(e)}`)}}function le(t,e){let r;return e?(r=new Error(e.getLineAndColumnMessage()+t),r.shortMessage=t,r.interval=e):r=new Error(t),r}function hs(){return le("Interval sources don't match")}function gu(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 yu(t,e,r){const n=e?`Grammar ${t} is not declared in namespace '${e}'`:"Undeclared grammar "+t;return le(n,r)}function bu(t,e){return le("Grammar "+t.name+" is already declared in this namespace")}function vu(t){return le(`Grammar '${t.name}' does not support incremental parsing`)}function yo(t,e,r){return le("Rule "+t+" is not declared in grammar "+e,r)}function wu(t,e,r){return le("Cannot override rule "+t+" because it is not declared in "+e,r)}function Su(t,e,r){return le("Cannot extend rule "+t+" because it is not declared in "+e,r)}function Ti(t,e,r,n){let s="Duplicate declaration for rule '"+t+"' in grammar '"+e+"'";return e!==r&&(s+=" (originally declared in '"+r+"')"),le(s,n)}function bo(t,e,r,n){return le("Wrong number of parameters for rule "+t+" (expected "+e+", got "+r+")",n)}function _u(t,e,r,n){return le("Wrong number of arguments for rule "+t+" (expected "+e+", got "+r+")",n)}function Ri(t,e,r){return le("Duplicate parameter names in rule "+t+": "+e.join(", "),r)}function Au(t,e){return le("Invalid parameter to rule "+t+": "+e+" has arity "+e.getArity()+", but parameter expressions must have arity 1",e.source)}const xu="NOTE: A _syntactic rule_ is a rule whose name begins with a capital letter. See https://ohmjs.org/d/svl for more details.";function Iu(t,e){return le("Cannot apply syntactic rule "+t+" from here (inside a lexical context)",e.source)}function ku(t){const{ruleName:e}=t;return le(`applySyntactic is for syntactic rules, but '${e}' is a lexical rule. `+xu,t.source)}function Eu(t){return le("applySyntactic is not required here (in a syntactic context)",t.source)}function Ni(t,e){return le("Incorrect argument type: expected "+t,e.source)}function Ou(t){return le("'...' can appear at most once in a rule body",t.source)}function Cu(t){const e=t._node;It(e&&e.isNonterminal()&&e.ctorName==="escapeChar_unicodeCodePoint");const r=t.children.slice(1,-1).map(s=>s.source),n=r[0].coverageWith(...r.slice(1));return le(`U+${n.contents} is not a valid Unicode code point`,n)}function vo(t,e){const r=e.length>0?e[e.length-1].args:[];let s="Nullable expression "+t.expr.substituteParams(r)+" 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 le(s,t.expr.source)}function wo(t,e,r,n){return le("Rule "+t+" involves an alternation which has inconsistent arity (expected "+e+", got "+r+")",n.source)}function Tu(t){const e=t.map(r=>r.message);return le(["Errors:"].concat(e).join(`
6
+ - `),t[0].interval)}function Ru(t,e,r,n){let s=n.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 ${r} '${e}'.${i}`,"Action stack (most recent call last):",s].join(`
11
+ `),o=le(a);return o.name="missingSemanticAction",o}function Nu(t){if(t.length===1)throw t[0];if(t.length>1)throw Tu(t)}function Fu(t){let e=0;return t.map(n=>{const s=n.toString();return e=Math.max(e,s.length),s}).map(n=>fo(n,e))}function Fi(t,e,r){const n=t.length,s=t.slice(0,r),i=t.slice(r+e.length);return(s+e+i).substr(0,n)}function Lu(...t){const e=this,{offset:r}=e,{repeatStr:n}=mu,s=new Bt;s.append("Line "+e.lineNum+", col "+e.colNum+`:
12
+ `);const i=Fu([e.prevLine==null?0:e.lineNum-1,e.lineNum,e.nextLine==null?0:e.lineNum+1]),a=(d,l,f)=>{s.append(f+i[d]+" | "+l+`
13
+ `)};e.prevLine!=null&&a(0,e.prevLine," "),a(1,e.line,"> ");const o=e.line.length;let c=n(" ",o+1);for(let d=0;d<t.length;++d){let l=t[d][0],f=t[d][1];It(l>=0&&l<=f,"range start must be >= 0 and <= end");const y=r-e.colNum+1;l=Math.max(0,l-y),f=Math.min(f-y,o),c=Fi(c,n("~",f-l),l)}const u=2+i[1].length+3;return s.append(n(" ",u)),c=Fi(c,"^",e.colNum-1),s.append(c.replace(/ +$/,"")+`
14
+ `),e.nextLine!=null&&a(2,e.nextLine," "),s.contents()}let fs=[];function So(t){fs.push(t)}function ju(t){fs.forEach(e=>{e(t)}),fs=null}function Js(t,e){let r=1,n=1,s=0,i=0,a=null,o=null,c=-1;for(;s<e;){const l=t.charAt(s++);l===`
15
+ `?(r++,n=1,c=i,i=s):l!=="\r"&&n++}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:r,colNum:n,line:d,prevLine:o,nextLine:a,toString:Lu}}function Qs(t,e,...r){return Js(t,e).toString(...r)}const Li=(()=>{let t=0;return e=>""+e+t++})();class Ce{constructor(e,r,n){Object.defineProperty(this,"_sourceString",{value:e,configurable:!1,enumerable:!1,writable:!1}),this.startIdx=r,this.endIdx=n}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 Js(this.sourceString,this.startIdx)}getLineAndColumnMessage(){const e=[this.startIdx,this.endIdx];return Qs(this.sourceString,this.startIdx,e)}minus(e){if(this.sourceString!==e.sourceString)throw hs();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 hs();return It(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,r=this.startIdx+e.match(/^\s*/)[0].length,n=this.endIdx-e.match(/\s*$/)[0].length;return new Ce(this.sourceString,r,n)}subInterval(e,r){const n=this.startIdx+e;return new Ce(this.sourceString,n,n+r)}}Ce.coverage=function(t,...e){let{startIdx:r,endIdx:n}=t;for(const s of e){if(s.sourceString!==t.sourceString)throw hs();r=Math.min(r,s.startIdx),n=Math.max(n,s.endIdx)}return new Ce(t.sourceString,r,n)};const Du=65535,Mu=1114111;class Dn{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>Du&&(this.pos+=1),this.examinedLength=Math.max(this.examinedLength,this.pos),e}matchString(e,r){let n;if(r){for(n=0;n<e.length;n++){const s=this.next(),i=e[n];if(s==null||s.toUpperCase()!==i.toUpperCase())return!1}return!0}for(n=0;n<e.length;n++)if(this.next()!==e[n])return!1;return!0}sourceSlice(e,r){return this.source.slice(e,r)}interval(e,r){return new Ce(this.source,e,r||this.pos)}}class _o{constructor(e,r,n,s,i,a,o){this.matcher=e,this.input=r,this.startExpr=n,this._cst=s,this._cstOffset=i,this._rightmostFailurePosition=a,this._rightmostFailures=o,this.failed()&&(us(this,"message",function(){const c="Expected "+this.getExpectedText();return Qs(this.input,this.getRightmostFailurePosition())+c}),us(this,"shortMessage",function(){const c="expected "+this.getExpectedText(),u=Js(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 Bt;let r=this.getRightmostFailures();r=r.filter(n=>!n.isFluffy());for(let n=0;n<r.length;n++)n>0&&(n===r.length-1?e.append(r.length>2?", or ":" or "):e.append(", ")),e.append(r[n].toString());return e.contents()}getInterval(){const e=this.getRightmostFailurePosition();return new Ce(this.input,e,e)}}class Pu{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,r){r.isLeftRecursion=!0,r.headApplication=e,r.nextLeftRecursion=this.currentLeftRecursion,this.currentLeftRecursion=r;const{applicationMemoKeyStack:n}=this,s=n.indexOf(e.toMemoKey())+1,i=n.slice(s);r.isInvolved=function(a){return i.indexOf(a)>=0},r.updateInvolvedApplicationMemoKeys=function(){for(let a=s;a<n.length;a++){const o=n[a];this.isInvolved(o)||i.push(o)}}}endLeftRecursion(){this.currentLeftRecursion=this.currentLeftRecursion.nextLeftRecursion}shouldUseMemoizedResult(e){if(!e.isLeftRecursion)return!0;const{applicationMemoKeyStack:r}=this;for(let n=0;n<r.length;n++){const s=r[n];if(e.isInvolved(s))return!1}return!0}memoize(e,r){return this.memo[e]=r,this.maxExaminedLength=Math.max(this.maxExaminedLength,r.examinedLength),this.maxRightmostFailureOffset=Math.max(this.maxRightmostFailureOffset,r.rightmostFailureOffset),r}clearObsoleteEntries(e,r){if(e+this.maxExaminedLength<=r)return;const{memo:n}=this;this.maxExaminedLength=0,this.maxRightmostFailureOffset=-1,Object.keys(n).forEach(s=>{const i=n[s];e+i.examinedLength>r?delete n[s]:(this.maxExaminedLength=Math.max(this.maxExaminedLength,i.examinedLength),this.maxRightmostFailureOffset=Math.max(this.maxRightmostFailureOffset,i.rightmostFailureOffset))})}}const $u="✗",qu="✓",Uu="⋅",Bu="⇒",zu="␉",Vu="␊",Wu="␍",ps={succeeded:1,isRootNode:2,isImplicitSpaces:4,isMemoized:8,isHeadOfLeftRecursion:16,terminatesLR:32};function Hu(t){return Fn(" ",t).join("")}function Gu(t,e,r){const n=Ao(t.slice(e,e+r));return n.length<r?n+Fn(" ",r-n.length).join(""):n}function Ao(t){return typeof t=="string"?t.replace(/ /g,Uu).replace(/\t/g,zu).replace(/\n/g,Vu).replace(/\r/g,Wu):String(t)}class vt{constructor(e,r,n,s,i,a,o){this.input=e,this.pos=this.pos1=r,this.pos2=n,this.source=new Ce(e,r,n),this.expr=s,this.bindings=a,this.children=o||[],this.terminatingLREntry=null,this._flags=i?ps.succeeded:0}get displayString(){return this.expr.toDisplayString()}clone(){return this.cloneWithExpr(this.expr)}cloneWithExpr(e){const r=new vt(this.input,this.pos,this.pos2,e,this.succeeded,this.bindings,this.children);return r.isHeadOfLeftRecursion=this.isHeadOfLeftRecursion,r.isImplicitSpaces=this.isImplicitSpaces,r.isMemoized=this.isMemoized,r.isRootNode=this.isRootNode,r.terminatesLR=this.terminatesLR,r.terminatingLREntry=this.terminatingLREntry,r}recordLRTermination(e,r){this.terminatingLREntry=new vt(this.input,this.pos,this.pos2,this.expr,!1,[r],[e]),this.terminatingLREntry.terminatesLR=!0}walk(e,r){let n=e;typeof n=="function"&&(n={enter:n});function s(i,a,o){let c=!0;n.enter&&n.enter.call(r,i,a,o)===vt.prototype.SKIP&&(c=!1),c&&(i.children.forEach(u=>{s(u,i,o+1)}),n.exit&&n.exit.call(r,i,a,o))}this.isRootNode?this.children.forEach(i=>{s(i,null,0)}):s(this,null,0)}toString(){const e=new Bt;return this.walk((r,n,s)=>{if(!r)return this.SKIP;if(r.expr.constructor.name!=="Alt"){if(e.append(Gu(r.input,r.pos,10)+Hu(s*2+1)),e.append((r.succeeded?qu:$u)+" "+r.displayString),r.isHeadOfLeftRecursion&&e.append(" (LR)"),r.succeeded){const a=Ao(r.source.contents);e.append(" "+Bu+" "),e.append(typeof a=="string"?'"'+a+'"':a)}e.append(`
18
+ `)}}),e.contents()}}vt.prototype.SKIP={};Object.keys(ps).forEach(t=>{const e=ps[t];Object.defineProperty(vt.prototype,t,{get(){return(this._flags&e)!==0},set(r){r?this._flags|=e:this._flags&=~e}})});z.prototype.allowsSkippingPrecedingSpace=De("allowsSkippingPrecedingSpace");Te.allowsSkippingPrecedingSpace=Re.allowsSkippingPrecedingSpace=X.prototype.allowsSkippingPrecedingSpace=Oe.prototype.allowsSkippingPrecedingSpace=Ne.prototype.allowsSkippingPrecedingSpace=Ee.prototype.allowsSkippingPrecedingSpace=function(){return!0};be.prototype.allowsSkippingPrecedingSpace=Me.prototype.allowsSkippingPrecedingSpace=qe.prototype.allowsSkippingPrecedingSpace=Pe.prototype.allowsSkippingPrecedingSpace=ke.prototype.allowsSkippingPrecedingSpace=Fe.prototype.allowsSkippingPrecedingSpace=Ae.prototype.allowsSkippingPrecedingSpace=function(){return!1};let dr;So(t=>{dr=t});let Qr;z.prototype.assertAllApplicationsAreValid=function(t,e){Qr=0,this._assertAllApplicationsAreValid(t,e)};z.prototype._assertAllApplicationsAreValid=De("_assertAllApplicationsAreValid");Te._assertAllApplicationsAreValid=Re._assertAllApplicationsAreValid=Oe.prototype._assertAllApplicationsAreValid=Ne.prototype._assertAllApplicationsAreValid=Fe.prototype._assertAllApplicationsAreValid=Ee.prototype._assertAllApplicationsAreValid=function(t,e){};qe.prototype._assertAllApplicationsAreValid=function(t,e){Qr++,this.expr._assertAllApplicationsAreValid(t,e),Qr--};be.prototype._assertAllApplicationsAreValid=function(t,e){for(let r=0;r<this.terms.length;r++)this.terms[r]._assertAllApplicationsAreValid(t,e)};Ae.prototype._assertAllApplicationsAreValid=function(t,e){for(let r=0;r<this.factors.length;r++)this.factors[r]._assertAllApplicationsAreValid(t,e)};Me.prototype._assertAllApplicationsAreValid=ke.prototype._assertAllApplicationsAreValid=Pe.prototype._assertAllApplicationsAreValid=function(t,e){this.expr._assertAllApplicationsAreValid(t,e)};X.prototype._assertAllApplicationsAreValid=function(t,e,r=!1){const n=e.rules[this.ruleName],s=Nt(t)&&Qr===0;if(!n)throw yo(this.ruleName,e.name,this.source);if(!r&&Nt(this.ruleName)&&!s)throw Iu(this.ruleName,this);const i=this.args.length,a=n.formals.length;if(i!==a)throw _u(this.ruleName,a,i,this.source);const o=dr&&n===dr.rules.applySyntactic;if(dr&&n===dr.rules.caseInsensitive&&!(this.args[0]instanceof Oe))throw Ni('a Terminal (e.g. "abc")',this.args[0]);if(o){const u=this.args[0];if(!(u instanceof X))throw Ni("a syntactic rule application",u);if(!Nt(u.ruleName))throw ku(u);if(s)throw Eu(this)}this.args.forEach(u=>{if(u._assertAllApplicationsAreValid(t,e,o),u.getArity()!==1)throw Au(this.ruleName,u)})};z.prototype.assertChoicesHaveUniformArity=De("assertChoicesHaveUniformArity");Te.assertChoicesHaveUniformArity=Re.assertChoicesHaveUniformArity=Oe.prototype.assertChoicesHaveUniformArity=Ne.prototype.assertChoicesHaveUniformArity=Fe.prototype.assertChoicesHaveUniformArity=qe.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 r=0;r<this.terms.length;r++){const n=this.terms[r];n.assertChoicesHaveUniformArity();const s=n.getArity();if(e!==s)throw wo(t,e,s,n)}};Ln.prototype.assertChoicesHaveUniformArity=function(t){const e=this.terms[0].getArity(),r=this.terms[1].getArity();if(e!==r)throw wo(t,r,e,this.terms[0])};Ae.prototype.assertChoicesHaveUniformArity=function(t){for(let e=0;e<this.factors.length;e++)this.factors[e].assertChoicesHaveUniformArity(t)};Me.prototype.assertChoicesHaveUniformArity=function(t){this.expr.assertChoicesHaveUniformArity(t)};ke.prototype.assertChoicesHaveUniformArity=function(t){};Pe.prototype.assertChoicesHaveUniformArity=function(t){this.expr.assertChoicesHaveUniformArity(t)};X.prototype.assertChoicesHaveUniformArity=function(t){};z.prototype.assertIteratedExprsAreNotNullable=De("assertIteratedExprsAreNotNullable");Te.assertIteratedExprsAreNotNullable=Re.assertIteratedExprsAreNotNullable=Oe.prototype.assertIteratedExprsAreNotNullable=Ne.prototype.assertIteratedExprsAreNotNullable=Fe.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)};Me.prototype.assertIteratedExprsAreNotNullable=function(t){if(this.expr.assertIteratedExprsAreNotNullable(t),this.expr.isNullable(t))throw vo(this,[])};mt.prototype.assertIteratedExprsAreNotNullable=ke.prototype.assertIteratedExprsAreNotNullable=Pe.prototype.assertIteratedExprsAreNotNullable=qe.prototype.assertIteratedExprsAreNotNullable=function(t){this.expr.assertIteratedExprsAreNotNullable(t)};X.prototype.assertIteratedExprsAreNotNullable=function(t){this.args.forEach(e=>{e.assertIteratedExprsAreNotNullable(t)})};class Ys{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 r=this.indexOfChild(e);if(r<0)throw new Error("Node.childBefore() called w/ an argument that is not a child");if(r===0)throw new Error("cannot get child before first child");return this.childAt(r-1)}childAfter(e){const r=this.indexOfChild(e);if(r<0)throw new Error("Node.childAfter() called w/ an argument that is not a child");if(r===this.numChildren()-1)throw new Error("cannot get child after last child");return this.childAt(r+1)}isTerminal(){return!1}isNonterminal(){return!1}isIteration(){return!1}isOptional(){return!1}}class Vt extends Ys{get ctorName(){return"_terminal"}isTerminal(){return!0}get primitiveValue(){throw new Error("The `primitiveValue` property was removed in Ohm v17.")}}class Ku extends Ys{constructor(e,r,n,s){super(s),this.ruleName=e,this.children=r,this.childOffsets=n}get ctorName(){return this.ruleName}isNonterminal(){return!0}isLexical(){return ho(this.ctorName)}isSyntactic(){return Nt(this.ctorName)}}class xo extends Ys{constructor(e,r,n,s){super(n),this.children=e,this.childOffsets=r,this.optional=s}get ctorName(){return"_iter"}isIteration(){return!0}isOptional(){return this.optional}}z.prototype.eval=De("eval");Te.eval=function(t){const{inputStream:e}=t,r=e.pos,n=e.nextCodePoint();return n!==void 0?(t.pushBinding(new Vt(String.fromCodePoint(n).length),r),!0):(t.processFailure(r,this),!1)};Re.eval=function(t){const{inputStream:e}=t,r=e.pos;return e.atEnd()?(t.pushBinding(new Vt(0),r),!0):(t.processFailure(r,this),!1)};Oe.prototype.eval=function(t){const{inputStream:e}=t,r=e.pos;return e.matchString(this.obj)?(t.pushBinding(new Vt(this.obj.length),r),!0):(t.processFailure(r,this),!1)};Ne.prototype.eval=function(t){const{inputStream:e}=t,r=e.pos,n=this.matchCodePoint?e.nextCodePoint():e.nextCharCode();return n!==void 0&&this.from.codePointAt(0)<=n&&n<=this.to.codePointAt(0)?(t.pushBinding(new Vt(String.fromCodePoint(n).length),r),!0):(t.processFailure(r,this),!1)};Fe.prototype.eval=function(t){return t.eval(t.currentApplication().args[this.index])};qe.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 r=this.factors[e];if(!t.eval(r))return!1}return!0};Me.prototype.eval=function(t){const{inputStream:e}=t,r=e.pos,n=this.getArity(),s=[],i=[];for(;s.length<n;)s.push([]),i.push([]);let a=0,o=r,c;for(;a<this.maxNumMatches&&t.eval(this.expr);){if(e.pos===o)throw vo(this,t._applicationStack);o=e.pos,a++;const f=t._bindings.splice(t._bindings.length-n,n),y=t._bindingOffsets.splice(t._bindingOffsets.length-n,n);for(c=0;c<f.length;c++)s[c].push(f[c]),i[c].push(y[c])}if(a<this.minNumMatches)return!1;let u=t.posToOffset(r),d=0;if(a>0){const f=s[n-1],y=i[n-1],b=y[y.length-1]+f[f.length-1].matchLength;u=i[0][0],d=b-u}const l=this instanceof mt;for(c=0;c<s.length;c++)t._bindings.push(new xo(s[c],i[c],d,l)),t._bindingOffsets.push(u);return!0};ke.prototype.eval=function(t){const{inputStream:e}=t,r=e.pos;t.pushFailuresInfo();const n=t.eval(this.expr);return t.popFailuresInfo(),n?(t.processFailure(r,this),!1):(e.pos=r,!0)};Pe.prototype.eval=function(t){const{inputStream:e}=t,r=e.pos;return t.eval(this.expr)?(e.pos=r,!0):!1};X.prototype.eval=function(t){const e=t.currentApplication(),r=e?e.args:[],n=this.substituteParams(r),s=t.getCurrentPosInfo();if(s.isActive(n))return n.handleCycle(t);const i=n.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 n.reallyEval(t)};X.prototype.handleCycle=function(t){const e=t.getCurrentPosInfo(),{currentLeftRecursion:r}=e,n=this.toMemoKey();let s=e.memo[n];return r&&r.headApplication.toMemoKey()===n?s.updateInvolvedApplicationMemoKeys():s||(s=e.memoize(n,{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,r=e.pos,n=t.getCurrentPosInfo(),s=t.grammar.rules[this.ruleName],{body:i}=s,{description:a}=s;t.enterApplication(n,this),a&&t.pushFailuresInfo();const o=e.examinedLength;e.examinedLength=0;let c=this.evalOnce(i,t);const u=n.currentLeftRecursion,d=this.toMemoKey(),l=u&&u.headApplication.toMemoKey()===d;let f;t.doNotMemoize?t.doNotMemoize=!1:l?(c=this.growSeedResult(i,t,r,u,c),n.endLeftRecursion(),f=u,f.examinedLength=e.examinedLength-r,f.rightmostFailureOffset=t._getRightmostFailureOffset(),n.memoize(d,f)):(!u||!u.isInvolved(d))&&(f=n.memoize(d,{matchLength:e.pos-r,examinedLength:e.examinedLength-r,value:c,failuresAtRightmostPosition:t.cloneRecordedFailures(),rightmostFailureOffset:t._getRightmostFailureOffset()}));const y=!!c;if(a&&(t.popFailuresInfo(),y||t.processFailure(r,this),f&&(f.failuresAtRightmostPosition=t.cloneRecordedFailures(),f.rightmostFailureOffset=t._getRightmostFailureOffset())),t.isTracing()&&f){const b=t.getTraceEntry(r,this,y,y?[c]:[]);l&&(It(b.terminatingLREntry!=null||!y),b.isHeadOfLeftRecursion=!0),f.traceEntry=b}return e.examinedLength=Math.max(e.examinedLength,o),t.exitApplication(n,c),y};X.prototype.evalOnce=function(t,e){const{inputStream:r}=e,n=r.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=r.pos-n;return new Ku(this.ruleName,i,a,o)}else return!1};X.prototype.growSeedResult=function(t,e,r,n,s){if(!s)return!1;const{inputStream:i}=e;for(;;){if(n.matchLength=i.pos-r,n.value=s,n.failuresAtRightmostPosition=e.cloneRecordedFailures(),e.isTracing()){const a=e.trace[e.trace.length-1];n.traceEntry=new vt(e.input,r,i.pos,this,!0,[s],[a.clone()])}if(i.pos=r,s=this.evalOnce(t,e),i.pos-r<=n.matchLength)break;e.isTracing()&&e.trace.splice(-2,1)}return e.isTracing()&&n.traceEntry.recordLRTermination(e.trace.pop(),s),i.pos=r+n.matchLength,n.value};Ee.prototype.eval=function(t){const{inputStream:e}=t,r=e.pos,n=e.nextCodePoint();if(n!==void 0&&n<=Mu){const s=String.fromCodePoint(n);if(this.pattern.test(s))return t.pushBinding(new Vt(s.length),r),!0}return t.processFailure(r,this),!1};z.prototype.getArity=De("getArity");Te.getArity=Re.getArity=Oe.prototype.getArity=Ne.prototype.getArity=Fe.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};Me.prototype.getArity=function(){return this.expr.getArity()};ke.prototype.getArity=function(){return 0};Pe.prototype.getArity=qe.prototype.getArity=function(){return this.expr.getArity()};function Qe(t,e){const r={};if(t.source&&e){const n=t.source.relativeTo(e);r.sourceInterval=[n.startIdx,n.endIdx]}return r}z.prototype.outputRecipe=De("outputRecipe");Te.outputRecipe=function(t,e){return["any",Qe(this,e)]};Re.outputRecipe=function(t,e){return["end",Qe(this,e)]};Oe.prototype.outputRecipe=function(t,e){return["terminal",Qe(this,e),this.obj]};Ne.prototype.outputRecipe=function(t,e){return["range",Qe(this,e),this.from,this.to]};Fe.prototype.outputRecipe=function(t,e){return["param",Qe(this,e),this.index]};be.prototype.outputRecipe=function(t,e){return["alt",Qe(this,e)].concat(this.terms.map(r=>r.outputRecipe(t,e)))};Ln.prototype.outputRecipe=function(t,e){return this.terms[0].outputRecipe(t,e)};jn.prototype.outputRecipe=function(t,e){const r=this.terms.slice(0,this.expansionPos),n=this.terms.slice(this.expansionPos+1);return["splice",Qe(this,e),r.map(s=>s.outputRecipe(t,e)),n.map(s=>s.outputRecipe(t,e))]};Ae.prototype.outputRecipe=function(t,e){return["seq",Qe(this,e)].concat(this.factors.map(r=>r.outputRecipe(t,e)))};zt.prototype.outputRecipe=ar.prototype.outputRecipe=mt.prototype.outputRecipe=ke.prototype.outputRecipe=Pe.prototype.outputRecipe=qe.prototype.outputRecipe=function(t,e){return[this.constructor.name.toLowerCase(),Qe(this,e),this.expr.outputRecipe(t,e)]};X.prototype.outputRecipe=function(t,e){return["app",Qe(this,e),this.ruleName,this.args.map(r=>r.outputRecipe(t,e))]};Ee.prototype.outputRecipe=function(t,e){return["unicodeChar",Qe(this,e),this.categoryOrProp]};z.prototype.introduceParams=De("introduceParams");Te.introduceParams=Re.introduceParams=Oe.prototype.introduceParams=Ne.prototype.introduceParams=Fe.prototype.introduceParams=Ee.prototype.introduceParams=function(t){return this};be.prototype.introduceParams=function(t){return this.terms.forEach((e,r,n)=>{n[r]=e.introduceParams(t)}),this};Ae.prototype.introduceParams=function(t){return this.factors.forEach((e,r,n)=>{n[r]=e.introduceParams(t)}),this};Me.prototype.introduceParams=ke.prototype.introduceParams=Pe.prototype.introduceParams=qe.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 Fe(e).withSource(this.source)}else return this.args.forEach((r,n,s)=>{s[n]=r.introduceParams(t)}),this};z.prototype.isNullable=function(t){return this._isNullable(t,Object.create(null))};z.prototype._isNullable=De("_isNullable");Te._isNullable=Ne.prototype._isNullable=Fe.prototype._isNullable=ar.prototype._isNullable=Ee.prototype._isNullable=function(t,e){return!1};Re._isNullable=function(t,e){return!0};Oe.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(r=>r._isNullable(t,e))};Ae.prototype._isNullable=function(t,e){return this.factors.every(r=>r._isNullable(t,e))};zt.prototype._isNullable=mt.prototype._isNullable=ke.prototype._isNullable=Pe.prototype._isNullable=function(t,e){return!0};qe.prototype._isNullable=function(t,e){return this.expr._isNullable(t,e)};X.prototype._isNullable=function(t,e){const r=this.toMemoKey();if(!Object.prototype.hasOwnProperty.call(e,r)){const{body:n}=t.rules[this.ruleName],s=n.substituteParams(this.args);e[r]=!1,e[r]=s._isNullable(t,e)}return e[r]};z.prototype.substituteParams=De("substituteParams");Te.substituteParams=Re.substituteParams=Oe.prototype.substituteParams=Ne.prototype.substituteParams=Ee.prototype.substituteParams=function(t){return this};Fe.prototype.substituteParams=function(t){return mo(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)))};Me.prototype.substituteParams=ke.prototype.substituteParams=Pe.prototype.substituteParams=qe.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(r=>r.substituteParams(t));return new X(this.ruleName,e)}};function ji(t){return/^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(t)}function Xs(t){const e=Object.create(null);t.forEach(r=>{e[r]=(e[r]||0)+1}),Object.keys(e).forEach(r=>{if(e[r]<=1)return;let n=1;t.forEach((s,i)=>{s===r&&(t[i]=s+"_"+n++)})})}z.prototype.toArgumentNameList=De("toArgumentNameList");Te.toArgumentNameList=function(t,e){return["any"]};Re.toArgumentNameList=function(t,e){return["end"]};Oe.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 r=this.from+"_to_"+this.to;return ji(r)||(r="_"+r),ji(r)||(r="$"+t),[r]};be.prototype.toArgumentNameList=function(t,e){const r=this.terms.map(i=>i.toArgumentNameList(t,!0)),n=[],s=r[0].length;for(let i=0;i<s;i++){const a=[];for(let c=0;c<this.terms.length;c++)a.push(r[c][i]);const o=lo(a);n.push(o.join("_or_"))}return e||Xs(n),n};Ae.prototype.toArgumentNameList=function(t,e){let r=[];return this.factors.forEach(n=>{const s=n.toArgumentNameList(t,!0);r=r.concat(s),t+=s.length}),e||Xs(r),r};Me.prototype.toArgumentNameList=function(t,e){const r=this.expr.toArgumentNameList(t,e).map(n=>n[n.length-1]==="s"?n+"es":n+"s");return e||Xs(r),r};mt.prototype.toArgumentNameList=function(t,e){return this.expr.toArgumentNameList(t,e).map(r=>"opt"+r[0].toUpperCase()+r.slice(1))};ke.prototype.toArgumentNameList=function(t,e){return[]};Pe.prototype.toArgumentNameList=qe.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]};Fe.prototype.toArgumentNameList=function(t,e){return["param"+this.index]};z.prototype.toDisplayString=De("toDisplayString");be.prototype.toDisplayString=Ae.prototype.toDisplayString=function(){return this.source?this.source.trimmed().contents:"["+this.constructor.name+"]"};Te.toDisplayString=Re.toDisplayString=Me.prototype.toDisplayString=ke.prototype.toDisplayString=Pe.prototype.toDisplayString=qe.prototype.toDisplayString=Oe.prototype.toDisplayString=Ne.prototype.toDisplayString=Fe.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 Zu(t){return t==="description"||t==="string"||t==="code"}class Ue{constructor(e,r,n){if(!Zu(n))throw new Error("invalid Failure type: "+n);this.pexpr=e,this.text=r,this.type=n,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 Ue(this.pexpr,this.text,this.type);return this.isFluffy()&&e.makeFluffy(),e}toKey(){return this.toString()+"#"+this.type}}z.prototype.toFailure=De("toFailure");Te.toFailure=function(t){return new Ue(this,"any object","description")};Re.toFailure=function(t){return new Ue(this,"end of input","description")};Oe.prototype.toFailure=function(t){return new Ue(this,this.obj,"string")};Ne.prototype.toFailure=function(t){return new Ue(this,JSON.stringify(this.from)+".."+JSON.stringify(this.to),"code")};ke.prototype.toFailure=function(t){const e=this.expr===Te?"nothing":"not "+this.expr.toFailure(t);return new Ue(this,e,"description")};Pe.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 Ue(this,e,"description")};Ee.prototype.toFailure=function(t){return new Ue(this,"a Unicode ["+this.categoryOrProp+"] character","description")};be.prototype.toFailure=function(t){const r="("+this.terms.map(n=>n.toFailure(t)).join(" or ")+")";return new Ue(this,r,"description")};Ae.prototype.toFailure=function(t){const r="("+this.factors.map(n=>n.toFailure(t)).join(" ")+")";return new Ue(this,r,"description")};Me.prototype.toFailure=function(t){const e="("+this.expr.toFailure(t)+this.operator+")";return new Ue(this,e,"description")};z.prototype.toString=De("toString");Te.toString=function(){return"any"};Re.toString=function(){return"end"};Oe.prototype.toString=function(){return JSON.stringify(this.obj)};Ne.prototype.toString=function(){return JSON.stringify(this.from)+".."+JSON.stringify(this.to)};Fe.prototype.toString=function(){return"$"+this.index};qe.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(" ")+")"};Me.prototype.toString=function(){return this.expr+this.operator};ke.prototype.toString=function(){return"~"+this.expr};Pe.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 ei extends z{constructor(e){super(),this.obj=e}_getString(e){const r=e.currentApplication().args[this.obj.index];return It(r instanceof Oe,"expected a Terminal expression"),r.obj}allowsSkippingPrecedingSpace(){return!0}eval(e){const{inputStream:r}=e,n=r.pos,s=this._getString(e);return r.matchString(s,!0)?(e.pushBinding(new Vt(s.length),n),!0):(e.processFailure(n,this),!1)}getArity(){return 1}substituteParams(e){return new ei(this.obj.substituteParams(e))}toDisplayString(){return this.obj.toDisplayString()+" (case-insensitive)"}toFailure(e){return new Ue(this,this.obj.toFailure(e)+" (case-insensitive)","description")}_isNullable(e,r){return this.obj._isNullable(e,r)}}let Io;So(t=>{Io=t.rules.applySyntactic.body});const Wn=new X("spaces");class Ju{constructor(e,r,n){this.matcher=e,this.startExpr=r,this.grammar=e.grammar,this.input=e.getInput(),this.inputStream=new Dn(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=[],n!==void 0&&(this.positionToRecordFailures=n,this.recordedFailures=Object.create(null))}posToOffset(e){return e-this._posStack[this._posStack.length-1]}enterApplication(e,r){this._posStack.push(this.inputStream.pos),this._applicationStack.push(r),this.inLexifiedContextStack.push(!1),e.enter(r),this._rightmostFailurePositionStack.push(this.rightmostFailurePosition),this.rightmostFailurePosition=-1}exitApplication(e,r){const n=this._posStack.pop();this._applicationStack.pop(),this.inLexifiedContextStack.pop(),e.exit(),this.rightmostFailurePosition=Math.max(this.rightmostFailurePosition,this._rightmostFailurePositionStack.pop()),r&&this.pushBinding(r,n)}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(Wn),this.popBinding(),this.popFailuresInfo(),this.inputStream.pos}skipSpacesIfInSyntacticContext(){return this.inSyntacticContext()?this.skipSpaces():this.inputStream.pos}maybeSkipSpacesBefore(e){return e.allowsSkippingPrecedingSpace()&&e!==Wn?this.skipSpacesIfInSyntacticContext():this.inputStream.pos}pushBinding(e,r){this._bindings.push(e),this._bindingOffsets.push(this.posToOffset(r))}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 r=this.memoTable[e];return r||(r=this.memoTable[e]=new Pu),r}processFailure(e,r){if(this.rightmostFailurePosition=Math.max(this.rightmostFailurePosition,e),this.recordedFailures&&e===this.positionToRecordFailures){const n=this.currentApplication();n&&(r=r.substituteParams(n.args)),this.recordFailure(r.toFailure(this.grammar),!1)}}recordFailure(e,r){const n=e.toKey();this.recordedFailures[n]?this.recordedFailures[n].isFluffy()&&!e.isFluffy()&&this.recordedFailures[n].clearFluffy():this.recordedFailures[n]=r?e.clone():e}recordFailures(e,r){Object.keys(e).forEach(n=>{this.recordFailure(e[n],r)})}cloneRecordedFailures(){if(!this.recordedFailures)return;const e=Object.create(null);return Object.keys(this.recordedFailures).forEach(r=>{e[r]=this.recordedFailures[r].clone()}),e}getRightmostFailurePosition(){return this.rightmostFailurePosition}_getRightmostFailureOffset(){return this.rightmostFailurePosition>=0?this.posToOffset(this.rightmostFailurePosition):-1}getMemoizedTraceEntry(e,r){const n=this.memoTable[e];if(n&&r instanceof X){const s=n.memo[r.toMemoKey()];if(s&&s.traceEntry){const i=s.traceEntry.cloneWithExpr(r);return i.isMemoized=!0,i}}return null}getTraceEntry(e,r,n,s){if(r instanceof X){const i=this.currentApplication(),a=i?i.args:[];r=r.substituteParams(a)}return this.getMemoizedTraceEntry(e,r)||new vt(this.input,e,this.inputStream.pos,r,n,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,r){this.trace&&this.trace.push(r.traceEntry);const n=this.inputStream.pos+r.rightmostFailureOffset;return this.rightmostFailurePosition=Math.max(this.rightmostFailurePosition,n),this.recordedFailures&&this.positionToRecordFailures===n&&r.failuresAtRightmostPosition&&this.recordFailures(r.failuresAtRightmostPosition,!0),this.inputStream.examinedLength=Math.max(this.inputStream.examinedLength,r.examinedLength+e),r.value?(this.inputStream.pos+=r.matchLength,this.pushBinding(r.value,e),!0):!1}eval(e){const{inputStream:r}=this,n=this._bindings.length,s=this.userData;let i;this.recordedFailures&&(i=this.recordedFailures,this.recordedFailures=Object.create(null));const a=r.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(n),l=this.getTraceEntry(o,e,u,d);l.isImplicitSpaces=e===Wn,l.isRootNode=e===this.startExpr,c.push(l),this.trace=c}return u?this.recordedFailures&&r.pos===this.positionToRecordFailures&&Object.keys(this.recordedFailures).forEach(d=>{this.recordedFailures[d].makeFluffy()}):(r.pos=a,this.truncateBindings(n),this.userData=s),this.recordedFailures&&this.recordFailures(i,!1),e===Io&&this.skipSpaces(),u}getMatchResult(){this.grammar._setUpMatchState(this),this.eval(this.startExpr);let e;this.recordedFailures&&(e=Object.keys(this.recordedFailures).map(n=>this.recordedFailures[n]));const r=this._bindings[0];return r&&(r.grammar=this.grammar),new _o(this.matcher,this.input,this.startExpr,r,this._bindingOffsets[0],this.rightmostFailurePosition,e)}getTrace(){this.trace=[];const e=this.getMatchResult(),r=this.trace[this.trace.length-1];return r.result=e,r}pushFailuresInfo(){this._rightmostFailurePositionStack.push(this.rightmostFailurePosition),this._recordedFailuresStack.push(this.recordedFailures)}popFailuresInfo(){this.rightmostFailurePosition=this._rightmostFailurePositionStack.pop(),this.recordedFailures=this._recordedFailuresStack.pop()}}class Qu{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,r,n){const s=this._input,i=this._memoTable;if(e<0||e>s.length||r<0||r>s.length||e>r)throw new Error("Invalid indices: "+e+" and "+r);this._input=s.slice(0,e)+n+s.slice(r),this._input!==s&&i.length>0&&(this._isMemoTableStale=!0);const a=i.slice(r);i.length=e;for(let o=0;o<n.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,r={incremental:!0}){return this._match(this._getStartExpr(e),{incremental:r.incremental,tracing:!1})}trace(e,r={incremental:!0}){return this._match(this._getStartExpr(e),{incremental:r.incremental,tracing:!0})}_match(e,r={}){const n={tracing:!1,incremental:!0,positionToRecordFailures:void 0,...r};if(!n.incremental)this._resetMemoTable();else if(this._isMemoTableStale&&!this.grammar.supportsIncrementalParsing)throw vu(this.grammar);const s=new Ju(this,e,n.positionToRecordFailures);return n.tracing?s.getTrace():s.getMatchResult()}_getStartExpr(e){const r=e||this.grammar.defaultStartRule;if(!r)throw new Error("Missing start rule argument -- the grammar has no default start rule.");const n=this.grammar.parseApplication(r);return new Ae([n,Re])}}const hr=[],ms=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);class Di{constructor(e,r,n){this._node=e,this.source=r,this._baseInterval=n,e.isNonterminal()&&It(r===n),this._childWrappers=[]}_forgetMemoizedResultFor(e){delete this._node[this._semantics.attributeKeys[e]],this.children.forEach(r=>{r._forgetMemoizedResultFor(e)})}child(e){if(!(0<=e&&e<this._node.numChildren()))return;let r=this._childWrappers[e];if(!r){const n=this._node.childAt(e),s=this._node.childOffsets[e],i=this._baseInterval.subInterval(s,n.matchLength),a=n.isNonterminal()?i:this._baseInterval;r=this._childWrappers[e]=this._semantics.wrap(n,i,a)}return r}_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 r=e||[],n=r.map(a=>a._node),s=new xo(n,[],-1,!1),i=this._semantics.wrap(s,null,null);return i._childWrappers=r,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 $e{constructor(e,r){const n=this;if(this.grammar=e,this.checkedActionDicts=!1,this.Wrapper=class extends(r?r.Wrapper:Di){constructor(s,i,a){super(s,i,a),n.checkActionDictsIfHaventAlready(),this._semantics=n}toString(){return"[semantics wrapper for "+n.grammar.name+"]"}},this.super=r,r){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:Li(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 r(s){return s.super!==$e.BuiltInSemantics._getSemantics()}let n=`(function(g) {
19
+ `;if(r(this)){n+=" var semantics = "+this.super.toRecipe(!0)+"(g";const s=this.super.grammar;let i=this.grammar;for(;i!==s;)n+=".superGrammar",i=i.superGrammar;n+=`);
20
+ `,n+=" return g.extendSemantics(semantics)"}else n+=" 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;r(this)&&this.super[s.toLowerCase()+"s"][a]?l="extend"+s:l="add"+s,n+=`
21
+ .`+l+"("+JSON.stringify(d)+", {";const f=[];Object.keys(o).forEach(y=>{if(o[y]!==u){let b=o[y].toString().trim();b=b.replace(/^.*\(/,"function("),f.push(`
22
+ `+JSON.stringify(y)+": "+b)}}),n+=f.join(",")+`
23
+ })`})}),n+=`;
24
+ })`,e||(n=`(function() {
25
+ var grammar = this.fromRecipe(`+this.grammar.toRecipe()+`);
26
+ var semantics = `+n+`(grammar);
27
+ return semantics;
28
+ });
29
+ `),n}addOperationOrAttribute(e,r,n){const s=e+"s",i=Mi(r,e),{name:a}=i,{formals:o}=i;this.assertNewName(a,e);const c=Yu(e,a,l),u={_default:c};Object.keys(n).forEach(f=>{u[f]=n[f]});const d=e==="operation"?new Sr(a,o,u,c):new gs(a,u,c);d.checkActionDict(this.grammar),this[s][a]=d;function l(...f){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[T,L]of Object.entries(f)){const k=y.formals[T];b[k]=L}const S=this.args;this.args=b;const j=y.execute(this._semantics,this);return this.args=S,j}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:Li(a)}))}extendOperationOrAttribute(e,r,n){const s=e+"s";if(Mi(r,"attribute"),!(this.super&&r in this.super[s]))throw new Error("Cannot extend "+e+" '"+r+"': did not inherit an "+e+" with that name");if(ms(this[s],r))throw new Error("Cannot extend "+e+" '"+r+"' again");const i=this[s][r].formals,a=this[s][r].actionDict,o=Object.create(a);Object.keys(n).forEach(c=>{o[c]=n[c]}),this[s][r]=e==="operation"?new Sr(r,i,o):new gs(r,o),this[s][r].checkActionDict(this.grammar)}assertNewName(e,r){if(ms(Di.prototype,e))throw new Error("Cannot add "+r+" '"+e+"': that's a reserved name");if(e in this.operations)throw new Error("Cannot add "+r+" '"+e+"': an operation with that name already exists");if(e in this.attributes)throw new Error("Cannot add "+r+" '"+e+"': an attribute with that name already exists")}wrap(e,r,n){const s=n||r;return e instanceof this.Wrapper?e:new this.Wrapper(e,r,s)}}function Mi(t,e){if(!$e.prototypeGrammar)return It(t.indexOf("(")===-1),{name:t,formals:[]};const r=$e.prototypeGrammar.match(t,e==="operation"?"OperationSignature":"AttributeSignature");if(r.failed())throw new Error(r.message);return $e.prototypeGrammarSemantics(r).parse()}function Yu(t,e,r){return function(...n){const i=(this._semantics.operations[e]||this._semantics.attributes[e]).formals.map(a=>this.args[a]);if(!this.isIteration()&&n.length===1)return r.apply(n[0],i);throw Ru(this.ctorName,e,t,hr)}}$e.createSemantics=function(t,e){const r=new $e(t,e!==void 0?e:$e.BuiltInSemantics._getSemantics()),n=function(i){if(!(i instanceof _o))throw new TypeError("Semantics expected a MatchResult, but got "+Zs(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 Dn(i.input);return r.wrap(a,o.interval(i._cstOffset,i.input.length))};return n.addOperation=function(s,i){return r.addOperationOrAttribute("operation",s,i),n},n.extendOperation=function(s,i){return r.extendOperationOrAttribute("operation",s,i),n},n.addAttribute=function(s,i){return r.addOperationOrAttribute("attribute",s,i),n},n.extendAttribute=function(s,i){return r.extendOperationOrAttribute("attribute",s,i),n},n._getActionDict=function(s){const i=r.operations[s]||r.attributes[s];if(!i)throw new Error('"'+s+'" is not a valid operation or attribute name in this semantics for "'+t.name+'"');return i.actionDict},n._remove=function(s){let i;return s in r.operations?(i=r.operations[s],delete r.operations[s]):s in r.attributes&&(i=r.attributes[s],delete r.attributes[s]),delete r.Wrapper.prototype[s],i},n.getOperationNames=function(){return Object.keys(r.operations)},n.getAttributeNames=function(){return Object.keys(r.attributes)},n.getGrammar=function(){return r.grammar},n.toRecipe=function(s){return r.toRecipe(s)},n.toString=r.toString.bind(r),n._getSemantics=function(){return r},n};class Sr{constructor(e,r,n,s){this.name=e,this.formals=r,this.actionDict=n,this.builtInDefault=s}checkActionDict(e){e._checkTopDownActionDict(this.typeName,this.name,this.actionDict)}execute(e,r){try{const{ctorName:n}=r._node;let s=this.actionDict[n];return s?(hr.push([this,n]),s.apply(r,r._children())):r.isNonterminal()&&(s=this.actionDict._nonterminal,s)?(hr.push([this,"_nonterminal",n]),s.apply(r,r._children())):(hr.push([this,"default action",n]),this.actionDict._default.apply(r,r._children()))}finally{hr.pop()}}}Sr.prototype.typeName="operation";class gs extends Sr{constructor(e,r,n){super(e,[],r,n)}execute(e,r){const n=r._node,s=e.attributeKeys[this.name];return ms(n,s)||(n[s]=Sr.prototype.execute.call(this,e,r)),n[s]}}gs.prototype.typeName="attribute";const Pi=["_iter","_terminal","_nonterminal","_default"];function $i(t){return Object.keys(t.rules).sort().map(e=>t.rules[e])}const Xu=t=>t.replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029");let ko,Eo;class Le{constructor(e,r,n,s){if(this.name=e,this.superGrammar=r,this.rules=n,s){if(!(s in n))throw new Error("Invalid start rule: '"+s+"' is not a rule in grammar '"+e+"'");this.defaultStartRule=s}this._matchStateInitializer=void 0,this.supportsIncrementalParsing=!0}matcher(){return new Qu(this)}isBuiltIn(){return this===Le.ProtoBuiltInRules||this===Le.BuiltInRules}equals(e){if(this===e)return!0;if(e==null||this.name!==e.name||this.defaultStartRule!==e.defaultStartRule||!(this.superGrammar===e.superGrammar||this.superGrammar.equals(e.superGrammar)))return!1;const r=$i(this),n=$i(e);return r.length===n.length&&r.every((s,i)=>s.description===n[i].description&&s.formals.join(",")===n[i].formals.join(",")&&s.body.toString()===n[i].body.toString())}match(e,r){const n=this.matcher();return n.replaceInputRange(0,0,e),n.match(r)}trace(e,r){const n=this.matcher();return n.replaceInputRange(0,0,e),n.trace(r)}createSemantics(){return $e.createSemantics(this)}extendSemantics(e){return $e.createSemantics(this,e._getSemantics())}_checkTopDownActionDict(e,r,n){const s=[];for(const i in n){const a=n[i];if(!Pi.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 '${r}' ${e}:`,...i].join(`
30
+ `));throw a.problems=s,a}}_topDownActionArity(e){return Pi.includes(e)?0:this.rules[e].body.getArity()}_inheritsFrom(e){let r=this.superGrammar;for(;r;){if(r.equals(e,!0))return!0;r=r.superGrammar}return!1}toRecipe(e=void 0){const r={};this.source&&(r.source=this.source.contents);let n=null;this.defaultStartRule&&(n=this.defaultStartRule);const s={};Object.keys(this.rules).forEach(o=>{const c=this.rules[o],{body:u}=c,d=!this.superGrammar||!this.superGrammar.rules[o];let l;d?l="define":l=u instanceof Ln?"extend":"override";const f={};if(c.source&&this.source){const S=c.source.relativeTo(this.source);f.sourceInterval=[S.startIdx,S.endIdx]}const y=d?c.description:null,b=u.outputRecipe(c.formals,this.source);s[o]=[l,f,y,c.formals,b]});let i="null";e?i=e:this.superGrammar&&!this.superGrammar.isBuiltIn()&&(i=this.superGrammar.toRecipe());const a=[...["grammar",r,this.name].map(JSON.stringify),i,...[n,s].map(JSON.stringify)];return Xu(`[${a.join(",")}]`)}toOperationActionDictionaryTemplate(){return this._toOperationOrAttributeActionDictionaryTemplate()}toAttributeActionDictionaryTemplate(){return this._toOperationOrAttributeActionDictionaryTemplate()}_toOperationOrAttributeActionDictionaryTemplate(){const e=new Bt;e.append("{");let r=!0;for(const n in this.rules){const{body:s}=this.rules[n];r?r=!1:e.append(","),e.append(`
31
+ `),e.append(" "),this.addSemanticActionTemplate(n,s,e)}return e.append(`
32
+ }`),e.contents()}addSemanticActionTemplate(e,r,n){n.append(e),n.append(": function(");const s=this._topDownActionArity(e);n.append(Fn("_",s).join(", ")),n.append(`) {
33
+ `),n.append(" }")}parseApplication(e){let r;if(e.indexOf("<")===-1)r=new X(e);else{const s=ko.match(e,"Base_application");r=Eo(s,{})}if(!(r.ruleName in this.rules))throw yo(r.ruleName,this.name);const{formals:n}=this.rules[r.ruleName];if(n.length!==r.args.length){const{source:s}=this.rules[r.ruleName];throw bo(r.ruleName,n.length,r.args.length,s)}return r}_setUpMatchState(e){this._matchStateInitializer&&this._matchStateInitializer(e)}}Le.ProtoBuiltInRules=new Le("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 ei(new Fe(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 zt(new X("space")),formals:[]},space:{body:new Ne("\0"," "),formals:[],description:"a space"}});Le.initApplicationParser=function(t,e){ko=t,Eo=e};class qi{constructor(e){this.name=e}sourceInterval(e,r){return this.source.subInterval(e,r-e)}ensureSuperGrammar(){return this.superGrammar||this.withSuperGrammar(this.name==="BuiltInRules"?Le.ProtoBuiltInRules:Le.BuiltInRules),this.superGrammar}ensureSuperGrammarRuleForOverriding(e,r){const n=this.ensureSuperGrammar().rules[e];if(!n)throw wu(e,this.superGrammar.name,r);return n}installOverriddenOrExtendedRule(e,r,n,s){const i=ls(r);if(i.length>0)throw Ri(e,i,s);const a=this.ensureSuperGrammar().rules[e],o=a.formals,c=o?o.length:0;if(r.length!==c)throw bo(e,c,r.length,s);return this.install(e,r,n,a.description,s)}install(e,r,n,s,i,a=!1){return this.rules[e]={body:n.introduceParams(r),formals:r,description:s,source:i,primitive:a},this}withSuperGrammar(e){if(this.superGrammar)throw new Error("the super grammar of a GrammarDecl cannot be set more than once");return this.superGrammar=e,this.rules=Object.create(e.rules),e.isBuiltIn()||(this.defaultStartRule=e.defaultStartRule),this}withDefaultStartRule(e){return this.defaultStartRule=e,this}withSource(e){return this.source=new Dn(e).interval(0,e.length),this}build(){const e=new Le(this.name,this.ensureSuperGrammar(),this.rules,this.defaultStartRule);e._matchStateInitializer=e.superGrammar._matchStateInitializer,e.supportsIncrementalParsing=e.superGrammar.supportsIncrementalParsing;const r=[];let n=!1;return Object.keys(e.rules).forEach(s=>{const{body:i}=e.rules[s];try{i.assertChoicesHaveUniformArity(s)}catch(a){r.push(a)}try{i.assertAllApplicationsAreValid(s,e)}catch(a){r.push(a),n=!0}}),n||Object.keys(e.rules).forEach(s=>{const{body:i}=e.rules[s];try{i.assertIteratedExprsAreNotNullable(e,[])}catch(a){r.push(a)}}),r.length>0&&Nu(r),this.source&&(e.source=this.source),e}define(e,r,n,s,i,a){if(this.ensureSuperGrammar(),this.superGrammar.rules[e])throw Ti(e,this.name,this.superGrammar.name,i);if(this.rules[e])throw Ti(e,this.name,this.name,i);const o=ls(r);if(o.length>0)throw Ri(e,o,i);return this.install(e,r,n,s,i,a)}override(e,r,n,s,i){return this.ensureSuperGrammarRuleForOverriding(e,i),this.installOverriddenOrExtendedRule(e,r,n,i),this}extend(e,r,n,s,i){if(!this.ensureSuperGrammar().rules[e])throw Su(e,this.superGrammar.name,i);const o=new Ln(this.superGrammar,e,n);return o.source=n.source,this.installOverriddenOrExtendedRule(e,r,o,i),this}}class Yr{constructor(e){this.currentDecl=null,this.currentRuleName=null,this.options=e||{}}newGrammar(e){return new qi(e)}grammar(e,r,n,s,i){const a=new qi(r);return n&&a.withSuperGrammar(n instanceof Le?n:this.fromRecipe(n)),s&&a.withDefaultStartRule(s),e&&e.source&&a.withSource(e.source),this.currentDecl=a,Object.keys(i).forEach(o=>{this.currentRuleName=o;const c=i[o],u=c[0],d=c[1],l=c[2],f=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,f,y,l,b)}),this.currentRuleName=this.currentDecl=null,a.build()}terminal(e){return new Oe(e)}range(e,r){return new Ne(e,r)}param(e){return new Fe(e)}alt(...e){let r=[];for(let n of e)n instanceof z||(n=this.fromRecipe(n)),n instanceof be?r=r.concat(n.terms):r.push(n);return r.length===1?r[0]:new be(r)}seq(...e){let r=[];for(let n of e)n instanceof z||(n=this.fromRecipe(n)),n instanceof Ae?r=r.concat(n.factors):r.push(n);return r.length===1?r[0]:new Ae(r)}star(e){return e instanceof z||(e=this.fromRecipe(e)),new zt(e)}plus(e){return e instanceof z||(e=this.fromRecipe(e)),new ar(e)}opt(e){return e instanceof z||(e=this.fromRecipe(e)),new mt(e)}not(e){return e instanceof z||(e=this.fromRecipe(e)),new ke(e)}lookahead(e){return e instanceof z||(e=this.fromRecipe(e)),this.options.eliminateLookaheads?new ke(new ke(e)):new Pe(e)}lex(e){return e instanceof z||(e=this.fromRecipe(e)),new qe(e)}app(e,r){return r&&r.length>0&&(r=r.map(function(n){return n instanceof z?n:this.fromRecipe(n)},this)),new X(e,r)}splice(e,r){return new jn(this.currentDecl.superGrammar,this.currentRuleName,e.map(n=>this.fromRecipe(n)),r.map(n=>this.fromRecipe(n)))}fromRecipe(e){const r=e[0]==="grammar"?e.slice(1):e.slice(2),n=this[e[0]](...r),s=e[1];return s&&s.sourceInterval&&this.currentDecl&&n.withSource(this.currentDecl.sourceInterval(...s.sourceInterval)),n}}function ti(t){return typeof t=="function"?t.call(new Yr):(typeof t=="string"&&(t=JSON.parse(t)),new Yr().fromRecipe(t))}const ri=ti(["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]]}]);Le.BuiltInRules=ri;ju(Le.BuiltInRules);const ni=ti(["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]},"--"]]]}]),Hn=Object.create(z.prototype);function Ui(t,e){for(const r in t)if(r===e)return!0;return!1}function Oo(t,e,r,n){const s=new Yr(n);let i,a,o,c=!1;return(r||ni).createSemantics().addOperation("visit",{Grammars(l){return l.children.map(f=>f.visit())},Grammar(l,f,y,b,S){const j=l.visit();i=s.newGrammar(j),f.child(0)&&f.child(0).visit(),b.children.map(L=>L.visit());const T=i.build();if(T.source=this.source.trimmed(),Ui(e,j))throw bu(T);return e[j]=T,T},SuperGrammar(l,f){const y=f.visit();if(y==="null")i.withSuperGrammar(null);else{if(!e||!Ui(e,y))throw yu(y,e,f.source);i.withSuperGrammar(e[y])}},Rule_define(l,f,y,b,S){a=l.visit(),o=f.children.map(k=>k.visit())[0]||[],!i.defaultStartRule&&i.ensureSuperGrammar()!==Le.ProtoBuiltInRules&&i.withDefaultStartRule(a);const j=S.visit(),T=y.children.map(k=>k.visit())[0],L=this.source.trimmed();return i.define(a,o,j,T,L)},Rule_override(l,f,y,b){a=l.visit(),o=f.children.map(T=>T.visit())[0]||[];const S=this.source.trimmed();i.ensureSuperGrammarRuleForOverriding(a,S),c=!0;const j=b.visit();return c=!1,i.override(a,o,j,null,S)},Rule_extend(l,f,y,b){a=l.visit(),o=f.children.map(T=>T.visit())[0]||[];const S=b.visit(),j=this.source.trimmed();return i.extend(a,o,S,null,j)},RuleBody(l,f){return s.alt(...f.visit()).withSource(this.source)},OverrideRuleBody(l,f){const y=f.visit(),b=y.indexOf(Hn);if(b>=0){const S=y.slice(0,b),j=y.slice(b+1);return j.forEach(T=>{if(T===Hn)throw Ou(T)}),new jn(i.superGrammar,a,S,j).withSource(this.source)}else return s.alt(...y).withSource(this.source)},Formals(l,f,y){return f.visit()},Params(l,f,y){return f.visit()},Alt(l){return s.alt(...l.visit()).withSource(this.source)},TopLevelTerm_inline(l,f){const y=a+"_"+f.visit(),b=l.visit(),S=this.source.trimmed(),j=!(i.superGrammar&&i.superGrammar.rules[y]);c&&!j?i.override(y,o,b,null,S):i.define(y,o,b,null,S);const T=o.map(L=>s.app(L));return s.app(y,T).withSource(b.source)},OverrideTopLevelTerm_superSplice(l){return Hn},Seq(l){return s.seq(...l.children.map(f=>f.visit())).withSource(this.source)},Iter_star(l,f){return s.star(l.visit()).withSource(this.source)},Iter_plus(l,f){return s.plus(l.visit()).withSource(this.source)},Iter_opt(l,f){return s.opt(l.visit()).withSource(this.source)},Pred_not(l,f){return s.not(f.visit()).withSource(this.source)},Pred_lookahead(l,f){return s.lookahead(f.visit()).withSource(this.source)},Lex_lex(l,f){return s.lex(f.visit()).withSource(this.source)},Base_application(l,f){const y=f.children.map(b=>b.visit())[0]||[];return s.app(l.visit(),y).withSource(this.source)},Base_range(l,f,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,f,y){return f.visit()},ruleDescr(l,f,y){return f.visit()},ruleDescrText(l){return this.sourceString.trim()},caseName(l,f,y,b,S){return y.visit()},name(l,f){return this.sourceString},nameFirst(l){},nameRest(l){},terminal(l,f,y){return f.children.map(b=>b.visit()).join("")},oneCharTerminal(l,f,y){return f.visit()},escapeChar(l){try{return po(this.sourceString)}catch(f){throw f instanceof RangeError&&f.message.startsWith("Invalid code point ")?Cu(l):f}},NonemptyListOf(l,f,y){return[l.visit()].concat(y.children.map(b=>b.visit()))},EmptyListOf(){return[]},_terminal(){return this.sourceString}})(t).visit()}const el=ti(["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",[]]]]}]);tl(Le.BuiltInRules);rl(el);function tl(t){const e={empty(){return this.iteration()},nonEmpty(r,n,s){return this.iteration([r].concat(s.children))},self(...r){return this}};$e.BuiltInSemantics=$e.createSemantics(t,null).addOperation("asIteration",{emptyListOf:e.empty,nonemptyListOf:e.nonEmpty,EmptyListOf:e.empty,NonemptyListOf:e.nonEmpty,_iter:e.self})}function rl(t){$e.prototypeGrammarSemantics=t.createSemantics().addOperation("parse",{AttributeSignature(e){return{name:e.parse(),formals:[]}},OperationSignature(e,r){return{name:e.parse(),formals:r.children.map(n=>n.parse())[0]||[]}},Formals(e,r,n){return r.asIteration().children.map(s=>s.parse())},name(e,r){return this.sourceString}}),$e.prototypeGrammar=t}function nl(t){let e=0;const r=[0],n=()=>r[r.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=n(),l=e+u;if(u>d)r.push(u),s[l]=1;else if(u<d){const f=r.length;for(;n()!==u;)r.pop();s[l]=-1*(f-r.length)}e+=o.length}return r.length>1&&(s[e]=1-r.length),s}const Co="an indented block",To="a dedent",Bi=1114112;class sl extends Dn{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),Bi):super.nextCharCode()}nextCodePoint(){return this._indentationAt(this.pos)!==0?(this.examinedLength=Math.max(this.examinedLength,this.pos),Bi):super.nextCodePoint()}}class zi extends z{constructor(e=!0){super(),this.isIndent=e}allowsSkippingPrecedingSpace(){return!0}eval(e){const{inputStream:r}=e,n=e.userData;e.doNotMemoize=!0;const s=r.pos,i=this.isIndent?1:-1;return(n[s]||0)*i>0?(e.userData=Object.create(n),e.userData[s]-=i,e.pushBinding(new Vt(0),s),!0):(e.processFailure(s,this),!1)}getArity(){return 1}_assertAllApplicationsAreValid(e,r){}_isNullable(e,r){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 r=this.isIndent?Co:To;return new Ue(this,r,"description")}}const il=new X("indent"),al=new X("dedent"),ol=new jn(ri,"any",[il,al],[]),cl=new Yr().newGrammar("IndentationSensitive").withSuperGrammar(ri).define("indent",[],new zi(!0),Co,void 0,!0).define("dedent",[],new zi(!1),To,void 0,!0).extend("any",[],ol,"any character",void 0).build();Object.assign(cl,{_matchStateInitializer(t){t.userData=nl(t.input),t.inputStream=new sl(t)},supportsIncrementalParsing:!1});Le.initApplicationParser(ni,Oo);const ul=t=>!!t.constructor&&typeof t.constructor.isBuffer=="function"&&t.constructor.isBuffer(t);function ll(t,e,r){const n=ni.match(t,"Grammars");if(n.failed())throw gu(n);return Oo(n,e,void 0,r)}function dl(t,e,r){const n=hl(t,e,r),s=Object.keys(n);if(s.length===0)throw new Error("Missing grammar definition");if(s.length>1){const a=n[s[1]].source;throw new Error(Qs(a.sourceString,a.startIdx)+"Found more than one grammar definition -- use ohm.grammars() instead.")}return n[s[0]]}function hl(t,e,r){const n=Object.create({});if(typeof t!="string")if(ul(t))t=t.toString();else throw new TypeError("Expected string as first argument, got "+Zs(t));return ll(t,n,r),n}function fl(t,e){return dl(t,e)}const pl=`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
+ `,Ro=fl(pl),No=Ro.createSemantics();No.addOperation("toAST",{RulesFile_versionFirst(t,e,r,n){return{imports:e.children.map(s=>s.toAST()),version:t.children.length>0?t.children[0].toAST():"1",functions:r.children.map(s=>s.toAST()),service:n.toAST()}},RulesFile_importsFirst(t,e,r,n){return{imports:t.children.map(s=>s.toAST()),version:e.toAST(),functions:r.children.map(s=>s.toAST()),service:n.toAST()}},ImportDecl(t,e,r,n,s,i,a,o){return{functions:r.asIteration().children.map(c=>c.sourceString),module:a.toAST().value}},RulesVersion(t,e,r,n){return r.toAST().value},ServiceBlock(t,e,r,n,s,i,a){return{name:e.sourceString,functions:[...n.children.map(o=>o.toAST()),...i.children.map(o=>o.toAST())],match:s.toAST()}},DocumentsMatch(t,e,r,n,s){const{lineNum:i,colNum:a}=t.source.getLineAndColumn();return{...n.toAST(),path:Wi(e.sourceString),loc:{line:i,col:a}}},MatchBody(t){const e=[],r=[],n=[];for(const s of t.children){const i=s.toAST();i._kind==="function"?e.push(i):i._kind==="allow"?r.push(i):i._kind==="match"&&n.push(i)}return{functions:e,allows:r,children:n}},MatchBodyItem(t){return t.toAST()},MatchBlock(t,e,r,n,s){const{functions:i,allows:a,children:o}=n.toAST(),{lineNum:c,colNum:u}=t.source.getLineAndColumn();return{_kind:"match",path:Wi(e.sourceString),functions:i,allows:a,children:o,loc:{line:c,col:u}}},AllowStatement(t,e,r,n,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,r){return[t.toAST(),...r.children.map(n=>n.toAST())]},Operation(t){return t.sourceString},FunctionDef(t,e,r,n,s,i,a,o,c){const{lets:u,expr:d}=o.toAST();return{_kind:"function",name:r.sourceString,parameters:s.toAST(),exported:t.sourceString.trim()==="export",lets:u,body:d}},ParameterList(t){return t.asIteration().children.map(e=>e.sourceString)},FunctionBody(t,e){return{lets:t.children.map(r=>r.toAST()),expr:e.toAST()}},LetBinding(t,e,r,n,s){return{name:e.sourceString,value:n.toAST()}},ReturnStatement(t,e,r){return e.toAST()},Expr(t){return t.toAST()},Ternary_ternary(t,e,r,n,s){return{type:"ternary",condition:t.toAST(),consequent:r.toAST(),alternate:s.toAST()}},LogicalOr_or(t,e,r){return{type:"binaryOp",op:"||",left:t.toAST(),right:r.toAST()}},LogicalAnd_and(t,e,r){return{type:"binaryOp",op:"&&",left:t.toAST(),right:r.toAST()}},InIsExpr_in(t,e,r){return{type:"inExpr",element:t.toAST(),collection:r.toAST()}},InIsExpr_is(t,e,r){return{type:"isExpr",value:t.toAST(),typeName:r.sourceString}},Equality_eq(t,e,r){return{type:"binaryOp",op:"==",left:t.toAST(),right:r.toAST()}},Equality_neq(t,e,r){return{type:"binaryOp",op:"!=",left:t.toAST(),right:r.toAST()}},Comparison_gte(t,e,r){return{type:"binaryOp",op:">=",left:t.toAST(),right:r.toAST()}},Comparison_lte(t,e,r){return{type:"binaryOp",op:"<=",left:t.toAST(),right:r.toAST()}},Comparison_gt(t,e,r){return{type:"binaryOp",op:">",left:t.toAST(),right:r.toAST()}},Comparison_lt(t,e,r){return{type:"binaryOp",op:"<",left:t.toAST(),right:r.toAST()}},Additive_add(t,e,r){return{type:"binaryOp",op:"+",left:t.toAST(),right:r.toAST()}},Additive_sub(t,e,r){return{type:"binaryOp",op:"-",left:t.toAST(),right:r.toAST()}},Multiplicative_mul(t,e,r){return{type:"binaryOp",op:"*",left:t.toAST(),right:r.toAST()}},Multiplicative_div(t,e,r){return{type:"binaryOp",op:"/",left:t.toAST(),right:r.toAST()}},Multiplicative_mod(t,e,r){return{type:"binaryOp",op:"%",left:t.toAST(),right:r.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,r,n,s,i){return{type:"methodCall",object:t.toAST(),method:r.sourceString,args:s.asIteration().children.map(a=>a.toAST())}},PostfixExpr_memberAccess(t,e,r){return{type:"memberAccess",object:t.toAST(),property:r.sourceString}},PostfixExpr_bracketAccess(t,e,r,n){return{type:"bracketAccess",object:t.toAST(),index:r.toAST()}},PostfixExpr_sliceAccess(t,e,r,n,s,i){return{type:"sliceAccess",object:t.toAST(),start:r.toAST(),end:s.toAST()}},Primary_paren(t,e,r){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,r,n){return{type:"functionCall",name:t.sourceString,args:r.asIteration().children.map(s=>s.toAST())}},PathLiteral(t,e,r,n){const s=[e.toAST()];for(const i of n.children)s.push(i.toAST());return{type:"pathLiteral",raw:this.sourceString,segments:s}},PathLitSegment_interpolation(t,e,r){return e.toAST()},PathLitSegment_captureRef(t,e,r){return`{${e.sourceString}}`},PathLitSegment_parenLiteral(t,e,r){return`(${e.sourceString})`},PathLitSegment_literal(t){return t.sourceString},ListLiteral(t,e,r,n){return{type:"listLiteral",elements:e.asIteration().children.map(s=>s.toAST())}},MapLiteral(t,e,r,n){return{type:"mapLiteral",entries:e.asIteration().children.map(s=>s.toAST())}},MapEntry(t,e,r){return{key:t.toAST(),value:r.toAST()}},literal(t){return t.toAST()},number_float(t,e,r){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,r){return{type:"literal",value:Vi(e.sourceString),raw:this.sourceString}},string_double(t,e,r){return{type:"literal",value:Vi(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 Vi(t){let e="";for(let r=0;r<t.length;r++){const n=t[r];if(n!=="\\"||r===t.length-1){e+=n;continue}switch(t[r+1]){case"\\":e+="\\",r++;break;case"'":e+="'",r++;break;case'"':e+='"',r++;break;case"n":e+=`
462
+ `,r++;break;case"r":e+="\r",r++;break;case"t":e+=" ",r++;break;case"/":e+="/",r++;break;default:e+=n}}return e}function Wi(t){const e=[],r=t.split("/").filter(Boolean);for(const n of r)if(n.startsWith("{")&&n.endsWith("}")){const s=n.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:n});return{raw:t,segments:e}}function ml(t,e){const r=t.getRightmostFailurePosition?.()??0,n=t.getExpectedText?.()??"";let s=1,i=-1;for(let u=0;u<r&&u<e.length;u++)e.charCodeAt(u)===10&&(s++,i=u);const a=r-i;let o=e.indexOf(`
463
+ `,r);o===-1&&(o=e.length);const c=e.slice(r,Math.min(o,r+40));return{line:s,column:a,offset:r,expected:n,actual:c,message:t.message??"Parse error"}}function si(t){const e=Xr(t);return e.ok?e.ast:null}function Xr(t){const e=t.trim();if(!e)return{ok:!1,error:{line:1,column:1,offset:0,expected:"",actual:"",message:"Empty rules file"}};const r=Ro.match(e);if(!r.succeeded())return{ok:!1,error:ml(r,e)};const n=No(r).toAST(),s=t.length-t.trimStart().length;let i=0;for(let a=0;a<s;a++)t.charCodeAt(a)===10&&i++;return i>0&&gl(n,i),{ok:!0,ast:n}}function gl(t,e){const r=[t.service.match];for(;r.length>0;){const n=r.pop();n.loc&&(n.loc.line+=e);for(const s of n.allows)s.loc&&(s.loc.line+=e);for(const s of n.children)r.push(s)}}function yl(t){const e=`rules_version = '2';
464
+ service cloud.firestore {
465
+ match /databases/{db}/documents {
466
+ ${t}
467
+ }
468
+ }`,r=si(e);return r?r.service.match.functions:null}const Fo={"||":2,"&&":3,"==":5,"!=":5,">":6,"<":6,">=":6,"<=":6,"+":7,"-":7,"*":8,"/":8,"%":8};function bl(t){switch(t.type){case"ternary":return 1;case"binaryOp":return Fo[t.op]??0;case"inExpr":return 4;case"isExpr":return 4;case"unaryOp":return 9;default:return 100}}function vl(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`${ze(t.object,10)}.${t.property}`;case"methodCall":return`${ze(t.object,10)}.${t.method}(${t.args.map(e=>Ie(e)).join(", ")})`;case"bracketAccess":return`${ze(t.object,10)}[${Ie(t.index)}]`;case"sliceAccess":return`${ze(t.object,10)}[${Ie(t.start)}:${Ie(t.end)}]`;case"binaryOp":{const e=Fo[t.op]??0,r=ze(t.left,e),n=ze(t.right,e+1);return`${r} ${t.op} ${n}`}case"unaryOp":return`${t.op}${ze(t.operand,9)}`;case"ternary":return`${ze(t.condition,2)} ? ${Ie(t.consequent)} : ${Ie(t.alternate)}`;case"inExpr":return`${ze(t.element,5)} in ${ze(t.collection,5)}`;case"isExpr":return`${ze(t.value,5)} is ${t.typeName}`;case"listLiteral":return t.elements.length===0?"[]":`[${t.elements.map(e=>Ie(e)).join(", ")}]`;case"mapLiteral":return t.entries.length===0?"{}":`{${t.entries.map(e=>`${Ie(e.key)}: ${Ie(e.value)}`).join(", ")}}`;case"pathLiteral":return"/"+t.segments.map(e=>typeof e=="string"?e:`$(${Ie(e)})`).join("/");case"functionCall":return`${t.name}(${t.args.map(e=>Ie(e)).join(", ")})`}}function ze(t,e){const r=vl(t);return bl(t)<e?`(${r})`:r}function Ie(t){return ze(t,0)}function Lo(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 _r(t){return" ".repeat(t)}function Vr(t,e){const r=_r(e),n=_r(e+2),s=t.parameters.join(", "),i=[],a=t.exported?"export ":"";i.push(`${r}${a}function ${t.name}(${s}) {`);for(const o of t.lets)i.push(`${n}let ${o.name} = ${Ie(o.value)};`);return i.push(`${n}return ${Ie(t.body)};`),i.push(`${r}}`),i.join(`
469
+ `)}function jo(t,e){const r=_r(e),n=t.operations.join(", ");return`${r}allow ${n}: if ${Ie(t.condition)};`}function Do(t,e=0){const r=_r(e),n=e+2,s=[];s.push(`${r}match ${Lo(t.path)} {`);for(const i of t.functions)s.push(Vr(i,n));for(const i of t.allows)s.push(jo(i,n));for(const i of t.children)s.push(Do(i,n));return s.push(`${r}}`),s.join(`
470
+ `)}function en(t){const e=[];for(const i of t.imports)e.push(`import { ${i.functions.join(", ")} } from '${i.module}';`);e.push(`rules_version = '${t.version}';`);for(const i of t.functions??[])e.push(Vr(i,0));e.push(`service ${t.service.name} {`);for(const i of t.service.functions??[])e.push(Vr(i,2));const r=t.service.match,n=_r(2),s=4;e.push(`${n}match ${Lo(r.path)} {`);for(const i of r.functions)e.push(Vr(i,s));for(const i of r.allows)e.push(jo(i,s));for(const i of r.children)e.push(Do(i,s));return e.push(`${n}}`),e.push("}"),e.push(""),e.join(`
471
+ `)}const Wr=new Set(["get","exists","getAfter","debug"]);function tn(t,e){return t.type!=="binaryOp"||t.op!==e?0:1+tn(t.right,e)}function ys(t){let e={op:"",depth:0};function r(s){if(s.type==="binaryOp"){const i=tn(s,"&&"),a=tn(s,"||");i>e.depth&&(e={op:"&&",depth:i}),a>e.depth&&(e={op:"||",depth:a}),r(s.left),r(s.right)}else n(s)}function n(s){switch(s.type){case"unaryOp":r(s.operand);break;case"methodCall":r(s.object),s.args.forEach(r);break;case"memberAccess":r(s.object);break;case"bracketAccess":r(s.object),r(s.index);break;case"ternary":r(s.condition),r(s.consequent),r(s.alternate);break;case"inExpr":r(s.element),r(s.collection);break;case"isExpr":r(s.value);break;case"listLiteral":s.elements.forEach(r);break;case"mapLiteral":s.entries.forEach(i=>{r(i.key),r(i.value)});break;case"functionCall":s.args.forEach(r);break}}return r(t),e}function ae(t){let e=1;switch(t.type){case"binaryOp":e+=ae(t.left)+ae(t.right);break;case"unaryOp":e+=ae(t.operand);break;case"methodCall":e+=ae(t.object);for(const r of t.args)e+=ae(r);break;case"memberAccess":e+=ae(t.object);break;case"bracketAccess":e+=ae(t.object)+ae(t.index);break;case"ternary":e+=ae(t.condition)+ae(t.consequent)+ae(t.alternate);break;case"inExpr":e+=ae(t.element)+ae(t.collection);break;case"isExpr":e+=ae(t.value);break;case"listLiteral":for(const r of t.elements)e+=ae(r);break;case"mapLiteral":for(const r of t.entries)e+=ae(r.key)+ae(r.value);break;case"functionCall":for(const r of t.args)e+=ae(r);break;case"pathLiteral":for(const r of t.segments)typeof r!="string"&&(e+=ae(r));break}return e}function ie(t){switch(t.type){case"literal":return`L:${t.raw}`;case"identifier":return`I:${t.name}`;case"memberAccess":return`M:${ie(t.object)}.${t.property}`;case"methodCall":return`MC:${ie(t.object)}.${t.method}(${t.args.map(ie).join(",")})`;case"bracketAccess":return`B:${ie(t.object)}[${ie(t.index)}]`;case"binaryOp":return`BO:${ie(t.left)}${t.op}${ie(t.right)}`;case"unaryOp":return`UO:${t.op}${ie(t.operand)}`;case"ternary":return`T:${ie(t.condition)}?${ie(t.consequent)}:${ie(t.alternate)}`;case"inExpr":return`IN:${ie(t.element)}in${ie(t.collection)}`;case"isExpr":return`IS:${ie(t.value)}is${t.typeName}`;case"listLiteral":return`LL:[${t.elements.map(ie).join(",")}]`;case"mapLiteral":return`ML:{${t.entries.map(e=>ie(e.key)+":"+ie(e.value)).join(",")}}`;case"functionCall":return`FC:${t.name}(${t.args.map(ie).join(",")})`;case"pathLiteral":return`PL:${t.raw}`;case"sliceAccess":return`SL:${ie(t.object)}[${ie(t.start)}:${ie(t.end)}]`;default:{const e=t;throw new Error(`expressionFingerprint: unhandled type ${e.type}`)}}}function Mo(t){return t.type==="binaryOp"&&t.op==="&&"?Mo(t.left):t}function Po(t){const e=new Map,r=new Set(t.map(s=>s.name));function n(s){const i=[],a=o=>{switch(o.type){case"functionCall":r.has(o.name)&&!Wr.has(o.name)&&i.push(o.name),o.args.forEach(a);break;case"binaryOp":a(o.left),a(o.right);break;case"unaryOp":a(o.operand);break;case"methodCall":a(o.object),o.args.forEach(a);break;case"memberAccess":a(o.object);break;case"bracketAccess":a(o.object),a(o.index);break;case"ternary":a(o.condition),a(o.consequent),a(o.alternate);break;case"inExpr":a(o.element),a(o.collection);break;case"isExpr":a(o.value);break;case"listLiteral":o.elements.forEach(a);break;case"mapLiteral":o.entries.forEach(c=>{a(c.key),a(c.value)});break}};return a(s),[...new Set(i)]}for(const s of t){const i=[];i.push(...n(s.body));for(const a of s.lets)i.push(...n(a.value));e.set(s.name,[...new Set(i)])}return e}function ii(t,e,r=new Set){if(r.has(t))return 0;r.add(t);const n=e.get(t)||[];if(n.length===0)return 1;let s=0;for(const i of n)s=Math.max(s,ii(i,e,new Set(r)));return 1+s}function $o(t,e,r=new Set){let n=0;const s=i=>{switch(i.type){case"functionCall":if(i.name==="get"||i.name==="exists")n++;else if(e.has(i.name)&&!r.has(i.name)){r.add(i.name);const a=e.get(i.name);s(a.body);for(const o of a.lets)s(o.value)}i.args.forEach(s);break;case"binaryOp":s(i.left),s(i.right);break;case"unaryOp":s(i.operand);break;case"methodCall":s(i.object),i.args.forEach(s);break;case"memberAccess":s(i.object);break;case"bracketAccess":s(i.object),s(i.index);break;case"ternary":s(i.condition),s(i.consequent),s(i.alternate);break;case"inExpr":s(i.element),s(i.collection);break;case"isExpr":s(i.value);break;case"listLiteral":i.elements.forEach(s);break;case"mapLiteral":i.entries.forEach(a=>{s(a.key),s(a.value)});break}};return s(t),n}function wl(t,e){const r=new Map,n=s=>{switch(s.type){case"functionCall":e.has(s.name)&&r.set(s.name,(r.get(s.name)??0)+1),s.args.forEach(n);break;case"binaryOp":n(s.left),n(s.right);break;case"unaryOp":n(s.operand);break;case"methodCall":n(s.object),s.args.forEach(n);break;case"memberAccess":n(s.object);break;case"bracketAccess":n(s.object),n(s.index);break;case"ternary":n(s.condition),n(s.consequent),n(s.alternate);break;case"inExpr":n(s.element),n(s.collection);break;case"isExpr":n(s.value);break;case"listLiteral":s.elements.forEach(n);break;case"mapLiteral":s.entries.forEach(i=>{n(i.key),n(i.value)});break}};return n(t),r}function qo(t,e,r=new Set){if(r.has(t))return!1;r.add(t);const n=e.get(t);if(!n)return!1;const s=i=>{switch(i.type){case"functionCall":return i.name==="get"||i.name==="exists"?!0:e.has(i.name)?qo(i.name,e,r):i.args.some(s);case"binaryOp":return s(i.left)||s(i.right);case"unaryOp":return s(i.operand);case"methodCall":return s(i.object)||i.args.some(s);case"memberAccess":return s(i.object);case"bracketAccess":return s(i.object)||s(i.index);case"ternary":return s(i.condition)||s(i.consequent)||s(i.alternate);case"inExpr":return s(i.element)||s(i.collection);case"isExpr":return s(i.value);case"listLiteral":return i.elements.some(s);case"mapLiteral":return i.entries.some(a=>s(a.key)||s(a.value));default:return!1}};return s(n.body)||n.lets.some(i=>s(i.value))}function bs(t,e,r=new Set){const n=s=>{switch(s.type){case"memberAccess":return s.property==="time"&&s.object.type==="identifier"&&s.object.name==="request"?!0:n(s.object);case"bracketAccess":return s.object.type==="identifier"&&s.object.name==="request"&&s.index.type==="literal"&&s.index.value==="time"?!0:n(s.object)||n(s.index);case"functionCall":if(e.has(s.name)&&!r.has(s.name)){r.add(s.name);const i=e.get(s.name);if(bs(i.body,e,r)||i.lets.some(a=>bs(a.value,e,r)))return!0}return s.args.some(n);case"binaryOp":return n(s.left)||n(s.right);case"unaryOp":return n(s.operand);case"methodCall":return n(s.object)||s.args.some(n);case"ternary":return n(s.condition)||n(s.consequent)||n(s.alternate);case"inExpr":return n(s.element)||n(s.collection);case"isExpr":return n(s.value);case"listLiteral":return s.elements.some(n);case"mapLiteral":return s.entries.some(i=>n(i.key)||n(i.value));default:return!1}};return n(t)}function Uo(t){const e=[...t.functions];for(const r of t.children)e.push(...Uo(r));return e}function Bo(t){const e=[];for(const r of t.allows)e.push({rule:r,path:t.path.raw,matchFunctions:t.functions});for(const r of t.children){const n=Bo(r);for(const s of n)s.matchFunctions=[...t.functions,...s.matchFunctions];e.push(...n)}return e}const Gn={where:"No equivalent in rules — restructure logic instead of filtering a list",filter:"No equivalent in rules — restructure logic instead of filtering a list",find:"No equivalent in rules",findIndex:"No equivalent in rules",map:"No equivalent in rules — lists are not transformable",reduce:"No equivalent in rules",forEach:"No equivalent in rules",every:'Use `list.hasAll([...])` for "all elements present"',some:'Use `list.hasAny([...])` for "any element present"',includes:"Use `x in list` instead of `list.includes(x)`",indexOf:"No equivalent in rules",push:"Lists are immutable in rules",pop:"Lists are immutable in rules",shift:"Lists are immutable in rules",unshift:"Lists are immutable in rules",splice:"Lists are immutable in rules",slice:"No equivalent in rules",sort:"Lists are immutable in rules",reverse:"Lists are immutable in rules",flat:"No equivalent in rules",flatMap:"No equivalent in rules",toLowerCase:"Use `.lower()` instead of `.toLowerCase()`",toUpperCase:"Use `.upper()` instead of `.toUpperCase()`",charAt:'No equivalent in rules — use `.split("")` and index',charCodeAt:"No equivalent in rules",substring:"No `.substring()` — use `.split()` and reassembly",substr:"No `.substr()` — use `.split()` and reassembly",padStart:"No equivalent in rules",padEnd:"No equivalent in rules",trimStart:"Use `.trim()` (trims both ends)",trimEnd:"Use `.trim()` (trims both ends)",toString:"Use the `string(x)` cast instead of `.toString()`"},it={Object:"No `Object` in rules — use `data.keys()` / `data.values()` directly",Array:"No `Array` in rules — test list type with `x is list`",JSON:"No `JSON` in rules — rules cannot parse or serialize JSON",Math:"No `Math` in rules — inline arithmetic or ternaries",Date:"No `Date` in rules — use `request.time` (a Timestamp)",String:"Use lowercase `string(x)` for casting",Number:"Use lowercase `int(x)` or `float(x)` for casting",Boolean:"Use lowercase `bool(x)` for casting",parseInt:"Use `int(x)` instead",parseFloat:"Use `float(x)` instead",isNaN:"No equivalent in rules",isFinite:"No equivalent in rules",Promise:"Rules are synchronous — no Promise support",undefined:"`undefined` does not exist in rules — use `null`"},Sl=[{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"}],_l=new Set(["size","keys","values","lower","upper","trim","hasAll","hasAny","hasOnly","toSet","toUtf8"]),Al=[{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 xl(t){const e=[],r=t.replace(/\/\/[^\n]*/g,"").replace(/\/\*[\s\S]*?\*\//g,"");for(const n of Al)n.pattern.test(r)&&e.push({rule:"INVALID_OPERATOR",severity:"error",message:n.message});return e}function zo(t,e){const r=t.path.raw;for(const n of t.functions){const s={matchPath:r,functionName:n.name};de(n.body,s,e);for(const i of n.lets)de(i.value,s,e)}for(let n=0;n<t.allows.length;n++)de(t.allows[n].condition,{matchPath:r,ruleIndex:n},e);for(const n of t.children)zo(n,e)}function de(t,e,r){switch(r(t,e),t.type){case"binaryOp":de(t.left,e,r),de(t.right,e,r);break;case"unaryOp":de(t.operand,e,r);break;case"methodCall":de(t.object,e,r),t.args.forEach(n=>de(n,e,r));break;case"memberAccess":de(t.object,e,r);break;case"bracketAccess":de(t.object,e,r),de(t.index,e,r);break;case"ternary":de(t.condition,e,r),de(t.consequent,e,r),de(t.alternate,e,r);break;case"inExpr":de(t.element,e,r),de(t.collection,e,r);break;case"isExpr":de(t.value,e,r);break;case"listLiteral":t.elements.forEach(n=>de(n,e,r));break;case"mapLiteral":t.entries.forEach(n=>{de(n.key,e,r),de(n.value,e,r)});break;case"functionCall":t.args.forEach(n=>de(n,e,r));break}}function Il(t){const e=[],r=new Set;function n(s,i,a,o){const c=`${s}|${i}|${a.matchPath||""}|${a.functionName||""}|${a.ruleIndex??""}`;r.has(c)||(r.add(c),e.push(o))}return zo(t.service.match,(s,i)=>{if(s.type==="methodCall"&&Gn[s.method]&&n("HALLUCINATED_METHOD",s.method,i,{rule:"HALLUCINATED_METHOD",severity:"error",message:`\`.${s.method}()\` does not exist in Firestore rules. ${Gn[s.method]}`,location:i,fix:Gn[s.method]}),s.type==="methodCall"&&s.object.type==="identifier"&&it[s.object.name]){const a=s.object.name;n("HALLUCINATED_GLOBAL",`${a}.${s.method}`,i,{rule:"HALLUCINATED_GLOBAL",severity:"error",message:`\`${a}.${s.method}()\` does not exist in Firestore rules. ${it[a]}`,location:i,fix:it[a]})}if(s.type==="functionCall"&&it[s.name]&&n("HALLUCINATED_GLOBAL",s.name,i,{rule:"HALLUCINATED_GLOBAL",severity:"error",message:`\`${s.name}()\` does not exist in Firestore rules. ${it[s.name]}`,location:i,fix:it[s.name]}),s.type==="identifier"&&it[s.name]&&n("HALLUCINATED_GLOBAL",`ref:${s.name}`,i,{rule:"HALLUCINATED_GLOBAL",severity:"error",message:`\`${s.name}\` is not a Firestore rules identifier. ${it[s.name]}`,location:i,fix:it[s.name]}),s.type==="memberAccess"&&s.object.type==="identifier"){const a=s.object.name,o=s.property,c=Sl.find(u=>u.receiver===a&&u.property===o);c&&n("WRONG_CONTEXT_PATH",`${a}.${o}`,i,{rule:"WRONG_CONTEXT_PATH",severity:"error",message:`\`${a}.${o}\` is not a valid Firestore rules path. ${c.suggestion}`,location:i,fix:c.suggestion})}if(s.type==="memberAccess"&&s.property==="length"&&s.object.type==="methodCall"&&n("LENGTH_PROPERTY","",i,{rule:"LENGTH_PROPERTY",severity:"error",message:"`.length` is not a valid property in Firestore rules — use `.size()` (a method, with parentheses).",location:i,fix:"Replace `.length` with `.size()`."}),s.type==="pathLiteral")for(const a of s.segments){if(typeof a!="string")continue;const o=a.match(/^\{([A-Za-z_][A-Za-z0-9_]*)\}$/);if(!o)continue;const c=o[1];n("INVALID_PATH_INTERPOLATION",`${s.raw}|${c}`,i,{rule:"INVALID_PATH_INTERPOLATION",severity:"error",message:`\`{${c}}\` 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 \`{${c}}\` with \`$(${c})\` in path \`${s.raw}\`.`,location:i,fix:`Replace \`{${c}}\` with \`$(${c})\` inside the path argument.`})}s.type==="memberAccess"&&_l.has(s.property)&&(s.object.type==="identifier"&&(s.object.name==="request"||s.object.name==="resource")||s.object.type==="memberAccess"||s.object.type==="methodCall"||s.object.type==="bracketAccess")&&n("METHOD_MISSING_PARENS",s.property,i,{rule:"METHOD_MISSING_PARENS",severity:"warning",message:`\`.${s.property}\` looks like a built-in method called without parentheses. Use \`.${s.property}()\` if you meant to invoke it (otherwise this is a field access).`,location:i,fix:`Add parentheses: \`.${s.property}()\`.`})}),e}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 kl(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 El(t,e){for(const r of t)r.lets.length>ge.LET_LIMIT&&e.push({rule:"LET_LIMIT",severity:"error",message:`Function '${r.name}' has ${r.lets.length} let bindings. Limit is ${ge.LET_LIMIT}.`,location:{functionName:r.name},fix:"Inline some let expressions into the return statement, or split the function."})}function Ol(t,e){for(const r of t){const n=ys(r.body);for(const s of r.lets){const i=ys(s.value);i.depth>n.depth&&(n.depth=i.depth,n.op=i.op)}n.depth>=ge.CHAIN_DEPTH_LIMIT?e.push({rule:"CHAIN_DEPTH",severity:"error",message:`Function '${r.name}' has a ${n.op} chain of depth ${n.depth}. Limit is ${ge.CHAIN_DEPTH_LIMIT}.`,location:{functionName:r.name},fix:"Split into nested groups: 'a && b && c && d' → '(a && b) && (c && d)' to halve chain depth."}):n.depth>=ge.CHAIN_DEPTH_ERROR?e.push({rule:"CHAIN_DEPTH",severity:"error",message:`Function '${r.name}' has a ${n.op} chain of depth ${n.depth}. Limit is ${ge.CHAIN_DEPTH_LIMIT}. Approaching failure.`,location:{functionName:r.name},fix:"Split the chain into nested groups to reduce depth."}):n.depth>=ge.CHAIN_DEPTH_WARN&&e.push({rule:"CHAIN_DEPTH",severity:"warning",message:`Function '${r.name}' has a ${n.op} chain of depth ${n.depth}. Limit is ${ge.CHAIN_DEPTH_LIMIT}.`,location:{functionName:r.name}})}}function Cl(t,e){const r=new Map;for(let n=0;n<t.length;n++){const s=t[n];if(!s.rule.operations.some(o=>o==="update"||o==="write"))continue;const i=ie(Mo(s.rule.condition)),a=s.path;r.has(a)||r.set(a,[]),r.get(a).push({index:n,gate:i,ops:s.rule.operations})}for(const[n,s]of r){const i=new Map;for(const a of s)i.has(a.gate)||i.set(a.gate,[]),i.get(a.gate).push(a.index);for(const[a,o]of i)o.length>=2&&e.push({rule:"SHARED_GATE",severity:"warning",message:`${o.length} allow rules in '${n}' share the same gate expression. This may cause cross-rule budget exhaustion. Rules: ${o.join(", ")}.`,location:{matchPath:n},fix:"Assign unique moveType or discriminator values so each rule has a unique first expression."})}}function Tl(t,e){let r=ae(t);const n=new Set;function s(i){if(i.type==="functionCall"&&e.has(i.name)&&!n.has(i.name)){n.add(i.name);const a=e.get(i.name);r+=ae(a.body);for(const o of a.lets)r+=ae(o.value);s(a.body);for(const o of a.lets)s(o.value)}switch(i.type){case"binaryOp":s(i.left),s(i.right);break;case"unaryOp":s(i.operand);break;case"methodCall":s(i.object),i.args.forEach(s);break;case"memberAccess":s(i.object);break;case"bracketAccess":s(i.object),s(i.index);break;case"ternary":s(i.condition),s(i.consequent),s(i.alternate);break;case"inExpr":s(i.element),s(i.collection);break;case"isExpr":s(i.value);break;case"listLiteral":i.elements.forEach(s);break;case"mapLiteral":i.entries.forEach(a=>{s(a.key),s(a.value)});break;case"functionCall":i.args.forEach(s);break}}return s(t),{totalExprs:r,callCount:n.size}}function Rl(t,e,r){const n=new Map;for(const s of e)n.set(s.name,s);for(let s=0;s<t.length;s++){const{totalExprs:i,callCount:a}=Tl(t[s].rule.condition,n),o=tn(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&&r.push({rule:"EXPRESSION_BUDGET",severity:"warning",message:`Rule #${s} has ~${i} expression nodes across ${a} function calls. Runtime budget is non-deterministic; actual evaluation depends on short-circuit behavior.`,location:{ruleIndex:s},fix:"If this rule fails at runtime (403), reduce function calls or expression count."})}}function Nl(t,e,r){const n=Po(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=ii(c.name,n);u>a&&(a=u)}switch(c.type){case"binaryOp":o(c.left),o(c.right);break;case"unaryOp":o(c.operand);break;case"methodCall":o(c.object),c.args.forEach(o);break;case"memberAccess":o(c.object);break;case"bracketAccess":o(c.object),o(c.index);break;case"ternary":o(c.condition),o(c.consequent),o(c.alternate);break;case"inExpr":o(c.element),o(c.collection);break;case"functionCall":c.args.forEach(o);break}};o(t[i].rule.condition),a>=ge.CALL_DEPTH_ERROR?r.push({rule:"CALL_DEPTH",severity:"error",message:`Rule #${i} has a function call chain of depth ${a}. May exceed call budget.`,location:{ruleIndex:i},fix:"Inline intermediate functions to reduce call depth."}):a>=ge.CALL_DEPTH_WARN&&r.push({rule:"CALL_DEPTH",severity:"warning",message:`Rule #${i} has a function call chain of depth ${a}.`,location:{ruleIndex:i}})}}function Fl(t,e,r){const n=new Map;for(const s of e)n.set(s.name,s);for(let s=0;s<t.length;s++){const i=$o(t[s].rule.condition,n);i>=ge.GET_COUNT_ERROR?r.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&&r.push({rule:"GET_COUNT",severity:"warning",message:`Rule #${s} invokes ${i} get()/exists() calls. Limit is ${ge.GET_COUNT_ERROR}.`,location:{ruleIndex:s}})}}function Ll(t,e,r){const n=new Map;for(const i of e)n.set(i.name,i);const s=new Set(e.map(i=>i.name));for(let i=0;i<t.length;i++){const a=wl(t[i].rule.condition,s);for(const[o,c]of a)c>=2&&qo(o,n)&&r.push({rule:"GET_DUPLICATION",severity:"warning",message:`Function '${o}' (contains get/exists) is called ${c} times in rule #${i}. Cache the result with a let binding in a wrapper function to reduce get() calls from ${c} to 1.`,location:{ruleIndex:i},fix:`Create a wrapper: function verifyAll(ret) { let c = ${o}(); return verify1(ret, c) && verify2(ret, c) && ...; }`})}}function jl(t,e,r,n){const s=new Map;for(const o of e)s.set(o.name,o);const i=new Set;for(let o=0;o<t.length;o++)bs(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 f=u[l];if(!(f.startsWith("{")&&f.endsWith("}"))&&f!==d[l])return!1}return!0}for(const o of r)if(!o.requestTime)for(const c of i)a(t[c].path,o.path)&&n.push({rule:"REQUEST_TIME_NOT_PINNED",severity:"warning",message:`Test case "${o.description}" targets rule #${c} (path '${t[c].path}') which reads request.time, but does not set requestTime. Result is non-deterministic across runs.`,location:{ruleIndex:c,matchPath:t[c].path,testCaseDescription:o.description},fix:"Set requestTime on this TestCase to an ISO-8601 timestamp so the rule evaluates deterministically."})}function gr(t){if(t.type==="literal"&&typeof t.value=="boolean")return t.value;if(t.type==="binaryOp"){const e=gr(t.left),r=gr(t.right);if(t.op==="&&")return e===!1||r===!1?!1:e===!0&&r===!0?!0:null;if(t.op==="||")return e===!0||r===!0?!0:e===!1&&r===!1?!1:null}if(t.type==="unaryOp"&&t.op==="!"){const e=gr(t.operand);return e===null?null:!e}return null}const Dl=new Set(["write","create","update","delete"]);function Ml(t,e){for(let r=0;r<t.length;r++){const n=t[r];if(gr(n.rule.condition)!==!0||!n.rule.operations.some(a=>Dl.has(a)))continue;const i=n.rule.operations.join(", ");e.push({rule:"PERMISSIVE_RULE",severity:"warning",message:`allow ${i} at ${n.path} resolves to a constant true predicate — this disables write security for the matched paths. If you reached for \`if true\` to escape a denial you don't understand, narrow the predicate to the specific request shape instead (auth identity, affected fields via diff, status transitions).`,location:{ruleIndex:r,matchPath:n.path},fix:"Replace the always-true predicate with a request-shape check (e.g. request.auth != null && request.resource.data.ownerId == request.auth.uid)."})}}function Vo(t,e){if(t.path.segments.some(n=>n.type==="recursive"))for(let n=0;n<t.allows.length;n++)gr(t.allows[n].condition)===!0&&e.push({rule:"RECURSIVE_WILDCARD_OPEN",severity:"error",message:`Recursive wildcard match (${t.path.raw}) with an always-true predicate exposes every document under this prefix. This is the Firebase open-rules anti-pattern — never ship it.`,location:{ruleIndex:n,matchPath:t.path.raw},fix:"Either narrow the match path to specific collections, or replace `if true` with a real predicate (auth identity, ownership, role)."});for(const n of t.children)Vo(n,e)}function Pl(t){return t.type==="literal"?t.value??"":t.type==="wildcard"?"{*}":t.type==="recursive"?"{**}":""}function $l(t){return t.map(Pl).join("/")}function vs(t,e){const r=$l(t.path.segments),n=e?`${e}/${r}`:r,s=[{block:t,normalizedPath:n}];for(const i of t.children)s.push(...vs(i,n));return s}function ne(t){switch(t.type){case"literal":return t.raw;case"identifier":return t.name;case"memberAccess":return`${ne(t.object)}.${t.property}`;case"methodCall":return`${ne(t.object)}.${t.method}(${t.args.map(ne).join(",")})`;case"bracketAccess":return`${ne(t.object)}[${ne(t.index)}]`;case"sliceAccess":return`${ne(t.object)}[${ne(t.start)}:${ne(t.end)}]`;case"binaryOp":return`(${ne(t.left)}${t.op}${ne(t.right)})`;case"unaryOp":return`(${t.op}${ne(t.operand)})`;case"ternary":return`(${ne(t.condition)}?${ne(t.consequent)}:${ne(t.alternate)})`;case"inExpr":return`(${ne(t.element)} in ${ne(t.collection)})`;case"isExpr":return`(${ne(t.value)} is ${t.typeName})`;case"listLiteral":return`[${t.elements.map(ne).join(",")}]`;case"mapLiteral":return`{${t.entries.map(e=>`${ne(e.key)}:${ne(e.value)}`).join(",")}}`;case"pathLiteral":return t.raw;case"functionCall":return`${t.name}(${t.args.map(ne).join(",")})`}}function rn(t){return t.type==="binaryOp"&&t.op==="&&"?[...rn(t.left),...rn(t.right)]:[t]}function ql(t,e,r){const n=vs(t,""),s=vs(e,""),i=new Map;for(const{block:a,normalizedPath:o}of n)i.has(o)||i.set(o,a);for(const{block:a,normalizedPath:o}of s){const c=i.get(o);if(!c){a.allows.length>0&&r.push({rule:"RULES_WEAKENED",severity:"warning",message:`Match block removed: ${o}`,location:{matchPath:o}});continue}for(const u of a.allows){const d=[...u.operations].sort().join(","),l=c.allows.find(S=>[...S.operations].sort().join(",")===d),f=u.operations.join(", ");if(!l){r.push({rule:"RULES_WEAKENED",severity:"warning",message:`Allow rule removed: ${o} allow ${f}`,location:{matchPath:o}});continue}const y=rn(u.condition).map(ne),b=new Set(rn(l.condition).map(ne));for(const S of y)b.has(S)||r.push({rule:"RULES_WEAKENED",severity:"warning",message:`Predicate removed from ${o} allow ${f}: ${S}`,location:{matchPath:o}})}}}function ws(t,e={}){const r=[];r.push(...xl(t)),kl(t,r);const n=Xr(t);if(!n.ok)return{warnings:r,metrics:{sourceSize:t.length,functionCount:0,allowRuleCount:0,maxChainDepth:0,maxChainOp:"",maxLetBindings:0,maxLetBindingsFunction:"",maxCallDepth:0,maxEstimatedExpressions:0,getCallCount:0},parseError:n.error};const s=n.ast,i=Uo(s.service.match),a=Bo(s.service.match);if(Ol(i,r),El(i,r),Cl(a,r),Rl(a,i,r),Nl(a,i,r),Fl(a,i,r),Ll(a,i,r),r.push(...Il(s)),Ml(a,r),Vo(s.service.match,r),e.testCases&&e.testCases.length>0&&jl(a,i,e.testCases,r),e.previousSource){const b=Xr(e.previousSource);b.ok&&ql(s.service.match,b.ast.service.match,r)}let o={depth:0,op:""},c={count:0,fn:""};for(const b of i){const S=ys(b.body);S.depth>o.depth&&(o={depth:S.depth,op:S.op}),b.lets.length>c.count&&(c={count:b.lets.length,fn:b.name})}const u=Po(i);let d=0;for(const b of i){const S=ii(b.name,u);S>d&&(d=S)}const l=new Map;for(const b of i)l.set(b.name,b);let f=0,y=0;for(const b of a){const S=$o(b.rule.condition,l);S>y&&(y=S)}return{warnings:r,metrics:{sourceSize:t.length,functionCount:i.length,allowRuleCount:a.length,maxChainDepth:o.depth,maxChainOp:o.op,maxLetBindings:c.count,maxLetBindingsFunction:c.fn,maxCallDepth:d,maxEstimatedExpressions:f,getCallCount:y}}}const ue=Symbol.for("pyric.RulesValue.NO_OP");class te{field(e){return null}callMethod(e,r){return ue}binaryOp(e,r){return ue}}function ye(t,e){if(Object.is(t,e))return!0;if(t instanceof te)return t.equals(e);if(e instanceof te)return e.equals(t);if(t instanceof fe||e instanceof fe)return t instanceof fe&&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(!Hi(t)||!Hi(e))return!1;const r=Object.keys(t),n=Object.keys(e);return r.length!==n.length?!1:r.every(s=>s in e&&ye(t[s],e[s]))}function Hi(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}class fe{items;constructor(e){this.items=[];for(const r of e)this.items.some(n=>ye(n,r))||this.items.push(r)}hasOnly(e){const r=e instanceof fe?e.toArray():e;return this.items.every(n=>r.some(s=>ye(n,s)))}equals(e){return!(e instanceof fe)||e.items.length!==this.items.length?!1:this.items.every(r=>e.items.some(n=>ye(r,n)))}hasAll(e){const r=e instanceof fe?e.toArray():e;for(const n of r)if(!this.items.some(s=>ye(s,n)))return!1;return!0}hasAny(e){const r=e instanceof fe?e.toArray():e;for(const n of r)if(this.items.some(s=>ye(s,n)))return!0;return!1}size(){return this.items.length}toArray(){return[...this.items]}difference(e){const r=e.toArray(),n=[];for(const s of this.items)r.some(i=>ye(s,i))||n.push(s);return new fe(n)}union(e){const r=e.toArray();return new fe([...this.items,...r])}intersection(e){const r=e.toArray(),n=[];for(const s of this.items)r.some(i=>ye(s,i))&&n.push(s);return new fe(n)}}class yr{before;after;constructor(e,r){this.before=e,this.after=r}addedKeys(){const e=[];for(const r of Object.keys(this.after))r in this.before||e.push(r);return new fe(e)}removedKeys(){const e=[];for(const r of Object.keys(this.before))r in this.after||e.push(r);return new fe(e)}changedKeys(){const e=[];for(const r of Object.keys(this.after))r in this.before&&!ye(this.before[r],this.after[r])&&e.push(r);return new fe(e)}affectedKeys(){const e=[],r=new Set([...Object.keys(this.before),...Object.keys(this.after)]);for(const n of r)(!(n in this.before)||!(n in this.after)||!ye(this.before[n],this.after[n]))&&e.push(n);return new fe(e)}unchangedKeys(){const e=[];for(const r of Object.keys(this.before))r in this.after&&ye(this.before[r],this.after[r])&&e.push(r);return new fe(e)}}const Ul=/^\{([A-Za-z_][A-Za-z0-9_]*)\}$/;class Xe extends te{typeName="path";segments;bindings;constructor(e,r={}){super(),this.segments=e,this.bindings=r}static fromString(e){const r=e.startsWith("/")?e.slice(1):e;return r.length===0?new Xe([]):new Xe(r.split("/"))}bind(e){const r=[],n={...this.bindings};for(const s of this.segments){const i=s.match(Ul);if(!i){r.push(s);continue}const a=i[1];if(a in e){const o=e[a];if(o==null)throw new TypeError(`Path.bind(): binding '${a}' must not be null`);const c=String(o);r.push(c),n[a]=c}else r.push(s)}return new Xe(r,n)}valueOf(){return NaN}toString(){return"/"+this.segments.join("/")}toJSON(){return{__type:"path",segments:[...this.segments]}}equals(e){if(!(e instanceof Xe)||this.segments.length!==e.segments.length)return!1;for(let r=0;r<this.segments.length;r++)if(this.segments[r]!==e.segments[r])return!1;return!0}field(e){if(/^\d+$/.test(e)){const r=Number(e);return r<0||r>=this.segments.length?null:this.segments[r]}return e in this.bindings?this.bindings[e]:null}callMethod(e,r){switch(e){case"bind":{const n=r[0];if(n==null||typeof n!="object"||Array.isArray(n)||n instanceof te)throw new TypeError(`Path.bind() requires a Map argument, got ${n===null?"null":typeof n}`);return this.bind(n)}default:return ue}}}class oe extends te{typeName="float";value;constructor(e){super(),this.value=e}valueOf(){return this.value}toString(){return Number.isInteger(this.value)?`${this.value}.0`:String(this.value)}toJSON(){return{__type:"float",value:this.value}}equals(e){return e instanceof oe?this.value===e.value:typeof e=="number"?this.value===e:!1}binaryOp(e,r){const n=r instanceof oe?r.value:typeof r=="number"?r:void 0;if(n===void 0)return ue;const s=this.value;switch(e){case"+":return new oe(s+n);case"-":return new oe(s-n);case"*":return new oe(s*n);case"/":return new oe(s/n);case"%":return new oe(s%n);case"<":return s<n;case"<=":return s<=n;case">":return s>n;case">=":return s>=n;default:return ue}}}class G extends Error{expr;constructor(e,r){super(e),this.expr=r,this.name="EvalError"}}class Je extends G{constructor(e,r){super(e,r),this.name="UnsupportedError"}}class Bl{entries=[];parents=[];frames=[];capture(e,r){const n=this.entries.length,s=this.parents.length>0?this.parents[this.parents.length-1]:null,i={source:Ie(e),kind:e.type,parent:s};this.stampFrame(i),this.entries.push(i),this.parents.push(n);try{const a=r();return this.entries[n].value=a,a}catch(a){throw this.entries[n].error=a instanceof Error?a.message:String(a),a}finally{this.parents.pop()}}skip(e){const r=this.parents.length>0?this.parents[this.parents.length-1]:null,n={source:Ie(e),kind:e.type,parent:r,skipped:!0};this.stampFrame(n),this.entries.push(n)}enterFrame(e){this.frames.push(e)}exitFrame(){this.frames.pop()}markEntryAsLetBinding(e,r){e<0||e>=this.entries.length||(this.entries[e].letBinding={name:r})}stampFrame(e){this.frames.length!==0&&(e.inlinedFrom={name:this.frames[this.frames.length-1]})}}function zl(t,e,r,n){const i=f=>f*Math.PI/180,a=i(t),o=i(r),c=i(r-t),u=i(n-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 rt extends te{typeName="latlng";lat;lng;constructor(e,r){super(),this.lat=e,this.lng=r}valueOf(){return NaN}toString(){return`${this.lat},${this.lng}`}toJSON(){return{__type:"latlng",lat:this.lat,lng:this.lng}}equals(e){return e instanceof rt&&this.lat===e.lat&&this.lng===e.lng}callMethod(e,r){switch(e){case"latitude":return this.lat;case"longitude":return this.lng;case"distance":{const n=r[0];if(!(n instanceof rt))throw new TypeError(`latlng.distance() requires a LatLng argument, got ${typeof n}`);return zl(this.lat,this.lng,n.lat,n.lng)}default:return ue}}}const Yt=1e9,Gi={w:10080*60,d:1440*60,h:3600,m:60,s:1};function Vl(t,e){let r=t+Math.trunc(e/Yt),n=e%Yt;return r>0&&n<0?(r-=1,n+=Yt):r<0&&n>0&&(r+=1,n-=Yt),{seconds:r,nanos:n}}class we extends te{typeName="duration";seconds;nanos;constructor(e,r){super();const n=Vl(e,r);this.seconds=n.seconds,this.nanos=n.nanos}static fromValue(e,r){if(r in Gi)return new we(e*Gi[r],0);if(r==="ms"){const n=Math.trunc(e/1e3),s=e-n*1e3;return new we(n,s*1e6)}if(r==="ns"){const n=Math.trunc(e/Yt),s=e-n*Yt;return new we(n,s)}throw new Error(`Unknown duration unit '${r}' (expected one of: w, d, h, m, s, ms, ns)`)}static fromTime(e,r,n,s){return new we(e*3600+r*60+n,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,r=Math.abs(this.seconds),n=Math.abs(this.nanos);return`${e?"-":""}${r}.${n.toString().padStart(9,"0")}s`}toJSON(){return{__type:"duration",seconds:this.seconds,nanos:this.nanos}}equals(e){return e instanceof we&&this.seconds===e.seconds&&this.nanos===e.nanos}callMethod(e,r){switch(e){case"seconds":return this.seconds;case"nanos":return this.nanos;default:return ue}}binaryOp(e,r){if(!(r instanceof we))return ue;switch(e){case"+":return new we(this.seconds+r.seconds,this.nanos+r.nanos);case"-":return new we(this.seconds-r.seconds,this.nanos-r.nanos);case"<":return this.compareTo(r)<0;case"<=":return this.compareTo(r)<=0;case">":return this.compareTo(r)>0;case">=":return this.compareTo(r)>=0;default:return ue}}compareTo(e){return this.seconds!==e.seconds?this.seconds-e.seconds:this.nanos-e.nanos}}const Ki=1e9,Wl=864e5,Kn=86400;function Hl(t,e){const r=Math.floor(e/Ki);return{seconds:t+r,nanos:e-r*Ki}}let xe=class ot extends te{typeName="timestamp";seconds;nanos;constructor(e,r){super();const n=Hl(e,r);this.seconds=n.seconds,this.nanos=n.nanos}static fromMillis(e){const r=Math.floor(e/1e3),n=e-r*1e3;return new ot(r,n*1e6)}static fromYMD(e,r,n){return ot.fromMillis(Date.UTC(e,r-1,n))}static fromIsoString(e){return ot.fromMillis(Date.parse(e))}toMillis(){return this.seconds*1e3+Math.floor(this.nanos/1e6)}toDate(){return new Date(this.toMillis())}valueOf(){return this.toMillis()}toString(){const e=new Date(this.toMillis()).toISOString(),r=this.nanos.toString().padStart(9,"0");return e.replace(/\.\d{3}Z$/,`.${r}Z`)}toJSON(){return{__type:"timestamp",seconds:this.seconds,nanos:this.nanos}}equals(e){return e instanceof ot&&this.seconds===e.seconds&&this.nanos===e.nanos}callMethod(e,r){switch(e){case"seconds":return this.seconds;case"nanos":return this.nanos;case"toMillis":return this.toMillis();case"year":return this.asDate().getUTCFullYear();case"month":return this.asDate().getUTCMonth()+1;case"day":return this.asDate().getUTCDate();case"hours":return this.asDate().getUTCHours();case"minutes":return this.asDate().getUTCMinutes();case"dayOfWeek":{const n=this.asDate().getUTCDay();return n===0?7:n}case"dayOfYear":{const n=this.asDate(),s=Date.UTC(n.getUTCFullYear(),0,1);return Math.floor((this.toMillis()-s)/Wl)+1}case"date":return ot.fromYMD(this.asDate().getUTCFullYear(),this.asDate().getUTCMonth()+1,this.asDate().getUTCDate());case"time":{const n=(this.seconds%Kn+Kn)%Kn,s=Math.floor(n/3600),i=Math.floor(n%3600/60),a=n%60;return we.fromTime(s,i,a,this.nanos)}default:return ue}}asDate(){return new Date(this.toMillis())}binaryOp(e,r){if(r instanceof ot)switch(e){case"-":return new we(this.seconds-r.seconds,this.nanos-r.nanos);case"<":return this.compareTo(r)<0;case"<=":return this.compareTo(r)<=0;case">":return this.compareTo(r)>0;case">=":return this.compareTo(r)>=0;default:return ue}if(r instanceof we)switch(e){case"+":return new ot(this.seconds+r.seconds,this.nanos+r.nanos);case"-":return new ot(this.seconds-r.seconds,this.nanos-r.nanos);default:return ue}return ue}compareTo(e){return this.seconds!==e.seconds?this.seconds-e.seconds:this.nanos-e.nanos}};const Zi="0123456789ABCDEF";function Gl(t){let e="";for(let r=0;r<t.length;r++){const n=t[r];e+=Zi[n>>>4]+Zi[n&15]}return e}function Kl(t){let e="";for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_")}function Zl(t,e){const r=Math.min(t.length,e.length);for(let n=0;n<r;n++)if(t[n]!==e[n])return t[n]<e[n]?-1:1;return t.length===e.length?0:t.length<e.length?-1:1}let Be=class fr extends te{typeName="bytes";data;constructor(e){super(),this.data=e}static fromUtf8(e){return new fr(new TextEncoder().encode(e))}static fromHex(e){if(e.length%2!==0)throw new Error(`Invalid hex string length: ${e.length}`);const r=new Uint8Array(e.length/2);for(let n=0;n<r.length;n++)r[n]=parseInt(e.substr(n*2,2),16);return new fr(r)}size(){return this.data.length}toBase64(){return Kl(this.data)}toHexString(){return Gl(this.data)}valueOf(){return this.data.length}toString(){return this.toBase64()}toJSON(){return{__type:"bytes",base64:this.toBase64()}}equals(e){if(!(e instanceof fr)||this.data.length!==e.data.length)return!1;for(let r=0;r<this.data.length;r++)if(this.data[r]!==e.data[r])return!1;return!0}callMethod(e,r){switch(e){case"size":return this.size();case"toBase64":return this.toBase64();case"toHexString":return this.toHexString()}return ue}binaryOp(e,r){if(!(r instanceof fr))return ue;const n=Zl(this.data,r.data);switch(e){case"<":return n<0;case"<=":return n<=0;case">":return n>0;case">=":return n>=0}return ue}};function br(t){return t.replace(/\$\(database\)/g,"(default)").replace(/^\/databases\/\(default\)\/documents\//,"")}function Ss(t,e){const r=t.split("/").filter(Boolean);return{data:e,id:r.at(-1)??"",__name__:new Xe(["databases","(default)","documents",...r])}}function Ji(t,e){const r=br(t);let n=e.mockDocuments.get(r);if(!n&&e.getDoc){const s=e.getDoc(r);s&&(e.mockDocuments.set(r,s),n=s)}if(n)return e.identitylessFunctionMocks?.has(r)?{data:n}:Ss(r,n);throw new G(`get() of non-existent document '${r}' (guard with exists() first)`)}function Qi(t,e){const r=br(t);if(e.mockDocuments.has(r))return!0;if(e.getDoc){const n=e.getDoc(r);if(n)return e.mockDocuments.set(r,n),!0}return!1}var Zn={exports:{}};const Jl={},Ql=Object.freeze(Object.defineProperty({__proto__:null,default:Jl},Symbol.toStringTag,{value:"Module"})),nn=pu(Ql);/**
472
+ * [js-md5]{@link https://github.com/emn178/js-md5}
473
+ *
474
+ * @namespace md5
475
+ * @version 0.8.3
476
+ * @author Chen, Yi-Cyuan [emn178@gmail.com]
477
+ * @copyright Chen, Yi-Cyuan 2014-2023
478
+ * @license MIT
479
+ */var Yi;function Yl(){return Yi||(Yi=1,(function(t){(function(){var e="input is invalid type",r="finalize already called",n=typeof window=="object",s=n?window:{};s.JS_MD5_NO_WINDOW&&(n=!1);var i=!n&&typeof self=="object",a=!s.JS_MD5_NO_NODE_JS&&typeof process=="object"&&process.versions&&process.versions.node;a?s=oo: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],f=["hex","array","digest","buffer","arrayBuffer","base64"],y="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),b=[],S;if(c){var j=new ArrayBuffer(68);S=new Uint8Array(j),b=new Uint32Array(j)}var T=Array.isArray;(s.JS_MD5_NO_NODE_JS||!T)&&(T=function(h){return Object.prototype.toString.call(h)==="[object Array]"});var L=ArrayBuffer.isView;c&&(s.JS_MD5_NO_ARRAY_BUFFER_IS_VIEW||!L)&&(L=function(h){return typeof h=="object"&&h.buffer&&h.buffer.constructor===ArrayBuffer});var k=function(h){var p=typeof h;if(p==="string")return[h,!0];if(p!=="object"||h===null)throw new Error(e);if(c&&h.constructor===ArrayBuffer)return[new Uint8Array(h),!1];if(!T(h)&&!L(h))throw new Error(e);return[h,!1]},$=function(h){return function(p){return new v(!0).update(p)[h]()}},V=function(){var h=$("hex");a&&(h=w(h)),h.create=function(){return new v},h.update=function(m){return h.create().update(m)};for(var p=0;p<f.length;++p){var g=f[p];h[g]=$(g)}return h},w=function(h){var p=nn,g=nn.Buffer,m;g.from&&!s.JS_MD5_NO_BUFFER_FROM?m=g.from:m=function(E){return new g(E)};var D=function(E){if(typeof E=="string")return p.createHash("md5").update(E,"utf8").digest("hex");if(E==null)throw new Error(e);return E.constructor===ArrayBuffer&&(E=new Uint8Array(E)),T(E)||L(E)||E.constructor===g?p.createHash("md5").update(m(E)).digest("hex"):h(E)};return D},x=function(h){return function(p,g){return new O(p,!0).update(g)[h]()}},_=function(){var h=x("hex");h.create=function(m){return new O(m)},h.update=function(m,D){return h.create(m).update(D)};for(var p=0;p<f.length;++p){var g=f[p];h[g]=x(g)}return h};function v(h){if(h)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=S;else if(c){var p=new ArrayBuffer(68);this.buffer8=new Uint8Array(p),this.blocks=new Uint32Array(p)}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(h){if(this.finalized)throw new Error(r);var p=k(h);h=p[0];for(var g=p[1],m,D=0,E,C=h.length,N=this.blocks,I=this.buffer8;D<C;){if(this.hashed&&(this.hashed=!1,N[0]=N[16],N[16]=N[1]=N[2]=N[3]=N[4]=N[5]=N[6]=N[7]=N[8]=N[9]=N[10]=N[11]=N[12]=N[13]=N[14]=N[15]=0),g)if(c)for(E=this.start;D<C&&E<64;++D)m=h.charCodeAt(D),m<128?I[E++]=m:m<2048?(I[E++]=192|m>>>6,I[E++]=128|m&63):m<55296||m>=57344?(I[E++]=224|m>>>12,I[E++]=128|m>>>6&63,I[E++]=128|m&63):(m=65536+((m&1023)<<10|h.charCodeAt(++D)&1023),I[E++]=240|m>>>18,I[E++]=128|m>>>12&63,I[E++]=128|m>>>6&63,I[E++]=128|m&63);else for(E=this.start;D<C&&E<64;++D)m=h.charCodeAt(D),m<128?N[E>>>2]|=m<<l[E++&3]:m<2048?(N[E>>>2]|=(192|m>>>6)<<l[E++&3],N[E>>>2]|=(128|m&63)<<l[E++&3]):m<55296||m>=57344?(N[E>>>2]|=(224|m>>>12)<<l[E++&3],N[E>>>2]|=(128|m>>>6&63)<<l[E++&3],N[E>>>2]|=(128|m&63)<<l[E++&3]):(m=65536+((m&1023)<<10|h.charCodeAt(++D)&1023),N[E>>>2]|=(240|m>>>18)<<l[E++&3],N[E>>>2]|=(128|m>>>12&63)<<l[E++&3],N[E>>>2]|=(128|m>>>6&63)<<l[E++&3],N[E>>>2]|=(128|m&63)<<l[E++&3]);else if(c)for(E=this.start;D<C&&E<64;++D)I[E++]=h[D];else for(E=this.start;D<C&&E<64;++D)N[E>>>2]|=h[D]<<l[E++&3];this.lastByteIndex=E,this.bytes+=E-this.start,E>=64?(this.start=E-64,this.hash(),this.hashed=!0):this.start=E}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this},v.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var h=this.blocks,p=this.lastByteIndex;h[p>>>2]|=d[p&3],p>=56&&(this.hashed||this.hash(),h[0]=h[16],h[16]=h[1]=h[2]=h[3]=h[4]=h[5]=h[6]=h[7]=h[8]=h[9]=h[10]=h[11]=h[12]=h[13]=h[14]=h[15]=0),h[14]=this.bytes<<3,h[15]=this.hBytes<<3|this.bytes>>>29,this.hash()}},v.prototype.hash=function(){var h,p,g,m,D,E,C=this.blocks;this.first?(h=C[0]-680876937,h=(h<<7|h>>>25)-271733879<<0,m=(-1732584194^h&2004318071)+C[1]-117830708,m=(m<<12|m>>>20)+h<<0,g=(-271733879^m&(h^-271733879))+C[2]-1126478375,g=(g<<17|g>>>15)+m<<0,p=(h^g&(m^h))+C[3]-1316259209,p=(p<<22|p>>>10)+g<<0):(h=this.h0,p=this.h1,g=this.h2,m=this.h3,h+=(m^p&(g^m))+C[0]-680876936,h=(h<<7|h>>>25)+p<<0,m+=(g^h&(p^g))+C[1]-389564586,m=(m<<12|m>>>20)+h<<0,g+=(p^m&(h^p))+C[2]+606105819,g=(g<<17|g>>>15)+m<<0,p+=(h^g&(m^h))+C[3]-1044525330,p=(p<<22|p>>>10)+g<<0),h+=(m^p&(g^m))+C[4]-176418897,h=(h<<7|h>>>25)+p<<0,m+=(g^h&(p^g))+C[5]+1200080426,m=(m<<12|m>>>20)+h<<0,g+=(p^m&(h^p))+C[6]-1473231341,g=(g<<17|g>>>15)+m<<0,p+=(h^g&(m^h))+C[7]-45705983,p=(p<<22|p>>>10)+g<<0,h+=(m^p&(g^m))+C[8]+1770035416,h=(h<<7|h>>>25)+p<<0,m+=(g^h&(p^g))+C[9]-1958414417,m=(m<<12|m>>>20)+h<<0,g+=(p^m&(h^p))+C[10]-42063,g=(g<<17|g>>>15)+m<<0,p+=(h^g&(m^h))+C[11]-1990404162,p=(p<<22|p>>>10)+g<<0,h+=(m^p&(g^m))+C[12]+1804603682,h=(h<<7|h>>>25)+p<<0,m+=(g^h&(p^g))+C[13]-40341101,m=(m<<12|m>>>20)+h<<0,g+=(p^m&(h^p))+C[14]-1502002290,g=(g<<17|g>>>15)+m<<0,p+=(h^g&(m^h))+C[15]+1236535329,p=(p<<22|p>>>10)+g<<0,h+=(g^m&(p^g))+C[1]-165796510,h=(h<<5|h>>>27)+p<<0,m+=(p^g&(h^p))+C[6]-1069501632,m=(m<<9|m>>>23)+h<<0,g+=(h^p&(m^h))+C[11]+643717713,g=(g<<14|g>>>18)+m<<0,p+=(m^h&(g^m))+C[0]-373897302,p=(p<<20|p>>>12)+g<<0,h+=(g^m&(p^g))+C[5]-701558691,h=(h<<5|h>>>27)+p<<0,m+=(p^g&(h^p))+C[10]+38016083,m=(m<<9|m>>>23)+h<<0,g+=(h^p&(m^h))+C[15]-660478335,g=(g<<14|g>>>18)+m<<0,p+=(m^h&(g^m))+C[4]-405537848,p=(p<<20|p>>>12)+g<<0,h+=(g^m&(p^g))+C[9]+568446438,h=(h<<5|h>>>27)+p<<0,m+=(p^g&(h^p))+C[14]-1019803690,m=(m<<9|m>>>23)+h<<0,g+=(h^p&(m^h))+C[3]-187363961,g=(g<<14|g>>>18)+m<<0,p+=(m^h&(g^m))+C[8]+1163531501,p=(p<<20|p>>>12)+g<<0,h+=(g^m&(p^g))+C[13]-1444681467,h=(h<<5|h>>>27)+p<<0,m+=(p^g&(h^p))+C[2]-51403784,m=(m<<9|m>>>23)+h<<0,g+=(h^p&(m^h))+C[7]+1735328473,g=(g<<14|g>>>18)+m<<0,p+=(m^h&(g^m))+C[12]-1926607734,p=(p<<20|p>>>12)+g<<0,D=p^g,h+=(D^m)+C[5]-378558,h=(h<<4|h>>>28)+p<<0,m+=(D^h)+C[8]-2022574463,m=(m<<11|m>>>21)+h<<0,E=m^h,g+=(E^p)+C[11]+1839030562,g=(g<<16|g>>>16)+m<<0,p+=(E^g)+C[14]-35309556,p=(p<<23|p>>>9)+g<<0,D=p^g,h+=(D^m)+C[1]-1530992060,h=(h<<4|h>>>28)+p<<0,m+=(D^h)+C[4]+1272893353,m=(m<<11|m>>>21)+h<<0,E=m^h,g+=(E^p)+C[7]-155497632,g=(g<<16|g>>>16)+m<<0,p+=(E^g)+C[10]-1094730640,p=(p<<23|p>>>9)+g<<0,D=p^g,h+=(D^m)+C[13]+681279174,h=(h<<4|h>>>28)+p<<0,m+=(D^h)+C[0]-358537222,m=(m<<11|m>>>21)+h<<0,E=m^h,g+=(E^p)+C[3]-722521979,g=(g<<16|g>>>16)+m<<0,p+=(E^g)+C[6]+76029189,p=(p<<23|p>>>9)+g<<0,D=p^g,h+=(D^m)+C[9]-640364487,h=(h<<4|h>>>28)+p<<0,m+=(D^h)+C[12]-421815835,m=(m<<11|m>>>21)+h<<0,E=m^h,g+=(E^p)+C[15]+530742520,g=(g<<16|g>>>16)+m<<0,p+=(E^g)+C[2]-995338651,p=(p<<23|p>>>9)+g<<0,h+=(g^(p|~m))+C[0]-198630844,h=(h<<6|h>>>26)+p<<0,m+=(p^(h|~g))+C[7]+1126891415,m=(m<<10|m>>>22)+h<<0,g+=(h^(m|~p))+C[14]-1416354905,g=(g<<15|g>>>17)+m<<0,p+=(m^(g|~h))+C[5]-57434055,p=(p<<21|p>>>11)+g<<0,h+=(g^(p|~m))+C[12]+1700485571,h=(h<<6|h>>>26)+p<<0,m+=(p^(h|~g))+C[3]-1894986606,m=(m<<10|m>>>22)+h<<0,g+=(h^(m|~p))+C[10]-1051523,g=(g<<15|g>>>17)+m<<0,p+=(m^(g|~h))+C[1]-2054922799,p=(p<<21|p>>>11)+g<<0,h+=(g^(p|~m))+C[8]+1873313359,h=(h<<6|h>>>26)+p<<0,m+=(p^(h|~g))+C[15]-30611744,m=(m<<10|m>>>22)+h<<0,g+=(h^(m|~p))+C[6]-1560198380,g=(g<<15|g>>>17)+m<<0,p+=(m^(g|~h))+C[13]+1309151649,p=(p<<21|p>>>11)+g<<0,h+=(g^(p|~m))+C[4]-145523070,h=(h<<6|h>>>26)+p<<0,m+=(p^(h|~g))+C[11]-1120210379,m=(m<<10|m>>>22)+h<<0,g+=(h^(m|~p))+C[2]+718787259,g=(g<<15|g>>>17)+m<<0,p+=(m^(g|~h))+C[9]-343485551,p=(p<<21|p>>>11)+g<<0,this.first?(this.h0=h+1732584193<<0,this.h1=p-271733879<<0,this.h2=g-1732584194<<0,this.h3=m+271733878<<0,this.first=!1):(this.h0=this.h0+h<<0,this.h1=this.h1+p<<0,this.h2=this.h2+g<<0,this.h3=this.h3+m<<0)},v.prototype.hex=function(){this.finalize();var h=this.h0,p=this.h1,g=this.h2,m=this.h3;return u[h>>>4&15]+u[h&15]+u[h>>>12&15]+u[h>>>8&15]+u[h>>>20&15]+u[h>>>16&15]+u[h>>>28&15]+u[h>>>24&15]+u[p>>>4&15]+u[p&15]+u[p>>>12&15]+u[p>>>8&15]+u[p>>>20&15]+u[p>>>16&15]+u[p>>>28&15]+u[p>>>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 h=this.h0,p=this.h1,g=this.h2,m=this.h3;return[h&255,h>>>8&255,h>>>16&255,h>>>24&255,p&255,p>>>8&255,p>>>16&255,p>>>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 h=new ArrayBuffer(16),p=new Uint32Array(h);return p[0]=this.h0,p[1]=this.h1,p[2]=this.h2,p[3]=this.h3,h},v.prototype.buffer=v.prototype.arrayBuffer,v.prototype.base64=function(){for(var h,p,g,m="",D=this.array(),E=0;E<15;)h=D[E++],p=D[E++],g=D[E++],m+=y[h>>>2]+y[(h<<4|p>>>4)&63]+y[(p<<2|g>>>6)&63]+y[g&63];return h=D[E],m+=y[h>>>2]+y[h<<4&63]+"==",m};function O(h,p){var g,m=k(h);if(h=m[0],m[1]){var D=[],E=h.length,C=0,N;for(g=0;g<E;++g)N=h.charCodeAt(g),N<128?D[C++]=N:N<2048?(D[C++]=192|N>>>6,D[C++]=128|N&63):N<55296||N>=57344?(D[C++]=224|N>>>12,D[C++]=128|N>>>6&63,D[C++]=128|N&63):(N=65536+((N&1023)<<10|h.charCodeAt(++g)&1023),D[C++]=240|N>>>18,D[C++]=128|N>>>12&63,D[C++]=128|N>>>6&63,D[C++]=128|N&63);h=D}h.length>64&&(h=new v(!0).update(h).array());var I=[],q=[];for(g=0;g<64;++g){var Z=h[g]||0;I[g]=92^Z,q[g]=54^Z}v.call(this,p),this.update(q),this.oKeyPad=I,this.inner=!0,this.sharedMemory=p}O.prototype=new v,O.prototype.finalize=function(){if(v.prototype.finalize.call(this),this.inner){this.inner=!1;var h=this.array();v.call(this,this.sharedMemory),this.update(this.oKeyPad),this.update(h),v.prototype.finalize.call(this)}};var A=V();A.md5=A,A.md5.hmac=_(),o?t.exports=A:s.md5=A})()})(Zn)),Zn.exports}var Xl=Yl(),Jn={exports:{}};/**
480
+ * [js-sha256]{@link https://github.com/emn178/js-sha256}
481
+ *
482
+ * @version 0.11.1
483
+ * @author Chen, Yi-Cyuan [emn178@gmail.com]
484
+ * @copyright Chen, Yi-Cyuan 2014-2025
485
+ * @license MIT
486
+ */var Xi;function ed(){return Xi||(Xi=1,(function(t){(function(){var e="input is invalid type",r=typeof window=="object",n=r?window:{};n.JS_SHA256_NO_WINDOW&&(r=!1);var s=!r&&typeof self=="object",i=!n.JS_SHA256_NO_NODE_JS&&typeof process=="object"&&process.versions&&process.versions.node&&process.type!="renderer";i?n=oo:s&&(n=self);var a=!n.JS_SHA256_NO_COMMON_JS&&!0&&t.exports,o=!n.JS_SHA256_NO_ARRAY_BUFFER&&typeof ArrayBuffer<"u",c="0123456789abcdef".split(""),u=[-2147483648,8388608,32768,128],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],f=["hex","array","digest","arrayBuffer"],y=[];(n.JS_SHA256_NO_NODE_JS||!Array.isArray)&&(Array.isArray=function(w){return Object.prototype.toString.call(w)==="[object Array]"}),o&&(n.JS_SHA256_NO_ARRAY_BUFFER_IS_VIEW||!ArrayBuffer.isView)&&(ArrayBuffer.isView=function(w){return typeof w=="object"&&w.buffer&&w.buffer.constructor===ArrayBuffer});var b=function(w,x){return function(_){return new k(x,!0).update(_)[w]()}},S=function(w){var x=b("hex",w);i&&(x=j(x,w)),x.create=function(){return new k(w)},x.update=function(O){return x.create().update(O)};for(var _=0;_<f.length;++_){var v=f[_];x[v]=b(v,w)}return x},j=function(w,x){var _=nn,v=nn.Buffer,O=x?"sha224":"sha256",A;v.from&&!n.JS_SHA256_NO_BUFFER_FROM?A=v.from:A=function(p){return new v(p)};var h=function(p){if(typeof p=="string")return _.createHash(O).update(p,"utf8").digest("hex");if(p==null)throw new Error(e);return p.constructor===ArrayBuffer&&(p=new Uint8Array(p)),Array.isArray(p)||ArrayBuffer.isView(p)||p.constructor===v?_.createHash(O).update(A(p)).digest("hex"):w(p)};return h},T=function(w,x){return function(_,v){return new $(_,x,!0).update(v)[w]()}},L=function(w){var x=T("hex",w);x.create=function(O){return new $(O,w)},x.update=function(O,A){return x.create(O).update(A)};for(var _=0;_<f.length;++_){var v=f[_];x[v]=T(v,w)}return x};function k(w,x){x?(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],w?(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=w}k.prototype.update=function(w){if(!this.finalized){var x,_=typeof w;if(_!=="string"){if(_==="object"){if(w===null)throw new Error(e);if(o&&w.constructor===ArrayBuffer)w=new Uint8Array(w);else if(!Array.isArray(w)&&(!o||!ArrayBuffer.isView(w)))throw new Error(e)}else throw new Error(e);x=!0}for(var v,O=0,A,h=w.length,p=this.blocks;O<h;){if(this.hashed&&(this.hashed=!1,p[0]=this.block,this.block=p[16]=p[1]=p[2]=p[3]=p[4]=p[5]=p[6]=p[7]=p[8]=p[9]=p[10]=p[11]=p[12]=p[13]=p[14]=p[15]=0),x)for(A=this.start;O<h&&A<64;++O)p[A>>>2]|=w[O]<<d[A++&3];else for(A=this.start;O<h&&A<64;++O)v=w.charCodeAt(O),v<128?p[A>>>2]|=v<<d[A++&3]:v<2048?(p[A>>>2]|=(192|v>>>6)<<d[A++&3],p[A>>>2]|=(128|v&63)<<d[A++&3]):v<55296||v>=57344?(p[A>>>2]|=(224|v>>>12)<<d[A++&3],p[A>>>2]|=(128|v>>>6&63)<<d[A++&3],p[A>>>2]|=(128|v&63)<<d[A++&3]):(v=65536+((v&1023)<<10|w.charCodeAt(++O)&1023),p[A>>>2]|=(240|v>>>18)<<d[A++&3],p[A>>>2]|=(128|v>>>12&63)<<d[A++&3],p[A>>>2]|=(128|v>>>6&63)<<d[A++&3],p[A>>>2]|=(128|v&63)<<d[A++&3]);this.lastByteIndex=A,this.bytes+=A-this.start,A>=64?(this.block=p[16],this.start=A-64,this.hash(),this.hashed=!0):this.start=A}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}},k.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var w=this.blocks,x=this.lastByteIndex;w[16]=this.block,w[x>>>2]|=u[x&3],this.block=w[16],x>=56&&(this.hashed||this.hash(),w[0]=this.block,w[16]=w[1]=w[2]=w[3]=w[4]=w[5]=w[6]=w[7]=w[8]=w[9]=w[10]=w[11]=w[12]=w[13]=w[14]=w[15]=0),w[14]=this.hBytes<<3|this.bytes>>>29,w[15]=this.bytes<<3,this.hash()}},k.prototype.hash=function(){var w=this.h0,x=this.h1,_=this.h2,v=this.h3,O=this.h4,A=this.h5,h=this.h6,p=this.h7,g=this.blocks,m,D,E,C,N,I,q,Z,pe,Q,ve;for(m=16;m<64;++m)N=g[m-15],D=(N>>>7|N<<25)^(N>>>18|N<<14)^N>>>3,N=g[m-2],E=(N>>>17|N<<15)^(N>>>19|N<<13)^N>>>10,g[m]=g[m-16]+D+g[m-7]+E<<0;for(ve=x&_,m=0;m<64;m+=4)this.first?(this.is224?(Z=300032,N=g[0]-1413257819,p=N-150054599<<0,v=N+24177077<<0):(Z=704751109,N=g[0]-210244248,p=N-1521486534<<0,v=N+143694565<<0),this.first=!1):(D=(w>>>2|w<<30)^(w>>>13|w<<19)^(w>>>22|w<<10),E=(O>>>6|O<<26)^(O>>>11|O<<21)^(O>>>25|O<<7),Z=w&x,C=Z^w&_^ve,q=O&A^~O&h,N=p+E+q+l[m]+g[m],I=D+C,p=v+N<<0,v=N+I<<0),D=(v>>>2|v<<30)^(v>>>13|v<<19)^(v>>>22|v<<10),E=(p>>>6|p<<26)^(p>>>11|p<<21)^(p>>>25|p<<7),pe=v&w,C=pe^v&x^Z,q=p&O^~p&A,N=h+E+q+l[m+1]+g[m+1],I=D+C,h=_+N<<0,_=N+I<<0,D=(_>>>2|_<<30)^(_>>>13|_<<19)^(_>>>22|_<<10),E=(h>>>6|h<<26)^(h>>>11|h<<21)^(h>>>25|h<<7),Q=_&v,C=Q^_&w^pe,q=h&p^~h&O,N=A+E+q+l[m+2]+g[m+2],I=D+C,A=x+N<<0,x=N+I<<0,D=(x>>>2|x<<30)^(x>>>13|x<<19)^(x>>>22|x<<10),E=(A>>>6|A<<26)^(A>>>11|A<<21)^(A>>>25|A<<7),ve=x&_,C=ve^x&v^Q,q=A&h^~A&p,N=O+E+q+l[m+3]+g[m+3],I=D+C,O=w+N<<0,w=N+I<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+w<<0,this.h1=this.h1+x<<0,this.h2=this.h2+_<<0,this.h3=this.h3+v<<0,this.h4=this.h4+O<<0,this.h5=this.h5+A<<0,this.h6=this.h6+h<<0,this.h7=this.h7+p<<0},k.prototype.hex=function(){this.finalize();var w=this.h0,x=this.h1,_=this.h2,v=this.h3,O=this.h4,A=this.h5,h=this.h6,p=this.h7,g=c[w>>>28&15]+c[w>>>24&15]+c[w>>>20&15]+c[w>>>16&15]+c[w>>>12&15]+c[w>>>8&15]+c[w>>>4&15]+c[w&15]+c[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[_>>>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[O>>>28&15]+c[O>>>24&15]+c[O>>>20&15]+c[O>>>16&15]+c[O>>>12&15]+c[O>>>8&15]+c[O>>>4&15]+c[O&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[h>>>28&15]+c[h>>>24&15]+c[h>>>20&15]+c[h>>>16&15]+c[h>>>12&15]+c[h>>>8&15]+c[h>>>4&15]+c[h&15];return this.is224||(g+=c[p>>>28&15]+c[p>>>24&15]+c[p>>>20&15]+c[p>>>16&15]+c[p>>>12&15]+c[p>>>8&15]+c[p>>>4&15]+c[p&15]),g},k.prototype.toString=k.prototype.hex,k.prototype.digest=function(){this.finalize();var w=this.h0,x=this.h1,_=this.h2,v=this.h3,O=this.h4,A=this.h5,h=this.h6,p=this.h7,g=[w>>>24&255,w>>>16&255,w>>>8&255,w&255,x>>>24&255,x>>>16&255,x>>>8&255,x&255,_>>>24&255,_>>>16&255,_>>>8&255,_&255,v>>>24&255,v>>>16&255,v>>>8&255,v&255,O>>>24&255,O>>>16&255,O>>>8&255,O&255,A>>>24&255,A>>>16&255,A>>>8&255,A&255,h>>>24&255,h>>>16&255,h>>>8&255,h&255];return this.is224||g.push(p>>>24&255,p>>>16&255,p>>>8&255,p&255),g},k.prototype.array=k.prototype.digest,k.prototype.arrayBuffer=function(){this.finalize();var w=new ArrayBuffer(this.is224?28:32),x=new DataView(w);return x.setUint32(0,this.h0),x.setUint32(4,this.h1),x.setUint32(8,this.h2),x.setUint32(12,this.h3),x.setUint32(16,this.h4),x.setUint32(20,this.h5),x.setUint32(24,this.h6),this.is224||x.setUint32(28,this.h7),w};function $(w,x,_){var v,O=typeof w;if(O==="string"){var A=[],h=w.length,p=0,g;for(v=0;v<h;++v)g=w.charCodeAt(v),g<128?A[p++]=g:g<2048?(A[p++]=192|g>>>6,A[p++]=128|g&63):g<55296||g>=57344?(A[p++]=224|g>>>12,A[p++]=128|g>>>6&63,A[p++]=128|g&63):(g=65536+((g&1023)<<10|w.charCodeAt(++v)&1023),A[p++]=240|g>>>18,A[p++]=128|g>>>12&63,A[p++]=128|g>>>6&63,A[p++]=128|g&63);w=A}else if(O==="object"){if(w===null)throw new Error(e);if(o&&w.constructor===ArrayBuffer)w=new Uint8Array(w);else if(!Array.isArray(w)&&(!o||!ArrayBuffer.isView(w)))throw new Error(e)}else throw new Error(e);w.length>64&&(w=new k(x,!0).update(w).array());var m=[],D=[];for(v=0;v<64;++v){var E=w[v]||0;m[v]=92^E,D[v]=54^E}k.call(this,x,_),this.update(D),this.oKeyPad=m,this.inner=!0,this.sharedMemory=_}$.prototype=new k,$.prototype.finalize=function(){if(k.prototype.finalize.call(this),this.inner){this.inner=!1;var w=this.array();k.call(this,this.is224,this.sharedMemory),this.update(this.oKeyPad),this.update(w),k.prototype.finalize.call(this)}};var V=S();V.sha256=V,V.sha224=S(!0),V.sha256.hmac=L(),V.sha224.hmac=L(!0),a?t.exports=V:(n.sha256=V.sha256,n.sha224=V.sha224)})()})(Jn)),Jn.exports}var td=ed();function rd(t){if(t instanceof Be)return t;if(typeof t=="string")return Be.fromUtf8(t);throw new G(`hashing.* requires Bytes or String, got ${typeof t}`)}function nd(t,e){const r=rd(e[0]);switch(t){case"md5":return new Be(new Uint8Array(Xl.md5.arrayBuffer(r.data)));case"sha256":return new Be(new Uint8Array(td.sha256.arrayBuffer(r.data)));case"crc32":{const n=id(r.data);return new Be(ea(n))}case"crc32c":{const n=od(r.data);return new Be(ea(n))}}throw new Je(`Unknown hashing method '${t}'`)}function ea(t){return new Uint8Array([t&255,t>>>8&255,t>>>16&255,t>>>24&255])}const sd=(()=>{const t=new Uint32Array(256);for(let e=0;e<256;e++){let r=e;for(let n=0;n<8;n++)r=r&1?3988292384^r>>>1:r>>>1;t[e]=r>>>0}return t})();function id(t){let e=4294967295;for(let r=0;r<t.length;r++)e=sd[(e^t[r])&255]^e>>>8;return(e^4294967295)>>>0}const ad=(()=>{const t=new Uint32Array(256);for(let e=0;e<256;e++){let r=e;for(let n=0;n<8;n++)r=r&1?2197175160^r>>>1:r>>>1;t[e]=r>>>0}return t})();function od(t){let e=4294967295;for(let r=0;r<t.length;r++)e=ad[(e^t[r])&255]^e>>>8;return(e^4294967295)>>>0}function cd(t){if(typeof t=="number")return Math.trunc(t);if(t instanceof oe)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 ud(t){if(t instanceof oe)return t;if(typeof t=="number")return new oe(t);if(typeof t=="string"){const e=t.trim();if(/^[+-]?(\d+\.?\d*|\.\d+)$/.test(e))return new oe(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 ld(t){if(typeof t=="boolean")return t;if(typeof t=="string"){if(t==="true")return!0;if(t==="false")return!1;throw new G(`bool() cannot convert string '${t}' to a boolean`)}throw new G(`bool() cannot convert ${typeof t} to a boolean`)}function dd(t,e,r,n){switch(t){case"get":{const a=String(W(e[0],r,n));return Ji(a,r)}case"exists":{const a=String(W(e[0],r,n));return Qi(a,r)}case"getAfter":{const a=W(e[0],r,n),o=String(a);if(o===r.afterStatePath.toString()){if(r.afterState===null)throw new G(`getAfter() of non-existent document '${o}' (guard with existsAfter() first)`);return Ss(br(o),r.afterState)}const c=br(o);if(r.batchProjection?.has(c)){const u=r.batchProjection.get(c);if(u===null)throw new G(`getAfter() of non-existent document '${o}' (guard with existsAfter() first)`);return Ss(c,u)}return Ji(o,r)}case"existsAfter":{const a=W(e[0],r,n),o=String(a);if(o===r.afterStatePath.toString())return r.existsAfter;const c=br(o);return r.batchProjection?.has(c)?r.batchProjection.get(c)!==null:Qi(o,r)}case"debug":return W(e[0],r,n);case"string":return String(W(e[0],r,n));case"int":return cd(W(e[0],r,n));case"float":return ud(W(e[0],r,n));case"bool":return ld(W(e[0],r,n));case"path":{const a=W(e[0],r,n);if(typeof a=="string")return Xe.fromString(a);throw new G(`path() requires a string argument, got ${typeof a}`)}}const s=r.functions.get(t);if(!s)throw new Je(`Unknown function: ${t}`);const i={...n};for(let a=0;a<s.parameters.length;a++)i[s.parameters[a]]=W(e[a],r,n);r.trace?.enterFrame(t);try{for(const a of s.lets){const o=r.trace?r.trace.entries.length:-1;i[a.name]=W(a.value,r,i),o>=0&&r.trace?.markEntryAsLetBinding(o,a.name)}return W(s.body,r,i)}finally{r.trace?.exitFrame()}}function hd(t,e,r,n,s){if(t.type==="identifier"){const o=t.name;if(ta(o)&&!(o in s)&&!(o in n.pathVariables)){const c=r.map(u=>W(u,n,s));return pd(o,e,c)}if(!ta(o)&&!(o in s)&&!(o in n.pathVariables)&&!Sd(o))throw new Je(`Unknown namespace or method '${o}.${e}()'`)}const i=W(t,n,s),a=r.map(o=>W(o,n,s));if(i instanceof te){const o=i.callMethod(e,a);if(o===ue)throw new Je(`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 yr(o,i);throw new G("diff() requires a map argument")}if(typeof i=="function")return i(...a);if(i instanceof fe)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 fe))throw new G(`Unsupported operation: set.${e} requires a Set argument`);return i[e](o)}}if(i instanceof yr)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"hasAll":return a[0].every(c=>Object.hasOwn(o,c));case"hasAny":return a[0].some(c=>Object.hasOwn(o,c));case"hasOnly":return Object.keys(o).every(c=>a[0].includes(c));case"diff":{const c=a[0];return new yr(c,o)}case"get":{const c=a[0],u=a[1];if(Array.isArray(c)){let l=o;for(const f of c){if(l==null||typeof l!="object"||Array.isArray(l)||l instanceof te)return u;const y=String(f);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 fe(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(Qn(String(a[0]),"g"));case"matches":return Qn(`^(?:${String(a[0])})$`).test(i);case"replace":return i.replace(Qn(String(a[0]),"g"),String(a[1]));case"toUtf8":return Be.fromUtf8(i)}throw new Je(`Unknown method '${e}' on ${typeof i}`)}function Qn(t,e=""){try{return new RegExp(t,e)}catch(r){throw new G(`Invalid regex '${t}': ${r.message}`)}}const fd=new Set(["math","timestamp","duration","latlng","hashing"]);function ta(t){return fd.has(t)}function pd(t,e,r){const n=t==="hashing"?r:r.map(md);switch(t){case"math":return yd(e,n);case"timestamp":return bd(e,n);case"duration":return vd(e,n);case"latlng":return gd(e,n);case"hashing":return nd(e,r)}throw new Je(`Unknown namespace '${t}'`)}function md(t){return t instanceof oe?t.value:t}function gd(t,e){switch(t){case"value":{const[r,n]=e;return new rt(r,n)}}throw new Je(`Unknown latlng method '${t}'`)}function yd(t,e){switch(t){case"abs":return Math.abs(e[0]);case"ceil":return Math.ceil(e[0]);case"floor":return Math.floor(e[0]);case"round":return Math.round(e[0]);case"sqrt":return Math.sqrt(e[0]);case"pow":return Math.pow(e[0],e[1]);case"isInfinite":{const r=e[0];return Number.isFinite(r)===!1&&Number.isNaN(r)===!1}case"isNaN":return Number.isNaN(e[0])}throw new Je(`Unknown math method '${t}'`)}function bd(t,e){switch(t){case"date":{const[r,n,s]=e;return xe.fromYMD(r,n,s)}case"value":return xe.fromMillis(e[0])}throw new Je(`Unknown timestamp method '${t}'`)}function vd(t,e){switch(t){case"value":try{return we.fromValue(e[0],e[1])}catch(r){throw new G(r.message)}case"time":{const[r,n,s,i]=e;return we.fromTime(r,n,s,i)}case"abs":{const r=e[0];if(!(r instanceof we))throw new G(`duration.abs() requires a Duration argument, got ${typeof r}`);return we.abs(r)}}throw new Je(`Unknown duration method '${t}'`)}function W(t,e,r={}){return e.trace?e.trace.capture(t,()=>ra(t,e,r)):ra(t,e,r)}function ra(t,e,r){switch(t.type){case"literal":return typeof t.value=="number"&&t.raw.includes(".")?new oe(t.value):t.value;case"identifier":return wd(t.name,e,r);case"binaryOp":return _d(t.op,t.left,t.right,e,r);case"unaryOp":{if(t.op==="!")return!W(t.operand,e,r);if(t.op==="-"){const n=W(t.operand,e,r);return n instanceof oe?new oe(-n.value):-n}throw new G(`Unknown unary op: ${t.op}`,t)}case"ternary":{const n=pr(W(t.condition,e,r),t.condition);return W(n?t.consequent:t.alternate,e,r)}case"memberAccess":{const n=W(t.object,e,r);if(n==null)throw new G(`Property '${t.property}' accessed on ${n===null?"null":"undefined"} value`,t);if(n instanceof te)return n.field(t.property);if(n instanceof yr)switch(t.property){case"addedKeys":return()=>n.addedKeys();case"removedKeys":return()=>n.removedKeys();case"changedKeys":return()=>n.changedKeys();case"affectedKeys":return()=>n.affectedKeys();case"unchangedKeys":return()=>n.unchangedKeys()}if(n instanceof fe)switch(t.property){case"size":return()=>n.size()}if(Object.hasOwn(n,t.property))return n[t.property];throw new G(`No field '${t.property}' on map (use 'in' or .get() to read a possibly-absent field)`,t)}case"bracketAccess":{const n=W(t.object,e,r),s=W(t.index,e,r);if(n==null)throw new G(`Index access on ${n===null?"null":"undefined"} value`,t);if(n instanceof te)return n.field(String(s));const i=String(s);return Object.hasOwn(n,i)?n[i]:null}case"sliceAccess":{const n=W(t.object,e,r),s=W(t.start,e,r),i=W(t.end,e,r);if(n==null)return null;if(typeof s!="number"||!Number.isInteger(s))throw new G(`Slice start must be an integer, got ${typeof s}`);if(typeof i!="number"||!Number.isInteger(i))throw new G(`Slice end must be an integer, got ${typeof i}`);if(s<0||i<0)throw new G(`Slice indices must be non-negative, got [${s}:${i}]`);if(typeof n=="string"||Array.isArray(n)){if(i>n.length)throw new G(`Slice end ${i} exceeds length ${n.length}`);return n.slice(s,i)}throw new G(`Slice not supported on ${typeof n}`)}case"inExpr":{const n=W(t.element,e,r),s=W(t.collection,e,r);return s==null?!1:Array.isArray(s)?s.some(i=>ye(i,n)):typeof s=="object"?Object.hasOwn(s,String(n)):!1}case"isExpr":{const n=W(t.value,e,r);switch(t.typeName){case"string":return typeof n=="string";case"int":return n instanceof te?!1:typeof n=="number";case"float":return n instanceof oe;case"number":return n instanceof oe?!0:n instanceof te?!1:typeof n=="number";case"bool":return typeof n=="boolean";case"null":return n===null;case"list":return Array.isArray(n);case"map":return n instanceof te||n instanceof yr||n instanceof fe?!1:typeof n=="object"&&n!==null&&!Array.isArray(n);default:return n instanceof te?n.typeName===t.typeName:!1}}case"listLiteral":return t.elements.map(n=>W(n,e,r));case"mapLiteral":{const n={};for(const s of t.entries){const i=String(W(s.key,e,r));n[i]=W(s.value,e,r)}return n}case"functionCall":return dd(t.name,t.args,e,r);case"methodCall":return hd(t.object,t.method,t.args,e,r);case"pathLiteral":{const n=[];for(const s of t.segments)typeof s=="string"?n.push(s):n.push(String(W(s,e,r)));return new Xe(n)}default:throw new G(`Unknown expression type: ${t.type}`,t)}}function wd(t,e,r){if(t in r)return r[t];if(t in e.pathVariables)return e.pathVariables[t];switch(t){case"request":return e.request;case"resource":if(e.resource===null)throw new G("Null value error.");return e.resource;case"true":return!0;case"false":return!1;case"null":return null}throw new G(`Undefined variable '${t}'`)}function Sd(t){return t==="request"||t==="resource"||t==="true"||t==="false"||t==="null"}function _d(t,e,r,n,s){if(t==="&&"){let o,c;try{o=pr(W(e,n,s),e)}catch(l){c=l}if(c===void 0&&o===!1)return n.trace?.skip(r),!1;let u,d;try{u=pr(W(r,n,s),r)}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=pr(W(e,n,s),e)}catch(l){c=l}if(c===void 0&&o===!0)return n.trace?.skip(r),!0;let u,d;try{u=pr(W(r,n,s),r)}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=W(e,n,s),a=W(r,n,s);if(t!=="=="&&t!=="!="){if(i instanceof te){const o=i.binaryOp(t,a);if(o!==ue)return o}if(typeof i=="number"&&a instanceof oe){const o=new oe(i).binaryOp(t,a);if(o!==ue)return o}if(a instanceof te&&(t==="+"||t==="*")){const o=a.binaryOp(t,i);if(o!==ue)return o}if((t!=="+"||typeof i!="string"&&typeof a!="string")&&(i instanceof te||a instanceof te)){const o=i instanceof te?i.typeName:typeof i,c=a instanceof te?a.typeName:typeof a;throw new G(`Operator '${t}' is not defined between ${o} and ${c}`)}}if((t==="<"||t===">"||t==="<="||t===">=")&&!(typeof i=="number"&&typeof a=="number"||typeof i=="string"&&typeof a=="string"))throw new G(`Operator '${t}' is not defined between ${typeof i} and ${typeof a}`);switch(t){case"==":return i===a||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 te)return i+String(a);throw new G(`Operator '+' is not defined between ${Array.isArray(i)?"list":typeof i} and ${Array.isArray(a)?"list":typeof a}`)}case"-":return i-a;case"*":return i*a;case"/":if(a===0)throw new G("Division by zero");return Math.trunc(i/a);case"%":if(a===0)throw new G("Modulo by zero");return i%a;default:throw new G(`Unknown binary op: ${t}`)}}function pr(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 Ad=new Set(["__proto__","prototype","constructor"]);function sn(t){if(Ad.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 Wo(t,e){const r={...t};for(const[n,s]of Object.entries(e)){sn(n);const i=Object.hasOwn(r,n)?r[n]:void 0;s!==null&&typeof s=="object"&&!Array.isArray(s)&&i!==null&&typeof i=="object"&&!Array.isArray(i)?r[n]=Wo(i,s):r[n]=s}return r}function xd(t,e,r){let n=t;for(let i=0;i<e.length-1;i++){const a=e[i];sn(a);const o=Object.hasOwn(n,a)?n[a]:void 0;(o===null||typeof o!="object"||Array.isArray(o))&&(n[a]={}),n=n[a]}const s=e[e.length-1];sn(s),n[s]=r}function Id(t,e){const r={...t};for(const[n,s]of Object.entries(e))n.includes(".")?xd(r,n.split("."),s):(sn(n),r[n]=s);return r}function kd(t,e,r){switch(t.kind){case"create":return r;case"set":return t.merge?Wo(e??{},r):r;case"update":return Id(e??{},r);case"delete":return null}}function Ho(t){if(t===null||typeof t!="object"||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function Ed(t){return typeof t=="object"&&t!==null&&t.__type==="serverTimestamp"}function Go(t,e){const r={};for(const[n,s]of Object.entries(t))Ed(s)?r[n]=e:Ho(s)?r[n]=Go(s,e):r[n]=s;return r}function Ct(t){return typeof t=="number"&&!Number.isInteger(t)?new oe(t):Array.isArray(t)?t.map(Ct):Ho(t)?t.__type==="float"&&typeof t.value=="number"?new oe(t.value):Object.fromEntries(Object.entries(t).map(([e,r])=>[e,Ct(r)])):t}function na(t){if(t.method==="list")return{limit:t.query?.limit??null,offset:t.query?.offset??null,orderBy:t.query?.orderBy??null}}function Hr(t){return`/${t.path.segments.map(r=>r.type==="literal"?r.value:r.type==="wildcard"?`{${r.name}}`:`{${r.name}=**}`).join("/")}`}function an(t,e,r,n){const s=[...r,...t.functions],i=t.path.segments,a={},o=[];let c=0,u;for(const f of i)if(f.type==="literal"){if(c>=e.length){u="request-shorter";break}if(e[c]!==f.value){u="literal-mismatch";break}c++}else if(f.type==="wildcard"){if(c>=e.length){u="request-shorter";break}a[f.name]=e[c],c===e.length-1&&o.push(f.name),c++}else a[f.name]=e.slice(c).join("/"),c<e.length&&o.push(f.name),c=e.length;if(u!==void 0)return n?.push({...t.loc?{line:t.loc.line}:{},blockPath:Hr(t),matchedSegments:c,totalSegments:i.length,bindings:a,matched:!1,reason:u}),[];const d=e.slice(c);if(d.length===0)return n?.push({...t.loc?{line:t.loc.line}:{},blockPath:Hr(t),matchedSegments:c,totalSegments:i.length,bindings:a,matched:!0}),[{block:t,pathVariables:a,candidateVariables:o,functions:s}];const l=[];for(const f of t.children)for(const y of an(f,d,s,n))y.pathVariables={...a,...y.pathVariables},y.candidateVariables=[...o,...y.candidateVariables],l.push(y);return n?.push({...t.loc?{line:t.loc.line}:{},blockPath:Hr(t),matchedSegments:c,totalSegments:i.length,bindings:a,...l.length>0?{matched:!0}:{matched:!1,reason:"no-matching-child"}}),l}class Od{attempts=[];push(e){this.attempts.push(e)}}function Cd(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 Td(t,e,r){const n=Cd(e),s=[],i=[],a=[];for(let u=0;u<t.allows.length;u++){const d=t.allows[u];d.operations.some(l=>n.includes(l))&&a.push({rule:d,index:u})}if(a.length===0)return i.push(`No allow rules found for operation '${e}'`),{decision:"DENY",trace:s,notes:i};let o=!1;const c=r.trace;for(const{rule:u,index:d}of a){const l=Rd(u,d),f=new Bl;r.trace=f;try{const y=W(u.condition,r);if(l.expressionTrace=f.entries,y)return l.verdict="ALLOW",s.push(l),r.trace=c,{decision:"ALLOW",trace:s,notes:i};l.verdict="DENY",s.push(l)}catch(y){l.expressionTrace=f.entries,y instanceof Je?(o=!0,l.verdict="UNSUPPORTED",l.message=y.message):(l.verdict="ERROR",l.message=y instanceof Error?y.message:String(y)),s.push(l)}}return r.trace=c,{decision:o?"UNSUPPORTED":"DENY",trace:s,notes:i}}function Rd(t,e){const r={ruleIndex:e,operations:[...t.operations],verdict:"DENY",conditionText:Ie(t.condition)};return t.loc&&(r.line=t.loc.line),r}function Nd(t,e,r,n,s){const i=new Map;for(const L of e)i.set(L.name,L);const a=new Map,o=new Set;if(t.functionMocks)for(const L of t.functionMocks)L.function==="get"&&typeof L.result=="object"&&L.result!==null?(a.set(L.path,Ct(L.result)),o.add(L.path)):L.function==="exists"&&L.result===!0&&(a.set(L.path,{}),o.add(L.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 Xe(d,r),f=Ct(t.data??{}),y=t.resource===void 0||t.resource===null?null:Ct(t.resource);let b,S;if(t.writeMode)b=kd(t.writeMode,y,f),S=b!==null;else switch(t.method){case"create":case"update":b=f,S=!0;break;case"delete":b=null,S=!1;break;case"get":case"list":default:b=y,S=y!==null;break}const j=b!==null?Ct(Go(b,c)):null,T=j??{};return{request:{auth:t.auth?{uid:t.auth.uid,token:t.auth.token??{}}:null,resource:{data:T},method:t.method,path:l,...na(t)?{query:na(t)}:{},time:c},resource:t.method==="create"||y===null?null:{data:Ct(y)},mockDocuments:a,identitylessFunctionMocks:o,getDoc:n,pathVariables:r,functions:i,database:"(default)",afterStatePath:l,afterState:j,existsAfter:S,...s?{batchProjection:s}:{}}}class Fd{simulate(e,r,n){if(!e||e.trim().length===0)return{success:!1,error:{code:"PARSE_FAILED",message:"Empty rules source — call setRules(sandbox, rules) from pyric/sandbox/firestore before operating, or initialize without rules to use the open-by-default ruleset. See pyric/sandbox docs.",recoverable:!0}};const s=si(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 r){const l=d.path.split("/").filter(Boolean),f=[...s.functions??[],...s.service.functions??[],...s.service.match.functions];let y=[];const b=new Od;for(const x of s.service.match.children)y.push(...an(x,l,f,b));let S=!1;if(y.length===0&&d.method==="list"){const x=[...l,"__hypothetical_doc__"];for(const _ of s.service.match.children)y.push(...an(_,x,f,b));y.length>0&&(S=!0)}const j={requestPath:d.path,attempts:b.attempts};if(y.length===0){const x=d.expectation==="DENY"?"PASSED":"FAILED";x==="PASSED"?a++:o++,i.push({description:d.description,expectation:d.expectation,state:x,decision:"DENY",trace:[],notes:[`No match block found for path '${d.path}'`],pathResolution:j});continue}let T="DENY";const L=[],k=[];let $=!1,V;for(const x of y){const _={...u,...x.pathVariables},v=Nd(d,x.functions,_,n?.getDoc,n?.batchProjection),O=Hr(x.block),A=Td(x.block,d.method,v);for(const h of A.trace)h.matchPath=O;if(L.push(...A.trace),k.push(...A.notes),A.decision==="ALLOW"){T="ALLOW",V=O;break}A.decision==="UNSUPPORTED"&&($=!0)}T!=="ALLOW"&&$&&(T="UNSUPPORTED"),T==="ALLOW"&&V&&k.push(`Allowed by match block '${V}'`),S&&k.push(`list on collection path '${d.path}' evaluated against the document-level match block (document wildcard hypothetical, resource undefined) — emulator-faithful`);let w;T==="UNSUPPORTED"?(w="UNSUPPORTED",c++):T===d.expectation?(w="PASSED",a++):(w="FAILED",o++),i.push({description:d.description,expectation:d.expectation,state:w,decision:T,trace:L,notes:k,pathResolution:j})}return{success:!0,data:{passed:a,failed:o,unsupported:c,results:i}}}}function Ld(t,e,r=new Map,n){if(on(t,r))return{provable:!0,reason:"list rule does not depend on per-document data; every doc is equally readable"};const s=Dd(t,r,n);if(!s.ok||s.required.length===0){const u="list rule depends on per-document data through a predicate the query cannot discharge (a rule is provable only when its entire doc-dependence reduces to top-level `resource.data.field == value` conjunctions, including through inlined helpers — disjunctions, ranges, `in`, membership/type checks, and nested paths are not provable)";return{provable:!1,reason:`${u} — prod rejects the whole query rather than filtering`,residual:{missing:[],mismatched:[],outOfScope:u}}}const i=s.required,a=e.where??[],o=[],c=[];for(const u of i){if(a.some(f=>f.field===u.field&&f.op==="=="&&qd(f.value,u.value)))continue;const l=a.find(f=>f.field===u.field&&f.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:jd(o,c),residual:{missing:o,mismatched:c}}}function jd(t,e){const r=[];if(t.length>0){const n=t.map(s=>`resource.data.${s.field} == ${s.fromAuthUid?"request.auth.uid":JSON.stringify(s.expectedValue)}`).join(", ");r.push(`the query has no matching where(...) equality for [${n}]`)}if(e.length>0){const n=e.map(s=>`resource.data.${s.field} == ${JSON.stringify(s.expectedValue)} but the query pins ${JSON.stringify(s.actualValue)}`).join(", ");r.push(`the query where(...) value does not match [${n}]`)}return`${r.join("; ")} — prod rejects the query ("rules are not filters")`}function on(t,e=new Map,r=new Set){const n=s=>{switch(s.type){case"literal":return!0;case"identifier":return s.name!=="resource";case"memberAccess":return n(s.object);case"bracketAccess":return n(s.object)&&n(s.index);case"sliceAccess":return n(s.object)&&n(s.start)&&n(s.end);case"binaryOp":return n(s.left)&&n(s.right);case"unaryOp":return n(s.operand);case"ternary":return n(s.condition)&&n(s.consequent)&&n(s.alternate);case"inExpr":return n(s.element)&&n(s.collection);case"isExpr":return n(s.value);case"listLiteral":return s.elements.every(n);case"mapLiteral":return s.entries.every(i=>n(i.key)&&n(i.value));case"pathLiteral":return s.segments.every(i=>typeof i=="string"||n(i));case"methodCall":return n(s.object)&&s.args.every(n);case"functionCall":{if(!s.args.every(n))return!1;const i=e.get(s.name);if(!i)return!0;if(r.has(s.name))return!1;const a=new Set(r).add(s.name);return on(i.body,e,a)&&i.lets.every(o=>on(o.value,e,a))}default:return!1}};return n(t)}function Dd(t,e,r){const n=[],s=(i,a)=>{if(i.type==="binaryOp"&&i.op==="&&")return s(i.left,a)&&s(i.right,a);if(i.type==="functionCall"&&e.has(i.name)&&!a.has(i.name)){const c=e.get(i.name),u=new Map;c.parameters.forEach((f,y)=>{const b=i.args[y];b&&u.set(f,b)});for(const f of c.lets)u.set(f.name,sa(f.value,u));const d=sa(c.body,u),l=new Set(a).add(i.name);return s(d,l)}const o=Md(i,r);return o?(n.push(o),!0):on(i,e)};return s(t,new Set)?{ok:!0,required:n}:{ok:!1}}function Md(t,e){if(t.type!=="binaryOp"||t.op!=="==")return null;const r=(n,s)=>{const i=$d(n);return i===null?null:s.type==="literal"?{field:i,value:s.value,fromAuthUid:!1}:e!==void 0&&Pd(s)?{field:i,value:e,fromAuthUid:!0}:null};return r(t.left,t.right)??r(t.right,t.left)}function Pd(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 sa(t,e){const r=n=>{switch(n.type){case"identifier":return e.get(n.name)??n;case"literal":return n;case"memberAccess":return{...n,object:r(n.object)};case"methodCall":return{...n,object:r(n.object),args:n.args.map(r)};case"bracketAccess":return{...n,object:r(n.object),index:r(n.index)};case"sliceAccess":return{...n,object:r(n.object),start:r(n.start),end:r(n.end)};case"binaryOp":return{...n,left:r(n.left),right:r(n.right)};case"unaryOp":return{...n,operand:r(n.operand)};case"ternary":return{...n,condition:r(n.condition),consequent:r(n.consequent),alternate:r(n.alternate)};case"inExpr":return{...n,element:r(n.element),collection:r(n.collection)};case"isExpr":return{...n,value:r(n.value)};case"listLiteral":return{...n,elements:n.elements.map(r)};case"mapLiteral":return{...n,entries:n.entries.map(s=>({key:r(s.key),value:r(s.value)}))};case"pathLiteral":return{...n,segments:n.segments.map(s=>typeof s=="string"?s:r(s))};case"functionCall":return{...n,args:n.args.map(r)}}};return r(t)}function $d(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 qd(t,e){return t===e}class jt extends te{typeName="reference";path;constructor(e){super(),this.path=Ud(e)}static fromResourceName(e){return new jt(Ko(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 jt?this.path===e.path:!1}field(e){switch(e){case"path":return this.path;case"id":return this.id;case"parent":return this.parent;default:return null}}callMethod(e,r){return ue}}function Ud(t){let e=Ko(t);return e.startsWith("/")&&(e=e.slice(1)),e.endsWith("/")&&(e=e.slice(0,-1)),e}function Ko(t){const e="/documents/",r=t.indexOf(e);return r===-1?t:t.slice(r+e.length)}class Wt extends te{typeName="vector";value;constructor(e){if(super(),!Array.isArray(e))throw new TypeError("Vector: value must be a number[]");for(let r=0;r<e.length;r++)if(typeof e[r]!="number")throw new TypeError(`Vector: element at index ${r} is not a number (got ${typeof e[r]})`);this.value=Object.freeze(e.slice())}get dimension(){return this.value.length}valueOf(){return NaN}toString(){return`[${this.value.join(", ")}]`}toJSON(){return{__type__:"__vector__",value:this.value.slice()}}equals(e){if(!(e instanceof Wt)||e.value.length!==this.value.length)return!1;for(let r=0;r<this.value.length;r++)if(e.value[r]!==this.value[r])return!1;return!0}callMethod(e,r){return ue}}var Y;(function(t){t.assertEqual=s=>{};function e(s){}t.assertIs=e;function r(s){throw new Error}t.assertNever=r,t.arrayToEnum=s=>{const i={};for(const a of s)i[a]=a;return i},t.getValidEnumValues=s=>{const i=t.objectKeys(s).filter(o=>typeof s[s[o]]!="number"),a={};for(const o of i)a[o]=s[o];return t.objectValues(a)},t.objectValues=s=>t.objectKeys(s).map(function(i){return s[i]}),t.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const i=[];for(const a in s)Object.prototype.hasOwnProperty.call(s,a)&&i.push(a);return i},t.find=(s,i)=>{for(const a of s)if(i(a))return a},t.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,i=" | "){return s.map(a=>typeof a=="string"?`'${a}'`:a).join(i)}t.joinValues=n,t.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(Y||(Y={}));var ia;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(ia||(ia={}));const M=Y.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),yt=t=>{switch(typeof t){case"undefined":return M.undefined;case"string":return M.string;case"number":return Number.isNaN(t)?M.nan:M.number;case"boolean":return M.boolean;case"function":return M.function;case"bigint":return M.bigint;case"symbol":return M.symbol;case"object":return Array.isArray(t)?M.array:t===null?M.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?M.promise:typeof Map<"u"&&t instanceof Map?M.map:typeof Set<"u"&&t instanceof Set?M.set:typeof Date<"u"&&t instanceof Date?M.date:M.object;default:return M.unknown}},R=Y.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 ft extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};const r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){const r=e||function(i){return i.message},n={_errors:[]},s=i=>{for(const a of i.issues)if(a.code==="invalid_union")a.unionErrors.map(s);else if(a.code==="invalid_return_type")s(a.returnTypeError);else if(a.code==="invalid_arguments")s(a.argumentsError);else if(a.path.length===0)n._errors.push(r(a));else{let o=n,c=0;for(;c<a.path.length;){const u=a.path[c];c===a.path.length-1?(o[u]=o[u]||{_errors:[]},o[u]._errors.push(r(a))):o[u]=o[u]||{_errors:[]},o=o[u],c++}}};return s(this),n}static assert(e){if(!(e instanceof ft))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Y.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){const r={},n=[];for(const s of this.issues)if(s.path.length>0){const i=s.path[0];r[i]=r[i]||[],r[i].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}}ft.create=t=>new ft(t);const _s=(t,e)=>{let r;switch(t.code){case R.invalid_type:t.received===M.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case R.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,Y.jsonStringifyReplacer)}`;break;case R.unrecognized_keys:r=`Unrecognized key(s) in object: ${Y.joinValues(t.keys,", ")}`;break;case R.invalid_union:r="Invalid input";break;case R.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Y.joinValues(t.options)}`;break;case R.invalid_enum_value:r=`Invalid enum value. Expected ${Y.joinValues(t.options)}, received '${t.received}'`;break;case R.invalid_arguments:r="Invalid function arguments";break;case R.invalid_return_type:r="Invalid function return type";break;case R.invalid_date:r="Invalid date";break;case R.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:Y.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case R.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case R.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case R.custom:r="Invalid input";break;case R.invalid_intersection_types:r="Intersection results could not be merged";break;case R.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case R.not_finite:r="Number must be finite";break;default:r=e.defaultError,Y.assertNever(t)}return{message:r}};let Bd=_s;function zd(){return Bd}const Vd=t=>{const{data:e,path:r,errorMaps:n,issueData:s}=t,i=[...r,...s.path||[]],a={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let o="";const c=n.filter(u=>!!u).slice().reverse();for(const u of c)o=u(a,{data:e,defaultError:o}).message;return{...s,path:i,message:o}};function F(t,e){const r=zd(),n=Vd({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===_s?void 0:_s].filter(s=>!!s)});t.common.issues.push(n)}class je{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){const n=[];for(const s of r){if(s.status==="aborted")return U;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){const n=[];for(const s of r){const i=await s.key,a=await s.value;n.push({key:i,value:a})}return je.mergeObjectSync(e,n)}static mergeObjectSync(e,r){const n={};for(const s of r){const{key:i,value:a}=s;if(i.status==="aborted"||a.status==="aborted")return U;i.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof a.value<"u"||s.alwaysSet)&&(n[i.value]=a.value)}return{status:e.value,value:n}}}const U=Object.freeze({status:"aborted"}),mr=t=>({status:"dirty",value:t}),Ve=t=>({status:"valid",value:t}),aa=t=>t.status==="aborted",oa=t=>t.status==="dirty",er=t=>t.status==="valid",cn=t=>typeof Promise<"u"&&t instanceof Promise;var P;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(P||(P={}));class nt{constructor(e,r,n,s){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const ca=(t,e)=>{if(er(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const r=new ft(t.common.issues);return this._error=r,this._error}}};function H(t){if(!t)return{};const{errorMap:e,invalid_type_error:r,required_error:n,description:s}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(a,o)=>{const{message:c}=t;return a.code==="invalid_enum_value"?{message:c??o.defaultError}:typeof o.data>"u"?{message:c??n??o.defaultError}:a.code!=="invalid_type"?{message:o.defaultError}:{message:c??r??o.defaultError}},description:s}}class K{get description(){return this._def.description}_getType(e){return yt(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:yt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new je,ctx:{common:e.parent.common,data:e.data,parsedType:yt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const r=this._parse(e);if(cn(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){const r=this._parse(e);return Promise.resolve(r)}parse(e,r){const n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){const n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:yt(e)},s=this._parseSync({data:e,path:n.path,parent:n});return ca(n,s)}"~validate"(e){const r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:yt(e)};if(!this["~standard"].async)try{const n=this._parseSync({data:e,path:[],parent:r});return er(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>er(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){const n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){const n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:yt(e)},s=this._parse({data:e,path:n.path,parent:n}),i=await(cn(s)?s:Promise.resolve(s));return ca(n,i)}refine(e,r){const n=s=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(s):r;return this._refinement((s,i)=>{const a=e(s),o=()=>i.addIssue({code:R.custom,...n(s)});return typeof Promise<"u"&&a instanceof Promise?a.then(c=>c?!0:(o(),!1)):a?!0:(o(),!1)})}refinement(e,r){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof r=="function"?r(n,s):r),!1))}_refinement(e){return new Pt({schema:this,typeName:B.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return dt.create(this,this._def)}nullable(){return $t.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return et.create(this)}promise(){return mn.create(this,this._def)}or(e){return dn.create([this,e],this._def)}and(e){return hn.create(this,e,this._def)}transform(e){return new Pt({...H(this._def),schema:this,typeName:B.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const r=typeof e=="function"?e:()=>e;return new gn({...H(this._def),innerType:this,defaultValue:r,typeName:B.ZodDefault})}brand(){return new Yo({typeName:B.ZodBranded,type:this,...H(this._def)})}catch(e){const r=typeof e=="function"?e:()=>e;return new yn({...H(this._def),innerType:this,catchValue:r,typeName:B.ZodCatch})}describe(e){const r=this.constructor;return new r({...this._def,description:e})}pipe(e){return oi.create(this,e)}readonly(){return bn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Wd=/^c[^\s-]{8,}$/i,Hd=/^[0-9a-z]+$/,Gd=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Kd=/^[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,Zd=/^[a-z0-9_-]{21}$/i,Jd=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Qd=/^[-+]?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)?)??$/,Yd=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Xd="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Yn;const eh=/^(?:(?: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])$/,th=/^(?:(?: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])$/,rh=/^(([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]))$/,nh=/^(([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])$/,sh=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ih=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Zo="((\\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])))",ah=new RegExp(`^${Zo}$`);function Jo(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);const r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function oh(t){return new RegExp(`^${Jo(t)}$`)}function ch(t){let e=`${Zo}T${Jo(t)}`;const r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function uh(t,e){return!!((e==="v4"||!e)&&eh.test(t)||(e==="v6"||!e)&&rh.test(t))}function lh(t,e){if(!Jd.test(t))return!1;try{const[r]=t.split(".");if(!r)return!1;const n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),s=JSON.parse(atob(n));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function dh(t,e){return!!((e==="v4"||!e)&&th.test(t)||(e==="v6"||!e)&&nh.test(t))}class ut extends K{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==M.string){const i=this._getOrReturnCtx(e);return F(i,{code:R.invalid_type,expected:M.string,received:i.parsedType}),U}const n=new je;let s;for(const i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),F(s,{code:R.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),F(s,{code:R.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="length"){const a=e.data.length>i.value,o=e.data.length<i.value;(a||o)&&(s=this._getOrReturnCtx(e,s),a?F(s,{code:R.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):o&&F(s,{code:R.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),n.dirty())}else if(i.kind==="email")Yd.test(e.data)||(s=this._getOrReturnCtx(e,s),F(s,{validation:"email",code:R.invalid_string,message:i.message}),n.dirty());else if(i.kind==="emoji")Yn||(Yn=new RegExp(Xd,"u")),Yn.test(e.data)||(s=this._getOrReturnCtx(e,s),F(s,{validation:"emoji",code:R.invalid_string,message:i.message}),n.dirty());else if(i.kind==="uuid")Kd.test(e.data)||(s=this._getOrReturnCtx(e,s),F(s,{validation:"uuid",code:R.invalid_string,message:i.message}),n.dirty());else if(i.kind==="nanoid")Zd.test(e.data)||(s=this._getOrReturnCtx(e,s),F(s,{validation:"nanoid",code:R.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid")Wd.test(e.data)||(s=this._getOrReturnCtx(e,s),F(s,{validation:"cuid",code:R.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid2")Hd.test(e.data)||(s=this._getOrReturnCtx(e,s),F(s,{validation:"cuid2",code:R.invalid_string,message:i.message}),n.dirty());else if(i.kind==="ulid")Gd.test(e.data)||(s=this._getOrReturnCtx(e,s),F(s,{validation:"ulid",code:R.invalid_string,message:i.message}),n.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),F(s,{validation:"url",code:R.invalid_string,message:i.message}),n.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),F(s,{validation:"regex",code:R.invalid_string,message:i.message}),n.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),F(s,{code:R.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),n.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),F(s,{code:R.invalid_string,validation:{startsWith:i.value},message:i.message}),n.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),F(s,{code:R.invalid_string,validation:{endsWith:i.value},message:i.message}),n.dirty()):i.kind==="datetime"?ch(i).test(e.data)||(s=this._getOrReturnCtx(e,s),F(s,{code:R.invalid_string,validation:"datetime",message:i.message}),n.dirty()):i.kind==="date"?ah.test(e.data)||(s=this._getOrReturnCtx(e,s),F(s,{code:R.invalid_string,validation:"date",message:i.message}),n.dirty()):i.kind==="time"?oh(i).test(e.data)||(s=this._getOrReturnCtx(e,s),F(s,{code:R.invalid_string,validation:"time",message:i.message}),n.dirty()):i.kind==="duration"?Qd.test(e.data)||(s=this._getOrReturnCtx(e,s),F(s,{validation:"duration",code:R.invalid_string,message:i.message}),n.dirty()):i.kind==="ip"?uh(e.data,i.version)||(s=this._getOrReturnCtx(e,s),F(s,{validation:"ip",code:R.invalid_string,message:i.message}),n.dirty()):i.kind==="jwt"?lh(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),F(s,{validation:"jwt",code:R.invalid_string,message:i.message}),n.dirty()):i.kind==="cidr"?dh(e.data,i.version)||(s=this._getOrReturnCtx(e,s),F(s,{validation:"cidr",code:R.invalid_string,message:i.message}),n.dirty()):i.kind==="base64"?sh.test(e.data)||(s=this._getOrReturnCtx(e,s),F(s,{validation:"base64",code:R.invalid_string,message:i.message}),n.dirty()):i.kind==="base64url"?ih.test(e.data)||(s=this._getOrReturnCtx(e,s),F(s,{validation:"base64url",code:R.invalid_string,message:i.message}),n.dirty()):Y.assertNever(i);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(s=>e.test(s),{validation:r,code:R.invalid_string,...P.errToObj(n)})}_addCheck(e){return new ut({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...P.errToObj(e)})}url(e){return this._addCheck({kind:"url",...P.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...P.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...P.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...P.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...P.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...P.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...P.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...P.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...P.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...P.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...P.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...P.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...P.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...P.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...P.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...P.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...P.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...P.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...P.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...P.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...P.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...P.errToObj(r)})}nonempty(e){return this.min(1,P.errToObj(e))}trim(){return new ut({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ut({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ut({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}}ut.create=t=>new ut({checks:[],typeName:B.ZodString,coerce:t?.coerce??!1,...H(t)});function hh(t,e){const r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=r>n?r:n,i=Number.parseInt(t.toFixed(s).replace(".","")),a=Number.parseInt(e.toFixed(s).replace(".",""));return i%a/10**s}class tr 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)!==M.number){const i=this._getOrReturnCtx(e);return F(i,{code:R.invalid_type,expected:M.number,received:i.parsedType}),U}let n;const s=new je;for(const i of this._def.checks)i.kind==="int"?Y.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{code:R.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),F(n,{code:R.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),F(n,{code:R.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?hh(e.data,i.value)!==0&&(n=this._getOrReturnCtx(e,n),F(n,{code:R.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{code:R.not_finite,message:i.message}),s.dirty()):Y.assertNever(i);return{status:s.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,P.toString(r))}gt(e,r){return this.setLimit("min",e,!1,P.toString(r))}lte(e,r){return this.setLimit("max",e,!0,P.toString(r))}lt(e,r){return this.setLimit("max",e,!1,P.toString(r))}setLimit(e,r,n,s){return new tr({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:P.toString(s)}]})}_addCheck(e){return new tr({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:P.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:P.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:P.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:P.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:P.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:P.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:P.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:P.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:P.toString(e)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&Y.isInteger(e.value))}get isFinite(){let e=null,r=null;for(const n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}}tr.create=t=>new tr({checks:[],typeName:B.ZodNumber,coerce:t?.coerce||!1,...H(t)});class Ar 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)!==M.bigint)return this._getInvalidInput(e);let n;const s=new je;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),F(n,{code:R.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),F(n,{code:R.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),F(n,{code:R.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):Y.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){const r=this._getOrReturnCtx(e);return F(r,{code:R.invalid_type,expected:M.bigint,received:r.parsedType}),U}gte(e,r){return this.setLimit("min",e,!0,P.toString(r))}gt(e,r){return this.setLimit("min",e,!1,P.toString(r))}lte(e,r){return this.setLimit("max",e,!0,P.toString(r))}lt(e,r){return this.setLimit("max",e,!1,P.toString(r))}setLimit(e,r,n,s){return new Ar({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:P.toString(s)}]})}_addCheck(e){return new Ar({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:P.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:P.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:P.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:P.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:P.toString(r)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}}Ar.create=t=>new Ar({checks:[],typeName:B.ZodBigInt,coerce:t?.coerce??!1,...H(t)});class As extends K{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==M.boolean){const n=this._getOrReturnCtx(e);return F(n,{code:R.invalid_type,expected:M.boolean,received:n.parsedType}),U}return Ve(e.data)}}As.create=t=>new As({typeName:B.ZodBoolean,coerce:t?.coerce||!1,...H(t)});class un extends K{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==M.date){const i=this._getOrReturnCtx(e);return F(i,{code:R.invalid_type,expected:M.date,received:i.parsedType}),U}if(Number.isNaN(e.data.getTime())){const i=this._getOrReturnCtx(e);return F(i,{code:R.invalid_date}),U}const n=new je;let s;for(const i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),F(s,{code:R.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),n.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),F(s,{code:R.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),n.dirty()):Y.assertNever(i);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new un({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:P.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:P.toString(r)})}get minDate(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}}un.create=t=>new un({checks:[],coerce:t?.coerce||!1,typeName:B.ZodDate,...H(t)});class ua extends K{_parse(e){if(this._getType(e)!==M.symbol){const n=this._getOrReturnCtx(e);return F(n,{code:R.invalid_type,expected:M.symbol,received:n.parsedType}),U}return Ve(e.data)}}ua.create=t=>new ua({typeName:B.ZodSymbol,...H(t)});class xs extends K{_parse(e){if(this._getType(e)!==M.undefined){const n=this._getOrReturnCtx(e);return F(n,{code:R.invalid_type,expected:M.undefined,received:n.parsedType}),U}return Ve(e.data)}}xs.create=t=>new xs({typeName:B.ZodUndefined,...H(t)});class ln extends K{_parse(e){if(this._getType(e)!==M.null){const n=this._getOrReturnCtx(e);return F(n,{code:R.invalid_type,expected:M.null,received:n.parsedType}),U}return Ve(e.data)}}ln.create=t=>new ln({typeName:B.ZodNull,...H(t)});class la extends K{constructor(){super(...arguments),this._any=!0}_parse(e){return Ve(e.data)}}la.create=t=>new la({typeName:B.ZodAny,...H(t)});class Is extends K{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ve(e.data)}}Is.create=t=>new Is({typeName:B.ZodUnknown,...H(t)});class _t extends K{_parse(e){const r=this._getOrReturnCtx(e);return F(r,{code:R.invalid_type,expected:M.never,received:r.parsedType}),U}}_t.create=t=>new _t({typeName:B.ZodNever,...H(t)});class da extends K{_parse(e){if(this._getType(e)!==M.undefined){const n=this._getOrReturnCtx(e);return F(n,{code:R.invalid_type,expected:M.void,received:n.parsedType}),U}return Ve(e.data)}}da.create=t=>new da({typeName:B.ZodVoid,...H(t)});class et extends K{_parse(e){const{ctx:r,status:n}=this._processInputParams(e),s=this._def;if(r.parsedType!==M.array)return F(r,{code:R.invalid_type,expected:M.array,received:r.parsedType}),U;if(s.exactLength!==null){const a=r.data.length>s.exactLength.value,o=r.data.length<s.exactLength.value;(a||o)&&(F(r,{code:a?R.too_big:R.too_small,minimum:o?s.exactLength.value:void 0,maximum:a?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&r.data.length<s.minLength.value&&(F(r,{code:R.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&r.data.length>s.maxLength.value&&(F(r,{code:R.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((a,o)=>s.type._parseAsync(new nt(r,a,r.path,o)))).then(a=>je.mergeArray(n,a));const i=[...r.data].map((a,o)=>s.type._parseSync(new nt(r,a,r.path,o)));return je.mergeArray(n,i)}get element(){return this._def.type}min(e,r){return new et({...this._def,minLength:{value:e,message:P.toString(r)}})}max(e,r){return new et({...this._def,maxLength:{value:e,message:P.toString(r)}})}length(e,r){return new et({...this._def,exactLength:{value:e,message:P.toString(r)}})}nonempty(e){return this.min(1,e)}}et.create=(t,e)=>new et({type:t,minLength:null,maxLength:null,exactLength:null,typeName:B.ZodArray,...H(e)});function Zt(t){if(t instanceof me){const e={};for(const r in t.shape){const n=t.shape[r];e[r]=dt.create(Zt(n))}return new me({...t._def,shape:()=>e})}else return t instanceof et?new et({...t._def,type:Zt(t.element)}):t instanceof dt?dt.create(Zt(t.unwrap())):t instanceof $t?$t.create(Zt(t.unwrap())):t instanceof Dt?Dt.create(t.items.map(e=>Zt(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(),r=Y.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==M.object){const u=this._getOrReturnCtx(e);return F(u,{code:R.invalid_type,expected:M.object,received:u.parsedType}),U}const{status:n,ctx:s}=this._processInputParams(e),{shape:i,keys:a}=this._getCached(),o=[];if(!(this._def.catchall instanceof _t&&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 nt(s,l,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof _t){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&&(F(s,{code:R.unrecognized_keys,keys:o}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const u=this._def.catchall;for(const d of o){const l=s.data[d];c.push({key:{status:"valid",value:d},value:u._parse(new nt(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,f=await d.value;u.push({key:l,value:f,alwaysSet:d.alwaysSet})}return u}).then(u=>je.mergeObjectSync(n,u)):je.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return P.errToObj,new me({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{const s=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:P.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new 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,r){return this.augment({[e]:r})}catchall(e){return new me({...this._def,catchall:e})}pick(e){const r={};for(const n of Y.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new me({...this._def,shape:()=>r})}omit(e){const r={};for(const n of Y.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new me({...this._def,shape:()=>r})}deepPartial(){return Zt(this)}partial(e){const r={};for(const n of Y.objectKeys(this.shape)){const s=this.shape[n];e&&!e[n]?r[n]=s:r[n]=s.optional()}return new me({...this._def,shape:()=>r})}required(e){const r={};for(const n of Y.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let i=this.shape[n];for(;i instanceof dt;)i=i._def.innerType;r[n]=i}return new me({...this._def,shape:()=>r})}keyof(){return Qo(Y.objectKeys(this.shape))}}me.create=(t,e)=>new me({shape:()=>t,unknownKeys:"strip",catchall:_t.create(),typeName:B.ZodObject,...H(e)});me.strictCreate=(t,e)=>new me({shape:()=>t,unknownKeys:"strict",catchall:_t.create(),typeName:B.ZodObject,...H(e)});me.lazycreate=(t,e)=>new me({shape:t,unknownKeys:"strip",catchall:_t.create(),typeName:B.ZodObject,...H(e)});class dn extends K{_parse(e){const{ctx:r}=this._processInputParams(e),n=this._def.options;function s(i){for(const o of i)if(o.result.status==="valid")return o.result;for(const o of i)if(o.result.status==="dirty")return r.common.issues.push(...o.ctx.common.issues),o.result;const a=i.map(o=>new ft(o.ctx.common.issues));return F(r,{code:R.invalid_union,unionErrors:a}),U}if(r.common.async)return Promise.all(n.map(async i=>{const a={...r,common:{...r.common,issues:[]},parent:null};return{result:await i._parseAsync({data:r.data,path:r.path,parent:a}),ctx:a}})).then(s);{let i;const a=[];for(const c of n){const u={...r,common:{...r.common,issues:[]},parent:null},d=c._parseSync({data:r.data,path:r.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 r.common.issues.push(...i.ctx.common.issues),i.result;const o=a.map(c=>new ft(c));return F(r,{code:R.invalid_union,unionErrors:o}),U}}get options(){return this._def.options}}dn.create=(t,e)=>new dn({options:t,typeName:B.ZodUnion,...H(e)});const ct=t=>t instanceof Es?ct(t.schema):t instanceof Pt?ct(t.innerType()):t instanceof pn?[t.value]:t instanceof Mt?t.options:t instanceof Os?Y.objectValues(t.enum):t instanceof gn?ct(t._def.innerType):t instanceof xs?[void 0]:t instanceof ln?[null]:t instanceof dt?[void 0,...ct(t.unwrap())]:t instanceof $t?[null,...ct(t.unwrap())]:t instanceof Yo||t instanceof bn?ct(t.unwrap()):t instanceof yn?ct(t._def.innerType):[];class ai extends K{_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==M.object)return F(r,{code:R.invalid_type,expected:M.object,received:r.parsedType}),U;const n=this.discriminator,s=r.data[n],i=this.optionsMap.get(s);return i?r.common.async?i._parseAsync({data:r.data,path:r.path,parent:r}):i._parseSync({data:r.data,path:r.path,parent:r}):(F(r,{code:R.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),U)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){const s=new Map;for(const i of r){const a=ct(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:r,optionsMap:s,...H(n)})}}function ks(t,e){const r=yt(t),n=yt(e);if(t===e)return{valid:!0,data:t};if(r===M.object&&n===M.object){const s=Y.objectKeys(e),i=Y.objectKeys(t).filter(o=>s.indexOf(o)!==-1),a={...t,...e};for(const o of i){const c=ks(t[o],e[o]);if(!c.valid)return{valid:!1};a[o]=c.data}return{valid:!0,data:a}}else if(r===M.array&&n===M.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=ks(a,o);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return r===M.date&&n===M.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}class hn extends K{_parse(e){const{status:r,ctx:n}=this._processInputParams(e),s=(i,a)=>{if(aa(i)||aa(a))return U;const o=ks(i.value,a.value);return o.valid?((oa(i)||oa(a))&&r.dirty(),{status:r.value,value:o.data}):(F(n,{code:R.invalid_intersection_types}),U)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([i,a])=>s(i,a)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}hn.create=(t,e,r)=>new hn({left:t,right:e,typeName:B.ZodIntersection,...H(r)});class Dt extends K{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.array)return F(n,{code:R.invalid_type,expected:M.array,received:n.parsedType}),U;if(n.data.length<this._def.items.length)return F(n,{code:R.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),U;!this._def.rest&&n.data.length>this._def.items.length&&(F(n,{code:R.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());const i=[...n.data].map((a,o)=>{const c=this._def.items[o]||this._def.rest;return c?c._parse(new nt(n,a,n.path,o)):null}).filter(a=>!!a);return n.common.async?Promise.all(i).then(a=>je.mergeArray(r,a)):je.mergeArray(r,i)}get items(){return this._def.items}rest(e){return new Dt({...this._def,rest:e})}}Dt.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Dt({items:t,typeName:B.ZodTuple,rest:null,...H(e)})};class fn extends K{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.object)return F(n,{code:R.invalid_type,expected:M.object,received:n.parsedType}),U;const s=[],i=this._def.keyType,a=this._def.valueType;for(const o in n.data)s.push({key:i._parse(new nt(n,o,n.path,o)),value:a._parse(new nt(n,n.data[o],n.path,o)),alwaysSet:o in n.data});return n.common.async?je.mergeObjectAsync(r,s):je.mergeObjectSync(r,s)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof K?new fn({keyType:e,valueType:r,typeName:B.ZodRecord,...H(n)}):new fn({keyType:ut.create(),valueType:e,typeName:B.ZodRecord,...H(r)})}}class ha extends K{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.map)return F(n,{code:R.invalid_type,expected:M.map,received:n.parsedType}),U;const s=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([o,c],u)=>({key:s._parse(new nt(n,o,n.path,[u,"key"])),value:i._parse(new nt(n,c,n.path,[u,"value"]))}));if(n.common.async){const o=new Map;return Promise.resolve().then(async()=>{for(const c of a){const u=await c.key,d=await c.value;if(u.status==="aborted"||d.status==="aborted")return U;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),o.set(u.value,d.value)}return{status:r.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")&&r.dirty(),o.set(u.value,d.value)}return{status:r.value,value:o}}}}ha.create=(t,e,r)=>new ha({valueType:e,keyType:t,typeName:B.ZodMap,...H(r)});class xr extends K{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.set)return F(n,{code:R.invalid_type,expected:M.set,received:n.parsedType}),U;const s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(F(n,{code:R.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),r.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(F(n,{code:R.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),r.dirty());const i=this._def.valueType;function a(c){const u=new Set;for(const d of c){if(d.status==="aborted")return U;d.status==="dirty"&&r.dirty(),u.add(d.value)}return{status:r.value,value:u}}const o=[...n.data.values()].map((c,u)=>i._parse(new nt(n,c,n.path,u)));return n.common.async?Promise.all(o).then(c=>a(c)):a(o)}min(e,r){return new xr({...this._def,minSize:{value:e,message:P.toString(r)}})}max(e,r){return new xr({...this._def,maxSize:{value:e,message:P.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}}xr.create=(t,e)=>new xr({valueType:t,minSize:null,maxSize:null,typeName:B.ZodSet,...H(e)});class Es extends K{get schema(){return this._def.getter()}_parse(e){const{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}}Es.create=(t,e)=>new Es({getter:t,typeName:B.ZodLazy,...H(e)});class pn extends K{_parse(e){if(e.data!==this._def.value){const r=this._getOrReturnCtx(e);return F(r,{received:r.data,code:R.invalid_literal,expected:this._def.value}),U}return{status:"valid",value:e.data}}get value(){return this._def.value}}pn.create=(t,e)=>new pn({value:t,typeName:B.ZodLiteral,...H(e)});function Qo(t,e){return new Mt({values:t,typeName:B.ZodEnum,...H(e)})}class Mt extends K{_parse(e){if(typeof e.data!="string"){const r=this._getOrReturnCtx(e),n=this._def.values;return F(r,{expected:Y.joinValues(n),received:r.parsedType,code:R.invalid_type}),U}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const r=this._getOrReturnCtx(e),n=this._def.values;return F(r,{received:r.data,code:R.invalid_enum_value,options:n}),U}return Ve(e.data)}get options(){return this._def.values}get enum(){const e={};for(const r of this._def.values)e[r]=r;return e}get Values(){const e={};for(const r of this._def.values)e[r]=r;return e}get Enum(){const e={};for(const r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return Mt.create(e,{...this._def,...r})}exclude(e,r=this._def){return Mt.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}}Mt.create=Qo;class Os extends K{_parse(e){const r=Y.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==M.string&&n.parsedType!==M.number){const s=Y.objectValues(r);return F(n,{expected:Y.joinValues(s),received:n.parsedType,code:R.invalid_type}),U}if(this._cache||(this._cache=new Set(Y.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const s=Y.objectValues(r);return F(n,{received:n.data,code:R.invalid_enum_value,options:s}),U}return Ve(e.data)}get enum(){return this._def.values}}Os.create=(t,e)=>new Os({values:t,typeName:B.ZodNativeEnum,...H(e)});class mn extends K{unwrap(){return this._def.type}_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==M.promise&&r.common.async===!1)return F(r,{code:R.invalid_type,expected:M.promise,received:r.parsedType}),U;const n=r.parsedType===M.promise?r.data:Promise.resolve(r.data);return Ve(n.then(s=>this._def.type.parseAsync(s,{path:r.path,errorMap:r.common.contextualErrorMap})))}}mn.create=(t,e)=>new mn({type:t,typeName:B.ZodPromise,...H(e)});class Pt extends K{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===B.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:r,ctx:n}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:a=>{F(n,a),a.fatal?r.abort():r.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){const a=s.transform(n.data,i);if(n.common.async)return Promise.resolve(a).then(async o=>{if(r.value==="aborted")return U;const c=await this._def.schema._parseAsync({data:o,path:n.path,parent:n});return c.status==="aborted"?U:c.status==="dirty"||r.value==="dirty"?mr(c.value):c});{if(r.value==="aborted")return U;const o=this._def.schema._parseSync({data:a,path:n.path,parent:n});return o.status==="aborted"?U:o.status==="dirty"||r.value==="dirty"?mr(o.value):o}}if(s.type==="refinement"){const a=o=>{const c=s.refinement(o,i);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(n.common.async===!1){const o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?U:(o.status==="dirty"&&r.dirty(),a(o.value),{status:r.value,value:o.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>o.status==="aborted"?U:(o.status==="dirty"&&r.dirty(),a(o.value).then(()=>({status:r.value,value:o.value}))))}if(s.type==="transform")if(n.common.async===!1){const a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!er(a))return U;const o=s.transform(a.value,i);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:o}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>er(a)?Promise.resolve(s.transform(a.value,i)).then(o=>({status:r.value,value:o})):U);Y.assertNever(s)}}Pt.create=(t,e,r)=>new Pt({schema:t,typeName:B.ZodEffects,effect:e,...H(r)});Pt.createWithPreprocess=(t,e,r)=>new Pt({schema:e,effect:{type:"preprocess",transform:t},typeName:B.ZodEffects,...H(r)});class dt extends K{_parse(e){return this._getType(e)===M.undefined?Ve(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}dt.create=(t,e)=>new dt({innerType:t,typeName:B.ZodOptional,...H(e)});class $t extends K{_parse(e){return this._getType(e)===M.null?Ve(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}$t.create=(t,e)=>new $t({innerType:t,typeName:B.ZodNullable,...H(e)});class gn extends K{_parse(e){const{ctx:r}=this._processInputParams(e);let n=r.data;return r.parsedType===M.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}}gn.create=(t,e)=>new gn({innerType:t,typeName:B.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...H(e)});class yn extends K{_parse(e){const{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return cn(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new ft(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new ft(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}yn.create=(t,e)=>new yn({innerType:t,typeName:B.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...H(e)});class fa extends K{_parse(e){if(this._getType(e)!==M.nan){const n=this._getOrReturnCtx(e);return F(n,{code:R.invalid_type,expected:M.nan,received:n.parsedType}),U}return{status:"valid",value:e.data}}}fa.create=t=>new fa({typeName:B.ZodNaN,...H(t)});class Yo extends K{_parse(e){const{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}}class oi extends K{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?U:i.status==="dirty"?(r.dirty(),mr(i.value)):this._def.out._parseAsync({data:i.value,path:n.path,parent:n})})();{const s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?U:s.status==="dirty"?(r.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,r){return new oi({in:e,out:r,typeName:B.ZodPipeline})}}class bn extends K{_parse(e){const r=this._def.innerType._parse(e),n=s=>(er(s)&&(s.value=Object.freeze(s.value)),s);return cn(r)?r.then(s=>n(s)):n(r)}unwrap(){return this._def.innerType}}bn.create=(t,e)=>new bn({innerType:t,typeName:B.ZodReadonly,...H(e)});var B;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(B||(B={}));const Ft=ut.create,pa=tr.create,ci=As.create,fh=ln.create,Ir=Is.create;_t.create;const ph=et.create,lt=me.create,ui=dn.create,mh=ai.create;hn.create;Dt.create;const kr=fn.create,qr=pn.create,vn=Mt.create;mn.create;dt.create;$t.create;const gh=["get","list","create","update","delete"],yh=lt({uid:Ft(),token:kr(Ir()).optional()}),bh=lt({function:vn(["get","exists"]).describe("Firestore function to mock"),path:Ft().describe('Document path, e.g. "users/alice"'),result:ui([kr(Ir()),ci()]).describe("Document data for get, boolean for exists")}),vh=mh("kind",[lt({kind:qr("create")}),lt({kind:qr("set"),merge:ci()}),lt({kind:qr("update")}),lt({kind:qr("delete")})]),wh=lt({limit:pa().optional(),offset:pa().optional(),orderBy:Ft().optional()});lt({description:Ft().describe("Human-readable description of what this test verifies"),expectation:vn(["ALLOW","DENY"]).describe("Expected outcome"),method:vn(gh).describe("Firestore method to test"),path:Ft().describe('Document path, e.g. "users/alice"'),auth:ui([yh,fh()]).optional().describe("Auth context; null or omitted for unauthenticated"),data:kr(Ir()).optional().describe("request.resource.data for write operations"),resource:kr(Ir()).optional().describe("Existing document data (resource.data)"),functionMocks:ph(bh).optional().describe("Mock get()/exists() calls in rules"),query:wh.optional().describe("request.query payload (list ops only): limit/offset/orderBy."),requestTime:Ft().optional().describe("Override for request.time (ISO-8601). Defaults to wallclock."),writeMode:vh.optional().describe("Optional write-mode override; controls update merge semantics and getAfter() projection.")});function Er(t){if(t.decision==="UNSUPPORTED")return;const e=t.decision==="ALLOW",r=e?t.trace.find(s=>s.verdict==="ALLOW"):t.trace.find(s=>s.verdict==="DENY"||s.verdict==="ERROR")??t.trace[t.trace.length-1];if(!r)return;const n={verdict:e?"allow":"deny"};return r.line!==void 0&&(n.line=r.line),r.conditionText!==void 0&&(n.expression=r.conditionText),r.expressionTrace!==void 0&&(n.expressionTrace=r.expressionTrace),n.line!==void 0||n.expression!==void 0||n.expressionTrace!==void 0?n:void 0}function Se(t){const e=[];for(const r of t.notes)e.push(r);for(const r of t.trace){const n=r.operations.join(","),s=`Rule #${r.ruleIndex} (${n})`;r.verdict==="ALLOW"?e.push(`${s} → ALLOW`):r.verdict==="DENY"?e.push(`${s} → deny`):r.verdict==="UNSUPPORTED"?e.push(`${s} → unsupported: ${r.message??""}`):e.push(`${s} → error: ${r.message??""}`)}return e.push(`Simulated: ${t.decision}`),e}lt({function:vn(["get","exists"]).describe("Cross-service Firestore function to mock"),path:Ft().describe('Firestore document path in collection/doc form, e.g. "users/alice"'),result:ui([kr(Ir()),ci()]).describe("Document fields for get, boolean for exists")});const Xo={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(Xo).sort());const Sh={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:[]},ec=["exists","existsAfter","get","getAfter"],_h=["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"],Ah={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"]},tc={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"]},xh=["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"],Ih=["get","hasAll","keys","matches","size","split"],kh={get:["map"],hasAll:["set"],keys:["map"],matches:["string"],size:["list","map","string"],split:["string"]},rc={duration:["value"],firestore:["exists","get"],timestamp:["date","value"]},Eh=new Set(xh),Oh=["request.auth.token","request.resource.metadata","resource.metadata"];function Ch(t,e){if(e.length===1)return!0;if(t==="firebase.storage"){const r=e.join(".");return Eh.has(r)||Oh.some(n=>r.startsWith(`${n}.`))}return e[0]==="request"?e[1]==="auth"||e[1]==="query"?!0:["time","method","path"].includes(e[1])?e.length===2:e[1]==="resource"&&(e.length===2||e[2]==="data"):e[0]==="resource"&&(e.length===1||e[1]==="data")}function wn(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 Th(t,e){if(!e||e==="unknown-ambient")return null;const r=e.join(".");return r==="request.resource"||r==="resource"?"resource":r==="request.auth"||r==="request.auth.token"||t==="cloud.firestore"&&(r==="request.resource.data"||r==="resource.data"||r==="request.query")||r==="request.resource.metadata"||r==="resource.metadata"?"map":r==="request.auth.uid"||r==="request.method"||r==="request.resource.contentType"||r==="resource.contentType"||t==="firebase.storage"&&(r.startsWith("request.resource.metadata.")||r.startsWith("resource.metadata."))?"string":r==="request.path"?"path":r==="request.time"||r==="resource.timeCreated"||r==="resource.updated"?"timestamp":["request.resource.size","resource.size","resource.generation","resource.metageneration"].includes(r)?"number":null}function ma(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 Rh=new Set(ec),Nh=Object.fromEntries(Object.entries(tc).map(([t,e])=>[t,new Set(e)])),Fh=Object.fromEntries(Object.entries(rc).map(([t,e])=>[t,new Set(e)]));function at(t,e){return t.some(r=>_e(r,e)!==null)?"unknown-ambient":null}function nc(t,e,r){const n=r.declarations?.get(t),s=new Map(n?.aliases),i=new Map(n?.receiverTypes);return t.parameters.forEach((a,o)=>{s.set(a,e[o]?.provenance??null),i.set(a,e[o]?.receiverType??null)}),{aliases:s,receiverTypes:i,functions:n?.functions??r.functions,service:r.service,stack:new Set([...r.stack,t.name]),declarations:r.declarations}}function rr(t,e){return{expression:t,provenance:_e(t,e),receiverType:he(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 r=_e(t.object,e);return r==="unknown-ambient"?r:r?[...r,t.property]:null}if(t.type==="bracketAccess"){const r=_e(t.object,e);return!r||r==="unknown-ambient"?r:t.index.type==="literal"&&typeof t.index.value=="string"?[...r,t.index.value]:[...r,"*"]}if(t.type==="ternary"){const r=_e(t.consequent,e),n=_e(t.alternate,e);return!r&&!n?null:Array.isArray(r)&&Array.isArray(n)&&r.join(".")===n.join(".")?r:"unknown-ambient"}if(t.type==="functionCall"){const r=e.functions.get(t.name),n=t.args.map(i=>rr(i,e));if(!r&&Rh.has(t.name))return null;if(!r||e.stack.has(r.name))return n.some(({provenance:i})=>i!==null)?"unknown-ambient":null;const s=nc(r,n,e);for(const i of r.lets){const a=rr(i.value,s);s.aliases.set(i.name,a.provenance),s.receiverTypes.set(i.name,a.receiverType)}return _e(r.body,s)}if(t.type==="methodCall"&&t.object.type==="identifier"&&t.object.name==="firestore"&&(t.method==="get"||t.method==="exists"))return null;switch(t.type){case"literal":return null;case"methodCall":return at([t.object,...t.args],e);case"sliceAccess":return at([t.object,t.start,t.end],e);case"binaryOp":return at([t.left,t.right],e);case"unaryOp":return at([t.operand],e);case"inExpr":return at([t.element,t.collection],e);case"isExpr":return at([t.value],e);case"listLiteral":return at(t.elements,e);case"mapLiteral":return at(t.entries.flatMap(({key:r,value:n})=>[r,n]),e);case"pathLiteral":return at(t.segments.filter(r=>typeof r!="string"),e);default:return null}}function he(t,e){const r=Th(e.service,_e(t,e));if(r)return r;switch(t.type){case"identifier":{const n=e.receiverTypes.get(t.name);return n||((e.service==="cloud.firestore"?Nh:Fh)[t.name]||t.name==="firestore"?"namespace":null)}case"literal":return t.value===null?"null":typeof t.value=="string"?"string":typeof t.value=="number"?"number":typeof t.value=="boolean"?"boolean":null;case"listLiteral":return"list";case"mapLiteral":return"map";case"pathLiteral":return"path";case"memberAccess":{const n=he(t.object,e);if(n==="mixed")return"mixed";if(t.property==="data"&&n==="document")return"map";if(t.object.type==="mapLiteral"){const s=t.object.entries.find(({key:i})=>i.type==="literal"&&i.value===t.property);return s?he(s.value,e):null}return null}case"bracketAccess":{const n=he(t.object,e);if(n==="mixed")return"mixed";if(t.object.type==="listLiteral"&&t.index.type==="literal"&&typeof t.index.value=="number"&&Number.isInteger(t.index.value)){const i=t.object.elements[t.index.value];return i?he(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?he(a.value,e):null}if(n==="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 n=he(t.object,e);return n==="mixed"?"mixed":n==="list"||n==="string"?n:null}case"methodCall":{const n=ma(t);if(t.object.type==="identifier"&&n)return n;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?he(o.value,e):i?he(i,e):null}return i&&he(i,e)?"mixed":null}return ma(t)}case"binaryOp":{const n=he(t.left,e),s=he(t.right,e);return t.op==="+"&&(n==="string"||s==="string")?"string":["==","!=","<","<=",">",">=","&&","||"].includes(t.op)?"boolean":["+","-","*","/","%"].includes(t.op)&&n==="number"&&s==="number"?"number":null}case"unaryOp":return t.op==="!"?"boolean":t.op==="-"&&he(t.operand,e)==="number"?"number":null;case"inExpr":case"isExpr":return"boolean";case"ternary":{const n=he(t.consequent,e),s=he(t.alternate,e);return!n&&!s?null:n===s?n:"mixed"}case"functionCall":{const n=e.functions.get(t.name);if(!n&&e.service==="cloud.firestore"){if(t.name==="get"||t.name==="getAfter")return"document";if(t.name==="exists")return"boolean"}if(!n||e.stack.has(n.name))return null;const s=nc(n,t.args.map(i=>rr(i,e)),e);for(const i of n.lets){const a=rr(i.value,s);s.aliases.set(i.name,a.provenance),s.receiverTypes.set(i.name,a.receiverType)}return he(n.body,s)}default:return null}}function Lh(t){return t.match(/^\.\/stdlib\/(.+?)(?:\.rules)?$/)?.[1]??t}function jh(t,e,r){const n=Lh(e),s=Xo[n];return s?s.includes(t)?null:`Function '${r}' from module '${e}' is not compatible with service '${t}'`:null}function Dh(t){throw new Error(`Unhandled Rules expression: ${JSON.stringify(t)}`)}const Mh=new Set(ec),Ph=new Set(_h),$h=Object.fromEntries(Object.entries(tc).map(([t,e])=>[t,new Set(e)])),qh=new Set(Ih),Uh=Object.fromEntries(Object.entries(rc).map(([t,e])=>[t,new Set(e)]));function Sn(t,e){return t==="unknown-ambient"?"binding '<derived ambient value>'":t&&!Ch(e,t)?`binding '${t.join(".")}'`:null}function Bh(t,e,r,n,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=r[0];if(a?.type==="literal"&&typeof a.value=="string")return Sn([...i,a.value],n);if(!wn(n,i))return`binding '${i.join(".")}.get(...)'`}return(e==="keys"||e==="values")&&!wn(n,i)?`binding '${i.join(".")}.${e}()'`:null}function zh(t,e,r,n){const s=_e(t,n),i=he(t,n);if(!i){if(s==="unknown-ambient")return"binding '<derived ambient receiver>'";let c=t;for(;c.type==="memberAccess"||c.type==="bracketAccess"||c.type==="methodCall"&&c.method==="get";)c=c.object;const u=he(c,n);return u==="map"||u==="list"||u==="document"?`method '.${e}()' has an unresolved projected receiver`:null}const o=(r==="cloud.firestore"?Ah:kh)[e];return o?.includes(i)?null:`method '.${e}()' requires ${o?.join("|")??"an accepted"} receiver, got ${i}`}function Vh(t,e,r,n){const s=_e(e,n);return s==="unknown-ambient"?"binding '<derived ambient value>'":s?t.type==="literal"&&typeof t.value=="string"?Sn([...s,t.value],r):wn(r,s)?null:`binding '<value> in ${s.join(".")}'`:null}function ga(t,e,r){const n=s=>{switch(s.type){case"memberAccess":{const i=Sn(_e(s,r),e);return i||n(s.object)}case"functionCall":{const i=r.functions.get(s.name);if(!i&&e==="firebase.storage")return`function '${s.name}()'`;if(!i&&!Mh.has(s.name))return`function '${s.name}()'`;for(const a of s.args){const o=n(a);if(o)return o}if(i&&!r.stack.has(i.name)){const a=new Map,o=new Map;i.parameters.forEach((u,d)=>{const l=s.args[d];a.set(u,l?_e(l,r):null),o.set(u,l?he(l,r):null)});const c=sc(i,e,{aliases:a,receiverTypes:o,functions:r.functions,service:e,stack:new Set([...r.stack,i.name])});if(c)return c}return null}case"methodCall":{if(s.object.type==="identifier"&&!r.aliases.has(s.object.name)){const u=(e==="cloud.firestore"?$h:Uh)[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=n(d);if(l)return l}return null}return s.object.name==="firestore"?`method 'firestore.${s.method}()'`:`namespace '${s.object.name}'`}if(!(e==="cloud.firestore"?Ph:qh).has(s.method))return`method '.${s.method}()'`;const a=zh(s.object,s.method,e,r);if(a)return a;const o=Bh(s.object,s.method,s.args,e,r);return o||(n(s.object)??s.args.map(n).find(Boolean)??null)}case"binaryOp":return n(s.left)??n(s.right);case"unaryOp":return n(s.operand);case"bracketAccess":{const i=_e(s.object,r);if(i==="unknown-ambient")return"binding '<derived ambient value>[...]'";const a=s.index.type==="literal"&&typeof s.index.value=="string";if(i&&!a)return wn(e,i)?n(s.object)??n(s.index):`binding '${i.join(".")}[...]'`;const o=Sn(_e(s,r),e);return o||(n(s.object)??n(s.index))}case"sliceAccess":return n(s.object)??n(s.start)??n(s.end);case"ternary":return n(s.condition)??n(s.consequent)??n(s.alternate);case"inExpr":return Vh(s.element,s.collection,e,r)??n(s.element)??n(s.collection);case"isExpr":return n(s.value);case"listLiteral":return s.elements.map(n).find(Boolean)??null;case"mapLiteral":for(const i of s.entries){const a=n(i.key)??n(i.value);if(a)return a}return null;case"pathLiteral":for(const i of s.segments)if(typeof i!="string"){const a=n(i);if(a)return a}return null;case"literal":return null;case"identifier":return s.name==="request"||s.name==="resource"||r.aliases.has(s.name)?null:`identifier '${s.name}'`;default:return Dh(s)}};return n(t)}function sc(t,e,r){const n=new Map(r.aliases),s=new Map(r.receiverTypes),i={...r,aliases:n,receiverTypes:s};for(const a of t.lets){const o=ga(a.value,e,i);if(o)return o;n.set(a.name,_e(a.value,i)),s.set(a.name,he(a.value,i))}return ga(t.body,e,i)}function Wh(t,e,r=new Map([[t.name,t]]),n=[]){const s={aliases:new Map,receiverTypes:new Map,functions:r,service:e,stack:new Set([t.name])};return sc(t,e,{aliases:new Map(t.parameters.map((i,a)=>[i,a<n.length?n[a]?.provenance??null:null])),receiverTypes:new Map(t.parameters.map((i,a)=>[i,n[a]?he(n[a].expression,s)??n[a].receiverType??null:null])),functions:r,service:e,stack:new Set([t.name])})}function Hh(t){throw new Error(`Unhandled Rules expression: ${JSON.stringify(t)}`)}function Gh(t){return t.replace(/^\.\.\//,"_").replace(/^\.\//,"").replace(/[.\/-]/g,"_")}function re(t,e){switch(t.type){case"functionCall":{const r=e.get(t.name)??t.name,n=t.args.map(s=>re(s,e));return r===t.name&&n.every((s,i)=>s===t.args[i])?t:{...t,name:r,args:n}}case"binaryOp":{const r=re(t.left,e),n=re(t.right,e);return r===t.left&&n===t.right?t:{...t,left:r,right:n}}case"unaryOp":{const r=re(t.operand,e);return r===t.operand?t:{...t,operand:r}}case"methodCall":{const r=re(t.object,e),n=t.args.map(s=>re(s,e));return r===t.object&&n.every((s,i)=>s===t.args[i])?t:{...t,object:r,args:n}}case"memberAccess":{const r=re(t.object,e);return r===t.object?t:{...t,object:r}}case"bracketAccess":{const r=re(t.object,e),n=re(t.index,e);return r===t.object&&n===t.index?t:{...t,object:r,index:n}}case"sliceAccess":{const r=re(t.object,e),n=re(t.start,e),s=re(t.end,e);return r===t.object&&n===t.start&&s===t.end?t:{...t,object:r,start:n,end:s}}case"ternary":{const r=re(t.condition,e),n=re(t.consequent,e),s=re(t.alternate,e);return r===t.condition&&n===t.consequent&&s===t.alternate?t:{...t,condition:r,consequent:n,alternate:s}}case"inExpr":{const r=re(t.element,e),n=re(t.collection,e);return r===t.element&&n===t.collection?t:{...t,element:r,collection:n}}case"isExpr":{const r=re(t.value,e);return r===t.value?t:{...t,value:r}}case"listLiteral":{const r=t.elements.map(n=>re(n,e));return r.every((n,s)=>n===t.elements[s])?t:{...t,elements:r}}case"mapLiteral":{const r=t.entries.map(n=>{const s=re(n.key,e),i=re(n.value,e);return s===n.key&&i===n.value?n:{key:s,value:i}});return r.every((n,s)=>n===t.entries[s])?t:{...t,entries:r}}case"pathLiteral":{const r=t.segments.map(n=>typeof n=="string"?n:re(n,e));return r.every((n,s)=>n===t.segments[s])?t:{...t,segments:r}}case"literal":case"identifier":return t;default:return Hh(t)}}function Kh(t,e){const r=Gh(e),n=new Map;for(const s of t)s.exported||n.set(s.name,`${r}__${s.name}`);return n.size===0?t:t.map(s=>{const i=re(s.body,n),a=s.lets.map(c=>{const u=re(c.value,n);return u===c.value?c:{...c,value:u}}),o=s.exported?s.name:n.get(s.name)??s.name;return i===s.body&&a===s.lets&&o===s.name?s:{...s,name:o,body:i,lets:a}})}function Zh(t){throw new Error(`Unhandled Rules expression: ${JSON.stringify(t)}`)}function li(t){const e=[],r=n=>{switch(n.type){case"functionCall":e.push(n),n.args.forEach(r);break;case"binaryOp":r(n.left),r(n.right);break;case"unaryOp":r(n.operand);break;case"methodCall":r(n.object),n.args.forEach(r);break;case"memberAccess":r(n.object);break;case"bracketAccess":r(n.object),r(n.index);break;case"sliceAccess":r(n.object),r(n.start),r(n.end);break;case"ternary":r(n.condition),r(n.consequent),r(n.alternate);break;case"inExpr":r(n.element),r(n.collection);break;case"isExpr":r(n.value);break;case"listLiteral":n.elements.forEach(r);break;case"mapLiteral":n.entries.forEach(({key:s,value:i})=>{r(s),r(i)});break;case"pathLiteral":n.segments.forEach(s=>{typeof s!="string"&&r(s)});break;case"literal":case"identifier":break;default:Zh(n)}};return r(t),e}function Jh(t){return{expression:t.expression,provenance:t.provenance,receiverType:!t.receiverType||t.receiverType==="mixed"?"unknown":t.receiverType}}function Qh(t,e){const r=[],n=new Map,s=t.service.name==="firebase.storage"?"firebase.storage":"cloud.firestore",i=(l,f=new Set)=>({aliases:new Map(l.aliases),receiverTypes:new Map(l.receiverTypes),functions:l.functions,service:s,stack:f,declarations:n}),a=(l,f,y)=>{if(y.has(l.name))return;const b=n.get(l);if(!b)return;const S=new Map(b.aliases),j=new Map(b.receiverTypes);l.parameters.forEach((L,k)=>{S.set(L,f[k]?.provenance??null),j.set(L,f[k]?.receiverType??null)});const T=i({aliases:S,receiverTypes:j,functions:b.functions},new Set([...y,l.name]));for(const L of l.lets){o(L.value,T);const k=rr(L.value,T);T.aliases.set(L.name,k.provenance),T.receiverTypes.set(L.name,k.receiverType)}o(l.body,T)},o=(l,f)=>{for(const y of li(l)){const b=y.args.map(j=>rr(j,f));y.name===e&&r.push({arguments:b.map(Jh)});const S=f.functions.get(y.name);S&&a(S,b,f.stack)}},c=new Map((t.functions??[]).map(l=>[l.name,l])),u=new Map(c);for(const l of t.service.functions??[])u.set(l.name,l);for(const l of t.functions??[])n.set(l,{aliases:new Map,receiverTypes:new Map,functions:c});for(const l of t.service.functions??[])n.set(l,{aliases:new Map,receiverTypes:new Map,functions:u});const d=(l,f)=>{const y=new Map(f.receiverTypes);for(const T of l.path.segments)T.type==="wildcard"&&y.set(T.name,"string"),T.type==="recursive"&&y.set(T.name,"path");const b=new Map(f.functions),S={aliases:f.aliases,receiverTypes:y,functions:b};for(const T of l.functions)b.set(T.name,T),n.set(T,S);const j=i(S);for(const{condition:T}of l.allows)o(T,j);l.children.forEach(T=>d(T,S))};return d(t.service.match,{aliases:new Map,receiverTypes:new Map,functions:u}),r}function Et(t){return li(t).map(({name:e})=>e)}function Yh(t,e){return[...t.values()].flatMap(n=>[...n.lets.map(({value:s})=>s),n.body]).flatMap(li).filter(({name:n})=>n===e).map(({args:n})=>n)}function Xh(t,e,r){const n=yl(t);return n?{success:!0,functions:n,bundled:r}:{success:!1,error:{code:"PARSE_FAILED",message:`Failed to parse module '${e}'`}}}function ya(t){return t.startsWith("./")||t.startsWith("../")}function Cs(t){return/^\.\/stdlib\/([A-Za-z0-9_-]+(?:\/[A-Za-z0-9_-]+)*)\.rules$/.exec(t)?.[1]??null}function ef(t,e,r,n=new Set){if(r?.modules&&Object.prototype.hasOwnProperty.call(r.modules,e))return Xh(r.modules[e],e,n.has(e));if(ya(e)&&r?.basePath){const i=`${r.basePath}/${e}${e.endsWith(".rules")?"":".rules"}`;if(!Cs(e))return{success:!1,error:{code:"UNKNOWN_MODULE",message:`Module '${e}' not found at ${i}`}}}return Cs(e)?{success:!1,error:{code:"UNKNOWN_MODULE",message:`Module '${e}' not found`}}:ya(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 tf(t,e,r,n=new Set){const s=Xr(e);if(!s.ok){const{line:I,column:q,message:Z}=s.error;return{success:!1,error:{code:"PARSE_FAILED",message:`Failed to parse source at line ${I}, col ${q}: ${Z}`}}}const i=s.ast;if(i.version!=="2+modules")return{success:!1,error:{code:"NOT_MODULE_SOURCE",message:`Version '${i.version}' is not a module source`}};if(i.service.name!=="cloud.firestore"&&i.service.name!=="firebase.storage")return{success:!1,error:{code:"UNSUPPORTED_SERVICE",message:`Module resolution does not support service '${i.service.name}'`}};if(i.imports.length===0)return i.version="2",{success:!0,data:{resolved:en(i),modules:[],bundledModules:[],evidenceIds:[]}};const a=i.imports.find(I=>I.functions.length===0);if(a)return{success:!1,error:{code:"UNKNOWN_FUNCTION",message:`Import from '${a.module}' must request at least one function`}};const o=new Map,c=new Map,u=new Map,d=new Map,l=[],f=[],y=new Map;for(const I of i.imports){const q=ef(t,I.module,r,n);if(!q.success)return{success:!1,error:q.error};l.includes(I.module)||l.push(I.module),q.bundled&&!f.includes(I.module)&&f.push(I.module);const Z=new Set,pe=q.functions.find(J=>Z.has(J.name)?!0:(Z.add(J.name),!1));if(pe)return{success:!1,error:{code:"DUPLICATE_FUNCTION",message:`Module '${I.module}' defines duplicate function '${pe.name}'`}};const Q=q.functions.find(J=>Wr.has(J.name));if(Q)return{success:!1,error:{code:"DUPLICATE_FUNCTION",message:`Function '${Q.name}' from module '${I.module}' conflicts with a Rules builtin`}};const ve=new Set;for(const J of q.functions)J.exported||ve.add(J.name);y.set(I.module,ve);const zn=Kh(q.functions,I.module),Oi=new Set;for(const J of zn){if(Oi.has(J.name))return{success:!1,error:{code:"DUPLICATE_FUNCTION",message:`Module '${I.module}' defines conflicting function name '${J.name}'`}};Oi.add(J.name)}const fu=new Set(zn.filter(J=>J.exported).map(J=>J.name));for(const J of zn){const kt=d.get(J.name);if(kt&&kt!==I.module)return{success:!1,error:{code:"DUPLICATE_FUNCTION",message:`Function '${J.name}' from module '${I.module}' conflicts with module '${kt}'`}};if(d.set(J.name,I.module),c.set(J.name,J),J.exported){if(o.has(J.name)&&u.get(J.name)!==I.module)return{success:!1,error:{code:"DUPLICATE_FUNCTION",message:`Function '${J.name}' exported by both '${u.get(J.name)}' and '${I.module}'`}};o.set(J.name,J),u.set(J.name,I.module)}}for(const J of I.functions){if(!fu.has(J))return{success:!1,error:{code:"UNKNOWN_FUNCTION",message:y.get(I.module)?.has(J)?`Function '${J}' in module '${I.module}' is not exported`:`Function '${J}' not found in module '${I.module}'`}};if(i.service.name==="cloud.firestore"||i.service.name==="firebase.storage"){const kt=q.bundled?jh(i.service.name,I.module,J):null;if(kt)return{success:!1,error:{code:"INCOMPATIBLE_FUNCTION",message:kt}}}}}const b=new Set(i.imports.flatMap(I=>I.functions)),S=[],j=new Set,T=[],L={cycle:null};function k(I){if(L.cycle)return;const q=T.indexOf(I);if(q>=0){L.cycle=[...T.slice(q),I];return}if(j.has(I))return;const Z=c.get(I);if(!Z)return;T.push(I);const pe=Et(Z.body);for(const Q of Z.lets)pe.push(...Et(Q.value));for(const Q of pe)c.has(Q)&&!Wr.has(Q)&&k(Q);T.pop(),!L.cycle&&(j.add(I),S.push({...Z,exported:!1}))}for(const I of i.imports)for(const q of I.functions)k(q);if(L.cycle)return{success:!1,error:{code:"CIRCULAR_DEPENDENCY",message:`Recursive module function dependency: ${L.cycle.join(" -> ")}`}};for(const I of S){const q=d.get(I.name),pe=[...I.lets.flatMap(({value:Q})=>Et(Q)),...Et(I.body)].find(Q=>{const ve=d.get(Q);return ve&&ve!==q&&!b.has(Q)});if(pe)return{success:!1,error:{code:"UNKNOWN_FUNCTION",message:`Function '${I.name}' in module '${q}' cannot call '${pe}' from another module`}}}const $=new Set(S.map(I=>I.name)),V=new Map((i.functions??[]).map(I=>[I.name,I])),w=new Set((i.service.functions??[]).map(I=>I.name)),x=(I,q)=>I.flatMap(Et).find(Z=>o.has(Z)&&!$.has(Z)&&!q.has(Z))??null,_=I=>I.flatMap(q=>[...q.lets.map(({value:Z})=>Z),q.body]),v=new Set(V.keys());let O=x(_(i.functions??[]),v);const A=new Set([...v,...w]);O??=x(_(i.service.functions??[]),A);const h=(I,q)=>{const Z=new Set([...q,...I.functions.map(Q=>Q.name)]),pe=[..._(I.functions),...I.allows.map(({condition:Q})=>Q)];return x(pe,Z)??I.children.map(Q=>h(Q,Z)).find(Boolean)??null};if(O??=h(i.service.match,A),O)return{success:!1,error:{code:"UNKNOWN_FUNCTION",message:`Source calls function '${O}' from module '${u.get(O)}' without importing it`}};const p=(I,q)=>{if(q.has(I.name))return!1;const Z=new Set([...q,I.name]);return[...I.lets.flatMap(({value:Q})=>Et(Q)),...Et(I.body)].some(Q=>{const ve=V.get(Q);return ve?p(ve,Z):$.has(Q)||w.has(Q)})},g=[...V.values()].find(I=>p(I,new Set));if(g)return{success:!1,error:{code:"INCOMPATIBLE_FUNCTION",message:`Global function '${g.name}' cannot call a service-scoped function`}};if(i.service.name==="firebase.storage"||i.service.name==="cloud.firestore"){const I=new Map(S.map(q=>[q.name,q]));for(const q of S){const Z=[...Qh(i,q.name),...Yh(I,q.name).map(Q=>({arguments:Q.map(ve=>({expression:ve,provenance:null,receiverType:"unknown"}))}))],pe=Z.length>0?Z:[{arguments:[]}];for(const{arguments:Q}of pe){const ve=Wh(q,i.service.name,c,Q);if(ve)return{success:!1,error:{code:"INCOMPATIBLE_FUNCTION",message:`Function '${q.name}' requires unsupported ${ve} for service '${i.service.name}'`}}}}}const m=new Set([...(i.functions??[]).map(I=>I.name),...(i.service.functions??[]).map(I=>I.name)]),D=I=>{I.functions.forEach(q=>m.add(q.name)),I.children.forEach(D)};D(i.service.match);const E=[...m].find(I=>Wr.has(I));if(E)return{success:!1,error:{code:"DUPLICATE_FUNCTION",message:`Source function '${E}' conflicts with a Rules builtin`}};for(const I of S)if(m.has(I.name))return{success:!1,error:{code:"DUPLICATE_FUNCTION",message:`Imported function '${I.name}' conflicts with a function defined in the source`}};i.service.functions=[...S,...i.service.functions??[]],i.version="2",i.imports=[];const C=new Set,N=i.service.name==="firebase.storage"?"storage-rules#":"firestore-rules#";for(const I of f){const q=Cs(I)??I,Z=Sh[q]??[];for(const pe of Z)pe.startsWith(N)&&C.add(pe)}return{success:!0,data:{resolved:en(i),modules:l,bundledModules:f,evidenceIds:[...C].sort()}}}const rf={atomic:`// @pyric-services cloud.firestore
487
+ // Atomic module — cross-document integrity for BATCH writes, via the
488
+ // get()/getAfter() pair. Firestore evaluates every write in a batch
489
+ // against rules, and getAfter() returns another document's POST-BATCH
490
+ // state — so a rule can require "this write is only valid if a
491
+ // companion write happened in the same atomic batch".
492
+ //
493
+ // All semantics live-verified against a production database: companion
494
+ // visibility, solo-write denial, wrong-delta denial, single-use consumption
495
+ // incl. replay denial, and out-of-batch getAfter() falling back to current
496
+ // state.
497
+ //
498
+ // Explicit-param design: pass BOTH states of the companion doc —
499
+ // \`get(path).data\` (pre-batch) and \`getAfter(path).data\` (post-batch).
500
+ //
501
+ // import { companionChangedBy, consumedFlag } from 'atomic';
502
+ //
503
+ // // Denormalized counter: creating a task REQUIRES the team's
504
+ // // taskCount to have been incremented in the same batch:
505
+ // match /teams/{teamId}/tasks/{taskId} {
506
+ // function teamBefore() {
507
+ // return get(/databases/$(database)/documents/teams/$(teamId)).data;
508
+ // }
509
+ // function teamAfter() {
510
+ // return getAfter(/databases/$(database)/documents/teams/$(teamId)).data;
511
+ // }
512
+ // allow create: if companionChangedBy(teamBefore(), teamAfter(), 'taskCount', 1);
513
+ // }
514
+ //
515
+ // // Single-use invite: the join is valid only when the invite was
516
+ // // consumed (false -> true) IN THIS BATCH — replays deny because
517
+ // // the pre-batch state is already true:
518
+ // allow update: if consumedFlag(inviteBefore(), inviteAfter(), 'used');
519
+ //
520
+ // NOTE (simulator): in-batch companion semantics cannot be expressed
521
+ // in the simulator or the Rules Test API mock surface — the simulator
522
+ // treats cross-doc getAfter() as get(). These function BODIES are
523
+ // simulator-tested with explicit values; the getAfter() WIRING is the
524
+ // live v1 scope's job. Companion writes need their own allow rules too —
525
+ // every write in a batch is evaluated.
526
+
527
+ // The companion doc's field changed by EXACTLY n in this batch.
528
+ // before/after are the SAME doc's get()/getAfter() data.
529
+ export function companionChangedBy(before, after, field, n) {
530
+ return after[field] == before[field] + n;
531
+ }
532
+
533
+ // A single-use flag was consumed IN THIS BATCH: pre-batch false,
534
+ // post-batch true. Replays deny (pre-batch is already true), and a
535
+ // solo write denies (getAfter == get, so false != true).
536
+ export function consumedFlag(before, after, flagField) {
537
+ return before[flagField] == false && after[flagField] == true;
538
+ }
539
+ `,auth:`// @pyric-services cloud.firestore,firebase.storage
540
+ // @pyric-evidence storage-rules#125,firestore-rules#189
541
+ export function isAuthenticated() {
542
+ return request.auth != null;
543
+ }
544
+
545
+ export function isOwner(userId) {
546
+ return isAuthenticated() && request.auth.uid == userId;
547
+ }
548
+ `,content:`// @pyric-services cloud.firestore
549
+ // Content module for author-owned documents — the most common
550
+ // Firebase app shape (posts, notes, docs, comments, tasks).
551
+ //
552
+ // Convention: documents carry an author field (a UID string) and
553
+ // usually a status field ('draft' | 'published' | ...). Field names
554
+ // are parameters, not conventions — pass yours.
555
+ //
556
+ // Usage:
557
+ // import { validAuthorCreate, isAuthor, canReadContent, notDeleted } from 'content';
558
+ // import { onlyFieldsChanged } from 'lifecycle';
559
+ //
560
+ // match /posts/{postId} {
561
+ // // Create: author is the signed-in user.
562
+ // allow create: if validAuthorCreate('author');
563
+ // // Read: published to everyone, drafts to the author only.
564
+ // allow read: if canReadContent('status', 'author') && notDeleted();
565
+ // // Update: author edits content fields; authorship immutable.
566
+ // allow update: if isAuthor('author') && onlyFieldsChanged(['title', 'body', 'status']);
567
+ // allow delete: if isAuthor('author');
568
+ // }
569
+
570
+ // Create guard: signed in, and the incoming doc's author field is the
571
+ // caller. Use on \`create\` (reads request.resource).
572
+ export function validAuthorCreate(authorField) {
573
+ return request.auth != null
574
+ && request.resource.data[authorField] == request.auth.uid;
575
+ }
576
+
577
+ // The caller is the EXISTING document's author. Use on update/delete
578
+ // (reads resource).
579
+ export function isAuthor(authorField) {
580
+ return request.auth != null
581
+ && resource.data[authorField] == request.auth.uid;
582
+ }
583
+
584
+ // Read visibility: published content is public; anything else is
585
+ // visible to its author only. Works for get; for list queries the
586
+ // client must filter (rules are not filters — a bare collection query
587
+ // will be denied unless it proves status == 'published').
588
+ export function canReadContent(statusField, authorField) {
589
+ return resource.data[statusField] == 'published'
590
+ || (request.auth != null && resource.data[authorField] == request.auth.uid);
591
+ }
592
+
593
+ // Soft-delete guard: the document is not marked deleted. Reads the
594
+ // EXISTING doc; a doc without the field passes — bracket access is
595
+ // the null-on-miss idiom (dotted access of a missing key ERRORS).
596
+ export function notDeleted() {
597
+ return resource.data['deleted'] != true;
598
+ }
599
+ `,counters:`// @pyric-services cloud.firestore
600
+ // Counters module for denormalized numeric integrity.
601
+ //
602
+ // The recurring shape: a client-maintained count (likes, votes, moves,
603
+ // quantities) that rules must keep honest — it may only change by a
604
+ // known step, or stay within known bounds. Generalizes the
605
+ // state-module's moveIncremented() (hardcoded to moveCount) to any
606
+ // field.
607
+ //
608
+ // Usage:
609
+ // import { incrementedBy, changedBy, boundedNumber } from 'counters';
610
+ //
611
+ // // A like toggle: likeCount moves by exactly ±1:
612
+ // allow update: if changedBy('likeCount', -1, 1);
613
+ //
614
+ // // A move counter: strictly +1 per move:
615
+ // allow update: if incrementedBy('moveCount', 1);
616
+ //
617
+ // // A rating: any write keeps it in [1, 5]:
618
+ // allow write: if boundedNumber('rating', 1, 5);
619
+
620
+ // The field changed by EXACTLY n relative to the existing document.
621
+ // n may be negative (decrement). Update rules only (needs resource).
622
+ export function incrementedBy(field, n) {
623
+ return request.resource.data[field] == resource.data[field] + n;
624
+ }
625
+
626
+ // The field's delta is within [min, max] (inclusive) — and it is NOT
627
+ // required to change (delta 0 passes when min <= 0 <= max).
628
+ export function changedBy(field, min, max) {
629
+ return request.resource.data[field] - resource.data[field] >= min
630
+ && request.resource.data[field] - resource.data[field] <= max;
631
+ }
632
+
633
+ // The incoming value is a number within [min, max] (inclusive).
634
+ // Works on create and update. Missing field reads null (dynamic
635
+ // access) and fails the type check rather than erroring.
636
+ export function boundedNumber(field, min, max) {
637
+ return (request.resource.data[field] is int || request.resource.data[field] is float)
638
+ && request.resource.data[field] >= min
639
+ && request.resource.data[field] <= max;
640
+ }
641
+ `,geometry:`// @pyric-services cloud.firestore
642
+ // Geometry module for movement game validation via config document lookup.
643
+ //
644
+ // Caller must pass the config document data as an explicit parameter.
645
+ // The config doc is read via get() and cached per request — define a
646
+ // config() function in your rules and pass its result to these functions.
647
+ //
648
+ // Config doc schema:
649
+ // moves[pieceType][fromCell][toCell] = true
650
+ // jumps[pieceType][fromCell][toCell] = capturedCellName
651
+ //
652
+ // Usage:
653
+ // import { validSimpleMove, validJumpMove } from 'geometry';
654
+ //
655
+ // function config() {
656
+ // return get(/databases/$(database)/documents/gameConfig/checkers).data;
657
+ // }
658
+ //
659
+ // allow update: if validSimpleMove(config())
660
+ // && piecePlaced() && moveIntegrity();
661
+ //
662
+ // allow update: if validJumpMove(config())
663
+ // && captureValid() && captureDecrement() && moveIntegrity();
664
+
665
+ // Validate a simple (non-capture) move via config document lookup.
666
+ // Uses 3-level dynamic nesting: cfg.moves[piece][from][to].
667
+ // piece comes from resource.data (pre-write board) so client can't fake it.
668
+ export function validSimpleMove(cfg) {
669
+ let mf = request.resource.data.moveFrom;
670
+ let mt = request.resource.data.moveTo;
671
+ let piece = resource.data[mf];
672
+ return cfg.moves[piece][mf][mt] == true;
673
+ }
674
+
675
+ // Validate a jump (capture) move via config document lookup.
676
+ // cfg.jumps[piece][from][to] returns the expected captured cell name.
677
+ // Caller must separately verify the captured piece is an opponent piece.
678
+ export function validJumpMove(cfg) {
679
+ let mf = request.resource.data.moveFrom;
680
+ let mt = request.resource.data.moveTo;
681
+ let cap = request.resource.data.captured;
682
+ let piece = resource.data[mf];
683
+ return cfg.jumps[piece][mf][mt] == cap;
684
+ }
685
+ `,joining:`// @pyric-services cloud.firestore
686
+ // Joining module — how membership CHANGES, safely. The connective
687
+ // tissue between content/spaces: spaces gates children behind a
688
+ // members field; joining lets users enter and leave that field
689
+ // WITHOUT an admin backend, with no privilege escalation.
690
+ //
691
+ // Convention: a MAP-shaped members field (uid -> role) on the parent
692
+ // doc. Compose with lifecycle's onlyFieldsChanged so a join/leave
693
+ // write can't touch anything else:
694
+ //
695
+ // import { onlyAddedSelf, onlyRemovedSelf } from 'joining';
696
+ // import { onlyFieldsChanged } from 'lifecycle';
697
+ // import { isSpaceMember, hasSpaceRole } from 'spaces';
698
+ //
699
+ // match /teams/{teamId} {
700
+ // allow read: if isSpaceMember(resource.data);
701
+ //
702
+ // // Open self-service join (public team) at a fixed role, and
703
+ // // self-service leave — nothing else about the doc may change:
704
+ // allow update: if onlyFieldsChanged(['members'])
705
+ // && (onlyAddedSelf('members', 'editor') || onlyRemovedSelf('members'));
706
+ // // Admins manage the doc freely:
707
+ // allow update: if hasSpaceRole(resource.data, 'admin');
708
+ // }
709
+ //
710
+ // Every guarantee here is production-verified against the live Rules Test API:
711
+ // the field-level map diff is reliable; the empty no-op diff DENIES (set
712
+ // equality, not hasOnly — hasOnly on an empty set passes); role escalation via
713
+ // CHANGING an existing entry denies; adding or removing anyone else denies.
714
+
715
+ // The write adds EXACTLY the caller to the members map, at EXACTLY
716
+ // \`role\`, changing and removing nobody. Update rules only.
717
+ export function onlyAddedSelf(membersField, role) {
718
+ let diff = request.resource.data[membersField].diff(resource.data[membersField]);
719
+ return request.auth != null
720
+ && diff.addedKeys() == [request.auth.uid].toSet()
721
+ && diff.changedKeys().size() == 0
722
+ && diff.removedKeys().size() == 0
723
+ && request.resource.data[membersField][request.auth.uid] == role;
724
+ }
725
+
726
+ // The write removes EXACTLY the caller from the members map, adding
727
+ // and changing nobody. Self-service leave. Update rules only.
728
+ export function onlyRemovedSelf(membersField) {
729
+ let diff = request.resource.data[membersField].diff(resource.data[membersField]);
730
+ return request.auth != null
731
+ && diff.removedKeys() == [request.auth.uid].toSet()
732
+ && diff.addedKeys().size() == 0
733
+ && diff.changedKeys().size() == 0;
734
+ }
735
+ `,lifecycle:`// @pyric-services cloud.firestore
736
+ // Lifecycle module for field immutability and timestamp enforcement.
737
+ //
738
+ // Common pattern: certain fields must never change after document creation
739
+ // (createdBy, createdAt, authorId).
740
+ //
741
+ // Usage:
742
+ // import { fieldUnchanged, immutableFields, isServerTimestamp } from 'lifecycle';
743
+ //
744
+ // // Single field:
745
+ // allow update: if fieldUnchanged('createdBy');
746
+ //
747
+ // // Multiple fields (replaces chained fieldUnchanged calls):
748
+ // allow update: if immutableFields(['createdBy', 'createdAt', 'authorId']);
749
+ //
750
+ // // The dual: users may edit title/body but NOTHING else:
751
+ // allow update: if onlyFieldsChanged(['title', 'body']);
752
+ //
753
+ // allow create: if isServerTimestamp('createdAt');
754
+
755
+ // Ensure a field's value is identical between existing and incoming document.
756
+ // Use on update rules to enforce immutability.
757
+ export function fieldUnchanged(field) {
758
+ return resource.data[field] == request.resource.data[field];
759
+ }
760
+
761
+ // Ensure multiple fields are unchanged between existing and incoming document.
762
+ // Uses MapDiff — one expression instead of N chained fieldUnchanged() calls.
763
+ export function immutableFields(fields) {
764
+ return request.resource.data.diff(resource.data).unchangedKeys().hasAll(fields);
765
+ }
766
+
767
+ // Ensure a field is set to the server timestamp.
768
+ // Use on create or update rules to enforce server-side time.
769
+ export function isServerTimestamp(field) {
770
+ return request.resource.data[field] == request.time;
771
+ }
772
+
773
+ // The dual of immutableFields: every changed field is in the allowed
774
+ // list (fields NOT listed are implicitly immutable). Top-level keys
775
+ // only — nested-map diffs are unreliable in production; flatten the
776
+ // schema instead of reaching for a nested diff.
777
+ export function onlyFieldsChanged(fields) {
778
+ return request.resource.data.diff(resource.data).affectedKeys().hasOnly(fields);
779
+ }
780
+
781
+ // Exactly n top-level fields changed in this write. n == 1 is the
782
+ // board-integrity / edit-one-field-per-write guard (Pattern 5,
783
+ // generalized beyond games).
784
+ export function nFieldsChanged(n) {
785
+ return request.resource.data.diff(resource.data).affectedKeys().size() == n;
786
+ }
787
+ `,lobby:`// @pyric-services cloud.firestore
788
+ // Lobby module for 2-participant coordination.
789
+ //
790
+ // Convention: documents must have these fields:
791
+ // host: string (creator's UID)
792
+ // guest: string ('' when waiting, joiner's UID when joined)
793
+ // status: 'waiting' | 'playing' | 'ready' (or any active state)
794
+ //
795
+ // Usage:
796
+ // import { validCreate, validJoin, canCancel } from 'lobby';
797
+ //
798
+ // allow create: if validCreate();
799
+ // allow update: if validJoin();
800
+ // allow delete: if canCancel();
801
+
802
+ // Is this a waiting lobby with an open seat?
803
+ function isWaiting() {
804
+ return resource.data.status == 'waiting'
805
+ && resource.data.guest == '';
806
+ }
807
+
808
+ // Create: caller is host, seat empty, status waiting
809
+ export function validCreate() {
810
+ return request.auth != null
811
+ && request.resource.data.host == request.auth.uid
812
+ && request.resource.data.guest == ''
813
+ && request.resource.data.status == 'waiting';
814
+ }
815
+
816
+ // Join: fill empty seat, transition to next status, no self-join
817
+ export function validJoin() {
818
+ return request.auth != null
819
+ && isWaiting()
820
+ && request.resource.data.guest == request.auth.uid
821
+ && request.auth.uid != resource.data.host
822
+ && request.resource.data.status == 'playing'
823
+ && request.resource.data.host == resource.data.host;
824
+ }
825
+
826
+ // Cancel: only host, only while waiting
827
+ export function canCancel() {
828
+ return request.auth != null
829
+ && resource.data.status == 'waiting'
830
+ && request.auth.uid == resource.data.host;
831
+ }
832
+ `,membership:`// @pyric-services cloud.firestore,firebase.storage
833
+ // @pyric-evidence storage-rules#125,firestore-rules#189
834
+ // Membership module for role-based and claims-based access control.
835
+ //
836
+ // Two access patterns:
837
+ // 1. Custom claims on auth token (0 get() calls, set server-side)
838
+ // 2. Member maps on documents (0 get() calls on the doc itself)
839
+ //
840
+ // Usage:
841
+ // import { hasClaim, hasClaimRole, isMemberOf, hasRole } from 'membership';
842
+ //
843
+ // // Workspace access via custom claims
844
+ // allow read: if hasClaim('workspace_id');
845
+ // allow write: if hasClaimRole('workspace_role', 'admin');
846
+ //
847
+ // // Project access via member map on document
848
+ // allow read: if isMemberOf(resource.data.members);
849
+ // allow update: if hasRole(resource.data.members, 'admin');
850
+
851
+ // Check if the auth token has a non-null value for a claim key.
852
+ export function hasClaim(claim) {
853
+ return request.auth != null
854
+ && request.auth.token[claim] != null;
855
+ }
856
+
857
+ // Check if the auth token has a specific value for a claim key.
858
+ export function hasClaimRole(claim, role) {
859
+ return request.auth != null
860
+ && request.auth.token[claim] == role;
861
+ }
862
+
863
+ // Check if the caller's UID exists as a key in a members map.
864
+ export function isMemberOf(membersMap) {
865
+ return request.auth != null
866
+ && request.auth.uid in membersMap;
867
+ }
868
+
869
+ // Check if the caller has a specific role in a members map.
870
+ export function hasRole(membersMap, role) {
871
+ return request.auth != null
872
+ && membersMap[request.auth.uid] == role;
873
+ }
874
+ `,spaces:`// @pyric-services cloud.firestore
875
+ // Spaces module — cross-document membership gating for shared spaces
876
+ // (teams, rooms, groups, projects, parties). The second-most-common
877
+ // app shape after author-owned content: a PARENT document defines who
878
+ // may touch its children.
879
+ //
880
+ // Explicit-param design (like geometry): the caller reads the parent
881
+ // doc ONCE via a helper and passes its data in. Define the helper in
882
+ // your rules — get() is cached per request, so every function below
883
+ // can share one read (of the 10-get budget):
884
+ //
885
+ // import { isSpaceMember, hasSpaceRole, validMemberCreate } from 'spaces';
886
+ //
887
+ // match /spaces/{spaceId}/tasks/{taskId} {
888
+ // function space() {
889
+ // return get(/databases/$(database)/documents/spaces/$(spaceId)).data;
890
+ // }
891
+ // allow read: if isSpaceMember(space());
892
+ // allow create: if validMemberCreate(space(), 'author');
893
+ // allow delete: if hasSpaceRole(space(), 'admin');
894
+ // }
895
+ //
896
+ // Members field shapes verified against the production engine:
897
+ // list: members: ['uidA', 'uidB'] → isSpaceMember only
898
+ // map: members: { uidA: 'admin', ... } → isSpaceMember + hasSpaceRole
899
+ // A missing members field, a non-member uid, or a missing parent doc
900
+ // (get() of a missing doc errors) all fail CLOSED.
901
+
902
+ // The caller is in the space's members field. \`in\` covers both
903
+ // shapes: list membership and map keys.
904
+ export function isSpaceMember(spaceData) {
905
+ return request.auth != null && request.auth.uid in spaceData.members;
906
+ }
907
+
908
+ // The caller's role in a MAP-shaped members field equals \`role\`.
909
+ // List-shaped members carry no roles — this denies on them.
910
+ export function hasSpaceRole(spaceData, role) {
911
+ return request.auth != null && spaceData.members[request.auth.uid] == role;
912
+ }
913
+
914
+ // Member-gated authored create: the caller is a member AND the
915
+ // incoming child doc's author field is the caller. The "post a
916
+ // message / add a task" guard.
917
+ export function validMemberCreate(spaceData, authorField) {
918
+ return isSpaceMember(spaceData)
919
+ && request.resource.data[authorField] == request.auth.uid;
920
+ }
921
+ `,state:`// @pyric-services cloud.firestore
922
+ // Game state machine helpers.
923
+ //
924
+ // Convention: documents must have these fields:
925
+ // status: 'waiting' | 'playing' | 'won' | 'draw'
926
+ // moveCount: number
927
+ // host: string (UID)
928
+ // guest: string (UID)
929
+ //
930
+ // Usage:
931
+ // import { isPlaying, moveIncremented, participantsUnchanged } from 'state';
932
+ //
933
+ // allow update: if isPlaying() && moveIncremented() && participantsUnchanged();
934
+
935
+ // Is the game actively in play?
936
+ export function isPlaying() {
937
+ return resource.data.status == 'playing';
938
+ }
939
+
940
+ // Did moveCount increment by exactly 1?
941
+ export function moveIncremented() {
942
+ return request.resource.data.moveCount == resource.data.moveCount + 1;
943
+ }
944
+
945
+ // Are host and guest unchanged? (prevents mid-game identity swap)
946
+ export function participantsUnchanged() {
947
+ return request.resource.data.host == resource.data.host
948
+ && request.resource.data.guest == resource.data.guest;
949
+ }
950
+ `,"storage/metadata":`// @pyric-services firebase.storage
951
+ // @pyric-evidence storage-rules#132
952
+ // Storage custom-metadata policies. Custom metadata is a flat string map.
953
+
954
+ export function hasRequiredMetadata(keys) {
955
+ return request.resource.metadata.keys().hasAll(keys);
956
+ }
957
+
958
+ export function metadataString(key, min, max) {
959
+ return request.resource.metadata[key] is string
960
+ && request.resource.metadata[key].size() >= min
961
+ && request.resource.metadata[key].size() <= max;
962
+ }
963
+
964
+ export function incomingMetadataOwner(key) {
965
+ return request.auth != null
966
+ && request.resource.metadata[key] == request.auth.uid;
967
+ }
968
+
969
+ export function existingMetadataOwner(key) {
970
+ return request.auth != null
971
+ && resource.metadata[key] == request.auth.uid;
972
+ }
973
+ `,"storage/objects":`// @pyric-services firebase.storage
974
+ // @pyric-evidence storage-rules#132
975
+ // Storage operation identity. Use request.method rather than null checks:
976
+ // production treats missing resource/request.resource bindings as errors.
977
+
978
+ export function isCreate() {
979
+ return request.method == 'create';
980
+ }
981
+
982
+ export function isUpdate() {
983
+ return request.method == 'update';
984
+ }
985
+
986
+ export function isDelete() {
987
+ return request.method == 'delete';
988
+ }
989
+ `,"storage/time":`// @pyric-services firebase.storage
990
+ // @pyric-evidence storage-rules#132
991
+ // Freshness checks over server-owned Storage object timestamps. Boundaries are
992
+ // strict: equality with the deadline is not "within" the window.
993
+
994
+ export function createdWithin(seconds) {
995
+ return request.time < resource.timeCreated + duration.value(seconds, 's');
996
+ }
997
+
998
+ export function updatedWithin(seconds) {
999
+ return request.time < resource.updated + duration.value(seconds, 's');
1000
+ }
1001
+ `,"storage/uploads":`// @pyric-services firebase.storage
1002
+ // @pyric-evidence storage-rules#132
1003
+ // Storage upload request primitives. These inspect declared object metadata;
1004
+ // MIME helpers do not inspect or authenticate the uploaded bytes.
1005
+
1006
+ export function sizeAtMost(maxBytes) {
1007
+ return request.resource.size <= maxBytes;
1008
+ }
1009
+
1010
+ export function sizeBetween(minBytes, maxBytes) {
1011
+ return request.resource.size >= minBytes
1012
+ && request.resource.size <= maxBytes;
1013
+ }
1014
+
1015
+ export function contentTypeMatches(pattern) {
1016
+ return request.resource.contentType.matches(pattern);
1017
+ }
1018
+
1019
+ export function contentTypeIsOneOf(types) {
1020
+ return request.resource.contentType in types;
1021
+ }
1022
+ `,timing:`// @pyric-services cloud.firestore
1023
+ // Timing module for cooldown / rate-limit enforcement.
1024
+ //
1025
+ // Rules CAN rate-limit (contrary to a common assumption — jrpg
1026
+ // FINDINGS F-004): compare request.time against a stored server
1027
+ // timestamp. Pair with lifecycle's isServerTimestamp on the SAME
1028
+ // write so the stored timestamp cannot be forged by the client:
1029
+ //
1030
+ // import { cooldownElapsed } from 'timing';
1031
+ // import { isServerTimestamp } from 'lifecycle';
1032
+ //
1033
+ // // At most one move every 2 seconds:
1034
+ // allow update: if cooldownElapsed('lastMoveAt', 2)
1035
+ // && isServerTimestamp('lastMoveAt');
1036
+
1037
+ // The stored timestamp is more than \`seconds\` old (strict). Update
1038
+ // rules only — needs \`resource\`. The field must be a Timestamp; a
1039
+ // missing field errors, which denies (fail-closed).
1040
+ export function cooldownElapsed(field, seconds) {
1041
+ return request.time > resource.data[field] + duration.value(seconds, 's');
1042
+ }
1043
+ `,transitions:`// @pyric-services cloud.firestore
1044
+ // Transitions module for state machine enforcement.
1045
+ //
1046
+ // Validates that a field transitions from one known value to another.
1047
+ // Use to enforce valid status flows (e.g., open -> in_progress -> completed).
1048
+ //
1049
+ // Usage:
1050
+ // import { validTransition, statusIs, newStatusIs } from 'transitions';
1051
+ //
1052
+ // // Only allow open -> in_progress
1053
+ // allow update: if validTransition('status', 'open', 'in_progress');
1054
+ //
1055
+ // // Allow update only when currently active
1056
+ // allow update: if statusIs('status', 'active');
1057
+ //
1058
+ // // Compound: multiple valid transitions via OR
1059
+ // allow update: if validTransition('status', 'open', 'in_progress')
1060
+ // || validTransition('status', 'in_progress', 'completed')
1061
+ // || validTransition('status', 'completed', 'archived');
1062
+
1063
+ // Check that a field transitions from one value to another.
1064
+ export function validTransition(field, from, to) {
1065
+ return resource.data[field] == from
1066
+ && request.resource.data[field] == to;
1067
+ }
1068
+
1069
+ // Check the current (existing) value of a field.
1070
+ export function statusIs(field, value) {
1071
+ return resource.data[field] == value;
1072
+ }
1073
+
1074
+ // Check the incoming (new) value of a field.
1075
+ export function newStatusIs(field, value) {
1076
+ return request.resource.data[field] == value;
1077
+ }
1078
+ `,turns:`// @pyric-services cloud.firestore
1079
+ // Turn enforcement for 2-participant games/sessions.
1080
+ //
1081
+ // Convention: documents must have these fields:
1082
+ // host: string (UID)
1083
+ // guest: string (UID)
1084
+ // currentTurn: 'host' | 'guest'
1085
+ //
1086
+ // Usage:
1087
+ // import { isMyTurn, turnFlipped } from 'turns';
1088
+ //
1089
+ // allow update: if isMyTurn() && turnFlipped();
1090
+
1091
+ // Is the caller the participant whose turn it is?
1092
+ export function isMyTurn() {
1093
+ return (resource.data.currentTurn == 'host'
1094
+ && request.auth.uid == resource.data.host)
1095
+ || (resource.data.currentTurn == 'guest'
1096
+ && request.auth.uid == resource.data.guest);
1097
+ }
1098
+
1099
+ // Did the turn alternate?
1100
+ export function turnFlipped() {
1101
+ return (resource.data.currentTurn == 'host'
1102
+ && request.resource.data.currentTurn == 'guest')
1103
+ || (resource.data.currentTurn == 'guest'
1104
+ && request.resource.data.currentTurn == 'host');
1105
+ }
1106
+ `,validation:`// @pyric-services cloud.firestore
1107
+ // Validation module for document field shape and value checks.
1108
+ //
1109
+ // Usage:
1110
+ // import { hasRequired, hasOnly, validString, isOneOf } from 'validation';
1111
+ //
1112
+ // allow create: if hasRequired(['title', 'status'])
1113
+ // && validString('title', 1, 100)
1114
+ // && isOneOf('status', ['draft', 'published']);
1115
+
1116
+ export function hasRequired(fields) {
1117
+ return request.resource.data.keys().hasAll(fields);
1118
+ }
1119
+
1120
+ export function hasOnly(fields) {
1121
+ return request.resource.data.keys().hasOnly(fields);
1122
+ }
1123
+
1124
+ // Incoming field is a string with size in [min, max] (inclusive).
1125
+ // Uses dynamic access, so a MISSING field reads as null (not an
1126
+ // error) and fails the \`is string\` check — safe on optional fields.
1127
+ export function validString(field, min, max) {
1128
+ return request.resource.data[field] is string
1129
+ && request.resource.data[field].size() >= min
1130
+ && request.resource.data[field].size() <= max;
1131
+ }
1132
+
1133
+ // Enum check: the incoming field value is one of the allowed values.
1134
+ // (\`in\` on a list — NOT \`.includes()\`, which does not exist in rules.)
1135
+ export function isOneOf(field, values) {
1136
+ return request.resource.data[field] in values;
1137
+ }
1138
+ `};function nf(){const t={};for(const[e,r]of Object.entries(rf))t[e]=r,t[`./stdlib/${e}.rules`]=r;return t}const ic=nf(),sf=new Set(Object.keys(ic));function ug(t,e){const r=Object.entries(e?.modules??{}),n=Object.fromEntries(r),s=new Set(r.map(([a])=>a)),i=new Set([...sf].filter(a=>!s.has(a)));return tf(null,t,{...e,modules:{...ic,...n}},i)}function af(t){return typeof t=="object"&&t!==null&&t.__type==="serverTimestamp"}const of={name:"date-to-timestamp",convert(t){return t instanceof Date?xe.fromMillis(t.getTime()):We}},cf={name:"server-timestamp-sentinel",convert(t,e){return af(t)?e.serverTime instanceof xe?e.serverTime:xe.fromMillis(Date.now()):We}};function uf(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 lf={name:"user-timestamp-to-rules-timestamp",convert(t){return uf(t)?new xe(t.seconds,t.nanoseconds):We}};function ba(t){return typeof t=="object"&&t!==null&&"isEqual"in t&&typeof t.isEqual=="function"}function Ts(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function va(t){if(typeof t!="object"||t===null||Ts(t))return;const e=t;if(typeof e.seconds=="number"){const r=typeof e.nanoseconds=="number"?e.nanoseconds:e.nanos;if(typeof r=="number")return{kind:"timestamp",seconds:e.seconds,nanoseconds:r}}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 Ge(t,e){if(Object.is(t,e))return!0;const r=va(t),n=va(e);if(r!==void 0||n!==void 0){if(r===void 0||n===void 0||r.kind!==n.kind)return!1;switch(r.kind){case"timestamp":return n.kind==="timestamp"&&r.seconds===n.seconds&&r.nanoseconds===n.nanoseconds;case"bytes":return n.kind==="bytes"&&r.values.length===n.values.length&&r.values.every((a,o)=>a===n.values[o]);case"vector":return n.kind==="vector"&&r.values.length===n.values.length&&r.values.every((a,o)=>a===n.values[o]);case"geo-point":return n.kind==="geo-point"&&r.latitude===n.latitude&&r.longitude===n.longitude;case"reference":return n.kind==="reference"&&r.path===n.path}}if(ba(t))return t.isEqual(e);if(ba(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)=>Ge(a,e[o]));if(!Ts(t)||!Ts(e))return!1;const s=Object.keys(t),i=Object.keys(e);return s.length!==i.length?!1:s.every(a=>a in e&&Ge(t[a],e[a]))}function df(t){return typeof t=="object"&&t!==null&&t.__type==="increment"&&typeof t.value=="number"}function hf(t){return typeof t=="object"&&t!==null&&t.__type==="arrayUnion"&&Array.isArray(t.values)}function ff(t){return typeof t=="object"&&t!==null&&t.__type==="arrayRemove"&&Array.isArray(t.values)}function pf(t){return typeof t=="object"&&t!==null&&t.__type==="deleteField"}function di(t){if(t.prior===null)return;if(t.fieldPath==="")return t.prior;let e=t.prior;for(const r of t.fieldPath.split(".")){const n=/^([^\[]*)/.exec(r),s=n?n[1]:r;if(s){if(typeof e!="object"||e===null)return;e=e[s]}const i=/\[(\d+)\]/g;let a;for(;(a=i.exec(r))!==null;){if(!Array.isArray(e))return;e=e[Number(a[1])]}}return e}const mf={name:"increment-sentinel",convert(t,e){if(!df(t))return We;const r=di(e);return(typeof r=="number"?r:0)+t.value}},gf={name:"array-union-sentinel",convert(t,e){if(!hf(t))return We;const r=di(e),n=Array.isArray(r)?r.slice():[];for(const s of t.values)n.some(a=>Ge(a,s))||n.push(s);return n}},yf={name:"array-remove-sentinel",convert(t,e){if(!ff(t))return We;const r=di(e);return Array.isArray(r)?r.filter(n=>!t.values.some(s=>Ge(n,s))):[]}},bf={name:"delete-field-sentinel",convert(t){return pf(t)?tt:We}},wa=Symbol.for("pyric.firestore.query-value-registry"),Sa=globalThis,Or=Sa[wa]??(Sa[wa]=new WeakMap),_a=Symbol.for("pyric.firestore.query-value-execution-registry"),Aa=globalThis,_n=Aa[_a]??(Aa[_a]=new WeakMap),xa=Symbol.for("pyric.firestore.query-value-owner-registry"),Ia=globalThis,An=Ia[xa]??(Ia[xa]=new WeakMap);function Ht(t,e,r=()=>t){Or.set(t,e),_n.set(t,r)}function ac(t){return Or.get(t)}function vf(t){return An.get(t)}function wf(t){return _n.get(t)?.()??t}function Sf(t,e){const r=Or.get(t),n=_n.get(t);r!==void 0&&Or.set(e,r),n!==void 0&&_n.set(e,n);const s=An.get(t);s!==void 0&&An.set(e,s)}const Rs=Symbol.for("pyric.firestore.reference-query-value");class _f{path;[Rs]=!0;constructor(e){this.path=e}isEqual(e){return typeof e=="object"&&e!==null&&Rs in e&&e.path===this.path}}function Af(t){const e=Or.get(t);if(typeof e!="object"||e===null||!(Rs in e))return;const r=e.path;return typeof r=="string"?r:void 0}function hi(t,e,r,n=t){Ht(t,new _f(e),()=>n),An.set(t,r)}function xf(t){if(t===null||typeof t!="object"||t instanceof jt)return!1;const e=t;return typeof e.path=="string"&&typeof e.id=="string"&&e._path!==void 0&&e._firestore!==void 0}const If={name:"document-reference",convert(t){if(typeof t=="object"&&t!==null){const e=Af(t);if(e!==void 0)return new jt(e)}return xf(t)?new jt(t.path):We}};function kf(t){return Array.isArray(t)&&t.every(e=>typeof e=="number")}function Ef(t){if(t===null||typeof t!="object"||t instanceof Wt)return null;const e=t;return kf(e._values)&&typeof e.toArray=="function"?e._values:null}const Of={name:"vector-value",convert(t){const e=Ef(t);return e===null?We:new Wt(e)}};function Cf(t){if(t===null||typeof t!="object"||t instanceof Be)return!1;const e=t;return typeof e.toBase64=="function"&&typeof e.toUint8Array=="function"&&typeof e.isEqual=="function"}function Tf(t){if(t===null||typeof t!="object"||t instanceof rt)return!1;const e=t;return typeof e.latitude=="number"&&typeof e.longitude=="number"&&typeof e.isEqual=="function"}const Rf={name:"fb-bytes-to-rules-bytes",convert(t){return Cf(t)?new Be(t.toUint8Array()):We}},Nf={name:"fb-geopoint-to-rules-latlng",convert(t){return Tf(t)?new rt(t.latitude,t.longitude):We}},We=Symbol("value-resolver:KEEP"),tt=Symbol("value-resolver:DELETE_MARKER"),Ns=[];function He(t){Ns.some(e=>e.name===t.name)||Ns.push(t)}function Ye(t,e){const r={};for(const[n,s]of Object.entries(t))r[n]=Fs(s,{...e,fieldPath:n});return r}function Fs(t,e){for(const r of Ns){const n=r.convert(t,e);if(n!==We)return n}if(Array.isArray(t))return t.map((r,n)=>Fs(r,{...e,fieldPath:`${e.fieldPath}[${n}]`}));if(Gt(t)){const r={};for(const[n,s]of Object.entries(t)){const i=e.fieldPath?`${e.fieldPath}.${n}`:n;r[n]=Fs(s,{...e,fieldPath:i})}return r}return t}function Gt(t){if(t===null||typeof t!="object")return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function Tt(t){const e={},r=[];for(const[n,s]of Object.entries(t)){if(s===tt){r.push(n);continue}e[n]=xn(s)}return{writes:e,deletedKeys:r}}function xn(t){if(t!==tt){if(Array.isArray(t))return t.filter(e=>e!==tt).map(xn);if(Gt(t)){const e={};for(const[r,n]of Object.entries(t))n!==tt&&(e[r]=xn(n));return e}return t}}function Ff(){He(of),He(cf),He(lf),He(mf),He(gf),He(yf),He(bf),He(If),He(Of),He(Rf),He(Nf)}function oc(t){return t.split(".")}const Lf=new Set(["__proto__","prototype","constructor"]);function ka(t){if(Lf.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 fi(t){const e={};for(const[r,n]of Object.entries(t))e[r]=cc(n);return e}function cc(t){return Array.isArray(t)?t.map(cc):Gt(t)?fi(t):t}function uc(t,e,r){let n=t;for(let i=0;i<e.length-1;i++){const a=e[i];ka(a);const o=Object.hasOwn(n,a)?n[a]:void 0;Gt(o)||(n[a]={}),n=n[a]}const s=e[e.length-1];ka(s),r===tt?delete n[s]:n[s]=xn(r)}function Ea(t,e){const r=fi(t);for(const[n,s]of Object.entries(e)){if(s!==tt&&In(s))throw new lc;uc(r,oc(n),s)}return r}class lc extends Error{constructor(){super("FieldValue.delete() can only appear at the top level of your update data"),this.name="DeleteFieldNestedError"}}function In(t){return t===tt?!0:Array.isArray(t)?t.some(In):Gt(t)?Object.values(t).some(In):!1}function jf(t){for(const e of Object.values(t))if(e!==tt&&In(e))throw new lc}function Df(t,e,r){const n=fi(t),s=[];if(r!==void 0)for(const i of r){const a=oc(i),o=Mf(e,a);o!==dc&&s.push({segments:a,value:o})}else hc(e,[],s);for(const{segments:i,value:a}of s)uc(n,i,a);return n}const dc=Symbol("field-merge:ABSENT");function Mf(t,e){let r=t;for(const n of e){if(!Gt(r)||!Object.hasOwn(r,n))return dc;r=r[n]}return r}function hc(t,e,r){const n=Object.keys(t);if(n.length===0&&e.length>0){r.push({segments:e,value:{}});return}for(const s of n){const i=t[s],a=[...e,s];Gt(i)&&i!==tt?hc(i,a,r):r.push({segments:a,value:i})}}function Pf(t,e){const r={};for(const n of e)Object.prototype.hasOwnProperty.call(t,n)&&(r[n]=t[n]);return r}class Xn{documents;versions=new Map;nextVersion=1;constructor(e={},r){this.documents=r??new Map;for(const[n,s]of Object.entries(e)){const i=Ye({...s},{path:n,method:"seed",prior:null}),{writes:a}=Tt(i);this.documents.set(n,a),this.bumpVersion(n)}}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,r={}){const n=e===""||e.endsWith("/")?e:e+"/",s=r.projection?c=>Pf(c,r.projection):c=>c,i=[],a=new Set,o=[];for(const[c,u]of this.documents){if(n!==""&&!c.startsWith(n))continue;if(!r.directOnly){i.push({path:c,data:s(u)});continue}const d=c.slice(n.length),l=d.indexOf("/");if(l===-1)i.push({path:c,data:s(u)}),a.add(d);else if(r.phantoms){const f=d.slice(0,l);f.length>0&&!o.includes(f)&&o.push(f)}}if(r.directOnly&&r.phantoms)for(const c of o)a.has(c)||i.push({path:n+c,data:{},phantom:!0});return i}list(e){return this.scan(e,{directOnly:!0,phantoms:!0})}listRootCollections(){const e=new Set,r=[];for(const n of this.documents.keys()){const s=n.split("/",1)[0];s.length!==0&&(e.has(s)||(e.add(s),r.push(s)))}return r}listSubcollections(e){const r=e.endsWith("/")?e:e+"/",n=new Set,s=[];for(const i of this.documents.keys()){if(!i.startsWith(r))continue;const o=i.slice(r.length).split("/",1)[0];o.length!==0&&(n.has(o)||(n.add(o),s.push(o)))}return s}snapshot(){const e={};for(const[r,n]of this.documents)e[r]={...n};return e}size(){return this.documents.size}create(e,r){if(this.documents.has(e))return{success:!1,error:`Document '${e}' already exists`};let n;try{const s=Ye({...r},{path:e,method:"create",prior:null});n=Tt(s).writes}catch(s){return{success:!1,error:s.message}}return this.documents.set(e,n),this.bumpVersion(e),{success:!0}}update(e,r){const n=this.documents.get(e);if(!n)return{success:!1,error:`Document '${e}' does not exist`};let s;try{const i=Ye({...r},{path:e,method:"update",prior:n});s=Ea(n,i)}catch(i){return{success:!1,error:i.message}}return this.documents.set(e,s),this.bumpVersion(e),{success:!0,priorData:{...n}}}setMerge(e,r,n){const s=this.documents.has(e)?{...this.documents.get(e)}:null,i=Ye({...r},{path:e,method:"set",prior:s}),a=Df(s??{},i,n);return this.documents.set(e,a),this.bumpVersion(e),{success:!0,priorData:s,created:s===null}}set(e,r){const n=this.documents.has(e)?{...this.documents.get(e)}:null,s=Ye({...r},{path:e,method:"set",prior:n}),{writes:i}=Tt(s);return this.documents.set(e,i),this.bumpVersion(e),{success:!0,priorData:n,created:n===null}}delete(e){const r=this.documents.get(e);return r?(this.documents.delete(e),this.bumpVersion(e),{success:!0,priorData:{...r}}):{success:!1,error:`Document '${e}' does not exist`}}applyBatch(e){const r=[];for(let s=0;s<e.length;s++){const i=e[s];switch(i.method){case"create":this.documents.has(i.path)&&r.push({index:s,error:`Document '${i.path}' already exists`});break;case"update":this.documents.has(i.path)||r.push({index:s,error:`Document '${i.path}' does not exist`});break}}if(r.length>0)return{success:!1,errors:r};const n=new Map;for(const s of e)n.has(s.path)||n.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=Ye({...s.data},{path:s.path,method:"create",prior:null}),{writes:a}=Tt(i);this.documents.set(s.path,a);break}case"update":{const i=this.documents.get(s.path),a=Ye({...s.data},{path:s.path,method:"update",prior:i});this.documents.set(s.path,Ea(i,a));break}case"set":{const i=n.get(s.path)??null,a=Ye({...s.data},{path:s.path,method:"set",prior:i}),{writes:o}=Tt(a);this.documents.set(s.path,o);break}case"delete":this.documents.delete(s.path);break}this.bumpVersion(s.path)}return{success:!0,priorStates:n}}restore(e){const r=new Set([...this.documents.keys(),...Object.keys(e)]);this.documents.clear();for(const[n,s]of Object.entries(e))this.documents.set(n,{...s});for(const n of r)this.bumpVersion(n)}restorePaths(e){for(const[r,n]of Object.entries(e))n===null?this.documents.delete(r):this.documents.set(r,{...n}),this.bumpVersion(r)}bumpVersion(e){this.versions.set(e,this.nextVersion++)}}class $f{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 r=this.baseCache.get(e);return r===void 0&&(r=structuredClone(this.base[e]),this.baseCache.set(e,r)),r}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,r){this.overlay.set(e,r),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 r=this.has(e);return this.overlay.delete(e),!this.cleared&&this.inBase(e)&&this.tombstones.add(e),r}clear(){this.overlay.clear(),this.tombstones.clear(),this.baseCache.clear(),this.cleared=!0}get size(){let e=0;for(const r of this)e++;return e}*keys(){for(const[e]of this)yield e}*[Symbol.iterator](){const e=new Set;if(!this.cleared)for(const r of Object.keys(this.base))this.tombstones.has(r)||(e.add(r),yield[r,this.overlay.has(r)?this.overlay.get(r):this.baseDoc(r)]);for(const[r,n]of this.overlay)e.has(r)||(yield[r,n])}}class qf{events=[];nextId=1;undoneEvents=[];append(e,r=!1){const n={...e,id:this.nextId++,timestamp:new Date().toISOString()};return this.events.push(n),r||(this.undoneEvents=[]),n}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 r=this.events[e];if(!r.aborted&&r.allowed&&r.method!=="get"&&r.method!=="list")return this.events.splice(e,1),this.undoneEvents.push(r),r}return null}popLastUndo(){return this.undoneEvents.pop()??null}size(){return this.events.length}clear(){this.events=[],this.undoneEvents=[],this.nextId=1}}function Uf(t){return new Date(t.toMillis()).toISOString()}class Fr extends Error{method;path;debugMessages;constructor(e,r,n,s){super(e),this.method=r,this.path=n,this.debugMessages=s,this.name="SimulatorUnsupportedError"}}function Lr(t,e,r){const n=r.filter(i=>i.includes("unsupported:")).map(i=>i.replace(/^.*unsupported:\s*/,"")).join("; "),s=n?` Reason(s): ${n}.`:"";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 Bf(t=""){return{description:t,expectation:"ALLOW",state:"PASSED",decision:"ALLOW",trace:[],notes:["admin lens — rules bypassed (Studio Gap #2)"]}}const zf=`rules_version = '2';
1139
+ service cloud.firestore {
1140
+ match /databases/{database}/documents {
1141
+ match /{document=**} {
1142
+ allow read, write: if true;
1143
+ }
1144
+ }
1145
+ }
1146
+ `;class Ot{swallowAsyncRejections;subscribers=new Set;constructor(e=!1){this.swallowAsyncRejections=e}get hasSubscribers(){return this.subscribers.size>0}subscribe(e){return this.subscribers.add(e),()=>{this.subscribers.delete(e)}}emit(...e){for(const r of this.subscribers)try{const n=r(...e);this.swallowAsyncRejections&&n&&typeof n.then=="function"&&n.catch(()=>{})}catch{}}clear(){this.subscribers.clear()}}class Vf{denial=new Ot;request=new Ot(!0);write=new Ot(!0);delivery=new Ot;suppressed=new Ot;lifecycle=new Ot;snapshotError=new Ot;clear(){this.denial.clear(),this.request.clear(),this.write.clear(),this.delivery.clear(),this.suppressed.clear(),this.lifecycle.clear(),this.snapshotError.clear()}}class Wf{currentTrigger;run(e,r){const n=this.currentTrigger;this.currentTrigger=e;try{return r()}finally{this.currentTrigger=n}}current(){return this.currentTrigger}}class ce extends Error{code;simError;constructor(e){super(e.message),this.name="FirestoreError",this.code=e.code,this.simError=e}}const Oa=Symbol.for("pyric.firestore.activity-value-registry"),Ca=globalThis,fc=Ca[Oa]??(Ca[Oa]=new WeakMap);function pc(){let t=2166136261,e=2654435769,r=2246822507,n=3266489909;const s=i=>{t=Math.imul(t^i,16777619),e=Math.imul(e^i,2246822507),r=Math.imul(r^i,3266489909),n=Math.imul(n^i,668265263)};return{update:i=>{if(typeof i=="string")for(let a=0;a<i.length;a+=1){const o=i.charCodeAt(a);s(o&255),s(o>>>8)}else for(const a of i)s(a)},finish:()=>[t,e,r,n].map(i=>(i>>>0).toString(16).padStart(8,"0")).join("")}}function pi(...t){const e=pc();for(const r of t)e.update(r);return e.finish()}function Hf(t){return{type:"string-digest",length:t.length,digest:pi("string\0",t)}}function qt(t,...e){return{type:`${t}-digest`,digest:pi(`${t}\0`,...e)}}function Gf(t){return{type:"bytes-digest",length:t.byteLength,digest:pi("bytes\0",t)}}function Ta(t){const e=pc(),r=(...s)=>{for(const i of s)e.update(i)},n=s=>{if(s===null){r("null;");return}switch(typeof s){case"string":r(`s${s.length}:`,s,";");return;case"number":r(`n${Object.is(s,-0)?"-0":String(s)};`);return;case"boolean":r(s?"b1;":"b0;");return;case"undefined":r("u;");return;case"bigint":r(`i${s.toString()};`);return;case"object":break;default:r(`x${typeof s};`);return}if(Array.isArray(s)){r(`a${s.length}[`);for(const o of s)n(o);r("];");return}const i=s,a=Object.keys(i).sort();r(`o${a.length}{`);for(const o of a)r(`k${o.length}:`,o,"="),n(i[o]);r("};")};return n(t),{type:"wire-value-digest",digest:e.finish()}}function st(t,e){fc.set(t,e)}function Kf(t){return fc.get(t)}class Zf{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 bt{seconds;nanoseconds;constructor(e,r){this.seconds=e,this.nanoseconds=r,st(this,qt("timestamp",String(e),"\0",String(r))),Ht(this,Object.freeze({type:"timestamp",seconds:e,nanoseconds:r}),()=>new bt(e,r))}static now(){return bt.fromMillis(Date.now())}static fromDate(e){return bt.fromMillis(e.getTime())}static fromMillis(e){const r=Math.floor(e/1e3),n=Math.floor((e-r*1e3)*1e6);return new bt(r,n)}toDate(){return new Date(this.toMillis())}toMillis(){return this.seconds*1e3+this.nanoseconds/1e6}isEqual(e){return e.seconds===this.seconds&&e.nanoseconds===this.nanoseconds}toString(){return`Timestamp(seconds=${this.seconds}, nanoseconds=${this.nanoseconds})`}toJSON(){return{type:"firestore/timestamp/1.0",seconds:this.seconds,nanoseconds:this.nanoseconds}}valueOf(){const r=this.seconds- -62135596800,n=String(r).padStart(12,"0"),s=String(this.nanoseconds).padStart(9,"0");return`${n}.${s}`}}function Ls(t){return t instanceof xe?new bt(t.seconds,t.nanos):t instanceof Be||t instanceof rt||t instanceof Wt?t:Array.isArray(t)?t.map(Ls):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).map(([e,r])=>[e,Ls(r)])):t}function jr(t){return Ls(t)}const Jf=/[*~/[\]]/,Qf=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class kn{_internalPath;constructor(...e){if(Array.isArray(e[0]))throw new Error("The FieldPath constructor no longer supports an array as its first argument. Please unpack your array and call FieldPath() with individual arguments.");if(e.length===0)throw new Error('Function "FieldPath()" requires at least 1 argument.');e.forEach((r,n)=>{if(typeof r!="string")throw new Error(`Element at index ${n} is not a valid string.`);if(r.length===0)throw new Error(`Element at index ${n} should not be an empty string.`)}),this._internalPath={segments:[...e],offset:0,len:e.length}}static DOCUMENT_ID=new kn("__name__");static documentId(){return kn.DOCUMENT_ID}isEqual(e){const r=mc(e),n=this._internalPath.segments;return n.length===r.length&&n.every((s,i)=>s===r[i])}toString(){return this._internalPath.segments.map(e=>Qf.test(e)?e:`\`${e.replace(/\\/g,"\\\\").replace(/`/g,"\\`")}\``).join(".")}}function lr(t){return new Error(`Value for argument "field" is not a valid field path. ${t}`)}function mc(t){if(t instanceof kn)return t._internalPath.segments;if(typeof t=="object"&&t!==null){const e=t._internalPath;if(Array.isArray(e?.segments)&&e.segments.every(r=>typeof r=="string"))return[...e.segments]}if(t===void 0)throw lr("The path cannot be omitted.");if(typeof t!="string")throw lr("Paths can only be specified as strings or via a FieldPath object.");if(t.includes(".."))throw lr('Paths must not contain ".." in them.');if(t.startsWith(".")||t.endsWith("."))throw lr('Paths must not start or end with ".".');if(t.length===0||Jf.test(t))throw lr(`Paths can't be empty and must not contain
1147
+ "*~/[]".`);return t.split(".")}function Yf(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function or(t,e){const r=mc(e);let n=t;for(const s of r){if(!Yf(n))return;n=Object.prototype.hasOwnProperty.call(n,s)?n[s]:void 0}return n}const nr=Object.freeze({hasPendingWrites:!1,fromCache:!1}),Ra=Object.freeze({hasPendingWrites:!0,fromCache:!1});function gc(t){const e=t.lastIndexOf("/");return e===-1?t:t.slice(e+1)}function Jt(t,e,r=nr){const n={id:gc(t),path:t},s=e!==null,i=s?jr(e):void 0;return{id:n.id,ref:n,metadata:r,exists:()=>s,data:()=>i,get:a=>or(i,a)}}function yc(t,e,r=nr){const n={id:gc(t),path:t},s=jr(e);return{id:n.id,ref:n,metadata:r,exists:()=>!0,data:()=>s,get:i=>or(s,i)}}function Qt(t,e,r,n,s=nr){const i=e.map(u=>yc(u.path,u.data,s)),a=n?Xf(n,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&&r.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 Xf(t,e,r,n=nr){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:yc(c.path,c.data,n),oldIndex:o,newIndex:-1})}for(let o=0;o<e.length;o++){const c=e[o],u=s.get(c.path);if(u===void 0)a.push({type:"added",doc:r[o],oldIndex:-1,newIndex:o});else{const d=t[u].data;JSON.stringify(d)!==JSON.stringify(c.data)&&a.push({type:"modified",doc:r[o],oldIndex:u,newIndex:o})}}return a}function Na(t,e){return t===null&&e===null?!0:t===null||e===null?!1:JSON.stringify(t)===JSON.stringify(e)}function ep(t,e){const r=`${e}/`;for(const n of t){if(!n.startsWith(r))continue;const s=n.slice(r.length);if(s.length>0&&!s.includes("/"))return!0}return!1}let es=0;function vr(){return es=es+1>>>0,`req-${es.toString(36)}-${Math.random().toString(36).slice(2,7)}`}function tp(t,e){const r=e==="allow";let n;for(const s of t){const i=/^Rule #(\d+) \(([^)]+)\) → (ALLOW|deny|unsupported)/.exec(s);if(!i)continue;const a={ruleIndex:Number(i[1]),operations:i[2].split(",").map(o=>o.trim())};if(r&&i[3]==="ALLOW")return a;n=a}return n}function Mn(t){const e={kind:"request",id:vr(),at:t.at,evalMs:t.evalMs,method:t.method,path:t.path,auth:t.auth?{uid:t.auth.uid,...t.auth.token?{token:t.auth.token}:{}}:null,result:t.result,reasons:t.debugMessages,origin:t.origin};t.resourceData!==void 0&&(e.request={resourceData:t.resourceData}),t.resourceBefore!==void 0&&(e.resourceBefore=t.resourceBefore),t.resourceAfter!==void 0&&(e.resourceAfter=t.resourceAfter);const r=tp(t.debugMessages,t.result);return r&&(e.matchedRule=r),t.result!=="unsupported"&&t.evaluatedRule&&(e.evaluatedRule=t.evaluatedRule),t.groupId!==void 0&&(e.groupId=t.groupId,t.origin==="batch"?e.groupKind="batch":t.origin==="transaction"&&(e.groupKind="transaction")),t.triggeredBy!==void 0&&(e.triggeredBy=t.triggeredBy),t.detail!==void 0&&(e.detail=t.detail),t.provenance!==void 0&&Object.assign(e,t.provenance),e}class rp{events;triggerScope;host;snapshotListeners=new Map;nextListenerId=0;deliveryQueue=[];deliveryScheduled=!1;constructor(e,r,n){this.events=e,this.triggerScope=r,this.host=n}emitSnapshotDelivery(e){if(!this.events.delivery.hasSubscribers)return;const r={kind:"snapshot_delivery",id:vr().replace(/^req-/,"snd-"),at:Date.now(),listenerId:e.listenerId,target:e.target,auth:e.auth?{uid:e.auth.uid,...e.auth.token?{token:e.auth.token}:{}}:null,addedCount:e.addedCount,modifiedCount:e.modifiedCount,removedCount:e.removedCount,size:e.size,...e.sample?{sample:e.sample}:{},...e.triggeredBy?{triggeredBy:e.triggeredBy}:{}};this.events.delivery.emit(r)}emitSnapshotSuppressed(e){if(!this.events.suppressed.hasSubscribers)return;const r={kind:"snapshot_suppressed",id:vr().replace(/^req-/,"sup-"),at:Date.now(),listenerId:e.listenerId,target:e.target,auth:e.auth?{uid:e.auth.uid,...e.auth.token?{token:e.auth.token}:{}}:null,reason:"no-op",...e.triggeredBy?{triggeredBy:e.triggeredBy}:{}};this.events.suppressed.emit(r)}emitLifecycle(e){if(!this.events.lifecycle.hasSubscribers)return;const r={kind:e.phase,id:vr().replace(/^req-/,"lc-"),at:Date.now(),listenerId:e.listenerId,target:e.target,auth:e.auth?{uid:e.auth.uid,...e.auth.token?{token:e.auth.token}:{}}:null};this.events.lifecycle.emit(r)}emitSnapshotError(e,r,n){this.events.snapshotError.emit(e,r,n)}addSnapshotListener(e,r,n={},s=null,i,a=!1,o=!1,c){const u=String(this.nextListenerId++),d={id:u,target:e,callback:r,auth:s,bypassRules:o,followsCurrentUser:a,...c?{authScope:c}:{},options:n,currentSnapshot:void 0,errored:!1,...i?{errorCallback:i}:{}};return this.snapshotListeners.set(u,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=Jt(e.target.path,s.data);e.currentSnapshot=i,e.currentDocData=s.data;try{e.callback(i)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"doc",path:e.target.path},auth:e.auth,addedCount:s.data!==null?1:0,modifiedCount:0,removedCount:0,size:s.data!==null?1:0,sample:{docs:[{path:e.target.path,data:s.data}]}});return}const r=this.host.silentReadCollection(e.target.collection,e.auth,e.target.constraints,e.bypassRules);if(!r.allowed){this.markErrored(e,r.error);return}const n=Qt({path:e.target.collection},r.docs,{excludesMetadataChanges:!e.options.includeMetadataChanges});e.currentSnapshot=n,e.currentDocs=r.docs;try{e.callback(n)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"query",collection:e.target.collection},auth:e.auth,addedCount:r.docs.length,modifiedCount:0,removedCount:0,size:r.docs.length,sample:{docs:r.docs.map(s=>({path:s.path,data:s.data}))}})}scheduleDelivery(e){this.deliveryQueue.push(e),!this.deliveryScheduled&&(this.deliveryScheduled=!0,queueMicrotask(()=>this.drainDeliveries()))}scheduleTriggeredDelivery(e,r){this.scheduleDelivery(()=>this.triggerScope.run(e,r))}drainDeliveries(){for(this.deliveryScheduled=!1;this.deliveryQueue.length>0;)this.deliveryQueue.shift()()}flushListeners(){this.drainDeliveries()}notifyListenersForPaths(e){if(e.size===0||this.snapshotListeners.size===0)return;const r=this.triggerScope.current(),n=Array.from(this.snapshotListeners.values());for(const s of n)this.scheduleTriggeredDelivery(r,()=>{this.snapshotListeners.has(s.id)&&(s.errored||(s.target.kind==="doc"?this.notifyDocListener(s,e):this.notifyQueryListener(s,e)))})}notifyDocListener(e,r){if(e.target.kind!=="doc"||!r.has(e.target.path))return;const n=this.host.silentReadDoc(e.target.path,e.auth,e.bypassRules);if(!n.allowed){this.markErrored(e,n.error);return}const s=e.currentDocData??null;if(Na(s,n.data)){this.emitSnapshotSuppressed({listenerId:e.id,target:{kind:"doc",path:e.target.path},auth:e.auth,...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}});return}const i=e.target.path,a=Jt(i,n.data,Ra);e.currentSnapshot=a,e.currentDocData=n.data;const o=s!==null,c=n.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:n.data}]},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),this.scheduleDocMetadataAck(e,i,n.data)}scheduleDocMetadataAck(e,r,n){e.options.includeMetadataChanges&&this.scheduleTriggeredDelivery(this.triggerScope.current(),()=>{if(!this.snapshotListeners.has(e.id)||e.errored)return;const s=Jt(r,n,nr);e.currentSnapshot=s;try{e.callback(s)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"doc",path:r},auth:e.auth,addedCount:0,modifiedCount:0,removedCount:0,size:n!==null?1:0,sample:{docs:[{path:r,data:n}]},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}})})}notifyQueryListener(e,r){if(e.target.kind!=="query"||!ep(r,e.target.collection))return;const n=this.host.silentReadCollection(e.target.collection,e.auth,e.target.constraints,e.bypassRules);if(!n.allowed){this.markErrored(e,n.error);return}const s=e.target.collection,i=e.currentDocs??[],a=Qt({path:s},n.docs,{excludesMetadataChanges:!e.options.includeMetadataChanges},i,Ra),o=a.docChanges();if(o.length===0){if(e.options.includeMetadataChanges){e.currentSnapshot=a,e.currentDocs=n.docs;try{e.callback(a)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"query",collection:s},auth:e.auth,addedCount:0,modifiedCount:0,removedCount:0,size:n.docs.length,sample:{docs:n.docs.map(l=>({path:l.path,data:l.data}))},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),this.scheduleQueryMetadataAck(e,s,n.docs);return}this.emitSnapshotSuppressed({listenerId:e.id,target:{kind:"query",collection:s},auth:e.auth,...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}});return}e.currentSnapshot=a,e.currentDocs=n.docs;let c=0,u=0,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:n.docs.length,sample:{docs:n.docs.map(l=>({path:l.path,data:l.data}))},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),this.scheduleQueryMetadataAck(e,s,n.docs)}scheduleQueryMetadataAck(e,r,n){e.options.includeMetadataChanges&&this.scheduleTriggeredDelivery(this.triggerScope.current(),()=>{if(!this.snapshotListeners.has(e.id)||e.errored)return;const s=Qt({path:r},n,{excludesMetadataChanges:!1},n,nr);e.currentSnapshot=s;try{e.callback(s)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"query",collection:r},auth:e.auth,addedCount:0,modifiedCount:0,removedCount:0,size:n.length,sample:{docs:n.map(i=>({path:i.path,data:i.data}))},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}})})}markErrored(e,r){if(e.errored=!0,this.emitSnapshotError(r,e.target,e.id),!!e.errorCallback)try{e.errorCallback(r)}catch{}}reEvaluateAllListeners(){if(this.snapshotListeners.size===0)return;const e=Array.from(this.snapshotListeners.values());for(const r of e)this.snapshotListeners.has(r.id)&&(r.target.kind==="doc"?this.reEvaluateDocListener(r):this.reEvaluateQueryListener(r))}reevaluateLiveListeners(e,r){if(this.snapshotListeners.size===0)return;const n=Array.from(this.snapshotListeners.values());for(const s of n)s.followsCurrentUser&&s.authScope===r&&this.snapshotListeners.has(s.id)&&(s.auth=e,s.target.kind==="doc"?this.reEvaluateDocListener(s):this.reEvaluateQueryListener(s))}reEvaluateDocListener(e){if(e.target.kind!=="doc")return;const r=this.host.silentReadDoc(e.target.path,e.auth,e.bypassRules);if(!r.allowed){if(e.errored)return;this.markErrored(e,r.error);return}if(e.errored){e.errored=!1;const i=Jt(e.target.path,r.data);e.currentSnapshot=i,e.currentDocData=r.data;try{e.callback(i)}catch{}return}const n=e.currentDocData??null;if(Na(n,r.data))return;const s=Jt(e.target.path,r.data);e.currentSnapshot=s,e.currentDocData=r.data;try{e.callback(s)}catch{}}reEvaluateQueryListener(e){if(e.target.kind!=="query")return;const r=this.host.silentReadCollection(e.target.collection,e.auth,e.target.constraints,e.bypassRules);if(!r.allowed){if(e.errored)return;this.markErrored(e,r.error);return}if(e.errored){e.errored=!1;const a=Qt({path:e.target.collection},r.docs,{excludesMetadataChanges:!e.options.includeMetadataChanges});e.currentSnapshot=a,e.currentDocs=r.docs;try{e.callback(a)}catch{}return}const n=e.currentDocs??[],s=Qt({path:e.target.collection},r.docs,{excludesMetadataChanges:!e.options.includeMetadataChanges},n);if(s.docChanges().length!==0){e.currentSnapshot=s,e.currentDocs=r.docs;try{e.callback(s)}catch{}}}getSnapshotListenerCount(){return this.snapshotListeners.size}dispose(){this.snapshotListeners.clear(),this.deliveryQueue.length=0,this.deliveryScheduled=!1}}class np{eventLog;host;constructor(e,r){this.eventLog=e,this.host=r}undo(){const e=this.eventLog.popLastWrite();if(!e)return null;if(e.priorDocs)this.host.state.restorePaths(e.priorDocs);else if(e.snapshot)this.host.state.restore(e.snapshot);else return null;return e}redo(){const e=this.eventLog.popLastUndo();if(!e)return null;const r=e.type==="batch"&&e.operations?e.operations.map(o=>o.path):e.path?[e.path]:[],n=!!e.snapshot,s=n?void 0:this.host.capturePriors(r),i=n?this.host.state.snapshot():void 0;if(e.type==="batch"&&e.operations)for(const o of e.operations)o.allowed&&this.host.applyWrite(o.method,o.path,o.data);else e.allowed&&this.host.applyWrite(e.method,e.path,e.data);const a=this.eventLog.append({...e,snapshot:i,priorDocs:s},!0);return{allowed:e.allowed,debugMessages:["Redo: "+(e.allowed?"applied":"skipped (was denied)")],event:a}}getEvents(){return this.eventLog.getEvents()}getEventCount(){return this.eventLog.size()}}class sp{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:si(this.currentSource)}),this.parsedCache.ast}}function ee(t,e,r){const n={code:t,message:e};return r?.request&&(n.request=r.request),r?.resource&&(n.resource=r.resource),r?.remediation&&(n.remediation=r.remediation),r?.query&&(n.query=r.query),n}function Pn(t,e,r){const n=t.get(e.path),s=e.method==="set"?n!==null?"update":"create":e.method;let i=e.data;if(e.method==="get"||e.method==="list")i=void 0;else if(e.method==="update"&&n&&e.data){const{writes:a,deletedKeys:o}=Tt(e.data),c={...n,...a};for(const u of o)delete c[u];i=c}else e.data&&(i=Tt(e.data).writes);return{description:`${e.method} ${e.path}`,expectation:"ALLOW",method:s,path:e.path,auth:e.auth?{uid:e.auth.uid,token:e.auth.token}:null,data:i,resource:n??void 0,...r?{requestTime:Uf(r)}:{}}}function bc(t,e,r,n,s,i){if(s){const a=n.map(o=>Bf(o.description));return{success:!0,data:{passed:a.length,failed:0,unsupported:0,results:a}}}return r.simulate(e.source,n,{getDoc:a=>t.get(a),...i?{batchProjection:i}:{}})}class ip{events;rules;simulator;host;eventLog;constructor(e,r,n,s,i){this.events=e,this.rules=r,this.simulator=n,this.host=s,this.eventLog=i}get state(){return this.host.state}emitRequest(e){this.events.request.hasSubscribers&&this.events.request.emit(Mn(e))}emitDenial(e){this.events.denial.emit(e)}execute(e){const{method:r,path:n,auth:s,bypassRules:i}=e,a=i?{admin:!0}:void 0,o=xe.fromMillis(Date.now()),c=Pn(this.state,e,o),u=Date.now(),d=performance.now(),l=bc(this.state,this.rules,this.simulator,[c],i),f=performance.now()-d;if(!l.success){const L=this.eventLog.append({type:"single",method:r,path:n,auth:s?{uid:s.uid}:null,allowed:!1,debugMessages:[`Simulation error: ${l.error.message}`]});return this.emitRequest({at:u,evalMs:f,method:r,path:n,auth:s,result:"deny",debugMessages:[`Simulation error: ${l.error.message}`],origin:"user",...a?{detail:a}:{}}),{allowed:!1,debugMessages:[l.error.message],event:L}}const y=l.data.results[0];if(y.state==="UNSUPPORTED")throw this.emitRequest({at:u,evalMs:f,method:r,path:n,auth:s,result:"unsupported",debugMessages:Se(y),origin:"user",...a?{detail:a}:{}}),new Fr(Lr(r,n,Se(y)),r,n,Se(y));const b=y.state==="PASSED";let S;b&&(S=r==="get"?this.state.get(n):this.state.list(n));const j=this.eventLog.append({type:"single",method:r,path:n,auth:s?{uid:s.uid}:null,allowed:b,debugMessages:Se(y)}),T={allowed:b,data:b?S:void 0,debugMessages:Se(y),event:j};if(!b){const L={method:r,path:n,auth:s},k=r==="get"?{data:this.state.get(n),exists:this.state.get(n)!==null}:void 0;T.error=ee("permission-denied",`${r} ${n} denied by rules`,{request:L,...k?{resource:k}:{}}),this.emitDenial(T.error)}return this.emitRequest({at:u,evalMs:f,method:r,path:n,auth:s,result:b?"allow":"deny",debugMessages:Se(y),evaluatedRule:Er(y),origin:"user",...r==="get"?{resourceBefore:{data:this.state.get(n),exists:this.state.get(n)!==null}}:{},...a?{detail:a}:{}}),T}}function vc(t){const e=new Map,r=new Set;for(const n of t)e.has(n.name)&&r.add(n.name),e.set(n.name,n);return{functions:e,ambiguousNames:r}}function wc(t,e,r,n=ap){const s=new Set;return{pathInvariant:!Gr(t,e,r,n,new Set,new Set,s),requiredFunctions:s}}function Gr(t,e,r,n,s,i,a){const o=c=>Gr(c,e,r,n,s,i,a);switch(t.type){case"literal":return!1;case"identifier":return!s.has(t.name)&&(e.has(t.name)||t.name==="request");case"memberAccess":return t.object.type==="identifier"&&t.object.name==="request"?!Fa.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"&&Fa.has(t.index.value)):o(t.object)||o(t.index);case"sliceAccess":return o(t.object)||o(t.start)||o(t.end);case"binaryOp":return o(t.left)||o(t.right);case"unaryOp":return o(t.operand);case"ternary":return o(t.condition)||o(t.consequent)||o(t.alternate);case"inExpr":return o(t.element)||o(t.collection);case"isExpr":return o(t.value);case"listLiteral":return t.elements.some(o);case"mapLiteral":return t.entries.some(c=>o(c.key)||o(c.value));case"pathLiteral":return t.segments.some(c=>typeof c!="string"&&o(c));case"functionCall":{if(t.args.some(o)||n.has(t.name))return!0;const c=r.get(t.name);if(!c)return!1;if(a.add(c.name),i.has(c.name))return!0;const u=new Set(i).add(c.name),d=new Set(c.parameters);for(const l of c.lets){if(Gr(l.value,e,r,n,d,u,a))return!0;d.add(l.name)}return Gr(c.body,e,r,n,d,u,a)}}}const Fa=new Set(["auth","method","query","time"]),ap=new Set;function op(t){if(!t)return null;const e=[...t.functions??[],...t.service.functions??[],...t.service.match.functions],r=new Set,n=t.service.match.children.flatMap(i=>{const a=cp(i,e,r);return a?[a]:[]});if(n.length===0)return null;const s=i=>i?.filter(a=>r.has(a.name));return{...t,functions:s(t.functions),service:{...t.service,functions:s(t.service.functions),match:{...t.service.match,functions:s(t.service.match.functions)??[],children:n}}}}function cp(t,e,r){const n=t.path.segments[0];if(t.path.segments.length!==1||n?.type!=="recursive")return null;const s=vc([...e,...t.functions]),i=t.allows.filter(a=>{if(!a.operations.some(c=>c==="list"||c==="read"))return!1;const o=wc(a.condition,new Set([n.name]),s.functions,s.ambiguousNames);if(o.pathInvariant)for(const c of o.requiredFunctions)r.add(c);return o.pathInvariant});return i.length===0?null:{...t,functions:t.functions.filter(a=>r.has(a.name)),allows:i,children:[]}}function up(t,e,r,n){if(!t)return{kind:"no-rule"};const s=e.split("/").filter(d=>d.length>0),i=[...t.functions??[],...t.service.functions??[],...t.service.match.functions],a=[];for(const d of t.service.match.children)a.push(...an(d,s,i));if(a.length===0)return{kind:"no-rule"};const o=[],c=new Set;let u=0;for(const d of a){const l=vc(d.functions),f=l.functions;for(const y of d.block.allows){if(!y.operations.some(j=>j==="list"||j==="read"))continue;if(u++,!wc(y.condition,new Set(d.candidateVariables),f,l.ambiguousNames).pathInvariant){o.push({reason:"list rule depends on the candidate document path",residual:{missing:[],mismatched:[]}});continue}const S=Ld(y.condition,n,f,r?.uid);S.provable?c.add(y):o.push({reason:S.reason,residual:S.residual})}}if(u===0)return{kind:"no-rule"};if(c.size===0){const d=o[0];return{kind:"unprovable",reason:d?.reason??"list rule depends on per-document data the query cannot guarantee",residual:d?.residual??{missing:[],mismatched:[]}}}return{kind:"provable",evaluationAst:lp(t,c),syntheticResource:dp(n)}}function lp(t,e){const r=n=>({...n,allows:n.allows.filter(s=>e.has(s)),children:n.children.map(r)});return{...t,service:{...t.service,match:r(t.service.match)}}}function dp(t){const e={};for(const r of t.where??[])r.op==="=="&&(e[r.field]=r.value);return e}function hp(t){const e=[];for(const n of t.missing)n.fromAuthUid?e.push(` .where('${n.field}', '==', request.auth.uid) // request.auth.uid is ${JSON.stringify(n.expectedValue)}`):e.push(` .where('${n.field}', '==', ${JSON.stringify(n.expectedValue)})`);for(const n of t.mismatched)e.push(` .where('${n.field}', '==', ${JSON.stringify(n.expectedValue)}) // the query pins ${JSON.stringify(n.actualValue)}, but the rule requires ${JSON.stringify(n.expectedValue)}`);return e.length===0?void 0:`The list rule requires per-document equalities the query does not guarantee. Add the matching where(...) constraint(s) so every returned document satisfies the rule:
1148
+ ${e.join(`
1149
+ `)}`}function fp(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 pp{events;rules;simulator;host;constructor(e,r,n,s){this.events=e,this.rules=r,this.simulator=n,this.host=s}authorize(e){const{path:r,auth:n,constraints:s,origin:i,triggeredBy:a}=e,o=fp(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:r,auth:n,result:"allow",debugMessages:[i==="listener"?"admin lens — rules bypassed":"admin lens — rules bypassed (Studio Gap #2)"],origin:i,...u?{detail:u}:{},...a?{triggeredBy:a}:{}}),{allowed:!0};const f=this.rules.ast(),y=e.collectionGroup?op(f):f;if(e.collectionGroup&&!y){const x=`list ${r} denied: symbolic collection-group proof is not supported; the query is rejected rather than authorizing from the currently stored rows`;this.emitRequest({at:l,evalMs:0,method:"list",path:r,auth:n,result:"deny",debugMessages:[x],origin:i,...u?{detail:u}:{},...a?{triggeredBy:a}:{}});const _=ee("permission-denied",x,{request:{method:"list",path:r,auth:n},query:s});return this.emitUserDenial(i,_),{allowed:!1,error:_}}const b=`${r}/__listPlaceholder__`,S=performance.now(),j=up(y,b,n,s);if(j.kind==="unprovable"){const x=`list ${r} denied: the query is statically unprovable for every possible result (rules are not filters), so the whole query is rejected — ${j.reason}`,_=hp(j.residual);this.emitRequest({at:l,evalMs:performance.now()-S,method:"list",path:r,auth:n,result:"deny",debugMessages:[x],origin:i,...u?{detail:u}:{},...a?{triggeredBy:a}:{}});const v=ee("permission-denied",x,{request:{method:"list",path:r,auth:n},query:s,..._?{remediation:_}:{}});return this.emitUserDenial(i,v),{allowed:!1,error:v}}const T=j.kind==="provable"?en(j.evaluationAst):e.collectionGroup?en(y):this.rules.source,L=Pn(this.host.state,{method:"list",path:b,auth:n},d);this.applyProof(L,j,s);const k=this.simulator.simulate(T,[L],{getDoc:x=>this.host.state.get(x)}),$=performance.now()-S;if(!k.success)return this.emitRequest({at:l,evalMs:$,method:"list",path:r,auth:n,result:"deny",debugMessages:[`Simulation error: ${k.error.message}`],origin:i,...u?{detail:u}:{},...a?{triggeredBy:a}:{}}),{allowed:!1,error:ee("permission-denied",`list ${r} simulator error`,{request:{method:"list",path:r,auth:n}})};const V=k.data.results[0],w=Se(V);if(V.state==="UNSUPPORTED")throw this.emitRequest({at:l,evalMs:$,method:"list",path:r,auth:n,result:"unsupported",debugMessages:w,origin:i,...u?{detail:u}:{},...a?{triggeredBy:a}:{}}),new Fr(Lr("list",r,w),"list",r,w);if(V.state!=="PASSED"){this.emitRequest({at:l,evalMs:$,method:"list",path:r,auth:n,result:"deny",debugMessages:w,evaluatedRule:Er(V),origin:i,...u?{detail:u}:{},...a?{triggeredBy:a}:{}});const x=ee("permission-denied",`list ${r} denied by rules`,{request:{method:"list",path:r,auth:n}});return this.emitUserDenial(i,x),{allowed:!1,error:x}}return this.emitRequest({at:l,evalMs:$,method:"list",path:r,auth:n,result:"allow",debugMessages:w,evaluatedRule:Er(V),origin:i,...u?{detail:u}:{},...a?{triggeredBy:a}:{}}),{allowed:!0}}applyProof(e,r,n){r.kind==="provable"&&(e.resource=r.syntheticResource),(n.limit!=null||n.offset!=null||n.orderBy!=null)&&(e.query={...n.limit!=null?{limit:n.limit}:{},...n.offset!=null?{offset:n.offset}:{},...n.orderBy!=null?{orderBy:n.orderBy}:{}})}emitRequest(e){this.events.request.hasSubscribers&&this.events.request.emit(Mn(e))}emitUserDenial(e,r){e==="user"&&this.events.denial.emit(r)}}function mp(t,e,r){if(e<=0)return[];const n=[];for(const s of t)n.length<e?La(n,s,r):r(s,n[n.length-1])<0&&(n.pop(),La(n,s,r));return n}function La(t,e,r){let n=0,s=t.length;for(;n<s;){const i=n+s>>1;r(e,t[i])<0?s=i:n=i+1}t.splice(n,0,e)}function gp(t){return typeof t.seconds=="number"&&(typeof t.nanos=="number"||typeof t.nanoseconds=="number")}function yp(t){return typeof t.latitude=="number"&&typeof t.longitude=="number"}function bp(t){return t.data instanceof Uint8Array}function vp(t){return typeof t.path=="string"}function En(t){if(t==null)return 0;const e=typeof t;if(e==="boolean")return 1;if(e==="number"||e==="bigint")return 2;if(e==="string")return 4;if(Array.isArray(t))return 8;if(e==="object"){const r=t;return gp(r)?3:bp(r)?5:yp(r)?7:vp(r)?6:9}return 9}function ja(t){const e=typeof t.nanos=="number"?t.nanos:t.nanoseconds??0;return[t.seconds,e]}function wp(t,e){const r=Number.isNaN(t),n=Number.isNaN(e);return r&&n?0:r?-1:n?1:t<e?-1:t>e?1:0}function Da(t,e){return t<e?-1:t>e?1:0}function At(t,e){const r=En(t),n=En(e);if(r!==n)return r<n?-1:1;switch(r){case 0:return 0;case 1:return t===e?0:t?1:-1;case 2:return wp(Number(t),Number(e));case 3:{const[s,i]=ja(t),[a,o]=ja(e);return s!==a?s<a?-1:1:i<o?-1:i>o?1:0}case 4:return Da(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 Da(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=At(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=At(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 Sp(t){const e=t.kind;if(e==="collection"){const r=t.path;return Object.freeze({kind:e,path:r})}if(e==="collection-group"){const r=t.collectionId;return Object.freeze({kind:e,collectionId:r})}throw new ce({code:"invalid-argument",message:`Unknown query scope kind: ${String(e)}`})}function Ma(t){const e=u=>{const d=u.kind;if(d==="where"){const f=u.field,y=u.op,b=u.value;return Object.freeze({kind:d,field:f,op:y,value:b})}if(d!=="and"&&d!=="or")throw new ce({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))})},r=u=>{if(u===void 0)return;const d=u.values,l=u.inclusive,f=u.fromSnapshot;return Object.freeze({values:Object.freeze(Array.from(d)),inclusive:l,fromSnapshot:f})},n=t.filters,s=t.orders,i=t.limitCount,a=t.limitFromEnd,o=t.start,c=t.end;return Object.freeze({filters:Object.freeze(Array.from(n,e)),orders:Object.freeze(Array.from(s,u=>{const d=u.field,l=u.direction;return Object.freeze({field:d,direction:l})})),limitCount:i,limitFromEnd:a,start:r(o),end:r(c)})}function Pa(t){const e=[],r=n=>{if(n.kind==="where"){if(n.field===wt)return;const s=n.value;(s===null||typeof s=="string"||typeof s=="number"||typeof s=="boolean")&&e.push(Object.freeze({field:n.field,op:n.op,value:s}));return}n.kind==="and"&&n.filters.forEach(r)};return t.filters.forEach(r),Object.freeze({where:Object.freeze(e),limit:t.limitCount??null,offset:null,orderBy:t.orders.length>0?t.orders[0].field:null})}function _p(t,e){if(e.kind==="collection")return t.scan(e.path,{directOnly:!0});const r=[];for(const[n,s]of Object.entries(t.snapshot())){const i=n.split("/").filter(a=>a.length>0);i.length>0&&i.length%2===0&&i[i.length-2]===e.collectionId&&r.push({path:n,data:s})}return r}const wt="__name__",Ap=new Set(["<","<=",">",">=","!=","not-in"]);function js(t,e){return e===wt?{path:t.path}:t.data[e]}function mi(t){return t.kind==="where"?Ap.has(t.op)?[t.field]:[]:t.filters.flatMap(mi)}function xp(t){return mi(t).length>0}function $n(t,e){return En(t)===En(e)}function Ip(t,e){return $n(t,e)&&At(t,e)<0}function kp(t,e){return $n(t,e)&&At(t,e)<=0}function Ep(t,e){return $n(t,e)&&At(t,e)>0}function Op(t,e){return $n(t,e)&&At(t,e)>=0}function Cp(t,e,r){const n=t!==void 0;switch(e){case"==":return n&&Ge(t,r);case"!=":return n&&t!==null&&!Ge(t,r);case"<":return n&&Ip(t,r);case"<=":return n&&kp(t,r);case">":return n&&Ep(t,r);case">=":return n&&Op(t,r);case"in":return n&&Array.isArray(r)&&r.some(s=>Ge(t,s));case"not-in":return!Array.isArray(r)||r.some(s=>s===null)?!1:n&&t!==null&&!r.some(s=>Ge(t,s));case"array-contains":return Array.isArray(t)&&t.some(s=>Ge(s,r));case"array-contains-any":return Array.isArray(t)&&Array.isArray(r)&&r.some(s=>t.some(i=>Ge(i,s)))}}function Tp(t,e){if(e===wt){const r=t.path.split("/");return r[r.length-1]??t.path}return t.data[e]}function Sc(t){if(Array.isArray(t))return t.map(Sc);if(t&&typeof t=="object"){const e=t;if(typeof e.id=="string")return e.id;if(typeof e.path=="string"){const r=e.path.split("/");return r[r.length-1]??e.path}}return t}function Ds(t,e){if(e.kind==="where"){const r=Tp(t,e.field),n=e.field===wt?Sc(e.value):e.value;return Cp(r,e.op,n)}return e.kind==="and"?e.filters.every(r=>Ds(t,r)):e.filters.some(r=>Ds(t,r))}function Rp(t,e){return t.filter(r=>e.every(n=>Ds(r,n)))}function $a(t,e,r){for(let n=0;n<e.length;n++){const s=At(js(t,r[n].field),e[n]);if(s!==0)return r[n].direction==="desc"?-s:s}return 0}function Np(t,e,r,n){return t.filter(s=>{if(r){const i=$a(s,r.values,e);if(r.inclusive?i<0:i<=0)return!1}if(n){const i=$a(s,n.values,e);if(n.inclusive?i>0:i>=0)return!1}return!0})}function _c(t,e){return t.filter(r=>e.every(n=>n.field===wt||r.data[n.field]!==void 0))}function Ac(t){return(e,r)=>{for(const n of t){const s=At(js(e,n.field),js(r,n.field));if(s!==0)return n.direction==="desc"?-s:s}return 0}}function Fp(t,e){return e.length===0?t:_c(t,e).sort(Ac(e))}function xc(t){const e=[...t.orders],r=new Set(e.map(s=>s.field)),n=t.orders.length>0?t.orders[t.orders.length-1].direction:"asc";for(const s of t.filters)for(const i of mi(s))i!==wt&&!r.has(i)&&(r.add(i),e.push({field:i,direction:n}));return r.has(wt)||e.push({field:wt,direction:n}),e}function ts(t,e){let r=Rp(t,[...e.filters]);const n=xc(e),s=e.orders.length>0||e.start!==void 0||e.end!==void 0||e.filters.some(xp);if(s&&e.limitCount!==void 0&&!e.limitFromEnd&&e.start===void 0&&e.end===void 0)return mp(_c(r,n),e.limitCount,Ac(n));if(s&&(r=Fp(r,n)),e.start||e.end){for(const i of[e.start,e.end])if(i&&!i.fromSnapshot&&i.values.length>e.orders.length)throw new ce({code:"invalid-argument",message:"Too many arguments provided to a cursor (startAt / startAfter / endAt / endBefore). The number of cursor values must be less than or equal to the number of orderBy() clauses."});r=Np(r,n,e.start,e.end)}if(e.limitCount!==void 0)if(e.limitFromEnd){if(e.orders.length===0)throw new ce({code:"unimplemented",message:"limitToLast() queries require at least one orderBy clause."});r=r.slice(-e.limitCount)}else r=r.slice(0,e.limitCount);return r}class Lp{events;triggerScope;rules;simulator;host;operationReader;listAuthorizer;constructor(e,r,n,s,i,a){this.events=e,this.triggerScope=r,this.rules=n,this.simulator=s,this.host=i,this.operationReader=new ip(e,n,s,i,a),this.listAuthorizer=new pp(e,n,s,i)}get state(){return this.host.state}emitRequest(e){this.events.request.hasSubscribers&&this.events.request.emit(Mn(e))}execute(e){return this.operationReader.execute(e)}silentReadDoc(e,r,n=!1){if(n){const y=this.state.get(e);return this.emitRequest({at:Date.now(),evalMs:0,method:"get",path:e,auth:r,result:"allow",debugMessages:["admin lens — rules bypassed"],origin:"listener",resourceBefore:{data:y,exists:y!==null},detail:{admin:!0},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),{allowed:!0,data:y}}const s=xe.fromMillis(Date.now()),i=Pn(this.state,{method:"get",path:e,auth:r},s),a=Date.now(),o=performance.now(),c=this.simulator.simulate(this.rules.source,[i],{getDoc:y=>this.state.get(y)}),u=performance.now()-o;if(!c.success)return this.emitRequest({at:a,evalMs:u,method:"get",path:e,auth:r,result:"deny",debugMessages:[`Simulation error: ${c.error.message}`],origin:"listener",...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),{allowed:!1,error:ee("permission-denied",`get ${e} simulator error`,{request:{method:"get",path:e,auth:r}})};const d=c.data.results[0];if(d.state==="UNSUPPORTED")throw this.emitRequest({at:a,evalMs:u,method:"get",path:e,auth:r,result:"unsupported",debugMessages:Se(d),origin:"listener",...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),new Fr(Lr("get",e,Se(d)),"get",e,Se(d));const l=d.state==="PASSED",f=this.state.get(e);return this.emitRequest({at:a,evalMs:u,method:"get",path:e,auth:r,result:l?"allow":"deny",debugMessages:Se(d),evaluatedRule:Er(d),origin:"listener",resourceBefore:{data:f,exists:f!==null},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),l?{allowed:!0,data:f}:{allowed:!1,error:ee("permission-denied",`get ${e} denied by rules`,{request:{method:"get",path:e,auth:r},resource:{data:f,exists:f!==null}})}}silentReadCollection(e,r,n,s=!1){if(typeof n=="function")return{allowed:!1,error:ee("invalid-argument","Callable query constraints are no longer executable; pass an immutable QueryConstraintPlan.")};const i=n?Ma(n.execution):void 0,a=i?Pa(i):{},o={requestTime:xe.fromMillis(Date.now()),at:Date.now()},c=this.triggerScope.current();if(s){const f=this.state.list(e).filter(S=>!S.phantom).map(S=>({path:S.path,data:S.data})),y=i?ts(f,i):f,b=this.listAuthorizer.authorize({path:e,auth:r,constraints:a,bypassRules:s,...n?.activityQuery?{activityQuery:n.activityQuery}:{},origin:"listener",...c?{triggeredBy:c}:{},timing:o});return b.allowed?{allowed:!0,docs:y}:b}const u=this.listAuthorizer.authorize({path:e,auth:r,constraints:a,...n?.activityQuery?{activityQuery:n.activityQuery}:{},origin:"listener",...c?{triggeredBy:c}:{},timing:o});if(!u.allowed)return u;const d=this.state.list(e).filter(f=>!f.phantom).map(f=>({path:f.path,data:f.data}));return{allowed:!0,docs:i?ts(d,i):d}}runQuery(e){const r=Sp(e.scope),n=Ma(e.execution),s=e.auth,i=e.bypassRules,a=e.activityQuery,o=_p(this.state,r),c=r.kind==="collection"?r.path:r.collectionId,u=Pa(n),d=this.listAuthorizer.authorize({path:c,collectionGroup:r.kind==="collection-group",auth:s,constraints:u,bypassRules:i,...a!==void 0?{activityQuery:a}:{},origin:"user"});return d.allowed?{allowed:!0,docs:ts(o,n)}:d}}const qa="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",Ua=20;function gi(){const t=new Uint8Array(Ua);globalThis.crypto.getRandomValues(t);let e="";for(let r=0;r<Ua;r++)e+=qa[t[r]%qa.length];return e}function Ic(t,e=""){const r=[],n=new WeakSet;return s(t,e),r;function s(i,a){if(i==null||typeof i!="object"||n.has(i)||(n.add(i),ac(i)!==void 0))return;if(Array.isArray(i)){i.forEach((u,d)=>s(u,`${a}[${d}]`));return}const o=i,c=jp(o);if(c){r.push({field:a,kind:c});return}for(const[u,d]of Object.entries(o)){const l=a?`${a}.${u}`:u;s(d,l)}}}function jp(t){const e=t.__type;return e==="serverTimestamp"?"serverTimestamp":e==="increment"?"increment":e==="arrayUnion"?"arrayUnion":e==="arrayRemove"?"arrayRemove":e==="deleteField"?"delete":null}Ff();class Dp{host;rules;simulator;eventLog;events;triggerScope;constructor(e,r,n,s,i,a){this.host=e,this.rules=r,this.simulator=n,this.eventLog=s,this.events=i,this.triggerScope=a}get state(){return this.host.state}emitDenial(e){this.events.denial.emit(e)}emitRequest(e){this.events.request.hasSubscribers&&this.events.request.emit(Mn(e))}emitWrite(e){this.events.write.hasSubscribers&&this.events.write.emit({kind:"write",id:vr().replace(/^req-/,"wr-"),at:Date.now(),method:e.method,path:e.path,auth:e.auth?{uid:e.auth.uid,...e.auth.token?{token:e.auth.token}:{}}:null,...e.data!==void 0?{data:e.data}:{},priorState:e.priorState,nextState:e.nextState,...e.groupId!==void 0?{groupId:e.groupId}:{},...e.groupKind!==void 0?{groupKind:e.groupKind}:{},...e.sentinels&&e.sentinels.length>0?{sentinels:e.sentinels}:{},...e.autoId!==void 0?{autoId:e.autoId}:{},requestTime:{seconds:e.requestTime.seconds,nanoseconds:e.requestTime.nanos},...e.detail!==void 0?{detail:e.detail}:{},...e.provenance??{}})}capturePriors(e){const r={};for(const n of e){const s=this.state.get(n);r[n]=s?{...s}:null}return r}runSimulate(e,r,n){return bc(this.state,this.rules,this.simulator,e,r,n)}buildBatchProjection(e){const r=new Map;for(const n of e)n.method==="get"||n.method==="list"||r.set(n.path,n.method==="delete"?null:n.data??{});return r}buildTestCase(e,r){return Pn(this.state,e,r)}notify(e,r,n){this.triggerScope.run({method:e,path:r},()=>this.host.notifyListenersForPaths(n))}}class kc{runtime;constructor(e){this.runtime=e}prepare(e,r){const n=xe.fromMillis(Date.now()),s=[];for(let i=0;i<e.length;i++){const a=e[i];try{const o=a.data?Ye({...a.data},{path:a.path,method:a.method,prior:this.runtime.state.get(a.path),serverTime:n}):a.data;s.push({method:a.method,path:a.path,data:o})}catch(o){const c=o.message,u=ee("invalid-argument",c),d=r.snapshot[a.path]??null,l={at:Date.now(),evalMs:0,method:a.ruleMethod,path:a.path,auth:r.auth,result:"deny",debugMessages:[`FieldValue resolve error: ${c}`],...this.includesRequestData(r,a)?{resourceData:a.preData}:{},resourceBefore:{data:d,exists:d!==null},origin:r.origin,groupId:r.groupId,...r.bypassRules?{detail:{admin:!0}}:{},...r.provenance?{provenance:r.provenance}:{}};return{index:i,input:a,message:c,error:u,request:l}}}return{context:r,inputs:e,resolvedOps:s,serverTime:n}}evaluateAndApply(e){const{context:r,inputs:n,resolvedOps:s,serverTime:i}=e,a=s.map((l,f)=>{const y=n[f];return this.runtime.buildTestCase({method:y.ruleMethod,path:l.path,auth:r.auth,data:l.data},i)}),o=this.runtime.buildBatchProjection(a),c=[];let u=!0;for(let l=0;l<s.length;l++){s[l];const f=n[l],y=r.snapshot[f.path]??null,b=Date.now(),S=performance.now(),j=this.runtime.runSimulate([a[l]],r.bypassRules,o),T=performance.now()-S;if(!j.success){const w=ee("invalid-argument",j.error.message);c.push({path:f.path,method:f.ruleMethod,allowed:!1,debugMessages:[j.error.message],error:w,request:this.request(e,f,y,b,T,"deny",[`Simulation error: ${j.error.message}`])}),u=!1;continue}const L=j.data.results[0],k=Se(L);if(L.state==="UNSUPPORTED")throw this.runtime.emitRequest(this.request(e,f,y,b,T,"unsupported",k)),new Fr(Lr(f.ruleMethod,f.path,k),f.ruleMethod,f.path,k);const $=L.state==="PASSED",V={path:f.path,method:f.ruleMethod,allowed:$,debugMessages:k,request:this.request(e,f,y,b,T,$?"allow":"deny",k)};$||(V.error=ee("permission-denied",`${f.ruleMethod} ${f.path} denied by rules`,{request:{method:f.ruleMethod,path:f.path,auth:r.auth,...this.includesRequestData(r,f)?{resourceData:f.preData}:{}},resource:{data:y,exists:y!==null}}),this.runtime.emitDenial(V.error),u=!1),c.push(V)}let d=null;if(u){const l=this.runtime.state.applyBatch(s);if(!l.success){u=!1;const f=l.errors?.[0];if(f!==void 0){const y=s[f.index];d=ee(y?.method==="create"?"already-exists":"not-found",f.error);const b=c[f.index];b&&(b.allowed=!1,b.error=d)}}}return{...e,outcomes:c,allowed:u,structuralError:d}}emitAndNotify(e){const{context:r,inputs:n,outcomes:s,serverTime:i}=e;for(let a=0;a<s.length;a++){const o=s[a],c=n[a],u=e.allowed&&o.allowed,d=r.snapshot[c.path]??null;if(o.request.resourceAfter=u?c.ruleMethod==="delete"?{data:null,exists:!1}:{data:this.runtime.state.get(c.path),exists:this.runtime.state.get(c.path)!==null}:{data:d,exists:d!==null},this.runtime.emitRequest(o.request),u){const l=c.preData?Ic(c.preData):void 0;this.runtime.emitWrite({method:c.ruleMethod,path:c.path,auth:r.auth,...c.ruleMethod!=="delete"&&c.preData?{data:c.preData}:{},priorState:d,nextState:c.ruleMethod==="delete"?null:this.runtime.state.get(c.path),groupId:r.groupId,groupKind:r.origin,...l&&l.length>0?{sentinels:l}:{},requestTime:i,...r.bypassRules?{detail:{admin:!0}}:{},...r.provenance?{provenance:r.provenance}:{}})}}e.allowed&&this.runtime.notify(r.origin,n[0]?.path??"",new Set(n.map(a=>a.path)))}request(e,r,n,s,i,a,o){const{context:c}=e;return{at:s,evalMs:i,method:r.ruleMethod,path:r.path,auth:c.auth,result:a,debugMessages:o,...this.includesRequestData(c,r)?{resourceData:r.preData}:{},resourceBefore:{data:n,exists:n!==null},origin:c.origin,groupId:c.groupId,...c.bypassRules?{detail:{admin:!0}}:{},...c.provenance?{provenance:c.provenance}:{}}}includesRequestData(e,r){return r.preData!==void 0&&(e.origin==="batch"||r.ruleMethod!=="delete")}}class Mp{runtime;pipeline;constructor(e){this.runtime=e,this.pipeline=new kc(e)}batch(e,r,n){const s=this.runtime.capturePriors(e.map(f=>f.path)),i=`batch-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,a=e.map(f=>({...f,ruleMethod:f.method,preData:f.data})),o=this.pipeline.prepare(a,{origin:"batch",groupId:i,auth:r,bypassRules:n,snapshot:s});if(!("resolvedOps"in o)){const f=this.runtime.eventLog.append({type:"batch",method:"batch",path:"",auth:r?{uid:r.uid}:null,allowed:!1,operations:e.map(y=>({method:y.method,path:y.path,data:y.data,allowed:!1})),debugMessages:[`FieldValue resolve error on '${o.input.path}': ${o.message}`]});return this.runtime.emitRequest(o.request),{allowed:!1,results:e.map(y=>({path:y.path,allowed:!1,debugMessages:[o.message],...y.path===o.input.path?{error:o.error}:{}})),event:f,error:o.error}}const c=this.pipeline.evaluateAndApply(o),u=c.outcomes.map(f=>({path:f.path,allowed:f.allowed,debugMessages:f.debugMessages,...f.error?{error:f.error}:{}})),d=this.runtime.eventLog.append({type:"batch",method:"batch",path:"",auth:r?{uid:r.uid}:null,allowed:c.allowed,priorDocs:c.allowed?s:void 0,operations:c.resolvedOps.map((f,y)=>({method:f.method,path:f.path,data:f.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(f=>f.error)?.error??ee("permission-denied","Batch denied")),{allowed:c.allowed,results:u,event:d,...l?{error:l}:{}}}}const Ms="Firestore transactions require all reads to be executed before all writes.";class Ec extends Error{simError;constructor(){super(Ms),this.name="ReadAfterWriteError",this.simError=ee("failed-precondition",Ms)}}class Ba extends Error{constructor(){super("A document read in the transaction changed before commit."),this.name="RetryableTransactionConflictError"}}class Oc extends Error{simError=ee("failed-precondition","Transaction failed all retries.");constructor(){super("Transaction failed all retries."),this.name="TransactionAttemptsExhaustedError"}}class Pp{versionReader;reader;reads=[];writes=[];readVersions=new Map;writeStarted=!1;constructor(e,r=()=>0){this.versionReader=r,this.reader=e}get(e){this.assertReadsAllowed();const r=this.reader(e);this.readVersions.has(e)||this.readVersions.set(e,this.versionReader(e)),this.reads.push({path:e,data:r});const n=r===null?null:structuredClone(r);return{path:e,exists:n!==null,data:()=>n===null?void 0:n}}getAll(...e){return this.assertReadsAllowed(),e.map(r=>this.get(r))}set(e,r){this.queue({method:"set",path:e,data:r})}create(e,r){this.queue({method:"create",path:e,data:r})}update(e,r){this.queue({method:"update",path:e,data:r})}delete(e){this.queue({method:"delete",path:e})}consume(){return{reads:this.reads,writes:this.writes,readVersions:this.readVersions}}hadWrites(){return this.writeStarted}queue(e){this.writeStarted=!0,this.writes.push(e)}assertReadsAllowed(){if(this.writeStarted)throw new Ec}}class $p extends Error{path;secondMethod;constructor(e,r){super(`Queued ${r} on '${e}' after a delete in the same transaction. This combination is unprobed against production Firestore; refusing to guess. Either drop the delete or split into two transactions.`),this.name="AmbiguousPostDeleteWriteError",this.path=e,this.secondMethod=r}}function qp(t){const e=new Map;for(const r of t){const n=e.get(r.path);if(n===void 0){e.set(r.path,Up(r));continue}if(n.method==="delete")throw new $p(r.path,r.method);e.set(r.path,Bp(n,r))}return Array.from(e.values())}function Up(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 Bp(t,e){switch(e.method){case"delete":return{method:"delete",path:e.path};case"set":{const r=rs(e);return{method:"set",path:e.path,data:r}}case"update":{const r=rs(e),s={...t.data??{},...r};return{method:t.method,path:e.path,data:s}}case"create":{const r=rs(e),s={...t.data??{},...r};return{method:"create",path:e.path,data:s}}}}function rs(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 zp{runtime;pipeline;constructor(e){this.runtime=e,this.pipeline=new kc(e)}transaction(e,r){return this.runAttempt(e,r,1)}runAttempt(e,r,n){const s=this.runtime.state.snapshot(),i=this.runtime.state.currentVersion(),a=new Map(Object.keys(s).map(d=>[d,this.runtime.state.version(d)])),o=d=>s[d]??null,c=new Pp(o,d=>{const l=a.get(d);if(l!==void 0)return l;const f=this.runtime.state.version(d);return f<=i?f:-1});let u;try{u=e(c)}catch(d){throw this.logAbortedTransaction(c,r.auth,d),d}if(u!==null&&typeof u?.then=="function")return u.then(d=>{try{return this.commitTransaction(c,s,r,d)}catch(l){return this.retryOrThrow(l,e,r,n)}},d=>{throw this.logAbortedTransaction(c,r.auth,d),d});try{return this.commitTransaction(c,s,r,u)}catch(d){return this.retryOrThrow(d,e,r,n)}}retryOrThrow(e,r,n,s){if(!(e instanceof Ba))throw e;const i=n.maxAttempts??5;if(s>=i)throw new Oc;return this.runAttempt(r,n,s+1)}commitTransaction(e,r,n,s){const{reads:i,writes:a,readVersions:o}=e.consume();for(const[k,$]of o)if(this.runtime.state.version(k)!==$)throw new Ba;const c=n.auth;if(a.length===0){const k=this.runtime.eventLog.append({type:"transaction",method:"transaction",path:"",auth:c?{uid:c.uid}:null,allowed:!0,reads:i.map($=>({path:$.path,data:$.data})),operations:[],snapshot:r,debugMessages:["Transaction committed (read-only — no writes queued)"]});return{allowed:!0,reads:[...i],writes:[],returnValue:s,event:k}}let u;try{u=qp(a)}catch(k){const $=k;throw this.runtime.eventLog.append({type:"transaction",method:"transaction",path:"",auth:c?{uid:c.uid}:null,allowed:!1,aborted:!0,reads:i.map(V=>({path:V.path,data:V.data})),error:{name:$.name,message:$.message,code:"failed-precondition"},debugMessages:[`Transaction aborted at merge: ${$.message}`]}),k}const d=Object.fromEntries(u.map(k=>[k.path,r[k.path]??null])),l=u.map(k=>{const $=k.method==="set"?this.runtime.state.get(k.path)!==null?"update":"create":k.method;return{...k,ruleMethod:$,preData:k.data}}),f=`tx-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,y=this.pipeline.prepare(l,{origin:"transaction",groupId:f,auth:c,bypassRules:n.bypassRules,provenance:n.provenance,snapshot:d});if(!("resolvedOps"in y)){const k=this.runtime.eventLog.append({type:"transaction",method:"transaction",path:"",auth:c?{uid:c.uid}:null,allowed:!1,reads:i.map($=>({path:$.path,data:$.data})),operations:u.map($=>({method:$.method,path:$.path,data:$.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(($,V)=>({path:$.path,method:$.ruleMethod,allowed:!1,debugMessages:V===y.index?[y.message]:[],...V===y.index?{error:y.error}:{}})),returnValue:s,event:k,error:y.error}}const b=this.pipeline.evaluateAndApply(y),S=b.outcomes.map(k=>({path:k.path,method:k.method,allowed:k.allowed,debugMessages:k.debugMessages,...k.error?{error:k.error}:{}})),j=this.runtime.eventLog.append({type:"transaction",method:"transaction",path:"",auth:c?{uid:c.uid}:null,allowed:b.allowed,reads:i.map(k=>({path:k.path,data:k.data})),operations:b.resolvedOps.map((k,$)=>({method:k.method,path:k.path,data:k.data,allowed:S[$]?.allowed??!1})),snapshot:b.allowed?r:void 0,debugMessages:b.allowed?["Transaction committed"]:["Transaction rolled back — one or more operations denied"]});this.pipeline.emitAndNotify(b);let T;b.allowed||(T=b.structuralError??S.find(k=>k.error)?.error??ee("permission-denied","Transaction denied"));const L={allowed:b.allowed,reads:[...i],writes:S,returnValue:s,event:j,...T?{error:T}:{}};return n.readOnly&&e.hadWrites()&&(L.readOnlyViolation=!0),L}logAbortedTransaction(e,r,n){const s=n,{reads:i}=e.consume();this.runtime.eventLog.append({type:"transaction",method:"transaction",path:"",auth:r?{uid:r.uid}:null,allowed:!1,aborted:!0,reads:i.map(a=>({path:a.path,data:a.data})),error:{name:n.name,message:n.message,...s.code!==void 0?{code:String(s.code)}:{}},debugMessages:[`Transaction aborted: ${n.message}`]})}}class Vp{runtime;batches;transactions;constructor(e,r,n,s,i,a){this.runtime=new Dp(e,r,n,s,i,a),this.batches=new Mp(this.runtime),this.transactions=new zp(this.runtime)}capturePriors(e){return this.runtime.capturePriors(e)}applyWrite(e,r,n,s){if(s!==void 0&&s!==!1&&(e==="create"||e==="update")){const i=s===!0?void 0:s.mergeFields;return this.runtime.state.setMerge(r,n??{},i),null}switch(e){case"create":{const i=this.runtime.state.create(r,n??{});return i.success?null:ee("already-exists",i.error??`Document '${r}' already exists`)}case"update":{const i=this.runtime.state.update(r,n??{});return i.success?null:ee("not-found",i.error??`Document '${r}' does not exist`)}case"set":return this.runtime.state.set(r,n??{}),null;case"delete":return this.runtime.state.delete(r),null;default:return null}}execute(e){const{method:r,path:n,auth:s,data:i,autoId:a,requestTime:o,merge:c,bypassRules:u}=e,d=u?{admin:!0}:void 0,l=this.runtime.capturePriors([n]),f=o??xe.fromMillis(Date.now());let y;try{y=i&&Ye({...i},{path:n,method:r,prior:this.runtime.state.get(n),serverTime:f}),r==="update"&&y&&jf(y)}catch(O){const A=O.message,h=this.runtime.eventLog.append({type:"single",method:r,path:n,auth:s?{uid:s.uid}:null,data:i,allowed:!1,priorDocs:l,debugMessages:[`FieldValue resolve error: ${A}`]});return this.runtime.emitRequest({at:Date.now(),evalMs:0,method:r,path:n,auth:s,result:"deny",debugMessages:[`FieldValue resolve error: ${A}`],...y?{resourceData:y}:i?{resourceData:i}:{},resourceBefore:{data:l[n]??null,exists:(l[n]??null)!==null},origin:"user",...d?{detail:d}:{}}),{allowed:!1,debugMessages:[A],event:h,error:ee("invalid-argument",A)}}const b=this.runtime.buildTestCase({...e,data:y},f),S=Date.now(),j=performance.now(),T=this.runtime.runSimulate([b],u),L=performance.now()-j;if(!T.success){const O=this.runtime.eventLog.append({type:"single",method:r,path:n,auth:s?{uid:s.uid}:null,data:y,allowed:!1,priorDocs:l,debugMessages:[`Simulation error: ${T.error.message}`]});return this.runtime.emitRequest({at:S,evalMs:L,method:r,path:n,auth:s,result:"deny",debugMessages:[`Simulation error: ${T.error.message}`],...i?{resourceData:i}:{},resourceBefore:{data:l[n]??null,exists:(l[n]??null)!==null},origin:"user",...d?{detail:d}:{}}),{allowed:!1,debugMessages:[T.error.message],event:O,error:ee("invalid-argument",T.error.message)}}const k=T.data.results[0];if(k.state==="UNSUPPORTED")throw this.runtime.emitRequest({at:S,evalMs:L,method:r,path:n,auth:s,result:"unsupported",debugMessages:Se(k),...i?{resourceData:i}:{},resourceBefore:{data:l[n]??null,exists:(l[n]??null)!==null},origin:"user",...d?{detail:d}:{}}),new Fr(Lr(r,n,Se(k)),r,n,Se(k));let $=k.state==="PASSED",V=null;$&&(V=this.applyWrite(r,n,y,c),V&&($=!1));const w=this.runtime.eventLog.append({type:"single",method:r,path:n,auth:s?{uid:s.uid}:null,data:y,allowed:$,priorDocs:$?l:void 0,debugMessages:Se(k)}),x={allowed:$,debugMessages:Se(k),event:w};if(!$)if(V)x.error=V;else{const O=l[n]??null,A=r==="set"?O!==null?"update":"create":r;x.error=ee("permission-denied",`${r} ${n} denied by rules`,{request:{method:A,path:n,auth:s,...i?{resourceData:i}:{}},resource:{data:O,exists:O!==null}}),this.runtime.emitDenial(x.error)}const _=l[n]??null,v=$?this.runtime.state.get(n):_;if(this.runtime.emitRequest({at:S,evalMs:L,method:r,path:n,auth:s,result:$?"allow":"deny",debugMessages:Se(k),evaluatedRule:Er(k),...i?{resourceData:i}:{},resourceBefore:{data:_,exists:_!==null},...r!=="delete"?{resourceAfter:{data:v,exists:v!==null}}:{resourceAfter:{data:null,exists:!1}},origin:"user",...d?{detail:d}:{}}),$){const O=i?Ic(i):void 0,A=a&&r==="create"?n.split("/").pop():void 0;this.runtime.emitWrite({method:r,path:n,auth:s,...r!=="delete"&&i?{data:i}:{},priorState:_,nextState:r==="delete"?null:v,...O&&O.length>0?{sentinels:O}:{},...A?{autoId:A}:{},requestTime:f,...d?{detail:d}:{}})}return $&&this.runtime.notify(r,n,new Set([n])),x}createWithAutoId(e,r,n,s){const i=e.endsWith("/")?e.slice(0,-1):e,a=gi(),o=`${i}/${a}`,c=this.execute({method:"create",path:o,auth:n,data:r,autoId:!0,bypassRules:s});return{path:o,result:c}}batch(e,r,n){return this.batches.batch(e,r,n)}transaction(e,r){return this.transactions.transaction(e,r)}}class za{state;eventLog;history;simulator;rules;seedSnapshot;events=new Vf;triggerScope=new Wf;reads;writes;listeners;constructor(){this.state=new Xn,this.eventLog=new qf;const e=this;this.simulator=new Fd,this.rules=new sp(zf),this.reads=new Lp(this.events,this.triggerScope,this.rules,this.simulator,{get state(){return e.state}},this.eventLog),this.listeners=new rp(this.events,this.triggerScope,this.reads),this.writes=new Vp({get state(){return e.state},notifyListenersForPaths:r=>e.listeners.notifyListenersForPaths(r)},this.rules,this.simulator,this.eventLog,this.events,this.triggerScope),this.history=new np(this.eventLog,{get state(){return e.state},capturePriors:r=>this.writes.capturePriors(r),applyWrite:(r,n,s,i)=>this.writes.applyWrite(r,n,s,i)}),this.seedSnapshot={}}onDenial(e){return this.events.denial.subscribe(e)}onRequest(e){return this.events.request.subscribe(e)}onWrite(e){return this.events.write.subscribe(e)}onSnapshotDelivery(e){return this.events.delivery.subscribe(e)}onSnapshotSuppressed(e){return this.events.suppressed.subscribe(e)}onListenerLifecycle(e){return this.events.lifecycle.subscribe(e)}onSnapshotError(e){return this.events.snapshotError.subscribe(e)}addSnapshotListener(e,r,n={},s=null,i,a=!1,o=!1,c){return this.listeners.addSnapshotListener(e,r,n,s,i,a,o,c)}flushListeners(){this.listeners.flushListeners()}getSnapshotListenerCount(){return this.listeners.getSnapshotListenerCount()}dispose(){this.listeners.dispose(),this.events.clear()}seed(e){return this.rules.set(e.rules),this.state=e.baseDocuments?new Xn({},new $f(e.baseDocuments)):new Xn(e.documents??{}),this.seedSnapshot=e.baseDocuments??this.state.snapshot(),this.eventLog.clear(),ws(e.rules)}deployRules(e){const r=ws(e);return this.rules.set(e),this.listeners.reEvaluateAllListeners(),r}reevaluateLiveListeners(e,r){this.listeners.reevaluateLiveListeners(e,r)}getRules(){return this.rules.source}getDocument(e){return this.state.get(e)}listDocuments(e){return this.state.list(e)}runQuery(e){return this.reads.runQuery(e)}listRootCollections(){return this.state.listRootCollections()}listSubcollections(e){return this.state.listSubcollections(e)}snapshot(){return this.state.snapshot()}adminSetDocument(e,r){this.state.set(e,r??{}),this.listeners.notifyListenersForPaths(new Set([e]))}adminDeleteDocument(e){const r=this.state.delete(e);return r.success&&this.listeners.notifyListenersForPaths(new Set([e])),{deleted:r.success}}execute(e){return e.method==="get"||e.method==="list"?this.reads.execute(e):this.writes.execute(e)}createWithAutoId(e,r,n,s){return this.writes.createWithAutoId(e,r,n,s)}batch(e,r,n){return this.writes.batch(e,r,n)}transaction(e,r){return this.writes.transaction(e,r)}undo(){return this.history.undo()}redo(){return this.history.redo()}getEvents(){return this.history.getEvents()}getEventCount(){return this.history.getEventCount()}}class se extends Error{code;denialContext;remediation;constructor(e,r,n){const s=typeof e=="object",i=s?e.code:e,a=s?e.message:r,o=s?e.denialContext:n,c=s?e.remediation:void 0,u=c!==void 0?`${a}
1150
+
1151
+ Remediation:
1152
+ ${c}`:a;super(u),this.name="SandboxError",this.code=i,o!==void 0&&(this.denialContext=o),c!==void 0&&(this.remediation=c)}}function Ps(t){return t.kind==="request"||t.kind==="operation"}function Dr(t){const e=Object.freeze({...t.source}),r=Object.freeze({...t.authLens});return Object.freeze({source:e,authLens:r,...t.planId===void 0?{}:{planId:t.planId}})}function yi(t){const e=Dr(t);return{actor:e.source,authLens:e.authLens,operationContext:e,...e.planId===void 0?{}:{planId:e.planId}}}function Va(t){const e=t?.operationContext?.source;if(e&&e.kind!=="unattributed")return e;if(t?.actor&&t.actor.kind!=="unattributed")return t.actor}function bi(t,e){const r=t?.operationContext?.source??t?.actor,n=e?.operationContext?.source??e?.actor;return Dr({source:Va(t)??Va(e)??r??n??{kind:"unattributed"},authLens:e?.operationContext?.authLens??e?.authLens??t?.operationContext?.authLens??t?.authLens??{mode:"app-session"},...(t?.operationContext?.planId??t?.planId??e?.operationContext?.planId??e?.planId)===void 0?{}:{planId:t?.operationContext?.planId??t?.planId??e?.operationContext?.planId??e?.planId}})}function Wp(t){return bi(void 0,t)}function Cc(t){return t.rulesDisposition?t.rulesDisposition:t.kind==="operation"&&t.origin==="admin"||t.detail?.admin===!0?{kind:"bypassed",reason:"admin"}:t.result==="unsupported"?{kind:"not-evaluated",reason:"unsupported"}:t.kind==="operation"&&t.result==="error"?{kind:"not-evaluated",reason:"runtime-error"}:t.kind==="operation"&&t.result==="not-applicable"?{kind:"not-evaluated",reason:"not-a-rules-operation"}:t.result==="deny"?{kind:"evaluated",verdict:"deny"}:t.kind==="request"?{kind:"evaluated",verdict:"allow"}:t.rules?{kind:"evaluated",verdict:"allow"}:{kind:"not-evaluated",reason:"no-rules"}}function Hp(t){return t===null?null:Object.freeze({uid:t.uid,...t.token===void 0?{}:{token:Tc(t.token)}})}function Tc(t){const e={};for(const[r,n]of Object.entries(t))e[r]=Rc(n);return Object.freeze(e)}function Rc(t){return Array.isArray(t)?Object.freeze(t.map(Rc)):t&&typeof t=="object"?Tc(t):t}function lg(t){return Ps(t)?Object.freeze({id:t.id,at:t.at,eventKind:t.kind,service:t.kind==="request"?t.service??"firestore":t.service,method:t.method,...t.path===void 0?{}:{path:t.path},auth:Hp(t.auth),result:t.result,context:Wp(t),rules:Object.freeze({...Cc(t)})}):null}function Wa(t){return t===null?{mode:"anon"}:t.token===void 0?{mode:"as",uid:t.uid}:{mode:"as",uid:t.uid,token:t.token}}class Mr{sandbox;auth;constructor(e,r,n){this.sandbox=e,this.auth=r,this.operationContext=Dr(n??{source:{kind:"unattributed"},authLens:Wa(r)})}operationContext;withAuth(e){return $s(e),new Mr(this.sandbox,e,{source:this.operationContext.source,authLens:Wa(e),...this.operationContext.planId===void 0?{}:{planId:this.operationContext.planId}})}}function vi(t,e){return new Mr(t.sandbox,t.auth,e)}function $s(t){if(t===null)return;if(t===void 0)throw new se({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(`
1153
+ `)});if(typeof t!="object")throw new se("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 se("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 se("invalid-argument","withAuth() requires `token` (when present) to be a plain object.")}function Gp(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),r=e.length%4===0?"":"=".repeat(4-e.length%4),n=atob(e+r),s=new Uint8Array(n.length);for(let i=0;i<n.length;i++)s[i]=n.charCodeAt(i);return s}function Kp(t){const e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r}function wi(t){return qs(t,!0)}function qs(t,e){if(t===null||typeof t!="object")return t;if(Array.isArray(t)){const a=t.map(o=>qs(o,!1));return e&&st(a,Ta(t)),a}const r=t,n=a=>(e&&st(a,Ta(t)),a),s=(a,o)=>(Ht(a,Object.freeze(o),()=>a),n(a));if(r.__type__==="__vector__"&&Array.isArray(r.value)){const a=Object.freeze(r.value.slice());return s(new Wt(a),{type:"vector",values:a})}if(typeof r.__type=="string")switch(r.__type){case"timestamp":return s(new xe(r.seconds,r.nanos),{type:"timestamp",seconds:r.seconds,nanoseconds:r.nanos});case"bytes":{const a=Gp(r.base64);return s(new Be(a),{type:"bytes",values:Object.freeze(Array.from(a))})}case"latlng":return s(new rt(r.lat,r.lng),{type:"geo-point",latitude:r.lat,longitude:r.lng});case"duration":return n(new we(r.seconds,r.nanos));case"reference":return n(new jt(r.path));case"path":return n(new Xe(r.segments))}if(typeof r.type=="string")switch(r.type){case"firestore/timestamp/1.0":{const a=r.seconds,o=r.nanoseconds;return s(new xe(a,o),{type:"timestamp",seconds:a,nanoseconds:o})}case"firestore/bytes/1.0":{const a=Kp(r.bytes);return s(new Be(a),{type:"bytes",values:Object.freeze(Array.from(a))})}case"firestore/geoPoint/1.0":return s(new rt(r.latitude,r.longitude),{type:"geo-point",latitude:r.latitude,longitude:r.longitude})}const i={};for(const[a,o]of Object.entries(r))i[a]=qs(o,!1);return n(i)}class Ur extends Error{constructor(e){super(e),this.name="PersistenceSchemaError"}}function Zp(t){let e;try{e=JSON.parse(t)}catch(s){throw new Ur(`Persisted blob is not valid JSON: ${s.message}`)}if(typeof e!="object"||e===null)throw new Ur("Persisted blob is not an object");if(e.version!==1&&e.version!==2)throw new Ur(`Persisted blob has version ${String(e.version)}, expected 1 or 2`);if(typeof e.firestore!="object"||e.firestore===null)throw new Ur("Persisted blob has no firestore field");const r={};for(const[s,i]of Object.entries(e.firestore))r[s]=wi(i);const n=e.services!==void 0&&typeof e.services=="object"&&e.services!==null?e.services:{};return{firestore:r,services:n}}const Jp=3,Qp=256,Us="meta";function Yp(t){let e=2166136261;for(let r=0;r<t.length;r++)e^=t.charCodeAt(r),e=e+((e<<1)+(e<<4)+(e<<7)+(e<<8)+(e<<24))>>>0;return(e%Qp).toString(16).padStart(2,"0")}function Xp(t){return JSON.parse(JSON.stringify(t))}function Nc(t){const e=JSON.stringify(t);let r=2166136261;for(let n=0;n<e.length;n++)r^=e.charCodeAt(n),r=Math.imul(r,16777619)>>>0;return r}function Fc(t,e,r){const n=new Map;n.set(Us,{version:Jp,savedAt:r,services:e});for(const[s,i]of Object.entries(t)){const a=Yp(s);let o=n.get(a);o||(o={docs:{}},n.set(a,o)),o.docs[s]=Xp(i)}for(const[s,i]of n)s!==Us&&(i.checksum=Nc(i.docs));return n}const Lc="pyric-v3-records";function dg(t){return JSON.stringify({format:Lc,records:Object.fromEntries(t)})}function hg(t){let e;try{e=JSON.parse(t)}catch{return new Map}const r=e;return r&&typeof r=="object"&&r.format===Lc&&typeof r.records=="object"&&r.records!==null?new Map(Object.entries(r.records)):jc(t)??new Map}function jc(t){let e;try{e=Zp(t)}catch{return null}return Fc(e.firestore,e.services,0)}function em(t){const e={};let r={};for(const[n,s]of t){if(n===Us){const a=s;a&&typeof a.services=="object"&&a.services!==null&&(r=a.services);continue}const i=s;if(!(!i||typeof i.docs!="object"||i.docs===null)){if(typeof i.checksum=="number"&&Nc(i.docs)!==i.checksum){console.warn(`[sandbox/persistence] checksum mismatch for bucket '${n}'; skipping corrupt bucket`);continue}for(const[a,o]of Object.entries(i.docs))e[a]=wi(o)}}return{firestore:e,services:r}}const sr="snapshots";function Ha(){const t=new Map,e=r=>{let n=t.get(r);return n||(n=new Map,t.set(r,n)),n};return{async getRecord(r,n){const s=t.get(r)?.get(n);return s===void 0?null:structuredClone(s)},async listRecords(r){return[...t.get(r)?.keys()??[]]},async putRecords(r,n){const s=e(r);for(const[i,a]of n)s.set(i,structuredClone(a))},async deleteRecords(r,n){const s=t.get(r);if(s)for(const i of n)s.delete(i)},async clear(r){t.delete(r)}}}function Dc(t){return new Promise((e,r)=>{const n=indexedDB.open(t,1);n.onupgradeneeded=()=>{const s=n.result;s.objectStoreNames.contains(sr)||s.createObjectStore(sr)},n.onsuccess=()=>e(n.result),n.onerror=()=>r(n.error??new Error(`Failed to open IndexedDB '${t}'`)),n.onblocked=()=>r(new Error(`IndexedDB open blocked for '${t}'`))})}function ns(t,e,r){return Dc(t).then(n=>new Promise((s,i)=>{const a=n.transaction(sr,e),o=a.objectStore(sr),c=r(o);let u=null;c&&(c.onsuccess=()=>{u=c.result??null},c.onerror=()=>i(c.error)),a.oncomplete=()=>{n.close(),s(u)},a.onerror=()=>{n.close(),i(a.error)},a.onabort=()=>{n.close(),i(a.error??new Error("IndexedDB transaction aborted"))}}))}function Ga(t,e){return Dc(t).then(r=>new Promise((n,s)=>{const i=r.transaction(sr,"readwrite");e(i.objectStore(sr)),i.oncomplete=()=>{r.close(),n()},i.onerror=()=>{r.close(),s(i.error)},i.onabort=()=>{r.close(),s(i.error??new Error("IndexedDB transaction aborted"))}}))}function tm(){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 ns(t,"readonly",n=>n.get(e))??null},async listRecords(t){return(await ns(t,"readonly",r=>r.getAllKeys())??[]).map(r=>String(r))},async putRecords(t,e){await Ga(t,r=>{for(const[n,s]of e)r.put(s,n)})},async deleteRecords(t,e){await Ga(t,r=>{for(const n of e)r.delete(n)})},async clear(t){await ns(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 rm=250,Ka="pyric:sandbox:auth-session";function ss(t){return t==="auth"||t==="auth-session:[DEFAULT]"?Ka:`${Ka}:${encodeURIComponent(t)}`}function Mc(t){const e=JSON.stringify(t);let r=2166136261;for(let n=0;n<e.length;n++)r^=e.charCodeAt(n),r=Math.imul(r,16777619)>>>0;return r}function nm(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 sm(t){return t.injectedBackend?t.injectedBackend:(t.backend??"indexedDB")==="memory"||typeof indexedDB>"u"?Ha():tm()}async function im(t,e){const r={...e,flushIntervalMs:e.flushIntervalMs??rm,backend:e.backend??"indexedDB"},n=sm(r),s=new Map,i=await am(t,n,r.key,s);let a=null,o=!1;const c=new Map,u=async()=>{if(o)return;const _=t.snapshot(),v=Fc(_.firestore,_.services,Date.now()),O=new Map,A=new Map;for(const[p,g]of v){const m=Mc(g);A.set(p,m),s.get(p)!==m&&O.set(p,g)}const h=[...s.keys()].filter(p=>!v.has(p));O.size>0&&await n.putRecords(r.key,O),h.length>0&&await n.deleteRecords(r.key,h),s.clear();for(const[p,g]of A)s.set(p,g)};let d=Promise.resolve();const l=()=>(a&&(clearTimeout(a),a=null),d=d.then(u,u),d),f=()=>{o||a||(a=setTimeout(()=>{a=null,l().catch(_=>{if(nm(_)){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:",_),f()})},r.flushIntervalMs))},y=(_,v)=>{if(!v.subscribe||c.has(_))return;const O=v.subscribe(()=>{f()});c.set(_,O)},b=new Map,S=new Map,j=(_,v)=>{if(!r.sessionStorage)return;const{local:O,session:A}=r.sessionStorage,h=ss(_),p=v.currentUid(),g=v.mode();if(p===null||g==="NONE"){O.removeItem(h),A.removeItem(h);return}const m=JSON.stringify({uid:p});g==="LOCAL"?(A.removeItem(h),O.setItem(h,m)):(O.removeItem(h),A.setItem(h,m))},T=_=>{if(!r.sessionStorage)return null;const v=ss(_);for(const[O,A]of[["LOCAL",r.sessionStorage.local],["SESSION",r.sessionStorage.session]]){const h=A.getItem(v);if(h)try{const p=JSON.parse(h);if(typeof p?.uid=="string")return{uid:p.uid,mode:O}}catch{A.removeItem(v)}}return null},L=_=>{if(!r.sessionStorage)return;const v=ss(_);r.sessionStorage.local.removeItem(v),r.sessionStorage.session.removeItem(v)},k=(_,v,O)=>{if(O.session)try{O.session.restore(v.uid,v.mode),S.delete(_)}catch(A){console.warn(`[sandbox/persistence] session restore for uid '${v.uid}' failed — clearing stored session:`,A),L(_),S.delete(_)}},$=(_,v)=>{if(!r.sessionStorage||!v.session||b.has(_))return;const O=v.session;b.set(_,O.subscribe(()=>j(_,O)))},V=(_,v)=>{if(!v.session)return;const O=S.get(_)??T(_);O&&k(_,O,v)};if(t instanceof xt){for(const[_,v]of t.getServiceRegistry())y(_,v),V(_,v),$(_,v);t.setServiceRegistrationHook((_,v)=>{if(i!==null&&_ in i)try{v.restore(i[_])}catch(A){console.warn(`[sandbox/persistence] late-restore for service '${_}' failed:`,A)}const O=T(_);O&&S.set(_,O),V(_,v),y(_,v),$(_,v),f()}),t.setServiceUnregistrationHook(_=>{c.get(_)?.(),c.delete(_),b.get(_)?.(),b.delete(_),S.delete(_),f()})}const w=t.onEvent(_=>{om(_)&&f()}),x=()=>{l().catch(()=>{})};return typeof window<"u"&&window.addEventListener("beforeunload",x),{options:r,flush:l,async clear(){a&&(clearTimeout(a),a=null),await n.clear(r.key),s.clear()},dispose(){if(!o){o=!0,a&&(clearTimeout(a),a=null),w();for(const _ of c.values())_();c.clear();for(const _ of b.values())_();b.clear(),t instanceof xt&&(t.setServiceRegistrationHook(null),t.setServiceUnregistrationHook(null)),typeof window<"u"&&window.removeEventListener("beforeunload",x)}}}}async function am(t,e,r,n){let s;try{s=await e.listRecords(r)}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(r,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 f=jc(l);f&&(o.push(d),c=f)}else a.push([d,l]);if(c){try{await e.putRecords(r,c),o.length>0&&await e.deleteRecords(r,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)n.set(d,Mc(l));const u=em(a);for(const[d,l]of Object.entries(u.firestore))t.admin.setDocument(d,l);if(t instanceof xt){const d=t.getServiceRegistry();for(const[l,f]of Object.entries(u.services)){const y=d.get(l);if(y)try{y.restore(f)}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 om(t){return t.kind==="write"||t.kind==="session_boundary"}function cm(t){return typeof t=="object"&&t!==null&&typeof t.kind=="string"&&typeof t.origin=="string"}let um=0;function lm(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`tab-${crypto.randomUUID()}`:`tab-${++um}-${typeof performance<"u"?performance.now().toFixed(3):String(Date.now())}`}function dm(t,e={}){let r,n=!1;if(e.channel)r=e.channel,n=!1;else if(typeof BroadcastChannel<"u")r=new BroadcastChannel("pyric:tabsync"),n=!0;else return()=>{};const s=e.originId??lm();let i=!1,a=!1;const o=t.onEvent(l=>{if(l.kind!=="write"||i)return;const f={kind:"write",origin:s,event:l};r.postMessage(f)}),c=l=>{if(!cm(l.data))return;const f=l.data;if(f.origin!==s){if(f.kind==="write")d(f.event);else if(f.kind==="hello"){const y={kind:"state",origin:s,to:f.origin,snapshot:t.snapshot()};r.postMessage(y)}else if(f.kind==="state"){if(f.to!==s||a)return;if(Object.keys(Ke(t).snapshot()).length>0){a=!0;return}i=!0;try{for(const[b,S]of Object.entries(f.snapshot.firestore))t.admin.setDocument(b,S)}finally{i=!1}a=!0}}};r.addEventListener("message",c);const u={kind:"hello",origin:s};return r.postMessage(u),()=>{o(),r.removeEventListener("message",c),n&&r.close()};function d(l){i=!0;try{if(l.method==="delete")t.admin.deleteDocument(l.path);else{const f=l.nextState;f!=null&&t.admin.setDocument(l.path,f)}}finally{i=!1}}}function hm(t,e){const r={...t};r.service=t.service??e?.service??"firestore";const s="detail"in t&&t.detail?.admin===!0&&t.operationContext===void 0&&t.authLens===void 0?{...t,authLens:{mode:"admin"}}:t,i=Ps(r)||t.operationContext!==void 0?bi(e,s):fm(t,e);return r.operationContext=i,r.actor=i.source,r.authLens=i.authLens,i.planId!==void 0&&(r.planId=i.planId),e?.activity!==void 0&&(r.activity={...r.activity,...e.activity}),Ps(r)&&(r.rulesDisposition=Object.freeze({...Cc(r)})),r}function fm(t,e){return Dr({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 pm(t,e){if(!t)return e;if(!e)return t;if(e.operationContext!==void 0)return Pc(t,e);if(!(t.operationContext!==void 0||t.actor!==void 0||t.authLens!==void 0||t.planId!==void 0||e.actor!==void 0||e.authLens!==void 0||e.planId!==void 0))return{...t,...e};const n=Dr({source:e.actor??t.operationContext?.source??t.actor??{kind:"unattributed"},authLens:e.authLens??t.operationContext?.authLens??t.authLens??{mode:"app-session"},...(e.planId??t.operationContext?.planId??t.planId)===void 0?{}:{planId:e.planId??t.operationContext?.planId??t.planId}});return{...t,...e,operationContext:n,actor:n.source,authLens:n.authLens,...n.planId===void 0?{}:{planId:n.planId}}}function Pc(t,e){if(!t)return e;if(!e)return t;if(!(t.operationContext!==void 0||t.actor!==void 0||t.authLens!==void 0||t.planId!==void 0||e.operationContext!==void 0||e.actor!==void 0||e.authLens!==void 0||e.planId!==void 0))return{...t,...e};const n=bi(t,e);return{...t,...e,operationContext:n,actor:n.source,authLens:n.authLens,...n.planId===void 0?{}:{planId:n.planId}}}let mm=1;function Lt(){const t=(mm++).toString(36),e=Math.random().toString(36).slice(2,7);return`sbe-${t}-${e}`}class xt{_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 xt(new za)}getEnv(){return this._env}withAuth(e){return $s(e),new Mr(this,e)}attachToEnv(){this.envUnsubs.push(this._env.onRequest(e=>{this.emitEvent(e)})),this.envUnsubs.push(this._env.onWrite(e=>{this.emitEvent(e)})),this.envUnsubs.push(this._env.onSnapshotDelivery(e=>this.emitEvent(e))),this.envUnsubs.push(this._env.onSnapshotSuppressed(e=>this.emitEvent(e))),this.envUnsubs.push(this._env.onListenerLifecycle(e=>this.emitEvent(e))),this.envUnsubs.push(this._env.onSnapshotError((e,r,n)=>{const s={kind:"listener_errored",id:Lt(),at:Date.now(),listenerId:n,target:r.kind==="doc"?{kind:"doc",path:r.path}:{kind:"query",collection:r.collection},auth:e.request?.auth??null,error:{code:"permission-denied",message:e.message}};this.emitEvent(s)}))}emitEvent(e,r){const n=Pc(this.ambientProvenance,r);this.dispatch(hm(e,n))}runWithProvenance(e,r){const n=this.ambientProvenance;this.ambientProvenance=pm(n,e);try{return r()}finally{this.ambientProvenance=n}}dispatch(e){if(this.eventHistory.push(e),this.dispatchedCount++,this.eventSubs.size!==0)for(const r of this.eventSubs)try{const n=r(e);n&&typeof n.then=="function"&&n.catch(()=>{})}catch{}}emitInternal(e,r){this.emitEvent(e,r)}onEvent(e){return this.eventSubs.add(e),()=>{this.eventSubs.delete(e)}}history(){return[...this.eventHistory]}primeEventHistory(e){return this.eventHistory.length>0||e.length===0?0:(this.eventHistory.push(...e),e.length)}get admin(){return{getDocument:e=>this._env.getDocument(e),listDocuments:e=>this._env.listDocuments(e),setDocument:(e,r)=>this._env.adminSetDocument(e,r),deleteDocument:e=>this._env.adminDeleteDocument(e)}}reset(){const e={kind:"session_boundary",id:Lt(),at:Date.now(),phase:"reset",priorOpCount:this.dispatchedCount};this.emitEvent(e),this.eventHistory=[],this._currentUser!==null&&(this._currentUser=null,this.notifyCurrentUserSubs(null));for(const r of this.envUnsubs)r();this.envUnsubs=[],this._env.dispose(),this._env=new za,this.attachToEnv()}async resetAll(){this.reset();const e=[],r=[];for(const[n,s]of this.serviceRegistry)s.reset&&r.push(Promise.resolve().then(()=>s.reset()).catch(i=>{e.push(`${n}: ${i instanceof Error?i.message:String(i)}`)}));return await Promise.all(r),{errors:e}}dispose(){const e={kind:"session_boundary",id:Lt(),at:Date.now(),phase:"dispose",priorOpCount:this.dispatchedCount};this.emitEvent(e);for(const r of this.envUnsubs)r();this.envUnsubs=[],this._env.dispose(),this.persistence&&(this.persistence.dispose(),this.persistence=null),this.serviceRegistry.clear(),this._onServiceRegistered=null,this._onServiceUnregistered=null,this.eventSubs.clear(),this.currentUserSubs.clear()}snapshot(){const e={};for(const[r,n]of this.serviceRegistry)e[r]=n.snapshot();return{firestore:this._env.snapshot(),services:e}}loadSnapshot(e){this.reset();for(const[r,n]of Object.entries(e.firestore))this._env.adminSetDocument(r,n);for(const[r,n]of this.serviceRegistry)if(r in e.services)try{n.restore(e.services[r])}catch(s){console.warn(`[sandbox] loadSnapshot: service '${r}' restore failed — Firestore is intact; that service's state may be incomplete:`,s)}}get currentUser(){return this._currentUser}set currentUser(e){$s(e),!gm(this._currentUser,e)&&(this._currentUser=e,this.notifyCurrentUserSubs(e))}onCurrentUserChanged(e){return this.currentUserSubs.add(e),()=>{this.currentUserSubs.delete(e)}}notifyCurrentUserSubs(e){if(this._env.reevaluateLiveListeners(e),this.currentUserSubs.size!==0)for(const r of this.currentUserSubs)try{const n=r(e);n&&typeof n.then=="function"&&n.catch(()=>{})}catch{}}async enablePersistence(e){if(this.persistence){if(this.persistence.options.key!==e.key)throw new se("failed-precondition",`Persistence already enabled with key '${this.persistence.options.key}'; cannot re-enable with key '${e.key}'. Dispose and recreate the sandbox.`);return}if(this.enablePersistencePromise)return this.enablePersistencePromise;this.enablePersistencePromise=(async()=>{const r=await im(this,e);this.persistence=r})();try{await this.enablePersistencePromise}finally{this.enablePersistencePromise=null}}enableTabSync(e){return dm(this,e)}async flush(){if(!this.persistence)throw new se("failed-precondition","flush() called before enablePersistence()");await this.persistence.flush()}async clearPersistence(){this.persistence&&await this.persistence.clear()}registerPersistableService(e,r){if(this.serviceRegistry.has(e))throw new se("failed-precondition",`registerPersistableService: a service named '${e}' is already registered on this sandbox. Each service name must be unique — the auth package registers 'auth' exactly once per sandbox.`);return this.serviceRegistry.set(e,r),this._onServiceRegistered&&this._onServiceRegistered(e,r),()=>{this.serviceRegistry.get(e)===r&&(this.serviceRegistry.delete(e),this._onServiceUnregistered?.(e))}}setServiceRegistrationHook(e){this._onServiceRegistered=e}setServiceUnregistrationHook(e){this._onServiceUnregistered=e}getServiceRegistry(){return this.serviceRegistry}}function gm(t,e){if(t===e)return!0;if(t===null||e===null||t.uid!==e.uid)return!1;const r=t.token===void 0?void 0:JSON.stringify(t.token),n=e.token===void 0?void 0:JSON.stringify(e.token);return r===n}function Ke(t){if(!(t instanceof xt))throw new se("invalid-argument","Sandbox handle was not produced by initializeSandbox(); custom Sandbox implementations are not supported.");return t.getEnv()}function fg(t,e,r){if(!(t instanceof xt))throw new se("invalid-argument","Sandbox handle was not produced by initializeSandbox(); custom Sandbox implementations are not supported.");t.emitInternal(e,r)}function pg(t){return{kind:"service_mutation",id:Lt(),at:Date.now(),...t}}function mg(t){const{at:e,...r}=t;return{kind:"operation",id:Lt(),at:e??Date.now(),...r}}function gg(t){const{at:e,...r}=t;return{kind:"commit",id:Lt(),at:e??Date.now(),...r}}function yg(t){const{at:e,...r}=t;return{kind:"listener",id:Lt(),at:e??Date.now(),...r}}function bg(){return xt.createRoot()}const ym=Symbol.for("pyric.remote.sandbox");function Si(t){return t!=null&&t[ym]===!0}function Cr(t){return t.replace(/^\/+|\/+$/g,"").split("/")}function $c(t){return Cr(t).length%2===0&&Cr(t).length>0}function _i(t){return Cr(t).length%2===1}function qn(t){const e=Cr(t);return e[e.length-1]??""}function qc(t){return Cr(t).slice(0,-1).join("/")}function Uc(t,e){const r=e!==void 0,n=r?jr(e):void 0;return{id:t.id,ref:t,exists:r,data:()=>r?n:void 0,get:s=>or(n,s)}}const Za=new WeakMap;let bm=1;function Ja(t){let e=Za.get(t);return e===void 0&&(e=bm++,Za.set(t,e)),e}function On(t){if(t===null||typeof t=="boolean")return t;if(typeof t=="string")return Hf(t);if(typeof t>"u")return{type:"undefined"};if(typeof t=="bigint")return qt("bigint",t.toString());if(typeof t=="number"){const r=Number.isNaN(t)?"NaN":t===1/0?"Infinity":t===-1/0?"-Infinity":Object.is(t,-0)?"-0":String(t);return qt("number",r)}if(typeof t!="object"&&typeof t!="function")return{type:typeof t,value:String(t)};const e=Kf(t);if(e!==void 0)return e;try{if(Array.isArray(t))return{type:"array",id:Ja(t)}}catch{}return{type:"opaque-object",id:Ja(t)}}function gt(t){return new ce({code:"invalid-argument",message:t})}function Bs(t,e,r,n=!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 gt(`Unsupported Firestore query value: ${typeof t}.`);if(typeof t!="object")throw gt("Unsupported Firestore query value.");const i=ac(t);if(i!==void 0){const o=vf(t);if(o!==void 0&&r!==void 0&&o!==r)throw gt("Document reference belongs to a different Firestore database.");return{comparison:{type:"registered-firestore-value",value:i},execution:wf(t)}}if(t instanceof Date){const o=t.getTime();if(!Number.isFinite(o))throw gt("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 Ht(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 gt("Cyclic query operands are not Firestore values.");const a=Object.getPrototypeOf(t);if(a!==Object.prototype&&a!==null&&!Array.isArray(t))throw gt("Firestore query maps must be plain objects.");e.add(t);try{if(Array.isArray(t)){if(s&&!n)throw gt("Nested arrays are not supported.");const u=t.map(l=>Bs(l,e,r,n,!0)),d=u.map(l=>l.execution);return st(d,On(t)),{comparison:{type:"array",values:u.map(l=>l.comparison)},execution:d}}const o=Object.keys(t).sort().map(u=>({key:u,captured:Bs(t[u],e,r,n,!1)})),c=Object.fromEntries(o.map(({key:u,captured:d})=>[u,d.execution]));return st(c,On(t)),{comparison:{type:"map",entries:o.map(({key:u,captured:d})=>[u,d.comparison])},execution:c}}finally{e.delete(t)}}function Bc(t,e,r=!1){try{const n=Bs(t,new Set,e,r);return Object.freeze({kind:"canonical",value:n.comparison,executionValue:n.execution})}catch(n){if(n instanceof ce)throw n;const s=n instanceof Error?n.message:String(n);throw gt(`Invalid Firestore query value: ${s}`)}}function zc(t,e){return Ge(t.value,e.value)}function Kr(t,e){if(t.kind==="where"){const r="comparisonValue"in t?t.comparisonValue:Bc(t.value,e,t.op==="in"||t.op==="not-in");return Object.freeze({kind:"where",field:t.field,op:t.op,value:r.executionValue,comparisonValue:r})}return Object.freeze({kind:t.kind,filters:Object.freeze(t.filters.map(r=>Kr(r,e)))})}function Br(t,e,r,n){const s=t.map(i=>Bc(i,n));return Object.freeze({values:Object.freeze(s.map(i=>i.executionValue)),comparisonValues:Object.freeze(s),inclusive:e,fromSnapshot:r})}function Vc(t,e){return t.length!==e.length?!1:t.every((r,n)=>{const s=e[n];return r.kind!==s.kind?!1:r.kind==="where"&&s.kind==="where"?r.field===s.field&&r.op===s.op&&zc(r.comparisonValue,s.comparisonValue):r.kind!=="where"&&s.kind!=="where"&&Vc(r.filters,s.filters)})}function Qa(t,e){return t===void 0||e===void 0?t===e:t.inclusive===e.inclusive&&t.comparisonValues.length===e.comparisonValues.length&&t.comparisonValues.every((r,n)=>zc(r,e.comparisonValues[n]))}function vm(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 Wc(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(Wc))})}function Ya(t){if(t!==void 0)return Object.freeze({values:t.values,inclusive:t.inclusive,fromSnapshot:t.fromSnapshot})}function wm(t,e){return Vc(t.filters,e.filters)&&t.orders.length===e.orders.length&&t.orders.every((r,n)=>{const s=e.orders[n];return r.field===s.field&&r.direction===s.direction})&&t.limitCount===e.limitCount&&t.limitFromEnd===e.limitFromEnd&&Qa(t.start,e.start)&&Qa(t.end,e.end)}const Hc="__name__";function Xa(t,e){const r=t.data();if(r===void 0)throw new ce({code:"not-found",message:`Snapshot-based cursors require an existing document — got an empty snapshot for ${t.id??"<unknown>"}.`});return e.map(n=>n.field===Hc?t.ref:r[n.field])}class Tr{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(r=>Kr(r))),this.orders=Object.freeze((e.orders??[]).map(r=>Object.freeze({...r}))),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(r=>r.executionValue)),comparisonValues:e.start.comparisonValues}),this.end=e.end===void 0?void 0:Object.freeze({...e.end,values:Object.freeze(e.end.comparisonValues.map(r=>r.executionValue)),comparisonValues:e.end.comparisonValues}),this.bypassRules=e.bypassRules??!1}where(e,r,n){return this.clone({clauses:[...this.clauses,Kr({kind:"where",field:e,op:r,value:n})]})}applyFilter(e){return this.clone({clauses:[...this.clauses,Kr(e)]})}orderBy(e,r="asc"){return this.clone({orders:[...this.orders,{field:e,direction:r}]})}limit(e){return this.clone({limitCount:e,limitFromEnd:!1})}limitToLast(e){return this.clone({limitCount:e,limitFromEnd:!0})}startCursor(e,r){return this.clone({start:Br(this.normalizeExplicitCursorValues(e),r,!1)})}endCursor(e,r){return this.clone({end:Br(this.normalizeExplicitCursorValues(e),r,!1)})}startCursorFromSnapshot(e,r){return this.clone({start:Br(Xa(e,this.normalizedOrders()),r,!0)})}endCursorFromSnapshot(e,r){return this.clone({end:Br(Xa(e,this.normalizedOrders()),r,!0)})}isStructurallyEqual(e){return e instanceof Tr?this.env===e.env&&this.bypassRules===e.bypassRules&&vm(this.queryScope(),e.queryScope())&&wm(this.comparableExecutionSpec(),e.comparableExecutionSpec()):!1}clone(e){return new Tr({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 r=e?.auth!==void 0?e.auth:this.auth;let n;try{n=this.env.runQuery({scope:this.queryScope(),auth:r,execution:this.executionSpec(),bypassRules:this.bypassRules,activityQuery:this.activityQuery()})}catch(s){const i=s?.simError;throw i?new ce(i):s}if(!n.allowed)throw new ce(n.error);return n.docs}activityQuery(){const e=n=>n.kind==="where"?{kind:"where",field:n.field,op:n.op,value:On(n.value)}:{kind:n.kind,filters:n.filters.map(e)},r=n=>n===void 0?null:{values:n.values.map(s=>On(s)),inclusive:n.inclusive,fromSnapshot:n.fromSnapshot};return{scope:this.activityScope(),filters:this.clauses.map(e),orderBy:this.orders.map(n=>({...n})),limit:this.limitCount??null,limitFromEnd:this.limitFromEnd,start:r(this.start),end:r(this.end)}}activityScope(){return{kind:"collection"}}normalizedOrders(){return xc(this.executionSpec())}normalizeExplicitCursorValues(e){const r=this.orders;return e.map((n,s)=>{if(r[s]?.field!==Hc)return n;if(typeof n!="string")throw new ce({code:"invalid-argument",message:"Expected a string for a document ID cursor value."});const i=n.includes("/")?n:`${this.collectionPath}/${n}`;return this.documentRef(i)})}executionSpec(){const e={filters:Object.freeze(this.clauses.map(Wc)),orders:this.orders,limitCount:this.limitCount,limitFromEnd:this.limitFromEnd,start:Ya(this.start),end:Ya(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 n=this.readQueryRows(e).map(s=>{const i=this.documentRef(s.path),a=jr(s.data);return{id:i.id,ref:i,exists:!0,data:()=>a,get:o=>or(a,o)}});return{size:n.length,empty:n.length===0,docs:n,forEach(s){n.forEach(s)}}}async aggregate(e,r){const n=this.readQueryRows(r),s={};for(const i of Object.keys(e))s[i]=_m(e[i],n);return{data:()=>s}}}function Sm(t,e){if(!e.includes("."))return t[e];let r=t;for(const n of e.split(".")){if(typeof r!="object"||r===null||Array.isArray(r))return;r=r[n]}return r}function _m(t,e){if(t.kind==="count")return e.length;let r=0,n=0;for(const s of e){const i=Sm(s.data,t.field);typeof i=="number"&&Number.isFinite(i)&&(r+=i,n++)}return t.kind==="sum"?r:n===0?null:r/n}function Kt(t,e){if(t.error)throw new ce(t.error);const r=t.debugMessages.length>0?t.debugMessages.join("; "):"(no debug message)";throw new ce(ee("permission-denied",`${e}: ${r}`))}class Am{env;auth;bypassRules;collectionRef;id;path;constructor(e,r,n,s=!1,i){this.env=e,this.auth=r,this.bypassRules=s,this.collectionRef=i,this.path=n,this.id=qn(n),st(this,qt("reference",n)),hi(this,n,e)}get parent(){return this.collectionRef(qc(this.path))}collection(e){return this.collectionRef(`${this.path}/${e}`)}async get(e){const r=this.env.execute({method:"get",path:this.path,auth:e?.auth!==void 0?e.auth:this.auth,bypassRules:this.bypassRules});r.allowed||Kt(r,"get denied");const n=r.data===void 0||r.data===null?void 0:r.data;return Uc(this,n)}async set(e,r){const n=r?.auth!==void 0?r.auth:this.auth;if(r?.mergeFields!==void 0){const i=r.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:n,merge:{mergeFields:i},bypassRules:this.bypassRules});c.allowed||Kt(c,`set denied (as ${o})`);return}if(r?.merge===!0){const a=this.env.getDocument(this.path)===null?"create":"update",o=this.env.execute({method:a,path:this.path,data:e,auth:n,merge:!0,bypassRules:this.bypassRules});o.allowed||Kt(o,`set denied (as ${a})`);return}const s=this.env.execute({method:"set",path:this.path,data:e,auth:n,bypassRules:this.bypassRules});s.allowed||Kt(s,"set denied")}async update(e,r){const n=this.env.execute({method:"update",path:this.path,data:e,auth:r?.auth!==void 0?r.auth:this.auth,bypassRules:this.bypassRules});n.allowed||Kt(n,"update denied")}async delete(e){const r=this.env.execute({method:"delete",path:this.path,auth:e?.auth!==void 0?e.auth:this.auth,bypassRules:this.bypassRules});r.allowed||Kt(r,"delete denied")}}function Cn(t,e,r,n){return new Am(t,e,r,n,s=>new Gc(t,e,s,n))}class Gc extends Tr{id;path;constructor(e,r,n,s=!1){super({env:e,auth:r,collectionPath:n,bypassRules:s,documentRef:i=>Cn(e,r,i,s)}),this.path=n,this.id=qn(n)}doc(e){const r=e??gi();return Cn(this.env,this.auth,`${this.path}/${r}`,this.bypassRules)}async add(e,r){const n=this.doc();return await n.set(e,r),n}}class Ai extends Tr{collectionId;constructor(e){super({...e,collectionPath:"",documentRef:r=>Cn(e.env,e.auth,r,e.bypassRules??!1)}),this.collectionId=e.collectionId}clone(e){return new Ai({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 xm{env;auth;bypassRules;ops=[];constructor(e,r,n=!1){this.env=e,this.auth=r,this.bypassRules=n}set(e,r){const s=this.env.getDocument(e.path)===null?"create":"update";return this.ops.push({method:s,path:e.path,data:r}),this}update(e,r){return this.ops.push({method:"update",path:e.path,data:r}),this}delete(e){return this.ops.push({method:"delete",path:e.path}),this}async commit(e){if(this.ops.length===0)return;const r=this.env.batch(this.ops,e?.auth!==void 0?e.auth:this.auth,this.bypassRules);if(r.allowed)return;if(r.error)throw new ce(r.error);const s=r.results.find(i=>!i.allowed)?.debugMessages.join("; ")??"batch denied";throw new ce(ee("permission-denied",`batch failed: ${s}`))}}function Im(t){return typeof t.where=="function"}class km{simTx;constructor(e){this.simTx=e}async get(e){if(Im(e)){const s=await e.get();return s.size>0&&this.simTx.getAll(...s.docs.map(i=>i.ref.path)),s}const n=this.simTx.get(e.path).data();return Uc(e,n)}set(e,r){return this.simTx.set(e.path,r),this}update(e,r){return this.simTx.update(e.path,r),this}delete(e){return this.simTx.delete(e.path),this}}class Em{env;auth;bypassRules;provenance;constructor(e,r,n=!1,s){this.env=e,this.auth=r,this.bypassRules=n,this.provenance=s}collection(e){if(!_i(e))throw new ce(ee("invalid-argument",`collection path must have an odd number of segments: ${e}`));return new Gc(this.env,this.auth,e,this.bypassRules)}doc(e){if(!$c(e))throw new ce(ee("invalid-argument",`document path must have an even number of segments: ${e}`));return Cn(this.env,this.auth,e,this.bypassRules)}collectionGroup(e){if(e.length===0||e.includes("/"))throw new ce(ee("invalid-argument",`collection group id must be a single non-empty segment with no '/': ${e}`));return new Ai({env:this.env,auth:this.auth,collectionId:e,bypassRules:this.bypassRules})}batch(){return new xm(this.env,this.auth,this.bypassRules)}async runTransaction(e,r){let n;try{n=await this.env.transaction(s=>{const i=new km(s);return e(i)},{auth:r?.auth!==void 0?r.auth:this.auth,bypassRules:this.bypassRules,provenance:this.provenance,maxAttempts:r?.maxAttempts})}catch(s){throw s instanceof Ec?new ce(s.simError):s instanceof Oc?new ce(s.simError):s}if(!n.allowed){if(n.error)throw new ce(n.error);const i=n.writes.find(a=>!a.allowed)?.debugMessages.join("; ")??"transaction denied at commit";throw new ce(ee("permission-denied",`transaction failed: ${i}`))}return n.returnValue}}function Om(t,e){return new Em(t,e?.auth??null,e?.bypassRules??!1,e?.provenance)}const Kc=Symbol("pyric/sandbox/context"),Zc=Symbol("pyric/sandbox/bypassRules");let zs=null;function Cm(t){zs=t}function Tm(t){const e=t;return typeof e.path=="string"&&e.path.length>0||typeof e.collectionPath=="string"&&e.collectionPath.length>0}function Rm(t){const e=t.trim();if(!e)return[];const r=e.indexOf(": ");if(r!==-1){const s=e.slice(r+2).trim().split("; ").map(i=>i.trim()).filter(i=>i.length>0);if(s.length>0)return s}return[e]}function eo(t,e){if(!(t instanceof ce))return t;const r=t.code;if(r!=="permission-denied")return new se(r,t.message);const n={auth:e.auth,reasons:Rm(t.message)},s=t.simError;if(s?.request){const i=s.request;n.request={method:i.method,path:i.path,...i.resourceData?{resourceData:i.resourceData}:{}}}return s?.resource&&(n.resource={data:s.resource.data,exists:s.resource.exists}),s?.query&&(n.query=s.query),s?.remediation!==void 0?new se({code:r,message:t.message,denialContext:n,remediation:s.remediation}):new se(r,t.message,n)}function Tn(t,e,r=!1){return new Proxy(t,{get(n,s,i){if(s===Kc)return e;if(s===Zc)return r;if(s==="onSnapshot"&&zs!==null&&!(s in n)&&Tm(n))return(...o)=>zs(i,...o);const a=Reflect.get(n,s,i);return typeof a!="function"?a:function(...o){let c;try{const u=()=>a.apply(n,o);c=e.sandbox.runWithProvenance?.(yi(e.operationContext),u)??u()}catch(u){throw eo(u,e)}return c instanceof Promise?c.then(u=>u&&typeof u=="object"?Tn(u,e,r):u).catch(u=>{throw eo(u,e)}):c&&typeof c=="object"?Tn(c,e,r):c}}})}function Jc(t,e=!1){if(Si(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 r=()=>Om(Ke(t.sandbox),{auth:t.auth,bypassRules:e,provenance:yi(t.operationContext)});return{collection(n){return r().collection(n)},doc(n){return r().doc(n)},collectionGroup(n){return r().collectionGroup(n)},batch(){return r().batch()},runTransaction(n,s){return r().runTransaction(n,s)},setRules(n){return Ke(t.sandbox).deployRules(n)},seed(n){const s=Ke(t.sandbox);return s.seed({rules:s.getRules(),documents:n?.documents??{}})},snapshot(){return Ke(t.sandbox).snapshot()}}}function Vs(t){if(t instanceof se)return t;if(t!==null&&typeof t=="object"){const e=t;if(typeof e.code=="string"&&typeof e.message=="string"){const r=e.denialContext!==null&&typeof e.denialContext=="object"?e.denialContext:void 0;return new se(e.code,e.message,r)}}return t}function ht(t){return new se("invalid-argument",t)}async function Ze(t,e){try{return await t.sandbox.channel.op({...e,actAs:t.lens})}catch(r){throw Vs(r)}}const Nm=new Set(["serverTimestamp","increment","arrayUnion","arrayRemove","deleteField"]);function Fm(t){return t!==null&&typeof t=="object"&&typeof t.__type=="string"&&Nm.has(t.__type)}function Lm(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(pt)};case"arrayRemove":return{__sentinel:"arrayRemove",values:t.values.map(pt)};case"deleteField":return{__sentinel:"deleteField"}}}function pt(t){if(t===null||typeof t!="object")return t;if(Fm(t))return Lm(t);if(t instanceof bt)return t.toJSON();if(t instanceof Date)return bt.fromDate(t).toJSON();if(Array.isArray(t))return t.map(pt);const e=Object.getPrototypeOf(t);if(e!==Object.prototype&&e!==null){const n=t.toJSON;if(typeof n=="function")return n.call(t);throw ht(`remote Firestore: cannot serialize a ${e.constructor?.name??"class"} instance for the wire — use plain data, Timestamp, Date, or FieldValue sentinels.`)}const r={};for(const[n,s]of Object.entries(t))r[n]=pt(s);return r}function Ut(t){return pt(t)}function Ws(t){return wi(JSON.parse(t.json))}function Qc(t){return jr(Ws(t))}function Yc(t,e){const r=e.exists&&e.data?Qc(e.data):void 0;return{id:t.id,ref:t,exists:e.exists,data:()=>r,get:n=>or(r,n)}}function Xc(t,e){const r=e.docs.map(n=>{const s=n.path??n.id,i=Rn(t,s),a=n.data?Qc(n.data):{};return{id:i.id,ref:i,exists:!0,data:()=>a,get:o=>or(a,o)}});return{size:r.length,empty:r.length===0,docs:r,forEach(n){r.forEach(s=>n(s))}}}const xi=Symbol("pyric/sandbox/admin-firestore/remoteSnapshotRegistrar");function jm(t){if(t===null||typeof t!="object")return;const e=t[xi];return typeof e=="function"?e:void 0}let Hs=null;function Dm(t){Hs=t}function eu(...t){if(Hs===null)throw new se("failed-precondition","remote Firestore: onSnapshot is not wired yet — import pyric-admin/firestore (or pyric/sandbox/admin-firestore) before subscribing.");return Hs(this,...t)}function tu(t,e,r,n,s){const i=r.includeMetadataChanges!==!0;let a,o;try{o=t.sandbox.channel.subscribe({target:e,actAs:t.lens},c=>{if(!n)return;const u=c;if(Array.isArray(u.docs)){const d=u.docs.map(y=>({path:y.path??y.id,data:y.data?Ws(y.data):{}})),l=e.__ref==="query"?e.source.__ref==="group"?e.source.collectionId:e.source.path:e.__ref==="group"?e.collectionId:e.path,f=Qt({path:l},d,{excludesMetadataChanges:i},a);a=d,n(f)}else if(typeof u.id=="string"){const d=u.path??u.id,l=u.exists&&u.data?Ws(u.data):null;n(Jt(d,l))}},c=>{const u=Vs(c);s?s(u):console.error("pyric remote Firestore: uncaught onSnapshot error:",u)})}catch(c){throw Vs(c)}return o}const ru=Symbol("pyric/sandbox/admin-firestore/remoteQueryState");function Mm(t){if(!(t===null||typeof t!="object"))return t[ru]}function nu(t){return t.kind==="where"?(su(t.op),{kind:"where",field:t.field,op:t.op,value:pt(t.value)}):{kind:t.kind,filters:t.filters.map(nu)}}const Pm=new Set(["<","<=","==","!=",">=",">","in","not-in","array-contains","array-contains-any"]);function su(t){if(!Pm.has(t))throw ht(`invalid where operator: ${String(t)}`)}function Zr(t){const e=[...t.filters];for(const r of t.orders)e.push({kind:"orderBy",field:r.field,direction:r.direction});return t.start&&e.push({kind:t.start.inclusive?"startAt":"startAfter",values:t.start.values.map(pt)}),t.end&&e.push({kind:t.end.inclusive?"endAt":"endBefore",values:t.end.values.map(pt)}),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 to(t,e,r){if(e.length===0)throw ht(`${r}(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 ht(`${r}(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 n=t.data();if(n===void 0)throw new se("not-found",`Snapshot-based cursors require an existing document — got an empty snapshot for ${t.id??"<unknown>"}.`);return e.map(s=>n[s.field])}function Ii(t,e){const r=s=>Ii(t,{...e,...s});return{[ru]:e,where(s,i,a){return su(i),r({filters:[...e.filters,{kind:"where",field:s,op:i,value:pt(a)}]})},applyFilter(s){return r({filters:[...e.filters,nu(s)]})},orderBy(s,i="asc"){return r({orders:[...e.orders,{field:s,direction:i}]})},limit(s){return r({limitCount:s,limitFromEnd:!1})},limitToLast(s){return r({limitCount:s,limitFromEnd:!0})},startCursor(s,i){return r({start:{values:[...s],inclusive:i}})},endCursor(s,i){return r({end:{values:[...s],inclusive:i}})},startCursorFromSnapshot(s,i){return r({start:{values:to(s,e.orders,i?"startAt":"startAfter"),inclusive:i}})},endCursorFromSnapshot(s,i){return r({end:{values:to(s,e.orders,i?"endAt":"endBefore"),inclusive:i}})},async get(s){Jr(e);const i=await Ze(t,{method:"getDocs",source:Zr(e)});return Xc(t,i)},async aggregate(s){Jr(e);const i=await Ze(t,{method:"aggregate",source:Zr(e),spec:s});return{data:()=>i.data}},[xi]:(s,i,a)=>(Jr(e),tu(t,Zr(e),s,i,a)),onSnapshot:eu}}function Jr(t){if(t.limitFromEnd&&t.orders.length===0)throw ht("limitToLast() queries require at least one orderBy clause.")}function Gs(t,e){const r=Ii(t,{source:{__ref:"collection",path:e},filters:[],orders:[],limitFromEnd:!1});return Object.assign(Object.create(Object.getPrototypeOf(r)),r,{id:qn(e),path:e,doc(s){const i=s??gi();return Rn(t,`${e}/${i}`)},async add(s,i){const a=await Ze(t,{method:"addDoc",collectionPath:e,data:Ut(s)});return Rn(t,a.path)}})}function Rn(t,e){const r={id:qn(e),path:e,get parent(){return Gs(t,qc(e))},collection(n){const s=`${e}/${n}`;if(!_i(s))throw ht(`collection path must have an odd number of segments: ${s}`);return Gs(t,s)},async get(n){const s=await Ze(t,{method:"getDoc",path:e});return Yc(r,s)},async set(n,s){await Ze(t,{method:"setDoc",path:e,data:Ut(n),...ro(s)?{options:ro(s)}:{}})},async update(n,s){await Ze(t,{method:"updateDoc",path:e,data:Ut(n)})},async delete(n){await Ze(t,{method:"deleteDoc",path:e})},[xi]:(n,s,i)=>tu(t,{__ref:"doc",path:e},n,s,i),onSnapshot:eu};return r}function ro(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 $m(t){const e=[];let r=!1;const n={set(i,a){return s(),e.push({method:"set",path:i.path,data:Ut(a)}),n},update(i,a){return s(),e.push({method:"update",path:i.path,data:Ut(a)}),n},delete(i){return s(),e.push({method:"delete",path:i.path}),n},async commit(i){s(),r=!0,await Ze(t,{method:"batchCommit",writes:e})}};function s(){if(r)throw new se("failed-precondition","WriteBatch has already been committed.")}return n}const qm=5;async function Um(t,e,r=qm){for(let n=0;n<r;n++){const s=[],i=[],a=()=>{if(i.length>0)throw new se("failed-precondition",Ms)},o={get(l){a();const f=Mm(l);return f!==void 0?u(f):c(l)},set(l,f){return i.push({method:"set",path:l.path,data:Ut(f)}),o},update(l,f){return i.push({method:"update",path:l.path,data:Ut(f)}),o},delete(l){return i.push({method:"delete",path:l.path}),o}};async function c(l){const f=await Ze(t,{method:"getDoc",path:l.path});return s.push({path:f.path??l.path,data:f.exists&&f.data?f.data:null}),Yc(l,f)}async function u(l){Jr(l);const f=await Ze(t,{method:"getDocs",source:Zr(l)});for(const y of f.docs)s.push({path:y.path??y.id,data:y.data??null});return Xc(t,f)}const d=await e(o);try{return await Ze(t,{method:"txnCommit",reads:s,writes:i}),d}catch(l){if(l instanceof se&&l.code==="aborted")continue;throw l}}throw new se("aborted",`Transaction failed after ${r} attempts due to repeated conflicts. Another writer is concurrently updating the same documents.`)}function is(t,e){return new se("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 iu(t,e){const r={sandbox:t,lens:e};return{collection(n){if(!_i(n))throw ht(`collection path must have an odd number of segments: ${n}`);return Gs(r,n)},doc(n){if(!$c(n))throw ht(`document path must have an even number of segments: ${n}`);return Rn(r,n)},collectionGroup(n){if(n.length===0||n.includes("/"))throw ht(`collection group id must be a single non-empty segment with no '/': ${n}`);return Ii(r,{source:{__ref:"group",collectionId:n},filters:[],orders:[],limitFromEnd:!1})},batch(){return $m(r)},runTransaction(n,s){return Um(r,n,s?.maxAttempts)},setRules(){throw is("setRules","Deploy rules asynchronously through the relay instead: `await sandbox.channel.op({ method: 'setFirestoreRules', source })`.")},seed(){throw is("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 is("snapshot","Read the worker state asynchronously instead: `await sandbox.channel.op({ method: 'admin.readState' })`.")}}}const no=new WeakMap;function au(t){const e=no.get(t);if(e)return e;const r=Si(t.sandbox)?iu(t.sandbox,Bm(t.auth)):Tn(Jc(t),t);return no.set(t,r),r}function Bm(t){return t==null?{mode:"anon"}:t.token===void 0?{mode:"as",uid:t.uid}:{mode:"as",uid:t.uid,token:t.token}}const so=new WeakMap;function zm(t){const e=Vm(t)?t:t.withAuth(null),r=so.get(e);if(r)return r;const n=e.operationContext.authLens.mode==="admin"?e:vi(e,{source:e.operationContext.source,authLens:{mode:"admin"},...e.operationContext.planId===void 0?{}:{planId:e.operationContext.planId}}),s=Si(n.sandbox)?iu(n.sandbox,{mode:"admin"}):Tn(Jc(n,!0),n,!0);return so.set(e,s),s}function Vm(t){return t!==null&&typeof t=="object"&&"sandbox"in t&&typeof t.withAuth=="function"}const zr=Symbol("pyric/firestore/followsCurrentUser"),as=Symbol("pyric/firestore/authSessionScope");function Wm(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 Hm(t){if(t!==null&&typeof t=="object"){const e=t.snapshotConstraints;if(typeof e=="function")return e.call(t)}}function Gm(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 ou(t,e,r,n,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 r=="function")a=r,o=n;else if(typeof r=="object"&&r!==null){const T=r;a=T.next,o=T.error}}else if(typeof e=="function")a=e,o=r;else if(typeof e=="object"&&e!==null){const T=e;a=T.next,o=T.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=jm(t);if(u){if(i[zr]===!0)throw new se("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=Km(t),l=Ke(d.sandbox);let f;if(Gm(t))f={kind:"doc",path:t.path};else{const T=Wm(t);if(T===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 L=Hm(t);f={kind:"query",collection:T,constraints:L}}const y=i[zr]===!0,b=i[as],S=t[Zc]===!0;if(zr in i){const{[zr]:T,...L}=i;i=L}if(as in i){const{[as]:T,...L}=i;i=L}const j=()=>l.addSnapshotListener(f,a??(()=>{}),i,d.auth,o,y,S,b);return d.sandbox.runWithProvenance?.(yi(d.operationContext),j)??j()}function Km(t){if(t===null||typeof t!="object")throw new TypeError("onSnapshot: reference must be a DocumentReference or Query.");const e=t[Kc];if(!e)throw new TypeError("onSnapshot: reference was not produced by a sandbox context — pass a ref obtained from `getFirestore(ctx)`.");return e}Cm(ou);Dm(ou);class Rt{bytes;constructor(e){this.bytes=e,st(this,Gf(e)),Ht(this,Object.freeze({type:"bytes",values:Object.freeze(Array.from(e))}),()=>new Rt(e.slice()))}static fromBase64String(e){const r=atob(e),n=new Uint8Array(r.length);for(let s=0;s<r.length;s+=1)n[s]=r.charCodeAt(s);return new Rt(n)}static fromUint8Array(e){return new Rt(e.slice())}toBase64(){let e="";for(const r of this.bytes)e+=String.fromCharCode(r);return btoa(e)}toUint8Array(){return this.bytes.slice()}toString(){return`Bytes(base64: ${this.toBase64()})`}isEqual(e){return e instanceof Rt&&this.bytes.length===e.bytes.length&&this.bytes.every((r,n)=>r===e.bytes[n])}toJSON(){return{type:"firestore/bytes/1.0",bytes:this.toBase64()}}static fromJSON(e){const r=e;if(r.type!=="firestore/bytes/1.0"||typeof r.bytes!="string")throw new TypeError("Invalid Bytes JSON value.");return Rt.fromBase64String(r.bytes)}}class wr{lat;lng;constructor(e,r){if(this.lat=e,this.lng=r,!Number.isFinite(e)||e<-90||e>90)throw new TypeError("Latitude must be a number between -90 and 90.");if(!Number.isFinite(r)||r<-180||r>180)throw new TypeError("Longitude must be a number between -180 and 180.");st(this,qt("geo-point",String(e),"\0",String(r))),Ht(this,Object.freeze({type:"geo-point",latitude:e,longitude:r}),()=>new wr(e,r))}get latitude(){return this.lat}get longitude(){return this.lng}isEqual(e){return e instanceof wr&&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 r=e;if(r.type!=="firestore/geoPoint/1.0"||typeof r.latitude!="number"||typeof r.longitude!="number")throw new TypeError("Invalid GeoPoint JSON value.");return new wr(r.latitude,r.longitude)}}class Xt{_values;constructor(e){this._values=e,Ht(this,Object.freeze({type:"vector",values:Object.freeze(e.slice())}),()=>new Xt(e.slice()))}static create(e){if(!e.every(r=>typeof r=="number"))throw new TypeError("Vector values must be numbers.");return new Xt(e.slice())}toArray(){return this._values.slice()}isEqual(e){const r=e instanceof Xt?e._values:void 0;return r!==void 0&&this._values.length===r.length&&this._values.every((n,s)=>n===r[s])}toJSON(){return{type:"firestore/vectorValue/1.0",vectorValues:this.toArray()}}static fromJSON(e){const r=e;if(r.type!=="firestore/vectorValue/1.0"||!Array.isArray(r.vectorValues)||!r.vectorValues.every(n=>typeof n=="number"))throw new TypeError("Invalid VectorValue JSON value.");return Xt.create(r.vectorValues)}}function Zm(t=[]){return Xt.create(t)}function vg(){return Zf.serverTimestamp()}const St=Symbol("pyric/firestore/target");function Pr(t){return t.kind==="sandbox"?t.db:t.getDb()}const Un=new WeakMap;function Jm(t,e){return Un.set(t,e),t}const $r=new WeakMap;function Qm(t,e,r){return Un.set(t,e),$r.set(t,r),t}function ki(t,e){const r=ur(e);if(t.kind==="sandbox")return r;const n=$r.get(r);if(!n)throw new TypeError("pyric/firestore: live ref missing rebuild closure — was it produced by a factory in this package?");return n(Pr(t))}function Ym(t,e){const r=ur(e);if(t.kind==="sandbox")return r;const n=$r.get(r);if(!n)throw new TypeError("pyric/firestore: live collection ref missing rebuild closure.");return n(Pr(t))}function wg(t,e){const r=ur(e);if(t.kind==="sandbox")return r;const n=$r.get(r);if(!n)throw new TypeError("pyric/firestore: live query missing rebuild closure.");return n(Pr(t))}function Rr(t,e,r){return e.kind==="sandbox-live"?Qm(t,e,r):Jm(t,e)}function Sg(t){const e=ur(t),r=$r.get(e);return r||(()=>e)}function cr(t){const e=Xm(t);return e.assertUsable?.(),e}function Xm(t){let e;if(St in t?e=t[St]:e=Un.get(t),!e)throw new TypeError("pyric/firestore: unrecognized reference — was it produced by a factory in this package?");return e}const cu=new WeakMap,uu=new WeakMap;function Ei(t){return cu.get(t)}function ur(t){return uu.get(t)??t}function lu(t,e,r){const n={id:t.id??"",path:t.path??""};return cu.set(n,r),uu.set(n,t),Un.set(n,e),n}function eg(t){return t instanceof Wt?Array.from(t.value):null}function Ks(t){if(t instanceof Be)return Rt.fromUint8Array(t.data);if(t instanceof rt)return new wr(t.lat,t.lng);const e=eg(t);if(e)return Zm(e);if(Array.isArray(t))return t.map(Ks);if(t!==null&&typeof t=="object"){const r=Object.getPrototypeOf(t);if(r===Object.prototype||r===null){const n={};for(const[s,i]of Object.entries(t))n[s]=Ks(i);return n}}return t}function _g(t){if(t!==void 0)return Ks(t)}class ir extends Error{code;customData;name="FirebaseError";constructor(e,r,n){super(r),this.code=e,this.customData=n,Object.setPrototypeOf(this,new.target.prototype)}}Object.defineProperty(ir,"name",{value:"FirebaseError"});let Nn;function Ag(t){Nn=t}function du(t){return Nn?.resolve(t,!1)}function tg(){if(!Nn)throw new TypeError("No default sandbox app registry is installed - import and initialize pyric/app before calling a service factory without an app.");return Nn.defaultApp()}function rg(t){if(t===void 0)return rg(tg());const e=du(t);if(e)return e.service("firestore/default",()=>{const{sandbox:r,session:n}=e,s=os();e.onDelete(s.terminate);const i=e.authScope;i&&s.own(n.onCurrentUserChanged(o=>{Ke(r).reevaluateLiveListeners(o,i)}));const a={kind:"sandbox-live",sandbox:r,getDb:io(r,()=>n.currentUser),authScope:i,...s};return{[St]:a,app:t}});if(hu(t)){const n={kind:"sandbox",db:au(t),sandbox:t.sandbox,...os()};return{[St]:n}}if(sg(t)){const r={kind:"sandbox-live",sandbox:t,getDb:io(t),...os()};return{[St]:r}}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 os(){let t=!1;const e=new Set;return{own(r){return t?(r(),()=>{}):(e.add(r),()=>e.delete(r))},assertUsable(){if(t)throw new ir("failed-precondition","The client has already been terminated.")},terminate(){if(!t){t=!0;for(const r of e)r();e.clear()}}}}function ng(t){const e=du(t);if(e){e.assertAlive();const a=e.sandbox;return ng(vi(a.withAuth(null),{source:{kind:"app"},authLens:{mode:"admin"}}))}const r=hu(t)?t:t.withAuth(null),n=r.sandbox,i={kind:"sandbox",db:zm(r),sandbox:n};return{[St]:i}}function hu(t){return t instanceof Mr}function sg(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 io(t,e=()=>t.currentUser){return()=>{const r=vi(t.withAuth(e()),{source:{kind:"app"},authLens:{mode:"app-session"}});return au(r)}}class ig{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 ir("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,r){if(this.started=!0,r&&this.cachedPaths.add(r),this.networkEnabled)return e();let n,s;const i=new Promise((o,c)=>{n=o,s=c}),a={path:r,promise:i,localDone:!1,resolve:n,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(r=>r.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 ir("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(r=>r.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 ao=new WeakMap;function Nr(t){let e=ao.get(t);return e||(e=new ig,ao.set(t,e)),e}function cs(t,e,r){return st(t,qt("reference",e)),hi(t,e,r),t}function xg(t,...e){const r=cr(t),n=St in t,s=n?void 0:Ei(t),i=Pr(r);if(n){if(e.length===0)throw new TypeError("doc(db, path) requires at least one path segment.");const d=e.join("/"),l=i.doc(d),f=Rr(l,r,y=>y.doc(d));return cs(f,d,r)}const a=ur(t),o=e.length===0?a.doc():a.doc(e.join("/")),c=o.path,u=Rr(o,r,d=>d.doc(c));if(s){const d=lu(u,r,s);return cs(d,c,r)}return cs(u,c,r)}function Ig(t,...e){const r=cr(t),n=St in t;if(e.length===0)throw new TypeError("collection() requires at least one path segment.");if(n){const c=e.join("/"),u=Pr(r).collection(c);return Rr(u,r,d=>d.collection(c))}const s=ur(t),i=e.join("/"),a=s.collection(i),o=a.path;return Rr(a,r,c=>c.collection(o))}function ag(t){return t instanceof Error&&"code"in t&&typeof t.code=="string"}function og(t){if(t instanceof ir||!ag(t))return t;const e={};t.denialContext!==void 0&&(e.denialContext=t.denialContext),t.remediation!==void 0&&(e.remediation=t.remediation);const r=new ir(t.code,t.message,Object.keys(e).length===0?void 0:e);return t.denialContext!==void 0&&Object.assign(r,{denialContext:t.denialContext}),t.remediation!==void 0&&Object.assign(r,{remediation:t.remediation}),r}async function Bn(t){try{return await t()}catch(e){throw og(e)}}async function kg(t,e,r){const n=cr(t),s=Ei(t),i=s?s.toFirestore(e):e;return Nr(n).runWrite(()=>Bn(()=>ki(n,t).set(i,r)),t.path)}async function Eg(t,e){const r=cr(t);return Nr(r).runWrite(()=>Bn(()=>ki(r,t).update(e)),t.path)}async function Og(t){const e=cr(t);return Nr(e).runWrite(()=>Bn(()=>ki(e,t).delete()),t.path)}async function Cg(t,e){const r=cr(t),n=Ei(t),s=n?n.toFirestore(e):e,i=await Nr(r).runWrite(async()=>{const c=await Bn(()=>Ym(r,t).add(s));return Nr(r).cachePath(c.path),c}),a=i.path,o=Rr(i,r,c=>c.doc(a));if(st(o,qt("reference",a)),hi(o,a,r,o),n){const c=lu(o,r,n);return Sf(o,c),c}return o}function Tg(t,e){return Ke(t).deployRules(e)}function Rg(t,e){const r=Ke(t);return r.seed({rules:r.getRules(),documents:e})}function Ng(t){return Ke(t).snapshot()}function Fg(t,e={}){const r=e.recentEventLimit??10,n=Ke(t),s=n.getRules(),i=s?ws(s):{warnings:[]},a=i.warnings.map(S=>({rule:S.rule,severity:S.severity,message:S.message})),o={errors:0,warnings:0,info:0};for(const S of i.warnings)S.severity==="error"?o.errors++:S.severity==="warning"?o.warnings++:o.info++;const c=n.snapshot(),u={};for(const S of Object.keys(c)){const j=S.split("/")[0]??"";j&&(u[j]=(u[j]??0)+1)}const d=t.history(),l=d.filter(S=>S.kind==="request"),f=l.filter(S=>S.result==="deny"),y=l.slice(-r).map(S=>({path:String(S.path??""),method:String(S.method??""),result:String(S.result??""),auth:S.auth??null})),b=f.slice(-r).map(S=>({path:String(S.path??""),method:String(S.method??""),auth:S.auth??null,debugMessage:typeof S.debugMessage=="string"?S.debugMessage:void 0}));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{gg as $,as as A,Og as B,hg as C,dg as D,Ag as E,zr as F,wi as G,lt as H,ph as I,Ir as J,Ft as K,kr as L,ui as M,fh as N,vn as O,ci as P,dt as Q,ut as R,tr as S,As as T,Mt as U,pn as V,dn as W,fg as X,pg as Y,me as Z,mg as _,Rg as a,yg as a0,ng as a1,Ha as a2,tg as a3,du as a4,se as a5,Xr as a6,oe as a7,bi as a8,yi as a9,vi as aa,Mr as ab,lg as ac,bt as ad,wr as ae,Rt as af,ws as ag,Jm as ah,_g as ai,uu as aj,hi as ak,zc as al,ki as am,wg as an,vg as ao,kg as b,Ng as c,xg as d,bg as e,fl as f,rg as g,Ke as h,Fg as i,Ei as j,og as k,Pr as l,Rr as m,lu as n,Bc as o,Sg as p,Nr as q,ug as r,Tg as s,cr as t,ur as u,$r as v,ir as w,Ig as x,Cg as y,Eg as z};