@pyric/cli 0.1.0-alpha.17 → 0.1.0-alpha.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (171) hide show
  1. package/README.md +29 -3
  2. package/dist/bridge/server/bridge.d.ts.map +1 -1
  3. package/dist/bridge/server/bridge.js +4 -2
  4. package/dist/bridge/server/bridge.js.map +1 -1
  5. package/dist/bridge/server/peer.d.ts.map +1 -1
  6. package/dist/bridge/server/peer.js +1 -0
  7. package/dist/bridge/server/peer.js.map +1 -1
  8. package/dist/cli/serve.d.ts.map +1 -1
  9. package/dist/cli/serve.js +1 -0
  10. package/dist/cli/serve.js.map +1 -1
  11. package/dist/conformance/.generated/conformance-docs.d.ts.map +1 -1
  12. package/dist/conformance/.generated/conformance-docs.js +1 -1
  13. package/dist/conformance/.generated/conformance-docs.js.map +1 -1
  14. package/dist/functions-rtdb/child.d.ts +1 -0
  15. package/dist/functions-rtdb/child.d.ts.map +1 -1
  16. package/dist/functions-rtdb/child.js +11 -1
  17. package/dist/functions-rtdb/child.js.map +1 -1
  18. package/dist/functions-rtdb/development-runtime.d.ts +1 -0
  19. package/dist/functions-rtdb/development-runtime.d.ts.map +1 -1
  20. package/dist/functions-rtdb/development-runtime.js +1 -0
  21. package/dist/functions-rtdb/development-runtime.js.map +1 -1
  22. package/dist/remote/index.d.ts.map +1 -1
  23. package/dist/remote/index.js +5 -3
  24. package/dist/remote/index.js.map +1 -1
  25. package/dist/serve/runtime/chip.d.ts.map +1 -1
  26. package/dist/serve/runtime/chip.js +24 -3
  27. package/dist/serve/runtime/chip.js.map +1 -1
  28. package/dist/serve/runtime/status.d.ts +1 -0
  29. package/dist/serve/runtime/status.d.ts.map +1 -1
  30. package/dist/serve/runtime/status.js +71 -13
  31. package/dist/serve/runtime/status.js.map +1 -1
  32. package/dist/serve/site-ui/_astro/_slug_.C6QfVOxJ.css +1 -0
  33. package/dist/serve/site-ui/_astro/{app.bnmVTkIY.js → app.B7pBzz5N.js} +7 -7
  34. package/dist/serve/site-ui/_astro/app.boex5SnQ.js +1 -0
  35. package/dist/serve/site-ui/_astro/{chess-showcase.kC8dXLKY.js → chess-showcase.DDqE-QGe.js} +1 -1
  36. package/dist/serve/site-ui/_astro/{example-runtime.D79PnoSk.js → example-runtime.B0byNQOl.js} +1 -1
  37. package/dist/serve/site-ui/_astro/index.uwPvjH_1.js +1 -0
  38. package/dist/serve/site-ui/_astro/{reads.BYBRLbsE.js → reads.Dh3z0fJy.js} +1 -1
  39. package/dist/serve/site-ui/_astro/{sandbox-controls.C9Aaazt8.js → sandbox-controls.C2IqtoSw.js} +3 -3
  40. package/dist/serve/site-ui/_astro/{seed.DANAIyRw.js → seed.CCmj00su.js} +1 -1
  41. package/dist/serve/site-ui/auth/index.html +1 -1
  42. package/dist/serve/site-ui/docs/_rhythm/index.html +1 -1
  43. package/dist/serve/site-ui/docs/agent/set-up-your-agent/index.html +48 -13
  44. package/dist/serve/site-ui/docs/agent/set-up-your-agent.md +74 -11
  45. package/dist/serve/site-ui/docs/agent/watch-and-review/index.html +1 -1
  46. package/dist/serve/site-ui/docs/agent/work-with-an-agent/index.html +1 -1
  47. package/dist/serve/site-ui/docs/ai-compat/index.html +1 -1
  48. package/dist/serve/site-ui/docs/api-reference/index.html +1 -1
  49. package/dist/serve/site-ui/docs/app-compat/index.html +1 -1
  50. package/dist/serve/site-ui/docs/auth-compat/index.html +1 -1
  51. package/dist/serve/site-ui/docs/build/ai-logic/index.html +19 -2
  52. package/dist/serve/site-ui/docs/build/ai-logic.md +28 -0
  53. package/dist/serve/site-ui/docs/build/authentication/index.html +1 -1
  54. package/dist/serve/site-ui/docs/build/cloud-firestore/index.html +1 -1
  55. package/dist/serve/site-ui/docs/build/cloud-messaging/index.html +1 -1
  56. package/dist/serve/site-ui/docs/build/cloud-storage/index.html +1 -1
  57. package/dist/serve/site-ui/docs/build/realtime-database/index.html +1 -1
  58. package/dist/serve/site-ui/docs/conformance-scores/index.html +22 -7
  59. package/dist/serve/site-ui/docs/conformance-scores.md +20 -5
  60. package/dist/serve/site-ui/docs/create-pyric-reference-api/index.html +1 -1
  61. package/dist/serve/site-ui/docs/database-compat/index.html +1 -1
  62. package/dist/serve/site-ui/docs/examples/chess/index.html +2 -2
  63. package/dist/serve/site-ui/docs/examples/index.html +1 -1
  64. package/dist/serve/site-ui/docs/firestore-compat/index.html +1 -1
  65. package/dist/serve/site-ui/docs/functions-rtdb-compat/index.html +1 -1
  66. package/dist/serve/site-ui/docs/get-started/how-the-swap-works/index.html +1 -1
  67. package/dist/serve/site-ui/docs/get-started/nextjs/index.html +1 -1
  68. package/dist/serve/site-ui/docs/get-started/start-building/index.html +17 -5
  69. package/dist/serve/site-ui/docs/get-started/start-building.md +29 -3
  70. package/dist/serve/site-ui/docs/get-started/vite/index.html +1 -1
  71. package/dist/serve/site-ui/docs/index.json +43 -8
  72. package/dist/serve/site-ui/docs/messaging-compat/index.html +1 -1
  73. package/dist/serve/site-ui/docs/observe/resolve-runtime-status/index.html +1 -1
  74. package/dist/serve/site-ui/docs/observe/see-whats-happening/index.html +1 -1
  75. package/dist/serve/site-ui/docs/observe/shape-your-data/index.html +1 -1
  76. package/dist/serve/site-ui/docs/overview/index.html +1 -1
  77. package/dist/serve/site-ui/docs/pyric-admin-app-reference-api/index.html +1 -1
  78. package/dist/serve/site-ui/docs/pyric-admin-auth-reference-api/index.html +1 -1
  79. package/dist/serve/site-ui/docs/pyric-admin-database-reference-api/index.html +1 -1
  80. package/dist/serve/site-ui/docs/pyric-admin-firestore-reference-api/index.html +1 -1
  81. package/dist/serve/site-ui/docs/pyric-admin-messaging-reference-api/index.html +1 -1
  82. package/dist/serve/site-ui/docs/pyric-admin-storage-reference-api/index.html +1 -1
  83. package/dist/serve/site-ui/docs/pyric-ai-reference-api/index.html +1 -1
  84. package/dist/serve/site-ui/docs/pyric-ai-scripting-reference-api/index.html +1 -1
  85. package/dist/serve/site-ui/docs/pyric-app-reference-api/index.html +1 -1
  86. package/dist/serve/site-ui/docs/pyric-auth-reference-api/index.html +1 -1
  87. package/dist/serve/site-ui/docs/pyric-cli-assurance-browser-reference-api/index.html +1 -1
  88. package/dist/serve/site-ui/docs/pyric-cli-assurance-reference-api/index.html +1 -1
  89. package/dist/serve/site-ui/docs/pyric-cli-bridge-client-reference-api/index.html +1 -1
  90. package/dist/serve/site-ui/docs/pyric-cli-bridge-reference-api/index.html +1 -1
  91. package/dist/serve/site-ui/docs/pyric-cli-conformance-browser-reference-api/index.html +1 -1
  92. package/dist/serve/site-ui/docs/pyric-cli-conformance-docs-reference-api/index.html +1 -1
  93. package/dist/serve/site-ui/docs/pyric-cli-conformance-reference-api/index.html +1 -1
  94. package/dist/serve/site-ui/docs/pyric-cli-credentials-node-reference-api/index.html +1 -1
  95. package/dist/serve/site-ui/docs/pyric-cli-discover-reference-api/index.html +1 -1
  96. package/dist/serve/site-ui/docs/pyric-cli-next-reference-api/index.html +1 -1
  97. package/dist/serve/site-ui/docs/pyric-cli-register-app-bridge-reference-api/index.html +1 -1
  98. package/dist/serve/site-ui/docs/pyric-cli-register-reference-api/index.html +1 -1
  99. package/dist/serve/site-ui/docs/pyric-cli-remote-reference-api/index.html +1 -1
  100. package/dist/serve/site-ui/docs/pyric-cli-serve-worker-reference-api/index.html +1 -1
  101. package/dist/serve/site-ui/docs/pyric-cli-verify-reference-api/index.html +1 -1
  102. package/dist/serve/site-ui/docs/pyric-cli-vite-reference-api/index.html +1 -1
  103. package/dist/serve/site-ui/docs/pyric-database-reference-api/index.html +1 -1
  104. package/dist/serve/site-ui/docs/pyric-firestore-reference-api/index.html +1 -1
  105. package/dist/serve/site-ui/docs/pyric-messaging-reference-api/index.html +1 -1
  106. package/dist/serve/site-ui/docs/pyric-messaging-sw-reference-api/index.html +1 -1
  107. package/dist/serve/site-ui/docs/pyric-rules-reference-api/index.html +1 -1
  108. package/dist/serve/site-ui/docs/pyric-sandbox-database-reference-api/index.html +1 -1
  109. package/dist/serve/site-ui/docs/pyric-sandbox-firestore-reference-api/index.html +1 -1
  110. package/dist/serve/site-ui/docs/pyric-sandbox-reference-api/index.html +1 -1
  111. package/dist/serve/site-ui/docs/pyric-storage-reference-api/index.html +1 -1
  112. package/dist/serve/site-ui/docs/pyric-ui-agents-reference-api/index.html +1 -1
  113. package/dist/serve/site-ui/docs/pyric-ui-auth-hooks-reference-api/index.html +1 -1
  114. package/dist/serve/site-ui/docs/pyric-ui-auth-reference-api/index.html +1 -1
  115. package/dist/serve/site-ui/docs/pyric-ui-events-hooks-reference-api/index.html +1 -1
  116. package/dist/serve/site-ui/docs/pyric-ui-events-reference-api/index.html +1 -1
  117. package/dist/serve/site-ui/docs/pyric-ui-firestore-hooks-reference-api/index.html +1 -1
  118. package/dist/serve/site-ui/docs/pyric-ui-firestore-reference-api/index.html +1 -1
  119. package/dist/serve/site-ui/docs/pyric-ui-primitives-reference-api/index.html +1 -1
  120. package/dist/serve/site-ui/docs/pyric-ui-rtdb-reference-api/index.html +1 -1
  121. package/dist/serve/site-ui/docs/pyric-ui-rules-hooks-reference-api/index.html +1 -1
  122. package/dist/serve/site-ui/docs/pyric-ui-rules-reference-api/index.html +1 -10
  123. package/dist/serve/site-ui/docs/pyric-ui-rules-reference-api.md +0 -9
  124. package/dist/serve/site-ui/docs/pyric-ui-storage-hooks-reference-api/index.html +1 -1
  125. package/dist/serve/site-ui/docs/pyric-ui-storage-reference-api/index.html +1 -1
  126. package/dist/serve/site-ui/docs/pyric-ui-traffic-hooks-reference-api/index.html +1 -1
  127. package/dist/serve/site-ui/docs/pyric-ui-traffic-reference-api/index.html +1 -1
  128. package/dist/serve/site-ui/docs/rules-compat/index.html +1 -1
  129. package/dist/serve/site-ui/docs/secure/audit-your-rules/index.html +1 -1
  130. package/dist/serve/site-ui/docs/secure/firestore-rules-limits/index.html +1 -1
  131. package/dist/serve/site-ui/docs/secure/read-a-denial/index.html +1 -1
  132. package/dist/serve/site-ui/docs/secure/rtdb-rules-in-typescript/index.html +1 -1
  133. package/dist/serve/site-ui/docs/secure/rules-standard-library/index.html +1 -1
  134. package/dist/serve/site-ui/docs/secure/secure-it-with-rules/index.html +1 -1
  135. package/dist/serve/site-ui/docs/secure/simulate-and-lint/index.html +1 -1
  136. package/dist/serve/site-ui/docs/secure/write-a-rules-test-suite/index.html +1 -1
  137. package/dist/serve/site-ui/docs/ship/ship-to-production/index.html +1 -1
  138. package/dist/serve/site-ui/docs/ship/test-in-node/index.html +1 -1
  139. package/dist/serve/site-ui/docs/storage-compat/index.html +1 -1
  140. package/dist/serve/site-ui/docs/trust/how-we-know-it-matches-firebase/index.html +1 -1
  141. package/dist/serve/site-ui/docs/trust/rules-standard-library/index.html +1 -1
  142. package/dist/serve/site-ui/docs/trust/storage-rules-stdlib-research/index.html +1 -1
  143. package/dist/serve/site-ui/docs/trust/versioning-and-compatibility/index.html +1 -1
  144. package/dist/serve/site-ui/docs/tutorial/index.html +2 -1
  145. package/dist/serve/site-ui/docs/tutorial.md +2 -0
  146. package/dist/serve/site-ui/examples/chess/index.html +1 -1
  147. package/dist/serve/site-ui/examples/firestore-first-write/index.html +1 -1
  148. package/dist/serve/site-ui/firestore/index.html +1 -1
  149. package/dist/serve/site-ui/index.html +1 -1
  150. package/dist/serve/site-ui/llms.txt +2 -2
  151. package/dist/serve/site-ui/rtdb/index.html +1 -1
  152. package/dist/serve/site-ui/settings/index.html +1 -1
  153. package/dist/serve/site-ui/storage/index.html +1 -1
  154. package/dist/serve/site-ui/traffic/index.html +1 -1
  155. package/dist/serve/vite-functions-development.d.ts.map +1 -1
  156. package/dist/serve/vite-functions-development.js +1 -0
  157. package/dist/serve/vite-functions-development.js.map +1 -1
  158. package/package.json +4 -4
  159. package/src/bridge/server/bridge.ts +5 -2
  160. package/src/bridge/server/peer.ts +2 -1
  161. package/src/cli/serve.ts +1 -0
  162. package/src/conformance/.generated/conformance-docs.ts +1 -1
  163. package/src/functions-rtdb/child.ts +12 -1
  164. package/src/functions-rtdb/development-runtime.ts +2 -0
  165. package/src/remote/index.ts +7 -5
  166. package/src/serve/runtime/chip.ts +24 -3
  167. package/src/serve/runtime/status.ts +76 -13
  168. package/src/serve/vite-functions-development.ts +1 -0
  169. package/dist/serve/site-ui/_astro/_slug_.BoKXYrnu.css +0 -1
  170. package/dist/serve/site-ui/_astro/app.t6u-adB_.js +0 -1
  171. package/dist/serve/site-ui/_astro/index.DzVde04M.js +0 -1
