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

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 (174) hide show
  1. package/README.md +9 -4
  2. package/README.md.orig +5 -1
  3. package/dist/bridge/server/mcp-contract.d.ts +2 -2
  4. package/dist/bridge/server/mcp-contract.d.ts.map +1 -1
  5. package/dist/bridge/server/mcp-contract.js +3 -0
  6. package/dist/bridge/server/mcp-contract.js.map +1 -1
  7. package/dist/cli/index.d.ts +1 -0
  8. package/dist/cli/index.d.ts.map +1 -1
  9. package/dist/cli/index.js +3 -0
  10. package/dist/cli/index.js.map +1 -1
  11. package/dist/cli/mcp-proxy.d.ts.map +1 -1
  12. package/dist/cli/mcp-proxy.js.map +1 -1
  13. package/dist/cli/rules.d.ts +1 -0
  14. package/dist/cli/rules.d.ts.map +1 -1
  15. package/dist/cli/rules.js +18 -4
  16. package/dist/cli/rules.js.map +1 -1
  17. package/dist/cli/service-command-records/storage-rules-resolve.d.ts +4 -0
  18. package/dist/cli/service-command-records/storage-rules-resolve.d.ts.map +1 -0
  19. package/dist/cli/service-command-records/storage-rules-resolve.js +3 -0
  20. package/dist/cli/service-command-records/storage-rules-resolve.js.map +1 -0
  21. package/dist/cli/service-commands.generated.d.ts +3 -0
  22. package/dist/cli/service-commands.generated.d.ts.map +1 -1
  23. package/dist/cli/service-commands.generated.js +2 -0
  24. package/dist/cli/service-commands.generated.js.map +1 -1
  25. package/dist/serve/rules.d.ts +3 -3
  26. package/dist/serve/rules.d.ts.map +1 -1
  27. package/dist/serve/rules.js +13 -5
  28. package/dist/serve/rules.js.map +1 -1
  29. package/dist/serve/site-ui/_astro/{RulesCodeEditor.CzwHdCi9.js → RulesCodeEditor.Bl-XMkhD.js} +1 -1
  30. package/dist/serve/site-ui/_astro/_example_.B9DG9HLJ.css +1 -0
  31. package/dist/serve/site-ui/_astro/{_slug_.C6QfVOxJ.css → _slug_.CupVK4TM.css} +1 -1
  32. package/dist/serve/site-ui/_astro/_studio_.CfxiQWkk.css +1 -0
  33. package/dist/serve/site-ui/_astro/app.Ce3MTLQm.js +1 -0
  34. package/dist/serve/site-ui/_astro/app.taqzyjD0.js +11 -0
  35. package/dist/serve/site-ui/_astro/chess-showcase.Dh5D8kqe.js +354 -0
  36. package/dist/serve/site-ui/_astro/{example-runtime.B0byNQOl.js → example-runtime.CuyAjjiG.js} +2 -26
  37. package/dist/serve/site-ui/_astro/sandbox-controls.BP4M5f1M.js +1169 -0
  38. package/dist/serve/site-ui/_astro/seed.CSUkloMi.js +20 -0
  39. package/dist/serve/site-ui/_astro/writes.C57paAj2.js +99 -0
  40. package/dist/serve/site-ui/auth/index.html +2 -2
  41. package/dist/serve/site-ui/docs/_rhythm/index.html +1 -1
  42. package/dist/serve/site-ui/docs/agent/set-up-your-agent/index.html +29 -4
  43. package/dist/serve/site-ui/docs/agent/set-up-your-agent.md +8 -5
  44. package/dist/serve/site-ui/docs/agent/watch-and-review/index.html +1 -1
  45. package/dist/serve/site-ui/docs/agent/work-with-an-agent/index.html +1 -1
  46. package/dist/serve/site-ui/docs/ai-compat/index.html +1 -1
  47. package/dist/serve/site-ui/docs/api-reference/index.html +1 -1
  48. package/dist/serve/site-ui/docs/app-compat/index.html +1 -1
  49. package/dist/serve/site-ui/docs/auth-compat/index.html +1 -1
  50. package/dist/serve/site-ui/docs/build/ai-logic/index.html +1 -1
  51. package/dist/serve/site-ui/docs/build/authentication/index.html +1 -1
  52. package/dist/serve/site-ui/docs/build/cloud-firestore/index.html +30 -52
  53. package/dist/serve/site-ui/docs/build/cloud-firestore.md +40 -36
  54. package/dist/serve/site-ui/docs/build/cloud-messaging/index.html +1 -1
  55. package/dist/serve/site-ui/docs/build/cloud-storage/index.html +1 -1
  56. package/dist/serve/site-ui/docs/build/realtime-database/index.html +1 -1
  57. package/dist/serve/site-ui/docs/conformance-scores/index.html +1 -1
  58. package/dist/serve/site-ui/docs/create-pyric-reference-api/index.html +1 -1
  59. package/dist/serve/site-ui/docs/database-compat/index.html +1 -1
  60. package/dist/serve/site-ui/docs/examples/chess/index.html +645 -249
  61. package/dist/serve/site-ui/docs/examples/chess.md +45 -16
  62. package/dist/serve/site-ui/docs/examples/index.html +2 -2
  63. package/dist/serve/site-ui/docs/firestore-compat/index.html +1 -1
  64. package/dist/serve/site-ui/docs/functions-rtdb-compat/index.html +1 -1
  65. package/dist/serve/site-ui/docs/get-started/how-the-swap-works/index.html +1 -1
  66. package/dist/serve/site-ui/docs/get-started/nextjs/index.html +1 -1
  67. package/dist/serve/site-ui/docs/get-started/start-building/index.html +29 -3
  68. package/dist/serve/site-ui/docs/get-started/start-building.md +9 -4
  69. package/dist/serve/site-ui/docs/get-started/vite/index.html +1 -1
  70. package/dist/serve/site-ui/docs/index.json +23 -18
  71. package/dist/serve/site-ui/docs/messaging-compat/index.html +1 -1
  72. package/dist/serve/site-ui/docs/observe/resolve-runtime-status/index.html +1 -1
  73. package/dist/serve/site-ui/docs/observe/see-whats-happening/index.html +1 -1
  74. package/dist/serve/site-ui/docs/observe/shape-your-data/index.html +1 -1
  75. package/dist/serve/site-ui/docs/overview/index.html +1 -1
  76. package/dist/serve/site-ui/docs/pyric-admin-app-reference-api/index.html +1 -1
  77. package/dist/serve/site-ui/docs/pyric-admin-auth-reference-api/index.html +1 -1
  78. package/dist/serve/site-ui/docs/pyric-admin-database-reference-api/index.html +1 -1
  79. package/dist/serve/site-ui/docs/pyric-admin-firestore-reference-api/index.html +1 -1
  80. package/dist/serve/site-ui/docs/pyric-admin-messaging-reference-api/index.html +1 -1
  81. package/dist/serve/site-ui/docs/pyric-admin-storage-reference-api/index.html +1 -1
  82. package/dist/serve/site-ui/docs/pyric-ai-reference-api/index.html +1 -1
  83. package/dist/serve/site-ui/docs/pyric-ai-scripting-reference-api/index.html +1 -1
  84. package/dist/serve/site-ui/docs/pyric-app-reference-api/index.html +1 -1
  85. package/dist/serve/site-ui/docs/pyric-auth-reference-api/index.html +1 -1
  86. package/dist/serve/site-ui/docs/pyric-cli-assurance-browser-reference-api/index.html +1 -1
  87. package/dist/serve/site-ui/docs/pyric-cli-assurance-reference-api/index.html +1 -1
  88. package/dist/serve/site-ui/docs/pyric-cli-bridge-client-reference-api/index.html +1 -1
  89. package/dist/serve/site-ui/docs/pyric-cli-bridge-reference-api/index.html +1 -1
  90. package/dist/serve/site-ui/docs/pyric-cli-conformance-browser-reference-api/index.html +1 -1
  91. package/dist/serve/site-ui/docs/pyric-cli-conformance-docs-reference-api/index.html +1 -1
  92. package/dist/serve/site-ui/docs/pyric-cli-conformance-reference-api/index.html +1 -1
  93. package/dist/serve/site-ui/docs/pyric-cli-credentials-node-reference-api/index.html +1 -1
  94. package/dist/serve/site-ui/docs/pyric-cli-discover-reference-api/index.html +1 -1
  95. package/dist/serve/site-ui/docs/pyric-cli-next-reference-api/index.html +1 -1
  96. package/dist/serve/site-ui/docs/pyric-cli-register-app-bridge-reference-api/index.html +1 -1
  97. package/dist/serve/site-ui/docs/pyric-cli-register-reference-api/index.html +1 -1
  98. package/dist/serve/site-ui/docs/pyric-cli-remote-reference-api/index.html +1 -1
  99. package/dist/serve/site-ui/docs/pyric-cli-serve-worker-reference-api/index.html +1 -1
  100. package/dist/serve/site-ui/docs/pyric-cli-verify-reference-api/index.html +1 -1
  101. package/dist/serve/site-ui/docs/pyric-cli-vite-reference-api/index.html +1 -1
  102. package/dist/serve/site-ui/docs/pyric-database-reference-api/index.html +1 -1
  103. package/dist/serve/site-ui/docs/pyric-firestore-reference-api/index.html +1 -1
  104. package/dist/serve/site-ui/docs/pyric-messaging-reference-api/index.html +1 -1
  105. package/dist/serve/site-ui/docs/pyric-messaging-sw-reference-api/index.html +1 -1
  106. package/dist/serve/site-ui/docs/pyric-rules-reference-api/index.html +1 -1
  107. package/dist/serve/site-ui/docs/pyric-sandbox-database-reference-api/index.html +1 -1
  108. package/dist/serve/site-ui/docs/pyric-sandbox-firestore-reference-api/index.html +1 -1
  109. package/dist/serve/site-ui/docs/pyric-sandbox-reference-api/index.html +1 -1
  110. package/dist/serve/site-ui/docs/pyric-storage-reference-api/index.html +1 -1
  111. package/dist/serve/site-ui/docs/pyric-ui-agents-reference-api/index.html +1 -1
  112. package/dist/serve/site-ui/docs/pyric-ui-auth-hooks-reference-api/index.html +1 -1
  113. package/dist/serve/site-ui/docs/pyric-ui-auth-reference-api/index.html +1 -1
  114. package/dist/serve/site-ui/docs/pyric-ui-events-hooks-reference-api/index.html +1 -1
  115. package/dist/serve/site-ui/docs/pyric-ui-events-reference-api/index.html +1 -1
  116. package/dist/serve/site-ui/docs/pyric-ui-firestore-hooks-reference-api/index.html +1 -1
  117. package/dist/serve/site-ui/docs/pyric-ui-firestore-reference-api/index.html +1 -1
  118. package/dist/serve/site-ui/docs/pyric-ui-primitives-reference-api/index.html +1 -1
  119. package/dist/serve/site-ui/docs/pyric-ui-rtdb-reference-api/index.html +1 -1
  120. package/dist/serve/site-ui/docs/pyric-ui-rules-hooks-reference-api/index.html +1 -1
  121. package/dist/serve/site-ui/docs/pyric-ui-rules-reference-api/index.html +1 -1
  122. package/dist/serve/site-ui/docs/pyric-ui-storage-hooks-reference-api/index.html +1 -1
  123. package/dist/serve/site-ui/docs/pyric-ui-storage-reference-api/index.html +1 -1
  124. package/dist/serve/site-ui/docs/pyric-ui-traffic-hooks-reference-api/index.html +1 -1
  125. package/dist/serve/site-ui/docs/pyric-ui-traffic-reference-api/index.html +1 -1
  126. package/dist/serve/site-ui/docs/rules-compat/index.html +1 -1
  127. package/dist/serve/site-ui/docs/secure/audit-your-rules/index.html +1 -1
  128. package/dist/serve/site-ui/docs/secure/firestore-rules-limits/index.html +1 -1
  129. package/dist/serve/site-ui/docs/secure/read-a-denial/index.html +1 -1
  130. package/dist/serve/site-ui/docs/secure/rtdb-rules-in-typescript/index.html +1 -1
  131. package/dist/serve/site-ui/docs/secure/rules-standard-library/index.html +1 -1
  132. package/dist/serve/site-ui/docs/secure/secure-it-with-rules/index.html +1 -1
  133. package/dist/serve/site-ui/docs/secure/simulate-and-lint/index.html +1 -1
  134. package/dist/serve/site-ui/docs/secure/write-a-rules-test-suite/index.html +1 -1
  135. package/dist/serve/site-ui/docs/ship/ship-to-production/index.html +1 -1
  136. package/dist/serve/site-ui/docs/ship/test-in-node/index.html +1 -1
  137. package/dist/serve/site-ui/docs/storage-compat/index.html +1 -1
  138. package/dist/serve/site-ui/docs/trust/how-we-know-it-matches-firebase/index.html +1 -1
  139. package/dist/serve/site-ui/docs/trust/rules-standard-library/index.html +1 -1
  140. package/dist/serve/site-ui/docs/trust/storage-rules-stdlib-research/index.html +1 -1
  141. package/dist/serve/site-ui/docs/trust/versioning-and-compatibility/index.html +1 -1
  142. package/dist/serve/site-ui/docs/tutorial/index.html +1 -1
  143. package/dist/serve/site-ui/examples/chess/index.html +2 -2
  144. package/dist/serve/site-ui/firestore/index.html +2 -2
  145. package/dist/serve/site-ui/index.html +2 -2
  146. package/dist/serve/site-ui/rtdb/index.html +2 -2
  147. package/dist/serve/site-ui/settings/index.html +2 -2
  148. package/dist/serve/site-ui/storage/index.html +2 -2
  149. package/dist/serve/site-ui/traffic/index.html +2 -2
  150. package/dist/serve/vite-rules-source.d.ts.map +1 -1
  151. package/dist/serve/vite-rules-source.js +28 -7
  152. package/dist/serve/vite-rules-source.js.map +1 -1
  153. package/package.json +4 -4
  154. package/src/bridge/server/mcp-contract.ts +3 -0
  155. package/src/cli/index.ts +3 -0
  156. package/src/cli/mcp-proxy.ts +6 -7
  157. package/src/cli/rules.ts +31 -4
  158. package/src/cli/service-command-records/storage-rules-resolve.ts +4 -0
  159. package/src/cli/service-commands.generated.ts +2 -0
  160. package/src/serve/rules.ts +15 -5
  161. package/src/serve/vite-rules-source.ts +29 -7
  162. package/dist/serve/site-ui/_astro/_example_.jevZ7OdV.css +0 -1
  163. package/dist/serve/site-ui/_astro/_studio_.B6b_G1ev.css +0 -1
  164. package/dist/serve/site-ui/_astro/app.B7pBzz5N.js +0 -11
  165. package/dist/serve/site-ui/_astro/app.boex5SnQ.js +0 -1
  166. package/dist/serve/site-ui/_astro/chess-showcase.DDqE-QGe.js +0 -1
  167. package/dist/serve/site-ui/_astro/chess-source-explorer.C5k9c5yK.js +0 -1
  168. package/dist/serve/site-ui/_astro/chess-v2.CFHmd3UL.js +0 -354
  169. package/dist/serve/site-ui/_astro/index.uwPvjH_1.js +0 -1
  170. package/dist/serve/site-ui/_astro/jsx-runtime.D_zvdyIk.js +0 -9
  171. package/dist/serve/site-ui/_astro/reads.Dh3z0fJy.js +0 -1
  172. package/dist/serve/site-ui/_astro/sandbox-controls.C2IqtoSw.js +0 -1252
  173. package/dist/serve/site-ui/_astro/seed.CCmj00su.js +0 -20
  174. package/dist/serve/site-ui/examples/firestore-first-write/index.html +0 -2
@@ -0,0 +1,1169 @@
1
+ var oa=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function qo(t){if(Object.prototype.hasOwnProperty.call(t,"__esModule"))return t;var e=t.default;if(typeof e=="function"){var r=function n(){return this instanceof n?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};r.prototype=e.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(t).forEach(function(n){var s=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(r,n,s.get?s:{enumerable:!0,get:function(){return t[n]}})}),r}var mn={exports:{}},Xt={};/**
2
+ * @license React
3
+ * react-jsx-runtime.production.js
4
+ *
5
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
6
+ *
7
+ * This source code is licensed under the MIT license found in the
8
+ * LICENSE file in the root directory of this source tree.
9
+ */var js;function Po(){if(js)return Xt;js=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function r(n,s,i){var a=null;if(i!==void 0&&(a=""+i),s.key!==void 0&&(a=""+s.key),"key"in s){i={};for(var o in s)o!=="key"&&(i[o]=s[o])}else i=s;return s=i.ref,{$$typeof:t,type:n,key:a,ref:s!==void 0?s:null,props:i}}return Xt.Fragment=e,Xt.jsx=r,Xt.jsxs=r,Xt}var qs;function $o(){return qs||(qs=1,mn.exports=Po()),mn.exports}var jp=$o();function Fe(t){const e=t||"";return function(){throw new Error("this method "+e+" is abstract! (it has no implementation in class "+this.constructor.name+")")}}function wt(t,e){if(!t)throw new Error(e||"Assertion failed")}function Cn(t,e,r){let n;Object.defineProperty(t,e,{get(){return n||(n=r.call(this)),n}})}function ca(t,e){const r=[];for(;e-- >0;)r.push(t());return r}function ua(t,e){return new Array(e+1).join(t)}function sn(t,e){return ca(()=>t,e)}function Rn(t){const e=[];for(let r=0;r<t.length;r++){const n=t[r];t.lastIndexOf(n)!==r&&e.indexOf(n)<0&&e.push(n)}return e}function la(t){const e=[];return t.forEach(r=>{e.indexOf(r)<0&&e.push(r)}),e}function kt(t){const e=t[0];return e===e.toUpperCase()}function da(t){return!kt(t)}function ha(t,e,r){return t.length<e?ua(" ",e-t.length)+t:t}function Dt(){this.strings=[]}Dt.prototype.append=function(t){this.strings.push(t)};Dt.prototype.contents=function(){return this.strings.join("")};const gn=t=>String.fromCodePoint(parseInt(t,16));function fa(t){if(t.charAt(0)==="\\")switch(t.charAt(1)){case"b":return"\b";case"f":return"\f";case"n":return`
10
+ `;case"r":return"\r";case"t":return" ";case"v":return"\v";case"x":return gn(t.slice(2,4));case"u":return t.charAt(2)==="{"?gn(t.slice(3,-1)):gn(t.slice(2,6));default:return t.charAt(1)}else return t}function fs(t){if(t==null)return String(t);const e=Object.prototype.toString.call(t);try{let r;return t.constructor&&t.constructor.name?r=t.constructor.name:e.indexOf("[object ")===0?r=e.slice(8,-1):r=typeof t,r+": "+JSON.stringify(String(t))}catch{return e}}function pa(t,e="unexpected null value"){if(t==null)throw new Error(e);return t}const Uo=Object.freeze(Object.defineProperty({__proto__:null,StringBuffer:Dt,abstract:Fe,assert:wt,checkNotNull:pa,copyWithoutDuplicates:la,defineLazyProperty:Cn,getDuplicates:Rn,isLexical:da,isSyntactic:kt,padLeft:ha,repeat:sn,repeatFn:ca,repeatStr:ua,unescapeCodePoint:fa,unexpectedObjToString:fs},Symbol.toStringTag,{value:"Module"})),ma=t=>new RegExp(String.raw`\p{${t}}`,"u"),Nn=Object.fromEntries(["Cc","Cf","Cn","Co","Cs","Ll","Lm","Lo","Lt","Lu","Mc","Me","Mn","Nd","Nl","No","Pc","Pd","Pe","Pf","Pi","Po","Ps","Sc","Sk","Sm","So","Zl","Zp","Zs"].map(t=>[t,ma(t)]));Nn.Ltmo=/\p{Lt}|\p{Lm}|\p{Lo}/u;const Ps=Object.fromEntries(["XID_Start","XID_Continue","White_Space"].map(t=>[t,ma(t)]));class V{constructor(){if(this.constructor===V)throw new Error("PExpr cannot be instantiated -- it's abstract")}withSource(e){return e&&(this.source=e.trimmed()),this}}const Ce=Object.create(V.prototype),Re=Object.create(V.prototype);class ke extends V{constructor(e){super(),this.obj=e}}class Ne extends V{constructor(e,r){super(),this.from=e,this.to=r,this.matchCodePoint=e.length>1||r.length>1}}class Le extends V{constructor(e){super(),this.index=e}}class ge extends V{constructor(e){super(),this.terms=e}}class an extends ge{constructor(e,r,n){const s=e.rules[r].body;super([n,s]),this.superGrammar=e,this.name=r,this.body=n}}class on extends ge{constructor(e,r,n,s){const i=e.rules[r].body;super([...n,i,...s]),this.superGrammar=e,this.ruleName=r,this.expansionPos=n.length}}class Se extends V{constructor(e){super(),this.factors=e}}class je extends V{constructor(e){super(),this.expr=e}}class Ft extends je{}class Yt extends je{}class ht extends je{}Ft.prototype.operator="*";Yt.prototype.operator="+";ht.prototype.operator="?";Ft.prototype.minNumMatches=0;Yt.prototype.minNumMatches=1;ht.prototype.minNumMatches=0;Ft.prototype.maxNumMatches=Number.POSITIVE_INFINITY;Yt.prototype.maxNumMatches=Number.POSITIVE_INFINITY;ht.prototype.maxNumMatches=1;class Ie extends V{constructor(e){super(),this.expr=e}}class qe extends V{constructor(e){super(),this.expr=e}}class $e extends V{constructor(e){super(),this.expr=e}}class X extends V{constructor(e,r=[]){super(),this.ruleName=e,this.args=r}isSyntactic(){return kt(this.ruleName)}toMemoKey(){return this._memoKey||Object.defineProperty(this,"_memoKey",{value:this.toString()}),this._memoKey}}class xe extends V{constructor(e){if(super(),this.categoryOrProp=e,e in Nn)this.pattern=Nn[e];else if(e in Ps)this.pattern=Ps[e];else throw new Error(`Invalid Unicode category or property name: ${JSON.stringify(e)}`)}}function ce(t,e){let r;return e?(r=new Error(e.getLineAndColumnMessage()+t),r.shortMessage=t,r.interval=e):r=new Error(t),r}function Ln(){return ce("Interval sources don't match")}function Bo(t){const e=new Error;return Object.defineProperty(e,"message",{enumerable:!0,get(){return t.message}}),Object.defineProperty(e,"shortMessage",{enumerable:!0,get(){return"Expected "+t.getExpectedText()}}),e.interval=t.getInterval(),e}function zo(t,e,r){const n=e?`Grammar ${t} is not declared in namespace '${e}'`:"Undeclared grammar "+t;return ce(n,r)}function Vo(t,e){return ce("Grammar "+t.name+" is already declared in this namespace")}function Ho(t){return ce(`Grammar '${t.name}' does not support incremental parsing`)}function ga(t,e,r){return ce("Rule "+t+" is not declared in grammar "+e,r)}function Wo(t,e,r){return ce("Cannot override rule "+t+" because it is not declared in "+e,r)}function Go(t,e,r){return ce("Cannot extend rule "+t+" because it is not declared in "+e,r)}function $s(t,e,r,n){let s="Duplicate declaration for rule '"+t+"' in grammar '"+e+"'";return e!==r&&(s+=" (originally declared in '"+r+"')"),ce(s,n)}function ya(t,e,r,n){return ce("Wrong number of parameters for rule "+t+" (expected "+e+", got "+r+")",n)}function Ko(t,e,r,n){return ce("Wrong number of arguments for rule "+t+" (expected "+e+", got "+r+")",n)}function Us(t,e,r){return ce("Duplicate parameter names in rule "+t+": "+e.join(", "),r)}function Zo(t,e){return ce("Invalid parameter to rule "+t+": "+e+" has arity "+e.getArity()+", but parameter expressions must have arity 1",e.source)}const Jo="NOTE: A _syntactic rule_ is a rule whose name begins with a capital letter. See https://ohmjs.org/d/svl for more details.";function Yo(t,e){return ce("Cannot apply syntactic rule "+t+" from here (inside a lexical context)",e.source)}function Qo(t){const{ruleName:e}=t;return ce(`applySyntactic is for syntactic rules, but '${e}' is a lexical rule. `+Jo,t.source)}function Xo(t){return ce("applySyntactic is not required here (in a syntactic context)",t.source)}function Bs(t,e){return ce("Incorrect argument type: expected "+t,e.source)}function ec(t){return ce("'...' can appear at most once in a rule body",t.source)}function tc(t){const e=t._node;wt(e&&e.isNonterminal()&&e.ctorName==="escapeChar_unicodeCodePoint");const r=t.children.slice(1,-1).map(s=>s.source),n=r[0].coverageWith(...r.slice(1));return ce(`U+${n.contents} is not a valid Unicode code point`,n)}function va(t,e){const r=e.length>0?e[e.length-1].args:[];let s="Nullable expression "+t.expr.substituteParams(r)+" is not allowed inside '"+t.operator+"' (possible infinite loop)";if(e.length>0){const i=e.map(a=>new X(a.ruleName,a.args)).join(`
11
+ `);s+=`
12
+ Application stack (most recent application last):
13
+ `+i}return ce(s,t.expr.source)}function ba(t,e,r,n){return ce("Rule "+t+" involves an alternation which has inconsistent arity (expected "+e+", got "+r+")",n.source)}function rc(t){const e=t.map(r=>r.message);return ce(["Errors:"].concat(e).join(`
14
+ - `),t[0].interval)}function nc(t,e,r,n){let s=n.slice(0,-1).map(c=>{const u=" "+c[0].name+" > "+c[1];return c.length===3?u+" for '"+c[2]+"'":u}).join(`
15
+ `);s+=`
16
+ `+e+" > "+t;let i="";t==="_iter"&&(i=[`
17
+ NOTE: as of Ohm v16, there is no default action for iteration nodes — see `," https://ohmjs.org/d/dsa for details."].join(`
18
+ `));const a=[`Missing semantic action for '${t}' in ${r} '${e}'.${i}`,"Action stack (most recent call last):",s].join(`
19
+ `),o=ce(a);return o.name="missingSemanticAction",o}function sc(t){if(t.length===1)throw t[0];if(t.length>1)throw rc(t)}function ic(t){let e=0;return t.map(n=>{const s=n.toString();return e=Math.max(e,s.length),s}).map(n=>ha(n,e))}function zs(t,e,r){const n=t.length,s=t.slice(0,r),i=t.slice(r+e.length);return(s+e+i).substr(0,n)}function ac(...t){const e=this,{offset:r}=e,{repeatStr:n}=Uo,s=new Dt;s.append("Line "+e.lineNum+", col "+e.colNum+`:
20
+ `);const i=ic([e.prevLine==null?0:e.lineNum-1,e.lineNum,e.nextLine==null?0:e.lineNum+1]),a=(f,l,p)=>{s.append(p+i[f]+" | "+l+`
21
+ `)};e.prevLine!=null&&a(0,e.prevLine," "),a(1,e.line,"> ");const o=e.line.length;let c=n(" ",o+1);for(let f=0;f<t.length;++f){let l=t[f][0],p=t[f][1];wt(l>=0&&l<=p,"range start must be >= 0 and <= end");const y=r-e.colNum+1;l=Math.max(0,l-y),p=Math.min(p-y,o),c=zs(c,n("~",p-l),l)}const u=2+i[1].length+3;return s.append(n(" ",u)),c=zs(c,"^",e.colNum-1),s.append(c.replace(/ +$/,"")+`
22
+ `),e.nextLine!=null&&a(2,e.nextLine," "),s.contents()}let Mn=[];function wa(t){Mn.push(t)}function oc(t){Mn.forEach(e=>{e(t)}),Mn=null}function ps(t,e){let r=1,n=1,s=0,i=0,a=null,o=null,c=-1;for(;s<e;){const l=t.charAt(s++);l===`
23
+ `?(r++,n=1,c=i,i=s):l!=="\r"&&n++}let u=t.indexOf(`
24
+ `,i);if(u===-1)u=t.length;else{const l=t.indexOf(`
25
+ `,u+1);a=l===-1?t.slice(u):t.slice(u,l),a=a.replace(/^\r?\n/,"").replace(/\r$/,"")}c>=0&&(o=t.slice(c,i).replace(/\r?\n$/,""));const f=t.slice(i,u).replace(/\r$/,"");return{offset:e,lineNum:r,colNum:n,line:f,prevLine:o,nextLine:a,toString:ac}}function ms(t,e,...r){return ps(t,e).toString(...r)}const Vs=(()=>{let t=0;return e=>""+e+t++})();class Oe{constructor(e,r,n){Object.defineProperty(this,"_sourceString",{value:e,configurable:!1,enumerable:!1,writable:!1}),this.startIdx=r,this.endIdx=n}get sourceString(){return this._sourceString}get contents(){return this._contents===void 0&&(this._contents=this.sourceString.slice(this.startIdx,this.endIdx)),this._contents}get length(){return this.endIdx-this.startIdx}coverageWith(...e){return Oe.coverage(...e,this)}collapsedLeft(){return new Oe(this.sourceString,this.startIdx,this.startIdx)}collapsedRight(){return new Oe(this.sourceString,this.endIdx,this.endIdx)}getLineAndColumn(){return ps(this.sourceString,this.startIdx)}getLineAndColumnMessage(){const e=[this.startIdx,this.endIdx];return ms(this.sourceString,this.startIdx,e)}minus(e){if(this.sourceString!==e.sourceString)throw Ln();return this.startIdx===e.startIdx&&this.endIdx===e.endIdx?[]:this.startIdx<e.startIdx&&e.endIdx<this.endIdx?[new Oe(this.sourceString,this.startIdx,e.startIdx),new Oe(this.sourceString,e.endIdx,this.endIdx)]:this.startIdx<e.endIdx&&e.endIdx<this.endIdx?[new Oe(this.sourceString,e.endIdx,this.endIdx)]:this.startIdx<e.startIdx&&e.startIdx<this.endIdx?[new Oe(this.sourceString,this.startIdx,e.startIdx)]:[this]}relativeTo(e){if(this.sourceString!==e.sourceString)throw Ln();return wt(this.startIdx>=e.startIdx&&this.endIdx<=e.endIdx,"other interval does not cover this one"),new Oe(this.sourceString,this.startIdx-e.startIdx,this.endIdx-e.startIdx)}trimmed(){const{contents:e}=this,r=this.startIdx+e.match(/^\s*/)[0].length,n=this.endIdx-e.match(/\s*$/)[0].length;return new Oe(this.sourceString,r,n)}subInterval(e,r){const n=this.startIdx+e;return new Oe(this.sourceString,n,n+r)}}Oe.coverage=function(t,...e){let{startIdx:r,endIdx:n}=t;for(const s of e){if(s.sourceString!==t.sourceString)throw Ln();r=Math.min(r,s.startIdx),n=Math.max(n,s.endIdx)}return new Oe(t.sourceString,r,n)};const cc=65535,uc=1114111;class cn{constructor(e){this.source=e,this.pos=0,this.examinedLength=0}atEnd(){const e=this.pos>=this.source.length;return this.examinedLength=Math.max(this.examinedLength,this.pos+1),e}next(){const e=this.source[this.pos++];return this.examinedLength=Math.max(this.examinedLength,this.pos),e}nextCharCode(){const e=this.next();return e&&e.charCodeAt(0)}nextCodePoint(){const e=this.source.slice(this.pos++).codePointAt(0);return e>cc&&(this.pos+=1),this.examinedLength=Math.max(this.examinedLength,this.pos),e}matchString(e,r){let n;if(r){for(n=0;n<e.length;n++){const s=this.next(),i=e[n];if(s==null||s.toUpperCase()!==i.toUpperCase())return!1}return!0}for(n=0;n<e.length;n++)if(this.next()!==e[n])return!1;return!0}sourceSlice(e,r){return this.source.slice(e,r)}interval(e,r){return new Oe(this.source,e,r||this.pos)}}class Sa{constructor(e,r,n,s,i,a,o){this.matcher=e,this.input=r,this.startExpr=n,this._cst=s,this._cstOffset=i,this._rightmostFailurePosition=a,this._rightmostFailures=o,this.failed()&&(Cn(this,"message",function(){const c="Expected "+this.getExpectedText();return ms(this.input,this.getRightmostFailurePosition())+c}),Cn(this,"shortMessage",function(){const c="expected "+this.getExpectedText(),u=ps(this.input,this.getRightmostFailurePosition());return"Line "+u.lineNum+", col "+u.colNum+": "+c}))}succeeded(){return!!this._cst}failed(){return!this.succeeded()}getRightmostFailurePosition(){return this._rightmostFailurePosition}getRightmostFailures(){if(!this._rightmostFailures){this.matcher.setInput(this.input);const e=this.matcher._match(this.startExpr,{tracing:!1,positionToRecordFailures:this.getRightmostFailurePosition()});this._rightmostFailures=e.getRightmostFailures()}return this._rightmostFailures}toString(){return this.succeeded()?"[match succeeded]":"[match failed at position "+this.getRightmostFailurePosition()+"]"}getExpectedText(){if(this.succeeded())throw new Error("cannot get expected text of a successful MatchResult");const e=new Dt;let r=this.getRightmostFailures();r=r.filter(n=>!n.isFluffy());for(let n=0;n<r.length;n++)n>0&&(n===r.length-1?e.append(r.length>2?", or ":" or "):e.append(", ")),e.append(r[n].toString());return e.contents()}getInterval(){const e=this.getRightmostFailurePosition();return new Oe(this.input,e,e)}}class lc{constructor(){this.applicationMemoKeyStack=[],this.memo={},this.maxExaminedLength=0,this.maxRightmostFailureOffset=-1,this.currentLeftRecursion=void 0}isActive(e){return this.applicationMemoKeyStack.indexOf(e.toMemoKey())>=0}enter(e){this.applicationMemoKeyStack.push(e.toMemoKey())}exit(){this.applicationMemoKeyStack.pop()}startLeftRecursion(e,r){r.isLeftRecursion=!0,r.headApplication=e,r.nextLeftRecursion=this.currentLeftRecursion,this.currentLeftRecursion=r;const{applicationMemoKeyStack:n}=this,s=n.indexOf(e.toMemoKey())+1,i=n.slice(s);r.isInvolved=function(a){return i.indexOf(a)>=0},r.updateInvolvedApplicationMemoKeys=function(){for(let a=s;a<n.length;a++){const o=n[a];this.isInvolved(o)||i.push(o)}}}endLeftRecursion(){this.currentLeftRecursion=this.currentLeftRecursion.nextLeftRecursion}shouldUseMemoizedResult(e){if(!e.isLeftRecursion)return!0;const{applicationMemoKeyStack:r}=this;for(let n=0;n<r.length;n++){const s=r[n];if(e.isInvolved(s))return!1}return!0}memoize(e,r){return this.memo[e]=r,this.maxExaminedLength=Math.max(this.maxExaminedLength,r.examinedLength),this.maxRightmostFailureOffset=Math.max(this.maxRightmostFailureOffset,r.rightmostFailureOffset),r}clearObsoleteEntries(e,r){if(e+this.maxExaminedLength<=r)return;const{memo:n}=this;this.maxExaminedLength=0,this.maxRightmostFailureOffset=-1,Object.keys(n).forEach(s=>{const i=n[s];e+i.examinedLength>r?delete n[s]:(this.maxExaminedLength=Math.max(this.maxExaminedLength,i.examinedLength),this.maxRightmostFailureOffset=Math.max(this.maxRightmostFailureOffset,i.rightmostFailureOffset))})}}const dc="✗",hc="✓",fc="⋅",pc="⇒",mc="␉",gc="␊",yc="␍",Dn={succeeded:1,isRootNode:2,isImplicitSpaces:4,isMemoized:8,isHeadOfLeftRecursion:16,terminatesLR:32};function vc(t){return sn(" ",t).join("")}function bc(t,e,r){const n=_a(t.slice(e,e+r));return n.length<r?n+sn(" ",r-n.length).join(""):n}function _a(t){return typeof t=="string"?t.replace(/ /g,fc).replace(/\t/g,mc).replace(/\n/g,gc).replace(/\r/g,yc):String(t)}class pt{constructor(e,r,n,s,i,a,o){this.input=e,this.pos=this.pos1=r,this.pos2=n,this.source=new Oe(e,r,n),this.expr=s,this.bindings=a,this.children=o||[],this.terminatingLREntry=null,this._flags=i?Dn.succeeded:0}get displayString(){return this.expr.toDisplayString()}clone(){return this.cloneWithExpr(this.expr)}cloneWithExpr(e){const r=new pt(this.input,this.pos,this.pos2,e,this.succeeded,this.bindings,this.children);return r.isHeadOfLeftRecursion=this.isHeadOfLeftRecursion,r.isImplicitSpaces=this.isImplicitSpaces,r.isMemoized=this.isMemoized,r.isRootNode=this.isRootNode,r.terminatesLR=this.terminatesLR,r.terminatingLREntry=this.terminatingLREntry,r}recordLRTermination(e,r){this.terminatingLREntry=new pt(this.input,this.pos,this.pos2,this.expr,!1,[r],[e]),this.terminatingLREntry.terminatesLR=!0}walk(e,r){let n=e;typeof n=="function"&&(n={enter:n});function s(i,a,o){let c=!0;n.enter&&n.enter.call(r,i,a,o)===pt.prototype.SKIP&&(c=!1),c&&(i.children.forEach(u=>{s(u,i,o+1)}),n.exit&&n.exit.call(r,i,a,o))}this.isRootNode?this.children.forEach(i=>{s(i,null,0)}):s(this,null,0)}toString(){const e=new Dt;return this.walk((r,n,s)=>{if(!r)return this.SKIP;if(r.expr.constructor.name!=="Alt"){if(e.append(bc(r.input,r.pos,10)+vc(s*2+1)),e.append((r.succeeded?hc:dc)+" "+r.displayString),r.isHeadOfLeftRecursion&&e.append(" (LR)"),r.succeeded){const a=_a(r.source.contents);e.append(" "+pc+" "),e.append(typeof a=="string"?'"'+a+'"':a)}e.append(`
26
+ `)}}),e.contents()}}pt.prototype.SKIP={};Object.keys(Dn).forEach(t=>{const e=Dn[t];Object.defineProperty(pt.prototype,t,{get(){return(this._flags&e)!==0},set(r){r?this._flags|=e:this._flags&=~e}})});V.prototype.allowsSkippingPrecedingSpace=Fe("allowsSkippingPrecedingSpace");Ce.allowsSkippingPrecedingSpace=Re.allowsSkippingPrecedingSpace=X.prototype.allowsSkippingPrecedingSpace=ke.prototype.allowsSkippingPrecedingSpace=Ne.prototype.allowsSkippingPrecedingSpace=xe.prototype.allowsSkippingPrecedingSpace=function(){return!0};ge.prototype.allowsSkippingPrecedingSpace=je.prototype.allowsSkippingPrecedingSpace=$e.prototype.allowsSkippingPrecedingSpace=qe.prototype.allowsSkippingPrecedingSpace=Ie.prototype.allowsSkippingPrecedingSpace=Le.prototype.allowsSkippingPrecedingSpace=Se.prototype.allowsSkippingPrecedingSpace=function(){return!1};let nr;wa(t=>{nr=t});let Er;V.prototype.assertAllApplicationsAreValid=function(t,e){Er=0,this._assertAllApplicationsAreValid(t,e)};V.prototype._assertAllApplicationsAreValid=Fe("_assertAllApplicationsAreValid");Ce._assertAllApplicationsAreValid=Re._assertAllApplicationsAreValid=ke.prototype._assertAllApplicationsAreValid=Ne.prototype._assertAllApplicationsAreValid=Le.prototype._assertAllApplicationsAreValid=xe.prototype._assertAllApplicationsAreValid=function(t,e){};$e.prototype._assertAllApplicationsAreValid=function(t,e){Er++,this.expr._assertAllApplicationsAreValid(t,e),Er--};ge.prototype._assertAllApplicationsAreValid=function(t,e){for(let r=0;r<this.terms.length;r++)this.terms[r]._assertAllApplicationsAreValid(t,e)};Se.prototype._assertAllApplicationsAreValid=function(t,e){for(let r=0;r<this.factors.length;r++)this.factors[r]._assertAllApplicationsAreValid(t,e)};je.prototype._assertAllApplicationsAreValid=Ie.prototype._assertAllApplicationsAreValid=qe.prototype._assertAllApplicationsAreValid=function(t,e){this.expr._assertAllApplicationsAreValid(t,e)};X.prototype._assertAllApplicationsAreValid=function(t,e,r=!1){const n=e.rules[this.ruleName],s=kt(t)&&Er===0;if(!n)throw ga(this.ruleName,e.name,this.source);if(!r&&kt(this.ruleName)&&!s)throw Yo(this.ruleName,this);const i=this.args.length,a=n.formals.length;if(i!==a)throw Ko(this.ruleName,a,i,this.source);const o=nr&&n===nr.rules.applySyntactic;if(nr&&n===nr.rules.caseInsensitive&&!(this.args[0]instanceof ke))throw Bs('a Terminal (e.g. "abc")',this.args[0]);if(o){const u=this.args[0];if(!(u instanceof X))throw Bs("a syntactic rule application",u);if(!kt(u.ruleName))throw Qo(u);if(s)throw Xo(this)}this.args.forEach(u=>{if(u._assertAllApplicationsAreValid(t,e,o),u.getArity()!==1)throw Zo(this.ruleName,u)})};V.prototype.assertChoicesHaveUniformArity=Fe("assertChoicesHaveUniformArity");Ce.assertChoicesHaveUniformArity=Re.assertChoicesHaveUniformArity=ke.prototype.assertChoicesHaveUniformArity=Ne.prototype.assertChoicesHaveUniformArity=Le.prototype.assertChoicesHaveUniformArity=$e.prototype.assertChoicesHaveUniformArity=xe.prototype.assertChoicesHaveUniformArity=function(t){};ge.prototype.assertChoicesHaveUniformArity=function(t){if(this.terms.length===0)return;const e=this.terms[0].getArity();for(let r=0;r<this.terms.length;r++){const n=this.terms[r];n.assertChoicesHaveUniformArity();const s=n.getArity();if(e!==s)throw ba(t,e,s,n)}};an.prototype.assertChoicesHaveUniformArity=function(t){const e=this.terms[0].getArity(),r=this.terms[1].getArity();if(e!==r)throw ba(t,r,e,this.terms[0])};Se.prototype.assertChoicesHaveUniformArity=function(t){for(let e=0;e<this.factors.length;e++)this.factors[e].assertChoicesHaveUniformArity(t)};je.prototype.assertChoicesHaveUniformArity=function(t){this.expr.assertChoicesHaveUniformArity(t)};Ie.prototype.assertChoicesHaveUniformArity=function(t){};qe.prototype.assertChoicesHaveUniformArity=function(t){this.expr.assertChoicesHaveUniformArity(t)};X.prototype.assertChoicesHaveUniformArity=function(t){};V.prototype.assertIteratedExprsAreNotNullable=Fe("assertIteratedExprsAreNotNullable");Ce.assertIteratedExprsAreNotNullable=Re.assertIteratedExprsAreNotNullable=ke.prototype.assertIteratedExprsAreNotNullable=Ne.prototype.assertIteratedExprsAreNotNullable=Le.prototype.assertIteratedExprsAreNotNullable=xe.prototype.assertIteratedExprsAreNotNullable=function(t){};ge.prototype.assertIteratedExprsAreNotNullable=function(t){for(let e=0;e<this.terms.length;e++)this.terms[e].assertIteratedExprsAreNotNullable(t)};Se.prototype.assertIteratedExprsAreNotNullable=function(t){for(let e=0;e<this.factors.length;e++)this.factors[e].assertIteratedExprsAreNotNullable(t)};je.prototype.assertIteratedExprsAreNotNullable=function(t){if(this.expr.assertIteratedExprsAreNotNullable(t),this.expr.isNullable(t))throw va(this,[])};ht.prototype.assertIteratedExprsAreNotNullable=Ie.prototype.assertIteratedExprsAreNotNullable=qe.prototype.assertIteratedExprsAreNotNullable=$e.prototype.assertIteratedExprsAreNotNullable=function(t){this.expr.assertIteratedExprsAreNotNullable(t)};X.prototype.assertIteratedExprsAreNotNullable=function(t){this.args.forEach(e=>{e.assertIteratedExprsAreNotNullable(t)})};class gs{constructor(e){this.matchLength=e}get ctorName(){throw new Error("subclass responsibility")}numChildren(){return this.children?this.children.length:0}childAt(e){if(this.children)return this.children[e]}indexOfChild(e){return this.children.indexOf(e)}hasChildren(){return this.numChildren()>0}hasNoChildren(){return!this.hasChildren()}onlyChild(){if(this.numChildren()!==1)throw new Error("cannot get only child of a node of type "+this.ctorName+" (it has "+this.numChildren()+" children)");return this.firstChild()}firstChild(){if(this.hasNoChildren())throw new Error("cannot get first child of a "+this.ctorName+" node, which has no children");return this.childAt(0)}lastChild(){if(this.hasNoChildren())throw new Error("cannot get last child of a "+this.ctorName+" node, which has no children");return this.childAt(this.numChildren()-1)}childBefore(e){const r=this.indexOfChild(e);if(r<0)throw new Error("Node.childBefore() called w/ an argument that is not a child");if(r===0)throw new Error("cannot get child before first child");return this.childAt(r-1)}childAfter(e){const r=this.indexOfChild(e);if(r<0)throw new Error("Node.childAfter() called w/ an argument that is not a child");if(r===this.numChildren()-1)throw new Error("cannot get child after last child");return this.childAt(r+1)}isTerminal(){return!1}isNonterminal(){return!1}isIteration(){return!1}isOptional(){return!1}}class jt extends gs{get ctorName(){return"_terminal"}isTerminal(){return!0}get primitiveValue(){throw new Error("The `primitiveValue` property was removed in Ohm v17.")}}class wc extends gs{constructor(e,r,n,s){super(s),this.ruleName=e,this.children=r,this.childOffsets=n}get ctorName(){return this.ruleName}isNonterminal(){return!0}isLexical(){return da(this.ctorName)}isSyntactic(){return kt(this.ctorName)}}class Aa extends gs{constructor(e,r,n,s){super(n),this.children=e,this.childOffsets=r,this.optional=s}get ctorName(){return"_iter"}isIteration(){return!0}isOptional(){return this.optional}}V.prototype.eval=Fe("eval");Ce.eval=function(t){const{inputStream:e}=t,r=e.pos,n=e.nextCodePoint();return n!==void 0?(t.pushBinding(new jt(String.fromCodePoint(n).length),r),!0):(t.processFailure(r,this),!1)};Re.eval=function(t){const{inputStream:e}=t,r=e.pos;return e.atEnd()?(t.pushBinding(new jt(0),r),!0):(t.processFailure(r,this),!1)};ke.prototype.eval=function(t){const{inputStream:e}=t,r=e.pos;return e.matchString(this.obj)?(t.pushBinding(new jt(this.obj.length),r),!0):(t.processFailure(r,this),!1)};Ne.prototype.eval=function(t){const{inputStream:e}=t,r=e.pos,n=this.matchCodePoint?e.nextCodePoint():e.nextCharCode();return n!==void 0&&this.from.codePointAt(0)<=n&&n<=this.to.codePointAt(0)?(t.pushBinding(new jt(String.fromCodePoint(n).length),r),!0):(t.processFailure(r,this),!1)};Le.prototype.eval=function(t){return t.eval(t.currentApplication().args[this.index])};$e.prototype.eval=function(t){t.enterLexifiedContext();const e=t.eval(this.expr);return t.exitLexifiedContext(),e};ge.prototype.eval=function(t){for(let e=0;e<this.terms.length;e++)if(t.eval(this.terms[e]))return!0;return!1};Se.prototype.eval=function(t){for(let e=0;e<this.factors.length;e++){const r=this.factors[e];if(!t.eval(r))return!1}return!0};je.prototype.eval=function(t){const{inputStream:e}=t,r=e.pos,n=this.getArity(),s=[],i=[];for(;s.length<n;)s.push([]),i.push([]);let a=0,o=r,c;for(;a<this.maxNumMatches&&t.eval(this.expr);){if(e.pos===o)throw va(this,t._applicationStack);o=e.pos,a++;const p=t._bindings.splice(t._bindings.length-n,n),y=t._bindingOffsets.splice(t._bindingOffsets.length-n,n);for(c=0;c<p.length;c++)s[c].push(p[c]),i[c].push(y[c])}if(a<this.minNumMatches)return!1;let u=t.posToOffset(r),f=0;if(a>0){const p=s[n-1],y=i[n-1],v=y[y.length-1]+p[p.length-1].matchLength;u=i[0][0],f=v-u}const l=this instanceof ht;for(c=0;c<s.length;c++)t._bindings.push(new Aa(s[c],i[c],f,l)),t._bindingOffsets.push(u);return!0};Ie.prototype.eval=function(t){const{inputStream:e}=t,r=e.pos;t.pushFailuresInfo();const n=t.eval(this.expr);return t.popFailuresInfo(),n?(t.processFailure(r,this),!1):(e.pos=r,!0)};qe.prototype.eval=function(t){const{inputStream:e}=t,r=e.pos;return t.eval(this.expr)?(e.pos=r,!0):!1};X.prototype.eval=function(t){const e=t.currentApplication(),r=e?e.args:[],n=this.substituteParams(r),s=t.getCurrentPosInfo();if(s.isActive(n))return n.handleCycle(t);const i=n.toMemoKey(),a=s.memo[i];if(a&&s.shouldUseMemoizedResult(a)){if(t.hasNecessaryInfo(a))return t.useMemoizedResult(t.inputStream.pos,a);delete s.memo[i]}return n.reallyEval(t)};X.prototype.handleCycle=function(t){const e=t.getCurrentPosInfo(),{currentLeftRecursion:r}=e,n=this.toMemoKey();let s=e.memo[n];return r&&r.headApplication.toMemoKey()===n?s.updateInvolvedApplicationMemoKeys():s||(s=e.memoize(n,{matchLength:0,examinedLength:0,value:!1,rightmostFailureOffset:-1}),e.startLeftRecursion(this,s)),t.useMemoizedResult(t.inputStream.pos,s)};X.prototype.reallyEval=function(t){const{inputStream:e}=t,r=e.pos,n=t.getCurrentPosInfo(),s=t.grammar.rules[this.ruleName],{body:i}=s,{description:a}=s;t.enterApplication(n,this),a&&t.pushFailuresInfo();const o=e.examinedLength;e.examinedLength=0;let c=this.evalOnce(i,t);const u=n.currentLeftRecursion,f=this.toMemoKey(),l=u&&u.headApplication.toMemoKey()===f;let p;t.doNotMemoize?t.doNotMemoize=!1:l?(c=this.growSeedResult(i,t,r,u,c),n.endLeftRecursion(),p=u,p.examinedLength=e.examinedLength-r,p.rightmostFailureOffset=t._getRightmostFailureOffset(),n.memoize(f,p)):(!u||!u.isInvolved(f))&&(p=n.memoize(f,{matchLength:e.pos-r,examinedLength:e.examinedLength-r,value:c,failuresAtRightmostPosition:t.cloneRecordedFailures(),rightmostFailureOffset:t._getRightmostFailureOffset()}));const y=!!c;if(a&&(t.popFailuresInfo(),y||t.processFailure(r,this),p&&(p.failuresAtRightmostPosition=t.cloneRecordedFailures(),p.rightmostFailureOffset=t._getRightmostFailureOffset())),t.isTracing()&&p){const v=t.getTraceEntry(r,this,y,y?[c]:[]);l&&(wt(v.terminatingLREntry!=null||!y),v.isHeadOfLeftRecursion=!0),p.traceEntry=v}return e.examinedLength=Math.max(e.examinedLength,o),t.exitApplication(n,c),y};X.prototype.evalOnce=function(t,e){const{inputStream:r}=e,n=r.pos;if(e.eval(t)){const s=t.getArity(),i=e._bindings.splice(e._bindings.length-s,s),a=e._bindingOffsets.splice(e._bindingOffsets.length-s,s),o=r.pos-n;return new wc(this.ruleName,i,a,o)}else return!1};X.prototype.growSeedResult=function(t,e,r,n,s){if(!s)return!1;const{inputStream:i}=e;for(;;){if(n.matchLength=i.pos-r,n.value=s,n.failuresAtRightmostPosition=e.cloneRecordedFailures(),e.isTracing()){const a=e.trace[e.trace.length-1];n.traceEntry=new pt(e.input,r,i.pos,this,!0,[s],[a.clone()])}if(i.pos=r,s=this.evalOnce(t,e),i.pos-r<=n.matchLength)break;e.isTracing()&&e.trace.splice(-2,1)}return e.isTracing()&&n.traceEntry.recordLRTermination(e.trace.pop(),s),i.pos=r+n.matchLength,n.value};xe.prototype.eval=function(t){const{inputStream:e}=t,r=e.pos,n=e.nextCodePoint();if(n!==void 0&&n<=uc){const s=String.fromCodePoint(n);if(this.pattern.test(s))return t.pushBinding(new jt(s.length),r),!0}return t.processFailure(r,this),!1};V.prototype.getArity=Fe("getArity");Ce.getArity=Re.getArity=ke.prototype.getArity=Ne.prototype.getArity=Le.prototype.getArity=X.prototype.getArity=xe.prototype.getArity=function(){return 1};ge.prototype.getArity=function(){return this.terms.length===0?0:this.terms[0].getArity()};Se.prototype.getArity=function(){let t=0;for(let e=0;e<this.factors.length;e++)t+=this.factors[e].getArity();return t};je.prototype.getArity=function(){return this.expr.getArity()};Ie.prototype.getArity=function(){return 0};qe.prototype.getArity=$e.prototype.getArity=function(){return this.expr.getArity()};function Ke(t,e){const r={};if(t.source&&e){const n=t.source.relativeTo(e);r.sourceInterval=[n.startIdx,n.endIdx]}return r}V.prototype.outputRecipe=Fe("outputRecipe");Ce.outputRecipe=function(t,e){return["any",Ke(this,e)]};Re.outputRecipe=function(t,e){return["end",Ke(this,e)]};ke.prototype.outputRecipe=function(t,e){return["terminal",Ke(this,e),this.obj]};Ne.prototype.outputRecipe=function(t,e){return["range",Ke(this,e),this.from,this.to]};Le.prototype.outputRecipe=function(t,e){return["param",Ke(this,e),this.index]};ge.prototype.outputRecipe=function(t,e){return["alt",Ke(this,e)].concat(this.terms.map(r=>r.outputRecipe(t,e)))};an.prototype.outputRecipe=function(t,e){return this.terms[0].outputRecipe(t,e)};on.prototype.outputRecipe=function(t,e){const r=this.terms.slice(0,this.expansionPos),n=this.terms.slice(this.expansionPos+1);return["splice",Ke(this,e),r.map(s=>s.outputRecipe(t,e)),n.map(s=>s.outputRecipe(t,e))]};Se.prototype.outputRecipe=function(t,e){return["seq",Ke(this,e)].concat(this.factors.map(r=>r.outputRecipe(t,e)))};Ft.prototype.outputRecipe=Yt.prototype.outputRecipe=ht.prototype.outputRecipe=Ie.prototype.outputRecipe=qe.prototype.outputRecipe=$e.prototype.outputRecipe=function(t,e){return[this.constructor.name.toLowerCase(),Ke(this,e),this.expr.outputRecipe(t,e)]};X.prototype.outputRecipe=function(t,e){return["app",Ke(this,e),this.ruleName,this.args.map(r=>r.outputRecipe(t,e))]};xe.prototype.outputRecipe=function(t,e){return["unicodeChar",Ke(this,e),this.categoryOrProp]};V.prototype.introduceParams=Fe("introduceParams");Ce.introduceParams=Re.introduceParams=ke.prototype.introduceParams=Ne.prototype.introduceParams=Le.prototype.introduceParams=xe.prototype.introduceParams=function(t){return this};ge.prototype.introduceParams=function(t){return this.terms.forEach((e,r,n)=>{n[r]=e.introduceParams(t)}),this};Se.prototype.introduceParams=function(t){return this.factors.forEach((e,r,n)=>{n[r]=e.introduceParams(t)}),this};je.prototype.introduceParams=Ie.prototype.introduceParams=qe.prototype.introduceParams=$e.prototype.introduceParams=function(t){return this.expr=this.expr.introduceParams(t),this};X.prototype.introduceParams=function(t){const e=t.indexOf(this.ruleName);if(e>=0){if(this.args.length>0)throw new Error("Parameterized rules cannot be passed as arguments to another rule.");return new Le(e).withSource(this.source)}else return this.args.forEach((r,n,s)=>{s[n]=r.introduceParams(t)}),this};V.prototype.isNullable=function(t){return this._isNullable(t,Object.create(null))};V.prototype._isNullable=Fe("_isNullable");Ce._isNullable=Ne.prototype._isNullable=Le.prototype._isNullable=Yt.prototype._isNullable=xe.prototype._isNullable=function(t,e){return!1};Re._isNullable=function(t,e){return!0};ke.prototype._isNullable=function(t,e){return typeof this.obj=="string"?this.obj==="":!1};ge.prototype._isNullable=function(t,e){return this.terms.length===0||this.terms.some(r=>r._isNullable(t,e))};Se.prototype._isNullable=function(t,e){return this.factors.every(r=>r._isNullable(t,e))};Ft.prototype._isNullable=ht.prototype._isNullable=Ie.prototype._isNullable=qe.prototype._isNullable=function(t,e){return!0};$e.prototype._isNullable=function(t,e){return this.expr._isNullable(t,e)};X.prototype._isNullable=function(t,e){const r=this.toMemoKey();if(!Object.prototype.hasOwnProperty.call(e,r)){const{body:n}=t.rules[this.ruleName],s=n.substituteParams(this.args);e[r]=!1,e[r]=s._isNullable(t,e)}return e[r]};V.prototype.substituteParams=Fe("substituteParams");Ce.substituteParams=Re.substituteParams=ke.prototype.substituteParams=Ne.prototype.substituteParams=xe.prototype.substituteParams=function(t){return this};Le.prototype.substituteParams=function(t){return pa(t[this.index])};ge.prototype.substituteParams=function(t){return new ge(this.terms.map(e=>e.substituteParams(t)))};Se.prototype.substituteParams=function(t){return new Se(this.factors.map(e=>e.substituteParams(t)))};je.prototype.substituteParams=Ie.prototype.substituteParams=qe.prototype.substituteParams=$e.prototype.substituteParams=function(t){return new this.constructor(this.expr.substituteParams(t))};X.prototype.substituteParams=function(t){if(this.args.length===0)return this;{const e=this.args.map(r=>r.substituteParams(t));return new X(this.ruleName,e)}};function Hs(t){return/^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(t)}function ys(t){const e=Object.create(null);t.forEach(r=>{e[r]=(e[r]||0)+1}),Object.keys(e).forEach(r=>{if(e[r]<=1)return;let n=1;t.forEach((s,i)=>{s===r&&(t[i]=s+"_"+n++)})})}V.prototype.toArgumentNameList=Fe("toArgumentNameList");Ce.toArgumentNameList=function(t,e){return["any"]};Re.toArgumentNameList=function(t,e){return["end"]};ke.prototype.toArgumentNameList=function(t,e){return typeof this.obj=="string"&&/^[_a-zA-Z0-9]+$/.test(this.obj)?["_"+this.obj]:["$"+t]};Ne.prototype.toArgumentNameList=function(t,e){let r=this.from+"_to_"+this.to;return Hs(r)||(r="_"+r),Hs(r)||(r="$"+t),[r]};ge.prototype.toArgumentNameList=function(t,e){const r=this.terms.map(i=>i.toArgumentNameList(t,!0)),n=[],s=r[0].length;for(let i=0;i<s;i++){const a=[];for(let c=0;c<this.terms.length;c++)a.push(r[c][i]);const o=la(a);n.push(o.join("_or_"))}return e||ys(n),n};Se.prototype.toArgumentNameList=function(t,e){let r=[];return this.factors.forEach(n=>{const s=n.toArgumentNameList(t,!0);r=r.concat(s),t+=s.length}),e||ys(r),r};je.prototype.toArgumentNameList=function(t,e){const r=this.expr.toArgumentNameList(t,e).map(n=>n[n.length-1]==="s"?n+"es":n+"s");return e||ys(r),r};ht.prototype.toArgumentNameList=function(t,e){return this.expr.toArgumentNameList(t,e).map(r=>"opt"+r[0].toUpperCase()+r.slice(1))};Ie.prototype.toArgumentNameList=function(t,e){return[]};qe.prototype.toArgumentNameList=$e.prototype.toArgumentNameList=function(t,e){return this.expr.toArgumentNameList(t,e)};X.prototype.toArgumentNameList=function(t,e){return[this.ruleName]};xe.prototype.toArgumentNameList=function(t,e){return["$"+t]};Le.prototype.toArgumentNameList=function(t,e){return["param"+this.index]};V.prototype.toDisplayString=Fe("toDisplayString");ge.prototype.toDisplayString=Se.prototype.toDisplayString=function(){return this.source?this.source.trimmed().contents:"["+this.constructor.name+"]"};Ce.toDisplayString=Re.toDisplayString=je.prototype.toDisplayString=Ie.prototype.toDisplayString=qe.prototype.toDisplayString=$e.prototype.toDisplayString=ke.prototype.toDisplayString=Ne.prototype.toDisplayString=Le.prototype.toDisplayString=function(){return this.toString()};X.prototype.toDisplayString=function(){if(this.args.length>0){const t=this.args.map(e=>e.toDisplayString());return this.ruleName+"<"+t.join(",")+">"}else return this.ruleName};xe.prototype.toDisplayString=function(){return"Unicode ["+this.categoryOrProp+"] character"};function Sc(t){return t==="description"||t==="string"||t==="code"}class Ue{constructor(e,r,n){if(!Sc(n))throw new Error("invalid Failure type: "+n);this.pexpr=e,this.text=r,this.type=n,this.fluffy=!1}getPExpr(){return this.pexpr}getText(){return this.text}getType(){return this.type}isDescription(){return this.type==="description"}isStringTerminal(){return this.type==="string"}isCode(){return this.type==="code"}isFluffy(){return this.fluffy}makeFluffy(){this.fluffy=!0}clearFluffy(){this.fluffy=!1}subsumes(e){return this.getText()===e.getText()&&this.type===e.type&&(!this.isFluffy()||this.isFluffy()&&e.isFluffy())}toString(){return this.type==="string"?JSON.stringify(this.getText()):this.getText()}clone(){const e=new Ue(this.pexpr,this.text,this.type);return this.isFluffy()&&e.makeFluffy(),e}toKey(){return this.toString()+"#"+this.type}}V.prototype.toFailure=Fe("toFailure");Ce.toFailure=function(t){return new Ue(this,"any object","description")};Re.toFailure=function(t){return new Ue(this,"end of input","description")};ke.prototype.toFailure=function(t){return new Ue(this,this.obj,"string")};Ne.prototype.toFailure=function(t){return new Ue(this,JSON.stringify(this.from)+".."+JSON.stringify(this.to),"code")};Ie.prototype.toFailure=function(t){const e=this.expr===Ce?"nothing":"not "+this.expr.toFailure(t);return new Ue(this,e,"description")};qe.prototype.toFailure=function(t){return this.expr.toFailure(t)};X.prototype.toFailure=function(t){let{description:e}=t.rules[this.ruleName];return e||(e=(/^[aeiouAEIOU]/.test(this.ruleName)?"an":"a")+" "+this.ruleName),new Ue(this,e,"description")};xe.prototype.toFailure=function(t){return new Ue(this,"a Unicode ["+this.categoryOrProp+"] character","description")};ge.prototype.toFailure=function(t){const r="("+this.terms.map(n=>n.toFailure(t)).join(" or ")+")";return new Ue(this,r,"description")};Se.prototype.toFailure=function(t){const r="("+this.factors.map(n=>n.toFailure(t)).join(" ")+")";return new Ue(this,r,"description")};je.prototype.toFailure=function(t){const e="("+this.expr.toFailure(t)+this.operator+")";return new Ue(this,e,"description")};V.prototype.toString=Fe("toString");Ce.toString=function(){return"any"};Re.toString=function(){return"end"};ke.prototype.toString=function(){return JSON.stringify(this.obj)};Ne.prototype.toString=function(){return JSON.stringify(this.from)+".."+JSON.stringify(this.to)};Le.prototype.toString=function(){return"$"+this.index};$e.prototype.toString=function(){return"#("+this.expr.toString()+")"};ge.prototype.toString=function(){return this.terms.length===1?this.terms[0].toString():"("+this.terms.map(t=>t.toString()).join(" | ")+")"};Se.prototype.toString=function(){return this.factors.length===1?this.factors[0].toString():"("+this.factors.map(t=>t.toString()).join(" ")+")"};je.prototype.toString=function(){return this.expr+this.operator};Ie.prototype.toString=function(){return"~"+this.expr};qe.prototype.toString=function(){return"&"+this.expr};X.prototype.toString=function(){if(this.args.length>0){const t=this.args.map(e=>e.toString());return this.ruleName+"<"+t.join(",")+">"}else return this.ruleName};xe.prototype.toString=function(){return"\\p{"+this.categoryOrProp+"}"};class vs extends V{constructor(e){super(),this.obj=e}_getString(e){const r=e.currentApplication().args[this.obj.index];return wt(r instanceof ke,"expected a Terminal expression"),r.obj}allowsSkippingPrecedingSpace(){return!0}eval(e){const{inputStream:r}=e,n=r.pos,s=this._getString(e);return r.matchString(s,!0)?(e.pushBinding(new jt(s.length),n),!0):(e.processFailure(n,this),!1)}getArity(){return 1}substituteParams(e){return new vs(this.obj.substituteParams(e))}toDisplayString(){return this.obj.toDisplayString()+" (case-insensitive)"}toFailure(e){return new Ue(this,this.obj.toFailure(e)+" (case-insensitive)","description")}_isNullable(e,r){return this.obj._isNullable(e,r)}}let Ia;wa(t=>{Ia=t.rules.applySyntactic.body});const yn=new X("spaces");class _c{constructor(e,r,n){this.matcher=e,this.startExpr=r,this.grammar=e.grammar,this.input=e.getInput(),this.inputStream=new cn(this.input),this.memoTable=e._memoTable,this.userData=void 0,this.doNotMemoize=!1,this._bindings=[],this._bindingOffsets=[],this._applicationStack=[],this._posStack=[0],this.inLexifiedContextStack=[!1],this.rightmostFailurePosition=-1,this._rightmostFailurePositionStack=[],this._recordedFailuresStack=[],n!==void 0&&(this.positionToRecordFailures=n,this.recordedFailures=Object.create(null))}posToOffset(e){return e-this._posStack[this._posStack.length-1]}enterApplication(e,r){this._posStack.push(this.inputStream.pos),this._applicationStack.push(r),this.inLexifiedContextStack.push(!1),e.enter(r),this._rightmostFailurePositionStack.push(this.rightmostFailurePosition),this.rightmostFailurePosition=-1}exitApplication(e,r){const n=this._posStack.pop();this._applicationStack.pop(),this.inLexifiedContextStack.pop(),e.exit(),this.rightmostFailurePosition=Math.max(this.rightmostFailurePosition,this._rightmostFailurePositionStack.pop()),r&&this.pushBinding(r,n)}enterLexifiedContext(){this.inLexifiedContextStack.push(!0)}exitLexifiedContext(){this.inLexifiedContextStack.pop()}currentApplication(){return this._applicationStack[this._applicationStack.length-1]}inSyntacticContext(){const e=this.currentApplication();return e?e.isSyntactic()&&!this.inLexifiedContext():this.startExpr.factors[0].isSyntactic()}inLexifiedContext(){return this.inLexifiedContextStack[this.inLexifiedContextStack.length-1]}skipSpaces(){return this.pushFailuresInfo(),this.eval(yn),this.popBinding(),this.popFailuresInfo(),this.inputStream.pos}skipSpacesIfInSyntacticContext(){return this.inSyntacticContext()?this.skipSpaces():this.inputStream.pos}maybeSkipSpacesBefore(e){return e.allowsSkippingPrecedingSpace()&&e!==yn?this.skipSpacesIfInSyntacticContext():this.inputStream.pos}pushBinding(e,r){this._bindings.push(e),this._bindingOffsets.push(this.posToOffset(r))}popBinding(){this._bindings.pop(),this._bindingOffsets.pop()}numBindings(){return this._bindings.length}truncateBindings(e){for(;this._bindings.length>e;)this.popBinding()}getCurrentPosInfo(){return this.getPosInfo(this.inputStream.pos)}getPosInfo(e){let r=this.memoTable[e];return r||(r=this.memoTable[e]=new lc),r}processFailure(e,r){if(this.rightmostFailurePosition=Math.max(this.rightmostFailurePosition,e),this.recordedFailures&&e===this.positionToRecordFailures){const n=this.currentApplication();n&&(r=r.substituteParams(n.args)),this.recordFailure(r.toFailure(this.grammar),!1)}}recordFailure(e,r){const n=e.toKey();this.recordedFailures[n]?this.recordedFailures[n].isFluffy()&&!e.isFluffy()&&this.recordedFailures[n].clearFluffy():this.recordedFailures[n]=r?e.clone():e}recordFailures(e,r){Object.keys(e).forEach(n=>{this.recordFailure(e[n],r)})}cloneRecordedFailures(){if(!this.recordedFailures)return;const e=Object.create(null);return Object.keys(this.recordedFailures).forEach(r=>{e[r]=this.recordedFailures[r].clone()}),e}getRightmostFailurePosition(){return this.rightmostFailurePosition}_getRightmostFailureOffset(){return this.rightmostFailurePosition>=0?this.posToOffset(this.rightmostFailurePosition):-1}getMemoizedTraceEntry(e,r){const n=this.memoTable[e];if(n&&r instanceof X){const s=n.memo[r.toMemoKey()];if(s&&s.traceEntry){const i=s.traceEntry.cloneWithExpr(r);return i.isMemoized=!0,i}}return null}getTraceEntry(e,r,n,s){if(r instanceof X){const i=this.currentApplication(),a=i?i.args:[];r=r.substituteParams(a)}return this.getMemoizedTraceEntry(e,r)||new pt(this.input,e,this.inputStream.pos,r,n,s,this.trace)}isTracing(){return!!this.trace}hasNecessaryInfo(e){return this.trace&&!e.traceEntry?!1:this.recordedFailures&&this.inputStream.pos+e.rightmostFailureOffset===this.positionToRecordFailures?!!e.failuresAtRightmostPosition:!0}useMemoizedResult(e,r){this.trace&&this.trace.push(r.traceEntry);const n=this.inputStream.pos+r.rightmostFailureOffset;return this.rightmostFailurePosition=Math.max(this.rightmostFailurePosition,n),this.recordedFailures&&this.positionToRecordFailures===n&&r.failuresAtRightmostPosition&&this.recordFailures(r.failuresAtRightmostPosition,!0),this.inputStream.examinedLength=Math.max(this.inputStream.examinedLength,r.examinedLength+e),r.value?(this.inputStream.pos+=r.matchLength,this.pushBinding(r.value,e),!0):!1}eval(e){const{inputStream:r}=this,n=this._bindings.length,s=this.userData;let i;this.recordedFailures&&(i=this.recordedFailures,this.recordedFailures=Object.create(null));const a=r.pos,o=this.maybeSkipSpacesBefore(e);let c;this.trace&&(c=this.trace,this.trace=[]);const u=e.eval(this);if(this.trace){const f=this._bindings.slice(n),l=this.getTraceEntry(o,e,u,f);l.isImplicitSpaces=e===yn,l.isRootNode=e===this.startExpr,c.push(l),this.trace=c}return u?this.recordedFailures&&r.pos===this.positionToRecordFailures&&Object.keys(this.recordedFailures).forEach(f=>{this.recordedFailures[f].makeFluffy()}):(r.pos=a,this.truncateBindings(n),this.userData=s),this.recordedFailures&&this.recordFailures(i,!1),e===Ia&&this.skipSpaces(),u}getMatchResult(){this.grammar._setUpMatchState(this),this.eval(this.startExpr);let e;this.recordedFailures&&(e=Object.keys(this.recordedFailures).map(n=>this.recordedFailures[n]));const r=this._bindings[0];return r&&(r.grammar=this.grammar),new Sa(this.matcher,this.input,this.startExpr,r,this._bindingOffsets[0],this.rightmostFailurePosition,e)}getTrace(){this.trace=[];const e=this.getMatchResult(),r=this.trace[this.trace.length-1];return r.result=e,r}pushFailuresInfo(){this._rightmostFailurePositionStack.push(this.rightmostFailurePosition),this._recordedFailuresStack.push(this.recordedFailures)}popFailuresInfo(){this.rightmostFailurePosition=this._rightmostFailurePositionStack.pop(),this.recordedFailures=this._recordedFailuresStack.pop()}}class Ac{constructor(e){this.grammar=e,this._memoTable=[],this._input="",this._isMemoTableStale=!1}_resetMemoTable(){this._memoTable=[],this._isMemoTableStale=!1}getInput(){return this._input}setInput(e){return this._input!==e&&this.replaceInputRange(0,this._input.length,e),this}replaceInputRange(e,r,n){const s=this._input,i=this._memoTable;if(e<0||e>s.length||r<0||r>s.length||e>r)throw new Error("Invalid indices: "+e+" and "+r);this._input=s.slice(0,e)+n+s.slice(r),this._input!==s&&i.length>0&&(this._isMemoTableStale=!0);const a=i.slice(r);i.length=e;for(let o=0;o<n.length;o++)i.push(void 0);for(const o of a)i.push(o);for(let o=0;o<e;o++){const c=i[o];c&&c.clearObsoleteEntries(o,e)}return this}match(e,r={incremental:!0}){return this._match(this._getStartExpr(e),{incremental:r.incremental,tracing:!1})}trace(e,r={incremental:!0}){return this._match(this._getStartExpr(e),{incremental:r.incremental,tracing:!0})}_match(e,r={}){const n={tracing:!1,incremental:!0,positionToRecordFailures:void 0,...r};if(!n.incremental)this._resetMemoTable();else if(this._isMemoTableStale&&!this.grammar.supportsIncrementalParsing)throw Ho(this.grammar);const s=new _c(this,e,n.positionToRecordFailures);return n.tracing?s.getTrace():s.getMatchResult()}_getStartExpr(e){const r=e||this.grammar.defaultStartRule;if(!r)throw new Error("Missing start rule argument -- the grammar has no default start rule.");const n=this.grammar.parseApplication(r);return new Se([n,Re])}}const sr=[],Fn=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);class Ws{constructor(e,r,n){this._node=e,this.source=r,this._baseInterval=n,e.isNonterminal()&&wt(r===n),this._childWrappers=[]}_forgetMemoizedResultFor(e){delete this._node[this._semantics.attributeKeys[e]],this.children.forEach(r=>{r._forgetMemoizedResultFor(e)})}child(e){if(!(0<=e&&e<this._node.numChildren()))return;let r=this._childWrappers[e];if(!r){const n=this._node.childAt(e),s=this._node.childOffsets[e],i=this._baseInterval.subInterval(s,n.matchLength),a=n.isNonterminal()?i:this._baseInterval;r=this._childWrappers[e]=this._semantics.wrap(n,i,a)}return r}_children(){for(let e=0;e<this._node.numChildren();e++)this.child(e);return this._childWrappers}isIteration(){return this._node.isIteration()}isTerminal(){return this._node.isTerminal()}isNonterminal(){return this._node.isNonterminal()}isSyntactic(){return this.isNonterminal()&&this._node.isSyntactic()}isLexical(){return this.isNonterminal()&&this._node.isLexical()}isOptional(){return this._node.isOptional()}iteration(e){const r=e||[],n=r.map(a=>a._node),s=new Aa(n,[],-1,!1),i=this._semantics.wrap(s,null,null);return i._childWrappers=r,i}get children(){return this._children()}get ctorName(){return this._node.ctorName}get numChildren(){return this._node.numChildren()}get sourceString(){return this.source.contents}}class Pe{constructor(e,r){const n=this;if(this.grammar=e,this.checkedActionDicts=!1,this.Wrapper=class extends(r?r.Wrapper:Ws){constructor(s,i,a){super(s,i,a),n.checkActionDictsIfHaventAlready(),this._semantics=n}toString(){return"[semantics wrapper for "+n.grammar.name+"]"}},this.super=r,r){if(!(e.equals(this.super.grammar)||e._inheritsFrom(this.super.grammar)))throw new Error("Cannot extend a semantics for grammar '"+this.super.grammar.name+"' for use with grammar '"+e.name+"' (not a sub-grammar)");this.operations=Object.create(this.super.operations),this.attributes=Object.create(this.super.attributes),this.attributeKeys=Object.create(null);for(const s in this.attributes)Object.defineProperty(this.attributeKeys,s,{value:Vs(s)})}else this.operations=Object.create(null),this.attributes=Object.create(null),this.attributeKeys=Object.create(null)}toString(){return"[semantics for "+this.grammar.name+"]"}checkActionDictsIfHaventAlready(){this.checkedActionDicts||(this.checkActionDicts(),this.checkedActionDicts=!0)}checkActionDicts(){let e;for(e in this.operations)this.operations[e].checkActionDict(this.grammar);for(e in this.attributes)this.attributes[e].checkActionDict(this.grammar)}toRecipe(e){function r(s){return s.super!==Pe.BuiltInSemantics._getSemantics()}let n=`(function(g) {
27
+ `;if(r(this)){n+=" var semantics = "+this.super.toRecipe(!0)+"(g";const s=this.super.grammar;let i=this.grammar;for(;i!==s;)n+=".superGrammar",i=i.superGrammar;n+=`);
28
+ `,n+=" return g.extendSemantics(semantics)"}else n+=" return g.createSemantics()";return["Operation","Attribute"].forEach(s=>{const i=this[s.toLowerCase()+"s"];Object.keys(i).forEach(a=>{const{actionDict:o,formals:c,builtInDefault:u}=i[a];let f=a;c.length>0&&(f+="("+c.join(", ")+")");let l;r(this)&&this.super[s.toLowerCase()+"s"][a]?l="extend"+s:l="add"+s,n+=`
29
+ .`+l+"("+JSON.stringify(f)+", {";const p=[];Object.keys(o).forEach(y=>{if(o[y]!==u){let v=o[y].toString().trim();v=v.replace(/^.*\(/,"function("),p.push(`
30
+ `+JSON.stringify(y)+": "+v)}}),n+=p.join(",")+`
31
+ })`})}),n+=`;
32
+ })`,e||(n=`(function() {
33
+ var grammar = this.fromRecipe(`+this.grammar.toRecipe()+`);
34
+ var semantics = `+n+`(grammar);
35
+ return semantics;
36
+ });
37
+ `),n}addOperationOrAttribute(e,r,n){const s=e+"s",i=Gs(r,e),{name:a}=i,{formals:o}=i;this.assertNewName(a,e);const c=Ic(e,a,l),u={_default:c};Object.keys(n).forEach(p=>{u[p]=n[p]});const f=e==="operation"?new dr(a,o,u,c):new jn(a,u,c);f.checkActionDict(this.grammar),this[s][a]=f;function l(...p){const y=this._semantics[s][a];if(arguments.length!==y.formals.length)throw new Error("Invalid number of arguments passed to "+a+" "+e+" (expected "+y.formals.length+", got "+arguments.length+")");const v=Object.create(null);for(const[C,k]of Object.entries(p)){const x=y.formals[C];v[x]=k}const w=this.args;this.args=v;const R=y.execute(this._semantics,this);return this.args=w,R}e==="operation"?(this.Wrapper.prototype[a]=l,this.Wrapper.prototype[a].toString=function(){return"["+a+" operation]"}):(Object.defineProperty(this.Wrapper.prototype,a,{get:l,configurable:!0}),Object.defineProperty(this.attributeKeys,a,{value:Vs(a)}))}extendOperationOrAttribute(e,r,n){const s=e+"s";if(Gs(r,"attribute"),!(this.super&&r in this.super[s]))throw new Error("Cannot extend "+e+" '"+r+"': did not inherit an "+e+" with that name");if(Fn(this[s],r))throw new Error("Cannot extend "+e+" '"+r+"' again");const i=this[s][r].formals,a=this[s][r].actionDict,o=Object.create(a);Object.keys(n).forEach(c=>{o[c]=n[c]}),this[s][r]=e==="operation"?new dr(r,i,o):new jn(r,o),this[s][r].checkActionDict(this.grammar)}assertNewName(e,r){if(Fn(Ws.prototype,e))throw new Error("Cannot add "+r+" '"+e+"': that's a reserved name");if(e in this.operations)throw new Error("Cannot add "+r+" '"+e+"': an operation with that name already exists");if(e in this.attributes)throw new Error("Cannot add "+r+" '"+e+"': an attribute with that name already exists")}wrap(e,r,n){const s=n||r;return e instanceof this.Wrapper?e:new this.Wrapper(e,r,s)}}function Gs(t,e){if(!Pe.prototypeGrammar)return wt(t.indexOf("(")===-1),{name:t,formals:[]};const r=Pe.prototypeGrammar.match(t,e==="operation"?"OperationSignature":"AttributeSignature");if(r.failed())throw new Error(r.message);return Pe.prototypeGrammarSemantics(r).parse()}function Ic(t,e,r){return function(...n){const i=(this._semantics.operations[e]||this._semantics.attributes[e]).formals.map(a=>this.args[a]);if(!this.isIteration()&&n.length===1)return r.apply(n[0],i);throw nc(this.ctorName,e,t,sr)}}Pe.createSemantics=function(t,e){const r=new Pe(t,e!==void 0?e:Pe.BuiltInSemantics._getSemantics()),n=function(i){if(!(i instanceof Sa))throw new TypeError("Semantics expected a MatchResult, but got "+fs(i));if(i.failed())throw new TypeError("cannot apply Semantics to "+i.toString());const a=i._cst;if(a.grammar!==t)throw new Error("Cannot use a MatchResult from grammar '"+a.grammar.name+"' with a semantics for '"+t.name+"'");const o=new cn(i.input);return r.wrap(a,o.interval(i._cstOffset,i.input.length))};return n.addOperation=function(s,i){return r.addOperationOrAttribute("operation",s,i),n},n.extendOperation=function(s,i){return r.extendOperationOrAttribute("operation",s,i),n},n.addAttribute=function(s,i){return r.addOperationOrAttribute("attribute",s,i),n},n.extendAttribute=function(s,i){return r.extendOperationOrAttribute("attribute",s,i),n},n._getActionDict=function(s){const i=r.operations[s]||r.attributes[s];if(!i)throw new Error('"'+s+'" is not a valid operation or attribute name in this semantics for "'+t.name+'"');return i.actionDict},n._remove=function(s){let i;return s in r.operations?(i=r.operations[s],delete r.operations[s]):s in r.attributes&&(i=r.attributes[s],delete r.attributes[s]),delete r.Wrapper.prototype[s],i},n.getOperationNames=function(){return Object.keys(r.operations)},n.getAttributeNames=function(){return Object.keys(r.attributes)},n.getGrammar=function(){return r.grammar},n.toRecipe=function(s){return r.toRecipe(s)},n.toString=r.toString.bind(r),n._getSemantics=function(){return r},n};class dr{constructor(e,r,n,s){this.name=e,this.formals=r,this.actionDict=n,this.builtInDefault=s}checkActionDict(e){e._checkTopDownActionDict(this.typeName,this.name,this.actionDict)}execute(e,r){try{const{ctorName:n}=r._node;let s=this.actionDict[n];return s?(sr.push([this,n]),s.apply(r,r._children())):r.isNonterminal()&&(s=this.actionDict._nonterminal,s)?(sr.push([this,"_nonterminal",n]),s.apply(r,r._children())):(sr.push([this,"default action",n]),this.actionDict._default.apply(r,r._children()))}finally{sr.pop()}}}dr.prototype.typeName="operation";class jn extends dr{constructor(e,r,n){super(e,[],r,n)}execute(e,r){const n=r._node,s=e.attributeKeys[this.name];return Fn(n,s)||(n[s]=dr.prototype.execute.call(this,e,r)),n[s]}}jn.prototype.typeName="attribute";const Ks=["_iter","_terminal","_nonterminal","_default"];function Zs(t){return Object.keys(t.rules).sort().map(e=>t.rules[e])}const xc=t=>t.replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029");let xa,ka;class Me{constructor(e,r,n,s){if(this.name=e,this.superGrammar=r,this.rules=n,s){if(!(s in n))throw new Error("Invalid start rule: '"+s+"' is not a rule in grammar '"+e+"'");this.defaultStartRule=s}this._matchStateInitializer=void 0,this.supportsIncrementalParsing=!0}matcher(){return new Ac(this)}isBuiltIn(){return this===Me.ProtoBuiltInRules||this===Me.BuiltInRules}equals(e){if(this===e)return!0;if(e==null||this.name!==e.name||this.defaultStartRule!==e.defaultStartRule||!(this.superGrammar===e.superGrammar||this.superGrammar.equals(e.superGrammar)))return!1;const r=Zs(this),n=Zs(e);return r.length===n.length&&r.every((s,i)=>s.description===n[i].description&&s.formals.join(",")===n[i].formals.join(",")&&s.body.toString()===n[i].body.toString())}match(e,r){const n=this.matcher();return n.replaceInputRange(0,0,e),n.match(r)}trace(e,r){const n=this.matcher();return n.replaceInputRange(0,0,e),n.trace(r)}createSemantics(){return Pe.createSemantics(this)}extendSemantics(e){return Pe.createSemantics(this,e._getSemantics())}_checkTopDownActionDict(e,r,n){const s=[];for(const i in n){const a=n[i];if(!Ks.includes(i)&&!(i in this.rules)){s.push(`'${i}' is not a valid semantic action for '${this.name}'`);continue}if(typeof a!="function"){s.push(`'${i}' must be a function in an action dictionary for '${this.name}'`);continue}const c=a.length,u=this._topDownActionArity(i);if(c!==u){let f;i==="_iter"||i==="_nonterminal"?f=`it should use a rest parameter, e.g. \`${i}(...children) {}\`. NOTE: this is new in Ohm v16 — see https://ohmjs.org/d/ati for details.`:f=`expected ${u}, got ${c}`,s.push(`Semantic action '${i}' has the wrong arity: ${f}`)}}if(s.length>0){const i=s.map(o=>"- "+o),a=new Error([`Found errors in the action dictionary of the '${r}' ${e}:`,...i].join(`
38
+ `));throw a.problems=s,a}}_topDownActionArity(e){return Ks.includes(e)?0:this.rules[e].body.getArity()}_inheritsFrom(e){let r=this.superGrammar;for(;r;){if(r.equals(e,!0))return!0;r=r.superGrammar}return!1}toRecipe(e=void 0){const r={};this.source&&(r.source=this.source.contents);let n=null;this.defaultStartRule&&(n=this.defaultStartRule);const s={};Object.keys(this.rules).forEach(o=>{const c=this.rules[o],{body:u}=c,f=!this.superGrammar||!this.superGrammar.rules[o];let l;f?l="define":l=u instanceof an?"extend":"override";const p={};if(c.source&&this.source){const w=c.source.relativeTo(this.source);p.sourceInterval=[w.startIdx,w.endIdx]}const y=f?c.description:null,v=u.outputRecipe(c.formals,this.source);s[o]=[l,p,y,c.formals,v]});let i="null";e?i=e:this.superGrammar&&!this.superGrammar.isBuiltIn()&&(i=this.superGrammar.toRecipe());const a=[...["grammar",r,this.name].map(JSON.stringify),i,...[n,s].map(JSON.stringify)];return xc(`[${a.join(",")}]`)}toOperationActionDictionaryTemplate(){return this._toOperationOrAttributeActionDictionaryTemplate()}toAttributeActionDictionaryTemplate(){return this._toOperationOrAttributeActionDictionaryTemplate()}_toOperationOrAttributeActionDictionaryTemplate(){const e=new Dt;e.append("{");let r=!0;for(const n in this.rules){const{body:s}=this.rules[n];r?r=!1:e.append(","),e.append(`
39
+ `),e.append(" "),this.addSemanticActionTemplate(n,s,e)}return e.append(`
40
+ }`),e.contents()}addSemanticActionTemplate(e,r,n){n.append(e),n.append(": function(");const s=this._topDownActionArity(e);n.append(sn("_",s).join(", ")),n.append(`) {
41
+ `),n.append(" }")}parseApplication(e){let r;if(e.indexOf("<")===-1)r=new X(e);else{const s=xa.match(e,"Base_application");r=ka(s,{})}if(!(r.ruleName in this.rules))throw ga(r.ruleName,this.name);const{formals:n}=this.rules[r.ruleName];if(n.length!==r.args.length){const{source:s}=this.rules[r.ruleName];throw ya(r.ruleName,n.length,r.args.length,s)}return r}_setUpMatchState(e){this._matchStateInitializer&&this._matchStateInitializer(e)}}Me.ProtoBuiltInRules=new Me("ProtoBuiltInRules",void 0,{any:{body:Ce,formals:[],description:"any character",primitive:!0},end:{body:Re,formals:[],description:"end of input",primitive:!0},caseInsensitive:{body:new vs(new Le(0)),formals:["str"],primitive:!0},lower:{body:new xe("Ll"),formals:[],description:"a lowercase letter",primitive:!0},upper:{body:new xe("Lu"),formals:[],description:"an uppercase letter",primitive:!0},unicodeLtmo:{body:new xe("Ltmo"),formals:[],description:"a Unicode character in Lt, Lm, or Lo",primitive:!0},spaces:{body:new Ft(new X("space")),formals:[]},space:{body:new Ne("\0"," "),formals:[],description:"a space"}});Me.initApplicationParser=function(t,e){xa=t,ka=e};class Js{constructor(e){this.name=e}sourceInterval(e,r){return this.source.subInterval(e,r-e)}ensureSuperGrammar(){return this.superGrammar||this.withSuperGrammar(this.name==="BuiltInRules"?Me.ProtoBuiltInRules:Me.BuiltInRules),this.superGrammar}ensureSuperGrammarRuleForOverriding(e,r){const n=this.ensureSuperGrammar().rules[e];if(!n)throw Wo(e,this.superGrammar.name,r);return n}installOverriddenOrExtendedRule(e,r,n,s){const i=Rn(r);if(i.length>0)throw Us(e,i,s);const a=this.ensureSuperGrammar().rules[e],o=a.formals,c=o?o.length:0;if(r.length!==c)throw ya(e,c,r.length,s);return this.install(e,r,n,a.description,s)}install(e,r,n,s,i,a=!1){return this.rules[e]={body:n.introduceParams(r),formals:r,description:s,source:i,primitive:a},this}withSuperGrammar(e){if(this.superGrammar)throw new Error("the super grammar of a GrammarDecl cannot be set more than once");return this.superGrammar=e,this.rules=Object.create(e.rules),e.isBuiltIn()||(this.defaultStartRule=e.defaultStartRule),this}withDefaultStartRule(e){return this.defaultStartRule=e,this}withSource(e){return this.source=new cn(e).interval(0,e.length),this}build(){const e=new Me(this.name,this.ensureSuperGrammar(),this.rules,this.defaultStartRule);e._matchStateInitializer=e.superGrammar._matchStateInitializer,e.supportsIncrementalParsing=e.superGrammar.supportsIncrementalParsing;const r=[];let n=!1;return Object.keys(e.rules).forEach(s=>{const{body:i}=e.rules[s];try{i.assertChoicesHaveUniformArity(s)}catch(a){r.push(a)}try{i.assertAllApplicationsAreValid(s,e)}catch(a){r.push(a),n=!0}}),n||Object.keys(e.rules).forEach(s=>{const{body:i}=e.rules[s];try{i.assertIteratedExprsAreNotNullable(e,[])}catch(a){r.push(a)}}),r.length>0&&sc(r),this.source&&(e.source=this.source),e}define(e,r,n,s,i,a){if(this.ensureSuperGrammar(),this.superGrammar.rules[e])throw $s(e,this.name,this.superGrammar.name,i);if(this.rules[e])throw $s(e,this.name,this.name,i);const o=Rn(r);if(o.length>0)throw Us(e,o,i);return this.install(e,r,n,s,i,a)}override(e,r,n,s,i){return this.ensureSuperGrammarRuleForOverriding(e,i),this.installOverriddenOrExtendedRule(e,r,n,i),this}extend(e,r,n,s,i){if(!this.ensureSuperGrammar().rules[e])throw Go(e,this.superGrammar.name,i);const o=new an(this.superGrammar,e,n);return o.source=n.source,this.installOverriddenOrExtendedRule(e,r,o,i),this}}class Tr{constructor(e){this.currentDecl=null,this.currentRuleName=null,this.options=e||{}}newGrammar(e){return new Js(e)}grammar(e,r,n,s,i){const a=new Js(r);return n&&a.withSuperGrammar(n instanceof Me?n:this.fromRecipe(n)),s&&a.withDefaultStartRule(s),e&&e.source&&a.withSource(e.source),this.currentDecl=a,Object.keys(i).forEach(o=>{this.currentRuleName=o;const c=i[o],u=c[0],f=c[1],l=c[2],p=c[3],y=this.fromRecipe(c[4]);let v;a.source&&f&&f.sourceInterval&&(v=a.source.subInterval(f.sourceInterval[0],f.sourceInterval[1]-f.sourceInterval[0])),a[u](o,p,y,l,v)}),this.currentRuleName=this.currentDecl=null,a.build()}terminal(e){return new ke(e)}range(e,r){return new Ne(e,r)}param(e){return new Le(e)}alt(...e){let r=[];for(let n of e)n instanceof V||(n=this.fromRecipe(n)),n instanceof ge?r=r.concat(n.terms):r.push(n);return r.length===1?r[0]:new ge(r)}seq(...e){let r=[];for(let n of e)n instanceof V||(n=this.fromRecipe(n)),n instanceof Se?r=r.concat(n.factors):r.push(n);return r.length===1?r[0]:new Se(r)}star(e){return e instanceof V||(e=this.fromRecipe(e)),new Ft(e)}plus(e){return e instanceof V||(e=this.fromRecipe(e)),new Yt(e)}opt(e){return e instanceof V||(e=this.fromRecipe(e)),new ht(e)}not(e){return e instanceof V||(e=this.fromRecipe(e)),new Ie(e)}lookahead(e){return e instanceof V||(e=this.fromRecipe(e)),this.options.eliminateLookaheads?new Ie(new Ie(e)):new qe(e)}lex(e){return e instanceof V||(e=this.fromRecipe(e)),new $e(e)}app(e,r){return r&&r.length>0&&(r=r.map(function(n){return n instanceof V?n:this.fromRecipe(n)},this)),new X(e,r)}splice(e,r){return new on(this.currentDecl.superGrammar,this.currentRuleName,e.map(n=>this.fromRecipe(n)),r.map(n=>this.fromRecipe(n)))}fromRecipe(e){const r=e[0]==="grammar"?e.slice(1):e.slice(2),n=this[e[0]](...r),s=e[1];return s&&s.sourceInterval&&this.currentDecl&&n.withSource(this.currentDecl.sourceInterval(...s.sourceInterval)),n}}function bs(t){return typeof t=="function"?t.call(new Tr):(typeof t=="string"&&(t=JSON.parse(t)),new Tr().fromRecipe(t))}const ws=bs(["grammar",{source:`BuiltInRules {
42
+
43
+ alnum (an alpha-numeric character)
44
+ = letter
45
+ | digit
46
+
47
+ letter (a letter)
48
+ = lower
49
+ | upper
50
+ | unicodeLtmo
51
+
52
+ digit (a digit)
53
+ = "0".."9"
54
+
55
+ hexDigit (a hexadecimal digit)
56
+ = digit
57
+ | "a".."f"
58
+ | "A".."F"
59
+
60
+ ListOf<elem, sep>
61
+ = NonemptyListOf<elem, sep>
62
+ | EmptyListOf<elem, sep>
63
+
64
+ NonemptyListOf<elem, sep>
65
+ = elem (sep elem)*
66
+
67
+ EmptyListOf<elem, sep>
68
+ = /* nothing */
69
+
70
+ listOf<elem, sep>
71
+ = nonemptyListOf<elem, sep>
72
+ | emptyListOf<elem, sep>
73
+
74
+ nonemptyListOf<elem, sep>
75
+ = elem (sep elem)*
76
+
77
+ emptyListOf<elem, sep>
78
+ = /* nothing */
79
+
80
+ // Allows a syntactic rule application within a lexical context.
81
+ applySyntactic<app> = app
82
+ }`},"BuiltInRules",null,null,{alnum:["define",{sourceInterval:[18,78]},"an alpha-numeric character",[],["alt",{sourceInterval:[60,78]},["app",{sourceInterval:[60,66]},"letter",[]],["app",{sourceInterval:[73,78]},"digit",[]]]],letter:["define",{sourceInterval:[82,142]},"a letter",[],["alt",{sourceInterval:[107,142]},["app",{sourceInterval:[107,112]},"lower",[]],["app",{sourceInterval:[119,124]},"upper",[]],["app",{sourceInterval:[131,142]},"unicodeLtmo",[]]]],digit:["define",{sourceInterval:[146,177]},"a digit",[],["range",{sourceInterval:[169,177]},"0","9"]],hexDigit:["define",{sourceInterval:[181,254]},"a hexadecimal digit",[],["alt",{sourceInterval:[219,254]},["app",{sourceInterval:[219,224]},"digit",[]],["range",{sourceInterval:[231,239]},"a","f"],["range",{sourceInterval:[246,254]},"A","F"]]],ListOf:["define",{sourceInterval:[258,336]},null,["elem","sep"],["alt",{sourceInterval:[282,336]},["app",{sourceInterval:[282,307]},"NonemptyListOf",[["param",{sourceInterval:[297,301]},0],["param",{sourceInterval:[303,306]},1]]],["app",{sourceInterval:[314,336]},"EmptyListOf",[["param",{sourceInterval:[326,330]},0],["param",{sourceInterval:[332,335]},1]]]]],NonemptyListOf:["define",{sourceInterval:[340,388]},null,["elem","sep"],["seq",{sourceInterval:[372,388]},["param",{sourceInterval:[372,376]},0],["star",{sourceInterval:[377,388]},["seq",{sourceInterval:[378,386]},["param",{sourceInterval:[378,381]},1],["param",{sourceInterval:[382,386]},0]]]]],EmptyListOf:["define",{sourceInterval:[392,434]},null,["elem","sep"],["seq",{sourceInterval:[438,438]}]],listOf:["define",{sourceInterval:[438,516]},null,["elem","sep"],["alt",{sourceInterval:[462,516]},["app",{sourceInterval:[462,487]},"nonemptyListOf",[["param",{sourceInterval:[477,481]},0],["param",{sourceInterval:[483,486]},1]]],["app",{sourceInterval:[494,516]},"emptyListOf",[["param",{sourceInterval:[506,510]},0],["param",{sourceInterval:[512,515]},1]]]]],nonemptyListOf:["define",{sourceInterval:[520,568]},null,["elem","sep"],["seq",{sourceInterval:[552,568]},["param",{sourceInterval:[552,556]},0],["star",{sourceInterval:[557,568]},["seq",{sourceInterval:[558,566]},["param",{sourceInterval:[558,561]},1],["param",{sourceInterval:[562,566]},0]]]]],emptyListOf:["define",{sourceInterval:[572,682]},null,["elem","sep"],["seq",{sourceInterval:[685,685]}]],applySyntactic:["define",{sourceInterval:[685,710]},null,["app"],["param",{sourceInterval:[707,710]},0]]}]);Me.BuiltInRules=ws;oc(Me.BuiltInRules);const Ss=bs(["grammar",{source:`Ohm {
83
+
84
+ Grammars
85
+ = Grammar*
86
+
87
+ Grammar
88
+ = ident SuperGrammar? "{" Rule* "}"
89
+
90
+ SuperGrammar
91
+ = "<:" ident
92
+
93
+ Rule
94
+ = ident Formals? ruleDescr? "=" RuleBody -- define
95
+ | ident Formals? ":=" OverrideRuleBody -- override
96
+ | ident Formals? "+=" RuleBody -- extend
97
+
98
+ RuleBody
99
+ = "|"? NonemptyListOf<TopLevelTerm, "|">
100
+
101
+ TopLevelTerm
102
+ = Seq caseName -- inline
103
+ | Seq
104
+
105
+ OverrideRuleBody
106
+ = "|"? NonemptyListOf<OverrideTopLevelTerm, "|">
107
+
108
+ OverrideTopLevelTerm
109
+ = "..." -- superSplice
110
+ | TopLevelTerm
111
+
112
+ Formals
113
+ = "<" ListOf<ident, ","> ">"
114
+
115
+ Params
116
+ = "<" ListOf<Seq, ","> ">"
117
+
118
+ Alt
119
+ = NonemptyListOf<Seq, "|">
120
+
121
+ Seq
122
+ = Iter*
123
+
124
+ Iter
125
+ = Pred "*" -- star
126
+ | Pred "+" -- plus
127
+ | Pred "?" -- opt
128
+ | Pred
129
+
130
+ Pred
131
+ = "~" Lex -- not
132
+ | "&" Lex -- lookahead
133
+ | Lex
134
+
135
+ Lex
136
+ = "#" Base -- lex
137
+ | Base
138
+
139
+ Base
140
+ = ident Params? ~(ruleDescr? "=" | ":=" | "+=") -- application
141
+ | oneCharTerminal ".." oneCharTerminal -- range
142
+ | terminal -- terminal
143
+ | "(" Alt ")" -- paren
144
+
145
+ ruleDescr (a rule description)
146
+ = "(" ruleDescrText ")"
147
+
148
+ ruleDescrText
149
+ = (~")" any)*
150
+
151
+ caseName
152
+ = "--" (~"\\n" space)* name (~"\\n" space)* ("\\n" | &"}")
153
+
154
+ name (a name)
155
+ = nameFirst nameRest*
156
+
157
+ nameFirst
158
+ = "_"
159
+ | letter
160
+
161
+ nameRest
162
+ = "_"
163
+ | alnum
164
+
165
+ ident (an identifier)
166
+ = name
167
+
168
+ terminal
169
+ = "\\"" terminalChar* "\\""
170
+
171
+ oneCharTerminal
172
+ = "\\"" terminalChar "\\""
173
+
174
+ terminalChar
175
+ = escapeChar
176
+ | ~"\\\\" ~"\\"" ~"\\n" "\\u{0}".."\\u{10FFFF}"
177
+
178
+ escapeChar (an escape sequence)
179
+ = "\\\\\\\\" -- backslash
180
+ | "\\\\\\"" -- doubleQuote
181
+ | "\\\\\\'" -- singleQuote
182
+ | "\\\\b" -- backspace
183
+ | "\\\\n" -- lineFeed
184
+ | "\\\\r" -- carriageReturn
185
+ | "\\\\t" -- tab
186
+ | "\\\\u{" hexDigit hexDigit? hexDigit?
187
+ hexDigit? hexDigit? hexDigit? "}" -- unicodeCodePoint
188
+ | "\\\\u" hexDigit hexDigit hexDigit hexDigit -- unicodeEscape
189
+ | "\\\\x" hexDigit hexDigit -- hexEscape
190
+
191
+ space
192
+ += comment
193
+
194
+ comment
195
+ = "//" (~"\\n" any)* &("\\n" | end) -- singleLine
196
+ | "/*" (~"*/" any)* "*/" -- multiLine
197
+
198
+ tokens = token*
199
+
200
+ token = caseName | comment | ident | operator | punctuation | terminal | any
201
+
202
+ operator = "<:" | "=" | ":=" | "+=" | "*" | "+" | "?" | "~" | "&"
203
+
204
+ punctuation = "<" | ">" | "," | "--"
205
+ }`},"Ohm",null,"Grammars",{Grammars:["define",{sourceInterval:[9,32]},null,[],["star",{sourceInterval:[24,32]},["app",{sourceInterval:[24,31]},"Grammar",[]]]],Grammar:["define",{sourceInterval:[36,83]},null,[],["seq",{sourceInterval:[50,83]},["app",{sourceInterval:[50,55]},"ident",[]],["opt",{sourceInterval:[56,69]},["app",{sourceInterval:[56,68]},"SuperGrammar",[]]],["terminal",{sourceInterval:[70,73]},"{"],["star",{sourceInterval:[74,79]},["app",{sourceInterval:[74,78]},"Rule",[]]],["terminal",{sourceInterval:[80,83]},"}"]]],SuperGrammar:["define",{sourceInterval:[87,116]},null,[],["seq",{sourceInterval:[106,116]},["terminal",{sourceInterval:[106,110]},"<:"],["app",{sourceInterval:[111,116]},"ident",[]]]],Rule_define:["define",{sourceInterval:[131,181]},null,[],["seq",{sourceInterval:[131,170]},["app",{sourceInterval:[131,136]},"ident",[]],["opt",{sourceInterval:[137,145]},["app",{sourceInterval:[137,144]},"Formals",[]]],["opt",{sourceInterval:[146,156]},["app",{sourceInterval:[146,155]},"ruleDescr",[]]],["terminal",{sourceInterval:[157,160]},"="],["app",{sourceInterval:[162,170]},"RuleBody",[]]]],Rule_override:["define",{sourceInterval:[188,248]},null,[],["seq",{sourceInterval:[188,235]},["app",{sourceInterval:[188,193]},"ident",[]],["opt",{sourceInterval:[194,202]},["app",{sourceInterval:[194,201]},"Formals",[]]],["terminal",{sourceInterval:[214,218]},":="],["app",{sourceInterval:[219,235]},"OverrideRuleBody",[]]]],Rule_extend:["define",{sourceInterval:[255,305]},null,[],["seq",{sourceInterval:[255,294]},["app",{sourceInterval:[255,260]},"ident",[]],["opt",{sourceInterval:[261,269]},["app",{sourceInterval:[261,268]},"Formals",[]]],["terminal",{sourceInterval:[281,285]},"+="],["app",{sourceInterval:[286,294]},"RuleBody",[]]]],Rule:["define",{sourceInterval:[120,305]},null,[],["alt",{sourceInterval:[131,305]},["app",{sourceInterval:[131,170]},"Rule_define",[]],["app",{sourceInterval:[188,235]},"Rule_override",[]],["app",{sourceInterval:[255,294]},"Rule_extend",[]]]],RuleBody:["define",{sourceInterval:[309,362]},null,[],["seq",{sourceInterval:[324,362]},["opt",{sourceInterval:[324,328]},["terminal",{sourceInterval:[324,327]},"|"]],["app",{sourceInterval:[329,362]},"NonemptyListOf",[["app",{sourceInterval:[344,356]},"TopLevelTerm",[]],["terminal",{sourceInterval:[358,361]},"|"]]]]],TopLevelTerm_inline:["define",{sourceInterval:[385,408]},null,[],["seq",{sourceInterval:[385,397]},["app",{sourceInterval:[385,388]},"Seq",[]],["app",{sourceInterval:[389,397]},"caseName",[]]]],TopLevelTerm:["define",{sourceInterval:[366,418]},null,[],["alt",{sourceInterval:[385,418]},["app",{sourceInterval:[385,397]},"TopLevelTerm_inline",[]],["app",{sourceInterval:[415,418]},"Seq",[]]]],OverrideRuleBody:["define",{sourceInterval:[422,491]},null,[],["seq",{sourceInterval:[445,491]},["opt",{sourceInterval:[445,449]},["terminal",{sourceInterval:[445,448]},"|"]],["app",{sourceInterval:[450,491]},"NonemptyListOf",[["app",{sourceInterval:[465,485]},"OverrideTopLevelTerm",[]],["terminal",{sourceInterval:[487,490]},"|"]]]]],OverrideTopLevelTerm_superSplice:["define",{sourceInterval:[522,543]},null,[],["terminal",{sourceInterval:[522,527]},"..."]],OverrideTopLevelTerm:["define",{sourceInterval:[495,562]},null,[],["alt",{sourceInterval:[522,562]},["app",{sourceInterval:[522,527]},"OverrideTopLevelTerm_superSplice",[]],["app",{sourceInterval:[550,562]},"TopLevelTerm",[]]]],Formals:["define",{sourceInterval:[566,606]},null,[],["seq",{sourceInterval:[580,606]},["terminal",{sourceInterval:[580,583]},"<"],["app",{sourceInterval:[584,602]},"ListOf",[["app",{sourceInterval:[591,596]},"ident",[]],["terminal",{sourceInterval:[598,601]},","]]],["terminal",{sourceInterval:[603,606]},">"]]],Params:["define",{sourceInterval:[610,647]},null,[],["seq",{sourceInterval:[623,647]},["terminal",{sourceInterval:[623,626]},"<"],["app",{sourceInterval:[627,643]},"ListOf",[["app",{sourceInterval:[634,637]},"Seq",[]],["terminal",{sourceInterval:[639,642]},","]]],["terminal",{sourceInterval:[644,647]},">"]]],Alt:["define",{sourceInterval:[651,685]},null,[],["app",{sourceInterval:[661,685]},"NonemptyListOf",[["app",{sourceInterval:[676,679]},"Seq",[]],["terminal",{sourceInterval:[681,684]},"|"]]]],Seq:["define",{sourceInterval:[689,704]},null,[],["star",{sourceInterval:[699,704]},["app",{sourceInterval:[699,703]},"Iter",[]]]],Iter_star:["define",{sourceInterval:[719,736]},null,[],["seq",{sourceInterval:[719,727]},["app",{sourceInterval:[719,723]},"Pred",[]],["terminal",{sourceInterval:[724,727]},"*"]]],Iter_plus:["define",{sourceInterval:[743,760]},null,[],["seq",{sourceInterval:[743,751]},["app",{sourceInterval:[743,747]},"Pred",[]],["terminal",{sourceInterval:[748,751]},"+"]]],Iter_opt:["define",{sourceInterval:[767,783]},null,[],["seq",{sourceInterval:[767,775]},["app",{sourceInterval:[767,771]},"Pred",[]],["terminal",{sourceInterval:[772,775]},"?"]]],Iter:["define",{sourceInterval:[708,794]},null,[],["alt",{sourceInterval:[719,794]},["app",{sourceInterval:[719,727]},"Iter_star",[]],["app",{sourceInterval:[743,751]},"Iter_plus",[]],["app",{sourceInterval:[767,775]},"Iter_opt",[]],["app",{sourceInterval:[790,794]},"Pred",[]]]],Pred_not:["define",{sourceInterval:[809,824]},null,[],["seq",{sourceInterval:[809,816]},["terminal",{sourceInterval:[809,812]},"~"],["app",{sourceInterval:[813,816]},"Lex",[]]]],Pred_lookahead:["define",{sourceInterval:[831,852]},null,[],["seq",{sourceInterval:[831,838]},["terminal",{sourceInterval:[831,834]},"&"],["app",{sourceInterval:[835,838]},"Lex",[]]]],Pred:["define",{sourceInterval:[798,862]},null,[],["alt",{sourceInterval:[809,862]},["app",{sourceInterval:[809,816]},"Pred_not",[]],["app",{sourceInterval:[831,838]},"Pred_lookahead",[]],["app",{sourceInterval:[859,862]},"Lex",[]]]],Lex_lex:["define",{sourceInterval:[876,892]},null,[],["seq",{sourceInterval:[876,884]},["terminal",{sourceInterval:[876,879]},"#"],["app",{sourceInterval:[880,884]},"Base",[]]]],Lex:["define",{sourceInterval:[866,903]},null,[],["alt",{sourceInterval:[876,903]},["app",{sourceInterval:[876,884]},"Lex_lex",[]],["app",{sourceInterval:[899,903]},"Base",[]]]],Base_application:["define",{sourceInterval:[918,979]},null,[],["seq",{sourceInterval:[918,963]},["app",{sourceInterval:[918,923]},"ident",[]],["opt",{sourceInterval:[924,931]},["app",{sourceInterval:[924,930]},"Params",[]]],["not",{sourceInterval:[932,963]},["alt",{sourceInterval:[934,962]},["seq",{sourceInterval:[934,948]},["opt",{sourceInterval:[934,944]},["app",{sourceInterval:[934,943]},"ruleDescr",[]]],["terminal",{sourceInterval:[945,948]},"="]],["terminal",{sourceInterval:[951,955]},":="],["terminal",{sourceInterval:[958,962]},"+="]]]]],Base_range:["define",{sourceInterval:[986,1041]},null,[],["seq",{sourceInterval:[986,1022]},["app",{sourceInterval:[986,1001]},"oneCharTerminal",[]],["terminal",{sourceInterval:[1002,1006]},".."],["app",{sourceInterval:[1007,1022]},"oneCharTerminal",[]]]],Base_terminal:["define",{sourceInterval:[1048,1106]},null,[],["app",{sourceInterval:[1048,1056]},"terminal",[]]],Base_paren:["define",{sourceInterval:[1113,1168]},null,[],["seq",{sourceInterval:[1113,1124]},["terminal",{sourceInterval:[1113,1116]},"("],["app",{sourceInterval:[1117,1120]},"Alt",[]],["terminal",{sourceInterval:[1121,1124]},")"]]],Base:["define",{sourceInterval:[907,1168]},null,[],["alt",{sourceInterval:[918,1168]},["app",{sourceInterval:[918,963]},"Base_application",[]],["app",{sourceInterval:[986,1022]},"Base_range",[]],["app",{sourceInterval:[1048,1056]},"Base_terminal",[]],["app",{sourceInterval:[1113,1124]},"Base_paren",[]]]],ruleDescr:["define",{sourceInterval:[1172,1231]},"a rule description",[],["seq",{sourceInterval:[1210,1231]},["terminal",{sourceInterval:[1210,1213]},"("],["app",{sourceInterval:[1214,1227]},"ruleDescrText",[]],["terminal",{sourceInterval:[1228,1231]},")"]]],ruleDescrText:["define",{sourceInterval:[1235,1266]},null,[],["star",{sourceInterval:[1255,1266]},["seq",{sourceInterval:[1256,1264]},["not",{sourceInterval:[1256,1260]},["terminal",{sourceInterval:[1257,1260]},")"]],["app",{sourceInterval:[1261,1264]},"any",[]]]]],caseName:["define",{sourceInterval:[1270,1338]},null,[],["seq",{sourceInterval:[1285,1338]},["terminal",{sourceInterval:[1285,1289]},"--"],["star",{sourceInterval:[1290,1304]},["seq",{sourceInterval:[1291,1302]},["not",{sourceInterval:[1291,1296]},["terminal",{sourceInterval:[1292,1296]},`
206
+ `]],["app",{sourceInterval:[1297,1302]},"space",[]]]],["app",{sourceInterval:[1305,1309]},"name",[]],["star",{sourceInterval:[1310,1324]},["seq",{sourceInterval:[1311,1322]},["not",{sourceInterval:[1311,1316]},["terminal",{sourceInterval:[1312,1316]},`
207
+ `]],["app",{sourceInterval:[1317,1322]},"space",[]]]],["alt",{sourceInterval:[1326,1337]},["terminal",{sourceInterval:[1326,1330]},`
208
+ `],["lookahead",{sourceInterval:[1333,1337]},["terminal",{sourceInterval:[1334,1337]},"}"]]]]],name:["define",{sourceInterval:[1342,1382]},"a name",[],["seq",{sourceInterval:[1363,1382]},["app",{sourceInterval:[1363,1372]},"nameFirst",[]],["star",{sourceInterval:[1373,1382]},["app",{sourceInterval:[1373,1381]},"nameRest",[]]]]],nameFirst:["define",{sourceInterval:[1386,1418]},null,[],["alt",{sourceInterval:[1402,1418]},["terminal",{sourceInterval:[1402,1405]},"_"],["app",{sourceInterval:[1412,1418]},"letter",[]]]],nameRest:["define",{sourceInterval:[1422,1452]},null,[],["alt",{sourceInterval:[1437,1452]},["terminal",{sourceInterval:[1437,1440]},"_"],["app",{sourceInterval:[1447,1452]},"alnum",[]]]],ident:["define",{sourceInterval:[1456,1489]},"an identifier",[],["app",{sourceInterval:[1485,1489]},"name",[]]],terminal:["define",{sourceInterval:[1493,1531]},null,[],["seq",{sourceInterval:[1508,1531]},["terminal",{sourceInterval:[1508,1512]},'"'],["star",{sourceInterval:[1513,1526]},["app",{sourceInterval:[1513,1525]},"terminalChar",[]]],["terminal",{sourceInterval:[1527,1531]},'"']]],oneCharTerminal:["define",{sourceInterval:[1535,1579]},null,[],["seq",{sourceInterval:[1557,1579]},["terminal",{sourceInterval:[1557,1561]},'"'],["app",{sourceInterval:[1562,1574]},"terminalChar",[]],["terminal",{sourceInterval:[1575,1579]},'"']]],terminalChar:["define",{sourceInterval:[1583,1660]},null,[],["alt",{sourceInterval:[1602,1660]},["app",{sourceInterval:[1602,1612]},"escapeChar",[]],["seq",{sourceInterval:[1621,1660]},["not",{sourceInterval:[1621,1626]},["terminal",{sourceInterval:[1622,1626]},"\\"]],["not",{sourceInterval:[1627,1632]},["terminal",{sourceInterval:[1628,1632]},'"']],["not",{sourceInterval:[1633,1638]},["terminal",{sourceInterval:[1634,1638]},`
209
+ `]],["range",{sourceInterval:[1639,1660]},"\0","􏿿"]]]],escapeChar_backslash:["define",{sourceInterval:[1703,1758]},null,[],["terminal",{sourceInterval:[1703,1709]},"\\\\"]],escapeChar_doubleQuote:["define",{sourceInterval:[1765,1822]},null,[],["terminal",{sourceInterval:[1765,1771]},'\\"']],escapeChar_singleQuote:["define",{sourceInterval:[1829,1886]},null,[],["terminal",{sourceInterval:[1829,1835]},"\\'"]],escapeChar_backspace:["define",{sourceInterval:[1893,1948]},null,[],["terminal",{sourceInterval:[1893,1898]},"\\b"]],escapeChar_lineFeed:["define",{sourceInterval:[1955,2009]},null,[],["terminal",{sourceInterval:[1955,1960]},"\\n"]],escapeChar_carriageReturn:["define",{sourceInterval:[2016,2076]},null,[],["terminal",{sourceInterval:[2016,2021]},"\\r"]],escapeChar_tab:["define",{sourceInterval:[2083,2132]},null,[],["terminal",{sourceInterval:[2083,2088]},"\\t"]],escapeChar_unicodeCodePoint:["define",{sourceInterval:[2139,2243]},null,[],["seq",{sourceInterval:[2139,2221]},["terminal",{sourceInterval:[2139,2145]},"\\u{"],["app",{sourceInterval:[2146,2154]},"hexDigit",[]],["opt",{sourceInterval:[2155,2164]},["app",{sourceInterval:[2155,2163]},"hexDigit",[]]],["opt",{sourceInterval:[2165,2174]},["app",{sourceInterval:[2165,2173]},"hexDigit",[]]],["opt",{sourceInterval:[2188,2197]},["app",{sourceInterval:[2188,2196]},"hexDigit",[]]],["opt",{sourceInterval:[2198,2207]},["app",{sourceInterval:[2198,2206]},"hexDigit",[]]],["opt",{sourceInterval:[2208,2217]},["app",{sourceInterval:[2208,2216]},"hexDigit",[]]],["terminal",{sourceInterval:[2218,2221]},"}"]]],escapeChar_unicodeEscape:["define",{sourceInterval:[2250,2309]},null,[],["seq",{sourceInterval:[2250,2291]},["terminal",{sourceInterval:[2250,2255]},"\\u"],["app",{sourceInterval:[2256,2264]},"hexDigit",[]],["app",{sourceInterval:[2265,2273]},"hexDigit",[]],["app",{sourceInterval:[2274,2282]},"hexDigit",[]],["app",{sourceInterval:[2283,2291]},"hexDigit",[]]]],escapeChar_hexEscape:["define",{sourceInterval:[2316,2371]},null,[],["seq",{sourceInterval:[2316,2339]},["terminal",{sourceInterval:[2316,2321]},"\\x"],["app",{sourceInterval:[2322,2330]},"hexDigit",[]],["app",{sourceInterval:[2331,2339]},"hexDigit",[]]]],escapeChar:["define",{sourceInterval:[1664,2371]},"an escape sequence",[],["alt",{sourceInterval:[1703,2371]},["app",{sourceInterval:[1703,1709]},"escapeChar_backslash",[]],["app",{sourceInterval:[1765,1771]},"escapeChar_doubleQuote",[]],["app",{sourceInterval:[1829,1835]},"escapeChar_singleQuote",[]],["app",{sourceInterval:[1893,1898]},"escapeChar_backspace",[]],["app",{sourceInterval:[1955,1960]},"escapeChar_lineFeed",[]],["app",{sourceInterval:[2016,2021]},"escapeChar_carriageReturn",[]],["app",{sourceInterval:[2083,2088]},"escapeChar_tab",[]],["app",{sourceInterval:[2139,2221]},"escapeChar_unicodeCodePoint",[]],["app",{sourceInterval:[2250,2291]},"escapeChar_unicodeEscape",[]],["app",{sourceInterval:[2316,2339]},"escapeChar_hexEscape",[]]]],space:["extend",{sourceInterval:[2375,2394]},null,[],["app",{sourceInterval:[2387,2394]},"comment",[]]],comment_singleLine:["define",{sourceInterval:[2412,2458]},null,[],["seq",{sourceInterval:[2412,2443]},["terminal",{sourceInterval:[2412,2416]},"//"],["star",{sourceInterval:[2417,2429]},["seq",{sourceInterval:[2418,2427]},["not",{sourceInterval:[2418,2423]},["terminal",{sourceInterval:[2419,2423]},`
210
+ `]],["app",{sourceInterval:[2424,2427]},"any",[]]]],["lookahead",{sourceInterval:[2430,2443]},["alt",{sourceInterval:[2432,2442]},["terminal",{sourceInterval:[2432,2436]},`
211
+ `],["app",{sourceInterval:[2439,2442]},"end",[]]]]]],comment_multiLine:["define",{sourceInterval:[2465,2501]},null,[],["seq",{sourceInterval:[2465,2487]},["terminal",{sourceInterval:[2465,2469]},"/*"],["star",{sourceInterval:[2470,2482]},["seq",{sourceInterval:[2471,2480]},["not",{sourceInterval:[2471,2476]},["terminal",{sourceInterval:[2472,2476]},"*/"]],["app",{sourceInterval:[2477,2480]},"any",[]]]],["terminal",{sourceInterval:[2483,2487]},"*/"]]],comment:["define",{sourceInterval:[2398,2501]},null,[],["alt",{sourceInterval:[2412,2501]},["app",{sourceInterval:[2412,2443]},"comment_singleLine",[]],["app",{sourceInterval:[2465,2487]},"comment_multiLine",[]]]],tokens:["define",{sourceInterval:[2505,2520]},null,[],["star",{sourceInterval:[2514,2520]},["app",{sourceInterval:[2514,2519]},"token",[]]]],token:["define",{sourceInterval:[2524,2600]},null,[],["alt",{sourceInterval:[2532,2600]},["app",{sourceInterval:[2532,2540]},"caseName",[]],["app",{sourceInterval:[2543,2550]},"comment",[]],["app",{sourceInterval:[2553,2558]},"ident",[]],["app",{sourceInterval:[2561,2569]},"operator",[]],["app",{sourceInterval:[2572,2583]},"punctuation",[]],["app",{sourceInterval:[2586,2594]},"terminal",[]],["app",{sourceInterval:[2597,2600]},"any",[]]]],operator:["define",{sourceInterval:[2604,2669]},null,[],["alt",{sourceInterval:[2615,2669]},["terminal",{sourceInterval:[2615,2619]},"<:"],["terminal",{sourceInterval:[2622,2625]},"="],["terminal",{sourceInterval:[2628,2632]},":="],["terminal",{sourceInterval:[2635,2639]},"+="],["terminal",{sourceInterval:[2642,2645]},"*"],["terminal",{sourceInterval:[2648,2651]},"+"],["terminal",{sourceInterval:[2654,2657]},"?"],["terminal",{sourceInterval:[2660,2663]},"~"],["terminal",{sourceInterval:[2666,2669]},"&"]]],punctuation:["define",{sourceInterval:[2673,2709]},null,[],["alt",{sourceInterval:[2687,2709]},["terminal",{sourceInterval:[2687,2690]},"<"],["terminal",{sourceInterval:[2693,2696]},">"],["terminal",{sourceInterval:[2699,2702]},","],["terminal",{sourceInterval:[2705,2709]},"--"]]]}]),vn=Object.create(V.prototype);function Ys(t,e){for(const r in t)if(r===e)return!0;return!1}function Ea(t,e,r,n){const s=new Tr(n);let i,a,o,c=!1;return(r||Ss).createSemantics().addOperation("visit",{Grammars(l){return l.children.map(p=>p.visit())},Grammar(l,p,y,v,w){const R=l.visit();i=s.newGrammar(R),p.child(0)&&p.child(0).visit(),v.children.map(k=>k.visit());const C=i.build();if(C.source=this.source.trimmed(),Ys(e,R))throw Vo(C);return e[R]=C,C},SuperGrammar(l,p){const y=p.visit();if(y==="null")i.withSuperGrammar(null);else{if(!e||!Ys(e,y))throw zo(y,e,p.source);i.withSuperGrammar(e[y])}},Rule_define(l,p,y,v,w){a=l.visit(),o=p.children.map(x=>x.visit())[0]||[],!i.defaultStartRule&&i.ensureSuperGrammar()!==Me.ProtoBuiltInRules&&i.withDefaultStartRule(a);const R=w.visit(),C=y.children.map(x=>x.visit())[0],k=this.source.trimmed();return i.define(a,o,R,C,k)},Rule_override(l,p,y,v){a=l.visit(),o=p.children.map(C=>C.visit())[0]||[];const w=this.source.trimmed();i.ensureSuperGrammarRuleForOverriding(a,w),c=!0;const R=v.visit();return c=!1,i.override(a,o,R,null,w)},Rule_extend(l,p,y,v){a=l.visit(),o=p.children.map(C=>C.visit())[0]||[];const w=v.visit(),R=this.source.trimmed();return i.extend(a,o,w,null,R)},RuleBody(l,p){return s.alt(...p.visit()).withSource(this.source)},OverrideRuleBody(l,p){const y=p.visit(),v=y.indexOf(vn);if(v>=0){const w=y.slice(0,v),R=y.slice(v+1);return R.forEach(C=>{if(C===vn)throw ec(C)}),new on(i.superGrammar,a,w,R).withSource(this.source)}else return s.alt(...y).withSource(this.source)},Formals(l,p,y){return p.visit()},Params(l,p,y){return p.visit()},Alt(l){return s.alt(...l.visit()).withSource(this.source)},TopLevelTerm_inline(l,p){const y=a+"_"+p.visit(),v=l.visit(),w=this.source.trimmed(),R=!(i.superGrammar&&i.superGrammar.rules[y]);c&&!R?i.override(y,o,v,null,w):i.define(y,o,v,null,w);const C=o.map(k=>s.app(k));return s.app(y,C).withSource(v.source)},OverrideTopLevelTerm_superSplice(l){return vn},Seq(l){return s.seq(...l.children.map(p=>p.visit())).withSource(this.source)},Iter_star(l,p){return s.star(l.visit()).withSource(this.source)},Iter_plus(l,p){return s.plus(l.visit()).withSource(this.source)},Iter_opt(l,p){return s.opt(l.visit()).withSource(this.source)},Pred_not(l,p){return s.not(p.visit()).withSource(this.source)},Pred_lookahead(l,p){return s.lookahead(p.visit()).withSource(this.source)},Lex_lex(l,p){return s.lex(p.visit()).withSource(this.source)},Base_application(l,p){const y=p.children.map(v=>v.visit())[0]||[];return s.app(l.visit(),y).withSource(this.source)},Base_range(l,p,y){return s.range(l.visit(),y.visit()).withSource(this.source)},Base_terminal(l){return s.terminal(l.visit()).withSource(this.source)},Base_paren(l,p,y){return p.visit()},ruleDescr(l,p,y){return p.visit()},ruleDescrText(l){return this.sourceString.trim()},caseName(l,p,y,v,w){return y.visit()},name(l,p){return this.sourceString},nameFirst(l){},nameRest(l){},terminal(l,p,y){return p.children.map(v=>v.visit()).join("")},oneCharTerminal(l,p,y){return p.visit()},escapeChar(l){try{return fa(this.sourceString)}catch(p){throw p instanceof RangeError&&p.message.startsWith("Invalid code point ")?tc(l):p}},NonemptyListOf(l,p,y){return[l.visit()].concat(y.children.map(v=>v.visit()))},EmptyListOf(){return[]},_terminal(){return this.sourceString}})(t).visit()}const kc=bs(["grammar",{source:`OperationsAndAttributes {
212
+
213
+ AttributeSignature =
214
+ name
215
+
216
+ OperationSignature =
217
+ name Formals?
218
+
219
+ Formals
220
+ = "(" ListOf<name, ","> ")"
221
+
222
+ name (a name)
223
+ = nameFirst nameRest*
224
+
225
+ nameFirst
226
+ = "_"
227
+ | letter
228
+
229
+ nameRest
230
+ = "_"
231
+ | alnum
232
+
233
+ }`},"OperationsAndAttributes",null,"AttributeSignature",{AttributeSignature:["define",{sourceInterval:[29,58]},null,[],["app",{sourceInterval:[54,58]},"name",[]]],OperationSignature:["define",{sourceInterval:[62,100]},null,[],["seq",{sourceInterval:[87,100]},["app",{sourceInterval:[87,91]},"name",[]],["opt",{sourceInterval:[92,100]},["app",{sourceInterval:[92,99]},"Formals",[]]]]],Formals:["define",{sourceInterval:[104,143]},null,[],["seq",{sourceInterval:[118,143]},["terminal",{sourceInterval:[118,121]},"("],["app",{sourceInterval:[122,139]},"ListOf",[["app",{sourceInterval:[129,133]},"name",[]],["terminal",{sourceInterval:[135,138]},","]]],["terminal",{sourceInterval:[140,143]},")"]]],name:["define",{sourceInterval:[147,187]},"a name",[],["seq",{sourceInterval:[168,187]},["app",{sourceInterval:[168,177]},"nameFirst",[]],["star",{sourceInterval:[178,187]},["app",{sourceInterval:[178,186]},"nameRest",[]]]]],nameFirst:["define",{sourceInterval:[191,223]},null,[],["alt",{sourceInterval:[207,223]},["terminal",{sourceInterval:[207,210]},"_"],["app",{sourceInterval:[217,223]},"letter",[]]]],nameRest:["define",{sourceInterval:[227,257]},null,[],["alt",{sourceInterval:[242,257]},["terminal",{sourceInterval:[242,245]},"_"],["app",{sourceInterval:[252,257]},"alnum",[]]]]}]);Ec(Me.BuiltInRules);Tc(kc);function Ec(t){const e={empty(){return this.iteration()},nonEmpty(r,n,s){return this.iteration([r].concat(s.children))},self(...r){return this}};Pe.BuiltInSemantics=Pe.createSemantics(t,null).addOperation("asIteration",{emptyListOf:e.empty,nonemptyListOf:e.nonEmpty,EmptyListOf:e.empty,NonemptyListOf:e.nonEmpty,_iter:e.self})}function Tc(t){Pe.prototypeGrammarSemantics=t.createSemantics().addOperation("parse",{AttributeSignature(e){return{name:e.parse(),formals:[]}},OperationSignature(e,r){return{name:e.parse(),formals:r.children.map(n=>n.parse())[0]||[]}},Formals(e,r,n){return r.asIteration().children.map(s=>s.parse())},name(e,r){return this.sourceString}}),Pe.prototypeGrammar=t}function Oc(t){let e=0;const r=[0],n=()=>r[r.length-1],s={},i=/( *).*(?:$|\r?\n|\r)/g;let a;for(;(a=i.exec(t))!=null;){const[o,c]=a;if(o.length===0)break;const u=c.length,f=n(),l=e+u;if(u>f)r.push(u),s[l]=1;else if(u<f){const p=r.length;for(;n()!==u;)r.pop();s[l]=-1*(p-r.length)}e+=o.length}return r.length>1&&(s[e]=1-r.length),s}const Ta="an indented block",Oa="a dedent",Qs=1114112;class Cc extends cn{constructor(e){super(e.input),this.state=e}_indentationAt(e){return this.state.userData[e]||0}atEnd(){return super.atEnd()&&this._indentationAt(this.pos)===0}next(){if(this._indentationAt(this.pos)!==0){this.examinedLength=Math.max(this.examinedLength,this.pos);return}return super.next()}nextCharCode(){return this._indentationAt(this.pos)!==0?(this.examinedLength=Math.max(this.examinedLength,this.pos),Qs):super.nextCharCode()}nextCodePoint(){return this._indentationAt(this.pos)!==0?(this.examinedLength=Math.max(this.examinedLength,this.pos),Qs):super.nextCodePoint()}}class Xs extends V{constructor(e=!0){super(),this.isIndent=e}allowsSkippingPrecedingSpace(){return!0}eval(e){const{inputStream:r}=e,n=e.userData;e.doNotMemoize=!0;const s=r.pos,i=this.isIndent?1:-1;return(n[s]||0)*i>0?(e.userData=Object.create(n),e.userData[s]-=i,e.pushBinding(new jt(0),s),!0):(e.processFailure(s,this),!1)}getArity(){return 1}_assertAllApplicationsAreValid(e,r){}_isNullable(e,r){return!1}assertChoicesHaveUniformArity(e){}assertIteratedExprsAreNotNullable(e){}introduceParams(e){return this}substituteParams(e){return this}toString(){return this.isIndent?"indent":"dedent"}toDisplayString(){return this.toString()}toFailure(e){const r=this.isIndent?Ta:Oa;return new Ue(this,r,"description")}}const Rc=new X("indent"),Nc=new X("dedent"),Lc=new on(ws,"any",[Rc,Nc],[]),Mc=new Tr().newGrammar("IndentationSensitive").withSuperGrammar(ws).define("indent",[],new Xs(!0),Ta,void 0,!0).define("dedent",[],new Xs(!1),Oa,void 0,!0).extend("any",[],Lc,"any character",void 0).build();Object.assign(Mc,{_matchStateInitializer(t){t.userData=Oc(t.input),t.inputStream=new Cc(t)},supportsIncrementalParsing:!1});Me.initApplicationParser(Ss,Ea);const Dc=t=>!!t.constructor&&typeof t.constructor.isBuffer=="function"&&t.constructor.isBuffer(t);function Fc(t,e,r){const n=Ss.match(t,"Grammars");if(n.failed())throw Bo(n);return Ea(n,e,void 0,r)}function jc(t,e,r){const n=qc(t,e,r),s=Object.keys(n);if(s.length===0)throw new Error("Missing grammar definition");if(s.length>1){const a=n[s[1]].source;throw new Error(ms(a.sourceString,a.startIdx)+"Found more than one grammar definition -- use ohm.grammars() instead.")}return n[s[0]]}function qc(t,e,r){const n=Object.create({});if(typeof t!="string")if(Dc(t))t=t.toString();else throw new TypeError("Expected string as first argument, got "+fs(t));return Fc(t,n,r),n}function Pc(t,e){return jc(t,e)}const $c=`FirestoreRules {
234
+ // === Top-level ===
235
+ // Syntactic rules (capitalized) auto-skip spaces between terms.
236
+ // Lexical rules (lowercase) do NOT skip spaces.
237
+
238
+ // Two accepted orderings. Real \`firestore.rules\` files put
239
+ // \`rules_version\` at line 1 (Firebase convention), so the
240
+ // \`versionFirst\` branch matches that natural shape. The
241
+ // \`importsFirst\` branch keeps legacy samples that put \`import\`
242
+ // declarations above the version line working. The semantic
243
+ // action below normalizes both into the same AST shape, so
244
+ // downstream code doesn't have to care which path matched.
245
+ // Declaration order is STRICT: imports, then functions (#347 probe,
246
+ // 2026-07-17): the production Rules Test API rejects \`import\` after a
247
+ // \`function\` ("Unexpected 'import'") and any declaration before
248
+ // \`rules_version\` ("Unexpected 'rules_version'"), under both
249
+ // rules_version '2' and '2+modules'. Pinned by
250
+ // test/rules/corpus/invalid/009-/010-.
251
+ RulesFile = RulesVersion? ImportDecl* FunctionDef* ServiceBlock -- versionFirst
252
+ | ImportDecl* RulesVersion FunctionDef* ServiceBlock -- importsFirst
253
+
254
+ ImportDecl = "import" "{" ListOf<ident, ","> ","? "}" "from" string ";"
255
+
256
+ RulesVersion = "rules_version" "=" string ";"
257
+
258
+ ServiceBlock = "service" serviceName "{" FunctionDef* DocumentsMatch FunctionDef* "}"
259
+
260
+ DocumentsMatch = "match" matchPath "{" MatchBody "}"
261
+
262
+ MatchBody = MatchBodyItem*
263
+
264
+ MatchBodyItem
265
+ = FunctionDef
266
+ | MatchBlock
267
+ | AllowStatement
268
+
269
+ MatchBlock = "match" matchPath "{" MatchBody "}"
270
+
271
+ // === Statements ===
272
+
273
+ AllowStatement = "allow" OperationList ":" "if" Expr ";"
274
+
275
+ OperationList = Operation ("," Operation)*
276
+
277
+ FunctionDef = "export"? "function" ident "(" ParameterList ")" "{" FunctionBody "}"
278
+
279
+ ParameterList = ListOf<ident, ",">
280
+
281
+ FunctionBody = LetBinding* ReturnStatement
282
+
283
+ LetBinding = "let" ident "=" Expr ";"
284
+
285
+ ReturnStatement = "return" Expr ";"
286
+
287
+ // === Lexical: operations and service name ===
288
+
289
+ Operation
290
+ = "read" ~identChar
291
+ | "write" ~identChar
292
+ | "get" ~identChar
293
+ | "list" ~identChar
294
+ | "create" ~identChar
295
+ | "update" ~identChar
296
+ | "delete" ~identChar
297
+
298
+ serviceName = letter (letter | ".")*
299
+
300
+ // === Lexical: match paths ===
301
+
302
+ matchPath = "/" matchPathSegment ("/" matchPathSegment)*
303
+
304
+ matchPathSegment
305
+ = "{" matchWildcard "}" -- wildcard
306
+ | pathIdent -- literal
307
+
308
+ matchWildcard
309
+ = identStart identChar* "=" "**" -- recursive
310
+ | identStart identChar* -- single
311
+
312
+ pathIdent = (letter | digit | "_" | "-" | ".")+
313
+
314
+ // === Expressions ===
315
+
316
+ Expr = Ternary
317
+
318
+ Ternary
319
+ = LogicalOr "?" Ternary ":" Ternary -- ternary
320
+ | LogicalOr
321
+
322
+ LogicalOr
323
+ = LogicalOr "||" LogicalAnd -- or
324
+ | LogicalAnd
325
+
326
+ LogicalAnd
327
+ = LogicalAnd "&&" InIsExpr -- and
328
+ | InIsExpr
329
+
330
+ InIsExpr
331
+ = Equality in Equality -- in
332
+ | Equality is typeName -- is
333
+ | Equality
334
+
335
+ in = "in" ~identChar
336
+ is = "is" ~identChar
337
+
338
+ Equality
339
+ = Equality "==" Comparison -- eq
340
+ | Equality "!=" Comparison -- neq
341
+ | Comparison
342
+
343
+ Comparison
344
+ = Comparison ">=" Additive -- gte
345
+ | Comparison "<=" Additive -- lte
346
+ | Comparison ">" Additive -- gt
347
+ | Comparison "<" Additive -- lt
348
+ | Additive
349
+
350
+ Additive
351
+ = Additive "+" Multiplicative -- add
352
+ | Additive "-" Multiplicative -- sub
353
+ | Multiplicative
354
+
355
+ Multiplicative
356
+ = Multiplicative "*" UnaryExpr -- mul
357
+ | Multiplicative "/" UnaryExpr -- div
358
+ | Multiplicative "%" UnaryExpr -- mod
359
+ | UnaryExpr
360
+
361
+ UnaryExpr
362
+ = "!" UnaryExpr -- not
363
+ | "-" UnaryExpr -- neg
364
+ | PostfixExpr
365
+
366
+ PostfixExpr
367
+ = PostfixExpr "." memberName "(" ListOf<Expr, ","> ")" -- methodCall
368
+ | PostfixExpr "." memberName -- memberAccess
369
+ | PostfixExpr "[" Expr ":" Expr "]" -- sliceAccess
370
+ | PostfixExpr "[" Expr "]" -- bracketAccess
371
+ | Primary
372
+
373
+ memberName = identStart identChar*
374
+
375
+ Primary
376
+ = "(" Expr ")" -- paren
377
+ | PathLiteral -- path
378
+ | ListLiteral -- list
379
+ | MapLiteral -- map
380
+ | ident "(" ListOf<Expr, ","> ")" -- functionCall
381
+ | literal
382
+ | ident
383
+
384
+ // === Path literals ===
385
+
386
+ PathLiteral = "/" PathLitSegment ("/" PathLitSegment)*
387
+
388
+ PathLitSegment
389
+ = "$(" Expr ")" -- interpolation
390
+ | "{" ident "}" -- captureRef
391
+ | "(" pathIdent ")" -- parenLiteral
392
+ | pathIdent -- literal
393
+
394
+ // === Literals ===
395
+
396
+ literal
397
+ = number
398
+ | string
399
+ | bool
400
+ | null
401
+
402
+ number
403
+ = digit+ "." digit+ -- float
404
+ | digit+ -- int
405
+
406
+ string
407
+ = "'" singleStringChar* "'" -- single
408
+ | "\\"" doubleStringChar* "\\"" -- double
409
+
410
+ singleStringChar
411
+ = "\\\\" stringEscapeChar -- escape
412
+ | ~"\\\\" ~"'" any -- char
413
+
414
+ doubleStringChar
415
+ = "\\\\" stringEscapeChar -- escape
416
+ | ~"\\\\" ~"\\"" any -- char
417
+
418
+ // Valid escape characters following a backslash. Anything else is rejected
419
+ // at parse time to match production semantics — production Firestore Rules
420
+ // raises a syntax error on unknown escapes (e.g. \`\\d\`, \`\\.\`). Keeping the
421
+ // sim strict here prevents over-permissive acceptance that masks model
422
+ // output that would crash at deploy.
423
+ stringEscapeChar = "\\\\" | "'" | "\\"" | "n" | "r" | "t" | "/"
424
+
425
+ ListLiteral = "[" ListOf<Expr, ","> ","? "]"
426
+
427
+ MapLiteral = "{" ListOf<MapEntry, ","> ","? "}"
428
+
429
+ MapEntry = (string | ident) ":" Expr
430
+
431
+ bool
432
+ = "true" ~identChar -- true
433
+ | "false" ~identChar -- false
434
+
435
+ null = "null" ~identChar
436
+
437
+ typeName
438
+ = "string" ~identChar
439
+ | "int" ~identChar
440
+ | "float" ~identChar
441
+ | "number" ~identChar
442
+ | "bool" ~identChar
443
+ | "list" ~identChar
444
+ | "map" ~identChar
445
+ | "timestamp" ~identChar
446
+ | "path" ~identChar
447
+ | "bytes" ~identChar
448
+ | "duration" ~identChar
449
+ | "latlng" ~identChar
450
+ | "reference" ~identChar
451
+
452
+ ident = ~keyword identStart identChar*
453
+
454
+ keyword
455
+ = ("true" | "false" | "null" | "in" | "is" | "if" | "return" | "let") ~identChar
456
+
457
+ identStart = letter | "_"
458
+
459
+ identChar = alnum | "_"
460
+
461
+ // === Whitespace and comments ===
462
+
463
+ space += comment
464
+
465
+ comment
466
+ = "//" (~"\\n" any)* &("\\n" | end) -- singleLine
467
+ | "/*" (~"*/" any)* "*/" -- multiLine
468
+ }
469
+ `,Ca=Pc($c),Ra=Ca.createSemantics();Ra.addOperation("toAST",{RulesFile_versionFirst(t,e,r,n){return{imports:e.children.map(s=>s.toAST()),version:t.children.length>0?t.children[0].toAST():"1",functions:r.children.map(s=>s.toAST()),service:n.toAST()}},RulesFile_importsFirst(t,e,r,n){return{imports:t.children.map(s=>s.toAST()),version:e.toAST(),functions:r.children.map(s=>s.toAST()),service:n.toAST()}},ImportDecl(t,e,r,n,s,i,a,o){const{lineNum:c,colNum:u}=t.source.getLineAndColumn();return{functions:r.asIteration().children.map(f=>f.sourceString),module:a.toAST().value,loc:{line:c,col:u}}},RulesVersion(t,e,r,n){return r.toAST().value},ServiceBlock(t,e,r,n,s,i,a){const{lineNum:o,colNum:c}=t.source.getLineAndColumn();return{name:e.sourceString,functions:[...n.children.map(u=>u.toAST()),...i.children.map(u=>u.toAST())],match:s.toAST(),loc:{line:o,col:c}}},DocumentsMatch(t,e,r,n,s){const{lineNum:i,colNum:a}=t.source.getLineAndColumn();return{...n.toAST(),path:ti(e.sourceString),loc:{line:i,col:a}}},MatchBody(t){const e=[],r=[],n=[];for(const s of t.children){const i=s.toAST();i._kind==="function"?e.push(i):i._kind==="allow"?r.push(i):i._kind==="match"&&n.push(i)}return{functions:e,allows:r,children:n}},MatchBodyItem(t){return t.toAST()},MatchBlock(t,e,r,n,s){const{functions:i,allows:a,children:o}=n.toAST(),{lineNum:c,colNum:u}=t.source.getLineAndColumn();return{_kind:"match",path:ti(e.sourceString),functions:i,allows:a,children:o,loc:{line:c,col:u}}},AllowStatement(t,e,r,n,s,i){const{lineNum:a,colNum:o}=t.source.getLineAndColumn();return{_kind:"allow",operations:e.toAST(),condition:s.toAST(),loc:{line:a,col:o}}},OperationList(t,e,r){return[t.toAST(),...r.children.map(n=>n.toAST())]},Operation(t){return t.sourceString},FunctionDef(t,e,r,n,s,i,a,o,c){const{lets:u,expr:f}=o.toAST(),{lineNum:l,colNum:p}=e.source.getLineAndColumn();let y=!1;return t.sourceString.trim()==="export"&&(y=!0),{_kind:"function",name:r.sourceString,parameters:s.toAST(),exported:y,lets:u,body:f,loc:{line:l,col:p}}},ParameterList(t){return t.asIteration().children.map(e=>e.sourceString)},FunctionBody(t,e){return{lets:t.children.map(r=>r.toAST()),expr:e.toAST()}},LetBinding(t,e,r,n,s){const{lineNum:i,colNum:a}=t.source.getLineAndColumn();return{name:e.sourceString,value:n.toAST(),loc:{line:i,col:a}}},ReturnStatement(t,e,r){return e.toAST()},Expr(t){return t.toAST()},Ternary_ternary(t,e,r,n,s){return{type:"ternary",condition:t.toAST(),consequent:r.toAST(),alternate:s.toAST()}},LogicalOr_or(t,e,r){return{type:"binaryOp",op:"||",left:t.toAST(),right:r.toAST()}},LogicalAnd_and(t,e,r){return{type:"binaryOp",op:"&&",left:t.toAST(),right:r.toAST()}},InIsExpr_in(t,e,r){return{type:"inExpr",element:t.toAST(),collection:r.toAST()}},InIsExpr_is(t,e,r){return{type:"isExpr",value:t.toAST(),typeName:r.sourceString}},Equality_eq(t,e,r){return{type:"binaryOp",op:"==",left:t.toAST(),right:r.toAST()}},Equality_neq(t,e,r){return{type:"binaryOp",op:"!=",left:t.toAST(),right:r.toAST()}},Comparison_gte(t,e,r){return{type:"binaryOp",op:">=",left:t.toAST(),right:r.toAST()}},Comparison_lte(t,e,r){return{type:"binaryOp",op:"<=",left:t.toAST(),right:r.toAST()}},Comparison_gt(t,e,r){return{type:"binaryOp",op:">",left:t.toAST(),right:r.toAST()}},Comparison_lt(t,e,r){return{type:"binaryOp",op:"<",left:t.toAST(),right:r.toAST()}},Additive_add(t,e,r){return{type:"binaryOp",op:"+",left:t.toAST(),right:r.toAST()}},Additive_sub(t,e,r){return{type:"binaryOp",op:"-",left:t.toAST(),right:r.toAST()}},Multiplicative_mul(t,e,r){return{type:"binaryOp",op:"*",left:t.toAST(),right:r.toAST()}},Multiplicative_div(t,e,r){return{type:"binaryOp",op:"/",left:t.toAST(),right:r.toAST()}},Multiplicative_mod(t,e,r){return{type:"binaryOp",op:"%",left:t.toAST(),right:r.toAST()}},UnaryExpr_not(t,e){return{type:"unaryOp",op:"!",operand:e.toAST()}},UnaryExpr_neg(t,e){return{type:"unaryOp",op:"-",operand:e.toAST()}},PostfixExpr_methodCall(t,e,r,n,s,i){return{type:"methodCall",object:t.toAST(),method:r.sourceString,args:s.asIteration().children.map(a=>a.toAST())}},PostfixExpr_memberAccess(t,e,r){return{type:"memberAccess",object:t.toAST(),property:r.sourceString}},PostfixExpr_bracketAccess(t,e,r,n){return{type:"bracketAccess",object:t.toAST(),index:r.toAST()}},PostfixExpr_sliceAccess(t,e,r,n,s,i){return{type:"sliceAccess",object:t.toAST(),start:r.toAST(),end:s.toAST()}},Primary_paren(t,e,r){return e.toAST()},Primary_path(t){return t.toAST()},Primary_list(t){return t.toAST()},Primary_map(t){return t.toAST()},Primary_functionCall(t,e,r,n){return{type:"functionCall",name:t.sourceString,args:r.asIteration().children.map(s=>s.toAST())}},PathLiteral(t,e,r,n){const s=[e.toAST()];for(const i of n.children)s.push(i.toAST());return{type:"pathLiteral",raw:this.sourceString,segments:s}},PathLitSegment_interpolation(t,e,r){return e.toAST()},PathLitSegment_captureRef(t,e,r){return`{${e.sourceString}}`},PathLitSegment_parenLiteral(t,e,r){return`(${e.sourceString})`},PathLitSegment_literal(t){return t.sourceString},ListLiteral(t,e,r,n){return{type:"listLiteral",elements:e.asIteration().children.map(s=>s.toAST())}},MapLiteral(t,e,r,n){return{type:"mapLiteral",entries:e.asIteration().children.map(s=>s.toAST())}},MapEntry(t,e,r){return{key:t.toAST(),value:r.toAST()}},literal(t){return t.toAST()},number_float(t,e,r){return{type:"literal",value:parseFloat(this.sourceString),raw:this.sourceString}},number_int(t){return{type:"literal",value:parseInt(this.sourceString,10),raw:this.sourceString}},string_single(t,e,r){return{type:"literal",value:ei(e.sourceString),raw:this.sourceString}},string_double(t,e,r){return{type:"literal",value:ei(e.sourceString),raw:this.sourceString}},bool_true(t){return{type:"literal",value:!0,raw:"true"}},bool_false(t){return{type:"literal",value:!1,raw:"false"}},null(t){return{type:"literal",value:null,raw:"null"}},ident(t,e){return{type:"identifier",name:this.sourceString}},_nonterminal(...t){return t.length===1?t[0].toAST():t.map(e=>e.toAST())},_terminal(){return this.sourceString}});function ei(t){let e="";for(let r=0;r<t.length;r++){const n=t[r];if(n!=="\\"||r===t.length-1){e+=n;continue}switch(t[r+1]){case"\\":e+="\\",r++;break;case"'":e+="'",r++;break;case'"':e+='"',r++;break;case"n":e+=`
470
+ `,r++;break;case"r":e+="\r",r++;break;case"t":e+=" ",r++;break;case"/":e+="/",r++;break;default:e+=n}}return e}function ti(t){const e=[],r=t.split("/").filter(Boolean);for(const n of r)if(n.startsWith("{")&&n.endsWith("}")){const s=n.slice(1,-1);s.endsWith("=**")?e.push({type:"recursive",name:s.slice(0,-3)}):e.push({type:"wildcard",name:s})}else e.push({type:"literal",value:n});return{raw:t,segments:e}}function Uc(t,e){const r=t.getRightmostFailurePosition?.()??0,n=t.getExpectedText?.()??"";let s=1,i=-1;for(let u=0;u<r&&u<e.length;u++)e.charCodeAt(u)===10&&(s++,i=u);const a=r-i;let o=e.indexOf(`
471
+ `,r);o===-1&&(o=e.length);const c=e.slice(r,Math.min(o,r+40));return{line:s,column:a,offset:r,expected:n,actual:c,message:t.message??"Parse error"}}function _s(t){const e=Or(t);return e.ok?e.ast:null}function Or(t){const e=t.trim();if(!e)return{ok:!1,error:{line:1,column:1,offset:0,expected:"",actual:"",message:"Empty rules file"}};const r=Ca.match(e);if(!r.succeeded())return{ok:!1,error:Uc(r,e)};const n=Ra(r).toAST(),s=t.length-t.trimStart().length;let i=0;for(let o=0;o<s;o++)t.charCodeAt(o)===10&&i++;return i>0&&Bc(n,i),{ok:!0,ast:n}}function Je(t,e){t!==void 0&&(t.line=t.line+e)}function Ar(t,e){Je(t.loc,e);for(const r of t.lets)Je(r.loc,e),Je(r.value.loc,e);Je(t.body.loc,e)}function Bc(t,e){Je(t.loc,e);for(const a of t.imports)Je(a.loc,e);if(t.functions!==void 0)for(const a of t.functions)Ar(a,e);if(Je(t.service.loc,e),t.service.functions!==void 0)for(const a of t.service.functions)Ar(a,e);const s=[t.service.match];let i=s.length;for(;i>0;){const a=s.pop();Je(a.loc,e);for(const o of a.functions)Ar(o,e);for(const o of a.allows)Je(o.loc,e),Je(o.condition.loc,e);for(const o of a.children)s.push(o);i=s.length}}function zc(t,e){t.loc!==void 0&&(t.loc.file=e);for(const s of t.lets)s.loc!==void 0&&(s.loc.file=e),s.value.loc!==void 0&&(s.value.loc.file=e);t.body.loc!==void 0&&(t.body.loc.file=e)}function Vc(t,e){const r=`rules_version = '2';
472
+ service cloud.firestore {
473
+ match /databases/{db}/documents {
474
+ ${t}
475
+ }
476
+ }`,n=_s(r);if(n===null)return null;const i=n.service.match.functions;for(const a of i)Ar(a,-3),e!==void 0&&zc(a,e);return i}const Na={"||":2,"&&":3,"==":5,"!=":5,">":6,"<":6,">=":6,"<=":6,"+":7,"-":7,"*":8,"/":8,"%":8};function Hc(t){switch(t.type){case"ternary":return 1;case"binaryOp":return Na[t.op]??0;case"inExpr":return 4;case"isExpr":return 4;case"unaryOp":return 9;default:return 100}}function Wc(t){switch(t.type){case"literal":return typeof t.value=="string"&&t.raw.startsWith('"')&&t.raw.endsWith('"')?`'${t.raw.slice(1,-1)}'`:t.raw;case"identifier":return t.name;case"memberAccess":return`${Ve(t.object,10)}.${t.property}`;case"methodCall":return`${Ve(t.object,10)}.${t.method}(${t.args.map(e=>ye(e)).join(", ")})`;case"bracketAccess":return`${Ve(t.object,10)}[${ye(t.index)}]`;case"sliceAccess":return`${Ve(t.object,10)}[${ye(t.start)}:${ye(t.end)}]`;case"binaryOp":{const e=Na[t.op]??0,r=Ve(t.left,e),n=Ve(t.right,e+1);return`${r} ${t.op} ${n}`}case"unaryOp":return`${t.op}${Ve(t.operand,9)}`;case"ternary":return`${Ve(t.condition,2)} ? ${ye(t.consequent)} : ${ye(t.alternate)}`;case"inExpr":return`${Ve(t.element,5)} in ${Ve(t.collection,5)}`;case"isExpr":return`${Ve(t.value,5)} is ${t.typeName}`;case"listLiteral":return t.elements.length===0?"[]":`[${t.elements.map(e=>ye(e)).join(", ")}]`;case"mapLiteral":return t.entries.length===0?"{}":`{${t.entries.map(e=>`${ye(e.key)}: ${ye(e.value)}`).join(", ")}}`;case"pathLiteral":return"/"+t.segments.map(e=>typeof e=="string"?e:`$(${ye(e)})`).join("/");case"functionCall":return`${t.name}(${t.args.map(e=>ye(e)).join(", ")})`}}function Ve(t,e){const r=Wc(t);return Hc(t)<e?`(${r})`:r}function ye(t){return Ve(t,0)}function Gc(t){return"/"+t.segments.map(e=>{switch(e.type){case"literal":return e.value;case"wildcard":return`{${e.name}}`;case"recursive":return`{${e.name}=**}`}}).join("/")}function Cr(t){return" ".repeat(t)}function Ht(t,e,r,n){if(t!==void 0){let i="firestore.rules";t.file!==void 0&&(i=t.file);const o={generatedLine:e,authoredLine:t.line,authoredCol:t.col,authoredFile:i};n!==void 0&&(o.expression=n),r.push(o)}}function qn(t,e,r,n){const s=Cr(e),i=Cr(e+2),a=t.parameters.join(", ");let o="";t.exported===!0&&(o="export ");const u=r.length+1;r.push(`${s}${o}function ${t.name}(${a}) {`),Ht(t.loc,u,n);for(const l of t.lets){const p=r.length+1;r.push(`${i}let ${l.name} = ${ye(l.value)};`),Ht(l.loc,p,n)}const f=r.length+1;r.push(`${i}return ${ye(t.body)};`),Ht(t.body.loc,f,n),r.push(`${s}}`)}function Kc(t,e,r,n){const s=Cr(e),i=t.operations.join(", "),a=ye(t.condition),o=r.length+1;r.push(`${s}allow ${i}: if ${a};`),Ht(t.loc,o,n,a)}function La(t,e,r,n){const s=Cr(e),i=e+2,a=r.length+1;r.push(`${s}match ${Gc(t.path)} {`),Ht(t.loc,a,n);for(const o of t.functions)qn(o,i,r,n);for(const o of t.allows)Kc(o,i,r,n);for(const o of t.children)La(o,i,r,n);r.push(`${s}}`)}function Pn(t){const e=[],r=[];for(const o of t.imports)e.push(`import { ${o.functions.join(", ")} } from '${o.module}';`);if(e.push(`rules_version = '${t.version}';`),t.functions!==void 0)for(const o of t.functions)qn(o,0,e,r);const s=e.length+1;if(e.push(`service ${t.service.name} {`),Ht(t.service.loc,s,r),t.service.functions!==void 0)for(const o of t.service.functions)qn(o,2,e,r);const a=t.service.match;return La(a,2,e,r),e.push("}"),e.push(""),{resolved:e.join(`
477
+ `),sourceMap:r}}function ri(t){return Pn(t).resolved}const Ir=new Set(["get","exists","getAfter","debug"]);function Rr(t,e){return t.type!=="binaryOp"||t.op!==e?0:1+Rr(t.right,e)}function $n(t){let e={op:"",depth:0};function r(s){if(s.type==="binaryOp"){const i=Rr(s,"&&"),a=Rr(s,"||");i>e.depth&&(e={op:"&&",depth:i}),a>e.depth&&(e={op:"||",depth:a}),r(s.left),r(s.right)}else n(s)}function n(s){switch(s.type){case"unaryOp":r(s.operand);break;case"methodCall":r(s.object),s.args.forEach(r);break;case"memberAccess":r(s.object);break;case"bracketAccess":r(s.object),r(s.index);break;case"ternary":r(s.condition),r(s.consequent),r(s.alternate);break;case"inExpr":r(s.element),r(s.collection);break;case"isExpr":r(s.value);break;case"listLiteral":s.elements.forEach(r);break;case"mapLiteral":s.entries.forEach(i=>{r(i.key),r(i.value)});break;case"functionCall":s.args.forEach(r);break}}return r(t),e}function ie(t){let e=1;switch(t.type){case"binaryOp":e+=ie(t.left)+ie(t.right);break;case"unaryOp":e+=ie(t.operand);break;case"methodCall":e+=ie(t.object);for(const r of t.args)e+=ie(r);break;case"memberAccess":e+=ie(t.object);break;case"bracketAccess":e+=ie(t.object)+ie(t.index);break;case"ternary":e+=ie(t.condition)+ie(t.consequent)+ie(t.alternate);break;case"inExpr":e+=ie(t.element)+ie(t.collection);break;case"isExpr":e+=ie(t.value);break;case"listLiteral":for(const r of t.elements)e+=ie(r);break;case"mapLiteral":for(const r of t.entries)e+=ie(r.key)+ie(r.value);break;case"functionCall":for(const r of t.args)e+=ie(r);break;case"pathLiteral":for(const r of t.segments)typeof r!="string"&&(e+=ie(r));break}return e}function se(t){switch(t.type){case"literal":return`L:${t.raw}`;case"identifier":return`I:${t.name}`;case"memberAccess":return`M:${se(t.object)}.${t.property}`;case"methodCall":return`MC:${se(t.object)}.${t.method}(${t.args.map(se).join(",")})`;case"bracketAccess":return`B:${se(t.object)}[${se(t.index)}]`;case"binaryOp":return`BO:${se(t.left)}${t.op}${se(t.right)}`;case"unaryOp":return`UO:${t.op}${se(t.operand)}`;case"ternary":return`T:${se(t.condition)}?${se(t.consequent)}:${se(t.alternate)}`;case"inExpr":return`IN:${se(t.element)}in${se(t.collection)}`;case"isExpr":return`IS:${se(t.value)}is${t.typeName}`;case"listLiteral":return`LL:[${t.elements.map(se).join(",")}]`;case"mapLiteral":return`ML:{${t.entries.map(e=>se(e.key)+":"+se(e.value)).join(",")}}`;case"functionCall":return`FC:${t.name}(${t.args.map(se).join(",")})`;case"pathLiteral":return`PL:${t.raw}`;case"sliceAccess":return`SL:${se(t.object)}[${se(t.start)}:${se(t.end)}]`;default:{const e=t;throw new Error(`expressionFingerprint: unhandled type ${e.type}`)}}}function Ma(t){return t.type==="binaryOp"&&t.op==="&&"?Ma(t.left):t}function Da(t){const e=new Map,r=new Set(t.map(s=>s.name));function n(s){const i=[],a=o=>{switch(o.type){case"functionCall":r.has(o.name)&&!Ir.has(o.name)&&i.push(o.name),o.args.forEach(a);break;case"binaryOp":a(o.left),a(o.right);break;case"unaryOp":a(o.operand);break;case"methodCall":a(o.object),o.args.forEach(a);break;case"memberAccess":a(o.object);break;case"bracketAccess":a(o.object),a(o.index);break;case"ternary":a(o.condition),a(o.consequent),a(o.alternate);break;case"inExpr":a(o.element),a(o.collection);break;case"isExpr":a(o.value);break;case"listLiteral":o.elements.forEach(a);break;case"mapLiteral":o.entries.forEach(c=>{a(c.key),a(c.value)});break}};return a(s),[...new Set(i)]}for(const s of t){const i=[];i.push(...n(s.body));for(const a of s.lets)i.push(...n(a.value));e.set(s.name,[...new Set(i)])}return e}function As(t,e,r=new Set){if(r.has(t))return 0;r.add(t);const n=e.get(t)||[];if(n.length===0)return 1;let s=0;for(const i of n)s=Math.max(s,As(i,e,new Set(r)));return 1+s}function Fa(t,e,r=new Set){let n=0;const s=i=>{switch(i.type){case"functionCall":if(i.name==="get"||i.name==="exists")n++;else if(e.has(i.name)&&!r.has(i.name)){r.add(i.name);const a=e.get(i.name);s(a.body);for(const o of a.lets)s(o.value)}i.args.forEach(s);break;case"binaryOp":s(i.left),s(i.right);break;case"unaryOp":s(i.operand);break;case"methodCall":s(i.object),i.args.forEach(s);break;case"memberAccess":s(i.object);break;case"bracketAccess":s(i.object),s(i.index);break;case"ternary":s(i.condition),s(i.consequent),s(i.alternate);break;case"inExpr":s(i.element),s(i.collection);break;case"isExpr":s(i.value);break;case"listLiteral":i.elements.forEach(s);break;case"mapLiteral":i.entries.forEach(a=>{s(a.key),s(a.value)});break}};return s(t),n}function Zc(t,e){const r=new Map,n=s=>{switch(s.type){case"functionCall":e.has(s.name)&&r.set(s.name,(r.get(s.name)??0)+1),s.args.forEach(n);break;case"binaryOp":n(s.left),n(s.right);break;case"unaryOp":n(s.operand);break;case"methodCall":n(s.object),s.args.forEach(n);break;case"memberAccess":n(s.object);break;case"bracketAccess":n(s.object),n(s.index);break;case"ternary":n(s.condition),n(s.consequent),n(s.alternate);break;case"inExpr":n(s.element),n(s.collection);break;case"isExpr":n(s.value);break;case"listLiteral":s.elements.forEach(n);break;case"mapLiteral":s.entries.forEach(i=>{n(i.key),n(i.value)});break}};return n(t),r}function ja(t,e,r=new Set){if(r.has(t))return!1;r.add(t);const n=e.get(t);if(!n)return!1;const s=i=>{switch(i.type){case"functionCall":return i.name==="get"||i.name==="exists"?!0:e.has(i.name)?ja(i.name,e,r):i.args.some(s);case"binaryOp":return s(i.left)||s(i.right);case"unaryOp":return s(i.operand);case"methodCall":return s(i.object)||i.args.some(s);case"memberAccess":return s(i.object);case"bracketAccess":return s(i.object)||s(i.index);case"ternary":return s(i.condition)||s(i.consequent)||s(i.alternate);case"inExpr":return s(i.element)||s(i.collection);case"isExpr":return s(i.value);case"listLiteral":return i.elements.some(s);case"mapLiteral":return i.entries.some(a=>s(a.key)||s(a.value));default:return!1}};return s(n.body)||n.lets.some(i=>s(i.value))}function Un(t,e,r=new Set){const n=s=>{switch(s.type){case"memberAccess":return s.property==="time"&&s.object.type==="identifier"&&s.object.name==="request"?!0:n(s.object);case"bracketAccess":return s.object.type==="identifier"&&s.object.name==="request"&&s.index.type==="literal"&&s.index.value==="time"?!0:n(s.object)||n(s.index);case"functionCall":if(e.has(s.name)&&!r.has(s.name)){r.add(s.name);const i=e.get(s.name);if(Un(i.body,e,r)||i.lets.some(a=>Un(a.value,e,r)))return!0}return s.args.some(n);case"binaryOp":return n(s.left)||n(s.right);case"unaryOp":return n(s.operand);case"methodCall":return n(s.object)||s.args.some(n);case"ternary":return n(s.condition)||n(s.consequent)||n(s.alternate);case"inExpr":return n(s.element)||n(s.collection);case"isExpr":return n(s.value);case"listLiteral":return s.elements.some(n);case"mapLiteral":return s.entries.some(i=>n(i.key)||n(i.value));default:return!1}};return n(t)}function qa(t){const e=[...t.functions];for(const r of t.children)e.push(...qa(r));return e}function Pa(t){const e=[];for(const r of t.allows)e.push({rule:r,path:t.path.raw,matchFunctions:t.functions});for(const r of t.children){const n=Pa(r);for(const s of n)s.matchFunctions=[...t.functions,...s.matchFunctions];e.push(...n)}return e}const Bn={where:"No equivalent in rules — restructure logic instead of filtering a list",filter:"No equivalent in rules — restructure logic instead of filtering a list",find:"No equivalent in rules",findIndex:"No equivalent in rules",map:"No equivalent in rules — lists are not transformable",reduce:"No equivalent in rules",forEach:"No equivalent in rules",every:'Use `list.hasAll([...])` for "all elements present"',some:'Use `list.hasAny([...])` for "any element present"',includes:"Use `x in list` instead of `list.includes(x)`",indexOf:"No equivalent in rules",push:"Lists are immutable in rules",pop:"Lists are immutable in rules",shift:"Lists are immutable in rules",unshift:"Lists are immutable in rules",splice:"Lists are immutable in rules",slice:"No equivalent in rules",sort:"Lists are immutable in rules",reverse:"Lists are immutable in rules",flat:"No equivalent in rules",flatMap:"No equivalent in rules",toLowerCase:"Use `.lower()` instead of `.toLowerCase()`",toUpperCase:"Use `.upper()` instead of `.toUpperCase()`",charAt:'No equivalent in rules — use `.split("")` and index',charCodeAt:"No equivalent in rules",substring:"No `.substring()` — use `.split()` and reassembly",substr:"No `.substr()` — use `.split()` and reassembly",padStart:"No equivalent in rules",padEnd:"No equivalent in rules",trimStart:"Use `.trim()` (trims both ends)",trimEnd:"Use `.trim()` (trims both ends)",toString:"Use the `string(x)` cast instead of `.toString()`"},it={Object:"No `Object` in rules — use `data.keys()` / `data.values()` directly",Array:"No `Array` in rules — test list type with `x is list`",JSON:"No `JSON` in rules — rules cannot parse or serialize JSON",Math:"No `Math` in rules — inline arithmetic or ternaries",Date:"No `Date` in rules — use `request.time` (a Timestamp)",String:"Use lowercase `string(x)` for casting",Number:"Use lowercase `int(x)` or `float(x)` for casting",Boolean:"Use direct comparison or validation instead of boolean casting",bool:"No `bool()` cast in rules — boolean casting is not supported in production Firestore rules.",parseInt:"Use `int(x)` instead",parseFloat:"Use `float(x)` instead",isNaN:"No equivalent in rules",isFinite:"No equivalent in rules",Promise:"Rules are synchronous — no Promise support",undefined:"`undefined` does not exist in rules — use `null`"},Jc=new Set(["abs","ceil","floor","round","sqrt","pow","isNaN"]),Yc=[{receiver:"request",property:"data",suggestion:"Use `request.resource.data` (the incoming write payload)"},{receiver:"request",property:"uid",suggestion:"Use `request.auth.uid`"},{receiver:"request",property:"token",suggestion:"Use `request.auth.token`"},{receiver:"request",property:"user",suggestion:"Use `request.auth` (or `request.auth.uid` for the user id)"},{receiver:"resource",property:"path",suggestion:"`resource.path` is not available — bind path captures in the match pattern"},{receiver:"resource",property:"exists",suggestion:"Use `resource != null` (or `exists()` for cross-document checks)"},{receiver:"resource",property:"id",suggestion:"`resource.id` is not available — capture the document id with `/{docId}` in the match path"}],Qc=new Set(["size","keys","values","lower","upper","trim","hasAll","hasAny","hasOnly","toSet","toUtf8"]),Xc=[{pattern:/===/,message:"Strict equality `===` is not supported in Firestore rules — use `==`."},{pattern:/!==/,message:"Strict inequality `!==` is not supported in Firestore rules — use `!=`."},{pattern:/\?\./,message:"Optional chaining `?.` is not supported — use `'field' in obj && obj.field`."},{pattern:/\?\?/,message:"Nullish coalescing `??` is not supported — use a ternary `cond ? a : b`."},{pattern:/=>/,message:"Arrow functions `=>` are not supported — define functions with `function name() { return ...; }`."},{pattern:/`[^`]*`/,message:"Backtick strings are not supported — use single or double quoted strings with `+` for concatenation."}];function eu(t){const e=[],r=t.replace(/\/\/[^\n]*/g,"").replace(/\/\*[\s\S]*?\*\//g,"");for(const n of Xc)n.pattern.test(r)&&e.push({rule:"INVALID_OPERATOR",severity:"error",message:n.message});return e}function $a(t,e){const r=t.path.raw;for(const n of t.functions){const s={matchPath:r,functionName:n.name};ue(n.body,s,e);for(const i of n.lets)ue(i.value,s,e)}for(let n=0;n<t.allows.length;n++)ue(t.allows[n].condition,{matchPath:r,ruleIndex:n},e);for(const n of t.children)$a(n,e)}function ue(t,e,r){switch(r(t,e),t.type){case"binaryOp":ue(t.left,e,r),ue(t.right,e,r);break;case"unaryOp":ue(t.operand,e,r);break;case"methodCall":ue(t.object,e,r),t.args.forEach(n=>ue(n,e,r));break;case"memberAccess":ue(t.object,e,r);break;case"bracketAccess":ue(t.object,e,r),ue(t.index,e,r);break;case"ternary":ue(t.condition,e,r),ue(t.consequent,e,r),ue(t.alternate,e,r);break;case"inExpr":ue(t.element,e,r),ue(t.collection,e,r);break;case"isExpr":ue(t.value,e,r);break;case"listLiteral":t.elements.forEach(n=>ue(n,e,r));break;case"mapLiteral":t.entries.forEach(n=>{ue(n.key,e,r),ue(n.value,e,r)});break;case"functionCall":t.args.forEach(n=>ue(n,e,r));break}}function tu(t,e){return e?!1:t.type==="functionCall"&&t.name==="debug"}function ru(t){return t.type==="methodCall"&&!!Bn[t.method]}function nu(t){return t.type!=="methodCall"||t.object.type!=="identifier"||t.object.name!=="math"?!1:!Jc.has(t.method)}function su(t){return t.type!=="methodCall"||t.method!=="hasAll"&&t.method!=="hasAny"&&t.method!=="hasOnly"?!1:t.object.type==="mapLiteral"||t.object.type==="memberAccess"&&t.object.property==="data"}function iu(t){return t.type!=="methodCall"||t.object.type!=="identifier"?!1:!!it[t.object.name]}function au(t){return t.type==="functionCall"&&!!it[t.name]}function ou(t){return t.type==="identifier"&&!!it[t.name]}function cu(t){if(t.type!=="memberAccess"||t.object.type!=="identifier")return;const e=t.object.name,r=t.property;return Yc.find(n=>n.receiver===e&&n.property===r)}function uu(t){return t.type==="memberAccess"&&t.property==="length"&&t.object.type==="methodCall"}function lu(t){return t.type!=="memberAccess"||!Qc.has(t.property)?!1:t.object.type==="identifier"&&(t.object.name==="request"||t.object.name==="resource")||t.object.type==="memberAccess"||t.object.type==="methodCall"||t.object.type==="bracketAccess"}function du(t,e={}){const r=[],n=new Set;function s(i,a,o,c){const u=`${i}|${a}|${o.matchPath||""}|${o.functionName||""}|${o.ruleIndex??""}`;n.has(u)||(n.add(u),r.push(c))}return $a(t.service.match,(i,a)=>{if(tu(i,e.allowDebug)&&s("HALLUCINATED_GLOBAL","debug",a,{rule:"HALLUCINATED_GLOBAL",severity:"error",message:"`debug()` helper is only permitted in local testing environments; remove it before deployment.",location:a,fix:"Remove debug() wrapper around the expression."}),ru(i)&&i.type==="methodCall"&&s("HALLUCINATED_METHOD",i.method,a,{rule:"HALLUCINATED_METHOD",severity:"error",message:`\`.${i.method}()\` does not exist in Firestore rules. ${Bn[i.method]}`,location:a,fix:Bn[i.method]}),nu(i)&&i.type==="methodCall"&&s("HALLUCINATED_METHOD",`math.${i.method}`,a,{rule:"HALLUCINATED_METHOD",severity:"error",message:`\`math.${i.method}()\` does not exist in production Firestore security rules.`,location:a,fix:"Use supported math namespace functions: abs, ceil, floor, round, sqrt, pow, isNaN."}),su(i)&&i.type==="methodCall"&&s("HALLUCINATED_METHOD",`map.${i.method}`,a,{rule:"HALLUCINATED_METHOD",severity:"error",message:`\`.${i.method}()\` cannot be called directly on a map in Firestore rules — call it on \`.keys()\` instead.`,location:a,fix:`Insert \`.keys()\`: e.g. \`data.keys().${i.method}(...)\`.`}),iu(i)&&i.type==="methodCall"&&i.object.type==="identifier"){const c=i.object.name;s("HALLUCINATED_GLOBAL",`${c}.${i.method}`,a,{rule:"HALLUCINATED_GLOBAL",severity:"error",message:`\`${c}.${i.method}()\` does not exist in Firestore rules. ${it[c]}`,location:a,fix:it[c]})}au(i)&&i.type==="functionCall"&&s("HALLUCINATED_GLOBAL",i.name,a,{rule:"HALLUCINATED_GLOBAL",severity:"error",message:`\`${i.name}()\` does not exist in Firestore rules. ${it[i.name]}`,location:a,fix:it[i.name]}),ou(i)&&i.type==="identifier"&&s("HALLUCINATED_GLOBAL",`ref:${i.name}`,a,{rule:"HALLUCINATED_GLOBAL",severity:"error",message:`\`${i.name}\` is not a Firestore rules identifier. ${it[i.name]}`,location:a,fix:it[i.name]});const o=cu(i);if(o&&i.type==="memberAccess"&&i.object.type==="identifier"){const c=i.object.name,u=i.property;s("WRONG_CONTEXT_PATH",`${c}.${u}`,a,{rule:"WRONG_CONTEXT_PATH",severity:"error",message:`\`${c}.${u}\` is not a valid Firestore rules path. ${o.suggestion}`,location:a,fix:o.suggestion})}if(uu(i)&&s("LENGTH_PROPERTY","",a,{rule:"LENGTH_PROPERTY",severity:"error",message:"`.length` is not a valid property in Firestore rules — use `.size()` (a method, with parentheses).",location:a,fix:"Replace `.length` with `.size()`."}),i.type==="pathLiteral")for(const c of i.segments){if(typeof c!="string")continue;const u=c.match(/^\{([A-Za-z_][A-Za-z0-9_]*)\}$/);if(!u)continue;const f=u[1];s("INVALID_PATH_INTERPOLATION",`${i.raw}|${f}`,a,{rule:"INVALID_PATH_INTERPOLATION",severity:"error",message:`\`{${f}}\` is not valid inside a path literal — Firestore rejects this at deploy. The \`{var}\` syntax is for match statement wildcards (e.g. \`match /users/{userId}\`); path interpolation in get()/exists()/getAfter()/existsAfter() requires \`$(var)\`. Replace \`{${f}}\` with \`$(${f})\` in path \`${i.raw}\`.`,location:a,fix:`Replace \`{${f}}\` with \`$(${f})\` inside the path argument.`})}lu(i)&&i.type==="memberAccess"&&s("METHOD_MISSING_PARENS",i.property,a,{rule:"METHOD_MISSING_PARENS",severity:"warning",message:`\`.${i.property}\` looks like a built-in method called without parentheses. Use \`.${i.property}()\` if you meant to invoke it (otherwise this is a field access).`,location:a,fix:`Add parentheses: \`.${i.property}()\`.`})}),r}const pe={SOURCE_SIZE:256*1024,CHAIN_DEPTH_ERROR:95,CHAIN_DEPTH_WARN:85,CHAIN_DEPTH_LIMIT:98,LET_LIMIT:11,RUNTIME_BUDGET:{low:{calls:2,warn:100},mid:{calls:4,warn:60},high:{warn:40}},CALL_DEPTH_WARN:6,CALL_DEPTH_ERROR:10,GET_COUNT_WARN:5,GET_COUNT_ERROR:10};function hu(t,e){t.length>pe.SOURCE_SIZE&&e.push({rule:"SOURCE_SIZE",severity:"error",message:`Rules source is ${(t.length/1024).toFixed(0)} KB, exceeding the 256 KB limit.`,fix:"Reduce string literals, remove comments, or split into smaller match blocks."})}function fu(t,e){for(const r of t)r.lets.length>pe.LET_LIMIT&&e.push({rule:"LET_LIMIT",severity:"error",message:`Function '${r.name}' has ${r.lets.length} let bindings. Limit is ${pe.LET_LIMIT}.`,location:{functionName:r.name},fix:"Inline some let expressions into the return statement, or split the function."})}function pu(t,e){for(const r of t){const n=$n(r.body);for(const s of r.lets){const i=$n(s.value);i.depth>n.depth&&(n.depth=i.depth,n.op=i.op)}n.depth>=pe.CHAIN_DEPTH_LIMIT?e.push({rule:"CHAIN_DEPTH",severity:"error",message:`Function '${r.name}' has a ${n.op} chain of depth ${n.depth}. Limit is ${pe.CHAIN_DEPTH_LIMIT}.`,location:{functionName:r.name},fix:"Split into nested groups: 'a && b && c && d' → '(a && b) && (c && d)' to halve chain depth."}):n.depth>=pe.CHAIN_DEPTH_ERROR?e.push({rule:"CHAIN_DEPTH",severity:"error",message:`Function '${r.name}' has a ${n.op} chain of depth ${n.depth}. Limit is ${pe.CHAIN_DEPTH_LIMIT}. Approaching failure.`,location:{functionName:r.name},fix:"Split the chain into nested groups to reduce depth."}):n.depth>=pe.CHAIN_DEPTH_WARN&&e.push({rule:"CHAIN_DEPTH",severity:"warning",message:`Function '${r.name}' has a ${n.op} chain of depth ${n.depth}. Limit is ${pe.CHAIN_DEPTH_LIMIT}.`,location:{functionName:r.name}})}}function mu(t,e){const r=new Map;for(let n=0;n<t.length;n++){const s=t[n];if(!s.rule.operations.some(o=>o==="update"||o==="write"))continue;const i=se(Ma(s.rule.condition)),a=s.path;r.has(a)||r.set(a,[]),r.get(a).push({index:n,gate:i,ops:s.rule.operations})}for(const[n,s]of r){const i=new Map;for(const a of s)i.has(a.gate)||i.set(a.gate,[]),i.get(a.gate).push(a.index);for(const[a,o]of i)o.length>=2&&e.push({rule:"SHARED_GATE",severity:"warning",message:`${o.length} allow rules in '${n}' share the same gate expression. This may cause cross-rule budget exhaustion. Rules: ${o.join(", ")}.`,location:{matchPath:n},fix:"Assign unique moveType or discriminator values so each rule has a unique first expression."})}}function gu(t,e){let r=ie(t);const n=new Set;function s(i){if(i.type==="functionCall"&&e.has(i.name)&&!n.has(i.name)){n.add(i.name);const a=e.get(i.name);r+=ie(a.body);for(const o of a.lets)r+=ie(o.value);s(a.body);for(const o of a.lets)s(o.value)}switch(i.type){case"binaryOp":s(i.left),s(i.right);break;case"unaryOp":s(i.operand);break;case"methodCall":s(i.object),i.args.forEach(s);break;case"memberAccess":s(i.object);break;case"bracketAccess":s(i.object),s(i.index);break;case"ternary":s(i.condition),s(i.consequent),s(i.alternate);break;case"inExpr":s(i.element),s(i.collection);break;case"isExpr":s(i.value);break;case"listLiteral":i.elements.forEach(s);break;case"mapLiteral":i.entries.forEach(a=>{s(a.key),s(a.value)});break;case"functionCall":i.args.forEach(s);break}}return s(t),{totalExprs:r,callCount:n.size}}function yu(t,e,r){const n=new Map;for(const s of e)n.set(s.name,s);for(let s=0;s<t.length;s++){const{totalExprs:i,callCount:a}=gu(t[s].rule.condition,n),o=Rr(t[s].rule.condition,"||"),c=o>5?.3:o>2?.5:1,u=Math.round(i*c),f=a<=pe.RUNTIME_BUDGET.low.calls?pe.RUNTIME_BUDGET.low:a<=pe.RUNTIME_BUDGET.mid.calls?pe.RUNTIME_BUDGET.mid:pe.RUNTIME_BUDGET.high;u>=f.warn&&r.push({rule:"EXPRESSION_BUDGET",severity:"warning",message:`Rule #${s} has ~${i} expression nodes across ${a} function calls. Runtime budget is non-deterministic; actual evaluation depends on short-circuit behavior.`,location:{ruleIndex:s},fix:"If this rule fails at runtime (403), reduce function calls or expression count."})}}function vu(t,e,r){const n=Da(e),s=new Map;for(const i of e)s.set(i.name,i);for(let i=0;i<t.length;i++){let a=0;const o=c=>{if(c.type==="functionCall"&&s.has(c.name)){const u=As(c.name,n);u>a&&(a=u)}switch(c.type){case"binaryOp":o(c.left),o(c.right);break;case"unaryOp":o(c.operand);break;case"methodCall":o(c.object),c.args.forEach(o);break;case"memberAccess":o(c.object);break;case"bracketAccess":o(c.object),o(c.index);break;case"ternary":o(c.condition),o(c.consequent),o(c.alternate);break;case"inExpr":o(c.element),o(c.collection);break;case"functionCall":c.args.forEach(o);break}};o(t[i].rule.condition),a>=pe.CALL_DEPTH_ERROR?r.push({rule:"CALL_DEPTH",severity:"error",message:`Rule #${i} has a function call chain of depth ${a}. May exceed call budget.`,location:{ruleIndex:i},fix:"Inline intermediate functions to reduce call depth."}):a>=pe.CALL_DEPTH_WARN&&r.push({rule:"CALL_DEPTH",severity:"warning",message:`Rule #${i} has a function call chain of depth ${a}.`,location:{ruleIndex:i}})}}function bu(t,e,r){const n=new Map;for(const s of e)n.set(s.name,s);for(let s=0;s<t.length;s++){const i=Fa(t[s].rule.condition,n);i>=pe.GET_COUNT_ERROR?r.push({rule:"GET_COUNT",severity:"error",message:`Rule #${s} may invoke ${i} get()/exists() calls. Limit is ${pe.GET_COUNT_ERROR}.`,location:{ruleIndex:s},fix:"Cache get() results via a config() wrapper function. Same-path calls are cached by Firestore."}):i>=pe.GET_COUNT_WARN&&r.push({rule:"GET_COUNT",severity:"warning",message:`Rule #${s} invokes ${i} get()/exists() calls. Limit is ${pe.GET_COUNT_ERROR}.`,location:{ruleIndex:s}})}}function wu(t,e,r){const n=new Map;for(const i of e)n.set(i.name,i);const s=new Set(e.map(i=>i.name));for(let i=0;i<t.length;i++){const a=Zc(t[i].rule.condition,s);for(const[o,c]of a)c>=2&&ja(o,n)&&r.push({rule:"GET_DUPLICATION",severity:"warning",message:`Function '${o}' (contains get/exists) is called ${c} times in rule #${i}. Cache the result with a let binding in a wrapper function to reduce get() calls from ${c} to 1.`,location:{ruleIndex:i},fix:`Create a wrapper: function verifyAll(ret) { let c = ${o}(); return verify1(ret, c) && verify2(ret, c) && ...; }`})}}function Su(t,e,r,n){const s=new Map;for(const o of e)s.set(o.name,o);const i=new Set;for(let o=0;o<t.length;o++)Un(t[o].rule.condition,s)&&i.add(o);if(i.size===0)return;function a(o,c){const u=o.split("/").filter(Boolean),f=c.split("/").filter(Boolean);if(u.length!==f.length)return!1;for(let l=0;l<u.length;l++){const p=u[l];if(!(p.startsWith("{")&&p.endsWith("}"))&&p!==f[l])return!1}return!0}for(const o of r)if(!o.requestTime)for(const c of i)a(t[c].path,o.path)&&n.push({rule:"REQUEST_TIME_NOT_PINNED",severity:"warning",message:`Test case "${o.description}" targets rule #${c} (path '${t[c].path}') which reads request.time, but does not set requestTime. Result is non-deterministic across runs.`,location:{ruleIndex:c,matchPath:t[c].path,testCaseDescription:o.description},fix:"Set requestTime on this TestCase to an ISO-8601 timestamp so the rule evaluates deterministically."})}function or(t){if(t.type==="literal"&&typeof t.value=="boolean")return t.value;if(t.type==="binaryOp"){const e=or(t.left),r=or(t.right);if(t.op==="&&")return e===!1||r===!1?!1:e===!0&&r===!0?!0:null;if(t.op==="||")return e===!0||r===!0?!0:e===!1&&r===!1?!1:null}if(t.type==="unaryOp"&&t.op==="!"){const e=or(t.operand);return e===null?null:!e}return null}const _u=new Set(["write","create","update","delete"]);function Au(t,e){for(let r=0;r<t.length;r++){const n=t[r];if(or(n.rule.condition)!==!0||!n.rule.operations.some(a=>_u.has(a)))continue;const i=n.rule.operations.join(", ");e.push({rule:"PERMISSIVE_RULE",severity:"warning",message:`allow ${i} at ${n.path} resolves to a constant true predicate — this disables write security for the matched paths. If you reached for \`if true\` to escape a denial you don't understand, narrow the predicate to the specific request shape instead (auth identity, affected fields via diff, status transitions).`,location:{ruleIndex:r,matchPath:n.path},fix:"Replace the always-true predicate with a request-shape check (e.g. request.auth != null && request.resource.data.ownerId == request.auth.uid)."})}}function Ua(t,e){if(t.path.segments.some(n=>n.type==="recursive"))for(let n=0;n<t.allows.length;n++)or(t.allows[n].condition)===!0&&e.push({rule:"RECURSIVE_WILDCARD_OPEN",severity:"error",message:`Recursive wildcard match (${t.path.raw}) with an always-true predicate exposes every document under this prefix. This is the Firebase open-rules anti-pattern — never ship it.`,location:{ruleIndex:n,matchPath:t.path.raw},fix:"Either narrow the match path to specific collections, or replace `if true` with a real predicate (auth identity, ownership, role)."});for(const n of t.children)Ua(n,e)}function Iu(t){return t.type==="literal"?t.value??"":t.type==="wildcard"?"{*}":t.type==="recursive"?"{**}":""}function xu(t){return t.map(Iu).join("/")}function zn(t,e){const r=xu(t.path.segments),n=e?`${e}/${r}`:r,s=[{block:t,normalizedPath:n}];for(const i of t.children)s.push(...zn(i,n));return s}function ne(t){switch(t.type){case"literal":return t.raw;case"identifier":return t.name;case"memberAccess":return`${ne(t.object)}.${t.property}`;case"methodCall":return`${ne(t.object)}.${t.method}(${t.args.map(ne).join(",")})`;case"bracketAccess":return`${ne(t.object)}[${ne(t.index)}]`;case"sliceAccess":return`${ne(t.object)}[${ne(t.start)}:${ne(t.end)}]`;case"binaryOp":return`(${ne(t.left)}${t.op}${ne(t.right)})`;case"unaryOp":return`(${t.op}${ne(t.operand)})`;case"ternary":return`(${ne(t.condition)}?${ne(t.consequent)}:${ne(t.alternate)})`;case"inExpr":return`(${ne(t.element)} in ${ne(t.collection)})`;case"isExpr":return`(${ne(t.value)} is ${t.typeName})`;case"listLiteral":return`[${t.elements.map(ne).join(",")}]`;case"mapLiteral":return`{${t.entries.map(e=>`${ne(e.key)}:${ne(e.value)}`).join(",")}}`;case"pathLiteral":return t.raw;case"functionCall":return`${t.name}(${t.args.map(ne).join(",")})`}}function Nr(t){return t.type==="binaryOp"&&t.op==="&&"?[...Nr(t.left),...Nr(t.right)]:[t]}function ku(t,e,r){const n=zn(t,""),s=zn(e,""),i=new Map;for(const{block:a,normalizedPath:o}of n)i.has(o)||i.set(o,a);for(const{block:a,normalizedPath:o}of s){const c=i.get(o);if(!c){a.allows.length>0&&r.push({rule:"RULES_WEAKENED",severity:"warning",message:`Match block removed: ${o}`,location:{matchPath:o}});continue}for(const u of a.allows){const f=[...u.operations].sort().join(","),l=c.allows.find(w=>[...w.operations].sort().join(",")===f),p=u.operations.join(", ");if(!l){r.push({rule:"RULES_WEAKENED",severity:"warning",message:`Allow rule removed: ${o} allow ${p}`,location:{matchPath:o}});continue}const y=Nr(u.condition).map(ne),v=new Set(Nr(l.condition).map(ne));for(const w of y)v.has(w)||r.push({rule:"RULES_WEAKENED",severity:"warning",message:`Predicate removed from ${o} allow ${p}: ${w}`,location:{matchPath:o}})}}}function Vn(t,e={}){const r=[];r.push(...eu(t)),hu(t,r);const n=Or(t);if(!n.ok)return{warnings:r,metrics:{sourceSize:t.length,functionCount:0,allowRuleCount:0,maxChainDepth:0,maxChainOp:"",maxLetBindings:0,maxLetBindingsFunction:"",maxCallDepth:0,maxEstimatedExpressions:0,getCallCount:0},parseError:n.error};const s=n.ast,i=qa(s.service.match),a=Pa(s.service.match);if(pu(i,r),fu(i,r),mu(a,r),yu(a,i,r),vu(a,i,r),bu(a,i,r),wu(a,i,r),r.push(...du(s,{allowDebug:e.allowDebug||!!(e.testCases&&e.testCases.length>0)})),Au(a,r),Ua(s.service.match,r),e.testCases&&e.testCases.length>0&&Su(a,i,e.testCases,r),e.previousSource){const v=Or(e.previousSource);v.ok&&ku(s.service.match,v.ast.service.match,r)}let o={depth:0,op:""},c={count:0,fn:""};for(const v of i){const w=$n(v.body);w.depth>o.depth&&(o={depth:w.depth,op:w.op}),v.lets.length>c.count&&(c={count:v.lets.length,fn:v.name})}const u=Da(i);let f=0;for(const v of i){const w=As(v.name,u);w>f&&(f=w)}const l=new Map;for(const v of i)l.set(v.name,v);let p=0,y=0;for(const v of a){const w=Fa(v.rule.condition,l);w>y&&(y=w)}return{warnings:r,metrics:{sourceSize:t.length,functionCount:i.length,allowRuleCount:a.length,maxChainDepth:o.depth,maxChainOp:o.op,maxLetBindings:c.count,maxLetBindingsFunction:c.fn,maxCallDepth:f,maxEstimatedExpressions:p,getCallCount:y}}}const Is={atomic:["cloud.firestore"],auth:["cloud.firestore","firebase.storage"],content:["cloud.firestore"],counters:["cloud.firestore"],geometry:["cloud.firestore"],joining:["cloud.firestore"],lifecycle:["cloud.firestore"],lobby:["cloud.firestore"],membership:["cloud.firestore","firebase.storage"],spaces:["cloud.firestore"],state:["cloud.firestore"],"storage/metadata":["firebase.storage"],"storage/objects":["firebase.storage"],"storage/time":["firebase.storage"],"storage/uploads":["firebase.storage"],timing:["cloud.firestore"],transitions:["cloud.firestore"],turns:["cloud.firestore"],validation:["cloud.firestore"]};Object.freeze(Object.keys(Is).sort());const Eu={atomic:[],auth:["storage-rules#125","firestore-rules#189"],content:[],counters:[],geometry:[],joining:[],lifecycle:[],lobby:[],membership:["storage-rules#125","firestore-rules#189"],spaces:[],state:[],"storage/metadata":["storage-rules#132"],"storage/objects":["storage-rules#132"],"storage/time":["storage-rules#132"],"storage/uploads":["storage-rules#132"],timing:[],transitions:[],turns:[],validation:[]},Ba=["exists","existsAfter","get","getAfter"],Tu=["addedKeys","affectedKeys","bind","changedKeys","concat","date","day","dayOfWeek","dayOfYear","diff","difference","distance","get","hasAll","hasAny","hasOnly","hours","intersection","join","keys","latitude","longitude","lower","matches","minutes","month","nanos","removeAll","removedKeys","replace","seconds","size","split","time","toBase64","toHexString","toMillis","toSet","toUtf8","trim","unchangedKeys","union","upper","values","year"],Ou={addedKeys:["mapdiff"],affectedKeys:["mapdiff"],bind:["path"],changedKeys:["mapdiff"],concat:["list"],date:["timestamp"],day:["timestamp"],dayOfWeek:["timestamp"],dayOfYear:["timestamp"],diff:["map"],difference:["set"],distance:["latlng"],get:["map"],hasAll:["list","set"],hasAny:["list","set"],hasOnly:["list","set"],hours:["timestamp"],intersection:["set"],join:["list"],keys:["map"],latitude:["latlng"],longitude:["latlng"],lower:["string"],matches:["string"],minutes:["timestamp"],month:["timestamp"],nanos:["duration","timestamp"],removeAll:["list"],removedKeys:["mapdiff"],replace:["string"],seconds:["duration","timestamp"],size:["bytes","list","map","set","string"],split:["string"],time:["timestamp"],toBase64:["bytes"],toHexString:["bytes"],toMillis:["timestamp"],toSet:["list"],toUtf8:["string"],trim:["string"],unchangedKeys:["mapdiff"],union:["set"],upper:["string"],values:["map"],year:["timestamp"]},za={cast:["float","int","path","string"],duration:["abs","time","value"],hashing:["crc32","crc32c","md5","sha256"],latlng:["value"],math:["abs","ceil","floor","isNaN","pow","round","sqrt"],timestamp:["date","value"]},Cu=["request","request.auth","request.auth.token","request.auth.uid","request.method","request.path","request.resource","request.resource.contentType","request.resource.metadata","request.resource.size","request.time","resource","resource.bucket","resource.contentType","resource.generation","resource.metadata","resource.metageneration","resource.name","resource.size","resource.timeCreated","resource.updated"],Ru=["get","hasAll","keys","matches","size","split"],Nu={get:["map"],hasAll:["set"],keys:["map"],matches:["string"],size:["list","map","string"],split:["string"]},Va={duration:["value"],firestore:["exists","get"],timestamp:["date","value"]},Lu=new Set(Cu),Mu=["request.auth.token","request.resource.metadata","resource.metadata"];function Du(t,e){if(e.length===1)return!0;if(t==="firebase.storage"){const r=e.join(".");return Lu.has(r)||Mu.some(n=>r.startsWith(`${n}.`))}return e[0]==="request"?e[1]==="auth"||e[1]==="query"?!0:["time","method","path"].includes(e[1])?e.length===2:e[1]==="resource"&&(e.length===2||e[2]==="data"):e[0]==="resource"&&(e.length===1||e[1]==="data")}function Lr(t,e){return e[0]==="request"&&e[1]==="auth"&&e[2]==="token"?!0:t==="firebase.storage"?e[0]==="resource"&&e[1]==="metadata"||e[0]==="request"&&e[1]==="resource"&&e[2]==="metadata":e[0]==="resource"&&e[1]==="data"||e[0]==="request"&&e[1]==="resource"&&e[2]==="data"||e[0]==="request"&&e[1]==="query"}function Fu(t,e){if(!e||e==="unknown-ambient")return null;const r=e.join(".");return r==="request.resource"||r==="resource"?"resource":r==="request.auth"||r==="request.auth.token"||t==="cloud.firestore"&&(r==="request.resource.data"||r==="resource.data"||r==="request.query")||r==="request.resource.metadata"||r==="resource.metadata"?"map":r==="request.auth.uid"||r==="request.method"||r==="request.resource.contentType"||r==="resource.contentType"||t==="firebase.storage"&&(r.startsWith("request.resource.metadata.")||r.startsWith("resource.metadata."))?"string":r==="request.path"?"path":r==="request.time"||r==="resource.timeCreated"||r==="resource.updated"?"timestamp":["request.resource.size","resource.size","resource.generation","resource.metageneration"].includes(r)?"number":null}function ni(t){if(t.type!=="methodCall")return null;if(t.object.type==="identifier"){if(t.object.name==="firestore"){if(t.method==="get")return"document";if(t.method==="exists")return"boolean"}if(t.object.name==="duration")return"duration";if(t.object.name==="timestamp")return"timestamp";if(t.object.name==="latlng")return"latlng";if(t.object.name==="hashing")return"bytes";if(t.object.name==="math")return"number";if(t.object.name==="cast"){if(t.method==="string")return"string";if(t.method==="path")return"path";if(t.method==="int"||t.method==="float")return"number"}}return["lower","upper","trim","replace","join","toBase64","toHexString"].includes(t.method)?"string":["matches","hasAny","hasAll","hasOnly"].includes(t.method)?"boolean":["concat","removeAll","split","values"].includes(t.method)?"list":["keys","toSet","addedKeys","removedKeys","changedKeys","affectedKeys","unchangedKeys","difference","union","intersection"].includes(t.method)?"set":t.method==="diff"?"mapdiff":t.method==="get"?null:t.method==="toUtf8"?"bytes":t.method==="date"?"timestamp":["size","year","month","day","hours","minutes","seconds","nanos","dayOfWeek","dayOfYear","toMillis","latitude","longitude","distance"].includes(t.method)?"number":null}const ju=new Set(Ba),qu=Object.fromEntries(Object.entries(za).map(([t,e])=>[t,new Set(e)])),Pu=Object.fromEntries(Object.entries(Va).map(([t,e])=>[t,new Set(e)]));function rt(t,e){return t.some(r=>we(r,e)!==null)?"unknown-ambient":null}function Ha(t,e,r){const n=r.declarations?.get(t),s=new Map(n?.aliases),i=new Map(n?.receiverTypes);return t.parameters.forEach((a,o)=>{s.set(a,e[o]?.provenance??null),i.set(a,e[o]?.receiverType??null)}),{aliases:s,receiverTypes:i,functions:n?.functions??r.functions,service:r.service,stack:new Set([...r.stack,t.name]),declarations:r.declarations}}function Wt(t,e){return{expression:t,provenance:we(t,e),receiverType:le(t,e)}}function we(t,e){if(t.type==="identifier")return t.name==="request"||t.name==="resource"?[t.name]:e.aliases.get(t.name)??null;if(t.type==="memberAccess"){const r=we(t.object,e);return r==="unknown-ambient"?r:r?[...r,t.property]:null}if(t.type==="bracketAccess"){const r=we(t.object,e);return!r||r==="unknown-ambient"?r:t.index.type==="literal"&&typeof t.index.value=="string"?[...r,t.index.value]:[...r,"*"]}if(t.type==="ternary"){const r=we(t.consequent,e),n=we(t.alternate,e);return!r&&!n?null:Array.isArray(r)&&Array.isArray(n)&&r.join(".")===n.join(".")?r:"unknown-ambient"}if(t.type==="functionCall"){const r=e.functions.get(t.name),n=t.args.map(i=>Wt(i,e));if(!r&&ju.has(t.name))return null;if(!r||e.stack.has(r.name))return n.some(({provenance:i})=>i!==null)?"unknown-ambient":null;const s=Ha(r,n,e);for(const i of r.lets){const a=Wt(i.value,s);s.aliases.set(i.name,a.provenance),s.receiverTypes.set(i.name,a.receiverType)}return we(r.body,s)}if(t.type==="methodCall"&&t.object.type==="identifier"&&t.object.name==="firestore"&&(t.method==="get"||t.method==="exists"))return null;switch(t.type){case"literal":return null;case"methodCall":return rt([t.object,...t.args],e);case"sliceAccess":return rt([t.object,t.start,t.end],e);case"binaryOp":return rt([t.left,t.right],e);case"unaryOp":return rt([t.operand],e);case"inExpr":return rt([t.element,t.collection],e);case"isExpr":return rt([t.value],e);case"listLiteral":return rt(t.elements,e);case"mapLiteral":return rt(t.entries.flatMap(({key:r,value:n})=>[r,n]),e);case"pathLiteral":return rt(t.segments.filter(r=>typeof r!="string"),e);default:return null}}function le(t,e){const r=Fu(e.service,we(t,e));if(r)return r;switch(t.type){case"identifier":{const n=e.receiverTypes.get(t.name);return n||((e.service==="cloud.firestore"?qu:Pu)[t.name]||t.name==="firestore"?"namespace":null)}case"literal":return t.value===null?"null":typeof t.value=="string"?"string":typeof t.value=="number"?"number":typeof t.value=="boolean"?"boolean":null;case"listLiteral":return"list";case"mapLiteral":return"map";case"pathLiteral":return"path";case"memberAccess":{const n=le(t.object,e);if(n==="mixed")return"mixed";if(t.property==="data"&&n==="document")return"map";if(t.object.type==="mapLiteral"){const s=t.object.entries.find(({key:i})=>i.type==="literal"&&i.value===t.property);return s?le(s.value,e):null}return null}case"bracketAccess":{const n=le(t.object,e);if(n==="mixed")return"mixed";if(t.object.type==="listLiteral"&&t.index.type==="literal"&&typeof t.index.value=="number"&&Number.isInteger(t.index.value)){const i=t.object.elements[t.index.value];return i?le(i,e):null}if(t.object.type==="mapLiteral"&&t.index.type==="literal"){const i=t.index.value,a=t.object.entries.find(({key:o})=>o.type==="literal"&&o.value===i);return a?le(a.value,e):null}if(n==="string")return"string";const s=we(t.object,e);return e.service==="firebase.storage"&&Array.isArray(s)&&(s.join(".")==="request.resource.metadata"||s.join(".")==="resource.metadata")?"string":null}case"sliceAccess":{const n=le(t.object,e);return n==="mixed"?"mixed":n==="list"||n==="string"?n:null}case"methodCall":{const n=ni(t);if(t.object.type==="identifier"&&n)return n;if(t.method==="get"){const s=we(t.object,e);if(e.service==="firebase.storage"&&Array.isArray(s)&&(s.join(".")==="request.resource.metadata"||s.join(".")==="resource.metadata"))return"string";const i=t.args[1];if(t.object.type==="mapLiteral"&&t.args[0]?.type==="literal"){const a=t.args[0].value,o=t.object.entries.find(({key:c})=>c.type==="literal"&&c.value===a);return o?le(o.value,e):i?le(i,e):null}return i&&le(i,e)?"mixed":null}return ni(t)}case"binaryOp":{const n=le(t.left,e),s=le(t.right,e);return t.op==="+"&&(n==="string"||s==="string")?"string":["==","!=","<","<=",">",">=","&&","||"].includes(t.op)?"boolean":["+","-","*","/","%"].includes(t.op)&&n==="number"&&s==="number"?"number":null}case"unaryOp":return t.op==="!"?"boolean":t.op==="-"&&le(t.operand,e)==="number"?"number":null;case"inExpr":case"isExpr":return"boolean";case"ternary":{const n=le(t.consequent,e),s=le(t.alternate,e);return!n&&!s?null:n===s?n:"mixed"}case"functionCall":{const n=e.functions.get(t.name);if(!n&&e.service==="cloud.firestore"){if(t.name==="get"||t.name==="getAfter")return"document";if(t.name==="exists")return"boolean"}if(!n||e.stack.has(n.name))return null;const s=Ha(n,t.args.map(i=>Wt(i,e)),e);for(const i of n.lets){const a=Wt(i.value,s);s.aliases.set(i.name,a.provenance),s.receiverTypes.set(i.name,a.receiverType)}return le(n.body,s)}default:return null}}function $u(t){return t.match(/^\.\/stdlib\/(.+?)(?:\.rules)?$/)?.[1]??t}function Uu(t,e,r){const n=$u(e),s=Is[n];return s?s.includes(t)?null:`Function '${r}' from module '${e}' is not compatible with service '${t}'`:null}function Bu(t){throw new Error(`Unhandled Rules expression: ${JSON.stringify(t)}`)}const zu=new Set(Ba),Vu=new Set(Tu),Hu=Object.fromEntries(Object.entries(za).map(([t,e])=>[t,new Set(e)])),Wu=new Set(Ru),Gu=Object.fromEntries(Object.entries(Va).map(([t,e])=>[t,new Set(e)]));function Mr(t,e){return t==="unknown-ambient"?"binding '<derived ambient value>'":t&&!Du(e,t)?`binding '${t.join(".")}'`:null}function Ku(t,e,r,n,s){if(e!=="get"&&e!=="keys"&&e!=="values")return null;const i=we(t,s);if(i==="unknown-ambient")return"binding '<derived ambient value>'";if(!i)return null;if(e==="get"){const a=r[0];if(a?.type==="literal"&&typeof a.value=="string")return Mr([...i,a.value],n);if(!Lr(n,i))return`binding '${i.join(".")}.get(...)'`}return(e==="keys"||e==="values")&&!Lr(n,i)?`binding '${i.join(".")}.${e}()'`:null}function Zu(t,e,r,n){const s=we(t,n),i=le(t,n);if(!i){if(s==="unknown-ambient")return"binding '<derived ambient receiver>'";let c=t;for(;c.type==="memberAccess"||c.type==="bracketAccess"||c.type==="methodCall"&&c.method==="get";)c=c.object;const u=le(c,n);return u==="map"||u==="list"||u==="document"?`method '.${e}()' has an unresolved projected receiver`:null}const o=(r==="cloud.firestore"?Ou:Nu)[e];return o?.includes(i)?null:`method '.${e}()' requires ${o?.join("|")??"an accepted"} receiver, got ${i}`}function Ju(t,e,r,n){const s=we(e,n);return s==="unknown-ambient"?"binding '<derived ambient value>'":s?t.type==="literal"&&typeof t.value=="string"?Mr([...s,t.value],r):Lr(r,s)?null:`binding '<value> in ${s.join(".")}'`:null}function si(t,e,r){const n=s=>{switch(s.type){case"memberAccess":{const i=Mr(we(s,r),e);return i||n(s.object)}case"functionCall":{const i=r.functions.get(s.name);if(!i&&e==="firebase.storage")return`function '${s.name}()'`;if(!i&&!zu.has(s.name))return`function '${s.name}()'`;for(const a of s.args){const o=n(a);if(o)return o}if(i&&!r.stack.has(i.name)){const a=new Map,o=new Map;i.parameters.forEach((u,f)=>{const l=s.args[f];a.set(u,l?we(l,r):null),o.set(u,l?le(l,r):null)});const c=Wa(i,e,{aliases:a,receiverTypes:o,functions:r.functions,service:e,stack:new Set([...r.stack,i.name])});if(c)return c}return null}case"methodCall":{if(s.object.type==="identifier"&&!r.aliases.has(s.object.name)){const u=(e==="cloud.firestore"?Hu:Gu)[s.object.name];if(u){if(!u.has(s.method))return`method '${s.object.name}.${s.method}()'`;for(const f of s.args){const l=n(f);if(l)return l}return null}return s.object.name==="firestore"?`method 'firestore.${s.method}()'`:`namespace '${s.object.name}'`}if(!(e==="cloud.firestore"?Vu:Wu).has(s.method))return`method '.${s.method}()'`;const a=Zu(s.object,s.method,e,r);if(a)return a;const o=Ku(s.object,s.method,s.args,e,r);return o||(n(s.object)??s.args.map(n).find(Boolean)??null)}case"binaryOp":return n(s.left)??n(s.right);case"unaryOp":return n(s.operand);case"bracketAccess":{const i=we(s.object,r);if(i==="unknown-ambient")return"binding '<derived ambient value>[...]'";const a=s.index.type==="literal"&&typeof s.index.value=="string";if(i&&!a)return Lr(e,i)?n(s.object)??n(s.index):`binding '${i.join(".")}[...]'`;const o=Mr(we(s,r),e);return o||(n(s.object)??n(s.index))}case"sliceAccess":return n(s.object)??n(s.start)??n(s.end);case"ternary":return n(s.condition)??n(s.consequent)??n(s.alternate);case"inExpr":return Ju(s.element,s.collection,e,r)??n(s.element)??n(s.collection);case"isExpr":return n(s.value);case"listLiteral":return s.elements.map(n).find(Boolean)??null;case"mapLiteral":for(const i of s.entries){const a=n(i.key)??n(i.value);if(a)return a}return null;case"pathLiteral":for(const i of s.segments)if(typeof i!="string"){const a=n(i);if(a)return a}return null;case"literal":return null;case"identifier":return s.name==="request"||s.name==="resource"||r.aliases.has(s.name)?null:`identifier '${s.name}'`;default:return Bu(s)}};return n(t)}function Wa(t,e,r){const n=new Map(r.aliases),s=new Map(r.receiverTypes),i={...r,aliases:n,receiverTypes:s};for(const a of t.lets){const o=si(a.value,e,i);if(o)return o;n.set(a.name,we(a.value,i)),s.set(a.name,le(a.value,i))}return si(t.body,e,i)}function Yu(t,e,r=new Map([[t.name,t]]),n=[]){const s={aliases:new Map,receiverTypes:new Map,functions:r,service:e,stack:new Set([t.name])};return Wa(t,e,{aliases:new Map(t.parameters.map((i,a)=>[i,a<n.length?n[a]?.provenance??null:null])),receiverTypes:new Map(t.parameters.map((i,a)=>[i,n[a]?le(n[a].expression,s)??n[a].receiverType??null:null])),functions:r,service:e,stack:new Set([t.name])})}function Qu(t){throw new Error(`Unhandled Rules expression: ${JSON.stringify(t)}`)}function Xu(t){return t.replace(/^\.\.\//,"_").replace(/^\.\//,"").replace(/[.\/-]/g,"_")}function re(t,e){switch(t.type){case"functionCall":{const r=e.get(t.name)??t.name,n=t.args.map(s=>re(s,e));return r===t.name&&n.every((s,i)=>s===t.args[i])?t:{...t,name:r,args:n}}case"binaryOp":{const r=re(t.left,e),n=re(t.right,e);return r===t.left&&n===t.right?t:{...t,left:r,right:n}}case"unaryOp":{const r=re(t.operand,e);return r===t.operand?t:{...t,operand:r}}case"methodCall":{const r=re(t.object,e),n=t.args.map(s=>re(s,e));return r===t.object&&n.every((s,i)=>s===t.args[i])?t:{...t,object:r,args:n}}case"memberAccess":{const r=re(t.object,e);return r===t.object?t:{...t,object:r}}case"bracketAccess":{const r=re(t.object,e),n=re(t.index,e);return r===t.object&&n===t.index?t:{...t,object:r,index:n}}case"sliceAccess":{const r=re(t.object,e),n=re(t.start,e),s=re(t.end,e);return r===t.object&&n===t.start&&s===t.end?t:{...t,object:r,start:n,end:s}}case"ternary":{const r=re(t.condition,e),n=re(t.consequent,e),s=re(t.alternate,e);return r===t.condition&&n===t.consequent&&s===t.alternate?t:{...t,condition:r,consequent:n,alternate:s}}case"inExpr":{const r=re(t.element,e),n=re(t.collection,e);return r===t.element&&n===t.collection?t:{...t,element:r,collection:n}}case"isExpr":{const r=re(t.value,e);return r===t.value?t:{...t,value:r}}case"listLiteral":{const r=t.elements.map(n=>re(n,e));return r.every((n,s)=>n===t.elements[s])?t:{...t,elements:r}}case"mapLiteral":{const r=t.entries.map(n=>{const s=re(n.key,e),i=re(n.value,e);return s===n.key&&i===n.value?n:{key:s,value:i}});return r.every((n,s)=>n===t.entries[s])?t:{...t,entries:r}}case"pathLiteral":{const r=t.segments.map(n=>typeof n=="string"?n:re(n,e));return r.every((n,s)=>n===t.segments[s])?t:{...t,segments:r}}case"literal":case"identifier":return t;default:return Qu(t)}}function el(t,e){const r=Xu(e),n=new Map;for(const s of t)s.exported||n.set(s.name,`${r}__${s.name}`);return n.size===0?t:t.map(s=>{const i=re(s.body,n),a=s.lets.map(c=>{const u=re(c.value,n);return u===c.value?c:{...c,value:u}}),o=s.exported?s.name:n.get(s.name)??s.name;return i===s.body&&a===s.lets&&o===s.name?s:{...s,name:o,body:i,lets:a}})}function tl(t){throw new Error(`Unhandled Rules expression: ${JSON.stringify(t)}`)}function xs(t){const e=[],r=n=>{switch(n.type){case"functionCall":e.push(n),n.args.forEach(r);break;case"binaryOp":r(n.left),r(n.right);break;case"unaryOp":r(n.operand);break;case"methodCall":r(n.object),n.args.forEach(r);break;case"memberAccess":r(n.object);break;case"bracketAccess":r(n.object),r(n.index);break;case"sliceAccess":r(n.object),r(n.start),r(n.end);break;case"ternary":r(n.condition),r(n.consequent),r(n.alternate);break;case"inExpr":r(n.element),r(n.collection);break;case"isExpr":r(n.value);break;case"listLiteral":n.elements.forEach(r);break;case"mapLiteral":n.entries.forEach(({key:s,value:i})=>{r(s),r(i)});break;case"pathLiteral":n.segments.forEach(s=>{typeof s!="string"&&r(s)});break;case"literal":case"identifier":break;default:tl(n)}};return r(t),e}function rl(t){return{expression:t.expression,provenance:t.provenance,receiverType:!t.receiverType||t.receiverType==="mixed"?"unknown":t.receiverType}}function nl(t,e){const r=[],n=new Map,s=t.service.name==="firebase.storage"?"firebase.storage":"cloud.firestore",i=(l,p=new Set)=>({aliases:new Map(l.aliases),receiverTypes:new Map(l.receiverTypes),functions:l.functions,service:s,stack:p,declarations:n}),a=(l,p,y)=>{if(y.has(l.name))return;const v=n.get(l);if(!v)return;const w=new Map(v.aliases),R=new Map(v.receiverTypes);l.parameters.forEach((k,x)=>{w.set(k,p[x]?.provenance??null),R.set(k,p[x]?.receiverType??null)});const C=i({aliases:w,receiverTypes:R,functions:v.functions},new Set([...y,l.name]));for(const k of l.lets){o(k.value,C);const x=Wt(k.value,C);C.aliases.set(k.name,x.provenance),C.receiverTypes.set(k.name,x.receiverType)}o(l.body,C)},o=(l,p)=>{for(const y of xs(l)){const v=y.args.map(R=>Wt(R,p));y.name===e&&r.push({arguments:v.map(rl)});const w=p.functions.get(y.name);w&&a(w,v,p.stack)}},c=new Map((t.functions??[]).map(l=>[l.name,l])),u=new Map(c);for(const l of t.service.functions??[])u.set(l.name,l);for(const l of t.functions??[])n.set(l,{aliases:new Map,receiverTypes:new Map,functions:c});for(const l of t.service.functions??[])n.set(l,{aliases:new Map,receiverTypes:new Map,functions:u});const f=(l,p)=>{const y=new Map(p.receiverTypes);for(const C of l.path.segments)C.type==="wildcard"&&y.set(C.name,"string"),C.type==="recursive"&&y.set(C.name,"path");const v=new Map(p.functions),w={aliases:p.aliases,receiverTypes:y,functions:v};for(const C of l.functions)v.set(C.name,C),n.set(C,w);const R=i(w);for(const{condition:C}of l.allows)o(C,R);l.children.forEach(C=>f(C,w))};return f(t.service.match,{aliases:new Map,receiverTypes:new Map,functions:u}),r}function _t(t){return xs(t).map(({name:e})=>e)}function sl(t,e){return[...t.values()].flatMap(n=>[...n.lets.map(({value:s})=>s),n.body]).flatMap(xs).filter(({name:n})=>n===e).map(({args:n})=>n)}function il(t,e,r){const n=Vc(t,e);return n===null?{success:!1,error:{code:"PARSE_FAILED",message:`Failed to parse module '${e}'`}}:{success:!0,functions:n,bundled:r}}function ii(t){return t.startsWith("./")||t.startsWith("../")}function Hn(t){return/^\.\/stdlib\/([A-Za-z0-9_-]+(?:\/[A-Za-z0-9_-]+)*)\.rules$/.exec(t)?.[1]??null}function al(t,e,r,n=new Set){if(r?.modules&&Object.prototype.hasOwnProperty.call(r.modules,e))return il(r.modules[e],e,n.has(e));if(ii(e)&&r?.basePath){const i=`${r.basePath}/${e}${e.endsWith(".rules")?"":".rules"}`;if(!Hn(e))return{success:!1,error:{code:"UNKNOWN_MODULE",message:`Module '${e}' not found at ${i}`}}}return Hn(e)?{success:!1,error:{code:"UNKNOWN_MODULE",message:`Module '${e}' not found`}}:ii(e)?{success:!1,error:{code:"UNKNOWN_MODULE",message:`Module '${e}' requires basePath for relative imports`}}:{success:!1,error:{code:"UNKNOWN_MODULE",message:`Module '${e}' not found`}}}function ol(t,e,r,n=new Set){const s=Or(e);if(!s.ok){const{line:M,column:z,message:ee}=s.error;return{success:!1,error:{code:"PARSE_FAILED",message:`Failed to parse source at line ${M}, col ${z}: ${ee}`}}}const i=s.ast,a=i.version==="2+modules",o=i.service.name==="firebase.storage";let c=o?"storage.rules":"firestore.rules";if(a&&(c=o?"storage.modules.rules":"firestore.modules.rules"),r!==void 0&&r.sourceFile!==void 0&&r.sourceFile!==""&&(c=r.sourceFile),cl(i,c),a===!1)return{success:!1,error:{code:"NOT_MODULE_SOURCE",message:`Version '${i.version}' is not a module source`}};if(i.service.name==="cloud.firestore"===!1&&i.service.name==="firebase.storage"===!1)return{success:!1,error:{code:"UNSUPPORTED_SERVICE",message:`Module resolution does not support service '${i.service.name}'`}};if(i.imports.length===0){i.version="2";const M=Pn(i),z=JSON.stringify(M.sourceMap);return{success:!0,data:{resolved:`${M.resolved}// @pyric-source-map: ${z}
478
+ `,modules:[],bundledModules:[],evidenceIds:[],sourceMap:M.sourceMap}}}const p=i.imports.find(M=>M.functions.length===0);if(p)return{success:!1,error:{code:"UNKNOWN_FUNCTION",message:`Import from '${p.module}' must request at least one function`}};const y=new Map,v=new Map,w=new Map,R=new Map,C=[],k=[],x=new Map;for(const M of i.imports){const z=al(t,M.module,r,n);if(!z.success)return{success:!1,error:z.error};C.includes(M.module)||C.push(M.module),z.bundled&&!k.includes(M.module)&&k.push(M.module);const ee=new Set,Te=z.functions.find(Z=>ee.has(Z.name)?!0:(ee.add(Z.name),!1));if(Te)return{success:!1,error:{code:"DUPLICATE_FUNCTION",message:`Module '${M.module}' defines duplicate function '${Te.name}'`}};const Q=z.functions.find(Z=>Ir.has(Z.name));if(Q)return{success:!1,error:{code:"DUPLICATE_FUNCTION",message:`Function '${Q.name}' from module '${M.module}' conflicts with a Rules builtin`}};const Be=new Set;for(const Z of z.functions)Z.exported||Be.add(Z.name);x.set(M.module,Be);const pn=el(z.functions,M.module),Fs=new Set;for(const Z of pn){if(Fs.has(Z.name))return{success:!1,error:{code:"DUPLICATE_FUNCTION",message:`Module '${M.module}' defines conflicting function name '${Z.name}'`}};Fs.add(Z.name)}const jo=new Set(pn.filter(Z=>Z.exported).map(Z=>Z.name));for(const Z of pn){const St=R.get(Z.name);if(St&&St!==M.module)return{success:!1,error:{code:"DUPLICATE_FUNCTION",message:`Function '${Z.name}' from module '${M.module}' conflicts with module '${St}'`}};if(R.set(Z.name,M.module),v.set(Z.name,Z),Z.exported){if(y.has(Z.name)&&w.get(Z.name)!==M.module)return{success:!1,error:{code:"DUPLICATE_FUNCTION",message:`Function '${Z.name}' exported by both '${w.get(Z.name)}' and '${M.module}'`}};y.set(Z.name,Z),w.set(Z.name,M.module)}}for(const Z of M.functions){if(!jo.has(Z))return{success:!1,error:{code:"UNKNOWN_FUNCTION",message:x.get(M.module)?.has(Z)?`Function '${Z}' in module '${M.module}' is not exported`:`Function '${Z}' not found in module '${M.module}'`}};if(i.service.name==="cloud.firestore"||i.service.name==="firebase.storage"){const St=z.bundled?Uu(i.service.name,M.module,Z):null;if(St)return{success:!1,error:{code:"INCOMPATIBLE_FUNCTION",message:St}}}}}const L=new Set(i.imports.flatMap(M=>M.functions)),$=[],S=new Set,T=[],_={cycle:null};function b(M){if(_.cycle)return;const z=T.indexOf(M);if(z>=0){_.cycle=[...T.slice(z),M];return}if(S.has(M))return;const ee=v.get(M);if(!ee)return;T.push(M);const Te=_t(ee.body);for(const Q of ee.lets)Te.push(..._t(Q.value));for(const Q of Te)v.has(Q)&&!Ir.has(Q)&&b(Q);T.pop(),!_.cycle&&(S.add(M),$.push({...ee,exported:!1}))}for(const M of i.imports)for(const z of M.functions)b(z);if(_.cycle)return{success:!1,error:{code:"CIRCULAR_DEPENDENCY",message:`Recursive module function dependency: ${_.cycle.join(" -> ")}`}};for(const M of $){const z=R.get(M.name),Te=[...M.lets.flatMap(({value:Q})=>_t(Q)),..._t(M.body)].find(Q=>{const Be=R.get(Q);return Be&&Be!==z&&!L.has(Q)});if(Te)return{success:!1,error:{code:"UNKNOWN_FUNCTION",message:`Function '${M.name}' in module '${z}' cannot call '${Te}' from another module`}}}const A=new Set($.map(M=>M.name)),I=new Map((i.functions??[]).map(M=>[M.name,M])),h=new Set((i.service.functions??[]).map(M=>M.name)),d=(M,z)=>M.flatMap(_t).find(ee=>y.has(ee)&&!A.has(ee)&&!z.has(ee))??null,g=M=>M.flatMap(z=>[...z.lets.map(({value:ee})=>ee),z.body]),m=new Set(I.keys());let F=d(g(i.functions??[]),m);const E=new Set([...m,...h]);F??=d(g(i.service.functions??[]),E);const O=(M,z)=>{const ee=new Set([...z,...M.functions.map(Q=>Q.name)]),Te=[...g(M.functions),...M.allows.map(({condition:Q})=>Q)];return d(Te,ee)??M.children.map(Q=>O(Q,ee)).find(Boolean)??null};if(F??=O(i.service.match,E),F)return{success:!1,error:{code:"UNKNOWN_FUNCTION",message:`Source calls function '${F}' from module '${w.get(F)}' without importing it`}};const D=(M,z)=>{if(z.has(M.name))return!1;const ee=new Set([...z,M.name]);return[...M.lets.flatMap(({value:Q})=>_t(Q)),..._t(M.body)].some(Q=>{const Be=I.get(Q);return Be?D(Be,ee):A.has(Q)||h.has(Q)})},Y=[...I.values()].find(M=>D(M,new Set));if(Y)return{success:!1,error:{code:"INCOMPATIBLE_FUNCTION",message:`Global function '${Y.name}' cannot call a service-scoped function`}};if(i.service.name==="firebase.storage"||i.service.name==="cloud.firestore"){const M=new Map($.map(z=>[z.name,z]));for(const z of $){const ee=[...nl(i,z.name),...sl(M,z.name).map(Q=>({arguments:Q.map(Be=>({expression:Be,provenance:null,receiverType:"unknown"}))}))],Te=ee.length>0?ee:[{arguments:[]}];for(const{arguments:Q}of Te){const Be=Yu(z,i.service.name,v,Q);if(Be)return{success:!1,error:{code:"INCOMPATIBLE_FUNCTION",message:`Function '${z.name}' requires unsupported ${Be} for service '${i.service.name}'`}}}}}const Ee=new Set([...(i.functions??[]).map(M=>M.name),...(i.service.functions??[]).map(M=>M.name)]),ze=M=>{M.functions.forEach(z=>Ee.add(z.name)),M.children.forEach(ze)};ze(i.service.match);const Pt=[...Ee].find(M=>Ir.has(M));if(Pt)return{success:!1,error:{code:"DUPLICATE_FUNCTION",message:`Source function '${Pt}' conflicts with a Rules builtin`}};for(const M of $)if(Ee.has(M.name))return{success:!1,error:{code:"DUPLICATE_FUNCTION",message:`Imported function '${M.name}' conflicts with a function defined in the source`}};i.service.functions=[...$,...i.service.functions??[]],i.version="2",i.imports=[];const $t=new Set,Ut=i.service.name==="firebase.storage"?"storage-rules#":"firestore-rules#";for(const M of k){const z=Hn(M)??M,ee=Eu[z]??[];for(const Te of ee)Te.startsWith(Ut)&&$t.add(Te)}const fn=Pn(i),Fo=JSON.stringify(fn.sourceMap);return{success:!0,data:{resolved:`${fn.resolved}// @pyric-source-map: ${Fo}
479
+ `,modules:C,bundledModules:k,evidenceIds:[...$t].sort(),sourceMap:fn.sourceMap}}}function cl(t,e){if(t.functions!==void 0)for(const a of t.functions)a.loc!==void 0&&(a.loc.file=e);if(t.service.functions!==void 0)for(const a of t.service.functions)a.loc!==void 0&&(a.loc.file=e);const s=[t.service.match];let i=s.length;for(;i>0;){const a=s.pop();a.loc!==void 0&&(a.loc.file=e);for(const c of a.allows)c.loc!==void 0&&(c.loc.file=e);for(const c of a.functions)c.loc!==void 0&&(c.loc.file=e);for(const c of a.children)s.push(c);i=s.length}}function Ga(t,e,r,n,s){if(e===void 0)return;let a=e,o=1;r!==void 0&&(o=r);let u="firestore.rules";n!==void 0&&n!==""&&(u=n);let l;s!==void 0&&(l=s);const y="// @pyric-source-map: ",v=t.indexOf(y);if(v!==-1){const x=v+y.length,L=t.indexOf(`
480
+ `,x);let $="";L!==-1?$=t.slice(x,L).trim():$=t.slice(x).trim();try{const T=JSON.parse($);if(Array.isArray(T)){for(const b of T)if(b.generatedLine===a){a=b.authoredLine,o=b.authoredCol,u=b.authoredFile,b.expression!==void 0&&(l=b.expression);break}}}catch{}}const R=`${u}:${a}:${o}`,C={line:a,col:o,file:u,citation:R};return l!==void 0&&(C.expression=l),C}const oe=Symbol.for("pyric.RulesValue.NO_OP");class te{field(e){return null}callMethod(e,r){return oe}binaryOp(e,r){return oe}}function me(t,e){if(Object.is(t,e))return!0;if(t instanceof te)return t.equals(e);if(e instanceof te)return e.equals(t);if(t instanceof de||e instanceof de)return t instanceof de&&t.equals(e);if(Array.isArray(t)||Array.isArray(e))return!Array.isArray(t)||!Array.isArray(e)||t.length!==e.length?!1:t.every((s,i)=>me(s,e[i]));if(!ai(t)||!ai(e))return!1;const r=Object.keys(t),n=Object.keys(e);return r.length!==n.length?!1:r.every(s=>s in e&&me(t[s],e[s]))}function ai(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}class de{items;constructor(e){this.items=[];for(const r of e)this.items.some(n=>me(n,r))||this.items.push(r)}hasOnly(e){const r=e instanceof de?e.toArray():e;return this.items.every(n=>r.some(s=>me(n,s)))}equals(e){return!(e instanceof de)||e.items.length!==this.items.length?!1:this.items.every(r=>e.items.some(n=>me(r,n)))}hasAll(e){const r=e instanceof de?e.toArray():e;for(const n of r)if(!this.items.some(s=>me(s,n)))return!1;return!0}hasAny(e){const r=e instanceof de?e.toArray():e;for(const n of r)if(this.items.some(s=>me(s,n)))return!0;return!1}size(){return this.items.length}toArray(){return[...this.items]}difference(e){const r=e.toArray(),n=[];for(const s of this.items)r.some(i=>me(s,i))||n.push(s);return new de(n)}union(e){const r=e.toArray();return new de([...this.items,...r])}intersection(e){const r=e.toArray(),n=[];for(const s of this.items)r.some(i=>me(s,i))&&n.push(s);return new de(n)}}class cr{before;after;constructor(e,r){this.before=e,this.after=r}addedKeys(){const e=[];for(const r of Object.keys(this.after))r in this.before||e.push(r);return new de(e)}removedKeys(){const e=[];for(const r of Object.keys(this.before))r in this.after||e.push(r);return new de(e)}changedKeys(){const e=[];for(const r of Object.keys(this.after))r in this.before&&!me(this.before[r],this.after[r])&&e.push(r);return new de(e)}affectedKeys(){const e=[],r=new Set([...Object.keys(this.before),...Object.keys(this.after)]);for(const n of r)(!(n in this.before)||!(n in this.after)||!me(this.before[n],this.after[n]))&&e.push(n);return new de(e)}unchangedKeys(){const e=[];for(const r of Object.keys(this.before))r in this.after&&me(this.before[r],this.after[r])&&e.push(r);return new de(e)}}const ul=/^\{([A-Za-z_][A-Za-z0-9_]*)\}$/;class Qe extends te{typeName="path";segments;bindings;constructor(e,r={}){super(),this.segments=e,this.bindings=r}static fromString(e){const r=e.startsWith("/")?e.slice(1):e;return r.length===0?new Qe([]):new Qe(r.split("/"))}bind(e){const r=[],n={...this.bindings};for(const s of this.segments){const i=s.match(ul);if(!i){r.push(s);continue}const a=i[1];if(a in e){const o=e[a];if(o==null)throw new TypeError(`Path.bind(): binding '${a}' must not be null`);const c=String(o);r.push(c),n[a]=c}else r.push(s)}return new Qe(r,n)}valueOf(){return NaN}toString(){return"/"+this.segments.join("/")}toJSON(){return{__type:"path",segments:[...this.segments]}}equals(e){if(!(e instanceof Qe)||this.segments.length!==e.segments.length)return!1;for(let r=0;r<this.segments.length;r++)if(this.segments[r]!==e.segments[r])return!1;return!0}field(e){if(/^\d+$/.test(e)){const r=Number(e);return r<0||r>=this.segments.length?null:this.segments[r]}return e in this.bindings?this.bindings[e]:null}callMethod(e,r){switch(e){case"bind":{const n=r[0];if(n==null||typeof n!="object"||Array.isArray(n)||n instanceof te)throw new TypeError(`Path.bind() requires a Map argument, got ${n===null?"null":typeof n}`);return this.bind(n)}default:return oe}}}class ae extends te{typeName="float";value;constructor(e){super(),this.value=e}valueOf(){return this.value}toString(){return Number.isInteger(this.value)?`${this.value}.0`:String(this.value)}toJSON(){return{__type:"float",value:this.value}}equals(e){return e instanceof ae?this.value===e.value:typeof e=="number"?this.value===e:!1}binaryOp(e,r){const n=r instanceof ae?r.value:typeof r=="number"?r:void 0;if(n===void 0)return oe;const s=this.value;switch(e){case"+":return new ae(s+n);case"-":return new ae(s-n);case"*":return new ae(s*n);case"/":return new ae(s/n);case"%":return new ae(s%n);case"<":return s<n;case"<=":return s<=n;case">":return s>n;case">=":return s>=n;default:return oe}}}class G extends Error{expr;constructor(e,r){super(e),this.expr=r,this.name="EvalError"}}class gt extends G{constructor(e,r){super(e,r),this.name="UnsupportedError"}}class ll{entries=[];parents=[];frames=[];capture(e,r){const n=this.entries.length,s=this.parents.length>0?this.parents[this.parents.length-1]:null,i={source:ye(e),kind:e.type,parent:s};this.stampFrame(i),this.entries.push(i),this.parents.push(n);try{const a=r();return this.entries[n].value=a,a}catch(a){throw this.entries[n].error=a instanceof Error?a.message:String(a),a}finally{this.parents.pop()}}skip(e){const r=this.parents.length>0?this.parents[this.parents.length-1]:null,n={source:ye(e),kind:e.type,parent:r,skipped:!0};this.stampFrame(n),this.entries.push(n)}enterFrame(e){this.frames.push(e)}exitFrame(){this.frames.pop()}markEntryAsLetBinding(e,r){e<0||e>=this.entries.length||(this.entries[e].letBinding={name:r})}stampFrame(e){this.frames.length!==0&&(e.inlinedFrom={name:this.frames[this.frames.length-1]})}}function dl(t,e,r,n){const i=p=>p*Math.PI/180,a=i(t),o=i(r),c=i(r-t),u=i(n-e),f=Math.sin(c/2)**2+Math.cos(a)*Math.cos(o)*Math.sin(u/2)**2;return 6371e3*(2*Math.atan2(Math.sqrt(f),Math.sqrt(1-f)))}class lt extends te{typeName="latlng";lat;lng;constructor(e,r){super(),this.lat=e,this.lng=r}valueOf(){return NaN}toString(){return`${this.lat},${this.lng}`}toJSON(){return{__type:"latlng",lat:this.lat,lng:this.lng}}equals(e){return e instanceof lt&&this.lat===e.lat&&this.lng===e.lng}callMethod(e,r){switch(e){case"latitude":return this.lat;case"longitude":return this.lng;case"distance":{const n=r[0];if(!(n instanceof lt))throw new TypeError(`latlng.distance() requires a LatLng argument, got ${typeof n}`);return dl(this.lat,this.lng,n.lat,n.lng)}default:return oe}}}const zt=1e9,oi={w:10080*60,d:1440*60,h:3600,m:60,s:1};function hl(t,e){let r=t+Math.trunc(e/zt),n=e%zt;return r>0&&n<0?(r-=1,n+=zt):r<0&&n>0&&(r+=1,n-=zt),{seconds:r,nanos:n}}class ve extends te{typeName="duration";seconds;nanos;constructor(e,r){super();const n=hl(e,r);this.seconds=n.seconds,this.nanos=n.nanos}static fromValue(e,r){if(r in oi)return new ve(e*oi[r],0);if(r==="ms"){const n=Math.trunc(e/1e3),s=e-n*1e3;return new ve(n,s*1e6)}if(r==="ns"){const n=Math.trunc(e/zt),s=e-n*zt;return new ve(n,s)}throw new Error(`Unknown duration unit '${r}' (expected one of: w, d, h, m, s, ms, ns)`)}static fromTime(e,r,n,s){return new ve(e*3600+r*60+n,s)}static abs(e){return new ve(Math.abs(e.seconds),Math.abs(e.nanos))}valueOf(){return this.seconds*1e3+Math.round(this.nanos/1e6)}toString(){const e=this.seconds<0||this.nanos<0,r=Math.abs(this.seconds),n=Math.abs(this.nanos);return`${e?"-":""}${r}.${n.toString().padStart(9,"0")}s`}toJSON(){return{__type:"duration",seconds:this.seconds,nanos:this.nanos}}equals(e){return e instanceof ve&&this.seconds===e.seconds&&this.nanos===e.nanos}callMethod(e,r){switch(e){case"seconds":return this.seconds;case"nanos":return this.nanos;default:return oe}}binaryOp(e,r){if(!(r instanceof ve))return oe;switch(e){case"+":return new ve(this.seconds+r.seconds,this.nanos+r.nanos);case"-":return new ve(this.seconds-r.seconds,this.nanos-r.nanos);case"<":return this.compareTo(r)<0;case"<=":return this.compareTo(r)<=0;case">":return this.compareTo(r)>0;case">=":return this.compareTo(r)>=0;default:return oe}}compareTo(e){return this.seconds!==e.seconds?this.seconds-e.seconds:this.nanos-e.nanos}}const ci=1e9,fl=864e5,bn=86400;function pl(t,e){const r=Math.floor(e/ci);return{seconds:t+r,nanos:e-r*ci}}let _e=class nt extends te{typeName="timestamp";seconds;nanos;constructor(e,r){super();const n=pl(e,r);this.seconds=n.seconds,this.nanos=n.nanos}static fromMillis(e){const r=Math.floor(e/1e3),n=e-r*1e3;return new nt(r,n*1e6)}static fromYMD(e,r,n){return nt.fromMillis(Date.UTC(e,r-1,n))}static fromIsoString(e){return nt.fromMillis(Date.parse(e))}toMillis(){return this.seconds*1e3+Math.floor(this.nanos/1e6)}toDate(){return new Date(this.toMillis())}valueOf(){return this.toMillis()}toString(){const e=new Date(this.toMillis()).toISOString(),r=this.nanos.toString().padStart(9,"0");return e.replace(/\.\d{3}Z$/,`.${r}Z`)}toJSON(){return{__type:"timestamp",seconds:this.seconds,nanos:this.nanos}}equals(e){return e instanceof nt&&this.seconds===e.seconds&&this.nanos===e.nanos}callMethod(e,r){switch(e){case"seconds":return this.seconds;case"nanos":return this.nanos;case"toMillis":return this.toMillis();case"year":return this.asDate().getUTCFullYear();case"month":return this.asDate().getUTCMonth()+1;case"day":return this.asDate().getUTCDate();case"hours":return this.asDate().getUTCHours();case"minutes":return this.asDate().getUTCMinutes();case"dayOfWeek":{const n=this.asDate().getUTCDay();return n===0?7:n}case"dayOfYear":{const n=this.asDate(),s=Date.UTC(n.getUTCFullYear(),0,1);return Math.floor((this.toMillis()-s)/fl)+1}case"date":return nt.fromYMD(this.asDate().getUTCFullYear(),this.asDate().getUTCMonth()+1,this.asDate().getUTCDate());case"time":{const n=(this.seconds%bn+bn)%bn,s=Math.floor(n/3600),i=Math.floor(n%3600/60),a=n%60;return ve.fromTime(s,i,a,this.nanos)}default:return oe}}asDate(){return new Date(this.toMillis())}binaryOp(e,r){if(r instanceof nt)switch(e){case"-":return new ve(this.seconds-r.seconds,this.nanos-r.nanos);case"<":return this.compareTo(r)<0;case"<=":return this.compareTo(r)<=0;case">":return this.compareTo(r)>0;case">=":return this.compareTo(r)>=0;default:return oe}if(r instanceof ve)switch(e){case"+":return new nt(this.seconds+r.seconds,this.nanos+r.nanos);case"-":return new nt(this.seconds-r.seconds,this.nanos-r.nanos);default:return oe}return oe}compareTo(e){return this.seconds!==e.seconds?this.seconds-e.seconds:this.nanos-e.nanos}};const ui="0123456789ABCDEF";function ml(t){let e="";for(let r=0;r<t.length;r++){const n=t[r];e+=ui[n>>>4]+ui[n&15]}return e}function gl(t){let e="";for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_")}function yl(t,e){const r=Math.min(t.length,e.length);for(let n=0;n<r;n++)if(t[n]!==e[n])return t[n]<e[n]?-1:1;return t.length===e.length?0:t.length<e.length?-1:1}class Ae extends te{typeName="bytes";data;constructor(e){super(),this.data=e}static fromUtf8(e){return new Ae(new TextEncoder().encode(e))}static fromHex(e){if(e.length%2!==0)throw new Error(`Invalid hex string length: ${e.length}`);const r=new Uint8Array(e.length/2);for(let n=0;n<r.length;n++)r[n]=parseInt(e.substr(n*2,2),16);return new Ae(r)}size(){return this.data.length}toBase64(){return gl(this.data)}toHexString(){return ml(this.data)}valueOf(){return this.data.length}toString(){return this.toBase64()}toJSON(){return{__type:"bytes",base64:this.toBase64()}}equals(e){if(!(e instanceof Ae)||this.data.length!==e.data.length)return!1;for(let r=0;r<this.data.length;r++)if(this.data[r]!==e.data[r])return!1;return!0}callMethod(e,r){switch(e){case"size":return this.size();case"toBase64":return this.toBase64();case"toHexString":return this.toHexString()}return oe}binaryOp(e,r){if(!(r instanceof Ae))return oe;const n=yl(this.data,r.data);switch(e){case"<":return n<0;case"<=":return n<=0;case">":return n>0;case">=":return n>=0}return oe}}function ur(t){return t.replace(/\$\(database\)/g,"(default)").replace(/^\/databases\/\(default\)\/documents\//,"")}function Wn(t,e){const r=t.split("/").filter(Boolean);return{data:e,id:r.at(-1)??"",__name__:new Qe(["databases","(default)","documents",...r])}}function li(t,e){const r=ur(t);let n=e.mockDocuments.get(r);if(!n&&e.getDoc){const s=e.getDoc(r);s&&(e.mockDocuments.set(r,s),n=s)}if(n)return e.identitylessFunctionMocks?.has(r)?{data:n}:Wn(r,n);throw new G(`get() of non-existent document '${r}' (guard with exists() first)`)}function di(t,e){const r=ur(t);if(e.mockDocuments.has(r))return!0;if(e.getDoc){const n=e.getDoc(r);if(n)return e.mockDocuments.set(r,n),!0}return!1}var wn={exports:{}};const vl={},bl=Object.freeze(Object.defineProperty({__proto__:null,default:vl},Symbol.toStringTag,{value:"Module"})),Dr=qo(bl);/**
481
+ * [js-md5]{@link https://github.com/emn178/js-md5}
482
+ *
483
+ * @namespace md5
484
+ * @version 0.8.3
485
+ * @author Chen, Yi-Cyuan [emn178@gmail.com]
486
+ * @copyright Chen, Yi-Cyuan 2014-2023
487
+ * @license MIT
488
+ */var hi;function wl(){return hi||(hi=1,(function(t){(function(){var e="input is invalid type",r="finalize already called",n=typeof window=="object",s=n?window:{};s.JS_MD5_NO_WINDOW&&(n=!1);var i=!n&&typeof self=="object",a=!s.JS_MD5_NO_NODE_JS&&typeof process=="object"&&process.versions&&process.versions.node;a?s=oa:i&&(s=self);var o=!s.JS_MD5_NO_COMMON_JS&&!0&&t.exports,c=!s.JS_MD5_NO_ARRAY_BUFFER&&typeof ArrayBuffer<"u",u="0123456789abcdef".split(""),f=[128,32768,8388608,-2147483648],l=[0,8,16,24],p=["hex","array","digest","buffer","arrayBuffer","base64"],y="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),v=[],w;if(c){var R=new ArrayBuffer(68);w=new Uint8Array(R),v=new Uint32Array(R)}var C=Array.isArray;(s.JS_MD5_NO_NODE_JS||!C)&&(C=function(h){return Object.prototype.toString.call(h)==="[object Array]"});var k=ArrayBuffer.isView;c&&(s.JS_MD5_NO_ARRAY_BUFFER_IS_VIEW||!k)&&(k=function(h){return typeof h=="object"&&h.buffer&&h.buffer.constructor===ArrayBuffer});var x=function(h){var d=typeof h;if(d==="string")return[h,!0];if(d!=="object"||h===null)throw new Error(e);if(c&&h.constructor===ArrayBuffer)return[new Uint8Array(h),!1];if(!C(h)&&!k(h))throw new Error(e);return[h,!1]},L=function(h){return function(d){return new b(!0).update(d)[h]()}},$=function(){var h=L("hex");a&&(h=S(h)),h.create=function(){return new b},h.update=function(m){return h.create().update(m)};for(var d=0;d<p.length;++d){var g=p[d];h[g]=L(g)}return h},S=function(h){var d=Dr,g=Dr.Buffer,m;g.from&&!s.JS_MD5_NO_BUFFER_FROM?m=g.from:m=function(E){return new g(E)};var F=function(E){if(typeof E=="string")return d.createHash("md5").update(E,"utf8").digest("hex");if(E==null)throw new Error(e);return E.constructor===ArrayBuffer&&(E=new Uint8Array(E)),C(E)||k(E)||E.constructor===g?d.createHash("md5").update(m(E)).digest("hex"):h(E)};return F},T=function(h){return function(d,g){return new A(d,!0).update(g)[h]()}},_=function(){var h=T("hex");h.create=function(m){return new A(m)},h.update=function(m,F){return h.create(m).update(F)};for(var d=0;d<p.length;++d){var g=p[d];h[g]=T(g)}return h};function b(h){if(h)v[0]=v[16]=v[1]=v[2]=v[3]=v[4]=v[5]=v[6]=v[7]=v[8]=v[9]=v[10]=v[11]=v[12]=v[13]=v[14]=v[15]=0,this.blocks=v,this.buffer8=w;else if(c){var d=new ArrayBuffer(68);this.buffer8=new Uint8Array(d),this.blocks=new Uint32Array(d)}else this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];this.h0=this.h1=this.h2=this.h3=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0}b.prototype.update=function(h){if(this.finalized)throw new Error(r);var d=x(h);h=d[0];for(var g=d[1],m,F=0,E,O=h.length,D=this.blocks,Y=this.buffer8;F<O;){if(this.hashed&&(this.hashed=!1,D[0]=D[16],D[16]=D[1]=D[2]=D[3]=D[4]=D[5]=D[6]=D[7]=D[8]=D[9]=D[10]=D[11]=D[12]=D[13]=D[14]=D[15]=0),g)if(c)for(E=this.start;F<O&&E<64;++F)m=h.charCodeAt(F),m<128?Y[E++]=m:m<2048?(Y[E++]=192|m>>>6,Y[E++]=128|m&63):m<55296||m>=57344?(Y[E++]=224|m>>>12,Y[E++]=128|m>>>6&63,Y[E++]=128|m&63):(m=65536+((m&1023)<<10|h.charCodeAt(++F)&1023),Y[E++]=240|m>>>18,Y[E++]=128|m>>>12&63,Y[E++]=128|m>>>6&63,Y[E++]=128|m&63);else for(E=this.start;F<O&&E<64;++F)m=h.charCodeAt(F),m<128?D[E>>>2]|=m<<l[E++&3]:m<2048?(D[E>>>2]|=(192|m>>>6)<<l[E++&3],D[E>>>2]|=(128|m&63)<<l[E++&3]):m<55296||m>=57344?(D[E>>>2]|=(224|m>>>12)<<l[E++&3],D[E>>>2]|=(128|m>>>6&63)<<l[E++&3],D[E>>>2]|=(128|m&63)<<l[E++&3]):(m=65536+((m&1023)<<10|h.charCodeAt(++F)&1023),D[E>>>2]|=(240|m>>>18)<<l[E++&3],D[E>>>2]|=(128|m>>>12&63)<<l[E++&3],D[E>>>2]|=(128|m>>>6&63)<<l[E++&3],D[E>>>2]|=(128|m&63)<<l[E++&3]);else if(c)for(E=this.start;F<O&&E<64;++F)Y[E++]=h[F];else for(E=this.start;F<O&&E<64;++F)D[E>>>2]|=h[F]<<l[E++&3];this.lastByteIndex=E,this.bytes+=E-this.start,E>=64?(this.start=E-64,this.hash(),this.hashed=!0):this.start=E}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this},b.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var h=this.blocks,d=this.lastByteIndex;h[d>>>2]|=f[d&3],d>=56&&(this.hashed||this.hash(),h[0]=h[16],h[16]=h[1]=h[2]=h[3]=h[4]=h[5]=h[6]=h[7]=h[8]=h[9]=h[10]=h[11]=h[12]=h[13]=h[14]=h[15]=0),h[14]=this.bytes<<3,h[15]=this.hBytes<<3|this.bytes>>>29,this.hash()}},b.prototype.hash=function(){var h,d,g,m,F,E,O=this.blocks;this.first?(h=O[0]-680876937,h=(h<<7|h>>>25)-271733879<<0,m=(-1732584194^h&2004318071)+O[1]-117830708,m=(m<<12|m>>>20)+h<<0,g=(-271733879^m&(h^-271733879))+O[2]-1126478375,g=(g<<17|g>>>15)+m<<0,d=(h^g&(m^h))+O[3]-1316259209,d=(d<<22|d>>>10)+g<<0):(h=this.h0,d=this.h1,g=this.h2,m=this.h3,h+=(m^d&(g^m))+O[0]-680876936,h=(h<<7|h>>>25)+d<<0,m+=(g^h&(d^g))+O[1]-389564586,m=(m<<12|m>>>20)+h<<0,g+=(d^m&(h^d))+O[2]+606105819,g=(g<<17|g>>>15)+m<<0,d+=(h^g&(m^h))+O[3]-1044525330,d=(d<<22|d>>>10)+g<<0),h+=(m^d&(g^m))+O[4]-176418897,h=(h<<7|h>>>25)+d<<0,m+=(g^h&(d^g))+O[5]+1200080426,m=(m<<12|m>>>20)+h<<0,g+=(d^m&(h^d))+O[6]-1473231341,g=(g<<17|g>>>15)+m<<0,d+=(h^g&(m^h))+O[7]-45705983,d=(d<<22|d>>>10)+g<<0,h+=(m^d&(g^m))+O[8]+1770035416,h=(h<<7|h>>>25)+d<<0,m+=(g^h&(d^g))+O[9]-1958414417,m=(m<<12|m>>>20)+h<<0,g+=(d^m&(h^d))+O[10]-42063,g=(g<<17|g>>>15)+m<<0,d+=(h^g&(m^h))+O[11]-1990404162,d=(d<<22|d>>>10)+g<<0,h+=(m^d&(g^m))+O[12]+1804603682,h=(h<<7|h>>>25)+d<<0,m+=(g^h&(d^g))+O[13]-40341101,m=(m<<12|m>>>20)+h<<0,g+=(d^m&(h^d))+O[14]-1502002290,g=(g<<17|g>>>15)+m<<0,d+=(h^g&(m^h))+O[15]+1236535329,d=(d<<22|d>>>10)+g<<0,h+=(g^m&(d^g))+O[1]-165796510,h=(h<<5|h>>>27)+d<<0,m+=(d^g&(h^d))+O[6]-1069501632,m=(m<<9|m>>>23)+h<<0,g+=(h^d&(m^h))+O[11]+643717713,g=(g<<14|g>>>18)+m<<0,d+=(m^h&(g^m))+O[0]-373897302,d=(d<<20|d>>>12)+g<<0,h+=(g^m&(d^g))+O[5]-701558691,h=(h<<5|h>>>27)+d<<0,m+=(d^g&(h^d))+O[10]+38016083,m=(m<<9|m>>>23)+h<<0,g+=(h^d&(m^h))+O[15]-660478335,g=(g<<14|g>>>18)+m<<0,d+=(m^h&(g^m))+O[4]-405537848,d=(d<<20|d>>>12)+g<<0,h+=(g^m&(d^g))+O[9]+568446438,h=(h<<5|h>>>27)+d<<0,m+=(d^g&(h^d))+O[14]-1019803690,m=(m<<9|m>>>23)+h<<0,g+=(h^d&(m^h))+O[3]-187363961,g=(g<<14|g>>>18)+m<<0,d+=(m^h&(g^m))+O[8]+1163531501,d=(d<<20|d>>>12)+g<<0,h+=(g^m&(d^g))+O[13]-1444681467,h=(h<<5|h>>>27)+d<<0,m+=(d^g&(h^d))+O[2]-51403784,m=(m<<9|m>>>23)+h<<0,g+=(h^d&(m^h))+O[7]+1735328473,g=(g<<14|g>>>18)+m<<0,d+=(m^h&(g^m))+O[12]-1926607734,d=(d<<20|d>>>12)+g<<0,F=d^g,h+=(F^m)+O[5]-378558,h=(h<<4|h>>>28)+d<<0,m+=(F^h)+O[8]-2022574463,m=(m<<11|m>>>21)+h<<0,E=m^h,g+=(E^d)+O[11]+1839030562,g=(g<<16|g>>>16)+m<<0,d+=(E^g)+O[14]-35309556,d=(d<<23|d>>>9)+g<<0,F=d^g,h+=(F^m)+O[1]-1530992060,h=(h<<4|h>>>28)+d<<0,m+=(F^h)+O[4]+1272893353,m=(m<<11|m>>>21)+h<<0,E=m^h,g+=(E^d)+O[7]-155497632,g=(g<<16|g>>>16)+m<<0,d+=(E^g)+O[10]-1094730640,d=(d<<23|d>>>9)+g<<0,F=d^g,h+=(F^m)+O[13]+681279174,h=(h<<4|h>>>28)+d<<0,m+=(F^h)+O[0]-358537222,m=(m<<11|m>>>21)+h<<0,E=m^h,g+=(E^d)+O[3]-722521979,g=(g<<16|g>>>16)+m<<0,d+=(E^g)+O[6]+76029189,d=(d<<23|d>>>9)+g<<0,F=d^g,h+=(F^m)+O[9]-640364487,h=(h<<4|h>>>28)+d<<0,m+=(F^h)+O[12]-421815835,m=(m<<11|m>>>21)+h<<0,E=m^h,g+=(E^d)+O[15]+530742520,g=(g<<16|g>>>16)+m<<0,d+=(E^g)+O[2]-995338651,d=(d<<23|d>>>9)+g<<0,h+=(g^(d|~m))+O[0]-198630844,h=(h<<6|h>>>26)+d<<0,m+=(d^(h|~g))+O[7]+1126891415,m=(m<<10|m>>>22)+h<<0,g+=(h^(m|~d))+O[14]-1416354905,g=(g<<15|g>>>17)+m<<0,d+=(m^(g|~h))+O[5]-57434055,d=(d<<21|d>>>11)+g<<0,h+=(g^(d|~m))+O[12]+1700485571,h=(h<<6|h>>>26)+d<<0,m+=(d^(h|~g))+O[3]-1894986606,m=(m<<10|m>>>22)+h<<0,g+=(h^(m|~d))+O[10]-1051523,g=(g<<15|g>>>17)+m<<0,d+=(m^(g|~h))+O[1]-2054922799,d=(d<<21|d>>>11)+g<<0,h+=(g^(d|~m))+O[8]+1873313359,h=(h<<6|h>>>26)+d<<0,m+=(d^(h|~g))+O[15]-30611744,m=(m<<10|m>>>22)+h<<0,g+=(h^(m|~d))+O[6]-1560198380,g=(g<<15|g>>>17)+m<<0,d+=(m^(g|~h))+O[13]+1309151649,d=(d<<21|d>>>11)+g<<0,h+=(g^(d|~m))+O[4]-145523070,h=(h<<6|h>>>26)+d<<0,m+=(d^(h|~g))+O[11]-1120210379,m=(m<<10|m>>>22)+h<<0,g+=(h^(m|~d))+O[2]+718787259,g=(g<<15|g>>>17)+m<<0,d+=(m^(g|~h))+O[9]-343485551,d=(d<<21|d>>>11)+g<<0,this.first?(this.h0=h+1732584193<<0,this.h1=d-271733879<<0,this.h2=g-1732584194<<0,this.h3=m+271733878<<0,this.first=!1):(this.h0=this.h0+h<<0,this.h1=this.h1+d<<0,this.h2=this.h2+g<<0,this.h3=this.h3+m<<0)},b.prototype.hex=function(){this.finalize();var h=this.h0,d=this.h1,g=this.h2,m=this.h3;return u[h>>>4&15]+u[h&15]+u[h>>>12&15]+u[h>>>8&15]+u[h>>>20&15]+u[h>>>16&15]+u[h>>>28&15]+u[h>>>24&15]+u[d>>>4&15]+u[d&15]+u[d>>>12&15]+u[d>>>8&15]+u[d>>>20&15]+u[d>>>16&15]+u[d>>>28&15]+u[d>>>24&15]+u[g>>>4&15]+u[g&15]+u[g>>>12&15]+u[g>>>8&15]+u[g>>>20&15]+u[g>>>16&15]+u[g>>>28&15]+u[g>>>24&15]+u[m>>>4&15]+u[m&15]+u[m>>>12&15]+u[m>>>8&15]+u[m>>>20&15]+u[m>>>16&15]+u[m>>>28&15]+u[m>>>24&15]},b.prototype.toString=b.prototype.hex,b.prototype.digest=function(){this.finalize();var h=this.h0,d=this.h1,g=this.h2,m=this.h3;return[h&255,h>>>8&255,h>>>16&255,h>>>24&255,d&255,d>>>8&255,d>>>16&255,d>>>24&255,g&255,g>>>8&255,g>>>16&255,g>>>24&255,m&255,m>>>8&255,m>>>16&255,m>>>24&255]},b.prototype.array=b.prototype.digest,b.prototype.arrayBuffer=function(){this.finalize();var h=new ArrayBuffer(16),d=new Uint32Array(h);return d[0]=this.h0,d[1]=this.h1,d[2]=this.h2,d[3]=this.h3,h},b.prototype.buffer=b.prototype.arrayBuffer,b.prototype.base64=function(){for(var h,d,g,m="",F=this.array(),E=0;E<15;)h=F[E++],d=F[E++],g=F[E++],m+=y[h>>>2]+y[(h<<4|d>>>4)&63]+y[(d<<2|g>>>6)&63]+y[g&63];return h=F[E],m+=y[h>>>2]+y[h<<4&63]+"==",m};function A(h,d){var g,m=x(h);if(h=m[0],m[1]){var F=[],E=h.length,O=0,D;for(g=0;g<E;++g)D=h.charCodeAt(g),D<128?F[O++]=D:D<2048?(F[O++]=192|D>>>6,F[O++]=128|D&63):D<55296||D>=57344?(F[O++]=224|D>>>12,F[O++]=128|D>>>6&63,F[O++]=128|D&63):(D=65536+((D&1023)<<10|h.charCodeAt(++g)&1023),F[O++]=240|D>>>18,F[O++]=128|D>>>12&63,F[O++]=128|D>>>6&63,F[O++]=128|D&63);h=F}h.length>64&&(h=new b(!0).update(h).array());var Y=[],Ee=[];for(g=0;g<64;++g){var ze=h[g]||0;Y[g]=92^ze,Ee[g]=54^ze}b.call(this,d),this.update(Ee),this.oKeyPad=Y,this.inner=!0,this.sharedMemory=d}A.prototype=new b,A.prototype.finalize=function(){if(b.prototype.finalize.call(this),this.inner){this.inner=!1;var h=this.array();b.call(this,this.sharedMemory),this.update(this.oKeyPad),this.update(h),b.prototype.finalize.call(this)}};var I=$();I.md5=I,I.md5.hmac=_(),o?t.exports=I:s.md5=I})()})(wn)),wn.exports}var Sl=wl(),Sn={exports:{}};/**
489
+ * [js-sha256]{@link https://github.com/emn178/js-sha256}
490
+ *
491
+ * @version 0.11.1
492
+ * @author Chen, Yi-Cyuan [emn178@gmail.com]
493
+ * @copyright Chen, Yi-Cyuan 2014-2025
494
+ * @license MIT
495
+ */var fi;function _l(){return fi||(fi=1,(function(t){(function(){var e="input is invalid type",r=typeof window=="object",n=r?window:{};n.JS_SHA256_NO_WINDOW&&(r=!1);var s=!r&&typeof self=="object",i=!n.JS_SHA256_NO_NODE_JS&&typeof process=="object"&&process.versions&&process.versions.node&&process.type!="renderer";i?n=oa:s&&(n=self);var a=!n.JS_SHA256_NO_COMMON_JS&&!0&&t.exports,o=!n.JS_SHA256_NO_ARRAY_BUFFER&&typeof ArrayBuffer<"u",c="0123456789abcdef".split(""),u=[-2147483648,8388608,32768,128],f=[24,16,8,0],l=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],p=["hex","array","digest","arrayBuffer"],y=[];(n.JS_SHA256_NO_NODE_JS||!Array.isArray)&&(Array.isArray=function(S){return Object.prototype.toString.call(S)==="[object Array]"}),o&&(n.JS_SHA256_NO_ARRAY_BUFFER_IS_VIEW||!ArrayBuffer.isView)&&(ArrayBuffer.isView=function(S){return typeof S=="object"&&S.buffer&&S.buffer.constructor===ArrayBuffer});var v=function(S,T){return function(_){return new x(T,!0).update(_)[S]()}},w=function(S){var T=v("hex",S);i&&(T=R(T,S)),T.create=function(){return new x(S)},T.update=function(A){return T.create().update(A)};for(var _=0;_<p.length;++_){var b=p[_];T[b]=v(b,S)}return T},R=function(S,T){var _=Dr,b=Dr.Buffer,A=T?"sha224":"sha256",I;b.from&&!n.JS_SHA256_NO_BUFFER_FROM?I=b.from:I=function(d){return new b(d)};var h=function(d){if(typeof d=="string")return _.createHash(A).update(d,"utf8").digest("hex");if(d==null)throw new Error(e);return d.constructor===ArrayBuffer&&(d=new Uint8Array(d)),Array.isArray(d)||ArrayBuffer.isView(d)||d.constructor===b?_.createHash(A).update(I(d)).digest("hex"):S(d)};return h},C=function(S,T){return function(_,b){return new L(_,T,!0).update(b)[S]()}},k=function(S){var T=C("hex",S);T.create=function(A){return new L(A,S)},T.update=function(A,I){return T.create(A).update(I)};for(var _=0;_<p.length;++_){var b=p[_];T[b]=C(b,S)}return T};function x(S,T){T?(y[0]=y[16]=y[1]=y[2]=y[3]=y[4]=y[5]=y[6]=y[7]=y[8]=y[9]=y[10]=y[11]=y[12]=y[13]=y[14]=y[15]=0,this.blocks=y):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],S?(this.h0=3238371032,this.h1=914150663,this.h2=812702999,this.h3=4144912697,this.h4=4290775857,this.h5=1750603025,this.h6=1694076839,this.h7=3204075428):(this.h0=1779033703,this.h1=3144134277,this.h2=1013904242,this.h3=2773480762,this.h4=1359893119,this.h5=2600822924,this.h6=528734635,this.h7=1541459225),this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0,this.is224=S}x.prototype.update=function(S){if(!this.finalized){var T,_=typeof S;if(_!=="string"){if(_==="object"){if(S===null)throw new Error(e);if(o&&S.constructor===ArrayBuffer)S=new Uint8Array(S);else if(!Array.isArray(S)&&(!o||!ArrayBuffer.isView(S)))throw new Error(e)}else throw new Error(e);T=!0}for(var b,A=0,I,h=S.length,d=this.blocks;A<h;){if(this.hashed&&(this.hashed=!1,d[0]=this.block,this.block=d[16]=d[1]=d[2]=d[3]=d[4]=d[5]=d[6]=d[7]=d[8]=d[9]=d[10]=d[11]=d[12]=d[13]=d[14]=d[15]=0),T)for(I=this.start;A<h&&I<64;++A)d[I>>>2]|=S[A]<<f[I++&3];else for(I=this.start;A<h&&I<64;++A)b=S.charCodeAt(A),b<128?d[I>>>2]|=b<<f[I++&3]:b<2048?(d[I>>>2]|=(192|b>>>6)<<f[I++&3],d[I>>>2]|=(128|b&63)<<f[I++&3]):b<55296||b>=57344?(d[I>>>2]|=(224|b>>>12)<<f[I++&3],d[I>>>2]|=(128|b>>>6&63)<<f[I++&3],d[I>>>2]|=(128|b&63)<<f[I++&3]):(b=65536+((b&1023)<<10|S.charCodeAt(++A)&1023),d[I>>>2]|=(240|b>>>18)<<f[I++&3],d[I>>>2]|=(128|b>>>12&63)<<f[I++&3],d[I>>>2]|=(128|b>>>6&63)<<f[I++&3],d[I>>>2]|=(128|b&63)<<f[I++&3]);this.lastByteIndex=I,this.bytes+=I-this.start,I>=64?(this.block=d[16],this.start=I-64,this.hash(),this.hashed=!0):this.start=I}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}},x.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var S=this.blocks,T=this.lastByteIndex;S[16]=this.block,S[T>>>2]|=u[T&3],this.block=S[16],T>=56&&(this.hashed||this.hash(),S[0]=this.block,S[16]=S[1]=S[2]=S[3]=S[4]=S[5]=S[6]=S[7]=S[8]=S[9]=S[10]=S[11]=S[12]=S[13]=S[14]=S[15]=0),S[14]=this.hBytes<<3|this.bytes>>>29,S[15]=this.bytes<<3,this.hash()}},x.prototype.hash=function(){var S=this.h0,T=this.h1,_=this.h2,b=this.h3,A=this.h4,I=this.h5,h=this.h6,d=this.h7,g=this.blocks,m,F,E,O,D,Y,Ee,ze,Pt,$t,Ut;for(m=16;m<64;++m)D=g[m-15],F=(D>>>7|D<<25)^(D>>>18|D<<14)^D>>>3,D=g[m-2],E=(D>>>17|D<<15)^(D>>>19|D<<13)^D>>>10,g[m]=g[m-16]+F+g[m-7]+E<<0;for(Ut=T&_,m=0;m<64;m+=4)this.first?(this.is224?(ze=300032,D=g[0]-1413257819,d=D-150054599<<0,b=D+24177077<<0):(ze=704751109,D=g[0]-210244248,d=D-1521486534<<0,b=D+143694565<<0),this.first=!1):(F=(S>>>2|S<<30)^(S>>>13|S<<19)^(S>>>22|S<<10),E=(A>>>6|A<<26)^(A>>>11|A<<21)^(A>>>25|A<<7),ze=S&T,O=ze^S&_^Ut,Ee=A&I^~A&h,D=d+E+Ee+l[m]+g[m],Y=F+O,d=b+D<<0,b=D+Y<<0),F=(b>>>2|b<<30)^(b>>>13|b<<19)^(b>>>22|b<<10),E=(d>>>6|d<<26)^(d>>>11|d<<21)^(d>>>25|d<<7),Pt=b&S,O=Pt^b&T^ze,Ee=d&A^~d&I,D=h+E+Ee+l[m+1]+g[m+1],Y=F+O,h=_+D<<0,_=D+Y<<0,F=(_>>>2|_<<30)^(_>>>13|_<<19)^(_>>>22|_<<10),E=(h>>>6|h<<26)^(h>>>11|h<<21)^(h>>>25|h<<7),$t=_&b,O=$t^_&S^Pt,Ee=h&d^~h&A,D=I+E+Ee+l[m+2]+g[m+2],Y=F+O,I=T+D<<0,T=D+Y<<0,F=(T>>>2|T<<30)^(T>>>13|T<<19)^(T>>>22|T<<10),E=(I>>>6|I<<26)^(I>>>11|I<<21)^(I>>>25|I<<7),Ut=T&_,O=Ut^T&b^$t,Ee=I&h^~I&d,D=A+E+Ee+l[m+3]+g[m+3],Y=F+O,A=S+D<<0,S=D+Y<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+S<<0,this.h1=this.h1+T<<0,this.h2=this.h2+_<<0,this.h3=this.h3+b<<0,this.h4=this.h4+A<<0,this.h5=this.h5+I<<0,this.h6=this.h6+h<<0,this.h7=this.h7+d<<0},x.prototype.hex=function(){this.finalize();var S=this.h0,T=this.h1,_=this.h2,b=this.h3,A=this.h4,I=this.h5,h=this.h6,d=this.h7,g=c[S>>>28&15]+c[S>>>24&15]+c[S>>>20&15]+c[S>>>16&15]+c[S>>>12&15]+c[S>>>8&15]+c[S>>>4&15]+c[S&15]+c[T>>>28&15]+c[T>>>24&15]+c[T>>>20&15]+c[T>>>16&15]+c[T>>>12&15]+c[T>>>8&15]+c[T>>>4&15]+c[T&15]+c[_>>>28&15]+c[_>>>24&15]+c[_>>>20&15]+c[_>>>16&15]+c[_>>>12&15]+c[_>>>8&15]+c[_>>>4&15]+c[_&15]+c[b>>>28&15]+c[b>>>24&15]+c[b>>>20&15]+c[b>>>16&15]+c[b>>>12&15]+c[b>>>8&15]+c[b>>>4&15]+c[b&15]+c[A>>>28&15]+c[A>>>24&15]+c[A>>>20&15]+c[A>>>16&15]+c[A>>>12&15]+c[A>>>8&15]+c[A>>>4&15]+c[A&15]+c[I>>>28&15]+c[I>>>24&15]+c[I>>>20&15]+c[I>>>16&15]+c[I>>>12&15]+c[I>>>8&15]+c[I>>>4&15]+c[I&15]+c[h>>>28&15]+c[h>>>24&15]+c[h>>>20&15]+c[h>>>16&15]+c[h>>>12&15]+c[h>>>8&15]+c[h>>>4&15]+c[h&15];return this.is224||(g+=c[d>>>28&15]+c[d>>>24&15]+c[d>>>20&15]+c[d>>>16&15]+c[d>>>12&15]+c[d>>>8&15]+c[d>>>4&15]+c[d&15]),g},x.prototype.toString=x.prototype.hex,x.prototype.digest=function(){this.finalize();var S=this.h0,T=this.h1,_=this.h2,b=this.h3,A=this.h4,I=this.h5,h=this.h6,d=this.h7,g=[S>>>24&255,S>>>16&255,S>>>8&255,S&255,T>>>24&255,T>>>16&255,T>>>8&255,T&255,_>>>24&255,_>>>16&255,_>>>8&255,_&255,b>>>24&255,b>>>16&255,b>>>8&255,b&255,A>>>24&255,A>>>16&255,A>>>8&255,A&255,I>>>24&255,I>>>16&255,I>>>8&255,I&255,h>>>24&255,h>>>16&255,h>>>8&255,h&255];return this.is224||g.push(d>>>24&255,d>>>16&255,d>>>8&255,d&255),g},x.prototype.array=x.prototype.digest,x.prototype.arrayBuffer=function(){this.finalize();var S=new ArrayBuffer(this.is224?28:32),T=new DataView(S);return T.setUint32(0,this.h0),T.setUint32(4,this.h1),T.setUint32(8,this.h2),T.setUint32(12,this.h3),T.setUint32(16,this.h4),T.setUint32(20,this.h5),T.setUint32(24,this.h6),this.is224||T.setUint32(28,this.h7),S};function L(S,T,_){var b,A=typeof S;if(A==="string"){var I=[],h=S.length,d=0,g;for(b=0;b<h;++b)g=S.charCodeAt(b),g<128?I[d++]=g:g<2048?(I[d++]=192|g>>>6,I[d++]=128|g&63):g<55296||g>=57344?(I[d++]=224|g>>>12,I[d++]=128|g>>>6&63,I[d++]=128|g&63):(g=65536+((g&1023)<<10|S.charCodeAt(++b)&1023),I[d++]=240|g>>>18,I[d++]=128|g>>>12&63,I[d++]=128|g>>>6&63,I[d++]=128|g&63);S=I}else if(A==="object"){if(S===null)throw new Error(e);if(o&&S.constructor===ArrayBuffer)S=new Uint8Array(S);else if(!Array.isArray(S)&&(!o||!ArrayBuffer.isView(S)))throw new Error(e)}else throw new Error(e);S.length>64&&(S=new x(T,!0).update(S).array());var m=[],F=[];for(b=0;b<64;++b){var E=S[b]||0;m[b]=92^E,F[b]=54^E}x.call(this,T,_),this.update(F),this.oKeyPad=m,this.inner=!0,this.sharedMemory=_}L.prototype=new x,L.prototype.finalize=function(){if(x.prototype.finalize.call(this),this.inner){this.inner=!1;var S=this.array();x.call(this,this.is224,this.sharedMemory),this.update(this.oKeyPad),this.update(S),x.prototype.finalize.call(this)}};var $=w();$.sha256=$,$.sha224=w(!0),$.sha256.hmac=k(),$.sha224.hmac=k(!0),a?t.exports=$:(n.sha256=$.sha256,n.sha224=$.sha224)})()})(Sn)),Sn.exports}var Al=_l();function Il(t){if(t instanceof Ae)return t;if(typeof t=="string")return Ae.fromUtf8(t);throw new G(`hashing.* requires Bytes or String, got ${typeof t}`)}function xl(t,e){const r=Il(e[0]);switch(t){case"md5":return new Ae(new Uint8Array(Sl.md5.arrayBuffer(r.data)));case"sha256":return new Ae(new Uint8Array(Al.sha256.arrayBuffer(r.data)));case"crc32":{const n=El(r.data);return new Ae(pi(n))}case"crc32c":{const n=Ol(r.data);return new Ae(pi(n))}}throw new gt(`Unknown hashing method '${t}'`)}function pi(t){return new Uint8Array([t&255,t>>>8&255,t>>>16&255,t>>>24&255])}const kl=(()=>{const t=new Uint32Array(256);for(let e=0;e<256;e++){let r=e;for(let n=0;n<8;n++)r=r&1?3988292384^r>>>1:r>>>1;t[e]=r>>>0}return t})();function El(t){let e=4294967295;for(let r=0;r<t.length;r++)e=kl[(e^t[r])&255]^e>>>8;return(e^4294967295)>>>0}const Tl=(()=>{const t=new Uint32Array(256);for(let e=0;e<256;e++){let r=e;for(let n=0;n<8;n++)r=r&1?2197175160^r>>>1:r>>>1;t[e]=r>>>0}return t})();function Ol(t){let e=4294967295;for(let r=0;r<t.length;r++)e=Tl[(e^t[r])&255]^e>>>8;return(e^4294967295)>>>0}function Cl(t){if(typeof t=="number")return Math.trunc(t);if(t instanceof ae)return Math.trunc(t.value);if(typeof t=="boolean")return t?1:0;if(typeof t=="string"){if(/^[+-]?\d+$/.test(t.trim()))return parseInt(t.trim(),10);throw new G(`int() cannot convert string '${t}' to an integer`)}throw new G(`int() cannot convert ${typeof t} to an integer`)}function Rl(t){if(t instanceof ae)return t;if(typeof t=="number")return new ae(t);if(typeof t=="string"){const e=t.trim();if(/^[+-]?(\d+\.?\d*|\.\d+)$/.test(e))return new ae(parseFloat(e));throw new G(`float() cannot convert string '${t}' to a float`)}throw new G(`float() cannot convert ${typeof t} to a float`)}function Nl(t,e,r,n){switch(t){case"get":{const a=String(W(e[0],r,n));return li(a,r)}case"exists":{const a=String(W(e[0],r,n));return di(a,r)}case"getAfter":{const a=W(e[0],r,n),o=String(a);if(o===r.afterStatePath.toString()){if(r.afterState===null)throw new G(`getAfter() of non-existent document '${o}' (guard with existsAfter() first)`);return Wn(ur(o),r.afterState)}const c=ur(o);if(r.batchProjection?.has(c)){const u=r.batchProjection.get(c);if(u===null)throw new G(`getAfter() of non-existent document '${o}' (guard with existsAfter() first)`);return Wn(c,u)}return li(o,r)}case"existsAfter":{const a=W(e[0],r,n),o=String(a);if(o===r.afterStatePath.toString())return r.existsAfter;const c=ur(o);return r.batchProjection?.has(c)?r.batchProjection.get(c)!==null:di(o,r)}case"debug":return W(e[0],r,n);case"string":return String(W(e[0],r,n));case"int":return Cl(W(e[0],r,n));case"float":return Rl(W(e[0],r,n));case"path":{const a=W(e[0],r,n);if(typeof a=="string")return Qe.fromString(a);throw new G(`path() requires a string argument, got ${typeof a}`)}}const s=r.functions.get(t);if(!s)throw new G(`Unknown function: ${t}`);const i={...n};for(let a=0;a<s.parameters.length;a++)i[s.parameters[a]]=W(e[a],r,n);r.trace?.enterFrame(t);try{for(const a of s.lets){const o=r.trace?r.trace.entries.length:-1;i[a.name]=W(a.value,r,i),o>=0&&r.trace?.markEntryAsLetBinding(o,a.name)}return W(s.body,r,i)}finally{r.trace?.exitFrame()}}function Ll(t,e,r,n,s){if(t.type==="identifier"){const o=t.name;if(mi(o)&&!(o in s)&&!(o in n.pathVariables)){const c=r.map(u=>W(u,n,s));return Dl(o,e,c)}if(!mi(o)&&!(o in s)&&!(o in n.pathVariables)&&!Bl(o))throw new gt(`Unknown namespace or method '${o}.${e}()'`)}const i=W(t,n,s),a=r.map(o=>W(o,n,s));if(i instanceof te){const o=i.callMethod(e,a);if(o===oe)throw new gt(`Unknown method '${e}' on ${i.typeName}`);return o}if(e==="diff"&&typeof i=="object"&&i!==null&&!Array.isArray(i)){const o=a[0];if(typeof o=="object"&&o!==null)return new cr(o,i);throw new G("diff() requires a map argument")}if(typeof i=="function")return i(...a);if(i instanceof de)switch(e){case"hasOnly":return i.hasOnly(a[0]);case"hasAll":return i.hasAll(a[0]);case"hasAny":return i.hasAny(a[0]);case"size":return i.size();case"difference":case"union":case"intersection":{const o=a[0];if(!(o instanceof de))throw new G(`Unsupported operation: set.${e} requires a Set argument`);return i[e](o)}}if(i instanceof cr)switch(e){case"addedKeys":return i.addedKeys();case"removedKeys":return i.removedKeys();case"changedKeys":return i.changedKeys();case"affectedKeys":return i.affectedKeys();case"unchangedKeys":return i.unchangedKeys()}if(typeof i=="object"&&i!==null&&!Array.isArray(i)){const o=i;switch(e){case"keys":return Object.keys(o);case"values":return Object.values(o);case"size":return Object.keys(o).length;case"diff":{const c=a[0];return new cr(c,o)}case"get":{const c=a[0],u=a[1];if(Array.isArray(c)){let l=o;for(const p of c){if(l==null||typeof l!="object"||Array.isArray(l)||l instanceof te)return u;const y=String(p);if(!Object.hasOwn(l,y))return u;l=l[y]}return l}const f=String(c);return Object.hasOwn(o,f)?o[f]:u}}}if(Array.isArray(i))switch(e){case"size":return i.length;case"hasAll":return a[0].every(o=>i.some(c=>me(c,o)));case"hasAny":return a[0].some(o=>i.some(c=>me(c,o)));case"hasOnly":{const o=a[0];return i.every(c=>o.some(u=>me(u,c)))}case"join":return i.join(String(a[0]??","));case"concat":{const o=a[0];if(!Array.isArray(o))throw new G(`List.concat requires a list argument, got ${typeof o}`);return[...i,...o]}case"removeAll":{const o=a[0];if(!Array.isArray(o))throw new G(`List.removeAll requires a list argument, got ${typeof o}`);return i.filter(c=>!o.some(u=>me(c,u)))}case"toSet":return new de(i);case"difference":case"union":case"intersection":throw new G(`Function not found on List receiver: ${e}`)}if(typeof i=="string")switch(e){case"size":return i.length;case"lower":return i.toLowerCase();case"upper":return i.toUpperCase();case"trim":return i.trim();case"split":return i.split(_n(String(a[0]),"g"));case"matches":return _n(`^(?:${String(a[0])})$`).test(i);case"replace":return i.replace(_n(String(a[0]),"g"),String(a[1]));case"toUtf8":return Ae.fromUtf8(i)}throw new G(`Unknown method '${e}' on ${typeof i}`)}function _n(t,e=""){try{return new RegExp(t,e)}catch(r){throw new G(`Invalid regex '${t}': ${r.message}`)}}const Ml=new Set(["math","timestamp","duration","latlng","hashing"]);function mi(t){return Ml.has(t)}function Dl(t,e,r){const n=t==="hashing"?r:r.map(Fl);switch(t){case"math":return ql(e,n);case"timestamp":return Pl(e,n);case"duration":return $l(e,n);case"latlng":return jl(e,n);case"hashing":return xl(e,r)}throw new gt(`Unknown namespace '${t}'`)}function Fl(t){return t instanceof ae?t.value:t}function jl(t,e){switch(t){case"value":{const[r,n]=e;return new lt(r,n)}}throw new gt(`Unknown latlng method '${t}'`)}function ql(t,e){switch(t){case"abs":return Math.abs(e[0]);case"ceil":return Math.ceil(e[0]);case"floor":return Math.floor(e[0]);case"round":return Math.round(e[0]);case"sqrt":return Math.sqrt(e[0]);case"pow":return Math.pow(e[0],e[1]);case"isNaN":return Number.isNaN(e[0])}throw new G(`Unknown math method '${t}'`)}function Pl(t,e){switch(t){case"date":{const[r,n,s]=e;return _e.fromYMD(r,n,s)}case"value":return _e.fromMillis(e[0])}throw new gt(`Unknown timestamp method '${t}'`)}function $l(t,e){switch(t){case"value":try{return ve.fromValue(e[0],e[1])}catch(r){throw new G(r.message)}case"time":{const[r,n,s,i]=e;return ve.fromTime(r,n,s,i)}case"abs":{const r=e[0];if(!(r instanceof ve))throw new G(`duration.abs() requires a Duration argument, got ${typeof r}`);return ve.abs(r)}}throw new gt(`Unknown duration method '${t}'`)}function W(t,e,r={}){return e.trace?e.trace.capture(t,()=>gi(t,e,r)):gi(t,e,r)}function gi(t,e,r){switch(t.type){case"literal":return typeof t.value=="number"&&t.raw.includes(".")?new ae(t.value):t.value;case"identifier":return Ul(t.name,e,r);case"binaryOp":return zl(t.op,t.left,t.right,e,r);case"unaryOp":{if(t.op==="!")return!W(t.operand,e,r);if(t.op==="-"){const n=W(t.operand,e,r);return n instanceof ae?new ae(-n.value):-n}throw new G(`Unknown unary op: ${t.op}`,t)}case"ternary":{const n=ir(W(t.condition,e,r),t.condition);return W(n?t.consequent:t.alternate,e,r)}case"memberAccess":{const n=W(t.object,e,r);if(n==null)throw new G(`Property '${t.property}' accessed on ${n===null?"null":"undefined"} value`,t);if(n instanceof te)return n.field(t.property);if(n instanceof cr)switch(t.property){case"addedKeys":return()=>n.addedKeys();case"removedKeys":return()=>n.removedKeys();case"changedKeys":return()=>n.changedKeys();case"affectedKeys":return()=>n.affectedKeys();case"unchangedKeys":return()=>n.unchangedKeys()}if(n instanceof de)switch(t.property){case"size":return()=>n.size()}if(Object.hasOwn(n,t.property))return n[t.property];throw new G(`No field '${t.property}' on map (use 'in' or .get() to read a possibly-absent field)`,t)}case"bracketAccess":{const n=W(t.object,e,r),s=W(t.index,e,r);if(n==null)throw new G(`Index access on ${n===null?"null":"undefined"} value`,t);if(n instanceof te)return n.field(String(s));const i=String(s);return Object.hasOwn(n,i)?n[i]:null}case"sliceAccess":{const n=W(t.object,e,r),s=W(t.start,e,r),i=W(t.end,e,r);if(n==null)return null;if(typeof s!="number"||!Number.isInteger(s))throw new G(`Slice start must be an integer, got ${typeof s}`);if(typeof i!="number"||!Number.isInteger(i))throw new G(`Slice end must be an integer, got ${typeof i}`);if(s<0||i<0)throw new G(`Slice indices must be non-negative, got [${s}:${i}]`);if(typeof n=="string"||Array.isArray(n)){if(i>n.length)throw new G(`Slice end ${i} exceeds length ${n.length}`);return n.slice(s,i)}throw new G(`Slice not supported on ${typeof n}`)}case"inExpr":{const n=W(t.element,e,r),s=W(t.collection,e,r);return s==null?!1:Array.isArray(s)?s.some(i=>me(i,n)):typeof s=="object"?Object.hasOwn(s,String(n)):!1}case"isExpr":{const n=W(t.value,e,r);switch(t.typeName){case"string":return typeof n=="string";case"int":return n instanceof te?!1:typeof n=="number";case"float":return n instanceof ae;case"number":return n instanceof ae?!0:n instanceof te?!1:typeof n=="number";case"bool":return typeof n=="boolean";case"null":return n===null;case"list":return Array.isArray(n);case"map":return n instanceof te||n instanceof cr||n instanceof de?!1:typeof n=="object"&&n!==null&&!Array.isArray(n);default:return n instanceof te?n.typeName===t.typeName:!1}}case"listLiteral":return t.elements.map(n=>W(n,e,r));case"mapLiteral":{const n={};for(const s of t.entries){const i=String(W(s.key,e,r));n[i]=W(s.value,e,r)}return n}case"functionCall":return Nl(t.name,t.args,e,r);case"methodCall":return Ll(t.object,t.method,t.args,e,r);case"pathLiteral":{const n=[];for(const s of t.segments)typeof s=="string"?n.push(s):n.push(String(W(s,e,r)));return new Qe(n)}default:throw new G(`Unknown expression type: ${t.type}`,t)}}function Ul(t,e,r){if(t in r)return r[t];if(t in e.pathVariables)return e.pathVariables[t];switch(t){case"request":return e.request;case"resource":if(e.resource===null)throw new G("Null value error.");return e.resource;case"true":return!0;case"false":return!1;case"null":return null}throw new G(`Undefined variable '${t}'`)}function Bl(t){return t==="request"||t==="resource"||t==="true"||t==="false"||t==="null"}function zl(t,e,r,n,s){if(t==="&&"){let o,c;try{o=ir(W(e,n,s),e)}catch(l){c=l}if(c===void 0&&o===!1)return n.trace?.skip(r),!1;let u,f;try{u=ir(W(r,n,s),r)}catch(l){f=l}if(f===void 0&&u===!1)return!1;if(c!==void 0)throw c;if(f!==void 0)throw f;return u}if(t==="||"){let o,c;try{o=ir(W(e,n,s),e)}catch(l){c=l}if(c===void 0&&o===!0)return n.trace?.skip(r),!0;let u,f;try{u=ir(W(r,n,s),r)}catch(l){f=l}if(f===void 0&&u===!0)return!0;if(c!==void 0)throw c;if(f!==void 0)throw f;return u}const i=W(e,n,s),a=W(r,n,s);if(t!=="=="&&t!=="!="){if(i instanceof te){const o=i.binaryOp(t,a);if(o!==oe)return o}if(typeof i=="number"&&a instanceof ae){const o=new ae(i).binaryOp(t,a);if(o!==oe)return o}if(a instanceof te&&(t==="+"||t==="*")){const o=a.binaryOp(t,i);if(o!==oe)return o}if((t!=="+"||typeof i!="string"&&typeof a!="string")&&(i instanceof te||a instanceof te)){const o=i instanceof te?i.typeName:typeof i,c=a instanceof te?a.typeName:typeof a;throw new G(`Operator '${t}' is not defined between ${o} and ${c}`)}}if((t==="<"||t===">"||t==="<="||t===">=")&&!(typeof i=="number"&&typeof a=="number"||typeof i=="string"&&typeof a=="string"))throw new G(`Operator '${t}' is not defined between ${typeof i} and ${typeof a}`);switch(t){case"==":return i===a||me(i,a);case"!=":return!(i===a||me(i,a));case"<":return i<a;case">":return i>a;case"<=":return i<=a;case">=":return i>=a;case"+":{if(Array.isArray(i)&&Array.isArray(a))return[...i,...a];if(typeof i=="string"&&typeof a=="string"||typeof i=="number"&&typeof a=="number")return i+a;if(typeof i=="string"&&a instanceof te)return i+String(a);throw new G(`Operator '+' is not defined between ${Array.isArray(i)?"list":typeof i} and ${Array.isArray(a)?"list":typeof a}`)}case"-":return i-a;case"*":return i*a;case"/":if(a===0)throw new G("Division by zero");return Math.trunc(i/a);case"%":if(a===0)throw new G("Modulo by zero");return i%a;default:throw new G(`Unknown binary op: ${t}`)}}function ir(t,e){if(typeof t=="boolean")return t;throw new G(`Expected a boolean control-flow operand, got ${t===null?"null":typeof t}`,e)}const Vl=new Set(["__proto__","prototype","constructor"]);function Fr(t){if(Vl.has(t))throw new Error(`Invalid field-path segment '${t}': the keys __proto__, prototype, and constructor are reserved and cannot appear in a field path.`)}function Ka(t,e){const r={...t};for(const[n,s]of Object.entries(e)){Fr(n);const i=Object.hasOwn(r,n)?r[n]:void 0;s!==null&&typeof s=="object"&&!Array.isArray(s)&&i!==null&&typeof i=="object"&&!Array.isArray(i)?r[n]=Ka(i,s):r[n]=s}return r}function Hl(t,e,r){let n=t;for(let i=0;i<e.length-1;i++){const a=e[i];Fr(a);const o=Object.hasOwn(n,a)?n[a]:void 0;(o===null||typeof o!="object"||Array.isArray(o))&&(n[a]={}),n=n[a]}const s=e[e.length-1];Fr(s),n[s]=r}function Wl(t,e){const r={...t};for(const[n,s]of Object.entries(e))n.includes(".")?Hl(r,n.split("."),s):(Fr(n),r[n]=s);return r}function Gl(t,e,r){switch(t.kind){case"create":return r;case"set":return t.merge?Ka(e??{},r):r;case"update":return Wl(e??{},r);case"delete":return null}}function Za(t){if(t===null||typeof t!="object"||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function Kl(t){return typeof t=="object"&&t!==null&&t.__type==="serverTimestamp"}function Ja(t,e){const r={};for(const[n,s]of Object.entries(t))Kl(s)?r[n]=e:Za(s)?r[n]=Ja(s,e):r[n]=s;return r}function It(t){return typeof t=="number"&&!Number.isInteger(t)?new ae(t):Array.isArray(t)?t.map(It):Za(t)?t.__type==="float"&&typeof t.value=="number"?new ae(t.value):Object.fromEntries(Object.entries(t).map(([e,r])=>[e,It(r)])):t}function yi(t){if(t.method==="list")return{limit:t.query?.limit??null,offset:t.query?.offset??null,orderBy:t.query?.orderBy??null}}function xr(t){return`/${t.path.segments.map(r=>r.type==="literal"?r.value:r.type==="wildcard"?`{${r.name}}`:`{${r.name}=**}`).join("/")}`}function jr(t,e,r,n){const s=[...r,...t.functions],i=t.path.segments,a={},o=[];let c=0,u;for(const p of i)if(p.type==="literal"){if(c>=e.length){u="request-shorter";break}if(e[c]!==p.value){u="literal-mismatch";break}c++}else if(p.type==="wildcard"){if(c>=e.length){u="request-shorter";break}a[p.name]=e[c],c===e.length-1&&o.push(p.name),c++}else a[p.name]=e.slice(c).join("/"),c<e.length&&o.push(p.name),c=e.length;if(u!==void 0)return n?.push({...t.loc?{line:t.loc.line}:{},blockPath:xr(t),matchedSegments:c,totalSegments:i.length,bindings:a,matched:!1,reason:u}),[];const f=e.slice(c);if(f.length===0)return n?.push({...t.loc?{line:t.loc.line}:{},blockPath:xr(t),matchedSegments:c,totalSegments:i.length,bindings:a,matched:!0}),[{block:t,pathVariables:a,candidateVariables:o,functions:s}];const l=[];for(const p of t.children)for(const y of jr(p,f,s,n))y.pathVariables={...a,...y.pathVariables},y.candidateVariables=[...o,...y.candidateVariables],l.push(y);return n?.push({...t.loc?{line:t.loc.line}:{},blockPath:xr(t),matchedSegments:c,totalSegments:i.length,bindings:a,...l.length>0?{matched:!0}:{matched:!1,reason:"no-matching-child"}}),l}class Zl{attempts=[];push(e){this.attempts.push(e)}}function Jl(t){switch(t){case"get":return["get","read"];case"list":return["list","read"];case"create":return["create","write"];case"update":return["update","write"];case"delete":return["delete","write"];default:return[t]}}function Yl(t,e,r,n){const s=Jl(e),i=[],a=[],o=[];for(let p=0;p<t.allows.length;p++){const y=t.allows[p];y.operations.some(w=>s.includes(w))&&o.push({rule:y,index:p})}if(o.length===0)return a.push(`No allow rules found for operation '${e}'`),{decision:"DENY",trace:i,notes:a};let u=!1;const f=r.trace;for(const{rule:p,index:y}of o){const v=Ql(p,y,n),w=new ll;r.trace=w;try{const R=W(p.condition,r);if(v.expressionTrace=w.entries,!!R)return v.verdict="ALLOW",i.push(v),r.trace=f,{decision:"ALLOW",trace:i,notes:a};v.verdict="DENY",i.push(v)}catch(R){v.expressionTrace=w.entries,R instanceof gt?(u=!0,v.verdict="UNSUPPORTED",v.message=R.message):(v.verdict="ERROR",R instanceof Error?v.message=R.message:v.message=String(R)),i.push(v)}}r.trace=f;let l="DENY";return u&&(l="UNSUPPORTED"),{decision:l,trace:i,notes:a}}function Ql(t,e,r){const n=ye(t.condition),s={ruleIndex:e,operations:[...t.operations],verdict:"DENY",conditionText:n};if(t.loc!==void 0){const a=t.loc;if(s.line=a.line,s.col=a.col,s.column=a.col,a.file!==void 0?(s.file=a.file,s.citation=`${a.file}:${a.line}:${a.col}`):(s.file="firestore.rules",s.citation=`firestore.rules:${a.line}:${a.col}`),r!==void 0){const u=Ga(r,a.line,a.col,a.file,n);u!==void 0&&(s.line=u.line,s.col=u.col,s.column=u.col,s.file=u.file,s.citation=u.citation,u.expression!==void 0&&(s.conditionText=u.expression))}}return s}function Xl(t,e,r,n,s){const i=new Map;for(const k of e)i.set(k.name,k);const a=new Map,o=new Set;if(t.functionMocks)for(const k of t.functionMocks)k.function==="get"&&typeof k.result=="object"&&k.result!==null?(a.set(k.path,It(k.result)),o.add(k.path)):k.function==="exists"&&k.result===!0&&(a.set(k.path,{}),o.add(k.path));const c=t.requestTime?_e.fromIsoString(t.requestTime):_e.fromMillis(Date.now()),f=["databases","(default)","documents",...(t.path.startsWith("/")?t.path.slice(1):t.path).split("/").filter(Boolean)],l=new Qe(f,r),p=It(t.data??{}),y=t.resource===void 0||t.resource===null?null:It(t.resource);let v,w;if(t.writeMode)v=Gl(t.writeMode,y,p),w=v!==null;else switch(t.method){case"create":case"update":v=p,w=!0;break;case"delete":v=null,w=!1;break;case"get":case"list":default:v=y,w=y!==null;break}const R=v!==null?It(Ja(v,c)):null,C=R??{};return{request:{auth:t.auth?{uid:t.auth.uid,token:t.auth.token??{}}:null,resource:{data:C},method:t.method,path:l,...yi(t)?{query:yi(t)}:{},time:c},resource:t.method==="create"||y===null?null:{data:It(y)},mockDocuments:a,identitylessFunctionMocks:o,getDoc:n,pathVariables:r,functions:i,database:"(default)",afterStatePath:l,afterState:R,existsAfter:w,...s?{batchProjection:s}:{}}}class ed{simulate(e,r,n){if(!e||e.trim().length===0)return{success:!1,error:{code:"PARSE_FAILED",message:"Empty rules source — call setRules(sandbox, rules) from pyric/sandbox/firestore before operating, or initialize without rules to use the open-by-default ruleset. See pyric/sandbox docs.",recoverable:!0}};const s=_s(e);if(!s)return{success:!1,error:{code:"PARSE_FAILED",message:"Failed to parse rules source",recoverable:!0}};const i=[];let a=0,o=0,c=0;const u={database:"(default)"};for(const f of s.service.match.path.segments)f.type==="wildcard"&&(u[f.name]="(default)");for(const f of r){const l=f.path.split("/").filter(Boolean),p=[...s.functions??[],...s.service.functions??[],...s.service.match.functions];let y=[];const v=new Zl;for(const d of s.service.match.children)y.push(...jr(d,l,p,v));let w=!1;const R=y.length===0,C=f.method==="list";if(R&&C){const d=[...l,"__hypothetical_doc__"];for(const m of s.service.match.children)y.push(...jr(m,d,p,v));y.length>0&&(w=!0)}const k={requestPath:f.path,attempts:v.attempts};if(y.length===0){const d=f.expectation==="DENY"?"PASSED":"FAILED";d==="PASSED"?a++:o++,i.push({description:f.description,expectation:f.expectation,state:d,decision:"DENY",trace:[],notes:[`No match block found for path '${f.path}'`],pathResolution:k});continue}let L="DENY";const $=[],S=[];let T=!1,_;for(const d of y){const g={...u,...d.pathVariables},m=Xl(f,d.functions,g,n?.getDoc,n?.batchProjection),F=xr(d.block),E=Yl(d.block,f.method,m,e);for(const Y of E.trace)Y.matchPath=F;if($.push(...E.trace),S.push(...E.notes),E.decision==="ALLOW"){L="ALLOW",_=F;break}E.decision==="UNSUPPORTED"&&(T=!0)}L!=="ALLOW"&&T&&(L="UNSUPPORTED"),L==="ALLOW"&&_!==void 0&&S.push(`Allowed by match block '${_}'`),w===!0&&S.push(`list on collection path '${f.path}' evaluated against the document-level match block (document wildcard hypothetical, resource undefined) — emulator-faithful`);let h;L==="UNSUPPORTED"?(h="UNSUPPORTED",c++):L===f.expectation?(h="PASSED",a++):(h="FAILED",o++),i.push({description:f.description,expectation:f.expectation,state:h,decision:L,trace:$,notes:S,pathResolution:k})}return{success:!0,data:{passed:a,failed:o,unsupported:c,results:i}}}}function td(t,e,r=new Map,n){if(qr(t,r))return{provable:!0,reason:"list rule does not depend on per-document data; every doc is equally readable"};const s=nd(t,r,n);if(!s.ok||s.required.length===0){const u="list rule depends on per-document data through a predicate the query cannot discharge (a rule is provable only when its entire doc-dependence reduces to top-level `resource.data.field == value` conjunctions, including through inlined helpers — disjunctions, ranges, `in`, membership/type checks, and nested paths are not provable)";return{provable:!1,reason:`${u} — prod rejects the whole query rather than filtering`,residual:{missing:[],mismatched:[],outOfScope:u}}}const i=s.required,a=e.where??[],o=[],c=[];for(const u of i){if(a.some(p=>p.field===u.field&&p.op==="=="&&od(p.value,u.value)))continue;const l=a.find(p=>p.field===u.field&&p.op==="==");l?c.push({field:u.field,expectedValue:u.value,actualValue:l.value}):o.push({field:u.field,expectedValue:u.value,fromAuthUid:u.fromAuthUid})}return o.length===0&&c.length===0?{provable:!0,reason:"every per-document predicate the rule requires is guaranteed by a query where(...) constraint"}:{provable:!1,reason:rd(o,c),residual:{missing:o,mismatched:c}}}function rd(t,e){const r=[];if(t.length>0){const n=t.map(s=>`resource.data.${s.field} == ${s.fromAuthUid?"request.auth.uid":JSON.stringify(s.expectedValue)}`).join(", ");r.push(`the query has no matching where(...) equality for [${n}]`)}if(e.length>0){const n=e.map(s=>`resource.data.${s.field} == ${JSON.stringify(s.expectedValue)} but the query pins ${JSON.stringify(s.actualValue)}`).join(", ");r.push(`the query where(...) value does not match [${n}]`)}return`${r.join("; ")} — prod rejects the query ("rules are not filters")`}function qr(t,e=new Map,r=new Set){const n=s=>{switch(s.type){case"literal":return!0;case"identifier":return s.name!=="resource";case"memberAccess":return n(s.object);case"bracketAccess":return n(s.object)&&n(s.index);case"sliceAccess":return n(s.object)&&n(s.start)&&n(s.end);case"binaryOp":return n(s.left)&&n(s.right);case"unaryOp":return n(s.operand);case"ternary":return n(s.condition)&&n(s.consequent)&&n(s.alternate);case"inExpr":return n(s.element)&&n(s.collection);case"isExpr":return n(s.value);case"listLiteral":return s.elements.every(n);case"mapLiteral":return s.entries.every(i=>n(i.key)&&n(i.value));case"pathLiteral":return s.segments.every(i=>typeof i=="string"||n(i));case"methodCall":return n(s.object)&&s.args.every(n);case"functionCall":{if(!s.args.every(n))return!1;const i=e.get(s.name);if(!i)return!0;if(r.has(s.name))return!1;const a=new Set(r).add(s.name);return qr(i.body,e,a)&&i.lets.every(o=>qr(o.value,e,a))}default:return!1}};return n(t)}function nd(t,e,r){const n=[],s=(i,a)=>{if(i.type==="binaryOp"&&i.op==="&&")return s(i.left,a)&&s(i.right,a);if(i.type==="functionCall"&&e.has(i.name)&&!a.has(i.name)){const c=e.get(i.name),u=new Map;c.parameters.forEach((p,y)=>{const v=i.args[y];v&&u.set(p,v)});for(const p of c.lets)u.set(p.name,vi(p.value,u));const f=vi(c.body,u),l=new Set(a).add(i.name);return s(f,l)}const o=sd(i,r);return o?(n.push(o),!0):qr(i,e)};return s(t,new Set)?{ok:!0,required:n}:{ok:!1}}function sd(t,e){if(t.type!=="binaryOp"||t.op!=="==")return null;const r=(n,s)=>{const i=ad(n);return i===null?null:s.type==="literal"?{field:i,value:s.value,fromAuthUid:!1}:e!==void 0&&id(s)?{field:i,value:e,fromAuthUid:!0}:null};return r(t.left,t.right)??r(t.right,t.left)}function id(t){return t.type==="memberAccess"&&t.property==="uid"&&t.object.type==="memberAccess"&&t.object.property==="auth"&&t.object.object.type==="identifier"&&t.object.object.name==="request"}function vi(t,e){const r=n=>{switch(n.type){case"identifier":return e.get(n.name)??n;case"literal":return n;case"memberAccess":return{...n,object:r(n.object)};case"methodCall":return{...n,object:r(n.object),args:n.args.map(r)};case"bracketAccess":return{...n,object:r(n.object),index:r(n.index)};case"sliceAccess":return{...n,object:r(n.object),start:r(n.start),end:r(n.end)};case"binaryOp":return{...n,left:r(n.left),right:r(n.right)};case"unaryOp":return{...n,operand:r(n.operand)};case"ternary":return{...n,condition:r(n.condition),consequent:r(n.consequent),alternate:r(n.alternate)};case"inExpr":return{...n,element:r(n.element),collection:r(n.collection)};case"isExpr":return{...n,value:r(n.value)};case"listLiteral":return{...n,elements:n.elements.map(r)};case"mapLiteral":return{...n,entries:n.entries.map(s=>({key:r(s.key),value:r(s.value)}))};case"pathLiteral":return{...n,segments:n.segments.map(s=>typeof s=="string"?s:r(s))};case"functionCall":return{...n,args:n.args.map(r)}}};return r(t)}function ad(t){return t.type==="memberAccess"&&t.object.type==="memberAccess"&&t.object.property==="data"&&t.object.object.type==="identifier"&&t.object.object.name==="resource"?t.property:null}function od(t,e){return t===e}class Ot extends te{typeName="reference";path;constructor(e){super(),this.path=cd(e)}static fromResourceName(e){return new Ot(Ya(e))}get id(){const e=this.path.lastIndexOf("/");return e===-1?this.path:this.path.slice(e+1)}get parent(){const e=this.path.lastIndexOf("/");return e===-1?"":this.path.slice(0,e)}valueOf(){return NaN}toString(){return this.path}toJSON(){return{__type:"reference",path:this.path}}equals(e){return e instanceof Ot?this.path===e.path:!1}field(e){switch(e){case"path":return this.path;case"id":return this.id;case"parent":return this.parent;default:return null}}callMethod(e,r){return oe}}function cd(t){let e=Ya(t);return e.startsWith("/")&&(e=e.slice(1)),e.endsWith("/")&&(e=e.slice(0,-1)),e}function Ya(t){const e="/documents/",r=t.indexOf(e);return r===-1?t:t.slice(r+e.length)}class Qt extends te{typeName="vector";value;constructor(e){if(super(),!Array.isArray(e))throw new TypeError("Vector: value must be a number[]");for(let r=0;r<e.length;r++)if(typeof e[r]!="number")throw new TypeError(`Vector: element at index ${r} is not a number (got ${typeof e[r]})`);this.value=Object.freeze(e.slice())}get dimension(){return this.value.length}valueOf(){return NaN}toString(){return`[${this.value.join(", ")}]`}toJSON(){return{__type__:"__vector__",value:this.value.slice()}}equals(e){if(!(e instanceof Qt)||e.value.length!==this.value.length)return!1;for(let r=0;r<this.value.length;r++)if(e.value[r]!==this.value[r])return!1;return!0}callMethod(e,r){return oe}}var J;(function(t){t.assertEqual=s=>{};function e(s){}t.assertIs=e;function r(s){throw new Error}t.assertNever=r,t.arrayToEnum=s=>{const i={};for(const a of s)i[a]=a;return i},t.getValidEnumValues=s=>{const i=t.objectKeys(s).filter(o=>typeof s[s[o]]!="number"),a={};for(const o of i)a[o]=s[o];return t.objectValues(a)},t.objectValues=s=>t.objectKeys(s).map(function(i){return s[i]}),t.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const i=[];for(const a in s)Object.prototype.hasOwnProperty.call(s,a)&&i.push(a);return i},t.find=(s,i)=>{for(const a of s)if(i(a))return a},t.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,i=" | "){return s.map(a=>typeof a=="string"?`'${a}'`:a).join(i)}t.joinValues=n,t.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(J||(J={}));var bi;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(bi||(bi={}));const q=J.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ft=t=>{switch(typeof t){case"undefined":return q.undefined;case"string":return q.string;case"number":return Number.isNaN(t)?q.nan:q.number;case"boolean":return q.boolean;case"function":return q.function;case"bigint":return q.bigint;case"symbol":return q.symbol;case"object":return Array.isArray(t)?q.array:t===null?q.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?q.promise:typeof Map<"u"&&t instanceof Map?q.map:typeof Set<"u"&&t instanceof Set?q.set:typeof Date<"u"&&t instanceof Date?q.date:q.object;default:return q.unknown}},N=J.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class dt extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};const r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){const r=e||function(i){return i.message},n={_errors:[]},s=i=>{for(const a of i.issues)if(a.code==="invalid_union")a.unionErrors.map(s);else if(a.code==="invalid_return_type")s(a.returnTypeError);else if(a.code==="invalid_arguments")s(a.argumentsError);else if(a.path.length===0)n._errors.push(r(a));else{let o=n,c=0;for(;c<a.path.length;){const u=a.path[c];c===a.path.length-1?(o[u]=o[u]||{_errors:[]},o[u]._errors.push(r(a))):o[u]=o[u]||{_errors:[]},o=o[u],c++}}};return s(this),n}static assert(e){if(!(e instanceof dt))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,J.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){const r={},n=[];for(const s of this.issues)if(s.path.length>0){const i=s.path[0];r[i]=r[i]||[],r[i].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}}dt.create=t=>new dt(t);const Gn=(t,e)=>{let r;switch(t.code){case N.invalid_type:t.received===q.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case N.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,J.jsonStringifyReplacer)}`;break;case N.unrecognized_keys:r=`Unrecognized key(s) in object: ${J.joinValues(t.keys,", ")}`;break;case N.invalid_union:r="Invalid input";break;case N.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${J.joinValues(t.options)}`;break;case N.invalid_enum_value:r=`Invalid enum value. Expected ${J.joinValues(t.options)}, received '${t.received}'`;break;case N.invalid_arguments:r="Invalid function arguments";break;case N.invalid_return_type:r="Invalid function return type";break;case N.invalid_date:r="Invalid date";break;case N.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:J.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case N.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case N.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case N.custom:r="Invalid input";break;case N.invalid_intersection_types:r="Intersection results could not be merged";break;case N.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case N.not_finite:r="Number must be finite";break;default:r=e.defaultError,J.assertNever(t)}return{message:r}};let ud=Gn;function ld(){return ud}const dd=t=>{const{data:e,path:r,errorMaps:n,issueData:s}=t,i=[...r,...s.path||[]],a={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let o="";const c=n.filter(u=>!!u).slice().reverse();for(const u of c)o=u(a,{data:e,defaultError:o}).message;return{...s,path:i,message:o}};function j(t,e){const r=ld(),n=dd({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Gn?void 0:Gn].filter(s=>!!s)});t.common.issues.push(n)}class De{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){const n=[];for(const s of r){if(s.status==="aborted")return U;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){const n=[];for(const s of r){const i=await s.key,a=await s.value;n.push({key:i,value:a})}return De.mergeObjectSync(e,n)}static mergeObjectSync(e,r){const n={};for(const s of r){const{key:i,value:a}=s;if(i.status==="aborted"||a.status==="aborted")return U;i.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof a.value<"u"||s.alwaysSet)&&(n[i.value]=a.value)}return{status:e.value,value:n}}}const U=Object.freeze({status:"aborted"}),ar=t=>({status:"dirty",value:t}),He=t=>({status:"valid",value:t}),wi=t=>t.status==="aborted",Si=t=>t.status==="dirty",Gt=t=>t.status==="valid",Pr=t=>typeof Promise<"u"&&t instanceof Promise;var P;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(P||(P={}));class tt{constructor(e,r,n,s){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const _i=(t,e)=>{if(Gt(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const r=new dt(t.common.issues);return this._error=r,this._error}}};function H(t){if(!t)return{};const{errorMap:e,invalid_type_error:r,required_error:n,description:s}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(a,o)=>{const{message:c}=t;return a.code==="invalid_enum_value"?{message:c??o.defaultError}:typeof o.data>"u"?{message:c??n??o.defaultError}:a.code!=="invalid_type"?{message:o.defaultError}:{message:c??r??o.defaultError}},description:s}}class K{get description(){return this._def.description}_getType(e){return ft(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:ft(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new De,ctx:{common:e.parent.common,data:e.data,parsedType:ft(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const r=this._parse(e);if(Pr(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){const r=this._parse(e);return Promise.resolve(r)}parse(e,r){const n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){const n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ft(e)},s=this._parseSync({data:e,path:n.path,parent:n});return _i(n,s)}"~validate"(e){const r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ft(e)};if(!this["~standard"].async)try{const n=this._parseSync({data:e,path:[],parent:r});return Gt(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>Gt(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){const n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){const n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ft(e)},s=this._parse({data:e,path:n.path,parent:n}),i=await(Pr(s)?s:Promise.resolve(s));return _i(n,i)}refine(e,r){const n=s=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(s):r;return this._refinement((s,i)=>{const a=e(s),o=()=>i.addIssue({code:N.custom,...n(s)});return typeof Promise<"u"&&a instanceof Promise?a.then(c=>c?!0:(o(),!1)):a?!0:(o(),!1)})}refinement(e,r){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof r=="function"?r(n,s):r),!1))}_refinement(e){return new Nt({schema:this,typeName:B.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return ut.create(this,this._def)}nullable(){return Lt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Xe.create(this)}promise(){return Wr.create(this,this._def)}or(e){return Br.create([this,e],this._def)}and(e){return zr.create(this,e,this._def)}transform(e){return new Nt({...H(this._def),schema:this,typeName:B.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const r=typeof e=="function"?e:()=>e;return new Gr({...H(this._def),innerType:this,defaultValue:r,typeName:B.ZodDefault})}brand(){return new to({typeName:B.ZodBranded,type:this,...H(this._def)})}catch(e){const r=typeof e=="function"?e:()=>e;return new Kr({...H(this._def),innerType:this,catchValue:r,typeName:B.ZodCatch})}describe(e){const r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Es.create(this,e)}readonly(){return Zr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const hd=/^c[^\s-]{8,}$/i,fd=/^[0-9a-z]+$/,pd=/^[0-9A-HJKMNP-TV-Z]{26}$/i,md=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,gd=/^[a-z0-9_-]{21}$/i,yd=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,vd=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,bd=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,wd="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let An;const Sd=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,_d=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Ad=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Id=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,xd=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,kd=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Qa="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Ed=new RegExp(`^${Qa}$`);function Xa(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);const r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function Td(t){return new RegExp(`^${Xa(t)}$`)}function Od(t){let e=`${Qa}T${Xa(t)}`;const r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function Cd(t,e){return!!((e==="v4"||!e)&&Sd.test(t)||(e==="v6"||!e)&&Ad.test(t))}function Rd(t,e){if(!yd.test(t))return!1;try{const[r]=t.split(".");if(!r)return!1;const n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),s=JSON.parse(atob(n));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function Nd(t,e){return!!((e==="v4"||!e)&&_d.test(t)||(e==="v6"||!e)&&Id.test(t))}class at extends K{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==q.string){const i=this._getOrReturnCtx(e);return j(i,{code:N.invalid_type,expected:q.string,received:i.parsedType}),U}const n=new De;let s;for(const i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),j(s,{code:N.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),j(s,{code:N.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="length"){const a=e.data.length>i.value,o=e.data.length<i.value;(a||o)&&(s=this._getOrReturnCtx(e,s),a?j(s,{code:N.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):o&&j(s,{code:N.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),n.dirty())}else if(i.kind==="email")bd.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"email",code:N.invalid_string,message:i.message}),n.dirty());else if(i.kind==="emoji")An||(An=new RegExp(wd,"u")),An.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"emoji",code:N.invalid_string,message:i.message}),n.dirty());else if(i.kind==="uuid")md.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"uuid",code:N.invalid_string,message:i.message}),n.dirty());else if(i.kind==="nanoid")gd.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"nanoid",code:N.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid")hd.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"cuid",code:N.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid2")fd.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"cuid2",code:N.invalid_string,message:i.message}),n.dirty());else if(i.kind==="ulid")pd.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"ulid",code:N.invalid_string,message:i.message}),n.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),j(s,{validation:"url",code:N.invalid_string,message:i.message}),n.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"regex",code:N.invalid_string,message:i.message}),n.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),j(s,{code:N.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),n.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),j(s,{code:N.invalid_string,validation:{startsWith:i.value},message:i.message}),n.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),j(s,{code:N.invalid_string,validation:{endsWith:i.value},message:i.message}),n.dirty()):i.kind==="datetime"?Od(i).test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{code:N.invalid_string,validation:"datetime",message:i.message}),n.dirty()):i.kind==="date"?Ed.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{code:N.invalid_string,validation:"date",message:i.message}),n.dirty()):i.kind==="time"?Td(i).test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{code:N.invalid_string,validation:"time",message:i.message}),n.dirty()):i.kind==="duration"?vd.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"duration",code:N.invalid_string,message:i.message}),n.dirty()):i.kind==="ip"?Cd(e.data,i.version)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"ip",code:N.invalid_string,message:i.message}),n.dirty()):i.kind==="jwt"?Rd(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"jwt",code:N.invalid_string,message:i.message}),n.dirty()):i.kind==="cidr"?Nd(e.data,i.version)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"cidr",code:N.invalid_string,message:i.message}),n.dirty()):i.kind==="base64"?xd.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"base64",code:N.invalid_string,message:i.message}),n.dirty()):i.kind==="base64url"?kd.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"base64url",code:N.invalid_string,message:i.message}),n.dirty()):J.assertNever(i);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(s=>e.test(s),{validation:r,code:N.invalid_string,...P.errToObj(n)})}_addCheck(e){return new at({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...P.errToObj(e)})}url(e){return this._addCheck({kind:"url",...P.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...P.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...P.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...P.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...P.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...P.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...P.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...P.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...P.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...P.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...P.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...P.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...P.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...P.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...P.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...P.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...P.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...P.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...P.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...P.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...P.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...P.errToObj(r)})}nonempty(e){return this.min(1,P.errToObj(e))}trim(){return new at({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new at({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new at({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}}at.create=t=>new at({checks:[],typeName:B.ZodString,coerce:t?.coerce??!1,...H(t)});function Ld(t,e){const r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=r>n?r:n,i=Number.parseInt(t.toFixed(s).replace(".","")),a=Number.parseInt(e.toFixed(s).replace(".",""));return i%a/10**s}class Kt extends K{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==q.number){const i=this._getOrReturnCtx(e);return j(i,{code:N.invalid_type,expected:q.number,received:i.parsedType}),U}let n;const s=new De;for(const i of this._def.checks)i.kind==="int"?J.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),j(n,{code:N.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),j(n,{code:N.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),j(n,{code:N.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?Ld(e.data,i.value)!==0&&(n=this._getOrReturnCtx(e,n),j(n,{code:N.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),j(n,{code:N.not_finite,message:i.message}),s.dirty()):J.assertNever(i);return{status:s.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,P.toString(r))}gt(e,r){return this.setLimit("min",e,!1,P.toString(r))}lte(e,r){return this.setLimit("max",e,!0,P.toString(r))}lt(e,r){return this.setLimit("max",e,!1,P.toString(r))}setLimit(e,r,n,s){return new Kt({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:P.toString(s)}]})}_addCheck(e){return new Kt({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:P.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:P.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:P.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:P.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:P.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:P.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:P.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:P.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:P.toString(e)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&J.isInteger(e.value))}get isFinite(){let e=null,r=null;for(const n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}}Kt.create=t=>new Kt({checks:[],typeName:B.ZodNumber,coerce:t?.coerce||!1,...H(t)});class hr extends K{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==q.bigint)return this._getInvalidInput(e);let n;const s=new De;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),j(n,{code:N.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),j(n,{code:N.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),j(n,{code:N.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):J.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){const r=this._getOrReturnCtx(e);return j(r,{code:N.invalid_type,expected:q.bigint,received:r.parsedType}),U}gte(e,r){return this.setLimit("min",e,!0,P.toString(r))}gt(e,r){return this.setLimit("min",e,!1,P.toString(r))}lte(e,r){return this.setLimit("max",e,!0,P.toString(r))}lt(e,r){return this.setLimit("max",e,!1,P.toString(r))}setLimit(e,r,n,s){return new hr({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:P.toString(s)}]})}_addCheck(e){return new hr({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:P.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:P.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:P.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:P.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:P.toString(r)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}}hr.create=t=>new hr({checks:[],typeName:B.ZodBigInt,coerce:t?.coerce??!1,...H(t)});class Kn extends K{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==q.boolean){const n=this._getOrReturnCtx(e);return j(n,{code:N.invalid_type,expected:q.boolean,received:n.parsedType}),U}return He(e.data)}}Kn.create=t=>new Kn({typeName:B.ZodBoolean,coerce:t?.coerce||!1,...H(t)});class $r extends K{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==q.date){const i=this._getOrReturnCtx(e);return j(i,{code:N.invalid_type,expected:q.date,received:i.parsedType}),U}if(Number.isNaN(e.data.getTime())){const i=this._getOrReturnCtx(e);return j(i,{code:N.invalid_date}),U}const n=new De;let s;for(const i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),j(s,{code:N.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),n.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),j(s,{code:N.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),n.dirty()):J.assertNever(i);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new $r({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:P.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:P.toString(r)})}get minDate(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}}$r.create=t=>new $r({checks:[],coerce:t?.coerce||!1,typeName:B.ZodDate,...H(t)});class Ai extends K{_parse(e){if(this._getType(e)!==q.symbol){const n=this._getOrReturnCtx(e);return j(n,{code:N.invalid_type,expected:q.symbol,received:n.parsedType}),U}return He(e.data)}}Ai.create=t=>new Ai({typeName:B.ZodSymbol,...H(t)});class Zn extends K{_parse(e){if(this._getType(e)!==q.undefined){const n=this._getOrReturnCtx(e);return j(n,{code:N.invalid_type,expected:q.undefined,received:n.parsedType}),U}return He(e.data)}}Zn.create=t=>new Zn({typeName:B.ZodUndefined,...H(t)});class Ur extends K{_parse(e){if(this._getType(e)!==q.null){const n=this._getOrReturnCtx(e);return j(n,{code:N.invalid_type,expected:q.null,received:n.parsedType}),U}return He(e.data)}}Ur.create=t=>new Ur({typeName:B.ZodNull,...H(t)});class Ii extends K{constructor(){super(...arguments),this._any=!0}_parse(e){return He(e.data)}}Ii.create=t=>new Ii({typeName:B.ZodAny,...H(t)});class Jn extends K{constructor(){super(...arguments),this._unknown=!0}_parse(e){return He(e.data)}}Jn.create=t=>new Jn({typeName:B.ZodUnknown,...H(t)});class yt extends K{_parse(e){const r=this._getOrReturnCtx(e);return j(r,{code:N.invalid_type,expected:q.never,received:r.parsedType}),U}}yt.create=t=>new yt({typeName:B.ZodNever,...H(t)});class xi extends K{_parse(e){if(this._getType(e)!==q.undefined){const n=this._getOrReturnCtx(e);return j(n,{code:N.invalid_type,expected:q.void,received:n.parsedType}),U}return He(e.data)}}xi.create=t=>new xi({typeName:B.ZodVoid,...H(t)});class Xe extends K{_parse(e){const{ctx:r,status:n}=this._processInputParams(e),s=this._def;if(r.parsedType!==q.array)return j(r,{code:N.invalid_type,expected:q.array,received:r.parsedType}),U;if(s.exactLength!==null){const a=r.data.length>s.exactLength.value,o=r.data.length<s.exactLength.value;(a||o)&&(j(r,{code:a?N.too_big:N.too_small,minimum:o?s.exactLength.value:void 0,maximum:a?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&r.data.length<s.minLength.value&&(j(r,{code:N.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&r.data.length>s.maxLength.value&&(j(r,{code:N.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((a,o)=>s.type._parseAsync(new tt(r,a,r.path,o)))).then(a=>De.mergeArray(n,a));const i=[...r.data].map((a,o)=>s.type._parseSync(new tt(r,a,r.path,o)));return De.mergeArray(n,i)}get element(){return this._def.type}min(e,r){return new Xe({...this._def,minLength:{value:e,message:P.toString(r)}})}max(e,r){return new Xe({...this._def,maxLength:{value:e,message:P.toString(r)}})}length(e,r){return new Xe({...this._def,exactLength:{value:e,message:P.toString(r)}})}nonempty(e){return this.min(1,e)}}Xe.create=(t,e)=>new Xe({type:t,minLength:null,maxLength:null,exactLength:null,typeName:B.ZodArray,...H(e)});function Bt(t){if(t instanceof fe){const e={};for(const r in t.shape){const n=t.shape[r];e[r]=ut.create(Bt(n))}return new fe({...t._def,shape:()=>e})}else return t instanceof Xe?new Xe({...t._def,type:Bt(t.element)}):t instanceof ut?ut.create(Bt(t.unwrap())):t instanceof Lt?Lt.create(Bt(t.unwrap())):t instanceof Ct?Ct.create(t.items.map(e=>Bt(e))):t}class fe extends K{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),r=J.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==q.object){const u=this._getOrReturnCtx(e);return j(u,{code:N.invalid_type,expected:q.object,received:u.parsedType}),U}const{status:n,ctx:s}=this._processInputParams(e),{shape:i,keys:a}=this._getCached(),o=[];if(!(this._def.catchall instanceof yt&&this._def.unknownKeys==="strip"))for(const u in s.data)a.includes(u)||o.push(u);const c=[];for(const u of a){const f=i[u],l=s.data[u];c.push({key:{status:"valid",value:u},value:f._parse(new tt(s,l,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof yt){const u=this._def.unknownKeys;if(u==="passthrough")for(const f of o)c.push({key:{status:"valid",value:f},value:{status:"valid",value:s.data[f]}});else if(u==="strict")o.length>0&&(j(s,{code:N.unrecognized_keys,keys:o}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const u=this._def.catchall;for(const f of o){const l=s.data[f];c.push({key:{status:"valid",value:f},value:u._parse(new tt(s,l,s.path,f)),alwaysSet:f in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const u=[];for(const f of c){const l=await f.key,p=await f.value;u.push({key:l,value:p,alwaysSet:f.alwaysSet})}return u}).then(u=>De.mergeObjectSync(n,u)):De.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return P.errToObj,new fe({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{const s=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:P.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new fe({...this._def,unknownKeys:"strip"})}passthrough(){return new fe({...this._def,unknownKeys:"passthrough"})}extend(e){return new fe({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new fe({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:B.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new fe({...this._def,catchall:e})}pick(e){const r={};for(const n of J.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new fe({...this._def,shape:()=>r})}omit(e){const r={};for(const n of J.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new fe({...this._def,shape:()=>r})}deepPartial(){return Bt(this)}partial(e){const r={};for(const n of J.objectKeys(this.shape)){const s=this.shape[n];e&&!e[n]?r[n]=s:r[n]=s.optional()}return new fe({...this._def,shape:()=>r})}required(e){const r={};for(const n of J.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let i=this.shape[n];for(;i instanceof ut;)i=i._def.innerType;r[n]=i}return new fe({...this._def,shape:()=>r})}keyof(){return eo(J.objectKeys(this.shape))}}fe.create=(t,e)=>new fe({shape:()=>t,unknownKeys:"strip",catchall:yt.create(),typeName:B.ZodObject,...H(e)});fe.strictCreate=(t,e)=>new fe({shape:()=>t,unknownKeys:"strict",catchall:yt.create(),typeName:B.ZodObject,...H(e)});fe.lazycreate=(t,e)=>new fe({shape:t,unknownKeys:"strip",catchall:yt.create(),typeName:B.ZodObject,...H(e)});class Br extends K{_parse(e){const{ctx:r}=this._processInputParams(e),n=this._def.options;function s(i){for(const o of i)if(o.result.status==="valid")return o.result;for(const o of i)if(o.result.status==="dirty")return r.common.issues.push(...o.ctx.common.issues),o.result;const a=i.map(o=>new dt(o.ctx.common.issues));return j(r,{code:N.invalid_union,unionErrors:a}),U}if(r.common.async)return Promise.all(n.map(async i=>{const a={...r,common:{...r.common,issues:[]},parent:null};return{result:await i._parseAsync({data:r.data,path:r.path,parent:a}),ctx:a}})).then(s);{let i;const a=[];for(const c of n){const u={...r,common:{...r.common,issues:[]},parent:null},f=c._parseSync({data:r.data,path:r.path,parent:u});if(f.status==="valid")return f;f.status==="dirty"&&!i&&(i={result:f,ctx:u}),u.common.issues.length&&a.push(u.common.issues)}if(i)return r.common.issues.push(...i.ctx.common.issues),i.result;const o=a.map(c=>new dt(c));return j(r,{code:N.invalid_union,unionErrors:o}),U}}get options(){return this._def.options}}Br.create=(t,e)=>new Br({options:t,typeName:B.ZodUnion,...H(e)});const st=t=>t instanceof Qn?st(t.schema):t instanceof Nt?st(t.innerType()):t instanceof Hr?[t.value]:t instanceof Rt?t.options:t instanceof Xn?J.objectValues(t.enum):t instanceof Gr?st(t._def.innerType):t instanceof Zn?[void 0]:t instanceof Ur?[null]:t instanceof ut?[void 0,...st(t.unwrap())]:t instanceof Lt?[null,...st(t.unwrap())]:t instanceof to||t instanceof Zr?st(t.unwrap()):t instanceof Kr?st(t._def.innerType):[];class ks extends K{_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==q.object)return j(r,{code:N.invalid_type,expected:q.object,received:r.parsedType}),U;const n=this.discriminator,s=r.data[n],i=this.optionsMap.get(s);return i?r.common.async?i._parseAsync({data:r.data,path:r.path,parent:r}):i._parseSync({data:r.data,path:r.path,parent:r}):(j(r,{code:N.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),U)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){const s=new Map;for(const i of r){const a=st(i.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const o of a){if(s.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);s.set(o,i)}}return new ks({typeName:B.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:s,...H(n)})}}function Yn(t,e){const r=ft(t),n=ft(e);if(t===e)return{valid:!0,data:t};if(r===q.object&&n===q.object){const s=J.objectKeys(e),i=J.objectKeys(t).filter(o=>s.indexOf(o)!==-1),a={...t,...e};for(const o of i){const c=Yn(t[o],e[o]);if(!c.valid)return{valid:!1};a[o]=c.data}return{valid:!0,data:a}}else if(r===q.array&&n===q.array){if(t.length!==e.length)return{valid:!1};const s=[];for(let i=0;i<t.length;i++){const a=t[i],o=e[i],c=Yn(a,o);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return r===q.date&&n===q.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}class zr extends K{_parse(e){const{status:r,ctx:n}=this._processInputParams(e),s=(i,a)=>{if(wi(i)||wi(a))return U;const o=Yn(i.value,a.value);return o.valid?((Si(i)||Si(a))&&r.dirty(),{status:r.value,value:o.data}):(j(n,{code:N.invalid_intersection_types}),U)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([i,a])=>s(i,a)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}zr.create=(t,e,r)=>new zr({left:t,right:e,typeName:B.ZodIntersection,...H(r)});class Ct extends K{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==q.array)return j(n,{code:N.invalid_type,expected:q.array,received:n.parsedType}),U;if(n.data.length<this._def.items.length)return j(n,{code:N.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),U;!this._def.rest&&n.data.length>this._def.items.length&&(j(n,{code:N.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());const i=[...n.data].map((a,o)=>{const c=this._def.items[o]||this._def.rest;return c?c._parse(new tt(n,a,n.path,o)):null}).filter(a=>!!a);return n.common.async?Promise.all(i).then(a=>De.mergeArray(r,a)):De.mergeArray(r,i)}get items(){return this._def.items}rest(e){return new Ct({...this._def,rest:e})}}Ct.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ct({items:t,typeName:B.ZodTuple,rest:null,...H(e)})};class Vr extends K{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==q.object)return j(n,{code:N.invalid_type,expected:q.object,received:n.parsedType}),U;const s=[],i=this._def.keyType,a=this._def.valueType;for(const o in n.data)s.push({key:i._parse(new tt(n,o,n.path,o)),value:a._parse(new tt(n,n.data[o],n.path,o)),alwaysSet:o in n.data});return n.common.async?De.mergeObjectAsync(r,s):De.mergeObjectSync(r,s)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof K?new Vr({keyType:e,valueType:r,typeName:B.ZodRecord,...H(n)}):new Vr({keyType:at.create(),valueType:e,typeName:B.ZodRecord,...H(r)})}}class ki extends K{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==q.map)return j(n,{code:N.invalid_type,expected:q.map,received:n.parsedType}),U;const s=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([o,c],u)=>({key:s._parse(new tt(n,o,n.path,[u,"key"])),value:i._parse(new tt(n,c,n.path,[u,"value"]))}));if(n.common.async){const o=new Map;return Promise.resolve().then(async()=>{for(const c of a){const u=await c.key,f=await c.value;if(u.status==="aborted"||f.status==="aborted")return U;(u.status==="dirty"||f.status==="dirty")&&r.dirty(),o.set(u.value,f.value)}return{status:r.value,value:o}})}else{const o=new Map;for(const c of a){const u=c.key,f=c.value;if(u.status==="aborted"||f.status==="aborted")return U;(u.status==="dirty"||f.status==="dirty")&&r.dirty(),o.set(u.value,f.value)}return{status:r.value,value:o}}}}ki.create=(t,e,r)=>new ki({valueType:e,keyType:t,typeName:B.ZodMap,...H(r)});class fr extends K{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==q.set)return j(n,{code:N.invalid_type,expected:q.set,received:n.parsedType}),U;const s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(j(n,{code:N.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),r.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(j(n,{code:N.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),r.dirty());const i=this._def.valueType;function a(c){const u=new Set;for(const f of c){if(f.status==="aborted")return U;f.status==="dirty"&&r.dirty(),u.add(f.value)}return{status:r.value,value:u}}const o=[...n.data.values()].map((c,u)=>i._parse(new tt(n,c,n.path,u)));return n.common.async?Promise.all(o).then(c=>a(c)):a(o)}min(e,r){return new fr({...this._def,minSize:{value:e,message:P.toString(r)}})}max(e,r){return new fr({...this._def,maxSize:{value:e,message:P.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}}fr.create=(t,e)=>new fr({valueType:t,minSize:null,maxSize:null,typeName:B.ZodSet,...H(e)});class Qn extends K{get schema(){return this._def.getter()}_parse(e){const{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}}Qn.create=(t,e)=>new Qn({getter:t,typeName:B.ZodLazy,...H(e)});class Hr extends K{_parse(e){if(e.data!==this._def.value){const r=this._getOrReturnCtx(e);return j(r,{received:r.data,code:N.invalid_literal,expected:this._def.value}),U}return{status:"valid",value:e.data}}get value(){return this._def.value}}Hr.create=(t,e)=>new Hr({value:t,typeName:B.ZodLiteral,...H(e)});function eo(t,e){return new Rt({values:t,typeName:B.ZodEnum,...H(e)})}class Rt extends K{_parse(e){if(typeof e.data!="string"){const r=this._getOrReturnCtx(e),n=this._def.values;return j(r,{expected:J.joinValues(n),received:r.parsedType,code:N.invalid_type}),U}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const r=this._getOrReturnCtx(e),n=this._def.values;return j(r,{received:r.data,code:N.invalid_enum_value,options:n}),U}return He(e.data)}get options(){return this._def.values}get enum(){const e={};for(const r of this._def.values)e[r]=r;return e}get Values(){const e={};for(const r of this._def.values)e[r]=r;return e}get Enum(){const e={};for(const r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return Rt.create(e,{...this._def,...r})}exclude(e,r=this._def){return Rt.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}}Rt.create=eo;class Xn extends K{_parse(e){const r=J.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==q.string&&n.parsedType!==q.number){const s=J.objectValues(r);return j(n,{expected:J.joinValues(s),received:n.parsedType,code:N.invalid_type}),U}if(this._cache||(this._cache=new Set(J.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const s=J.objectValues(r);return j(n,{received:n.data,code:N.invalid_enum_value,options:s}),U}return He(e.data)}get enum(){return this._def.values}}Xn.create=(t,e)=>new Xn({values:t,typeName:B.ZodNativeEnum,...H(e)});class Wr extends K{unwrap(){return this._def.type}_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==q.promise&&r.common.async===!1)return j(r,{code:N.invalid_type,expected:q.promise,received:r.parsedType}),U;const n=r.parsedType===q.promise?r.data:Promise.resolve(r.data);return He(n.then(s=>this._def.type.parseAsync(s,{path:r.path,errorMap:r.common.contextualErrorMap})))}}Wr.create=(t,e)=>new Wr({type:t,typeName:B.ZodPromise,...H(e)});class Nt extends K{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===B.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:r,ctx:n}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:a=>{j(n,a),a.fatal?r.abort():r.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){const a=s.transform(n.data,i);if(n.common.async)return Promise.resolve(a).then(async o=>{if(r.value==="aborted")return U;const c=await this._def.schema._parseAsync({data:o,path:n.path,parent:n});return c.status==="aborted"?U:c.status==="dirty"||r.value==="dirty"?ar(c.value):c});{if(r.value==="aborted")return U;const o=this._def.schema._parseSync({data:a,path:n.path,parent:n});return o.status==="aborted"?U:o.status==="dirty"||r.value==="dirty"?ar(o.value):o}}if(s.type==="refinement"){const a=o=>{const c=s.refinement(o,i);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(n.common.async===!1){const o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?U:(o.status==="dirty"&&r.dirty(),a(o.value),{status:r.value,value:o.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>o.status==="aborted"?U:(o.status==="dirty"&&r.dirty(),a(o.value).then(()=>({status:r.value,value:o.value}))))}if(s.type==="transform")if(n.common.async===!1){const a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Gt(a))return U;const o=s.transform(a.value,i);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:o}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>Gt(a)?Promise.resolve(s.transform(a.value,i)).then(o=>({status:r.value,value:o})):U);J.assertNever(s)}}Nt.create=(t,e,r)=>new Nt({schema:t,typeName:B.ZodEffects,effect:e,...H(r)});Nt.createWithPreprocess=(t,e,r)=>new Nt({schema:e,effect:{type:"preprocess",transform:t},typeName:B.ZodEffects,...H(r)});class ut extends K{_parse(e){return this._getType(e)===q.undefined?He(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ut.create=(t,e)=>new ut({innerType:t,typeName:B.ZodOptional,...H(e)});class Lt extends K{_parse(e){return this._getType(e)===q.null?He(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Lt.create=(t,e)=>new Lt({innerType:t,typeName:B.ZodNullable,...H(e)});class Gr extends K{_parse(e){const{ctx:r}=this._processInputParams(e);let n=r.data;return r.parsedType===q.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}}Gr.create=(t,e)=>new Gr({innerType:t,typeName:B.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...H(e)});class Kr extends K{_parse(e){const{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Pr(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new dt(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new dt(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}Kr.create=(t,e)=>new Kr({innerType:t,typeName:B.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...H(e)});class Ei extends K{_parse(e){if(this._getType(e)!==q.nan){const n=this._getOrReturnCtx(e);return j(n,{code:N.invalid_type,expected:q.nan,received:n.parsedType}),U}return{status:"valid",value:e.data}}}Ei.create=t=>new Ei({typeName:B.ZodNaN,...H(t)});class to extends K{_parse(e){const{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}}class Es extends K{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?U:i.status==="dirty"?(r.dirty(),ar(i.value)):this._def.out._parseAsync({data:i.value,path:n.path,parent:n})})();{const s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?U:s.status==="dirty"?(r.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,r){return new Es({in:e,out:r,typeName:B.ZodPipeline})}}class Zr extends K{_parse(e){const r=this._def.innerType._parse(e),n=s=>(Gt(s)&&(s.value=Object.freeze(s.value)),s);return Pr(r)?r.then(s=>n(s)):n(r)}unwrap(){return this._def.innerType}}Zr.create=(t,e)=>new Zr({innerType:t,typeName:B.ZodReadonly,...H(e)});var B;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(B||(B={}));const Et=at.create,Ti=Kt.create,Ts=Kn.create,Md=Ur.create,pr=Jn.create;yt.create;const Dd=Xe.create,ot=fe.create,Os=Br.create,Fd=ks.create;zr.create;Ct.create;const mr=Vr.create,Sr=Hr.create,Jr=Rt.create;Wr.create;ut.create;Lt.create;const jd=["get","list","create","update","delete"],qd=ot({uid:Et(),token:mr(pr()).optional()}),Pd=ot({function:Jr(["get","exists"]).describe("Firestore function to mock"),path:Et().describe('Document path, e.g. "users/alice"'),result:Os([mr(pr()),Ts()]).describe("Document data for get, boolean for exists")}),$d=Fd("kind",[ot({kind:Sr("create")}),ot({kind:Sr("set"),merge:Ts()}),ot({kind:Sr("update")}),ot({kind:Sr("delete")})]),Ud=ot({limit:Ti().optional(),offset:Ti().optional(),orderBy:Et().optional()});ot({description:Et().describe("Human-readable description of what this test verifies"),expectation:Jr(["ALLOW","DENY"]).describe("Expected outcome"),method:Jr(jd).describe("Firestore method to test"),path:Et().describe('Document path, e.g. "users/alice"'),auth:Os([qd,Md()]).optional().describe("Auth context; null or omitted for unauthenticated"),data:mr(pr()).optional().describe("request.resource.data for write operations"),resource:mr(pr()).optional().describe("Existing document data (resource.data)"),functionMocks:Dd(Pd).optional().describe("Mock get()/exists() calls in rules"),query:Ud.optional().describe("request.query payload (list ops only): limit/offset/orderBy."),requestTime:Et().optional().describe("Override for request.time (ISO-8601). Defaults to wallclock."),writeMode:$d.optional().describe("Optional write-mode override; controls update merge semantics and getAfter() projection.")});function Mt(t){if(t.decision==="UNSUPPORTED")return;const r=t.decision==="ALLOW";let n="deny",s;if(r)n="allow",s=t.trace.find(C=>C.verdict==="ALLOW");else if(n="deny",s=t.trace.find(k=>k.verdict==="DENY"?!0:k.verdict==="ERROR"),s===void 0){const k=t.trace.length;k>0&&(s=t.trace[k-1])}if(s===void 0)return;const a={verdict:n};s.line!==void 0&&(a.line=s.line),s.col!==void 0&&(a.col=s.col,a.column=s.col),s.column!==void 0&&(a.col=s.column,a.column=s.column),s.file!==void 0&&(a.file=s.file),s.citation!==void 0&&(a.citation=s.citation),s.conditionText!==void 0&&(a.expression=s.conditionText),s.expressionTrace!==void 0&&(a.expressionTrace=s.expressionTrace);const v=a.line!==void 0,w=a.expression!==void 0,R=a.expressionTrace!==void 0;if(v||w||R)return a}function be(t){const e=[];for(const r of t.notes)e.push(r);for(const r of t.trace){const n=r.operations.join(","),s=`Rule #${r.ruleIndex} (${n})`;r.verdict==="ALLOW"?e.push(`${s} → ALLOW`):r.verdict==="DENY"?e.push(`${s} → deny`):r.verdict==="UNSUPPORTED"?e.push(`${s} → unsupported: ${r.message??""}`):e.push(`${s} → error: ${r.message??""}`)}return e.push(`Simulated: ${t.decision}`),e}ot({function:Jr(["get","exists"]).describe("Cross-service Firestore function to mock"),path:Et().describe('Firestore document path in collection/doc form, e.g. "users/alice"'),result:Os([mr(pr()),Ts()]).describe("Document fields for get, boolean for exists")});const Bd={atomic:`// @pyric-services cloud.firestore
496
+ // Atomic module — cross-document integrity for BATCH writes, via the
497
+ // get()/getAfter() pair. Firestore evaluates every write in a batch
498
+ // against rules, and getAfter() returns another document's POST-BATCH
499
+ // state — so a rule can require "this write is only valid if a
500
+ // companion write happened in the same atomic batch".
501
+ //
502
+ // All semantics live-verified against a production database: companion
503
+ // visibility, solo-write denial, wrong-delta denial, single-use consumption
504
+ // incl. replay denial, and out-of-batch getAfter() falling back to current
505
+ // state.
506
+ //
507
+ // Explicit-param design: pass BOTH states of the companion doc —
508
+ // \`get(path).data\` (pre-batch) and \`getAfter(path).data\` (post-batch).
509
+ //
510
+ // import { companionChangedBy, consumedFlag } from 'atomic';
511
+ //
512
+ // // Denormalized counter: creating a task REQUIRES the team's
513
+ // // taskCount to have been incremented in the same batch:
514
+ // match /teams/{teamId}/tasks/{taskId} {
515
+ // function teamBefore() {
516
+ // return get(/databases/$(database)/documents/teams/$(teamId)).data;
517
+ // }
518
+ // function teamAfter() {
519
+ // return getAfter(/databases/$(database)/documents/teams/$(teamId)).data;
520
+ // }
521
+ // allow create: if companionChangedBy(teamBefore(), teamAfter(), 'taskCount', 1);
522
+ // }
523
+ //
524
+ // // Single-use invite: the join is valid only when the invite was
525
+ // // consumed (false -> true) IN THIS BATCH — replays deny because
526
+ // // the pre-batch state is already true:
527
+ // allow update: if consumedFlag(inviteBefore(), inviteAfter(), 'used');
528
+ //
529
+ // NOTE (simulator): in-batch companion semantics cannot be expressed
530
+ // in the simulator or the Rules Test API mock surface — the simulator
531
+ // treats cross-doc getAfter() as get(). These function BODIES are
532
+ // simulator-tested with explicit values; the getAfter() WIRING is the
533
+ // live v1 scope's job. Companion writes need their own allow rules too —
534
+ // every write in a batch is evaluated.
535
+
536
+ // The companion doc's field changed by EXACTLY n in this batch.
537
+ // before/after are the SAME doc's get()/getAfter() data.
538
+ export function companionChangedBy(before, after, field, n) {
539
+ return after[field] == before[field] + n;
540
+ }
541
+
542
+ // A single-use flag was consumed IN THIS BATCH: pre-batch false,
543
+ // post-batch true. Replays deny (pre-batch is already true), and a
544
+ // solo write denies (getAfter == get, so false != true).
545
+ export function consumedFlag(before, after, flagField) {
546
+ return before[flagField] == false && after[flagField] == true;
547
+ }
548
+ `,auth:`// @pyric-services cloud.firestore,firebase.storage
549
+ // @pyric-evidence storage-rules#125,firestore-rules#189
550
+ export function isAuthenticated() {
551
+ return request.auth != null;
552
+ }
553
+
554
+ export function isOwner(userId) {
555
+ return isAuthenticated() && request.auth.uid == userId;
556
+ }
557
+ `,content:`// @pyric-services cloud.firestore
558
+ // Content module for author-owned documents — the most common
559
+ // Firebase app shape (posts, notes, docs, comments, tasks).
560
+ //
561
+ // Convention: documents carry an author field (a UID string) and
562
+ // usually a status field ('draft' | 'published' | ...). Field names
563
+ // are parameters, not conventions — pass yours.
564
+ //
565
+ // Usage:
566
+ // import { validAuthorCreate, isAuthor, canReadContent, notDeleted } from 'content';
567
+ // import { onlyFieldsChanged } from 'lifecycle';
568
+ //
569
+ // match /posts/{postId} {
570
+ // // Create: author is the signed-in user.
571
+ // allow create: if validAuthorCreate('author');
572
+ // // Read: published to everyone, drafts to the author only.
573
+ // allow read: if canReadContent('status', 'author') && notDeleted();
574
+ // // Update: author edits content fields; authorship immutable.
575
+ // allow update: if isAuthor('author') && onlyFieldsChanged(['title', 'body', 'status']);
576
+ // allow delete: if isAuthor('author');
577
+ // }
578
+
579
+ // Create guard: signed in, and the incoming doc's author field is the
580
+ // caller. Use on \`create\` (reads request.resource).
581
+ export function validAuthorCreate(authorField) {
582
+ return request.auth != null
583
+ && request.resource.data[authorField] == request.auth.uid;
584
+ }
585
+
586
+ // The caller is the EXISTING document's author. Use on update/delete
587
+ // (reads resource).
588
+ export function isAuthor(authorField) {
589
+ return request.auth != null
590
+ && resource.data[authorField] == request.auth.uid;
591
+ }
592
+
593
+ // Read visibility: published content is public; anything else is
594
+ // visible to its author only. Works for get; for list queries the
595
+ // client must filter (rules are not filters — a bare collection query
596
+ // will be denied unless it proves status == 'published').
597
+ export function canReadContent(statusField, authorField) {
598
+ return resource.data[statusField] == 'published'
599
+ || (request.auth != null && resource.data[authorField] == request.auth.uid);
600
+ }
601
+
602
+ // Soft-delete guard: the document is not marked deleted. Reads the
603
+ // EXISTING doc; a doc without the field passes — bracket access is
604
+ // the null-on-miss idiom (dotted access of a missing key ERRORS).
605
+ export function notDeleted() {
606
+ return resource.data['deleted'] != true;
607
+ }
608
+ `,counters:`// @pyric-services cloud.firestore
609
+ // Counters module for denormalized numeric integrity.
610
+ //
611
+ // The recurring shape: a client-maintained count (likes, votes, moves,
612
+ // quantities) that rules must keep honest — it may only change by a
613
+ // known step, or stay within known bounds. Generalizes the
614
+ // state-module's moveIncremented() (hardcoded to moveCount) to any
615
+ // field.
616
+ //
617
+ // Usage:
618
+ // import { incrementedBy, changedBy, boundedNumber } from 'counters';
619
+ //
620
+ // // A like toggle: likeCount moves by exactly ±1:
621
+ // allow update: if changedBy('likeCount', -1, 1);
622
+ //
623
+ // // A move counter: strictly +1 per move:
624
+ // allow update: if incrementedBy('moveCount', 1);
625
+ //
626
+ // // A rating: any write keeps it in [1, 5]:
627
+ // allow write: if boundedNumber('rating', 1, 5);
628
+
629
+ // The field changed by EXACTLY n relative to the existing document.
630
+ // n may be negative (decrement). Update rules only (needs resource).
631
+ export function incrementedBy(field, n) {
632
+ return request.resource.data[field] == resource.data[field] + n;
633
+ }
634
+
635
+ // The field's delta is within [min, max] (inclusive) — and it is NOT
636
+ // required to change (delta 0 passes when min <= 0 <= max).
637
+ export function changedBy(field, min, max) {
638
+ return request.resource.data[field] - resource.data[field] >= min
639
+ && request.resource.data[field] - resource.data[field] <= max;
640
+ }
641
+
642
+ // The incoming value is a number within [min, max] (inclusive).
643
+ // Works on create and update. Missing field reads null (dynamic
644
+ // access) and fails the type check rather than erroring.
645
+ export function boundedNumber(field, min, max) {
646
+ return (request.resource.data[field] is int || request.resource.data[field] is float)
647
+ && request.resource.data[field] >= min
648
+ && request.resource.data[field] <= max;
649
+ }
650
+ `,geometry:`// @pyric-services cloud.firestore
651
+ // Geometry module for movement game validation via config document lookup.
652
+ //
653
+ // Caller must pass the config document data as an explicit parameter.
654
+ // The config doc is read via get() and cached per request — define a
655
+ // config() function in your rules and pass its result to these functions.
656
+ //
657
+ // Config doc schema:
658
+ // moves[pieceType][fromCell][toCell] = true
659
+ // jumps[pieceType][fromCell][toCell] = capturedCellName
660
+ //
661
+ // Usage:
662
+ // import { validSimpleMove, validJumpMove } from 'geometry';
663
+ //
664
+ // function config() {
665
+ // return get(/databases/$(database)/documents/gameConfig/checkers).data;
666
+ // }
667
+ //
668
+ // allow update: if validSimpleMove(config())
669
+ // && piecePlaced() && moveIntegrity();
670
+ //
671
+ // allow update: if validJumpMove(config())
672
+ // && captureValid() && captureDecrement() && moveIntegrity();
673
+
674
+ // Validate a simple (non-capture) move via config document lookup.
675
+ // Uses 3-level dynamic nesting: cfg.moves[piece][from][to].
676
+ // piece comes from resource.data (pre-write board) so client can't fake it.
677
+ export function validSimpleMove(cfg) {
678
+ let mf = request.resource.data.moveFrom;
679
+ let mt = request.resource.data.moveTo;
680
+ let piece = resource.data[mf];
681
+ return cfg.moves[piece][mf][mt] == true;
682
+ }
683
+
684
+ // Validate a jump (capture) move via config document lookup.
685
+ // cfg.jumps[piece][from][to] returns the expected captured cell name.
686
+ // Caller must separately verify the captured piece is an opponent piece.
687
+ export function validJumpMove(cfg) {
688
+ let mf = request.resource.data.moveFrom;
689
+ let mt = request.resource.data.moveTo;
690
+ let cap = request.resource.data.captured;
691
+ let piece = resource.data[mf];
692
+ return cfg.jumps[piece][mf][mt] == cap;
693
+ }
694
+ `,joining:`// @pyric-services cloud.firestore
695
+ // Joining module — how membership CHANGES, safely. The connective
696
+ // tissue between content/spaces: spaces gates children behind a
697
+ // members field; joining lets users enter and leave that field
698
+ // WITHOUT an admin backend, with no privilege escalation.
699
+ //
700
+ // Convention: a MAP-shaped members field (uid -> role) on the parent
701
+ // doc. Compose with lifecycle's onlyFieldsChanged so a join/leave
702
+ // write can't touch anything else:
703
+ //
704
+ // import { onlyAddedSelf, onlyRemovedSelf } from 'joining';
705
+ // import { onlyFieldsChanged } from 'lifecycle';
706
+ // import { isSpaceMember, hasSpaceRole } from 'spaces';
707
+ //
708
+ // match /teams/{teamId} {
709
+ // allow read: if isSpaceMember(resource.data);
710
+ //
711
+ // // Open self-service join (public team) at a fixed role, and
712
+ // // self-service leave — nothing else about the doc may change:
713
+ // allow update: if onlyFieldsChanged(['members'])
714
+ // && (onlyAddedSelf('members', 'editor') || onlyRemovedSelf('members'));
715
+ // // Admins manage the doc freely:
716
+ // allow update: if hasSpaceRole(resource.data, 'admin');
717
+ // }
718
+ //
719
+ // Every guarantee here is production-verified against the live Rules Test API:
720
+ // the field-level map diff is reliable; the empty no-op diff DENIES (set
721
+ // equality, not hasOnly — hasOnly on an empty set passes); role escalation via
722
+ // CHANGING an existing entry denies; adding or removing anyone else denies.
723
+
724
+ // The write adds EXACTLY the caller to the members map, at EXACTLY
725
+ // \`role\`, changing and removing nobody. Update rules only.
726
+ export function onlyAddedSelf(membersField, role) {
727
+ let diff = request.resource.data[membersField].diff(resource.data[membersField]);
728
+ return request.auth != null
729
+ && diff.addedKeys() == [request.auth.uid].toSet()
730
+ && diff.changedKeys().size() == 0
731
+ && diff.removedKeys().size() == 0
732
+ && request.resource.data[membersField][request.auth.uid] == role;
733
+ }
734
+
735
+ // The write removes EXACTLY the caller from the members map, adding
736
+ // and changing nobody. Self-service leave. Update rules only.
737
+ export function onlyRemovedSelf(membersField) {
738
+ let diff = request.resource.data[membersField].diff(resource.data[membersField]);
739
+ return request.auth != null
740
+ && diff.removedKeys() == [request.auth.uid].toSet()
741
+ && diff.addedKeys().size() == 0
742
+ && diff.changedKeys().size() == 0;
743
+ }
744
+ `,lifecycle:`// @pyric-services cloud.firestore
745
+ // Lifecycle module for field immutability and timestamp enforcement.
746
+ //
747
+ // Common pattern: certain fields must never change after document creation
748
+ // (createdBy, createdAt, authorId).
749
+ //
750
+ // Usage:
751
+ // import { fieldUnchanged, immutableFields, isServerTimestamp } from 'lifecycle';
752
+ //
753
+ // // Single field:
754
+ // allow update: if fieldUnchanged('createdBy');
755
+ //
756
+ // // Multiple fields (replaces chained fieldUnchanged calls):
757
+ // allow update: if immutableFields(['createdBy', 'createdAt', 'authorId']);
758
+ //
759
+ // // The dual: users may edit title/body but NOTHING else:
760
+ // allow update: if onlyFieldsChanged(['title', 'body']);
761
+ //
762
+ // allow create: if isServerTimestamp('createdAt');
763
+
764
+ // Ensure a field's value is identical between existing and incoming document.
765
+ // Use on update rules to enforce immutability.
766
+ export function fieldUnchanged(field) {
767
+ return resource.data[field] == request.resource.data[field];
768
+ }
769
+
770
+ // Ensure multiple fields are unchanged between existing and incoming document.
771
+ // Uses MapDiff — one expression instead of N chained fieldUnchanged() calls.
772
+ export function immutableFields(fields) {
773
+ return request.resource.data.diff(resource.data).unchangedKeys().hasAll(fields);
774
+ }
775
+
776
+ // Ensure a field is set to the server timestamp.
777
+ // Use on create or update rules to enforce server-side time.
778
+ export function isServerTimestamp(field) {
779
+ return request.resource.data[field] == request.time;
780
+ }
781
+
782
+ // The dual of immutableFields: every changed field is in the allowed
783
+ // list (fields NOT listed are implicitly immutable). Top-level keys
784
+ // only — nested-map diffs are unreliable in production; flatten the
785
+ // schema instead of reaching for a nested diff.
786
+ export function onlyFieldsChanged(fields) {
787
+ return request.resource.data.diff(resource.data).affectedKeys().hasOnly(fields);
788
+ }
789
+
790
+ // Exactly n top-level fields changed in this write. n == 1 is the
791
+ // board-integrity / edit-one-field-per-write guard (Pattern 5,
792
+ // generalized beyond games).
793
+ export function nFieldsChanged(n) {
794
+ return request.resource.data.diff(resource.data).affectedKeys().size() == n;
795
+ }
796
+ `,lobby:`// @pyric-services cloud.firestore
797
+ // Lobby module for 2-participant coordination.
798
+ //
799
+ // Convention: documents must have these fields:
800
+ // host: string (creator's UID)
801
+ // guest: string ('' when waiting, joiner's UID when joined)
802
+ // status: 'waiting' | 'playing' | 'ready' (or any active state)
803
+ //
804
+ // Usage:
805
+ // import { validCreate, validJoin, canCancel } from 'lobby';
806
+ //
807
+ // allow create: if validCreate();
808
+ // allow update: if validJoin();
809
+ // allow delete: if canCancel();
810
+
811
+ // Is this a waiting lobby with an open seat?
812
+ function isWaiting() {
813
+ return resource.data.status == 'waiting'
814
+ && resource.data.guest == '';
815
+ }
816
+
817
+ // Create: caller is host, seat empty, status waiting
818
+ export function validCreate() {
819
+ return request.auth != null
820
+ && request.resource.data.host == request.auth.uid
821
+ && request.resource.data.guest == ''
822
+ && request.resource.data.status == 'waiting';
823
+ }
824
+
825
+ // Join: fill empty seat, transition to next status, no self-join
826
+ export function validJoin() {
827
+ return request.auth != null
828
+ && isWaiting()
829
+ && request.resource.data.guest == request.auth.uid
830
+ && request.auth.uid != resource.data.host
831
+ && request.resource.data.status == 'playing'
832
+ && request.resource.data.host == resource.data.host;
833
+ }
834
+
835
+ // Cancel: only host, only while waiting
836
+ export function canCancel() {
837
+ return request.auth != null
838
+ && resource.data.status == 'waiting'
839
+ && request.auth.uid == resource.data.host;
840
+ }
841
+ `,membership:`// @pyric-services cloud.firestore,firebase.storage
842
+ // @pyric-evidence storage-rules#125,firestore-rules#189
843
+ // Membership module for role-based and claims-based access control.
844
+ //
845
+ // Two access patterns:
846
+ // 1. Custom claims on auth token (0 get() calls, set server-side)
847
+ // 2. Member maps on documents (0 get() calls on the doc itself)
848
+ //
849
+ // Usage:
850
+ // import { hasClaim, hasClaimRole, isMemberOf, hasRole } from 'membership';
851
+ //
852
+ // // Workspace access via custom claims
853
+ // allow read: if hasClaim('workspace_id');
854
+ // allow write: if hasClaimRole('workspace_role', 'admin');
855
+ //
856
+ // // Project access via member map on document
857
+ // allow read: if isMemberOf(resource.data.members);
858
+ // allow update: if hasRole(resource.data.members, 'admin');
859
+
860
+ // Check if the auth token has a non-null value for a claim key.
861
+ export function hasClaim(claim) {
862
+ return request.auth != null
863
+ && request.auth.token[claim] != null;
864
+ }
865
+
866
+ // Check if the auth token has a specific value for a claim key.
867
+ export function hasClaimRole(claim, role) {
868
+ return request.auth != null
869
+ && request.auth.token[claim] == role;
870
+ }
871
+
872
+ // Check if the caller's UID exists as a key in a members map.
873
+ export function isMemberOf(membersMap) {
874
+ return request.auth != null
875
+ && request.auth.uid in membersMap;
876
+ }
877
+
878
+ // Check if the caller has a specific role in a members map.
879
+ export function hasRole(membersMap, role) {
880
+ return request.auth != null
881
+ && membersMap[request.auth.uid] == role;
882
+ }
883
+ `,spaces:`// @pyric-services cloud.firestore
884
+ // Spaces module — cross-document membership gating for shared spaces
885
+ // (teams, rooms, groups, projects, parties). The second-most-common
886
+ // app shape after author-owned content: a PARENT document defines who
887
+ // may touch its children.
888
+ //
889
+ // Explicit-param design (like geometry): the caller reads the parent
890
+ // doc ONCE via a helper and passes its data in. Define the helper in
891
+ // your rules — get() is cached per request, so every function below
892
+ // can share one read (of the 10-get budget):
893
+ //
894
+ // import { isSpaceMember, hasSpaceRole, validMemberCreate } from 'spaces';
895
+ //
896
+ // match /spaces/{spaceId}/tasks/{taskId} {
897
+ // function space() {
898
+ // return get(/databases/$(database)/documents/spaces/$(spaceId)).data;
899
+ // }
900
+ // allow read: if isSpaceMember(space());
901
+ // allow create: if validMemberCreate(space(), 'author');
902
+ // allow delete: if hasSpaceRole(space(), 'admin');
903
+ // }
904
+ //
905
+ // Members field shapes verified against the production engine:
906
+ // list: members: ['uidA', 'uidB'] → isSpaceMember only
907
+ // map: members: { uidA: 'admin', ... } → isSpaceMember + hasSpaceRole
908
+ // A missing members field, a non-member uid, or a missing parent doc
909
+ // (get() of a missing doc errors) all fail CLOSED.
910
+
911
+ // The caller is in the space's members field. \`in\` covers both
912
+ // shapes: list membership and map keys.
913
+ export function isSpaceMember(spaceData) {
914
+ return request.auth != null && request.auth.uid in spaceData.members;
915
+ }
916
+
917
+ // The caller's role in a MAP-shaped members field equals \`role\`.
918
+ // List-shaped members carry no roles — this denies on them.
919
+ export function hasSpaceRole(spaceData, role) {
920
+ return request.auth != null && spaceData.members[request.auth.uid] == role;
921
+ }
922
+
923
+ // Member-gated authored create: the caller is a member AND the
924
+ // incoming child doc's author field is the caller. The "post a
925
+ // message / add a task" guard.
926
+ export function validMemberCreate(spaceData, authorField) {
927
+ return isSpaceMember(spaceData)
928
+ && request.resource.data[authorField] == request.auth.uid;
929
+ }
930
+ `,state:`// @pyric-services cloud.firestore
931
+ // Game state machine helpers.
932
+ //
933
+ // Convention: documents must have these fields:
934
+ // status: 'waiting' | 'playing' | 'won' | 'draw'
935
+ // moveCount: number
936
+ // host: string (UID)
937
+ // guest: string (UID)
938
+ //
939
+ // Usage:
940
+ // import { isPlaying, moveIncremented, participantsUnchanged } from 'state';
941
+ //
942
+ // allow update: if isPlaying() && moveIncremented() && participantsUnchanged();
943
+
944
+ // Is the game actively in play?
945
+ export function isPlaying() {
946
+ return resource.data.status == 'playing';
947
+ }
948
+
949
+ // Did moveCount increment by exactly 1?
950
+ export function moveIncremented() {
951
+ return request.resource.data.moveCount == resource.data.moveCount + 1;
952
+ }
953
+
954
+ // Are host and guest unchanged? (prevents mid-game identity swap)
955
+ export function participantsUnchanged() {
956
+ return request.resource.data.host == resource.data.host
957
+ && request.resource.data.guest == resource.data.guest;
958
+ }
959
+ `,"storage/metadata":`// @pyric-services firebase.storage
960
+ // @pyric-evidence storage-rules#132
961
+ // Storage custom-metadata policies. Custom metadata is a flat string map.
962
+
963
+ export function hasRequiredMetadata(keys) {
964
+ return request.resource.metadata.keys().hasAll(keys);
965
+ }
966
+
967
+ export function metadataString(key, min, max) {
968
+ return request.resource.metadata[key] is string
969
+ && request.resource.metadata[key].size() >= min
970
+ && request.resource.metadata[key].size() <= max;
971
+ }
972
+
973
+ export function incomingMetadataOwner(key) {
974
+ return request.auth != null
975
+ && request.resource.metadata[key] == request.auth.uid;
976
+ }
977
+
978
+ export function existingMetadataOwner(key) {
979
+ return request.auth != null
980
+ && resource.metadata[key] == request.auth.uid;
981
+ }
982
+ `,"storage/objects":`// @pyric-services firebase.storage
983
+ // @pyric-evidence storage-rules#132
984
+ // Storage operation identity. Use request.method rather than null checks:
985
+ // production treats missing resource/request.resource bindings as errors.
986
+
987
+ export function isCreate() {
988
+ return request.method == 'create';
989
+ }
990
+
991
+ export function isUpdate() {
992
+ return request.method == 'update';
993
+ }
994
+
995
+ export function isDelete() {
996
+ return request.method == 'delete';
997
+ }
998
+ `,"storage/time":`// @pyric-services firebase.storage
999
+ // @pyric-evidence storage-rules#132
1000
+ // Freshness checks over server-owned Storage object timestamps. Boundaries are
1001
+ // strict: equality with the deadline is not "within" the window.
1002
+
1003
+ export function createdWithin(seconds) {
1004
+ return request.time < resource.timeCreated + duration.value(seconds, 's');
1005
+ }
1006
+
1007
+ export function updatedWithin(seconds) {
1008
+ return request.time < resource.updated + duration.value(seconds, 's');
1009
+ }
1010
+ `,"storage/uploads":`// @pyric-services firebase.storage
1011
+ // @pyric-evidence storage-rules#132
1012
+ // Storage upload request primitives. These inspect declared object metadata;
1013
+ // MIME helpers do not inspect or authenticate the uploaded bytes.
1014
+
1015
+ export function sizeAtMost(maxBytes) {
1016
+ return request.resource.size <= maxBytes;
1017
+ }
1018
+
1019
+ export function sizeBetween(minBytes, maxBytes) {
1020
+ return request.resource.size >= minBytes
1021
+ && request.resource.size <= maxBytes;
1022
+ }
1023
+
1024
+ export function contentTypeMatches(pattern) {
1025
+ return request.resource.contentType.matches(pattern);
1026
+ }
1027
+
1028
+ export function contentTypeIsOneOf(types) {
1029
+ return request.resource.contentType in types;
1030
+ }
1031
+ `,timing:`// @pyric-services cloud.firestore
1032
+ // Timing module for cooldown / rate-limit enforcement.
1033
+ //
1034
+ // Rules CAN rate-limit (contrary to a common assumption — jrpg
1035
+ // FINDINGS F-004): compare request.time against a stored server
1036
+ // timestamp. Pair with lifecycle's isServerTimestamp on the SAME
1037
+ // write so the stored timestamp cannot be forged by the client:
1038
+ //
1039
+ // import { cooldownElapsed } from 'timing';
1040
+ // import { isServerTimestamp } from 'lifecycle';
1041
+ //
1042
+ // // At most one move every 2 seconds:
1043
+ // allow update: if cooldownElapsed('lastMoveAt', 2)
1044
+ // && isServerTimestamp('lastMoveAt');
1045
+
1046
+ // The stored timestamp is more than \`seconds\` old (strict). Update
1047
+ // rules only — needs \`resource\`. The field must be a Timestamp; a
1048
+ // missing field errors, which denies (fail-closed).
1049
+ export function cooldownElapsed(field, seconds) {
1050
+ return request.time > resource.data[field] + duration.value(seconds, 's');
1051
+ }
1052
+ `,transitions:`// @pyric-services cloud.firestore
1053
+ // Transitions module for state machine enforcement.
1054
+ //
1055
+ // Validates that a field transitions from one known value to another.
1056
+ // Use to enforce valid status flows (e.g., open -> in_progress -> completed).
1057
+ //
1058
+ // Usage:
1059
+ // import { validTransition, statusIs, newStatusIs } from 'transitions';
1060
+ //
1061
+ // // Only allow open -> in_progress
1062
+ // allow update: if validTransition('status', 'open', 'in_progress');
1063
+ //
1064
+ // // Allow update only when currently active
1065
+ // allow update: if statusIs('status', 'active');
1066
+ //
1067
+ // // Compound: multiple valid transitions via OR
1068
+ // allow update: if validTransition('status', 'open', 'in_progress')
1069
+ // || validTransition('status', 'in_progress', 'completed')
1070
+ // || validTransition('status', 'completed', 'archived');
1071
+
1072
+ // Check that a field transitions from one value to another.
1073
+ export function validTransition(field, from, to) {
1074
+ return resource.data[field] == from
1075
+ && request.resource.data[field] == to;
1076
+ }
1077
+
1078
+ // Check the current (existing) value of a field.
1079
+ export function statusIs(field, value) {
1080
+ return resource.data[field] == value;
1081
+ }
1082
+
1083
+ // Check the incoming (new) value of a field.
1084
+ export function newStatusIs(field, value) {
1085
+ return request.resource.data[field] == value;
1086
+ }
1087
+ `,turns:`// @pyric-services cloud.firestore
1088
+ // Turn enforcement for 2-participant games/sessions.
1089
+ //
1090
+ // Convention: documents must have these fields:
1091
+ // host: string (UID)
1092
+ // guest: string (UID)
1093
+ // currentTurn: 'host' | 'guest'
1094
+ //
1095
+ // Usage:
1096
+ // import { isMyTurn, turnFlipped } from 'turns';
1097
+ //
1098
+ // allow update: if isMyTurn() && turnFlipped();
1099
+
1100
+ // Is the caller the participant whose turn it is?
1101
+ export function isMyTurn() {
1102
+ return (resource.data.currentTurn == 'host'
1103
+ && request.auth.uid == resource.data.host)
1104
+ || (resource.data.currentTurn == 'guest'
1105
+ && request.auth.uid == resource.data.guest);
1106
+ }
1107
+
1108
+ // Did the turn alternate?
1109
+ export function turnFlipped() {
1110
+ return (resource.data.currentTurn == 'host'
1111
+ && request.resource.data.currentTurn == 'guest')
1112
+ || (resource.data.currentTurn == 'guest'
1113
+ && request.resource.data.currentTurn == 'host');
1114
+ }
1115
+ `,validation:`// @pyric-services cloud.firestore
1116
+ // Validation module for document field shape and value checks.
1117
+ //
1118
+ // Usage:
1119
+ // import { hasRequired, hasOnly, validString, isOneOf } from 'validation';
1120
+ //
1121
+ // allow create: if hasRequired(['title', 'status'])
1122
+ // && validString('title', 1, 100)
1123
+ // && isOneOf('status', ['draft', 'published']);
1124
+
1125
+ export function hasRequired(fields) {
1126
+ return request.resource.data.keys().hasAll(fields);
1127
+ }
1128
+
1129
+ export function hasOnly(fields) {
1130
+ return request.resource.data.keys().hasOnly(fields);
1131
+ }
1132
+
1133
+ // Incoming field is a string with size in [min, max] (inclusive).
1134
+ // Uses dynamic access, so a MISSING field reads as null (not an
1135
+ // error) and fails the \`is string\` check — safe on optional fields.
1136
+ export function validString(field, min, max) {
1137
+ return request.resource.data[field] is string
1138
+ && request.resource.data[field].size() >= min
1139
+ && request.resource.data[field].size() <= max;
1140
+ }
1141
+
1142
+ // Enum check: the incoming field value is one of the allowed values.
1143
+ // (\`in\` on a list — NOT \`.includes()\`, which does not exist in rules.)
1144
+ export function isOneOf(field, values) {
1145
+ return request.resource.data[field] in values;
1146
+ }
1147
+ `};function zd(){const t={};for(const[e,r]of Object.entries(Bd))t[e]=r,t[`./stdlib/${e}.rules`]=r;return t}const ro=zd(),Vd=new Set(Object.keys(ro));function qp(t,e){const r=Object.entries(e?.modules??{}),n=Object.fromEntries(r),s=new Set(r.map(([a])=>a)),i=new Set([...Vd].filter(a=>!s.has(a)));return ol(null,t,{...e,modules:{...ro,...n}},i)}const Hd={key:"builtins",kind:"language-namespace",description:"Top-level functions always in scope inside rules — get, exists, getAfter, debug. Called bare, no namespace prefix.",purpose:"The four built-in functions Firestore Rules ships with at the top level. They are NOT inside a namespace — call `get(path)`, not `firestore.get(path)`. Used to read other documents (cross-document gates), check existence, peek at post-write state, and print debug values.",whenToUse:"Reach for `builtins` any time a rule needs information that isn't already on `request` or `resource`. Most common: `get(path)` to read another document's fields inside a predicate.",entries:[{signature:"get(path: path): Resource",description:"Read another document. Returns a Resource whose `.data` is the doc map. Counts against the rule's `get()` budget (cap 10 per evaluation).",examples:["allow update: if get(/databases/$(database)/documents/users/$(request.auth.uid)).data.role == 'admin';"],notes:"Path must start with `/databases/$(database)/documents/`. Hardcoding a different database id silently fails."},{signature:"exists(path: path): bool",description:"True if a document at `path` exists. Counts against the get() budget like `get`.",examples:["allow create: if exists(/databases/$(database)/documents/teams/$(request.resource.data.teamId));"]},{signature:"getAfter(path: path): Resource",description:"Like `get`, but reads the doc AS IT WILL BE after the current transaction commits. Use for cross-document consistency gates that depend on the post-write state of another doc in the same batch.",notes:"Only meaningful inside transactions / batched writes. Outside a batch, equivalent to `get`."},{signature:"debug(value: any): bool",description:"Print `value` to the Firestore emulator/test runner log and return true. No-op in production. Useful for narrowing why a rule denies during local development.",notes:"Always returns true — wrapping it in a predicate (`if debug(resource.data.x) && otherCondition`) shows the value without changing rule outcome."}],relatedKeys:["request","resource","path"]},Wd={key:"math",kind:"language-namespace",description:"Numeric helpers — abs, ceil, floor, round, sqrt, pow, isInfinite, isNaN. Use when rules need to coerce or bound numbers.",purpose:"The `math` namespace exposes a small set of numeric utilities for use inside rule predicates. Functions are called as `math.<fn>(...)`. Always in scope; no import needed.",whenToUse:"Reach for `math` whenever a rule needs to round, bound, or guard against non-finite numbers in a user-supplied field.",entries:[{signature:"math.abs(n: number): number",description:"Absolute value of `n`."},{signature:"math.ceil(n: number): int",description:"Smallest integer >= `n`."},{signature:"math.floor(n: number): int",description:"Largest integer <= `n`."},{signature:"math.round(n: number): int",description:"Nearest integer to `n`."},{signature:"math.sqrt(n: number): number",description:"Square root of `n`. Negative input returns NaN."},{signature:"math.pow(base: number, exp: number): number",description:"`base` raised to `exp`."},{signature:"math.isInfinite(n: number): bool",description:"True if `n` is +Infinity or -Infinity.",notes:"Pairs with `math.isNaN` for safe numeric guards before arithmetic."},{signature:"math.isNaN(n: number): bool",description:"True if `n` is NaN."}],examples:["allow update: if math.ceil(request.resource.data.score) <= 100;","allow create: if !math.isNaN(request.resource.data.lat) && !math.isInfinite(request.resource.data.lat);"],relatedKeys:["hashing"]},Gd={key:"timestamp",kind:"language-namespace",description:"Timestamp constructors — date(year, month, day), value(epochMillis). Use to build timestamps in rule comparisons.",purpose:"The `timestamp` namespace contains constructors that produce Timestamp values for use in comparisons. The Timestamp TYPE has its own methods (year, month, etc.) — those live under the `string`/`list`/`map`-style key `timestamp-methods` in this stdlib, accessed via dot notation on a timestamp value.",whenToUse:"Reach for the `timestamp` namespace when a rule needs to construct a specific Timestamp value to compare against `request.time` or a document field.",entries:[{signature:"timestamp.date(year: int, month: int, day: int): Timestamp",description:"Construct a Timestamp at UTC midnight of the given date.",examples:["allow read: if request.time > timestamp.date(2024, 1, 1);"]},{signature:"timestamp.value(epochMillis: int): Timestamp",description:"Construct a Timestamp from epoch milliseconds."}],relatedKeys:["duration","request","lifecycle"]},Kd={key:"duration",kind:"language-namespace",description:'Duration constructors — value(magnitude, unit), time(h, m, s, ns), abs(d). Use for "within N seconds" windows.',purpose:"The `duration` namespace builds Duration values that can be added to or subtracted from Timestamps. Useful for time-window predicates in security rules.",whenToUse:'Reach for `duration` whenever a rule expresses a time window — "within 5 minutes of write", "older than 30 days", etc.',entries:[{signature:"duration.value(magnitude: int, unit: 'w' | 'd' | 'h' | 'm' | 's' | 'ms' | 'ns'): Duration",description:"Construct a Duration of `magnitude` of the given unit.",examples:["allow update: if request.time < resource.data.createdAt + duration.value(5, 'm');"]},{signature:"duration.time(h: int, m: int, s: int, ns: int): Duration",description:"Construct a Duration as a sum of hours, minutes, seconds, nanoseconds."},{signature:"duration.abs(d: Duration): Duration",description:"Absolute value of a Duration (drops sign)."}],relatedKeys:["timestamp"]},Zd={key:"latlng",kind:"language-namespace",description:"GeoPoint constructor — value(lat, lng). Builds LatLng values for proximity rules.",purpose:"The `latlng` namespace constructs LatLng values. The LatLng type itself has methods (`latitude()`, `longitude()`, `distance(other)`) accessed via dot notation on a latlng value.",whenToUse:'Reach for `latlng` when a rule gates on physical proximity — e.g. "this write must come within N meters of the document\'s anchor point".',entries:[{signature:"latlng.value(lat: number, lng: number): LatLng",description:"Construct a LatLng. Latitude in [-90, 90], longitude in [-180, 180].",examples:["allow update: if latlng.value(request.resource.data.lat, request.resource.data.lng).distance(resource.data.anchor) < 1000;"]}]},Jd={key:"hashing",kind:"language-namespace",description:"Hash digests — md5, sha256, crc32, crc32c. Each takes Bytes or String and returns Bytes.",purpose:"The `hashing` namespace exposes one-shot digest functions. Output is Bytes; compare equality with `==` against a stored Bytes value.",whenToUse:"Reach for `hashing` for tamper-evidence checks — comparing a submitted hash against a stored digest, or verifying a public-facing checksum.",entries:[{signature:"hashing.md5(input: Bytes | String): Bytes",description:"MD5 digest. 128-bit; do not use for security-sensitive integrity proofs."},{signature:"hashing.sha256(input: Bytes | String): Bytes",description:"SHA-256 digest. 256-bit; the right choice for integrity proofs."},{signature:"hashing.crc32(input: Bytes | String): Bytes",description:"CRC32 checksum (Bytes). Use for non-cryptographic integrity."},{signature:"hashing.crc32c(input: Bytes | String): Bytes",description:"CRC32C checksum (Bytes). Same role as crc32 with a different polynomial."}],examples:["allow update: if hashing.sha256(request.resource.data.payload) == resource.data.checksum;"],relatedKeys:["bytes"]},Yd={key:"string",kind:"type-methods",description:"Methods on string values — matches, lower, upper, trim, size, split, replace, toUtf8. Called as `value.method(...)`.",purpose:"Methods available on values of type `string` inside rule expressions. Dispatched on the value: `myField.matches(...)`, not `string.matches(myField, ...)`. The engine routes the call based on the value's runtime type.",whenToUse:"Reach for these whenever a rule examines a string field — pattern checks, case-insensitive comparisons, trimming user input, encoding to bytes.",entries:[{signature:"string.matches(pattern: string): bool",description:"True if the string matches the given RE2 regex (full match).",examples:["allow create: if request.resource.data.email.matches('.*@example[.]com');"],notes:"Pattern is RE2 syntax, NOT JavaScript regex. No anchors needed — the match is full-string by default."},{signature:"string.lower(): string",description:"Return the string lowercased."},{signature:"string.upper(): string",description:"Return the string uppercased."},{signature:"string.trim(): string",description:"Strip leading + trailing whitespace."},{signature:"string.size(): int",description:"Length in characters (NOT bytes — use `toUtf8().size()` for byte length)."},{signature:"string.split(separator: string): list<string>",description:"Split the string into a list on `separator`."},{signature:"string.replace(old: string, new: string): string",description:"Replace all occurrences of `old` with `new`."},{signature:"string.toUtf8(): bytes",description:"Encode the string as UTF-8 bytes.",notes:"Use before hashing if the input is a string."}],examples:["allow create: if request.resource.data.slug.size() > 0 && request.resource.data.slug.size() <= 64;","allow update: if request.resource.data.kind.lower() == 'public';"],relatedKeys:["bytes","hashing","validation"]},Qd={key:"list",kind:"type-methods",description:"Methods on list values — hasAll, hasAny, hasOnly, size, toSet, concat, removeAll, join. Called as `value.method(...)`.",purpose:"Methods on list values — used to check membership, compare contents, transform to sets, and concatenate. Lists in rules are ordered + finite; methods often have parallel semantics on the `set` view produced by `toSet()`.",whenToUse:'Reach for these whenever a rule examines an array field — tag membership ("user can update if their uid is in editors"), array-shape validation, or projecting to a set for difference checks.',entries:[{signature:"list.hasAll(other: list): bool",description:"True if every element of `other` is present in this list.",examples:["allow update: if request.resource.data.tags.hasAll(['public', 'reviewed']);"]},{signature:"list.hasAny(other: list): bool",description:"True if at least one element of `other` is present in this list."},{signature:"list.hasOnly(other: list): bool",description:"True if every element of THIS list is in `other` (i.e. this is a subset).",notes:'Often the right call for "no fields outside this allowlist" patterns when used with `request.resource.data.keys()`.'},{signature:"list.size(): int",description:"Number of elements."},{signature:"list.toSet(): set",description:"Convert to a Set view (de-duplicated, unordered). Useful for `difference`/`union`/`intersection` operations."},{signature:"list.concat(other: list): list",description:"Return a new list with `other` appended."},{signature:"list.removeAll(other: list): list",description:"Return a new list with every element of `other` removed."},{signature:"list.join(separator: string): string",description:"Join elements into a single string with `separator` between them."}],relatedKeys:["map","string"]},Xd={key:"map",kind:"type-methods",description:"Methods on map values — keys, values, size, get, diff. Called as `value.method(...)`.",purpose:"Methods on map values. The most common in rule code: `keys()` returns a list of map keys (combined with `list.hasAll`/`list.hasOnly` for shape checks), and `diff(other)` returns a MapDiff used to assert which fields changed across an update.",whenToUse:"Reach for these for shape validation (which keys exist), for default-aware reads (`get(key, default)`), and for diff-based immutability gates on updates.",entries:[{signature:"map.keys(): list<string>",description:"List of top-level keys in the map.",examples:["allow create: if request.resource.data.keys().hasOnly(['title','body','authorId']);"]},{signature:"map.values(): list",description:"List of top-level values in the map."},{signature:"map.size(): int",description:"Number of top-level keys."},{signature:"map.get(key: string, fallback: any): any",description:"Return `map[key]` if present, otherwise `fallback`. Same shape as `get(map, key, fallback)`."},{signature:"map.diff(other: map): MapDiff",description:"Return a MapDiff with `.addedKeys()`, `.removedKeys()`, `.changedKeys()`, `.affectedKeys()`, `.unchangedKeys()` methods, each returning a Set of keys.",examples:["allow update: if request.resource.data.diff(resource.data).affectedKeys().hasOnly(['updatedAt']);"],notes:"The MapDiff result is the right surface for immutability gates — easier to read than chaining individual field-unchanged checks."}],relatedKeys:["list","lifecycle","validation"]},eh={key:"bytes",kind:"type-methods",description:"Methods on bytes values — size, toBase64, toHexString. Called as `value.method(...)`.",purpose:"Methods on Bytes values — the output of hashing operations and the storage shape for arbitrary binary payloads. Bytes also support comparison operators (<, <=, >, >=) for lexicographic ordering.",whenToUse:"Reach for these when a rule examines a Bytes field — typically a stored digest from `hashing.sha256(...)` — or when comparing two hashes for tamper-evidence.",entries:[{signature:"bytes.size(): int",description:"Number of bytes."},{signature:"bytes.toBase64(): string",description:"Standard base64 encoding of the bytes."},{signature:"bytes.toHexString(): string",description:"Lowercase hexadecimal encoding of the bytes."}],relatedKeys:["hashing","string"]},th={key:"path",kind:"type-methods",description:"Methods on path values — bind. Used to fill in template variables in document paths.",purpose:"Path values are the type used for cross-document references inside rules (e.g. the path passed to `get()` or `exists()`). The `bind` method substitutes template variables into a path literal.",whenToUse:"Reach for `path.bind` when a `get()` or `exists()` call needs a dynamic path with one or more template variables filled in from rule context.",entries:[{signature:"path.bind(bindings: map<string, string>): path",description:"Return a new path with template variables (`{name}`) replaced by values from `bindings`.",examples:["allow update: if exists(/databases/$(database)/documents/users/$(request.auth.uid)/profile/main);"],notes:"In practice most rule code constructs paths inline with `$()` interpolation instead of `path.bind`. `bind` is here for completeness."}],relatedKeys:["request","resource"]},rh={key:"request",kind:"globals",description:"Root namespace for the in-flight request — auth, resource.data, time, path, method, query. Always available, no import.",purpose:"The `request` identifier carries everything the engine knows about the current request — who is making it (`auth`), what they are sending (`resource.data`), when (`time`), and where (`path`, `method`). These are *paths*, not callables — read fields off them in rule predicates.",whenToUse:"Every non-trivial rule reads from `request` to authorize the operation. The two most common touchpoints: `request.auth` (who) and `request.resource.data` (what).",entries:[{signature:"request.auth: map | null",description:"The authenticated user. `null` for unauthenticated requests.",examples:["allow read: if request.auth != null;"]},{signature:"request.auth.uid: string",description:"The signed-in user's UID. Only safe to read after a null-check on `request.auth`.",examples:["allow update: if request.auth.uid == resource.data.ownerId;"]},{signature:"request.auth.token: map",description:"Map of custom claims set on the user's ID token (e.g. `request.auth.token.admin`).",examples:["allow delete: if request.auth.token.admin == true;"],notes:"Custom claims live under `request.auth.token.*`, NOT `request.auth.*`. Agents often emit `request.auth.admin` — that always reads `null`."},{signature:"request.resource.data: map",description:"The document data being written (create/update/set). Read it to validate what the client is sending.",examples:["allow create: if request.resource.data.keys().hasOnly(['title','body','authorId']);"]},{signature:"request.time: timestamp",description:"Server time of the request. Compare against document timestamps for windowed gates."},{signature:"request.path: path",description:"Path of the document being operated on (e.g. `/databases/(default)/documents/users/alice`)."},{signature:"request.method: 'get' | 'list' | 'create' | 'update' | 'delete'",description:"Which operation triggered the rule. Usually inferred from the `allow` clause, but available for fine-grained checks."},{signature:"request.query: map",description:"Query metadata for `list` requests — `limit`, `offset`, `orderBy`. Available on `allow list` rules only."}],relatedKeys:["resource","auth"]},nh={key:"resource",kind:"globals",description:"Root namespace for the existing document — use resource.data to compare against what is already there.",purpose:"The `resource` identifier is the document state BEFORE the request — what is currently stored. When the target does not exist, evaluating `resource` raises a null-value error; it is not a comparable null. On an update/delete of an existing document, it contains the pre-write data. Use it to compare incoming changes against existing values.",whenToUse:'Whenever a rule needs the pre-write state — e.g. "the existing owner is the one updating", "the field already had this value before the write".',entries:[{signature:"resource.data: map",description:"The currently stored document data. When the target does not exist, evaluating `resource` raises a null-value error.",examples:["allow update: if resource.data.ownerId == request.auth.uid;"]}],relatedKeys:["request"]},sh={key:"auth",kind:"user-module",description:"User-authored module: authentication primitives (isAuthenticated, isOwner). Self-contained. Import via `import { isAuthenticated, isOwner } from 'auth';` (the resolver also accepts the path form `from './stdlib/auth.rules'` if you prefer).",purpose:'Two-function module covering the most common access-control predicates in any user-facing app: "is the request authenticated" and "is the request the owner of this document".',whenToUse:"Import as the first stdlib module on any project that has user-owned documents. Pairs with `validation` and `lifecycle` for full create/update/delete coverage.",entries:[{signature:"isAuthenticated(): bool",description:"`request.auth != null`."},{signature:"isOwner(userId: string): bool",description:"`request.auth.uid == userId`. Pass a field path like `resource.data.ownerId`.",examples:["allow update: if isAuthenticated() && isOwner(resource.data.ownerId);"]}],examples:[`rules_version = '2+modules';
1148
+ import { isAuthenticated } from 'auth';
1149
+
1150
+ service cloud.firestore {
1151
+ match /databases/{db}/documents {
1152
+ match /posts/{id} { allow read: if isAuthenticated(); }
1153
+ }
1154
+ }`],relatedKeys:["validation","lifecycle","membership"]},ih={key:"validation",kind:"user-module",description:"User-authored module: shape validation (hasRequired, hasOnly). Self-contained. Import via `import { hasRequired, hasOnly } from 'validation';` after `rules_version = '2+modules';`.",purpose:'Field-shape predicates: "the incoming doc has all these fields" and "the incoming doc has only these fields". Layered on top of `request.resource.data.keys()` so the agent does not have to remember the list-method idioms.',whenToUse:"Reach for `validation` on every `create` allow rule to gate field shape — and on `update` rules when the schema is strict.",entries:[{signature:"hasRequired(fields: list<string>): bool",description:"`request.resource.data.keys().hasAll(fields)`."},{signature:"hasOnly(fields: list<string>): bool",description:"`request.resource.data.keys().hasOnly(fields)`.",examples:["allow create: if hasRequired(['title','body']) && hasOnly(['title','body','tags']);"]},{signature:"validString(field: string, min: int, max: int): bool",description:"The incoming field is a string with size in [min, max] (inclusive). Uses dynamic access, so a MISSING field reads null and fails the type check instead of erroring — safe on optional fields.",examples:["allow create: if validString('title', 1, 100);"]},{signature:"isOneOf(field: string, values: list): bool",description:"Enum check: the incoming field value is in the allowed list (`request.resource.data[field] in values`). The rules idiom for what JS would write as `.includes()` — which does not exist here.",examples:["allow create: if isOneOf('status', ['draft', 'published']);"]}],relatedKeys:["map","lifecycle","content"]},ah={key:"lobby",kind:"user-module",description:"User-authored module: lobby lifecycle (validCreate, validJoin, canCancel) for two-player game sessions. Self-contained.",purpose:"Convention-based lifecycle for game lobbies — assumes the document has `host`, `guest`, and `status` fields. Encapsulates the rules for opening a lobby, joining as the second player, and cancelling.",whenToUse:"Reach for `lobby` on games with a join-then-start flow. The convention names are load-bearing — if your schema differs, fork these functions rather than try to remap.",entries:[{signature:"validCreate(): bool",description:'Host is the auth user, guest is empty, status is "waiting".'},{signature:"validJoin(): bool",description:'Guest slot is empty, joiner is not the host, status transitions to "playing".'},{signature:"canCancel(): bool",description:'Status is "waiting" and the requester is the host.'}],relatedKeys:["turns","state","transitions"]},oh={key:"turns",kind:"user-module",description:"User-authored module: turn enforcement for two-player games (isMyTurn, turnFlipped). Self-contained.",purpose:"Convention-based turn handling on docs with `host`, `guest`, and `currentTurn` fields. Asserts the request is from the current player and that turn alternates correctly across writes.",whenToUse:"Reach for `turns` on any turn-based game where exactly one player can act per state.",entries:[{signature:"isMyTurn(): bool",description:"Current player matches the auth uid (matches against `host` or `guest`)."},{signature:"turnFlipped(): bool",description:"After the write, `currentTurn` has switched from host to guest (or vice-versa)."}],relatedKeys:["lobby","state","transitions"]},ch={key:"state",kind:"user-module",description:"User-authored module: game state tracking (isPlaying, moveIncremented, participantsUnchanged). Self-contained.",purpose:"Mid-game state predicates: the game is in play, the move counter incremented by exactly one, the participant list did not change.",whenToUse:"Reach for `state` on per-move updates to assert the move actually advanced the game and did not change the players.",entries:[{signature:"isPlaying(): bool",description:'`resource.data.status == "playing"`.'},{signature:"moveIncremented(): bool",description:"`request.resource.data.moveCount == resource.data.moveCount + 1`."},{signature:"participantsUnchanged(): bool",description:"Host and guest fields are identical pre- and post-write."}],relatedKeys:["turns","lifecycle","transitions"]},uh={key:"membership",kind:"user-module",description:"User-authored module: claims + role-based access (hasClaim, hasClaimRole, isMemberOf, hasRole). Self-contained.",purpose:'Two halves: claim-based checks against the auth token, and role checks against a `members` map on a document. The module is the right cover for "team-style" apps where each doc has a participant map.',whenToUse:"Reach for `membership` whenever a rule gates on a custom claim (`request.auth.token.admin`) or on a role inside a participant map.",entries:[{signature:"hasClaim(claim: string): bool",description:"Auth token has a non-null value for the named claim."},{signature:"hasClaimRole(claim: string, role: string): bool",description:"Auth token claim equals the named role value."},{signature:"isMemberOf(membersMap: map): bool",description:"Auth uid is a key in the members map."},{signature:"hasRole(membersMap: map, role: string): bool",description:"Auth uid is in the members map with the named role."}],relatedKeys:["auth","request"]},lh={key:"lifecycle",kind:"user-module",description:"User-authored module: field immutability + server-timestamp checks (fieldUnchanged, immutableFields, isServerTimestamp). Self-contained.",purpose:"Locks specific fields against modification on updates and asserts that a timestamp field matches `request.time` (i.e. the client used the server-timestamp sentinel).",whenToUse:"Reach for `lifecycle` on every update rule to lock identity fields (`createdAt`, `ownerId`) and to enforce server-set timestamps.",entries:[{signature:"fieldUnchanged(field: string): bool",description:"The named field is byte-identical before and after the write."},{signature:"immutableFields(fields: list<string>): bool",description:"All listed fields are unchanged. Implemented via MapDiff so it is cheaper than chaining `fieldUnchanged` calls."},{signature:"isServerTimestamp(field: string): bool",description:"The named field equals `request.time` (i.e. the client wrote `FieldValue.serverTimestamp()`)."},{signature:"onlyFieldsChanged(fields: list<string>): bool",description:'The dual of immutableFields: every CHANGED field is in the allowed list, so unlisted fields are implicitly immutable (adds and removes count as changes). The single most common update guard — "users may edit title/body and nothing else". Top-level keys only; nested-map diffs are unreliable in production.',examples:["allow update: if onlyFieldsChanged(['title', 'body']);"]},{signature:"nFieldsChanged(n: int): bool",description:"Exactly n top-level fields changed in this write. `nFieldsChanged(1)` is the board-integrity / edit-one-field-per-write guard."}],relatedKeys:["map","validation","request","counters"]},dh={key:"transitions",kind:"user-module",description:"User-authored module: state-machine transitions (validTransition, statusIs, newStatusIs). Self-contained.",purpose:"Asserts that a field moves from one specific value to another specific value on a write. Use to encode state-machine edges directly in rules.",whenToUse:"Reach for `transitions` whenever a rule encodes a state machine — order: pending → paid → shipped, etc.",entries:[{signature:"validTransition(field: string, from: string, to: string): bool",description:"Field was `from` before and is `to` after."},{signature:"statusIs(field: string, value: string): bool",description:"Pre-write field equals `value`."},{signature:"newStatusIs(field: string, value: string): bool",description:"Post-write field equals `value`."}],relatedKeys:["state","lifecycle"]},hh={key:"geometry",kind:"user-module",description:"User-authored module: movement validation via config-doc lookup (validSimpleMove, validJumpMove). Caller must pass the config from a `get()` call.",purpose:'Board-game movement rules expressed as lookups in a config document — `cfg.moves[piece][from][to]` for simple moves, `cfg.jumps[piece][from][to]` for jumps (with captured-cell info). The module is "explicit parameter" style: no implicit reads — the caller passes the config explicitly.',whenToUse:"Reach for `geometry` on grid-based games (chess, checkers, go variants). Pair the function call with a `get()` on your config document.",entries:[{signature:"validSimpleMove(cfg: map): bool",description:"`cfg.moves[piece][from][to] == true`."},{signature:"validJumpMove(cfg: map): bool",description:"`cfg.jumps[piece][from][to] == capturedCell`."}],relatedKeys:["transitions","state"]},fh={key:"counters",kind:"user-module",description:"User-authored module: denormalized numeric integrity (incrementedBy, changedBy, boundedNumber). Self-contained.",purpose:"Keeps client-maintained counts honest — likes, votes, moves, quantities may only change by a known step or stay within known bounds. Generalizes the state module's moveIncremented() (hardcoded to moveCount) to any field.",whenToUse:"Reach for `counters` whenever a numeric field is client-written but semantically constrained: vote/like toggles (`changedBy(f, -1, 1)`), move counters (`incrementedBy(f, 1)`), ratings (`boundedNumber(f, 1, 5)`).",entries:[{signature:"incrementedBy(field: string, n: int): bool",description:"The field changed by EXACTLY n vs the existing document (n may be negative). Update rules only.",examples:["allow update: if incrementedBy('moveCount', 1);"]},{signature:"changedBy(field: string, min: int, max: int): bool",description:"The field's delta is within [min, max] inclusive; a zero delta passes when the range spans 0.",examples:["allow update: if changedBy('likeCount', -1, 1);"]},{signature:"boundedNumber(field: string, min: number, max: number): bool",description:"The incoming value is an int or float within [min, max]. Missing field reads null (dynamic access) and fails closed.",examples:["allow write: if boundedNumber('rating', 1, 5);"]}],relatedKeys:["lifecycle","state"]},ph={key:"timing",kind:"user-module",description:"User-authored module: cooldown / rate-limit enforcement (cooldownElapsed). Self-contained. Live-verified against the production engine.",purpose:"Rules CAN rate-limit: compare `request.time` against a stored server timestamp with duration arithmetic. Enforces a minimum interval between writes to a document.",whenToUse:"Reach for `timing` to throttle per-document writes — game move intervals, post cooldowns, retry backoff. ALWAYS pair with lifecycle's `isServerTimestamp(field)` on the same write so the stored timestamp cannot be forged by the client. Per-document intervals only; sliding-window quotas need a counter document plus this guard.",entries:[{signature:"cooldownElapsed(field: string, seconds: int): bool",description:"`request.time > resource.data[field] + duration.value(seconds, 's')` — the stored timestamp is STRICTLY older than the window. Update rules only (needs `resource`); a missing or non-timestamp field errors, which denies (fail-closed).",examples:["allow update: if cooldownElapsed('lastMoveAt', 2) && isServerTimestamp('lastMoveAt');"]}],relatedKeys:["lifecycle","timestamp","duration"]},mh={key:"content",kind:"user-module",description:"User-authored module: author-owned documents (validAuthorCreate, isAuthor, canReadContent, notDeleted). Self-contained. Field names are parameters, not conventions.",purpose:"The most common Firebase app shape — posts, notes, docs, comments, tasks. Covers the create/read/update/delete lifecycle of documents that belong to their author, with draft/published visibility and soft delete.",whenToUse:"Reach for `content` on any collection whose documents have an author/owner field. Compose with lifecycle.onlyFieldsChanged to keep authorship immutable on edits.",entries:[{signature:"validAuthorCreate(authorField: string): bool",description:"Create guard: signed in AND the incoming doc's author field is the caller's uid.",examples:["allow create: if validAuthorCreate('author');"]},{signature:"isAuthor(authorField: string): bool",description:"The caller is the EXISTING document's author. Update/delete rules.",examples:["allow update: if isAuthor('author') && onlyFieldsChanged(['title', 'body']);"]},{signature:"canReadContent(statusField: string, authorField: string): bool",description:"Published content is public; anything else is visible to its author only. `get` rules — a bare collection `list` will be denied unless the query proves `status == 'published'` via filters (rules are not filters).",examples:["allow read: if canReadContent('status', 'author') && notDeleted();"]},{signature:"notDeleted(): bool",description:"Soft-delete guard: `resource.data['deleted'] != true`. Bracket access is the null-on-miss idiom, so a document WITHOUT the field passes."}],relatedKeys:["auth","lifecycle","validation"]},gh={key:"spaces",kind:"user-module",description:"User-authored module: cross-document membership gating (isSpaceMember, hasSpaceRole, validMemberCreate). Explicit param — pass the parent doc data from a get(). Live-verified against the production engine.",purpose:"Shared spaces — teams, rooms, groups, projects, parties: a PARENT document's members field gates its children. The second-most-common app shape after author-owned content.",whenToUse:"Reach for `spaces` whenever a subcollection is gated by a parent doc. Define ONE helper in the child match block — `function space() { return get(/databases/$(database)/documents/spaces/$(spaceId)).data; }` — and pass it to every function: get() is cached per request, so all rules on the request share a single read of the 10-get budget. Do NOT inline a get() per allow clause.",entries:[{signature:"isSpaceMember(spaceData: map): bool",description:"The caller's uid is in `spaceData.members`. `in` covers BOTH shapes: list membership (`members: ['a','b']`) and map keys (`members: {a: 'admin'}`). Missing field / non-member / missing parent doc all fail closed.",examples:["allow read: if isSpaceMember(space());"]},{signature:"hasSpaceRole(spaceData: map, role: string): bool",description:"The caller's role in a MAP-shaped members field equals `role` (`spaceData.members[request.auth.uid] == role`). List-shaped members carry no roles — denies.",examples:["allow delete: if hasSpaceRole(space(), 'admin');"]},{signature:"validMemberCreate(spaceData: map, authorField: string): bool",description:`Member-gated authored create: caller is a member AND the incoming child doc's author field is the caller. The "post a message / add a task" guard.`,examples:["allow create: if validMemberCreate(space(), 'author');"]}],relatedKeys:["membership","content","builtins"]},yh={key:"joining",kind:"user-module",description:"User-authored module: safe self-service membership changes (onlyAddedSelf, onlyRemovedSelf). Self-contained. Live-verified against the production engine.",purpose:"How membership CHANGES without an admin backend: users join and leave a MAP-shaped members field (uid -> role) with zero privilege escalation — no self-granted roles, no touching other members, no-op writes denied.",whenToUse:"Reach for `joining` on the PARENT doc's update rule wherever spaces gates the children. ALWAYS compose with lifecycle's onlyFieldsChanged(['members']) so a join/leave write cannot modify anything else on the doc. Invite-doc consumption (single-use invites) is a Pattern, not a function — it needs a batch write + getAfter().",entries:[{signature:"onlyAddedSelf(membersField: string, role: string): bool",description:"The write adds EXACTLY the caller to the members map at EXACTLY `role` — changing nobody, removing nobody; a no-op write denies (uses set equality `diff.addedKeys() == [uid].toSet()`, not hasOnly, which passes on an empty diff). Update rules only.",examples:["allow update: if onlyFieldsChanged(['members']) && (onlyAddedSelf('members', 'editor') || onlyRemovedSelf('members'));"]},{signature:"onlyRemovedSelf(membersField: string): bool",description:"The write removes EXACTLY the caller — adding nobody, changing nobody. Self-service leave. Update rules only."}],relatedKeys:["spaces","lifecycle","membership"]},vh={key:"atomic",kind:"user-module",description:"User-authored module: cross-document BATCH-write integrity via get()/getAfter() (companionChangedBy, consumedFlag). Explicit param. Live-verified against a real production database.",purpose:"Rules that require a COMPANION write in the same atomic batch: denormalized counters (create task + increment team.taskCount), single-use invite consumption (join + mark invite used), paired documents. getAfter(path) returns the post-batch state of another doc in the batch; for docs not in the batch it equals get(path).",whenToUse:"Reach for `atomic` when two documents must change together. Define before()/after() helpers — `get(path).data` and `getAfter(path).data` for the SAME companion path — and pass both. Every write in a batch is rules-evaluated: the companion write needs its own allow rule. The client must use a batch/transaction (writeBatch / runTransaction); solo writes deny by construction.",entries:[{signature:"companionChangedBy(before: map, after: map, field: string, n: int): bool",description:"The companion doc's field changed by EXACTLY n in this batch (`after[field] == before[field] + n`). A solo write denies: without a companion write, getAfter == get, so the delta is 0.",examples:["allow create: if companionChangedBy(teamBefore(), teamAfter(), 'taskCount', 1);"]},{signature:"consumedFlag(before: map, after: map, flagField: string): bool",description:"A single-use flag was consumed IN THIS BATCH: pre-batch false AND post-batch true. Replays deny (already true before the batch); solo writes deny (false != true when getAfter == get). Pair with an allow rule on the flag doc itself (e.g. invitee-only, resource.used == false).",examples:["allow update: if consumedFlag(inviteBefore(), inviteAfter(), 'used');"]}],relatedKeys:["counters","joining","spaces","builtins"]},bh={key:"storage/uploads",kind:"user-module",description:"Storage module: inclusive upload-size limits and declared MIME metadata allowlists.",purpose:"Apply bounded upload policies to the incoming Storage object. MIME helpers inspect declared metadata; they do not inspect or authenticate the uploaded bytes.",whenToUse:"Use for Storage create or update rules that limit object size or accepted content-type metadata.",entries:[{signature:"sizeAtMost(maxBytes: int): bool",description:"The incoming object size is at most the inclusive byte limit."},{signature:"sizeBetween(minBytes: int, maxBytes: int): bool",description:"The incoming object size is inside the inclusive byte range."},{signature:"contentTypeMatches(pattern: string): bool",description:"The incoming content-type metadata matches the entire RE2 pattern.",notes:"This checks declared metadata, not the uploaded bytes."},{signature:"contentTypeIsOneOf(types: list): bool",description:"The incoming content-type metadata equals one allowlisted value.",notes:"This checks declared metadata, not the uploaded bytes."}],relatedKeys:["auth","membership","storage/metadata","storage/objects"]},wh={key:"storage/metadata",kind:"user-module",description:"Storage module: required custom metadata, bounded string values, and metadata ownership.",purpose:"Validate the flat string map in Storage custom metadata and connect incoming or existing ownership metadata to the authenticated UID.",whenToUse:"Use when object paths alone do not carry every upload invariant and custom metadata must be present, bounded, or owner-bound.",entries:[{signature:"hasRequiredMetadata(keys: list): bool",description:"The incoming custom metadata contains every required key."},{signature:"metadataString(key: string, min: int, max: int): bool",description:"The incoming metadata value is a string within the inclusive size range."},{signature:"incomingMetadataOwner(key: string): bool",description:"The incoming metadata value equals the authenticated UID."},{signature:"existingMetadataOwner(key: string): bool",description:"The existing metadata value equals the authenticated UID."}],relatedKeys:["auth","membership","storage/uploads","storage/objects"]},Sh={key:"storage/objects",kind:"user-module",description:"Storage module: distinguish create, update, and delete operations safely.",purpose:"Branch Storage authorization by request method without relying on missing resource bindings or null checks.",whenToUse:"Use when create, update, and delete require different ownership or validation checks.",entries:[{signature:"isCreate(): bool",description:"The Storage request method is 'create'."},{signature:"isUpdate(): bool",description:"The Storage request method is 'update'."},{signature:"isDelete(): bool",description:"The Storage request method is 'delete'."}],relatedKeys:["auth","membership","storage/uploads","storage/metadata"]},_h={key:"storage/time",kind:"user-module",description:"Storage module: strict freshness windows over server-owned object timestamps.",purpose:"Check whether an existing Storage object was created or updated within a bounded number of seconds.",whenToUse:"Use for access policies whose validity expires relative to an existing object timestamp.",entries:[{signature:"createdWithin(seconds: int): bool",description:"Request time is strictly before creation time plus the window.",notes:"Equality with the deadline denies. Requires an existing object."},{signature:"updatedWithin(seconds: int): bool",description:"Request time is strictly before update time plus the window.",notes:"Equality with the deadline denies. Requires an existing object."}],relatedKeys:["storage/objects","auth","membership"]};function Ah(t){if(t.kind!=="user-module")return["firestore"];const e=Is[t.key];return e?e.map(r=>r==="firebase.storage"?"storage":"firestore"):["firestore"]}[Hd,Wd,Gd,Kd,Zd,Jd,Yd,Qd,Xd,eh,th,rh,nh,sh,ih,ah,oh,ch,uh,lh,dh,hh,fh,ph,mh,gh,yh,vh,bh,wh,Sh,_h].map(t=>({...t,services:Ah(t)}));function Ih(t){return typeof t=="object"&&t!==null&&t.__type==="serverTimestamp"}const xh={name:"date-to-timestamp",convert(t){return t instanceof Date?_e.fromMillis(t.getTime()):We}},kh={name:"server-timestamp-sentinel",convert(t,e){return Ih(t)?e.serverTime instanceof _e?e.serverTime:_e.fromMillis(Date.now()):We}};function Eh(t){if(t===null||typeof t!="object"||t instanceof _e)return!1;const e=t;return typeof e.seconds=="number"&&typeof e.nanoseconds=="number"&&typeof e.toMillis=="function"}const Th={name:"user-timestamp-to-rules-timestamp",convert(t){return Eh(t)?new _e(t.seconds,t.nanoseconds):We}};function Oi(t){return typeof t=="object"&&t!==null&&"isEqual"in t&&typeof t.isEqual=="function"}function es(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function Ci(t){if(typeof t!="object"||t===null||es(t))return;const e=t;if(typeof e.seconds=="number"){const r=typeof e.nanoseconds=="number"?e.nanoseconds:e.nanos;if(typeof r=="number")return{kind:"timestamp",seconds:e.seconds,nanoseconds:r}}if(e.data instanceof Uint8Array)return{kind:"bytes",values:Array.from(e.data)};if(typeof e.toUint8Array=="function")return{kind:"bytes",values:Array.from(e.toUint8Array())};if(typeof e.latitude=="number"&&typeof e.longitude=="number")return{kind:"geo-point",latitude:e.latitude,longitude:e.longitude};if(typeof e.lat=="number"&&typeof e.lng=="number")return{kind:"geo-point",latitude:e.lat,longitude:e.lng};if(typeof e.path=="string")return{kind:"reference",path:e.path};if(e.typeName==="vector"&&Array.isArray(e.value))return{kind:"vector",values:e.value};if(typeof e.toArray=="function")return{kind:"vector",values:e.toArray()}}function Ye(t,e){if(Object.is(t,e))return!0;const r=Ci(t),n=Ci(e);if(r!==void 0||n!==void 0){if(r===void 0||n===void 0||r.kind!==n.kind)return!1;switch(r.kind){case"timestamp":return n.kind==="timestamp"&&r.seconds===n.seconds&&r.nanoseconds===n.nanoseconds;case"bytes":return n.kind==="bytes"&&r.values.length===n.values.length&&r.values.every((a,o)=>a===n.values[o]);case"vector":return n.kind==="vector"&&r.values.length===n.values.length&&r.values.every((a,o)=>a===n.values[o]);case"geo-point":return n.kind==="geo-point"&&r.latitude===n.latitude&&r.longitude===n.longitude;case"reference":return n.kind==="reference"&&r.path===n.path}}if(Oi(t))return t.isEqual(e);if(Oi(e))return e.isEqual(t);if(Array.isArray(t)||Array.isArray(e))return!Array.isArray(t)||!Array.isArray(e)||t.length!==e.length?!1:t.every((a,o)=>Ye(a,e[o]));if(!es(t)||!es(e))return!1;const s=Object.keys(t),i=Object.keys(e);return s.length!==i.length?!1:s.every(a=>a in e&&Ye(t[a],e[a]))}function Oh(t){return typeof t=="object"&&t!==null&&t.__type==="increment"&&typeof t.value=="number"}function Ch(t){return typeof t=="object"&&t!==null&&t.__type==="arrayUnion"&&Array.isArray(t.values)}function Rh(t){return typeof t=="object"&&t!==null&&t.__type==="arrayRemove"&&Array.isArray(t.values)}function Nh(t){return typeof t=="object"&&t!==null&&t.__type==="deleteField"}function Cs(t){if(t.prior===null)return;if(t.fieldPath==="")return t.prior;let e=t.prior;for(const r of t.fieldPath.split(".")){const n=/^([^\[]*)/.exec(r),s=n?n[1]:r;if(s){if(typeof e!="object"||e===null)return;e=e[s]}const i=/\[(\d+)\]/g;let a;for(;(a=i.exec(r))!==null;){if(!Array.isArray(e))return;e=e[Number(a[1])]}}return e}const Lh={name:"increment-sentinel",convert(t,e){if(!Oh(t))return We;const r=Cs(e);return(typeof r=="number"?r:0)+t.value}},Mh={name:"array-union-sentinel",convert(t,e){if(!Ch(t))return We;const r=Cs(e),n=Array.isArray(r)?r.slice():[];for(const s of t.values)n.some(a=>Ye(a,s))||n.push(s);return n}},Dh={name:"array-remove-sentinel",convert(t,e){if(!Rh(t))return We;const r=Cs(e);return Array.isArray(r)?r.filter(n=>!t.values.some(s=>Ye(n,s))):[]}},Fh={name:"delete-field-sentinel",convert(t){return Nh(t)?et:We}},Ri=Symbol.for("pyric.firestore.query-value-registry"),Ni=globalThis,gr=Ni[Ri]??(Ni[Ri]=new WeakMap),Li=Symbol.for("pyric.firestore.query-value-execution-registry"),Mi=globalThis,Yr=Mi[Li]??(Mi[Li]=new WeakMap),Di=Symbol.for("pyric.firestore.query-value-owner-registry"),Fi=globalThis,Qr=Fi[Di]??(Fi[Di]=new WeakMap);function Rs(t,e,r=()=>t){gr.set(t,e),Yr.set(t,r)}function jh(t){return gr.get(t)}function Pp(t){return Qr.get(t)}function $p(t){return Yr.get(t)?.()??t}function Up(t,e){const r=gr.get(t),n=Yr.get(t);r!==void 0&&gr.set(e,r),n!==void 0&&Yr.set(e,n);const s=Qr.get(t);s!==void 0&&Qr.set(e,s)}const ts=Symbol.for("pyric.firestore.reference-query-value");class qh{path;[ts]=!0;constructor(e){this.path=e}isEqual(e){return typeof e=="object"&&e!==null&&ts in e&&e.path===this.path}}function Ph(t){const e=gr.get(t);if(typeof e!="object"||e===null||!(ts in e))return;const r=e.path;return typeof r=="string"?r:void 0}function Bp(t,e,r,n=t){Rs(t,new qh(e),()=>n),Qr.set(t,r)}function $h(t){if(t===null||typeof t!="object"||t instanceof Ot)return!1;const e=t;return typeof e.path=="string"&&typeof e.id=="string"&&e._path!==void 0&&e._firestore!==void 0}const Uh={name:"document-reference",convert(t){if(typeof t=="object"&&t!==null){const e=Ph(t);if(e!==void 0)return new Ot(e)}return $h(t)?new Ot(t.path):We}};function Bh(t){return Array.isArray(t)&&t.every(e=>typeof e=="number")}function zh(t){if(t===null||typeof t!="object"||t instanceof Qt)return null;const e=t;return Bh(e._values)&&typeof e.toArray=="function"?e._values:null}const Vh={name:"vector-value",convert(t){const e=zh(t);return e===null?We:new Qt(e)}};function Hh(t){if(t===null||typeof t!="object"||t instanceof Ae)return!1;const e=t;return typeof e.toBase64=="function"&&typeof e.toUint8Array=="function"&&typeof e.isEqual=="function"}function Wh(t){if(t===null||typeof t!="object"||t instanceof lt)return!1;const e=t;return typeof e.latitude=="number"&&typeof e.longitude=="number"&&typeof e.isEqual=="function"}const Gh={name:"fb-bytes-to-rules-bytes",convert(t){return Hh(t)?new Ae(t.toUint8Array()):We}},Kh={name:"fb-geopoint-to-rules-latlng",convert(t){return Wh(t)?new lt(t.latitude,t.longitude):We}},We=Symbol("value-resolver:KEEP"),et=Symbol("value-resolver:DELETE_MARKER"),rs=[];function Ge(t){rs.some(e=>e.name===t.name)||rs.push(t)}function Ze(t,e){const r={};for(const[n,s]of Object.entries(t))r[n]=ns(s,{...e,fieldPath:n});return r}function ns(t,e){for(const r of rs){const n=r.convert(t,e);if(n!==We)return n}if(Array.isArray(t))return t.map((r,n)=>ns(r,{...e,fieldPath:`${e.fieldPath}[${n}]`}));if(qt(t)){const r={};for(const[n,s]of Object.entries(t)){const i=e.fieldPath?`${e.fieldPath}.${n}`:n;r[n]=ns(s,{...e,fieldPath:i})}return r}return t}function qt(t){if(t===null||typeof t!="object")return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function xt(t){const e={},r=[];for(const[n,s]of Object.entries(t)){if(s===et){r.push(n);continue}e[n]=Xr(s)}return{writes:e,deletedKeys:r}}function Xr(t){if(t!==et){if(Array.isArray(t))return t.filter(e=>e!==et).map(Xr);if(qt(t)){const e={};for(const[r,n]of Object.entries(t))n!==et&&(e[r]=Xr(n));return e}return t}}function Zh(){Ge(xh),Ge(kh),Ge(Th),Ge(Lh),Ge(Mh),Ge(Dh),Ge(Fh),Ge(Uh),Ge(Vh),Ge(Gh),Ge(Kh)}function no(t){return t.split(".")}const Jh=new Set(["__proto__","prototype","constructor"]);function ji(t){if(Jh.has(t))throw new Error(`Invalid field-path segment '${t}': the keys __proto__, prototype, and constructor are reserved and cannot appear in a field path.`)}function Ns(t){const e={};for(const[r,n]of Object.entries(t))e[r]=so(n);return e}function so(t){return Array.isArray(t)?t.map(so):qt(t)?Ns(t):t}function io(t,e,r){let n=t;for(let i=0;i<e.length-1;i++){const a=e[i];ji(a);const o=Object.hasOwn(n,a)?n[a]:void 0;qt(o)||(n[a]={}),n=n[a]}const s=e[e.length-1];ji(s),r===et?delete n[s]:n[s]=Xr(r)}function qi(t,e){const r=Ns(t);for(const[n,s]of Object.entries(e)){if(s!==et&&en(s))throw new ao;io(r,no(n),s)}return r}class ao extends Error{constructor(){super("FieldValue.delete() can only appear at the top level of your update data"),this.name="DeleteFieldNestedError"}}function en(t){return t===et?!0:Array.isArray(t)?t.some(en):qt(t)?Object.values(t).some(en):!1}function Yh(t){for(const e of Object.values(t))if(e!==et&&en(e))throw new ao}function ss(t,e,r){const n=Ns(t),s=[];if(r!==void 0)for(const i of r){const a=no(i),o=Qh(e,a);o!==oo&&s.push({segments:a,value:o})}else co(e,[],s);for(const{segments:i,value:a}of s)io(n,i,a);return n}const oo=Symbol("field-merge:ABSENT");function Qh(t,e){let r=t;for(const n of e){if(!qt(r)||!Object.hasOwn(r,n))return oo;r=r[n]}return r}function co(t,e,r){const n=Object.keys(t);if(n.length===0&&e.length>0){r.push({segments:e,value:{}});return}for(const s of n){const i=t[s],a=[...e,s];qt(i)&&i!==et?co(i,a,r):r.push({segments:a,value:i})}}function Xh(t,e){const r={};for(const n of e)Object.prototype.hasOwnProperty.call(t,n)&&(r[n]=t[n]);return r}class In{documents;versions=new Map;nextVersion=1;constructor(e={},r){this.documents=r??new Map;for(const[n,s]of Object.entries(e)){const i=Ze({...s},{path:n,method:"seed",prior:null}),{writes:a}=xt(i);this.documents.set(n,a),this.bumpVersion(n)}}get(e){return this.documents.get(e)??null}version(e){return this.versions.get(e)??0}currentVersion(){return this.nextVersion-1}exists(e){return this.documents.has(e)}scan(e,r={}){const n=e===""||e.endsWith("/")?e:e+"/",s=r.projection?c=>Xh(c,r.projection):c=>c,i=[],a=new Set,o=[];for(const[c,u]of this.documents){if(n!==""&&!c.startsWith(n))continue;if(!r.directOnly){i.push({path:c,data:s(u)});continue}const f=c.slice(n.length),l=f.indexOf("/");if(l===-1)i.push({path:c,data:s(u)}),a.add(f);else if(r.phantoms){const p=f.slice(0,l);p.length>0&&!o.includes(p)&&o.push(p)}}if(r.directOnly&&r.phantoms)for(const c of o)a.has(c)||i.push({path:n+c,data:{},phantom:!0});return i}list(e){return this.scan(e,{directOnly:!0,phantoms:!0})}listRootCollections(){const e=new Set,r=[];for(const n of this.documents.keys()){const s=n.split("/",1)[0];s.length!==0&&(e.has(s)||(e.add(s),r.push(s)))}return r}listSubcollections(e){const r=e.endsWith("/")?e:e+"/",n=new Set,s=[];for(const i of this.documents.keys()){if(!i.startsWith(r))continue;const o=i.slice(r.length).split("/",1)[0];o.length!==0&&(n.has(o)||(n.add(o),s.push(o)))}return s}snapshot(){const e={};for(const[r,n]of this.documents)e[r]={...n};return e}size(){return this.documents.size}create(e,r){if(this.documents.has(e))return{success:!1,error:`Document '${e}' already exists`};let n;try{const s=Ze({...r},{path:e,method:"create",prior:null});n=xt(s).writes}catch(s){return{success:!1,error:s.message}}return this.documents.set(e,n),this.bumpVersion(e),{success:!0}}update(e,r){const n=this.documents.get(e);if(!n)return{success:!1,error:`Document '${e}' does not exist`};let s;try{const i=Ze({...r},{path:e,method:"update",prior:n});s=qi(n,i)}catch(i){return{success:!1,error:i.message}}return this.documents.set(e,s),this.bumpVersion(e),{success:!0,priorData:{...n}}}setMerge(e,r,n){const s=this.documents.has(e)?{...this.documents.get(e)}:null,i=Ze({...r},{path:e,method:"set",prior:s}),a=ss(s??{},i,n);return this.documents.set(e,a),this.bumpVersion(e),{success:!0,priorData:s,created:s===null}}set(e,r){const n=this.documents.has(e)?{...this.documents.get(e)}:null,s=Ze({...r},{path:e,method:"set",prior:n}),{writes:i}=xt(s);return this.documents.set(e,i),this.bumpVersion(e),{success:!0,priorData:n,created:n===null}}delete(e){const r=this.documents.get(e);return r?(this.documents.delete(e),this.bumpVersion(e),{success:!0,priorData:{...r}}):{success:!1,error:`Document '${e}' does not exist`}}applyBatch(e){const r=[];for(let s=0;s<e.length;s++){const i=e[s];switch(i.method){case"create":this.documents.has(i.path)&&r.push({index:s,error:`Document '${i.path}' already exists`});break;case"update":this.documents.has(i.path)||r.push({index:s,error:`Document '${i.path}' does not exist`});break}}if(r.length>0)return{success:!1,errors:r};const n=new Map;for(const s of e)n.has(s.path)||n.set(s.path,this.documents.has(s.path)?{...this.documents.get(s.path)}:null);for(const s of e){switch(s.method){case"create":{const i=Ze({...s.data},{path:s.path,method:"create",prior:null}),{writes:a}=xt(i);this.documents.set(s.path,a);break}case"update":{const i=this.documents.get(s.path),a=Ze({...s.data},{path:s.path,method:"update",prior:i});this.documents.set(s.path,qi(i,a));break}case"set":{const i=n.get(s.path)??null,a=Ze({...s.data},{path:s.path,method:"set",prior:i}),{writes:o}=xt(a);this.documents.set(s.path,o);break}case"delete":this.documents.delete(s.path);break}this.bumpVersion(s.path)}return{success:!0,priorStates:n}}restore(e){const r=new Set([...this.documents.keys(),...Object.keys(e)]);this.documents.clear();for(const[n,s]of Object.entries(e))this.documents.set(n,{...s});for(const n of r)this.bumpVersion(n)}restorePaths(e){for(const[r,n]of Object.entries(e))n===null?this.documents.delete(r):this.documents.set(r,{...n}),this.bumpVersion(r)}bumpVersion(e){this.versions.set(e,this.nextVersion++)}}class ef{base;overlay=new Map;tombstones=new Set;baseCache=new Map;cleared=!1;constructor(e){this.base=e}inBase(e){return Object.prototype.hasOwnProperty.call(this.base,e)}baseDoc(e){let r=this.baseCache.get(e);return r===void 0&&(r=structuredClone(this.base[e]),this.baseCache.set(e,r)),r}get(e){if(this.overlay.has(e))return this.overlay.get(e);if(!(this.cleared||this.tombstones.has(e)))return this.inBase(e)?this.baseDoc(e):void 0}set(e,r){this.overlay.set(e,r),this.tombstones.delete(e)}has(e){return this.overlay.has(e)?!0:this.cleared||this.tombstones.has(e)?!1:this.inBase(e)}delete(e){const r=this.has(e);return this.overlay.delete(e),!this.cleared&&this.inBase(e)&&this.tombstones.add(e),r}clear(){this.overlay.clear(),this.tombstones.clear(),this.baseCache.clear(),this.cleared=!0}get size(){let e=0;for(const r of this)e++;return e}*keys(){for(const[e]of this)yield e}*[Symbol.iterator](){const e=new Set;if(!this.cleared)for(const r of Object.keys(this.base))this.tombstones.has(r)||(e.add(r),yield[r,this.overlay.has(r)?this.overlay.get(r):this.baseDoc(r)]);for(const[r,n]of this.overlay)e.has(r)||(yield[r,n])}}class tf{events=[];nextId=1;undoneEvents=[];append(e,r=!1){const n={...e,id:this.nextId++,timestamp:new Date().toISOString()};return this.events.push(n),r||(this.undoneEvents=[]),n}getEvents(){return[...this.events]}getWriteEvents(){return this.events.filter(e=>e.allowed&&e.method!=="get"&&e.method!=="list")}lastWriteEvent(){const e=this.getWriteEvents();return e.length>0?e[e.length-1]:null}popLastWrite(){for(let e=this.events.length-1;e>=0;e--){const r=this.events[e];if(!r.aborted&&r.allowed&&r.method!=="get"&&r.method!=="list")return this.events.splice(e,1),this.undoneEvents.push(r),r}return null}popLastUndo(){return this.undoneEvents.pop()??null}size(){return this.events.length}clear(){this.events=[],this.undoneEvents=[],this.nextId=1}}function rf(t){return new Date(t.toMillis()).toISOString()}class yr extends Error{method;path;debugMessages;constructor(e,r,n,s){super(e),this.method=r,this.path=n,this.debugMessages=s,this.name="SimulatorUnsupportedError"}}function vr(t,e,r){const n=r.filter(i=>i.includes("unsupported:")).map(i=>i.replace(/^.*unsupported:\s*/,"")).join("; "),s=n?` Reason(s): ${n}.`:"";return`Simulator cannot decide ${t} on ${e} — the rule uses a feature the local simulator does not yet implement.${s} Verify this rule against production using TestFirestoreRulesHandler, or file a sim-gap entry in REBUILD_PLAN.md.`}function nf(t=""){return{description:t,expectation:"ALLOW",state:"PASSED",decision:"ALLOW",trace:[],notes:["admin lens — rules bypassed (Studio Gap #2)"]}}const sf=`rules_version = '2';
1155
+ service cloud.firestore {
1156
+ match /databases/{database}/documents {
1157
+ match /{document=**} {
1158
+ allow read, write: if true;
1159
+ }
1160
+ }
1161
+ }
1162
+ `;class At{swallowAsyncRejections;subscribers=new Set;constructor(e=!1){this.swallowAsyncRejections=e}get hasSubscribers(){return this.subscribers.size>0}subscribe(e){return this.subscribers.add(e),()=>{this.subscribers.delete(e)}}emit(...e){for(const r of this.subscribers)try{const n=r(...e);this.swallowAsyncRejections&&n&&typeof n.then=="function"&&n.catch(()=>{})}catch{}}clear(){this.subscribers.clear()}}class af{denial=new At;request=new At(!0);write=new At(!0);delivery=new At;suppressed=new At;lifecycle=new At;snapshotError=new At;clear(){this.denial.clear(),this.request.clear(),this.write.clear(),this.delivery.clear(),this.suppressed.clear(),this.lifecycle.clear(),this.snapshotError.clear()}}class of{currentTrigger;run(e,r){const n=this.currentTrigger;this.currentTrigger=e;try{return r()}finally{this.currentTrigger=n}}current(){return this.currentTrigger}}class tn extends Error{code;simError;constructor(e){super(e.message),this.name="FirestoreError",this.code=e.code,this.simError=e}}const Pi=Symbol.for("pyric.firestore.activity-value-registry"),$i=globalThis,uo=$i[Pi]??($i[Pi]=new WeakMap);function lo(){let t=2166136261,e=2654435769,r=2246822507,n=3266489909;const s=i=>{t=Math.imul(t^i,16777619),e=Math.imul(e^i,2246822507),r=Math.imul(r^i,3266489909),n=Math.imul(n^i,668265263)};return{update:i=>{if(typeof i=="string")for(let a=0;a<i.length;a+=1){const o=i.charCodeAt(a);s(o&255),s(o>>>8)}else for(const a of i)s(a)},finish:()=>[t,e,r,n].map(i=>(i>>>0).toString(16).padStart(8,"0")).join("")}}function Ls(...t){const e=lo();for(const r of t)e.update(r);return e.finish()}function zp(t){return{type:"string-digest",length:t.length,digest:Ls("string\0",t)}}function cf(t,...e){return{type:`${t}-digest`,digest:Ls(`${t}\0`,...e)}}function Vp(t){return{type:"bytes-digest",length:t.byteLength,digest:Ls("bytes\0",t)}}function Ui(t){const e=lo(),r=(...s)=>{for(const i of s)e.update(i)},n=s=>{if(s===null){r("null;");return}switch(typeof s){case"string":r(`s${s.length}:`,s,";");return;case"number":r(`n${Object.is(s,-0)?"-0":String(s)};`);return;case"boolean":r(s?"b1;":"b0;");return;case"undefined":r("u;");return;case"bigint":r(`i${s.toString()};`);return;case"object":break;default:r(`x${typeof s};`);return}if(Array.isArray(s)){r(`a${s.length}[`);for(const o of s)n(o);r("];");return}const i=s,a=Object.keys(i).sort();r(`o${a.length}{`);for(const o of a)r(`k${o.length}:`,o,"="),n(i[o]);r("};")};return n(t),{type:"wire-value-digest",digest:e.finish()}}function is(t,e){uo.set(t,e)}function Hp(t){return uo.get(t)}class Wp{static serverTimestamp(){return{__type:"serverTimestamp"}}static increment(e){return{__type:"increment",value:e}}static arrayUnion(...e){return{__type:"arrayUnion",values:e}}static arrayRemove(...e){return{__type:"arrayRemove",values:e}}static delete(){return{__type:"deleteField"}}}class Vt{seconds;nanoseconds;constructor(e,r){this.seconds=e,this.nanoseconds=r,is(this,cf("timestamp",String(e),"\0",String(r))),Rs(this,Object.freeze({type:"timestamp",seconds:e,nanoseconds:r}),()=>new Vt(e,r))}static now(){return Vt.fromMillis(Date.now())}static fromDate(e){return Vt.fromMillis(e.getTime())}static fromMillis(e){const r=Math.floor(e/1e3),n=Math.floor((e-r*1e3)*1e6);return new Vt(r,n)}toDate(){return new Date(this.toMillis())}toMillis(){return this.seconds*1e3+this.nanoseconds/1e6}isEqual(e){return e.seconds===this.seconds&&e.nanoseconds===this.nanoseconds}toString(){return`Timestamp(seconds=${this.seconds}, nanoseconds=${this.nanoseconds})`}toJSON(){return{type:"firestore/timestamp/1.0",seconds:this.seconds,nanoseconds:this.nanoseconds}}valueOf(){const r=this.seconds- -62135596800,n=String(r).padStart(12,"0"),s=String(this.nanoseconds).padStart(9,"0");return`${n}.${s}`}}function as(t){return t instanceof _e?new Vt(t.seconds,t.nanos):t instanceof Ae||t instanceof lt||t instanceof Qt?t:Array.isArray(t)?t.map(as):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).map(([e,r])=>[e,as(r)])):t}function ho(t){return as(t)}const uf=/[*~/[\]]/,lf=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class rn{_internalPath;constructor(...e){if(Array.isArray(e[0]))throw new Error("The FieldPath constructor no longer supports an array as its first argument. Please unpack your array and call FieldPath() with individual arguments.");if(e.length===0)throw new Error('Function "FieldPath()" requires at least 1 argument.');e.forEach((r,n)=>{if(typeof r!="string")throw new Error(`Element at index ${n} is not a valid string.`);if(r.length===0)throw new Error(`Element at index ${n} should not be an empty string.`)}),this._internalPath={segments:[...e],offset:0,len:e.length}}static DOCUMENT_ID=new rn("__name__");static documentId(){return rn.DOCUMENT_ID}isEqual(e){const r=fo(e),n=this._internalPath.segments;return n.length===r.length&&n.every((s,i)=>s===r[i])}toString(){return this._internalPath.segments.map(e=>lf.test(e)?e:`\`${e.replace(/\\/g,"\\\\").replace(/`/g,"\\`")}\``).join(".")}}function er(t){return new Error(`Value for argument "field" is not a valid field path. ${t}`)}function fo(t){if(t instanceof rn)return t._internalPath.segments;if(typeof t=="object"&&t!==null){const e=t._internalPath;if(Array.isArray(e?.segments)&&e.segments.every(r=>typeof r=="string"))return[...e.segments]}if(t===void 0)throw er("The path cannot be omitted.");if(typeof t!="string")throw er("Paths can only be specified as strings or via a FieldPath object.");if(t.includes(".."))throw er('Paths must not contain ".." in them.');if(t.startsWith(".")||t.endsWith("."))throw er('Paths must not start or end with ".".');if(t.length===0||uf.test(t))throw er(`Paths can't be empty and must not contain
1163
+ "*~/[]".`);return t.split(".")}function df(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function po(t,e){const r=fo(e);let n=t;for(const s of r){if(!df(n))return;n=Object.prototype.hasOwnProperty.call(n,s)?n[s]:void 0}return n}const Zt=Object.freeze({hasPendingWrites:!1,fromCache:!1}),Bi=Object.freeze({hasPendingWrites:!0,fromCache:!1});function mo(t){const e=t.lastIndexOf("/");return e===-1?t:t.slice(e+1)}function tr(t,e,r=Zt){const n={id:mo(t),path:t},s=e!==null,i=s?ho(e):void 0;return{id:n.id,ref:n,metadata:r,exists:()=>s,data:()=>i,get:a=>po(i,a)}}function go(t,e,r=Zt){const n={id:mo(t),path:t},s=ho(e);return{id:n.id,ref:n,metadata:r,exists:()=>!0,data:()=>s,get:i=>po(s,i)}}function rr(t,e,r,n,s=Zt){const i=e.map(u=>go(u.path,u.data,s)),a=n?hf(n,e,i,s):i.map((u,f)=>({type:"added",doc:u,oldIndex:-1,newIndex:f}));let o=null,c=null;return{query:t,metadata:s,size:i.length,empty:i.length===0,docs:i,forEach(u){for(const f of i)u(f)},docChanges(u){const f=!!u?.includeMetadataChanges;if(f&&r.excludesMetadataChanges)throw new Error("To include metadata changes with your document changes, you must also pass { includeMetadataChanges: true } to onSnapshot().");return f?(c||(c=a.slice()),c):(o||(o=a.slice()),o)}}}function hf(t,e,r,n=Zt){const s=new Map;t.forEach((o,c)=>s.set(o.path,c));const i=new Map;e.forEach((o,c)=>i.set(o.path,c));const a=[];for(let o=0;o<t.length;o++){const c=t[o];i.has(c.path)||a.push({type:"removed",doc:go(c.path,c.data,n),oldIndex:o,newIndex:-1})}for(let o=0;o<e.length;o++){const c=e[o],u=s.get(c.path);if(u===void 0)a.push({type:"added",doc:r[o],oldIndex:-1,newIndex:o});else{const f=t[u].data;JSON.stringify(f)!==JSON.stringify(c.data)&&a.push({type:"modified",doc:r[o],oldIndex:u,newIndex:o})}}return a}function zi(t,e){return t===null&&e===null?!0:t===null||e===null?!1:JSON.stringify(t)===JSON.stringify(e)}function ff(t,e){const r=`${e}/`;for(const n of t){if(!n.startsWith(r))continue;const s=n.slice(r.length);if(s.length>0&&!s.includes("/"))return!0}return!1}let xn=0;function lr(){return xn=xn+1>>>0,`req-${xn.toString(36)}-${Math.random().toString(36).slice(2,7)}`}function pf(t,e){const r=e==="allow";let n;for(const s of t){const i=/^Rule #(\d+) \(([^)]+)\) → (ALLOW|deny|unsupported)/.exec(s);if(!i)continue;const a={ruleIndex:Number(i[1]),operations:i[2].split(",").map(o=>o.trim())};if(r&&i[3]==="ALLOW")return a;n=a}return n}function un(t){const e={kind:"request",id:lr(),at:t.at,evalMs:t.evalMs,method:t.method,path:t.path,auth:t.auth?{uid:t.auth.uid,...t.auth.token?{token:t.auth.token}:{}}:null,result:t.result,reasons:t.debugMessages,origin:t.origin};t.resourceData!==void 0&&(e.request={resourceData:t.resourceData}),t.resourceBefore!==void 0&&(e.resourceBefore=t.resourceBefore),t.resourceAfter!==void 0&&(e.resourceAfter=t.resourceAfter);const r=pf(t.debugMessages,t.result);return r&&(e.matchedRule=r),t.result!=="unsupported"&&t.evaluatedRule&&(e.evaluatedRule=t.evaluatedRule),t.groupId!==void 0&&(e.groupId=t.groupId,t.origin==="batch"?e.groupKind="batch":t.origin==="transaction"&&(e.groupKind="transaction")),t.triggeredBy!==void 0&&(e.triggeredBy=t.triggeredBy),t.detail!==void 0&&(e.detail=t.detail),t.provenance!==void 0&&Object.assign(e,t.provenance),e}class mf{events;triggerScope;host;snapshotListeners=new Map;nextListenerId=0;deliveryQueue=[];deliveryScheduled=!1;constructor(e,r,n){this.events=e,this.triggerScope=r,this.host=n}emitSnapshotDelivery(e){if(!this.events.delivery.hasSubscribers)return;const r={kind:"snapshot_delivery",id:lr().replace(/^req-/,"snd-"),at:Date.now(),listenerId:e.listenerId,target:e.target,auth:e.auth?{uid:e.auth.uid,...e.auth.token?{token:e.auth.token}:{}}:null,addedCount:e.addedCount,modifiedCount:e.modifiedCount,removedCount:e.removedCount,size:e.size,...e.sample?{sample:e.sample}:{},...e.triggeredBy?{triggeredBy:e.triggeredBy}:{}};this.events.delivery.emit(r)}emitSnapshotSuppressed(e){if(!this.events.suppressed.hasSubscribers)return;const r={kind:"snapshot_suppressed",id:lr().replace(/^req-/,"sup-"),at:Date.now(),listenerId:e.listenerId,target:e.target,auth:e.auth?{uid:e.auth.uid,...e.auth.token?{token:e.auth.token}:{}}:null,reason:"no-op",...e.triggeredBy?{triggeredBy:e.triggeredBy}:{}};this.events.suppressed.emit(r)}emitLifecycle(e){if(!this.events.lifecycle.hasSubscribers)return;const r={kind:e.phase,id:lr().replace(/^req-/,"lc-"),at:Date.now(),listenerId:e.listenerId,target:e.target,auth:e.auth?{uid:e.auth.uid,...e.auth.token?{token:e.auth.token}:{}}:null};this.events.lifecycle.emit(r)}emitSnapshotError(e,r,n){this.events.snapshotError.emit(e,r,n)}addSnapshotListener(e,r,n={},s=null,i,a=!1,o=!1,c){const u=String(this.nextListenerId++),f={id:u,target:e,callback:r,auth:s,bypassRules:o,followsCurrentUser:a,...c?{authScope:c}:{},options:n,currentSnapshot:void 0,errored:!1,...i?{errorCallback:i}:{}};return this.snapshotListeners.set(u,f),this.emitLifecycle({phase:"listener_attach",listenerId:u,target:e.kind==="doc"?{kind:"doc",path:e.path}:{kind:"query",collection:e.collection,...e.constraints?.activityQuery?{query:e.constraints.activityQuery}:{}},auth:s}),this.scheduleDelivery(()=>{this.snapshotListeners.has(u)&&this.fireInitialSnapshot(f)}),()=>{const l=this.snapshotListeners.has(u);this.snapshotListeners.delete(u),l&&this.emitLifecycle({phase:"listener_detach",listenerId:u,target:e.kind==="doc"?{kind:"doc",path:e.path}:{kind:"query",collection:e.collection,...e.constraints?.activityQuery?{query:e.constraints.activityQuery}:{}},auth:s})}}fireInitialSnapshot(e){if(e.target.kind==="doc"){const s=this.host.silentReadDoc(e.target.path,e.auth,e.bypassRules);if(!s.allowed){this.markErrored(e,s.error);return}const i=tr(e.target.path,s.data);e.currentSnapshot=i,e.currentDocData=s.data;try{e.callback(i)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"doc",path:e.target.path},auth:e.auth,addedCount:s.data!==null?1:0,modifiedCount:0,removedCount:0,size:s.data!==null?1:0,sample:{docs:[{path:e.target.path,data:s.data}]}});return}const r=this.host.silentReadCollection(e.target.collection,e.auth,e.target.constraints,e.bypassRules);if(!r.allowed){this.markErrored(e,r.error);return}const n=rr({path:e.target.collection},r.docs,{excludesMetadataChanges:!e.options.includeMetadataChanges});e.currentSnapshot=n,e.currentDocs=r.docs;try{e.callback(n)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"query",collection:e.target.collection},auth:e.auth,addedCount:r.docs.length,modifiedCount:0,removedCount:0,size:r.docs.length,sample:{docs:r.docs.map(s=>({path:s.path,data:s.data}))}})}scheduleDelivery(e){this.deliveryQueue.push(e),!this.deliveryScheduled&&(this.deliveryScheduled=!0,queueMicrotask(()=>this.drainDeliveries()))}scheduleTriggeredDelivery(e,r){this.scheduleDelivery(()=>this.triggerScope.run(e,r))}drainDeliveries(){for(this.deliveryScheduled=!1;this.deliveryQueue.length>0;)this.deliveryQueue.shift()()}flushListeners(){this.drainDeliveries()}notifyListenersForPaths(e){if(e.size===0||this.snapshotListeners.size===0)return;const r=this.triggerScope.current(),n=Array.from(this.snapshotListeners.values());for(const s of n)this.scheduleTriggeredDelivery(r,()=>{this.snapshotListeners.has(s.id)&&(s.errored||(s.target.kind==="doc"?this.notifyDocListener(s,e):this.notifyQueryListener(s,e)))})}notifyDocListener(e,r){if(e.target.kind!=="doc"||!r.has(e.target.path))return;const n=this.host.silentReadDoc(e.target.path,e.auth,e.bypassRules);if(!n.allowed){this.markErrored(e,n.error);return}const s=e.currentDocData??null;if(zi(s,n.data)){this.emitSnapshotSuppressed({listenerId:e.id,target:{kind:"doc",path:e.target.path},auth:e.auth,...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}});return}const i=e.target.path,a=tr(i,n.data,Bi);e.currentSnapshot=a,e.currentDocData=n.data;const o=s!==null,c=n.data!==null,u=!o&&c?1:0,f=o&&!c?1:0,l=o&&c?1:0;try{e.callback(a)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"doc",path:i},auth:e.auth,addedCount:u,modifiedCount:l,removedCount:f,size:c?1:0,sample:{docs:[{path:i,data:n.data}]},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),this.scheduleDocMetadataAck(e,i,n.data)}scheduleDocMetadataAck(e,r,n){e.options.includeMetadataChanges&&this.scheduleTriggeredDelivery(this.triggerScope.current(),()=>{if(!this.snapshotListeners.has(e.id)||e.errored)return;const s=tr(r,n,Zt);e.currentSnapshot=s;try{e.callback(s)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"doc",path:r},auth:e.auth,addedCount:0,modifiedCount:0,removedCount:0,size:n!==null?1:0,sample:{docs:[{path:r,data:n}]},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}})})}notifyQueryListener(e,r){if(e.target.kind!=="query"||!ff(r,e.target.collection))return;const n=this.host.silentReadCollection(e.target.collection,e.auth,e.target.constraints,e.bypassRules);if(!n.allowed){this.markErrored(e,n.error);return}const s=e.target.collection,i=e.currentDocs??[],a=rr({path:s},n.docs,{excludesMetadataChanges:!e.options.includeMetadataChanges},i,Bi),o=a.docChanges();if(o.length===0){if(e.options.includeMetadataChanges){e.currentSnapshot=a,e.currentDocs=n.docs;try{e.callback(a)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"query",collection:s},auth:e.auth,addedCount:0,modifiedCount:0,removedCount:0,size:n.docs.length,sample:{docs:n.docs.map(l=>({path:l.path,data:l.data}))},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),this.scheduleQueryMetadataAck(e,s,n.docs);return}this.emitSnapshotSuppressed({listenerId:e.id,target:{kind:"query",collection:s},auth:e.auth,...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}});return}e.currentSnapshot=a,e.currentDocs=n.docs;let c=0,u=0,f=0;for(const l of o)l.type==="added"?c++:l.type==="modified"?u++:l.type==="removed"&&f++;try{e.callback(a)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"query",collection:s},auth:e.auth,addedCount:c,modifiedCount:u,removedCount:f,size:n.docs.length,sample:{docs:n.docs.map(l=>({path:l.path,data:l.data}))},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),this.scheduleQueryMetadataAck(e,s,n.docs)}scheduleQueryMetadataAck(e,r,n){e.options.includeMetadataChanges&&this.scheduleTriggeredDelivery(this.triggerScope.current(),()=>{if(!this.snapshotListeners.has(e.id)||e.errored)return;const s=rr({path:r},n,{excludesMetadataChanges:!1},n,Zt);e.currentSnapshot=s;try{e.callback(s)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"query",collection:r},auth:e.auth,addedCount:0,modifiedCount:0,removedCount:0,size:n.length,sample:{docs:n.map(i=>({path:i.path,data:i.data}))},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}})})}markErrored(e,r){if(e.errored=!0,this.emitSnapshotError(r,e.target,e.id),!!e.errorCallback)try{e.errorCallback(r)}catch{}}reEvaluateAllListeners(){if(this.snapshotListeners.size===0)return;const e=Array.from(this.snapshotListeners.values());for(const r of e)this.snapshotListeners.has(r.id)&&(r.target.kind==="doc"?this.reEvaluateDocListener(r):this.reEvaluateQueryListener(r))}reevaluateLiveListeners(e,r){if(this.snapshotListeners.size===0)return;const n=Array.from(this.snapshotListeners.values());for(const s of n)s.followsCurrentUser&&s.authScope===r&&this.snapshotListeners.has(s.id)&&(s.auth=e,s.target.kind==="doc"?this.reEvaluateDocListener(s):this.reEvaluateQueryListener(s))}reEvaluateDocListener(e){if(e.target.kind!=="doc")return;const r=this.host.silentReadDoc(e.target.path,e.auth,e.bypassRules);if(!r.allowed){if(e.errored)return;this.markErrored(e,r.error);return}if(e.errored){e.errored=!1;const i=tr(e.target.path,r.data);e.currentSnapshot=i,e.currentDocData=r.data;try{e.callback(i)}catch{}return}const n=e.currentDocData??null;if(zi(n,r.data))return;const s=tr(e.target.path,r.data);e.currentSnapshot=s,e.currentDocData=r.data;try{e.callback(s)}catch{}}reEvaluateQueryListener(e){if(e.target.kind!=="query")return;const r=this.host.silentReadCollection(e.target.collection,e.auth,e.target.constraints,e.bypassRules);if(!r.allowed){if(e.errored)return;this.markErrored(e,r.error);return}if(e.errored){e.errored=!1;const a=rr({path:e.target.collection},r.docs,{excludesMetadataChanges:!e.options.includeMetadataChanges});e.currentSnapshot=a,e.currentDocs=r.docs;try{e.callback(a)}catch{}return}const n=e.currentDocs??[],s=rr({path:e.target.collection},r.docs,{excludesMetadataChanges:!e.options.includeMetadataChanges},n);if(s.docChanges().length!==0){e.currentSnapshot=s,e.currentDocs=r.docs;try{e.callback(s)}catch{}}}getSnapshotListenerCount(){return this.snapshotListeners.size}dispose(){this.snapshotListeners.clear(),this.deliveryQueue.length=0,this.deliveryScheduled=!1}}class gf{eventLog;host;constructor(e,r){this.eventLog=e,this.host=r}undo(){const e=this.eventLog.popLastWrite();if(!e)return null;if(e.priorDocs)this.host.state.restorePaths(e.priorDocs);else if(e.snapshot)this.host.state.restore(e.snapshot);else return null;return e}redo(){const e=this.eventLog.popLastUndo();if(!e)return null;const r=e.type==="batch"&&e.operations?e.operations.map(o=>o.path):e.path?[e.path]:[],n=!!e.snapshot,s=n?void 0:this.host.capturePriors(r),i=n?this.host.state.snapshot():void 0;if(e.type==="batch"&&e.operations)for(const o of e.operations)o.allowed&&this.host.applyWrite(o.method,o.path,o.data);else e.allowed&&this.host.applyWrite(e.method,e.path,e.data);const a=this.eventLog.append({...e,snapshot:i,priorDocs:s},!0);return{allowed:e.allowed,debugMessages:["Redo: "+(e.allowed?"applied":"skipped (was denied)")],event:a}}getEvents(){return this.eventLog.getEvents()}getEventCount(){return this.eventLog.size()}}class yf{currentSource;parsedCache=null;constructor(e){this.currentSource=e}get source(){return this.currentSource}set(e){this.currentSource=e}ast(){return this.parsedCache?.source!==this.currentSource&&(this.parsedCache={source:this.currentSource,ast:_s(this.currentSource)}),this.parsedCache.ast}}function he(t,e,r){const n={code:t,message:e};return r!==void 0&&(r.request!==void 0&&(n.request=r.request),r.resource!==void 0&&(n.resource=r.resource),r.remediation!==void 0&&(n.remediation=r.remediation),r.query!==void 0&&(n.query=r.query),r.rule!==void 0&&(n.rule=r.rule)),n}function ln(t,e,r){const n=t.get(e.path),s=e.method==="set"?n!==null?"update":"create":e.method;let i=e.data;if(e.method==="get"||e.method==="list")i=void 0;else if(e.method==="update"&&n&&e.data){const{writes:a,deletedKeys:o}=xt(e.data),c={...n,...a};for(const u of o)delete c[u];i=c}else e.data&&(i=xt(e.data).writes);return{description:`${e.method} ${e.path}`,expectation:"ALLOW",method:s,path:e.path,auth:e.auth?{uid:e.auth.uid,token:e.auth.token}:null,data:i,resource:n??void 0,...r?{requestTime:rf(r)}:{}}}function yo(t,e,r,n,s,i){if(s){const a=n.map(o=>nf(o.description));return{success:!0,data:{passed:a.length,failed:0,unsupported:0,results:a}}}return r.simulate(e.source,n,{getDoc:a=>t.get(a),...i?{batchProjection:i}:{}})}class vf{events;rules;simulator;host;eventLog;constructor(e,r,n,s,i){this.events=e,this.rules=r,this.simulator=n,this.host=s,this.eventLog=i}get state(){return this.host.state}emitRequest(e){this.events.request.hasSubscribers&&this.events.request.emit(un(e))}emitDenial(e){this.events.denial.emit(e)}execute(e){const{method:r,path:n,auth:s,bypassRules:i}=e;let a;i===!0&&(a={admin:!0});const c=_e.fromMillis(Date.now()),u=ln(this.state,e,c),f=Date.now(),l=performance.now(),p=yo(this.state,this.rules,this.simulator,[u],i),y=performance.now()-l;let v=null;if(s!==void 0&&s!==null&&(v={uid:s.uid}),p.success===!0===!1){const d=this.eventLog.append({type:"single",method:r,path:n,auth:v,allowed:!1,debugMessages:[`Simulation error: ${p.error.message}`]}),g={at:f,evalMs:y,method:r,path:n,auth:s,result:"deny",debugMessages:[`Simulation error: ${p.error.message}`],origin:"user"};return a!==void 0&&(g.detail=a),this.emitRequest(g),{allowed:!1,debugMessages:[p.error.message],event:d}}const k=p.data.results[0];if(k.state==="UNSUPPORTED"){const d={at:f,evalMs:y,method:r,path:n,auth:s,result:"unsupported",debugMessages:be(k),origin:"user"};throw a!==void 0&&(d.detail=a),this.emitRequest(d),new yr(vr(r,n,be(k)),r,n,be(k))}const L=k.state==="PASSED";let $;L&&(r==="get"?$=this.state.get(n):$=this.state.list(n));const S=this.eventLog.append({type:"single",method:r,path:n,auth:v,allowed:L,debugMessages:be(k)}),T={allowed:L,debugMessages:be(k),event:S};L&&(T.data=$);const _=Mt(k);if(L===!1){const g={request:{method:r,path:n,auth:s}};if(r==="get"){const E=this.state.get(n),O=E!==null;g.resource={data:E,exists:O}}_!==void 0&&(g.rule=_),T.error=he("permission-denied",`${r} ${n} denied by rules`,g),this.emitDenial(T.error)}let b="deny";L&&(b="allow");const A={at:f,evalMs:y,method:r,path:n,auth:s,result:b,debugMessages:be(k),evaluatedRule:_,origin:"user"};if(r==="get"){const d=this.state.get(n),g=d!==null;A.resourceBefore={data:d,exists:g}}return a!==void 0&&(A.detail=a),this.emitRequest(A),T}}function vo(t){const e=new Map,r=new Set;for(const n of t)e.has(n.name)&&r.add(n.name),e.set(n.name,n);return{functions:e,ambiguousNames:r}}function bo(t,e,r,n=bf){const s=new Set;return{pathInvariant:!kr(t,e,r,n,new Set,new Set,s),requiredFunctions:s}}function kr(t,e,r,n,s,i,a){const o=c=>kr(c,e,r,n,s,i,a);switch(t.type){case"literal":return!1;case"identifier":return!s.has(t.name)&&(e.has(t.name)||t.name==="request");case"memberAccess":return t.object.type==="identifier"&&t.object.name==="request"?!Vi.has(t.property):o(t.object);case"methodCall":return o(t.object)||t.args.some(o);case"bracketAccess":return t.object.type==="identifier"&&t.object.name==="request"?!(t.index.type==="literal"&&typeof t.index.value=="string"&&Vi.has(t.index.value)):o(t.object)||o(t.index);case"sliceAccess":return o(t.object)||o(t.start)||o(t.end);case"binaryOp":return o(t.left)||o(t.right);case"unaryOp":return o(t.operand);case"ternary":return o(t.condition)||o(t.consequent)||o(t.alternate);case"inExpr":return o(t.element)||o(t.collection);case"isExpr":return o(t.value);case"listLiteral":return t.elements.some(o);case"mapLiteral":return t.entries.some(c=>o(c.key)||o(c.value));case"pathLiteral":return t.segments.some(c=>typeof c!="string"&&o(c));case"functionCall":{if(t.args.some(o)||n.has(t.name))return!0;const c=r.get(t.name);if(!c)return!1;if(a.add(c.name),i.has(c.name))return!0;const u=new Set(i).add(c.name),f=new Set(c.parameters);for(const l of c.lets){if(kr(l.value,e,r,n,f,u,a))return!0;f.add(l.name)}return kr(c.body,e,r,n,f,u,a)}}}const Vi=new Set(["auth","method","query","time"]),bf=new Set;function wf(t){if(!t)return null;const e=[...t.functions??[],...t.service.functions??[],...t.service.match.functions],r=new Set,n=t.service.match.children.flatMap(i=>{const a=Sf(i,e,r);return a?[a]:[]});if(n.length===0)return null;const s=i=>i?.filter(a=>r.has(a.name));return{...t,functions:s(t.functions),service:{...t.service,functions:s(t.service.functions),match:{...t.service.match,functions:s(t.service.match.functions)??[],children:n}}}}function Sf(t,e,r){const n=t.path.segments[0];if(t.path.segments.length!==1||n?.type!=="recursive")return null;const s=vo([...e,...t.functions]),i=t.allows.filter(a=>{if(!a.operations.some(c=>c==="list"||c==="read"))return!1;const o=bo(a.condition,new Set([n.name]),s.functions,s.ambiguousNames);if(o.pathInvariant)for(const c of o.requiredFunctions)r.add(c);return o.pathInvariant});return i.length===0?null:{...t,functions:t.functions.filter(a=>r.has(a.name)),allows:i,children:[]}}function _f(t,e,r,n,s){if(t!==null===!1)return{kind:"no-rule"};const a=e.split("/").filter(w=>w.length>0),o=[...t.functions??[],...t.service.functions??[],...t.service.match.functions],c=[];for(const w of t.service.match.children)c.push(...jr(w,a,o));if(c.length===0)return{kind:"no-rule"};const f=[],l=new Set;let p=0;for(const w of c){const R=vo(w.functions),C=R.functions;for(const k of w.block.allows){if(k.operations.some(_=>_==="list"?!0:_==="read")===!1)continue;if(p++,bo(k.condition,new Set(w.candidateVariables),C,R.ambiguousNames).pathInvariant===!0===!1){f.push({reason:"list rule depends on the candidate document path",residual:{missing:[],mismatched:[]},rule:k});continue}const S=td(k.condition,n,C,r?.uid);S.provable===!0?l.add(k):f.push({reason:S.reason,residual:S.residual,rule:k})}}if(p===0)return{kind:"no-rule"};if(l.size===0){const w=f[0];let R="list rule depends on per-document data the query cannot guarantee",C={missing:[],mismatched:[]},k;if(w!==void 0&&(R=w.reason,C=w.residual,w.rule!==void 0)){const T=w.rule,_=ye(T.condition);if(k={verdict:"deny",expression:_},T.loc!==void 0){const A=T.loc;let I="";s!==void 0&&(I=s);const d=Ga(I,A.line,A.col,A.file,_);d!==void 0?(k.line=d.line,k.col=d.col,k.column=d.col,k.file=d.file,k.citation=d.citation,d.expression!==void 0&&(k.expression=d.expression)):(k.line=A.line,k.col=A.col,k.column=A.col,A.file!==void 0?(k.file=A.file,k.citation=`${A.file}:${A.line}:${A.col}`):(k.file="firestore.rules",k.citation=`firestore.rules:${A.line}:${A.col}`))}}const L={kind:"unprovable",reason:R,residual:C};return k!==void 0&&(L.rule=k),L}return{kind:"provable",evaluationAst:Af(t,l),syntheticResource:If(n)}}function Af(t,e){const r=n=>({...n,allows:n.allows.filter(s=>e.has(s)),children:n.children.map(r)});return{...t,service:{...t.service,match:r(t.service.match)}}}function If(t){const e={};for(const r of t.where??[])r.op==="=="&&(e[r.field]=r.value);return e}function xf(t){const e=[];for(const n of t.missing)n.fromAuthUid?e.push(` .where('${n.field}', '==', request.auth.uid) // request.auth.uid is ${JSON.stringify(n.expectedValue)}`):e.push(` .where('${n.field}', '==', ${JSON.stringify(n.expectedValue)})`);for(const n of t.mismatched)e.push(` .where('${n.field}', '==', ${JSON.stringify(n.expectedValue)}) // the query pins ${JSON.stringify(n.actualValue)}, but the rule requires ${JSON.stringify(n.expectedValue)}`);return e.length===0?void 0:`The list rule requires per-document equalities the query does not guarantee. Add the matching where(...) constraint(s) so every returned document satisfies the rule:
1164
+ ${e.join(`
1165
+ `)}`}function kf(t){if(!(t.limit==null&&t.offset==null&&t.orderBy==null))return{...t.limit!=null?{limit:t.limit}:{},...t.offset!=null?{offset:t.offset}:{},...t.orderBy!=null?{orderBy:t.orderBy}:{}}}class Ef{events;rules;simulator;host;constructor(e,r,n,s){this.events=e,this.rules=r,this.simulator=n,this.host=s}authorize(e){const{path:r,auth:n,constraints:s,origin:i,triggeredBy:a}=e,o=kf(s),c={...e.bypassRules?{admin:!0}:{},...o?{query:o}:{},...e.activityQuery!==void 0?{activityQuery:e.activityQuery}:{}},u=Object.keys(c).length>0?c:void 0,f=e.timing?.requestTime??(e.bypassRules?void 0:_e.fromMillis(Date.now())),l=e.timing?.at??Date.now();if(e.bypassRules)return this.emitRequest({at:l,evalMs:0,method:"list",path:r,auth:n,result:"allow",debugMessages:[i==="listener"?"admin lens — rules bypassed":"admin lens — rules bypassed (Studio Gap #2)"],origin:i,...u?{detail:u}:{},...a?{triggeredBy:a}:{}}),{allowed:!0};const p=this.rules.ast(),y=e.collectionGroup?wf(p):p;if(e.collectionGroup&&!y){const b=`list ${r} denied: symbolic collection-group proof is not supported; the query is rejected rather than authorizing from the currently stored rows`;this.emitRequest({at:l,evalMs:0,method:"list",path:r,auth:n,result:"deny",debugMessages:[b],origin:i,...u?{detail:u}:{},...a?{triggeredBy:a}:{}});const A=he("permission-denied",b,{request:{method:"list",path:r,auth:n},query:s});return this.emitUserDenial(i,A),{allowed:!1,error:A}}const v=`${r}/__listPlaceholder__`,w=performance.now(),R=_f(y,v,n,s,this.rules.source);if(R.kind==="unprovable"){const b=`list ${r} denied: the query is statically unprovable for every possible result (rules are not filters), so the whole query is rejected — ${R.reason}`,A=xf(R.residual),I={at:l,evalMs:performance.now()-w,method:"list",path:r,auth:n,result:"deny",debugMessages:[b],origin:i};u!==void 0&&(I.detail=u),a!==void 0&&(I.triggeredBy=a),this.emitRequest(I);const g={request:{method:"list",path:r,auth:n},query:s};A!==void 0&&A!==""&&(g.remediation=A),R.rule!==void 0&&(g.rule=R.rule);const E=he("permission-denied",b,g);return this.emitUserDenial(i,E),{allowed:!1,error:E}}const k=R.kind==="provable"?ri(R.evaluationAst):e.collectionGroup?ri(y):this.rules.source,x=ln(this.host.state,{method:"list",path:v,auth:n},f);this.applyProof(x,R,s);const L=this.simulator.simulate(k,[x],{getDoc:b=>this.host.state.get(b)}),$=performance.now()-w;if(!L.success)return this.emitRequest({at:l,evalMs:$,method:"list",path:r,auth:n,result:"deny",debugMessages:[`Simulation error: ${L.error.message}`],origin:i,...u?{detail:u}:{},...a?{triggeredBy:a}:{}}),{allowed:!1,error:he("permission-denied",`list ${r} simulator error`,{request:{method:"list",path:r,auth:n}})};const S=L.data.results[0],T=be(S);if(S.state==="UNSUPPORTED")throw this.emitRequest({at:l,evalMs:$,method:"list",path:r,auth:n,result:"unsupported",debugMessages:T,origin:i,...u?{detail:u}:{},...a?{triggeredBy:a}:{}}),new yr(vr("list",r,T),"list",r,T);if(S.state!=="PASSED"){const b=Mt(S),A={at:l,evalMs:$,method:"list",path:r,auth:n,result:"deny",debugMessages:T,evaluatedRule:b,origin:i};u!==void 0&&(A.detail=u),a!==void 0&&(A.triggeredBy=a),this.emitRequest(A);const d={request:{method:"list",path:r,auth:n}};b!==void 0&&(d.rule=b);const m=he("permission-denied",`list ${r} denied by rules`,d);return this.emitUserDenial(i,m),{allowed:!1,error:m}}return this.emitRequest({at:l,evalMs:$,method:"list",path:r,auth:n,result:"allow",debugMessages:T,evaluatedRule:Mt(S),origin:i,...u?{detail:u}:{},...a?{triggeredBy:a}:{}}),{allowed:!0}}applyProof(e,r,n){r.kind==="provable"&&(e.resource=r.syntheticResource),(n.limit!=null||n.offset!=null||n.orderBy!=null)&&(e.query={...n.limit!=null?{limit:n.limit}:{},...n.offset!=null?{offset:n.offset}:{},...n.orderBy!=null?{orderBy:n.orderBy}:{}})}emitRequest(e){this.events.request.hasSubscribers&&this.events.request.emit(un(e))}emitUserDenial(e,r){e==="user"&&this.events.denial.emit(r)}}function Tf(t,e,r){if(e<=0)return[];const n=[];for(const s of t)n.length<e?Hi(n,s,r):r(s,n[n.length-1])<0&&(n.pop(),Hi(n,s,r));return n}function Hi(t,e,r){let n=0,s=t.length;for(;n<s;){const i=n+s>>1;r(e,t[i])<0?s=i:n=i+1}t.splice(n,0,e)}function Of(t){return typeof t.seconds=="number"&&(typeof t.nanos=="number"||typeof t.nanoseconds=="number")}function Cf(t){return typeof t.latitude=="number"&&typeof t.longitude=="number"}function Rf(t){return t.data instanceof Uint8Array}function Nf(t){return typeof t.path=="string"}function nn(t){if(t==null)return 0;const e=typeof t;if(e==="boolean")return 1;if(e==="number"||e==="bigint")return 2;if(e==="string")return 4;if(Array.isArray(t))return 8;if(e==="object"){const r=t;return Of(r)?3:Rf(r)?5:Cf(r)?7:Nf(r)?6:9}return 9}function Wi(t){const e=typeof t.nanos=="number"?t.nanos:t.nanoseconds??0;return[t.seconds,e]}function Lf(t,e){const r=Number.isNaN(t),n=Number.isNaN(e);return r&&n?0:r?-1:n?1:t<e?-1:t>e?1:0}function Gi(t,e){return t<e?-1:t>e?1:0}function vt(t,e){const r=nn(t),n=nn(e);if(r!==n)return r<n?-1:1;switch(r){case 0:return 0;case 1:return t===e?0:t?1:-1;case 2:return Lf(Number(t),Number(e));case 3:{const[s,i]=Wi(t),[a,o]=Wi(e);return s!==a?s<a?-1:1:i<o?-1:i>o?1:0}case 4:return Gi(t,e);case 5:{const s=t.data,i=e.data,a=Math.min(s.length,i.length);for(let o=0;o<a;o++)if(s[o]!==i[o])return s[o]<i[o]?-1:1;return s.length<i.length?-1:s.length>i.length?1:0}case 6:return Gi(t.path,e.path);case 7:{const s=t,i=e;return s.latitude!==i.latitude?s.latitude<i.latitude?-1:1:s.longitude<i.longitude?-1:s.longitude>i.longitude?1:0}case 8:{const s=t,i=e,a=Math.min(s.length,i.length);for(let o=0;o<a;o++){const c=vt(s[o],i[o]);if(c!==0)return c}return s.length<i.length?-1:s.length>i.length?1:0}case 9:{const s=t,i=e,a=Object.keys(s).sort(),o=Object.keys(i).sort(),c=Math.min(a.length,o.length);for(let u=0;u<c;u++){if(a[u]!==o[u])return a[u]<o[u]?-1:1;const f=vt(s[a[u]],i[o[u]]);if(f!==0)return f}return a.length<o.length?-1:a.length>o.length?1:0}default:return 0}}function Mf(t){const e=t.kind;if(e==="collection"){const r=t.path;return Object.freeze({kind:e,path:r})}if(e==="collection-group"){const r=t.collectionId;return Object.freeze({kind:e,collectionId:r})}throw new tn({code:"invalid-argument",message:`Unknown query scope kind: ${String(e)}`})}function Ki(t){const e=u=>{const f=u.kind;if(f==="where"){const p=u.field,y=u.op,v=u.value;return Object.freeze({kind:f,field:p,op:y,value:v})}if(f!=="and"&&f!=="or")throw new tn({code:"invalid-argument",message:`Unknown query filter kind: ${String(f)}`});const l=u.filters;return Object.freeze({kind:f,filters:Object.freeze(Array.from(l,e))})},r=u=>{if(u===void 0)return;const f=u.values,l=u.inclusive,p=u.fromSnapshot;return Object.freeze({values:Object.freeze(Array.from(f)),inclusive:l,fromSnapshot:p})},n=t.filters,s=t.orders,i=t.limitCount,a=t.limitFromEnd,o=t.start,c=t.end;return Object.freeze({filters:Object.freeze(Array.from(n,e)),orders:Object.freeze(Array.from(s,u=>{const f=u.field,l=u.direction;return Object.freeze({field:f,direction:l})})),limitCount:i,limitFromEnd:a,start:r(o),end:r(c)})}function Zi(t){const e=[],r=n=>{if(n.kind==="where"){if(n.field===mt)return;const s=n.value;(s===null||typeof s=="string"||typeof s=="number"||typeof s=="boolean")&&e.push(Object.freeze({field:n.field,op:n.op,value:s}));return}n.kind==="and"&&n.filters.forEach(r)};return t.filters.forEach(r),Object.freeze({where:Object.freeze(e),limit:t.limitCount??null,offset:null,orderBy:t.orders.length>0?t.orders[0].field:null})}function Df(t,e){if(e.kind==="collection")return t.scan(e.path,{directOnly:!0});const r=[];for(const[n,s]of Object.entries(t.snapshot())){const i=n.split("/").filter(a=>a.length>0);i.length>0&&i.length%2===0&&i[i.length-2]===e.collectionId&&r.push({path:n,data:s})}return r}const mt="__name__",Ff=new Set(["<","<=",">",">=","!=","not-in"]);function os(t,e){return e===mt?{path:t.path}:t.data[e]}function Ms(t){return t.kind==="where"?Ff.has(t.op)?[t.field]:[]:t.filters.flatMap(Ms)}function jf(t){return Ms(t).length>0}function dn(t,e){return nn(t)===nn(e)}function qf(t,e){return dn(t,e)&&vt(t,e)<0}function Pf(t,e){return dn(t,e)&&vt(t,e)<=0}function $f(t,e){return dn(t,e)&&vt(t,e)>0}function Uf(t,e){return dn(t,e)&&vt(t,e)>=0}function Bf(t,e,r){const n=t!==void 0;switch(e){case"==":return n&&Ye(t,r);case"!=":return n&&t!==null&&!Ye(t,r);case"<":return n&&qf(t,r);case"<=":return n&&Pf(t,r);case">":return n&&$f(t,r);case">=":return n&&Uf(t,r);case"in":return n&&Array.isArray(r)&&r.some(s=>Ye(t,s));case"not-in":return!Array.isArray(r)||r.some(s=>s===null)?!1:n&&t!==null&&!r.some(s=>Ye(t,s));case"array-contains":return Array.isArray(t)&&t.some(s=>Ye(s,r));case"array-contains-any":return Array.isArray(t)&&Array.isArray(r)&&r.some(s=>t.some(i=>Ye(i,s)))}}function zf(t,e){if(e===mt){const r=t.path.split("/");return r[r.length-1]??t.path}return t.data[e]}function wo(t){if(Array.isArray(t))return t.map(wo);if(t&&typeof t=="object"){const e=t;if(typeof e.id=="string")return e.id;if(typeof e.path=="string"){const r=e.path.split("/");return r[r.length-1]??e.path}}return t}function cs(t,e){if(e.kind==="where"){const r=zf(t,e.field),n=e.field===mt?wo(e.value):e.value;return Bf(r,e.op,n)}return e.kind==="and"?e.filters.every(r=>cs(t,r)):e.filters.some(r=>cs(t,r))}function Vf(t,e){return t.filter(r=>e.every(n=>cs(r,n)))}function Ji(t,e,r){for(let n=0;n<e.length;n++){const s=vt(os(t,r[n].field),e[n]);if(s!==0)return r[n].direction==="desc"?-s:s}return 0}function Hf(t,e,r,n){return t.filter(s=>{if(r){const i=Ji(s,r.values,e);if(r.inclusive?i<0:i<=0)return!1}if(n){const i=Ji(s,n.values,e);if(n.inclusive?i>0:i>=0)return!1}return!0})}function So(t,e){return t.filter(r=>e.every(n=>n.field===mt||r.data[n.field]!==void 0))}function _o(t){return(e,r)=>{for(const n of t){const s=vt(os(e,n.field),os(r,n.field));if(s!==0)return n.direction==="desc"?-s:s}return 0}}function Wf(t,e){return e.length===0?t:So(t,e).sort(_o(e))}function Gf(t){const e=[...t.orders],r=new Set(e.map(s=>s.field)),n=t.orders.length>0?t.orders[t.orders.length-1].direction:"asc";for(const s of t.filters)for(const i of Ms(s))i!==mt&&!r.has(i)&&(r.add(i),e.push({field:i,direction:n}));return r.has(mt)||e.push({field:mt,direction:n}),e}function kn(t,e){let r=Vf(t,[...e.filters]);const n=Gf(e),s=e.orders.length>0||e.start!==void 0||e.end!==void 0||e.filters.some(jf);if(s&&e.limitCount!==void 0&&!e.limitFromEnd&&e.start===void 0&&e.end===void 0)return Tf(So(r,n),e.limitCount,_o(n));if(s&&(r=Wf(r,n)),e.start||e.end){for(const i of[e.start,e.end])if(i&&!i.fromSnapshot&&i.values.length>e.orders.length)throw new tn({code:"invalid-argument",message:"Too many arguments provided to a cursor (startAt / startAfter / endAt / endBefore). The number of cursor values must be less than or equal to the number of orderBy() clauses."});r=Hf(r,n,e.start,e.end)}if(e.limitCount!==void 0)if(e.limitFromEnd){if(e.orders.length===0)throw new tn({code:"unimplemented",message:"limitToLast() queries require at least one orderBy clause."});r=r.slice(-e.limitCount)}else r=r.slice(0,e.limitCount);return r}class Kf{events;triggerScope;rules;simulator;host;operationReader;listAuthorizer;constructor(e,r,n,s,i,a){this.events=e,this.triggerScope=r,this.rules=n,this.simulator=s,this.host=i,this.operationReader=new vf(e,n,s,i,a),this.listAuthorizer=new Ef(e,n,s,i)}get state(){return this.host.state}emitRequest(e){this.events.request.hasSubscribers&&this.events.request.emit(un(e))}execute(e){return this.operationReader.execute(e)}silentReadDoc(e,r,n=!1){if(n){const x=this.state.get(e);return this.emitRequest({at:Date.now(),evalMs:0,method:"get",path:e,auth:r,result:"allow",debugMessages:["admin lens — rules bypassed"],origin:"listener",resourceBefore:{data:x,exists:x!==null},detail:{admin:!0},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),{allowed:!0,data:x}}const s=_e.fromMillis(Date.now()),i=ln(this.state,{method:"get",path:e,auth:r},s),a=Date.now(),o=performance.now(),c=this.simulator.simulate(this.rules.source,[i],{getDoc:x=>this.state.get(x)}),u=performance.now()-o;if(!c.success)return this.emitRequest({at:a,evalMs:u,method:"get",path:e,auth:r,result:"deny",debugMessages:[`Simulation error: ${c.error.message}`],origin:"listener",...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),{allowed:!1,error:he("permission-denied",`get ${e} simulator error`,{request:{method:"get",path:e,auth:r}})};const f=c.data.results[0];if(f.state==="UNSUPPORTED")throw this.emitRequest({at:a,evalMs:u,method:"get",path:e,auth:r,result:"unsupported",debugMessages:be(f),origin:"listener",...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),new yr(vr("get",e,be(f)),"get",e,be(f));const l=f.state==="PASSED",p=this.state.get(e),y=Mt(f);let v="deny";l&&(v="allow");const w=p!==null,R={at:a,evalMs:u,method:"get",path:e,auth:r,result:v,debugMessages:be(f),evaluatedRule:y,origin:"listener",resourceBefore:{data:p,exists:w}},C=this.triggerScope.current();if(C!==void 0&&(R.triggeredBy=C),this.emitRequest(R),l===!1){const x={request:{method:"get",path:e,auth:r},resource:{data:p,exists:w}};return y!==void 0&&(x.rule=y),{allowed:!1,error:he("permission-denied",`get ${e} denied by rules`,x)}}return{allowed:!0,data:p}}silentReadCollection(e,r,n,s=!1){if(typeof n=="function")return{allowed:!1,error:he("invalid-argument","Callable query constraints are no longer executable; pass an immutable QueryConstraintPlan.")};const i=n?Ki(n.execution):void 0,a=i?Zi(i):{},o={requestTime:_e.fromMillis(Date.now()),at:Date.now()},c=this.triggerScope.current();if(s){const p=this.state.list(e).filter(w=>!w.phantom).map(w=>({path:w.path,data:w.data})),y=i?kn(p,i):p,v=this.listAuthorizer.authorize({path:e,auth:r,constraints:a,bypassRules:s,...n?.activityQuery?{activityQuery:n.activityQuery}:{},origin:"listener",...c?{triggeredBy:c}:{},timing:o});return v.allowed?{allowed:!0,docs:y}:v}const u=this.listAuthorizer.authorize({path:e,auth:r,constraints:a,...n?.activityQuery?{activityQuery:n.activityQuery}:{},origin:"listener",...c?{triggeredBy:c}:{},timing:o});if(!u.allowed)return u;const f=this.state.list(e).filter(p=>!p.phantom).map(p=>({path:p.path,data:p.data}));return{allowed:!0,docs:i?kn(f,i):f}}runQuery(e){const r=Mf(e.scope),n=Ki(e.execution),s=e.auth,i=e.bypassRules,a=e.activityQuery,o=Df(this.state,r),c=r.kind==="collection"?r.path:r.collectionId,u=Zi(n),f=this.listAuthorizer.authorize({path:c,collectionGroup:r.kind==="collection-group",auth:s,constraints:u,bypassRules:i,...a!==void 0?{activityQuery:a}:{},origin:"user"});return f.allowed?{allowed:!0,docs:kn(o,n)}:f}}const Yi="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",Qi=20;function Zf(){const t=new Uint8Array(Qi);globalThis.crypto.getRandomValues(t);let e="";for(let r=0;r<Qi;r++)e+=Yi[t[r]%Yi.length];return e}function Ao(t,e=""){const r=[],n=new WeakSet;return s(t,e),r;function s(i,a){if(i==null||typeof i!="object"||n.has(i)||(n.add(i),jh(i)!==void 0))return;if(Array.isArray(i)){i.forEach((u,f)=>s(u,`${a}[${f}]`));return}const o=i,c=Jf(o);if(c){r.push({field:a,kind:c});return}for(const[u,f]of Object.entries(o)){const l=a?`${a}.${u}`:u;s(f,l)}}}function Jf(t){const e=t.__type;return e==="serverTimestamp"?"serverTimestamp":e==="increment"?"increment":e==="arrayUnion"?"arrayUnion":e==="arrayRemove"?"arrayRemove":e==="deleteField"?"delete":null}Zh();class Yf{host;rules;simulator;eventLog;events;triggerScope;constructor(e,r,n,s,i,a){this.host=e,this.rules=r,this.simulator=n,this.eventLog=s,this.events=i,this.triggerScope=a}get state(){return this.host.state}emitDenial(e){this.events.denial.emit(e)}emitRequest(e){this.events.request.hasSubscribers&&this.events.request.emit(un(e))}emitWrite(e){this.events.write.hasSubscribers&&this.events.write.emit({kind:"write",id:lr().replace(/^req-/,"wr-"),at:Date.now(),method:e.method,path:e.path,auth:e.auth?{uid:e.auth.uid,...e.auth.token?{token:e.auth.token}:{}}:null,...e.data!==void 0?{data:e.data}:{},priorState:e.priorState,nextState:e.nextState,...e.groupId!==void 0?{groupId:e.groupId}:{},...e.groupKind!==void 0?{groupKind:e.groupKind}:{},...e.sentinels&&e.sentinels.length>0?{sentinels:e.sentinels}:{},...e.autoId!==void 0?{autoId:e.autoId}:{},requestTime:{seconds:e.requestTime.seconds,nanoseconds:e.requestTime.nanos},...e.detail!==void 0?{detail:e.detail}:{},...e.provenance??{}})}capturePriors(e){const r={};for(const n of e){const s=this.state.get(n);r[n]=s?{...s}:null}return r}runSimulate(e,r,n){return yo(this.state,this.rules,this.simulator,e,r,n)}isReadOnlyMethod(e){return e==="get"||e==="list"}resolvePriorDocumentState(e,r,n){return r.has(e)?r.get(e)??null:n.exists(e)?n.get(e)??null:null}computeProjectedUpdate(e,r){return e===null?null:ss(e,r??{})}computeProjectedOverwrite(e,r){return ss(e??{},r??{})}buildBatchProjection(e){const r=new Map;for(const n of e){if(this.isReadOnlyMethod(n.method))continue;if(n.method==="delete"){r.set(n.path,null);continue}const s=this.resolvePriorDocumentState(n.path,r,this.state);if(n.method==="update"){const i=this.computeProjectedUpdate(s,n.data);r.set(n.path,i)}else{const i=this.computeProjectedOverwrite(s,n.data);r.set(n.path,i)}}return r}buildTestCase(e,r){return ln(this.state,e,r)}notify(e,r,n){this.triggerScope.run({method:e,path:r},()=>this.host.notifyListenersForPaths(n))}}class Io{runtime;constructor(e){this.runtime=e}prepare(e,r){const n=_e.fromMillis(Date.now()),s=[];for(let i=0;i<e.length;i++){const a=e[i];try{const o=a.data?Ze({...a.data},{path:a.path,method:a.method,prior:this.runtime.state.get(a.path),serverTime:n}):a.data;s.push({method:a.method,path:a.path,data:o})}catch(o){const c=o.message,u=he("invalid-argument",c),f=r.snapshot[a.path]??null,l={at:Date.now(),evalMs:0,method:a.ruleMethod,path:a.path,auth:r.auth,result:"deny",debugMessages:[`FieldValue resolve error: ${c}`],...this.includesRequestData(r,a)?{resourceData:a.preData}:{},resourceBefore:{data:f,exists:f!==null},origin:r.origin,groupId:r.groupId,...r.bypassRules?{detail:{admin:!0}}:{},...r.provenance?{provenance:r.provenance}:{}};return{index:i,input:a,message:c,error:u,request:l}}}return{context:r,inputs:e,resolvedOps:s,serverTime:n}}evaluateAndApply(e){const{context:r,inputs:n,resolvedOps:s,serverTime:i}=e,a=s.map((l,p)=>{const y=n[p];return this.runtime.buildTestCase({method:y.ruleMethod,path:l.path,auth:r.auth,data:l.data},i)}),o=this.runtime.buildBatchProjection(a),c=[];let u=!0;for(let l=0;l<s.length;l++){s[l];const p=n[l],y=r.snapshot[p.path]??null,v=Date.now(),w=performance.now(),R=this.runtime.runSimulate([a[l]],r.bypassRules,o),C=performance.now()-w;if(!R.success){const T=he("invalid-argument",R.error.message);c.push({path:p.path,method:p.ruleMethod,allowed:!1,debugMessages:[R.error.message],error:T,request:this.request(e,p,y,v,C,"deny",[`Simulation error: ${R.error.message}`])}),u=!1;continue}const k=R.data.results[0],x=be(k);if(k.state==="UNSUPPORTED")throw this.runtime.emitRequest(this.request(e,p,y,v,C,"unsupported",x)),new yr(vr(p.ruleMethod,p.path,x),p.ruleMethod,p.path,x);const L=k.state==="PASSED";let $="deny";L&&($="allow");const S={path:p.path,method:p.ruleMethod,allowed:L,debugMessages:x,request:this.request(e,p,y,v,C,$,x)};if(L===!1){const T=Mt(k),_=y!==null,b={request:{method:p.ruleMethod,path:p.path,auth:r.auth},resource:{data:y,exists:_}};this.includesRequestData(r,p)&&(b.request.resourceData=p.preData),T!==void 0&&(b.rule=T),S.error=he("permission-denied",`${p.ruleMethod} ${p.path} denied by rules`,b),this.runtime.emitDenial(S.error),u=!1}c.push(S)}let f=null;if(u){const l=this.runtime.state.applyBatch(s);if(!l.success){u=!1;const p=l.errors?.[0];if(p!==void 0){const y=s[p.index];f=he(y?.method==="create"?"already-exists":"not-found",p.error);const v=c[p.index];v&&(v.allowed=!1,v.error=f)}}}return{...e,outcomes:c,allowed:u,structuralError:f}}emitAndNotify(e){const{context:r,inputs:n,outcomes:s,serverTime:i}=e;for(let a=0;a<s.length;a++){const o=s[a],c=n[a],u=e.allowed&&o.allowed,f=r.snapshot[c.path]??null;if(o.request.resourceAfter=u?c.ruleMethod==="delete"?{data:null,exists:!1}:{data:this.runtime.state.get(c.path),exists:this.runtime.state.get(c.path)!==null}:{data:f,exists:f!==null},this.runtime.emitRequest(o.request),u){const l=c.preData?Ao(c.preData):void 0;this.runtime.emitWrite({method:c.ruleMethod,path:c.path,auth:r.auth,...c.ruleMethod!=="delete"&&c.preData?{data:c.preData}:{},priorState:f,nextState:c.ruleMethod==="delete"?null:this.runtime.state.get(c.path),groupId:r.groupId,groupKind:r.origin,...l&&l.length>0?{sentinels:l}:{},requestTime:i,...r.bypassRules?{detail:{admin:!0}}:{},...r.provenance?{provenance:r.provenance}:{}})}}e.allowed&&this.runtime.notify(r.origin,n[0]?.path??"",new Set(n.map(a=>a.path)))}request(e,r,n,s,i,a,o){const{context:c}=e;return{at:s,evalMs:i,method:r.ruleMethod,path:r.path,auth:c.auth,result:a,debugMessages:o,...this.includesRequestData(c,r)?{resourceData:r.preData}:{},resourceBefore:{data:n,exists:n!==null},origin:c.origin,groupId:c.groupId,...c.bypassRules?{detail:{admin:!0}}:{},...c.provenance?{provenance:c.provenance}:{}}}includesRequestData(e,r){return r.preData!==void 0&&(e.origin==="batch"||r.ruleMethod!=="delete")}}class Qf{runtime;pipeline;constructor(e){this.runtime=e,this.pipeline=new Io(e)}batch(e,r,n){const s=this.runtime.capturePriors(e.map(p=>p.path)),i=`batch-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,a=e.map(p=>({...p,ruleMethod:p.method,preData:p.data})),o=this.pipeline.prepare(a,{origin:"batch",groupId:i,auth:r,bypassRules:n,snapshot:s});if(!("resolvedOps"in o)){const p=this.runtime.eventLog.append({type:"batch",method:"batch",path:"",auth:r?{uid:r.uid}:null,allowed:!1,operations:e.map(y=>({method:y.method,path:y.path,data:y.data,allowed:!1})),debugMessages:[`FieldValue resolve error on '${o.input.path}': ${o.message}`]});return this.runtime.emitRequest(o.request),{allowed:!1,results:e.map(y=>({path:y.path,allowed:!1,debugMessages:[o.message],...y.path===o.input.path?{error:o.error}:{}})),event:p,error:o.error}}const c=this.pipeline.evaluateAndApply(o),u=c.outcomes.map(p=>({path:p.path,allowed:p.allowed,debugMessages:p.debugMessages,...p.error?{error:p.error}:{}})),f=this.runtime.eventLog.append({type:"batch",method:"batch",path:"",auth:r?{uid:r.uid}:null,allowed:c.allowed,priorDocs:c.allowed?s:void 0,operations:c.resolvedOps.map((p,y)=>({method:p.method,path:p.path,data:p.data,allowed:u[y]?.allowed??!1})),debugMessages:c.allowed?["Batch committed"]:["Batch rolled back — one or more operations denied"]});this.pipeline.emitAndNotify(c);let l;return c.allowed||(l=c.structuralError??u.find(p=>p.error)?.error??he("permission-denied","Batch denied")),{allowed:c.allowed,results:u,event:f,...l?{error:l}:{}}}}const Xi="Firestore transactions require all reads to be executed before all writes.";class Xf extends Error{simError;constructor(){super(Xi),this.name="ReadAfterWriteError",this.simError=he("failed-precondition",Xi)}}class ea extends Error{constructor(){super("A document read in the transaction changed before commit."),this.name="RetryableTransactionConflictError"}}class ep extends Error{simError=he("failed-precondition","Transaction failed all retries.");constructor(){super("Transaction failed all retries."),this.name="TransactionAttemptsExhaustedError"}}class tp{versionReader;reader;reads=[];writes=[];readVersions=new Map;writeStarted=!1;constructor(e,r=()=>0){this.versionReader=r,this.reader=e}get(e){this.assertReadsAllowed();const r=this.reader(e);this.readVersions.has(e)||this.readVersions.set(e,this.versionReader(e)),this.reads.push({path:e,data:r});const n=r===null?null:structuredClone(r);return{path:e,exists:n!==null,data:()=>n===null?void 0:n}}getAll(...e){return this.assertReadsAllowed(),e.map(r=>this.get(r))}set(e,r){this.queue({method:"set",path:e,data:r})}create(e,r){this.queue({method:"create",path:e,data:r})}update(e,r){this.queue({method:"update",path:e,data:r})}delete(e){this.queue({method:"delete",path:e})}consume(){return{reads:this.reads,writes:this.writes,readVersions:this.readVersions}}hadWrites(){return this.writeStarted}queue(e){this.writeStarted=!0,this.writes.push(e)}assertReadsAllowed(){if(this.writeStarted)throw new Xf}}class rp extends Error{path;secondMethod;constructor(e,r){super(`Queued ${r} on '${e}' after a delete in the same transaction. This combination is unprobed against production Firestore; refusing to guess. Either drop the delete or split into two transactions.`),this.name="AmbiguousPostDeleteWriteError",this.path=e,this.secondMethod=r}}function np(t){const e=new Map;for(const r of t){const n=e.get(r.path);if(n===void 0){e.set(r.path,sp(r));continue}if(n.method==="delete")throw new rp(r.path,r.method);e.set(r.path,ip(n,r))}return Array.from(e.values())}function sp(t){if(t.method==="delete")return{method:"delete",path:t.path};if(t.data===void 0)throw new Error(`internal: queued ${t.method} on ${t.path} has no data — Transaction class invariant violated`);return{method:t.method,path:t.path,data:t.data}}function ip(t,e){switch(e.method){case"delete":return{method:"delete",path:e.path};case"set":{const r=En(e);return{method:"set",path:e.path,data:r}}case"update":{const r=En(e),s={...t.data??{},...r};return{method:t.method,path:e.path,data:s}}case"create":{const r=En(e),s={...t.data??{},...r};return{method:"create",path:e.path,data:s}}}}function En(t){if(t.data===void 0)throw new Error(`internal: queued ${t.method} on ${t.path} has no data — Transaction class invariant violated`);return t.data}class ap{runtime;pipeline;constructor(e){this.runtime=e,this.pipeline=new Io(e)}transaction(e,r){return this.runAttempt(e,r,1)}runAttempt(e,r,n){const s=this.runtime.state.snapshot(),i=this.runtime.state.currentVersion(),a=new Map(Object.keys(s).map(f=>[f,this.runtime.state.version(f)])),o=f=>s[f]??null,c=new tp(o,f=>{const l=a.get(f);if(l!==void 0)return l;const p=this.runtime.state.version(f);return p<=i?p:-1});let u;try{u=e(c)}catch(f){throw this.logAbortedTransaction(c,r.auth,f),f}if(u!==null&&typeof u?.then=="function")return u.then(f=>{try{return this.commitTransaction(c,s,r,f)}catch(l){return this.retryOrThrow(l,e,r,n)}},f=>{throw this.logAbortedTransaction(c,r.auth,f),f});try{return this.commitTransaction(c,s,r,u)}catch(f){return this.retryOrThrow(f,e,r,n)}}retryOrThrow(e,r,n,s){if(!(e instanceof ea))throw e;const i=n.maxAttempts??5;if(s>=i)throw new ep;return this.runAttempt(r,n,s+1)}commitTransaction(e,r,n,s){const{reads:i,writes:a,readVersions:o}=e.consume();for(const[x,L]of o)if(this.runtime.state.version(x)!==L)throw new ea;const c=n.auth;if(a.length===0){const x=this.runtime.eventLog.append({type:"transaction",method:"transaction",path:"",auth:c?{uid:c.uid}:null,allowed:!0,reads:i.map(L=>({path:L.path,data:L.data})),operations:[],snapshot:r,debugMessages:["Transaction committed (read-only — no writes queued)"]});return{allowed:!0,reads:[...i],writes:[],returnValue:s,event:x}}let u;try{u=np(a)}catch(x){const L=x;throw this.runtime.eventLog.append({type:"transaction",method:"transaction",path:"",auth:c?{uid:c.uid}:null,allowed:!1,aborted:!0,reads:i.map($=>({path:$.path,data:$.data})),error:{name:L.name,message:L.message,code:"failed-precondition"},debugMessages:[`Transaction aborted at merge: ${L.message}`]}),x}const f=Object.fromEntries(u.map(x=>[x.path,r[x.path]??null])),l=u.map(x=>{const L=x.method==="set"?this.runtime.state.get(x.path)!==null?"update":"create":x.method;return{...x,ruleMethod:L,preData:x.data}}),p=`tx-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,y=this.pipeline.prepare(l,{origin:"transaction",groupId:p,auth:c,bypassRules:n.bypassRules,provenance:n.provenance,snapshot:f});if(!("resolvedOps"in y)){const x=this.runtime.eventLog.append({type:"transaction",method:"transaction",path:"",auth:c?{uid:c.uid}:null,allowed:!1,reads:i.map(L=>({path:L.path,data:L.data})),operations:u.map(L=>({method:L.method,path:L.path,data:L.data,allowed:!1})),debugMessages:[`FieldValue resolve error on '${y.input.path}': ${y.message}`]});return this.runtime.emitRequest(y.request),{allowed:!1,reads:[...i],writes:l.map((L,$)=>({path:L.path,method:L.ruleMethod,allowed:!1,debugMessages:$===y.index?[y.message]:[],...$===y.index?{error:y.error}:{}})),returnValue:s,event:x,error:y.error}}const v=this.pipeline.evaluateAndApply(y),w=v.outcomes.map(x=>({path:x.path,method:x.method,allowed:x.allowed,debugMessages:x.debugMessages,...x.error?{error:x.error}:{}})),R=this.runtime.eventLog.append({type:"transaction",method:"transaction",path:"",auth:c?{uid:c.uid}:null,allowed:v.allowed,reads:i.map(x=>({path:x.path,data:x.data})),operations:v.resolvedOps.map((x,L)=>({method:x.method,path:x.path,data:x.data,allowed:w[L]?.allowed??!1})),snapshot:v.allowed?r:void 0,debugMessages:v.allowed?["Transaction committed"]:["Transaction rolled back — one or more operations denied"]});this.pipeline.emitAndNotify(v);let C;v.allowed||(C=v.structuralError??w.find(x=>x.error)?.error??he("permission-denied","Transaction denied"));const k={allowed:v.allowed,reads:[...i],writes:w,returnValue:s,event:R,...C?{error:C}:{}};return n.readOnly&&e.hadWrites()&&(k.readOnlyViolation=!0),k}logAbortedTransaction(e,r,n){const s=n,{reads:i}=e.consume();this.runtime.eventLog.append({type:"transaction",method:"transaction",path:"",auth:r?{uid:r.uid}:null,allowed:!1,aborted:!0,reads:i.map(a=>({path:a.path,data:a.data})),error:{name:n.name,message:n.message,...s.code!==void 0?{code:String(s.code)}:{}},debugMessages:[`Transaction aborted: ${n.message}`]})}}class op{runtime;batches;transactions;constructor(e,r,n,s,i,a){this.runtime=new Yf(e,r,n,s,i,a),this.batches=new Qf(this.runtime),this.transactions=new ap(this.runtime)}capturePriors(e){return this.runtime.capturePriors(e)}applyWrite(e,r,n,s){if(s!==void 0&&s!==!1&&(e==="create"||e==="update")){const i=s===!0?void 0:s.mergeFields;return this.runtime.state.setMerge(r,n??{},i),null}switch(e){case"create":{const i=this.runtime.state.create(r,n??{});return i.success?null:he("already-exists",i.error??`Document '${r}' already exists`)}case"update":{const i=this.runtime.state.update(r,n??{});return i.success?null:he("not-found",i.error??`Document '${r}' does not exist`)}case"set":return this.runtime.state.set(r,n??{}),null;case"delete":return this.runtime.state.delete(r),null;default:return null}}execute(e){const{method:r,path:n,auth:s,data:i,autoId:a,requestTime:o,merge:c,bypassRules:u}=e,f=u?{admin:!0}:void 0,l=this.runtime.capturePriors([n]),p=o??_e.fromMillis(Date.now());let y;try{y=i&&Ze({...i},{path:n,method:r,prior:this.runtime.state.get(n),serverTime:p}),r==="update"&&y&&Yh(y)}catch(A){const I=A.message,h=this.runtime.eventLog.append({type:"single",method:r,path:n,auth:s?{uid:s.uid}:null,data:i,allowed:!1,priorDocs:l,debugMessages:[`FieldValue resolve error: ${I}`]});return this.runtime.emitRequest({at:Date.now(),evalMs:0,method:r,path:n,auth:s,result:"deny",debugMessages:[`FieldValue resolve error: ${I}`],...y?{resourceData:y}:i?{resourceData:i}:{},resourceBefore:{data:l[n]??null,exists:(l[n]??null)!==null},origin:"user",...f?{detail:f}:{}}),{allowed:!1,debugMessages:[I],event:h,error:he("invalid-argument",I)}}const v=this.runtime.buildTestCase({...e,data:y},p),w=Date.now(),R=performance.now(),C=this.runtime.runSimulate([v],u),k=performance.now()-R;if(!C.success){const A=this.runtime.eventLog.append({type:"single",method:r,path:n,auth:s?{uid:s.uid}:null,data:y,allowed:!1,priorDocs:l,debugMessages:[`Simulation error: ${C.error.message}`]});return this.runtime.emitRequest({at:w,evalMs:k,method:r,path:n,auth:s,result:"deny",debugMessages:[`Simulation error: ${C.error.message}`],...i?{resourceData:i}:{},resourceBefore:{data:l[n]??null,exists:(l[n]??null)!==null},origin:"user",...f?{detail:f}:{}}),{allowed:!1,debugMessages:[C.error.message],event:A,error:he("invalid-argument",C.error.message)}}const x=C.data.results[0];if(x.state==="UNSUPPORTED")throw this.runtime.emitRequest({at:w,evalMs:k,method:r,path:n,auth:s,result:"unsupported",debugMessages:be(x),...i?{resourceData:i}:{},resourceBefore:{data:l[n]??null,exists:(l[n]??null)!==null},origin:"user",...f?{detail:f}:{}}),new yr(vr(r,n,be(x)),r,n,be(x));let L=x.state==="PASSED",$=null;L&&($=this.applyWrite(r,n,y,c),$&&(L=!1));const S=this.runtime.eventLog.append({type:"single",method:r,path:n,auth:s?{uid:s.uid}:null,data:y,allowed:L,priorDocs:L?l:void 0,debugMessages:be(x)}),T={allowed:L,debugMessages:be(x),event:S};if(L===!1){let A=!1;if($!==void 0&&$!==null&&(A=!0),A)T.error=$;else{let h=null;const d=l[n];d!==void 0&&(h=d);let m=r;r==="set"&&(h!==null?m="update":m="create");const E=Mt(x),D={request:{method:m,path:n,auth:s},resource:{data:h,exists:h!==null}};i!==void 0&&(D.request.resourceData=i),E!==void 0&&(D.rule=E),T.error=he("permission-denied",`${r} ${n} denied by rules`,D),this.runtime.emitDenial(T.error)}}const _=l[n]??null,b=L?this.runtime.state.get(n):_;if(this.runtime.emitRequest({at:w,evalMs:k,method:r,path:n,auth:s,result:L?"allow":"deny",debugMessages:be(x),evaluatedRule:Mt(x),...i?{resourceData:i}:{},resourceBefore:{data:_,exists:_!==null},...r!=="delete"?{resourceAfter:{data:b,exists:b!==null}}:{resourceAfter:{data:null,exists:!1}},origin:"user",...f?{detail:f}:{}}),L){const A=i?Ao(i):void 0,I=a&&r==="create"?n.split("/").pop():void 0;this.runtime.emitWrite({method:r,path:n,auth:s,...r!=="delete"&&i?{data:i}:{},priorState:_,nextState:r==="delete"?null:b,...A&&A.length>0?{sentinels:A}:{},...I?{autoId:I}:{},requestTime:p,...f?{detail:f}:{}})}return L&&this.runtime.notify(r,n,new Set([n])),T}createWithAutoId(e,r,n,s){const i=e.endsWith("/")?e.slice(0,-1):e,a=Zf(),o=`${i}/${a}`,c=this.execute({method:"create",path:o,auth:n,data:r,autoId:!0,bypassRules:s});return{path:o,result:c}}batch(e,r,n){return this.batches.batch(e,r,n)}transaction(e,r){return this.transactions.transaction(e,r)}}class ta{state;eventLog;history;simulator;rules;seedSnapshot;events=new af;triggerScope=new of;reads;writes;listeners;constructor(){this.state=new In,this.eventLog=new tf;const e=this;this.simulator=new ed,this.rules=new yf(sf),this.reads=new Kf(this.events,this.triggerScope,this.rules,this.simulator,{get state(){return e.state}},this.eventLog),this.listeners=new mf(this.events,this.triggerScope,this.reads),this.writes=new op({get state(){return e.state},notifyListenersForPaths:r=>e.listeners.notifyListenersForPaths(r)},this.rules,this.simulator,this.eventLog,this.events,this.triggerScope),this.history=new gf(this.eventLog,{get state(){return e.state},capturePriors:r=>this.writes.capturePriors(r),applyWrite:(r,n,s,i)=>this.writes.applyWrite(r,n,s,i)}),this.seedSnapshot={}}onDenial(e){return this.events.denial.subscribe(e)}onRequest(e){return this.events.request.subscribe(e)}onWrite(e){return this.events.write.subscribe(e)}onSnapshotDelivery(e){return this.events.delivery.subscribe(e)}onSnapshotSuppressed(e){return this.events.suppressed.subscribe(e)}onListenerLifecycle(e){return this.events.lifecycle.subscribe(e)}onSnapshotError(e){return this.events.snapshotError.subscribe(e)}addSnapshotListener(e,r,n={},s=null,i,a=!1,o=!1,c){return this.listeners.addSnapshotListener(e,r,n,s,i,a,o,c)}flushListeners(){this.listeners.flushListeners()}getSnapshotListenerCount(){return this.listeners.getSnapshotListenerCount()}dispose(){this.listeners.dispose(),this.events.clear()}seed(e){return this.rules.set(e.rules),this.state=e.baseDocuments?new In({},new ef(e.baseDocuments)):new In(e.documents??{}),this.seedSnapshot=e.baseDocuments??this.state.snapshot(),this.eventLog.clear(),Vn(e.rules)}deployRules(e){const r=Vn(e);return this.rules.set(e),this.listeners.reEvaluateAllListeners(),r}reevaluateLiveListeners(e,r){this.listeners.reevaluateLiveListeners(e,r)}getRules(){return this.rules.source}getDocument(e){return this.state.get(e)}listDocuments(e){return this.state.list(e)}runQuery(e){return this.reads.runQuery(e)}listRootCollections(){return this.state.listRootCollections()}listSubcollections(e){return this.state.listSubcollections(e)}snapshot(){return this.state.snapshot()}adminSetDocument(e,r){this.state.set(e,r??{}),this.listeners.notifyListenersForPaths(new Set([e]))}adminDeleteDocument(e){const r=this.state.delete(e);return r.success&&this.listeners.notifyListenersForPaths(new Set([e])),{deleted:r.success}}execute(e){return e.method==="get"||e.method==="list"?this.reads.execute(e):this.writes.execute(e)}createWithAutoId(e,r,n,s){return this.writes.createWithAutoId(e,r,n,s)}batch(e,r,n){return this.writes.batch(e,r,n)}transaction(e,r){return this.writes.transaction(e,r)}undo(){return this.history.undo()}redo(){return this.history.redo()}getEvents(){return this.history.getEvents()}getEventCount(){return this.history.getEventCount()}}class ct extends Error{code;denialContext;remediation;constructor(e,r,n){const s=typeof e=="object",i=s?e.code:e,a=s?e.message:r,o=s?e.denialContext:n,c=s?e.remediation:void 0,u=c!==void 0?`${a}
1166
+
1167
+ Remediation:
1168
+ ${c}`:a;super(u),this.name="SandboxError",this.code=i,o!==void 0&&(this.denialContext=o),c!==void 0&&(this.remediation=c)}}function us(t){return t.kind==="request"||t.kind==="operation"||t.kind==="listener"&&t.phase==="errored"}function br(t){const e=Object.freeze({...t.source}),r=Object.freeze({...t.authLens});return Object.freeze({source:e,authLens:r,...t.planId===void 0?{}:{planId:t.planId}})}function Gp(t){const e=br(t);return{actor:e.source,authLens:e.authLens,operationContext:e,...e.planId===void 0?{}:{planId:e.planId}}}function ra(t){const e=t?.operationContext?.source;if(e&&e.kind!=="unattributed")return e;if(t?.actor&&t.actor.kind!=="unattributed")return t.actor}function Ds(t,e){const r=t?.operationContext?.source??t?.actor,n=e?.operationContext?.source??e?.actor;return br({source:ra(t)??ra(e)??r??n??{kind:"unattributed"},authLens:e?.operationContext?.authLens??e?.authLens??t?.operationContext?.authLens??t?.authLens??{mode:"app-session"},...(t?.operationContext?.planId??t?.planId??e?.operationContext?.planId??e?.planId)===void 0?{}:{planId:t?.operationContext?.planId??t?.planId??e?.operationContext?.planId??e?.planId}})}function cp(t){return Ds(void 0,t)}function up(t){if(t.result==="deny")return!0;if(!("error"in t)||!t.error||typeof t.error!="object")return!1;const e=t.error.code;if(typeof e!="string")return!1;const r=e.toLowerCase();return r==="permission_denied"||r==="permission-denied"||r==="auth/permission-denied"}function xo(t){return"rulesDisposition"in t&&t.rulesDisposition?t.rulesDisposition:t.kind==="operation"&&t.origin==="admin"?{kind:"bypassed",reason:"admin"}:t.detail?.admin===!0?{kind:"bypassed",reason:"admin"}:up(t)?{kind:"evaluated",verdict:"deny"}:t.result==="unsupported"?{kind:"not-evaluated",reason:"unsupported"}:t.kind==="operation"&&t.result==="error"?{kind:"not-evaluated",reason:"runtime-error"}:t.kind==="operation"&&t.result==="not-applicable"?{kind:"not-evaluated",reason:"not-a-rules-operation"}:t.kind==="listener"?t.rules?{kind:"evaluated",verdict:"deny"}:{kind:"not-evaluated",reason:"runtime-error"}:t.kind==="request"?{kind:"evaluated",verdict:"allow"}:"rules"in t&&t.rules?{kind:"evaluated",verdict:"allow"}:{kind:"not-evaluated",reason:"no-rules"}}function lp(t){if(t===null)return null;let e;return t.token!==void 0&&(e=ko(t.token)),Object.freeze({uid:t.uid,...e===void 0?{}:{token:e}})}function ko(t){const e={};for(const[r,n]of Object.entries(t))e[r]=Eo(n);return Object.freeze(e)}function Eo(t){return Array.isArray(t)?Object.freeze(t.map(Eo)):t&&typeof t=="object"?ko(t):t}function Kp(t){if(!us(t))return null;let e="listen",r;t.kind==="request"||t.kind==="operation"?(e=t.method,t.path!==void 0&&(r=t.path)):t.kind==="listener"&&(e="listen",t.target.path!==void 0&&(r=t.target.path));let n="firestore";return t.service!==void 0&&(n=t.service),Object.freeze({id:t.id,at:t.at,eventKind:t.kind,service:n,method:e,...r===void 0?{}:{path:r},auth:lp(t.auth),result:t.result,context:cp(t),rules:Object.freeze({...xo(t)})})}function na(t){return t===null?{mode:"anon"}:t.token===void 0?{mode:"as",uid:t.uid}:{mode:"as",uid:t.uid,token:t.token}}class hn{sandbox;auth;constructor(e,r,n){this.sandbox=e,this.auth=r,this.operationContext=br(n??{source:{kind:"unattributed"},authLens:na(r)})}operationContext;withAuth(e){return ls(e),new hn(this.sandbox,e,{source:this.operationContext.source,authLens:na(e),...this.operationContext.planId===void 0?{}:{planId:this.operationContext.planId}})}}function Zp(t,e){return new hn(t.sandbox,t.auth,e)}function ls(t){if(t===null)return;if(t===void 0)throw new ct({code:"invalid-argument",message:"withAuth() requires an explicit AuthState argument.",remediation:["For anonymous (unauthenticated) access: withAuth(null)",'For authenticated access: withAuth({ uid: "someUid" })','For custom claims: withAuth({ uid: "someUid", token: { role: "admin" } })'].join(`
1169
+ `)});if(typeof t!="object")throw new ct("invalid-argument","withAuth() expected null or an object with a `uid` field.");const e=t;if(typeof e.uid!="string"||e.uid.length===0)throw new ct("invalid-argument","withAuth() requires `uid` to be a non-empty string.");if("token"in e&&e.token!==void 0&&(e.token===null||typeof e.token!="object"||Array.isArray(e.token)))throw new ct("invalid-argument","withAuth() requires `token` (when present) to be a plain object.")}function dp(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),r=e.length%4===0?"":"=".repeat(4-e.length%4),n=atob(e+r),s=new Uint8Array(n.length);for(let i=0;i<n.length;i++)s[i]=n.charCodeAt(i);return s}function hp(t){const e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r}function To(t){return ds(t,!0)}function ds(t,e){if(t===null||typeof t!="object")return t;if(Array.isArray(t)){const a=t.map(o=>ds(o,!1));return e&&is(a,Ui(t)),a}const r=t,n=a=>(e&&is(a,Ui(t)),a),s=(a,o)=>(Rs(a,Object.freeze(o),()=>a),n(a));if(r.__type__==="__vector__"&&Array.isArray(r.value)){const a=Object.freeze(r.value.slice());return s(new Qt(a),{type:"vector",values:a})}if(typeof r.__type=="string")switch(r.__type){case"timestamp":return s(new _e(r.seconds,r.nanos),{type:"timestamp",seconds:r.seconds,nanoseconds:r.nanos});case"bytes":{const a=dp(r.base64);return s(new Ae(a),{type:"bytes",values:Object.freeze(Array.from(a))})}case"latlng":return s(new lt(r.lat,r.lng),{type:"geo-point",latitude:r.lat,longitude:r.lng});case"duration":return n(new ve(r.seconds,r.nanos));case"reference":return n(new Ot(r.path));case"path":return n(new Qe(r.segments))}if(typeof r.type=="string")switch(r.type){case"firestore/timestamp/1.0":{const a=r.seconds,o=r.nanoseconds;return s(new _e(a,o),{type:"timestamp",seconds:a,nanoseconds:o})}case"firestore/bytes/1.0":{const a=hp(r.bytes);return s(new Ae(a),{type:"bytes",values:Object.freeze(Array.from(a))})}case"firestore/geoPoint/1.0":return s(new lt(r.latitude,r.longitude),{type:"geo-point",latitude:r.latitude,longitude:r.longitude})}const i={};for(const[a,o]of Object.entries(r))i[a]=ds(o,!1);return n(i)}class _r extends Error{constructor(e){super(e),this.name="PersistenceSchemaError"}}function fp(t){let e;try{e=JSON.parse(t)}catch(s){throw new _r(`Persisted blob is not valid JSON: ${s.message}`)}if(typeof e!="object"||e===null)throw new _r("Persisted blob is not an object");if(e.version!==1&&e.version!==2)throw new _r(`Persisted blob has version ${String(e.version)}, expected 1 or 2`);if(typeof e.firestore!="object"||e.firestore===null)throw new _r("Persisted blob has no firestore field");const r={};for(const[s,i]of Object.entries(e.firestore))r[s]=To(i);const n=e.services!==void 0&&typeof e.services=="object"&&e.services!==null?e.services:{};return{firestore:r,services:n}}const pp=3,mp=256,hs="meta";function gp(t){let e=2166136261;for(let r=0;r<t.length;r++)e^=t.charCodeAt(r),e=e+((e<<1)+(e<<4)+(e<<7)+(e<<8)+(e<<24))>>>0;return(e%mp).toString(16).padStart(2,"0")}function yp(t){return JSON.parse(JSON.stringify(t))}function Oo(t){const e=JSON.stringify(t);let r=2166136261;for(let n=0;n<e.length;n++)r^=e.charCodeAt(n),r=Math.imul(r,16777619)>>>0;return r}function Co(t,e,r){const n=new Map;n.set(hs,{version:pp,savedAt:r,services:e});for(const[s,i]of Object.entries(t)){const a=gp(s);let o=n.get(a);o||(o={docs:{}},n.set(a,o)),o.docs[s]=yp(i)}for(const[s,i]of n)s!==hs&&(i.checksum=Oo(i.docs));return n}const Ro="pyric-v3-records";function Jp(t){return JSON.stringify({format:Ro,records:Object.fromEntries(t)})}function Yp(t){let e;try{e=JSON.parse(t)}catch{return new Map}const r=e;return r&&typeof r=="object"&&r.format===Ro&&typeof r.records=="object"&&r.records!==null?new Map(Object.entries(r.records)):No(t)??new Map}function No(t){let e;try{e=fp(t)}catch{return null}return Co(e.firestore,e.services,0)}function vp(t){const e={};let r={};for(const[n,s]of t){if(n===hs){const a=s;a&&typeof a.services=="object"&&a.services!==null&&(r=a.services);continue}const i=s;if(!(!i||typeof i.docs!="object"||i.docs===null)){if(typeof i.checksum=="number"&&Oo(i.docs)!==i.checksum){console.warn(`[sandbox/persistence] checksum mismatch for bucket '${n}'; skipping corrupt bucket`);continue}for(const[a,o]of Object.entries(i.docs))e[a]=To(o)}}return{firestore:e,services:r}}const Jt="snapshots";function sa(){const t=new Map,e=r=>{let n=t.get(r);return n||(n=new Map,t.set(r,n)),n};return{async getRecord(r,n){const s=t.get(r)?.get(n);return s===void 0?null:structuredClone(s)},async listRecords(r){return[...t.get(r)?.keys()??[]]},async putRecords(r,n){const s=e(r);for(const[i,a]of n)s.set(i,structuredClone(a))},async deleteRecords(r,n){const s=t.get(r);if(s)for(const i of n)s.delete(i)},async clear(r){t.delete(r)}}}function Lo(t){return new Promise((e,r)=>{const n=indexedDB.open(t,1);n.onupgradeneeded=()=>{const s=n.result;s.objectStoreNames.contains(Jt)||s.createObjectStore(Jt)},n.onsuccess=()=>e(n.result),n.onerror=()=>r(n.error??new Error(`Failed to open IndexedDB '${t}'`)),n.onblocked=()=>r(new Error(`IndexedDB open blocked for '${t}'`))})}function Tn(t,e,r){return Lo(t).then(n=>new Promise((s,i)=>{const a=n.transaction(Jt,e),o=a.objectStore(Jt),c=r(o);let u=null;c&&(c.onsuccess=()=>{u=c.result??null},c.onerror=()=>i(c.error)),a.oncomplete=()=>{n.close(),s(u)},a.onerror=()=>{n.close(),i(a.error)},a.onabort=()=>{n.close(),i(a.error??new Error("IndexedDB transaction aborted"))}}))}function ia(t,e){return Lo(t).then(r=>new Promise((n,s)=>{const i=r.transaction(Jt,"readwrite");e(i.objectStore(Jt)),i.oncomplete=()=>{r.close(),n()},i.onerror=()=>{r.close(),s(i.error)},i.onabort=()=>{r.close(),s(i.error??new Error("IndexedDB transaction aborted"))}}))}function bp(){if(typeof indexedDB>"u")throw new Error('IndexedDB is not available in this environment. Use { backend: "memory" } or supply an injectedBackend.');return{async getRecord(t,e){return await Tn(t,"readonly",n=>n.get(e))??null},async listRecords(t){return(await Tn(t,"readonly",r=>r.getAllKeys())??[]).map(r=>String(r))},async putRecords(t,e){await ia(t,r=>{for(const[n,s]of e)r.put(s,n)})},async deleteRecords(t,e){await ia(t,r=>{for(const n of e)r.delete(n)})},async clear(t){await Tn(t,"readwrite",e=>e.clear())},async estimate(){if(typeof navigator>"u"||!navigator.storage?.estimate)return null;const t=await navigator.storage.estimate();return{usage:t.usage??0,quota:t.quota??0}}}}const wp=250,aa="pyric:sandbox:auth-session";function On(t){return t==="auth"||t==="auth-session:[DEFAULT]"?aa:`${aa}:${encodeURIComponent(t)}`}function Mo(t){const e=JSON.stringify(t);let r=2166136261;for(let n=0;n<e.length;n++)r^=e.charCodeAt(n),r=Math.imul(r,16777619)>>>0;return r}function Sp(t){if(t&&typeof t=="object"){if(t.name==="QuotaExceededError")return!0;const e=t.message;if(typeof e=="string"&&/quota/i.test(e))return!0}return!1}function _p(t){return t.injectedBackend?t.injectedBackend:(t.backend??"indexedDB")==="memory"||typeof indexedDB>"u"?sa():bp()}async function Ap(t,e){const r={...e,flushIntervalMs:e.flushIntervalMs??wp,backend:e.backend??"indexedDB"},n=_p(r),s=new Map,i=await Ip(t,n,r.key,s);let a=null,o=!1;const c=new Map,u=async()=>{if(o)return;const _=t.snapshot(),b=Co(_.firestore,_.services,Date.now()),A=new Map,I=new Map;for(const[d,g]of b){const m=Mo(g);I.set(d,m),s.get(d)!==m&&A.set(d,g)}const h=[...s.keys()].filter(d=>!b.has(d));A.size>0&&await n.putRecords(r.key,A),h.length>0&&await n.deleteRecords(r.key,h),s.clear();for(const[d,g]of I)s.set(d,g)};let f=Promise.resolve();const l=()=>(a&&(clearTimeout(a),a=null),f=f.then(u,u),f),p=()=>{o||a||(a=setTimeout(()=>{a=null,l().catch(_=>{if(Sp(_)){console.warn("[sandbox/persistence] storage quota exceeded; recent changes are kept in memory only. Free storage or reduce sandbox data to persist them.");return}console.warn("[sandbox/persistence] auto-flush failed, will retry:",_),p()})},r.flushIntervalMs))},y=(_,b)=>{if(!b.subscribe||c.has(_))return;const A=b.subscribe(()=>{p()});c.set(_,A)},v=new Map,w=new Map,R=(_,b)=>{if(!r.sessionStorage)return;const{local:A,session:I}=r.sessionStorage,h=On(_),d=b.currentUid(),g=b.mode();if(d===null||g==="NONE"){A.removeItem(h),I.removeItem(h);return}const m=JSON.stringify({uid:d});g==="LOCAL"?(I.removeItem(h),A.setItem(h,m)):(A.removeItem(h),I.setItem(h,m))},C=_=>{if(!r.sessionStorage)return null;const b=On(_);for(const[A,I]of[["LOCAL",r.sessionStorage.local],["SESSION",r.sessionStorage.session]]){const h=I.getItem(b);if(h)try{const d=JSON.parse(h);if(typeof d?.uid=="string")return{uid:d.uid,mode:A}}catch{I.removeItem(b)}}return null},k=_=>{if(!r.sessionStorage)return;const b=On(_);r.sessionStorage.local.removeItem(b),r.sessionStorage.session.removeItem(b)},x=(_,b,A)=>{if(A.session)try{A.session.restore(b.uid,b.mode),w.delete(_)}catch(I){console.warn(`[sandbox/persistence] session restore for uid '${b.uid}' failed — clearing stored session:`,I),k(_),w.delete(_)}},L=(_,b)=>{if(!r.sessionStorage||!b.session||v.has(_))return;const A=b.session;v.set(_,A.subscribe(()=>R(_,A)))},$=(_,b)=>{if(!b.session)return;const A=w.get(_)??C(_);A&&x(_,A,b)};if(t instanceof bt){for(const[_,b]of t.getServiceRegistry())y(_,b),$(_,b),L(_,b);t.setServiceRegistrationHook((_,b)=>{if(i!==null&&_ in i)try{b.restore(i[_])}catch(I){console.warn(`[sandbox/persistence] late-restore for service '${_}' failed:`,I)}const A=C(_);A&&w.set(_,A),$(_,b),y(_,b),L(_,b),p()}),t.setServiceUnregistrationHook(_=>{c.get(_)?.(),c.delete(_),v.get(_)?.(),v.delete(_),w.delete(_),p()})}const S=t.onEvent(_=>{xp(_)&&p()}),T=()=>{l().catch(()=>{})};return typeof window<"u"&&window.addEventListener("beforeunload",T),{options:r,flush:l,async clear(){a&&(clearTimeout(a),a=null),await n.clear(r.key),s.clear()},dispose(){if(!o){o=!0,a&&(clearTimeout(a),a=null),S();for(const _ of c.values())_();c.clear();for(const _ of v.values())_();v.clear(),t instanceof bt&&(t.setServiceRegistrationHook(null),t.setServiceUnregistrationHook(null)),typeof window<"u"&&window.removeEventListener("beforeunload",T)}}}}async function Ip(t,e,r,n){let s;try{s=await e.listRecords(r)}catch(f){return console.warn("[sandbox/persistence] backend list failed:",f),null}if(s.length===0)return null;const i=[];for(const f of s)try{const l=await e.getRecord(r,f);l!==null&&i.push([f,l])}catch(l){console.warn(`[sandbox/persistence] failed to read persisted record '${f}':`,l)}const a=[],o=[];let c=null;for(const[f,l]of i)if(typeof l=="string"){const p=No(l);p&&(o.push(f),c=p)}else a.push([f,l]);if(c){try{await e.putRecords(r,c),o.length>0&&await e.deleteRecords(r,o)}catch(f){console.warn("[sandbox/persistence] v2 migration write failed:",f)}for(const[f,l]of c)a.push([f,l])}for(const[f,l]of a)n.set(f,Mo(l));const u=vp(a);for(const[f,l]of Object.entries(u.firestore))t.admin.setDocument(f,l);if(t instanceof bt){const f=t.getServiceRegistry();for(const[l,p]of Object.entries(u.services)){const y=f.get(l);if(y)try{y.restore(p)}catch(v){console.warn(`[sandbox/persistence] service '${l}' restore failed — Firestore state is intact; auth users may need to be re-created:`,v)}}}return u.services}function xp(t){return t.kind==="write"||t.kind==="session_boundary"}function kp(t){return typeof t=="object"&&t!==null&&typeof t.kind=="string"&&typeof t.origin=="string"}let Ep=0;function Tp(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`tab-${crypto.randomUUID()}`:`tab-${++Ep}-${typeof performance<"u"?performance.now().toFixed(3):String(Date.now())}`}function Op(t,e={}){let r,n=!1;if(e.channel)r=e.channel,n=!1;else if(typeof BroadcastChannel<"u")r=new BroadcastChannel("pyric:tabsync"),n=!0;else return()=>{};const s=e.originId??Tp();let i=!1,a=!1;const o=t.onEvent(l=>{if(l.kind!=="write"||i)return;const p={kind:"write",origin:s,event:l};r.postMessage(p)}),c=l=>{if(!kp(l.data))return;const p=l.data;if(p.origin!==s){if(p.kind==="write")f(p.event);else if(p.kind==="hello"){const y={kind:"state",origin:s,to:p.origin,snapshot:t.snapshot()};r.postMessage(y)}else if(p.kind==="state"){if(p.to!==s||a)return;if(Object.keys(wr(t).snapshot()).length>0){a=!0;return}i=!0;try{for(const[v,w]of Object.entries(p.snapshot.firestore))t.admin.setDocument(v,w)}finally{i=!1}a=!0}}};r.addEventListener("message",c);const u={kind:"hello",origin:s};return r.postMessage(u),()=>{o(),r.removeEventListener("message",c),n&&r.close()};function f(l){i=!0;try{if(l.method==="delete")t.admin.deleteDocument(l.path);else{const p=l.nextState;p!=null&&t.admin.setDocument(l.path,p)}}finally{i=!1}}}function Cp(t,e){const r={...t};r.service=t.service??e?.service??"firestore";const s="detail"in t&&t.detail?.admin===!0&&t.operationContext===void 0&&t.authLens===void 0?{...t,authLens:{mode:"admin"}}:t,i=us(r)||t.operationContext!==void 0?Ds(e,s):Rp(t,e);return r.operationContext=i,r.actor=i.source,r.authLens=i.authLens,i.planId!==void 0&&(r.planId=i.planId),e?.activity!==void 0&&(r.activity={...r.activity,...e.activity}),us(r)&&(r.rulesDisposition=Object.freeze({...xo(r)})),r}function Rp(t,e){return br({source:t.actor??t.operationContext?.source??e?.actor??e?.operationContext?.source??{kind:"unattributed"},authLens:t.authLens??t.operationContext?.authLens??e?.authLens??e?.operationContext?.authLens??{mode:"app-session"},...(t.planId??t.operationContext?.planId??e?.planId??e?.operationContext?.planId)===void 0?{}:{planId:t.planId??t.operationContext?.planId??e?.planId??e?.operationContext?.planId}})}function Np(t,e){if(!t)return e;if(!e)return t;if(e.operationContext!==void 0)return Do(t,e);if(!(t.operationContext!==void 0||t.actor!==void 0||t.authLens!==void 0||t.planId!==void 0||e.actor!==void 0||e.authLens!==void 0||e.planId!==void 0))return{...t,...e};const n=br({source:e.actor??t.operationContext?.source??t.actor??{kind:"unattributed"},authLens:e.authLens??t.operationContext?.authLens??t.authLens??{mode:"app-session"},...(e.planId??t.operationContext?.planId??t.planId)===void 0?{}:{planId:e.planId??t.operationContext?.planId??t.planId}});return{...t,...e,operationContext:n,actor:n.source,authLens:n.authLens,...n.planId===void 0?{}:{planId:n.planId}}}function Do(t,e){if(!t)return e;if(!e)return t;if(!(t.operationContext!==void 0||t.actor!==void 0||t.authLens!==void 0||t.planId!==void 0||e.operationContext!==void 0||e.actor!==void 0||e.authLens!==void 0||e.planId!==void 0))return{...t,...e};const n=Ds(t,e);return{...t,...e,operationContext:n,actor:n.source,authLens:n.authLens,...n.planId===void 0?{}:{planId:n.planId}}}let Lp=1;function Tt(){const t=(Lp++).toString(36),e=Math.random().toString(36).slice(2,7);return`sbe-${t}-${e}`}class bt{_env;eventSubs=new Set;envUnsubs=[];dispatchedCount=0;eventHistory=[];ambientProvenance;_currentUser=null;currentUserSubs=new Set;persistence=null;enablePersistencePromise=null;serviceRegistry=new Map;_onServiceRegistered=null;_onServiceUnregistered=null;constructor(e){this._env=e,this.attachToEnv()}static createRoot(){return new bt(new ta)}getEnv(){return this._env}withAuth(e){return ls(e),new hn(this,e)}attachToEnv(){this.envUnsubs.push(this._env.onRequest(e=>{this.emitEvent(e)})),this.envUnsubs.push(this._env.onWrite(e=>{this.emitEvent(e)})),this.envUnsubs.push(this._env.onSnapshotDelivery(e=>this.emitEvent(e))),this.envUnsubs.push(this._env.onSnapshotSuppressed(e=>this.emitEvent(e))),this.envUnsubs.push(this._env.onListenerLifecycle(e=>this.emitEvent(e))),this.envUnsubs.push(this._env.onSnapshotError((e,r,n)=>{const s={kind:"listener_errored",id:Tt(),at:Date.now(),listenerId:n,target:r.kind==="doc"?{kind:"doc",path:r.path}:{kind:"query",collection:r.collection},auth:e.request?.auth??null,error:{code:"permission-denied",message:e.message}};this.emitEvent(s)}))}emitEvent(e,r){const n=Do(this.ambientProvenance,r);this.dispatch(Cp(e,n))}runWithProvenance(e,r){const n=this.ambientProvenance;this.ambientProvenance=Np(n,e);try{return r()}finally{this.ambientProvenance=n}}dispatch(e){if(this.eventHistory.push(e),this.dispatchedCount++,this.eventSubs.size!==0)for(const r of this.eventSubs)try{const n=r(e);n&&typeof n.then=="function"&&n.catch(()=>{})}catch{}}emitInternal(e,r){this.emitEvent(e,r)}onEvent(e){return this.eventSubs.add(e),()=>{this.eventSubs.delete(e)}}history(){return[...this.eventHistory]}primeEventHistory(e){return this.eventHistory.length>0||e.length===0?0:(this.eventHistory.push(...e),e.length)}get admin(){return{getDocument:e=>this._env.getDocument(e),listDocuments:e=>this._env.listDocuments(e),setDocument:(e,r)=>this._env.adminSetDocument(e,r),deleteDocument:e=>this._env.adminDeleteDocument(e)}}reset(){const e={kind:"session_boundary",id:Tt(),at:Date.now(),phase:"reset",priorOpCount:this.dispatchedCount};this.emitEvent(e),this.eventHistory=[],this._currentUser!==null&&(this._currentUser=null,this.notifyCurrentUserSubs(null));for(const r of this.envUnsubs)r();this.envUnsubs=[],this._env.dispose(),this._env=new ta,this.attachToEnv()}async resetAll(){this.reset();const e=[],r=[];for(const[n,s]of this.serviceRegistry)s.reset&&r.push(Promise.resolve().then(()=>s.reset()).catch(i=>{e.push(`${n}: ${i instanceof Error?i.message:String(i)}`)}));return await Promise.all(r),{errors:e}}dispose(){const e={kind:"session_boundary",id:Tt(),at:Date.now(),phase:"dispose",priorOpCount:this.dispatchedCount};this.emitEvent(e);for(const r of this.envUnsubs)r();this.envUnsubs=[],this._env.dispose(),this.persistence&&(this.persistence.dispose(),this.persistence=null),this.serviceRegistry.clear(),this._onServiceRegistered=null,this._onServiceUnregistered=null,this.eventSubs.clear(),this.currentUserSubs.clear()}snapshot(){const e={};for(const[r,n]of this.serviceRegistry)e[r]=n.snapshot();return{firestore:this._env.snapshot(),services:e}}loadSnapshot(e){this.reset();for(const[r,n]of Object.entries(e.firestore))this._env.adminSetDocument(r,n);for(const[r,n]of this.serviceRegistry)if(r in e.services)try{n.restore(e.services[r])}catch(s){console.warn(`[sandbox] loadSnapshot: service '${r}' restore failed — Firestore is intact; that service's state may be incomplete:`,s)}}get currentUser(){return this._currentUser}set currentUser(e){ls(e),!Mp(this._currentUser,e)&&(this._currentUser=e,this.notifyCurrentUserSubs(e))}onCurrentUserChanged(e){return this.currentUserSubs.add(e),()=>{this.currentUserSubs.delete(e)}}notifyCurrentUserSubs(e){if(this._env.reevaluateLiveListeners(e),this.currentUserSubs.size!==0)for(const r of this.currentUserSubs)try{const n=r(e);n&&typeof n.then=="function"&&n.catch(()=>{})}catch{}}async enablePersistence(e){if(this.persistence){if(this.persistence.options.key!==e.key)throw new ct("failed-precondition",`Persistence already enabled with key '${this.persistence.options.key}'; cannot re-enable with key '${e.key}'. Dispose and recreate the sandbox.`);return}if(this.enablePersistencePromise)return this.enablePersistencePromise;this.enablePersistencePromise=(async()=>{const r=await Ap(this,e);this.persistence=r})();try{await this.enablePersistencePromise}finally{this.enablePersistencePromise=null}}enableTabSync(e){return Op(this,e)}async flush(){if(!this.persistence)throw new ct("failed-precondition","flush() called before enablePersistence()");await this.persistence.flush()}async clearPersistence(){this.persistence&&await this.persistence.clear()}registerPersistableService(e,r){if(this.serviceRegistry.has(e))throw new ct("failed-precondition",`registerPersistableService: a service named '${e}' is already registered on this sandbox. Each service name must be unique — the auth package registers 'auth' exactly once per sandbox.`);return this.serviceRegistry.set(e,r),this._onServiceRegistered&&this._onServiceRegistered(e,r),()=>{this.serviceRegistry.get(e)===r&&(this.serviceRegistry.delete(e),this._onServiceUnregistered?.(e))}}setServiceRegistrationHook(e){this._onServiceRegistered=e}setServiceUnregistrationHook(e){this._onServiceUnregistered=e}getServiceRegistry(){return this.serviceRegistry}}function Mp(t,e){if(t===e)return!0;if(t===null||e===null||t.uid!==e.uid)return!1;const r=t.token===void 0?void 0:JSON.stringify(t.token),n=e.token===void 0?void 0:JSON.stringify(e.token);return r===n}function wr(t){if(!(t instanceof bt))throw new ct("invalid-argument","Sandbox handle was not produced by initializeSandbox(); custom Sandbox implementations are not supported.");return t.getEnv()}function Qp(t,e,r){if(!(t instanceof bt))throw new ct("invalid-argument","Sandbox handle was not produced by initializeSandbox(); custom Sandbox implementations are not supported.");t.emitInternal(e,r)}function Xp(t){return{kind:"service_mutation",id:Tt(),at:Date.now(),...t}}function em(t){const{at:e,...r}=t;return{kind:"operation",id:Tt(),at:e??Date.now(),...r}}function tm(t){const{at:e,...r}=t;return{kind:"commit",id:Tt(),at:e??Date.now(),...r}}function rm(t){const{at:e,...r}=t;return{kind:"listener",id:Tt(),at:e??Date.now(),...r}}function nm(){return bt.createRoot()}function sm(t,e){return wr(t).deployRules(e)}function im(t,e){const r=wr(t);return r.seed({rules:r.getRules(),documents:e})}function am(t){return wr(t).snapshot()}function om(t,e={}){const r=e.recentEventLimit??10,n=wr(t),s=n.getRules(),i=s?Vn(s):{warnings:[]},a=i.warnings.map(w=>({rule:w.rule,severity:w.severity,message:w.message})),o={errors:0,warnings:0,info:0};for(const w of i.warnings)w.severity==="error"?o.errors++:w.severity==="warning"?o.warnings++:o.info++;const c=n.snapshot(),u={};for(const w of Object.keys(c)){const R=w.split("/")[0]??"";R&&(u[R]=(u[R]??0)+1)}const f=t.history(),l=[];for(const w of f){const R=w.kind==="request",C=w.kind==="operation",k=w.kind==="listener";(R||C||k&&w.phase==="errored")&&l.push(w)}const p=[];for(const w of l)if(w.result==="deny")p.push(w);else{const C=w.error;C!==void 0&&C.code==="PERMISSION_DENIED"&&p.push(w)}const y=l.slice(-r).map(w=>{let R="";if(w.path!==void 0)R=String(w.path);else{const L=w.target;L!==void 0&&L.path!==void 0&&(R=String(L.path))}let C="listen";w.method!==void 0&&(C=String(w.method));let k="error";if(w.result!==void 0)k=String(w.result);else{const L=w.error;L!==void 0&&L.code==="PERMISSION_DENIED"&&(k="deny")}let x=null;return w.auth!==void 0&&(x=w.auth),{path:R,method:C,result:k,auth:x}}),v=p.slice(-r).map(w=>{let R="";if(w.path!==void 0)R=String(w.path);else{const L=w.target;L!==void 0&&L.path!==void 0&&(R=String(L.path))}let C="listen";w.method!==void 0&&(C=String(w.method));let k=null;w.auth!==void 0&&(k=w.auth);let x;return typeof w.debugMessage=="string"&&(x=w.debugMessage),{path:R,method:C,auth:k,debugMessage:x}});return{rules:{source:s,sizeBytes:new TextEncoder().encode(s).byteLength,isEmpty:s.trim().length===0,lint:{...o,findings:a}},documents:{totalCount:Object.keys(c).length,byCollection:u},events:{totalCount:f.length,recentDenials:v,recentRequests:y}}}export{Pp as $,Br as A,wr as B,sa as C,ct as D,Kp as E,us as F,Pc as G,ot as H,Dd as I,pr as J,Et as K,mr as L,Os as M,Md as N,Jr as O,Ts as P,ho as Q,ae as R,hn as S,Vt as T,po as U,zp as V,cf as W,Hp as X,tn as Y,fe as Z,jh as _,im as a,$p as a0,Rs as a1,is as a2,Ye as a3,Gf as a4,he as a5,Zf as a6,Xf as a7,ep as a8,rr as a9,tr as aa,Xi as ab,Vp as ac,Wp as ad,Ae as ae,lt as af,Qt as ag,Up as ah,am as b,nm as c,em as d,Qp as e,tm as f,rm as g,Bp as h,om as i,jp as j,Jp as k,To as l,Xp as m,Or as n,Ds as o,Yp as p,Gp as q,qp as r,sm as s,Zp as t,ut as u,at as v,Kt as w,Kn as x,Rt as y,Hr as z};