@pyric/cli 0.1.0-alpha.13 → 0.1.0-alpha.15

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 (614) 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/cli/serve.d.ts +1 -1
  6. package/dist/cli/serve.d.ts.map +1 -1
  7. package/dist/cli/serve.js +208 -285
  8. package/dist/cli/serve.js.map +1 -1
  9. package/dist/cli/service-command-records/database-rules-generate.d.ts +4 -0
  10. package/dist/cli/service-command-records/database-rules-generate.d.ts.map +1 -0
  11. package/dist/cli/service-command-records/database-rules-generate.js +3 -0
  12. package/dist/cli/service-command-records/database-rules-generate.js.map +1 -0
  13. package/dist/cli/service-command-records/database-rules-lint.d.ts +4 -0
  14. package/dist/cli/service-command-records/database-rules-lint.d.ts.map +1 -0
  15. package/dist/cli/service-command-records/database-rules-lint.js +3 -0
  16. package/dist/cli/service-command-records/database-rules-lint.js.map +1 -0
  17. package/dist/cli/service-command-records/database-rules-simulate.d.ts +4 -0
  18. package/dist/cli/service-command-records/database-rules-simulate.d.ts.map +1 -0
  19. package/dist/cli/service-command-records/database-rules-simulate.js +3 -0
  20. package/dist/cli/service-command-records/database-rules-simulate.js.map +1 -0
  21. package/dist/cli/service-command-records/database-rules-validate.d.ts +4 -0
  22. package/dist/cli/service-command-records/database-rules-validate.d.ts.map +1 -0
  23. package/dist/cli/service-command-records/database-rules-validate.js +3 -0
  24. package/dist/cli/service-command-records/database-rules-validate.js.map +1 -0
  25. package/dist/cli/service-command-records/firestore-indexes-generate.d.ts +4 -0
  26. package/dist/cli/service-command-records/firestore-indexes-generate.d.ts.map +1 -0
  27. package/dist/cli/service-command-records/firestore-indexes-generate.js +3 -0
  28. package/dist/cli/service-command-records/firestore-indexes-generate.js.map +1 -0
  29. package/dist/cli/service-command-records/firestore-rules-lint.d.ts +4 -0
  30. package/dist/cli/service-command-records/firestore-rules-lint.d.ts.map +1 -0
  31. package/dist/cli/service-command-records/firestore-rules-lint.js +3 -0
  32. package/dist/cli/service-command-records/firestore-rules-lint.js.map +1 -0
  33. package/dist/cli/service-command-records/firestore-rules-resolve.d.ts +4 -0
  34. package/dist/cli/service-command-records/firestore-rules-resolve.d.ts.map +1 -0
  35. package/dist/cli/service-command-records/firestore-rules-resolve.js +3 -0
  36. package/dist/cli/service-command-records/firestore-rules-resolve.js.map +1 -0
  37. package/dist/cli/service-command-records/firestore-rules-simulate.d.ts +4 -0
  38. package/dist/cli/service-command-records/firestore-rules-simulate.d.ts.map +1 -0
  39. package/dist/cli/service-command-records/firestore-rules-simulate.js +3 -0
  40. package/dist/cli/service-command-records/firestore-rules-simulate.js.map +1 -0
  41. package/dist/cli/service-command-records/firestore-rules-validate.d.ts +4 -0
  42. package/dist/cli/service-command-records/firestore-rules-validate.d.ts.map +1 -0
  43. package/dist/cli/service-command-records/firestore-rules-validate.js +3 -0
  44. package/dist/cli/service-command-records/firestore-rules-validate.js.map +1 -0
  45. package/dist/cli/service-command-records/storage-rules-lint.d.ts +4 -0
  46. package/dist/cli/service-command-records/storage-rules-lint.d.ts.map +1 -0
  47. package/dist/cli/service-command-records/storage-rules-lint.js +3 -0
  48. package/dist/cli/service-command-records/storage-rules-lint.js.map +1 -0
  49. package/dist/cli/service-command-records/storage-rules-simulate.d.ts +4 -0
  50. package/dist/cli/service-command-records/storage-rules-simulate.d.ts.map +1 -0
  51. package/dist/cli/service-command-records/storage-rules-simulate.js +3 -0
  52. package/dist/cli/service-command-records/storage-rules-simulate.js.map +1 -0
  53. package/dist/cli/service-commands.d.ts +7 -0
  54. package/dist/cli/service-commands.d.ts.map +1 -1
  55. package/dist/cli/service-commands.generated.d.ts +35 -0
  56. package/dist/cli/service-commands.generated.d.ts.map +1 -0
  57. package/dist/cli/service-commands.generated.js +25 -0
  58. package/dist/cli/service-commands.generated.js.map +1 -0
  59. package/dist/cli/service-commands.js +23 -40
  60. package/dist/cli/service-commands.js.map +1 -1
  61. package/dist/conformance/.generated/can-i-use-browser.d.ts.map +1 -1
  62. package/dist/conformance/.generated/can-i-use-browser.js +1 -1
  63. package/dist/conformance/.generated/can-i-use-browser.js.map +1 -1
  64. package/dist/conformance/.generated/can-i-use.d.ts.map +1 -1
  65. package/dist/conformance/.generated/can-i-use.js +1 -1
  66. package/dist/conformance/.generated/can-i-use.js.map +1 -1
  67. package/dist/conformance/.generated/conformance-docs.d.ts.map +1 -1
  68. package/dist/conformance/.generated/conformance-docs.js +1 -1
  69. package/dist/conformance/.generated/conformance-docs.js.map +1 -1
  70. package/dist/functions-rtdb/development-runtime.d.ts +63 -0
  71. package/dist/functions-rtdb/development-runtime.d.ts.map +1 -0
  72. package/dist/functions-rtdb/development-runtime.js +244 -0
  73. package/dist/functions-rtdb/development-runtime.js.map +1 -0
  74. package/dist/serve/bridge-mount.d.ts +32 -2
  75. package/dist/serve/bridge-mount.d.ts.map +1 -1
  76. package/dist/serve/bridge-mount.js +232 -18
  77. package/dist/serve/bridge-mount.js.map +1 -1
  78. package/dist/serve/bundler.d.ts +4 -18
  79. package/dist/serve/bundler.d.ts.map +1 -1
  80. package/dist/serve/bundler.js +15 -37
  81. package/dist/serve/bundler.js.map +1 -1
  82. package/dist/serve/entries/app-client.d.ts.map +1 -1
  83. package/dist/serve/entries/app-client.js +5 -5
  84. package/dist/serve/entries/app-client.js.map +1 -1
  85. package/dist/serve/entries/auth-helper-core.d.ts +23 -6
  86. package/dist/serve/entries/auth-helper-core.d.ts.map +1 -1
  87. package/dist/serve/entries/auth-helper-core.js +55 -24
  88. package/dist/serve/entries/auth-helper-core.js.map +1 -1
  89. package/dist/serve/entries/database.d.ts +28 -0
  90. package/dist/serve/entries/database.d.ts.map +1 -1
  91. package/dist/serve/entries/database.js +95 -26
  92. package/dist/serve/entries/database.js.map +1 -1
  93. package/dist/serve/entries/init.d.ts.map +1 -1
  94. package/dist/serve/entries/init.js +21 -12
  95. package/dist/serve/entries/init.js.map +1 -1
  96. package/dist/serve/html-injection.d.ts +5 -0
  97. package/dist/serve/html-injection.d.ts.map +1 -0
  98. package/dist/serve/html-injection.js +59 -0
  99. package/dist/serve/html-injection.js.map +1 -0
  100. package/dist/serve/namespace.d.ts +6 -22
  101. package/dist/serve/namespace.d.ts.map +1 -1
  102. package/dist/serve/namespace.js +23 -145
  103. package/dist/serve/namespace.js.map +1 -1
  104. package/dist/serve/runtime/worker-generation.d.ts +10 -2
  105. package/dist/serve/runtime/worker-generation.d.ts.map +1 -1
  106. package/dist/serve/runtime/worker-generation.js +29 -8
  107. package/dist/serve/runtime/worker-generation.js.map +1 -1
  108. package/dist/serve/runtime/worker-replacement.d.ts +1 -2
  109. package/dist/serve/runtime/worker-replacement.d.ts.map +1 -1
  110. package/dist/serve/sandbox-session.d.ts +78 -0
  111. package/dist/serve/sandbox-session.d.ts.map +1 -0
  112. package/dist/serve/sandbox-session.js +171 -0
  113. package/dist/serve/sandbox-session.js.map +1 -0
  114. package/dist/serve/server.d.ts +5 -2
  115. package/dist/serve/server.d.ts.map +1 -1
  116. package/dist/serve/server.js +21 -5
  117. package/dist/serve/server.js.map +1 -1
  118. package/dist/serve/site-tree.d.ts +8 -0
  119. package/dist/serve/site-tree.d.ts.map +1 -0
  120. package/dist/serve/site-tree.js +113 -0
  121. package/dist/serve/site-tree.js.map +1 -0
  122. package/dist/serve/site-ui/_astro/RulesCodeEditor.CzwHdCi9.js +23 -0
  123. package/dist/serve/site-ui/_astro/_example_.jevZ7OdV.css +1 -0
  124. package/dist/serve/site-ui/_astro/_slug_.BoKXYrnu.css +1 -0
  125. package/dist/serve/site-ui/_astro/_studio_.BtYpqe1A.css +1 -0
  126. package/dist/serve/site-ui/_astro/app.BnMC0ywl.js +109 -0
  127. package/dist/serve/site-ui/_astro/app.BsFsMjn0.css +1 -0
  128. package/dist/serve/site-ui/_astro/app.DVXXR-WI.js +1 -0
  129. package/dist/serve/site-ui/_astro/chess-showcase.DzPO6kz0.js +1 -0
  130. package/dist/serve/site-ui/_astro/chess-source-explorer.C5k9c5yK.js +1 -0
  131. package/dist/serve/site-ui/_astro/chess-v2.CFHmd3UL.js +354 -0
  132. package/dist/serve/site-ui/_astro/client.D2ORs4B-.js +25 -0
  133. package/dist/serve/site-ui/_astro/example-runtime.CM0H02rx.js +291 -0
  134. package/dist/serve/site-ui/_astro/index.B4Kh80he.js +1 -0
  135. package/dist/serve/site-ui/_astro/index.DBy5LfQW.js +9 -0
  136. package/dist/serve/site-ui/_astro/index.DNyk7q8W.js +9 -0
  137. package/dist/serve/site-ui/_astro/jsx-runtime.D_zvdyIk.js +9 -0
  138. package/dist/serve/site-ui/_astro/reads.D1exkX1-.js +1 -0
  139. package/dist/serve/site-ui/_astro/sandbox-controls.BqMePr5V.js +1153 -0
  140. package/dist/serve/site-ui/_astro/seed.BCn5DhHS.js +20 -0
  141. package/dist/serve/site-ui/auth/index.html +11 -0
  142. package/dist/serve/site-ui/docs/_rhythm/index.html +100 -0
  143. package/dist/serve/site-ui/docs/agent/set-up-your-agent/index.html +43 -0
  144. package/dist/serve/site-ui/docs/agent/watch-and-review/index.html +26 -0
  145. package/dist/serve/site-ui/docs/agent/work-with-an-agent/index.html +70 -0
  146. package/dist/serve/{docs-ui → site-ui}/docs/ai-compat/index.html +3 -3
  147. package/dist/serve/site-ui/docs/api-reference/index.html +68 -0
  148. package/dist/serve/{docs-ui → site-ui}/docs/app-compat/index.html +3 -3
  149. package/dist/serve/{docs-ui → site-ui}/docs/auth-compat/index.html +3 -3
  150. package/dist/serve/site-ui/docs/build/ai-logic/index.html +64 -0
  151. package/dist/serve/site-ui/docs/build/authentication/index.html +66 -0
  152. package/dist/serve/site-ui/docs/build/cloud-firestore/index.html +84 -0
  153. package/dist/serve/site-ui/docs/build/cloud-messaging/index.html +71 -0
  154. package/dist/serve/site-ui/docs/build/cloud-storage/index.html +66 -0
  155. package/dist/serve/{docs-ui → site-ui}/docs/build/cloud-storage.md +2 -2
  156. package/dist/serve/site-ui/docs/build/realtime-database/index.html +67 -0
  157. package/dist/serve/site-ui/docs/conformance-scores/index.html +50 -0
  158. package/dist/serve/{docs-ui → site-ui}/docs/conformance-scores.md +3 -3
  159. package/dist/serve/site-ui/docs/create-pyric-reference-api/index.html +531 -0
  160. package/dist/serve/{docs-ui → site-ui}/docs/database-compat/index.html +211 -168
  161. package/dist/serve/{docs-ui → site-ui}/docs/database-compat.md +208 -170
  162. package/dist/serve/site-ui/docs/examples/chess/index.html +384 -0
  163. package/dist/serve/site-ui/docs/examples/chess.md +57 -0
  164. package/dist/serve/site-ui/docs/examples/index.html +3 -0
  165. package/dist/serve/site-ui/docs/examples.md +4 -0
  166. package/dist/serve/{docs-ui → site-ui}/docs/firestore-compat/index.html +55 -91
  167. package/dist/serve/{docs-ui → site-ui}/docs/firestore-compat.md +52 -88
  168. package/dist/serve/site-ui/docs/functions-rtdb-compat/index.html +73 -0
  169. package/dist/serve/site-ui/docs/get-started/how-the-swap-works/index.html +29 -0
  170. package/dist/serve/site-ui/docs/get-started/start-building/index.html +33 -0
  171. package/dist/serve/{docs-ui → site-ui}/docs/index.json +595 -26
  172. package/dist/serve/site-ui/docs/messaging-compat/index.html +324 -0
  173. package/dist/serve/{docs-ui → site-ui}/docs/messaging-compat.md +71 -1
  174. package/dist/serve/site-ui/docs/observe/resolve-runtime-status/index.html +28 -0
  175. package/dist/serve/site-ui/docs/observe/see-whats-happening/index.html +74 -0
  176. package/dist/serve/site-ui/docs/observe/shape-your-data/index.html +45 -0
  177. package/dist/serve/site-ui/docs/overview/index.html +17 -0
  178. package/dist/serve/site-ui/docs/pyric-admin-app-reference-api/index.html +186 -0
  179. package/dist/serve/{docs-ui → site-ui}/docs/pyric-admin-auth-reference-api/index.html +4 -4
  180. package/dist/serve/{docs-ui → site-ui}/docs/pyric-admin-database-reference-api/index.html +4 -4
  181. package/dist/serve/{docs-ui → site-ui}/docs/pyric-admin-firestore-reference-api/index.html +318 -202
  182. package/dist/serve/{docs-ui → site-ui}/docs/pyric-admin-firestore-reference-api.md +154 -27
  183. package/dist/serve/{docs-ui → site-ui}/docs/pyric-admin-messaging-reference-api/index.html +5 -5
  184. package/dist/serve/site-ui/docs/pyric-admin-storage-reference-api/index.html +318 -0
  185. package/dist/serve/{docs-ui → site-ui}/docs/pyric-ai-reference-api/index.html +5 -5
  186. package/dist/serve/site-ui/docs/pyric-ai-scripting-reference-api/index.html +160 -0
  187. package/dist/serve/site-ui/docs/pyric-app-reference-api/index.html +425 -0
  188. package/dist/serve/{docs-ui → site-ui}/docs/pyric-auth-reference-api/index.html +5 -5
  189. package/dist/serve/site-ui/docs/pyric-cli-assurance-browser-reference-api/index.html +60 -0
  190. package/dist/serve/{docs-ui → site-ui}/docs/pyric-cli-assurance-reference-api/index.html +4 -4
  191. package/dist/serve/{docs-ui → site-ui}/docs/pyric-cli-bridge-client-reference-api/index.html +4 -4
  192. package/dist/serve/site-ui/docs/pyric-cli-bridge-reference-api/index.html +507 -0
  193. package/dist/serve/site-ui/docs/pyric-cli-conformance-browser-reference-api/index.html +258 -0
  194. package/dist/serve/site-ui/docs/pyric-cli-conformance-docs-reference-api/index.html +51 -0
  195. package/dist/serve/site-ui/docs/pyric-cli-conformance-reference-api/index.html +308 -0
  196. package/dist/serve/site-ui/docs/pyric-cli-credentials-node-reference-api/index.html +68 -0
  197. package/dist/serve/{docs-ui → site-ui}/docs/pyric-cli-discover-reference-api/index.html +4 -4
  198. package/dist/serve/site-ui/docs/pyric-cli-register-reference-api/index.html +11 -0
  199. package/dist/serve/{docs-ui → site-ui}/docs/pyric-cli-remote-reference-api/index.html +4 -4
  200. package/dist/serve/{docs-ui → site-ui}/docs/pyric-cli-serve-worker-reference-api/index.html +1186 -1384
  201. package/dist/serve/{docs-ui → site-ui}/docs/pyric-cli-serve-worker-reference-api.md +817 -1291
  202. package/dist/serve/{docs-ui → site-ui}/docs/pyric-cli-verify-reference-api/index.html +4 -4
  203. package/dist/serve/site-ui/docs/pyric-cli-vite-reference-api/index.html +126 -0
  204. package/dist/serve/{docs-ui → site-ui}/docs/pyric-cli-vite-reference-api.md +1 -1
  205. package/dist/serve/site-ui/docs/pyric-database-reference-api/index.html +2641 -0
  206. package/dist/serve/{docs-ui → site-ui}/docs/pyric-database-reference-api.md +1055 -158
  207. package/dist/serve/{docs-ui → site-ui}/docs/pyric-firestore-reference-api/index.html +311 -249
  208. package/dist/serve/{docs-ui → site-ui}/docs/pyric-firestore-reference-api.md +72 -54
  209. package/dist/serve/site-ui/docs/pyric-messaging-reference-api/index.html +509 -0
  210. package/dist/serve/site-ui/docs/pyric-messaging-sw-reference-api/index.html +182 -0
  211. package/dist/serve/{docs-ui → site-ui}/docs/pyric-rules-reference-api/index.html +7 -26
  212. package/dist/serve/{docs-ui → site-ui}/docs/pyric-rules-reference-api.md +13 -23
  213. package/dist/serve/site-ui/docs/pyric-sandbox-database-reference-api/index.html +121 -0
  214. package/dist/serve/site-ui/docs/pyric-sandbox-firestore-reference-api/index.html +203 -0
  215. package/dist/serve/{docs-ui → site-ui}/docs/pyric-sandbox-reference-api/index.html +26 -5
  216. package/dist/serve/{docs-ui → site-ui}/docs/pyric-sandbox-reference-api.md +22 -22
  217. package/dist/serve/{docs-ui → site-ui}/docs/pyric-storage-reference-api/index.html +5 -15
  218. package/dist/serve/{docs-ui → site-ui}/docs/pyric-storage-reference-api.md +0 -13
  219. package/dist/serve/site-ui/docs/pyric-ui-agents-reference-api/index.html +639 -0
  220. package/dist/serve/site-ui/docs/pyric-ui-auth-hooks-reference-api/index.html +100 -0
  221. package/dist/serve/{docs-ui → site-ui}/docs/pyric-ui-auth-reference-api/index.html +4 -4
  222. package/dist/serve/site-ui/docs/pyric-ui-events-hooks-reference-api/index.html +24 -0
  223. package/dist/serve/{docs-ui → site-ui}/docs/pyric-ui-events-reference-api/index.html +4 -4
  224. package/dist/serve/site-ui/docs/pyric-ui-firestore-hooks-reference-api/index.html +136 -0
  225. package/dist/serve/{docs-ui → site-ui}/docs/pyric-ui-firestore-reference-api/index.html +7 -7
  226. package/dist/serve/{docs-ui → site-ui}/docs/pyric-ui-firestore-reference-api.md +4 -4
  227. package/dist/serve/{docs-ui → site-ui}/docs/pyric-ui-primitives-reference-api/index.html +4 -4
  228. package/dist/serve/{docs-ui → site-ui}/docs/pyric-ui-rtdb-reference-api/index.html +4 -4
  229. package/dist/serve/site-ui/docs/pyric-ui-rules-hooks-reference-api/index.html +16 -0
  230. package/dist/serve/{docs-ui → site-ui}/docs/pyric-ui-rules-reference-api/index.html +4 -4
  231. package/dist/serve/site-ui/docs/pyric-ui-storage-hooks-reference-api/index.html +176 -0
  232. package/dist/serve/{docs-ui → site-ui}/docs/pyric-ui-storage-reference-api/index.html +10 -11
  233. package/dist/serve/{docs-ui → site-ui}/docs/pyric-ui-storage-reference-api.md +7 -8
  234. package/dist/serve/site-ui/docs/pyric-ui-traffic-hooks-reference-api/index.html +188 -0
  235. package/dist/serve/{docs-ui → site-ui}/docs/pyric-ui-traffic-reference-api/index.html +4 -4
  236. package/dist/serve/{docs-ui → site-ui}/docs/rules-compat/index.html +87 -57
  237. package/dist/serve/{docs-ui → site-ui}/docs/rules-compat.md +84 -54
  238. package/dist/serve/site-ui/docs/secure/audit-your-rules/index.html +51 -0
  239. package/dist/serve/site-ui/docs/secure/firestore-rules-limits/index.html +106 -0
  240. package/dist/serve/site-ui/docs/secure/read-a-denial/index.html +41 -0
  241. package/dist/serve/site-ui/docs/secure/rtdb-rules-in-typescript/index.html +67 -0
  242. package/dist/serve/site-ui/docs/secure/rules-standard-library/index.html +159 -0
  243. package/dist/serve/{docs-ui → site-ui}/docs/secure/rules-standard-library.md +2 -2
  244. package/dist/serve/site-ui/docs/secure/secure-it-with-rules/index.html +47 -0
  245. package/dist/serve/site-ui/docs/secure/simulate-and-lint/index.html +95 -0
  246. package/dist/serve/site-ui/docs/secure/write-a-rules-test-suite/index.html +82 -0
  247. package/dist/serve/site-ui/docs/ship/ship-to-production/index.html +37 -0
  248. package/dist/serve/site-ui/docs/ship/test-in-node/index.html +75 -0
  249. package/dist/serve/{docs-ui → site-ui}/docs/storage-compat/index.html +8 -8
  250. package/dist/serve/{docs-ui → site-ui}/docs/storage-compat.md +5 -5
  251. package/dist/serve/site-ui/docs/trust/how-we-know-it-matches-firebase/index.html +132 -0
  252. package/dist/serve/site-ui/docs/trust/rules-standard-library/index.html +861 -0
  253. package/dist/serve/site-ui/docs/trust/rules-standard-library.md +344 -0
  254. package/dist/serve/site-ui/docs/trust/storage-rules-stdlib-research/index.html +582 -0
  255. package/dist/serve/site-ui/docs/trust/storage-rules-stdlib-research.md +448 -0
  256. package/dist/serve/site-ui/docs/trust/versioning-and-compatibility/index.html +14 -0
  257. package/dist/serve/{docs-ui → site-ui}/docs/tutorial/index.html +4 -4
  258. package/dist/serve/{docs-ui → site-ui}/docs/tutorial.md +1 -1
  259. package/dist/serve/site-ui/examples/chess/index.html +2 -0
  260. package/dist/serve/site-ui/examples/firestore-first-write/index.html +2 -0
  261. package/dist/serve/site-ui/firestore/index.html +11 -0
  262. package/dist/serve/site-ui/index.html +11 -0
  263. package/dist/serve/{docs-ui → site-ui}/llms.txt +6 -2
  264. package/dist/serve/site-ui/rtdb/index.html +11 -0
  265. package/dist/serve/site-ui/settings/index.html +11 -0
  266. package/dist/serve/site-ui/storage/index.html +11 -0
  267. package/dist/serve/site-ui/studio-routes.json +1 -0
  268. package/dist/serve/site-ui/traffic/index.html +11 -0
  269. package/dist/serve/standalone-assets.d.ts +4 -10
  270. package/dist/serve/standalone-assets.d.ts.map +1 -1
  271. package/dist/serve/standalone-assets.js +8 -21
  272. package/dist/serve/standalone-assets.js.map +1 -1
  273. package/dist/serve/vite-ai-config.d.ts +2 -0
  274. package/dist/serve/vite-ai-config.d.ts.map +1 -1
  275. package/dist/serve/vite-ai-config.js +4 -0
  276. package/dist/serve/vite-ai-config.js.map +1 -1
  277. package/dist/serve/vite-functions-development.d.ts +29 -0
  278. package/dist/serve/vite-functions-development.d.ts.map +1 -0
  279. package/dist/serve/vite-functions-development.js +150 -0
  280. package/dist/serve/vite-functions-development.js.map +1 -0
  281. package/dist/serve/vite-generation-bridge.d.ts +17 -0
  282. package/dist/serve/vite-generation-bridge.d.ts.map +1 -0
  283. package/dist/serve/vite-generation-bridge.js +47 -0
  284. package/dist/serve/vite-generation-bridge.js.map +1 -0
  285. package/dist/serve/vite-generation-functions.d.ts +35 -0
  286. package/dist/serve/vite-generation-functions.d.ts.map +1 -0
  287. package/dist/serve/vite-generation-functions.js +46 -0
  288. package/dist/serve/vite-generation-functions.js.map +1 -0
  289. package/dist/serve/vite-generation-middleware.d.ts +10 -0
  290. package/dist/serve/vite-generation-middleware.d.ts.map +1 -0
  291. package/dist/serve/vite-generation-middleware.js +40 -0
  292. package/dist/serve/vite-generation-middleware.js.map +1 -0
  293. package/dist/serve/vite-generation-rules-watch.d.ts +8 -0
  294. package/dist/serve/vite-generation-rules-watch.d.ts.map +1 -0
  295. package/dist/serve/vite-generation-rules-watch.js +33 -0
  296. package/dist/serve/vite-generation-rules-watch.js.map +1 -0
  297. package/dist/serve/vite-module-swap.d.ts +16 -0
  298. package/dist/serve/vite-module-swap.d.ts.map +1 -0
  299. package/dist/serve/vite-module-swap.js +96 -0
  300. package/dist/serve/vite-module-swap.js.map +1 -0
  301. package/dist/serve/vite-page-runtime.d.ts +29 -0
  302. package/dist/serve/vite-page-runtime.d.ts.map +1 -0
  303. package/dist/serve/vite-page-runtime.js +71 -0
  304. package/dist/serve/vite-page-runtime.js.map +1 -0
  305. package/dist/serve/vite-plugin.d.ts +44 -4
  306. package/dist/serve/vite-plugin.d.ts.map +1 -1
  307. package/dist/serve/vite-plugin.js +62 -864
  308. package/dist/serve/vite-plugin.js.map +1 -1
  309. package/dist/serve/vite-sandbox-generation.d.ts +57 -0
  310. package/dist/serve/vite-sandbox-generation.d.ts.map +1 -0
  311. package/dist/serve/vite-sandbox-generation.js +178 -0
  312. package/dist/serve/vite-sandbox-generation.js.map +1 -0
  313. package/dist/serve/vite-worker-runtime.d.ts +1 -1
  314. package/dist/serve/vite-worker-runtime.d.ts.map +1 -1
  315. package/dist/serve/vite-worker-runtime.js +8 -4
  316. package/dist/serve/vite-worker-runtime.js.map +1 -1
  317. package/dist/serve/worker/client/disconnect.d.ts.map +1 -1
  318. package/dist/serve/worker/client/disconnect.js +2 -0
  319. package/dist/serve/worker/client/disconnect.js.map +1 -1
  320. package/dist/serve/worker/client/handles.d.ts +5 -0
  321. package/dist/serve/worker/client/handles.d.ts.map +1 -1
  322. package/dist/serve/worker/client/handles.js.map +1 -1
  323. package/dist/serve/worker/client/pagehide.d.ts +13 -0
  324. package/dist/serve/worker/client/pagehide.d.ts.map +1 -0
  325. package/dist/serve/worker/client/pagehide.js +19 -0
  326. package/dist/serve/worker/client/pagehide.js.map +1 -0
  327. package/dist/serve/worker/client/rtdb-admin.d.ts +8 -0
  328. package/dist/serve/worker/client/rtdb-admin.d.ts.map +1 -0
  329. package/dist/serve/worker/client/rtdb-admin.js +39 -0
  330. package/dist/serve/worker/client/rtdb-admin.js.map +1 -0
  331. package/dist/serve/worker/client/rtdb-connection-lifecycle.d.ts +15 -0
  332. package/dist/serve/worker/client/rtdb-connection-lifecycle.d.ts.map +1 -0
  333. package/dist/serve/worker/client/rtdb-connection-lifecycle.js +45 -0
  334. package/dist/serve/worker/client/rtdb-connection-lifecycle.js.map +1 -0
  335. package/dist/serve/worker/client/rtdb-controls.d.ts +6 -0
  336. package/dist/serve/worker/client/rtdb-controls.d.ts.map +1 -0
  337. package/dist/serve/worker/client/rtdb-controls.js +8 -0
  338. package/dist/serve/worker/client/rtdb-controls.js.map +1 -0
  339. package/dist/serve/worker/client/rtdb-listeners.d.ts +24 -0
  340. package/dist/serve/worker/client/rtdb-listeners.d.ts.map +1 -0
  341. package/dist/serve/worker/client/rtdb-listeners.js +262 -0
  342. package/dist/serve/worker/client/rtdb-listeners.js.map +1 -0
  343. package/dist/serve/worker/client/rtdb-reads.d.ts +4 -0
  344. package/dist/serve/worker/client/rtdb-reads.d.ts.map +1 -0
  345. package/dist/serve/worker/client/rtdb-reads.js +11 -0
  346. package/dist/serve/worker/client/rtdb-reads.js.map +1 -0
  347. package/dist/serve/worker/client/rtdb-references.d.ts +19 -0
  348. package/dist/serve/worker/client/rtdb-references.d.ts.map +1 -0
  349. package/dist/serve/worker/client/rtdb-references.js +63 -0
  350. package/dist/serve/worker/client/rtdb-references.js.map +1 -0
  351. package/dist/serve/worker/client/rtdb-snapshots.d.ts +20 -0
  352. package/dist/serve/worker/client/rtdb-snapshots.d.ts.map +1 -0
  353. package/dist/serve/worker/client/rtdb-snapshots.js +64 -0
  354. package/dist/serve/worker/client/rtdb-snapshots.js.map +1 -0
  355. package/dist/serve/worker/client/rtdb-transactions.d.ts +14 -0
  356. package/dist/serve/worker/client/rtdb-transactions.d.ts.map +1 -0
  357. package/dist/serve/worker/client/rtdb-transactions.js +34 -0
  358. package/dist/serve/worker/client/rtdb-transactions.js.map +1 -0
  359. package/dist/serve/worker/client/rtdb-writes.d.ts +8 -0
  360. package/dist/serve/worker/client/rtdb-writes.d.ts.map +1 -0
  361. package/dist/serve/worker/client/rtdb-writes.js +65 -0
  362. package/dist/serve/worker/client/rtdb-writes.js.map +1 -0
  363. package/dist/serve/worker/client.d.ts +0 -2
  364. package/dist/serve/worker/client.d.ts.map +1 -1
  365. package/dist/serve/worker/client.js +0 -2
  366. package/dist/serve/worker/client.js.map +1 -1
  367. package/dist/serve/worker/entry.js +2 -2
  368. package/dist/serve/worker/entry.js.map +1 -1
  369. package/dist/serve/worker/host/dispatch.d.ts +2 -0
  370. package/dist/serve/worker/host/dispatch.d.ts.map +1 -1
  371. package/dist/serve/worker/host/dispatch.js +24 -2
  372. package/dist/serve/worker/host/dispatch.js.map +1 -1
  373. package/dist/serve/worker/host/rtdb.d.ts +6 -2
  374. package/dist/serve/worker/host/rtdb.d.ts.map +1 -1
  375. package/dist/serve/worker/host/rtdb.js +224 -2
  376. package/dist/serve/worker/host/rtdb.js.map +1 -1
  377. package/dist/serve/worker/host/studio.d.ts.map +1 -1
  378. package/dist/serve/worker/host/studio.js +2 -0
  379. package/dist/serve/worker/host/studio.js.map +1 -1
  380. package/dist/serve/worker/host/subscriptions.d.ts.map +1 -1
  381. package/dist/serve/worker/host/subscriptions.js +3 -3
  382. package/dist/serve/worker/host/subscriptions.js.map +1 -1
  383. package/dist/serve/worker/host.d.ts +1 -1
  384. package/dist/serve/worker/host.d.ts.map +1 -1
  385. package/dist/serve/worker/host.js +1 -1
  386. package/dist/serve/worker/host.js.map +1 -1
  387. package/dist/serve/worker/index.d.ts +16 -1
  388. package/dist/serve/worker/index.d.ts.map +1 -1
  389. package/dist/serve/worker/index.js +17 -4
  390. package/dist/serve/worker/index.js.map +1 -1
  391. package/dist/serve/worker/protocol.d.ts +57 -0
  392. package/dist/serve/worker/protocol.d.ts.map +1 -1
  393. package/dist/serve/worker/protocol.js.map +1 -1
  394. package/dist/serve/worker/rtdb-value-equality.d.ts +3 -0
  395. package/dist/serve/worker/rtdb-value-equality.d.ts.map +1 -0
  396. package/dist/serve/worker/rtdb-value-equality.js +18 -0
  397. package/dist/serve/worker/rtdb-value-equality.js.map +1 -0
  398. package/dist/serve/worker/serve-init.js +2 -2
  399. package/dist/serve/worker/serve-init.js.map +1 -1
  400. package/dist/serve/worker/service-worker-relay.js +2 -2
  401. package/dist/serve/worker/service-worker-relay.js.map +1 -1
  402. package/package.json +7 -5
  403. package/src/assurance/.generated/conformance-verdicts.ts +120 -75
  404. package/src/cli/serve.ts +216 -308
  405. package/src/cli/service-command-records/database-rules-generate.ts +3 -0
  406. package/src/cli/service-command-records/database-rules-lint.ts +3 -0
  407. package/src/cli/service-command-records/database-rules-simulate.ts +3 -0
  408. package/src/cli/service-command-records/database-rules-validate.ts +3 -0
  409. package/src/cli/service-command-records/firestore-indexes-generate.ts +3 -0
  410. package/src/cli/service-command-records/firestore-rules-lint.ts +3 -0
  411. package/src/cli/service-command-records/firestore-rules-resolve.ts +3 -0
  412. package/src/cli/service-command-records/firestore-rules-simulate.ts +3 -0
  413. package/src/cli/service-command-records/firestore-rules-validate.ts +3 -0
  414. package/src/cli/service-command-records/storage-rules-lint.ts +3 -0
  415. package/src/cli/service-command-records/storage-rules-simulate.ts +3 -0
  416. package/src/cli/service-commands.generated.ts +27 -0
  417. package/src/cli/service-commands.test.ts +43 -0
  418. package/src/cli/service-commands.ts +36 -51
  419. package/src/conformance/.generated/can-i-use-browser.ts +1 -1
  420. package/src/conformance/.generated/can-i-use.ts +1 -1
  421. package/src/conformance/.generated/conformance-docs.ts +1 -1
  422. package/src/functions-rtdb/development-runtime.ts +299 -0
  423. package/src/serve/bridge-mount.ts +253 -19
  424. package/src/serve/bundler.ts +17 -36
  425. package/src/serve/entries/app-client.ts +5 -4
  426. package/src/serve/entries/auth-helper-core.ts +83 -30
  427. package/src/serve/entries/database.ts +180 -57
  428. package/src/serve/entries/init.ts +30 -20
  429. package/src/serve/html-injection.ts +65 -0
  430. package/src/serve/namespace.ts +26 -169
  431. package/src/serve/runtime/worker-generation.ts +29 -7
  432. package/src/serve/runtime/worker-replacement.ts +1 -1
  433. package/src/serve/sandbox-session.ts +233 -0
  434. package/src/serve/server.ts +20 -5
  435. package/src/serve/site-tree.ts +146 -0
  436. package/src/serve/standalone-assets.ts +9 -26
  437. package/src/serve/vite-ai-config.ts +8 -0
  438. package/src/serve/vite-functions-development.ts +201 -0
  439. package/src/serve/vite-generation-bridge.ts +66 -0
  440. package/src/serve/vite-generation-functions.ts +78 -0
  441. package/src/serve/vite-generation-middleware.ts +56 -0
  442. package/src/serve/vite-generation-rules-watch.ts +37 -0
  443. package/src/serve/vite-module-swap.ts +119 -0
  444. package/src/serve/vite-page-runtime.ts +100 -0
  445. package/src/serve/vite-plugin.ts +78 -882
  446. package/src/serve/vite-sandbox-generation.ts +255 -0
  447. package/src/serve/vite-worker-runtime.ts +12 -5
  448. package/src/serve/worker/client/disconnect.ts +3 -1
  449. package/src/serve/worker/client/handles.ts +5 -0
  450. package/src/serve/worker/client/pagehide.ts +31 -0
  451. package/src/serve/worker/client/rtdb-admin.ts +74 -0
  452. package/src/serve/worker/client/rtdb-connection-lifecycle.ts +52 -0
  453. package/src/serve/worker/client/rtdb-controls.ts +8 -0
  454. package/src/serve/worker/client/rtdb-listeners.ts +337 -0
  455. package/src/serve/worker/client/rtdb-reads.ts +12 -0
  456. package/src/serve/worker/client/rtdb-references.ts +85 -0
  457. package/src/serve/worker/client/rtdb-snapshots.ts +118 -0
  458. package/src/serve/worker/client/rtdb-transactions.ts +51 -0
  459. package/src/serve/worker/client/rtdb-writes.ts +74 -0
  460. package/src/serve/worker/client.ts +0 -2
  461. package/src/serve/worker/entry.ts +2 -2
  462. package/src/serve/worker/host/dispatch.ts +22 -2
  463. package/src/serve/worker/host/rtdb.ts +243 -2
  464. package/src/serve/worker/host/studio.ts +2 -0
  465. package/src/serve/worker/host/subscriptions.ts +8 -4
  466. package/src/serve/worker/host.ts +1 -1
  467. package/src/serve/worker/index.ts +58 -10
  468. package/src/serve/worker/protocol.ts +23 -2
  469. package/src/serve/worker/rtdb-value-equality.ts +17 -0
  470. package/src/serve/worker/serve-init.ts +2 -2
  471. package/src/serve/worker/service-worker-relay.ts +2 -2
  472. package/dist/serve/docs-ui/_astro/_slug_.DUci-duz.css +0 -1
  473. package/dist/serve/docs-ui/docs/_rhythm/index.html +0 -100
  474. package/dist/serve/docs-ui/docs/agent/set-up-your-agent/index.html +0 -43
  475. package/dist/serve/docs-ui/docs/agent/watch-and-review/index.html +0 -26
  476. package/dist/serve/docs-ui/docs/agent/work-with-an-agent/index.html +0 -70
  477. package/dist/serve/docs-ui/docs/api-reference/index.html +0 -68
  478. package/dist/serve/docs-ui/docs/build/ai-logic/index.html +0 -64
  479. package/dist/serve/docs-ui/docs/build/authentication/index.html +0 -66
  480. package/dist/serve/docs-ui/docs/build/cloud-firestore/index.html +0 -70
  481. package/dist/serve/docs-ui/docs/build/cloud-messaging/index.html +0 -71
  482. package/dist/serve/docs-ui/docs/build/cloud-storage/index.html +0 -66
  483. package/dist/serve/docs-ui/docs/build/realtime-database/index.html +0 -67
  484. package/dist/serve/docs-ui/docs/conformance-scores/index.html +0 -50
  485. package/dist/serve/docs-ui/docs/create-pyric-reference-api/index.html +0 -531
  486. package/dist/serve/docs-ui/docs/functions-rtdb-compat/index.html +0 -73
  487. package/dist/serve/docs-ui/docs/get-started/how-the-swap-works/index.html +0 -29
  488. package/dist/serve/docs-ui/docs/get-started/start-building/index.html +0 -33
  489. package/dist/serve/docs-ui/docs/messaging-compat/index.html +0 -265
  490. package/dist/serve/docs-ui/docs/observe/resolve-runtime-status/index.html +0 -28
  491. package/dist/serve/docs-ui/docs/observe/see-whats-happening/index.html +0 -74
  492. package/dist/serve/docs-ui/docs/observe/shape-your-data/index.html +0 -45
  493. package/dist/serve/docs-ui/docs/overview/index.html +0 -17
  494. package/dist/serve/docs-ui/docs/pyric-admin-app-reference-api/index.html +0 -186
  495. package/dist/serve/docs-ui/docs/pyric-admin-storage-reference-api/index.html +0 -318
  496. package/dist/serve/docs-ui/docs/pyric-ai-scripting-reference-api/index.html +0 -160
  497. package/dist/serve/docs-ui/docs/pyric-app-reference-api/index.html +0 -425
  498. package/dist/serve/docs-ui/docs/pyric-cli-assurance-browser-reference-api/index.html +0 -60
  499. package/dist/serve/docs-ui/docs/pyric-cli-bridge-reference-api/index.html +0 -507
  500. package/dist/serve/docs-ui/docs/pyric-cli-conformance-browser-reference-api/index.html +0 -258
  501. package/dist/serve/docs-ui/docs/pyric-cli-conformance-docs-reference-api/index.html +0 -51
  502. package/dist/serve/docs-ui/docs/pyric-cli-conformance-reference-api/index.html +0 -308
  503. package/dist/serve/docs-ui/docs/pyric-cli-credentials-node-reference-api/index.html +0 -68
  504. package/dist/serve/docs-ui/docs/pyric-cli-register-reference-api/index.html +0 -11
  505. package/dist/serve/docs-ui/docs/pyric-cli-vite-reference-api/index.html +0 -126
  506. package/dist/serve/docs-ui/docs/pyric-database-reference-api/index.html +0 -1852
  507. package/dist/serve/docs-ui/docs/pyric-messaging-reference-api/index.html +0 -509
  508. package/dist/serve/docs-ui/docs/pyric-messaging-sw-reference-api/index.html +0 -182
  509. package/dist/serve/docs-ui/docs/pyric-sandbox-database-reference-api/index.html +0 -121
  510. package/dist/serve/docs-ui/docs/pyric-sandbox-firestore-reference-api/index.html +0 -203
  511. package/dist/serve/docs-ui/docs/pyric-ui-agents-reference-api/index.html +0 -639
  512. package/dist/serve/docs-ui/docs/pyric-ui-auth-hooks-reference-api/index.html +0 -100
  513. package/dist/serve/docs-ui/docs/pyric-ui-events-hooks-reference-api/index.html +0 -24
  514. package/dist/serve/docs-ui/docs/pyric-ui-firestore-hooks-reference-api/index.html +0 -136
  515. package/dist/serve/docs-ui/docs/pyric-ui-rules-hooks-reference-api/index.html +0 -16
  516. package/dist/serve/docs-ui/docs/pyric-ui-storage-hooks-reference-api/index.html +0 -176
  517. package/dist/serve/docs-ui/docs/pyric-ui-traffic-hooks-reference-api/index.html +0 -188
  518. package/dist/serve/docs-ui/docs/secure/audit-your-rules/index.html +0 -51
  519. package/dist/serve/docs-ui/docs/secure/firestore-rules-limits/index.html +0 -106
  520. package/dist/serve/docs-ui/docs/secure/read-a-denial/index.html +0 -41
  521. package/dist/serve/docs-ui/docs/secure/rtdb-rules-in-typescript/index.html +0 -67
  522. package/dist/serve/docs-ui/docs/secure/rules-standard-library/index.html +0 -159
  523. package/dist/serve/docs-ui/docs/secure/secure-it-with-rules/index.html +0 -47
  524. package/dist/serve/docs-ui/docs/secure/simulate-and-lint/index.html +0 -95
  525. package/dist/serve/docs-ui/docs/secure/write-a-rules-test-suite/index.html +0 -82
  526. package/dist/serve/docs-ui/docs/ship/ship-to-production/index.html +0 -37
  527. package/dist/serve/docs-ui/docs/ship/test-in-node/index.html +0 -75
  528. package/dist/serve/docs-ui/docs/trust/how-we-know-it-matches-firebase/index.html +0 -132
  529. package/dist/serve/docs-ui/docs/trust/versioning-and-compatibility/index.html +0 -14
  530. package/dist/serve/docs-ui/index.html +0 -1
  531. package/dist/serve/studio-ui/assets/RulesCodeEditor-BDlH-5lp.js +0 -23
  532. package/dist/serve/studio-ui/assets/index-Bf9SSE8L.js +0 -1218
  533. package/dist/serve/studio-ui/assets/index-BlSGru_r.css +0 -1
  534. package/dist/serve/studio-ui/assets/seed-D_UjxfOU.js +0 -20
  535. package/dist/serve/studio-ui/index.html +0 -32
  536. package/dist/serve/worker/client/rtdb.d.ts +0 -36
  537. package/dist/serve/worker/client/rtdb.d.ts.map +0 -1
  538. package/dist/serve/worker/client/rtdb.js +0 -241
  539. package/dist/serve/worker/client/rtdb.js.map +0 -1
  540. package/src/serve/worker/client/rtdb.ts +0 -311
  541. /package/dist/serve/{docs-ui → site-ui}/404.html +0 -0
  542. /package/dist/serve/{docs-ui → site-ui}/_astro/_slug_.CXh9yTP1.css +0 -0
  543. /package/dist/serve/{docs-ui → site-ui}/docs/_rhythm.md +0 -0
  544. /package/dist/serve/{docs-ui → site-ui}/docs/agent/set-up-your-agent.md +0 -0
  545. /package/dist/serve/{docs-ui → site-ui}/docs/agent/watch-and-review.md +0 -0
  546. /package/dist/serve/{docs-ui → site-ui}/docs/agent/work-with-an-agent.md +0 -0
  547. /package/dist/serve/{docs-ui → site-ui}/docs/ai-compat.md +0 -0
  548. /package/dist/serve/{docs-ui → site-ui}/docs/api-reference.md +0 -0
  549. /package/dist/serve/{docs-ui → site-ui}/docs/app-compat.md +0 -0
  550. /package/dist/serve/{docs-ui → site-ui}/docs/auth-compat.md +0 -0
  551. /package/dist/serve/{docs-ui → site-ui}/docs/build/ai-logic.md +0 -0
  552. /package/dist/serve/{docs-ui → site-ui}/docs/build/authentication.md +0 -0
  553. /package/dist/serve/{docs-ui → site-ui}/docs/build/cloud-firestore.md +0 -0
  554. /package/dist/serve/{docs-ui → site-ui}/docs/build/cloud-messaging.md +0 -0
  555. /package/dist/serve/{docs-ui → site-ui}/docs/build/realtime-database.md +0 -0
  556. /package/dist/serve/{docs-ui → site-ui}/docs/create-pyric-reference-api.md +0 -0
  557. /package/dist/serve/{docs-ui → site-ui}/docs/functions-rtdb-compat.md +0 -0
  558. /package/dist/serve/{docs-ui → site-ui}/docs/get-started/how-the-swap-works.md +0 -0
  559. /package/dist/serve/{docs-ui → site-ui}/docs/get-started/start-building.md +0 -0
  560. /package/dist/serve/{docs-ui → site-ui}/docs/index.html +0 -0
  561. /package/dist/serve/{docs-ui → site-ui}/docs/observe/resolve-runtime-status.md +0 -0
  562. /package/dist/serve/{docs-ui → site-ui}/docs/observe/see-whats-happening.md +0 -0
  563. /package/dist/serve/{docs-ui → site-ui}/docs/observe/shape-your-data.md +0 -0
  564. /package/dist/serve/{docs-ui → site-ui}/docs/overview.md +0 -0
  565. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-admin-app-reference-api.md +0 -0
  566. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-admin-auth-reference-api.md +0 -0
  567. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-admin-database-reference-api.md +0 -0
  568. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-admin-messaging-reference-api.md +0 -0
  569. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-admin-storage-reference-api.md +0 -0
  570. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-ai-reference-api.md +0 -0
  571. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-ai-scripting-reference-api.md +0 -0
  572. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-app-reference-api.md +0 -0
  573. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-auth-reference-api.md +0 -0
  574. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-cli-assurance-browser-reference-api.md +0 -0
  575. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-cli-assurance-reference-api.md +0 -0
  576. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-cli-bridge-client-reference-api.md +0 -0
  577. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-cli-bridge-reference-api.md +0 -0
  578. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-cli-conformance-browser-reference-api.md +0 -0
  579. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-cli-conformance-docs-reference-api.md +0 -0
  580. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-cli-conformance-reference-api.md +0 -0
  581. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-cli-credentials-node-reference-api.md +0 -0
  582. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-cli-discover-reference-api.md +0 -0
  583. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-cli-register-reference-api.md +0 -0
  584. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-cli-remote-reference-api.md +0 -0
  585. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-cli-verify-reference-api.md +0 -0
  586. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-messaging-reference-api.md +0 -0
  587. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-messaging-sw-reference-api.md +0 -0
  588. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-sandbox-database-reference-api.md +0 -0
  589. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-sandbox-firestore-reference-api.md +0 -0
  590. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-ui-agents-reference-api.md +0 -0
  591. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-ui-auth-hooks-reference-api.md +0 -0
  592. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-ui-auth-reference-api.md +0 -0
  593. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-ui-events-hooks-reference-api.md +0 -0
  594. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-ui-events-reference-api.md +0 -0
  595. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-ui-firestore-hooks-reference-api.md +0 -0
  596. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-ui-primitives-reference-api.md +0 -0
  597. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-ui-rtdb-reference-api.md +0 -0
  598. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-ui-rules-hooks-reference-api.md +0 -0
  599. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-ui-rules-reference-api.md +0 -0
  600. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-ui-storage-hooks-reference-api.md +0 -0
  601. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-ui-traffic-hooks-reference-api.md +0 -0
  602. /package/dist/serve/{docs-ui → site-ui}/docs/pyric-ui-traffic-reference-api.md +0 -0
  603. /package/dist/serve/{docs-ui → site-ui}/docs/secure/audit-your-rules.md +0 -0
  604. /package/dist/serve/{docs-ui → site-ui}/docs/secure/firestore-rules-limits.md +0 -0
  605. /package/dist/serve/{docs-ui → site-ui}/docs/secure/read-a-denial.md +0 -0
  606. /package/dist/serve/{docs-ui → site-ui}/docs/secure/rtdb-rules-in-typescript.md +0 -0
  607. /package/dist/serve/{docs-ui → site-ui}/docs/secure/secure-it-with-rules.md +0 -0
  608. /package/dist/serve/{docs-ui → site-ui}/docs/secure/simulate-and-lint.md +0 -0
  609. /package/dist/serve/{docs-ui → site-ui}/docs/secure/write-a-rules-test-suite.md +0 -0
  610. /package/dist/serve/{docs-ui → site-ui}/docs/ship/ship-to-production.md +0 -0
  611. /package/dist/serve/{docs-ui → site-ui}/docs/ship/test-in-node.md +0 -0
  612. /package/dist/serve/{docs-ui → site-ui}/docs/trust/how-we-know-it-matches-firebase.md +0 -0
  613. /package/dist/serve/{docs-ui → site-ui}/docs/trust/versioning-and-compatibility.md +0 -0
  614. /package/dist/serve/{studio-ui → site-ui}/pyric-logo.svg +0 -0
@@ -1,1218 +0,0 @@
1
- var QN=Object.defineProperty;var JN=(t,e,n)=>e in t?QN(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var G=(t,e,n)=>JN(t,typeof e!="symbol"?e+"":e,n);(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))r(s);new MutationObserver(s=>{for(const o of s)if(o.type==="childList")for(const c of o.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&r(c)}).observe(document,{childList:!0,subtree:!0});function n(s){const o={};return s.integrity&&(o.integrity=s.integrity),s.referrerPolicy&&(o.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?o.credentials="include":s.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function r(s){if(s.ep)return;s.ep=!0;const o=n(s);fetch(s.href,o)}})();var f1=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function XN(t){if(Object.prototype.hasOwnProperty.call(t,"__esModule"))return t;var e=t.default;if(typeof e=="function"){var n=function r(){return this instanceof r?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};n.prototype=e.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(t).forEach(function(r){var s=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(n,r,s.get?s:{enumerable:!0,get:function(){return t[r]}})}),n}var Ep={exports:{}},dl={};/**
2
- * @license React
3
- * react-jsx-runtime.production.js
4
- *
5
- * Copyright (c) Meta Platforms, Inc. and affiliates.
6
- *
7
- * This source code is licensed under the MIT license found in the
8
- * LICENSE file in the root directory of this source tree.
9
- */var Fw;function eO(){if(Fw)return dl;Fw=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function n(r,s,o){var c=null;if(o!==void 0&&(c=""+o),s.key!==void 0&&(c=""+s.key),"key"in s){o={};for(var d in s)d!=="key"&&(o[d]=s[d])}else o=s;return s=o.ref,{$$typeof:t,type:r,key:c,ref:s!==void 0?s:null,props:o}}return dl.Fragment=e,dl.jsx=n,dl.jsxs=n,dl}var zw;function tO(){return zw||(zw=1,Ep.exports=eO()),Ep.exports}var h=tO(),Ap={exports:{}},ve={};/**
10
- * @license React
11
- * react.production.js
12
- *
13
- * Copyright (c) Meta Platforms, Inc. and affiliates.
14
- *
15
- * This source code is licensed under the MIT license found in the
16
- * LICENSE file in the root directory of this source tree.
17
- */var Pw;function nO(){if(Pw)return ve;Pw=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),s=Symbol.for("react.profiler"),o=Symbol.for("react.consumer"),c=Symbol.for("react.context"),d=Symbol.for("react.forward_ref"),f=Symbol.for("react.suspense"),p=Symbol.for("react.memo"),g=Symbol.for("react.lazy"),b=Symbol.for("react.activity"),v=Symbol.iterator;function w(B){return B===null||typeof B!="object"?null:(B=v&&B[v]||B["@@iterator"],typeof B=="function"?B:null)}var _={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},k=Object.assign,I={};function N(B,ee,ae){this.props=B,this.context=ee,this.refs=I,this.updater=ae||_}N.prototype.isReactComponent={},N.prototype.setState=function(B,ee){if(typeof B!="object"&&typeof B!="function"&&B!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,B,ee,"setState")},N.prototype.forceUpdate=function(B){this.updater.enqueueForceUpdate(this,B,"forceUpdate")};function R(){}R.prototype=N.prototype;function M(B,ee,ae){this.props=B,this.context=ee,this.refs=I,this.updater=ae||_}var F=M.prototype=new R;F.constructor=M,k(F,N.prototype),F.isPureReactComponent=!0;var D=Array.isArray;function C(){}var L={H:null,A:null,T:null,S:null},U=Object.prototype.hasOwnProperty;function H(B,ee,ae){var le=ae.ref;return{$$typeof:t,type:B,key:ee,ref:le!==void 0?le:null,props:ae}}function z(B,ee){return H(B.type,ee,B.props)}function q(B){return typeof B=="object"&&B!==null&&B.$$typeof===t}function x(B){var ee={"=":"=0",":":"=2"};return"$"+B.replace(/[=:]/g,function(ae){return ee[ae]})}var E=/\/+/g;function O(B,ee){return typeof B=="object"&&B!==null&&B.key!=null?x(""+B.key):ee.toString(36)}function T(B){switch(B.status){case"fulfilled":return B.value;case"rejected":throw B.reason;default:switch(typeof B.status=="string"?B.then(C,C):(B.status="pending",B.then(function(ee){B.status==="pending"&&(B.status="fulfilled",B.value=ee)},function(ee){B.status==="pending"&&(B.status="rejected",B.reason=ee)})),B.status){case"fulfilled":return B.value;case"rejected":throw B.reason}}throw B}function P(B,ee,ae,le,ye){var je=typeof B;(je==="undefined"||je==="boolean")&&(B=null);var Ve=!1;if(B===null)Ve=!0;else switch(je){case"bigint":case"string":case"number":Ve=!0;break;case"object":switch(B.$$typeof){case t:case e:Ve=!0;break;case g:return Ve=B._init,P(Ve(B._payload),ee,ae,le,ye)}}if(Ve)return ye=ye(B),Ve=le===""?"."+O(B,0):le,D(ye)?(ae="",Ve!=null&&(ae=Ve.replace(E,"$&/")+"/"),P(ye,ee,ae,"",function(bo){return bo})):ye!=null&&(q(ye)&&(ye=z(ye,ae+(ye.key==null||B&&B.key===ye.key?"":(""+ye.key).replace(E,"$&/")+"/")+Ve)),ee.push(ye)),1;Ve=0;var tn=le===""?".":le+":";if(D(B))for(var vt=0;vt<B.length;vt++)le=B[vt],je=tn+O(le,vt),Ve+=P(le,ee,ae,je,ye);else if(vt=w(B),typeof vt=="function")for(B=vt.call(B),vt=0;!(le=B.next()).done;)le=le.value,je=tn+O(le,vt++),Ve+=P(le,ee,ae,je,ye);else if(je==="object"){if(typeof B.then=="function")return P(T(B),ee,ae,le,ye);throw ee=String(B),Error("Objects are not valid as a React child (found: "+(ee==="[object Object]"?"object with keys {"+Object.keys(B).join(", ")+"}":ee)+"). If you meant to render a collection of children, use an array instead.")}return Ve}function $(B,ee,ae){if(B==null)return B;var le=[],ye=0;return P(B,le,"","",function(je){return ee.call(ae,je,ye++)}),le}function K(B){if(B._status===-1){var ee=B._result;ee=ee(),ee.then(function(ae){(B._status===0||B._status===-1)&&(B._status=1,B._result=ae)},function(ae){(B._status===0||B._status===-1)&&(B._status=2,B._result=ae)}),B._status===-1&&(B._status=0,B._result=ee)}if(B._status===1)return B._result.default;throw B._result}var W=typeof reportError=="function"?reportError:function(B){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var ee=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof B=="object"&&B!==null&&typeof B.message=="string"?String(B.message):String(B),error:B});if(!window.dispatchEvent(ee))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",B);return}console.error(B)},se={map:$,forEach:function(B,ee,ae){$(B,function(){ee.apply(this,arguments)},ae)},count:function(B){var ee=0;return $(B,function(){ee++}),ee},toArray:function(B){return $(B,function(ee){return ee})||[]},only:function(B){if(!q(B))throw Error("React.Children.only expected to receive a single React element child.");return B}};return ve.Activity=b,ve.Children=se,ve.Component=N,ve.Fragment=n,ve.Profiler=s,ve.PureComponent=M,ve.StrictMode=r,ve.Suspense=f,ve.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=L,ve.__COMPILER_RUNTIME={__proto__:null,c:function(B){return L.H.useMemoCache(B)}},ve.cache=function(B){return function(){return B.apply(null,arguments)}},ve.cacheSignal=function(){return null},ve.cloneElement=function(B,ee,ae){if(B==null)throw Error("The argument must be a React element, but you passed "+B+".");var le=k({},B.props),ye=B.key;if(ee!=null)for(je in ee.key!==void 0&&(ye=""+ee.key),ee)!U.call(ee,je)||je==="key"||je==="__self"||je==="__source"||je==="ref"&&ee.ref===void 0||(le[je]=ee[je]);var je=arguments.length-2;if(je===1)le.children=ae;else if(1<je){for(var Ve=Array(je),tn=0;tn<je;tn++)Ve[tn]=arguments[tn+2];le.children=Ve}return H(B.type,ye,le)},ve.createContext=function(B){return B={$$typeof:c,_currentValue:B,_currentValue2:B,_threadCount:0,Provider:null,Consumer:null},B.Provider=B,B.Consumer={$$typeof:o,_context:B},B},ve.createElement=function(B,ee,ae){var le,ye={},je=null;if(ee!=null)for(le in ee.key!==void 0&&(je=""+ee.key),ee)U.call(ee,le)&&le!=="key"&&le!=="__self"&&le!=="__source"&&(ye[le]=ee[le]);var Ve=arguments.length-2;if(Ve===1)ye.children=ae;else if(1<Ve){for(var tn=Array(Ve),vt=0;vt<Ve;vt++)tn[vt]=arguments[vt+2];ye.children=tn}if(B&&B.defaultProps)for(le in Ve=B.defaultProps,Ve)ye[le]===void 0&&(ye[le]=Ve[le]);return H(B,je,ye)},ve.createRef=function(){return{current:null}},ve.forwardRef=function(B){return{$$typeof:d,render:B}},ve.isValidElement=q,ve.lazy=function(B){return{$$typeof:g,_payload:{_status:-1,_result:B},_init:K}},ve.memo=function(B,ee){return{$$typeof:p,type:B,compare:ee===void 0?null:ee}},ve.startTransition=function(B){var ee=L.T,ae={};L.T=ae;try{var le=B(),ye=L.S;ye!==null&&ye(ae,le),typeof le=="object"&&le!==null&&typeof le.then=="function"&&le.then(C,W)}catch(je){W(je)}finally{ee!==null&&ae.types!==null&&(ee.types=ae.types),L.T=ee}},ve.unstable_useCacheRefresh=function(){return L.H.useCacheRefresh()},ve.use=function(B){return L.H.use(B)},ve.useActionState=function(B,ee,ae){return L.H.useActionState(B,ee,ae)},ve.useCallback=function(B,ee){return L.H.useCallback(B,ee)},ve.useContext=function(B){return L.H.useContext(B)},ve.useDebugValue=function(){},ve.useDeferredValue=function(B,ee){return L.H.useDeferredValue(B,ee)},ve.useEffect=function(B,ee){return L.H.useEffect(B,ee)},ve.useEffectEvent=function(B){return L.H.useEffectEvent(B)},ve.useId=function(){return L.H.useId()},ve.useImperativeHandle=function(B,ee,ae){return L.H.useImperativeHandle(B,ee,ae)},ve.useInsertionEffect=function(B,ee){return L.H.useInsertionEffect(B,ee)},ve.useLayoutEffect=function(B,ee){return L.H.useLayoutEffect(B,ee)},ve.useMemo=function(B,ee){return L.H.useMemo(B,ee)},ve.useOptimistic=function(B,ee){return L.H.useOptimistic(B,ee)},ve.useReducer=function(B,ee,ae){return L.H.useReducer(B,ee,ae)},ve.useRef=function(B){return L.H.useRef(B)},ve.useState=function(B){return L.H.useState(B)},ve.useSyncExternalStore=function(B,ee,ae){return L.H.useSyncExternalStore(B,ee,ae)},ve.useTransition=function(){return L.H.useTransition()},ve.version="19.2.7",ve}var Vw;function By(){return Vw||(Vw=1,Ap.exports=nO()),Ap.exports}var A=By(),jp={exports:{}},fl={},kp={exports:{}},Cp={};/**
18
- * @license React
19
- * scheduler.production.js
20
- *
21
- * Copyright (c) Meta Platforms, Inc. and affiliates.
22
- *
23
- * This source code is licensed under the MIT license found in the
24
- * LICENSE file in the root directory of this source tree.
25
- */var Hw;function rO(){return Hw||(Hw=1,(function(t){function e(P,$){var K=P.length;P.push($);e:for(;0<K;){var W=K-1>>>1,se=P[W];if(0<s(se,$))P[W]=$,P[K]=se,K=W;else break e}}function n(P){return P.length===0?null:P[0]}function r(P){if(P.length===0)return null;var $=P[0],K=P.pop();if(K!==$){P[0]=K;e:for(var W=0,se=P.length,B=se>>>1;W<B;){var ee=2*(W+1)-1,ae=P[ee],le=ee+1,ye=P[le];if(0>s(ae,K))le<se&&0>s(ye,ae)?(P[W]=ye,P[le]=K,W=le):(P[W]=ae,P[ee]=K,W=ee);else if(le<se&&0>s(ye,K))P[W]=ye,P[le]=K,W=le;else break e}}return $}function s(P,$){var K=P.sortIndex-$.sortIndex;return K!==0?K:P.id-$.id}if(t.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var o=performance;t.unstable_now=function(){return o.now()}}else{var c=Date,d=c.now();t.unstable_now=function(){return c.now()-d}}var f=[],p=[],g=1,b=null,v=3,w=!1,_=!1,k=!1,I=!1,N=typeof setTimeout=="function"?setTimeout:null,R=typeof clearTimeout=="function"?clearTimeout:null,M=typeof setImmediate<"u"?setImmediate:null;function F(P){for(var $=n(p);$!==null;){if($.callback===null)r(p);else if($.startTime<=P)r(p),$.sortIndex=$.expirationTime,e(f,$);else break;$=n(p)}}function D(P){if(k=!1,F(P),!_)if(n(f)!==null)_=!0,C||(C=!0,x());else{var $=n(p);$!==null&&T(D,$.startTime-P)}}var C=!1,L=-1,U=5,H=-1;function z(){return I?!0:!(t.unstable_now()-H<U)}function q(){if(I=!1,C){var P=t.unstable_now();H=P;var $=!0;try{e:{_=!1,k&&(k=!1,R(L),L=-1),w=!0;var K=v;try{t:{for(F(P),b=n(f);b!==null&&!(b.expirationTime>P&&z());){var W=b.callback;if(typeof W=="function"){b.callback=null,v=b.priorityLevel;var se=W(b.expirationTime<=P);if(P=t.unstable_now(),typeof se=="function"){b.callback=se,F(P),$=!0;break t}b===n(f)&&r(f),F(P)}else r(f);b=n(f)}if(b!==null)$=!0;else{var B=n(p);B!==null&&T(D,B.startTime-P),$=!1}}break e}finally{b=null,v=K,w=!1}$=void 0}}finally{$?x():C=!1}}}var x;if(typeof M=="function")x=function(){M(q)};else if(typeof MessageChannel<"u"){var E=new MessageChannel,O=E.port2;E.port1.onmessage=q,x=function(){O.postMessage(null)}}else x=function(){N(q,0)};function T(P,$){L=N(function(){P(t.unstable_now())},$)}t.unstable_IdlePriority=5,t.unstable_ImmediatePriority=1,t.unstable_LowPriority=4,t.unstable_NormalPriority=3,t.unstable_Profiling=null,t.unstable_UserBlockingPriority=2,t.unstable_cancelCallback=function(P){P.callback=null},t.unstable_forceFrameRate=function(P){0>P||125<P?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):U=0<P?Math.floor(1e3/P):5},t.unstable_getCurrentPriorityLevel=function(){return v},t.unstable_next=function(P){switch(v){case 1:case 2:case 3:var $=3;break;default:$=v}var K=v;v=$;try{return P()}finally{v=K}},t.unstable_requestPaint=function(){I=!0},t.unstable_runWithPriority=function(P,$){switch(P){case 1:case 2:case 3:case 4:case 5:break;default:P=3}var K=v;v=P;try{return $()}finally{v=K}},t.unstable_scheduleCallback=function(P,$,K){var W=t.unstable_now();switch(typeof K=="object"&&K!==null?(K=K.delay,K=typeof K=="number"&&0<K?W+K:W):K=W,P){case 1:var se=-1;break;case 2:se=250;break;case 5:se=1073741823;break;case 4:se=1e4;break;default:se=5e3}return se=K+se,P={id:g++,callback:$,priorityLevel:P,startTime:K,expirationTime:se,sortIndex:-1},K>W?(P.sortIndex=K,e(p,P),n(f)===null&&P===n(p)&&(k?(R(L),L=-1):k=!0,T(D,K-W))):(P.sortIndex=se,e(f,P),_||w||(_=!0,C||(C=!0,x()))),P},t.unstable_shouldYield=z,t.unstable_wrapCallback=function(P){var $=v;return function(){var K=v;v=$;try{return P.apply(this,arguments)}finally{v=K}}}})(Cp)),Cp}var Gw;function sO(){return Gw||(Gw=1,kp.exports=rO()),kp.exports}var Np={exports:{}},Kt={};/**
26
- * @license React
27
- * react-dom.production.js
28
- *
29
- * Copyright (c) Meta Platforms, Inc. and affiliates.
30
- *
31
- * This source code is licensed under the MIT license found in the
32
- * LICENSE file in the root directory of this source tree.
33
- */var Kw;function iO(){if(Kw)return Kt;Kw=1;var t=By();function e(f){var p="https://react.dev/errors/"+f;if(1<arguments.length){p+="?args[]="+encodeURIComponent(arguments[1]);for(var g=2;g<arguments.length;g++)p+="&args[]="+encodeURIComponent(arguments[g])}return"Minified React error #"+f+"; visit "+p+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function n(){}var r={d:{f:n,r:function(){throw Error(e(522))},D:n,C:n,L:n,m:n,X:n,S:n,M:n},p:0,findDOMNode:null},s=Symbol.for("react.portal");function o(f,p,g){var b=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:s,key:b==null?null:""+b,children:f,containerInfo:p,implementation:g}}var c=t.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function d(f,p){if(f==="font")return"";if(typeof p=="string")return p==="use-credentials"?p:""}return Kt.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=r,Kt.createPortal=function(f,p){var g=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!p||p.nodeType!==1&&p.nodeType!==9&&p.nodeType!==11)throw Error(e(299));return o(f,p,null,g)},Kt.flushSync=function(f){var p=c.T,g=r.p;try{if(c.T=null,r.p=2,f)return f()}finally{c.T=p,r.p=g,r.d.f()}},Kt.preconnect=function(f,p){typeof f=="string"&&(p?(p=p.crossOrigin,p=typeof p=="string"?p==="use-credentials"?p:"":void 0):p=null,r.d.C(f,p))},Kt.prefetchDNS=function(f){typeof f=="string"&&r.d.D(f)},Kt.preinit=function(f,p){if(typeof f=="string"&&p&&typeof p.as=="string"){var g=p.as,b=d(g,p.crossOrigin),v=typeof p.integrity=="string"?p.integrity:void 0,w=typeof p.fetchPriority=="string"?p.fetchPriority:void 0;g==="style"?r.d.S(f,typeof p.precedence=="string"?p.precedence:void 0,{crossOrigin:b,integrity:v,fetchPriority:w}):g==="script"&&r.d.X(f,{crossOrigin:b,integrity:v,fetchPriority:w,nonce:typeof p.nonce=="string"?p.nonce:void 0})}},Kt.preinitModule=function(f,p){if(typeof f=="string")if(typeof p=="object"&&p!==null){if(p.as==null||p.as==="script"){var g=d(p.as,p.crossOrigin);r.d.M(f,{crossOrigin:g,integrity:typeof p.integrity=="string"?p.integrity:void 0,nonce:typeof p.nonce=="string"?p.nonce:void 0})}}else p==null&&r.d.M(f)},Kt.preload=function(f,p){if(typeof f=="string"&&typeof p=="object"&&p!==null&&typeof p.as=="string"){var g=p.as,b=d(g,p.crossOrigin);r.d.L(f,g,{crossOrigin:b,integrity:typeof p.integrity=="string"?p.integrity:void 0,nonce:typeof p.nonce=="string"?p.nonce:void 0,type:typeof p.type=="string"?p.type:void 0,fetchPriority:typeof p.fetchPriority=="string"?p.fetchPriority:void 0,referrerPolicy:typeof p.referrerPolicy=="string"?p.referrerPolicy:void 0,imageSrcSet:typeof p.imageSrcSet=="string"?p.imageSrcSet:void 0,imageSizes:typeof p.imageSizes=="string"?p.imageSizes:void 0,media:typeof p.media=="string"?p.media:void 0})}},Kt.preloadModule=function(f,p){if(typeof f=="string")if(p){var g=d(p.as,p.crossOrigin);r.d.m(f,{as:typeof p.as=="string"&&p.as!=="script"?p.as:void 0,crossOrigin:g,integrity:typeof p.integrity=="string"?p.integrity:void 0})}else r.d.m(f)},Kt.requestFormReset=function(f){r.d.r(f)},Kt.unstable_batchedUpdates=function(f,p){return f(p)},Kt.useFormState=function(f,p,g){return c.H.useFormState(f,p,g)},Kt.useFormStatus=function(){return c.H.useHostTransitionStatus()},Kt.version="19.2.7",Kt}var Yw;function h1(){if(Yw)return Np.exports;Yw=1;function t(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(t)}catch(e){console.error(e)}}return t(),Np.exports=iO(),Np.exports}/**
34
- * @license React
35
- * react-dom-client.production.js
36
- *
37
- * Copyright (c) Meta Platforms, Inc. and affiliates.
38
- *
39
- * This source code is licensed under the MIT license found in the
40
- * LICENSE file in the root directory of this source tree.
41
- */var Zw;function aO(){if(Zw)return fl;Zw=1;var t=sO(),e=By(),n=h1();function r(i){var a="https://react.dev/errors/"+i;if(1<arguments.length){a+="?args[]="+encodeURIComponent(arguments[1]);for(var l=2;l<arguments.length;l++)a+="&args[]="+encodeURIComponent(arguments[l])}return"Minified React error #"+i+"; visit "+a+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function s(i){return!(!i||i.nodeType!==1&&i.nodeType!==9&&i.nodeType!==11)}function o(i){var a=i,l=i;if(i.alternate)for(;a.return;)a=a.return;else{i=a;do a=i,(a.flags&4098)!==0&&(l=a.return),i=a.return;while(i)}return a.tag===3?l:null}function c(i){if(i.tag===13){var a=i.memoizedState;if(a===null&&(i=i.alternate,i!==null&&(a=i.memoizedState)),a!==null)return a.dehydrated}return null}function d(i){if(i.tag===31){var a=i.memoizedState;if(a===null&&(i=i.alternate,i!==null&&(a=i.memoizedState)),a!==null)return a.dehydrated}return null}function f(i){if(o(i)!==i)throw Error(r(188))}function p(i){var a=i.alternate;if(!a){if(a=o(i),a===null)throw Error(r(188));return a!==i?null:i}for(var l=i,u=a;;){var m=l.return;if(m===null)break;var y=m.alternate;if(y===null){if(u=m.return,u!==null){l=u;continue}break}if(m.child===y.child){for(y=m.child;y;){if(y===l)return f(m),i;if(y===u)return f(m),a;y=y.sibling}throw Error(r(188))}if(l.return!==u.return)l=m,u=y;else{for(var S=!1,j=m.child;j;){if(j===l){S=!0,l=m,u=y;break}if(j===u){S=!0,u=m,l=y;break}j=j.sibling}if(!S){for(j=y.child;j;){if(j===l){S=!0,l=y,u=m;break}if(j===u){S=!0,u=y,l=m;break}j=j.sibling}if(!S)throw Error(r(189))}}if(l.alternate!==u)throw Error(r(190))}if(l.tag!==3)throw Error(r(188));return l.stateNode.current===l?i:a}function g(i){var a=i.tag;if(a===5||a===26||a===27||a===6)return i;for(i=i.child;i!==null;){if(a=g(i),a!==null)return a;i=i.sibling}return null}var b=Object.assign,v=Symbol.for("react.element"),w=Symbol.for("react.transitional.element"),_=Symbol.for("react.portal"),k=Symbol.for("react.fragment"),I=Symbol.for("react.strict_mode"),N=Symbol.for("react.profiler"),R=Symbol.for("react.consumer"),M=Symbol.for("react.context"),F=Symbol.for("react.forward_ref"),D=Symbol.for("react.suspense"),C=Symbol.for("react.suspense_list"),L=Symbol.for("react.memo"),U=Symbol.for("react.lazy"),H=Symbol.for("react.activity"),z=Symbol.for("react.memo_cache_sentinel"),q=Symbol.iterator;function x(i){return i===null||typeof i!="object"?null:(i=q&&i[q]||i["@@iterator"],typeof i=="function"?i:null)}var E=Symbol.for("react.client.reference");function O(i){if(i==null)return null;if(typeof i=="function")return i.$$typeof===E?null:i.displayName||i.name||null;if(typeof i=="string")return i;switch(i){case k:return"Fragment";case N:return"Profiler";case I:return"StrictMode";case D:return"Suspense";case C:return"SuspenseList";case H:return"Activity"}if(typeof i=="object")switch(i.$$typeof){case _:return"Portal";case M:return i.displayName||"Context";case R:return(i._context.displayName||"Context")+".Consumer";case F:var a=i.render;return i=i.displayName,i||(i=a.displayName||a.name||"",i=i!==""?"ForwardRef("+i+")":"ForwardRef"),i;case L:return a=i.displayName||null,a!==null?a:O(i.type)||"Memo";case U:a=i._payload,i=i._init;try{return O(i(a))}catch{}}return null}var T=Array.isArray,P=e.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,$=n.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,K={pending:!1,data:null,method:null,action:null},W=[],se=-1;function B(i){return{current:i}}function ee(i){0>se||(i.current=W[se],W[se]=null,se--)}function ae(i,a){se++,W[se]=i.current,i.current=a}var le=B(null),ye=B(null),je=B(null),Ve=B(null);function tn(i,a){switch(ae(je,a),ae(ye,i),ae(le,null),a.nodeType){case 9:case 11:i=(i=a.documentElement)&&(i=i.namespaceURI)?uw(i):0;break;default:if(i=a.tagName,a=a.namespaceURI)a=uw(a),i=dw(a,i);else switch(i){case"svg":i=1;break;case"math":i=2;break;default:i=0}}ee(le),ae(le,i)}function vt(){ee(le),ee(ye),ee(je)}function bo(i){i.memoizedState!==null&&ae(Ve,i);var a=le.current,l=dw(a,i.type);a!==l&&(ae(ye,i),ae(le,l))}function ic(i){ye.current===i&&(ee(le),ee(ye)),Ve.current===i&&(ee(Ve),ol._currentValue=K)}var af,qg;function ii(i){if(af===void 0)try{throw Error()}catch(l){var a=l.stack.trim().match(/\n( *(at )?)/);af=a&&a[1]||"",qg=-1<l.stack.indexOf(`
42
- at`)?" (<anonymous>)":-1<l.stack.indexOf("@")?"@unknown:0:0":""}return`
43
- `+af+i+qg}var of=!1;function lf(i,a){if(!i||of)return"";of=!0;var l=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var u={DetermineComponentFrameRoot:function(){try{if(a){var ie=function(){throw Error()};if(Object.defineProperty(ie.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(ie,[])}catch(te){var X=te}Reflect.construct(i,[],ie)}else{try{ie.call()}catch(te){X=te}i.call(ie.prototype)}}else{try{throw Error()}catch(te){X=te}(ie=i())&&typeof ie.catch=="function"&&ie.catch(function(){})}}catch(te){if(te&&X&&typeof te.stack=="string")return[te.stack,X.stack]}return[null,null]}};u.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var m=Object.getOwnPropertyDescriptor(u.DetermineComponentFrameRoot,"name");m&&m.configurable&&Object.defineProperty(u.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var y=u.DetermineComponentFrameRoot(),S=y[0],j=y[1];if(S&&j){var V=S.split(`
44
- `),J=j.split(`
45
- `);for(m=u=0;u<V.length&&!V[u].includes("DetermineComponentFrameRoot");)u++;for(;m<J.length&&!J[m].includes("DetermineComponentFrameRoot");)m++;if(u===V.length||m===J.length)for(u=V.length-1,m=J.length-1;1<=u&&0<=m&&V[u]!==J[m];)m--;for(;1<=u&&0<=m;u--,m--)if(V[u]!==J[m]){if(u!==1||m!==1)do if(u--,m--,0>m||V[u]!==J[m]){var ne=`
46
- `+V[u].replace(" at new "," at ");return i.displayName&&ne.includes("<anonymous>")&&(ne=ne.replace("<anonymous>",i.displayName)),ne}while(1<=u&&0<=m);break}}}finally{of=!1,Error.prepareStackTrace=l}return(l=i?i.displayName||i.name:"")?ii(l):""}function Ck(i,a){switch(i.tag){case 26:case 27:case 5:return ii(i.type);case 16:return ii("Lazy");case 13:return i.child!==a&&a!==null?ii("Suspense Fallback"):ii("Suspense");case 19:return ii("SuspenseList");case 0:case 15:return lf(i.type,!1);case 11:return lf(i.type.render,!1);case 1:return lf(i.type,!0);case 31:return ii("Activity");default:return""}}function Fg(i){try{var a="",l=null;do a+=Ck(i,l),l=i,i=i.return;while(i);return a}catch(u){return`
47
- Error generating stack: `+u.message+`
48
- `+u.stack}}var cf=Object.prototype.hasOwnProperty,uf=t.unstable_scheduleCallback,df=t.unstable_cancelCallback,Nk=t.unstable_shouldYield,Ok=t.unstable_requestPaint,_n=t.unstable_now,Rk=t.unstable_getCurrentPriorityLevel,zg=t.unstable_ImmediatePriority,Pg=t.unstable_UserBlockingPriority,ac=t.unstable_NormalPriority,Tk=t.unstable_LowPriority,Vg=t.unstable_IdlePriority,Dk=t.log,Ik=t.unstable_setDisableYieldValue,vo=null,En=null;function ds(i){if(typeof Dk=="function"&&Ik(i),En&&typeof En.setStrictMode=="function")try{En.setStrictMode(vo,i)}catch{}}var An=Math.clz32?Math.clz32:Uk,Mk=Math.log,Lk=Math.LN2;function Uk(i){return i>>>=0,i===0?32:31-(Mk(i)/Lk|0)|0}var oc=256,lc=262144,cc=4194304;function ai(i){var a=i&42;if(a!==0)return a;switch(i&-i){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return i&261888;case 262144:case 524288:case 1048576:case 2097152:return i&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return i&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return i}}function uc(i,a,l){var u=i.pendingLanes;if(u===0)return 0;var m=0,y=i.suspendedLanes,S=i.pingedLanes;i=i.warmLanes;var j=u&134217727;return j!==0?(u=j&~y,u!==0?m=ai(u):(S&=j,S!==0?m=ai(S):l||(l=j&~i,l!==0&&(m=ai(l))))):(j=u&~y,j!==0?m=ai(j):S!==0?m=ai(S):l||(l=u&~i,l!==0&&(m=ai(l)))),m===0?0:a!==0&&a!==m&&(a&y)===0&&(y=m&-m,l=a&-a,y>=l||y===32&&(l&4194048)!==0)?a:m}function wo(i,a){return(i.pendingLanes&~(i.suspendedLanes&~i.pingedLanes)&a)===0}function $k(i,a){switch(i){case 1:case 2:case 4:case 8:case 64:return a+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function Hg(){var i=cc;return cc<<=1,(cc&62914560)===0&&(cc=4194304),i}function ff(i){for(var a=[],l=0;31>l;l++)a.push(i);return a}function xo(i,a){i.pendingLanes|=a,a!==268435456&&(i.suspendedLanes=0,i.pingedLanes=0,i.warmLanes=0)}function Bk(i,a,l,u,m,y){var S=i.pendingLanes;i.pendingLanes=l,i.suspendedLanes=0,i.pingedLanes=0,i.warmLanes=0,i.expiredLanes&=l,i.entangledLanes&=l,i.errorRecoveryDisabledLanes&=l,i.shellSuspendCounter=0;var j=i.entanglements,V=i.expirationTimes,J=i.hiddenUpdates;for(l=S&~l;0<l;){var ne=31-An(l),ie=1<<ne;j[ne]=0,V[ne]=-1;var X=J[ne];if(X!==null)for(J[ne]=null,ne=0;ne<X.length;ne++){var te=X[ne];te!==null&&(te.lane&=-536870913)}l&=~ie}u!==0&&Gg(i,u,0),y!==0&&m===0&&i.tag!==0&&(i.suspendedLanes|=y&~(S&~a))}function Gg(i,a,l){i.pendingLanes|=a,i.suspendedLanes&=~a;var u=31-An(a);i.entangledLanes|=a,i.entanglements[u]=i.entanglements[u]|1073741824|l&261930}function Kg(i,a){var l=i.entangledLanes|=a;for(i=i.entanglements;l;){var u=31-An(l),m=1<<u;m&a|i[u]&a&&(i[u]|=a),l&=~m}}function Yg(i,a){var l=a&-a;return l=(l&42)!==0?1:hf(l),(l&(i.suspendedLanes|a))!==0?0:l}function hf(i){switch(i){case 2:i=1;break;case 8:i=4;break;case 32:i=16;break;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:i=128;break;case 268435456:i=134217728;break;default:i=0}return i}function pf(i){return i&=-i,2<i?8<i?(i&134217727)!==0?32:268435456:8:2}function Zg(){var i=$.p;return i!==0?i:(i=window.event,i===void 0?32:Iw(i.type))}function Wg(i,a){var l=$.p;try{return $.p=i,a()}finally{$.p=l}}var fs=Math.random().toString(36).slice(2),Ut="__reactFiber$"+fs,dn="__reactProps$"+fs,ea="__reactContainer$"+fs,mf="__reactEvents$"+fs,qk="__reactListeners$"+fs,Fk="__reactHandles$"+fs,Qg="__reactResources$"+fs,So="__reactMarker$"+fs;function yf(i){delete i[Ut],delete i[dn],delete i[mf],delete i[qk],delete i[Fk]}function ta(i){var a=i[Ut];if(a)return a;for(var l=i.parentNode;l;){if(a=l[ea]||l[Ut]){if(l=a.alternate,a.child!==null||l!==null&&l.child!==null)for(i=bw(i);i!==null;){if(l=i[Ut])return l;i=bw(i)}return a}i=l,l=i.parentNode}return null}function na(i){if(i=i[Ut]||i[ea]){var a=i.tag;if(a===5||a===6||a===13||a===31||a===26||a===27||a===3)return i}return null}function _o(i){var a=i.tag;if(a===5||a===26||a===27||a===6)return i.stateNode;throw Error(r(33))}function ra(i){var a=i[Qg];return a||(a=i[Qg]={hoistableStyles:new Map,hoistableScripts:new Map}),a}function Dt(i){i[So]=!0}var Jg=new Set,Xg={};function oi(i,a){sa(i,a),sa(i+"Capture",a)}function sa(i,a){for(Xg[i]=a,i=0;i<a.length;i++)Jg.add(a[i])}var zk=RegExp("^[:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD][:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$"),eb={},tb={};function Pk(i){return cf.call(tb,i)?!0:cf.call(eb,i)?!1:zk.test(i)?tb[i]=!0:(eb[i]=!0,!1)}function dc(i,a,l){if(Pk(a))if(l===null)i.removeAttribute(a);else{switch(typeof l){case"undefined":case"function":case"symbol":i.removeAttribute(a);return;case"boolean":var u=a.toLowerCase().slice(0,5);if(u!=="data-"&&u!=="aria-"){i.removeAttribute(a);return}}i.setAttribute(a,""+l)}}function fc(i,a,l){if(l===null)i.removeAttribute(a);else{switch(typeof l){case"undefined":case"function":case"symbol":case"boolean":i.removeAttribute(a);return}i.setAttribute(a,""+l)}}function Dr(i,a,l,u){if(u===null)i.removeAttribute(l);else{switch(typeof u){case"undefined":case"function":case"symbol":case"boolean":i.removeAttribute(l);return}i.setAttributeNS(a,l,""+u)}}function Bn(i){switch(typeof i){case"bigint":case"boolean":case"number":case"string":case"undefined":return i;case"object":return i;default:return""}}function nb(i){var a=i.type;return(i=i.nodeName)&&i.toLowerCase()==="input"&&(a==="checkbox"||a==="radio")}function Vk(i,a,l){var u=Object.getOwnPropertyDescriptor(i.constructor.prototype,a);if(!i.hasOwnProperty(a)&&typeof u<"u"&&typeof u.get=="function"&&typeof u.set=="function"){var m=u.get,y=u.set;return Object.defineProperty(i,a,{configurable:!0,get:function(){return m.call(this)},set:function(S){l=""+S,y.call(this,S)}}),Object.defineProperty(i,a,{enumerable:u.enumerable}),{getValue:function(){return l},setValue:function(S){l=""+S},stopTracking:function(){i._valueTracker=null,delete i[a]}}}}function gf(i){if(!i._valueTracker){var a=nb(i)?"checked":"value";i._valueTracker=Vk(i,a,""+i[a])}}function rb(i){if(!i)return!1;var a=i._valueTracker;if(!a)return!0;var l=a.getValue(),u="";return i&&(u=nb(i)?i.checked?"true":"false":i.value),i=u,i!==l?(a.setValue(i),!0):!1}function hc(i){if(i=i||(typeof document<"u"?document:void 0),typeof i>"u")return null;try{return i.activeElement||i.body}catch{return i.body}}var Hk=/[\n"\\]/g;function qn(i){return i.replace(Hk,function(a){return"\\"+a.charCodeAt(0).toString(16)+" "})}function bf(i,a,l,u,m,y,S,j){i.name="",S!=null&&typeof S!="function"&&typeof S!="symbol"&&typeof S!="boolean"?i.type=S:i.removeAttribute("type"),a!=null?S==="number"?(a===0&&i.value===""||i.value!=a)&&(i.value=""+Bn(a)):i.value!==""+Bn(a)&&(i.value=""+Bn(a)):S!=="submit"&&S!=="reset"||i.removeAttribute("value"),a!=null?vf(i,S,Bn(a)):l!=null?vf(i,S,Bn(l)):u!=null&&i.removeAttribute("value"),m==null&&y!=null&&(i.defaultChecked=!!y),m!=null&&(i.checked=m&&typeof m!="function"&&typeof m!="symbol"),j!=null&&typeof j!="function"&&typeof j!="symbol"&&typeof j!="boolean"?i.name=""+Bn(j):i.removeAttribute("name")}function sb(i,a,l,u,m,y,S,j){if(y!=null&&typeof y!="function"&&typeof y!="symbol"&&typeof y!="boolean"&&(i.type=y),a!=null||l!=null){if(!(y!=="submit"&&y!=="reset"||a!=null)){gf(i);return}l=l!=null?""+Bn(l):"",a=a!=null?""+Bn(a):l,j||a===i.value||(i.value=a),i.defaultValue=a}u=u??m,u=typeof u!="function"&&typeof u!="symbol"&&!!u,i.checked=j?i.checked:!!u,i.defaultChecked=!!u,S!=null&&typeof S!="function"&&typeof S!="symbol"&&typeof S!="boolean"&&(i.name=S),gf(i)}function vf(i,a,l){a==="number"&&hc(i.ownerDocument)===i||i.defaultValue===""+l||(i.defaultValue=""+l)}function ia(i,a,l,u){if(i=i.options,a){a={};for(var m=0;m<l.length;m++)a["$"+l[m]]=!0;for(l=0;l<i.length;l++)m=a.hasOwnProperty("$"+i[l].value),i[l].selected!==m&&(i[l].selected=m),m&&u&&(i[l].defaultSelected=!0)}else{for(l=""+Bn(l),a=null,m=0;m<i.length;m++){if(i[m].value===l){i[m].selected=!0,u&&(i[m].defaultSelected=!0);return}a!==null||i[m].disabled||(a=i[m])}a!==null&&(a.selected=!0)}}function ib(i,a,l){if(a!=null&&(a=""+Bn(a),a!==i.value&&(i.value=a),l==null)){i.defaultValue!==a&&(i.defaultValue=a);return}i.defaultValue=l!=null?""+Bn(l):""}function ab(i,a,l,u){if(a==null){if(u!=null){if(l!=null)throw Error(r(92));if(T(u)){if(1<u.length)throw Error(r(93));u=u[0]}l=u}l==null&&(l=""),a=l}l=Bn(a),i.defaultValue=l,u=i.textContent,u===l&&u!==""&&u!==null&&(i.value=u),gf(i)}function aa(i,a){if(a){var l=i.firstChild;if(l&&l===i.lastChild&&l.nodeType===3){l.nodeValue=a;return}}i.textContent=a}var Gk=new Set("animationIterationCount aspectRatio borderImageOutset borderImageSlice borderImageWidth boxFlex boxFlexGroup boxOrdinalGroup columnCount columns flex flexGrow flexPositive flexShrink flexNegative flexOrder gridArea gridRow gridRowEnd gridRowSpan gridRowStart gridColumn gridColumnEnd gridColumnSpan gridColumnStart fontWeight lineClamp lineHeight opacity order orphans scale tabSize widows zIndex zoom fillOpacity floodOpacity stopOpacity strokeDasharray strokeDashoffset strokeMiterlimit strokeOpacity strokeWidth MozAnimationIterationCount MozBoxFlex MozBoxFlexGroup MozLineClamp msAnimationIterationCount msFlex msZoom msFlexGrow msFlexNegative msFlexOrder msFlexPositive msFlexShrink msGridColumn msGridColumnSpan msGridRow msGridRowSpan WebkitAnimationIterationCount WebkitBoxFlex WebKitBoxFlexGroup WebkitBoxOrdinalGroup WebkitColumnCount WebkitColumns WebkitFlex WebkitFlexGrow WebkitFlexPositive WebkitFlexShrink WebkitLineClamp".split(" "));function ob(i,a,l){var u=a.indexOf("--")===0;l==null||typeof l=="boolean"||l===""?u?i.setProperty(a,""):a==="float"?i.cssFloat="":i[a]="":u?i.setProperty(a,l):typeof l!="number"||l===0||Gk.has(a)?a==="float"?i.cssFloat=l:i[a]=(""+l).trim():i[a]=l+"px"}function lb(i,a,l){if(a!=null&&typeof a!="object")throw Error(r(62));if(i=i.style,l!=null){for(var u in l)!l.hasOwnProperty(u)||a!=null&&a.hasOwnProperty(u)||(u.indexOf("--")===0?i.setProperty(u,""):u==="float"?i.cssFloat="":i[u]="");for(var m in a)u=a[m],a.hasOwnProperty(m)&&l[m]!==u&&ob(i,m,u)}else for(var y in a)a.hasOwnProperty(y)&&ob(i,y,a[y])}function wf(i){if(i.indexOf("-")===-1)return!1;switch(i){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var Kk=new Map([["acceptCharset","accept-charset"],["htmlFor","for"],["httpEquiv","http-equiv"],["crossOrigin","crossorigin"],["accentHeight","accent-height"],["alignmentBaseline","alignment-baseline"],["arabicForm","arabic-form"],["baselineShift","baseline-shift"],["capHeight","cap-height"],["clipPath","clip-path"],["clipRule","clip-rule"],["colorInterpolation","color-interpolation"],["colorInterpolationFilters","color-interpolation-filters"],["colorProfile","color-profile"],["colorRendering","color-rendering"],["dominantBaseline","dominant-baseline"],["enableBackground","enable-background"],["fillOpacity","fill-opacity"],["fillRule","fill-rule"],["floodColor","flood-color"],["floodOpacity","flood-opacity"],["fontFamily","font-family"],["fontSize","font-size"],["fontSizeAdjust","font-size-adjust"],["fontStretch","font-stretch"],["fontStyle","font-style"],["fontVariant","font-variant"],["fontWeight","font-weight"],["glyphName","glyph-name"],["glyphOrientationHorizontal","glyph-orientation-horizontal"],["glyphOrientationVertical","glyph-orientation-vertical"],["horizAdvX","horiz-adv-x"],["horizOriginX","horiz-origin-x"],["imageRendering","image-rendering"],["letterSpacing","letter-spacing"],["lightingColor","lighting-color"],["markerEnd","marker-end"],["markerMid","marker-mid"],["markerStart","marker-start"],["overlinePosition","overline-position"],["overlineThickness","overline-thickness"],["paintOrder","paint-order"],["panose-1","panose-1"],["pointerEvents","pointer-events"],["renderingIntent","rendering-intent"],["shapeRendering","shape-rendering"],["stopColor","stop-color"],["stopOpacity","stop-opacity"],["strikethroughPosition","strikethrough-position"],["strikethroughThickness","strikethrough-thickness"],["strokeDasharray","stroke-dasharray"],["strokeDashoffset","stroke-dashoffset"],["strokeLinecap","stroke-linecap"],["strokeLinejoin","stroke-linejoin"],["strokeMiterlimit","stroke-miterlimit"],["strokeOpacity","stroke-opacity"],["strokeWidth","stroke-width"],["textAnchor","text-anchor"],["textDecoration","text-decoration"],["textRendering","text-rendering"],["transformOrigin","transform-origin"],["underlinePosition","underline-position"],["underlineThickness","underline-thickness"],["unicodeBidi","unicode-bidi"],["unicodeRange","unicode-range"],["unitsPerEm","units-per-em"],["vAlphabetic","v-alphabetic"],["vHanging","v-hanging"],["vIdeographic","v-ideographic"],["vMathematical","v-mathematical"],["vectorEffect","vector-effect"],["vertAdvY","vert-adv-y"],["vertOriginX","vert-origin-x"],["vertOriginY","vert-origin-y"],["wordSpacing","word-spacing"],["writingMode","writing-mode"],["xmlnsXlink","xmlns:xlink"],["xHeight","x-height"]]),Yk=/^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*:/i;function pc(i){return Yk.test(""+i)?"javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')":i}function Ir(){}var xf=null;function Sf(i){return i=i.target||i.srcElement||window,i.correspondingUseElement&&(i=i.correspondingUseElement),i.nodeType===3?i.parentNode:i}var oa=null,la=null;function cb(i){var a=na(i);if(a&&(i=a.stateNode)){var l=i[dn]||null;e:switch(i=a.stateNode,a.type){case"input":if(bf(i,l.value,l.defaultValue,l.defaultValue,l.checked,l.defaultChecked,l.type,l.name),a=l.name,l.type==="radio"&&a!=null){for(l=i;l.parentNode;)l=l.parentNode;for(l=l.querySelectorAll('input[name="'+qn(""+a)+'"][type="radio"]'),a=0;a<l.length;a++){var u=l[a];if(u!==i&&u.form===i.form){var m=u[dn]||null;if(!m)throw Error(r(90));bf(u,m.value,m.defaultValue,m.defaultValue,m.checked,m.defaultChecked,m.type,m.name)}}for(a=0;a<l.length;a++)u=l[a],u.form===i.form&&rb(u)}break e;case"textarea":ib(i,l.value,l.defaultValue);break e;case"select":a=l.value,a!=null&&ia(i,!!l.multiple,a,!1)}}}var _f=!1;function ub(i,a,l){if(_f)return i(a,l);_f=!0;try{var u=i(a);return u}finally{if(_f=!1,(oa!==null||la!==null)&&(tu(),oa&&(a=oa,i=la,la=oa=null,cb(a),i)))for(a=0;a<i.length;a++)cb(i[a])}}function Eo(i,a){var l=i.stateNode;if(l===null)return null;var u=l[dn]||null;if(u===null)return null;l=u[a];e:switch(a){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(u=!u.disabled)||(i=i.type,u=!(i==="button"||i==="input"||i==="select"||i==="textarea")),i=!u;break e;default:i=!1}if(i)return null;if(l&&typeof l!="function")throw Error(r(231,a,typeof l));return l}var Mr=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Ef=!1;if(Mr)try{var Ao={};Object.defineProperty(Ao,"passive",{get:function(){Ef=!0}}),window.addEventListener("test",Ao,Ao),window.removeEventListener("test",Ao,Ao)}catch{Ef=!1}var hs=null,Af=null,mc=null;function db(){if(mc)return mc;var i,a=Af,l=a.length,u,m="value"in hs?hs.value:hs.textContent,y=m.length;for(i=0;i<l&&a[i]===m[i];i++);var S=l-i;for(u=1;u<=S&&a[l-u]===m[y-u];u++);return mc=m.slice(i,1<u?1-u:void 0)}function yc(i){var a=i.keyCode;return"charCode"in i?(i=i.charCode,i===0&&a===13&&(i=13)):i=a,i===10&&(i=13),32<=i||i===13?i:0}function gc(){return!0}function fb(){return!1}function fn(i){function a(l,u,m,y,S){this._reactName=l,this._targetInst=m,this.type=u,this.nativeEvent=y,this.target=S,this.currentTarget=null;for(var j in i)i.hasOwnProperty(j)&&(l=i[j],this[j]=l?l(y):y[j]);return this.isDefaultPrevented=(y.defaultPrevented!=null?y.defaultPrevented:y.returnValue===!1)?gc:fb,this.isPropagationStopped=fb,this}return b(a.prototype,{preventDefault:function(){this.defaultPrevented=!0;var l=this.nativeEvent;l&&(l.preventDefault?l.preventDefault():typeof l.returnValue!="unknown"&&(l.returnValue=!1),this.isDefaultPrevented=gc)},stopPropagation:function(){var l=this.nativeEvent;l&&(l.stopPropagation?l.stopPropagation():typeof l.cancelBubble!="unknown"&&(l.cancelBubble=!0),this.isPropagationStopped=gc)},persist:function(){},isPersistent:gc}),a}var li={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(i){return i.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},bc=fn(li),jo=b({},li,{view:0,detail:0}),Zk=fn(jo),jf,kf,ko,vc=b({},jo,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:Nf,button:0,buttons:0,relatedTarget:function(i){return i.relatedTarget===void 0?i.fromElement===i.srcElement?i.toElement:i.fromElement:i.relatedTarget},movementX:function(i){return"movementX"in i?i.movementX:(i!==ko&&(ko&&i.type==="mousemove"?(jf=i.screenX-ko.screenX,kf=i.screenY-ko.screenY):kf=jf=0,ko=i),jf)},movementY:function(i){return"movementY"in i?i.movementY:kf}}),hb=fn(vc),Wk=b({},vc,{dataTransfer:0}),Qk=fn(Wk),Jk=b({},jo,{relatedTarget:0}),Cf=fn(Jk),Xk=b({},li,{animationName:0,elapsedTime:0,pseudoElement:0}),eC=fn(Xk),tC=b({},li,{clipboardData:function(i){return"clipboardData"in i?i.clipboardData:window.clipboardData}}),nC=fn(tC),rC=b({},li,{data:0}),pb=fn(rC),sC={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},iC={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},aC={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function oC(i){var a=this.nativeEvent;return a.getModifierState?a.getModifierState(i):(i=aC[i])?!!a[i]:!1}function Nf(){return oC}var lC=b({},jo,{key:function(i){if(i.key){var a=sC[i.key]||i.key;if(a!=="Unidentified")return a}return i.type==="keypress"?(i=yc(i),i===13?"Enter":String.fromCharCode(i)):i.type==="keydown"||i.type==="keyup"?iC[i.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:Nf,charCode:function(i){return i.type==="keypress"?yc(i):0},keyCode:function(i){return i.type==="keydown"||i.type==="keyup"?i.keyCode:0},which:function(i){return i.type==="keypress"?yc(i):i.type==="keydown"||i.type==="keyup"?i.keyCode:0}}),cC=fn(lC),uC=b({},vc,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),mb=fn(uC),dC=b({},jo,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:Nf}),fC=fn(dC),hC=b({},li,{propertyName:0,elapsedTime:0,pseudoElement:0}),pC=fn(hC),mC=b({},vc,{deltaX:function(i){return"deltaX"in i?i.deltaX:"wheelDeltaX"in i?-i.wheelDeltaX:0},deltaY:function(i){return"deltaY"in i?i.deltaY:"wheelDeltaY"in i?-i.wheelDeltaY:"wheelDelta"in i?-i.wheelDelta:0},deltaZ:0,deltaMode:0}),yC=fn(mC),gC=b({},li,{newState:0,oldState:0}),bC=fn(gC),vC=[9,13,27,32],Of=Mr&&"CompositionEvent"in window,Co=null;Mr&&"documentMode"in document&&(Co=document.documentMode);var wC=Mr&&"TextEvent"in window&&!Co,yb=Mr&&(!Of||Co&&8<Co&&11>=Co),gb=" ",bb=!1;function vb(i,a){switch(i){case"keyup":return vC.indexOf(a.keyCode)!==-1;case"keydown":return a.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function wb(i){return i=i.detail,typeof i=="object"&&"data"in i?i.data:null}var ca=!1;function xC(i,a){switch(i){case"compositionend":return wb(a);case"keypress":return a.which!==32?null:(bb=!0,gb);case"textInput":return i=a.data,i===gb&&bb?null:i;default:return null}}function SC(i,a){if(ca)return i==="compositionend"||!Of&&vb(i,a)?(i=db(),mc=Af=hs=null,ca=!1,i):null;switch(i){case"paste":return null;case"keypress":if(!(a.ctrlKey||a.altKey||a.metaKey)||a.ctrlKey&&a.altKey){if(a.char&&1<a.char.length)return a.char;if(a.which)return String.fromCharCode(a.which)}return null;case"compositionend":return yb&&a.locale!=="ko"?null:a.data;default:return null}}var _C={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function xb(i){var a=i&&i.nodeName&&i.nodeName.toLowerCase();return a==="input"?!!_C[i.type]:a==="textarea"}function Sb(i,a,l,u){oa?la?la.push(u):la=[u]:oa=u,a=lu(a,"onChange"),0<a.length&&(l=new bc("onChange","change",null,l,u),i.push({event:l,listeners:a}))}var No=null,Oo=null;function EC(i){sw(i,0)}function wc(i){var a=_o(i);if(rb(a))return i}function _b(i,a){if(i==="change")return a}var Eb=!1;if(Mr){var Rf;if(Mr){var Tf="oninput"in document;if(!Tf){var Ab=document.createElement("div");Ab.setAttribute("oninput","return;"),Tf=typeof Ab.oninput=="function"}Rf=Tf}else Rf=!1;Eb=Rf&&(!document.documentMode||9<document.documentMode)}function jb(){No&&(No.detachEvent("onpropertychange",kb),Oo=No=null)}function kb(i){if(i.propertyName==="value"&&wc(Oo)){var a=[];Sb(a,Oo,i,Sf(i)),ub(EC,a)}}function AC(i,a,l){i==="focusin"?(jb(),No=a,Oo=l,No.attachEvent("onpropertychange",kb)):i==="focusout"&&jb()}function jC(i){if(i==="selectionchange"||i==="keyup"||i==="keydown")return wc(Oo)}function kC(i,a){if(i==="click")return wc(a)}function CC(i,a){if(i==="input"||i==="change")return wc(a)}function NC(i,a){return i===a&&(i!==0||1/i===1/a)||i!==i&&a!==a}var jn=typeof Object.is=="function"?Object.is:NC;function Ro(i,a){if(jn(i,a))return!0;if(typeof i!="object"||i===null||typeof a!="object"||a===null)return!1;var l=Object.keys(i),u=Object.keys(a);if(l.length!==u.length)return!1;for(u=0;u<l.length;u++){var m=l[u];if(!cf.call(a,m)||!jn(i[m],a[m]))return!1}return!0}function Cb(i){for(;i&&i.firstChild;)i=i.firstChild;return i}function Nb(i,a){var l=Cb(i);i=0;for(var u;l;){if(l.nodeType===3){if(u=i+l.textContent.length,i<=a&&u>=a)return{node:l,offset:a-i};i=u}e:{for(;l;){if(l.nextSibling){l=l.nextSibling;break e}l=l.parentNode}l=void 0}l=Cb(l)}}function Ob(i,a){return i&&a?i===a?!0:i&&i.nodeType===3?!1:a&&a.nodeType===3?Ob(i,a.parentNode):"contains"in i?i.contains(a):i.compareDocumentPosition?!!(i.compareDocumentPosition(a)&16):!1:!1}function Rb(i){i=i!=null&&i.ownerDocument!=null&&i.ownerDocument.defaultView!=null?i.ownerDocument.defaultView:window;for(var a=hc(i.document);a instanceof i.HTMLIFrameElement;){try{var l=typeof a.contentWindow.location.href=="string"}catch{l=!1}if(l)i=a.contentWindow;else break;a=hc(i.document)}return a}function Df(i){var a=i&&i.nodeName&&i.nodeName.toLowerCase();return a&&(a==="input"&&(i.type==="text"||i.type==="search"||i.type==="tel"||i.type==="url"||i.type==="password")||a==="textarea"||i.contentEditable==="true")}var OC=Mr&&"documentMode"in document&&11>=document.documentMode,ua=null,If=null,To=null,Mf=!1;function Tb(i,a,l){var u=l.window===l?l.document:l.nodeType===9?l:l.ownerDocument;Mf||ua==null||ua!==hc(u)||(u=ua,"selectionStart"in u&&Df(u)?u={start:u.selectionStart,end:u.selectionEnd}:(u=(u.ownerDocument&&u.ownerDocument.defaultView||window).getSelection(),u={anchorNode:u.anchorNode,anchorOffset:u.anchorOffset,focusNode:u.focusNode,focusOffset:u.focusOffset}),To&&Ro(To,u)||(To=u,u=lu(If,"onSelect"),0<u.length&&(a=new bc("onSelect","select",null,a,l),i.push({event:a,listeners:u}),a.target=ua)))}function ci(i,a){var l={};return l[i.toLowerCase()]=a.toLowerCase(),l["Webkit"+i]="webkit"+a,l["Moz"+i]="moz"+a,l}var da={animationend:ci("Animation","AnimationEnd"),animationiteration:ci("Animation","AnimationIteration"),animationstart:ci("Animation","AnimationStart"),transitionrun:ci("Transition","TransitionRun"),transitionstart:ci("Transition","TransitionStart"),transitioncancel:ci("Transition","TransitionCancel"),transitionend:ci("Transition","TransitionEnd")},Lf={},Db={};Mr&&(Db=document.createElement("div").style,"AnimationEvent"in window||(delete da.animationend.animation,delete da.animationiteration.animation,delete da.animationstart.animation),"TransitionEvent"in window||delete da.transitionend.transition);function ui(i){if(Lf[i])return Lf[i];if(!da[i])return i;var a=da[i],l;for(l in a)if(a.hasOwnProperty(l)&&l in Db)return Lf[i]=a[l];return i}var Ib=ui("animationend"),Mb=ui("animationiteration"),Lb=ui("animationstart"),RC=ui("transitionrun"),TC=ui("transitionstart"),DC=ui("transitioncancel"),Ub=ui("transitionend"),$b=new Map,Uf="abort auxClick beforeToggle cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");Uf.push("scrollEnd");function sr(i,a){$b.set(i,a),oi(a,[i])}var xc=typeof reportError=="function"?reportError:function(i){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var a=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof i=="object"&&i!==null&&typeof i.message=="string"?String(i.message):String(i),error:i});if(!window.dispatchEvent(a))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",i);return}console.error(i)},Fn=[],fa=0,$f=0;function Sc(){for(var i=fa,a=$f=fa=0;a<i;){var l=Fn[a];Fn[a++]=null;var u=Fn[a];Fn[a++]=null;var m=Fn[a];Fn[a++]=null;var y=Fn[a];if(Fn[a++]=null,u!==null&&m!==null){var S=u.pending;S===null?m.next=m:(m.next=S.next,S.next=m),u.pending=m}y!==0&&Bb(l,m,y)}}function _c(i,a,l,u){Fn[fa++]=i,Fn[fa++]=a,Fn[fa++]=l,Fn[fa++]=u,$f|=u,i.lanes|=u,i=i.alternate,i!==null&&(i.lanes|=u)}function Bf(i,a,l,u){return _c(i,a,l,u),Ec(i)}function di(i,a){return _c(i,null,null,a),Ec(i)}function Bb(i,a,l){i.lanes|=l;var u=i.alternate;u!==null&&(u.lanes|=l);for(var m=!1,y=i.return;y!==null;)y.childLanes|=l,u=y.alternate,u!==null&&(u.childLanes|=l),y.tag===22&&(i=y.stateNode,i===null||i._visibility&1||(m=!0)),i=y,y=y.return;return i.tag===3?(y=i.stateNode,m&&a!==null&&(m=31-An(l),i=y.hiddenUpdates,u=i[m],u===null?i[m]=[a]:u.push(a),a.lane=l|536870912),y):null}function Ec(i){if(50<el)throw el=0,Yh=null,Error(r(185));for(var a=i.return;a!==null;)i=a,a=i.return;return i.tag===3?i.stateNode:null}var ha={};function IC(i,a,l,u){this.tag=i,this.key=l,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.refCleanup=this.ref=null,this.pendingProps=a,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=u,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function kn(i,a,l,u){return new IC(i,a,l,u)}function qf(i){return i=i.prototype,!(!i||!i.isReactComponent)}function Lr(i,a){var l=i.alternate;return l===null?(l=kn(i.tag,a,i.key,i.mode),l.elementType=i.elementType,l.type=i.type,l.stateNode=i.stateNode,l.alternate=i,i.alternate=l):(l.pendingProps=a,l.type=i.type,l.flags=0,l.subtreeFlags=0,l.deletions=null),l.flags=i.flags&65011712,l.childLanes=i.childLanes,l.lanes=i.lanes,l.child=i.child,l.memoizedProps=i.memoizedProps,l.memoizedState=i.memoizedState,l.updateQueue=i.updateQueue,a=i.dependencies,l.dependencies=a===null?null:{lanes:a.lanes,firstContext:a.firstContext},l.sibling=i.sibling,l.index=i.index,l.ref=i.ref,l.refCleanup=i.refCleanup,l}function qb(i,a){i.flags&=65011714;var l=i.alternate;return l===null?(i.childLanes=0,i.lanes=a,i.child=null,i.subtreeFlags=0,i.memoizedProps=null,i.memoizedState=null,i.updateQueue=null,i.dependencies=null,i.stateNode=null):(i.childLanes=l.childLanes,i.lanes=l.lanes,i.child=l.child,i.subtreeFlags=0,i.deletions=null,i.memoizedProps=l.memoizedProps,i.memoizedState=l.memoizedState,i.updateQueue=l.updateQueue,i.type=l.type,a=l.dependencies,i.dependencies=a===null?null:{lanes:a.lanes,firstContext:a.firstContext}),i}function Ac(i,a,l,u,m,y){var S=0;if(u=i,typeof i=="function")qf(i)&&(S=1);else if(typeof i=="string")S=BN(i,l,le.current)?26:i==="html"||i==="head"||i==="body"?27:5;else e:switch(i){case H:return i=kn(31,l,a,m),i.elementType=H,i.lanes=y,i;case k:return fi(l.children,m,y,a);case I:S=8,m|=24;break;case N:return i=kn(12,l,a,m|2),i.elementType=N,i.lanes=y,i;case D:return i=kn(13,l,a,m),i.elementType=D,i.lanes=y,i;case C:return i=kn(19,l,a,m),i.elementType=C,i.lanes=y,i;default:if(typeof i=="object"&&i!==null)switch(i.$$typeof){case M:S=10;break e;case R:S=9;break e;case F:S=11;break e;case L:S=14;break e;case U:S=16,u=null;break e}S=29,l=Error(r(130,i===null?"null":typeof i,"")),u=null}return a=kn(S,l,a,m),a.elementType=i,a.type=u,a.lanes=y,a}function fi(i,a,l,u){return i=kn(7,i,u,a),i.lanes=l,i}function Ff(i,a,l){return i=kn(6,i,null,a),i.lanes=l,i}function Fb(i){var a=kn(18,null,null,0);return a.stateNode=i,a}function zf(i,a,l){return a=kn(4,i.children!==null?i.children:[],i.key,a),a.lanes=l,a.stateNode={containerInfo:i.containerInfo,pendingChildren:null,implementation:i.implementation},a}var zb=new WeakMap;function zn(i,a){if(typeof i=="object"&&i!==null){var l=zb.get(i);return l!==void 0?l:(a={value:i,source:a,stack:Fg(a)},zb.set(i,a),a)}return{value:i,source:a,stack:Fg(a)}}var pa=[],ma=0,jc=null,Do=0,Pn=[],Vn=0,ps=null,pr=1,mr="";function Ur(i,a){pa[ma++]=Do,pa[ma++]=jc,jc=i,Do=a}function Pb(i,a,l){Pn[Vn++]=pr,Pn[Vn++]=mr,Pn[Vn++]=ps,ps=i;var u=pr;i=mr;var m=32-An(u)-1;u&=~(1<<m),l+=1;var y=32-An(a)+m;if(30<y){var S=m-m%5;y=(u&(1<<S)-1).toString(32),u>>=S,m-=S,pr=1<<32-An(a)+m|l<<m|u,mr=y+i}else pr=1<<y|l<<m|u,mr=i}function Pf(i){i.return!==null&&(Ur(i,1),Pb(i,1,0))}function Vf(i){for(;i===jc;)jc=pa[--ma],pa[ma]=null,Do=pa[--ma],pa[ma]=null;for(;i===ps;)ps=Pn[--Vn],Pn[Vn]=null,mr=Pn[--Vn],Pn[Vn]=null,pr=Pn[--Vn],Pn[Vn]=null}function Vb(i,a){Pn[Vn++]=pr,Pn[Vn++]=mr,Pn[Vn++]=ps,pr=a.id,mr=a.overflow,ps=i}var $t=null,rt=null,De=!1,ms=null,Hn=!1,Hf=Error(r(519));function ys(i){var a=Error(r(418,1<arguments.length&&arguments[1]!==void 0&&arguments[1]?"text":"HTML",""));throw Io(zn(a,i)),Hf}function Hb(i){var a=i.stateNode,l=i.type,u=i.memoizedProps;switch(a[Ut]=i,a[dn]=u,l){case"dialog":Ce("cancel",a),Ce("close",a);break;case"iframe":case"object":case"embed":Ce("load",a);break;case"video":case"audio":for(l=0;l<nl.length;l++)Ce(nl[l],a);break;case"source":Ce("error",a);break;case"img":case"image":case"link":Ce("error",a),Ce("load",a);break;case"details":Ce("toggle",a);break;case"input":Ce("invalid",a),sb(a,u.value,u.defaultValue,u.checked,u.defaultChecked,u.type,u.name,!0);break;case"select":Ce("invalid",a);break;case"textarea":Ce("invalid",a),ab(a,u.value,u.defaultValue,u.children)}l=u.children,typeof l!="string"&&typeof l!="number"&&typeof l!="bigint"||a.textContent===""+l||u.suppressHydrationWarning===!0||lw(a.textContent,l)?(u.popover!=null&&(Ce("beforetoggle",a),Ce("toggle",a)),u.onScroll!=null&&Ce("scroll",a),u.onScrollEnd!=null&&Ce("scrollend",a),u.onClick!=null&&(a.onclick=Ir),a=!0):a=!1,a||ys(i,!0)}function Gb(i){for($t=i.return;$t;)switch($t.tag){case 5:case 31:case 13:Hn=!1;return;case 27:case 3:Hn=!0;return;default:$t=$t.return}}function ya(i){if(i!==$t)return!1;if(!De)return Gb(i),De=!0,!1;var a=i.tag,l;if((l=a!==3&&a!==27)&&((l=a===5)&&(l=i.type,l=!(l!=="form"&&l!=="button")||cp(i.type,i.memoizedProps)),l=!l),l&&rt&&ys(i),Gb(i),a===13){if(i=i.memoizedState,i=i!==null?i.dehydrated:null,!i)throw Error(r(317));rt=gw(i)}else if(a===31){if(i=i.memoizedState,i=i!==null?i.dehydrated:null,!i)throw Error(r(317));rt=gw(i)}else a===27?(a=rt,Os(i.type)?(i=pp,pp=null,rt=i):rt=a):rt=$t?Kn(i.stateNode.nextSibling):null;return!0}function hi(){rt=$t=null,De=!1}function Gf(){var i=ms;return i!==null&&(yn===null?yn=i:yn.push.apply(yn,i),ms=null),i}function Io(i){ms===null?ms=[i]:ms.push(i)}var Kf=B(null),pi=null,$r=null;function gs(i,a,l){ae(Kf,a._currentValue),a._currentValue=l}function Br(i){i._currentValue=Kf.current,ee(Kf)}function Yf(i,a,l){for(;i!==null;){var u=i.alternate;if((i.childLanes&a)!==a?(i.childLanes|=a,u!==null&&(u.childLanes|=a)):u!==null&&(u.childLanes&a)!==a&&(u.childLanes|=a),i===l)break;i=i.return}}function Zf(i,a,l,u){var m=i.child;for(m!==null&&(m.return=i);m!==null;){var y=m.dependencies;if(y!==null){var S=m.child;y=y.firstContext;e:for(;y!==null;){var j=y;y=m;for(var V=0;V<a.length;V++)if(j.context===a[V]){y.lanes|=l,j=y.alternate,j!==null&&(j.lanes|=l),Yf(y.return,l,i),u||(S=null);break e}y=j.next}}else if(m.tag===18){if(S=m.return,S===null)throw Error(r(341));S.lanes|=l,y=S.alternate,y!==null&&(y.lanes|=l),Yf(S,l,i),S=null}else S=m.child;if(S!==null)S.return=m;else for(S=m;S!==null;){if(S===i){S=null;break}if(m=S.sibling,m!==null){m.return=S.return,S=m;break}S=S.return}m=S}}function ga(i,a,l,u){i=null;for(var m=a,y=!1;m!==null;){if(!y){if((m.flags&524288)!==0)y=!0;else if((m.flags&262144)!==0)break}if(m.tag===10){var S=m.alternate;if(S===null)throw Error(r(387));if(S=S.memoizedProps,S!==null){var j=m.type;jn(m.pendingProps.value,S.value)||(i!==null?i.push(j):i=[j])}}else if(m===Ve.current){if(S=m.alternate,S===null)throw Error(r(387));S.memoizedState.memoizedState!==m.memoizedState.memoizedState&&(i!==null?i.push(ol):i=[ol])}m=m.return}i!==null&&Zf(a,i,l,u),a.flags|=262144}function kc(i){for(i=i.firstContext;i!==null;){if(!jn(i.context._currentValue,i.memoizedValue))return!0;i=i.next}return!1}function mi(i){pi=i,$r=null,i=i.dependencies,i!==null&&(i.firstContext=null)}function Bt(i){return Kb(pi,i)}function Cc(i,a){return pi===null&&mi(i),Kb(i,a)}function Kb(i,a){var l=a._currentValue;if(a={context:a,memoizedValue:l,next:null},$r===null){if(i===null)throw Error(r(308));$r=a,i.dependencies={lanes:0,firstContext:a},i.flags|=524288}else $r=$r.next=a;return l}var MC=typeof AbortController<"u"?AbortController:function(){var i=[],a=this.signal={aborted:!1,addEventListener:function(l,u){i.push(u)}};this.abort=function(){a.aborted=!0,i.forEach(function(l){return l()})}},LC=t.unstable_scheduleCallback,UC=t.unstable_NormalPriority,_t={$$typeof:M,Consumer:null,Provider:null,_currentValue:null,_currentValue2:null,_threadCount:0};function Wf(){return{controller:new MC,data:new Map,refCount:0}}function Mo(i){i.refCount--,i.refCount===0&&LC(UC,function(){i.controller.abort()})}var Lo=null,Qf=0,ba=0,va=null;function $C(i,a){if(Lo===null){var l=Lo=[];Qf=0,ba=ep(),va={status:"pending",value:void 0,then:function(u){l.push(u)}}}return Qf++,a.then(Yb,Yb),a}function Yb(){if(--Qf===0&&Lo!==null){va!==null&&(va.status="fulfilled");var i=Lo;Lo=null,ba=0,va=null;for(var a=0;a<i.length;a++)(0,i[a])()}}function BC(i,a){var l=[],u={status:"pending",value:null,reason:null,then:function(m){l.push(m)}};return i.then(function(){u.status="fulfilled",u.value=a;for(var m=0;m<l.length;m++)(0,l[m])(a)},function(m){for(u.status="rejected",u.reason=m,m=0;m<l.length;m++)(0,l[m])(void 0)}),u}var Zb=P.S;P.S=function(i,a){T0=_n(),typeof a=="object"&&a!==null&&typeof a.then=="function"&&$C(i,a),Zb!==null&&Zb(i,a)};var yi=B(null);function Jf(){var i=yi.current;return i!==null?i:Xe.pooledCache}function Nc(i,a){a===null?ae(yi,yi.current):ae(yi,a.pool)}function Wb(){var i=Jf();return i===null?null:{parent:_t._currentValue,pool:i}}var wa=Error(r(460)),Xf=Error(r(474)),Oc=Error(r(542)),Rc={then:function(){}};function Qb(i){return i=i.status,i==="fulfilled"||i==="rejected"}function Jb(i,a,l){switch(l=i[l],l===void 0?i.push(a):l!==a&&(a.then(Ir,Ir),a=l),a.status){case"fulfilled":return a.value;case"rejected":throw i=a.reason,ev(i),i;default:if(typeof a.status=="string")a.then(Ir,Ir);else{if(i=Xe,i!==null&&100<i.shellSuspendCounter)throw Error(r(482));i=a,i.status="pending",i.then(function(u){if(a.status==="pending"){var m=a;m.status="fulfilled",m.value=u}},function(u){if(a.status==="pending"){var m=a;m.status="rejected",m.reason=u}})}switch(a.status){case"fulfilled":return a.value;case"rejected":throw i=a.reason,ev(i),i}throw bi=a,wa}}function gi(i){try{var a=i._init;return a(i._payload)}catch(l){throw l!==null&&typeof l=="object"&&typeof l.then=="function"?(bi=l,wa):l}}var bi=null;function Xb(){if(bi===null)throw Error(r(459));var i=bi;return bi=null,i}function ev(i){if(i===wa||i===Oc)throw Error(r(483))}var xa=null,Uo=0;function Tc(i){var a=Uo;return Uo+=1,xa===null&&(xa=[]),Jb(xa,i,a)}function $o(i,a){a=a.props.ref,i.ref=a!==void 0?a:null}function Dc(i,a){throw a.$$typeof===v?Error(r(525)):(i=Object.prototype.toString.call(a),Error(r(31,i==="[object Object]"?"object with keys {"+Object.keys(a).join(", ")+"}":i)))}function tv(i){function a(Z,Y){if(i){var Q=Z.deletions;Q===null?(Z.deletions=[Y],Z.flags|=16):Q.push(Y)}}function l(Z,Y){if(!i)return null;for(;Y!==null;)a(Z,Y),Y=Y.sibling;return null}function u(Z){for(var Y=new Map;Z!==null;)Z.key!==null?Y.set(Z.key,Z):Y.set(Z.index,Z),Z=Z.sibling;return Y}function m(Z,Y){return Z=Lr(Z,Y),Z.index=0,Z.sibling=null,Z}function y(Z,Y,Q){return Z.index=Q,i?(Q=Z.alternate,Q!==null?(Q=Q.index,Q<Y?(Z.flags|=67108866,Y):Q):(Z.flags|=67108866,Y)):(Z.flags|=1048576,Y)}function S(Z){return i&&Z.alternate===null&&(Z.flags|=67108866),Z}function j(Z,Y,Q,re){return Y===null||Y.tag!==6?(Y=Ff(Q,Z.mode,re),Y.return=Z,Y):(Y=m(Y,Q),Y.return=Z,Y)}function V(Z,Y,Q,re){var pe=Q.type;return pe===k?ne(Z,Y,Q.props.children,re,Q.key):Y!==null&&(Y.elementType===pe||typeof pe=="object"&&pe!==null&&pe.$$typeof===U&&gi(pe)===Y.type)?(Y=m(Y,Q.props),$o(Y,Q),Y.return=Z,Y):(Y=Ac(Q.type,Q.key,Q.props,null,Z.mode,re),$o(Y,Q),Y.return=Z,Y)}function J(Z,Y,Q,re){return Y===null||Y.tag!==4||Y.stateNode.containerInfo!==Q.containerInfo||Y.stateNode.implementation!==Q.implementation?(Y=zf(Q,Z.mode,re),Y.return=Z,Y):(Y=m(Y,Q.children||[]),Y.return=Z,Y)}function ne(Z,Y,Q,re,pe){return Y===null||Y.tag!==7?(Y=fi(Q,Z.mode,re,pe),Y.return=Z,Y):(Y=m(Y,Q),Y.return=Z,Y)}function ie(Z,Y,Q){if(typeof Y=="string"&&Y!==""||typeof Y=="number"||typeof Y=="bigint")return Y=Ff(""+Y,Z.mode,Q),Y.return=Z,Y;if(typeof Y=="object"&&Y!==null){switch(Y.$$typeof){case w:return Q=Ac(Y.type,Y.key,Y.props,null,Z.mode,Q),$o(Q,Y),Q.return=Z,Q;case _:return Y=zf(Y,Z.mode,Q),Y.return=Z,Y;case U:return Y=gi(Y),ie(Z,Y,Q)}if(T(Y)||x(Y))return Y=fi(Y,Z.mode,Q,null),Y.return=Z,Y;if(typeof Y.then=="function")return ie(Z,Tc(Y),Q);if(Y.$$typeof===M)return ie(Z,Cc(Z,Y),Q);Dc(Z,Y)}return null}function X(Z,Y,Q,re){var pe=Y!==null?Y.key:null;if(typeof Q=="string"&&Q!==""||typeof Q=="number"||typeof Q=="bigint")return pe!==null?null:j(Z,Y,""+Q,re);if(typeof Q=="object"&&Q!==null){switch(Q.$$typeof){case w:return Q.key===pe?V(Z,Y,Q,re):null;case _:return Q.key===pe?J(Z,Y,Q,re):null;case U:return Q=gi(Q),X(Z,Y,Q,re)}if(T(Q)||x(Q))return pe!==null?null:ne(Z,Y,Q,re,null);if(typeof Q.then=="function")return X(Z,Y,Tc(Q),re);if(Q.$$typeof===M)return X(Z,Y,Cc(Z,Q),re);Dc(Z,Q)}return null}function te(Z,Y,Q,re,pe){if(typeof re=="string"&&re!==""||typeof re=="number"||typeof re=="bigint")return Z=Z.get(Q)||null,j(Y,Z,""+re,pe);if(typeof re=="object"&&re!==null){switch(re.$$typeof){case w:return Z=Z.get(re.key===null?Q:re.key)||null,V(Y,Z,re,pe);case _:return Z=Z.get(re.key===null?Q:re.key)||null,J(Y,Z,re,pe);case U:return re=gi(re),te(Z,Y,Q,re,pe)}if(T(re)||x(re))return Z=Z.get(Q)||null,ne(Y,Z,re,pe,null);if(typeof re.then=="function")return te(Z,Y,Q,Tc(re),pe);if(re.$$typeof===M)return te(Z,Y,Q,Cc(Y,re),pe);Dc(Y,re)}return null}function de(Z,Y,Q,re){for(var pe=null,Be=null,fe=Y,Se=Y=0,Oe=null;fe!==null&&Se<Q.length;Se++){fe.index>Se?(Oe=fe,fe=null):Oe=fe.sibling;var qe=X(Z,fe,Q[Se],re);if(qe===null){fe===null&&(fe=Oe);break}i&&fe&&qe.alternate===null&&a(Z,fe),Y=y(qe,Y,Se),Be===null?pe=qe:Be.sibling=qe,Be=qe,fe=Oe}if(Se===Q.length)return l(Z,fe),De&&Ur(Z,Se),pe;if(fe===null){for(;Se<Q.length;Se++)fe=ie(Z,Q[Se],re),fe!==null&&(Y=y(fe,Y,Se),Be===null?pe=fe:Be.sibling=fe,Be=fe);return De&&Ur(Z,Se),pe}for(fe=u(fe);Se<Q.length;Se++)Oe=te(fe,Z,Se,Q[Se],re),Oe!==null&&(i&&Oe.alternate!==null&&fe.delete(Oe.key===null?Se:Oe.key),Y=y(Oe,Y,Se),Be===null?pe=Oe:Be.sibling=Oe,Be=Oe);return i&&fe.forEach(function(Ms){return a(Z,Ms)}),De&&Ur(Z,Se),pe}function me(Z,Y,Q,re){if(Q==null)throw Error(r(151));for(var pe=null,Be=null,fe=Y,Se=Y=0,Oe=null,qe=Q.next();fe!==null&&!qe.done;Se++,qe=Q.next()){fe.index>Se?(Oe=fe,fe=null):Oe=fe.sibling;var Ms=X(Z,fe,qe.value,re);if(Ms===null){fe===null&&(fe=Oe);break}i&&fe&&Ms.alternate===null&&a(Z,fe),Y=y(Ms,Y,Se),Be===null?pe=Ms:Be.sibling=Ms,Be=Ms,fe=Oe}if(qe.done)return l(Z,fe),De&&Ur(Z,Se),pe;if(fe===null){for(;!qe.done;Se++,qe=Q.next())qe=ie(Z,qe.value,re),qe!==null&&(Y=y(qe,Y,Se),Be===null?pe=qe:Be.sibling=qe,Be=qe);return De&&Ur(Z,Se),pe}for(fe=u(fe);!qe.done;Se++,qe=Q.next())qe=te(fe,Z,Se,qe.value,re),qe!==null&&(i&&qe.alternate!==null&&fe.delete(qe.key===null?Se:qe.key),Y=y(qe,Y,Se),Be===null?pe=qe:Be.sibling=qe,Be=qe);return i&&fe.forEach(function(WN){return a(Z,WN)}),De&&Ur(Z,Se),pe}function Je(Z,Y,Q,re){if(typeof Q=="object"&&Q!==null&&Q.type===k&&Q.key===null&&(Q=Q.props.children),typeof Q=="object"&&Q!==null){switch(Q.$$typeof){case w:e:{for(var pe=Q.key;Y!==null;){if(Y.key===pe){if(pe=Q.type,pe===k){if(Y.tag===7){l(Z,Y.sibling),re=m(Y,Q.props.children),re.return=Z,Z=re;break e}}else if(Y.elementType===pe||typeof pe=="object"&&pe!==null&&pe.$$typeof===U&&gi(pe)===Y.type){l(Z,Y.sibling),re=m(Y,Q.props),$o(re,Q),re.return=Z,Z=re;break e}l(Z,Y);break}else a(Z,Y);Y=Y.sibling}Q.type===k?(re=fi(Q.props.children,Z.mode,re,Q.key),re.return=Z,Z=re):(re=Ac(Q.type,Q.key,Q.props,null,Z.mode,re),$o(re,Q),re.return=Z,Z=re)}return S(Z);case _:e:{for(pe=Q.key;Y!==null;){if(Y.key===pe)if(Y.tag===4&&Y.stateNode.containerInfo===Q.containerInfo&&Y.stateNode.implementation===Q.implementation){l(Z,Y.sibling),re=m(Y,Q.children||[]),re.return=Z,Z=re;break e}else{l(Z,Y);break}else a(Z,Y);Y=Y.sibling}re=zf(Q,Z.mode,re),re.return=Z,Z=re}return S(Z);case U:return Q=gi(Q),Je(Z,Y,Q,re)}if(T(Q))return de(Z,Y,Q,re);if(x(Q)){if(pe=x(Q),typeof pe!="function")throw Error(r(150));return Q=pe.call(Q),me(Z,Y,Q,re)}if(typeof Q.then=="function")return Je(Z,Y,Tc(Q),re);if(Q.$$typeof===M)return Je(Z,Y,Cc(Z,Q),re);Dc(Z,Q)}return typeof Q=="string"&&Q!==""||typeof Q=="number"||typeof Q=="bigint"?(Q=""+Q,Y!==null&&Y.tag===6?(l(Z,Y.sibling),re=m(Y,Q),re.return=Z,Z=re):(l(Z,Y),re=Ff(Q,Z.mode,re),re.return=Z,Z=re),S(Z)):l(Z,Y)}return function(Z,Y,Q,re){try{Uo=0;var pe=Je(Z,Y,Q,re);return xa=null,pe}catch(fe){if(fe===wa||fe===Oc)throw fe;var Be=kn(29,fe,null,Z.mode);return Be.lanes=re,Be.return=Z,Be}finally{}}}var vi=tv(!0),nv=tv(!1),bs=!1;function eh(i){i.updateQueue={baseState:i.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function th(i,a){i=i.updateQueue,a.updateQueue===i&&(a.updateQueue={baseState:i.baseState,firstBaseUpdate:i.firstBaseUpdate,lastBaseUpdate:i.lastBaseUpdate,shared:i.shared,callbacks:null})}function vs(i){return{lane:i,tag:0,payload:null,callback:null,next:null}}function ws(i,a,l){var u=i.updateQueue;if(u===null)return null;if(u=u.shared,(ze&2)!==0){var m=u.pending;return m===null?a.next=a:(a.next=m.next,m.next=a),u.pending=a,a=Ec(i),Bb(i,null,l),a}return _c(i,u,a,l),Ec(i)}function Bo(i,a,l){if(a=a.updateQueue,a!==null&&(a=a.shared,(l&4194048)!==0)){var u=a.lanes;u&=i.pendingLanes,l|=u,a.lanes=l,Kg(i,l)}}function nh(i,a){var l=i.updateQueue,u=i.alternate;if(u!==null&&(u=u.updateQueue,l===u)){var m=null,y=null;if(l=l.firstBaseUpdate,l!==null){do{var S={lane:l.lane,tag:l.tag,payload:l.payload,callback:null,next:null};y===null?m=y=S:y=y.next=S,l=l.next}while(l!==null);y===null?m=y=a:y=y.next=a}else m=y=a;l={baseState:u.baseState,firstBaseUpdate:m,lastBaseUpdate:y,shared:u.shared,callbacks:u.callbacks},i.updateQueue=l;return}i=l.lastBaseUpdate,i===null?l.firstBaseUpdate=a:i.next=a,l.lastBaseUpdate=a}var rh=!1;function qo(){if(rh){var i=va;if(i!==null)throw i}}function Fo(i,a,l,u){rh=!1;var m=i.updateQueue;bs=!1;var y=m.firstBaseUpdate,S=m.lastBaseUpdate,j=m.shared.pending;if(j!==null){m.shared.pending=null;var V=j,J=V.next;V.next=null,S===null?y=J:S.next=J,S=V;var ne=i.alternate;ne!==null&&(ne=ne.updateQueue,j=ne.lastBaseUpdate,j!==S&&(j===null?ne.firstBaseUpdate=J:j.next=J,ne.lastBaseUpdate=V))}if(y!==null){var ie=m.baseState;S=0,ne=J=V=null,j=y;do{var X=j.lane&-536870913,te=X!==j.lane;if(te?(Ne&X)===X:(u&X)===X){X!==0&&X===ba&&(rh=!0),ne!==null&&(ne=ne.next={lane:0,tag:j.tag,payload:j.payload,callback:null,next:null});e:{var de=i,me=j;X=a;var Je=l;switch(me.tag){case 1:if(de=me.payload,typeof de=="function"){ie=de.call(Je,ie,X);break e}ie=de;break e;case 3:de.flags=de.flags&-65537|128;case 0:if(de=me.payload,X=typeof de=="function"?de.call(Je,ie,X):de,X==null)break e;ie=b({},ie,X);break e;case 2:bs=!0}}X=j.callback,X!==null&&(i.flags|=64,te&&(i.flags|=8192),te=m.callbacks,te===null?m.callbacks=[X]:te.push(X))}else te={lane:X,tag:j.tag,payload:j.payload,callback:j.callback,next:null},ne===null?(J=ne=te,V=ie):ne=ne.next=te,S|=X;if(j=j.next,j===null){if(j=m.shared.pending,j===null)break;te=j,j=te.next,te.next=null,m.lastBaseUpdate=te,m.shared.pending=null}}while(!0);ne===null&&(V=ie),m.baseState=V,m.firstBaseUpdate=J,m.lastBaseUpdate=ne,y===null&&(m.shared.lanes=0),As|=S,i.lanes=S,i.memoizedState=ie}}function rv(i,a){if(typeof i!="function")throw Error(r(191,i));i.call(a)}function sv(i,a){var l=i.callbacks;if(l!==null)for(i.callbacks=null,i=0;i<l.length;i++)rv(l[i],a)}var Sa=B(null),Ic=B(0);function iv(i,a){i=Yr,ae(Ic,i),ae(Sa,a),Yr=i|a.baseLanes}function sh(){ae(Ic,Yr),ae(Sa,Sa.current)}function ih(){Yr=Ic.current,ee(Sa),ee(Ic)}var Cn=B(null),Gn=null;function xs(i){var a=i.alternate;ae(wt,wt.current&1),ae(Cn,i),Gn===null&&(a===null||Sa.current!==null||a.memoizedState!==null)&&(Gn=i)}function ah(i){ae(wt,wt.current),ae(Cn,i),Gn===null&&(Gn=i)}function av(i){i.tag===22?(ae(wt,wt.current),ae(Cn,i),Gn===null&&(Gn=i)):Ss()}function Ss(){ae(wt,wt.current),ae(Cn,Cn.current)}function Nn(i){ee(Cn),Gn===i&&(Gn=null),ee(wt)}var wt=B(0);function Mc(i){for(var a=i;a!==null;){if(a.tag===13){var l=a.memoizedState;if(l!==null&&(l=l.dehydrated,l===null||fp(l)||hp(l)))return a}else if(a.tag===19&&(a.memoizedProps.revealOrder==="forwards"||a.memoizedProps.revealOrder==="backwards"||a.memoizedProps.revealOrder==="unstable_legacy-backwards"||a.memoizedProps.revealOrder==="together")){if((a.flags&128)!==0)return a}else if(a.child!==null){a.child.return=a,a=a.child;continue}if(a===i)break;for(;a.sibling===null;){if(a.return===null||a.return===i)return null;a=a.return}a.sibling.return=a.return,a=a.sibling}return null}var qr=0,xe=null,We=null,Et=null,Lc=!1,_a=!1,wi=!1,Uc=0,zo=0,Ea=null,qC=0;function dt(){throw Error(r(321))}function oh(i,a){if(a===null)return!1;for(var l=0;l<a.length&&l<i.length;l++)if(!jn(i[l],a[l]))return!1;return!0}function lh(i,a,l,u,m,y){return qr=y,xe=a,a.memoizedState=null,a.updateQueue=null,a.lanes=0,P.H=i===null||i.memoizedState===null?Pv:_h,wi=!1,y=l(u,m),wi=!1,_a&&(y=lv(a,l,u,m)),ov(i),y}function ov(i){P.H=Ho;var a=We!==null&&We.next!==null;if(qr=0,Et=We=xe=null,Lc=!1,zo=0,Ea=null,a)throw Error(r(300));i===null||At||(i=i.dependencies,i!==null&&kc(i)&&(At=!0))}function lv(i,a,l,u){xe=i;var m=0;do{if(_a&&(Ea=null),zo=0,_a=!1,25<=m)throw Error(r(301));if(m+=1,Et=We=null,i.updateQueue!=null){var y=i.updateQueue;y.lastEffect=null,y.events=null,y.stores=null,y.memoCache!=null&&(y.memoCache.index=0)}P.H=Vv,y=a(l,u)}while(_a);return y}function FC(){var i=P.H,a=i.useState()[0];return a=typeof a.then=="function"?Po(a):a,i=i.useState()[0],(We!==null?We.memoizedState:null)!==i&&(xe.flags|=1024),a}function ch(){var i=Uc!==0;return Uc=0,i}function uh(i,a,l){a.updateQueue=i.updateQueue,a.flags&=-2053,i.lanes&=~l}function dh(i){if(Lc){for(i=i.memoizedState;i!==null;){var a=i.queue;a!==null&&(a.pending=null),i=i.next}Lc=!1}qr=0,Et=We=xe=null,_a=!1,zo=Uc=0,Ea=null}function nn(){var i={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return Et===null?xe.memoizedState=Et=i:Et=Et.next=i,Et}function xt(){if(We===null){var i=xe.alternate;i=i!==null?i.memoizedState:null}else i=We.next;var a=Et===null?xe.memoizedState:Et.next;if(a!==null)Et=a,We=i;else{if(i===null)throw xe.alternate===null?Error(r(467)):Error(r(310));We=i,i={memoizedState:We.memoizedState,baseState:We.baseState,baseQueue:We.baseQueue,queue:We.queue,next:null},Et===null?xe.memoizedState=Et=i:Et=Et.next=i}return Et}function $c(){return{lastEffect:null,events:null,stores:null,memoCache:null}}function Po(i){var a=zo;return zo+=1,Ea===null&&(Ea=[]),i=Jb(Ea,i,a),a=xe,(Et===null?a.memoizedState:Et.next)===null&&(a=a.alternate,P.H=a===null||a.memoizedState===null?Pv:_h),i}function Bc(i){if(i!==null&&typeof i=="object"){if(typeof i.then=="function")return Po(i);if(i.$$typeof===M)return Bt(i)}throw Error(r(438,String(i)))}function fh(i){var a=null,l=xe.updateQueue;if(l!==null&&(a=l.memoCache),a==null){var u=xe.alternate;u!==null&&(u=u.updateQueue,u!==null&&(u=u.memoCache,u!=null&&(a={data:u.data.map(function(m){return m.slice()}),index:0})))}if(a==null&&(a={data:[],index:0}),l===null&&(l=$c(),xe.updateQueue=l),l.memoCache=a,l=a.data[a.index],l===void 0)for(l=a.data[a.index]=Array(i),u=0;u<i;u++)l[u]=z;return a.index++,l}function Fr(i,a){return typeof a=="function"?a(i):a}function qc(i){var a=xt();return hh(a,We,i)}function hh(i,a,l){var u=i.queue;if(u===null)throw Error(r(311));u.lastRenderedReducer=l;var m=i.baseQueue,y=u.pending;if(y!==null){if(m!==null){var S=m.next;m.next=y.next,y.next=S}a.baseQueue=m=y,u.pending=null}if(y=i.baseState,m===null)i.memoizedState=y;else{a=m.next;var j=S=null,V=null,J=a,ne=!1;do{var ie=J.lane&-536870913;if(ie!==J.lane?(Ne&ie)===ie:(qr&ie)===ie){var X=J.revertLane;if(X===0)V!==null&&(V=V.next={lane:0,revertLane:0,gesture:null,action:J.action,hasEagerState:J.hasEagerState,eagerState:J.eagerState,next:null}),ie===ba&&(ne=!0);else if((qr&X)===X){J=J.next,X===ba&&(ne=!0);continue}else ie={lane:0,revertLane:J.revertLane,gesture:null,action:J.action,hasEagerState:J.hasEagerState,eagerState:J.eagerState,next:null},V===null?(j=V=ie,S=y):V=V.next=ie,xe.lanes|=X,As|=X;ie=J.action,wi&&l(y,ie),y=J.hasEagerState?J.eagerState:l(y,ie)}else X={lane:ie,revertLane:J.revertLane,gesture:J.gesture,action:J.action,hasEagerState:J.hasEagerState,eagerState:J.eagerState,next:null},V===null?(j=V=X,S=y):V=V.next=X,xe.lanes|=ie,As|=ie;J=J.next}while(J!==null&&J!==a);if(V===null?S=y:V.next=j,!jn(y,i.memoizedState)&&(At=!0,ne&&(l=va,l!==null)))throw l;i.memoizedState=y,i.baseState=S,i.baseQueue=V,u.lastRenderedState=y}return m===null&&(u.lanes=0),[i.memoizedState,u.dispatch]}function ph(i){var a=xt(),l=a.queue;if(l===null)throw Error(r(311));l.lastRenderedReducer=i;var u=l.dispatch,m=l.pending,y=a.memoizedState;if(m!==null){l.pending=null;var S=m=m.next;do y=i(y,S.action),S=S.next;while(S!==m);jn(y,a.memoizedState)||(At=!0),a.memoizedState=y,a.baseQueue===null&&(a.baseState=y),l.lastRenderedState=y}return[y,u]}function cv(i,a,l){var u=xe,m=xt(),y=De;if(y){if(l===void 0)throw Error(r(407));l=l()}else l=a();var S=!jn((We||m).memoizedState,l);if(S&&(m.memoizedState=l,At=!0),m=m.queue,gh(fv.bind(null,u,m,i),[i]),m.getSnapshot!==a||S||Et!==null&&Et.memoizedState.tag&1){if(u.flags|=2048,Aa(9,{destroy:void 0},dv.bind(null,u,m,l,a),null),Xe===null)throw Error(r(349));y||(qr&127)!==0||uv(u,a,l)}return l}function uv(i,a,l){i.flags|=16384,i={getSnapshot:a,value:l},a=xe.updateQueue,a===null?(a=$c(),xe.updateQueue=a,a.stores=[i]):(l=a.stores,l===null?a.stores=[i]:l.push(i))}function dv(i,a,l,u){a.value=l,a.getSnapshot=u,hv(a)&&pv(i)}function fv(i,a,l){return l(function(){hv(a)&&pv(i)})}function hv(i){var a=i.getSnapshot;i=i.value;try{var l=a();return!jn(i,l)}catch{return!0}}function pv(i){var a=di(i,2);a!==null&&gn(a,i,2)}function mh(i){var a=nn();if(typeof i=="function"){var l=i;if(i=l(),wi){ds(!0);try{l()}finally{ds(!1)}}}return a.memoizedState=a.baseState=i,a.queue={pending:null,lanes:0,dispatch:null,lastRenderedReducer:Fr,lastRenderedState:i},a}function mv(i,a,l,u){return i.baseState=l,hh(i,We,typeof u=="function"?u:Fr)}function zC(i,a,l,u,m){if(Pc(i))throw Error(r(485));if(i=a.action,i!==null){var y={payload:m,action:i,next:null,isTransition:!0,status:"pending",value:null,reason:null,listeners:[],then:function(S){y.listeners.push(S)}};P.T!==null?l(!0):y.isTransition=!1,u(y),l=a.pending,l===null?(y.next=a.pending=y,yv(a,y)):(y.next=l.next,a.pending=l.next=y)}}function yv(i,a){var l=a.action,u=a.payload,m=i.state;if(a.isTransition){var y=P.T,S={};P.T=S;try{var j=l(m,u),V=P.S;V!==null&&V(S,j),gv(i,a,j)}catch(J){yh(i,a,J)}finally{y!==null&&S.types!==null&&(y.types=S.types),P.T=y}}else try{y=l(m,u),gv(i,a,y)}catch(J){yh(i,a,J)}}function gv(i,a,l){l!==null&&typeof l=="object"&&typeof l.then=="function"?l.then(function(u){bv(i,a,u)},function(u){return yh(i,a,u)}):bv(i,a,l)}function bv(i,a,l){a.status="fulfilled",a.value=l,vv(a),i.state=l,a=i.pending,a!==null&&(l=a.next,l===a?i.pending=null:(l=l.next,a.next=l,yv(i,l)))}function yh(i,a,l){var u=i.pending;if(i.pending=null,u!==null){u=u.next;do a.status="rejected",a.reason=l,vv(a),a=a.next;while(a!==u)}i.action=null}function vv(i){i=i.listeners;for(var a=0;a<i.length;a++)(0,i[a])()}function wv(i,a){return a}function xv(i,a){if(De){var l=Xe.formState;if(l!==null){e:{var u=xe;if(De){if(rt){t:{for(var m=rt,y=Hn;m.nodeType!==8;){if(!y){m=null;break t}if(m=Kn(m.nextSibling),m===null){m=null;break t}}y=m.data,m=y==="F!"||y==="F"?m:null}if(m){rt=Kn(m.nextSibling),u=m.data==="F!";break e}}ys(u)}u=!1}u&&(a=l[0])}}return l=nn(),l.memoizedState=l.baseState=a,u={pending:null,lanes:0,dispatch:null,lastRenderedReducer:wv,lastRenderedState:a},l.queue=u,l=qv.bind(null,xe,u),u.dispatch=l,u=mh(!1),y=Sh.bind(null,xe,!1,u.queue),u=nn(),m={state:a,dispatch:null,action:i,pending:null},u.queue=m,l=zC.bind(null,xe,m,y,l),m.dispatch=l,u.memoizedState=i,[a,l,!1]}function Sv(i){var a=xt();return _v(a,We,i)}function _v(i,a,l){if(a=hh(i,a,wv)[0],i=qc(Fr)[0],typeof a=="object"&&a!==null&&typeof a.then=="function")try{var u=Po(a)}catch(S){throw S===wa?Oc:S}else u=a;a=xt();var m=a.queue,y=m.dispatch;return l!==a.memoizedState&&(xe.flags|=2048,Aa(9,{destroy:void 0},PC.bind(null,m,l),null)),[u,y,i]}function PC(i,a){i.action=a}function Ev(i){var a=xt(),l=We;if(l!==null)return _v(a,l,i);xt(),a=a.memoizedState,l=xt();var u=l.queue.dispatch;return l.memoizedState=i,[a,u,!1]}function Aa(i,a,l,u){return i={tag:i,create:l,deps:u,inst:a,next:null},a=xe.updateQueue,a===null&&(a=$c(),xe.updateQueue=a),l=a.lastEffect,l===null?a.lastEffect=i.next=i:(u=l.next,l.next=i,i.next=u,a.lastEffect=i),i}function Av(){return xt().memoizedState}function Fc(i,a,l,u){var m=nn();xe.flags|=i,m.memoizedState=Aa(1|a,{destroy:void 0},l,u===void 0?null:u)}function zc(i,a,l,u){var m=xt();u=u===void 0?null:u;var y=m.memoizedState.inst;We!==null&&u!==null&&oh(u,We.memoizedState.deps)?m.memoizedState=Aa(a,y,l,u):(xe.flags|=i,m.memoizedState=Aa(1|a,y,l,u))}function jv(i,a){Fc(8390656,8,i,a)}function gh(i,a){zc(2048,8,i,a)}function VC(i){xe.flags|=4;var a=xe.updateQueue;if(a===null)a=$c(),xe.updateQueue=a,a.events=[i];else{var l=a.events;l===null?a.events=[i]:l.push(i)}}function kv(i){var a=xt().memoizedState;return VC({ref:a,nextImpl:i}),function(){if((ze&2)!==0)throw Error(r(440));return a.impl.apply(void 0,arguments)}}function Cv(i,a){return zc(4,2,i,a)}function Nv(i,a){return zc(4,4,i,a)}function Ov(i,a){if(typeof a=="function"){i=i();var l=a(i);return function(){typeof l=="function"?l():a(null)}}if(a!=null)return i=i(),a.current=i,function(){a.current=null}}function Rv(i,a,l){l=l!=null?l.concat([i]):null,zc(4,4,Ov.bind(null,a,i),l)}function bh(){}function Tv(i,a){var l=xt();a=a===void 0?null:a;var u=l.memoizedState;return a!==null&&oh(a,u[1])?u[0]:(l.memoizedState=[i,a],i)}function Dv(i,a){var l=xt();a=a===void 0?null:a;var u=l.memoizedState;if(a!==null&&oh(a,u[1]))return u[0];if(u=i(),wi){ds(!0);try{i()}finally{ds(!1)}}return l.memoizedState=[u,a],u}function vh(i,a,l){return l===void 0||(qr&1073741824)!==0&&(Ne&261930)===0?i.memoizedState=a:(i.memoizedState=l,i=I0(),xe.lanes|=i,As|=i,l)}function Iv(i,a,l,u){return jn(l,a)?l:Sa.current!==null?(i=vh(i,l,u),jn(i,a)||(At=!0),i):(qr&42)===0||(qr&1073741824)!==0&&(Ne&261930)===0?(At=!0,i.memoizedState=l):(i=I0(),xe.lanes|=i,As|=i,a)}function Mv(i,a,l,u,m){var y=$.p;$.p=y!==0&&8>y?y:8;var S=P.T,j={};P.T=j,Sh(i,!1,a,l);try{var V=m(),J=P.S;if(J!==null&&J(j,V),V!==null&&typeof V=="object"&&typeof V.then=="function"){var ne=BC(V,u);Vo(i,a,ne,Tn(i))}else Vo(i,a,u,Tn(i))}catch(ie){Vo(i,a,{then:function(){},status:"rejected",reason:ie},Tn())}finally{$.p=y,S!==null&&j.types!==null&&(S.types=j.types),P.T=S}}function HC(){}function wh(i,a,l,u){if(i.tag!==5)throw Error(r(476));var m=Lv(i).queue;Mv(i,m,a,K,l===null?HC:function(){return Uv(i),l(u)})}function Lv(i){var a=i.memoizedState;if(a!==null)return a;a={memoizedState:K,baseState:K,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Fr,lastRenderedState:K},next:null};var l={};return a.next={memoizedState:l,baseState:l,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Fr,lastRenderedState:l},next:null},i.memoizedState=a,i=i.alternate,i!==null&&(i.memoizedState=a),a}function Uv(i){var a=Lv(i);a.next===null&&(a=i.alternate.memoizedState),Vo(i,a.next.queue,{},Tn())}function xh(){return Bt(ol)}function $v(){return xt().memoizedState}function Bv(){return xt().memoizedState}function GC(i){for(var a=i.return;a!==null;){switch(a.tag){case 24:case 3:var l=Tn();i=vs(l);var u=ws(a,i,l);u!==null&&(gn(u,a,l),Bo(u,a,l)),a={cache:Wf()},i.payload=a;return}a=a.return}}function KC(i,a,l){var u=Tn();l={lane:u,revertLane:0,gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null},Pc(i)?Fv(a,l):(l=Bf(i,a,l,u),l!==null&&(gn(l,i,u),zv(l,a,u)))}function qv(i,a,l){var u=Tn();Vo(i,a,l,u)}function Vo(i,a,l,u){var m={lane:u,revertLane:0,gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null};if(Pc(i))Fv(a,m);else{var y=i.alternate;if(i.lanes===0&&(y===null||y.lanes===0)&&(y=a.lastRenderedReducer,y!==null))try{var S=a.lastRenderedState,j=y(S,l);if(m.hasEagerState=!0,m.eagerState=j,jn(j,S))return _c(i,a,m,0),Xe===null&&Sc(),!1}catch{}finally{}if(l=Bf(i,a,m,u),l!==null)return gn(l,i,u),zv(l,a,u),!0}return!1}function Sh(i,a,l,u){if(u={lane:2,revertLane:ep(),gesture:null,action:u,hasEagerState:!1,eagerState:null,next:null},Pc(i)){if(a)throw Error(r(479))}else a=Bf(i,l,u,2),a!==null&&gn(a,i,2)}function Pc(i){var a=i.alternate;return i===xe||a!==null&&a===xe}function Fv(i,a){_a=Lc=!0;var l=i.pending;l===null?a.next=a:(a.next=l.next,l.next=a),i.pending=a}function zv(i,a,l){if((l&4194048)!==0){var u=a.lanes;u&=i.pendingLanes,l|=u,a.lanes=l,Kg(i,l)}}var Ho={readContext:Bt,use:Bc,useCallback:dt,useContext:dt,useEffect:dt,useImperativeHandle:dt,useLayoutEffect:dt,useInsertionEffect:dt,useMemo:dt,useReducer:dt,useRef:dt,useState:dt,useDebugValue:dt,useDeferredValue:dt,useTransition:dt,useSyncExternalStore:dt,useId:dt,useHostTransitionStatus:dt,useFormState:dt,useActionState:dt,useOptimistic:dt,useMemoCache:dt,useCacheRefresh:dt};Ho.useEffectEvent=dt;var Pv={readContext:Bt,use:Bc,useCallback:function(i,a){return nn().memoizedState=[i,a===void 0?null:a],i},useContext:Bt,useEffect:jv,useImperativeHandle:function(i,a,l){l=l!=null?l.concat([i]):null,Fc(4194308,4,Ov.bind(null,a,i),l)},useLayoutEffect:function(i,a){return Fc(4194308,4,i,a)},useInsertionEffect:function(i,a){Fc(4,2,i,a)},useMemo:function(i,a){var l=nn();a=a===void 0?null:a;var u=i();if(wi){ds(!0);try{i()}finally{ds(!1)}}return l.memoizedState=[u,a],u},useReducer:function(i,a,l){var u=nn();if(l!==void 0){var m=l(a);if(wi){ds(!0);try{l(a)}finally{ds(!1)}}}else m=a;return u.memoizedState=u.baseState=m,i={pending:null,lanes:0,dispatch:null,lastRenderedReducer:i,lastRenderedState:m},u.queue=i,i=i.dispatch=KC.bind(null,xe,i),[u.memoizedState,i]},useRef:function(i){var a=nn();return i={current:i},a.memoizedState=i},useState:function(i){i=mh(i);var a=i.queue,l=qv.bind(null,xe,a);return a.dispatch=l,[i.memoizedState,l]},useDebugValue:bh,useDeferredValue:function(i,a){var l=nn();return vh(l,i,a)},useTransition:function(){var i=mh(!1);return i=Mv.bind(null,xe,i.queue,!0,!1),nn().memoizedState=i,[!1,i]},useSyncExternalStore:function(i,a,l){var u=xe,m=nn();if(De){if(l===void 0)throw Error(r(407));l=l()}else{if(l=a(),Xe===null)throw Error(r(349));(Ne&127)!==0||uv(u,a,l)}m.memoizedState=l;var y={value:l,getSnapshot:a};return m.queue=y,jv(fv.bind(null,u,y,i),[i]),u.flags|=2048,Aa(9,{destroy:void 0},dv.bind(null,u,y,l,a),null),l},useId:function(){var i=nn(),a=Xe.identifierPrefix;if(De){var l=mr,u=pr;l=(u&~(1<<32-An(u)-1)).toString(32)+l,a="_"+a+"R_"+l,l=Uc++,0<l&&(a+="H"+l.toString(32)),a+="_"}else l=qC++,a="_"+a+"r_"+l.toString(32)+"_";return i.memoizedState=a},useHostTransitionStatus:xh,useFormState:xv,useActionState:xv,useOptimistic:function(i){var a=nn();a.memoizedState=a.baseState=i;var l={pending:null,lanes:0,dispatch:null,lastRenderedReducer:null,lastRenderedState:null};return a.queue=l,a=Sh.bind(null,xe,!0,l),l.dispatch=a,[i,a]},useMemoCache:fh,useCacheRefresh:function(){return nn().memoizedState=GC.bind(null,xe)},useEffectEvent:function(i){var a=nn(),l={impl:i};return a.memoizedState=l,function(){if((ze&2)!==0)throw Error(r(440));return l.impl.apply(void 0,arguments)}}},_h={readContext:Bt,use:Bc,useCallback:Tv,useContext:Bt,useEffect:gh,useImperativeHandle:Rv,useInsertionEffect:Cv,useLayoutEffect:Nv,useMemo:Dv,useReducer:qc,useRef:Av,useState:function(){return qc(Fr)},useDebugValue:bh,useDeferredValue:function(i,a){var l=xt();return Iv(l,We.memoizedState,i,a)},useTransition:function(){var i=qc(Fr)[0],a=xt().memoizedState;return[typeof i=="boolean"?i:Po(i),a]},useSyncExternalStore:cv,useId:$v,useHostTransitionStatus:xh,useFormState:Sv,useActionState:Sv,useOptimistic:function(i,a){var l=xt();return mv(l,We,i,a)},useMemoCache:fh,useCacheRefresh:Bv};_h.useEffectEvent=kv;var Vv={readContext:Bt,use:Bc,useCallback:Tv,useContext:Bt,useEffect:gh,useImperativeHandle:Rv,useInsertionEffect:Cv,useLayoutEffect:Nv,useMemo:Dv,useReducer:ph,useRef:Av,useState:function(){return ph(Fr)},useDebugValue:bh,useDeferredValue:function(i,a){var l=xt();return We===null?vh(l,i,a):Iv(l,We.memoizedState,i,a)},useTransition:function(){var i=ph(Fr)[0],a=xt().memoizedState;return[typeof i=="boolean"?i:Po(i),a]},useSyncExternalStore:cv,useId:$v,useHostTransitionStatus:xh,useFormState:Ev,useActionState:Ev,useOptimistic:function(i,a){var l=xt();return We!==null?mv(l,We,i,a):(l.baseState=i,[i,l.queue.dispatch])},useMemoCache:fh,useCacheRefresh:Bv};Vv.useEffectEvent=kv;function Eh(i,a,l,u){a=i.memoizedState,l=l(u,a),l=l==null?a:b({},a,l),i.memoizedState=l,i.lanes===0&&(i.updateQueue.baseState=l)}var Ah={enqueueSetState:function(i,a,l){i=i._reactInternals;var u=Tn(),m=vs(u);m.payload=a,l!=null&&(m.callback=l),a=ws(i,m,u),a!==null&&(gn(a,i,u),Bo(a,i,u))},enqueueReplaceState:function(i,a,l){i=i._reactInternals;var u=Tn(),m=vs(u);m.tag=1,m.payload=a,l!=null&&(m.callback=l),a=ws(i,m,u),a!==null&&(gn(a,i,u),Bo(a,i,u))},enqueueForceUpdate:function(i,a){i=i._reactInternals;var l=Tn(),u=vs(l);u.tag=2,a!=null&&(u.callback=a),a=ws(i,u,l),a!==null&&(gn(a,i,l),Bo(a,i,l))}};function Hv(i,a,l,u,m,y,S){return i=i.stateNode,typeof i.shouldComponentUpdate=="function"?i.shouldComponentUpdate(u,y,S):a.prototype&&a.prototype.isPureReactComponent?!Ro(l,u)||!Ro(m,y):!0}function Gv(i,a,l,u){i=a.state,typeof a.componentWillReceiveProps=="function"&&a.componentWillReceiveProps(l,u),typeof a.UNSAFE_componentWillReceiveProps=="function"&&a.UNSAFE_componentWillReceiveProps(l,u),a.state!==i&&Ah.enqueueReplaceState(a,a.state,null)}function xi(i,a){var l=a;if("ref"in a){l={};for(var u in a)u!=="ref"&&(l[u]=a[u])}if(i=i.defaultProps){l===a&&(l=b({},l));for(var m in i)l[m]===void 0&&(l[m]=i[m])}return l}function Kv(i){xc(i)}function Yv(i){console.error(i)}function Zv(i){xc(i)}function Vc(i,a){try{var l=i.onUncaughtError;l(a.value,{componentStack:a.stack})}catch(u){setTimeout(function(){throw u})}}function Wv(i,a,l){try{var u=i.onCaughtError;u(l.value,{componentStack:l.stack,errorBoundary:a.tag===1?a.stateNode:null})}catch(m){setTimeout(function(){throw m})}}function jh(i,a,l){return l=vs(l),l.tag=3,l.payload={element:null},l.callback=function(){Vc(i,a)},l}function Qv(i){return i=vs(i),i.tag=3,i}function Jv(i,a,l,u){var m=l.type.getDerivedStateFromError;if(typeof m=="function"){var y=u.value;i.payload=function(){return m(y)},i.callback=function(){Wv(a,l,u)}}var S=l.stateNode;S!==null&&typeof S.componentDidCatch=="function"&&(i.callback=function(){Wv(a,l,u),typeof m!="function"&&(js===null?js=new Set([this]):js.add(this));var j=u.stack;this.componentDidCatch(u.value,{componentStack:j!==null?j:""})})}function YC(i,a,l,u,m){if(l.flags|=32768,u!==null&&typeof u=="object"&&typeof u.then=="function"){if(a=l.alternate,a!==null&&ga(a,l,m,!0),l=Cn.current,l!==null){switch(l.tag){case 31:case 13:return Gn===null?nu():l.alternate===null&&ft===0&&(ft=3),l.flags&=-257,l.flags|=65536,l.lanes=m,u===Rc?l.flags|=16384:(a=l.updateQueue,a===null?l.updateQueue=new Set([u]):a.add(u),Qh(i,u,m)),!1;case 22:return l.flags|=65536,u===Rc?l.flags|=16384:(a=l.updateQueue,a===null?(a={transitions:null,markerInstances:null,retryQueue:new Set([u])},l.updateQueue=a):(l=a.retryQueue,l===null?a.retryQueue=new Set([u]):l.add(u)),Qh(i,u,m)),!1}throw Error(r(435,l.tag))}return Qh(i,u,m),nu(),!1}if(De)return a=Cn.current,a!==null?((a.flags&65536)===0&&(a.flags|=256),a.flags|=65536,a.lanes=m,u!==Hf&&(i=Error(r(422),{cause:u}),Io(zn(i,l)))):(u!==Hf&&(a=Error(r(423),{cause:u}),Io(zn(a,l))),i=i.current.alternate,i.flags|=65536,m&=-m,i.lanes|=m,u=zn(u,l),m=jh(i.stateNode,u,m),nh(i,m),ft!==4&&(ft=2)),!1;var y=Error(r(520),{cause:u});if(y=zn(y,l),Xo===null?Xo=[y]:Xo.push(y),ft!==4&&(ft=2),a===null)return!0;u=zn(u,l),l=a;do{switch(l.tag){case 3:return l.flags|=65536,i=m&-m,l.lanes|=i,i=jh(l.stateNode,u,i),nh(l,i),!1;case 1:if(a=l.type,y=l.stateNode,(l.flags&128)===0&&(typeof a.getDerivedStateFromError=="function"||y!==null&&typeof y.componentDidCatch=="function"&&(js===null||!js.has(y))))return l.flags|=65536,m&=-m,l.lanes|=m,m=Qv(m),Jv(m,i,l,u),nh(l,m),!1}l=l.return}while(l!==null);return!1}var kh=Error(r(461)),At=!1;function qt(i,a,l,u){a.child=i===null?nv(a,null,l,u):vi(a,i.child,l,u)}function Xv(i,a,l,u,m){l=l.render;var y=a.ref;if("ref"in u){var S={};for(var j in u)j!=="ref"&&(S[j]=u[j])}else S=u;return mi(a),u=lh(i,a,l,S,y,m),j=ch(),i!==null&&!At?(uh(i,a,m),zr(i,a,m)):(De&&j&&Pf(a),a.flags|=1,qt(i,a,u,m),a.child)}function e0(i,a,l,u,m){if(i===null){var y=l.type;return typeof y=="function"&&!qf(y)&&y.defaultProps===void 0&&l.compare===null?(a.tag=15,a.type=y,t0(i,a,y,u,m)):(i=Ac(l.type,null,u,a,a.mode,m),i.ref=a.ref,i.return=a,a.child=i)}if(y=i.child,!Mh(i,m)){var S=y.memoizedProps;if(l=l.compare,l=l!==null?l:Ro,l(S,u)&&i.ref===a.ref)return zr(i,a,m)}return a.flags|=1,i=Lr(y,u),i.ref=a.ref,i.return=a,a.child=i}function t0(i,a,l,u,m){if(i!==null){var y=i.memoizedProps;if(Ro(y,u)&&i.ref===a.ref)if(At=!1,a.pendingProps=u=y,Mh(i,m))(i.flags&131072)!==0&&(At=!0);else return a.lanes=i.lanes,zr(i,a,m)}return Ch(i,a,l,u,m)}function n0(i,a,l,u){var m=u.children,y=i!==null?i.memoizedState:null;if(i===null&&a.stateNode===null&&(a.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),u.mode==="hidden"){if((a.flags&128)!==0){if(y=y!==null?y.baseLanes|l:l,i!==null){for(u=a.child=i.child,m=0;u!==null;)m=m|u.lanes|u.childLanes,u=u.sibling;u=m&~y}else u=0,a.child=null;return r0(i,a,y,l,u)}if((l&536870912)!==0)a.memoizedState={baseLanes:0,cachePool:null},i!==null&&Nc(a,y!==null?y.cachePool:null),y!==null?iv(a,y):sh(),av(a);else return u=a.lanes=536870912,r0(i,a,y!==null?y.baseLanes|l:l,l,u)}else y!==null?(Nc(a,y.cachePool),iv(a,y),Ss(),a.memoizedState=null):(i!==null&&Nc(a,null),sh(),Ss());return qt(i,a,m,l),a.child}function Go(i,a){return i!==null&&i.tag===22||a.stateNode!==null||(a.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),a.sibling}function r0(i,a,l,u,m){var y=Jf();return y=y===null?null:{parent:_t._currentValue,pool:y},a.memoizedState={baseLanes:l,cachePool:y},i!==null&&Nc(a,null),sh(),av(a),i!==null&&ga(i,a,u,!0),a.childLanes=m,null}function Hc(i,a){return a=Kc({mode:a.mode,children:a.children},i.mode),a.ref=i.ref,i.child=a,a.return=i,a}function s0(i,a,l){return vi(a,i.child,null,l),i=Hc(a,a.pendingProps),i.flags|=2,Nn(a),a.memoizedState=null,i}function ZC(i,a,l){var u=a.pendingProps,m=(a.flags&128)!==0;if(a.flags&=-129,i===null){if(De){if(u.mode==="hidden")return i=Hc(a,u),a.lanes=536870912,Go(null,i);if(ah(a),(i=rt)?(i=yw(i,Hn),i=i!==null&&i.data==="&"?i:null,i!==null&&(a.memoizedState={dehydrated:i,treeContext:ps!==null?{id:pr,overflow:mr}:null,retryLane:536870912,hydrationErrors:null},l=Fb(i),l.return=a,a.child=l,$t=a,rt=null)):i=null,i===null)throw ys(a);return a.lanes=536870912,null}return Hc(a,u)}var y=i.memoizedState;if(y!==null){var S=y.dehydrated;if(ah(a),m)if(a.flags&256)a.flags&=-257,a=s0(i,a,l);else if(a.memoizedState!==null)a.child=i.child,a.flags|=128,a=null;else throw Error(r(558));else if(At||ga(i,a,l,!1),m=(l&i.childLanes)!==0,At||m){if(u=Xe,u!==null&&(S=Yg(u,l),S!==0&&S!==y.retryLane))throw y.retryLane=S,di(i,S),gn(u,i,S),kh;nu(),a=s0(i,a,l)}else i=y.treeContext,rt=Kn(S.nextSibling),$t=a,De=!0,ms=null,Hn=!1,i!==null&&Vb(a,i),a=Hc(a,u),a.flags|=4096;return a}return i=Lr(i.child,{mode:u.mode,children:u.children}),i.ref=a.ref,a.child=i,i.return=a,i}function Gc(i,a){var l=a.ref;if(l===null)i!==null&&i.ref!==null&&(a.flags|=4194816);else{if(typeof l!="function"&&typeof l!="object")throw Error(r(284));(i===null||i.ref!==l)&&(a.flags|=4194816)}}function Ch(i,a,l,u,m){return mi(a),l=lh(i,a,l,u,void 0,m),u=ch(),i!==null&&!At?(uh(i,a,m),zr(i,a,m)):(De&&u&&Pf(a),a.flags|=1,qt(i,a,l,m),a.child)}function i0(i,a,l,u,m,y){return mi(a),a.updateQueue=null,l=lv(a,u,l,m),ov(i),u=ch(),i!==null&&!At?(uh(i,a,y),zr(i,a,y)):(De&&u&&Pf(a),a.flags|=1,qt(i,a,l,y),a.child)}function a0(i,a,l,u,m){if(mi(a),a.stateNode===null){var y=ha,S=l.contextType;typeof S=="object"&&S!==null&&(y=Bt(S)),y=new l(u,y),a.memoizedState=y.state!==null&&y.state!==void 0?y.state:null,y.updater=Ah,a.stateNode=y,y._reactInternals=a,y=a.stateNode,y.props=u,y.state=a.memoizedState,y.refs={},eh(a),S=l.contextType,y.context=typeof S=="object"&&S!==null?Bt(S):ha,y.state=a.memoizedState,S=l.getDerivedStateFromProps,typeof S=="function"&&(Eh(a,l,S,u),y.state=a.memoizedState),typeof l.getDerivedStateFromProps=="function"||typeof y.getSnapshotBeforeUpdate=="function"||typeof y.UNSAFE_componentWillMount!="function"&&typeof y.componentWillMount!="function"||(S=y.state,typeof y.componentWillMount=="function"&&y.componentWillMount(),typeof y.UNSAFE_componentWillMount=="function"&&y.UNSAFE_componentWillMount(),S!==y.state&&Ah.enqueueReplaceState(y,y.state,null),Fo(a,u,y,m),qo(),y.state=a.memoizedState),typeof y.componentDidMount=="function"&&(a.flags|=4194308),u=!0}else if(i===null){y=a.stateNode;var j=a.memoizedProps,V=xi(l,j);y.props=V;var J=y.context,ne=l.contextType;S=ha,typeof ne=="object"&&ne!==null&&(S=Bt(ne));var ie=l.getDerivedStateFromProps;ne=typeof ie=="function"||typeof y.getSnapshotBeforeUpdate=="function",j=a.pendingProps!==j,ne||typeof y.UNSAFE_componentWillReceiveProps!="function"&&typeof y.componentWillReceiveProps!="function"||(j||J!==S)&&Gv(a,y,u,S),bs=!1;var X=a.memoizedState;y.state=X,Fo(a,u,y,m),qo(),J=a.memoizedState,j||X!==J||bs?(typeof ie=="function"&&(Eh(a,l,ie,u),J=a.memoizedState),(V=bs||Hv(a,l,V,u,X,J,S))?(ne||typeof y.UNSAFE_componentWillMount!="function"&&typeof y.componentWillMount!="function"||(typeof y.componentWillMount=="function"&&y.componentWillMount(),typeof y.UNSAFE_componentWillMount=="function"&&y.UNSAFE_componentWillMount()),typeof y.componentDidMount=="function"&&(a.flags|=4194308)):(typeof y.componentDidMount=="function"&&(a.flags|=4194308),a.memoizedProps=u,a.memoizedState=J),y.props=u,y.state=J,y.context=S,u=V):(typeof y.componentDidMount=="function"&&(a.flags|=4194308),u=!1)}else{y=a.stateNode,th(i,a),S=a.memoizedProps,ne=xi(l,S),y.props=ne,ie=a.pendingProps,X=y.context,J=l.contextType,V=ha,typeof J=="object"&&J!==null&&(V=Bt(J)),j=l.getDerivedStateFromProps,(J=typeof j=="function"||typeof y.getSnapshotBeforeUpdate=="function")||typeof y.UNSAFE_componentWillReceiveProps!="function"&&typeof y.componentWillReceiveProps!="function"||(S!==ie||X!==V)&&Gv(a,y,u,V),bs=!1,X=a.memoizedState,y.state=X,Fo(a,u,y,m),qo();var te=a.memoizedState;S!==ie||X!==te||bs||i!==null&&i.dependencies!==null&&kc(i.dependencies)?(typeof j=="function"&&(Eh(a,l,j,u),te=a.memoizedState),(ne=bs||Hv(a,l,ne,u,X,te,V)||i!==null&&i.dependencies!==null&&kc(i.dependencies))?(J||typeof y.UNSAFE_componentWillUpdate!="function"&&typeof y.componentWillUpdate!="function"||(typeof y.componentWillUpdate=="function"&&y.componentWillUpdate(u,te,V),typeof y.UNSAFE_componentWillUpdate=="function"&&y.UNSAFE_componentWillUpdate(u,te,V)),typeof y.componentDidUpdate=="function"&&(a.flags|=4),typeof y.getSnapshotBeforeUpdate=="function"&&(a.flags|=1024)):(typeof y.componentDidUpdate!="function"||S===i.memoizedProps&&X===i.memoizedState||(a.flags|=4),typeof y.getSnapshotBeforeUpdate!="function"||S===i.memoizedProps&&X===i.memoizedState||(a.flags|=1024),a.memoizedProps=u,a.memoizedState=te),y.props=u,y.state=te,y.context=V,u=ne):(typeof y.componentDidUpdate!="function"||S===i.memoizedProps&&X===i.memoizedState||(a.flags|=4),typeof y.getSnapshotBeforeUpdate!="function"||S===i.memoizedProps&&X===i.memoizedState||(a.flags|=1024),u=!1)}return y=u,Gc(i,a),u=(a.flags&128)!==0,y||u?(y=a.stateNode,l=u&&typeof l.getDerivedStateFromError!="function"?null:y.render(),a.flags|=1,i!==null&&u?(a.child=vi(a,i.child,null,m),a.child=vi(a,null,l,m)):qt(i,a,l,m),a.memoizedState=y.state,i=a.child):i=zr(i,a,m),i}function o0(i,a,l,u){return hi(),a.flags|=256,qt(i,a,l,u),a.child}var Nh={dehydrated:null,treeContext:null,retryLane:0,hydrationErrors:null};function Oh(i){return{baseLanes:i,cachePool:Wb()}}function Rh(i,a,l){return i=i!==null?i.childLanes&~l:0,a&&(i|=Rn),i}function l0(i,a,l){var u=a.pendingProps,m=!1,y=(a.flags&128)!==0,S;if((S=y)||(S=i!==null&&i.memoizedState===null?!1:(wt.current&2)!==0),S&&(m=!0,a.flags&=-129),S=(a.flags&32)!==0,a.flags&=-33,i===null){if(De){if(m?xs(a):Ss(),(i=rt)?(i=yw(i,Hn),i=i!==null&&i.data!=="&"?i:null,i!==null&&(a.memoizedState={dehydrated:i,treeContext:ps!==null?{id:pr,overflow:mr}:null,retryLane:536870912,hydrationErrors:null},l=Fb(i),l.return=a,a.child=l,$t=a,rt=null)):i=null,i===null)throw ys(a);return hp(i)?a.lanes=32:a.lanes=536870912,null}var j=u.children;return u=u.fallback,m?(Ss(),m=a.mode,j=Kc({mode:"hidden",children:j},m),u=fi(u,m,l,null),j.return=a,u.return=a,j.sibling=u,a.child=j,u=a.child,u.memoizedState=Oh(l),u.childLanes=Rh(i,S,l),a.memoizedState=Nh,Go(null,u)):(xs(a),Th(a,j))}var V=i.memoizedState;if(V!==null&&(j=V.dehydrated,j!==null)){if(y)a.flags&256?(xs(a),a.flags&=-257,a=Dh(i,a,l)):a.memoizedState!==null?(Ss(),a.child=i.child,a.flags|=128,a=null):(Ss(),j=u.fallback,m=a.mode,u=Kc({mode:"visible",children:u.children},m),j=fi(j,m,l,null),j.flags|=2,u.return=a,j.return=a,u.sibling=j,a.child=u,vi(a,i.child,null,l),u=a.child,u.memoizedState=Oh(l),u.childLanes=Rh(i,S,l),a.memoizedState=Nh,a=Go(null,u));else if(xs(a),hp(j)){if(S=j.nextSibling&&j.nextSibling.dataset,S)var J=S.dgst;S=J,u=Error(r(419)),u.stack="",u.digest=S,Io({value:u,source:null,stack:null}),a=Dh(i,a,l)}else if(At||ga(i,a,l,!1),S=(l&i.childLanes)!==0,At||S){if(S=Xe,S!==null&&(u=Yg(S,l),u!==0&&u!==V.retryLane))throw V.retryLane=u,di(i,u),gn(S,i,u),kh;fp(j)||nu(),a=Dh(i,a,l)}else fp(j)?(a.flags|=192,a.child=i.child,a=null):(i=V.treeContext,rt=Kn(j.nextSibling),$t=a,De=!0,ms=null,Hn=!1,i!==null&&Vb(a,i),a=Th(a,u.children),a.flags|=4096);return a}return m?(Ss(),j=u.fallback,m=a.mode,V=i.child,J=V.sibling,u=Lr(V,{mode:"hidden",children:u.children}),u.subtreeFlags=V.subtreeFlags&65011712,J!==null?j=Lr(J,j):(j=fi(j,m,l,null),j.flags|=2),j.return=a,u.return=a,u.sibling=j,a.child=u,Go(null,u),u=a.child,j=i.child.memoizedState,j===null?j=Oh(l):(m=j.cachePool,m!==null?(V=_t._currentValue,m=m.parent!==V?{parent:V,pool:V}:m):m=Wb(),j={baseLanes:j.baseLanes|l,cachePool:m}),u.memoizedState=j,u.childLanes=Rh(i,S,l),a.memoizedState=Nh,Go(i.child,u)):(xs(a),l=i.child,i=l.sibling,l=Lr(l,{mode:"visible",children:u.children}),l.return=a,l.sibling=null,i!==null&&(S=a.deletions,S===null?(a.deletions=[i],a.flags|=16):S.push(i)),a.child=l,a.memoizedState=null,l)}function Th(i,a){return a=Kc({mode:"visible",children:a},i.mode),a.return=i,i.child=a}function Kc(i,a){return i=kn(22,i,null,a),i.lanes=0,i}function Dh(i,a,l){return vi(a,i.child,null,l),i=Th(a,a.pendingProps.children),i.flags|=2,a.memoizedState=null,i}function c0(i,a,l){i.lanes|=a;var u=i.alternate;u!==null&&(u.lanes|=a),Yf(i.return,a,l)}function Ih(i,a,l,u,m,y){var S=i.memoizedState;S===null?i.memoizedState={isBackwards:a,rendering:null,renderingStartTime:0,last:u,tail:l,tailMode:m,treeForkCount:y}:(S.isBackwards=a,S.rendering=null,S.renderingStartTime=0,S.last=u,S.tail=l,S.tailMode=m,S.treeForkCount=y)}function u0(i,a,l){var u=a.pendingProps,m=u.revealOrder,y=u.tail;u=u.children;var S=wt.current,j=(S&2)!==0;if(j?(S=S&1|2,a.flags|=128):S&=1,ae(wt,S),qt(i,a,u,l),u=De?Do:0,!j&&i!==null&&(i.flags&128)!==0)e:for(i=a.child;i!==null;){if(i.tag===13)i.memoizedState!==null&&c0(i,l,a);else if(i.tag===19)c0(i,l,a);else if(i.child!==null){i.child.return=i,i=i.child;continue}if(i===a)break e;for(;i.sibling===null;){if(i.return===null||i.return===a)break e;i=i.return}i.sibling.return=i.return,i=i.sibling}switch(m){case"forwards":for(l=a.child,m=null;l!==null;)i=l.alternate,i!==null&&Mc(i)===null&&(m=l),l=l.sibling;l=m,l===null?(m=a.child,a.child=null):(m=l.sibling,l.sibling=null),Ih(a,!1,m,l,y,u);break;case"backwards":case"unstable_legacy-backwards":for(l=null,m=a.child,a.child=null;m!==null;){if(i=m.alternate,i!==null&&Mc(i)===null){a.child=m;break}i=m.sibling,m.sibling=l,l=m,m=i}Ih(a,!0,l,null,y,u);break;case"together":Ih(a,!1,null,null,void 0,u);break;default:a.memoizedState=null}return a.child}function zr(i,a,l){if(i!==null&&(a.dependencies=i.dependencies),As|=a.lanes,(l&a.childLanes)===0)if(i!==null){if(ga(i,a,l,!1),(l&a.childLanes)===0)return null}else return null;if(i!==null&&a.child!==i.child)throw Error(r(153));if(a.child!==null){for(i=a.child,l=Lr(i,i.pendingProps),a.child=l,l.return=a;i.sibling!==null;)i=i.sibling,l=l.sibling=Lr(i,i.pendingProps),l.return=a;l.sibling=null}return a.child}function Mh(i,a){return(i.lanes&a)!==0?!0:(i=i.dependencies,!!(i!==null&&kc(i)))}function WC(i,a,l){switch(a.tag){case 3:tn(a,a.stateNode.containerInfo),gs(a,_t,i.memoizedState.cache),hi();break;case 27:case 5:bo(a);break;case 4:tn(a,a.stateNode.containerInfo);break;case 10:gs(a,a.type,a.memoizedProps.value);break;case 31:if(a.memoizedState!==null)return a.flags|=128,ah(a),null;break;case 13:var u=a.memoizedState;if(u!==null)return u.dehydrated!==null?(xs(a),a.flags|=128,null):(l&a.child.childLanes)!==0?l0(i,a,l):(xs(a),i=zr(i,a,l),i!==null?i.sibling:null);xs(a);break;case 19:var m=(i.flags&128)!==0;if(u=(l&a.childLanes)!==0,u||(ga(i,a,l,!1),u=(l&a.childLanes)!==0),m){if(u)return u0(i,a,l);a.flags|=128}if(m=a.memoizedState,m!==null&&(m.rendering=null,m.tail=null,m.lastEffect=null),ae(wt,wt.current),u)break;return null;case 22:return a.lanes=0,n0(i,a,l,a.pendingProps);case 24:gs(a,_t,i.memoizedState.cache)}return zr(i,a,l)}function d0(i,a,l){if(i!==null)if(i.memoizedProps!==a.pendingProps)At=!0;else{if(!Mh(i,l)&&(a.flags&128)===0)return At=!1,WC(i,a,l);At=(i.flags&131072)!==0}else At=!1,De&&(a.flags&1048576)!==0&&Pb(a,Do,a.index);switch(a.lanes=0,a.tag){case 16:e:{var u=a.pendingProps;if(i=gi(a.elementType),a.type=i,typeof i=="function")qf(i)?(u=xi(i,u),a.tag=1,a=a0(null,a,i,u,l)):(a.tag=0,a=Ch(null,a,i,u,l));else{if(i!=null){var m=i.$$typeof;if(m===F){a.tag=11,a=Xv(null,a,i,u,l);break e}else if(m===L){a.tag=14,a=e0(null,a,i,u,l);break e}}throw a=O(i)||i,Error(r(306,a,""))}}return a;case 0:return Ch(i,a,a.type,a.pendingProps,l);case 1:return u=a.type,m=xi(u,a.pendingProps),a0(i,a,u,m,l);case 3:e:{if(tn(a,a.stateNode.containerInfo),i===null)throw Error(r(387));u=a.pendingProps;var y=a.memoizedState;m=y.element,th(i,a),Fo(a,u,null,l);var S=a.memoizedState;if(u=S.cache,gs(a,_t,u),u!==y.cache&&Zf(a,[_t],l,!0),qo(),u=S.element,y.isDehydrated)if(y={element:u,isDehydrated:!1,cache:S.cache},a.updateQueue.baseState=y,a.memoizedState=y,a.flags&256){a=o0(i,a,u,l);break e}else if(u!==m){m=zn(Error(r(424)),a),Io(m),a=o0(i,a,u,l);break e}else{switch(i=a.stateNode.containerInfo,i.nodeType){case 9:i=i.body;break;default:i=i.nodeName==="HTML"?i.ownerDocument.body:i}for(rt=Kn(i.firstChild),$t=a,De=!0,ms=null,Hn=!0,l=nv(a,null,u,l),a.child=l;l;)l.flags=l.flags&-3|4096,l=l.sibling}else{if(hi(),u===m){a=zr(i,a,l);break e}qt(i,a,u,l)}a=a.child}return a;case 26:return Gc(i,a),i===null?(l=Sw(a.type,null,a.pendingProps,null))?a.memoizedState=l:De||(l=a.type,i=a.pendingProps,u=cu(je.current).createElement(l),u[Ut]=a,u[dn]=i,Ft(u,l,i),Dt(u),a.stateNode=u):a.memoizedState=Sw(a.type,i.memoizedProps,a.pendingProps,i.memoizedState),null;case 27:return bo(a),i===null&&De&&(u=a.stateNode=vw(a.type,a.pendingProps,je.current),$t=a,Hn=!0,m=rt,Os(a.type)?(pp=m,rt=Kn(u.firstChild)):rt=m),qt(i,a,a.pendingProps.children,l),Gc(i,a),i===null&&(a.flags|=4194304),a.child;case 5:return i===null&&De&&((m=u=rt)&&(u=jN(u,a.type,a.pendingProps,Hn),u!==null?(a.stateNode=u,$t=a,rt=Kn(u.firstChild),Hn=!1,m=!0):m=!1),m||ys(a)),bo(a),m=a.type,y=a.pendingProps,S=i!==null?i.memoizedProps:null,u=y.children,cp(m,y)?u=null:S!==null&&cp(m,S)&&(a.flags|=32),a.memoizedState!==null&&(m=lh(i,a,FC,null,null,l),ol._currentValue=m),Gc(i,a),qt(i,a,u,l),a.child;case 6:return i===null&&De&&((i=l=rt)&&(l=kN(l,a.pendingProps,Hn),l!==null?(a.stateNode=l,$t=a,rt=null,i=!0):i=!1),i||ys(a)),null;case 13:return l0(i,a,l);case 4:return tn(a,a.stateNode.containerInfo),u=a.pendingProps,i===null?a.child=vi(a,null,u,l):qt(i,a,u,l),a.child;case 11:return Xv(i,a,a.type,a.pendingProps,l);case 7:return qt(i,a,a.pendingProps,l),a.child;case 8:return qt(i,a,a.pendingProps.children,l),a.child;case 12:return qt(i,a,a.pendingProps.children,l),a.child;case 10:return u=a.pendingProps,gs(a,a.type,u.value),qt(i,a,u.children,l),a.child;case 9:return m=a.type._context,u=a.pendingProps.children,mi(a),m=Bt(m),u=u(m),a.flags|=1,qt(i,a,u,l),a.child;case 14:return e0(i,a,a.type,a.pendingProps,l);case 15:return t0(i,a,a.type,a.pendingProps,l);case 19:return u0(i,a,l);case 31:return ZC(i,a,l);case 22:return n0(i,a,l,a.pendingProps);case 24:return mi(a),u=Bt(_t),i===null?(m=Jf(),m===null&&(m=Xe,y=Wf(),m.pooledCache=y,y.refCount++,y!==null&&(m.pooledCacheLanes|=l),m=y),a.memoizedState={parent:u,cache:m},eh(a),gs(a,_t,m)):((i.lanes&l)!==0&&(th(i,a),Fo(a,null,null,l),qo()),m=i.memoizedState,y=a.memoizedState,m.parent!==u?(m={parent:u,cache:u},a.memoizedState=m,a.lanes===0&&(a.memoizedState=a.updateQueue.baseState=m),gs(a,_t,u)):(u=y.cache,gs(a,_t,u),u!==m.cache&&Zf(a,[_t],l,!0))),qt(i,a,a.pendingProps.children,l),a.child;case 29:throw a.pendingProps}throw Error(r(156,a.tag))}function Pr(i){i.flags|=4}function Lh(i,a,l,u,m){if((a=(i.mode&32)!==0)&&(a=!1),a){if(i.flags|=16777216,(m&335544128)===m)if(i.stateNode.complete)i.flags|=8192;else if($0())i.flags|=8192;else throw bi=Rc,Xf}else i.flags&=-16777217}function f0(i,a){if(a.type!=="stylesheet"||(a.state.loading&4)!==0)i.flags&=-16777217;else if(i.flags|=16777216,!kw(a))if($0())i.flags|=8192;else throw bi=Rc,Xf}function Yc(i,a){a!==null&&(i.flags|=4),i.flags&16384&&(a=i.tag!==22?Hg():536870912,i.lanes|=a,Na|=a)}function Ko(i,a){if(!De)switch(i.tailMode){case"hidden":a=i.tail;for(var l=null;a!==null;)a.alternate!==null&&(l=a),a=a.sibling;l===null?i.tail=null:l.sibling=null;break;case"collapsed":l=i.tail;for(var u=null;l!==null;)l.alternate!==null&&(u=l),l=l.sibling;u===null?a||i.tail===null?i.tail=null:i.tail.sibling=null:u.sibling=null}}function st(i){var a=i.alternate!==null&&i.alternate.child===i.child,l=0,u=0;if(a)for(var m=i.child;m!==null;)l|=m.lanes|m.childLanes,u|=m.subtreeFlags&65011712,u|=m.flags&65011712,m.return=i,m=m.sibling;else for(m=i.child;m!==null;)l|=m.lanes|m.childLanes,u|=m.subtreeFlags,u|=m.flags,m.return=i,m=m.sibling;return i.subtreeFlags|=u,i.childLanes=l,a}function QC(i,a,l){var u=a.pendingProps;switch(Vf(a),a.tag){case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return st(a),null;case 1:return st(a),null;case 3:return l=a.stateNode,u=null,i!==null&&(u=i.memoizedState.cache),a.memoizedState.cache!==u&&(a.flags|=2048),Br(_t),vt(),l.pendingContext&&(l.context=l.pendingContext,l.pendingContext=null),(i===null||i.child===null)&&(ya(a)?Pr(a):i===null||i.memoizedState.isDehydrated&&(a.flags&256)===0||(a.flags|=1024,Gf())),st(a),null;case 26:var m=a.type,y=a.memoizedState;return i===null?(Pr(a),y!==null?(st(a),f0(a,y)):(st(a),Lh(a,m,null,u,l))):y?y!==i.memoizedState?(Pr(a),st(a),f0(a,y)):(st(a),a.flags&=-16777217):(i=i.memoizedProps,i!==u&&Pr(a),st(a),Lh(a,m,i,u,l)),null;case 27:if(ic(a),l=je.current,m=a.type,i!==null&&a.stateNode!=null)i.memoizedProps!==u&&Pr(a);else{if(!u){if(a.stateNode===null)throw Error(r(166));return st(a),null}i=le.current,ya(a)?Hb(a):(i=vw(m,u,l),a.stateNode=i,Pr(a))}return st(a),null;case 5:if(ic(a),m=a.type,i!==null&&a.stateNode!=null)i.memoizedProps!==u&&Pr(a);else{if(!u){if(a.stateNode===null)throw Error(r(166));return st(a),null}if(y=le.current,ya(a))Hb(a);else{var S=cu(je.current);switch(y){case 1:y=S.createElementNS("http://www.w3.org/2000/svg",m);break;case 2:y=S.createElementNS("http://www.w3.org/1998/Math/MathML",m);break;default:switch(m){case"svg":y=S.createElementNS("http://www.w3.org/2000/svg",m);break;case"math":y=S.createElementNS("http://www.w3.org/1998/Math/MathML",m);break;case"script":y=S.createElement("div"),y.innerHTML="<script><\/script>",y=y.removeChild(y.firstChild);break;case"select":y=typeof u.is=="string"?S.createElement("select",{is:u.is}):S.createElement("select"),u.multiple?y.multiple=!0:u.size&&(y.size=u.size);break;default:y=typeof u.is=="string"?S.createElement(m,{is:u.is}):S.createElement(m)}}y[Ut]=a,y[dn]=u;e:for(S=a.child;S!==null;){if(S.tag===5||S.tag===6)y.appendChild(S.stateNode);else if(S.tag!==4&&S.tag!==27&&S.child!==null){S.child.return=S,S=S.child;continue}if(S===a)break e;for(;S.sibling===null;){if(S.return===null||S.return===a)break e;S=S.return}S.sibling.return=S.return,S=S.sibling}a.stateNode=y;e:switch(Ft(y,m,u),m){case"button":case"input":case"select":case"textarea":u=!!u.autoFocus;break e;case"img":u=!0;break e;default:u=!1}u&&Pr(a)}}return st(a),Lh(a,a.type,i===null?null:i.memoizedProps,a.pendingProps,l),null;case 6:if(i&&a.stateNode!=null)i.memoizedProps!==u&&Pr(a);else{if(typeof u!="string"&&a.stateNode===null)throw Error(r(166));if(i=je.current,ya(a)){if(i=a.stateNode,l=a.memoizedProps,u=null,m=$t,m!==null)switch(m.tag){case 27:case 5:u=m.memoizedProps}i[Ut]=a,i=!!(i.nodeValue===l||u!==null&&u.suppressHydrationWarning===!0||lw(i.nodeValue,l)),i||ys(a,!0)}else i=cu(i).createTextNode(u),i[Ut]=a,a.stateNode=i}return st(a),null;case 31:if(l=a.memoizedState,i===null||i.memoizedState!==null){if(u=ya(a),l!==null){if(i===null){if(!u)throw Error(r(318));if(i=a.memoizedState,i=i!==null?i.dehydrated:null,!i)throw Error(r(557));i[Ut]=a}else hi(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;st(a),i=!1}else l=Gf(),i!==null&&i.memoizedState!==null&&(i.memoizedState.hydrationErrors=l),i=!0;if(!i)return a.flags&256?(Nn(a),a):(Nn(a),null);if((a.flags&128)!==0)throw Error(r(558))}return st(a),null;case 13:if(u=a.memoizedState,i===null||i.memoizedState!==null&&i.memoizedState.dehydrated!==null){if(m=ya(a),u!==null&&u.dehydrated!==null){if(i===null){if(!m)throw Error(r(318));if(m=a.memoizedState,m=m!==null?m.dehydrated:null,!m)throw Error(r(317));m[Ut]=a}else hi(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;st(a),m=!1}else m=Gf(),i!==null&&i.memoizedState!==null&&(i.memoizedState.hydrationErrors=m),m=!0;if(!m)return a.flags&256?(Nn(a),a):(Nn(a),null)}return Nn(a),(a.flags&128)!==0?(a.lanes=l,a):(l=u!==null,i=i!==null&&i.memoizedState!==null,l&&(u=a.child,m=null,u.alternate!==null&&u.alternate.memoizedState!==null&&u.alternate.memoizedState.cachePool!==null&&(m=u.alternate.memoizedState.cachePool.pool),y=null,u.memoizedState!==null&&u.memoizedState.cachePool!==null&&(y=u.memoizedState.cachePool.pool),y!==m&&(u.flags|=2048)),l!==i&&l&&(a.child.flags|=8192),Yc(a,a.updateQueue),st(a),null);case 4:return vt(),i===null&&sp(a.stateNode.containerInfo),st(a),null;case 10:return Br(a.type),st(a),null;case 19:if(ee(wt),u=a.memoizedState,u===null)return st(a),null;if(m=(a.flags&128)!==0,y=u.rendering,y===null)if(m)Ko(u,!1);else{if(ft!==0||i!==null&&(i.flags&128)!==0)for(i=a.child;i!==null;){if(y=Mc(i),y!==null){for(a.flags|=128,Ko(u,!1),i=y.updateQueue,a.updateQueue=i,Yc(a,i),a.subtreeFlags=0,i=l,l=a.child;l!==null;)qb(l,i),l=l.sibling;return ae(wt,wt.current&1|2),De&&Ur(a,u.treeForkCount),a.child}i=i.sibling}u.tail!==null&&_n()>Xc&&(a.flags|=128,m=!0,Ko(u,!1),a.lanes=4194304)}else{if(!m)if(i=Mc(y),i!==null){if(a.flags|=128,m=!0,i=i.updateQueue,a.updateQueue=i,Yc(a,i),Ko(u,!0),u.tail===null&&u.tailMode==="hidden"&&!y.alternate&&!De)return st(a),null}else 2*_n()-u.renderingStartTime>Xc&&l!==536870912&&(a.flags|=128,m=!0,Ko(u,!1),a.lanes=4194304);u.isBackwards?(y.sibling=a.child,a.child=y):(i=u.last,i!==null?i.sibling=y:a.child=y,u.last=y)}return u.tail!==null?(i=u.tail,u.rendering=i,u.tail=i.sibling,u.renderingStartTime=_n(),i.sibling=null,l=wt.current,ae(wt,m?l&1|2:l&1),De&&Ur(a,u.treeForkCount),i):(st(a),null);case 22:case 23:return Nn(a),ih(),u=a.memoizedState!==null,i!==null?i.memoizedState!==null!==u&&(a.flags|=8192):u&&(a.flags|=8192),u?(l&536870912)!==0&&(a.flags&128)===0&&(st(a),a.subtreeFlags&6&&(a.flags|=8192)):st(a),l=a.updateQueue,l!==null&&Yc(a,l.retryQueue),l=null,i!==null&&i.memoizedState!==null&&i.memoizedState.cachePool!==null&&(l=i.memoizedState.cachePool.pool),u=null,a.memoizedState!==null&&a.memoizedState.cachePool!==null&&(u=a.memoizedState.cachePool.pool),u!==l&&(a.flags|=2048),i!==null&&ee(yi),null;case 24:return l=null,i!==null&&(l=i.memoizedState.cache),a.memoizedState.cache!==l&&(a.flags|=2048),Br(_t),st(a),null;case 25:return null;case 30:return null}throw Error(r(156,a.tag))}function JC(i,a){switch(Vf(a),a.tag){case 1:return i=a.flags,i&65536?(a.flags=i&-65537|128,a):null;case 3:return Br(_t),vt(),i=a.flags,(i&65536)!==0&&(i&128)===0?(a.flags=i&-65537|128,a):null;case 26:case 27:case 5:return ic(a),null;case 31:if(a.memoizedState!==null){if(Nn(a),a.alternate===null)throw Error(r(340));hi()}return i=a.flags,i&65536?(a.flags=i&-65537|128,a):null;case 13:if(Nn(a),i=a.memoizedState,i!==null&&i.dehydrated!==null){if(a.alternate===null)throw Error(r(340));hi()}return i=a.flags,i&65536?(a.flags=i&-65537|128,a):null;case 19:return ee(wt),null;case 4:return vt(),null;case 10:return Br(a.type),null;case 22:case 23:return Nn(a),ih(),i!==null&&ee(yi),i=a.flags,i&65536?(a.flags=i&-65537|128,a):null;case 24:return Br(_t),null;case 25:return null;default:return null}}function h0(i,a){switch(Vf(a),a.tag){case 3:Br(_t),vt();break;case 26:case 27:case 5:ic(a);break;case 4:vt();break;case 31:a.memoizedState!==null&&Nn(a);break;case 13:Nn(a);break;case 19:ee(wt);break;case 10:Br(a.type);break;case 22:case 23:Nn(a),ih(),i!==null&&ee(yi);break;case 24:Br(_t)}}function Yo(i,a){try{var l=a.updateQueue,u=l!==null?l.lastEffect:null;if(u!==null){var m=u.next;l=m;do{if((l.tag&i)===i){u=void 0;var y=l.create,S=l.inst;u=y(),S.destroy=u}l=l.next}while(l!==m)}}catch(j){Ge(a,a.return,j)}}function _s(i,a,l){try{var u=a.updateQueue,m=u!==null?u.lastEffect:null;if(m!==null){var y=m.next;u=y;do{if((u.tag&i)===i){var S=u.inst,j=S.destroy;if(j!==void 0){S.destroy=void 0,m=a;var V=l,J=j;try{J()}catch(ne){Ge(m,V,ne)}}}u=u.next}while(u!==y)}}catch(ne){Ge(a,a.return,ne)}}function p0(i){var a=i.updateQueue;if(a!==null){var l=i.stateNode;try{sv(a,l)}catch(u){Ge(i,i.return,u)}}}function m0(i,a,l){l.props=xi(i.type,i.memoizedProps),l.state=i.memoizedState;try{l.componentWillUnmount()}catch(u){Ge(i,a,u)}}function Zo(i,a){try{var l=i.ref;if(l!==null){switch(i.tag){case 26:case 27:case 5:var u=i.stateNode;break;case 30:u=i.stateNode;break;default:u=i.stateNode}typeof l=="function"?i.refCleanup=l(u):l.current=u}}catch(m){Ge(i,a,m)}}function yr(i,a){var l=i.ref,u=i.refCleanup;if(l!==null)if(typeof u=="function")try{u()}catch(m){Ge(i,a,m)}finally{i.refCleanup=null,i=i.alternate,i!=null&&(i.refCleanup=null)}else if(typeof l=="function")try{l(null)}catch(m){Ge(i,a,m)}else l.current=null}function y0(i){var a=i.type,l=i.memoizedProps,u=i.stateNode;try{e:switch(a){case"button":case"input":case"select":case"textarea":l.autoFocus&&u.focus();break e;case"img":l.src?u.src=l.src:l.srcSet&&(u.srcset=l.srcSet)}}catch(m){Ge(i,i.return,m)}}function Uh(i,a,l){try{var u=i.stateNode;wN(u,i.type,l,a),u[dn]=a}catch(m){Ge(i,i.return,m)}}function g0(i){return i.tag===5||i.tag===3||i.tag===26||i.tag===27&&Os(i.type)||i.tag===4}function $h(i){e:for(;;){for(;i.sibling===null;){if(i.return===null||g0(i.return))return null;i=i.return}for(i.sibling.return=i.return,i=i.sibling;i.tag!==5&&i.tag!==6&&i.tag!==18;){if(i.tag===27&&Os(i.type)||i.flags&2||i.child===null||i.tag===4)continue e;i.child.return=i,i=i.child}if(!(i.flags&2))return i.stateNode}}function Bh(i,a,l){var u=i.tag;if(u===5||u===6)i=i.stateNode,a?(l.nodeType===9?l.body:l.nodeName==="HTML"?l.ownerDocument.body:l).insertBefore(i,a):(a=l.nodeType===9?l.body:l.nodeName==="HTML"?l.ownerDocument.body:l,a.appendChild(i),l=l._reactRootContainer,l!=null||a.onclick!==null||(a.onclick=Ir));else if(u!==4&&(u===27&&Os(i.type)&&(l=i.stateNode,a=null),i=i.child,i!==null))for(Bh(i,a,l),i=i.sibling;i!==null;)Bh(i,a,l),i=i.sibling}function Zc(i,a,l){var u=i.tag;if(u===5||u===6)i=i.stateNode,a?l.insertBefore(i,a):l.appendChild(i);else if(u!==4&&(u===27&&Os(i.type)&&(l=i.stateNode),i=i.child,i!==null))for(Zc(i,a,l),i=i.sibling;i!==null;)Zc(i,a,l),i=i.sibling}function b0(i){var a=i.stateNode,l=i.memoizedProps;try{for(var u=i.type,m=a.attributes;m.length;)a.removeAttributeNode(m[0]);Ft(a,u,l),a[Ut]=i,a[dn]=l}catch(y){Ge(i,i.return,y)}}var Vr=!1,jt=!1,qh=!1,v0=typeof WeakSet=="function"?WeakSet:Set,It=null;function XC(i,a){if(i=i.containerInfo,op=yu,i=Rb(i),Df(i)){if("selectionStart"in i)var l={start:i.selectionStart,end:i.selectionEnd};else e:{l=(l=i.ownerDocument)&&l.defaultView||window;var u=l.getSelection&&l.getSelection();if(u&&u.rangeCount!==0){l=u.anchorNode;var m=u.anchorOffset,y=u.focusNode;u=u.focusOffset;try{l.nodeType,y.nodeType}catch{l=null;break e}var S=0,j=-1,V=-1,J=0,ne=0,ie=i,X=null;t:for(;;){for(var te;ie!==l||m!==0&&ie.nodeType!==3||(j=S+m),ie!==y||u!==0&&ie.nodeType!==3||(V=S+u),ie.nodeType===3&&(S+=ie.nodeValue.length),(te=ie.firstChild)!==null;)X=ie,ie=te;for(;;){if(ie===i)break t;if(X===l&&++J===m&&(j=S),X===y&&++ne===u&&(V=S),(te=ie.nextSibling)!==null)break;ie=X,X=ie.parentNode}ie=te}l=j===-1||V===-1?null:{start:j,end:V}}else l=null}l=l||{start:0,end:0}}else l=null;for(lp={focusedElem:i,selectionRange:l},yu=!1,It=a;It!==null;)if(a=It,i=a.child,(a.subtreeFlags&1028)!==0&&i!==null)i.return=a,It=i;else for(;It!==null;){switch(a=It,y=a.alternate,i=a.flags,a.tag){case 0:if((i&4)!==0&&(i=a.updateQueue,i=i!==null?i.events:null,i!==null))for(l=0;l<i.length;l++)m=i[l],m.ref.impl=m.nextImpl;break;case 11:case 15:break;case 1:if((i&1024)!==0&&y!==null){i=void 0,l=a,m=y.memoizedProps,y=y.memoizedState,u=l.stateNode;try{var de=xi(l.type,m);i=u.getSnapshotBeforeUpdate(de,y),u.__reactInternalSnapshotBeforeUpdate=i}catch(me){Ge(l,l.return,me)}}break;case 3:if((i&1024)!==0){if(i=a.stateNode.containerInfo,l=i.nodeType,l===9)dp(i);else if(l===1)switch(i.nodeName){case"HEAD":case"HTML":case"BODY":dp(i);break;default:i.textContent=""}}break;case 5:case 26:case 27:case 6:case 4:case 17:break;default:if((i&1024)!==0)throw Error(r(163))}if(i=a.sibling,i!==null){i.return=a.return,It=i;break}It=a.return}}function w0(i,a,l){var u=l.flags;switch(l.tag){case 0:case 11:case 15:Gr(i,l),u&4&&Yo(5,l);break;case 1:if(Gr(i,l),u&4)if(i=l.stateNode,a===null)try{i.componentDidMount()}catch(S){Ge(l,l.return,S)}else{var m=xi(l.type,a.memoizedProps);a=a.memoizedState;try{i.componentDidUpdate(m,a,i.__reactInternalSnapshotBeforeUpdate)}catch(S){Ge(l,l.return,S)}}u&64&&p0(l),u&512&&Zo(l,l.return);break;case 3:if(Gr(i,l),u&64&&(i=l.updateQueue,i!==null)){if(a=null,l.child!==null)switch(l.child.tag){case 27:case 5:a=l.child.stateNode;break;case 1:a=l.child.stateNode}try{sv(i,a)}catch(S){Ge(l,l.return,S)}}break;case 27:a===null&&u&4&&b0(l);case 26:case 5:Gr(i,l),a===null&&u&4&&y0(l),u&512&&Zo(l,l.return);break;case 12:Gr(i,l);break;case 31:Gr(i,l),u&4&&_0(i,l);break;case 13:Gr(i,l),u&4&&E0(i,l),u&64&&(i=l.memoizedState,i!==null&&(i=i.dehydrated,i!==null&&(l=lN.bind(null,l),CN(i,l))));break;case 22:if(u=l.memoizedState!==null||Vr,!u){a=a!==null&&a.memoizedState!==null||jt,m=Vr;var y=jt;Vr=u,(jt=a)&&!y?Kr(i,l,(l.subtreeFlags&8772)!==0):Gr(i,l),Vr=m,jt=y}break;case 30:break;default:Gr(i,l)}}function x0(i){var a=i.alternate;a!==null&&(i.alternate=null,x0(a)),i.child=null,i.deletions=null,i.sibling=null,i.tag===5&&(a=i.stateNode,a!==null&&yf(a)),i.stateNode=null,i.return=null,i.dependencies=null,i.memoizedProps=null,i.memoizedState=null,i.pendingProps=null,i.stateNode=null,i.updateQueue=null}var ot=null,hn=!1;function Hr(i,a,l){for(l=l.child;l!==null;)S0(i,a,l),l=l.sibling}function S0(i,a,l){if(En&&typeof En.onCommitFiberUnmount=="function")try{En.onCommitFiberUnmount(vo,l)}catch{}switch(l.tag){case 26:jt||yr(l,a),Hr(i,a,l),l.memoizedState?l.memoizedState.count--:l.stateNode&&(l=l.stateNode,l.parentNode.removeChild(l));break;case 27:jt||yr(l,a);var u=ot,m=hn;Os(l.type)&&(ot=l.stateNode,hn=!1),Hr(i,a,l),sl(l.stateNode),ot=u,hn=m;break;case 5:jt||yr(l,a);case 6:if(u=ot,m=hn,ot=null,Hr(i,a,l),ot=u,hn=m,ot!==null)if(hn)try{(ot.nodeType===9?ot.body:ot.nodeName==="HTML"?ot.ownerDocument.body:ot).removeChild(l.stateNode)}catch(y){Ge(l,a,y)}else try{ot.removeChild(l.stateNode)}catch(y){Ge(l,a,y)}break;case 18:ot!==null&&(hn?(i=ot,pw(i.nodeType===9?i.body:i.nodeName==="HTML"?i.ownerDocument.body:i,l.stateNode),Ua(i)):pw(ot,l.stateNode));break;case 4:u=ot,m=hn,ot=l.stateNode.containerInfo,hn=!0,Hr(i,a,l),ot=u,hn=m;break;case 0:case 11:case 14:case 15:_s(2,l,a),jt||_s(4,l,a),Hr(i,a,l);break;case 1:jt||(yr(l,a),u=l.stateNode,typeof u.componentWillUnmount=="function"&&m0(l,a,u)),Hr(i,a,l);break;case 21:Hr(i,a,l);break;case 22:jt=(u=jt)||l.memoizedState!==null,Hr(i,a,l),jt=u;break;default:Hr(i,a,l)}}function _0(i,a){if(a.memoizedState===null&&(i=a.alternate,i!==null&&(i=i.memoizedState,i!==null))){i=i.dehydrated;try{Ua(i)}catch(l){Ge(a,a.return,l)}}}function E0(i,a){if(a.memoizedState===null&&(i=a.alternate,i!==null&&(i=i.memoizedState,i!==null&&(i=i.dehydrated,i!==null))))try{Ua(i)}catch(l){Ge(a,a.return,l)}}function eN(i){switch(i.tag){case 31:case 13:case 19:var a=i.stateNode;return a===null&&(a=i.stateNode=new v0),a;case 22:return i=i.stateNode,a=i._retryCache,a===null&&(a=i._retryCache=new v0),a;default:throw Error(r(435,i.tag))}}function Wc(i,a){var l=eN(i);a.forEach(function(u){if(!l.has(u)){l.add(u);var m=cN.bind(null,i,u);u.then(m,m)}})}function pn(i,a){var l=a.deletions;if(l!==null)for(var u=0;u<l.length;u++){var m=l[u],y=i,S=a,j=S;e:for(;j!==null;){switch(j.tag){case 27:if(Os(j.type)){ot=j.stateNode,hn=!1;break e}break;case 5:ot=j.stateNode,hn=!1;break e;case 3:case 4:ot=j.stateNode.containerInfo,hn=!0;break e}j=j.return}if(ot===null)throw Error(r(160));S0(y,S,m),ot=null,hn=!1,y=m.alternate,y!==null&&(y.return=null),m.return=null}if(a.subtreeFlags&13886)for(a=a.child;a!==null;)A0(a,i),a=a.sibling}var ir=null;function A0(i,a){var l=i.alternate,u=i.flags;switch(i.tag){case 0:case 11:case 14:case 15:pn(a,i),mn(i),u&4&&(_s(3,i,i.return),Yo(3,i),_s(5,i,i.return));break;case 1:pn(a,i),mn(i),u&512&&(jt||l===null||yr(l,l.return)),u&64&&Vr&&(i=i.updateQueue,i!==null&&(u=i.callbacks,u!==null&&(l=i.shared.hiddenCallbacks,i.shared.hiddenCallbacks=l===null?u:l.concat(u))));break;case 26:var m=ir;if(pn(a,i),mn(i),u&512&&(jt||l===null||yr(l,l.return)),u&4){var y=l!==null?l.memoizedState:null;if(u=i.memoizedState,l===null)if(u===null)if(i.stateNode===null){e:{u=i.type,l=i.memoizedProps,m=m.ownerDocument||m;t:switch(u){case"title":y=m.getElementsByTagName("title")[0],(!y||y[So]||y[Ut]||y.namespaceURI==="http://www.w3.org/2000/svg"||y.hasAttribute("itemprop"))&&(y=m.createElement(u),m.head.insertBefore(y,m.querySelector("head > title"))),Ft(y,u,l),y[Ut]=i,Dt(y),u=y;break e;case"link":var S=Aw("link","href",m).get(u+(l.href||""));if(S){for(var j=0;j<S.length;j++)if(y=S[j],y.getAttribute("href")===(l.href==null||l.href===""?null:l.href)&&y.getAttribute("rel")===(l.rel==null?null:l.rel)&&y.getAttribute("title")===(l.title==null?null:l.title)&&y.getAttribute("crossorigin")===(l.crossOrigin==null?null:l.crossOrigin)){S.splice(j,1);break t}}y=m.createElement(u),Ft(y,u,l),m.head.appendChild(y);break;case"meta":if(S=Aw("meta","content",m).get(u+(l.content||""))){for(j=0;j<S.length;j++)if(y=S[j],y.getAttribute("content")===(l.content==null?null:""+l.content)&&y.getAttribute("name")===(l.name==null?null:l.name)&&y.getAttribute("property")===(l.property==null?null:l.property)&&y.getAttribute("http-equiv")===(l.httpEquiv==null?null:l.httpEquiv)&&y.getAttribute("charset")===(l.charSet==null?null:l.charSet)){S.splice(j,1);break t}}y=m.createElement(u),Ft(y,u,l),m.head.appendChild(y);break;default:throw Error(r(468,u))}y[Ut]=i,Dt(y),u=y}i.stateNode=u}else jw(m,i.type,i.stateNode);else i.stateNode=Ew(m,u,i.memoizedProps);else y!==u?(y===null?l.stateNode!==null&&(l=l.stateNode,l.parentNode.removeChild(l)):y.count--,u===null?jw(m,i.type,i.stateNode):Ew(m,u,i.memoizedProps)):u===null&&i.stateNode!==null&&Uh(i,i.memoizedProps,l.memoizedProps)}break;case 27:pn(a,i),mn(i),u&512&&(jt||l===null||yr(l,l.return)),l!==null&&u&4&&Uh(i,i.memoizedProps,l.memoizedProps);break;case 5:if(pn(a,i),mn(i),u&512&&(jt||l===null||yr(l,l.return)),i.flags&32){m=i.stateNode;try{aa(m,"")}catch(de){Ge(i,i.return,de)}}u&4&&i.stateNode!=null&&(m=i.memoizedProps,Uh(i,m,l!==null?l.memoizedProps:m)),u&1024&&(qh=!0);break;case 6:if(pn(a,i),mn(i),u&4){if(i.stateNode===null)throw Error(r(162));u=i.memoizedProps,l=i.stateNode;try{l.nodeValue=u}catch(de){Ge(i,i.return,de)}}break;case 3:if(fu=null,m=ir,ir=uu(a.containerInfo),pn(a,i),ir=m,mn(i),u&4&&l!==null&&l.memoizedState.isDehydrated)try{Ua(a.containerInfo)}catch(de){Ge(i,i.return,de)}qh&&(qh=!1,j0(i));break;case 4:u=ir,ir=uu(i.stateNode.containerInfo),pn(a,i),mn(i),ir=u;break;case 12:pn(a,i),mn(i);break;case 31:pn(a,i),mn(i),u&4&&(u=i.updateQueue,u!==null&&(i.updateQueue=null,Wc(i,u)));break;case 13:pn(a,i),mn(i),i.child.flags&8192&&i.memoizedState!==null!=(l!==null&&l.memoizedState!==null)&&(Jc=_n()),u&4&&(u=i.updateQueue,u!==null&&(i.updateQueue=null,Wc(i,u)));break;case 22:m=i.memoizedState!==null;var V=l!==null&&l.memoizedState!==null,J=Vr,ne=jt;if(Vr=J||m,jt=ne||V,pn(a,i),jt=ne,Vr=J,mn(i),u&8192)e:for(a=i.stateNode,a._visibility=m?a._visibility&-2:a._visibility|1,m&&(l===null||V||Vr||jt||Si(i)),l=null,a=i;;){if(a.tag===5||a.tag===26){if(l===null){V=l=a;try{if(y=V.stateNode,m)S=y.style,typeof S.setProperty=="function"?S.setProperty("display","none","important"):S.display="none";else{j=V.stateNode;var ie=V.memoizedProps.style,X=ie!=null&&ie.hasOwnProperty("display")?ie.display:null;j.style.display=X==null||typeof X=="boolean"?"":(""+X).trim()}}catch(de){Ge(V,V.return,de)}}}else if(a.tag===6){if(l===null){V=a;try{V.stateNode.nodeValue=m?"":V.memoizedProps}catch(de){Ge(V,V.return,de)}}}else if(a.tag===18){if(l===null){V=a;try{var te=V.stateNode;m?mw(te,!0):mw(V.stateNode,!1)}catch(de){Ge(V,V.return,de)}}}else if((a.tag!==22&&a.tag!==23||a.memoizedState===null||a===i)&&a.child!==null){a.child.return=a,a=a.child;continue}if(a===i)break e;for(;a.sibling===null;){if(a.return===null||a.return===i)break e;l===a&&(l=null),a=a.return}l===a&&(l=null),a.sibling.return=a.return,a=a.sibling}u&4&&(u=i.updateQueue,u!==null&&(l=u.retryQueue,l!==null&&(u.retryQueue=null,Wc(i,l))));break;case 19:pn(a,i),mn(i),u&4&&(u=i.updateQueue,u!==null&&(i.updateQueue=null,Wc(i,u)));break;case 30:break;case 21:break;default:pn(a,i),mn(i)}}function mn(i){var a=i.flags;if(a&2){try{for(var l,u=i.return;u!==null;){if(g0(u)){l=u;break}u=u.return}if(l==null)throw Error(r(160));switch(l.tag){case 27:var m=l.stateNode,y=$h(i);Zc(i,y,m);break;case 5:var S=l.stateNode;l.flags&32&&(aa(S,""),l.flags&=-33);var j=$h(i);Zc(i,j,S);break;case 3:case 4:var V=l.stateNode.containerInfo,J=$h(i);Bh(i,J,V);break;default:throw Error(r(161))}}catch(ne){Ge(i,i.return,ne)}i.flags&=-3}a&4096&&(i.flags&=-4097)}function j0(i){if(i.subtreeFlags&1024)for(i=i.child;i!==null;){var a=i;j0(a),a.tag===5&&a.flags&1024&&a.stateNode.reset(),i=i.sibling}}function Gr(i,a){if(a.subtreeFlags&8772)for(a=a.child;a!==null;)w0(i,a.alternate,a),a=a.sibling}function Si(i){for(i=i.child;i!==null;){var a=i;switch(a.tag){case 0:case 11:case 14:case 15:_s(4,a,a.return),Si(a);break;case 1:yr(a,a.return);var l=a.stateNode;typeof l.componentWillUnmount=="function"&&m0(a,a.return,l),Si(a);break;case 27:sl(a.stateNode);case 26:case 5:yr(a,a.return),Si(a);break;case 22:a.memoizedState===null&&Si(a);break;case 30:Si(a);break;default:Si(a)}i=i.sibling}}function Kr(i,a,l){for(l=l&&(a.subtreeFlags&8772)!==0,a=a.child;a!==null;){var u=a.alternate,m=i,y=a,S=y.flags;switch(y.tag){case 0:case 11:case 15:Kr(m,y,l),Yo(4,y);break;case 1:if(Kr(m,y,l),u=y,m=u.stateNode,typeof m.componentDidMount=="function")try{m.componentDidMount()}catch(J){Ge(u,u.return,J)}if(u=y,m=u.updateQueue,m!==null){var j=u.stateNode;try{var V=m.shared.hiddenCallbacks;if(V!==null)for(m.shared.hiddenCallbacks=null,m=0;m<V.length;m++)rv(V[m],j)}catch(J){Ge(u,u.return,J)}}l&&S&64&&p0(y),Zo(y,y.return);break;case 27:b0(y);case 26:case 5:Kr(m,y,l),l&&u===null&&S&4&&y0(y),Zo(y,y.return);break;case 12:Kr(m,y,l);break;case 31:Kr(m,y,l),l&&S&4&&_0(m,y);break;case 13:Kr(m,y,l),l&&S&4&&E0(m,y);break;case 22:y.memoizedState===null&&Kr(m,y,l),Zo(y,y.return);break;case 30:break;default:Kr(m,y,l)}a=a.sibling}}function Fh(i,a){var l=null;i!==null&&i.memoizedState!==null&&i.memoizedState.cachePool!==null&&(l=i.memoizedState.cachePool.pool),i=null,a.memoizedState!==null&&a.memoizedState.cachePool!==null&&(i=a.memoizedState.cachePool.pool),i!==l&&(i!=null&&i.refCount++,l!=null&&Mo(l))}function zh(i,a){i=null,a.alternate!==null&&(i=a.alternate.memoizedState.cache),a=a.memoizedState.cache,a!==i&&(a.refCount++,i!=null&&Mo(i))}function ar(i,a,l,u){if(a.subtreeFlags&10256)for(a=a.child;a!==null;)k0(i,a,l,u),a=a.sibling}function k0(i,a,l,u){var m=a.flags;switch(a.tag){case 0:case 11:case 15:ar(i,a,l,u),m&2048&&Yo(9,a);break;case 1:ar(i,a,l,u);break;case 3:ar(i,a,l,u),m&2048&&(i=null,a.alternate!==null&&(i=a.alternate.memoizedState.cache),a=a.memoizedState.cache,a!==i&&(a.refCount++,i!=null&&Mo(i)));break;case 12:if(m&2048){ar(i,a,l,u),i=a.stateNode;try{var y=a.memoizedProps,S=y.id,j=y.onPostCommit;typeof j=="function"&&j(S,a.alternate===null?"mount":"update",i.passiveEffectDuration,-0)}catch(V){Ge(a,a.return,V)}}else ar(i,a,l,u);break;case 31:ar(i,a,l,u);break;case 13:ar(i,a,l,u);break;case 23:break;case 22:y=a.stateNode,S=a.alternate,a.memoizedState!==null?y._visibility&2?ar(i,a,l,u):Wo(i,a):y._visibility&2?ar(i,a,l,u):(y._visibility|=2,ja(i,a,l,u,(a.subtreeFlags&10256)!==0||!1)),m&2048&&Fh(S,a);break;case 24:ar(i,a,l,u),m&2048&&zh(a.alternate,a);break;default:ar(i,a,l,u)}}function ja(i,a,l,u,m){for(m=m&&((a.subtreeFlags&10256)!==0||!1),a=a.child;a!==null;){var y=i,S=a,j=l,V=u,J=S.flags;switch(S.tag){case 0:case 11:case 15:ja(y,S,j,V,m),Yo(8,S);break;case 23:break;case 22:var ne=S.stateNode;S.memoizedState!==null?ne._visibility&2?ja(y,S,j,V,m):Wo(y,S):(ne._visibility|=2,ja(y,S,j,V,m)),m&&J&2048&&Fh(S.alternate,S);break;case 24:ja(y,S,j,V,m),m&&J&2048&&zh(S.alternate,S);break;default:ja(y,S,j,V,m)}a=a.sibling}}function Wo(i,a){if(a.subtreeFlags&10256)for(a=a.child;a!==null;){var l=i,u=a,m=u.flags;switch(u.tag){case 22:Wo(l,u),m&2048&&Fh(u.alternate,u);break;case 24:Wo(l,u),m&2048&&zh(u.alternate,u);break;default:Wo(l,u)}a=a.sibling}}var Qo=8192;function ka(i,a,l){if(i.subtreeFlags&Qo)for(i=i.child;i!==null;)C0(i,a,l),i=i.sibling}function C0(i,a,l){switch(i.tag){case 26:ka(i,a,l),i.flags&Qo&&i.memoizedState!==null&&qN(l,ir,i.memoizedState,i.memoizedProps);break;case 5:ka(i,a,l);break;case 3:case 4:var u=ir;ir=uu(i.stateNode.containerInfo),ka(i,a,l),ir=u;break;case 22:i.memoizedState===null&&(u=i.alternate,u!==null&&u.memoizedState!==null?(u=Qo,Qo=16777216,ka(i,a,l),Qo=u):ka(i,a,l));break;default:ka(i,a,l)}}function N0(i){var a=i.alternate;if(a!==null&&(i=a.child,i!==null)){a.child=null;do a=i.sibling,i.sibling=null,i=a;while(i!==null)}}function Jo(i){var a=i.deletions;if((i.flags&16)!==0){if(a!==null)for(var l=0;l<a.length;l++){var u=a[l];It=u,R0(u,i)}N0(i)}if(i.subtreeFlags&10256)for(i=i.child;i!==null;)O0(i),i=i.sibling}function O0(i){switch(i.tag){case 0:case 11:case 15:Jo(i),i.flags&2048&&_s(9,i,i.return);break;case 3:Jo(i);break;case 12:Jo(i);break;case 22:var a=i.stateNode;i.memoizedState!==null&&a._visibility&2&&(i.return===null||i.return.tag!==13)?(a._visibility&=-3,Qc(i)):Jo(i);break;default:Jo(i)}}function Qc(i){var a=i.deletions;if((i.flags&16)!==0){if(a!==null)for(var l=0;l<a.length;l++){var u=a[l];It=u,R0(u,i)}N0(i)}for(i=i.child;i!==null;){switch(a=i,a.tag){case 0:case 11:case 15:_s(8,a,a.return),Qc(a);break;case 22:l=a.stateNode,l._visibility&2&&(l._visibility&=-3,Qc(a));break;default:Qc(a)}i=i.sibling}}function R0(i,a){for(;It!==null;){var l=It;switch(l.tag){case 0:case 11:case 15:_s(8,l,a);break;case 23:case 22:if(l.memoizedState!==null&&l.memoizedState.cachePool!==null){var u=l.memoizedState.cachePool.pool;u!=null&&u.refCount++}break;case 24:Mo(l.memoizedState.cache)}if(u=l.child,u!==null)u.return=l,It=u;else e:for(l=i;It!==null;){u=It;var m=u.sibling,y=u.return;if(x0(u),u===l){It=null;break e}if(m!==null){m.return=y,It=m;break e}It=y}}}var tN={getCacheForType:function(i){var a=Bt(_t),l=a.data.get(i);return l===void 0&&(l=i(),a.data.set(i,l)),l},cacheSignal:function(){return Bt(_t).controller.signal}},nN=typeof WeakMap=="function"?WeakMap:Map,ze=0,Xe=null,ke=null,Ne=0,He=0,On=null,Es=!1,Ca=!1,Ph=!1,Yr=0,ft=0,As=0,_i=0,Vh=0,Rn=0,Na=0,Xo=null,yn=null,Hh=!1,Jc=0,T0=0,Xc=1/0,eu=null,js=null,Ot=0,ks=null,Oa=null,Zr=0,Gh=0,Kh=null,D0=null,el=0,Yh=null;function Tn(){return(ze&2)!==0&&Ne!==0?Ne&-Ne:P.T!==null?ep():Zg()}function I0(){if(Rn===0)if((Ne&536870912)===0||De){var i=lc;lc<<=1,(lc&3932160)===0&&(lc=262144),Rn=i}else Rn=536870912;return i=Cn.current,i!==null&&(i.flags|=32),Rn}function gn(i,a,l){(i===Xe&&(He===2||He===9)||i.cancelPendingCommit!==null)&&(Ra(i,0),Cs(i,Ne,Rn,!1)),xo(i,l),((ze&2)===0||i!==Xe)&&(i===Xe&&((ze&2)===0&&(_i|=l),ft===4&&Cs(i,Ne,Rn,!1)),gr(i))}function M0(i,a,l){if((ze&6)!==0)throw Error(r(327));var u=!l&&(a&127)===0&&(a&i.expiredLanes)===0||wo(i,a),m=u?iN(i,a):Wh(i,a,!0),y=u;do{if(m===0){Ca&&!u&&Cs(i,a,0,!1);break}else{if(l=i.current.alternate,y&&!rN(l)){m=Wh(i,a,!1),y=!1;continue}if(m===2){if(y=a,i.errorRecoveryDisabledLanes&y)var S=0;else S=i.pendingLanes&-536870913,S=S!==0?S:S&536870912?536870912:0;if(S!==0){a=S;e:{var j=i;m=Xo;var V=j.current.memoizedState.isDehydrated;if(V&&(Ra(j,S).flags|=256),S=Wh(j,S,!1),S!==2){if(Ph&&!V){j.errorRecoveryDisabledLanes|=y,_i|=y,m=4;break e}y=yn,yn=m,y!==null&&(yn===null?yn=y:yn.push.apply(yn,y))}m=S}if(y=!1,m!==2)continue}}if(m===1){Ra(i,0),Cs(i,a,0,!0);break}e:{switch(u=i,y=m,y){case 0:case 1:throw Error(r(345));case 4:if((a&4194048)!==a)break;case 6:Cs(u,a,Rn,!Es);break e;case 2:yn=null;break;case 3:case 5:break;default:throw Error(r(329))}if((a&62914560)===a&&(m=Jc+300-_n(),10<m)){if(Cs(u,a,Rn,!Es),uc(u,0,!0)!==0)break e;Zr=a,u.timeoutHandle=fw(L0.bind(null,u,l,yn,eu,Hh,a,Rn,_i,Na,Es,y,"Throttled",-0,0),m);break e}L0(u,l,yn,eu,Hh,a,Rn,_i,Na,Es,y,null,-0,0)}}break}while(!0);gr(i)}function L0(i,a,l,u,m,y,S,j,V,J,ne,ie,X,te){if(i.timeoutHandle=-1,ie=a.subtreeFlags,ie&8192||(ie&16785408)===16785408){ie={stylesheets:null,count:0,imgCount:0,imgBytes:0,suspenseyImages:[],waitingForImages:!0,waitingForViewTransition:!1,unsuspend:Ir},C0(a,y,ie);var de=(y&62914560)===y?Jc-_n():(y&4194048)===y?T0-_n():0;if(de=FN(ie,de),de!==null){Zr=y,i.cancelPendingCommit=de(V0.bind(null,i,a,y,l,u,m,S,j,V,ne,ie,null,X,te)),Cs(i,y,S,!J);return}}V0(i,a,y,l,u,m,S,j,V)}function rN(i){for(var a=i;;){var l=a.tag;if((l===0||l===11||l===15)&&a.flags&16384&&(l=a.updateQueue,l!==null&&(l=l.stores,l!==null)))for(var u=0;u<l.length;u++){var m=l[u],y=m.getSnapshot;m=m.value;try{if(!jn(y(),m))return!1}catch{return!1}}if(l=a.child,a.subtreeFlags&16384&&l!==null)l.return=a,a=l;else{if(a===i)break;for(;a.sibling===null;){if(a.return===null||a.return===i)return!0;a=a.return}a.sibling.return=a.return,a=a.sibling}}return!0}function Cs(i,a,l,u){a&=~Vh,a&=~_i,i.suspendedLanes|=a,i.pingedLanes&=~a,u&&(i.warmLanes|=a),u=i.expirationTimes;for(var m=a;0<m;){var y=31-An(m),S=1<<y;u[y]=-1,m&=~S}l!==0&&Gg(i,l,a)}function tu(){return(ze&6)===0?(tl(0),!1):!0}function Zh(){if(ke!==null){if(He===0)var i=ke.return;else i=ke,$r=pi=null,dh(i),xa=null,Uo=0,i=ke;for(;i!==null;)h0(i.alternate,i),i=i.return;ke=null}}function Ra(i,a){var l=i.timeoutHandle;l!==-1&&(i.timeoutHandle=-1,_N(l)),l=i.cancelPendingCommit,l!==null&&(i.cancelPendingCommit=null,l()),Zr=0,Zh(),Xe=i,ke=l=Lr(i.current,null),Ne=a,He=0,On=null,Es=!1,Ca=wo(i,a),Ph=!1,Na=Rn=Vh=_i=As=ft=0,yn=Xo=null,Hh=!1,(a&8)!==0&&(a|=a&32);var u=i.entangledLanes;if(u!==0)for(i=i.entanglements,u&=a;0<u;){var m=31-An(u),y=1<<m;a|=i[m],u&=~y}return Yr=a,Sc(),l}function U0(i,a){xe=null,P.H=Ho,a===wa||a===Oc?(a=Xb(),He=3):a===Xf?(a=Xb(),He=4):He=a===kh?8:a!==null&&typeof a=="object"&&typeof a.then=="function"?6:1,On=a,ke===null&&(ft=1,Vc(i,zn(a,i.current)))}function $0(){var i=Cn.current;return i===null?!0:(Ne&4194048)===Ne?Gn===null:(Ne&62914560)===Ne||(Ne&536870912)!==0?i===Gn:!1}function B0(){var i=P.H;return P.H=Ho,i===null?Ho:i}function q0(){var i=P.A;return P.A=tN,i}function nu(){ft=4,Es||(Ne&4194048)!==Ne&&Cn.current!==null||(Ca=!0),(As&134217727)===0&&(_i&134217727)===0||Xe===null||Cs(Xe,Ne,Rn,!1)}function Wh(i,a,l){var u=ze;ze|=2;var m=B0(),y=q0();(Xe!==i||Ne!==a)&&(eu=null,Ra(i,a)),a=!1;var S=ft;e:do try{if(He!==0&&ke!==null){var j=ke,V=On;switch(He){case 8:Zh(),S=6;break e;case 3:case 2:case 9:case 6:Cn.current===null&&(a=!0);var J=He;if(He=0,On=null,Ta(i,j,V,J),l&&Ca){S=0;break e}break;default:J=He,He=0,On=null,Ta(i,j,V,J)}}sN(),S=ft;break}catch(ne){U0(i,ne)}while(!0);return a&&i.shellSuspendCounter++,$r=pi=null,ze=u,P.H=m,P.A=y,ke===null&&(Xe=null,Ne=0,Sc()),S}function sN(){for(;ke!==null;)F0(ke)}function iN(i,a){var l=ze;ze|=2;var u=B0(),m=q0();Xe!==i||Ne!==a?(eu=null,Xc=_n()+500,Ra(i,a)):Ca=wo(i,a);e:do try{if(He!==0&&ke!==null){a=ke;var y=On;t:switch(He){case 1:He=0,On=null,Ta(i,a,y,1);break;case 2:case 9:if(Qb(y)){He=0,On=null,z0(a);break}a=function(){He!==2&&He!==9||Xe!==i||(He=7),gr(i)},y.then(a,a);break e;case 3:He=7;break e;case 4:He=5;break e;case 7:Qb(y)?(He=0,On=null,z0(a)):(He=0,On=null,Ta(i,a,y,7));break;case 5:var S=null;switch(ke.tag){case 26:S=ke.memoizedState;case 5:case 27:var j=ke;if(S?kw(S):j.stateNode.complete){He=0,On=null;var V=j.sibling;if(V!==null)ke=V;else{var J=j.return;J!==null?(ke=J,ru(J)):ke=null}break t}}He=0,On=null,Ta(i,a,y,5);break;case 6:He=0,On=null,Ta(i,a,y,6);break;case 8:Zh(),ft=6;break e;default:throw Error(r(462))}}aN();break}catch(ne){U0(i,ne)}while(!0);return $r=pi=null,P.H=u,P.A=m,ze=l,ke!==null?0:(Xe=null,Ne=0,Sc(),ft)}function aN(){for(;ke!==null&&!Nk();)F0(ke)}function F0(i){var a=d0(i.alternate,i,Yr);i.memoizedProps=i.pendingProps,a===null?ru(i):ke=a}function z0(i){var a=i,l=a.alternate;switch(a.tag){case 15:case 0:a=i0(l,a,a.pendingProps,a.type,void 0,Ne);break;case 11:a=i0(l,a,a.pendingProps,a.type.render,a.ref,Ne);break;case 5:dh(a);default:h0(l,a),a=ke=qb(a,Yr),a=d0(l,a,Yr)}i.memoizedProps=i.pendingProps,a===null?ru(i):ke=a}function Ta(i,a,l,u){$r=pi=null,dh(a),xa=null,Uo=0;var m=a.return;try{if(YC(i,m,a,l,Ne)){ft=1,Vc(i,zn(l,i.current)),ke=null;return}}catch(y){if(m!==null)throw ke=m,y;ft=1,Vc(i,zn(l,i.current)),ke=null;return}a.flags&32768?(De||u===1?i=!0:Ca||(Ne&536870912)!==0?i=!1:(Es=i=!0,(u===2||u===9||u===3||u===6)&&(u=Cn.current,u!==null&&u.tag===13&&(u.flags|=16384))),P0(a,i)):ru(a)}function ru(i){var a=i;do{if((a.flags&32768)!==0){P0(a,Es);return}i=a.return;var l=QC(a.alternate,a,Yr);if(l!==null){ke=l;return}if(a=a.sibling,a!==null){ke=a;return}ke=a=i}while(a!==null);ft===0&&(ft=5)}function P0(i,a){do{var l=JC(i.alternate,i);if(l!==null){l.flags&=32767,ke=l;return}if(l=i.return,l!==null&&(l.flags|=32768,l.subtreeFlags=0,l.deletions=null),!a&&(i=i.sibling,i!==null)){ke=i;return}ke=i=l}while(i!==null);ft=6,ke=null}function V0(i,a,l,u,m,y,S,j,V){i.cancelPendingCommit=null;do su();while(Ot!==0);if((ze&6)!==0)throw Error(r(327));if(a!==null){if(a===i.current)throw Error(r(177));if(y=a.lanes|a.childLanes,y|=$f,Bk(i,l,y,S,j,V),i===Xe&&(ke=Xe=null,Ne=0),Oa=a,ks=i,Zr=l,Gh=y,Kh=m,D0=u,(a.subtreeFlags&10256)!==0||(a.flags&10256)!==0?(i.callbackNode=null,i.callbackPriority=0,uN(ac,function(){return Z0(),null})):(i.callbackNode=null,i.callbackPriority=0),u=(a.flags&13878)!==0,(a.subtreeFlags&13878)!==0||u){u=P.T,P.T=null,m=$.p,$.p=2,S=ze,ze|=4;try{XC(i,a,l)}finally{ze=S,$.p=m,P.T=u}}Ot=1,H0(),G0(),K0()}}function H0(){if(Ot===1){Ot=0;var i=ks,a=Oa,l=(a.flags&13878)!==0;if((a.subtreeFlags&13878)!==0||l){l=P.T,P.T=null;var u=$.p;$.p=2;var m=ze;ze|=4;try{A0(a,i);var y=lp,S=Rb(i.containerInfo),j=y.focusedElem,V=y.selectionRange;if(S!==j&&j&&j.ownerDocument&&Ob(j.ownerDocument.documentElement,j)){if(V!==null&&Df(j)){var J=V.start,ne=V.end;if(ne===void 0&&(ne=J),"selectionStart"in j)j.selectionStart=J,j.selectionEnd=Math.min(ne,j.value.length);else{var ie=j.ownerDocument||document,X=ie&&ie.defaultView||window;if(X.getSelection){var te=X.getSelection(),de=j.textContent.length,me=Math.min(V.start,de),Je=V.end===void 0?me:Math.min(V.end,de);!te.extend&&me>Je&&(S=Je,Je=me,me=S);var Z=Nb(j,me),Y=Nb(j,Je);if(Z&&Y&&(te.rangeCount!==1||te.anchorNode!==Z.node||te.anchorOffset!==Z.offset||te.focusNode!==Y.node||te.focusOffset!==Y.offset)){var Q=ie.createRange();Q.setStart(Z.node,Z.offset),te.removeAllRanges(),me>Je?(te.addRange(Q),te.extend(Y.node,Y.offset)):(Q.setEnd(Y.node,Y.offset),te.addRange(Q))}}}}for(ie=[],te=j;te=te.parentNode;)te.nodeType===1&&ie.push({element:te,left:te.scrollLeft,top:te.scrollTop});for(typeof j.focus=="function"&&j.focus(),j=0;j<ie.length;j++){var re=ie[j];re.element.scrollLeft=re.left,re.element.scrollTop=re.top}}yu=!!op,lp=op=null}finally{ze=m,$.p=u,P.T=l}}i.current=a,Ot=2}}function G0(){if(Ot===2){Ot=0;var i=ks,a=Oa,l=(a.flags&8772)!==0;if((a.subtreeFlags&8772)!==0||l){l=P.T,P.T=null;var u=$.p;$.p=2;var m=ze;ze|=4;try{w0(i,a.alternate,a)}finally{ze=m,$.p=u,P.T=l}}Ot=3}}function K0(){if(Ot===4||Ot===3){Ot=0,Ok();var i=ks,a=Oa,l=Zr,u=D0;(a.subtreeFlags&10256)!==0||(a.flags&10256)!==0?Ot=5:(Ot=0,Oa=ks=null,Y0(i,i.pendingLanes));var m=i.pendingLanes;if(m===0&&(js=null),pf(l),a=a.stateNode,En&&typeof En.onCommitFiberRoot=="function")try{En.onCommitFiberRoot(vo,a,void 0,(a.current.flags&128)===128)}catch{}if(u!==null){a=P.T,m=$.p,$.p=2,P.T=null;try{for(var y=i.onRecoverableError,S=0;S<u.length;S++){var j=u[S];y(j.value,{componentStack:j.stack})}}finally{P.T=a,$.p=m}}(Zr&3)!==0&&su(),gr(i),m=i.pendingLanes,(l&261930)!==0&&(m&42)!==0?i===Yh?el++:(el=0,Yh=i):el=0,tl(0)}}function Y0(i,a){(i.pooledCacheLanes&=a)===0&&(a=i.pooledCache,a!=null&&(i.pooledCache=null,Mo(a)))}function su(){return H0(),G0(),K0(),Z0()}function Z0(){if(Ot!==5)return!1;var i=ks,a=Gh;Gh=0;var l=pf(Zr),u=P.T,m=$.p;try{$.p=32>l?32:l,P.T=null,l=Kh,Kh=null;var y=ks,S=Zr;if(Ot=0,Oa=ks=null,Zr=0,(ze&6)!==0)throw Error(r(331));var j=ze;if(ze|=4,O0(y.current),k0(y,y.current,S,l),ze=j,tl(0,!1),En&&typeof En.onPostCommitFiberRoot=="function")try{En.onPostCommitFiberRoot(vo,y)}catch{}return!0}finally{$.p=m,P.T=u,Y0(i,a)}}function W0(i,a,l){a=zn(l,a),a=jh(i.stateNode,a,2),i=ws(i,a,2),i!==null&&(xo(i,2),gr(i))}function Ge(i,a,l){if(i.tag===3)W0(i,i,l);else for(;a!==null;){if(a.tag===3){W0(a,i,l);break}else if(a.tag===1){var u=a.stateNode;if(typeof a.type.getDerivedStateFromError=="function"||typeof u.componentDidCatch=="function"&&(js===null||!js.has(u))){i=zn(l,i),l=Qv(2),u=ws(a,l,2),u!==null&&(Jv(l,u,a,i),xo(u,2),gr(u));break}}a=a.return}}function Qh(i,a,l){var u=i.pingCache;if(u===null){u=i.pingCache=new nN;var m=new Set;u.set(a,m)}else m=u.get(a),m===void 0&&(m=new Set,u.set(a,m));m.has(l)||(Ph=!0,m.add(l),i=oN.bind(null,i,a,l),a.then(i,i))}function oN(i,a,l){var u=i.pingCache;u!==null&&u.delete(a),i.pingedLanes|=i.suspendedLanes&l,i.warmLanes&=~l,Xe===i&&(Ne&l)===l&&(ft===4||ft===3&&(Ne&62914560)===Ne&&300>_n()-Jc?(ze&2)===0&&Ra(i,0):Vh|=l,Na===Ne&&(Na=0)),gr(i)}function Q0(i,a){a===0&&(a=Hg()),i=di(i,a),i!==null&&(xo(i,a),gr(i))}function lN(i){var a=i.memoizedState,l=0;a!==null&&(l=a.retryLane),Q0(i,l)}function cN(i,a){var l=0;switch(i.tag){case 31:case 13:var u=i.stateNode,m=i.memoizedState;m!==null&&(l=m.retryLane);break;case 19:u=i.stateNode;break;case 22:u=i.stateNode._retryCache;break;default:throw Error(r(314))}u!==null&&u.delete(a),Q0(i,l)}function uN(i,a){return uf(i,a)}var iu=null,Da=null,Jh=!1,au=!1,Xh=!1,Ns=0;function gr(i){i!==Da&&i.next===null&&(Da===null?iu=Da=i:Da=Da.next=i),au=!0,Jh||(Jh=!0,fN())}function tl(i,a){if(!Xh&&au){Xh=!0;do for(var l=!1,u=iu;u!==null;){if(i!==0){var m=u.pendingLanes;if(m===0)var y=0;else{var S=u.suspendedLanes,j=u.pingedLanes;y=(1<<31-An(42|i)+1)-1,y&=m&~(S&~j),y=y&201326741?y&201326741|1:y?y|2:0}y!==0&&(l=!0,tw(u,y))}else y=Ne,y=uc(u,u===Xe?y:0,u.cancelPendingCommit!==null||u.timeoutHandle!==-1),(y&3)===0||wo(u,y)||(l=!0,tw(u,y));u=u.next}while(l);Xh=!1}}function dN(){J0()}function J0(){au=Jh=!1;var i=0;Ns!==0&&SN()&&(i=Ns);for(var a=_n(),l=null,u=iu;u!==null;){var m=u.next,y=X0(u,a);y===0?(u.next=null,l===null?iu=m:l.next=m,m===null&&(Da=l)):(l=u,(i!==0||(y&3)!==0)&&(au=!0)),u=m}Ot!==0&&Ot!==5||tl(i),Ns!==0&&(Ns=0)}function X0(i,a){for(var l=i.suspendedLanes,u=i.pingedLanes,m=i.expirationTimes,y=i.pendingLanes&-62914561;0<y;){var S=31-An(y),j=1<<S,V=m[S];V===-1?((j&l)===0||(j&u)!==0)&&(m[S]=$k(j,a)):V<=a&&(i.expiredLanes|=j),y&=~j}if(a=Xe,l=Ne,l=uc(i,i===a?l:0,i.cancelPendingCommit!==null||i.timeoutHandle!==-1),u=i.callbackNode,l===0||i===a&&(He===2||He===9)||i.cancelPendingCommit!==null)return u!==null&&u!==null&&df(u),i.callbackNode=null,i.callbackPriority=0;if((l&3)===0||wo(i,l)){if(a=l&-l,a===i.callbackPriority)return a;switch(u!==null&&df(u),pf(l)){case 2:case 8:l=Pg;break;case 32:l=ac;break;case 268435456:l=Vg;break;default:l=ac}return u=ew.bind(null,i),l=uf(l,u),i.callbackPriority=a,i.callbackNode=l,a}return u!==null&&u!==null&&df(u),i.callbackPriority=2,i.callbackNode=null,2}function ew(i,a){if(Ot!==0&&Ot!==5)return i.callbackNode=null,i.callbackPriority=0,null;var l=i.callbackNode;if(su()&&i.callbackNode!==l)return null;var u=Ne;return u=uc(i,i===Xe?u:0,i.cancelPendingCommit!==null||i.timeoutHandle!==-1),u===0?null:(M0(i,u,a),X0(i,_n()),i.callbackNode!=null&&i.callbackNode===l?ew.bind(null,i):null)}function tw(i,a){if(su())return null;M0(i,a,!0)}function fN(){EN(function(){(ze&6)!==0?uf(zg,dN):J0()})}function ep(){if(Ns===0){var i=ba;i===0&&(i=oc,oc<<=1,(oc&261888)===0&&(oc=256)),Ns=i}return Ns}function nw(i){return i==null||typeof i=="symbol"||typeof i=="boolean"?null:typeof i=="function"?i:pc(""+i)}function rw(i,a){var l=a.ownerDocument.createElement("input");return l.name=a.name,l.value=a.value,i.id&&l.setAttribute("form",i.id),a.parentNode.insertBefore(l,a),i=new FormData(i),l.parentNode.removeChild(l),i}function hN(i,a,l,u,m){if(a==="submit"&&l&&l.stateNode===m){var y=nw((m[dn]||null).action),S=u.submitter;S&&(a=(a=S[dn]||null)?nw(a.formAction):S.getAttribute("formAction"),a!==null&&(y=a,S=null));var j=new bc("action","action",null,u,m);i.push({event:j,listeners:[{instance:null,listener:function(){if(u.defaultPrevented){if(Ns!==0){var V=S?rw(m,S):new FormData(m);wh(l,{pending:!0,data:V,method:m.method,action:y},null,V)}}else typeof y=="function"&&(j.preventDefault(),V=S?rw(m,S):new FormData(m),wh(l,{pending:!0,data:V,method:m.method,action:y},y,V))},currentTarget:m}]})}}for(var tp=0;tp<Uf.length;tp++){var np=Uf[tp],pN=np.toLowerCase(),mN=np[0].toUpperCase()+np.slice(1);sr(pN,"on"+mN)}sr(Ib,"onAnimationEnd"),sr(Mb,"onAnimationIteration"),sr(Lb,"onAnimationStart"),sr("dblclick","onDoubleClick"),sr("focusin","onFocus"),sr("focusout","onBlur"),sr(RC,"onTransitionRun"),sr(TC,"onTransitionStart"),sr(DC,"onTransitionCancel"),sr(Ub,"onTransitionEnd"),sa("onMouseEnter",["mouseout","mouseover"]),sa("onMouseLeave",["mouseout","mouseover"]),sa("onPointerEnter",["pointerout","pointerover"]),sa("onPointerLeave",["pointerout","pointerover"]),oi("onChange","change click focusin focusout input keydown keyup selectionchange".split(" ")),oi("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" ")),oi("onBeforeInput",["compositionend","keypress","textInput","paste"]),oi("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" ")),oi("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" ")),oi("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var nl="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),yN=new Set("beforetoggle cancel close invalid load scroll scrollend toggle".split(" ").concat(nl));function sw(i,a){a=(a&4)!==0;for(var l=0;l<i.length;l++){var u=i[l],m=u.event;u=u.listeners;e:{var y=void 0;if(a)for(var S=u.length-1;0<=S;S--){var j=u[S],V=j.instance,J=j.currentTarget;if(j=j.listener,V!==y&&m.isPropagationStopped())break e;y=j,m.currentTarget=J;try{y(m)}catch(ne){xc(ne)}m.currentTarget=null,y=V}else for(S=0;S<u.length;S++){if(j=u[S],V=j.instance,J=j.currentTarget,j=j.listener,V!==y&&m.isPropagationStopped())break e;y=j,m.currentTarget=J;try{y(m)}catch(ne){xc(ne)}m.currentTarget=null,y=V}}}}function Ce(i,a){var l=a[mf];l===void 0&&(l=a[mf]=new Set);var u=i+"__bubble";l.has(u)||(iw(a,i,2,!1),l.add(u))}function rp(i,a,l){var u=0;a&&(u|=4),iw(l,i,u,a)}var ou="_reactListening"+Math.random().toString(36).slice(2);function sp(i){if(!i[ou]){i[ou]=!0,Jg.forEach(function(l){l!=="selectionchange"&&(yN.has(l)||rp(l,!1,i),rp(l,!0,i))});var a=i.nodeType===9?i:i.ownerDocument;a===null||a[ou]||(a[ou]=!0,rp("selectionchange",!1,a))}}function iw(i,a,l,u){switch(Iw(a)){case 2:var m=VN;break;case 8:m=HN;break;default:m=vp}l=m.bind(null,a,l,i),m=void 0,!Ef||a!=="touchstart"&&a!=="touchmove"&&a!=="wheel"||(m=!0),u?m!==void 0?i.addEventListener(a,l,{capture:!0,passive:m}):i.addEventListener(a,l,!0):m!==void 0?i.addEventListener(a,l,{passive:m}):i.addEventListener(a,l,!1)}function ip(i,a,l,u,m){var y=u;if((a&1)===0&&(a&2)===0&&u!==null)e:for(;;){if(u===null)return;var S=u.tag;if(S===3||S===4){var j=u.stateNode.containerInfo;if(j===m)break;if(S===4)for(S=u.return;S!==null;){var V=S.tag;if((V===3||V===4)&&S.stateNode.containerInfo===m)return;S=S.return}for(;j!==null;){if(S=ta(j),S===null)return;if(V=S.tag,V===5||V===6||V===26||V===27){u=y=S;continue e}j=j.parentNode}}u=u.return}ub(function(){var J=y,ne=Sf(l),ie=[];e:{var X=$b.get(i);if(X!==void 0){var te=bc,de=i;switch(i){case"keypress":if(yc(l)===0)break e;case"keydown":case"keyup":te=cC;break;case"focusin":de="focus",te=Cf;break;case"focusout":de="blur",te=Cf;break;case"beforeblur":case"afterblur":te=Cf;break;case"click":if(l.button===2)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":te=hb;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":te=Qk;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":te=fC;break;case Ib:case Mb:case Lb:te=eC;break;case Ub:te=pC;break;case"scroll":case"scrollend":te=Zk;break;case"wheel":te=yC;break;case"copy":case"cut":case"paste":te=nC;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":te=mb;break;case"toggle":case"beforetoggle":te=bC}var me=(a&4)!==0,Je=!me&&(i==="scroll"||i==="scrollend"),Z=me?X!==null?X+"Capture":null:X;me=[];for(var Y=J,Q;Y!==null;){var re=Y;if(Q=re.stateNode,re=re.tag,re!==5&&re!==26&&re!==27||Q===null||Z===null||(re=Eo(Y,Z),re!=null&&me.push(rl(Y,re,Q))),Je)break;Y=Y.return}0<me.length&&(X=new te(X,de,null,l,ne),ie.push({event:X,listeners:me}))}}if((a&7)===0){e:{if(X=i==="mouseover"||i==="pointerover",te=i==="mouseout"||i==="pointerout",X&&l!==xf&&(de=l.relatedTarget||l.fromElement)&&(ta(de)||de[ea]))break e;if((te||X)&&(X=ne.window===ne?ne:(X=ne.ownerDocument)?X.defaultView||X.parentWindow:window,te?(de=l.relatedTarget||l.toElement,te=J,de=de?ta(de):null,de!==null&&(Je=o(de),me=de.tag,de!==Je||me!==5&&me!==27&&me!==6)&&(de=null)):(te=null,de=J),te!==de)){if(me=hb,re="onMouseLeave",Z="onMouseEnter",Y="mouse",(i==="pointerout"||i==="pointerover")&&(me=mb,re="onPointerLeave",Z="onPointerEnter",Y="pointer"),Je=te==null?X:_o(te),Q=de==null?X:_o(de),X=new me(re,Y+"leave",te,l,ne),X.target=Je,X.relatedTarget=Q,re=null,ta(ne)===J&&(me=new me(Z,Y+"enter",de,l,ne),me.target=Q,me.relatedTarget=Je,re=me),Je=re,te&&de)t:{for(me=gN,Z=te,Y=de,Q=0,re=Z;re;re=me(re))Q++;re=0;for(var pe=Y;pe;pe=me(pe))re++;for(;0<Q-re;)Z=me(Z),Q--;for(;0<re-Q;)Y=me(Y),re--;for(;Q--;){if(Z===Y||Y!==null&&Z===Y.alternate){me=Z;break t}Z=me(Z),Y=me(Y)}me=null}else me=null;te!==null&&aw(ie,X,te,me,!1),de!==null&&Je!==null&&aw(ie,Je,de,me,!0)}}e:{if(X=J?_o(J):window,te=X.nodeName&&X.nodeName.toLowerCase(),te==="select"||te==="input"&&X.type==="file")var Be=_b;else if(xb(X))if(Eb)Be=CC;else{Be=jC;var fe=AC}else te=X.nodeName,!te||te.toLowerCase()!=="input"||X.type!=="checkbox"&&X.type!=="radio"?J&&wf(J.elementType)&&(Be=_b):Be=kC;if(Be&&(Be=Be(i,J))){Sb(ie,Be,l,ne);break e}fe&&fe(i,X,J),i==="focusout"&&J&&X.type==="number"&&J.memoizedProps.value!=null&&vf(X,"number",X.value)}switch(fe=J?_o(J):window,i){case"focusin":(xb(fe)||fe.contentEditable==="true")&&(ua=fe,If=J,To=null);break;case"focusout":To=If=ua=null;break;case"mousedown":Mf=!0;break;case"contextmenu":case"mouseup":case"dragend":Mf=!1,Tb(ie,l,ne);break;case"selectionchange":if(OC)break;case"keydown":case"keyup":Tb(ie,l,ne)}var Se;if(Of)e:{switch(i){case"compositionstart":var Oe="onCompositionStart";break e;case"compositionend":Oe="onCompositionEnd";break e;case"compositionupdate":Oe="onCompositionUpdate";break e}Oe=void 0}else ca?vb(i,l)&&(Oe="onCompositionEnd"):i==="keydown"&&l.keyCode===229&&(Oe="onCompositionStart");Oe&&(yb&&l.locale!=="ko"&&(ca||Oe!=="onCompositionStart"?Oe==="onCompositionEnd"&&ca&&(Se=db()):(hs=ne,Af="value"in hs?hs.value:hs.textContent,ca=!0)),fe=lu(J,Oe),0<fe.length&&(Oe=new pb(Oe,i,null,l,ne),ie.push({event:Oe,listeners:fe}),Se?Oe.data=Se:(Se=wb(l),Se!==null&&(Oe.data=Se)))),(Se=wC?xC(i,l):SC(i,l))&&(Oe=lu(J,"onBeforeInput"),0<Oe.length&&(fe=new pb("onBeforeInput","beforeinput",null,l,ne),ie.push({event:fe,listeners:Oe}),fe.data=Se)),hN(ie,i,J,l,ne)}sw(ie,a)})}function rl(i,a,l){return{instance:i,listener:a,currentTarget:l}}function lu(i,a){for(var l=a+"Capture",u=[];i!==null;){var m=i,y=m.stateNode;if(m=m.tag,m!==5&&m!==26&&m!==27||y===null||(m=Eo(i,l),m!=null&&u.unshift(rl(i,m,y)),m=Eo(i,a),m!=null&&u.push(rl(i,m,y))),i.tag===3)return u;i=i.return}return[]}function gN(i){if(i===null)return null;do i=i.return;while(i&&i.tag!==5&&i.tag!==27);return i||null}function aw(i,a,l,u,m){for(var y=a._reactName,S=[];l!==null&&l!==u;){var j=l,V=j.alternate,J=j.stateNode;if(j=j.tag,V!==null&&V===u)break;j!==5&&j!==26&&j!==27||J===null||(V=J,m?(J=Eo(l,y),J!=null&&S.unshift(rl(l,J,V))):m||(J=Eo(l,y),J!=null&&S.push(rl(l,J,V)))),l=l.return}S.length!==0&&i.push({event:a,listeners:S})}var bN=/\r\n?/g,vN=/\u0000|\uFFFD/g;function ow(i){return(typeof i=="string"?i:""+i).replace(bN,`
49
- `).replace(vN,"")}function lw(i,a){return a=ow(a),ow(i)===a}function Qe(i,a,l,u,m,y){switch(l){case"children":typeof u=="string"?a==="body"||a==="textarea"&&u===""||aa(i,u):(typeof u=="number"||typeof u=="bigint")&&a!=="body"&&aa(i,""+u);break;case"className":fc(i,"class",u);break;case"tabIndex":fc(i,"tabindex",u);break;case"dir":case"role":case"viewBox":case"width":case"height":fc(i,l,u);break;case"style":lb(i,u,y);break;case"data":if(a!=="object"){fc(i,"data",u);break}case"src":case"href":if(u===""&&(a!=="a"||l!=="href")){i.removeAttribute(l);break}if(u==null||typeof u=="function"||typeof u=="symbol"||typeof u=="boolean"){i.removeAttribute(l);break}u=pc(""+u),i.setAttribute(l,u);break;case"action":case"formAction":if(typeof u=="function"){i.setAttribute(l,"javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')");break}else typeof y=="function"&&(l==="formAction"?(a!=="input"&&Qe(i,a,"name",m.name,m,null),Qe(i,a,"formEncType",m.formEncType,m,null),Qe(i,a,"formMethod",m.formMethod,m,null),Qe(i,a,"formTarget",m.formTarget,m,null)):(Qe(i,a,"encType",m.encType,m,null),Qe(i,a,"method",m.method,m,null),Qe(i,a,"target",m.target,m,null)));if(u==null||typeof u=="symbol"||typeof u=="boolean"){i.removeAttribute(l);break}u=pc(""+u),i.setAttribute(l,u);break;case"onClick":u!=null&&(i.onclick=Ir);break;case"onScroll":u!=null&&Ce("scroll",i);break;case"onScrollEnd":u!=null&&Ce("scrollend",i);break;case"dangerouslySetInnerHTML":if(u!=null){if(typeof u!="object"||!("__html"in u))throw Error(r(61));if(l=u.__html,l!=null){if(m.children!=null)throw Error(r(60));i.innerHTML=l}}break;case"multiple":i.multiple=u&&typeof u!="function"&&typeof u!="symbol";break;case"muted":i.muted=u&&typeof u!="function"&&typeof u!="symbol";break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"defaultValue":case"defaultChecked":case"innerHTML":case"ref":break;case"autoFocus":break;case"xlinkHref":if(u==null||typeof u=="function"||typeof u=="boolean"||typeof u=="symbol"){i.removeAttribute("xlink:href");break}l=pc(""+u),i.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",l);break;case"contentEditable":case"spellCheck":case"draggable":case"value":case"autoReverse":case"externalResourcesRequired":case"focusable":case"preserveAlpha":u!=null&&typeof u!="function"&&typeof u!="symbol"?i.setAttribute(l,""+u):i.removeAttribute(l);break;case"inert":case"allowFullScreen":case"async":case"autoPlay":case"controls":case"default":case"defer":case"disabled":case"disablePictureInPicture":case"disableRemotePlayback":case"formNoValidate":case"hidden":case"loop":case"noModule":case"noValidate":case"open":case"playsInline":case"readOnly":case"required":case"reversed":case"scoped":case"seamless":case"itemScope":u&&typeof u!="function"&&typeof u!="symbol"?i.setAttribute(l,""):i.removeAttribute(l);break;case"capture":case"download":u===!0?i.setAttribute(l,""):u!==!1&&u!=null&&typeof u!="function"&&typeof u!="symbol"?i.setAttribute(l,u):i.removeAttribute(l);break;case"cols":case"rows":case"size":case"span":u!=null&&typeof u!="function"&&typeof u!="symbol"&&!isNaN(u)&&1<=u?i.setAttribute(l,u):i.removeAttribute(l);break;case"rowSpan":case"start":u==null||typeof u=="function"||typeof u=="symbol"||isNaN(u)?i.removeAttribute(l):i.setAttribute(l,u);break;case"popover":Ce("beforetoggle",i),Ce("toggle",i),dc(i,"popover",u);break;case"xlinkActuate":Dr(i,"http://www.w3.org/1999/xlink","xlink:actuate",u);break;case"xlinkArcrole":Dr(i,"http://www.w3.org/1999/xlink","xlink:arcrole",u);break;case"xlinkRole":Dr(i,"http://www.w3.org/1999/xlink","xlink:role",u);break;case"xlinkShow":Dr(i,"http://www.w3.org/1999/xlink","xlink:show",u);break;case"xlinkTitle":Dr(i,"http://www.w3.org/1999/xlink","xlink:title",u);break;case"xlinkType":Dr(i,"http://www.w3.org/1999/xlink","xlink:type",u);break;case"xmlBase":Dr(i,"http://www.w3.org/XML/1998/namespace","xml:base",u);break;case"xmlLang":Dr(i,"http://www.w3.org/XML/1998/namespace","xml:lang",u);break;case"xmlSpace":Dr(i,"http://www.w3.org/XML/1998/namespace","xml:space",u);break;case"is":dc(i,"is",u);break;case"innerText":case"textContent":break;default:(!(2<l.length)||l[0]!=="o"&&l[0]!=="O"||l[1]!=="n"&&l[1]!=="N")&&(l=Kk.get(l)||l,dc(i,l,u))}}function ap(i,a,l,u,m,y){switch(l){case"style":lb(i,u,y);break;case"dangerouslySetInnerHTML":if(u!=null){if(typeof u!="object"||!("__html"in u))throw Error(r(61));if(l=u.__html,l!=null){if(m.children!=null)throw Error(r(60));i.innerHTML=l}}break;case"children":typeof u=="string"?aa(i,u):(typeof u=="number"||typeof u=="bigint")&&aa(i,""+u);break;case"onScroll":u!=null&&Ce("scroll",i);break;case"onScrollEnd":u!=null&&Ce("scrollend",i);break;case"onClick":u!=null&&(i.onclick=Ir);break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"innerHTML":case"ref":break;case"innerText":case"textContent":break;default:if(!Xg.hasOwnProperty(l))e:{if(l[0]==="o"&&l[1]==="n"&&(m=l.endsWith("Capture"),a=l.slice(2,m?l.length-7:void 0),y=i[dn]||null,y=y!=null?y[l]:null,typeof y=="function"&&i.removeEventListener(a,y,m),typeof u=="function")){typeof y!="function"&&y!==null&&(l in i?i[l]=null:i.hasAttribute(l)&&i.removeAttribute(l)),i.addEventListener(a,u,m);break e}l in i?i[l]=u:u===!0?i.setAttribute(l,""):dc(i,l,u)}}}function Ft(i,a,l){switch(a){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"img":Ce("error",i),Ce("load",i);var u=!1,m=!1,y;for(y in l)if(l.hasOwnProperty(y)){var S=l[y];if(S!=null)switch(y){case"src":u=!0;break;case"srcSet":m=!0;break;case"children":case"dangerouslySetInnerHTML":throw Error(r(137,a));default:Qe(i,a,y,S,l,null)}}m&&Qe(i,a,"srcSet",l.srcSet,l,null),u&&Qe(i,a,"src",l.src,l,null);return;case"input":Ce("invalid",i);var j=y=S=m=null,V=null,J=null;for(u in l)if(l.hasOwnProperty(u)){var ne=l[u];if(ne!=null)switch(u){case"name":m=ne;break;case"type":S=ne;break;case"checked":V=ne;break;case"defaultChecked":J=ne;break;case"value":y=ne;break;case"defaultValue":j=ne;break;case"children":case"dangerouslySetInnerHTML":if(ne!=null)throw Error(r(137,a));break;default:Qe(i,a,u,ne,l,null)}}sb(i,y,j,V,J,S,m,!1);return;case"select":Ce("invalid",i),u=S=y=null;for(m in l)if(l.hasOwnProperty(m)&&(j=l[m],j!=null))switch(m){case"value":y=j;break;case"defaultValue":S=j;break;case"multiple":u=j;default:Qe(i,a,m,j,l,null)}a=y,l=S,i.multiple=!!u,a!=null?ia(i,!!u,a,!1):l!=null&&ia(i,!!u,l,!0);return;case"textarea":Ce("invalid",i),y=m=u=null;for(S in l)if(l.hasOwnProperty(S)&&(j=l[S],j!=null))switch(S){case"value":u=j;break;case"defaultValue":m=j;break;case"children":y=j;break;case"dangerouslySetInnerHTML":if(j!=null)throw Error(r(91));break;default:Qe(i,a,S,j,l,null)}ab(i,u,m,y);return;case"option":for(V in l)if(l.hasOwnProperty(V)&&(u=l[V],u!=null))switch(V){case"selected":i.selected=u&&typeof u!="function"&&typeof u!="symbol";break;default:Qe(i,a,V,u,l,null)}return;case"dialog":Ce("beforetoggle",i),Ce("toggle",i),Ce("cancel",i),Ce("close",i);break;case"iframe":case"object":Ce("load",i);break;case"video":case"audio":for(u=0;u<nl.length;u++)Ce(nl[u],i);break;case"image":Ce("error",i),Ce("load",i);break;case"details":Ce("toggle",i);break;case"embed":case"source":case"link":Ce("error",i),Ce("load",i);case"area":case"base":case"br":case"col":case"hr":case"keygen":case"meta":case"param":case"track":case"wbr":case"menuitem":for(J in l)if(l.hasOwnProperty(J)&&(u=l[J],u!=null))switch(J){case"children":case"dangerouslySetInnerHTML":throw Error(r(137,a));default:Qe(i,a,J,u,l,null)}return;default:if(wf(a)){for(ne in l)l.hasOwnProperty(ne)&&(u=l[ne],u!==void 0&&ap(i,a,ne,u,l,void 0));return}}for(j in l)l.hasOwnProperty(j)&&(u=l[j],u!=null&&Qe(i,a,j,u,l,null))}function wN(i,a,l,u){switch(a){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"input":var m=null,y=null,S=null,j=null,V=null,J=null,ne=null;for(te in l){var ie=l[te];if(l.hasOwnProperty(te)&&ie!=null)switch(te){case"checked":break;case"value":break;case"defaultValue":V=ie;default:u.hasOwnProperty(te)||Qe(i,a,te,null,u,ie)}}for(var X in u){var te=u[X];if(ie=l[X],u.hasOwnProperty(X)&&(te!=null||ie!=null))switch(X){case"type":y=te;break;case"name":m=te;break;case"checked":J=te;break;case"defaultChecked":ne=te;break;case"value":S=te;break;case"defaultValue":j=te;break;case"children":case"dangerouslySetInnerHTML":if(te!=null)throw Error(r(137,a));break;default:te!==ie&&Qe(i,a,X,te,u,ie)}}bf(i,S,j,V,J,ne,y,m);return;case"select":te=S=j=X=null;for(y in l)if(V=l[y],l.hasOwnProperty(y)&&V!=null)switch(y){case"value":break;case"multiple":te=V;default:u.hasOwnProperty(y)||Qe(i,a,y,null,u,V)}for(m in u)if(y=u[m],V=l[m],u.hasOwnProperty(m)&&(y!=null||V!=null))switch(m){case"value":X=y;break;case"defaultValue":j=y;break;case"multiple":S=y;default:y!==V&&Qe(i,a,m,y,u,V)}a=j,l=S,u=te,X!=null?ia(i,!!l,X,!1):!!u!=!!l&&(a!=null?ia(i,!!l,a,!0):ia(i,!!l,l?[]:"",!1));return;case"textarea":te=X=null;for(j in l)if(m=l[j],l.hasOwnProperty(j)&&m!=null&&!u.hasOwnProperty(j))switch(j){case"value":break;case"children":break;default:Qe(i,a,j,null,u,m)}for(S in u)if(m=u[S],y=l[S],u.hasOwnProperty(S)&&(m!=null||y!=null))switch(S){case"value":X=m;break;case"defaultValue":te=m;break;case"children":break;case"dangerouslySetInnerHTML":if(m!=null)throw Error(r(91));break;default:m!==y&&Qe(i,a,S,m,u,y)}ib(i,X,te);return;case"option":for(var de in l)if(X=l[de],l.hasOwnProperty(de)&&X!=null&&!u.hasOwnProperty(de))switch(de){case"selected":i.selected=!1;break;default:Qe(i,a,de,null,u,X)}for(V in u)if(X=u[V],te=l[V],u.hasOwnProperty(V)&&X!==te&&(X!=null||te!=null))switch(V){case"selected":i.selected=X&&typeof X!="function"&&typeof X!="symbol";break;default:Qe(i,a,V,X,u,te)}return;case"img":case"link":case"area":case"base":case"br":case"col":case"embed":case"hr":case"keygen":case"meta":case"param":case"source":case"track":case"wbr":case"menuitem":for(var me in l)X=l[me],l.hasOwnProperty(me)&&X!=null&&!u.hasOwnProperty(me)&&Qe(i,a,me,null,u,X);for(J in u)if(X=u[J],te=l[J],u.hasOwnProperty(J)&&X!==te&&(X!=null||te!=null))switch(J){case"children":case"dangerouslySetInnerHTML":if(X!=null)throw Error(r(137,a));break;default:Qe(i,a,J,X,u,te)}return;default:if(wf(a)){for(var Je in l)X=l[Je],l.hasOwnProperty(Je)&&X!==void 0&&!u.hasOwnProperty(Je)&&ap(i,a,Je,void 0,u,X);for(ne in u)X=u[ne],te=l[ne],!u.hasOwnProperty(ne)||X===te||X===void 0&&te===void 0||ap(i,a,ne,X,u,te);return}}for(var Z in l)X=l[Z],l.hasOwnProperty(Z)&&X!=null&&!u.hasOwnProperty(Z)&&Qe(i,a,Z,null,u,X);for(ie in u)X=u[ie],te=l[ie],!u.hasOwnProperty(ie)||X===te||X==null&&te==null||Qe(i,a,ie,X,u,te)}function cw(i){switch(i){case"css":case"script":case"font":case"img":case"image":case"input":case"link":return!0;default:return!1}}function xN(){if(typeof performance.getEntriesByType=="function"){for(var i=0,a=0,l=performance.getEntriesByType("resource"),u=0;u<l.length;u++){var m=l[u],y=m.transferSize,S=m.initiatorType,j=m.duration;if(y&&j&&cw(S)){for(S=0,j=m.responseEnd,u+=1;u<l.length;u++){var V=l[u],J=V.startTime;if(J>j)break;var ne=V.transferSize,ie=V.initiatorType;ne&&cw(ie)&&(V=V.responseEnd,S+=ne*(V<j?1:(j-J)/(V-J)))}if(--u,a+=8*(y+S)/(m.duration/1e3),i++,10<i)break}}if(0<i)return a/i/1e6}return navigator.connection&&(i=navigator.connection.downlink,typeof i=="number")?i:5}var op=null,lp=null;function cu(i){return i.nodeType===9?i:i.ownerDocument}function uw(i){switch(i){case"http://www.w3.org/2000/svg":return 1;case"http://www.w3.org/1998/Math/MathML":return 2;default:return 0}}function dw(i,a){if(i===0)switch(a){case"svg":return 1;case"math":return 2;default:return 0}return i===1&&a==="foreignObject"?0:i}function cp(i,a){return i==="textarea"||i==="noscript"||typeof a.children=="string"||typeof a.children=="number"||typeof a.children=="bigint"||typeof a.dangerouslySetInnerHTML=="object"&&a.dangerouslySetInnerHTML!==null&&a.dangerouslySetInnerHTML.__html!=null}var up=null;function SN(){var i=window.event;return i&&i.type==="popstate"?i===up?!1:(up=i,!0):(up=null,!1)}var fw=typeof setTimeout=="function"?setTimeout:void 0,_N=typeof clearTimeout=="function"?clearTimeout:void 0,hw=typeof Promise=="function"?Promise:void 0,EN=typeof queueMicrotask=="function"?queueMicrotask:typeof hw<"u"?function(i){return hw.resolve(null).then(i).catch(AN)}:fw;function AN(i){setTimeout(function(){throw i})}function Os(i){return i==="head"}function pw(i,a){var l=a,u=0;do{var m=l.nextSibling;if(i.removeChild(l),m&&m.nodeType===8)if(l=m.data,l==="/$"||l==="/&"){if(u===0){i.removeChild(m),Ua(a);return}u--}else if(l==="$"||l==="$?"||l==="$~"||l==="$!"||l==="&")u++;else if(l==="html")sl(i.ownerDocument.documentElement);else if(l==="head"){l=i.ownerDocument.head,sl(l);for(var y=l.firstChild;y;){var S=y.nextSibling,j=y.nodeName;y[So]||j==="SCRIPT"||j==="STYLE"||j==="LINK"&&y.rel.toLowerCase()==="stylesheet"||l.removeChild(y),y=S}}else l==="body"&&sl(i.ownerDocument.body);l=m}while(l);Ua(a)}function mw(i,a){var l=i;i=0;do{var u=l.nextSibling;if(l.nodeType===1?a?(l._stashedDisplay=l.style.display,l.style.display="none"):(l.style.display=l._stashedDisplay||"",l.getAttribute("style")===""&&l.removeAttribute("style")):l.nodeType===3&&(a?(l._stashedText=l.nodeValue,l.nodeValue=""):l.nodeValue=l._stashedText||""),u&&u.nodeType===8)if(l=u.data,l==="/$"){if(i===0)break;i--}else l!=="$"&&l!=="$?"&&l!=="$~"&&l!=="$!"||i++;l=u}while(l)}function dp(i){var a=i.firstChild;for(a&&a.nodeType===10&&(a=a.nextSibling);a;){var l=a;switch(a=a.nextSibling,l.nodeName){case"HTML":case"HEAD":case"BODY":dp(l),yf(l);continue;case"SCRIPT":case"STYLE":continue;case"LINK":if(l.rel.toLowerCase()==="stylesheet")continue}i.removeChild(l)}}function jN(i,a,l,u){for(;i.nodeType===1;){var m=l;if(i.nodeName.toLowerCase()!==a.toLowerCase()){if(!u&&(i.nodeName!=="INPUT"||i.type!=="hidden"))break}else if(u){if(!i[So])switch(a){case"meta":if(!i.hasAttribute("itemprop"))break;return i;case"link":if(y=i.getAttribute("rel"),y==="stylesheet"&&i.hasAttribute("data-precedence"))break;if(y!==m.rel||i.getAttribute("href")!==(m.href==null||m.href===""?null:m.href)||i.getAttribute("crossorigin")!==(m.crossOrigin==null?null:m.crossOrigin)||i.getAttribute("title")!==(m.title==null?null:m.title))break;return i;case"style":if(i.hasAttribute("data-precedence"))break;return i;case"script":if(y=i.getAttribute("src"),(y!==(m.src==null?null:m.src)||i.getAttribute("type")!==(m.type==null?null:m.type)||i.getAttribute("crossorigin")!==(m.crossOrigin==null?null:m.crossOrigin))&&y&&i.hasAttribute("async")&&!i.hasAttribute("itemprop"))break;return i;default:return i}}else if(a==="input"&&i.type==="hidden"){var y=m.name==null?null:""+m.name;if(m.type==="hidden"&&i.getAttribute("name")===y)return i}else return i;if(i=Kn(i.nextSibling),i===null)break}return null}function kN(i,a,l){if(a==="")return null;for(;i.nodeType!==3;)if((i.nodeType!==1||i.nodeName!=="INPUT"||i.type!=="hidden")&&!l||(i=Kn(i.nextSibling),i===null))return null;return i}function yw(i,a){for(;i.nodeType!==8;)if((i.nodeType!==1||i.nodeName!=="INPUT"||i.type!=="hidden")&&!a||(i=Kn(i.nextSibling),i===null))return null;return i}function fp(i){return i.data==="$?"||i.data==="$~"}function hp(i){return i.data==="$!"||i.data==="$?"&&i.ownerDocument.readyState!=="loading"}function CN(i,a){var l=i.ownerDocument;if(i.data==="$~")i._reactRetry=a;else if(i.data!=="$?"||l.readyState!=="loading")a();else{var u=function(){a(),l.removeEventListener("DOMContentLoaded",u)};l.addEventListener("DOMContentLoaded",u),i._reactRetry=u}}function Kn(i){for(;i!=null;i=i.nextSibling){var a=i.nodeType;if(a===1||a===3)break;if(a===8){if(a=i.data,a==="$"||a==="$!"||a==="$?"||a==="$~"||a==="&"||a==="F!"||a==="F")break;if(a==="/$"||a==="/&")return null}}return i}var pp=null;function gw(i){i=i.nextSibling;for(var a=0;i;){if(i.nodeType===8){var l=i.data;if(l==="/$"||l==="/&"){if(a===0)return Kn(i.nextSibling);a--}else l!=="$"&&l!=="$!"&&l!=="$?"&&l!=="$~"&&l!=="&"||a++}i=i.nextSibling}return null}function bw(i){i=i.previousSibling;for(var a=0;i;){if(i.nodeType===8){var l=i.data;if(l==="$"||l==="$!"||l==="$?"||l==="$~"||l==="&"){if(a===0)return i;a--}else l!=="/$"&&l!=="/&"||a++}i=i.previousSibling}return null}function vw(i,a,l){switch(a=cu(l),i){case"html":if(i=a.documentElement,!i)throw Error(r(452));return i;case"head":if(i=a.head,!i)throw Error(r(453));return i;case"body":if(i=a.body,!i)throw Error(r(454));return i;default:throw Error(r(451))}}function sl(i){for(var a=i.attributes;a.length;)i.removeAttributeNode(a[0]);yf(i)}var Yn=new Map,ww=new Set;function uu(i){return typeof i.getRootNode=="function"?i.getRootNode():i.nodeType===9?i:i.ownerDocument}var Wr=$.d;$.d={f:NN,r:ON,D:RN,C:TN,L:DN,m:IN,X:LN,S:MN,M:UN};function NN(){var i=Wr.f(),a=tu();return i||a}function ON(i){var a=na(i);a!==null&&a.tag===5&&a.type==="form"?Uv(a):Wr.r(i)}var Ia=typeof document>"u"?null:document;function xw(i,a,l){var u=Ia;if(u&&typeof a=="string"&&a){var m=qn(a);m='link[rel="'+i+'"][href="'+m+'"]',typeof l=="string"&&(m+='[crossorigin="'+l+'"]'),ww.has(m)||(ww.add(m),i={rel:i,crossOrigin:l,href:a},u.querySelector(m)===null&&(a=u.createElement("link"),Ft(a,"link",i),Dt(a),u.head.appendChild(a)))}}function RN(i){Wr.D(i),xw("dns-prefetch",i,null)}function TN(i,a){Wr.C(i,a),xw("preconnect",i,a)}function DN(i,a,l){Wr.L(i,a,l);var u=Ia;if(u&&i&&a){var m='link[rel="preload"][as="'+qn(a)+'"]';a==="image"&&l&&l.imageSrcSet?(m+='[imagesrcset="'+qn(l.imageSrcSet)+'"]',typeof l.imageSizes=="string"&&(m+='[imagesizes="'+qn(l.imageSizes)+'"]')):m+='[href="'+qn(i)+'"]';var y=m;switch(a){case"style":y=Ma(i);break;case"script":y=La(i)}Yn.has(y)||(i=b({rel:"preload",href:a==="image"&&l&&l.imageSrcSet?void 0:i,as:a},l),Yn.set(y,i),u.querySelector(m)!==null||a==="style"&&u.querySelector(il(y))||a==="script"&&u.querySelector(al(y))||(a=u.createElement("link"),Ft(a,"link",i),Dt(a),u.head.appendChild(a)))}}function IN(i,a){Wr.m(i,a);var l=Ia;if(l&&i){var u=a&&typeof a.as=="string"?a.as:"script",m='link[rel="modulepreload"][as="'+qn(u)+'"][href="'+qn(i)+'"]',y=m;switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":y=La(i)}if(!Yn.has(y)&&(i=b({rel:"modulepreload",href:i},a),Yn.set(y,i),l.querySelector(m)===null)){switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(l.querySelector(al(y)))return}u=l.createElement("link"),Ft(u,"link",i),Dt(u),l.head.appendChild(u)}}}function MN(i,a,l){Wr.S(i,a,l);var u=Ia;if(u&&i){var m=ra(u).hoistableStyles,y=Ma(i);a=a||"default";var S=m.get(y);if(!S){var j={loading:0,preload:null};if(S=u.querySelector(il(y)))j.loading=5;else{i=b({rel:"stylesheet",href:i,"data-precedence":a},l),(l=Yn.get(y))&&mp(i,l);var V=S=u.createElement("link");Dt(V),Ft(V,"link",i),V._p=new Promise(function(J,ne){V.onload=J,V.onerror=ne}),V.addEventListener("load",function(){j.loading|=1}),V.addEventListener("error",function(){j.loading|=2}),j.loading|=4,du(S,a,u)}S={type:"stylesheet",instance:S,count:1,state:j},m.set(y,S)}}}function LN(i,a){Wr.X(i,a);var l=Ia;if(l&&i){var u=ra(l).hoistableScripts,m=La(i),y=u.get(m);y||(y=l.querySelector(al(m)),y||(i=b({src:i,async:!0},a),(a=Yn.get(m))&&yp(i,a),y=l.createElement("script"),Dt(y),Ft(y,"link",i),l.head.appendChild(y)),y={type:"script",instance:y,count:1,state:null},u.set(m,y))}}function UN(i,a){Wr.M(i,a);var l=Ia;if(l&&i){var u=ra(l).hoistableScripts,m=La(i),y=u.get(m);y||(y=l.querySelector(al(m)),y||(i=b({src:i,async:!0,type:"module"},a),(a=Yn.get(m))&&yp(i,a),y=l.createElement("script"),Dt(y),Ft(y,"link",i),l.head.appendChild(y)),y={type:"script",instance:y,count:1,state:null},u.set(m,y))}}function Sw(i,a,l,u){var m=(m=je.current)?uu(m):null;if(!m)throw Error(r(446));switch(i){case"meta":case"title":return null;case"style":return typeof l.precedence=="string"&&typeof l.href=="string"?(a=Ma(l.href),l=ra(m).hoistableStyles,u=l.get(a),u||(u={type:"style",instance:null,count:0,state:null},l.set(a,u)),u):{type:"void",instance:null,count:0,state:null};case"link":if(l.rel==="stylesheet"&&typeof l.href=="string"&&typeof l.precedence=="string"){i=Ma(l.href);var y=ra(m).hoistableStyles,S=y.get(i);if(S||(m=m.ownerDocument||m,S={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},y.set(i,S),(y=m.querySelector(il(i)))&&!y._p&&(S.instance=y,S.state.loading=5),Yn.has(i)||(l={rel:"preload",as:"style",href:l.href,crossOrigin:l.crossOrigin,integrity:l.integrity,media:l.media,hrefLang:l.hrefLang,referrerPolicy:l.referrerPolicy},Yn.set(i,l),y||$N(m,i,l,S.state))),a&&u===null)throw Error(r(528,""));return S}if(a&&u!==null)throw Error(r(529,""));return null;case"script":return a=l.async,l=l.src,typeof l=="string"&&a&&typeof a!="function"&&typeof a!="symbol"?(a=La(l),l=ra(m).hoistableScripts,u=l.get(a),u||(u={type:"script",instance:null,count:0,state:null},l.set(a,u)),u):{type:"void",instance:null,count:0,state:null};default:throw Error(r(444,i))}}function Ma(i){return'href="'+qn(i)+'"'}function il(i){return'link[rel="stylesheet"]['+i+"]"}function _w(i){return b({},i,{"data-precedence":i.precedence,precedence:null})}function $N(i,a,l,u){i.querySelector('link[rel="preload"][as="style"]['+a+"]")?u.loading=1:(a=i.createElement("link"),u.preload=a,a.addEventListener("load",function(){return u.loading|=1}),a.addEventListener("error",function(){return u.loading|=2}),Ft(a,"link",l),Dt(a),i.head.appendChild(a))}function La(i){return'[src="'+qn(i)+'"]'}function al(i){return"script[async]"+i}function Ew(i,a,l){if(a.count++,a.instance===null)switch(a.type){case"style":var u=i.querySelector('style[data-href~="'+qn(l.href)+'"]');if(u)return a.instance=u,Dt(u),u;var m=b({},l,{"data-href":l.href,"data-precedence":l.precedence,href:null,precedence:null});return u=(i.ownerDocument||i).createElement("style"),Dt(u),Ft(u,"style",m),du(u,l.precedence,i),a.instance=u;case"stylesheet":m=Ma(l.href);var y=i.querySelector(il(m));if(y)return a.state.loading|=4,a.instance=y,Dt(y),y;u=_w(l),(m=Yn.get(m))&&mp(u,m),y=(i.ownerDocument||i).createElement("link"),Dt(y);var S=y;return S._p=new Promise(function(j,V){S.onload=j,S.onerror=V}),Ft(y,"link",u),a.state.loading|=4,du(y,l.precedence,i),a.instance=y;case"script":return y=La(l.src),(m=i.querySelector(al(y)))?(a.instance=m,Dt(m),m):(u=l,(m=Yn.get(y))&&(u=b({},l),yp(u,m)),i=i.ownerDocument||i,m=i.createElement("script"),Dt(m),Ft(m,"link",u),i.head.appendChild(m),a.instance=m);case"void":return null;default:throw Error(r(443,a.type))}else a.type==="stylesheet"&&(a.state.loading&4)===0&&(u=a.instance,a.state.loading|=4,du(u,l.precedence,i));return a.instance}function du(i,a,l){for(var u=l.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),m=u.length?u[u.length-1]:null,y=m,S=0;S<u.length;S++){var j=u[S];if(j.dataset.precedence===a)y=j;else if(y!==m)break}y?y.parentNode.insertBefore(i,y.nextSibling):(a=l.nodeType===9?l.head:l,a.insertBefore(i,a.firstChild))}function mp(i,a){i.crossOrigin==null&&(i.crossOrigin=a.crossOrigin),i.referrerPolicy==null&&(i.referrerPolicy=a.referrerPolicy),i.title==null&&(i.title=a.title)}function yp(i,a){i.crossOrigin==null&&(i.crossOrigin=a.crossOrigin),i.referrerPolicy==null&&(i.referrerPolicy=a.referrerPolicy),i.integrity==null&&(i.integrity=a.integrity)}var fu=null;function Aw(i,a,l){if(fu===null){var u=new Map,m=fu=new Map;m.set(l,u)}else m=fu,u=m.get(l),u||(u=new Map,m.set(l,u));if(u.has(i))return u;for(u.set(i,null),l=l.getElementsByTagName(i),m=0;m<l.length;m++){var y=l[m];if(!(y[So]||y[Ut]||i==="link"&&y.getAttribute("rel")==="stylesheet")&&y.namespaceURI!=="http://www.w3.org/2000/svg"){var S=y.getAttribute(a)||"";S=i+S;var j=u.get(S);j?j.push(y):u.set(S,[y])}}return u}function jw(i,a,l){i=i.ownerDocument||i,i.head.insertBefore(l,a==="title"?i.querySelector("head > title"):null)}function BN(i,a,l){if(l===1||a.itemProp!=null)return!1;switch(i){case"meta":case"title":return!0;case"style":if(typeof a.precedence!="string"||typeof a.href!="string"||a.href==="")break;return!0;case"link":if(typeof a.rel!="string"||typeof a.href!="string"||a.href===""||a.onLoad||a.onError)break;switch(a.rel){case"stylesheet":return i=a.disabled,typeof a.precedence=="string"&&i==null;default:return!0}case"script":if(a.async&&typeof a.async!="function"&&typeof a.async!="symbol"&&!a.onLoad&&!a.onError&&a.src&&typeof a.src=="string")return!0}return!1}function kw(i){return!(i.type==="stylesheet"&&(i.state.loading&3)===0)}function qN(i,a,l,u){if(l.type==="stylesheet"&&(typeof u.media!="string"||matchMedia(u.media).matches!==!1)&&(l.state.loading&4)===0){if(l.instance===null){var m=Ma(u.href),y=a.querySelector(il(m));if(y){a=y._p,a!==null&&typeof a=="object"&&typeof a.then=="function"&&(i.count++,i=hu.bind(i),a.then(i,i)),l.state.loading|=4,l.instance=y,Dt(y);return}y=a.ownerDocument||a,u=_w(u),(m=Yn.get(m))&&mp(u,m),y=y.createElement("link"),Dt(y);var S=y;S._p=new Promise(function(j,V){S.onload=j,S.onerror=V}),Ft(y,"link",u),l.instance=y}i.stylesheets===null&&(i.stylesheets=new Map),i.stylesheets.set(l,a),(a=l.state.preload)&&(l.state.loading&3)===0&&(i.count++,l=hu.bind(i),a.addEventListener("load",l),a.addEventListener("error",l))}}var gp=0;function FN(i,a){return i.stylesheets&&i.count===0&&mu(i,i.stylesheets),0<i.count||0<i.imgCount?function(l){var u=setTimeout(function(){if(i.stylesheets&&mu(i,i.stylesheets),i.unsuspend){var y=i.unsuspend;i.unsuspend=null,y()}},6e4+a);0<i.imgBytes&&gp===0&&(gp=62500*xN());var m=setTimeout(function(){if(i.waitingForImages=!1,i.count===0&&(i.stylesheets&&mu(i,i.stylesheets),i.unsuspend)){var y=i.unsuspend;i.unsuspend=null,y()}},(i.imgBytes>gp?50:800)+a);return i.unsuspend=l,function(){i.unsuspend=null,clearTimeout(u),clearTimeout(m)}}:null}function hu(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)mu(this,this.stylesheets);else if(this.unsuspend){var i=this.unsuspend;this.unsuspend=null,i()}}}var pu=null;function mu(i,a){i.stylesheets=null,i.unsuspend!==null&&(i.count++,pu=new Map,a.forEach(zN,i),pu=null,hu.call(i))}function zN(i,a){if(!(a.state.loading&4)){var l=pu.get(i);if(l)var u=l.get(null);else{l=new Map,pu.set(i,l);for(var m=i.querySelectorAll("link[data-precedence],style[data-precedence]"),y=0;y<m.length;y++){var S=m[y];(S.nodeName==="LINK"||S.getAttribute("media")!=="not all")&&(l.set(S.dataset.precedence,S),u=S)}u&&l.set(null,u)}m=a.instance,S=m.getAttribute("data-precedence"),y=l.get(S)||u,y===u&&l.set(null,m),l.set(S,m),this.count++,u=hu.bind(this),m.addEventListener("load",u),m.addEventListener("error",u),y?y.parentNode.insertBefore(m,y.nextSibling):(i=i.nodeType===9?i.head:i,i.insertBefore(m,i.firstChild)),a.state.loading|=4}}var ol={$$typeof:M,Provider:null,Consumer:null,_currentValue:K,_currentValue2:K,_threadCount:0};function PN(i,a,l,u,m,y,S,j,V){this.tag=1,this.containerInfo=i,this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.next=this.pendingContext=this.context=this.cancelPendingCommit=null,this.callbackPriority=0,this.expirationTimes=ff(-1),this.entangledLanes=this.shellSuspendCounter=this.errorRecoveryDisabledLanes=this.expiredLanes=this.warmLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=ff(0),this.hiddenUpdates=ff(null),this.identifierPrefix=u,this.onUncaughtError=m,this.onCaughtError=y,this.onRecoverableError=S,this.pooledCache=null,this.pooledCacheLanes=0,this.formState=V,this.incompleteTransitions=new Map}function Cw(i,a,l,u,m,y,S,j,V,J,ne,ie){return i=new PN(i,a,l,S,V,J,ne,ie,j),a=1,y===!0&&(a|=24),y=kn(3,null,null,a),i.current=y,y.stateNode=i,a=Wf(),a.refCount++,i.pooledCache=a,a.refCount++,y.memoizedState={element:u,isDehydrated:l,cache:a},eh(y),i}function Nw(i){return i?(i=ha,i):ha}function Ow(i,a,l,u,m,y){m=Nw(m),u.context===null?u.context=m:u.pendingContext=m,u=vs(a),u.payload={element:l},y=y===void 0?null:y,y!==null&&(u.callback=y),l=ws(i,u,a),l!==null&&(gn(l,i,a),Bo(l,i,a))}function Rw(i,a){if(i=i.memoizedState,i!==null&&i.dehydrated!==null){var l=i.retryLane;i.retryLane=l!==0&&l<a?l:a}}function bp(i,a){Rw(i,a),(i=i.alternate)&&Rw(i,a)}function Tw(i){if(i.tag===13||i.tag===31){var a=di(i,67108864);a!==null&&gn(a,i,67108864),bp(i,67108864)}}function Dw(i){if(i.tag===13||i.tag===31){var a=Tn();a=hf(a);var l=di(i,a);l!==null&&gn(l,i,a),bp(i,a)}}var yu=!0;function VN(i,a,l,u){var m=P.T;P.T=null;var y=$.p;try{$.p=2,vp(i,a,l,u)}finally{$.p=y,P.T=m}}function HN(i,a,l,u){var m=P.T;P.T=null;var y=$.p;try{$.p=8,vp(i,a,l,u)}finally{$.p=y,P.T=m}}function vp(i,a,l,u){if(yu){var m=wp(u);if(m===null)ip(i,a,u,gu,l),Mw(i,u);else if(KN(m,i,a,l,u))u.stopPropagation();else if(Mw(i,u),a&4&&-1<GN.indexOf(i)){for(;m!==null;){var y=na(m);if(y!==null)switch(y.tag){case 3:if(y=y.stateNode,y.current.memoizedState.isDehydrated){var S=ai(y.pendingLanes);if(S!==0){var j=y;for(j.pendingLanes|=2,j.entangledLanes|=2;S;){var V=1<<31-An(S);j.entanglements[1]|=V,S&=~V}gr(y),(ze&6)===0&&(Xc=_n()+500,tl(0))}}break;case 31:case 13:j=di(y,2),j!==null&&gn(j,y,2),tu(),bp(y,2)}if(y=wp(u),y===null&&ip(i,a,u,gu,l),y===m)break;m=y}m!==null&&u.stopPropagation()}else ip(i,a,u,null,l)}}function wp(i){return i=Sf(i),xp(i)}var gu=null;function xp(i){if(gu=null,i=ta(i),i!==null){var a=o(i);if(a===null)i=null;else{var l=a.tag;if(l===13){if(i=c(a),i!==null)return i;i=null}else if(l===31){if(i=d(a),i!==null)return i;i=null}else if(l===3){if(a.stateNode.current.memoizedState.isDehydrated)return a.tag===3?a.stateNode.containerInfo:null;i=null}else a!==i&&(i=null)}}return gu=i,null}function Iw(i){switch(i){case"beforetoggle":case"cancel":case"click":case"close":case"contextmenu":case"copy":case"cut":case"auxclick":case"dblclick":case"dragend":case"dragstart":case"drop":case"focusin":case"focusout":case"input":case"invalid":case"keydown":case"keypress":case"keyup":case"mousedown":case"mouseup":case"paste":case"pause":case"play":case"pointercancel":case"pointerdown":case"pointerup":case"ratechange":case"reset":case"resize":case"seeked":case"submit":case"toggle":case"touchcancel":case"touchend":case"touchstart":case"volumechange":case"change":case"selectionchange":case"textInput":case"compositionstart":case"compositionend":case"compositionupdate":case"beforeblur":case"afterblur":case"beforeinput":case"blur":case"fullscreenchange":case"focus":case"hashchange":case"popstate":case"select":case"selectstart":return 2;case"drag":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"mousemove":case"mouseout":case"mouseover":case"pointermove":case"pointerout":case"pointerover":case"scroll":case"touchmove":case"wheel":case"mouseenter":case"mouseleave":case"pointerenter":case"pointerleave":return 8;case"message":switch(Rk()){case zg:return 2;case Pg:return 8;case ac:case Tk:return 32;case Vg:return 268435456;default:return 32}default:return 32}}var Sp=!1,Rs=null,Ts=null,Ds=null,ll=new Map,cl=new Map,Is=[],GN="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset".split(" ");function Mw(i,a){switch(i){case"focusin":case"focusout":Rs=null;break;case"dragenter":case"dragleave":Ts=null;break;case"mouseover":case"mouseout":Ds=null;break;case"pointerover":case"pointerout":ll.delete(a.pointerId);break;case"gotpointercapture":case"lostpointercapture":cl.delete(a.pointerId)}}function ul(i,a,l,u,m,y){return i===null||i.nativeEvent!==y?(i={blockedOn:a,domEventName:l,eventSystemFlags:u,nativeEvent:y,targetContainers:[m]},a!==null&&(a=na(a),a!==null&&Tw(a)),i):(i.eventSystemFlags|=u,a=i.targetContainers,m!==null&&a.indexOf(m)===-1&&a.push(m),i)}function KN(i,a,l,u,m){switch(a){case"focusin":return Rs=ul(Rs,i,a,l,u,m),!0;case"dragenter":return Ts=ul(Ts,i,a,l,u,m),!0;case"mouseover":return Ds=ul(Ds,i,a,l,u,m),!0;case"pointerover":var y=m.pointerId;return ll.set(y,ul(ll.get(y)||null,i,a,l,u,m)),!0;case"gotpointercapture":return y=m.pointerId,cl.set(y,ul(cl.get(y)||null,i,a,l,u,m)),!0}return!1}function Lw(i){var a=ta(i.target);if(a!==null){var l=o(a);if(l!==null){if(a=l.tag,a===13){if(a=c(l),a!==null){i.blockedOn=a,Wg(i.priority,function(){Dw(l)});return}}else if(a===31){if(a=d(l),a!==null){i.blockedOn=a,Wg(i.priority,function(){Dw(l)});return}}else if(a===3&&l.stateNode.current.memoizedState.isDehydrated){i.blockedOn=l.tag===3?l.stateNode.containerInfo:null;return}}}i.blockedOn=null}function bu(i){if(i.blockedOn!==null)return!1;for(var a=i.targetContainers;0<a.length;){var l=wp(i.nativeEvent);if(l===null){l=i.nativeEvent;var u=new l.constructor(l.type,l);xf=u,l.target.dispatchEvent(u),xf=null}else return a=na(l),a!==null&&Tw(a),i.blockedOn=l,!1;a.shift()}return!0}function Uw(i,a,l){bu(i)&&l.delete(a)}function YN(){Sp=!1,Rs!==null&&bu(Rs)&&(Rs=null),Ts!==null&&bu(Ts)&&(Ts=null),Ds!==null&&bu(Ds)&&(Ds=null),ll.forEach(Uw),cl.forEach(Uw)}function vu(i,a){i.blockedOn===a&&(i.blockedOn=null,Sp||(Sp=!0,t.unstable_scheduleCallback(t.unstable_NormalPriority,YN)))}var wu=null;function $w(i){wu!==i&&(wu=i,t.unstable_scheduleCallback(t.unstable_NormalPriority,function(){wu===i&&(wu=null);for(var a=0;a<i.length;a+=3){var l=i[a],u=i[a+1],m=i[a+2];if(typeof u!="function"){if(xp(u||l)===null)continue;break}var y=na(l);y!==null&&(i.splice(a,3),a-=3,wh(y,{pending:!0,data:m,method:l.method,action:u},u,m))}}))}function Ua(i){function a(V){return vu(V,i)}Rs!==null&&vu(Rs,i),Ts!==null&&vu(Ts,i),Ds!==null&&vu(Ds,i),ll.forEach(a),cl.forEach(a);for(var l=0;l<Is.length;l++){var u=Is[l];u.blockedOn===i&&(u.blockedOn=null)}for(;0<Is.length&&(l=Is[0],l.blockedOn===null);)Lw(l),l.blockedOn===null&&Is.shift();if(l=(i.ownerDocument||i).$$reactFormReplay,l!=null)for(u=0;u<l.length;u+=3){var m=l[u],y=l[u+1],S=m[dn]||null;if(typeof y=="function")S||$w(l);else if(S){var j=null;if(y&&y.hasAttribute("formAction")){if(m=y,S=y[dn]||null)j=S.formAction;else if(xp(m)!==null)continue}else j=S.action;typeof j=="function"?l[u+1]=j:(l.splice(u,3),u-=3),$w(l)}}}function Bw(){function i(y){y.canIntercept&&y.info==="react-transition"&&y.intercept({handler:function(){return new Promise(function(S){return m=S})},focusReset:"manual",scroll:"manual"})}function a(){m!==null&&(m(),m=null),u||setTimeout(l,20)}function l(){if(!u&&!navigation.transition){var y=navigation.currentEntry;y&&y.url!=null&&navigation.navigate(y.url,{state:y.getState(),info:"react-transition",history:"replace"})}}if(typeof navigation=="object"){var u=!1,m=null;return navigation.addEventListener("navigate",i),navigation.addEventListener("navigatesuccess",a),navigation.addEventListener("navigateerror",a),setTimeout(l,100),function(){u=!0,navigation.removeEventListener("navigate",i),navigation.removeEventListener("navigatesuccess",a),navigation.removeEventListener("navigateerror",a),m!==null&&(m(),m=null)}}}function _p(i){this._internalRoot=i}xu.prototype.render=_p.prototype.render=function(i){var a=this._internalRoot;if(a===null)throw Error(r(409));var l=a.current,u=Tn();Ow(l,u,i,a,null,null)},xu.prototype.unmount=_p.prototype.unmount=function(){var i=this._internalRoot;if(i!==null){this._internalRoot=null;var a=i.containerInfo;Ow(i.current,2,null,i,null,null),tu(),a[ea]=null}};function xu(i){this._internalRoot=i}xu.prototype.unstable_scheduleHydration=function(i){if(i){var a=Zg();i={blockedOn:null,target:i,priority:a};for(var l=0;l<Is.length&&a!==0&&a<Is[l].priority;l++);Is.splice(l,0,i),l===0&&Lw(i)}};var qw=e.version;if(qw!=="19.2.7")throw Error(r(527,qw,"19.2.7"));$.findDOMNode=function(i){var a=i._reactInternals;if(a===void 0)throw typeof i.render=="function"?Error(r(188)):(i=Object.keys(i).join(","),Error(r(268,i)));return i=p(a),i=i!==null?g(i):null,i=i===null?null:i.stateNode,i};var ZN={bundleType:0,version:"19.2.7",rendererPackageName:"react-dom",currentDispatcherRef:P,reconcilerVersion:"19.2.7"};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"){var Su=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!Su.isDisabled&&Su.supportsFiber)try{vo=Su.inject(ZN),En=Su}catch{}}return fl.createRoot=function(i,a){if(!s(i))throw Error(r(299));var l=!1,u="",m=Kv,y=Yv,S=Zv;return a!=null&&(a.unstable_strictMode===!0&&(l=!0),a.identifierPrefix!==void 0&&(u=a.identifierPrefix),a.onUncaughtError!==void 0&&(m=a.onUncaughtError),a.onCaughtError!==void 0&&(y=a.onCaughtError),a.onRecoverableError!==void 0&&(S=a.onRecoverableError)),a=Cw(i,1,!1,null,null,l,u,null,m,y,S,Bw),i[ea]=a.current,sp(i),new _p(a)},fl.hydrateRoot=function(i,a,l){if(!s(i))throw Error(r(299));var u=!1,m="",y=Kv,S=Yv,j=Zv,V=null;return l!=null&&(l.unstable_strictMode===!0&&(u=!0),l.identifierPrefix!==void 0&&(m=l.identifierPrefix),l.onUncaughtError!==void 0&&(y=l.onUncaughtError),l.onCaughtError!==void 0&&(S=l.onCaughtError),l.onRecoverableError!==void 0&&(j=l.onRecoverableError),l.formState!==void 0&&(V=l.formState)),a=Cw(i,1,!0,a,l??null,u,m,V,y,S,j,Bw),a.context=Nw(null),l=a.current,u=Tn(),u=hf(u),m=vs(u),m.callback=null,ws(l,m,u),l=u,a.current.lanes=l,xo(a,l),gr(a),i[ea]=a.current,sp(i),new xu(a)},fl.version="19.2.7",fl}var Ww;function oO(){if(Ww)return jp.exports;Ww=1;function t(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(t)}catch(e){console.error(e)}}return t(),jp.exports=aO(),jp.exports}var lO=oO();const cO="modulepreload",uO=function(t){return"/__pyric/ui/"+t},Qw={},p1=function(e,n,r){let s=Promise.resolve();if(n&&n.length>0){let c=function(p){return Promise.all(p.map(g=>Promise.resolve(g).then(b=>({status:"fulfilled",value:b}),b=>({status:"rejected",reason:b}))))};document.getElementsByTagName("link");const d=document.querySelector("meta[property=csp-nonce]"),f=(d==null?void 0:d.nonce)||(d==null?void 0:d.getAttribute("nonce"));s=c(n.map(p=>{if(p=uO(p),p in Qw)return;Qw[p]=!0;const g=p.endsWith(".css"),b=g?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${p}"]${b}`))return;const v=document.createElement("link");if(v.rel=g?"stylesheet":cO,g||(v.as="script"),v.crossOrigin="",v.href=p,f&&v.setAttribute("nonce",f),document.head.appendChild(v),g)return new Promise((w,_)=>{v.addEventListener("load",w),v.addEventListener("error",()=>_(new Error(`Unable to preload CSS for ${p}`)))})}))}function o(c){const d=new Event("vite:preloadError",{cancelable:!0});if(d.payload=c,window.dispatchEvent(d),!d.defaultPrevented)throw c}return s.then(c=>{for(const d of c||[])d.status==="rejected"&&o(d.reason);return e().catch(o)})};function m1(t){return t.kind==="session_boundary"&&t.phase==="reset"}function dO(t,e){return m1(e)?[e]:[...t,e]}const y1=A.createContext(null),g1={status:"disabled",handles:null,events:[]};function fO({children:t}){return h.jsx(y1.Provider,{value:g1,children:t})}function cs(){return A.useContext(y1)??g1}function ln(t){const e=t||"";return function(){throw new Error("this method "+e+" is abstract! (it has no implementation in class "+this.constructor.name+")")}}function ti(t,e){if(!t)throw new Error(e||"Assertion failed")}function hm(t,e,n){let r;Object.defineProperty(t,e,{get(){return r||(r=n.call(this)),r}})}function b1(t,e){const n=[];for(;e-- >0;)n.push(t());return n}function v1(t,e){return new Array(e+1).join(t)}function Cd(t,e){return b1(()=>t,e)}function pm(t){const e=[];for(let n=0;n<t.length;n++){const r=t[n];t.lastIndexOf(r)!==n&&e.indexOf(r)<0&&e.push(r)}return e}function w1(t){const e=[];return t.forEach(n=>{e.indexOf(n)<0&&e.push(n)}),e}function Ii(t){const e=t[0];return e===e.toUpperCase()}function x1(t){return!Ii(t)}function S1(t,e,n){return t.length<e?v1(" ",e-t.length)+t:t}function Gi(){this.strings=[]}Gi.prototype.append=function(t){this.strings.push(t)};Gi.prototype.contents=function(){return this.strings.join("")};const Op=t=>String.fromCodePoint(parseInt(t,16));function _1(t){if(t.charAt(0)==="\\")switch(t.charAt(1)){case"b":return"\b";case"f":return"\f";case"n":return`
50
- `;case"r":return"\r";case"t":return" ";case"v":return"\v";case"x":return Op(t.slice(2,4));case"u":return t.charAt(2)==="{"?Op(t.slice(3,-1)):Op(t.slice(2,6));default:return t.charAt(1)}else return t}function qy(t){if(t==null)return String(t);const e=Object.prototype.toString.call(t);try{let n;return t.constructor&&t.constructor.name?n=t.constructor.name:e.indexOf("[object ")===0?n=e.slice(8,-1):n=typeof t,n+": "+JSON.stringify(String(t))}catch{return e}}function E1(t,e="unexpected null value"){if(t==null)throw new Error(e);return t}const hO=Object.freeze(Object.defineProperty({__proto__:null,StringBuffer:Gi,abstract:ln,assert:ti,checkNotNull:E1,copyWithoutDuplicates:w1,defineLazyProperty:hm,getDuplicates:pm,isLexical:x1,isSyntactic:Ii,padLeft:S1,repeat:Cd,repeatFn:b1,repeatStr:v1,unescapeCodePoint:_1,unexpectedObjToString:qy},Symbol.toStringTag,{value:"Module"})),A1=t=>new RegExp(String.raw`\p{${t}}`,"u"),mm=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,A1(t)]));mm.Ltmo=new RegExp("\\p{Lt}|\\p{Lm}|\\p{Lo}","u");const Jw=Object.fromEntries(["XID_Start","XID_Continue","White_Space"].map(t=>[t,A1(t)]));class we{constructor(){if(this.constructor===we)throw new Error("PExpr cannot be instantiated -- it's abstract")}withSource(e){return e&&(this.source=e.trimmed()),this}}const Qt=Object.create(we.prototype),Jt=Object.create(we.prototype);class Gt extends we{constructor(e){super(),this.obj=e}}class Xt extends we{constructor(e,n){super(),this.from=e,this.to=n,this.matchCodePoint=e.length>1||n.length>1}}class en extends we{constructor(e){super(),this.index=e}}class Tt extends we{constructor(e){super(),this.terms=e}}class Nd extends Tt{constructor(e,n,r){const s=e.rules[n].body;super([r,s]),this.superGrammar=e,this.name=n,this.body=r}}class Od extends Tt{constructor(e,n,r,s){const o=e.rules[n].body;super([...r,o,...s]),this.superGrammar=e,this.ruleName=n,this.expansionPos=r.length}}class Lt extends we{constructor(e){super(),this.factors=e}}class cn extends we{constructor(e){super(),this.expr=e}}class Ki extends cn{}class co extends cn{}class us extends cn{}Ki.prototype.operator="*";co.prototype.operator="+";us.prototype.operator="?";Ki.prototype.minNumMatches=0;co.prototype.minNumMatches=1;us.prototype.minNumMatches=0;Ki.prototype.maxNumMatches=Number.POSITIVE_INFINITY;co.prototype.maxNumMatches=Number.POSITIVE_INFINITY;us.prototype.maxNumMatches=1;class Vt extends we{constructor(e){super(),this.expr=e}}class un extends we{constructor(e){super(),this.expr=e}}class xn extends we{constructor(e){super(),this.expr=e}}class Ze extends we{constructor(e,n=[]){super(),this.ruleName=e,this.args=n}isSyntactic(){return Ii(this.ruleName)}toMemoKey(){return this._memoKey||Object.defineProperty(this,"_memoKey",{value:this.toString()}),this._memoKey}}class Ht extends we{constructor(e){if(super(),this.categoryOrProp=e,e in mm)this.pattern=mm[e];else if(e in Jw)this.pattern=Jw[e];else throw new Error(`Invalid Unicode category or property name: ${JSON.stringify(e)}`)}}function bt(t,e){let n;return e?(n=new Error(e.getLineAndColumnMessage()+t),n.shortMessage=t,n.interval=e):n=new Error(t),n}function ym(){return bt("Interval sources don't match")}function pO(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 mO(t,e,n){const r=e?`Grammar ${t} is not declared in namespace '${e}'`:"Undeclared grammar "+t;return bt(r,n)}function yO(t,e){return bt("Grammar "+t.name+" is already declared in this namespace")}function gO(t){return bt(`Grammar '${t.name}' does not support incremental parsing`)}function j1(t,e,n){return bt("Rule "+t+" is not declared in grammar "+e,n)}function bO(t,e,n){return bt("Cannot override rule "+t+" because it is not declared in "+e,n)}function vO(t,e,n){return bt("Cannot extend rule "+t+" because it is not declared in "+e,n)}function Xw(t,e,n,r){let s="Duplicate declaration for rule '"+t+"' in grammar '"+e+"'";return e!==n&&(s+=" (originally declared in '"+n+"')"),bt(s,r)}function k1(t,e,n,r){return bt("Wrong number of parameters for rule "+t+" (expected "+e+", got "+n+")",r)}function wO(t,e,n,r){return bt("Wrong number of arguments for rule "+t+" (expected "+e+", got "+n+")",r)}function ex(t,e,n){return bt("Duplicate parameter names in rule "+t+": "+e.join(", "),n)}function xO(t,e){return bt("Invalid parameter to rule "+t+": "+e+" has arity "+e.getArity()+", but parameter expressions must have arity 1",e.source)}const SO="NOTE: A _syntactic rule_ is a rule whose name begins with a capital letter. See https://ohmjs.org/d/svl for more details.";function _O(t,e){return bt("Cannot apply syntactic rule "+t+" from here (inside a lexical context)",e.source)}function EO(t){const{ruleName:e}=t;return bt(`applySyntactic is for syntactic rules, but '${e}' is a lexical rule. `+SO,t.source)}function AO(t){return bt("applySyntactic is not required here (in a syntactic context)",t.source)}function tx(t,e){return bt("Incorrect argument type: expected "+t,e.source)}function jO(t){return bt("'...' can appear at most once in a rule body",t.source)}function kO(t){const e=t._node;ti(e&&e.isNonterminal()&&e.ctorName==="escapeChar_unicodeCodePoint");const n=t.children.slice(1,-1).map(s=>s.source),r=n[0].coverageWith(...n.slice(1));return bt(`U+${r.contents} is not a valid Unicode code point`,r)}function C1(t,e){const n=e.length>0?e[e.length-1].args:[];let s="Nullable expression "+t.expr.substituteParams(n)+" is not allowed inside '"+t.operator+"' (possible infinite loop)";if(e.length>0){const o=e.map(c=>new Ze(c.ruleName,c.args)).join(`
51
- `);s+=`
52
- Application stack (most recent application last):
53
- `+o}return bt(s,t.expr.source)}function N1(t,e,n,r){return bt("Rule "+t+" involves an alternation which has inconsistent arity (expected "+e+", got "+n+")",r.source)}function CO(t){const e=t.map(n=>n.message);return bt(["Errors:"].concat(e).join(`
54
- - `),t[0].interval)}function NO(t,e,n,r){let s=r.slice(0,-1).map(f=>{const p=" "+f[0].name+" > "+f[1];return f.length===3?p+" for '"+f[2]+"'":p}).join(`
55
- `);s+=`
56
- `+e+" > "+t;let o="";t==="_iter"&&(o=[`
57
- NOTE: as of Ohm v16, there is no default action for iteration nodes — see `," https://ohmjs.org/d/dsa for details."].join(`
58
- `));const c=[`Missing semantic action for '${t}' in ${n} '${e}'.${o}`,"Action stack (most recent call last):",s].join(`
59
- `),d=bt(c);return d.name="missingSemanticAction",d}function OO(t){if(t.length===1)throw t[0];if(t.length>1)throw CO(t)}function RO(t){let e=0;return t.map(r=>{const s=r.toString();return e=Math.max(e,s.length),s}).map(r=>S1(r,e))}function nx(t,e,n){const r=t.length,s=t.slice(0,n),o=t.slice(n+e.length);return(s+e+o).substr(0,r)}function TO(...t){const e=this,{offset:n}=e,{repeatStr:r}=hO,s=new Gi;s.append("Line "+e.lineNum+", col "+e.colNum+`:
60
- `);const o=RO([e.prevLine==null?0:e.lineNum-1,e.lineNum,e.nextLine==null?0:e.lineNum+1]),c=(g,b,v)=>{s.append(v+o[g]+" | "+b+`
61
- `)};e.prevLine!=null&&c(0,e.prevLine," "),c(1,e.line,"> ");const d=e.line.length;let f=r(" ",d+1);for(let g=0;g<t.length;++g){let b=t[g][0],v=t[g][1];ti(b>=0&&b<=v,"range start must be >= 0 and <= end");const w=n-e.colNum+1;b=Math.max(0,b-w),v=Math.min(v-w,d),f=nx(f,r("~",v-b),b)}const p=2+o[1].length+3;return s.append(r(" ",p)),f=nx(f,"^",e.colNum-1),s.append(f.replace(/ +$/,"")+`
62
- `),e.nextLine!=null&&c(2,e.nextLine," "),s.contents()}let gm=[];function O1(t){gm.push(t)}function DO(t){gm.forEach(e=>{e(t)}),gm=null}function Fy(t,e){let n=1,r=1,s=0,o=0,c=null,d=null,f=-1;for(;s<e;){const b=t.charAt(s++);b===`
63
- `?(n++,r=1,f=o,o=s):b!=="\r"&&r++}let p=t.indexOf(`
64
- `,o);if(p===-1)p=t.length;else{const b=t.indexOf(`
65
- `,p+1);c=b===-1?t.slice(p):t.slice(p,b),c=c.replace(/^\r?\n/,"").replace(/\r$/,"")}f>=0&&(d=t.slice(f,o).replace(/\r?\n$/,""));const g=t.slice(o,p).replace(/\r$/,"");return{offset:e,lineNum:n,colNum:r,line:g,prevLine:d,nextLine:c,toString:TO}}function zy(t,e,...n){return Fy(t,e).toString(...n)}const rx=(()=>{let t=0;return e=>""+e+t++})();class Yt{constructor(e,n,r){Object.defineProperty(this,"_sourceString",{value:e,configurable:!1,enumerable:!1,writable:!1}),this.startIdx=n,this.endIdx=r}get sourceString(){return this._sourceString}get contents(){return this._contents===void 0&&(this._contents=this.sourceString.slice(this.startIdx,this.endIdx)),this._contents}get length(){return this.endIdx-this.startIdx}coverageWith(...e){return Yt.coverage(...e,this)}collapsedLeft(){return new Yt(this.sourceString,this.startIdx,this.startIdx)}collapsedRight(){return new Yt(this.sourceString,this.endIdx,this.endIdx)}getLineAndColumn(){return Fy(this.sourceString,this.startIdx)}getLineAndColumnMessage(){const e=[this.startIdx,this.endIdx];return zy(this.sourceString,this.startIdx,e)}minus(e){if(this.sourceString!==e.sourceString)throw ym();return this.startIdx===e.startIdx&&this.endIdx===e.endIdx?[]:this.startIdx<e.startIdx&&e.endIdx<this.endIdx?[new Yt(this.sourceString,this.startIdx,e.startIdx),new Yt(this.sourceString,e.endIdx,this.endIdx)]:this.startIdx<e.endIdx&&e.endIdx<this.endIdx?[new Yt(this.sourceString,e.endIdx,this.endIdx)]:this.startIdx<e.startIdx&&e.startIdx<this.endIdx?[new Yt(this.sourceString,this.startIdx,e.startIdx)]:[this]}relativeTo(e){if(this.sourceString!==e.sourceString)throw ym();return ti(this.startIdx>=e.startIdx&&this.endIdx<=e.endIdx,"other interval does not cover this one"),new Yt(this.sourceString,this.startIdx-e.startIdx,this.endIdx-e.startIdx)}trimmed(){const{contents:e}=this,n=this.startIdx+e.match(/^\s*/)[0].length,r=this.endIdx-e.match(/\s*$/)[0].length;return new Yt(this.sourceString,n,r)}subInterval(e,n){const r=this.startIdx+e;return new Yt(this.sourceString,r,r+n)}}Yt.coverage=function(t,...e){let{startIdx:n,endIdx:r}=t;for(const s of e){if(s.sourceString!==t.sourceString)throw ym();n=Math.min(n,s.startIdx),r=Math.max(r,s.endIdx)}return new Yt(t.sourceString,n,r)};const IO=65535,MO=1114111;class Rd{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>IO&&(this.pos+=1),this.examinedLength=Math.max(this.examinedLength,this.pos),e}matchString(e,n){let r;if(n){for(r=0;r<e.length;r++){const s=this.next(),o=e[r];if(s==null||s.toUpperCase()!==o.toUpperCase())return!1}return!0}for(r=0;r<e.length;r++)if(this.next()!==e[r])return!1;return!0}sourceSlice(e,n){return this.source.slice(e,n)}interval(e,n){return new Yt(this.source,e,n||this.pos)}}class R1{constructor(e,n,r,s,o,c,d){this.matcher=e,this.input=n,this.startExpr=r,this._cst=s,this._cstOffset=o,this._rightmostFailurePosition=c,this._rightmostFailures=d,this.failed()&&(hm(this,"message",function(){const f="Expected "+this.getExpectedText();return zy(this.input,this.getRightmostFailurePosition())+f}),hm(this,"shortMessage",function(){const f="expected "+this.getExpectedText(),p=Fy(this.input,this.getRightmostFailurePosition());return"Line "+p.lineNum+", col "+p.colNum+": "+f}))}succeeded(){return!!this._cst}failed(){return!this.succeeded()}getRightmostFailurePosition(){return this._rightmostFailurePosition}getRightmostFailures(){if(!this._rightmostFailures){this.matcher.setInput(this.input);const e=this.matcher._match(this.startExpr,{tracing:!1,positionToRecordFailures:this.getRightmostFailurePosition()});this._rightmostFailures=e.getRightmostFailures()}return this._rightmostFailures}toString(){return this.succeeded()?"[match succeeded]":"[match failed at position "+this.getRightmostFailurePosition()+"]"}getExpectedText(){if(this.succeeded())throw new Error("cannot get expected text of a successful MatchResult");const e=new Gi;let n=this.getRightmostFailures();n=n.filter(r=>!r.isFluffy());for(let r=0;r<n.length;r++)r>0&&(r===n.length-1?e.append(n.length>2?", or ":" or "):e.append(", ")),e.append(n[r].toString());return e.contents()}getInterval(){const e=this.getRightmostFailurePosition();return new Yt(this.input,e,e)}}class LO{constructor(){this.applicationMemoKeyStack=[],this.memo={},this.maxExaminedLength=0,this.maxRightmostFailureOffset=-1,this.currentLeftRecursion=void 0}isActive(e){return this.applicationMemoKeyStack.indexOf(e.toMemoKey())>=0}enter(e){this.applicationMemoKeyStack.push(e.toMemoKey())}exit(){this.applicationMemoKeyStack.pop()}startLeftRecursion(e,n){n.isLeftRecursion=!0,n.headApplication=e,n.nextLeftRecursion=this.currentLeftRecursion,this.currentLeftRecursion=n;const{applicationMemoKeyStack:r}=this,s=r.indexOf(e.toMemoKey())+1,o=r.slice(s);n.isInvolved=function(c){return o.indexOf(c)>=0},n.updateInvolvedApplicationMemoKeys=function(){for(let c=s;c<r.length;c++){const d=r[c];this.isInvolved(d)||o.push(d)}}}endLeftRecursion(){this.currentLeftRecursion=this.currentLeftRecursion.nextLeftRecursion}shouldUseMemoizedResult(e){if(!e.isLeftRecursion)return!0;const{applicationMemoKeyStack:n}=this;for(let r=0;r<n.length;r++){const s=n[r];if(e.isInvolved(s))return!1}return!0}memoize(e,n){return this.memo[e]=n,this.maxExaminedLength=Math.max(this.maxExaminedLength,n.examinedLength),this.maxRightmostFailureOffset=Math.max(this.maxRightmostFailureOffset,n.rightmostFailureOffset),n}clearObsoleteEntries(e,n){if(e+this.maxExaminedLength<=n)return;const{memo:r}=this;this.maxExaminedLength=0,this.maxRightmostFailureOffset=-1,Object.keys(r).forEach(s=>{const o=r[s];e+o.examinedLength>n?delete r[s]:(this.maxExaminedLength=Math.max(this.maxExaminedLength,o.examinedLength),this.maxRightmostFailureOffset=Math.max(this.maxRightmostFailureOffset,o.rightmostFailureOffset))})}}const UO="✗",$O="✓",BO="⋅",qO="⇒",FO="␉",zO="␊",PO="␍",bm={succeeded:1,isRootNode:2,isImplicitSpaces:4,isMemoized:8,isHeadOfLeftRecursion:16,terminatesLR:32};function VO(t){return Cd(" ",t).join("")}function HO(t,e,n){const r=T1(t.slice(e,e+n));return r.length<n?r+Cd(" ",n-r.length).join(""):r}function T1(t){return typeof t=="string"?t.replace(/ /g,BO).replace(/\t/g,FO).replace(/\n/g,zO).replace(/\r/g,PO):String(t)}class Gs{constructor(e,n,r,s,o,c,d){this.input=e,this.pos=this.pos1=n,this.pos2=r,this.source=new Yt(e,n,r),this.expr=s,this.bindings=c,this.children=d||[],this.terminatingLREntry=null,this._flags=o?bm.succeeded:0}get displayString(){return this.expr.toDisplayString()}clone(){return this.cloneWithExpr(this.expr)}cloneWithExpr(e){const n=new Gs(this.input,this.pos,this.pos2,e,this.succeeded,this.bindings,this.children);return n.isHeadOfLeftRecursion=this.isHeadOfLeftRecursion,n.isImplicitSpaces=this.isImplicitSpaces,n.isMemoized=this.isMemoized,n.isRootNode=this.isRootNode,n.terminatesLR=this.terminatesLR,n.terminatingLREntry=this.terminatingLREntry,n}recordLRTermination(e,n){this.terminatingLREntry=new Gs(this.input,this.pos,this.pos2,this.expr,!1,[n],[e]),this.terminatingLREntry.terminatesLR=!0}walk(e,n){let r=e;typeof r=="function"&&(r={enter:r});function s(o,c,d){let f=!0;r.enter&&r.enter.call(n,o,c,d)===Gs.prototype.SKIP&&(f=!1),f&&(o.children.forEach(p=>{s(p,o,d+1)}),r.exit&&r.exit.call(n,o,c,d))}this.isRootNode?this.children.forEach(o=>{s(o,null,0)}):s(this,null,0)}toString(){const e=new Gi;return this.walk((n,r,s)=>{if(!n)return this.SKIP;if(n.expr.constructor.name!=="Alt"){if(e.append(HO(n.input,n.pos,10)+VO(s*2+1)),e.append((n.succeeded?$O:UO)+" "+n.displayString),n.isHeadOfLeftRecursion&&e.append(" (LR)"),n.succeeded){const c=T1(n.source.contents);e.append(" "+qO+" "),e.append(typeof c=="string"?'"'+c+'"':c)}e.append(`
66
- `)}}),e.contents()}}Gs.prototype.SKIP={};Object.keys(bm).forEach(t=>{const e=bm[t];Object.defineProperty(Gs.prototype,t,{get(){return(this._flags&e)!==0},set(n){n?this._flags|=e:this._flags&=~e}})});we.prototype.allowsSkippingPrecedingSpace=ln("allowsSkippingPrecedingSpace");Qt.allowsSkippingPrecedingSpace=Jt.allowsSkippingPrecedingSpace=Ze.prototype.allowsSkippingPrecedingSpace=Gt.prototype.allowsSkippingPrecedingSpace=Xt.prototype.allowsSkippingPrecedingSpace=Ht.prototype.allowsSkippingPrecedingSpace=function(){return!0};Tt.prototype.allowsSkippingPrecedingSpace=cn.prototype.allowsSkippingPrecedingSpace=xn.prototype.allowsSkippingPrecedingSpace=un.prototype.allowsSkippingPrecedingSpace=Vt.prototype.allowsSkippingPrecedingSpace=en.prototype.allowsSkippingPrecedingSpace=Lt.prototype.allowsSkippingPrecedingSpace=function(){return!1};let vl;O1(t=>{vl=t});let Vu;we.prototype.assertAllApplicationsAreValid=function(t,e){Vu=0,this._assertAllApplicationsAreValid(t,e)};we.prototype._assertAllApplicationsAreValid=ln("_assertAllApplicationsAreValid");Qt._assertAllApplicationsAreValid=Jt._assertAllApplicationsAreValid=Gt.prototype._assertAllApplicationsAreValid=Xt.prototype._assertAllApplicationsAreValid=en.prototype._assertAllApplicationsAreValid=Ht.prototype._assertAllApplicationsAreValid=function(t,e){};xn.prototype._assertAllApplicationsAreValid=function(t,e){Vu++,this.expr._assertAllApplicationsAreValid(t,e),Vu--};Tt.prototype._assertAllApplicationsAreValid=function(t,e){for(let n=0;n<this.terms.length;n++)this.terms[n]._assertAllApplicationsAreValid(t,e)};Lt.prototype._assertAllApplicationsAreValid=function(t,e){for(let n=0;n<this.factors.length;n++)this.factors[n]._assertAllApplicationsAreValid(t,e)};cn.prototype._assertAllApplicationsAreValid=Vt.prototype._assertAllApplicationsAreValid=un.prototype._assertAllApplicationsAreValid=function(t,e){this.expr._assertAllApplicationsAreValid(t,e)};Ze.prototype._assertAllApplicationsAreValid=function(t,e,n=!1){const r=e.rules[this.ruleName],s=Ii(t)&&Vu===0;if(!r)throw j1(this.ruleName,e.name,this.source);if(!n&&Ii(this.ruleName)&&!s)throw _O(this.ruleName,this);const o=this.args.length,c=r.formals.length;if(o!==c)throw wO(this.ruleName,c,o,this.source);const d=vl&&r===vl.rules.applySyntactic;if(vl&&r===vl.rules.caseInsensitive&&!(this.args[0]instanceof Gt))throw tx('a Terminal (e.g. "abc")',this.args[0]);if(d){const p=this.args[0];if(!(p instanceof Ze))throw tx("a syntactic rule application",p);if(!Ii(p.ruleName))throw EO(p);if(s)throw AO(this)}this.args.forEach(p=>{if(p._assertAllApplicationsAreValid(t,e,d),p.getArity()!==1)throw xO(this.ruleName,p)})};we.prototype.assertChoicesHaveUniformArity=ln("assertChoicesHaveUniformArity");Qt.assertChoicesHaveUniformArity=Jt.assertChoicesHaveUniformArity=Gt.prototype.assertChoicesHaveUniformArity=Xt.prototype.assertChoicesHaveUniformArity=en.prototype.assertChoicesHaveUniformArity=xn.prototype.assertChoicesHaveUniformArity=Ht.prototype.assertChoicesHaveUniformArity=function(t){};Tt.prototype.assertChoicesHaveUniformArity=function(t){if(this.terms.length===0)return;const e=this.terms[0].getArity();for(let n=0;n<this.terms.length;n++){const r=this.terms[n];r.assertChoicesHaveUniformArity();const s=r.getArity();if(e!==s)throw N1(t,e,s,r)}};Nd.prototype.assertChoicesHaveUniformArity=function(t){const e=this.terms[0].getArity(),n=this.terms[1].getArity();if(e!==n)throw N1(t,n,e,this.terms[0])};Lt.prototype.assertChoicesHaveUniformArity=function(t){for(let e=0;e<this.factors.length;e++)this.factors[e].assertChoicesHaveUniformArity(t)};cn.prototype.assertChoicesHaveUniformArity=function(t){this.expr.assertChoicesHaveUniformArity(t)};Vt.prototype.assertChoicesHaveUniformArity=function(t){};un.prototype.assertChoicesHaveUniformArity=function(t){this.expr.assertChoicesHaveUniformArity(t)};Ze.prototype.assertChoicesHaveUniformArity=function(t){};we.prototype.assertIteratedExprsAreNotNullable=ln("assertIteratedExprsAreNotNullable");Qt.assertIteratedExprsAreNotNullable=Jt.assertIteratedExprsAreNotNullable=Gt.prototype.assertIteratedExprsAreNotNullable=Xt.prototype.assertIteratedExprsAreNotNullable=en.prototype.assertIteratedExprsAreNotNullable=Ht.prototype.assertIteratedExprsAreNotNullable=function(t){};Tt.prototype.assertIteratedExprsAreNotNullable=function(t){for(let e=0;e<this.terms.length;e++)this.terms[e].assertIteratedExprsAreNotNullable(t)};Lt.prototype.assertIteratedExprsAreNotNullable=function(t){for(let e=0;e<this.factors.length;e++)this.factors[e].assertIteratedExprsAreNotNullable(t)};cn.prototype.assertIteratedExprsAreNotNullable=function(t){if(this.expr.assertIteratedExprsAreNotNullable(t),this.expr.isNullable(t))throw C1(this,[])};us.prototype.assertIteratedExprsAreNotNullable=Vt.prototype.assertIteratedExprsAreNotNullable=un.prototype.assertIteratedExprsAreNotNullable=xn.prototype.assertIteratedExprsAreNotNullable=function(t){this.expr.assertIteratedExprsAreNotNullable(t)};Ze.prototype.assertIteratedExprsAreNotNullable=function(t){this.args.forEach(e=>{e.assertIteratedExprsAreNotNullable(t)})};let Py=class{constructor(e){this.matchLength=e}get ctorName(){throw new Error("subclass responsibility")}numChildren(){return this.children?this.children.length:0}childAt(e){if(this.children)return this.children[e]}indexOfChild(e){return this.children.indexOf(e)}hasChildren(){return this.numChildren()>0}hasNoChildren(){return!this.hasChildren()}onlyChild(){if(this.numChildren()!==1)throw new Error("cannot get only child of a node of type "+this.ctorName+" (it has "+this.numChildren()+" children)");return this.firstChild()}firstChild(){if(this.hasNoChildren())throw new Error("cannot get first child of a "+this.ctorName+" node, which has no children");return this.childAt(0)}lastChild(){if(this.hasNoChildren())throw new Error("cannot get last child of a "+this.ctorName+" node, which has no children");return this.childAt(this.numChildren()-1)}childBefore(e){const n=this.indexOfChild(e);if(n<0)throw new Error("Node.childBefore() called w/ an argument that is not a child");if(n===0)throw new Error("cannot get child before first child");return this.childAt(n-1)}childAfter(e){const n=this.indexOfChild(e);if(n<0)throw new Error("Node.childAfter() called w/ an argument that is not a child");if(n===this.numChildren()-1)throw new Error("cannot get child after last child");return this.childAt(n+1)}isTerminal(){return!1}isNonterminal(){return!1}isIteration(){return!1}isOptional(){return!1}};class Yi extends Py{get ctorName(){return"_terminal"}isTerminal(){return!0}get primitiveValue(){throw new Error("The `primitiveValue` property was removed in Ohm v17.")}}class GO extends Py{constructor(e,n,r,s){super(s),this.ruleName=e,this.children=n,this.childOffsets=r}get ctorName(){return this.ruleName}isNonterminal(){return!0}isLexical(){return x1(this.ctorName)}isSyntactic(){return Ii(this.ctorName)}}class D1 extends Py{constructor(e,n,r,s){super(r),this.children=e,this.childOffsets=n,this.optional=s}get ctorName(){return"_iter"}isIteration(){return!0}isOptional(){return this.optional}}we.prototype.eval=ln("eval");Qt.eval=function(t){const{inputStream:e}=t,n=e.pos,r=e.nextCodePoint();return r!==void 0?(t.pushBinding(new Yi(String.fromCodePoint(r).length),n),!0):(t.processFailure(n,this),!1)};Jt.eval=function(t){const{inputStream:e}=t,n=e.pos;return e.atEnd()?(t.pushBinding(new Yi(0),n),!0):(t.processFailure(n,this),!1)};Gt.prototype.eval=function(t){const{inputStream:e}=t,n=e.pos;return e.matchString(this.obj)?(t.pushBinding(new Yi(this.obj.length),n),!0):(t.processFailure(n,this),!1)};Xt.prototype.eval=function(t){const{inputStream:e}=t,n=e.pos,r=this.matchCodePoint?e.nextCodePoint():e.nextCharCode();return r!==void 0&&this.from.codePointAt(0)<=r&&r<=this.to.codePointAt(0)?(t.pushBinding(new Yi(String.fromCodePoint(r).length),n),!0):(t.processFailure(n,this),!1)};en.prototype.eval=function(t){return t.eval(t.currentApplication().args[this.index])};xn.prototype.eval=function(t){t.enterLexifiedContext();const e=t.eval(this.expr);return t.exitLexifiedContext(),e};Tt.prototype.eval=function(t){for(let e=0;e<this.terms.length;e++)if(t.eval(this.terms[e]))return!0;return!1};Lt.prototype.eval=function(t){for(let e=0;e<this.factors.length;e++){const n=this.factors[e];if(!t.eval(n))return!1}return!0};cn.prototype.eval=function(t){const{inputStream:e}=t,n=e.pos,r=this.getArity(),s=[],o=[];for(;s.length<r;)s.push([]),o.push([]);let c=0,d=n,f;for(;c<this.maxNumMatches&&t.eval(this.expr);){if(e.pos===d)throw C1(this,t._applicationStack);d=e.pos,c++;const v=t._bindings.splice(t._bindings.length-r,r),w=t._bindingOffsets.splice(t._bindingOffsets.length-r,r);for(f=0;f<v.length;f++)s[f].push(v[f]),o[f].push(w[f])}if(c<this.minNumMatches)return!1;let p=t.posToOffset(n),g=0;if(c>0){const v=s[r-1],w=o[r-1],_=w[w.length-1]+v[v.length-1].matchLength;p=o[0][0],g=_-p}const b=this instanceof us;for(f=0;f<s.length;f++)t._bindings.push(new D1(s[f],o[f],g,b)),t._bindingOffsets.push(p);return!0};Vt.prototype.eval=function(t){const{inputStream:e}=t,n=e.pos;t.pushFailuresInfo();const r=t.eval(this.expr);return t.popFailuresInfo(),r?(t.processFailure(n,this),!1):(e.pos=n,!0)};un.prototype.eval=function(t){const{inputStream:e}=t,n=e.pos;return t.eval(this.expr)?(e.pos=n,!0):!1};Ze.prototype.eval=function(t){const e=t.currentApplication(),n=e?e.args:[],r=this.substituteParams(n),s=t.getCurrentPosInfo();if(s.isActive(r))return r.handleCycle(t);const o=r.toMemoKey(),c=s.memo[o];if(c&&s.shouldUseMemoizedResult(c)){if(t.hasNecessaryInfo(c))return t.useMemoizedResult(t.inputStream.pos,c);delete s.memo[o]}return r.reallyEval(t)};Ze.prototype.handleCycle=function(t){const e=t.getCurrentPosInfo(),{currentLeftRecursion:n}=e,r=this.toMemoKey();let s=e.memo[r];return n&&n.headApplication.toMemoKey()===r?s.updateInvolvedApplicationMemoKeys():s||(s=e.memoize(r,{matchLength:0,examinedLength:0,value:!1,rightmostFailureOffset:-1}),e.startLeftRecursion(this,s)),t.useMemoizedResult(t.inputStream.pos,s)};Ze.prototype.reallyEval=function(t){const{inputStream:e}=t,n=e.pos,r=t.getCurrentPosInfo(),s=t.grammar.rules[this.ruleName],{body:o}=s,{description:c}=s;t.enterApplication(r,this),c&&t.pushFailuresInfo();const d=e.examinedLength;e.examinedLength=0;let f=this.evalOnce(o,t);const p=r.currentLeftRecursion,g=this.toMemoKey(),b=p&&p.headApplication.toMemoKey()===g;let v;t.doNotMemoize?t.doNotMemoize=!1:b?(f=this.growSeedResult(o,t,n,p,f),r.endLeftRecursion(),v=p,v.examinedLength=e.examinedLength-n,v.rightmostFailureOffset=t._getRightmostFailureOffset(),r.memoize(g,v)):(!p||!p.isInvolved(g))&&(v=r.memoize(g,{matchLength:e.pos-n,examinedLength:e.examinedLength-n,value:f,failuresAtRightmostPosition:t.cloneRecordedFailures(),rightmostFailureOffset:t._getRightmostFailureOffset()}));const w=!!f;if(c&&(t.popFailuresInfo(),w||t.processFailure(n,this),v&&(v.failuresAtRightmostPosition=t.cloneRecordedFailures(),v.rightmostFailureOffset=t._getRightmostFailureOffset())),t.isTracing()&&v){const _=t.getTraceEntry(n,this,w,w?[f]:[]);b&&(ti(_.terminatingLREntry!=null||!w),_.isHeadOfLeftRecursion=!0),v.traceEntry=_}return e.examinedLength=Math.max(e.examinedLength,d),t.exitApplication(r,f),w};Ze.prototype.evalOnce=function(t,e){const{inputStream:n}=e,r=n.pos;if(e.eval(t)){const s=t.getArity(),o=e._bindings.splice(e._bindings.length-s,s),c=e._bindingOffsets.splice(e._bindingOffsets.length-s,s),d=n.pos-r;return new GO(this.ruleName,o,c,d)}else return!1};Ze.prototype.growSeedResult=function(t,e,n,r,s){if(!s)return!1;const{inputStream:o}=e;for(;;){if(r.matchLength=o.pos-n,r.value=s,r.failuresAtRightmostPosition=e.cloneRecordedFailures(),e.isTracing()){const c=e.trace[e.trace.length-1];r.traceEntry=new Gs(e.input,n,o.pos,this,!0,[s],[c.clone()])}if(o.pos=n,s=this.evalOnce(t,e),o.pos-n<=r.matchLength)break;e.isTracing()&&e.trace.splice(-2,1)}return e.isTracing()&&r.traceEntry.recordLRTermination(e.trace.pop(),s),o.pos=n+r.matchLength,r.value};Ht.prototype.eval=function(t){const{inputStream:e}=t,n=e.pos,r=e.nextCodePoint();if(r!==void 0&&r<=MO){const s=String.fromCodePoint(r);if(this.pattern.test(s))return t.pushBinding(new Yi(s.length),n),!0}return t.processFailure(n,this),!1};we.prototype.getArity=ln("getArity");Qt.getArity=Jt.getArity=Gt.prototype.getArity=Xt.prototype.getArity=en.prototype.getArity=Ze.prototype.getArity=Ht.prototype.getArity=function(){return 1};Tt.prototype.getArity=function(){return this.terms.length===0?0:this.terms[0].getArity()};Lt.prototype.getArity=function(){let t=0;for(let e=0;e<this.factors.length;e++)t+=this.factors[e].getArity();return t};cn.prototype.getArity=function(){return this.expr.getArity()};Vt.prototype.getArity=function(){return 0};un.prototype.getArity=xn.prototype.getArity=function(){return this.expr.getArity()};function hr(t,e){const n={};if(t.source&&e){const r=t.source.relativeTo(e);n.sourceInterval=[r.startIdx,r.endIdx]}return n}we.prototype.outputRecipe=ln("outputRecipe");Qt.outputRecipe=function(t,e){return["any",hr(this,e)]};Jt.outputRecipe=function(t,e){return["end",hr(this,e)]};Gt.prototype.outputRecipe=function(t,e){return["terminal",hr(this,e),this.obj]};Xt.prototype.outputRecipe=function(t,e){return["range",hr(this,e),this.from,this.to]};en.prototype.outputRecipe=function(t,e){return["param",hr(this,e),this.index]};Tt.prototype.outputRecipe=function(t,e){return["alt",hr(this,e)].concat(this.terms.map(n=>n.outputRecipe(t,e)))};Nd.prototype.outputRecipe=function(t,e){return this.terms[0].outputRecipe(t,e)};Od.prototype.outputRecipe=function(t,e){const n=this.terms.slice(0,this.expansionPos),r=this.terms.slice(this.expansionPos+1);return["splice",hr(this,e),n.map(s=>s.outputRecipe(t,e)),r.map(s=>s.outputRecipe(t,e))]};Lt.prototype.outputRecipe=function(t,e){return["seq",hr(this,e)].concat(this.factors.map(n=>n.outputRecipe(t,e)))};Ki.prototype.outputRecipe=co.prototype.outputRecipe=us.prototype.outputRecipe=Vt.prototype.outputRecipe=un.prototype.outputRecipe=xn.prototype.outputRecipe=function(t,e){return[this.constructor.name.toLowerCase(),hr(this,e),this.expr.outputRecipe(t,e)]};Ze.prototype.outputRecipe=function(t,e){return["app",hr(this,e),this.ruleName,this.args.map(n=>n.outputRecipe(t,e))]};Ht.prototype.outputRecipe=function(t,e){return["unicodeChar",hr(this,e),this.categoryOrProp]};we.prototype.introduceParams=ln("introduceParams");Qt.introduceParams=Jt.introduceParams=Gt.prototype.introduceParams=Xt.prototype.introduceParams=en.prototype.introduceParams=Ht.prototype.introduceParams=function(t){return this};Tt.prototype.introduceParams=function(t){return this.terms.forEach((e,n,r)=>{r[n]=e.introduceParams(t)}),this};Lt.prototype.introduceParams=function(t){return this.factors.forEach((e,n,r)=>{r[n]=e.introduceParams(t)}),this};cn.prototype.introduceParams=Vt.prototype.introduceParams=un.prototype.introduceParams=xn.prototype.introduceParams=function(t){return this.expr=this.expr.introduceParams(t),this};Ze.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 en(e).withSource(this.source)}else return this.args.forEach((n,r,s)=>{s[r]=n.introduceParams(t)}),this};we.prototype.isNullable=function(t){return this._isNullable(t,Object.create(null))};we.prototype._isNullable=ln("_isNullable");Qt._isNullable=Xt.prototype._isNullable=en.prototype._isNullable=co.prototype._isNullable=Ht.prototype._isNullable=function(t,e){return!1};Jt._isNullable=function(t,e){return!0};Gt.prototype._isNullable=function(t,e){return typeof this.obj=="string"?this.obj==="":!1};Tt.prototype._isNullable=function(t,e){return this.terms.length===0||this.terms.some(n=>n._isNullable(t,e))};Lt.prototype._isNullable=function(t,e){return this.factors.every(n=>n._isNullable(t,e))};Ki.prototype._isNullable=us.prototype._isNullable=Vt.prototype._isNullable=un.prototype._isNullable=function(t,e){return!0};xn.prototype._isNullable=function(t,e){return this.expr._isNullable(t,e)};Ze.prototype._isNullable=function(t,e){const n=this.toMemoKey();if(!Object.prototype.hasOwnProperty.call(e,n)){const{body:r}=t.rules[this.ruleName],s=r.substituteParams(this.args);e[n]=!1,e[n]=s._isNullable(t,e)}return e[n]};we.prototype.substituteParams=ln("substituteParams");Qt.substituteParams=Jt.substituteParams=Gt.prototype.substituteParams=Xt.prototype.substituteParams=Ht.prototype.substituteParams=function(t){return this};en.prototype.substituteParams=function(t){return E1(t[this.index])};Tt.prototype.substituteParams=function(t){return new Tt(this.terms.map(e=>e.substituteParams(t)))};Lt.prototype.substituteParams=function(t){return new Lt(this.factors.map(e=>e.substituteParams(t)))};cn.prototype.substituteParams=Vt.prototype.substituteParams=un.prototype.substituteParams=xn.prototype.substituteParams=function(t){return new this.constructor(this.expr.substituteParams(t))};Ze.prototype.substituteParams=function(t){if(this.args.length===0)return this;{const e=this.args.map(n=>n.substituteParams(t));return new Ze(this.ruleName,e)}};function sx(t){return/^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(t)}function Vy(t){const e=Object.create(null);t.forEach(n=>{e[n]=(e[n]||0)+1}),Object.keys(e).forEach(n=>{if(e[n]<=1)return;let r=1;t.forEach((s,o)=>{s===n&&(t[o]=s+"_"+r++)})})}we.prototype.toArgumentNameList=ln("toArgumentNameList");Qt.toArgumentNameList=function(t,e){return["any"]};Jt.toArgumentNameList=function(t,e){return["end"]};Gt.prototype.toArgumentNameList=function(t,e){return typeof this.obj=="string"&&/^[_a-zA-Z0-9]+$/.test(this.obj)?["_"+this.obj]:["$"+t]};Xt.prototype.toArgumentNameList=function(t,e){let n=this.from+"_to_"+this.to;return sx(n)||(n="_"+n),sx(n)||(n="$"+t),[n]};Tt.prototype.toArgumentNameList=function(t,e){const n=this.terms.map(o=>o.toArgumentNameList(t,!0)),r=[],s=n[0].length;for(let o=0;o<s;o++){const c=[];for(let f=0;f<this.terms.length;f++)c.push(n[f][o]);const d=w1(c);r.push(d.join("_or_"))}return e||Vy(r),r};Lt.prototype.toArgumentNameList=function(t,e){let n=[];return this.factors.forEach(r=>{const s=r.toArgumentNameList(t,!0);n=n.concat(s),t+=s.length}),e||Vy(n),n};cn.prototype.toArgumentNameList=function(t,e){const n=this.expr.toArgumentNameList(t,e).map(r=>r[r.length-1]==="s"?r+"es":r+"s");return e||Vy(n),n};us.prototype.toArgumentNameList=function(t,e){return this.expr.toArgumentNameList(t,e).map(n=>"opt"+n[0].toUpperCase()+n.slice(1))};Vt.prototype.toArgumentNameList=function(t,e){return[]};un.prototype.toArgumentNameList=xn.prototype.toArgumentNameList=function(t,e){return this.expr.toArgumentNameList(t,e)};Ze.prototype.toArgumentNameList=function(t,e){return[this.ruleName]};Ht.prototype.toArgumentNameList=function(t,e){return["$"+t]};en.prototype.toArgumentNameList=function(t,e){return["param"+this.index]};we.prototype.toDisplayString=ln("toDisplayString");Tt.prototype.toDisplayString=Lt.prototype.toDisplayString=function(){return this.source?this.source.trimmed().contents:"["+this.constructor.name+"]"};Qt.toDisplayString=Jt.toDisplayString=cn.prototype.toDisplayString=Vt.prototype.toDisplayString=un.prototype.toDisplayString=xn.prototype.toDisplayString=Gt.prototype.toDisplayString=Xt.prototype.toDisplayString=en.prototype.toDisplayString=function(){return this.toString()};Ze.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};Ht.prototype.toDisplayString=function(){return"Unicode ["+this.categoryOrProp+"] character"};function KO(t){return t==="description"||t==="string"||t==="code"}class Sn{constructor(e,n,r){if(!KO(r))throw new Error("invalid Failure type: "+r);this.pexpr=e,this.text=n,this.type=r,this.fluffy=!1}getPExpr(){return this.pexpr}getText(){return this.text}getType(){return this.type}isDescription(){return this.type==="description"}isStringTerminal(){return this.type==="string"}isCode(){return this.type==="code"}isFluffy(){return this.fluffy}makeFluffy(){this.fluffy=!0}clearFluffy(){this.fluffy=!1}subsumes(e){return this.getText()===e.getText()&&this.type===e.type&&(!this.isFluffy()||this.isFluffy()&&e.isFluffy())}toString(){return this.type==="string"?JSON.stringify(this.getText()):this.getText()}clone(){const e=new Sn(this.pexpr,this.text,this.type);return this.isFluffy()&&e.makeFluffy(),e}toKey(){return this.toString()+"#"+this.type}}we.prototype.toFailure=ln("toFailure");Qt.toFailure=function(t){return new Sn(this,"any object","description")};Jt.toFailure=function(t){return new Sn(this,"end of input","description")};Gt.prototype.toFailure=function(t){return new Sn(this,this.obj,"string")};Xt.prototype.toFailure=function(t){return new Sn(this,JSON.stringify(this.from)+".."+JSON.stringify(this.to),"code")};Vt.prototype.toFailure=function(t){const e=this.expr===Qt?"nothing":"not "+this.expr.toFailure(t);return new Sn(this,e,"description")};un.prototype.toFailure=function(t){return this.expr.toFailure(t)};Ze.prototype.toFailure=function(t){let{description:e}=t.rules[this.ruleName];return e||(e=(/^[aeiouAEIOU]/.test(this.ruleName)?"an":"a")+" "+this.ruleName),new Sn(this,e,"description")};Ht.prototype.toFailure=function(t){return new Sn(this,"a Unicode ["+this.categoryOrProp+"] character","description")};Tt.prototype.toFailure=function(t){const n="("+this.terms.map(r=>r.toFailure(t)).join(" or ")+")";return new Sn(this,n,"description")};Lt.prototype.toFailure=function(t){const n="("+this.factors.map(r=>r.toFailure(t)).join(" ")+")";return new Sn(this,n,"description")};cn.prototype.toFailure=function(t){const e="("+this.expr.toFailure(t)+this.operator+")";return new Sn(this,e,"description")};we.prototype.toString=ln("toString");Qt.toString=function(){return"any"};Jt.toString=function(){return"end"};Gt.prototype.toString=function(){return JSON.stringify(this.obj)};Xt.prototype.toString=function(){return JSON.stringify(this.from)+".."+JSON.stringify(this.to)};en.prototype.toString=function(){return"$"+this.index};xn.prototype.toString=function(){return"#("+this.expr.toString()+")"};Tt.prototype.toString=function(){return this.terms.length===1?this.terms[0].toString():"("+this.terms.map(t=>t.toString()).join(" | ")+")"};Lt.prototype.toString=function(){return this.factors.length===1?this.factors[0].toString():"("+this.factors.map(t=>t.toString()).join(" ")+")"};cn.prototype.toString=function(){return this.expr+this.operator};Vt.prototype.toString=function(){return"~"+this.expr};un.prototype.toString=function(){return"&"+this.expr};Ze.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};Ht.prototype.toString=function(){return"\\p{"+this.categoryOrProp+"}"};class Hy extends we{constructor(e){super(),this.obj=e}_getString(e){const n=e.currentApplication().args[this.obj.index];return ti(n instanceof Gt,"expected a Terminal expression"),n.obj}allowsSkippingPrecedingSpace(){return!0}eval(e){const{inputStream:n}=e,r=n.pos,s=this._getString(e);return n.matchString(s,!0)?(e.pushBinding(new Yi(s.length),r),!0):(e.processFailure(r,this),!1)}getArity(){return 1}substituteParams(e){return new Hy(this.obj.substituteParams(e))}toDisplayString(){return this.obj.toDisplayString()+" (case-insensitive)"}toFailure(e){return new Sn(this,this.obj.toFailure(e)+" (case-insensitive)","description")}_isNullable(e,n){return this.obj._isNullable(e,n)}}let I1;O1(t=>{I1=t.rules.applySyntactic.body});const Rp=new Ze("spaces");class YO{constructor(e,n,r){this.matcher=e,this.startExpr=n,this.grammar=e.grammar,this.input=e.getInput(),this.inputStream=new Rd(this.input),this.memoTable=e._memoTable,this.userData=void 0,this.doNotMemoize=!1,this._bindings=[],this._bindingOffsets=[],this._applicationStack=[],this._posStack=[0],this.inLexifiedContextStack=[!1],this.rightmostFailurePosition=-1,this._rightmostFailurePositionStack=[],this._recordedFailuresStack=[],r!==void 0&&(this.positionToRecordFailures=r,this.recordedFailures=Object.create(null))}posToOffset(e){return e-this._posStack[this._posStack.length-1]}enterApplication(e,n){this._posStack.push(this.inputStream.pos),this._applicationStack.push(n),this.inLexifiedContextStack.push(!1),e.enter(n),this._rightmostFailurePositionStack.push(this.rightmostFailurePosition),this.rightmostFailurePosition=-1}exitApplication(e,n){const r=this._posStack.pop();this._applicationStack.pop(),this.inLexifiedContextStack.pop(),e.exit(),this.rightmostFailurePosition=Math.max(this.rightmostFailurePosition,this._rightmostFailurePositionStack.pop()),n&&this.pushBinding(n,r)}enterLexifiedContext(){this.inLexifiedContextStack.push(!0)}exitLexifiedContext(){this.inLexifiedContextStack.pop()}currentApplication(){return this._applicationStack[this._applicationStack.length-1]}inSyntacticContext(){const e=this.currentApplication();return e?e.isSyntactic()&&!this.inLexifiedContext():this.startExpr.factors[0].isSyntactic()}inLexifiedContext(){return this.inLexifiedContextStack[this.inLexifiedContextStack.length-1]}skipSpaces(){return this.pushFailuresInfo(),this.eval(Rp),this.popBinding(),this.popFailuresInfo(),this.inputStream.pos}skipSpacesIfInSyntacticContext(){return this.inSyntacticContext()?this.skipSpaces():this.inputStream.pos}maybeSkipSpacesBefore(e){return e.allowsSkippingPrecedingSpace()&&e!==Rp?this.skipSpacesIfInSyntacticContext():this.inputStream.pos}pushBinding(e,n){this._bindings.push(e),this._bindingOffsets.push(this.posToOffset(n))}popBinding(){this._bindings.pop(),this._bindingOffsets.pop()}numBindings(){return this._bindings.length}truncateBindings(e){for(;this._bindings.length>e;)this.popBinding()}getCurrentPosInfo(){return this.getPosInfo(this.inputStream.pos)}getPosInfo(e){let n=this.memoTable[e];return n||(n=this.memoTable[e]=new LO),n}processFailure(e,n){if(this.rightmostFailurePosition=Math.max(this.rightmostFailurePosition,e),this.recordedFailures&&e===this.positionToRecordFailures){const r=this.currentApplication();r&&(n=n.substituteParams(r.args)),this.recordFailure(n.toFailure(this.grammar),!1)}}recordFailure(e,n){const r=e.toKey();this.recordedFailures[r]?this.recordedFailures[r].isFluffy()&&!e.isFluffy()&&this.recordedFailures[r].clearFluffy():this.recordedFailures[r]=n?e.clone():e}recordFailures(e,n){Object.keys(e).forEach(r=>{this.recordFailure(e[r],n)})}cloneRecordedFailures(){if(!this.recordedFailures)return;const e=Object.create(null);return Object.keys(this.recordedFailures).forEach(n=>{e[n]=this.recordedFailures[n].clone()}),e}getRightmostFailurePosition(){return this.rightmostFailurePosition}_getRightmostFailureOffset(){return this.rightmostFailurePosition>=0?this.posToOffset(this.rightmostFailurePosition):-1}getMemoizedTraceEntry(e,n){const r=this.memoTable[e];if(r&&n instanceof Ze){const s=r.memo[n.toMemoKey()];if(s&&s.traceEntry){const o=s.traceEntry.cloneWithExpr(n);return o.isMemoized=!0,o}}return null}getTraceEntry(e,n,r,s){if(n instanceof Ze){const o=this.currentApplication(),c=o?o.args:[];n=n.substituteParams(c)}return this.getMemoizedTraceEntry(e,n)||new Gs(this.input,e,this.inputStream.pos,n,r,s,this.trace)}isTracing(){return!!this.trace}hasNecessaryInfo(e){return this.trace&&!e.traceEntry?!1:this.recordedFailures&&this.inputStream.pos+e.rightmostFailureOffset===this.positionToRecordFailures?!!e.failuresAtRightmostPosition:!0}useMemoizedResult(e,n){this.trace&&this.trace.push(n.traceEntry);const r=this.inputStream.pos+n.rightmostFailureOffset;return this.rightmostFailurePosition=Math.max(this.rightmostFailurePosition,r),this.recordedFailures&&this.positionToRecordFailures===r&&n.failuresAtRightmostPosition&&this.recordFailures(n.failuresAtRightmostPosition,!0),this.inputStream.examinedLength=Math.max(this.inputStream.examinedLength,n.examinedLength+e),n.value?(this.inputStream.pos+=n.matchLength,this.pushBinding(n.value,e),!0):!1}eval(e){const{inputStream:n}=this,r=this._bindings.length,s=this.userData;let o;this.recordedFailures&&(o=this.recordedFailures,this.recordedFailures=Object.create(null));const c=n.pos,d=this.maybeSkipSpacesBefore(e);let f;this.trace&&(f=this.trace,this.trace=[]);const p=e.eval(this);if(this.trace){const g=this._bindings.slice(r),b=this.getTraceEntry(d,e,p,g);b.isImplicitSpaces=e===Rp,b.isRootNode=e===this.startExpr,f.push(b),this.trace=f}return p?this.recordedFailures&&n.pos===this.positionToRecordFailures&&Object.keys(this.recordedFailures).forEach(g=>{this.recordedFailures[g].makeFluffy()}):(n.pos=c,this.truncateBindings(r),this.userData=s),this.recordedFailures&&this.recordFailures(o,!1),e===I1&&this.skipSpaces(),p}getMatchResult(){this.grammar._setUpMatchState(this),this.eval(this.startExpr);let e;this.recordedFailures&&(e=Object.keys(this.recordedFailures).map(r=>this.recordedFailures[r]));const n=this._bindings[0];return n&&(n.grammar=this.grammar),new R1(this.matcher,this.input,this.startExpr,n,this._bindingOffsets[0],this.rightmostFailurePosition,e)}getTrace(){this.trace=[];const e=this.getMatchResult(),n=this.trace[this.trace.length-1];return n.result=e,n}pushFailuresInfo(){this._rightmostFailurePositionStack.push(this.rightmostFailurePosition),this._recordedFailuresStack.push(this.recordedFailures)}popFailuresInfo(){this.rightmostFailurePosition=this._rightmostFailurePositionStack.pop(),this.recordedFailures=this._recordedFailuresStack.pop()}}class ZO{constructor(e){this.grammar=e,this._memoTable=[],this._input="",this._isMemoTableStale=!1}_resetMemoTable(){this._memoTable=[],this._isMemoTableStale=!1}getInput(){return this._input}setInput(e){return this._input!==e&&this.replaceInputRange(0,this._input.length,e),this}replaceInputRange(e,n,r){const s=this._input,o=this._memoTable;if(e<0||e>s.length||n<0||n>s.length||e>n)throw new Error("Invalid indices: "+e+" and "+n);this._input=s.slice(0,e)+r+s.slice(n),this._input!==s&&o.length>0&&(this._isMemoTableStale=!0);const c=o.slice(n);o.length=e;for(let d=0;d<r.length;d++)o.push(void 0);for(const d of c)o.push(d);for(let d=0;d<e;d++){const f=o[d];f&&f.clearObsoleteEntries(d,e)}return this}match(e,n={incremental:!0}){return this._match(this._getStartExpr(e),{incremental:n.incremental,tracing:!1})}trace(e,n={incremental:!0}){return this._match(this._getStartExpr(e),{incremental:n.incremental,tracing:!0})}_match(e,n={}){const r={tracing:!1,incremental:!0,positionToRecordFailures:void 0,...n};if(!r.incremental)this._resetMemoTable();else if(this._isMemoTableStale&&!this.grammar.supportsIncrementalParsing)throw gO(this.grammar);const s=new YO(this,e,r.positionToRecordFailures);return r.tracing?s.getTrace():s.getMatchResult()}_getStartExpr(e){const n=e||this.grammar.defaultStartRule;if(!n)throw new Error("Missing start rule argument -- the grammar has no default start rule.");const r=this.grammar.parseApplication(n);return new Lt([r,Jt])}}const wl=[],vm=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);class ix{constructor(e,n,r){this._node=e,this.source=n,this._baseInterval=r,e.isNonterminal()&&ti(n===r),this._childWrappers=[]}_forgetMemoizedResultFor(e){delete this._node[this._semantics.attributeKeys[e]],this.children.forEach(n=>{n._forgetMemoizedResultFor(e)})}child(e){if(!(0<=e&&e<this._node.numChildren()))return;let n=this._childWrappers[e];if(!n){const r=this._node.childAt(e),s=this._node.childOffsets[e],o=this._baseInterval.subInterval(s,r.matchLength),c=r.isNonterminal()?o:this._baseInterval;n=this._childWrappers[e]=this._semantics.wrap(r,o,c)}return n}_children(){for(let e=0;e<this._node.numChildren();e++)this.child(e);return this._childWrappers}isIteration(){return this._node.isIteration()}isTerminal(){return this._node.isTerminal()}isNonterminal(){return this._node.isNonterminal()}isSyntactic(){return this.isNonterminal()&&this._node.isSyntactic()}isLexical(){return this.isNonterminal()&&this._node.isLexical()}isOptional(){return this._node.isOptional()}iteration(e){const n=e||[],r=n.map(c=>c._node),s=new D1(r,[],-1,!1),o=this._semantics.wrap(s,null,null);return o._childWrappers=n,o}get children(){return this._children()}get ctorName(){return this._node.ctorName}get numChildren(){return this._node.numChildren()}get sourceString(){return this.source.contents}}class wn{constructor(e,n){const r=this;if(this.grammar=e,this.checkedActionDicts=!1,this.Wrapper=class extends(n?n.Wrapper:ix){constructor(s,o,c){super(s,o,c),r.checkActionDictsIfHaventAlready(),this._semantics=r}toString(){return"[semantics wrapper for "+r.grammar.name+"]"}},this.super=n,n){if(!(e.equals(this.super.grammar)||e._inheritsFrom(this.super.grammar)))throw new Error("Cannot extend a semantics for grammar '"+this.super.grammar.name+"' for use with grammar '"+e.name+"' (not a sub-grammar)");this.operations=Object.create(this.super.operations),this.attributes=Object.create(this.super.attributes),this.attributeKeys=Object.create(null);for(const s in this.attributes)Object.defineProperty(this.attributeKeys,s,{value:rx(s)})}else this.operations=Object.create(null),this.attributes=Object.create(null),this.attributeKeys=Object.create(null)}toString(){return"[semantics for "+this.grammar.name+"]"}checkActionDictsIfHaventAlready(){this.checkedActionDicts||(this.checkActionDicts(),this.checkedActionDicts=!0)}checkActionDicts(){let e;for(e in this.operations)this.operations[e].checkActionDict(this.grammar);for(e in this.attributes)this.attributes[e].checkActionDict(this.grammar)}toRecipe(e){function n(s){return s.super!==wn.BuiltInSemantics._getSemantics()}let r=`(function(g) {
67
- `;if(n(this)){r+=" var semantics = "+this.super.toRecipe(!0)+"(g";const s=this.super.grammar;let o=this.grammar;for(;o!==s;)r+=".superGrammar",o=o.superGrammar;r+=`);
68
- `,r+=" return g.extendSemantics(semantics)"}else r+=" return g.createSemantics()";return["Operation","Attribute"].forEach(s=>{const o=this[s.toLowerCase()+"s"];Object.keys(o).forEach(c=>{const{actionDict:d,formals:f,builtInDefault:p}=o[c];let g=c;f.length>0&&(g+="("+f.join(", ")+")");let b;n(this)&&this.super[s.toLowerCase()+"s"][c]?b="extend"+s:b="add"+s,r+=`
69
- .`+b+"("+JSON.stringify(g)+", {";const v=[];Object.keys(d).forEach(w=>{if(d[w]!==p){let _=d[w].toString().trim();_=_.replace(/^.*\(/,"function("),v.push(`
70
- `+JSON.stringify(w)+": "+_)}}),r+=v.join(",")+`
71
- })`})}),r+=`;
72
- })`,e||(r=`(function() {
73
- var grammar = this.fromRecipe(`+this.grammar.toRecipe()+`);
74
- var semantics = `+r+`(grammar);
75
- return semantics;
76
- });
77
- `),r}addOperationOrAttribute(e,n,r){const s=e+"s",o=ax(n,e),{name:c}=o,{formals:d}=o;this.assertNewName(c,e);const f=WO(e,c,b),p={_default:f};Object.keys(r).forEach(v=>{p[v]=r[v]});const g=e==="operation"?new Rl(c,d,p,f):new wm(c,p,f);g.checkActionDict(this.grammar),this[s][c]=g;function b(...v){const w=this._semantics[s][c];if(arguments.length!==w.formals.length)throw new Error("Invalid number of arguments passed to "+c+" "+e+" (expected "+w.formals.length+", got "+arguments.length+")");const _=Object.create(null);for(const[N,R]of Object.entries(v)){const M=w.formals[N];_[M]=R}const k=this.args;this.args=_;const I=w.execute(this._semantics,this);return this.args=k,I}e==="operation"?(this.Wrapper.prototype[c]=b,this.Wrapper.prototype[c].toString=function(){return"["+c+" operation]"}):(Object.defineProperty(this.Wrapper.prototype,c,{get:b,configurable:!0}),Object.defineProperty(this.attributeKeys,c,{value:rx(c)}))}extendOperationOrAttribute(e,n,r){const s=e+"s";if(ax(n,"attribute"),!(this.super&&n in this.super[s]))throw new Error("Cannot extend "+e+" '"+n+"': did not inherit an "+e+" with that name");if(vm(this[s],n))throw new Error("Cannot extend "+e+" '"+n+"' again");const o=this[s][n].formals,c=this[s][n].actionDict,d=Object.create(c);Object.keys(r).forEach(f=>{d[f]=r[f]}),this[s][n]=e==="operation"?new Rl(n,o,d):new wm(n,d),this[s][n].checkActionDict(this.grammar)}assertNewName(e,n){if(vm(ix.prototype,e))throw new Error("Cannot add "+n+" '"+e+"': that's a reserved name");if(e in this.operations)throw new Error("Cannot add "+n+" '"+e+"': an operation with that name already exists");if(e in this.attributes)throw new Error("Cannot add "+n+" '"+e+"': an attribute with that name already exists")}wrap(e,n,r){const s=r||n;return e instanceof this.Wrapper?e:new this.Wrapper(e,n,s)}}function ax(t,e){if(!wn.prototypeGrammar)return ti(t.indexOf("(")===-1),{name:t,formals:[]};const n=wn.prototypeGrammar.match(t,e==="operation"?"OperationSignature":"AttributeSignature");if(n.failed())throw new Error(n.message);return wn.prototypeGrammarSemantics(n).parse()}function WO(t,e,n){return function(...r){const o=(this._semantics.operations[e]||this._semantics.attributes[e]).formals.map(c=>this.args[c]);if(!this.isIteration()&&r.length===1)return n.apply(r[0],o);throw NO(this.ctorName,e,t,wl)}}wn.createSemantics=function(t,e){const n=new wn(t,e!==void 0?e:wn.BuiltInSemantics._getSemantics()),r=function(o){if(!(o instanceof R1))throw new TypeError("Semantics expected a MatchResult, but got "+qy(o));if(o.failed())throw new TypeError("cannot apply Semantics to "+o.toString());const c=o._cst;if(c.grammar!==t)throw new Error("Cannot use a MatchResult from grammar '"+c.grammar.name+"' with a semantics for '"+t.name+"'");const d=new Rd(o.input);return n.wrap(c,d.interval(o._cstOffset,o.input.length))};return r.addOperation=function(s,o){return n.addOperationOrAttribute("operation",s,o),r},r.extendOperation=function(s,o){return n.extendOperationOrAttribute("operation",s,o),r},r.addAttribute=function(s,o){return n.addOperationOrAttribute("attribute",s,o),r},r.extendAttribute=function(s,o){return n.extendOperationOrAttribute("attribute",s,o),r},r._getActionDict=function(s){const o=n.operations[s]||n.attributes[s];if(!o)throw new Error('"'+s+'" is not a valid operation or attribute name in this semantics for "'+t.name+'"');return o.actionDict},r._remove=function(s){let o;return s in n.operations?(o=n.operations[s],delete n.operations[s]):s in n.attributes&&(o=n.attributes[s],delete n.attributes[s]),delete n.Wrapper.prototype[s],o},r.getOperationNames=function(){return Object.keys(n.operations)},r.getAttributeNames=function(){return Object.keys(n.attributes)},r.getGrammar=function(){return n.grammar},r.toRecipe=function(s){return n.toRecipe(s)},r.toString=n.toString.bind(n),r._getSemantics=function(){return n},r};class Rl{constructor(e,n,r,s){this.name=e,this.formals=n,this.actionDict=r,this.builtInDefault=s}checkActionDict(e){e._checkTopDownActionDict(this.typeName,this.name,this.actionDict)}execute(e,n){try{const{ctorName:r}=n._node;let s=this.actionDict[r];return s?(wl.push([this,r]),s.apply(n,n._children())):n.isNonterminal()&&(s=this.actionDict._nonterminal,s)?(wl.push([this,"_nonterminal",r]),s.apply(n,n._children())):(wl.push([this,"default action",r]),this.actionDict._default.apply(n,n._children()))}finally{wl.pop()}}}Rl.prototype.typeName="operation";class wm extends Rl{constructor(e,n,r){super(e,[],n,r)}execute(e,n){const r=n._node,s=e.attributeKeys[this.name];return vm(r,s)||(r[s]=Rl.prototype.execute.call(this,e,n)),r[s]}}wm.prototype.typeName="attribute";const ox=["_iter","_terminal","_nonterminal","_default"];function lx(t){return Object.keys(t.rules).sort().map(e=>t.rules[e])}const QO=t=>t.replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029");let M1,L1;class an{constructor(e,n,r,s){if(this.name=e,this.superGrammar=n,this.rules=r,s){if(!(s in r))throw new Error("Invalid start rule: '"+s+"' is not a rule in grammar '"+e+"'");this.defaultStartRule=s}this._matchStateInitializer=void 0,this.supportsIncrementalParsing=!0}matcher(){return new ZO(this)}isBuiltIn(){return this===an.ProtoBuiltInRules||this===an.BuiltInRules}equals(e){if(this===e)return!0;if(e==null||this.name!==e.name||this.defaultStartRule!==e.defaultStartRule||!(this.superGrammar===e.superGrammar||this.superGrammar.equals(e.superGrammar)))return!1;const n=lx(this),r=lx(e);return n.length===r.length&&n.every((s,o)=>s.description===r[o].description&&s.formals.join(",")===r[o].formals.join(",")&&s.body.toString()===r[o].body.toString())}match(e,n){const r=this.matcher();return r.replaceInputRange(0,0,e),r.match(n)}trace(e,n){const r=this.matcher();return r.replaceInputRange(0,0,e),r.trace(n)}createSemantics(){return wn.createSemantics(this)}extendSemantics(e){return wn.createSemantics(this,e._getSemantics())}_checkTopDownActionDict(e,n,r){const s=[];for(const o in r){const c=r[o];if(!ox.includes(o)&&!(o in this.rules)){s.push(`'${o}' is not a valid semantic action for '${this.name}'`);continue}if(typeof c!="function"){s.push(`'${o}' must be a function in an action dictionary for '${this.name}'`);continue}const f=c.length,p=this._topDownActionArity(o);if(f!==p){let g;o==="_iter"||o==="_nonterminal"?g=`it should use a rest parameter, e.g. \`${o}(...children) {}\`. NOTE: this is new in Ohm v16 — see https://ohmjs.org/d/ati for details.`:g=`expected ${p}, got ${f}`,s.push(`Semantic action '${o}' has the wrong arity: ${g}`)}}if(s.length>0){const o=s.map(d=>"- "+d),c=new Error([`Found errors in the action dictionary of the '${n}' ${e}:`,...o].join(`
78
- `));throw c.problems=s,c}}_topDownActionArity(e){return ox.includes(e)?0:this.rules[e].body.getArity()}_inheritsFrom(e){let n=this.superGrammar;for(;n;){if(n.equals(e,!0))return!0;n=n.superGrammar}return!1}toRecipe(e=void 0){const n={};this.source&&(n.source=this.source.contents);let r=null;this.defaultStartRule&&(r=this.defaultStartRule);const s={};Object.keys(this.rules).forEach(d=>{const f=this.rules[d],{body:p}=f,g=!this.superGrammar||!this.superGrammar.rules[d];let b;g?b="define":b=p instanceof Nd?"extend":"override";const v={};if(f.source&&this.source){const k=f.source.relativeTo(this.source);v.sourceInterval=[k.startIdx,k.endIdx]}const w=g?f.description:null,_=p.outputRecipe(f.formals,this.source);s[d]=[b,v,w,f.formals,_]});let o="null";e?o=e:this.superGrammar&&!this.superGrammar.isBuiltIn()&&(o=this.superGrammar.toRecipe());const c=[...["grammar",n,this.name].map(JSON.stringify),o,...[r,s].map(JSON.stringify)];return QO(`[${c.join(",")}]`)}toOperationActionDictionaryTemplate(){return this._toOperationOrAttributeActionDictionaryTemplate()}toAttributeActionDictionaryTemplate(){return this._toOperationOrAttributeActionDictionaryTemplate()}_toOperationOrAttributeActionDictionaryTemplate(){const e=new Gi;e.append("{");let n=!0;for(const r in this.rules){const{body:s}=this.rules[r];n?n=!1:e.append(","),e.append(`
79
- `),e.append(" "),this.addSemanticActionTemplate(r,s,e)}return e.append(`
80
- }`),e.contents()}addSemanticActionTemplate(e,n,r){r.append(e),r.append(": function(");const s=this._topDownActionArity(e);r.append(Cd("_",s).join(", ")),r.append(`) {
81
- `),r.append(" }")}parseApplication(e){let n;if(e.indexOf("<")===-1)n=new Ze(e);else{const s=M1.match(e,"Base_application");n=L1(s,{})}if(!(n.ruleName in this.rules))throw j1(n.ruleName,this.name);const{formals:r}=this.rules[n.ruleName];if(r.length!==n.args.length){const{source:s}=this.rules[n.ruleName];throw k1(n.ruleName,r.length,n.args.length,s)}return n}_setUpMatchState(e){this._matchStateInitializer&&this._matchStateInitializer(e)}}an.ProtoBuiltInRules=new an("ProtoBuiltInRules",void 0,{any:{body:Qt,formals:[],description:"any character",primitive:!0},end:{body:Jt,formals:[],description:"end of input",primitive:!0},caseInsensitive:{body:new Hy(new en(0)),formals:["str"],primitive:!0},lower:{body:new Ht("Ll"),formals:[],description:"a lowercase letter",primitive:!0},upper:{body:new Ht("Lu"),formals:[],description:"an uppercase letter",primitive:!0},unicodeLtmo:{body:new Ht("Ltmo"),formals:[],description:"a Unicode character in Lt, Lm, or Lo",primitive:!0},spaces:{body:new Ki(new Ze("space")),formals:[]},space:{body:new Xt("\0"," "),formals:[],description:"a space"}});an.initApplicationParser=function(t,e){M1=t,L1=e};class cx{constructor(e){this.name=e}sourceInterval(e,n){return this.source.subInterval(e,n-e)}ensureSuperGrammar(){return this.superGrammar||this.withSuperGrammar(this.name==="BuiltInRules"?an.ProtoBuiltInRules:an.BuiltInRules),this.superGrammar}ensureSuperGrammarRuleForOverriding(e,n){const r=this.ensureSuperGrammar().rules[e];if(!r)throw bO(e,this.superGrammar.name,n);return r}installOverriddenOrExtendedRule(e,n,r,s){const o=pm(n);if(o.length>0)throw ex(e,o,s);const c=this.ensureSuperGrammar().rules[e],d=c.formals,f=d?d.length:0;if(n.length!==f)throw k1(e,f,n.length,s);return this.install(e,n,r,c.description,s)}install(e,n,r,s,o,c=!1){return this.rules[e]={body:r.introduceParams(n),formals:n,description:s,source:o,primitive:c},this}withSuperGrammar(e){if(this.superGrammar)throw new Error("the super grammar of a GrammarDecl cannot be set more than once");return this.superGrammar=e,this.rules=Object.create(e.rules),e.isBuiltIn()||(this.defaultStartRule=e.defaultStartRule),this}withDefaultStartRule(e){return this.defaultStartRule=e,this}withSource(e){return this.source=new Rd(e).interval(0,e.length),this}build(){const e=new an(this.name,this.ensureSuperGrammar(),this.rules,this.defaultStartRule);e._matchStateInitializer=e.superGrammar._matchStateInitializer,e.supportsIncrementalParsing=e.superGrammar.supportsIncrementalParsing;const n=[];let r=!1;return Object.keys(e.rules).forEach(s=>{const{body:o}=e.rules[s];try{o.assertChoicesHaveUniformArity(s)}catch(c){n.push(c)}try{o.assertAllApplicationsAreValid(s,e)}catch(c){n.push(c),r=!0}}),r||Object.keys(e.rules).forEach(s=>{const{body:o}=e.rules[s];try{o.assertIteratedExprsAreNotNullable(e,[])}catch(c){n.push(c)}}),n.length>0&&OO(n),this.source&&(e.source=this.source),e}define(e,n,r,s,o,c){if(this.ensureSuperGrammar(),this.superGrammar.rules[e])throw Xw(e,this.name,this.superGrammar.name,o);if(this.rules[e])throw Xw(e,this.name,this.name,o);const d=pm(n);if(d.length>0)throw ex(e,d,o);return this.install(e,n,r,s,o,c)}override(e,n,r,s,o){return this.ensureSuperGrammarRuleForOverriding(e,o),this.installOverriddenOrExtendedRule(e,n,r,o),this}extend(e,n,r,s,o){if(!this.ensureSuperGrammar().rules[e])throw vO(e,this.superGrammar.name,o);const d=new Nd(this.superGrammar,e,r);return d.source=r.source,this.installOverriddenOrExtendedRule(e,n,d,o),this}}class Hu{constructor(e){this.currentDecl=null,this.currentRuleName=null,this.options=e||{}}newGrammar(e){return new cx(e)}grammar(e,n,r,s,o){const c=new cx(n);return r&&c.withSuperGrammar(r instanceof an?r:this.fromRecipe(r)),s&&c.withDefaultStartRule(s),e&&e.source&&c.withSource(e.source),this.currentDecl=c,Object.keys(o).forEach(d=>{this.currentRuleName=d;const f=o[d],p=f[0],g=f[1],b=f[2],v=f[3],w=this.fromRecipe(f[4]);let _;c.source&&g&&g.sourceInterval&&(_=c.source.subInterval(g.sourceInterval[0],g.sourceInterval[1]-g.sourceInterval[0])),c[p](d,v,w,b,_)}),this.currentRuleName=this.currentDecl=null,c.build()}terminal(e){return new Gt(e)}range(e,n){return new Xt(e,n)}param(e){return new en(e)}alt(...e){let n=[];for(let r of e)r instanceof we||(r=this.fromRecipe(r)),r instanceof Tt?n=n.concat(r.terms):n.push(r);return n.length===1?n[0]:new Tt(n)}seq(...e){let n=[];for(let r of e)r instanceof we||(r=this.fromRecipe(r)),r instanceof Lt?n=n.concat(r.factors):n.push(r);return n.length===1?n[0]:new Lt(n)}star(e){return e instanceof we||(e=this.fromRecipe(e)),new Ki(e)}plus(e){return e instanceof we||(e=this.fromRecipe(e)),new co(e)}opt(e){return e instanceof we||(e=this.fromRecipe(e)),new us(e)}not(e){return e instanceof we||(e=this.fromRecipe(e)),new Vt(e)}lookahead(e){return e instanceof we||(e=this.fromRecipe(e)),this.options.eliminateLookaheads?new Vt(new Vt(e)):new un(e)}lex(e){return e instanceof we||(e=this.fromRecipe(e)),new xn(e)}app(e,n){return n&&n.length>0&&(n=n.map(function(r){return r instanceof we?r:this.fromRecipe(r)},this)),new Ze(e,n)}splice(e,n){return new Od(this.currentDecl.superGrammar,this.currentRuleName,e.map(r=>this.fromRecipe(r)),n.map(r=>this.fromRecipe(r)))}fromRecipe(e){const n=e[0]==="grammar"?e.slice(1):e.slice(2),r=this[e[0]](...n),s=e[1];return s&&s.sourceInterval&&this.currentDecl&&r.withSource(this.currentDecl.sourceInterval(...s.sourceInterval)),r}}function Gy(t){return typeof t=="function"?t.call(new Hu):(typeof t=="string"&&(t=JSON.parse(t)),new Hu().fromRecipe(t))}const Ky=Gy(["grammar",{source:`BuiltInRules {
82
-
83
- alnum (an alpha-numeric character)
84
- = letter
85
- | digit
86
-
87
- letter (a letter)
88
- = lower
89
- | upper
90
- | unicodeLtmo
91
-
92
- digit (a digit)
93
- = "0".."9"
94
-
95
- hexDigit (a hexadecimal digit)
96
- = digit
97
- | "a".."f"
98
- | "A".."F"
99
-
100
- ListOf<elem, sep>
101
- = NonemptyListOf<elem, sep>
102
- | EmptyListOf<elem, sep>
103
-
104
- NonemptyListOf<elem, sep>
105
- = elem (sep elem)*
106
-
107
- EmptyListOf<elem, sep>
108
- = /* nothing */
109
-
110
- listOf<elem, sep>
111
- = nonemptyListOf<elem, sep>
112
- | emptyListOf<elem, sep>
113
-
114
- nonemptyListOf<elem, sep>
115
- = elem (sep elem)*
116
-
117
- emptyListOf<elem, sep>
118
- = /* nothing */
119
-
120
- // Allows a syntactic rule application within a lexical context.
121
- applySyntactic<app> = app
122
- }`},"BuiltInRules",null,null,{alnum:["define",{sourceInterval:[18,78]},"an alpha-numeric character",[],["alt",{sourceInterval:[60,78]},["app",{sourceInterval:[60,66]},"letter",[]],["app",{sourceInterval:[73,78]},"digit",[]]]],letter:["define",{sourceInterval:[82,142]},"a letter",[],["alt",{sourceInterval:[107,142]},["app",{sourceInterval:[107,112]},"lower",[]],["app",{sourceInterval:[119,124]},"upper",[]],["app",{sourceInterval:[131,142]},"unicodeLtmo",[]]]],digit:["define",{sourceInterval:[146,177]},"a digit",[],["range",{sourceInterval:[169,177]},"0","9"]],hexDigit:["define",{sourceInterval:[181,254]},"a hexadecimal digit",[],["alt",{sourceInterval:[219,254]},["app",{sourceInterval:[219,224]},"digit",[]],["range",{sourceInterval:[231,239]},"a","f"],["range",{sourceInterval:[246,254]},"A","F"]]],ListOf:["define",{sourceInterval:[258,336]},null,["elem","sep"],["alt",{sourceInterval:[282,336]},["app",{sourceInterval:[282,307]},"NonemptyListOf",[["param",{sourceInterval:[297,301]},0],["param",{sourceInterval:[303,306]},1]]],["app",{sourceInterval:[314,336]},"EmptyListOf",[["param",{sourceInterval:[326,330]},0],["param",{sourceInterval:[332,335]},1]]]]],NonemptyListOf:["define",{sourceInterval:[340,388]},null,["elem","sep"],["seq",{sourceInterval:[372,388]},["param",{sourceInterval:[372,376]},0],["star",{sourceInterval:[377,388]},["seq",{sourceInterval:[378,386]},["param",{sourceInterval:[378,381]},1],["param",{sourceInterval:[382,386]},0]]]]],EmptyListOf:["define",{sourceInterval:[392,434]},null,["elem","sep"],["seq",{sourceInterval:[438,438]}]],listOf:["define",{sourceInterval:[438,516]},null,["elem","sep"],["alt",{sourceInterval:[462,516]},["app",{sourceInterval:[462,487]},"nonemptyListOf",[["param",{sourceInterval:[477,481]},0],["param",{sourceInterval:[483,486]},1]]],["app",{sourceInterval:[494,516]},"emptyListOf",[["param",{sourceInterval:[506,510]},0],["param",{sourceInterval:[512,515]},1]]]]],nonemptyListOf:["define",{sourceInterval:[520,568]},null,["elem","sep"],["seq",{sourceInterval:[552,568]},["param",{sourceInterval:[552,556]},0],["star",{sourceInterval:[557,568]},["seq",{sourceInterval:[558,566]},["param",{sourceInterval:[558,561]},1],["param",{sourceInterval:[562,566]},0]]]]],emptyListOf:["define",{sourceInterval:[572,682]},null,["elem","sep"],["seq",{sourceInterval:[685,685]}]],applySyntactic:["define",{sourceInterval:[685,710]},null,["app"],["param",{sourceInterval:[707,710]},0]]}]);an.BuiltInRules=Ky;DO(an.BuiltInRules);const Yy=Gy(["grammar",{source:`Ohm {
123
-
124
- Grammars
125
- = Grammar*
126
-
127
- Grammar
128
- = ident SuperGrammar? "{" Rule* "}"
129
-
130
- SuperGrammar
131
- = "<:" ident
132
-
133
- Rule
134
- = ident Formals? ruleDescr? "=" RuleBody -- define
135
- | ident Formals? ":=" OverrideRuleBody -- override
136
- | ident Formals? "+=" RuleBody -- extend
137
-
138
- RuleBody
139
- = "|"? NonemptyListOf<TopLevelTerm, "|">
140
-
141
- TopLevelTerm
142
- = Seq caseName -- inline
143
- | Seq
144
-
145
- OverrideRuleBody
146
- = "|"? NonemptyListOf<OverrideTopLevelTerm, "|">
147
-
148
- OverrideTopLevelTerm
149
- = "..." -- superSplice
150
- | TopLevelTerm
151
-
152
- Formals
153
- = "<" ListOf<ident, ","> ">"
154
-
155
- Params
156
- = "<" ListOf<Seq, ","> ">"
157
-
158
- Alt
159
- = NonemptyListOf<Seq, "|">
160
-
161
- Seq
162
- = Iter*
163
-
164
- Iter
165
- = Pred "*" -- star
166
- | Pred "+" -- plus
167
- | Pred "?" -- opt
168
- | Pred
169
-
170
- Pred
171
- = "~" Lex -- not
172
- | "&" Lex -- lookahead
173
- | Lex
174
-
175
- Lex
176
- = "#" Base -- lex
177
- | Base
178
-
179
- Base
180
- = ident Params? ~(ruleDescr? "=" | ":=" | "+=") -- application
181
- | oneCharTerminal ".." oneCharTerminal -- range
182
- | terminal -- terminal
183
- | "(" Alt ")" -- paren
184
-
185
- ruleDescr (a rule description)
186
- = "(" ruleDescrText ")"
187
-
188
- ruleDescrText
189
- = (~")" any)*
190
-
191
- caseName
192
- = "--" (~"\\n" space)* name (~"\\n" space)* ("\\n" | &"}")
193
-
194
- name (a name)
195
- = nameFirst nameRest*
196
-
197
- nameFirst
198
- = "_"
199
- | letter
200
-
201
- nameRest
202
- = "_"
203
- | alnum
204
-
205
- ident (an identifier)
206
- = name
207
-
208
- terminal
209
- = "\\"" terminalChar* "\\""
210
-
211
- oneCharTerminal
212
- = "\\"" terminalChar "\\""
213
-
214
- terminalChar
215
- = escapeChar
216
- | ~"\\\\" ~"\\"" ~"\\n" "\\u{0}".."\\u{10FFFF}"
217
-
218
- escapeChar (an escape sequence)
219
- = "\\\\\\\\" -- backslash
220
- | "\\\\\\"" -- doubleQuote
221
- | "\\\\\\'" -- singleQuote
222
- | "\\\\b" -- backspace
223
- | "\\\\n" -- lineFeed
224
- | "\\\\r" -- carriageReturn
225
- | "\\\\t" -- tab
226
- | "\\\\u{" hexDigit hexDigit? hexDigit?
227
- hexDigit? hexDigit? hexDigit? "}" -- unicodeCodePoint
228
- | "\\\\u" hexDigit hexDigit hexDigit hexDigit -- unicodeEscape
229
- | "\\\\x" hexDigit hexDigit -- hexEscape
230
-
231
- space
232
- += comment
233
-
234
- comment
235
- = "//" (~"\\n" any)* &("\\n" | end) -- singleLine
236
- | "/*" (~"*/" any)* "*/" -- multiLine
237
-
238
- tokens = token*
239
-
240
- token = caseName | comment | ident | operator | punctuation | terminal | any
241
-
242
- operator = "<:" | "=" | ":=" | "+=" | "*" | "+" | "?" | "~" | "&"
243
-
244
- punctuation = "<" | ">" | "," | "--"
245
- }`},"Ohm",null,"Grammars",{Grammars:["define",{sourceInterval:[9,32]},null,[],["star",{sourceInterval:[24,32]},["app",{sourceInterval:[24,31]},"Grammar",[]]]],Grammar:["define",{sourceInterval:[36,83]},null,[],["seq",{sourceInterval:[50,83]},["app",{sourceInterval:[50,55]},"ident",[]],["opt",{sourceInterval:[56,69]},["app",{sourceInterval:[56,68]},"SuperGrammar",[]]],["terminal",{sourceInterval:[70,73]},"{"],["star",{sourceInterval:[74,79]},["app",{sourceInterval:[74,78]},"Rule",[]]],["terminal",{sourceInterval:[80,83]},"}"]]],SuperGrammar:["define",{sourceInterval:[87,116]},null,[],["seq",{sourceInterval:[106,116]},["terminal",{sourceInterval:[106,110]},"<:"],["app",{sourceInterval:[111,116]},"ident",[]]]],Rule_define:["define",{sourceInterval:[131,181]},null,[],["seq",{sourceInterval:[131,170]},["app",{sourceInterval:[131,136]},"ident",[]],["opt",{sourceInterval:[137,145]},["app",{sourceInterval:[137,144]},"Formals",[]]],["opt",{sourceInterval:[146,156]},["app",{sourceInterval:[146,155]},"ruleDescr",[]]],["terminal",{sourceInterval:[157,160]},"="],["app",{sourceInterval:[162,170]},"RuleBody",[]]]],Rule_override:["define",{sourceInterval:[188,248]},null,[],["seq",{sourceInterval:[188,235]},["app",{sourceInterval:[188,193]},"ident",[]],["opt",{sourceInterval:[194,202]},["app",{sourceInterval:[194,201]},"Formals",[]]],["terminal",{sourceInterval:[214,218]},":="],["app",{sourceInterval:[219,235]},"OverrideRuleBody",[]]]],Rule_extend:["define",{sourceInterval:[255,305]},null,[],["seq",{sourceInterval:[255,294]},["app",{sourceInterval:[255,260]},"ident",[]],["opt",{sourceInterval:[261,269]},["app",{sourceInterval:[261,268]},"Formals",[]]],["terminal",{sourceInterval:[281,285]},"+="],["app",{sourceInterval:[286,294]},"RuleBody",[]]]],Rule:["define",{sourceInterval:[120,305]},null,[],["alt",{sourceInterval:[131,305]},["app",{sourceInterval:[131,170]},"Rule_define",[]],["app",{sourceInterval:[188,235]},"Rule_override",[]],["app",{sourceInterval:[255,294]},"Rule_extend",[]]]],RuleBody:["define",{sourceInterval:[309,362]},null,[],["seq",{sourceInterval:[324,362]},["opt",{sourceInterval:[324,328]},["terminal",{sourceInterval:[324,327]},"|"]],["app",{sourceInterval:[329,362]},"NonemptyListOf",[["app",{sourceInterval:[344,356]},"TopLevelTerm",[]],["terminal",{sourceInterval:[358,361]},"|"]]]]],TopLevelTerm_inline:["define",{sourceInterval:[385,408]},null,[],["seq",{sourceInterval:[385,397]},["app",{sourceInterval:[385,388]},"Seq",[]],["app",{sourceInterval:[389,397]},"caseName",[]]]],TopLevelTerm:["define",{sourceInterval:[366,418]},null,[],["alt",{sourceInterval:[385,418]},["app",{sourceInterval:[385,397]},"TopLevelTerm_inline",[]],["app",{sourceInterval:[415,418]},"Seq",[]]]],OverrideRuleBody:["define",{sourceInterval:[422,491]},null,[],["seq",{sourceInterval:[445,491]},["opt",{sourceInterval:[445,449]},["terminal",{sourceInterval:[445,448]},"|"]],["app",{sourceInterval:[450,491]},"NonemptyListOf",[["app",{sourceInterval:[465,485]},"OverrideTopLevelTerm",[]],["terminal",{sourceInterval:[487,490]},"|"]]]]],OverrideTopLevelTerm_superSplice:["define",{sourceInterval:[522,543]},null,[],["terminal",{sourceInterval:[522,527]},"..."]],OverrideTopLevelTerm:["define",{sourceInterval:[495,562]},null,[],["alt",{sourceInterval:[522,562]},["app",{sourceInterval:[522,527]},"OverrideTopLevelTerm_superSplice",[]],["app",{sourceInterval:[550,562]},"TopLevelTerm",[]]]],Formals:["define",{sourceInterval:[566,606]},null,[],["seq",{sourceInterval:[580,606]},["terminal",{sourceInterval:[580,583]},"<"],["app",{sourceInterval:[584,602]},"ListOf",[["app",{sourceInterval:[591,596]},"ident",[]],["terminal",{sourceInterval:[598,601]},","]]],["terminal",{sourceInterval:[603,606]},">"]]],Params:["define",{sourceInterval:[610,647]},null,[],["seq",{sourceInterval:[623,647]},["terminal",{sourceInterval:[623,626]},"<"],["app",{sourceInterval:[627,643]},"ListOf",[["app",{sourceInterval:[634,637]},"Seq",[]],["terminal",{sourceInterval:[639,642]},","]]],["terminal",{sourceInterval:[644,647]},">"]]],Alt:["define",{sourceInterval:[651,685]},null,[],["app",{sourceInterval:[661,685]},"NonemptyListOf",[["app",{sourceInterval:[676,679]},"Seq",[]],["terminal",{sourceInterval:[681,684]},"|"]]]],Seq:["define",{sourceInterval:[689,704]},null,[],["star",{sourceInterval:[699,704]},["app",{sourceInterval:[699,703]},"Iter",[]]]],Iter_star:["define",{sourceInterval:[719,736]},null,[],["seq",{sourceInterval:[719,727]},["app",{sourceInterval:[719,723]},"Pred",[]],["terminal",{sourceInterval:[724,727]},"*"]]],Iter_plus:["define",{sourceInterval:[743,760]},null,[],["seq",{sourceInterval:[743,751]},["app",{sourceInterval:[743,747]},"Pred",[]],["terminal",{sourceInterval:[748,751]},"+"]]],Iter_opt:["define",{sourceInterval:[767,783]},null,[],["seq",{sourceInterval:[767,775]},["app",{sourceInterval:[767,771]},"Pred",[]],["terminal",{sourceInterval:[772,775]},"?"]]],Iter:["define",{sourceInterval:[708,794]},null,[],["alt",{sourceInterval:[719,794]},["app",{sourceInterval:[719,727]},"Iter_star",[]],["app",{sourceInterval:[743,751]},"Iter_plus",[]],["app",{sourceInterval:[767,775]},"Iter_opt",[]],["app",{sourceInterval:[790,794]},"Pred",[]]]],Pred_not:["define",{sourceInterval:[809,824]},null,[],["seq",{sourceInterval:[809,816]},["terminal",{sourceInterval:[809,812]},"~"],["app",{sourceInterval:[813,816]},"Lex",[]]]],Pred_lookahead:["define",{sourceInterval:[831,852]},null,[],["seq",{sourceInterval:[831,838]},["terminal",{sourceInterval:[831,834]},"&"],["app",{sourceInterval:[835,838]},"Lex",[]]]],Pred:["define",{sourceInterval:[798,862]},null,[],["alt",{sourceInterval:[809,862]},["app",{sourceInterval:[809,816]},"Pred_not",[]],["app",{sourceInterval:[831,838]},"Pred_lookahead",[]],["app",{sourceInterval:[859,862]},"Lex",[]]]],Lex_lex:["define",{sourceInterval:[876,892]},null,[],["seq",{sourceInterval:[876,884]},["terminal",{sourceInterval:[876,879]},"#"],["app",{sourceInterval:[880,884]},"Base",[]]]],Lex:["define",{sourceInterval:[866,903]},null,[],["alt",{sourceInterval:[876,903]},["app",{sourceInterval:[876,884]},"Lex_lex",[]],["app",{sourceInterval:[899,903]},"Base",[]]]],Base_application:["define",{sourceInterval:[918,979]},null,[],["seq",{sourceInterval:[918,963]},["app",{sourceInterval:[918,923]},"ident",[]],["opt",{sourceInterval:[924,931]},["app",{sourceInterval:[924,930]},"Params",[]]],["not",{sourceInterval:[932,963]},["alt",{sourceInterval:[934,962]},["seq",{sourceInterval:[934,948]},["opt",{sourceInterval:[934,944]},["app",{sourceInterval:[934,943]},"ruleDescr",[]]],["terminal",{sourceInterval:[945,948]},"="]],["terminal",{sourceInterval:[951,955]},":="],["terminal",{sourceInterval:[958,962]},"+="]]]]],Base_range:["define",{sourceInterval:[986,1041]},null,[],["seq",{sourceInterval:[986,1022]},["app",{sourceInterval:[986,1001]},"oneCharTerminal",[]],["terminal",{sourceInterval:[1002,1006]},".."],["app",{sourceInterval:[1007,1022]},"oneCharTerminal",[]]]],Base_terminal:["define",{sourceInterval:[1048,1106]},null,[],["app",{sourceInterval:[1048,1056]},"terminal",[]]],Base_paren:["define",{sourceInterval:[1113,1168]},null,[],["seq",{sourceInterval:[1113,1124]},["terminal",{sourceInterval:[1113,1116]},"("],["app",{sourceInterval:[1117,1120]},"Alt",[]],["terminal",{sourceInterval:[1121,1124]},")"]]],Base:["define",{sourceInterval:[907,1168]},null,[],["alt",{sourceInterval:[918,1168]},["app",{sourceInterval:[918,963]},"Base_application",[]],["app",{sourceInterval:[986,1022]},"Base_range",[]],["app",{sourceInterval:[1048,1056]},"Base_terminal",[]],["app",{sourceInterval:[1113,1124]},"Base_paren",[]]]],ruleDescr:["define",{sourceInterval:[1172,1231]},"a rule description",[],["seq",{sourceInterval:[1210,1231]},["terminal",{sourceInterval:[1210,1213]},"("],["app",{sourceInterval:[1214,1227]},"ruleDescrText",[]],["terminal",{sourceInterval:[1228,1231]},")"]]],ruleDescrText:["define",{sourceInterval:[1235,1266]},null,[],["star",{sourceInterval:[1255,1266]},["seq",{sourceInterval:[1256,1264]},["not",{sourceInterval:[1256,1260]},["terminal",{sourceInterval:[1257,1260]},")"]],["app",{sourceInterval:[1261,1264]},"any",[]]]]],caseName:["define",{sourceInterval:[1270,1338]},null,[],["seq",{sourceInterval:[1285,1338]},["terminal",{sourceInterval:[1285,1289]},"--"],["star",{sourceInterval:[1290,1304]},["seq",{sourceInterval:[1291,1302]},["not",{sourceInterval:[1291,1296]},["terminal",{sourceInterval:[1292,1296]},`
246
- `]],["app",{sourceInterval:[1297,1302]},"space",[]]]],["app",{sourceInterval:[1305,1309]},"name",[]],["star",{sourceInterval:[1310,1324]},["seq",{sourceInterval:[1311,1322]},["not",{sourceInterval:[1311,1316]},["terminal",{sourceInterval:[1312,1316]},`
247
- `]],["app",{sourceInterval:[1317,1322]},"space",[]]]],["alt",{sourceInterval:[1326,1337]},["terminal",{sourceInterval:[1326,1330]},`
248
- `],["lookahead",{sourceInterval:[1333,1337]},["terminal",{sourceInterval:[1334,1337]},"}"]]]]],name:["define",{sourceInterval:[1342,1382]},"a name",[],["seq",{sourceInterval:[1363,1382]},["app",{sourceInterval:[1363,1372]},"nameFirst",[]],["star",{sourceInterval:[1373,1382]},["app",{sourceInterval:[1373,1381]},"nameRest",[]]]]],nameFirst:["define",{sourceInterval:[1386,1418]},null,[],["alt",{sourceInterval:[1402,1418]},["terminal",{sourceInterval:[1402,1405]},"_"],["app",{sourceInterval:[1412,1418]},"letter",[]]]],nameRest:["define",{sourceInterval:[1422,1452]},null,[],["alt",{sourceInterval:[1437,1452]},["terminal",{sourceInterval:[1437,1440]},"_"],["app",{sourceInterval:[1447,1452]},"alnum",[]]]],ident:["define",{sourceInterval:[1456,1489]},"an identifier",[],["app",{sourceInterval:[1485,1489]},"name",[]]],terminal:["define",{sourceInterval:[1493,1531]},null,[],["seq",{sourceInterval:[1508,1531]},["terminal",{sourceInterval:[1508,1512]},'"'],["star",{sourceInterval:[1513,1526]},["app",{sourceInterval:[1513,1525]},"terminalChar",[]]],["terminal",{sourceInterval:[1527,1531]},'"']]],oneCharTerminal:["define",{sourceInterval:[1535,1579]},null,[],["seq",{sourceInterval:[1557,1579]},["terminal",{sourceInterval:[1557,1561]},'"'],["app",{sourceInterval:[1562,1574]},"terminalChar",[]],["terminal",{sourceInterval:[1575,1579]},'"']]],terminalChar:["define",{sourceInterval:[1583,1660]},null,[],["alt",{sourceInterval:[1602,1660]},["app",{sourceInterval:[1602,1612]},"escapeChar",[]],["seq",{sourceInterval:[1621,1660]},["not",{sourceInterval:[1621,1626]},["terminal",{sourceInterval:[1622,1626]},"\\"]],["not",{sourceInterval:[1627,1632]},["terminal",{sourceInterval:[1628,1632]},'"']],["not",{sourceInterval:[1633,1638]},["terminal",{sourceInterval:[1634,1638]},`
249
- `]],["range",{sourceInterval:[1639,1660]},"\0","􏿿"]]]],escapeChar_backslash:["define",{sourceInterval:[1703,1758]},null,[],["terminal",{sourceInterval:[1703,1709]},"\\\\"]],escapeChar_doubleQuote:["define",{sourceInterval:[1765,1822]},null,[],["terminal",{sourceInterval:[1765,1771]},'\\"']],escapeChar_singleQuote:["define",{sourceInterval:[1829,1886]},null,[],["terminal",{sourceInterval:[1829,1835]},"\\'"]],escapeChar_backspace:["define",{sourceInterval:[1893,1948]},null,[],["terminal",{sourceInterval:[1893,1898]},"\\b"]],escapeChar_lineFeed:["define",{sourceInterval:[1955,2009]},null,[],["terminal",{sourceInterval:[1955,1960]},"\\n"]],escapeChar_carriageReturn:["define",{sourceInterval:[2016,2076]},null,[],["terminal",{sourceInterval:[2016,2021]},"\\r"]],escapeChar_tab:["define",{sourceInterval:[2083,2132]},null,[],["terminal",{sourceInterval:[2083,2088]},"\\t"]],escapeChar_unicodeCodePoint:["define",{sourceInterval:[2139,2243]},null,[],["seq",{sourceInterval:[2139,2221]},["terminal",{sourceInterval:[2139,2145]},"\\u{"],["app",{sourceInterval:[2146,2154]},"hexDigit",[]],["opt",{sourceInterval:[2155,2164]},["app",{sourceInterval:[2155,2163]},"hexDigit",[]]],["opt",{sourceInterval:[2165,2174]},["app",{sourceInterval:[2165,2173]},"hexDigit",[]]],["opt",{sourceInterval:[2188,2197]},["app",{sourceInterval:[2188,2196]},"hexDigit",[]]],["opt",{sourceInterval:[2198,2207]},["app",{sourceInterval:[2198,2206]},"hexDigit",[]]],["opt",{sourceInterval:[2208,2217]},["app",{sourceInterval:[2208,2216]},"hexDigit",[]]],["terminal",{sourceInterval:[2218,2221]},"}"]]],escapeChar_unicodeEscape:["define",{sourceInterval:[2250,2309]},null,[],["seq",{sourceInterval:[2250,2291]},["terminal",{sourceInterval:[2250,2255]},"\\u"],["app",{sourceInterval:[2256,2264]},"hexDigit",[]],["app",{sourceInterval:[2265,2273]},"hexDigit",[]],["app",{sourceInterval:[2274,2282]},"hexDigit",[]],["app",{sourceInterval:[2283,2291]},"hexDigit",[]]]],escapeChar_hexEscape:["define",{sourceInterval:[2316,2371]},null,[],["seq",{sourceInterval:[2316,2339]},["terminal",{sourceInterval:[2316,2321]},"\\x"],["app",{sourceInterval:[2322,2330]},"hexDigit",[]],["app",{sourceInterval:[2331,2339]},"hexDigit",[]]]],escapeChar:["define",{sourceInterval:[1664,2371]},"an escape sequence",[],["alt",{sourceInterval:[1703,2371]},["app",{sourceInterval:[1703,1709]},"escapeChar_backslash",[]],["app",{sourceInterval:[1765,1771]},"escapeChar_doubleQuote",[]],["app",{sourceInterval:[1829,1835]},"escapeChar_singleQuote",[]],["app",{sourceInterval:[1893,1898]},"escapeChar_backspace",[]],["app",{sourceInterval:[1955,1960]},"escapeChar_lineFeed",[]],["app",{sourceInterval:[2016,2021]},"escapeChar_carriageReturn",[]],["app",{sourceInterval:[2083,2088]},"escapeChar_tab",[]],["app",{sourceInterval:[2139,2221]},"escapeChar_unicodeCodePoint",[]],["app",{sourceInterval:[2250,2291]},"escapeChar_unicodeEscape",[]],["app",{sourceInterval:[2316,2339]},"escapeChar_hexEscape",[]]]],space:["extend",{sourceInterval:[2375,2394]},null,[],["app",{sourceInterval:[2387,2394]},"comment",[]]],comment_singleLine:["define",{sourceInterval:[2412,2458]},null,[],["seq",{sourceInterval:[2412,2443]},["terminal",{sourceInterval:[2412,2416]},"//"],["star",{sourceInterval:[2417,2429]},["seq",{sourceInterval:[2418,2427]},["not",{sourceInterval:[2418,2423]},["terminal",{sourceInterval:[2419,2423]},`
250
- `]],["app",{sourceInterval:[2424,2427]},"any",[]]]],["lookahead",{sourceInterval:[2430,2443]},["alt",{sourceInterval:[2432,2442]},["terminal",{sourceInterval:[2432,2436]},`
251
- `],["app",{sourceInterval:[2439,2442]},"end",[]]]]]],comment_multiLine:["define",{sourceInterval:[2465,2501]},null,[],["seq",{sourceInterval:[2465,2487]},["terminal",{sourceInterval:[2465,2469]},"/*"],["star",{sourceInterval:[2470,2482]},["seq",{sourceInterval:[2471,2480]},["not",{sourceInterval:[2471,2476]},["terminal",{sourceInterval:[2472,2476]},"*/"]],["app",{sourceInterval:[2477,2480]},"any",[]]]],["terminal",{sourceInterval:[2483,2487]},"*/"]]],comment:["define",{sourceInterval:[2398,2501]},null,[],["alt",{sourceInterval:[2412,2501]},["app",{sourceInterval:[2412,2443]},"comment_singleLine",[]],["app",{sourceInterval:[2465,2487]},"comment_multiLine",[]]]],tokens:["define",{sourceInterval:[2505,2520]},null,[],["star",{sourceInterval:[2514,2520]},["app",{sourceInterval:[2514,2519]},"token",[]]]],token:["define",{sourceInterval:[2524,2600]},null,[],["alt",{sourceInterval:[2532,2600]},["app",{sourceInterval:[2532,2540]},"caseName",[]],["app",{sourceInterval:[2543,2550]},"comment",[]],["app",{sourceInterval:[2553,2558]},"ident",[]],["app",{sourceInterval:[2561,2569]},"operator",[]],["app",{sourceInterval:[2572,2583]},"punctuation",[]],["app",{sourceInterval:[2586,2594]},"terminal",[]],["app",{sourceInterval:[2597,2600]},"any",[]]]],operator:["define",{sourceInterval:[2604,2669]},null,[],["alt",{sourceInterval:[2615,2669]},["terminal",{sourceInterval:[2615,2619]},"<:"],["terminal",{sourceInterval:[2622,2625]},"="],["terminal",{sourceInterval:[2628,2632]},":="],["terminal",{sourceInterval:[2635,2639]},"+="],["terminal",{sourceInterval:[2642,2645]},"*"],["terminal",{sourceInterval:[2648,2651]},"+"],["terminal",{sourceInterval:[2654,2657]},"?"],["terminal",{sourceInterval:[2660,2663]},"~"],["terminal",{sourceInterval:[2666,2669]},"&"]]],punctuation:["define",{sourceInterval:[2673,2709]},null,[],["alt",{sourceInterval:[2687,2709]},["terminal",{sourceInterval:[2687,2690]},"<"],["terminal",{sourceInterval:[2693,2696]},">"],["terminal",{sourceInterval:[2699,2702]},","],["terminal",{sourceInterval:[2705,2709]},"--"]]]}]),Tp=Object.create(we.prototype);function ux(t,e){for(const n in t)if(n===e)return!0;return!1}function U1(t,e,n,r){const s=new Hu(r);let o,c,d,f=!1;return(n||Yy).createSemantics().addOperation("visit",{Grammars(b){return b.children.map(v=>v.visit())},Grammar(b,v,w,_,k){const I=b.visit();o=s.newGrammar(I),v.child(0)&&v.child(0).visit(),_.children.map(R=>R.visit());const N=o.build();if(N.source=this.source.trimmed(),ux(e,I))throw yO(N);return e[I]=N,N},SuperGrammar(b,v){const w=v.visit();if(w==="null")o.withSuperGrammar(null);else{if(!e||!ux(e,w))throw mO(w,e,v.source);o.withSuperGrammar(e[w])}},Rule_define(b,v,w,_,k){c=b.visit(),d=v.children.map(M=>M.visit())[0]||[],!o.defaultStartRule&&o.ensureSuperGrammar()!==an.ProtoBuiltInRules&&o.withDefaultStartRule(c);const I=k.visit(),N=w.children.map(M=>M.visit())[0],R=this.source.trimmed();return o.define(c,d,I,N,R)},Rule_override(b,v,w,_){c=b.visit(),d=v.children.map(N=>N.visit())[0]||[];const k=this.source.trimmed();o.ensureSuperGrammarRuleForOverriding(c,k),f=!0;const I=_.visit();return f=!1,o.override(c,d,I,null,k)},Rule_extend(b,v,w,_){c=b.visit(),d=v.children.map(N=>N.visit())[0]||[];const k=_.visit(),I=this.source.trimmed();return o.extend(c,d,k,null,I)},RuleBody(b,v){return s.alt(...v.visit()).withSource(this.source)},OverrideRuleBody(b,v){const w=v.visit(),_=w.indexOf(Tp);if(_>=0){const k=w.slice(0,_),I=w.slice(_+1);return I.forEach(N=>{if(N===Tp)throw jO(N)}),new Od(o.superGrammar,c,k,I).withSource(this.source)}else return s.alt(...w).withSource(this.source)},Formals(b,v,w){return v.visit()},Params(b,v,w){return v.visit()},Alt(b){return s.alt(...b.visit()).withSource(this.source)},TopLevelTerm_inline(b,v){const w=c+"_"+v.visit(),_=b.visit(),k=this.source.trimmed(),I=!(o.superGrammar&&o.superGrammar.rules[w]);f&&!I?o.override(w,d,_,null,k):o.define(w,d,_,null,k);const N=d.map(R=>s.app(R));return s.app(w,N).withSource(_.source)},OverrideTopLevelTerm_superSplice(b){return Tp},Seq(b){return s.seq(...b.children.map(v=>v.visit())).withSource(this.source)},Iter_star(b,v){return s.star(b.visit()).withSource(this.source)},Iter_plus(b,v){return s.plus(b.visit()).withSource(this.source)},Iter_opt(b,v){return s.opt(b.visit()).withSource(this.source)},Pred_not(b,v){return s.not(v.visit()).withSource(this.source)},Pred_lookahead(b,v){return s.lookahead(v.visit()).withSource(this.source)},Lex_lex(b,v){return s.lex(v.visit()).withSource(this.source)},Base_application(b,v){const w=v.children.map(_=>_.visit())[0]||[];return s.app(b.visit(),w).withSource(this.source)},Base_range(b,v,w){return s.range(b.visit(),w.visit()).withSource(this.source)},Base_terminal(b){return s.terminal(b.visit()).withSource(this.source)},Base_paren(b,v,w){return v.visit()},ruleDescr(b,v,w){return v.visit()},ruleDescrText(b){return this.sourceString.trim()},caseName(b,v,w,_,k){return w.visit()},name(b,v){return this.sourceString},nameFirst(b){},nameRest(b){},terminal(b,v,w){return v.children.map(_=>_.visit()).join("")},oneCharTerminal(b,v,w){return v.visit()},escapeChar(b){try{return _1(this.sourceString)}catch(v){throw v instanceof RangeError&&v.message.startsWith("Invalid code point ")?kO(b):v}},NonemptyListOf(b,v,w){return[b.visit()].concat(w.children.map(_=>_.visit()))},EmptyListOf(){return[]},_terminal(){return this.sourceString}})(t).visit()}const JO=Gy(["grammar",{source:`OperationsAndAttributes {
252
-
253
- AttributeSignature =
254
- name
255
-
256
- OperationSignature =
257
- name Formals?
258
-
259
- Formals
260
- = "(" ListOf<name, ","> ")"
261
-
262
- name (a name)
263
- = nameFirst nameRest*
264
-
265
- nameFirst
266
- = "_"
267
- | letter
268
-
269
- nameRest
270
- = "_"
271
- | alnum
272
-
273
- }`},"OperationsAndAttributes",null,"AttributeSignature",{AttributeSignature:["define",{sourceInterval:[29,58]},null,[],["app",{sourceInterval:[54,58]},"name",[]]],OperationSignature:["define",{sourceInterval:[62,100]},null,[],["seq",{sourceInterval:[87,100]},["app",{sourceInterval:[87,91]},"name",[]],["opt",{sourceInterval:[92,100]},["app",{sourceInterval:[92,99]},"Formals",[]]]]],Formals:["define",{sourceInterval:[104,143]},null,[],["seq",{sourceInterval:[118,143]},["terminal",{sourceInterval:[118,121]},"("],["app",{sourceInterval:[122,139]},"ListOf",[["app",{sourceInterval:[129,133]},"name",[]],["terminal",{sourceInterval:[135,138]},","]]],["terminal",{sourceInterval:[140,143]},")"]]],name:["define",{sourceInterval:[147,187]},"a name",[],["seq",{sourceInterval:[168,187]},["app",{sourceInterval:[168,177]},"nameFirst",[]],["star",{sourceInterval:[178,187]},["app",{sourceInterval:[178,186]},"nameRest",[]]]]],nameFirst:["define",{sourceInterval:[191,223]},null,[],["alt",{sourceInterval:[207,223]},["terminal",{sourceInterval:[207,210]},"_"],["app",{sourceInterval:[217,223]},"letter",[]]]],nameRest:["define",{sourceInterval:[227,257]},null,[],["alt",{sourceInterval:[242,257]},["terminal",{sourceInterval:[242,245]},"_"],["app",{sourceInterval:[252,257]},"alnum",[]]]]}]);XO(an.BuiltInRules);eR(JO);function XO(t){const e={empty(){return this.iteration()},nonEmpty(n,r,s){return this.iteration([n].concat(s.children))},self(...n){return this}};wn.BuiltInSemantics=wn.createSemantics(t,null).addOperation("asIteration",{emptyListOf:e.empty,nonemptyListOf:e.nonEmpty,EmptyListOf:e.empty,NonemptyListOf:e.nonEmpty,_iter:e.self})}function eR(t){wn.prototypeGrammarSemantics=t.createSemantics().addOperation("parse",{AttributeSignature(e){return{name:e.parse(),formals:[]}},OperationSignature(e,n){return{name:e.parse(),formals:n.children.map(r=>r.parse())[0]||[]}},Formals(e,n,r){return n.asIteration().children.map(s=>s.parse())},name(e,n){return this.sourceString}}),wn.prototypeGrammar=t}function tR(t){let e=0;const n=[0],r=()=>n[n.length-1],s={},o=/( *).*(?:$|\r?\n|\r)/g;let c;for(;(c=o.exec(t))!=null;){const[d,f]=c;if(d.length===0)break;const p=f.length,g=r(),b=e+p;if(p>g)n.push(p),s[b]=1;else if(p<g){const v=n.length;for(;r()!==p;)n.pop();s[b]=-1*(v-n.length)}e+=d.length}return n.length>1&&(s[e]=1-n.length),s}const $1="an indented block",B1="a dedent",dx=1114112;class nR extends Rd{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),dx):super.nextCharCode()}nextCodePoint(){return this._indentationAt(this.pos)!==0?(this.examinedLength=Math.max(this.examinedLength,this.pos),dx):super.nextCodePoint()}}class fx extends we{constructor(e=!0){super(),this.isIndent=e}allowsSkippingPrecedingSpace(){return!0}eval(e){const{inputStream:n}=e,r=e.userData;e.doNotMemoize=!0;const s=n.pos,o=this.isIndent?1:-1;return(r[s]||0)*o>0?(e.userData=Object.create(r),e.userData[s]-=o,e.pushBinding(new Yi(0),s),!0):(e.processFailure(s,this),!1)}getArity(){return 1}_assertAllApplicationsAreValid(e,n){}_isNullable(e,n){return!1}assertChoicesHaveUniformArity(e){}assertIteratedExprsAreNotNullable(e){}introduceParams(e){return this}substituteParams(e){return this}toString(){return this.isIndent?"indent":"dedent"}toDisplayString(){return this.toString()}toFailure(e){const n=this.isIndent?$1:B1;return new Sn(this,n,"description")}}const rR=new Ze("indent"),sR=new Ze("dedent"),iR=new Od(Ky,"any",[rR,sR],[]),aR=new Hu().newGrammar("IndentationSensitive").withSuperGrammar(Ky).define("indent",[],new fx(!0),$1,void 0,!0).define("dedent",[],new fx(!1),B1,void 0,!0).extend("any",[],iR,"any character",void 0).build();Object.assign(aR,{_matchStateInitializer(t){t.userData=tR(t.input),t.inputStream=new nR(t)},supportsIncrementalParsing:!1});an.initApplicationParser(Yy,U1);const oR=t=>!!t.constructor&&typeof t.constructor.isBuffer=="function"&&t.constructor.isBuffer(t);function lR(t,e,n){const r=Yy.match(t,"Grammars");if(r.failed())throw pO(r);return U1(r,e,void 0,n)}function cR(t,e,n){const r=uR(t,e,n),s=Object.keys(r);if(s.length===0)throw new Error("Missing grammar definition");if(s.length>1){const c=r[s[1]].source;throw new Error(zy(c.sourceString,c.startIdx)+"Found more than one grammar definition -- use ohm.grammars() instead.")}return r[s[0]]}function uR(t,e,n){const r=Object.create({});if(typeof t!="string")if(oR(t))t=t.toString();else throw new TypeError("Expected string as first argument, got "+qy(t));return lR(t,r,n),r}function q1(t,e){return cR(t,e)}const dR=`FirestoreRules {
274
- // === Top-level ===
275
- // Syntactic rules (capitalized) auto-skip spaces between terms.
276
- // Lexical rules (lowercase) do NOT skip spaces.
277
-
278
- // Two accepted orderings. Real \`firestore.rules\` files put
279
- // \`rules_version\` at line 1 (Firebase convention), so the
280
- // \`versionFirst\` branch matches that natural shape. The
281
- // \`importsFirst\` branch keeps legacy samples that put \`import\`
282
- // declarations above the version line working. The semantic
283
- // action below normalizes both into the same AST shape, so
284
- // downstream code doesn't have to care which path matched.
285
- // Declaration order is STRICT: imports, then functions (#347 probe,
286
- // 2026-07-17): the production Rules Test API rejects \`import\` after a
287
- // \`function\` ("Unexpected 'import'") and any declaration before
288
- // \`rules_version\` ("Unexpected 'rules_version'"), under both
289
- // rules_version '2' and '2+modules'. Pinned by
290
- // test/rules/corpus/invalid/009-/010-.
291
- RulesFile = RulesVersion? ImportDecl* FunctionDef* ServiceBlock -- versionFirst
292
- | ImportDecl* RulesVersion FunctionDef* ServiceBlock -- importsFirst
293
-
294
- ImportDecl = "import" "{" ListOf<ident, ","> ","? "}" "from" string ";"
295
-
296
- RulesVersion = "rules_version" "=" string ";"
297
-
298
- ServiceBlock = "service" serviceName "{" FunctionDef* DocumentsMatch FunctionDef* "}"
299
-
300
- DocumentsMatch = "match" matchPath "{" MatchBody "}"
301
-
302
- MatchBody = MatchBodyItem*
303
-
304
- MatchBodyItem
305
- = FunctionDef
306
- | MatchBlock
307
- | AllowStatement
308
-
309
- MatchBlock = "match" matchPath "{" MatchBody "}"
310
-
311
- // === Statements ===
312
-
313
- AllowStatement = "allow" OperationList ":" "if" Expr ";"
314
-
315
- OperationList = Operation ("," Operation)*
316
-
317
- FunctionDef = "export"? "function" ident "(" ParameterList ")" "{" FunctionBody "}"
318
-
319
- ParameterList = ListOf<ident, ",">
320
-
321
- FunctionBody = LetBinding* ReturnStatement
322
-
323
- LetBinding = "let" ident "=" Expr ";"
324
-
325
- ReturnStatement = "return" Expr ";"
326
-
327
- // === Lexical: operations and service name ===
328
-
329
- Operation
330
- = "read" ~identChar
331
- | "write" ~identChar
332
- | "get" ~identChar
333
- | "list" ~identChar
334
- | "create" ~identChar
335
- | "update" ~identChar
336
- | "delete" ~identChar
337
-
338
- serviceName = letter (letter | ".")*
339
-
340
- // === Lexical: match paths ===
341
-
342
- matchPath = "/" matchPathSegment ("/" matchPathSegment)*
343
-
344
- matchPathSegment
345
- = "{" matchWildcard "}" -- wildcard
346
- | pathIdent -- literal
347
-
348
- matchWildcard
349
- = identStart identChar* "=" "**" -- recursive
350
- | identStart identChar* -- single
351
-
352
- pathIdent = (letter | digit | "_" | "-" | ".")+
353
-
354
- // === Expressions ===
355
-
356
- Expr = Ternary
357
-
358
- Ternary
359
- = LogicalOr "?" Ternary ":" Ternary -- ternary
360
- | LogicalOr
361
-
362
- LogicalOr
363
- = LogicalOr "||" LogicalAnd -- or
364
- | LogicalAnd
365
-
366
- LogicalAnd
367
- = LogicalAnd "&&" InIsExpr -- and
368
- | InIsExpr
369
-
370
- InIsExpr
371
- = Equality in Equality -- in
372
- | Equality is typeName -- is
373
- | Equality
374
-
375
- in = "in" ~identChar
376
- is = "is" ~identChar
377
-
378
- Equality
379
- = Equality "==" Comparison -- eq
380
- | Equality "!=" Comparison -- neq
381
- | Comparison
382
-
383
- Comparison
384
- = Comparison ">=" Additive -- gte
385
- | Comparison "<=" Additive -- lte
386
- | Comparison ">" Additive -- gt
387
- | Comparison "<" Additive -- lt
388
- | Additive
389
-
390
- Additive
391
- = Additive "+" Multiplicative -- add
392
- | Additive "-" Multiplicative -- sub
393
- | Multiplicative
394
-
395
- Multiplicative
396
- = Multiplicative "*" UnaryExpr -- mul
397
- | Multiplicative "/" UnaryExpr -- div
398
- | Multiplicative "%" UnaryExpr -- mod
399
- | UnaryExpr
400
-
401
- UnaryExpr
402
- = "!" UnaryExpr -- not
403
- | "-" UnaryExpr -- neg
404
- | PostfixExpr
405
-
406
- PostfixExpr
407
- = PostfixExpr "." memberName "(" ListOf<Expr, ","> ")" -- methodCall
408
- | PostfixExpr "." memberName -- memberAccess
409
- | PostfixExpr "[" Expr ":" Expr "]" -- sliceAccess
410
- | PostfixExpr "[" Expr "]" -- bracketAccess
411
- | Primary
412
-
413
- memberName = identStart identChar*
414
-
415
- Primary
416
- = "(" Expr ")" -- paren
417
- | PathLiteral -- path
418
- | ListLiteral -- list
419
- | MapLiteral -- map
420
- | ident "(" ListOf<Expr, ","> ")" -- functionCall
421
- | literal
422
- | ident
423
-
424
- // === Path literals ===
425
-
426
- PathLiteral = "/" PathLitSegment ("/" PathLitSegment)*
427
-
428
- PathLitSegment
429
- = "$(" Expr ")" -- interpolation
430
- | "{" ident "}" -- captureRef
431
- | "(" pathIdent ")" -- parenLiteral
432
- | pathIdent -- literal
433
-
434
- // === Literals ===
435
-
436
- literal
437
- = number
438
- | string
439
- | bool
440
- | null
441
-
442
- number
443
- = digit+ "." digit+ -- float
444
- | digit+ -- int
445
-
446
- string
447
- = "'" singleStringChar* "'" -- single
448
- | "\\"" doubleStringChar* "\\"" -- double
449
-
450
- singleStringChar
451
- = "\\\\" stringEscapeChar -- escape
452
- | ~"\\\\" ~"'" any -- char
453
-
454
- doubleStringChar
455
- = "\\\\" stringEscapeChar -- escape
456
- | ~"\\\\" ~"\\"" any -- char
457
-
458
- // Valid escape characters following a backslash. Anything else is rejected
459
- // at parse time to match production semantics — production Firestore Rules
460
- // raises a syntax error on unknown escapes (e.g. \`\\d\`, \`\\.\`). Keeping the
461
- // sim strict here prevents over-permissive acceptance that masks model
462
- // output that would crash at deploy.
463
- stringEscapeChar = "\\\\" | "'" | "\\"" | "n" | "r" | "t" | "/"
464
-
465
- ListLiteral = "[" ListOf<Expr, ","> ","? "]"
466
-
467
- MapLiteral = "{" ListOf<MapEntry, ","> ","? "}"
468
-
469
- MapEntry = (string | ident) ":" Expr
470
-
471
- bool
472
- = "true" ~identChar -- true
473
- | "false" ~identChar -- false
474
-
475
- null = "null" ~identChar
476
-
477
- typeName
478
- = "string" ~identChar
479
- | "int" ~identChar
480
- | "float" ~identChar
481
- | "number" ~identChar
482
- | "bool" ~identChar
483
- | "list" ~identChar
484
- | "map" ~identChar
485
- | "timestamp" ~identChar
486
- | "path" ~identChar
487
- | "bytes" ~identChar
488
- | "duration" ~identChar
489
- | "latlng" ~identChar
490
- | "reference" ~identChar
491
-
492
- ident = ~keyword identStart identChar*
493
-
494
- keyword
495
- = ("true" | "false" | "null" | "in" | "is" | "if" | "return" | "let") ~identChar
496
-
497
- identStart = letter | "_"
498
-
499
- identChar = alnum | "_"
500
-
501
- // === Whitespace and comments ===
502
-
503
- space += comment
504
-
505
- comment
506
- = "//" (~"\\n" any)* &("\\n" | end) -- singleLine
507
- | "/*" (~"*/" any)* "*/" -- multiLine
508
- }
509
- `,F1=q1(dR),z1=F1.createSemantics();z1.addOperation("toAST",{RulesFile_versionFirst(t,e,n,r){return{imports:e.children.map(s=>s.toAST()),version:t.children.length>0?t.children[0].toAST():"1",functions:n.children.map(s=>s.toAST()),service:r.toAST()}},RulesFile_importsFirst(t,e,n,r){return{imports:t.children.map(s=>s.toAST()),version:e.toAST(),functions:n.children.map(s=>s.toAST()),service:r.toAST()}},ImportDecl(t,e,n,r,s,o,c,d){return{functions:n.asIteration().children.map(f=>f.sourceString),module:c.toAST().value}},RulesVersion(t,e,n,r){return n.toAST().value},ServiceBlock(t,e,n,r,s,o,c){return{name:e.sourceString,functions:[...r.children.map(d=>d.toAST()),...o.children.map(d=>d.toAST())],match:s.toAST()}},DocumentsMatch(t,e,n,r,s){const{lineNum:o,colNum:c}=t.source.getLineAndColumn();return{...r.toAST(),path:px(e.sourceString),loc:{line:o,col:c}}},MatchBody(t){const e=[],n=[],r=[];for(const s of t.children){const o=s.toAST();o._kind==="function"?e.push(o):o._kind==="allow"?n.push(o):o._kind==="match"&&r.push(o)}return{functions:e,allows:n,children:r}},MatchBodyItem(t){return t.toAST()},MatchBlock(t,e,n,r,s){const{functions:o,allows:c,children:d}=r.toAST(),{lineNum:f,colNum:p}=t.source.getLineAndColumn();return{_kind:"match",path:px(e.sourceString),functions:o,allows:c,children:d,loc:{line:f,col:p}}},AllowStatement(t,e,n,r,s,o){const{lineNum:c,colNum:d}=t.source.getLineAndColumn();return{_kind:"allow",operations:e.toAST(),condition:s.toAST(),loc:{line:c,col:d}}},OperationList(t,e,n){return[t.toAST(),...n.children.map(r=>r.toAST())]},Operation(t){return t.sourceString},FunctionDef(t,e,n,r,s,o,c,d,f){const{lets:p,expr:g}=d.toAST();return{_kind:"function",name:n.sourceString,parameters:s.toAST(),exported:t.sourceString.trim()==="export",lets:p,body:g}},ParameterList(t){return t.asIteration().children.map(e=>e.sourceString)},FunctionBody(t,e){return{lets:t.children.map(n=>n.toAST()),expr:e.toAST()}},LetBinding(t,e,n,r,s){return{name:e.sourceString,value:r.toAST()}},ReturnStatement(t,e,n){return e.toAST()},Expr(t){return t.toAST()},Ternary_ternary(t,e,n,r,s){return{type:"ternary",condition:t.toAST(),consequent:n.toAST(),alternate:s.toAST()}},LogicalOr_or(t,e,n){return{type:"binaryOp",op:"||",left:t.toAST(),right:n.toAST()}},LogicalAnd_and(t,e,n){return{type:"binaryOp",op:"&&",left:t.toAST(),right:n.toAST()}},InIsExpr_in(t,e,n){return{type:"inExpr",element:t.toAST(),collection:n.toAST()}},InIsExpr_is(t,e,n){return{type:"isExpr",value:t.toAST(),typeName:n.sourceString}},Equality_eq(t,e,n){return{type:"binaryOp",op:"==",left:t.toAST(),right:n.toAST()}},Equality_neq(t,e,n){return{type:"binaryOp",op:"!=",left:t.toAST(),right:n.toAST()}},Comparison_gte(t,e,n){return{type:"binaryOp",op:">=",left:t.toAST(),right:n.toAST()}},Comparison_lte(t,e,n){return{type:"binaryOp",op:"<=",left:t.toAST(),right:n.toAST()}},Comparison_gt(t,e,n){return{type:"binaryOp",op:">",left:t.toAST(),right:n.toAST()}},Comparison_lt(t,e,n){return{type:"binaryOp",op:"<",left:t.toAST(),right:n.toAST()}},Additive_add(t,e,n){return{type:"binaryOp",op:"+",left:t.toAST(),right:n.toAST()}},Additive_sub(t,e,n){return{type:"binaryOp",op:"-",left:t.toAST(),right:n.toAST()}},Multiplicative_mul(t,e,n){return{type:"binaryOp",op:"*",left:t.toAST(),right:n.toAST()}},Multiplicative_div(t,e,n){return{type:"binaryOp",op:"/",left:t.toAST(),right:n.toAST()}},Multiplicative_mod(t,e,n){return{type:"binaryOp",op:"%",left:t.toAST(),right:n.toAST()}},UnaryExpr_not(t,e){return{type:"unaryOp",op:"!",operand:e.toAST()}},UnaryExpr_neg(t,e){return{type:"unaryOp",op:"-",operand:e.toAST()}},PostfixExpr_methodCall(t,e,n,r,s,o){return{type:"methodCall",object:t.toAST(),method:n.sourceString,args:s.asIteration().children.map(c=>c.toAST())}},PostfixExpr_memberAccess(t,e,n){return{type:"memberAccess",object:t.toAST(),property:n.sourceString}},PostfixExpr_bracketAccess(t,e,n,r){return{type:"bracketAccess",object:t.toAST(),index:n.toAST()}},PostfixExpr_sliceAccess(t,e,n,r,s,o){return{type:"sliceAccess",object:t.toAST(),start:n.toAST(),end:s.toAST()}},Primary_paren(t,e,n){return e.toAST()},Primary_path(t){return t.toAST()},Primary_list(t){return t.toAST()},Primary_map(t){return t.toAST()},Primary_functionCall(t,e,n,r){return{type:"functionCall",name:t.sourceString,args:n.asIteration().children.map(s=>s.toAST())}},PathLiteral(t,e,n,r){const s=[e.toAST()];for(const o of r.children)s.push(o.toAST());return{type:"pathLiteral",raw:this.sourceString,segments:s}},PathLitSegment_interpolation(t,e,n){return e.toAST()},PathLitSegment_captureRef(t,e,n){return`{${e.sourceString}}`},PathLitSegment_parenLiteral(t,e,n){return`(${e.sourceString})`},PathLitSegment_literal(t){return t.sourceString},ListLiteral(t,e,n,r){return{type:"listLiteral",elements:e.asIteration().children.map(s=>s.toAST())}},MapLiteral(t,e,n,r){return{type:"mapLiteral",entries:e.asIteration().children.map(s=>s.toAST())}},MapEntry(t,e,n){return{key:t.toAST(),value:n.toAST()}},literal(t){return t.toAST()},number_float(t,e,n){return{type:"literal",value:parseFloat(this.sourceString),raw:this.sourceString}},number_int(t){return{type:"literal",value:parseInt(this.sourceString,10),raw:this.sourceString}},string_single(t,e,n){return{type:"literal",value:hx(e.sourceString),raw:this.sourceString}},string_double(t,e,n){return{type:"literal",value:hx(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 hx(t){let e="";for(let n=0;n<t.length;n++){const r=t[n];if(r!=="\\"||n===t.length-1){e+=r;continue}switch(t[n+1]){case"\\":e+="\\",n++;break;case"'":e+="'",n++;break;case'"':e+='"',n++;break;case"n":e+=`
510
- `,n++;break;case"r":e+="\r",n++;break;case"t":e+=" ",n++;break;case"/":e+="/",n++;break;default:e+=r}}return e}function px(t){const e=[],n=t.split("/").filter(Boolean);for(const r of n)if(r.startsWith("{")&&r.endsWith("}")){const s=r.slice(1,-1);s.endsWith("=**")?e.push({type:"recursive",name:s.slice(0,-3)}):e.push({type:"wildcard",name:s})}else e.push({type:"literal",value:r});return{raw:t,segments:e}}function fR(t,e){var p,g;const n=((p=t.getRightmostFailurePosition)==null?void 0:p.call(t))??0,r=((g=t.getExpectedText)==null?void 0:g.call(t))??"";let s=1,o=-1;for(let b=0;b<n&&b<e.length;b++)e.charCodeAt(b)===10&&(s++,o=b);const c=n-o;let d=e.indexOf(`
511
- `,n);d===-1&&(d=e.length);const f=e.slice(n,Math.min(d,n+40));return{line:s,column:c,offset:n,expected:r,actual:f,message:t.message??"Parse error"}}function Zy(t){const e=Tl(t);return e.ok?e.ast:null}function Tl(t){const e=t.trim();if(!e)return{ok:!1,error:{line:1,column:1,offset:0,expected:"",actual:"",message:"Empty rules file"}};const n=F1.match(e);if(!n.succeeded())return{ok:!1,error:fR(n,e)};const r=z1(n).toAST(),s=t.length-t.trimStart().length;let o=0;for(let c=0;c<s;c++)t.charCodeAt(c)===10&&o++;return o>0&&hR(r,o),{ok:!0,ast:r}}function hR(t,e){const n=[t.service.match];for(;n.length>0;){const r=n.pop();r.loc&&(r.loc.line+=e);for(const s of r.allows)s.loc&&(s.loc.line+=e);for(const s of r.children)n.push(s)}}function pR(t){const e=`rules_version = '2';
512
- service cloud.firestore {
513
- match /databases/{db}/documents {
514
- ${t}
515
- }
516
- }`,n=Zy(e);return n?n.service.match.functions:null}const P1={"||":2,"&&":3,"==":5,"!=":5,">":6,"<":6,">=":6,"<=":6,"+":7,"-":7,"*":8,"/":8,"%":8};function mR(t){switch(t.type){case"ternary":return 1;case"binaryOp":return P1[t.op]??0;case"inExpr":return 4;case"isExpr":return 4;case"unaryOp":return 9;default:return 100}}function yR(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`${Zn(t.object,10)}.${t.property}`;case"methodCall":return`${Zn(t.object,10)}.${t.method}(${t.args.map(e=>zt(e)).join(", ")})`;case"bracketAccess":return`${Zn(t.object,10)}[${zt(t.index)}]`;case"sliceAccess":return`${Zn(t.object,10)}[${zt(t.start)}:${zt(t.end)}]`;case"binaryOp":{const e=P1[t.op]??0,n=Zn(t.left,e),r=Zn(t.right,e+1);return`${n} ${t.op} ${r}`}case"unaryOp":return`${t.op}${Zn(t.operand,9)}`;case"ternary":return`${Zn(t.condition,2)} ? ${zt(t.consequent)} : ${zt(t.alternate)}`;case"inExpr":return`${Zn(t.element,5)} in ${Zn(t.collection,5)}`;case"isExpr":return`${Zn(t.value,5)} is ${t.typeName}`;case"listLiteral":return t.elements.length===0?"[]":`[${t.elements.map(e=>zt(e)).join(", ")}]`;case"mapLiteral":return t.entries.length===0?"{}":`{${t.entries.map(e=>`${zt(e.key)}: ${zt(e.value)}`).join(", ")}}`;case"pathLiteral":return"/"+t.segments.map(e=>typeof e=="string"?e:`$(${zt(e)})`).join("/");case"functionCall":return`${t.name}(${t.args.map(e=>zt(e)).join(", ")})`}}function Zn(t,e){const n=yR(t);return mR(t)<e?`(${n})`:n}function zt(t){return Zn(t,0)}function V1(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 Dl(t){return" ".repeat(t)}function H1(t,e){const n=Dl(e),r=Dl(e+2),s=t.parameters.join(", "),o=[],c=t.exported?"export ":"";o.push(`${n}${c}function ${t.name}(${s}) {`);for(const d of t.lets)o.push(`${r}let ${d.name} = ${zt(d.value)};`);return o.push(`${r}return ${zt(t.body)};`),o.push(`${n}}`),o.join(`
517
- `)}function G1(t,e){const n=Dl(e),r=t.operations.join(", ");return`${n}allow ${r}: if ${zt(t.condition)};`}function K1(t,e=0){const n=Dl(e),r=e+2,s=[];s.push(`${n}match ${V1(t.path)} {`);for(const o of t.functions)s.push(H1(o,r));for(const o of t.allows)s.push(G1(o,r));for(const o of t.children)s.push(K1(o,r));return s.push(`${n}}`),s.join(`
518
- `)}function mx(t){const e=[];for(const o of t.imports)e.push(`import { ${o.functions.join(", ")} } from '${o.module}';`);e.push(`rules_version = '${t.version}';`),e.push(`service ${t.service.name} {`);const n=t.service.match,r=Dl(2),s=4;e.push(`${r}match ${V1(n.path)} {`);for(const o of n.functions)e.push(H1(o,s));for(const o of n.allows)e.push(G1(o,s));for(const o of n.children)e.push(K1(o,s));return e.push(`${r}}`),e.push("}"),e.push(""),e.join(`
519
- `)}function Gu(t,e){return t.type!=="binaryOp"||t.op!==e?0:1+Gu(t.right,e)}function xm(t){let e={op:"",depth:0};function n(s){if(s.type==="binaryOp"){const o=Gu(s,"&&"),c=Gu(s,"||");o>e.depth&&(e={op:"&&",depth:o}),c>e.depth&&(e={op:"||",depth:c}),n(s.left),n(s.right)}else r(s)}function r(s){switch(s.type){case"unaryOp":n(s.operand);break;case"methodCall":n(s.object),s.args.forEach(n);break;case"memberAccess":n(s.object);break;case"bracketAccess":n(s.object),n(s.index);break;case"ternary":n(s.condition),n(s.consequent),n(s.alternate);break;case"inExpr":n(s.element),n(s.collection);break;case"isExpr":n(s.value);break;case"listLiteral":s.elements.forEach(n);break;case"mapLiteral":s.entries.forEach(o=>{n(o.key),n(o.value)});break;case"functionCall":s.args.forEach(n);break}}return n(t),e}function pt(t){let e=1;switch(t.type){case"binaryOp":e+=pt(t.left)+pt(t.right);break;case"unaryOp":e+=pt(t.operand);break;case"methodCall":e+=pt(t.object);for(const n of t.args)e+=pt(n);break;case"memberAccess":e+=pt(t.object);break;case"bracketAccess":e+=pt(t.object)+pt(t.index);break;case"ternary":e+=pt(t.condition)+pt(t.consequent)+pt(t.alternate);break;case"inExpr":e+=pt(t.element)+pt(t.collection);break;case"isExpr":e+=pt(t.value);break;case"listLiteral":for(const n of t.elements)e+=pt(n);break;case"mapLiteral":for(const n of t.entries)e+=pt(n.key)+pt(n.value);break;case"functionCall":for(const n of t.args)e+=pt(n);break;case"pathLiteral":for(const n of t.segments)typeof n!="string"&&(e+=pt(n));break}return e}function ht(t){switch(t.type){case"literal":return`L:${t.raw}`;case"identifier":return`I:${t.name}`;case"memberAccess":return`M:${ht(t.object)}.${t.property}`;case"methodCall":return`MC:${ht(t.object)}.${t.method}(${t.args.map(ht).join(",")})`;case"bracketAccess":return`B:${ht(t.object)}[${ht(t.index)}]`;case"binaryOp":return`BO:${ht(t.left)}${t.op}${ht(t.right)}`;case"unaryOp":return`UO:${t.op}${ht(t.operand)}`;case"ternary":return`T:${ht(t.condition)}?${ht(t.consequent)}:${ht(t.alternate)}`;case"inExpr":return`IN:${ht(t.element)}in${ht(t.collection)}`;case"isExpr":return`IS:${ht(t.value)}is${t.typeName}`;case"listLiteral":return`LL:[${t.elements.map(ht).join(",")}]`;case"mapLiteral":return`ML:{${t.entries.map(e=>ht(e.key)+":"+ht(e.value)).join(",")}}`;case"functionCall":return`FC:${t.name}(${t.args.map(ht).join(",")})`;case"pathLiteral":return`PL:${t.raw}`;case"sliceAccess":return`SL:${ht(t.object)}[${ht(t.start)}:${ht(t.end)}]`;default:{const e=t;throw new Error(`expressionFingerprint: unhandled type ${e.type}`)}}}function Y1(t){return t.type==="binaryOp"&&t.op==="&&"?Y1(t.left):t}function Z1(t){const e=new Map,n=new Set(t.map(o=>o.name)),r=new Set(["get","exists","getAfter","debug"]);function s(o){const c=[],d=f=>{switch(f.type){case"functionCall":n.has(f.name)&&!r.has(f.name)&&c.push(f.name),f.args.forEach(d);break;case"binaryOp":d(f.left),d(f.right);break;case"unaryOp":d(f.operand);break;case"methodCall":d(f.object),f.args.forEach(d);break;case"memberAccess":d(f.object);break;case"bracketAccess":d(f.object),d(f.index);break;case"ternary":d(f.condition),d(f.consequent),d(f.alternate);break;case"inExpr":d(f.element),d(f.collection);break;case"isExpr":d(f.value);break;case"listLiteral":f.elements.forEach(d);break;case"mapLiteral":f.entries.forEach(p=>{d(p.key),d(p.value)});break}};return d(o),[...new Set(c)]}for(const o of t){const c=[];c.push(...s(o.body));for(const d of o.lets)c.push(...s(d.value));e.set(o.name,[...new Set(c)])}return e}function Wy(t,e,n=new Set){if(n.has(t))return 0;n.add(t);const r=e.get(t)||[];if(r.length===0)return 1;let s=0;for(const o of r)s=Math.max(s,Wy(o,e,new Set(n)));return 1+s}function W1(t,e,n=new Set){let r=0;const s=o=>{switch(o.type){case"functionCall":if(o.name==="get"||o.name==="exists")r++;else if(e.has(o.name)&&!n.has(o.name)){n.add(o.name);const c=e.get(o.name);s(c.body);for(const d of c.lets)s(d.value)}o.args.forEach(s);break;case"binaryOp":s(o.left),s(o.right);break;case"unaryOp":s(o.operand);break;case"methodCall":s(o.object),o.args.forEach(s);break;case"memberAccess":s(o.object);break;case"bracketAccess":s(o.object),s(o.index);break;case"ternary":s(o.condition),s(o.consequent),s(o.alternate);break;case"inExpr":s(o.element),s(o.collection);break;case"isExpr":s(o.value);break;case"listLiteral":o.elements.forEach(s);break;case"mapLiteral":o.entries.forEach(c=>{s(c.key),s(c.value)});break}};return s(t),r}function gR(t,e){const n=new Map,r=s=>{switch(s.type){case"functionCall":e.has(s.name)&&n.set(s.name,(n.get(s.name)??0)+1),s.args.forEach(r);break;case"binaryOp":r(s.left),r(s.right);break;case"unaryOp":r(s.operand);break;case"methodCall":r(s.object),s.args.forEach(r);break;case"memberAccess":r(s.object);break;case"bracketAccess":r(s.object),r(s.index);break;case"ternary":r(s.condition),r(s.consequent),r(s.alternate);break;case"inExpr":r(s.element),r(s.collection);break;case"isExpr":r(s.value);break;case"listLiteral":s.elements.forEach(r);break;case"mapLiteral":s.entries.forEach(o=>{r(o.key),r(o.value)});break}};return r(t),n}function Q1(t,e,n=new Set){if(n.has(t))return!1;n.add(t);const r=e.get(t);if(!r)return!1;const s=o=>{switch(o.type){case"functionCall":return o.name==="get"||o.name==="exists"?!0:e.has(o.name)?Q1(o.name,e,n):o.args.some(s);case"binaryOp":return s(o.left)||s(o.right);case"unaryOp":return s(o.operand);case"methodCall":return s(o.object)||o.args.some(s);case"memberAccess":return s(o.object);case"bracketAccess":return s(o.object)||s(o.index);case"ternary":return s(o.condition)||s(o.consequent)||s(o.alternate);case"inExpr":return s(o.element)||s(o.collection);case"isExpr":return s(o.value);case"listLiteral":return o.elements.some(s);case"mapLiteral":return o.entries.some(c=>s(c.key)||s(c.value));default:return!1}};return s(r.body)||r.lets.some(o=>s(o.value))}function Sm(t,e,n=new Set){const r=s=>{switch(s.type){case"memberAccess":return s.property==="time"&&s.object.type==="identifier"&&s.object.name==="request"?!0:r(s.object);case"bracketAccess":return s.object.type==="identifier"&&s.object.name==="request"&&s.index.type==="literal"&&s.index.value==="time"?!0:r(s.object)||r(s.index);case"functionCall":if(e.has(s.name)&&!n.has(s.name)){n.add(s.name);const o=e.get(s.name);if(Sm(o.body,e,n)||o.lets.some(c=>Sm(c.value,e,n)))return!0}return s.args.some(r);case"binaryOp":return r(s.left)||r(s.right);case"unaryOp":return r(s.operand);case"methodCall":return r(s.object)||s.args.some(r);case"ternary":return r(s.condition)||r(s.consequent)||r(s.alternate);case"inExpr":return r(s.element)||r(s.collection);case"isExpr":return r(s.value);case"listLiteral":return s.elements.some(r);case"mapLiteral":return s.entries.some(o=>r(o.key)||r(o.value));default:return!1}};return r(t)}function J1(t){const e=[...t.functions];for(const n of t.children)e.push(...J1(n));return e}function X1(t){const e=[];for(const n of t.allows)e.push({rule:n,path:t.path.raw,matchFunctions:t.functions});for(const n of t.children){const r=X1(n);for(const s of r)s.matchFunctions=[...t.functions,...s.matchFunctions];e.push(...r)}return e}const Dp={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()`"},Qr={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`"},bR=[{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"}],vR=new Set(["size","keys","values","lower","upper","trim","hasAll","hasAny","hasOnly","toSet","toUtf8"]),wR=[{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 xR(t){const e=[],n=t.replace(/\/\/[^\n]*/g,"").replace(/\/\*[\s\S]*?\*\//g,"");for(const r of wR)r.pattern.test(n)&&e.push({rule:"INVALID_OPERATOR",severity:"error",message:r.message});return e}function eE(t,e){const n=t.path.raw;for(const r of t.functions){const s={matchPath:n,functionName:r.name};St(r.body,s,e);for(const o of r.lets)St(o.value,s,e)}for(let r=0;r<t.allows.length;r++)St(t.allows[r].condition,{matchPath:n,ruleIndex:r},e);for(const r of t.children)eE(r,e)}function St(t,e,n){switch(n(t,e),t.type){case"binaryOp":St(t.left,e,n),St(t.right,e,n);break;case"unaryOp":St(t.operand,e,n);break;case"methodCall":St(t.object,e,n),t.args.forEach(r=>St(r,e,n));break;case"memberAccess":St(t.object,e,n);break;case"bracketAccess":St(t.object,e,n),St(t.index,e,n);break;case"ternary":St(t.condition,e,n),St(t.consequent,e,n),St(t.alternate,e,n);break;case"inExpr":St(t.element,e,n),St(t.collection,e,n);break;case"isExpr":St(t.value,e,n);break;case"listLiteral":t.elements.forEach(r=>St(r,e,n));break;case"mapLiteral":t.entries.forEach(r=>{St(r.key,e,n),St(r.value,e,n)});break;case"functionCall":t.args.forEach(r=>St(r,e,n));break}}function SR(t){const e=[],n=new Set;function r(s,o,c,d){const f=`${s}|${o}|${c.matchPath||""}|${c.functionName||""}|${c.ruleIndex??""}`;n.has(f)||(n.add(f),e.push(d))}return eE(t.service.match,(s,o)=>{if(s.type==="methodCall"&&Dp[s.method]&&r("HALLUCINATED_METHOD",s.method,o,{rule:"HALLUCINATED_METHOD",severity:"error",message:`\`.${s.method}()\` does not exist in Firestore rules. ${Dp[s.method]}`,location:o,fix:Dp[s.method]}),s.type==="methodCall"&&s.object.type==="identifier"&&Qr[s.object.name]){const c=s.object.name;r("HALLUCINATED_GLOBAL",`${c}.${s.method}`,o,{rule:"HALLUCINATED_GLOBAL",severity:"error",message:`\`${c}.${s.method}()\` does not exist in Firestore rules. ${Qr[c]}`,location:o,fix:Qr[c]})}if(s.type==="functionCall"&&Qr[s.name]&&r("HALLUCINATED_GLOBAL",s.name,o,{rule:"HALLUCINATED_GLOBAL",severity:"error",message:`\`${s.name}()\` does not exist in Firestore rules. ${Qr[s.name]}`,location:o,fix:Qr[s.name]}),s.type==="identifier"&&Qr[s.name]&&r("HALLUCINATED_GLOBAL",`ref:${s.name}`,o,{rule:"HALLUCINATED_GLOBAL",severity:"error",message:`\`${s.name}\` is not a Firestore rules identifier. ${Qr[s.name]}`,location:o,fix:Qr[s.name]}),s.type==="memberAccess"&&s.object.type==="identifier"){const c=s.object.name,d=s.property,f=bR.find(p=>p.receiver===c&&p.property===d);f&&r("WRONG_CONTEXT_PATH",`${c}.${d}`,o,{rule:"WRONG_CONTEXT_PATH",severity:"error",message:`\`${c}.${d}\` is not a valid Firestore rules path. ${f.suggestion}`,location:o,fix:f.suggestion})}if(s.type==="memberAccess"&&s.property==="length"&&s.object.type==="methodCall"&&r("LENGTH_PROPERTY","",o,{rule:"LENGTH_PROPERTY",severity:"error",message:"`.length` is not a valid property in Firestore rules — use `.size()` (a method, with parentheses).",location:o,fix:"Replace `.length` with `.size()`."}),s.type==="pathLiteral")for(const c of s.segments){if(typeof c!="string")continue;const d=c.match(/^\{([A-Za-z_][A-Za-z0-9_]*)\}$/);if(!d)continue;const f=d[1];r("INVALID_PATH_INTERPOLATION",`${s.raw}|${f}`,o,{rule:"INVALID_PATH_INTERPOLATION",severity:"error",message:`\`{${f}}\` is not valid inside a path literal — Firestore rejects this at deploy. The \`{var}\` syntax is for match statement wildcards (e.g. \`match /users/{userId}\`); path interpolation in get()/exists()/getAfter()/existsAfter() requires \`$(var)\`. Replace \`{${f}}\` with \`$(${f})\` in path \`${s.raw}\`.`,location:o,fix:`Replace \`{${f}}\` with \`$(${f})\` inside the path argument.`})}s.type==="memberAccess"&&vR.has(s.property)&&(s.object.type==="identifier"&&(s.object.name==="request"||s.object.name==="resource")||s.object.type==="memberAccess"||s.object.type==="methodCall"||s.object.type==="bracketAccess")&&r("METHOD_MISSING_PARENS",s.property,o,{rule:"METHOD_MISSING_PARENS",severity:"warning",message:`\`.${s.property}\` looks like a built-in method called without parentheses. Use \`.${s.property}()\` if you meant to invoke it (otherwise this is a field access).`,location:o,fix:`Add parentheses: \`.${s.property}()\`.`})}),e}const Nt={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 _R(t,e){t.length>Nt.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 ER(t,e){for(const n of t)n.lets.length>Nt.LET_LIMIT&&e.push({rule:"LET_LIMIT",severity:"error",message:`Function '${n.name}' has ${n.lets.length} let bindings. Limit is ${Nt.LET_LIMIT}.`,location:{functionName:n.name},fix:"Inline some let expressions into the return statement, or split the function."})}function AR(t,e){for(const n of t){const r=xm(n.body);for(const s of n.lets){const o=xm(s.value);o.depth>r.depth&&(r.depth=o.depth,r.op=o.op)}r.depth>=Nt.CHAIN_DEPTH_LIMIT?e.push({rule:"CHAIN_DEPTH",severity:"error",message:`Function '${n.name}' has a ${r.op} chain of depth ${r.depth}. Limit is ${Nt.CHAIN_DEPTH_LIMIT}.`,location:{functionName:n.name},fix:"Split into nested groups: 'a && b && c && d' → '(a && b) && (c && d)' to halve chain depth."}):r.depth>=Nt.CHAIN_DEPTH_ERROR?e.push({rule:"CHAIN_DEPTH",severity:"error",message:`Function '${n.name}' has a ${r.op} chain of depth ${r.depth}. Limit is ${Nt.CHAIN_DEPTH_LIMIT}. Approaching failure.`,location:{functionName:n.name},fix:"Split the chain into nested groups to reduce depth."}):r.depth>=Nt.CHAIN_DEPTH_WARN&&e.push({rule:"CHAIN_DEPTH",severity:"warning",message:`Function '${n.name}' has a ${r.op} chain of depth ${r.depth}. Limit is ${Nt.CHAIN_DEPTH_LIMIT}.`,location:{functionName:n.name}})}}function jR(t,e){const n=new Map;for(let r=0;r<t.length;r++){const s=t[r];if(!s.rule.operations.some(d=>d==="update"||d==="write"))continue;const o=ht(Y1(s.rule.condition)),c=s.path;n.has(c)||n.set(c,[]),n.get(c).push({index:r,gate:o,ops:s.rule.operations})}for(const[r,s]of n){const o=new Map;for(const c of s)o.has(c.gate)||o.set(c.gate,[]),o.get(c.gate).push(c.index);for(const[c,d]of o)d.length>=2&&e.push({rule:"SHARED_GATE",severity:"warning",message:`${d.length} allow rules in '${r}' share the same gate expression. This may cause cross-rule budget exhaustion. Rules: ${d.join(", ")}.`,location:{matchPath:r},fix:"Assign unique moveType or discriminator values so each rule has a unique first expression."})}}function kR(t,e){let n=pt(t);const r=new Set;function s(o){if(o.type==="functionCall"&&e.has(o.name)&&!r.has(o.name)){r.add(o.name);const c=e.get(o.name);n+=pt(c.body);for(const d of c.lets)n+=pt(d.value);s(c.body);for(const d of c.lets)s(d.value)}switch(o.type){case"binaryOp":s(o.left),s(o.right);break;case"unaryOp":s(o.operand);break;case"methodCall":s(o.object),o.args.forEach(s);break;case"memberAccess":s(o.object);break;case"bracketAccess":s(o.object),s(o.index);break;case"ternary":s(o.condition),s(o.consequent),s(o.alternate);break;case"inExpr":s(o.element),s(o.collection);break;case"isExpr":s(o.value);break;case"listLiteral":o.elements.forEach(s);break;case"mapLiteral":o.entries.forEach(c=>{s(c.key),s(c.value)});break;case"functionCall":o.args.forEach(s);break}}return s(t),{totalExprs:n,callCount:r.size}}function CR(t,e,n){const r=new Map;for(const s of e)r.set(s.name,s);for(let s=0;s<t.length;s++){const{totalExprs:o,callCount:c}=kR(t[s].rule.condition,r),d=Gu(t[s].rule.condition,"||"),f=d>5?.3:d>2?.5:1,p=Math.round(o*f),g=c<=Nt.RUNTIME_BUDGET.low.calls?Nt.RUNTIME_BUDGET.low:c<=Nt.RUNTIME_BUDGET.mid.calls?Nt.RUNTIME_BUDGET.mid:Nt.RUNTIME_BUDGET.high;p>=g.warn&&n.push({rule:"EXPRESSION_BUDGET",severity:"warning",message:`Rule #${s} has ~${o} expression nodes across ${c} function calls. Runtime budget is non-deterministic; actual evaluation depends on short-circuit behavior.`,location:{ruleIndex:s},fix:"If this rule fails at runtime (403), reduce function calls or expression count."})}}function NR(t,e,n){const r=Z1(e),s=new Map;for(const o of e)s.set(o.name,o);for(let o=0;o<t.length;o++){let c=0;const d=f=>{if(f.type==="functionCall"&&s.has(f.name)){const p=Wy(f.name,r);p>c&&(c=p)}switch(f.type){case"binaryOp":d(f.left),d(f.right);break;case"unaryOp":d(f.operand);break;case"methodCall":d(f.object),f.args.forEach(d);break;case"memberAccess":d(f.object);break;case"bracketAccess":d(f.object),d(f.index);break;case"ternary":d(f.condition),d(f.consequent),d(f.alternate);break;case"inExpr":d(f.element),d(f.collection);break;case"functionCall":f.args.forEach(d);break}};d(t[o].rule.condition),c>=Nt.CALL_DEPTH_ERROR?n.push({rule:"CALL_DEPTH",severity:"error",message:`Rule #${o} has a function call chain of depth ${c}. May exceed call budget.`,location:{ruleIndex:o},fix:"Inline intermediate functions to reduce call depth."}):c>=Nt.CALL_DEPTH_WARN&&n.push({rule:"CALL_DEPTH",severity:"warning",message:`Rule #${o} has a function call chain of depth ${c}.`,location:{ruleIndex:o}})}}function OR(t,e,n){const r=new Map;for(const s of e)r.set(s.name,s);for(let s=0;s<t.length;s++){const o=W1(t[s].rule.condition,r);o>=Nt.GET_COUNT_ERROR?n.push({rule:"GET_COUNT",severity:"error",message:`Rule #${s} may invoke ${o} get()/exists() calls. Limit is ${Nt.GET_COUNT_ERROR}.`,location:{ruleIndex:s},fix:"Cache get() results via a config() wrapper function. Same-path calls are cached by Firestore."}):o>=Nt.GET_COUNT_WARN&&n.push({rule:"GET_COUNT",severity:"warning",message:`Rule #${s} invokes ${o} get()/exists() calls. Limit is ${Nt.GET_COUNT_ERROR}.`,location:{ruleIndex:s}})}}function RR(t,e,n){const r=new Map;for(const o of e)r.set(o.name,o);const s=new Set(e.map(o=>o.name));for(let o=0;o<t.length;o++){const c=gR(t[o].rule.condition,s);for(const[d,f]of c)f>=2&&Q1(d,r)&&n.push({rule:"GET_DUPLICATION",severity:"warning",message:`Function '${d}' (contains get/exists) is called ${f} times in rule #${o}. Cache the result with a let binding in a wrapper function to reduce get() calls from ${f} to 1.`,location:{ruleIndex:o},fix:`Create a wrapper: function verifyAll(ret) { let c = ${d}(); return verify1(ret, c) && verify2(ret, c) && ...; }`})}}function TR(t,e,n,r){const s=new Map;for(const d of e)s.set(d.name,d);const o=new Set;for(let d=0;d<t.length;d++)Sm(t[d].rule.condition,s)&&o.add(d);if(o.size===0)return;function c(d,f){const p=d.split("/").filter(Boolean),g=f.split("/").filter(Boolean);if(p.length!==g.length)return!1;for(let b=0;b<p.length;b++){const v=p[b];if(!(v.startsWith("{")&&v.endsWith("}"))&&v!==g[b])return!1}return!0}for(const d of n)if(!d.requestTime)for(const f of o)c(t[f].path,d.path)&&r.push({rule:"REQUEST_TIME_NOT_PINNED",severity:"warning",message:`Test case "${d.description}" targets rule #${f} (path '${t[f].path}') which reads request.time, but does not set requestTime. Result is non-deterministic across runs.`,location:{ruleIndex:f,matchPath:t[f].path,testCaseDescription:d.description},fix:"Set requestTime on this TestCase to an ISO-8601 timestamp so the rule evaluates deterministically."})}function _l(t){if(t.type==="literal"&&typeof t.value=="boolean")return t.value;if(t.type==="binaryOp"){const e=_l(t.left),n=_l(t.right);if(t.op==="&&")return e===!1||n===!1?!1:e===!0&&n===!0?!0:null;if(t.op==="||")return e===!0||n===!0?!0:e===!1&&n===!1?!1:null}if(t.type==="unaryOp"&&t.op==="!"){const e=_l(t.operand);return e===null?null:!e}return null}const DR=new Set(["write","create","update","delete"]);function IR(t,e){for(let n=0;n<t.length;n++){const r=t[n];if(_l(r.rule.condition)!==!0||!r.rule.operations.some(c=>DR.has(c)))continue;const o=r.rule.operations.join(", ");e.push({rule:"PERMISSIVE_RULE",severity:"warning",message:`allow ${o} at ${r.path} resolves to a constant true predicate — this disables write security for the matched paths. If you reached for \`if true\` to escape a denial you don't understand, narrow the predicate to the specific request shape instead (auth identity, affected fields via diff, status transitions).`,location:{ruleIndex:n,matchPath:r.path},fix:"Replace the always-true predicate with a request-shape check (e.g. request.auth != null && request.resource.data.ownerId == request.auth.uid)."})}}function tE(t,e){if(t.path.segments.some(r=>r.type==="recursive"))for(let r=0;r<t.allows.length;r++)_l(t.allows[r].condition)===!0&&e.push({rule:"RECURSIVE_WILDCARD_OPEN",severity:"error",message:`Recursive wildcard match (${t.path.raw}) with an always-true predicate exposes every document under this prefix. This is the Firebase open-rules anti-pattern — never ship it.`,location:{ruleIndex:r,matchPath:t.path.raw},fix:"Either narrow the match path to specific collections, or replace `if true` with a real predicate (auth identity, ownership, role)."});for(const r of t.children)tE(r,e)}function MR(t){return t.type==="literal"?t.value??"":t.type==="wildcard"?"{*}":t.type==="recursive"?"{**}":""}function LR(t){return t.map(MR).join("/")}function _m(t,e){const n=LR(t.path.segments),r=e?`${e}/${n}`:n,s=[{block:t,normalizedPath:r}];for(const o of t.children)s.push(..._m(o,r));return s}function ct(t){switch(t.type){case"literal":return t.raw;case"identifier":return t.name;case"memberAccess":return`${ct(t.object)}.${t.property}`;case"methodCall":return`${ct(t.object)}.${t.method}(${t.args.map(ct).join(",")})`;case"bracketAccess":return`${ct(t.object)}[${ct(t.index)}]`;case"sliceAccess":return`${ct(t.object)}[${ct(t.start)}:${ct(t.end)}]`;case"binaryOp":return`(${ct(t.left)}${t.op}${ct(t.right)})`;case"unaryOp":return`(${t.op}${ct(t.operand)})`;case"ternary":return`(${ct(t.condition)}?${ct(t.consequent)}:${ct(t.alternate)})`;case"inExpr":return`(${ct(t.element)} in ${ct(t.collection)})`;case"isExpr":return`(${ct(t.value)} is ${t.typeName})`;case"listLiteral":return`[${t.elements.map(ct).join(",")}]`;case"mapLiteral":return`{${t.entries.map(e=>`${ct(e.key)}:${ct(e.value)}`).join(",")}}`;case"pathLiteral":return t.raw;case"functionCall":return`${t.name}(${t.args.map(ct).join(",")})`}}function Ku(t){return t.type==="binaryOp"&&t.op==="&&"?[...Ku(t.left),...Ku(t.right)]:[t]}function UR(t,e,n){const r=_m(t,""),s=_m(e,""),o=new Map;for(const{block:c,normalizedPath:d}of r)o.has(d)||o.set(d,c);for(const{block:c,normalizedPath:d}of s){const f=o.get(d);if(!f){c.allows.length>0&&n.push({rule:"RULES_WEAKENED",severity:"warning",message:`Match block removed: ${d}`,location:{matchPath:d}});continue}for(const p of c.allows){const g=[...p.operations].sort().join(","),b=f.allows.find(k=>[...k.operations].sort().join(",")===g),v=p.operations.join(", ");if(!b){n.push({rule:"RULES_WEAKENED",severity:"warning",message:`Allow rule removed: ${d} allow ${v}`,location:{matchPath:d}});continue}const w=Ku(p.condition).map(ct),_=new Set(Ku(b.condition).map(ct));for(const k of w)_.has(k)||n.push({rule:"RULES_WEAKENED",severity:"warning",message:`Predicate removed from ${d} allow ${v}: ${k}`,location:{matchPath:d}})}}}function Yu(t,e={}){const n=[];n.push(...xR(t)),_R(t,n);const r=Tl(t);if(!r.ok)return{warnings:n,metrics:{sourceSize:t.length,functionCount:0,allowRuleCount:0,maxChainDepth:0,maxChainOp:"",maxLetBindings:0,maxLetBindingsFunction:"",maxCallDepth:0,maxEstimatedExpressions:0,getCallCount:0},parseError:r.error};const s=r.ast,o=J1(s.service.match),c=X1(s.service.match);if(AR(o,n),ER(o,n),jR(c,n),CR(c,o,n),NR(c,o,n),OR(c,o,n),RR(c,o,n),n.push(...SR(s)),IR(c,n),tE(s.service.match,n),e.testCases&&e.testCases.length>0&&TR(c,o,e.testCases,n),e.previousSource){const _=Tl(e.previousSource);_.ok&&UR(s.service.match,_.ast.service.match,n)}let d={depth:0,op:""},f={count:0,fn:""};for(const _ of o){const k=xm(_.body);k.depth>d.depth&&(d={depth:k.depth,op:k.op}),_.lets.length>f.count&&(f={count:_.lets.length,fn:_.name})}const p=Z1(o);let g=0;for(const _ of o){const k=Wy(_.name,p);k>g&&(g=k)}const b=new Map;for(const _ of o)b.set(_.name,_);let v=0,w=0;for(const _ of c){const k=W1(_.rule.condition,b);k>w&&(w=k)}return{warnings:n,metrics:{sourceSize:t.length,functionCount:o.length,allowRuleCount:c.length,maxChainDepth:d.depth,maxChainOp:d.op,maxLetBindings:f.count,maxLetBindingsFunction:f.fn,maxCallDepth:g,maxEstimatedExpressions:v,getCallCount:w}}}class lt{constructor(e){G(this,"items");this.items=new Set(e)}hasOnly(e){const n=e instanceof lt?e.toArray():e;for(const r of this.items)if(!n.includes(r))return!1;return!0}equals(e){if(!(e instanceof lt)||e.items.size!==this.items.size)return!1;for(const n of this.items)if(!e.items.has(n))return!1;return!0}hasAll(e){const n=e instanceof lt?e.toArray():e;for(const r of n)if(!this.items.has(r))return!1;return!0}hasAny(e){const n=e instanceof lt?e.toArray():e;for(const r of n)if(this.items.has(r))return!0;return!1}size(){return this.items.size}toArray(){return[...this.items]}difference(e){const n=new Set(e instanceof lt?e.toArray():e),r=[];for(const s of this.items)n.has(s)||r.push(s);return new lt(r)}union(e){const n=e instanceof lt?e.toArray():e,r=new Set(this.items);for(const s of n)r.add(s);return new lt(r)}intersection(e){const n=new Set(e instanceof lt?e.toArray():e),r=[];for(const s of this.items)n.has(s)&&r.push(s);return new lt(r)}}const gt=Symbol.for("pyric.RulesValue.NO_OP");class tt{field(e){return null}callMethod(e,n){return gt}binaryOp(e,n){return gt}}function Wn(t,e){if(Object.is(t,e))return!0;if(t instanceof tt)return t.equals(e);if(e instanceof tt)return e.equals(t);if(t instanceof lt||e instanceof lt)return t instanceof lt&&t.equals(e);if(Array.isArray(t)||Array.isArray(e))return!Array.isArray(t)||!Array.isArray(e)||t.length!==e.length?!1:t.every((s,o)=>Wn(s,e[o]));if(!yx(t)||!yx(e))return!1;const n=Object.keys(t),r=Object.keys(e);return n.length!==r.length?!1:n.every(s=>s in e&&Wn(t[s],e[s]))}function yx(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}class El{constructor(e,n){G(this,"before");G(this,"after");this.before=e,this.after=n}addedKeys(){const e=[];for(const n of Object.keys(this.after))n in this.before||e.push(n);return new lt(e)}removedKeys(){const e=[];for(const n of Object.keys(this.before))n in this.after||e.push(n);return new lt(e)}changedKeys(){const e=[];for(const n of Object.keys(this.after))n in this.before&&!Wn(this.before[n],this.after[n])&&e.push(n);return new lt(e)}affectedKeys(){const e=[],n=new Set([...Object.keys(this.before),...Object.keys(this.after)]);for(const r of n)(!(r in this.before)||!(r in this.after)||!Wn(this.before[r],this.after[r]))&&e.push(r);return new lt(e)}unchangedKeys(){const e=[];for(const n of Object.keys(this.before))n in this.after&&Wn(this.before[n],this.after[n])&&e.push(n);return new lt(e)}}function $R(t,e,n,r){const o=v=>v*Math.PI/180,c=o(t),d=o(n),f=o(n-t),p=o(r-e),g=Math.sin(f/2)**2+Math.cos(c)*Math.cos(d)*Math.sin(p/2)**2;return 6371e3*(2*Math.atan2(Math.sqrt(g),Math.sqrt(1-g)))}class Cr extends tt{constructor(n,r){super();G(this,"typeName","latlng");G(this,"lat");G(this,"lng");this.lat=n,this.lng=r}valueOf(){return NaN}toString(){return`${this.lat},${this.lng}`}toJSON(){return{__type:"latlng",lat:this.lat,lng:this.lng}}equals(n){return n instanceof Cr&&this.lat===n.lat&&this.lng===n.lng}callMethod(n,r){switch(n){case"latitude":return this.lat;case"longitude":return this.lng;case"distance":{const s=r[0];if(!(s instanceof Cr))throw new TypeError(`latlng.distance() requires a LatLng argument, got ${typeof s}`);return $R(this.lat,this.lng,s.lat,s.lng)}default:return gt}}}const Ka=1e9,gx={w:10080*60,d:1440*60,h:3600,m:60,s:1};function BR(t,e){let n=t+Math.trunc(e/Ka),r=e%Ka;return n>0&&r<0?(n-=1,r+=Ka):n<0&&r>0&&(n+=1,r-=Ka),{seconds:n,nanos:r}}class Mt extends tt{constructor(n,r){super();G(this,"typeName","duration");G(this,"seconds");G(this,"nanos");const s=BR(n,r);this.seconds=s.seconds,this.nanos=s.nanos}static fromValue(n,r){if(r in gx)return new Mt(n*gx[r],0);if(r==="ms"){const s=Math.trunc(n/1e3),o=n-s*1e3;return new Mt(s,o*1e6)}if(r==="ns"){const s=Math.trunc(n/Ka),o=n-s*Ka;return new Mt(s,o)}throw new Error(`Unknown duration unit '${r}' (expected one of: w, d, h, m, s, ms, ns)`)}static fromTime(n,r,s,o){return new Mt(n*3600+r*60+s,o)}static abs(n){return new Mt(Math.abs(n.seconds),Math.abs(n.nanos))}valueOf(){return this.seconds*1e3+Math.round(this.nanos/1e6)}toString(){const n=this.seconds<0||this.nanos<0,r=Math.abs(this.seconds),s=Math.abs(this.nanos);return`${n?"-":""}${r}.${s.toString().padStart(9,"0")}s`}toJSON(){return{__type:"duration",seconds:this.seconds,nanos:this.nanos}}equals(n){return n instanceof Mt&&this.seconds===n.seconds&&this.nanos===n.nanos}callMethod(n,r){switch(n){case"seconds":return this.seconds;case"nanos":return this.nanos;default:return gt}}binaryOp(n,r){if(!(r instanceof Mt))return gt;switch(n){case"+":return new Mt(this.seconds+r.seconds,this.nanos+r.nanos);case"-":return new Mt(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 gt}}compareTo(n){return this.seconds!==n.seconds?this.seconds-n.seconds:this.nanos-n.nanos}}const bx=1e9,qR=864e5,Ip=86400;function FR(t,e){const n=Math.floor(e/bx);return{seconds:t+n,nanos:e-n*bx}}let Rt=class Xr extends tt{constructor(n,r){super();G(this,"typeName","timestamp");G(this,"seconds");G(this,"nanos");const s=FR(n,r);this.seconds=s.seconds,this.nanos=s.nanos}static fromMillis(n){const r=Math.floor(n/1e3),s=n-r*1e3;return new Xr(r,s*1e6)}static fromYMD(n,r,s){return Xr.fromMillis(Date.UTC(n,r-1,s))}static fromIsoString(n){return Xr.fromMillis(Date.parse(n))}toMillis(){return this.seconds*1e3+Math.floor(this.nanos/1e6)}toDate(){return new Date(this.toMillis())}valueOf(){return this.toMillis()}toString(){const n=new Date(this.toMillis()).toISOString(),r=this.nanos.toString().padStart(9,"0");return n.replace(/\.\d{3}Z$/,`.${r}Z`)}toJSON(){return{__type:"timestamp",seconds:this.seconds,nanos:this.nanos}}equals(n){return n instanceof Xr&&this.seconds===n.seconds&&this.nanos===n.nanos}callMethod(n,r){switch(n){case"seconds":return this.seconds;case"nanos":return this.nanos;case"toMillis":return this.toMillis();case"year":return this.asDate().getUTCFullYear();case"month":return this.asDate().getUTCMonth()+1;case"day":return this.asDate().getUTCDate();case"hours":return this.asDate().getUTCHours();case"minutes":return this.asDate().getUTCMinutes();case"dayOfWeek":{const s=this.asDate().getUTCDay();return s===0?7:s}case"dayOfYear":{const s=this.asDate(),o=Date.UTC(s.getUTCFullYear(),0,1);return Math.floor((this.toMillis()-o)/qR)+1}case"date":return Xr.fromYMD(this.asDate().getUTCFullYear(),this.asDate().getUTCMonth()+1,this.asDate().getUTCDate());case"time":{const s=(this.seconds%Ip+Ip)%Ip,o=Math.floor(s/3600),c=Math.floor(s%3600/60),d=s%60;return Mt.fromTime(o,c,d,this.nanos)}default:return gt}}asDate(){return new Date(this.toMillis())}binaryOp(n,r){if(r instanceof Xr)switch(n){case"-":return new Mt(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 gt}if(r instanceof Mt)switch(n){case"+":return new Xr(this.seconds+r.seconds,this.nanos+r.nanos);case"-":return new Xr(this.seconds-r.seconds,this.nanos-r.nanos);default:return gt}return gt}compareTo(n){return this.seconds!==n.seconds?this.seconds-n.seconds:this.nanos-n.nanos}};const vx="0123456789abcdef";function zR(t){let e="";for(let n=0;n<t.length;n++){const r=t[n];e+=vx[r>>>4]+vx[r&15]}return e}function PR(t){let e="";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function VR(t,e){const n=Math.min(t.length,e.length);for(let r=0;r<n;r++)if(t[r]!==e[r])return t[r]<e[r]?-1:1;return t.length===e.length?0:t.length<e.length?-1:1}let In=class xl extends tt{constructor(n){super();G(this,"typeName","bytes");G(this,"data");this.data=n}static fromUtf8(n){return new xl(new TextEncoder().encode(n))}static fromHex(n){if(n.length%2!==0)throw new Error(`Invalid hex string length: ${n.length}`);const r=new Uint8Array(n.length/2);for(let s=0;s<r.length;s++)r[s]=parseInt(n.substr(s*2,2),16);return new xl(r)}size(){return this.data.length}toBase64(){return PR(this.data)}toHexString(){return zR(this.data)}valueOf(){return this.data.length}toString(){return this.toBase64()}toJSON(){return{__type:"bytes",base64:this.toBase64()}}equals(n){if(!(n instanceof xl)||this.data.length!==n.data.length)return!1;for(let r=0;r<this.data.length;r++)if(this.data[r]!==n.data[r])return!1;return!0}callMethod(n,r){switch(n){case"size":return this.size();case"toBase64":return this.toBase64();case"toHexString":return this.toHexString()}return gt}binaryOp(n,r){if(!(r instanceof xl))return gt;const s=VR(this.data,r.data);switch(n){case"<":return s<0;case"<=":return s<=0;case">":return s>0;case">=":return s>=0}return gt}};const HR=/^\{([A-Za-z_][A-Za-z0-9_]*)\}$/;class dr extends tt{constructor(n,r={}){super();G(this,"typeName","path");G(this,"segments");G(this,"bindings");this.segments=n,this.bindings=r}static fromString(n){const r=n.startsWith("/")?n.slice(1):n;return r.length===0?new dr([]):new dr(r.split("/"))}bind(n){const r=[],s={...this.bindings};for(const o of this.segments){const c=o.match(HR);if(!c){r.push(o);continue}const d=c[1];if(d in n){const f=n[d];if(f==null)throw new TypeError(`Path.bind(): binding '${d}' must not be null`);const p=String(f);r.push(p),s[d]=p}else r.push(o)}return new dr(r,s)}valueOf(){return NaN}toString(){return"/"+this.segments.join("/")}toJSON(){return{__type:"path",segments:[...this.segments]}}equals(n){if(!(n instanceof dr)||this.segments.length!==n.segments.length)return!1;for(let r=0;r<this.segments.length;r++)if(this.segments[r]!==n.segments[r])return!1;return!0}field(n){if(/^\d+$/.test(n)){const r=Number(n);return r<0||r>=this.segments.length?null:this.segments[r]}return n in this.bindings?this.bindings[n]:null}callMethod(n,r){switch(n){case"bind":{const s=r[0];if(s==null||typeof s!="object"||Array.isArray(s)||s instanceof tt)throw new TypeError(`Path.bind() requires a Map argument, got ${s===null?"null":typeof s}`);return this.bind(s)}default:return gt}}}class Ke extends tt{constructor(n){super();G(this,"typeName","float");G(this,"value");this.value=n}valueOf(){return this.value}toString(){return Number.isInteger(this.value)?`${this.value}.0`:String(this.value)}toJSON(){return{__type:"float",value:this.value}}equals(n){return n instanceof Ke?this.value===n.value:typeof n=="number"?this.value===n:!1}binaryOp(n,r){const s=r instanceof Ke?r.value:typeof r=="number"?r:void 0;if(s===void 0)return gt;const o=this.value;switch(n){case"+":return new Ke(o+s);case"-":return new Ke(o-s);case"*":return new Ke(o*s);case"/":return new Ke(o/s);case"%":return new Ke(o%s);case"<":return o<s;case"<=":return o<=s;case">":return o>s;case">=":return o>=s;default:return gt}}}var Mp={exports:{}};const GR={},KR=Object.freeze(Object.defineProperty({__proto__:null,default:GR},Symbol.toStringTag,{value:"Module"})),Zu=XN(KR);/**
520
- * [js-md5]{@link https://github.com/emn178/js-md5}
521
- *
522
- * @namespace md5
523
- * @version 0.8.3
524
- * @author Chen, Yi-Cyuan [emn178@gmail.com]
525
- * @copyright Chen, Yi-Cyuan 2014-2023
526
- * @license MIT
527
- */var wx;function YR(){return wx||(wx=1,(function(t){(function(){var e="input is invalid type",n="finalize already called",r=typeof window=="object",s=r?window:{};s.JS_MD5_NO_WINDOW&&(r=!1);var o=!r&&typeof self=="object",c=!s.JS_MD5_NO_NODE_JS&&typeof process=="object"&&process.versions&&process.versions.node;c?s=f1:o&&(s=self);var d=!s.JS_MD5_NO_COMMON_JS&&!0&&t.exports,f=!s.JS_MD5_NO_ARRAY_BUFFER&&typeof ArrayBuffer<"u",p="0123456789abcdef".split(""),g=[128,32768,8388608,-2147483648],b=[0,8,16,24],v=["hex","array","digest","buffer","arrayBuffer","base64"],w="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),_=[],k;if(f){var I=new ArrayBuffer(68);k=new Uint8Array(I),_=new Uint32Array(I)}var N=Array.isArray;(s.JS_MD5_NO_NODE_JS||!N)&&(N=function(x){return Object.prototype.toString.call(x)==="[object Array]"});var R=ArrayBuffer.isView;f&&(s.JS_MD5_NO_ARRAY_BUFFER_IS_VIEW||!R)&&(R=function(x){return typeof x=="object"&&x.buffer&&x.buffer.constructor===ArrayBuffer});var M=function(x){var E=typeof x;if(E==="string")return[x,!0];if(E!=="object"||x===null)throw new Error(e);if(f&&x.constructor===ArrayBuffer)return[new Uint8Array(x),!1];if(!N(x)&&!R(x))throw new Error(e);return[x,!1]},F=function(x){return function(E){return new H(!0).update(E)[x]()}},D=function(){var x=F("hex");c&&(x=C(x)),x.create=function(){return new H},x.update=function(T){return x.create().update(T)};for(var E=0;E<v.length;++E){var O=v[E];x[O]=F(O)}return x},C=function(x){var E=Zu,O=Zu.Buffer,T;O.from&&!s.JS_MD5_NO_BUFFER_FROM?T=O.from:T=function($){return new O($)};var P=function($){if(typeof $=="string")return E.createHash("md5").update($,"utf8").digest("hex");if($==null)throw new Error(e);return $.constructor===ArrayBuffer&&($=new Uint8Array($)),N($)||R($)||$.constructor===O?E.createHash("md5").update(T($)).digest("hex"):x($)};return P},L=function(x){return function(E,O){return new z(E,!0).update(O)[x]()}},U=function(){var x=L("hex");x.create=function(T){return new z(T)},x.update=function(T,P){return x.create(T).update(P)};for(var E=0;E<v.length;++E){var O=v[E];x[O]=L(O)}return x};function H(x){if(x)_[0]=_[16]=_[1]=_[2]=_[3]=_[4]=_[5]=_[6]=_[7]=_[8]=_[9]=_[10]=_[11]=_[12]=_[13]=_[14]=_[15]=0,this.blocks=_,this.buffer8=k;else if(f){var E=new ArrayBuffer(68);this.buffer8=new Uint8Array(E),this.blocks=new Uint32Array(E)}else this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];this.h0=this.h1=this.h2=this.h3=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0}H.prototype.update=function(x){if(this.finalized)throw new Error(n);var E=M(x);x=E[0];for(var O=E[1],T,P=0,$,K=x.length,W=this.blocks,se=this.buffer8;P<K;){if(this.hashed&&(this.hashed=!1,W[0]=W[16],W[16]=W[1]=W[2]=W[3]=W[4]=W[5]=W[6]=W[7]=W[8]=W[9]=W[10]=W[11]=W[12]=W[13]=W[14]=W[15]=0),O)if(f)for($=this.start;P<K&&$<64;++P)T=x.charCodeAt(P),T<128?se[$++]=T:T<2048?(se[$++]=192|T>>>6,se[$++]=128|T&63):T<55296||T>=57344?(se[$++]=224|T>>>12,se[$++]=128|T>>>6&63,se[$++]=128|T&63):(T=65536+((T&1023)<<10|x.charCodeAt(++P)&1023),se[$++]=240|T>>>18,se[$++]=128|T>>>12&63,se[$++]=128|T>>>6&63,se[$++]=128|T&63);else for($=this.start;P<K&&$<64;++P)T=x.charCodeAt(P),T<128?W[$>>>2]|=T<<b[$++&3]:T<2048?(W[$>>>2]|=(192|T>>>6)<<b[$++&3],W[$>>>2]|=(128|T&63)<<b[$++&3]):T<55296||T>=57344?(W[$>>>2]|=(224|T>>>12)<<b[$++&3],W[$>>>2]|=(128|T>>>6&63)<<b[$++&3],W[$>>>2]|=(128|T&63)<<b[$++&3]):(T=65536+((T&1023)<<10|x.charCodeAt(++P)&1023),W[$>>>2]|=(240|T>>>18)<<b[$++&3],W[$>>>2]|=(128|T>>>12&63)<<b[$++&3],W[$>>>2]|=(128|T>>>6&63)<<b[$++&3],W[$>>>2]|=(128|T&63)<<b[$++&3]);else if(f)for($=this.start;P<K&&$<64;++P)se[$++]=x[P];else for($=this.start;P<K&&$<64;++P)W[$>>>2]|=x[P]<<b[$++&3];this.lastByteIndex=$,this.bytes+=$-this.start,$>=64?(this.start=$-64,this.hash(),this.hashed=!0):this.start=$}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this},H.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var x=this.blocks,E=this.lastByteIndex;x[E>>>2]|=g[E&3],E>=56&&(this.hashed||this.hash(),x[0]=x[16],x[16]=x[1]=x[2]=x[3]=x[4]=x[5]=x[6]=x[7]=x[8]=x[9]=x[10]=x[11]=x[12]=x[13]=x[14]=x[15]=0),x[14]=this.bytes<<3,x[15]=this.hBytes<<3|this.bytes>>>29,this.hash()}},H.prototype.hash=function(){var x,E,O,T,P,$,K=this.blocks;this.first?(x=K[0]-680876937,x=(x<<7|x>>>25)-271733879<<0,T=(-1732584194^x&2004318071)+K[1]-117830708,T=(T<<12|T>>>20)+x<<0,O=(-271733879^T&(x^-271733879))+K[2]-1126478375,O=(O<<17|O>>>15)+T<<0,E=(x^O&(T^x))+K[3]-1316259209,E=(E<<22|E>>>10)+O<<0):(x=this.h0,E=this.h1,O=this.h2,T=this.h3,x+=(T^E&(O^T))+K[0]-680876936,x=(x<<7|x>>>25)+E<<0,T+=(O^x&(E^O))+K[1]-389564586,T=(T<<12|T>>>20)+x<<0,O+=(E^T&(x^E))+K[2]+606105819,O=(O<<17|O>>>15)+T<<0,E+=(x^O&(T^x))+K[3]-1044525330,E=(E<<22|E>>>10)+O<<0),x+=(T^E&(O^T))+K[4]-176418897,x=(x<<7|x>>>25)+E<<0,T+=(O^x&(E^O))+K[5]+1200080426,T=(T<<12|T>>>20)+x<<0,O+=(E^T&(x^E))+K[6]-1473231341,O=(O<<17|O>>>15)+T<<0,E+=(x^O&(T^x))+K[7]-45705983,E=(E<<22|E>>>10)+O<<0,x+=(T^E&(O^T))+K[8]+1770035416,x=(x<<7|x>>>25)+E<<0,T+=(O^x&(E^O))+K[9]-1958414417,T=(T<<12|T>>>20)+x<<0,O+=(E^T&(x^E))+K[10]-42063,O=(O<<17|O>>>15)+T<<0,E+=(x^O&(T^x))+K[11]-1990404162,E=(E<<22|E>>>10)+O<<0,x+=(T^E&(O^T))+K[12]+1804603682,x=(x<<7|x>>>25)+E<<0,T+=(O^x&(E^O))+K[13]-40341101,T=(T<<12|T>>>20)+x<<0,O+=(E^T&(x^E))+K[14]-1502002290,O=(O<<17|O>>>15)+T<<0,E+=(x^O&(T^x))+K[15]+1236535329,E=(E<<22|E>>>10)+O<<0,x+=(O^T&(E^O))+K[1]-165796510,x=(x<<5|x>>>27)+E<<0,T+=(E^O&(x^E))+K[6]-1069501632,T=(T<<9|T>>>23)+x<<0,O+=(x^E&(T^x))+K[11]+643717713,O=(O<<14|O>>>18)+T<<0,E+=(T^x&(O^T))+K[0]-373897302,E=(E<<20|E>>>12)+O<<0,x+=(O^T&(E^O))+K[5]-701558691,x=(x<<5|x>>>27)+E<<0,T+=(E^O&(x^E))+K[10]+38016083,T=(T<<9|T>>>23)+x<<0,O+=(x^E&(T^x))+K[15]-660478335,O=(O<<14|O>>>18)+T<<0,E+=(T^x&(O^T))+K[4]-405537848,E=(E<<20|E>>>12)+O<<0,x+=(O^T&(E^O))+K[9]+568446438,x=(x<<5|x>>>27)+E<<0,T+=(E^O&(x^E))+K[14]-1019803690,T=(T<<9|T>>>23)+x<<0,O+=(x^E&(T^x))+K[3]-187363961,O=(O<<14|O>>>18)+T<<0,E+=(T^x&(O^T))+K[8]+1163531501,E=(E<<20|E>>>12)+O<<0,x+=(O^T&(E^O))+K[13]-1444681467,x=(x<<5|x>>>27)+E<<0,T+=(E^O&(x^E))+K[2]-51403784,T=(T<<9|T>>>23)+x<<0,O+=(x^E&(T^x))+K[7]+1735328473,O=(O<<14|O>>>18)+T<<0,E+=(T^x&(O^T))+K[12]-1926607734,E=(E<<20|E>>>12)+O<<0,P=E^O,x+=(P^T)+K[5]-378558,x=(x<<4|x>>>28)+E<<0,T+=(P^x)+K[8]-2022574463,T=(T<<11|T>>>21)+x<<0,$=T^x,O+=($^E)+K[11]+1839030562,O=(O<<16|O>>>16)+T<<0,E+=($^O)+K[14]-35309556,E=(E<<23|E>>>9)+O<<0,P=E^O,x+=(P^T)+K[1]-1530992060,x=(x<<4|x>>>28)+E<<0,T+=(P^x)+K[4]+1272893353,T=(T<<11|T>>>21)+x<<0,$=T^x,O+=($^E)+K[7]-155497632,O=(O<<16|O>>>16)+T<<0,E+=($^O)+K[10]-1094730640,E=(E<<23|E>>>9)+O<<0,P=E^O,x+=(P^T)+K[13]+681279174,x=(x<<4|x>>>28)+E<<0,T+=(P^x)+K[0]-358537222,T=(T<<11|T>>>21)+x<<0,$=T^x,O+=($^E)+K[3]-722521979,O=(O<<16|O>>>16)+T<<0,E+=($^O)+K[6]+76029189,E=(E<<23|E>>>9)+O<<0,P=E^O,x+=(P^T)+K[9]-640364487,x=(x<<4|x>>>28)+E<<0,T+=(P^x)+K[12]-421815835,T=(T<<11|T>>>21)+x<<0,$=T^x,O+=($^E)+K[15]+530742520,O=(O<<16|O>>>16)+T<<0,E+=($^O)+K[2]-995338651,E=(E<<23|E>>>9)+O<<0,x+=(O^(E|~T))+K[0]-198630844,x=(x<<6|x>>>26)+E<<0,T+=(E^(x|~O))+K[7]+1126891415,T=(T<<10|T>>>22)+x<<0,O+=(x^(T|~E))+K[14]-1416354905,O=(O<<15|O>>>17)+T<<0,E+=(T^(O|~x))+K[5]-57434055,E=(E<<21|E>>>11)+O<<0,x+=(O^(E|~T))+K[12]+1700485571,x=(x<<6|x>>>26)+E<<0,T+=(E^(x|~O))+K[3]-1894986606,T=(T<<10|T>>>22)+x<<0,O+=(x^(T|~E))+K[10]-1051523,O=(O<<15|O>>>17)+T<<0,E+=(T^(O|~x))+K[1]-2054922799,E=(E<<21|E>>>11)+O<<0,x+=(O^(E|~T))+K[8]+1873313359,x=(x<<6|x>>>26)+E<<0,T+=(E^(x|~O))+K[15]-30611744,T=(T<<10|T>>>22)+x<<0,O+=(x^(T|~E))+K[6]-1560198380,O=(O<<15|O>>>17)+T<<0,E+=(T^(O|~x))+K[13]+1309151649,E=(E<<21|E>>>11)+O<<0,x+=(O^(E|~T))+K[4]-145523070,x=(x<<6|x>>>26)+E<<0,T+=(E^(x|~O))+K[11]-1120210379,T=(T<<10|T>>>22)+x<<0,O+=(x^(T|~E))+K[2]+718787259,O=(O<<15|O>>>17)+T<<0,E+=(T^(O|~x))+K[9]-343485551,E=(E<<21|E>>>11)+O<<0,this.first?(this.h0=x+1732584193<<0,this.h1=E-271733879<<0,this.h2=O-1732584194<<0,this.h3=T+271733878<<0,this.first=!1):(this.h0=this.h0+x<<0,this.h1=this.h1+E<<0,this.h2=this.h2+O<<0,this.h3=this.h3+T<<0)},H.prototype.hex=function(){this.finalize();var x=this.h0,E=this.h1,O=this.h2,T=this.h3;return p[x>>>4&15]+p[x&15]+p[x>>>12&15]+p[x>>>8&15]+p[x>>>20&15]+p[x>>>16&15]+p[x>>>28&15]+p[x>>>24&15]+p[E>>>4&15]+p[E&15]+p[E>>>12&15]+p[E>>>8&15]+p[E>>>20&15]+p[E>>>16&15]+p[E>>>28&15]+p[E>>>24&15]+p[O>>>4&15]+p[O&15]+p[O>>>12&15]+p[O>>>8&15]+p[O>>>20&15]+p[O>>>16&15]+p[O>>>28&15]+p[O>>>24&15]+p[T>>>4&15]+p[T&15]+p[T>>>12&15]+p[T>>>8&15]+p[T>>>20&15]+p[T>>>16&15]+p[T>>>28&15]+p[T>>>24&15]},H.prototype.toString=H.prototype.hex,H.prototype.digest=function(){this.finalize();var x=this.h0,E=this.h1,O=this.h2,T=this.h3;return[x&255,x>>>8&255,x>>>16&255,x>>>24&255,E&255,E>>>8&255,E>>>16&255,E>>>24&255,O&255,O>>>8&255,O>>>16&255,O>>>24&255,T&255,T>>>8&255,T>>>16&255,T>>>24&255]},H.prototype.array=H.prototype.digest,H.prototype.arrayBuffer=function(){this.finalize();var x=new ArrayBuffer(16),E=new Uint32Array(x);return E[0]=this.h0,E[1]=this.h1,E[2]=this.h2,E[3]=this.h3,x},H.prototype.buffer=H.prototype.arrayBuffer,H.prototype.base64=function(){for(var x,E,O,T="",P=this.array(),$=0;$<15;)x=P[$++],E=P[$++],O=P[$++],T+=w[x>>>2]+w[(x<<4|E>>>4)&63]+w[(E<<2|O>>>6)&63]+w[O&63];return x=P[$],T+=w[x>>>2]+w[x<<4&63]+"==",T};function z(x,E){var O,T=M(x);if(x=T[0],T[1]){var P=[],$=x.length,K=0,W;for(O=0;O<$;++O)W=x.charCodeAt(O),W<128?P[K++]=W:W<2048?(P[K++]=192|W>>>6,P[K++]=128|W&63):W<55296||W>=57344?(P[K++]=224|W>>>12,P[K++]=128|W>>>6&63,P[K++]=128|W&63):(W=65536+((W&1023)<<10|x.charCodeAt(++O)&1023),P[K++]=240|W>>>18,P[K++]=128|W>>>12&63,P[K++]=128|W>>>6&63,P[K++]=128|W&63);x=P}x.length>64&&(x=new H(!0).update(x).array());var se=[],B=[];for(O=0;O<64;++O){var ee=x[O]||0;se[O]=92^ee,B[O]=54^ee}H.call(this,E),this.update(B),this.oKeyPad=se,this.inner=!0,this.sharedMemory=E}z.prototype=new H,z.prototype.finalize=function(){if(H.prototype.finalize.call(this),this.inner){this.inner=!1;var x=this.array();H.call(this,this.sharedMemory),this.update(this.oKeyPad),this.update(x),H.prototype.finalize.call(this)}};var q=D();q.md5=q,q.md5.hmac=U(),d?t.exports=q:s.md5=q})()})(Mp)),Mp.exports}var ZR=YR(),Lp={exports:{}};/**
528
- * [js-sha256]{@link https://github.com/emn178/js-sha256}
529
- *
530
- * @version 0.11.1
531
- * @author Chen, Yi-Cyuan [emn178@gmail.com]
532
- * @copyright Chen, Yi-Cyuan 2014-2025
533
- * @license MIT
534
- */var xx;function WR(){return xx||(xx=1,(function(t){(function(){var e="input is invalid type",n=typeof window=="object",r=n?window:{};r.JS_SHA256_NO_WINDOW&&(n=!1);var s=!n&&typeof self=="object",o=!r.JS_SHA256_NO_NODE_JS&&typeof process=="object"&&process.versions&&process.versions.node&&process.type!="renderer";o?r=f1:s&&(r=self);var c=!r.JS_SHA256_NO_COMMON_JS&&!0&&t.exports,d=!r.JS_SHA256_NO_ARRAY_BUFFER&&typeof ArrayBuffer<"u",f="0123456789abcdef".split(""),p=[-2147483648,8388608,32768,128],g=[24,16,8,0],b=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],v=["hex","array","digest","arrayBuffer"],w=[];(r.JS_SHA256_NO_NODE_JS||!Array.isArray)&&(Array.isArray=function(C){return Object.prototype.toString.call(C)==="[object Array]"}),d&&(r.JS_SHA256_NO_ARRAY_BUFFER_IS_VIEW||!ArrayBuffer.isView)&&(ArrayBuffer.isView=function(C){return typeof C=="object"&&C.buffer&&C.buffer.constructor===ArrayBuffer});var _=function(C,L){return function(U){return new M(L,!0).update(U)[C]()}},k=function(C){var L=_("hex",C);o&&(L=I(L,C)),L.create=function(){return new M(C)},L.update=function(z){return L.create().update(z)};for(var U=0;U<v.length;++U){var H=v[U];L[H]=_(H,C)}return L},I=function(C,L){var U=Zu,H=Zu.Buffer,z=L?"sha224":"sha256",q;H.from&&!r.JS_SHA256_NO_BUFFER_FROM?q=H.from:q=function(E){return new H(E)};var x=function(E){if(typeof E=="string")return U.createHash(z).update(E,"utf8").digest("hex");if(E==null)throw new Error(e);return E.constructor===ArrayBuffer&&(E=new Uint8Array(E)),Array.isArray(E)||ArrayBuffer.isView(E)||E.constructor===H?U.createHash(z).update(q(E)).digest("hex"):C(E)};return x},N=function(C,L){return function(U,H){return new F(U,L,!0).update(H)[C]()}},R=function(C){var L=N("hex",C);L.create=function(z){return new F(z,C)},L.update=function(z,q){return L.create(z).update(q)};for(var U=0;U<v.length;++U){var H=v[U];L[H]=N(H,C)}return L};function M(C,L){L?(w[0]=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,this.blocks=w):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],C?(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=C}M.prototype.update=function(C){if(!this.finalized){var L,U=typeof C;if(U!=="string"){if(U==="object"){if(C===null)throw new Error(e);if(d&&C.constructor===ArrayBuffer)C=new Uint8Array(C);else if(!Array.isArray(C)&&(!d||!ArrayBuffer.isView(C)))throw new Error(e)}else throw new Error(e);L=!0}for(var H,z=0,q,x=C.length,E=this.blocks;z<x;){if(this.hashed&&(this.hashed=!1,E[0]=this.block,this.block=E[16]=E[1]=E[2]=E[3]=E[4]=E[5]=E[6]=E[7]=E[8]=E[9]=E[10]=E[11]=E[12]=E[13]=E[14]=E[15]=0),L)for(q=this.start;z<x&&q<64;++z)E[q>>>2]|=C[z]<<g[q++&3];else for(q=this.start;z<x&&q<64;++z)H=C.charCodeAt(z),H<128?E[q>>>2]|=H<<g[q++&3]:H<2048?(E[q>>>2]|=(192|H>>>6)<<g[q++&3],E[q>>>2]|=(128|H&63)<<g[q++&3]):H<55296||H>=57344?(E[q>>>2]|=(224|H>>>12)<<g[q++&3],E[q>>>2]|=(128|H>>>6&63)<<g[q++&3],E[q>>>2]|=(128|H&63)<<g[q++&3]):(H=65536+((H&1023)<<10|C.charCodeAt(++z)&1023),E[q>>>2]|=(240|H>>>18)<<g[q++&3],E[q>>>2]|=(128|H>>>12&63)<<g[q++&3],E[q>>>2]|=(128|H>>>6&63)<<g[q++&3],E[q>>>2]|=(128|H&63)<<g[q++&3]);this.lastByteIndex=q,this.bytes+=q-this.start,q>=64?(this.block=E[16],this.start=q-64,this.hash(),this.hashed=!0):this.start=q}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}},M.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var C=this.blocks,L=this.lastByteIndex;C[16]=this.block,C[L>>>2]|=p[L&3],this.block=C[16],L>=56&&(this.hashed||this.hash(),C[0]=this.block,C[16]=C[1]=C[2]=C[3]=C[4]=C[5]=C[6]=C[7]=C[8]=C[9]=C[10]=C[11]=C[12]=C[13]=C[14]=C[15]=0),C[14]=this.hBytes<<3|this.bytes>>>29,C[15]=this.bytes<<3,this.hash()}},M.prototype.hash=function(){var C=this.h0,L=this.h1,U=this.h2,H=this.h3,z=this.h4,q=this.h5,x=this.h6,E=this.h7,O=this.blocks,T,P,$,K,W,se,B,ee,ae,le,ye;for(T=16;T<64;++T)W=O[T-15],P=(W>>>7|W<<25)^(W>>>18|W<<14)^W>>>3,W=O[T-2],$=(W>>>17|W<<15)^(W>>>19|W<<13)^W>>>10,O[T]=O[T-16]+P+O[T-7]+$<<0;for(ye=L&U,T=0;T<64;T+=4)this.first?(this.is224?(ee=300032,W=O[0]-1413257819,E=W-150054599<<0,H=W+24177077<<0):(ee=704751109,W=O[0]-210244248,E=W-1521486534<<0,H=W+143694565<<0),this.first=!1):(P=(C>>>2|C<<30)^(C>>>13|C<<19)^(C>>>22|C<<10),$=(z>>>6|z<<26)^(z>>>11|z<<21)^(z>>>25|z<<7),ee=C&L,K=ee^C&U^ye,B=z&q^~z&x,W=E+$+B+b[T]+O[T],se=P+K,E=H+W<<0,H=W+se<<0),P=(H>>>2|H<<30)^(H>>>13|H<<19)^(H>>>22|H<<10),$=(E>>>6|E<<26)^(E>>>11|E<<21)^(E>>>25|E<<7),ae=H&C,K=ae^H&L^ee,B=E&z^~E&q,W=x+$+B+b[T+1]+O[T+1],se=P+K,x=U+W<<0,U=W+se<<0,P=(U>>>2|U<<30)^(U>>>13|U<<19)^(U>>>22|U<<10),$=(x>>>6|x<<26)^(x>>>11|x<<21)^(x>>>25|x<<7),le=U&H,K=le^U&C^ae,B=x&E^~x&z,W=q+$+B+b[T+2]+O[T+2],se=P+K,q=L+W<<0,L=W+se<<0,P=(L>>>2|L<<30)^(L>>>13|L<<19)^(L>>>22|L<<10),$=(q>>>6|q<<26)^(q>>>11|q<<21)^(q>>>25|q<<7),ye=L&U,K=ye^L&H^le,B=q&x^~q&E,W=z+$+B+b[T+3]+O[T+3],se=P+K,z=C+W<<0,C=W+se<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+C<<0,this.h1=this.h1+L<<0,this.h2=this.h2+U<<0,this.h3=this.h3+H<<0,this.h4=this.h4+z<<0,this.h5=this.h5+q<<0,this.h6=this.h6+x<<0,this.h7=this.h7+E<<0},M.prototype.hex=function(){this.finalize();var C=this.h0,L=this.h1,U=this.h2,H=this.h3,z=this.h4,q=this.h5,x=this.h6,E=this.h7,O=f[C>>>28&15]+f[C>>>24&15]+f[C>>>20&15]+f[C>>>16&15]+f[C>>>12&15]+f[C>>>8&15]+f[C>>>4&15]+f[C&15]+f[L>>>28&15]+f[L>>>24&15]+f[L>>>20&15]+f[L>>>16&15]+f[L>>>12&15]+f[L>>>8&15]+f[L>>>4&15]+f[L&15]+f[U>>>28&15]+f[U>>>24&15]+f[U>>>20&15]+f[U>>>16&15]+f[U>>>12&15]+f[U>>>8&15]+f[U>>>4&15]+f[U&15]+f[H>>>28&15]+f[H>>>24&15]+f[H>>>20&15]+f[H>>>16&15]+f[H>>>12&15]+f[H>>>8&15]+f[H>>>4&15]+f[H&15]+f[z>>>28&15]+f[z>>>24&15]+f[z>>>20&15]+f[z>>>16&15]+f[z>>>12&15]+f[z>>>8&15]+f[z>>>4&15]+f[z&15]+f[q>>>28&15]+f[q>>>24&15]+f[q>>>20&15]+f[q>>>16&15]+f[q>>>12&15]+f[q>>>8&15]+f[q>>>4&15]+f[q&15]+f[x>>>28&15]+f[x>>>24&15]+f[x>>>20&15]+f[x>>>16&15]+f[x>>>12&15]+f[x>>>8&15]+f[x>>>4&15]+f[x&15];return this.is224||(O+=f[E>>>28&15]+f[E>>>24&15]+f[E>>>20&15]+f[E>>>16&15]+f[E>>>12&15]+f[E>>>8&15]+f[E>>>4&15]+f[E&15]),O},M.prototype.toString=M.prototype.hex,M.prototype.digest=function(){this.finalize();var C=this.h0,L=this.h1,U=this.h2,H=this.h3,z=this.h4,q=this.h5,x=this.h6,E=this.h7,O=[C>>>24&255,C>>>16&255,C>>>8&255,C&255,L>>>24&255,L>>>16&255,L>>>8&255,L&255,U>>>24&255,U>>>16&255,U>>>8&255,U&255,H>>>24&255,H>>>16&255,H>>>8&255,H&255,z>>>24&255,z>>>16&255,z>>>8&255,z&255,q>>>24&255,q>>>16&255,q>>>8&255,q&255,x>>>24&255,x>>>16&255,x>>>8&255,x&255];return this.is224||O.push(E>>>24&255,E>>>16&255,E>>>8&255,E&255),O},M.prototype.array=M.prototype.digest,M.prototype.arrayBuffer=function(){this.finalize();var C=new ArrayBuffer(this.is224?28:32),L=new DataView(C);return L.setUint32(0,this.h0),L.setUint32(4,this.h1),L.setUint32(8,this.h2),L.setUint32(12,this.h3),L.setUint32(16,this.h4),L.setUint32(20,this.h5),L.setUint32(24,this.h6),this.is224||L.setUint32(28,this.h7),C};function F(C,L,U){var H,z=typeof C;if(z==="string"){var q=[],x=C.length,E=0,O;for(H=0;H<x;++H)O=C.charCodeAt(H),O<128?q[E++]=O:O<2048?(q[E++]=192|O>>>6,q[E++]=128|O&63):O<55296||O>=57344?(q[E++]=224|O>>>12,q[E++]=128|O>>>6&63,q[E++]=128|O&63):(O=65536+((O&1023)<<10|C.charCodeAt(++H)&1023),q[E++]=240|O>>>18,q[E++]=128|O>>>12&63,q[E++]=128|O>>>6&63,q[E++]=128|O&63);C=q}else if(z==="object"){if(C===null)throw new Error(e);if(d&&C.constructor===ArrayBuffer)C=new Uint8Array(C);else if(!Array.isArray(C)&&(!d||!ArrayBuffer.isView(C)))throw new Error(e)}else throw new Error(e);C.length>64&&(C=new M(L,!0).update(C).array());var T=[],P=[];for(H=0;H<64;++H){var $=C[H]||0;T[H]=92^$,P[H]=54^$}M.call(this,L,U),this.update(P),this.oKeyPad=T,this.inner=!0,this.sharedMemory=U}F.prototype=new M,F.prototype.finalize=function(){if(M.prototype.finalize.call(this),this.inner){this.inner=!1;var C=this.array();M.call(this,this.is224,this.sharedMemory),this.update(this.oKeyPad),this.update(C),M.prototype.finalize.call(this)}};var D=k();D.sha256=D,D.sha224=k(!0),D.sha256.hmac=R(),D.sha224.hmac=R(!0),c?t.exports=D:(r.sha256=D.sha256,r.sha224=D.sha224)})()})(Lp)),Lp.exports}var QR=WR();let Me=class extends Error{constructor(n,r){super(n);G(this,"expr");this.expr=r,this.name="EvalError"}};class Qn extends Me{constructor(e,n){super(e,n),this.name="UnsupportedError"}}class JR{constructor(){G(this,"entries",[]);G(this,"parents",[]);G(this,"frames",[])}capture(e,n){const r=this.entries.length,s=this.parents.length>0?this.parents[this.parents.length-1]:null,o={source:zt(e),kind:e.type,parent:s};this.stampFrame(o),this.entries.push(o),this.parents.push(r);try{const c=n();return this.entries[r].value=c,c}catch(c){throw this.entries[r].error=c instanceof Error?c.message:String(c),c}finally{this.parents.pop()}}skip(e){const n=this.parents.length>0?this.parents[this.parents.length-1]:null,r={source:zt(e),kind:e.type,parent:n,skipped:!0};this.stampFrame(r),this.entries.push(r)}enterFrame(e){this.frames.push(e)}exitFrame(){this.frames.pop()}stampFrame(e){this.frames.length!==0&&(e.inlinedFrom={name:this.frames[this.frames.length-1]})}markEntryAsLetBinding(e,n){e<0||e>=this.entries.length||(this.entries[e].letBinding={name:n})}}function _e(t,e,n={}){return e.trace?e.trace.capture(t,()=>Sx(t,e,n)):Sx(t,e,n)}function Sx(t,e,n){switch(t.type){case"literal":return typeof t.value=="number"&&t.raw.includes(".")?new Ke(t.value):t.value;case"identifier":return XR(t.name,e,n);case"binaryOp":return tT(t.op,t.left,t.right,e,n);case"unaryOp":{if(t.op==="!")return!_e(t.operand,e,n);if(t.op==="-"){const r=_e(t.operand,e,n);return r instanceof Ke?new Ke(-r.value):-r}throw new Me(`Unknown unary op: ${t.op}`,t)}case"ternary":{const r=_e(t.condition,e,n);return _e(r?t.consequent:t.alternate,e,n)}case"memberAccess":{const r=_e(t.object,e,n);if(r==null)throw new Me(`Property '${t.property}' accessed on ${r===null?"null":"undefined"} value`,t);if(r instanceof tt)return r.field(t.property);if(r instanceof El)switch(t.property){case"addedKeys":return()=>r.addedKeys();case"removedKeys":return()=>r.removedKeys();case"changedKeys":return()=>r.changedKeys();case"affectedKeys":return()=>r.affectedKeys();case"unchangedKeys":return()=>r.unchangedKeys()}if(r instanceof lt)switch(t.property){case"size":return()=>r.size()}if(Object.hasOwn(r,t.property))return r[t.property];throw new Me(`No field '${t.property}' on map (use 'in' or .get() to read a possibly-absent field)`,t)}case"bracketAccess":{const r=_e(t.object,e,n),s=_e(t.index,e,n);if(r==null)throw new Me(`Index access on ${r===null?"null":"undefined"} value`,t);if(r instanceof tt)return r.field(String(s));const o=String(s);return Object.hasOwn(r,o)?r[o]:null}case"sliceAccess":{const r=_e(t.object,e,n),s=_e(t.start,e,n),o=_e(t.end,e,n);if(r==null)return null;if(typeof s!="number"||!Number.isInteger(s))throw new Me(`Slice start must be an integer, got ${typeof s}`);if(typeof o!="number"||!Number.isInteger(o))throw new Me(`Slice end must be an integer, got ${typeof o}`);if(s<0||o<0)throw new Me(`Slice indices must be non-negative, got [${s}:${o}]`);if(typeof r=="string"||Array.isArray(r))return r.slice(s,o);throw new Me(`Slice not supported on ${typeof r}`)}case"inExpr":{const r=_e(t.element,e,n),s=_e(t.collection,e,n);return s==null?!1:Array.isArray(s)?s.some(o=>Wn(o,r)):typeof s=="object"?Object.hasOwn(s,String(r)):!1}case"isExpr":{const r=_e(t.value,e,n);switch(t.typeName){case"string":return typeof r=="string";case"int":return r instanceof tt?!1:typeof r=="number";case"float":return r instanceof Ke;case"number":return r instanceof Ke?!0:r instanceof tt?!1:typeof r=="number";case"bool":return typeof r=="boolean";case"null":return r===null;case"list":return Array.isArray(r);case"map":return r instanceof tt||r instanceof El||r instanceof lt?!1:typeof r=="object"&&r!==null&&!Array.isArray(r);default:return r instanceof tt?r.typeName===t.typeName:!1}}case"listLiteral":return t.elements.map(r=>_e(r,e,n));case"mapLiteral":{const r={};for(const s of t.entries){const o=String(_e(s.key,e,n));r[o]=_e(s.value,e,n)}return r}case"functionCall":return iT(t.name,t.args,e,n);case"methodCall":return aT(t.object,t.method,t.args,e,n);case"pathLiteral":{const r=[];for(const s of t.segments)typeof s=="string"?r.push(s):r.push(String(_e(s,e,n)));return new dr(r)}default:throw new Me(`Unknown expression type: ${t.type}`,t)}}function XR(t,e,n){if(t in n)return n[t];if(t in e.pathVariables)return e.pathVariables[t];switch(t){case"request":return e.request;case"resource":if(e.resource===null)throw new Me("Null value error.");return e.resource;case"true":return!0;case"false":return!1;case"null":return null}throw new Me(`Undefined variable '${t}'`)}function eT(t){return t==="request"||t==="resource"||t==="true"||t==="false"||t==="null"}function tT(t,e,n,r,s){var d,f;if(t==="&&"){let p,g;try{p=_e(e,r,s)}catch(w){g=w}if(g===void 0&&!p)return(d=r.trace)==null||d.skip(n),!1;let b,v;try{b=_e(n,r,s)}catch(w){v=w}if(v===void 0&&!b)return!1;if(g!==void 0)throw g;if(v!==void 0)throw v;return!!b}if(t==="||"){let p,g;try{p=_e(e,r,s)}catch(w){g=w}if(g===void 0&&p)return(f=r.trace)==null||f.skip(n),!0;let b,v;try{b=_e(n,r,s)}catch(w){v=w}if(v===void 0&&b)return!0;if(g!==void 0)throw g;if(v!==void 0)throw v;return!!b}const o=_e(e,r,s),c=_e(n,r,s);if(t!=="=="&&t!=="!="){if(o instanceof tt){const p=o.binaryOp(t,c);if(p!==gt)return p}if(typeof o=="number"&&c instanceof Ke){const p=new Ke(o).binaryOp(t,c);if(p!==gt)return p}if(c instanceof tt&&(t==="+"||t==="*")){const p=c.binaryOp(t,o);if(p!==gt)return p}if((t!=="+"||typeof o!="string"&&typeof c!="string")&&(o instanceof tt||c instanceof tt)){const p=o instanceof tt?o.typeName:typeof o,g=c instanceof tt?c.typeName:typeof c;throw new Me(`Operator '${t}' is not defined between ${p} and ${g}`)}}if((t==="<"||t===">"||t==="<="||t===">=")&&!(typeof o=="number"&&typeof c=="number"||typeof o=="string"&&typeof c=="string"))throw new Me(`Operator '${t}' is not defined between ${typeof o} and ${typeof c}`);switch(t){case"==":return o===c||Wn(o,c);case"!=":return!(o===c||Wn(o,c));case"<":return o<c;case">":return o>c;case"<=":return o<=c;case">=":return o>=c;case"+":{if(Array.isArray(o)&&Array.isArray(c))return[...o,...c];if(typeof o=="string"&&typeof c=="string"||typeof o=="number"&&typeof c=="number")return o+c;if(typeof o=="string"&&c instanceof tt)return o+String(c);throw new Me(`Operator '+' is not defined between ${Array.isArray(o)?"list":typeof o} and ${Array.isArray(c)?"list":typeof c}`)}case"-":return o-c;case"*":return o*c;case"/":if(c===0)throw new Me("Division by zero");return Math.trunc(o/c);case"%":if(c===0)throw new Me("Modulo by zero");return o%c;default:throw new Me(`Unknown binary op: ${t}`)}}function nT(t){if(typeof t=="number")return Math.trunc(t);if(t instanceof Ke)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 Me(`int() cannot convert string '${t}' to an integer`)}throw new Me(`int() cannot convert ${typeof t} to an integer`)}function rT(t){if(t instanceof Ke)return t;if(typeof t=="number")return new Ke(t);if(typeof t=="string"){const e=t.trim();if(/^[+-]?(\d+\.?\d*|\.\d+)$/.test(e))return new Ke(parseFloat(e));throw new Me(`float() cannot convert string '${t}' to a float`)}throw new Me(`float() cannot convert ${typeof t} to a float`)}function sT(t){if(typeof t=="boolean")return t;if(typeof t=="string"){if(t==="true")return!0;if(t==="false")return!1;throw new Me(`bool() cannot convert string '${t}' to a boolean`)}throw new Me(`bool() cannot convert ${typeof t} to a boolean`)}function iT(t,e,n,r){var c,d,f,p,g;switch(t){case"get":{const b=String(_e(e[0],n,r));return Ax(b,n)}case"exists":{const b=String(_e(e[0],n,r));return jx(b,n)}case"getAfter":{const b=_e(e[0],n,r),v=String(b);if(v===n.afterStatePath.toString()){if(n.afterState===null)throw new Me(`getAfter() of non-existent document '${v}' (guard with existsAfter() first)`);return Em(Al(v),n.afterState)}const w=Al(v);if((c=n.batchProjection)!=null&&c.has(w)){const _=n.batchProjection.get(w);if(_===null)throw new Me(`getAfter() of non-existent document '${v}' (guard with existsAfter() first)`);return Em(w,_)}return Ax(v,n)}case"existsAfter":{const b=_e(e[0],n,r),v=String(b);if(v===n.afterStatePath.toString())return n.existsAfter;const w=Al(v);return(d=n.batchProjection)!=null&&d.has(w)?n.batchProjection.get(w)!==null:jx(v,n)}case"debug":return _e(e[0],n,r);case"string":return String(_e(e[0],n,r));case"int":return nT(_e(e[0],n,r));case"float":return rT(_e(e[0],n,r));case"bool":return sT(_e(e[0],n,r));case"path":{const b=_e(e[0],n,r);if(b instanceof dr)return b;if(typeof b=="string")return dr.fromString(b);throw new Me(`path() requires a string argument, got ${typeof b}`)}}const s=n.functions.get(t);if(!s)throw new Qn(`Unknown function: ${t}`);const o={...r};for(let b=0;b<s.parameters.length;b++)o[s.parameters[b]]=_e(e[b],n,r);(f=n.trace)==null||f.enterFrame(t);try{for(const b of s.lets){const v=n.trace?n.trace.entries.length:-1;o[b.name]=_e(b.value,n,o),v>=0&&((p=n.trace)==null||p.markEntryAsLetBinding(v,b.name))}return _e(s.body,n,o)}finally{(g=n.trace)==null||g.exitFrame()}}function aT(t,e,n,r,s){if(t.type==="identifier"){const d=t.name;if(_x(d)&&!(d in s)&&!(d in r.pathVariables)){const f=n.map(p=>_e(p,r,s));return lT(d,e,f)}if(!_x(d)&&!(d in s)&&!(d in r.pathVariables)&&!eT(d))throw new Qn(`Unknown namespace or method '${d}.${e}()'`)}const o=_e(t,r,s),c=n.map(d=>_e(d,r,s));if(o instanceof tt){const d=o.callMethod(e,c);if(d===gt)throw new Qn(`Unknown method '${e}' on ${o.typeName}`);return d}if(e==="diff"&&typeof o=="object"&&o!==null&&!Array.isArray(o)){const d=c[0];if(typeof d=="object"&&d!==null)return new El(d,o);throw new Me("diff() requires a map argument")}if(typeof o=="function")return o(...c);if(o instanceof lt)switch(e){case"hasOnly":return o.hasOnly(c[0]);case"hasAll":return o.hasAll(c[0]);case"hasAny":return o.hasAny(c[0]);case"size":return o.size();case"difference":case"union":case"intersection":throw new Qn(`Set.${e}() is not faithfully modeled by the simulator (oracle capture shows production denies calls that reach it) — abstaining rather than guessing`)}if(o instanceof El)switch(e){case"addedKeys":return o.addedKeys();case"removedKeys":return o.removedKeys();case"changedKeys":return o.changedKeys();case"affectedKeys":return o.affectedKeys();case"unchangedKeys":return o.unchangedKeys()}if(typeof o=="object"&&o!==null&&!Array.isArray(o)){const d=o;switch(e){case"keys":return new lt(Object.keys(d));case"values":return Object.values(d);case"size":return Object.keys(d).length;case"hasAll":return c[0].every(f=>Object.hasOwn(d,f));case"hasAny":return c[0].some(f=>Object.hasOwn(d,f));case"hasOnly":return Object.keys(d).every(f=>c[0].includes(f));case"diff":{const f=c[0];return new El(f,d)}case"get":{const f=c[0],p=c[1];if(Array.isArray(f)){let b=d;for(const v of f){if(b==null||typeof b!="object"||Array.isArray(b)||b instanceof tt)return p;const w=String(v);if(!Object.hasOwn(b,w))return p;b=b[w]}return b}const g=String(f);return Object.hasOwn(d,g)?d[g]:p}}}if(Array.isArray(o))switch(e){case"size":return o.length;case"hasAll":return c[0].every(d=>o.some(f=>Wn(f,d)));case"hasAny":return c[0].some(d=>o.some(f=>Wn(f,d)));case"hasOnly":{const d=c[0];return o.every(f=>d.some(p=>Wn(p,f)))}case"join":return o.join(String(c[0]??","));case"concat":{const d=c[0];if(!Array.isArray(d))throw new Me(`List.concat requires a list argument, got ${typeof d}`);return[...o,...d]}case"removeAll":{const d=c[0];if(!Array.isArray(d))throw new Me(`List.removeAll requires a list argument, got ${typeof d}`);return o.filter(f=>!d.some(p=>Wn(f,p)))}case"toSet":return new lt(o.map(d=>String(d)))}if(typeof o=="string")switch(e){case"size":return o.length;case"lower":return o.toLowerCase();case"upper":return o.toUpperCase();case"trim":return o.trim();case"split":return o.split(Up(String(c[0]),"g"));case"matches":return Up(`^(?:${String(c[0])})$`).test(o);case"replace":return o.replace(Up(String(c[0]),"g"),String(c[1]));case"toUtf8":return In.fromUtf8(o)}throw new Qn(`Unknown method '${e}' on ${typeof o}`)}function Up(t,e=""){try{return new RegExp(t,e)}catch(n){throw new Me(`Invalid regex '${t}': ${n.message}`)}}const oT=new Set(["math","timestamp","duration","latlng","hashing"]);function _x(t){return oT.has(t)}function lT(t,e,n){const r=t==="hashing"?n:n.map(cT);switch(t){case"math":return gT(e,r);case"timestamp":return bT(e,r);case"duration":return vT(e,r);case"latlng":return yT(e,r);case"hashing":return dT(e,n)}throw new Qn(`Unknown namespace '${t}'`)}function cT(t){return t instanceof Ke?t.value:t}function uT(t){if(t instanceof In)return t;if(typeof t=="string")return In.fromUtf8(t);throw new Me(`hashing.* requires Bytes or String, got ${typeof t}`)}function dT(t,e){const n=uT(e[0]);switch(t){case"md5":return new In(new Uint8Array(ZR.md5.arrayBuffer(n.data)));case"sha256":return new In(new Uint8Array(QR.sha256.arrayBuffer(n.data)));case"crc32":{const r=hT(n.data);return new In(Ex(r))}case"crc32c":{const r=mT(n.data);return new In(Ex(r))}}throw new Qn(`Unknown hashing method '${t}'`)}function Ex(t){return new Uint8Array([t>>>24&255,t>>>16&255,t>>>8&255,t&255])}const fT=(()=>{const t=new Uint32Array(256);for(let e=0;e<256;e++){let n=e;for(let r=0;r<8;r++)n=n&1?3988292384^n>>>1:n>>>1;t[e]=n>>>0}return t})();function hT(t){let e=4294967295;for(let n=0;n<t.length;n++)e=fT[(e^t[n])&255]^e>>>8;return(e^4294967295)>>>0}const pT=(()=>{const t=new Uint32Array(256);for(let e=0;e<256;e++){let n=e;for(let r=0;r<8;r++)n=n&1?2197175160^n>>>1:n>>>1;t[e]=n>>>0}return t})();function mT(t){let e=4294967295;for(let n=0;n<t.length;n++)e=pT[(e^t[n])&255]^e>>>8;return(e^4294967295)>>>0}function yT(t,e){switch(t){case"value":{const[n,r]=e;return new Cr(n,r)}}throw new Qn(`Unknown latlng method '${t}'`)}function gT(t,e){switch(t){case"abs":return Math.abs(e[0]);case"ceil":return Math.ceil(e[0]);case"floor":return Math.floor(e[0]);case"round":return Math.round(e[0]);case"sqrt":return Math.sqrt(e[0]);case"pow":return Math.pow(e[0],e[1]);case"isInfinite":{const n=e[0];return Number.isFinite(n)===!1&&Number.isNaN(n)===!1}case"isNaN":return Number.isNaN(e[0])}throw new Qn(`Unknown math method '${t}'`)}function bT(t,e){switch(t){case"date":{const[n,r,s]=e;return Rt.fromYMD(n,r,s)}case"value":return Rt.fromMillis(e[0])}throw new Qn(`Unknown timestamp method '${t}'`)}function vT(t,e){switch(t){case"value":try{return Mt.fromValue(e[0],e[1])}catch(n){throw new Me(n.message)}case"time":{const[n,r,s,o]=e;return Mt.fromTime(n,r,s,o)}case"abs":{const n=e[0];if(!(n instanceof Mt))throw new Me(`duration.abs() requires a Duration argument, got ${typeof n}`);return Mt.abs(n)}}throw new Qn(`Unknown duration method '${t}'`)}function Al(t,e){return t.replace(/\$\(database\)/g,"(default)").replace(/^\/databases\/\(default\)\/documents\//,"")}function Em(t,e){const n=t.split("/").filter(Boolean),r=n.length>0?n[n.length-1]:"",s=["databases","(default)","documents",...n];return{data:e,id:r,__name__:new dr(s)}}function Ax(t,e){const n=Al(t);let r=e.mockDocuments.get(n);if(!r&&e.getDoc){const s=e.getDoc(n);s&&(e.mockDocuments.set(n,s),r=s)}if(r)return Em(n,r);throw new Me(`get() of non-existent document '${n}' (guard with exists() first)`)}function jx(t,e){const n=Al(t);if(e.mockDocuments.has(n))return!0;if(e.getDoc){const r=e.getDoc(n);if(r)return e.mockDocuments.set(n,r),!0}return!1}const wT=new Set(["__proto__","prototype","constructor"]);function Wu(t){if(wT.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 nE(t,e){const n={...t};for(const[r,s]of Object.entries(e)){Wu(r);const o=Object.hasOwn(n,r)?n[r]:void 0;s!==null&&typeof s=="object"&&!Array.isArray(s)&&o!==null&&typeof o=="object"&&!Array.isArray(o)?n[r]=nE(o,s):n[r]=s}return n}function xT(t,e,n){let r=t;for(let o=0;o<e.length-1;o++){const c=e[o];Wu(c);const d=Object.hasOwn(r,c)?r[c]:void 0;(d===null||typeof d!="object"||Array.isArray(d))&&(r[c]={}),r=r[c]}const s=e[e.length-1];Wu(s),r[s]=n}function ST(t,e){const n={...t};for(const[r,s]of Object.entries(e))r.includes(".")?xT(n,r.split("."),s):(Wu(r),n[r]=s);return n}function _T(t,e,n){switch(t.kind){case"create":return n;case"set":return t.merge?nE(e??{},n):n;case"update":return ST(e??{},n);case"delete":return null}}class ET{constructor(){G(this,"attempts",[])}push(e){this.attempts.push(e)}}function $u(t){return"/"+t.path.segments.map(n=>n.type==="literal"?n.value:n.type==="wildcard"?`{${n.name}}`:`{${n.name}=**}`).join("/")}function Am(t,e,n,r){const s=[...n,...t.functions],o=t.path.segments,c={};let d=0,f;for(const b of o)if(b.type==="literal"){if(d>=e.length){f="request-shorter";break}if(e[d]!==b.value){f="literal-mismatch";break}d++}else if(b.type==="wildcard"){if(d>=e.length){f="request-shorter";break}c[b.name]=e[d],d++}else b.type==="recursive"&&(c[b.name]=e.slice(d).join("/"),d=e.length);if(f!==void 0)return r==null||r.push({...t.loc?{line:t.loc.line}:{},blockPath:$u(t),matchedSegments:d,totalSegments:o.length,bindings:c,matched:!1,reason:f}),[];const p=e.slice(d);if(p.length===0)return r==null||r.push({...t.loc?{line:t.loc.line}:{},blockPath:$u(t),matchedSegments:d,totalSegments:o.length,bindings:c,matched:!0}),[{block:t,pathVariables:c,parentFunctions:s}];const g=[];for(const b of t.children)for(const v of Am(b,p,s,r))v.pathVariables={...c,...v.pathVariables},g.push(v);return r==null||r.push({...t.loc?{line:t.loc.line}:{},blockPath:$u(t),matchedSegments:d,totalSegments:o.length,bindings:c,...g.length>0?{matched:!0}:{matched:!1,reason:"no-matching-child"}}),g}function AT(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 jT(t,e,n){const r=AT(e),s=[],o=[],c=[];for(let p=0;p<t.allows.length;p++){const g=t.allows[p];g.operations.some(b=>r.includes(b))&&c.push({rule:g,index:p})}if(c.length===0)return o.push(`No allow rules found for operation '${e}'`),{decision:"DENY",trace:s,notes:o};let d=!1;const f=n.trace;for(const{rule:p,index:g}of c){const b=kT(p,g),v=new JR;n.trace=v;try{const w=_e(p.condition,n);if(b.expressionTrace=v.entries,w)return b.verdict="ALLOW",s.push(b),n.trace=f,{decision:"ALLOW",trace:s,notes:o};b.verdict="DENY",s.push(b)}catch(w){b.expressionTrace=v.entries,w instanceof Qn?(d=!0,b.verdict="UNSUPPORTED",b.message=w.message):(b.verdict="ERROR",b.message=w instanceof Error?w.message:String(w)),s.push(b)}}return n.trace=f,{decision:d?"UNSUPPORTED":"DENY",trace:s,notes:o}}function kT(t,e){const n={ruleIndex:e,operations:[...t.operations],verdict:"DENY",conditionText:zt(t.condition)};return t.loc&&(n.line=t.loc.line),n}function CT(t){return typeof t=="object"&&t!==null&&t.__type==="serverTimestamp"}function rE(t,e){const n={};for(const[r,s]of Object.entries(t))CT(s)?n[r]=e:NT(s)?n[r]=rE(s,e):n[r]=s;return n}function NT(t){if(t===null||typeof t!="object"||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function OT(t){var e,n,r;return t.method!=="list"?{}:{limit:((e=t.query)==null?void 0:e.limit)??null,offset:((n=t.query)==null?void 0:n.offset)??null,orderBy:((r=t.query)==null?void 0:r.orderBy)??null}}function RT(t,e,n,r,s){const o=new Map;for(const N of e)o.set(N.name,N);const c=new Map;if(t.functionMocks)for(const N of t.functionMocks)N.function==="get"&&typeof N.result=="object"&&N.result!==null?c.set(N.path,N.result):N.function==="exists"&&N.result===!0&&c.set(N.path,{});const d=t.requestTime?Rt.fromIsoString(t.requestTime):Rt.fromMillis(Date.now()),p=["databases","(default)","documents",...(t.path.startsWith("/")?t.path.slice(1):t.path).split("/").filter(Boolean)],g=new dr(p,n),b=t.data??{},v=t.resource??null;let w,_;if(t.writeMode)w=_T(t.writeMode,v,b),_=w!==null;else switch(t.method){case"create":case"update":w=b,_=!0;break;case"delete":w=null,_=!1;break;case"get":case"list":default:w=v,_=v!==null;break}const k=w!==null?rE(w,d):null,I=k??{};return{request:{auth:t.auth?{uid:t.auth.uid,token:t.auth.token??{}}:null,resource:{data:I},method:t.method,path:g,query:OT(t),time:d},resource:t.method==="create"||v===null?null:{data:v},mockDocuments:c,getDoc:r,pathVariables:n,functions:o,database:"(default)",afterStatePath:g,afterState:k,existsAfter:_,...s?{batchProjection:s}:{}}}class TT{simulate(e,n,r){if(!e||e.trim().length===0)return{success:!1,error:{code:"PARSE_FAILED",message:"Empty rules source — call setRules(sandbox, rules) from pyric/sandbox/firestore before operating, or initialize without rules to use the open-by-default ruleset. See pyric/sandbox docs.",recoverable:!0}};const s=Zy(e);if(!s)return{success:!1,error:{code:"PARSE_FAILED",message:"Failed to parse rules source",recoverable:!0}};const o=[];let c=0,d=0,f=0;const p={database:"(default)"};for(const g of s.service.match.path.segments)g.type==="wildcard"&&(p[g.name]="(default)");for(const g of n){const b=g.path.split("/").filter(Boolean),v=[...s.functions??[],...s.service.functions??[],...s.service.match.functions];let w=[];const _=new ET;for(const L of s.service.match.children)w.push(...Am(L,b,v,_));let k=!1;if(w.length===0&&g.method==="list"){const L=[...b,"__hypothetical_doc__"];for(const U of s.service.match.children)w.push(...Am(U,L,v,_));w.length>0&&(k=!0)}const I={requestPath:g.path,attempts:_.attempts};if(w.length===0){const L=g.expectation==="DENY"?"PASSED":"FAILED";L==="PASSED"?c++:d++,o.push({description:g.description,expectation:g.expectation,state:L,decision:"DENY",trace:[],notes:[`No match block found for path '${g.path}'`],pathResolution:I});continue}let N="DENY";const R=[],M=[];let F=!1,D;for(const L of w){const U=[...L.parentFunctions,...L.block.functions],H={...p,...L.pathVariables},z=RT(g,U,H,r==null?void 0:r.getDoc,r==null?void 0:r.batchProjection),q=$u(L.block),x=jT(L.block,g.method,z);for(const E of x.trace)E.matchPath=q;if(R.push(...x.trace),M.push(...x.notes),x.decision==="ALLOW"){N="ALLOW",D=q;break}x.decision==="UNSUPPORTED"&&(F=!0)}N!=="ALLOW"&&F&&(N="UNSUPPORTED"),N==="ALLOW"&&D&&M.push(`Allowed by match block '${D}'`),k&&M.push(`list on collection path '${g.path}' evaluated against the document-level match block (document wildcard hypothetical, resource undefined) — emulator-faithful`);let C;N==="UNSUPPORTED"?(C="UNSUPPORTED",f++):N===g.expectation?(C="PASSED",c++):(C="FAILED",d++),o.push({description:g.description,expectation:g.expectation,state:C,decision:N,trace:R,notes:M,pathResolution:I})}return{success:!0,data:{passed:c,failed:d,unsupported:f,results:o}}}}const Mi={maxExpressionLength:256,maxStringLiteralLength:1024,maxAstDepth:16},DT=["serverTimestamp","increment","arrayUnion","arrayRemove","deleteField"],IT={serverTimestamp:{min:0,max:0},increment:{min:1,max:1},arrayUnion:{min:1,max:1/0},arrayRemove:{min:1,max:1/0},deleteField:{min:0,max:0}};function MT(t){return DT.includes(t)}class Ct extends Error{constructor(n,r){super(n);G(this,"code","invalid-argument");G(this,"pos");this.name="ExpressionLexError",this.pos=r}}class xr extends Error{constructor(n,r){super(n);G(this,"code","invalid-argument");G(this,"pos");this.name="ExpressionParseError",this.pos=r}}const LT={"(":"lparen",")":"rparen","[":"lbracket","]":"rbracket",",":"comma",".":"dot","?":"question",":":"colon","+":"plus","-":"minus","*":"star","/":"slash","%":"percent"},UT={true:"true",false:"false",null:"null"};function $T(t){if(t.length>Mi.maxExpressionLength)throw new Ct(`expression exceeds ${Mi.maxExpressionLength}-character cap (got ${t.length})`,Le(Mi.maxExpressionLength));const e=[];let n=0;for(;n<t.length;){const r=n,s=t[n];if(s===" "||s===" "||s==="\r"||s===`
535
- `){n+=1;continue}if(s==='"'||s==="'"){const{token:c,next:d}=FT(t,n,s);if(e.push(c),n=d,n<=r)throw new Ct("lexer stalled on string",Le(r));continue}if(s>="0"&&s<="9"){const{token:c,next:d}=qT(t,n);if(e.push(c),n=d,n<=r)throw new Ct("lexer stalled on number",Le(r));continue}if(Td(s)){const{token:c,next:d}=BT(t,n);e.push(c),n=d;continue}if(s==="$"){const{token:c,next:d}=kx(t,n,"$","reference");e.push(c),n=d;continue}if(s==="@"){const{token:c,next:d}=kx(t,n,"@","sentinel");e.push(c),n=d;continue}if(s==="="&&t[n+1]==="="){e.push({kind:"eq",pos:Le(n)}),n+=2;continue}if(s==="!"&&t[n+1]==="="){e.push({kind:"neq",pos:Le(n)}),n+=2;continue}if(s==="<"){t[n+1]==="="?(e.push({kind:"lte",pos:Le(n)}),n+=2):(e.push({kind:"lt",pos:Le(n)}),n+=1);continue}if(s===">"){t[n+1]==="="?(e.push({kind:"gte",pos:Le(n)}),n+=2):(e.push({kind:"gt",pos:Le(n)}),n+=1);continue}if(s==="&"){if(t[n+1]!=="&")throw new Ct("unexpected '&' (did you mean '&&'?)",Le(n));e.push({kind:"and",pos:Le(n)}),n+=2;continue}if(s==="|"){if(t[n+1]!=="|")throw new Ct("unexpected '|' (did you mean '||'?)",Le(n));e.push({kind:"or",pos:Le(n)}),n+=2;continue}if(s==="!"){e.push({kind:"bang",pos:Le(n)}),n+=1;continue}if(s==="=")throw new Ct("unexpected '=' (did you mean '=='?)",Le(n));const o=LT[s];if(o){e.push({kind:o,pos:Le(n)}),n+=1;continue}throw new Ct(`unexpected character ${JSON.stringify(s)}`,Le(n))}return e.push({kind:"eof",pos:Le(t.length)}),e}function Le(t){return{offset:t,column:t+1}}function Td(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="_"}function sE(t){return Td(t)||t>="0"&&t<="9"}function BT(t,e){let n=e+1;for(;n<t.length&&sE(t[n]);)n+=1;const r=t.slice(e,n),s=UT[r];return s?{token:{kind:s,pos:Le(e)},next:n}:{token:{kind:"identifier",pos:Le(e),value:r},next:n}}function kx(t,e,n,r){const s=e+1;if(s>=t.length||!Td(t[s]))throw new Ct(`expected identifier after '${n}'`,Le(e));let o=s+1;for(;o<t.length&&sE(t[o]);)o+=1;const c=t.slice(s,o);return{token:{kind:r,pos:Le(e),value:c},next:o}}function qT(t,e){let n=e;const r=t[n];if(n+=1,r==="0"){if(n<t.length&&t[n]>="0"&&t[n]<="9")throw new Ct("leading zeros are not allowed in number literals",Le(e))}else for(;n<t.length&&t[n]>="0"&&t[n]<="9";)n+=1;let s=!1;if(n<t.length&&t[n]==="."){const d=t[n+1];if(d!==void 0&&d>="0"&&d<="9")for(s=!0,n+=1;n<t.length&&t[n]>="0"&&t[n]<="9";)n+=1;else if(!(d!==void 0&&Td(d)))throw new Ct("expected digit after '.' in number literal",Le(n))}const o=t.slice(e,n),c=Number.parseFloat(o);if(!Number.isFinite(c))throw new Ct(`numeric literal '${o}' is not finite`,Le(e));if(!s&&!Number.isSafeInteger(c))throw new Ct(`integer literal '${o}' exceeds safe integer range`,Le(e));return{token:{kind:"number",pos:Le(e),value:c},next:n}}function FT(t,e,n){let r=e+1,s="";for(;r<t.length;){const o=t[r];if(o===n)return{token:{kind:"string",pos:Le(e),value:s},next:r+1};if(o==="\\"){const c=t[r+1];if(c===void 0)throw new Ct("unterminated escape sequence in string literal",Le(r));switch(c){case'"':s+='"';break;case"'":s+="'";break;case"\\":s+="\\";break;case"n":s+=`
536
- `;break;case"t":s+=" ";break;default:throw new Ct(`invalid escape sequence '\\${c}' (only \\", \\', \\\\, \\n, \\t are allowed)`,Le(r))}r+=2}else{if(o===`
537
- `||o==="\r")throw new Ct("unterminated string literal (newline before closing quote)",Le(e));s+=o,r+=1}if(s.length>Mi.maxStringLiteralLength)throw new Ct(`string literal exceeds ${Mi.maxStringLiteralLength}-character cap`,Le(e))}throw new Ct("unterminated string literal",Le(e))}function zT(t){const e=new PT(t),n=e.parseExpression();return e.expect("eof","unexpected trailing tokens"),GT(n),n}class PT{constructor(e){G(this,"tokens");G(this,"cursor",0);this.tokens=e}parseExpression(){return this.parseTernary()}parseTernary(){const e=this.parseLogicalOr();if(this.peek().kind!=="question")return e;const n=this.consume(),r=this.parseExpression();this.expect("colon","expected ':' in ternary");const s=this.parseExpression();return{kind:"ternary",cond:e,whenTrue:r,whenFalse:s,pos:n.pos}}parseLogicalOr(){let e=this.parseLogicalAnd();for(;this.peek().kind==="or";){const n=this.consume(),r=this.parseLogicalAnd();e={kind:"logical",op:"||",left:e,right:r,pos:n.pos}}return e}parseLogicalAnd(){let e=this.parseComparison();for(;this.peek().kind==="and";){const n=this.consume(),r=this.parseComparison();e={kind:"logical",op:"&&",left:e,right:r,pos:n.pos}}return e}parseComparison(){let e=this.parseSum();for(;;){const n=VT(this.peek().kind);if(!n)break;const r=this.consume(),s=this.parseSum();e={kind:"binary",op:n,left:e,right:s,pos:r.pos}}return e}parseSum(){let e=this.parseProduct();for(;;){const n=this.peek().kind;if(n!=="plus"&&n!=="minus")break;const r=this.consume(),s=this.parseProduct();e={kind:"binary",op:n==="plus"?"+":"-",left:e,right:s,pos:r.pos}}return e}parseProduct(){let e=this.parseUnary();for(;;){const n=this.peek().kind;if(n!=="star"&&n!=="slash"&&n!=="percent")break;const r=this.consume(),s=this.parseUnary();e={kind:"binary",op:n==="star"?"*":n==="slash"?"/":"%",left:e,right:s,pos:r.pos}}return e}parseUnary(){const e=this.peek().kind;if(e==="minus"||e==="bang"){const n=this.consume(),r=this.parseUnary();return{kind:"unary",op:e==="minus"?"-":"!",operand:r,pos:n.pos}}return this.parsePostfix()}parsePostfix(){let e=this.parsePrimary();for(;;){const n=this.peek().kind;if(n==="dot"){const r=this.consume(),s=this.expect("identifier","expected identifier after '.'");e={kind:"fieldAccess",target:e,field:s.value,pos:r.pos}}else if(n==="lbracket"){const r=this.consume(),s=this.parseExpression();this.expect("rbracket","expected ']'"),e={kind:"indexAccess",target:e,index:s,pos:r.pos}}else break}return e}parsePrimary(){const e=this.peek();switch(e.kind){case"number":return this.consume(),{kind:"literal",value:e.value,pos:e.pos};case"string":return this.consume(),{kind:"literal",value:e.value,pos:e.pos};case"true":return this.consume(),{kind:"literal",value:!0,pos:e.pos};case"false":return this.consume(),{kind:"literal",value:!1,pos:e.pos};case"null":return this.consume(),{kind:"literal",value:null,pos:e.pos};case"reference":return this.consume(),{kind:"reference",alias:e.value,pos:e.pos};case"sentinel":return this.parseSentinelCall();case"lparen":{this.consume();const n=this.parseExpression();return this.expect("rparen","expected ')'"),n}case"identifier":throw new xr(`bare identifier '${e.value}' is not a value (did you mean '$${e.value}' or '@${e.value}'?)`,e.pos);case"eof":throw new xr("unexpected end of expression",e.pos);default:throw new xr("unexpected token",e.pos)}}parseSentinelCall(){const e=this.consume(),n=e.value;if(!MT(n))throw new xr(`unknown sentinel '@${n}' (allowed: serverTimestamp, increment, arrayUnion, arrayRemove, deleteField)`,e.pos);this.expect("lparen",`expected '(' after sentinel '@${n}'`);const r=[];if(this.peek().kind!=="rparen")for(r.push(this.parseExpression());this.peek().kind==="comma";)this.consume(),r.push(this.parseExpression());this.expect("rparen","expected ')' after sentinel arguments");const s=IT[n];if(r.length<s.min||r.length>s.max){const o=s.max===1/0?`at least ${s.min}`:s.min===s.max?`exactly ${s.min}`:`${s.min}..${s.max}`;throw new xr(`sentinel '@${n}' expects ${o} argument(s), got ${r.length}`,e.pos)}return{kind:"sentinel",name:n,args:r,pos:e.pos}}peek(){return this.tokens[this.cursor]}consume(){const e=this.tokens[this.cursor];return this.cursor+=1,e}expect(e,n){const r=this.peek();if(r.kind!==e)throw new xr(`${n} (got ${HT(r)})`,r.pos);return this.consume()}}function VT(t){switch(t){case"eq":return"==";case"neq":return"!=";case"lt":return"<";case"lte":return"<=";case"gt":return">";case"gte":return">=";default:return null}}function HT(t){return t.kind==="eof"?"end of expression":t.value!==void 0?`${t.kind} ${JSON.stringify(t.value)}`:t.kind}function GT(t){e(t);function e(n){let r=0;switch(n.kind){case"literal":case"reference":r=0;break;case"unary":r=e(n.operand);break;case"binary":case"logical":r=Math.max(e(n.left),e(n.right));break;case"ternary":r=Math.max(e(n.cond),e(n.whenTrue),e(n.whenFalse));break;case"fieldAccess":r=e(n.target);break;case"indexAccess":r=Math.max(e(n.target),e(n.index));break;case"sentinel":r=n.args.length===0?0:Math.max(...n.args.map(e));break}const s=r+1;if(s>Mi.maxAstDepth)throw new xr(`expression AST exceeds depth cap of ${Mi.maxAstDepth}`,n.pos);return s}}class Xa extends tt{constructor(n){super();G(this,"typeName","reference");G(this,"path");this.path=KT(n)}static fromResourceName(n){return new Xa(iE(n))}get id(){const n=this.path.lastIndexOf("/");return n===-1?this.path:this.path.slice(n+1)}get parent(){const n=this.path.lastIndexOf("/");return n===-1?"":this.path.slice(0,n)}valueOf(){return NaN}toString(){return this.path}toJSON(){return{__type:"reference",path:this.path}}equals(n){return n instanceof Xa?this.path===n.path:!1}field(n){switch(n){case"path":return this.path;case"id":return this.id;case"parent":return this.parent;default:return null}}callMethod(n,r){return gt}}function KT(t){let e=iE(t);return e.startsWith("/")&&(e=e.slice(1)),e.endsWith("/")&&(e=e.slice(0,-1)),e}function iE(t){const e="/documents/",n=t.indexOf(e);return n===-1?t:t.slice(n+e.length)}class uo extends tt{constructor(n){super();G(this,"typeName","vector");G(this,"value");if(!Array.isArray(n))throw new TypeError("Vector: value must be a number[]");for(let r=0;r<n.length;r++)if(typeof n[r]!="number")throw new TypeError(`Vector: element at index ${r} is not a number (got ${typeof n[r]})`);this.value=Object.freeze(n.slice())}get dimension(){return this.value.length}valueOf(){return NaN}toString(){return`[${this.value.join(", ")}]`}toJSON(){return{__type__:"__vector__",value:this.value.slice()}}equals(n){if(!(n instanceof uo)||n.value.length!==this.value.length)return!1;for(let r=0;r<this.value.length;r++)if(n.value[r]!==this.value[r])return!1;return!0}callMethod(n,r){return gt}}var Ue;(function(t){t.assertEqual=s=>{};function e(s){}t.assertIs=e;function n(s){throw new Error}t.assertNever=n,t.arrayToEnum=s=>{const o={};for(const c of s)o[c]=c;return o},t.getValidEnumValues=s=>{const o=t.objectKeys(s).filter(d=>typeof s[s[d]]!="number"),c={};for(const d of o)c[d]=s[d];return t.objectValues(c)},t.objectValues=s=>t.objectKeys(s).map(function(o){return s[o]}),t.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const o=[];for(const c in s)Object.prototype.hasOwnProperty.call(s,c)&&o.push(c);return o},t.find=(s,o)=>{for(const c of s)if(o(c))return c},t.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function r(s,o=" | "){return s.map(c=>typeof c=="string"?`'${c}'`:c).join(o)}t.joinValues=r,t.jsonStringifyReplacer=(s,o)=>typeof o=="bigint"?o.toString():o})(Ue||(Ue={}));var Cx;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(Cx||(Cx={}));const ue=Ue.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Bs=t=>{switch(typeof t){case"undefined":return ue.undefined;case"string":return ue.string;case"number":return Number.isNaN(t)?ue.nan:ue.number;case"boolean":return ue.boolean;case"function":return ue.function;case"bigint":return ue.bigint;case"symbol":return ue.symbol;case"object":return Array.isArray(t)?ue.array:t===null?ue.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?ue.promise:typeof Map<"u"&&t instanceof Map?ue.map:typeof Set<"u"&&t instanceof Set?ue.set:typeof Date<"u"&&t instanceof Date?ue.date:ue.object;default:return ue.unknown}},oe=Ue.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 as extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){const n=e||function(o){return o.message},r={_errors:[]},s=o=>{for(const c of o.issues)if(c.code==="invalid_union")c.unionErrors.map(s);else if(c.code==="invalid_return_type")s(c.returnTypeError);else if(c.code==="invalid_arguments")s(c.argumentsError);else if(c.path.length===0)r._errors.push(n(c));else{let d=r,f=0;for(;f<c.path.length;){const p=c.path[f];f===c.path.length-1?(d[p]=d[p]||{_errors:[]},d[p]._errors.push(n(c))):d[p]=d[p]||{_errors:[]},d=d[p],f++}}};return s(this),r}static assert(e){if(!(e instanceof as))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Ue.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){const n={},r=[];for(const s of this.issues)if(s.path.length>0){const o=s.path[0];n[o]=n[o]||[],n[o].push(e(s))}else r.push(e(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}as.create=t=>new as(t);const jm=(t,e)=>{let n;switch(t.code){case oe.invalid_type:t.received===ue.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case oe.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,Ue.jsonStringifyReplacer)}`;break;case oe.unrecognized_keys:n=`Unrecognized key(s) in object: ${Ue.joinValues(t.keys,", ")}`;break;case oe.invalid_union:n="Invalid input";break;case oe.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${Ue.joinValues(t.options)}`;break;case oe.invalid_enum_value:n=`Invalid enum value. Expected ${Ue.joinValues(t.options)}, received '${t.received}'`;break;case oe.invalid_arguments:n="Invalid function arguments";break;case oe.invalid_return_type:n="Invalid function return type";break;case oe.invalid_date:n="Invalid date";break;case oe.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:Ue.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case oe.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case oe.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case oe.custom:n="Invalid input";break;case oe.invalid_intersection_types:n="Intersection results could not be merged";break;case oe.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case oe.not_finite:n="Number must be finite";break;default:n=e.defaultError,Ue.assertNever(t)}return{message:n}};let YT=jm;function ZT(){return YT}const WT=t=>{const{data:e,path:n,errorMaps:r,issueData:s}=t,o=[...n,...s.path||[]],c={...s,path:o};if(s.message!==void 0)return{...s,path:o,message:s.message};let d="";const f=r.filter(p=>!!p).slice().reverse();for(const p of f)d=p(c,{data:e,defaultError:d}).message;return{...s,path:o,message:d}};function ce(t,e){const n=ZT(),r=WT({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===jm?void 0:jm].filter(s=>!!s)});t.common.issues.push(r)}class on{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){const r=[];for(const s of n){if(s.status==="aborted")return ge;s.status==="dirty"&&e.dirty(),r.push(s.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){const r=[];for(const s of n){const o=await s.key,c=await s.value;r.push({key:o,value:c})}return on.mergeObjectSync(e,r)}static mergeObjectSync(e,n){const r={};for(const s of n){const{key:o,value:c}=s;if(o.status==="aborted"||c.status==="aborted")return ge;o.status==="dirty"&&e.dirty(),c.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof c.value<"u"||s.alwaysSet)&&(r[o.value]=c.value)}return{status:e.value,value:r}}}const ge=Object.freeze({status:"aborted"}),Sl=t=>({status:"dirty",value:t}),er=t=>({status:"valid",value:t}),Nx=t=>t.status==="aborted",Ox=t=>t.status==="dirty",eo=t=>t.status==="valid",Qu=t=>typeof Promise<"u"&&t instanceof Promise;var he;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(he||(he={}));class Nr{constructor(e,n,r,s){this._cachedPath=[],this.parent=e,this.data=n,this._path=r,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const Rx=(t,e)=>{if(eo(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new as(t.common.issues);return this._error=n,this._error}}};function Ee(t){if(!t)return{};const{errorMap:e,invalid_type_error:n,required_error:r,description:s}=t;if(e&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(c,d)=>{const{message:f}=t;return c.code==="invalid_enum_value"?{message:f??d.defaultError}:typeof d.data>"u"?{message:f??r??d.defaultError}:c.code!=="invalid_type"?{message:d.defaultError}:{message:f??n??d.defaultError}},description:s}}class Te{get description(){return this._def.description}_getType(e){return Bs(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:Bs(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new on,ctx:{common:e.parent.common,data:e.data,parsedType:Bs(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const n=this._parse(e);if(Qu(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){const n=this._parse(e);return Promise.resolve(n)}parse(e,n){const r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){const r={common:{issues:[],async:(n==null?void 0:n.async)??!1,contextualErrorMap:n==null?void 0:n.errorMap},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Bs(e)},s=this._parseSync({data:e,path:r.path,parent:r});return Rx(r,s)}"~validate"(e){var r,s;const n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Bs(e)};if(!this["~standard"].async)try{const o=this._parseSync({data:e,path:[],parent:n});return eo(o)?{value:o.value}:{issues:n.common.issues}}catch(o){(s=(r=o==null?void 0:o.message)==null?void 0:r.toLowerCase())!=null&&s.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(o=>eo(o)?{value:o.value}:{issues:n.common.issues})}async parseAsync(e,n){const r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){const r={common:{issues:[],contextualErrorMap:n==null?void 0:n.errorMap,async:!0},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Bs(e)},s=this._parse({data:e,path:r.path,parent:r}),o=await(Qu(s)?s:Promise.resolve(s));return Rx(r,o)}refine(e,n){const r=s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n;return this._refinement((s,o)=>{const c=e(s),d=()=>o.addIssue({code:oe.custom,...r(s)});return typeof Promise<"u"&&c instanceof Promise?c.then(f=>f?!0:(d(),!1)):c?!0:(d(),!1)})}refinement(e,n){return this._refinement((r,s)=>e(r)?!0:(s.addIssue(typeof n=="function"?n(r,s):n),!1))}_refinement(e){return new qi({schema:this,typeName:be.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return jr.create(this,this._def)}nullable(){return Fi.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ar.create(this)}promise(){return rd.create(this,this._def)}or(e){return Ml.create([this,e],this._def)}and(e){return td.create(this,e,this._def)}transform(e){return new qi({...Ee(this._def),schema:this,typeName:be.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const n=typeof e=="function"?e:()=>e;return new sd({...Ee(this._def),innerType:this,defaultValue:n,typeName:be.ZodDefault})}brand(){return new cE({typeName:be.ZodBranded,type:this,...Ee(this._def)})}catch(e){const n=typeof e=="function"?e:()=>e;return new id({...Ee(this._def),innerType:this,catchValue:n,typeName:be.ZodCatch})}describe(e){const n=this.constructor;return new n({...this._def,description:e})}pipe(e){return Jy.create(this,e)}readonly(){return ad.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const QT=/^c[^\s-]{8,}$/i,JT=/^[0-9a-z]+$/,XT=/^[0-9A-HJKMNP-TV-Z]{26}$/i,e2=/^[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,t2=/^[a-z0-9_-]{21}$/i,n2=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,r2=/^[-+]?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)?)??$/,s2=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,i2="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let $p;const a2=/^(?:(?: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])$/,o2=/^(?:(?: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])$/,l2=/^(([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]))$/,c2=/^(([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])$/,u2=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,d2=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,aE="((\\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])))",f2=new RegExp(`^${aE}$`);function oE(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);const n=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function h2(t){return new RegExp(`^${oE(t)}$`)}function p2(t){let e=`${aE}T${oE(t)}`;const n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function m2(t,e){return!!((e==="v4"||!e)&&a2.test(t)||(e==="v6"||!e)&&l2.test(t))}function y2(t,e){if(!n2.test(t))return!1;try{const[n]=t.split(".");if(!n)return!1;const r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),s=JSON.parse(atob(r));return!(typeof s!="object"||s===null||"typ"in s&&(s==null?void 0:s.typ)!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function g2(t,e){return!!((e==="v4"||!e)&&o2.test(t)||(e==="v6"||!e)&&c2.test(t))}class _r extends Te{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==ue.string){const o=this._getOrReturnCtx(e);return ce(o,{code:oe.invalid_type,expected:ue.string,received:o.parsedType}),ge}const r=new on;let s;for(const o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(s=this._getOrReturnCtx(e,s),ce(s,{code:oe.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="max")e.data.length>o.value&&(s=this._getOrReturnCtx(e,s),ce(s,{code:oe.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="length"){const c=e.data.length>o.value,d=e.data.length<o.value;(c||d)&&(s=this._getOrReturnCtx(e,s),c?ce(s,{code:oe.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):d&&ce(s,{code:oe.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),r.dirty())}else if(o.kind==="email")s2.test(e.data)||(s=this._getOrReturnCtx(e,s),ce(s,{validation:"email",code:oe.invalid_string,message:o.message}),r.dirty());else if(o.kind==="emoji")$p||($p=new RegExp(i2,"u")),$p.test(e.data)||(s=this._getOrReturnCtx(e,s),ce(s,{validation:"emoji",code:oe.invalid_string,message:o.message}),r.dirty());else if(o.kind==="uuid")e2.test(e.data)||(s=this._getOrReturnCtx(e,s),ce(s,{validation:"uuid",code:oe.invalid_string,message:o.message}),r.dirty());else if(o.kind==="nanoid")t2.test(e.data)||(s=this._getOrReturnCtx(e,s),ce(s,{validation:"nanoid",code:oe.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid")QT.test(e.data)||(s=this._getOrReturnCtx(e,s),ce(s,{validation:"cuid",code:oe.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid2")JT.test(e.data)||(s=this._getOrReturnCtx(e,s),ce(s,{validation:"cuid2",code:oe.invalid_string,message:o.message}),r.dirty());else if(o.kind==="ulid")XT.test(e.data)||(s=this._getOrReturnCtx(e,s),ce(s,{validation:"ulid",code:oe.invalid_string,message:o.message}),r.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),ce(s,{validation:"url",code:oe.invalid_string,message:o.message}),r.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),ce(s,{validation:"regex",code:oe.invalid_string,message:o.message}),r.dirty())):o.kind==="trim"?e.data=e.data.trim():o.kind==="includes"?e.data.includes(o.value,o.position)||(s=this._getOrReturnCtx(e,s),ce(s,{code:oe.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),r.dirty()):o.kind==="toLowerCase"?e.data=e.data.toLowerCase():o.kind==="toUpperCase"?e.data=e.data.toUpperCase():o.kind==="startsWith"?e.data.startsWith(o.value)||(s=this._getOrReturnCtx(e,s),ce(s,{code:oe.invalid_string,validation:{startsWith:o.value},message:o.message}),r.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(s=this._getOrReturnCtx(e,s),ce(s,{code:oe.invalid_string,validation:{endsWith:o.value},message:o.message}),r.dirty()):o.kind==="datetime"?p2(o).test(e.data)||(s=this._getOrReturnCtx(e,s),ce(s,{code:oe.invalid_string,validation:"datetime",message:o.message}),r.dirty()):o.kind==="date"?f2.test(e.data)||(s=this._getOrReturnCtx(e,s),ce(s,{code:oe.invalid_string,validation:"date",message:o.message}),r.dirty()):o.kind==="time"?h2(o).test(e.data)||(s=this._getOrReturnCtx(e,s),ce(s,{code:oe.invalid_string,validation:"time",message:o.message}),r.dirty()):o.kind==="duration"?r2.test(e.data)||(s=this._getOrReturnCtx(e,s),ce(s,{validation:"duration",code:oe.invalid_string,message:o.message}),r.dirty()):o.kind==="ip"?m2(e.data,o.version)||(s=this._getOrReturnCtx(e,s),ce(s,{validation:"ip",code:oe.invalid_string,message:o.message}),r.dirty()):o.kind==="jwt"?y2(e.data,o.alg)||(s=this._getOrReturnCtx(e,s),ce(s,{validation:"jwt",code:oe.invalid_string,message:o.message}),r.dirty()):o.kind==="cidr"?g2(e.data,o.version)||(s=this._getOrReturnCtx(e,s),ce(s,{validation:"cidr",code:oe.invalid_string,message:o.message}),r.dirty()):o.kind==="base64"?u2.test(e.data)||(s=this._getOrReturnCtx(e,s),ce(s,{validation:"base64",code:oe.invalid_string,message:o.message}),r.dirty()):o.kind==="base64url"?d2.test(e.data)||(s=this._getOrReturnCtx(e,s),ce(s,{validation:"base64url",code:oe.invalid_string,message:o.message}),r.dirty()):Ue.assertNever(o);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(s=>e.test(s),{validation:n,code:oe.invalid_string,...he.errToObj(r)})}_addCheck(e){return new _r({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...he.errToObj(e)})}url(e){return this._addCheck({kind:"url",...he.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...he.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...he.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...he.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...he.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...he.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...he.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...he.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...he.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...he.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...he.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...he.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,offset:(e==null?void 0:e.offset)??!1,local:(e==null?void 0:e.local)??!1,...he.errToObj(e==null?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,...he.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...he.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...he.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n==null?void 0:n.position,...he.errToObj(n==null?void 0:n.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...he.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...he.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...he.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...he.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...he.errToObj(n)})}nonempty(e){return this.min(1,he.errToObj(e))}trim(){return new _r({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new _r({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new _r({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}}_r.create=t=>new _r({checks:[],typeName:be.ZodString,coerce:(t==null?void 0:t.coerce)??!1,...Ee(t)});function b2(t,e){const n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,s=n>r?n:r,o=Number.parseInt(t.toFixed(s).replace(".","")),c=Number.parseInt(e.toFixed(s).replace(".",""));return o%c/10**s}class $i extends Te{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==ue.number){const o=this._getOrReturnCtx(e);return ce(o,{code:oe.invalid_type,expected:ue.number,received:o.parsedType}),ge}let r;const s=new on;for(const o of this._def.checks)o.kind==="int"?Ue.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),ce(r,{code:oe.invalid_type,expected:"integer",received:"float",message:o.message}),s.dirty()):o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(r=this._getOrReturnCtx(e,r),ce(r,{code:oe.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(r=this._getOrReturnCtx(e,r),ce(r,{code:oe.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="multipleOf"?b2(e.data,o.value)!==0&&(r=this._getOrReturnCtx(e,r),ce(r,{code:oe.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),ce(r,{code:oe.not_finite,message:o.message}),s.dirty()):Ue.assertNever(o);return{status:s.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,he.toString(n))}gt(e,n){return this.setLimit("min",e,!1,he.toString(n))}lte(e,n){return this.setLimit("max",e,!0,he.toString(n))}lt(e,n){return this.setLimit("max",e,!1,he.toString(n))}setLimit(e,n,r,s){return new $i({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:he.toString(s)}]})}_addCheck(e){return new $i({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:he.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:he.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:he.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:he.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:he.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:he.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:he.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:he.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:he.toString(e)})}get minValue(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&Ue.isInteger(e.value))}get isFinite(){let e=null,n=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(n)&&Number.isFinite(e)}}$i.create=t=>new $i({checks:[],typeName:be.ZodNumber,coerce:(t==null?void 0:t.coerce)||!1,...Ee(t)});class Il extends Te{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==ue.bigint)return this._getInvalidInput(e);let r;const s=new on;for(const o of this._def.checks)o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(r=this._getOrReturnCtx(e,r),ce(r,{code:oe.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(r=this._getOrReturnCtx(e,r),ce(r,{code:oe.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),ce(r,{code:oe.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):Ue.assertNever(o);return{status:s.value,value:e.data}}_getInvalidInput(e){const n=this._getOrReturnCtx(e);return ce(n,{code:oe.invalid_type,expected:ue.bigint,received:n.parsedType}),ge}gte(e,n){return this.setLimit("min",e,!0,he.toString(n))}gt(e,n){return this.setLimit("min",e,!1,he.toString(n))}lte(e,n){return this.setLimit("max",e,!0,he.toString(n))}lt(e,n){return this.setLimit("max",e,!1,he.toString(n))}setLimit(e,n,r,s){return new Il({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:he.toString(s)}]})}_addCheck(e){return new Il({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:he.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:he.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:he.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:he.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:he.toString(n)})}get minValue(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}}Il.create=t=>new Il({checks:[],typeName:be.ZodBigInt,coerce:(t==null?void 0:t.coerce)??!1,...Ee(t)});class Ju extends Te{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==ue.boolean){const r=this._getOrReturnCtx(e);return ce(r,{code:oe.invalid_type,expected:ue.boolean,received:r.parsedType}),ge}return er(e.data)}}Ju.create=t=>new Ju({typeName:be.ZodBoolean,coerce:(t==null?void 0:t.coerce)||!1,...Ee(t)});class Xu extends Te{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==ue.date){const o=this._getOrReturnCtx(e);return ce(o,{code:oe.invalid_type,expected:ue.date,received:o.parsedType}),ge}if(Number.isNaN(e.data.getTime())){const o=this._getOrReturnCtx(e);return ce(o,{code:oe.invalid_date}),ge}const r=new on;let s;for(const o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(s=this._getOrReturnCtx(e,s),ce(s,{code:oe.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),r.dirty()):o.kind==="max"?e.data.getTime()>o.value&&(s=this._getOrReturnCtx(e,s),ce(s,{code:oe.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),r.dirty()):Ue.assertNever(o);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Xu({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:he.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:he.toString(n)})}get minDate(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}}Xu.create=t=>new Xu({checks:[],coerce:(t==null?void 0:t.coerce)||!1,typeName:be.ZodDate,...Ee(t)});class Tx extends Te{_parse(e){if(this._getType(e)!==ue.symbol){const r=this._getOrReturnCtx(e);return ce(r,{code:oe.invalid_type,expected:ue.symbol,received:r.parsedType}),ge}return er(e.data)}}Tx.create=t=>new Tx({typeName:be.ZodSymbol,...Ee(t)});class km extends Te{_parse(e){if(this._getType(e)!==ue.undefined){const r=this._getOrReturnCtx(e);return ce(r,{code:oe.invalid_type,expected:ue.undefined,received:r.parsedType}),ge}return er(e.data)}}km.create=t=>new km({typeName:be.ZodUndefined,...Ee(t)});class ed extends Te{_parse(e){if(this._getType(e)!==ue.null){const r=this._getOrReturnCtx(e);return ce(r,{code:oe.invalid_type,expected:ue.null,received:r.parsedType}),ge}return er(e.data)}}ed.create=t=>new ed({typeName:be.ZodNull,...Ee(t)});class Dx extends Te{constructor(){super(...arguments),this._any=!0}_parse(e){return er(e.data)}}Dx.create=t=>new Dx({typeName:be.ZodAny,...Ee(t)});class Cm extends Te{constructor(){super(...arguments),this._unknown=!0}_parse(e){return er(e.data)}}Cm.create=t=>new Cm({typeName:be.ZodUnknown,...Ee(t)});class Zs extends Te{_parse(e){const n=this._getOrReturnCtx(e);return ce(n,{code:oe.invalid_type,expected:ue.never,received:n.parsedType}),ge}}Zs.create=t=>new Zs({typeName:be.ZodNever,...Ee(t)});class Ix extends Te{_parse(e){if(this._getType(e)!==ue.undefined){const r=this._getOrReturnCtx(e);return ce(r,{code:oe.invalid_type,expected:ue.void,received:r.parsedType}),ge}return er(e.data)}}Ix.create=t=>new Ix({typeName:be.ZodVoid,...Ee(t)});class Ar extends Te{_parse(e){const{ctx:n,status:r}=this._processInputParams(e),s=this._def;if(n.parsedType!==ue.array)return ce(n,{code:oe.invalid_type,expected:ue.array,received:n.parsedType}),ge;if(s.exactLength!==null){const c=n.data.length>s.exactLength.value,d=n.data.length<s.exactLength.value;(c||d)&&(ce(n,{code:c?oe.too_big:oe.too_small,minimum:d?s.exactLength.value:void 0,maximum:c?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(s.minLength!==null&&n.data.length<s.minLength.value&&(ce(n,{code:oe.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&n.data.length>s.maxLength.value&&(ce(n,{code:oe.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((c,d)=>s.type._parseAsync(new Nr(n,c,n.path,d)))).then(c=>on.mergeArray(r,c));const o=[...n.data].map((c,d)=>s.type._parseSync(new Nr(n,c,n.path,d)));return on.mergeArray(r,o)}get element(){return this._def.type}min(e,n){return new Ar({...this._def,minLength:{value:e,message:he.toString(n)}})}max(e,n){return new Ar({...this._def,maxLength:{value:e,message:he.toString(n)}})}length(e,n){return new Ar({...this._def,exactLength:{value:e,message:he.toString(n)}})}nonempty(e){return this.min(1,e)}}Ar.create=(t,e)=>new Ar({type:t,minLength:null,maxLength:null,exactLength:null,typeName:be.ZodArray,...Ee(e)});function Pa(t){if(t instanceof mt){const e={};for(const n in t.shape){const r=t.shape[n];e[n]=jr.create(Pa(r))}return new mt({...t._def,shape:()=>e})}else return t instanceof Ar?new Ar({...t._def,type:Pa(t.element)}):t instanceof jr?jr.create(Pa(t.unwrap())):t instanceof Fi?Fi.create(Pa(t.unwrap())):t instanceof Bi?Bi.create(t.items.map(e=>Pa(e))):t}class mt extends Te{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),n=Ue.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==ue.object){const p=this._getOrReturnCtx(e);return ce(p,{code:oe.invalid_type,expected:ue.object,received:p.parsedType}),ge}const{status:r,ctx:s}=this._processInputParams(e),{shape:o,keys:c}=this._getCached(),d=[];if(!(this._def.catchall instanceof Zs&&this._def.unknownKeys==="strip"))for(const p in s.data)c.includes(p)||d.push(p);const f=[];for(const p of c){const g=o[p],b=s.data[p];f.push({key:{status:"valid",value:p},value:g._parse(new Nr(s,b,s.path,p)),alwaysSet:p in s.data})}if(this._def.catchall instanceof Zs){const p=this._def.unknownKeys;if(p==="passthrough")for(const g of d)f.push({key:{status:"valid",value:g},value:{status:"valid",value:s.data[g]}});else if(p==="strict")d.length>0&&(ce(s,{code:oe.unrecognized_keys,keys:d}),r.dirty());else if(p!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const p=this._def.catchall;for(const g of d){const b=s.data[g];f.push({key:{status:"valid",value:g},value:p._parse(new Nr(s,b,s.path,g)),alwaysSet:g in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const p=[];for(const g of f){const b=await g.key,v=await g.value;p.push({key:b,value:v,alwaysSet:g.alwaysSet})}return p}).then(p=>on.mergeObjectSync(r,p)):on.mergeObjectSync(r,f)}get shape(){return this._def.shape()}strict(e){return he.errToObj,new mt({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{var o,c;const s=((c=(o=this._def).errorMap)==null?void 0:c.call(o,n,r).message)??r.defaultError;return n.code==="unrecognized_keys"?{message:he.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new mt({...this._def,unknownKeys:"strip"})}passthrough(){return new mt({...this._def,unknownKeys:"passthrough"})}extend(e){return new mt({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new mt({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:be.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new mt({...this._def,catchall:e})}pick(e){const n={};for(const r of Ue.objectKeys(e))e[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new mt({...this._def,shape:()=>n})}omit(e){const n={};for(const r of Ue.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new mt({...this._def,shape:()=>n})}deepPartial(){return Pa(this)}partial(e){const n={};for(const r of Ue.objectKeys(this.shape)){const s=this.shape[r];e&&!e[r]?n[r]=s:n[r]=s.optional()}return new mt({...this._def,shape:()=>n})}required(e){const n={};for(const r of Ue.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let o=this.shape[r];for(;o instanceof jr;)o=o._def.innerType;n[r]=o}return new mt({...this._def,shape:()=>n})}keyof(){return lE(Ue.objectKeys(this.shape))}}mt.create=(t,e)=>new mt({shape:()=>t,unknownKeys:"strip",catchall:Zs.create(),typeName:be.ZodObject,...Ee(e)});mt.strictCreate=(t,e)=>new mt({shape:()=>t,unknownKeys:"strict",catchall:Zs.create(),typeName:be.ZodObject,...Ee(e)});mt.lazycreate=(t,e)=>new mt({shape:t,unknownKeys:"strip",catchall:Zs.create(),typeName:be.ZodObject,...Ee(e)});class Ml extends Te{_parse(e){const{ctx:n}=this._processInputParams(e),r=this._def.options;function s(o){for(const d of o)if(d.result.status==="valid")return d.result;for(const d of o)if(d.result.status==="dirty")return n.common.issues.push(...d.ctx.common.issues),d.result;const c=o.map(d=>new as(d.ctx.common.issues));return ce(n,{code:oe.invalid_union,unionErrors:c}),ge}if(n.common.async)return Promise.all(r.map(async o=>{const c={...n,common:{...n.common,issues:[]},parent:null};return{result:await o._parseAsync({data:n.data,path:n.path,parent:c}),ctx:c}})).then(s);{let o;const c=[];for(const f of r){const p={...n,common:{...n.common,issues:[]},parent:null},g=f._parseSync({data:n.data,path:n.path,parent:p});if(g.status==="valid")return g;g.status==="dirty"&&!o&&(o={result:g,ctx:p}),p.common.issues.length&&c.push(p.common.issues)}if(o)return n.common.issues.push(...o.ctx.common.issues),o.result;const d=c.map(f=>new as(f));return ce(n,{code:oe.invalid_union,unionErrors:d}),ge}}get options(){return this._def.options}}Ml.create=(t,e)=>new Ml({options:t,typeName:be.ZodUnion,...Ee(e)});const es=t=>t instanceof Om?es(t.schema):t instanceof qi?es(t.innerType()):t instanceof Ul?[t.value]:t instanceof Ws?t.options:t instanceof Rm?Ue.objectValues(t.enum):t instanceof sd?es(t._def.innerType):t instanceof km?[void 0]:t instanceof ed?[null]:t instanceof jr?[void 0,...es(t.unwrap())]:t instanceof Fi?[null,...es(t.unwrap())]:t instanceof cE||t instanceof ad?es(t.unwrap()):t instanceof id?es(t._def.innerType):[];class Qy extends Te{_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==ue.object)return ce(n,{code:oe.invalid_type,expected:ue.object,received:n.parsedType}),ge;const r=this.discriminator,s=n.data[r],o=this.optionsMap.get(s);return o?n.common.async?o._parseAsync({data:n.data,path:n.path,parent:n}):o._parseSync({data:n.data,path:n.path,parent:n}):(ce(n,{code:oe.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),ge)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){const s=new Map;for(const o of n){const c=es(o.shape[e]);if(!c.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const d of c){if(s.has(d))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(d)}`);s.set(d,o)}}return new Qy({typeName:be.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:s,...Ee(r)})}}function Nm(t,e){const n=Bs(t),r=Bs(e);if(t===e)return{valid:!0,data:t};if(n===ue.object&&r===ue.object){const s=Ue.objectKeys(e),o=Ue.objectKeys(t).filter(d=>s.indexOf(d)!==-1),c={...t,...e};for(const d of o){const f=Nm(t[d],e[d]);if(!f.valid)return{valid:!1};c[d]=f.data}return{valid:!0,data:c}}else if(n===ue.array&&r===ue.array){if(t.length!==e.length)return{valid:!1};const s=[];for(let o=0;o<t.length;o++){const c=t[o],d=e[o],f=Nm(c,d);if(!f.valid)return{valid:!1};s.push(f.data)}return{valid:!0,data:s}}else return n===ue.date&&r===ue.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}class td extends Te{_parse(e){const{status:n,ctx:r}=this._processInputParams(e),s=(o,c)=>{if(Nx(o)||Nx(c))return ge;const d=Nm(o.value,c.value);return d.valid?((Ox(o)||Ox(c))&&n.dirty(),{status:n.value,value:d.data}):(ce(r,{code:oe.invalid_intersection_types}),ge)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([o,c])=>s(o,c)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}td.create=(t,e,n)=>new td({left:t,right:e,typeName:be.ZodIntersection,...Ee(n)});class Bi extends Te{_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==ue.array)return ce(r,{code:oe.invalid_type,expected:ue.array,received:r.parsedType}),ge;if(r.data.length<this._def.items.length)return ce(r,{code:oe.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),ge;!this._def.rest&&r.data.length>this._def.items.length&&(ce(r,{code:oe.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const o=[...r.data].map((c,d)=>{const f=this._def.items[d]||this._def.rest;return f?f._parse(new Nr(r,c,r.path,d)):null}).filter(c=>!!c);return r.common.async?Promise.all(o).then(c=>on.mergeArray(n,c)):on.mergeArray(n,o)}get items(){return this._def.items}rest(e){return new Bi({...this._def,rest:e})}}Bi.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Bi({items:t,typeName:be.ZodTuple,rest:null,...Ee(e)})};class nd extends Te{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==ue.object)return ce(r,{code:oe.invalid_type,expected:ue.object,received:r.parsedType}),ge;const s=[],o=this._def.keyType,c=this._def.valueType;for(const d in r.data)s.push({key:o._parse(new Nr(r,d,r.path,d)),value:c._parse(new Nr(r,r.data[d],r.path,d)),alwaysSet:d in r.data});return r.common.async?on.mergeObjectAsync(n,s):on.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof Te?new nd({keyType:e,valueType:n,typeName:be.ZodRecord,...Ee(r)}):new nd({keyType:_r.create(),valueType:e,typeName:be.ZodRecord,...Ee(n)})}}class Mx extends Te{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==ue.map)return ce(r,{code:oe.invalid_type,expected:ue.map,received:r.parsedType}),ge;const s=this._def.keyType,o=this._def.valueType,c=[...r.data.entries()].map(([d,f],p)=>({key:s._parse(new Nr(r,d,r.path,[p,"key"])),value:o._parse(new Nr(r,f,r.path,[p,"value"]))}));if(r.common.async){const d=new Map;return Promise.resolve().then(async()=>{for(const f of c){const p=await f.key,g=await f.value;if(p.status==="aborted"||g.status==="aborted")return ge;(p.status==="dirty"||g.status==="dirty")&&n.dirty(),d.set(p.value,g.value)}return{status:n.value,value:d}})}else{const d=new Map;for(const f of c){const p=f.key,g=f.value;if(p.status==="aborted"||g.status==="aborted")return ge;(p.status==="dirty"||g.status==="dirty")&&n.dirty(),d.set(p.value,g.value)}return{status:n.value,value:d}}}}Mx.create=(t,e,n)=>new Mx({valueType:e,keyType:t,typeName:be.ZodMap,...Ee(n)});class Ll extends Te{_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==ue.set)return ce(r,{code:oe.invalid_type,expected:ue.set,received:r.parsedType}),ge;const s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(ce(r,{code:oe.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),n.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&(ce(r,{code:oe.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());const o=this._def.valueType;function c(f){const p=new Set;for(const g of f){if(g.status==="aborted")return ge;g.status==="dirty"&&n.dirty(),p.add(g.value)}return{status:n.value,value:p}}const d=[...r.data.values()].map((f,p)=>o._parse(new Nr(r,f,r.path,p)));return r.common.async?Promise.all(d).then(f=>c(f)):c(d)}min(e,n){return new Ll({...this._def,minSize:{value:e,message:he.toString(n)}})}max(e,n){return new Ll({...this._def,maxSize:{value:e,message:he.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}}Ll.create=(t,e)=>new Ll({valueType:t,minSize:null,maxSize:null,typeName:be.ZodSet,...Ee(e)});class Om extends Te{get schema(){return this._def.getter()}_parse(e){const{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}Om.create=(t,e)=>new Om({getter:t,typeName:be.ZodLazy,...Ee(e)});class Ul extends Te{_parse(e){if(e.data!==this._def.value){const n=this._getOrReturnCtx(e);return ce(n,{received:n.data,code:oe.invalid_literal,expected:this._def.value}),ge}return{status:"valid",value:e.data}}get value(){return this._def.value}}Ul.create=(t,e)=>new Ul({value:t,typeName:be.ZodLiteral,...Ee(e)});function lE(t,e){return new Ws({values:t,typeName:be.ZodEnum,...Ee(e)})}class Ws extends Te{_parse(e){if(typeof e.data!="string"){const n=this._getOrReturnCtx(e),r=this._def.values;return ce(n,{expected:Ue.joinValues(r),received:n.parsedType,code:oe.invalid_type}),ge}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const n=this._getOrReturnCtx(e),r=this._def.values;return ce(n,{received:n.data,code:oe.invalid_enum_value,options:r}),ge}return er(e.data)}get options(){return this._def.values}get enum(){const e={};for(const n of this._def.values)e[n]=n;return e}get Values(){const e={};for(const n of this._def.values)e[n]=n;return e}get Enum(){const e={};for(const n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return Ws.create(e,{...this._def,...n})}exclude(e,n=this._def){return Ws.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}}Ws.create=lE;class Rm extends Te{_parse(e){const n=Ue.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==ue.string&&r.parsedType!==ue.number){const s=Ue.objectValues(n);return ce(r,{expected:Ue.joinValues(s),received:r.parsedType,code:oe.invalid_type}),ge}if(this._cache||(this._cache=new Set(Ue.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const s=Ue.objectValues(n);return ce(r,{received:r.data,code:oe.invalid_enum_value,options:s}),ge}return er(e.data)}get enum(){return this._def.values}}Rm.create=(t,e)=>new Rm({values:t,typeName:be.ZodNativeEnum,...Ee(e)});class rd extends Te{unwrap(){return this._def.type}_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==ue.promise&&n.common.async===!1)return ce(n,{code:oe.invalid_type,expected:ue.promise,received:n.parsedType}),ge;const r=n.parsedType===ue.promise?n.data:Promise.resolve(n.data);return er(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}}rd.create=(t,e)=>new rd({type:t,typeName:be.ZodPromise,...Ee(e)});class qi extends Te{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===be.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:n,ctx:r}=this._processInputParams(e),s=this._def.effect||null,o={addIssue:c=>{ce(r,c),c.fatal?n.abort():n.dirty()},get path(){return r.path}};if(o.addIssue=o.addIssue.bind(o),s.type==="preprocess"){const c=s.transform(r.data,o);if(r.common.async)return Promise.resolve(c).then(async d=>{if(n.value==="aborted")return ge;const f=await this._def.schema._parseAsync({data:d,path:r.path,parent:r});return f.status==="aborted"?ge:f.status==="dirty"||n.value==="dirty"?Sl(f.value):f});{if(n.value==="aborted")return ge;const d=this._def.schema._parseSync({data:c,path:r.path,parent:r});return d.status==="aborted"?ge:d.status==="dirty"||n.value==="dirty"?Sl(d.value):d}}if(s.type==="refinement"){const c=d=>{const f=s.refinement(d,o);if(r.common.async)return Promise.resolve(f);if(f instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return d};if(r.common.async===!1){const d=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return d.status==="aborted"?ge:(d.status==="dirty"&&n.dirty(),c(d.value),{status:n.value,value:d.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(d=>d.status==="aborted"?ge:(d.status==="dirty"&&n.dirty(),c(d.value).then(()=>({status:n.value,value:d.value}))))}if(s.type==="transform")if(r.common.async===!1){const c=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!eo(c))return ge;const d=s.transform(c.value,o);if(d instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:d}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(c=>eo(c)?Promise.resolve(s.transform(c.value,o)).then(d=>({status:n.value,value:d})):ge);Ue.assertNever(s)}}qi.create=(t,e,n)=>new qi({schema:t,typeName:be.ZodEffects,effect:e,...Ee(n)});qi.createWithPreprocess=(t,e,n)=>new qi({schema:e,effect:{type:"preprocess",transform:t},typeName:be.ZodEffects,...Ee(n)});class jr extends Te{_parse(e){return this._getType(e)===ue.undefined?er(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}jr.create=(t,e)=>new jr({innerType:t,typeName:be.ZodOptional,...Ee(e)});class Fi extends Te{_parse(e){return this._getType(e)===ue.null?er(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Fi.create=(t,e)=>new Fi({innerType:t,typeName:be.ZodNullable,...Ee(e)});class sd extends Te{_parse(e){const{ctx:n}=this._processInputParams(e);let r=n.data;return n.parsedType===ue.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}sd.create=(t,e)=>new sd({innerType:t,typeName:be.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Ee(e)});class id extends Te{_parse(e){const{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Qu(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new as(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new as(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}id.create=(t,e)=>new id({innerType:t,typeName:be.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Ee(e)});class Lx extends Te{_parse(e){if(this._getType(e)!==ue.nan){const r=this._getOrReturnCtx(e);return ce(r,{code:oe.invalid_type,expected:ue.nan,received:r.parsedType}),ge}return{status:"valid",value:e.data}}}Lx.create=t=>new Lx({typeName:be.ZodNaN,...Ee(t)});class cE extends Te{_parse(e){const{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}}class Jy extends Te{_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{const o=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?ge:o.status==="dirty"?(n.dirty(),Sl(o.value)):this._def.out._parseAsync({data:o.value,path:r.path,parent:r})})();{const s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?ge:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(e,n){return new Jy({in:e,out:n,typeName:be.ZodPipeline})}}class ad extends Te{_parse(e){const n=this._def.innerType._parse(e),r=s=>(eo(s)&&(s.value=Object.freeze(s.value)),s);return Qu(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}}ad.create=(t,e)=>new ad({innerType:t,typeName:be.ZodReadonly,...Ee(e)});var be;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(be||(be={}));const vn=_r.create,Ux=$i.create,$l=Ju.create,uE=ed.create,rs=Cm.create;Zs.create;const dE=Ar.create,Mn=mt.create,Dd=Ml.create,v2=Qy.create;td.create;Bi.create;const Qs=nd.create,_u=Ul.create,to=Ws.create;rd.create;jr.create;Fi.create;const w2=["get","list","create","update","delete"],x2=Mn({uid:vn(),token:Qs(rs()).optional()}),S2=Mn({function:to(["get","exists"]).describe("Firestore function to mock"),path:vn().describe('Document path, e.g. "users/alice"'),result:Dd([Qs(rs()),$l()]).describe("Document data for get, boolean for exists")}),_2=v2("kind",[Mn({kind:_u("create")}),Mn({kind:_u("set"),merge:$l()}),Mn({kind:_u("update")}),Mn({kind:_u("delete")})]),E2=Mn({limit:Ux().optional(),offset:Ux().optional(),orderBy:vn().optional()});Mn({description:vn().describe("Human-readable description of what this test verifies"),expectation:to(["ALLOW","DENY"]).describe("Expected outcome"),method:to(w2).describe("Firestore method to test"),path:vn().describe('Document path, e.g. "users/alice"'),auth:Dd([x2,uE()]).optional().describe("Auth context; null or omitted for unauthenticated"),data:Qs(rs()).optional().describe("request.resource.data for write operations"),resource:Qs(rs()).optional().describe("Existing document data (resource.data)"),functionMocks:dE(S2).optional().describe("Mock get()/exists() calls in rules"),query:E2.optional().describe("request.query payload (list ops only): limit/offset/orderBy."),requestTime:vn().optional().describe("Override for request.time (ISO-8601). Defaults to wallclock."),writeMode:_2.optional().describe("Optional write-mode override; controls update merge semantics and getAfter() projection.")});function Ni(t){if(t.decision==="UNSUPPORTED")return;const e=t.decision==="ALLOW",n=e?t.trace.find(s=>s.verdict==="ALLOW"):t.trace.find(s=>s.verdict==="DENY"||s.verdict==="ERROR")??t.trace[t.trace.length-1];if(!n)return;const r={verdict:e?"allow":"deny"};return n.line!==void 0&&(r.line=n.line),n.conditionText!==void 0&&(r.expression=n.conditionText),n.expressionTrace!==void 0&&(r.expressionTrace=n.expressionTrace),r.line!==void 0||r.expression!==void 0||r.expressionTrace!==void 0?r:void 0}function Re(t){const e=[];for(const n of t.notes)e.push(n);for(const n of t.trace){const r=n.operations.join(","),s=`Rule #${n.ruleIndex} (${r})`;n.verdict==="ALLOW"?e.push(`${s} → ALLOW`):n.verdict==="DENY"?e.push(`${s} → deny`):n.verdict==="UNSUPPORTED"?e.push(`${s} → unsupported: ${n.message??""}`):e.push(`${s} → error: ${n.message??""}`)}return e.push(`Simulated: ${t.decision}`),e}Mn({function:to(["get","exists"]).describe("Cross-service Firestore function to mock"),path:vn().describe('Firestore document path in collection/doc form, e.g. "users/alice"'),result:Dd([Qs(rs()),$l()]).describe("Document fields for get, boolean for exists")});class Ln extends Error{constructor(n,r,s){super(r);G(this,"code");G(this,"pos");this.name="EvalError",this.code=n,this.pos=s}}function Yl(t){if(typeof t!="object"||t===null)return!1;const e=t,n=e.__type,r=Object.keys(e);switch(n){case"serverTimestamp":case"deleteField":return r.length===1;case"increment":return r.length===2&&typeof e.value=="number";case"arrayUnion":case"arrayRemove":return r.length===2&&Array.isArray(e.values);default:return!1}}function Xn(t,e){return new Ln("type-mismatch",e,t.pos)}function Un(t,e){switch(t.kind){case"literal":return t.value;case"reference":return A2(t,e);case"sentinel":return j2(t,e);case"unary":return k2(t,e);case"binary":return C2(t,e);case"logical":return O2(t,e);case"ternary":return R2(t,e);case"fieldAccess":return T2(t,e);case"indexAccess":return D2(t,e)}}function A2(t,e){if(!Object.prototype.hasOwnProperty.call(e.reads,t.alias))throw new Ln("unknown-reference",`unknown alias '$${t.alias}' (not in reads). Hint: aliases are case-sensitive; sentinels use '@' not '$'.`,t.pos);return e.reads[t.alias]??null}function j2(t,e){const n=t.args.map(r=>{const s=Un(r,e);if(Yl(s))throw new Ln("sentinel-misuse",`sentinel '@${s.__type}' cannot be a sentinel argument`,r.pos);return s});switch(t.name){case"serverTimestamp":return{__type:"serverTimestamp"};case"deleteField":return{__type:"deleteField"};case"increment":{const r=n[0];if(typeof r!="number")throw Xn(t,`'@increment' expects a numeric argument, got ${Zt(r)}`);return od(r,t),{__type:"increment",value:r}}case"arrayUnion":return{__type:"arrayUnion",values:n};case"arrayRemove":return{__type:"arrayRemove",values:n}}}function k2(t,e){const n=Un(t.operand,e);if(Tm(n,t),t.op==="-"){if(typeof n!="number")throw Xn(t,`unary '-' expects a number, got ${Zt(n)}`);const r=-n;return od(r,t),r}if(typeof n!="boolean")throw Xn(t,`unary '!' expects a boolean, got ${Zt(n)}`);return!n}function C2(t,e){const n=Un(t.left,e),r=Un(t.right,e);switch(Tm(n,t),Tm(r,t),t.op){case"+":if(typeof n=="number"&&typeof r=="number"){const s=n+r;return od(s,t),s}if(typeof n=="string"&&typeof r=="string")return n+r;throw Xn(t,`'+' expects (number, number) or (string, string); got (${Zt(n)}, ${Zt(r)})`);case"-":case"*":case"/":case"%":{if(typeof n!="number"||typeof r!="number")throw Xn(t,`'${t.op}' expects (number, number); got (${Zt(n)}, ${Zt(r)})`);let s;switch(t.op){case"-":s=n-r;break;case"*":s=n*r;break;case"/":s=n/r;break;case"%":s=n%r;break}return od(s,t),s}case"==":return $x(t,n,r);case"!=":return!$x(t,n,r);case"<":case"<=":case">":case">=":return N2(t,n,r)}}function $x(t,e,n){if(e===null||n===null)return e===n;const r=typeof e;if(r!==typeof n)return!1;if(r==="number"||r==="string"||r==="boolean")return e===n;throw Xn(t,"equality between objects/arrays is not supported (compare specific fields instead)")}function N2(t,e,n){if(!(typeof e=="number"&&typeof n=="number"||typeof e=="string"&&typeof n=="string"))throw Xn(t,`'${t.op}' expects matching number/number or string/string operands; got (${Zt(e)}, ${Zt(n)})`);switch(t.op){case"<":return e<n;case"<=":return e<=n;case">":return e>n;case">=":return e>=n;default:throw new Error("unreachable")}}function O2(t,e){const n=Un(t.left,e);if(typeof n!="boolean")throw Xn(t,`'${t.op}' expects boolean operands; left is ${Zt(n)}`);if(t.op==="&&"){if(!n)return!1}else if(n)return!0;const r=Un(t.right,e);if(typeof r!="boolean")throw Xn(t,`'${t.op}' expects boolean operands; right is ${Zt(r)}`);return r}function R2(t,e){const n=Un(t.cond,e);if(typeof n!="boolean")throw Xn(t,`ternary condition must be boolean, got ${Zt(n)}`);return Un(n?t.whenTrue:t.whenFalse,e)}function T2(t,e){const n=Un(t.target,e);if(n==null)throw new Ln("null-access",`cannot access field '${t.field}' on null`,t.pos);if(typeof n!="object"||Array.isArray(n)||Yl(n))throw Xn(t,`cannot access field '${t.field}' on ${Zt(n)}`);const r=n;return Object.prototype.hasOwnProperty.call(r,t.field)?r[t.field]:null}function D2(t,e){const n=Un(t.target,e);if(n==null)throw new Ln("null-access","cannot index null target",t.pos);const r=Un(t.index,e);if(Array.isArray(n)){if(typeof r!="number"||!Number.isInteger(r))throw new Ln("invalid-index",`array index must be a non-negative integer, got ${Zt(r)}`,t.pos);if(r<0)throw new Ln("invalid-index",`negative array index ${r} not supported (use length-based indexing in eval)`,t.pos);return r>=n.length?null:n[r]}if(typeof n=="object"&&!Yl(n)){if(typeof r!="string")throw new Ln("invalid-index",`object key must be a string, got ${Zt(r)}`,t.pos);const s=n;return Object.prototype.hasOwnProperty.call(s,r)?s[r]:null}throw Xn(t,`cannot index into ${Zt(n)}`)}function Tm(t,e){if(Yl(t))throw new Ln("sentinel-misuse",`sentinel '@${t.__type}' cannot be used as an operator operand`,e.pos)}function od(t,e){if(!Number.isFinite(t))throw new Ln("division-by-zero",`arithmetic produced a non-finite value (${Number.isNaN(t)?"NaN":"Infinity"})`,e.pos)}function Zt(t){if(t===null)return"null";if(Array.isArray(t))return`array(${t.length})`;if(typeof t=="object"&&t!==null){if(Yl(t))return`sentinel '@${t.__type}'`;const e=Object.keys(t);if(e.length===0)return"object {}";const n=e.slice(0,3).join(", "),r=e.length>3?", …":"";return`object {${n}${r}}`}return typeof t}const fE="$expr";class ld extends Error{constructor(n,r){super(n);G(this,"code","invalid-argument");G(this,"path");this.name="ExpressionWalkError",this.path=r}}function I2(t,e){return Dm(t,e,"")}function Dm(t,e,n){if(t===null)return null;if(typeof t!="object")return t;if(Array.isArray(t)){const o=new Array(t.length);for(let c=0;c<t.length;c+=1)o[c]=Dm(t[c],e,n===""?String(c):`${n}.${c}`);return o}const r=t;if(Object.prototype.hasOwnProperty.call(r,fE))return M2(r,e,n);const s={};for(const o of Object.keys(r))s[o]=Dm(r[o],e,n===""?o:`${n}.${o}`);return s}function M2(t,e,n){const r=Object.keys(t);if(r.length!==1)throw new ld(`expression wrapper at '${n||"<root>"}' must have only the '$expr' key, got [${r.map(d=>JSON.stringify(d)).join(", ")}]`,n);const s=t[fE];if(typeof s!="string")throw new ld(`'$expr' value at '${n||"<root>"}' must be a string, got ${$2(s)}`,n);const o=U2(s,n);return L2(o,e,n)}function L2(t,e,n){try{return Un(t,e)}catch(r){if(r instanceof Ln){const s=new Ln(r.code,`at '${n||"<root>"}': ${r.message}`,r.pos);throw s.cause=r,s}throw r}}function U2(t,e){try{return zT($T(t))}catch(n){throw n instanceof Ct?Bx(n,Ct,e):n instanceof xr?Bx(n,xr,e):n}}function Bx(t,e,n){const r=new e(`at '${n||"<root>"}': ${t.message}`,t.pos);return r.cause=t,r}function $2(t){return t===null?"null":Array.isArray(t)?"array":typeof t}const hE=new Set(["get","exists","getAfter","debug"]);function cd(t){const e=[],n=r=>{switch(r.type){case"functionCall":e.push(r.name),r.args.forEach(n);break;case"binaryOp":n(r.left),n(r.right);break;case"unaryOp":n(r.operand);break;case"methodCall":n(r.object),r.args.forEach(n);break;case"memberAccess":n(r.object);break;case"bracketAccess":n(r.object),n(r.index);break;case"ternary":n(r.condition),n(r.consequent),n(r.alternate);break;case"inExpr":n(r.element),n(r.collection);break;case"isExpr":n(r.value);break;case"listLiteral":r.elements.forEach(n);break;case"mapLiteral":r.entries.forEach(s=>{n(s.key),n(s.value)});break}};return n(t),e}function B2(t){return t.replace(/^\.\.\//,"_").replace(/^\.\//,"").replace(/[.\/-]/g,"_")}function kt(t,e){switch(t.type){case"functionCall":{const n=e.get(t.name)??t.name,r=t.args.map(s=>kt(s,e));return n===t.name&&r.every((s,o)=>s===t.args[o])?t:{...t,name:n,args:r}}case"binaryOp":{const n=kt(t.left,e),r=kt(t.right,e);return n===t.left&&r===t.right?t:{...t,left:n,right:r}}case"unaryOp":{const n=kt(t.operand,e);return n===t.operand?t:{...t,operand:n}}case"methodCall":{const n=kt(t.object,e),r=t.args.map(s=>kt(s,e));return n===t.object&&r.every((s,o)=>s===t.args[o])?t:{...t,object:n,args:r}}case"memberAccess":{const n=kt(t.object,e);return n===t.object?t:{...t,object:n}}case"bracketAccess":{const n=kt(t.object,e),r=kt(t.index,e);return n===t.object&&r===t.index?t:{...t,object:n,index:r}}case"ternary":{const n=kt(t.condition,e),r=kt(t.consequent,e),s=kt(t.alternate,e);return n===t.condition&&r===t.consequent&&s===t.alternate?t:{...t,condition:n,consequent:r,alternate:s}}case"inExpr":{const n=kt(t.element,e),r=kt(t.collection,e);return n===t.element&&r===t.collection?t:{...t,element:n,collection:r}}case"isExpr":{const n=kt(t.value,e);return n===t.value?t:{...t,value:n}}case"listLiteral":{const n=t.elements.map(r=>kt(r,e));return n.every((r,s)=>r===t.elements[s])?t:{...t,elements:n}}case"mapLiteral":{const n=t.entries.map(r=>{const s=kt(r.key,e),o=kt(r.value,e);return s===r.key&&o===r.value?r:{key:s,value:o}});return n.every((r,s)=>r===t.entries[s])?t:{...t,entries:n}}default:return t}}function q2(t,e){const n=B2(e),r=new Map;for(const s of t)s.exported||r.set(s.name,`${n}__${s.name}`);return r.size===0?t:t.map(s=>{const o=kt(s.body,r),c=s.lets.map(f=>{const p=kt(f.value,r);return p===f.value?f:{...f,value:p}}),d=s.exported?s.name:r.get(s.name)??s.name;return o===s.body&&c===s.lets&&d===s.name?s:{...s,name:d,body:o,lets:c}})}function pE(t,e,n=new Set){if(n.has(t))return[];n.add(t);const r=e.get(t);if(!r)return[];const s=[],o=cd(r.body);for(const c of r.lets)o.push(...cd(c.value));for(const c of o)e.has(c)&&!hE.has(c)&&(s.push(c),s.push(...pE(c,e,n)));return s}function Bp(t,e){const n=pR(t);return n?{success:!0,functions:n}:{success:!1,error:{code:"PARSE_FAILED",message:`Failed to parse module '${e}'`}}}function qx(t){return t.startsWith("./")||t.startsWith("../")}function F2(t,e,n){if(n!=null&&n.modules&&e in n.modules)return Bp(n.modules[e],e);if(qx(e)&&(n!=null&&n.basePath)){const s=`${n.basePath}/${e}.rules`,o=(t==null?void 0:t.readRelative(n.basePath,e))??null;return o===null?{success:!1,error:{code:"UNKNOWN_MODULE",message:`Module '${e}' not found at ${s}`}}:Bp(o,e)}if(qx(e))return{success:!1,error:{code:"UNKNOWN_MODULE",message:`Module '${e}' requires basePath for relative imports`}};const r=(t==null?void 0:t.readStdlib(e))??null;return r===null?{success:!1,error:{code:"UNKNOWN_MODULE",message:`Module '${e}' not found`}}:Bp(r,e)}function z2(t,e,n){var k;const r=Tl(e);if(!r.ok){const{line:I,column:N,message:R}=r.error;return{success:!1,error:{code:"PARSE_FAILED",message:`Failed to parse source at line ${I}, col ${N}: ${R}`}}}const s=r.ast;if(s.version!=="2+modules")return{success:!1,error:{code:"NOT_MODULE_SOURCE",message:`Version '${s.version}' is not a module source`}};if(s.imports.length===0)return s.version="2",{success:!0,data:{resolved:mx(s),modules:[]}};const o=new Map,c=new Map,d=new Map,f=[],p=new Map;for(const I of s.imports){const N=F2(t,I.module,n);if(!N.success)return{success:!1,error:N.error};f.includes(I.module)||f.push(I.module);const R=new Set;for(const F of N.functions)F.exported||R.add(F.name);p.set(I.module,R);const M=q2(N.functions,I.module);for(const F of M)if(c.set(F.name,F),F.exported){if(o.has(F.name)&&d.get(F.name)!==I.module)return{success:!1,error:{code:"DUPLICATE_FUNCTION",message:`Function '${F.name}' exported by both '${d.get(F.name)}' and '${I.module}'`}};o.set(F.name,F),d.set(F.name,I.module)}for(const F of I.functions)if(!o.has(F))return{success:!1,error:{code:"UNKNOWN_FUNCTION",message:((k=p.get(I.module))==null?void 0:k.has(F))?`Function '${F}' in module '${I.module}' is not exported`:`Function '${F}' not found in module '${I.module}'`}}}const g=new Set;for(const I of s.imports)for(const N of I.functions){g.add(N);for(const R of pE(N,c))g.add(R)}const b=[],v=new Set;function w(I){if(v.has(I))return;v.add(I);const N=c.get(I);if(!N)return;const R=cd(N.body);for(const M of N.lets)R.push(...cd(M.value));for(const M of R)c.has(M)&&!hE.has(M)&&w(M);b.push({...N,exported:!1})}for(const I of s.imports)for(const N of I.functions)w(N);const _=new Set(s.service.match.functions.map(I=>I.name));for(const I of b)if(_.has(I.name))return{success:!1,error:{code:"DUPLICATE_FUNCTION",message:`Imported function '${I.name}' conflicts with a function defined in the source`}};return s.service.match.functions=[...b,...s.service.match.functions],s.version="2",s.imports=[],{success:!0,data:{resolved:mx(s),modules:f}}}const P2={atomic:`// Atomic module — cross-document integrity for BATCH writes, via the
538
- // get()/getAfter() pair. Firestore evaluates every write in a batch
539
- // against rules, and getAfter() returns another document's POST-BATCH
540
- // state — so a rule can require "this write is only valid if a
541
- // companion write happened in the same atomic batch".
542
- //
543
- // All semantics live-verified against a production database: companion
544
- // visibility, solo-write denial, wrong-delta denial, single-use consumption
545
- // incl. replay denial, and out-of-batch getAfter() falling back to current
546
- // state.
547
- //
548
- // Explicit-param design: pass BOTH states of the companion doc —
549
- // \`get(path).data\` (pre-batch) and \`getAfter(path).data\` (post-batch).
550
- //
551
- // import { companionChangedBy, consumedFlag } from 'atomic';
552
- //
553
- // // Denormalized counter: creating a task REQUIRES the team's
554
- // // taskCount to have been incremented in the same batch:
555
- // match /teams/{teamId}/tasks/{taskId} {
556
- // function teamBefore() {
557
- // return get(/databases/$(database)/documents/teams/$(teamId)).data;
558
- // }
559
- // function teamAfter() {
560
- // return getAfter(/databases/$(database)/documents/teams/$(teamId)).data;
561
- // }
562
- // allow create: if companionChangedBy(teamBefore(), teamAfter(), 'taskCount', 1);
563
- // }
564
- //
565
- // // Single-use invite: the join is valid only when the invite was
566
- // // consumed (false -> true) IN THIS BATCH — replays deny because
567
- // // the pre-batch state is already true:
568
- // allow update: if consumedFlag(inviteBefore(), inviteAfter(), 'used');
569
- //
570
- // NOTE (simulator): in-batch companion semantics cannot be expressed
571
- // in the simulator or the Rules Test API mock surface — the simulator
572
- // treats cross-doc getAfter() as get(). These function BODIES are
573
- // simulator-tested with explicit values; the getAfter() WIRING is the
574
- // live v1 scope's job. Companion writes need their own allow rules too —
575
- // every write in a batch is evaluated.
576
-
577
- // The companion doc's field changed by EXACTLY n in this batch.
578
- // before/after are the SAME doc's get()/getAfter() data.
579
- export function companionChangedBy(before, after, field, n) {
580
- return after[field] == before[field] + n;
581
- }
582
-
583
- // A single-use flag was consumed IN THIS BATCH: pre-batch false,
584
- // post-batch true. Replays deny (pre-batch is already true), and a
585
- // solo write denies (getAfter == get, so false != true).
586
- export function consumedFlag(before, after, flagField) {
587
- return before[flagField] == false && after[flagField] == true;
588
- }
589
- `,auth:`export function isAuthenticated() {
590
- return request.auth != null;
591
- }
592
-
593
- export function isOwner(userId) {
594
- return isAuthenticated() && request.auth.uid == userId;
595
- }
596
- `,content:`// Content module for author-owned documents — the most common
597
- // Firebase app shape (posts, notes, docs, comments, tasks).
598
- //
599
- // Convention: documents carry an author field (a UID string) and
600
- // usually a status field ('draft' | 'published' | ...). Field names
601
- // are parameters, not conventions — pass yours.
602
- //
603
- // Usage:
604
- // import { validAuthorCreate, isAuthor, canReadContent, notDeleted } from 'content';
605
- // import { onlyFieldsChanged } from 'lifecycle';
606
- //
607
- // match /posts/{postId} {
608
- // // Create: author is the signed-in user.
609
- // allow create: if validAuthorCreate('author');
610
- // // Read: published to everyone, drafts to the author only.
611
- // allow read: if canReadContent('status', 'author') && notDeleted();
612
- // // Update: author edits content fields; authorship immutable.
613
- // allow update: if isAuthor('author') && onlyFieldsChanged(['title', 'body', 'status']);
614
- // allow delete: if isAuthor('author');
615
- // }
616
-
617
- // Create guard: signed in, and the incoming doc's author field is the
618
- // caller. Use on \`create\` (reads request.resource).
619
- export function validAuthorCreate(authorField) {
620
- return request.auth != null
621
- && request.resource.data[authorField] == request.auth.uid;
622
- }
623
-
624
- // The caller is the EXISTING document's author. Use on update/delete
625
- // (reads resource).
626
- export function isAuthor(authorField) {
627
- return request.auth != null
628
- && resource.data[authorField] == request.auth.uid;
629
- }
630
-
631
- // Read visibility: published content is public; anything else is
632
- // visible to its author only. Works for get; for list queries the
633
- // client must filter (rules are not filters — a bare collection query
634
- // will be denied unless it proves status == 'published').
635
- export function canReadContent(statusField, authorField) {
636
- return resource.data[statusField] == 'published'
637
- || (request.auth != null && resource.data[authorField] == request.auth.uid);
638
- }
639
-
640
- // Soft-delete guard: the document is not marked deleted. Reads the
641
- // EXISTING doc; a doc without the field passes — bracket access is
642
- // the null-on-miss idiom (dotted access of a missing key ERRORS).
643
- export function notDeleted() {
644
- return resource.data['deleted'] != true;
645
- }
646
- `,counters:`// Counters module for denormalized numeric integrity.
647
- //
648
- // The recurring shape: a client-maintained count (likes, votes, moves,
649
- // quantities) that rules must keep honest — it may only change by a
650
- // known step, or stay within known bounds. Generalizes the
651
- // state-module's moveIncremented() (hardcoded to moveCount) to any
652
- // field.
653
- //
654
- // Usage:
655
- // import { incrementedBy, changedBy, boundedNumber } from 'counters';
656
- //
657
- // // A like toggle: likeCount moves by exactly ±1:
658
- // allow update: if changedBy('likeCount', -1, 1);
659
- //
660
- // // A move counter: strictly +1 per move:
661
- // allow update: if incrementedBy('moveCount', 1);
662
- //
663
- // // A rating: any write keeps it in [1, 5]:
664
- // allow write: if boundedNumber('rating', 1, 5);
665
-
666
- // The field changed by EXACTLY n relative to the existing document.
667
- // n may be negative (decrement). Update rules only (needs resource).
668
- export function incrementedBy(field, n) {
669
- return request.resource.data[field] == resource.data[field] + n;
670
- }
671
-
672
- // The field's delta is within [min, max] (inclusive) — and it is NOT
673
- // required to change (delta 0 passes when min <= 0 <= max).
674
- export function changedBy(field, min, max) {
675
- return request.resource.data[field] - resource.data[field] >= min
676
- && request.resource.data[field] - resource.data[field] <= max;
677
- }
678
-
679
- // The incoming value is a number within [min, max] (inclusive).
680
- // Works on create and update. Missing field reads null (dynamic
681
- // access) and fails the type check rather than erroring.
682
- export function boundedNumber(field, min, max) {
683
- return (request.resource.data[field] is int || request.resource.data[field] is float)
684
- && request.resource.data[field] >= min
685
- && request.resource.data[field] <= max;
686
- }
687
- `,geometry:`// Geometry module for movement game validation via config document lookup.
688
- //
689
- // Caller must pass the config document data as an explicit parameter.
690
- // The config doc is read via get() and cached per request — define a
691
- // config() function in your rules and pass its result to these functions.
692
- //
693
- // Config doc schema:
694
- // moves[pieceType][fromCell][toCell] = true
695
- // jumps[pieceType][fromCell][toCell] = capturedCellName
696
- //
697
- // Usage:
698
- // import { validSimpleMove, validJumpMove } from 'geometry';
699
- //
700
- // function config() {
701
- // return get(/databases/$(database)/documents/gameConfig/checkers).data;
702
- // }
703
- //
704
- // allow update: if validSimpleMove(config())
705
- // && piecePlaced() && moveIntegrity();
706
- //
707
- // allow update: if validJumpMove(config())
708
- // && captureValid() && captureDecrement() && moveIntegrity();
709
-
710
- // Validate a simple (non-capture) move via config document lookup.
711
- // Uses 3-level dynamic nesting: cfg.moves[piece][from][to].
712
- // piece comes from resource.data (pre-write board) so client can't fake it.
713
- export function validSimpleMove(cfg) {
714
- let mf = request.resource.data.moveFrom;
715
- let mt = request.resource.data.moveTo;
716
- let piece = resource.data[mf];
717
- return cfg.moves[piece][mf][mt] == true;
718
- }
719
-
720
- // Validate a jump (capture) move via config document lookup.
721
- // cfg.jumps[piece][from][to] returns the expected captured cell name.
722
- // Caller must separately verify the captured piece is an opponent piece.
723
- export function validJumpMove(cfg) {
724
- let mf = request.resource.data.moveFrom;
725
- let mt = request.resource.data.moveTo;
726
- let cap = request.resource.data.captured;
727
- let piece = resource.data[mf];
728
- return cfg.jumps[piece][mf][mt] == cap;
729
- }
730
- `,joining:`// Joining module — how membership CHANGES, safely. The connective
731
- // tissue between content/spaces: spaces gates children behind a
732
- // members field; joining lets users enter and leave that field
733
- // WITHOUT an admin backend, with no privilege escalation.
734
- //
735
- // Convention: a MAP-shaped members field (uid -> role) on the parent
736
- // doc. Compose with lifecycle's onlyFieldsChanged so a join/leave
737
- // write can't touch anything else:
738
- //
739
- // import { onlyAddedSelf, onlyRemovedSelf } from 'joining';
740
- // import { onlyFieldsChanged } from 'lifecycle';
741
- // import { isSpaceMember, hasSpaceRole } from 'spaces';
742
- //
743
- // match /teams/{teamId} {
744
- // allow read: if isSpaceMember(resource.data);
745
- //
746
- // // Open self-service join (public team) at a fixed role, and
747
- // // self-service leave — nothing else about the doc may change:
748
- // allow update: if onlyFieldsChanged(['members'])
749
- // && (onlyAddedSelf('members', 'editor') || onlyRemovedSelf('members'));
750
- // // Admins manage the doc freely:
751
- // allow update: if hasSpaceRole(resource.data, 'admin');
752
- // }
753
- //
754
- // Every guarantee here is production-verified against the live Rules Test API:
755
- // the field-level map diff is reliable; the empty no-op diff DENIES (set
756
- // equality, not hasOnly — hasOnly on an empty set passes); role escalation via
757
- // CHANGING an existing entry denies; adding or removing anyone else denies.
758
-
759
- // The write adds EXACTLY the caller to the members map, at EXACTLY
760
- // \`role\`, changing and removing nobody. Update rules only.
761
- export function onlyAddedSelf(membersField, role) {
762
- let diff = request.resource.data[membersField].diff(resource.data[membersField]);
763
- return request.auth != null
764
- && diff.addedKeys() == [request.auth.uid].toSet()
765
- && diff.changedKeys().size() == 0
766
- && diff.removedKeys().size() == 0
767
- && request.resource.data[membersField][request.auth.uid] == role;
768
- }
769
-
770
- // The write removes EXACTLY the caller from the members map, adding
771
- // and changing nobody. Self-service leave. Update rules only.
772
- export function onlyRemovedSelf(membersField) {
773
- let diff = request.resource.data[membersField].diff(resource.data[membersField]);
774
- return request.auth != null
775
- && diff.removedKeys() == [request.auth.uid].toSet()
776
- && diff.addedKeys().size() == 0
777
- && diff.changedKeys().size() == 0;
778
- }
779
- `,lifecycle:`// Lifecycle module for field immutability and timestamp enforcement.
780
- //
781
- // Common pattern: certain fields must never change after document creation
782
- // (createdBy, createdAt, authorId).
783
- //
784
- // Usage:
785
- // import { fieldUnchanged, immutableFields, isServerTimestamp } from 'lifecycle';
786
- //
787
- // // Single field:
788
- // allow update: if fieldUnchanged('createdBy');
789
- //
790
- // // Multiple fields (replaces chained fieldUnchanged calls):
791
- // allow update: if immutableFields(['createdBy', 'createdAt', 'authorId']);
792
- //
793
- // // The dual: users may edit title/body but NOTHING else:
794
- // allow update: if onlyFieldsChanged(['title', 'body']);
795
- //
796
- // allow create: if isServerTimestamp('createdAt');
797
-
798
- // Ensure a field's value is identical between existing and incoming document.
799
- // Use on update rules to enforce immutability.
800
- export function fieldUnchanged(field) {
801
- return resource.data[field] == request.resource.data[field];
802
- }
803
-
804
- // Ensure multiple fields are unchanged between existing and incoming document.
805
- // Uses MapDiff — one expression instead of N chained fieldUnchanged() calls.
806
- export function immutableFields(fields) {
807
- return request.resource.data.diff(resource.data).unchangedKeys().hasAll(fields);
808
- }
809
-
810
- // Ensure a field is set to the server timestamp.
811
- // Use on create or update rules to enforce server-side time.
812
- export function isServerTimestamp(field) {
813
- return request.resource.data[field] == request.time;
814
- }
815
-
816
- // The dual of immutableFields: every changed field is in the allowed
817
- // list (fields NOT listed are implicitly immutable). Top-level keys
818
- // only — nested-map diffs are unreliable in production; flatten the
819
- // schema instead of reaching for a nested diff.
820
- export function onlyFieldsChanged(fields) {
821
- return request.resource.data.diff(resource.data).affectedKeys().hasOnly(fields);
822
- }
823
-
824
- // Exactly n top-level fields changed in this write. n == 1 is the
825
- // board-integrity / edit-one-field-per-write guard (Pattern 5,
826
- // generalized beyond games).
827
- export function nFieldsChanged(n) {
828
- return request.resource.data.diff(resource.data).affectedKeys().size() == n;
829
- }
830
- `,lobby:`// Lobby module for 2-participant coordination.
831
- //
832
- // Convention: documents must have these fields:
833
- // host: string (creator's UID)
834
- // guest: string ('' when waiting, joiner's UID when joined)
835
- // status: 'waiting' | 'playing' | 'ready' (or any active state)
836
- //
837
- // Usage:
838
- // import { validCreate, validJoin, canCancel } from 'lobby';
839
- //
840
- // allow create: if validCreate();
841
- // allow update: if validJoin();
842
- // allow delete: if canCancel();
843
-
844
- // Is this a waiting lobby with an open seat?
845
- function isWaiting() {
846
- return resource.data.status == 'waiting'
847
- && resource.data.guest == '';
848
- }
849
-
850
- // Create: caller is host, seat empty, status waiting
851
- export function validCreate() {
852
- return request.auth != null
853
- && request.resource.data.host == request.auth.uid
854
- && request.resource.data.guest == ''
855
- && request.resource.data.status == 'waiting';
856
- }
857
-
858
- // Join: fill empty seat, transition to next status, no self-join
859
- export function validJoin() {
860
- return request.auth != null
861
- && isWaiting()
862
- && request.resource.data.guest == request.auth.uid
863
- && request.auth.uid != resource.data.host
864
- && request.resource.data.status == 'playing'
865
- && request.resource.data.host == resource.data.host;
866
- }
867
-
868
- // Cancel: only host, only while waiting
869
- export function canCancel() {
870
- return request.auth != null
871
- && resource.data.status == 'waiting'
872
- && request.auth.uid == resource.data.host;
873
- }
874
- `,membership:`// Membership module for role-based and claims-based access control.
875
- //
876
- // Two access patterns:
877
- // 1. Custom claims on auth token (0 get() calls, set server-side)
878
- // 2. Member maps on documents (0 get() calls on the doc itself)
879
- //
880
- // Usage:
881
- // import { hasClaim, hasClaimRole, isMemberOf, hasRole } from 'membership';
882
- //
883
- // // Workspace access via custom claims
884
- // allow read: if hasClaim('workspace_id');
885
- // allow write: if hasClaimRole('workspace_role', 'admin');
886
- //
887
- // // Project access via member map on document
888
- // allow read: if isMemberOf(resource.data.members);
889
- // allow update: if hasRole(resource.data.members, 'admin');
890
-
891
- // Check if the auth token has a non-null value for a claim key.
892
- export function hasClaim(claim) {
893
- return request.auth != null
894
- && request.auth.token[claim] != null;
895
- }
896
-
897
- // Check if the auth token has a specific value for a claim key.
898
- export function hasClaimRole(claim, role) {
899
- return request.auth != null
900
- && request.auth.token[claim] == role;
901
- }
902
-
903
- // Check if the caller's UID exists as a key in a members map.
904
- export function isMemberOf(membersMap) {
905
- return request.auth != null
906
- && request.auth.uid in membersMap;
907
- }
908
-
909
- // Check if the caller has a specific role in a members map.
910
- export function hasRole(membersMap, role) {
911
- return request.auth != null
912
- && membersMap[request.auth.uid] == role;
913
- }
914
- `,spaces:`// Spaces module — cross-document membership gating for shared spaces
915
- // (teams, rooms, groups, projects, parties). The second-most-common
916
- // app shape after author-owned content: a PARENT document defines who
917
- // may touch its children.
918
- //
919
- // Explicit-param design (like geometry): the caller reads the parent
920
- // doc ONCE via a helper and passes its data in. Define the helper in
921
- // your rules — get() is cached per request, so every function below
922
- // can share one read (of the 10-get budget):
923
- //
924
- // import { isSpaceMember, hasSpaceRole, validMemberCreate } from 'spaces';
925
- //
926
- // match /spaces/{spaceId}/tasks/{taskId} {
927
- // function space() {
928
- // return get(/databases/$(database)/documents/spaces/$(spaceId)).data;
929
- // }
930
- // allow read: if isSpaceMember(space());
931
- // allow create: if validMemberCreate(space(), 'author');
932
- // allow delete: if hasSpaceRole(space(), 'admin');
933
- // }
934
- //
935
- // Members field shapes verified against the production engine:
936
- // list: members: ['uidA', 'uidB'] → isSpaceMember only
937
- // map: members: { uidA: 'admin', ... } → isSpaceMember + hasSpaceRole
938
- // A missing members field, a non-member uid, or a missing parent doc
939
- // (get() of a missing doc errors) all fail CLOSED.
940
-
941
- // The caller is in the space's members field. \`in\` covers both
942
- // shapes: list membership and map keys.
943
- export function isSpaceMember(spaceData) {
944
- return request.auth != null && request.auth.uid in spaceData.members;
945
- }
946
-
947
- // The caller's role in a MAP-shaped members field equals \`role\`.
948
- // List-shaped members carry no roles — this denies on them.
949
- export function hasSpaceRole(spaceData, role) {
950
- return request.auth != null && spaceData.members[request.auth.uid] == role;
951
- }
952
-
953
- // Member-gated authored create: the caller is a member AND the
954
- // incoming child doc's author field is the caller. The "post a
955
- // message / add a task" guard.
956
- export function validMemberCreate(spaceData, authorField) {
957
- return isSpaceMember(spaceData)
958
- && request.resource.data[authorField] == request.auth.uid;
959
- }
960
- `,state:`// Game state machine helpers.
961
- //
962
- // Convention: documents must have these fields:
963
- // status: 'waiting' | 'playing' | 'won' | 'draw'
964
- // moveCount: number
965
- // host: string (UID)
966
- // guest: string (UID)
967
- //
968
- // Usage:
969
- // import { isPlaying, moveIncremented, participantsUnchanged } from 'state';
970
- //
971
- // allow update: if isPlaying() && moveIncremented() && participantsUnchanged();
972
-
973
- // Is the game actively in play?
974
- export function isPlaying() {
975
- return resource.data.status == 'playing';
976
- }
977
-
978
- // Did moveCount increment by exactly 1?
979
- export function moveIncremented() {
980
- return request.resource.data.moveCount == resource.data.moveCount + 1;
981
- }
982
-
983
- // Are host and guest unchanged? (prevents mid-game identity swap)
984
- export function participantsUnchanged() {
985
- return request.resource.data.host == resource.data.host
986
- && request.resource.data.guest == resource.data.guest;
987
- }
988
- `,timing:`// Timing module for cooldown / rate-limit enforcement.
989
- //
990
- // Rules CAN rate-limit (contrary to a common assumption — jrpg
991
- // FINDINGS F-004): compare request.time against a stored server
992
- // timestamp. Pair with lifecycle's isServerTimestamp on the SAME
993
- // write so the stored timestamp cannot be forged by the client:
994
- //
995
- // import { cooldownElapsed } from 'timing';
996
- // import { isServerTimestamp } from 'lifecycle';
997
- //
998
- // // At most one move every 2 seconds:
999
- // allow update: if cooldownElapsed('lastMoveAt', 2)
1000
- // && isServerTimestamp('lastMoveAt');
1001
-
1002
- // The stored timestamp is more than \`seconds\` old (strict). Update
1003
- // rules only — needs \`resource\`. The field must be a Timestamp; a
1004
- // missing field errors, which denies (fail-closed).
1005
- export function cooldownElapsed(field, seconds) {
1006
- return request.time > resource.data[field] + duration.value(seconds, 's');
1007
- }
1008
- `,transitions:`// Transitions module for state machine enforcement.
1009
- //
1010
- // Validates that a field transitions from one known value to another.
1011
- // Use to enforce valid status flows (e.g., open -> in_progress -> completed).
1012
- //
1013
- // Usage:
1014
- // import { validTransition, statusIs, newStatusIs } from 'transitions';
1015
- //
1016
- // // Only allow open -> in_progress
1017
- // allow update: if validTransition('status', 'open', 'in_progress');
1018
- //
1019
- // // Allow update only when currently active
1020
- // allow update: if statusIs('status', 'active');
1021
- //
1022
- // // Compound: multiple valid transitions via OR
1023
- // allow update: if validTransition('status', 'open', 'in_progress')
1024
- // || validTransition('status', 'in_progress', 'completed')
1025
- // || validTransition('status', 'completed', 'archived');
1026
-
1027
- // Check that a field transitions from one value to another.
1028
- export function validTransition(field, from, to) {
1029
- return resource.data[field] == from
1030
- && request.resource.data[field] == to;
1031
- }
1032
-
1033
- // Check the current (existing) value of a field.
1034
- export function statusIs(field, value) {
1035
- return resource.data[field] == value;
1036
- }
1037
-
1038
- // Check the incoming (new) value of a field.
1039
- export function newStatusIs(field, value) {
1040
- return request.resource.data[field] == value;
1041
- }
1042
- `,turns:`// Turn enforcement for 2-participant games/sessions.
1043
- //
1044
- // Convention: documents must have these fields:
1045
- // host: string (UID)
1046
- // guest: string (UID)
1047
- // currentTurn: 'host' | 'guest'
1048
- //
1049
- // Usage:
1050
- // import { isMyTurn, turnFlipped } from 'turns';
1051
- //
1052
- // allow update: if isMyTurn() && turnFlipped();
1053
-
1054
- // Is the caller the participant whose turn it is?
1055
- export function isMyTurn() {
1056
- return (resource.data.currentTurn == 'host'
1057
- && request.auth.uid == resource.data.host)
1058
- || (resource.data.currentTurn == 'guest'
1059
- && request.auth.uid == resource.data.guest);
1060
- }
1061
-
1062
- // Did the turn alternate?
1063
- export function turnFlipped() {
1064
- return (resource.data.currentTurn == 'host'
1065
- && request.resource.data.currentTurn == 'guest')
1066
- || (resource.data.currentTurn == 'guest'
1067
- && request.resource.data.currentTurn == 'host');
1068
- }
1069
- `,validation:`// Validation module for document field shape and value checks.
1070
- //
1071
- // Usage:
1072
- // import { hasRequired, hasOnly, validString, isOneOf } from 'validation';
1073
- //
1074
- // allow create: if hasRequired(['title', 'status'])
1075
- // && validString('title', 1, 100)
1076
- // && isOneOf('status', ['draft', 'published']);
1077
-
1078
- export function hasRequired(fields) {
1079
- return request.resource.data.keys().hasAll(fields);
1080
- }
1081
-
1082
- export function hasOnly(fields) {
1083
- return request.resource.data.keys().hasOnly(fields);
1084
- }
1085
-
1086
- // Incoming field is a string with size in [min, max] (inclusive).
1087
- // Uses dynamic access, so a MISSING field reads as null (not an
1088
- // error) and fails the \`is string\` check — safe on optional fields.
1089
- export function validString(field, min, max) {
1090
- return request.resource.data[field] is string
1091
- && request.resource.data[field].size() >= min
1092
- && request.resource.data[field].size() <= max;
1093
- }
1094
-
1095
- // Enum check: the incoming field value is one of the allowed values.
1096
- // (\`in\` on a list — NOT \`.includes()\`, which does not exist in rules.)
1097
- export function isOneOf(field, values) {
1098
- return request.resource.data[field] in values;
1099
- }
1100
- `};function V2(){const t={};for(const[e,n]of Object.entries(P2))t[e]=n,t[`./stdlib/${e}.rules`]=n;return t}V2();const H2=`RtdbExpr {
1101
- Expr = Ternary
1102
-
1103
- Ternary
1104
- = Logical "?" Ternary ":" Ternary -- ternary
1105
- | Logical
1106
-
1107
- Logical
1108
- = Logical "&&" Comparison -- and
1109
- | Logical "||" Comparison -- or
1110
- | Comparison
1111
-
1112
- Comparison
1113
- = Comparison "===" Additive -- strictEq
1114
- | Comparison "!==" Additive -- strictNeq
1115
- | Comparison ">=" Additive -- gte
1116
- | Comparison "<=" Additive -- lte
1117
- | Comparison ">" Additive -- gt
1118
- | Comparison "<" Additive -- lt
1119
- | Comparison "==" Additive -- looseEq
1120
- | Comparison "!=" Additive -- looseNeq
1121
- | Additive
1122
-
1123
- Additive
1124
- = Additive "+" Multiplicative -- add
1125
- | Additive "-" Multiplicative -- sub
1126
- | Multiplicative
1127
-
1128
- Multiplicative
1129
- = Multiplicative "*" UnaryExpr -- mul
1130
- | Multiplicative "/" UnaryExpr -- div
1131
- | Multiplicative "%" UnaryExpr -- mod
1132
- | UnaryExpr
1133
-
1134
- UnaryExpr
1135
- = "!" UnaryExpr -- not
1136
- | "-" UnaryExpr -- neg
1137
- | CallExpr
1138
-
1139
- CallExpr
1140
- = CallExpr "." ident "(" ListOf<Expr, ","> ")" -- methodCall
1141
- | CallExpr "." ident -- memberAccess
1142
- | CallExpr "[" Expr "]" -- indexAccess
1143
- | Primary
1144
-
1145
- Primary
1146
- = "(" Expr ")" -- paren
1147
- | Array
1148
- | literal
1149
- | ident
1150
-
1151
- Array = "[" ListOf<Expr, ","> "]"
1152
-
1153
- literal
1154
- = number
1155
- | string
1156
- | regex
1157
- | bool
1158
- | null
1159
-
1160
- number
1161
- = digit+ "." digit+ -- float
1162
- | digit+ -- int
1163
-
1164
- string
1165
- = "\\"" doubleStringChar* "\\"" -- double
1166
- | "'" singleStringChar* "'" -- single
1167
-
1168
- doubleStringChar
1169
- = "\\\\" any -- escape
1170
- | ~"\\"" any -- char
1171
-
1172
- singleStringChar
1173
- = "\\\\" any -- escape
1174
- | ~"'" any -- char
1175
-
1176
- regex = "/" regexBody "/" regexFlags
1177
-
1178
- regexBody = regexChar+
1179
-
1180
- regexChar
1181
- = "\\\\" any -- escape
1182
- | ~("/" | "\\n") any -- char
1183
-
1184
- regexFlags = alnum*
1185
-
1186
- bool
1187
- = "true" ~identChar -- true
1188
- | "false" ~identChar -- false
1189
-
1190
- null = "null" ~identChar
1191
-
1192
- ident = "$"? identStart identChar*
1193
-
1194
- identStart = letter | "_"
1195
-
1196
- identChar = alnum | "_" | "$"
1197
- }
1198
- `;let Fx;function mE(){return Fx??(Fx=q1(H2)),Fx}function Id(t){return mE().match(t.trim())}function Md(){return mE().createSemantics()}let qp;function G2(){if(qp)return qp;const t=Md();return t.addOperation("identifiers",{_nonterminal(...e){return e.flatMap(n=>n.identifiers())},_iter(...e){return e.flatMap(n=>n.identifiers())},_terminal(){return[]},CallExpr_methodCall(e,n,r,s,o,c){return[...e.identifiers(),...o.asIteration().children.flatMap(d=>d.identifiers())]},CallExpr_memberAccess(e,n,r){return e.identifiers()},ident(e,n,r){return[this.sourceString]}}),qp=t,t}function K2(t){const e=Id(t);if(e.failed())return{raw:t,valid:!1,errors:[{code:"PARSE_ERROR",message:e.message??"Parse failed"}],warnings:[],referencedIdentifiers:[]};const n=G2()(e).identifiers(),r=[...new Set(n)];return{raw:t,valid:!0,errors:[],warnings:[],referencedIdentifiers:r}}function Y2(t){return typeof t=="object"&&t!==null&&t.__type==="serverTimestamp"}const Z2={name:"date-to-timestamp",convert(t){return t instanceof Date?Rt.fromMillis(t.getTime()):tr}},W2={name:"server-timestamp-sentinel",convert(t,e){return Y2(t)?e.serverTime instanceof Rt?e.serverTime:Rt.fromMillis(Date.now()):tr}};function Q2(t){if(t===null||typeof t!="object"||t instanceof Rt)return!1;const e=t;return typeof e.seconds=="number"&&typeof e.nanoseconds=="number"&&typeof e.toMillis=="function"}const J2={name:"user-timestamp-to-rules-timestamp",convert(t){return Q2(t)?new Rt(t.seconds,t.nanoseconds):tr}};function zx(t){return typeof t=="object"&&t!==null&&"isEqual"in t&&typeof t.isEqual=="function"}function Px(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function Sr(t,e){if(Object.is(t,e))return!0;if(zx(t))return t.isEqual(e);if(zx(e))return e.isEqual(t);if(Array.isArray(t)||Array.isArray(e))return!Array.isArray(t)||!Array.isArray(e)||t.length!==e.length?!1:t.every((s,o)=>Sr(s,e[o]));if(!Px(t)||!Px(e))return!1;const n=Object.keys(t),r=Object.keys(e);return n.length!==r.length?!1:n.every(s=>s in e&&Sr(t[s],e[s]))}function X2(t){return typeof t=="object"&&t!==null&&t.__type==="increment"&&typeof t.value=="number"}function eD(t){return typeof t=="object"&&t!==null&&t.__type==="arrayUnion"&&Array.isArray(t.values)}function tD(t){return typeof t=="object"&&t!==null&&t.__type==="arrayRemove"&&Array.isArray(t.values)}function nD(t){return typeof t=="object"&&t!==null&&t.__type==="deleteField"}function Xy(t){if(t.prior===null)return;if(t.fieldPath==="")return t.prior;let e=t.prior;for(const n of t.fieldPath.split(".")){const r=/^([^\[]*)/.exec(n),s=r?r[1]:n;if(s){if(typeof e!="object"||e===null)return;e=e[s]}const o=/\[(\d+)\]/g;let c;for(;(c=o.exec(n))!==null;){if(!Array.isArray(e))return;e=e[Number(c[1])]}}return e}const rD={name:"increment-sentinel",convert(t,e){if(!X2(t))return tr;const n=Xy(e);return(typeof n=="number"?n:0)+t.value}},sD={name:"array-union-sentinel",convert(t,e){if(!eD(t))return tr;const n=Xy(e),r=Array.isArray(n)?n.slice():[];for(const s of t.values)r.some(c=>Sr(c,s))||r.push(s);return r}},iD={name:"array-remove-sentinel",convert(t,e){if(!tD(t))return tr;const n=Xy(e);return Array.isArray(n)?n.filter(r=>!t.values.some(s=>Sr(r,s))):[]}},aD={name:"delete-field-sentinel",convert(t){return nD(t)?kr:tr}};function oD(t){if(t===null||typeof t!="object"||t instanceof Xa)return!1;const e=t;return typeof e.path=="string"&&typeof e.id=="string"&&e._path!==void 0&&e._firestore!==void 0}const lD={name:"document-reference",convert(t){return oD(t)?new Xa(t.path):tr}};function cD(t){return Array.isArray(t)&&t.every(e=>typeof e=="number")}function uD(t){if(t===null||typeof t!="object"||t instanceof uo)return null;const e=t;return cD(e._values)&&typeof e.toArray=="function"?e._values:null}const dD={name:"vector-value",convert(t){const e=uD(t);return e===null?tr:new uo(e)}};function fD(t){if(t===null||typeof t!="object"||t instanceof In)return!1;const e=t;return typeof e.toBase64=="function"&&typeof e.toUint8Array=="function"&&typeof e.isEqual=="function"}function hD(t){if(t===null||typeof t!="object"||t instanceof Cr)return!1;const e=t;return typeof e.latitude=="number"&&typeof e.longitude=="number"&&typeof e.isEqual=="function"}const pD={name:"fb-bytes-to-rules-bytes",convert(t){return fD(t)?new In(t.toUint8Array()):tr}},mD={name:"fb-geopoint-to-rules-latlng",convert(t){return hD(t)?new Cr(t.latitude,t.longitude):tr}},tr=Symbol("value-resolver:KEEP"),kr=Symbol("value-resolver:DELETE_MARKER"),Im=[];function or(t){Im.some(e=>e.name===t.name)||Im.push(t)}function cr(t,e){const n={};for(const[r,s]of Object.entries(t))n[r]=Mm(s,{...e,fieldPath:r});return n}function Mm(t,e){for(const n of Im){const r=n.convert(t,e);if(r!==tr)return r}if(Array.isArray(t))return t.map((n,r)=>Mm(n,{...e,fieldPath:`${e.fieldPath}[${r}]`}));if(Zi(t)){const n={};for(const[r,s]of Object.entries(t)){const o=e.fieldPath?`${e.fieldPath}.${r}`:r;n[r]=Mm(s,{...e,fieldPath:o})}return n}return t}function Zi(t){if(t===null||typeof t!="object")return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function Oi(t){const e={},n=[];for(const[r,s]of Object.entries(t)){if(s===kr){n.push(r);continue}e[r]=ud(s)}return{writes:e,deletedKeys:n}}function ud(t){if(t!==kr){if(Array.isArray(t))return t.filter(e=>e!==kr).map(ud);if(Zi(t)){const e={};for(const[n,r]of Object.entries(t))r!==kr&&(e[n]=ud(r));return e}return t}}function yD(){or(Z2),or(W2),or(J2),or(rD),or(sD),or(iD),or(aD),or(lD),or(dD),or(pD),or(mD)}function yE(t){return t.split(".")}const gD=new Set(["__proto__","prototype","constructor"]);function Vx(t){if(gD.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 eg(t){const e={};for(const[n,r]of Object.entries(t))e[n]=gE(r);return e}function gE(t){return Array.isArray(t)?t.map(gE):Zi(t)?eg(t):t}function bE(t,e,n){let r=t;for(let o=0;o<e.length-1;o++){const c=e[o];Vx(c);const d=Object.hasOwn(r,c)?r[c]:void 0;Zi(d)||(r[c]={}),r=r[c]}const s=e[e.length-1];Vx(s),n===kr?delete r[s]:r[s]=ud(n)}function Hx(t,e){const n=eg(t);for(const[r,s]of Object.entries(e)){if(s!==kr&&dd(s))throw new vE;bE(n,yE(r),s)}return n}class vE extends Error{constructor(){super("FieldValue.delete() can only appear at the top level of your update data"),this.name="DeleteFieldNestedError"}}function dd(t){return t===kr?!0:Array.isArray(t)?t.some(dd):Zi(t)?Object.values(t).some(dd):!1}function bD(t){for(const e of Object.values(t))if(e!==kr&&dd(e))throw new vE}function vD(t,e,n){const r=eg(t),s=[];if(n!==void 0)for(const o of n){const c=yE(o),d=wD(e,c);d!==wE&&s.push({segments:c,value:d})}else xE(e,[],s);for(const{segments:o,value:c}of s)bE(r,o,c);return r}const wE=Symbol("field-merge:ABSENT");function wD(t,e){let n=t;for(const r of e){if(!Zi(n)||!Object.hasOwn(n,r))return wE;n=n[r]}return n}function xE(t,e,n){const r=Object.keys(t);if(r.length===0&&e.length>0){n.push({segments:e,value:{}});return}for(const s of r){const o=t[s],c=[...e,s];Zi(o)&&o!==kr?xE(o,c,n):n.push({segments:c,value:o})}}function xD(t,e){const n={};for(const r of e)Object.prototype.hasOwnProperty.call(t,r)&&(n[r]=t[r]);return n}class Fp{constructor(e={},n){G(this,"documents");this.documents=n??new Map;for(const[r,s]of Object.entries(e)){const o=cr({...s},{path:r,method:"seed",prior:null}),{writes:c}=Oi(o);this.documents.set(r,c)}}get(e){return this.documents.get(e)??null}exists(e){return this.documents.has(e)}scan(e,n={}){const r=e===""||e.endsWith("/")?e:e+"/",s=n.projection?f=>xD(f,n.projection):f=>f,o=[],c=new Set,d=[];for(const[f,p]of this.documents){if(r!==""&&!f.startsWith(r))continue;if(!n.directOnly){o.push({path:f,data:s(p)});continue}const g=f.slice(r.length),b=g.indexOf("/");if(b===-1)o.push({path:f,data:s(p)}),c.add(g);else if(n.phantoms){const v=g.slice(0,b);v.length>0&&!d.includes(v)&&d.push(v)}}if(n.directOnly&&n.phantoms)for(const f of d)c.has(f)||o.push({path:r+f,data:{},phantom:!0});return o}list(e){return this.scan(e,{directOnly:!0,phantoms:!0})}listRootCollections(){const e=new Set,n=[];for(const r of this.documents.keys()){const s=r.split("/",1)[0];s.length!==0&&(e.has(s)||(e.add(s),n.push(s)))}return n}listSubcollections(e){const n=e.endsWith("/")?e:e+"/",r=new Set,s=[];for(const o of this.documents.keys()){if(!o.startsWith(n))continue;const d=o.slice(n.length).split("/",1)[0];d.length!==0&&(r.has(d)||(r.add(d),s.push(d)))}return s}snapshot(){const e={};for(const[n,r]of this.documents)e[n]={...r};return e}size(){return this.documents.size}create(e,n){if(this.documents.has(e))return{success:!1,error:`Document '${e}' already exists`};let r;try{const s=cr({...n},{path:e,method:"create",prior:null});r=Oi(s).writes}catch(s){return{success:!1,error:s.message}}return this.documents.set(e,r),{success:!0}}update(e,n){const r=this.documents.get(e);if(!r)return{success:!1,error:`Document '${e}' does not exist`};let s;try{const o=cr({...n},{path:e,method:"update",prior:r});s=Hx(r,o)}catch(o){return{success:!1,error:o.message}}return this.documents.set(e,s),{success:!0,priorData:{...r}}}setMerge(e,n,r){const s=this.documents.has(e)?{...this.documents.get(e)}:null,o=cr({...n},{path:e,method:"set",prior:s}),c=vD(s??{},o,r);return this.documents.set(e,c),{success:!0,priorData:s,created:s===null}}set(e,n){const r=this.documents.has(e)?{...this.documents.get(e)}:null,s=cr({...n},{path:e,method:"set",prior:r}),{writes:o}=Oi(s);return this.documents.set(e,o),{success:!0,priorData:r,created:r===null}}delete(e){const n=this.documents.get(e);return n?(this.documents.delete(e),{success:!0,priorData:{...n}}):{success:!1,error:`Document '${e}' does not exist`}}applyBatch(e){const n=[];for(let s=0;s<e.length;s++){const o=e[s];switch(o.method){case"create":this.documents.has(o.path)&&n.push({index:s,error:`Document '${o.path}' already exists`});break;case"update":this.documents.has(o.path)||n.push({index:s,error:`Document '${o.path}' does not exist`});break}}if(n.length>0)return{success:!1,errors:n};const r=new Map;for(const s of e)r.has(s.path)||r.set(s.path,this.documents.has(s.path)?{...this.documents.get(s.path)}:null);for(const s of e)switch(s.method){case"create":{const o=cr({...s.data},{path:s.path,method:"create",prior:null}),{writes:c}=Oi(o);this.documents.set(s.path,c);break}case"update":{const o=this.documents.get(s.path),c=cr({...s.data},{path:s.path,method:"update",prior:o});this.documents.set(s.path,Hx(o,c));break}case"set":{const o=r.get(s.path)??null,c=cr({...s.data},{path:s.path,method:"set",prior:o}),{writes:d}=Oi(c);this.documents.set(s.path,d);break}case"delete":this.documents.delete(s.path);break}return{success:!0,priorStates:r}}restore(e){this.documents.clear();for(const[n,r]of Object.entries(e))this.documents.set(n,{...r})}restorePaths(e){for(const[n,r]of Object.entries(e))r===null?this.documents.delete(n):this.documents.set(n,{...r})}}class SD{constructor(e){G(this,"base");G(this,"overlay",new Map);G(this,"tombstones",new Set);G(this,"baseCache",new Map);G(this,"cleared",!1);this.base=e}inBase(e){return Object.prototype.hasOwnProperty.call(this.base,e)}baseDoc(e){let n=this.baseCache.get(e);return n===void 0&&(n=structuredClone(this.base[e]),this.baseCache.set(e,n)),n}get(e){if(this.overlay.has(e))return this.overlay.get(e);if(!(this.cleared||this.tombstones.has(e)))return this.inBase(e)?this.baseDoc(e):void 0}set(e,n){this.overlay.set(e,n),this.tombstones.delete(e)}has(e){return this.overlay.has(e)?!0:this.cleared||this.tombstones.has(e)?!1:this.inBase(e)}delete(e){const n=this.has(e);return this.overlay.delete(e),!this.cleared&&this.inBase(e)&&this.tombstones.add(e),n}clear(){this.overlay.clear(),this.tombstones.clear(),this.baseCache.clear(),this.cleared=!0}get size(){let e=0;for(const n of this)e++;return e}*keys(){for(const[e]of this)yield e}*[Symbol.iterator](){const e=new Set;if(!this.cleared)for(const n of Object.keys(this.base))this.tombstones.has(n)||(e.add(n),yield[n,this.overlay.has(n)?this.overlay.get(n):this.baseDoc(n)]);for(const[n,r]of this.overlay)e.has(n)||(yield[n,r])}}class _D{constructor(){G(this,"events",[]);G(this,"nextId",1);G(this,"undoneEvents",[])}append(e,n=!1){const r={...e,id:this.nextId++,timestamp:new Date().toISOString()};return this.events.push(r),n||(this.undoneEvents=[]),r}getEvents(){return[...this.events]}getWriteEvents(){return this.events.filter(e=>e.allowed&&e.method!=="get"&&e.method!=="list")}lastWriteEvent(){const e=this.getWriteEvents();return e.length>0?e[e.length-1]:null}popLastWrite(){for(let e=this.events.length-1;e>=0;e--){const n=this.events[e];if(!n.aborted&&n.allowed&&n.method!=="get"&&n.method!=="list")return this.events.splice(e,1),this.undoneEvents.push(n),n}return null}popLastUndo(){return this.undoneEvents.pop()??null}size(){return this.events.length}clear(){this.events=[],this.undoneEvents=[],this.nextId=1}}function Pe(t,e,n){const r={code:t,message:e};return n!=null&&n.request&&(r.request=n.request),n!=null&&n.resource&&(r.resource=n.resource),n!=null&&n.remediation&&(r.remediation=n.remediation),n!=null&&n.query&&(r.query=n.query),r}const Gx="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",Kx=20;function tg(){const t=new Uint8Array(Kx);globalThis.crypto.getRandomValues(t);let e="";for(let n=0;n<Kx;n++)e+=Gx[t[n]%Gx.length];return e}function zp(t,e=""){const n=[];return r(t,e),n;function r(s,o){if(s==null||typeof s!="object")return;if(Array.isArray(s)){s.forEach((f,p)=>r(f,`${o}[${p}]`));return}const c=s,d=ED(c);if(d){n.push({field:o,kind:d});return}for(const[f,p]of Object.entries(c)){const g=o?`${o}.${f}`:f;r(p,g)}}}function ED(t){const e=t.__type;return e==="serverTimestamp"?"serverTimestamp":e==="increment"?"increment":e==="arrayUnion"?"arrayUnion":e==="arrayRemove"?"arrayRemove":e==="deleteField"?"delete":null}const Lm="Firestore transactions require all reads to be executed before all writes.";class SE extends Error{constructor(){super(Lm);G(this,"simError");this.name="ReadAfterWriteError",this.simError=Pe("failed-precondition",Lm)}}class AD{constructor(e){G(this,"reader");G(this,"reads",[]);G(this,"writes",[]);G(this,"writeStarted",!1);this.reader=e}get(e){this.assertReadsAllowed();const n=this.reader(e);this.reads.push({path:e,data:n});const r=n===null?null:structuredClone(n);return{path:e,exists:r!==null,data:()=>r===null?void 0:r}}getAll(...e){return this.assertReadsAllowed(),e.map(n=>this.get(n))}set(e,n){this.queue({method:"set",path:e,data:n})}create(e,n){this.queue({method:"create",path:e,data:n})}update(e,n){this.queue({method:"update",path:e,data:n})}delete(e){this.queue({method:"delete",path:e})}consume(){return{reads:this.reads,writes:this.writes}}hadWrites(){return this.writeStarted}queue(e){this.writeStarted=!0,this.writes.push(e)}assertReadsAllowed(){if(this.writeStarted)throw new SE}}class jD extends Error{constructor(n,r){super(`Queued ${r} on '${n}' after a delete in the same transaction. This combination is unprobed against production Firestore; refusing to guess. Either drop the delete or split into two transactions.`);G(this,"path");G(this,"secondMethod");this.name="AmbiguousPostDeleteWriteError",this.path=n,this.secondMethod=r}}function kD(t){const e=new Map;for(const n of t){const r=e.get(n.path);if(r===void 0){e.set(n.path,CD(n));continue}if(r.method==="delete")throw new jD(n.path,n.method);e.set(n.path,ND(r,n))}return Array.from(e.values())}function CD(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 ND(t,e){switch(e.method){case"delete":return{method:"delete",path:e.path};case"set":{const n=Pp(e);return{method:"set",path:e.path,data:n}}case"update":{const n=Pp(e),s={...t.data??{},...n};return{method:t.method,path:e.path,data:s}}case"create":{const n=Pp(e),s={...t.data??{},...n};return{method:"create",path:e.path,data:s}}}}function Pp(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}let Vp=0;function jl(){return Vp=Vp+1>>>0,`req-${Vp.toString(36)}-${Math.random().toString(36).slice(2,7)}`}function OD(t,e){const n=e==="allow";let r;for(const s of t){const o=/^Rule #(\d+) \(([^)]+)\) → (ALLOW|deny|unsupported)/.exec(s);if(!o)continue;const c={ruleIndex:Number(o[1]),operations:o[2].split(",").map(d=>d.trim())};if(n&&o[3]==="ALLOW")return c;r=c}return r}function _E(t){const e={kind:"request",id:jl(),at:t.at,evalMs:t.evalMs,method:t.method,path:t.path,auth:t.auth?{uid:t.auth.uid,...t.auth.token?{token:t.auth.token}:{}}:null,result:t.result,reasons:t.debugMessages,origin:t.origin};t.resourceData!==void 0&&(e.request={resourceData:t.resourceData}),t.resourceBefore!==void 0&&(e.resourceBefore=t.resourceBefore),t.resourceAfter!==void 0&&(e.resourceAfter=t.resourceAfter);const n=OD(t.debugMessages,t.result);return n&&(e.matchedRule=n),t.result!=="unsupported"&&t.evaluatedRule&&(e.evaluatedRule=t.evaluatedRule),t.groupId!==void 0&&(e.groupId=t.groupId,t.origin==="batch"?e.groupKind="batch":t.origin==="transaction"&&(e.groupKind="transaction")),t.triggeredBy!==void 0&&(e.triggeredBy=t.triggeredBy),t.detail!==void 0&&(e.detail=t.detail),t.provenance!==void 0&&Object.assign(e,t.provenance),e}function RD(t){return new Date(t.toMillis()).toISOString()}class Ri extends Error{constructor(n,r,s,o){super(n);G(this,"method");G(this,"path");G(this,"debugMessages");this.method=r,this.path=s,this.debugMessages=o,this.name="SimulatorUnsupportedError"}}function Ti(t,e,n){const r=n.filter(o=>o.includes("unsupported:")).map(o=>o.replace(/^.*unsupported:\s*/,"")).join("; "),s=r?` Reason(s): ${r}.`:"";return`Simulator cannot decide ${t} on ${e} — the rule uses a feature the local simulator does not yet implement.${s} Verify this rule against production using TestFirestoreRulesHandler, or file a sim-gap entry in REBUILD_PLAN.md.`}function TD(t=""){return{description:t,expectation:"ALLOW",state:"PASSED",decision:"ALLOW",trace:[],notes:["admin lens — rules bypassed (Studio Gap #2)"]}}const DD=`rules_version = '2';
1199
- service cloud.firestore {
1200
- match /databases/{database}/documents {
1201
- match /{document=**} {
1202
- allow read, write: if true;
1203
- }
1204
- }
1205
- }
1206
- `;class Ei{constructor(e=!1){G(this,"swallowAsyncRejections");G(this,"subscribers",new Set);this.swallowAsyncRejections=e}get hasSubscribers(){return this.subscribers.size>0}subscribe(e){return this.subscribers.add(e),()=>{this.subscribers.delete(e)}}emit(...e){for(const n of this.subscribers)try{const r=n(...e);this.swallowAsyncRejections&&r&&typeof r.then=="function"&&r.catch(()=>{})}catch{}}clear(){this.subscribers.clear()}}class ID{constructor(){G(this,"denial",new Ei);G(this,"request",new Ei(!0));G(this,"write",new Ei(!0));G(this,"delivery",new Ei);G(this,"suppressed",new Ei);G(this,"lifecycle",new Ei);G(this,"snapshotError",new Ei)}clear(){this.denial.clear(),this.request.clear(),this.write.clear(),this.delivery.clear(),this.suppressed.clear(),this.lifecycle.clear(),this.snapshotError.clear()}}class MD{constructor(){G(this,"currentTrigger")}run(e,n){const r=this.currentTrigger;this.currentTrigger=e;try{return n()}finally{this.currentTrigger=r}}current(){return this.currentTrigger}}const Yx=Symbol.for("pyric.firestore.activity-value-registry"),Zx=globalThis,EE=Zx[Yx]??(Zx[Yx]=new WeakMap);function AE(){let t=2166136261,e=2654435769,n=2246822507,r=3266489909;const s=o=>{t=Math.imul(t^o,16777619),e=Math.imul(e^o,2246822507),n=Math.imul(n^o,3266489909),r=Math.imul(r^o,668265263)};return{update:o=>{if(typeof o=="string")for(let c=0;c<o.length;c+=1){const d=o.charCodeAt(c);s(d&255),s(d>>>8)}else for(const c of o)s(c)},finish:()=>[t,e,n,r].map(o=>(o>>>0).toString(16).padStart(8,"0")).join("")}}function ng(...t){const e=AE();for(const n of t)e.update(n);return e.finish()}function LD(t){return{type:"string-digest",length:t.length,digest:ng("string\0",t)}}function Bl(t,...e){return{type:`${t}-digest`,digest:ng(`${t}\0`,...e)}}function UD(t){return{type:"bytes-digest",length:t.byteLength,digest:ng("bytes\0",t)}}function Wx(t){const e=AE(),n=(...s)=>{for(const o of s)e.update(o)},r=s=>{if(s===null){n("null;");return}switch(typeof s){case"string":n(`s${s.length}:`,s,";");return;case"number":n(`n${Object.is(s,-0)?"-0":String(s)};`);return;case"boolean":n(s?"b1;":"b0;");return;case"undefined":n("u;");return;case"bigint":n(`i${s.toString()};`);return;case"object":break;default:n(`x${typeof s};`);return}if(Array.isArray(s)){n(`a${s.length}[`);for(const d of s)r(d);n("];");return}const o=s,c=Object.keys(o).sort();n(`o${c.length}{`);for(const d of c)n(`k${d.length}:`,d,"="),r(o[d]);n("};")};return r(t),{type:"wire-value-digest",digest:e.finish()}}function no(t,e){EE.set(t,e)}function $D(t){return EE.get(t)}class BD{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 $n{constructor(e,n){G(this,"seconds");G(this,"nanoseconds");this.seconds=e,this.nanoseconds=n,no(this,Bl("timestamp",String(e),"\0",String(n)))}static now(){return $n.fromMillis(Date.now())}static fromDate(e){return $n.fromMillis(e.getTime())}static fromMillis(e){const n=Math.floor(e/1e3),r=Math.floor((e-n*1e3)*1e6);return new $n(n,r)}toDate(){return new Date(this.toMillis())}toMillis(){return this.seconds*1e3+this.nanoseconds/1e6}isEqual(e){return e.seconds===this.seconds&&e.nanoseconds===this.nanoseconds}toString(){return`Timestamp(seconds=${this.seconds}, nanoseconds=${this.nanoseconds})`}toJSON(){return{type:"firestore/timestamp/1.0",seconds:this.seconds,nanoseconds:this.nanoseconds}}valueOf(){const n=this.seconds- -62135596800,r=String(n).padStart(12,"0"),s=String(this.nanoseconds).padStart(9,"0");return`${r}.${s}`}}class sn extends Error{constructor(n){super(n.message);G(this,"code");G(this,"simError");this.name="FirestoreError",this.code=n.code,this.simError=n}}function Um(t){return t instanceof Rt?new $n(t.seconds,t.nanos):t instanceof In||t instanceof Cr?t:Array.isArray(t)?t.map(Um):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).map(([e,n])=>[e,Um(n)])):t}function fo(t){return Um(t)}const ro=Object.freeze({hasPendingWrites:!1,fromCache:!1}),Qx=Object.freeze({hasPendingWrites:!0,fromCache:!1});function jE(t,e){if(t===void 0)return;const n=e.split(".");let r=t;for(const s of n){if(r==null||typeof r!="object")return;r=r[s]}return r}function kE(t){const e=t.lastIndexOf("/");return e===-1?t:t.slice(e+1)}function Va(t,e,n=ro){const r={id:kE(t),path:t},s=e!==null,o=s?fo(e):void 0;return{id:r.id,ref:r,metadata:n,exists:()=>s,data:()=>o,get:c=>jE(o,c)}}function CE(t,e,n=ro){const r={id:kE(t),path:t},s=fo(e);return{id:r.id,ref:r,metadata:n,exists:()=>!0,data:()=>s,get:o=>jE(s,o)}}function Ha(t,e,n,r,s=ro){const o=e.map(p=>CE(p.path,p.data,s)),c=r?qD(r,e,o,s):o.map((p,g)=>({type:"added",doc:p,oldIndex:-1,newIndex:g}));let d=null,f=null;return{query:t,metadata:s,size:o.length,empty:o.length===0,docs:o,forEach(p){for(const g of o)p(g)},docChanges(p){const g=!!(p!=null&&p.includeMetadataChanges);if(g&&n.excludesMetadataChanges)throw new Error("To include metadata changes with your document changes, you must also pass { includeMetadataChanges: true } to onSnapshot().");return g?(f||(f=c.slice()),f):(d||(d=c.slice()),d)}}}function qD(t,e,n,r=ro){const s=new Map;t.forEach((d,f)=>s.set(d.path,f));const o=new Map;e.forEach((d,f)=>o.set(d.path,f));const c=[];for(let d=0;d<t.length;d++){const f=t[d];o.has(f.path)||c.push({type:"removed",doc:CE(f.path,f.data,r),oldIndex:d,newIndex:-1})}for(let d=0;d<e.length;d++){const f=e[d],p=s.get(f.path);if(p===void 0)c.push({type:"added",doc:n[d],oldIndex:-1,newIndex:d});else{const g=t[p].data;JSON.stringify(g)!==JSON.stringify(f.data)&&c.push({type:"modified",doc:n[d],oldIndex:p,newIndex:d})}}return c}function Jx(t,e){return t===null&&e===null?!0:t===null||e===null?!1:JSON.stringify(t)===JSON.stringify(e)}function FD(t,e){const n=`${e}/`;for(const r of t){if(!r.startsWith(n))continue;const s=r.slice(n.length);if(s.length>0&&!s.includes("/"))return!0}return!1}class zD{constructor(e,n,r){G(this,"events");G(this,"triggerScope");G(this,"host");G(this,"snapshotListeners",new Map);G(this,"nextListenerId",0);G(this,"deliveryQueue",[]);G(this,"deliveryScheduled",!1);this.events=e,this.triggerScope=n,this.host=r}emitSnapshotDelivery(e){if(!this.events.delivery.hasSubscribers)return;const n={kind:"snapshot_delivery",id:jl().replace(/^req-/,"snd-"),at:Date.now(),listenerId:e.listenerId,target:e.target,auth:e.auth?{uid:e.auth.uid,...e.auth.token?{token:e.auth.token}:{}}:null,addedCount:e.addedCount,modifiedCount:e.modifiedCount,removedCount:e.removedCount,size:e.size,...e.sample?{sample:e.sample}:{},...e.triggeredBy?{triggeredBy:e.triggeredBy}:{}};this.events.delivery.emit(n)}emitSnapshotSuppressed(e){if(!this.events.suppressed.hasSubscribers)return;const n={kind:"snapshot_suppressed",id:jl().replace(/^req-/,"sup-"),at:Date.now(),listenerId:e.listenerId,target:e.target,auth:e.auth?{uid:e.auth.uid,...e.auth.token?{token:e.auth.token}:{}}:null,reason:"no-op",...e.triggeredBy?{triggeredBy:e.triggeredBy}:{}};this.events.suppressed.emit(n)}emitLifecycle(e){if(!this.events.lifecycle.hasSubscribers)return;const n={kind:e.phase,id:jl().replace(/^req-/,"lc-"),at:Date.now(),listenerId:e.listenerId,target:e.target,auth:e.auth?{uid:e.auth.uid,...e.auth.token?{token:e.auth.token}:{}}:null};this.events.lifecycle.emit(n)}emitSnapshotError(e,n,r){this.events.snapshotError.emit(e,n,r)}addSnapshotListener(e,n,r={},s=null,o,c=!1,d=!1,f){var b;const p=String(this.nextListenerId++),g={id:p,target:e,callback:n,auth:s,bypassRules:d,followsCurrentUser:c,...f?{authScope:f}:{},options:r,currentSnapshot:void 0,errored:!1,...o?{errorCallback:o}:{}};return this.snapshotListeners.set(p,g),this.emitLifecycle({phase:"listener_attach",listenerId:p,target:e.kind==="doc"?{kind:"doc",path:e.path}:{kind:"query",collection:e.collection,...(b=e.constraints)!=null&&b.activityQuery?{query:e.constraints.activityQuery}:{}},auth:s}),this.scheduleDelivery(()=>{this.snapshotListeners.has(p)&&this.fireInitialSnapshot(g)}),()=>{var w;const v=this.snapshotListeners.has(p);this.snapshotListeners.delete(p),v&&this.emitLifecycle({phase:"listener_detach",listenerId:p,target:e.kind==="doc"?{kind:"doc",path:e.path}:{kind:"query",collection:e.collection,...(w=e.constraints)!=null&&w.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 o=Va(e.target.path,s.data);e.currentSnapshot=o,e.currentDocData=s.data;try{e.callback(o)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"doc",path:e.target.path},auth:e.auth,addedCount:s.data!==null?1:0,modifiedCount:0,removedCount:0,size:s.data!==null?1:0,sample:{docs:[{path:e.target.path,data:s.data}]}});return}const n=this.host.silentReadCollection(e.target.collection,e.auth,e.target.constraints,e.bypassRules);if(!n.allowed){this.markErrored(e,n.error);return}const r=Ha({path:e.target.collection},n.docs,{excludesMetadataChanges:!e.options.includeMetadataChanges});e.currentSnapshot=r,e.currentDocs=n.docs;try{e.callback(r)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"query",collection:e.target.collection},auth:e.auth,addedCount:n.docs.length,modifiedCount:0,removedCount:0,size:n.docs.length,sample:{docs:n.docs.map(s=>({path:s.path,data:s.data}))}})}scheduleDelivery(e){this.deliveryQueue.push(e),!this.deliveryScheduled&&(this.deliveryScheduled=!0,queueMicrotask(()=>this.drainDeliveries()))}scheduleTriggeredDelivery(e,n){this.scheduleDelivery(()=>this.triggerScope.run(e,n))}drainDeliveries(){for(this.deliveryScheduled=!1;this.deliveryQueue.length>0;)this.deliveryQueue.shift()()}flushListeners(){this.drainDeliveries()}notifyListenersForPaths(e){if(e.size===0||this.snapshotListeners.size===0)return;const n=this.triggerScope.current(),r=Array.from(this.snapshotListeners.values());for(const s of r)this.scheduleTriggeredDelivery(n,()=>{this.snapshotListeners.has(s.id)&&(s.errored||(s.target.kind==="doc"?this.notifyDocListener(s,e):this.notifyQueryListener(s,e)))})}notifyDocListener(e,n){if(e.target.kind!=="doc"||!n.has(e.target.path))return;const r=this.host.silentReadDoc(e.target.path,e.auth,e.bypassRules);if(!r.allowed){this.markErrored(e,r.error);return}const s=e.currentDocData??null;if(Jx(s,r.data)){this.emitSnapshotSuppressed({listenerId:e.id,target:{kind:"doc",path:e.target.path},auth:e.auth,...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}});return}const o=e.target.path,c=Va(o,r.data,Qx);e.currentSnapshot=c,e.currentDocData=r.data;const d=s!==null,f=r.data!==null,p=!d&&f?1:0,g=d&&!f?1:0,b=d&&f?1:0;try{e.callback(c)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"doc",path:o},auth:e.auth,addedCount:p,modifiedCount:b,removedCount:g,size:f?1:0,sample:{docs:[{path:o,data:r.data}]},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),this.scheduleDocMetadataAck(e,o,r.data)}scheduleDocMetadataAck(e,n,r){e.options.includeMetadataChanges&&this.scheduleTriggeredDelivery(this.triggerScope.current(),()=>{if(!this.snapshotListeners.has(e.id)||e.errored)return;const s=Va(n,r,ro);e.currentSnapshot=s;try{e.callback(s)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"doc",path:n},auth:e.auth,addedCount:0,modifiedCount:0,removedCount:0,size:r!==null?1:0,sample:{docs:[{path:n,data:r}]},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}})})}notifyQueryListener(e,n){if(e.target.kind!=="query"||!FD(n,e.target.collection))return;const r=this.host.silentReadCollection(e.target.collection,e.auth,e.target.constraints,e.bypassRules);if(!r.allowed){this.markErrored(e,r.error);return}const s=e.target.collection,o=e.currentDocs??[],c=Ha({path:s},r.docs,{excludesMetadataChanges:!e.options.includeMetadataChanges},o,Qx),d=c.docChanges();if(d.length===0){this.emitSnapshotSuppressed({listenerId:e.id,target:{kind:"query",collection:s},auth:e.auth,...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}});return}e.currentSnapshot=c,e.currentDocs=r.docs;let f=0,p=0,g=0;for(const b of d)b.type==="added"?f++:b.type==="modified"?p++:b.type==="removed"&&g++;try{e.callback(c)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"query",collection:s},auth:e.auth,addedCount:f,modifiedCount:p,removedCount:g,size:r.docs.length,sample:{docs:r.docs.map(b=>({path:b.path,data:b.data}))},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),this.scheduleQueryMetadataAck(e,s,r.docs)}scheduleQueryMetadataAck(e,n,r){e.options.includeMetadataChanges&&this.scheduleTriggeredDelivery(this.triggerScope.current(),()=>{if(!this.snapshotListeners.has(e.id)||e.errored)return;const s=Ha({path:n},r,{excludesMetadataChanges:!1},r,ro);e.currentSnapshot=s;try{e.callback(s)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"query",collection:n},auth:e.auth,addedCount:0,modifiedCount:0,removedCount:0,size:r.length,sample:{docs:r.map(o=>({path:o.path,data:o.data}))},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}})})}markErrored(e,n){if(e.errored=!0,this.emitSnapshotError(n,e.target,e.id),!!e.errorCallback)try{e.errorCallback(n)}catch{}}reEvaluateAllListeners(){if(this.snapshotListeners.size===0)return;const e=Array.from(this.snapshotListeners.values());for(const n of e)this.snapshotListeners.has(n.id)&&(n.target.kind==="doc"?this.reEvaluateDocListener(n):this.reEvaluateQueryListener(n))}reevaluateLiveListeners(e,n){if(this.snapshotListeners.size===0)return;const r=Array.from(this.snapshotListeners.values());for(const s of r)s.followsCurrentUser&&s.authScope===n&&this.snapshotListeners.has(s.id)&&(s.auth=e,s.target.kind==="doc"?this.reEvaluateDocListener(s):this.reEvaluateQueryListener(s))}reEvaluateDocListener(e){if(e.target.kind!=="doc")return;const n=this.host.silentReadDoc(e.target.path,e.auth,e.bypassRules);if(!n.allowed){if(e.errored)return;this.markErrored(e,n.error);return}if(e.errored){e.errored=!1;const o=Va(e.target.path,n.data);e.currentSnapshot=o,e.currentDocData=n.data;try{e.callback(o)}catch{}return}const r=e.currentDocData??null;if(Jx(r,n.data))return;const s=Va(e.target.path,n.data);e.currentSnapshot=s,e.currentDocData=n.data;try{e.callback(s)}catch{}}reEvaluateQueryListener(e){if(e.target.kind!=="query")return;const n=this.host.silentReadCollection(e.target.collection,e.auth,e.target.constraints,e.bypassRules);if(!n.allowed){if(e.errored)return;this.markErrored(e,n.error);return}if(e.errored){e.errored=!1;const c=Ha({path:e.target.collection},n.docs,{excludesMetadataChanges:!e.options.includeMetadataChanges});e.currentSnapshot=c,e.currentDocs=n.docs;try{e.callback(c)}catch{}return}const r=e.currentDocs??[],s=Ha({path:e.target.collection},n.docs,{excludesMetadataChanges:!e.options.includeMetadataChanges},r);if(s.docChanges().length!==0){e.currentSnapshot=s,e.currentDocs=n.docs;try{e.callback(s)}catch{}}}getSnapshotListenerCount(){return this.snapshotListeners.size}dispose(){this.snapshotListeners.clear(),this.deliveryQueue.length=0,this.deliveryScheduled=!1}}class PD{constructor(e,n){G(this,"eventLog");G(this,"host");this.eventLog=e,this.host=n}undo(){const e=this.eventLog.popLastWrite();if(!e)return null;if(e.priorDocs)this.host.state.restorePaths(e.priorDocs);else if(e.snapshot)this.host.state.restore(e.snapshot);else return null;return e}redo(){const e=this.eventLog.popLastUndo();if(!e)return null;const n=e.type==="batch"&&e.operations?e.operations.map(d=>d.path):e.path?[e.path]:[],r=!!e.snapshot,s=r?void 0:this.host.capturePriors(n),o=r?this.host.state.snapshot():void 0;if(e.type==="batch"&&e.operations)for(const d of e.operations)d.allowed&&this.host.applyWrite(d.method,d.path,d.data);else e.allowed&&this.host.applyWrite(e.method,e.path,e.data);const c=this.eventLog.append({...e,snapshot:o,priorDocs:s},!0);return{allowed:e.allowed,debugMessages:["Redo: "+(e.allowed?"applied":"skipped (was denied)")],event:c}}getEvents(){return this.eventLog.getEvents()}getEventCount(){return this.eventLog.size()}}class VD{constructor(e){G(this,"currentSource");G(this,"parsedCache",null);this.currentSource=e}get source(){return this.currentSource}set(e){this.currentSource=e}ast(){var e;return((e=this.parsedCache)==null?void 0:e.source)!==this.currentSource&&(this.parsedCache={source:this.currentSource,ast:Zy(this.currentSource)}),this.parsedCache.ast}}function HD(t,e,n=new Map,r){if(fd(t,n))return{provable:!0,reason:"list rule does not depend on per-document data; every doc is equally readable"};const s=KD(t,n,r);if(!s.ok||s.required.length===0){const p="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:`${p} — prod rejects the whole query rather than filtering`,residual:{missing:[],mismatched:[],outOfScope:p}}}const o=s.required,c=e.where??[],d=[],f=[];for(const p of o){if(c.some(v=>v.field===p.field&&v.op==="=="&&QD(v.value,p.value)))continue;const b=c.find(v=>v.field===p.field&&v.op==="==");b?f.push({field:p.field,expectedValue:p.value,actualValue:b.value}):d.push({field:p.field,expectedValue:p.value,fromAuthUid:p.fromAuthUid})}return d.length===0&&f.length===0?{provable:!0,reason:"every per-document predicate the rule requires is guaranteed by a query where(...) constraint"}:{provable:!1,reason:GD(d,f),residual:{missing:d,mismatched:f}}}function GD(t,e){const n=[];if(t.length>0){const r=t.map(s=>`resource.data.${s.field} == ${s.fromAuthUid?"request.auth.uid":JSON.stringify(s.expectedValue)}`).join(", ");n.push(`the query has no matching where(...) equality for [${r}]`)}if(e.length>0){const r=e.map(s=>`resource.data.${s.field} == ${JSON.stringify(s.expectedValue)} but the query pins ${JSON.stringify(s.actualValue)}`).join(", ");n.push(`the query where(...) value does not match [${r}]`)}return`${n.join("; ")} — prod rejects the query ("rules are not filters")`}function $m(t,e=new Map,n=new Set){const r=s=>{switch(s.type){case"memberAccess":return s.property==="data"&&s.object.type==="identifier"&&s.object.name==="resource"?!0:r(s.object);case"bracketAccess":return r(s.object)||r(s.index);case"functionCall":if(e.has(s.name)&&!n.has(s.name)){n.add(s.name);const o=e.get(s.name);if($m(o.body,e,n)||o.lets.some(c=>$m(c.value,e,n)))return!0}return s.args.some(r);case"binaryOp":return r(s.left)||r(s.right);case"unaryOp":return r(s.operand);case"methodCall":return r(s.object)||s.args.some(r);case"ternary":return r(s.condition)||r(s.consequent)||r(s.alternate);case"inExpr":return r(s.element)||r(s.collection);case"isExpr":return r(s.value);case"listLiteral":return s.elements.some(r);case"mapLiteral":return s.entries.some(o=>r(o.key)||r(o.value));default:return!1}};return r(t)}function fd(t,e=new Map,n=new Set){const r=s=>{switch(s.type){case"literal":return!0;case"identifier":return s.name!=="resource";case"memberAccess":return r(s.object);case"bracketAccess":return r(s.object)&&r(s.index);case"sliceAccess":return r(s.object)&&r(s.start)&&r(s.end);case"binaryOp":return r(s.left)&&r(s.right);case"unaryOp":return r(s.operand);case"ternary":return r(s.condition)&&r(s.consequent)&&r(s.alternate);case"inExpr":return r(s.element)&&r(s.collection);case"isExpr":return r(s.value);case"listLiteral":return s.elements.every(r);case"mapLiteral":return s.entries.every(o=>r(o.key)&&r(o.value));case"pathLiteral":return s.segments.every(o=>typeof o=="string"||r(o));case"methodCall":return r(s.object)&&s.args.every(r);case"functionCall":{if(!s.args.every(r))return!1;const o=e.get(s.name);if(!o)return!0;if(n.has(s.name))return!1;const c=new Set(n).add(s.name);return fd(o.body,e,c)&&o.lets.every(d=>fd(d.value,e,c))}default:return!1}};return r(t)}function KD(t,e,n){const r=[],s=(o,c)=>{if(o.type==="binaryOp"&&o.op==="&&")return s(o.left,c)&&s(o.right,c);if(o.type==="functionCall"&&e.has(o.name)&&!c.has(o.name)){const f=e.get(o.name),p=new Map;f.parameters.forEach((v,w)=>{const _=o.args[w];_&&p.set(v,_)});for(const v of f.lets)p.set(v.name,Xx(v.value,p));const g=Xx(f.body,p),b=new Set(c).add(o.name);return s(g,b)}const d=YD(o,n);return d?(r.push(d),!0):fd(o,e)};return s(t,new Set)?{ok:!0,required:r}:{ok:!1}}function YD(t,e){if(t.type!=="binaryOp"||t.op!=="==")return null;const n=(r,s)=>{const o=WD(r);return o===null?null:s.type==="literal"?{field:o,value:s.value,fromAuthUid:!1}:e!==void 0&&ZD(s)?{field:o,value:e,fromAuthUid:!0}:null};return n(t.left,t.right)??n(t.right,t.left)}function ZD(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 Xx(t,e){const n=r=>{switch(r.type){case"identifier":return e.get(r.name)??r;case"literal":return r;case"memberAccess":return{...r,object:n(r.object)};case"methodCall":return{...r,object:n(r.object),args:r.args.map(n)};case"bracketAccess":return{...r,object:n(r.object),index:n(r.index)};case"sliceAccess":return{...r,object:n(r.object),start:n(r.start),end:n(r.end)};case"binaryOp":return{...r,left:n(r.left),right:n(r.right)};case"unaryOp":return{...r,operand:n(r.operand)};case"ternary":return{...r,condition:n(r.condition),consequent:n(r.consequent),alternate:n(r.alternate)};case"inExpr":return{...r,element:n(r.element),collection:n(r.collection)};case"isExpr":return{...r,value:n(r.value)};case"listLiteral":return{...r,elements:r.elements.map(n)};case"mapLiteral":return{...r,entries:r.entries.map(s=>({key:n(s.key),value:n(s.value)}))};case"pathLiteral":return{...r,segments:r.segments.map(s=>typeof s=="string"?s:n(s))};case"functionCall":return{...r,args:r.args.map(n)}}};return n(t)}function WD(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}function eS(t,e,n,r){if(!t)return{kind:"no-rule"};const s=e.split("/").filter(v=>v.length>0),o=t.service.match.functions;let c=null;for(const v of t.service.match.children)if(c=NE(v,s,o),c)break;if(!c)return{kind:"no-rule"};const d=c.block.allows.filter(v=>v.operations.some(w=>w==="list"||w==="read"));if(d.length===0)return{kind:"no-rule"};const f=new Map;for(const v of c.functions)f.set(v.name,v);const p=[];let g=!1,b=!1;for(const v of d){const w=HD(v.condition,r,f,n==null?void 0:n.uid);w.provable?(g=!0,$m(v.condition,f)&&(b=!0)):p.push({reason:w.reason,residual:w.residual})}if(!g){const v=p[0];return{kind:"unprovable",reason:(v==null?void 0:v.reason)??"list rule depends on per-document data the query cannot guarantee",residual:(v==null?void 0:v.residual)??{missing:[],mismatched:[]}}}return b?{kind:"provable",syntheticResource:JD(r)}:{kind:"provable"}}function NE(t,e,n){const r=[...n,...t.functions];let s=0;for(const c of t.path.segments)if(c.type==="literal"){if(s>=e.length||e[s]!==c.value)return null;s++}else if(c.type==="wildcard"){if(s>=e.length)return null;s++}else s=e.length;const o=e.slice(s);if(o.length===0)return{block:t,functions:r};for(const c of t.children){const d=NE(c,o,r);if(d)return d}return null}function JD(t){const e={};for(const n of t.where??[])n.op==="=="&&(e[n.field]=n.value);return e}function tS(t){const e=[];for(const r of t.missing)r.fromAuthUid?e.push(` .where('${r.field}', '==', request.auth.uid) // request.auth.uid is ${JSON.stringify(r.expectedValue)}`):e.push(` .where('${r.field}', '==', ${JSON.stringify(r.expectedValue)})`);for(const r of t.mismatched)e.push(` .where('${r.field}', '==', ${JSON.stringify(r.expectedValue)}) // the query pins ${JSON.stringify(r.actualValue)}, but the rule requires ${JSON.stringify(r.expectedValue)}`);return e.length===0?void 0:`The list rule requires per-document equalities the query does not guarantee. Add the matching where(...) constraint(s) so every returned document satisfies the rule:
1207
- ${e.join(`
1208
- `)}`}function nS(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 XD{constructor(e,n,r,s,o){G(this,"events");G(this,"triggerScope");G(this,"rules");G(this,"simulator");G(this,"host");this.events=e,this.triggerScope=n,this.rules=r,this.simulator=s,this.host=o}get state(){return this.host.state}emitRequest(e){this.events.request.hasSubscribers&&this.events.request.emit(_E(e))}emitDenial(e){this.events.denial.emit(e)}silentReadDoc(e,n,r=!1){if(r){const w=this.state.get(e);return this.emitRequest({at:Date.now(),evalMs:0,method:"get",path:e,auth:n,result:"allow",debugMessages:["admin lens — rules bypassed"],origin:"listener",resourceBefore:{data:w,exists:w!==null},detail:{admin:!0},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),{allowed:!0,data:w}}const s=Rt.fromMillis(Date.now()),o=this.host.buildTestCase({method:"get",path:e,auth:n},s),c=Date.now(),d=performance.now(),f=this.simulator.simulate(this.rules.source,[o],{getDoc:w=>this.state.get(w)}),p=performance.now()-d;if(!f.success)return this.emitRequest({at:c,evalMs:p,method:"get",path:e,auth:n,result:"deny",debugMessages:[`Simulation error: ${f.error.message}`],origin:"listener",...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),{allowed:!1,error:Pe("permission-denied",`get ${e} simulator error`,{request:{method:"get",path:e,auth:n}})};const g=f.data.results[0];if(g.state==="UNSUPPORTED")throw this.emitRequest({at:c,evalMs:p,method:"get",path:e,auth:n,result:"unsupported",debugMessages:Re(g),origin:"listener",...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),new Ri(Ti("get",e,Re(g)),"get",e,Re(g));const b=g.state==="PASSED",v=this.state.get(e);return this.emitRequest({at:c,evalMs:p,method:"get",path:e,auth:n,result:b?"allow":"deny",debugMessages:Re(g),evaluatedRule:Ni(g),origin:"listener",resourceBefore:{data:v,exists:v!==null},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),b?{allowed:!0,data:v}:{allowed:!1,error:Pe("permission-denied",`get ${e} denied by rules`,{request:{method:"get",path:e,auth:n},resource:{data:v,exists:v!==null}})}}silentReadCollection(e,n,r,s=!1){const o=Rt.fromMillis(Date.now()),c=`${e}/__listPlaceholder__`,d=(r==null?void 0:r.structured)??{},f=nS(d),p={...s?{admin:!0}:{},...f?{query:f}:{},...r!=null&&r.activityQuery?{activityQuery:r.activityQuery}:{}},g=Object.keys(p).length>0?p:void 0,b=Date.now(),v=performance.now();if(s){const F=this.state.list(e).filter(C=>!C.phantom).map(C=>({path:C.path,data:C.data})),D=r?r(F):F;return this.emitRequest({at:b,evalMs:0,method:"list",path:e,auth:n,result:"allow",debugMessages:["admin lens — rules bypassed"],origin:"listener",...g?{detail:g}:{},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),{allowed:!0,docs:D}}const w=eS(this.rules.ast(),c,n,d);if(w.kind==="unprovable"){const F=performance.now()-v,D=`list ${e} denied: the query is statically unprovable for every possible result (rules are not filters), so the whole query is rejected — ${w.reason}`,C=tS(w.residual);return this.emitRequest({at:b,evalMs:F,method:"list",path:e,auth:n,result:"deny",debugMessages:[D],origin:"listener",...g?{detail:g}:{},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),{allowed:!1,error:Pe("permission-denied",D,{request:{method:"list",path:e,auth:n},query:d,...C?{remediation:C}:{}})}}const _=this.host.buildTestCase({method:"list",path:c,auth:n},o);this.applyListProof(_,w,d);const k=this.simulator.simulate(this.rules.source,[_],{getDoc:F=>this.state.get(F)}),I=performance.now()-v;if(!k.success)return this.emitRequest({at:b,evalMs:I,method:"list",path:e,auth:n,result:"deny",debugMessages:[`Simulation error: ${k.error.message}`],origin:"listener",...g?{detail:g}:{},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),{allowed:!1,error:Pe("permission-denied",`list ${e} simulator error`,{request:{method:"list",path:e,auth:n}})};const N=k.data.results[0];if(N.state==="UNSUPPORTED")throw this.emitRequest({at:b,evalMs:I,method:"list",path:e,auth:n,result:"unsupported",debugMessages:Re(N),origin:"listener",...g?{detail:g}:{},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),new Ri(Ti("list",e,Re(N)),"list",e,Re(N));if(N.state!=="PASSED")return this.emitRequest({at:b,evalMs:I,method:"list",path:e,auth:n,result:"deny",debugMessages:Re(N),evaluatedRule:Ni(N),origin:"listener",...g?{detail:g}:{},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),{allowed:!1,error:Pe("permission-denied",`list ${e} denied by rules`,{request:{method:"list",path:e,auth:n}})};this.emitRequest({at:b,evalMs:I,method:"list",path:e,auth:n,result:"allow",debugMessages:Re(N),evaluatedRule:Ni(N),origin:"listener",...g?{detail:g}:{},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}});const R=this.state.list(e).filter(F=>!F.phantom).map(F=>({path:F.path,data:F.data}));return{allowed:!0,docs:r?r(R):R}}applyListProof(e,n,r){n.kind==="provable"&&n.syntheticResource&&(e.resource=n.syntheticResource),(r.limit!=null||r.offset!=null||r.orderBy!=null)&&(e.query={...r.limit!=null?{limit:r.limit}:{},...r.offset!=null?{offset:r.offset}:{},...r.orderBy!=null?{orderBy:r.orderBy}:{}})}readQueryCandidates(e,n,r,s,o,c){const d=s??{},f=nS(d),p={...o?{admin:!0}:{},...f?{query:f}:{},...c!==void 0?{activityQuery:c}:{}},g=Object.keys(p).length>0?p:void 0;if(o)return this.emitRequest({at:Date.now(),evalMs:0,method:"list",path:n,auth:r,result:"allow",debugMessages:["admin lens — rules bypassed (Studio Gap #2)"],origin:"user",...g?{detail:g}:{}}),{allowed:!0,docs:e};const b=Rt.fromMillis(Date.now()),v=`${n}/__listPlaceholder__`,w=Date.now(),_=performance.now(),k=eS(this.rules.ast(),v,r,d);if(k.kind==="unprovable"){const F=performance.now()-_,D=`list ${n} denied: the query is statically unprovable for every possible result (rules are not filters), so the whole query is rejected — ${k.reason}`,C=tS(k.residual);this.emitRequest({at:w,evalMs:F,method:"list",path:n,auth:r,result:"deny",debugMessages:[D],origin:"user",...g?{detail:g}:{}});const L=Pe("permission-denied",D,{request:{method:"list",path:n,auth:r},query:d,...C?{remediation:C}:{}});return this.emitDenial(L),{allowed:!1,error:L}}const I=this.host.buildTestCase({method:"list",path:v,auth:r},b);this.applyListProof(I,k,d);const N=this.simulator.simulate(this.rules.source,[I],{getDoc:F=>this.state.get(F)}),R=performance.now()-_;if(!N.success)return this.emitRequest({at:w,evalMs:R,method:"list",path:n,auth:r,result:"deny",debugMessages:[`Simulation error: ${N.error.message}`],origin:"user",...g?{detail:g}:{}}),{allowed:!1,error:Pe("permission-denied",`list ${n} simulator error`,{request:{method:"list",path:n,auth:r}})};const M=N.data.results[0];if(M.state==="UNSUPPORTED")throw this.emitRequest({at:w,evalMs:R,method:"list",path:n,auth:r,result:"unsupported",debugMessages:Re(M),origin:"user",...g?{detail:g}:{}}),new Ri(Ti("list",n,Re(M)),"list",n,Re(M));if(M.state!=="PASSED"){const F=Re(M);this.emitRequest({at:w,evalMs:R,method:"list",path:n,auth:r,result:"deny",debugMessages:F,evaluatedRule:Ni(M),origin:"user",...g?{detail:g}:{}});const D=Pe("permission-denied",`list ${n} denied by rules`,{request:{method:"list",path:n,auth:r}});return this.emitDenial(D),{allowed:!1,error:D}}return this.emitRequest({at:w,evalMs:R,method:"list",path:n,auth:r,result:"allow",debugMessages:Re(M),evaluatedRule:Ni(M),origin:"user",...g?{detail:g}:{}}),{allowed:!0,docs:e}}}yD();class rS{constructor(){G(this,"state");G(this,"eventLog");G(this,"history");G(this,"simulator");G(this,"rules");G(this,"seedSnapshot");G(this,"events",new ID);G(this,"triggerScope",new MD);G(this,"reads");G(this,"listeners");this.state=new Fp,this.eventLog=new _D;const e=this;this.history=new PD(this.eventLog,{get state(){return e.state},capturePriors:n=>this.capturePriors(n),applyWrite:(n,r,s,o)=>this.applyWrite(n,r,s,o)}),this.simulator=new TT,this.rules=new VD(DD),this.reads=new XD(this.events,this.triggerScope,this.rules,this.simulator,{get state(){return e.state},buildTestCase:(n,r)=>this.buildTestCase(n,r)}),this.listeners=new zD(this.events,this.triggerScope,this.reads),this.seedSnapshot={}}onDenial(e){return this.events.denial.subscribe(e)}emitDenial(e){this.events.denial.emit(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)}emitWrite(e){if(!this.events.write.hasSubscribers)return;const n={kind:"write",id:jl().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??{}};this.events.write.emit(n)}emitRequest(e){this.events.request.hasSubscribers&&this.events.request.emit(_E(e))}onSnapshotError(e){return this.events.snapshotError.subscribe(e)}addSnapshotListener(e,n,r={},s=null,o,c=!1,d=!1,f){return this.listeners.addSnapshotListener(e,n,r,s,o,c,d,f)}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 Fp({},new SD(e.baseDocuments)):new Fp(e.documents??{}),this.seedSnapshot=e.baseDocuments??this.state.snapshot(),this.eventLog.clear(),Yu(e.rules)}deployRules(e){const n=Yu(e);return this.rules.set(e),this.listeners.reEvaluateAllListeners(),n}reevaluateLiveListeners(e,n){this.listeners.reevaluateLiveListeners(e,n)}getRules(){return this.rules.source}getDocument(e){return this.state.get(e)}listDocuments(e){return this.state.list(e)}scanDocuments(e,n){return this.state.scan(e,n)}readQueryCandidates(e,n,r,s,o,c){return this.reads.readQueryCandidates(e,n,r,s,o,c)}listRootCollections(){return this.state.listRootCollections()}listSubcollections(e){return this.state.listSubcollections(e)}snapshot(){return this.state.snapshot()}capturePriors(e){const n={};for(const r of e){const s=this.state.get(r);n[r]=s?{...s}:null}return n}adminSetDocument(e,n){this.state.set(e,n??{}),this.listeners.notifyListenersForPaths(new Set([e]))}adminDeleteDocument(e){const n=this.state.delete(e);return n.success&&this.listeners.notifyListenersForPaths(new Set([e])),{deleted:n.success}}runSimulate(e,n,r){if(n){const s=e.map(o=>TD(o.description));return{success:!0,data:{passed:s.length,failed:0,unsupported:0,results:s}}}return this.simulator.simulate(this.rules.source,e,{getDoc:s=>this.state.get(s),...r?{batchProjection:r}:{}})}buildBatchProjection(e){const n=new Map;for(const r of e)r.method==="get"||r.method==="list"||n.set(r.path,r.method==="delete"?null:r.data??{});return n}execute(e){const{method:n,path:r,auth:s,data:o,autoId:c,requestTime:d,merge:f,bypassRules:p}=e,g=p?{admin:!0}:void 0;if(n==="get"||n==="list"){const z=Rt.fromMillis(Date.now()),q=this.buildTestCase(e,z),x=Date.now(),E=performance.now(),O=this.runSimulate([q],p),T=performance.now()-E;if(!O.success){const B=this.eventLog.append({type:"single",method:n,path:r,auth:s?{uid:s.uid}:null,allowed:!1,debugMessages:[`Simulation error: ${O.error.message}`]});return this.emitRequest({at:x,evalMs:T,method:n,path:r,auth:s,result:"deny",debugMessages:[`Simulation error: ${O.error.message}`],origin:"user",...g?{detail:g}:{}}),{allowed:!1,debugMessages:[O.error.message],event:B}}const P=O.data.results[0];if(P.state==="UNSUPPORTED")throw this.emitRequest({at:x,evalMs:T,method:n,path:r,auth:s,result:"unsupported",debugMessages:Re(P),origin:"user",...g?{detail:g}:{}}),new Ri(Ti(n,r,Re(P)),n,r,Re(P));const $=P.state==="PASSED";let K;$&&(K=n==="get"?this.state.get(r):this.state.list(r));const W=this.eventLog.append({type:"single",method:n,path:r,auth:s?{uid:s.uid}:null,allowed:$,debugMessages:Re(P)}),se={allowed:$,data:$?K:void 0,debugMessages:Re(P),event:W};if(!$){const B={method:n,path:r,auth:s},ee=n==="get"?{data:this.state.get(r),exists:this.state.get(r)!==null}:void 0;se.error=Pe("permission-denied",`${n} ${r} denied by rules`,{request:B,...ee?{resource:ee}:{}}),this.emitDenial(se.error)}return this.emitRequest({at:x,evalMs:T,method:n,path:r,auth:s,result:$?"allow":"deny",debugMessages:Re(P),evaluatedRule:Ni(P),origin:"user",...n==="get"?{resourceBefore:{data:this.state.get(r),exists:this.state.get(r)!==null}}:{},...g?{detail:g}:{}}),se}const b=this.capturePriors([r]),v=d??Rt.fromMillis(Date.now());let w;try{w=o&&cr({...o},{path:r,method:n,prior:this.state.get(r),serverTime:v}),n==="update"&&w&&bD(w)}catch(z){const q=z.message,x=this.eventLog.append({type:"single",method:n,path:r,auth:s?{uid:s.uid}:null,data:o,allowed:!1,priorDocs:b,debugMessages:[`FieldValue resolve error: ${q}`]});return this.emitRequest({at:Date.now(),evalMs:0,method:n,path:r,auth:s,result:"deny",debugMessages:[`FieldValue resolve error: ${q}`],...w?{resourceData:w}:o?{resourceData:o}:{},resourceBefore:{data:b[r]??null,exists:(b[r]??null)!==null},origin:"user",...g?{detail:g}:{}}),{allowed:!1,debugMessages:[q],event:x,error:Pe("invalid-argument",q)}}const _=this.buildTestCase({...e,data:w},v),k=Date.now(),I=performance.now(),N=this.runSimulate([_],p),R=performance.now()-I;if(!N.success){const z=this.eventLog.append({type:"single",method:n,path:r,auth:s?{uid:s.uid}:null,data:w,allowed:!1,priorDocs:b,debugMessages:[`Simulation error: ${N.error.message}`]});return this.emitRequest({at:k,evalMs:R,method:n,path:r,auth:s,result:"deny",debugMessages:[`Simulation error: ${N.error.message}`],...o?{resourceData:o}:{},resourceBefore:{data:b[r]??null,exists:(b[r]??null)!==null},origin:"user",...g?{detail:g}:{}}),{allowed:!1,debugMessages:[N.error.message],event:z,error:Pe("invalid-argument",N.error.message)}}const M=N.data.results[0];if(M.state==="UNSUPPORTED")throw this.emitRequest({at:k,evalMs:R,method:n,path:r,auth:s,result:"unsupported",debugMessages:Re(M),...o?{resourceData:o}:{},resourceBefore:{data:b[r]??null,exists:(b[r]??null)!==null},origin:"user",...g?{detail:g}:{}}),new Ri(Ti(n,r,Re(M)),n,r,Re(M));let F=M.state==="PASSED",D=null;F&&(D=this.applyWrite(n,r,w,f),D&&(F=!1));const C=this.eventLog.append({type:"single",method:n,path:r,auth:s?{uid:s.uid}:null,data:w,allowed:F,priorDocs:F?b:void 0,debugMessages:Re(M)}),L={allowed:F,debugMessages:Re(M),event:C};if(!F)if(D)L.error=D;else{const z=b[r]??null,q=n==="set"?z!==null?"update":"create":n;L.error=Pe("permission-denied",`${n} ${r} denied by rules`,{request:{method:q,path:r,auth:s,...o?{resourceData:o}:{}},resource:{data:z,exists:z!==null}}),this.emitDenial(L.error)}const U=b[r]??null,H=F?this.state.get(r):U;if(this.emitRequest({at:k,evalMs:R,method:n,path:r,auth:s,result:F?"allow":"deny",debugMessages:Re(M),evaluatedRule:Ni(M),...o?{resourceData:o}:{},resourceBefore:{data:U,exists:U!==null},...n!=="delete"?{resourceAfter:{data:H,exists:H!==null}}:{resourceAfter:{data:null,exists:!1}},origin:"user",...g?{detail:g}:{}}),F){const z=o?zp(o):void 0,q=c&&n==="create"?r.split("/").pop():void 0;this.emitWrite({method:n,path:r,auth:s,...n!=="delete"&&o?{data:o}:{},priorState:U,nextState:n==="delete"?null:H,...z&&z.length>0?{sentinels:z}:{},...q?{autoId:q}:{},requestTime:v,...g?{detail:g}:{}})}return F&&this.triggerScope.run({method:n,path:r},()=>this.listeners.notifyListenersForPaths(new Set([r]))),L}createWithAutoId(e,n,r,s){const o=e.endsWith("/")?e.slice(0,-1):e,c=tg(),d=`${o}/${c}`,f=this.execute({method:"create",path:d,auth:r,data:n,autoId:!0,bypassRules:s});return{path:d,result:f}}batch(e,n,r){var N,R,M,F;const s=r?{admin:!0}:void 0,o=this.capturePriors(e.map(D=>D.path)),c=[],d=Rt.fromMillis(Date.now()),f=`batch-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,p=[],g=[];for(const D of e)try{g.push({...D,data:D.data?cr({...D.data},{path:D.path,method:D.method,prior:this.state.get(D.path),serverTime:d}):D.data})}catch(C){const L=C.message,U=this.eventLog.append({type:"batch",method:"batch",path:"",auth:n?{uid:n.uid}:null,allowed:!1,operations:e.map(z=>({method:z.method,path:z.path,data:z.data,allowed:!1})),debugMessages:[`FieldValue resolve error on '${D.path}': ${L}`]});this.emitRequest({at:Date.now(),evalMs:0,method:D.method,path:D.path,auth:n,result:"deny",debugMessages:[`FieldValue resolve error: ${L}`],...D.data?{resourceData:D.data}:{},resourceBefore:{data:o[D.path]??null,exists:(o[D.path]??null)!==null},origin:"batch",groupId:f,...s?{detail:s}:{}});const H=Pe("invalid-argument",L);return{allowed:!1,results:e.map(z=>({path:z.path,allowed:!1,debugMessages:[L],...z.path===D.path?{error:H}:{}})),event:U,error:H}}const b=g.map(D=>this.buildTestCase({method:D.method,path:D.path,auth:n,data:D.data},d)),v=this.buildBatchProjection(b);let w=!0;for(let D=0;D<g.length;D++){const C=g[D],L=(N=e[D])==null?void 0:N.data,U=b[D],H=Date.now(),z=performance.now(),q=this.runSimulate([U],r,v),x=performance.now()-z;if(!q.success){c.push({path:C.path,allowed:!1,debugMessages:[q.error.message],error:Pe("invalid-argument",q.error.message)}),p.push({at:H,evalMs:x,method:C.method,path:C.path,auth:n,result:"deny",debugMessages:[`Simulation error: ${q.error.message}`],...L?{resourceData:L}:{},resourceBefore:{data:o[C.path]??null,exists:(o[C.path]??null)!==null},origin:"batch",groupId:f,...s?{detail:s}:{}}),w=!1;continue}const E=q.data.results[0];if(E.state==="UNSUPPORTED")throw this.emitRequest({at:H,evalMs:x,method:C.method,path:C.path,auth:n,result:"unsupported",debugMessages:Re(E),...L?{resourceData:L}:{},resourceBefore:{data:o[C.path]??null,exists:(o[C.path]??null)!==null},origin:"batch",groupId:f,...s?{detail:s}:{}}),new Ri(Ti(C.method,C.path,Re(E)),C.method,C.path,Re(E));const O=E.state==="PASSED",T={path:C.path,allowed:O,debugMessages:Re(E)};if(!O){const P=o[C.path]??null;T.error=Pe("permission-denied",`${C.method} ${C.path} denied by rules`,{request:{method:C.method,path:C.path,auth:n,...L?{resourceData:L}:{}},resource:{data:P,exists:P!==null}}),this.emitDenial(T.error),w=!1}p.push({at:H,evalMs:x,method:C.method,path:C.path,auth:n,result:O?"allow":"deny",debugMessages:Re(E),...L?{resourceData:L}:{},resourceBefore:{data:o[C.path]??null,exists:(o[C.path]??null)!==null},origin:"batch",groupId:f,...s?{detail:s}:{}}),c.push(T)}let _=null;if(w){const D=g.map(L=>({method:L.method,path:L.path,data:L.data})),C=this.state.applyBatch(D);if(!C.success){w=!1;const L=(R=C.errors)==null?void 0:R[0];if(L!==void 0){const U=g[L.index],H=(U==null?void 0:U.method)==="create"?"already-exists":"not-found";_=Pe(H,L.error);const z=c[L.index];z&&(z.allowed=!1,z.error=_)}}}const k=this.eventLog.append({type:"batch",method:"batch",path:"",auth:n?{uid:n.uid}:null,allowed:w,priorDocs:w?o:void 0,operations:g.map((D,C)=>{var L;return{method:D.method,path:D.path,data:D.data,allowed:((L=c[C])==null?void 0:L.allowed)??!1}}),debugMessages:w?["Batch committed"]:["Batch rolled back — one or more operations denied"]});let I;w||(I=_??((M=c.find(D=>D.error))==null?void 0:M.error)??Pe("permission-denied","Batch denied"));for(let D=0;D<p.length;D++){const C=p[D];if(!C)continue;const L=w&&((F=c[D])==null?void 0:F.allowed)===!0;if(L){const U=this.state.get(C.path);C.method!=="delete"?C.resourceAfter={data:U,exists:U!==null}:C.resourceAfter={data:null,exists:!1}}else{const U=o[C.path]??null;C.resourceAfter={data:U,exists:U!==null}}if(this.emitRequest(C),L&&C.method!=="get"&&C.method!=="list"){const U=o[C.path]??null,H=e[D],z=H&&"data"in H&&H.data?zp(H.data):void 0;this.emitWrite({method:C.method,path:C.path,auth:n,...C.method!=="delete"&&C.resourceData?{data:C.resourceData}:{},priorState:U,nextState:C.method==="delete"?null:this.state.get(C.path),...C.groupId?{groupId:C.groupId,groupKind:"batch"}:{},...z&&z.length>0?{sentinels:z}:{},requestTime:d,...s?{detail:s}:{}})}}if(w){const D=new Set;for(const L of g)D.add(L.path);const C=g[0];this.triggerScope.run({method:"batch",path:(C==null?void 0:C.path)??""},()=>this.listeners.notifyListenersForPaths(D))}return{allowed:w,results:c,event:k,...I?{error:I}:{}}}transaction(e,n){const r=n.auth,s=this.state.snapshot(),o=f=>this.state.get(f),c=new AD(o);let d;try{d=e(c)}catch(f){throw this.logAbortedTransaction(c,r,f),f}return d!==null&&typeof(d==null?void 0:d.then)=="function"?d.then(f=>this.commitTransaction(c,r,s,n,f),f=>{throw this.logAbortedTransaction(c,r,f),f}):this.commitTransaction(c,r,s,n,d)}commitTransaction(e,n,r,s,o){var C,L,U,H;const{reads:c,writes:d}=e.consume(),f=s.bypassRules?{admin:!0}:void 0,p=`tx-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,g=[];if(d.length===0){const z=this.eventLog.append({type:"transaction",method:"transaction",path:"",auth:n?{uid:n.uid}:null,allowed:!0,reads:c.map(q=>({path:q.path,data:q.data})),operations:[],snapshot:r,debugMessages:["Transaction committed (read-only — no writes queued)"]});return{allowed:!0,reads:[...c],writes:[],returnValue:o,event:z}}let b;try{b=kD(d)}catch(z){const q=z;throw this.eventLog.append({type:"transaction",method:"transaction",path:"",auth:n?{uid:n.uid}:null,allowed:!1,aborted:!0,reads:c.map(x=>({path:x.path,data:x.data})),error:{name:q.name,message:q.message,code:"failed-precondition"},debugMessages:[`Transaction aborted at merge: ${q.message}`]}),z}const v=Rt.fromMillis(Date.now()),w=[];for(const z of b){if(z.method==="delete"){w.push(z);continue}try{const q=cr({...z.data},{path:z.path,method:z.method,prior:this.state.get(z.path),serverTime:v});w.push({...z,data:q})}catch(q){const x=q.message,E=Pe("invalid-argument",x),O=this.eventLog.append({type:"transaction",method:"transaction",path:"",auth:n?{uid:n.uid}:null,allowed:!1,reads:c.map($=>({path:$.path,data:$.data})),operations:b.map($=>({method:$.method,path:$.path,data:$.data,allowed:!1})),debugMessages:[`FieldValue resolve error on '${z.path}': ${x}`]}),T=z.method==="set"?this.state.get(z.path)!==null?"update":"create":z.method,P=r[z.path]??null;return this.emitRequest({at:Date.now(),evalMs:0,method:T,path:z.path,auth:n,result:"deny",debugMessages:[`FieldValue resolve error: ${x}`],...z.data&&T!=="delete"?{resourceData:z.data}:{},resourceBefore:{data:P,exists:P!==null},origin:"transaction",groupId:p,...f?{detail:f}:{},provenance:s.provenance}),{allowed:!1,reads:[...c],writes:b.map($=>{const K=$.method==="set"?this.state.get($.path)!==null?"update":"create":$.method;return{path:$.path,method:K,allowed:!1,debugMessages:$.path===z.path?[x]:[],...$.path===z.path?{error:E}:{}}}),returnValue:o,event:O,error:E}}}const _=w.map(z=>{const q=this.state.get(z.path)!==null,x=z.method==="set"?q?"update":"create":z.method;return this.buildTestCase({method:x,path:z.path,auth:n,data:z.data},v)}),k=this.buildBatchProjection(_),I=[];let N=!0;for(let z=0;z<w.length;z++){const q=w[z],x=(C=b[z])==null?void 0:C.data,E=this.state.get(q.path)!==null,O=q.method==="set"?E?"update":"create":q.method,T=r[q.path]??null,P=_[z],$=Date.now(),K=performance.now(),W=this.runSimulate([P],s.bypassRules,k),se=performance.now()-K;if(!W.success){I.push({path:q.path,method:O,allowed:!1,debugMessages:[W.error.message],error:Pe("invalid-argument",W.error.message)}),g.push({at:$,evalMs:se,method:O,path:q.path,auth:n,result:"deny",debugMessages:[`Simulation error: ${W.error.message}`],...x&&O!=="delete"?{resourceData:x}:{},resourceBefore:{data:T,exists:T!==null},origin:"transaction",groupId:p,...f?{detail:f}:{},provenance:s.provenance}),N=!1;continue}const B=W.data.results[0];if(B.state==="UNSUPPORTED")throw this.emitRequest({at:$,evalMs:se,method:O,path:q.path,auth:n,result:"unsupported",debugMessages:Re(B),...x&&O!=="delete"?{resourceData:x}:{},resourceBefore:{data:T,exists:T!==null},origin:"transaction",groupId:p,...f?{detail:f}:{},provenance:s.provenance}),new Ri(Ti(O,q.path,Re(B)),O,q.path,Re(B));const ee=B.state==="PASSED",ae={path:q.path,method:O,allowed:ee,debugMessages:Re(B)};if(g.push({at:$,evalMs:se,method:O,path:q.path,auth:n,result:ee?"allow":"deny",debugMessages:Re(B),...x&&O!=="delete"?{resourceData:x}:{},resourceBefore:{data:T,exists:T!==null},origin:"transaction",groupId:p,...f?{detail:f}:{},provenance:s.provenance}),!ee){const le=r[q.path]??null;ae.error=Pe("permission-denied",`${O} ${q.path} denied by rules`,{request:{method:O,path:q.path,auth:n,...x&&O!=="delete"?{resourceData:x}:{}},resource:{data:le,exists:le!==null}}),this.emitDenial(ae.error),N=!1}I.push(ae)}let R=null;if(N){const z=this.state.applyBatch(w);if(!z.success){N=!1;const q=(L=z.errors)==null?void 0:L[0];if(q!==void 0){const x=w[q.index],E=(x==null?void 0:x.method)==="create"?"already-exists":"not-found";R=Pe(E,q.error);const O=I[q.index];O&&(O.allowed=!1,O.error=R)}}}const M=this.eventLog.append({type:"transaction",method:"transaction",path:"",auth:n?{uid:n.uid}:null,allowed:N,reads:c.map(z=>({path:z.path,data:z.data})),operations:w.map((z,q)=>{var x;return{method:z.method,path:z.path,data:z.data,allowed:((x=I[q])==null?void 0:x.allowed)??!1}}),snapshot:N?r:void 0,debugMessages:N?["Transaction committed"]:["Transaction rolled back — one or more operations denied"]});for(let z=0;z<g.length;z++){const q=g[z],x=N&&((U=I[z])==null?void 0:U.allowed)===!0;if(x){const E=this.state.get(q.path);q.method!=="delete"?q.resourceAfter={data:E,exists:E!==null}:q.resourceAfter={data:null,exists:!1}}else{const E=r[q.path]??null;q.resourceAfter={data:E,exists:E!==null}}if(this.emitRequest(q),x&&q.method!=="get"&&q.method!=="list"){const E=r[q.path]??null,O=b[z],T=O&&O.method!=="delete"&&O.data?zp(O.data):void 0;this.emitWrite({method:q.method,path:q.path,auth:n,...q.method!=="delete"&&q.resourceData?{data:q.resourceData}:{},priorState:E,nextState:q.method==="delete"?null:this.state.get(q.path),...q.groupId?{groupId:q.groupId,groupKind:"transaction"}:{},...T&&T.length>0?{sentinels:T}:{},requestTime:v,...f?{detail:f}:{},provenance:s.provenance})}}let F;N||(F=R??((H=I.find(z=>z.error))==null?void 0:H.error)??Pe("permission-denied","Transaction denied"));const D={allowed:N,reads:[...c],writes:I,returnValue:o,event:M,...F?{error:F}:{}};if(s.readOnly&&e.hadWrites()&&(D.readOnlyViolation=!0),N){const z=new Set;for(const x of w)z.add(x.path);const q=w[0];this.triggerScope.run({method:"transaction",path:(q==null?void 0:q.path)??""},()=>this.listeners.notifyListenersForPaths(z))}return D}logAbortedTransaction(e,n,r){const s=r,{reads:o}=e.consume();this.eventLog.append({type:"transaction",method:"transaction",path:"",auth:n?{uid:n.uid}:null,allowed:!1,aborted:!0,reads:o.map(c=>({path:c.path,data:c.data})),error:{name:r.name,message:r.message,...s.code!==void 0?{code:String(s.code)}:{}},debugMessages:[`Transaction aborted: ${r.message}`]})}undo(){return this.history.undo()}redo(){return this.history.redo()}getEvents(){return this.history.getEvents()}getEventCount(){return this.history.getEventCount()}buildTestCase(e,n){const r=this.state.get(e.path),s=e.method==="set"?r!==null?"update":"create":e.method;let o=e.data;if(e.method==="get"||e.method==="list")o=void 0;else if(e.method==="update"&&r&&e.data){const{writes:c,deletedKeys:d}=Oi(e.data),f={...r,...c};for(const p of d)delete f[p];o=f}else e.data&&(o=Oi(e.data).writes);return{description:`${e.method} ${e.path}`,expectation:"ALLOW",method:s,path:e.path,auth:e.auth?{uid:e.auth.uid,token:e.auth.token}:null,data:o,resource:r??void 0,...n?{requestTime:RD(n)}:{}}}applyWrite(e,n,r,s){if(s!==void 0&&s!==!1&&(e==="create"||e==="update")){const o=s===!0?void 0:s.mergeFields;return this.state.setMerge(n,r??{},o),null}switch(e){case"create":{const o=this.state.create(n,r??{});return o.success?null:Pe("already-exists",o.error??`Document '${n}' already exists`)}case"update":{const o=this.state.update(n,r??{});return o.success?null:Pe("not-found",o.error??`Document '${n}' does not exist`)}case"set":return this.state.set(n,r??{}),null;case"delete":return this.state.delete(n),null;default:return null}}}class nt extends Error{constructor(n,r,s){const o=typeof n=="object",c=o?n.code:n,d=o?n.message:r,f=o?n.denialContext:s,p=o?n.remediation:void 0,g=p!==void 0?`${d}
1209
-
1210
- Remediation:
1211
- ${p}`:d;super(g);G(this,"code");G(this,"denialContext");G(this,"remediation");this.name="SandboxError",this.code=c,f!==void 0&&(this.denialContext=f),p!==void 0&&(this.remediation=p)}}function Bm(t){return t.kind==="request"||t.kind==="operation"}function Zl(t){const e=Object.freeze({...t.source}),n=Object.freeze({...t.authLens});return Object.freeze({source:e,authLens:n,...t.planId===void 0?{}:{planId:t.planId}})}function ql(t){const e=Zl(t);return{actor:e.source,authLens:e.authLens,operationContext:e,...e.planId===void 0?{}:{planId:e.planId}}}function sS(t){var n;const e=(n=t==null?void 0:t.operationContext)==null?void 0:n.source;if(e&&e.kind!=="unattributed")return e;if(t!=null&&t.actor&&t.actor.kind!=="unattributed")return t.actor}function Ld(t,e){var s,o,c,d,f,p,g,b;const n=((s=t==null?void 0:t.operationContext)==null?void 0:s.source)??(t==null?void 0:t.actor),r=((o=e==null?void 0:e.operationContext)==null?void 0:o.source)??(e==null?void 0:e.actor);return Zl({source:sS(t)??sS(e)??n??r??{kind:"unattributed"},authLens:((c=e==null?void 0:e.operationContext)==null?void 0:c.authLens)??(e==null?void 0:e.authLens)??((d=t==null?void 0:t.operationContext)==null?void 0:d.authLens)??(t==null?void 0:t.authLens)??{mode:"app-session"},...(((f=t==null?void 0:t.operationContext)==null?void 0:f.planId)??(t==null?void 0:t.planId)??((p=e==null?void 0:e.operationContext)==null?void 0:p.planId)??(e==null?void 0:e.planId))===void 0?{}:{planId:((g=t==null?void 0:t.operationContext)==null?void 0:g.planId)??(t==null?void 0:t.planId)??((b=e==null?void 0:e.operationContext)==null?void 0:b.planId)??(e==null?void 0:e.planId)}})}function eI(t){return Ld(void 0,t)}function OE(t){var e;return t.rulesDisposition?t.rulesDisposition:t.kind==="operation"&&t.origin==="admin"||((e=t.detail)==null?void 0:e.admin)===!0?{kind:"bypassed",reason:"admin"}:t.result==="unsupported"?{kind:"not-evaluated",reason:"unsupported"}:t.kind==="operation"&&t.result==="error"?{kind:"not-evaluated",reason:"runtime-error"}:t.kind==="operation"&&t.result==="not-applicable"?{kind:"not-evaluated",reason:"not-a-rules-operation"}:t.result==="deny"?{kind:"evaluated",verdict:"deny"}:t.kind==="request"?{kind:"evaluated",verdict:"allow"}:t.rules?{kind:"evaluated",verdict:"allow"}:{kind:"not-evaluated",reason:"no-rules"}}function tI(t){return t===null?null:Object.freeze({uid:t.uid,...t.token===void 0?{}:{token:RE(t.token)}})}function RE(t){const e={};for(const[n,r]of Object.entries(t))e[n]=TE(r);return Object.freeze(e)}function TE(t){return Array.isArray(t)?Object.freeze(t.map(TE)):t&&typeof t=="object"?RE(t):t}function DE(t){return Bm(t)?Object.freeze({id:t.id,at:t.at,eventKind:t.kind,service:t.kind==="request"?t.service??"firestore":t.service,method:t.method,...t.path===void 0?{}:{path:t.path},auth:tI(t.auth),result:t.result,context:eI(t),rules:Object.freeze({...OE(t)})}):null}function iS(t){return t===null?{mode:"anon"}:t.token===void 0?{mode:"as",uid:t.uid}:{mode:"as",uid:t.uid,token:t.token}}class ho{constructor(e,n,r){G(this,"sandbox");G(this,"auth");G(this,"operationContext");this.sandbox=e,this.auth=n,this.operationContext=Zl(r??{source:{kind:"unattributed"},authLens:iS(n)})}withAuth(e){return qm(e),new ho(this.sandbox,e,{source:this.operationContext.source,authLens:iS(e),...this.operationContext.planId===void 0?{}:{planId:this.operationContext.planId}})}}function Wl(t,e){return new ho(t.sandbox,t.auth,e)}function qm(t){if(t===null)return;if(t===void 0)throw new nt({code:"invalid-argument",message:"withAuth() requires an explicit AuthState argument.",remediation:["For anonymous (unauthenticated) access: withAuth(null)",'For authenticated access: withAuth({ uid: "someUid" })','For custom claims: withAuth({ uid: "someUid", token: { role: "admin" } })'].join(`
1212
- `)});if(typeof t!="object")throw new nt("invalid-argument","withAuth() expected null or an object with a `uid` field.");const e=t;if(typeof e.uid!="string"||e.uid.length===0)throw new nt("invalid-argument","withAuth() requires `uid` to be a non-empty string.");if("token"in e&&e.token!==void 0&&(e.token===null||typeof e.token!="object"||Array.isArray(e.token)))throw new nt("invalid-argument","withAuth() requires `token` (when present) to be a plain object.")}function nI(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),n=e.length%4===0?"":"=".repeat(4-e.length%4),r=atob(e+n),s=new Uint8Array(r.length);for(let o=0;o<r.length;o++)s[o]=r.charCodeAt(o);return s}function rI(t){const e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return n}function Ud(t){return Fm(t,!0)}function Fm(t,e){if(t===null||typeof t!="object")return t;if(Array.isArray(t)){const o=t.map(c=>Fm(c,!1));return e&&no(o,Wx(t)),o}const n=t,r=o=>(e&&no(o,Wx(t)),o);if(n.__type__==="__vector__"&&Array.isArray(n.value))return r(new uo(n.value));if(typeof n.__type=="string")switch(n.__type){case"timestamp":return r(new Rt(n.seconds,n.nanos));case"bytes":return r(new In(nI(n.base64)));case"latlng":return r(new Cr(n.lat,n.lng));case"duration":return r(new Mt(n.seconds,n.nanos));case"reference":return r(new Xa(n.path));case"path":return r(new dr(n.segments))}if(typeof n.type=="string")switch(n.type){case"firestore/timestamp/1.0":{const o=n.seconds,c=n.nanoseconds;return r(new Rt(o,c))}case"firestore/bytes/1.0":return r(new In(rI(n.bytes)));case"firestore/geoPoint/1.0":return r(new Cr(n.latitude,n.longitude))}const s={};for(const[o,c]of Object.entries(n))s[o]=Fm(c,!1);return r(s)}class Eu extends Error{constructor(e){super(e),this.name="PersistenceSchemaError"}}function sI(t){let e;try{e=JSON.parse(t)}catch(s){throw new Eu(`Persisted blob is not valid JSON: ${s.message}`)}if(typeof e!="object"||e===null)throw new Eu("Persisted blob is not an object");if(e.version!==1&&e.version!==2)throw new Eu(`Persisted blob has version ${String(e.version)}, expected 1 or 2`);if(typeof e.firestore!="object"||e.firestore===null)throw new Eu("Persisted blob has no firestore field");const n={};for(const[s,o]of Object.entries(e.firestore))n[s]=Ud(o);const r=e.services!==void 0&&typeof e.services=="object"&&e.services!==null?e.services:{};return{firestore:n,services:r}}const iI=3,aI=256,zm="meta";function oI(t){let e=2166136261;for(let n=0;n<t.length;n++)e^=t.charCodeAt(n),e=e+((e<<1)+(e<<4)+(e<<7)+(e<<8)+(e<<24))>>>0;return(e%aI).toString(16).padStart(2,"0")}function lI(t){return JSON.parse(JSON.stringify(t))}function IE(t){const e=JSON.stringify(t);let n=2166136261;for(let r=0;r<e.length;r++)n^=e.charCodeAt(r),n=Math.imul(n,16777619)>>>0;return n}function ME(t,e,n){const r=new Map;r.set(zm,{version:iI,savedAt:n,services:e});for(const[s,o]of Object.entries(t)){const c=oI(s);let d=r.get(c);d||(d={docs:{}},r.set(c,d)),d.docs[s]=lI(o)}for(const[s,o]of r)s!==zm&&(o.checksum=IE(o.docs));return r}const LE="pyric-v3-records";function cI(t){return JSON.stringify({format:LE,records:Object.fromEntries(t)})}function uI(t){let e;try{e=JSON.parse(t)}catch{return new Map}const n=e;return n&&typeof n=="object"&&n.format===LE&&typeof n.records=="object"&&n.records!==null?new Map(Object.entries(n.records)):UE(t)??new Map}function UE(t){let e;try{e=sI(t)}catch{return null}return ME(e.firestore,e.services,0)}function dI(t){const e={};let n={};for(const[r,s]of t){if(r===zm){const c=s;c&&typeof c.services=="object"&&c.services!==null&&(n=c.services);continue}const o=s;if(!(!o||typeof o.docs!="object"||o.docs===null)){if(typeof o.checksum=="number"&&IE(o.docs)!==o.checksum){console.warn(`[sandbox/persistence] checksum mismatch for bucket '${r}'; skipping corrupt bucket`);continue}for(const[c,d]of Object.entries(o.docs))e[c]=Ud(d)}}return{firestore:e,services:n}}const so="snapshots";function Pm(){const t=new Map,e=n=>{let r=t.get(n);return r||(r=new Map,t.set(n,r)),r};return{async getRecord(n,r){var o;const s=(o=t.get(n))==null?void 0:o.get(r);return s===void 0?null:structuredClone(s)},async listRecords(n){var r;return[...((r=t.get(n))==null?void 0:r.keys())??[]]},async putRecords(n,r){const s=e(n);for(const[o,c]of r)s.set(o,structuredClone(c))},async deleteRecords(n,r){const s=t.get(n);if(s)for(const o of r)s.delete(o)},async clear(n){t.delete(n)}}}function $E(t){return new Promise((e,n)=>{const r=indexedDB.open(t,1);r.onupgradeneeded=()=>{const s=r.result;s.objectStoreNames.contains(so)||s.createObjectStore(so)},r.onsuccess=()=>e(r.result),r.onerror=()=>n(r.error??new Error(`Failed to open IndexedDB '${t}'`)),r.onblocked=()=>n(new Error(`IndexedDB open blocked for '${t}'`))})}function Hp(t,e,n){return $E(t).then(r=>new Promise((s,o)=>{const c=r.transaction(so,e),d=c.objectStore(so),f=n(d);let p=null;f&&(f.onsuccess=()=>{p=f.result??null},f.onerror=()=>o(f.error)),c.oncomplete=()=>{r.close(),s(p)},c.onerror=()=>{r.close(),o(c.error)},c.onabort=()=>{r.close(),o(c.error??new Error("IndexedDB transaction aborted"))}}))}function aS(t,e){return $E(t).then(n=>new Promise((r,s)=>{const o=n.transaction(so,"readwrite");e(o.objectStore(so)),o.oncomplete=()=>{n.close(),r()},o.onerror=()=>{n.close(),s(o.error)},o.onabort=()=>{n.close(),s(o.error??new Error("IndexedDB transaction aborted"))}}))}function fI(){if(typeof indexedDB>"u")throw new Error('IndexedDB is not available in this environment. Use { backend: "memory" } or supply an injectedBackend.');return{async getRecord(t,e){return await Hp(t,"readonly",r=>r.get(e))??null},async listRecords(t){return(await Hp(t,"readonly",n=>n.getAllKeys())??[]).map(n=>String(n))},async putRecords(t,e){await aS(t,n=>{for(const[r,s]of e)n.put(s,r)})},async deleteRecords(t,e){await aS(t,n=>{for(const r of e)n.delete(r)})},async clear(t){await Hp(t,"readwrite",e=>e.clear())},async estimate(){var e;if(typeof navigator>"u"||!((e=navigator.storage)!=null&&e.estimate))return null;const t=await navigator.storage.estimate();return{usage:t.usage??0,quota:t.quota??0}}}}const hI=250,oS="pyric:sandbox:auth-session";function Gp(t){return t==="auth"||t==="auth-session:[DEFAULT]"?oS:`${oS}:${encodeURIComponent(t)}`}function BE(t){const e=JSON.stringify(t);let n=2166136261;for(let r=0;r<e.length;r++)n^=e.charCodeAt(r),n=Math.imul(n,16777619)>>>0;return n}function pI(t){if(t&&typeof t=="object"){if(t.name==="QuotaExceededError")return!0;const e=t.message;if(typeof e=="string"&&/quota/i.test(e))return!0}return!1}function mI(t){return t.injectedBackend?t.injectedBackend:(t.backend??"indexedDB")==="memory"||typeof indexedDB>"u"?Pm():fI()}async function yI(t,e){const n={...e,flushIntervalMs:e.flushIntervalMs??hI,backend:e.backend??"indexedDB"},r=mI(n),s=new Map,o=await gI(t,r,n.key,s);let c=null,d=!1;const f=new Map,p=async()=>{if(d)return;const U=t.snapshot(),H=ME(U.firestore,U.services,Date.now()),z=new Map,q=new Map;for(const[E,O]of H){const T=BE(O);q.set(E,T),s.get(E)!==T&&z.set(E,O)}const x=[...s.keys()].filter(E=>!H.has(E));z.size>0&&await r.putRecords(n.key,z),x.length>0&&await r.deleteRecords(n.key,x),s.clear();for(const[E,O]of q)s.set(E,O)};let g=Promise.resolve();const b=()=>(c&&(clearTimeout(c),c=null),g=g.then(p,p),g),v=()=>{d||c||(c=setTimeout(()=>{c=null,b().catch(U=>{if(pI(U)){console.warn("[sandbox/persistence] storage quota exceeded; recent changes are kept in memory only. Free storage or reduce sandbox data to persist them.");return}console.warn("[sandbox/persistence] auto-flush failed, will retry:",U),v()})},n.flushIntervalMs))},w=(U,H)=>{if(!H.subscribe||f.has(U))return;const z=H.subscribe(()=>{v()});f.set(U,z)},_=new Map,k=new Map,I=(U,H)=>{if(!n.sessionStorage)return;const{local:z,session:q}=n.sessionStorage,x=Gp(U),E=H.currentUid(),O=H.mode();if(E===null||O==="NONE"){z.removeItem(x),q.removeItem(x);return}const T=JSON.stringify({uid:E});O==="LOCAL"?(q.removeItem(x),z.setItem(x,T)):(z.removeItem(x),q.setItem(x,T))},N=U=>{if(!n.sessionStorage)return null;const H=Gp(U);for(const[z,q]of[["LOCAL",n.sessionStorage.local],["SESSION",n.sessionStorage.session]]){const x=q.getItem(H);if(x)try{const E=JSON.parse(x);if(typeof(E==null?void 0:E.uid)=="string")return{uid:E.uid,mode:z}}catch{q.removeItem(H)}}return null},R=U=>{if(!n.sessionStorage)return;const H=Gp(U);n.sessionStorage.local.removeItem(H),n.sessionStorage.session.removeItem(H)},M=(U,H,z)=>{if(z.session)try{z.session.restore(H.uid,H.mode),k.delete(U)}catch(q){console.warn(`[sandbox/persistence] session restore for uid '${H.uid}' failed — clearing stored session:`,q),R(U),k.delete(U)}},F=(U,H)=>{if(!n.sessionStorage||!H.session||_.has(U))return;const z=H.session;_.set(U,z.subscribe(()=>I(U,z)))},D=(U,H)=>{if(!H.session)return;const z=k.get(U)??N(U);z&&M(U,z,H)};if(t instanceof Js){for(const[U,H]of t.getServiceRegistry())w(U,H),D(U,H),F(U,H);t.setServiceRegistrationHook((U,H)=>{if(o!==null&&U in o)try{H.restore(o[U])}catch(q){console.warn(`[sandbox/persistence] late-restore for service '${U}' failed:`,q)}const z=N(U);z&&k.set(U,z),D(U,H),w(U,H),F(U,H),v()}),t.setServiceUnregistrationHook(U=>{var H,z;(H=f.get(U))==null||H(),f.delete(U),(z=_.get(U))==null||z(),_.delete(U),k.delete(U),v()})}const C=t.onEvent(U=>{bI(U)&&v()}),L=()=>{b().catch(()=>{})};return typeof window<"u"&&window.addEventListener("beforeunload",L),{options:n,flush:b,async clear(){c&&(clearTimeout(c),c=null),await r.clear(n.key),s.clear()},dispose(){if(!d){d=!0,c&&(clearTimeout(c),c=null),C();for(const U of f.values())U();f.clear();for(const U of _.values())U();_.clear(),t instanceof Js&&(t.setServiceRegistrationHook(null),t.setServiceUnregistrationHook(null)),typeof window<"u"&&window.removeEventListener("beforeunload",L)}}}}async function gI(t,e,n,r){let s;try{s=await e.listRecords(n)}catch(g){return console.warn("[sandbox/persistence] backend list failed:",g),null}if(s.length===0)return null;const o=[];for(const g of s)try{const b=await e.getRecord(n,g);b!==null&&o.push([g,b])}catch(b){console.warn(`[sandbox/persistence] failed to read persisted record '${g}':`,b)}const c=[],d=[];let f=null;for(const[g,b]of o)if(typeof b=="string"){const v=UE(b);v&&(d.push(g),f=v)}else c.push([g,b]);if(f){try{await e.putRecords(n,f),d.length>0&&await e.deleteRecords(n,d)}catch(g){console.warn("[sandbox/persistence] v2 migration write failed:",g)}for(const[g,b]of f)c.push([g,b])}for(const[g,b]of c)r.set(g,BE(b));const p=dI(c);for(const[g,b]of Object.entries(p.firestore))t.admin.setDocument(g,b);if(t instanceof Js){const g=t.getServiceRegistry();for(const[b,v]of Object.entries(p.services)){const w=g.get(b);if(w)try{w.restore(v)}catch(_){console.warn(`[sandbox/persistence] service '${b}' restore failed — Firestore state is intact; auth users may need to be re-created:`,_)}}}return p.services}function bI(t){return t.kind==="write"||t.kind==="session_boundary"}function vI(t){return typeof t=="object"&&t!==null&&typeof t.kind=="string"&&typeof t.origin=="string"}let wI=0;function xI(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`tab-${crypto.randomUUID()}`:`tab-${++wI}-${typeof performance<"u"?performance.now().toFixed(3):String(Date.now())}`}function SI(t,e={}){let n,r=!1;if(e.channel)n=e.channel,r=!1;else if(typeof BroadcastChannel<"u")n=new BroadcastChannel("pyric:tabsync"),r=!0;else return()=>{};const s=e.originId??xI();let o=!1,c=!1;const d=t.onEvent(b=>{if(b.kind!=="write"||o)return;const v={kind:"write",origin:s,event:b};n.postMessage(v)}),f=b=>{if(!vI(b.data))return;const v=b.data;if(v.origin!==s){if(v.kind==="write")g(v.event);else if(v.kind==="hello"){const w={kind:"state",origin:s,to:v.origin,snapshot:t.snapshot()};n.postMessage(w)}else if(v.kind==="state"){if(v.to!==s||c)return;if(Object.keys(Wt(t).snapshot()).length>0){c=!0;return}o=!0;try{for(const[_,k]of Object.entries(v.snapshot.firestore))t.admin.setDocument(_,k)}finally{o=!1}c=!0}}};n.addEventListener("message",f);const p={kind:"hello",origin:s};return n.postMessage(p),()=>{d(),n.removeEventListener("message",f),r&&n.close()};function g(b){o=!0;try{if(b.method==="delete")t.admin.deleteDocument(b.path);else{const v=b.nextState;v!=null&&t.admin.setDocument(b.path,v)}}finally{o=!1}}}function _I(t,e){var c;const n={...t};n.service=t.service??(e==null?void 0:e.service)??"firestore";const s="detail"in t&&((c=t.detail)==null?void 0:c.admin)===!0&&t.operationContext===void 0&&t.authLens===void 0?{...t,authLens:{mode:"admin"}}:t,o=Bm(n)||t.operationContext!==void 0?Ld(e,s):EI(t,e);return n.operationContext=o,n.actor=o.source,n.authLens=o.authLens,o.planId!==void 0&&(n.planId=o.planId),(e==null?void 0:e.activity)!==void 0&&(n.activity={...n.activity,...e.activity}),Bm(n)&&(n.rulesDisposition=Object.freeze({...OE(n)})),n}function EI(t,e){var n,r,s,o,c,d,f,p;return Zl({source:t.actor??((n=t.operationContext)==null?void 0:n.source)??(e==null?void 0:e.actor)??((r=e==null?void 0:e.operationContext)==null?void 0:r.source)??{kind:"unattributed"},authLens:t.authLens??((s=t.operationContext)==null?void 0:s.authLens)??(e==null?void 0:e.authLens)??((o=e==null?void 0:e.operationContext)==null?void 0:o.authLens)??{mode:"app-session"},...(t.planId??((c=t.operationContext)==null?void 0:c.planId)??(e==null?void 0:e.planId)??((d=e==null?void 0:e.operationContext)==null?void 0:d.planId))===void 0?{}:{planId:t.planId??((f=t.operationContext)==null?void 0:f.planId)??(e==null?void 0:e.planId)??((p=e==null?void 0:e.operationContext)==null?void 0:p.planId)}})}function AI(t,e){var s,o,c,d;if(!t)return e;if(!e)return t;if(e.operationContext!==void 0)return qE(t,e);if(!(t.operationContext!==void 0||t.actor!==void 0||t.authLens!==void 0||t.planId!==void 0||e.actor!==void 0||e.authLens!==void 0||e.planId!==void 0))return{...t,...e};const r=Zl({source:e.actor??((s=t.operationContext)==null?void 0:s.source)??t.actor??{kind:"unattributed"},authLens:e.authLens??((o=t.operationContext)==null?void 0:o.authLens)??t.authLens??{mode:"app-session"},...(e.planId??((c=t.operationContext)==null?void 0:c.planId)??t.planId)===void 0?{}:{planId:e.planId??((d=t.operationContext)==null?void 0:d.planId)??t.planId}});return{...t,...e,operationContext:r,actor:r.source,authLens:r.authLens,...r.planId===void 0?{}:{planId:r.planId}}}function qE(t,e){if(!t)return e;if(!e)return t;if(!(t.operationContext!==void 0||t.actor!==void 0||t.authLens!==void 0||t.planId!==void 0||e.operationContext!==void 0||e.actor!==void 0||e.authLens!==void 0||e.planId!==void 0))return{...t,...e};const r=Ld(t,e);return{...t,...e,operationContext:r,actor:r.source,authLens:r.authLens,...r.planId===void 0?{}:{planId:r.planId}}}let jI=1;function Li(){const t=(jI++).toString(36),e=Math.random().toString(36).slice(2,7);return`sbe-${t}-${e}`}class Js{constructor(e){G(this,"_env");G(this,"eventSubs",new Set);G(this,"envUnsubs",[]);G(this,"dispatchedCount",0);G(this,"eventHistory",[]);G(this,"ambientProvenance");G(this,"_currentUser",null);G(this,"currentUserSubs",new Set);G(this,"persistence",null);G(this,"enablePersistencePromise",null);G(this,"serviceRegistry",new Map);G(this,"_onServiceRegistered",null);G(this,"_onServiceUnregistered",null);this._env=e,this.attachToEnv()}static createRoot(){return new Js(new rS)}getEnv(){return this._env}withAuth(e){return qm(e),new ho(this,e)}attachToEnv(){this.envUnsubs.push(this._env.onRequest(e=>{this.emitEvent(e)})),this.envUnsubs.push(this._env.onWrite(e=>{this.emitEvent(e)})),this.envUnsubs.push(this._env.onSnapshotDelivery(e=>this.emitEvent(e))),this.envUnsubs.push(this._env.onSnapshotSuppressed(e=>this.emitEvent(e))),this.envUnsubs.push(this._env.onListenerLifecycle(e=>this.emitEvent(e))),this.envUnsubs.push(this._env.onSnapshotError((e,n,r)=>{var o;const s={kind:"listener_errored",id:Li(),at:Date.now(),listenerId:r,target:n.kind==="doc"?{kind:"doc",path:n.path}:{kind:"query",collection:n.collection},auth:((o=e.request)==null?void 0:o.auth)??null,error:{code:"permission-denied",message:e.message}};this.emitEvent(s)}))}emitEvent(e,n){const r=qE(this.ambientProvenance,n);this.dispatch(_I(e,r))}runWithProvenance(e,n){const r=this.ambientProvenance;this.ambientProvenance=AI(r,e);try{return n()}finally{this.ambientProvenance=r}}dispatch(e){if(this.eventHistory.push(e),this.dispatchedCount++,this.eventSubs.size!==0)for(const n of this.eventSubs)try{const r=n(e);r&&typeof r.then=="function"&&r.catch(()=>{})}catch{}}emitInternal(e,n){this.emitEvent(e,n)}onEvent(e){return this.eventSubs.add(e),()=>{this.eventSubs.delete(e)}}history(){return[...this.eventHistory]}primeEventHistory(e){return this.eventHistory.length>0||e.length===0?0:(this.eventHistory.push(...e),e.length)}get admin(){return{getDocument:e=>this._env.getDocument(e),listDocuments:e=>this._env.listDocuments(e),setDocument:(e,n)=>this._env.adminSetDocument(e,n),deleteDocument:e=>this._env.adminDeleteDocument(e)}}reset(){const e={kind:"session_boundary",id:Li(),at:Date.now(),phase:"reset",priorOpCount:this.dispatchedCount};this.emitEvent(e),this.eventHistory=[],this._currentUser!==null&&(this._currentUser=null,this.notifyCurrentUserSubs(null));for(const n of this.envUnsubs)n();this.envUnsubs=[],this._env.dispose(),this._env=new rS,this.attachToEnv()}async resetAll(){this.reset();const e=[],n=[];for(const[r,s]of this.serviceRegistry)s.reset&&n.push(Promise.resolve().then(()=>s.reset()).catch(o=>{e.push(`${r}: ${o instanceof Error?o.message:String(o)}`)}));return await Promise.all(n),{errors:e}}dispose(){const e={kind:"session_boundary",id:Li(),at:Date.now(),phase:"dispose",priorOpCount:this.dispatchedCount};this.emitEvent(e);for(const n of this.envUnsubs)n();this.envUnsubs=[],this._env.dispose(),this.persistence&&(this.persistence.dispose(),this.persistence=null),this.serviceRegistry.clear(),this._onServiceRegistered=null,this._onServiceUnregistered=null,this.eventSubs.clear(),this.currentUserSubs.clear()}snapshot(){const e={};for(const[n,r]of this.serviceRegistry)e[n]=r.snapshot();return{firestore:this._env.snapshot(),services:e}}loadSnapshot(e){this.reset();for(const[n,r]of Object.entries(e.firestore))this._env.adminSetDocument(n,r);for(const[n,r]of this.serviceRegistry)if(n in e.services)try{r.restore(e.services[n])}catch(s){console.warn(`[sandbox] loadSnapshot: service '${n}' restore failed — Firestore is intact; that service's state may be incomplete:`,s)}}get currentUser(){return this._currentUser}set currentUser(e){qm(e),!kI(this._currentUser,e)&&(this._currentUser=e,this.notifyCurrentUserSubs(e))}onCurrentUserChanged(e){return this.currentUserSubs.add(e),()=>{this.currentUserSubs.delete(e)}}notifyCurrentUserSubs(e){if(this._env.reevaluateLiveListeners(e),this.currentUserSubs.size!==0)for(const n of this.currentUserSubs)try{const r=n(e);r&&typeof r.then=="function"&&r.catch(()=>{})}catch{}}async enablePersistence(e){if(this.persistence){if(this.persistence.options.key!==e.key)throw new nt("failed-precondition",`Persistence already enabled with key '${this.persistence.options.key}'; cannot re-enable with key '${e.key}'. Dispose and recreate the sandbox.`);return}if(this.enablePersistencePromise)return this.enablePersistencePromise;this.enablePersistencePromise=(async()=>{const n=await yI(this,e);this.persistence=n})();try{await this.enablePersistencePromise}finally{this.enablePersistencePromise=null}}enableTabSync(e){return SI(this,e)}async flush(){if(!this.persistence)throw new nt("failed-precondition","flush() called before enablePersistence()");await this.persistence.flush()}async clearPersistence(){this.persistence&&await this.persistence.clear()}registerPersistableService(e,n){if(this.serviceRegistry.has(e))throw new nt("failed-precondition",`registerPersistableService: a service named '${e}' is already registered on this sandbox. Each service name must be unique — the auth package registers 'auth' exactly once per sandbox.`);return this.serviceRegistry.set(e,n),this._onServiceRegistered&&this._onServiceRegistered(e,n),()=>{var r;this.serviceRegistry.get(e)===n&&(this.serviceRegistry.delete(e),(r=this._onServiceUnregistered)==null||r.call(this,e))}}setServiceRegistrationHook(e){this._onServiceRegistered=e}setServiceUnregistrationHook(e){this._onServiceUnregistered=e}getServiceRegistry(){return this.serviceRegistry}}function kI(t,e){if(t===e)return!0;if(t===null||e===null||t.uid!==e.uid)return!1;const n=t.token===void 0?void 0:JSON.stringify(t.token),r=e.token===void 0?void 0:JSON.stringify(e.token);return n===r}function Wt(t){if(!(t instanceof Js))throw new nt("invalid-argument","Sandbox handle was not produced by initializeSandbox(); custom Sandbox implementations are not supported.");return t.getEnv()}function Vs(t,e,n){if(!(t instanceof Js))throw new nt("invalid-argument","Sandbox handle was not produced by initializeSandbox(); custom Sandbox implementations are not supported.");t.emitInternal(e,n)}function $d(t){return{kind:"service_mutation",id:Li(),at:Date.now(),...t}}function FE(t){const{at:e,...n}=t;return{kind:"operation",id:Li(),at:e??Date.now(),...n}}function CI(t){const{at:e,...n}=t;return{kind:"commit",id:Li(),at:e??Date.now(),...n}}function NI(t){const{at:e,...n}=t;return{kind:"listener",id:Li(),at:e??Date.now(),...n}}const OI=Symbol.for("pyric.remote.sandbox");function rg(t){return t!=null&&t[OI]===!0}function zE(t,e=""){const n=VE();return Wt(n).seed({rules:e,baseDocuments:t.firestore}),{sandbox:n,rules:e,base:t,events:[],discarded:!1}}function RI(t,e){TI(t);const n=Wt(t.sandbox).snapshot(),r=DI(e);return MI(r,n)}function PE(t){t.discarded||(t.discarded=!0,t.sandbox.dispose())}function TI(t){if(t.discarded)throw new Error("Branch has been discarded or promoted; create a new fork.")}function DI(t){return II(t)?Wt(t).snapshot():t.firestore}function II(t){return typeof t.snapshot=="function"}function MI(t,e){const n=[],r=new Set([...Object.keys(t),...Object.keys(e)]);for(const s of r){const o=t[s],c=e[s];if(o===void 0&&c!==void 0){n.push({kind:"real-divergence",path:s,before:void 0,after:c});continue}if(o!==void 0&&c===void 0){n.push({kind:"real-divergence",path:s,before:o,after:void 0});continue}o===void 0||c===void 0||LI(s,o,c,n)}return n}function LI(t,e,n,r){s(e,n,"");function s(o,c,d){if(o===c)return;const f=o!==null&&typeof o=="object"&&!Array.isArray(o),p=c!==null&&typeof c=="object"&&!Array.isArray(c);if(f&&p){const g=o,b=c,v=new Set([...Object.keys(g),...Object.keys(b)]);for(const w of v){const _=d?`${d}.${w}`:w;s(g[w],b[w],_)}return}if(Array.isArray(o)&&Array.isArray(c)){const g=Math.max(o.length,c.length);for(let b=0;b<g;b++)s(o[b],c[b],`${d}[${b}]`);return}Vm(o,c)||r.push({kind:"real-divergence",path:t,field:d||void 0,before:o,after:c})}}function Vm(t,e){if(t===e)return!0;if(t===null||e===null||typeof t!="object"||typeof e!="object")return!1;const n=Array.isArray(t),r=Array.isArray(e);if(n!==r)return!1;if(n&&r){if(t.length!==e.length)return!1;for(let f=0;f<t.length;f++)if(!Vm(t[f],e[f]))return!1;return!0}const s=t,o=e,c=Object.keys(s),d=Object.keys(o);if(c.length!==d.length)return!1;for(const f of c)if(!Object.prototype.hasOwnProperty.call(o,f)||!Vm(s[f],o[f]))return!1;return!0}function VE(t={}){return Js.createRoot()}function hl(t,e){return`${t.replace(/\/$/,"")}${e}`}function UI(t){const e=t;return{async read(n){const r=await fetch(hl(e,`/__pyric/workspace?path=${encodeURIComponent(n)}`));if(r.status===404)return null;if(!r.ok)throw new Error(`workspace.read(${n}) → ${r.status}`);return r.text()},async write(n,r){const s=await fetch(hl(e,`/__pyric/workspace?path=${encodeURIComponent(n)}`),{method:"PUT",body:r});if(!s.ok)throw new Error(`workspace.write(${n}) → ${s.status}`)},async list(n){const r=n?`?dir=${encodeURIComponent(n)}`:"",s=await fetch(hl(e,`/__pyric/workspace/list${r}`));if(!s.ok)throw new Error(`workspace.list(${n??""}) → ${s.status}`);return await s.json()},async remove(n){const r=await fetch(hl(e,`/__pyric/workspace?path=${encodeURIComponent(n)}`),{method:"DELETE"});if(!r.ok)throw new Error(`workspace.remove(${n}) → ${r.status}`)},watch(n){const r=new EventSource(hl(e,"/__pyric/workspace/watch")),s=o=>{try{n(JSON.parse(o.data))}catch{}};return r.addEventListener("change",s),()=>{r.removeEventListener("change",s),r.close()}}}}function pl(t,e){return`${t.replace(/\/$/,"")}${e}`}function $I(t){const e=t;return{async list(){const n=await fetch(pl(e,"/__pyric/projects"));if(!n.ok)throw new Error(`projects.list() → ${n.status}`);return await n.json()},async open(n){const r=await fetch(pl(e,`/__pyric/projects/${encodeURIComponent(n)}`));if(!r.ok)throw new Error(`projects.open(${n}) → ${r.status}`);return{meta:await r.json(),workspace:UI(e)}},async create(n){const r=await fetch(pl(e,"/__pyric/projects"),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(n)});if(!r.ok)throw new Error(`projects.create() → ${r.status}`);return await r.json()},async update(n,r){const s=await fetch(pl(e,`/__pyric/projects/${encodeURIComponent(n)}`),{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify(r)});if(!s.ok)throw new Error(`projects.update(${n}) → ${s.status}`)},async remove(n){const r=await fetch(pl(e,`/__pyric/projects/${encodeURIComponent(n)}`),{method:"DELETE"});if(!r.ok)throw new Error(`projects.remove(${n}) → ${r.status}`)}}}function BI(t,e){return`${t.replace(/\/$/,"")}${e}`}function Kp(t){return/auth/i.test(t)?"auth":"firestore"}function qI(t){const e=t,r={"content-type":"application/json","x-pyric-writer":`studio-${Math.random().toString(36).slice(2)}`},s=new Map,o=f=>BI(e,`/__pyric/state?section=${Kp(f)}`),c=async f=>{const p=Kp(f),g=s.get(p);if(g)return g;const b=await fetch(o(f));let v=new Map;if(b.ok){const w=await b.text();w&&w!=="null"&&(v=uI(w))}else if(b.status!==404)throw new Error(`persistence.read(${f}) → ${b.status}`);return s.set(p,v),v},d=async(f,p)=>{const g=await fetch(o(f),{method:"POST",headers:r,body:cI(p)});if(g.status===423)throw new Error("persistence.write blocked, another tab holds the persist writer lock");if(!g.ok)throw new Error(`persistence.write(${f}) → ${g.status}`)};return{async getRecord(f,p){return(await c(f)).get(p)??null},async listRecords(f){return[...(await c(f)).keys()]},async putRecords(f,p){const g=await c(f);for(const[b,v]of p)g.set(b,v);await d(f,g)},async deleteRecords(f,p){const g=await c(f);for(const b of p)g.delete(b);await d(f,g)},async clear(f){s.set(Kp(f),new Map);const p=await fetch(o(f),{method:"POST",headers:r,body:"null"});if(!p.ok&&p.status!==423)throw new Error(`persistence.clear(${f}) → ${p.status}`)}}}const FI="local";function zI(){const t=new Map,e=new Set,n=r=>{for(const s of e)s(r)};return{async read(r){return t.has(r)?t.get(r):null},async write(r,s){const o=t.has(r)?"update":"create";t.set(r,s),n({path:r,type:o})},async list(r){const s=r?`${r.replace(/\/+$/,"")}/`:"",o=[];for(const c of t.keys())s&&!c.startsWith(s)||o.push({path:c,kind:"file"});return o},async remove(r){t.delete(r)&&n({path:r,type:"delete"})},watch(r){return e.add(r),()=>e.delete(r)}}}function PI(){const t=zI();let e={id:FI,title:"Local Project",createdAt:Date.now(),updatedAt:Date.now()};return{async list(){return[e]},async open(n){if(n!==e.id)throw new Error(`Static Studio runs in single-project mode — no project '${n}'.`);return{meta:e,workspace:t}},async create(){throw new Error("Static Studio runs in single-project mode — creating additional projects is not supported.")},async update(n,r){n===e.id&&(e={...e,...r,updatedAt:Date.now()})},async remove(){}}}class Wi extends Error{constructor(n,r,s){super(r);G(this,"code");G(this,"customData");G(this,"name","FirebaseError");this.code=n,this.customData=s,Object.setPrototypeOf(this,new.target.prototype)}}Object.defineProperty(Wi,"name",{value:"FirebaseError"});let Wa;function VI(t){Wa=t}function sg(t){return Wa==null?void 0:Wa.resolve(t,!1)}function HE(){if(!Wa)throw new TypeError("No default sandbox app registry is installed - import and initialize pyric/app before calling a service factory without an app.");return Wa.defaultApp()}function HI(){let t=null;const e=new Set;return{get currentUser(){return t},set currentUser(n){if(t!==n){t=n;for(const r of[...e])r(n)}},onCurrentUserChanged(n){return e.add(n),()=>e.delete(n)}}}const GE=new WeakMap;let Hm;function GI(t,e,n=HI()){const r=t.name,s=n===e?void 0:{},o=new Map,c=new Set,d={app:t,sandbox:e,session:n,services:o,cleanups:c,assertAlive(){if(d.deleted)throw new Wi("app/app-deleted",`Firebase: Firebase App named '${r}' already deleted (app/app-deleted).`)},...s?{authScope:s}:{},service(f,p){const g=o.get(f);if(g!==void 0)return g;d.assertAlive();const b=p();return o.set(f,b),b},onDelete(f){return d.deleted?(f(),()=>{}):(c.add(f),()=>c.delete(f))},deleted:!1};return GE.set(t,d),d}function KI(t){Hm=t}VI({resolve(t,e){const n=typeof t=="object"&&t!==null?GE.get(t):void 0;if(n)return n},defaultApp(){if(!Hm)throw new TypeError("No default sandbox app registry is installed - import and initialize pyric/app before calling a service factory without an app.");return Hm()}});const YI="[DEFAULT]",ZI=new Map;function WI(t,e){return new Wi(`app/${t}`,`Firebase: ${e} (app/${t}).`)}function QI(t){return WI("no-app",`No Firebase App '${t}' has been created - call initializeApp() first`)}function JI(t=YI){const e=ZI.get(t);if(!e)throw QI(t);return e.app}KI(JI);let XI=0,eM=0;function Ae(){return`op-${++XI}`}function po(){return`sub-${++eM}`}const Gm=new Map,ig=new Map,ag=new Map,Ql=new WeakSet,tM=new Set;function nM(){return Object.assign(new Error("Firebase App was deleted"),{code:"app/app-deleted"})}function Jl(t,e,n,r){return Ql.has(t)?!1:(ig.set(e,n),t.postMessage(r),!0)}function rM(t,e,n,r){return Ql.has(t)?!1:(ag.set(e,{port:t,next:n}),t.postMessage(r),!0)}function Xl(t,e){ig.delete(e),ag.delete(e),Ql.has(t)||t.postMessage({t:"unsub",subId:e})}function lS(t,e){if(e.denialContext===void 0||typeof fetch!="function")return;const n={kind:t,code:e.code,message:e.message,denialContext:e.denialContext,...typeof e.remediation=="string"?{remediation:e.remediation}:{}};try{fetch("/__pyric/denials",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(n)}).catch(()=>{})}catch{}}function og(t){t.onmessage=e=>{const n=e.data;if(n.t==="res"){const r=Gm.get(n.id);if(!r)return;if(Gm.delete(n.id),n.ok)r.resolve(n.value);else{const s=new Error(n.error.message);s.code=n.error.code,n.error.denialContext!==void 0&&(s.denialContext=n.error.denialContext),n.error.aiEnvelope!==void 0&&(s.aiEnvelope=n.error.aiEnvelope),lS("read",s),r.reject(s)}}else if(n.t==="snap"){const r=ig.get(n.subId);if(!r)return;const s=n.value??{};if(s.__error){const o=s.__error,c=new Error(o.message);c.code=o.code,o.denialContext!==void 0&&(c.denialContext=o.denialContext),o.aiEnvelope!==void 0&&(c.aiEnvelope=o.aiEnvelope),lS("listener",c),r.error?r.error(c):console.error("pyric/firestore: Uncaught Error in snapshot listener:",c);return}r.next(n.value)}else if(n.t==="event"){const r=ag.get(n.subId);r&&r.next(n.events)}else if(n.t==="runtime-reload")for(const r of tM)r(n)}}let io;function cS(t){io=t&&t.mode==="app-session"?void 0:t}function sM(){return io}let Km;function iM(t){Km=t}function lg(t){return Km&&(t.t==="op"||t.t==="sub")?{...t,issuer:Km}:t}function KE(t,e){return Ql.has(t)?Promise.reject(nM()):new Promise((n,r)=>{const s=e;Gm.set(s.id,{port:t,resolve:n,reject:r}),t.postMessage(e)})}function Ye(t,e){return KE(t,lg(e))}function nr(t,e){if(Ql.has(t)&&!e.method.startsWith("rtdb."))return Promise.reject(new Wi("failed-precondition","The client has already been terminated."));const n=io?{...e,actAs:io}:e;return Ye(t,n)}function aM(t,e,n={}){if(typeof SharedWorker>"u")throw new Error("SharedWorker is not available. Open this page over http:// (not file://) and use a supported browser (Chrome 4+, Firefox 29+, Safari 16.4+).");const r=new SharedWorker(t,{type:"classic",name:"pyric-shared-worker"});n.onError&&r.addEventListener("error",o=>{var d;const c=o.message||`failed to load ${String(t)}`;(d=n.onError)==null||d.call(n,new Error(`Pyric SharedWorker error: ${c}`))});const s=r.port;return og(s),s.start(),{__kind:"client-db",port:s}}async function oM(t){return(await Ye(t.port,{t:"op",id:Ae(),method:"getVersion"})).instanceId??""}async function lM(t){return(await Ye(t.port,{t:"op",id:Ae(),method:"exportState"})).bundle}async function cM(t,e){await Ye(t.port,{t:"op",id:Ae(),method:"importState",bundle:e})}async function uM(t,e){await Ye(t.port,{t:"op",id:Ae(),method:"saveBranch",name:e})}async function dM(t){return(await Ye(t.port,{t:"op",id:Ae(),method:"listBranches"})).branches??[]}async function fM(t,e){await Ye(t.port,{t:"op",id:Ae(),method:"switchBranch",name:e})}async function hM(t,e){await Ye(t.port,{t:"op",id:Ae(),method:"deleteBranch",name:e})}async function pM(t,e,n){return await Ye(t.port,{t:"tool",id:Ae(),name:e,args:n})}function mM(t,e){return KE(t.port,{...e,issuer:void 0,relaySource:"remote",t:"op",id:Ae()})}function yM(t,e,n){if(e.target==="events")throw new Error("event-stream subscriptions cannot be relayed over the bridge yet (needs bounded backpressure — slice 2)");const r=po();return Jl(t.port,r,{port:t.port,next:n,error:o=>n({__error:{code:o.code??"unknown",message:o instanceof Error?o.message:String(o)}})},{...e,issuer:void 0,relaySource:"remote",t:"sub",subId:r})||queueMicrotask(()=>n({__error:{code:"app/app-deleted",message:"Firebase App was deleted"}})),()=>{Xl(t.port,r)}}function cg(t){return t.split("/").at(-1)??t}function gM(t,...e){const n=("port"in t,t.port);let r;if(t.__kind==="client-db"){if(e.length===0)throw new TypeError("doc(db, path) requires a path segment.");r=e.join("/")}else{const o=t.descriptor.path;r=e.length>0?`${o}/${e.join("/")}`:o}return{__kind:"doc-ref",descriptor:{__ref:"doc",path:r},port:n,id:cg(r),path:r}}function bM(t,...e){const n=t.port;if(e.length===0)throw new TypeError("collection() requires a path segment.");let r;return t.__kind==="client-db"?r=e.join("/"):r=`${t.descriptor.path}/${e.join("/")}`,{__kind:"coll-ref",descriptor:{__ref:"collection",path:r},port:n,id:cg(r),path:r}}function vM(t){return{_descriptor:{kind:"limit",n:t}}}function wM(...t){return{_descriptor:{kind:"startAfter",values:t}}}function xM(t,...e){const n=(t.__kind==="coll-ref",t.descriptor),r=t.__kind==="query"?t.descriptor.constraints:[];return{__kind:"query",descriptor:{__ref:"query",source:n.__ref==="query"?n.source:n,constraints:[...r,...e.map(o=>o._descriptor)]},port:t.port}}function SM(t){return Ud(JSON.parse(t.json))}const YE=8*1024*1024;function _M(t,e){const n=new Error(`${e} is ${t} bytes — over the ${YE/1048576} MiB storage op cap (MAX_STORAGE_OP_BYTES). Streaming/resumable transfers are not supported on the sandbox backend; split the object or keep it under the cap.`);return n.code="payload-too-large",n}function EM(t){let e="";for(let r=0;r<t.length;r+=32768){const s=t.subarray(r,r+32768);e+=String.fromCharCode.apply(null,s)}return btoa(e)}function AM(t){return SM(t)}function ug(t,e){const n=t.exists&&t.data?AM(t.data):void 0,r=t.path??t.id,s={__kind:"doc-ref",descriptor:{__ref:"doc",path:r},port:e,id:t.id,path:r};return{id:t.id,path:r,ref:s,exists:()=>t.exists,data:()=>n}}function ZE(t,e){const n=t.docs.map(r=>ug(r,e));return{size:n.length,empty:n.length===0,docs:n}}async function jM(t){const e=await nr(t.port,{t:"op",id:Ae(),method:"getDoc",path:t.descriptor.path});return ug(e,t.port)}async function kM(t){const e=await nr(t.port,{t:"op",id:Ae(),method:"getDocs",source:(t.__kind==="coll-ref",t.descriptor)});return ZE(e,t.port)}async function CM(t){return(await nr(t.port,{t:"op",id:Ae(),method:"listRootCollections"})).ids}async function NM(t,e){return(await nr(t.port,{t:"op",id:Ae(),method:"listSubcollections",docPath:e})).ids}function OM(t,e,n){const r=po(),s=t.port,o={port:s,service:"firestore",next:f=>{const p=f;"docs"in p?e(ZE(p,s)):e(ug(p,s))},error:n},c=(t.__kind==="doc-ref"||t.__kind==="coll-ref",t.descriptor);return!Jl(s,r,o,lg(io?{t:"sub",subId:r,target:c,actAs:io}:{t:"sub",subId:r,target:c}))&&n&&queueMicrotask(()=>n(new Error("Firebase App was deleted"))),()=>{Xl(s,r)}}async function RM(t,e,n){await nr(t.port,{t:"op",id:Ae(),method:"setDoc",path:t.descriptor.path,data:e,options:n})}async function TM(t){await nr(t.port,{t:"op",id:Ae(),method:"deleteDoc",path:t.descriptor.path})}async function DM(t,e){const n=await nr(t.port,{t:"op",id:Ae(),method:"addDoc",collectionPath:t.descriptor.path,data:e});return{__kind:"doc-ref",descriptor:{__ref:"doc",path:n.path},port:t.port,id:n.id,path:n.path}}async function IM(t,e){return await Ye(t.port,{t:"op",id:Ae(),method:"admin.listDocuments",path:e})}function MM(t){const e=(t??"/").split("/").filter(Boolean).join("/");return e?`/${e}`:"/"}new Array(12).fill(0);async function LM(t){return Ye(t.port,{t:"op",id:Ae(),method:"rtdb.adminSnapshot"})}async function UM(t,e,n){await Ye(t.port,{t:"op",id:Ae(),method:"rtdb.set",path:e,value:n,actAs:{mode:"admin"}})}async function $M(t,e,n){await Ye(t.port,{t:"op",id:Ae(),method:"rtdb.update",path:e,values:n,actAs:{mode:"admin"}})}async function BM(t,e){await Ye(t.port,{t:"op",id:Ae(),method:"rtdb.remove",path:e,actAs:{mode:"admin"}})}function qM(t,e,n,r){const s=po();return!Jl(t.port,s,{port:t.port,next:c=>n((c==null?void 0:c.value)??null),error:r},lg({t:"sub",subId:s,target:{service:"rtdb",path:MM(e)},actAs:{mode:"admin"}}))&&r&&queueMicrotask(()=>r(new Error("FIREBASE FATAL ERROR: Database has been deleted."))),()=>{Xl(t.port,s)}}function FM(t,e){const n=po(),r=t.port;return rM(r,n,e,{t:"sub",subId:n,target:"events"}),()=>{Xl(r,n)}}async function zM(t){return await Ye(t.port,{t:"op",id:Ae(),method:"getSnapshot"})}async function PM(t){return await Ye(t.port,{t:"op",id:Ae(),method:"resetAll"})??{errors:[]}}const VM=15e3;function HM(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`page-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function uS(){return typeof location>"u"?"/":`${location.pathname}${location.search}${location.hash}`}function dS(){return typeof document>"u"?"visible":document.visibilityState==="hidden"?"hidden":"visible"}function GM(t){const{db:e,kind:n}=t,r=t.clientId??HM(),s=t.heartbeatIntervalMs??VM;let o=!1,c=null;const d=()=>{Ye(e.port,{t:"op",id:Ae(),method:"presence.register",clientId:r,kind:n,route:uS(),visibility:dS()}).catch(()=>{})},f=()=>{Ye(e.port,{t:"op",id:Ae(),method:"presence.heartbeat",clientId:r}).catch(()=>{})},p=()=>{Ye(e.port,{t:"op",id:Ae(),method:"presence.update",clientId:r,route:uS(),visibility:dS()}).catch(()=>{})},g=()=>{Ye(e.port,{t:"op",id:Ae(),method:"presence.disconnect",clientId:r}).catch(()=>{})};d(),typeof document<"u"&&document.addEventListener("visibilitychange",p),typeof window<"u"&&(window.addEventListener("popstate",p),window.addEventListener("hashchange",p),window.addEventListener("pagehide",b),c=setInterval(()=>{o||f()},s));function b(){v()}function v(){o||(o=!0,c!=null&&(clearInterval(c),c=null),typeof document<"u"&&document.removeEventListener("visibilitychange",p),typeof window<"u"&&(window.removeEventListener("popstate",p),window.removeEventListener("hashchange",p),window.removeEventListener("pagehide",b)),g())}return{clientId:r,kind:n,stop:v}}function KM(t,e){const n=po();return Jl(t.port,n,{port:t.port,next:r=>{e(r)}},{t:"sub",subId:n,target:"presence"}),()=>{Xl(t.port,n)}}const YM=Symbol("pyric.clientUser.port");function ZM(t,e){const n={uid:e.uid,email:e.email,emailVerified:e.emailVerified,displayName:e.displayName,photoURL:e.photoURL,phoneNumber:e.phoneNumber,isAnonymous:e.isAnonymous,providerId:e.providerId,providerData:e.providerData,async getIdToken(r){return await Ye(t,{t:"op",id:Ae(),method:"auth.getIdToken",forceRefresh:r})},async getIdTokenResult(r){return await Ye(t,{t:"op",id:Ae(),method:"auth.getIdTokenResult",forceRefresh:r})}};return Object.defineProperty(n,YM,{value:t,enumerable:!1}),n}function WM(t,e){return e?ZM(t,e):null}function QM(t,e){let n;if(typeof t=="object"&&"__kind"in t&&t.__kind==="client-db")n=t.port;else{if(typeof SharedWorker>"u")throw new Error("SharedWorker is not available. Open this page over http:// (not file://) and use a supported browser (Chrome 4+, Firefox 29+, Safari 16.4+).");n=new SharedWorker(t,{type:"classic",name:"pyric-shared-worker"}).port,n.start(),og(n)}const r={__kind:"client-auth",port:n,currentUser:null},s=po();return Jl(n,s,{port:n,next:o=>{r.currentUser=WM(n,o)}},{t:"sub",subId:s,target:"authState"}),r}async function JM(t){return await Ye(t.port,{t:"op",id:Ae(),method:"auth.listUsers"})}async function XM(t,e){return await Ye(t.port,{t:"op",id:Ae(),method:"auth.adminCreateUser",request:e})}async function eL(t,e,n){return await Ye(t.port,{t:"op",id:Ae(),method:"auth.adminUpdateUser",uid:e,request:n})}async function tL(t,e){await Ye(t.port,{t:"op",id:Ae(),method:"auth.adminDeleteUser",uid:e})}async function nL(t){await Ye(t.port,{t:"op",id:Ae(),method:"auth.adminClearUsers"})}async function rL(t){return await Ye(t.port,{t:"op",id:Ae(),method:"auth.getProviderConfig"})}async function sL(t,e,n){await Ye(t.port,{t:"op",id:Ae(),method:"auth.setProviderConfig",providerId:e,enabled:n})}function iL(t){return t.replace(/^\/+|\/+$/g,"")}function aL(t,e){let n;if(typeof t=="object"&&"__kind"in t&&t.__kind==="client-db")n=t.port;else{if(typeof SharedWorker>"u")throw new Error("SharedWorker is not available. Open this page over http:// (not file://) and use a supported browser.");n=new SharedWorker(t,{type:"classic",name:"pyric-shared-worker"}).port,n.start(),og(n)}return{__kind:"client-storage",port:n}}function oL(t,e){const n=iL(e??"");let r;if(t.__kind==="client-storage")r=n;else{const s=t.fullPath;r=n?s?`${s}/${n}`:n:s}return{__kind:"storage-ref",port:t.port,fullPath:r,name:cg(r)}}async function lL(t){const e=await nr(t.port,{t:"op",id:Ae(),method:"storage.listAll",path:t.fullPath}),n=r=>({__kind:"storage-ref",port:t.port,fullPath:r.fullPath,name:r.name});return{items:e.items.map(n),prefixes:e.prefixes.map(n)}}async function cL(t){return await nr(t.port,{t:"op",id:Ae(),method:"storage.getMetadata",path:t.fullPath})}async function uL(t){return await nr(t.port,{t:"op",id:Ae(),method:"storage.getBlob",path:t.fullPath})}async function dL(t,e,n){const r=e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof ArrayBuffer?new Uint8Array(e):e;if(r.byteLength>YE)throw _M(r.byteLength,`uploadBytes payload for '${t.fullPath}'`);const s=(n==null?void 0:n.contentType)??(e instanceof Blob&&e.type?e.type:void 0),o=await nr(t.port,{t:"op",id:Ae(),method:"storage.putBytes",path:t.fullPath,dataB64:EM(r),...s!==void 0?{contentType:s}:{},...n!==void 0?{metadata:n}:{}});return{ref:t,metadata:o}}async function fL(t){await nr(t.port,{t:"op",id:Ae(),method:"storage.deleteObject",path:t.fullPath})}const hL="/__pyric/sdk/worker.js";function pL(t){let e=[],n=!1;const r=new Set;let s=null;function o(){s||(s=FM(t,c=>{const d=!n;n=!0;const f=d?[]:[...e];for(const p of c)m1(p)&&(f.length=0),f.push(p);e=f;for(const p of c)for(const g of r)g(p)}))}return{history:()=>e,subscribe:c=>(r.add(c),o(),()=>{r.delete(c),r.size===0&&s&&(s(),s=null,n=!1,e=[])})}}function mL(t=hL){if(typeof SharedWorker>"u")return null;iM("studio");let e;try{e=aM(t)}catch{return null}cS({mode:"admin"});const n=GM({db:e,kind:"studio"}),r=pL(e),s=QM(e);return{db:e,presenceClientId:n.clientId,subscribePresence:o=>KM(e,o),instanceId:()=>oM(e),exportState:()=>lM(e),importState:o=>cM(e,o),saveBranch:o=>uM(e,o),listBranches:()=>dM(e),switchBranch:o=>fM(e,o),deleteBranch:o=>hM(e,o),feed:r,setLens:o=>cS(o),getLens:()=>sM(),listRootCollections:()=>CM(e),listSubcollections:o=>NM(e,o),listDocuments:async o=>(await IM(e,o)).map(({path:c,phantom:d})=>({path:c,phantom:d})),readRtdbState:()=>LM(e),setRtdbValue:(o,c)=>UM(e,o,c),updateRtdbValue:(o,c)=>$M(e,o,c),deleteRtdbValue:o=>BM(e,o),subscribeRtdbValue:(o,c,d)=>qM(e,o,c,d),firestoreApi:{collection:bM,doc:gM,getDoc:jM,getDocs:kM,onSnapshot:OM,setDoc:RM,deleteDoc:TM,addDoc:DM,query:xM,limit:vM,startAfter:wM},auth:s,authApi:{listUsers:()=>JM(s),subscribeUsers:(o,c)=>r.subscribe(d=>{d.kind==="service_mutation"&&d.service==="auth"&&c()}),createUser:(o,c)=>XM(s,c),updateUser:(o,c,d)=>eL(s,c,d),deleteUser:(o,c)=>tL(s,c),clearUsers:()=>nL(s),getAuthProviderConfig:()=>rL(s),setAuthProviderConfig:(o,c,d)=>sL(s,c,d),subscribeAuthProviderConfig:(o,c)=>r.subscribe(d=>{d.kind==="service_mutation"&&d.op==="provider_config_update"&&c()})},storage:aL(e),storageApi:{ref:oL,listAll:lL,getMetadata:cL,getBlob:uL,uploadBytes:dL,deleteObject:fL},getSnapshot:()=>zM(e),resetAll:()=>PM(e)}}const fS=5174,hS="/sandbox",yL=4001,gL="worker-relay";function bL(t){if(t===null||typeof t!="object")return!1;const e=t.type;return e==="hello"||e==="hello-ack"||e==="attach"||e==="attach-ack"||e==="tool-call"||e==="tool-result"||e==="worker-op"||e==="worker-res"||e==="worker-sub"||e==="worker-unsub"||e==="worker-snap"||e==="ping"||e==="pong"}function Ym(t){var e;if(t===null||typeof t!="object")return null;if(typeof Blob<"u"&&t instanceof Blob)return"Blob";if(t instanceof ArrayBuffer)return"ArrayBuffer";if(ArrayBuffer.isView(t))return((e=t.constructor)==null?void 0:e.name)??"TypedArray";if(Array.isArray(t)){for(const n of t){const r=Ym(n);if(r)return r}return null}for(const n of Object.values(t)){const r=Ym(n);if(r)return r}return null}function pS(t,e){const n=Ym(e);if(!n)return;const r=new Error(`worker ${t} produced a binary payload (${n}) that cannot cross the JSON bridge relay — it would be silently corrupted by JSON.stringify. Use the base64 storage ops instead ('storage.getBytes' / 'storage.putBytes'), which carry bytes as JSON-safe 'dataB64' strings; 'storage.getBlob' is MessagePort-only.`);throw r.code="invalid-argument",r}const vL=()=>{throw new Error("pyric dev: fs is not available in the browser")},mS=vL,Zm=(...t)=>t.join("/"),wL=t=>t.split("/").slice(0,-1).join("/")||"/",xL=t=>String(t).replace("file://",""),SL=wL(xL(import.meta.url)),_L=Zm(SL,"stdlib"),EL={readRelative(t,e){try{return mS(Zm(t,`${e}.rules`),"utf-8")}catch{return null}},readStdlib(t){try{return mS(Zm(_L,`${t}.rules`),"utf-8")}catch{return null}}};function AL(t,e){return z2(EL,t,e)}function jL(t){const{resolveSandbox:e,resolveModulesFn:n}=t;return[{name:"firestore_simulator_create",description:'Seed the session\'s local Firestore environment with rules and optional initial documents. Resets any prior state. Supports `rules_version = "2+modules"` — modules resolve in-process before seeding. Returns the lint result + document count for verification.',parameters:{type:"object",properties:{rules:{type:"string",description:"Firestore security rules source (version 2 or 2+modules)."},documents:{type:"object",description:'Initial documents keyed by full path, e.g. `{ "users/u1": { name: "alice" } }`.',additionalProperties:!0}},required:["rules"]},async execute(r){const{rules:s,documents:o}=r;let c=s;if(c.includes("'2+modules'")||c.includes('"2+modules"')){if(!n)return{ok:!1,summary:"Module resolve unavailable: this builder was not wired with `resolveModulesFn`. Use a package entry that wires module resolution, such as pyric/rules/node, instead of importing the impl directly.",data:{code:"NO_MODULE_RESOLVER"}};const p=n(c);if(!p.success)return{ok:!1,summary:`Module resolve failed: ${p.error.message}`,data:p};c=p.data.resolved}const f=(await e()).seed({rules:c,documents:o??{}});return{ok:!0,summary:`Seeded sandbox with ${Object.keys(o??{}).length} document(s)`,data:{lint:f,documentCount:Object.keys(o??{}).length}}}},{name:"firestore_simulator_execute",description:"Execute a single write (create / update / delete) against the seeded sandbox. Rules evaluate against the in-memory state; allow → state mutates and the op is logged, deny → state unchanged and `debugMessages` explain the rule decision.",parameters:{type:"object",properties:{method:{type:"string",enum:["create","update","delete"]},path:{type:"string",description:"Document path, e.g. `users/u1`."},auth:{description:"Auth context. `null` for unauthenticated. Otherwise `{ uid, token? }` where `token` is the custom-claims object."},data:{type:"object",description:"Document data. Required for create / update.",additionalProperties:!0}},required:["method","path","auth"]},async execute(r){const{method:s,path:o,auth:c,data:d}=r,p=(await e()).execute({method:s,path:o,auth:c,data:d});return{ok:p.allowed,summary:p.allowed?`${s} on ${o} allowed`:`${s} on ${o} denied`,data:{allowed:p.allowed,debugMessages:p.debugMessages}}}},{name:"firestore_simulator_read",description:"Read a document (`get`) or list a collection (`list`) from the seeded sandbox. Default uses admin access (bypasses rules). Set `evaluateRules: true` with an `auth` context to test read access control through the rules engine.",parameters:{type:"object",properties:{path:{type:"string",description:"Doc path for `get`, collection path for `list`."},method:{type:"string",enum:["get","list"],description:"Default `get`."},auth:{description:"Auth context. Required when `evaluateRules` is true."},evaluateRules:{type:"boolean",description:"Evaluate read rules against `auth`. Default false (admin read)."}},required:["path"]},async execute(r){const{path:s,method:o,auth:c,evaluateRules:d}=r,f=await e();if(d){const p=f.execute({method:o??"get",path:s,auth:c??null});return{ok:p.allowed,summary:p.allowed?`${o??"get"} on ${s} allowed`:`${o??"get"} on ${s} denied`,data:{allowed:p.allowed,document:p.data,debugMessages:p.debugMessages}}}return o==="list"?{ok:!0,summary:`Listed ${s}`,data:{documents:f.listDocuments(s)}}:{ok:!0,summary:`Read ${s}`,data:{document:f.getDocument(s)}}}},{name:"firestore_simulator_batch",description:"Execute multiple writes atomically. All operations must pass rules — if any denies, none apply. Rules evaluate each op against pre-batch state (no cross-visibility within the batch).",parameters:{type:"object",properties:{operations:{type:"array",items:{type:"object",properties:{method:{type:"string",enum:["create","update","delete"]},path:{type:"string"},data:{type:"object",additionalProperties:!0}},required:["method","path"]}},auth:{description:"Auth context for every op. `null` for unauthenticated."}},required:["operations","auth"]},async execute(r){const{operations:s,auth:o}=r,d=(await e()).batch(s,o);return{ok:d.allowed,summary:d.allowed?`Batch of ${s.length} op(s) committed`:`Batch of ${s.length} op(s) rejected by rules. To SEED data, use the admin data tool firestore_batch_write; to test rules, pass an auth the rules permit.`,data:{allowed:d.allowed,results:d.results}}}},{name:"firestore_create_with_auto_id",description:"Create a document at `<collection>/<auto-id>` with a Firestore-compatible 20-char alphanumeric id (mirrors the live SDK `addDoc()` flow). Rules evaluate as for an explicit-id `create`. Returns the minted path so the caller can re-read the doc without a side channel.",parameters:{type:"object",properties:{collection:{type:"string",description:"Collection path under which to mint the new document, e.g. `users` or `users/u1/posts`."},auth:{description:"Auth context. `null` for unauthenticated. Otherwise `{ uid, token? }`."},data:{type:"object",description:"Document data.",additionalProperties:!0}},required:["collection","auth","data"]},async execute(r){const{collection:s,auth:o,data:c}=r,d=await e(),{path:f,result:p}=d.createWithAutoId(s,c,o);return{ok:p.allowed,summary:p.allowed?`Created ${f}`:`Create at ${f} denied by rules (as ${o?o.uid:"unauthenticated"}). To SEED data, use the admin data tool firestore_add_document; to test rules, pass an auth the rules permit.`,data:{path:f,allowed:p.allowed,debugMessages:p.debugMessages}}}},{name:"firestore_simulator_undo",description:"Undo the last allowed write. Restores state to immediately before that op. Returns the undone event, or a `{ undone: false }` outcome when the log is empty.",parameters:{type:"object",properties:{}},async execute(){const s=(await e()).undo();return s?{ok:!0,summary:`Undid ${s.method} on ${s.path}`,data:{undone:!0,event:{method:s.method,path:s.path}}}:{ok:!0,summary:"Nothing to undo",data:{undone:!1}}}},{name:"firestore_simulator_redo",description:"Re-apply the most recently undone write. Pairs with `firestore_simulator_undo`. Returns the re-applied event, or `{ redone: false }` when the undo stack is empty (no recent undo to redo).",parameters:{type:"object",properties:{}},async execute(){var o,c;const s=(await e()).redo();return s?{ok:s.allowed,summary:s.allowed?`Redid ${((o=s.event)==null?void 0:o.method)??"op"} on ${((c=s.event)==null?void 0:c.path)??"?"}`:"Redo restored a denied event (no state change)",data:{redone:!0,allowed:s.allowed,event:s.event?{method:s.event.method,path:s.event.path}:null,debugMessages:s.debugMessages}}:{ok:!0,summary:"Nothing to redo",data:{redone:!1}}}},{name:"firestore_simulator_events",description:'Return every event the sandbox has seen — allowed and denied — with timestamps, auth, and debug messages. Useful for audit / replay / "why did this rule deny?" investigations.',parameters:{type:"object",properties:{}},async execute(){return{ok:!0,summary:"Event log",data:{events:(await e()).getEvents().map(s=>({id:s.id,method:s.method,path:s.path,allowed:s.allowed,auth:s.auth,debugMessages:s.debugMessages}))}}}},{name:"firestore_simulator_transaction",description:'Run a declarative transaction. Reads are captured server-side and referenced from write data via `{ "$expr": "..." }` wrappers — agents never see the read values, eliminating the "round-trip the doc through context" cost. Expression DSL: arithmetic (+ - * / %), comparison, &&/||/?:, $alias.field references, string literals in either "double" or \'single\' quotes, and @sentinel(...) calls (@increment, @serverTimestamp, @arrayUnion, @arrayRemove, @deleteField). Reads are omitted from the response by default; set `includeReads: true` when debugging a denial.',parameters:{type:"object",properties:{auth:{description:"Auth context for rule eval. `null` for unauthenticated."},readOnly:{type:"boolean",description:"Hint that the transaction is read-only. v1: writes are still committed; `readOnlyViolation: true` surfaces on the response if any was queued."},includeReads:{type:"boolean",description:"Default false. When true, the response includes the captured read data + per-write debugMessages."},reads:{type:"object",description:"Reads keyed by alias. Aliases referenced from write expressions as `$alias` (e.g. `$src.balance`).",additionalProperties:{type:"string"}},writes:{type:"array",minItems:1,items:{type:"object",properties:{method:{type:"string",enum:["create","update","set","delete"]},path:{type:"string"},data:{type:"object",additionalProperties:!0}},required:["method","path"]},description:"Write operations to apply atomically."}},required:["reads","writes","auth"]},async execute(r){const{auth:s,readOnly:o,includeReads:c,reads:d,writes:f}=r;for(let b=0;b<f.length;b+=1){const v=f[b];if(v.method==="delete"&&v.data!==void 0)return{ok:!1,summary:`writes[${b}]: 'delete' must not include 'data'`,data:{code:"INVALID_INPUT"}};if(v.method!=="delete"&&v.data===void 0)return{ok:!1,summary:`writes[${b}]: '${v.method}' requires 'data'`,data:{code:"INVALID_INPUT"}}}const p=await e(),g=c===!0;try{const b=p.transaction(w=>{const _={};for(const[k,I]of Object.entries(d)){const R=w.get(I).data();_[k]=R===void 0?null:R}for(let k=0;k<f.length;k+=1){const I=f[k];if(I.method==="delete"){w.delete(I.path);continue}const N=I2(I.data,{reads:_});if(N===null||typeof N!="object"||Array.isArray(N))throw new ld(`writes[${k}].data resolved to a non-object`,`writes.${k}.data`);const R=N;switch(I.method){case"create":w.create(I.path,R);break;case"update":w.update(I.path,R);break;case"set":w.set(I.path,R);break}}},{auth:s,readOnly:o}),v={allowed:b.allowed,writes:b.writes.map(w=>{const _={path:w.path,method:w.method,allowed:w.allowed};return w.error&&(_.error={code:w.error.code,message:w.error.message}),g&&(_.debugMessages=w.debugMessages),_})};return b.error&&(v.error={code:b.error.code,message:b.error.message}),b.readOnlyViolation&&(v.readOnlyViolation=!0),g&&(v.reads=b.reads.map(w=>({path:w.path,data:w.data}))),{ok:b.allowed,summary:b.allowed?`Transaction committed (${f.length} write(s))`:"Transaction rolled back",data:v}}catch(b){if(b instanceof ld||b instanceof Ct||b instanceof xr||b instanceof Ln)return{ok:!1,summary:`Transaction failed: ${b.message}`,data:{allowed:!1,writes:[],error:{code:"invalid-argument",message:b.message}}};throw b}}}]}function WE(t){return jL({resolveSandbox:t.resolveSandbox,resolveModulesFn:AL})}function Fl(t){return t.replace(/^\/+|\/+$/g,"").split("/")}function QE(t){return Fl(t).length%2===0&&Fl(t).length>0}function dg(t){return Fl(t).length%2===1}function Bd(t){const e=Fl(t);return e[e.length-1]??""}function JE(t){return Fl(t).slice(0,-1).join("/")}function kL(t,e){const n=e!==void 0,r=n?fo(e):void 0;return{id:t.id,ref:t,exists:n,data:()=>n?r:void 0}}function $a(t,e){if(t.error)throw new sn(t.error);const n=t.debugMessages.length>0?t.debugMessages.join("; "):"(no debug message)";throw new sn(Pe("permission-denied",`${e}: ${n}`))}class fg{constructor(e,n,r,s=!1){G(this,"env");G(this,"auth");G(this,"bypassRules");G(this,"id");G(this,"path");this.env=e,this.auth=n,this.bypassRules=s,this.path=r,this.id=Bd(r),no(this,Bl("reference",r))}get parent(){return new Jm(this.env,this.auth,JE(this.path),this.bypassRules)}collection(e){return new Jm(this.env,this.auth,`${this.path}/${e}`,this.bypassRules)}async get(e){const n=this.env.execute({method:"get",path:this.path,auth:(e==null?void 0:e.auth)!==void 0?e.auth:this.auth,bypassRules:this.bypassRules});n.allowed||$a(n,"get denied");const r=n.data===void 0||n.data===null?void 0:n.data;return kL(this,r)}async set(e,n){const r=(n==null?void 0:n.auth)!==void 0?n.auth:this.auth;if((n==null?void 0:n.mergeFields)!==void 0){const o=n.mergeFields.map(p=>String(p)),d=this.env.getDocument(this.path)===null?"create":"update",f=this.env.execute({method:d,path:this.path,data:e,auth:r,merge:{mergeFields:o},bypassRules:this.bypassRules});f.allowed||$a(f,`set denied (as ${d})`);return}if((n==null?void 0:n.merge)===!0){const c=this.env.getDocument(this.path)===null?"create":"update",d=this.env.execute({method:c,path:this.path,data:e,auth:r,merge:!0,bypassRules:this.bypassRules});d.allowed||$a(d,`set denied (as ${c})`);return}const s=this.env.execute({method:"set",path:this.path,data:e,auth:r,bypassRules:this.bypassRules});s.allowed||$a(s,"set denied")}async update(e,n){const r=this.env.execute({method:"update",path:this.path,data:e,auth:(n==null?void 0:n.auth)!==void 0?n.auth:this.auth,bypassRules:this.bypassRules});r.allowed||$a(r,"update denied")}async delete(e){const n=this.env.execute({method:"delete",path:this.path,auth:(e==null?void 0:e.auth)!==void 0?e.auth:this.auth,bypassRules:this.bypassRules});n.allowed||$a(n,"delete denied")}}const yS=new WeakMap;let CL=1;function gS(t){let e=yS.get(t);return e===void 0&&(e=CL++,yS.set(t,e)),e}function bS(t){if(t===null||typeof t=="boolean")return t;if(typeof t=="string")return LD(t);if(typeof t>"u")return{type:"undefined"};if(typeof t=="bigint")return Bl("bigint",t.toString());if(typeof t=="number"){const n=Number.isNaN(t)?"NaN":t===1/0?"Infinity":t===-1/0?"-Infinity":Object.is(t,-0)?"-0":String(t);return Bl("number",n)}if(typeof t!="object"&&typeof t!="function")return{type:typeof t,value:String(t)};const e=$D(t);if(e!==void 0)return e;try{if(Array.isArray(t))return{type:"array",id:gS(t)}}catch{}return{type:"opaque-object",id:gS(t)}}function NL(t){return typeof t.seconds=="number"&&(typeof t.nanos=="number"||typeof t.nanoseconds=="number")}function OL(t){return typeof t.latitude=="number"&&typeof t.longitude=="number"}function RL(t){return t.data instanceof Uint8Array}function TL(t){return typeof t.path=="string"}function hd(t){if(t==null)return 0;const e=typeof t;if(e==="boolean")return 1;if(e==="number"||e==="bigint")return 2;if(e==="string")return 4;if(Array.isArray(t))return 8;if(e==="object"){const n=t;return NL(n)?3:RL(n)?5:OL(n)?7:TL(n)?6:9}return 9}function vS(t){const e=typeof t.nanos=="number"?t.nanos:t.nanoseconds??0;return[t.seconds,e]}function DL(t,e){const n=Number.isNaN(t),r=Number.isNaN(e);return n&&r?0:n?-1:r?1:t<e?-1:t>e?1:0}function wS(t,e){return t<e?-1:t>e?1:0}function Xs(t,e){const n=hd(t),r=hd(e);if(n!==r)return n<r?-1:1;switch(n){case 0:return 0;case 1:return t===e?0:t?1:-1;case 2:return DL(Number(t),Number(e));case 3:{const[s,o]=vS(t),[c,d]=vS(e);return s!==c?s<c?-1:1:o<d?-1:o>d?1:0}case 4:return wS(t,e);case 5:{const s=t.data,o=e.data,c=Math.min(s.length,o.length);for(let d=0;d<c;d++)if(s[d]!==o[d])return s[d]<o[d]?-1:1;return s.length<o.length?-1:s.length>o.length?1:0}case 6:return wS(t.path,e.path);case 7:{const s=t,o=e;return s.latitude!==o.latitude?s.latitude<o.latitude?-1:1:s.longitude<o.longitude?-1:s.longitude>o.longitude?1:0}case 8:{const s=t,o=e,c=Math.min(s.length,o.length);for(let d=0;d<c;d++){const f=Xs(s[d],o[d]);if(f!==0)return f}return s.length<o.length?-1:s.length>o.length?1:0}case 9:{const s=t,o=e,c=Object.keys(s).sort(),d=Object.keys(o).sort(),f=Math.min(c.length,d.length);for(let p=0;p<f;p++){if(c[p]!==d[p])return c[p]<d[p]?-1:1;const g=Xs(s[c[p]],o[d[p]]);if(g!==0)return g}return c.length<d.length?-1:c.length>d.length?1:0}default:return 0}}function IL(t,e,n){if(e<=0)return[];const r=[];for(const s of t)r.length<e?xS(r,s,n):n(s,r[r.length-1])<0&&(r.pop(),xS(r,s,n));return r}function xS(t,e,n){let r=0,s=t.length;for(;r<s;){const o=r+s>>1;n(e,t[o])<0?s=o:r=o+1}t.splice(r,0,e)}const Ks="__name__",ML=new Set(["<","<=",">",">=","!=","not-in"]);function Wm(t,e){return e===Ks?{path:t.path}:t.data[e]}function hg(t){return t.kind==="where"?ML.has(t.op)?[t.field]:[]:t.filters.flatMap(hg)}function LL(t){return hg(t).length>0}function qd(t,e){return hd(t)===hd(e)}function UL(t,e){return qd(t,e)&&Xs(t,e)<0}function $L(t,e){return qd(t,e)&&Xs(t,e)<=0}function BL(t,e){return qd(t,e)&&Xs(t,e)>0}function qL(t,e){return qd(t,e)&&Xs(t,e)>=0}function FL(t,e,n){const r=t!==void 0;switch(e){case"==":return r&&Sr(t,n);case"!=":return r&&t!==null&&!Sr(t,n);case"<":return r&&UL(t,n);case"<=":return r&&$L(t,n);case">":return r&&BL(t,n);case">=":return r&&qL(t,n);case"in":return r&&Array.isArray(n)&&n.some(s=>Sr(t,s));case"not-in":return!Array.isArray(n)||n.some(s=>s===null)?!1:r&&t!==null&&!n.some(s=>Sr(t,s));case"array-contains":return Array.isArray(t)&&t.some(s=>Sr(s,n));case"array-contains-any":return Array.isArray(t)&&Array.isArray(n)&&n.some(s=>t.some(o=>Sr(o,s)))}}function zL(t,e){if(e===Ks){const n=t.path.split("/");return n[n.length-1]??t.path}return t.data[e]}function XE(t){if(Array.isArray(t))return t.map(XE);if(t&&typeof t=="object"){const e=t;if(typeof e.id=="string")return e.id;if(typeof e.path=="string"){const n=e.path.split("/");return n[n.length-1]??e.path}}return t}function Qm(t,e){if(e.kind==="where"){const n=zL(t,e.field),r=e.field===Ks?XE(e.value):e.value;return FL(n,e.op,r)}return e.kind==="and"?e.filters.every(n=>Qm(t,n)):e.filters.some(n=>Qm(t,n))}function PL(t,e){return t.filter(n=>e.every(r=>Qm(n,r)))}function SS(t,e){const n=t.data();if(n===void 0)throw new sn({code:"not-found",message:`Snapshot-based cursors require an existing document — got an empty snapshot for ${t.id??"<unknown>"}.`});return e.map(r=>r.field===Ks?{path:t.ref.path}:n[r.field])}function _S(t,e,n){for(let r=0;r<e.length;r++){const s=Xs(Wm(t,n[r].field),e[r]);if(s!==0)return n[r].direction==="desc"?-s:s}return 0}function VL(t,e,n,r){return t.filter(s=>{if(n){const o=_S(s,n.values,e);if(n.inclusive?o<0:o<=0)return!1}if(r){const o=_S(s,r.values,e);if(r.inclusive?o>0:o>=0)return!1}return!0})}function eA(t,e){return t.filter(n=>e.every(r=>r.field===Ks||n.data[r.field]!==void 0))}function tA(t){return(e,n)=>{for(const r of t){const s=Xs(Wm(e,r.field),Wm(n,r.field));if(s!==0)return r.direction==="desc"?-s:s}return 0}}function HL(t,e){return e.length===0?t:eA(t,e).sort(tA(e))}class Fd{constructor(e,n,r,s=[],o=[],c,d=!1,f,p,g=!1){G(this,"env");G(this,"auth");G(this,"collectionPath");G(this,"clauses");G(this,"orders");G(this,"limitCount");G(this,"limitFromEnd");G(this,"start");G(this,"end");G(this,"bypassRules");this.env=e,this.auth=n,this.collectionPath=r,this.clauses=s,this.orders=o,this.limitCount=c,this.limitFromEnd=d,this.start=f,this.end=p,this.bypassRules=g}where(e,n,r){return this.clone({clauses:[...this.clauses,{kind:"where",field:e,op:n,value:r}]})}applyFilter(e){return this.clone({clauses:[...this.clauses,e]})}orderBy(e,n="asc"){return this.clone({orders:[...this.orders,{field:e,direction:n}]})}limit(e){return this.clone({limitCount:e,limitFromEnd:!1})}limitToLast(e){return this.clone({limitCount:e,limitFromEnd:!0})}startCursor(e,n){return this.clone({start:{values:[...e],inclusive:n,fromSnapshot:!1}})}endCursor(e,n){return this.clone({end:{values:[...e],inclusive:n,fromSnapshot:!1}})}startCursorFromSnapshot(e,n){return this.clone({start:{values:SS(e,this.normalizedOrders()),inclusive:n,fromSnapshot:!0}})}endCursorFromSnapshot(e,n){return this.clone({end:{values:SS(e,this.normalizedOrders()),inclusive:n,fromSnapshot:!0}})}clone(e){return new Fd(this.env,this.auth,this.collectionPath,e.clauses??this.clauses,e.orders??this.orders,e.limitCount!==void 0||"limitCount"in e?e.limitCount:this.limitCount,e.limitFromEnd??this.limitFromEnd,"start"in e?e.start:this.start,"end"in e?e.end:this.end,this.bypassRules)}gatherCandidates(){return this.env.scanDocuments(this.collectionPath,{directOnly:!0})}listRulePath(){return this.collectionPath}readCandidates(e){const n=(e==null?void 0:e.auth)!==void 0?e.auth:this.auth,r=this.env.readQueryCandidates(this.gatherCandidates(),this.listRulePath(),n,this.structuredConstraints(),this.bypassRules,this.activityQuery());if(!r.allowed)throw new sn(r.error);return r.docs}structuredConstraints(){const e=[],n=r=>{if(r.kind==="where"){const s=r.value;(s===null||typeof s=="string"||typeof s=="number"||typeof s=="boolean")&&e.push({field:r.field,op:r.op,value:s});return}r.kind==="and"&&r.filters.forEach(n)};for(const r of this.clauses)n(r);return{where:e,limit:this.limitCount??null,offset:null,orderBy:this.orders.length>0?this.orders[0].field:null}}activityQuery(){const e=r=>r.kind==="where"?{kind:"where",field:r.field,op:r.op,value:bS(r.value)}:{kind:r.kind,filters:r.filters.map(e)},n=r=>r===void 0?null:{values:r.values.map(s=>bS(s)),inclusive:r.inclusive,fromSnapshot:r.fromSnapshot};return{scope:this.activityScope(),filters:this.clauses.map(e),orderBy:this.orders.map(r=>({...r})),limit:this.limitCount??null,limitFromEnd:this.limitFromEnd,start:n(this.start),end:n(this.end)}}activityScope(){return{kind:"collection"}}applyConstraints(e){let n=PL(e,[...this.clauses]);const r=this.normalizedOrders(),s=this.orders.length>0||this.start!==void 0||this.end!==void 0||this.clauses.some(LL);if(s&&this.limitCount!==void 0&&!this.limitFromEnd&&this.start===void 0&&this.end===void 0)return IL(eA(n,r),this.limitCount,tA(r));if(s&&(n=HL(n,r)),this.start||this.end){for(const o of[this.start,this.end])if(o&&!o.fromSnapshot&&o.values.length>this.orders.length)throw new sn({code:"invalid-argument",message:"Too many arguments provided to a cursor (startAt / startAfter / endAt / endBefore). The number of cursor values must be less than or equal to the number of orderBy() clauses."});n=VL(n,r,this.start,this.end)}if(this.limitCount!==void 0)if(this.limitFromEnd){if(this.orders.length===0)throw new sn({code:"invalid-argument",message:"limitToLast() queries require at least one orderBy clause."});n=n.slice(-this.limitCount)}else n=n.slice(0,this.limitCount);return n}normalizedOrders(){const e=[...this.orders],n=new Set(e.map(s=>s.field)),r=this.orders.length>0?this.orders[this.orders.length-1].direction:"asc";for(const s of this.clauses)for(const o of hg(s))o!==Ks&&!n.has(o)&&(n.add(o),e.push({field:o,direction:r}));return n.has(Ks)||e.push({field:Ks,direction:r}),e}snapshotConstraints(){const e=n=>this.applyConstraints(n);return e.structured=this.structuredConstraints(),e.activityQuery=this.activityQuery(),e}async get(e){const r=this.applyConstraints(this.readCandidates(e)).map(s=>{const o=new fg(this.env,this.auth,s.path,this.bypassRules),c=fo(s.data);return{id:o.id,ref:o,exists:!0,data:()=>c}});return{size:r.length,empty:r.length===0,docs:r,forEach(s){r.forEach(s)}}}async aggregate(e,n){const r=this.applyConstraints(this.readCandidates(n)),s={};for(const o of Object.keys(e))s[o]=KL(e[o],r);return{data:()=>s}}}function GL(t,e){if(!e.includes("."))return t[e];let n=t;for(const r of e.split(".")){if(typeof n!="object"||n===null||Array.isArray(n))return;n=n[r]}return n}function KL(t,e){if(t.kind==="count")return e.length;let n=0,r=0;for(const s of e){const o=GL(s.data,t.field);typeof o=="number"&&Number.isFinite(o)&&(n+=o,r++)}return t.kind==="sum"?n:r===0?null:n/r}class pg extends Fd{constructor(n,r,s,o=[],c=[],d,f=!1,p,g,b=!1){super(n,r,"",o,c,d,f,p,g,b);G(this,"collectionId");this.collectionId=s}clone(n){return new pg(this.env,this.auth,this.collectionId,n.clauses??this.clauses,n.orders??this.orders,"limitCount"in n?n.limitCount:this.limitCount,n.limitFromEnd??this.limitFromEnd,"start"in n?n.start:this.start,"end"in n?n.end:this.end,this.bypassRules)}gatherCandidates(){const n=[],r=this.env.snapshot();for(const s of Object.keys(r))YL(s)===this.collectionId&&n.push({path:s,data:r[s]});return n}listRulePath(){return this.collectionId}activityScope(){return{kind:"collection-group"}}}function YL(t){const e=t.split("/").filter(n=>n.length>0);return e.length===0||e.length%2!==0?null:e[e.length-2]}class Jm extends Fd{constructor(n,r,s,o=!1){super(n,r,s,[],[],void 0,!1,void 0,void 0,o);G(this,"id");G(this,"path");this.path=s,this.id=Bd(s)}doc(n){const r=n??tg();return new fg(this.env,this.auth,`${this.path}/${r}`,this.bypassRules)}async add(n,r){const s=this.doc();return await s.set(n,r),s}}class ZL{constructor(e,n,r=!1){G(this,"env");G(this,"auth");G(this,"bypassRules");G(this,"ops",[]);this.env=e,this.auth=n,this.bypassRules=r}set(e,n){const s=this.env.getDocument(e.path)===null?"create":"update";return this.ops.push({method:s,path:e.path,data:n}),this}update(e,n){return this.ops.push({method:"update",path:e.path,data:n}),this}delete(e){return this.ops.push({method:"delete",path:e.path}),this}async commit(e){if(this.ops.length===0)return;const n=this.env.batch(this.ops,(e==null?void 0:e.auth)!==void 0?e.auth:this.auth,this.bypassRules);if(n.allowed)return;if(n.error)throw new sn(n.error);const r=n.results.find(o=>!o.allowed),s=(r==null?void 0:r.debugMessages.join("; "))??"batch denied";throw new sn(Pe("permission-denied",`batch failed: ${s}`))}}function WL(t){return typeof t.where=="function"}class QL{constructor(e){G(this,"simTx");this.simTx=e}async get(e){if(WL(e)){const o=await e.get();return o.size>0&&this.simTx.getAll(...o.docs.map(c=>c.ref.path)),o}const r=this.simTx.get(e.path).data();if(r===void 0)return{id:e.id,ref:e,exists:!1,data:()=>{}};const s=fo(r);return{id:e.id,ref:e,exists:!0,data:()=>s}}set(e,n){return this.simTx.set(e.path,n),this}update(e,n){return this.simTx.update(e.path,n),this}delete(e){return this.simTx.delete(e.path),this}}class JL{constructor(e,n,r=!1,s){G(this,"env");G(this,"auth");G(this,"bypassRules");G(this,"provenance");this.env=e,this.auth=n,this.bypassRules=r,this.provenance=s}collection(e){if(!dg(e))throw new sn(Pe("invalid-argument",`collection path must have an odd number of segments: ${e}`));return new Jm(this.env,this.auth,e,this.bypassRules)}doc(e){if(!QE(e))throw new sn(Pe("invalid-argument",`document path must have an even number of segments: ${e}`));return new fg(this.env,this.auth,e,this.bypassRules)}collectionGroup(e){if(e.length===0||e.includes("/"))throw new sn(Pe("invalid-argument",`collection group id must be a single non-empty segment with no '/': ${e}`));return new pg(this.env,this.auth,e,[],[],void 0,!1,void 0,void 0,this.bypassRules)}batch(){return new ZL(this.env,this.auth,this.bypassRules)}async runTransaction(e,n){let r;try{r=await this.env.transaction(s=>{const o=new QL(s);return e(o)},{auth:(n==null?void 0:n.auth)!==void 0?n.auth:this.auth,bypassRules:this.bypassRules,provenance:this.provenance})}catch(s){throw s instanceof SE?new sn(s.simError):s}if(!r.allowed){if(r.error)throw new sn(r.error);const s=r.writes.find(c=>!c.allowed),o=(s==null?void 0:s.debugMessages.join("; "))??"transaction denied at commit";throw new sn(Pe("permission-denied",`transaction failed: ${o}`))}return r.returnValue}}function XL(t,e){return new JL(t,(e==null?void 0:e.auth)??null,(e==null?void 0:e.bypassRules)??!1,e==null?void 0:e.provenance)}const nA=Symbol("pyric/sandbox/context"),rA=Symbol("pyric/sandbox/bypassRules");let Xm=null;function eU(t){Xm=t}function tU(t){const e=t;return typeof e.path=="string"&&e.path.length>0||typeof e.collectionPath=="string"&&e.collectionPath.length>0}function nU(t){const e=t.trim();if(!e)return[];const n=e.indexOf(": ");if(n!==-1){const s=e.slice(n+2).trim().split("; ").map(o=>o.trim()).filter(o=>o.length>0);if(s.length>0)return s}return[e]}function ES(t,e){if(!(t instanceof sn))return t;const n=t.code;if(n!=="permission-denied")return new nt(n,t.message);const r={auth:e.auth,reasons:nU(t.message)},s=t.simError;if(s!=null&&s.request){const o=s.request;r.request={method:o.method,path:o.path,...o.resourceData?{resourceData:o.resourceData}:{}}}return s!=null&&s.resource&&(r.resource={data:s.resource.data,exists:s.resource.exists}),s!=null&&s.query&&(r.query=s.query),(s==null?void 0:s.remediation)!==void 0?new nt({code:n,message:t.message,denialContext:r,remediation:s.remediation}):new nt(n,t.message,r)}function pd(t,e,n=!1){return new Proxy(t,{get(r,s,o){if(s===nA)return e;if(s===rA)return n;if(s==="onSnapshot"&&Xm!==null&&!(s in r)&&tU(r))return(...d)=>Xm(o,...d);const c=Reflect.get(r,s,o);return typeof c!="function"?c:function(...d){var p,g;let f;try{const b=()=>c.apply(r,d);f=((g=(p=e.sandbox).runWithProvenance)==null?void 0:g.call(p,ql(e.operationContext),b))??b()}catch(b){throw ES(b,e)}return f instanceof Promise?f.then(b=>b&&typeof b=="object"?pd(b,e,n):b).catch(b=>{throw ES(b,e)}):f&&typeof f=="object"?pd(f,e,n):f}}})}function sA(t,e=!1){if(rg(t.sandbox))throw new Error("pyric/sandbox/admin-firestore: internal — a remote sandbox context reached the local engine builder; remote dispatch should have handled it. Please report this.");const n=()=>XL(Wt(t.sandbox),{auth:t.auth,bypassRules:e,provenance:ql(t.operationContext)});return{collection(r){return n().collection(r)},doc(r){return n().doc(r)},collectionGroup(r){return n().collectionGroup(r)},batch(){return n().batch()},runTransaction(r,s){return n().runTransaction(r)},setRules(r){return Wt(t.sandbox).deployRules(r)},seed(r){const s=Wt(t.sandbox);return s.seed({rules:s.getRules(),documents:(r==null?void 0:r.documents)??{}})},snapshot(){return Wt(t.sandbox).snapshot()}}}function ey(t){if(t instanceof nt)return t;if(t!==null&&typeof t=="object"){const e=t;if(typeof e.code=="string"&&typeof e.message=="string"){const n=e.denialContext!==null&&typeof e.denialContext=="object"?e.denialContext:void 0;return new nt(e.code,e.message,n)}}return t}function ss(t){return new nt("invalid-argument",t)}async function fr(t,e){try{return await t.sandbox.channel.op({...e,actAs:t.lens})}catch(n){throw ey(n)}}const rU=new Set(["serverTimestamp","increment","arrayUnion","arrayRemove","deleteField"]);function sU(t){return t!==null&&typeof t=="object"&&typeof t.__type=="string"&&rU.has(t.__type)}function iU(t){switch(t.__type){case"serverTimestamp":return{__sentinel:"serverTimestamp"};case"increment":return{__sentinel:"increment",n:t.value};case"arrayUnion":return{__sentinel:"arrayUnion",values:t.values.map(os)};case"arrayRemove":return{__sentinel:"arrayRemove",values:t.values.map(os)};case"deleteField":return{__sentinel:"deleteField"}}}function os(t){var r;if(t===null||typeof t!="object")return t;if(sU(t))return iU(t);if(t instanceof $n)return t.toJSON();if(t instanceof Date)return $n.fromDate(t).toJSON();if(Array.isArray(t))return t.map(os);const e=Object.getPrototypeOf(t);if(e!==Object.prototype&&e!==null){const s=t.toJSON;if(typeof s=="function")return s.call(t);throw ss(`remote Firestore: cannot serialize a ${((r=e.constructor)==null?void 0:r.name)??"class"} instance for the wire — use plain data, Timestamp, Date, or FieldValue sentinels.`)}const n={};for(const[s,o]of Object.entries(t))n[s]=os(o);return n}function zi(t){return os(t)}function ty(t){return Ud(JSON.parse(t.json))}function iA(t){return fo(ty(t))}function aA(t,e){const n=e.exists&&e.data?iA(e.data):void 0;return{id:t.id,ref:t,exists:e.exists,data:()=>n}}function oA(t,e){const n=e.docs.map(r=>{const s=r.path??r.id,o=md(t,s),c=r.data?iA(r.data):{};return{id:o.id,ref:o,exists:!0,data:()=>c}});return{size:n.length,empty:n.length===0,docs:n,forEach(r){n.forEach(s=>r(s))}}}const mg=Symbol("pyric/sandbox/admin-firestore/remoteSnapshotRegistrar");function aU(t){if(t===null||typeof t!="object")return;const e=t[mg];return typeof e=="function"?e:void 0}let ny=null;function oU(t){ny=t}function lA(...t){if(ny===null)throw new nt("failed-precondition","remote Firestore: onSnapshot is not wired yet — import pyric-admin/firestore (or pyric/sandbox/admin-firestore) before subscribing.");return ny(this,...t)}function cA(t,e,n,r,s){const o=n.includeMetadataChanges!==!0;let c,d;try{d=t.sandbox.channel.subscribe({target:e,actAs:t.lens},f=>{if(!r)return;const p=f;if(Array.isArray(p.docs)){const g=p.docs.map(w=>({path:w.path??w.id,data:w.data?ty(w.data):{}})),b=e.__ref==="query"?e.source.__ref==="group"?e.source.collectionId:e.source.path:e.__ref==="group"?e.collectionId:e.path,v=Ha({path:b},g,{excludesMetadataChanges:o},c);c=g,r(v)}else if(typeof p.id=="string"){const g=p.path??p.id,b=p.exists&&p.data?ty(p.data):null;r(Va(g,b))}},f=>{const p=ey(f);s?s(p):console.error("pyric remote Firestore: uncaught onSnapshot error:",p)})}catch(f){throw ey(f)}return d}const uA=Symbol("pyric/sandbox/admin-firestore/remoteQueryState");function lU(t){if(!(t===null||typeof t!="object"))return t[uA]}function dA(t){return t.kind==="where"?(fA(t.op),{kind:"where",field:t.field,op:t.op,value:os(t.value)}):{kind:t.kind,filters:t.filters.map(dA)}}const cU=new Set(["<","<=","==","!=",">=",">","in","not-in","array-contains","array-contains-any"]);function fA(t){if(!cU.has(t))throw ss(`invalid where operator: ${String(t)}`)}function Bu(t){const e=[...t.filters];for(const n of t.orders)e.push({kind:"orderBy",field:n.field,direction:n.direction});return t.start&&e.push({kind:t.start.inclusive?"startAt":"startAfter",values:t.start.values.map(os)}),t.end&&e.push({kind:t.end.inclusive?"endAt":"endBefore",values:t.end.values.map(os)}),t.limitCount!==void 0&&e.push(t.limitFromEnd?{kind:"limitToLast",n:t.limitCount}:{kind:"limit",n:t.limitCount}),e.length===0?t.source:{__ref:"query",source:t.source,constraints:e}}function AS(t,e,n){if(e.length===0)throw ss(`${n}(snapshot) on a remote sandbox requires at least one explicit orderBy() clause — the relay protocol has no document-key cursor.`);if(e.some(s=>s.field==="__name__"))throw ss(`${n}(snapshot) on a remote sandbox does not support orderBy('__name__') — the relay protocol has no document-key cursor, and __name__ is not a data field a value cursor can carry. Order by a real document field instead.`);const r=t.data();if(r===void 0)throw new nt("not-found",`Snapshot-based cursors require an existing document — got an empty snapshot for ${t.id??"<unknown>"}.`);return e.map(s=>r[s.field])}function yg(t,e){const n=s=>yg(t,{...e,...s});return{[uA]:e,where(s,o,c){return fA(o),n({filters:[...e.filters,{kind:"where",field:s,op:o,value:os(c)}]})},applyFilter(s){return n({filters:[...e.filters,dA(s)]})},orderBy(s,o="asc"){return n({orders:[...e.orders,{field:s,direction:o}]})},limit(s){return n({limitCount:s,limitFromEnd:!1})},limitToLast(s){return n({limitCount:s,limitFromEnd:!0})},startCursor(s,o){return n({start:{values:[...s],inclusive:o}})},endCursor(s,o){return n({end:{values:[...s],inclusive:o}})},startCursorFromSnapshot(s,o){return n({start:{values:AS(s,e.orders,o?"startAt":"startAfter"),inclusive:o}})},endCursorFromSnapshot(s,o){return n({end:{values:AS(s,e.orders,o?"endAt":"endBefore"),inclusive:o}})},async get(s){qu(e);const o=await fr(t,{method:"getDocs",source:Bu(e)});return oA(t,o)},async aggregate(s){qu(e);const o=await fr(t,{method:"aggregate",source:Bu(e),spec:s});return{data:()=>o.data}},[mg]:(s,o,c)=>(qu(e),cA(t,Bu(e),s,o,c)),onSnapshot:lA}}function qu(t){if(t.limitFromEnd&&t.orders.length===0)throw ss("limitToLast() queries require at least one orderBy clause.")}function ry(t,e){const n=yg(t,{source:{__ref:"collection",path:e},filters:[],orders:[],limitFromEnd:!1});return Object.assign(Object.create(Object.getPrototypeOf(n)),n,{id:Bd(e),path:e,doc(s){const o=s??tg();return md(t,`${e}/${o}`)},async add(s,o){const c=await fr(t,{method:"addDoc",collectionPath:e,data:zi(s)});return md(t,c.path)}})}function md(t,e){const n={id:Bd(e),path:e,get parent(){return ry(t,JE(e))},collection(r){const s=`${e}/${r}`;if(!dg(s))throw ss(`collection path must have an odd number of segments: ${s}`);return ry(t,s)},async get(r){const s=await fr(t,{method:"getDoc",path:e});return aA(n,s)},async set(r,s){await fr(t,{method:"setDoc",path:e,data:zi(r),...jS(s)?{options:jS(s)}:{}})},async update(r,s){await fr(t,{method:"updateDoc",path:e,data:zi(r)})},async delete(r){await fr(t,{method:"deleteDoc",path:e})},[mg]:(r,s,o)=>cA(t,{__ref:"doc",path:e},r,s,o),onSnapshot:lA};return n}function jS(t){if(!t)return;const e={};return t.merge!==void 0&&(e.merge=t.merge),t.mergeFields!==void 0&&(e.mergeFields=[...t.mergeFields]),e.merge!==void 0||e.mergeFields!==void 0?e:void 0}function uU(t){const e=[];let n=!1;const r={set(o,c){return s(),e.push({method:"set",path:o.path,data:zi(c)}),r},update(o,c){return s(),e.push({method:"update",path:o.path,data:zi(c)}),r},delete(o){return s(),e.push({method:"delete",path:o.path}),r},async commit(o){s(),n=!0,await fr(t,{method:"batchCommit",writes:e})}};function s(){if(n)throw new nt("failed-precondition","WriteBatch has already been committed.")}return r}const kS=5;async function dU(t,e){for(let n=0;n<kS;n++){const r=[],s=[],o=()=>{if(s.length>0)throw new nt("failed-precondition",Lm)},c={get(g){o();const b=lU(g);return b!==void 0?f(b):d(g)},set(g,b){return s.push({method:"set",path:g.path,data:zi(b)}),c},update(g,b){return s.push({method:"update",path:g.path,data:zi(b)}),c},delete(g){return s.push({method:"delete",path:g.path}),c}};async function d(g){const b=await fr(t,{method:"getDoc",path:g.path});return r.push({path:b.path??g.path,data:b.exists&&b.data?b.data:null}),aA(g,b)}async function f(g){qu(g);const b=await fr(t,{method:"getDocs",source:Bu(g)});for(const v of b.docs)r.push({path:v.path??v.id,data:v.data??null});return oA(t,b)}const p=await e(c);try{return await fr(t,{method:"txnCommit",reads:r,writes:s}),p}catch(g){if(g instanceof nt&&g.code==="aborted")continue;throw g}}throw new nt("aborted",`Transaction failed after ${kS} attempts due to repeated conflicts. Another writer is concurrently updating the same documents.`)}function Yp(t,e){return new nt("unimplemented",`SandboxFirestore.${t} is not available on a remote sandbox — its return value is synchronous and the data lives in the browser worker. ${e}`)}function hA(t,e){const n={sandbox:t,lens:e};return{collection(r){if(!dg(r))throw ss(`collection path must have an odd number of segments: ${r}`);return ry(n,r)},doc(r){if(!QE(r))throw ss(`document path must have an even number of segments: ${r}`);return md(n,r)},collectionGroup(r){if(r.length===0||r.includes("/"))throw ss(`collection group id must be a single non-empty segment with no '/': ${r}`);return yg(n,{source:{__ref:"group",collectionId:r},filters:[],orders:[],limitFromEnd:!1})},batch(){return uU(n)},runTransaction(r,s){return dU(n,r)},setRules(){throw Yp("setRules","Deploy rules asynchronously through the relay instead: `await sandbox.channel.op({ method: 'setFirestoreRules', source })`.")},seed(){throw Yp("seed","The relay has no atomic seed op; write seed docs through this handle (`db.doc(path).set(data)` / `db.batch()`), or drive `sandbox.channel.op({ method: 'admin.setDocument', path, data })` per document.")},snapshot(){throw Yp("snapshot","Read the worker state asynchronously instead: `await sandbox.channel.op({ method: 'admin.readState' })`.")}}}const CS=new WeakMap;function pA(t){const e=CS.get(t);if(e)return e;const n=rg(t.sandbox)?hA(t.sandbox,fU(t.auth)):pd(sA(t),t);return CS.set(t,n),n}function fU(t){return t==null?{mode:"anon"}:t.token===void 0?{mode:"as",uid:t.uid}:{mode:"as",uid:t.uid,token:t.token}}const NS=new WeakMap;function hU(t){const e=pU(t)?t:t.withAuth(null),n=NS.get(e);if(n)return n;const r=e.operationContext.authLens.mode==="admin"?e:Wl(e,{source:e.operationContext.source,authLens:{mode:"admin"},...e.operationContext.planId===void 0?{}:{planId:e.operationContext.planId}}),s=rg(r.sandbox)?hA(r.sandbox,{mode:"admin"}):pd(sA(r,!0),r,!0);return NS.set(e,s),s}function pU(t){return t!==null&&typeof t=="object"&&"sandbox"in t&&typeof t.withAuth=="function"}const Ya=Symbol("pyric/firestore/followsCurrentUser"),kl=Symbol("pyric/firestore/authSessionScope");function mU(t){if(t===null||typeof t!="object")return null;const e=t;return typeof e.path=="string"&&e.path.length>0?e.path:typeof e.collectionPath=="string"&&e.collectionPath.length>0?e.collectionPath:null}function yU(t){if(t!==null&&typeof t=="object"){const e=t.snapshotConstraints;if(typeof e=="function")return e.call(t)}}function gU(t){if(t===null||typeof t!="object")return!1;const e=t;return typeof e.path=="string"&&e.path.length>0&&e.parent!==void 0&&e.parent!==null}function mA(t,e,n,r,s){var N,R;let o={},c,d;if(typeof e=="object"&&e!==null&&typeof e.next!="function"&&typeof e.error!="function"&&typeof e.complete!="function"){if(o=e,typeof n=="function")c=n,d=r;else if(typeof n=="object"&&n!==null){const M=n;c=M.next,d=M.error}}else if(typeof e=="function")c=e,d=n;else if(typeof e=="object"&&e!==null){const M=e;c=M.next,d=M.error}if(!c&&!d)throw new TypeError("onSnapshot: missing handler. Provide a callback, or an observer with a `next` and/or `error` method.");const p=aU(t);if(p){if(o[Ya]===!0)throw new nt("unimplemented","onSnapshot: live (follows-current-user) listeners are not supported on a remote sandbox — remote listeners are frozen to the identity of the context that created the ref.");return p(o,c,d)}const g=bU(t),b=Wt(g.sandbox);let v;if(gU(t))v={kind:"doc",path:t.path};else{const M=mU(t);if(M===null)throw new TypeError("onSnapshot: could not determine the collection path for this Query. Pass a CollectionReference or a Query produced by `.where`/`.orderBy`/`.limit` on a CollectionReference obtained from `getFirestore(ctx)`.");const F=yU(t);v={kind:"query",collection:M,constraints:F}}const w=o[Ya]===!0,_=o[kl],k=t[rA]===!0;if(Ya in o){const{[Ya]:M,...F}=o;o=F}if(kl in o){const{[kl]:M,...F}=o;o=F}const I=()=>b.addSnapshotListener(v,c??(()=>{}),o,g.auth,d,w,k,_);return((R=(N=g.sandbox).runWithProvenance)==null?void 0:R.call(N,ql(g.operationContext),I))??I()}function bU(t){if(t===null||typeof t!="object")throw new TypeError("onSnapshot: reference must be a DocumentReference or Query.");const e=t[nA];if(!e)throw new TypeError("onSnapshot: reference was not produced by a sandbox context — pass a ref obtained from `getFirestore(ctx)`.");return e}eU(mA);oU(mA);class Er{constructor(e){G(this,"bytes");this.bytes=e,no(this,UD(e))}static fromBase64String(e){const n=atob(e),r=new Uint8Array(n.length);for(let s=0;s<n.length;s+=1)r[s]=n.charCodeAt(s);return new Er(r)}static fromUint8Array(e){return new Er(e.slice())}toBase64(){let e="";for(const n of this.bytes)e+=String.fromCharCode(n);return btoa(e)}toUint8Array(){return this.bytes.slice()}toString(){return`Bytes(base64: ${this.toBase64()})`}isEqual(e){return e instanceof Er&&this.bytes.length===e.bytes.length&&this.bytes.every((n,r)=>n===e.bytes[r])}toJSON(){return{type:"firestore/bytes/1.0",bytes:this.toBase64()}}static fromJSON(e){const n=e;if(n.type!=="firestore/bytes/1.0"||typeof n.bytes!="string")throw new TypeError("Invalid Bytes JSON value.");return Er.fromBase64String(n.bytes)}}class Or{constructor(e,n){G(this,"lat");G(this,"lng");if(this.lat=e,this.lng=n,!Number.isFinite(e)||e<-90||e>90)throw new TypeError("Latitude must be a number between -90 and 90.");if(!Number.isFinite(n)||n<-180||n>180)throw new TypeError("Longitude must be a number between -180 and 180.");no(this,Bl("geo-point",String(e),"\0",String(n)))}get latitude(){return this.lat}get longitude(){return this.lng}isEqual(e){return e instanceof Or&&this.lat===e.lat&&this.lng===e.lng}toJSON(){return{latitude:this.lat,longitude:this.lng,type:"firestore/geoPoint/1.0"}}static fromJSON(e){const n=e;if(n.type!=="firestore/geoPoint/1.0"||typeof n.latitude!="number"||typeof n.longitude!="number")throw new TypeError("Invalid GeoPoint JSON value.");return new Or(n.latitude,n.longitude)}}class Cl{constructor(e){G(this,"_values");this._values=e}static create(e){if(!e.every(n=>typeof n=="number"))throw new TypeError("Vector values must be numbers.");return new Cl(e.slice())}toArray(){return this._values.slice()}isEqual(e){const n=e instanceof Cl?e._values:void 0;return n!==void 0&&this._values.length===n.length&&this._values.every((r,s)=>r===n[s])}toJSON(){return{type:"firestore/vectorValue/1.0",vectorValues:this.toArray()}}static fromJSON(e){const n=e;if(n.type!=="firestore/vectorValue/1.0"||!Array.isArray(n.vectorValues)||!n.vectorValues.every(r=>typeof r=="number"))throw new TypeError("Invalid VectorValue JSON value.");return Cl.create(n.vectorValues)}}function vU(t=[]){return Cl.create(t)}function Zz(){return BD.serverTimestamp()}const Ys=Symbol("pyric/firestore/target");function ni(t){return t.kind==="sandbox"?t.db:t.getDb()}const zd=new WeakMap;function sy(t,e){return zd.set(t,e),t}const Qi=new WeakMap;function wU(t,e,n){return zd.set(t,e),Qi.set(t,n),t}function Pd(t,e){const n=Ji(e);if(t.kind==="sandbox")return n;const r=Qi.get(n);if(!r)throw new TypeError("pyric/firestore: live ref missing rebuild closure — was it produced by a factory in this package?");return r(ni(t))}function xU(t,e){const n=Ji(e);if(t.kind==="sandbox")return n;const r=Qi.get(n);if(!r)throw new TypeError("pyric/firestore: live collection ref missing rebuild closure.");return r(ni(t))}function SU(t,e){const n=Ji(e);if(t.kind==="sandbox")return n;const r=Qi.get(n);if(!r)throw new TypeError("pyric/firestore: live query missing rebuild closure.");return r(ni(t))}function ao(t,e,n){return e.kind==="sandbox-live"?wU(t,e,n):sy(t,e)}function _U(t){const e=Ji(t),n=Qi.get(e);return n||(()=>e)}function Tr(t){var n;let e;if(Ys in t?e=t[Ys]:e=zd.get(t),!e)throw new TypeError("pyric/firestore: unrecognized reference — was it produced by a factory in this package?");return e.kind==="sandbox-live"&&((n=e.assertUsable)==null||n.call(e)),e}const yA=new WeakMap,yd=new WeakMap;function mo(t){return yA.get(t)}function Ji(t){return yd.get(t)??t}function gg(t,e,n){const r={id:t.id??"",path:t.path??""};return yA.set(r,n),yd.set(r,t),zd.set(r,e),r}function OS(t){return Array.isArray(t)&&t.every(e=>typeof e=="number")}function EU(t){if(t instanceof uo)return Array.from(t.value);if(t===null||typeof t!="object")return null;const e=t;return e.typeName==="vector"&&OS(e.value)||e.__type__==="__vector__"&&OS(e.value)?e.value:null}function iy(t){if(t instanceof In)return Er.fromUint8Array(t.data);if(t instanceof Cr)return new Or(t.lat,t.lng);const e=EU(t);if(e)return vU(e);if(Array.isArray(t))return t.map(iy);if(t!==null&&typeof t=="object"){const n=Object.getPrototypeOf(t);if(n===Object.prototype||n===null){const r={};for(const[s,o]of Object.entries(t))r[s]=iy(o);return r}}return t}function gA(t){if(t!==void 0)return iy(t)}function Vd(t){if(t===void 0)return Vd(HE());const e=sg(t);if(e)return e.service("firestore/default",()=>{const{sandbox:n,session:r}=e;let s=!1;e.onDelete(()=>{s=!0});const o=e.authScope;o&&e.onDelete(r.onCurrentUserChanged(d=>{Wt(n).reevaluateLiveListeners(d,o)}));const c={kind:"sandbox-live",sandbox:n,getDb:RS(n,()=>r.currentUser),authScope:o,own:d=>e.onDelete(d),assertUsable:()=>{if(s)throw new Wi("failed-precondition","The client has already been terminated.")}};return{[Ys]:c,app:t}});if(bA(t)){const r={kind:"sandbox",db:pA(t),sandbox:t.sandbox};return{[Ys]:r}}if(AU(t)){const n={kind:"sandbox-live",sandbox:t,getDb:RS(t)};return{[Ys]:n}}throw new TypeError("pyric/firestore is a sandbox-only mirror. Package resolution must leave firebase/firestore unchanged for production; activate pyric dev or @pyric/cli/register before importing to select the sandbox.")}function bg(t){const e=sg(t);if(e){e.assertAlive();const c=e.sandbox;return bg(Wl(c.withAuth(null),{source:{kind:"app"},authLens:{mode:"admin"}}))}const n=bA(t)?t:t.withAuth(null),r=n.sandbox,o={kind:"sandbox",db:hU(n),sandbox:r};return{[Ys]:o}}function bA(t){return t instanceof ho}function AU(t){if(t===null||typeof t!="object")return!1;const e=t;return typeof e.withAuth=="function"&&typeof e.onCurrentUserChanged=="function"&&"currentUser"in e&&"admin"in e}function RS(t,e=()=>t.currentUser){return()=>{const n=Wl(t.withAuth(e()),{source:{kind:"app"},authLens:{mode:"app-session"}});return pA(n)}}function gd(t){const e=t,n=e.data.bind(t);return Object.defineProperty(e,"data",{value:()=>gA(n()),configurable:!0,writable:!0}),t}function vA(t,e){return{id:t.id,exists:t.exists,data:()=>{if(!(typeof t.exists=="function"?t.exists():t.exists))return;const r=gA(t.data()),s={id:t.id,exists:!0,data:()=>r};return e.fromFirestore(s)}}}function Hd(t,e){if(!t||typeof t!="object")return t;const n=t;if(n.ref&&(sy(n.ref,e),TS(n.ref,e)),DS(n),Array.isArray(n.docs))for(const r of n.docs)r!=null&&r.ref&&(sy(r.ref,e),TS(r.ref,e)),r&&DS(r);return t}function TS(t,e){if(typeof t.path!="string"||t.path.length===0||yd.has(t))return;const n=t.path;try{const r=ni(e).doc(n);yd.set(t,r),e.kind==="sandbox-live"&&Qi.set(r,s=>s.doc(n))}catch{}}function DS(t){const e=t.exists;if(typeof e=="function")return;const n=e===!0;try{Object.defineProperty(t,"exists",{value:()=>n,writable:!0,configurable:!0,enumerable:!0})}catch{}}async function vg(t){const e=Tr(t),n=mo(t),r=await Pd(e,t).get();return n?vA(r,n):(Hd(r,e),gd(r))}async function zl(t){const e=Tr(t),n=mo(t),r=await SU(e,t).get();if(n){const o=n,c=r.docs.map(d=>vA(d,o));return{size:c.length,empty:c.length===0,docs:c}}Hd(r,e);const s=r.docs;for(const o of s)gd(o);return r}function ur(t,...e){const n=Tr(t),r=Ys in t,s=r?void 0:mo(t),o=ni(n);if(r){if(e.length===0)throw new TypeError("doc(db, path) requires at least one path segment.");const g=e.join("/"),b=o.doc(g);return ao(b,n,w=>w.doc(g))}const c=Ji(t),d=e.length===0?c.doc():c.doc(e.join("/")),f=d.path,p=ao(d,n,g=>g.doc(f));return s?gg(p,n,s):p}function Ui(t,...e){const n=Tr(t),r=Ys in t;if(e.length===0)throw new TypeError("collection() requires at least one path segment.");if(r){const f=e.join("/"),p=ni(n).collection(f);return ao(p,n,g=>g.collection(f))}const s=Ji(t),o=e.join("/"),c=s.collection(o),d=c.path;return ao(c,n,f=>f.collection(d))}async function Pl(t,e,n){const r=Tr(t),s=mo(t),o=s?s.toFirestore(e):e;return Pd(r,t).set(o,n)}async function ay(t,e){const n=Tr(t);return Pd(n,t).update(e)}async function bd(t){const e=Tr(t);return Pd(e,t).delete()}async function wg(t,e){const n=Tr(t),r=mo(t),s=r?r.toFirestore(e):e,o=await xU(n,t).add(s),c=o.path,d=ao(o,n,f=>f.doc(c));return r?gg(d,n,r):d}function wA(t){return typeof t=="string"?t:t._internalPath.segments.join(".")}function Vl(t,...e){const n=Tr(t),r=mo(t),s=_U(t),o=f=>{let p=s(f);for(const g of e)p=g.applySandbox(p);return p},c=o(ni(n)),d=ao(c,n,f=>o(f));return r?gg(d,n,r):d}function jU(t,e,n){const r=wA(t);return{applySandbox:o=>o.where(r,e,n),_sandboxFilter:{kind:"where",field:r,op:e,value:n}}}function IS(t,e){const n=wA(t);return{applySandbox:r=>r.orderBy(n,e)}}function vd(t){return{applySandbox:e=>e.limit(t)}}function kU(t){if(t.length!==1)return!1;const e=t[0];return e!==null&&typeof e=="object"&&"data"in e&&typeof e.data=="function"}function CU(...t){if(kU(t)){const e=t[0];return{applySandbox:n=>n.startCursorFromSnapshot(e,!1)}}return{applySandbox:e=>e.startCursor(t,!1)}}function NU(t,e,n,r){const s=Tr(t),o=RU(s,t),c=TU(e,n,r,s),d=DU(c,s),f=d.length===3?o.onSnapshot(d[0],d[1],d[2]):d.length===2?o.onSnapshot(d[0],d[1]):o.onSnapshot(d[0]);if(s.kind!=="sandbox-live"||!s.own)return f;let p=!1;const g=()=>{p||(p=!0,f())},b=()=>{var w;p||(g(),(w=OU(d))==null||w(new Wi("aborted","The operation was aborted.")))},v=s.own(b);return()=>{v(),g()}}function OU(t){const e=t.at(-1);if(typeof e=="function"&&t.length>=3)return e;if(e&&typeof e=="object"){const n=e.error;if(typeof n=="function")return n}}function RU(t,e){const n=Ji(e);if(t.kind==="sandbox")return n;const r=Qi.get(n);if(!r)throw new TypeError("pyric/firestore: live ref missing rebuild closure for onSnapshot.");return r(ni(t))}function xA(t){if(typeof t!="object"||t===null)return!1;const e=t;return typeof e.next=="function"||typeof e.error=="function"||typeof e.complete=="function"}function TU(t,e,n,r){if(typeof t=="object"&&t!==null&&!xA(t)){const o=e;return typeof o=="function"?[t,MS(o,r),n??oy]:o&&typeof o=="object"?[t,LS(o,r)]:[t]}return typeof t=="function"?[MS(t,r),e??oy]:t&&typeof t=="object"?[LS(t,r)]:[t]}function DU(t,e){if(e.kind!=="sandbox-live")return t;const n=t[0];return typeof n=="object"&&n!==null&&!xA(n)?[{...n,[Ya]:!0,...e.authScope?{[kl]:e.authScope}:{}},...t.slice(1)]:[{[Ya]:!0,...e.authScope?{[kl]:e.authScope}:{}},...t]}function SA(t,e){if(!t||typeof t!="object")return t;const n=t;if(typeof n.data=="function"&&gd(t),Array.isArray(n.docs))for(const r of n.docs)gd(r);return t}function oy(t){console.error("pyric/firestore: Uncaught Error in snapshot listener:",t)}function MS(t,e){return n=>t(SA(Hd(n,e)))}function LS(t,e){return{...t,next:t.next?n=>t.next(SA(Hd(n,e))):void 0,error:t.error??oy}}function Wz(t,e){return Wt(t).deployRules(e)}function IU(t,e={}){const n=e.recentEventLimit??10,r=Wt(t),s=r.getRules(),o=s?Yu(s):{warnings:[]},c=o.warnings.map(k=>({rule:k.rule,severity:k.severity,message:k.message})),d={errors:0,warnings:0,info:0};for(const k of o.warnings)k.severity==="error"?d.errors++:k.severity==="warning"?d.warnings++:d.info++;const f=r.snapshot(),p={};for(const k of Object.keys(f)){const I=k.split("/")[0]??"";I&&(p[I]=(p[I]??0)+1)}const g=t.history(),b=g.filter(k=>k.kind==="request"),v=b.filter(k=>k.result==="deny"),w=b.slice(-n).map(k=>({path:String(k.path??""),method:String(k.method??""),result:String(k.result??""),auth:k.auth??null})),_=v.slice(-n).map(k=>({path:String(k.path??""),method:String(k.method??""),auth:k.auth??null,debugMessage:typeof k.debugMessage=="string"?k.debugMessage:void 0}));return{rules:{source:s,sizeBytes:new TextEncoder().encode(s).byteLength,isEmpty:s.trim().length===0,lint:{...d,findings:c}},documents:{totalCount:Object.keys(f).length,byCollection:p},events:{totalCount:g.length,recentDenials:_,recentRequests:w}}}const Ls={description:"Identity to act as. Omit or 'admin' = admin write that BYPASSES rules (sandbox seeding). { uid, claims? } = act as that user with rules ENFORCED.",oneOf:[{type:"string",enum:["admin"]},{type:"object",properties:{uid:{type:"string"},claims:{type:"object",description:"Custom claims forwarded to the rule context (request.auth.token)."}},required:["uid"]}]},MU=["<","<=","==","!=",">=",">","in","not-in","array-contains","array-contains-any"],LU={type:"object",properties:{field:{type:"string"},op:{type:"string",enum:[...MU]},value:{}},required:["field","op","value"]};function _A(t){const{resolveDb:e}=t;return[{name:"firestore_get_document",description:"Get a Firestore document by path. Admin by default; pass `as:{uid}` to read with rules enforced as that user.",parameters:{type:"object",properties:{path:{type:"string",description:'e.g. "users/alice"'},as:Ls},required:["path"]},async execute(n){const r=n,s=await e(r.as),o=ur(s,r.path),c=await vg(o),d=typeof c.exists=="function"?c.exists():c.exists;return{ok:!0,summary:d?`Got ${r.path}`:`No document at ${r.path}`,data:{exists:d,data:d?c.data():null}}}},{name:"firestore_list_documents",description:"List documents in a collection. Supports orderBy + limit. Admin by default; pass `as:{uid}` to enforce rules.",parameters:{type:"object",properties:{collection:{type:"string"},orderBy:{type:"string"},limit:{type:"number"},as:Ls},required:["collection"]},async execute(n){const r=n,s=await e(r.as),o=Ui(s,r.collection),c=[];r.orderBy&&c.push(IS(r.orderBy)),r.limit&&c.push(vd(r.limit));const d=await zl(Vl(o,...c));return{ok:!0,summary:`${d.size} docs in ${r.collection}`,data:{docs:d.docs.map(f=>({id:f.id,data:f.data()}))}}}},{name:"firestore_create_document",description:"Create or replace a Firestore document at an explicit path. Admin by default (bypasses rules — for seeding); pass `as:{uid}` to write as that user with rules enforced.",parameters:{type:"object",properties:{path:{type:"string"},data:{type:"object"},as:Ls},required:["path","data"]},async execute(n){const r=n,s=await e(r.as);return await Pl(ur(s,r.path),r.data),{ok:!0,summary:`Created ${r.path}`}}},{name:"firestore_add_document",description:"Add a document with an auto-generated id under a collection (mirrors the Web SDK addDoc). Admin by default — the right tool for seeding; pass `as:{uid}` to write as a user with rules enforced. Returns the minted path.",parameters:{type:"object",properties:{collection:{type:"string",description:'Collection to add the doc under, e.g. "users" or "users/u1/posts".'},data:{type:"object"},as:Ls},required:["collection","data"]},async execute(n){const r=n,s=await e(r.as),o=await wg(Ui(s,r.collection),r.data);return{ok:!0,summary:`Created ${o.path}`,data:{path:o.path,id:o.id}}}},{name:"firestore_update_document",description:"Merge fields into an existing Firestore document. Admin by default; pass `as:{uid}` to enforce rules.",parameters:{type:"object",properties:{path:{type:"string"},data:{type:"object"},as:Ls},required:["path","data"]},async execute(n){const r=n,s=await e(r.as);return await ay(ur(s,r.path),r.data),{ok:!0,summary:`Updated ${r.path}`}}},{name:"firestore_delete_document",description:"Delete a Firestore document. Admin by default; pass `as:{uid}` to enforce rules.",parameters:{type:"object",properties:{path:{type:"string"},as:Ls},required:["path"]},async execute(n){const r=n,s=await e(r.as);return await bd(ur(s,r.path)),{ok:!0,summary:`Deleted ${r.path}`}}},{name:"firestore_batch_write",description:"Apply many writes (set / update / delete) in ONE call — the efficient way to seed or bulk-edit (one call, not N). Applied in order; stops on the first failure. Admin by default; pass `as:{uid}` to apply them as a user with rules enforced. Up to 500 ops.",parameters:{type:"object",properties:{operations:{type:"array",description:"Writes applied in order; stops on the first failure (NOT atomic — earlier writes are not rolled back).",minItems:1,maxItems:500,items:{type:"object",properties:{op:{type:"string",enum:["set","update","delete"]},path:{type:"string"},data:{type:"object",description:"Required for set/update; ignored for delete."}},required:["op","path"]}},as:Ls},required:["operations"]},async execute(n){const r=n;if(r.operations.length===0||r.operations.length>500)return{ok:!1,summary:`firestore_batch_write: operations must be 1..500 (got ${r.operations.length}).`};const s=await e(r.as);for(const o of r.operations){const c=ur(s,o.path);o.op==="set"?await Pl(c,o.data??{}):o.op==="update"?await ay(c,o.data??{}):await bd(c)}return{ok:!0,summary:`Applied ${r.operations.length} write(s)`,data:{count:r.operations.length}}}},{name:"firestore_query_where",description:"Query a collection with one or more where clauses (AND-semantics) + optional orderBy + limit. For OR semantics use a single where clause with the `in` / `array-contains-any` op. Admin by default; pass `as:{uid}` to enforce rules.",parameters:{type:"object",properties:{collection:{type:"string"},where:{type:"array",description:"One or more where clauses. AND across clauses.",items:LU,minItems:1},orderBy:{type:"string"},limit:{type:"number"},as:Ls},required:["collection","where"]},async execute(n){const r=n,s=await e(r.as),o=Ui(s,r.collection),c=r.where.map(f=>jU(f.field,f.op,f.value));r.orderBy&&c.push(IS(r.orderBy)),r.limit&&c.push(vd(r.limit));const d=await zl(Vl(o,...c));return{ok:!0,summary:`${d.size} matches in ${r.collection}`,data:{docs:d.docs.map(f=>({id:f.id,data:f.data()}))}}}}]}function EA(t){const{resolveSandbox:e}=t;return[{name:"sandbox_inspect",description:"Single-call sandbox diagnostic. Returns current rules source, lint summary, doc count by collection, and recent denials + requests. Use this FIRST when debugging unexpected sandbox behavior — it surfaces the rules / state / event log without forcing per-tool grep.",parameters:{type:"object",properties:{recentEventLimit:{type:"number",description:"Cap on recent denials/requests returned. Default 10.",default:10}}},async execute(n){const r=n,s=await e(),o=IU(s,{recentEventLimit:r.recentEventLimit});return{ok:!0,summary:`rules: ${o.rules.isEmpty?"EMPTY (setRules has not been called)":`${o.rules.sizeBytes}B, ${o.rules.lint.errors} errors / ${o.rules.lint.warnings} warnings`} · docs: ${o.documents.totalCount} across ${Object.keys(o.documents.byCollection).length} collections · events: ${o.events.totalCount} total, ${o.events.recentDenials.length} recent denials`,data:o}}}]}function US(t,e){return{code:t.code,severity:e,message:t.message,path:t.path,origin:"validate"}}let Di=[],ly=!1,cy=!1,uy=!1,Zp;function UU(){if(Zp)return Zp;const t=Md();return t.addOperation("lint",{_nonterminal(...e){e.forEach(n=>n.lint())},_iter(...e){e.forEach(n=>n.lint())},_terminal(){},CallExpr_methodCall(e,n,r,s,o,c){e.lint(),o.asIteration().children.forEach(d=>d.lint()),r.sourceString==="child"&&e.sourceString==="data"&&(uy=!0)},ident(e,n,r){const s=this.sourceString;s==="data"&&(ly=!0),s==="newData"&&(cy=!0)},bool_true(e){Di.push({code:"HARDCODED_TRUE",message:"Rule expression is hardcoded to true"})},bool_false(e){Di.push({code:"HARDCODED_FALSE",message:"Rule expression is hardcoded to false"})},Comparison_looseEq(e,n,r){Di.push({code:"LOOSE_EQUALITY",message:"Use '===' instead of '=='"}),e.lint(),r.lint()},Comparison_looseNeq(e,n,r){Di.push({code:"LOOSE_INEQUALITY",message:"Use '!==' instead of '!='"}),e.lint(),r.lint()}}),Zp=t,t}function $U(t,e="read"){const n=Id(t);return n.failed()?[]:(Di=[],ly=!1,cy=!1,uy=!1,UU()(n).lint(),e==="write"&&ly&&!cy&&!uy&&Di.push({code:"DATA_IN_WRITE",message:"Write rule references 'data' but not 'newData'; consider using 'newData' to check incoming data"}),[...Di])}const BU={read:new Set(["auth","data","root","now"]),write:new Set(["auth","data","newData","root","now"]),validate:new Set(["auth","data","newData","root","now"])},qU=new Set(["val","exists","hasChild","hasChildren","isString","isNumber","isBoolean","child","parent","getPriority"]),FU=new Set(["matches","contains","beginsWith","endsWith","replace","toLowerCase","toUpperCase","length"]),zU=new Set([...qU,...FU]);let Nl=[],Fu="read",AA=new Set,Wp;function PU(){if(Wp)return Wp;const t=Md();return t.addOperation("validate",{_nonterminal(...e){e.forEach(n=>n.validate())},_iter(...e){e.forEach(n=>n.validate())},_terminal(){},CallExpr_methodCall(e,n,r,s,o,c){e.validate();const d=r.sourceString;zU.has(d)||Nl.push({code:"UNKNOWN_METHOD",message:`Unknown method '${d}'`}),o.asIteration().children.forEach(f=>f.validate())},CallExpr_memberAccess(e,n,r){e.validate()},CallExpr_indexAccess(e,n,r,s){e.validate(),r.validate()},ident(e,n,r){const s=this.sourceString;if(e.sourceString==="$")return;const c=BU[Fu];c&&(!c.has(s)&&!AA.has(s)&&Nl.push({code:"UNKNOWN_IDENTIFIER",message:`Identifier '${s}' is not allowed in '${Fu}' context`}),s==="newData"&&Fu==="read"&&Nl.push({code:"NEWDATA_IN_READ",message:"'newData' is not available in 'read' context"}))}}),Wp=t,t}function VU(t,e,n=[]){const r=Id(t);return r.failed()?[]:(Nl=[],Fu=e,AA=new Set(n.map(s=>s.startsWith("$")?s.slice(1):s)),PU()(r).validate(),[...Nl])}const HU=new Set(["__proto__","prototype","constructor"]);function $S(t,e){return HU.has(e)?null:typeof t=="string"?e==="length"?t.length:null:t===null||typeof t!="object"||!Object.hasOwn(t,e)?null:t[e]??null}class is{constructor(e,n="/",r){G(this,"_value");G(this,"_path");G(this,"_root");this._value=e??null,this._path=n,this._root=r!==void 0?r:e}val(){return this._value}exists(){return this._value!==null&&this._value!==void 0}hasChild(e){return this.child(e).exists()}hasChildren(e){return Array.isArray(e)?e.every(n=>this.hasChild(String(n))):typeof this._value=="object"&&this._value!==null&&Object.keys(this._value).length>0}isString(){return typeof this._value=="string"}isNumber(){return typeof this._value=="number"}isBoolean(){return typeof this._value=="boolean"}child(e){const n=e.split("/").filter(o=>o.length>0);let r=this._value,s=this._path;for(const o of n){if(r==null||typeof r!="object"){r=null,s=`${s}/${o}`.replace(/\/+/g,"/");break}r=Object.hasOwn(r,o)?r[o]??null:null,s=`${s==="/"?"":s}/${o}`}return new is(r,s,this._root)}parent(){if(this._path==="/")return null;const e=this._path.split("/").filter(s=>s.length>0);e.pop();const n="/"+e.join("/"),r=new is(this._root,"/");return n==="/"?r:r.child(e.join("/"))}getPriority(){return null}}class GU{constructor(e){G(this,"value");this.value=e}matches(e){return(e instanceof RegExp?e:new RegExp(e)).test(this.value)}contains(e){return this.value.includes(e)}beginsWith(e){return this.value.startsWith(e)}endsWith(e){return this.value.endsWith(e)}replace(e,n){if(e instanceof RegExp){const r=e.flags.includes("g")?e.flags:`${e.flags}g`;return this.value.replace(new RegExp(e.source,r),n)}return e===""?this.value:this.value.split(e).join(n)}toLowerCase(){return this.value.toLowerCase()}toUpperCase(){return this.value.toUpperCase()}get length(){return this.value.length}}let $s={auth:null,data:new is(null),newData:new is(null),root:new is(null),now:Date.now(),pathVariableBindings:{}},Qp;function KU(){if(Qp)return Qp;const t=Md();return t.addOperation("eval",{Expr(e){return e.eval()},Ternary_ternary(e,n,r,s,o){return e.eval()?r.eval():o.eval()},Ternary(e){return e.eval()},Logical_and(e,n,r){return e.eval()&&r.eval()},Logical_or(e,n,r){return e.eval()||r.eval()},Logical(e){return e.eval()},Comparison_strictEq(e,n,r){return e.eval()===r.eval()},Comparison_strictNeq(e,n,r){return e.eval()!==r.eval()},Comparison_gte(e,n,r){return e.eval()>=r.eval()},Comparison_lte(e,n,r){return e.eval()<=r.eval()},Comparison_gt(e,n,r){return e.eval()>r.eval()},Comparison_lt(e,n,r){return e.eval()<r.eval()},Comparison_looseEq(e,n,r){return e.eval()==r.eval()},Comparison_looseNeq(e,n,r){return e.eval()!=r.eval()},Comparison(e){return e.eval()},Additive_add(e,n,r){return e.eval()+r.eval()},Additive_sub(e,n,r){return e.eval()-r.eval()},Additive(e){return e.eval()},Multiplicative_mul(e,n,r){return e.eval()*r.eval()},Multiplicative_div(e,n,r){return e.eval()/r.eval()},Multiplicative_mod(e,n,r){return e.eval()%r.eval()},Multiplicative(e){return e.eval()},UnaryExpr_not(e,n){return!n.eval()},UnaryExpr_neg(e,n){return-n.eval()},UnaryExpr(e){return e.eval()},CallExpr_methodCall(e,n,r,s,o,c){const d=e.eval(),f=r.sourceString,p=o.asIteration().children.map(g=>g.eval());if(d instanceof is)switch(f){case"val":return d.val();case"exists":return d.exists();case"hasChild":return d.hasChild(String(p[0]));case"hasChildren":return d.hasChildren(p.length>0?p[0]:void 0);case"isString":return d.isString();case"isNumber":return d.isNumber();case"isBoolean":return d.isBoolean();case"child":return d.child(String(p[0]));case"parent":return d.parent();case"getPriority":return d.getPriority();default:throw new Error(`Unknown DataSnapshot method: ${f}`)}if(typeof d=="string"){const g=new GU(d);switch(f){case"matches":return g.matches(p[0]);case"contains":return g.contains(String(p[0]));case"beginsWith":return g.beginsWith(String(p[0]));case"endsWith":return g.endsWith(String(p[0]));case"replace":return g.replace(p[0],String(p[1]));case"toLowerCase":return g.toLowerCase();case"toUpperCase":return g.toUpperCase();default:throw new Error(`Unknown string method: ${f}`)}}throw new Error(`Unknown method '${f}' for the given value.`)},CallExpr_memberAccess(e,n,r){const s=e.eval();return s==null?null:$S(s,r.sourceString)},CallExpr_indexAccess(e,n,r,s){const o=e.eval(),c=r.eval();return o==null?null:$S(o,String(c))},CallExpr(e){return e.eval()},Primary_paren(e,n,r){return n.eval()},Primary(e){return e.eval()},Array(e,n,r){return n.asIteration().children.map(s=>s.eval())},literal(e){return e.eval()},number_float(e,n,r){return parseFloat(this.sourceString)},number_int(e){return parseInt(this.sourceString,10)},number(e){return e.eval()},string_double(e,n,r){return JSON.parse(this.sourceString)},string_single(e,n,r){return n.children.map(s=>s.sourceString).join("")},string(e){return e.eval()},regex(e,n,r,s){return new RegExp(n.sourceString,s.sourceString)},bool_true(e){return!0},bool_false(e){return!1},bool(e){return e.eval()},null(e){return null},ident(e,n,r){const s=this.sourceString;if(s in $s.pathVariableBindings)return $s.pathVariableBindings[s];switch(s){case"auth":return $s.auth;case"data":return $s.data;case"newData":return $s.newData;case"root":return $s.root;case"now":return $s.now;default:return}}}),Qp=t,t}function jA(t,e){const n=Id(t);if(n.failed())throw new Error(n.message??"RTDB expression failed to parse");return $s=e,KU()(n).eval()}const YU=Mn({operation:to(["read","write","validate"]),path:vn().min(1).startsWith("/"),auth:Dd([Mn({uid:vn(),token:Qs(rs())}),uE()]),mockData:Qs(rs()),newData:rs().optional(),updates:dE(Mn({path:vn().min(1).startsWith("/"),value:rs()})).optional()});to(["INVALID_INPUT","NO_MATCHING_RULE","EVALUATION_ERROR"]);Mn({allowed:$l(),unsupported:$l().optional(),matchedPath:vn(),matchedRule:vn(),reason:vn(),pathVariableBindings:Qs(vn())});function ZU(t){const e=t.val();return e===null||typeof e!="object"?[]:Object.keys(e)}function WU(t,e,n,r,s,o){let c=null;function d(p,g,b,v,w){if(!b.exists())return null;const _=p.validate;if(_){if(!_.parsed.valid)c||(c={node:p,rule:_,bindings:v,unsupported:!0});else if(!jA(_.raw,s(g,b,v)))return{node:p,rule:_,bindings:v}}for(const k of p.children){const I=k.path.split("/").filter(Boolean);if(I.length===0)continue;const N=I[I.length-1],R=N.startsWith("$");if(w.length>0){if(!R&&w[0]!==N)continue;return d(k,g.child(w[0]),b.child(w[0]),R?{...v,[N]:w[0]}:v,w.slice(1))}if(R)for(const M of ZU(b)){const F=d(k,g.child(M),b.child(M),{...v,[N]:M},[]);if(F)return F}else{const M=d(k,g.child(N),b.child(N),v,[]);if(M)return M}}return null}return d(t,e,n,r,o)??c}function kA(t,e,n,r=0){const s=[{node:t,pathVariableBindings:{...n},depth:r}];if(e.length===0)return s;for(const o of t.children){const c=o.path.split("/").filter(Boolean);if(c.length===0)continue;const d=c[c.length-1],f=d.startsWith("$");if(f||e[0]===d){const p=f?{...n,[d]:e[0]}:{...n},g=kA(o,e.slice(1),p,r+1);return s.push(...g),s}}return s}function dy(t,e,n){if(e.length===0)return n??null;const[r,...s]=e,o=t!==null&&typeof t=="object"&&!Array.isArray(t)?{...t}:{},c=Object.hasOwn(o,r)?o[r]:null,d=dy(c,s,n);return d==null?delete o[r]:o[r]=d,o}function QU(t,e,n,r){if(!r||r.length===0)return dy(t,e,n??null);let s=t;for(const o of r){const c=o.path.split("/").filter(Boolean);s=dy(s,c,o.value??null)}return s}class JU{execute(e,n){const r=YU.safeParse(n);if(!r.success)return{success:!1,error:{code:"INVALID_INPUT",message:r.error.message,recoverable:!0}};const{operation:s,path:o,auth:c,mockData:d,newData:f,updates:p}=r.data;try{const g=o.split("/").filter(Boolean),b=e,v=kA(b,g,{}),w=new is(d,"/"),_=s==="read"?d:QU(d,g,f,p),k=new is(_,"/"),I=(F,D,C)=>{const L={};for(const[U,H]of Object.entries(C))L[U]=H,L[U.slice(1)]=H;return{auth:c?{uid:c.uid,token:c.token}:null,data:F,newData:D,root:w,now:Date.now(),pathVariableBindings:L}};let N;for(const F of v){const D=F.node[s];if(!D)continue;if(!D.parsed.valid){N||(N=F);continue}const C=g.slice(0,F.depth).join("/"),L=w.child(C),U=k.child(C);if(jA(D.raw,I(L,U,F.pathVariableBindings))){if(s==="write"){const z=WU(b,w,k,{},I,g);if(z)return{success:!0,data:{allowed:!1,unsupported:z.unsupported===!0,matchedPath:z.node.path,matchedRule:z.rule.raw,reason:z.unsupported?`Validation rule at '${z.node.path}' contains an expression the simulator cannot evaluate: ${z.rule.raw} — not evaluated; production may reject this write.`:"Validation rule evaluated to false",pathVariableBindings:z.bindings}}}return{success:!0,data:{allowed:!0,matchedPath:F.node.path,matchedRule:D.raw,reason:"Rule expression evaluated to true",pathVariableBindings:F.pathVariableBindings}}}}if(N){const F=N.node[s];return{success:!0,data:{allowed:!1,unsupported:!0,matchedPath:N.node.path,matchedRule:F.raw,reason:`'${s}' rule at '${N.node.path}' contains an expression the simulator cannot evaluate: ${F.raw} — not evaluated; production may reject or allow this ${s}.`,pathVariableBindings:N.pathVariableBindings}}}const R=v[v.length-1],M=R.node[s];return M?{success:!0,data:{allowed:!1,matchedPath:R.node.path,matchedRule:M.raw,reason:"Rule expression evaluated to false",pathVariableBindings:R.pathVariableBindings}}:{success:!1,error:{code:"NO_MATCHING_RULE",message:`No '${s}' rule found for path '${o}'`,recoverable:!0}}}catch(g){return{success:!1,error:{code:"EVALUATION_ERROR",message:g instanceof Error?g.message:String(g),recoverable:!1}}}}}const XU=new Set([".read",".write",".validate",".indexOn"]);function CA(t,e,n=[]){const r=K2(t),s=r.valid?VU(t,e,n):r.errors,o=r.valid?$U(t,e):[];return{raw:t,parsed:{...r,errors:s,warnings:o}}}function NA(t,e,n){const r={path:e,pathVariables:[...n],children:[]};for(const[o,c]of[[".read","read"],[".write","write"],[".validate","validate"]]){const d=t[o];d!==void 0&&(r[c]=CA(String(d),c,n))}const s=t[".indexOn"];s!==void 0&&(r.indexOn=Array.isArray(s)?s.map(String):[String(s)]);for(const[o,c]of Object.entries(t)){if(XU.has(o)||typeof c!="object"||c===null)continue;const d=e==="/"?`/${o}`:`${e}/${o}`,f=o.startsWith("$")?[...n,o]:[...n];r.children.push(NA(c,d,f))}return r}function OA(t){if(!t||typeof t!="object")throw new Error("Invalid rules JSON: expected an object");const e=t;if(!("rules"in e))throw new Error('Invalid rules JSON: missing top-level "rules" key');if(typeof e.rules!="object"||e.rules===null)throw new Error('Invalid rules JSON: "rules" must be an object');return NA(e.rules,"/",[])}function Jp(t){return t==="true"?!0:t==="false"?!1:t}function RA(t){const e={};t.read&&(e[".read"]=Jp(t.read.raw)),t.write&&(e[".write"]=Jp(t.write.raw)),t.validate&&(e[".validate"]=Jp(t.validate.raw)),t.indexOn&&(e[".indexOn"]=t.indexOn);for(const n of t.children){const r=n.path.split("/").filter(Boolean);e[r[r.length-1]]=RA(n)}return e}function e$(t){if(!t||typeof t!="object"||!("path"in t))throw new Error("Invalid compiled rules: expected a rules node with a 'path' property");return{rules:RA(t)}}function xg(t,e){return new JU().execute(t,e)}const ts=t=>t,BS=(...t)=>ts(t.map(e=>`(${e})`).join(" && ")),t$=(...t)=>ts(t.map(e=>`(${e})`).join(" || ")),TA=t=>t,n$=()=>TA("newData.hasChildren()"),r$=t=>TA(`newData.hasChild("${t}")`);function DA(t,e){const n=t.shape,r=[],s={};for(const[d,f]of Object.entries(n)){const p=f,g=p instanceof jr,b=g?p.unwrap():p;g||r.push(d);const v=IA(b,d),w=e==null?void 0:e[d];if(w&&w.length>0?s[d]={validate:BS(v,...w)}:s[d]={validate:v},b instanceof mt){const _=DA(b);s[d]={validate:_.validate,children:_.children}}}const o=[n$()];for(const d of r)o.push(r$(d));return{validate:BS(...o),children:s}}function IA(t,e){if(t instanceof _r)return ts("newData.isString()");if(t instanceof $i)return ts("newData.isNumber()");if(t instanceof Ju)return ts("newData.isBoolean()");if(t instanceof Ws){const n=t.options;return ts(n.map(r=>`newData.val() === "${r}"`).join(" || "))}if(t instanceof Ul){const n=t.value;return ts(typeof n=="string"?`newData.val() === "${n}"`:`newData.val() === ${n}`)}if(t instanceof Ml){const n=t._def.options;return t$(...n.map(r=>IA(r,e)))}if(t instanceof mt)return ts("newData.hasChildren()");throw new Error(`Unsupported Zod type for RTDB rules: ${t.constructor.name} on field "${e}"`)}function s$(t){let e;if(typeof t=="function"){const s=[];t({path:(o,c)=>s.push([o,c])}),e=s}else e=Object.entries(t);const n=MA(e);n.sort((s,o)=>{const c=s[0]==="/"?0:s[0].split("/").filter(Boolean).length,d=o[0]==="/"?0:o[0].split("/").filter(Boolean).length;return c-d||s[0].localeCompare(o[0])});const r={path:"/",pathVariables:[],children:[]};for(const[s]of n)s!=="/"&&i$(r,s);for(const[s,o]of n){const c=s==="/"?r:Sg(r,s);c&&a$(r,c,o,s)}return r}function i$(t,e){const n=e.split("/").filter(Boolean);let r=t;for(let s=0;s<n.length;s++){const o="/"+n.slice(0,s+1).join("/"),c=n.slice(0,s+1).filter(f=>f.startsWith("$"));let d=r.children.find(f=>f.path===o);d||(d={path:o,pathVariables:c,children:[]},r.children.push(d)),r=d}}function a$(t,e,n,r){const s=r.split("/").filter(o=>o.startsWith("$"));if(n.read&&(e.read=Ba(n.read,"read",s)),n.write&&(e.write=Ba(n.write,"write",s)),n.validate&&(e.validate=Ba(n.validate,"validate",s)),n.schema){const o=DA(n.schema,n.fieldConstraints);e.validate||(e.validate=Ba(o.validate,"validate",s));for(const[c,d]of Object.entries(o.children)){const f=`${r}/${c}`;let p=e.children.find(g=>g.path===f);if(p||(p={path:f,pathVariables:s,children:[]},e.children.push(p)),p.validate=Ba(d.validate,"validate",s),"children"in d&&d.children)for(const[g,b]of Object.entries(d.children)){const v=`${f}/${g}`;let w=p.children.find(_=>_.path===v);w||(w={path:v,pathVariables:s,children:[]},p.children.push(w)),w.validate=Ba(b.validate,"validate",s)}}}if(n.indexOn){const o=r.split("/").filter(Boolean),c=o[o.length-1];if(c!=null&&c.startsWith("$")){const d="/"+o.slice(0,-1).join("/"),f=Sg(t,d);f&&(f.indexOn=n.indexOn)}}}function MA(t){const e=[];for(const[n,r]of t){const{children:s,...o}=r;if(e.push([n,o]),s){const c=Object.entries(s).map(([d,f])=>[n+d,f]);e.push(...MA(c))}}return e}function Ba(t,e,n){return CA(String(t),e,n)}function Sg(t,e){if(t.path===e)return t;for(const n of t.children){const r=Sg(n,e);if(r)return r}return null}function o$(t){return t==null?null:typeof t=="string"?{uid:t,token:{}}:{uid:t.uid,token:t.token??{}}}function l$(t){return{operation:t.operation,path:t.path,auth:o$(t.auth),mockData:t.mockData??t.data??{},...t.newData!==void 0?{newData:t.newData}:{}}}function Xp(t,e,n,r){return((n==null?void 0:n.parsed[r])??[]).map(s=>({path:t,rule:e,code:s.code,message:s.message}))}function fy(t,e){const n=[...Xp(t.path,".read",t.read,e),...Xp(t.path,".write",t.write,e),...Xp(t.path,".validate",t.validate,e)];for(const r of t.children)n.push(...fy(r,e));return n}class c${constructor(e){G(this,"definition");this.definition=e}compile(){return s$(this.definition.paths)}toJSON(){return e$(this.compile())}check(){try{const e=this.compile(),n=fy(e,"errors"),r=fy(e,"warnings");return{ok:n.length===0,errors:n,warnings:r}}catch(e){return{ok:!1,errors:[{path:"/",rule:"ruleset",code:"COMPILE_ERROR",message:e instanceof Error?e.message:String(e)}],warnings:[]}}}simulate(e){return xg(this.compile(),l$(e))}}function u$(t){return new c$(t)}function d$(t){const e=t;return typeof e.toJSON=="function"&&typeof e.simulate=="function"&&typeof e.check=="function"}function f$(t){const e=t;return typeof e=="object"&&e!==null&&"rules"in e&&!("paths"in e)&&typeof e.toJSON!="function"}class em{constructor(e){G(this,"doc");this.doc=e}lint(){const e=this.doc.check();return[...e.errors.map(n=>US(n,"error")),...e.warnings.map(n=>US(n,"warning"))]}runOne(e){const n=this.doc.simulate({operation:e.operation,path:e.path,auth:e.auth??null,...e.data!==void 0?{data:e.data}:{},...e.newData!==void 0?{newData:e.newData}:{}});if(!n.success)return{case:e,...e.description!==void 0?{description:e.description}:{},expectation:e.expectation,decision:"UNSUPPORTED",passed:!1,unsupported:!0,matchedPath:e.path,matchedRule:e.operation,reason:n.error.message};const r=n.data,s=r.unsupported===!0,o=s?"UNSUPPORTED":r.allowed?"ALLOW":"DENY",c=!s&&o===e.expectation;return{case:e,...e.description!==void 0?{description:e.description}:{},expectation:e.expectation,decision:o,passed:c,unsupported:s,matchedPath:r.matchedPath,matchedRule:r.matchedRule,reason:r.reason}}simulate(e){const n=e.map(c=>this.runOne(c));let r=0,s=0,o=0;for(const c of n)c.unsupported?o++:c.passed?r++:s++;return{passed:r,failed:s,unsupported:o,cases:n}}explain(e){const n=this.runOne(e);return{decision:n.decision,expectation:n.expectation,passed:n.passed,unsupported:n.unsupported,matchedPath:n.matchedPath,matchedRule:n.matchedRule,reason:n.reason}}toJSON(){return this.doc.toJSON()}}function h$(t){return t==null?null:typeof t=="string"?{uid:t,token:{}}:{uid:t.uid,token:t.token??{}}}class p${constructor(e){G(this,"json");G(this,"compiled");this.json=e,this.compiled=OA(e)}toJSON(){return this.json}compile(){return this.compiled}check(){return{ok:!0,errors:[],warnings:[]}}simulate(e){return xg(this.compiled,{operation:e.operation,path:e.path,auth:h$(e.auth),mockData:e.mockData??e.data??{},...e.newData!==void 0?{newData:e.newData}:{}})}}function m$(t){return d$(t)?new em(t):f$(t)?new em(new p$(t)):new em(u$(t))}const y$=new Set(["__proto__","prototype","constructor"]);function et(t){if(t===""||t==="/")return[];const e=t.split("/").filter(n=>n.length>0);for(const n of e)if(y$.has(n))throw new Error(`Invalid RTDB path segment '${n}': the keys __proto__, prototype, and constructor are reserved and cannot appear in a path.`);return e}function rn(t){return t.length===0?"/":"/"+t.join("/")}function Ps(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(n=>Ps(n));const e={};for(const[n,r]of Object.entries(t))e[n]=Ps(r);return e}function qS(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Qa(t,e){if(Object.is(t,e))return!0;if(Array.isArray(t)||Array.isArray(e))return!Array.isArray(t)||!Array.isArray(e)||t.length!==e.length?!1:t.every((s,o)=>Qa(s,e[o]));if(!qS(t)||!qS(e))return!1;const n=Object.keys(t),r=Object.keys(e);return n.length!==r.length?!1:n.every(s=>s in e&&Qa(t[s],e[s]))}class g${constructor(){G(this,"root",{})}snapshot(){return Ps(this.root)}restore(e){this.root=Ps(e)}read(e){const n=et(e);let r=this.root;for(const s of n){if(r===null||typeof r!="object"||Array.isArray(r))return null;const o=r;if(!Object.hasOwn(o,s))return null;r=o[s]}return Ps(r)}write(e,n){const r=et(e),s=this.read(e);if(r.length===0)return n===null?(this.root={},s):(this.root=Ps(n),s);(this.root===null||typeof this.root!="object"||Array.isArray(this.root))&&(this.root={});let o=this.root;for(let d=0;d<r.length-1;d++){const f=r[d],p=Object.hasOwn(o,f)?o[f]:void 0;if(p==null||typeof p!="object"||Array.isArray(p)){const g={};o[f]=g,o=g}else o=p}const c=r[r.length-1];return n===null?(delete o[c],this.trim(r)):o[c]=Ps(n),s}multiUpdate(e){const r=Object.entries(e).map(([o,c])=>({path:rn(et(o)),value:c}));for(let o=0;o<r.length;o++)for(let c=o+1;c<r.length;c++){const d=r[o].path,f=r[c].path;if(d===f)throw new Error(`multi-path update: duplicate path '${d}'.`);const p=d==="/"?"/":d+"/",g=f==="/"?"/":f+"/";if(d!=="/"&&f.startsWith(p))throw new Error(`multi-path update: '${f}' is a descendant of '${d}'.`);if(f!=="/"&&d.startsWith(g))throw new Error(`multi-path update: '${d}' is a descendant of '${f}'.`)}const s=[];for(const{path:o,value:c}of r){const d=this.write(o,c);s.push({path:o,prior:d})}return s}shallowUpdate(e,n){const r=[],s=et(e);for(const[o,c]of Object.entries(n)){const d=[...s,...et(o)],f=rn(d),p=this.write(f,c);r.push({path:f,prior:p})}return r}trim(e){if(!(this.root===null||typeof this.root!="object"||Array.isArray(this.root)))for(let n=e.length-1;n>=1;n--){const r=e.slice(0,n),s=e[n-1];let o=this.root;for(let d=0;d<r.length-1;d++){const f=o[r[d]];if(f==null||typeof f!="object"||Array.isArray(f))return;o=f}const c=o[s];if(c!==void 0&&typeof c=="object"&&c!==null&&!Array.isArray(c)&&Object.keys(c).length===0){delete o[s];continue}return}}}const FS="-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz";let zS=0;const Ai=new Array(12).fill(0);function b$(t=Date.now()){const e=t===zS;zS=t;const n=new Array(8);let r=t;for(let o=7;o>=0;o--)n[o]=FS.charAt(r%64),r=Math.floor(r/64);if(r!==0)throw new Error("RTDB push-id: timestamp overflow.");let s=n.join("");if(e){let o;for(o=11;o>=0&&Ai[o]===63;o--)Ai[o]=0;if(o<0)for(let c=0;c<12;c++)Ai[c]=Math.floor(Math.random()*64);else Ai[o]=(Ai[o]??0)+1}else for(let o=0;o<12;o++)Ai[o]=Math.floor(Math.random()*64);for(let o=0;o<12;o++)s+=FS.charAt(Ai[o]);if(s.length!==20)throw new Error(`RTDB push-id: bad length ${s.length}.`);return s}function v$(t){return t===null||typeof t!="object"?!1:t[".sv"]==="timestamp"}function w$(t){if(t===null||typeof t!="object")return!1;const e=t[".sv"];return e!==null&&typeof e=="object"&&typeof e.increment=="number"}function vr(t,e,n){if(v$(t))return e;if(w$(t)){const o=t[".sv"].increment;return(typeof n=="number"?n:0)+o}if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map((o,c)=>vr(o,e,Array.isArray(n)?n[c]:void 0));const r=n!==null&&typeof n=="object"&&!Array.isArray(n)?n:void 0,s={};for(const[o,c]of Object.entries(t))s[o]=vr(c,e,r?r[o]:void 0);return s}function ji(){const t=new Error("PERMISSION_DENIED: Permission denied");return t.code="PERMISSION_DENIED",t}class x${constructor(){G(this,"compiled",null)}setRules(e){if(e===null){this.compiled=null;return}this.compiled=OA(e)}hasRules(){return this.compiled!==null}check(e,n,r){return this.evaluate(e,n,r).check}evaluate(e,n,r){if(this.compiled===null)return{check:"allow",reasons:["No RTDB rules loaded; default allow."]};const s=r.auth===null?null:{uid:r.auth.uid,token:r.auth.token??{}},o=xg(this.compiled,{operation:e,path:n==="/"?"/":n,auth:s,mockData:r.mockData,newData:r.newData,updates:r.updates});return o.success?o.data.unsupported?{check:"unsupported",reasons:[`${o.data.matchedPath} ${e} UNSUPPORTED: ${o.data.reason}`],matchedPath:o.data.matchedPath,matchedRule:o.data.matchedRule,reason:o.data.reason,pathVariableBindings:o.data.pathVariableBindings}:{check:o.data.allowed?"allow":"deny",reasons:[`${o.data.matchedPath} ${e} ${o.data.allowed?"ALLOW":"DENY"}: ${o.data.reason}`],matchedPath:o.data.matchedPath,matchedRule:o.data.matchedRule,reason:o.data.reason,pathVariableBindings:o.data.pathVariableBindings}:o.error.code==="NO_MATCHING_RULE"?{check:"no-rule",reasons:[o.error.message],errorCode:o.error.code,errorMessage:o.error.message}:{check:"no-rule",reasons:[o.error.message],errorCode:o.error.code,errorMessage:o.error.message}}}function LA(t,e){if(t===e)return 0;if(t===null)return-1;if(e===null)return 1;const n=PS(t),r=PS(e);return n!==r?n-r:typeof t=="number"&&typeof e=="number"?t<e?-1:t>e?1:0:typeof t=="boolean"&&typeof e=="boolean"?t===e?0:t?1:-1:typeof t=="string"&&typeof e=="string"?t<e?-1:t>e?1:0:0}function PS(t){return t===null?0:typeof t=="boolean"?1:typeof t=="number"?2:typeof t=="string"?3:4}const S$=/^-?(0*)\d{1,10}$/,_$=-2147483648,E$=2147483647;function VS(t){if(S$.test(t)){const e=Number(t);if(e>=_$&&e<=E$)return e}return null}function wd(t,e){if(t===e)return 0;const n=VS(t),r=VS(e);return n!==null?r!==null?n-r===0?t.length-e.length:n-r:-1:r!==null?1:t<e?-1:1}function hy(t,e,n){const r=t??{kind:"key"};switch(r.kind){case"key":return e;case"value":return n;case"child":{if(n===null||typeof n!="object"||Array.isArray(n))return null;const s=r.path.split("/").filter(c=>c.length>0);let o=n;for(const c of s){if(o===null||typeof o!="object"||Array.isArray(o))return null;o=o[c]??null}return o}}}function qa(t,e){if(t===null||typeof t!="object"||Array.isArray(t))return[];let r=Object.entries(t).map(([o,c])=>({key:o,value:c}));const s=(e.orderBy??{kind:"key"}).kind==="key";r.sort((o,c)=>{if(s)return wd(o.key,c.key);const d=hy(e.orderBy,o.key,o.value),f=hy(e.orderBy,c.key,c.value),p=LA(d,f);return p!==0?p:wd(o.key,c.key)});for(const o of e.bounds)r=r.filter(c=>A$(o,c,e.orderBy));if(e.limit){const o=e.limit.n;e.limit.kind==="limitToFirst"?r=r.slice(0,o):r=o>=r.length?r:r.slice(r.length-o)}return r}function A$(t,e,n){const s=(n??{kind:"key"}).kind==="key"?wd(e.key,String(t.value)):LA(hy(n,e.key,e.value),t.value),o=c=>wd(e.key,c);switch(t.kind){case"startAt":return s>0?!0:s<0?!1:t.key===void 0||o(t.key)>=0;case"startAfter":return s>0?!0:s<0||t.key===void 0?!1:o(t.key)>0;case"endAt":return s<0?!0:s>0?!1:t.key===void 0||o(t.key)<=0;case"endBefore":return s<0?!0:s>0||t.key===void 0?!1:o(t.key)<0;case"equalTo":return s!==0?!1:t.key===void 0||o(t.key)===0}}const j$=/[\[\].#$/\u0000-\u001F\u007F]/;function k$(t){return t.length!==0&&!j$.test(t)}function C$(t){return typeof t=="number"&&(Number.isNaN(t)||t===1/0||t===-1/0)}function N$(t){return t===".priority"||t===".value"||t===".sv"}function O$(t,e){py(t,e,"set")}function py(t,e,n){if(t===void 0)throw new Error(`${n} failed: value argument contains undefined in property '${e}'`);if(typeof t=="function")throw new Error(`${n} failed: value argument contains a function in property '${e}'`);if(C$(t))throw new Error(`${n} failed: value argument contains ${String(t)} in property '${e}'`);if(!(t===null||typeof t!="object")){if(Array.isArray(t)){for(let r=0;r<t.length;r++){if(!(r in t))continue;const s=t[r];s!==void 0&&py(s,`${e}/${r}`,n)}return}for(const[r,s]of Object.entries(t)){if(!N$(r)&&!k$(r))throw new Error(`${n} failed: value argument contains an invalid key (${r}) in path ${e}. Keys must be non-empty strings and can't contain ".", "#", "$", "/", "[", or "]"`);py(s,`${e}/${r}`,n)}}}function Us(t,e){return O$(t,e),my(t)}function my(t){if(t==null)return null;if(typeof t!="object")return t;if(Array.isArray(t)){const n={};for(let r=0;r<t.length;r++){if(!(r in t))continue;const s=my(t[r]);s!==null&&(n[String(r)]=s)}return Object.keys(n).length===0?null:n}const e={};for(const[n,r]of Object.entries(t)){if(n===".sv"){e[n]=r;continue}const s=my(r);s!==null&&(e[n]=s)}return Object.keys(e).length===0?null:e}function zu(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(c=>zu(c));const e=t,n=Object.keys(e);let r=n.length>0,s=0;for(const c of n)if(/^(0|[1-9]\d*)$/.test(c))s=Math.max(s,Number(c));else{r=!1;break}if(r&&s<2*n.length){const c=[];for(let d=0;d<=s;d++){const f=e[String(d)];c[d]=f===void 0?null:zu(f)}return c}const o={};for(const[c,d]of Object.entries(e))o[c]=zu(d);return o}function Jr(t){return t==="unsupported"?"unsupported":"deny"}class R${constructor(e){G(this,"tree",new g$);G(this,"rules",new x$);G(this,"activeRules",null);G(this,"valueListeners",new Set);G(this,"childListeners",new Set);G(this,"nextId",0);G(this,"writeSubscribers",new Set);G(this,"sandbox");this.sandbox=e}emitRtdbEvent(e,n,r,s={}){if(this.sandbox)try{Vs(this.sandbox,$d({service:"rtdb",op:n,path:r,auth:e,before:s.before,after:s.after,detail:s.detail}),{service:"rtdb"})}catch{}}nextListenerId(){return this.nextId+=1,`rtdb-listener-${this.nextId.toString(36)}`}nextGroupId(e){return this.nextId+=1,`rtdb-${e}-${this.nextId.toString(36)}`}emitOperation(e,n,r,s,o,c={}){if(this.sandbox)try{Vs(this.sandbox,FE({service:"rtdb",method:n,path:br(r),auth:e,result:s,origin:c.origin??"user",durationMs:c.durationMs,reasons:o==null?void 0:o.reasons,rules:o?{engine:"rtdb",matchedPath:o.matchedPath,matchedRule:o.matchedRule,pathVariableBindings:o.pathVariableBindings,reason:o.reason,errorCode:o.errorCode}:void 0,request:c.request,resourceBefore:c.resourceBefore,resourceAfter:c.resourceAfter,groupId:c.groupId,groupKind:c.groupKind,triggeredBy:c.triggeredBy,detail:c.detail,at:c.at}),{service:"rtdb"})}catch{}}emitCommit(e,n,r,s={}){if(this.sandbox)try{Vs(this.sandbox,CI({service:"rtdb",method:n,path:br(r),auth:e,data:s.data,priorState:s.priorState,nextState:s.nextState,groupId:s.groupId,groupKind:s.groupKind,replay:s.replay,detail:s.detail}),{service:"rtdb"})}catch{}}emitListener(e,n,r,s={}){if(this.sandbox)try{Vs(this.sandbox,NI({service:"rtdb",phase:e,listenerId:n.id,target:{kind:s.event??"value",path:br(n.path)},auth:r,result:s.result,size:s.size,sample:s.sample,reason:s.reason,error:s.error,triggeredBy:s.triggeredBy,detail:s.detail}),{service:"rtdb"})}catch{}}setData(e){this.tree.restore({});for(const[n,r]of Object.entries(e)){const s=Us(vr(r,Date.now()),n==="/"?"":n);this.tree.write(n,s)}this.notifyWrite()}setRules(e){this.rules.setRules(e),this.activeRules=e===null?null:structuredClone(e)}getActiveRules(){return this.activeRules===null?null:structuredClone(this.activeRules)}snapshotState(){return this.tree.snapshot()}adminGet(e){const n=this.tree.read(e);return this.emitOperation(null,"get",e,"not-applicable",void 0,{origin:"admin",resourceBefore:{data:n,exists:n!==null}}),n}adminGetQuery(e,n){const r=qa(this.tree.read(e),n);return this.emitOperation(null,"get",e,"not-applicable",void 0,{origin:"admin",request:{query:n},resourceBefore:{data:Au(r),exists:r.length>0}}),r}adminSet(e,n){const r=Date.now(),s=this.tree.read(e),o=Us(vr(n,r,s),e==="/"?"":e);this.emitOperation(null,o===null?"remove":"set",e,"not-applicable",void 0,{origin:"admin",request:{data:n,resourceData:n},resourceBefore:{data:s,exists:s!==null},resourceAfter:{data:o,exists:o!==null}});const c=this.snapshotChildListenerParents();this.tree.write(e,o),this.fanOut([e]),this.fanOutChildren(c);const d=this.tree.read(e),f=d===null?"remove":"set";this.emitCommit(null,f,e,{data:n,priorState:s,nextState:d,replay:{requestTime:r},detail:{admin:!0}}),this.notifyWrite()}adminUpdate(e,n){const r=Date.now(),s=this.tree.read(e),o=Object.keys(n).some(g=>g.includes("/")),c=this.snapshotChildListenerParents();if(o){const g={};for(const[v,w]of Object.entries(n)){const _=rn([...et(e),...et(v)]);g[_]=Us(vr(w,r,this.tree.read(_)),_)}this.emitOperation(null,"update",e,"not-applicable",void 0,{origin:"admin",request:{data:n,resourceData:n},resourceBefore:{data:s,exists:s!==null},detail:{admin:!0,multiPath:!0,paths:Object.keys(g)}}),this.tree.multiUpdate(g),this.fanOut(Object.keys(g)),this.fanOutChildren(c);const b=this.tree.read(e);this.emitCommit(null,"update",e,{data:n,priorState:s,nextState:b,replay:{requestTime:r},detail:{admin:!0,multiPath:!0,paths:Object.keys(g)}}),this.notifyWrite();return}const d={},f=[];for(const[g,b]of Object.entries(n)){const v=rn([...et(e),...et(g)]);f.push(v),d[g]=Us(vr(b,r,this.tree.read(v)),v)}this.emitOperation(null,"update",e,"not-applicable",void 0,{origin:"admin",request:{data:n,resourceData:n},resourceBefore:{data:s,exists:s!==null},detail:{admin:!0,multiPath:!1,keys:Object.keys(d)}}),this.tree.shallowUpdate(e,d),this.fanOut(f),this.fanOutChildren(c);const p=this.tree.read(e);this.emitCommit(null,"update",e,{data:n,priorState:s,nextState:p,replay:{requestTime:r},detail:{admin:!0,multiPath:!1,keys:Object.keys(d)}}),this.notifyWrite()}adminRemove(e){this.adminSet(e,null)}get(e,n){const r=Date.now(),s=this.tree.read(n),o=this.rules.evaluate("read",n==="/"?"/":n,{auth:e,mockData:this.tree.snapshot()});if(o.check!=="allow")throw this.emitOperation(e,"get",n,Jr(o.check),o,{at:r,durationMs:Date.now()-r,resourceBefore:{data:s,exists:s!==null}}),ji();return this.emitOperation(e,"get",n,"allow",o,{at:r,durationMs:Date.now()-r,resourceBefore:{data:s,exists:s!==null}}),this.tree.read(n)}set(e,n,r){this.setInternal(e,n,r,"set")}setInternal(e,n,r,s){const o=Date.now(),c=vr(r,o,this.tree.read(n)),d=Us(c,n==="/"?"":n),f=this.tree.read(n),p=Date.now(),g=this.rules.evaluate("write",n==="/"?"/":n,{auth:e,mockData:this.tree.snapshot(),newData:d}),b={data:f,exists:f!==null},v={data:d,exists:d!==null};if(g.check!=="allow")throw this.emitOperation(e,s,n,Jr(g.check),g,{at:p,durationMs:Date.now()-p,request:{data:r,resourceData:r},resourceBefore:b,resourceAfter:v}),ji();this.emitOperation(e,s,n,"allow",g,{at:p,durationMs:Date.now()-p,request:{data:r,resourceData:r},resourceBefore:b,resourceAfter:v});const w=this.snapshotChildListenerParents();this.tree.write(n,d),this.fanOut([n]),this.fanOutChildren(w);const _=this.tree.read(n),k=_===null?"remove":s;this.emitCommit(e,k,n,{data:r,priorState:f,nextState:_,replay:{requestTime:o}}),this.emitRtdbEvent(e,k,br(n),{before:f,after:_}),this.notifyWrite()}remove(e,n){this.setInternal(e,n,null,"remove")}update(e,n,r){const s=Date.now();if(Object.keys(r).some(w=>w.includes("/"))){const w=this.nextGroupId("update"),_={};for(const[F,D]of Object.entries(r)){const C=[...et(n),...et(F)],L=rn(C);_[L]=Us(vr(D,s,this.tree.read(L)),L)}const k=this.tree.snapshot(),I=Object.entries(_).map(([F,D])=>({path:F,value:D}));for(const[F,D]of Object.entries(_)){const C=Date.now(),L=this.tree.read(F),U=this.rules.evaluate("write",F,{auth:e,mockData:k,newData:D,updates:I}),H={at:C,durationMs:Date.now()-C,origin:"batch",request:{data:D,resourceData:D},resourceBefore:{data:L,exists:L!==null},resourceAfter:{data:D,exists:D!==null},groupId:w,groupKind:"batch",detail:{multiPath:!0,rootPath:br(n)}};if(U.check!=="allow")throw this.emitOperation(e,"update",F,Jr(U.check),U,H),ji();this.emitOperation(e,"update",F,"allow",U,H)}const N=this.tree.read(n),R=this.snapshotChildListenerParents();this.tree.multiUpdate(_),this.fanOut(Object.keys(_)),this.fanOutChildren(R);const M=this.tree.read(n);this.emitCommit(e,"update",n,{data:r,priorState:N,nextState:M,groupId:w,groupKind:"batch",replay:{requestTime:s},detail:{multiPath:!0,paths:Object.keys(_)}}),this.emitRtdbEvent(e,"update",br(n),{after:_,detail:{multiPath:!0,paths:Object.keys(_)}}),this.notifyWrite();return}const c={};for(const[w,_]of Object.entries(r)){const k=rn([...et(n),...et(w)]);c[w]=Us(vr(_,s,this.tree.read(k)),k)}const d=this.tree.snapshot(),f=[],p=this.nextGroupId("update");for(const[w,_]of Object.entries(c)){const k=rn([...et(n),...et(w)]);f.push(k);const I=Date.now(),N=this.tree.read(k),R=this.rules.evaluate("write",k,{auth:e,mockData:d,newData:_}),M={at:I,durationMs:Date.now()-I,origin:"batch",request:{data:_,resourceData:_},resourceBefore:{data:N,exists:N!==null},resourceAfter:{data:_,exists:_!==null},groupId:p,groupKind:"batch",detail:{multiPath:!1,rootPath:br(n),key:w}};if(R.check!=="allow")throw this.emitOperation(e,"update",k,Jr(R.check),R,M),ji();this.emitOperation(e,"update",k,"allow",R,M)}const g=this.tree.read(n),b=this.snapshotChildListenerParents();this.tree.shallowUpdate(n,c),this.fanOut(f),this.fanOutChildren(b);const v=this.tree.read(n);this.emitCommit(e,"update",n,{data:r,priorState:g,nextState:v,groupId:p,groupKind:"batch",replay:{requestTime:s},detail:{multiPath:!1,keys:Object.keys(c)}}),this.emitRtdbEvent(e,"update",br(n),{after:c,detail:{multiPath:!1,keys:Object.keys(c)}}),this.notifyWrite()}onValue(e,n,r,s){const o=Date.now(),c=this.rules.evaluate("read",n==="/"?"/":n,{auth:e,mockData:this.tree.snapshot()});if(c.check!=="allow")throw this.emitOperation(e,"listen",n,Jr(c.check),c,{at:o,durationMs:Date.now()-o,request:s?{query:s}:void 0,origin:"listener"}),this.emitListener("errored",{id:this.nextListenerId(),path:n},e,{event:"value",result:"deny",error:{code:"PERMISSION_DENIED",message:"PERMISSION_DENIED: Permission denied",reasons:c.reasons}}),ji();return this.attachValueListener(e,n,r,s,{origin:"listener",result:"allow",evaluation:c,at:o})}adminOnValue(e,n,r){return this.attachValueListener(null,e,n,r,{origin:"admin",result:"not-applicable",evaluation:void 0,at:Date.now()})}attachValueListener(e,n,r,s,o){const{at:c}=o,d=this.nextListenerId();this.emitOperation(e,"listen",n,o.result,o.evaluation,{at:c,durationMs:Date.now()-c,request:s?{query:s}:void 0,origin:o.origin});const f={id:d,auth:e,cb:r,path:n,query:s};if(this.valueListeners.add(f),this.emitListener("attach",f,e,{event:"value",result:"allow",detail:s?{query:s}:void 0}),s){const p=qa(this.tree.read(n),s);f.lastWindow=p;const g={val:Au(p),exists:p.length>0,key:this.keyForPath(n)};try{r(g),this.emitListener("delivery",f,e,{event:"value",size:p.length,sample:g.val,detail:{initial:!0,query:!0}})}catch(b){this.emitListener("errored",f,e,{event:"value",result:"error",error:{message:b instanceof Error?b.message:String(b)},detail:{initial:!0,query:!0}})}}else{const p=this.makeSnap(n);f.lastValue=p.val;try{r(p),this.emitListener("delivery",f,e,{event:"value",size:p.exists?1:0,sample:p.val,detail:{initial:!0}})}catch(g){this.emitListener("errored",f,e,{event:"value",result:"error",error:{message:g instanceof Error?g.message:String(g)},detail:{initial:!0}})}}return()=>{this.valueListeners.delete(f),this.emitListener("detach",f,e,{event:"value"})}}getQuery(e,n,r){const s=Date.now(),o=this.rules.evaluate("read",n==="/"?"/":n,{auth:e,mockData:this.tree.snapshot()});if(o.check!=="allow")throw this.emitOperation(e,"get",n,Jr(o.check),o,{at:s,durationMs:Date.now()-s,request:{query:r}}),ji();const c=qa(this.tree.read(n),r);return this.emitOperation(e,"get",n,"allow",o,{at:s,durationMs:Date.now()-s,request:{query:r},resourceBefore:{data:Au(c),exists:c.length>0}}),c}keyForPath(e){const n=et(e);return n.length===0?null:n[n.length-1]}makeSnap(e){const n=this.tree.read(e),r=n!==null,s=et(e),o=s.length===0?null:s[s.length-1];return{val:n,exists:r,key:o}}fanOut(e){if(this.valueListeners.size===0)return;const n=e.map(r=>rn(et(r)));for(const r of this.valueListeners){const s=rn(et(r.path));if(!n.some(f=>{if(f===s)return!0;const p=s==="/"?"/":s+"/",g=f==="/"?"/":f+"/";return!!(s==="/"||f.startsWith(p)||s.startsWith(g))}))continue;if(r.query){const f=qa(this.tree.read(r.path),r.query);if(T$(r.lastWindow??[],f)){this.emitListener("suppressed",r,r.auth,{event:"value",reason:"no-op",detail:{query:!0}});continue}r.lastWindow=f;const p={val:Au(f),exists:f.length>0,key:this.keyForPath(r.path)};this.emitListener("delivery",r,r.auth,{event:"value",size:f.length,sample:p.val,detail:{query:!0}});try{r.cb(p)}catch(g){this.emitListener("errored",r,r.auth,{event:"value",result:"error",error:{message:g instanceof Error?g.message:String(g)},detail:{query:!0}})}continue}const c=this.makeSnap(r.path),d=r.lastValue;if(d!==void 0&&Qa(d,c.val)){this.emitListener("suppressed",r,r.auth,{event:"value",reason:"no-op"});continue}r.lastValue=c.val,this.emitListener("delivery",r,r.auth,{event:"value",size:c.exists?1:0,sample:c.val});try{r.cb(c)}catch(f){this.emitListener("errored",r,r.auth,{event:"value",result:"error",error:{message:f instanceof Error?f.message:String(f)}})}}}runTransaction(e,n,r,s){const o=(s==null?void 0:s.applyLocally)!==!1,c=et(n),d=c.length===0?null:c[c.length-1],f=this.tree.read(n),p=f===null?null:zu(Ps(f)),g=r(p),b=this.nextGroupId("transaction");if(g===void 0)return this.emitOperation(e,"transaction",n,"not-applicable",void 0,{origin:"transaction",groupId:b,groupKind:"transaction",resourceBefore:{data:f,exists:f!==null},detail:{committed:!1,aborted:!0}}),{committed:!1,val:f,key:d};const v=Date.now(),w=Us(vr(g,v,f),n==="/"?"":n);if(o){const I=this.tree.snapshot();this.tree.write(n,w),this.fanOut([n]);const N=Date.now(),R=this.rules.evaluate("write",n==="/"?"/":n,{auth:e,mockData:I,newData:w});if(R.check!=="allow")throw this.emitOperation(e,"transaction",n,Jr(R.check),R,{at:N,durationMs:Date.now()-N,origin:"transaction",request:{data:g,resourceData:g},resourceBefore:{data:f,exists:f!==null},resourceAfter:{data:w,exists:w!==null},groupId:b,groupKind:"transaction"}),this.tree.restore(I),this.fanOut([n]),HS();return this.emitOperation(e,"transaction",n,"allow",R,{at:N,durationMs:Date.now()-N,origin:"transaction",request:{data:g,resourceData:g},resourceBefore:{data:f,exists:f!==null},resourceAfter:{data:w,exists:w!==null},groupId:b,groupKind:"transaction"}),this.emitCommit(e,"transaction",n,{data:g,priorState:f,nextState:w,groupId:b,groupKind:"transaction",replay:{requestTime:v},detail:{committed:!0,applyLocally:!0}}),this.emitRtdbEvent(e,"transaction",br(n),{before:f,after:w,detail:{committed:!0}}),this.notifyWrite(),{committed:!0,val:w,key:d}}const _=Date.now(),k=this.rules.evaluate("write",n==="/"?"/":n,{auth:e,mockData:this.tree.snapshot(),newData:w});if(k.check!=="allow")throw this.emitOperation(e,"transaction",n,Jr(k.check),k,{at:_,durationMs:Date.now()-_,origin:"transaction",request:{data:g,resourceData:g},resourceBefore:{data:f,exists:f!==null},resourceAfter:{data:w,exists:w!==null},groupId:b,groupKind:"transaction"}),HS();return this.emitOperation(e,"transaction",n,"allow",k,{at:_,durationMs:Date.now()-_,origin:"transaction",request:{data:g,resourceData:g},resourceBefore:{data:f,exists:f!==null},resourceAfter:{data:w,exists:w!==null},groupId:b,groupKind:"transaction"}),this.tree.write(n,w),this.fanOut([n]),this.emitCommit(e,"transaction",n,{data:g,priorState:f,nextState:w,groupId:b,groupKind:"transaction",replay:{requestTime:v},detail:{committed:!0,applyLocally:!1}}),this.emitRtdbEvent(e,"transaction",br(n),{before:f,after:w,detail:{committed:!0}}),{committed:!0,val:w,key:d}}onChild(e,n,r,s,o){const c=this.nextListenerId(),d=Date.now(),f=this.rules.evaluate("read",r==="/"?"/":r,{auth:e,mockData:this.tree.snapshot()});if(f.check!=="allow")throw this.emitOperation(e,"listen",r,Jr(f.check),f,{at:d,durationMs:Date.now()-d,origin:"listener",detail:{event:n}}),this.emitListener("errored",{id:c,path:r},e,{event:n,result:"deny",error:{code:"PERMISSION_DENIED",message:"PERMISSION_DENIED: Permission denied",reasons:f.reasons}}),ji();this.emitOperation(e,"listen",r,"allow",f,{at:d,durationMs:Date.now()-d,origin:"listener",detail:{event:n}});const p={id:c,auth:e,event:n,path:r,cb:s,spec:o};if(this.childListeners.add(p),this.emitListener("attach",p,e,{event:n,result:"allow",detail:o?{query:o}:void 0}),o){const g=qa(this.tree.read(r),o);if(p.lastWindow=g,n==="child_added")for(const{key:b,value:v}of g){this.emitListener("delivery",p,e,{event:n,size:1,sample:{key:b,val:v},detail:{initial:!0,query:!0}});try{s({key:b,val:v})}catch(w){this.emitListener("errored",p,e,{event:n,result:"error",error:{message:w instanceof Error?w.message:String(w)},detail:{initial:!0,query:!0}})}}}else if(n==="child_added")for(const{key:g,val:b}of this.directChildren(r)){this.emitListener("delivery",p,e,{event:n,size:1,sample:{key:g,val:b},detail:{initial:!0}});try{s({key:g,val:b})}catch(v){this.emitListener("errored",p,e,{event:n,result:"error",error:{message:v instanceof Error?v.message:String(v)},detail:{initial:!0}})}}return()=>{this.childListeners.delete(p),this.emitListener("detach",p,e,{event:n})}}off(e,n,r){const s=rn(et(e));if(n===void 0||n==="value")for(const d of[...this.valueListeners])rn(et(d.path))===s&&(r!==void 0&&d.cb!==r||(this.valueListeners.delete(d),this.emitListener("detach",d,d.auth,{event:"value"})));const c=n===void 0?["child_added","child_changed","child_removed","child_moved"]:n==="value"?[]:[n];if(c.length>0)for(const d of[...this.childListeners])c.includes(d.event)&&rn(et(d.path))===s&&(r!==void 0&&d.cb!==r||(this.childListeners.delete(d),this.emitListener("detach",d,d.auth,{event:d.event})))}directChildren(e){const n=this.tree.read(e);if(n===null||typeof n!="object"||Array.isArray(n))return[];const r=[];for(const[s,o]of Object.entries(n))r.push({key:s,val:o});return r}snapshotChildListenerParents(){const e=new Map;if(this.childListeners.size===0)return e;for(const n of this.childListeners){const r=rn(et(n.path));if(e.has(r))continue;const s=new Map;for(const{key:o,val:c}of this.directChildren(r))s.set(o,c);e.set(r,s)}return e}fanOutChildren(e){if(this.childListeners.size===0)return;const n=new Map;for(const r of this.childListeners){if(r.spec){this.fanOutQueryChild(r);continue}const s=rn(et(r.path)),o=n.get(s)??[];o.push(r),n.set(s,o)}for(const[r,s]of n){const o=e.get(r)??new Map,c=new Map;for(const{key:g,val:b}of this.directChildren(r))c.set(g,b);const d=[],f=[],p=[];for(const[g,b]of c)o.has(g)?Qa(o.get(g),b)||f.push({key:g,val:b}):d.push({key:g,val:b});for(const[g,b]of o)c.has(g)||p.push({key:g,val:b});for(const g of s){let b;switch(g.event){case"child_added":b=d;break;case"child_changed":b=f;break;case"child_removed":b=p;break;case"child_moved":b=[];break}for(const v of b){this.emitListener("delivery",g,g.auth,{event:g.event,size:1,sample:v});try{g.cb(v)}catch(w){this.emitListener("errored",g,g.auth,{event:g.event,result:"error",error:{message:w instanceof Error?w.message:String(w)}})}}}}}fanOutQueryChild(e){const n=e.lastWindow??[],r=qa(this.tree.read(e.path),e.spec);e.lastWindow=r;const s=new Map(n.map(d=>[d.key,d.value])),o=new Map(r.map(d=>[d.key,d.value]));let c=[];switch(e.event){case"child_added":for(const{key:d,value:f}of r)s.has(d)||c.push({key:d,val:f});break;case"child_changed":for(const{key:d,value:f}of r)s.has(d)&&!Qa(s.get(d),f)&&c.push({key:d,val:f});break;case"child_removed":for(const{key:d,value:f}of n)o.has(d)||c.push({key:d,val:f});break;case"child_moved":c=[];break}for(const d of c){this.emitListener("delivery",e,e.auth,{event:e.event,size:1,sample:d,detail:{query:!0}});try{e.cb(d)}catch(f){this.emitListener("errored",e,e.auth,{event:e.event,result:"error",error:{message:f instanceof Error?f.message:String(f)},detail:{query:!0}})}}}exportTree(){return this.tree.snapshot()}restoreTree(e){const n=this.snapshotChildListenerParents();this.tree.restore(e??{}),this.fanOut(["/"]),this.fanOutChildren(n)}subscribeWrites(e){return this.writeSubscribers.add(e),()=>{this.writeSubscribers.delete(e)}}notifyWrite(){if(this.writeSubscribers.size!==0)for(const e of this.writeSubscribers)try{e()}catch{}}mintKey(){return b$()}listenerCount(){return this.valueListeners.size}childListenerCount(){return this.childListeners.size}}function br(t){return rn(et(t))}function HS(){return new Error("permission_denied")}function Au(t){if(t.length===0)return null;const e={};for(const{key:n,value:r}of t)e[n]=r;return e}function T$(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++){const r=t[n],s=e[n];if(r.key!==s.key||!Qa(r.value,s.value))return!1}return!0}const GS=new WeakMap;function UA(t){let e=GS.get(t);if(e)return e;e=new R$(t),GS.set(t,e);const n=e;return t.registerPersistableService("rtdb",{snapshot:()=>n.exportTree(),restore:r=>{n.restoreTree(r)},subscribe:r=>n.subscribeWrites(r),reset:()=>{n.restoreTree(null)}}),e}function D$(t){return UA(t).getActiveRules()}function KS(t){return UA(t).snapshotState()}function I$(t,e){return t==="/"?`/${e}`:`${t}/${e}`}function YS(t){return t===null?"null":Array.isArray(t)?"array":typeof t}function M$(t){const e=(t??"/").split("/").filter(Boolean);return e.length===0?"/":`/${e.join("/")}`}function L$(t,e){let n=t;for(const r of e.split("/").filter(Boolean)){if(n===null||typeof n!="object"||Array.isArray(n))return null;n=n[r]}return n??null}function $A(t,e,n,r,s){if(t===null||typeof t!="object"||Array.isArray(t))return{path:e,childCount:0,truncated:!1,children:[],schema:{},valueType:YS(t)};const o=Object.entries(t).sort(([b],[v])=>b.localeCompare(v)),c={},d=[];for(const[b,v]of o)v!==null&&typeof v=="object"&&!Array.isArray(v)?d.push([b,v]):c[b]=YS(v);const f=n>=r&&d.length>0,p=o.length>s,g=n>=r?[]:d.slice(0,s).map(([b,v])=>$A(v,I$(e,b),n+1,r,s));return{path:e,childCount:o.length,truncated:f||p,children:g,schema:c}}function U$(t,e={}){const n=M$(e.path),r=e.maxDepth??10,s=e.maxChildren??100;return $A(L$(t,n),n,0,r,s)}function BA(t){return t.children.reduce((e,n)=>e+1+BA(n),0)}function qA(t){return[{name:"rtdb_simulate_access",description:"Simulate one read, write, or validate operation against the RTDB rules and data currently loaded in the local sandbox. No production database is contacted and no prior rules-loading tool call is required.",parameters:{type:"object",properties:{operation:{type:"string",enum:["read","write","validate"]},path:{type:"string"},auth:{anyOf:[{type:"null"},{type:"object",properties:{uid:{type:"string"},claims:{type:"object"}},required:["uid"]}]},newData:{}},required:["operation","path"]},async execute(e){const n=e,r=await t.resolveSandbox(),s=D$(r);if(!s)return{ok:!1,summary:"No RTDB rules are loaded in the local sandbox.",data:{code:"NO_ACTIVE_RULES"}};const o=KS(r),c=o!==null&&typeof o=="object"&&!Array.isArray(o)?o:{},d={expectation:"ALLOW",operation:n.operation,path:n.path,auth:n.auth?{uid:n.auth.uid,token:n.auth.claims??{}}:null,data:c,...n.newData!==void 0?{newData:n.newData}:{}},f=m$(s).simulate([d]).cases[0];return{ok:!f.unsupported,summary:f.unsupported?`Simulation unsupported: ${f.reason}`:`Simulation: ${f.decision.toLowerCase()}`,data:{decision:f.decision,allowed:f.decision==="ALLOW",unsupported:f.unsupported,matchedPath:f.matchedPath,matchedRule:f.matchedRule,reason:f.reason}}}},{name:"rtdb_crawl_structure",description:"Describe the structure of the RTDB data currently loaded in the local sandbox without returning leaf values or contacting a production database.",parameters:{type:"object",properties:{path:{type:"string",description:"Root-relative path to inspect. Defaults to /."},maxDepth:{type:"number",minimum:0,description:"Maximum object depth to return. Defaults to 10."},maxChildren:{type:"number",minimum:1,description:"Maximum object children to return per node. Defaults to 100."}}},async execute(e){const n=e,r=await t.resolveSandbox(),s=U$(KS(r),n);return{ok:!0,summary:`Crawled ${BA(s)} object paths from ${s.path}`,data:s}}}]}function $$(t){const e=Wt(t),n=r=>r&&r!=="admin"?Vd(t.withAuth({uid:r.uid,token:r.claims})):bg(t);return[...WE({resolveSandbox:()=>e}),..._A({resolveDb:n}),...EA({resolveSandbox:()=>t}),...qA({resolveSandbox:()=>t})]}function B$(t){const e=new Map($$(t).map(n=>[n.name,n]));return async(n,r)=>{const s=e.get(n);if(!s)throw new z$(n);const o={signal:new AbortController().signal},c=await s.execute(r,o);return{ok:c.ok,summary:c.summary,data:c.data}}}const ZS=new WeakMap;async function q$(t,e,n){let r=ZS.get(t);return r||(r=B$(t),ZS.set(t,r)),r(e,n)}const F$=(()=>{const t=async()=>{throw new Error("SANDBOX_TOOL_NAMES: stub resolver should never be invoked")};return[...WE({resolveSandbox:t}),..._A({resolveDb:t}),...EA({resolveSandbox:t}),...qA({resolveSandbox:t})].map(e=>e.name)})();class z$ extends Error{constructor(n){super(`unknown sandbox tool: ${n}`);G(this,"tool");this.tool=n,this.name="UnknownToolError"}}const P$=500,V$=3e4,H$=2e3,G$=.5,K$=3;function Y$(t,e={}){const n=Z$(e.url),r=e.sandboxId??W$(),s=e.dispatcher??q$,o=e.toolNames??[...F$],c=e.initialReconnectDelayMs??P$,d=e.maxReconnectDelayMs??V$,f=e.noReconnect??!1,p=e.onStateChange??(()=>{}),g=e.standbyPollMs??H$,b=e.fetchImpl??($=>fetch($)),v=e.workerRelay??null;let w=null,_=!1,k=0,I=null,N=null,R=0,M={kind:"connecting"};const F=new Map;function D(){for(const $ of F.values())try{$()}catch{}F.clear()}function C($){M=$;try{p($)}catch{}}function L($){if(w&&w.readyState===WebSocket.OPEN)try{w.send(JSON.stringify($))}catch{}}function U(){if(_)return;C({kind:"connecting"});let $;try{$=new WebSocket(n)}catch(K){P(`failed to open WebSocket: ${K instanceof Error?K.message:String(K)}`);return}w=$,$.onopen=()=>{k=0;const K={type:"hello",protocol:1,tools:o,sandboxId:r,...v?{capabilities:[gL]}:{}};L(K)},$.onmessage=K=>{let W;try{W=JSON.parse(typeof K.data=="string"?K.data:"")}catch{return}if(bL(W)){if(W.type==="hello-ack"){C({kind:"connected",bridgeVersion:W.bridgeVersion});return}if(W.type==="tool-call"){H(W);return}if(W.type==="worker-op"){z(W);return}if(W.type==="worker-sub"){q(W);return}if(W.type==="worker-unsub"){const se=F.get(W.subId);if(se){F.delete(W.subId);try{se()}catch{}}return}if(W.type==="ping"){L({type:"pong",id:W.id});return}}},$.onclose=K=>{const W=K.reason||`closed (code ${K.code})`;if(w=null,D(),K.code===yL){E();return}P(W)},$.onerror=()=>{}}async function H($){let K;try{const W=await s(t,$.name,$.args??{});K={type:"tool-result",id:$.id,ok:!0,result:W}}catch(W){K={type:"tool-result",id:$.id,ok:!1,error:{code:W instanceof Error?W.name:"Error",message:W instanceof Error?W.message:String(W)}}}L(K)}async function z($){if(v)try{const K=await v.op($.op);pS(`op '${$.op.method}'`,K),L({type:"worker-res",id:$.id,ok:!0,value:K})}catch(K){const W=K.denialContext;L({type:"worker-res",id:$.id,ok:!1,error:{code:K.code??"unknown",message:K instanceof Error?K.message:String(K),...W!==void 0?{denialContext:W}:{}}})}}function q($){if(v&&!F.has($.subId))try{const K=v.subscribe($.sub,W=>{try{pS(`subscription '${$.subId}'`,W)}catch(se){L({type:"worker-snap",subId:$.subId,value:{__error:{code:se.code??"invalid-argument",message:se instanceof Error?se.message:String(se)}}});return}L({type:"worker-snap",subId:$.subId,value:W})});F.set($.subId,K)}catch(K){const W=K.denialContext;L({type:"worker-snap",subId:$.subId,value:{__error:{code:K.code??"unknown",message:K instanceof Error?K.message:String(K),...W!==void 0?{denialContext:W}:{}}}})}}function x(){try{const $=new URL(n);$.protocol=$.protocol==="wss:"?"https:":"http:";const K=$.origin;return[`${K}/__pyric/health`,`${K}/health`]}catch{return[]}}function E(){if(!_){if(f){C({kind:"disconnected",reason:"replaced by a newer sandbox peer"});return}k=0,R=0,C({kind:"standby"}),O()}}function O(){if(_)return;const $=g*(1+Math.random()*G$);N=setTimeout(()=>{N=null,T()},$)}async function T(){if(_)return;let $=null;for(const K of x())try{const W=await b(K);if(!W.ok)continue;const se=await W.json();if(typeof se.sandboxConnected=="boolean"){$=!se.sandboxConnected;break}}catch{}if(!_){if($===!0){U();return}if($===!1){R=0,O();return}if(R+=1,R>=K$){P("standby health poll unreachable");return}O()}}function P($){if(_)return;if(f){C({kind:"disconnected",reason:$});return}k+=1;const K=Math.min(c*2**(k-1),d);C({kind:"reconnecting",attempt:k,delayMs:K}),I=setTimeout(()=>{I=null,U()},K)}return U(),{disconnect(){if(_=!0,D(),I&&(clearTimeout(I),I=null),N&&(clearTimeout(N),N=null),w){try{w.close()}catch{}w=null}C({kind:"disconnected",reason:"client closed"})},state(){return M}}}function Z$(t){if(t)return t;if(typeof window<"u"){const e=window.__PYRIC_BRIDGE_URL__;if(e)return e;const n=window.location.hostname||"localhost";return`${window.location.protocol==="https:"?"wss:":"ws:"}//${n}:${fS}${hS}`}return`ws://localhost:${fS}${hS}`}function W$(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`sb-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function Q$(t,e){try{const n=new URL(t,e.href).pathname;return`${e.protocol==="https:"?"wss:":"ws:"}//${e.host}${n}`}catch{return t}}function J$(t,e){return{url:e,dispatcher:(n,r,s)=>pM(t,r,s),workerRelay:{op:n=>mM(t,n),subscribe:(n,r)=>yM(t,n,r)}}}async function X$(t,e={}){const n=e.baseUrl??"",r=e.fetchImpl??(typeof fetch<"u"?fetch:null),s=p=>{var g;return(g=e.onStateChange)==null?void 0:g.call(e,{kind:"disconnected",reason:p})};if(!r)return s("no fetch available"),null;let o;try{const p=await r(`${n}/__pyric/init.json`);if(!p.ok)return s("not served"),null;o=(await p.json()).bridgeUrl??null}catch{return s("not served"),null}if(!o)return s("bridge off"),null;const c=e.locationLike??(typeof window<"u"?window.location:null),d=c?Q$(o,c):o,f=Y$(null,{...J$(t,d),...e.onStateChange?{onStateChange:e.onStateChange}:{},...e.initialReconnectDelayMs!==void 0?{initialReconnectDelayMs:e.initialReconnectDelayMs}:{},...e.maxReconnectDelayMs!==void 0?{maxReconnectDelayMs:e.maxReconnectDelayMs}:{}});return console.info("[pyric studio] registered as the sandbox bridge peer at",d),f}const e3={};function t3(){return!1}function n3(){let t={kind:"connecting"};const e=new Set;return{get:()=>t,subscribe(n){return e.add(n),()=>e.delete(n)},set(n){t=n;for(const r of e)r()}}}function r3(t,e={}){if(t==="local"){const n=e.baseUrl??"",r=t3(),s=e.persistence==="memory"||r?Pm():qI(n),o=e.disableLive?null:mL(e.workerUrl),c=o?n3():null;return o&&c&&X$(o.db,{baseUrl:n,onStateChange:d=>c.set(d)}),{mode:t,projects:r?PI():$I(n),persistence:s,...o?{live:o}:{},...c?{bridge:c}:{}}}throw new Error(`createStudioEnvironment(${t}): only 'local' is wired in v1 (T3). 'browser'/'hosted' land in A3.`)}const FA=A.createContext(null);function s3(t){try{return{status:"ready",env:r3(t),error:null}}catch(e){return{status:"error",env:null,error:e instanceof Error?e:new Error(String(e))}}}function i3({mode:t="local",children:e}){const n=A.useMemo(()=>s3(t),[t]);return h.jsx(FA.Provider,{value:n,children:e})}function rr(){const t=A.useContext(FA);if(!t)throw new Error("useEnvironment must be used within an <EnvironmentProvider>");return t}const a3="pyric-studio:theme",Pu="dark";function o3(){return Pu}function l3(){typeof document>"u"||document.documentElement.setAttribute("data-theme","dark")}const c3=A.createContext(null);function u3({children:t}){const[e,n]=A.useState(o3);A.useEffect(()=>{l3();try{localStorage.setItem(a3,Pu)}catch{}},[e]);const r="dark",s=A.useCallback(d=>n(Pu),[]),o=A.useCallback(()=>n(Pu),[]),c=A.useMemo(()=>({choice:e,resolvedTheme:r,setChoice:s,cycleChoice:o}),[e,r,s,o]);return h.jsx(c3.Provider,{value:c,children:t})}function zA(){const t=typeof import.meta<"u"&&"/__pyric/ui/"||"/";return t.endsWith("/")?t:`${t}/`}function d3(t){const e={};for(const n of t.replace(/^\?/,"").split("&")){if(!n)continue;const r=n.indexOf("="),s=r===-1?n:n.slice(0,r),o=r===-1?"":n.slice(r+1);s&&(e[decodeURIComponent(s)]=decodeURIComponent(o))}return e}function _g(t,e="",n=zA()){let r=t;const s=n.replace(/\/$/,"");n!=="/"&&(t===s||t.startsWith(n))&&(r=t.slice(s.length));const o=r.split("/").filter(Boolean).map(f=>decodeURIComponent(f)),[c="",...d]=o;return{tab:c,rest:d,query:d3(e)}}function f3(t,e=zA()){const n=[t.tab,...t.rest??[]].filter(s=>s!=null&&s!=="").map(s=>encodeURIComponent(s)).join("/"),r=Object.entries(t.query??{}).filter(([,s])=>s!=null&&s!=="").map(([s,o])=>`${encodeURIComponent(s)}=${encodeURIComponent(String(o))}`).join("&");return`${e}${n}${r?`?${r}`:""}`}const yy="pyric:studio:navigated",h3={tab:"",rest:[],query:{}};function PA(){return typeof window<"u"?window.location.pathname+window.location.search:""}function Rr(){return typeof window>"u"?h3:_g(window.location.pathname,window.location.search)}function p3(t){return t.tab==="home"?{...t,tab:""}:t}function Gd(t){return f3(p3(t))}function VA(){typeof window<"u"&&window.dispatchEvent(new Event(yy))}function Jn(t){if(typeof window>"u")return;const e=Gd(t);PA()!==e&&(window.history.pushState(null,"",e),VA())}function xd(t){typeof window>"u"||(window.history.replaceState(null,"",Gd(t)),VA())}function ec(t){return typeof window>"u"?()=>{}:(window.addEventListener("popstate",t),window.addEventListener(yy,t),()=>{window.removeEventListener("popstate",t),window.removeEventListener(yy,t)})}function m3(t,e){const n=A.useCallback(o=>t.includes(o)?o:e,[t,e]),r=A.useSyncExternalStore(ec,()=>n(Rr().tab),()=>e);A.useEffect(()=>{const o=typeof window<"u"?window.location.hash:"";if(o.length>1){const d=o.slice(1),f=d.indexOf("?"),p=_g(`/${f===-1?d:d.slice(0,f)}`,f===-1?"":d.slice(f),"/");if(t.includes(p.tab)){xd(p);return}}const c=Rr();c.tab!==""&&!t.includes(c.tab)&&xd({tab:n(c.tab)})},[n]);const s=A.useCallback(o=>{const c=n(o);c!==r&&Jn({tab:c})},[n,r]);return[r,s]}let gy=null;function y3(t){gy=t}function g3(){return gy?(gy(),!0):!1}function b3(t){return(t.metaKey||t.ctrlKey)&&!t.altKey&&!t.shiftKey&&(t.key==="k"||t.key==="K")}const v3=[{id:"home",label:"Home",description:"What is happening in the sandbox, and where to go next."},{id:"firestore",label:"Firestore",description:"Browse and edit collections, documents, and references."},{id:"auth",label:"Auth",description:"View and edit users, claims, providers, and account state."},{id:"rtdb",label:"RTDB",description:"Browse and edit RTDB data in the shared sandbox."},{id:"storage",label:"Storage",description:"Browse buckets, inspect objects, upload, and delete files."},{id:"traffic",label:"Traffic",description:"Watch sandbox requests, listener activity, and rule decisions."},{id:"assurance",label:"Assurance",description:"Compare intended access with qualified local sandbox behavior."},{id:"settings",label:"Settings",description:"Configure models, keys, theme, sandbox maintenance, and diagnostics."}];function w3({assuranceEnabled:t=!1}={}){return v3.filter(e=>e.id!=="assurance"||t)}const Pi=w3({assuranceEnabled:!1}),x3=Pi.map(t=>t.id);function S3(t){return Pi.find(e=>e.id===t)??Pi[0]}function _3(t,e){const n=t.toLowerCase(),r=e.toLowerCase();let s=0;for(const o of r)if(o===n[s]&&s++,s===n.length)return!0;return s===n.length}const E3=7;function A3(t,e){const n=t.trim();if(!n)return[];const r=e.filter(b=>b.id!=="settings"),s=[],o=[],c=[],[d="",...f]=n.split(/\s+/),p=f.join(" ");for(const b of r){const v={id:`tab:${b.id}`,label:`Go to ${b.label}`,hint:b.description,target:{tab:b.id}},w=b.label.toLowerCase();if(w.startsWith(n.toLowerCase())?s.push(v):_3(n,b.label)&&o.push(v),p&&(w===d.toLowerCase()||w.startsWith(d.toLowerCase()))){const _=p.split("/").filter(Boolean);b.id==="firestore"||b.id==="storage"?c.push({id:`deep:${b.id}:${p}`,label:`Open /${_.join("/")} in ${b.label}`,hint:b.id==="firestore"?"Firestore path":"Storage object path",target:{tab:b.id,rest:_}}):b.id==="auth"?c.push({id:`deep:auth:${p}`,label:`Open user ${p} in Auth`,hint:"Auth uid",target:{tab:"auth",rest:[p]}}):b.id==="traffic"&&c.push({id:`deep:traffic:${p}`,label:`Open ${p} in the rules inspector`,hint:"Traffic event id",target:{tab:"traffic",query:{inspect:p}}})}}const g=n.match(/^gs:\/\/[^/]+\/(.+)$/);if(g){const b=g[1].split("/").filter(Boolean);c.unshift({id:`deep:storage:${g[1]}`,label:`Open ${g[1]} in Storage`,hint:"Storage object path",target:{tab:"storage",rest:b}})}else if(n.includes("/")&&!n.includes(" ")){const b=n.split("/").filter(Boolean);b.length&&c.push({id:`deep:firestore:${n}`,label:`Open /${b.join("/")} in Firestore`,hint:"Firestore path",target:{tab:"firestore",rest:b}})}return[...s,...c,...o].slice(0,E3)}function by(t){return`${t.kind}:${t.target.tab}:${(t.target.rest??[]).join("/")}`}const vy={docsPerCollection:50,collectionsScanned:20,users:100,objects:200,storageListCalls:20,subcollections:30,subcollectionRpcCalls:40};async function j3(t,e,{maxObjects:n,maxListCalls:r}){const s=[],o=[t];let c=0;for(;o.length&&s.length<n&&c<r;){c++;const d=await e(o.shift());for(const f of d.items){if(s.length>=n)break;s.push(f.fullPath)}o.push(...d.prefixes)}return s}async function k3(t,e,n,{maxSubcollections:r,maxRpcCalls:s,docsPerCollection:o}){const c=[],d=[],f=[...t];let p=0;for(;f.length&&c.length<r&&p<s;){const g=f.shift();p++;let b=[];try{b=await e(g)}catch{continue}for(const v of b){if(c.length>=r)break;const w=`${g}/${v}`;c.push(w);try{const _=await n(w,o);for(const k of _.slice(0,o))d.push(k),f.push(k)}catch{}}}return{subcollections:c,documents:d}}const C3=5;function Sd(t,e){const n=t.toLowerCase(),r=e.toLowerCase();if(!n||!r)return 0;if(r===n)return 1e3;if(r.startsWith(n))return 900-Math.min(r.length-n.length,100);const s=r.indexOf(n);if(s!==-1)return 700-Math.min(s,100);let o=0,c=-1,d=-1;for(let p=0;p<r.length&&o<n.length;p++)r[p]===n[o]&&(c===-1&&(c=p),d=p,o++);if(o!==n.length)return 0;const f=d-c+1;return Math.max(1,400-(f-n.length)*10-Math.min(c,50))}const N3={collection:"Firestore collections",document:"Firestore documents",subcollection:"Firestore subcollections",user:"Auth users",object:"Storage objects","rtdb-key":"RTDB keys"},O3=["collection","document","subcollection","user","object","rtdb-key"];function R3(t){switch(t.kind){case"collection":return"Firestore collection";case"document":return"Firestore document";case"subcollection":return t.alt?`Subcollection of /${t.alt}`:"Subcollection";case"user":return t.alt?`Auth user · uid ${t.alt}`:"Auth user";case"object":return"Storage object";case"rtdb-key":return"RTDB top-level key"}}function HA(t){return t.endsWith("/")?{base:t.slice(0,-1),trailing:!0}:{base:t,trailing:!1}}function T3(t,e){const{base:n,trailing:r}=HA(t);if(!n)return 0;const s=n.split("/"),o=e.split("/");if(s.length>o.length)return 0;const c=s.length-1;for(let d=0;d<c;d++)if(s[d].toLowerCase()!==o[d].toLowerCase())return 0;return r?s[c].toLowerCase()===o[c].toLowerCase()?850:0:Sd(s[c],o[c])}function D3(t,e){const{base:n,trailing:r}=HA(t);if(!n||n.includes("/"))return 0;const s=e.split("/").pop()??e;return r?s.toLowerCase()===n.toLowerCase()?850:0:Sd(n,s)}function WS(t,e,n,r=C3){const s=t.trim();if(!s)return[];const o=[],c=A3(t,e);c.length&&o.push({kind:"navigate",title:"Go to",results:c});for(const d of O3){const f=d==="document"||d==="subcollection",p=d==="collection"||d==="subcollection",g=new Map;for(const v of n)v.kind===d&&g.set(by(v),v);const b=[...g.values()].map(v=>({entry:v,score:Math.max(Sd(s,v.label),v.alt?Sd(s,v.alt):0,f?T3(s,v.label):0,p?D3(s,v.label):0)})).filter(v=>v.score>0).sort((v,w)=>w.score-v.score||v.entry.label.localeCompare(w.entry.label)).slice(0,r);b.length&&o.push({kind:d,title:N3[d],results:b.map(({entry:v})=>({id:by(v),label:v.label,hint:R3(v),target:v.target}))})}return o}function QS(t){return t.flatMap(e=>e.results)}function I3(t){return{kind:"collection",label:t,target:{tab:"firestore",rest:[t]}}}function JS(t){return{kind:"document",label:t,target:{tab:"firestore",rest:t.split("/").filter(Boolean)}}}function M3(t){const e=t.split("/").filter(Boolean),n=e.slice(0,-1).join("/");return{kind:"subcollection",label:t,alt:n||void 0,target:{tab:"firestore",rest:e}}}function L3(t){return t.email?{kind:"user",label:t.email,alt:t.uid,target:{tab:"auth",rest:[t.uid]}}:{kind:"user",label:t.uid,target:{tab:"auth",rest:[t.uid]}}}function U3(t){return{kind:"object",label:t,target:{tab:"storage",rest:t.split("/").filter(Boolean)}}}function $3(t){return{kind:"rtdb-key",label:t,target:{tab:"rtdb",rest:[t]}}}async function B3(t,e={},n){const r={...vy,...e},s=[],o=g=>{g.length&&(s.push(...g),n==null||n(g))},c=(async()=>{var v;let g=[];try{g=await((v=t.listRootCollections)==null?void 0:v.call(t))??[]}catch{g=[]}g.length&&o(g.map(I3));const b=[];if(t.listDocumentPaths)for(const w of g.slice(0,r.collectionsScanned))try{const k=(await t.listDocumentPaths(w,r.docsPerCollection)).slice(0,r.docsPerCollection);b.push(...k),o(k.map(JS))}catch{}if(t.listSubcollections&&t.listDocumentPaths)try{const{subcollections:w,documents:_}=await k3(b,t.listSubcollections,t.listDocumentPaths,{maxSubcollections:r.subcollections,maxRpcCalls:r.subcollectionRpcCalls,docsPerCollection:r.docsPerCollection});o(w.map(M3)),o(_.map(JS))}catch{}})(),d=(async()=>{if(t.listUsers)try{const g=await t.listUsers(r.users);o(g.slice(0,r.users).map(L3))}catch{}})(),f=(async()=>{if(t.listStorageObjectPaths)try{const g=await t.listStorageObjectPaths(r.objects);o(g.slice(0,r.objects).map(U3))}catch{}})(),p=(async()=>{if(t.listRtdbTopLevelKeys)try{o((await t.listRtdbTopLevelKeys()).map($3))}catch{}})();return await Promise.allSettled([c,d,f,p]),s}const GA=Symbol("pyric/auth/target"),q3=Symbol("pyric.user.internal");function Fe(t,e){return new Wi(t,`Firebase: ${e} (${t}).`)}const KA={PASSWORD:"password"},tm={EMAIL_LINK:"emailLink",EMAIL_PASSWORD:"password"};class Kd{constructor(e,n){G(this,"providerId");G(this,"signInMethod");this.providerId=e,this.signInMethod=n}toJSON(){return{providerId:this.providerId,signInMethod:this.signInMethod}}static fromJSON(e){const n=typeof e=="string"?F3(e):e;if(!n)return null;const r=n.providerId,s=n.signInMethod;if(typeof r!="string"||typeof s!="string")return null;if(r===KA.PASSWORD){const o=typeof n.email=="string"?n.email:"",c=typeof n.password=="string"?n.password:"";return new z3(o,c,s)}return new Kd(r,s)}}function F3(t){try{const e=JSON.parse(t);return typeof e=="object"&&e!==null?e:null}catch{return null}}class z3 extends Kd{constructor(n,r,s=tm.EMAIL_PASSWORD){super(KA.PASSWORD,s);G(this,"email");G(this,"secret");this.email=n,Object.defineProperty(this,"secret",{value:r,enumerable:!1,writable:!1})}get password(){return this.signInMethod===tm.EMAIL_PASSWORD?this.secret:null}get emailLink(){return this.signInMethod===tm.EMAIL_LINK?this.secret:null}toJSON(){return{providerId:this.providerId,signInMethod:this.signInMethod,email:this.email,password:this.secret}}}class Yd extends Kd{constructor(n,r,s={}){super(n,r);G(this,"idToken");G(this,"accessToken");G(this,"secret");this.idToken=s.idToken,this.accessToken=s.accessToken,this.secret=s.secret}toJSON(){return{providerId:this.providerId,signInMethod:this.signInMethod,idToken:this.idToken,accessToken:this.accessToken,secret:this.secret}}}function Eg(t,e){return e?new Yd(t,t):null}const qs=class qs{constructor(){G(this,"providerId",qs.PROVIDER_ID)}addScope(e){return this}setCustomParameters(e){return this}static credentialFromResult(e){return Eg(qs.PROVIDER_ID,e)}static credentialFromError(e){return null}static credential(e,n){return new Yd(qs.PROVIDER_ID,qs.GOOGLE_SIGN_IN_METHOD,{idToken:e??void 0,accessToken:n??void 0})}};G(qs,"PROVIDER_ID","google.com"),G(qs,"GOOGLE_SIGN_IN_METHOD","google.com");let wy=qs;const Fs=class Fs{constructor(){G(this,"providerId",Fs.PROVIDER_ID)}addScope(e){return this}setCustomParameters(e){return this}static credentialFromResult(e){return Eg(Fs.PROVIDER_ID,e)}static credentialFromError(e){return null}static credential(e){return new Yd(Fs.PROVIDER_ID,Fs.FACEBOOK_SIGN_IN_METHOD,{accessToken:e})}};G(Fs,"PROVIDER_ID","facebook.com"),G(Fs,"FACEBOOK_SIGN_IN_METHOD","facebook.com");let xy=Fs;const zs=class zs{constructor(){G(this,"providerId",zs.PROVIDER_ID)}addScope(e){return this}setCustomParameters(e){return this}static credentialFromResult(e){return Eg(zs.PROVIDER_ID,e)}static credentialFromError(e){return null}static credential(e){return new Yd(zs.PROVIDER_ID,zs.GITHUB_SIGN_IN_METHOD,{accessToken:e})}};G(zs,"PROVIDER_ID","github.com"),G(zs,"GITHUB_SIGN_IN_METHOD","github.com");let Sy=zs;const YA=[wy.PROVIDER_ID,"apple.com",xy.PROVIDER_ID,Sy.PROVIDER_ID,"twitter.com","microsoft.com","yahoo.com"];function Ag(t,e=!1){var r;const n=t[GA];if(!n)throw new TypeError("pyric/auth: unrecognized Auth handle — was it produced by getAuth(...)?");return e||(r=n.assertAlive)==null||r.call(n),n}class P3{constructor(){G(this,"mockResults",new Map);G(this,"resolver",null);G(this,"redirectResult",null);G(this,"actionCodes",new Map);G(this,"nextCodeSerial",1);G(this,"outbox",[]);G(this,"mailResolver",null)}setMockResult(e,n){this.mockResults.set(e,n)}consumeMockResult(e){const n=this.mockResults.get(e);return n&&this.mockResults.delete(e),n}setResolver(e){this.resolver=e}getResolver(){return this.resolver}setRedirectResult(e){this.redirectResult=e}takeRedirectResult(){const e=this.redirectResult;return this.redirectResult=null,e}mintActionCode(e){const n=`sandbox-oob-${this.nextCodeSerial++}`;return this.actionCodes.set(n,e),n}stageActionCode(e,n){this.actionCodes.set(e,n)}peekActionCode(e){return this.actionCodes.get(e)}consumeActionCode(e){const n=this.actionCodes.get(e);return n&&this.actionCodes.delete(e),n}setMailResolver(e){this.mailResolver=e}deliverMail(e){if(this.outbox.push(e),this.mailResolver)try{this.mailResolver.deliver(e)}catch{}}takeMail(e){const n=e===void 0?this.outbox.length>0?0:-1:this.outbox.findIndex(r=>r.email.toLowerCase()===e.toLowerCase());return n<0?null:this.outbox.splice(n,1)[0]??null}listMail(){return[...this.outbox]}}function V3(t,e,n){let r=5381;const s=JSON.stringify(e)+":"+String(n);for(let c=0;c<s.length;c++)r=(r<<5)+r+s.charCodeAt(c)|0;const o=(r>>>0).toString(16).padStart(8,"0");return`sandbox-id-token-${t}-${o}`}function ki(t){if(typeof t!="string"||t.length===0)throw Fe("auth/invalid-email","Error");const e=t.indexOf("@");if(e<=0||e===t.length-1)throw Fe("auth/invalid-email","Error")}function ml(t){if(typeof t!="string"||t.length<6)throw Fe("auth/weak-password","Password should be at least 6 characters")}function ZA(){return{usersByEmail:new Map,usersByUid:new Map,userDbSubscribers:new Set,providerConfig:new Map([["password",!0],["anonymous",!0]]),providerConfigSubscribers:new Set,counters:{nextAdminUserId:1,nextAnonymousId:1}}}const H3="__pyric_no_password__";class WA{constructor(e,n=e,r=ZA(),s){G(this,"usersByEmail");G(this,"usersByUid");G(this,"authStateSubs",[]);G(this,"idTokenSubs",[]);G(this,"userDbSubs");G(this,"beforeStateSubs",[]);G(this,"sharedCounters");G(this,"flow",new P3);G(this,"sandbox");G(this,"session");G(this,"cachedUser",null);G(this,"lastNotifiedUid",null);G(this,"applyingTransition",!1);G(this,"tokenCache",new Map);G(this,"nextTokenSerial",1);G(this,"persistenceMode","LOCAL");G(this,"signInProviderByUid",new Map);G(this,"providerConfig");G(this,"providerConfigSubs");G(this,"providerEnforcementDelegated",!1);G(this,"sessionChangeSubs",new Set);var c;this.sandbox=e,this.session=n,this.usersByEmail=r.usersByEmail,this.usersByUid=r.usersByUid,this.userDbSubs=r.userDbSubscribers,this.providerConfig=r.providerConfig,this.providerConfigSubs=r.providerConfigSubscribers,this.sharedCounters=r.counters,this.cachedUser=this.buildUserFromState(n.currentUser),this.lastNotifiedUid=((c=this.cachedUser)==null?void 0:c.uid)??null;const o=n.onCurrentUserChanged(d=>{var g;if(this.applyingTransition)return;const f=d===null?null:d.uid,p=((g=this.cachedUser)==null?void 0:g.uid)??null;f!==p&&(this.cachedUser=this.buildUserFromState(d)),this.notifyAuthListeners()});s==null||s(()=>{o(),this.authStateSubs.length=0,this.idTokenSubs.length=0,this.beforeStateSubs.length=0})}getCurrentUser(){return this.cachedUser}subscribe(e,n){const r=e==="auth-state"?this.authStateSubs:this.idTokenSubs,s={observer:n,hasFired:!1,lastValue:null};return r.push(s),queueMicrotask(()=>{r.includes(s)&&(s.hasFired&&s.lastValue===this.cachedUser||this.deliverOne(s,this.cachedUser))}),()=>{const o=r.indexOf(s);o!==-1&&r.splice(o,1)}}fanOut(e="both"){const n=this.cachedUser;if(e==="both"||e==="auth-state")for(const r of[...this.authStateSubs])this.deliverOne(r,n);if(e==="both"||e==="id-token")for(const r of[...this.idTokenSubs])this.deliverOne(r,n)}notifyAuthListeners(){var n;this.fanOut("id-token");const e=((n=this.cachedUser)==null?void 0:n.uid)??null;this.lastNotifiedUid!==e&&(this.lastNotifiedUid=e,this.fanOut("auth-state"))}deliverOne(e,n){e.hasFired=!0,e.lastValue=n;const r=e.observer;try{typeof r=="function"?r(n):r.next&&r.next(n)}catch{}}makeStored(e){return{email:null,password:null,displayName:null,phoneNumber:null,photoUrl:null,customClaims:{},isAnonymous:!1,providerUserInfo:[],disabled:!1,emailVerified:!1,createdAt:new Date().toISOString(),lastLoginAt:null,...e}}notifyUsersChanged(){for(const e of[...this.userDbSubs])try{e()}catch{}}emitAuthEvent(e,n={}){try{Vs(this.sandbox,$d({service:"auth",op:e,path:n.path,auth:n.auth??this.session.currentUser,before:n.before,after:n.after,detail:n.detail}),{service:"auth"})}catch{}}subscribeUsers(e){return this.userDbSubs.add(e),()=>{this.userDbSubs.delete(e)}}isProviderEnabled(e){return this.providerConfig.get(e)??!0}listProviderConfig(){return[...this.providerConfig.entries()].map(([e,n])=>({providerId:e,enabled:n}))}setProviderConfig(e,n){const r=this.providerConfig.get(e)??!0;r!==n&&(this.providerConfig.set(e,n),this.notifyProviderConfigChanged(),this.emitAuthEvent("provider_config_update",{path:e,auth:null,before:{providerId:e,enabled:r},after:{providerId:e,enabled:n}}))}notifyProviderConfigChanged(){for(const e of[...this.providerConfigSubs])try{e()}catch{}}subscribeProviderConfig(e){return this.providerConfigSubs.add(e),()=>{this.providerConfigSubs.delete(e)}}setProviderEnforcementDelegated(e){this.providerEnforcementDelegated=e}assertProviderEnabled(e){if(!this.providerEnforcementDelegated&&!this.isProviderEnabled(e))throw Fe("auth/operation-not-allowed",`${e} sign-in is disabled for this sandbox project. Enable it with sandbox.setAuthProviderConfig(auth, '${e}', true).`)}exportProviderConfig(){return Object.fromEntries(this.providerConfig)}restoreProviderConfig(e){if(this.providerConfig.clear(),e&&typeof e=="object")for(const[n,r]of Object.entries(e))typeof r=="boolean"&&this.providerConfig.set(n,r);else this.providerConfig.set("password",!0),this.providerConfig.set("anonymous",!0);this.notifyProviderConfigChanged()}getPersistenceMode(){return this.persistenceMode}setPersistenceMode(e){this.persistenceMode!==e&&(this.persistenceMode=e,this.notifySessionChanged())}notifySessionChanged(){for(const e of[...this.sessionChangeSubs])try{e()}catch{}}subscribeSession(e){return this.sessionChangeSubs.add(e),()=>{this.sessionChangeSubs.delete(e)}}seedUsers(e){for(const n of e){const r=this.usersByUid.get(n.uid);r!=null&&r.email&&r.email.toLowerCase()!==n.email.toLowerCase()&&this.usersByEmail.delete(r.email.toLowerCase());const s=this.makeStored({uid:n.uid,email:n.email,password:n.password,displayName:n.displayName??null,customClaims:n.customClaims??{},providerUserInfo:[{providerId:n.providerId??"password"}]});this.usersByEmail.set(n.email.toLowerCase(),s),this.usersByUid.set(n.uid,s)}e.length>0&&this.notifyUsersChanged()}exportUsers(){var n;const e=[];for(const r of this.usersByUid.values()){if(r.email===null)continue;const s={uid:r.uid,email:r.email,password:r.password??H3,providerId:((n=r.providerUserInfo[0])==null?void 0:n.providerId)??"password"};r.displayName!==null&&(s.displayName=r.displayName),Object.keys(r.customClaims).length>0&&(s.customClaims=r.customClaims),e.push(s)}return e}restoreSession(e){var o;const n=this.usersByUid.get(e);if(!n)throw Fe("auth/user-not-found",`restoreSession: no identity with uid ${e}.`);if(n.disabled)throw Fe("auth/user-disabled",`restoreSession: user ${e} is disabled.`);const r=n.isAnonymous?"anonymous":((o=n.providerUserInfo[0])==null?void 0:o.providerId)??"password",s=this.buildUserFromStored(n);return this.setCurrentUser(s,r),s}findByEmail(e){return this.usersByEmail.get(e.toLowerCase())}findByUid(e){return this.usersByUid.get(e)}mintActionCode(e){return this.flow.mintActionCode(e)}stageActionCode(e,n){this.flow.stageActionCode(e,n)}peekActionCode(e){return this.flow.peekActionCode(e)}consumeActionCode(e){return this.flow.consumeActionCode(e)}deliverMail(e){this.flow.deliverMail(e)}takeMail(e){return this.flow.takeMail(e)}listMail(){return this.flow.listMail()}setMailResolver(e){this.flow.setMailResolver(e)}setEmailVerified(e,n){const r=this.requireByEmail(e);return r.emailVerified!==n&&(r.emailVerified=n,this.notifyUsersChanged(),this.emitAuthEvent("user_update",{path:r.uid,after:this.toRecord(r),detail:{emailVerified:n}})),r}setPasswordByEmail(e,n){ml(n);const r=this.requireByEmail(e);return r.password=n,this.notifyUsersChanged(),this.emitAuthEvent("user_update",{path:r.uid,after:this.toRecord(r),detail:{passwordReset:!0}}),r}changeEmail(e,n){ki(n);const r=this.requireByEmail(e),s=n.toLowerCase(),o=this.usersByEmail.get(s);if(o&&o.uid!==r.uid)throw Fe("auth/email-already-in-use",`An account already exists for ${n}.`);return r.email&&this.usersByEmail.delete(r.email.toLowerCase()),r.email=n,r.emailVerified=!0,this.usersByEmail.set(s,r),this.notifyUsersChanged(),this.emitAuthEvent("user_update",{path:r.uid,after:this.toRecord(r),detail:{emailChanged:n}}),r}upsertEmailLinkUser(e){ki(e);const n=e.toLowerCase(),r=this.usersByEmail.get(n);if(r)return r.providerUserInfo.some(c=>c.providerId==="password")||r.providerUserInfo.push({providerId:"password"}),r.emailVerified=!0,this.notifyUsersChanged(),{stored:r,isNewUser:!1};const s=`email-${n}-${this.usersByEmail.size+1}`,o=this.makeStored({uid:s,email:e,providerUserInfo:[{providerId:"password"}]});return o.emailVerified=!0,this.usersByEmail.set(n,o),this.usersByUid.set(s,o),this.notifyUsersChanged(),this.emitAuthEvent("user_create",{path:s,after:this.toRecord(o),detail:{emailLink:!0}}),{stored:o,isNewUser:!0}}linkProvider(e,n,r){const s=this.usersByUid.get(e);if(!s)throw Fe("auth/user-not-found",`linkWithCredential: no identity with uid ${e}.`);if(s.providerUserInfo.some(c=>c.providerId===n))throw Fe("auth/provider-already-linked",`User can only be linked to one identity for the given provider (${n}).`);const o=r==null?void 0:r.email;if(o){ki(o);const c=o.toLowerCase(),d=this.usersByEmail.get(c);if(d&&d.uid!==e)throw Fe("auth/email-already-in-use",`An account already exists for ${o}.`);r.password!==void 0&&r.password!==null&&(ml(r.password),s.password=r.password),s.email&&s.email.toLowerCase()!==c&&this.usersByEmail.delete(s.email.toLowerCase()),s.email=o,this.usersByEmail.set(c,s),r.emailVerified!==void 0&&(s.emailVerified=r.emailVerified)}return s.providerUserInfo.push({providerId:n}),s.isAnonymous&&(s.isAnonymous=!1),this.notifyUsersChanged(),this.emitAuthEvent("user_update",{path:e,after:this.toRecord(s),detail:{linked:n}}),s}unlinkProvider(e,n){const r=this.usersByUid.get(e);if(!r)throw Fe("auth/user-not-found",`unlink: no identity with uid ${e}.`);const s=r.providerUserInfo.findIndex(o=>o.providerId===n);if(s<0)throw Fe("auth/no-such-provider",`User was not linked to an account with the given provider (${n}).`);return r.providerUserInfo.splice(s,1),n==="password"&&(r.password=null),this.notifyUsersChanged(),this.emitAuthEvent("user_update",{path:e,after:this.toRecord(r),detail:{unlinked:n}}),r}requireByEmail(e){const n=this.usersByEmail.get(e.toLowerCase());if(!n)throw Fe("auth/user-not-found",`No user found for ${e}.`);return n}createEmailPasswordUser(e,n){ki(e),ml(n);const r=e.toLowerCase();if(this.usersByEmail.has(r))throw Fe("auth/email-already-in-use",`An account already exists for ${e}.`);const s=`email-${r}-${this.usersByEmail.size+1}`,o=this.makeStored({uid:s,email:e,password:n,providerUserInfo:[{providerId:"password"}]});return this.usersByEmail.set(r,o),this.usersByUid.set(s,o),this.notifyUsersChanged(),this.emitAuthEvent("user_create",{path:s,after:this.toRecord(o)}),o}beforeAuthStateChanged(e,n){const r={callback:e,onAbort:n,active:!0};return this.beforeStateSubs.push(r),()=>{r.active=!1}}async runBeforeStateChange(e){if(e===this.cachedUser)return;const n=[];try{for(const r of this.beforeStateSubs)r.active&&(await r.callback(e),r.onAbort&&n.push(r.onAbort))}catch(r){n.reverse();for(const o of n)try{o()}catch{}const s=r instanceof Error?r.message:String(r);throw Fe("auth/login-blocked",s)}}transitionCurrentUser(e,n){return!this.beforeStateSubs.some(s=>s.active)||e===this.cachedUser?(this.setCurrentUser(e,n),Promise.resolve()):this.runBeforeStateChange(e).then(()=>{this.setCurrentUser(e,n)})}setCurrentUser(e,n){if(e===null){const c=this.cachedUser;this.cachedUser=null,this.applyingTransition=!0;try{this.session.currentUser=null}finally{this.applyingTransition=!1}c&&(this.tokenCache.delete(c.uid),this.notifyAuthListeners(),this.notifySessionChanged(),this.emitAuthEvent("sign_out",{path:c.uid,auth:{uid:c.uid}}));return}n!==void 0&&this.signInProviderByUid.set(e.uid,n);const r=this.usersByUid.get(e.uid),s=(r==null?void 0:r.customClaims)??{};n!==void 0&&r&&(r.lastLoginAt=new Date().toISOString(),this.notifyUsersChanged()),this.cachedUser=e,this.tokenCache.set(e.uid,this.mintToken(e.uid,s));const o={uid:e.uid,token:s};this.applyingTransition=!0;try{this.session.currentUser=o}finally{this.applyingTransition=!1}this.notifyAuthListeners(),this.notifySessionChanged(),n!==void 0&&this.emitAuthEvent("sign_in",{path:e.uid,auth:o,after:{uid:e.uid,isAnonymous:e.isAnonymous,email:e.email},detail:{providerId:n??"anonymous"}})}setMockResult(e,n){this.flow.setMockResult(e,n)}consumeMockResult(e){return this.flow.consumeMockResult(e)}setResolver(e){this.flow.setResolver(e)}getResolver(){return this.flow.getResolver()}setRedirectResult(e){this.flow.setRedirectResult(e)}takeRedirectResult(){return this.flow.takeRedirectResult()}recordProviderSignIn(e,n){let r=!1,s=this.usersByUid.get(e.uid);s||(s=this.makeStored({uid:e.uid,email:e.email,displayName:e.displayName,isAnonymous:e.isAnonymous}),this.usersByUid.set(e.uid,s),e.email&&this.usersByEmail.set(e.email.toLowerCase(),s),r=!0),s.providerUserInfo.some(o=>o.providerId===n)||(s.providerUserInfo.push({providerId:n}),r=!0),r&&this.notifyUsersChanged()}createSignInCredential(e){const{providerId:n}=e;let r;if("uid"in e){const s=this.usersByUid.get(e.uid);if(!s)throw Fe("auth/user-not-found",`createSignInCredential: no identity with uid ${e.uid}. Use the {spec} shape to create one.`);r=s}else{const{spec:s}=e,o=this.usersByEmail.get(s.email.toLowerCase());o?r=o:(r=this.makeStored({uid:s.uid??`${n}:${s.email}`,email:s.email,displayName:s.displayName??null,customClaims:s.customClaims??{}}),this.usersByUid.set(r.uid,r),this.usersByEmail.set(s.email.toLowerCase(),r),this.notifyUsersChanged())}return r.providerUserInfo.some(s=>s.providerId===n)||(r.providerUserInfo.push({providerId:n}),this.notifyUsersChanged()),{user:this.buildUserFromStored(r),providerId:n,operationType:"signIn"}}listIdentities(){return[...this.usersByUid.values()].map(e=>{var n;return{uid:e.uid,email:e.email,displayName:e.displayName,providerId:e.isAnonymous?"anonymous":((n=e.providerUserInfo[0])==null?void 0:n.providerId)??"password",providerUserInfo:[...e.providerUserInfo],isAnonymous:e.isAnonymous,customClaims:e.customClaims}})}toRecord(e){return{uid:e.uid,email:e.email,displayName:e.displayName,phoneNumber:e.phoneNumber,photoUrl:e.photoUrl,customClaims:{...e.customClaims},providerUserInfo:e.providerUserInfo.map(n=>({...n})),isAnonymous:e.isAnonymous,disabled:e.disabled,emailVerified:e.emailVerified,createdAt:e.createdAt,lastLoginAt:e.lastLoginAt}}listUsers(){return[...this.usersByUid.values()].map(e=>this.toRecord(e))}sanitizeLinkedProviders(e,n,r){var c;const s=new Set,o=[];for(const d of e){const f=(c=d==null?void 0:d.providerId)==null?void 0:c.trim();if(!f)throw Fe("auth/argument-error",`${r}: providerUserInfo entries need a non-empty providerId.`);f==="password"||f==="anonymous"||s.has(f)||(s.add(f),o.push({providerId:f}))}return n&&o.unshift({providerId:"password"}),o}createUser(e){const n=e.uid??`user-${this.sharedCounters.nextAdminUserId++}`;if(this.usersByUid.has(n))throw Fe("auth/uid-already-exists",`createUser: a user with uid ${n} already exists.`);if(e.email!==void 0&&(ki(e.email),this.usersByEmail.has(e.email.toLowerCase())))throw Fe("auth/email-already-in-use",`An account already exists for ${e.email}.`);if(e.password!==void 0&&(ml(e.password),e.email===void 0))throw Fe("auth/invalid-email","createUser: a password requires an email.");const r=this.makeStored({uid:n,email:e.email??null,password:e.password??null,displayName:e.displayName??null,phoneNumber:e.phoneNumber??null,photoUrl:e.photoUrl??null,customClaims:e.customClaims??{},disabled:e.disabled??!1,emailVerified:e.emailVerified??!1,providerUserInfo:this.sanitizeLinkedProviders(e.providerUserInfo??[],e.password!==void 0,"createUser")});this.usersByUid.set(n,r),r.email&&this.usersByEmail.set(r.email.toLowerCase(),r),this.notifyUsersChanged();const s=this.toRecord(r);return this.emitAuthEvent("user_create",{path:n,auth:null,after:s}),s}updateUser(e,n){const r=this.usersByUid.get(e);if(!r)throw Fe("auth/user-not-found",`No user found for uid ${e}.`);const s=this.toRecord(r);if(n.email!==void 0){ki(n.email);const c=n.email.toLowerCase(),d=this.usersByEmail.get(c);if(d&&d!==r)throw Fe("auth/email-already-in-use",`An account already exists for ${n.email}.`);r.email&&this.usersByEmail.delete(r.email.toLowerCase()),r.email=n.email,this.usersByEmail.set(c,r)}n.password!==void 0&&(ml(n.password),r.password=n.password,r.providerUserInfo.some(c=>c.providerId==="password")||r.providerUserInfo.push({providerId:"password"})),n.providerUserInfo!==void 0&&(r.providerUserInfo=this.sanitizeLinkedProviders(n.providerUserInfo,r.password!==null,"updateUser")),n.displayName!==void 0&&(r.displayName=n.displayName),n.customClaims!==void 0&&(r.customClaims={...n.customClaims}),n.disabled!==void 0&&(r.disabled=n.disabled),n.emailVerified!==void 0&&(r.emailVerified=n.emailVerified),this.notifyUsersChanged();const o=this.toRecord(r);return this.emitAuthEvent("user_update",{path:e,auth:null,before:s,after:o}),o}deleteUser(e){const n=this.usersByUid.get(e);if(!n)throw Fe("auth/user-not-found",`No user found for uid ${e}.`);const r=this.toRecord(n);this.usersByUid.delete(e),n.email&&this.usersByEmail.get(n.email.toLowerCase())===n&&this.usersByEmail.delete(n.email.toLowerCase()),this.tokenCache.delete(e),this.signInProviderByUid.delete(e),this.notifyUsersChanged(),this.emitAuthEvent("user_delete",{path:e,auth:null,before:r})}clearUsers(){if(this.usersByUid.size===0&&this.usersByEmail.size===0)return;const e=this.usersByUid.size;this.usersByUid.clear(),this.usersByEmail.clear(),this.notifyUsersChanged(),this.emitAuthEvent("users_clear",{path:"*",auth:null,detail:{count:e}})}assertSignInAllowed(e){var n;if((n=this.usersByUid.get(e))!=null&&n.disabled)throw Fe("auth/user-disabled","The user account has been disabled by an administrator.")}buildUserFromStored(e){return this.makeUser({uid:e.uid,email:e.email,displayName:e.displayName,isAnonymous:e.isAnonymous,claims:e.customClaims,photoURL:e.photoUrl,emailVerified:e.emailVerified,phoneNumber:e.phoneNumber,providers:e.providerUserInfo})}mintAnonymousUser(){const e=`anonymous-${this.sharedCounters.nextAnonymousId++}`,n=this.makeStored({uid:e,isAnonymous:!0});return this.usersByUid.set(e,n),this.notifyUsersChanged(),this.emitAuthEvent("user_create",{path:e,after:this.toRecord(n),detail:{isAnonymous:!0}}),this.makeUser({uid:e,email:null,displayName:null,isAnonymous:!0,claims:{}})}mintDetachedSession(e){var n;switch(e.kind){case"anonymous":return this.assertProviderEnabled("anonymous"),this.establishDetachedSession(this.mintAnonymousUser(),"anonymous");case"password":return this.assertProviderEnabled("password"),this.establishDetachedSession(this.buildUserFromStored(this.validatePassword(e.email,e.password)),"password");case"createPassword":return this.assertProviderEnabled("password"),this.establishDetachedSession(this.buildUserFromStored(this.createEmailPasswordUser(e.email,e.password)),"password");case"uid":{const r=this.usersByUid.get(e.uid);if(!r)throw Fe("auth/user-not-found",`mintSession: no identity with uid ${e.uid}.`);if(r.disabled)throw Fe("auth/user-disabled",`mintSession: user ${e.uid} is disabled.`);const s=r.isAnonymous?"anonymous":((n=r.providerUserInfo[0])==null?void 0:n.providerId)??"password";return this.establishDetachedSession(this.buildUserFromStored(r),s)}}}establishDetachedSession(e,n){this.signInProviderByUid.set(e.uid,n);const r=this.usersByUid.get(e.uid),s=(r==null?void 0:r.customClaims)??{};r&&(r.lastLoginAt=new Date().toISOString(),this.notifyUsersChanged()),this.tokenCache.set(e.uid,this.mintToken(e.uid,s));const o={uid:e.uid,token:s};return this.emitAuthEvent("sign_in",{path:e.uid,auth:o,after:{uid:e.uid,isAnonymous:e.isAnonymous,email:e.email},detail:{providerId:n,session:"connection"}}),{user:e,state:o}}buildUserFromState(e){if(e===null)return null;const n=this.usersByUid.get(e.uid);return n?this.buildUserFromStored({...n,customClaims:e.token??n.customClaims}):this.makeUser({uid:e.uid,email:null,displayName:null,isAnonymous:e.uid.startsWith("anonymous-"),claims:e.token??{}})}mintToken(e,n){const r=new Date,s=new Date(r.getTime()+100*365*24*60*60*1e3),o=this.nextTokenSerial++,c=V3(e,n,o),d=this.signInProviderByUid.get(e)??null,f={sub:e,aud:"pyric-sandbox",iss:"https://sandbox.pyric.dev",auth_time:Math.floor(r.getTime()/1e3),iat:Math.floor(r.getTime()/1e3),exp:Math.floor(s.getTime()/1e3),...n,firebase:{sign_in_provider:d}},p={token:c,claims:f,expirationTime:s.toISOString(),issuedAtTime:r.toISOString(),authTime:r.toISOString(),signInProvider:d};return{token:c,result:p}}getIdTokenFor(e,n,r){if(r){const c=this.mintToken(e,n);return this.tokenCache.set(e,c),this.fanOut("id-token"),c.token}const s=this.tokenCache.get(e);if(s)return s.token;const o=this.mintToken(e,n);return this.tokenCache.set(e,o),o.token}getIdTokenResultFor(e,n,r){if(r){const c=this.mintToken(e,n);return this.tokenCache.set(e,c),this.fanOut("id-token"),c.result}const s=this.tokenCache.get(e);if(s)return s.result;const o=this.mintToken(e,n);return this.tokenCache.set(e,o),o.result}makeUser(e){const n=e.photoURL??null,r=e.phoneNumber??null,s=e.emailVerified??!1,o="firebase",c=e.providers??[{providerId:"password"}],d=e.isAnonymous?[]:c.map(p=>({uid:e.uid,displayName:e.displayName,email:e.email,phoneNumber:r,photoURL:n,providerId:p.providerId})),f={uid:e.uid,email:e.email,emailVerified:s,displayName:e.displayName,photoURL:n,phoneNumber:r,isAnonymous:e.isAnonymous,providerId:o,providerData:d,getIdToken:async p=>this.getIdTokenFor(e.uid,this.liveClaims(e.uid,e.claims),p===!0),getIdTokenResult:async p=>this.getIdTokenResultFor(e.uid,this.liveClaims(e.uid,e.claims),p===!0)};return Object.defineProperty(f,q3,{value:{updateProfile:p=>(this.updateProfileFor(f,p),Promise.resolve()),delete:()=>(this.deleteFor(f),Promise.resolve()),updateEmail:p=>(this.updateEmailFor(f,p),Promise.resolve()),updatePassword:p=>(this.updatePasswordFor(f,p),Promise.resolve()),reload:()=>(this.reloadFor(f),Promise.resolve()),target:this.selfTarget()},enumerable:!1}),f}selfTarget(){return{kind:"sandbox",sandbox:this.sandbox,backend:this}}updateProfileFor(e,n){const r=this.usersByUid.get(e.uid),s=r?this.toRecord(r):void 0;r&&(n.displayName!==void 0&&(r.displayName=n.displayName),n.photoURL!==void 0&&(r.photoUrl=n.photoURL)),this.applyProfileToUser(e,n),this.cachedUser&&this.cachedUser.uid===e.uid&&this.cachedUser!==e&&this.applyProfileToUser(this.cachedUser,n),this.notifyUsersChanged(),this.emitAuthEvent("user_update",{path:e.uid,auth:{uid:e.uid},before:s,after:r?this.toRecord(r):void 0,detail:{displayName:n.displayName,photoURL:n.photoURL}})}applyProfileToUser(e,n){var o;const r=e;n.displayName!==void 0&&(r.displayName=n.displayName),n.photoURL!==void 0&&(r.photoURL=n.photoURL);const s=(o=e.providerData)==null?void 0:o[0];s&&(n.displayName!==void 0&&(s.displayName=n.displayName),n.photoURL!==void 0&&(s.photoURL=n.photoURL))}updateProfileByUid(e,n){const r=this.usersByUid.get(e);if(!r)throw Fe("auth/user-not-found",`updateProfile: no identity with uid ${e}.`);const s=this.toRecord(r);n.displayName!==void 0&&(r.displayName=n.displayName),n.photoURL!==void 0&&(r.photoUrl=n.photoURL),this.cachedUser&&this.cachedUser.uid===e&&this.applyProfileToUser(this.cachedUser,n),this.notifyUsersChanged();const o=this.toRecord(r);return this.emitAuthEvent("user_update",{path:e,auth:{uid:e},before:s,after:o,detail:{displayName:n.displayName,photoURL:n.photoURL}}),o}deleteFor(e){this.usersByUid.has(e.uid)&&this.deleteUser(e.uid),this.cachedUser&&this.cachedUser.uid===e.uid&&this.setCurrentUser(null)}updateEmailFor(e,n){this.updateUser(e.uid,{email:n}),this.applyEmailToUser(e,n),this.cachedUser&&this.cachedUser.uid===e.uid&&this.cachedUser!==e&&this.applyEmailToUser(this.cachedUser,n)}applyEmailToUser(e,n){var s;e.email=n;const r=(s=e.providerData)==null?void 0:s[0];r&&(r.email=n)}updatePasswordFor(e,n){this.updateUser(e.uid,{password:n})}reloadFor(e){const n=this.usersByUid.get(e.uid);if(!n)throw Fe("auth/user-token-expired","The user's credential is no longer valid. The user must sign in again.");this.applyStoredToUser(e,n),this.cachedUser&&this.cachedUser.uid===e.uid&&this.cachedUser!==e&&this.applyStoredToUser(this.cachedUser,n)}applyStoredToUser(e,n){const r=e;r.email=n.email,r.displayName=n.displayName,r.photoURL=n.photoUrl,r.emailVerified=n.emailVerified,r.phoneNumber=n.phoneNumber}liveClaims(e,n){var r;return((r=this.usersByUid.get(e))==null?void 0:r.customClaims)??n}validatePassword(e,n){if(ki(e),typeof n!="string"||n.length===0)throw Fe("auth/missing-password","A non-empty password must be provided");const r=this.findByEmail(e);if(!r)throw Fe("auth/user-not-found",`No user found for ${e}.`);if(r.disabled)throw Fe("auth/user-disabled","The user account has been disabled by an administrator.");if(r.password!==n)throw Fe("auth/wrong-password","Invalid password.");return r}}const XS=new WeakSet,ju=new WeakMap;function QA(t,e,n,r="[DEFAULT]"){return G3(t,e),K3(t,e,n,r)}function G3(t,e){XS.has(t)||(XS.add(t),t.registerPersistableService("auth",{snapshot:()=>({users:e.exportUsers(),providers:e.exportProviderConfig()}),restore:n=>{const r=n;e.clearUsers(),Array.isArray(r==null?void 0:r.users)&&r.users.length>0&&e.seedUsers(r.users),e.restoreProviderConfig(r==null?void 0:r.providers)},reset:()=>{e.clearUsers(),e.restoreProviderConfig(void 0)},subscribe:n=>{const r=e.subscribeUsers(n),s=e.subscribeProviderConfig(n);return()=>{r(),s()}}}))}function e_(t){return{snapshot:()=>null,restore:()=>{},session:{currentUid:()=>{var e;return((e=t.session.currentUser)==null?void 0:e.uid)??null},restore:(e,n)=>{t.backend.setPersistenceMode(n),t.backend.restoreSession(e)},mode:()=>t.backend.getPersistenceMode(),subscribe:e=>(t.subscribers.add(e),t.unsubscribeBackend||(t.unsubscribeBackend=t.backend.subscribeSession(()=>{for(const n of t.subscribers)n()})),()=>{var n;t.subscribers.delete(e),t.subscribers.size===0&&((n=t.unsubscribeBackend)==null||n.call(t),t.unsubscribeBackend=void 0)})}}}function K3(t,e,n,r){var p,g;let s=ju.get(t);s||(s=new Map,ju.set(t,s));const o=`auth-session:${r}`,c=s.get(o);if(c){const b=++c.generation;return(p=c.unregisterService)==null||p.call(c),c.unregisterService=void 0,(g=c.unsubscribeBackend)==null||g.call(c),c.unsubscribeBackend=void 0,c.backend=e,c.session=n,c.unregisterService=t.registerPersistableService(o,e_(c)),()=>{var v,w;c.generation===b&&((v=c.unregisterService)==null||v.call(c),c.unregisterService=void 0,(w=c.unsubscribeBackend)==null||w.call(c),c.unsubscribeBackend=void 0,c.subscribers.clear(),s.get(o)===c&&s.delete(o),s.size===0&&ju.delete(t))}}const d={backend:e,session:n,subscribers:new Set,generation:1};s.set(o,d),d.unregisterService=t.registerPersistableService(o,e_(d));const f=d.generation;return()=>{var b,v;d.generation===f&&((b=d.unregisterService)==null||b.call(d),d.unregisterService=void 0,(v=d.unsubscribeBackend)==null||v.call(d),d.unsubscribeBackend=void 0,d.subscribers.clear(),s.get(o)===d&&s.delete(o),s.size===0&&ju.delete(t))}}async function Qz(t){const{backend:e}=Ag(t);e.assertProviderEnabled("anonymous");const n=e.getCurrentUser();if(n!=null&&n.isAnonymous)return{user:n,providerId:null,operationType:"signIn",_additionalUserInfo:{isNewUser:!1,profile:{},providerId:null}};const r=e.mintAnonymousUser();return await e.transitionCurrentUser(r,"anonymous"),{user:r,providerId:null,operationType:"signIn",_additionalUserInfo:{isNewUser:!0,profile:{},providerId:null}}}async function Y3(t){var n;const e=Ag(t,!0);try{(n=e.assertAlive)==null||n.call(e)}catch(r){if(r.code==="app/app-deleted")return;throw r}await e.backend.transitionCurrentUser(null)}const t_=new WeakMap,n_=new WeakMap,r_=new WeakMap;function JA(t){let e=n_.get(t);return e||(e=ZA(),n_.set(t,e)),e}function Z3(t){let e=t_.get(t);return e||(e=new WA(t,t,JA(t)),t_.set(t,e),QA(t,e,t)),e}function W3(t,e){return e.service("auth/backend",()=>{const{sandbox:n,session:r}=e,s=new WA(n,r,JA(n),o=>{e.onDelete(o)});return e.onDelete(QA(n,s,r,t.name)),s})}function XA(t){if(t===void 0)return XA(HE());const e=sg(t);if(e)return e.service("auth/default",()=>{const n={kind:"sandbox",sandbox:e.sandbox,backend:W3(t,e),own:r=>e.onDelete(r),assertAlive:()=>e.assertAlive()};return s_(n,t)});if(Q3(t)){let n=r_.get(t);return n||(n=s_({kind:"sandbox",sandbox:t,backend:Z3(t)}),r_.set(t,n),n)}throw new TypeError("pyric/auth is a sandbox-only mirror. Package resolution must leave firebase/auth unchanged for production; activate pyric dev or @pyric/cli/register before importing to select the sandbox.")}function Q3(t){return typeof t=="object"&&t!==null&&typeof t.onCurrentUserChanged=="function"&&typeof t.withAuth=="function"}function s_(t,e){const n={[GA]:t,...e?{app:e}:{},signOut(){return Y3(n)}};return Object.defineProperty(n,"currentUser",{enumerable:!0,get(){return t.backend.getCurrentUser()}})}function it(t){return Ag(t)}const lr={setUser(t,e){it(t).backend.setCurrentUser(e)},setAuthFlowResolver(t,e){it(t).backend.setResolver(e)},setAuthMailResolver(t,e){it(t).backend.setMailResolver(e)},takeAuthMail(t,e){return it(t).backend.takeMail(e)},listAuthMail(t){return it(t).backend.listMail()},mockActionCode(t,e,n){it(t).backend.stageActionCode(e,n)},listIdentities(t){return it(t).backend.listIdentities()},createSignInCredential(t,e){return it(t).backend.createSignInCredential(e)},mockSignInResult(t,e){const n=e.providerId;if(!n)throw new nt("invalid-argument","sandbox.mockSignInResult: result.providerId is required so the next signInWithPopup / signInWithCredential call can match.");it(t).backend.setMockResult(n,e)},seedUsers(t,e){it(t).backend.seedUsers(e)},exportUsers(t){return it(t).backend.exportUsers()},restoreSession(t,e){return it(t).backend.restoreSession(e)},mintSession(t,e){return it(t).backend.mintDetachedSession(e)},listUsers(t){return it(t).backend.listUsers()},createUser(t,e){return it(t).backend.createUser(e)},updateUser(t,e,n){return it(t).backend.updateUser(e,n)},updateProfile(t,e,n){return it(t).backend.updateProfileByUid(e,n)},deleteUser(t,e){it(t).backend.deleteUser(e)},clearUsers(t){it(t).backend.clearUsers()},subscribeUsers(t,e){return it(t).backend.subscribeUsers(e)},getAuthProviderConfig(t){return it(t).backend.listProviderConfig()},setAuthProviderConfig(t,e,n){it(t).backend.setProviderConfig(e,n)},assertAuthProviderEnabled(t,e){it(t).backend.assertProviderEnabled(e)},delegateProviderEnforcement(t,e){it(t).backend.setProviderEnforcementDelegated(e)},subscribeAuthProviderConfig(t,e){return it(t).backend.subscribeProviderConfig(e)}},_y="pyric-storage";function J3(t){return t?`${_y}:${t}`:_y}const X3=1,wr="blobs",bn="metadata";function e6(t=_y){return n6(t).then(e=>new t6(e))}class t6{constructor(e){G(this,"db");this.db=e}async put(e,n,r){const s=this.db.transaction([wr,bn],"readwrite");s.objectStore(wr).put(n,e),s.objectStore(bn).put(r,e),await ku(s)}async getBlob(e){const n=this.db.transaction(wr,"readonly");return nm(n.objectStore(wr).get(e))}async getMetadata(e){const n=this.db.transaction(bn,"readonly");return nm(n.objectStore(bn).get(e))}async putMetadata(e,n){const r=this.db.transaction(bn,"readwrite");r.objectStore(bn).put(n,e),await ku(r)}async delete(e){const n=this.db.transaction([wr,bn],"readwrite");n.objectStore(wr).delete(e),n.objectStore(bn).delete(e),await ku(n)}async listByPrefix(e){const n=this.db.transaction(bn,"readonly"),r=IDBKeyRange.bound(e,e+"￿",!1,!1);return nm(n.objectStore(bn).getAll(r))}async reset(){const e=this.db.transaction([wr,bn],"readwrite");e.objectStore(wr).clear(),e.objectStore(bn).clear(),await ku(e)}close(){this.db.close()}}function n6(t){return new Promise((e,n)=>{const r=indexedDB.open(t,X3);r.addEventListener("upgradeneeded",()=>{const s=r.result;s.objectStoreNames.contains(wr)||s.createObjectStore(wr),s.objectStoreNames.contains(bn)||s.createObjectStore(bn)}),r.addEventListener("success",()=>e(r.result)),r.addEventListener("error",()=>n(r.error)),r.addEventListener("blocked",()=>n(new Error(`IndexedDB open blocked for db "${t}"`)))})}function nm(t){return new Promise((e,n)=>{t.addEventListener("success",()=>e(t.result)),t.addEventListener("error",()=>n(t.error))})}function ku(t){return new Promise((e,n)=>{t.addEventListener("complete",()=>e()),t.addEventListener("error",()=>n(t.error)),t.addEventListener("abort",()=>n(t.error??new Error("IndexedDB transaction aborted")))})}function i_(t){switch(t){case"read":return["get","list"];case"write":return["create","update","delete"];default:return[t]}}const r6=new Set(["&&","||","==","!=","<",">","<=",">=","+","-","*","/","%"]);function ej(t){return{segments:t.path.segments.map(s6),children:t.children.map(ej),allows:t.allows.map(e=>({verbs:e.operations,condition:at(e.condition)})),functions:t.functions.map(Ey)}}function s6(t){switch(t.type){case"literal":return{kind:"literal",value:t.value};case"wildcard":return{kind:"param",name:t.name};case"recursive":return{kind:"wildcard",name:t.name}}}function Ey(t){return{name:t.name,params:t.parameters,lets:t.lets.map(e=>({name:e.name,value:at(e.value)})),body:at(t.body)}}function at(t){switch(t.type){case"literal":return typeof t.value=="number"&&t.raw.includes(".")?{kind:"literal",value:new Ke(t.value)}:{kind:"literal",value:t.value};case"identifier":return{kind:"ident",name:t.name};case"memberAccess":return{kind:"member",target:at(t.object),name:t.property};case"methodCall":return{kind:"methodcall",target:at(t.object),method:t.method,args:t.args.map(at)};case"bracketAccess":return{kind:"index",target:at(t.object),index:at(t.index)};case"sliceAccess":return{kind:"slice",target:at(t.object),start:at(t.start),end:at(t.end)};case"binaryOp":if(!r6.has(t.op))throw new SyntaxError(`Unsupported binary operator '${t.op}' in storage rules.`);return{kind:"binary",op:t.op,left:at(t.left),right:at(t.right)};case"unaryOp":if(t.op!=="!"&&t.op!=="-")throw new SyntaxError(`Unsupported unary operator '${t.op}' in storage rules.`);return{kind:"unary",op:t.op,arg:at(t.operand)};case"ternary":return{kind:"ternary",cond:at(t.condition),then:at(t.consequent),else:at(t.alternate)};case"inExpr":return{kind:"in",element:at(t.element),collection:at(t.collection)};case"isExpr":return{kind:"is",value:at(t.value),typeName:t.typeName};case"listLiteral":return{kind:"list",elements:t.elements.map(at)};case"mapLiteral":return{kind:"map",entries:t.entries.map(e=>({key:at(e.key),value:at(e.value)}))};case"pathLiteral":return{kind:"path",segments:t.segments.map(e=>typeof e=="string"?{kind:"literal",value:e}:{kind:"interp",expr:at(e)})};case"functionCall":return{kind:"call",name:t.name,args:t.args.map(at)};default:{const e=t;throw new SyntaxError(`Unsupported expression construct: ${JSON.stringify(e)}`)}}}function tj(t){const e=Tl(t);if(!e.ok)throw new SyntaxError(`Storage rules parse error at line ${e.error.line}, column ${e.error.column}: expected ${e.error.expected}.`);const n=e.ast;if(n.service.name!=="firebase.storage")throw new SyntaxError(`Expected 'service firebase.storage', got 'service ${n.service.name}'.`);const r={segments:[],children:[ej(n.service.match)],allows:[],functions:[...(n.imports??[]).flatMap(s=>s.functions.map(o=>({name:o,params:[],lets:[],body:{kind:"literal",value:null},unresolvedImport:s.module}))),...(n.functions??[]).map(Ey),...(n.service.functions??[]).map(Ey)]};return nj(r,new Map),{_root:r}}function nj(t,e){const n=new Map(e);for(const r of t.functions)n.set(r.name,r);t.visibleFuncs=n;for(const r of t.functions)r.declScope=n;for(const r of t.children)nj(r,n)}function Zd(t){return t?{size:t.size,contentType:t.contentType,metadata:t.customMetadata,name:i6(t.fullPath,t.bucket),bucket:t.bucket,timeCreated:t.timeCreated,updated:t.updated,generation:a_(t.generation),metageneration:a_(t.metageneration)}:null}function i6(t,e){if(t===void 0)return;const n=t.startsWith("/")?t.slice(1):t;if(e!==void 0){const s=`b/${e}/o/`;if(n.startsWith(s))return n.slice(s.length)}const r=/^b\/[^/]+\/o\//.exec(n);return r?n.slice(r[0].length):n}function a_(t){if(t===void 0)return;const e=Number(t);return Number.isFinite(e)?e:void 0}function a6(t){return{size:t.size,contentType:t.contentType,metadata:t.customMetadata}}function rj(t,e,n=new Date,r){const s=n.getTime(),o=o6(e.request.path),c=[],d=new Set(i_(e.request.method));function f(g,b,v){const w=l6(g.segments,b,v);if(!w)return!1;const _=w.params,k=w.left;if(k.length===0)for(const I of g.allows){const N=new Set(I.verbs.flatMap(i_));if(![...d].some(F=>N.has(F)))continue;let M;try{const F=I.condition?Ie(I.condition,{input:e,now:s,params:_,locals:{},funcs:g.visibleFuncs??new Map,depth:0,firestoreLookup:r}):!0;if(ut(F)){c.push(`match ${rm(g.segments)} ${e.request.method}: ${F.message}`);continue}M=Ga(F)}catch(F){if(F instanceof $e){c.push(`match ${rm(g.segments)} ${e.request.method}: ${F.message}`);continue}throw F}if(M)return!0;c.push(`match ${rm(g.segments)} ${e.request.method}: condition false`)}for(const I of g.children)if(f(I,k,_))return!0;return!1}const p=f(t._root,o,{});return!p&&c.length===0&&c.push(`no rule matches ${e.request.method} /${o.join("/")}`),{allowed:p,reasons:c}}function o6(t){return t.split("/").filter(e=>e.length>0)}function rm(t){return"/"+t.map(e=>e.kind==="literal"?e.value:e.kind==="param"?`{${e.name}}`:`{${e.name}=**}`).join("/")}function l6(t,e,n){let r=0;const s={...n};for(let o=0;o<t.length;o++){const c=t[o];if(c.kind==="wildcard")return s[c.name]=e.slice(r),{left:[],params:s};if(r>=e.length)return null;if(c.kind==="literal"){if(e[r]!==c.value)return null;r++}else s[c.name]=e[r],r++}return{left:e.slice(r),params:s}}class Dn{constructor(e){G(this,"message");this.message=e}}function ut(t){return t instanceof Dn}function o_(t,e){const n=t[e];return n===void 0?new Dn(`Property ${e} is undefined on object.`):n}function Ga(t){return ut(t)?!1:t!==!1&&t!==null&&t!==void 0&&!(typeof t=="number"&&Number.isNaN(t))}class $e extends Error{}const l_=20;function Ie(t,e){switch(t.kind){case"literal":return t.value;case"ident":return t.name in e.locals?e.locals[t.name]:t.name==="request"?f6(e.input,e.now):t.name==="resource"?d6(e.input.resource):t.name in e.params?e.params[t.name]:void 0;case"member":{const n=Ie(t.target,e);return ut(n)?n:n==null?new Dn("Null value error."):o_(n,t.name)}case"index":{const n=Ie(t.target,e);if(ut(n))return n;if(n==null)return new Dn("Null value error.");const r=Ie(t.index,e);return ut(r)?r:o_(n,String(r))}case"call":return c6(t,e);case"methodcall":return h6(t,e);case"path":throw new $e("a Firestore path literal is only valid as an argument to firestore.get()/exists()");case"unary":{const n=Ie(t.arg,e);return ut(n)?n:t.op==="-"?n instanceof Ke?new Ke(-n.value):typeof n!="number"?new Dn(`Unary '-' applied to ${ns(n)}.`):-n:!Ga(n)}case"ternary":{const n=Ie(t.cond,e);return ut(n)?n:Ga(n)?Ie(t.then,e):Ie(t.else,e)}case"in":{const n=Ie(t.element,e);if(ut(n))return n;const r=Ie(t.collection,e);return ut(r)?r:Array.isArray(r)?r.some(s=>Ol(s,n)):r!==null&&typeof r=="object"?typeof n=="string"&&Object.prototype.hasOwnProperty.call(r,n):new Dn(`'in' applied to ${ns(r)} (expected a list or map).`)}case"is":{const n=Ie(t.value,e);return ut(n)?n:u6(n,t.typeName)}case"list":{const n=[];for(const r of t.elements){const s=Ie(r,e);if(ut(s))return s;n.push(s)}return n}case"map":{const n={};for(const r of t.entries){const s=Ie(r.key,e);if(ut(s))return s;if(typeof s!="string")return new Dn(`Map literal key is ${ns(s)} (expected a string).`);const o=Ie(r.value,e);if(ut(o))return o;n[s]=o}return n}case"slice":{const n=Ie(t.target,e);if(ut(n))return n;const r=Ie(t.start,e);if(ut(r))return r;const s=Ie(t.end,e);return ut(s)?s:typeof r!="number"||typeof s!="number"||!Number.isInteger(r)||!Number.isInteger(s)?new Dn("Slice bounds must be integers."):Array.isArray(n)||typeof n=="string"?r<0||s<r||s>n.length?new Dn(`Slice bounds [${r}:${s}] out of range for ${ns(n)} of size ${n.length}.`):n.slice(r,s):new Dn(`Slice applied to ${ns(n)} (expected a list or string).`)}case"binary":{if(t.op==="&&"){const s=Ie(t.left,e);return ut(s)?s:Ga(s)?Ie(t.right,e):s}if(t.op==="||"){const s=Ie(t.left,e);if(ut(s)){const o=Ie(t.right,e);return Ga(o)?o:s}return Ga(s)?s:Ie(t.right,e)}const n=Ie(t.left,e);if(ut(n))return n;const r=Ie(t.right,e);if(ut(r))return r;switch(t.op){case"==":return Ol(n,r);case"!=":return!Ol(n,r);case"<":return Cu(n,r)<0;case">":return Cu(n,r)>0;case"<=":return Cu(n,r)<=0;case">=":return Cu(n,r)>=0;case"+":return Ci(n,r,(s,o)=>s+o);case"-":return Ci(n,r,(s,o)=>s-o);case"*":return Ci(n,r,(s,o)=>s*o);case"/":return Za(n)||Za(r)?Ci(n,r,(s,o)=>s/o):ei(r)===0?new Dn("Division by zero."):Ci(n,r,(s,o)=>Math.trunc(s/o));case"%":return Za(n)||Za(r)?Ci(n,r,(s,o)=>s%o):ei(r)===0?new Dn("Modulo by zero."):Ci(n,r,(s,o)=>s%o)}}}}function c6(t,e){const n=e.funcs.get(t.name);if(!n)throw new $e(`undefined function ${t.name}()`);if(n.unresolvedImport!==void 0)throw new $e(`function ${t.name}() is imported from '${n.unresolvedImport}', but import module resolution is not implemented`);if(n.params.length!==t.args.length)throw new $e(`function ${t.name}() expects ${n.params.length} argument(s), got ${t.args.length}`);const r=e.depth+1;if(r>l_)throw new $e(`function ${t.name}() exceeded max call depth ${l_}`);const s=t.args.map(d=>Ie(d,e)),o={};n.params.forEach((d,f)=>{o[d]=s[f]});const c={input:e.input,now:e.now,params:{},locals:o,funcs:n.declScope??new Map,depth:r,firestoreLookup:e.firestoreLookup};for(const d of n.lets)o[d.name]=Ie(d.value,c);return Ie(n.body,c)}function u6(t,e){switch(e){case"string":return typeof t=="string";case"bool":return typeof t=="boolean";case"int":return typeof t=="number"&&Number.isInteger(t);case"float":return t instanceof Ke||typeof t=="number"&&!Number.isInteger(t);case"number":return t instanceof Ke||typeof t=="number";case"list":return Array.isArray(t);case"map":return t!==null&&typeof t=="object"&&!Array.isArray(t);default:return new Dn(`'is ${e}' is not supported by the storage evaluator.`)}}function ei(t){if(typeof t=="number")return t;if(t instanceof Ke)return t.value}function Za(t){return t instanceof Ke}function Cu(t,e){const n=ei(t),r=ei(e);return n!==void 0&&r!==void 0?n-r:typeof t=="string"&&typeof e=="string"?t<e?-1:t>e?1:0:Number.NaN}function Ci(t,e,n){const r=ei(t),s=ei(e);if(r===void 0||s===void 0)return;const o=n(r,s);return Za(t)||Za(e)?new Ke(o):o}function d6(t){return t===null?null:{size:t.size,contentType:t.contentType,metadata:t.metadata,name:t.name,bucket:t.bucket,generation:t.generation,metageneration:t.metageneration,timeCreated:c_(t.timeCreated),updated:c_(t.updated)}}function c_(t){if(t===void 0)return;const e=Date.parse(t);return Number.isNaN(e)?void 0:e}function f6(t,e){return{auth:t.request.auth,resource:t.request.resource??null,method:t.request.method,path:t.request.path,time:e}}function h6(t,e){if(t.target.kind==="ident"&&t.target.name==="timestamp"&&!(t.target.name in e.locals)&&!(t.target.name in e.params))return g6(t,e);if(t.target.kind==="ident"&&t.target.name==="duration"&&!(t.target.name in e.locals)&&!(t.target.name in e.params))return y6(t,e);if(t.target.kind==="ident"&&t.target.name==="firestore"&&!(t.target.name in e.locals)&&!(t.target.name in e.params))return p6(t,e);if(t.method==="matches")return b6(t,e);if(t.method==="split")return v6(t,e);if(t.method==="size")return w6(t,e);throw new $e(`unsupported method .${t.method}()`)}function p6(t,e){if(t.method!=="get"&&t.method!=="exists")throw new $e(`unsupported method firestore.${t.method}()`);if(!e.firestoreLookup)throw new $e(`firestore.${t.method}() is unsupported here — no Firestore lookup capability is configured`);if(t.args.length!==1)throw new $e(`firestore.${t.method}() expects a single path argument`);const n=t.args[0];if(n.kind!=="path")throw new $e(`firestore.${t.method}() requires a /databases/.../documents/... path literal`);const r=m6(n,e);if(t.method==="exists")return e.firestoreLookup.exists(r);const s=e.firestoreLookup.get(r);if(s===null)throw new $e(`firestore.get() targeted a nonexistent document: ${r}`);return{data:s}}function m6(t,e){const n=t.segments.map(s=>{if(s.kind==="literal")return s.value;const o=Ie(s.expr,e);if(typeof o=="string")return o;if(typeof o=="number")return String(o);throw new $e(`Firestore path interpolation resolved to ${ns(o)} (expected a string)`)});if(n.length<4||n[0]!=="databases"||n[2]!=="documents")throw new $e(`malformed Firestore path — expected /databases/<db>/documents/... , got /${n.join("/")}`);const r=n.slice(3);if(r.length===0||r.length%2!==0)throw new $e(`Firestore path does not point at a document (needs an even segment count): ${r.join("/")}`);return r.join("/")}const u_={w:10080*60*1e3,d:1440*60*1e3,h:3600*1e3,m:60*1e3,s:1e3,ms:1,ns:1e-6};function y6(t,e){if(t.method!=="value")throw new $e(`unsupported duration.${t.method}()`);const n=t.args.map(c=>Ie(c,e));if(n.length!==2||typeof n[0]!="number"||typeof n[1]!="string")throw new $e("duration.value() expects (magnitude: number, unit: string)");const[r,s]=n,o=u_[s];if(o===void 0)throw new $e(`duration.value() got unknown unit "${s}" — expected one of ${Object.keys(u_).join(", ")}`);return r*o}function g6(t,e){const n=t.args.map(r=>Ie(r,e));if(t.method==="value"){if(n.length!==1||typeof n[0]!="number")throw new $e("timestamp.value() expects (epochMillis: number)");return n[0]}if(t.method==="date"){if(n.length!==3||!n.every(c=>typeof c=="number"))throw new $e("timestamp.date() expects (year, month, day) numbers");const[r,s,o]=n;return Date.UTC(r,s-1,o)}throw new $e(`unsupported timestamp.${t.method}()`)}function b6(t,e){const n=Ie(t.target,e);if(ut(n))return n;if(typeof n!="string")throw new $e(`matches() requires a string target, got ${ns(n)}`);if(t.args.length!==1)throw new $e("matches() expects a single pattern argument");const r=Ie(t.args[0],e);if(typeof r!="string")throw new $e("matches() pattern must be a string");const s=/\\[1-9]/.test(r),o=/\(\?<?[=!]/.test(r);if(s||o)throw new $e(`matches() pattern uses an RE2-unsupported construct (${s?"backreference":"lookaround"}) that production would reject`);let c;try{c=new RegExp(`^(?:${r})$`)}catch(d){throw new $e(`matches() invalid regex pattern: ${d.message}`)}return c.test(n)}function v6(t,e){const n=Ie(t.target,e);if(ut(n))return n;if(typeof n!="string")throw new $e(`split() requires a string target, got ${ns(n)}`);if(t.args.length!==1)throw new $e("split() expects a single pattern argument");const r=Ie(t.args[0],e);if(typeof r!="string")throw new $e("split() pattern must be a string");const s=/\\[1-9]/.test(r),o=/\(\?<?[=!]/.test(r);if(s||o)throw new $e(`split() pattern uses an RE2-unsupported construct (${s?"backreference":"lookaround"}) that production would reject`);let c;try{c=new RegExp(r)}catch(d){throw new $e(`split() invalid regex pattern: ${d.message}`)}return n.split(c)}function w6(t,e){const n=Ie(t.target,e);if(ut(n))return n;if(t.args.length!==0)throw new $e("size() expects no arguments");if(typeof n=="string"||Array.isArray(n))return n.length;if(n!==null&&typeof n=="object")return Object.keys(n).length;throw new $e(`size() requires a string, list, or map target, got ${ns(n)}`)}function Ol(t,e){if(t===e)return!0;if(t==null||e==null)return t==null&&e==null;const n=ei(t),r=ei(e);if(n!==void 0&&r!==void 0)return n===r;if(Array.isArray(t)&&Array.isArray(e))return t.length===e.length&&t.every((s,o)=>Ol(s,e[o]));if(typeof t=="object"&&typeof e=="object"&&!Array.isArray(t)&&!Array.isArray(e)){const s=Object.keys(t),o=Object.keys(e);return s.length===o.length&&s.every(c=>Object.prototype.hasOwnProperty.call(e,c)&&Ol(t[c],e[c]))}return!1}function ns(t){return t===null?"null":t===void 0?"undefined":t instanceof Ke?"float":typeof t}const x6="pyric-default",Wd=Symbol("pyric/storage/target");function Vi(t){var e;return((e=t.currentAuth)==null?void 0:e.call(t))??t.context.auth}class S6{constructor(e,n=null){G(this,"backend");G(this,"rules");this.backend=e,this.rules=n}}const d_=new WeakMap,f_=new WeakMap;function _6(t,e,n){const r=d_.get(t);if(r){const c=f_.get(t)??null;if(e.rules!==void 0&&e.rules!==c)throw new Error(`pyric/storage: ${n} received a rules source, but this sandbox's storage service is already open ${c===null?"without rules":"with a different rules source"} — rules are honored only on the FIRST storage call per Sandbox, so these rules would be silently discarded. Configure rules on the first storage call for this sandbox.`);return r}const s=e.rules?tj(e.rules):null,o=e6(e.dbName??J3(e.projectId)).then(c=>new S6(c,s));return d_.set(t,o),f_.set(t,e.rules??null),t.registerPersistableService("storage",{snapshot:()=>null,restore:()=>{},reset:async()=>{await(await o).backend.reset()}}),o}function sm(t){return t instanceof ho}const h_=new WeakMap,p_=new WeakMap;function E6(t,e={}){const n=!sm(t),r=sm(t)?t.sandbox:t,s=_6(r,e,"getAdminStorageSandbox");if(n){const g=p_.get(r);if(g)return g}const o=sm(t)?t:r.withAuth(null),c=o.operationContext.authLens.mode==="admin"?o:Wl(o,{source:o.operationContext.source,authLens:{mode:"admin"},...o.operationContext.planId===void 0?{}:{planId:o.operationContext.planId}}),d=h_.get(o);if(d)return d;const f={kind:"sandbox",sandbox:r,context:c,bucket:e.bucket??x6,servicePromise:s,admin:!0},p=Object.freeze({[Wd]:f});return h_.set(o,p),n&&p_.set(r,p),p}function yo(t,e){const n=Ld(e,ql(t.context.operationContext));return{...e,...ql(n),service:"storage"}}function ls(t){const e=t[Wd];if(!e)throw new TypeError("pyric/storage: not a FirebaseStorage handle — was it produced by getStorageSandbox?");return e}function tc(t){return ls(t).servicePromise}function A6(t){return`storage/${t}`}class nc extends Error{constructor(n,r){const s=A6(n);super(`${s}: ${r}`);G(this,"code");this.name="StorageError",this.code=s,Object.setPrototypeOf(this,nc.prototype)}}function sj(t){return new nc("object-not-found",`no object at "${t}".`)}function j6(t,e,n){return new nc("unauthorized",`${t} "${e}" denied by rules${n}.`)}function jg(t){return new nc("invalid-root-operation",`${t} cannot operate on the root reference.`)}function Hl(t,e){return C6(t)?(ls(t.storage),new Gl(t.storage,k6(t.fullPath,e??""))):(ls(t),new Gl(t,ij(e??"")))}class Gl{constructor(e,n){G(this,"storage");G(this,"bucket");G(this,"fullPath");this.storage=e;const r=ls(e);this.bucket=r.bucket,this.fullPath=n}get name(){if(this.fullPath==="")return"";const e=this.fullPath.lastIndexOf("/");return e===-1?this.fullPath:this.fullPath.slice(e+1)}get parent(){if(this.fullPath==="")return null;const e=this.fullPath.lastIndexOf("/"),n=e===-1?"":this.fullPath.slice(0,e);return new Gl(this.storage,n)}get root(){return this.fullPath===""?this:new Gl(this.storage,"")}toString(){return`gs://${this.bucket}/${this.fullPath}`}}function ij(t){return t===""?"":t.split("/").filter(e=>e.length>0).join("/")}function k6(t,e){const n=ij(e);return t===""?n:n===""?t:`${t}/${n}`}function C6(t){if(t===null||typeof t!="object"||Wd in t)return!1;const e=t;return typeof e.fullPath=="string"&&e.storage!==void 0}function rc(t,e,n,r){const s=(n==null?void 0:n.kind)==="sandbox"?yo(n,r):r;if((n==null?void 0:n.kind)==="sandbox"&&n.admin===!0){Nu(n,e,"not-applicable",void 0,"admin",!1,s);return}if(!t.rules){Nu(n,e,"allow",void 0,"user",!1,s);return}const o=n?N6(e,n.bucket):e,c=rj(t.rules,o,void 0,O6(n));if(!c.allowed){Nu(n,e,"deny",c.reasons,"user",!0,s);const d=c.reasons.length>0?` — ${c.reasons.join("; ")}`:"";throw j6(e.request.method,e.request.path,d)}Nu(n,e,"allow",c.reasons,"user",!0,s)}function N6(t,e){const n=t.request.path.replace(/^\/+/,"");return{...t,request:{...t.request,path:n===""?`b/${e}/o`:`b/${e}/o/${n}`}}}function Nu(t,e,n,r,s,o,c){if(t)try{Vs(t.sandbox,FE({service:"storage",method:e.request.method,path:e.request.path,auth:e.request.auth,result:n,origin:s,reasons:r,rulesDisposition:s==="admin"?{kind:"bypassed",reason:"admin"}:o?{kind:"evaluated",verdict:n==="deny"?"deny":"allow"}:{kind:"not-evaluated",reason:"no-rules"},rules:o?{engine:"storage",reason:r&&r.length>0?r.join("; "):void 0}:void 0}),{...c,service:"storage"})}catch{}}function O6(t){if(!t)return;const e=t.sandbox.admin;return{get:n=>e.getDocument(n),exists:n=>e.getDocument(n)!==null}}function aj(t){return{...t}}async function R6(t){T6(t,"getMetadata");const e=ls(t.storage),n=yo(e),r=await tc(t.storage),s=await r.backend.getMetadata(t.fullPath);if(rc(r,{request:{auth:Vi(e),method:"get",path:t.fullPath},resource:Zd(s)},e,n),!s)throw sj(t.fullPath);return aj(s)}function T6(t,e){if(t.fullPath==="")throw jg(e)}const D6="application/octet-stream";async function I6(t,e,n,r){$6(t,"uploadBytes");const s=ls(t.storage),o=yo(s,r),c=L6(e,n==null?void 0:n.contentType),d=M6({ref:t,blob:c,settable:n}),f=await tc(t.storage),p=await f.backend.getMetadata(t.fullPath);rc(f,{request:{auth:Vi(s),method:p?"update":"create",path:t.fullPath,resource:a6({size:d.size,contentType:d.contentType,customMetadata:d.customMetadata})},resource:Zd(p)},s,o),await f.backend.put(t.fullPath,c,d);try{Vs(s.sandbox,$d({service:"storage",op:"object_put",path:t.fullPath,auth:Vi(s),before:p??void 0,after:d,detail:{bucket:t.bucket,size:d.size,contentType:d.contentType,overwrite:p!=null}}),o)}catch{}return{ref:t,metadata:aj(d)}}function M6(t){const{ref:e,blob:n,settable:r}=t,s=(t.now??new Date).toISOString(),o=U6(t.now??new Date),c=e.name;return{fullPath:e.fullPath,name:c,bucket:e.bucket,generation:o,metageneration:"1",timeCreated:s,updated:s,size:n.size,contentType:(r==null?void 0:r.contentType)||n.type||D6,cacheControl:r==null?void 0:r.cacheControl,contentDisposition:r==null?void 0:r.contentDisposition,contentEncoding:r==null?void 0:r.contentEncoding,contentLanguage:r==null?void 0:r.contentLanguage,customMetadata:r==null?void 0:r.customMetadata}}function L6(t,e){return t instanceof Blob?e&&e!==t.type?new Blob([t],{type:e}):t:new Blob([t],{type:e??""})}function U6(t){return String(t.getTime())}function $6(t,e){if(t.fullPath==="")throw jg(e)}async function B6(t,e){return lj(t,"getBlob"),q6(t,e)}async function oj(t,e){lj(t,"deleteObject");const n=ls(t.storage),r=yo(n,e),s=await tc(t.storage),o=await s.backend.getMetadata(t.fullPath);rc(s,{request:{auth:Vi(n),method:"delete",path:t.fullPath},resource:Zd(o)},n,r),await s.backend.delete(t.fullPath);try{Vs(n.sandbox,$d({service:"storage",op:"object_delete",path:t.fullPath,auth:Vi(n),before:o??void 0,detail:{bucket:t.bucket}}),r)}catch{}}async function q6(t,e){const n=ls(t.storage),r=yo(n),s=await tc(t.storage),o=await s.backend.getMetadata(t.fullPath);rc(s,{request:{auth:Vi(n),method:"get",path:t.fullPath},resource:Zd(o)},n,r);const c=await s.backend.getBlob(t.fullPath);if(!c)throw sj(t.fullPath);return typeof e=="number"&&c.size>e?c.slice(0,e):c}function lj(t,e){if(t.fullPath==="")throw jg(e)}async function kg(t){const e=t.storage,n=ls(e),r=yo(n),s=await tc(e);rc(s,{request:{auth:Vi(n),method:"list",path:t.fullPath},resource:null},n,r);const o=t.fullPath===""?"":`${t.fullPath}/`,c=await s.backend.listByPrefix(o),d=[],f=new Set,p=[];for(const g of c){if(!g.fullPath.startsWith(o))continue;const b=g.fullPath.slice(o.length);if(b==="")continue;const v=b.indexOf("/");if(v===-1)d.push(Hl(e,g.fullPath));else{const w=b.slice(0,v),_=`${o}${w}`;f.has(_)||(f.add(_),p.push(Hl(e,_)))}}return p.sort((g,b)=>g.fullPath<b.fullPath?-1:g.fullPath>b.fullPath?1:0),{items:d,prefixes:p}}function F6(t,e,n){const r={name:n,options:structuredClone(e),automaticDataCollectionEnabled:!0};return GI(r,t),r}const z6=Object.freeze({source:Object.freeze({kind:"studio"}),authLens:Object.freeze({mode:"admin"})});function P6(t){return Wl(t.withAuth(null),z6)}const V6="pyric-studio";function cj(t,e){return t.listDocuments(e).map(({path:n,phantom:r})=>({path:n,phantom:r}))}let H6=0;function G6(t){const e=F6(t,{projectId:"pyric-studio"},`pyric-studio-${H6++}`),n=Wt(t),r=P6(t);return{sandbox:t,app:e,firestore:Vd(t),adminFirestore:bg(r),auth:XA(t),storage:E6(r),listRootCollections:()=>n.listRootCollections(),listSubcollections:s=>n.listSubcollections(s),listDocuments:s=>cj(n,s)}}function K6(t,e){const[n,r]=A.useState(!1),[s,o]=A.useState(null),c=A.useMemo(()=>VE(),[]),d=A.useMemo(()=>{try{return G6(c)}catch(p){return o(p instanceof Error?p:new Error(String(p))),null}},[c]);return A.useEffect(()=>{let p=!1;if(!t){r(!1);return}return c.enablePersistence({key:V6,injectedBackend:t}).then(()=>{p||r(!0)}).catch(g=>{p||o(g instanceof Error?g:new Error(String(g)))}),()=>{p=!0}},[c,t]),s?{status:"error",handles:null,error:s}:d?t!=null&&n||e==="ready"?{status:"ready",handles:d}:{status:"pending",handles:null}:{status:"error",handles:null,error:new Error("Studio: failed to construct the sandbox data handles.")}}function Y6(t){var n;const e=((n=t.rules)==null?void 0:n.engine)??t.service;return e==="rtdb"||e==="storage"?e:"firestore"}function Z6(t){switch(Y6(t)){case"firestore":return{impersonate:{kind:"live",tool:"worker setLens({mode:'as',uid}) → Firestore replay"},editedRuleset:{kind:"live",tool:"fork + firestore_lint_rules + firestore_simulate_rules"}};case"rtdb":return{impersonate:{kind:"pending",tool:"rtdb_simulate_access",hint:"RTDB re-runs through the local rules simulator as this user once the Studio worker exposes rtdb_simulate_access. This is a simulation, not a live re-issue — RTDB has no live local enforcement path."},editedRuleset:{kind:"pending",tool:"RulesEvaluator.setRules + rtdb_simulate_access",hint:"Editing the RTDB ruleset re-simulates the write once the worker exposes the RTDB simulator. Note: there is no whole-ruleset RTDB linter yet (rtdb_build_expression lints a single expression)."}};case"storage":return{impersonate:{kind:"absent",missingTool:"storage_simulate_rules",hint:"Storage rules are enforced and evaluated allow/deny events open this inspector, but Studio has no Storage replay operation to re-run this request as a user."},editedRuleset:{kind:"absent",missingTool:"storage_simulate_rules + edited-rules deployment seam",hint:"Storage rules are enforced and denial events are inspectable. Testing an edit still needs a Studio Storage replay operation plus a temporary edited-rules deployment seam."}}}}function W6(t){var e;return((e=DE(t))==null?void 0:e.rules.kind)==="evaluated"}function Q6(t){return"service"in t&&typeof t.service=="string"?t.service:"firestore"}function J6(t){const e=t.request;if(e){if("resourceData"in e&&e.resourceData!==void 0)return e.resourceData;if("data"in e)return e.data}}function X6(t){const e=[];for(const n of t)W6(n)&&e.push(e4(n));return e.sort((n,r)=>r.at-n.at)}function e4(t){const e={id:t.id,at:t.at,result:t.result==="allow"?"allow":t.result==="unsupported"?"unsupported":"deny",method:t.method,service:Q6(t),path:t.path??"(service)",auth:t.auth,reasons:t.reasons??[],origin:t.origin,unsupported:t.result==="unsupported"};"matchedRule"in t&&t.matchedRule&&(e.matchedRule=t.matchedRule),"evaluatedRule"in t&&t.evaluatedRule&&(e.evaluatedRule=t.evaluatedRule),"rules"in t&&t.rules&&(e.rules=t.rules);const n=J6(t);return n!==void 0&&(e.resourceData=n),t.resourceBefore&&(e.resourceBefore={data:t.resourceBefore.data,exists:t.resourceBefore.exists}),e}const m_=/^Rule #(\d+) \(([^)]+)\) → (ALLOW|deny|unsupported)/;function t4(t){var n;const e=((n=t.rules)==null?void 0:n.engine)??t.service;return e==="rtdb"||e==="storage"?e:"firestore"}function n4(t){var n;if(((n=t.rules)==null?void 0:n.reason)==="Validation rule evaluated to false")return"validate";const e=t.method;return e==="get"||e==="list"||e==="listen"?"read":"write"}function r4(t){var s;const e=t4(t),n=t.reasons.filter(o=>m_.test(o)),r=t.reasons.filter(o=>!m_.test(o));if(t.unsupported)return{headline:`The simulator hit an unmodelled rules feature evaluating ${t.method} ${t.path}.`,engine:e,ruleLines:n,otherLines:r,implicitDeny:!1};if(t.result==="allow"){if(e==="firestore"&&t.matchedRule){const c=t.matchedRule,d=`Rule #${c.ruleIndex} (${c.operations.join(", ")})`;return{headline:`${d} allowed ${t.method} on ${t.path}.`,engine:e,ruleNode:d,ruleLines:n,otherLines:r,implicitDeny:!1}}return!t.matchedRule&&!t.rules&&!t.evaluatedRule&&n.length===0?{headline:`This ${t.method} on ${t.path} succeeded, but no rules evaluation was recorded for it — rules likely never ran (an admin/bypass operation from a worker that didn't stamp its lens, or a pre-provenance event).`,engine:e,ruleLines:n,otherLines:r,implicitDeny:!1,noEvaluation:!0}:{headline:`Rules allowed ${t.method} on ${t.path}.`,engine:e,...(s=t.rules)!=null&&s.matchedRule?{ruleExpression:t.rules.matchedRule}:{},ruleLines:n,otherLines:r,implicitDeny:!1}}return e==="rtdb"?i4(t,n,r):e==="storage"?a4(t,n,r):s4(t,n,r)}function s4(t,e,n){const r=!t.matchedRule;let s,o;if(r)s=`No rule allowed ${t.method} on ${t.path}: implicit deny (no matching \`allow\`).`;else{const c=t.matchedRule;o=`Rule #${c.ruleIndex} (${c.operations.join(", ")})`,s=`${o} denied ${t.method} on ${t.path}.`}return{headline:s,engine:"firestore",ruleNode:o,ruleLines:e,otherLines:n,implicitDeny:r}}function i4(t,e,n){const r=t.rules,s=n4(t),o=!(r!=null&&r.matchedPath)||(r==null?void 0:r.errorCode)==="NO_MATCHING_RULE",c=r!=null&&r.pathVariableBindings&&Object.keys(r.pathVariableBindings).length>0?r.pathVariableBindings:void 0;let d,f;return o?d=`No \`.${s}\` rule granted ${t.method} on ${t.path}: RTDB implicit deny (no rule matched).`:s==="validate"?(f=`${r.matchedPath} .validate`,d=`The \`.validate\` rule at \`${r.matchedPath}\` rejected the proposed value for ${t.method} ${t.path}.`):(f=`${r.matchedPath} .${s}`,d=`The \`.${s}\` rule at \`${r.matchedPath}\` evaluated false for ${t.method} ${t.path}.`),{headline:d,engine:"rtdb",ruleNode:f,ruleExpression:r==null?void 0:r.matchedRule,phase:s,bindings:c,ruleLines:e,otherLines:n,implicitDeny:o}}function a4(t,e,n){const r=t.reasons.find(d=>/^match\s/.test(d)),o=t.reasons.some(d=>/^no rule matches/.test(d))||!r;return{headline:o?`No \`match\` block allowed ${t.method} on ${t.path}: Storage implicit deny (no rule matched).`:`A \`match\` block condition evaluated false for ${t.method} on ${t.path}.`,engine:"storage",ruleNode:o?void 0:r,ruleLines:e,otherLines:n,implicitDeny:o}}function o4(t){var e;return!!((e=t.auth)!=null&&e.uid)}function l4(t){return t.skipped?"skipped":t.error!==void 0?"error":t.value===!0?"true":t.value===!1?"false":"value"}function c4(t){var s;const e=(s=t.evaluatedRule)==null?void 0:s.expressionTrace;if(!e||e.length===0)return[];const n=e.map(o=>({source:o.source,outcome:l4(o),...o.value!==void 0?{value:o.value}:{},...o.error!==void 0?{error:o.error}:{},...o.letBinding?{letBinding:o.letBinding.name}:{},...o.inlinedFrom?{inlinedFrom:o.inlinedFrom.name}:{},depth:0,children:[]})),r=[];return e.forEach((o,c)=>{o.parent===null||o.parent===void 0||!n[o.parent]?r.push(n[c]):(n[c].depth=n[o.parent].depth+1,n[o.parent].children.push(n[c]))}),r}function u4(t){const e=[{name:"request.auth",present:t.auth!==null,value:t.auth,...t.auth===null?{absentNote:"request.auth was null — the request was unauthenticated."}:{}},{name:"request.method",present:!0,value:t.method},{name:"request.path",present:!0,value:t.path}],n=t.method==="get"||t.method==="list"||t.method==="listen";return e.push({name:"request.resource.data",present:t.resourceData!==void 0,value:t.resourceData??null,...t.resourceData===void 0?{absentNote:n?"A read carries no proposed write, so request.resource.data is absent.":"No proposed write payload was captured for this denial."}:{}}),e.push({name:"resource",present:t.resourceBefore!==void 0,value:t.resourceBefore?{data:t.resourceBefore.data,exists:t.resourceBefore.exists}:null,...t.resourceBefore===void 0?{absentNote:"The rule evaluated no existing document (e.g. a list/query, or the doc did not exist)."}:{}}),e}function d4(t){const e=Wt(t.sandbox);return{sandbox:t.sandbox,app:t.app,firestore:t.firestore,adminFirestore:t.adminFirestore,auth:t.auth,storage:t.storage,listRootCollections:()=>e.listRootCollections(),listSubcollections:n=>e.listSubcollections(n),listDocuments:n=>cj(e,n)}}function ri(){const t=cs(),e=rr(),n=e.status==="ready"?e.env.persistence:void 0,r=K6(n,e.status),s=e.status==="ready"?e.env.live:void 0,o=f4(s);return A.useMemo(()=>{switch(t.status){case"ready":return{status:"ready",handles:d4(t.handles)};case"pending":return{status:"pending",handles:null};case"error":return{status:"error",handles:null,error:t.error};case"disabled":{if(s&&r.status==="ready"){const c=s.db;return{status:"ready",firestoreApi:s.firestoreApi,authApi:s.authApi,storageApi:s.storageApi,handles:{...r.handles,firestore:c,adminFirestore:c,auth:s.auth,storage:s.storage,listRootCollections:()=>o,listSubcollections:d=>s.listSubcollections(d),listDocuments:d=>s.listDocuments(d)}}}return r}}},[t,r,s,o])}function f4(t){const[e,n]=A.useState([]);return A.useEffect(()=>{if(!t){n([]);return}let r=!0;const s=()=>{t.listRootCollections().then(c=>{r&&n(c)}).catch(()=>{})};try{t.setLens({mode:"admin"})}catch{}s();const o=t.feed.subscribe(()=>s());return()=>{r=!1,o()}},[t]),e}const _d=500;function im(t){return t.length>_d?t.slice(-_d):t}function sc(){var d;const t=cs(),e=rr(),n=e.status==="ready"?(d=e.env.live)==null?void 0:d.feed:void 0,r=t.status==="ready",[s,o]=A.useState([]);A.useEffect(()=>{if(r||!n){o([]);return}return o(im(n.history())),n.subscribe(p=>o(g=>im(dO(g,p))))},[r,n]);const c=A.useMemo(()=>r?im(t.events):[],[r,t]);return r?c:s}function h4(t){return t.kind==="request"||t.kind==="operation"}function p4(t){const e=DE(t);if(!e)throw new Error("Studio traffic adapter received a non-operation event");return t.kind==="request"?{...t,operationContext:e.context,rulesDisposition:e.rules}:{kind:"operation",service:t.service,id:t.id,at:t.at,durationMs:t.durationMs,method:t.method,path:t.path??"(service)",auth:t.auth,result:t.result,reasons:t.reasons??[],request:t.request,resourceBefore:t.resourceBefore,resourceAfter:t.resourceAfter,origin:t.origin,groupId:t.groupId,groupKind:t.groupKind,triggeredBy:t.triggeredBy,operationContext:e.context,rulesDisposition:e.rules}}function m4(){const t=sc();return A.useMemo(()=>t.filter(h4).map(p4),[t])}function y4(){const t=sc();return A.useMemo(()=>X6(t),[t])}function g4(){const t=ri();return A.useCallback(async e=>{var d,f;if(t.status!=="ready")throw new Error("No sandbox available to seed.");const n=t.handles.adminFirestore,r=((d=t.firestoreApi)==null?void 0:d.doc)??ur,s=((f=t.firestoreApi)==null?void 0:f.setDoc)??Pl;let o=0;const c=[];for(const p of e)try{await s(r(n,p.path),p.data),o++}catch(g){c.push(`${p.path}: ${g instanceof Error?g.message:String(g)}`)}return{written:o,errors:c}},[t])}function b4(){const t=ri();return A.useCallback(async e=>{var c;if(t.status!=="ready")throw new Error("No sandbox available to seed auth.");const n=t.handles.auth,r=((c=t.authApi)==null?void 0:c.createUser)??lr.createUser;let s=0;const o=[];for(const d of e)try{await r(n,d.request),s++}catch(f){const p=d.request.uid??d.request.email??"<auto>";o.push(`${p}: ${f instanceof Error?f.message:String(f)}`)}return{created:s,errors:o}},[t])}function v4(){const t=ri(),e=rr(),n=e.status==="ready"?e.env.live:void 0;return A.useCallback(async()=>{if(t.status!=="ready")throw new Error("No sandbox to clear.");const r=[];try{const s=n?await n.resetAll():await t.handles.sandbox.resetAll();r.push(...(s==null?void 0:s.errors)??[])}catch(s){r.push(`reset: ${s instanceof Error?s.message:String(s)}`)}return{errors:r}},[t,n])}function w4(){const t=v4(),e=g4(),n=b4(),r=cs();return A.useCallback(async()=>{const s=await t();if(r.status==="ready"){const{applySeed:o,deploySeedRules:c}=await p1(async()=>{const{applySeed:d,deploySeedRules:f}=await import("./seed-D_UjxfOU.js");return{applySeed:d,deploySeedRules:f}},[]);c(r.handles.sandbox),await o(r.handles)}else try{const o=await fetch("/__pyric/init.json").then(f=>f.ok?f.json():null),c=o==null?void 0:o.seed;c&&await e(Object.entries(c).map(([f,p])=>({path:f,data:p})));const d=o==null?void 0:o.authUsers;Array.isArray(d)&&await n(d.map(f=>({request:f})))}catch(o){s.errors.push(`reseed: ${o instanceof Error?o.message:String(o)}`)}return s},[t,e,n,r])}function x4(){const t=cs(),e=rr(),n=e.status==="ready"?e.env.live:void 0,r=t.status==="ready"?t.handles.sandbox:null;return A.useCallback(async()=>r?r.snapshot():n?n.getSnapshot():null,[r,n])}function Cg(){const t=rr(),e=t.status==="ready"?t.env.live:void 0,[n,r]=A.useState("");return A.useEffect(()=>{if(!e){r("");return}let s=!1;return e.instanceId().then(o=>{s||r(o)}),()=>{s=!0}},[e]),n}function S4(){const t=rr(),e=t.status==="ready"?t.env.live:void 0;return A.useCallback(async()=>e?e.exportState():null,[e])}function _4(){const t=rr(),e=t.status==="ready"?t.env.live:void 0;return A.useCallback(async n=>e?(await e.importState(n),!0):!1,[e])}function E4(){const t=rr(),e=t.status==="ready"?t.env.live:void 0,[n,r]=A.useState([]),s=A.useCallback(async()=>{r(e?await e.listBranches():[])},[e]);A.useEffect(()=>{s()},[s]);const o=A.useCallback(async f=>{e&&(await e.saveBranch(f),await s())},[e,s]),c=A.useCallback(async f=>{e&&await e.switchBranch(f)},[e]),d=A.useCallback(async f=>{e&&(await e.deleteBranch(f),await s())},[e,s]);return{branches:n,save:o,switchTo:c,remove:d}}function A4(){const t=cs(),e=t.status==="ready",[n,r]=A.useState("");return A.useEffect(()=>{if(e)return;let s=!0;return fetch("/__pyric/init.json").then(o=>o.ok?o.json():null).then(o=>{s&&o&&typeof o.rules=="string"&&r(o.rules)}).catch(()=>{}),()=>{s=!1}},[e]),A.useMemo(()=>{if(t.status!=="ready")return n;try{return Wt(t.handles.sandbox).getRules()}catch{return""}},[t,n])}function j4(t){let e=!0;return n=>{const r=e;e=!1,t(s=>C4(s,n,r))}}function k4(t){const e=new Map;for(const n of t)e.set(by(n),n);return[...e.values()]}function C4(t,e,n){return k4(n?e:[...t??[],...e])}const N4=3e4;function uj(){const t=ri(),e=rr(),[n,r]=A.useState(null),[s,o]=A.useState(!1),c=A.useRef(!1),d=A.useRef(t);d.current=t;const f=e.status==="ready"?e.env.live:void 0,p=A.useRef(f);p.current=f;const g=A.useRef(null),b=A.useRef(0),v=A.useRef(null),w=A.useRef(0),_=A.useCallback(I=>{var O,T,P,$,K,W,se;const N=d.current;if(N.status!=="ready")return;const R=++b.current;c.current=!0,o(!0);const M=N.handles,F=M.adminFirestore,D=((O=N.firestoreApi)==null?void 0:O.collection)??Ui,C=((T=N.firestoreApi)==null?void 0:T.query)??Vl,L=((P=N.firestoreApi)==null?void 0:P.getDocs)??zl,U=(($=N.firestoreApi)==null?void 0:$.limit)??vd,H=((K=N.storageApi)==null?void 0:K.ref)??Hl,z=((W=N.storageApi)==null?void 0:W.listAll)??kg,q=((se=N.authApi)==null?void 0:se.listUsers)??lr.listUsers,x={listRootCollections:()=>M.listRootCollections(),listDocumentPaths:async(B,ee)=>(await L(C(D(F,B),U(ee)))).docs.slice(0,ee).map(le=>`${B}/${le.id}`),listSubcollections:B=>Promise.resolve(M.listSubcollections(B)),listUsers:async B=>(await Promise.resolve(q(M.auth))).slice(0,B).map(ae=>({uid:ae.uid,email:ae.email??null})),listStorageObjectPaths:B=>j3(H(M.storage,""),z,{maxObjects:B,maxListCalls:vy.storageListCalls}),listRtdbTopLevelKeys:async()=>{const B=p.current;if(!B)return[];const ee=Date.now()-w.current<N4;if(v.current!==null&&ee&&!(I!=null&&I.rtdbLikely))return v.current;const ae=await B.readRtdbState(),le=ae===null||typeof ae!="object"||Array.isArray(ae)?[]:Object.keys(ae);return v.current=le,w.current=Date.now(),le}},E=j4(B=>r(B));B3(x,vy,B=>{R===b.current&&E(B)}).catch(()=>{}).finally(()=>{if(R===b.current&&(c.current=!1,o(!1),r(B=>B??[]),g.current)){const B=g.current;g.current=null,_(B)}})},[]),k=A.useCallback(I=>{if(d.current.status==="ready"){if(c.current){g.current={...g.current,...I};return}_(I)}},[_]);return A.useEffect(()=>{t.status==="ready"&&n===null&&!c.current&&_()},[t,n,_]),{entries:n,building:s,ensure:k}}const O4=150;function R4(t){return t.startsWith("/")||/rtdb/i.test(t)}function dj({autoFocus:t,onNavigated:e,onEscape:n,exposeFocus:r}){const[s,o]=A.useState(""),[c,d]=A.useState(""),[f,p]=A.useState(0),[g,b]=A.useState(!1),v=A.useRef(null),{entries:w,building:_,ensure:k}=uj();A.useEffect(()=>{if(r)return r(()=>{var D;return(D=v.current)==null?void 0:D.focus()}),()=>r(null)},[r]),A.useEffect(()=>{var D;t&&((D=v.current)==null||D.focus())},[t]),A.useEffect(()=>{const D=setTimeout(()=>d(s),O4);return()=>clearTimeout(D)},[s]);const I=A.useMemo(()=>WS(c,Pi,w??[]),[c,w]),N=A.useMemo(()=>QS(I),[I]);A.useEffect(()=>{p(D=>N.length===0?0:Math.min(D,N.length-1))},[N.length]);const R=D=>{D&&(o(""),d(""),b(!1),Jn(D.target),e==null||e(D.target))},M=()=>{if(s===c){R(N[f]??N[0]);return}const D=QS(WS(s,Pi,w??[]));R(D[0])};let F=0;return h.jsxs("div",{className:"studio-home__command",children:[h.jsx("div",{className:"studio-home__command-row",children:h.jsx("input",{ref:v,className:"studio-home__command-input",type:"text",value:s,placeholder:"Jump to a surface, collection, doc, user, or object…","aria-label":"Command input",role:"combobox","aria-expanded":g&&N.length>0,"aria-autocomplete":"list",onFocus:()=>{k(),b(!0)},onBlur:()=>b(!1),onChange:D=>{const C=D.target.value;o(C),b(!0),R4(C)&&k({rtdbLikely:!0})},onKeyDown:D=>{if(D.key==="ArrowDown")D.preventDefault(),p(C=>Math.min(C+1,Math.max(N.length-1,0)));else if(D.key==="ArrowUp")D.preventDefault(),p(C=>Math.max(C-1,0));else if(D.key==="Enter")M();else if(D.key==="Escape"){if(n){n();return}o(""),d(""),b(!1)}}})}),g&&!I.length&&_&&w===null?h.jsx("div",{className:"studio-home__command-results",role:"status","aria-live":"polite",children:h.jsx("span",{className:"studio-home__command-group-title",children:"Indexing sandbox…"})}):null,g&&I.length?h.jsx("div",{className:"studio-home__command-results",role:"listbox","aria-label":"Suggestions",onMouseDown:D=>D.preventDefault(),children:I.map(D=>{const C=F;return F+=D.results.length,h.jsxs("div",{className:"studio-home__command-group",children:[h.jsx("span",{className:"studio-home__command-group-title","aria-hidden":"true",children:D.title}),h.jsx("ul",{className:"studio-home__command-group-list",children:D.results.map((L,U)=>{const H=C+U;return h.jsx("li",{children:h.jsxs("button",{type:"button",role:"option","aria-selected":H===f,className:"studio-home__command-result","data-active":H===f?"true":void 0,onMouseEnter:()=>p(H),onClick:()=>R(L),children:[h.jsx("span",{className:"studio-home__command-label",children:L.label}),h.jsx("span",{className:"studio-home__command-sub",children:L.hint})]})},L.id)})})]},D.kind)})}):null]})}function T4({onClose:t}){const e=A.useRef(null);return A.useEffect(()=>(e.current=document.activeElement,()=>{const n=e.current;n instanceof HTMLElement&&n.focus()}),[]),A.useEffect(()=>{const n=r=>{r.key==="Escape"&&t()};return window.addEventListener("keydown",n),()=>window.removeEventListener("keydown",n)},[t]),h.jsx("div",{className:"studio__cmdk-backdrop",onMouseDown:t,children:h.jsx("div",{className:"studio__cmdk",role:"dialog","aria-modal":"true","aria-label":"Command",onMouseDown:n=>n.stopPropagation(),children:h.jsx(dj,{autoFocus:!0,onEscape:t,onNavigated:t})})})}const D4={status:"loading",payload:null},Ou={status:"absent",payload:null};let Ed=D4,y_=!1;const Ay=new Set;function Ru(t){Ed=t;for(const e of Ay)e()}function I4(){if(!y_){if(y_=!0,typeof fetch>"u"){Ed=Ou;return}fetch("/__pyric/init.json").then(async t=>{if(!t.ok||!(t.headers.get("content-type")??"").includes("json"))return Ru(Ou);const n=await t.json();Ru({status:"ready",payload:n})}).catch(()=>Ru(Ou))}}function M4(t){return Ay.add(t),I4(),()=>Ay.delete(t)}function Qd(){return A.useSyncExternalStore(M4,()=>Ed,()=>Ed)}function L4(t){return t.kind==="absent"?"absent":t.sandboxConnected?"available":"idle"}function U4(t,e){if(t!==200||typeof e!="object"||e===null)return{kind:"absent"};const n=e.sandboxConnected;return typeof n!="boolean"?{kind:"absent"}:{kind:"json",sandboxConnected:n}}async function $4(t){try{const e=await t("/__pyric/health");return e.ok?(e.headers.get("content-type")??"").includes("json")?U4(e.status,await e.json()):{kind:"absent"}:{kind:"absent"}}catch{return{kind:"absent"}}}function B4(t=5e3){const[e,n]=A.useState("checking");return A.useEffect(()=>{if(typeof fetch>"u"){n("absent");return}let r=!0,s=null;const o=async()=>{const p=L4(await $4(fetch));return r&&(n(p),p==="absent"&&s&&(clearInterval(s),s=null)),p},c=()=>typeof document>"u"||document.visibilityState!=="hidden",d=()=>{s||(s=setInterval(()=>{c()&&o()},t))},f=()=>{c()&&o()};return o().then(p=>{r&&p!=="absent"&&d()}),typeof document<"u"&&document.addEventListener("visibilitychange",f),()=>{r=!1,s&&clearInterval(s),typeof document<"u"&&document.removeEventListener("visibilitychange",f)}},[t]),e}const q4="Only pages in this browser profile, on this origin, connected to this shared sandbox worker. Other profiles, incognito windows, origins, or worker names are not visible.";function F4(t,e){const n=Math.max(0,e-t);return n<5e3?"just now":n<6e4?`${Math.floor(n/1e3)}s ago`:n<36e5?`${Math.floor(n/6e4)}m ago`:`${Math.floor(n/36e5)}h ago`}function z4(t){return t==="studio"?"Studio":"App"}function P4(t,e,n=Date.now()){const r=t.clients.length,s=t.clients.map(c=>({clientId:c.clientId,kindLabel:z4(c.kind),route:c.route||"/",visibilityLabel:c.visibility==="hidden"?"Hidden":"Visible",isThisPage:c.clientId===e,freshnessLabel:F4(c.lastSeen,n)}));s.sort((c,d)=>c.isThisPage!==d.isThisPage?c.isThisPage?-1:1:c.kindLabel!==d.kindLabel?c.kindLabel==="Studio"?-1:1:c.route.localeCompare(d.route));const o=s.filter(c=>!c.isThisPage).length;return{count:r,chipLabel:r===1?"1 page connected":`${r} pages connected`,prominent:r>1,clients:s,boundaryCopy:q4,otherCount:o}}function V4(){const t=rr(),e=t.status==="ready"&&t.env.live?t.env.live:null,[n,r]=A.useState(null);return A.useEffect(()=>{if(!e){r(null);return}const s=e.presenceClientId;return e.subscribePresence(o=>{r(P4(o,s))})},[e]),n}function H4(){const t=rr(),e=Qd(),n=B4(),r=V4(),[s,o]=A.useState(!1),c=A.useRef(null),f=e.status==="ready"&&t.status==="ready"&&!t.env.live,p=t.status==="error",g=p?"backend error":f?"worker unreachable":null,b=n==="available";return A.useEffect(()=>{if(!s)return;const v=w=>{var _;w.key==="Escape"&&(o(!1),(_=c.current)==null||_.focus())};return document.addEventListener("keydown",v),()=>document.removeEventListener("keydown",v)},[s]),h.jsxs("div",{className:"studio__status","aria-label":"Studio status",children:[g?h.jsxs("a",{className:"studio-chip studio-chip--warn",href:Gd({tab:"settings"}),title:p?t.error.message:"Served, but the shared sandbox worker is not reachable; data views may be stale. Open Settings diagnostics.",onClick:v=>{v.preventDefault(),Jn({tab:"settings"})},children:[h.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),g]}):null,r&&r.count>0?h.jsxs("span",{className:"studio-presence",children:[h.jsxs("button",{ref:c,type:"button",className:r.prominent?"studio-chip studio-chip--live studio-presence__trigger":"studio-chip studio-presence__trigger","aria-haspopup":"dialog","aria-expanded":s,"aria-controls":"studio-presence-panel",title:r.otherCount>0?`${r.chipLabel}. ${r.otherCount} other page${r.otherCount===1?"":"s"} can keep the worker alive.`:`${r.chipLabel}. Expand for details.`,onClick:()=>o(v=>!v),children:[h.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),r.chipLabel]}),s?h.jsxs(h.Fragment,{children:[h.jsx("div",{className:"studio-presence__backdrop",onMouseDown:()=>o(!1)}),h.jsxs("div",{id:"studio-presence-panel",className:"studio-presence__panel",role:"dialog","aria-label":"Connected pages",children:[h.jsx("p",{className:"studio-presence__lead",children:r.count===1?"This page is the only connection to the shared sandbox worker.":`${r.count} pages share this sandbox worker. Closing this page alone will not restart it.`}),h.jsx("ul",{className:"studio-presence__list",children:r.clients.map(v=>h.jsxs("li",{className:"studio-presence__item",children:[h.jsxs("div",{className:"studio-presence__item-head",children:[h.jsx("span",{className:"studio-presence__kind",children:v.kindLabel}),v.isThisPage?h.jsx("span",{className:"studio-presence__this",children:"This page"}):null]}),h.jsx("div",{className:"studio-presence__route",title:v.route,children:v.route}),h.jsxs("div",{className:"studio-presence__meta",children:[v.visibilityLabel," · ",v.freshnessLabel]})]},v.clientId))}),h.jsx("p",{className:"studio-presence__boundary",children:r.boundaryCopy})]})]}):null]}):null,b?h.jsxs("span",{className:"studio-chip studio-chip--live",title:"MCP bridge available — a sandbox peer is connected; external agents can reach this sandbox.",children:[h.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),"MCP bridge"]}):null]})}function G4(t,e){const n=t.triggeredBy,r=e.triggeredBy;return!n&&!r?!0:!n||!r?!1:n.method===r.method&&n.path===r.path}function g_(t,e,n){let r=0;for(const s of n)s.result==="deny"&&r++;return{type:"group",kind:t,key:e,events:n,count:n.length,denies:r}}function K4({events:t,groupBatches:e=!0,groupListenerRuns:n=!0}){return A.useMemo(()=>{const r=[];let s=0;for(;s<t.length;){const o=t[s];if(e&&o.groupId){let c=s+1;for(;c<t.length&&t[c].groupId===o.groupId;)c++;const d=t.slice(s,c),f=o.origin==="transaction"?"transaction":"batch";r.push(g_(f,o.groupId,d)),s=c;continue}if(n&&o.origin==="listener"){let c=s+1;for(;c<t.length&&t[c].origin==="listener"&&!t[c].groupId&&G4(t[c],o);)c++;const d=t.slice(s,c);if(d.length>1){const f=o.triggeredBy?`${o.triggeredBy.method}:${o.triggeredBy.path}`:"unknown";r.push(g_("listener-run",`listener-run:${f}:${s}`,d))}else r.push({type:"single",event:o});s=c;continue}r.push({type:"single",event:o}),s++}return{items:r}},[t,e,n])}const Y4={buckets:[],total:0,denies:0,maxCount:0,outOfWindow:0};function Z4({events:t,window:e,bucketCount:n=30}){return A.useMemo(()=>W4(t,e,n),[t,e.start,e.end,n])}function W4(t,e,n=30){const r=e.end-e.start;if(n<=0||r<=0)return Y4;const s=r/n,o=new Array(n).fill(0),c=new Array(n).fill(0);let d=0,f=0,p=0;for(const v of t){const w=v.at;if(w<e.start||w>=e.end){p++;continue}let _=Math.floor((w-e.start)/s);_>=n&&(_=n-1),o[_]++,d++,v.result==="deny"&&(c[_]++,f++)}let g=0;for(const v of o)v>g&&(g=v);return{buckets:o.map((v,w)=>{const _=c[w];return{index:w,start:e.start+w*s,end:e.start+(w+1)*s,count:v,denies:_,allows:v-_,heightRatio:g===0?0:v/g,denyHeightRatio:g===0?0:_/g}}),total:d,denies:f,maxCount:g,outOfWindow:p}}const Q4=new Set(["get","list"]),J4=new Set(["create","update","set"]),X4=new Set(["delete","remove"]),eB=[{key:"reads",label:"Read ops"},{key:"writes",label:"Writes"},{key:"deletes",label:"Deletes"}],tB=[{key:"allows",label:"Allows"},{key:"denies",label:"Denies"},{key:"errors",label:"Errors"}];function Jd(t){return t.origin==="admin"}function nB(t,e=Jd){return t.result==="allow"||e(t)?Q4.has(t.method)?"reads":J4.has(t.method)?"writes":X4.has(t.method)?"deletes":null:null}function rB(t,e=Jd){return e(t)?null:t.result==="allow"?"allows":t.result==="deny"?"denies":t.result==="error"?"errors":null}const sB=t=>({points:[],series:t.map(e=>({key:e.key,label:e.label,values:[],total:0})),maxValue:0});function fj(t,e,n,r,s){const o=e.end-e.start;if(n<=0||o<=0)return sB(r);const c=o/n,d=new Map(r.map(v=>[v.key,new Array(n).fill(0)])),f=new Map(r.map(v=>[v.key,0]));for(const v of t){const w=v.at;if(w<e.start||w>=e.end)continue;const _=s(v);if(_==null)continue;let k=Math.floor((w-e.start)/c);k>=n&&(k=n-1);const I=d.get(_);I[k]++,f.set(_,(f.get(_)??0)+1)}let p=0;for(const v of d.values())for(const w of v)w>p&&(p=w);const g=new Array(n);for(let v=0;v<n;v++)g[v]={index:v,start:e.start+v*c,end:e.start+(v+1)*c};const b=r.map(v=>({key:v.key,label:v.label,values:d.get(v.key),total:f.get(v.key)??0}));return{points:g,series:b,maxValue:p}}function iB(t,e,n=24,r=Jd){return fj(t,e,n,eB,s=>nB(s,r))}function aB(t,e,n=24,r=Jd){return fj(t,e,n,tB,s=>rB(s,r))}function oB({events:t,window:e,bucketCount:n=24,isAdmin:r}){return A.useMemo(()=>iB(t,e,n,r),[t,e.start,e.end,n,r])}function lB({events:t,window:e,bucketCount:n=24,isAdmin:r}){return A.useMemo(()=>aB(t,e,n,r),[t,e.start,e.end,n,r])}function Ja({children:t,kind:e,className:n,ariaLabel:r}){return h.jsx("span",{"data-pyric-badge":"","data-pyric-badge-kind":e,className:n,"aria-label":r,children:r?h.jsx("span",{"aria-hidden":"true",children:t}):t})}function Kl(t){const e=new Date(t),n=r=>String(r).padStart(2,"0");return`${n(e.getHours())}:${n(e.getMinutes())}:${n(e.getSeconds())}`}function hj({event:t,selected:e,onSelect:n,renderClassification:r,formatTime:s=Kl,className:o}){return h.jsxs("button",{type:"button",onClick:()=>n==null?void 0:n(t),className:o,"data-pyric-traffic-row":"","data-pyric-result":t.result,"data-pyric-origin":t.origin,"data-pyric-method":t.method,"data-pyric-selected":e?"":void 0,children:[h.jsx("span",{"data-pyric-traffic-time":"",children:s(t.at)}),h.jsx("span",{"data-pyric-traffic-service":t.service??"",children:t.service??""}),h.jsx(Ja,{kind:t.method,children:t.method}),h.jsx("span",{"data-pyric-traffic-path":"",children:t.path||"/"}),r?r(t):null]})}var Ng=h1();function Fa(t,e,n){let r=n.initialDeps??[],s,o=!0;function c(){var d,f,p;let g;n.key&&((d=n.debug)!=null&&d.call(n))&&(g=Date.now());const b=t();if(!(b.length!==r.length||b.some((_,k)=>r[k]!==_)))return s;r=b;let w;if(n.key&&((f=n.debug)!=null&&f.call(n))&&(w=Date.now()),s=e(...b),n.key&&((p=n.debug)!=null&&p.call(n))){const _=Math.round((Date.now()-g)*100)/100,k=Math.round((Date.now()-w)*100)/100,I=k/16,N=(R,M)=>{for(R=String(R);R.length<M;)R=" "+R;return R};console.info(`%c⏱ ${N(k,5)} /${N(_,5)} ms`,`
1213
- font-size: .6rem;
1214
- font-weight: bold;
1215
- color: hsl(${Math.max(0,Math.min(120-120*I,120))}deg 100% 31%);`,n==null?void 0:n.key)}return n!=null&&n.onChange&&!(o&&n.skipInitialOnChange)&&n.onChange(s),o=!1,s}return c.updateDeps=d=>{r=d},c}function b_(t,e){if(t===void 0)throw new Error("Unexpected undefined");return t}const cB=(t,e)=>Math.abs(t-e)<1.01,uB=(t,e,n)=>{let r;return function(...s){t.clearTimeout(r),r=t.setTimeout(()=>e.apply(this,s),n)}},v_=t=>{const{offsetWidth:e,offsetHeight:n}=t;return{width:e,height:n}},dB=t=>t,fB=t=>{const e=Math.max(t.startIndex-t.overscan,0),n=Math.min(t.endIndex+t.overscan,t.count-1),r=[];for(let s=e;s<=n;s++)r.push(s);return r},hB=(t,e)=>{const n=t.scrollElement;if(!n)return;const r=t.targetWindow;if(!r)return;const s=c=>{const{width:d,height:f}=c;e({width:Math.round(d),height:Math.round(f)})};if(s(v_(n)),!r.ResizeObserver)return()=>{};const o=new r.ResizeObserver(c=>{const d=()=>{const f=c[0];if(f!=null&&f.borderBoxSize){const p=f.borderBoxSize[0];if(p){s({width:p.inlineSize,height:p.blockSize});return}}s(v_(n))};t.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(d):d()});return o.observe(n,{box:"border-box"}),()=>{o.unobserve(n)}},w_={passive:!0},x_=typeof window>"u"?!0:"onscrollend"in window,pB=(t,e)=>{const n=t.scrollElement;if(!n)return;const r=t.targetWindow;if(!r)return;let s=0;const o=t.options.useScrollendEvent&&x_?()=>{}:uB(r,()=>{e(s,!1)},t.options.isScrollingResetDelay),c=g=>()=>{const{horizontal:b,isRtl:v}=t.options;s=b?n.scrollLeft*(v&&-1||1):n.scrollTop,o(),e(s,g)},d=c(!0),f=c(!1);n.addEventListener("scroll",d,w_);const p=t.options.useScrollendEvent&&x_;return p&&n.addEventListener("scrollend",f,w_),()=>{n.removeEventListener("scroll",d),p&&n.removeEventListener("scrollend",f)}},mB=(t,e,n)=>{if(e!=null&&e.borderBoxSize){const r=e.borderBoxSize[0];if(r)return Math.round(r[n.options.horizontal?"inlineSize":"blockSize"])}return t[n.options.horizontal?"offsetWidth":"offsetHeight"]},yB=(t,{adjustments:e=0,behavior:n},r)=>{var s,o;const c=t+e;(o=(s=r.scrollElement)==null?void 0:s.scrollTo)==null||o.call(s,{[r.options.horizontal?"left":"top"]:c,behavior:n})};class gB{constructor(e){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this.itemSizeCache=new Map,this.laneAssignments=new Map,this.pendingMeasuredCacheIndexes=[],this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this.elementsCache=new Map,this.now=()=>{var n,r,s;return((s=(r=(n=this.targetWindow)==null?void 0:n.performance)==null?void 0:r.now)==null?void 0:s.call(r))??Date.now()},this.observer=(()=>{let n=null;const r=()=>n||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:n=new this.targetWindow.ResizeObserver(s=>{s.forEach(o=>{const c=()=>{const d=o.target,f=this.indexFromElement(d);if(!d.isConnected){this.observer.unobserve(d);return}this.shouldMeasureDuringScroll(f)&&this.resizeItem(f,this.options.measureElement(d,o,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(c):c()})}));return{disconnect:()=>{var s;(s=r())==null||s.disconnect(),n=null},observe:s=>{var o;return(o=r())==null?void 0:o.observe(s,{box:"border-box"})},unobserve:s=>{var o;return(o=r())==null?void 0:o.unobserve(s)}}})(),this.range=null,this.setOptions=n=>{Object.entries(n).forEach(([r,s])=>{typeof s>"u"&&delete n[r]}),this.options={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:dB,rangeExtractor:fB,onChange:()=>{},measureElement:mB,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",...n}},this.notify=n=>{var r,s;(s=(r=this.options).onChange)==null||s.call(r,this,n)},this.maybeNotify=Fa(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),n=>{this.notify(n)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(n=>n()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var n;const r=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==r){if(this.cleanup(),!r){this.maybeNotify();return}this.scrollElement=r,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((n=this.scrollElement)==null?void 0:n.window)??null,this.elementsCache.forEach(s=>{this.observer.observe(s)}),this.unsubs.push(this.options.observeElementRect(this,s=>{this.scrollRect=s,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(s,o)=>{this.scrollAdjustments=0,this.scrollDirection=o?this.getScrollOffset()<s?"forward":"backward":null,this.scrollOffset=s,this.isScrolling=o,this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getFurthestMeasurement=(n,r)=>{const s=new Map,o=new Map;for(let c=r-1;c>=0;c--){const d=n[c];if(s.has(d.lane))continue;const f=o.get(d.lane);if(f==null||d.end>f.end?o.set(d.lane,d):d.end<f.end&&s.set(d.lane,!0),s.size===this.options.lanes)break}return o.size===this.options.lanes?Array.from(o.values()).sort((c,d)=>c.end===d.end?c.index-d.index:c.end-d.end)[0]:void 0},this.getMeasurementOptions=Fa(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode],(n,r,s,o,c,d,f)=>(this.prevLanes!==void 0&&this.prevLanes!==d&&(this.lanesChangedFlag=!0),this.prevLanes=d,this.pendingMeasuredCacheIndexes=[],{count:n,paddingStart:r,scrollMargin:s,getItemKey:o,enabled:c,lanes:d,laneAssignmentMode:f}),{key:!1}),this.getMeasurements=Fa(()=>[this.getMeasurementOptions(),this.itemSizeCache],({count:n,paddingStart:r,scrollMargin:s,getItemKey:o,enabled:c,lanes:d,laneAssignmentMode:f},p)=>{if(!c)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>n)for(const w of this.laneAssignments.keys())w>=n&&this.laneAssignments.delete(w);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMeasuredCacheIndexes=[]),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(w=>{this.itemSizeCache.set(w.key,w.size)}));const g=this.lanesSettling?0:this.pendingMeasuredCacheIndexes.length>0?Math.min(...this.pendingMeasuredCacheIndexes):0;this.pendingMeasuredCacheIndexes=[],this.lanesSettling&&this.measurementsCache.length===n&&(this.lanesSettling=!1);const b=this.measurementsCache.slice(0,g),v=new Array(d).fill(void 0);for(let w=0;w<g;w++){const _=b[w];_&&(v[_.lane]=w)}for(let w=g;w<n;w++){const _=o(w),k=this.laneAssignments.get(w);let I,N;const R=f==="estimate"||p.has(_);if(k!==void 0&&this.options.lanes>1){I=k;const C=v[I],L=C!==void 0?b[C]:void 0;N=L?L.end+this.options.gap:r+s}else{const C=this.options.lanes===1?b[w-1]:this.getFurthestMeasurement(b,w);N=C?C.end+this.options.gap:r+s,I=C?C.lane:w%this.options.lanes,this.options.lanes>1&&R&&this.laneAssignments.set(w,I)}const M=p.get(_),F=typeof M=="number"?M:this.options.estimateSize(w),D=N+F;b[w]={index:w,start:N,size:F,end:D,key:_,lane:I},v[I]=w}return this.measurementsCache=b,b},{key:!1,debug:()=>this.options.debug}),this.calculateRange=Fa(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,s,o)=>this.range=n.length>0&&r>0?bB({measurements:n,outerSize:r,scrollOffset:s,lanes:o}):null,{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=Fa(()=>{let n=null,r=null;const s=this.calculateRange();return s&&(n=s.startIndex,r=s.endIndex),this.maybeNotify.updateDeps([this.isScrolling,n,r]),[this.options.rangeExtractor,this.options.overscan,this.options.count,n,r]},(n,r,s,o,c)=>o===null||c===null?[]:n({startIndex:o,endIndex:c,overscan:r,count:s}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=n=>{const r=this.options.indexAttribute,s=n.getAttribute(r);return s?parseInt(s,10):(console.warn(`Missing attribute name '${r}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=n=>{var r;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const s=this.scrollState.index??((r=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:r.index);if(s!==void 0&&this.range){const o=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),c=Math.max(0,s-o),d=Math.min(this.options.count-1,s+o);return n>=c&&n<=d}return!0},this.measureElement=n=>{if(!n){this.elementsCache.forEach((c,d)=>{c.isConnected||(this.observer.unobserve(c),this.elementsCache.delete(d))});return}const r=this.indexFromElement(n),s=this.options.getItemKey(r),o=this.elementsCache.get(s);o!==n&&(o&&this.observer.unobserve(o),this.observer.observe(n),this.elementsCache.set(s,n)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(r)&&this.resizeItem(r,this.options.measureElement(n,void 0,this))},this.resizeItem=(n,r)=>{var s;const o=this.measurementsCache[n];if(!o)return;const c=this.itemSizeCache.get(o.key)??o.size,d=r-c;d!==0&&(((s=this.scrollState)==null?void 0:s.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(o,d,this):o.start<this.getScrollOffset()+this.scrollAdjustments)&&this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=d,behavior:void 0}),this.pendingMeasuredCacheIndexes.push(o.index),this.itemSizeCache=new Map(this.itemSizeCache.set(o.key,r)),this.notify(!1))},this.getVirtualItems=Fa(()=>[this.getVirtualIndexes(),this.getMeasurements()],(n,r)=>{const s=[];for(let o=0,c=n.length;o<c;o++){const d=n[o],f=r[d];s.push(f)}return s},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=n=>{const r=this.getMeasurements();if(r.length!==0)return b_(r[pj(0,r.length-1,s=>b_(r[s]).start,n)])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const n=this.scrollElement.document.documentElement;return this.options.horizontal?n.scrollWidth-this.scrollElement.innerWidth:n.scrollHeight-this.scrollElement.innerHeight}},this.getOffsetForAlignment=(n,r,s=0)=>{if(!this.scrollElement)return 0;const o=this.getSize(),c=this.getScrollOffset();r==="auto"&&(r=n>=c+o?"end":"start"),r==="center"?n+=(s-o)/2:r==="end"&&(n-=o);const d=this.getMaxScrollOffset();return Math.max(Math.min(d,n),0)},this.getOffsetForIndex=(n,r="auto")=>{n=Math.max(0,Math.min(n,this.options.count-1));const s=this.getSize(),o=this.getScrollOffset(),c=this.measurementsCache[n];if(!c)return;if(r==="auto")if(c.end>=o+s-this.options.scrollPaddingEnd)r="end";else if(c.start<=o+this.options.scrollPaddingStart)r="start";else return[o,r];if(r==="end"&&n===this.options.count-1)return[this.getMaxScrollOffset(),r];const d=r==="end"?c.end+this.options.scrollPaddingEnd:c.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(d,r,c.size),r]},this.scrollToOffset=(n,{align:r="start",behavior:s="auto"}={})=>{const o=this.getOffsetForAlignment(n,r),c=this.now();this.scrollState={index:null,align:r,behavior:s,startedAt:c,lastTargetOffset:o,stableFrames:0},this._scrollToOffset(o,{adjustments:void 0,behavior:s}),this.scheduleScrollReconcile()},this.scrollToIndex=(n,{align:r="auto",behavior:s="auto"}={})=>{n=Math.max(0,Math.min(n,this.options.count-1));const o=this.getOffsetForIndex(n,r);if(!o)return;const[c,d]=o,f=this.now();this.scrollState={index:n,align:d,behavior:s,startedAt:f,lastTargetOffset:c,stableFrames:0},this._scrollToOffset(c,{adjustments:void 0,behavior:s}),this.scheduleScrollReconcile()},this.scrollBy=(n,{behavior:r="auto"}={})=>{const s=this.getScrollOffset()+n,o=this.now();this.scrollState={index:null,align:"start",behavior:r,startedAt:o,lastTargetOffset:s,stableFrames:0},this._scrollToOffset(s,{adjustments:void 0,behavior:r}),this.scheduleScrollReconcile()},this.getTotalSize=()=>{var n;const r=this.getMeasurements();let s;if(r.length===0)s=this.options.paddingStart;else if(this.options.lanes===1)s=((n=r[r.length-1])==null?void 0:n.end)??0;else{const o=Array(this.options.lanes).fill(null);let c=r.length-1;for(;c>=0&&o.some(d=>d===null);){const d=r[c];o[d.lane]===null&&(o[d.lane]=d.end),c--}s=Math.max(...o.filter(d=>d!==null))}return Math.max(s-this.options.scrollMargin+this.options.paddingEnd,0)},this._scrollToOffset=(n,{adjustments:r,behavior:s})=>{this.options.scrollToFn(n,{behavior:s,adjustments:r},this)},this.measure=()=>{this.itemSizeCache=new Map,this.laneAssignments=new Map,this.notify(!1)},this.setOptions(e)}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const r=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,s=r?r[0]:this.scrollState.lastTargetOffset,o=1,c=s!==this.scrollState.lastTargetOffset;if(!c&&cB(s,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=o){this.scrollState=null;return}}else this.scrollState.stableFrames=0,c&&(this.scrollState.lastTargetOffset=s,this.scrollState.behavior="auto",this._scrollToOffset(s,{adjustments:void 0,behavior:"auto"}));this.scheduleScrollReconcile()}}const pj=(t,e,n,r)=>{for(;t<=e;){const s=(t+e)/2|0,o=n(s);if(o<r)t=s+1;else if(o>r)e=s-1;else return s}return t>0?t-1:0};function bB({measurements:t,outerSize:e,scrollOffset:n,lanes:r}){const s=t.length-1,o=f=>t[f].start;if(t.length<=r)return{startIndex:0,endIndex:s};let c=pj(0,s,o,n),d=c;if(r===1)for(;d<s&&t[d].end<n+e;)d++;else if(r>1){const f=Array(r).fill(0);for(;d<s&&f.some(g=>g<n+e);){const g=t[d];f[g.lane]=g.end,d++}const p=Array(r).fill(n+e);for(;c>=0&&p.some(g=>g>=n);){const g=t[c];p[g.lane]=g.start,c--}c=Math.max(0,c-c%r),d=Math.min(s,d+(r-1-d%r))}return{startIndex:c,endIndex:d}}const S_=typeof document<"u"?A.useLayoutEffect:A.useEffect;function vB({useFlushSync:t=!0,...e}){const n=A.useReducer(()=>({}),{})[1],r={...e,onChange:(o,c)=>{var d;t&&c?Ng.flushSync(n):n(),(d=e.onChange)==null||d.call(e,o,c)}},[s]=A.useState(()=>new gB(r));return s.setOptions(r),S_(()=>s._didMount(),[]),S_(()=>s._willUpdate()),s}function wB(t){return vB({observeElementRect:hB,observeElementOffset:pB,scrollToFn:yB,...t})}function Og({items:t,estimateSize:e,renderItem:n,overscan:r=5,className:s,height:o="100%",getItemKey:c}){const d=A.useRef(null),f=typeof e=="function"?e:()=>e,p=wB({count:t.length,getScrollElement:()=>d.current,estimateSize:f,overscan:r});return h.jsx("div",{ref:d,className:s,"data-pyric-ui":"virtual-list",style:{height:o,overflowY:"auto",contain:"strict"},children:h.jsx("div",{"data-pyric-virtual-inner":!0,style:{height:`${p.getTotalSize()}px`,width:"100%",position:"relative"},children:p.getVirtualItems().map(g=>{const b=t[g.index],v=c?c(b,g.index):g.key;return h.jsx("div",{"data-pyric-virtual-row":!0,"data-index":g.index,ref:p.measureElement,style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${g.start}px)`},children:n(b,g.index)},v)})})})}const xB={batch:"batch write",transaction:"transaction","listener-run":"listener re-evals"};function SB({group:t,defaultExpanded:e=!1,onSelect:n,selectedId:r,renderClassification:s,formatTime:o,className:c}){const[d,f]=A.useState(e);return h.jsxs("div",{className:c,"data-pyric-traffic-group":"","data-pyric-group-kind":t.kind,"data-pyric-expanded":d?"":void 0,children:[h.jsxs("button",{type:"button",onClick:()=>f(p=>!p),"data-pyric-traffic-group-header":"","data-pyric-group-kind":t.kind,"aria-expanded":d,children:[h.jsx("span",{"data-pyric-group-kind-label":"",children:xB[t.kind]}),h.jsxs("span",{"data-pyric-group-count":"",children:["×",t.count]}),t.denies>0?h.jsxs("span",{"data-pyric-group-denies":"",children:[t.denies," denied"]}):null]}),d?h.jsx("ul",{"data-pyric-traffic-group-members":"",children:t.events.map(p=>h.jsx("li",{"data-pyric-traffic-entry":"","data-pyric-traffic-id":p.id,children:h.jsx(hj,{event:p,selected:p.id===r,onSelect:n,renderClassification:s,formatTime:o})},p.id))}):null]})}function _B(t){return t<0?0:t>1?1:t}function am(t,e){const n=e.end-e.start;return n<=0?0:_B((t-e.start)/n)}function EB({events:t,buckets:e,window:n,bucketCount:r=30,brush:s,onBrush:o,renderBucketSummary:c,liveAt:d,header:f,axis:p,emptyState:g,className:b}){const v=A.useId(),[w,_]=A.useState(null),[k,I]=A.useState(null),N=Z4({events:t??[],window:n,bucketCount:r}),R=e??N,{buckets:M,total:F}=R,D=w??k,C=D===null?null:M.find(x=>x.index===D)??null,L=C!==null&&(s==null?void 0:s.start)===C.start&&s.end===C.end;if(M.length===0)return h.jsx("div",{className:b,"data-pyric-ui":"traffic-timeline","data-pyric-empty":"",children:g});const U=F===0,H=d===void 0?n.end:d,z=H==null?null:am(H,n),q=typeof p=="function"?p(n):p;return h.jsxs("div",{className:b,"data-pyric-ui":"traffic-timeline","data-pyric-empty":U?"":void 0,children:[f!==void 0&&h.jsx("div",{"data-pyric-timeline-header":"",children:f}),h.jsxs("div",{"data-pyric-timeline-chart":"",children:[h.jsx("div",{"data-pyric-timeline-bars":"",role:o?"group":"img","aria-label":"request volume over time",children:M.map(x=>h.jsx(AB,{bucket:x,window:n,onBrush:o,onHover:c?_:void 0,onFocus:c?I:void 0,summaryId:c&&!L&&(C==null?void 0:C.index)===x.index?v:void 0,selected:(s==null?void 0:s.start)===x.start&&s.end===x.end},x.index))}),C&&c&&!L?h.jsx("div",{id:v,role:"tooltip","data-pyric-bucket-summary":"",style:{"--pyric-bucket-summary-x":(C.index+.5)/Math.max(M.length,1)},children:c(C)}):null,s&&h.jsx("div",{"data-pyric-brush":"","aria-hidden":"true",style:{"--pyric-brush-left":am(s.start,n),"--pyric-brush-right":1-am(s.end,n)}}),z!=null&&h.jsx("div",{"data-pyric-live":"","aria-hidden":"true",style:{"--pyric-live-x":z}})]}),q!=null&&h.jsx("div",{"data-pyric-timeline-axis":"",children:q})]})}function AB({bucket:t,window:e,onBrush:n,onHover:r,onFocus:s,summaryId:o,selected:c}){const d=n!==void 0,f=`${t.count} ${t.count===1?"request":"requests"}`,p=`${t.denies} denied`;return h.jsxs("button",{type:"button","data-pyric-bucket":"","data-pyric-bucket-index":t.index,"data-pyric-bucket-count":t.count,"data-pyric-bucket-denies":t.denies,"data-pyric-has-denies":t.denies>0?"":void 0,"data-pyric-bucket-selected":c?"":void 0,disabled:!d,"aria-label":`${f}, ${p}`,"aria-describedby":o,"aria-pressed":d?c:void 0,onPointerEnter:r?()=>r(t.index):void 0,onPointerLeave:r?()=>r(null):void 0,onFocus:s?()=>s(t.index):void 0,onBlur:s?()=>s(null):void 0,onClick:d?()=>n==null?void 0:n({start:t.start,end:t.end}):void 0,style:{"--pyric-bucket-h":t.heightRatio,"--pyric-bucket-deny-h":t.denyHeightRatio},children:[h.jsx("span",{"data-pyric-bucket-allow":"","aria-hidden":"true"}),h.jsx("span",{"data-pyric-bucket-deny":"","aria-hidden":"true"})]})}const jB=t=>String(t);function kB({series:t,visible:e,onToggle:n,formatValue:r=jB,className:s}){const o=e!==void 0&&n!==void 0;return h.jsx("div",{className:s,"data-pyric-ui":"traffic-metric-cards",role:o?"group":void 0,children:t.map((c,d)=>{const f=e?e.has(c.key):!0,p=h.jsxs(h.Fragment,{children:[h.jsx("span",{"data-pyric-metric-swatch":"","aria-hidden":"true"}),h.jsx("span",{"data-pyric-metric-label":"",children:c.label}),h.jsx("span",{"data-pyric-metric-value":"",children:r(c.total)})]});return o?h.jsxs("label",{"data-pyric-metric-card":"","data-pyric-metric-key":c.key,"data-pyric-series-index":d,"data-pyric-metric-hidden":f?void 0:"",children:[h.jsx("input",{type:"checkbox",checked:f,onChange:()=>n(c.key),"data-pyric-metric-checkbox":""}),p]},c.key):h.jsx("span",{"data-pyric-metric-card":"","data-pyric-metric-key":c.key,"data-pyric-series-index":d,children:p},c.key)})})}const CB=t=>String(t),NB=t=>new Date(t).toLocaleTimeString();function OB({points:t,series:e,visible:n,omitZeroSeries:r=!1,formatValue:s=CB,formatTime:o=NB,emptyState:c,className:d}){const[f,p]=A.useState(null);if(t.length===0)return h.jsx("div",{className:d,"data-pyric-ui":"traffic-line-chart","data-pyric-empty":"",children:c});const g=e.filter(N=>(!n||n.has(N.key))&&(!r||N.total>0));let b=0;for(const N of g)for(const R of N.values)R>b&&(b=R);const v=b===0?1:b,w=t.length,_=N=>w===1?50:N/(w-1)*100,k=N=>100-N/v*100,I=f!=null?t[f]:null;return h.jsx("div",{className:d,"data-pyric-ui":"traffic-line-chart",children:h.jsxs("div",{"data-pyric-chart-svg":"",children:[h.jsx("svg",{viewBox:"0 0 100 100",preserveAspectRatio:"none",role:"img","aria-label":"metrics over time",children:e.map(N=>{const R=e.indexOf(N);if(!((!n||n.has(N.key))&&(!r||N.total>0)))return null;const F=N.values.map((D,C)=>`${C===0?"M":"L"}${_(C)},${k(D)}`).join(" ");return h.jsx("path",{"data-pyric-chart-line":"","data-pyric-series-key":N.key,"data-pyric-series-index":R,d:F,fill:"none",vectorEffect:"non-scaling-stroke"},N.key)})}),h.jsx("div",{"data-pyric-chart-hits":"",children:t.map((N,R)=>h.jsx("button",{type:"button","data-pyric-chart-hit":"","data-pyric-point-index":R,onMouseEnter:()=>p(R),onFocus:()=>p(R),onMouseLeave:()=>p(M=>M===R?null:M),onBlur:()=>p(M=>M===R?null:M),"aria-label":`${o(N.start)} to ${o(N.end)}`},N.index))}),I&&h.jsxs("div",{"data-pyric-chart-tooltip":"",style:{"--pyric-hover-x":_(I.index)},children:[h.jsxs("div",{"data-pyric-tooltip-time":"",children:[o(I.start)," – ",o(I.end)]}),g.map(N=>h.jsxs("div",{"data-pyric-tooltip-row":"","data-pyric-series-key":N.key,"data-pyric-series-index":e.indexOf(N),children:[h.jsx("span",{"data-pyric-tooltip-label":"",children:N.label}),h.jsx("span",{"data-pyric-tooltip-value":"",children:s(N.values[I.index])})]},N.key))]})]})})}const RB={listUsers:lr.listUsers,subscribeUsers:lr.subscribeUsers,createUser:lr.createUser,updateUser:lr.updateUser,deleteUser:lr.deleteUser,clearUsers:lr.clearUsers,getAuthProviderConfig:lr.getAuthProviderConfig,setAuthProviderConfig:lr.setAuthProviderConfig,subscribeAuthProviderConfig:lr.subscribeAuthProviderConfig},mj=A.createContext(RB);function TB(){return A.useContext(mj)}function yj({value:t,children:e}){return A.createElement(mj.Provider,{value:t},e)}function DB(t,e){return[t.uid,t.email,t.displayName,t.phoneNumber].some(n=>n!=null&&n.toLowerCase().includes(e))}function Rg(t){const{listUsers:e,subscribeUsers:n,createUser:r,updateUser:s,deleteUser:o,clearUsers:c}=TB(),[d,f]=A.useState([]),[p,g]=A.useState(!0),[b,v]=A.useState(void 0),[w,_]=A.useState("");A.useEffect(()=>{let D=!1;g(!0),v(void 0);const C=z=>{D||(f(z),g(!1))},L=z=>{D||(f([]),v(z instanceof Error?z:new Error(String(z))),g(!1))},U=()=>{try{const z=e(t);z&&typeof z.then=="function"?z.then(C).catch(L):C(z)}catch(z){L(z)}};let H;try{U(),H=n(t,U)}catch(z){L(z)}return()=>{D=!0,H==null||H()}},[t,e,n]);const k=A.useMemo(()=>{const D=w.trim().toLowerCase();return D?d.filter(C=>DB(C,D)):d},[d,w]),I=A.useCallback(D=>r(t,D),[t,r]),N=A.useCallback((D,C)=>s(t,D,C),[t,s]),R=A.useCallback(D=>o(t,D),[t,o]),M=A.useCallback(()=>c(t),[t,c]),F=A.useCallback(()=>{const D=e(t);D&&typeof D.then=="function"?D.then(C=>f(C)).catch(()=>{}):f(D)},[t,e]);return{users:k,totalCount:d.length,isLoading:p,error:b,filter:w,setFilter:_,createUser:I,updateUser:N,deleteUser:R,clearUsers:M,refresh:F}}const IB=["iss","aud","sub","iat","exp","nbf","jti","nonce","azp","acr","amr","cnf","auth_time","firebase","at_hash","c_hash"],MB=1e3;function gj(t){const e=t.trim();if(!e)return{ok:!0,claims:void 0};if(e.length>MB)return{ok:!1,message:"Custom claims length must not exceed 1000 characters"};let n;try{n=JSON.parse(e)}catch{return{ok:!1,message:"Custom claims must be a valid JSON object"}}if(typeof n!="object"||n===null||Array.isArray(n))return{ok:!1,message:"Custom claims must be a valid JSON object"};for(const r of IB)if(r in n)return{ok:!1,message:`Custom claims must not have forbidden key: ${r}`};return{ok:!0,claims:n}}const LB={email:"",password:"",displayName:"",phoneNumber:"",photoUrl:"",emailVerified:!1,disabled:!1,claimsText:"",providerIds:[]},UB=new Set(["password","anonymous","phone"]),$B=/^[^@]+@[^@]+\.[^@]+$/,__=6;function BB(t){return t?{email:t.email??"",password:"",displayName:t.displayName??"",phoneNumber:t.phoneNumber??"",photoUrl:t.photoUrl??"",emailVerified:t.emailVerified,disabled:t.disabled,claimsText:Object.keys(t.customClaims).length?JSON.stringify(t.customClaims,null,2):"",providerIds:t.providerUserInfo.map(e=>e.providerId).filter(e=>!UB.has(e))}:{...LB}}function qB(t){const e=BB(t);return{fields:e,initial:{...e}}}function FB(t,e){switch(e.type){case"setField":return{...t,fields:{...t.fields,[e.field]:e.value}};case"reset":return{...t,fields:{...t.initial}}}}function zB(t){const e={},n=t.email.trim(),r=t.password;n&&!$B.test(n)&&(e.email="Invalid email"),r&&r.length<__&&(e.password=`Password should be at least ${__} characters`),r&&!n&&(e.password="Email is required for password authentication");const s=gj(t.claimsText);return s.ok||(e.claims=s.message),e}function PB(t){const{fields:e,initial:n}=t;return Object.keys(e).some(r=>r==="providerIds"?!bj(e.providerIds,n.providerIds):e[r]!==n[r])}function bj(t,e){if(t.length!==e.length)return!1;const n=[...e].sort();return[...t].sort().every((r,s)=>r===n[s])}function vj(t){const e=gj(t.claimsText);return e.ok?e.claims:void 0}function VB(t){const e=t.fields,n={emailVerified:e.emailVerified,disabled:e.disabled};e.email.trim()&&(n.email=e.email.trim()),e.password&&(n.password=e.password),e.displayName.trim()&&(n.displayName=e.displayName.trim()),e.phoneNumber.trim()&&(n.phoneNumber=e.phoneNumber.trim()),e.photoUrl.trim()&&(n.photoUrl=e.photoUrl.trim());const r=vj(e);return r&&(n.customClaims=r),e.providerIds.length&&(n.providerUserInfo=e.providerIds.map(s=>({providerId:s}))),n}function HB(t){const{fields:e,initial:n}=t,r={};return e.email.trim()!==n.email&&e.email.trim()&&(r.email=e.email.trim()),e.password&&e.password!==n.password&&(r.password=e.password),e.displayName.trim()!==n.displayName&&(r.displayName=e.displayName.trim()||null),e.emailVerified!==n.emailVerified&&(r.emailVerified=e.emailVerified),e.disabled!==n.disabled&&(r.disabled=e.disabled),e.claimsText!==n.claimsText&&(r.customClaims=vj(e)??{}),bj(e.providerIds,n.providerIds)||(r.providerUserInfo=e.providerIds.map(s=>({providerId:s}))),r}function wj(t={}){const[e,n]=A.useReducer(FB,t.initial,qB),r=A.useMemo(()=>zB(e.fields),[e.fields]),s=A.useMemo(()=>PB(e),[e]),o=A.useCallback((d,f)=>n({type:"setField",field:d,value:f}),[]),c=A.useCallback(()=>n({type:"reset"}),[]);return{fields:e.fields,errors:r,isDirty:s,isValid:Object.keys(r).length===0,setField:o,reset:c,toCreateRequest:()=>VB(e),toUpdateRequest:()=>HB(e),dispatch:n}}const GB={"google.com":"Google","apple.com":"Apple","gc.apple.com":"Game Center","facebook.com":"Facebook","github.com":"GitHub","microsoft.com":"Microsoft","playgames.google.com":"Play Games","twitter.com":"Twitter","yahoo.com":"Yahoo",password:"Email/Password",phone:"Phone",anonymous:"Anonymous",oidc:"OIDC",saml:"SAML"};function Ad(t){return GB[t]??t}function E_(t){return t.email??t.phoneNumber??(t.isAnonymous?"anonymous":t.uid)}function KB(t){return t.isAnonymous&&t.providerUserInfo.length===0?h.jsx("span",{"data-pyric-provider-id":"anonymous",children:Ad("anonymous")}):t.providerUserInfo.map(e=>h.jsx("span",{"data-pyric-provider-id":e.providerId,children:Ad(e.providerId)},e.providerId))}function A_(t){if(!t)return"—";const e=new Date(t);return Number.isNaN(e.getTime())?"—":e.toLocaleDateString()}function xj({users:t,isLoading:e,error:n,filter:r,onSelect:s,renderIdentifier:o,renderProviders:c,renderSelection:d,renderSelectionHeader:f,renderActions:p,renderActionsHeader:g,formatCreatedAt:b=A_,formatLastLoginAt:v=A_,emptyState:w,noResultsState:_,className:k,virtualizeThreshold:I=100,rowHeight:N=44,virtualizedHeight:R="60vh"}){if(n)return h.jsx("div",{className:k,"data-pyric-ui":"auth-user-list","data-pyric-error":"",role:"alert",children:n.message});if(e&&t.length===0)return h.jsx("div",{className:k,"data-pyric-ui":"auth-user-list","data-pyric-loading":""});if(t.length===0){const D=!!(r!=null&&r.trim());return h.jsx("div",{className:k,"data-pyric-ui":"auth-user-list","data-pyric-empty":"","data-pyric-no-results":D?"":void 0,children:D?_??"No results":w??"No users for this project yet"})}const M=t.length>I,F=D=>h.jsxs("div",{role:"row","data-pyric-user-entry":!0,"data-pyric-user-uid":D.uid,"data-pyric-user-disabled":D.disabled?"":void 0,children:[d?h.jsx("span",{role:"cell","data-pyric-user-cell":"selection",children:d(D)}):null,h.jsx("span",{role:"cell","data-pyric-user-cell":"identifier",children:s?h.jsx("button",{type:"button","data-pyric-user-select":!0,onClick:()=>s(D),children:o?o(D):E_(D)}):(o??E_)(D)}),h.jsx("span",{role:"cell","data-pyric-user-cell":"providers",children:(c??KB)(D)}),h.jsx("span",{role:"cell","data-pyric-user-cell":"created",children:b(D.createdAt)}),h.jsx("span",{role:"cell","data-pyric-user-cell":"signed-in",children:v(D.lastLoginAt)}),h.jsx("span",{role:"cell","data-pyric-user-cell":"uid",children:D.uid}),p?h.jsx("span",{role:"cell","data-pyric-user-cell":"actions",children:p(D)}):null]},D.uid);return h.jsxs("div",{className:k,role:"table","aria-label":"Authentication users","data-pyric-ui":"auth-user-list","data-pyric-virtualized":M?"":void 0,"data-pyric-selection":d?"":void 0,"data-pyric-actions":p?"":void 0,children:[h.jsxs("div",{role:"row","data-pyric-user-header":!0,children:[d?h.jsx("span",{role:"columnheader","data-pyric-user-cell":"selection","aria-label":"Selection",children:f}):null,h.jsx("span",{role:"columnheader","data-pyric-user-cell":"identifier",children:"Identifier"}),h.jsx("span",{role:"columnheader","data-pyric-user-cell":"providers",children:"Provider"}),h.jsx("span",{role:"columnheader","data-pyric-user-cell":"created",children:"Created"}),h.jsx("span",{role:"columnheader","data-pyric-user-cell":"signed-in",children:"Signed In"}),h.jsx("span",{role:"columnheader","data-pyric-user-cell":"uid",children:"User UID"}),p?h.jsx("span",{role:"columnheader","data-pyric-user-cell":"actions","aria-label":"Actions",children:g}):null]}),M?h.jsx(Og,{items:t,estimateSize:N,height:R,getItemKey:D=>D.uid,renderItem:F}):h.jsx("div",{role:"rowgroup","data-pyric-user-rows":!0,children:t.map(F)})]})}function YB({value:t,onChange:e,error:n,hint:r,placeholder:s='{"role":"admin"}',className:o}){return h.jsxs("div",{className:o,"data-pyric-ui":"claims-field",children:[h.jsx("textarea",{"data-pyric-field":"claims","data-pyric-claims-invalid":n!=null?"":void 0,"aria-label":"Custom claims (optional)","aria-invalid":n!=null||void 0,placeholder:s,value:t,onChange:c=>e(c.target.value)}),n!=null&&h.jsx("p",{role:"alert","data-pyric-claims-error":!0,children:n}),r!=null&&h.jsx("p",{"data-pyric-claims-hint":!0,children:r})]})}function ZB({selected:t,onChange:e}){return h.jsx("div",{"data-pyric-provider-checklist":!0,children:YA.map(n=>h.jsxs("label",{"data-pyric-provider-option":n,children:[h.jsx("input",{type:"checkbox",checked:t.includes(n),onChange:r=>e(r.target.checked?[...t,n]:t.filter(s=>s!==n))}),h.jsx("span",{"data-pyric-provider-option-label":!0,children:Ad(n)}),h.jsx("span",{"data-pyric-provider-option-id":!0,children:n})]},n))})}function Sj({initial:t,onSubmit:e,onCancel:n,submitLabel:r="Save",cancelLabel:s="Cancel",children:o,className:c,renderField:d}){const f=wj({initial:t}),p=t?"edit":"create",g=f.isValid&&(p==="create"||f.isDirty),b=(_,k,I,N,R=null)=>({name:_,label:k,input:N,error:R,kind:I,defaultRender:()=>I==="checkbox"?h.jsxs("label",{"data-pyric-field-label":_,children:[N,h.jsx("span",{"data-pyric-label-text":!0,children:k})]},_):I==="group"?h.jsxs("fieldset",{"data-pyric-field-label":_,children:[h.jsx("legend",{"data-pyric-label-text":!0,children:k}),N]},_):h.jsxs("label",{"data-pyric-field-label":_,children:[h.jsx("span",{"data-pyric-label-text":!0,children:k}),N,R!=null&&h.jsx("p",{role:"alert","data-pyric-field-error":_,children:R})]},_)}),v=[b("email","Email","text",h.jsx("input",{type:"email","data-pyric-field":"email",placeholder:"email@example.com",value:f.fields.email,onChange:_=>f.setField("email",_.target.value)}),f.errors.email??null),b("password","Password","text",h.jsx("input",{type:"password","data-pyric-field":"password",placeholder:p==="edit"?"New password (unchanged if empty)":"Password",value:f.fields.password,onChange:_=>f.setField("password",_.target.value)}),f.errors.password??null),b("display-name","Display name","text",h.jsx("input",{type:"text","data-pyric-field":"display-name",placeholder:"Display name (optional)",value:f.fields.displayName,onChange:_=>f.setField("displayName",_.target.value)})),b("phone-number","Phone number","text",h.jsx("input",{type:"tel","data-pyric-field":"phone-number",placeholder:"+1 555 555 0100",value:f.fields.phoneNumber,onChange:_=>f.setField("phoneNumber",_.target.value)})),b("photo-url","Photo URL","text",h.jsx("input",{type:"url","data-pyric-field":"photo-url",placeholder:"https://example.com/avatar.png",value:f.fields.photoUrl,onChange:_=>f.setField("photoUrl",_.target.value)})),...p==="create"?[b("providers","Sign-in providers","group",h.jsx(ZB,{selected:f.fields.providerIds,onChange:_=>f.setField("providerIds",_)}))]:[],b("email-verified","Verified email","checkbox",h.jsx("input",{type:"checkbox","data-pyric-field":"email-verified",checked:f.fields.emailVerified,onChange:_=>f.setField("emailVerified",_.target.checked)})),b("disabled","Disabled (sign-in attempts are rejected)","checkbox",h.jsx("input",{type:"checkbox","data-pyric-field":"disabled",checked:f.fields.disabled,onChange:_=>f.setField("disabled",_.target.checked)}))],w=_=>{_.preventDefault(),g&&e(p==="edit"?{mode:p,uid:t.uid,request:f.toUpdateRequest()}:{mode:p,request:f.toCreateRequest()})};return h.jsxs("form",{className:c,"data-pyric-ui":"auth-user-form","data-pyric-mode":p,"data-pyric-is-dirty":f.isDirty?"":void 0,"data-pyric-is-valid":f.isValid?"":void 0,onSubmit:w,children:[v.map(_=>d?h.jsx(A.Fragment,{children:d(_)},_.name):_.defaultRender()),h.jsx(YB,{value:f.fields.claimsText,onChange:_=>f.setField("claimsText",_),error:f.errors.claims}),o,h.jsxs("footer",{"data-pyric-form-actions":!0,children:[n?h.jsx("button",{type:"button","data-pyric-cancel":!0,onClick:n,children:s}):null,h.jsx("button",{type:"submit","data-pyric-submit":!0,disabled:!g,children:r})]})]})}function WB({open:t,onOpenChange:e,title:n,body:r,destructive:s,confirmLabel:o="Confirm",cancelLabel:c="Cancel",onConfirm:d,className:f}){const p=A.useRef(null),g=A.useRef(null);return A.useEffect(()=>{if(!t)return;const b=v=>{v.key==="Escape"&&(v.stopPropagation(),e(!1))};return window.addEventListener("keydown",b),()=>window.removeEventListener("keydown",b)},[t,e]),A.useEffect(()=>{var b;if(t)return g.current=document.activeElement,(b=p.current)==null||b.focus(),()=>{var w;const v=g.current;(w=v==null?void 0:v.focus)==null||w.call(v)}},[t]),!t||typeof document>"u"?null:Ng.createPortal(h.jsxs("div",{role:"presentation","data-pyric-ui":"confirm-portal",onClick:b=>{b.target===b.currentTarget&&e(!1)},children:[h.jsx("div",{"data-pyric-ui":"confirm-overlay","aria-hidden":"true"}),h.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"pyric-confirm-title","aria-describedby":r?"pyric-confirm-body":void 0,className:f,"data-pyric-ui":"confirm-dialog","data-pyric-destructive":s?"":void 0,children:[h.jsx("div",{id:"pyric-confirm-title","data-pyric-confirm-title":!0,children:n}),r?h.jsx("div",{id:"pyric-confirm-body","data-pyric-confirm-body":!0,children:r}):null,h.jsxs("div",{"data-pyric-confirm-actions":!0,children:[h.jsx("button",{type:"button","data-pyric-confirm-cancel":!0,onClick:()=>e(!1),children:c}),h.jsx("button",{ref:p,type:"button","data-pyric-confirm-confirm":!0,"data-pyric-destructive":s?"":void 0,onClick:d,children:o})]})]})]}),document.body)}const _j=A.createContext(null);function go(){const t=A.useContext(_j);if(!t)throw new Error("useConfirm: missing <ConfirmProvider> ancestor");return t}function Tg({children:t,dialogClassName:e}){const[n,r]=A.useState(null),s=A.useRef(!1),o=A.useCallback(p=>new Promise(g=>{s.current=!1,r({options:p,resolve:g})}),[]),c=A.useCallback(()=>{n&&(s.current||(s.current=!0,n.resolve(!0),r(null)))},[n]),d=A.useCallback(p=>{p||n&&(s.current||(s.current=!0,n.resolve(!1),r(null)))},[n]),f=A.useMemo(()=>o,[o]);return h.jsxs(_j.Provider,{value:f,children:[t,n?h.jsx(WB,{open:!0,onOpenChange:d,title:n.options.title,body:n.options.body,destructive:n.options.destructive,confirmLabel:n.options.confirmLabel,cancelLabel:n.options.cancelLabel,onConfirm:c,className:e}):null]})}function QB(t){return t.email??t.phoneNumber??t.displayName??t.uid}function JB({user:t,onDelete:e,title:n="Delete user",body:r,confirmLabel:s="Delete",renderTrigger:o,className:c}){const d=go(),f=async()=>{await d({title:n,body:r??`This will permanently delete ${QB(t)}.`,destructive:!0,confirmLabel:s})&&e(t.uid)};return o?h.jsx(h.Fragment,{children:o({onClick:f})}):h.jsx("button",{type:"button",className:c,"data-pyric-ui":"delete-user","data-pyric-destructive":!0,onClick:f,children:"Delete user"})}function XB(t){if(t instanceof Error)return t;if(typeof t=="string")return new Error(t);if(t&&typeof t=="object"){const e=t,n=typeof e.message=="string"?e.message:null,r=typeof e.code=="string"?e.code:null;if(n&&r)return new Error(`[${r}] ${n}`);if(n)return new Error(n);if(r)return new Error(r);try{return new Error(JSON.stringify(t))}catch{return new Error(Object.prototype.toString.call(t))}}return new Error(String(t))}const e5={addDoc:wg,collection:Ui,deleteDoc:bd,doc:ur,getDoc:vg,getDocs:zl,limit:vd,onSnapshot:NU,query:Vl,setDoc:Pl,startAfter:CU},Ej=A.createContext(e5);function Dg(){return A.useContext(Ej)}function t5({value:t,children:e}){return A.createElement(Ej.Provider,{value:t},e)}function n5(t){const{onSnapshot:e}=Dg(),[n,r]=A.useState(()=>({data:void 0,error:void 0,isLoading:t!=null}));return A.useEffect(()=>{if(!t){r({data:void 0,error:void 0,isLoading:!1});return}return r(o=>({data:o.data,error:void 0,isLoading:!0})),e(t,o=>r({data:o,error:void 0,isLoading:!1}),o=>r({data:void 0,error:XB(o),isLoading:!1}))},[e,t]),n}function Xd(t){return t==null?"null":typeof t=="string"?"string":typeof t=="number"?"number":typeof t=="boolean"?"boolean":typeof t=="object"&&Xi(t)!==null?"vector":Array.isArray(t)?"array":t instanceof $n?"timestamp":t instanceof Or?"geopoint":t instanceof Er?"bytes":typeof t=="object"&&Aj(t)?"timestamp":typeof t=="object"&&jj(t)?"geopoint":typeof t=="object"&&r5(t)?"reference":typeof t=="object"?"map":"null"}function Aj(t){const e=t;return Object.keys(e).length!==2?!1:typeof e.seconds=="number"&&typeof e.nanoseconds=="number"||typeof e._seconds=="number"&&typeof e._nanoseconds=="number"}function jj(t){const e=t;return Object.keys(e).length===2&&typeof e.latitude=="number"&&typeof e.longitude=="number"}function r5(t){const e=t;if(typeof e.path!="string"||typeof e.id!="string")return!1;const n=typeof e.firestore=="object"&&e.firestore!==null,r=typeof e.env=="object"&&e.env!==null,s=e.type==="document";return n||r||s}function Xi(t){if(t===null||typeof t!="object")return null;const e=t;if(e.typeName==="vector"&&Tu(e.value)||e.__type__==="__vector__"&&Tu(e.value))return Du(e.value);if(Tu(e._values))return Du(e._values);if(typeof e.toArray=="function")try{const n=e.toArray();if(Tu(n))return Du(n)}catch{}return null}function Tu(t){return Array.isArray(t)&&t.every(e=>typeof e=="number")}function Du(t){const e=t.slice();return{values:e,dimension:e.length}}const j_=4;function kj(t){const e=t.values.slice(0,j_).join(", "),n=t.values.length>j_?", …":"";return`vector · ${t.dimension} [${e}${n}]`}function oo(t){const e=Xi(t);if(e)return kj(e);if(Array.isArray(t))return t.map(oo);if(t&&typeof t=="object"){const n=Object.getPrototypeOf(t);if(n===Object.prototype||n===null){const r={};for(const[s,o]of Object.entries(t))r[s]=oo(o);return r}}return t}function Cj(){return crypto.randomUUID()}function s5(t){const e=Cj(),n={rootId:e,nodes:{[e]:{id:e,parentId:null,key:null,type:"map",value:void 0}},childIds:{[e]:[]}};for(const[r,s]of Object.entries(t))jy(n,e,r,s);return n}function jy(t,e,n,r){const s=Xd(r),o=Cj(),c={id:o,parentId:e,key:n,type:s,value:i5(s)?void 0:r};if(t.nodes[o]=c,t.childIds[o]=[],t.childIds[e].push(o),s==="map"&&r&&typeof r=="object")for(const[d,f]of Object.entries(r))jy(t,o,d,f);else if(s==="array"&&Array.isArray(r))for(const d of r)jy(t,o,null,d);return o}function i5(t){return t==="map"||t==="array"}function Nj(t){const e=t.nodes[t.rootId];if(!e||e.type!=="map")throw new Error("treeToData: tree root must be a map node");return ky(t,t.rootId)}function ky(t,e){const n=t.nodes[e];if(!n)throw new Error(`serializeNode: missing node ${e}`);switch(n.type){case"map":{const r={};for(const s of t.childIds[e]??[]){const o=t.nodes[s];o&&o.key!=null&&(r[o.key]=ky(t,s))}return r}case"array":{const r=[];for(const s of t.childIds[e]??[])r.push(ky(t,s));return r}default:return n.value}}function Cy(t){const e={};for(const[r,s]of Object.entries(t.nodes))e[r]={...s};const n={};for(const[r,s]of Object.entries(t.childIds))n[r]=[...s];return{rootId:t.rootId,nodes:e,childIds:n}}function Oj(t,e){const n=[e],r=[e];for(;r.length;){const s=r.shift();for(const o of t.childIds[s]??[])n.push(o),r.push(o)}return n}function Rj(t,e){switch(t){case"string":return typeof e=="string"?void 0:"Expected a string";case"number":return typeof e!="number"?"Expected a number":Number.isFinite(e)?void 0:"Number must be finite";case"boolean":return typeof e=="boolean"?void 0:"Expected a boolean";case"null":return e==null?void 0:"Expected null";case"timestamp":return e instanceof $n?void 0:"Expected a Timestamp";case"geopoint":return e instanceof Or?e.latitude<-90||e.latitude>90?"Latitude must be between -90 and 90":e.longitude<-180||e.longitude>180?"Longitude must be between -180 and 180":void 0:"Expected a GeoPoint";case"reference":if(e===null||typeof e!="object")return"Expected a DocumentReference";const n=e;return typeof n.path!="string"?"Reference missing `path`":n.path?n.path.split("/").filter(Boolean).length%2!==0?"Reference path must have an even segment count":void 0:"Reference path is empty";case"bytes":return e instanceof Er?void 0:"Expected a Bytes value";case"vector":return Xi(e)!==null?void 0:"Expected a vector value";case"map":case"array":return}}function Tj(t){const e={};let n=0;for(const[r,s]of Object.entries(t.nodes))e[r]={...s,error:void 0};for(const r of Object.values(e)){if(r.type==="map"||r.type==="array")continue;const s=Rj(r.type,r.value);s&&(e[r.id].error=s,n++)}for(const[r,s]of Object.entries(e)){if(s.type!=="map")continue;const o=t.childIds[r]??[],c=new Map;for(const d of o){const f=e[d];if(!f)continue;const p=f.key??"";p||(f.error||n++,e[d].error=e[d].error??"Field name is required");const g=c.get(p)??[];g.push(d),c.set(p,g)}for(const[d,f]of c)if(d&&f.length>1)for(const p of f)e[p].error||n++,e[p].error=e[p].error??"Field name must be unique"}return{tree:{rootId:t.rootId,nodes:e,childIds:t.childIds},errorCount:n}}function Ig(t){switch(t){case"string":return"";case"number":return 0;case"boolean":return!1;case"null":return null;case"timestamp":return $n.now();case"geopoint":return new Or(0,0);case"reference":return{path:"",id:"",firestore:{}};case"bytes":return Er.fromUint8Array(new Uint8Array);case"vector":return{__type__:"__vector__",value:[]};case"map":case"array":return}}function Ny(t){if(t===null||typeof t!="object"||Xi(t)!==null)return t;if(Aj(t)){const n=t;return new $n(n.seconds??n._seconds??0,n.nanoseconds??n._nanoseconds??0)}if(jj(t)){const n=t;return new Or(n.latitude,n.longitude)}if(Array.isArray(t))return t.map(Ny);const e=Object.getPrototypeOf(t);if(e===Object.prototype||e===null){const n={};for(const[r,s]of Object.entries(t))n[r]=Ny(s);return n}return t}function Dj(t){const e=s5(Ny(t)),{tree:n,errorCount:r}=Tj(e);return{tree:n,initial:n,errorCount:r}}function a5(t,e){switch(e.type){case"setValue":return za(t,n=>l5(n,e.nodeId,e.value));case"setType":return za(t,n=>c5(n,e.nodeId,e.newType));case"setKey":return za(t,n=>u5(n,e.nodeId,e.key));case"addMapEntry":return za(t,n=>d5(n,e.parentId,e.key,e.childType));case"addArrayEntry":return za(t,n=>f5(n,e.parentId,e.childType));case"remove":return za(t,n=>h5(n,e.nodeId));case"reset":return{tree:t.initial,initial:t.initial,errorCount:o5(t.initial)};case"replaceData":return Dj(e.data);case"touch":{const n=t.tree.nodes[e.nodeId];if(!n||n.touched)return t;const r=Cy(t.tree);return r.nodes[e.nodeId]={...r.nodes[e.nodeId],touched:!0},{...t,tree:r}}case"touchAll":{const n=Cy(t.tree);for(const r of Object.keys(n.nodes))n.nodes[r]={...n.nodes[r],touched:!0};return{...t,tree:n}}}}function za(t,e){const n=e(Cy(t.tree)),{tree:r,errorCount:s}=Tj(n);return{...t,tree:r,errorCount:s}}function o5(t){let e=0;for(const n of Object.values(t.nodes))n.error&&e++;return e}function l5(t,e,n){const r=t.nodes[e];return!r||r.type==="map"||r.type==="array"||(t.nodes[e]={...r,value:n}),t}function c5(t,e,n){const r=t.nodes[e];if(!r||r.id===t.rootId&&n!=="map"||r.type===n)return t;if(r.type==="map"||r.type==="array"){const o=(t.childIds[e]??[]).slice();for(const c of o)for(const d of Oj(t,c))delete t.nodes[d],delete t.childIds[d];t.childIds[e]=[]}const s=n==="map"||n==="array"?void 0:Ig(n);return t.nodes[e]={...r,type:n,value:s},t}function u5(t,e,n){const r=t.nodes[e];if(!r||r.parentId==null)return t;const s=t.nodes[r.parentId];return!s||s.type!=="map"||(t.nodes[e]={...r,key:n}),t}function d5(t,e,n,r){const s=t.nodes[e];if(!s||s.type!=="map")return t;const o=crypto.randomUUID(),c=r==="map"||r==="array"?void 0:Ig(r);return t.nodes[o]={id:o,parentId:e,key:n,type:r,value:c},t.childIds[o]=[],t.childIds[e]=[...t.childIds[e]??[],o],t}function f5(t,e,n){const r=t.nodes[e];if(!r||r.type!=="array"||n==="array")return t;const s=crypto.randomUUID(),o=n==="map"?void 0:Ig(n);return t.nodes[s]={id:s,parentId:e,key:null,type:n,value:o},t.childIds[s]=[],t.childIds[e]=[...t.childIds[e]??[],s],t}function h5(t,e){const n=t.nodes[e];if(!n||n.id===t.rootId)return t;const r=Oj(t,e);for(const s of r)delete t.nodes[s],delete t.childIds[s];return n.parentId!=null&&(t.childIds[n.parentId]=(t.childIds[n.parentId]??[]).filter(s=>s!==e)),t}function Ij(t={}){const e=t.initial??{},n=A.useRef(null);n.current==null&&(n.current=Dj(e));const[r,s]=A.useReducer(a5,n.current),o=A.useCallback((R,M)=>s({type:"setValue",nodeId:R,value:M}),[]),c=A.useCallback((R,M)=>s({type:"setType",nodeId:R,newType:M}),[]),d=A.useCallback((R,M)=>s({type:"setKey",nodeId:R,key:M}),[]),f=A.useCallback((R,M,F)=>s({type:"addMapEntry",parentId:R,key:M,childType:F}),[]),p=A.useCallback((R,M)=>s({type:"addArrayEntry",parentId:R,childType:M}),[]),g=A.useCallback(R=>s({type:"remove",nodeId:R}),[]),b=A.useCallback(()=>s({type:"reset"}),[]),v=A.useCallback(R=>s({type:"replaceData",data:R}),[]),w=A.useCallback(R=>s({type:"touch",nodeId:R}),[]),_=A.useCallback(()=>s({type:"touchAll"}),[]),k=A.useCallback(()=>Nj(r.tree),[r.tree]),I=r.tree!==r.initial,N=r.errorCount===0;return A.useMemo(()=>({...r,isDirty:I,isValid:N,dispatch:s,setValue:o,setType:c,setKey:d,addMapEntry:f,addArrayEntry:p,remove:g,reset:b,replaceData:v,touch:w,touchAll:_,toData:k}),[r,I,N,o,c,d,f,p,g,b,v,w,_,k])}function p5({collection:t,query:e,pageSize:n=50,mode:r="paged"}){const[s,o]=A.useState([]),[c,d]=A.useState(!0),[f,p]=A.useState(void 0),[g,b]=A.useState(!1),[v,w]=A.useState(0),[_,k]=A.useState(n),I=A.useRef(0),[N,R]=A.useState(0),{addDoc:M,deleteDoc:F,doc:D,getDoc:C,getDocs:L,limit:U,onSnapshot:H,query:z,setDoc:q,startAfter:x}=Dg();A.useEffect(()=>{k(n)},[t,r,n,e]),A.useEffect(()=>{let $=!1;r==="paged"&&o([]),b(!1),d(!0),p(void 0);const K=e??t,W=r==="live"?_:n,se=z(K,U(W)),B=ae=>{$||(o([...ae.docs]),b(ae.docs.length===W),d(!1))},ee=ae=>{$||(p(ae instanceof Error?ae:new Error(String(ae))),d(!1))};if(r==="live"){const ae=++I.current,le=H(se,ye=>{R(ae),B(ye)},ee);return()=>{$=!0,le()}}return L(se).then(ae=>{B(ae)}).catch(ee),()=>{$=!0}},[t,L,U,r,H,n,e,z,_,v]);const E=A.useCallback(()=>{if(!g||c)return;if(r==="live"){d(!0),k(se=>se+n);return}const $=s[s.length-1];if(!$)return;d(!0);const W=z(e??t,x($),U(n));L(W).then(se=>{o(B=>[...B,...se.docs]),b(se.docs.length===n),d(!1)}).catch(se=>{p(se instanceof Error?se:new Error(String(se))),d(!1)})},[t,s,L,g,c,U,r,n,e,z,x]),O=A.useCallback(async($,K,W)=>{if($==null){const B=await M(t,K);return r==="paged"&&w(ee=>ee+1),B}const se=D(t,$);if((W==null?void 0:W.onExisting)==="fail"){const B=await C(se);if(typeof B.exists=="function"?B.exists():!!B.exists){const ae=new Error(`Document "${$}" already exists.`);throw ae.code="already-exists",ae}}return await q(se,K),r==="paged"&&w(B=>B+1),se},[M,t,D,C,r,q]),T=A.useCallback(async $=>{await F($),r==="paged"&&w(K=>K+1)},[F,r]),P=A.useCallback(()=>w($=>$+1),[]);return{documents:s,isLoading:c,error:f,subscriptionGeneration:N,hasMore:g,loadMore:E,createDocument:O,deleteDocument:T,refresh:P}}function m5({firestore:t,documentRef:e,listSubcollections:n}){const[r,s]=A.useState([]),[o,c]=A.useState(!1),[d,f]=A.useState(void 0),p=A.useRef(n);p.current=n;const g=e==null?void 0:e.path;return A.useEffect(()=>{if(!e){s([]),c(!1),f(void 0);return}let b=!1;return c(!0),f(void 0),p.current(t,e).then(v=>{b||(s(v),c(!1))}).catch(v=>{b||(f(v instanceof Error?v:new Error(String(v))),c(!1))}),()=>{b=!0}},[t,g]),{subcollections:r,isLoading:o,error:d}}function k_(t){return typeof t=="object"&&t!==null&&"isEqual"in t&&typeof t.isEqual=="function"}function C_(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function jd(t,e){if(Object.is(t,e))return!0;if(k_(t))return t.isEqual(e);if(k_(e))return e.isEqual(t);if(t instanceof Uint8Array||e instanceof Uint8Array)return!(t instanceof Uint8Array)||!(e instanceof Uint8Array)||t.length!==e.length?!1:t.every((s,o)=>s===e[o]);if(Array.isArray(t)||Array.isArray(e))return!Array.isArray(t)||!Array.isArray(e)||t.length!==e.length?!1:t.every((s,o)=>jd(s,e[o]));if(!C_(t)||!C_(e))return!1;const n=Object.keys(t),r=Object.keys(e);return n.length!==r.length?!1:n.every(s=>s in e&&jd(t[s],e[s]))}function y5({value:t,path:e}){return h.jsx("span",{"data-pyric-field-type":"string","data-pyric-field-path":e,children:t})}function g5({value:t,onChange:e,error:n,path:r}){return h.jsxs("label",{"data-pyric-field-type":"string","data-pyric-field-path":r,"data-pyric-error":n?"":void 0,children:[h.jsx("input",{type:"text",value:t,onChange:s=>e(s.target.value),"aria-invalid":n?"true":void 0}),n?h.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const b5={type:"string",Display:y5,Edit:g5};function v5({value:t,path:e}){return h.jsx("span",{"data-pyric-field-type":"number","data-pyric-field-path":e,children:String(t)})}function w5({value:t,onChange:e,error:n,path:r}){return h.jsxs("label",{"data-pyric-field-type":"number","data-pyric-field-path":r,"data-pyric-error":n?"":void 0,children:[h.jsx("input",{type:"number",value:Number.isFinite(t)?t:"",onChange:s=>{const o=s.target.value,c=o===""?Number.NaN:parseFloat(o);e(c)},"aria-invalid":n?"true":void 0}),n?h.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const x5={type:"number",Display:v5,Edit:w5};function S5({value:t,path:e}){return h.jsx("span",{"data-pyric-field-type":"boolean","data-pyric-field-path":e,"data-value":t?"true":"false",children:t?"true":"false"})}function _5({value:t,onChange:e,path:n}){return h.jsx("span",{"data-pyric-field-type":"boolean","data-pyric-field-path":n,"data-value":t?"true":"false",children:h.jsxs("select",{value:t?"true":"false",onChange:r=>e(r.target.value==="true"),"aria-label":"Boolean value","data-pyric-boolean-select":!0,children:[h.jsx("option",{value:"true",children:"true"}),h.jsx("option",{value:"false",children:"false"})]})})}const E5={type:"boolean",Display:S5,Edit:_5};function A5({path:t}){return h.jsx("span",{"data-pyric-field-type":"null","data-pyric-field-path":t,children:"null"})}function j5({path:t}){return h.jsx("span",{"data-pyric-field-type":"null","data-pyric-field-path":t,children:"null"})}const k5={type:"null",Display:A5,Edit:j5};function Mj(t){if(t instanceof $n)return t.toDate();const e=t,n=e?e.seconds??e._seconds:void 0,r=e?e.nanoseconds??e._nanoseconds??0:0;return typeof n=="number"?new Date(n*1e3+Math.floor(r/1e6)):new Date(NaN)}function C5({value:t,path:e}){const n=Mj(t),r=Number.isNaN(n.getTime())?"":n.toISOString();return h.jsx("time",{dateTime:r,"data-pyric-field-type":"timestamp","data-pyric-field-path":e,children:r})}function N5({value:t,onChange:e,error:n,path:r}){const s=Mj(t),o=new Date(s.getTime()-s.getTimezoneOffset()*6e4),c=Number.isNaN(o.getTime())?"":o.toISOString().slice(0,16);return h.jsxs("label",{"data-pyric-field-type":"timestamp","data-pyric-field-path":r,"data-pyric-error":n?"":void 0,children:[h.jsx("input",{type:"datetime-local",value:c,onChange:d=>{const f=d.target.value;if(!f)return;const p=new Date(f);e($n.fromDate(p))},"aria-invalid":n?"true":void 0}),n?h.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const O5={type:"timestamp",Display:C5,Edit:N5};function R5({value:t,path:e}){return h.jsxs("span",{"data-pyric-field-type":"geopoint","data-pyric-field-path":e,"data-lat":String(t.latitude),"data-lng":String(t.longitude),children:[t.latitude,", ",t.longitude]})}function T5({value:t,onChange:e,error:n,path:r}){return h.jsxs("span",{"data-pyric-field-type":"geopoint","data-pyric-field-path":r,"data-pyric-error":n?"":void 0,children:[h.jsx("label",{children:h.jsx("input",{type:"number",step:"any",min:-90,max:90,value:t.latitude,onChange:s=>{const o=parseFloat(s.target.value);try{e(new Or(o,t.longitude))}catch{}},"aria-label":"Latitude"})}),h.jsx("label",{children:h.jsx("input",{type:"number",step:"any",min:-180,max:180,value:t.longitude,onChange:s=>{const o=parseFloat(s.target.value);try{e(new Or(t.latitude,o))}catch{}},"aria-label":"Longitude"})}),n?h.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const D5={type:"geopoint",Display:R5,Edit:T5},Lj=A.createContext({});Lj.Provider;function I5(){return A.useContext(Lj)}function M5({value:t,path:e}){const{onReferenceClick:n}=I5();return n?h.jsx("button",{type:"button",onClick:()=>n(t),"data-pyric-field-type":"reference","data-pyric-field-path":e,"data-target-path":t.path,"data-pyric-clickable":"",children:t.path}):h.jsx("span",{"data-pyric-field-type":"reference","data-pyric-field-path":e,"data-target-path":t.path,children:t.path})}function L5({value:t,onChange:e,error:n,path:r}){return h.jsxs("label",{"data-pyric-field-type":"reference","data-pyric-field-path":r,"data-pyric-error":n?"":void 0,children:[h.jsx("input",{type:"text",value:t.path,placeholder:"users/alice",onChange:s=>{const o=s.target.value,c=o.split("/").filter(Boolean),d=c[c.length-1]??"",f=t.firestore??{};e({path:o,id:d,firestore:f,type:"document"})},"aria-invalid":n?"true":void 0}),n?h.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const U5={type:"reference",Display:M5,Edit:L5};function $5({value:t,path:e}){const n=t.toBase64();return h.jsx("code",{"data-pyric-field-type":"bytes","data-pyric-field-path":e,"data-byte-length":String(t.toUint8Array().byteLength),children:n})}function B5({value:t,onChange:e,error:n,path:r}){return h.jsxs("label",{"data-pyric-field-type":"bytes","data-pyric-field-path":r,"data-pyric-error":n?"":void 0,children:[h.jsx("textarea",{value:t.toBase64(),onChange:s=>{try{e(Er.fromBase64String(s.target.value))}catch{}},"aria-invalid":n?"true":void 0}),n?h.jsx("span",{"data-pyric-error-message":!0,children:n}):null]})}const q5={type:"bytes",Display:$5,Edit:B5};function Oy({value:t,path:e,fieldEditors:n}){const r=Xd(t),s=n[r];if(!s)return null;const{Display:o}=s;return h.jsx(o,{value:t,path:e,fieldEditors:n})}function Uj({label:t,value:e,path:n,fieldEditors:r,kind:s}){const o=Xd(e),c=o==="map"||o==="array",[d,f]=A.useState(!0),p=s==="key"?{"data-pyric-tree-key":""}:{"data-pyric-tree-index":""},g=s==="key"?{"data-field-name":t}:{"data-field-index":t};return c?h.jsxs("li",{"data-pyric-tree-entry":!0,"data-pyric-tree-nested":!0,...g,children:[h.jsxs("button",{type:"button","data-pyric-tree-toggle":!0,"aria-expanded":d,onClick:()=>f(b=>!b),children:[h.jsx("span",{"data-pyric-tree-chevron":!0,"aria-hidden":"true",children:"›"}),h.jsx("span",{...p,children:t})]}),d?h.jsx(Oy,{value:e,path:n,fieldEditors:r}):null]}):h.jsxs("li",{"data-pyric-tree-entry":!0,...g,children:[h.jsx("span",{"data-pyric-tree-chevron":!0,"data-pyric-tree-chevron-empty":!0,"aria-hidden":"true"}),h.jsx("span",{...p,children:t}),h.jsx(Oy,{value:e,path:n,fieldEditors:r})]})}function F5({value:t,path:e,fieldEditors:n}){const r=Object.entries(t).sort(([s],[o])=>s.localeCompare(o));return h.jsx("ul",{"data-pyric-field-type":"map","data-pyric-tree":!0,"data-pyric-field-path":e,children:r.map(([s,o])=>h.jsx(Uj,{label:s,value:o,path:e?`${e}.${s}`:s,fieldEditors:n??{},kind:"key"},s))})}const z5={type:"map",Display:F5};function P5({value:t,path:e,fieldEditors:n}){return h.jsx("ul",{"data-pyric-field-type":"array","data-pyric-tree":!0,"data-pyric-field-path":e,children:t.map((r,s)=>h.jsx(Uj,{label:String(s),value:r,path:e?`${e}[${s}]`:`[${s}]`,fieldEditors:n??{},kind:"index"},s))})}const V5={type:"array",Display:P5},N_=4;function H5(t){return t.length<=N_?`[${t.join(", ")}]`:`[${t.slice(0,N_).join(", ")}, …]`}function G5({value:t,path:e}){const n=Xi(t);return n?h.jsxs("span",{"data-pyric-field-type":"vector","data-pyric-field-path":e,"data-dimension":String(n.dimension),children:[h.jsx("span",{"data-pyric-vector-dims":!0,children:`vector · ${n.dimension}`}),h.jsx("span",{"data-pyric-vector-preview":!0,children:H5(n.values)})]}):h.jsx("span",{"data-pyric-field-type":"vector","data-pyric-field-path":e})}function K5(t){let e;try{e=JSON.parse(t)}catch{return{ok:!1,error:"Invalid JSON"}}return!Array.isArray(e)||!e.every(n=>typeof n=="number")?{ok:!1,error:"Expected a JSON array of numbers"}:{ok:!0,value:{__type__:"__vector__",value:e}}}function Y5({value:t,onChange:e,error:n,path:r}){const s=Xi(t),o=s?JSON.stringify(s.values):"[]",[c,d]=A.useState(o),[f,p]=A.useState(void 0),g=w=>{d(w);const _=K5(w);if(!_.ok){p(_.error);return}p(void 0),e(_.value)},b=s?s.dimension:0,v=f??n;return h.jsxs("label",{"data-pyric-field-type":"vector","data-pyric-field-path":r,"data-dimension":String(b),"data-pyric-error":v?"":void 0,children:[h.jsx("span",{"data-pyric-vector-dims":!0,children:`vector · ${b}`}),h.jsx("span",{"data-pyric-vector-note":!0,children:"Replace whole. Paste a JSON number array."}),h.jsx("textarea",{"data-pyric-vector-raw":!0,value:c,onChange:w=>g(w.target.value),"aria-invalid":v?"true":void 0,"aria-label":"Vector value (JSON number array)"}),v?h.jsx("span",{"data-pyric-error-message":!0,children:v}):null]})}const Z5={type:"vector",Display:G5,Edit:Y5},O_={string:b5,number:x5,boolean:E5,null:k5,timestamp:O5,geopoint:D5,reference:U5,bytes:q5,map:z5,array:V5,vector:Z5};function $j(t){return t?{...O_,...t}:O_}function ef(t={}){const e=A.useRef(null),n=t.narrowBreakpoint??480,r=t.mediumBreakpoint??768,[s,o]=A.useState("wide");return A.useEffect(()=>{const c=e.current;if(!c||typeof ResizeObserver>"u")return;const d=new ResizeObserver(f=>{const p=f[0];if(!p)return;const g=p.contentRect.width;g<n?o("narrow"):g<r?o("medium"):o("wide")});return d.observe(c),()=>d.disconnect()},[n,r]),{ref:e,size:s}}const Bj=A.createContext(null);function si(){const t=A.useContext(Bj);if(!t)throw new Error("DocumentEditor.* components must render inside <DocumentEditor.Root>");return t}function W5({initial:t,fieldEditors:e,onChange:n,children:r,className:s}){const o=Ij({initial:t}),c=$j(e),d=A.useRef(n);d.current=n,A.useEffect(()=>{var g;(g=d.current)==null||g.call(d,o)},[o]);const{ref:f,size:p}=ef();return h.jsx(Bj.Provider,{value:{editor:o,fieldEditors:c},children:h.jsx("div",{ref:f,className:s,"data-pyric-ui":"document-editor","data-pyric-is-valid":o.isValid?"":void 0,"data-pyric-is-dirty":o.isDirty?"":void 0,"data-size":p,children:r})})}function Q5(){const{editor:t}=si(),e=t.tree.childIds[t.tree.rootId]??[];return h.jsxs("div",{"data-pyric-editor-fields":!0,children:[e.map(n=>h.jsx(Mg,{nodeId:n,path:J5(t,n)},n)),h.jsx(qj,{parentId:t.tree.rootId})]})}function J5(t,e){const n=[];let r=t.tree.nodes[e];for(;r&&r.parentId!=null;){const s=t.tree.nodes[r.parentId];if(!s)break;if(s.type==="array"){const o=(t.tree.childIds[s.id]??[]).indexOf(r.id);n.unshift(`[${o}]`)}else n.unshift(r.key??"");r=s}return n.reduce((s,o)=>o.startsWith("[")?`${s}${o}`:s?`${s}.${o}`:o,"")}function Mg({nodeId:t,path:e}){const{editor:n,fieldEditors:r}=si(),s=n.tree.nodes[t];if(!s)return null;if(s.type==="map")return h.jsx(t8,{node:s,path:e});if(s.type==="array")return h.jsx(n8,{node:s,path:e});const o=r[s.type],c=o==null?void 0:o.Edit;if(!c)return null;const d=s.touched?s.error:void 0;return h.jsxs("div",{"data-pyric-field-entry":!0,"data-field-name":s.key??void 0,"data-pyric-error":d?"":void 0,onBlur:()=>n.touch(s.id),children:[h.jsx(Lg,{node:s,path:e}),h.jsx(c,{value:s.value,path:e,error:d,onChange:f=>n.setValue(s.id,f)})]})}function Lg({node:t,path:e}){const{editor:n}=si(),r=t.parentId!=null?n.tree.nodes[t.parentId]:null,s=(r==null?void 0:r.type)==="map";return t.id===n.tree.rootId?null:h.jsxs("div",{"data-pyric-field-chrome":!0,"data-pyric-field-path":e,children:[s?h.jsx("input",{type:"text",value:t.key??"",onChange:c=>n.setKey(t.id,c.target.value),"aria-label":"Field name","data-pyric-field-key-input":!0,"aria-invalid":t.touched&&t.error?"true":void 0}):null,h.jsx(e8,{node:t}),h.jsx("button",{type:"button",onClick:()=>n.remove(t.id),"data-pyric-remove":!0,"aria-label":"Remove field",children:"×"})]})}const X5=["string","number","boolean","null","timestamp","geopoint","reference","bytes","vector","map","array"];function e8({node:t}){const{editor:e}=si(),n=t.parentId!=null?e.tree.nodes[t.parentId]:null,r=X5.filter(s=>!((n==null?void 0:n.type)==="array"&&s==="array"));return h.jsx("select",{value:t.type,onChange:s=>e.setType(t.id,s.target.value),"aria-label":"Field type","data-pyric-field-type-select":!0,children:r.map(s=>h.jsx("option",{value:s,children:s},s))})}function t8({node:t,path:e}){const{editor:n}=si(),r=n.tree.childIds[t.id]??[];return h.jsxs("div",{"data-pyric-field-entry":!0,"data-pyric-field-type":"map","data-field-name":t.key??void 0,children:[t.id!==n.tree.rootId?h.jsx(Lg,{node:t,path:e}):null,h.jsx("div",{"data-pyric-map-children":!0,children:r.map(s=>{const o=n.tree.nodes[s];if(!o)return null;const c=e?`${e}.${o.key??""}`:o.key??"";return h.jsx(Mg,{nodeId:s,path:c},s)})}),h.jsx(qj,{parentId:t.id})]})}function n8({node:t,path:e}){const{editor:n}=si(),r=n.tree.childIds[t.id]??[];return h.jsxs("div",{"data-pyric-field-entry":!0,"data-pyric-field-type":"array","data-field-name":t.key??void 0,children:[h.jsx(Lg,{node:t,path:e}),h.jsx("ol",{"data-pyric-array-children":!0,children:r.map((s,o)=>{const c=e?`${e}[${o}]`:`[${o}]`;return h.jsx("li",{"data-field-index":String(o),children:h.jsx(Mg,{nodeId:s,path:c})},s)})}),h.jsx(r8,{parentId:t.id})]})}function qj({parentId:t}){const{editor:e}=si();return h.jsx("button",{type:"button","data-pyric-add-map-entry":!0,onClick:()=>e.addMapEntry(t,"","string"),children:"+ Add field"})}function r8({parentId:t}){const{editor:e}=si();return h.jsx("button",{type:"button","data-pyric-add-array-entry":!0,onClick:()=>e.addArrayEntry(t,"string"),children:"+ Add item"})}const R_={Root:W5,Fields:Q5};function s8({collections:t,isLoading:e,error:n,onSelect:r,emptyState:s,className:o}){return n?h.jsx("div",{className:o,"data-pyric-ui":"collection-list","data-pyric-error":"",role:"alert",children:n.message}):e&&t.length===0?h.jsx("div",{className:o,"data-pyric-ui":"collection-list","data-pyric-loading":""}):t.length===0?h.jsx("div",{className:o,"data-pyric-ui":"collection-list","data-pyric-empty":"",children:s}):h.jsx("ul",{className:o,"data-pyric-ui":"collection-list",children:t.map(c=>h.jsx("li",{"data-pyric-collection-entry":!0,"data-pyric-collection-id":c.id,children:h.jsx("button",{type:"button",onClick:()=>r==null?void 0:r(c),"data-pyric-collection-select":!0,children:c.id})},c.path))})}const yl=new Map;function Ug({scope:t,entries:e,equals:n=Object.is,durationMs:r=1200,ready:s=!0}){const o=A.useRef(null),c=A.useRef(new Map),d=A.useRef(new Map),[f,p]=A.useState(yl);return A.useEffect(()=>{const g=o.current;if(!s){if(g&&g.scope!==t){o.current=null;for(const v of d.current.values())clearTimeout(v);d.current.clear(),c.current.clear(),p(yl)}return}if(!g||g.scope!==t){o.current={scope:t,entries:e};for(const v of d.current.values())clearTimeout(v);d.current.clear(),c.current.clear(),p(yl);return}const b=new Map;for(const[v,w]of e){const _=g.entries.has(v),k=g.entries.get(v);if(_&&n(k,w))continue;const I=c.current.get(v)===0?1:0;c.current.set(v,I),b.set(v,{kind:_?"modified":"added",cycle:I})}o.current={scope:t,entries:e},p(v=>{const w=new Map(v);let _=b.size>0;for(const k of v.keys())e.has(k)||(w.delete(k),_=!0);for(const[k,I]of b)w.set(k,I);return _?w.size===0?yl:w:v});for(const[v,w]of b){const _=d.current.get(v);_&&clearTimeout(_);const k=setTimeout(()=>{d.current.delete(v),p(I=>{var R;if(((R=I.get(v))==null?void 0:R.cycle)!==w.cycle)return I;const N=new Map(I);return N.delete(v),N.size===0?yl:N})},r);d.current.set(v,k)}},[r,e,n,s,t]),A.useEffect(()=>()=>{for(const g of d.current.values())clearTimeout(g);d.current.clear()},[]),f}function gl(t){return t.ref}function i8({documents:t,isLoading:e,error:n,hasMore:r,onSelect:s,onLoadMore:o,renderLabel:c,renderRowAction:d,emptyState:f,className:p,updateScope:g="document-list",virtualizeThreshold:b=100,rowHeight:v=36,virtualizedHeight:w="60vh"}){const _=A.useMemo(()=>new Map(t.map(N=>[gl(N).path,N.data()])),[t]),k=Ug({scope:g,entries:_,equals:jd,ready:!e});if(n)return h.jsx("div",{className:p,"data-pyric-ui":"document-list","data-pyric-error":"",role:"alert",children:n.message});if(e&&t.length===0)return h.jsx("div",{className:p,"data-pyric-ui":"document-list","data-pyric-loading":""});if(t.length===0)return h.jsx("div",{className:p,"data-pyric-ui":"document-list","data-pyric-empty":"",children:f});const I=t.length>b;return h.jsxs("div",{className:p,"data-pyric-ui":"document-list","data-pyric-virtualized":I?"":void 0,children:[I?h.jsx(Og,{items:t,estimateSize:v,height:w,getItemKey:N=>gl(N).path,renderItem:N=>{const R=k.get(gl(N).path);return h.jsxs("div",{"data-pyric-document-entry":!0,"data-pyric-document-id":N.id,"data-pyric-update":R==null?void 0:R.kind,"data-pyric-update-cycle":R==null?void 0:R.cycle,children:[h.jsx("button",{type:"button",onClick:()=>s==null?void 0:s(gl(N)),"data-pyric-document-select":!0,"data-pyric-update":R==null?void 0:R.kind,"data-pyric-update-cycle":R==null?void 0:R.cycle,children:c?c(N):N.id}),d?h.jsx("span",{"data-pyric-document-action":!0,children:d(N)}):null]})}}):h.jsx("ul",{"data-pyric-document-list-items":!0,children:t.map(N=>{const R=gl(N),M=k.get(R.path);return h.jsxs("li",{"data-pyric-document-entry":!0,"data-pyric-document-id":N.id,"data-pyric-update":M==null?void 0:M.kind,"data-pyric-update-cycle":M==null?void 0:M.cycle,children:[h.jsx("button",{type:"button",onClick:()=>s==null?void 0:s(R),"data-pyric-document-select":!0,"data-pyric-update":M==null?void 0:M.kind,"data-pyric-update-cycle":M==null?void 0:M.cycle,children:c?c(N):N.id}),d?h.jsx("span",{"data-pyric-document-action":!0,children:d(N)}):null]},R.path)})}),r&&o?h.jsx("button",{type:"button",onClick:o,"data-pyric-load-more":!0,disabled:e,children:"Load more"}):null]})}const a8=/^__.*__$/;function Fj(t){if(t.length===0)return"Cannot be empty";if(t.includes("/"))return'Cannot contain "/"';if(t==="."||t==="..")return'Cannot be "." or ".."';if(a8.test(t))return"Cannot match __.*__ (reserved)";if(l8(t)>1500)return"Cannot exceed 1500 bytes"}function o8(t){return Fj(t)}function l8(t){return new TextEncoder().encode(t).length}function c8(t){return Fj(t)}const T_="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function u8(){let t="";for(let e=0;e<20;e++)t+=T_.charAt(Math.floor(Math.random()*T_.length));return t}const d8={ref:Hl,listAll:kg,getMetadata:R6,getBlob:B6,uploadBytes:I6,deleteObject:oj},zj=A.createContext(d8);function tf(){return A.useContext(zj)}function f8({value:t,children:e}){return A.createElement(zj.Provider,{value:t},e)}function om(t){return t.replace(/^\/+|\/+$/g,"")}function Ry(t,e){return t.fullPath<e.fullPath?-1:t.fullPath>e.fullPath?1:0}function lm(t,e){return t.some(n=>n.fullPath===e.fullPath)?t:[...t,e].sort(Ry)}function h8(t,e){const{listAll:n,ref:r}=tf(),s=om(e),[o,c]=A.useState(()=>({status:t==null?"idle":"loading",items:[],prefixes:[],error:void 0})),[d,f]=A.useState(0),p=A.useRef(new Map);A.useEffect(()=>{if(p.current.clear(),t==null){c({status:"idle",items:[],prefixes:[],error:void 0});return}let _=!1;return c({status:"loading",items:[],prefixes:[],error:void 0}),n(r(t,s)).then(k=>{_||c({status:"success",items:[...k.items].sort(Ry),prefixes:[...k.prefixes].sort(Ry),error:void 0})}).catch(k=>{_||c({status:"error",items:[],prefixes:[],error:k instanceof Error?k:new Error(String(k))})}),()=>{_=!0}},[t,s,d]);const g=A.useCallback(()=>f(_=>_+1),[]),b=A.useCallback(_=>{if(t==null)return;const k=_.endsWith("/"),I=om(_),N=s===""?"":`${s}/`;if(!I.startsWith(N)||I===s)return;const R=I.slice(N.length),M=R.indexOf("/");c(F=>{if(F.status==="idle")return F;if(M===-1)return k?(p.current.set(I,F.prefixes.some(C=>C.fullPath===I)?null:I),{...F,prefixes:lm(F.prefixes,r(t,I))}):(p.current.set(I,F.items.some(C=>C.fullPath===I)?null:I),{...F,items:lm(F.items,r(t,I))});const D=`${N}${R.slice(0,M)}`;return p.current.set(I,F.prefixes.some(C=>C.fullPath===D)?null:D),{...F,prefixes:lm(F.prefixes,r(t,D))}})},[t,s]),v=A.useCallback(_=>{const k=om(_),I=p.current.get(k);if(p.current.delete(k),I===null)return;const N=I??k;c(R=>({...R,items:R.items.filter(M=>M.fullPath!==N),prefixes:R.prefixes.filter(M=>M.fullPath!==N)}))},[]),w=A.useMemo(()=>[...o.prefixes.map(_=>({kind:"folder",name:_.name,fullPath:_.fullPath,ref:_})),...o.items.map(_=>({kind:"object",name:_.name,fullPath:_.fullPath,ref:_}))],[o.prefixes,o.items]);return{status:o.status,items:o.items,prefixes:o.prefixes,entries:w,error:o.error,refresh:g,insertItem:b,removeItem:v}}function yt(t){return t.split("/").filter(Boolean).join("/")}function p8(t={}){const{path:e,onPathChange:n,defaultPath:r=""}=t,s=e!==void 0,[o,c]=A.useState(()=>yt(r)),d=s?yt(e):o,f=A.useCallback(w=>{const _=yt(w);s||c(_),n==null||n(_)},[s,n]),p=A.useMemo(()=>d===""?[]:d.split("/"),[d]),g=A.useCallback(w=>{const _=yt(w);f(_.includes("/")||d===""?_:`${d}/${_}`)},[d,f]),b=A.useCallback(()=>{p.length!==0&&f(p.slice(0,-1).join("/"))},[p,f]),v=A.useCallback(w=>{f(w<0?"":p.slice(0,w+1).join("/"))},[p,f]);return{path:d,segments:p,setPath:f,enter:g,up:b,navigateToIndex:v}}const D_={status:"idle",blob:void 0,url:void 0,error:void 0};function m8(t,e){const{getBlob:n,getMetadata:r,ref:s}=tf(),o=e==null?null:yt(e),c=t!=null&&o!=null&&o!=="",[d,f]=A.useState(()=>({status:c?"loading":"idle",metadata:void 0,error:void 0})),[p,g]=A.useState(D_),[b,v]=A.useState(0),w=A.useRef(0);A.useEffect(()=>{if(w.current++,g(D_),!c){f({status:"idle",metadata:void 0,error:void 0});return}let N=!1;return f({status:"loading",metadata:void 0,error:void 0}),r(s(t,o)).then(R=>{N||f({status:"success",metadata:R,error:void 0})}).catch(R=>{N||f({status:"error",metadata:void 0,error:R instanceof Error?R:new Error(String(R))})}),()=>{N=!0}},[t,o,b]);const _=p.url;A.useEffect(()=>{if(_!==void 0)return()=>{URL.revokeObjectURL(_)}},[_]);const k=A.useCallback(()=>v(N=>N+1),[]),I=A.useCallback(()=>{if(t==null||o==null||o==="")return;const N=++w.current;g({status:"loading",blob:void 0,url:void 0,error:void 0}),n(s(t,o)).then(R=>{N===w.current&&g({status:"success",blob:R,url:URL.createObjectURL(R),error:void 0})}).catch(R=>{N===w.current&&g({status:"error",blob:void 0,url:void 0,error:R instanceof Error?R:new Error(String(R))})})},[t,o]);return{status:d.status,metadata:d.metadata,error:d.error,refresh:k,blobStatus:p.status,blob:p.blob,blobUrl:p.url,blobError:p.error,loadBlob:I}}function y8(){const[t,e]=A.useState(()=>new Map),n=A.useCallback(p=>t.has(p),[t]),r=A.useCallback(p=>{e(g=>{if(g.has(p.fullPath))return g;const b=new Map(g);return b.set(p.fullPath,p),b})},[]),s=A.useCallback(p=>{e(g=>{if(!g.has(p))return g;const b=new Map(g);return b.delete(p),b})},[]),o=A.useCallback(p=>{e(g=>{const b=new Map(g);return b.has(p.fullPath)?b.delete(p.fullPath):b.set(p.fullPath,p),b})},[]),c=A.useCallback(p=>{e(new Map(p.map(g=>[g.fullPath,g])))},[]),d=A.useCallback(()=>e(new Map),[]);return{selected:A.useMemo(()=>[...t.values()],[t]),size:t.size,isSelected:n,toggle:o,select:r,deselect:s,selectAll:c,clear:d}}function g8(t,e){const n=Hl(t,e);return{storage:t,bucket:n.bucket,fullPath:`${n.fullPath}/`,name:"",parent:n,root:n.root,toString:()=>`${n.toString()}/`}}function b8(t){return{...t,fullPath:`${t.fullPath}/`,name:""}}function v8(t){return{async*start(e){const n=t??{listAll:kg,deleteObject:oj};let r=0;const s=[e],o=[];for(;s.length>0;){const c=s.pop();o.push(c);const d=await n.listAll(c);s.push(...d.prefixes);for(const f of d.items)await n.deleteObject(f),r++,yield{deletedCount:r,done:!1}}for(const c of o)try{await n.deleteObject(b8(c))}catch{}yield{deletedCount:r,done:!0}}}}function w8(t,e={}){const n=tf(),[r,s]=A.useState(0),[o,c]=A.useState(!1),[d,f]=A.useState(void 0),p=A.useRef(0),g=A.useRef(e);return g.current=e,{deleteEntries:A.useCallback(async v=>{var N,R;const w=++p.current;s(0),f(void 0);const _={deleted:[],failed:[]};if(t==null||v.length===0)return _;c(!0);const k=g.current.impl??v8(n);let I=0;try{for(const M of v){(N=g.current.list)==null||N.removeItem(M.fullPath);try{if(M.kind==="object")await n.deleteObject(n.ref(t,M.fullPath)),I++;else for await(const F of k.start(n.ref(t,M.fullPath))){if(w!==p.current)return _;if(s(I+F.deletedCount),F.done){I+=F.deletedCount;break}}_.deleted.push(M.fullPath),w===p.current&&s(I)}catch(F){const D=F instanceof Error?F:new Error(String(F));_.failed.push({fullPath:M.fullPath,error:D}),(R=g.current.list)==null||R.insertItem(M.kind==="folder"?`${M.fullPath}/`:M.fullPath),w===p.current&&_.failed.length===1&&f(D)}}return _}finally{w===p.current&&c(!1)}},[n,t]),progress:r,isRunning:o,error:d}}const x8=Object.freeze({read:!0,write:!0,delete:!0,upload:!0,reasons:Object.freeze({read:[],write:[]})});function S8(t,e={}){const{paths:n,rules:r,identity:s,writeResource:o}=e,c=t==null?null:t[Wd],[d,f]=A.useState(()=>({status:t==null?"idle":"loading",rules:null,source:"none",error:void 0}));A.useEffect(()=>{if(c==null){f({status:"idle",rules:null,source:"none",error:void 0});return}if(r!=null){try{const R=typeof r=="string"?tj(r):r;f({status:"ready",rules:R,source:"option",error:void 0})}catch(R){f({status:"error",rules:null,source:"none",error:R instanceof Error?R:new Error(String(R))})}return}let N=!1;return f({status:"loading",rules:null,source:"none",error:void 0}),c.servicePromise.then(R=>{N||f({status:"ready",rules:R.rules,source:R.rules?"sandbox":"none",error:void 0})}).catch(R=>{N||f({status:"error",rules:null,source:"none",error:R instanceof Error?R:new Error(String(R))})}),()=>{N=!0}},[c,r]);const p=s!==void 0?s:(c==null?void 0:c.context.auth)??null,{rules:g,status:b}=d,v=o==null?void 0:o.size,w=o==null?void 0:o.contentType,_=A.useCallback(N=>{if(g==null)return x8;const R=yt(N),M=(c==null?void 0:c.bucket)??"pyric-default",F=R===""?`b/${M}/o`:`b/${M}/o/${R}`,D=U=>rj(g,{request:{auth:p,method:U,path:F,...U==="write"&&v!==void 0?{resource:{size:v,contentType:w}}:{}},resource:null}),C=D("read"),L=D("write");return{read:C.allowed,write:L.allowed,delete:L.allowed,upload:L.allowed,reasons:{read:C.allowed?[]:C.reasons,write:L.allowed?[]:L.reasons}}},[g,c==null?void 0:c.bucket,p,v,w]),k=typeof n=="string"?n:(n??[]).join(`
1216
- `),I=A.useMemo(()=>{const N=typeof n=="string"?[n]:n??[],R={};for(const M of N)R[yt(M)]=_(M);return R},[k,_]);return{status:b,source:d.source,advisory:!1,identity:p,verdicts:I,verdictFor:_,error:d.error}}function I_(t,e){return t===""?e:e===""?t:`${t}/${e}`}function _8(t){return t instanceof Blob?t.size:t.byteLength}function E8(t){if(t instanceof Blob){const e=t;return{path:e.webkitRelativePath||e.name,data:e}}return t}function A8(t,e={}){const{ref:n,uploadBytes:r}=tf(),s=yt(e.path??""),[o,c]=A.useState([]),d=A.useRef(e);d.current=e;const f=A.useCallback(v=>{c(w=>w.map(_=>_.id===v.id?v:_))},[]),p=A.useCallback(async v=>{var k,I,N;if(t==null)throw new Error("useObjectUpload: storage handle is null");const _=(Array.isArray(v)?v:[v]).map(R=>{const M=E8(R);return{task:{id:crypto.randomUUID(),fullPath:I_(s,yt(M.path)),status:"running",bytesTransferred:0,totalBytes:_8(M.data)},entry:M}});c(R=>[...R,..._.map(M=>M.task)]);for(const{task:R}of _)(k=d.current.list)==null||k.insertItem(R.fullPath),(N=(I=d.current).onProgress)==null||N.call(I,R);return Promise.all(_.map(async({task:R,entry:M})=>{var F,D,C,L,U,H,z;try{const q=await r(n(t,R.fullPath),M.data,M.metadata),x={...R,status:"success",bytesTransferred:R.totalBytes,metadata:q.metadata};return f(x),(D=(F=d.current).onProgress)==null||D.call(F,x),(L=(C=d.current).onComplete)==null||L.call(C,x),x}catch(q){const x={...R,status:"error",error:q instanceof Error?q:new Error(String(q))};return(U=d.current.list)==null||U.removeItem(R.fullPath),f(x),(z=(H=d.current).onError)==null||z.call(H,x),x}}))},[t,s,f,n,r]),g=A.useCallback(async v=>{var _,k;if(t==null)throw new Error("useObjectUpload: storage handle is null");const w=I_(s,yt(v));if(w==="")throw new Error("createFolder: folder name is empty");(_=d.current.list)==null||_.insertItem(`${w}/`);try{await r(g8(t,w),new Blob([]),{contentType:"text/plain"})}catch(I){throw(k=d.current.list)==null||k.removeItem(w),I}},[t,s,r]),b=A.useCallback(()=>{c(v=>v.filter(w=>w.status==="running"))},[]);return{tasks:o,isUploading:o.some(v=>v.status==="running"),upload:p,createFolder:g,clearCompleted:b}}function j8({path:t,onNavigate:e,rootLabel:n="/",separator:r="/",className:s}){const o=yt(t),c=o===""?[]:o.split("/");return h.jsx("nav",{className:s,"data-pyric-ui":"path-breadcrumb","aria-label":"Storage path",children:h.jsxs("ol",{"data-pyric-breadcrumb-list":!0,children:[h.jsx("li",{"data-pyric-breadcrumb-item":!0,children:h.jsx("button",{type:"button",onClick:()=>e==null?void 0:e(""),"data-pyric-breadcrumb-link":!0,"data-pyric-breadcrumb-root":!0,"data-pyric-current":c.length===0?"":void 0,"aria-current":c.length===0?"page":void 0,children:n})}),c.map((d,f)=>{const p=f===c.length-1,g=c.slice(0,f+1).join("/");return h.jsxs("li",{"data-pyric-breadcrumb-item":!0,children:[h.jsx("span",{"aria-hidden":!0,"data-pyric-breadcrumb-separator":!0,children:r}),h.jsx("button",{type:"button",onClick:()=>e==null?void 0:e(g),"data-pyric-breadcrumb-link":!0,"data-pyric-current":p?"":void 0,"aria-current":p?"page":void 0,children:d})]},g)})]})})}function k8({entries:t,status:e="success",error:n,onNavigate:r,onSelect:s,selectedPath:o,gate:c,renderEntry:d,renderRowAction:f,emptyState:p,className:g,virtualizeThreshold:b=100,rowHeight:v=36,virtualizedHeight:w="60vh"}){const{ref:_,size:k}=ef();if(n)return h.jsx("div",{className:g,"data-pyric-ui":"object-browser","data-pyric-error":"",role:"alert",children:n.message});if((e==="loading"||e==="idle")&&t.length===0)return h.jsx("div",{className:g,"data-pyric-ui":"object-browser","data-pyric-loading":e==="loading"?"":void 0,"data-pyric-idle":e==="idle"?"":void 0});if(t.length===0)return h.jsx("div",{className:g,"data-pyric-ui":"object-browser","data-pyric-empty":"",children:p});const I=M=>{if(!c)return{denied:!1};const F=c.verdictFor(M.fullPath);return F.read?{denied:!1}:{denied:!0,reason:F.reasons.read.join("; ")}},N=M=>{const F=M.kind==="object"&&M.fullPath===o;return h.jsxs(h.Fragment,{children:[h.jsx("button",{type:"button",onClick:()=>M.kind==="folder"?r==null?void 0:r(M.fullPath):s==null?void 0:s(M.ref),"data-pyric-entry-select":!0,"data-pyric-selected":F?"":void 0,"aria-selected":F||void 0,children:d?d(M):M.name}),f?h.jsx("span",{"data-pyric-storage-action":!0,children:f(M)}):null]})},R=t.length>b;return h.jsx("div",{ref:_,className:g,"data-pyric-ui":"object-browser","data-size":k,"data-pyric-virtualized":R?"":void 0,children:R?h.jsx(Og,{items:t,estimateSize:v,height:w,getItemKey:M=>`${M.kind}:${M.fullPath}`,renderItem:M=>{const F=I(M);return h.jsx("div",{"data-pyric-storage-entry":!0,"data-pyric-entry-kind":M.kind,"data-pyric-entry-path":M.fullPath,"data-pyric-denied":F.denied?"":void 0,"data-pyric-denied-reason":F.reason,children:N(M)})}}):h.jsx("ul",{"data-pyric-object-browser-items":!0,children:t.map(M=>{const F=I(M);return h.jsx("li",{"data-pyric-storage-entry":!0,"data-pyric-entry-kind":M.kind,"data-pyric-entry-path":M.fullPath,"data-pyric-denied":F.denied?"":void 0,"data-pyric-denied-reason":F.reason,children:N(M)},`${M.kind}:${M.fullPath}`)})})})}async function Pj(t,e,n){const r=e===""?t.name:`${e}/${t.name}`;if(t.isFile){const s=await new Promise((o,c)=>t.file(o,c));n.push({file:s,relativePath:r});return}if(t.isDirectory){const s=t.createReader();for(;;){const o=await new Promise((c,d)=>s.readEntries(c,d));if(o.length===0)break;for(const c of o)await Pj(c,r,n)}}}async function C8(t){var r;const e=[],n=t.items?Array.from(t.items):[];for(const s of n){if(s.kind!=="file")continue;const o=s.webkitGetAsEntry,c=typeof o=="function"?o.call(s):null;if(c)await Pj(c,"",e);else{const d=(r=s.getAsFile)==null?void 0:r.call(s);d&&e.push({file:d,relativePath:d.name})}}if(e.length===0)for(const s of Array.from(t.files??[]))e.push({file:s,relativePath:s.name});return e}function N8({onFiles:t,children:e,disabled:n,disabledReason:r,className:s}){const[o,c]=A.useState(!1),d=A.useRef(0),f=A.useCallback(v=>{v.preventDefault(),!n&&(d.current+=1,c(!0))},[n]),p=A.useCallback(v=>{v.preventDefault()},[]),g=A.useCallback(v=>{v.preventDefault(),!n&&(d.current=Math.max(0,d.current-1),d.current===0&&c(!1))},[n]),b=A.useCallback(v=>{if(v.preventDefault(),d.current=0,c(!1),n)return;const w=v.dataTransfer;w&&C8(w).then(_=>{_.length>0&&t(_)})},[n,t]);return h.jsx("div",{className:s,"data-pyric-ui":"upload-dropzone","data-dragging":o?"":void 0,"data-disabled":n?"":void 0,"data-disabled-reason":n?r:void 0,"aria-disabled":n||void 0,onDragEnter:f,onDragOver:p,onDragLeave:g,onDrop:b,children:e})}function O8(t){const e=t.lastIndexOf(".");return e<=0||e===t.length-1?{stem:t,ext:""}:{stem:t.slice(0,e),ext:t.slice(e)}}function R8(t){const e=/^(.*) \((\d+)\)$/.exec(t);if(!e)return{base:t,counter:null};const n=Number(e[2]);return Number.isSafeInteger(n)?{base:e[1],counter:n}:{base:t,counter:null}}function M_(t,e){if(!e.has(t))return t;const{stem:n,ext:r}=O8(t),{base:s,counter:o}=R8(n);let c=o===null?1:o+1;for(;;){const d=`${s} (${c})${r}`;if(!e.has(d))return d;c+=1}}function T8(t,e){const n=new Set(e),r=new Map;return t.map(s=>{const o=s.indexOf("/");if(o===-1){const f=M_(s,n);return n.add(f),f}const c=s.slice(0,o);let d=r.get(c);return d===void 0&&(d=M_(c,n),n.add(d),r.set(c,d)),`${d}${s.slice(o)}`})}function L_(t){const e=yt(t);if(e==="")return[];const n=e.split("/");return n.map((r,s)=>n.slice(0,s+1).join("/"))}const Vj=[];function D8(t,e){switch(e.type){case"create":{const n=L_(e.path).filter(r=>!t.includes(r));return n.length===0?t:[...t,...n].sort()}case"materialize":{const n=new Set(L_(e.path));if(n.size===0)return t;const r=t.filter(s=>!n.has(s));return r.length===t.length?t:r}case"discard":{const n=yt(e.path);if(n==="")return t;const r=t.filter(s=>s!==n&&!s.startsWith(`${n}/`));return r.length===t.length?t:r}case"clear":return t.length===0?t:Vj}}function I8(t,e){const n=yt(e),r=n===""?"":`${n}/`;return t.filter(s=>s.startsWith(r)&&s!==n&&!s.slice(r.length).includes("/")).map(s=>s.slice(r.length))}function U_(t,e){return t.includes(yt(e))}function M8(t){const e=yt(t);return e===""?"Enter a folder name.":e.split("/").some(r=>r==="."||r==="..")?'Folder names may not be "." or "..".':null}const L8=256*1024;function Ty(t){return(t.contentType??"").split(";")[0].trim().toLowerCase()}const U8={id:"image",match:t=>Ty(t).startsWith("image/"),needsBlob:!0,render:({metadata:t,blobUrl:e})=>e?h.jsx("img",{"data-pyric-preview-image":!0,src:e,alt:t.name}):null};function $8({blob:t,isJson:e}){const[n,r]=A.useState(void 0);return A.useEffect(()=>{let s=!1;return t.text().then(o=>{if(!s){if(e)try{r(JSON.stringify(JSON.parse(o),null,2));return}catch{}r(o)}}),()=>{s=!0}},[t,e]),n===void 0?null:h.jsx("pre",{"data-pyric-preview-text":!0,children:n})}const B8={id:"text",match:t=>{const e=Ty(t);return e.startsWith("text/")||e==="application/json"},needsBlob:!0,maxBytes:L8,render:({metadata:t,blob:e})=>e?h.jsx($8,{blob:e,isJson:Ty(t)==="application/json"}):null},q8=[U8,B8];function F8(t,e){for(const n of[...e??[],...q8])if(n.match(t))return n}const z8=[{key:"fullPath",label:"Path",value:t=>t.fullPath},{key:"size",label:"Size",value:t=>`${t.size}`},{key:"contentType",label:"Content type",value:t=>t.contentType},{key:"cacheControl",label:"Cache control",value:t=>t.cacheControl},{key:"timeCreated",label:"Created",value:t=>t.timeCreated},{key:"updated",label:"Updated",value:t=>t.updated}];function P8({metadata:t}){return h.jsxs("dl",{"data-pyric-object-metadata":!0,children:[z8.map(({key:e,label:n,value:r})=>{const s=r(t);return s===void 0?null:h.jsxs("div",{"data-pyric-metadata-field":e,children:[h.jsx("dt",{children:n}),h.jsx("dd",{children:s})]},e)}),Object.entries(t.customMetadata??{}).map(([e,n])=>h.jsxs("div",{"data-pyric-metadata-field":"customMetadata","data-pyric-metadata-key":e,children:[h.jsx("dt",{children:e}),h.jsx("dd",{children:n})]},`custom:${e}`))]})}function V8({storage:t,path:e,previews:n,renderMetadata:r,children:s,className:o}){var N,R;const{ref:c,size:d}=ef(),f=m8(t,e),{metadata:p,blobStatus:g,loadBlob:b}=f,v=p?F8(p,n):void 0,w=(v==null?void 0:v.maxBytes)!==void 0&&p!==void 0&&p.size>v.maxBytes,_=(v==null?void 0:v.needsBlob)===!0&&!w;if(A.useEffect(()=>{_&&g==="idle"&&b()},[_,g,b]),f.status==="idle")return h.jsx("div",{className:o,"data-pyric-ui":"object-inspector","data-pyric-idle":""});if(f.status==="loading")return h.jsx("div",{className:o,"data-pyric-ui":"object-inspector","data-pyric-loading":""});if(f.status==="error"||p===void 0)return h.jsx("div",{className:o,"data-pyric-ui":"object-inspector","data-pyric-error":"",role:"alert",children:(N=f.error)==null?void 0:N.message});let k,I={};return v===void 0?I={"data-pyric-preview-none":""}:w?I={"data-pyric-preview-too-large":""}:_&&g==="loading"?I={"data-pyric-preview-loading":""}:_&&g==="error"?(I={"data-pyric-preview-error":""},k=(R=f.blobError)==null?void 0:R.message):(!_||g==="success")&&(k=v.render({metadata:p,blob:f.blob,blobUrl:f.blobUrl})),h.jsxs("div",{ref:c,className:o,"data-pyric-ui":"object-inspector","data-size":d,children:[h.jsx("div",{"data-pyric-object-name":!0,children:p.name}),r?r(p):h.jsx(P8,{metadata:p}),h.jsx("div",{"data-pyric-object-preview":!0,"data-pyric-preview":v==null?void 0:v.id,...I,children:k}),s]})}const Hj=A.createContext(null);function H8(){const t=A.useContext(Hj);if(!t)throw new Error("useToast: missing <ToastProvider> ancestor");return t}function G8({children:t,defaultDuration:e=5e3,className:n,regionLabel:r="Notifications"}){const[s,o]=A.useState([]),c=A.useCallback(p=>{o(g=>g.filter(b=>b.id!==p))},[]),d=A.useCallback(p=>{const g=crypto.randomUUID(),b=p.duration??e;return o(v=>[...v,{id:g,...p}]),b>0&&window.setTimeout(()=>{o(v=>v.filter(w=>w.id!==g))},b),g},[e]),f=A.useMemo(()=>({toast:d,dismiss:c,toasts:s}),[d,c,s]);return h.jsxs(Hj.Provider,{value:f,children:[t,h.jsx(K8,{toasts:s,dismiss:c,className:n,regionLabel:r})]})}function K8({toasts:t,dismiss:e,className:n,regionLabel:r}){const[s,o]=A.useState(!1);return A.useEffect(()=>o(!0),[]),!s||typeof document>"u"?null:Ng.createPortal(h.jsx("ol",{"aria-label":r,"aria-live":"polite","data-pyric-ui":"toast-region",className:n,children:t.map(c=>h.jsxs("li",{"data-pyric-toast":!0,"data-pyric-toast-kind":c.kind??"info",role:c.kind==="error"?"alert":"status",children:[h.jsx("div",{"data-pyric-toast-title":!0,children:c.title}),c.body?h.jsx("div",{"data-pyric-toast-body":!0,children:c.body}):null,h.jsx("button",{type:"button","data-pyric-toast-dismiss":!0,"aria-label":"Dismiss",onClick:()=>e(c.id),children:"×"})]},c.id))}),document.body)}function Y8({storage:t,entries:e,impl:n,list:r,gate:s,title:o,body:c,confirmLabel:d="Delete",onDeleted:f,onFailed:p,renderTrigger:g,className:b}){const v=go(),{toast:w}=H8(),{deleteEntries:_,isRunning:k,progress:I}=w8(t,{impl:n,list:r}),N=s?e.map(D=>({entry:D,verdict:s.verdictFor(D.fullPath)})).filter(D=>!D.verdict.delete):[],R=N.length===0?void 0:`Delete denied for ${N[0].entry.fullPath}${N.length>1?` (+${N.length-1} more)`:""}: ${N[0].verdict.reasons.write.join("; ")}`,M=k||e.length===0||t==null||N.length>0,F=async()=>{if(M||!await v({title:o??(e.length===1?`Delete ${e[0].fullPath}?`:`Delete ${e.length} items?`),body:c??h.jsx("ul",{"data-pyric-delete-selection-paths":!0,children:e.map(L=>h.jsxs("li",{"data-pyric-entry-kind":L.kind,children:[L.fullPath,L.kind==="folder"?"/":""]},L.fullPath))}),destructive:!0,confirmLabel:d}))return;const C=await _(e);C.failed.length===0?(w({title:`Deleted ${C.deleted.length} ${C.deleted.length===1?"item":"items"}`,kind:"success"}),f==null||f(C)):(w({title:`Delete failed for ${C.failed.length} of ${e.length}`,kind:"error",body:h.jsx("ul",{"data-pyric-delete-selection-failures":!0,children:C.failed.map(L=>h.jsxs("li",{children:[L.fullPath,":"," ",L.error.code??L.error.message]},L.fullPath))})}),p==null||p(C))};return g?h.jsx(h.Fragment,{children:g({onClick:F,isRunning:k,progress:I,disabled:M,deniedReason:R})}):h.jsx("button",{type:"button",onClick:F,className:b,disabled:M,title:R,"data-pyric-ui":"delete-selection","data-pyric-destructive":"","data-pyric-running":k?"":void 0,"data-pyric-denied":R?"":void 0,"data-pyric-denied-reason":R,children:k?`Deleting… (${I})`:d})}function kd(t){const e=t.split("/").filter(Boolean),n=[];let r="";return e.forEach((s,o)=>{r=r?`${r}/${s}`:s,n.push({kind:o%2===0?"collection":"document",id:s,path:r})}),n}function Gj(t){const e=t.indexOf("?");return _g(e===-1?t:t.slice(0,e),e===-1?"":t.slice(e))}function Z8(t){const{tab:e,rest:n,query:r}=Gj(t),s=n.join("/");return e==="firestore"?{view:"firestore",path:kd(s)}:e==="auth"?{view:"auth",uid:n[0]??null}:e==="storage"?s?{view:"storage",kind:r.kind==="prefix"?"prefix":"object",path:s}:{view:"storage",kind:"root"}:null}function W8(t){switch(t.view){case"firestore":{const e=t.path[t.path.length-1];return{tab:"firestore",rest:e?e.path.split("/").filter(Boolean):[]}}case"auth":return{tab:"auth",rest:t.uid?[t.uid]:[]};case"storage":return t.kind==="root"?{tab:"storage"}:{tab:"storage",rest:t.path.split("/").filter(Boolean),...t.kind==="prefix"?{query:{kind:"prefix"}}:{}}}}function Kj(t){const{tab:e,query:n}=Gj(t),r=Z8(t),s=e==="traffic"?n.inspect??null:null;return{target:r,selectedInspectId:s}}let $_=null,Dy=Kj("");function Q8(){const t=PA();return t!==$_&&($_=t,Dy=Kj(t)),Dy}function J8(){return Dy}function Iu(t){Jn(W8(t))}function X8(t){Jn({tab:"traffic",query:{inspect:t}})}function nf(){const t=A.useSyncExternalStore(ec,Q8,J8),e=A.useCallback(s=>Iu(s),[]),n=A.useCallback(s=>{switch(s.kind){case"user":Iu({view:"auth",uid:s.uid});break;case"storage":Iu({view:"storage",kind:"object",path:s.objectPath});break;case"document":Iu({view:"firestore",path:kd(s.path)});break}},[]),r=A.useCallback(s=>X8(s),[]);return A.useMemo(()=>({target:t.target,navigate:e,navigateRef:n,selectedInspectId:t.selectedInspectId,navigateInspect:r}),[t,e,n,r])}const eq={narrowBreakpoint:640,mediumBreakpoint:920};function tq(t){switch(t){case"narrow":return 1;case"medium":return 2;case"wide":return 3}}function nq(t,e){const n=tq(e),r=Math.min(Math.max(t,1),n),s=Math.max(t-r,0),o=e==="narrow"?0:n-r;return{startIndex:s,visibleCount:r,emptySlots:o}}function cm({label:t,error:e,hint:n,children:r}){return h.jsxs("div",{className:"fs-modal__group",children:[h.jsx("span",{className:"fs-modal__label",children:t}),r,e?h.jsx("span",{className:"fs-modal__err",role:"alert",children:e}):n?h.jsx("span",{className:"fs-modal__hint",children:n}):null]})}function Yj({mode:t,parentPath:e,onCreate:n,onClose:r}){const[s,o]=A.useState(""),[c,d]=A.useState(()=>u8()),[f,p]=A.useState(null),[g,b]=A.useState(null),[v,w]=A.useState(!1),_=A.useRef(null),k=t==="collection"&&s?o8(s):void 0,I=c?c8(c):void 0,R=!(t==="collection"&&(!s||k))&&!!c&&!I&&!v;A.useEffect(()=>{const D=C=>{C.key==="Escape"&&!v&&r()};return document.addEventListener("keydown",D),()=>document.removeEventListener("keydown",D)},[v,r]);const M=async()=>{if(!(!R||!f)){if(!f.isValid){f.touchAll();return}w(!0),b(null);try{await n({collectionId:t==="collection"?s:null,docId:c,data:Nj(f.tree)}),r()}catch(D){b(D instanceof Error?D:new Error(String(D))),w(!1)}}},F=t==="collection"?"Start a collection":"Add a document";return h.jsx("div",{className:"fs-modal-backdrop",onMouseDown:D=>{D.target===D.currentTarget&&!v&&r()},children:h.jsxs("div",{ref:_,className:"fs-modal",role:"dialog","aria-modal":"true","aria-label":F,"data-pyric-ui":"fs-create-modal","data-fs-create-mode":t,children:[h.jsx("h2",{className:"fs-modal__title",children:F}),h.jsx(cm,{label:"Parent path",children:h.jsx("span",{className:"fs-modal__path",children:e})}),t==="collection"?h.jsx(cm,{label:"Collection ID",error:k,children:h.jsx("input",{autoFocus:!0,type:"text",value:s,placeholder:"e.g. users",onChange:D=>o(D.target.value),"data-pyric-field":"collection-id","aria-invalid":k?"true":void 0})}):null,h.jsx(cm,{label:"Document ID",error:c?I:"Cannot be empty",hint:"Auto-generated — edit to set your own.",children:h.jsx("input",{autoFocus:t==="document",type:"text",value:c,onChange:D=>d(D.target.value),"data-pyric-field":"doc-id","aria-invalid":I||!c?"true":void 0})}),h.jsxs("div",{className:"fs-modal__group",children:[h.jsx("span",{className:"fs-modal__label",children:"Fields"}),h.jsx("div",{className:"fs-modal__fields",children:h.jsx(R_.Root,{initial:{},onChange:p,children:h.jsx(R_.Fields,{})})})]}),g?h.jsx("p",{className:"fs-modal__err",role:"alert",children:g.message}):null,h.jsxs("div",{className:"fs-modal__actions",children:[h.jsx("button",{type:"button",className:"fs-editor__cancel",disabled:v,onClick:r,children:"Cancel"}),h.jsx("button",{type:"button",className:"fs-editor__save",disabled:!R,onClick:()=>void M(),children:v?"Saving…":"Save"})]})]})})}function Zj({items:t,label:e="More actions"}){const[n,r]=A.useState(!1),[s,o]=A.useState(null),c=A.useRef(null),d=()=>{var f;if(!n){const p=(f=c.current)==null?void 0:f.getBoundingClientRect();p&&o({top:p.bottom+4,right:window.innerWidth-p.right})}r(p=>!p)};return A.useEffect(()=>{if(!n)return;const f=p=>{var g;p.key==="Escape"&&(r(!1),(g=c.current)==null||g.focus())};return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[n]),h.jsxs("span",{className:"fs-overflow","data-pyric-ui":"fs-overflow-menu",children:[h.jsx("button",{ref:c,type:"button",className:"fs-overflow__trigger","aria-haspopup":"menu","aria-expanded":n,"aria-label":e,onClick:d,children:h.jsx("span",{"aria-hidden":"true",children:"⋮"})}),n?h.jsxs(h.Fragment,{children:[h.jsx("div",{className:"fs-overflow__backdrop",onMouseDown:()=>r(!1)}),h.jsx("div",{className:"fs-overflow__menu",role:"menu",style:s?{top:s.top,right:s.right}:void 0,children:t.map(f=>h.jsx("button",{type:"button",role:"menuitem",className:"fs-overflow__item","data-destructive":f.destructive?"":void 0,disabled:f.disabled,onClick:()=>{r(!1),f.onSelect()},children:f.label},f.label))})]}):null]})}function Wj(t){return JSON.stringify(t)}function rq(t,e){const n=new Map,r=(s,o)=>{const c=e(s),d=Wj(o);if(c==="map"){const f=s,p=Object.keys(f).sort();n.set(d,[c,p]);for(const g of p)r(f[g],[...o,["field",g]]);return}if(c==="array"){const f=s;n.set(d,[c,f.map((p,g)=>String(g))]),f.forEach((p,g)=>r(p,[...o,["index",g]]));return}n.set(d,[c,s])};for(const[s,o]of Object.entries(t))r(o,[["field",s]]);return n}function Qj(t,e){const n=[];let r=t.nodes[e];for(;r&&r.parentId!=null;){const s=t.nodes[r.parentId];if(!s)break;s.type==="array"?n.unshift(["index",(t.childIds[s.id]??[]).indexOf(r.id)]):n.unshift(["field",r.key??""]),r=s}return Wj(n)}function sq(t,e){const n=[];let r=t.nodes[e];for(;r&&r.parentId!=null;){const s=t.nodes[r.parentId];if(!s)break;if(s.type==="array"){const o=(t.childIds[s.id]??[]).indexOf(r.id);n.unshift(`[${o}]`)}else n.unshift(r.key??"");r=s}return n.reduce((s,o)=>o.startsWith("[")?`${s}${o}`:s?`${s}.${o}`:o,"")}function iq(t,e){const n=t.nodes[e],r=(n==null?void 0:n.parentId)!=null?t.nodes[n.parentId]:null;if((r==null?void 0:r.type)==="array"){const s=(t.childIds[r.id]??[]).indexOf(e);return{label:String(s),isArrayChild:!0}}return{label:(n==null?void 0:n.key)??"",isArrayChild:!1}}function B_(t,e,n){switch(t.type){case"map":return"{…}";case"array":return"[…]";case"string":return JSON.stringify(t.value);case"null":return"null";case"vector":{const r=e(t.value);return r?n(r):"vector"}default:return String(t.value)}}const aq=42;function oq(t,e,n,r=aq){const s=t.nodes[e],o=t.childIds[e]??[];let c;return s.type==="array"?c=`[${o.slice(0,3).map(f=>B_(t.nodes[f],n.asVectorView,n.vectorPreview)).join(", ")}${o.length>3?", …":""}]`:c=`{${o.slice(0,2).map(f=>`"${t.nodes[f].key}": ${B_(t.nodes[f],n.asVectorView,n.vectorPreview)}`).join(", ")}${o.length>2?", …":""}}`,c.length>r?`${c.slice(0,r-1)}…`:c}function lq(t,e,n){return e.parentId==null?!1:(t.childIds[e.parentId]??[]).some(s=>{var o;return s!==e.id&&((o=t.nodes[s])==null?void 0:o.key)===n})}function cq(t){return t.shiftKey===!0}const Jj=["string","number","boolean","null","timestamp","geopoint","reference","bytes","vector"],uq=[...Jj,"map","array"];function dq({snapshot:t,documentRef:e,onCommit:n,onDeleteDocument:r,onDeleteDocumentFields:s,fieldEditors:o,onReferenceClick:c,onStartCollection:d,firestore:f,listSubcollections:p,onSubcollectionClick:g}){const b=A.useMemo(()=>(t==null?void 0:t.data())??{},[t]),v=A.useMemo(()=>b,[]),w=Ij({initial:v}),_=w.replaceData,k=A.useMemo(()=>$j(o),[o]),I=go(),[N,R]=A.useState(()=>new Set),[M,F]=A.useState(null),D=A.useRef(t),C=A.useRef(new Set),L=A.useRef(!1),[U,H]=A.useState(null),z=A.useMemo(()=>rq(b,Xd),[b]),q=Ug({scope:e.path,entries:z,equals:jd,ready:M===null});A.useEffect(()=>{L.current&&(L.current=!1,H(null),n(w.toData()).catch(se=>{H(se instanceof Error?se:new Error(String(se)))}))},[w.tree]),A.useEffect(()=>{!t||t===D.current||M!==null||(D.current=t,C.current.clear(),_(t.data()??{}))},[M,_,t]);const x=A.useCallback(se=>{R(B=>{const ee=new Set(B);return ee.has(se)?ee.delete(se):ee.add(se),ee})},[]),[E,O]=A.useState(null),T=A.useCallback((se,B)=>{if(B==="map"?w.addMapEntry(se,"","string"):w.addArrayEntry(se,"string"),se!==w.tree.rootId){const ee=Qj(w.tree,se);R(ae=>new Set(ae).add(ee))}O(se)},[w]);A.useEffect(()=>{if(!E)return;const se=w.tree.childIds[E]??[],B=se[se.length-1];B&&!M&&(C.current.add(B),F(B),O(null))},[w.tree,E]);const P=A.useCallback(se=>{w.remove(se),C.current.delete(se),L.current=!0,M===se&&F(null)},[w,M]),$=A.useCallback(async(se,B,ee)=>{if(cq(ee)){P(se.id);return}await I({title:`Delete field "${B}"?`,destructive:!0,confirmLabel:"Delete"})&&P(se.id)},[I,P]),K=e.id,W=w.tree.childIds[w.tree.rootId]??[];return h.jsxs("div",{"data-pyric-ui":"fs-doctree",className:"fs-doctree",children:[h.jsxs("div",{className:"fs-doctree__head",children:[h.jsx("span",{className:"fs-doctree__docid",children:K}),h.jsx(Zj,{items:[{label:"Delete document fields",onSelect:()=>{(async()=>await I({title:"Delete all fields?",body:"The document itself is kept, empty.",destructive:!0,confirmLabel:"Delete fields"})&&s())()},destructive:!0},{label:"Delete document",onSelect:r,destructive:!0}]})]}),U?h.jsx("p",{className:"fs-doctree__err",children:U.message}):null,h.jsxs("ul",{className:"fs-doctree__rows",children:[d?h.jsx("li",{className:"fs-doctree__action-row",children:h.jsxs("button",{type:"button",className:"fs-doctree__action",onClick:d,children:[h.jsx("span",{"aria-hidden":"true",children:"+"})," Start collection"]})}):null,h.jsx("li",{className:"fs-doctree__action-row",children:h.jsxs("button",{type:"button",className:"fs-doctree__action",onClick:()=>T(w.tree.rootId,"map"),children:[h.jsx("span",{"aria-hidden":"true",children:"+"})," Add field"]})}),W.map(se=>h.jsx(Xj,{nodeId:se,depth:0,editor:w,registry:k,expanded:N,onToggle:x,editingId:M,setEditingId:F,newIdsRef:C,onAdd:T,onDelete:$,onCommitNeeded:()=>{L.current=!0},onReferenceClick:c,updates:q},se))]}),f&&p?h.jsx(ek,{firestore:f,documentRef:e,listSubcollections:p,onSubcollectionClick:g}):null]})}function Xj({nodeId:t,depth:e,editor:n,registry:r,expanded:s,onToggle:o,editingId:c,setEditingId:d,newIdsRef:f,onAdd:p,onDelete:g,onCommitNeeded:b,onReferenceClick:v,updates:w}){const{tree:_}=n,k=_.nodes[t];if(!k)return null;const{label:I,isArrayChild:N}=iq(_,t),R=k.type==="map"||k.type==="array",M=sq(_,t),F=Qj(_,t),D=w.get(F),C=s.has(F),L=c===t,U=f.current.has(t);return L?h.jsx("li",{className:"fs-doctree__row fs-doctree__row--editing","data-pyric-doctree-depth":e,style:{"--fs-depth":e},children:h.jsx(fq,{node:k,isNew:U,isArrayChild:N,tree:_,editor:n,registry:r,path:M,onCommitNeeded:b,onDone:()=>{f.current.delete(t),d(null)},onCancelNew:()=>{n.remove(t),f.current.delete(t),d(null)}})}):h.jsxs("li",{className:"fs-doctree__row","data-pyric-doctree-depth":e,"data-pyric-doctree-nested":R?"":void 0,style:{"--fs-depth":e},children:[h.jsxs("div",{className:"fs-doctree__line","data-pyric-update":D==null?void 0:D.kind,"data-pyric-update-cycle":D==null?void 0:D.cycle,children:[R?h.jsx("button",{type:"button",className:"fs-doctree__caret","aria-expanded":C,onClick:()=>o(F),children:h.jsx("span",{"aria-hidden":"true",children:C?"▼":"▶"})}):h.jsx("span",{className:"fs-doctree__caret fs-doctree__caret--empty","aria-hidden":"true"}),N?h.jsx("span",{className:"fs-doctree__chip",children:I}):h.jsx("span",{className:"fs-doctree__key",children:I}),R?C?null:h.jsx("span",{className:"fs-doctree__preview",children:oq(_,t,{asVectorView:Xi,vectorPreview:kj})}):h.jsx("span",{className:"fs-doctree__value",children:h.jsx(Oy,{value:k.value,path:M,fieldEditors:r})}),h.jsxs("span",{className:"fs-doctree__hover",children:[h.jsxs("span",{className:"fs-doctree__typenote",children:["(",k.type,")"]}),R?h.jsx("button",{type:"button",className:"fs-doctree__icon",title:"Add field","aria-label":`Add field to ${I||"document"}`,onClick:()=>p(t,k.type==="array"?"array":"map"),children:"+"}):h.jsx("button",{type:"button",className:"fs-doctree__icon",title:"Edit","aria-label":`Edit ${I}`,onClick:()=>d(t),children:"✎"}),h.jsx("button",{type:"button",className:"fs-doctree__icon fs-doctree__icon--danger",title:"Delete (shift-click to skip confirmation)","aria-label":`Delete ${I||"field"} (shift-click to skip confirmation)`,onClick:H=>void g(k,I,{shiftKey:H.shiftKey}),children:"🗑"})]})]}),R&&C?h.jsxs("ul",{className:"fs-doctree__children",children:[(_.childIds[t]??[]).map(H=>h.jsx(Xj,{nodeId:H,depth:e+1,editor:n,registry:r,expanded:s,onToggle:o,editingId:c,setEditingId:d,newIdsRef:f,onAdd:p,onDelete:g,onCommitNeeded:b,onReferenceClick:v,updates:w},H)),h.jsx("li",{className:"fs-doctree__action-row fs-doctree__action-row--nested",children:h.jsxs("button",{type:"button",className:"fs-doctree__action",onClick:()=>p(t,k.type==="array"?"array":"map"),children:[h.jsx("span",{"aria-hidden":"true",children:"+"})," ",k.type==="array"?"Add item":"Add field"]})})]}):null]})}function fq({node:t,isNew:e,isArrayChild:n,tree:r,editor:s,registry:o,path:c,onCommitNeeded:d,onDone:f,onCancelNew:p}){const[g,b]=A.useState(t.key??""),[v,w]=A.useState(t.type),[_,k]=A.useState(t.value),[I,N]=A.useState(!1),R=n?void 0:g===""?"Field name is required":lq(r,t,g)?"Field name must be unique":void 0,M=v==="map"||v==="array"?void 0:Rj(v,_),F=!R&&!M,D=()=>{if(!F){N(!0);return}n||s.setKey(t.id,g),v!==t.type&&s.setType(t.id,v),v!=="map"&&v!=="array"&&s.setValue(t.id,_),d(),f()},C=()=>{e?p():f()},L=o[v],U=L==null?void 0:L.Edit,H=v!=="map"&&v!=="array"&&U?h.jsx(U,{value:_,path:c,error:I?M:void 0,onChange:x=>k(x)}):v==="map"||v==="array"?h.jsxs("span",{className:"fs-doctree__editnote",children:["Saves as an empty ",v," — add its children afterward."]}):null,z=h.jsxs("span",{className:"fs-doctree__editactions",children:[h.jsx("button",{type:"button",className:"fs-doctree__editsave",onClick:D,"aria-label":"Save field",children:"✓"}),h.jsx("button",{type:"button",className:"fs-doctree__editcancel",onClick:C,"aria-label":"Cancel edit",children:"✕"})]}),q=h.jsx("select",{className:"fs-doctree__edittype",value:v,onChange:x=>{const E=x.target.value;w(E),E!=="map"&&E!=="array"&&E!==v&&k(hq(E))},"aria-label":"Field type",children:(e?uq:Jj).map(x=>h.jsx("option",{value:x,children:x},x))});return h.jsxs("div",{className:"fs-doctree__editrow",onKeyDown:x=>{x.key==="Enter"&&!x.target.matches("textarea")?(x.preventDefault(),D()):x.key==="Escape"&&(x.preventDefault(),C())},children:[n?null:h.jsxs("div",{className:"fs-doctree__editline",children:[h.jsx("input",{type:"text",className:"fs-doctree__editkey",value:g,placeholder:"Field name",autoFocus:e,onChange:x=>b(x.target.value),onBlur:()=>N(!0),"aria-label":"Field name","aria-invalid":I&&R?"true":void 0}),q]}),h.jsxs("div",{className:"fs-doctree__editline",children:[n?q:null,H,z]}),I&&R?h.jsx("span",{className:"fs-doctree__editerr",children:R}):null]})}function hq(t){switch(t){case"string":return"";case"number":return 0;case"boolean":return!1;default:return null}}function ek({firestore:t,documentRef:e,listSubcollections:n,onSubcollectionClick:r}){const{subcollections:s,isLoading:o}=m5({firestore:t,documentRef:e,listSubcollections:n});return!o&&s.length===0?null:h.jsxs("section",{"data-pyric-ui":"fs-doctree-subcollections","data-pyric-loading":o?"":void 0,children:[h.jsx("div",{className:"fs-doctree__subhead",children:"Subcollections"}),h.jsx("ul",{className:"fs-doctree__sublist",children:s.map(c=>h.jsx("li",{children:r?h.jsxs("button",{type:"button",className:"fs-doctree__subrow",onClick:()=>r(c),"aria-label":`Open subcollection ${c.id}`,children:[h.jsx("span",{children:c.id}),h.jsx("span",{className:"fs-doctree__subtype",children:"subcollection"}),h.jsx("span",{"aria-hidden":"true",children:"›"})]}):h.jsxs("div",{className:"fs-doctree__subrow",children:[h.jsx("span",{children:c.id}),h.jsx("span",{className:"fs-doctree__subtype",children:"subcollection"})]})},c.path))})]})}function pq(t){return t.split("/").filter(Boolean).length%2===0}function tk(t,e){async function*n(s,o,c=!1){const d=await e.listSubcollections(s.path);for(const f of d)yield*r(t.collection(s,f),o);c||(await t.deleteDoc(s),o.n++,yield{deletedCount:o.n,done:!1})}async function*r(s,o){const c=await e.listDocuments(s.path);for(const d of c){const f=d.path.split("/").pop();f&&(yield*n(t.doc(s,f),o,d.phantom===!0))}}return{async*start(s){const o={n:0};pq(s.path)?yield*n(s,o):yield*r(s,o),yield{deletedCount:o.n,done:!0}}}}async function nk(t,e){for await(const n of t.start(e))if(n.done)return}async function rk({confirm:t,ref:e,api:n,recursiveImpl:r}){let s=!1;return await t({title:`Delete document "${e.id}"?`,body:h.jsxs("label",{className:"fs-delete-recursive",children:[h.jsx("input",{type:"checkbox",onChange:c=>{s=c.currentTarget.checked}}),h.jsx("span",{children:"Also delete subcollections recursively. Leave this off to keep nested data."})]}),destructive:!0,confirmLabel:"Delete document"})?(s?await nk(r,e):await n.deleteDoc(e),!0):!1}function mq(t){const e=t.exists;return typeof e=="function"?e.call(t):e}async function yq(t,e,n,r){const s=t.doc(e,n),o=await t.getDoc(s);if(typeof o.exists=="function"?o.exists():!!o.exists)throw new Error(`Document "${n}" already exists here — choose a different ID.`);await t.setDoc(s,r)}function gq(t){return{id:t.id,ref:t,data:()=>{},__pyricPhantom:!0}}function q_(t){return t.__pyricPhantom===!0}function bq(t,e,n){const r=n.split("/");if(r.length===1)return t.collection(e,n);const s=r[r.length-1],o=r.slice(0,-1).join("/");return t.collection(t.doc(e,o),s)}function vq({handles:t}){var F;const{target:e,navigate:n}=nf(),r=t.adminFirestore,s=Dg(),o=A.useMemo(()=>(e==null?void 0:e.view)==="firestore"?e.path:[],[e]),c=A.useCallback(D=>{const C=typeof D=="function"?D(o):D;n({view:"firestore",path:C})},[n,o]),d=(D,C)=>c(L=>[...L.slice(0,D+1),C]),[f,p]=A.useState(null),g=A.useCallback(async({collectionId:D,docId:C,data:L})=>{if(!f||!D)return;const U=f.parentDocPath,H=U?s.collection(s.doc(r,U),D):s.collection(r,D);await yq(s,H,C,L);const z=U?`${U}/${D}`:D;n({view:"firestore",path:kd(`${z}/${C}`)})},[s,r,f,n]),b=[h.jsx(Sq,{api:s,firestore:r,collectionIds:t.listRootCollections(),onSelect:D=>c([{kind:"collection",id:D,path:D}]),onStartCollection:()=>p({parentDocPath:null})},"__root__"),...o.map((D,C)=>{var L;return D.kind==="collection"?h.jsx(_q,{api:s,firestore:r,handles:t,collectionPath:D.path,selectedId:((L=o[C+1])==null?void 0:L.id)??null,onSelect:U=>d(C,{kind:"document",id:U.id,path:U.path}),onCollectionDeleted:()=>c(U=>U.slice(0,C))},D.path):h.jsx(Eq,{api:s,firestore:r,handles:t,docPath:D.path,onOpenSubcollection:U=>d(C,{kind:"collection",id:U.id,path:U.path}),onReferenceClick:U=>n({view:"firestore",path:kd(U.path)}),onStartCollection:()=>p({parentDocPath:D.path}),onDeleted:()=>c(U=>U.slice(0,C))},D.path)})],{ref:v,size:w}=ef(eq),{startIndex:_,visibleCount:k,emptySlots:I}=nq(b.length,w),N=b.slice(_,_+k),R=o.length===0?"Select a collection":((F=o[o.length-1])==null?void 0:F.kind)==="collection"?"Select a document":null,M=[...N,...Array.from({length:I},(D,C)=>h.jsx(xq,{hint:C===0?R:null},`__empty_${C}__`))];return A.useEffect(()=>{if(w==="wide")return;const D=v.current;if(!D)return;const C=document.activeElement;if(C&&C!==document.body&&D.contains(C))return;const L=D.querySelector(".fs-columns > .fs-col:last-child");L&&(L.tabIndex=-1,L.focus({preventScroll:!0}))},[o.length,w]),h.jsx(Tg,{children:h.jsxs("div",{ref:v,"data-pyric-ui":"fs-browser","data-fs-depth":o.length,"data-size":w,children:[h.jsx(wq,{path:o,onHome:()=>c([]),onJump:D=>c(C=>C.slice(0,D+1))}),h.jsx("div",{className:"fs-columns",children:M}),f?h.jsx(Yj,{mode:"collection",parentPath:f.parentDocPath?`/${f.parentDocPath}`:"/",onCreate:g,onClose:()=>p(null)}):null]})})}function wq({path:t,onHome:e,onJump:n}){return h.jsxs("nav",{"data-pyric-ui":"fs-breadcrumb","aria-label":"Firestore path",children:[h.jsx("button",{type:"button",className:"fs-crumb",onClick:e,children:"home"}),t.map((r,s)=>h.jsxs(A.Fragment,{children:[h.jsx("span",{className:"fs-crumb-sep","aria-hidden":!0,children:"›"}),s===t.length-1?h.jsx("span",{className:"fs-crumb fs-crumb--current",children:r.id}):h.jsx("button",{type:"button",className:"fs-crumb",onClick:()=>n(s),children:r.id})]},r.path))]})}function xq({hint:t}){return h.jsx("section",{"data-pyric-ui":"fs-empty-col",className:"fs-pane fs-col fs-col--empty","aria-hidden":t?void 0:!0,children:t?h.jsx("p",{className:"fs-empty",children:t}):null})}function Sq({api:t,firestore:e,collectionIds:n,onSelect:r,onStartCollection:s}){const o=A.useMemo(()=>n.map(c=>t.collection(e,c)),[t,e,n]);return h.jsxs("section",{"data-pyric-ui":"fs-collections",className:"fs-pane fs-col",children:[h.jsxs("div",{className:"fs-phead",children:[h.jsx("span",{className:"fs-phead-title",children:"Collections"}),h.jsx("button",{type:"button",className:"fs-add",onClick:s,children:"+ New"})]}),h.jsx(s8,{collections:o,onSelect:c=>r(c.id),emptyState:h.jsx("p",{className:"fs-empty",children:"No collections yet. App or agent writes show up here."})})]})}function _q({api:t,firestore:e,handles:n,collectionPath:r,selectedId:s,onSelect:o,onCollectionDeleted:c}){const d=A.useMemo(()=>bq(t,e,r),[t,e,r]),{documents:f,isLoading:p,error:g,subscriptionGeneration:b,hasMore:v,loadMore:w,createDocument:_}=p5({collection:d,mode:"live"}),[k,I]=A.useState([]);A.useEffect(()=>{let q=!1;return Promise.resolve(n.listDocuments(r)).then(x=>{q||I(x.filter(E=>E.phantom).map(E=>E.path.split("/").pop()??""))}).catch(()=>{q||I([])}),()=>{q=!0}},[n,r,f]);const N=A.useMemo(()=>{const q=new Set(f.map(x=>x.id));return[...f,...k.filter(x=>x.length>0&&!q.has(x)).map(x=>gq(t.doc(e,`${r}/${x}`)))]},[f,k,t,e,r]),R=r.split("/").pop()??r,[M,F]=A.useState(null),[D,C]=A.useState(!1),L=go(),U=A.useMemo(()=>tk(t,n),[t,n]),H=A.useCallback(async q=>{F(null);try{await rk({confirm:L,ref:q,api:t,recursiveImpl:U})}catch(x){F(x instanceof Error?x:new Error(String(x)))}},[t,L,U]),z=A.useCallback(async()=>{if(await L({title:`Delete collection "${R}"?`,body:"This deletes every document in it (and their subcollections).",destructive:!0,confirmLabel:"Delete collection"})){F(null);try{await nk(U,d),c()}catch(x){F(x instanceof Error?x:new Error(String(x)))}}},[L,U,d,R,c]);return h.jsxs("section",{"data-pyric-ui":"fs-documents",className:"fs-pane fs-col",children:[h.jsxs("div",{className:"fs-phead",children:[h.jsx("span",{className:"fs-phead-title",children:R}),h.jsx("span",{className:"fs-phead-actions",children:h.jsx("button",{type:"button",className:"fs-add",onClick:()=>C(!0),children:"+ New"})}),h.jsx(Zj,{items:[{label:"Delete collection",onSelect:()=>void z(),destructive:!0}]})]}),D?h.jsx(Yj,{mode:"document",parentPath:`/${r}`,onCreate:async({docId:q,data:x})=>{const E=await _(q,x,{onExisting:"fail"});o(E)},onClose:()=>C(!1)}):null,h.jsx(i8,{documents:N,isLoading:p,error:g,updateScope:`${r}:${b}`,hasMore:v,onLoadMore:w,onSelect:o,renderLabel:q=>{const x=q.ref;return h.jsx("span",{"data-pyric-selected":s===x.id?"":void 0,style:{display:"contents"},children:q_(q)?h.jsxs(h.Fragment,{children:[h.jsx("span",{className:"fs-doc-phantom",children:q.id}),h.jsx("span",{className:"fs-sub fs-doc-phantom-hint",children:"missing"})]}):q.id})},renderRowAction:q=>{if(q_(q))return null;const x=q.ref;return h.jsx("button",{type:"button",className:"fs-doc-del",title:"Delete document","aria-label":`Delete ${x.id}`,onClick:E=>{E.stopPropagation(),H(x)},children:"×"})},emptyState:h.jsx("p",{className:"fs-empty",children:"No documents."})}),M?h.jsx("p",{className:"fs-empty fs-doc-del-err",children:M.message}):null]})}function Eq({api:t,firestore:e,handles:n,docPath:r,onOpenSubcollection:s,onReferenceClick:o,onStartCollection:c,onDeleted:d}){const f=A.useMemo(()=>t.doc(e,r),[t,e,r]),{data:p,error:g,isLoading:b}=n5(f),v=A.useCallback(async(F,D)=>(await n.listSubcollections(D.path)).map(L=>t.collection(D,L)),[n,t]),w=go(),_=A.useMemo(()=>tk(t,n),[t,n]),[k,I]=A.useState(null),N=A.useCallback(async()=>{I(null);try{await rk({confirm:w,ref:f,api:t,recursiveImpl:_})&&d()}catch(F){I(F instanceof Error?F:new Error(String(F)))}},[t,w,_,f,d]),R=A.useCallback(async()=>{await t.setDoc(f,{})},[t,f]),M=p!=null&&mq(p);return h.jsxs("section",{"data-pyric-ui":"fs-document",className:"fs-pane fs-col doc",children:[M?null:h.jsxs("div",{className:"fs-phead",children:[h.jsx("span",{className:"fs-phead-title",children:f.id}),h.jsx("span",{className:"fs-phead-actions",children:h.jsx("button",{type:"button",className:"fs-add",onClick:c,children:"+ Collection"})})]}),p&&M?h.jsx(dq,{snapshot:p,documentRef:f,firestore:e,listSubcollections:v,onReferenceClick:o,onSubcollectionClick:s,onStartCollection:c,onDeleteDocument:()=>void N(),onDeleteDocumentFields:R,onCommit:async F=>{await t.setDoc(f,F)}},r):g?h.jsx("p",{className:"fs-empty fs-doc-del-err",children:g.message}):b?h.jsx("p",{className:"fs-empty",children:"Loading document…"}):h.jsxs(h.Fragment,{children:[h.jsx("p",{className:"fs-empty",children:"This document does not exist."}),h.jsx(ek,{firestore:e,documentRef:f,listSubcollections:v,onSubcollectionClick:s})]}),k?h.jsx("p",{className:"fs-empty fs-doc-del-err",children:k.message}):null]})}const Aq="block w-full text-sm text-soft-white";function jq({auth:t,focusUid:e}){const{users:n,totalCount:r,isLoading:s,error:o,filter:c,setFilter:d,updateUser:f}=Rg(t),[p,g]=A.useState(null);A.useEffect(()=>{e&&(g(e),d(e))},[e,d]);const b=n.find(v=>v.uid===p)??null;return h.jsxs("div",{className:"grid grid-cols-[1fr_320px] gap-4",children:[h.jsxs("section",{className:"min-w-0",children:[h.jsx("input",{value:c,onChange:v=>d(v.target.value),placeholder:"Filter users…",className:"mb-3 w-full rounded border border-border bg-content-bg px-3 py-1.5 text-sm text-soft-white placeholder:text-slate-gray"}),h.jsx(xj,{users:n,isLoading:s,error:o,filter:c,onSelect:v=>g(v.uid),className:Aq,emptyState:h.jsx("p",{className:"py-6 text-sm text-slate-gray",children:"No users yet. Sign in from the app, or the agent seeds them, and they appear here."}),noResultsState:h.jsx("p",{className:"py-6 text-sm text-slate-gray",children:"No users match the filter."})}),h.jsxs("p",{className:"mt-2 text-xs text-slate-gray",children:[r," user(s) total"]})]}),h.jsx("section",{className:"min-w-0 border-l border-border pl-4",children:b?h.jsx(kq,{user:b,onSave:v=>f(b.uid,v)},b.uid):h.jsx("p",{className:"py-6 text-sm text-slate-gray",children:"Select a user to view and edit."})})]})}function kq({user:t,onSave:e}){const n=wj({initial:t}),[r,s]=A.useState(null),[o,c]=A.useState(!1),d=()=>{s(null),c(!1);try{e(n.toUpdateRequest()),c(!0)}catch(f){s(f instanceof Error?f:new Error(String(f)))}};return h.jsxs("div",{"data-pyric-ui":"auth-editor",children:[h.jsx("h3",{className:"mb-3 truncate font-mono text-xs text-slate-gray",title:t.uid,children:t.uid}),h.jsxs("label",{className:"mb-3 block text-xs text-slate-gray",children:["Display name",h.jsx("input",{value:n.fields.displayName,onChange:f=>n.setField("displayName",f.target.value),className:"mt-1 w-full rounded border border-border bg-content-bg px-2 py-1 text-sm text-soft-white"})]}),h.jsxs("label",{className:"mb-3 block text-xs text-slate-gray",children:["Custom claims (JSON)",h.jsx("textarea",{value:n.fields.claimsText,onChange:f=>n.setField("claimsText",f.target.value),rows:6,spellCheck:!1,className:"mt-1 w-full rounded border border-border bg-content-bg p-2 font-mono text-xs text-soft-white"}),n.errors.claims?h.jsx("span",{className:"text-danger",children:n.errors.claims}):null]}),h.jsxs("label",{className:"mb-3 flex items-center gap-2 text-xs text-slate-gray",children:[h.jsx("input",{type:"checkbox",checked:n.fields.disabled,onChange:f=>n.setField("disabled",f.target.checked)}),"Disabled"]}),r?h.jsx("p",{className:"mb-2 text-xs text-danger",children:r.message}):null,o?h.jsx("p",{className:"mb-2 text-xs text-primary",children:"Saved."}):null,h.jsxs("div",{className:"flex gap-2",children:[h.jsx("button",{type:"button",onClick:d,disabled:!n.isValid||!n.isDirty,className:"rounded bg-primary/15 px-3 py-1 text-xs font-medium text-primary hover:bg-primary/25 disabled:opacity-40",children:"Save"}),h.jsx("button",{type:"button",onClick:n.reset,disabled:!n.isDirty,className:"rounded border border-border px-3 py-1 text-xs text-slate-gray hover:text-soft-white disabled:opacity-40",children:"Reset"})]})]})}function F_(t){const e=yt(t),n=e.lastIndexOf("/");return n===-1?"":e.slice(0,n)}function z_(t,e){return t===""?e:e===""?t:`${t}/${e}`}function P_(t){const e=t.lastIndexOf("/");return e===-1?t:t.slice(e+1)}const Cq=[{key:"size",label:"size",value:t=>`${t.size} bytes`},{key:"contentType",label:"content type",value:t=>t.contentType},{key:"timeCreated",label:"created",value:t=>t.timeCreated},{key:"updated",label:"updated",value:t=>t.updated},{key:"md5Hash",label:"md5",value:t=>t.md5Hash},{key:"cacheControl",label:"cache control",value:t=>t.cacheControl},{key:"fullPath",label:"path",value:t=>`gs://${t.bucket}/${t.fullPath}`}];function Nq(t){const e=Object.entries(t.customMetadata??{});return h.jsxs("dl",{"data-pyric-object-metadata":!0,children:[h.jsx("div",{"data-storage-meta-group":!0,children:"Metadata"}),Cq.map(({key:n,label:r,value:s})=>{const o=s(t);return o===void 0?null:h.jsxs("div",{"data-pyric-metadata-field":n,children:[h.jsx("dt",{children:r}),h.jsx("dd",{children:o})]},n)}),e.length>0?h.jsx("div",{"data-storage-meta-group":!0,children:"Custom metadata"}):null,e.map(([n,r])=>h.jsxs("div",{"data-pyric-metadata-field":"customMetadata","data-pyric-metadata-key":n,children:[h.jsx("dt",{children:n}),h.jsx("dd",{children:r})]},`custom:${n}`))]})}function Oq(){return h.jsx("svg",{"aria-hidden":!0,viewBox:"0 0 16 16",width:"13",height:"13",fill:"none",stroke:"currentColor",strokeWidth:"1.25",strokeLinejoin:"round",children:h.jsx("path",{d:"M1.75 4.25c0-.55.45-1 1-1h3.4l1.5 1.7h5.6c.55 0 1 .45 1 1v6.05c0 .55-.45 1-1 1H2.75c-.55 0-1-.45-1-1z"})})}function Rq(){return h.jsxs("svg",{"aria-hidden":!0,viewBox:"0 0 16 16",width:"13",height:"13",fill:"none",stroke:"currentColor",strokeWidth:"1.25",strokeLinejoin:"round",children:[h.jsx("path",{d:"M4.25 1.75h5l3 3v9.5h-8z"}),h.jsx("path",{d:"M9.25 1.75v3h3"})]})}function Tq(t){const e=t.kind==="folder";return h.jsxs(h.Fragment,{children:[h.jsxs("span",{className:"storage__cell-name",children:[h.jsx("span",{className:"storage__ic","aria-hidden":!0,children:e?h.jsx(Oq,{}):h.jsx(Rq,{})}),h.jsx("span",{className:"storage__nm",children:t.name}),e?h.jsx("span",{"aria-hidden":!0,className:"storage__chev",children:"›"}):null]}),h.jsx("span",{className:"storage__cell-type",children:e?"folder":"file"}),h.jsx("span",{className:"storage__cell-size"}),h.jsx("span",{className:"storage__cell-updated"})]})}function Dq({storage:t,focusTarget:e}){var q;const n=nf(),r=e.kind==="object"?yt(e.path):null,s=e.kind==="prefix"?yt(e.path):r?F_(r):"",o=A.useCallback(x=>{const E=yt(x);n.navigate(E?{view:"storage",kind:"prefix",path:E}:{view:"storage",kind:"root"})},[n.navigate]),c=p8({path:s,onPathChange:o}),d=x=>{n.navigate({view:"storage",kind:"object",path:yt(x)})},f=h8(t,c.path),p=y8(),g=S8(t),[b,v]=A.useReducer(D8,Vj),w=A8(t,{path:c.path,list:f,onComplete:x=>v({type:"materialize",path:F_(x.fullPath)})});A.useEffect(()=>{if(f.status==="success")for(const x of f.entries)x.kind==="folder"&&U_(b,x.fullPath)&&v({type:"materialize",path:x.fullPath})},[f.status,f.entries,b]);const[_,k]=A.useState(!1),[I,N]=A.useState(""),[R,M]=A.useState(null),F=A.useRef(null),D=A.useMemo(()=>{const x=I8(b,c.path).filter(T=>!f.entries.some(P=>P.kind==="folder"&&P.name===T));if(x.length===0)return f.entries;const E=x.map(T=>{const P=z_(c.path,T);return{kind:"folder",name:T,fullPath:P,ref:{fullPath:P,name:T}}});return[...[...f.entries.filter(T=>T.kind==="folder"),...E].sort((T,P)=>T.name<P.name?-1:T.name>P.name?1:0),...f.entries.filter(T=>T.kind==="object")]},[f.entries,b,c.path]),C=D.length>0&&D.every(x=>p.isSelected(x.fullPath)),L=x=>{const E=new Set(D.map(T=>T.name)),O=T8(x.map(T=>T.relativePath),E);w.upload(x.map((T,P)=>({path:O[P],data:T.file})))},U=x=>{x.preventDefault();const E=M8(I);if(E){M(E);return}const O=z_(c.path,yt(I));v({type:"create",path:O}),c.setPath(O),N(""),M(null),k(!1)};A.useEffect(()=>p.clear(),[c.path,p.clear]);const H=w.tasks.filter(x=>x.status==="error"),z=g.verdictFor(c.path);return h.jsx(G8,{children:h.jsx(Tg,{children:h.jsxs("div",{className:"storage",children:[h.jsxs("div",{className:"storage__sub",children:[h.jsx(j8,{path:c.path,rootLabel:"files",onNavigate:c.setPath}),h.jsx("div",{className:"storage__actions",children:p.size>0?h.jsxs(h.Fragment,{children:[h.jsxs("span",{className:"studio-selection-count",children:[p.size," selected"]}),h.jsx(Y8,{storage:t,entries:p.selected,list:f,gate:g,className:"studio-selection-delete",onDeleted:x=>{for(const E of p.selected)E.kind==="folder"&&x.deleted.includes(E.fullPath)&&v({type:"discard",path:E.fullPath});r&&p.selected.some(E=>E.kind==="object"?E.fullPath===r:r.startsWith(`${E.fullPath}/`))&&c.setPath(c.path),p.clear(),f.refresh()},onFailed:x=>{const E=new Set(x.failed.map(O=>O.fullPath));p.selectAll(p.selected.filter(O=>E.has(O.fullPath))),f.refresh()}}),h.jsx("button",{type:"button",className:"storage__action",onClick:p.clear,children:"Clear selection"})]}):h.jsxs(h.Fragment,{children:[h.jsx("button",{type:"button",className:"storage__action","aria-expanded":_,onClick:()=>{k(x=>!x),M(null)},children:"New folder"}),h.jsx("button",{type:"button",className:"storage__action storage__action--upload",onClick:()=>{var x;return(x=F.current)==null?void 0:x.click()},children:"Upload files"}),h.jsx("input",{ref:F,type:"file",multiple:!0,hidden:!0,onChange:x=>{const E=Array.from(x.currentTarget.files??[]);E.length>0&&L(E.map(O=>({file:O,relativePath:O.name}))),x.currentTarget.value=""}})]})})]}),_?h.jsxs("form",{className:"storage__newfolder",onSubmit:U,children:[h.jsx("input",{autoFocus:!0,className:"storage__newfolder-input",placeholder:"folder or nested/path/of/folders","aria-label":"New folder name",value:I,onChange:x=>{N(x.currentTarget.value),M(null)},onKeyDown:x=>{x.key==="Escape"&&k(!1)}}),h.jsx("button",{type:"submit",className:"storage__newfolder-btn",children:"Create"}),R?h.jsx("span",{className:"storage__newfolder-err",role:"alert",children:R}):h.jsx("span",{className:"storage__newfolder-note",children:"Nested paths create the whole chain. Empty folders last this session only — upload a file to keep one."})]}):null,H.length>0?h.jsxs("p",{className:"storage__upload-err",role:"alert",children:[H.length===1?`Upload failed: ${P_(H[0].fullPath)} — ${((q=H[0].error)==null?void 0:q.message)??"error"}`:`${H.length} uploads failed: ${H.map(x=>P_(x.fullPath)).join(", ")}`,h.jsx("button",{type:"button",className:"storage__upload-err-dismiss",onClick:w.clearCompleted,children:"Dismiss"})]}):null,h.jsxs("div",{className:"storage__body","data-storage-level":r?"inspector":"browser",children:[h.jsxs(N8,{className:"storage__browser",onFiles:L,disabled:!z.upload,disabledReason:z.reasons.write.join("; "),children:[h.jsxs("div",{className:"storage__lhead",children:[h.jsx("label",{className:"storage__select-all",title:"Select all in this folder",children:h.jsx("input",{type:"checkbox","aria-label":"Select all in this folder",checked:C,onChange:x=>x.currentTarget.checked?p.selectAll(D):p.clear()})}),h.jsx("span",{children:"name"}),h.jsx("span",{children:"type"}),h.jsx("span",{children:"size"}),h.jsx("span",{children:"updated"})]}),h.jsx(k8,{entries:D,status:f.status,error:f.error,gate:g,selectedPath:r??void 0,renderEntry:Tq,renderRowAction:x=>h.jsx("label",{className:"storage__select-row",title:`Select ${x.name}`,children:h.jsx("input",{type:"checkbox","aria-label":`Select ${x.name}`,checked:p.isSelected(x.fullPath),onChange:()=>p.toggle(x)})}),onNavigate:c.enter,onSelect:x=>d(x.fullPath),emptyState:h.jsx("p",{className:"storage__empty",children:U_(b,c.path)?"Empty folder — session-only until a file is uploaded here. Drop files anywhere in this pane, or use Upload files.":"No files yet. Drop files here or use Upload files; files your app uploads to Storage also appear here."})}),h.jsxs("div",{className:"storage__dropcue","aria-hidden":!0,children:["Drop to upload to /",c.path||""]})]}),h.jsx("div",{className:"storage__inspector",children:r?h.jsxs(h.Fragment,{children:[h.jsx("button",{type:"button",className:"storage__back",onClick:()=>c.setPath(c.path),"aria-label":"Back to files",children:"‹ Files"}),h.jsx(V8,{storage:t,path:r,renderMetadata:Nq})]}):h.jsx("p",{className:"storage__inspector-hint",children:"Select an object to inspect its preview and metadata."})})]})]})})})}function Iq({view:t}){const e=t==="firestore"?"Firestore":t==="auth"?"Auth":"Storage";return h.jsxs("div",{"data-pyric-ui":"data-pending",className:"flex flex-col items-center justify-center gap-2 py-16 text-center",children:[h.jsx("span",{className:"rounded-full border border-border px-3 py-1 text-xs uppercase tracking-wide text-slate-gray",children:"Local backend pending"}),h.jsxs("p",{className:"max-w-md text-sm leading-relaxed text-slate-gray",children:["The ",e," viewer mounts here. It goes live once the local sandbox backend is reachable (the served `pyric dev --ui` workspace)."]})]})}function sk({view:t}){const{target:e}=nf(),n=ri(),r=n.status==="ready"?n.handles.auth:null;return h.jsx("div",{"data-pyric-ui":"data-feature",children:n.status!=="ready"||!r?h.jsx(Iq,{view:t}):n.authApi?h.jsx(yj,{value:n.authApi,children:h.jsx(V_,{view:t,handles:n.handles,auth:r,target:e,firestoreApi:n.firestoreApi,storageApi:n.storageApi})}):h.jsx(V_,{view:t,handles:n.handles,auth:r,target:e,firestoreApi:n.firestoreApi,storageApi:n.storageApi})})}function V_({view:t,handles:e,auth:n,target:r,firestoreApi:s,storageApi:o}){const{users:c}=Rg(n),d=A.useMemo(()=>new Set(c.map(f=>f.uid)),[c]);switch(t){case"firestore":{const f=h.jsx(vq,{handles:e,knownUids:d});return s?h.jsx(t5,{value:s,children:f}):f}case"auth":return h.jsx(jq,{auth:n,focusUid:(r==null?void 0:r.view)==="auth"?r.uid:null});case"storage":{const f=h.jsx(Dq,{storage:e.storage,focusTarget:(r==null?void 0:r.view)==="storage"?r:{kind:"root"}});return o?h.jsx(f8,{value:o,children:f}):f}}}function Mq(){return h.jsx(sk,{view:"firestore"})}function Lq(){return h.jsx(sk,{view:"storage"})}function Uq(t,e){const n=new Set(e.map(r=>r.uid));return new Set([...t].filter(r=>n.has(r)))}async function $q(t,e){const n=[];for(const r of t)try{await e(r.uid)}catch{n.push(r.uid)}return n}function Bq(t){const[e,n]=A.useState(()=>new Set);A.useEffect(()=>{n(s=>{const o=Uq(s,t);return o.size===s.size&&[...o].every(c=>s.has(c))?s:o})},[t]);const r=A.useMemo(()=>t.filter(s=>e.has(s.uid)),[e,t]);return{selectedUsers:r,allVisibleSelected:t.length>0&&r.length===t.length,isSelected:s=>e.has(s),toggle(s){n(o=>{const c=new Set(o);return c.has(s)?c.delete(s):c.add(s),c})},selectAll(s){n(s?new Set(t.map(o=>o.uid)):new Set)},replace(s){n(new Set(s))},clear(){n(new Set)}}}function qq({users:t,filter:e,onDelete:n,onComplete:r}){const s=go(),[o,c]=A.useState(!1),[d,f]=A.useState(null),p=async()=>{const g=e.trim().length>0;if(!await s({title:`Delete ${t.length} ${t.length===1?"user":"users"}?`,body:g?`Only the ${t.length} users shown by the current filter will be deleted.`:`This will permanently delete the ${t.length} selected users.`,destructive:!0,confirmLabel:"Delete users"}))return;c(!0),f(null);const v=await $q(t,n);c(!1),f(v.length>0?`Could not delete ${v.length} selected user(s).`:null),r(v)};return h.jsxs(h.Fragment,{children:[h.jsx("button",{type:"button",className:"studio-selection-delete",disabled:o,onClick:()=>void p(),children:o?"Deleting…":"Delete"}),d?h.jsx("span",{className:"auth-sub__error",children:d}):null]})}function ik(t){if(!t)return"never";const e=new Date(t).getTime();if(Number.isNaN(e))return"never";const n=Math.max(0,Math.round((Date.now()-e)/1e3));if(n<45)return"just now";const r=Math.round(n/60);if(r<60)return`${r}m ago`;const s=Math.round(r/60);return s<24?`${s}h ago`:`${Math.round(s/24)}d ago`}function ak(t){if(!t)return"unknown";const e=new Date(t);return Number.isNaN(e.getTime())?"unknown":e.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}function Fq(t){const e=t.isAnonymous&&!t.email,n=t.email??t.phoneNumber??(e?"anonymous":t.uid);return h.jsxs("span",{className:e?"auth-ident auth-ident--anon":"auth-ident",children:[h.jsx("span",{className:"auth-ident__primary",title:n,children:n}),h.jsx("span",{className:"auth-ident__uid",title:t.uid,children:t.uid})]})}function zq({auth:t}={}){const e=cs(),n=ri(),r=t??(n.status==="ready"?n.handles.auth:null),s=n.status==="ready"?n.authApi:void 0;if(!r)return h.jsx("div",{className:"auth-surface","data-pyric-ui":"auth-surface",children:h.jsx(Kq,{status:e.status})});const o=h.jsx(Tg,{children:h.jsx(Pq,{auth:r})});return s?h.jsx(yj,{value:s,children:o}):o}function Pq({auth:t}){var N;const{users:e,totalCount:n,isLoading:r,error:s,filter:o,setFilter:c,createUser:d,updateUser:f,deleteUser:p}=Rg(t),g=nf(),b=((N=g.target)==null?void 0:N.view)==="auth"?g.target.uid:null,v=R=>g.navigate({view:"auth",uid:R}),w=A.useMemo(()=>e.find(R=>R.uid===b)??null,[e,b]),[_,k]=A.useState(!1),I=Bq(e);return h.jsxs("div",{className:"auth-surface","data-pyric-ui":"auth-surface",children:[h.jsxs("div",{className:"auth-sub",children:[h.jsxs("span",{className:"auth-sub__h",children:["users ",h.jsxs("span",{className:"auth-sub__n",children:["· ",n]})]}),h.jsx("input",{className:"auth-sub__filter",value:o,onChange:R=>c(R.target.value),placeholder:"filter users…","aria-label":"Filter users"}),h.jsx("div",{className:"auth-sub__right",children:I.selectedUsers.length>0?h.jsxs(h.Fragment,{children:[h.jsxs("span",{className:"studio-selection-count",children:[I.selectedUsers.length," selected"]}),h.jsx(qq,{users:I.selectedUsers,filter:o,onDelete:R=>Promise.resolve(p(R)),onComplete:R=>{I.replace(R),b&&!R.includes(b)&&v(null)}}),h.jsx("button",{type:"button",className:"auth-sub__clear",onClick:I.clear,children:"Clear selection"})]}):h.jsx("button",{type:"button",className:"auth-sub__add",onClick:()=>{k(!0),v(null)},children:"Add user"})})]}),h.jsxs("div",{className:"auth-body","data-auth-level":w||_?"detail":"list",children:[h.jsx("div",{className:"auth-list",children:h.jsx(xj,{users:e,isLoading:r,error:s,filter:o,onSelect:R=>{k(!1),v(R.uid)},renderIdentifier:Fq,formatCreatedAt:ak,formatLastLoginAt:ik,renderSelectionHeader:h.jsx("label",{className:"auth-select",title:"Select all shown users",children:h.jsx("input",{type:"checkbox","aria-label":"Select all shown users",checked:I.allVisibleSelected,onChange:R=>I.selectAll(R.currentTarget.checked)})}),renderSelection:R=>h.jsx("label",{className:"auth-select",title:`Select ${R.uid}`,children:h.jsx("input",{type:"checkbox","aria-label":`Select ${R.uid}`,checked:I.isSelected(R.uid),onChange:()=>I.toggle(R.uid)})}),emptyState:h.jsx("p",{className:"auth-zero",children:"No users yet. Sign-ins from the app, agent-seeded users, and “Add user” all land here."}),noResultsState:h.jsxs("p",{className:"auth-zero",children:["No users match “",o,"”."]})})}),h.jsx("div",{className:"auth-detail",children:_?h.jsx(Vq,{onCancel:()=>k(!1),onCreate:async R=>{const M=await Promise.resolve(d(R));k(!1),v(M.uid)}}):w?h.jsxs(h.Fragment,{children:[h.jsx("button",{type:"button",className:"auth-back",onClick:()=>v(null),"aria-label":"Back to users",children:"‹ Users"}),h.jsx(Gq,{user:w,onSave:R=>{R.mode==="edit"&&f(R.uid,R.request)},onProvidersChange:async R=>{await Promise.resolve(f(w.uid,{providerUserInfo:R}))},onDelete:()=>{p(w.uid),v(null)}},w.uid)]}):h.jsx("div",{className:"auth-detail__empty",children:h.jsx("p",{className:"auth-zero",children:"Select a user to view and edit."})})})]})]})}function Vq({onCreate:t,onCancel:e}){const[n,r]=A.useState(null),s=o=>{o.mode==="create"&&(r(null),t(o.request).catch(c=>{r(c instanceof Error?c:new Error(String(c)))}))};return h.jsxs("div",{className:"auth-editor","data-pyric-ui":"auth-create-user",children:[h.jsxs("div",{className:"auth-editor__head",children:[h.jsx("div",{className:"auth-editor__who",children:"New user"}),h.jsx("div",{className:"auth-editor__meta",children:"Created without signing in — admin semantics, like the emulator’s add-user flow."})]}),h.jsx(Sj,{onSubmit:s,onCancel:e,submitLabel:"Create user",children:n?h.jsx("p",{className:"auth-save auth-save--error",role:"alert",children:n.message}):null})]})}const H_=[...YA];function Hq({user:t,onChange:e}){const[n,r]=A.useState(null),[s,o]=A.useState(""),c=t.providerUserInfo.map(w=>w.providerId),d=c.includes("password"),f=c.filter(w=>w!=="password"),p=f.filter(w=>!H_.includes(w)),g=w=>{r(null),e(w.map(_=>({providerId:_}))).catch(_=>{r(_ instanceof Error?_:new Error(String(_)))})},b=(w,_)=>{g(_?[...f,w]:f.filter(k=>k!==w))},v=()=>{const w=s.trim();w&&(o(""),!f.includes(w)&&g([...f,w]))};return h.jsxs("section",{className:"auth-providers-editor","aria-label":"Sign-in providers",children:[h.jsx("div",{className:"auth-group",children:"Sign-in providers"}),h.jsx("div",{className:"auth-providers-editor__list",children:[...H_,...p].map(w=>h.jsxs("label",{className:"auth-provider-row","data-pyric-provider-id":w,children:[h.jsx("input",{type:"checkbox",checked:f.includes(w),onChange:_=>b(w,_.target.checked)}),h.jsx("span",{className:"auth-provider-row__label",children:Ad(w)}),h.jsx("span",{className:"auth-provider-row__id",children:w})]},w))}),d||t.isAnonymous?h.jsx("p",{className:"auth-providers-editor__derived",children:d?"Password is linked by the password credential above.":"Anonymous — the provider lives on the token, not the record."}):null,h.jsx("div",{className:"auth-provider-custom",children:h.jsxs("label",{className:"auth-provider-custom__field",children:[h.jsx("span",{className:"auth-provider-custom__label",children:"Custom provider ID"}),h.jsxs("span",{className:"auth-provider-custom__row",children:[h.jsx("input",{type:"text",value:s,placeholder:"oidc.my-provider",onChange:w=>o(w.target.value),onKeyDown:w=>{w.key==="Enter"&&(w.preventDefault(),v())}}),h.jsx("button",{type:"button",onClick:v,disabled:!s.trim(),children:"Link"})]})]})}),n?h.jsx("p",{className:"auth-save auth-save--error",role:"alert",children:n.message}):null]})}function Gq({user:t,onSave:e,onProvidersChange:n,onDelete:r}){const[s,o]=A.useState(null),[c,d]=A.useState(!1),f=b=>{o(null),d(!1);try{e(b),d(!0)}catch(v){o(v instanceof Error?v:new Error(String(v)))}},p=ak(t.createdAt),g=ik(t.lastLoginAt);return h.jsxs("div",{className:"auth-editor","data-pyric-user-disabled":t.disabled?"":void 0,children:[h.jsxs("div",{className:"auth-editor__head",children:[h.jsxs("div",{className:"auth-editor__who",children:[t.email??(t.isAnonymous?"anonymous":t.uid),t.disabled?h.jsx("span",{className:"auth-tag-off",children:"disabled"}):null]}),h.jsxs("div",{className:"auth-editor__uid",children:["uid · ",t.uid]}),h.jsxs("div",{className:"auth-editor__meta",children:["created ",p," · signed in ",g]})]}),h.jsx(Hq,{user:t,onChange:n}),h.jsxs(Sj,{initial:t,onSubmit:f,submitLabel:"Save",children:[s?h.jsx("p",{className:"auth-save auth-save--error",role:"alert",children:s.message}):null,c?h.jsx("p",{className:"auth-save auth-save--ok",children:"Saved."}):null]},t.uid),h.jsx("div",{className:"auth-editor__foot",children:h.jsx(JB,{user:t,onDelete:r,className:"auth-del"})})]})}function Kq({status:t}){const e=t==="pending"?"Seeding the sandbox…":t==="error"?"The dev-seed failed. Check the console.":"No sandbox Auth handle. Run with the dev-seed (DEV) or a live env.";return h.jsx("div",{className:"auth-detail__empty","data-pyric-ui":"auth-surface-empty",children:h.jsx("p",{className:"auth-zero",children:e})})}function Yq(t){return t.operationContext.source.kind==="studio"}function Zq(t,e){return e?t.filter(n=>!Yq(n)):[...t]}const Wq=["all","allow","deny","bypassed"];function rf(t){return t.rulesDisposition.kind==="bypassed"?"bypassed":t.rulesDisposition.kind==="evaluated"?t.rulesDisposition.verdict:null}function Qq(t,e){return e==="all"?[...t]:t.filter(n=>rf(n)===e)}function um(t){return t.rulesDisposition.kind==="evaluated"}function G_(t){const e=t.path;if(t.service==="storage"&&t.method==="list"&&(e===""||e==="/"))return{tab:"storage"};if(!e||e==="(service)")return null;const n=e.split("/").filter(Boolean);switch(t.service??"firestore"){case"firestore":return n.length?{tab:"firestore",rest:n}:null;case"rtdb":return{tab:"rtdb"};case"storage":return n.length?{tab:"storage",rest:n,...t.method==="list"?{query:{kind:"prefix"}}:{}}:null;case"auth":return e!=="*"?{tab:"auth",rest:[e]}:null;default:return null}}const Iy="inspect";function ok(t){const e=t[Iy];return e||null}function lk(t,e){const{[Iy]:n,...r}=t;return e?{...r,[Iy]:e}:r}function Jq(t,e){return lk(t,ok(t)===e?null:e)}function Xq(t){const e=Yu(t),n=e.warnings.map(r=>({rule:r.rule,severity:r.severity,message:r.message,...r.fix?{fix:r.fix}:{}}));return e.parseError?{parseable:!1,parseError:e.parseError.message,findings:n}:{parseable:!0,findings:n}}async function eF(t,e,n,r){const s=Xq(n);if(!s.parseable)return{result:{outcome:"error",code:"lint-parse-error",message:s.parseError??"The edited ruleset did not parse."},diff:[],lint:s};const o=zE(t,n);try{const c=await ck(o.sandbox,e),d=c.outcome==="allow"?RI(o,r):[];return{result:c,diff:d,lint:s}}finally{PE(o)}}async function ck(t,e){var s;const n=Vd(t.withAuth(e.auth)),r=tF(e.resourceData);try{switch(e.method){case"get":await vg(ur(n,e.path));break;case"list":case"listen":await zl(Vl(Ui(n,e.path)));break;case"create":case"set":await Pl(ur(n,e.path),r);break;case"update":await ay(ur(n,e.path),r);break;case"delete":await bd(ur(n,e.path));break;default:await wg(Ui(n,nF(e.path)),r)}return{outcome:"allow"}}catch(o){if(o instanceof nt&&o.code==="permission-denied"){const d=(s=o.denialContext)==null?void 0:s.reasons;return{outcome:"deny",code:o.code,message:o.message,...d?{reasons:d}:{}}}return{outcome:"error",code:o instanceof nt?o.code:"unknown",message:o instanceof Error?o.message:String(o)}}}function tF(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:{}}function nF(t){const e=t.lastIndexOf("/");return e<0?t:t.slice(0,e)}const rF=A.lazy(()=>p1(()=>import("./RulesCodeEditor-BDlH-5lp.js"),[]));function uk(t){return h.jsx(A.Suspense,{fallback:h.jsx(sF,{value:t.value,minHeightRem:t.minHeightRem}),children:h.jsx(rF,{...t})})}function sF({value:t,minHeightRem:e=14}){return h.jsx("pre",{"data-pyric-ui":"rules-code-editor-loading",className:"overflow-auto rounded-md border border-border bg-content-bg p-3 font-mono text-xs text-slate-gray",style:{minHeight:`${e}rem`},children:t||"Loading editor…"})}function dk({denial:t,editedRules:e,rulesSource:n,onEditedRulesChange:r,onRerunAsUser:s,onRerunAgainstRules:o}){const c=r4(t);return h.jsxs("div",{"data-pyric-ui":"denial-detail",className:"flex min-h-0 flex-col gap-4 overflow-auto rounded-lg border border-border bg-sidebar-bg p-5",children:[h.jsxs("section",{children:[h.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[t.result==="allow"?h.jsx(Ja,{kind:"allow",className:"rounded bg-primary/15 px-2 py-0.5 text-xs font-semibold uppercase text-primary",children:"allowed"}):h.jsx(Ja,{kind:"deny",className:"rounded bg-danger/15 px-2 py-0.5 text-xs font-semibold uppercase text-danger",children:t.unsupported?"unsupported":"denied"}),h.jsxs("span",{className:"font-mono text-sm text-soft-white",children:[t.service!=="firestore"?`${t.service} · `:"",t.method," ",t.path]})]}),h.jsx("p",{className:"text-sm leading-relaxed text-soft-white",children:c.headline})]}),c.noEvaluation?h.jsx("p",{"data-pyric-ui":"rules-debug-no-evaluation",className:"rounded-md border border-border bg-content-bg px-3 py-2 text-xs text-slate-gray",children:"No matched rule, evaluation trace, or re-run is shown because this event carries no rules verdict to ground them in."}):h.jsxs(h.Fragment,{children:[h.jsx(iF,{denial:t,exp:c,rulesSource:n}),h.jsx(oF,{denial:t})]}),h.jsx(cF,{denial:t}),c.noEvaluation?null:h.jsx(hF,{denial:t,editedRules:e,onEditedRulesChange:r,onRerunAsUser:s,onRerunAgainstRules:o})]})}function iF({denial:t,exp:e,rulesSource:n}){return e.engine==="rtdb"?h.jsx(dF,{denial:t,exp:e}):e.engine==="storage"?h.jsx(fF,{exp:e}):h.jsx(aF,{denial:t,exp:e,rulesSource:n})}function aF({denial:t,exp:e,rulesSource:n}){var c;const r=(c=t.evaluatedRule)==null?void 0:c.line,s=t.result==="allow",o=!!n&&n.trim().length>0;return h.jsx(Hs,{label:e.implicitDeny||!e.ruleNode?"matched rule":`matched rule — ${e.ruleNode}${r?` · line ${r}`:""}`,children:o?h.jsx(uk,{value:n,readOnly:!0,markLine:r,markKind:s?"allow":"deny",minHeightRem:12,ariaLabel:`Deployed firestore.rules — the ${s?"allowing":"denying"} rule is marked`}):h.jsx("pre",{className:"overflow-auto rounded-md border border-border bg-content-bg p-3 font-mono text-xs leading-relaxed text-slate-gray",children:[...e.ruleLines,...e.otherLines].join(`
1217
- `)||"(no trace)"})})}function oF({denial:t}){const e=c4(t);return e.length===0?null:h.jsx(Hs,{label:"show the work — how the condition evaluated",children:h.jsx("div",{"data-pyric-ui":"rules-debug-trace",className:"flex flex-col gap-0.5 overflow-auto rounded-md border border-border bg-content-bg p-3",children:e.map((n,r)=>h.jsx(fk,{step:n},r))})})}const lF={true:"✓",false:"✗",skipped:"⊘",error:"!",value:"·"};function fk({step:t}){const e=t.outcome==="true"?"text-diff-add":t.outcome==="false"||t.outcome==="error"?"text-danger":"text-slate-gray",n=t.outcome==="skipped"?"not evaluated (short-circuit)":t.outcome==="error"?t.error:`→ ${hk(t.value)}`;return h.jsxs(h.Fragment,{children:[h.jsxs("div",{className:"flex items-baseline gap-2 font-mono text-xs",style:{paddingLeft:`${t.depth*.9}rem`},children:[h.jsx("span",{"aria-hidden":!0,className:`w-3 shrink-0 text-center font-bold ${e}`,children:lF[t.outcome]}),h.jsxs("span",{className:t.outcome==="skipped"?"text-slate-gray line-through":"text-soft-white",children:[t.letBinding?`let ${t.letBinding} = `:"",t.source]}),h.jsx("span",{className:"text-slate-gray",children:n}),t.inlinedFrom?h.jsxs("span",{className:"text-[0.6rem] uppercase tracking-wide text-slate-gray",children:[t.inlinedFrom,"()"]}):null]}),t.children.map((r,s)=>h.jsx(fk,{step:r},s))]})}function hk(t){if(t===void 0)return"undefined";try{return JSON.stringify(oo(t))}catch{return String(t)}}function cF({denial:t}){const e=u4(t);return h.jsx(Hs,{label:"what the rule saw (request / resource)",children:h.jsx("div",{"data-pyric-ui":"rules-debug-variables",className:"flex flex-col gap-2 rounded-md border border-border bg-content-bg p-3",children:e.map(n=>h.jsx(uF,{variable:n},n.name))})})}function uF({variable:t}){return h.jsxs("div",{className:"flex flex-col gap-0.5",children:[h.jsx("span",{className:"font-mono text-[0.7rem] text-primary",children:t.name}),t.present?h.jsx(pk,{value:t.value}):h.jsxs("span",{className:"font-mono text-xs italic text-slate-gray",children:["absent",t.absentNote?` — ${t.absentNote}`:""]})]})}function pk({value:t,depth:e=0}){const[n,r]=A.useState(e<2),s=oo(t);if(s===null||typeof s!="object")return h.jsx("span",{className:"font-mono text-xs text-soft-white",children:hk(s)});const o=Array.isArray(s)?s.map((c,d)=>[String(d),c]):Object.entries(s);return o.length===0?h.jsx("span",{className:"font-mono text-xs text-slate-gray",children:Array.isArray(s)?"[]":"{}"}):h.jsxs("div",{className:"flex flex-col",children:[h.jsxs("button",{type:"button",onClick:()=>r(c=>!c),"aria-expanded":n,className:"flex w-fit items-center gap-1 font-mono text-xs text-slate-gray hover:text-soft-white",children:[h.jsx("span",{"aria-hidden":!0,children:n?"▾":"▸"}),h.jsx("span",{children:Array.isArray(s)?`[${o.length}]`:`{${o.length}}`})]}),n?h.jsx("div",{className:"flex flex-col gap-0.5 border-l border-border pl-3",children:o.map(([c,d])=>h.jsxs("div",{className:"flex flex-wrap items-baseline gap-2",children:[h.jsxs("span",{className:"font-mono text-xs text-slate-gray",children:[c,":"]}),h.jsx(pk,{value:d,depth:e+1})]},c))}):null]})}function dF({denial:t,exp:e}){var n,r;return h.jsxs(h.Fragment,{children:[h.jsx(Hs,{label:e.implicitDeny?"rule node":`rule node — ${e.ruleNode}`,children:h.jsxs("code",{className:"font-mono text-xs text-soft-white",children:[e.phase?`.${e.phase}`:"(no matching rule)",(n=t.rules)!=null&&n.matchedPath?` at ${t.rules.matchedPath}`:""]})}),e.ruleExpression?h.jsx(Hs,{label:"rule expression",children:h.jsx("pre",{className:"overflow-auto rounded-md border border-border bg-content-bg p-3 font-mono text-xs text-slate-gray",children:e.ruleExpression})}):null,e.bindings?h.jsx(Hs,{label:"$variable bindings",children:h.jsx("code",{className:"font-mono text-xs text-soft-white",children:Object.entries(e.bindings).map(([s,o])=>`${s.startsWith("$")?s:`$${s}`} → ${o}`).join(", ")})}):null,(r=t.rules)!=null&&r.reason?h.jsx(Hs,{label:"simulator reason",children:h.jsx("code",{className:"font-mono text-xs text-slate-gray",children:t.rules.reason})}):null]})}function fF({exp:t}){return h.jsxs(Hs,{label:t.implicitDeny?"matched rule":"matched rule (match block)",children:[t.ruleNode?h.jsx("code",{className:"mb-2 block font-mono text-xs text-soft-white",children:t.ruleNode}):null,h.jsx("pre",{className:"overflow-auto rounded-md border border-border bg-content-bg p-3 font-mono text-xs leading-relaxed text-slate-gray",children:[...t.ruleLines,...t.otherLines].join(`
1218
- `)||"(no trace)"})]})}function Hs({label:t,children:e}){return h.jsxs("div",{className:"flex flex-col gap-1",children:[h.jsx("span",{className:"text-[0.65rem] font-semibold uppercase tracking-wider text-slate-gray",children:t}),e]})}function hF({denial:t,editedRules:e,onEditedRulesChange:n,onRerunAsUser:r,onRerunAgainstRules:s}){var _,k,I;const[o,c]=A.useState(null),[d,f]=A.useState(null),p=Z6(t),g=p.impersonate.kind==="live"&&!!r&&!!((_=t.auth)!=null&&_.uid),b=p.editedRuleset.kind==="live"&&!!s;async function v(){if(r){c("pending");try{c(await r(t))}catch(N){c({outcome:"error",code:"unknown",message:String(N)})}}}async function w(){if(s){f("pending");try{f(await s(t,e??""))}catch(N){f({result:{outcome:"error",code:"unknown",message:String(N)},diff:[],lint:{parseable:!0,findings:[]}})}}}return h.jsxs("section",{"data-pyric-ui":"rerun-panel",className:"mt-1 flex flex-col gap-4 border-t border-border pt-4",children:[o4(t)?h.jsxs("div",{className:"flex flex-col gap-2",children:[h.jsxs("div",{className:"flex items-center justify-between gap-3",children:[h.jsx("span",{className:"text-sm font-medium text-soft-white",children:"Re-run as the attempting user"}),h.jsx("button",{type:"button",disabled:!g||o==="pending",onClick:v,className:"rounded-md border border-primary/40 px-3 py-1 text-xs font-medium text-primary transition-colors hover:bg-primary/10 disabled:cursor-not-allowed disabled:border-border disabled:text-slate-gray",children:o==="pending"?"Running…":p.impersonate.kind==="live"?`Impersonate ${((k=t.auth)==null?void 0:k.uid)??""}`:"Impersonation not available"})]}),h.jsx(K_,{support:p.impersonate,haveCallback:!!r}),o&&o!=="pending"?h.jsx(Y_,{result:o}):null]}):null,h.jsxs("div",{className:"flex flex-col gap-2",children:[h.jsxs("div",{className:"flex items-center justify-between gap-3",children:[h.jsx("span",{className:"text-sm font-medium text-soft-white",children:"Re-run against an edited ruleset"}),h.jsx("button",{type:"button",disabled:!b||d==="pending",onClick:w,className:"rounded-md border border-primary/40 px-3 py-1 text-xs font-medium text-primary transition-colors hover:bg-primary/10 disabled:cursor-not-allowed disabled:border-border disabled:text-slate-gray",children:d==="pending"?"Linting + forking…":"Lint, then test on a branch"})]}),n&&p.editedRuleset.kind==="live"?h.jsx(uk,{value:e??"",onChange:n,markLine:(I=t.evaluatedRule)==null?void 0:I.line,markKind:t.result==="allow"?"allow":"deny",minHeightRem:14,ariaLabel:"Edited firestore.rules to test the op against"}):null,h.jsx(K_,{support:p.editedRuleset,haveCallback:!!s}),d&&d!=="pending"?h.jsxs(h.Fragment,{children:[d.lint.findings.length>0||!d.lint.parseable?h.jsx(pF,{lint:d.lint}):null,h.jsx(Y_,{result:d.result}),d.diff.length>0?h.jsx(yF,{diff:d.diff}):null]}):null]})]})}function K_({support:t,haveCallback:e}){if(t.kind==="pending"||t.kind==="absent"){const n=t.kind==="pending"?t.tool:t.missingTool;return h.jsxs("p",{"data-pyric-ui":"rerun-hint-gated",className:"rounded-md border border-border bg-content-bg px-3 py-2 text-xs text-slate-gray",children:[t.hint," ",h.jsx("code",{className:"font-mono text-[0.7rem] text-warning",children:n})]})}return e?null:h.jsx("p",{className:"rounded-md border border-border bg-content-bg px-3 py-2 text-xs text-slate-gray",children:"Wired to the live sandbox once the local backend is reachable. The denial, rule, and context above are already live."})}function pF({lint:t}){return h.jsxs("div",{"data-pyric-ui":"rerun-lint",className:"flex flex-col gap-1 rounded-md border border-border bg-content-bg p-3",children:[h.jsx("span",{className:"text-[0.65rem] font-semibold uppercase tracking-wider text-slate-gray",children:"lint (firestore_lint_rules)"}),t.parseable?t.findings.map((e,n)=>h.jsxs("p",{className:"font-mono text-xs",children:[h.jsx("span",{className:e.severity==="error"?"text-danger":"text-warning",children:e.rule}),h.jsxs("span",{className:"text-slate-gray",children:[" — ",e.message]})]},`${e.rule}-${n}`)):h.jsx("p",{className:"font-mono text-xs text-danger",children:t.parseError})]})}function Y_({result:t}){return t.outcome==="allow"?h.jsxs("p",{className:"flex items-center gap-2 text-xs",children:[h.jsx(Ja,{kind:"allow",className:"rounded bg-primary/15 px-2 py-0.5 font-semibold uppercase text-primary",children:"allow"}),h.jsx("span",{className:"text-slate-gray",children:"The re-run is permitted under these rules."})]}):t.outcome==="deny"?h.jsxs("p",{className:"flex items-center gap-2 text-xs",children:[h.jsx(Ja,{kind:"deny",className:"rounded bg-danger/15 px-2 py-0.5 font-semibold uppercase text-danger",children:"deny"}),h.jsxs("span",{className:"text-slate-gray",children:["Denied under these rules: ",t.message]})]}):h.jsxs("p",{className:"flex items-center gap-2 text-xs",children:[h.jsx(Ja,{kind:"error",className:"rounded bg-warning/15 px-2 py-0.5 font-semibold uppercase text-warning",children:t.code}),h.jsx("span",{className:"text-slate-gray",children:t.message})]})}function mF(t){return t.kind==="autoid-alias"?{path:t.originalPath,before:t.originalPath,after:t.replayedPath}:{path:t.path,..."field"in t&&t.field?{field:t.field}:{},before:t.before,after:t.after}}function yF({diff:t}){return h.jsxs("div",{"data-pyric-ui":"rules-debug-diff",className:"flex flex-col gap-1 rounded-md border border-border bg-content-bg p-3",children:[h.jsx("span",{className:"text-[0.65rem] font-semibold uppercase tracking-wider text-slate-gray",children:"what the re-run changed (branch vs live)"}),t.map((e,n)=>{const r=mF(e),s=r.field?`.${r.field}`:"",o=r.before===void 0&&r.after!==void 0,c=r.before!==void 0&&r.after===void 0;return h.jsxs("div",{className:"font-mono text-xs",children:[h.jsxs("span",{className:o?"text-diff-add":c?"text-diff-remove":"text-warning",children:[o?"+ ":c?"- ":"~ ",r.path,s]}),o?null:h.jsx("span",{className:"ml-2 text-slate-gray",children:JSON.stringify(oo(r.before))}),c?null:h.jsxs("span",{className:"ml-2 text-soft-white",children:["→ ",JSON.stringify(oo(r.after))]})]},`${r.path}-${n}`)})]})}function Z_({eventId:t,onClose:e}){const n=y4(),r=x4(),s=A4(),o=n.find(b=>b.id===t),[c,d]=A.useState(""),f=c||s;if(!o)return h.jsxs("div",{"data-pyric-ui":"traffic-inspect-missing",className:"traffic__inspector",children:[h.jsx("p",{className:"traffic__inspector-missing",children:"This operation isn't in this session's traffic. It may be from an earlier session, or the event has aged out of the buffer."}),h.jsx("button",{type:"button",className:"traffic__inspector-close",onClick:e,children:"Back to the log"})]});const p=async b=>{const v=await r();if(!v)return{outcome:"error",code:"no-backend",message:"No sandbox snapshot to re-run against."};const w=zE(v,s);try{return await ck(w.sandbox,b)}finally{PE(w)}},g=async(b,v)=>{const w=await r();return w?eF(w,b,v,w):{result:{outcome:"error",code:"no-backend",message:"No sandbox snapshot to re-run against."},diff:[],lint:{parseable:!0,findings:[]}}};return h.jsxs("div",{"data-pyric-ui":"traffic-rules-inspector",className:"traffic__inspector",children:[h.jsxs("div",{className:"traffic__inspector-bar",children:[h.jsx("span",{className:"traffic__inspector-title",children:"rules inspector"}),h.jsx("button",{type:"button",className:"traffic__inspector-close",onClick:e,"aria-label":"Close rules inspector (Esc)",children:"close (esc)"})]}),h.jsx(dk,{denial:o,editedRules:f,rulesSource:s,onEditedRulesChange:d,onRerunAsUser:p,onRerunAgainstRules:g})]})}const gF=new Intl.NumberFormat,bF={reads:"read operations",writes:"writes",deletes:"deletes"},vF={allows:"allowed requests",denies:"denied requests"};function W_(t){return t.length<=1?t[0]??"":t.length===2?`${t[0]} and ${t[1]}`:`${t.slice(0,-1).join(", ")}, and ${t.at(-1)}`}function Q_(t){return t&&`${t[0].toUpperCase()}${t.slice(1)}`}function mk(t,e){const n=t.reduce((p,g)=>p+g.total,0);if(n===0)return{total:n,headline:e.emptyHeadline,finding:e.emptyFinding};const r=Math.max(...t.map(p=>p.total)),s=t.filter(p=>p.total===r),o=`${gF.format(n)} observed ${n===1?e.singular:e.plural}`,c=p=>e.labels[p.key]??p.label.toLowerCase();if(s.length>1){const p=s.map(c);return{total:n,headline:o,finding:s.length===t.length?`${e.evenSplitPrefix} ${W_(p)}.`:`${Q_(W_(p))} tied for the largest share of ${e.subject} in this window.`}}const d=s[0],f=Math.round(d.total/n*100);return{total:n,headline:o,finding:`${Q_(c(d))} accounted for ${f}% of ${e.subject} in this window.`}}function wF(t){return mk(t,{labels:bF,singular:"billable operation",plural:"billable operations",subject:"activity",evenSplitPrefix:"Activity was split evenly across",emptyHeadline:"No billable activity observed",emptyFinding:"Successful reads, writes, and deletes will appear here as they happen."})}function xF(t){return mk(t,{labels:vF,singular:"Rules evaluation",plural:"Rules evaluations",subject:"evaluations",evenSplitPrefix:"Evaluations were split evenly between",emptyHeadline:"No Rules evaluations observed",emptyFinding:"Allow and deny decisions will appear here as Rules evaluate requests."})}const SF=new Intl.NumberFormat,_F=new Intl.DateTimeFormat(void 0,{hour:"numeric",minute:"2-digit"});function J_(t){return SF.format(t)}function bl(t){return _F.format(t)}function EF(t){return rf(t)==="bypassed"}function AF(t){return t.every(e=>e.total===0)}function yk({eyebrow:t,story:e,series:n,points:r,window:s,emptyLabel:o,evidenceTitle:c,source:d,methodology:f}){const[p,g]=A.useState(()=>new Set(n.map(v=>v.key))),b=A.useCallback(v=>{g(w=>{const _=new Set(w);return _.has(v)?_.delete(v):_.add(v),_})},[]);return h.jsxs("section",{className:"traffic__metric-panel traffic__metric-panel--journal","data-pyric-ui":"traffic-metric-panel",children:[h.jsxs("header",{className:"traffic__metric-story",children:[h.jsx("p",{className:"traffic__metric-eyebrow",children:t}),h.jsx("h3",{className:"traffic__metric-headline",children:e.headline}),h.jsx("p",{className:"traffic__metric-finding",children:e.finding})]}),h.jsx(kB,{series:n,visible:p,onToggle:b,formatValue:J_,className:`traffic__metric-cards traffic__metric-cards--journal traffic__metric-cards--${n.length}`}),AF(n)?h.jsx("p",{className:"traffic__empty",children:o}):h.jsxs("div",{className:"traffic__metric-evidence",children:[h.jsxs("div",{className:"traffic__metric-evidence-header",children:[h.jsx("h4",{children:c}),h.jsxs("span",{children:[bl(s.start),"–",bl(s.end)]})]}),h.jsx(OB,{points:r,series:n,visible:p,omitZeroSeries:!0,formatValue:J_,formatTime:bl,className:"traffic__chart traffic__chart--journal"}),h.jsxs("div",{className:"traffic__metric-axis","aria-hidden":"true",children:[h.jsx("span",{children:bl(s.start)}),h.jsx("span",{children:bl(s.end)})]})]}),h.jsxs("footer",{className:"traffic__metric-footer",children:[h.jsx("p",{className:"traffic__metric-source",children:d}),h.jsxs("details",{className:"traffic__metric-methodology",children:[h.jsx("summary",{children:"How this is counted"}),h.jsx("div",{children:f})]})]})]})}function jF({events:t,window:e}){const n=A.useMemo(()=>t.filter(o=>(o.service??"firestore")==="firestore"),[t]),r=oB({events:n,window:e,isAdmin:EF}),s=A.useMemo(()=>wF(r.series),[r.series]);return h.jsx("div",{className:"traffic__metrics","data-pyric-ui":"traffic-billable-view",children:h.jsx(yk,{eyebrow:"Billable activity",story:s,series:r.series,points:r.points,window:e,emptyLabel:"No reads, writes, or deletes in this session yet.",evidenceTitle:"When the activity happened",source:"Source: Pyric Firestore sandbox events · Operation counts, not a Firebase invoice",methodology:h.jsxs(h.Fragment,{children:[h.jsxs("p",{children:["Counts successful Firestore sandbox ",h.jsx("code",{children:"get"}),"/",h.jsx("code",{children:"list"}),","," ",h.jsx("code",{children:"create"}),"/",h.jsx("code",{children:"update"}),"/",h.jsx("code",{children:"set"}),", and"," ",h.jsx("code",{children:"delete"}),"/",h.jsx("code",{children:"remove"})," operations in the displayed window. Rules-bypassed admin operations are included because they still execute."]}),h.jsxs("p",{children:[h.jsx("strong",{children:"Read ops are a proxy, not billed document reads."})," Each"," ",h.jsx("code",{children:"list"})," is counted once because the event does not report how many documents the query returned. This is observed sandbox activity, not a Firebase invoice."]})]})})})}function kF({events:t,window:e}){const n=A.useMemo(()=>t.filter(c=>c.rulesDisposition.kind==="evaluated"),[t]),r=lB({events:n,window:e}),s=A.useMemo(()=>r.series.filter(c=>c.key==="allows"||c.key==="denies"),[r.series]),o=A.useMemo(()=>xF(s),[s]);return h.jsx("div",{className:"traffic__metrics","data-pyric-ui":"traffic-rules-view",children:h.jsx(yk,{eyebrow:"Rules decisions",story:o,series:s,points:r.points,window:e,emptyLabel:"No allow or deny decisions in this session yet.",evidenceTitle:"When Rules evaluated requests",source:"Source: Pyric sandbox events · Evaluated Rules dispositions only",methodology:h.jsxs(h.Fragment,{children:[h.jsxs("p",{children:["Counts only operations whose canonical Rules disposition is"," ",h.jsx("code",{children:"evaluated"}),", grouped by its ",h.jsx("code",{children:"allow"})," or ",h.jsx("code",{children:"deny"})," ","verdict."]}),h.jsxs("p",{children:[h.jsx("strong",{children:"Bypasses and runtime failures are not Rules decisions."})," Admin bypasses, services without Rules, unsupported operations, and runtime errors are excluded because Rules did not produce a verdict."]})]})})})}const CF=[{id:"timeline",label:"Timeline"},{id:"billable",label:"Billable metrics"},{id:"rules",label:"Rules"}];function NF(t){return t==="billable"?"billable":t==="rules"||t==="subscriptions"?"rules":"timeline"}function OF(t,e){return t===0?"No requests occurred in this interval.":t===1?e===1?"The request in this interval was denied.":"One request occurred in this interval; it was not denied.":e===0?`${t} requests occurred in this interval; none were denied.`:e===t?`All ${t} requests in this interval were denied.`:`${t} requests occurred in this interval; ${e} ${e===1?"was":"were"} denied.`}function RF(t,e){const n=t.filter(s=>s.at>=e.start&&s.at<e.end),r=n.reduce((s,o)=>s+(o.result==="deny"?1:0),0);return{window:e,events:n,total:n.length,denies:r,finding:OF(n.length,r)}}function TF(t,e){return(t==null?void 0:t.start)===e.start&&t.end===e.end?null:e}function DF(){const{tab:t,query:e}=Rr();return t!=="traffic"?"timeline":NF(e.view)}function IF(){const t=A.useSyncExternalStore(ec,DF,()=>"timeline"),e=A.useCallback(n=>{const r={...Rr().query,view:n==="timeline"?void 0:n};r.view===void 0&&delete r.view,Jn({tab:"traffic",query:r})},[]);return[t,e]}function MF(){const t=A.useSyncExternalStore(ec,()=>Rr().query.hide==="studio",()=>!1),e=A.useCallback(()=>{const n={...Rr().query};n.hide==="studio"?delete n.hide:n.hide="studio",Jn({tab:"traffic",query:n})},[]);return[t,e]}function LF(t,e){const n=Math.max(0,Math.round((e-t)/1e3));if(n<60)return`${n}s ago`;const r=Math.round(n/60);return r<60?`${r}m ago`:`${Math.round(r/60)}h ago`}function X_(t){return`${Kl(t.start)}–${Kl(t.end)}`}function UF({event:t}){const e=rf(t);return e?h.jsx("span",{className:"traffic__verdict","data-verdict":e,children:e}):null}function $F(){return A.useSyncExternalStore(ec,()=>ok(Rr().query),()=>null)}const dm=100;function BF(){const t=m4(),[e,n]=IF(),[r,s]=MF(),o=A.useMemo(()=>Zq(t,r),[t,r]),c=t.length-o.length,[d,f]=A.useState("all"),[p,g]=A.useState(null),b=$F(),[v,w]=A.useState(dm),_=E=>{Jn({tab:"traffic",query:Jq(Rr().query,E)})},k=()=>{Jn({tab:"traffic",query:lk(Rr().query,null)})};A.useEffect(()=>{if(!b)return;const E=O=>{O.key==="Escape"&&k()};return globalThis.addEventListener("keydown",E),()=>globalThis.removeEventListener("keydown",E)},[b]);const I=A.useMemo(()=>{const E=Date.now();if(o.length===0)return{start:E-15*6e4,end:E};let O=1/0;for(const T of o)T.at<O&&(O=T.at);return{start:Math.min(O,E-6e4),end:E+1e3}},[o]),N=I.end,R=A.useMemo(()=>p?RF(o,p):null,[o,p]),M=(R==null?void 0:R.events)??o,F=A.useMemo(()=>Qq(M,d).sort((E,O)=>O.at-E.at),[M,d]),{items:D}=K4({events:F}),C=D.slice(0,v),L=D.length-C.length,U=o.length>=_d,H=o.filter(E=>E.result==="deny").length,z=E=>h.jsx(UF,{event:E}),q=E=>{if(um(E)){_(E.id);return}const O=G_(E);O&&Jn(O)},x=b!=null&&C.some(E=>E.type!=="group"&&E.event.id===b);return h.jsxs("section",{"data-pyric-ui":"traffic-surface",className:"traffic",children:[h.jsxs("div",{className:"traffic__tabs",role:"tablist","aria-label":"Traffic views",children:[CF.map(E=>h.jsx("button",{type:"button",role:"tab",className:"traffic__tab","aria-selected":e===E.id,onClick:()=>n(E.id),children:E.label},E.id)),h.jsxs("button",{type:"button",className:"traffic__hide-studio","aria-pressed":r,onClick:s,title:"Hide ops issued by Pyric Studio's own viewers and editors",children:["Hide Studio traffic",r&&c>0?` (${c} hidden)`:""]})]}),e==="billable"?h.jsx(jF,{events:o,window:I}):e==="rules"?h.jsx(kF,{events:o,window:I}):h.jsxs(h.Fragment,{children:[h.jsx(EB,{events:o,window:I,brush:p??void 0,onBrush:E=>{g(O=>TF(O,E)),b&&k()},liveAt:I.end,bucketCount:36,className:"traffic__timeline",header:h.jsxs("div",{className:"traffic__tl-header",children:[h.jsxs("span",{className:"traffic__tl-count",children:[o.length," requests",U?` (showing latest ${_d})`:""]}),H>0?h.jsxs("button",{type:"button",className:"traffic__tl-deny","aria-pressed":d==="deny",onClick:()=>f(E=>E==="deny"?"all":"deny"),title:"Filter the stream to denied requests",children:[H," denied"]}):null,h.jsx("span",{className:"traffic__tl-live",children:"live"})]}),axis:E=>h.jsxs("div",{className:"traffic__tl-axis",children:[h.jsx("span",{children:LF(E.start,N)}),h.jsx("span",{children:"now"})]}),renderBucketSummary:E=>h.jsxs("div",{className:"traffic__bucket-summary",children:[h.jsx("span",{children:X_(E)}),h.jsxs("strong",{children:[E.count," ",E.count===1?"request":"requests"]}),h.jsxs("span",{children:[E.denies," denied"]})]}),emptyState:h.jsx("p",{className:"traffic__empty",children:"No requests in this window yet."})}),R?h.jsxs("section",{className:"traffic__time-focus","aria-label":"Selected traffic interval","aria-live":"polite",children:[h.jsxs("div",{className:"traffic__time-focus-story",children:[h.jsx("p",{className:"traffic__time-focus-eyebrow",children:"Selected interval"}),h.jsx("h3",{children:X_(R.window)}),h.jsx("p",{children:R.finding})]}),h.jsx("button",{type:"button",onClick:()=>g(null),children:"Show all traffic"})]}):null,h.jsxs("div",{className:"traffic__filters",role:"group","aria-label":"Traffic filters",children:[h.jsx("span",{className:"traffic__filters-label","aria-hidden":"true",children:"verdict"}),Wq.map(E=>h.jsx("button",{type:"button",className:"traffic__filter","aria-pressed":d===E,onClick:()=>f(E),children:E},E))]}),b&&!x?h.jsx(Z_,{eventId:b,onClose:k},b):null,D.length===0?h.jsx("p",{className:"traffic__empty",children:R?d==="all"?"No requests occurred in the selected interval.":`No ${d} traffic occurred in the selected interval.`:d==="all"?"No requests yet. Reads, writes, and listeners against the sandbox stream in live.":`No ${d} traffic in this session.`}):h.jsxs("div",{className:"traffic__log","data-pyric-ui":"traffic-log","data-pyric-grouped":"","data-pyric-time-focused":R?"":void 0,children:[h.jsx("ul",{"data-pyric-traffic-log-items":"",children:C.map(E=>E.type==="group"?h.jsx("li",{"data-pyric-traffic-group-entry":"",children:h.jsx(SB,{group:E,onSelect:O=>{const T=O;if(um(T)){_(T.id);return}const P=G_(T);P&&Jn(P)},renderClassification:O=>z(O),formatTime:Kl})},E.key):h.jsxs("li",{"data-pyric-traffic-entry":"","data-pyric-traffic-id":E.event.id,"data-verdict":rf(E.event)??void 0,children:[h.jsx(hj,{event:E.event,selected:E.event.id===b,onSelect:O=>q(O),renderClassification:O=>z(O),formatTime:Kl}),E.event.id===b&&um(E.event)?h.jsx(Z_,{eventId:b,onClose:k},b):null]},E.event.id))}),L>0?h.jsxs("button",{type:"button",className:"traffic__show-more",onClick:()=>w(E=>E+dm),children:["Show ",Math.min(L,dm)," more (",L," hidden)"]}):null]})]})]})}const e1=["amber","teal","coral","slate","olive","plum","rust","indigo","mint","sand","ash","jade"],t1=["fox","owl","lynx","crane","otter","wren","ibex","hare","newt","moth","seal","vole"];function $g(t){if(!t)return"";let e=0;for(let n=0;n<t.length;n++)e=Math.imul(e,31)+t.charCodeAt(n)>>>0;return`${e1[e%e1.length]}-${t1[(e>>>4)%t1.length]}`}function qF(t){var r;const e=((r=t.operationContext)==null?void 0:r.source)??t.actor;if((e==null?void 0:e.kind)==="agent")return{provenance:"agent",identity:`agent:${e.name}`};if((e==null?void 0:e.kind)==="studio")return{provenance:"studio",identity:"studio"};if((e==null?void 0:e.kind)==="app-builder")return{provenance:"app-builder",identity:"builder"};const n="auth"in t&&t.auth&&typeof t.auth=="object"?t.auth.uid:void 0;return!e||e.kind==="unattributed"?{provenance:"unattributed",identity:n??"unattributed"}:{provenance:"app",identity:n??"app"}}function FF(t){return t?{tab:"firestore",rest:t.split("/").filter(Boolean)}:null}function zF(t){var s;const{provenance:e,identity:n}=qF(t),r={id:t.id,at:t.at,provenance:e,identity:n};switch(t.kind){case"write":return{...r,denied:!1,summary:`${t.method} /${t.path}`,target:FF(t.path)};case"request":return t.result!=="deny"?null:{...r,denied:!0,summary:`denied ${t.method} /${t.path}`,target:{tab:"traffic",query:{inspect:t.id}}};case"operation":return t.result==="deny"?{...r,denied:!0,summary:`denied ${t.service} ${t.method}${t.path?` ${t.path}`:""}`,target:{tab:"traffic",query:{inspect:t.id}}}:null;case"service_mutation":{const o=t.path?` ${t.path}`:"",c=t.service==="auth"&&t.path&&t.path!=="*"?{tab:"auth",rest:[t.path]}:t.service==="storage"&&t.path?{tab:"storage",rest:t.path.split("/").filter(Boolean)}:t.service==="rtdb"?{tab:"rtdb"}:null;return{...r,denied:!1,summary:`${t.service} ${t.op}${o}`,target:c}}case"commit":return t.service!=="rtdb"||((s=t.detail)==null?void 0:s.admin)!==!0?null:{...r,denied:!1,summary:`rtdb ${t.method}${t.path?` ${t.path}`:""}`,target:{tab:"rtdb"}};case"session_boundary":return{...r,provenance:"system",identity:"sandbox",denied:!1,summary:`session ${t.phase}`,target:null};default:return null}}function PF(t,e=20){const n=[];for(let r=t.length-1;r>=0&&n.length<e;r--){const s=zF(t[r]);s&&n.push(s)}return n}const VF=20;function HF(t){Jn(t)}function lo({target:t,className:e,children:n,title:r}){return h.jsx("a",{className:e,href:Gd(t),title:r,onClick:s=>{s.metaKey||s.ctrlKey||s.shiftKey||s.altKey||(s.preventDefault(),HF(t))},children:n})}function GF(){const t=cs(),e=Qd(),n=Cg();if(e.status==="loading"||t.status==="pending")return h.jsxs("div",{className:"studio-home__status","aria-label":"Sandbox status",children:[h.jsx("span",{className:"studio-chip studio-home__skeleton-chip","aria-hidden":"true"}),h.jsx("span",{className:"studio-chip studio-home__skeleton-chip","aria-hidden":"true"})]});const s=[];if(t.status==="ready"&&e.status!=="ready"&&s.push(h.jsxs("span",{className:"studio-chip",title:"In-page seeded sandbox — no server. Data resets on reload.",children:[h.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),"dev seed · in-page"]},"seed")),e.status==="ready"){const o=e.payload;s.push(h.jsxs(lo,{className:"studio-chip",target:{tab:"settings"},title:"Persistence mode — manage in Settings.",children:[h.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),o.persist?"persisted to disk":"ephemeral"]},"persist")),o.rulesHash&&s.push(h.jsxs("span",{className:"studio-chip",title:"Hash of the rules this serve deployed to the sandbox.",children:[h.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),"rules ",o.rulesHash.slice(0,8)]},"rules"))}return n&&s.push(h.jsxs(lo,{className:"studio-chip",target:{tab:"settings"},title:`Sandbox instance ${n} — maintenance lives in Settings.`,children:[h.jsx("span",{className:"studio-chip__dot","aria-hidden":"true"}),$g(n)]},"instance")),h.jsx("div",{className:"studio-home__status","aria-label":"Sandbox status",children:s})}function KF(t){return new Date(t).toLocaleTimeString(void 0,{hour12:!1})}function YF(){const t=sc(),e=A.useMemo(()=>PF(t,VF),[t]);return h.jsxs("section",{className:"studio-panel studio-home__feed","aria-label":"Live activity",children:[h.jsxs("header",{className:"studio-home__feed-head",children:[h.jsx("h2",{className:"studio-panel__title studio-home__feed-title",children:"Activity"}),h.jsx(lo,{className:"studio-home__feed-all",target:{tab:"traffic"},children:"view all in Traffic →"})]}),e.length===0?h.jsx("p",{className:"studio-home__feed-empty",children:"No activity yet — writes, denials, and seeds show up here live."}):h.jsx("div",{className:"studio-home__feed-scroll",children:h.jsx("ol",{className:"studio-home__feed-list",children:e.map(n=>{const r=h.jsxs(h.Fragment,{children:[h.jsxs("span",{className:"studio-home__feed-ident","data-provenance":n.provenance,children:[h.jsx("span",{className:"studio-home__feed-dot","aria-hidden":"true"}),n.identity]}),h.jsx("span",{className:"studio-home__feed-summary","data-denied":n.denied?"true":void 0,children:n.summary}),h.jsx("time",{className:"studio-home__feed-time",dateTime:new Date(n.at).toISOString(),children:KF(n.at)})]});return h.jsx("li",{children:n.target?h.jsx(lo,{className:"studio-home__feed-row",target:n.target,children:r}):h.jsx("span",{className:"studio-home__feed-row",children:r})},n.id)})})})]})}const ZF=["firestore","auth","rtdb","storage","traffic"];function WF(){const t=ri(),e=sc(),n=A.useMemo(()=>{const r={};if(t.status==="ready"){const s=t.handles.listRootCollections().length;r.firestore=`${s} collection${s===1?"":"s"}`}return e.length&&(r.traffic=`${e.length} events`),r},[t,e]);return h.jsx("div",{className:"studio-home__tiles",children:ZF.map(r=>{const s=Pi.find(o=>o.id===r);return s?h.jsxs(lo,{className:"studio-card studio-home__tile",target:{tab:r},children:[h.jsxs("span",{className:"studio-home__tile-top",children:[h.jsx("span",{className:"studio-home__tile-label",children:s.label}),n[r]?h.jsx("span",{className:"studio-badge",children:n[r]}):null]}),h.jsx("span",{className:"studio-home__tile-desc",children:s.description})]},r):null})})}function QF(){const t=Qd(),e=t.status==="ready",n=e&&!!t.payload.bridgeUrl,r=typeof window<"u"?window.location.origin:"",s=e?t.payload.rulesHash:null;return h.jsxs(h.Fragment,{children:[h.jsxs("section",{className:"studio-card studio-home__onboard","aria-label":"Connect your agent",children:[h.jsx("span",{className:"studio-home__tile-label",children:"Connect your agent"}),h.jsx("span",{className:"studio-home__tile-desc",children:"Point Claude Code, Cursor, or any MCP client at this sandbox and its writes show up in the feed, attributed."}),h.jsx("code",{className:"studio-home__snippet",children:n?`${r}/__pyric/mcp`:"pyric dev --bridge # then <url>/__pyric/mcp"})]}),h.jsxs("section",{className:"studio-card studio-home__onboard","aria-label":"Seed data",children:[h.jsx("span",{className:"studio-home__tile-label",children:"Seed data"}),h.jsx("span",{className:"studio-home__tile-desc",children:"Start from a fixture, or create documents by hand in the Firestore browser."}),h.jsx("code",{className:"studio-home__snippet",children:"pyric dev --seed seed.json"}),h.jsx(lo,{className:"studio-home__onboard-link",target:{tab:"firestore"},children:"open Firestore →"})]}),h.jsxs("section",{className:"studio-card studio-home__onboard","aria-label":"Bring your rules",children:[h.jsx("span",{className:"studio-home__tile-label",children:"Bring your rules"}),s?h.jsxs("span",{className:"studio-home__tile-desc",children:["Your repo rules are deployed to this sandbox (",s.slice(0,8),"). Denials will appear in the feed and in Traffic."]}):h.jsxs(h.Fragment,{children:[h.jsx("span",{className:"studio-home__tile-desc",children:"Serve your repo's rules file and every denial becomes a debuggable event."}),h.jsx("code",{className:"studio-home__snippet",children:"pyric dev --rules firestore.rules"})]})]})]})}function JF(){const t=ri(),e=sc(),n=cs(),r=t.status==="pending"||n.status==="pending",s=!r&&e.length===0&&(t.status!=="ready"||t.handles.listRootCollections().length===0);return h.jsxs("section",{className:"studio-surface studio-home","aria-label":"Home",children:[h.jsxs("div",{className:"studio-home__hero",children:[h.jsx("img",{className:"studio-home__hero-logo",src:"/__pyric/ui/pyric-logo.svg",alt:"","aria-hidden":"true"}),h.jsx("h1",{className:"studio-home__hero-title",children:"Firebase that runs in the browser"})]}),h.jsx(dj,{exposeFocus:y3}),h.jsx(GF,{}),h.jsx("div",{className:"studio-home__body",children:r?h.jsxs("section",{className:"studio-panel studio-home__feed studio-home__skeleton","aria-hidden":"true",children:[h.jsx("div",{className:"studio-home__skeleton-row"}),h.jsx("div",{className:"studio-home__skeleton-row"}),h.jsx("div",{className:"studio-home__skeleton-row"})]}):s?h.jsx(QF,{}):h.jsxs(h.Fragment,{children:[h.jsx(YF,{}),h.jsx(WF,{})]})})]})}function Pt(t){const e=t.split("/").filter(Boolean);return e.length===0?"/":`/${e.join("/")}`}function Hi(t){return Pt(t).split("/").filter(Boolean)}function My(t,e){return Pt([...Hi(t),...e.split("/").filter(Boolean)].join("/"))}function gk(t,e){const n=Hi(t),r=Hi(e);if(r.length<n.length)return null;for(let o=0;o<n.length;o++)if(r[o]!==n[o])return null;const s=r.slice(n.length);return s.length===0?"/":`/${s.join("/")}`}function bk(t){if(t==null)return null;if(typeof t!="object")return t;const e=t;let n=!1;const r={};for(const[s,o]of Object.entries(e)){const c=bk(o);if(c===null){n=!0;continue}c!==o&&(n=!0),r[s]=c}return Object.keys(r).length===0?null:n?r:t}function XF(t){if(typeof t=="string")return JSON.stringify(t);if(t==null)return"null";if(typeof t=="object")try{return JSON.stringify(t)??"null"}catch{return"null"}return String(t)}function Bg(t){return t===null||typeof t!="object"?!1:Object.keys(t).length>0}function vk(t){return t===null||typeof t!="object"?[]:Object.entries(t).sort(([e],[n])=>e.localeCompare(n,void 0,{numeric:!0}))}function wk(t,e){let n=t??null;for(const r of Hi(e)){if(n===null||typeof n!="object")return null;n=n[r]??null}return n}function ez(t){return t==null?"null":Array.isArray(t)?"array":typeof t}function Ly(t,e){if(Object.is(t,e))return!0;if(Array.isArray(t)||Array.isArray(e))return!Array.isArray(t)||!Array.isArray(e)||t.length!==e.length?!1:t.every((c,d)=>Ly(c,e[d]));if(t===null||e===null||typeof t!="object"||typeof e!="object")return!1;const n=t,r=e,s=Object.keys(n),o=Object.keys(r);return s.length!==o.length?!1:s.every(c=>c in r&&Ly(n[c],r[c]))}function tz(t,e){const n=new Map,r=(s,o)=>{if(!Bg(s)){n.set(o,["leaf",s??null]);return}const c=vk(s);n.set(o,["parent",c.map(([d])=>d)]);for(const[d,f]of c)r(f,My(o,d))};return r(t,Pt(e)),n}function nz(t){let e=t.trim();if(e.length===0)return"/";const n=/^[a-z][a-z0-9+.-]*:\/\/[^/?#]+/i.exec(e);return n&&(e=e.slice(n[0].length)),e=e.replace(/[?#].*$/,""),Pt(e)}function rz(t){const e=Hi(t);return e.map((n,r)=>({label:n,path:`/${e.slice(0,r+1).join("/")}`}))}const sz=["string","number","boolean","json"];function n1(t){switch(typeof t){case"string":return"string";case"number":return"number";case"boolean":return"boolean";default:return"json"}}function iz(t,e){return e==="json"?JSON.stringify(t??null):t==null?"":String(t)}function az(t){if(t.trim().length===0)return"Enter a key.";const e=t.match(/[.$#[\]/]/);return e?`Keys can't contain "${e[0]}".`:null}function oz(t,e){switch(t){case"string":return{ok:!0,value:e};case"number":{const n=e.trim();if(n.length===0)return{ok:!1,error:"Enter a number."};const r=Number(n);return Number.isNaN(r)?{ok:!1,error:`"${e}" is not a number.`}:{ok:!0,value:r}}case"boolean":{const n=e.trim().toLowerCase();return n==="true"?{ok:!0,value:!0}:n==="false"?{ok:!0,value:!1}:{ok:!1,error:"Enter true or false."}}case"json":{const n=e.trim();if(n.length===0)return{ok:!0,value:null};try{return{ok:!0,value:JSON.parse(n)}}catch(r){return{ok:!1,error:r instanceof Error?r.message:"Invalid JSON."}}}}}function xk(t){return{path:Pt(t),status:"loading",value:null,error:null,expanded:{},pages:{}}}function Sk(t,e){const n=gk(t.path,e);return n===null?null:wk(t.value,n)}function lz(t,e){const n=Pt(e);return n===t.path||t.expanded[n]===!0}function cz(t,e,n){const r=vk(Sk(t,e)),s=Math.min(r.length,t.pages[Pt(e)]??n);return{entries:r.slice(0,s),total:r.length,hiddenCount:r.length-s}}function r1(t,e){const n={};let r=!1;for(const[s,o]of Object.entries(t)){const c=gk(e.path,s);c!==null&&Bg(wk(e.value,c))?n[s]=o:r=!0}return r?n:t}function _k(t,e){switch(e.type){case"navigate":{const n=Pt(e.path);return n===t.path?t:xk(n)}case"value":{if(Pt(e.path)!==t.path)return t;const n={...t,status:"live",value:bk(e.value),error:null};return n.expanded=r1(t.expanded,n),n.pages=r1(t.pages,n),n}case"error":return Pt(e.path)!==t.path?t:{...t,status:"error",error:e.message};case"expand":{const n=Pt(e.path);return n===t.path||t.expanded[n]?t:{...t,expanded:{...t.expanded,[n]:!0}}}case"collapse":{const n=Pt(e.path);if(!t.expanded[n])return t;const r={...t.expanded};return delete r[n],{...t,expanded:r}}case"toggle":{const n=Pt(e.path);return _k(t,{type:t.expanded[n]?"collapse":"expand",path:n})}case"show-more":{const n=Pt(e.path),r=t.pages[n]??e.pageSize;return{...t,pages:{...t.pages,[n]:r+e.pageSize}}}}}const uz=50;function dz(t,e,n={}){const r=n.pageSize??uz,s=Pt(e),[o,c]=A.useReducer(_k,s,xk),d=A.useMemo(()=>tz(o.value,o.path),[o.path,o.value]),f=Ug({scope:o.path,entries:d,equals:Ly,ready:o.status==="live"});o.path!==s&&c({type:"navigate",path:s}),A.useEffect(()=>{let k=!1;const I=t.subscribeValue(s,N=>{k||c({type:"value",path:s,value:N})},N=>{k||c({type:"error",path:s,message:N instanceof Error?N.message:String(N)})});return()=>{k=!0,I()}},[t,s]);const p=A.useCallback(k=>Sk(o,k),[o]),g=A.useCallback(k=>lz(o,k),[o]),b=A.useCallback(k=>cz(o,k,r),[o,r]),v=A.useCallback(k=>c({type:"toggle",path:k}),[]),w=A.useCallback(k=>c({type:"show-more",path:k,pageSize:r}),[r]),_=A.useCallback(k=>f.get(Pt(k)),[f]);return A.useMemo(()=>({state:o,pageSize:r,valueAt:p,isExpanded:g,childrenAt:b,toggle:v,showMore:w,updateAt:_}),[o,r,p,g,b,v,w,_])}function fz({path:t,onNavigate:e,rootLabel:n="/",inputPrefix:r,className:s}){const o=Pt(t),[c,d]=A.useState(!1),f=A.useRef(null);A.useEffect(()=>{var v;c&&((v=f.current)==null||v.select())},[c]);const p=v=>{var w;v.preventDefault(),e(nz(((w=f.current)==null?void 0:w.value)??"")),d(!1)},g=()=>d(!1),b=rz(o);return h.jsx("nav",{className:s,"data-pyric-ui":"rtdb-path-bar","data-rtdb-editing":c?"":void 0,"aria-label":"Database path",children:c?h.jsxs("form",{"data-rtdb-path-form":!0,onSubmit:p,children:[r?h.jsx("span",{"data-rtdb-path-prefix":!0,children:r}):null,h.jsx("input",{ref:f,"data-rtdb-path-input":!0,"aria-label":"Database path",autoFocus:!0,defaultValue:o,onBlur:g,onKeyDown:v=>{v.key==="Escape"&&g()},spellCheck:!1})]}):h.jsxs(h.Fragment,{children:[h.jsxs("ol",{"data-rtdb-crumb-list":!0,children:[h.jsx("li",{"data-rtdb-crumb-item":!0,children:h.jsx("button",{type:"button","data-rtdb-crumb":!0,"data-rtdb-crumb-root":!0,"data-pyric-current":b.length===0?"":void 0,"aria-current":b.length===0?"page":void 0,onClick:()=>e("/"),children:n})}),b.map((v,w)=>{const _=w===b.length-1;return h.jsxs("li",{"data-rtdb-crumb-item":!0,children:[h.jsx("span",{"aria-hidden":!0,"data-rtdb-crumb-separator":!0,children:"/"}),h.jsx("button",{type:"button","data-rtdb-crumb":!0,"data-pyric-current":_?"":void 0,"aria-current":_?"page":void 0,onClick:()=>e(v.path),children:v.label})]},v.path)})]}),h.jsx("button",{type:"button","data-rtdb-path-edit":!0,"aria-label":"Edit path",title:"Edit path",onClick:()=>d(!0),children:h.jsx("svg",{"aria-hidden":!0,viewBox:"0 0 16 16",width:"12",height:"12",fill:"currentColor",children:h.jsx("path",{d:"M11.7 1.3a1 1 0 0 1 1.4 0l1.6 1.6a1 1 0 0 1 0 1.4l-8.5 8.5-3.4 1.1a.5.5 0 0 1-.63-.63l1.1-3.4 8.43-8.57ZM10.9 3.5l1.6 1.6 1.2-1.2-1.6-1.6-1.2 1.2Z"})})})]})})}function hz({tree:t,api:e,onNavigate:n,rootLabel:r="/",className:s}){const{state:o}=t,c=Hi(o.path),d=c.length===0?r:c[c.length-1];return h.jsx("div",{className:s,"data-pyric-ui":"rtdb-tree",children:o.status==="loading"?h.jsx("p",{"data-rtdb-loading":!0,children:"Loading…"}):o.status==="error"?h.jsx("p",{role:"alert","data-rtdb-error":!0,children:o.error}):h.jsx(Ek,{tree:t,api:e,onNavigate:n,path:o.path,label:d,isViewRoot:!0})})}function Ek({tree:t,api:e,onNavigate:n,path:r,label:s,isViewRoot:o}){const c=t.valueAt(r),d=Bg(c),f=t.isExpanded(r),p=t.updateAt(r),[g,b]=A.useState(!1),[v,w]=A.useState(!1),[_,k]=A.useState(!1),[I,N]=A.useState(null),R=async(D,C)=>{try{await D(),N(null),C()}catch(L){N(L instanceof Error?L.message:String(L))}},M=()=>{b(!0),k(!1),d&&!f&&t.toggle(r)},F=d&&f?t.childrenAt(r):null;return h.jsxs("div",{"data-rtdb-node":!0,"data-rtdb-kind":d?"parent":"leaf","data-rtdb-view-root":o?"":void 0,"data-rtdb-expanded":d&&f?"":void 0,children:[h.jsxs("div",{"data-rtdb-row":!0,"data-pyric-update":p==null?void 0:p.kind,"data-pyric-update-cycle":p==null?void 0:p.cycle,children:[d&&!o?h.jsx("button",{type:"button","data-rtdb-caret":!0,"aria-expanded":f,"aria-label":f?"Collapse":"Expand",onClick:()=>t.toggle(r),children:h.jsx("svg",{"aria-hidden":!0,viewBox:"0 0 8 8",width:"8",height:"8",fill:"currentColor",children:h.jsx("path",{d:"M1 0l6 4-6 4z"})})}):h.jsx("span",{"aria-hidden":!0,"data-rtdb-caret-spacer":!0}),h.jsx("button",{type:"button","data-rtdb-key":!0,"aria-label":"Key name",onClick:()=>n==null?void 0:n(r),children:s}),d?null:h.jsxs(h.Fragment,{children:[h.jsx("span",{"aria-hidden":!0,"data-rtdb-sep":!0,children:":"}),h.jsx("button",{type:"button","data-rtdb-value":!0,"data-rtdb-type":ez(c),title:"Edit value",onClick:()=>{w(!0),k(!1)},children:XF(c)})]}),h.jsx("span",{"data-rtdb-actions":!0,children:_?h.jsxs("span",{"data-rtdb-confirm":!0,children:[h.jsxs("span",{"data-rtdb-confirm-label":!0,children:["Delete",d?" subtree":"","?"]}),h.jsx("button",{type:"button","data-rtdb-confirm-yes":!0,onClick:()=>void R(()=>e.remove(r),()=>k(!1)),children:"Delete"}),h.jsx("button",{type:"button","data-rtdb-confirm-no":!0,onClick:()=>k(!1),children:"Cancel"})]}):h.jsxs(h.Fragment,{children:[h.jsx("button",{type:"button","data-rtdb-action-add":!0,"aria-label":`Add child to ${s1(r)}`,title:"Add child",onClick:M,children:"+"}),h.jsx("button",{type:"button","data-rtdb-action-delete":!0,"aria-label":`Delete ${s1(r)}`,title:"Delete",onClick:()=>k(!0),children:"×"})]})})]}),I?h.jsx("p",{role:"alert","data-rtdb-error":!0,children:I}):null,v?h.jsx(i1,{initialType:n1(c),initialText:iz(c,n1(c)),submitLabel:"Save",onCancel:()=>w(!1),onSubmit:D=>R(()=>e.set(r,D),()=>w(!1))}):null,g?h.jsx(i1,{withKey:!0,initialType:"string",initialText:"",submitLabel:"Add",onCancel:()=>b(!1),onSubmit:(D,C)=>R(()=>e.set(My(r,C),D),()=>b(!1))}):null,F?h.jsxs("ul",{"data-rtdb-children":!0,children:[F.entries.map(([D])=>h.jsx("li",{children:h.jsx(Ek,{tree:t,api:e,onNavigate:n,path:My(r,D),label:D})},D)),F.hiddenCount>0?h.jsx("li",{"data-rtdb-show-more-item":!0,children:h.jsxs("button",{type:"button","data-rtdb-show-more":!0,onClick:()=>t.showMore(r),children:["Show more (",F.hiddenCount," hidden)"]})}):null]}):null]})}function s1(t){const e=Hi(t);return e.length===0?"root":e[e.length-1]}function i1({withKey:t,initialType:e,initialText:n,submitLabel:r,onSubmit:s,onCancel:o}){const c=A.useRef(null),d=A.useRef(null),[f,p]=A.useState(e),[g,b]=A.useState(null),v=_=>{var N,R;_.preventDefault();const k=((N=c.current)==null?void 0:N.value)??"";if(t){const M=az(k);if(M){b(M);return}}const I=oz(f,((R=d.current)==null?void 0:R.value)??"");if(!I.ok){b(I.error);return}b(null),s(I.value,t?k.trim():void 0)},w=_=>{_.key==="Escape"&&o()};return h.jsxs("form",{"data-rtdb-editor":!0,onSubmit:v,children:[t?h.jsx("input",{ref:c,"data-rtdb-editor-key":!0,"aria-label":"Child key",placeholder:"key",autoFocus:!0,onKeyDown:w,spellCheck:!1}):null,h.jsx("select",{"data-rtdb-editor-type":!0,"aria-label":"Value type",value:f,onChange:_=>p(_.currentTarget.value),onKeyDown:w,children:sz.map(_=>h.jsx("option",{value:_,children:_},_))}),f==="boolean"?h.jsxs("select",{ref:d,"data-rtdb-editor-value":!0,"aria-label":"Value",defaultValue:n.trim().toLowerCase()==="true"?"true":"false",onKeyDown:w,children:[h.jsx("option",{value:"true",children:"true"}),h.jsx("option",{value:"false",children:"false"})]}):h.jsx("input",{ref:d,"data-rtdb-editor-value":!0,"aria-label":"Value",placeholder:f==="json"?'{ "key": "value" }':"value",autoFocus:!t,defaultValue:n,onKeyDown:w,spellCheck:!1}),h.jsx("button",{type:"submit","data-rtdb-editor-save":!0,children:r}),h.jsx("button",{type:"button","data-rtdb-editor-cancel":!0,onClick:o,children:"Cancel"}),g?h.jsx("span",{role:"alert","data-rtdb-editor-error":!0,children:g}):null]})}function pz(){const t=rr(),e=t.status==="ready"?t.env.live:void 0;return h.jsxs("section",{className:"studio-surface grid gap-4","aria-labelledby":"rtdb-title",children:[h.jsxs("div",{className:"studio-surface__intro",children:[h.jsx("p",{className:"studio-surface__eyebrow",children:"RTDB"}),h.jsx("h1",{id:"rtdb-title",className:"studio-surface__title",children:"RTDB"}),h.jsx("p",{className:"studio-surface__copy",children:"Browse and edit RTDB data in the shared sandbox."})]}),e?h.jsx(yz,{live:e}):h.jsx(mz,{})]})}function mz(){return h.jsxs("div",{className:"rounded-md border border-dashed border-line bg-panel p-8 text-center",children:[h.jsx("span",{className:"rounded-full border border-line px-3 py-1 text-xs uppercase tracking-wide text-muted",children:"Shared worker pending"}),h.jsx("p",{className:"mx-auto mt-3 max-w-md text-sm leading-relaxed text-muted",children:"The RTDB viewer goes live once Studio connects to the shared sandbox worker."})]})}function yz({live:t}){const[e,n]=A.useState("/"),r=$g(Cg()),s=r?`${r}-sandbox`:"sandbox",o=A.useMemo(()=>({set:(d,f)=>t.setRtdbValue(d,f),remove:d=>t.deleteRtdbValue(d),subscribeValue:(d,f,p)=>t.subscribeRtdbValue(d,f,p)}),[t]),c=dz(o,e);return h.jsxs("div",{className:"rtdb",children:[h.jsx(fz,{className:"rtdb__pathbar",path:e,onNavigate:n,rootLabel:s,inputPrefix:s}),h.jsx(hz,{className:"rtdb__tree",tree:c,api:o,onNavigate:n,rootLabel:s})]})}function gz(t){if(t===null)return null;const e={collections:0,users:0,objects:0,rtdbKeys:0};for(const n of t)n.kind==="collection"?e.collections++:n.kind==="user"?e.users++:n.kind==="object"?e.objects++:n.kind==="rtdb-key"&&e.rtdbKeys++;return e}function Mu(t,e,n=`${e}s`){return`${t} ${t===1?e:n}`}function bz(t){if(t===null)return"measuring…";const e=[];return t.collections&&e.push(Mu(t.collections,"collection")),t.users&&e.push(Mu(t.users,"user")),t.objects&&e.push(Mu(t.objects,"file")),t.rtdbKeys&&e.push(Mu(t.rtdbKeys,"RTDB key")),e.length?e.join(" · "):"empty — no data yet"}function sf(){return{width:15,height:15,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:1.7,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0}}function vz(){return h.jsxs("svg",{...sf(),children:[h.jsx("path",{d:"M12 4v10"}),h.jsx("path",{d:"M8 10l4 4 4-4"}),h.jsx("path",{d:"M4 19h16"})]})}function wz(){return h.jsxs("svg",{...sf(),children:[h.jsx("path",{d:"M12 14V4"}),h.jsx("path",{d:"M8 8l4-4 4 4"}),h.jsx("path",{d:"M4 19h16"})]})}function xz(){return h.jsxs("svg",{...sf(),children:[h.jsx("circle",{cx:"7",cy:"6",r:"2.4"}),h.jsx("circle",{cx:"7",cy:"18",r:"2.4"}),h.jsx("circle",{cx:"17",cy:"8",r:"2.4"}),h.jsx("path",{d:"M7 8.4v7.2"}),h.jsx("path",{d:"M17 10.4c0 3-4 3.6-7 4.4"})]})}function Sz(){return h.jsxs("svg",{...sf(),children:[h.jsx("path",{d:"M4 5v5h5"}),h.jsx("path",{d:"M4.6 10a8 8 0 1 0 1.7-5.3"})]})}function Lu({glyph:t,name:e,caption:n,disabled:r,danger:s,onClick:o}){return h.jsxs("button",{type:"button",className:"studio-sandbox__action","data-danger":s?"true":void 0,disabled:r,onClick:o,children:[h.jsxs("span",{className:"studio-sandbox__action-top",children:[t,h.jsx("span",{className:"studio-sandbox__action-name",children:e})]}),h.jsx("span",{className:"studio-sandbox__action-caption",children:n})]})}function _z(){const t=w4(),e=S4(),n=_4(),r=E4(),s=Qd(),o=A.useRef(null),c=$g(Cg()),[d,f]=A.useState(!1),[p,g]=A.useState(!1),[b,v]=A.useState(!1),[w,_]=A.useState(!1),[k,I]=A.useState(""),N=uj(),{ensure:R}=N;A.useEffect(()=>R(),[R]);const M=gz(N.entries),F=bz(M),D=s.status==="ready"?s.payload.persist?"persisted to disk":"ephemeral":"in-page · resets on reload",C=async()=>{const x=await e();if(!x||typeof document>"u")return;const E=URL.createObjectURL(new Blob([x],{type:"application/json"})),O=document.createElement("a");O.href=E,O.download=`pyric-sandbox-${c||"export"}.json`,O.click(),URL.revokeObjectURL(E)},L=async x=>{var O;const E=(O=x.target.files)==null?void 0:O[0];if(x.target.value="",!!E&&!(typeof window<"u"&&!window.confirm("Import replaces all data in this sandbox. This cannot be undone. Continue?"))){g(!0);try{await n(await E.text())}finally{g(!1)}}},U=async()=>{v(!1),f(!0);try{await t()}finally{f(!1)}},H=async()=>{const x=k.trim();x&&(await r.save(x),I(""),_(!1))},z=async x=>{typeof window<"u"&&!window.confirm(`Switch to branch "${x}"? This replaces the current sandbox state.`)||await r.switchTo(x)},q=async x=>{typeof window<"u"&&!window.confirm(`Delete branch "${x}"?`)||await r.remove(x)};return h.jsxs("section",{className:"studio-surface studio-settings","aria-labelledby":"settings-title",children:[h.jsxs("div",{className:"studio-surface__intro",children:[h.jsx("p",{className:"studio-surface__eyebrow",children:"Settings"}),h.jsx("h1",{id:"settings-title",className:"studio-surface__title",children:"Configuration and maintenance."}),h.jsx("p",{className:"studio-surface__copy",children:"Global controls live here so service surfaces can stay focused on their primary work."})]}),h.jsx("div",{className:"studio-settings__grid",children:h.jsxs("section",{className:"studio-panel studio-settings__panel","aria-labelledby":"settings-sandbox-title",children:[h.jsx("h2",{id:"settings-sandbox-title",className:"studio-panel__title",children:"Sandbox"}),h.jsxs("div",{className:"studio-sandbox__live","aria-label":"Sandbox contents",children:[h.jsx("span",{className:"studio-sandbox__instance mono",children:c||"local"}),h.jsx("span",{className:"studio-sandbox__inventory",children:F}),h.jsx("span",{className:"studio-sandbox__persist",children:D})]}),h.jsxs("div",{className:"studio-sandbox__actions",children:[h.jsx(Lu,{glyph:h.jsx(vz,{}),name:"Export",caption:"Downloads all of this as one file.",onClick:()=>void C()}),h.jsx(Lu,{glyph:h.jsx(wz,{}),name:p?"Importing…":"Import",caption:"A chosen file replaces everything here.",disabled:p,onClick:()=>{var x;return(x=o.current)==null?void 0:x.click()}}),h.jsx(Lu,{glyph:h.jsx(xz,{}),name:"Save branch",caption:"Keeps a copy you can return to.",onClick:()=>_(x=>!x)}),h.jsx(Lu,{glyph:h.jsx(Sz,{}),name:d?"Resetting…":"Reset session",caption:"Everything returns to the seeded start.",disabled:d,danger:!0,onClick:()=>v(!0)})]}),h.jsx("input",{ref:o,type:"file",accept:"application/json,.json",className:"studio-settings__file",onChange:L}),w?h.jsxs("form",{className:"studio-sandbox__name-row",onSubmit:x=>{x.preventDefault(),H()},children:[h.jsx("input",{className:"studio-sandbox__name-input",type:"text",value:k,placeholder:"branch name","aria-label":"Branch name",autoFocus:!0,onChange:x=>I(x.target.value),onKeyDown:x=>{x.key==="Escape"&&(_(!1),I(""))}}),h.jsx("button",{type:"submit",className:"studio-button",disabled:!k.trim(),children:"Save"}),h.jsx("button",{type:"button",className:"studio-button",onClick:()=>{_(!1),I("")},children:"Cancel"})]}):null,b?h.jsxs("div",{className:"studio-sandbox__confirm",role:"alert",children:[h.jsx("span",{className:"studio-sandbox__confirm-copy",children:M&&F!=="empty — no data yet"?`This erases ${F}.`:"This erases everything in this sandbox."}),h.jsxs("span",{className:"studio-sandbox__confirm-actions",children:[h.jsx("button",{type:"button",className:"studio-button studio-button--danger",onClick:()=>void U(),children:"Erase and reseed"}),h.jsx("button",{type:"button",className:"studio-button",onClick:()=>v(!1),children:"Keep"})]})]}):null,r.branches.length>0?h.jsx("div",{className:"studio-settings__branches",children:r.branches.map(x=>h.jsxs("div",{className:"studio-settings__branch",children:[h.jsx("span",{className:"mono",children:x}),h.jsxs("span",{className:"studio-settings__branch-actions",children:[h.jsx("button",{type:"button",className:"studio-button",onClick:()=>void z(x),children:"Switch"}),h.jsx("button",{type:"button",className:"studio-button",onClick:()=>void q(x),children:"Delete"})]})]},x))}):h.jsx("p",{className:"studio-sandbox__branches-empty",children:"No branches yet — Save branch keeps this exact state to come back to."})]})})]})}function Uu(t){return t===null?"absent":t===void 0?"unknown":typeof t=="string"?t:typeof t=="number"||typeof t=="boolean"?String(t):JSON.stringify(t)}function Ez(t){const e=t.stateDiff;if(!e)return"No state evidence";if(!e.changed)return t.mutation.output!==void 0?"Read result captured":"No state change";if(e.before&&e.after&&typeof e.before=="object"&&typeof e.after=="object"&&!Array.isArray(e.before)&&!Array.isArray(e.after)){const n=e.before,r=e.after,o=[...new Set([...Object.keys(n),...Object.keys(r)])].filter(c=>JSON.stringify(n[c])!==JSON.stringify(r[c]));if(o.length>0&&o.length<=3)return o.map(c=>`${c}: ${Uu(n[c])} -> ${Uu(r[c])}`).join(", ")}return`${Uu(e.before)} -> ${Uu(e.after)}`}function Az(t){return t.results.map(e=>({id:e.probeId,service:e.control.operation.service,operation:`${e.mutation.operation.method} ${e.mutation.operation.path}`,actor:e.actorEvidence.uid??(e.actorEvidence.acquisition==="anonymous-request"?"anonymous":e.actorEvidence.actorId),expected:e.invariant.expected,observed:e.mutation.decision,classification:e.classification,impact:Ez(e),supported:e.qualification.supported}))}function jz(t){const e=t.mutation.events.find(c=>c.result==="allow"||c.result==="deny"||c.result==="unsupported");if(!e)return null;const n=e.result,r={id:e.id??`${t.probeId}-decision`,at:e.at??0,result:n,method:e.method??e.op??t.mutation.operation.method,service:e.service??t.mutation.operation.service,path:e.path??t.mutation.operation.path,auth:e.auth??null,reasons:e.reasons??[],origin:e.origin??"user",unsupported:n==="unsupported"};e.matchedRule&&(r.matchedRule=e.matchedRule),e.evaluatedRule&&(r.evaluatedRule=e.evaluatedRule),e.rules&&(r.rules=e.rules),e.resourceBefore&&(r.resourceBefore=e.resourceBefore);const s=e.request,o=(s==null?void 0:s.resourceData)??(s==null?void 0:s.data);return o!==void 0&&(r.resourceData=o),r}const kz="pyric:assurance-campaign",Cz="pyric-assurance-v1",Uy=new Set;let a1=!1,o1;function l1(t){for(const e of Uy)e(t)}function c1(t){return!!t&&typeof t=="object"&&t.schema==="pyric.assurance.visualization.v1"&&typeof t.campaignId=="string"}function Nz(){if(!(a1||typeof document>"u")){a1=!0,globalThis.addEventListener(kz,t=>{const e=t.detail;c1(e)&&l1(e)});try{o1=new BroadcastChannel(Cz),o1.onmessage=t=>{c1(t.data)&&l1(t.data)}}catch{}}}function Oz(t){return Nz(),Uy.add(t),()=>Uy.delete(t)}function fm(t){return{campaignId:"collaboration-local-v1",probeId:t.id,targetHash:"fnv1a32-7f4c911a",actorEvidence:{actorId:"member-b",acquisition:"password",reachability:"reachable",uid:"mallory"},invariant:{id:`${t.id}-invariant`,service:t.service,statement:t.statement,expected:"DENY",source:"declared",confidence:"authoritative"},mutationSpec:{dimension:t.service==="firestore"?"payload":"path",description:t.description,operation:t.mutation},control:{operation:t.control,decision:"ALLOW",events:[]},mutation:{operation:t.mutation,decision:"ALLOW",events:t.service==="firestore"?[{id:"req-firestore-owner-transfer",at:100,kind:"request",service:"firestore",method:"update",path:"rooms/r1",result:"allow",auth:{uid:"mallory",token:{}},reasons:["Rule #1 (update) -> ALLOW"],origin:"user",request:{resourceData:{ownerId:"mallory"}},resourceBefore:{exists:!0,data:t.before},matchedRule:{ruleIndex:0,operations:["update"]}}]:[]},stateDiff:{changed:!0,before:t.before,after:t.after},qualification:{engine:"pyric-local-sandboxes",supported:!0,requirements:[{id:`${t.service}.local-supported-subset`,supported:!0,reason:"This probe stays within the supported local evaluator subset."}]},classification:"local-counterexample"}}const Rz=[fm({id:"firestore-owner-transfer",service:"firestore",control:{service:"firestore",method:"update",path:"rooms/r1",data:{title:"Edited"}},mutation:{service:"firestore",method:"update",path:"rooms/r1",data:{ownerId:"mallory"}},statement:"A non-owner room member must not change ownerId.",description:"Changed only the updated field from title to ownerId.",before:{ownerId:"alice",title:"Original title"},after:{ownerId:"mallory",title:"Original title"}}),fm({id:"rtdb-other-role",service:"rtdb",control:{service:"rtdb",method:"set",path:"/rooms/r1/members/mallory/status",data:"online"},mutation:{service:"rtdb",method:"set",path:"/rooms/r1/members/alice/role",data:"online"},statement:"A member must not change another member's role.",description:"Changed only the target path from own status to another member role.",before:"owner",after:"online"}),fm({id:"storage-overwrite-owner",service:"storage",control:{service:"storage",method:"upload",path:"b/pyric-default/o/rooms/r1/mallory/note.json",dataBase64:"bWFsbG9yeQ==",customMetadata:{owner:"mallory"}},mutation:{service:"storage",method:"upload",path:"b/pyric-default/o/rooms/r1/alice/private.json",dataBase64:"bWFsbG9yeQ==",customMetadata:{owner:"mallory"}},statement:"A member must not overwrite an object owned by another actor.",description:"Changed only the target from a new own object to an existing other-owned object.",before:{text:"alice-secret",customMetadata:{owner:"alice"}},after:{text:"mallory",customMetadata:{owner:"mallory"}}})],Jz=Rz.map(t=>({...t,campaignId:"collaboration-local-v1-fixed",targetHash:"fnv1a32-a9f18f23",mutation:{...t.mutation,decision:"DENY",events:[]},stateDiff:void 0,classification:"no-counterexample"}));const $y="pyric:assurance:campaigns",Ak="pyric:assurance:campaign:";function Tz(t){return!!t&&typeof t=="object"&&t.schema==="pyric.assurance.visualization.v1"&&typeof t.campaignId=="string"}function Dz(){if(typeof sessionStorage>"u")return[];try{const t=JSON.parse(sessionStorage.getItem($y)??"[]");if(!Array.isArray(t))return[];const e=t.map(n=>sessionStorage.getItem(`${Ak}${String(n)}`)).filter(n=>!!n).map(n=>JSON.parse(n)).filter(Tz);return e.length,e}catch{return[]}}function Iz(t){if(!(typeof sessionStorage>"u"))try{const e=JSON.parse(sessionStorage.getItem($y)??"[]"),n=Array.isArray(e)?e.map(String):[];n.includes(t.campaignId)||n.push(t.campaignId),sessionStorage.setItem($y,JSON.stringify(n)),sessionStorage.setItem(`${Ak}${t.campaignId}`,JSON.stringify(t))}catch{}}function Mz(t,e){const n=t.findIndex(s=>s.campaignId===e.campaignId);if(n===-1)return[...t,e];const r=[...t];return r[n]=e,r}function Lz(){const[t,e]=A.useState(Dz);return A.useEffect(()=>{const r=Oz(s=>{Iz(s),e(o=>Mz(o,s))});return()=>{r()}},[]),t}function Uz(t,e){return t!==e?"assurance-verdict--mismatch":e==="ALLOW"?"assurance-verdict--allow":"assurance-verdict--deny"}function $z(t){return t.replaceAll("-"," ")}function u1({value:t}){return h.jsx("pre",{className:"assurance-evidence__json",children:JSON.stringify(t,null,2)})}function Bz(){return h.jsxs("section",{className:"assurance-empty","aria-labelledby":"assurance-empty-title",children:[h.jsx("p",{className:"assurance-surface__eyebrow",children:"Local authorization assurance"}),h.jsx("h1",{id:"assurance-empty-title",children:"No campaign in this Studio session"}),h.jsx("p",{children:"Campaigns appear here as the local assurance tools map actors, run controls, and test explicit security invariants."}),h.jsx("span",{className:"assurance-local-state",children:"Pyric sandboxes only | network off"})]})}function d1({attachment:t}){return t?h.jsxs("div",{className:"assurance-attachment","aria-label":"Attached sandbox inventory",children:[h.jsxs("span",{children:[h.jsx("strong",{children:t.source.origin}),"read-only clone"]}),h.jsxs("span",{children:[h.jsx("strong",{children:t.inventory.firestoreDocuments}),"Firestore docs"]}),h.jsxs("span",{children:[h.jsx("strong",{children:t.inventory.authUsers}),"Auth users"]}),h.jsxs("span",{children:[h.jsx("strong",{children:t.inventory.rtdbPresent?"present":"empty"}),"RTDB"]})]}):null}function qz({campaigns:t}){var M,F,D,C,L;const e=Lz(),n=t??e,r=Rr().query,[s,o]=A.useState(r.campaign??((M=n.find(U=>U.report))==null?void 0:M.campaignId)??((F=n[0])==null?void 0:F.campaignId)??""),c=n.find(U=>U.campaignId===s)??n[0],d=A.useMemo(()=>c!=null&&c.report?Az(c.report):[],[c]),[f,p]=A.useState(r.probe??((D=d[0])==null?void 0:D.id)??"");if(A.useEffect(()=>{!s&&n[0]&&o(n[0].campaignId)},[s,n]),A.useEffect(()=>{var U;d.some(H=>H.id===f)||p(((U=d[0])==null?void 0:U.id)??"")},[d,f]),!c)return h.jsx(Bz,{});const g=(C=c.context)==null?void 0:C.attachment,b=c.report;if(!b)return h.jsxs("section",{className:"assurance-empty","aria-labelledby":"assurance-mapped-title",children:[h.jsx("p",{className:"assurance-surface__eyebrow",children:c.campaignId}),h.jsx("h1",{id:"assurance-mapped-title",children:"Campaign mapped, awaiting its first run"}),h.jsxs("p",{children:[c.observations.length," known-good operation(s) and"," ",c.probes.length," probe(s) are available."]}),h.jsx(d1,{attachment:g}),g!=null&&g.coverageGaps.length?h.jsx("ul",{className:"assurance-coverage-gaps","aria-label":"Attachment coverage gaps",children:g.coverageGaps.map(U=>h.jsxs("li",{children:[h.jsx("code",{children:U.service}),U.reason]},U.code))}):null,h.jsx("span",{className:"assurance-local-state",children:"Pyric sandboxes only | network off"})]});const v=d.find(U=>U.id===f)??d[0],w=b.results.find(U=>U.probeId===(v==null?void 0:v.id)),_=w?jz(w):null,k=(L=c.verifications)==null?void 0:L.at(-1),I=k!==void 0&&k.summary.controlsPassed===k.summary.probes&&k.summary.noCounterexamples===k.summary.probes&&k.summary.localCounterexamples===0&&k.summary.engineGaps===0&&k.summary.invalidProbes===0;function N(U){var q,x;o(U);const H=n.find(E=>E.campaignId===U),z=((x=(q=H==null?void 0:H.report)==null?void 0:q.results[0])==null?void 0:x.probeId)??"";p(z),xd({tab:"assurance",query:{campaign:U,probe:z||void 0}})}function R(U){p(U.id),xd({tab:"assurance",query:{campaign:c.campaignId,probe:U.id}})}return h.jsxs("section",{className:"assurance-surface","aria-labelledby":"assurance-title",children:[h.jsxs("header",{className:"assurance-surface__header",children:[h.jsxs("div",{children:[h.jsx("p",{className:"assurance-surface__eyebrow",children:"Local authorization assurance"}),h.jsx("h1",{id:"assurance-title",children:c.campaignId})]}),h.jsxs("div",{className:"assurance-surface__controls",children:[n.length>1?h.jsxs("label",{children:[h.jsx("span",{children:"Campaign"}),h.jsx("select",{value:c.campaignId,onChange:U=>N(U.target.value),children:n.map(U=>h.jsx("option",{value:U.campaignId,children:U.campaignId},U.campaignId))})]}):null,h.jsx("span",{className:"assurance-local-state",children:"Pyric sandboxes only | network off"})]})]}),h.jsx(d1,{attachment:g}),h.jsxs("div",{className:"assurance-summary","aria-label":"Campaign summary",children:[h.jsxs("div",{children:[h.jsx("span",{children:"Controls"}),h.jsxs("strong",{children:[b.summary.controlsPassed,"/",b.summary.probes]})]}),h.jsxs("div",{children:[h.jsx("span",{children:"Counterexamples"}),h.jsx("strong",{children:b.summary.localCounterexamples})]}),h.jsxs("div",{children:[h.jsx("span",{children:"Candidate signals"}),h.jsx("strong",{children:b.summary.candidateSignals})]}),h.jsxs("div",{children:[h.jsx("span",{children:"Engine gaps"}),h.jsx("strong",{children:b.summary.engineGaps})]}),h.jsxs("div",{children:[h.jsx("span",{children:"Coverage gaps"}),h.jsx("strong",{children:(g==null?void 0:g.coverageGaps.length)??0})]})]}),k?h.jsxs("div",{className:`assurance-verification-band assurance-verification-band--${I?"passed":"failed"}`,role:"status",children:[h.jsx("strong",{children:I?"Candidate rules verified":"Candidate rules need review"}),h.jsxs("span",{children:[k.summary.controlsPassed,"/",k.summary.probes," ","controls preserved"," | ",k.summary.noCounterexamples,"/",k.summary.probes," negative cases denied"]}),h.jsx("code",{children:k.campaignId})]}):null,g!=null&&g.coverageGaps.length?h.jsxs("div",{className:"assurance-coverage-band",children:[h.jsxs("strong",{children:[g.coverageGaps.length," attachment gap(s)"]}),h.jsx("span",{children:g.coverageGaps.map(U=>`${U.service}: ${U.reason}`).join(" ")})]}):null,h.jsxs("div",{className:"assurance-workspace",children:[h.jsxs("section",{className:"assurance-matrix","aria-labelledby":"assurance-matrix-title",children:[h.jsxs("div",{className:"assurance-section-heading",children:[h.jsx("h2",{id:"assurance-matrix-title",children:"Expected and observed access"}),h.jsx("span",{children:b.targetHash})]}),h.jsxs("div",{className:"assurance-table",role:"table",children:[h.jsxs("div",{className:"assurance-table__header",role:"row",children:[h.jsx("span",{role:"columnheader",children:"Operation"}),h.jsx("span",{role:"columnheader",children:"Actor"}),h.jsx("span",{role:"columnheader",children:"Expected"}),h.jsx("span",{role:"columnheader",children:"Observed"}),h.jsx("span",{role:"columnheader",children:"Impact"})]}),d.map(U=>h.jsxs("button",{type:"button",className:"assurance-table__row","aria-pressed":U.id===(v==null?void 0:v.id),onClick:()=>R(U),role:"row",children:[h.jsxs("span",{role:"cell",children:[h.jsx("small",{children:U.service}),U.operation]}),h.jsx("span",{role:"cell",children:U.actor}),h.jsx("span",{role:"cell",className:`assurance-verdict ${U.expected==="ALLOW"?"assurance-verdict--allow":"assurance-verdict--deny"}`,children:U.expected}),h.jsx("span",{role:"cell",className:`assurance-verdict ${Uz(U.expected,U.observed)}`,children:U.observed}),h.jsx("span",{role:"cell",children:U.impact})]},U.id))]})]}),w?h.jsxs("aside",{className:"assurance-inspector","aria-labelledby":"assurance-inspector-title",children:[h.jsxs("div",{className:"assurance-section-heading",children:[h.jsxs("div",{children:[h.jsx("span",{className:`assurance-classification assurance-classification--${w.classification}`,children:$z(w.classification)}),h.jsx("h2",{id:"assurance-inspector-title",children:w.probeId})]}),h.jsx("span",{children:w.actorEvidence.reachability})]}),h.jsxs("dl",{className:"assurance-facts",children:[h.jsxs("div",{children:[h.jsx("dt",{children:"Invariant"}),h.jsx("dd",{children:w.invariant.statement})]}),h.jsxs("div",{children:[h.jsx("dt",{children:"Mutation"}),h.jsx("dd",{children:w.mutationSpec.description})]}),h.jsxs("div",{children:[h.jsx("dt",{children:"Actor"}),h.jsxs("dd",{children:[w.actorEvidence.uid??w.actorEvidence.actorId," ","via ",w.actorEvidence.acquisition]})]}),h.jsxs("div",{children:[h.jsx("dt",{children:"Fidelity"}),h.jsx("dd",{children:w.qualification.supported?"Supported for this probe":"Engine gap"})]})]}),w.qualification.requirements.some(U=>!U.supported)?h.jsx("ul",{className:"assurance-gaps",children:w.qualification.requirements.filter(U=>!U.supported).map(U=>h.jsxs("li",{children:[h.jsx("code",{children:U.id}),U.reason]},U.id))}):null,w.stateDiff?h.jsxs("section",{className:"assurance-evidence","aria-labelledby":"assurance-state-title",children:[h.jsx("h3",{id:"assurance-state-title",children:"State evidence"}),h.jsxs("div",{className:"assurance-evidence__diff",children:[h.jsxs("div",{children:[h.jsx("span",{children:"Before"}),h.jsx(u1,{value:w.stateDiff.before})]}),h.jsxs("div",{children:[h.jsx("span",{children:"After"}),h.jsx(u1,{value:w.stateDiff.after})]})]})]}):null,_?h.jsxs("section",{className:"assurance-rule-decision","aria-labelledby":"assurance-rule-title",children:[h.jsx("h3",{id:"assurance-rule-title",children:"Rule decision"}),h.jsx(dk,{denial:_})]}):h.jsx("p",{className:"assurance-no-decision",children:"This service recorded operation and state evidence but no canonical rule-decision event."})]}):null]})]})}function jk(){const t="/__pyric/ui/";return`${t.endsWith("/")?t:`${t}/`}docs`}function Fz(){const[t,e]=A.useState(!1);return A.useEffect(()=>{let n=!0;return fetch(`${jk()}/index.json`,{method:"HEAD"}).then(r=>{const s=r.headers.get("content-type")??"";n&&r.ok&&s.includes("json")&&e(!0)}).catch(()=>{}),()=>{n=!1}},[]),t}function zz({id:t}){const e=S3(t),n=cs(),r=[`route #${e.id}`];return n.status==="ready"?(r.push(`events: ${n.events.length}`),r.push("dev-seed: ready")):n.status==="pending"?r.push("dev-seed: seeding…"):n.status==="error"?r.push("dev-seed: error"):r.push("dev-seed: off"),h.jsxs("section",{className:"studio__placeholder","aria-labelledby":`route-${e.id}`,children:[h.jsx("p",{className:"studio__placeholder-eyebrow",children:"Surface"}),h.jsx("h2",{id:`route-${e.id}`,className:"studio__placeholder-title",children:e.label}),h.jsx("p",{className:"studio__placeholder-blurb",children:e.description}),h.jsx("div",{className:"studio__placeholder-meta",children:r.map(s=>h.jsx("span",{children:s},s))})]})}function Pz({id:t}){switch(t){case"home":return h.jsx(JF,{});case"firestore":return h.jsx(Mq,{});case"auth":return h.jsx(zq,{});case"storage":return h.jsx(Lq,{});case"rtdb":return h.jsx(pz,{});case"traffic":return h.jsx(BF,{});case"assurance":return h.jsx(qz,{});case"settings":return h.jsx(_z,{});default:return h.jsx(zz,{id:t})}}function Vz(){const[t,e]=m3(x3,"home"),n=d=>e(d),[r,s]=A.useState(!1),o=Fz(),c=t==="home";return A.useEffect(()=>{const d=f=>{if(b3(f)){if(r){f.preventDefault(),s(!1);return}if(c){g3()&&f.preventDefault();return}f.preventDefault(),s(!0)}};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[c,r]),A.useEffect(()=>{c&&s(!1)},[c]),A.useEffect(()=>{var d;(d=document.querySelector('.studio__nav [aria-current="page"]'))==null||d.scrollIntoView({block:"nearest",inline:"center"})},[t]),h.jsxs("div",{className:"studio","data-surface":t,children:[h.jsx("header",{className:"studio__bar",children:h.jsxs("div",{className:"studio__bar-inner",children:[h.jsx("span",{className:"studio__brand","aria-label":"Pyric Studio",children:"Pyric"}),h.jsxs("nav",{className:"studio__nav","aria-label":"Studio tabs",children:[Pi.map(d=>h.jsx("button",{type:"button",className:"studio__nav-tab","aria-current":d.id===t?"page":void 0,onClick:()=>n(d.id),children:d.label},d.id)),o?h.jsx("a",{className:"studio__nav-tab",href:jk(),children:"Docs"}):null]}),h.jsx(H4,{})]})}),h.jsx("main",{className:"studio__content","data-surface":t,children:h.jsx("div",{className:"studio__surface-slot","data-active":"true",children:h.jsx(Pz,{id:t})})}),r?h.jsx(T4,{onClose:()=>s(!1)}):null]})}function Hz(){return h.jsx(u3,{children:h.jsx(fO,{children:h.jsx(i3,{mode:"local",children:h.jsx(Vz,{})})})})}const kk=document.getElementById("root");if(!kk)throw new Error("Pyric Studio: #root element not found");lO.createRoot(kk).render(h.jsx(A.StrictMode,{children:h.jsx(Hz,{})}));export{Or as G,$n as T,Pl as a,Zz as b,lr as c,ur as d,Qz as e,Y3 as f,A as g,h as j,Hl as r,Wz as s,I6 as u};