@@ -1,4 +1,4 @@
1
- import{j as o}from"./jsx-runtime.D_zvdyIk.js";import{g as p,d as f,b as l,e as g,s as h,a as _}from"./sandbox-controls.C9Aaazt8.js";import{g as k}from"./reads.BYBRLbsE.js";import{r as c}from"./index.DBy5LfQW.js";function S(n){if(n.presentation==="showcase")throw new Error(`Pyric showcase '${n.header}' cannot use the generic example runtime`)}const b={header:"Play chess against Security Rules",subLabel:"Firestore Security Rules · Isolated browser sandbox",summary:"Move a piece; Pyric commits the new board or denies the write.",docsPath:"/docs/examples/chess/",service:"firestore",presentation:"showcase",renderer:"chess"};async function w({sandbox:n}){const t=p(n.withAuth({uid:"ada"})),e=f(t,"notes","first");return await l(e,{title:"The sandbox is local",ownerId:"ada"}),(await k(e)).data()}const x={header:"Write to an isolated Firestore sandbox",subLabel:"Cloud Firestore · Browser sandbox",summary:"Run a Firestore write and read without starting a SharedWorker or touching another example.",docsPath:"/docs/build/cloud-firestore/",service:"firestore",firestore:{rules:`
1
+ import{j as o}from"./jsx-runtime.D_zvdyIk.js";import{g as p,d as f,b as l,e as g,s as h,a as _}from"./sandbox-controls.C2IqtoSw.js";import{g as k}from"./reads.Dh3z0fJy.js";import{r as c}from"./index.DBy5LfQW.js";function S(n){if(n.presentation==="showcase")throw new Error(`Pyric showcase '${n.header}' cannot use the generic example runtime`)}const b={header:"Play chess against Security Rules",subLabel:"Firestore Security Rules · Isolated browser sandbox",summary:"Move a piece; Pyric commits the new board or denies the write.",docsPath:"/docs/examples/chess/",service:"firestore",presentation:"showcase",renderer:"chess"};async function w({sandbox:n}){const t=p(n.withAuth({uid:"ada"})),e=f(t,"notes","first");return await l(e,{title:"The sandbox is local",ownerId:"ada"}),(await k(e)).data()}const x={header:"Write to an isolated Firestore sandbox",subLabel:"Cloud Firestore · Browser sandbox",summary:"Run a Firestore write and read without starting a SharedWorker or touching another example.",docsPath:"/docs/build/cloud-firestore/",service:"firestore",firestore:{rules:`
2
2
  rules_version = '2';
3
3
  service cloud.firestore {
4
4
  match /databases/{database}/documents {
@@ -0,0 +1 @@
1
+ import{e as o}from"./sandbox-controls.C2IqtoSw.js";function t(i={}){return o()}export{t as i};
@@ -1 +1 @@
1
- import{A as h,ac as u,ad as g,p as y,ae as m,w as q,af as j,C,z as M,B as b,ag as W,t as D,ah as k,ai as z}from"./sandbox-controls.C9Aaazt8.js";const O=new WeakMap;function B(e){return O.get(e)?.raw??e}const E=new WeakMap,x=new WeakMap;function l(e,a,t,n,r){O.set(e,{target:t,path:a.ref.path,kind:r,converter:n,raw:a})}function F(e,a){const t=b(e),n=b(a);return t.isStructurallyEqual?.(n)??t===n}function I(e,a,t,n){const r=e,s=(x.get(r)??[]).filter(c=>c.query.deref()!==void 0),o=s.find(c=>{const i=c.query.deref();return i!==void 0&&F(i,a)});if(o!==void 0){const c=T(o.docs,t)&&o.metadata.fromCache===n.fromCache&&o.metadata.hasPendingWrites===n.hasPendingWrites;return o.docs=t,o.metadata=n,c?"settled":"initial"}return s.push({query:new WeakRef(a),docs:t,metadata:n}),x.set(r,s),"initial"}function T(e,a){return e.length===a.length&&e.every((t,n)=>{const r=a[n];return t.path===r.path&&W(t.data,r.data)})}function w(e,a,t,n,r){const s=a,o=d=>({path:d.ref?.path??"",data:M(d.data?.(),t)}),c=Object.freeze((s.docs??[]).map(o)),i=Object.freeze((s.docChanges?.()??[]).map(d=>({...o(d.doc??{}),type:d.type??"",oldIndex:d.oldIndex??-1,newIndex:d.newIndex??-1}))),f=Object.freeze({fromCache:s.metadata?.fromCache===!0,hasPendingWrites:s.metadata?.hasPendingWrites===!0});E.set(e,{target:t,query:n,converter:y(n)??null,source:r,...r==="read"?{readPhase:I(t,n,c,f)}:{},metadata:f,docs:c,changes:i})}function P(e,a){const t=e,n=t.data.bind(e);return Object.defineProperty(t,"data",{value:()=>g(n()),configurable:!0,writable:!0}),a&&t.ref?.path&&Object.defineProperty(t,"metadata",{value:h(a).snapshotMetadata(t.ref.path),configurable:!0}),e}function v(e,a,t,n){const r={id:e.id,ref:e.ref,exists:e.exists,metadata:h(t).snapshotMetadata(e.ref.path),data:()=>{if(!(typeof e.exists=="function"?e.exists():e.exists))return;const o=g(e.data()),c={id:e.id,ref:e.ref,exists:!0,metadata:h(t).snapshotMetadata(e.ref.path),data:()=>o};return a.fromFirestore(c)}};return u(r,t),u(e.ref,t),p(e.ref,t),l(r,e,t,a,n),r}function Q(e,a){if(!e||typeof e!="object")return e;u(e,a);const t=e;if(t.ref&&(u(t.ref,a),p(t.ref,a)),S(t),Array.isArray(t.docs))for(const n of t.docs)n&&(u(n,a),l(n,n,a,null,"query-child")),n?.ref&&(u(n.ref,a),p(n.ref,a)),n&&S(n);else t.ref&&l(e,e,a,null,"document");return e}function p(e,a){if(typeof e.path!="string"||e.path.length===0)return;const t=e.path;try{const n=m.get(e),r=n??q(a).doc(t);n===void 0&&m.set(e,r),j(e,t,a,r),a.kind==="sandbox-live"&&C.set(r,s=>s.doc(t))}catch{}}function S(e){const a=e.exists;if(typeof a=="function")return;const t=a===!0;try{Object.defineProperty(e,"exists",{value:()=>t,writable:!0,configurable:!0,enumerable:!0})}catch{}}async function U(e){const a=D(e),t=h(a);t.markStarted();const n=y(e),r=await k(a,e).get();return t.cachePath(e.path),n?v(r,n,a,"document"):(Q(r,a),P(r,a))}async function K(e){const a=D(e),t=h(a);t.markStarted();const n=y(e),r=await z(a,e).get();if(t.cacheQuery(e),n){const o=n,c=r.docs.map(f=>v(f,o,a,"query-child")),i=u({size:c.length,empty:c.length===0,docs:c,metadata:t.querySnapshotMetadata()},a);for(const f of c)t.cachePath(f.ref.path);return w(i,r,a,e,"read"),i}Q(r,a);const s=r.docs;for(const o of s)t.cachePath(o.ref.path),P(o,a);return Object.defineProperty(r,"metadata",{value:t.querySnapshotMetadata(),configurable:!0}),w(r,r,a,e,"read"),r}export{w as a,K as b,U as g,B as r,Q as t,P as w};
1
+ import{A as h,ac as u,ad as g,p as y,ae as m,w as q,af as j,C,z as M,B as b,ag as W,t as D,ah as k,ai as z}from"./sandbox-controls.C2IqtoSw.js";const O=new WeakMap;function B(e){return O.get(e)?.raw??e}const E=new WeakMap,x=new WeakMap;function l(e,a,t,n,r){O.set(e,{target:t,path:a.ref.path,kind:r,converter:n,raw:a})}function F(e,a){const t=b(e),n=b(a);return t.isStructurallyEqual?.(n)??t===n}function I(e,a,t,n){const r=e,s=(x.get(r)??[]).filter(c=>c.query.deref()!==void 0),o=s.find(c=>{const i=c.query.deref();return i!==void 0&&F(i,a)});if(o!==void 0){const c=T(o.docs,t)&&o.metadata.fromCache===n.fromCache&&o.metadata.hasPendingWrites===n.hasPendingWrites;return o.docs=t,o.metadata=n,c?"settled":"initial"}return s.push({query:new WeakRef(a),docs:t,metadata:n}),x.set(r,s),"initial"}function T(e,a){return e.length===a.length&&e.every((t,n)=>{const r=a[n];return t.path===r.path&&W(t.data,r.data)})}function w(e,a,t,n,r){const s=a,o=d=>({path:d.ref?.path??"",data:M(d.data?.(),t)}),c=Object.freeze((s.docs??[]).map(o)),i=Object.freeze((s.docChanges?.()??[]).map(d=>({...o(d.doc??{}),type:d.type??"",oldIndex:d.oldIndex??-1,newIndex:d.newIndex??-1}))),f=Object.freeze({fromCache:s.metadata?.fromCache===!0,hasPendingWrites:s.metadata?.hasPendingWrites===!0});E.set(e,{target:t,query:n,converter:y(n)??null,source:r,...r==="read"?{readPhase:I(t,n,c,f)}:{},metadata:f,docs:c,changes:i})}function P(e,a){const t=e,n=t.data.bind(e);return Object.defineProperty(t,"data",{value:()=>g(n()),configurable:!0,writable:!0}),a&&t.ref?.path&&Object.defineProperty(t,"metadata",{value:h(a).snapshotMetadata(t.ref.path),configurable:!0}),e}function v(e,a,t,n){const r={id:e.id,ref:e.ref,exists:e.exists,metadata:h(t).snapshotMetadata(e.ref.path),data:()=>{if(!(typeof e.exists=="function"?e.exists():e.exists))return;const o=g(e.data()),c={id:e.id,ref:e.ref,exists:!0,metadata:h(t).snapshotMetadata(e.ref.path),data:()=>o};return a.fromFirestore(c)}};return u(r,t),u(e.ref,t),p(e.ref,t),l(r,e,t,a,n),r}function Q(e,a){if(!e||typeof e!="object")return e;u(e,a);const t=e;if(t.ref&&(u(t.ref,a),p(t.ref,a)),S(t),Array.isArray(t.docs))for(const n of t.docs)n&&(u(n,a),l(n,n,a,null,"query-child")),n?.ref&&(u(n.ref,a),p(n.ref,a)),n&&S(n);else t.ref&&l(e,e,a,null,"document");return e}function p(e,a){if(typeof e.path!="string"||e.path.length===0)return;const t=e.path;try{const n=m.get(e),r=n??q(a).doc(t);n===void 0&&m.set(e,r),j(e,t,a,r),a.kind==="sandbox-live"&&C.set(r,s=>s.doc(t))}catch{}}function S(e){const a=e.exists;if(typeof a=="function")return;const t=a===!0;try{Object.defineProperty(e,"exists",{value:()=>t,writable:!0,configurable:!0,enumerable:!0})}catch{}}async function U(e){const a=D(e),t=h(a);t.markStarted();const n=y(e),r=await k(a,e).get();return t.cachePath(e.path),n?v(r,n,a,"document"):(Q(r,a),P(r,a))}async function K(e){const a=D(e),t=h(a);t.markStarted();const n=y(e),r=await z(a,e).get();if(t.cacheQuery(e),n){const o=n,c=r.docs.map(f=>v(f,o,a,"query-child")),i=u({size:c.length,empty:c.length===0,docs:c,metadata:t.querySnapshotMetadata()},a);for(const f of c)t.cachePath(f.ref.path);return w(i,r,a,e,"read"),i}Q(r,a);const s=r.docs;for(const o of s)t.cachePath(o.ref.path),P(o,a);return Object.defineProperty(r,"metadata",{value:t.querySnapshotMetadata(),configurable:!0}),w(r,r,a,e,"read"),r}export{w as a,K as b,U as g,B as r,Q as t,P as w};
@@ -1136,7 +1136,7 @@ export function validString(field, min, max) {
1136
1136
  export function isOneOf(field, values) {
1137
1137
  return request.resource.data[field] in values;
1138
1138
  }
1139
- `};function Pf(){const t={};for(const[e,n]of Object.entries(jf))t[e]=n,t[`./stdlib/${e}.rules`]=n;return t}const Ic=Pf(),$f=new Set(Object.keys(Ic));function Qg(t,e){const n=Object.entries(e?.modules??{}),r=Object.fromEntries(n),s=new Set(n.map(([a])=>a)),i=new Set([...$f].filter(a=>!s.has(a)));return rh(null,t,{...e,modules:{...Ic,...r}},i)}const qf=`RtdbExpr {
1139
+ `};function Pf(){const t={};for(const[e,n]of Object.entries(jf))t[e]=n,t[`./stdlib/${e}.rules`]=n;return t}const Ic=Pf(),$f=new Set(Object.keys(Ic));function Yg(t,e){const n=Object.entries(e?.modules??{}),r=Object.fromEntries(n),s=new Set(n.map(([a])=>a)),i=new Set([...$f].filter(a=>!s.has(a)));return rh(null,t,{...e,modules:{...Ic,...r}},i)}const qf=`RtdbExpr {
1140
1140
  Expr = Ternary
1141
1141
 
1142
1142
  Ternary
@@ -1248,5 +1248,5 @@ ${e.join(`
1248
1248
  `)}`}function Zp(t){if(!(t.limit==null&&t.offset==null&&t.orderBy==null))return{...t.limit!=null?{limit:t.limit}:{},...t.offset!=null?{offset:t.offset}:{},...t.orderBy!=null?{orderBy:t.orderBy}:{}}}class Jp{events;rules;simulator;host;constructor(e,n,r,s){this.events=e,this.rules=n,this.simulator=r,this.host=s}authorize(e){const{path:n,auth:r,constraints:s,origin:i,triggeredBy:a}=e,o=Zp(s),c={...e.bypassRules?{admin:!0}:{},...o?{query:o}:{},...e.activityQuery!==void 0?{activityQuery:e.activityQuery}:{}},u=Object.keys(c).length>0?c:void 0,d=e.timing?.requestTime??(e.bypassRules?void 0:xe.fromMillis(Date.now())),l=e.timing?.at??Date.now();if(e.bypassRules)return this.emitRequest({at:l,evalMs:0,method:"list",path:n,auth:r,result:"allow",debugMessages:[i==="listener"?"admin lens — rules bypassed":"admin lens — rules bypassed (Studio Gap #2)"],origin:i,...u?{detail:u}:{},...a?{triggeredBy:a}:{}}),{allowed:!0};const p=this.rules.ast(),y=e.collectionGroup?zp(p):p;if(e.collectionGroup&&!y){const v=`list ${n} denied: symbolic collection-group proof is not supported; the query is rejected rather than authorizing from the currently stored rows`;this.emitRequest({at:l,evalMs:0,method:"list",path:n,auth:r,result:"deny",debugMessages:[v],origin:i,...u?{detail:u}:{},...a?{triggeredBy:a}:{}});const A=te("permission-denied",v,{request:{method:"list",path:n,auth:r},query:s});return this.emitUserDenial(i,A),{allowed:!1,error:A}}const b=`${n}/__listPlaceholder__`,w=performance.now(),R=Wp(y,b,r,s,this.rules.source);if(R.kind==="unprovable"){const v=`list ${n} denied: the query is statically unprovable for every possible result (rules are not filters), so the whole query is rejected — ${R.reason}`,A=Kp(R.residual),x={at:l,evalMs:performance.now()-w,method:"list",path:n,auth:r,result:"deny",debugMessages:[v],origin:i};u!==void 0&&(x.detail=u),a!==void 0&&(x.triggeredBy=a),this.emitRequest(x);const g={request:{method:"list",path:n,auth:r},query:s};A!==void 0&&A!==""&&(g.remediation=A),R.rule!==void 0&&(g.rule=R.rule);const O=te("permission-denied",v,g);return this.emitUserDenial(i,O),{allowed:!1,error:O}}const I=R.kind==="provable"?aa(R.evaluationAst):e.collectionGroup?aa(y):this.rules.source,E=Jr(this.host.state,{method:"list",path:b,auth:r},d);this.applyProof(E,R,s);const N=this.simulator.simulate(I,[E],{getDoc:v=>this.host.state.get(v)}),q=performance.now()-w;if(!N.success)return this.emitRequest({at:l,evalMs:q,method:"list",path:n,auth:r,result:"deny",debugMessages:[`Simulation error: ${N.error.message}`],origin:i,...u?{detail:u}:{},...a?{triggeredBy:a}:{}}),{allowed:!1,error:te("permission-denied",`list ${n} simulator error`,{request:{method:"list",path:n,auth:r}})};const S=N.data.results[0],k=Se(S);if(S.state==="UNSUPPORTED")throw this.emitRequest({at:l,evalMs:q,method:"list",path:n,auth:r,result:"unsupported",debugMessages:k,origin:i,...u?{detail:u}:{},...a?{triggeredBy:a}:{}}),new Wn(Hn("list",n,k),"list",n,k);if(S.state!=="PASSED"){const v=Kt(S),A={at:l,evalMs:q,method:"list",path:n,auth:r,result:"deny",debugMessages:k,evaluatedRule:v,origin:i};u!==void 0&&(A.detail=u),a!==void 0&&(A.triggeredBy=a),this.emitRequest(A);const h={request:{method:"list",path:n,auth:r}};v!==void 0&&(h.rule=v);const m=te("permission-denied",`list ${n} denied by rules`,h);return this.emitUserDenial(i,m),{allowed:!1,error:m}}return this.emitRequest({at:l,evalMs:q,method:"list",path:n,auth:r,result:"allow",debugMessages:k,evaluatedRule:Kt(S),origin:i,...u?{detail:u}:{},...a?{triggeredBy:a}:{}}),{allowed:!0}}applyProof(e,n,r){n.kind==="provable"&&(e.resource=n.syntheticResource),(r.limit!=null||r.offset!=null||r.orderBy!=null)&&(e.query={...r.limit!=null?{limit:r.limit}:{},...r.offset!=null?{offset:r.offset}:{},...r.orderBy!=null?{orderBy:r.orderBy}:{}})}emitRequest(e){this.events.request.hasSubscribers&&this.events.request.emit(Zr(e))}emitUserDenial(e,n){e==="user"&&this.events.denial.emit(n)}}function Qp(t,e,n){if(e<=0)return[];const r=[];for(const s of t)r.length<e?Ja(r,s,n):n(s,r[r.length-1])<0&&(r.pop(),Ja(r,s,n));return r}function Ja(t,e,n){let r=0,s=t.length;for(;r<s;){const i=r+s>>1;n(e,t[i])<0?s=i:r=i+1}t.splice(r,0,e)}function Yp(t){return typeof t.seconds=="number"&&(typeof t.nanos=="number"||typeof t.nanoseconds=="number")}function Xp(t){return typeof t.latitude=="number"&&typeof t.longitude=="number"}function em(t){return t.data instanceof Uint8Array}function tm(t){return typeof t.path=="string"}function Pr(t){if(t==null)return 0;const e=typeof t;if(e==="boolean")return 1;if(e==="number"||e==="bigint")return 2;if(e==="string")return 4;if(Array.isArray(t))return 8;if(e==="object"){const n=t;return Yp(n)?3:em(n)?5:Xp(n)?7:tm(n)?6:9}return 9}function Qa(t){const e=typeof t.nanos=="number"?t.nanos:t.nanoseconds??0;return[t.seconds,e]}function nm(t,e){const n=Number.isNaN(t),r=Number.isNaN(e);return n&&r?0:n?-1:r?1:t<e?-1:t>e?1:0}function Ya(t,e){return t<e?-1:t>e?1:0}function Rt(t,e){const n=Pr(t),r=Pr(e);if(n!==r)return n<r?-1:1;switch(n){case 0:return 0;case 1:return t===e?0:t?1:-1;case 2:return nm(Number(t),Number(e));case 3:{const[s,i]=Qa(t),[a,o]=Qa(e);return s!==a?s<a?-1:1:i<o?-1:i>o?1:0}case 4:return Ya(t,e);case 5:{const s=t.data,i=e.data,a=Math.min(s.length,i.length);for(let o=0;o<a;o++)if(s[o]!==i[o])return s[o]<i[o]?-1:1;return s.length<i.length?-1:s.length>i.length?1:0}case 6:return Ya(t.path,e.path);case 7:{const s=t,i=e;return s.latitude!==i.latitude?s.latitude<i.latitude?-1:1:s.longitude<i.longitude?-1:s.longitude>i.longitude?1:0}case 8:{const s=t,i=e,a=Math.min(s.length,i.length);for(let o=0;o<a;o++){const c=Rt(s[o],i[o]);if(c!==0)return c}return s.length<i.length?-1:s.length>i.length?1:0}case 9:{const s=t,i=e,a=Object.keys(s).sort(),o=Object.keys(i).sort(),c=Math.min(a.length,o.length);for(let u=0;u<c;u++){if(a[u]!==o[u])return a[u]<o[u]?-1:1;const d=Rt(s[a[u]],i[o[u]]);if(d!==0)return d}return a.length<o.length?-1:a.length>o.length?1:0}default:return 0}}function rm(t){const e=t.kind;if(e==="collection"){const n=t.path;return Object.freeze({kind:e,path:n})}if(e==="collection-group"){const n=t.collectionId;return Object.freeze({kind:e,collectionId:n})}throw new ue({code:"invalid-argument",message:`Unknown query scope kind: ${String(e)}`})}function Xa(t){const e=u=>{const d=u.kind;if(d==="where"){const p=u.field,y=u.op,b=u.value;return Object.freeze({kind:d,field:p,op:y,value:b})}if(d!=="and"&&d!=="or")throw new ue({code:"invalid-argument",message:`Unknown query filter kind: ${String(d)}`});const l=u.filters;return Object.freeze({kind:d,filters:Object.freeze(Array.from(l,e))})},n=u=>{if(u===void 0)return;const d=u.values,l=u.inclusive,p=u.fromSnapshot;return Object.freeze({values:Object.freeze(Array.from(d)),inclusive:l,fromSnapshot:p})},r=t.filters,s=t.orders,i=t.limitCount,a=t.limitFromEnd,o=t.start,c=t.end;return Object.freeze({filters:Object.freeze(Array.from(r,e)),orders:Object.freeze(Array.from(s,u=>{const d=u.field,l=u.direction;return Object.freeze({field:d,direction:l})})),limitCount:i,limitFromEnd:a,start:n(o),end:n(c)})}function eo(t){const e=[],n=r=>{if(r.kind==="where"){if(r.field===Et)return;const s=r.value;(s===null||typeof s=="string"||typeof s=="number"||typeof s=="boolean")&&e.push(Object.freeze({field:r.field,op:r.op,value:s}));return}r.kind==="and"&&r.filters.forEach(n)};return t.filters.forEach(n),Object.freeze({where:Object.freeze(e),limit:t.limitCount??null,offset:null,orderBy:t.orders.length>0?t.orders[0].field:null})}function sm(t,e){if(e.kind==="collection")return t.scan(e.path,{directOnly:!0});const n=[];for(const[r,s]of Object.entries(t.snapshot())){const i=r.split("/").filter(a=>a.length>0);i.length>0&&i.length%2===0&&i[i.length-2]===e.collectionId&&n.push({path:r,data:s})}return n}const Et="__name__",im=new Set(["<","<=",">",">=","!=","not-in"]);function Qs(t,e){return e===Et?{path:t.path}:t.data[e]}function Ci(t){return t.kind==="where"?im.has(t.op)?[t.field]:[]:t.filters.flatMap(Ci)}function am(t){return Ci(t).length>0}function Qr(t,e){return Pr(t)===Pr(e)}function om(t,e){return Qr(t,e)&&Rt(t,e)<0}function cm(t,e){return Qr(t,e)&&Rt(t,e)<=0}function um(t,e){return Qr(t,e)&&Rt(t,e)>0}function lm(t,e){return Qr(t,e)&&Rt(t,e)>=0}function dm(t,e,n){const r=t!==void 0;switch(e){case"==":return r&&Ye(t,n);case"!=":return r&&t!==null&&!Ye(t,n);case"<":return r&&om(t,n);case"<=":return r&&cm(t,n);case">":return r&&um(t,n);case">=":return r&&lm(t,n);case"in":return r&&Array.isArray(n)&&n.some(s=>Ye(t,s));case"not-in":return!Array.isArray(n)||n.some(s=>s===null)?!1:r&&t!==null&&!n.some(s=>Ye(t,s));case"array-contains":return Array.isArray(t)&&t.some(s=>Ye(s,n));case"array-contains-any":return Array.isArray(t)&&Array.isArray(n)&&n.some(s=>t.some(i=>Ye(i,s)))}}function hm(t,e){if(e===Et){const n=t.path.split("/");return n[n.length-1]??t.path}return t.data[e]}function Bc(t){if(Array.isArray(t))return t.map(Bc);if(t&&typeof t=="object"){const e=t;if(typeof e.id=="string")return e.id;if(typeof e.path=="string"){const n=e.path.split("/");return n[n.length-1]??e.path}}return t}function Ys(t,e){if(e.kind==="where"){const n=hm(t,e.field),r=e.field===Et?Bc(e.value):e.value;return dm(n,e.op,r)}return e.kind==="and"?e.filters.every(n=>Ys(t,n)):e.filters.some(n=>Ys(t,n))}function fm(t,e){return t.filter(n=>e.every(r=>Ys(n,r)))}function to(t,e,n){for(let r=0;r<e.length;r++){const s=Rt(Qs(t,n[r].field),e[r]);if(s!==0)return n[r].direction==="desc"?-s:s}return 0}function pm(t,e,n,r){return t.filter(s=>{if(n){const i=to(s,n.values,e);if(n.inclusive?i<0:i<=0)return!1}if(r){const i=to(s,r.values,e);if(r.inclusive?i>0:i>=0)return!1}return!0})}function zc(t,e){return t.filter(n=>e.every(r=>r.field===Et||n.data[r.field]!==void 0))}function Vc(t){return(e,n)=>{for(const r of t){const s=Rt(Qs(e,r.field),Qs(n,r.field));if(s!==0)return r.direction==="desc"?-s:s}return 0}}function mm(t,e){return e.length===0?t:zc(t,e).sort(Vc(e))}function Wc(t){const e=[...t.orders],n=new Set(e.map(s=>s.field)),r=t.orders.length>0?t.orders[t.orders.length-1].direction:"asc";for(const s of t.filters)for(const i of Ci(s))i!==Et&&!n.has(i)&&(n.add(i),e.push({field:i,direction:r}));return n.has(Et)||e.push({field:Et,direction:r}),e}function hs(t,e){let n=fm(t,[...e.filters]);const r=Wc(e),s=e.orders.length>0||e.start!==void 0||e.end!==void 0||e.filters.some(am);if(s&&e.limitCount!==void 0&&!e.limitFromEnd&&e.start===void 0&&e.end===void 0)return Qp(zc(n,r),e.limitCount,Vc(r));if(s&&(n=mm(n,r)),e.start||e.end){for(const i of[e.start,e.end])if(i&&!i.fromSnapshot&&i.values.length>e.orders.length)throw new ue({code:"invalid-argument",message:"Too many arguments provided to a cursor (startAt / startAfter / endAt / endBefore). The number of cursor values must be less than or equal to the number of orderBy() clauses."});n=pm(n,r,e.start,e.end)}if(e.limitCount!==void 0)if(e.limitFromEnd){if(e.orders.length===0)throw new ue({code:"unimplemented",message:"limitToLast() queries require at least one orderBy clause."});n=n.slice(-e.limitCount)}else n=n.slice(0,e.limitCount);return n}class gm{events;triggerScope;rules;simulator;host;operationReader;listAuthorizer;constructor(e,n,r,s,i,a){this.events=e,this.triggerScope=n,this.rules=r,this.simulator=s,this.host=i,this.operationReader=new Up(e,r,s,i,a),this.listAuthorizer=new Jp(e,r,s,i)}get state(){return this.host.state}emitRequest(e){this.events.request.hasSubscribers&&this.events.request.emit(Zr(e))}execute(e){return this.operationReader.execute(e)}silentReadDoc(e,n,r=!1){if(r){const E=this.state.get(e);return this.emitRequest({at:Date.now(),evalMs:0,method:"get",path:e,auth:n,result:"allow",debugMessages:["admin lens — rules bypassed"],origin:"listener",resourceBefore:{data:E,exists:E!==null},detail:{admin:!0},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),{allowed:!0,data:E}}const s=xe.fromMillis(Date.now()),i=Jr(this.state,{method:"get",path:e,auth:n},s),a=Date.now(),o=performance.now(),c=this.simulator.simulate(this.rules.source,[i],{getDoc:E=>this.state.get(E)}),u=performance.now()-o;if(!c.success)return this.emitRequest({at:a,evalMs:u,method:"get",path:e,auth:n,result:"deny",debugMessages:[`Simulation error: ${c.error.message}`],origin:"listener",...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),{allowed:!1,error:te("permission-denied",`get ${e} simulator error`,{request:{method:"get",path:e,auth:n}})};const d=c.data.results[0];if(d.state==="UNSUPPORTED")throw this.emitRequest({at:a,evalMs:u,method:"get",path:e,auth:n,result:"unsupported",debugMessages:Se(d),origin:"listener",...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),new Wn(Hn("get",e,Se(d)),"get",e,Se(d));const l=d.state==="PASSED",p=this.state.get(e),y=Kt(d);let b="deny";l&&(b="allow");const w=p!==null,R={at:a,evalMs:u,method:"get",path:e,auth:n,result:b,debugMessages:Se(d),evaluatedRule:y,origin:"listener",resourceBefore:{data:p,exists:w}},C=this.triggerScope.current();if(C!==void 0&&(R.triggeredBy=C),this.emitRequest(R),l===!1){const E={request:{method:"get",path:e,auth:n},resource:{data:p,exists:w}};return y!==void 0&&(E.rule=y),{allowed:!1,error:te("permission-denied",`get ${e} denied by rules`,E)}}return{allowed:!0,data:p}}silentReadCollection(e,n,r,s=!1){if(typeof r=="function")return{allowed:!1,error:te("invalid-argument","Callable query constraints are no longer executable; pass an immutable QueryConstraintPlan.")};const i=r?Xa(r.execution):void 0,a=i?eo(i):{},o={requestTime:xe.fromMillis(Date.now()),at:Date.now()},c=this.triggerScope.current();if(s){const p=this.state.list(e).filter(w=>!w.phantom).map(w=>({path:w.path,data:w.data})),y=i?hs(p,i):p,b=this.listAuthorizer.authorize({path:e,auth:n,constraints:a,bypassRules:s,...r?.activityQuery?{activityQuery:r.activityQuery}:{},origin:"listener",...c?{triggeredBy:c}:{},timing:o});return b.allowed?{allowed:!0,docs:y}:b}const u=this.listAuthorizer.authorize({path:e,auth:n,constraints:a,...r?.activityQuery?{activityQuery:r.activityQuery}:{},origin:"listener",...c?{triggeredBy:c}:{},timing:o});if(!u.allowed)return u;const d=this.state.list(e).filter(p=>!p.phantom).map(p=>({path:p.path,data:p.data}));return{allowed:!0,docs:i?hs(d,i):d}}runQuery(e){const n=rm(e.scope),r=Xa(e.execution),s=e.auth,i=e.bypassRules,a=e.activityQuery,o=sm(this.state,n),c=n.kind==="collection"?n.path:n.collectionId,u=eo(r),d=this.listAuthorizer.authorize({path:c,collectionGroup:n.kind==="collection-group",auth:s,constraints:u,bypassRules:i,...a!==void 0?{activityQuery:a}:{},origin:"user"});return d.allowed?{allowed:!0,docs:hs(o,r)}:d}}const no="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",ro=20;function Ti(){const t=new Uint8Array(ro);globalThis.crypto.getRandomValues(t);let e="";for(let n=0;n<ro;n++)e+=no[t[n]%no.length];return e}function Hc(t,e=""){const n=[],r=new WeakSet;return s(t,e),n;function s(i,a){if(i==null||typeof i!="object"||r.has(i)||(r.add(i),kc(i)!==void 0))return;if(Array.isArray(i)){i.forEach((u,d)=>s(u,`${a}[${d}]`));return}const o=i,c=ym(o);if(c){n.push({field:a,kind:c});return}for(const[u,d]of Object.entries(o)){const l=a?`${a}.${u}`:u;s(d,l)}}}function ym(t){const e=t.__type;return e==="serverTimestamp"?"serverTimestamp":e==="increment"?"increment":e==="arrayUnion"?"arrayUnion":e==="arrayRemove"?"arrayRemove":e==="deleteField"?"delete":null}gp();class bm{host;rules;simulator;eventLog;events;triggerScope;constructor(e,n,r,s,i,a){this.host=e,this.rules=n,this.simulator=r,this.eventLog=s,this.events=i,this.triggerScope=a}get state(){return this.host.state}emitDenial(e){this.events.denial.emit(e)}emitRequest(e){this.events.request.hasSubscribers&&this.events.request.emit(Zr(e))}emitWrite(e){this.events.write.hasSubscribers&&this.events.write.emit({kind:"write",id:Ln().replace(/^req-/,"wr-"),at:Date.now(),method:e.method,path:e.path,auth:e.auth?{uid:e.auth.uid,...e.auth.token?{token:e.auth.token}:{}}:null,...e.data!==void 0?{data:e.data}:{},priorState:e.priorState,nextState:e.nextState,...e.groupId!==void 0?{groupId:e.groupId}:{},...e.groupKind!==void 0?{groupKind:e.groupKind}:{},...e.sentinels&&e.sentinels.length>0?{sentinels:e.sentinels}:{},...e.autoId!==void 0?{autoId:e.autoId}:{},requestTime:{seconds:e.requestTime.seconds,nanoseconds:e.requestTime.nanos},...e.detail!==void 0?{detail:e.detail}:{},...e.provenance??{}})}capturePriors(e){const n={};for(const r of e){const s=this.state.get(r);n[r]=s?{...s}:null}return n}runSimulate(e,n,r){return $c(this.state,this.rules,this.simulator,e,n,r)}isReadOnlyMethod(e){return e==="get"||e==="list"}resolvePriorDocumentState(e,n,r){return n.has(e)?n.get(e)??null:r.exists(e)?r.get(e)??null:null}computeProjectedUpdate(e,n){return e===null?null:Zs(e,n??{})}computeProjectedOverwrite(e,n){return Zs(e??{},n??{})}buildBatchProjection(e){const n=new Map;for(const r of e){if(this.isReadOnlyMethod(r.method))continue;if(r.method==="delete"){n.set(r.path,null);continue}const s=this.resolvePriorDocumentState(r.path,n,this.state);if(r.method==="update"){const i=this.computeProjectedUpdate(s,r.data);n.set(r.path,i)}else{const i=this.computeProjectedOverwrite(s,r.data);n.set(r.path,i)}}return n}buildTestCase(e,n){return Jr(this.state,e,n)}notify(e,n,r){this.triggerScope.run({method:e,path:n},()=>this.host.notifyListenersForPaths(r))}}class Gc{runtime;constructor(e){this.runtime=e}prepare(e,n){const r=xe.fromMillis(Date.now()),s=[];for(let i=0;i<e.length;i++){const a=e[i];try{const o=a.data?nt({...a.data},{path:a.path,method:a.method,prior:this.runtime.state.get(a.path),serverTime:r}):a.data;s.push({method:a.method,path:a.path,data:o})}catch(o){const c=o.message,u=te("invalid-argument",c),d=n.snapshot[a.path]??null,l={at:Date.now(),evalMs:0,method:a.ruleMethod,path:a.path,auth:n.auth,result:"deny",debugMessages:[`FieldValue resolve error: ${c}`],...this.includesRequestData(n,a)?{resourceData:a.preData}:{},resourceBefore:{data:d,exists:d!==null},origin:n.origin,groupId:n.groupId,...n.bypassRules?{detail:{admin:!0}}:{},...n.provenance?{provenance:n.provenance}:{}};return{index:i,input:a,message:c,error:u,request:l}}}return{context:n,inputs:e,resolvedOps:s,serverTime:r}}evaluateAndApply(e){const{context:n,inputs:r,resolvedOps:s,serverTime:i}=e,a=s.map((l,p)=>{const y=r[p];return this.runtime.buildTestCase({method:y.ruleMethod,path:l.path,auth:n.auth,data:l.data},i)}),o=this.runtime.buildBatchProjection(a),c=[];let u=!0;for(let l=0;l<s.length;l++){s[l];const p=r[l],y=n.snapshot[p.path]??null,b=Date.now(),w=performance.now(),R=this.runtime.runSimulate([a[l]],n.bypassRules,o),C=performance.now()-w;if(!R.success){const k=te("invalid-argument",R.error.message);c.push({path:p.path,method:p.ruleMethod,allowed:!1,debugMessages:[R.error.message],error:k,request:this.request(e,p,y,b,C,"deny",[`Simulation error: ${R.error.message}`])}),u=!1;continue}const I=R.data.results[0],E=Se(I);if(I.state==="UNSUPPORTED")throw this.runtime.emitRequest(this.request(e,p,y,b,C,"unsupported",E)),new Wn(Hn(p.ruleMethod,p.path,E),p.ruleMethod,p.path,E);const N=I.state==="PASSED";let q="deny";N&&(q="allow");const S={path:p.path,method:p.ruleMethod,allowed:N,debugMessages:E,request:this.request(e,p,y,b,C,q,E)};if(N===!1){const k=Kt(I),_=y!==null,v={request:{method:p.ruleMethod,path:p.path,auth:n.auth},resource:{data:y,exists:_}};this.includesRequestData(n,p)&&(v.request.resourceData=p.preData),k!==void 0&&(v.rule=k),S.error=te("permission-denied",`${p.ruleMethod} ${p.path} denied by rules`,v),this.runtime.emitDenial(S.error),u=!1}c.push(S)}let d=null;if(u){const l=this.runtime.state.applyBatch(s);if(!l.success){u=!1;const p=l.errors?.[0];if(p!==void 0){const y=s[p.index];d=te(y?.method==="create"?"already-exists":"not-found",p.error);const b=c[p.index];b&&(b.allowed=!1,b.error=d)}}}return{...e,outcomes:c,allowed:u,structuralError:d}}emitAndNotify(e){const{context:n,inputs:r,outcomes:s,serverTime:i}=e;for(let a=0;a<s.length;a++){const o=s[a],c=r[a],u=e.allowed&&o.allowed,d=n.snapshot[c.path]??null;if(o.request.resourceAfter=u?c.ruleMethod==="delete"?{data:null,exists:!1}:{data:this.runtime.state.get(c.path),exists:this.runtime.state.get(c.path)!==null}:{data:d,exists:d!==null},this.runtime.emitRequest(o.request),u){const l=c.preData?Hc(c.preData):void 0;this.runtime.emitWrite({method:c.ruleMethod,path:c.path,auth:n.auth,...c.ruleMethod!=="delete"&&c.preData?{data:c.preData}:{},priorState:d,nextState:c.ruleMethod==="delete"?null:this.runtime.state.get(c.path),groupId:n.groupId,groupKind:n.origin,...l&&l.length>0?{sentinels:l}:{},requestTime:i,...n.bypassRules?{detail:{admin:!0}}:{},...n.provenance?{provenance:n.provenance}:{}})}}e.allowed&&this.runtime.notify(n.origin,r[0]?.path??"",new Set(r.map(a=>a.path)))}request(e,n,r,s,i,a,o){const{context:c}=e;return{at:s,evalMs:i,method:n.ruleMethod,path:n.path,auth:c.auth,result:a,debugMessages:o,...this.includesRequestData(c,n)?{resourceData:n.preData}:{},resourceBefore:{data:r,exists:r!==null},origin:c.origin,groupId:c.groupId,...c.bypassRules?{detail:{admin:!0}}:{},...c.provenance?{provenance:c.provenance}:{}}}includesRequestData(e,n){return n.preData!==void 0&&(e.origin==="batch"||n.ruleMethod!=="delete")}}class vm{runtime;pipeline;constructor(e){this.runtime=e,this.pipeline=new Gc(e)}batch(e,n,r){const s=this.runtime.capturePriors(e.map(p=>p.path)),i=`batch-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,a=e.map(p=>({...p,ruleMethod:p.method,preData:p.data})),o=this.pipeline.prepare(a,{origin:"batch",groupId:i,auth:n,bypassRules:r,snapshot:s});if(!("resolvedOps"in o)){const p=this.runtime.eventLog.append({type:"batch",method:"batch",path:"",auth:n?{uid:n.uid}:null,allowed:!1,operations:e.map(y=>({method:y.method,path:y.path,data:y.data,allowed:!1})),debugMessages:[`FieldValue resolve error on '${o.input.path}': ${o.message}`]});return this.runtime.emitRequest(o.request),{allowed:!1,results:e.map(y=>({path:y.path,allowed:!1,debugMessages:[o.message],...y.path===o.input.path?{error:o.error}:{}})),event:p,error:o.error}}const c=this.pipeline.evaluateAndApply(o),u=c.outcomes.map(p=>({path:p.path,allowed:p.allowed,debugMessages:p.debugMessages,...p.error?{error:p.error}:{}})),d=this.runtime.eventLog.append({type:"batch",method:"batch",path:"",auth:n?{uid:n.uid}:null,allowed:c.allowed,priorDocs:c.allowed?s:void 0,operations:c.resolvedOps.map((p,y)=>({method:p.method,path:p.path,data:p.data,allowed:u[y]?.allowed??!1})),debugMessages:c.allowed?["Batch committed"]:["Batch rolled back — one or more operations denied"]});this.pipeline.emitAndNotify(c);let l;return c.allowed||(l=c.structuralError??u.find(p=>p.error)?.error??te("permission-denied","Batch denied")),{allowed:c.allowed,results:u,event:d,...l?{error:l}:{}}}}const Xs="Firestore transactions require all reads to be executed before all writes.";class Kc extends Error{simError;constructor(){super(Xs),this.name="ReadAfterWriteError",this.simError=te("failed-precondition",Xs)}}class so extends Error{constructor(){super("A document read in the transaction changed before commit."),this.name="RetryableTransactionConflictError"}}class Zc extends Error{simError=te("failed-precondition","Transaction failed all retries.");constructor(){super("Transaction failed all retries."),this.name="TransactionAttemptsExhaustedError"}}class wm{versionReader;reader;reads=[];writes=[];readVersions=new Map;writeStarted=!1;constructor(e,n=()=>0){this.versionReader=n,this.reader=e}get(e){this.assertReadsAllowed();const n=this.reader(e);this.readVersions.has(e)||this.readVersions.set(e,this.versionReader(e)),this.reads.push({path:e,data:n});const r=n===null?null:structuredClone(n);return{path:e,exists:r!==null,data:()=>r===null?void 0:r}}getAll(...e){return this.assertReadsAllowed(),e.map(n=>this.get(n))}set(e,n){this.queue({method:"set",path:e,data:n})}create(e,n){this.queue({method:"create",path:e,data:n})}update(e,n){this.queue({method:"update",path:e,data:n})}delete(e){this.queue({method:"delete",path:e})}consume(){return{reads:this.reads,writes:this.writes,readVersions:this.readVersions}}hadWrites(){return this.writeStarted}queue(e){this.writeStarted=!0,this.writes.push(e)}assertReadsAllowed(){if(this.writeStarted)throw new Kc}}class Sm extends Error{path;secondMethod;constructor(e,n){super(`Queued ${n} on '${e}' after a delete in the same transaction. This combination is unprobed against production Firestore; refusing to guess. Either drop the delete or split into two transactions.`),this.name="AmbiguousPostDeleteWriteError",this.path=e,this.secondMethod=n}}function _m(t){const e=new Map;for(const n of t){const r=e.get(n.path);if(r===void 0){e.set(n.path,Am(n));continue}if(r.method==="delete")throw new Sm(n.path,n.method);e.set(n.path,xm(r,n))}return Array.from(e.values())}function Am(t){if(t.method==="delete")return{method:"delete",path:t.path};if(t.data===void 0)throw new Error(`internal: queued ${t.method} on ${t.path} has no data — Transaction class invariant violated`);return{method:t.method,path:t.path,data:t.data}}function xm(t,e){switch(e.method){case"delete":return{method:"delete",path:e.path};case"set":{const n=fs(e);return{method:"set",path:e.path,data:n}}case"update":{const n=fs(e),s={...t.data??{},...n};return{method:t.method,path:e.path,data:s}}case"create":{const n=fs(e),s={...t.data??{},...n};return{method:"create",path:e.path,data:s}}}}function fs(t){if(t.data===void 0)throw new Error(`internal: queued ${t.method} on ${t.path} has no data — Transaction class invariant violated`);return t.data}class Im{runtime;pipeline;constructor(e){this.runtime=e,this.pipeline=new Gc(e)}transaction(e,n){return this.runAttempt(e,n,1)}runAttempt(e,n,r){const s=this.runtime.state.snapshot(),i=this.runtime.state.currentVersion(),a=new Map(Object.keys(s).map(d=>[d,this.runtime.state.version(d)])),o=d=>s[d]??null,c=new wm(o,d=>{const l=a.get(d);if(l!==void 0)return l;const p=this.runtime.state.version(d);return p<=i?p:-1});let u;try{u=e(c)}catch(d){throw this.logAbortedTransaction(c,n.auth,d),d}if(u!==null&&typeof u?.then=="function")return u.then(d=>{try{return this.commitTransaction(c,s,n,d)}catch(l){return this.retryOrThrow(l,e,n,r)}},d=>{throw this.logAbortedTransaction(c,n.auth,d),d});try{return this.commitTransaction(c,s,n,u)}catch(d){return this.retryOrThrow(d,e,n,r)}}retryOrThrow(e,n,r,s){if(!(e instanceof so))throw e;const i=r.maxAttempts??5;if(s>=i)throw new Zc;return this.runAttempt(n,r,s+1)}commitTransaction(e,n,r,s){const{reads:i,writes:a,readVersions:o}=e.consume();for(const[E,N]of o)if(this.runtime.state.version(E)!==N)throw new so;const c=r.auth;if(a.length===0){const E=this.runtime.eventLog.append({type:"transaction",method:"transaction",path:"",auth:c?{uid:c.uid}:null,allowed:!0,reads:i.map(N=>({path:N.path,data:N.data})),operations:[],snapshot:n,debugMessages:["Transaction committed (read-only — no writes queued)"]});return{allowed:!0,reads:[...i],writes:[],returnValue:s,event:E}}let u;try{u=_m(a)}catch(E){const N=E;throw this.runtime.eventLog.append({type:"transaction",method:"transaction",path:"",auth:c?{uid:c.uid}:null,allowed:!1,aborted:!0,reads:i.map(q=>({path:q.path,data:q.data})),error:{name:N.name,message:N.message,code:"failed-precondition"},debugMessages:[`Transaction aborted at merge: ${N.message}`]}),E}const d=Object.fromEntries(u.map(E=>[E.path,n[E.path]??null])),l=u.map(E=>{const N=E.method==="set"?this.runtime.state.get(E.path)!==null?"update":"create":E.method;return{...E,ruleMethod:N,preData:E.data}}),p=`tx-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,y=this.pipeline.prepare(l,{origin:"transaction",groupId:p,auth:c,bypassRules:r.bypassRules,provenance:r.provenance,snapshot:d});if(!("resolvedOps"in y)){const E=this.runtime.eventLog.append({type:"transaction",method:"transaction",path:"",auth:c?{uid:c.uid}:null,allowed:!1,reads:i.map(N=>({path:N.path,data:N.data})),operations:u.map(N=>({method:N.method,path:N.path,data:N.data,allowed:!1})),debugMessages:[`FieldValue resolve error on '${y.input.path}': ${y.message}`]});return this.runtime.emitRequest(y.request),{allowed:!1,reads:[...i],writes:l.map((N,q)=>({path:N.path,method:N.ruleMethod,allowed:!1,debugMessages:q===y.index?[y.message]:[],...q===y.index?{error:y.error}:{}})),returnValue:s,event:E,error:y.error}}const b=this.pipeline.evaluateAndApply(y),w=b.outcomes.map(E=>({path:E.path,method:E.method,allowed:E.allowed,debugMessages:E.debugMessages,...E.error?{error:E.error}:{}})),R=this.runtime.eventLog.append({type:"transaction",method:"transaction",path:"",auth:c?{uid:c.uid}:null,allowed:b.allowed,reads:i.map(E=>({path:E.path,data:E.data})),operations:b.resolvedOps.map((E,N)=>({method:E.method,path:E.path,data:E.data,allowed:w[N]?.allowed??!1})),snapshot:b.allowed?n:void 0,debugMessages:b.allowed?["Transaction committed"]:["Transaction rolled back — one or more operations denied"]});this.pipeline.emitAndNotify(b);let C;b.allowed||(C=b.structuralError??w.find(E=>E.error)?.error??te("permission-denied","Transaction denied"));const I={allowed:b.allowed,reads:[...i],writes:w,returnValue:s,event:R,...C?{error:C}:{}};return r.readOnly&&e.hadWrites()&&(I.readOnlyViolation=!0),I}logAbortedTransaction(e,n,r){const s=r,{reads:i}=e.consume();this.runtime.eventLog.append({type:"transaction",method:"transaction",path:"",auth:n?{uid:n.uid}:null,allowed:!1,aborted:!0,reads:i.map(a=>({path:a.path,data:a.data})),error:{name:r.name,message:r.message,...s.code!==void 0?{code:String(s.code)}:{}},debugMessages:[`Transaction aborted: ${r.message}`]})}}class Em{runtime;batches;transactions;constructor(e,n,r,s,i,a){this.runtime=new bm(e,n,r,s,i,a),this.batches=new vm(this.runtime),this.transactions=new Im(this.runtime)}capturePriors(e){return this.runtime.capturePriors(e)}applyWrite(e,n,r,s){if(s!==void 0&&s!==!1&&(e==="create"||e==="update")){const i=s===!0?void 0:s.mergeFields;return this.runtime.state.setMerge(n,r??{},i),null}switch(e){case"create":{const i=this.runtime.state.create(n,r??{});return i.success?null:te("already-exists",i.error??`Document '${n}' already exists`)}case"update":{const i=this.runtime.state.update(n,r??{});return i.success?null:te("not-found",i.error??`Document '${n}' does not exist`)}case"set":return this.runtime.state.set(n,r??{}),null;case"delete":return this.runtime.state.delete(n),null;default:return null}}execute(e){const{method:n,path:r,auth:s,data:i,autoId:a,requestTime:o,merge:c,bypassRules:u}=e,d=u?{admin:!0}:void 0,l=this.runtime.capturePriors([r]),p=o??xe.fromMillis(Date.now());let y;try{y=i&&nt({...i},{path:r,method:n,prior:this.runtime.state.get(r),serverTime:p}),n==="update"&&y&&bp(y)}catch(A){const x=A.message,f=this.runtime.eventLog.append({type:"single",method:n,path:r,auth:s?{uid:s.uid}:null,data:i,allowed:!1,priorDocs:l,debugMessages:[`FieldValue resolve error: ${x}`]});return this.runtime.emitRequest({at:Date.now(),evalMs:0,method:n,path:r,auth:s,result:"deny",debugMessages:[`FieldValue resolve error: ${x}`],...y?{resourceData:y}:i?{resourceData:i}:{},resourceBefore:{data:l[r]??null,exists:(l[r]??null)!==null},origin:"user",...d?{detail:d}:{}}),{allowed:!1,debugMessages:[x],event:f,error:te("invalid-argument",x)}}const b=this.runtime.buildTestCase({...e,data:y},p),w=Date.now(),R=performance.now(),C=this.runtime.runSimulate([b],u),I=performance.now()-R;if(!C.success){const A=this.runtime.eventLog.append({type:"single",method:n,path:r,auth:s?{uid:s.uid}:null,data:y,allowed:!1,priorDocs:l,debugMessages:[`Simulation error: ${C.error.message}`]});return this.runtime.emitRequest({at:w,evalMs:I,method:n,path:r,auth:s,result:"deny",debugMessages:[`Simulation error: ${C.error.message}`],...i?{resourceData:i}:{},resourceBefore:{data:l[r]??null,exists:(l[r]??null)!==null},origin:"user",...d?{detail:d}:{}}),{allowed:!1,debugMessages:[C.error.message],event:A,error:te("invalid-argument",C.error.message)}}const E=C.data.results[0];if(E.state==="UNSUPPORTED")throw this.runtime.emitRequest({at:w,evalMs:I,method:n,path:r,auth:s,result:"unsupported",debugMessages:Se(E),...i?{resourceData:i}:{},resourceBefore:{data:l[r]??null,exists:(l[r]??null)!==null},origin:"user",...d?{detail:d}:{}}),new Wn(Hn(n,r,Se(E)),n,r,Se(E));let N=E.state==="PASSED",q=null;N&&(q=this.applyWrite(n,r,y,c),q&&(N=!1));const S=this.runtime.eventLog.append({type:"single",method:n,path:r,auth:s?{uid:s.uid}:null,data:y,allowed:N,priorDocs:N?l:void 0,debugMessages:Se(E)}),k={allowed:N,debugMessages:Se(E),event:S};if(N===!1){let A=!1;if(q!==void 0&&q!==null&&(A=!0),A)k.error=q;else{let f=null;const h=l[r];h!==void 0&&(f=h);let m=n;n==="set"&&(f!==null?m="update":m="create");const O=Kt(E),D={request:{method:m,path:r,auth:s},resource:{data:f,exists:f!==null}};i!==void 0&&(D.request.resourceData=i),O!==void 0&&(D.rule=O),k.error=te("permission-denied",`${n} ${r} denied by rules`,D),this.runtime.emitDenial(k.error)}}const _=l[r]??null,v=N?this.runtime.state.get(r):_;if(this.runtime.emitRequest({at:w,evalMs:I,method:n,path:r,auth:s,result:N?"allow":"deny",debugMessages:Se(E),evaluatedRule:Kt(E),...i?{resourceData:i}:{},resourceBefore:{data:_,exists:_!==null},...n!=="delete"?{resourceAfter:{data:v,exists:v!==null}}:{resourceAfter:{data:null,exists:!1}},origin:"user",...d?{detail:d}:{}}),N){const A=i?Hc(i):void 0,x=a&&n==="create"?r.split("/").pop():void 0;this.runtime.emitWrite({method:n,path:r,auth:s,...n!=="delete"&&i?{data:i}:{},priorState:_,nextState:n==="delete"?null:v,...A&&A.length>0?{sentinels:A}:{},...x?{autoId:x}:{},requestTime:p,...d?{detail:d}:{}})}return N&&this.runtime.notify(n,r,new Set([r])),k}createWithAutoId(e,n,r,s){const i=e.endsWith("/")?e.slice(0,-1):e,a=Ti(),o=`${i}/${a}`,c=this.execute({method:"create",path:o,auth:r,data:n,autoId:!0,bypassRules:s});return{path:o,result:c}}batch(e,n,r){return this.batches.batch(e,n,r)}transaction(e,n){return this.transactions.transaction(e,n)}}class io{state;eventLog;history;simulator;rules;seedSnapshot;events=new Ep;triggerScope=new kp;reads;writes;listeners;constructor(){this.state=new ls,this.eventLog=new _p;const e=this;this.simulator=new Jh,this.rules=new qp(Ip),this.reads=new gm(this.events,this.triggerScope,this.rules,this.simulator,{get state(){return e.state}},this.eventLog),this.listeners=new Pp(this.events,this.triggerScope,this.reads),this.writes=new Em({get state(){return e.state},notifyListenersForPaths:n=>e.listeners.notifyListenersForPaths(n)},this.rules,this.simulator,this.eventLog,this.events,this.triggerScope),this.history=new $p(this.eventLog,{get state(){return e.state},capturePriors:n=>this.writes.capturePriors(n),applyWrite:(n,r,s,i)=>this.writes.applyWrite(n,r,s,i)}),this.seedSnapshot={}}onDenial(e){return this.events.denial.subscribe(e)}onRequest(e){return this.events.request.subscribe(e)}onWrite(e){return this.events.write.subscribe(e)}onSnapshotDelivery(e){return this.events.delivery.subscribe(e)}onSnapshotSuppressed(e){return this.events.suppressed.subscribe(e)}onListenerLifecycle(e){return this.events.lifecycle.subscribe(e)}onSnapshotError(e){return this.events.snapshotError.subscribe(e)}addSnapshotListener(e,n,r={},s=null,i,a=!1,o=!1,c){return this.listeners.addSnapshotListener(e,n,r,s,i,a,o,c)}flushListeners(){this.listeners.flushListeners()}getSnapshotListenerCount(){return this.listeners.getSnapshotListenerCount()}dispose(){this.listeners.dispose(),this.events.clear()}seed(e){return this.rules.set(e.rules),this.state=e.baseDocuments?new ls({},new Sp(e.baseDocuments)):new ls(e.documents??{}),this.seedSnapshot=e.baseDocuments??this.state.snapshot(),this.eventLog.clear(),Ds(e.rules)}deployRules(e){const n=Ds(e);return this.rules.set(e),this.listeners.reEvaluateAllListeners(),n}reevaluateLiveListeners(e,n){this.listeners.reevaluateLiveListeners(e,n)}getRules(){return this.rules.source}getDocument(e){return this.state.get(e)}listDocuments(e){return this.state.list(e)}runQuery(e){return this.reads.runQuery(e)}listRootCollections(){return this.state.listRootCollections()}listSubcollections(e){return this.state.listSubcollections(e)}snapshot(){return this.state.snapshot()}adminSetDocument(e,n){this.state.set(e,n??{}),this.listeners.notifyListenersForPaths(new Set([e]))}adminDeleteDocument(e){const n=this.state.delete(e);return n.success&&this.listeners.notifyListenersForPaths(new Set([e])),{deleted:n.success}}execute(e){return e.method==="get"||e.method==="list"?this.reads.execute(e):this.writes.execute(e)}createWithAutoId(e,n,r,s){return this.writes.createWithAutoId(e,n,r,s)}batch(e,n,r){return this.writes.batch(e,n,r)}transaction(e,n){return this.writes.transaction(e,n)}undo(){return this.history.undo()}redo(){return this.history.redo()}getEvents(){return this.history.getEvents()}getEventCount(){return this.history.getEventCount()}}class ie extends Error{code;denialContext;remediation;constructor(e,n,r){const s=typeof e=="object",i=s?e.code:e,a=s?e.message:n,o=s?e.denialContext:r,c=s?e.remediation:void 0,u=c!==void 0?`${a}
1249
1249
 
1250
1250
  Remediation:
1251
- ${c}`:a;super(u),this.name="SandboxError",this.code=i,o!==void 0&&(this.denialContext=o),c!==void 0&&(this.remediation=c)}}function ei(t){return t.kind==="request"||t.kind==="operation"||t.kind==="listener"&&t.phase==="errored"}function Kn(t){const e=Object.freeze({...t.source}),n=Object.freeze({...t.authLens});return Object.freeze({source:e,authLens:n,...t.planId===void 0?{}:{planId:t.planId}})}function Ri(t){const e=Kn(t);return{actor:e.source,authLens:e.authLens,operationContext:e,...e.planId===void 0?{}:{planId:e.planId}}}function ao(t){const e=t?.operationContext?.source;if(e&&e.kind!=="unattributed")return e;if(t?.actor&&t.actor.kind!=="unattributed")return t.actor}function Ni(t,e){const n=t?.operationContext?.source??t?.actor,r=e?.operationContext?.source??e?.actor;return Kn({source:ao(t)??ao(e)??n??r??{kind:"unattributed"},authLens:e?.operationContext?.authLens??e?.authLens??t?.operationContext?.authLens??t?.authLens??{mode:"app-session"},...(t?.operationContext?.planId??t?.planId??e?.operationContext?.planId??e?.planId)===void 0?{}:{planId:t?.operationContext?.planId??t?.planId??e?.operationContext?.planId??e?.planId}})}function km(t){return Ni(void 0,t)}function Jc(t){return"rulesDisposition"in t&&t.rulesDisposition?t.rulesDisposition:t.kind==="operation"&&t.origin==="admin"?{kind:"bypassed",reason:"admin"}:t.detail?.admin===!0?{kind:"bypassed",reason:"admin"}:t.result==="unsupported"?{kind:"not-evaluated",reason:"unsupported"}:t.kind==="operation"&&t.result==="error"?{kind:"not-evaluated",reason:"runtime-error"}:t.kind==="operation"&&t.result==="not-applicable"?{kind:"not-evaluated",reason:"not-a-rules-operation"}:t.kind==="listener"?t.result==="deny"?{kind:"evaluated",verdict:"deny"}:t.error?.code==="PERMISSION_DENIED"?{kind:"evaluated",verdict:"deny"}:t.rules?{kind:"evaluated",verdict:"deny"}:{kind:"not-evaluated",reason:"runtime-error"}:t.result==="deny"?{kind:"evaluated",verdict:"deny"}:t.kind==="request"?{kind:"evaluated",verdict:"allow"}:"rules"in t&&t.rules?{kind:"evaluated",verdict:"allow"}:{kind:"not-evaluated",reason:"no-rules"}}function Om(t){if(t===null)return null;let e;return t.token!==void 0&&(e=Qc(t.token)),Object.freeze({uid:t.uid,...e===void 0?{}:{token:e}})}function Qc(t){const e={};for(const[n,r]of Object.entries(t))e[n]=Yc(r);return Object.freeze(e)}function Yc(t){return Array.isArray(t)?Object.freeze(t.map(Yc)):t&&typeof t=="object"?Qc(t):t}function Yg(t){if(!ei(t))return null;let e="listen",n;t.kind==="request"||t.kind==="operation"?(e=t.method,t.path!==void 0&&(n=t.path)):t.kind==="listener"&&(e="listen",t.target.path!==void 0&&(n=t.target.path));let r="firestore";return t.service!==void 0&&(r=t.service),Object.freeze({id:t.id,at:t.at,eventKind:t.kind,service:r,method:e,...n===void 0?{}:{path:n},auth:Om(t.auth),result:t.result,context:km(t),rules:Object.freeze({...Jc(t)})})}function oo(t){return t===null?{mode:"anon"}:t.token===void 0?{mode:"as",uid:t.uid}:{mode:"as",uid:t.uid,token:t.token}}class Zn{sandbox;auth;constructor(e,n,r){this.sandbox=e,this.auth=n,this.operationContext=Kn(r??{source:{kind:"unattributed"},authLens:oo(n)})}operationContext;withAuth(e){return ti(e),new Zn(this.sandbox,e,{source:this.operationContext.source,authLens:oo(e),...this.operationContext.planId===void 0?{}:{planId:this.operationContext.planId}})}}function Li(t,e){return new Zn(t.sandbox,t.auth,e)}function ti(t){if(t===null)return;if(t===void 0)throw new ie({code:"invalid-argument",message:"withAuth() requires an explicit AuthState argument.",remediation:["For anonymous (unauthenticated) access: withAuth(null)",'For authenticated access: withAuth({ uid: "someUid" })','For custom claims: withAuth({ uid: "someUid", token: { role: "admin" } })'].join(`
1252
- `)});if(typeof t!="object")throw new ie("invalid-argument","withAuth() expected null or an object with a `uid` field.");const e=t;if(typeof e.uid!="string"||e.uid.length===0)throw new ie("invalid-argument","withAuth() requires `uid` to be a non-empty string.");if("token"in e&&e.token!==void 0&&(e.token===null||typeof e.token!="object"||Array.isArray(e.token)))throw new ie("invalid-argument","withAuth() requires `token` (when present) to be a plain object.")}function Cm(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),n=e.length%4===0?"":"=".repeat(4-e.length%4),r=atob(e+n),s=new Uint8Array(r.length);for(let i=0;i<r.length;i++)s[i]=r.charCodeAt(i);return s}function Tm(t){const e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return n}function Fi(t){return ni(t,!0)}function ni(t,e){if(t===null||typeof t!="object")return t;if(Array.isArray(t)){const a=t.map(o=>ni(o,!1));return e&&ut(a,Ha(t)),a}const n=t,r=a=>(e&&ut(a,Ha(t)),a),s=(a,o)=>(tn(a,Object.freeze(o),()=>a),r(a));if(n.__type__==="__vector__"&&Array.isArray(n.value)){const a=Object.freeze(n.value.slice());return s(new en(a),{type:"vector",values:a})}if(typeof n.__type=="string")switch(n.__type){case"timestamp":return s(new xe(n.seconds,n.nanos),{type:"timestamp",seconds:n.seconds,nanoseconds:n.nanos});case"bytes":{const a=Cm(n.base64);return s(new We(a),{type:"bytes",values:Object.freeze(Array.from(a))})}case"latlng":return s(new ot(n.lat,n.lng),{type:"geo-point",latitude:n.lat,longitude:n.lng});case"duration":return r(new we(n.seconds,n.nanos));case"reference":return r(new zt(n.path));case"path":return r(new st(n.segments))}if(typeof n.type=="string")switch(n.type){case"firestore/timestamp/1.0":{const a=n.seconds,o=n.nanoseconds;return s(new xe(a,o),{type:"timestamp",seconds:a,nanoseconds:o})}case"firestore/bytes/1.0":{const a=Tm(n.bytes);return s(new We(a),{type:"bytes",values:Object.freeze(Array.from(a))})}case"firestore/geoPoint/1.0":return s(new ot(n.latitude,n.longitude),{type:"geo-point",latitude:n.latitude,longitude:n.longitude})}const i={};for(const[a,o]of Object.entries(n))i[a]=ni(o,!1);return r(i)}class Xn extends Error{constructor(e){super(e),this.name="PersistenceSchemaError"}}function Rm(t){let e;try{e=JSON.parse(t)}catch(s){throw new Xn(`Persisted blob is not valid JSON: ${s.message}`)}if(typeof e!="object"||e===null)throw new Xn("Persisted blob is not an object");if(e.version!==1&&e.version!==2)throw new Xn(`Persisted blob has version ${String(e.version)}, expected 1 or 2`);if(typeof e.firestore!="object"||e.firestore===null)throw new Xn("Persisted blob has no firestore field");const n={};for(const[s,i]of Object.entries(e.firestore))n[s]=Fi(i);const r=e.services!==void 0&&typeof e.services=="object"&&e.services!==null?e.services:{};return{firestore:n,services:r}}const Nm=3,Lm=256,ri="meta";function Fm(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%Lm).toString(16).padStart(2,"0")}function Dm(t){return JSON.parse(JSON.stringify(t))}function Xc(t){const e=JSON.stringify(t);let n=2166136261;for(let r=0;r<e.length;r++)n^=e.charCodeAt(r),n=Math.imul(n,16777619)>>>0;return n}function eu(t,e,n){const r=new Map;r.set(ri,{version:Nm,savedAt:n,services:e});for(const[s,i]of Object.entries(t)){const a=Fm(s);let o=r.get(a);o||(o={docs:{}},r.set(a,o)),o.docs[s]=Dm(i)}for(const[s,i]of r)s!==ri&&(i.checksum=Xc(i.docs));return r}const tu="pyric-v3-records";function Xg(t){return JSON.stringify({format:tu,records:Object.fromEntries(t)})}function ey(t){let e;try{e=JSON.parse(t)}catch{return new Map}const n=e;return n&&typeof n=="object"&&n.format===tu&&typeof n.records=="object"&&n.records!==null?new Map(Object.entries(n.records)):nu(t)??new Map}function nu(t){let e;try{e=Rm(t)}catch{return null}return eu(e.firestore,e.services,0)}function Mm(t){const e={};let n={};for(const[r,s]of t){if(r===ri){const a=s;a&&typeof a.services=="object"&&a.services!==null&&(n=a.services);continue}const i=s;if(!(!i||typeof i.docs!="object"||i.docs===null)){if(typeof i.checksum=="number"&&Xc(i.docs)!==i.checksum){console.warn(`[sandbox/persistence] checksum mismatch for bucket '${r}'; skipping corrupt bucket`);continue}for(const[a,o]of Object.entries(i.docs))e[a]=Fi(o)}}return{firestore:e,services:n}}const yn="snapshots";function co(){const t=new Map,e=n=>{let r=t.get(n);return r||(r=new Map,t.set(n,r)),r};return{async getRecord(n,r){const s=t.get(n)?.get(r);return s===void 0?null:structuredClone(s)},async listRecords(n){return[...t.get(n)?.keys()??[]]},async putRecords(n,r){const s=e(n);for(const[i,a]of r)s.set(i,structuredClone(a))},async deleteRecords(n,r){const s=t.get(n);if(s)for(const i of r)s.delete(i)},async clear(n){t.delete(n)}}}function ru(t){return new Promise((e,n)=>{const r=indexedDB.open(t,1);r.onupgradeneeded=()=>{const s=r.result;s.objectStoreNames.contains(yn)||s.createObjectStore(yn)},r.onsuccess=()=>e(r.result),r.onerror=()=>n(r.error??new Error(`Failed to open IndexedDB '${t}'`)),r.onblocked=()=>n(new Error(`IndexedDB open blocked for '${t}'`))})}function ps(t,e,n){return ru(t).then(r=>new Promise((s,i)=>{const a=r.transaction(yn,e),o=a.objectStore(yn),c=n(o);let u=null;c&&(c.onsuccess=()=>{u=c.result??null},c.onerror=()=>i(c.error)),a.oncomplete=()=>{r.close(),s(u)},a.onerror=()=>{r.close(),i(a.error)},a.onabort=()=>{r.close(),i(a.error??new Error("IndexedDB transaction aborted"))}}))}function uo(t,e){return ru(t).then(n=>new Promise((r,s)=>{const i=n.transaction(yn,"readwrite");e(i.objectStore(yn)),i.oncomplete=()=>{n.close(),r()},i.onerror=()=>{n.close(),s(i.error)},i.onabort=()=>{n.close(),s(i.error??new Error("IndexedDB transaction aborted"))}}))}function jm(){if(typeof indexedDB>"u")throw new Error('IndexedDB is not available in this environment. Use { backend: "memory" } or supply an injectedBackend.');return{async getRecord(t,e){return await ps(t,"readonly",r=>r.get(e))??null},async listRecords(t){return(await ps(t,"readonly",n=>n.getAllKeys())??[]).map(n=>String(n))},async putRecords(t,e){await uo(t,n=>{for(const[r,s]of e)n.put(s,r)})},async deleteRecords(t,e){await uo(t,n=>{for(const r of e)n.delete(r)})},async clear(t){await ps(t,"readwrite",e=>e.clear())},async estimate(){if(typeof navigator>"u"||!navigator.storage?.estimate)return null;const t=await navigator.storage.estimate();return{usage:t.usage??0,quota:t.quota??0}}}}const Pm=250,lo="pyric:sandbox:auth-session";function ms(t){return t==="auth"||t==="auth-session:[DEFAULT]"?lo:`${lo}:${encodeURIComponent(t)}`}function su(t){const e=JSON.stringify(t);let n=2166136261;for(let r=0;r<e.length;r++)n^=e.charCodeAt(r),n=Math.imul(n,16777619)>>>0;return n}function $m(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 qm(t){return t.injectedBackend?t.injectedBackend:(t.backend??"indexedDB")==="memory"||typeof indexedDB>"u"?co():jm()}async function Um(t,e){const n={...e,flushIntervalMs:e.flushIntervalMs??Pm,backend:e.backend??"indexedDB"},r=qm(n),s=new Map,i=await Bm(t,r,n.key,s);let a=null,o=!1;const c=new Map,u=async()=>{if(o)return;const _=t.snapshot(),v=eu(_.firestore,_.services,Date.now()),A=new Map,x=new Map;for(const[h,g]of v){const m=su(g);x.set(h,m),s.get(h)!==m&&A.set(h,g)}const f=[...s.keys()].filter(h=>!v.has(h));A.size>0&&await r.putRecords(n.key,A),f.length>0&&await r.deleteRecords(n.key,f),s.clear();for(const[h,g]of x)s.set(h,g)};let d=Promise.resolve();const l=()=>(a&&(clearTimeout(a),a=null),d=d.then(u,u),d),p=()=>{o||a||(a=setTimeout(()=>{a=null,l().catch(_=>{if($m(_)){console.warn("[sandbox/persistence] storage quota exceeded; recent changes are kept in memory only. Free storage or reduce sandbox data to persist them.");return}console.warn("[sandbox/persistence] auto-flush failed, will retry:",_),p()})},n.flushIntervalMs))},y=(_,v)=>{if(!v.subscribe||c.has(_))return;const A=v.subscribe(()=>{p()});c.set(_,A)},b=new Map,w=new Map,R=(_,v)=>{if(!n.sessionStorage)return;const{local:A,session:x}=n.sessionStorage,f=ms(_),h=v.currentUid(),g=v.mode();if(h===null||g==="NONE"){A.removeItem(f),x.removeItem(f);return}const m=JSON.stringify({uid:h});g==="LOCAL"?(x.removeItem(f),A.setItem(f,m)):(A.removeItem(f),x.setItem(f,m))},C=_=>{if(!n.sessionStorage)return null;const v=ms(_);for(const[A,x]of[["LOCAL",n.sessionStorage.local],["SESSION",n.sessionStorage.session]]){const f=x.getItem(v);if(f)try{const h=JSON.parse(f);if(typeof h?.uid=="string")return{uid:h.uid,mode:A}}catch{x.removeItem(v)}}return null},I=_=>{if(!n.sessionStorage)return;const v=ms(_);n.sessionStorage.local.removeItem(v),n.sessionStorage.session.removeItem(v)},E=(_,v,A)=>{if(A.session)try{A.session.restore(v.uid,v.mode),w.delete(_)}catch(x){console.warn(`[sandbox/persistence] session restore for uid '${v.uid}' failed — clearing stored session:`,x),I(_),w.delete(_)}},N=(_,v)=>{if(!n.sessionStorage||!v.session||b.has(_))return;const A=v.session;b.set(_,A.subscribe(()=>R(_,A)))},q=(_,v)=>{if(!v.session)return;const A=w.get(_)??C(_);A&&E(_,A,v)};if(t instanceof Nt){for(const[_,v]of t.getServiceRegistry())y(_,v),q(_,v),N(_,v);t.setServiceRegistrationHook((_,v)=>{if(i!==null&&_ in i)try{v.restore(i[_])}catch(x){console.warn(`[sandbox/persistence] late-restore for service '${_}' failed:`,x)}const A=C(_);A&&w.set(_,A),q(_,v),y(_,v),N(_,v),p()}),t.setServiceUnregistrationHook(_=>{c.get(_)?.(),c.delete(_),b.get(_)?.(),b.delete(_),w.delete(_),p()})}const S=t.onEvent(_=>{zm(_)&&p()}),k=()=>{l().catch(()=>{})};return typeof window<"u"&&window.addEventListener("beforeunload",k),{options:n,flush:l,async clear(){a&&(clearTimeout(a),a=null),await r.clear(n.key),s.clear()},dispose(){if(!o){o=!0,a&&(clearTimeout(a),a=null),S();for(const _ of c.values())_();c.clear();for(const _ of b.values())_();b.clear(),t instanceof Nt&&(t.setServiceRegistrationHook(null),t.setServiceUnregistrationHook(null)),typeof window<"u"&&window.removeEventListener("beforeunload",k)}}}}async function Bm(t,e,n,r){let s;try{s=await e.listRecords(n)}catch(d){return console.warn("[sandbox/persistence] backend list failed:",d),null}if(s.length===0)return null;const i=[];for(const d of s)try{const l=await e.getRecord(n,d);l!==null&&i.push([d,l])}catch(l){console.warn(`[sandbox/persistence] failed to read persisted record '${d}':`,l)}const a=[],o=[];let c=null;for(const[d,l]of i)if(typeof l=="string"){const p=nu(l);p&&(o.push(d),c=p)}else a.push([d,l]);if(c){try{await e.putRecords(n,c),o.length>0&&await e.deleteRecords(n,o)}catch(d){console.warn("[sandbox/persistence] v2 migration write failed:",d)}for(const[d,l]of c)a.push([d,l])}for(const[d,l]of a)r.set(d,su(l));const u=Mm(a);for(const[d,l]of Object.entries(u.firestore))t.admin.setDocument(d,l);if(t instanceof Nt){const d=t.getServiceRegistry();for(const[l,p]of Object.entries(u.services)){const y=d.get(l);if(y)try{y.restore(p)}catch(b){console.warn(`[sandbox/persistence] service '${l}' restore failed — Firestore state is intact; auth users may need to be re-created:`,b)}}}return u.services}function zm(t){return t.kind==="write"||t.kind==="session_boundary"}function Vm(t){return typeof t=="object"&&t!==null&&typeof t.kind=="string"&&typeof t.origin=="string"}let Wm=0;function Hm(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`tab-${crypto.randomUUID()}`:`tab-${++Wm}-${typeof performance<"u"?performance.now().toFixed(3):String(Date.now())}`}function Gm(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??Hm();let i=!1,a=!1;const o=t.onEvent(l=>{if(l.kind!=="write"||i)return;const p={kind:"write",origin:s,event:l};n.postMessage(p)}),c=l=>{if(!Vm(l.data))return;const p=l.data;if(p.origin!==s){if(p.kind==="write")d(p.event);else if(p.kind==="hello"){const y={kind:"state",origin:s,to:p.origin,snapshot:t.snapshot()};n.postMessage(y)}else if(p.kind==="state"){if(p.to!==s||a)return;if(Object.keys(Xe(t).snapshot()).length>0){a=!0;return}i=!0;try{for(const[b,w]of Object.entries(p.snapshot.firestore))t.admin.setDocument(b,w)}finally{i=!1}a=!0}}};n.addEventListener("message",c);const u={kind:"hello",origin:s};return n.postMessage(u),()=>{o(),n.removeEventListener("message",c),r&&n.close()};function d(l){i=!0;try{if(l.method==="delete")t.admin.deleteDocument(l.path);else{const p=l.nextState;p!=null&&t.admin.setDocument(l.path,p)}}finally{i=!1}}}function Km(t,e){const n={...t};n.service=t.service??e?.service??"firestore";const s="detail"in t&&t.detail?.admin===!0&&t.operationContext===void 0&&t.authLens===void 0?{...t,authLens:{mode:"admin"}}:t,i=ei(n)||t.operationContext!==void 0?Ni(e,s):Zm(t,e);return n.operationContext=i,n.actor=i.source,n.authLens=i.authLens,i.planId!==void 0&&(n.planId=i.planId),e?.activity!==void 0&&(n.activity={...n.activity,...e.activity}),ei(n)&&(n.rulesDisposition=Object.freeze({...Jc(n)})),n}function Zm(t,e){return Kn({source:t.actor??t.operationContext?.source??e?.actor??e?.operationContext?.source??{kind:"unattributed"},authLens:t.authLens??t.operationContext?.authLens??e?.authLens??e?.operationContext?.authLens??{mode:"app-session"},...(t.planId??t.operationContext?.planId??e?.planId??e?.operationContext?.planId)===void 0?{}:{planId:t.planId??t.operationContext?.planId??e?.planId??e?.operationContext?.planId}})}function Jm(t,e){if(!t)return e;if(!e)return t;if(e.operationContext!==void 0)return iu(t,e);if(!(t.operationContext!==void 0||t.actor!==void 0||t.authLens!==void 0||t.planId!==void 0||e.actor!==void 0||e.authLens!==void 0||e.planId!==void 0))return{...t,...e};const r=Kn({source:e.actor??t.operationContext?.source??t.actor??{kind:"unattributed"},authLens:e.authLens??t.operationContext?.authLens??t.authLens??{mode:"app-session"},...(e.planId??t.operationContext?.planId??t.planId)===void 0?{}:{planId:e.planId??t.operationContext?.planId??t.planId}});return{...t,...e,operationContext:r,actor:r.source,authLens:r.authLens,...r.planId===void 0?{}:{planId:r.planId}}}function iu(t,e){if(!t)return e;if(!e)return t;if(!(t.operationContext!==void 0||t.actor!==void 0||t.authLens!==void 0||t.planId!==void 0||e.operationContext!==void 0||e.actor!==void 0||e.authLens!==void 0||e.planId!==void 0))return{...t,...e};const r=Ni(t,e);return{...t,...e,operationContext:r,actor:r.source,authLens:r.authLens,...r.planId===void 0?{}:{planId:r.planId}}}let Qm=1;function Bt(){const t=(Qm++).toString(36),e=Math.random().toString(36).slice(2,7);return`sbe-${t}-${e}`}class Nt{_env;eventSubs=new Set;envUnsubs=[];dispatchedCount=0;eventHistory=[];ambientProvenance;_currentUser=null;currentUserSubs=new Set;persistence=null;enablePersistencePromise=null;serviceRegistry=new Map;_onServiceRegistered=null;_onServiceUnregistered=null;constructor(e){this._env=e,this.attachToEnv()}static createRoot(){return new Nt(new io)}getEnv(){return this._env}withAuth(e){return ti(e),new Zn(this,e)}attachToEnv(){this.envUnsubs.push(this._env.onRequest(e=>{this.emitEvent(e)})),this.envUnsubs.push(this._env.onWrite(e=>{this.emitEvent(e)})),this.envUnsubs.push(this._env.onSnapshotDelivery(e=>this.emitEvent(e))),this.envUnsubs.push(this._env.onSnapshotSuppressed(e=>this.emitEvent(e))),this.envUnsubs.push(this._env.onListenerLifecycle(e=>this.emitEvent(e))),this.envUnsubs.push(this._env.onSnapshotError((e,n,r)=>{const s={kind:"listener_errored",id:Bt(),at:Date.now(),listenerId:r,target:n.kind==="doc"?{kind:"doc",path:n.path}:{kind:"query",collection:n.collection},auth:e.request?.auth??null,error:{code:"permission-denied",message:e.message}};this.emitEvent(s)}))}emitEvent(e,n){const r=iu(this.ambientProvenance,n);this.dispatch(Km(e,r))}runWithProvenance(e,n){const r=this.ambientProvenance;this.ambientProvenance=Jm(r,e);try{return n()}finally{this.ambientProvenance=r}}dispatch(e){if(this.eventHistory.push(e),this.dispatchedCount++,this.eventSubs.size!==0)for(const n of this.eventSubs)try{const r=n(e);r&&typeof r.then=="function"&&r.catch(()=>{})}catch{}}emitInternal(e,n){this.emitEvent(e,n)}onEvent(e){return this.eventSubs.add(e),()=>{this.eventSubs.delete(e)}}history(){return[...this.eventHistory]}primeEventHistory(e){return this.eventHistory.length>0||e.length===0?0:(this.eventHistory.push(...e),e.length)}get admin(){return{getDocument:e=>this._env.getDocument(e),listDocuments:e=>this._env.listDocuments(e),setDocument:(e,n)=>this._env.adminSetDocument(e,n),deleteDocument:e=>this._env.adminDeleteDocument(e)}}reset(){const e={kind:"session_boundary",id:Bt(),at:Date.now(),phase:"reset",priorOpCount:this.dispatchedCount};this.emitEvent(e),this.eventHistory=[],this._currentUser!==null&&(this._currentUser=null,this.notifyCurrentUserSubs(null));for(const n of this.envUnsubs)n();this.envUnsubs=[],this._env.dispose(),this._env=new io,this.attachToEnv()}async resetAll(){this.reset();const e=[],n=[];for(const[r,s]of this.serviceRegistry)s.reset&&n.push(Promise.resolve().then(()=>s.reset()).catch(i=>{e.push(`${r}: ${i instanceof Error?i.message:String(i)}`)}));return await Promise.all(n),{errors:e}}dispose(){const e={kind:"session_boundary",id:Bt(),at:Date.now(),phase:"dispose",priorOpCount:this.dispatchedCount};this.emitEvent(e);for(const n of this.envUnsubs)n();this.envUnsubs=[],this._env.dispose(),this.persistence&&(this.persistence.dispose(),this.persistence=null),this.serviceRegistry.clear(),this._onServiceRegistered=null,this._onServiceUnregistered=null,this.eventSubs.clear(),this.currentUserSubs.clear()}snapshot(){const e={};for(const[n,r]of this.serviceRegistry)e[n]=r.snapshot();return{firestore:this._env.snapshot(),services:e}}loadSnapshot(e){this.reset();for(const[n,r]of Object.entries(e.firestore))this._env.adminSetDocument(n,r);for(const[n,r]of this.serviceRegistry)if(n in e.services)try{r.restore(e.services[n])}catch(s){console.warn(`[sandbox] loadSnapshot: service '${n}' restore failed — Firestore is intact; that service's state may be incomplete:`,s)}}get currentUser(){return this._currentUser}set currentUser(e){ti(e),!Ym(this._currentUser,e)&&(this._currentUser=e,this.notifyCurrentUserSubs(e))}onCurrentUserChanged(e){return this.currentUserSubs.add(e),()=>{this.currentUserSubs.delete(e)}}notifyCurrentUserSubs(e){if(this._env.reevaluateLiveListeners(e),this.currentUserSubs.size!==0)for(const n of this.currentUserSubs)try{const r=n(e);r&&typeof r.then=="function"&&r.catch(()=>{})}catch{}}async enablePersistence(e){if(this.persistence){if(this.persistence.options.key!==e.key)throw new ie("failed-precondition",`Persistence already enabled with key '${this.persistence.options.key}'; cannot re-enable with key '${e.key}'. Dispose and recreate the sandbox.`);return}if(this.enablePersistencePromise)return this.enablePersistencePromise;this.enablePersistencePromise=(async()=>{const n=await Um(this,e);this.persistence=n})();try{await this.enablePersistencePromise}finally{this.enablePersistencePromise=null}}enableTabSync(e){return Gm(this,e)}async flush(){if(!this.persistence)throw new ie("failed-precondition","flush() called before enablePersistence()");await this.persistence.flush()}async clearPersistence(){this.persistence&&await this.persistence.clear()}registerPersistableService(e,n){if(this.serviceRegistry.has(e))throw new ie("failed-precondition",`registerPersistableService: a service named '${e}' is already registered on this sandbox. Each service name must be unique — the auth package registers 'auth' exactly once per sandbox.`);return this.serviceRegistry.set(e,n),this._onServiceRegistered&&this._onServiceRegistered(e,n),()=>{this.serviceRegistry.get(e)===n&&(this.serviceRegistry.delete(e),this._onServiceUnregistered?.(e))}}setServiceRegistrationHook(e){this._onServiceRegistered=e}setServiceUnregistrationHook(e){this._onServiceUnregistered=e}getServiceRegistry(){return this.serviceRegistry}}function Ym(t,e){if(t===e)return!0;if(t===null||e===null||t.uid!==e.uid)return!1;const n=t.token===void 0?void 0:JSON.stringify(t.token),r=e.token===void 0?void 0:JSON.stringify(e.token);return n===r}function Xe(t){if(!(t instanceof Nt))throw new ie("invalid-argument","Sandbox handle was not produced by initializeSandbox(); custom Sandbox implementations are not supported.");return t.getEnv()}function ty(t,e,n){if(!(t instanceof Nt))throw new ie("invalid-argument","Sandbox handle was not produced by initializeSandbox(); custom Sandbox implementations are not supported.");t.emitInternal(e,n)}function ny(t){return{kind:"service_mutation",id:Bt(),at:Date.now(),...t}}function ry(t){const{at:e,...n}=t;return{kind:"operation",id:Bt(),at:e??Date.now(),...n}}function sy(t){const{at:e,...n}=t;return{kind:"commit",id:Bt(),at:e??Date.now(),...n}}function iy(t){const{at:e,...n}=t;return{kind:"listener",id:Bt(),at:e??Date.now(),...n}}function ay(){return Nt.createRoot()}const Xm=Symbol.for("pyric.remote.sandbox");function Di(t){return t!=null&&t[Xm]===!0}const eg={read:new Set(["auth","data","root","now"]),write:new Set(["auth","data","newData","root","now"]),validate:new Set(["auth","data","newData","root","now"])},tg=new Set(["val","exists","hasChild","hasChildren","isString","isNumber","isBoolean","child","parent","getPriority"]),ng=new Set(["matches","contains","beginsWith","endsWith","replace","toLowerCase","toUpperCase","length"]),rg=new Set([...tg,...ng]);let Fn=[],ar="read",au=new Set,gs;function sg(){if(gs)return gs;const t=Bf();return t.addOperation("validate",{_nonterminal(...e){e.forEach(n=>n.validate())},_iter(...e){e.forEach(n=>n.validate())},_terminal(){},CallExpr_methodCall(e,n,r,s,i,a){e.validate();const o=r.sourceString;rg.has(o)||Fn.push({code:"UNKNOWN_METHOD",message:`Unknown method '${o}'`}),i.asIteration().children.forEach(c=>c.validate())},CallExpr_memberAccess(e,n,r){e.validate()},CallExpr_indexAccess(e,n,r,s){e.validate(),r.validate()},ident(e,n,r){const s=this.sourceString;if(e.sourceString==="$")return;const a=eg[ar];a&&(!a.has(s)&&!au.has(s)&&Fn.push({code:"UNKNOWN_IDENTIFIER",message:`Identifier '${s}' is not allowed in '${ar}' context`}),s==="newData"&&ar==="read"&&Fn.push({code:"NEWDATA_IN_READ",message:"'newData' is not available in 'read' context"}))}}),gs=t,t}function oy(t,e,n=[]){const r=Uf(t);return r.failed()?[]:(Fn=[],ar=e,au=new Set(n.map(s=>s.startsWith("$")?s.slice(1):s)),sg()(r).validate(),[...Fn])}const cy=He({operation:mn(["read","write","validate"]),path:qe().min(1).startsWith("/"),auth:Kr([He({uid:qe(),token:Tt(mt())}),Ac()]),mockData:Tt(mt()),newData:mt().optional(),updates:xc(He({path:qe().min(1).startsWith("/"),value:mt()})).optional()});mn(["INVALID_INPUT","NO_MATCHING_RULE","EVALUATION_ERROR"]);He({allowed:$n(),unsupported:$n().optional(),matchedPath:qe(),matchedRule:qe(),reason:qe(),pathVariableBindings:Tt(qe())});const ho="-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz";let fo=0;const jt=new Array(12).fill(0);function uy(t=Date.now()){const e=t===fo;fo=t;const n=new Array(8);let r=t;for(let i=7;i>=0;i--)n[i]=ho.charAt(r%64),r=Math.floor(r/64);if(r!==0)throw new Error("RTDB push-id: timestamp overflow.");let s=n.join("");if(e){let i;for(i=11;i>=0&&jt[i]===63;i--)jt[i]=0;if(i<0)for(let a=0;a<12;a++)jt[a]=Math.floor(Math.random()*64);else jt[i]=(jt[i]??0)+1}else for(let i=0;i<12;i++)jt[i]=Math.floor(Math.random()*64);for(let i=0;i<12;i++)s+=ho.charAt(jt[i]);if(s.length!==20)throw new Error(`RTDB push-id: bad length ${s.length}.`);return s}function Un(t){return t.replace(/^\/+|\/+$/g,"").split("/")}function ou(t){return Un(t).length%2===0&&Un(t).length>0}function Mi(t){return Un(t).length%2===1}function Yr(t){const e=Un(t);return e[e.length-1]??""}function cu(t){return Un(t).slice(0,-1).join("/")}function uu(t,e){const n=e!==void 0,r=n?Gn(e):void 0;return{id:t.id,ref:t,exists:n,data:()=>n?r:void 0,get:s=>wn(r,s)}}const po=new WeakMap;let ig=1;function mo(t){let e=po.get(t);return e===void 0&&(e=ig++,po.set(t,e)),e}function $r(t){if(t===null||typeof t=="boolean")return t;if(typeof t=="string")return Op(t);if(typeof t>"u")return{type:"undefined"};if(typeof t=="bigint")return Zt("bigint",t.toString());if(typeof t=="number"){const n=Number.isNaN(t)?"NaN":t===1/0?"Infinity":t===-1/0?"-Infinity":Object.is(t,-0)?"-0":String(t);return Zt("number",n)}if(typeof t!="object"&&typeof t!="function")return{type:typeof t,value:String(t)};const e=Tp(t);if(e!==void 0)return e;try{if(Array.isArray(t))return{type:"array",id:mo(t)}}catch{}return{type:"opaque-object",id:mo(t)}}function _t(t){return new ue({code:"invalid-argument",message:t})}function si(t,e,n,r=!1,s=!1){if(t===null||typeof t=="string"||typeof t=="boolean")return{comparison:t,execution:t};if(typeof t=="number")return{comparison:t,execution:t};if(typeof t>"u"||typeof t=="bigint"||typeof t=="function"||typeof t=="symbol")throw _t(`Unsupported Firestore query value: ${typeof t}.`);if(typeof t!="object")throw _t("Unsupported Firestore query value.");const i=kc(t);if(i!==void 0){const o=np(t);if(o!==void 0&&n!==void 0&&o!==n)throw _t("Document reference belongs to a different Firestore database.");return{comparison:{type:"registered-firestore-value",value:i},execution:rp(t)}}if(t instanceof Date){const o=t.getTime();if(!Number.isFinite(o))throw _t("Invalid Date query value.");const c=Math.floor(o/1e3),u=Object.freeze({seconds:c,nanoseconds:Math.floor((o-c*1e3)*1e6)}),d={type:"timestamp",...u};return tn(u,d,()=>Object.freeze({...u})),{comparison:{type:"registered-firestore-value",value:d},execution:u}}if(t instanceof Uint8Array){const o=t.slice();return{comparison:{type:"bytes",values:Array.from(o)},execution:o}}if(e.has(t))throw _t("Cyclic query operands are not Firestore values.");const a=Object.getPrototypeOf(t);if(a!==Object.prototype&&a!==null&&!Array.isArray(t))throw _t("Firestore query maps must be plain objects.");e.add(t);try{if(Array.isArray(t)){if(s&&!r)throw _t("Nested arrays are not supported.");const u=t.map(l=>si(l,e,n,r,!0)),d=u.map(l=>l.execution);return ut(d,$r(t)),{comparison:{type:"array",values:u.map(l=>l.comparison)},execution:d}}const o=Object.keys(t).sort().map(u=>({key:u,captured:si(t[u],e,n,r,!1)})),c=Object.fromEntries(o.map(({key:u,captured:d})=>[u,d.execution]));return ut(c,$r(t)),{comparison:{type:"map",entries:o.map(({key:u,captured:d})=>[u,d.comparison])},execution:c}}finally{e.delete(t)}}function lu(t,e,n=!1){try{const r=si(t,new Set,e,n);return Object.freeze({kind:"canonical",value:r.comparison,executionValue:r.execution})}catch(r){if(r instanceof ue)throw r;const s=r instanceof Error?r.message:String(r);throw _t(`Invalid Firestore query value: ${s}`)}}function du(t,e){return Ye(t.value,e.value)}function or(t,e){if(t.kind==="where"){const n="comparisonValue"in t?t.comparisonValue:lu(t.value,e,t.op==="in"||t.op==="not-in");return Object.freeze({kind:"where",field:t.field,op:t.op,value:n.executionValue,comparisonValue:n})}return Object.freeze({kind:t.kind,filters:Object.freeze(t.filters.map(n=>or(n,e)))})}function er(t,e,n,r){const s=t.map(i=>lu(i,r));return Object.freeze({values:Object.freeze(s.map(i=>i.executionValue)),comparisonValues:Object.freeze(s),inclusive:e,fromSnapshot:n})}function hu(t,e){return t.length!==e.length?!1:t.every((n,r)=>{const s=e[r];return n.kind!==s.kind?!1:n.kind==="where"&&s.kind==="where"?n.field===s.field&&n.op===s.op&&du(n.comparisonValue,s.comparisonValue):n.kind!=="where"&&s.kind!=="where"&&hu(n.filters,s.filters)})}function go(t,e){return t===void 0||e===void 0?t===e:t.inclusive===e.inclusive&&t.comparisonValues.length===e.comparisonValues.length&&t.comparisonValues.every((n,r)=>du(n,e.comparisonValues[r]))}function ag(t,e){return t.kind!==e.kind?!1:t.kind==="collection"&&e.kind==="collection"?t.path===e.path:t.kind==="collection-group"&&e.kind==="collection-group"&&t.collectionId===e.collectionId}function fu(t){return t.kind==="where"?Object.freeze({kind:t.kind,field:t.field,op:t.op,value:t.value}):Object.freeze({kind:t.kind,filters:Object.freeze(t.filters.map(fu))})}function yo(t){if(t!==void 0)return Object.freeze({values:t.values,inclusive:t.inclusive,fromSnapshot:t.fromSnapshot})}function og(t,e){return hu(t.filters,e.filters)&&t.orders.length===e.orders.length&&t.orders.every((n,r)=>{const s=e.orders[r];return n.field===s.field&&n.direction===s.direction})&&t.limitCount===e.limitCount&&t.limitFromEnd===e.limitFromEnd&&go(t.start,e.start)&&go(t.end,e.end)}const pu="__name__";function bo(t,e){const n=t.data();if(n===void 0)throw new ue({code:"not-found",message:`Snapshot-based cursors require an existing document — got an empty snapshot for ${t.id??"<unknown>"}.`});return e.map(r=>r.field===pu?t.ref:n[r.field])}class Bn{env;auth;collectionPath;clauses;orders;limitCount;limitFromEnd;start;end;bypassRules;documentRef;constructor(e){this.env=e.env,this.auth=e.auth,this.collectionPath=e.collectionPath,this.documentRef=e.documentRef,this.clauses=Object.freeze((e.clauses??[]).map(n=>or(n))),this.orders=Object.freeze((e.orders??[]).map(n=>Object.freeze({...n}))),this.limitCount=e.limitCount,this.limitFromEnd=e.limitFromEnd??!1,this.start=e.start===void 0?void 0:Object.freeze({...e.start,values:Object.freeze(e.start.comparisonValues.map(n=>n.executionValue)),comparisonValues:e.start.comparisonValues}),this.end=e.end===void 0?void 0:Object.freeze({...e.end,values:Object.freeze(e.end.comparisonValues.map(n=>n.executionValue)),comparisonValues:e.end.comparisonValues}),this.bypassRules=e.bypassRules??!1}where(e,n,r){return this.clone({clauses:[...this.clauses,or({kind:"where",field:e,op:n,value:r})]})}applyFilter(e){return this.clone({clauses:[...this.clauses,or(e)]})}orderBy(e,n="asc"){return this.clone({orders:[...this.orders,{field:e,direction:n}]})}limit(e){return this.clone({limitCount:e,limitFromEnd:!1})}limitToLast(e){return this.clone({limitCount:e,limitFromEnd:!0})}startCursor(e,n){return this.clone({start:er(this.normalizeExplicitCursorValues(e),n,!1)})}endCursor(e,n){return this.clone({end:er(this.normalizeExplicitCursorValues(e),n,!1)})}startCursorFromSnapshot(e,n){return this.clone({start:er(bo(e,this.normalizedOrders()),n,!0)})}endCursorFromSnapshot(e,n){return this.clone({end:er(bo(e,this.normalizedOrders()),n,!0)})}isStructurallyEqual(e){return e instanceof Bn?this.env===e.env&&this.bypassRules===e.bypassRules&&ag(this.queryScope(),e.queryScope())&&og(this.comparableExecutionSpec(),e.comparableExecutionSpec()):!1}clone(e){return new Bn({env:this.env,auth:this.auth,collectionPath:this.collectionPath,documentRef:this.documentRef,clauses:e.clauses??this.clauses,orders:e.orders??this.orders,limitCount:"limitCount"in e?e.limitCount:this.limitCount,limitFromEnd:e.limitFromEnd??this.limitFromEnd,start:"start"in e?e.start:this.start,end:"end"in e?e.end:this.end,bypassRules:this.bypassRules})}queryScope(){return{kind:"collection",path:this.collectionPath}}readQueryRows(e){const n=e?.auth!==void 0?e.auth:this.auth;let r;try{r=this.env.runQuery({scope:this.queryScope(),auth:n,execution:this.executionSpec(),bypassRules:this.bypassRules,activityQuery:this.activityQuery()})}catch(s){const i=s?.simError;throw i?new ue(i):s}if(!r.allowed)throw new ue(r.error);return r.docs}activityQuery(){const e=r=>r.kind==="where"?{kind:"where",field:r.field,op:r.op,value:$r(r.value)}:{kind:r.kind,filters:r.filters.map(e)},n=r=>r===void 0?null:{values:r.values.map(s=>$r(s)),inclusive:r.inclusive,fromSnapshot:r.fromSnapshot};return{scope:this.activityScope(),filters:this.clauses.map(e),orderBy:this.orders.map(r=>({...r})),limit:this.limitCount??null,limitFromEnd:this.limitFromEnd,start:n(this.start),end:n(this.end)}}activityScope(){return{kind:"collection"}}normalizedOrders(){return Wc(this.executionSpec())}normalizeExplicitCursorValues(e){const n=this.orders;return e.map((r,s)=>{if(n[s]?.field!==pu)return r;if(typeof r!="string")throw new ue({code:"invalid-argument",message:"Expected a string for a document ID cursor value."});const i=r.includes("/")?r:`${this.collectionPath}/${r}`;return this.documentRef(i)})}executionSpec(){const e={filters:Object.freeze(this.clauses.map(fu)),orders:this.orders,limitCount:this.limitCount,limitFromEnd:this.limitFromEnd,start:yo(this.start),end:yo(this.end)};return Object.freeze(e)}comparableExecutionSpec(){return{filters:this.clauses,orders:this.orders,limitCount:this.limitCount,limitFromEnd:this.limitFromEnd,start:this.start,end:this.end}}snapshotConstraints(){return Object.freeze({execution:this.executionSpec(),activityQuery:this.activityQuery()})}async get(e){const r=this.readQueryRows(e).map(s=>{const i=this.documentRef(s.path),a=Gn(s.data);return{id:i.id,ref:i,exists:!0,data:()=>a,get:o=>wn(a,o)}});return{size:r.length,empty:r.length===0,docs:r,forEach(s){r.forEach(s)}}}async aggregate(e,n){const r=this.readQueryRows(n),s={};for(const i of Object.keys(e))s[i]=ug(e[i],r);return{data:()=>s}}}function cg(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 ug(t,e){if(t.kind==="count")return e.length;let n=0,r=0;for(const s of e){const i=cg(s.data,t.field);typeof i=="number"&&Number.isFinite(i)&&(n+=i,r++)}return t.kind==="sum"?n:r===0?null:n/r}function sn(t,e){if(t.error)throw new ue(t.error);const n=t.debugMessages.length>0?t.debugMessages.join("; "):"(no debug message)";throw new ue(te("permission-denied",`${e}: ${n}`))}class lg{env;auth;bypassRules;collectionRef;id;path;constructor(e,n,r,s=!1,i){this.env=e,this.auth=n,this.bypassRules=s,this.collectionRef=i,this.path=r,this.id=Yr(r),ut(this,Zt("reference",r)),Ei(this,r,e)}get parent(){return this.collectionRef(cu(this.path))}collection(e){return this.collectionRef(`${this.path}/${e}`)}async get(e){const n=this.env.execute({method:"get",path:this.path,auth:e?.auth!==void 0?e.auth:this.auth,bypassRules:this.bypassRules});n.allowed||sn(n,"get denied");const r=n.data===void 0||n.data===null?void 0:n.data;return uu(this,r)}async set(e,n){const r=n?.auth!==void 0?n.auth:this.auth;if(n?.mergeFields!==void 0){const i=n.mergeFields.map(u=>String(u)),o=this.env.getDocument(this.path)===null?"create":"update",c=this.env.execute({method:o,path:this.path,data:e,auth:r,merge:{mergeFields:i},bypassRules:this.bypassRules});c.allowed||sn(c,`set denied (as ${o})`);return}if(n?.merge===!0){const a=this.env.getDocument(this.path)===null?"create":"update",o=this.env.execute({method:a,path:this.path,data:e,auth:r,merge:!0,bypassRules:this.bypassRules});o.allowed||sn(o,`set denied (as ${a})`);return}const s=this.env.execute({method:"set",path:this.path,data:e,auth:r,bypassRules:this.bypassRules});s.allowed||sn(s,"set denied")}async update(e,n){const r=this.env.execute({method:"update",path:this.path,data:e,auth:n?.auth!==void 0?n.auth:this.auth,bypassRules:this.bypassRules});r.allowed||sn(r,"update denied")}async delete(e){const n=this.env.execute({method:"delete",path:this.path,auth:e?.auth!==void 0?e.auth:this.auth,bypassRules:this.bypassRules});n.allowed||sn(n,"delete denied")}}function qr(t,e,n,r){return new lg(t,e,n,r,s=>new mu(t,e,s,r))}class mu extends Bn{id;path;constructor(e,n,r,s=!1){super({env:e,auth:n,collectionPath:r,bypassRules:s,documentRef:i=>qr(e,n,i,s)}),this.path=r,this.id=Yr(r)}doc(e){const n=e??Ti();return qr(this.env,this.auth,`${this.path}/${n}`,this.bypassRules)}async add(e,n){const r=this.doc();return await r.set(e,n),r}}class ji extends Bn{collectionId;constructor(e){super({...e,collectionPath:"",documentRef:n=>qr(e.env,e.auth,n,e.bypassRules??!1)}),this.collectionId=e.collectionId}clone(e){return new ji({env:this.env,auth:this.auth,collectionId:this.collectionId,clauses:e.clauses??this.clauses,orders:e.orders??this.orders,limitCount:"limitCount"in e?e.limitCount:this.limitCount,limitFromEnd:e.limitFromEnd??this.limitFromEnd,start:"start"in e?e.start:this.start,end:"end"in e?e.end:this.end,bypassRules:this.bypassRules})}queryScope(){return{kind:"collection-group",collectionId:this.collectionId}}activityScope(){return{kind:"collection-group"}}}class dg{env;auth;bypassRules;ops=[];constructor(e,n,r=!1){this.env=e,this.auth=n,this.bypassRules=r}set(e,n){const s=this.env.getDocument(e.path)===null?"create":"update";return this.ops.push({method:s,path:e.path,data:n}),this}update(e,n){return this.ops.push({method:"update",path:e.path,data:n}),this}delete(e){return this.ops.push({method:"delete",path:e.path}),this}async commit(e){if(this.ops.length===0)return;const n=this.env.batch(this.ops,e?.auth!==void 0?e.auth:this.auth,this.bypassRules);if(n.allowed)return;if(n.error)throw new ue(n.error);const s=n.results.find(i=>!i.allowed)?.debugMessages.join("; ")??"batch denied";throw new ue(te("permission-denied",`batch failed: ${s}`))}}function hg(t){return typeof t.where=="function"}class fg{simTx;constructor(e){this.simTx=e}async get(e){if(hg(e)){const s=await e.get();return s.size>0&&this.simTx.getAll(...s.docs.map(i=>i.ref.path)),s}const r=this.simTx.get(e.path).data();return uu(e,r)}set(e,n){return this.simTx.set(e.path,n),this}update(e,n){return this.simTx.update(e.path,n),this}delete(e){return this.simTx.delete(e.path),this}}class pg{env;auth;bypassRules;provenance;constructor(e,n,r=!1,s){this.env=e,this.auth=n,this.bypassRules=r,this.provenance=s}collection(e){if(!Mi(e))throw new ue(te("invalid-argument",`collection path must have an odd number of segments: ${e}`));return new mu(this.env,this.auth,e,this.bypassRules)}doc(e){if(!ou(e))throw new ue(te("invalid-argument",`document path must have an even number of segments: ${e}`));return qr(this.env,this.auth,e,this.bypassRules)}collectionGroup(e){if(e.length===0||e.includes("/"))throw new ue(te("invalid-argument",`collection group id must be a single non-empty segment with no '/': ${e}`));return new ji({env:this.env,auth:this.auth,collectionId:e,bypassRules:this.bypassRules})}batch(){return new dg(this.env,this.auth,this.bypassRules)}async runTransaction(e,n){let r;try{r=await this.env.transaction(s=>{const i=new fg(s);return e(i)},{auth:n?.auth!==void 0?n.auth:this.auth,bypassRules:this.bypassRules,provenance:this.provenance,maxAttempts:n?.maxAttempts})}catch(s){throw s instanceof Kc?new ue(s.simError):s instanceof Zc?new ue(s.simError):s}if(!r.allowed){if(r.error)throw new ue(r.error);const i=r.writes.find(a=>!a.allowed)?.debugMessages.join("; ")??"transaction denied at commit";throw new ue(te("permission-denied",`transaction failed: ${i}`))}return r.returnValue}}function mg(t,e){return new pg(t,e?.auth??null,e?.bypassRules??!1,e?.provenance)}const gu=Symbol("pyric/sandbox/context"),yu=Symbol("pyric/sandbox/bypassRules");let ii=null;function gg(t){ii=t}function yg(t){const e=t;return typeof e.path=="string"&&e.path.length>0||typeof e.collectionPath=="string"&&e.collectionPath.length>0}function bg(t){const e=t.trim();if(!e)return[];const n=e.indexOf(": ");if(n!==-1){const s=e.slice(n+2).trim().split("; ").map(i=>i.trim()).filter(i=>i.length>0);if(s.length>0)return s}return[e]}function vo(t,e){if(t instanceof ue===!1)return t;const r=t.code;if(r==="permission-denied"===!1)return new ie(r,t.message);const i={auth:e.auth,reasons:bg(t.message)},a=t.simError;if(a!==void 0){if(a.request!==void 0){const y=a.request;i.request={method:y.method,path:y.path},y.resourceData!==void 0&&(i.request.resourceData=y.resourceData)}if(a.resource!==void 0&&(i.resource={data:a.resource.data,exists:a.resource.exists}),a.query!==void 0&&(i.query=a.query),a.rule!==void 0&&(i.rule=a.rule),a.remediation!==void 0)return new ie({code:r,message:t.message,denialContext:i,remediation:a.remediation})}return new ie(r,t.message,i)}function Ur(t,e,n=!1){return new Proxy(t,{get(r,s,i){if(s===gu)return e;if(s===yu)return n;if(s==="onSnapshot"&&ii!==null&&!(s in r)&&yg(r))return(...o)=>ii(i,...o);const a=Reflect.get(r,s,i);return typeof a!="function"?a:function(...o){let c;try{const u=()=>a.apply(r,o);c=e.sandbox.runWithProvenance?.(Ri(e.operationContext),u)??u()}catch(u){throw vo(u,e)}return c instanceof Promise?c.then(u=>u&&typeof u=="object"?Ur(u,e,n):u).catch(u=>{throw vo(u,e)}):c&&typeof c=="object"?Ur(c,e,n):c}}})}function bu(t,e=!1){if(Di(t.sandbox))throw new Error("pyric/sandbox/admin-firestore: internal — a remote sandbox context reached the local engine builder; remote dispatch should have handled it. Please report this.");const n=()=>mg(Xe(t.sandbox),{auth:t.auth,bypassRules:e,provenance:Ri(t.operationContext)});return{collection(r){return n().collection(r)},doc(r){return n().doc(r)},collectionGroup(r){return n().collectionGroup(r)},batch(){return n().batch()},runTransaction(r,s){return n().runTransaction(r,s)},setRules(r){return Xe(t.sandbox).deployRules(r)},seed(r){const s=Xe(t.sandbox);return s.seed({rules:s.getRules(),documents:r?.documents??{}})},snapshot(){return Xe(t.sandbox).snapshot()}}}function ai(t){if(t instanceof ie)return t;if(t!==null&&typeof t=="object"){const e=t;if(typeof e.code=="string"&&typeof e.message=="string"){const n=e.denialContext!==null&&typeof e.denialContext=="object"?e.denialContext:void 0;return new ie(e.code,e.message,n)}}return t}function yt(t){return new ie("invalid-argument",t)}async function et(t,e){try{return await t.sandbox.channel.op({...e,actAs:t.lens})}catch(n){throw ai(n)}}const vg=new Set(["serverTimestamp","increment","arrayUnion","arrayRemove","deleteField"]);function wg(t){return t!==null&&typeof t=="object"&&typeof t.__type=="string"&&vg.has(t.__type)}function Sg(t){switch(t.__type){case"serverTimestamp":return{__sentinel:"serverTimestamp"};case"increment":return{__sentinel:"increment",n:t.value};case"arrayUnion":return{__sentinel:"arrayUnion",values:t.values.map(vt)};case"arrayRemove":return{__sentinel:"arrayRemove",values:t.values.map(vt)};case"deleteField":return{__sentinel:"deleteField"}}}function vt(t){if(t===null||typeof t!="object")return t;if(wg(t))return Sg(t);if(t instanceof xt)return t.toJSON();if(t instanceof Date)return xt.fromDate(t).toJSON();if(Array.isArray(t))return t.map(vt);const e=Object.getPrototypeOf(t);if(e!==Object.prototype&&e!==null){const r=t.toJSON;if(typeof r=="function")return r.call(t);throw yt(`remote Firestore: cannot serialize a ${e.constructor?.name??"class"} instance for the wire — use plain data, Timestamp, Date, or FieldValue sentinels.`)}const n={};for(const[r,s]of Object.entries(t))n[r]=vt(s);return n}function Jt(t){return vt(t)}function oi(t){return Fi(JSON.parse(t.json))}function vu(t){return Gn(oi(t))}function wu(t,e){const n=e.exists&&e.data?vu(e.data):void 0;return{id:t.id,ref:t,exists:e.exists,data:()=>n,get:r=>wn(n,r)}}function Su(t,e){const n=e.docs.map(r=>{const s=r.path??r.id,i=Br(t,s),a=r.data?vu(r.data):{};return{id:i.id,ref:i,exists:!0,data:()=>a,get:o=>wn(a,o)}});return{size:n.length,empty:n.length===0,docs:n,forEach(r){n.forEach(s=>r(s))}}}const Pi=Symbol("pyric/sandbox/admin-firestore/remoteSnapshotRegistrar");function _g(t){if(t===null||typeof t!="object")return;const e=t[Pi];return typeof e=="function"?e:void 0}let ci=null;function Ag(t){ci=t}function _u(...t){if(ci===null)throw new ie("failed-precondition","remote Firestore: onSnapshot is not wired yet — import pyric-admin/firestore (or pyric/sandbox/admin-firestore) before subscribing.");return ci(this,...t)}function Au(t,e,n,r,s){const i=n.includeMetadataChanges!==!0;let a,o;try{o=t.sandbox.channel.subscribe({target:e,actAs:t.lens},c=>{if(!r)return;const u=c;if(Array.isArray(u.docs)){const d=u.docs.map(y=>({path:y.path??y.id,data:y.data?oi(y.data):{}})),l=e.__ref==="query"?e.source.__ref==="group"?e.source.collectionId:e.source.path:e.__ref==="group"?e.collectionId:e.path,p=cn({path:l},d,{excludesMetadataChanges:i},a);a=d,r(p)}else if(typeof u.id=="string"){const d=u.path??u.id,l=u.exists&&u.data?oi(u.data):null;r(on(d,l))}},c=>{const u=ai(c);s?s(u):console.error("pyric remote Firestore: uncaught onSnapshot error:",u)})}catch(c){throw ai(c)}return o}const xu=Symbol("pyric/sandbox/admin-firestore/remoteQueryState");function xg(t){if(!(t===null||typeof t!="object"))return t[xu]}function Iu(t){return t.kind==="where"?(Eu(t.op),{kind:"where",field:t.field,op:t.op,value:vt(t.value)}):{kind:t.kind,filters:t.filters.map(Iu)}}const Ig=new Set(["<","<=","==","!=",">=",">","in","not-in","array-contains","array-contains-any"]);function Eu(t){if(!Ig.has(t))throw yt(`invalid where operator: ${String(t)}`)}function cr(t){const e=[...t.filters];for(const n of t.orders)e.push({kind:"orderBy",field:n.field,direction:n.direction});return t.start&&e.push({kind:t.start.inclusive?"startAt":"startAfter",values:t.start.values.map(vt)}),t.end&&e.push({kind:t.end.inclusive?"endAt":"endBefore",values:t.end.values.map(vt)}),t.limitCount!==void 0&&e.push(t.limitFromEnd?{kind:"limitToLast",n:t.limitCount}:{kind:"limit",n:t.limitCount}),e.length===0?t.source:{__ref:"query",source:t.source,constraints:e}}function wo(t,e,n){if(e.length===0)throw yt(`${n}(snapshot) on a remote sandbox requires at least one explicit orderBy() clause — the relay protocol has no document-key cursor.`);if(e.some(s=>s.field==="__name__"))throw yt(`${n}(snapshot) on a remote sandbox does not support orderBy('__name__') — the relay protocol has no document-key cursor, and __name__ is not a data field a value cursor can carry. Order by a real document field instead.`);const r=t.data();if(r===void 0)throw new ie("not-found",`Snapshot-based cursors require an existing document — got an empty snapshot for ${t.id??"<unknown>"}.`);return e.map(s=>r[s.field])}function $i(t,e){const n=s=>$i(t,{...e,...s});return{[xu]:e,where(s,i,a){return Eu(i),n({filters:[...e.filters,{kind:"where",field:s,op:i,value:vt(a)}]})},applyFilter(s){return n({filters:[...e.filters,Iu(s)]})},orderBy(s,i="asc"){return n({orders:[...e.orders,{field:s,direction:i}]})},limit(s){return n({limitCount:s,limitFromEnd:!1})},limitToLast(s){return n({limitCount:s,limitFromEnd:!0})},startCursor(s,i){return n({start:{values:[...s],inclusive:i}})},endCursor(s,i){return n({end:{values:[...s],inclusive:i}})},startCursorFromSnapshot(s,i){return n({start:{values:wo(s,e.orders,i?"startAt":"startAfter"),inclusive:i}})},endCursorFromSnapshot(s,i){return n({end:{values:wo(s,e.orders,i?"endAt":"endBefore"),inclusive:i}})},async get(s){ur(e);const i=await et(t,{method:"getDocs",source:cr(e)});return Su(t,i)},async aggregate(s){ur(e);const i=await et(t,{method:"aggregate",source:cr(e),spec:s});return{data:()=>i.data}},[Pi]:(s,i,a)=>(ur(e),Au(t,cr(e),s,i,a)),onSnapshot:_u}}function ur(t){if(t.limitFromEnd&&t.orders.length===0)throw yt("limitToLast() queries require at least one orderBy clause.")}function ui(t,e){const n=$i(t,{source:{__ref:"collection",path:e},filters:[],orders:[],limitFromEnd:!1});return Object.assign(Object.create(Object.getPrototypeOf(n)),n,{id:Yr(e),path:e,doc(s){const i=s??Ti();return Br(t,`${e}/${i}`)},async add(s,i){const a=await et(t,{method:"addDoc",collectionPath:e,data:Jt(s)});return Br(t,a.path)}})}function Br(t,e){const n={id:Yr(e),path:e,get parent(){return ui(t,cu(e))},collection(r){const s=`${e}/${r}`;if(!Mi(s))throw yt(`collection path must have an odd number of segments: ${s}`);return ui(t,s)},async get(r){const s=await et(t,{method:"getDoc",path:e});return wu(n,s)},async set(r,s){await et(t,{method:"setDoc",path:e,data:Jt(r),...So(s)?{options:So(s)}:{}})},async update(r,s){await et(t,{method:"updateDoc",path:e,data:Jt(r)})},async delete(r){await et(t,{method:"deleteDoc",path:e})},[Pi]:(r,s,i)=>Au(t,{__ref:"doc",path:e},r,s,i),onSnapshot:_u};return n}function So(t){if(!t)return;const e={};return t.merge!==void 0&&(e.merge=t.merge),t.mergeFields!==void 0&&(e.mergeFields=[...t.mergeFields]),e.merge!==void 0||e.mergeFields!==void 0?e:void 0}function Eg(t){const e=[];let n=!1;const r={set(i,a){return s(),e.push({method:"set",path:i.path,data:Jt(a)}),r},update(i,a){return s(),e.push({method:"update",path:i.path,data:Jt(a)}),r},delete(i){return s(),e.push({method:"delete",path:i.path}),r},async commit(i){s(),n=!0,await et(t,{method:"batchCommit",writes:e})}};function s(){if(n)throw new ie("failed-precondition","WriteBatch has already been committed.")}return r}const kg=5;async function Og(t,e,n=kg){for(let r=0;r<n;r++){const s=[],i=[],a=()=>{if(i.length>0)throw new ie("failed-precondition",Xs)},o={get(l){a();const p=xg(l);return p!==void 0?u(p):c(l)},set(l,p){return i.push({method:"set",path:l.path,data:Jt(p)}),o},update(l,p){return i.push({method:"update",path:l.path,data:Jt(p)}),o},delete(l){return i.push({method:"delete",path:l.path}),o}};async function c(l){const p=await et(t,{method:"getDoc",path:l.path});return s.push({path:p.path??l.path,data:p.exists&&p.data?p.data:null}),wu(l,p)}async function u(l){ur(l);const p=await et(t,{method:"getDocs",source:cr(l)});for(const y of p.docs)s.push({path:y.path??y.id,data:y.data??null});return Su(t,p)}const d=await e(o);try{return await et(t,{method:"txnCommit",reads:s,writes:i}),d}catch(l){if(l instanceof ie&&l.code==="aborted")continue;throw l}}throw new ie("aborted",`Transaction failed after ${n} attempts due to repeated conflicts. Another writer is concurrently updating the same documents.`)}function ys(t,e){return new ie("unimplemented",`SandboxFirestore.${t} is not available on a remote sandbox — its return value is synchronous and the data lives in the browser worker. ${e}`)}function ku(t,e){const n={sandbox:t,lens:e};return{collection(r){if(!Mi(r))throw yt(`collection path must have an odd number of segments: ${r}`);return ui(n,r)},doc(r){if(!ou(r))throw yt(`document path must have an even number of segments: ${r}`);return Br(n,r)},collectionGroup(r){if(r.length===0||r.includes("/"))throw yt(`collection group id must be a single non-empty segment with no '/': ${r}`);return $i(n,{source:{__ref:"group",collectionId:r},filters:[],orders:[],limitFromEnd:!1})},batch(){return Eg(n)},runTransaction(r,s){return Og(n,r,s?.maxAttempts)},setRules(){throw ys("setRules","Deploy rules asynchronously through the relay instead: `await sandbox.channel.op({ method: 'setFirestoreRules', source })`.")},seed(){throw ys("seed","The relay has no atomic seed op; write seed docs through this handle (`db.doc(path).set(data)` / `db.batch()`), or drive `sandbox.channel.op({ method: 'admin.setDocument', path, data })` per document.")},snapshot(){throw ys("snapshot","Read the worker state asynchronously instead: `await sandbox.channel.op({ method: 'admin.readState' })`.")}}}const _o=new WeakMap;function Ou(t){const e=_o.get(t);if(e)return e;const n=Di(t.sandbox)?ku(t.sandbox,Cg(t.auth)):Ur(bu(t),t);return _o.set(t,n),n}function Cg(t){return t==null?{mode:"anon"}:t.token===void 0?{mode:"as",uid:t.uid}:{mode:"as",uid:t.uid,token:t.token}}const Ao=new WeakMap;function Tg(t){const e=Rg(t)?t:t.withAuth(null),n=Ao.get(e);if(n)return n;const r=e.operationContext.authLens.mode==="admin"?e:Li(e,{source:e.operationContext.source,authLens:{mode:"admin"},...e.operationContext.planId===void 0?{}:{planId:e.operationContext.planId}}),s=Di(r.sandbox)?ku(r.sandbox,{mode:"admin"}):Ur(bu(r,!0),r,!0);return Ao.set(e,s),s}function Rg(t){return t!==null&&typeof t=="object"&&"sandbox"in t&&typeof t.withAuth=="function"}const tr=Symbol("pyric/firestore/followsCurrentUser"),bs=Symbol("pyric/firestore/authSessionScope");function Ng(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 Lg(t){if(t!==null&&typeof t=="object"){const e=t.snapshotConstraints;if(typeof e=="function")return e.call(t)}}function Fg(t){if(t===null||typeof t!="object")return!1;const e=t;return typeof e.path=="string"&&e.path.length>0&&e.parent!==void 0&&e.parent!==null}function Cu(t,e,n,r,s){let i={},a,o;if(typeof e=="object"&&e!==null&&typeof e.next!="function"&&typeof e.error!="function"&&typeof e.complete!="function"){if(i=e,typeof n=="function")a=n,o=r;else if(typeof n=="object"&&n!==null){const C=n;a=C.next,o=C.error}}else if(typeof e=="function")a=e,o=n;else if(typeof e=="object"&&e!==null){const C=e;a=C.next,o=C.error}if(!a&&!o)throw new TypeError("onSnapshot: missing handler. Provide a callback, or an observer with a `next` and/or `error` method.");const u=_g(t);if(u){if(i[tr]===!0)throw new ie("unimplemented","onSnapshot: live (follows-current-user) listeners are not supported on a remote sandbox — remote listeners are frozen to the identity of the context that created the ref.");return u(i,a,o)}const d=Dg(t),l=Xe(d.sandbox);let p;if(Fg(t))p={kind:"doc",path:t.path};else{const C=Ng(t);if(C===null)throw new TypeError("onSnapshot: could not determine the collection path for this Query. Pass a CollectionReference or a Query produced by `.where`/`.orderBy`/`.limit` on a CollectionReference obtained from `getFirestore(ctx)`.");const I=Lg(t);p={kind:"query",collection:C,constraints:I}}const y=i[tr]===!0,b=i[bs],w=t[yu]===!0;if(tr in i){const{[tr]:C,...I}=i;i=I}if(bs in i){const{[bs]:C,...I}=i;i=I}const R=()=>l.addSnapshotListener(p,a??(()=>{}),i,d.auth,o,y,w,b);return d.sandbox.runWithProvenance?.(Ri(d.operationContext),R)??R()}function Dg(t){if(t===null||typeof t!="object")throw new TypeError("onSnapshot: reference must be a DocumentReference or Query.");const e=t[gu];if(!e)throw new TypeError("onSnapshot: reference was not produced by a sandbox context — pass a ref obtained from `getFirestore(ctx)`.");return e}gg(Cu);Ag(Cu);class qt{bytes;constructor(e){this.bytes=e,ut(this,Cp(e)),tn(this,Object.freeze({type:"bytes",values:Object.freeze(Array.from(e))}),()=>new qt(e.slice()))}static fromBase64String(e){const n=atob(e),r=new Uint8Array(n.length);for(let s=0;s<n.length;s+=1)r[s]=n.charCodeAt(s);return new qt(r)}static fromUint8Array(e){return new qt(e.slice())}toBase64(){let e="";for(const n of this.bytes)e+=String.fromCharCode(n);return btoa(e)}toUint8Array(){return this.bytes.slice()}toString(){return`Bytes(base64: ${this.toBase64()})`}isEqual(e){return e instanceof qt&&this.bytes.length===e.bytes.length&&this.bytes.every((n,r)=>n===e.bytes[r])}toJSON(){return{type:"firestore/bytes/1.0",bytes:this.toBase64()}}static fromJSON(e){const n=e;if(n.type!=="firestore/bytes/1.0"||typeof n.bytes!="string")throw new TypeError("Invalid Bytes JSON value.");return qt.fromBase64String(n.bytes)}}class Dn{lat;lng;constructor(e,n){if(this.lat=e,this.lng=n,!Number.isFinite(e)||e<-90||e>90)throw new TypeError("Latitude must be a number between -90 and 90.");if(!Number.isFinite(n)||n<-180||n>180)throw new TypeError("Longitude must be a number between -180 and 180.");ut(this,Zt("geo-point",String(e),"\0",String(n))),tn(this,Object.freeze({type:"geo-point",latitude:e,longitude:n}),()=>new Dn(e,n))}get latitude(){return this.lat}get longitude(){return this.lng}isEqual(e){return e instanceof Dn&&this.lat===e.lat&&this.lng===e.lng}toJSON(){return{latitude:this.lat,longitude:this.lng,type:"firestore/geoPoint/1.0"}}static fromJSON(e){const n=e;if(n.type!=="firestore/geoPoint/1.0"||typeof n.latitude!="number"||typeof n.longitude!="number")throw new TypeError("Invalid GeoPoint JSON value.");return new Dn(n.latitude,n.longitude)}}class ln{_values;constructor(e){this._values=e,tn(this,Object.freeze({type:"vector",values:Object.freeze(e.slice())}),()=>new ln(e.slice()))}static create(e){if(!e.every(n=>typeof n=="number"))throw new TypeError("Vector values must be numbers.");return new ln(e.slice())}toArray(){return this._values.slice()}isEqual(e){const n=e instanceof ln?e._values:void 0;return n!==void 0&&this._values.length===n.length&&this._values.every((r,s)=>r===n[s])}toJSON(){return{type:"firestore/vectorValue/1.0",vectorValues:this.toArray()}}static fromJSON(e){const n=e;if(n.type!=="firestore/vectorValue/1.0"||!Array.isArray(n.vectorValues)||!n.vectorValues.every(r=>typeof r=="number"))throw new TypeError("Invalid VectorValue JSON value.");return ln.create(n.vectorValues)}}function Mg(t=[]){return ln.create(t)}function ly(){return Rp.serverTimestamp()}const kt=Symbol("pyric/firestore/target");function Jn(t){return t.kind==="sandbox"?t.db:t.getDb()}const Xr=new WeakMap;function jg(t,e){return Xr.set(t,e),t}const Qn=new WeakMap;function Pg(t,e,n){return Xr.set(t,e),Qn.set(t,n),t}function qi(t,e){const n=_n(e);if(t.kind==="sandbox")return n;const r=Qn.get(n);if(!r)throw new TypeError("pyric/firestore: live ref missing rebuild closure — was it produced by a factory in this package?");return r(Jn(t))}function $g(t,e){const n=_n(e);if(t.kind==="sandbox")return n;const r=Qn.get(n);if(!r)throw new TypeError("pyric/firestore: live collection ref missing rebuild closure.");return r(Jn(t))}function dy(t,e){const n=_n(e);if(t.kind==="sandbox")return n;const r=Qn.get(n);if(!r)throw new TypeError("pyric/firestore: live query missing rebuild closure.");return r(Jn(t))}function zn(t,e,n){return e.kind==="sandbox-live"?Pg(t,e,n):jg(t,e)}function hy(t){const e=_n(t),n=Qn.get(e);return n||(()=>e)}function Sn(t){const e=qg(t);return e.assertUsable?.(),e}function qg(t){let e;if(kt in t?e=t[kt]:e=Xr.get(t),!e)throw new TypeError("pyric/firestore: unrecognized reference — was it produced by a factory in this package?");return e}const Tu=new WeakMap,Ru=new WeakMap;function Ui(t){return Tu.get(t)}function _n(t){return Ru.get(t)??t}function Nu(t,e,n){const r={id:t.id??"",path:t.path??""};return Tu.set(r,n),Ru.set(r,t),Xr.set(r,e),r}function Ug(t){return t instanceof en?Array.from(t.value):null}function li(t){if(t instanceof We)return qt.fromUint8Array(t.data);if(t instanceof ot)return new Dn(t.lat,t.lng);const e=Ug(t);if(e)return Mg(e);if(Array.isArray(t))return t.map(li);if(t!==null&&typeof t=="object"){const n=Object.getPrototypeOf(t);if(n===Object.prototype||n===null){const r={};for(const[s,i]of Object.entries(t))r[s]=li(i);return r}}return t}function fy(t){if(t!==void 0)return li(t)}class bn extends Error{code;customData;name="FirebaseError";constructor(e,n,r){super(n),this.code=e,this.customData=r,Object.setPrototypeOf(this,new.target.prototype)}}Object.defineProperty(bn,"name",{value:"FirebaseError"});let zr;function py(t){zr=t}function Lu(t){return zr?.resolve(t,!1)}function Bg(){if(!zr)throw new TypeError("No default sandbox app registry is installed - import and initialize pyric/app before calling a service factory without an app.");return zr.defaultApp()}function zg(t){if(t===void 0)return zg(Bg());const e=Lu(t);if(e)return e.service("firestore/default",()=>{const{sandbox:n,session:r}=e,s=vs();e.onDelete(s.terminate);const i=e.authScope;i&&s.own(r.onCurrentUserChanged(o=>{Xe(n).reevaluateLiveListeners(o,i)}));const a={kind:"sandbox-live",sandbox:n,getDb:xo(n,()=>r.currentUser),authScope:i,...s};return{[kt]:a,app:t}});if(Fu(t)){const r={kind:"sandbox",db:Ou(t),sandbox:t.sandbox,...vs()};return{[kt]:r}}if(Wg(t)){const n={kind:"sandbox-live",sandbox:t,getDb:xo(t),...vs()};return{[kt]:n}}throw new TypeError("pyric/firestore is a sandbox-only mirror. Package resolution must leave firebase/firestore unchanged for production; activate pyric dev or @pyric/cli/register before importing to select the sandbox.")}function vs(){let t=!1;const e=new Set;return{own(n){return t?(n(),()=>{}):(e.add(n),()=>e.delete(n))},assertUsable(){if(t)throw new bn("failed-precondition","The client has already been terminated.")},terminate(){if(!t){t=!0;for(const n of e)n();e.clear()}}}}function Vg(t){const e=Lu(t);if(e){e.assertAlive();const a=e.sandbox;return Vg(Li(a.withAuth(null),{source:{kind:"app"},authLens:{mode:"admin"}}))}const n=Fu(t)?t:t.withAuth(null),r=n.sandbox,i={kind:"sandbox",db:Tg(n),sandbox:r};return{[kt]:i}}function Fu(t){return t instanceof Zn}function Wg(t){if(t===null||typeof t!="object")return!1;const e=t;return typeof e.withAuth=="function"&&typeof e.onCurrentUserChanged=="function"&&"currentUser"in e&&"admin"in e}function xo(t,e=()=>t.currentUser){return()=>{const n=Li(t.withAuth(e()),{source:{kind:"app"},authLens:{mode:"app-session"}});return Ou(n)}}class Hg{started=!1;networkEnabled=!0;persistenceMode;pending=new Set;cachedPaths=new Set;cachedQueries=new WeakSet;syncObservers=new Set;syncScheduled=!1;markStarted(){this.started=!0}enablePersistence(e){if(this.started||this.persistenceMode!==void 0)throw new bn("failed-precondition","Firestore has already been started and persistence can no longer be enabled.");this.persistenceMode=e,this.started=!0}disableNetwork(){this.started=!0,this.networkEnabled=!1}async enableNetwork(){this.started=!0,this.networkEnabled=!0;for(const e of this.pending)e.localDone&&e.resolve(e.value);await Promise.all([...this.pending].map(e=>e.promise))}runWrite(e,n){if(this.started=!0,n&&this.cachedPaths.add(n),this.networkEnabled)return e();let r,s;const i=new Promise((o,c)=>{r=o,s=c}),a={path:n,promise:i,localDone:!1,resolve:r,reject:s};return this.pending.add(a),e().then(o=>{a.localDone=!0,a.value=o,this.networkEnabled&&a.resolve(o)},o=>a.reject(o)),i.then(()=>this.pending.delete(a),()=>this.pending.delete(a)),i}waitForPendingWrites(){this.started=!0;const e=[...this.pending].map(n=>n.promise);return Promise.all(e).then(()=>{})}cachePath(e){this.started=!0,this.cachedPaths.add(e)}assertPathCached(e){if(this.started=!0,!this.cachedPaths.has(e))throw new bn("unavailable","Failed to get document from cache. (However, this document may exist on the server.)")}cacheQuery(e){this.started=!0,this.cachedQueries.add(e)}hasCachedQuery(e){return this.started=!0,this.cachedQueries.has(e)||this.cachedPaths.size>0}snapshotMetadata(e){return Object.freeze({fromCache:!this.networkEnabled,hasPendingWrites:[...this.pending].some(n=>n.path===e)})}querySnapshotMetadata(){return Object.freeze({fromCache:!this.networkEnabled,hasPendingWrites:this.pending.size>0})}addSnapshotsInSyncObserver(e){return this.syncObservers.add(e),e(),()=>this.syncObservers.delete(e)}notifySnapshotDelivered(){this.syncScheduled||this.syncObservers.size===0||(this.syncScheduled=!0,queueMicrotask(()=>{this.syncScheduled=!1;for(const e of[...this.syncObservers])e()}))}}const Io=new WeakMap;function Vn(t){let e=Io.get(t);return e||(e=new Hg,Io.set(t,e)),e}function ws(t,e,n){return ut(t,Zt("reference",e)),Ei(t,e,n),t}function my(t,...e){const n=Sn(t),r=kt in t,s=r?void 0:Ui(t),i=Jn(n);if(r){if(e.length===0)throw new TypeError("doc(db, path) requires at least one path segment.");const d=e.join("/"),l=i.doc(d),p=zn(l,n,y=>y.doc(d));return ws(p,d,n)}const a=_n(t),o=e.length===0?a.doc():a.doc(e.join("/")),c=o.path,u=zn(o,n,d=>d.doc(c));if(s){const d=Nu(u,n,s);return ws(d,c,n)}return ws(u,c,n)}function gy(t,...e){const n=Sn(t),r=kt in t;if(e.length===0)throw new TypeError("collection() requires at least one path segment.");if(r){const c=e.join("/"),u=Jn(n).collection(c);return zn(u,n,d=>d.collection(c))}const s=_n(t),i=e.join("/"),a=s.collection(i),o=a.path;return zn(a,n,c=>c.collection(o))}function Gg(t){return t instanceof Error&&"code"in t&&typeof t.code=="string"}function Kg(t){if(t instanceof bn||!Gg(t))return t;const e={};t.denialContext!==void 0&&(e.denialContext=t.denialContext),t.remediation!==void 0&&(e.remediation=t.remediation);const n=new bn(t.code,t.message,Object.keys(e).length===0?void 0:e);return t.denialContext!==void 0&&Object.assign(n,{denialContext:t.denialContext}),t.remediation!==void 0&&Object.assign(n,{remediation:t.remediation}),n}async function es(t){try{return await t()}catch(e){throw Kg(e)}}async function yy(t,e,n){const r=Sn(t),s=Ui(t),i=s?s.toFirestore(e):e;return Vn(r).runWrite(()=>es(()=>qi(r,t).set(i,n)),t.path)}async function by(t,e){const n=Sn(t);return Vn(n).runWrite(()=>es(()=>qi(n,t).update(e)),t.path)}async function vy(t){const e=Sn(t);return Vn(e).runWrite(()=>es(()=>qi(e,t).delete()),t.path)}async function wy(t,e){const n=Sn(t),r=Ui(t),s=r?r.toFirestore(e):e,i=await Vn(n).runWrite(async()=>{const c=await es(()=>$g(n,t).add(s));return Vn(n).cachePath(c.path),c}),a=i.path,o=zn(i,n,c=>c.doc(a));if(ut(o,Zt("reference",a)),Ei(o,a,n,o),r){const c=Nu(o,n,r);return sp(o,c),c}return o}function Sy(t,e){return Xe(t).deployRules(e)}function _y(t,e){const n=Xe(t);return n.seed({rules:n.getRules(),documents:e})}function Ay(t){return Xe(t).snapshot()}function xy(t,e={}){const n=e.recentEventLimit??10,r=Xe(t),s=r.getRules(),i=s?Ds(s):{warnings:[]},a=i.warnings.map(w=>({rule:w.rule,severity:w.severity,message:w.message})),o={errors:0,warnings:0,info:0};for(const w of i.warnings)w.severity==="error"?o.errors++:w.severity==="warning"?o.warnings++:o.info++;const c=r.snapshot(),u={};for(const w of Object.keys(c)){const R=w.split("/")[0]??"";R&&(u[R]=(u[R]??0)+1)}const d=t.history(),l=[];for(const w of d){const R=w.kind==="request",C=w.kind==="operation",I=w.kind==="listener";(R||C||I&&w.phase==="errored")&&l.push(w)}const p=[];for(const w of l)if(w.result==="deny")p.push(w);else{const C=w.error;C!==void 0&&C.code==="PERMISSION_DENIED"&&p.push(w)}const y=l.slice(-n).map(w=>{let R="";if(w.path!==void 0)R=String(w.path);else{const N=w.target;N!==void 0&&N.path!==void 0&&(R=String(N.path))}let C="listen";w.method!==void 0&&(C=String(w.method));let I="error";if(w.result!==void 0)I=String(w.result);else{const N=w.error;N!==void 0&&N.code==="PERMISSION_DENIED"&&(I="deny")}let E=null;return w.auth!==void 0&&(E=w.auth),{path:R,method:C,result:I,auth:E}}),b=p.slice(-n).map(w=>{let R="";if(w.path!==void 0)R=String(w.path);else{const N=w.target;N!==void 0&&N.path!==void 0&&(R=String(N.path))}let C="listen";w.method!==void 0&&(C=String(w.method));let I=null;w.auth!==void 0&&(I=w.auth);let E;return typeof w.debugMessage=="string"&&(E=w.debugMessage),{path:R,method:C,auth:I,debugMessage:E}});return{rules:{source:s,sizeBytes:new TextEncoder().encode(s).byteLength,isEmpty:s.trim().length===0,lint:{...o,findings:a}},documents:{totalCount:Object.keys(c).length,byCollection:u},events:{totalCount:d.length,recentDenials:b,recentRequests:y}}}export{Or as $,Vn as A,_n as B,Qn as C,bs as D,bn as E,tr as F,gy as G,wy as H,by as I,vy as J,ey as K,Xg as L,py as M,Fi as N,hr as O,Ni as P,Ri as Q,ce as R,cy as S,Li as T,Zn as U,gt as V,pt as W,pn as X,$s as Y,me as Z,Wt as _,_y as a,Ir as a0,Xe as a1,Vg as a2,co as a3,Bg as a4,Lu as a5,ie as a6,Yg as a7,ei as a8,xt as a9,Dn as aa,qt as ab,jg as ac,fy as ad,Ru as ae,Ei as af,du as ag,qi as ah,dy as ai,ly as aj,yy as b,Ay as c,my as d,ay as e,Bf as f,zg as g,ty as h,xy as i,ny as j,ry as k,sy as l,Uf as m,iy as n,uy as o,Ui as p,hy as q,Qg as r,Sy as s,Sn as t,Kg as u,oy as v,Jn as w,zn as x,Nu as y,lu as z};
1251
+ ${c}`:a;super(u),this.name="SandboxError",this.code=i,o!==void 0&&(this.denialContext=o),c!==void 0&&(this.remediation=c)}}function ei(t){return t.kind==="request"||t.kind==="operation"||t.kind==="listener"&&t.phase==="errored"}function Kn(t){const e=Object.freeze({...t.source}),n=Object.freeze({...t.authLens});return Object.freeze({source:e,authLens:n,...t.planId===void 0?{}:{planId:t.planId}})}function Ri(t){const e=Kn(t);return{actor:e.source,authLens:e.authLens,operationContext:e,...e.planId===void 0?{}:{planId:e.planId}}}function ao(t){const e=t?.operationContext?.source;if(e&&e.kind!=="unattributed")return e;if(t?.actor&&t.actor.kind!=="unattributed")return t.actor}function Ni(t,e){const n=t?.operationContext?.source??t?.actor,r=e?.operationContext?.source??e?.actor;return Kn({source:ao(t)??ao(e)??n??r??{kind:"unattributed"},authLens:e?.operationContext?.authLens??e?.authLens??t?.operationContext?.authLens??t?.authLens??{mode:"app-session"},...(t?.operationContext?.planId??t?.planId??e?.operationContext?.planId??e?.planId)===void 0?{}:{planId:t?.operationContext?.planId??t?.planId??e?.operationContext?.planId??e?.planId}})}function km(t){return Ni(void 0,t)}function Om(t){if(t.result==="deny")return!0;if(!("error"in t)||!t.error||typeof t.error!="object")return!1;const e=t.error.code;if(typeof e!="string")return!1;const n=e.toLowerCase();return n==="permission_denied"||n==="permission-denied"||n==="auth/permission-denied"}function Jc(t){return"rulesDisposition"in t&&t.rulesDisposition?t.rulesDisposition:t.kind==="operation"&&t.origin==="admin"?{kind:"bypassed",reason:"admin"}:t.detail?.admin===!0?{kind:"bypassed",reason:"admin"}:Om(t)?{kind:"evaluated",verdict:"deny"}:t.result==="unsupported"?{kind:"not-evaluated",reason:"unsupported"}:t.kind==="operation"&&t.result==="error"?{kind:"not-evaluated",reason:"runtime-error"}:t.kind==="operation"&&t.result==="not-applicable"?{kind:"not-evaluated",reason:"not-a-rules-operation"}:t.kind==="listener"?t.rules?{kind:"evaluated",verdict:"deny"}:{kind:"not-evaluated",reason:"runtime-error"}:t.kind==="request"?{kind:"evaluated",verdict:"allow"}:"rules"in t&&t.rules?{kind:"evaluated",verdict:"allow"}:{kind:"not-evaluated",reason:"no-rules"}}function Cm(t){if(t===null)return null;let e;return t.token!==void 0&&(e=Qc(t.token)),Object.freeze({uid:t.uid,...e===void 0?{}:{token:e}})}function Qc(t){const e={};for(const[n,r]of Object.entries(t))e[n]=Yc(r);return Object.freeze(e)}function Yc(t){return Array.isArray(t)?Object.freeze(t.map(Yc)):t&&typeof t=="object"?Qc(t):t}function Xg(t){if(!ei(t))return null;let e="listen",n;t.kind==="request"||t.kind==="operation"?(e=t.method,t.path!==void 0&&(n=t.path)):t.kind==="listener"&&(e="listen",t.target.path!==void 0&&(n=t.target.path));let r="firestore";return t.service!==void 0&&(r=t.service),Object.freeze({id:t.id,at:t.at,eventKind:t.kind,service:r,method:e,...n===void 0?{}:{path:n},auth:Cm(t.auth),result:t.result,context:km(t),rules:Object.freeze({...Jc(t)})})}function oo(t){return t===null?{mode:"anon"}:t.token===void 0?{mode:"as",uid:t.uid}:{mode:"as",uid:t.uid,token:t.token}}class Zn{sandbox;auth;constructor(e,n,r){this.sandbox=e,this.auth=n,this.operationContext=Kn(r??{source:{kind:"unattributed"},authLens:oo(n)})}operationContext;withAuth(e){return ti(e),new Zn(this.sandbox,e,{source:this.operationContext.source,authLens:oo(e),...this.operationContext.planId===void 0?{}:{planId:this.operationContext.planId}})}}function Li(t,e){return new Zn(t.sandbox,t.auth,e)}function ti(t){if(t===null)return;if(t===void 0)throw new ie({code:"invalid-argument",message:"withAuth() requires an explicit AuthState argument.",remediation:["For anonymous (unauthenticated) access: withAuth(null)",'For authenticated access: withAuth({ uid: "someUid" })','For custom claims: withAuth({ uid: "someUid", token: { role: "admin" } })'].join(`
1252
+ `)});if(typeof t!="object")throw new ie("invalid-argument","withAuth() expected null or an object with a `uid` field.");const e=t;if(typeof e.uid!="string"||e.uid.length===0)throw new ie("invalid-argument","withAuth() requires `uid` to be a non-empty string.");if("token"in e&&e.token!==void 0&&(e.token===null||typeof e.token!="object"||Array.isArray(e.token)))throw new ie("invalid-argument","withAuth() requires `token` (when present) to be a plain object.")}function Tm(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),n=e.length%4===0?"":"=".repeat(4-e.length%4),r=atob(e+n),s=new Uint8Array(r.length);for(let i=0;i<r.length;i++)s[i]=r.charCodeAt(i);return s}function Rm(t){const e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return n}function Fi(t){return ni(t,!0)}function ni(t,e){if(t===null||typeof t!="object")return t;if(Array.isArray(t)){const a=t.map(o=>ni(o,!1));return e&&ut(a,Ha(t)),a}const n=t,r=a=>(e&&ut(a,Ha(t)),a),s=(a,o)=>(tn(a,Object.freeze(o),()=>a),r(a));if(n.__type__==="__vector__"&&Array.isArray(n.value)){const a=Object.freeze(n.value.slice());return s(new en(a),{type:"vector",values:a})}if(typeof n.__type=="string")switch(n.__type){case"timestamp":return s(new xe(n.seconds,n.nanos),{type:"timestamp",seconds:n.seconds,nanoseconds:n.nanos});case"bytes":{const a=Tm(n.base64);return s(new We(a),{type:"bytes",values:Object.freeze(Array.from(a))})}case"latlng":return s(new ot(n.lat,n.lng),{type:"geo-point",latitude:n.lat,longitude:n.lng});case"duration":return r(new we(n.seconds,n.nanos));case"reference":return r(new zt(n.path));case"path":return r(new st(n.segments))}if(typeof n.type=="string")switch(n.type){case"firestore/timestamp/1.0":{const a=n.seconds,o=n.nanoseconds;return s(new xe(a,o),{type:"timestamp",seconds:a,nanoseconds:o})}case"firestore/bytes/1.0":{const a=Rm(n.bytes);return s(new We(a),{type:"bytes",values:Object.freeze(Array.from(a))})}case"firestore/geoPoint/1.0":return s(new ot(n.latitude,n.longitude),{type:"geo-point",latitude:n.latitude,longitude:n.longitude})}const i={};for(const[a,o]of Object.entries(n))i[a]=ni(o,!1);return r(i)}class Xn extends Error{constructor(e){super(e),this.name="PersistenceSchemaError"}}function Nm(t){let e;try{e=JSON.parse(t)}catch(s){throw new Xn(`Persisted blob is not valid JSON: ${s.message}`)}if(typeof e!="object"||e===null)throw new Xn("Persisted blob is not an object");if(e.version!==1&&e.version!==2)throw new Xn(`Persisted blob has version ${String(e.version)}, expected 1 or 2`);if(typeof e.firestore!="object"||e.firestore===null)throw new Xn("Persisted blob has no firestore field");const n={};for(const[s,i]of Object.entries(e.firestore))n[s]=Fi(i);const r=e.services!==void 0&&typeof e.services=="object"&&e.services!==null?e.services:{};return{firestore:n,services:r}}const Lm=3,Fm=256,ri="meta";function Dm(t){let e=2166136261;for(let n=0;n<t.length;n++)e^=t.charCodeAt(n),e=e+((e<<1)+(e<<4)+(e<<7)+(e<<8)+(e<<24))>>>0;return(e%Fm).toString(16).padStart(2,"0")}function Mm(t){return JSON.parse(JSON.stringify(t))}function Xc(t){const e=JSON.stringify(t);let n=2166136261;for(let r=0;r<e.length;r++)n^=e.charCodeAt(r),n=Math.imul(n,16777619)>>>0;return n}function eu(t,e,n){const r=new Map;r.set(ri,{version:Lm,savedAt:n,services:e});for(const[s,i]of Object.entries(t)){const a=Dm(s);let o=r.get(a);o||(o={docs:{}},r.set(a,o)),o.docs[s]=Mm(i)}for(const[s,i]of r)s!==ri&&(i.checksum=Xc(i.docs));return r}const tu="pyric-v3-records";function ey(t){return JSON.stringify({format:tu,records:Object.fromEntries(t)})}function ty(t){let e;try{e=JSON.parse(t)}catch{return new Map}const n=e;return n&&typeof n=="object"&&n.format===tu&&typeof n.records=="object"&&n.records!==null?new Map(Object.entries(n.records)):nu(t)??new Map}function nu(t){let e;try{e=Nm(t)}catch{return null}return eu(e.firestore,e.services,0)}function jm(t){const e={};let n={};for(const[r,s]of t){if(r===ri){const a=s;a&&typeof a.services=="object"&&a.services!==null&&(n=a.services);continue}const i=s;if(!(!i||typeof i.docs!="object"||i.docs===null)){if(typeof i.checksum=="number"&&Xc(i.docs)!==i.checksum){console.warn(`[sandbox/persistence] checksum mismatch for bucket '${r}'; skipping corrupt bucket`);continue}for(const[a,o]of Object.entries(i.docs))e[a]=Fi(o)}}return{firestore:e,services:n}}const yn="snapshots";function co(){const t=new Map,e=n=>{let r=t.get(n);return r||(r=new Map,t.set(n,r)),r};return{async getRecord(n,r){const s=t.get(n)?.get(r);return s===void 0?null:structuredClone(s)},async listRecords(n){return[...t.get(n)?.keys()??[]]},async putRecords(n,r){const s=e(n);for(const[i,a]of r)s.set(i,structuredClone(a))},async deleteRecords(n,r){const s=t.get(n);if(s)for(const i of r)s.delete(i)},async clear(n){t.delete(n)}}}function ru(t){return new Promise((e,n)=>{const r=indexedDB.open(t,1);r.onupgradeneeded=()=>{const s=r.result;s.objectStoreNames.contains(yn)||s.createObjectStore(yn)},r.onsuccess=()=>e(r.result),r.onerror=()=>n(r.error??new Error(`Failed to open IndexedDB '${t}'`)),r.onblocked=()=>n(new Error(`IndexedDB open blocked for '${t}'`))})}function ps(t,e,n){return ru(t).then(r=>new Promise((s,i)=>{const a=r.transaction(yn,e),o=a.objectStore(yn),c=n(o);let u=null;c&&(c.onsuccess=()=>{u=c.result??null},c.onerror=()=>i(c.error)),a.oncomplete=()=>{r.close(),s(u)},a.onerror=()=>{r.close(),i(a.error)},a.onabort=()=>{r.close(),i(a.error??new Error("IndexedDB transaction aborted"))}}))}function uo(t,e){return ru(t).then(n=>new Promise((r,s)=>{const i=n.transaction(yn,"readwrite");e(i.objectStore(yn)),i.oncomplete=()=>{n.close(),r()},i.onerror=()=>{n.close(),s(i.error)},i.onabort=()=>{n.close(),s(i.error??new Error("IndexedDB transaction aborted"))}}))}function Pm(){if(typeof indexedDB>"u")throw new Error('IndexedDB is not available in this environment. Use { backend: "memory" } or supply an injectedBackend.');return{async getRecord(t,e){return await ps(t,"readonly",r=>r.get(e))??null},async listRecords(t){return(await ps(t,"readonly",n=>n.getAllKeys())??[]).map(n=>String(n))},async putRecords(t,e){await uo(t,n=>{for(const[r,s]of e)n.put(s,r)})},async deleteRecords(t,e){await uo(t,n=>{for(const r of e)n.delete(r)})},async clear(t){await ps(t,"readwrite",e=>e.clear())},async estimate(){if(typeof navigator>"u"||!navigator.storage?.estimate)return null;const t=await navigator.storage.estimate();return{usage:t.usage??0,quota:t.quota??0}}}}const $m=250,lo="pyric:sandbox:auth-session";function ms(t){return t==="auth"||t==="auth-session:[DEFAULT]"?lo:`${lo}:${encodeURIComponent(t)}`}function su(t){const e=JSON.stringify(t);let n=2166136261;for(let r=0;r<e.length;r++)n^=e.charCodeAt(r),n=Math.imul(n,16777619)>>>0;return n}function qm(t){if(t&&typeof t=="object"){if(t.name==="QuotaExceededError")return!0;const e=t.message;if(typeof e=="string"&&/quota/i.test(e))return!0}return!1}function Um(t){return t.injectedBackend?t.injectedBackend:(t.backend??"indexedDB")==="memory"||typeof indexedDB>"u"?co():Pm()}async function Bm(t,e){const n={...e,flushIntervalMs:e.flushIntervalMs??$m,backend:e.backend??"indexedDB"},r=Um(n),s=new Map,i=await zm(t,r,n.key,s);let a=null,o=!1;const c=new Map,u=async()=>{if(o)return;const _=t.snapshot(),v=eu(_.firestore,_.services,Date.now()),A=new Map,x=new Map;for(const[h,g]of v){const m=su(g);x.set(h,m),s.get(h)!==m&&A.set(h,g)}const f=[...s.keys()].filter(h=>!v.has(h));A.size>0&&await r.putRecords(n.key,A),f.length>0&&await r.deleteRecords(n.key,f),s.clear();for(const[h,g]of x)s.set(h,g)};let d=Promise.resolve();const l=()=>(a&&(clearTimeout(a),a=null),d=d.then(u,u),d),p=()=>{o||a||(a=setTimeout(()=>{a=null,l().catch(_=>{if(qm(_)){console.warn("[sandbox/persistence] storage quota exceeded; recent changes are kept in memory only. Free storage or reduce sandbox data to persist them.");return}console.warn("[sandbox/persistence] auto-flush failed, will retry:",_),p()})},n.flushIntervalMs))},y=(_,v)=>{if(!v.subscribe||c.has(_))return;const A=v.subscribe(()=>{p()});c.set(_,A)},b=new Map,w=new Map,R=(_,v)=>{if(!n.sessionStorage)return;const{local:A,session:x}=n.sessionStorage,f=ms(_),h=v.currentUid(),g=v.mode();if(h===null||g==="NONE"){A.removeItem(f),x.removeItem(f);return}const m=JSON.stringify({uid:h});g==="LOCAL"?(x.removeItem(f),A.setItem(f,m)):(A.removeItem(f),x.setItem(f,m))},C=_=>{if(!n.sessionStorage)return null;const v=ms(_);for(const[A,x]of[["LOCAL",n.sessionStorage.local],["SESSION",n.sessionStorage.session]]){const f=x.getItem(v);if(f)try{const h=JSON.parse(f);if(typeof h?.uid=="string")return{uid:h.uid,mode:A}}catch{x.removeItem(v)}}return null},I=_=>{if(!n.sessionStorage)return;const v=ms(_);n.sessionStorage.local.removeItem(v),n.sessionStorage.session.removeItem(v)},E=(_,v,A)=>{if(A.session)try{A.session.restore(v.uid,v.mode),w.delete(_)}catch(x){console.warn(`[sandbox/persistence] session restore for uid '${v.uid}' failed — clearing stored session:`,x),I(_),w.delete(_)}},N=(_,v)=>{if(!n.sessionStorage||!v.session||b.has(_))return;const A=v.session;b.set(_,A.subscribe(()=>R(_,A)))},q=(_,v)=>{if(!v.session)return;const A=w.get(_)??C(_);A&&E(_,A,v)};if(t instanceof Nt){for(const[_,v]of t.getServiceRegistry())y(_,v),q(_,v),N(_,v);t.setServiceRegistrationHook((_,v)=>{if(i!==null&&_ in i)try{v.restore(i[_])}catch(x){console.warn(`[sandbox/persistence] late-restore for service '${_}' failed:`,x)}const A=C(_);A&&w.set(_,A),q(_,v),y(_,v),N(_,v),p()}),t.setServiceUnregistrationHook(_=>{c.get(_)?.(),c.delete(_),b.get(_)?.(),b.delete(_),w.delete(_),p()})}const S=t.onEvent(_=>{Vm(_)&&p()}),k=()=>{l().catch(()=>{})};return typeof window<"u"&&window.addEventListener("beforeunload",k),{options:n,flush:l,async clear(){a&&(clearTimeout(a),a=null),await r.clear(n.key),s.clear()},dispose(){if(!o){o=!0,a&&(clearTimeout(a),a=null),S();for(const _ of c.values())_();c.clear();for(const _ of b.values())_();b.clear(),t instanceof Nt&&(t.setServiceRegistrationHook(null),t.setServiceUnregistrationHook(null)),typeof window<"u"&&window.removeEventListener("beforeunload",k)}}}}async function zm(t,e,n,r){let s;try{s=await e.listRecords(n)}catch(d){return console.warn("[sandbox/persistence] backend list failed:",d),null}if(s.length===0)return null;const i=[];for(const d of s)try{const l=await e.getRecord(n,d);l!==null&&i.push([d,l])}catch(l){console.warn(`[sandbox/persistence] failed to read persisted record '${d}':`,l)}const a=[],o=[];let c=null;for(const[d,l]of i)if(typeof l=="string"){const p=nu(l);p&&(o.push(d),c=p)}else a.push([d,l]);if(c){try{await e.putRecords(n,c),o.length>0&&await e.deleteRecords(n,o)}catch(d){console.warn("[sandbox/persistence] v2 migration write failed:",d)}for(const[d,l]of c)a.push([d,l])}for(const[d,l]of a)r.set(d,su(l));const u=jm(a);for(const[d,l]of Object.entries(u.firestore))t.admin.setDocument(d,l);if(t instanceof Nt){const d=t.getServiceRegistry();for(const[l,p]of Object.entries(u.services)){const y=d.get(l);if(y)try{y.restore(p)}catch(b){console.warn(`[sandbox/persistence] service '${l}' restore failed — Firestore state is intact; auth users may need to be re-created:`,b)}}}return u.services}function Vm(t){return t.kind==="write"||t.kind==="session_boundary"}function Wm(t){return typeof t=="object"&&t!==null&&typeof t.kind=="string"&&typeof t.origin=="string"}let Hm=0;function Gm(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`tab-${crypto.randomUUID()}`:`tab-${++Hm}-${typeof performance<"u"?performance.now().toFixed(3):String(Date.now())}`}function Km(t,e={}){let n,r=!1;if(e.channel)n=e.channel,r=!1;else if(typeof BroadcastChannel<"u")n=new BroadcastChannel("pyric:tabsync"),r=!0;else return()=>{};const s=e.originId??Gm();let i=!1,a=!1;const o=t.onEvent(l=>{if(l.kind!=="write"||i)return;const p={kind:"write",origin:s,event:l};n.postMessage(p)}),c=l=>{if(!Wm(l.data))return;const p=l.data;if(p.origin!==s){if(p.kind==="write")d(p.event);else if(p.kind==="hello"){const y={kind:"state",origin:s,to:p.origin,snapshot:t.snapshot()};n.postMessage(y)}else if(p.kind==="state"){if(p.to!==s||a)return;if(Object.keys(Xe(t).snapshot()).length>0){a=!0;return}i=!0;try{for(const[b,w]of Object.entries(p.snapshot.firestore))t.admin.setDocument(b,w)}finally{i=!1}a=!0}}};n.addEventListener("message",c);const u={kind:"hello",origin:s};return n.postMessage(u),()=>{o(),n.removeEventListener("message",c),r&&n.close()};function d(l){i=!0;try{if(l.method==="delete")t.admin.deleteDocument(l.path);else{const p=l.nextState;p!=null&&t.admin.setDocument(l.path,p)}}finally{i=!1}}}function Zm(t,e){const n={...t};n.service=t.service??e?.service??"firestore";const s="detail"in t&&t.detail?.admin===!0&&t.operationContext===void 0&&t.authLens===void 0?{...t,authLens:{mode:"admin"}}:t,i=ei(n)||t.operationContext!==void 0?Ni(e,s):Jm(t,e);return n.operationContext=i,n.actor=i.source,n.authLens=i.authLens,i.planId!==void 0&&(n.planId=i.planId),e?.activity!==void 0&&(n.activity={...n.activity,...e.activity}),ei(n)&&(n.rulesDisposition=Object.freeze({...Jc(n)})),n}function Jm(t,e){return Kn({source:t.actor??t.operationContext?.source??e?.actor??e?.operationContext?.source??{kind:"unattributed"},authLens:t.authLens??t.operationContext?.authLens??e?.authLens??e?.operationContext?.authLens??{mode:"app-session"},...(t.planId??t.operationContext?.planId??e?.planId??e?.operationContext?.planId)===void 0?{}:{planId:t.planId??t.operationContext?.planId??e?.planId??e?.operationContext?.planId}})}function Qm(t,e){if(!t)return e;if(!e)return t;if(e.operationContext!==void 0)return iu(t,e);if(!(t.operationContext!==void 0||t.actor!==void 0||t.authLens!==void 0||t.planId!==void 0||e.actor!==void 0||e.authLens!==void 0||e.planId!==void 0))return{...t,...e};const r=Kn({source:e.actor??t.operationContext?.source??t.actor??{kind:"unattributed"},authLens:e.authLens??t.operationContext?.authLens??t.authLens??{mode:"app-session"},...(e.planId??t.operationContext?.planId??t.planId)===void 0?{}:{planId:e.planId??t.operationContext?.planId??t.planId}});return{...t,...e,operationContext:r,actor:r.source,authLens:r.authLens,...r.planId===void 0?{}:{planId:r.planId}}}function iu(t,e){if(!t)return e;if(!e)return t;if(!(t.operationContext!==void 0||t.actor!==void 0||t.authLens!==void 0||t.planId!==void 0||e.operationContext!==void 0||e.actor!==void 0||e.authLens!==void 0||e.planId!==void 0))return{...t,...e};const r=Ni(t,e);return{...t,...e,operationContext:r,actor:r.source,authLens:r.authLens,...r.planId===void 0?{}:{planId:r.planId}}}let Ym=1;function Bt(){const t=(Ym++).toString(36),e=Math.random().toString(36).slice(2,7);return`sbe-${t}-${e}`}class Nt{_env;eventSubs=new Set;envUnsubs=[];dispatchedCount=0;eventHistory=[];ambientProvenance;_currentUser=null;currentUserSubs=new Set;persistence=null;enablePersistencePromise=null;serviceRegistry=new Map;_onServiceRegistered=null;_onServiceUnregistered=null;constructor(e){this._env=e,this.attachToEnv()}static createRoot(){return new Nt(new io)}getEnv(){return this._env}withAuth(e){return ti(e),new Zn(this,e)}attachToEnv(){this.envUnsubs.push(this._env.onRequest(e=>{this.emitEvent(e)})),this.envUnsubs.push(this._env.onWrite(e=>{this.emitEvent(e)})),this.envUnsubs.push(this._env.onSnapshotDelivery(e=>this.emitEvent(e))),this.envUnsubs.push(this._env.onSnapshotSuppressed(e=>this.emitEvent(e))),this.envUnsubs.push(this._env.onListenerLifecycle(e=>this.emitEvent(e))),this.envUnsubs.push(this._env.onSnapshotError((e,n,r)=>{const s={kind:"listener_errored",id:Bt(),at:Date.now(),listenerId:r,target:n.kind==="doc"?{kind:"doc",path:n.path}:{kind:"query",collection:n.collection},auth:e.request?.auth??null,error:{code:"permission-denied",message:e.message}};this.emitEvent(s)}))}emitEvent(e,n){const r=iu(this.ambientProvenance,n);this.dispatch(Zm(e,r))}runWithProvenance(e,n){const r=this.ambientProvenance;this.ambientProvenance=Qm(r,e);try{return n()}finally{this.ambientProvenance=r}}dispatch(e){if(this.eventHistory.push(e),this.dispatchedCount++,this.eventSubs.size!==0)for(const n of this.eventSubs)try{const r=n(e);r&&typeof r.then=="function"&&r.catch(()=>{})}catch{}}emitInternal(e,n){this.emitEvent(e,n)}onEvent(e){return this.eventSubs.add(e),()=>{this.eventSubs.delete(e)}}history(){return[...this.eventHistory]}primeEventHistory(e){return this.eventHistory.length>0||e.length===0?0:(this.eventHistory.push(...e),e.length)}get admin(){return{getDocument:e=>this._env.getDocument(e),listDocuments:e=>this._env.listDocuments(e),setDocument:(e,n)=>this._env.adminSetDocument(e,n),deleteDocument:e=>this._env.adminDeleteDocument(e)}}reset(){const e={kind:"session_boundary",id:Bt(),at:Date.now(),phase:"reset",priorOpCount:this.dispatchedCount};this.emitEvent(e),this.eventHistory=[],this._currentUser!==null&&(this._currentUser=null,this.notifyCurrentUserSubs(null));for(const n of this.envUnsubs)n();this.envUnsubs=[],this._env.dispose(),this._env=new io,this.attachToEnv()}async resetAll(){this.reset();const e=[],n=[];for(const[r,s]of this.serviceRegistry)s.reset&&n.push(Promise.resolve().then(()=>s.reset()).catch(i=>{e.push(`${r}: ${i instanceof Error?i.message:String(i)}`)}));return await Promise.all(n),{errors:e}}dispose(){const e={kind:"session_boundary",id:Bt(),at:Date.now(),phase:"dispose",priorOpCount:this.dispatchedCount};this.emitEvent(e);for(const n of this.envUnsubs)n();this.envUnsubs=[],this._env.dispose(),this.persistence&&(this.persistence.dispose(),this.persistence=null),this.serviceRegistry.clear(),this._onServiceRegistered=null,this._onServiceUnregistered=null,this.eventSubs.clear(),this.currentUserSubs.clear()}snapshot(){const e={};for(const[n,r]of this.serviceRegistry)e[n]=r.snapshot();return{firestore:this._env.snapshot(),services:e}}loadSnapshot(e){this.reset();for(const[n,r]of Object.entries(e.firestore))this._env.adminSetDocument(n,r);for(const[n,r]of this.serviceRegistry)if(n in e.services)try{r.restore(e.services[n])}catch(s){console.warn(`[sandbox] loadSnapshot: service '${n}' restore failed — Firestore is intact; that service's state may be incomplete:`,s)}}get currentUser(){return this._currentUser}set currentUser(e){ti(e),!Xm(this._currentUser,e)&&(this._currentUser=e,this.notifyCurrentUserSubs(e))}onCurrentUserChanged(e){return this.currentUserSubs.add(e),()=>{this.currentUserSubs.delete(e)}}notifyCurrentUserSubs(e){if(this._env.reevaluateLiveListeners(e),this.currentUserSubs.size!==0)for(const n of this.currentUserSubs)try{const r=n(e);r&&typeof r.then=="function"&&r.catch(()=>{})}catch{}}async enablePersistence(e){if(this.persistence){if(this.persistence.options.key!==e.key)throw new ie("failed-precondition",`Persistence already enabled with key '${this.persistence.options.key}'; cannot re-enable with key '${e.key}'. Dispose and recreate the sandbox.`);return}if(this.enablePersistencePromise)return this.enablePersistencePromise;this.enablePersistencePromise=(async()=>{const n=await Bm(this,e);this.persistence=n})();try{await this.enablePersistencePromise}finally{this.enablePersistencePromise=null}}enableTabSync(e){return Km(this,e)}async flush(){if(!this.persistence)throw new ie("failed-precondition","flush() called before enablePersistence()");await this.persistence.flush()}async clearPersistence(){this.persistence&&await this.persistence.clear()}registerPersistableService(e,n){if(this.serviceRegistry.has(e))throw new ie("failed-precondition",`registerPersistableService: a service named '${e}' is already registered on this sandbox. Each service name must be unique — the auth package registers 'auth' exactly once per sandbox.`);return this.serviceRegistry.set(e,n),this._onServiceRegistered&&this._onServiceRegistered(e,n),()=>{this.serviceRegistry.get(e)===n&&(this.serviceRegistry.delete(e),this._onServiceUnregistered?.(e))}}setServiceRegistrationHook(e){this._onServiceRegistered=e}setServiceUnregistrationHook(e){this._onServiceUnregistered=e}getServiceRegistry(){return this.serviceRegistry}}function Xm(t,e){if(t===e)return!0;if(t===null||e===null||t.uid!==e.uid)return!1;const n=t.token===void 0?void 0:JSON.stringify(t.token),r=e.token===void 0?void 0:JSON.stringify(e.token);return n===r}function Xe(t){if(!(t instanceof Nt))throw new ie("invalid-argument","Sandbox handle was not produced by initializeSandbox(); custom Sandbox implementations are not supported.");return t.getEnv()}function ny(t,e,n){if(!(t instanceof Nt))throw new ie("invalid-argument","Sandbox handle was not produced by initializeSandbox(); custom Sandbox implementations are not supported.");t.emitInternal(e,n)}function ry(t){return{kind:"service_mutation",id:Bt(),at:Date.now(),...t}}function sy(t){const{at:e,...n}=t;return{kind:"operation",id:Bt(),at:e??Date.now(),...n}}function iy(t){const{at:e,...n}=t;return{kind:"commit",id:Bt(),at:e??Date.now(),...n}}function ay(t){const{at:e,...n}=t;return{kind:"listener",id:Bt(),at:e??Date.now(),...n}}function oy(){return Nt.createRoot()}const eg=Symbol.for("pyric.remote.sandbox");function Di(t){return t!=null&&t[eg]===!0}const tg={read:new Set(["auth","data","root","now"]),write:new Set(["auth","data","newData","root","now"]),validate:new Set(["auth","data","newData","root","now"])},ng=new Set(["val","exists","hasChild","hasChildren","isString","isNumber","isBoolean","child","parent","getPriority"]),rg=new Set(["matches","contains","beginsWith","endsWith","replace","toLowerCase","toUpperCase","length"]),sg=new Set([...ng,...rg]);let Fn=[],ar="read",au=new Set,gs;function ig(){if(gs)return gs;const t=Bf();return t.addOperation("validate",{_nonterminal(...e){e.forEach(n=>n.validate())},_iter(...e){e.forEach(n=>n.validate())},_terminal(){},CallExpr_methodCall(e,n,r,s,i,a){e.validate();const o=r.sourceString;sg.has(o)||Fn.push({code:"UNKNOWN_METHOD",message:`Unknown method '${o}'`}),i.asIteration().children.forEach(c=>c.validate())},CallExpr_memberAccess(e,n,r){e.validate()},CallExpr_indexAccess(e,n,r,s){e.validate(),r.validate()},ident(e,n,r){const s=this.sourceString;if(e.sourceString==="$")return;const a=tg[ar];a&&(!a.has(s)&&!au.has(s)&&Fn.push({code:"UNKNOWN_IDENTIFIER",message:`Identifier '${s}' is not allowed in '${ar}' context`}),s==="newData"&&ar==="read"&&Fn.push({code:"NEWDATA_IN_READ",message:"'newData' is not available in 'read' context"}))}}),gs=t,t}function cy(t,e,n=[]){const r=Uf(t);return r.failed()?[]:(Fn=[],ar=e,au=new Set(n.map(s=>s.startsWith("$")?s.slice(1):s)),ig()(r).validate(),[...Fn])}const uy=He({operation:mn(["read","write","validate"]),path:qe().min(1).startsWith("/"),auth:Kr([He({uid:qe(),token:Tt(mt())}),Ac()]),mockData:Tt(mt()),newData:mt().optional(),updates:xc(He({path:qe().min(1).startsWith("/"),value:mt()})).optional()});mn(["INVALID_INPUT","NO_MATCHING_RULE","EVALUATION_ERROR"]);He({allowed:$n(),unsupported:$n().optional(),matchedPath:qe(),matchedRule:qe(),reason:qe(),pathVariableBindings:Tt(qe())});const ho="-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz";let fo=0;const jt=new Array(12).fill(0);function ly(t=Date.now()){const e=t===fo;fo=t;const n=new Array(8);let r=t;for(let i=7;i>=0;i--)n[i]=ho.charAt(r%64),r=Math.floor(r/64);if(r!==0)throw new Error("RTDB push-id: timestamp overflow.");let s=n.join("");if(e){let i;for(i=11;i>=0&&jt[i]===63;i--)jt[i]=0;if(i<0)for(let a=0;a<12;a++)jt[a]=Math.floor(Math.random()*64);else jt[i]=(jt[i]??0)+1}else for(let i=0;i<12;i++)jt[i]=Math.floor(Math.random()*64);for(let i=0;i<12;i++)s+=ho.charAt(jt[i]);if(s.length!==20)throw new Error(`RTDB push-id: bad length ${s.length}.`);return s}function Un(t){return t.replace(/^\/+|\/+$/g,"").split("/")}function ou(t){return Un(t).length%2===0&&Un(t).length>0}function Mi(t){return Un(t).length%2===1}function Yr(t){const e=Un(t);return e[e.length-1]??""}function cu(t){return Un(t).slice(0,-1).join("/")}function uu(t,e){const n=e!==void 0,r=n?Gn(e):void 0;return{id:t.id,ref:t,exists:n,data:()=>n?r:void 0,get:s=>wn(r,s)}}const po=new WeakMap;let ag=1;function mo(t){let e=po.get(t);return e===void 0&&(e=ag++,po.set(t,e)),e}function $r(t){if(t===null||typeof t=="boolean")return t;if(typeof t=="string")return Op(t);if(typeof t>"u")return{type:"undefined"};if(typeof t=="bigint")return Zt("bigint",t.toString());if(typeof t=="number"){const n=Number.isNaN(t)?"NaN":t===1/0?"Infinity":t===-1/0?"-Infinity":Object.is(t,-0)?"-0":String(t);return Zt("number",n)}if(typeof t!="object"&&typeof t!="function")return{type:typeof t,value:String(t)};const e=Tp(t);if(e!==void 0)return e;try{if(Array.isArray(t))return{type:"array",id:mo(t)}}catch{}return{type:"opaque-object",id:mo(t)}}function _t(t){return new ue({code:"invalid-argument",message:t})}function si(t,e,n,r=!1,s=!1){if(t===null||typeof t=="string"||typeof t=="boolean")return{comparison:t,execution:t};if(typeof t=="number")return{comparison:t,execution:t};if(typeof t>"u"||typeof t=="bigint"||typeof t=="function"||typeof t=="symbol")throw _t(`Unsupported Firestore query value: ${typeof t}.`);if(typeof t!="object")throw _t("Unsupported Firestore query value.");const i=kc(t);if(i!==void 0){const o=np(t);if(o!==void 0&&n!==void 0&&o!==n)throw _t("Document reference belongs to a different Firestore database.");return{comparison:{type:"registered-firestore-value",value:i},execution:rp(t)}}if(t instanceof Date){const o=t.getTime();if(!Number.isFinite(o))throw _t("Invalid Date query value.");const c=Math.floor(o/1e3),u=Object.freeze({seconds:c,nanoseconds:Math.floor((o-c*1e3)*1e6)}),d={type:"timestamp",...u};return tn(u,d,()=>Object.freeze({...u})),{comparison:{type:"registered-firestore-value",value:d},execution:u}}if(t instanceof Uint8Array){const o=t.slice();return{comparison:{type:"bytes",values:Array.from(o)},execution:o}}if(e.has(t))throw _t("Cyclic query operands are not Firestore values.");const a=Object.getPrototypeOf(t);if(a!==Object.prototype&&a!==null&&!Array.isArray(t))throw _t("Firestore query maps must be plain objects.");e.add(t);try{if(Array.isArray(t)){if(s&&!r)throw _t("Nested arrays are not supported.");const u=t.map(l=>si(l,e,n,r,!0)),d=u.map(l=>l.execution);return ut(d,$r(t)),{comparison:{type:"array",values:u.map(l=>l.comparison)},execution:d}}const o=Object.keys(t).sort().map(u=>({key:u,captured:si(t[u],e,n,r,!1)})),c=Object.fromEntries(o.map(({key:u,captured:d})=>[u,d.execution]));return ut(c,$r(t)),{comparison:{type:"map",entries:o.map(({key:u,captured:d})=>[u,d.comparison])},execution:c}}finally{e.delete(t)}}function lu(t,e,n=!1){try{const r=si(t,new Set,e,n);return Object.freeze({kind:"canonical",value:r.comparison,executionValue:r.execution})}catch(r){if(r instanceof ue)throw r;const s=r instanceof Error?r.message:String(r);throw _t(`Invalid Firestore query value: ${s}`)}}function du(t,e){return Ye(t.value,e.value)}function or(t,e){if(t.kind==="where"){const n="comparisonValue"in t?t.comparisonValue:lu(t.value,e,t.op==="in"||t.op==="not-in");return Object.freeze({kind:"where",field:t.field,op:t.op,value:n.executionValue,comparisonValue:n})}return Object.freeze({kind:t.kind,filters:Object.freeze(t.filters.map(n=>or(n,e)))})}function er(t,e,n,r){const s=t.map(i=>lu(i,r));return Object.freeze({values:Object.freeze(s.map(i=>i.executionValue)),comparisonValues:Object.freeze(s),inclusive:e,fromSnapshot:n})}function hu(t,e){return t.length!==e.length?!1:t.every((n,r)=>{const s=e[r];return n.kind!==s.kind?!1:n.kind==="where"&&s.kind==="where"?n.field===s.field&&n.op===s.op&&du(n.comparisonValue,s.comparisonValue):n.kind!=="where"&&s.kind!=="where"&&hu(n.filters,s.filters)})}function go(t,e){return t===void 0||e===void 0?t===e:t.inclusive===e.inclusive&&t.comparisonValues.length===e.comparisonValues.length&&t.comparisonValues.every((n,r)=>du(n,e.comparisonValues[r]))}function og(t,e){return t.kind!==e.kind?!1:t.kind==="collection"&&e.kind==="collection"?t.path===e.path:t.kind==="collection-group"&&e.kind==="collection-group"&&t.collectionId===e.collectionId}function fu(t){return t.kind==="where"?Object.freeze({kind:t.kind,field:t.field,op:t.op,value:t.value}):Object.freeze({kind:t.kind,filters:Object.freeze(t.filters.map(fu))})}function yo(t){if(t!==void 0)return Object.freeze({values:t.values,inclusive:t.inclusive,fromSnapshot:t.fromSnapshot})}function cg(t,e){return hu(t.filters,e.filters)&&t.orders.length===e.orders.length&&t.orders.every((n,r)=>{const s=e.orders[r];return n.field===s.field&&n.direction===s.direction})&&t.limitCount===e.limitCount&&t.limitFromEnd===e.limitFromEnd&&go(t.start,e.start)&&go(t.end,e.end)}const pu="__name__";function bo(t,e){const n=t.data();if(n===void 0)throw new ue({code:"not-found",message:`Snapshot-based cursors require an existing document — got an empty snapshot for ${t.id??"<unknown>"}.`});return e.map(r=>r.field===pu?t.ref:n[r.field])}class Bn{env;auth;collectionPath;clauses;orders;limitCount;limitFromEnd;start;end;bypassRules;documentRef;constructor(e){this.env=e.env,this.auth=e.auth,this.collectionPath=e.collectionPath,this.documentRef=e.documentRef,this.clauses=Object.freeze((e.clauses??[]).map(n=>or(n))),this.orders=Object.freeze((e.orders??[]).map(n=>Object.freeze({...n}))),this.limitCount=e.limitCount,this.limitFromEnd=e.limitFromEnd??!1,this.start=e.start===void 0?void 0:Object.freeze({...e.start,values:Object.freeze(e.start.comparisonValues.map(n=>n.executionValue)),comparisonValues:e.start.comparisonValues}),this.end=e.end===void 0?void 0:Object.freeze({...e.end,values:Object.freeze(e.end.comparisonValues.map(n=>n.executionValue)),comparisonValues:e.end.comparisonValues}),this.bypassRules=e.bypassRules??!1}where(e,n,r){return this.clone({clauses:[...this.clauses,or({kind:"where",field:e,op:n,value:r})]})}applyFilter(e){return this.clone({clauses:[...this.clauses,or(e)]})}orderBy(e,n="asc"){return this.clone({orders:[...this.orders,{field:e,direction:n}]})}limit(e){return this.clone({limitCount:e,limitFromEnd:!1})}limitToLast(e){return this.clone({limitCount:e,limitFromEnd:!0})}startCursor(e,n){return this.clone({start:er(this.normalizeExplicitCursorValues(e),n,!1)})}endCursor(e,n){return this.clone({end:er(this.normalizeExplicitCursorValues(e),n,!1)})}startCursorFromSnapshot(e,n){return this.clone({start:er(bo(e,this.normalizedOrders()),n,!0)})}endCursorFromSnapshot(e,n){return this.clone({end:er(bo(e,this.normalizedOrders()),n,!0)})}isStructurallyEqual(e){return e instanceof Bn?this.env===e.env&&this.bypassRules===e.bypassRules&&og(this.queryScope(),e.queryScope())&&cg(this.comparableExecutionSpec(),e.comparableExecutionSpec()):!1}clone(e){return new Bn({env:this.env,auth:this.auth,collectionPath:this.collectionPath,documentRef:this.documentRef,clauses:e.clauses??this.clauses,orders:e.orders??this.orders,limitCount:"limitCount"in e?e.limitCount:this.limitCount,limitFromEnd:e.limitFromEnd??this.limitFromEnd,start:"start"in e?e.start:this.start,end:"end"in e?e.end:this.end,bypassRules:this.bypassRules})}queryScope(){return{kind:"collection",path:this.collectionPath}}readQueryRows(e){const n=e?.auth!==void 0?e.auth:this.auth;let r;try{r=this.env.runQuery({scope:this.queryScope(),auth:n,execution:this.executionSpec(),bypassRules:this.bypassRules,activityQuery:this.activityQuery()})}catch(s){const i=s?.simError;throw i?new ue(i):s}if(!r.allowed)throw new ue(r.error);return r.docs}activityQuery(){const e=r=>r.kind==="where"?{kind:"where",field:r.field,op:r.op,value:$r(r.value)}:{kind:r.kind,filters:r.filters.map(e)},n=r=>r===void 0?null:{values:r.values.map(s=>$r(s)),inclusive:r.inclusive,fromSnapshot:r.fromSnapshot};return{scope:this.activityScope(),filters:this.clauses.map(e),orderBy:this.orders.map(r=>({...r})),limit:this.limitCount??null,limitFromEnd:this.limitFromEnd,start:n(this.start),end:n(this.end)}}activityScope(){return{kind:"collection"}}normalizedOrders(){return Wc(this.executionSpec())}normalizeExplicitCursorValues(e){const n=this.orders;return e.map((r,s)=>{if(n[s]?.field!==pu)return r;if(typeof r!="string")throw new ue({code:"invalid-argument",message:"Expected a string for a document ID cursor value."});const i=r.includes("/")?r:`${this.collectionPath}/${r}`;return this.documentRef(i)})}executionSpec(){const e={filters:Object.freeze(this.clauses.map(fu)),orders:this.orders,limitCount:this.limitCount,limitFromEnd:this.limitFromEnd,start:yo(this.start),end:yo(this.end)};return Object.freeze(e)}comparableExecutionSpec(){return{filters:this.clauses,orders:this.orders,limitCount:this.limitCount,limitFromEnd:this.limitFromEnd,start:this.start,end:this.end}}snapshotConstraints(){return Object.freeze({execution:this.executionSpec(),activityQuery:this.activityQuery()})}async get(e){const r=this.readQueryRows(e).map(s=>{const i=this.documentRef(s.path),a=Gn(s.data);return{id:i.id,ref:i,exists:!0,data:()=>a,get:o=>wn(a,o)}});return{size:r.length,empty:r.length===0,docs:r,forEach(s){r.forEach(s)}}}async aggregate(e,n){const r=this.readQueryRows(n),s={};for(const i of Object.keys(e))s[i]=lg(e[i],r);return{data:()=>s}}}function ug(t,e){if(!e.includes("."))return t[e];let n=t;for(const r of e.split(".")){if(typeof n!="object"||n===null||Array.isArray(n))return;n=n[r]}return n}function lg(t,e){if(t.kind==="count")return e.length;let n=0,r=0;for(const s of e){const i=ug(s.data,t.field);typeof i=="number"&&Number.isFinite(i)&&(n+=i,r++)}return t.kind==="sum"?n:r===0?null:n/r}function sn(t,e){if(t.error)throw new ue(t.error);const n=t.debugMessages.length>0?t.debugMessages.join("; "):"(no debug message)";throw new ue(te("permission-denied",`${e}: ${n}`))}class dg{env;auth;bypassRules;collectionRef;id;path;constructor(e,n,r,s=!1,i){this.env=e,this.auth=n,this.bypassRules=s,this.collectionRef=i,this.path=r,this.id=Yr(r),ut(this,Zt("reference",r)),Ei(this,r,e)}get parent(){return this.collectionRef(cu(this.path))}collection(e){return this.collectionRef(`${this.path}/${e}`)}async get(e){const n=this.env.execute({method:"get",path:this.path,auth:e?.auth!==void 0?e.auth:this.auth,bypassRules:this.bypassRules});n.allowed||sn(n,"get denied");const r=n.data===void 0||n.data===null?void 0:n.data;return uu(this,r)}async set(e,n){const r=n?.auth!==void 0?n.auth:this.auth;if(n?.mergeFields!==void 0){const i=n.mergeFields.map(u=>String(u)),o=this.env.getDocument(this.path)===null?"create":"update",c=this.env.execute({method:o,path:this.path,data:e,auth:r,merge:{mergeFields:i},bypassRules:this.bypassRules});c.allowed||sn(c,`set denied (as ${o})`);return}if(n?.merge===!0){const a=this.env.getDocument(this.path)===null?"create":"update",o=this.env.execute({method:a,path:this.path,data:e,auth:r,merge:!0,bypassRules:this.bypassRules});o.allowed||sn(o,`set denied (as ${a})`);return}const s=this.env.execute({method:"set",path:this.path,data:e,auth:r,bypassRules:this.bypassRules});s.allowed||sn(s,"set denied")}async update(e,n){const r=this.env.execute({method:"update",path:this.path,data:e,auth:n?.auth!==void 0?n.auth:this.auth,bypassRules:this.bypassRules});r.allowed||sn(r,"update denied")}async delete(e){const n=this.env.execute({method:"delete",path:this.path,auth:e?.auth!==void 0?e.auth:this.auth,bypassRules:this.bypassRules});n.allowed||sn(n,"delete denied")}}function qr(t,e,n,r){return new dg(t,e,n,r,s=>new mu(t,e,s,r))}class mu extends Bn{id;path;constructor(e,n,r,s=!1){super({env:e,auth:n,collectionPath:r,bypassRules:s,documentRef:i=>qr(e,n,i,s)}),this.path=r,this.id=Yr(r)}doc(e){const n=e??Ti();return qr(this.env,this.auth,`${this.path}/${n}`,this.bypassRules)}async add(e,n){const r=this.doc();return await r.set(e,n),r}}class ji extends Bn{collectionId;constructor(e){super({...e,collectionPath:"",documentRef:n=>qr(e.env,e.auth,n,e.bypassRules??!1)}),this.collectionId=e.collectionId}clone(e){return new ji({env:this.env,auth:this.auth,collectionId:this.collectionId,clauses:e.clauses??this.clauses,orders:e.orders??this.orders,limitCount:"limitCount"in e?e.limitCount:this.limitCount,limitFromEnd:e.limitFromEnd??this.limitFromEnd,start:"start"in e?e.start:this.start,end:"end"in e?e.end:this.end,bypassRules:this.bypassRules})}queryScope(){return{kind:"collection-group",collectionId:this.collectionId}}activityScope(){return{kind:"collection-group"}}}class hg{env;auth;bypassRules;ops=[];constructor(e,n,r=!1){this.env=e,this.auth=n,this.bypassRules=r}set(e,n){const s=this.env.getDocument(e.path)===null?"create":"update";return this.ops.push({method:s,path:e.path,data:n}),this}update(e,n){return this.ops.push({method:"update",path:e.path,data:n}),this}delete(e){return this.ops.push({method:"delete",path:e.path}),this}async commit(e){if(this.ops.length===0)return;const n=this.env.batch(this.ops,e?.auth!==void 0?e.auth:this.auth,this.bypassRules);if(n.allowed)return;if(n.error)throw new ue(n.error);const s=n.results.find(i=>!i.allowed)?.debugMessages.join("; ")??"batch denied";throw new ue(te("permission-denied",`batch failed: ${s}`))}}function fg(t){return typeof t.where=="function"}class pg{simTx;constructor(e){this.simTx=e}async get(e){if(fg(e)){const s=await e.get();return s.size>0&&this.simTx.getAll(...s.docs.map(i=>i.ref.path)),s}const r=this.simTx.get(e.path).data();return uu(e,r)}set(e,n){return this.simTx.set(e.path,n),this}update(e,n){return this.simTx.update(e.path,n),this}delete(e){return this.simTx.delete(e.path),this}}class mg{env;auth;bypassRules;provenance;constructor(e,n,r=!1,s){this.env=e,this.auth=n,this.bypassRules=r,this.provenance=s}collection(e){if(!Mi(e))throw new ue(te("invalid-argument",`collection path must have an odd number of segments: ${e}`));return new mu(this.env,this.auth,e,this.bypassRules)}doc(e){if(!ou(e))throw new ue(te("invalid-argument",`document path must have an even number of segments: ${e}`));return qr(this.env,this.auth,e,this.bypassRules)}collectionGroup(e){if(e.length===0||e.includes("/"))throw new ue(te("invalid-argument",`collection group id must be a single non-empty segment with no '/': ${e}`));return new ji({env:this.env,auth:this.auth,collectionId:e,bypassRules:this.bypassRules})}batch(){return new hg(this.env,this.auth,this.bypassRules)}async runTransaction(e,n){let r;try{r=await this.env.transaction(s=>{const i=new pg(s);return e(i)},{auth:n?.auth!==void 0?n.auth:this.auth,bypassRules:this.bypassRules,provenance:this.provenance,maxAttempts:n?.maxAttempts})}catch(s){throw s instanceof Kc?new ue(s.simError):s instanceof Zc?new ue(s.simError):s}if(!r.allowed){if(r.error)throw new ue(r.error);const i=r.writes.find(a=>!a.allowed)?.debugMessages.join("; ")??"transaction denied at commit";throw new ue(te("permission-denied",`transaction failed: ${i}`))}return r.returnValue}}function gg(t,e){return new mg(t,e?.auth??null,e?.bypassRules??!1,e?.provenance)}const gu=Symbol("pyric/sandbox/context"),yu=Symbol("pyric/sandbox/bypassRules");let ii=null;function yg(t){ii=t}function bg(t){const e=t;return typeof e.path=="string"&&e.path.length>0||typeof e.collectionPath=="string"&&e.collectionPath.length>0}function vg(t){const e=t.trim();if(!e)return[];const n=e.indexOf(": ");if(n!==-1){const s=e.slice(n+2).trim().split("; ").map(i=>i.trim()).filter(i=>i.length>0);if(s.length>0)return s}return[e]}function vo(t,e){if(t instanceof ue===!1)return t;const r=t.code;if(r==="permission-denied"===!1)return new ie(r,t.message);const i={auth:e.auth,reasons:vg(t.message)},a=t.simError;if(a!==void 0){if(a.request!==void 0){const y=a.request;i.request={method:y.method,path:y.path},y.resourceData!==void 0&&(i.request.resourceData=y.resourceData)}if(a.resource!==void 0&&(i.resource={data:a.resource.data,exists:a.resource.exists}),a.query!==void 0&&(i.query=a.query),a.rule!==void 0&&(i.rule=a.rule),a.remediation!==void 0)return new ie({code:r,message:t.message,denialContext:i,remediation:a.remediation})}return new ie(r,t.message,i)}function Ur(t,e,n=!1){return new Proxy(t,{get(r,s,i){if(s===gu)return e;if(s===yu)return n;if(s==="onSnapshot"&&ii!==null&&!(s in r)&&bg(r))return(...o)=>ii(i,...o);const a=Reflect.get(r,s,i);return typeof a!="function"?a:function(...o){let c;try{const u=()=>a.apply(r,o);c=e.sandbox.runWithProvenance?.(Ri(e.operationContext),u)??u()}catch(u){throw vo(u,e)}return c instanceof Promise?c.then(u=>u&&typeof u=="object"?Ur(u,e,n):u).catch(u=>{throw vo(u,e)}):c&&typeof c=="object"?Ur(c,e,n):c}}})}function bu(t,e=!1){if(Di(t.sandbox))throw new Error("pyric/sandbox/admin-firestore: internal — a remote sandbox context reached the local engine builder; remote dispatch should have handled it. Please report this.");const n=()=>gg(Xe(t.sandbox),{auth:t.auth,bypassRules:e,provenance:Ri(t.operationContext)});return{collection(r){return n().collection(r)},doc(r){return n().doc(r)},collectionGroup(r){return n().collectionGroup(r)},batch(){return n().batch()},runTransaction(r,s){return n().runTransaction(r,s)},setRules(r){return Xe(t.sandbox).deployRules(r)},seed(r){const s=Xe(t.sandbox);return s.seed({rules:s.getRules(),documents:r?.documents??{}})},snapshot(){return Xe(t.sandbox).snapshot()}}}function ai(t){if(t instanceof ie)return t;if(t!==null&&typeof t=="object"){const e=t;if(typeof e.code=="string"&&typeof e.message=="string"){const n=e.denialContext!==null&&typeof e.denialContext=="object"?e.denialContext:void 0;return new ie(e.code,e.message,n)}}return t}function yt(t){return new ie("invalid-argument",t)}async function et(t,e){try{return await t.sandbox.channel.op({...e,actAs:t.lens})}catch(n){throw ai(n)}}const wg=new Set(["serverTimestamp","increment","arrayUnion","arrayRemove","deleteField"]);function Sg(t){return t!==null&&typeof t=="object"&&typeof t.__type=="string"&&wg.has(t.__type)}function _g(t){switch(t.__type){case"serverTimestamp":return{__sentinel:"serverTimestamp"};case"increment":return{__sentinel:"increment",n:t.value};case"arrayUnion":return{__sentinel:"arrayUnion",values:t.values.map(vt)};case"arrayRemove":return{__sentinel:"arrayRemove",values:t.values.map(vt)};case"deleteField":return{__sentinel:"deleteField"}}}function vt(t){if(t===null||typeof t!="object")return t;if(Sg(t))return _g(t);if(t instanceof xt)return t.toJSON();if(t instanceof Date)return xt.fromDate(t).toJSON();if(Array.isArray(t))return t.map(vt);const e=Object.getPrototypeOf(t);if(e!==Object.prototype&&e!==null){const r=t.toJSON;if(typeof r=="function")return r.call(t);throw yt(`remote Firestore: cannot serialize a ${e.constructor?.name??"class"} instance for the wire — use plain data, Timestamp, Date, or FieldValue sentinels.`)}const n={};for(const[r,s]of Object.entries(t))n[r]=vt(s);return n}function Jt(t){return vt(t)}function oi(t){return Fi(JSON.parse(t.json))}function vu(t){return Gn(oi(t))}function wu(t,e){const n=e.exists&&e.data?vu(e.data):void 0;return{id:t.id,ref:t,exists:e.exists,data:()=>n,get:r=>wn(n,r)}}function Su(t,e){const n=e.docs.map(r=>{const s=r.path??r.id,i=Br(t,s),a=r.data?vu(r.data):{};return{id:i.id,ref:i,exists:!0,data:()=>a,get:o=>wn(a,o)}});return{size:n.length,empty:n.length===0,docs:n,forEach(r){n.forEach(s=>r(s))}}}const Pi=Symbol("pyric/sandbox/admin-firestore/remoteSnapshotRegistrar");function Ag(t){if(t===null||typeof t!="object")return;const e=t[Pi];return typeof e=="function"?e:void 0}let ci=null;function xg(t){ci=t}function _u(...t){if(ci===null)throw new ie("failed-precondition","remote Firestore: onSnapshot is not wired yet — import pyric-admin/firestore (or pyric/sandbox/admin-firestore) before subscribing.");return ci(this,...t)}function Au(t,e,n,r,s){const i=n.includeMetadataChanges!==!0;let a,o;try{o=t.sandbox.channel.subscribe({target:e,actAs:t.lens},c=>{if(!r)return;const u=c;if(Array.isArray(u.docs)){const d=u.docs.map(y=>({path:y.path??y.id,data:y.data?oi(y.data):{}})),l=e.__ref==="query"?e.source.__ref==="group"?e.source.collectionId:e.source.path:e.__ref==="group"?e.collectionId:e.path,p=cn({path:l},d,{excludesMetadataChanges:i},a);a=d,r(p)}else if(typeof u.id=="string"){const d=u.path??u.id,l=u.exists&&u.data?oi(u.data):null;r(on(d,l))}},c=>{const u=ai(c);s?s(u):console.error("pyric remote Firestore: uncaught onSnapshot error:",u)})}catch(c){throw ai(c)}return o}const xu=Symbol("pyric/sandbox/admin-firestore/remoteQueryState");function Ig(t){if(!(t===null||typeof t!="object"))return t[xu]}function Iu(t){return t.kind==="where"?(Eu(t.op),{kind:"where",field:t.field,op:t.op,value:vt(t.value)}):{kind:t.kind,filters:t.filters.map(Iu)}}const Eg=new Set(["<","<=","==","!=",">=",">","in","not-in","array-contains","array-contains-any"]);function Eu(t){if(!Eg.has(t))throw yt(`invalid where operator: ${String(t)}`)}function cr(t){const e=[...t.filters];for(const n of t.orders)e.push({kind:"orderBy",field:n.field,direction:n.direction});return t.start&&e.push({kind:t.start.inclusive?"startAt":"startAfter",values:t.start.values.map(vt)}),t.end&&e.push({kind:t.end.inclusive?"endAt":"endBefore",values:t.end.values.map(vt)}),t.limitCount!==void 0&&e.push(t.limitFromEnd?{kind:"limitToLast",n:t.limitCount}:{kind:"limit",n:t.limitCount}),e.length===0?t.source:{__ref:"query",source:t.source,constraints:e}}function wo(t,e,n){if(e.length===0)throw yt(`${n}(snapshot) on a remote sandbox requires at least one explicit orderBy() clause — the relay protocol has no document-key cursor.`);if(e.some(s=>s.field==="__name__"))throw yt(`${n}(snapshot) on a remote sandbox does not support orderBy('__name__') — the relay protocol has no document-key cursor, and __name__ is not a data field a value cursor can carry. Order by a real document field instead.`);const r=t.data();if(r===void 0)throw new ie("not-found",`Snapshot-based cursors require an existing document — got an empty snapshot for ${t.id??"<unknown>"}.`);return e.map(s=>r[s.field])}function $i(t,e){const n=s=>$i(t,{...e,...s});return{[xu]:e,where(s,i,a){return Eu(i),n({filters:[...e.filters,{kind:"where",field:s,op:i,value:vt(a)}]})},applyFilter(s){return n({filters:[...e.filters,Iu(s)]})},orderBy(s,i="asc"){return n({orders:[...e.orders,{field:s,direction:i}]})},limit(s){return n({limitCount:s,limitFromEnd:!1})},limitToLast(s){return n({limitCount:s,limitFromEnd:!0})},startCursor(s,i){return n({start:{values:[...s],inclusive:i}})},endCursor(s,i){return n({end:{values:[...s],inclusive:i}})},startCursorFromSnapshot(s,i){return n({start:{values:wo(s,e.orders,i?"startAt":"startAfter"),inclusive:i}})},endCursorFromSnapshot(s,i){return n({end:{values:wo(s,e.orders,i?"endAt":"endBefore"),inclusive:i}})},async get(s){ur(e);const i=await et(t,{method:"getDocs",source:cr(e)});return Su(t,i)},async aggregate(s){ur(e);const i=await et(t,{method:"aggregate",source:cr(e),spec:s});return{data:()=>i.data}},[Pi]:(s,i,a)=>(ur(e),Au(t,cr(e),s,i,a)),onSnapshot:_u}}function ur(t){if(t.limitFromEnd&&t.orders.length===0)throw yt("limitToLast() queries require at least one orderBy clause.")}function ui(t,e){const n=$i(t,{source:{__ref:"collection",path:e},filters:[],orders:[],limitFromEnd:!1});return Object.assign(Object.create(Object.getPrototypeOf(n)),n,{id:Yr(e),path:e,doc(s){const i=s??Ti();return Br(t,`${e}/${i}`)},async add(s,i){const a=await et(t,{method:"addDoc",collectionPath:e,data:Jt(s)});return Br(t,a.path)}})}function Br(t,e){const n={id:Yr(e),path:e,get parent(){return ui(t,cu(e))},collection(r){const s=`${e}/${r}`;if(!Mi(s))throw yt(`collection path must have an odd number of segments: ${s}`);return ui(t,s)},async get(r){const s=await et(t,{method:"getDoc",path:e});return wu(n,s)},async set(r,s){await et(t,{method:"setDoc",path:e,data:Jt(r),...So(s)?{options:So(s)}:{}})},async update(r,s){await et(t,{method:"updateDoc",path:e,data:Jt(r)})},async delete(r){await et(t,{method:"deleteDoc",path:e})},[Pi]:(r,s,i)=>Au(t,{__ref:"doc",path:e},r,s,i),onSnapshot:_u};return n}function So(t){if(!t)return;const e={};return t.merge!==void 0&&(e.merge=t.merge),t.mergeFields!==void 0&&(e.mergeFields=[...t.mergeFields]),e.merge!==void 0||e.mergeFields!==void 0?e:void 0}function kg(t){const e=[];let n=!1;const r={set(i,a){return s(),e.push({method:"set",path:i.path,data:Jt(a)}),r},update(i,a){return s(),e.push({method:"update",path:i.path,data:Jt(a)}),r},delete(i){return s(),e.push({method:"delete",path:i.path}),r},async commit(i){s(),n=!0,await et(t,{method:"batchCommit",writes:e})}};function s(){if(n)throw new ie("failed-precondition","WriteBatch has already been committed.")}return r}const Og=5;async function Cg(t,e,n=Og){for(let r=0;r<n;r++){const s=[],i=[],a=()=>{if(i.length>0)throw new ie("failed-precondition",Xs)},o={get(l){a();const p=Ig(l);return p!==void 0?u(p):c(l)},set(l,p){return i.push({method:"set",path:l.path,data:Jt(p)}),o},update(l,p){return i.push({method:"update",path:l.path,data:Jt(p)}),o},delete(l){return i.push({method:"delete",path:l.path}),o}};async function c(l){const p=await et(t,{method:"getDoc",path:l.path});return s.push({path:p.path??l.path,data:p.exists&&p.data?p.data:null}),wu(l,p)}async function u(l){ur(l);const p=await et(t,{method:"getDocs",source:cr(l)});for(const y of p.docs)s.push({path:y.path??y.id,data:y.data??null});return Su(t,p)}const d=await e(o);try{return await et(t,{method:"txnCommit",reads:s,writes:i}),d}catch(l){if(l instanceof ie&&l.code==="aborted")continue;throw l}}throw new ie("aborted",`Transaction failed after ${n} attempts due to repeated conflicts. Another writer is concurrently updating the same documents.`)}function ys(t,e){return new ie("unimplemented",`SandboxFirestore.${t} is not available on a remote sandbox — its return value is synchronous and the data lives in the browser worker. ${e}`)}function ku(t,e){const n={sandbox:t,lens:e};return{collection(r){if(!Mi(r))throw yt(`collection path must have an odd number of segments: ${r}`);return ui(n,r)},doc(r){if(!ou(r))throw yt(`document path must have an even number of segments: ${r}`);return Br(n,r)},collectionGroup(r){if(r.length===0||r.includes("/"))throw yt(`collection group id must be a single non-empty segment with no '/': ${r}`);return $i(n,{source:{__ref:"group",collectionId:r},filters:[],orders:[],limitFromEnd:!1})},batch(){return kg(n)},runTransaction(r,s){return Cg(n,r,s?.maxAttempts)},setRules(){throw ys("setRules","Deploy rules asynchronously through the relay instead: `await sandbox.channel.op({ method: 'setFirestoreRules', source })`.")},seed(){throw ys("seed","The relay has no atomic seed op; write seed docs through this handle (`db.doc(path).set(data)` / `db.batch()`), or drive `sandbox.channel.op({ method: 'admin.setDocument', path, data })` per document.")},snapshot(){throw ys("snapshot","Read the worker state asynchronously instead: `await sandbox.channel.op({ method: 'admin.readState' })`.")}}}const _o=new WeakMap;function Ou(t){const e=_o.get(t);if(e)return e;const n=Di(t.sandbox)?ku(t.sandbox,Tg(t.auth)):Ur(bu(t),t);return _o.set(t,n),n}function Tg(t){return t==null?{mode:"anon"}:t.token===void 0?{mode:"as",uid:t.uid}:{mode:"as",uid:t.uid,token:t.token}}const Ao=new WeakMap;function Rg(t){const e=Ng(t)?t:t.withAuth(null),n=Ao.get(e);if(n)return n;const r=e.operationContext.authLens.mode==="admin"?e:Li(e,{source:e.operationContext.source,authLens:{mode:"admin"},...e.operationContext.planId===void 0?{}:{planId:e.operationContext.planId}}),s=Di(r.sandbox)?ku(r.sandbox,{mode:"admin"}):Ur(bu(r,!0),r,!0);return Ao.set(e,s),s}function Ng(t){return t!==null&&typeof t=="object"&&"sandbox"in t&&typeof t.withAuth=="function"}const tr=Symbol("pyric/firestore/followsCurrentUser"),bs=Symbol("pyric/firestore/authSessionScope");function Lg(t){if(t===null||typeof t!="object")return null;const e=t;return typeof e.path=="string"&&e.path.length>0?e.path:typeof e.collectionPath=="string"&&e.collectionPath.length>0?e.collectionPath:null}function Fg(t){if(t!==null&&typeof t=="object"){const e=t.snapshotConstraints;if(typeof e=="function")return e.call(t)}}function Dg(t){if(t===null||typeof t!="object")return!1;const e=t;return typeof e.path=="string"&&e.path.length>0&&e.parent!==void 0&&e.parent!==null}function Cu(t,e,n,r,s){let i={},a,o;if(typeof e=="object"&&e!==null&&typeof e.next!="function"&&typeof e.error!="function"&&typeof e.complete!="function"){if(i=e,typeof n=="function")a=n,o=r;else if(typeof n=="object"&&n!==null){const C=n;a=C.next,o=C.error}}else if(typeof e=="function")a=e,o=n;else if(typeof e=="object"&&e!==null){const C=e;a=C.next,o=C.error}if(!a&&!o)throw new TypeError("onSnapshot: missing handler. Provide a callback, or an observer with a `next` and/or `error` method.");const u=Ag(t);if(u){if(i[tr]===!0)throw new ie("unimplemented","onSnapshot: live (follows-current-user) listeners are not supported on a remote sandbox — remote listeners are frozen to the identity of the context that created the ref.");return u(i,a,o)}const d=Mg(t),l=Xe(d.sandbox);let p;if(Dg(t))p={kind:"doc",path:t.path};else{const C=Lg(t);if(C===null)throw new TypeError("onSnapshot: could not determine the collection path for this Query. Pass a CollectionReference or a Query produced by `.where`/`.orderBy`/`.limit` on a CollectionReference obtained from `getFirestore(ctx)`.");const I=Fg(t);p={kind:"query",collection:C,constraints:I}}const y=i[tr]===!0,b=i[bs],w=t[yu]===!0;if(tr in i){const{[tr]:C,...I}=i;i=I}if(bs in i){const{[bs]:C,...I}=i;i=I}const R=()=>l.addSnapshotListener(p,a??(()=>{}),i,d.auth,o,y,w,b);return d.sandbox.runWithProvenance?.(Ri(d.operationContext),R)??R()}function Mg(t){if(t===null||typeof t!="object")throw new TypeError("onSnapshot: reference must be a DocumentReference or Query.");const e=t[gu];if(!e)throw new TypeError("onSnapshot: reference was not produced by a sandbox context — pass a ref obtained from `getFirestore(ctx)`.");return e}yg(Cu);xg(Cu);class qt{bytes;constructor(e){this.bytes=e,ut(this,Cp(e)),tn(this,Object.freeze({type:"bytes",values:Object.freeze(Array.from(e))}),()=>new qt(e.slice()))}static fromBase64String(e){const n=atob(e),r=new Uint8Array(n.length);for(let s=0;s<n.length;s+=1)r[s]=n.charCodeAt(s);return new qt(r)}static fromUint8Array(e){return new qt(e.slice())}toBase64(){let e="";for(const n of this.bytes)e+=String.fromCharCode(n);return btoa(e)}toUint8Array(){return this.bytes.slice()}toString(){return`Bytes(base64: ${this.toBase64()})`}isEqual(e){return e instanceof qt&&this.bytes.length===e.bytes.length&&this.bytes.every((n,r)=>n===e.bytes[r])}toJSON(){return{type:"firestore/bytes/1.0",bytes:this.toBase64()}}static fromJSON(e){const n=e;if(n.type!=="firestore/bytes/1.0"||typeof n.bytes!="string")throw new TypeError("Invalid Bytes JSON value.");return qt.fromBase64String(n.bytes)}}class Dn{lat;lng;constructor(e,n){if(this.lat=e,this.lng=n,!Number.isFinite(e)||e<-90||e>90)throw new TypeError("Latitude must be a number between -90 and 90.");if(!Number.isFinite(n)||n<-180||n>180)throw new TypeError("Longitude must be a number between -180 and 180.");ut(this,Zt("geo-point",String(e),"\0",String(n))),tn(this,Object.freeze({type:"geo-point",latitude:e,longitude:n}),()=>new Dn(e,n))}get latitude(){return this.lat}get longitude(){return this.lng}isEqual(e){return e instanceof Dn&&this.lat===e.lat&&this.lng===e.lng}toJSON(){return{latitude:this.lat,longitude:this.lng,type:"firestore/geoPoint/1.0"}}static fromJSON(e){const n=e;if(n.type!=="firestore/geoPoint/1.0"||typeof n.latitude!="number"||typeof n.longitude!="number")throw new TypeError("Invalid GeoPoint JSON value.");return new Dn(n.latitude,n.longitude)}}class ln{_values;constructor(e){this._values=e,tn(this,Object.freeze({type:"vector",values:Object.freeze(e.slice())}),()=>new ln(e.slice()))}static create(e){if(!e.every(n=>typeof n=="number"))throw new TypeError("Vector values must be numbers.");return new ln(e.slice())}toArray(){return this._values.slice()}isEqual(e){const n=e instanceof ln?e._values:void 0;return n!==void 0&&this._values.length===n.length&&this._values.every((r,s)=>r===n[s])}toJSON(){return{type:"firestore/vectorValue/1.0",vectorValues:this.toArray()}}static fromJSON(e){const n=e;if(n.type!=="firestore/vectorValue/1.0"||!Array.isArray(n.vectorValues)||!n.vectorValues.every(r=>typeof r=="number"))throw new TypeError("Invalid VectorValue JSON value.");return ln.create(n.vectorValues)}}function jg(t=[]){return ln.create(t)}function dy(){return Rp.serverTimestamp()}const kt=Symbol("pyric/firestore/target");function Jn(t){return t.kind==="sandbox"?t.db:t.getDb()}const Xr=new WeakMap;function Pg(t,e){return Xr.set(t,e),t}const Qn=new WeakMap;function $g(t,e,n){return Xr.set(t,e),Qn.set(t,n),t}function qi(t,e){const n=_n(e);if(t.kind==="sandbox")return n;const r=Qn.get(n);if(!r)throw new TypeError("pyric/firestore: live ref missing rebuild closure — was it produced by a factory in this package?");return r(Jn(t))}function qg(t,e){const n=_n(e);if(t.kind==="sandbox")return n;const r=Qn.get(n);if(!r)throw new TypeError("pyric/firestore: live collection ref missing rebuild closure.");return r(Jn(t))}function hy(t,e){const n=_n(e);if(t.kind==="sandbox")return n;const r=Qn.get(n);if(!r)throw new TypeError("pyric/firestore: live query missing rebuild closure.");return r(Jn(t))}function zn(t,e,n){return e.kind==="sandbox-live"?$g(t,e,n):Pg(t,e)}function fy(t){const e=_n(t),n=Qn.get(e);return n||(()=>e)}function Sn(t){const e=Ug(t);return e.assertUsable?.(),e}function Ug(t){let e;if(kt in t?e=t[kt]:e=Xr.get(t),!e)throw new TypeError("pyric/firestore: unrecognized reference — was it produced by a factory in this package?");return e}const Tu=new WeakMap,Ru=new WeakMap;function Ui(t){return Tu.get(t)}function _n(t){return Ru.get(t)??t}function Nu(t,e,n){const r={id:t.id??"",path:t.path??""};return Tu.set(r,n),Ru.set(r,t),Xr.set(r,e),r}function Bg(t){return t instanceof en?Array.from(t.value):null}function li(t){if(t instanceof We)return qt.fromUint8Array(t.data);if(t instanceof ot)return new Dn(t.lat,t.lng);const e=Bg(t);if(e)return jg(e);if(Array.isArray(t))return t.map(li);if(t!==null&&typeof t=="object"){const n=Object.getPrototypeOf(t);if(n===Object.prototype||n===null){const r={};for(const[s,i]of Object.entries(t))r[s]=li(i);return r}}return t}function py(t){if(t!==void 0)return li(t)}class bn extends Error{code;customData;name="FirebaseError";constructor(e,n,r){super(n),this.code=e,this.customData=r,Object.setPrototypeOf(this,new.target.prototype)}}Object.defineProperty(bn,"name",{value:"FirebaseError"});let zr;function my(t){zr=t}function Lu(t){return zr?.resolve(t,!1)}function zg(){if(!zr)throw new TypeError("No default sandbox app registry is installed - import and initialize pyric/app before calling a service factory without an app.");return zr.defaultApp()}function Vg(t){if(t===void 0)return Vg(zg());const e=Lu(t);if(e)return e.service("firestore/default",()=>{const{sandbox:n,session:r}=e,s=vs();e.onDelete(s.terminate);const i=e.authScope;i&&s.own(r.onCurrentUserChanged(o=>{Xe(n).reevaluateLiveListeners(o,i)}));const a={kind:"sandbox-live",sandbox:n,getDb:xo(n,()=>r.currentUser),authScope:i,...s};return{[kt]:a,app:t}});if(Fu(t)){const r={kind:"sandbox",db:Ou(t),sandbox:t.sandbox,...vs()};return{[kt]:r}}if(Hg(t)){const n={kind:"sandbox-live",sandbox:t,getDb:xo(t),...vs()};return{[kt]:n}}throw new TypeError("pyric/firestore is a sandbox-only mirror. Package resolution must leave firebase/firestore unchanged for production; activate pyric dev or @pyric/cli/register before importing to select the sandbox.")}function vs(){let t=!1;const e=new Set;return{own(n){return t?(n(),()=>{}):(e.add(n),()=>e.delete(n))},assertUsable(){if(t)throw new bn("failed-precondition","The client has already been terminated.")},terminate(){if(!t){t=!0;for(const n of e)n();e.clear()}}}}function Wg(t){const e=Lu(t);if(e){e.assertAlive();const a=e.sandbox;return Wg(Li(a.withAuth(null),{source:{kind:"app"},authLens:{mode:"admin"}}))}const n=Fu(t)?t:t.withAuth(null),r=n.sandbox,i={kind:"sandbox",db:Rg(n),sandbox:r};return{[kt]:i}}function Fu(t){return t instanceof Zn}function Hg(t){if(t===null||typeof t!="object")return!1;const e=t;return typeof e.withAuth=="function"&&typeof e.onCurrentUserChanged=="function"&&"currentUser"in e&&"admin"in e}function xo(t,e=()=>t.currentUser){return()=>{const n=Li(t.withAuth(e()),{source:{kind:"app"},authLens:{mode:"app-session"}});return Ou(n)}}class Gg{started=!1;networkEnabled=!0;persistenceMode;pending=new Set;cachedPaths=new Set;cachedQueries=new WeakSet;syncObservers=new Set;syncScheduled=!1;markStarted(){this.started=!0}enablePersistence(e){if(this.started||this.persistenceMode!==void 0)throw new bn("failed-precondition","Firestore has already been started and persistence can no longer be enabled.");this.persistenceMode=e,this.started=!0}disableNetwork(){this.started=!0,this.networkEnabled=!1}async enableNetwork(){this.started=!0,this.networkEnabled=!0;for(const e of this.pending)e.localDone&&e.resolve(e.value);await Promise.all([...this.pending].map(e=>e.promise))}runWrite(e,n){if(this.started=!0,n&&this.cachedPaths.add(n),this.networkEnabled)return e();let r,s;const i=new Promise((o,c)=>{r=o,s=c}),a={path:n,promise:i,localDone:!1,resolve:r,reject:s};return this.pending.add(a),e().then(o=>{a.localDone=!0,a.value=o,this.networkEnabled&&a.resolve(o)},o=>a.reject(o)),i.then(()=>this.pending.delete(a),()=>this.pending.delete(a)),i}waitForPendingWrites(){this.started=!0;const e=[...this.pending].map(n=>n.promise);return Promise.all(e).then(()=>{})}cachePath(e){this.started=!0,this.cachedPaths.add(e)}assertPathCached(e){if(this.started=!0,!this.cachedPaths.has(e))throw new bn("unavailable","Failed to get document from cache. (However, this document may exist on the server.)")}cacheQuery(e){this.started=!0,this.cachedQueries.add(e)}hasCachedQuery(e){return this.started=!0,this.cachedQueries.has(e)||this.cachedPaths.size>0}snapshotMetadata(e){return Object.freeze({fromCache:!this.networkEnabled,hasPendingWrites:[...this.pending].some(n=>n.path===e)})}querySnapshotMetadata(){return Object.freeze({fromCache:!this.networkEnabled,hasPendingWrites:this.pending.size>0})}addSnapshotsInSyncObserver(e){return this.syncObservers.add(e),e(),()=>this.syncObservers.delete(e)}notifySnapshotDelivered(){this.syncScheduled||this.syncObservers.size===0||(this.syncScheduled=!0,queueMicrotask(()=>{this.syncScheduled=!1;for(const e of[...this.syncObservers])e()}))}}const Io=new WeakMap;function Vn(t){let e=Io.get(t);return e||(e=new Gg,Io.set(t,e)),e}function ws(t,e,n){return ut(t,Zt("reference",e)),Ei(t,e,n),t}function gy(t,...e){const n=Sn(t),r=kt in t,s=r?void 0:Ui(t),i=Jn(n);if(r){if(e.length===0)throw new TypeError("doc(db, path) requires at least one path segment.");const d=e.join("/"),l=i.doc(d),p=zn(l,n,y=>y.doc(d));return ws(p,d,n)}const a=_n(t),o=e.length===0?a.doc():a.doc(e.join("/")),c=o.path,u=zn(o,n,d=>d.doc(c));if(s){const d=Nu(u,n,s);return ws(d,c,n)}return ws(u,c,n)}function yy(t,...e){const n=Sn(t),r=kt in t;if(e.length===0)throw new TypeError("collection() requires at least one path segment.");if(r){const c=e.join("/"),u=Jn(n).collection(c);return zn(u,n,d=>d.collection(c))}const s=_n(t),i=e.join("/"),a=s.collection(i),o=a.path;return zn(a,n,c=>c.collection(o))}function Kg(t){return t instanceof Error&&"code"in t&&typeof t.code=="string"}function Zg(t){if(t instanceof bn||!Kg(t))return t;const e={};t.denialContext!==void 0&&(e.denialContext=t.denialContext),t.remediation!==void 0&&(e.remediation=t.remediation);const n=new bn(t.code,t.message,Object.keys(e).length===0?void 0:e);return t.denialContext!==void 0&&Object.assign(n,{denialContext:t.denialContext}),t.remediation!==void 0&&Object.assign(n,{remediation:t.remediation}),n}async function es(t){try{return await t()}catch(e){throw Zg(e)}}async function by(t,e,n){const r=Sn(t),s=Ui(t),i=s?s.toFirestore(e):e;return Vn(r).runWrite(()=>es(()=>qi(r,t).set(i,n)),t.path)}async function vy(t,e){const n=Sn(t);return Vn(n).runWrite(()=>es(()=>qi(n,t).update(e)),t.path)}async function wy(t){const e=Sn(t);return Vn(e).runWrite(()=>es(()=>qi(e,t).delete()),t.path)}async function Sy(t,e){const n=Sn(t),r=Ui(t),s=r?r.toFirestore(e):e,i=await Vn(n).runWrite(async()=>{const c=await es(()=>qg(n,t).add(s));return Vn(n).cachePath(c.path),c}),a=i.path,o=zn(i,n,c=>c.doc(a));if(ut(o,Zt("reference",a)),Ei(o,a,n,o),r){const c=Nu(o,n,r);return sp(o,c),c}return o}function _y(t,e){return Xe(t).deployRules(e)}function Ay(t,e){const n=Xe(t);return n.seed({rules:n.getRules(),documents:e})}function xy(t){return Xe(t).snapshot()}function Iy(t,e={}){const n=e.recentEventLimit??10,r=Xe(t),s=r.getRules(),i=s?Ds(s):{warnings:[]},a=i.warnings.map(w=>({rule:w.rule,severity:w.severity,message:w.message})),o={errors:0,warnings:0,info:0};for(const w of i.warnings)w.severity==="error"?o.errors++:w.severity==="warning"?o.warnings++:o.info++;const c=r.snapshot(),u={};for(const w of Object.keys(c)){const R=w.split("/")[0]??"";R&&(u[R]=(u[R]??0)+1)}const d=t.history(),l=[];for(const w of d){const R=w.kind==="request",C=w.kind==="operation",I=w.kind==="listener";(R||C||I&&w.phase==="errored")&&l.push(w)}const p=[];for(const w of l)if(w.result==="deny")p.push(w);else{const C=w.error;C!==void 0&&C.code==="PERMISSION_DENIED"&&p.push(w)}const y=l.slice(-n).map(w=>{let R="";if(w.path!==void 0)R=String(w.path);else{const N=w.target;N!==void 0&&N.path!==void 0&&(R=String(N.path))}let C="listen";w.method!==void 0&&(C=String(w.method));let I="error";if(w.result!==void 0)I=String(w.result);else{const N=w.error;N!==void 0&&N.code==="PERMISSION_DENIED"&&(I="deny")}let E=null;return w.auth!==void 0&&(E=w.auth),{path:R,method:C,result:I,auth:E}}),b=p.slice(-n).map(w=>{let R="";if(w.path!==void 0)R=String(w.path);else{const N=w.target;N!==void 0&&N.path!==void 0&&(R=String(N.path))}let C="listen";w.method!==void 0&&(C=String(w.method));let I=null;w.auth!==void 0&&(I=w.auth);let E;return typeof w.debugMessage=="string"&&(E=w.debugMessage),{path:R,method:C,auth:I,debugMessage:E}});return{rules:{source:s,sizeBytes:new TextEncoder().encode(s).byteLength,isEmpty:s.trim().length===0,lint:{...o,findings:a}},documents:{totalCount:Object.keys(c).length,byCollection:u},events:{totalCount:d.length,recentDenials:b,recentRequests:y}}}export{Or as $,Vn as A,_n as B,Qn as C,bs as D,bn as E,tr as F,yy as G,Sy as H,vy as I,wy as J,ty as K,ey as L,my as M,Fi as N,hr as O,Ni as P,Ri as Q,ce as R,uy as S,Li as T,Zn as U,gt as V,pt as W,pn as X,$s as Y,me as Z,Wt as _,Ay as a,Ir as a0,Xe as a1,Wg as a2,co as a3,zg as a4,Lu as a5,ie as a6,Xg as a7,ei as a8,xt as a9,Dn as aa,qt as ab,Pg as ac,py as ad,Ru as ae,Ei as af,du as ag,qi as ah,hy as ai,dy as aj,by as b,xy as c,gy as d,oy as e,Bf as f,Vg as g,ny as h,Iy as i,ry as j,sy as k,iy as l,Uf as m,ay as n,ly as o,Ui as p,fy as q,Yg as r,_y as s,Sn as t,Zg as u,cy as v,Jn as w,zn as x,Nu as y,lu as z};
@@ -1,4 +1,4 @@
1
- import{s as n,a as f,b as h,u as d,r as m}from"./app.bnmVTkIY.js";import{s as w,b as o,aj as p,d as s,aa as A,a9 as g}from"./sandbox-controls.C9Aaazt8.js";import"./jsx-runtime.D_zvdyIk.js";import"./index.DBy5LfQW.js";import"./reads.BYBRLbsE.js";import"./index.DzVde04M.js";import"./index.DNyk7q8W.js";async function b(a){n.createUser(a,{uid:"alice",email:"alice@gmail.com",displayName:"Alice Nguyen",emailVerified:!0,photoUrl:"https://lh3.googleusercontent.com/a/alice",providerUserInfo:[{providerId:"google.com"}],customClaims:{plan:"pro"}}),n.createUser(a,{uid:"bob",email:"bob@example.com",password:"pyric-demo",displayName:"Bob Carter",emailVerified:!0,customClaims:{role:"editor"}}),n.createUser(a,{uid:"carol",email:"carol@example.com",displayName:"Carol Diaz",emailVerified:!1}),await f(a),await h(a)}const y=new A(37.7749,-122.4194);async function C(a){const r=Date.now(),i=e=>g.fromMillis(r-e*6e4),l=[{id:"alice",name:"Alice Nguyen",email:"alice@gmail.com",plan:"pro"},{id:"bob",name:"Bob Carter",email:"bob@example.com",plan:"free"},{id:"carol",name:"Carol Diaz",email:"carol@example.com",plan:"free"}];for(const e of l)await o(s(a,"users",e.id),{name:e.name,email:e.email,plan:e.plan,createdAt:p()});const t=["alice","bob","carol"],c=["Ship the redesign","Reply to carol","Buy milk","Draft the launch post","Review the rules","Plan offsite","Renew the domain","Read the spec","Fix the flaky test","Call the bank","Water the plants","Book the flights"];for(let e=0;e<c.length;e++){const u=t[e%t.length];await o(s(a,"notes",`note-${String(e+1).padStart(2,"0")}`),{title:c[e],done:e%3===0,pinned:e===0,priority:e%3+1,ownerId:u,ownerRef:`users/${u}`,tags:e%2===0?["work","urgent"]:["personal"],meta:{source:e%2===0?"app":"import",revision:e+1,flags:{starred:e%4===0,archived:!1}},location:e%3===0?y:null,createdAt:i(120-e*7),updatedAt:p()})}await o(s(a,"posts","post-hello"),{title:"Hello world",body:"First post from the seeded sandbox.",authorRef:"users/alice",published:!0,publishedAt:i(8)}),await o(s(a,"posts","post-draft"),{title:"Draft: roadmap",body:"Unpublished draft.",authorRef:"users/bob",published:!1})}async function R(a){const r=new TextEncoder,l=Uint8Array.from(atob("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=="),t=>t.charCodeAt(0));await d(m(a,"avatars/alice.png"),l,{contentType:"image/png"}),await d(m(a,"notes/note-01/attachment.txt"),r.encode(`Attachment for the redesign note.
1
+ import{s as n,a as f,b as h,u as d,r as m}from"./app.B7pBzz5N.js";import{s as w,b as o,aj as p,d as s,aa as A,a9 as g}from"./sandbox-controls.C2IqtoSw.js";import"./jsx-runtime.D_zvdyIk.js";import"./index.DBy5LfQW.js";import"./reads.Dh3z0fJy.js";import"./index.uwPvjH_1.js";import"./index.DNyk7q8W.js";async function b(a){n.createUser(a,{uid:"alice",email:"alice@gmail.com",displayName:"Alice Nguyen",emailVerified:!0,photoUrl:"https://lh3.googleusercontent.com/a/alice",providerUserInfo:[{providerId:"google.com"}],customClaims:{plan:"pro"}}),n.createUser(a,{uid:"bob",email:"bob@example.com",password:"pyric-demo",displayName:"Bob Carter",emailVerified:!0,customClaims:{role:"editor"}}),n.createUser(a,{uid:"carol",email:"carol@example.com",displayName:"Carol Diaz",emailVerified:!1}),await f(a),await h(a)}const y=new A(37.7749,-122.4194);async function C(a){const r=Date.now(),i=e=>g.fromMillis(r-e*6e4),l=[{id:"alice",name:"Alice Nguyen",email:"alice@gmail.com",plan:"pro"},{id:"bob",name:"Bob Carter",email:"bob@example.com",plan:"free"},{id:"carol",name:"Carol Diaz",email:"carol@example.com",plan:"free"}];for(const e of l)await o(s(a,"users",e.id),{name:e.name,email:e.email,plan:e.plan,createdAt:p()});const t=["alice","bob","carol"],c=["Ship the redesign","Reply to carol","Buy milk","Draft the launch post","Review the rules","Plan offsite","Renew the domain","Read the spec","Fix the flaky test","Call the bank","Water the plants","Book the flights"];for(let e=0;e<c.length;e++){const u=t[e%t.length];await o(s(a,"notes",`note-${String(e+1).padStart(2,"0")}`),{title:c[e],done:e%3===0,pinned:e===0,priority:e%3+1,ownerId:u,ownerRef:`users/${u}`,tags:e%2===0?["work","urgent"]:["personal"],meta:{source:e%2===0?"app":"import",revision:e+1,flags:{starred:e%4===0,archived:!1}},location:e%3===0?y:null,createdAt:i(120-e*7),updatedAt:p()})}await o(s(a,"posts","post-hello"),{title:"Hello world",body:"First post from the seeded sandbox.",authorRef:"users/alice",published:!0,publishedAt:i(8)}),await o(s(a,"posts","post-draft"),{title:"Draft: roadmap",body:"Unpublished draft.",authorRef:"users/bob",published:!1})}async function R(a){const r=new TextEncoder,l=Uint8Array.from(atob("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=="),t=>t.charCodeAt(0));await d(m(a,"avatars/alice.png"),l,{contentType:"image/png"}),await d(m(a,"notes/note-01/attachment.txt"),r.encode(`Attachment for the redesign note.
2
2
  `),{contentType:"text/plain"})}const x=`rules_version = '2';
3
3
  service cloud.firestore {
4
4
  match /databases/{database}/documents {
@@ -4,7 +4,7 @@
4
4
  } catch {}
5
5
  document.documentElement.setAttribute('data-theme', 'dark');
6
6
  </script><link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin><link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500;700&display=swap" rel="stylesheet"><link rel="stylesheet" href="/__pyric/ui/_astro/_studio_.B6b_G1ev.css">
7
- <link rel="stylesheet" href="/__pyric/ui/_astro/app.BsFsMjn0.css"></head> <body> <div id="root" data-astro-cid-w5sm6wlz> <style>astro-island,astro-slot,astro-static-slot{display:contents}</style><script>(()=>{var e=async t=>{await(await t())()};(self.Astro||(self.Astro={})).only=e;window.dispatchEvent(new Event("astro:only"));})();</script><script>(()=>{var A=Object.defineProperty;var g=(i,o,a)=>o in i?A(i,o,{enumerable:!0,configurable:!0,writable:!0,value:a}):i[o]=a;var d=(i,o,a)=>g(i,typeof o!="symbol"?o+"":o,a);{let i={0:t=>m(t),1:t=>a(t),2:t=>new RegExp(t),3:t=>new Date(t),4:t=>new Map(a(t)),5:t=>new Set(a(t)),6:t=>BigInt(t),7:t=>new URL(t),8:t=>new Uint8Array(t),9:t=>new Uint16Array(t),10:t=>new Uint32Array(t),11:t=>1/0*t},o=t=>{let[l,e]=t;return l in i?i[l](e):void 0},a=t=>t.map(o),m=t=>typeof t!="object"||t===null?t:Object.fromEntries(Object.entries(t).map(([l,e])=>[l,o(e)]));class y extends HTMLElement{constructor(){super(...arguments);d(this,"Component");d(this,"hydrator");d(this,"hydrate",async()=>{var b;if(!this.hydrator||!this.isConnected)return;let e=(b=this.parentElement)==null?void 0:b.closest("astro-island[ssr]");if(e){e.addEventListener("astro:hydrate",this.hydrate,{once:!0});return}let c=this.querySelectorAll("astro-slot"),n={},h=this.querySelectorAll("template[data-astro-template]");for(let r of h){let s=r.closest(this.tagName);s!=null&&s.isSameNode(this)&&(n[r.getAttribute("data-astro-template")||"default"]=r.innerHTML,r.remove())}for(let r of c){let s=r.closest(this.tagName);s!=null&&s.isSameNode(this)&&(n[r.getAttribute("name")||"default"]=r.innerHTML)}let p;try{p=this.hasAttribute("props")?m(JSON.parse(this.getAttribute("props"))):{}}catch(r){let s=this.getAttribute("component-url")||"<unknown>",v=this.getAttribute("component-export");throw v&&(s+=` (export ${v})`),console.error(`[hydrate] Error parsing props for component ${s}`,this.getAttribute("props"),r),r}let u;await this.hydrator(this)(this.Component,p,n,{client:this.getAttribute("client")}),this.removeAttribute("ssr"),this.dispatchEvent(new CustomEvent("astro:hydrate"))});d(this,"unmount",()=>{this.isConnected||this.dispatchEvent(new CustomEvent("astro:unmount"))})}disconnectedCallback(){document.removeEventListener("astro:after-swap",this.unmount),document.addEventListener("astro:after-swap",this.unmount,{once:!0})}connectedCallback(){if(!this.hasAttribute("await-children")||document.readyState==="interactive"||document.readyState==="complete")this.childrenConnectedCallback();else{let e=()=>{document.removeEventListener("DOMContentLoaded",e),c.disconnect(),this.childrenConnectedCallback()},c=new MutationObserver(()=>{var n;((n=this.lastChild)==null?void 0:n.nodeType)===Node.COMMENT_NODE&&this.lastChild.nodeValue==="astro:end"&&(this.lastChild.remove(),e())});c.observe(this,{childList:!0}),document.addEventListener("DOMContentLoaded",e)}}async childrenConnectedCallback(){let e=this.getAttribute("before-hydration-url");e&&await import(e),this.start()}async start(){let e=JSON.parse(this.getAttribute("opts")),c=this.getAttribute("client");if(Astro[c]===void 0){window.addEventListener(`astro:${c}`,()=>this.start(),{once:!0});return}try{await Astro[c](async()=>{let n=this.getAttribute("renderer-url"),[h,{default:p}]=await Promise.all([import(this.getAttribute("component-url")),n?import(n):()=>()=>{}]),u=this.getAttribute("component-export")||"default";if(!u.includes("."))this.Component=h[u];else{this.Component=h;for(let f of u.split("."))this.Component=this.Component[f]}return this.hydrator=p,this.hydrate},e,this)}catch(n){console.error(`[astro-island] Error hydrating ${this.getAttribute("component-url")}`,n)}}attributeChangedCallback(){this.hydrate()}}d(y,"observedAttributes",["props"]),customElements.get("astro-island")||customElements.define("astro-island",y)}})();</script><astro-island uid="b1btC" component-url="/__pyric/ui/_astro/app.t6u-adB_.js" component-export="StudioApp" renderer-url="/__pyric/ui/_astro/client.D2ORs4B-.js" props="{&quot;data-astro-cid-w5sm6wlz&quot;:[0,true]}" ssr client="only" opts="{&quot;name&quot;:&quot;StudioApp&quot;,&quot;value&quot;:&quot;react&quot;}" await-children><p class="studio-loading" aria-live="polite" data-astro-cid-w5sm6wlz>
7
+ <link rel="stylesheet" href="/__pyric/ui/_astro/app.BsFsMjn0.css"></head> <body> <div id="root" data-astro-cid-w5sm6wlz> <style>astro-island,astro-slot,astro-static-slot{display:contents}</style><script>(()=>{var e=async t=>{await(await t())()};(self.Astro||(self.Astro={})).only=e;window.dispatchEvent(new Event("astro:only"));})();</script><script>(()=>{var A=Object.defineProperty;var g=(i,o,a)=>o in i?A(i,o,{enumerable:!0,configurable:!0,writable:!0,value:a}):i[o]=a;var d=(i,o,a)=>g(i,typeof o!="symbol"?o+"":o,a);{let i={0:t=>m(t),1:t=>a(t),2:t=>new RegExp(t),3:t=>new Date(t),4:t=>new Map(a(t)),5:t=>new Set(a(t)),6:t=>BigInt(t),7:t=>new URL(t),8:t=>new Uint8Array(t),9:t=>new Uint16Array(t),10:t=>new Uint32Array(t),11:t=>1/0*t},o=t=>{let[l,e]=t;return l in i?i[l](e):void 0},a=t=>t.map(o),m=t=>typeof t!="object"||t===null?t:Object.fromEntries(Object.entries(t).map(([l,e])=>[l,o(e)]));class y extends HTMLElement{constructor(){super(...arguments);d(this,"Component");d(this,"hydrator");d(this,"hydrate",async()=>{var b;if(!this.hydrator||!this.isConnected)return;let e=(b=this.parentElement)==null?void 0:b.closest("astro-island[ssr]");if(e){e.addEventListener("astro:hydrate",this.hydrate,{once:!0});return}let c=this.querySelectorAll("astro-slot"),n={},h=this.querySelectorAll("template[data-astro-template]");for(let r of h){let s=r.closest(this.tagName);s!=null&&s.isSameNode(this)&&(n[r.getAttribute("data-astro-template")||"default"]=r.innerHTML,r.remove())}for(let r of c){let s=r.closest(this.tagName);s!=null&&s.isSameNode(this)&&(n[r.getAttribute("name")||"default"]=r.innerHTML)}let p;try{p=this.hasAttribute("props")?m(JSON.parse(this.getAttribute("props"))):{}}catch(r){let s=this.getAttribute("component-url")||"<unknown>",v=this.getAttribute("component-export");throw v&&(s+=` (export ${v})`),console.error(`[hydrate] Error parsing props for component ${s}`,this.getAttribute("props"),r),r}let u;await this.hydrator(this)(this.Component,p,n,{client:this.getAttribute("client")}),this.removeAttribute("ssr"),this.dispatchEvent(new CustomEvent("astro:hydrate"))});d(this,"unmount",()=>{this.isConnected||this.dispatchEvent(new CustomEvent("astro:unmount"))})}disconnectedCallback(){document.removeEventListener("astro:after-swap",this.unmount),document.addEventListener("astro:after-swap",this.unmount,{once:!0})}connectedCallback(){if(!this.hasAttribute("await-children")||document.readyState==="interactive"||document.readyState==="complete")this.childrenConnectedCallback();else{let e=()=>{document.removeEventListener("DOMContentLoaded",e),c.disconnect(),this.childrenConnectedCallback()},c=new MutationObserver(()=>{var n;((n=this.lastChild)==null?void 0:n.nodeType)===Node.COMMENT_NODE&&this.lastChild.nodeValue==="astro:end"&&(this.lastChild.remove(),e())});c.observe(this,{childList:!0}),document.addEventListener("DOMContentLoaded",e)}}async childrenConnectedCallback(){let e=this.getAttribute("before-hydration-url");e&&await import(e),this.start()}async start(){let e=JSON.parse(this.getAttribute("opts")),c=this.getAttribute("client");if(Astro[c]===void 0){window.addEventListener(`astro:${c}`,()=>this.start(),{once:!0});return}try{await Astro[c](async()=>{let n=this.getAttribute("renderer-url"),[h,{default:p}]=await Promise.all([import(this.getAttribute("component-url")),n?import(n):()=>()=>{}]),u=this.getAttribute("component-export")||"default";if(!u.includes("."))this.Component=h[u];else{this.Component=h;for(let f of u.split("."))this.Component=this.Component[f]}return this.hydrator=p,this.hydrate},e,this)}catch(n){console.error(`[astro-island] Error hydrating ${this.getAttribute("component-url")}`,n)}}attributeChangedCallback(){this.hydrate()}}d(y,"observedAttributes",["props"]),customElements.get("astro-island")||customElements.define("astro-island",y)}})();</script><astro-island uid="b1btC" component-url="/__pyric/ui/_astro/app.boex5SnQ.js" component-export="StudioApp" renderer-url="/__pyric/ui/_astro/client.D2ORs4B-.js" props="{&quot;data-astro-cid-w5sm6wlz&quot;:[0,true]}" ssr client="only" opts="{&quot;name&quot;:&quot;StudioApp&quot;,&quot;value&quot;:&quot;react&quot;}" await-children><p class="studio-loading" aria-live="polite" data-astro-cid-w5sm6wlz>
8
8
  Starting Pyric Studio…
9
9
  </p><template data-astro-template="fallback"><p class="studio-loading" aria-live="polite" data-astro-cid-w5sm6wlz>
10
10
  Starting Pyric Studio…