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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/dist/bridge/client/dispatch.js +1 -1
  2. package/dist/bridge/client/dispatch.js.map +1 -1
  3. package/dist/serve/entries/auth-helper-core.d.ts +9 -0
  4. package/dist/serve/entries/auth-helper-core.d.ts.map +1 -1
  5. package/dist/serve/entries/auth-helper-core.js +28 -1
  6. package/dist/serve/entries/auth-helper-core.js.map +1 -1
  7. package/dist/serve/entries/auth.d.ts.map +1 -1
  8. package/dist/serve/entries/auth.js +6 -4
  9. package/dist/serve/entries/auth.js.map +1 -1
  10. package/dist/serve/site-ui/_astro/app.4HeLP_FA.js +109 -0
  11. package/dist/serve/site-ui/_astro/app.BgSnCR5G.js +1 -0
  12. package/dist/serve/site-ui/_astro/{chess-showcase.DzPO6kz0.js → chess-showcase.CnoxIle5.js} +1 -1
  13. package/dist/serve/site-ui/_astro/{example-runtime.CM0H02rx.js → example-runtime.R1d96L6-.js} +1 -1
  14. package/dist/serve/site-ui/_astro/index.BJiOemMX.js +1 -0
  15. package/dist/serve/site-ui/_astro/{reads.D1exkX1-.js → reads.BrKNdKAa.js} +1 -1
  16. package/dist/serve/site-ui/_astro/{sandbox-controls.BqMePr5V.js → sandbox-controls.BTb3EbQp.js} +32 -32
  17. package/dist/serve/site-ui/_astro/{seed.BCn5DhHS.js → seed.EyI3VYEu.js} +1 -1
  18. package/dist/serve/site-ui/auth/index.html +1 -1
  19. package/dist/serve/site-ui/docs/examples/chess/index.html +1 -1
  20. package/dist/serve/site-ui/docs/pyric-auth-reference-api/index.html +1 -1
  21. package/dist/serve/site-ui/docs/pyric-auth-reference-api.md +1 -1
  22. package/dist/serve/site-ui/examples/chess/index.html +1 -1
  23. package/dist/serve/site-ui/examples/firestore-first-write/index.html +1 -1
  24. package/dist/serve/site-ui/firestore/index.html +1 -1
  25. package/dist/serve/site-ui/index.html +1 -1
  26. package/dist/serve/site-ui/rtdb/index.html +1 -1
  27. package/dist/serve/site-ui/settings/index.html +1 -1
  28. package/dist/serve/site-ui/storage/index.html +1 -1
  29. package/dist/serve/site-ui/traffic/index.html +1 -1
  30. package/package.json +4 -4
  31. package/src/bridge/client/dispatch.ts +1 -1
  32. package/src/serve/entries/auth-helper-core.ts +35 -1
  33. package/src/serve/entries/auth.ts +8 -4
  34. package/dist/serve/site-ui/_astro/app.BnMC0ywl.js +0 -109
  35. package/dist/serve/site-ui/_astro/app.DVXXR-WI.js +0 -1
  36. package/dist/serve/site-ui/_astro/index.B4Kh80he.js +0 -1
@@ -1,21 +1,21 @@
1
- var co=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function mu(t){if(Object.prototype.hasOwnProperty.call(t,"__esModule"))return t;var e=t.default;if(typeof e=="function"){var r=function n(){return this instanceof n?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};r.prototype=e.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(t).forEach(function(n){var s=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(r,n,s.get?s:{enumerable:!0,get:function(){return t[n]}})}),r}function De(t){const e=t||"";return function(){throw new Error("this method "+e+" is abstract! (it has no implementation in class "+this.constructor.name+")")}}function It(t,e){if(!t)throw new Error(e||"Assertion failed")}function ls(t,e,r){let n;Object.defineProperty(t,e,{get(){return n||(n=r.call(this)),n}})}function uo(t,e){const r=[];for(;e-- >0;)r.push(t());return r}function lo(t,e){return new Array(e+1).join(t)}function Ln(t,e){return uo(()=>t,e)}function ds(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 ho(t){const e=[];return t.forEach(r=>{e.indexOf(r)<0&&e.push(r)}),e}function Nt(t){const e=t[0];return e===e.toUpperCase()}function fo(t){return!Nt(t)}function po(t,e,r){return t.length<e?lo(" ",e-t.length)+t:t}function Bt(){this.strings=[]}Bt.prototype.append=function(t){this.strings.push(t)};Bt.prototype.contents=function(){return this.strings.join("")};const Wn=t=>String.fromCodePoint(parseInt(t,16));function mo(t){if(t.charAt(0)==="\\")switch(t.charAt(1)){case"b":return"\b";case"f":return"\f";case"n":return`
2
- `;case"r":return"\r";case"t":return" ";case"v":return"\v";case"x":return Wn(t.slice(2,4));case"u":return t.charAt(2)==="{"?Wn(t.slice(3,-1)):Wn(t.slice(2,6));default:return t.charAt(1)}else return t}function Js(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 go(t,e="unexpected null value"){if(t==null)throw new Error(e);return t}const gu=Object.freeze(Object.defineProperty({__proto__:null,StringBuffer:Bt,abstract:De,assert:It,checkNotNull:go,copyWithoutDuplicates:ho,defineLazyProperty:ls,getDuplicates:ds,isLexical:fo,isSyntactic:Nt,padLeft:po,repeat:Ln,repeatFn:uo,repeatStr:lo,unescapeCodePoint:mo,unexpectedObjToString:Js},Symbol.toStringTag,{value:"Module"})),yo=t=>new RegExp(String.raw`\p{${t}}`,"u"),hs=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,yo(t)]));hs.Ltmo=/\p{Lt}|\p{Lm}|\p{Lo}/u;const Ti=Object.fromEntries(["XID_Start","XID_Continue","White_Space"].map(t=>[t,yo(t)]));class z{constructor(){if(this.constructor===z)throw new Error("PExpr cannot be instantiated -- it's abstract")}withSource(e){return e&&(this.source=e.trimmed()),this}}const Te=Object.create(z.prototype),Re=Object.create(z.prototype);class Oe extends z{constructor(e){super(),this.obj=e}}class Ne extends z{constructor(e,r){super(),this.from=e,this.to=r,this.matchCodePoint=e.length>1||r.length>1}}class Fe extends z{constructor(e){super(),this.index=e}}class be extends z{constructor(e){super(),this.terms=e}}class jn extends be{constructor(e,r,n){const s=e.rules[r].body;super([n,s]),this.superGrammar=e,this.name=r,this.body=n}}class Dn extends be{constructor(e,r,n,s){const i=e.rules[r].body;super([...n,i,...s]),this.superGrammar=e,this.ruleName=r,this.expansionPos=n.length}}class Ae extends z{constructor(e){super(),this.factors=e}}class Me extends z{constructor(e){super(),this.expr=e}}class zt extends Me{}class ar extends Me{}class mt extends Me{}zt.prototype.operator="*";ar.prototype.operator="+";mt.prototype.operator="?";zt.prototype.minNumMatches=0;ar.prototype.minNumMatches=1;mt.prototype.minNumMatches=0;zt.prototype.maxNumMatches=Number.POSITIVE_INFINITY;ar.prototype.maxNumMatches=Number.POSITIVE_INFINITY;mt.prototype.maxNumMatches=1;class ke extends z{constructor(e){super(),this.expr=e}}class Pe extends z{constructor(e){super(),this.expr=e}}class qe extends z{constructor(e){super(),this.expr=e}}class X extends z{constructor(e,r=[]){super(),this.ruleName=e,this.args=r}isSyntactic(){return Nt(this.ruleName)}toMemoKey(){return this._memoKey||Object.defineProperty(this,"_memoKey",{value:this.toString()}),this._memoKey}}class Ee extends z{constructor(e){if(super(),this.categoryOrProp=e,e in hs)this.pattern=hs[e];else if(e in Ti)this.pattern=Ti[e];else throw new Error(`Invalid Unicode category or property name: ${JSON.stringify(e)}`)}}function le(t,e){let r;return e?(r=new Error(e.getLineAndColumnMessage()+t),r.shortMessage=t,r.interval=e):r=new Error(t),r}function fs(){return le("Interval sources don't match")}function yu(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 bu(t,e,r){const n=e?`Grammar ${t} is not declared in namespace '${e}'`:"Undeclared grammar "+t;return le(n,r)}function vu(t,e){return le("Grammar "+t.name+" is already declared in this namespace")}function wu(t){return le(`Grammar '${t.name}' does not support incremental parsing`)}function bo(t,e,r){return le("Rule "+t+" is not declared in grammar "+e,r)}function Su(t,e,r){return le("Cannot override rule "+t+" because it is not declared in "+e,r)}function _u(t,e,r){return le("Cannot extend rule "+t+" because it is not declared in "+e,r)}function Ri(t,e,r,n){let s="Duplicate declaration for rule '"+t+"' in grammar '"+e+"'";return e!==r&&(s+=" (originally declared in '"+r+"')"),le(s,n)}function vo(t,e,r,n){return le("Wrong number of parameters for rule "+t+" (expected "+e+", got "+r+")",n)}function Au(t,e,r,n){return le("Wrong number of arguments for rule "+t+" (expected "+e+", got "+r+")",n)}function Ni(t,e,r){return le("Duplicate parameter names in rule "+t+": "+e.join(", "),r)}function xu(t,e){return le("Invalid parameter to rule "+t+": "+e+" has arity "+e.getArity()+", but parameter expressions must have arity 1",e.source)}const Iu="NOTE: A _syntactic rule_ is a rule whose name begins with a capital letter. See https://ohmjs.org/d/svl for more details.";function ku(t,e){return le("Cannot apply syntactic rule "+t+" from here (inside a lexical context)",e.source)}function Eu(t){const{ruleName:e}=t;return le(`applySyntactic is for syntactic rules, but '${e}' is a lexical rule. `+Iu,t.source)}function Ou(t){return le("applySyntactic is not required here (in a syntactic context)",t.source)}function Fi(t,e){return le("Incorrect argument type: expected "+t,e.source)}function Cu(t){return le("'...' can appear at most once in a rule body",t.source)}function Tu(t){const e=t._node;It(e&&e.isNonterminal()&&e.ctorName==="escapeChar_unicodeCodePoint");const r=t.children.slice(1,-1).map(s=>s.source),n=r[0].coverageWith(...r.slice(1));return le(`U+${n.contents} is not a valid Unicode code point`,n)}function wo(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(`
1
+ var oo=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function pu(t){if(Object.prototype.hasOwnProperty.call(t,"__esModule"))return t;var e=t.default;if(typeof e=="function"){var r=function n(){return this instanceof n?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};r.prototype=e.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(t).forEach(function(n){var s=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(r,n,s.get?s:{enumerable:!0,get:function(){return t[n]}})}),r}function De(t){const e=t||"";return function(){throw new Error("this method "+e+" is abstract! (it has no implementation in class "+this.constructor.name+")")}}function It(t,e){if(!t)throw new Error(e||"Assertion failed")}function us(t,e,r){let n;Object.defineProperty(t,e,{get(){return n||(n=r.call(this)),n}})}function co(t,e){const r=[];for(;e-- >0;)r.push(t());return r}function uo(t,e){return new Array(e+1).join(t)}function Fn(t,e){return co(()=>t,e)}function ls(t){const e=[];for(let r=0;r<t.length;r++){const n=t[r];t.lastIndexOf(n)!==r&&e.indexOf(n)<0&&e.push(n)}return e}function lo(t){const e=[];return t.forEach(r=>{e.indexOf(r)<0&&e.push(r)}),e}function Nt(t){const e=t[0];return e===e.toUpperCase()}function ho(t){return!Nt(t)}function fo(t,e,r){return t.length<e?uo(" ",e-t.length)+t:t}function Bt(){this.strings=[]}Bt.prototype.append=function(t){this.strings.push(t)};Bt.prototype.contents=function(){return this.strings.join("")};const Vn=t=>String.fromCodePoint(parseInt(t,16));function po(t){if(t.charAt(0)==="\\")switch(t.charAt(1)){case"b":return"\b";case"f":return"\f";case"n":return`
2
+ `;case"r":return"\r";case"t":return" ";case"v":return"\v";case"x":return Vn(t.slice(2,4));case"u":return t.charAt(2)==="{"?Vn(t.slice(3,-1)):Vn(t.slice(2,6));default:return t.charAt(1)}else return t}function Zs(t){if(t==null)return String(t);const e=Object.prototype.toString.call(t);try{let r;return t.constructor&&t.constructor.name?r=t.constructor.name:e.indexOf("[object ")===0?r=e.slice(8,-1):r=typeof t,r+": "+JSON.stringify(String(t))}catch{return e}}function mo(t,e="unexpected null value"){if(t==null)throw new Error(e);return t}const mu=Object.freeze(Object.defineProperty({__proto__:null,StringBuffer:Bt,abstract:De,assert:It,checkNotNull:mo,copyWithoutDuplicates:lo,defineLazyProperty:us,getDuplicates:ls,isLexical:ho,isSyntactic:Nt,padLeft:fo,repeat:Fn,repeatFn:co,repeatStr:uo,unescapeCodePoint:po,unexpectedObjToString:Zs},Symbol.toStringTag,{value:"Module"})),go=t=>new RegExp(String.raw`\p{${t}}`,"u"),ds=Object.fromEntries(["Cc","Cf","Cn","Co","Cs","Ll","Lm","Lo","Lt","Lu","Mc","Me","Mn","Nd","Nl","No","Pc","Pd","Pe","Pf","Pi","Po","Ps","Sc","Sk","Sm","So","Zl","Zp","Zs"].map(t=>[t,go(t)]));ds.Ltmo=/\p{Lt}|\p{Lm}|\p{Lo}/u;const Ci=Object.fromEntries(["XID_Start","XID_Continue","White_Space"].map(t=>[t,go(t)]));class z{constructor(){if(this.constructor===z)throw new Error("PExpr cannot be instantiated -- it's abstract")}withSource(e){return e&&(this.source=e.trimmed()),this}}const Te=Object.create(z.prototype),Re=Object.create(z.prototype);class Oe extends z{constructor(e){super(),this.obj=e}}class Ne extends z{constructor(e,r){super(),this.from=e,this.to=r,this.matchCodePoint=e.length>1||r.length>1}}class Fe extends z{constructor(e){super(),this.index=e}}class be extends z{constructor(e){super(),this.terms=e}}class Ln extends be{constructor(e,r,n){const s=e.rules[r].body;super([n,s]),this.superGrammar=e,this.name=r,this.body=n}}class jn extends be{constructor(e,r,n,s){const i=e.rules[r].body;super([...n,i,...s]),this.superGrammar=e,this.ruleName=r,this.expansionPos=n.length}}class Ae extends z{constructor(e){super(),this.factors=e}}class Me extends z{constructor(e){super(),this.expr=e}}class zt extends Me{}class ar extends Me{}class mt extends Me{}zt.prototype.operator="*";ar.prototype.operator="+";mt.prototype.operator="?";zt.prototype.minNumMatches=0;ar.prototype.minNumMatches=1;mt.prototype.minNumMatches=0;zt.prototype.maxNumMatches=Number.POSITIVE_INFINITY;ar.prototype.maxNumMatches=Number.POSITIVE_INFINITY;mt.prototype.maxNumMatches=1;class ke extends z{constructor(e){super(),this.expr=e}}class Pe extends z{constructor(e){super(),this.expr=e}}class qe extends z{constructor(e){super(),this.expr=e}}class X extends z{constructor(e,r=[]){super(),this.ruleName=e,this.args=r}isSyntactic(){return Nt(this.ruleName)}toMemoKey(){return this._memoKey||Object.defineProperty(this,"_memoKey",{value:this.toString()}),this._memoKey}}class Ee extends z{constructor(e){if(super(),this.categoryOrProp=e,e in ds)this.pattern=ds[e];else if(e in Ci)this.pattern=Ci[e];else throw new Error(`Invalid Unicode category or property name: ${JSON.stringify(e)}`)}}function le(t,e){let r;return e?(r=new Error(e.getLineAndColumnMessage()+t),r.shortMessage=t,r.interval=e):r=new Error(t),r}function hs(){return le("Interval sources don't match")}function gu(t){const e=new Error;return Object.defineProperty(e,"message",{enumerable:!0,get(){return t.message}}),Object.defineProperty(e,"shortMessage",{enumerable:!0,get(){return"Expected "+t.getExpectedText()}}),e.interval=t.getInterval(),e}function yu(t,e,r){const n=e?`Grammar ${t} is not declared in namespace '${e}'`:"Undeclared grammar "+t;return le(n,r)}function bu(t,e){return le("Grammar "+t.name+" is already declared in this namespace")}function vu(t){return le(`Grammar '${t.name}' does not support incremental parsing`)}function yo(t,e,r){return le("Rule "+t+" is not declared in grammar "+e,r)}function wu(t,e,r){return le("Cannot override rule "+t+" because it is not declared in "+e,r)}function Su(t,e,r){return le("Cannot extend rule "+t+" because it is not declared in "+e,r)}function Ti(t,e,r,n){let s="Duplicate declaration for rule '"+t+"' in grammar '"+e+"'";return e!==r&&(s+=" (originally declared in '"+r+"')"),le(s,n)}function bo(t,e,r,n){return le("Wrong number of parameters for rule "+t+" (expected "+e+", got "+r+")",n)}function _u(t,e,r,n){return le("Wrong number of arguments for rule "+t+" (expected "+e+", got "+r+")",n)}function Ri(t,e,r){return le("Duplicate parameter names in rule "+t+": "+e.join(", "),r)}function Au(t,e){return le("Invalid parameter to rule "+t+": "+e+" has arity "+e.getArity()+", but parameter expressions must have arity 1",e.source)}const xu="NOTE: A _syntactic rule_ is a rule whose name begins with a capital letter. See https://ohmjs.org/d/svl for more details.";function Iu(t,e){return le("Cannot apply syntactic rule "+t+" from here (inside a lexical context)",e.source)}function ku(t){const{ruleName:e}=t;return le(`applySyntactic is for syntactic rules, but '${e}' is a lexical rule. `+xu,t.source)}function Eu(t){return le("applySyntactic is not required here (in a syntactic context)",t.source)}function Ni(t,e){return le("Incorrect argument type: expected "+t,e.source)}function Ou(t){return le("'...' can appear at most once in a rule body",t.source)}function Cu(t){const e=t._node;It(e&&e.isNonterminal()&&e.ctorName==="escapeChar_unicodeCodePoint");const r=t.children.slice(1,-1).map(s=>s.source),n=r[0].coverageWith(...r.slice(1));return le(`U+${n.contents} is not a valid Unicode code point`,n)}function vo(t,e){const r=e.length>0?e[e.length-1].args:[];let s="Nullable expression "+t.expr.substituteParams(r)+" is not allowed inside '"+t.operator+"' (possible infinite loop)";if(e.length>0){const i=e.map(a=>new X(a.ruleName,a.args)).join(`
3
3
  `);s+=`
4
4
  Application stack (most recent application last):
5
- `+i}return le(s,t.expr.source)}function So(t,e,r,n){return le("Rule "+t+" involves an alternation which has inconsistent arity (expected "+e+", got "+r+")",n.source)}function Ru(t){const e=t.map(r=>r.message);return le(["Errors:"].concat(e).join(`
6
- - `),t[0].interval)}function Nu(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(`
5
+ `+i}return le(s,t.expr.source)}function wo(t,e,r,n){return le("Rule "+t+" involves an alternation which has inconsistent arity (expected "+e+", got "+r+")",n.source)}function Tu(t){const e=t.map(r=>r.message);return le(["Errors:"].concat(e).join(`
6
+ - `),t[0].interval)}function Ru(t,e,r,n){let s=n.slice(0,-1).map(c=>{const u=" "+c[0].name+" > "+c[1];return c.length===3?u+" for '"+c[2]+"'":u}).join(`
7
7
  `);s+=`
8
8
  `+e+" > "+t;let i="";t==="_iter"&&(i=[`
9
9
  NOTE: as of Ohm v16, there is no default action for iteration nodes — see `," https://ohmjs.org/d/dsa for details."].join(`
10
10
  `));const a=[`Missing semantic action for '${t}' in ${r} '${e}'.${i}`,"Action stack (most recent call last):",s].join(`
11
- `),o=le(a);return o.name="missingSemanticAction",o}function Fu(t){if(t.length===1)throw t[0];if(t.length>1)throw Ru(t)}function Lu(t){let e=0;return t.map(n=>{const s=n.toString();return e=Math.max(e,s.length),s}).map(n=>po(n,e))}function Li(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 ju(...t){const e=this,{offset:r}=e,{repeatStr:n}=gu,s=new Bt;s.append("Line "+e.lineNum+", col "+e.colNum+`:
12
- `);const i=Lu([e.prevLine==null?0:e.lineNum-1,e.lineNum,e.nextLine==null?0:e.lineNum+1]),a=(d,l,f)=>{s.append(f+i[d]+" | "+l+`
13
- `)};e.prevLine!=null&&a(0,e.prevLine," "),a(1,e.line,"> ");const o=e.line.length;let c=n(" ",o+1);for(let d=0;d<t.length;++d){let l=t[d][0],f=t[d][1];It(l>=0&&l<=f,"range start must be >= 0 and <= end");const y=r-e.colNum+1;l=Math.max(0,l-y),f=Math.min(f-y,o),c=Li(c,n("~",f-l),l)}const u=2+i[1].length+3;return s.append(n(" ",u)),c=Li(c,"^",e.colNum-1),s.append(c.replace(/ +$/,"")+`
14
- `),e.nextLine!=null&&a(2,e.nextLine," "),s.contents()}let ps=[];function _o(t){ps.push(t)}function Du(t){ps.forEach(e=>{e(t)}),ps=null}function Qs(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===`
11
+ `),o=le(a);return o.name="missingSemanticAction",o}function Nu(t){if(t.length===1)throw t[0];if(t.length>1)throw Tu(t)}function Fu(t){let e=0;return t.map(n=>{const s=n.toString();return e=Math.max(e,s.length),s}).map(n=>fo(n,e))}function Fi(t,e,r){const n=t.length,s=t.slice(0,r),i=t.slice(r+e.length);return(s+e+i).substr(0,n)}function Lu(...t){const e=this,{offset:r}=e,{repeatStr:n}=mu,s=new Bt;s.append("Line "+e.lineNum+", col "+e.colNum+`:
12
+ `);const i=Fu([e.prevLine==null?0:e.lineNum-1,e.lineNum,e.nextLine==null?0:e.lineNum+1]),a=(d,l,f)=>{s.append(f+i[d]+" | "+l+`
13
+ `)};e.prevLine!=null&&a(0,e.prevLine," "),a(1,e.line,"> ");const o=e.line.length;let c=n(" ",o+1);for(let d=0;d<t.length;++d){let l=t[d][0],f=t[d][1];It(l>=0&&l<=f,"range start must be >= 0 and <= end");const y=r-e.colNum+1;l=Math.max(0,l-y),f=Math.min(f-y,o),c=Fi(c,n("~",f-l),l)}const u=2+i[1].length+3;return s.append(n(" ",u)),c=Fi(c,"^",e.colNum-1),s.append(c.replace(/ +$/,"")+`
14
+ `),e.nextLine!=null&&a(2,e.nextLine," "),s.contents()}let fs=[];function So(t){fs.push(t)}function ju(t){fs.forEach(e=>{e(t)}),fs=null}function Js(t,e){let r=1,n=1,s=0,i=0,a=null,o=null,c=-1;for(;s<e;){const l=t.charAt(s++);l===`
15
15
  `?(r++,n=1,c=i,i=s):l!=="\r"&&n++}let u=t.indexOf(`
16
16
  `,i);if(u===-1)u=t.length;else{const l=t.indexOf(`
17
- `,u+1);a=l===-1?t.slice(u):t.slice(u,l),a=a.replace(/^\r?\n/,"").replace(/\r$/,"")}c>=0&&(o=t.slice(c,i).replace(/\r?\n$/,""));const d=t.slice(i,u).replace(/\r$/,"");return{offset:e,lineNum:r,colNum:n,line:d,prevLine:o,nextLine:a,toString:ju}}function Ys(t,e,...r){return Qs(t,e).toString(...r)}const ji=(()=>{let t=0;return e=>""+e+t++})();class Ce{constructor(e,r,n){Object.defineProperty(this,"_sourceString",{value:e,configurable:!1,enumerable:!1,writable:!1}),this.startIdx=r,this.endIdx=n}get sourceString(){return this._sourceString}get contents(){return this._contents===void 0&&(this._contents=this.sourceString.slice(this.startIdx,this.endIdx)),this._contents}get length(){return this.endIdx-this.startIdx}coverageWith(...e){return Ce.coverage(...e,this)}collapsedLeft(){return new Ce(this.sourceString,this.startIdx,this.startIdx)}collapsedRight(){return new Ce(this.sourceString,this.endIdx,this.endIdx)}getLineAndColumn(){return Qs(this.sourceString,this.startIdx)}getLineAndColumnMessage(){const e=[this.startIdx,this.endIdx];return Ys(this.sourceString,this.startIdx,e)}minus(e){if(this.sourceString!==e.sourceString)throw fs();return this.startIdx===e.startIdx&&this.endIdx===e.endIdx?[]:this.startIdx<e.startIdx&&e.endIdx<this.endIdx?[new Ce(this.sourceString,this.startIdx,e.startIdx),new Ce(this.sourceString,e.endIdx,this.endIdx)]:this.startIdx<e.endIdx&&e.endIdx<this.endIdx?[new Ce(this.sourceString,e.endIdx,this.endIdx)]:this.startIdx<e.startIdx&&e.startIdx<this.endIdx?[new Ce(this.sourceString,this.startIdx,e.startIdx)]:[this]}relativeTo(e){if(this.sourceString!==e.sourceString)throw fs();return It(this.startIdx>=e.startIdx&&this.endIdx<=e.endIdx,"other interval does not cover this one"),new Ce(this.sourceString,this.startIdx-e.startIdx,this.endIdx-e.startIdx)}trimmed(){const{contents:e}=this,r=this.startIdx+e.match(/^\s*/)[0].length,n=this.endIdx-e.match(/\s*$/)[0].length;return new Ce(this.sourceString,r,n)}subInterval(e,r){const n=this.startIdx+e;return new Ce(this.sourceString,n,n+r)}}Ce.coverage=function(t,...e){let{startIdx:r,endIdx:n}=t;for(const s of e){if(s.sourceString!==t.sourceString)throw fs();r=Math.min(r,s.startIdx),n=Math.max(n,s.endIdx)}return new Ce(t.sourceString,r,n)};const Mu=65535,Pu=1114111;class Mn{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>Mu&&(this.pos+=1),this.examinedLength=Math.max(this.examinedLength,this.pos),e}matchString(e,r){let n;if(r){for(n=0;n<e.length;n++){const s=this.next(),i=e[n];if(s==null||s.toUpperCase()!==i.toUpperCase())return!1}return!0}for(n=0;n<e.length;n++)if(this.next()!==e[n])return!1;return!0}sourceSlice(e,r){return this.source.slice(e,r)}interval(e,r){return new Ce(this.source,e,r||this.pos)}}class Ao{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()&&(ls(this,"message",function(){const c="Expected "+this.getExpectedText();return Ys(this.input,this.getRightmostFailurePosition())+c}),ls(this,"shortMessage",function(){const c="expected "+this.getExpectedText(),u=Qs(this.input,this.getRightmostFailurePosition());return"Line "+u.lineNum+", col "+u.colNum+": "+c}))}succeeded(){return!!this._cst}failed(){return!this.succeeded()}getRightmostFailurePosition(){return this._rightmostFailurePosition}getRightmostFailures(){if(!this._rightmostFailures){this.matcher.setInput(this.input);const e=this.matcher._match(this.startExpr,{tracing:!1,positionToRecordFailures:this.getRightmostFailurePosition()});this._rightmostFailures=e.getRightmostFailures()}return this._rightmostFailures}toString(){return this.succeeded()?"[match succeeded]":"[match failed at position "+this.getRightmostFailurePosition()+"]"}getExpectedText(){if(this.succeeded())throw new Error("cannot get expected text of a successful MatchResult");const e=new Bt;let r=this.getRightmostFailures();r=r.filter(n=>!n.isFluffy());for(let n=0;n<r.length;n++)n>0&&(n===r.length-1?e.append(r.length>2?", or ":" or "):e.append(", ")),e.append(r[n].toString());return e.contents()}getInterval(){const e=this.getRightmostFailurePosition();return new Ce(this.input,e,e)}}class $u{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 qu="✗",Uu="✓",Bu="⋅",zu="⇒",Vu="␉",Wu="␊",Hu="␍",ms={succeeded:1,isRootNode:2,isImplicitSpaces:4,isMemoized:8,isHeadOfLeftRecursion:16,terminatesLR:32};function Gu(t){return Ln(" ",t).join("")}function Ku(t,e,r){const n=xo(t.slice(e,e+r));return n.length<r?n+Ln(" ",r-n.length).join(""):n}function xo(t){return typeof t=="string"?t.replace(/ /g,Bu).replace(/\t/g,Vu).replace(/\n/g,Wu).replace(/\r/g,Hu):String(t)}class vt{constructor(e,r,n,s,i,a,o){this.input=e,this.pos=this.pos1=r,this.pos2=n,this.source=new Ce(e,r,n),this.expr=s,this.bindings=a,this.children=o||[],this.terminatingLREntry=null,this._flags=i?ms.succeeded:0}get displayString(){return this.expr.toDisplayString()}clone(){return this.cloneWithExpr(this.expr)}cloneWithExpr(e){const r=new vt(this.input,this.pos,this.pos2,e,this.succeeded,this.bindings,this.children);return r.isHeadOfLeftRecursion=this.isHeadOfLeftRecursion,r.isImplicitSpaces=this.isImplicitSpaces,r.isMemoized=this.isMemoized,r.isRootNode=this.isRootNode,r.terminatesLR=this.terminatesLR,r.terminatingLREntry=this.terminatingLREntry,r}recordLRTermination(e,r){this.terminatingLREntry=new vt(this.input,this.pos,this.pos2,this.expr,!1,[r],[e]),this.terminatingLREntry.terminatesLR=!0}walk(e,r){let n=e;typeof n=="function"&&(n={enter:n});function s(i,a,o){let c=!0;n.enter&&n.enter.call(r,i,a,o)===vt.prototype.SKIP&&(c=!1),c&&(i.children.forEach(u=>{s(u,i,o+1)}),n.exit&&n.exit.call(r,i,a,o))}this.isRootNode?this.children.forEach(i=>{s(i,null,0)}):s(this,null,0)}toString(){const e=new Bt;return this.walk((r,n,s)=>{if(!r)return this.SKIP;if(r.expr.constructor.name!=="Alt"){if(e.append(Ku(r.input,r.pos,10)+Gu(s*2+1)),e.append((r.succeeded?Uu:qu)+" "+r.displayString),r.isHeadOfLeftRecursion&&e.append(" (LR)"),r.succeeded){const a=xo(r.source.contents);e.append(" "+zu+" "),e.append(typeof a=="string"?'"'+a+'"':a)}e.append(`
18
- `)}}),e.contents()}}vt.prototype.SKIP={};Object.keys(ms).forEach(t=>{const e=ms[t];Object.defineProperty(vt.prototype,t,{get(){return(this._flags&e)!==0},set(r){r?this._flags|=e:this._flags&=~e}})});z.prototype.allowsSkippingPrecedingSpace=De("allowsSkippingPrecedingSpace");Te.allowsSkippingPrecedingSpace=Re.allowsSkippingPrecedingSpace=X.prototype.allowsSkippingPrecedingSpace=Oe.prototype.allowsSkippingPrecedingSpace=Ne.prototype.allowsSkippingPrecedingSpace=Ee.prototype.allowsSkippingPrecedingSpace=function(){return!0};be.prototype.allowsSkippingPrecedingSpace=Me.prototype.allowsSkippingPrecedingSpace=qe.prototype.allowsSkippingPrecedingSpace=Pe.prototype.allowsSkippingPrecedingSpace=ke.prototype.allowsSkippingPrecedingSpace=Fe.prototype.allowsSkippingPrecedingSpace=Ae.prototype.allowsSkippingPrecedingSpace=function(){return!1};let dr;_o(t=>{dr=t});let Yr;z.prototype.assertAllApplicationsAreValid=function(t,e){Yr=0,this._assertAllApplicationsAreValid(t,e)};z.prototype._assertAllApplicationsAreValid=De("_assertAllApplicationsAreValid");Te._assertAllApplicationsAreValid=Re._assertAllApplicationsAreValid=Oe.prototype._assertAllApplicationsAreValid=Ne.prototype._assertAllApplicationsAreValid=Fe.prototype._assertAllApplicationsAreValid=Ee.prototype._assertAllApplicationsAreValid=function(t,e){};qe.prototype._assertAllApplicationsAreValid=function(t,e){Yr++,this.expr._assertAllApplicationsAreValid(t,e),Yr--};be.prototype._assertAllApplicationsAreValid=function(t,e){for(let r=0;r<this.terms.length;r++)this.terms[r]._assertAllApplicationsAreValid(t,e)};Ae.prototype._assertAllApplicationsAreValid=function(t,e){for(let r=0;r<this.factors.length;r++)this.factors[r]._assertAllApplicationsAreValid(t,e)};Me.prototype._assertAllApplicationsAreValid=ke.prototype._assertAllApplicationsAreValid=Pe.prototype._assertAllApplicationsAreValid=function(t,e){this.expr._assertAllApplicationsAreValid(t,e)};X.prototype._assertAllApplicationsAreValid=function(t,e,r=!1){const n=e.rules[this.ruleName],s=Nt(t)&&Yr===0;if(!n)throw bo(this.ruleName,e.name,this.source);if(!r&&Nt(this.ruleName)&&!s)throw ku(this.ruleName,this);const i=this.args.length,a=n.formals.length;if(i!==a)throw Au(this.ruleName,a,i,this.source);const o=dr&&n===dr.rules.applySyntactic;if(dr&&n===dr.rules.caseInsensitive&&!(this.args[0]instanceof Oe))throw Fi('a Terminal (e.g. "abc")',this.args[0]);if(o){const u=this.args[0];if(!(u instanceof X))throw Fi("a syntactic rule application",u);if(!Nt(u.ruleName))throw Eu(u);if(s)throw Ou(this)}this.args.forEach(u=>{if(u._assertAllApplicationsAreValid(t,e,o),u.getArity()!==1)throw xu(this.ruleName,u)})};z.prototype.assertChoicesHaveUniformArity=De("assertChoicesHaveUniformArity");Te.assertChoicesHaveUniformArity=Re.assertChoicesHaveUniformArity=Oe.prototype.assertChoicesHaveUniformArity=Ne.prototype.assertChoicesHaveUniformArity=Fe.prototype.assertChoicesHaveUniformArity=qe.prototype.assertChoicesHaveUniformArity=Ee.prototype.assertChoicesHaveUniformArity=function(t){};be.prototype.assertChoicesHaveUniformArity=function(t){if(this.terms.length===0)return;const e=this.terms[0].getArity();for(let r=0;r<this.terms.length;r++){const n=this.terms[r];n.assertChoicesHaveUniformArity();const s=n.getArity();if(e!==s)throw So(t,e,s,n)}};jn.prototype.assertChoicesHaveUniformArity=function(t){const e=this.terms[0].getArity(),r=this.terms[1].getArity();if(e!==r)throw So(t,r,e,this.terms[0])};Ae.prototype.assertChoicesHaveUniformArity=function(t){for(let e=0;e<this.factors.length;e++)this.factors[e].assertChoicesHaveUniformArity(t)};Me.prototype.assertChoicesHaveUniformArity=function(t){this.expr.assertChoicesHaveUniformArity(t)};ke.prototype.assertChoicesHaveUniformArity=function(t){};Pe.prototype.assertChoicesHaveUniformArity=function(t){this.expr.assertChoicesHaveUniformArity(t)};X.prototype.assertChoicesHaveUniformArity=function(t){};z.prototype.assertIteratedExprsAreNotNullable=De("assertIteratedExprsAreNotNullable");Te.assertIteratedExprsAreNotNullable=Re.assertIteratedExprsAreNotNullable=Oe.prototype.assertIteratedExprsAreNotNullable=Ne.prototype.assertIteratedExprsAreNotNullable=Fe.prototype.assertIteratedExprsAreNotNullable=Ee.prototype.assertIteratedExprsAreNotNullable=function(t){};be.prototype.assertIteratedExprsAreNotNullable=function(t){for(let e=0;e<this.terms.length;e++)this.terms[e].assertIteratedExprsAreNotNullable(t)};Ae.prototype.assertIteratedExprsAreNotNullable=function(t){for(let e=0;e<this.factors.length;e++)this.factors[e].assertIteratedExprsAreNotNullable(t)};Me.prototype.assertIteratedExprsAreNotNullable=function(t){if(this.expr.assertIteratedExprsAreNotNullable(t),this.expr.isNullable(t))throw wo(this,[])};mt.prototype.assertIteratedExprsAreNotNullable=ke.prototype.assertIteratedExprsAreNotNullable=Pe.prototype.assertIteratedExprsAreNotNullable=qe.prototype.assertIteratedExprsAreNotNullable=function(t){this.expr.assertIteratedExprsAreNotNullable(t)};X.prototype.assertIteratedExprsAreNotNullable=function(t){this.args.forEach(e=>{e.assertIteratedExprsAreNotNullable(t)})};class Xs{constructor(e){this.matchLength=e}get ctorName(){throw new Error("subclass responsibility")}numChildren(){return this.children?this.children.length:0}childAt(e){if(this.children)return this.children[e]}indexOfChild(e){return this.children.indexOf(e)}hasChildren(){return this.numChildren()>0}hasNoChildren(){return!this.hasChildren()}onlyChild(){if(this.numChildren()!==1)throw new Error("cannot get only child of a node of type "+this.ctorName+" (it has "+this.numChildren()+" children)");return this.firstChild()}firstChild(){if(this.hasNoChildren())throw new Error("cannot get first child of a "+this.ctorName+" node, which has no children");return this.childAt(0)}lastChild(){if(this.hasNoChildren())throw new Error("cannot get last child of a "+this.ctorName+" node, which has no children");return this.childAt(this.numChildren()-1)}childBefore(e){const r=this.indexOfChild(e);if(r<0)throw new Error("Node.childBefore() called w/ an argument that is not a child");if(r===0)throw new Error("cannot get child before first child");return this.childAt(r-1)}childAfter(e){const r=this.indexOfChild(e);if(r<0)throw new Error("Node.childAfter() called w/ an argument that is not a child");if(r===this.numChildren()-1)throw new Error("cannot get child after last child");return this.childAt(r+1)}isTerminal(){return!1}isNonterminal(){return!1}isIteration(){return!1}isOptional(){return!1}}class Vt extends Xs{get ctorName(){return"_terminal"}isTerminal(){return!0}get primitiveValue(){throw new Error("The `primitiveValue` property was removed in Ohm v17.")}}class Zu extends Xs{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 fo(this.ctorName)}isSyntactic(){return Nt(this.ctorName)}}class Io extends Xs{constructor(e,r,n,s){super(n),this.children=e,this.childOffsets=r,this.optional=s}get ctorName(){return"_iter"}isIteration(){return!0}isOptional(){return this.optional}}z.prototype.eval=De("eval");Te.eval=function(t){const{inputStream:e}=t,r=e.pos,n=e.nextCodePoint();return n!==void 0?(t.pushBinding(new Vt(String.fromCodePoint(n).length),r),!0):(t.processFailure(r,this),!1)};Re.eval=function(t){const{inputStream:e}=t,r=e.pos;return e.atEnd()?(t.pushBinding(new Vt(0),r),!0):(t.processFailure(r,this),!1)};Oe.prototype.eval=function(t){const{inputStream:e}=t,r=e.pos;return e.matchString(this.obj)?(t.pushBinding(new Vt(this.obj.length),r),!0):(t.processFailure(r,this),!1)};Ne.prototype.eval=function(t){const{inputStream:e}=t,r=e.pos,n=this.matchCodePoint?e.nextCodePoint():e.nextCharCode();return n!==void 0&&this.from.codePointAt(0)<=n&&n<=this.to.codePointAt(0)?(t.pushBinding(new Vt(String.fromCodePoint(n).length),r),!0):(t.processFailure(r,this),!1)};Fe.prototype.eval=function(t){return t.eval(t.currentApplication().args[this.index])};qe.prototype.eval=function(t){t.enterLexifiedContext();const e=t.eval(this.expr);return t.exitLexifiedContext(),e};be.prototype.eval=function(t){for(let e=0;e<this.terms.length;e++)if(t.eval(this.terms[e]))return!0;return!1};Ae.prototype.eval=function(t){for(let e=0;e<this.factors.length;e++){const r=this.factors[e];if(!t.eval(r))return!1}return!0};Me.prototype.eval=function(t){const{inputStream:e}=t,r=e.pos,n=this.getArity(),s=[],i=[];for(;s.length<n;)s.push([]),i.push([]);let a=0,o=r,c;for(;a<this.maxNumMatches&&t.eval(this.expr);){if(e.pos===o)throw wo(this,t._applicationStack);o=e.pos,a++;const f=t._bindings.splice(t._bindings.length-n,n),y=t._bindingOffsets.splice(t._bindingOffsets.length-n,n);for(c=0;c<f.length;c++)s[c].push(f[c]),i[c].push(y[c])}if(a<this.minNumMatches)return!1;let u=t.posToOffset(r),d=0;if(a>0){const f=s[n-1],y=i[n-1],b=y[y.length-1]+f[f.length-1].matchLength;u=i[0][0],d=b-u}const l=this instanceof mt;for(c=0;c<s.length;c++)t._bindings.push(new Io(s[c],i[c],d,l)),t._bindingOffsets.push(u);return!0};ke.prototype.eval=function(t){const{inputStream:e}=t,r=e.pos;t.pushFailuresInfo();const n=t.eval(this.expr);return t.popFailuresInfo(),n?(t.processFailure(r,this),!1):(e.pos=r,!0)};Pe.prototype.eval=function(t){const{inputStream:e}=t,r=e.pos;return t.eval(this.expr)?(e.pos=r,!0):!1};X.prototype.eval=function(t){const e=t.currentApplication(),r=e?e.args:[],n=this.substituteParams(r),s=t.getCurrentPosInfo();if(s.isActive(n))return n.handleCycle(t);const i=n.toMemoKey(),a=s.memo[i];if(a&&s.shouldUseMemoizedResult(a)){if(t.hasNecessaryInfo(a))return t.useMemoizedResult(t.inputStream.pos,a);delete s.memo[i]}return n.reallyEval(t)};X.prototype.handleCycle=function(t){const e=t.getCurrentPosInfo(),{currentLeftRecursion:r}=e,n=this.toMemoKey();let s=e.memo[n];return r&&r.headApplication.toMemoKey()===n?s.updateInvolvedApplicationMemoKeys():s||(s=e.memoize(n,{matchLength:0,examinedLength:0,value:!1,rightmostFailureOffset:-1}),e.startLeftRecursion(this,s)),t.useMemoizedResult(t.inputStream.pos,s)};X.prototype.reallyEval=function(t){const{inputStream:e}=t,r=e.pos,n=t.getCurrentPosInfo(),s=t.grammar.rules[this.ruleName],{body:i}=s,{description:a}=s;t.enterApplication(n,this),a&&t.pushFailuresInfo();const o=e.examinedLength;e.examinedLength=0;let c=this.evalOnce(i,t);const u=n.currentLeftRecursion,d=this.toMemoKey(),l=u&&u.headApplication.toMemoKey()===d;let f;t.doNotMemoize?t.doNotMemoize=!1:l?(c=this.growSeedResult(i,t,r,u,c),n.endLeftRecursion(),f=u,f.examinedLength=e.examinedLength-r,f.rightmostFailureOffset=t._getRightmostFailureOffset(),n.memoize(d,f)):(!u||!u.isInvolved(d))&&(f=n.memoize(d,{matchLength:e.pos-r,examinedLength:e.examinedLength-r,value:c,failuresAtRightmostPosition:t.cloneRecordedFailures(),rightmostFailureOffset:t._getRightmostFailureOffset()}));const y=!!c;if(a&&(t.popFailuresInfo(),y||t.processFailure(r,this),f&&(f.failuresAtRightmostPosition=t.cloneRecordedFailures(),f.rightmostFailureOffset=t._getRightmostFailureOffset())),t.isTracing()&&f){const b=t.getTraceEntry(r,this,y,y?[c]:[]);l&&(It(b.terminatingLREntry!=null||!y),b.isHeadOfLeftRecursion=!0),f.traceEntry=b}return e.examinedLength=Math.max(e.examinedLength,o),t.exitApplication(n,c),y};X.prototype.evalOnce=function(t,e){const{inputStream:r}=e,n=r.pos;if(e.eval(t)){const s=t.getArity(),i=e._bindings.splice(e._bindings.length-s,s),a=e._bindingOffsets.splice(e._bindingOffsets.length-s,s),o=r.pos-n;return new Zu(this.ruleName,i,a,o)}else return!1};X.prototype.growSeedResult=function(t,e,r,n,s){if(!s)return!1;const{inputStream:i}=e;for(;;){if(n.matchLength=i.pos-r,n.value=s,n.failuresAtRightmostPosition=e.cloneRecordedFailures(),e.isTracing()){const a=e.trace[e.trace.length-1];n.traceEntry=new vt(e.input,r,i.pos,this,!0,[s],[a.clone()])}if(i.pos=r,s=this.evalOnce(t,e),i.pos-r<=n.matchLength)break;e.isTracing()&&e.trace.splice(-2,1)}return e.isTracing()&&n.traceEntry.recordLRTermination(e.trace.pop(),s),i.pos=r+n.matchLength,n.value};Ee.prototype.eval=function(t){const{inputStream:e}=t,r=e.pos,n=e.nextCodePoint();if(n!==void 0&&n<=Pu){const s=String.fromCodePoint(n);if(this.pattern.test(s))return t.pushBinding(new Vt(s.length),r),!0}return t.processFailure(r,this),!1};z.prototype.getArity=De("getArity");Te.getArity=Re.getArity=Oe.prototype.getArity=Ne.prototype.getArity=Fe.prototype.getArity=X.prototype.getArity=Ee.prototype.getArity=function(){return 1};be.prototype.getArity=function(){return this.terms.length===0?0:this.terms[0].getArity()};Ae.prototype.getArity=function(){let t=0;for(let e=0;e<this.factors.length;e++)t+=this.factors[e].getArity();return t};Me.prototype.getArity=function(){return this.expr.getArity()};ke.prototype.getArity=function(){return 0};Pe.prototype.getArity=qe.prototype.getArity=function(){return this.expr.getArity()};function Qe(t,e){const r={};if(t.source&&e){const n=t.source.relativeTo(e);r.sourceInterval=[n.startIdx,n.endIdx]}return r}z.prototype.outputRecipe=De("outputRecipe");Te.outputRecipe=function(t,e){return["any",Qe(this,e)]};Re.outputRecipe=function(t,e){return["end",Qe(this,e)]};Oe.prototype.outputRecipe=function(t,e){return["terminal",Qe(this,e),this.obj]};Ne.prototype.outputRecipe=function(t,e){return["range",Qe(this,e),this.from,this.to]};Fe.prototype.outputRecipe=function(t,e){return["param",Qe(this,e),this.index]};be.prototype.outputRecipe=function(t,e){return["alt",Qe(this,e)].concat(this.terms.map(r=>r.outputRecipe(t,e)))};jn.prototype.outputRecipe=function(t,e){return this.terms[0].outputRecipe(t,e)};Dn.prototype.outputRecipe=function(t,e){const r=this.terms.slice(0,this.expansionPos),n=this.terms.slice(this.expansionPos+1);return["splice",Qe(this,e),r.map(s=>s.outputRecipe(t,e)),n.map(s=>s.outputRecipe(t,e))]};Ae.prototype.outputRecipe=function(t,e){return["seq",Qe(this,e)].concat(this.factors.map(r=>r.outputRecipe(t,e)))};zt.prototype.outputRecipe=ar.prototype.outputRecipe=mt.prototype.outputRecipe=ke.prototype.outputRecipe=Pe.prototype.outputRecipe=qe.prototype.outputRecipe=function(t,e){return[this.constructor.name.toLowerCase(),Qe(this,e),this.expr.outputRecipe(t,e)]};X.prototype.outputRecipe=function(t,e){return["app",Qe(this,e),this.ruleName,this.args.map(r=>r.outputRecipe(t,e))]};Ee.prototype.outputRecipe=function(t,e){return["unicodeChar",Qe(this,e),this.categoryOrProp]};z.prototype.introduceParams=De("introduceParams");Te.introduceParams=Re.introduceParams=Oe.prototype.introduceParams=Ne.prototype.introduceParams=Fe.prototype.introduceParams=Ee.prototype.introduceParams=function(t){return this};be.prototype.introduceParams=function(t){return this.terms.forEach((e,r,n)=>{n[r]=e.introduceParams(t)}),this};Ae.prototype.introduceParams=function(t){return this.factors.forEach((e,r,n)=>{n[r]=e.introduceParams(t)}),this};Me.prototype.introduceParams=ke.prototype.introduceParams=Pe.prototype.introduceParams=qe.prototype.introduceParams=function(t){return this.expr=this.expr.introduceParams(t),this};X.prototype.introduceParams=function(t){const e=t.indexOf(this.ruleName);if(e>=0){if(this.args.length>0)throw new Error("Parameterized rules cannot be passed as arguments to another rule.");return new Fe(e).withSource(this.source)}else return this.args.forEach((r,n,s)=>{s[n]=r.introduceParams(t)}),this};z.prototype.isNullable=function(t){return this._isNullable(t,Object.create(null))};z.prototype._isNullable=De("_isNullable");Te._isNullable=Ne.prototype._isNullable=Fe.prototype._isNullable=ar.prototype._isNullable=Ee.prototype._isNullable=function(t,e){return!1};Re._isNullable=function(t,e){return!0};Oe.prototype._isNullable=function(t,e){return typeof this.obj=="string"?this.obj==="":!1};be.prototype._isNullable=function(t,e){return this.terms.length===0||this.terms.some(r=>r._isNullable(t,e))};Ae.prototype._isNullable=function(t,e){return this.factors.every(r=>r._isNullable(t,e))};zt.prototype._isNullable=mt.prototype._isNullable=ke.prototype._isNullable=Pe.prototype._isNullable=function(t,e){return!0};qe.prototype._isNullable=function(t,e){return this.expr._isNullable(t,e)};X.prototype._isNullable=function(t,e){const r=this.toMemoKey();if(!Object.prototype.hasOwnProperty.call(e,r)){const{body:n}=t.rules[this.ruleName],s=n.substituteParams(this.args);e[r]=!1,e[r]=s._isNullable(t,e)}return e[r]};z.prototype.substituteParams=De("substituteParams");Te.substituteParams=Re.substituteParams=Oe.prototype.substituteParams=Ne.prototype.substituteParams=Ee.prototype.substituteParams=function(t){return this};Fe.prototype.substituteParams=function(t){return go(t[this.index])};be.prototype.substituteParams=function(t){return new be(this.terms.map(e=>e.substituteParams(t)))};Ae.prototype.substituteParams=function(t){return new Ae(this.factors.map(e=>e.substituteParams(t)))};Me.prototype.substituteParams=ke.prototype.substituteParams=Pe.prototype.substituteParams=qe.prototype.substituteParams=function(t){return new this.constructor(this.expr.substituteParams(t))};X.prototype.substituteParams=function(t){if(this.args.length===0)return this;{const e=this.args.map(r=>r.substituteParams(t));return new X(this.ruleName,e)}};function Di(t){return/^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(t)}function ei(t){const e=Object.create(null);t.forEach(r=>{e[r]=(e[r]||0)+1}),Object.keys(e).forEach(r=>{if(e[r]<=1)return;let n=1;t.forEach((s,i)=>{s===r&&(t[i]=s+"_"+n++)})})}z.prototype.toArgumentNameList=De("toArgumentNameList");Te.toArgumentNameList=function(t,e){return["any"]};Re.toArgumentNameList=function(t,e){return["end"]};Oe.prototype.toArgumentNameList=function(t,e){return typeof this.obj=="string"&&/^[_a-zA-Z0-9]+$/.test(this.obj)?["_"+this.obj]:["$"+t]};Ne.prototype.toArgumentNameList=function(t,e){let r=this.from+"_to_"+this.to;return Di(r)||(r="_"+r),Di(r)||(r="$"+t),[r]};be.prototype.toArgumentNameList=function(t,e){const r=this.terms.map(i=>i.toArgumentNameList(t,!0)),n=[],s=r[0].length;for(let i=0;i<s;i++){const a=[];for(let c=0;c<this.terms.length;c++)a.push(r[c][i]);const o=ho(a);n.push(o.join("_or_"))}return e||ei(n),n};Ae.prototype.toArgumentNameList=function(t,e){let r=[];return this.factors.forEach(n=>{const s=n.toArgumentNameList(t,!0);r=r.concat(s),t+=s.length}),e||ei(r),r};Me.prototype.toArgumentNameList=function(t,e){const r=this.expr.toArgumentNameList(t,e).map(n=>n[n.length-1]==="s"?n+"es":n+"s");return e||ei(r),r};mt.prototype.toArgumentNameList=function(t,e){return this.expr.toArgumentNameList(t,e).map(r=>"opt"+r[0].toUpperCase()+r.slice(1))};ke.prototype.toArgumentNameList=function(t,e){return[]};Pe.prototype.toArgumentNameList=qe.prototype.toArgumentNameList=function(t,e){return this.expr.toArgumentNameList(t,e)};X.prototype.toArgumentNameList=function(t,e){return[this.ruleName]};Ee.prototype.toArgumentNameList=function(t,e){return["$"+t]};Fe.prototype.toArgumentNameList=function(t,e){return["param"+this.index]};z.prototype.toDisplayString=De("toDisplayString");be.prototype.toDisplayString=Ae.prototype.toDisplayString=function(){return this.source?this.source.trimmed().contents:"["+this.constructor.name+"]"};Te.toDisplayString=Re.toDisplayString=Me.prototype.toDisplayString=ke.prototype.toDisplayString=Pe.prototype.toDisplayString=qe.prototype.toDisplayString=Oe.prototype.toDisplayString=Ne.prototype.toDisplayString=Fe.prototype.toDisplayString=function(){return this.toString()};X.prototype.toDisplayString=function(){if(this.args.length>0){const t=this.args.map(e=>e.toDisplayString());return this.ruleName+"<"+t.join(",")+">"}else return this.ruleName};Ee.prototype.toDisplayString=function(){return"Unicode ["+this.categoryOrProp+"] character"};function Ju(t){return t==="description"||t==="string"||t==="code"}class Ue{constructor(e,r,n){if(!Ju(n))throw new Error("invalid Failure type: "+n);this.pexpr=e,this.text=r,this.type=n,this.fluffy=!1}getPExpr(){return this.pexpr}getText(){return this.text}getType(){return this.type}isDescription(){return this.type==="description"}isStringTerminal(){return this.type==="string"}isCode(){return this.type==="code"}isFluffy(){return this.fluffy}makeFluffy(){this.fluffy=!0}clearFluffy(){this.fluffy=!1}subsumes(e){return this.getText()===e.getText()&&this.type===e.type&&(!this.isFluffy()||this.isFluffy()&&e.isFluffy())}toString(){return this.type==="string"?JSON.stringify(this.getText()):this.getText()}clone(){const e=new Ue(this.pexpr,this.text,this.type);return this.isFluffy()&&e.makeFluffy(),e}toKey(){return this.toString()+"#"+this.type}}z.prototype.toFailure=De("toFailure");Te.toFailure=function(t){return new Ue(this,"any object","description")};Re.toFailure=function(t){return new Ue(this,"end of input","description")};Oe.prototype.toFailure=function(t){return new Ue(this,this.obj,"string")};Ne.prototype.toFailure=function(t){return new Ue(this,JSON.stringify(this.from)+".."+JSON.stringify(this.to),"code")};ke.prototype.toFailure=function(t){const e=this.expr===Te?"nothing":"not "+this.expr.toFailure(t);return new Ue(this,e,"description")};Pe.prototype.toFailure=function(t){return this.expr.toFailure(t)};X.prototype.toFailure=function(t){let{description:e}=t.rules[this.ruleName];return e||(e=(/^[aeiouAEIOU]/.test(this.ruleName)?"an":"a")+" "+this.ruleName),new Ue(this,e,"description")};Ee.prototype.toFailure=function(t){return new Ue(this,"a Unicode ["+this.categoryOrProp+"] character","description")};be.prototype.toFailure=function(t){const r="("+this.terms.map(n=>n.toFailure(t)).join(" or ")+")";return new Ue(this,r,"description")};Ae.prototype.toFailure=function(t){const r="("+this.factors.map(n=>n.toFailure(t)).join(" ")+")";return new Ue(this,r,"description")};Me.prototype.toFailure=function(t){const e="("+this.expr.toFailure(t)+this.operator+")";return new Ue(this,e,"description")};z.prototype.toString=De("toString");Te.toString=function(){return"any"};Re.toString=function(){return"end"};Oe.prototype.toString=function(){return JSON.stringify(this.obj)};Ne.prototype.toString=function(){return JSON.stringify(this.from)+".."+JSON.stringify(this.to)};Fe.prototype.toString=function(){return"$"+this.index};qe.prototype.toString=function(){return"#("+this.expr.toString()+")"};be.prototype.toString=function(){return this.terms.length===1?this.terms[0].toString():"("+this.terms.map(t=>t.toString()).join(" | ")+")"};Ae.prototype.toString=function(){return this.factors.length===1?this.factors[0].toString():"("+this.factors.map(t=>t.toString()).join(" ")+")"};Me.prototype.toString=function(){return this.expr+this.operator};ke.prototype.toString=function(){return"~"+this.expr};Pe.prototype.toString=function(){return"&"+this.expr};X.prototype.toString=function(){if(this.args.length>0){const t=this.args.map(e=>e.toString());return this.ruleName+"<"+t.join(",")+">"}else return this.ruleName};Ee.prototype.toString=function(){return"\\p{"+this.categoryOrProp+"}"};class ti extends z{constructor(e){super(),this.obj=e}_getString(e){const r=e.currentApplication().args[this.obj.index];return It(r instanceof Oe,"expected a Terminal expression"),r.obj}allowsSkippingPrecedingSpace(){return!0}eval(e){const{inputStream:r}=e,n=r.pos,s=this._getString(e);return r.matchString(s,!0)?(e.pushBinding(new Vt(s.length),n),!0):(e.processFailure(n,this),!1)}getArity(){return 1}substituteParams(e){return new ti(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 ko;_o(t=>{ko=t.rules.applySyntactic.body});const Hn=new X("spaces");class Qu{constructor(e,r,n){this.matcher=e,this.startExpr=r,this.grammar=e.grammar,this.input=e.getInput(),this.inputStream=new Mn(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(Hn),this.popBinding(),this.popFailuresInfo(),this.inputStream.pos}skipSpacesIfInSyntacticContext(){return this.inSyntacticContext()?this.skipSpaces():this.inputStream.pos}maybeSkipSpacesBefore(e){return e.allowsSkippingPrecedingSpace()&&e!==Hn?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 $u),r}processFailure(e,r){if(this.rightmostFailurePosition=Math.max(this.rightmostFailurePosition,e),this.recordedFailures&&e===this.positionToRecordFailures){const n=this.currentApplication();n&&(r=r.substituteParams(n.args)),this.recordFailure(r.toFailure(this.grammar),!1)}}recordFailure(e,r){const n=e.toKey();this.recordedFailures[n]?this.recordedFailures[n].isFluffy()&&!e.isFluffy()&&this.recordedFailures[n].clearFluffy():this.recordedFailures[n]=r?e.clone():e}recordFailures(e,r){Object.keys(e).forEach(n=>{this.recordFailure(e[n],r)})}cloneRecordedFailures(){if(!this.recordedFailures)return;const e=Object.create(null);return Object.keys(this.recordedFailures).forEach(r=>{e[r]=this.recordedFailures[r].clone()}),e}getRightmostFailurePosition(){return this.rightmostFailurePosition}_getRightmostFailureOffset(){return this.rightmostFailurePosition>=0?this.posToOffset(this.rightmostFailurePosition):-1}getMemoizedTraceEntry(e,r){const n=this.memoTable[e];if(n&&r instanceof X){const s=n.memo[r.toMemoKey()];if(s&&s.traceEntry){const i=s.traceEntry.cloneWithExpr(r);return i.isMemoized=!0,i}}return null}getTraceEntry(e,r,n,s){if(r instanceof X){const i=this.currentApplication(),a=i?i.args:[];r=r.substituteParams(a)}return this.getMemoizedTraceEntry(e,r)||new vt(this.input,e,this.inputStream.pos,r,n,s,this.trace)}isTracing(){return!!this.trace}hasNecessaryInfo(e){return this.trace&&!e.traceEntry?!1:this.recordedFailures&&this.inputStream.pos+e.rightmostFailureOffset===this.positionToRecordFailures?!!e.failuresAtRightmostPosition:!0}useMemoizedResult(e,r){this.trace&&this.trace.push(r.traceEntry);const n=this.inputStream.pos+r.rightmostFailureOffset;return this.rightmostFailurePosition=Math.max(this.rightmostFailurePosition,n),this.recordedFailures&&this.positionToRecordFailures===n&&r.failuresAtRightmostPosition&&this.recordFailures(r.failuresAtRightmostPosition,!0),this.inputStream.examinedLength=Math.max(this.inputStream.examinedLength,r.examinedLength+e),r.value?(this.inputStream.pos+=r.matchLength,this.pushBinding(r.value,e),!0):!1}eval(e){const{inputStream:r}=this,n=this._bindings.length,s=this.userData;let i;this.recordedFailures&&(i=this.recordedFailures,this.recordedFailures=Object.create(null));const a=r.pos,o=this.maybeSkipSpacesBefore(e);let c;this.trace&&(c=this.trace,this.trace=[]);const u=e.eval(this);if(this.trace){const d=this._bindings.slice(n),l=this.getTraceEntry(o,e,u,d);l.isImplicitSpaces=e===Hn,l.isRootNode=e===this.startExpr,c.push(l),this.trace=c}return u?this.recordedFailures&&r.pos===this.positionToRecordFailures&&Object.keys(this.recordedFailures).forEach(d=>{this.recordedFailures[d].makeFluffy()}):(r.pos=a,this.truncateBindings(n),this.userData=s),this.recordedFailures&&this.recordFailures(i,!1),e===ko&&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 Ao(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 Yu{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 wu(this.grammar);const s=new Qu(this,e,n.positionToRecordFailures);return n.tracing?s.getTrace():s.getMatchResult()}_getStartExpr(e){const r=e||this.grammar.defaultStartRule;if(!r)throw new Error("Missing start rule argument -- the grammar has no default start rule.");const n=this.grammar.parseApplication(r);return new Ae([n,Re])}}const hr=[],gs=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);class Mi{constructor(e,r,n){this._node=e,this.source=r,this._baseInterval=n,e.isNonterminal()&&It(r===n),this._childWrappers=[]}_forgetMemoizedResultFor(e){delete this._node[this._semantics.attributeKeys[e]],this.children.forEach(r=>{r._forgetMemoizedResultFor(e)})}child(e){if(!(0<=e&&e<this._node.numChildren()))return;let r=this._childWrappers[e];if(!r){const n=this._node.childAt(e),s=this._node.childOffsets[e],i=this._baseInterval.subInterval(s,n.matchLength),a=n.isNonterminal()?i:this._baseInterval;r=this._childWrappers[e]=this._semantics.wrap(n,i,a)}return r}_children(){for(let e=0;e<this._node.numChildren();e++)this.child(e);return this._childWrappers}isIteration(){return this._node.isIteration()}isTerminal(){return this._node.isTerminal()}isNonterminal(){return this._node.isNonterminal()}isSyntactic(){return this.isNonterminal()&&this._node.isSyntactic()}isLexical(){return this.isNonterminal()&&this._node.isLexical()}isOptional(){return this._node.isOptional()}iteration(e){const r=e||[],n=r.map(a=>a._node),s=new Io(n,[],-1,!1),i=this._semantics.wrap(s,null,null);return i._childWrappers=r,i}get children(){return this._children()}get ctorName(){return this._node.ctorName}get numChildren(){return this._node.numChildren()}get sourceString(){return this.source.contents}}class $e{constructor(e,r){const n=this;if(this.grammar=e,this.checkedActionDicts=!1,this.Wrapper=class extends(r?r.Wrapper:Mi){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:ji(s)})}else this.operations=Object.create(null),this.attributes=Object.create(null),this.attributeKeys=Object.create(null)}toString(){return"[semantics for "+this.grammar.name+"]"}checkActionDictsIfHaventAlready(){this.checkedActionDicts||(this.checkActionDicts(),this.checkedActionDicts=!0)}checkActionDicts(){let e;for(e in this.operations)this.operations[e].checkActionDict(this.grammar);for(e in this.attributes)this.attributes[e].checkActionDict(this.grammar)}toRecipe(e){function r(s){return s.super!==$e.BuiltInSemantics._getSemantics()}let n=`(function(g) {
17
+ `,u+1);a=l===-1?t.slice(u):t.slice(u,l),a=a.replace(/^\r?\n/,"").replace(/\r$/,"")}c>=0&&(o=t.slice(c,i).replace(/\r?\n$/,""));const d=t.slice(i,u).replace(/\r$/,"");return{offset:e,lineNum:r,colNum:n,line:d,prevLine:o,nextLine:a,toString:Lu}}function Qs(t,e,...r){return Js(t,e).toString(...r)}const Li=(()=>{let t=0;return e=>""+e+t++})();class Ce{constructor(e,r,n){Object.defineProperty(this,"_sourceString",{value:e,configurable:!1,enumerable:!1,writable:!1}),this.startIdx=r,this.endIdx=n}get sourceString(){return this._sourceString}get contents(){return this._contents===void 0&&(this._contents=this.sourceString.slice(this.startIdx,this.endIdx)),this._contents}get length(){return this.endIdx-this.startIdx}coverageWith(...e){return Ce.coverage(...e,this)}collapsedLeft(){return new Ce(this.sourceString,this.startIdx,this.startIdx)}collapsedRight(){return new Ce(this.sourceString,this.endIdx,this.endIdx)}getLineAndColumn(){return Js(this.sourceString,this.startIdx)}getLineAndColumnMessage(){const e=[this.startIdx,this.endIdx];return Qs(this.sourceString,this.startIdx,e)}minus(e){if(this.sourceString!==e.sourceString)throw hs();return this.startIdx===e.startIdx&&this.endIdx===e.endIdx?[]:this.startIdx<e.startIdx&&e.endIdx<this.endIdx?[new Ce(this.sourceString,this.startIdx,e.startIdx),new Ce(this.sourceString,e.endIdx,this.endIdx)]:this.startIdx<e.endIdx&&e.endIdx<this.endIdx?[new Ce(this.sourceString,e.endIdx,this.endIdx)]:this.startIdx<e.startIdx&&e.startIdx<this.endIdx?[new Ce(this.sourceString,this.startIdx,e.startIdx)]:[this]}relativeTo(e){if(this.sourceString!==e.sourceString)throw hs();return It(this.startIdx>=e.startIdx&&this.endIdx<=e.endIdx,"other interval does not cover this one"),new Ce(this.sourceString,this.startIdx-e.startIdx,this.endIdx-e.startIdx)}trimmed(){const{contents:e}=this,r=this.startIdx+e.match(/^\s*/)[0].length,n=this.endIdx-e.match(/\s*$/)[0].length;return new Ce(this.sourceString,r,n)}subInterval(e,r){const n=this.startIdx+e;return new Ce(this.sourceString,n,n+r)}}Ce.coverage=function(t,...e){let{startIdx:r,endIdx:n}=t;for(const s of e){if(s.sourceString!==t.sourceString)throw hs();r=Math.min(r,s.startIdx),n=Math.max(n,s.endIdx)}return new Ce(t.sourceString,r,n)};const Du=65535,Mu=1114111;class Dn{constructor(e){this.source=e,this.pos=0,this.examinedLength=0}atEnd(){const e=this.pos>=this.source.length;return this.examinedLength=Math.max(this.examinedLength,this.pos+1),e}next(){const e=this.source[this.pos++];return this.examinedLength=Math.max(this.examinedLength,this.pos),e}nextCharCode(){const e=this.next();return e&&e.charCodeAt(0)}nextCodePoint(){const e=this.source.slice(this.pos++).codePointAt(0);return e>Du&&(this.pos+=1),this.examinedLength=Math.max(this.examinedLength,this.pos),e}matchString(e,r){let n;if(r){for(n=0;n<e.length;n++){const s=this.next(),i=e[n];if(s==null||s.toUpperCase()!==i.toUpperCase())return!1}return!0}for(n=0;n<e.length;n++)if(this.next()!==e[n])return!1;return!0}sourceSlice(e,r){return this.source.slice(e,r)}interval(e,r){return new Ce(this.source,e,r||this.pos)}}class _o{constructor(e,r,n,s,i,a,o){this.matcher=e,this.input=r,this.startExpr=n,this._cst=s,this._cstOffset=i,this._rightmostFailurePosition=a,this._rightmostFailures=o,this.failed()&&(us(this,"message",function(){const c="Expected "+this.getExpectedText();return Qs(this.input,this.getRightmostFailurePosition())+c}),us(this,"shortMessage",function(){const c="expected "+this.getExpectedText(),u=Js(this.input,this.getRightmostFailurePosition());return"Line "+u.lineNum+", col "+u.colNum+": "+c}))}succeeded(){return!!this._cst}failed(){return!this.succeeded()}getRightmostFailurePosition(){return this._rightmostFailurePosition}getRightmostFailures(){if(!this._rightmostFailures){this.matcher.setInput(this.input);const e=this.matcher._match(this.startExpr,{tracing:!1,positionToRecordFailures:this.getRightmostFailurePosition()});this._rightmostFailures=e.getRightmostFailures()}return this._rightmostFailures}toString(){return this.succeeded()?"[match succeeded]":"[match failed at position "+this.getRightmostFailurePosition()+"]"}getExpectedText(){if(this.succeeded())throw new Error("cannot get expected text of a successful MatchResult");const e=new Bt;let r=this.getRightmostFailures();r=r.filter(n=>!n.isFluffy());for(let n=0;n<r.length;n++)n>0&&(n===r.length-1?e.append(r.length>2?", or ":" or "):e.append(", ")),e.append(r[n].toString());return e.contents()}getInterval(){const e=this.getRightmostFailurePosition();return new Ce(this.input,e,e)}}class Pu{constructor(){this.applicationMemoKeyStack=[],this.memo={},this.maxExaminedLength=0,this.maxRightmostFailureOffset=-1,this.currentLeftRecursion=void 0}isActive(e){return this.applicationMemoKeyStack.indexOf(e.toMemoKey())>=0}enter(e){this.applicationMemoKeyStack.push(e.toMemoKey())}exit(){this.applicationMemoKeyStack.pop()}startLeftRecursion(e,r){r.isLeftRecursion=!0,r.headApplication=e,r.nextLeftRecursion=this.currentLeftRecursion,this.currentLeftRecursion=r;const{applicationMemoKeyStack:n}=this,s=n.indexOf(e.toMemoKey())+1,i=n.slice(s);r.isInvolved=function(a){return i.indexOf(a)>=0},r.updateInvolvedApplicationMemoKeys=function(){for(let a=s;a<n.length;a++){const o=n[a];this.isInvolved(o)||i.push(o)}}}endLeftRecursion(){this.currentLeftRecursion=this.currentLeftRecursion.nextLeftRecursion}shouldUseMemoizedResult(e){if(!e.isLeftRecursion)return!0;const{applicationMemoKeyStack:r}=this;for(let n=0;n<r.length;n++){const s=r[n];if(e.isInvolved(s))return!1}return!0}memoize(e,r){return this.memo[e]=r,this.maxExaminedLength=Math.max(this.maxExaminedLength,r.examinedLength),this.maxRightmostFailureOffset=Math.max(this.maxRightmostFailureOffset,r.rightmostFailureOffset),r}clearObsoleteEntries(e,r){if(e+this.maxExaminedLength<=r)return;const{memo:n}=this;this.maxExaminedLength=0,this.maxRightmostFailureOffset=-1,Object.keys(n).forEach(s=>{const i=n[s];e+i.examinedLength>r?delete n[s]:(this.maxExaminedLength=Math.max(this.maxExaminedLength,i.examinedLength),this.maxRightmostFailureOffset=Math.max(this.maxRightmostFailureOffset,i.rightmostFailureOffset))})}}const $u="✗",qu="✓",Uu="⋅",Bu="⇒",zu="␉",Vu="␊",Wu="␍",ps={succeeded:1,isRootNode:2,isImplicitSpaces:4,isMemoized:8,isHeadOfLeftRecursion:16,terminatesLR:32};function Hu(t){return Fn(" ",t).join("")}function Gu(t,e,r){const n=Ao(t.slice(e,e+r));return n.length<r?n+Fn(" ",r-n.length).join(""):n}function Ao(t){return typeof t=="string"?t.replace(/ /g,Uu).replace(/\t/g,zu).replace(/\n/g,Vu).replace(/\r/g,Wu):String(t)}class vt{constructor(e,r,n,s,i,a,o){this.input=e,this.pos=this.pos1=r,this.pos2=n,this.source=new Ce(e,r,n),this.expr=s,this.bindings=a,this.children=o||[],this.terminatingLREntry=null,this._flags=i?ps.succeeded:0}get displayString(){return this.expr.toDisplayString()}clone(){return this.cloneWithExpr(this.expr)}cloneWithExpr(e){const r=new vt(this.input,this.pos,this.pos2,e,this.succeeded,this.bindings,this.children);return r.isHeadOfLeftRecursion=this.isHeadOfLeftRecursion,r.isImplicitSpaces=this.isImplicitSpaces,r.isMemoized=this.isMemoized,r.isRootNode=this.isRootNode,r.terminatesLR=this.terminatesLR,r.terminatingLREntry=this.terminatingLREntry,r}recordLRTermination(e,r){this.terminatingLREntry=new vt(this.input,this.pos,this.pos2,this.expr,!1,[r],[e]),this.terminatingLREntry.terminatesLR=!0}walk(e,r){let n=e;typeof n=="function"&&(n={enter:n});function s(i,a,o){let c=!0;n.enter&&n.enter.call(r,i,a,o)===vt.prototype.SKIP&&(c=!1),c&&(i.children.forEach(u=>{s(u,i,o+1)}),n.exit&&n.exit.call(r,i,a,o))}this.isRootNode?this.children.forEach(i=>{s(i,null,0)}):s(this,null,0)}toString(){const e=new Bt;return this.walk((r,n,s)=>{if(!r)return this.SKIP;if(r.expr.constructor.name!=="Alt"){if(e.append(Gu(r.input,r.pos,10)+Hu(s*2+1)),e.append((r.succeeded?qu:$u)+" "+r.displayString),r.isHeadOfLeftRecursion&&e.append(" (LR)"),r.succeeded){const a=Ao(r.source.contents);e.append(" "+Bu+" "),e.append(typeof a=="string"?'"'+a+'"':a)}e.append(`
18
+ `)}}),e.contents()}}vt.prototype.SKIP={};Object.keys(ps).forEach(t=>{const e=ps[t];Object.defineProperty(vt.prototype,t,{get(){return(this._flags&e)!==0},set(r){r?this._flags|=e:this._flags&=~e}})});z.prototype.allowsSkippingPrecedingSpace=De("allowsSkippingPrecedingSpace");Te.allowsSkippingPrecedingSpace=Re.allowsSkippingPrecedingSpace=X.prototype.allowsSkippingPrecedingSpace=Oe.prototype.allowsSkippingPrecedingSpace=Ne.prototype.allowsSkippingPrecedingSpace=Ee.prototype.allowsSkippingPrecedingSpace=function(){return!0};be.prototype.allowsSkippingPrecedingSpace=Me.prototype.allowsSkippingPrecedingSpace=qe.prototype.allowsSkippingPrecedingSpace=Pe.prototype.allowsSkippingPrecedingSpace=ke.prototype.allowsSkippingPrecedingSpace=Fe.prototype.allowsSkippingPrecedingSpace=Ae.prototype.allowsSkippingPrecedingSpace=function(){return!1};let dr;So(t=>{dr=t});let Qr;z.prototype.assertAllApplicationsAreValid=function(t,e){Qr=0,this._assertAllApplicationsAreValid(t,e)};z.prototype._assertAllApplicationsAreValid=De("_assertAllApplicationsAreValid");Te._assertAllApplicationsAreValid=Re._assertAllApplicationsAreValid=Oe.prototype._assertAllApplicationsAreValid=Ne.prototype._assertAllApplicationsAreValid=Fe.prototype._assertAllApplicationsAreValid=Ee.prototype._assertAllApplicationsAreValid=function(t,e){};qe.prototype._assertAllApplicationsAreValid=function(t,e){Qr++,this.expr._assertAllApplicationsAreValid(t,e),Qr--};be.prototype._assertAllApplicationsAreValid=function(t,e){for(let r=0;r<this.terms.length;r++)this.terms[r]._assertAllApplicationsAreValid(t,e)};Ae.prototype._assertAllApplicationsAreValid=function(t,e){for(let r=0;r<this.factors.length;r++)this.factors[r]._assertAllApplicationsAreValid(t,e)};Me.prototype._assertAllApplicationsAreValid=ke.prototype._assertAllApplicationsAreValid=Pe.prototype._assertAllApplicationsAreValid=function(t,e){this.expr._assertAllApplicationsAreValid(t,e)};X.prototype._assertAllApplicationsAreValid=function(t,e,r=!1){const n=e.rules[this.ruleName],s=Nt(t)&&Qr===0;if(!n)throw yo(this.ruleName,e.name,this.source);if(!r&&Nt(this.ruleName)&&!s)throw Iu(this.ruleName,this);const i=this.args.length,a=n.formals.length;if(i!==a)throw _u(this.ruleName,a,i,this.source);const o=dr&&n===dr.rules.applySyntactic;if(dr&&n===dr.rules.caseInsensitive&&!(this.args[0]instanceof Oe))throw Ni('a Terminal (e.g. "abc")',this.args[0]);if(o){const u=this.args[0];if(!(u instanceof X))throw Ni("a syntactic rule application",u);if(!Nt(u.ruleName))throw ku(u);if(s)throw Eu(this)}this.args.forEach(u=>{if(u._assertAllApplicationsAreValid(t,e,o),u.getArity()!==1)throw Au(this.ruleName,u)})};z.prototype.assertChoicesHaveUniformArity=De("assertChoicesHaveUniformArity");Te.assertChoicesHaveUniformArity=Re.assertChoicesHaveUniformArity=Oe.prototype.assertChoicesHaveUniformArity=Ne.prototype.assertChoicesHaveUniformArity=Fe.prototype.assertChoicesHaveUniformArity=qe.prototype.assertChoicesHaveUniformArity=Ee.prototype.assertChoicesHaveUniformArity=function(t){};be.prototype.assertChoicesHaveUniformArity=function(t){if(this.terms.length===0)return;const e=this.terms[0].getArity();for(let r=0;r<this.terms.length;r++){const n=this.terms[r];n.assertChoicesHaveUniformArity();const s=n.getArity();if(e!==s)throw wo(t,e,s,n)}};Ln.prototype.assertChoicesHaveUniformArity=function(t){const e=this.terms[0].getArity(),r=this.terms[1].getArity();if(e!==r)throw wo(t,r,e,this.terms[0])};Ae.prototype.assertChoicesHaveUniformArity=function(t){for(let e=0;e<this.factors.length;e++)this.factors[e].assertChoicesHaveUniformArity(t)};Me.prototype.assertChoicesHaveUniformArity=function(t){this.expr.assertChoicesHaveUniformArity(t)};ke.prototype.assertChoicesHaveUniformArity=function(t){};Pe.prototype.assertChoicesHaveUniformArity=function(t){this.expr.assertChoicesHaveUniformArity(t)};X.prototype.assertChoicesHaveUniformArity=function(t){};z.prototype.assertIteratedExprsAreNotNullable=De("assertIteratedExprsAreNotNullable");Te.assertIteratedExprsAreNotNullable=Re.assertIteratedExprsAreNotNullable=Oe.prototype.assertIteratedExprsAreNotNullable=Ne.prototype.assertIteratedExprsAreNotNullable=Fe.prototype.assertIteratedExprsAreNotNullable=Ee.prototype.assertIteratedExprsAreNotNullable=function(t){};be.prototype.assertIteratedExprsAreNotNullable=function(t){for(let e=0;e<this.terms.length;e++)this.terms[e].assertIteratedExprsAreNotNullable(t)};Ae.prototype.assertIteratedExprsAreNotNullable=function(t){for(let e=0;e<this.factors.length;e++)this.factors[e].assertIteratedExprsAreNotNullable(t)};Me.prototype.assertIteratedExprsAreNotNullable=function(t){if(this.expr.assertIteratedExprsAreNotNullable(t),this.expr.isNullable(t))throw vo(this,[])};mt.prototype.assertIteratedExprsAreNotNullable=ke.prototype.assertIteratedExprsAreNotNullable=Pe.prototype.assertIteratedExprsAreNotNullable=qe.prototype.assertIteratedExprsAreNotNullable=function(t){this.expr.assertIteratedExprsAreNotNullable(t)};X.prototype.assertIteratedExprsAreNotNullable=function(t){this.args.forEach(e=>{e.assertIteratedExprsAreNotNullable(t)})};class Ys{constructor(e){this.matchLength=e}get ctorName(){throw new Error("subclass responsibility")}numChildren(){return this.children?this.children.length:0}childAt(e){if(this.children)return this.children[e]}indexOfChild(e){return this.children.indexOf(e)}hasChildren(){return this.numChildren()>0}hasNoChildren(){return!this.hasChildren()}onlyChild(){if(this.numChildren()!==1)throw new Error("cannot get only child of a node of type "+this.ctorName+" (it has "+this.numChildren()+" children)");return this.firstChild()}firstChild(){if(this.hasNoChildren())throw new Error("cannot get first child of a "+this.ctorName+" node, which has no children");return this.childAt(0)}lastChild(){if(this.hasNoChildren())throw new Error("cannot get last child of a "+this.ctorName+" node, which has no children");return this.childAt(this.numChildren()-1)}childBefore(e){const r=this.indexOfChild(e);if(r<0)throw new Error("Node.childBefore() called w/ an argument that is not a child");if(r===0)throw new Error("cannot get child before first child");return this.childAt(r-1)}childAfter(e){const r=this.indexOfChild(e);if(r<0)throw new Error("Node.childAfter() called w/ an argument that is not a child");if(r===this.numChildren()-1)throw new Error("cannot get child after last child");return this.childAt(r+1)}isTerminal(){return!1}isNonterminal(){return!1}isIteration(){return!1}isOptional(){return!1}}class Vt extends Ys{get ctorName(){return"_terminal"}isTerminal(){return!0}get primitiveValue(){throw new Error("The `primitiveValue` property was removed in Ohm v17.")}}class Ku extends Ys{constructor(e,r,n,s){super(s),this.ruleName=e,this.children=r,this.childOffsets=n}get ctorName(){return this.ruleName}isNonterminal(){return!0}isLexical(){return ho(this.ctorName)}isSyntactic(){return Nt(this.ctorName)}}class xo extends Ys{constructor(e,r,n,s){super(n),this.children=e,this.childOffsets=r,this.optional=s}get ctorName(){return"_iter"}isIteration(){return!0}isOptional(){return this.optional}}z.prototype.eval=De("eval");Te.eval=function(t){const{inputStream:e}=t,r=e.pos,n=e.nextCodePoint();return n!==void 0?(t.pushBinding(new Vt(String.fromCodePoint(n).length),r),!0):(t.processFailure(r,this),!1)};Re.eval=function(t){const{inputStream:e}=t,r=e.pos;return e.atEnd()?(t.pushBinding(new Vt(0),r),!0):(t.processFailure(r,this),!1)};Oe.prototype.eval=function(t){const{inputStream:e}=t,r=e.pos;return e.matchString(this.obj)?(t.pushBinding(new Vt(this.obj.length),r),!0):(t.processFailure(r,this),!1)};Ne.prototype.eval=function(t){const{inputStream:e}=t,r=e.pos,n=this.matchCodePoint?e.nextCodePoint():e.nextCharCode();return n!==void 0&&this.from.codePointAt(0)<=n&&n<=this.to.codePointAt(0)?(t.pushBinding(new Vt(String.fromCodePoint(n).length),r),!0):(t.processFailure(r,this),!1)};Fe.prototype.eval=function(t){return t.eval(t.currentApplication().args[this.index])};qe.prototype.eval=function(t){t.enterLexifiedContext();const e=t.eval(this.expr);return t.exitLexifiedContext(),e};be.prototype.eval=function(t){for(let e=0;e<this.terms.length;e++)if(t.eval(this.terms[e]))return!0;return!1};Ae.prototype.eval=function(t){for(let e=0;e<this.factors.length;e++){const r=this.factors[e];if(!t.eval(r))return!1}return!0};Me.prototype.eval=function(t){const{inputStream:e}=t,r=e.pos,n=this.getArity(),s=[],i=[];for(;s.length<n;)s.push([]),i.push([]);let a=0,o=r,c;for(;a<this.maxNumMatches&&t.eval(this.expr);){if(e.pos===o)throw vo(this,t._applicationStack);o=e.pos,a++;const f=t._bindings.splice(t._bindings.length-n,n),y=t._bindingOffsets.splice(t._bindingOffsets.length-n,n);for(c=0;c<f.length;c++)s[c].push(f[c]),i[c].push(y[c])}if(a<this.minNumMatches)return!1;let u=t.posToOffset(r),d=0;if(a>0){const f=s[n-1],y=i[n-1],b=y[y.length-1]+f[f.length-1].matchLength;u=i[0][0],d=b-u}const l=this instanceof mt;for(c=0;c<s.length;c++)t._bindings.push(new xo(s[c],i[c],d,l)),t._bindingOffsets.push(u);return!0};ke.prototype.eval=function(t){const{inputStream:e}=t,r=e.pos;t.pushFailuresInfo();const n=t.eval(this.expr);return t.popFailuresInfo(),n?(t.processFailure(r,this),!1):(e.pos=r,!0)};Pe.prototype.eval=function(t){const{inputStream:e}=t,r=e.pos;return t.eval(this.expr)?(e.pos=r,!0):!1};X.prototype.eval=function(t){const e=t.currentApplication(),r=e?e.args:[],n=this.substituteParams(r),s=t.getCurrentPosInfo();if(s.isActive(n))return n.handleCycle(t);const i=n.toMemoKey(),a=s.memo[i];if(a&&s.shouldUseMemoizedResult(a)){if(t.hasNecessaryInfo(a))return t.useMemoizedResult(t.inputStream.pos,a);delete s.memo[i]}return n.reallyEval(t)};X.prototype.handleCycle=function(t){const e=t.getCurrentPosInfo(),{currentLeftRecursion:r}=e,n=this.toMemoKey();let s=e.memo[n];return r&&r.headApplication.toMemoKey()===n?s.updateInvolvedApplicationMemoKeys():s||(s=e.memoize(n,{matchLength:0,examinedLength:0,value:!1,rightmostFailureOffset:-1}),e.startLeftRecursion(this,s)),t.useMemoizedResult(t.inputStream.pos,s)};X.prototype.reallyEval=function(t){const{inputStream:e}=t,r=e.pos,n=t.getCurrentPosInfo(),s=t.grammar.rules[this.ruleName],{body:i}=s,{description:a}=s;t.enterApplication(n,this),a&&t.pushFailuresInfo();const o=e.examinedLength;e.examinedLength=0;let c=this.evalOnce(i,t);const u=n.currentLeftRecursion,d=this.toMemoKey(),l=u&&u.headApplication.toMemoKey()===d;let f;t.doNotMemoize?t.doNotMemoize=!1:l?(c=this.growSeedResult(i,t,r,u,c),n.endLeftRecursion(),f=u,f.examinedLength=e.examinedLength-r,f.rightmostFailureOffset=t._getRightmostFailureOffset(),n.memoize(d,f)):(!u||!u.isInvolved(d))&&(f=n.memoize(d,{matchLength:e.pos-r,examinedLength:e.examinedLength-r,value:c,failuresAtRightmostPosition:t.cloneRecordedFailures(),rightmostFailureOffset:t._getRightmostFailureOffset()}));const y=!!c;if(a&&(t.popFailuresInfo(),y||t.processFailure(r,this),f&&(f.failuresAtRightmostPosition=t.cloneRecordedFailures(),f.rightmostFailureOffset=t._getRightmostFailureOffset())),t.isTracing()&&f){const b=t.getTraceEntry(r,this,y,y?[c]:[]);l&&(It(b.terminatingLREntry!=null||!y),b.isHeadOfLeftRecursion=!0),f.traceEntry=b}return e.examinedLength=Math.max(e.examinedLength,o),t.exitApplication(n,c),y};X.prototype.evalOnce=function(t,e){const{inputStream:r}=e,n=r.pos;if(e.eval(t)){const s=t.getArity(),i=e._bindings.splice(e._bindings.length-s,s),a=e._bindingOffsets.splice(e._bindingOffsets.length-s,s),o=r.pos-n;return new Ku(this.ruleName,i,a,o)}else return!1};X.prototype.growSeedResult=function(t,e,r,n,s){if(!s)return!1;const{inputStream:i}=e;for(;;){if(n.matchLength=i.pos-r,n.value=s,n.failuresAtRightmostPosition=e.cloneRecordedFailures(),e.isTracing()){const a=e.trace[e.trace.length-1];n.traceEntry=new vt(e.input,r,i.pos,this,!0,[s],[a.clone()])}if(i.pos=r,s=this.evalOnce(t,e),i.pos-r<=n.matchLength)break;e.isTracing()&&e.trace.splice(-2,1)}return e.isTracing()&&n.traceEntry.recordLRTermination(e.trace.pop(),s),i.pos=r+n.matchLength,n.value};Ee.prototype.eval=function(t){const{inputStream:e}=t,r=e.pos,n=e.nextCodePoint();if(n!==void 0&&n<=Mu){const s=String.fromCodePoint(n);if(this.pattern.test(s))return t.pushBinding(new Vt(s.length),r),!0}return t.processFailure(r,this),!1};z.prototype.getArity=De("getArity");Te.getArity=Re.getArity=Oe.prototype.getArity=Ne.prototype.getArity=Fe.prototype.getArity=X.prototype.getArity=Ee.prototype.getArity=function(){return 1};be.prototype.getArity=function(){return this.terms.length===0?0:this.terms[0].getArity()};Ae.prototype.getArity=function(){let t=0;for(let e=0;e<this.factors.length;e++)t+=this.factors[e].getArity();return t};Me.prototype.getArity=function(){return this.expr.getArity()};ke.prototype.getArity=function(){return 0};Pe.prototype.getArity=qe.prototype.getArity=function(){return this.expr.getArity()};function Qe(t,e){const r={};if(t.source&&e){const n=t.source.relativeTo(e);r.sourceInterval=[n.startIdx,n.endIdx]}return r}z.prototype.outputRecipe=De("outputRecipe");Te.outputRecipe=function(t,e){return["any",Qe(this,e)]};Re.outputRecipe=function(t,e){return["end",Qe(this,e)]};Oe.prototype.outputRecipe=function(t,e){return["terminal",Qe(this,e),this.obj]};Ne.prototype.outputRecipe=function(t,e){return["range",Qe(this,e),this.from,this.to]};Fe.prototype.outputRecipe=function(t,e){return["param",Qe(this,e),this.index]};be.prototype.outputRecipe=function(t,e){return["alt",Qe(this,e)].concat(this.terms.map(r=>r.outputRecipe(t,e)))};Ln.prototype.outputRecipe=function(t,e){return this.terms[0].outputRecipe(t,e)};jn.prototype.outputRecipe=function(t,e){const r=this.terms.slice(0,this.expansionPos),n=this.terms.slice(this.expansionPos+1);return["splice",Qe(this,e),r.map(s=>s.outputRecipe(t,e)),n.map(s=>s.outputRecipe(t,e))]};Ae.prototype.outputRecipe=function(t,e){return["seq",Qe(this,e)].concat(this.factors.map(r=>r.outputRecipe(t,e)))};zt.prototype.outputRecipe=ar.prototype.outputRecipe=mt.prototype.outputRecipe=ke.prototype.outputRecipe=Pe.prototype.outputRecipe=qe.prototype.outputRecipe=function(t,e){return[this.constructor.name.toLowerCase(),Qe(this,e),this.expr.outputRecipe(t,e)]};X.prototype.outputRecipe=function(t,e){return["app",Qe(this,e),this.ruleName,this.args.map(r=>r.outputRecipe(t,e))]};Ee.prototype.outputRecipe=function(t,e){return["unicodeChar",Qe(this,e),this.categoryOrProp]};z.prototype.introduceParams=De("introduceParams");Te.introduceParams=Re.introduceParams=Oe.prototype.introduceParams=Ne.prototype.introduceParams=Fe.prototype.introduceParams=Ee.prototype.introduceParams=function(t){return this};be.prototype.introduceParams=function(t){return this.terms.forEach((e,r,n)=>{n[r]=e.introduceParams(t)}),this};Ae.prototype.introduceParams=function(t){return this.factors.forEach((e,r,n)=>{n[r]=e.introduceParams(t)}),this};Me.prototype.introduceParams=ke.prototype.introduceParams=Pe.prototype.introduceParams=qe.prototype.introduceParams=function(t){return this.expr=this.expr.introduceParams(t),this};X.prototype.introduceParams=function(t){const e=t.indexOf(this.ruleName);if(e>=0){if(this.args.length>0)throw new Error("Parameterized rules cannot be passed as arguments to another rule.");return new Fe(e).withSource(this.source)}else return this.args.forEach((r,n,s)=>{s[n]=r.introduceParams(t)}),this};z.prototype.isNullable=function(t){return this._isNullable(t,Object.create(null))};z.prototype._isNullable=De("_isNullable");Te._isNullable=Ne.prototype._isNullable=Fe.prototype._isNullable=ar.prototype._isNullable=Ee.prototype._isNullable=function(t,e){return!1};Re._isNullable=function(t,e){return!0};Oe.prototype._isNullable=function(t,e){return typeof this.obj=="string"?this.obj==="":!1};be.prototype._isNullable=function(t,e){return this.terms.length===0||this.terms.some(r=>r._isNullable(t,e))};Ae.prototype._isNullable=function(t,e){return this.factors.every(r=>r._isNullable(t,e))};zt.prototype._isNullable=mt.prototype._isNullable=ke.prototype._isNullable=Pe.prototype._isNullable=function(t,e){return!0};qe.prototype._isNullable=function(t,e){return this.expr._isNullable(t,e)};X.prototype._isNullable=function(t,e){const r=this.toMemoKey();if(!Object.prototype.hasOwnProperty.call(e,r)){const{body:n}=t.rules[this.ruleName],s=n.substituteParams(this.args);e[r]=!1,e[r]=s._isNullable(t,e)}return e[r]};z.prototype.substituteParams=De("substituteParams");Te.substituteParams=Re.substituteParams=Oe.prototype.substituteParams=Ne.prototype.substituteParams=Ee.prototype.substituteParams=function(t){return this};Fe.prototype.substituteParams=function(t){return mo(t[this.index])};be.prototype.substituteParams=function(t){return new be(this.terms.map(e=>e.substituteParams(t)))};Ae.prototype.substituteParams=function(t){return new Ae(this.factors.map(e=>e.substituteParams(t)))};Me.prototype.substituteParams=ke.prototype.substituteParams=Pe.prototype.substituteParams=qe.prototype.substituteParams=function(t){return new this.constructor(this.expr.substituteParams(t))};X.prototype.substituteParams=function(t){if(this.args.length===0)return this;{const e=this.args.map(r=>r.substituteParams(t));return new X(this.ruleName,e)}};function ji(t){return/^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(t)}function Xs(t){const e=Object.create(null);t.forEach(r=>{e[r]=(e[r]||0)+1}),Object.keys(e).forEach(r=>{if(e[r]<=1)return;let n=1;t.forEach((s,i)=>{s===r&&(t[i]=s+"_"+n++)})})}z.prototype.toArgumentNameList=De("toArgumentNameList");Te.toArgumentNameList=function(t,e){return["any"]};Re.toArgumentNameList=function(t,e){return["end"]};Oe.prototype.toArgumentNameList=function(t,e){return typeof this.obj=="string"&&/^[_a-zA-Z0-9]+$/.test(this.obj)?["_"+this.obj]:["$"+t]};Ne.prototype.toArgumentNameList=function(t,e){let r=this.from+"_to_"+this.to;return ji(r)||(r="_"+r),ji(r)||(r="$"+t),[r]};be.prototype.toArgumentNameList=function(t,e){const r=this.terms.map(i=>i.toArgumentNameList(t,!0)),n=[],s=r[0].length;for(let i=0;i<s;i++){const a=[];for(let c=0;c<this.terms.length;c++)a.push(r[c][i]);const o=lo(a);n.push(o.join("_or_"))}return e||Xs(n),n};Ae.prototype.toArgumentNameList=function(t,e){let r=[];return this.factors.forEach(n=>{const s=n.toArgumentNameList(t,!0);r=r.concat(s),t+=s.length}),e||Xs(r),r};Me.prototype.toArgumentNameList=function(t,e){const r=this.expr.toArgumentNameList(t,e).map(n=>n[n.length-1]==="s"?n+"es":n+"s");return e||Xs(r),r};mt.prototype.toArgumentNameList=function(t,e){return this.expr.toArgumentNameList(t,e).map(r=>"opt"+r[0].toUpperCase()+r.slice(1))};ke.prototype.toArgumentNameList=function(t,e){return[]};Pe.prototype.toArgumentNameList=qe.prototype.toArgumentNameList=function(t,e){return this.expr.toArgumentNameList(t,e)};X.prototype.toArgumentNameList=function(t,e){return[this.ruleName]};Ee.prototype.toArgumentNameList=function(t,e){return["$"+t]};Fe.prototype.toArgumentNameList=function(t,e){return["param"+this.index]};z.prototype.toDisplayString=De("toDisplayString");be.prototype.toDisplayString=Ae.prototype.toDisplayString=function(){return this.source?this.source.trimmed().contents:"["+this.constructor.name+"]"};Te.toDisplayString=Re.toDisplayString=Me.prototype.toDisplayString=ke.prototype.toDisplayString=Pe.prototype.toDisplayString=qe.prototype.toDisplayString=Oe.prototype.toDisplayString=Ne.prototype.toDisplayString=Fe.prototype.toDisplayString=function(){return this.toString()};X.prototype.toDisplayString=function(){if(this.args.length>0){const t=this.args.map(e=>e.toDisplayString());return this.ruleName+"<"+t.join(",")+">"}else return this.ruleName};Ee.prototype.toDisplayString=function(){return"Unicode ["+this.categoryOrProp+"] character"};function Zu(t){return t==="description"||t==="string"||t==="code"}class Ue{constructor(e,r,n){if(!Zu(n))throw new Error("invalid Failure type: "+n);this.pexpr=e,this.text=r,this.type=n,this.fluffy=!1}getPExpr(){return this.pexpr}getText(){return this.text}getType(){return this.type}isDescription(){return this.type==="description"}isStringTerminal(){return this.type==="string"}isCode(){return this.type==="code"}isFluffy(){return this.fluffy}makeFluffy(){this.fluffy=!0}clearFluffy(){this.fluffy=!1}subsumes(e){return this.getText()===e.getText()&&this.type===e.type&&(!this.isFluffy()||this.isFluffy()&&e.isFluffy())}toString(){return this.type==="string"?JSON.stringify(this.getText()):this.getText()}clone(){const e=new Ue(this.pexpr,this.text,this.type);return this.isFluffy()&&e.makeFluffy(),e}toKey(){return this.toString()+"#"+this.type}}z.prototype.toFailure=De("toFailure");Te.toFailure=function(t){return new Ue(this,"any object","description")};Re.toFailure=function(t){return new Ue(this,"end of input","description")};Oe.prototype.toFailure=function(t){return new Ue(this,this.obj,"string")};Ne.prototype.toFailure=function(t){return new Ue(this,JSON.stringify(this.from)+".."+JSON.stringify(this.to),"code")};ke.prototype.toFailure=function(t){const e=this.expr===Te?"nothing":"not "+this.expr.toFailure(t);return new Ue(this,e,"description")};Pe.prototype.toFailure=function(t){return this.expr.toFailure(t)};X.prototype.toFailure=function(t){let{description:e}=t.rules[this.ruleName];return e||(e=(/^[aeiouAEIOU]/.test(this.ruleName)?"an":"a")+" "+this.ruleName),new Ue(this,e,"description")};Ee.prototype.toFailure=function(t){return new Ue(this,"a Unicode ["+this.categoryOrProp+"] character","description")};be.prototype.toFailure=function(t){const r="("+this.terms.map(n=>n.toFailure(t)).join(" or ")+")";return new Ue(this,r,"description")};Ae.prototype.toFailure=function(t){const r="("+this.factors.map(n=>n.toFailure(t)).join(" ")+")";return new Ue(this,r,"description")};Me.prototype.toFailure=function(t){const e="("+this.expr.toFailure(t)+this.operator+")";return new Ue(this,e,"description")};z.prototype.toString=De("toString");Te.toString=function(){return"any"};Re.toString=function(){return"end"};Oe.prototype.toString=function(){return JSON.stringify(this.obj)};Ne.prototype.toString=function(){return JSON.stringify(this.from)+".."+JSON.stringify(this.to)};Fe.prototype.toString=function(){return"$"+this.index};qe.prototype.toString=function(){return"#("+this.expr.toString()+")"};be.prototype.toString=function(){return this.terms.length===1?this.terms[0].toString():"("+this.terms.map(t=>t.toString()).join(" | ")+")"};Ae.prototype.toString=function(){return this.factors.length===1?this.factors[0].toString():"("+this.factors.map(t=>t.toString()).join(" ")+")"};Me.prototype.toString=function(){return this.expr+this.operator};ke.prototype.toString=function(){return"~"+this.expr};Pe.prototype.toString=function(){return"&"+this.expr};X.prototype.toString=function(){if(this.args.length>0){const t=this.args.map(e=>e.toString());return this.ruleName+"<"+t.join(",")+">"}else return this.ruleName};Ee.prototype.toString=function(){return"\\p{"+this.categoryOrProp+"}"};class ei extends z{constructor(e){super(),this.obj=e}_getString(e){const r=e.currentApplication().args[this.obj.index];return It(r instanceof Oe,"expected a Terminal expression"),r.obj}allowsSkippingPrecedingSpace(){return!0}eval(e){const{inputStream:r}=e,n=r.pos,s=this._getString(e);return r.matchString(s,!0)?(e.pushBinding(new Vt(s.length),n),!0):(e.processFailure(n,this),!1)}getArity(){return 1}substituteParams(e){return new ei(this.obj.substituteParams(e))}toDisplayString(){return this.obj.toDisplayString()+" (case-insensitive)"}toFailure(e){return new Ue(this,this.obj.toFailure(e)+" (case-insensitive)","description")}_isNullable(e,r){return this.obj._isNullable(e,r)}}let Io;So(t=>{Io=t.rules.applySyntactic.body});const Wn=new X("spaces");class Ju{constructor(e,r,n){this.matcher=e,this.startExpr=r,this.grammar=e.grammar,this.input=e.getInput(),this.inputStream=new Dn(this.input),this.memoTable=e._memoTable,this.userData=void 0,this.doNotMemoize=!1,this._bindings=[],this._bindingOffsets=[],this._applicationStack=[],this._posStack=[0],this.inLexifiedContextStack=[!1],this.rightmostFailurePosition=-1,this._rightmostFailurePositionStack=[],this._recordedFailuresStack=[],n!==void 0&&(this.positionToRecordFailures=n,this.recordedFailures=Object.create(null))}posToOffset(e){return e-this._posStack[this._posStack.length-1]}enterApplication(e,r){this._posStack.push(this.inputStream.pos),this._applicationStack.push(r),this.inLexifiedContextStack.push(!1),e.enter(r),this._rightmostFailurePositionStack.push(this.rightmostFailurePosition),this.rightmostFailurePosition=-1}exitApplication(e,r){const n=this._posStack.pop();this._applicationStack.pop(),this.inLexifiedContextStack.pop(),e.exit(),this.rightmostFailurePosition=Math.max(this.rightmostFailurePosition,this._rightmostFailurePositionStack.pop()),r&&this.pushBinding(r,n)}enterLexifiedContext(){this.inLexifiedContextStack.push(!0)}exitLexifiedContext(){this.inLexifiedContextStack.pop()}currentApplication(){return this._applicationStack[this._applicationStack.length-1]}inSyntacticContext(){const e=this.currentApplication();return e?e.isSyntactic()&&!this.inLexifiedContext():this.startExpr.factors[0].isSyntactic()}inLexifiedContext(){return this.inLexifiedContextStack[this.inLexifiedContextStack.length-1]}skipSpaces(){return this.pushFailuresInfo(),this.eval(Wn),this.popBinding(),this.popFailuresInfo(),this.inputStream.pos}skipSpacesIfInSyntacticContext(){return this.inSyntacticContext()?this.skipSpaces():this.inputStream.pos}maybeSkipSpacesBefore(e){return e.allowsSkippingPrecedingSpace()&&e!==Wn?this.skipSpacesIfInSyntacticContext():this.inputStream.pos}pushBinding(e,r){this._bindings.push(e),this._bindingOffsets.push(this.posToOffset(r))}popBinding(){this._bindings.pop(),this._bindingOffsets.pop()}numBindings(){return this._bindings.length}truncateBindings(e){for(;this._bindings.length>e;)this.popBinding()}getCurrentPosInfo(){return this.getPosInfo(this.inputStream.pos)}getPosInfo(e){let r=this.memoTable[e];return r||(r=this.memoTable[e]=new Pu),r}processFailure(e,r){if(this.rightmostFailurePosition=Math.max(this.rightmostFailurePosition,e),this.recordedFailures&&e===this.positionToRecordFailures){const n=this.currentApplication();n&&(r=r.substituteParams(n.args)),this.recordFailure(r.toFailure(this.grammar),!1)}}recordFailure(e,r){const n=e.toKey();this.recordedFailures[n]?this.recordedFailures[n].isFluffy()&&!e.isFluffy()&&this.recordedFailures[n].clearFluffy():this.recordedFailures[n]=r?e.clone():e}recordFailures(e,r){Object.keys(e).forEach(n=>{this.recordFailure(e[n],r)})}cloneRecordedFailures(){if(!this.recordedFailures)return;const e=Object.create(null);return Object.keys(this.recordedFailures).forEach(r=>{e[r]=this.recordedFailures[r].clone()}),e}getRightmostFailurePosition(){return this.rightmostFailurePosition}_getRightmostFailureOffset(){return this.rightmostFailurePosition>=0?this.posToOffset(this.rightmostFailurePosition):-1}getMemoizedTraceEntry(e,r){const n=this.memoTable[e];if(n&&r instanceof X){const s=n.memo[r.toMemoKey()];if(s&&s.traceEntry){const i=s.traceEntry.cloneWithExpr(r);return i.isMemoized=!0,i}}return null}getTraceEntry(e,r,n,s){if(r instanceof X){const i=this.currentApplication(),a=i?i.args:[];r=r.substituteParams(a)}return this.getMemoizedTraceEntry(e,r)||new vt(this.input,e,this.inputStream.pos,r,n,s,this.trace)}isTracing(){return!!this.trace}hasNecessaryInfo(e){return this.trace&&!e.traceEntry?!1:this.recordedFailures&&this.inputStream.pos+e.rightmostFailureOffset===this.positionToRecordFailures?!!e.failuresAtRightmostPosition:!0}useMemoizedResult(e,r){this.trace&&this.trace.push(r.traceEntry);const n=this.inputStream.pos+r.rightmostFailureOffset;return this.rightmostFailurePosition=Math.max(this.rightmostFailurePosition,n),this.recordedFailures&&this.positionToRecordFailures===n&&r.failuresAtRightmostPosition&&this.recordFailures(r.failuresAtRightmostPosition,!0),this.inputStream.examinedLength=Math.max(this.inputStream.examinedLength,r.examinedLength+e),r.value?(this.inputStream.pos+=r.matchLength,this.pushBinding(r.value,e),!0):!1}eval(e){const{inputStream:r}=this,n=this._bindings.length,s=this.userData;let i;this.recordedFailures&&(i=this.recordedFailures,this.recordedFailures=Object.create(null));const a=r.pos,o=this.maybeSkipSpacesBefore(e);let c;this.trace&&(c=this.trace,this.trace=[]);const u=e.eval(this);if(this.trace){const d=this._bindings.slice(n),l=this.getTraceEntry(o,e,u,d);l.isImplicitSpaces=e===Wn,l.isRootNode=e===this.startExpr,c.push(l),this.trace=c}return u?this.recordedFailures&&r.pos===this.positionToRecordFailures&&Object.keys(this.recordedFailures).forEach(d=>{this.recordedFailures[d].makeFluffy()}):(r.pos=a,this.truncateBindings(n),this.userData=s),this.recordedFailures&&this.recordFailures(i,!1),e===Io&&this.skipSpaces(),u}getMatchResult(){this.grammar._setUpMatchState(this),this.eval(this.startExpr);let e;this.recordedFailures&&(e=Object.keys(this.recordedFailures).map(n=>this.recordedFailures[n]));const r=this._bindings[0];return r&&(r.grammar=this.grammar),new _o(this.matcher,this.input,this.startExpr,r,this._bindingOffsets[0],this.rightmostFailurePosition,e)}getTrace(){this.trace=[];const e=this.getMatchResult(),r=this.trace[this.trace.length-1];return r.result=e,r}pushFailuresInfo(){this._rightmostFailurePositionStack.push(this.rightmostFailurePosition),this._recordedFailuresStack.push(this.recordedFailures)}popFailuresInfo(){this.rightmostFailurePosition=this._rightmostFailurePositionStack.pop(),this.recordedFailures=this._recordedFailuresStack.pop()}}class Qu{constructor(e){this.grammar=e,this._memoTable=[],this._input="",this._isMemoTableStale=!1}_resetMemoTable(){this._memoTable=[],this._isMemoTableStale=!1}getInput(){return this._input}setInput(e){return this._input!==e&&this.replaceInputRange(0,this._input.length,e),this}replaceInputRange(e,r,n){const s=this._input,i=this._memoTable;if(e<0||e>s.length||r<0||r>s.length||e>r)throw new Error("Invalid indices: "+e+" and "+r);this._input=s.slice(0,e)+n+s.slice(r),this._input!==s&&i.length>0&&(this._isMemoTableStale=!0);const a=i.slice(r);i.length=e;for(let o=0;o<n.length;o++)i.push(void 0);for(const o of a)i.push(o);for(let o=0;o<e;o++){const c=i[o];c&&c.clearObsoleteEntries(o,e)}return this}match(e,r={incremental:!0}){return this._match(this._getStartExpr(e),{incremental:r.incremental,tracing:!1})}trace(e,r={incremental:!0}){return this._match(this._getStartExpr(e),{incremental:r.incremental,tracing:!0})}_match(e,r={}){const n={tracing:!1,incremental:!0,positionToRecordFailures:void 0,...r};if(!n.incremental)this._resetMemoTable();else if(this._isMemoTableStale&&!this.grammar.supportsIncrementalParsing)throw vu(this.grammar);const s=new Ju(this,e,n.positionToRecordFailures);return n.tracing?s.getTrace():s.getMatchResult()}_getStartExpr(e){const r=e||this.grammar.defaultStartRule;if(!r)throw new Error("Missing start rule argument -- the grammar has no default start rule.");const n=this.grammar.parseApplication(r);return new Ae([n,Re])}}const hr=[],ms=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);class Di{constructor(e,r,n){this._node=e,this.source=r,this._baseInterval=n,e.isNonterminal()&&It(r===n),this._childWrappers=[]}_forgetMemoizedResultFor(e){delete this._node[this._semantics.attributeKeys[e]],this.children.forEach(r=>{r._forgetMemoizedResultFor(e)})}child(e){if(!(0<=e&&e<this._node.numChildren()))return;let r=this._childWrappers[e];if(!r){const n=this._node.childAt(e),s=this._node.childOffsets[e],i=this._baseInterval.subInterval(s,n.matchLength),a=n.isNonterminal()?i:this._baseInterval;r=this._childWrappers[e]=this._semantics.wrap(n,i,a)}return r}_children(){for(let e=0;e<this._node.numChildren();e++)this.child(e);return this._childWrappers}isIteration(){return this._node.isIteration()}isTerminal(){return this._node.isTerminal()}isNonterminal(){return this._node.isNonterminal()}isSyntactic(){return this.isNonterminal()&&this._node.isSyntactic()}isLexical(){return this.isNonterminal()&&this._node.isLexical()}isOptional(){return this._node.isOptional()}iteration(e){const r=e||[],n=r.map(a=>a._node),s=new xo(n,[],-1,!1),i=this._semantics.wrap(s,null,null);return i._childWrappers=r,i}get children(){return this._children()}get ctorName(){return this._node.ctorName}get numChildren(){return this._node.numChildren()}get sourceString(){return this.source.contents}}class $e{constructor(e,r){const n=this;if(this.grammar=e,this.checkedActionDicts=!1,this.Wrapper=class extends(r?r.Wrapper:Di){constructor(s,i,a){super(s,i,a),n.checkActionDictsIfHaventAlready(),this._semantics=n}toString(){return"[semantics wrapper for "+n.grammar.name+"]"}},this.super=r,r){if(!(e.equals(this.super.grammar)||e._inheritsFrom(this.super.grammar)))throw new Error("Cannot extend a semantics for grammar '"+this.super.grammar.name+"' for use with grammar '"+e.name+"' (not a sub-grammar)");this.operations=Object.create(this.super.operations),this.attributes=Object.create(this.super.attributes),this.attributeKeys=Object.create(null);for(const s in this.attributes)Object.defineProperty(this.attributeKeys,s,{value:Li(s)})}else this.operations=Object.create(null),this.attributes=Object.create(null),this.attributeKeys=Object.create(null)}toString(){return"[semantics for "+this.grammar.name+"]"}checkActionDictsIfHaventAlready(){this.checkedActionDicts||(this.checkActionDicts(),this.checkedActionDicts=!0)}checkActionDicts(){let e;for(e in this.operations)this.operations[e].checkActionDict(this.grammar);for(e in this.attributes)this.attributes[e].checkActionDict(this.grammar)}toRecipe(e){function r(s){return s.super!==$e.BuiltInSemantics._getSemantics()}let n=`(function(g) {
19
19
  `;if(r(this)){n+=" var semantics = "+this.super.toRecipe(!0)+"(g";const s=this.super.grammar;let i=this.grammar;for(;i!==s;)n+=".superGrammar",i=i.superGrammar;n+=`);
20
20
  `,n+=" return g.extendSemantics(semantics)"}else n+=" return g.createSemantics()";return["Operation","Attribute"].forEach(s=>{const i=this[s.toLowerCase()+"s"];Object.keys(i).forEach(a=>{const{actionDict:o,formals:c,builtInDefault:u}=i[a];let d=a;c.length>0&&(d+="("+c.join(", ")+")");let l;r(this)&&this.super[s.toLowerCase()+"s"][a]?l="extend"+s:l="add"+s,n+=`
21
21
  .`+l+"("+JSON.stringify(d)+", {";const f=[];Object.keys(o).forEach(y=>{if(o[y]!==u){let b=o[y].toString().trim();b=b.replace(/^.*\(/,"function("),f.push(`
@@ -26,11 +26,11 @@ NOTE: as of Ohm v16, there is no default action for iteration nodes — see `,"
26
26
  var semantics = `+n+`(grammar);
27
27
  return semantics;
28
28
  });
29
- `),n}addOperationOrAttribute(e,r,n){const s=e+"s",i=Pi(r,e),{name:a}=i,{formals:o}=i;this.assertNewName(a,e);const c=Xu(e,a,l),u={_default:c};Object.keys(n).forEach(f=>{u[f]=n[f]});const d=e==="operation"?new Sr(a,o,u,c):new ys(a,u,c);d.checkActionDict(this.grammar),this[s][a]=d;function l(...f){const y=this._semantics[s][a];if(arguments.length!==y.formals.length)throw new Error("Invalid number of arguments passed to "+a+" "+e+" (expected "+y.formals.length+", got "+arguments.length+")");const b=Object.create(null);for(const[T,L]of Object.entries(f)){const k=y.formals[T];b[k]=L}const S=this.args;this.args=b;const j=y.execute(this._semantics,this);return this.args=S,j}e==="operation"?(this.Wrapper.prototype[a]=l,this.Wrapper.prototype[a].toString=function(){return"["+a+" operation]"}):(Object.defineProperty(this.Wrapper.prototype,a,{get:l,configurable:!0}),Object.defineProperty(this.attributeKeys,a,{value:ji(a)}))}extendOperationOrAttribute(e,r,n){const s=e+"s";if(Pi(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(gs(this[s],r))throw new Error("Cannot extend "+e+" '"+r+"' again");const i=this[s][r].formals,a=this[s][r].actionDict,o=Object.create(a);Object.keys(n).forEach(c=>{o[c]=n[c]}),this[s][r]=e==="operation"?new Sr(r,i,o):new ys(r,o),this[s][r].checkActionDict(this.grammar)}assertNewName(e,r){if(gs(Mi.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 Pi(t,e){if(!$e.prototypeGrammar)return It(t.indexOf("(")===-1),{name:t,formals:[]};const r=$e.prototypeGrammar.match(t,e==="operation"?"OperationSignature":"AttributeSignature");if(r.failed())throw new Error(r.message);return $e.prototypeGrammarSemantics(r).parse()}function Xu(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 Nu(this.ctorName,e,t,hr)}}$e.createSemantics=function(t,e){const r=new $e(t,e!==void 0?e:$e.BuiltInSemantics._getSemantics()),n=function(i){if(!(i instanceof Ao))throw new TypeError("Semantics expected a MatchResult, but got "+Js(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 Mn(i.input);return r.wrap(a,o.interval(i._cstOffset,i.input.length))};return n.addOperation=function(s,i){return r.addOperationOrAttribute("operation",s,i),n},n.extendOperation=function(s,i){return r.extendOperationOrAttribute("operation",s,i),n},n.addAttribute=function(s,i){return r.addOperationOrAttribute("attribute",s,i),n},n.extendAttribute=function(s,i){return r.extendOperationOrAttribute("attribute",s,i),n},n._getActionDict=function(s){const i=r.operations[s]||r.attributes[s];if(!i)throw new Error('"'+s+'" is not a valid operation or attribute name in this semantics for "'+t.name+'"');return i.actionDict},n._remove=function(s){let i;return s in r.operations?(i=r.operations[s],delete r.operations[s]):s in r.attributes&&(i=r.attributes[s],delete r.attributes[s]),delete r.Wrapper.prototype[s],i},n.getOperationNames=function(){return Object.keys(r.operations)},n.getAttributeNames=function(){return Object.keys(r.attributes)},n.getGrammar=function(){return r.grammar},n.toRecipe=function(s){return r.toRecipe(s)},n.toString=r.toString.bind(r),n._getSemantics=function(){return r},n};class Sr{constructor(e,r,n,s){this.name=e,this.formals=r,this.actionDict=n,this.builtInDefault=s}checkActionDict(e){e._checkTopDownActionDict(this.typeName,this.name,this.actionDict)}execute(e,r){try{const{ctorName:n}=r._node;let s=this.actionDict[n];return s?(hr.push([this,n]),s.apply(r,r._children())):r.isNonterminal()&&(s=this.actionDict._nonterminal,s)?(hr.push([this,"_nonterminal",n]),s.apply(r,r._children())):(hr.push([this,"default action",n]),this.actionDict._default.apply(r,r._children()))}finally{hr.pop()}}}Sr.prototype.typeName="operation";class ys extends Sr{constructor(e,r,n){super(e,[],r,n)}execute(e,r){const n=r._node,s=e.attributeKeys[this.name];return gs(n,s)||(n[s]=Sr.prototype.execute.call(this,e,r)),n[s]}}ys.prototype.typeName="attribute";const $i=["_iter","_terminal","_nonterminal","_default"];function qi(t){return Object.keys(t.rules).sort().map(e=>t.rules[e])}const el=t=>t.replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029");let Eo,Oo;class Le{constructor(e,r,n,s){if(this.name=e,this.superGrammar=r,this.rules=n,s){if(!(s in n))throw new Error("Invalid start rule: '"+s+"' is not a rule in grammar '"+e+"'");this.defaultStartRule=s}this._matchStateInitializer=void 0,this.supportsIncrementalParsing=!0}matcher(){return new Yu(this)}isBuiltIn(){return this===Le.ProtoBuiltInRules||this===Le.BuiltInRules}equals(e){if(this===e)return!0;if(e==null||this.name!==e.name||this.defaultStartRule!==e.defaultStartRule||!(this.superGrammar===e.superGrammar||this.superGrammar.equals(e.superGrammar)))return!1;const r=qi(this),n=qi(e);return r.length===n.length&&r.every((s,i)=>s.description===n[i].description&&s.formals.join(",")===n[i].formals.join(",")&&s.body.toString()===n[i].body.toString())}match(e,r){const n=this.matcher();return n.replaceInputRange(0,0,e),n.match(r)}trace(e,r){const n=this.matcher();return n.replaceInputRange(0,0,e),n.trace(r)}createSemantics(){return $e.createSemantics(this)}extendSemantics(e){return $e.createSemantics(this,e._getSemantics())}_checkTopDownActionDict(e,r,n){const s=[];for(const i in n){const a=n[i];if(!$i.includes(i)&&!(i in this.rules)){s.push(`'${i}' is not a valid semantic action for '${this.name}'`);continue}if(typeof a!="function"){s.push(`'${i}' must be a function in an action dictionary for '${this.name}'`);continue}const c=a.length,u=this._topDownActionArity(i);if(c!==u){let d;i==="_iter"||i==="_nonterminal"?d=`it should use a rest parameter, e.g. \`${i}(...children) {}\`. NOTE: this is new in Ohm v16 — see https://ohmjs.org/d/ati for details.`:d=`expected ${u}, got ${c}`,s.push(`Semantic action '${i}' has the wrong arity: ${d}`)}}if(s.length>0){const i=s.map(o=>"- "+o),a=new Error([`Found errors in the action dictionary of the '${r}' ${e}:`,...i].join(`
30
- `));throw a.problems=s,a}}_topDownActionArity(e){return $i.includes(e)?0:this.rules[e].body.getArity()}_inheritsFrom(e){let r=this.superGrammar;for(;r;){if(r.equals(e,!0))return!0;r=r.superGrammar}return!1}toRecipe(e=void 0){const r={};this.source&&(r.source=this.source.contents);let n=null;this.defaultStartRule&&(n=this.defaultStartRule);const s={};Object.keys(this.rules).forEach(o=>{const c=this.rules[o],{body:u}=c,d=!this.superGrammar||!this.superGrammar.rules[o];let l;d?l="define":l=u instanceof jn?"extend":"override";const f={};if(c.source&&this.source){const S=c.source.relativeTo(this.source);f.sourceInterval=[S.startIdx,S.endIdx]}const y=d?c.description:null,b=u.outputRecipe(c.formals,this.source);s[o]=[l,f,y,c.formals,b]});let i="null";e?i=e:this.superGrammar&&!this.superGrammar.isBuiltIn()&&(i=this.superGrammar.toRecipe());const a=[...["grammar",r,this.name].map(JSON.stringify),i,...[n,s].map(JSON.stringify)];return el(`[${a.join(",")}]`)}toOperationActionDictionaryTemplate(){return this._toOperationOrAttributeActionDictionaryTemplate()}toAttributeActionDictionaryTemplate(){return this._toOperationOrAttributeActionDictionaryTemplate()}_toOperationOrAttributeActionDictionaryTemplate(){const e=new Bt;e.append("{");let r=!0;for(const n in this.rules){const{body:s}=this.rules[n];r?r=!1:e.append(","),e.append(`
29
+ `),n}addOperationOrAttribute(e,r,n){const s=e+"s",i=Mi(r,e),{name:a}=i,{formals:o}=i;this.assertNewName(a,e);const c=Yu(e,a,l),u={_default:c};Object.keys(n).forEach(f=>{u[f]=n[f]});const d=e==="operation"?new Sr(a,o,u,c):new gs(a,u,c);d.checkActionDict(this.grammar),this[s][a]=d;function l(...f){const y=this._semantics[s][a];if(arguments.length!==y.formals.length)throw new Error("Invalid number of arguments passed to "+a+" "+e+" (expected "+y.formals.length+", got "+arguments.length+")");const b=Object.create(null);for(const[T,L]of Object.entries(f)){const k=y.formals[T];b[k]=L}const S=this.args;this.args=b;const j=y.execute(this._semantics,this);return this.args=S,j}e==="operation"?(this.Wrapper.prototype[a]=l,this.Wrapper.prototype[a].toString=function(){return"["+a+" operation]"}):(Object.defineProperty(this.Wrapper.prototype,a,{get:l,configurable:!0}),Object.defineProperty(this.attributeKeys,a,{value:Li(a)}))}extendOperationOrAttribute(e,r,n){const s=e+"s";if(Mi(r,"attribute"),!(this.super&&r in this.super[s]))throw new Error("Cannot extend "+e+" '"+r+"': did not inherit an "+e+" with that name");if(ms(this[s],r))throw new Error("Cannot extend "+e+" '"+r+"' again");const i=this[s][r].formals,a=this[s][r].actionDict,o=Object.create(a);Object.keys(n).forEach(c=>{o[c]=n[c]}),this[s][r]=e==="operation"?new Sr(r,i,o):new gs(r,o),this[s][r].checkActionDict(this.grammar)}assertNewName(e,r){if(ms(Di.prototype,e))throw new Error("Cannot add "+r+" '"+e+"': that's a reserved name");if(e in this.operations)throw new Error("Cannot add "+r+" '"+e+"': an operation with that name already exists");if(e in this.attributes)throw new Error("Cannot add "+r+" '"+e+"': an attribute with that name already exists")}wrap(e,r,n){const s=n||r;return e instanceof this.Wrapper?e:new this.Wrapper(e,r,s)}}function Mi(t,e){if(!$e.prototypeGrammar)return It(t.indexOf("(")===-1),{name:t,formals:[]};const r=$e.prototypeGrammar.match(t,e==="operation"?"OperationSignature":"AttributeSignature");if(r.failed())throw new Error(r.message);return $e.prototypeGrammarSemantics(r).parse()}function Yu(t,e,r){return function(...n){const i=(this._semantics.operations[e]||this._semantics.attributes[e]).formals.map(a=>this.args[a]);if(!this.isIteration()&&n.length===1)return r.apply(n[0],i);throw Ru(this.ctorName,e,t,hr)}}$e.createSemantics=function(t,e){const r=new $e(t,e!==void 0?e:$e.BuiltInSemantics._getSemantics()),n=function(i){if(!(i instanceof _o))throw new TypeError("Semantics expected a MatchResult, but got "+Zs(i));if(i.failed())throw new TypeError("cannot apply Semantics to "+i.toString());const a=i._cst;if(a.grammar!==t)throw new Error("Cannot use a MatchResult from grammar '"+a.grammar.name+"' with a semantics for '"+t.name+"'");const o=new Dn(i.input);return r.wrap(a,o.interval(i._cstOffset,i.input.length))};return n.addOperation=function(s,i){return r.addOperationOrAttribute("operation",s,i),n},n.extendOperation=function(s,i){return r.extendOperationOrAttribute("operation",s,i),n},n.addAttribute=function(s,i){return r.addOperationOrAttribute("attribute",s,i),n},n.extendAttribute=function(s,i){return r.extendOperationOrAttribute("attribute",s,i),n},n._getActionDict=function(s){const i=r.operations[s]||r.attributes[s];if(!i)throw new Error('"'+s+'" is not a valid operation or attribute name in this semantics for "'+t.name+'"');return i.actionDict},n._remove=function(s){let i;return s in r.operations?(i=r.operations[s],delete r.operations[s]):s in r.attributes&&(i=r.attributes[s],delete r.attributes[s]),delete r.Wrapper.prototype[s],i},n.getOperationNames=function(){return Object.keys(r.operations)},n.getAttributeNames=function(){return Object.keys(r.attributes)},n.getGrammar=function(){return r.grammar},n.toRecipe=function(s){return r.toRecipe(s)},n.toString=r.toString.bind(r),n._getSemantics=function(){return r},n};class Sr{constructor(e,r,n,s){this.name=e,this.formals=r,this.actionDict=n,this.builtInDefault=s}checkActionDict(e){e._checkTopDownActionDict(this.typeName,this.name,this.actionDict)}execute(e,r){try{const{ctorName:n}=r._node;let s=this.actionDict[n];return s?(hr.push([this,n]),s.apply(r,r._children())):r.isNonterminal()&&(s=this.actionDict._nonterminal,s)?(hr.push([this,"_nonterminal",n]),s.apply(r,r._children())):(hr.push([this,"default action",n]),this.actionDict._default.apply(r,r._children()))}finally{hr.pop()}}}Sr.prototype.typeName="operation";class gs extends Sr{constructor(e,r,n){super(e,[],r,n)}execute(e,r){const n=r._node,s=e.attributeKeys[this.name];return ms(n,s)||(n[s]=Sr.prototype.execute.call(this,e,r)),n[s]}}gs.prototype.typeName="attribute";const Pi=["_iter","_terminal","_nonterminal","_default"];function $i(t){return Object.keys(t.rules).sort().map(e=>t.rules[e])}const Xu=t=>t.replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029");let ko,Eo;class Le{constructor(e,r,n,s){if(this.name=e,this.superGrammar=r,this.rules=n,s){if(!(s in n))throw new Error("Invalid start rule: '"+s+"' is not a rule in grammar '"+e+"'");this.defaultStartRule=s}this._matchStateInitializer=void 0,this.supportsIncrementalParsing=!0}matcher(){return new Qu(this)}isBuiltIn(){return this===Le.ProtoBuiltInRules||this===Le.BuiltInRules}equals(e){if(this===e)return!0;if(e==null||this.name!==e.name||this.defaultStartRule!==e.defaultStartRule||!(this.superGrammar===e.superGrammar||this.superGrammar.equals(e.superGrammar)))return!1;const r=$i(this),n=$i(e);return r.length===n.length&&r.every((s,i)=>s.description===n[i].description&&s.formals.join(",")===n[i].formals.join(",")&&s.body.toString()===n[i].body.toString())}match(e,r){const n=this.matcher();return n.replaceInputRange(0,0,e),n.match(r)}trace(e,r){const n=this.matcher();return n.replaceInputRange(0,0,e),n.trace(r)}createSemantics(){return $e.createSemantics(this)}extendSemantics(e){return $e.createSemantics(this,e._getSemantics())}_checkTopDownActionDict(e,r,n){const s=[];for(const i in n){const a=n[i];if(!Pi.includes(i)&&!(i in this.rules)){s.push(`'${i}' is not a valid semantic action for '${this.name}'`);continue}if(typeof a!="function"){s.push(`'${i}' must be a function in an action dictionary for '${this.name}'`);continue}const c=a.length,u=this._topDownActionArity(i);if(c!==u){let d;i==="_iter"||i==="_nonterminal"?d=`it should use a rest parameter, e.g. \`${i}(...children) {}\`. NOTE: this is new in Ohm v16 — see https://ohmjs.org/d/ati for details.`:d=`expected ${u}, got ${c}`,s.push(`Semantic action '${i}' has the wrong arity: ${d}`)}}if(s.length>0){const i=s.map(o=>"- "+o),a=new Error([`Found errors in the action dictionary of the '${r}' ${e}:`,...i].join(`
30
+ `));throw a.problems=s,a}}_topDownActionArity(e){return Pi.includes(e)?0:this.rules[e].body.getArity()}_inheritsFrom(e){let r=this.superGrammar;for(;r;){if(r.equals(e,!0))return!0;r=r.superGrammar}return!1}toRecipe(e=void 0){const r={};this.source&&(r.source=this.source.contents);let n=null;this.defaultStartRule&&(n=this.defaultStartRule);const s={};Object.keys(this.rules).forEach(o=>{const c=this.rules[o],{body:u}=c,d=!this.superGrammar||!this.superGrammar.rules[o];let l;d?l="define":l=u instanceof Ln?"extend":"override";const f={};if(c.source&&this.source){const S=c.source.relativeTo(this.source);f.sourceInterval=[S.startIdx,S.endIdx]}const y=d?c.description:null,b=u.outputRecipe(c.formals,this.source);s[o]=[l,f,y,c.formals,b]});let i="null";e?i=e:this.superGrammar&&!this.superGrammar.isBuiltIn()&&(i=this.superGrammar.toRecipe());const a=[...["grammar",r,this.name].map(JSON.stringify),i,...[n,s].map(JSON.stringify)];return Xu(`[${a.join(",")}]`)}toOperationActionDictionaryTemplate(){return this._toOperationOrAttributeActionDictionaryTemplate()}toAttributeActionDictionaryTemplate(){return this._toOperationOrAttributeActionDictionaryTemplate()}_toOperationOrAttributeActionDictionaryTemplate(){const e=new Bt;e.append("{");let r=!0;for(const n in this.rules){const{body:s}=this.rules[n];r?r=!1:e.append(","),e.append(`
31
31
  `),e.append(" "),this.addSemanticActionTemplate(n,s,e)}return e.append(`
32
- }`),e.contents()}addSemanticActionTemplate(e,r,n){n.append(e),n.append(": function(");const s=this._topDownActionArity(e);n.append(Ln("_",s).join(", ")),n.append(`) {
33
- `),n.append(" }")}parseApplication(e){let r;if(e.indexOf("<")===-1)r=new X(e);else{const s=Eo.match(e,"Base_application");r=Oo(s,{})}if(!(r.ruleName in this.rules))throw bo(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 vo(r.ruleName,n.length,r.args.length,s)}return r}_setUpMatchState(e){this._matchStateInitializer&&this._matchStateInitializer(e)}}Le.ProtoBuiltInRules=new Le("ProtoBuiltInRules",void 0,{any:{body:Te,formals:[],description:"any character",primitive:!0},end:{body:Re,formals:[],description:"end of input",primitive:!0},caseInsensitive:{body:new ti(new Fe(0)),formals:["str"],primitive:!0},lower:{body:new Ee("Ll"),formals:[],description:"a lowercase letter",primitive:!0},upper:{body:new Ee("Lu"),formals:[],description:"an uppercase letter",primitive:!0},unicodeLtmo:{body:new Ee("Ltmo"),formals:[],description:"a Unicode character in Lt, Lm, or Lo",primitive:!0},spaces:{body:new zt(new X("space")),formals:[]},space:{body:new Ne("\0"," "),formals:[],description:"a space"}});Le.initApplicationParser=function(t,e){Eo=t,Oo=e};class Ui{constructor(e){this.name=e}sourceInterval(e,r){return this.source.subInterval(e,r-e)}ensureSuperGrammar(){return this.superGrammar||this.withSuperGrammar(this.name==="BuiltInRules"?Le.ProtoBuiltInRules:Le.BuiltInRules),this.superGrammar}ensureSuperGrammarRuleForOverriding(e,r){const n=this.ensureSuperGrammar().rules[e];if(!n)throw Su(e,this.superGrammar.name,r);return n}installOverriddenOrExtendedRule(e,r,n,s){const i=ds(r);if(i.length>0)throw Ni(e,i,s);const a=this.ensureSuperGrammar().rules[e],o=a.formals,c=o?o.length:0;if(r.length!==c)throw vo(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 Mn(e).interval(0,e.length),this}build(){const e=new Le(this.name,this.ensureSuperGrammar(),this.rules,this.defaultStartRule);e._matchStateInitializer=e.superGrammar._matchStateInitializer,e.supportsIncrementalParsing=e.superGrammar.supportsIncrementalParsing;const r=[];let n=!1;return Object.keys(e.rules).forEach(s=>{const{body:i}=e.rules[s];try{i.assertChoicesHaveUniformArity(s)}catch(a){r.push(a)}try{i.assertAllApplicationsAreValid(s,e)}catch(a){r.push(a),n=!0}}),n||Object.keys(e.rules).forEach(s=>{const{body:i}=e.rules[s];try{i.assertIteratedExprsAreNotNullable(e,[])}catch(a){r.push(a)}}),r.length>0&&Fu(r),this.source&&(e.source=this.source),e}define(e,r,n,s,i,a){if(this.ensureSuperGrammar(),this.superGrammar.rules[e])throw Ri(e,this.name,this.superGrammar.name,i);if(this.rules[e])throw Ri(e,this.name,this.name,i);const o=ds(r);if(o.length>0)throw Ni(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 _u(e,this.superGrammar.name,i);const o=new jn(this.superGrammar,e,n);return o.source=n.source,this.installOverriddenOrExtendedRule(e,r,o,i),this}}class Xr{constructor(e){this.currentDecl=null,this.currentRuleName=null,this.options=e||{}}newGrammar(e){return new Ui(e)}grammar(e,r,n,s,i){const a=new Ui(r);return n&&a.withSuperGrammar(n instanceof Le?n:this.fromRecipe(n)),s&&a.withDefaultStartRule(s),e&&e.source&&a.withSource(e.source),this.currentDecl=a,Object.keys(i).forEach(o=>{this.currentRuleName=o;const c=i[o],u=c[0],d=c[1],l=c[2],f=c[3],y=this.fromRecipe(c[4]);let b;a.source&&d&&d.sourceInterval&&(b=a.source.subInterval(d.sourceInterval[0],d.sourceInterval[1]-d.sourceInterval[0])),a[u](o,f,y,l,b)}),this.currentRuleName=this.currentDecl=null,a.build()}terminal(e){return new Oe(e)}range(e,r){return new Ne(e,r)}param(e){return new Fe(e)}alt(...e){let r=[];for(let n of e)n instanceof z||(n=this.fromRecipe(n)),n instanceof be?r=r.concat(n.terms):r.push(n);return r.length===1?r[0]:new be(r)}seq(...e){let r=[];for(let n of e)n instanceof z||(n=this.fromRecipe(n)),n instanceof Ae?r=r.concat(n.factors):r.push(n);return r.length===1?r[0]:new Ae(r)}star(e){return e instanceof z||(e=this.fromRecipe(e)),new zt(e)}plus(e){return e instanceof z||(e=this.fromRecipe(e)),new ar(e)}opt(e){return e instanceof z||(e=this.fromRecipe(e)),new mt(e)}not(e){return e instanceof z||(e=this.fromRecipe(e)),new ke(e)}lookahead(e){return e instanceof z||(e=this.fromRecipe(e)),this.options.eliminateLookaheads?new ke(new ke(e)):new Pe(e)}lex(e){return e instanceof z||(e=this.fromRecipe(e)),new qe(e)}app(e,r){return r&&r.length>0&&(r=r.map(function(n){return n instanceof z?n:this.fromRecipe(n)},this)),new X(e,r)}splice(e,r){return new Dn(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 ri(t){return typeof t=="function"?t.call(new Xr):(typeof t=="string"&&(t=JSON.parse(t)),new Xr().fromRecipe(t))}const ni=ri(["grammar",{source:`BuiltInRules {
32
+ }`),e.contents()}addSemanticActionTemplate(e,r,n){n.append(e),n.append(": function(");const s=this._topDownActionArity(e);n.append(Fn("_",s).join(", ")),n.append(`) {
33
+ `),n.append(" }")}parseApplication(e){let r;if(e.indexOf("<")===-1)r=new X(e);else{const s=ko.match(e,"Base_application");r=Eo(s,{})}if(!(r.ruleName in this.rules))throw yo(r.ruleName,this.name);const{formals:n}=this.rules[r.ruleName];if(n.length!==r.args.length){const{source:s}=this.rules[r.ruleName];throw bo(r.ruleName,n.length,r.args.length,s)}return r}_setUpMatchState(e){this._matchStateInitializer&&this._matchStateInitializer(e)}}Le.ProtoBuiltInRules=new Le("ProtoBuiltInRules",void 0,{any:{body:Te,formals:[],description:"any character",primitive:!0},end:{body:Re,formals:[],description:"end of input",primitive:!0},caseInsensitive:{body:new ei(new Fe(0)),formals:["str"],primitive:!0},lower:{body:new Ee("Ll"),formals:[],description:"a lowercase letter",primitive:!0},upper:{body:new Ee("Lu"),formals:[],description:"an uppercase letter",primitive:!0},unicodeLtmo:{body:new Ee("Ltmo"),formals:[],description:"a Unicode character in Lt, Lm, or Lo",primitive:!0},spaces:{body:new zt(new X("space")),formals:[]},space:{body:new Ne("\0"," "),formals:[],description:"a space"}});Le.initApplicationParser=function(t,e){ko=t,Eo=e};class qi{constructor(e){this.name=e}sourceInterval(e,r){return this.source.subInterval(e,r-e)}ensureSuperGrammar(){return this.superGrammar||this.withSuperGrammar(this.name==="BuiltInRules"?Le.ProtoBuiltInRules:Le.BuiltInRules),this.superGrammar}ensureSuperGrammarRuleForOverriding(e,r){const n=this.ensureSuperGrammar().rules[e];if(!n)throw wu(e,this.superGrammar.name,r);return n}installOverriddenOrExtendedRule(e,r,n,s){const i=ls(r);if(i.length>0)throw Ri(e,i,s);const a=this.ensureSuperGrammar().rules[e],o=a.formals,c=o?o.length:0;if(r.length!==c)throw bo(e,c,r.length,s);return this.install(e,r,n,a.description,s)}install(e,r,n,s,i,a=!1){return this.rules[e]={body:n.introduceParams(r),formals:r,description:s,source:i,primitive:a},this}withSuperGrammar(e){if(this.superGrammar)throw new Error("the super grammar of a GrammarDecl cannot be set more than once");return this.superGrammar=e,this.rules=Object.create(e.rules),e.isBuiltIn()||(this.defaultStartRule=e.defaultStartRule),this}withDefaultStartRule(e){return this.defaultStartRule=e,this}withSource(e){return this.source=new Dn(e).interval(0,e.length),this}build(){const e=new Le(this.name,this.ensureSuperGrammar(),this.rules,this.defaultStartRule);e._matchStateInitializer=e.superGrammar._matchStateInitializer,e.supportsIncrementalParsing=e.superGrammar.supportsIncrementalParsing;const r=[];let n=!1;return Object.keys(e.rules).forEach(s=>{const{body:i}=e.rules[s];try{i.assertChoicesHaveUniformArity(s)}catch(a){r.push(a)}try{i.assertAllApplicationsAreValid(s,e)}catch(a){r.push(a),n=!0}}),n||Object.keys(e.rules).forEach(s=>{const{body:i}=e.rules[s];try{i.assertIteratedExprsAreNotNullable(e,[])}catch(a){r.push(a)}}),r.length>0&&Nu(r),this.source&&(e.source=this.source),e}define(e,r,n,s,i,a){if(this.ensureSuperGrammar(),this.superGrammar.rules[e])throw Ti(e,this.name,this.superGrammar.name,i);if(this.rules[e])throw Ti(e,this.name,this.name,i);const o=ls(r);if(o.length>0)throw Ri(e,o,i);return this.install(e,r,n,s,i,a)}override(e,r,n,s,i){return this.ensureSuperGrammarRuleForOverriding(e,i),this.installOverriddenOrExtendedRule(e,r,n,i),this}extend(e,r,n,s,i){if(!this.ensureSuperGrammar().rules[e])throw Su(e,this.superGrammar.name,i);const o=new Ln(this.superGrammar,e,n);return o.source=n.source,this.installOverriddenOrExtendedRule(e,r,o,i),this}}class Yr{constructor(e){this.currentDecl=null,this.currentRuleName=null,this.options=e||{}}newGrammar(e){return new qi(e)}grammar(e,r,n,s,i){const a=new qi(r);return n&&a.withSuperGrammar(n instanceof Le?n:this.fromRecipe(n)),s&&a.withDefaultStartRule(s),e&&e.source&&a.withSource(e.source),this.currentDecl=a,Object.keys(i).forEach(o=>{this.currentRuleName=o;const c=i[o],u=c[0],d=c[1],l=c[2],f=c[3],y=this.fromRecipe(c[4]);let b;a.source&&d&&d.sourceInterval&&(b=a.source.subInterval(d.sourceInterval[0],d.sourceInterval[1]-d.sourceInterval[0])),a[u](o,f,y,l,b)}),this.currentRuleName=this.currentDecl=null,a.build()}terminal(e){return new Oe(e)}range(e,r){return new Ne(e,r)}param(e){return new Fe(e)}alt(...e){let r=[];for(let n of e)n instanceof z||(n=this.fromRecipe(n)),n instanceof be?r=r.concat(n.terms):r.push(n);return r.length===1?r[0]:new be(r)}seq(...e){let r=[];for(let n of e)n instanceof z||(n=this.fromRecipe(n)),n instanceof Ae?r=r.concat(n.factors):r.push(n);return r.length===1?r[0]:new Ae(r)}star(e){return e instanceof z||(e=this.fromRecipe(e)),new zt(e)}plus(e){return e instanceof z||(e=this.fromRecipe(e)),new ar(e)}opt(e){return e instanceof z||(e=this.fromRecipe(e)),new mt(e)}not(e){return e instanceof z||(e=this.fromRecipe(e)),new ke(e)}lookahead(e){return e instanceof z||(e=this.fromRecipe(e)),this.options.eliminateLookaheads?new ke(new ke(e)):new Pe(e)}lex(e){return e instanceof z||(e=this.fromRecipe(e)),new qe(e)}app(e,r){return r&&r.length>0&&(r=r.map(function(n){return n instanceof z?n:this.fromRecipe(n)},this)),new X(e,r)}splice(e,r){return new jn(this.currentDecl.superGrammar,this.currentRuleName,e.map(n=>this.fromRecipe(n)),r.map(n=>this.fromRecipe(n)))}fromRecipe(e){const r=e[0]==="grammar"?e.slice(1):e.slice(2),n=this[e[0]](...r),s=e[1];return s&&s.sourceInterval&&this.currentDecl&&n.withSource(this.currentDecl.sourceInterval(...s.sourceInterval)),n}}function ti(t){return typeof t=="function"?t.call(new Yr):(typeof t=="string"&&(t=JSON.parse(t)),new Yr().fromRecipe(t))}const ri=ti(["grammar",{source:`BuiltInRules {
34
34
 
35
35
  alnum (an alpha-numeric character)
36
36
  = letter
@@ -71,7 +71,7 @@ NOTE: as of Ohm v16, there is no default action for iteration nodes — see `,"
71
71
 
72
72
  // Allows a syntactic rule application within a lexical context.
73
73
  applySyntactic<app> = app
74
- }`},"BuiltInRules",null,null,{alnum:["define",{sourceInterval:[18,78]},"an alpha-numeric character",[],["alt",{sourceInterval:[60,78]},["app",{sourceInterval:[60,66]},"letter",[]],["app",{sourceInterval:[73,78]},"digit",[]]]],letter:["define",{sourceInterval:[82,142]},"a letter",[],["alt",{sourceInterval:[107,142]},["app",{sourceInterval:[107,112]},"lower",[]],["app",{sourceInterval:[119,124]},"upper",[]],["app",{sourceInterval:[131,142]},"unicodeLtmo",[]]]],digit:["define",{sourceInterval:[146,177]},"a digit",[],["range",{sourceInterval:[169,177]},"0","9"]],hexDigit:["define",{sourceInterval:[181,254]},"a hexadecimal digit",[],["alt",{sourceInterval:[219,254]},["app",{sourceInterval:[219,224]},"digit",[]],["range",{sourceInterval:[231,239]},"a","f"],["range",{sourceInterval:[246,254]},"A","F"]]],ListOf:["define",{sourceInterval:[258,336]},null,["elem","sep"],["alt",{sourceInterval:[282,336]},["app",{sourceInterval:[282,307]},"NonemptyListOf",[["param",{sourceInterval:[297,301]},0],["param",{sourceInterval:[303,306]},1]]],["app",{sourceInterval:[314,336]},"EmptyListOf",[["param",{sourceInterval:[326,330]},0],["param",{sourceInterval:[332,335]},1]]]]],NonemptyListOf:["define",{sourceInterval:[340,388]},null,["elem","sep"],["seq",{sourceInterval:[372,388]},["param",{sourceInterval:[372,376]},0],["star",{sourceInterval:[377,388]},["seq",{sourceInterval:[378,386]},["param",{sourceInterval:[378,381]},1],["param",{sourceInterval:[382,386]},0]]]]],EmptyListOf:["define",{sourceInterval:[392,434]},null,["elem","sep"],["seq",{sourceInterval:[438,438]}]],listOf:["define",{sourceInterval:[438,516]},null,["elem","sep"],["alt",{sourceInterval:[462,516]},["app",{sourceInterval:[462,487]},"nonemptyListOf",[["param",{sourceInterval:[477,481]},0],["param",{sourceInterval:[483,486]},1]]],["app",{sourceInterval:[494,516]},"emptyListOf",[["param",{sourceInterval:[506,510]},0],["param",{sourceInterval:[512,515]},1]]]]],nonemptyListOf:["define",{sourceInterval:[520,568]},null,["elem","sep"],["seq",{sourceInterval:[552,568]},["param",{sourceInterval:[552,556]},0],["star",{sourceInterval:[557,568]},["seq",{sourceInterval:[558,566]},["param",{sourceInterval:[558,561]},1],["param",{sourceInterval:[562,566]},0]]]]],emptyListOf:["define",{sourceInterval:[572,682]},null,["elem","sep"],["seq",{sourceInterval:[685,685]}]],applySyntactic:["define",{sourceInterval:[685,710]},null,["app"],["param",{sourceInterval:[707,710]},0]]}]);Le.BuiltInRules=ni;Du(Le.BuiltInRules);const si=ri(["grammar",{source:`Ohm {
74
+ }`},"BuiltInRules",null,null,{alnum:["define",{sourceInterval:[18,78]},"an alpha-numeric character",[],["alt",{sourceInterval:[60,78]},["app",{sourceInterval:[60,66]},"letter",[]],["app",{sourceInterval:[73,78]},"digit",[]]]],letter:["define",{sourceInterval:[82,142]},"a letter",[],["alt",{sourceInterval:[107,142]},["app",{sourceInterval:[107,112]},"lower",[]],["app",{sourceInterval:[119,124]},"upper",[]],["app",{sourceInterval:[131,142]},"unicodeLtmo",[]]]],digit:["define",{sourceInterval:[146,177]},"a digit",[],["range",{sourceInterval:[169,177]},"0","9"]],hexDigit:["define",{sourceInterval:[181,254]},"a hexadecimal digit",[],["alt",{sourceInterval:[219,254]},["app",{sourceInterval:[219,224]},"digit",[]],["range",{sourceInterval:[231,239]},"a","f"],["range",{sourceInterval:[246,254]},"A","F"]]],ListOf:["define",{sourceInterval:[258,336]},null,["elem","sep"],["alt",{sourceInterval:[282,336]},["app",{sourceInterval:[282,307]},"NonemptyListOf",[["param",{sourceInterval:[297,301]},0],["param",{sourceInterval:[303,306]},1]]],["app",{sourceInterval:[314,336]},"EmptyListOf",[["param",{sourceInterval:[326,330]},0],["param",{sourceInterval:[332,335]},1]]]]],NonemptyListOf:["define",{sourceInterval:[340,388]},null,["elem","sep"],["seq",{sourceInterval:[372,388]},["param",{sourceInterval:[372,376]},0],["star",{sourceInterval:[377,388]},["seq",{sourceInterval:[378,386]},["param",{sourceInterval:[378,381]},1],["param",{sourceInterval:[382,386]},0]]]]],EmptyListOf:["define",{sourceInterval:[392,434]},null,["elem","sep"],["seq",{sourceInterval:[438,438]}]],listOf:["define",{sourceInterval:[438,516]},null,["elem","sep"],["alt",{sourceInterval:[462,516]},["app",{sourceInterval:[462,487]},"nonemptyListOf",[["param",{sourceInterval:[477,481]},0],["param",{sourceInterval:[483,486]},1]]],["app",{sourceInterval:[494,516]},"emptyListOf",[["param",{sourceInterval:[506,510]},0],["param",{sourceInterval:[512,515]},1]]]]],nonemptyListOf:["define",{sourceInterval:[520,568]},null,["elem","sep"],["seq",{sourceInterval:[552,568]},["param",{sourceInterval:[552,556]},0],["star",{sourceInterval:[557,568]},["seq",{sourceInterval:[558,566]},["param",{sourceInterval:[558,561]},1],["param",{sourceInterval:[562,566]},0]]]]],emptyListOf:["define",{sourceInterval:[572,682]},null,["elem","sep"],["seq",{sourceInterval:[685,685]}]],applySyntactic:["define",{sourceInterval:[685,710]},null,["app"],["param",{sourceInterval:[707,710]},0]]}]);Le.BuiltInRules=ri;ju(Le.BuiltInRules);const ni=ti(["grammar",{source:`Ohm {
75
75
 
76
76
  Grammars
77
77
  = Grammar*
@@ -200,7 +200,7 @@ NOTE: as of Ohm v16, there is no default action for iteration nodes — see `,"
200
200
  `],["lookahead",{sourceInterval:[1333,1337]},["terminal",{sourceInterval:[1334,1337]},"}"]]]]],name:["define",{sourceInterval:[1342,1382]},"a name",[],["seq",{sourceInterval:[1363,1382]},["app",{sourceInterval:[1363,1372]},"nameFirst",[]],["star",{sourceInterval:[1373,1382]},["app",{sourceInterval:[1373,1381]},"nameRest",[]]]]],nameFirst:["define",{sourceInterval:[1386,1418]},null,[],["alt",{sourceInterval:[1402,1418]},["terminal",{sourceInterval:[1402,1405]},"_"],["app",{sourceInterval:[1412,1418]},"letter",[]]]],nameRest:["define",{sourceInterval:[1422,1452]},null,[],["alt",{sourceInterval:[1437,1452]},["terminal",{sourceInterval:[1437,1440]},"_"],["app",{sourceInterval:[1447,1452]},"alnum",[]]]],ident:["define",{sourceInterval:[1456,1489]},"an identifier",[],["app",{sourceInterval:[1485,1489]},"name",[]]],terminal:["define",{sourceInterval:[1493,1531]},null,[],["seq",{sourceInterval:[1508,1531]},["terminal",{sourceInterval:[1508,1512]},'"'],["star",{sourceInterval:[1513,1526]},["app",{sourceInterval:[1513,1525]},"terminalChar",[]]],["terminal",{sourceInterval:[1527,1531]},'"']]],oneCharTerminal:["define",{sourceInterval:[1535,1579]},null,[],["seq",{sourceInterval:[1557,1579]},["terminal",{sourceInterval:[1557,1561]},'"'],["app",{sourceInterval:[1562,1574]},"terminalChar",[]],["terminal",{sourceInterval:[1575,1579]},'"']]],terminalChar:["define",{sourceInterval:[1583,1660]},null,[],["alt",{sourceInterval:[1602,1660]},["app",{sourceInterval:[1602,1612]},"escapeChar",[]],["seq",{sourceInterval:[1621,1660]},["not",{sourceInterval:[1621,1626]},["terminal",{sourceInterval:[1622,1626]},"\\"]],["not",{sourceInterval:[1627,1632]},["terminal",{sourceInterval:[1628,1632]},'"']],["not",{sourceInterval:[1633,1638]},["terminal",{sourceInterval:[1634,1638]},`
201
201
  `]],["range",{sourceInterval:[1639,1660]},"\0","􏿿"]]]],escapeChar_backslash:["define",{sourceInterval:[1703,1758]},null,[],["terminal",{sourceInterval:[1703,1709]},"\\\\"]],escapeChar_doubleQuote:["define",{sourceInterval:[1765,1822]},null,[],["terminal",{sourceInterval:[1765,1771]},'\\"']],escapeChar_singleQuote:["define",{sourceInterval:[1829,1886]},null,[],["terminal",{sourceInterval:[1829,1835]},"\\'"]],escapeChar_backspace:["define",{sourceInterval:[1893,1948]},null,[],["terminal",{sourceInterval:[1893,1898]},"\\b"]],escapeChar_lineFeed:["define",{sourceInterval:[1955,2009]},null,[],["terminal",{sourceInterval:[1955,1960]},"\\n"]],escapeChar_carriageReturn:["define",{sourceInterval:[2016,2076]},null,[],["terminal",{sourceInterval:[2016,2021]},"\\r"]],escapeChar_tab:["define",{sourceInterval:[2083,2132]},null,[],["terminal",{sourceInterval:[2083,2088]},"\\t"]],escapeChar_unicodeCodePoint:["define",{sourceInterval:[2139,2243]},null,[],["seq",{sourceInterval:[2139,2221]},["terminal",{sourceInterval:[2139,2145]},"\\u{"],["app",{sourceInterval:[2146,2154]},"hexDigit",[]],["opt",{sourceInterval:[2155,2164]},["app",{sourceInterval:[2155,2163]},"hexDigit",[]]],["opt",{sourceInterval:[2165,2174]},["app",{sourceInterval:[2165,2173]},"hexDigit",[]]],["opt",{sourceInterval:[2188,2197]},["app",{sourceInterval:[2188,2196]},"hexDigit",[]]],["opt",{sourceInterval:[2198,2207]},["app",{sourceInterval:[2198,2206]},"hexDigit",[]]],["opt",{sourceInterval:[2208,2217]},["app",{sourceInterval:[2208,2216]},"hexDigit",[]]],["terminal",{sourceInterval:[2218,2221]},"}"]]],escapeChar_unicodeEscape:["define",{sourceInterval:[2250,2309]},null,[],["seq",{sourceInterval:[2250,2291]},["terminal",{sourceInterval:[2250,2255]},"\\u"],["app",{sourceInterval:[2256,2264]},"hexDigit",[]],["app",{sourceInterval:[2265,2273]},"hexDigit",[]],["app",{sourceInterval:[2274,2282]},"hexDigit",[]],["app",{sourceInterval:[2283,2291]},"hexDigit",[]]]],escapeChar_hexEscape:["define",{sourceInterval:[2316,2371]},null,[],["seq",{sourceInterval:[2316,2339]},["terminal",{sourceInterval:[2316,2321]},"\\x"],["app",{sourceInterval:[2322,2330]},"hexDigit",[]],["app",{sourceInterval:[2331,2339]},"hexDigit",[]]]],escapeChar:["define",{sourceInterval:[1664,2371]},"an escape sequence",[],["alt",{sourceInterval:[1703,2371]},["app",{sourceInterval:[1703,1709]},"escapeChar_backslash",[]],["app",{sourceInterval:[1765,1771]},"escapeChar_doubleQuote",[]],["app",{sourceInterval:[1829,1835]},"escapeChar_singleQuote",[]],["app",{sourceInterval:[1893,1898]},"escapeChar_backspace",[]],["app",{sourceInterval:[1955,1960]},"escapeChar_lineFeed",[]],["app",{sourceInterval:[2016,2021]},"escapeChar_carriageReturn",[]],["app",{sourceInterval:[2083,2088]},"escapeChar_tab",[]],["app",{sourceInterval:[2139,2221]},"escapeChar_unicodeCodePoint",[]],["app",{sourceInterval:[2250,2291]},"escapeChar_unicodeEscape",[]],["app",{sourceInterval:[2316,2339]},"escapeChar_hexEscape",[]]]],space:["extend",{sourceInterval:[2375,2394]},null,[],["app",{sourceInterval:[2387,2394]},"comment",[]]],comment_singleLine:["define",{sourceInterval:[2412,2458]},null,[],["seq",{sourceInterval:[2412,2443]},["terminal",{sourceInterval:[2412,2416]},"//"],["star",{sourceInterval:[2417,2429]},["seq",{sourceInterval:[2418,2427]},["not",{sourceInterval:[2418,2423]},["terminal",{sourceInterval:[2419,2423]},`
202
202
  `]],["app",{sourceInterval:[2424,2427]},"any",[]]]],["lookahead",{sourceInterval:[2430,2443]},["alt",{sourceInterval:[2432,2442]},["terminal",{sourceInterval:[2432,2436]},`
203
- `],["app",{sourceInterval:[2439,2442]},"end",[]]]]]],comment_multiLine:["define",{sourceInterval:[2465,2501]},null,[],["seq",{sourceInterval:[2465,2487]},["terminal",{sourceInterval:[2465,2469]},"/*"],["star",{sourceInterval:[2470,2482]},["seq",{sourceInterval:[2471,2480]},["not",{sourceInterval:[2471,2476]},["terminal",{sourceInterval:[2472,2476]},"*/"]],["app",{sourceInterval:[2477,2480]},"any",[]]]],["terminal",{sourceInterval:[2483,2487]},"*/"]]],comment:["define",{sourceInterval:[2398,2501]},null,[],["alt",{sourceInterval:[2412,2501]},["app",{sourceInterval:[2412,2443]},"comment_singleLine",[]],["app",{sourceInterval:[2465,2487]},"comment_multiLine",[]]]],tokens:["define",{sourceInterval:[2505,2520]},null,[],["star",{sourceInterval:[2514,2520]},["app",{sourceInterval:[2514,2519]},"token",[]]]],token:["define",{sourceInterval:[2524,2600]},null,[],["alt",{sourceInterval:[2532,2600]},["app",{sourceInterval:[2532,2540]},"caseName",[]],["app",{sourceInterval:[2543,2550]},"comment",[]],["app",{sourceInterval:[2553,2558]},"ident",[]],["app",{sourceInterval:[2561,2569]},"operator",[]],["app",{sourceInterval:[2572,2583]},"punctuation",[]],["app",{sourceInterval:[2586,2594]},"terminal",[]],["app",{sourceInterval:[2597,2600]},"any",[]]]],operator:["define",{sourceInterval:[2604,2669]},null,[],["alt",{sourceInterval:[2615,2669]},["terminal",{sourceInterval:[2615,2619]},"<:"],["terminal",{sourceInterval:[2622,2625]},"="],["terminal",{sourceInterval:[2628,2632]},":="],["terminal",{sourceInterval:[2635,2639]},"+="],["terminal",{sourceInterval:[2642,2645]},"*"],["terminal",{sourceInterval:[2648,2651]},"+"],["terminal",{sourceInterval:[2654,2657]},"?"],["terminal",{sourceInterval:[2660,2663]},"~"],["terminal",{sourceInterval:[2666,2669]},"&"]]],punctuation:["define",{sourceInterval:[2673,2709]},null,[],["alt",{sourceInterval:[2687,2709]},["terminal",{sourceInterval:[2687,2690]},"<"],["terminal",{sourceInterval:[2693,2696]},">"],["terminal",{sourceInterval:[2699,2702]},","],["terminal",{sourceInterval:[2705,2709]},"--"]]]}]),Gn=Object.create(z.prototype);function Bi(t,e){for(const r in t)if(r===e)return!0;return!1}function Co(t,e,r,n){const s=new Xr(n);let i,a,o,c=!1;return(r||si).createSemantics().addOperation("visit",{Grammars(l){return l.children.map(f=>f.visit())},Grammar(l,f,y,b,S){const j=l.visit();i=s.newGrammar(j),f.child(0)&&f.child(0).visit(),b.children.map(L=>L.visit());const T=i.build();if(T.source=this.source.trimmed(),Bi(e,j))throw vu(T);return e[j]=T,T},SuperGrammar(l,f){const y=f.visit();if(y==="null")i.withSuperGrammar(null);else{if(!e||!Bi(e,y))throw bu(y,e,f.source);i.withSuperGrammar(e[y])}},Rule_define(l,f,y,b,S){a=l.visit(),o=f.children.map(k=>k.visit())[0]||[],!i.defaultStartRule&&i.ensureSuperGrammar()!==Le.ProtoBuiltInRules&&i.withDefaultStartRule(a);const j=S.visit(),T=y.children.map(k=>k.visit())[0],L=this.source.trimmed();return i.define(a,o,j,T,L)},Rule_override(l,f,y,b){a=l.visit(),o=f.children.map(T=>T.visit())[0]||[];const S=this.source.trimmed();i.ensureSuperGrammarRuleForOverriding(a,S),c=!0;const j=b.visit();return c=!1,i.override(a,o,j,null,S)},Rule_extend(l,f,y,b){a=l.visit(),o=f.children.map(T=>T.visit())[0]||[];const S=b.visit(),j=this.source.trimmed();return i.extend(a,o,S,null,j)},RuleBody(l,f){return s.alt(...f.visit()).withSource(this.source)},OverrideRuleBody(l,f){const y=f.visit(),b=y.indexOf(Gn);if(b>=0){const S=y.slice(0,b),j=y.slice(b+1);return j.forEach(T=>{if(T===Gn)throw Cu(T)}),new Dn(i.superGrammar,a,S,j).withSource(this.source)}else return s.alt(...y).withSource(this.source)},Formals(l,f,y){return f.visit()},Params(l,f,y){return f.visit()},Alt(l){return s.alt(...l.visit()).withSource(this.source)},TopLevelTerm_inline(l,f){const y=a+"_"+f.visit(),b=l.visit(),S=this.source.trimmed(),j=!(i.superGrammar&&i.superGrammar.rules[y]);c&&!j?i.override(y,o,b,null,S):i.define(y,o,b,null,S);const T=o.map(L=>s.app(L));return s.app(y,T).withSource(b.source)},OverrideTopLevelTerm_superSplice(l){return Gn},Seq(l){return s.seq(...l.children.map(f=>f.visit())).withSource(this.source)},Iter_star(l,f){return s.star(l.visit()).withSource(this.source)},Iter_plus(l,f){return s.plus(l.visit()).withSource(this.source)},Iter_opt(l,f){return s.opt(l.visit()).withSource(this.source)},Pred_not(l,f){return s.not(f.visit()).withSource(this.source)},Pred_lookahead(l,f){return s.lookahead(f.visit()).withSource(this.source)},Lex_lex(l,f){return s.lex(f.visit()).withSource(this.source)},Base_application(l,f){const y=f.children.map(b=>b.visit())[0]||[];return s.app(l.visit(),y).withSource(this.source)},Base_range(l,f,y){return s.range(l.visit(),y.visit()).withSource(this.source)},Base_terminal(l){return s.terminal(l.visit()).withSource(this.source)},Base_paren(l,f,y){return f.visit()},ruleDescr(l,f,y){return f.visit()},ruleDescrText(l){return this.sourceString.trim()},caseName(l,f,y,b,S){return y.visit()},name(l,f){return this.sourceString},nameFirst(l){},nameRest(l){},terminal(l,f,y){return f.children.map(b=>b.visit()).join("")},oneCharTerminal(l,f,y){return f.visit()},escapeChar(l){try{return mo(this.sourceString)}catch(f){throw f instanceof RangeError&&f.message.startsWith("Invalid code point ")?Tu(l):f}},NonemptyListOf(l,f,y){return[l.visit()].concat(y.children.map(b=>b.visit()))},EmptyListOf(){return[]},_terminal(){return this.sourceString}})(t).visit()}const tl=ri(["grammar",{source:`OperationsAndAttributes {
203
+ `],["app",{sourceInterval:[2439,2442]},"end",[]]]]]],comment_multiLine:["define",{sourceInterval:[2465,2501]},null,[],["seq",{sourceInterval:[2465,2487]},["terminal",{sourceInterval:[2465,2469]},"/*"],["star",{sourceInterval:[2470,2482]},["seq",{sourceInterval:[2471,2480]},["not",{sourceInterval:[2471,2476]},["terminal",{sourceInterval:[2472,2476]},"*/"]],["app",{sourceInterval:[2477,2480]},"any",[]]]],["terminal",{sourceInterval:[2483,2487]},"*/"]]],comment:["define",{sourceInterval:[2398,2501]},null,[],["alt",{sourceInterval:[2412,2501]},["app",{sourceInterval:[2412,2443]},"comment_singleLine",[]],["app",{sourceInterval:[2465,2487]},"comment_multiLine",[]]]],tokens:["define",{sourceInterval:[2505,2520]},null,[],["star",{sourceInterval:[2514,2520]},["app",{sourceInterval:[2514,2519]},"token",[]]]],token:["define",{sourceInterval:[2524,2600]},null,[],["alt",{sourceInterval:[2532,2600]},["app",{sourceInterval:[2532,2540]},"caseName",[]],["app",{sourceInterval:[2543,2550]},"comment",[]],["app",{sourceInterval:[2553,2558]},"ident",[]],["app",{sourceInterval:[2561,2569]},"operator",[]],["app",{sourceInterval:[2572,2583]},"punctuation",[]],["app",{sourceInterval:[2586,2594]},"terminal",[]],["app",{sourceInterval:[2597,2600]},"any",[]]]],operator:["define",{sourceInterval:[2604,2669]},null,[],["alt",{sourceInterval:[2615,2669]},["terminal",{sourceInterval:[2615,2619]},"<:"],["terminal",{sourceInterval:[2622,2625]},"="],["terminal",{sourceInterval:[2628,2632]},":="],["terminal",{sourceInterval:[2635,2639]},"+="],["terminal",{sourceInterval:[2642,2645]},"*"],["terminal",{sourceInterval:[2648,2651]},"+"],["terminal",{sourceInterval:[2654,2657]},"?"],["terminal",{sourceInterval:[2660,2663]},"~"],["terminal",{sourceInterval:[2666,2669]},"&"]]],punctuation:["define",{sourceInterval:[2673,2709]},null,[],["alt",{sourceInterval:[2687,2709]},["terminal",{sourceInterval:[2687,2690]},"<"],["terminal",{sourceInterval:[2693,2696]},">"],["terminal",{sourceInterval:[2699,2702]},","],["terminal",{sourceInterval:[2705,2709]},"--"]]]}]),Hn=Object.create(z.prototype);function Ui(t,e){for(const r in t)if(r===e)return!0;return!1}function Oo(t,e,r,n){const s=new Yr(n);let i,a,o,c=!1;return(r||ni).createSemantics().addOperation("visit",{Grammars(l){return l.children.map(f=>f.visit())},Grammar(l,f,y,b,S){const j=l.visit();i=s.newGrammar(j),f.child(0)&&f.child(0).visit(),b.children.map(L=>L.visit());const T=i.build();if(T.source=this.source.trimmed(),Ui(e,j))throw bu(T);return e[j]=T,T},SuperGrammar(l,f){const y=f.visit();if(y==="null")i.withSuperGrammar(null);else{if(!e||!Ui(e,y))throw yu(y,e,f.source);i.withSuperGrammar(e[y])}},Rule_define(l,f,y,b,S){a=l.visit(),o=f.children.map(k=>k.visit())[0]||[],!i.defaultStartRule&&i.ensureSuperGrammar()!==Le.ProtoBuiltInRules&&i.withDefaultStartRule(a);const j=S.visit(),T=y.children.map(k=>k.visit())[0],L=this.source.trimmed();return i.define(a,o,j,T,L)},Rule_override(l,f,y,b){a=l.visit(),o=f.children.map(T=>T.visit())[0]||[];const S=this.source.trimmed();i.ensureSuperGrammarRuleForOverriding(a,S),c=!0;const j=b.visit();return c=!1,i.override(a,o,j,null,S)},Rule_extend(l,f,y,b){a=l.visit(),o=f.children.map(T=>T.visit())[0]||[];const S=b.visit(),j=this.source.trimmed();return i.extend(a,o,S,null,j)},RuleBody(l,f){return s.alt(...f.visit()).withSource(this.source)},OverrideRuleBody(l,f){const y=f.visit(),b=y.indexOf(Hn);if(b>=0){const S=y.slice(0,b),j=y.slice(b+1);return j.forEach(T=>{if(T===Hn)throw Ou(T)}),new jn(i.superGrammar,a,S,j).withSource(this.source)}else return s.alt(...y).withSource(this.source)},Formals(l,f,y){return f.visit()},Params(l,f,y){return f.visit()},Alt(l){return s.alt(...l.visit()).withSource(this.source)},TopLevelTerm_inline(l,f){const y=a+"_"+f.visit(),b=l.visit(),S=this.source.trimmed(),j=!(i.superGrammar&&i.superGrammar.rules[y]);c&&!j?i.override(y,o,b,null,S):i.define(y,o,b,null,S);const T=o.map(L=>s.app(L));return s.app(y,T).withSource(b.source)},OverrideTopLevelTerm_superSplice(l){return Hn},Seq(l){return s.seq(...l.children.map(f=>f.visit())).withSource(this.source)},Iter_star(l,f){return s.star(l.visit()).withSource(this.source)},Iter_plus(l,f){return s.plus(l.visit()).withSource(this.source)},Iter_opt(l,f){return s.opt(l.visit()).withSource(this.source)},Pred_not(l,f){return s.not(f.visit()).withSource(this.source)},Pred_lookahead(l,f){return s.lookahead(f.visit()).withSource(this.source)},Lex_lex(l,f){return s.lex(f.visit()).withSource(this.source)},Base_application(l,f){const y=f.children.map(b=>b.visit())[0]||[];return s.app(l.visit(),y).withSource(this.source)},Base_range(l,f,y){return s.range(l.visit(),y.visit()).withSource(this.source)},Base_terminal(l){return s.terminal(l.visit()).withSource(this.source)},Base_paren(l,f,y){return f.visit()},ruleDescr(l,f,y){return f.visit()},ruleDescrText(l){return this.sourceString.trim()},caseName(l,f,y,b,S){return y.visit()},name(l,f){return this.sourceString},nameFirst(l){},nameRest(l){},terminal(l,f,y){return f.children.map(b=>b.visit()).join("")},oneCharTerminal(l,f,y){return f.visit()},escapeChar(l){try{return po(this.sourceString)}catch(f){throw f instanceof RangeError&&f.message.startsWith("Invalid code point ")?Cu(l):f}},NonemptyListOf(l,f,y){return[l.visit()].concat(y.children.map(b=>b.visit()))},EmptyListOf(){return[]},_terminal(){return this.sourceString}})(t).visit()}const el=ti(["grammar",{source:`OperationsAndAttributes {
204
204
 
205
205
  AttributeSignature =
206
206
  name
@@ -222,7 +222,7 @@ NOTE: as of Ohm v16, there is no default action for iteration nodes — see `,"
222
222
  = "_"
223
223
  | alnum
224
224
 
225
- }`},"OperationsAndAttributes",null,"AttributeSignature",{AttributeSignature:["define",{sourceInterval:[29,58]},null,[],["app",{sourceInterval:[54,58]},"name",[]]],OperationSignature:["define",{sourceInterval:[62,100]},null,[],["seq",{sourceInterval:[87,100]},["app",{sourceInterval:[87,91]},"name",[]],["opt",{sourceInterval:[92,100]},["app",{sourceInterval:[92,99]},"Formals",[]]]]],Formals:["define",{sourceInterval:[104,143]},null,[],["seq",{sourceInterval:[118,143]},["terminal",{sourceInterval:[118,121]},"("],["app",{sourceInterval:[122,139]},"ListOf",[["app",{sourceInterval:[129,133]},"name",[]],["terminal",{sourceInterval:[135,138]},","]]],["terminal",{sourceInterval:[140,143]},")"]]],name:["define",{sourceInterval:[147,187]},"a name",[],["seq",{sourceInterval:[168,187]},["app",{sourceInterval:[168,177]},"nameFirst",[]],["star",{sourceInterval:[178,187]},["app",{sourceInterval:[178,186]},"nameRest",[]]]]],nameFirst:["define",{sourceInterval:[191,223]},null,[],["alt",{sourceInterval:[207,223]},["terminal",{sourceInterval:[207,210]},"_"],["app",{sourceInterval:[217,223]},"letter",[]]]],nameRest:["define",{sourceInterval:[227,257]},null,[],["alt",{sourceInterval:[242,257]},["terminal",{sourceInterval:[242,245]},"_"],["app",{sourceInterval:[252,257]},"alnum",[]]]]}]);rl(Le.BuiltInRules);nl(tl);function rl(t){const e={empty(){return this.iteration()},nonEmpty(r,n,s){return this.iteration([r].concat(s.children))},self(...r){return this}};$e.BuiltInSemantics=$e.createSemantics(t,null).addOperation("asIteration",{emptyListOf:e.empty,nonemptyListOf:e.nonEmpty,EmptyListOf:e.empty,NonemptyListOf:e.nonEmpty,_iter:e.self})}function nl(t){$e.prototypeGrammarSemantics=t.createSemantics().addOperation("parse",{AttributeSignature(e){return{name:e.parse(),formals:[]}},OperationSignature(e,r){return{name:e.parse(),formals:r.children.map(n=>n.parse())[0]||[]}},Formals(e,r,n){return r.asIteration().children.map(s=>s.parse())},name(e,r){return this.sourceString}}),$e.prototypeGrammar=t}function sl(t){let e=0;const r=[0],n=()=>r[r.length-1],s={},i=/( *).*(?:$|\r?\n|\r)/g;let a;for(;(a=i.exec(t))!=null;){const[o,c]=a;if(o.length===0)break;const u=c.length,d=n(),l=e+u;if(u>d)r.push(u),s[l]=1;else if(u<d){const f=r.length;for(;n()!==u;)r.pop();s[l]=-1*(f-r.length)}e+=o.length}return r.length>1&&(s[e]=1-r.length),s}const To="an indented block",Ro="a dedent",zi=1114112;class il extends Mn{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),zi):super.nextCharCode()}nextCodePoint(){return this._indentationAt(this.pos)!==0?(this.examinedLength=Math.max(this.examinedLength,this.pos),zi):super.nextCodePoint()}}class Vi extends z{constructor(e=!0){super(),this.isIndent=e}allowsSkippingPrecedingSpace(){return!0}eval(e){const{inputStream:r}=e,n=e.userData;e.doNotMemoize=!0;const s=r.pos,i=this.isIndent?1:-1;return(n[s]||0)*i>0?(e.userData=Object.create(n),e.userData[s]-=i,e.pushBinding(new Vt(0),s),!0):(e.processFailure(s,this),!1)}getArity(){return 1}_assertAllApplicationsAreValid(e,r){}_isNullable(e,r){return!1}assertChoicesHaveUniformArity(e){}assertIteratedExprsAreNotNullable(e){}introduceParams(e){return this}substituteParams(e){return this}toString(){return this.isIndent?"indent":"dedent"}toDisplayString(){return this.toString()}toFailure(e){const r=this.isIndent?To:Ro;return new Ue(this,r,"description")}}const al=new X("indent"),ol=new X("dedent"),cl=new Dn(ni,"any",[al,ol],[]),ul=new Xr().newGrammar("IndentationSensitive").withSuperGrammar(ni).define("indent",[],new Vi(!0),To,void 0,!0).define("dedent",[],new Vi(!1),Ro,void 0,!0).extend("any",[],cl,"any character",void 0).build();Object.assign(ul,{_matchStateInitializer(t){t.userData=sl(t.input),t.inputStream=new il(t)},supportsIncrementalParsing:!1});Le.initApplicationParser(si,Co);const ll=t=>!!t.constructor&&typeof t.constructor.isBuffer=="function"&&t.constructor.isBuffer(t);function dl(t,e,r){const n=si.match(t,"Grammars");if(n.failed())throw yu(n);return Co(n,e,void 0,r)}function hl(t,e,r){const n=fl(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(Ys(a.sourceString,a.startIdx)+"Found more than one grammar definition -- use ohm.grammars() instead.")}return n[s[0]]}function fl(t,e,r){const n=Object.create({});if(typeof t!="string")if(ll(t))t=t.toString();else throw new TypeError("Expected string as first argument, got "+Js(t));return dl(t,n,r),n}function pl(t,e){return hl(t,e)}const ml=`FirestoreRules {
225
+ }`},"OperationsAndAttributes",null,"AttributeSignature",{AttributeSignature:["define",{sourceInterval:[29,58]},null,[],["app",{sourceInterval:[54,58]},"name",[]]],OperationSignature:["define",{sourceInterval:[62,100]},null,[],["seq",{sourceInterval:[87,100]},["app",{sourceInterval:[87,91]},"name",[]],["opt",{sourceInterval:[92,100]},["app",{sourceInterval:[92,99]},"Formals",[]]]]],Formals:["define",{sourceInterval:[104,143]},null,[],["seq",{sourceInterval:[118,143]},["terminal",{sourceInterval:[118,121]},"("],["app",{sourceInterval:[122,139]},"ListOf",[["app",{sourceInterval:[129,133]},"name",[]],["terminal",{sourceInterval:[135,138]},","]]],["terminal",{sourceInterval:[140,143]},")"]]],name:["define",{sourceInterval:[147,187]},"a name",[],["seq",{sourceInterval:[168,187]},["app",{sourceInterval:[168,177]},"nameFirst",[]],["star",{sourceInterval:[178,187]},["app",{sourceInterval:[178,186]},"nameRest",[]]]]],nameFirst:["define",{sourceInterval:[191,223]},null,[],["alt",{sourceInterval:[207,223]},["terminal",{sourceInterval:[207,210]},"_"],["app",{sourceInterval:[217,223]},"letter",[]]]],nameRest:["define",{sourceInterval:[227,257]},null,[],["alt",{sourceInterval:[242,257]},["terminal",{sourceInterval:[242,245]},"_"],["app",{sourceInterval:[252,257]},"alnum",[]]]]}]);tl(Le.BuiltInRules);rl(el);function tl(t){const e={empty(){return this.iteration()},nonEmpty(r,n,s){return this.iteration([r].concat(s.children))},self(...r){return this}};$e.BuiltInSemantics=$e.createSemantics(t,null).addOperation("asIteration",{emptyListOf:e.empty,nonemptyListOf:e.nonEmpty,EmptyListOf:e.empty,NonemptyListOf:e.nonEmpty,_iter:e.self})}function rl(t){$e.prototypeGrammarSemantics=t.createSemantics().addOperation("parse",{AttributeSignature(e){return{name:e.parse(),formals:[]}},OperationSignature(e,r){return{name:e.parse(),formals:r.children.map(n=>n.parse())[0]||[]}},Formals(e,r,n){return r.asIteration().children.map(s=>s.parse())},name(e,r){return this.sourceString}}),$e.prototypeGrammar=t}function nl(t){let e=0;const r=[0],n=()=>r[r.length-1],s={},i=/( *).*(?:$|\r?\n|\r)/g;let a;for(;(a=i.exec(t))!=null;){const[o,c]=a;if(o.length===0)break;const u=c.length,d=n(),l=e+u;if(u>d)r.push(u),s[l]=1;else if(u<d){const f=r.length;for(;n()!==u;)r.pop();s[l]=-1*(f-r.length)}e+=o.length}return r.length>1&&(s[e]=1-r.length),s}const Co="an indented block",To="a dedent",Bi=1114112;class sl extends Dn{constructor(e){super(e.input),this.state=e}_indentationAt(e){return this.state.userData[e]||0}atEnd(){return super.atEnd()&&this._indentationAt(this.pos)===0}next(){if(this._indentationAt(this.pos)!==0){this.examinedLength=Math.max(this.examinedLength,this.pos);return}return super.next()}nextCharCode(){return this._indentationAt(this.pos)!==0?(this.examinedLength=Math.max(this.examinedLength,this.pos),Bi):super.nextCharCode()}nextCodePoint(){return this._indentationAt(this.pos)!==0?(this.examinedLength=Math.max(this.examinedLength,this.pos),Bi):super.nextCodePoint()}}class zi extends z{constructor(e=!0){super(),this.isIndent=e}allowsSkippingPrecedingSpace(){return!0}eval(e){const{inputStream:r}=e,n=e.userData;e.doNotMemoize=!0;const s=r.pos,i=this.isIndent?1:-1;return(n[s]||0)*i>0?(e.userData=Object.create(n),e.userData[s]-=i,e.pushBinding(new Vt(0),s),!0):(e.processFailure(s,this),!1)}getArity(){return 1}_assertAllApplicationsAreValid(e,r){}_isNullable(e,r){return!1}assertChoicesHaveUniformArity(e){}assertIteratedExprsAreNotNullable(e){}introduceParams(e){return this}substituteParams(e){return this}toString(){return this.isIndent?"indent":"dedent"}toDisplayString(){return this.toString()}toFailure(e){const r=this.isIndent?Co:To;return new Ue(this,r,"description")}}const il=new X("indent"),al=new X("dedent"),ol=new jn(ri,"any",[il,al],[]),cl=new Yr().newGrammar("IndentationSensitive").withSuperGrammar(ri).define("indent",[],new zi(!0),Co,void 0,!0).define("dedent",[],new zi(!1),To,void 0,!0).extend("any",[],ol,"any character",void 0).build();Object.assign(cl,{_matchStateInitializer(t){t.userData=nl(t.input),t.inputStream=new sl(t)},supportsIncrementalParsing:!1});Le.initApplicationParser(ni,Oo);const ul=t=>!!t.constructor&&typeof t.constructor.isBuffer=="function"&&t.constructor.isBuffer(t);function ll(t,e,r){const n=ni.match(t,"Grammars");if(n.failed())throw gu(n);return Oo(n,e,void 0,r)}function dl(t,e,r){const n=hl(t,e,r),s=Object.keys(n);if(s.length===0)throw new Error("Missing grammar definition");if(s.length>1){const a=n[s[1]].source;throw new Error(Qs(a.sourceString,a.startIdx)+"Found more than one grammar definition -- use ohm.grammars() instead.")}return n[s[0]]}function hl(t,e,r){const n=Object.create({});if(typeof t!="string")if(ul(t))t=t.toString();else throw new TypeError("Expected string as first argument, got "+Zs(t));return ll(t,n,r),n}function fl(t,e){return dl(t,e)}const pl=`FirestoreRules {
226
226
  // === Top-level ===
227
227
  // Syntactic rules (capitalized) auto-skip spaces between terms.
228
228
  // Lexical rules (lowercase) do NOT skip spaces.
@@ -458,17 +458,17 @@ NOTE: as of Ohm v16, there is no default action for iteration nodes — see `,"
458
458
  = "//" (~"\\n" any)* &("\\n" | end) -- singleLine
459
459
  | "/*" (~"*/" any)* "*/" -- multiLine
460
460
  }
461
- `,No=pl(ml),Fo=No.createSemantics();Fo.addOperation("toAST",{RulesFile_versionFirst(t,e,r,n){return{imports:e.children.map(s=>s.toAST()),version:t.children.length>0?t.children[0].toAST():"1",functions:r.children.map(s=>s.toAST()),service:n.toAST()}},RulesFile_importsFirst(t,e,r,n){return{imports:t.children.map(s=>s.toAST()),version:e.toAST(),functions:r.children.map(s=>s.toAST()),service:n.toAST()}},ImportDecl(t,e,r,n,s,i,a,o){return{functions:r.asIteration().children.map(c=>c.sourceString),module:a.toAST().value}},RulesVersion(t,e,r,n){return r.toAST().value},ServiceBlock(t,e,r,n,s,i,a){return{name:e.sourceString,functions:[...n.children.map(o=>o.toAST()),...i.children.map(o=>o.toAST())],match:s.toAST()}},DocumentsMatch(t,e,r,n,s){const{lineNum:i,colNum:a}=t.source.getLineAndColumn();return{...n.toAST(),path:Hi(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:Hi(e.sourceString),functions:i,allows:a,children:o,loc:{line:c,col:u}}},AllowStatement(t,e,r,n,s,i){const{lineNum:a,colNum:o}=t.source.getLineAndColumn();return{_kind:"allow",operations:e.toAST(),condition:s.toAST(),loc:{line:a,col:o}}},OperationList(t,e,r){return[t.toAST(),...r.children.map(n=>n.toAST())]},Operation(t){return t.sourceString},FunctionDef(t,e,r,n,s,i,a,o,c){const{lets:u,expr:d}=o.toAST();return{_kind:"function",name:r.sourceString,parameters:s.toAST(),exported:t.sourceString.trim()==="export",lets:u,body:d}},ParameterList(t){return t.asIteration().children.map(e=>e.sourceString)},FunctionBody(t,e){return{lets:t.children.map(r=>r.toAST()),expr:e.toAST()}},LetBinding(t,e,r,n,s){return{name:e.sourceString,value:n.toAST()}},ReturnStatement(t,e,r){return e.toAST()},Expr(t){return t.toAST()},Ternary_ternary(t,e,r,n,s){return{type:"ternary",condition:t.toAST(),consequent:r.toAST(),alternate:s.toAST()}},LogicalOr_or(t,e,r){return{type:"binaryOp",op:"||",left:t.toAST(),right:r.toAST()}},LogicalAnd_and(t,e,r){return{type:"binaryOp",op:"&&",left:t.toAST(),right:r.toAST()}},InIsExpr_in(t,e,r){return{type:"inExpr",element:t.toAST(),collection:r.toAST()}},InIsExpr_is(t,e,r){return{type:"isExpr",value:t.toAST(),typeName:r.sourceString}},Equality_eq(t,e,r){return{type:"binaryOp",op:"==",left:t.toAST(),right:r.toAST()}},Equality_neq(t,e,r){return{type:"binaryOp",op:"!=",left:t.toAST(),right:r.toAST()}},Comparison_gte(t,e,r){return{type:"binaryOp",op:">=",left:t.toAST(),right:r.toAST()}},Comparison_lte(t,e,r){return{type:"binaryOp",op:"<=",left:t.toAST(),right:r.toAST()}},Comparison_gt(t,e,r){return{type:"binaryOp",op:">",left:t.toAST(),right:r.toAST()}},Comparison_lt(t,e,r){return{type:"binaryOp",op:"<",left:t.toAST(),right:r.toAST()}},Additive_add(t,e,r){return{type:"binaryOp",op:"+",left:t.toAST(),right:r.toAST()}},Additive_sub(t,e,r){return{type:"binaryOp",op:"-",left:t.toAST(),right:r.toAST()}},Multiplicative_mul(t,e,r){return{type:"binaryOp",op:"*",left:t.toAST(),right:r.toAST()}},Multiplicative_div(t,e,r){return{type:"binaryOp",op:"/",left:t.toAST(),right:r.toAST()}},Multiplicative_mod(t,e,r){return{type:"binaryOp",op:"%",left:t.toAST(),right:r.toAST()}},UnaryExpr_not(t,e){return{type:"unaryOp",op:"!",operand:e.toAST()}},UnaryExpr_neg(t,e){return{type:"unaryOp",op:"-",operand:e.toAST()}},PostfixExpr_methodCall(t,e,r,n,s,i){return{type:"methodCall",object:t.toAST(),method:r.sourceString,args:s.asIteration().children.map(a=>a.toAST())}},PostfixExpr_memberAccess(t,e,r){return{type:"memberAccess",object:t.toAST(),property:r.sourceString}},PostfixExpr_bracketAccess(t,e,r,n){return{type:"bracketAccess",object:t.toAST(),index:r.toAST()}},PostfixExpr_sliceAccess(t,e,r,n,s,i){return{type:"sliceAccess",object:t.toAST(),start:r.toAST(),end:s.toAST()}},Primary_paren(t,e,r){return e.toAST()},Primary_path(t){return t.toAST()},Primary_list(t){return t.toAST()},Primary_map(t){return t.toAST()},Primary_functionCall(t,e,r,n){return{type:"functionCall",name:t.sourceString,args:r.asIteration().children.map(s=>s.toAST())}},PathLiteral(t,e,r,n){const s=[e.toAST()];for(const i of n.children)s.push(i.toAST());return{type:"pathLiteral",raw:this.sourceString,segments:s}},PathLitSegment_interpolation(t,e,r){return e.toAST()},PathLitSegment_captureRef(t,e,r){return`{${e.sourceString}}`},PathLitSegment_parenLiteral(t,e,r){return`(${e.sourceString})`},PathLitSegment_literal(t){return t.sourceString},ListLiteral(t,e,r,n){return{type:"listLiteral",elements:e.asIteration().children.map(s=>s.toAST())}},MapLiteral(t,e,r,n){return{type:"mapLiteral",entries:e.asIteration().children.map(s=>s.toAST())}},MapEntry(t,e,r){return{key:t.toAST(),value:r.toAST()}},literal(t){return t.toAST()},number_float(t,e,r){return{type:"literal",value:parseFloat(this.sourceString),raw:this.sourceString}},number_int(t){return{type:"literal",value:parseInt(this.sourceString,10),raw:this.sourceString}},string_single(t,e,r){return{type:"literal",value:Wi(e.sourceString),raw:this.sourceString}},string_double(t,e,r){return{type:"literal",value:Wi(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 Wi(t){let e="";for(let r=0;r<t.length;r++){const n=t[r];if(n!=="\\"||r===t.length-1){e+=n;continue}switch(t[r+1]){case"\\":e+="\\",r++;break;case"'":e+="'",r++;break;case'"':e+='"',r++;break;case"n":e+=`
462
- `,r++;break;case"r":e+="\r",r++;break;case"t":e+=" ",r++;break;case"/":e+="/",r++;break;default:e+=n}}return e}function Hi(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 gl(t,e){const r=t.getRightmostFailurePosition?.()??0,n=t.getExpectedText?.()??"";let s=1,i=-1;for(let u=0;u<r&&u<e.length;u++)e.charCodeAt(u)===10&&(s++,i=u);const a=r-i;let o=e.indexOf(`
463
- `,r);o===-1&&(o=e.length);const c=e.slice(r,Math.min(o,r+40));return{line:s,column:a,offset:r,expected:n,actual:c,message:t.message??"Parse error"}}function ii(t){const e=en(t);return e.ok?e.ast:null}function en(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=No.match(e);if(!r.succeeded())return{ok:!1,error:gl(r,e)};const n=Fo(r).toAST(),s=t.length-t.trimStart().length;let i=0;for(let a=0;a<s;a++)t.charCodeAt(a)===10&&i++;return i>0&&yl(n,i),{ok:!0,ast:n}}function yl(t,e){const r=[t.service.match];for(;r.length>0;){const n=r.pop();n.loc&&(n.loc.line+=e);for(const s of n.allows)s.loc&&(s.loc.line+=e);for(const s of n.children)r.push(s)}}function bl(t){const e=`rules_version = '2';
461
+ `,Ro=fl(pl),No=Ro.createSemantics();No.addOperation("toAST",{RulesFile_versionFirst(t,e,r,n){return{imports:e.children.map(s=>s.toAST()),version:t.children.length>0?t.children[0].toAST():"1",functions:r.children.map(s=>s.toAST()),service:n.toAST()}},RulesFile_importsFirst(t,e,r,n){return{imports:t.children.map(s=>s.toAST()),version:e.toAST(),functions:r.children.map(s=>s.toAST()),service:n.toAST()}},ImportDecl(t,e,r,n,s,i,a,o){return{functions:r.asIteration().children.map(c=>c.sourceString),module:a.toAST().value}},RulesVersion(t,e,r,n){return r.toAST().value},ServiceBlock(t,e,r,n,s,i,a){return{name:e.sourceString,functions:[...n.children.map(o=>o.toAST()),...i.children.map(o=>o.toAST())],match:s.toAST()}},DocumentsMatch(t,e,r,n,s){const{lineNum:i,colNum:a}=t.source.getLineAndColumn();return{...n.toAST(),path:Wi(e.sourceString),loc:{line:i,col:a}}},MatchBody(t){const e=[],r=[],n=[];for(const s of t.children){const i=s.toAST();i._kind==="function"?e.push(i):i._kind==="allow"?r.push(i):i._kind==="match"&&n.push(i)}return{functions:e,allows:r,children:n}},MatchBodyItem(t){return t.toAST()},MatchBlock(t,e,r,n,s){const{functions:i,allows:a,children:o}=n.toAST(),{lineNum:c,colNum:u}=t.source.getLineAndColumn();return{_kind:"match",path:Wi(e.sourceString),functions:i,allows:a,children:o,loc:{line:c,col:u}}},AllowStatement(t,e,r,n,s,i){const{lineNum:a,colNum:o}=t.source.getLineAndColumn();return{_kind:"allow",operations:e.toAST(),condition:s.toAST(),loc:{line:a,col:o}}},OperationList(t,e,r){return[t.toAST(),...r.children.map(n=>n.toAST())]},Operation(t){return t.sourceString},FunctionDef(t,e,r,n,s,i,a,o,c){const{lets:u,expr:d}=o.toAST();return{_kind:"function",name:r.sourceString,parameters:s.toAST(),exported:t.sourceString.trim()==="export",lets:u,body:d}},ParameterList(t){return t.asIteration().children.map(e=>e.sourceString)},FunctionBody(t,e){return{lets:t.children.map(r=>r.toAST()),expr:e.toAST()}},LetBinding(t,e,r,n,s){return{name:e.sourceString,value:n.toAST()}},ReturnStatement(t,e,r){return e.toAST()},Expr(t){return t.toAST()},Ternary_ternary(t,e,r,n,s){return{type:"ternary",condition:t.toAST(),consequent:r.toAST(),alternate:s.toAST()}},LogicalOr_or(t,e,r){return{type:"binaryOp",op:"||",left:t.toAST(),right:r.toAST()}},LogicalAnd_and(t,e,r){return{type:"binaryOp",op:"&&",left:t.toAST(),right:r.toAST()}},InIsExpr_in(t,e,r){return{type:"inExpr",element:t.toAST(),collection:r.toAST()}},InIsExpr_is(t,e,r){return{type:"isExpr",value:t.toAST(),typeName:r.sourceString}},Equality_eq(t,e,r){return{type:"binaryOp",op:"==",left:t.toAST(),right:r.toAST()}},Equality_neq(t,e,r){return{type:"binaryOp",op:"!=",left:t.toAST(),right:r.toAST()}},Comparison_gte(t,e,r){return{type:"binaryOp",op:">=",left:t.toAST(),right:r.toAST()}},Comparison_lte(t,e,r){return{type:"binaryOp",op:"<=",left:t.toAST(),right:r.toAST()}},Comparison_gt(t,e,r){return{type:"binaryOp",op:">",left:t.toAST(),right:r.toAST()}},Comparison_lt(t,e,r){return{type:"binaryOp",op:"<",left:t.toAST(),right:r.toAST()}},Additive_add(t,e,r){return{type:"binaryOp",op:"+",left:t.toAST(),right:r.toAST()}},Additive_sub(t,e,r){return{type:"binaryOp",op:"-",left:t.toAST(),right:r.toAST()}},Multiplicative_mul(t,e,r){return{type:"binaryOp",op:"*",left:t.toAST(),right:r.toAST()}},Multiplicative_div(t,e,r){return{type:"binaryOp",op:"/",left:t.toAST(),right:r.toAST()}},Multiplicative_mod(t,e,r){return{type:"binaryOp",op:"%",left:t.toAST(),right:r.toAST()}},UnaryExpr_not(t,e){return{type:"unaryOp",op:"!",operand:e.toAST()}},UnaryExpr_neg(t,e){return{type:"unaryOp",op:"-",operand:e.toAST()}},PostfixExpr_methodCall(t,e,r,n,s,i){return{type:"methodCall",object:t.toAST(),method:r.sourceString,args:s.asIteration().children.map(a=>a.toAST())}},PostfixExpr_memberAccess(t,e,r){return{type:"memberAccess",object:t.toAST(),property:r.sourceString}},PostfixExpr_bracketAccess(t,e,r,n){return{type:"bracketAccess",object:t.toAST(),index:r.toAST()}},PostfixExpr_sliceAccess(t,e,r,n,s,i){return{type:"sliceAccess",object:t.toAST(),start:r.toAST(),end:s.toAST()}},Primary_paren(t,e,r){return e.toAST()},Primary_path(t){return t.toAST()},Primary_list(t){return t.toAST()},Primary_map(t){return t.toAST()},Primary_functionCall(t,e,r,n){return{type:"functionCall",name:t.sourceString,args:r.asIteration().children.map(s=>s.toAST())}},PathLiteral(t,e,r,n){const s=[e.toAST()];for(const i of n.children)s.push(i.toAST());return{type:"pathLiteral",raw:this.sourceString,segments:s}},PathLitSegment_interpolation(t,e,r){return e.toAST()},PathLitSegment_captureRef(t,e,r){return`{${e.sourceString}}`},PathLitSegment_parenLiteral(t,e,r){return`(${e.sourceString})`},PathLitSegment_literal(t){return t.sourceString},ListLiteral(t,e,r,n){return{type:"listLiteral",elements:e.asIteration().children.map(s=>s.toAST())}},MapLiteral(t,e,r,n){return{type:"mapLiteral",entries:e.asIteration().children.map(s=>s.toAST())}},MapEntry(t,e,r){return{key:t.toAST(),value:r.toAST()}},literal(t){return t.toAST()},number_float(t,e,r){return{type:"literal",value:parseFloat(this.sourceString),raw:this.sourceString}},number_int(t){return{type:"literal",value:parseInt(this.sourceString,10),raw:this.sourceString}},string_single(t,e,r){return{type:"literal",value:Vi(e.sourceString),raw:this.sourceString}},string_double(t,e,r){return{type:"literal",value:Vi(e.sourceString),raw:this.sourceString}},bool_true(t){return{type:"literal",value:!0,raw:"true"}},bool_false(t){return{type:"literal",value:!1,raw:"false"}},null(t){return{type:"literal",value:null,raw:"null"}},ident(t,e){return{type:"identifier",name:this.sourceString}},_nonterminal(...t){return t.length===1?t[0].toAST():t.map(e=>e.toAST())},_terminal(){return this.sourceString}});function Vi(t){let e="";for(let r=0;r<t.length;r++){const n=t[r];if(n!=="\\"||r===t.length-1){e+=n;continue}switch(t[r+1]){case"\\":e+="\\",r++;break;case"'":e+="'",r++;break;case'"':e+='"',r++;break;case"n":e+=`
462
+ `,r++;break;case"r":e+="\r",r++;break;case"t":e+=" ",r++;break;case"/":e+="/",r++;break;default:e+=n}}return e}function Wi(t){const e=[],r=t.split("/").filter(Boolean);for(const n of r)if(n.startsWith("{")&&n.endsWith("}")){const s=n.slice(1,-1);s.endsWith("=**")?e.push({type:"recursive",name:s.slice(0,-3)}):e.push({type:"wildcard",name:s})}else e.push({type:"literal",value:n});return{raw:t,segments:e}}function ml(t,e){const r=t.getRightmostFailurePosition?.()??0,n=t.getExpectedText?.()??"";let s=1,i=-1;for(let u=0;u<r&&u<e.length;u++)e.charCodeAt(u)===10&&(s++,i=u);const a=r-i;let o=e.indexOf(`
463
+ `,r);o===-1&&(o=e.length);const c=e.slice(r,Math.min(o,r+40));return{line:s,column:a,offset:r,expected:n,actual:c,message:t.message??"Parse error"}}function si(t){const e=Xr(t);return e.ok?e.ast:null}function Xr(t){const e=t.trim();if(!e)return{ok:!1,error:{line:1,column:1,offset:0,expected:"",actual:"",message:"Empty rules file"}};const r=Ro.match(e);if(!r.succeeded())return{ok:!1,error:ml(r,e)};const n=No(r).toAST(),s=t.length-t.trimStart().length;let i=0;for(let a=0;a<s;a++)t.charCodeAt(a)===10&&i++;return i>0&&gl(n,i),{ok:!0,ast:n}}function gl(t,e){const r=[t.service.match];for(;r.length>0;){const n=r.pop();n.loc&&(n.loc.line+=e);for(const s of n.allows)s.loc&&(s.loc.line+=e);for(const s of n.children)r.push(s)}}function yl(t){const e=`rules_version = '2';
464
464
  service cloud.firestore {
465
465
  match /databases/{db}/documents {
466
466
  ${t}
467
467
  }
468
- }`,r=ii(e);return r?r.service.match.functions:null}const Lo={"||":2,"&&":3,"==":5,"!=":5,">":6,"<":6,">=":6,"<=":6,"+":7,"-":7,"*":8,"/":8,"%":8};function vl(t){switch(t.type){case"ternary":return 1;case"binaryOp":return Lo[t.op]??0;case"inExpr":return 4;case"isExpr":return 4;case"unaryOp":return 9;default:return 100}}function wl(t){switch(t.type){case"literal":return typeof t.value=="string"&&t.raw.startsWith('"')&&t.raw.endsWith('"')?`'${t.raw.slice(1,-1)}'`:t.raw;case"identifier":return t.name;case"memberAccess":return`${ze(t.object,10)}.${t.property}`;case"methodCall":return`${ze(t.object,10)}.${t.method}(${t.args.map(e=>Ie(e)).join(", ")})`;case"bracketAccess":return`${ze(t.object,10)}[${Ie(t.index)}]`;case"sliceAccess":return`${ze(t.object,10)}[${Ie(t.start)}:${Ie(t.end)}]`;case"binaryOp":{const e=Lo[t.op]??0,r=ze(t.left,e),n=ze(t.right,e+1);return`${r} ${t.op} ${n}`}case"unaryOp":return`${t.op}${ze(t.operand,9)}`;case"ternary":return`${ze(t.condition,2)} ? ${Ie(t.consequent)} : ${Ie(t.alternate)}`;case"inExpr":return`${ze(t.element,5)} in ${ze(t.collection,5)}`;case"isExpr":return`${ze(t.value,5)} is ${t.typeName}`;case"listLiteral":return t.elements.length===0?"[]":`[${t.elements.map(e=>Ie(e)).join(", ")}]`;case"mapLiteral":return t.entries.length===0?"{}":`{${t.entries.map(e=>`${Ie(e.key)}: ${Ie(e.value)}`).join(", ")}}`;case"pathLiteral":return"/"+t.segments.map(e=>typeof e=="string"?e:`$(${Ie(e)})`).join("/");case"functionCall":return`${t.name}(${t.args.map(e=>Ie(e)).join(", ")})`}}function ze(t,e){const r=wl(t);return vl(t)<e?`(${r})`:r}function Ie(t){return ze(t,0)}function jo(t){return"/"+t.segments.map(e=>{switch(e.type){case"literal":return e.value;case"wildcard":return`{${e.name}}`;case"recursive":return`{${e.name}=**}`}}).join("/")}function _r(t){return" ".repeat(t)}function Wr(t,e){const r=_r(e),n=_r(e+2),s=t.parameters.join(", "),i=[],a=t.exported?"export ":"";i.push(`${r}${a}function ${t.name}(${s}) {`);for(const o of t.lets)i.push(`${n}let ${o.name} = ${Ie(o.value)};`);return i.push(`${n}return ${Ie(t.body)};`),i.push(`${r}}`),i.join(`
469
- `)}function Do(t,e){const r=_r(e),n=t.operations.join(", ");return`${r}allow ${n}: if ${Ie(t.condition)};`}function Mo(t,e=0){const r=_r(e),n=e+2,s=[];s.push(`${r}match ${jo(t.path)} {`);for(const i of t.functions)s.push(Wr(i,n));for(const i of t.allows)s.push(Do(i,n));for(const i of t.children)s.push(Mo(i,n));return s.push(`${r}}`),s.join(`
470
- `)}function tn(t){const e=[];for(const i of t.imports)e.push(`import { ${i.functions.join(", ")} } from '${i.module}';`);e.push(`rules_version = '${t.version}';`);for(const i of t.functions??[])e.push(Wr(i,0));e.push(`service ${t.service.name} {`);for(const i of t.service.functions??[])e.push(Wr(i,2));const r=t.service.match,n=_r(2),s=4;e.push(`${n}match ${jo(r.path)} {`);for(const i of r.functions)e.push(Wr(i,s));for(const i of r.allows)e.push(Do(i,s));for(const i of r.children)e.push(Mo(i,s));return e.push(`${n}}`),e.push("}"),e.push(""),e.join(`
471
- `)}const Hr=new Set(["get","exists","getAfter","debug"]);function rn(t,e){return t.type!=="binaryOp"||t.op!==e?0:1+rn(t.right,e)}function bs(t){let e={op:"",depth:0};function r(s){if(s.type==="binaryOp"){const i=rn(s,"&&"),a=rn(s,"||");i>e.depth&&(e={op:"&&",depth:i}),a>e.depth&&(e={op:"||",depth:a}),r(s.left),r(s.right)}else n(s)}function n(s){switch(s.type){case"unaryOp":r(s.operand);break;case"methodCall":r(s.object),s.args.forEach(r);break;case"memberAccess":r(s.object);break;case"bracketAccess":r(s.object),r(s.index);break;case"ternary":r(s.condition),r(s.consequent),r(s.alternate);break;case"inExpr":r(s.element),r(s.collection);break;case"isExpr":r(s.value);break;case"listLiteral":s.elements.forEach(r);break;case"mapLiteral":s.entries.forEach(i=>{r(i.key),r(i.value)});break;case"functionCall":s.args.forEach(r);break}}return r(t),e}function ae(t){let e=1;switch(t.type){case"binaryOp":e+=ae(t.left)+ae(t.right);break;case"unaryOp":e+=ae(t.operand);break;case"methodCall":e+=ae(t.object);for(const r of t.args)e+=ae(r);break;case"memberAccess":e+=ae(t.object);break;case"bracketAccess":e+=ae(t.object)+ae(t.index);break;case"ternary":e+=ae(t.condition)+ae(t.consequent)+ae(t.alternate);break;case"inExpr":e+=ae(t.element)+ae(t.collection);break;case"isExpr":e+=ae(t.value);break;case"listLiteral":for(const r of t.elements)e+=ae(r);break;case"mapLiteral":for(const r of t.entries)e+=ae(r.key)+ae(r.value);break;case"functionCall":for(const r of t.args)e+=ae(r);break;case"pathLiteral":for(const r of t.segments)typeof r!="string"&&(e+=ae(r));break}return e}function ie(t){switch(t.type){case"literal":return`L:${t.raw}`;case"identifier":return`I:${t.name}`;case"memberAccess":return`M:${ie(t.object)}.${t.property}`;case"methodCall":return`MC:${ie(t.object)}.${t.method}(${t.args.map(ie).join(",")})`;case"bracketAccess":return`B:${ie(t.object)}[${ie(t.index)}]`;case"binaryOp":return`BO:${ie(t.left)}${t.op}${ie(t.right)}`;case"unaryOp":return`UO:${t.op}${ie(t.operand)}`;case"ternary":return`T:${ie(t.condition)}?${ie(t.consequent)}:${ie(t.alternate)}`;case"inExpr":return`IN:${ie(t.element)}in${ie(t.collection)}`;case"isExpr":return`IS:${ie(t.value)}is${t.typeName}`;case"listLiteral":return`LL:[${t.elements.map(ie).join(",")}]`;case"mapLiteral":return`ML:{${t.entries.map(e=>ie(e.key)+":"+ie(e.value)).join(",")}}`;case"functionCall":return`FC:${t.name}(${t.args.map(ie).join(",")})`;case"pathLiteral":return`PL:${t.raw}`;case"sliceAccess":return`SL:${ie(t.object)}[${ie(t.start)}:${ie(t.end)}]`;default:{const e=t;throw new Error(`expressionFingerprint: unhandled type ${e.type}`)}}}function Po(t){return t.type==="binaryOp"&&t.op==="&&"?Po(t.left):t}function $o(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)&&!Hr.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 ai(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,ai(i,e,new Set(r)));return 1+s}function qo(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 Sl(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 Uo(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)?Uo(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 vs(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(vs(i.body,e,r)||i.lets.some(a=>vs(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 Bo(t){const e=[...t.functions];for(const r of t.children)e.push(...Bo(r));return e}function zo(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=zo(r);for(const s of n)s.matchFunctions=[...t.functions,...s.matchFunctions];e.push(...n)}return e}const Kn={where:"No equivalent in rules — restructure logic instead of filtering a list",filter:"No equivalent in rules — restructure logic instead of filtering a list",find:"No equivalent in rules",findIndex:"No equivalent in rules",map:"No equivalent in rules — lists are not transformable",reduce:"No equivalent in rules",forEach:"No equivalent in rules",every:'Use `list.hasAll([...])` for "all elements present"',some:'Use `list.hasAny([...])` for "any element present"',includes:"Use `x in list` instead of `list.includes(x)`",indexOf:"No equivalent in rules",push:"Lists are immutable in rules",pop:"Lists are immutable in rules",shift:"Lists are immutable in rules",unshift:"Lists are immutable in rules",splice:"Lists are immutable in rules",slice:"No equivalent in rules",sort:"Lists are immutable in rules",reverse:"Lists are immutable in rules",flat:"No equivalent in rules",flatMap:"No equivalent in rules",toLowerCase:"Use `.lower()` instead of `.toLowerCase()`",toUpperCase:"Use `.upper()` instead of `.toUpperCase()`",charAt:'No equivalent in rules — use `.split("")` and index',charCodeAt:"No equivalent in rules",substring:"No `.substring()` — use `.split()` and reassembly",substr:"No `.substr()` — use `.split()` and reassembly",padStart:"No equivalent in rules",padEnd:"No equivalent in rules",trimStart:"Use `.trim()` (trims both ends)",trimEnd:"Use `.trim()` (trims both ends)",toString:"Use the `string(x)` cast instead of `.toString()`"},it={Object:"No `Object` in rules — use `data.keys()` / `data.values()` directly",Array:"No `Array` in rules — test list type with `x is list`",JSON:"No `JSON` in rules — rules cannot parse or serialize JSON",Math:"No `Math` in rules — inline arithmetic or ternaries",Date:"No `Date` in rules — use `request.time` (a Timestamp)",String:"Use lowercase `string(x)` for casting",Number:"Use lowercase `int(x)` or `float(x)` for casting",Boolean:"Use lowercase `bool(x)` for casting",parseInt:"Use `int(x)` instead",parseFloat:"Use `float(x)` instead",isNaN:"No equivalent in rules",isFinite:"No equivalent in rules",Promise:"Rules are synchronous — no Promise support",undefined:"`undefined` does not exist in rules — use `null`"},_l=[{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"}],Al=new Set(["size","keys","values","lower","upper","trim","hasAll","hasAny","hasOnly","toSet","toUtf8"]),xl=[{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 Il(t){const e=[],r=t.replace(/\/\/[^\n]*/g,"").replace(/\/\*[\s\S]*?\*\//g,"");for(const n of xl)n.pattern.test(r)&&e.push({rule:"INVALID_OPERATOR",severity:"error",message:n.message});return e}function Vo(t,e){const r=t.path.raw;for(const n of t.functions){const s={matchPath:r,functionName:n.name};de(n.body,s,e);for(const i of n.lets)de(i.value,s,e)}for(let n=0;n<t.allows.length;n++)de(t.allows[n].condition,{matchPath:r,ruleIndex:n},e);for(const n of t.children)Vo(n,e)}function de(t,e,r){switch(r(t,e),t.type){case"binaryOp":de(t.left,e,r),de(t.right,e,r);break;case"unaryOp":de(t.operand,e,r);break;case"methodCall":de(t.object,e,r),t.args.forEach(n=>de(n,e,r));break;case"memberAccess":de(t.object,e,r);break;case"bracketAccess":de(t.object,e,r),de(t.index,e,r);break;case"ternary":de(t.condition,e,r),de(t.consequent,e,r),de(t.alternate,e,r);break;case"inExpr":de(t.element,e,r),de(t.collection,e,r);break;case"isExpr":de(t.value,e,r);break;case"listLiteral":t.elements.forEach(n=>de(n,e,r));break;case"mapLiteral":t.entries.forEach(n=>{de(n.key,e,r),de(n.value,e,r)});break;case"functionCall":t.args.forEach(n=>de(n,e,r));break}}function kl(t){const e=[],r=new Set;function n(s,i,a,o){const c=`${s}|${i}|${a.matchPath||""}|${a.functionName||""}|${a.ruleIndex??""}`;r.has(c)||(r.add(c),e.push(o))}return Vo(t.service.match,(s,i)=>{if(s.type==="methodCall"&&Kn[s.method]&&n("HALLUCINATED_METHOD",s.method,i,{rule:"HALLUCINATED_METHOD",severity:"error",message:`\`.${s.method}()\` does not exist in Firestore rules. ${Kn[s.method]}`,location:i,fix:Kn[s.method]}),s.type==="methodCall"&&s.object.type==="identifier"&&it[s.object.name]){const a=s.object.name;n("HALLUCINATED_GLOBAL",`${a}.${s.method}`,i,{rule:"HALLUCINATED_GLOBAL",severity:"error",message:`\`${a}.${s.method}()\` does not exist in Firestore rules. ${it[a]}`,location:i,fix:it[a]})}if(s.type==="functionCall"&&it[s.name]&&n("HALLUCINATED_GLOBAL",s.name,i,{rule:"HALLUCINATED_GLOBAL",severity:"error",message:`\`${s.name}()\` does not exist in Firestore rules. ${it[s.name]}`,location:i,fix:it[s.name]}),s.type==="identifier"&&it[s.name]&&n("HALLUCINATED_GLOBAL",`ref:${s.name}`,i,{rule:"HALLUCINATED_GLOBAL",severity:"error",message:`\`${s.name}\` is not a Firestore rules identifier. ${it[s.name]}`,location:i,fix:it[s.name]}),s.type==="memberAccess"&&s.object.type==="identifier"){const a=s.object.name,o=s.property,c=_l.find(u=>u.receiver===a&&u.property===o);c&&n("WRONG_CONTEXT_PATH",`${a}.${o}`,i,{rule:"WRONG_CONTEXT_PATH",severity:"error",message:`\`${a}.${o}\` is not a valid Firestore rules path. ${c.suggestion}`,location:i,fix:c.suggestion})}if(s.type==="memberAccess"&&s.property==="length"&&s.object.type==="methodCall"&&n("LENGTH_PROPERTY","",i,{rule:"LENGTH_PROPERTY",severity:"error",message:"`.length` is not a valid property in Firestore rules — use `.size()` (a method, with parentheses).",location:i,fix:"Replace `.length` with `.size()`."}),s.type==="pathLiteral")for(const a of s.segments){if(typeof a!="string")continue;const o=a.match(/^\{([A-Za-z_][A-Za-z0-9_]*)\}$/);if(!o)continue;const c=o[1];n("INVALID_PATH_INTERPOLATION",`${s.raw}|${c}`,i,{rule:"INVALID_PATH_INTERPOLATION",severity:"error",message:`\`{${c}}\` is not valid inside a path literal — Firestore rejects this at deploy. The \`{var}\` syntax is for match statement wildcards (e.g. \`match /users/{userId}\`); path interpolation in get()/exists()/getAfter()/existsAfter() requires \`$(var)\`. Replace \`{${c}}\` with \`$(${c})\` in path \`${s.raw}\`.`,location:i,fix:`Replace \`{${c}}\` with \`$(${c})\` inside the path argument.`})}s.type==="memberAccess"&&Al.has(s.property)&&(s.object.type==="identifier"&&(s.object.name==="request"||s.object.name==="resource")||s.object.type==="memberAccess"||s.object.type==="methodCall"||s.object.type==="bracketAccess")&&n("METHOD_MISSING_PARENS",s.property,i,{rule:"METHOD_MISSING_PARENS",severity:"warning",message:`\`.${s.property}\` looks like a built-in method called without parentheses. Use \`.${s.property}()\` if you meant to invoke it (otherwise this is a field access).`,location:i,fix:`Add parentheses: \`.${s.property}()\`.`})}),e}const ge={SOURCE_SIZE:256*1024,CHAIN_DEPTH_ERROR:95,CHAIN_DEPTH_WARN:85,CHAIN_DEPTH_LIMIT:98,LET_LIMIT:11,RUNTIME_BUDGET:{low:{calls:2,warn:100},mid:{calls:4,warn:60},high:{warn:40}},CALL_DEPTH_WARN:6,CALL_DEPTH_ERROR:10,GET_COUNT_WARN:5,GET_COUNT_ERROR:10};function El(t,e){t.length>ge.SOURCE_SIZE&&e.push({rule:"SOURCE_SIZE",severity:"error",message:`Rules source is ${(t.length/1024).toFixed(0)} KB, exceeding the 256 KB limit.`,fix:"Reduce string literals, remove comments, or split into smaller match blocks."})}function Ol(t,e){for(const r of t)r.lets.length>ge.LET_LIMIT&&e.push({rule:"LET_LIMIT",severity:"error",message:`Function '${r.name}' has ${r.lets.length} let bindings. Limit is ${ge.LET_LIMIT}.`,location:{functionName:r.name},fix:"Inline some let expressions into the return statement, or split the function."})}function Cl(t,e){for(const r of t){const n=bs(r.body);for(const s of r.lets){const i=bs(s.value);i.depth>n.depth&&(n.depth=i.depth,n.op=i.op)}n.depth>=ge.CHAIN_DEPTH_LIMIT?e.push({rule:"CHAIN_DEPTH",severity:"error",message:`Function '${r.name}' has a ${n.op} chain of depth ${n.depth}. Limit is ${ge.CHAIN_DEPTH_LIMIT}.`,location:{functionName:r.name},fix:"Split into nested groups: 'a && b && c && d' → '(a && b) && (c && d)' to halve chain depth."}):n.depth>=ge.CHAIN_DEPTH_ERROR?e.push({rule:"CHAIN_DEPTH",severity:"error",message:`Function '${r.name}' has a ${n.op} chain of depth ${n.depth}. Limit is ${ge.CHAIN_DEPTH_LIMIT}. Approaching failure.`,location:{functionName:r.name},fix:"Split the chain into nested groups to reduce depth."}):n.depth>=ge.CHAIN_DEPTH_WARN&&e.push({rule:"CHAIN_DEPTH",severity:"warning",message:`Function '${r.name}' has a ${n.op} chain of depth ${n.depth}. Limit is ${ge.CHAIN_DEPTH_LIMIT}.`,location:{functionName:r.name}})}}function Tl(t,e){const r=new Map;for(let n=0;n<t.length;n++){const s=t[n];if(!s.rule.operations.some(o=>o==="update"||o==="write"))continue;const i=ie(Po(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 Rl(t,e){let r=ae(t);const n=new Set;function s(i){if(i.type==="functionCall"&&e.has(i.name)&&!n.has(i.name)){n.add(i.name);const a=e.get(i.name);r+=ae(a.body);for(const o of a.lets)r+=ae(o.value);s(a.body);for(const o of a.lets)s(o.value)}switch(i.type){case"binaryOp":s(i.left),s(i.right);break;case"unaryOp":s(i.operand);break;case"methodCall":s(i.object),i.args.forEach(s);break;case"memberAccess":s(i.object);break;case"bracketAccess":s(i.object),s(i.index);break;case"ternary":s(i.condition),s(i.consequent),s(i.alternate);break;case"inExpr":s(i.element),s(i.collection);break;case"isExpr":s(i.value);break;case"listLiteral":i.elements.forEach(s);break;case"mapLiteral":i.entries.forEach(a=>{s(a.key),s(a.value)});break;case"functionCall":i.args.forEach(s);break}}return s(t),{totalExprs:r,callCount:n.size}}function Nl(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}=Rl(t[s].rule.condition,n),o=rn(t[s].rule.condition,"||"),c=o>5?.3:o>2?.5:1,u=Math.round(i*c),d=a<=ge.RUNTIME_BUDGET.low.calls?ge.RUNTIME_BUDGET.low:a<=ge.RUNTIME_BUDGET.mid.calls?ge.RUNTIME_BUDGET.mid:ge.RUNTIME_BUDGET.high;u>=d.warn&&r.push({rule:"EXPRESSION_BUDGET",severity:"warning",message:`Rule #${s} has ~${i} expression nodes across ${a} function calls. Runtime budget is non-deterministic; actual evaluation depends on short-circuit behavior.`,location:{ruleIndex:s},fix:"If this rule fails at runtime (403), reduce function calls or expression count."})}}function Fl(t,e,r){const n=$o(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=ai(c.name,n);u>a&&(a=u)}switch(c.type){case"binaryOp":o(c.left),o(c.right);break;case"unaryOp":o(c.operand);break;case"methodCall":o(c.object),c.args.forEach(o);break;case"memberAccess":o(c.object);break;case"bracketAccess":o(c.object),o(c.index);break;case"ternary":o(c.condition),o(c.consequent),o(c.alternate);break;case"inExpr":o(c.element),o(c.collection);break;case"functionCall":c.args.forEach(o);break}};o(t[i].rule.condition),a>=ge.CALL_DEPTH_ERROR?r.push({rule:"CALL_DEPTH",severity:"error",message:`Rule #${i} has a function call chain of depth ${a}. May exceed call budget.`,location:{ruleIndex:i},fix:"Inline intermediate functions to reduce call depth."}):a>=ge.CALL_DEPTH_WARN&&r.push({rule:"CALL_DEPTH",severity:"warning",message:`Rule #${i} has a function call chain of depth ${a}.`,location:{ruleIndex:i}})}}function Ll(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=qo(t[s].rule.condition,n);i>=ge.GET_COUNT_ERROR?r.push({rule:"GET_COUNT",severity:"error",message:`Rule #${s} may invoke ${i} get()/exists() calls. Limit is ${ge.GET_COUNT_ERROR}.`,location:{ruleIndex:s},fix:"Cache get() results via a config() wrapper function. Same-path calls are cached by Firestore."}):i>=ge.GET_COUNT_WARN&&r.push({rule:"GET_COUNT",severity:"warning",message:`Rule #${s} invokes ${i} get()/exists() calls. Limit is ${ge.GET_COUNT_ERROR}.`,location:{ruleIndex:s}})}}function jl(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=Sl(t[i].rule.condition,s);for(const[o,c]of a)c>=2&&Uo(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 Dl(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++)vs(t[o].rule.condition,s)&&i.add(o);if(i.size===0)return;function a(o,c){const u=o.split("/").filter(Boolean),d=c.split("/").filter(Boolean);if(u.length!==d.length)return!1;for(let l=0;l<u.length;l++){const f=u[l];if(!(f.startsWith("{")&&f.endsWith("}"))&&f!==d[l])return!1}return!0}for(const o of r)if(!o.requestTime)for(const c of i)a(t[c].path,o.path)&&n.push({rule:"REQUEST_TIME_NOT_PINNED",severity:"warning",message:`Test case "${o.description}" targets rule #${c} (path '${t[c].path}') which reads request.time, but does not set requestTime. Result is non-deterministic across runs.`,location:{ruleIndex:c,matchPath:t[c].path,testCaseDescription:o.description},fix:"Set requestTime on this TestCase to an ISO-8601 timestamp so the rule evaluates deterministically."})}function gr(t){if(t.type==="literal"&&typeof t.value=="boolean")return t.value;if(t.type==="binaryOp"){const e=gr(t.left),r=gr(t.right);if(t.op==="&&")return e===!1||r===!1?!1:e===!0&&r===!0?!0:null;if(t.op==="||")return e===!0||r===!0?!0:e===!1&&r===!1?!1:null}if(t.type==="unaryOp"&&t.op==="!"){const e=gr(t.operand);return e===null?null:!e}return null}const Ml=new Set(["write","create","update","delete"]);function Pl(t,e){for(let r=0;r<t.length;r++){const n=t[r];if(gr(n.rule.condition)!==!0||!n.rule.operations.some(a=>Ml.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 Wo(t,e){if(t.path.segments.some(n=>n.type==="recursive"))for(let n=0;n<t.allows.length;n++)gr(t.allows[n].condition)===!0&&e.push({rule:"RECURSIVE_WILDCARD_OPEN",severity:"error",message:`Recursive wildcard match (${t.path.raw}) with an always-true predicate exposes every document under this prefix. This is the Firebase open-rules anti-pattern — never ship it.`,location:{ruleIndex:n,matchPath:t.path.raw},fix:"Either narrow the match path to specific collections, or replace `if true` with a real predicate (auth identity, ownership, role)."});for(const n of t.children)Wo(n,e)}function $l(t){return t.type==="literal"?t.value??"":t.type==="wildcard"?"{*}":t.type==="recursive"?"{**}":""}function ql(t){return t.map($l).join("/")}function ws(t,e){const r=ql(t.path.segments),n=e?`${e}/${r}`:r,s=[{block:t,normalizedPath:n}];for(const i of t.children)s.push(...ws(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 nn(t){return t.type==="binaryOp"&&t.op==="&&"?[...nn(t.left),...nn(t.right)]:[t]}function Ul(t,e,r){const n=ws(t,""),s=ws(e,""),i=new Map;for(const{block:a,normalizedPath:o}of n)i.has(o)||i.set(o,a);for(const{block:a,normalizedPath:o}of s){const c=i.get(o);if(!c){a.allows.length>0&&r.push({rule:"RULES_WEAKENED",severity:"warning",message:`Match block removed: ${o}`,location:{matchPath:o}});continue}for(const u of a.allows){const d=[...u.operations].sort().join(","),l=c.allows.find(S=>[...S.operations].sort().join(",")===d),f=u.operations.join(", ");if(!l){r.push({rule:"RULES_WEAKENED",severity:"warning",message:`Allow rule removed: ${o} allow ${f}`,location:{matchPath:o}});continue}const y=nn(u.condition).map(ne),b=new Set(nn(l.condition).map(ne));for(const S of y)b.has(S)||r.push({rule:"RULES_WEAKENED",severity:"warning",message:`Predicate removed from ${o} allow ${f}: ${S}`,location:{matchPath:o}})}}}function Ss(t,e={}){const r=[];r.push(...Il(t)),El(t,r);const n=en(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=Bo(s.service.match),a=zo(s.service.match);if(Cl(i,r),Ol(i,r),Tl(a,r),Nl(a,i,r),Fl(a,i,r),Ll(a,i,r),jl(a,i,r),r.push(...kl(s)),Pl(a,r),Wo(s.service.match,r),e.testCases&&e.testCases.length>0&&Dl(a,i,e.testCases,r),e.previousSource){const b=en(e.previousSource);b.ok&&Ul(s.service.match,b.ast.service.match,r)}let o={depth:0,op:""},c={count:0,fn:""};for(const b of i){const S=bs(b.body);S.depth>o.depth&&(o={depth:S.depth,op:S.op}),b.lets.length>c.count&&(c={count:b.lets.length,fn:b.name})}const u=$o(i);let d=0;for(const b of i){const S=ai(b.name,u);S>d&&(d=S)}const l=new Map;for(const b of i)l.set(b.name,b);let f=0,y=0;for(const b of a){const S=qo(b.rule.condition,l);S>y&&(y=S)}return{warnings:r,metrics:{sourceSize:t.length,functionCount:i.length,allowRuleCount:a.length,maxChainDepth:o.depth,maxChainOp:o.op,maxLetBindings:c.count,maxLetBindingsFunction:c.fn,maxCallDepth:d,maxEstimatedExpressions:f,getCallCount:y}}}const ue=Symbol.for("pyric.RulesValue.NO_OP");class te{field(e){return null}callMethod(e,r){return ue}binaryOp(e,r){return ue}}function ye(t,e){if(Object.is(t,e))return!0;if(t instanceof te)return t.equals(e);if(e instanceof te)return e.equals(t);if(t instanceof fe||e instanceof fe)return t instanceof fe&&t.equals(e);if(Array.isArray(t)||Array.isArray(e))return!Array.isArray(t)||!Array.isArray(e)||t.length!==e.length?!1:t.every((s,i)=>ye(s,e[i]));if(!Gi(t)||!Gi(e))return!1;const r=Object.keys(t),n=Object.keys(e);return r.length!==n.length?!1:r.every(s=>s in e&&ye(t[s],e[s]))}function Gi(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}class fe{items;constructor(e){this.items=[];for(const r of e)this.items.some(n=>ye(n,r))||this.items.push(r)}hasOnly(e){const r=e instanceof fe?e.toArray():e;return this.items.every(n=>r.some(s=>ye(n,s)))}equals(e){return!(e instanceof fe)||e.items.length!==this.items.length?!1:this.items.every(r=>e.items.some(n=>ye(r,n)))}hasAll(e){const r=e instanceof fe?e.toArray():e;for(const n of r)if(!this.items.some(s=>ye(s,n)))return!1;return!0}hasAny(e){const r=e instanceof fe?e.toArray():e;for(const n of r)if(this.items.some(s=>ye(s,n)))return!0;return!1}size(){return this.items.length}toArray(){return[...this.items]}difference(e){const r=e.toArray(),n=[];for(const s of this.items)r.some(i=>ye(s,i))||n.push(s);return new fe(n)}union(e){const r=e.toArray();return new fe([...this.items,...r])}intersection(e){const r=e.toArray(),n=[];for(const s of this.items)r.some(i=>ye(s,i))&&n.push(s);return new fe(n)}}class yr{before;after;constructor(e,r){this.before=e,this.after=r}addedKeys(){const e=[];for(const r of Object.keys(this.after))r in this.before||e.push(r);return new fe(e)}removedKeys(){const e=[];for(const r of Object.keys(this.before))r in this.after||e.push(r);return new fe(e)}changedKeys(){const e=[];for(const r of Object.keys(this.after))r in this.before&&!ye(this.before[r],this.after[r])&&e.push(r);return new fe(e)}affectedKeys(){const e=[],r=new Set([...Object.keys(this.before),...Object.keys(this.after)]);for(const n of r)(!(n in this.before)||!(n in this.after)||!ye(this.before[n],this.after[n]))&&e.push(n);return new fe(e)}unchangedKeys(){const e=[];for(const r of Object.keys(this.before))r in this.after&&ye(this.before[r],this.after[r])&&e.push(r);return new fe(e)}}const Bl=/^\{([A-Za-z_][A-Za-z0-9_]*)\}$/;class Xe extends te{typeName="path";segments;bindings;constructor(e,r={}){super(),this.segments=e,this.bindings=r}static fromString(e){const r=e.startsWith("/")?e.slice(1):e;return r.length===0?new Xe([]):new Xe(r.split("/"))}bind(e){const r=[],n={...this.bindings};for(const s of this.segments){const i=s.match(Bl);if(!i){r.push(s);continue}const a=i[1];if(a in e){const o=e[a];if(o==null)throw new TypeError(`Path.bind(): binding '${a}' must not be null`);const c=String(o);r.push(c),n[a]=c}else r.push(s)}return new Xe(r,n)}valueOf(){return NaN}toString(){return"/"+this.segments.join("/")}toJSON(){return{__type:"path",segments:[...this.segments]}}equals(e){if(!(e instanceof Xe)||this.segments.length!==e.segments.length)return!1;for(let r=0;r<this.segments.length;r++)if(this.segments[r]!==e.segments[r])return!1;return!0}field(e){if(/^\d+$/.test(e)){const r=Number(e);return r<0||r>=this.segments.length?null:this.segments[r]}return e in this.bindings?this.bindings[e]:null}callMethod(e,r){switch(e){case"bind":{const n=r[0];if(n==null||typeof n!="object"||Array.isArray(n)||n instanceof te)throw new TypeError(`Path.bind() requires a Map argument, got ${n===null?"null":typeof n}`);return this.bind(n)}default:return ue}}}class oe extends te{typeName="float";value;constructor(e){super(),this.value=e}valueOf(){return this.value}toString(){return Number.isInteger(this.value)?`${this.value}.0`:String(this.value)}toJSON(){return{__type:"float",value:this.value}}equals(e){return e instanceof oe?this.value===e.value:typeof e=="number"?this.value===e:!1}binaryOp(e,r){const n=r instanceof oe?r.value:typeof r=="number"?r:void 0;if(n===void 0)return ue;const s=this.value;switch(e){case"+":return new oe(s+n);case"-":return new oe(s-n);case"*":return new oe(s*n);case"/":return new oe(s/n);case"%":return new oe(s%n);case"<":return s<n;case"<=":return s<=n;case">":return s>n;case">=":return s>=n;default:return ue}}}class G extends Error{expr;constructor(e,r){super(e),this.expr=r,this.name="EvalError"}}class Je extends G{constructor(e,r){super(e,r),this.name="UnsupportedError"}}class zl{entries=[];parents=[];frames=[];capture(e,r){const n=this.entries.length,s=this.parents.length>0?this.parents[this.parents.length-1]:null,i={source:Ie(e),kind:e.type,parent:s};this.stampFrame(i),this.entries.push(i),this.parents.push(n);try{const a=r();return this.entries[n].value=a,a}catch(a){throw this.entries[n].error=a instanceof Error?a.message:String(a),a}finally{this.parents.pop()}}skip(e){const r=this.parents.length>0?this.parents[this.parents.length-1]:null,n={source:Ie(e),kind:e.type,parent:r,skipped:!0};this.stampFrame(n),this.entries.push(n)}enterFrame(e){this.frames.push(e)}exitFrame(){this.frames.pop()}markEntryAsLetBinding(e,r){e<0||e>=this.entries.length||(this.entries[e].letBinding={name:r})}stampFrame(e){this.frames.length!==0&&(e.inlinedFrom={name:this.frames[this.frames.length-1]})}}function Vl(t,e,r,n){const i=f=>f*Math.PI/180,a=i(t),o=i(r),c=i(r-t),u=i(n-e),d=Math.sin(c/2)**2+Math.cos(a)*Math.cos(o)*Math.sin(u/2)**2;return 6371e3*(2*Math.atan2(Math.sqrt(d),Math.sqrt(1-d)))}class rt extends te{typeName="latlng";lat;lng;constructor(e,r){super(),this.lat=e,this.lng=r}valueOf(){return NaN}toString(){return`${this.lat},${this.lng}`}toJSON(){return{__type:"latlng",lat:this.lat,lng:this.lng}}equals(e){return e instanceof rt&&this.lat===e.lat&&this.lng===e.lng}callMethod(e,r){switch(e){case"latitude":return this.lat;case"longitude":return this.lng;case"distance":{const n=r[0];if(!(n instanceof rt))throw new TypeError(`latlng.distance() requires a LatLng argument, got ${typeof n}`);return Vl(this.lat,this.lng,n.lat,n.lng)}default:return ue}}}const Yt=1e9,Ki={w:10080*60,d:1440*60,h:3600,m:60,s:1};function Wl(t,e){let r=t+Math.trunc(e/Yt),n=e%Yt;return r>0&&n<0?(r-=1,n+=Yt):r<0&&n>0&&(r+=1,n-=Yt),{seconds:r,nanos:n}}class we extends te{typeName="duration";seconds;nanos;constructor(e,r){super();const n=Wl(e,r);this.seconds=n.seconds,this.nanos=n.nanos}static fromValue(e,r){if(r in Ki)return new we(e*Ki[r],0);if(r==="ms"){const n=Math.trunc(e/1e3),s=e-n*1e3;return new we(n,s*1e6)}if(r==="ns"){const n=Math.trunc(e/Yt),s=e-n*Yt;return new we(n,s)}throw new Error(`Unknown duration unit '${r}' (expected one of: w, d, h, m, s, ms, ns)`)}static fromTime(e,r,n,s){return new we(e*3600+r*60+n,s)}static abs(e){return new we(Math.abs(e.seconds),Math.abs(e.nanos))}valueOf(){return this.seconds*1e3+Math.round(this.nanos/1e6)}toString(){const e=this.seconds<0||this.nanos<0,r=Math.abs(this.seconds),n=Math.abs(this.nanos);return`${e?"-":""}${r}.${n.toString().padStart(9,"0")}s`}toJSON(){return{__type:"duration",seconds:this.seconds,nanos:this.nanos}}equals(e){return e instanceof we&&this.seconds===e.seconds&&this.nanos===e.nanos}callMethod(e,r){switch(e){case"seconds":return this.seconds;case"nanos":return this.nanos;default:return ue}}binaryOp(e,r){if(!(r instanceof we))return ue;switch(e){case"+":return new we(this.seconds+r.seconds,this.nanos+r.nanos);case"-":return new we(this.seconds-r.seconds,this.nanos-r.nanos);case"<":return this.compareTo(r)<0;case"<=":return this.compareTo(r)<=0;case">":return this.compareTo(r)>0;case">=":return this.compareTo(r)>=0;default:return ue}}compareTo(e){return this.seconds!==e.seconds?this.seconds-e.seconds:this.nanos-e.nanos}}const Zi=1e9,Hl=864e5,Zn=86400;function Gl(t,e){const r=Math.floor(e/Zi);return{seconds:t+r,nanos:e-r*Zi}}let xe=class ot extends te{typeName="timestamp";seconds;nanos;constructor(e,r){super();const n=Gl(e,r);this.seconds=n.seconds,this.nanos=n.nanos}static fromMillis(e){const r=Math.floor(e/1e3),n=e-r*1e3;return new ot(r,n*1e6)}static fromYMD(e,r,n){return ot.fromMillis(Date.UTC(e,r-1,n))}static fromIsoString(e){return ot.fromMillis(Date.parse(e))}toMillis(){return this.seconds*1e3+Math.floor(this.nanos/1e6)}toDate(){return new Date(this.toMillis())}valueOf(){return this.toMillis()}toString(){const e=new Date(this.toMillis()).toISOString(),r=this.nanos.toString().padStart(9,"0");return e.replace(/\.\d{3}Z$/,`.${r}Z`)}toJSON(){return{__type:"timestamp",seconds:this.seconds,nanos:this.nanos}}equals(e){return e instanceof ot&&this.seconds===e.seconds&&this.nanos===e.nanos}callMethod(e,r){switch(e){case"seconds":return this.seconds;case"nanos":return this.nanos;case"toMillis":return this.toMillis();case"year":return this.asDate().getUTCFullYear();case"month":return this.asDate().getUTCMonth()+1;case"day":return this.asDate().getUTCDate();case"hours":return this.asDate().getUTCHours();case"minutes":return this.asDate().getUTCMinutes();case"dayOfWeek":{const n=this.asDate().getUTCDay();return n===0?7:n}case"dayOfYear":{const n=this.asDate(),s=Date.UTC(n.getUTCFullYear(),0,1);return Math.floor((this.toMillis()-s)/Hl)+1}case"date":return ot.fromYMD(this.asDate().getUTCFullYear(),this.asDate().getUTCMonth()+1,this.asDate().getUTCDate());case"time":{const n=(this.seconds%Zn+Zn)%Zn,s=Math.floor(n/3600),i=Math.floor(n%3600/60),a=n%60;return we.fromTime(s,i,a,this.nanos)}default:return ue}}asDate(){return new Date(this.toMillis())}binaryOp(e,r){if(r instanceof ot)switch(e){case"-":return new we(this.seconds-r.seconds,this.nanos-r.nanos);case"<":return this.compareTo(r)<0;case"<=":return this.compareTo(r)<=0;case">":return this.compareTo(r)>0;case">=":return this.compareTo(r)>=0;default:return ue}if(r instanceof we)switch(e){case"+":return new ot(this.seconds+r.seconds,this.nanos+r.nanos);case"-":return new ot(this.seconds-r.seconds,this.nanos-r.nanos);default:return ue}return ue}compareTo(e){return this.seconds!==e.seconds?this.seconds-e.seconds:this.nanos-e.nanos}};const Ji="0123456789ABCDEF";function Kl(t){let e="";for(let r=0;r<t.length;r++){const n=t[r];e+=Ji[n>>>4]+Ji[n&15]}return e}function Zl(t){let e="";for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_")}function Jl(t,e){const r=Math.min(t.length,e.length);for(let n=0;n<r;n++)if(t[n]!==e[n])return t[n]<e[n]?-1:1;return t.length===e.length?0:t.length<e.length?-1:1}let Be=class fr extends te{typeName="bytes";data;constructor(e){super(),this.data=e}static fromUtf8(e){return new fr(new TextEncoder().encode(e))}static fromHex(e){if(e.length%2!==0)throw new Error(`Invalid hex string length: ${e.length}`);const r=new Uint8Array(e.length/2);for(let n=0;n<r.length;n++)r[n]=parseInt(e.substr(n*2,2),16);return new fr(r)}size(){return this.data.length}toBase64(){return Zl(this.data)}toHexString(){return Kl(this.data)}valueOf(){return this.data.length}toString(){return this.toBase64()}toJSON(){return{__type:"bytes",base64:this.toBase64()}}equals(e){if(!(e instanceof fr)||this.data.length!==e.data.length)return!1;for(let r=0;r<this.data.length;r++)if(this.data[r]!==e.data[r])return!1;return!0}callMethod(e,r){switch(e){case"size":return this.size();case"toBase64":return this.toBase64();case"toHexString":return this.toHexString()}return ue}binaryOp(e,r){if(!(r instanceof fr))return ue;const n=Jl(this.data,r.data);switch(e){case"<":return n<0;case"<=":return n<=0;case">":return n>0;case">=":return n>=0}return ue}};function br(t){return t.replace(/\$\(database\)/g,"(default)").replace(/^\/databases\/\(default\)\/documents\//,"")}function _s(t,e){const r=t.split("/").filter(Boolean);return{data:e,id:r.at(-1)??"",__name__:new Xe(["databases","(default)","documents",...r])}}function Qi(t,e){const r=br(t);let n=e.mockDocuments.get(r);if(!n&&e.getDoc){const s=e.getDoc(r);s&&(e.mockDocuments.set(r,s),n=s)}if(n)return e.identitylessFunctionMocks?.has(r)?{data:n}:_s(r,n);throw new G(`get() of non-existent document '${r}' (guard with exists() first)`)}function Yi(t,e){const r=br(t);if(e.mockDocuments.has(r))return!0;if(e.getDoc){const n=e.getDoc(r);if(n)return e.mockDocuments.set(r,n),!0}return!1}var Jn={exports:{}};const Ql={},Yl=Object.freeze(Object.defineProperty({__proto__:null,default:Ql},Symbol.toStringTag,{value:"Module"})),sn=mu(Yl);/**
468
+ }`,r=si(e);return r?r.service.match.functions:null}const Fo={"||":2,"&&":3,"==":5,"!=":5,">":6,"<":6,">=":6,"<=":6,"+":7,"-":7,"*":8,"/":8,"%":8};function bl(t){switch(t.type){case"ternary":return 1;case"binaryOp":return Fo[t.op]??0;case"inExpr":return 4;case"isExpr":return 4;case"unaryOp":return 9;default:return 100}}function vl(t){switch(t.type){case"literal":return typeof t.value=="string"&&t.raw.startsWith('"')&&t.raw.endsWith('"')?`'${t.raw.slice(1,-1)}'`:t.raw;case"identifier":return t.name;case"memberAccess":return`${ze(t.object,10)}.${t.property}`;case"methodCall":return`${ze(t.object,10)}.${t.method}(${t.args.map(e=>Ie(e)).join(", ")})`;case"bracketAccess":return`${ze(t.object,10)}[${Ie(t.index)}]`;case"sliceAccess":return`${ze(t.object,10)}[${Ie(t.start)}:${Ie(t.end)}]`;case"binaryOp":{const e=Fo[t.op]??0,r=ze(t.left,e),n=ze(t.right,e+1);return`${r} ${t.op} ${n}`}case"unaryOp":return`${t.op}${ze(t.operand,9)}`;case"ternary":return`${ze(t.condition,2)} ? ${Ie(t.consequent)} : ${Ie(t.alternate)}`;case"inExpr":return`${ze(t.element,5)} in ${ze(t.collection,5)}`;case"isExpr":return`${ze(t.value,5)} is ${t.typeName}`;case"listLiteral":return t.elements.length===0?"[]":`[${t.elements.map(e=>Ie(e)).join(", ")}]`;case"mapLiteral":return t.entries.length===0?"{}":`{${t.entries.map(e=>`${Ie(e.key)}: ${Ie(e.value)}`).join(", ")}}`;case"pathLiteral":return"/"+t.segments.map(e=>typeof e=="string"?e:`$(${Ie(e)})`).join("/");case"functionCall":return`${t.name}(${t.args.map(e=>Ie(e)).join(", ")})`}}function ze(t,e){const r=vl(t);return bl(t)<e?`(${r})`:r}function Ie(t){return ze(t,0)}function Lo(t){return"/"+t.segments.map(e=>{switch(e.type){case"literal":return e.value;case"wildcard":return`{${e.name}}`;case"recursive":return`{${e.name}=**}`}}).join("/")}function _r(t){return" ".repeat(t)}function Vr(t,e){const r=_r(e),n=_r(e+2),s=t.parameters.join(", "),i=[],a=t.exported?"export ":"";i.push(`${r}${a}function ${t.name}(${s}) {`);for(const o of t.lets)i.push(`${n}let ${o.name} = ${Ie(o.value)};`);return i.push(`${n}return ${Ie(t.body)};`),i.push(`${r}}`),i.join(`
469
+ `)}function jo(t,e){const r=_r(e),n=t.operations.join(", ");return`${r}allow ${n}: if ${Ie(t.condition)};`}function Do(t,e=0){const r=_r(e),n=e+2,s=[];s.push(`${r}match ${Lo(t.path)} {`);for(const i of t.functions)s.push(Vr(i,n));for(const i of t.allows)s.push(jo(i,n));for(const i of t.children)s.push(Do(i,n));return s.push(`${r}}`),s.join(`
470
+ `)}function en(t){const e=[];for(const i of t.imports)e.push(`import { ${i.functions.join(", ")} } from '${i.module}';`);e.push(`rules_version = '${t.version}';`);for(const i of t.functions??[])e.push(Vr(i,0));e.push(`service ${t.service.name} {`);for(const i of t.service.functions??[])e.push(Vr(i,2));const r=t.service.match,n=_r(2),s=4;e.push(`${n}match ${Lo(r.path)} {`);for(const i of r.functions)e.push(Vr(i,s));for(const i of r.allows)e.push(jo(i,s));for(const i of r.children)e.push(Do(i,s));return e.push(`${n}}`),e.push("}"),e.push(""),e.join(`
471
+ `)}const Wr=new Set(["get","exists","getAfter","debug"]);function tn(t,e){return t.type!=="binaryOp"||t.op!==e?0:1+tn(t.right,e)}function ys(t){let e={op:"",depth:0};function r(s){if(s.type==="binaryOp"){const i=tn(s,"&&"),a=tn(s,"||");i>e.depth&&(e={op:"&&",depth:i}),a>e.depth&&(e={op:"||",depth:a}),r(s.left),r(s.right)}else n(s)}function n(s){switch(s.type){case"unaryOp":r(s.operand);break;case"methodCall":r(s.object),s.args.forEach(r);break;case"memberAccess":r(s.object);break;case"bracketAccess":r(s.object),r(s.index);break;case"ternary":r(s.condition),r(s.consequent),r(s.alternate);break;case"inExpr":r(s.element),r(s.collection);break;case"isExpr":r(s.value);break;case"listLiteral":s.elements.forEach(r);break;case"mapLiteral":s.entries.forEach(i=>{r(i.key),r(i.value)});break;case"functionCall":s.args.forEach(r);break}}return r(t),e}function ae(t){let e=1;switch(t.type){case"binaryOp":e+=ae(t.left)+ae(t.right);break;case"unaryOp":e+=ae(t.operand);break;case"methodCall":e+=ae(t.object);for(const r of t.args)e+=ae(r);break;case"memberAccess":e+=ae(t.object);break;case"bracketAccess":e+=ae(t.object)+ae(t.index);break;case"ternary":e+=ae(t.condition)+ae(t.consequent)+ae(t.alternate);break;case"inExpr":e+=ae(t.element)+ae(t.collection);break;case"isExpr":e+=ae(t.value);break;case"listLiteral":for(const r of t.elements)e+=ae(r);break;case"mapLiteral":for(const r of t.entries)e+=ae(r.key)+ae(r.value);break;case"functionCall":for(const r of t.args)e+=ae(r);break;case"pathLiteral":for(const r of t.segments)typeof r!="string"&&(e+=ae(r));break}return e}function ie(t){switch(t.type){case"literal":return`L:${t.raw}`;case"identifier":return`I:${t.name}`;case"memberAccess":return`M:${ie(t.object)}.${t.property}`;case"methodCall":return`MC:${ie(t.object)}.${t.method}(${t.args.map(ie).join(",")})`;case"bracketAccess":return`B:${ie(t.object)}[${ie(t.index)}]`;case"binaryOp":return`BO:${ie(t.left)}${t.op}${ie(t.right)}`;case"unaryOp":return`UO:${t.op}${ie(t.operand)}`;case"ternary":return`T:${ie(t.condition)}?${ie(t.consequent)}:${ie(t.alternate)}`;case"inExpr":return`IN:${ie(t.element)}in${ie(t.collection)}`;case"isExpr":return`IS:${ie(t.value)}is${t.typeName}`;case"listLiteral":return`LL:[${t.elements.map(ie).join(",")}]`;case"mapLiteral":return`ML:{${t.entries.map(e=>ie(e.key)+":"+ie(e.value)).join(",")}}`;case"functionCall":return`FC:${t.name}(${t.args.map(ie).join(",")})`;case"pathLiteral":return`PL:${t.raw}`;case"sliceAccess":return`SL:${ie(t.object)}[${ie(t.start)}:${ie(t.end)}]`;default:{const e=t;throw new Error(`expressionFingerprint: unhandled type ${e.type}`)}}}function Mo(t){return t.type==="binaryOp"&&t.op==="&&"?Mo(t.left):t}function Po(t){const e=new Map,r=new Set(t.map(s=>s.name));function n(s){const i=[],a=o=>{switch(o.type){case"functionCall":r.has(o.name)&&!Wr.has(o.name)&&i.push(o.name),o.args.forEach(a);break;case"binaryOp":a(o.left),a(o.right);break;case"unaryOp":a(o.operand);break;case"methodCall":a(o.object),o.args.forEach(a);break;case"memberAccess":a(o.object);break;case"bracketAccess":a(o.object),a(o.index);break;case"ternary":a(o.condition),a(o.consequent),a(o.alternate);break;case"inExpr":a(o.element),a(o.collection);break;case"isExpr":a(o.value);break;case"listLiteral":o.elements.forEach(a);break;case"mapLiteral":o.entries.forEach(c=>{a(c.key),a(c.value)});break}};return a(s),[...new Set(i)]}for(const s of t){const i=[];i.push(...n(s.body));for(const a of s.lets)i.push(...n(a.value));e.set(s.name,[...new Set(i)])}return e}function ii(t,e,r=new Set){if(r.has(t))return 0;r.add(t);const n=e.get(t)||[];if(n.length===0)return 1;let s=0;for(const i of n)s=Math.max(s,ii(i,e,new Set(r)));return 1+s}function $o(t,e,r=new Set){let n=0;const s=i=>{switch(i.type){case"functionCall":if(i.name==="get"||i.name==="exists")n++;else if(e.has(i.name)&&!r.has(i.name)){r.add(i.name);const a=e.get(i.name);s(a.body);for(const o of a.lets)s(o.value)}i.args.forEach(s);break;case"binaryOp":s(i.left),s(i.right);break;case"unaryOp":s(i.operand);break;case"methodCall":s(i.object),i.args.forEach(s);break;case"memberAccess":s(i.object);break;case"bracketAccess":s(i.object),s(i.index);break;case"ternary":s(i.condition),s(i.consequent),s(i.alternate);break;case"inExpr":s(i.element),s(i.collection);break;case"isExpr":s(i.value);break;case"listLiteral":i.elements.forEach(s);break;case"mapLiteral":i.entries.forEach(a=>{s(a.key),s(a.value)});break}};return s(t),n}function wl(t,e){const r=new Map,n=s=>{switch(s.type){case"functionCall":e.has(s.name)&&r.set(s.name,(r.get(s.name)??0)+1),s.args.forEach(n);break;case"binaryOp":n(s.left),n(s.right);break;case"unaryOp":n(s.operand);break;case"methodCall":n(s.object),s.args.forEach(n);break;case"memberAccess":n(s.object);break;case"bracketAccess":n(s.object),n(s.index);break;case"ternary":n(s.condition),n(s.consequent),n(s.alternate);break;case"inExpr":n(s.element),n(s.collection);break;case"isExpr":n(s.value);break;case"listLiteral":s.elements.forEach(n);break;case"mapLiteral":s.entries.forEach(i=>{n(i.key),n(i.value)});break}};return n(t),r}function qo(t,e,r=new Set){if(r.has(t))return!1;r.add(t);const n=e.get(t);if(!n)return!1;const s=i=>{switch(i.type){case"functionCall":return i.name==="get"||i.name==="exists"?!0:e.has(i.name)?qo(i.name,e,r):i.args.some(s);case"binaryOp":return s(i.left)||s(i.right);case"unaryOp":return s(i.operand);case"methodCall":return s(i.object)||i.args.some(s);case"memberAccess":return s(i.object);case"bracketAccess":return s(i.object)||s(i.index);case"ternary":return s(i.condition)||s(i.consequent)||s(i.alternate);case"inExpr":return s(i.element)||s(i.collection);case"isExpr":return s(i.value);case"listLiteral":return i.elements.some(s);case"mapLiteral":return i.entries.some(a=>s(a.key)||s(a.value));default:return!1}};return s(n.body)||n.lets.some(i=>s(i.value))}function bs(t,e,r=new Set){const n=s=>{switch(s.type){case"memberAccess":return s.property==="time"&&s.object.type==="identifier"&&s.object.name==="request"?!0:n(s.object);case"bracketAccess":return s.object.type==="identifier"&&s.object.name==="request"&&s.index.type==="literal"&&s.index.value==="time"?!0:n(s.object)||n(s.index);case"functionCall":if(e.has(s.name)&&!r.has(s.name)){r.add(s.name);const i=e.get(s.name);if(bs(i.body,e,r)||i.lets.some(a=>bs(a.value,e,r)))return!0}return s.args.some(n);case"binaryOp":return n(s.left)||n(s.right);case"unaryOp":return n(s.operand);case"methodCall":return n(s.object)||s.args.some(n);case"ternary":return n(s.condition)||n(s.consequent)||n(s.alternate);case"inExpr":return n(s.element)||n(s.collection);case"isExpr":return n(s.value);case"listLiteral":return s.elements.some(n);case"mapLiteral":return s.entries.some(i=>n(i.key)||n(i.value));default:return!1}};return n(t)}function Uo(t){const e=[...t.functions];for(const r of t.children)e.push(...Uo(r));return e}function Bo(t){const e=[];for(const r of t.allows)e.push({rule:r,path:t.path.raw,matchFunctions:t.functions});for(const r of t.children){const n=Bo(r);for(const s of n)s.matchFunctions=[...t.functions,...s.matchFunctions];e.push(...n)}return e}const Gn={where:"No equivalent in rules — restructure logic instead of filtering a list",filter:"No equivalent in rules — restructure logic instead of filtering a list",find:"No equivalent in rules",findIndex:"No equivalent in rules",map:"No equivalent in rules — lists are not transformable",reduce:"No equivalent in rules",forEach:"No equivalent in rules",every:'Use `list.hasAll([...])` for "all elements present"',some:'Use `list.hasAny([...])` for "any element present"',includes:"Use `x in list` instead of `list.includes(x)`",indexOf:"No equivalent in rules",push:"Lists are immutable in rules",pop:"Lists are immutable in rules",shift:"Lists are immutable in rules",unshift:"Lists are immutable in rules",splice:"Lists are immutable in rules",slice:"No equivalent in rules",sort:"Lists are immutable in rules",reverse:"Lists are immutable in rules",flat:"No equivalent in rules",flatMap:"No equivalent in rules",toLowerCase:"Use `.lower()` instead of `.toLowerCase()`",toUpperCase:"Use `.upper()` instead of `.toUpperCase()`",charAt:'No equivalent in rules — use `.split("")` and index',charCodeAt:"No equivalent in rules",substring:"No `.substring()` — use `.split()` and reassembly",substr:"No `.substr()` — use `.split()` and reassembly",padStart:"No equivalent in rules",padEnd:"No equivalent in rules",trimStart:"Use `.trim()` (trims both ends)",trimEnd:"Use `.trim()` (trims both ends)",toString:"Use the `string(x)` cast instead of `.toString()`"},it={Object:"No `Object` in rules — use `data.keys()` / `data.values()` directly",Array:"No `Array` in rules — test list type with `x is list`",JSON:"No `JSON` in rules — rules cannot parse or serialize JSON",Math:"No `Math` in rules — inline arithmetic or ternaries",Date:"No `Date` in rules — use `request.time` (a Timestamp)",String:"Use lowercase `string(x)` for casting",Number:"Use lowercase `int(x)` or `float(x)` for casting",Boolean:"Use lowercase `bool(x)` for casting",parseInt:"Use `int(x)` instead",parseFloat:"Use `float(x)` instead",isNaN:"No equivalent in rules",isFinite:"No equivalent in rules",Promise:"Rules are synchronous — no Promise support",undefined:"`undefined` does not exist in rules — use `null`"},Sl=[{receiver:"request",property:"data",suggestion:"Use `request.resource.data` (the incoming write payload)"},{receiver:"request",property:"uid",suggestion:"Use `request.auth.uid`"},{receiver:"request",property:"token",suggestion:"Use `request.auth.token`"},{receiver:"request",property:"user",suggestion:"Use `request.auth` (or `request.auth.uid` for the user id)"},{receiver:"resource",property:"path",suggestion:"`resource.path` is not available — bind path captures in the match pattern"},{receiver:"resource",property:"exists",suggestion:"Use `resource != null` (or `exists()` for cross-document checks)"},{receiver:"resource",property:"id",suggestion:"`resource.id` is not available — capture the document id with `/{docId}` in the match path"}],_l=new Set(["size","keys","values","lower","upper","trim","hasAll","hasAny","hasOnly","toSet","toUtf8"]),Al=[{pattern:/===/,message:"Strict equality `===` is not supported in Firestore rules — use `==`."},{pattern:/!==/,message:"Strict inequality `!==` is not supported in Firestore rules — use `!=`."},{pattern:/\?\./,message:"Optional chaining `?.` is not supported — use `'field' in obj && obj.field`."},{pattern:/\?\?/,message:"Nullish coalescing `??` is not supported — use a ternary `cond ? a : b`."},{pattern:/=>/,message:"Arrow functions `=>` are not supported — define functions with `function name() { return ...; }`."},{pattern:/`[^`]*`/,message:"Backtick strings are not supported — use single or double quoted strings with `+` for concatenation."}];function xl(t){const e=[],r=t.replace(/\/\/[^\n]*/g,"").replace(/\/\*[\s\S]*?\*\//g,"");for(const n of Al)n.pattern.test(r)&&e.push({rule:"INVALID_OPERATOR",severity:"error",message:n.message});return e}function zo(t,e){const r=t.path.raw;for(const n of t.functions){const s={matchPath:r,functionName:n.name};de(n.body,s,e);for(const i of n.lets)de(i.value,s,e)}for(let n=0;n<t.allows.length;n++)de(t.allows[n].condition,{matchPath:r,ruleIndex:n},e);for(const n of t.children)zo(n,e)}function de(t,e,r){switch(r(t,e),t.type){case"binaryOp":de(t.left,e,r),de(t.right,e,r);break;case"unaryOp":de(t.operand,e,r);break;case"methodCall":de(t.object,e,r),t.args.forEach(n=>de(n,e,r));break;case"memberAccess":de(t.object,e,r);break;case"bracketAccess":de(t.object,e,r),de(t.index,e,r);break;case"ternary":de(t.condition,e,r),de(t.consequent,e,r),de(t.alternate,e,r);break;case"inExpr":de(t.element,e,r),de(t.collection,e,r);break;case"isExpr":de(t.value,e,r);break;case"listLiteral":t.elements.forEach(n=>de(n,e,r));break;case"mapLiteral":t.entries.forEach(n=>{de(n.key,e,r),de(n.value,e,r)});break;case"functionCall":t.args.forEach(n=>de(n,e,r));break}}function Il(t){const e=[],r=new Set;function n(s,i,a,o){const c=`${s}|${i}|${a.matchPath||""}|${a.functionName||""}|${a.ruleIndex??""}`;r.has(c)||(r.add(c),e.push(o))}return zo(t.service.match,(s,i)=>{if(s.type==="methodCall"&&Gn[s.method]&&n("HALLUCINATED_METHOD",s.method,i,{rule:"HALLUCINATED_METHOD",severity:"error",message:`\`.${s.method}()\` does not exist in Firestore rules. ${Gn[s.method]}`,location:i,fix:Gn[s.method]}),s.type==="methodCall"&&s.object.type==="identifier"&&it[s.object.name]){const a=s.object.name;n("HALLUCINATED_GLOBAL",`${a}.${s.method}`,i,{rule:"HALLUCINATED_GLOBAL",severity:"error",message:`\`${a}.${s.method}()\` does not exist in Firestore rules. ${it[a]}`,location:i,fix:it[a]})}if(s.type==="functionCall"&&it[s.name]&&n("HALLUCINATED_GLOBAL",s.name,i,{rule:"HALLUCINATED_GLOBAL",severity:"error",message:`\`${s.name}()\` does not exist in Firestore rules. ${it[s.name]}`,location:i,fix:it[s.name]}),s.type==="identifier"&&it[s.name]&&n("HALLUCINATED_GLOBAL",`ref:${s.name}`,i,{rule:"HALLUCINATED_GLOBAL",severity:"error",message:`\`${s.name}\` is not a Firestore rules identifier. ${it[s.name]}`,location:i,fix:it[s.name]}),s.type==="memberAccess"&&s.object.type==="identifier"){const a=s.object.name,o=s.property,c=Sl.find(u=>u.receiver===a&&u.property===o);c&&n("WRONG_CONTEXT_PATH",`${a}.${o}`,i,{rule:"WRONG_CONTEXT_PATH",severity:"error",message:`\`${a}.${o}\` is not a valid Firestore rules path. ${c.suggestion}`,location:i,fix:c.suggestion})}if(s.type==="memberAccess"&&s.property==="length"&&s.object.type==="methodCall"&&n("LENGTH_PROPERTY","",i,{rule:"LENGTH_PROPERTY",severity:"error",message:"`.length` is not a valid property in Firestore rules — use `.size()` (a method, with parentheses).",location:i,fix:"Replace `.length` with `.size()`."}),s.type==="pathLiteral")for(const a of s.segments){if(typeof a!="string")continue;const o=a.match(/^\{([A-Za-z_][A-Za-z0-9_]*)\}$/);if(!o)continue;const c=o[1];n("INVALID_PATH_INTERPOLATION",`${s.raw}|${c}`,i,{rule:"INVALID_PATH_INTERPOLATION",severity:"error",message:`\`{${c}}\` is not valid inside a path literal — Firestore rejects this at deploy. The \`{var}\` syntax is for match statement wildcards (e.g. \`match /users/{userId}\`); path interpolation in get()/exists()/getAfter()/existsAfter() requires \`$(var)\`. Replace \`{${c}}\` with \`$(${c})\` in path \`${s.raw}\`.`,location:i,fix:`Replace \`{${c}}\` with \`$(${c})\` inside the path argument.`})}s.type==="memberAccess"&&_l.has(s.property)&&(s.object.type==="identifier"&&(s.object.name==="request"||s.object.name==="resource")||s.object.type==="memberAccess"||s.object.type==="methodCall"||s.object.type==="bracketAccess")&&n("METHOD_MISSING_PARENS",s.property,i,{rule:"METHOD_MISSING_PARENS",severity:"warning",message:`\`.${s.property}\` looks like a built-in method called without parentheses. Use \`.${s.property}()\` if you meant to invoke it (otherwise this is a field access).`,location:i,fix:`Add parentheses: \`.${s.property}()\`.`})}),e}const ge={SOURCE_SIZE:256*1024,CHAIN_DEPTH_ERROR:95,CHAIN_DEPTH_WARN:85,CHAIN_DEPTH_LIMIT:98,LET_LIMIT:11,RUNTIME_BUDGET:{low:{calls:2,warn:100},mid:{calls:4,warn:60},high:{warn:40}},CALL_DEPTH_WARN:6,CALL_DEPTH_ERROR:10,GET_COUNT_WARN:5,GET_COUNT_ERROR:10};function kl(t,e){t.length>ge.SOURCE_SIZE&&e.push({rule:"SOURCE_SIZE",severity:"error",message:`Rules source is ${(t.length/1024).toFixed(0)} KB, exceeding the 256 KB limit.`,fix:"Reduce string literals, remove comments, or split into smaller match blocks."})}function El(t,e){for(const r of t)r.lets.length>ge.LET_LIMIT&&e.push({rule:"LET_LIMIT",severity:"error",message:`Function '${r.name}' has ${r.lets.length} let bindings. Limit is ${ge.LET_LIMIT}.`,location:{functionName:r.name},fix:"Inline some let expressions into the return statement, or split the function."})}function Ol(t,e){for(const r of t){const n=ys(r.body);for(const s of r.lets){const i=ys(s.value);i.depth>n.depth&&(n.depth=i.depth,n.op=i.op)}n.depth>=ge.CHAIN_DEPTH_LIMIT?e.push({rule:"CHAIN_DEPTH",severity:"error",message:`Function '${r.name}' has a ${n.op} chain of depth ${n.depth}. Limit is ${ge.CHAIN_DEPTH_LIMIT}.`,location:{functionName:r.name},fix:"Split into nested groups: 'a && b && c && d' → '(a && b) && (c && d)' to halve chain depth."}):n.depth>=ge.CHAIN_DEPTH_ERROR?e.push({rule:"CHAIN_DEPTH",severity:"error",message:`Function '${r.name}' has a ${n.op} chain of depth ${n.depth}. Limit is ${ge.CHAIN_DEPTH_LIMIT}. Approaching failure.`,location:{functionName:r.name},fix:"Split the chain into nested groups to reduce depth."}):n.depth>=ge.CHAIN_DEPTH_WARN&&e.push({rule:"CHAIN_DEPTH",severity:"warning",message:`Function '${r.name}' has a ${n.op} chain of depth ${n.depth}. Limit is ${ge.CHAIN_DEPTH_LIMIT}.`,location:{functionName:r.name}})}}function Cl(t,e){const r=new Map;for(let n=0;n<t.length;n++){const s=t[n];if(!s.rule.operations.some(o=>o==="update"||o==="write"))continue;const i=ie(Mo(s.rule.condition)),a=s.path;r.has(a)||r.set(a,[]),r.get(a).push({index:n,gate:i,ops:s.rule.operations})}for(const[n,s]of r){const i=new Map;for(const a of s)i.has(a.gate)||i.set(a.gate,[]),i.get(a.gate).push(a.index);for(const[a,o]of i)o.length>=2&&e.push({rule:"SHARED_GATE",severity:"warning",message:`${o.length} allow rules in '${n}' share the same gate expression. This may cause cross-rule budget exhaustion. Rules: ${o.join(", ")}.`,location:{matchPath:n},fix:"Assign unique moveType or discriminator values so each rule has a unique first expression."})}}function Tl(t,e){let r=ae(t);const n=new Set;function s(i){if(i.type==="functionCall"&&e.has(i.name)&&!n.has(i.name)){n.add(i.name);const a=e.get(i.name);r+=ae(a.body);for(const o of a.lets)r+=ae(o.value);s(a.body);for(const o of a.lets)s(o.value)}switch(i.type){case"binaryOp":s(i.left),s(i.right);break;case"unaryOp":s(i.operand);break;case"methodCall":s(i.object),i.args.forEach(s);break;case"memberAccess":s(i.object);break;case"bracketAccess":s(i.object),s(i.index);break;case"ternary":s(i.condition),s(i.consequent),s(i.alternate);break;case"inExpr":s(i.element),s(i.collection);break;case"isExpr":s(i.value);break;case"listLiteral":i.elements.forEach(s);break;case"mapLiteral":i.entries.forEach(a=>{s(a.key),s(a.value)});break;case"functionCall":i.args.forEach(s);break}}return s(t),{totalExprs:r,callCount:n.size}}function Rl(t,e,r){const n=new Map;for(const s of e)n.set(s.name,s);for(let s=0;s<t.length;s++){const{totalExprs:i,callCount:a}=Tl(t[s].rule.condition,n),o=tn(t[s].rule.condition,"||"),c=o>5?.3:o>2?.5:1,u=Math.round(i*c),d=a<=ge.RUNTIME_BUDGET.low.calls?ge.RUNTIME_BUDGET.low:a<=ge.RUNTIME_BUDGET.mid.calls?ge.RUNTIME_BUDGET.mid:ge.RUNTIME_BUDGET.high;u>=d.warn&&r.push({rule:"EXPRESSION_BUDGET",severity:"warning",message:`Rule #${s} has ~${i} expression nodes across ${a} function calls. Runtime budget is non-deterministic; actual evaluation depends on short-circuit behavior.`,location:{ruleIndex:s},fix:"If this rule fails at runtime (403), reduce function calls or expression count."})}}function Nl(t,e,r){const n=Po(e),s=new Map;for(const i of e)s.set(i.name,i);for(let i=0;i<t.length;i++){let a=0;const o=c=>{if(c.type==="functionCall"&&s.has(c.name)){const u=ii(c.name,n);u>a&&(a=u)}switch(c.type){case"binaryOp":o(c.left),o(c.right);break;case"unaryOp":o(c.operand);break;case"methodCall":o(c.object),c.args.forEach(o);break;case"memberAccess":o(c.object);break;case"bracketAccess":o(c.object),o(c.index);break;case"ternary":o(c.condition),o(c.consequent),o(c.alternate);break;case"inExpr":o(c.element),o(c.collection);break;case"functionCall":c.args.forEach(o);break}};o(t[i].rule.condition),a>=ge.CALL_DEPTH_ERROR?r.push({rule:"CALL_DEPTH",severity:"error",message:`Rule #${i} has a function call chain of depth ${a}. May exceed call budget.`,location:{ruleIndex:i},fix:"Inline intermediate functions to reduce call depth."}):a>=ge.CALL_DEPTH_WARN&&r.push({rule:"CALL_DEPTH",severity:"warning",message:`Rule #${i} has a function call chain of depth ${a}.`,location:{ruleIndex:i}})}}function Fl(t,e,r){const n=new Map;for(const s of e)n.set(s.name,s);for(let s=0;s<t.length;s++){const i=$o(t[s].rule.condition,n);i>=ge.GET_COUNT_ERROR?r.push({rule:"GET_COUNT",severity:"error",message:`Rule #${s} may invoke ${i} get()/exists() calls. Limit is ${ge.GET_COUNT_ERROR}.`,location:{ruleIndex:s},fix:"Cache get() results via a config() wrapper function. Same-path calls are cached by Firestore."}):i>=ge.GET_COUNT_WARN&&r.push({rule:"GET_COUNT",severity:"warning",message:`Rule #${s} invokes ${i} get()/exists() calls. Limit is ${ge.GET_COUNT_ERROR}.`,location:{ruleIndex:s}})}}function Ll(t,e,r){const n=new Map;for(const i of e)n.set(i.name,i);const s=new Set(e.map(i=>i.name));for(let i=0;i<t.length;i++){const a=wl(t[i].rule.condition,s);for(const[o,c]of a)c>=2&&qo(o,n)&&r.push({rule:"GET_DUPLICATION",severity:"warning",message:`Function '${o}' (contains get/exists) is called ${c} times in rule #${i}. Cache the result with a let binding in a wrapper function to reduce get() calls from ${c} to 1.`,location:{ruleIndex:i},fix:`Create a wrapper: function verifyAll(ret) { let c = ${o}(); return verify1(ret, c) && verify2(ret, c) && ...; }`})}}function jl(t,e,r,n){const s=new Map;for(const o of e)s.set(o.name,o);const i=new Set;for(let o=0;o<t.length;o++)bs(t[o].rule.condition,s)&&i.add(o);if(i.size===0)return;function a(o,c){const u=o.split("/").filter(Boolean),d=c.split("/").filter(Boolean);if(u.length!==d.length)return!1;for(let l=0;l<u.length;l++){const f=u[l];if(!(f.startsWith("{")&&f.endsWith("}"))&&f!==d[l])return!1}return!0}for(const o of r)if(!o.requestTime)for(const c of i)a(t[c].path,o.path)&&n.push({rule:"REQUEST_TIME_NOT_PINNED",severity:"warning",message:`Test case "${o.description}" targets rule #${c} (path '${t[c].path}') which reads request.time, but does not set requestTime. Result is non-deterministic across runs.`,location:{ruleIndex:c,matchPath:t[c].path,testCaseDescription:o.description},fix:"Set requestTime on this TestCase to an ISO-8601 timestamp so the rule evaluates deterministically."})}function gr(t){if(t.type==="literal"&&typeof t.value=="boolean")return t.value;if(t.type==="binaryOp"){const e=gr(t.left),r=gr(t.right);if(t.op==="&&")return e===!1||r===!1?!1:e===!0&&r===!0?!0:null;if(t.op==="||")return e===!0||r===!0?!0:e===!1&&r===!1?!1:null}if(t.type==="unaryOp"&&t.op==="!"){const e=gr(t.operand);return e===null?null:!e}return null}const Dl=new Set(["write","create","update","delete"]);function Ml(t,e){for(let r=0;r<t.length;r++){const n=t[r];if(gr(n.rule.condition)!==!0||!n.rule.operations.some(a=>Dl.has(a)))continue;const i=n.rule.operations.join(", ");e.push({rule:"PERMISSIVE_RULE",severity:"warning",message:`allow ${i} at ${n.path} resolves to a constant true predicate — this disables write security for the matched paths. If you reached for \`if true\` to escape a denial you don't understand, narrow the predicate to the specific request shape instead (auth identity, affected fields via diff, status transitions).`,location:{ruleIndex:r,matchPath:n.path},fix:"Replace the always-true predicate with a request-shape check (e.g. request.auth != null && request.resource.data.ownerId == request.auth.uid)."})}}function Vo(t,e){if(t.path.segments.some(n=>n.type==="recursive"))for(let n=0;n<t.allows.length;n++)gr(t.allows[n].condition)===!0&&e.push({rule:"RECURSIVE_WILDCARD_OPEN",severity:"error",message:`Recursive wildcard match (${t.path.raw}) with an always-true predicate exposes every document under this prefix. This is the Firebase open-rules anti-pattern — never ship it.`,location:{ruleIndex:n,matchPath:t.path.raw},fix:"Either narrow the match path to specific collections, or replace `if true` with a real predicate (auth identity, ownership, role)."});for(const n of t.children)Vo(n,e)}function Pl(t){return t.type==="literal"?t.value??"":t.type==="wildcard"?"{*}":t.type==="recursive"?"{**}":""}function $l(t){return t.map(Pl).join("/")}function vs(t,e){const r=$l(t.path.segments),n=e?`${e}/${r}`:r,s=[{block:t,normalizedPath:n}];for(const i of t.children)s.push(...vs(i,n));return s}function ne(t){switch(t.type){case"literal":return t.raw;case"identifier":return t.name;case"memberAccess":return`${ne(t.object)}.${t.property}`;case"methodCall":return`${ne(t.object)}.${t.method}(${t.args.map(ne).join(",")})`;case"bracketAccess":return`${ne(t.object)}[${ne(t.index)}]`;case"sliceAccess":return`${ne(t.object)}[${ne(t.start)}:${ne(t.end)}]`;case"binaryOp":return`(${ne(t.left)}${t.op}${ne(t.right)})`;case"unaryOp":return`(${t.op}${ne(t.operand)})`;case"ternary":return`(${ne(t.condition)}?${ne(t.consequent)}:${ne(t.alternate)})`;case"inExpr":return`(${ne(t.element)} in ${ne(t.collection)})`;case"isExpr":return`(${ne(t.value)} is ${t.typeName})`;case"listLiteral":return`[${t.elements.map(ne).join(",")}]`;case"mapLiteral":return`{${t.entries.map(e=>`${ne(e.key)}:${ne(e.value)}`).join(",")}}`;case"pathLiteral":return t.raw;case"functionCall":return`${t.name}(${t.args.map(ne).join(",")})`}}function rn(t){return t.type==="binaryOp"&&t.op==="&&"?[...rn(t.left),...rn(t.right)]:[t]}function ql(t,e,r){const n=vs(t,""),s=vs(e,""),i=new Map;for(const{block:a,normalizedPath:o}of n)i.has(o)||i.set(o,a);for(const{block:a,normalizedPath:o}of s){const c=i.get(o);if(!c){a.allows.length>0&&r.push({rule:"RULES_WEAKENED",severity:"warning",message:`Match block removed: ${o}`,location:{matchPath:o}});continue}for(const u of a.allows){const d=[...u.operations].sort().join(","),l=c.allows.find(S=>[...S.operations].sort().join(",")===d),f=u.operations.join(", ");if(!l){r.push({rule:"RULES_WEAKENED",severity:"warning",message:`Allow rule removed: ${o} allow ${f}`,location:{matchPath:o}});continue}const y=rn(u.condition).map(ne),b=new Set(rn(l.condition).map(ne));for(const S of y)b.has(S)||r.push({rule:"RULES_WEAKENED",severity:"warning",message:`Predicate removed from ${o} allow ${f}: ${S}`,location:{matchPath:o}})}}}function ws(t,e={}){const r=[];r.push(...xl(t)),kl(t,r);const n=Xr(t);if(!n.ok)return{warnings:r,metrics:{sourceSize:t.length,functionCount:0,allowRuleCount:0,maxChainDepth:0,maxChainOp:"",maxLetBindings:0,maxLetBindingsFunction:"",maxCallDepth:0,maxEstimatedExpressions:0,getCallCount:0},parseError:n.error};const s=n.ast,i=Uo(s.service.match),a=Bo(s.service.match);if(Ol(i,r),El(i,r),Cl(a,r),Rl(a,i,r),Nl(a,i,r),Fl(a,i,r),Ll(a,i,r),r.push(...Il(s)),Ml(a,r),Vo(s.service.match,r),e.testCases&&e.testCases.length>0&&jl(a,i,e.testCases,r),e.previousSource){const b=Xr(e.previousSource);b.ok&&ql(s.service.match,b.ast.service.match,r)}let o={depth:0,op:""},c={count:0,fn:""};for(const b of i){const S=ys(b.body);S.depth>o.depth&&(o={depth:S.depth,op:S.op}),b.lets.length>c.count&&(c={count:b.lets.length,fn:b.name})}const u=Po(i);let d=0;for(const b of i){const S=ii(b.name,u);S>d&&(d=S)}const l=new Map;for(const b of i)l.set(b.name,b);let f=0,y=0;for(const b of a){const S=$o(b.rule.condition,l);S>y&&(y=S)}return{warnings:r,metrics:{sourceSize:t.length,functionCount:i.length,allowRuleCount:a.length,maxChainDepth:o.depth,maxChainOp:o.op,maxLetBindings:c.count,maxLetBindingsFunction:c.fn,maxCallDepth:d,maxEstimatedExpressions:f,getCallCount:y}}}const ue=Symbol.for("pyric.RulesValue.NO_OP");class te{field(e){return null}callMethod(e,r){return ue}binaryOp(e,r){return ue}}function ye(t,e){if(Object.is(t,e))return!0;if(t instanceof te)return t.equals(e);if(e instanceof te)return e.equals(t);if(t instanceof fe||e instanceof fe)return t instanceof fe&&t.equals(e);if(Array.isArray(t)||Array.isArray(e))return!Array.isArray(t)||!Array.isArray(e)||t.length!==e.length?!1:t.every((s,i)=>ye(s,e[i]));if(!Hi(t)||!Hi(e))return!1;const r=Object.keys(t),n=Object.keys(e);return r.length!==n.length?!1:r.every(s=>s in e&&ye(t[s],e[s]))}function Hi(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}class fe{items;constructor(e){this.items=[];for(const r of e)this.items.some(n=>ye(n,r))||this.items.push(r)}hasOnly(e){const r=e instanceof fe?e.toArray():e;return this.items.every(n=>r.some(s=>ye(n,s)))}equals(e){return!(e instanceof fe)||e.items.length!==this.items.length?!1:this.items.every(r=>e.items.some(n=>ye(r,n)))}hasAll(e){const r=e instanceof fe?e.toArray():e;for(const n of r)if(!this.items.some(s=>ye(s,n)))return!1;return!0}hasAny(e){const r=e instanceof fe?e.toArray():e;for(const n of r)if(this.items.some(s=>ye(s,n)))return!0;return!1}size(){return this.items.length}toArray(){return[...this.items]}difference(e){const r=e.toArray(),n=[];for(const s of this.items)r.some(i=>ye(s,i))||n.push(s);return new fe(n)}union(e){const r=e.toArray();return new fe([...this.items,...r])}intersection(e){const r=e.toArray(),n=[];for(const s of this.items)r.some(i=>ye(s,i))&&n.push(s);return new fe(n)}}class yr{before;after;constructor(e,r){this.before=e,this.after=r}addedKeys(){const e=[];for(const r of Object.keys(this.after))r in this.before||e.push(r);return new fe(e)}removedKeys(){const e=[];for(const r of Object.keys(this.before))r in this.after||e.push(r);return new fe(e)}changedKeys(){const e=[];for(const r of Object.keys(this.after))r in this.before&&!ye(this.before[r],this.after[r])&&e.push(r);return new fe(e)}affectedKeys(){const e=[],r=new Set([...Object.keys(this.before),...Object.keys(this.after)]);for(const n of r)(!(n in this.before)||!(n in this.after)||!ye(this.before[n],this.after[n]))&&e.push(n);return new fe(e)}unchangedKeys(){const e=[];for(const r of Object.keys(this.before))r in this.after&&ye(this.before[r],this.after[r])&&e.push(r);return new fe(e)}}const Ul=/^\{([A-Za-z_][A-Za-z0-9_]*)\}$/;class Xe extends te{typeName="path";segments;bindings;constructor(e,r={}){super(),this.segments=e,this.bindings=r}static fromString(e){const r=e.startsWith("/")?e.slice(1):e;return r.length===0?new Xe([]):new Xe(r.split("/"))}bind(e){const r=[],n={...this.bindings};for(const s of this.segments){const i=s.match(Ul);if(!i){r.push(s);continue}const a=i[1];if(a in e){const o=e[a];if(o==null)throw new TypeError(`Path.bind(): binding '${a}' must not be null`);const c=String(o);r.push(c),n[a]=c}else r.push(s)}return new Xe(r,n)}valueOf(){return NaN}toString(){return"/"+this.segments.join("/")}toJSON(){return{__type:"path",segments:[...this.segments]}}equals(e){if(!(e instanceof Xe)||this.segments.length!==e.segments.length)return!1;for(let r=0;r<this.segments.length;r++)if(this.segments[r]!==e.segments[r])return!1;return!0}field(e){if(/^\d+$/.test(e)){const r=Number(e);return r<0||r>=this.segments.length?null:this.segments[r]}return e in this.bindings?this.bindings[e]:null}callMethod(e,r){switch(e){case"bind":{const n=r[0];if(n==null||typeof n!="object"||Array.isArray(n)||n instanceof te)throw new TypeError(`Path.bind() requires a Map argument, got ${n===null?"null":typeof n}`);return this.bind(n)}default:return ue}}}class oe extends te{typeName="float";value;constructor(e){super(),this.value=e}valueOf(){return this.value}toString(){return Number.isInteger(this.value)?`${this.value}.0`:String(this.value)}toJSON(){return{__type:"float",value:this.value}}equals(e){return e instanceof oe?this.value===e.value:typeof e=="number"?this.value===e:!1}binaryOp(e,r){const n=r instanceof oe?r.value:typeof r=="number"?r:void 0;if(n===void 0)return ue;const s=this.value;switch(e){case"+":return new oe(s+n);case"-":return new oe(s-n);case"*":return new oe(s*n);case"/":return new oe(s/n);case"%":return new oe(s%n);case"<":return s<n;case"<=":return s<=n;case">":return s>n;case">=":return s>=n;default:return ue}}}class G extends Error{expr;constructor(e,r){super(e),this.expr=r,this.name="EvalError"}}class Je extends G{constructor(e,r){super(e,r),this.name="UnsupportedError"}}class Bl{entries=[];parents=[];frames=[];capture(e,r){const n=this.entries.length,s=this.parents.length>0?this.parents[this.parents.length-1]:null,i={source:Ie(e),kind:e.type,parent:s};this.stampFrame(i),this.entries.push(i),this.parents.push(n);try{const a=r();return this.entries[n].value=a,a}catch(a){throw this.entries[n].error=a instanceof Error?a.message:String(a),a}finally{this.parents.pop()}}skip(e){const r=this.parents.length>0?this.parents[this.parents.length-1]:null,n={source:Ie(e),kind:e.type,parent:r,skipped:!0};this.stampFrame(n),this.entries.push(n)}enterFrame(e){this.frames.push(e)}exitFrame(){this.frames.pop()}markEntryAsLetBinding(e,r){e<0||e>=this.entries.length||(this.entries[e].letBinding={name:r})}stampFrame(e){this.frames.length!==0&&(e.inlinedFrom={name:this.frames[this.frames.length-1]})}}function zl(t,e,r,n){const i=f=>f*Math.PI/180,a=i(t),o=i(r),c=i(r-t),u=i(n-e),d=Math.sin(c/2)**2+Math.cos(a)*Math.cos(o)*Math.sin(u/2)**2;return 6371e3*(2*Math.atan2(Math.sqrt(d),Math.sqrt(1-d)))}class rt extends te{typeName="latlng";lat;lng;constructor(e,r){super(),this.lat=e,this.lng=r}valueOf(){return NaN}toString(){return`${this.lat},${this.lng}`}toJSON(){return{__type:"latlng",lat:this.lat,lng:this.lng}}equals(e){return e instanceof rt&&this.lat===e.lat&&this.lng===e.lng}callMethod(e,r){switch(e){case"latitude":return this.lat;case"longitude":return this.lng;case"distance":{const n=r[0];if(!(n instanceof rt))throw new TypeError(`latlng.distance() requires a LatLng argument, got ${typeof n}`);return zl(this.lat,this.lng,n.lat,n.lng)}default:return ue}}}const Yt=1e9,Gi={w:10080*60,d:1440*60,h:3600,m:60,s:1};function Vl(t,e){let r=t+Math.trunc(e/Yt),n=e%Yt;return r>0&&n<0?(r-=1,n+=Yt):r<0&&n>0&&(r+=1,n-=Yt),{seconds:r,nanos:n}}class we extends te{typeName="duration";seconds;nanos;constructor(e,r){super();const n=Vl(e,r);this.seconds=n.seconds,this.nanos=n.nanos}static fromValue(e,r){if(r in Gi)return new we(e*Gi[r],0);if(r==="ms"){const n=Math.trunc(e/1e3),s=e-n*1e3;return new we(n,s*1e6)}if(r==="ns"){const n=Math.trunc(e/Yt),s=e-n*Yt;return new we(n,s)}throw new Error(`Unknown duration unit '${r}' (expected one of: w, d, h, m, s, ms, ns)`)}static fromTime(e,r,n,s){return new we(e*3600+r*60+n,s)}static abs(e){return new we(Math.abs(e.seconds),Math.abs(e.nanos))}valueOf(){return this.seconds*1e3+Math.round(this.nanos/1e6)}toString(){const e=this.seconds<0||this.nanos<0,r=Math.abs(this.seconds),n=Math.abs(this.nanos);return`${e?"-":""}${r}.${n.toString().padStart(9,"0")}s`}toJSON(){return{__type:"duration",seconds:this.seconds,nanos:this.nanos}}equals(e){return e instanceof we&&this.seconds===e.seconds&&this.nanos===e.nanos}callMethod(e,r){switch(e){case"seconds":return this.seconds;case"nanos":return this.nanos;default:return ue}}binaryOp(e,r){if(!(r instanceof we))return ue;switch(e){case"+":return new we(this.seconds+r.seconds,this.nanos+r.nanos);case"-":return new we(this.seconds-r.seconds,this.nanos-r.nanos);case"<":return this.compareTo(r)<0;case"<=":return this.compareTo(r)<=0;case">":return this.compareTo(r)>0;case">=":return this.compareTo(r)>=0;default:return ue}}compareTo(e){return this.seconds!==e.seconds?this.seconds-e.seconds:this.nanos-e.nanos}}const Ki=1e9,Wl=864e5,Kn=86400;function Hl(t,e){const r=Math.floor(e/Ki);return{seconds:t+r,nanos:e-r*Ki}}let xe=class ot extends te{typeName="timestamp";seconds;nanos;constructor(e,r){super();const n=Hl(e,r);this.seconds=n.seconds,this.nanos=n.nanos}static fromMillis(e){const r=Math.floor(e/1e3),n=e-r*1e3;return new ot(r,n*1e6)}static fromYMD(e,r,n){return ot.fromMillis(Date.UTC(e,r-1,n))}static fromIsoString(e){return ot.fromMillis(Date.parse(e))}toMillis(){return this.seconds*1e3+Math.floor(this.nanos/1e6)}toDate(){return new Date(this.toMillis())}valueOf(){return this.toMillis()}toString(){const e=new Date(this.toMillis()).toISOString(),r=this.nanos.toString().padStart(9,"0");return e.replace(/\.\d{3}Z$/,`.${r}Z`)}toJSON(){return{__type:"timestamp",seconds:this.seconds,nanos:this.nanos}}equals(e){return e instanceof ot&&this.seconds===e.seconds&&this.nanos===e.nanos}callMethod(e,r){switch(e){case"seconds":return this.seconds;case"nanos":return this.nanos;case"toMillis":return this.toMillis();case"year":return this.asDate().getUTCFullYear();case"month":return this.asDate().getUTCMonth()+1;case"day":return this.asDate().getUTCDate();case"hours":return this.asDate().getUTCHours();case"minutes":return this.asDate().getUTCMinutes();case"dayOfWeek":{const n=this.asDate().getUTCDay();return n===0?7:n}case"dayOfYear":{const n=this.asDate(),s=Date.UTC(n.getUTCFullYear(),0,1);return Math.floor((this.toMillis()-s)/Wl)+1}case"date":return ot.fromYMD(this.asDate().getUTCFullYear(),this.asDate().getUTCMonth()+1,this.asDate().getUTCDate());case"time":{const n=(this.seconds%Kn+Kn)%Kn,s=Math.floor(n/3600),i=Math.floor(n%3600/60),a=n%60;return we.fromTime(s,i,a,this.nanos)}default:return ue}}asDate(){return new Date(this.toMillis())}binaryOp(e,r){if(r instanceof ot)switch(e){case"-":return new we(this.seconds-r.seconds,this.nanos-r.nanos);case"<":return this.compareTo(r)<0;case"<=":return this.compareTo(r)<=0;case">":return this.compareTo(r)>0;case">=":return this.compareTo(r)>=0;default:return ue}if(r instanceof we)switch(e){case"+":return new ot(this.seconds+r.seconds,this.nanos+r.nanos);case"-":return new ot(this.seconds-r.seconds,this.nanos-r.nanos);default:return ue}return ue}compareTo(e){return this.seconds!==e.seconds?this.seconds-e.seconds:this.nanos-e.nanos}};const Zi="0123456789ABCDEF";function Gl(t){let e="";for(let r=0;r<t.length;r++){const n=t[r];e+=Zi[n>>>4]+Zi[n&15]}return e}function Kl(t){let e="";for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_")}function Zl(t,e){const r=Math.min(t.length,e.length);for(let n=0;n<r;n++)if(t[n]!==e[n])return t[n]<e[n]?-1:1;return t.length===e.length?0:t.length<e.length?-1:1}let Be=class fr extends te{typeName="bytes";data;constructor(e){super(),this.data=e}static fromUtf8(e){return new fr(new TextEncoder().encode(e))}static fromHex(e){if(e.length%2!==0)throw new Error(`Invalid hex string length: ${e.length}`);const r=new Uint8Array(e.length/2);for(let n=0;n<r.length;n++)r[n]=parseInt(e.substr(n*2,2),16);return new fr(r)}size(){return this.data.length}toBase64(){return Kl(this.data)}toHexString(){return Gl(this.data)}valueOf(){return this.data.length}toString(){return this.toBase64()}toJSON(){return{__type:"bytes",base64:this.toBase64()}}equals(e){if(!(e instanceof fr)||this.data.length!==e.data.length)return!1;for(let r=0;r<this.data.length;r++)if(this.data[r]!==e.data[r])return!1;return!0}callMethod(e,r){switch(e){case"size":return this.size();case"toBase64":return this.toBase64();case"toHexString":return this.toHexString()}return ue}binaryOp(e,r){if(!(r instanceof fr))return ue;const n=Zl(this.data,r.data);switch(e){case"<":return n<0;case"<=":return n<=0;case">":return n>0;case">=":return n>=0}return ue}};function br(t){return t.replace(/\$\(database\)/g,"(default)").replace(/^\/databases\/\(default\)\/documents\//,"")}function Ss(t,e){const r=t.split("/").filter(Boolean);return{data:e,id:r.at(-1)??"",__name__:new Xe(["databases","(default)","documents",...r])}}function Ji(t,e){const r=br(t);let n=e.mockDocuments.get(r);if(!n&&e.getDoc){const s=e.getDoc(r);s&&(e.mockDocuments.set(r,s),n=s)}if(n)return e.identitylessFunctionMocks?.has(r)?{data:n}:Ss(r,n);throw new G(`get() of non-existent document '${r}' (guard with exists() first)`)}function Qi(t,e){const r=br(t);if(e.mockDocuments.has(r))return!0;if(e.getDoc){const n=e.getDoc(r);if(n)return e.mockDocuments.set(r,n),!0}return!1}var Zn={exports:{}};const Jl={},Ql=Object.freeze(Object.defineProperty({__proto__:null,default:Jl},Symbol.toStringTag,{value:"Module"})),nn=pu(Ql);/**
472
472
  * [js-md5]{@link https://github.com/emn178/js-md5}
473
473
  *
474
474
  * @namespace md5
@@ -476,14 +476,14 @@ ${t}
476
476
  * @author Chen, Yi-Cyuan [emn178@gmail.com]
477
477
  * @copyright Chen, Yi-Cyuan 2014-2023
478
478
  * @license MIT
479
- */var Xi;function Xl(){return Xi||(Xi=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=co:i&&(s=self);var o=!s.JS_MD5_NO_COMMON_JS&&!0&&t.exports,c=!s.JS_MD5_NO_ARRAY_BUFFER&&typeof ArrayBuffer<"u",u="0123456789abcdef".split(""),d=[128,32768,8388608,-2147483648],l=[0,8,16,24],f=["hex","array","digest","buffer","arrayBuffer","base64"],y="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),b=[],S;if(c){var j=new ArrayBuffer(68);S=new Uint8Array(j),b=new Uint32Array(j)}var T=Array.isArray;(s.JS_MD5_NO_NODE_JS||!T)&&(T=function(h){return Object.prototype.toString.call(h)==="[object Array]"});var L=ArrayBuffer.isView;c&&(s.JS_MD5_NO_ARRAY_BUFFER_IS_VIEW||!L)&&(L=function(h){return typeof h=="object"&&h.buffer&&h.buffer.constructor===ArrayBuffer});var k=function(h){var p=typeof h;if(p==="string")return[h,!0];if(p!=="object"||h===null)throw new Error(e);if(c&&h.constructor===ArrayBuffer)return[new Uint8Array(h),!1];if(!T(h)&&!L(h))throw new Error(e);return[h,!1]},$=function(h){return function(p){return new v(!0).update(p)[h]()}},V=function(){var h=$("hex");a&&(h=w(h)),h.create=function(){return new v},h.update=function(m){return h.create().update(m)};for(var p=0;p<f.length;++p){var g=f[p];h[g]=$(g)}return h},w=function(h){var p=sn,g=sn.Buffer,m;g.from&&!s.JS_MD5_NO_BUFFER_FROM?m=g.from:m=function(E){return new g(E)};var D=function(E){if(typeof E=="string")return p.createHash("md5").update(E,"utf8").digest("hex");if(E==null)throw new Error(e);return E.constructor===ArrayBuffer&&(E=new Uint8Array(E)),T(E)||L(E)||E.constructor===g?p.createHash("md5").update(m(E)).digest("hex"):h(E)};return D},x=function(h){return function(p,g){return new O(p,!0).update(g)[h]()}},_=function(){var h=x("hex");h.create=function(m){return new O(m)},h.update=function(m,D){return h.create(m).update(D)};for(var p=0;p<f.length;++p){var g=f[p];h[g]=x(g)}return h};function v(h){if(h)b[0]=b[16]=b[1]=b[2]=b[3]=b[4]=b[5]=b[6]=b[7]=b[8]=b[9]=b[10]=b[11]=b[12]=b[13]=b[14]=b[15]=0,this.blocks=b,this.buffer8=S;else if(c){var p=new ArrayBuffer(68);this.buffer8=new Uint8Array(p),this.blocks=new Uint32Array(p)}else this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];this.h0=this.h1=this.h2=this.h3=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0}v.prototype.update=function(h){if(this.finalized)throw new Error(r);var p=k(h);h=p[0];for(var g=p[1],m,D=0,E,C=h.length,N=this.blocks,I=this.buffer8;D<C;){if(this.hashed&&(this.hashed=!1,N[0]=N[16],N[16]=N[1]=N[2]=N[3]=N[4]=N[5]=N[6]=N[7]=N[8]=N[9]=N[10]=N[11]=N[12]=N[13]=N[14]=N[15]=0),g)if(c)for(E=this.start;D<C&&E<64;++D)m=h.charCodeAt(D),m<128?I[E++]=m:m<2048?(I[E++]=192|m>>>6,I[E++]=128|m&63):m<55296||m>=57344?(I[E++]=224|m>>>12,I[E++]=128|m>>>6&63,I[E++]=128|m&63):(m=65536+((m&1023)<<10|h.charCodeAt(++D)&1023),I[E++]=240|m>>>18,I[E++]=128|m>>>12&63,I[E++]=128|m>>>6&63,I[E++]=128|m&63);else for(E=this.start;D<C&&E<64;++D)m=h.charCodeAt(D),m<128?N[E>>>2]|=m<<l[E++&3]:m<2048?(N[E>>>2]|=(192|m>>>6)<<l[E++&3],N[E>>>2]|=(128|m&63)<<l[E++&3]):m<55296||m>=57344?(N[E>>>2]|=(224|m>>>12)<<l[E++&3],N[E>>>2]|=(128|m>>>6&63)<<l[E++&3],N[E>>>2]|=(128|m&63)<<l[E++&3]):(m=65536+((m&1023)<<10|h.charCodeAt(++D)&1023),N[E>>>2]|=(240|m>>>18)<<l[E++&3],N[E>>>2]|=(128|m>>>12&63)<<l[E++&3],N[E>>>2]|=(128|m>>>6&63)<<l[E++&3],N[E>>>2]|=(128|m&63)<<l[E++&3]);else if(c)for(E=this.start;D<C&&E<64;++D)I[E++]=h[D];else for(E=this.start;D<C&&E<64;++D)N[E>>>2]|=h[D]<<l[E++&3];this.lastByteIndex=E,this.bytes+=E-this.start,E>=64?(this.start=E-64,this.hash(),this.hashed=!0):this.start=E}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this},v.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var h=this.blocks,p=this.lastByteIndex;h[p>>>2]|=d[p&3],p>=56&&(this.hashed||this.hash(),h[0]=h[16],h[16]=h[1]=h[2]=h[3]=h[4]=h[5]=h[6]=h[7]=h[8]=h[9]=h[10]=h[11]=h[12]=h[13]=h[14]=h[15]=0),h[14]=this.bytes<<3,h[15]=this.hBytes<<3|this.bytes>>>29,this.hash()}},v.prototype.hash=function(){var h,p,g,m,D,E,C=this.blocks;this.first?(h=C[0]-680876937,h=(h<<7|h>>>25)-271733879<<0,m=(-1732584194^h&2004318071)+C[1]-117830708,m=(m<<12|m>>>20)+h<<0,g=(-271733879^m&(h^-271733879))+C[2]-1126478375,g=(g<<17|g>>>15)+m<<0,p=(h^g&(m^h))+C[3]-1316259209,p=(p<<22|p>>>10)+g<<0):(h=this.h0,p=this.h1,g=this.h2,m=this.h3,h+=(m^p&(g^m))+C[0]-680876936,h=(h<<7|h>>>25)+p<<0,m+=(g^h&(p^g))+C[1]-389564586,m=(m<<12|m>>>20)+h<<0,g+=(p^m&(h^p))+C[2]+606105819,g=(g<<17|g>>>15)+m<<0,p+=(h^g&(m^h))+C[3]-1044525330,p=(p<<22|p>>>10)+g<<0),h+=(m^p&(g^m))+C[4]-176418897,h=(h<<7|h>>>25)+p<<0,m+=(g^h&(p^g))+C[5]+1200080426,m=(m<<12|m>>>20)+h<<0,g+=(p^m&(h^p))+C[6]-1473231341,g=(g<<17|g>>>15)+m<<0,p+=(h^g&(m^h))+C[7]-45705983,p=(p<<22|p>>>10)+g<<0,h+=(m^p&(g^m))+C[8]+1770035416,h=(h<<7|h>>>25)+p<<0,m+=(g^h&(p^g))+C[9]-1958414417,m=(m<<12|m>>>20)+h<<0,g+=(p^m&(h^p))+C[10]-42063,g=(g<<17|g>>>15)+m<<0,p+=(h^g&(m^h))+C[11]-1990404162,p=(p<<22|p>>>10)+g<<0,h+=(m^p&(g^m))+C[12]+1804603682,h=(h<<7|h>>>25)+p<<0,m+=(g^h&(p^g))+C[13]-40341101,m=(m<<12|m>>>20)+h<<0,g+=(p^m&(h^p))+C[14]-1502002290,g=(g<<17|g>>>15)+m<<0,p+=(h^g&(m^h))+C[15]+1236535329,p=(p<<22|p>>>10)+g<<0,h+=(g^m&(p^g))+C[1]-165796510,h=(h<<5|h>>>27)+p<<0,m+=(p^g&(h^p))+C[6]-1069501632,m=(m<<9|m>>>23)+h<<0,g+=(h^p&(m^h))+C[11]+643717713,g=(g<<14|g>>>18)+m<<0,p+=(m^h&(g^m))+C[0]-373897302,p=(p<<20|p>>>12)+g<<0,h+=(g^m&(p^g))+C[5]-701558691,h=(h<<5|h>>>27)+p<<0,m+=(p^g&(h^p))+C[10]+38016083,m=(m<<9|m>>>23)+h<<0,g+=(h^p&(m^h))+C[15]-660478335,g=(g<<14|g>>>18)+m<<0,p+=(m^h&(g^m))+C[4]-405537848,p=(p<<20|p>>>12)+g<<0,h+=(g^m&(p^g))+C[9]+568446438,h=(h<<5|h>>>27)+p<<0,m+=(p^g&(h^p))+C[14]-1019803690,m=(m<<9|m>>>23)+h<<0,g+=(h^p&(m^h))+C[3]-187363961,g=(g<<14|g>>>18)+m<<0,p+=(m^h&(g^m))+C[8]+1163531501,p=(p<<20|p>>>12)+g<<0,h+=(g^m&(p^g))+C[13]-1444681467,h=(h<<5|h>>>27)+p<<0,m+=(p^g&(h^p))+C[2]-51403784,m=(m<<9|m>>>23)+h<<0,g+=(h^p&(m^h))+C[7]+1735328473,g=(g<<14|g>>>18)+m<<0,p+=(m^h&(g^m))+C[12]-1926607734,p=(p<<20|p>>>12)+g<<0,D=p^g,h+=(D^m)+C[5]-378558,h=(h<<4|h>>>28)+p<<0,m+=(D^h)+C[8]-2022574463,m=(m<<11|m>>>21)+h<<0,E=m^h,g+=(E^p)+C[11]+1839030562,g=(g<<16|g>>>16)+m<<0,p+=(E^g)+C[14]-35309556,p=(p<<23|p>>>9)+g<<0,D=p^g,h+=(D^m)+C[1]-1530992060,h=(h<<4|h>>>28)+p<<0,m+=(D^h)+C[4]+1272893353,m=(m<<11|m>>>21)+h<<0,E=m^h,g+=(E^p)+C[7]-155497632,g=(g<<16|g>>>16)+m<<0,p+=(E^g)+C[10]-1094730640,p=(p<<23|p>>>9)+g<<0,D=p^g,h+=(D^m)+C[13]+681279174,h=(h<<4|h>>>28)+p<<0,m+=(D^h)+C[0]-358537222,m=(m<<11|m>>>21)+h<<0,E=m^h,g+=(E^p)+C[3]-722521979,g=(g<<16|g>>>16)+m<<0,p+=(E^g)+C[6]+76029189,p=(p<<23|p>>>9)+g<<0,D=p^g,h+=(D^m)+C[9]-640364487,h=(h<<4|h>>>28)+p<<0,m+=(D^h)+C[12]-421815835,m=(m<<11|m>>>21)+h<<0,E=m^h,g+=(E^p)+C[15]+530742520,g=(g<<16|g>>>16)+m<<0,p+=(E^g)+C[2]-995338651,p=(p<<23|p>>>9)+g<<0,h+=(g^(p|~m))+C[0]-198630844,h=(h<<6|h>>>26)+p<<0,m+=(p^(h|~g))+C[7]+1126891415,m=(m<<10|m>>>22)+h<<0,g+=(h^(m|~p))+C[14]-1416354905,g=(g<<15|g>>>17)+m<<0,p+=(m^(g|~h))+C[5]-57434055,p=(p<<21|p>>>11)+g<<0,h+=(g^(p|~m))+C[12]+1700485571,h=(h<<6|h>>>26)+p<<0,m+=(p^(h|~g))+C[3]-1894986606,m=(m<<10|m>>>22)+h<<0,g+=(h^(m|~p))+C[10]-1051523,g=(g<<15|g>>>17)+m<<0,p+=(m^(g|~h))+C[1]-2054922799,p=(p<<21|p>>>11)+g<<0,h+=(g^(p|~m))+C[8]+1873313359,h=(h<<6|h>>>26)+p<<0,m+=(p^(h|~g))+C[15]-30611744,m=(m<<10|m>>>22)+h<<0,g+=(h^(m|~p))+C[6]-1560198380,g=(g<<15|g>>>17)+m<<0,p+=(m^(g|~h))+C[13]+1309151649,p=(p<<21|p>>>11)+g<<0,h+=(g^(p|~m))+C[4]-145523070,h=(h<<6|h>>>26)+p<<0,m+=(p^(h|~g))+C[11]-1120210379,m=(m<<10|m>>>22)+h<<0,g+=(h^(m|~p))+C[2]+718787259,g=(g<<15|g>>>17)+m<<0,p+=(m^(g|~h))+C[9]-343485551,p=(p<<21|p>>>11)+g<<0,this.first?(this.h0=h+1732584193<<0,this.h1=p-271733879<<0,this.h2=g-1732584194<<0,this.h3=m+271733878<<0,this.first=!1):(this.h0=this.h0+h<<0,this.h1=this.h1+p<<0,this.h2=this.h2+g<<0,this.h3=this.h3+m<<0)},v.prototype.hex=function(){this.finalize();var h=this.h0,p=this.h1,g=this.h2,m=this.h3;return u[h>>>4&15]+u[h&15]+u[h>>>12&15]+u[h>>>8&15]+u[h>>>20&15]+u[h>>>16&15]+u[h>>>28&15]+u[h>>>24&15]+u[p>>>4&15]+u[p&15]+u[p>>>12&15]+u[p>>>8&15]+u[p>>>20&15]+u[p>>>16&15]+u[p>>>28&15]+u[p>>>24&15]+u[g>>>4&15]+u[g&15]+u[g>>>12&15]+u[g>>>8&15]+u[g>>>20&15]+u[g>>>16&15]+u[g>>>28&15]+u[g>>>24&15]+u[m>>>4&15]+u[m&15]+u[m>>>12&15]+u[m>>>8&15]+u[m>>>20&15]+u[m>>>16&15]+u[m>>>28&15]+u[m>>>24&15]},v.prototype.toString=v.prototype.hex,v.prototype.digest=function(){this.finalize();var h=this.h0,p=this.h1,g=this.h2,m=this.h3;return[h&255,h>>>8&255,h>>>16&255,h>>>24&255,p&255,p>>>8&255,p>>>16&255,p>>>24&255,g&255,g>>>8&255,g>>>16&255,g>>>24&255,m&255,m>>>8&255,m>>>16&255,m>>>24&255]},v.prototype.array=v.prototype.digest,v.prototype.arrayBuffer=function(){this.finalize();var h=new ArrayBuffer(16),p=new Uint32Array(h);return p[0]=this.h0,p[1]=this.h1,p[2]=this.h2,p[3]=this.h3,h},v.prototype.buffer=v.prototype.arrayBuffer,v.prototype.base64=function(){for(var h,p,g,m="",D=this.array(),E=0;E<15;)h=D[E++],p=D[E++],g=D[E++],m+=y[h>>>2]+y[(h<<4|p>>>4)&63]+y[(p<<2|g>>>6)&63]+y[g&63];return h=D[E],m+=y[h>>>2]+y[h<<4&63]+"==",m};function O(h,p){var g,m=k(h);if(h=m[0],m[1]){var D=[],E=h.length,C=0,N;for(g=0;g<E;++g)N=h.charCodeAt(g),N<128?D[C++]=N:N<2048?(D[C++]=192|N>>>6,D[C++]=128|N&63):N<55296||N>=57344?(D[C++]=224|N>>>12,D[C++]=128|N>>>6&63,D[C++]=128|N&63):(N=65536+((N&1023)<<10|h.charCodeAt(++g)&1023),D[C++]=240|N>>>18,D[C++]=128|N>>>12&63,D[C++]=128|N>>>6&63,D[C++]=128|N&63);h=D}h.length>64&&(h=new v(!0).update(h).array());var I=[],q=[];for(g=0;g<64;++g){var Z=h[g]||0;I[g]=92^Z,q[g]=54^Z}v.call(this,p),this.update(q),this.oKeyPad=I,this.inner=!0,this.sharedMemory=p}O.prototype=new v,O.prototype.finalize=function(){if(v.prototype.finalize.call(this),this.inner){this.inner=!1;var h=this.array();v.call(this,this.sharedMemory),this.update(this.oKeyPad),this.update(h),v.prototype.finalize.call(this)}};var A=V();A.md5=A,A.md5.hmac=_(),o?t.exports=A:s.md5=A})()})(Jn)),Jn.exports}var ed=Xl(),Qn={exports:{}};/**
479
+ */var Yi;function Yl(){return Yi||(Yi=1,(function(t){(function(){var e="input is invalid type",r="finalize already called",n=typeof window=="object",s=n?window:{};s.JS_MD5_NO_WINDOW&&(n=!1);var i=!n&&typeof self=="object",a=!s.JS_MD5_NO_NODE_JS&&typeof process=="object"&&process.versions&&process.versions.node;a?s=oo:i&&(s=self);var o=!s.JS_MD5_NO_COMMON_JS&&!0&&t.exports,c=!s.JS_MD5_NO_ARRAY_BUFFER&&typeof ArrayBuffer<"u",u="0123456789abcdef".split(""),d=[128,32768,8388608,-2147483648],l=[0,8,16,24],f=["hex","array","digest","buffer","arrayBuffer","base64"],y="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),b=[],S;if(c){var j=new ArrayBuffer(68);S=new Uint8Array(j),b=new Uint32Array(j)}var T=Array.isArray;(s.JS_MD5_NO_NODE_JS||!T)&&(T=function(h){return Object.prototype.toString.call(h)==="[object Array]"});var L=ArrayBuffer.isView;c&&(s.JS_MD5_NO_ARRAY_BUFFER_IS_VIEW||!L)&&(L=function(h){return typeof h=="object"&&h.buffer&&h.buffer.constructor===ArrayBuffer});var k=function(h){var p=typeof h;if(p==="string")return[h,!0];if(p!=="object"||h===null)throw new Error(e);if(c&&h.constructor===ArrayBuffer)return[new Uint8Array(h),!1];if(!T(h)&&!L(h))throw new Error(e);return[h,!1]},$=function(h){return function(p){return new v(!0).update(p)[h]()}},V=function(){var h=$("hex");a&&(h=w(h)),h.create=function(){return new v},h.update=function(m){return h.create().update(m)};for(var p=0;p<f.length;++p){var g=f[p];h[g]=$(g)}return h},w=function(h){var p=nn,g=nn.Buffer,m;g.from&&!s.JS_MD5_NO_BUFFER_FROM?m=g.from:m=function(E){return new g(E)};var D=function(E){if(typeof E=="string")return p.createHash("md5").update(E,"utf8").digest("hex");if(E==null)throw new Error(e);return E.constructor===ArrayBuffer&&(E=new Uint8Array(E)),T(E)||L(E)||E.constructor===g?p.createHash("md5").update(m(E)).digest("hex"):h(E)};return D},x=function(h){return function(p,g){return new O(p,!0).update(g)[h]()}},_=function(){var h=x("hex");h.create=function(m){return new O(m)},h.update=function(m,D){return h.create(m).update(D)};for(var p=0;p<f.length;++p){var g=f[p];h[g]=x(g)}return h};function v(h){if(h)b[0]=b[16]=b[1]=b[2]=b[3]=b[4]=b[5]=b[6]=b[7]=b[8]=b[9]=b[10]=b[11]=b[12]=b[13]=b[14]=b[15]=0,this.blocks=b,this.buffer8=S;else if(c){var p=new ArrayBuffer(68);this.buffer8=new Uint8Array(p),this.blocks=new Uint32Array(p)}else this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];this.h0=this.h1=this.h2=this.h3=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0}v.prototype.update=function(h){if(this.finalized)throw new Error(r);var p=k(h);h=p[0];for(var g=p[1],m,D=0,E,C=h.length,N=this.blocks,I=this.buffer8;D<C;){if(this.hashed&&(this.hashed=!1,N[0]=N[16],N[16]=N[1]=N[2]=N[3]=N[4]=N[5]=N[6]=N[7]=N[8]=N[9]=N[10]=N[11]=N[12]=N[13]=N[14]=N[15]=0),g)if(c)for(E=this.start;D<C&&E<64;++D)m=h.charCodeAt(D),m<128?I[E++]=m:m<2048?(I[E++]=192|m>>>6,I[E++]=128|m&63):m<55296||m>=57344?(I[E++]=224|m>>>12,I[E++]=128|m>>>6&63,I[E++]=128|m&63):(m=65536+((m&1023)<<10|h.charCodeAt(++D)&1023),I[E++]=240|m>>>18,I[E++]=128|m>>>12&63,I[E++]=128|m>>>6&63,I[E++]=128|m&63);else for(E=this.start;D<C&&E<64;++D)m=h.charCodeAt(D),m<128?N[E>>>2]|=m<<l[E++&3]:m<2048?(N[E>>>2]|=(192|m>>>6)<<l[E++&3],N[E>>>2]|=(128|m&63)<<l[E++&3]):m<55296||m>=57344?(N[E>>>2]|=(224|m>>>12)<<l[E++&3],N[E>>>2]|=(128|m>>>6&63)<<l[E++&3],N[E>>>2]|=(128|m&63)<<l[E++&3]):(m=65536+((m&1023)<<10|h.charCodeAt(++D)&1023),N[E>>>2]|=(240|m>>>18)<<l[E++&3],N[E>>>2]|=(128|m>>>12&63)<<l[E++&3],N[E>>>2]|=(128|m>>>6&63)<<l[E++&3],N[E>>>2]|=(128|m&63)<<l[E++&3]);else if(c)for(E=this.start;D<C&&E<64;++D)I[E++]=h[D];else for(E=this.start;D<C&&E<64;++D)N[E>>>2]|=h[D]<<l[E++&3];this.lastByteIndex=E,this.bytes+=E-this.start,E>=64?(this.start=E-64,this.hash(),this.hashed=!0):this.start=E}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this},v.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var h=this.blocks,p=this.lastByteIndex;h[p>>>2]|=d[p&3],p>=56&&(this.hashed||this.hash(),h[0]=h[16],h[16]=h[1]=h[2]=h[3]=h[4]=h[5]=h[6]=h[7]=h[8]=h[9]=h[10]=h[11]=h[12]=h[13]=h[14]=h[15]=0),h[14]=this.bytes<<3,h[15]=this.hBytes<<3|this.bytes>>>29,this.hash()}},v.prototype.hash=function(){var h,p,g,m,D,E,C=this.blocks;this.first?(h=C[0]-680876937,h=(h<<7|h>>>25)-271733879<<0,m=(-1732584194^h&2004318071)+C[1]-117830708,m=(m<<12|m>>>20)+h<<0,g=(-271733879^m&(h^-271733879))+C[2]-1126478375,g=(g<<17|g>>>15)+m<<0,p=(h^g&(m^h))+C[3]-1316259209,p=(p<<22|p>>>10)+g<<0):(h=this.h0,p=this.h1,g=this.h2,m=this.h3,h+=(m^p&(g^m))+C[0]-680876936,h=(h<<7|h>>>25)+p<<0,m+=(g^h&(p^g))+C[1]-389564586,m=(m<<12|m>>>20)+h<<0,g+=(p^m&(h^p))+C[2]+606105819,g=(g<<17|g>>>15)+m<<0,p+=(h^g&(m^h))+C[3]-1044525330,p=(p<<22|p>>>10)+g<<0),h+=(m^p&(g^m))+C[4]-176418897,h=(h<<7|h>>>25)+p<<0,m+=(g^h&(p^g))+C[5]+1200080426,m=(m<<12|m>>>20)+h<<0,g+=(p^m&(h^p))+C[6]-1473231341,g=(g<<17|g>>>15)+m<<0,p+=(h^g&(m^h))+C[7]-45705983,p=(p<<22|p>>>10)+g<<0,h+=(m^p&(g^m))+C[8]+1770035416,h=(h<<7|h>>>25)+p<<0,m+=(g^h&(p^g))+C[9]-1958414417,m=(m<<12|m>>>20)+h<<0,g+=(p^m&(h^p))+C[10]-42063,g=(g<<17|g>>>15)+m<<0,p+=(h^g&(m^h))+C[11]-1990404162,p=(p<<22|p>>>10)+g<<0,h+=(m^p&(g^m))+C[12]+1804603682,h=(h<<7|h>>>25)+p<<0,m+=(g^h&(p^g))+C[13]-40341101,m=(m<<12|m>>>20)+h<<0,g+=(p^m&(h^p))+C[14]-1502002290,g=(g<<17|g>>>15)+m<<0,p+=(h^g&(m^h))+C[15]+1236535329,p=(p<<22|p>>>10)+g<<0,h+=(g^m&(p^g))+C[1]-165796510,h=(h<<5|h>>>27)+p<<0,m+=(p^g&(h^p))+C[6]-1069501632,m=(m<<9|m>>>23)+h<<0,g+=(h^p&(m^h))+C[11]+643717713,g=(g<<14|g>>>18)+m<<0,p+=(m^h&(g^m))+C[0]-373897302,p=(p<<20|p>>>12)+g<<0,h+=(g^m&(p^g))+C[5]-701558691,h=(h<<5|h>>>27)+p<<0,m+=(p^g&(h^p))+C[10]+38016083,m=(m<<9|m>>>23)+h<<0,g+=(h^p&(m^h))+C[15]-660478335,g=(g<<14|g>>>18)+m<<0,p+=(m^h&(g^m))+C[4]-405537848,p=(p<<20|p>>>12)+g<<0,h+=(g^m&(p^g))+C[9]+568446438,h=(h<<5|h>>>27)+p<<0,m+=(p^g&(h^p))+C[14]-1019803690,m=(m<<9|m>>>23)+h<<0,g+=(h^p&(m^h))+C[3]-187363961,g=(g<<14|g>>>18)+m<<0,p+=(m^h&(g^m))+C[8]+1163531501,p=(p<<20|p>>>12)+g<<0,h+=(g^m&(p^g))+C[13]-1444681467,h=(h<<5|h>>>27)+p<<0,m+=(p^g&(h^p))+C[2]-51403784,m=(m<<9|m>>>23)+h<<0,g+=(h^p&(m^h))+C[7]+1735328473,g=(g<<14|g>>>18)+m<<0,p+=(m^h&(g^m))+C[12]-1926607734,p=(p<<20|p>>>12)+g<<0,D=p^g,h+=(D^m)+C[5]-378558,h=(h<<4|h>>>28)+p<<0,m+=(D^h)+C[8]-2022574463,m=(m<<11|m>>>21)+h<<0,E=m^h,g+=(E^p)+C[11]+1839030562,g=(g<<16|g>>>16)+m<<0,p+=(E^g)+C[14]-35309556,p=(p<<23|p>>>9)+g<<0,D=p^g,h+=(D^m)+C[1]-1530992060,h=(h<<4|h>>>28)+p<<0,m+=(D^h)+C[4]+1272893353,m=(m<<11|m>>>21)+h<<0,E=m^h,g+=(E^p)+C[7]-155497632,g=(g<<16|g>>>16)+m<<0,p+=(E^g)+C[10]-1094730640,p=(p<<23|p>>>9)+g<<0,D=p^g,h+=(D^m)+C[13]+681279174,h=(h<<4|h>>>28)+p<<0,m+=(D^h)+C[0]-358537222,m=(m<<11|m>>>21)+h<<0,E=m^h,g+=(E^p)+C[3]-722521979,g=(g<<16|g>>>16)+m<<0,p+=(E^g)+C[6]+76029189,p=(p<<23|p>>>9)+g<<0,D=p^g,h+=(D^m)+C[9]-640364487,h=(h<<4|h>>>28)+p<<0,m+=(D^h)+C[12]-421815835,m=(m<<11|m>>>21)+h<<0,E=m^h,g+=(E^p)+C[15]+530742520,g=(g<<16|g>>>16)+m<<0,p+=(E^g)+C[2]-995338651,p=(p<<23|p>>>9)+g<<0,h+=(g^(p|~m))+C[0]-198630844,h=(h<<6|h>>>26)+p<<0,m+=(p^(h|~g))+C[7]+1126891415,m=(m<<10|m>>>22)+h<<0,g+=(h^(m|~p))+C[14]-1416354905,g=(g<<15|g>>>17)+m<<0,p+=(m^(g|~h))+C[5]-57434055,p=(p<<21|p>>>11)+g<<0,h+=(g^(p|~m))+C[12]+1700485571,h=(h<<6|h>>>26)+p<<0,m+=(p^(h|~g))+C[3]-1894986606,m=(m<<10|m>>>22)+h<<0,g+=(h^(m|~p))+C[10]-1051523,g=(g<<15|g>>>17)+m<<0,p+=(m^(g|~h))+C[1]-2054922799,p=(p<<21|p>>>11)+g<<0,h+=(g^(p|~m))+C[8]+1873313359,h=(h<<6|h>>>26)+p<<0,m+=(p^(h|~g))+C[15]-30611744,m=(m<<10|m>>>22)+h<<0,g+=(h^(m|~p))+C[6]-1560198380,g=(g<<15|g>>>17)+m<<0,p+=(m^(g|~h))+C[13]+1309151649,p=(p<<21|p>>>11)+g<<0,h+=(g^(p|~m))+C[4]-145523070,h=(h<<6|h>>>26)+p<<0,m+=(p^(h|~g))+C[11]-1120210379,m=(m<<10|m>>>22)+h<<0,g+=(h^(m|~p))+C[2]+718787259,g=(g<<15|g>>>17)+m<<0,p+=(m^(g|~h))+C[9]-343485551,p=(p<<21|p>>>11)+g<<0,this.first?(this.h0=h+1732584193<<0,this.h1=p-271733879<<0,this.h2=g-1732584194<<0,this.h3=m+271733878<<0,this.first=!1):(this.h0=this.h0+h<<0,this.h1=this.h1+p<<0,this.h2=this.h2+g<<0,this.h3=this.h3+m<<0)},v.prototype.hex=function(){this.finalize();var h=this.h0,p=this.h1,g=this.h2,m=this.h3;return u[h>>>4&15]+u[h&15]+u[h>>>12&15]+u[h>>>8&15]+u[h>>>20&15]+u[h>>>16&15]+u[h>>>28&15]+u[h>>>24&15]+u[p>>>4&15]+u[p&15]+u[p>>>12&15]+u[p>>>8&15]+u[p>>>20&15]+u[p>>>16&15]+u[p>>>28&15]+u[p>>>24&15]+u[g>>>4&15]+u[g&15]+u[g>>>12&15]+u[g>>>8&15]+u[g>>>20&15]+u[g>>>16&15]+u[g>>>28&15]+u[g>>>24&15]+u[m>>>4&15]+u[m&15]+u[m>>>12&15]+u[m>>>8&15]+u[m>>>20&15]+u[m>>>16&15]+u[m>>>28&15]+u[m>>>24&15]},v.prototype.toString=v.prototype.hex,v.prototype.digest=function(){this.finalize();var h=this.h0,p=this.h1,g=this.h2,m=this.h3;return[h&255,h>>>8&255,h>>>16&255,h>>>24&255,p&255,p>>>8&255,p>>>16&255,p>>>24&255,g&255,g>>>8&255,g>>>16&255,g>>>24&255,m&255,m>>>8&255,m>>>16&255,m>>>24&255]},v.prototype.array=v.prototype.digest,v.prototype.arrayBuffer=function(){this.finalize();var h=new ArrayBuffer(16),p=new Uint32Array(h);return p[0]=this.h0,p[1]=this.h1,p[2]=this.h2,p[3]=this.h3,h},v.prototype.buffer=v.prototype.arrayBuffer,v.prototype.base64=function(){for(var h,p,g,m="",D=this.array(),E=0;E<15;)h=D[E++],p=D[E++],g=D[E++],m+=y[h>>>2]+y[(h<<4|p>>>4)&63]+y[(p<<2|g>>>6)&63]+y[g&63];return h=D[E],m+=y[h>>>2]+y[h<<4&63]+"==",m};function O(h,p){var g,m=k(h);if(h=m[0],m[1]){var D=[],E=h.length,C=0,N;for(g=0;g<E;++g)N=h.charCodeAt(g),N<128?D[C++]=N:N<2048?(D[C++]=192|N>>>6,D[C++]=128|N&63):N<55296||N>=57344?(D[C++]=224|N>>>12,D[C++]=128|N>>>6&63,D[C++]=128|N&63):(N=65536+((N&1023)<<10|h.charCodeAt(++g)&1023),D[C++]=240|N>>>18,D[C++]=128|N>>>12&63,D[C++]=128|N>>>6&63,D[C++]=128|N&63);h=D}h.length>64&&(h=new v(!0).update(h).array());var I=[],q=[];for(g=0;g<64;++g){var Z=h[g]||0;I[g]=92^Z,q[g]=54^Z}v.call(this,p),this.update(q),this.oKeyPad=I,this.inner=!0,this.sharedMemory=p}O.prototype=new v,O.prototype.finalize=function(){if(v.prototype.finalize.call(this),this.inner){this.inner=!1;var h=this.array();v.call(this,this.sharedMemory),this.update(this.oKeyPad),this.update(h),v.prototype.finalize.call(this)}};var A=V();A.md5=A,A.md5.hmac=_(),o?t.exports=A:s.md5=A})()})(Zn)),Zn.exports}var Xl=Yl(),Jn={exports:{}};/**
480
480
  * [js-sha256]{@link https://github.com/emn178/js-sha256}
481
481
  *
482
482
  * @version 0.11.1
483
483
  * @author Chen, Yi-Cyuan [emn178@gmail.com]
484
484
  * @copyright Chen, Yi-Cyuan 2014-2025
485
485
  * @license MIT
486
- */var ea;function td(){return ea||(ea=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=co:s&&(n=self);var a=!n.JS_SHA256_NO_COMMON_JS&&!0&&t.exports,o=!n.JS_SHA256_NO_ARRAY_BUFFER&&typeof ArrayBuffer<"u",c="0123456789abcdef".split(""),u=[-2147483648,8388608,32768,128],d=[24,16,8,0],l=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],f=["hex","array","digest","arrayBuffer"],y=[];(n.JS_SHA256_NO_NODE_JS||!Array.isArray)&&(Array.isArray=function(w){return Object.prototype.toString.call(w)==="[object Array]"}),o&&(n.JS_SHA256_NO_ARRAY_BUFFER_IS_VIEW||!ArrayBuffer.isView)&&(ArrayBuffer.isView=function(w){return typeof w=="object"&&w.buffer&&w.buffer.constructor===ArrayBuffer});var b=function(w,x){return function(_){return new k(x,!0).update(_)[w]()}},S=function(w){var x=b("hex",w);i&&(x=j(x,w)),x.create=function(){return new k(w)},x.update=function(O){return x.create().update(O)};for(var _=0;_<f.length;++_){var v=f[_];x[v]=b(v,w)}return x},j=function(w,x){var _=sn,v=sn.Buffer,O=x?"sha224":"sha256",A;v.from&&!n.JS_SHA256_NO_BUFFER_FROM?A=v.from:A=function(p){return new v(p)};var h=function(p){if(typeof p=="string")return _.createHash(O).update(p,"utf8").digest("hex");if(p==null)throw new Error(e);return p.constructor===ArrayBuffer&&(p=new Uint8Array(p)),Array.isArray(p)||ArrayBuffer.isView(p)||p.constructor===v?_.createHash(O).update(A(p)).digest("hex"):w(p)};return h},T=function(w,x){return function(_,v){return new $(_,x,!0).update(v)[w]()}},L=function(w){var x=T("hex",w);x.create=function(O){return new $(O,w)},x.update=function(O,A){return x.create(O).update(A)};for(var _=0;_<f.length;++_){var v=f[_];x[v]=T(v,w)}return x};function k(w,x){x?(y[0]=y[16]=y[1]=y[2]=y[3]=y[4]=y[5]=y[6]=y[7]=y[8]=y[9]=y[10]=y[11]=y[12]=y[13]=y[14]=y[15]=0,this.blocks=y):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],w?(this.h0=3238371032,this.h1=914150663,this.h2=812702999,this.h3=4144912697,this.h4=4290775857,this.h5=1750603025,this.h6=1694076839,this.h7=3204075428):(this.h0=1779033703,this.h1=3144134277,this.h2=1013904242,this.h3=2773480762,this.h4=1359893119,this.h5=2600822924,this.h6=528734635,this.h7=1541459225),this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0,this.is224=w}k.prototype.update=function(w){if(!this.finalized){var x,_=typeof w;if(_!=="string"){if(_==="object"){if(w===null)throw new Error(e);if(o&&w.constructor===ArrayBuffer)w=new Uint8Array(w);else if(!Array.isArray(w)&&(!o||!ArrayBuffer.isView(w)))throw new Error(e)}else throw new Error(e);x=!0}for(var v,O=0,A,h=w.length,p=this.blocks;O<h;){if(this.hashed&&(this.hashed=!1,p[0]=this.block,this.block=p[16]=p[1]=p[2]=p[3]=p[4]=p[5]=p[6]=p[7]=p[8]=p[9]=p[10]=p[11]=p[12]=p[13]=p[14]=p[15]=0),x)for(A=this.start;O<h&&A<64;++O)p[A>>>2]|=w[O]<<d[A++&3];else for(A=this.start;O<h&&A<64;++O)v=w.charCodeAt(O),v<128?p[A>>>2]|=v<<d[A++&3]:v<2048?(p[A>>>2]|=(192|v>>>6)<<d[A++&3],p[A>>>2]|=(128|v&63)<<d[A++&3]):v<55296||v>=57344?(p[A>>>2]|=(224|v>>>12)<<d[A++&3],p[A>>>2]|=(128|v>>>6&63)<<d[A++&3],p[A>>>2]|=(128|v&63)<<d[A++&3]):(v=65536+((v&1023)<<10|w.charCodeAt(++O)&1023),p[A>>>2]|=(240|v>>>18)<<d[A++&3],p[A>>>2]|=(128|v>>>12&63)<<d[A++&3],p[A>>>2]|=(128|v>>>6&63)<<d[A++&3],p[A>>>2]|=(128|v&63)<<d[A++&3]);this.lastByteIndex=A,this.bytes+=A-this.start,A>=64?(this.block=p[16],this.start=A-64,this.hash(),this.hashed=!0):this.start=A}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}},k.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var w=this.blocks,x=this.lastByteIndex;w[16]=this.block,w[x>>>2]|=u[x&3],this.block=w[16],x>=56&&(this.hashed||this.hash(),w[0]=this.block,w[16]=w[1]=w[2]=w[3]=w[4]=w[5]=w[6]=w[7]=w[8]=w[9]=w[10]=w[11]=w[12]=w[13]=w[14]=w[15]=0),w[14]=this.hBytes<<3|this.bytes>>>29,w[15]=this.bytes<<3,this.hash()}},k.prototype.hash=function(){var w=this.h0,x=this.h1,_=this.h2,v=this.h3,O=this.h4,A=this.h5,h=this.h6,p=this.h7,g=this.blocks,m,D,E,C,N,I,q,Z,pe,Q,ve;for(m=16;m<64;++m)N=g[m-15],D=(N>>>7|N<<25)^(N>>>18|N<<14)^N>>>3,N=g[m-2],E=(N>>>17|N<<15)^(N>>>19|N<<13)^N>>>10,g[m]=g[m-16]+D+g[m-7]+E<<0;for(ve=x&_,m=0;m<64;m+=4)this.first?(this.is224?(Z=300032,N=g[0]-1413257819,p=N-150054599<<0,v=N+24177077<<0):(Z=704751109,N=g[0]-210244248,p=N-1521486534<<0,v=N+143694565<<0),this.first=!1):(D=(w>>>2|w<<30)^(w>>>13|w<<19)^(w>>>22|w<<10),E=(O>>>6|O<<26)^(O>>>11|O<<21)^(O>>>25|O<<7),Z=w&x,C=Z^w&_^ve,q=O&A^~O&h,N=p+E+q+l[m]+g[m],I=D+C,p=v+N<<0,v=N+I<<0),D=(v>>>2|v<<30)^(v>>>13|v<<19)^(v>>>22|v<<10),E=(p>>>6|p<<26)^(p>>>11|p<<21)^(p>>>25|p<<7),pe=v&w,C=pe^v&x^Z,q=p&O^~p&A,N=h+E+q+l[m+1]+g[m+1],I=D+C,h=_+N<<0,_=N+I<<0,D=(_>>>2|_<<30)^(_>>>13|_<<19)^(_>>>22|_<<10),E=(h>>>6|h<<26)^(h>>>11|h<<21)^(h>>>25|h<<7),Q=_&v,C=Q^_&w^pe,q=h&p^~h&O,N=A+E+q+l[m+2]+g[m+2],I=D+C,A=x+N<<0,x=N+I<<0,D=(x>>>2|x<<30)^(x>>>13|x<<19)^(x>>>22|x<<10),E=(A>>>6|A<<26)^(A>>>11|A<<21)^(A>>>25|A<<7),ve=x&_,C=ve^x&v^Q,q=A&h^~A&p,N=O+E+q+l[m+3]+g[m+3],I=D+C,O=w+N<<0,w=N+I<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+w<<0,this.h1=this.h1+x<<0,this.h2=this.h2+_<<0,this.h3=this.h3+v<<0,this.h4=this.h4+O<<0,this.h5=this.h5+A<<0,this.h6=this.h6+h<<0,this.h7=this.h7+p<<0},k.prototype.hex=function(){this.finalize();var w=this.h0,x=this.h1,_=this.h2,v=this.h3,O=this.h4,A=this.h5,h=this.h6,p=this.h7,g=c[w>>>28&15]+c[w>>>24&15]+c[w>>>20&15]+c[w>>>16&15]+c[w>>>12&15]+c[w>>>8&15]+c[w>>>4&15]+c[w&15]+c[x>>>28&15]+c[x>>>24&15]+c[x>>>20&15]+c[x>>>16&15]+c[x>>>12&15]+c[x>>>8&15]+c[x>>>4&15]+c[x&15]+c[_>>>28&15]+c[_>>>24&15]+c[_>>>20&15]+c[_>>>16&15]+c[_>>>12&15]+c[_>>>8&15]+c[_>>>4&15]+c[_&15]+c[v>>>28&15]+c[v>>>24&15]+c[v>>>20&15]+c[v>>>16&15]+c[v>>>12&15]+c[v>>>8&15]+c[v>>>4&15]+c[v&15]+c[O>>>28&15]+c[O>>>24&15]+c[O>>>20&15]+c[O>>>16&15]+c[O>>>12&15]+c[O>>>8&15]+c[O>>>4&15]+c[O&15]+c[A>>>28&15]+c[A>>>24&15]+c[A>>>20&15]+c[A>>>16&15]+c[A>>>12&15]+c[A>>>8&15]+c[A>>>4&15]+c[A&15]+c[h>>>28&15]+c[h>>>24&15]+c[h>>>20&15]+c[h>>>16&15]+c[h>>>12&15]+c[h>>>8&15]+c[h>>>4&15]+c[h&15];return this.is224||(g+=c[p>>>28&15]+c[p>>>24&15]+c[p>>>20&15]+c[p>>>16&15]+c[p>>>12&15]+c[p>>>8&15]+c[p>>>4&15]+c[p&15]),g},k.prototype.toString=k.prototype.hex,k.prototype.digest=function(){this.finalize();var w=this.h0,x=this.h1,_=this.h2,v=this.h3,O=this.h4,A=this.h5,h=this.h6,p=this.h7,g=[w>>>24&255,w>>>16&255,w>>>8&255,w&255,x>>>24&255,x>>>16&255,x>>>8&255,x&255,_>>>24&255,_>>>16&255,_>>>8&255,_&255,v>>>24&255,v>>>16&255,v>>>8&255,v&255,O>>>24&255,O>>>16&255,O>>>8&255,O&255,A>>>24&255,A>>>16&255,A>>>8&255,A&255,h>>>24&255,h>>>16&255,h>>>8&255,h&255];return this.is224||g.push(p>>>24&255,p>>>16&255,p>>>8&255,p&255),g},k.prototype.array=k.prototype.digest,k.prototype.arrayBuffer=function(){this.finalize();var w=new ArrayBuffer(this.is224?28:32),x=new DataView(w);return x.setUint32(0,this.h0),x.setUint32(4,this.h1),x.setUint32(8,this.h2),x.setUint32(12,this.h3),x.setUint32(16,this.h4),x.setUint32(20,this.h5),x.setUint32(24,this.h6),this.is224||x.setUint32(28,this.h7),w};function $(w,x,_){var v,O=typeof w;if(O==="string"){var A=[],h=w.length,p=0,g;for(v=0;v<h;++v)g=w.charCodeAt(v),g<128?A[p++]=g:g<2048?(A[p++]=192|g>>>6,A[p++]=128|g&63):g<55296||g>=57344?(A[p++]=224|g>>>12,A[p++]=128|g>>>6&63,A[p++]=128|g&63):(g=65536+((g&1023)<<10|w.charCodeAt(++v)&1023),A[p++]=240|g>>>18,A[p++]=128|g>>>12&63,A[p++]=128|g>>>6&63,A[p++]=128|g&63);w=A}else if(O==="object"){if(w===null)throw new Error(e);if(o&&w.constructor===ArrayBuffer)w=new Uint8Array(w);else if(!Array.isArray(w)&&(!o||!ArrayBuffer.isView(w)))throw new Error(e)}else throw new Error(e);w.length>64&&(w=new k(x,!0).update(w).array());var m=[],D=[];for(v=0;v<64;++v){var E=w[v]||0;m[v]=92^E,D[v]=54^E}k.call(this,x,_),this.update(D),this.oKeyPad=m,this.inner=!0,this.sharedMemory=_}$.prototype=new k,$.prototype.finalize=function(){if(k.prototype.finalize.call(this),this.inner){this.inner=!1;var w=this.array();k.call(this,this.is224,this.sharedMemory),this.update(this.oKeyPad),this.update(w),k.prototype.finalize.call(this)}};var V=S();V.sha256=V,V.sha224=S(!0),V.sha256.hmac=L(),V.sha224.hmac=L(!0),a?t.exports=V:(n.sha256=V.sha256,n.sha224=V.sha224)})()})(Qn)),Qn.exports}var rd=td();function nd(t){if(t instanceof Be)return t;if(typeof t=="string")return Be.fromUtf8(t);throw new G(`hashing.* requires Bytes or String, got ${typeof t}`)}function sd(t,e){const r=nd(e[0]);switch(t){case"md5":return new Be(new Uint8Array(ed.md5.arrayBuffer(r.data)));case"sha256":return new Be(new Uint8Array(rd.sha256.arrayBuffer(r.data)));case"crc32":{const n=ad(r.data);return new Be(ta(n))}case"crc32c":{const n=cd(r.data);return new Be(ta(n))}}throw new Je(`Unknown hashing method '${t}'`)}function ta(t){return new Uint8Array([t&255,t>>>8&255,t>>>16&255,t>>>24&255])}const id=(()=>{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 ad(t){let e=4294967295;for(let r=0;r<t.length;r++)e=id[(e^t[r])&255]^e>>>8;return(e^4294967295)>>>0}const od=(()=>{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 cd(t){let e=4294967295;for(let r=0;r<t.length;r++)e=od[(e^t[r])&255]^e>>>8;return(e^4294967295)>>>0}function ud(t){if(typeof t=="number")return Math.trunc(t);if(t instanceof oe)return Math.trunc(t.value);if(typeof t=="boolean")return t?1:0;if(typeof t=="string"){if(/^[+-]?\d+$/.test(t.trim()))return parseInt(t.trim(),10);throw new G(`int() cannot convert string '${t}' to an integer`)}throw new G(`int() cannot convert ${typeof t} to an integer`)}function ld(t){if(t instanceof oe)return t;if(typeof t=="number")return new oe(t);if(typeof t=="string"){const e=t.trim();if(/^[+-]?(\d+\.?\d*|\.\d+)$/.test(e))return new oe(parseFloat(e));throw new G(`float() cannot convert string '${t}' to a float`)}throw new G(`float() cannot convert ${typeof t} to a float`)}function dd(t){if(typeof t=="boolean")return t;if(typeof t=="string"){if(t==="true")return!0;if(t==="false")return!1;throw new G(`bool() cannot convert string '${t}' to a boolean`)}throw new G(`bool() cannot convert ${typeof t} to a boolean`)}function hd(t,e,r,n){switch(t){case"get":{const a=String(W(e[0],r,n));return Qi(a,r)}case"exists":{const a=String(W(e[0],r,n));return Yi(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 _s(br(o),r.afterState)}const c=br(o);if(r.batchProjection?.has(c)){const u=r.batchProjection.get(c);if(u===null)throw new G(`getAfter() of non-existent document '${o}' (guard with existsAfter() first)`);return _s(c,u)}return Qi(o,r)}case"existsAfter":{const a=W(e[0],r,n),o=String(a);if(o===r.afterStatePath.toString())return r.existsAfter;const c=br(o);return r.batchProjection?.has(c)?r.batchProjection.get(c)!==null:Yi(o,r)}case"debug":return W(e[0],r,n);case"string":return String(W(e[0],r,n));case"int":return ud(W(e[0],r,n));case"float":return ld(W(e[0],r,n));case"bool":return dd(W(e[0],r,n));case"path":{const a=W(e[0],r,n);if(typeof a=="string")return Xe.fromString(a);throw new G(`path() requires a string argument, got ${typeof a}`)}}const s=r.functions.get(t);if(!s)throw new Je(`Unknown function: ${t}`);const i={...n};for(let a=0;a<s.parameters.length;a++)i[s.parameters[a]]=W(e[a],r,n);r.trace?.enterFrame(t);try{for(const a of s.lets){const o=r.trace?r.trace.entries.length:-1;i[a.name]=W(a.value,r,i),o>=0&&r.trace?.markEntryAsLetBinding(o,a.name)}return W(s.body,r,i)}finally{r.trace?.exitFrame()}}function fd(t,e,r,n,s){if(t.type==="identifier"){const o=t.name;if(ra(o)&&!(o in s)&&!(o in n.pathVariables)){const c=r.map(u=>W(u,n,s));return md(o,e,c)}if(!ra(o)&&!(o in s)&&!(o in n.pathVariables)&&!_d(o))throw new Je(`Unknown namespace or method '${o}.${e}()'`)}const i=W(t,n,s),a=r.map(o=>W(o,n,s));if(i instanceof te){const o=i.callMethod(e,a);if(o===ue)throw new Je(`Unknown method '${e}' on ${i.typeName}`);return o}if(e==="diff"&&typeof i=="object"&&i!==null&&!Array.isArray(i)){const o=a[0];if(typeof o=="object"&&o!==null)return new yr(o,i);throw new G("diff() requires a map argument")}if(typeof i=="function")return i(...a);if(i instanceof fe)switch(e){case"hasOnly":return i.hasOnly(a[0]);case"hasAll":return i.hasAll(a[0]);case"hasAny":return i.hasAny(a[0]);case"size":return i.size();case"difference":case"union":case"intersection":{const o=a[0];if(!(o instanceof fe))throw new G(`Unsupported operation: set.${e} requires a Set argument`);return i[e](o)}}if(i instanceof yr)switch(e){case"addedKeys":return i.addedKeys();case"removedKeys":return i.removedKeys();case"changedKeys":return i.changedKeys();case"affectedKeys":return i.affectedKeys();case"unchangedKeys":return i.unchangedKeys()}if(typeof i=="object"&&i!==null&&!Array.isArray(i)){const o=i;switch(e){case"keys":return Object.keys(o);case"values":return Object.values(o);case"size":return Object.keys(o).length;case"hasAll":return a[0].every(c=>Object.hasOwn(o,c));case"hasAny":return a[0].some(c=>Object.hasOwn(o,c));case"hasOnly":return Object.keys(o).every(c=>a[0].includes(c));case"diff":{const c=a[0];return new yr(c,o)}case"get":{const c=a[0],u=a[1];if(Array.isArray(c)){let l=o;for(const f of c){if(l==null||typeof l!="object"||Array.isArray(l)||l instanceof te)return u;const y=String(f);if(!Object.hasOwn(l,y))return u;l=l[y]}return l}const d=String(c);return Object.hasOwn(o,d)?o[d]:u}}}if(Array.isArray(i))switch(e){case"size":return i.length;case"hasAll":return a[0].every(o=>i.some(c=>ye(c,o)));case"hasAny":return a[0].some(o=>i.some(c=>ye(c,o)));case"hasOnly":{const o=a[0];return i.every(c=>o.some(u=>ye(u,c)))}case"join":return i.join(String(a[0]??","));case"concat":{const o=a[0];if(!Array.isArray(o))throw new G(`List.concat requires a list argument, got ${typeof o}`);return[...i,...o]}case"removeAll":{const o=a[0];if(!Array.isArray(o))throw new G(`List.removeAll requires a list argument, got ${typeof o}`);return i.filter(c=>!o.some(u=>ye(c,u)))}case"toSet":return new fe(i);case"difference":case"union":case"intersection":throw new G(`Function not found on List receiver: ${e}`)}if(typeof i=="string")switch(e){case"size":return i.length;case"lower":return i.toLowerCase();case"upper":return i.toUpperCase();case"trim":return i.trim();case"split":return i.split(Yn(String(a[0]),"g"));case"matches":return Yn(`^(?:${String(a[0])})$`).test(i);case"replace":return i.replace(Yn(String(a[0]),"g"),String(a[1]));case"toUtf8":return Be.fromUtf8(i)}throw new Je(`Unknown method '${e}' on ${typeof i}`)}function Yn(t,e=""){try{return new RegExp(t,e)}catch(r){throw new G(`Invalid regex '${t}': ${r.message}`)}}const pd=new Set(["math","timestamp","duration","latlng","hashing"]);function ra(t){return pd.has(t)}function md(t,e,r){const n=t==="hashing"?r:r.map(gd);switch(t){case"math":return bd(e,n);case"timestamp":return vd(e,n);case"duration":return wd(e,n);case"latlng":return yd(e,n);case"hashing":return sd(e,r)}throw new Je(`Unknown namespace '${t}'`)}function gd(t){return t instanceof oe?t.value:t}function yd(t,e){switch(t){case"value":{const[r,n]=e;return new rt(r,n)}}throw new Je(`Unknown latlng method '${t}'`)}function bd(t,e){switch(t){case"abs":return Math.abs(e[0]);case"ceil":return Math.ceil(e[0]);case"floor":return Math.floor(e[0]);case"round":return Math.round(e[0]);case"sqrt":return Math.sqrt(e[0]);case"pow":return Math.pow(e[0],e[1]);case"isInfinite":{const r=e[0];return Number.isFinite(r)===!1&&Number.isNaN(r)===!1}case"isNaN":return Number.isNaN(e[0])}throw new Je(`Unknown math method '${t}'`)}function vd(t,e){switch(t){case"date":{const[r,n,s]=e;return xe.fromYMD(r,n,s)}case"value":return xe.fromMillis(e[0])}throw new Je(`Unknown timestamp method '${t}'`)}function wd(t,e){switch(t){case"value":try{return we.fromValue(e[0],e[1])}catch(r){throw new G(r.message)}case"time":{const[r,n,s,i]=e;return we.fromTime(r,n,s,i)}case"abs":{const r=e[0];if(!(r instanceof we))throw new G(`duration.abs() requires a Duration argument, got ${typeof r}`);return we.abs(r)}}throw new Je(`Unknown duration method '${t}'`)}function W(t,e,r={}){return e.trace?e.trace.capture(t,()=>na(t,e,r)):na(t,e,r)}function na(t,e,r){switch(t.type){case"literal":return typeof t.value=="number"&&t.raw.includes(".")?new oe(t.value):t.value;case"identifier":return Sd(t.name,e,r);case"binaryOp":return Ad(t.op,t.left,t.right,e,r);case"unaryOp":{if(t.op==="!")return!W(t.operand,e,r);if(t.op==="-"){const n=W(t.operand,e,r);return n instanceof oe?new oe(-n.value):-n}throw new G(`Unknown unary op: ${t.op}`,t)}case"ternary":{const n=pr(W(t.condition,e,r),t.condition);return W(n?t.consequent:t.alternate,e,r)}case"memberAccess":{const n=W(t.object,e,r);if(n==null)throw new G(`Property '${t.property}' accessed on ${n===null?"null":"undefined"} value`,t);if(n instanceof te)return n.field(t.property);if(n instanceof yr)switch(t.property){case"addedKeys":return()=>n.addedKeys();case"removedKeys":return()=>n.removedKeys();case"changedKeys":return()=>n.changedKeys();case"affectedKeys":return()=>n.affectedKeys();case"unchangedKeys":return()=>n.unchangedKeys()}if(n instanceof fe)switch(t.property){case"size":return()=>n.size()}if(Object.hasOwn(n,t.property))return n[t.property];throw new G(`No field '${t.property}' on map (use 'in' or .get() to read a possibly-absent field)`,t)}case"bracketAccess":{const n=W(t.object,e,r),s=W(t.index,e,r);if(n==null)throw new G(`Index access on ${n===null?"null":"undefined"} value`,t);if(n instanceof te)return n.field(String(s));const i=String(s);return Object.hasOwn(n,i)?n[i]:null}case"sliceAccess":{const n=W(t.object,e,r),s=W(t.start,e,r),i=W(t.end,e,r);if(n==null)return null;if(typeof s!="number"||!Number.isInteger(s))throw new G(`Slice start must be an integer, got ${typeof s}`);if(typeof i!="number"||!Number.isInteger(i))throw new G(`Slice end must be an integer, got ${typeof i}`);if(s<0||i<0)throw new G(`Slice indices must be non-negative, got [${s}:${i}]`);if(typeof n=="string"||Array.isArray(n)){if(i>n.length)throw new G(`Slice end ${i} exceeds length ${n.length}`);return n.slice(s,i)}throw new G(`Slice not supported on ${typeof n}`)}case"inExpr":{const n=W(t.element,e,r),s=W(t.collection,e,r);return s==null?!1:Array.isArray(s)?s.some(i=>ye(i,n)):typeof s=="object"?Object.hasOwn(s,String(n)):!1}case"isExpr":{const n=W(t.value,e,r);switch(t.typeName){case"string":return typeof n=="string";case"int":return n instanceof te?!1:typeof n=="number";case"float":return n instanceof oe;case"number":return n instanceof oe?!0:n instanceof te?!1:typeof n=="number";case"bool":return typeof n=="boolean";case"null":return n===null;case"list":return Array.isArray(n);case"map":return n instanceof te||n instanceof yr||n instanceof fe?!1:typeof n=="object"&&n!==null&&!Array.isArray(n);default:return n instanceof te?n.typeName===t.typeName:!1}}case"listLiteral":return t.elements.map(n=>W(n,e,r));case"mapLiteral":{const n={};for(const s of t.entries){const i=String(W(s.key,e,r));n[i]=W(s.value,e,r)}return n}case"functionCall":return hd(t.name,t.args,e,r);case"methodCall":return fd(t.object,t.method,t.args,e,r);case"pathLiteral":{const n=[];for(const s of t.segments)typeof s=="string"?n.push(s):n.push(String(W(s,e,r)));return new Xe(n)}default:throw new G(`Unknown expression type: ${t.type}`,t)}}function Sd(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 _d(t){return t==="request"||t==="resource"||t==="true"||t==="false"||t==="null"}function Ad(t,e,r,n,s){if(t==="&&"){let o,c;try{o=pr(W(e,n,s),e)}catch(l){c=l}if(c===void 0&&o===!1)return n.trace?.skip(r),!1;let u,d;try{u=pr(W(r,n,s),r)}catch(l){d=l}if(d===void 0&&u===!1)return!1;if(c!==void 0)throw c;if(d!==void 0)throw d;return u}if(t==="||"){let o,c;try{o=pr(W(e,n,s),e)}catch(l){c=l}if(c===void 0&&o===!0)return n.trace?.skip(r),!0;let u,d;try{u=pr(W(r,n,s),r)}catch(l){d=l}if(d===void 0&&u===!0)return!0;if(c!==void 0)throw c;if(d!==void 0)throw d;return u}const i=W(e,n,s),a=W(r,n,s);if(t!=="=="&&t!=="!="){if(i instanceof te){const o=i.binaryOp(t,a);if(o!==ue)return o}if(typeof i=="number"&&a instanceof oe){const o=new oe(i).binaryOp(t,a);if(o!==ue)return o}if(a instanceof te&&(t==="+"||t==="*")){const o=a.binaryOp(t,i);if(o!==ue)return o}if((t!=="+"||typeof i!="string"&&typeof a!="string")&&(i instanceof te||a instanceof te)){const o=i instanceof te?i.typeName:typeof i,c=a instanceof te?a.typeName:typeof a;throw new G(`Operator '${t}' is not defined between ${o} and ${c}`)}}if((t==="<"||t===">"||t==="<="||t===">=")&&!(typeof i=="number"&&typeof a=="number"||typeof i=="string"&&typeof a=="string"))throw new G(`Operator '${t}' is not defined between ${typeof i} and ${typeof a}`);switch(t){case"==":return i===a||ye(i,a);case"!=":return!(i===a||ye(i,a));case"<":return i<a;case">":return i>a;case"<=":return i<=a;case">=":return i>=a;case"+":{if(Array.isArray(i)&&Array.isArray(a))return[...i,...a];if(typeof i=="string"&&typeof a=="string"||typeof i=="number"&&typeof a=="number")return i+a;if(typeof i=="string"&&a instanceof te)return i+String(a);throw new G(`Operator '+' is not defined between ${Array.isArray(i)?"list":typeof i} and ${Array.isArray(a)?"list":typeof a}`)}case"-":return i-a;case"*":return i*a;case"/":if(a===0)throw new G("Division by zero");return Math.trunc(i/a);case"%":if(a===0)throw new G("Modulo by zero");return i%a;default:throw new G(`Unknown binary op: ${t}`)}}function pr(t,e){if(typeof t=="boolean")return t;throw new G(`Expected a boolean control-flow operand, got ${t===null?"null":typeof t}`,e)}const xd=new Set(["__proto__","prototype","constructor"]);function an(t){if(xd.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 Ho(t,e){const r={...t};for(const[n,s]of Object.entries(e)){an(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]=Ho(i,s):r[n]=s}return r}function Id(t,e,r){let n=t;for(let i=0;i<e.length-1;i++){const a=e[i];an(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];an(s),n[s]=r}function kd(t,e){const r={...t};for(const[n,s]of Object.entries(e))n.includes(".")?Id(r,n.split("."),s):(an(n),r[n]=s);return r}function Ed(t,e,r){switch(t.kind){case"create":return r;case"set":return t.merge?Ho(e??{},r):r;case"update":return kd(e??{},r);case"delete":return null}}function Go(t){if(t===null||typeof t!="object"||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function Od(t){return typeof t=="object"&&t!==null&&t.__type==="serverTimestamp"}function Ko(t,e){const r={};for(const[n,s]of Object.entries(t))Od(s)?r[n]=e:Go(s)?r[n]=Ko(s,e):r[n]=s;return r}function Ct(t){return typeof t=="number"&&!Number.isInteger(t)?new oe(t):Array.isArray(t)?t.map(Ct):Go(t)?t.__type==="float"&&typeof t.value=="number"?new oe(t.value):Object.fromEntries(Object.entries(t).map(([e,r])=>[e,Ct(r)])):t}function sa(t){if(t.method==="list")return{limit:t.query?.limit??null,offset:t.query?.offset??null,orderBy:t.query?.orderBy??null}}function Gr(t){return`/${t.path.segments.map(r=>r.type==="literal"?r.value:r.type==="wildcard"?`{${r.name}}`:`{${r.name}=**}`).join("/")}`}function on(t,e,r,n){const s=[...r,...t.functions],i=t.path.segments,a={},o=[];let c=0,u;for(const f of i)if(f.type==="literal"){if(c>=e.length){u="request-shorter";break}if(e[c]!==f.value){u="literal-mismatch";break}c++}else if(f.type==="wildcard"){if(c>=e.length){u="request-shorter";break}a[f.name]=e[c],c===e.length-1&&o.push(f.name),c++}else a[f.name]=e.slice(c).join("/"),c<e.length&&o.push(f.name),c=e.length;if(u!==void 0)return n?.push({...t.loc?{line:t.loc.line}:{},blockPath:Gr(t),matchedSegments:c,totalSegments:i.length,bindings:a,matched:!1,reason:u}),[];const d=e.slice(c);if(d.length===0)return n?.push({...t.loc?{line:t.loc.line}:{},blockPath:Gr(t),matchedSegments:c,totalSegments:i.length,bindings:a,matched:!0}),[{block:t,pathVariables:a,candidateVariables:o,functions:s}];const l=[];for(const f of t.children)for(const y of on(f,d,s,n))y.pathVariables={...a,...y.pathVariables},y.candidateVariables=[...o,...y.candidateVariables],l.push(y);return n?.push({...t.loc?{line:t.loc.line}:{},blockPath:Gr(t),matchedSegments:c,totalSegments:i.length,bindings:a,...l.length>0?{matched:!0}:{matched:!1,reason:"no-matching-child"}}),l}class Cd{attempts=[];push(e){this.attempts.push(e)}}function Td(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 Rd(t,e,r){const n=Td(e),s=[],i=[],a=[];for(let u=0;u<t.allows.length;u++){const d=t.allows[u];d.operations.some(l=>n.includes(l))&&a.push({rule:d,index:u})}if(a.length===0)return i.push(`No allow rules found for operation '${e}'`),{decision:"DENY",trace:s,notes:i};let o=!1;const c=r.trace;for(const{rule:u,index:d}of a){const l=Nd(u,d),f=new zl;r.trace=f;try{const y=W(u.condition,r);if(l.expressionTrace=f.entries,y)return l.verdict="ALLOW",s.push(l),r.trace=c,{decision:"ALLOW",trace:s,notes:i};l.verdict="DENY",s.push(l)}catch(y){l.expressionTrace=f.entries,y instanceof Je?(o=!0,l.verdict="UNSUPPORTED",l.message=y.message):(l.verdict="ERROR",l.message=y instanceof Error?y.message:String(y)),s.push(l)}}return r.trace=c,{decision:o?"UNSUPPORTED":"DENY",trace:s,notes:i}}function Nd(t,e){const r={ruleIndex:e,operations:[...t.operations],verdict:"DENY",conditionText:Ie(t.condition)};return t.loc&&(r.line=t.loc.line),r}function Fd(t,e,r,n,s){const i=new Map;for(const L of e)i.set(L.name,L);const a=new Map,o=new Set;if(t.functionMocks)for(const L of t.functionMocks)L.function==="get"&&typeof L.result=="object"&&L.result!==null?(a.set(L.path,Ct(L.result)),o.add(L.path)):L.function==="exists"&&L.result===!0&&(a.set(L.path,{}),o.add(L.path));const c=t.requestTime?xe.fromIsoString(t.requestTime):xe.fromMillis(Date.now()),d=["databases","(default)","documents",...(t.path.startsWith("/")?t.path.slice(1):t.path).split("/").filter(Boolean)],l=new Xe(d,r),f=Ct(t.data??{}),y=t.resource===void 0||t.resource===null?null:Ct(t.resource);let b,S;if(t.writeMode)b=Ed(t.writeMode,y,f),S=b!==null;else switch(t.method){case"create":case"update":b=f,S=!0;break;case"delete":b=null,S=!1;break;case"get":case"list":default:b=y,S=y!==null;break}const j=b!==null?Ct(Ko(b,c)):null,T=j??{};return{request:{auth:t.auth?{uid:t.auth.uid,token:t.auth.token??{}}:null,resource:{data:T},method:t.method,path:l,...sa(t)?{query:sa(t)}:{},time:c},resource:t.method==="create"||y===null?null:{data:Ct(y)},mockDocuments:a,identitylessFunctionMocks:o,getDoc:n,pathVariables:r,functions:i,database:"(default)",afterStatePath:l,afterState:j,existsAfter:S,...s?{batchProjection:s}:{}}}class Ld{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=ii(e);if(!s)return{success:!1,error:{code:"PARSE_FAILED",message:"Failed to parse rules source",recoverable:!0}};const i=[];let a=0,o=0,c=0;const u={database:"(default)"};for(const d of s.service.match.path.segments)d.type==="wildcard"&&(u[d.name]="(default)");for(const d of r){const l=d.path.split("/").filter(Boolean),f=[...s.functions??[],...s.service.functions??[],...s.service.match.functions];let y=[];const b=new Cd;for(const x of s.service.match.children)y.push(...on(x,l,f,b));let S=!1;if(y.length===0&&d.method==="list"){const x=[...l,"__hypothetical_doc__"];for(const _ of s.service.match.children)y.push(...on(_,x,f,b));y.length>0&&(S=!0)}const j={requestPath:d.path,attempts:b.attempts};if(y.length===0){const x=d.expectation==="DENY"?"PASSED":"FAILED";x==="PASSED"?a++:o++,i.push({description:d.description,expectation:d.expectation,state:x,decision:"DENY",trace:[],notes:[`No match block found for path '${d.path}'`],pathResolution:j});continue}let T="DENY";const L=[],k=[];let $=!1,V;for(const x of y){const _={...u,...x.pathVariables},v=Fd(d,x.functions,_,n?.getDoc,n?.batchProjection),O=Gr(x.block),A=Rd(x.block,d.method,v);for(const h of A.trace)h.matchPath=O;if(L.push(...A.trace),k.push(...A.notes),A.decision==="ALLOW"){T="ALLOW",V=O;break}A.decision==="UNSUPPORTED"&&($=!0)}T!=="ALLOW"&&$&&(T="UNSUPPORTED"),T==="ALLOW"&&V&&k.push(`Allowed by match block '${V}'`),S&&k.push(`list on collection path '${d.path}' evaluated against the document-level match block (document wildcard hypothetical, resource undefined) — emulator-faithful`);let w;T==="UNSUPPORTED"?(w="UNSUPPORTED",c++):T===d.expectation?(w="PASSED",a++):(w="FAILED",o++),i.push({description:d.description,expectation:d.expectation,state:w,decision:T,trace:L,notes:k,pathResolution:j})}return{success:!0,data:{passed:a,failed:o,unsupported:c,results:i}}}}function jd(t,e,r=new Map,n){if(cn(t,r))return{provable:!0,reason:"list rule does not depend on per-document data; every doc is equally readable"};const s=Md(t,r,n);if(!s.ok||s.required.length===0){const u="list rule depends on per-document data through a predicate the query cannot discharge (a rule is provable only when its entire doc-dependence reduces to top-level `resource.data.field == value` conjunctions, including through inlined helpers — disjunctions, ranges, `in`, membership/type checks, and nested paths are not provable)";return{provable:!1,reason:`${u} — prod rejects the whole query rather than filtering`,residual:{missing:[],mismatched:[],outOfScope:u}}}const i=s.required,a=e.where??[],o=[],c=[];for(const u of i){if(a.some(f=>f.field===u.field&&f.op==="=="&&Ud(f.value,u.value)))continue;const l=a.find(f=>f.field===u.field&&f.op==="==");l?c.push({field:u.field,expectedValue:u.value,actualValue:l.value}):o.push({field:u.field,expectedValue:u.value,fromAuthUid:u.fromAuthUid})}return o.length===0&&c.length===0?{provable:!0,reason:"every per-document predicate the rule requires is guaranteed by a query where(...) constraint"}:{provable:!1,reason:Dd(o,c),residual:{missing:o,mismatched:c}}}function Dd(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 cn(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 cn(i.body,e,a)&&i.lets.every(o=>cn(o.value,e,a))}default:return!1}};return n(t)}function Md(t,e,r){const n=[],s=(i,a)=>{if(i.type==="binaryOp"&&i.op==="&&")return s(i.left,a)&&s(i.right,a);if(i.type==="functionCall"&&e.has(i.name)&&!a.has(i.name)){const c=e.get(i.name),u=new Map;c.parameters.forEach((f,y)=>{const b=i.args[y];b&&u.set(f,b)});for(const f of c.lets)u.set(f.name,ia(f.value,u));const d=ia(c.body,u),l=new Set(a).add(i.name);return s(d,l)}const o=Pd(i,r);return o?(n.push(o),!0):cn(i,e)};return s(t,new Set)?{ok:!0,required:n}:{ok:!1}}function Pd(t,e){if(t.type!=="binaryOp"||t.op!=="==")return null;const r=(n,s)=>{const i=qd(n);return i===null?null:s.type==="literal"?{field:i,value:s.value,fromAuthUid:!1}:e!==void 0&&$d(s)?{field:i,value:e,fromAuthUid:!0}:null};return r(t.left,t.right)??r(t.right,t.left)}function $d(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 ia(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 qd(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 Ud(t,e){return t===e}class jt extends te{typeName="reference";path;constructor(e){super(),this.path=Bd(e)}static fromResourceName(e){return new jt(Zo(e))}get id(){const e=this.path.lastIndexOf("/");return e===-1?this.path:this.path.slice(e+1)}get parent(){const e=this.path.lastIndexOf("/");return e===-1?"":this.path.slice(0,e)}valueOf(){return NaN}toString(){return this.path}toJSON(){return{__type:"reference",path:this.path}}equals(e){return e instanceof jt?this.path===e.path:!1}field(e){switch(e){case"path":return this.path;case"id":return this.id;case"parent":return this.parent;default:return null}}callMethod(e,r){return ue}}function Bd(t){let e=Zo(t);return e.startsWith("/")&&(e=e.slice(1)),e.endsWith("/")&&(e=e.slice(0,-1)),e}function Zo(t){const e="/documents/",r=t.indexOf(e);return r===-1?t:t.slice(r+e.length)}class Wt extends te{typeName="vector";value;constructor(e){if(super(),!Array.isArray(e))throw new TypeError("Vector: value must be a number[]");for(let r=0;r<e.length;r++)if(typeof e[r]!="number")throw new TypeError(`Vector: element at index ${r} is not a number (got ${typeof e[r]})`);this.value=Object.freeze(e.slice())}get dimension(){return this.value.length}valueOf(){return NaN}toString(){return`[${this.value.join(", ")}]`}toJSON(){return{__type__:"__vector__",value:this.value.slice()}}equals(e){if(!(e instanceof Wt)||e.value.length!==this.value.length)return!1;for(let r=0;r<this.value.length;r++)if(e.value[r]!==this.value[r])return!1;return!0}callMethod(e,r){return ue}}var Y;(function(t){t.assertEqual=s=>{};function e(s){}t.assertIs=e;function r(s){throw new Error}t.assertNever=r,t.arrayToEnum=s=>{const i={};for(const a of s)i[a]=a;return i},t.getValidEnumValues=s=>{const i=t.objectKeys(s).filter(o=>typeof s[s[o]]!="number"),a={};for(const o of i)a[o]=s[o];return t.objectValues(a)},t.objectValues=s=>t.objectKeys(s).map(function(i){return s[i]}),t.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const i=[];for(const a in s)Object.prototype.hasOwnProperty.call(s,a)&&i.push(a);return i},t.find=(s,i)=>{for(const a of s)if(i(a))return a},t.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,i=" | "){return s.map(a=>typeof a=="string"?`'${a}'`:a).join(i)}t.joinValues=n,t.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(Y||(Y={}));var aa;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(aa||(aa={}));const M=Y.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),yt=t=>{switch(typeof t){case"undefined":return M.undefined;case"string":return M.string;case"number":return Number.isNaN(t)?M.nan:M.number;case"boolean":return M.boolean;case"function":return M.function;case"bigint":return M.bigint;case"symbol":return M.symbol;case"object":return Array.isArray(t)?M.array:t===null?M.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?M.promise:typeof Map<"u"&&t instanceof Map?M.map:typeof Set<"u"&&t instanceof Set?M.set:typeof Date<"u"&&t instanceof Date?M.date:M.object;default:return M.unknown}},R=Y.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class ft extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};const r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){const r=e||function(i){return i.message},n={_errors:[]},s=i=>{for(const a of i.issues)if(a.code==="invalid_union")a.unionErrors.map(s);else if(a.code==="invalid_return_type")s(a.returnTypeError);else if(a.code==="invalid_arguments")s(a.argumentsError);else if(a.path.length===0)n._errors.push(r(a));else{let o=n,c=0;for(;c<a.path.length;){const u=a.path[c];c===a.path.length-1?(o[u]=o[u]||{_errors:[]},o[u]._errors.push(r(a))):o[u]=o[u]||{_errors:[]},o=o[u],c++}}};return s(this),n}static assert(e){if(!(e instanceof ft))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Y.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){const r={},n=[];for(const s of this.issues)if(s.path.length>0){const i=s.path[0];r[i]=r[i]||[],r[i].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}}ft.create=t=>new ft(t);const As=(t,e)=>{let r;switch(t.code){case R.invalid_type:t.received===M.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case R.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,Y.jsonStringifyReplacer)}`;break;case R.unrecognized_keys:r=`Unrecognized key(s) in object: ${Y.joinValues(t.keys,", ")}`;break;case R.invalid_union:r="Invalid input";break;case R.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Y.joinValues(t.options)}`;break;case R.invalid_enum_value:r=`Invalid enum value. Expected ${Y.joinValues(t.options)}, received '${t.received}'`;break;case R.invalid_arguments:r="Invalid function arguments";break;case R.invalid_return_type:r="Invalid function return type";break;case R.invalid_date:r="Invalid date";break;case R.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:Y.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case R.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case R.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case R.custom:r="Invalid input";break;case R.invalid_intersection_types:r="Intersection results could not be merged";break;case R.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case R.not_finite:r="Number must be finite";break;default:r=e.defaultError,Y.assertNever(t)}return{message:r}};let zd=As;function Vd(){return zd}const Wd=t=>{const{data:e,path:r,errorMaps:n,issueData:s}=t,i=[...r,...s.path||[]],a={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let o="";const c=n.filter(u=>!!u).slice().reverse();for(const u of c)o=u(a,{data:e,defaultError:o}).message;return{...s,path:i,message:o}};function F(t,e){const r=Vd(),n=Wd({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===As?void 0:As].filter(s=>!!s)});t.common.issues.push(n)}class je{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){const n=[];for(const s of r){if(s.status==="aborted")return U;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){const n=[];for(const s of r){const i=await s.key,a=await s.value;n.push({key:i,value:a})}return je.mergeObjectSync(e,n)}static mergeObjectSync(e,r){const n={};for(const s of r){const{key:i,value:a}=s;if(i.status==="aborted"||a.status==="aborted")return U;i.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof a.value<"u"||s.alwaysSet)&&(n[i.value]=a.value)}return{status:e.value,value:n}}}const U=Object.freeze({status:"aborted"}),mr=t=>({status:"dirty",value:t}),Ve=t=>({status:"valid",value:t}),oa=t=>t.status==="aborted",ca=t=>t.status==="dirty",er=t=>t.status==="valid",un=t=>typeof Promise<"u"&&t instanceof Promise;var P;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(P||(P={}));class nt{constructor(e,r,n,s){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const ua=(t,e)=>{if(er(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const r=new ft(t.common.issues);return this._error=r,this._error}}};function H(t){if(!t)return{};const{errorMap:e,invalid_type_error:r,required_error:n,description:s}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(a,o)=>{const{message:c}=t;return a.code==="invalid_enum_value"?{message:c??o.defaultError}:typeof o.data>"u"?{message:c??n??o.defaultError}:a.code!=="invalid_type"?{message:o.defaultError}:{message:c??r??o.defaultError}},description:s}}class K{get description(){return this._def.description}_getType(e){return yt(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:yt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new je,ctx:{common:e.parent.common,data:e.data,parsedType:yt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const r=this._parse(e);if(un(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){const r=this._parse(e);return Promise.resolve(r)}parse(e,r){const n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){const n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:yt(e)},s=this._parseSync({data:e,path:n.path,parent:n});return ua(n,s)}"~validate"(e){const r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:yt(e)};if(!this["~standard"].async)try{const n=this._parseSync({data:e,path:[],parent:r});return er(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>er(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){const n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){const n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:yt(e)},s=this._parse({data:e,path:n.path,parent:n}),i=await(un(s)?s:Promise.resolve(s));return ua(n,i)}refine(e,r){const n=s=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(s):r;return this._refinement((s,i)=>{const a=e(s),o=()=>i.addIssue({code:R.custom,...n(s)});return typeof Promise<"u"&&a instanceof Promise?a.then(c=>c?!0:(o(),!1)):a?!0:(o(),!1)})}refinement(e,r){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof r=="function"?r(n,s):r),!1))}_refinement(e){return new Pt({schema:this,typeName:B.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return dt.create(this,this._def)}nullable(){return $t.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return et.create(this)}promise(){return gn.create(this,this._def)}or(e){return hn.create([this,e],this._def)}and(e){return fn.create(this,e,this._def)}transform(e){return new Pt({...H(this._def),schema:this,typeName:B.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const r=typeof e=="function"?e:()=>e;return new yn({...H(this._def),innerType:this,defaultValue:r,typeName:B.ZodDefault})}brand(){return new Xo({typeName:B.ZodBranded,type:this,...H(this._def)})}catch(e){const r=typeof e=="function"?e:()=>e;return new bn({...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 ci.create(this,e)}readonly(){return vn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Hd=/^c[^\s-]{8,}$/i,Gd=/^[0-9a-z]+$/,Kd=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Zd=/^[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,Jd=/^[a-z0-9_-]{21}$/i,Qd=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Yd=/^[-+]?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)?)??$/,Xd=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,eh="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Xn;const th=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,rh=/^(?:(?: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])$/,nh=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,sh=/^(([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])$/,ih=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ah=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Jo="((\\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])))",oh=new RegExp(`^${Jo}$`);function Qo(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 ch(t){return new RegExp(`^${Qo(t)}$`)}function uh(t){let e=`${Jo}T${Qo(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 lh(t,e){return!!((e==="v4"||!e)&&th.test(t)||(e==="v6"||!e)&&nh.test(t))}function dh(t,e){if(!Qd.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 hh(t,e){return!!((e==="v4"||!e)&&rh.test(t)||(e==="v6"||!e)&&sh.test(t))}class ut extends K{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==M.string){const i=this._getOrReturnCtx(e);return F(i,{code:R.invalid_type,expected:M.string,received:i.parsedType}),U}const n=new je;let s;for(const i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),F(s,{code:R.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),F(s,{code:R.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="length"){const a=e.data.length>i.value,o=e.data.length<i.value;(a||o)&&(s=this._getOrReturnCtx(e,s),a?F(s,{code:R.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):o&&F(s,{code:R.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),n.dirty())}else if(i.kind==="email")Xd.test(e.data)||(s=this._getOrReturnCtx(e,s),F(s,{validation:"email",code:R.invalid_string,message:i.message}),n.dirty());else if(i.kind==="emoji")Xn||(Xn=new RegExp(eh,"u")),Xn.test(e.data)||(s=this._getOrReturnCtx(e,s),F(s,{validation:"emoji",code:R.invalid_string,message:i.message}),n.dirty());else if(i.kind==="uuid")Zd.test(e.data)||(s=this._getOrReturnCtx(e,s),F(s,{validation:"uuid",code:R.invalid_string,message:i.message}),n.dirty());else if(i.kind==="nanoid")Jd.test(e.data)||(s=this._getOrReturnCtx(e,s),F(s,{validation:"nanoid",code:R.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid")Hd.test(e.data)||(s=this._getOrReturnCtx(e,s),F(s,{validation:"cuid",code:R.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid2")Gd.test(e.data)||(s=this._getOrReturnCtx(e,s),F(s,{validation:"cuid2",code:R.invalid_string,message:i.message}),n.dirty());else if(i.kind==="ulid")Kd.test(e.data)||(s=this._getOrReturnCtx(e,s),F(s,{validation:"ulid",code:R.invalid_string,message:i.message}),n.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),F(s,{validation:"url",code:R.invalid_string,message:i.message}),n.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),F(s,{validation:"regex",code:R.invalid_string,message:i.message}),n.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),F(s,{code:R.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),n.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),F(s,{code:R.invalid_string,validation:{startsWith:i.value},message:i.message}),n.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),F(s,{code:R.invalid_string,validation:{endsWith:i.value},message:i.message}),n.dirty()):i.kind==="datetime"?uh(i).test(e.data)||(s=this._getOrReturnCtx(e,s),F(s,{code:R.invalid_string,validation:"datetime",message:i.message}),n.dirty()):i.kind==="date"?oh.test(e.data)||(s=this._getOrReturnCtx(e,s),F(s,{code:R.invalid_string,validation:"date",message:i.message}),n.dirty()):i.kind==="time"?ch(i).test(e.data)||(s=this._getOrReturnCtx(e,s),F(s,{code:R.invalid_string,validation:"time",message:i.message}),n.dirty()):i.kind==="duration"?Yd.test(e.data)||(s=this._getOrReturnCtx(e,s),F(s,{validation:"duration",code:R.invalid_string,message:i.message}),n.dirty()):i.kind==="ip"?lh(e.data,i.version)||(s=this._getOrReturnCtx(e,s),F(s,{validation:"ip",code:R.invalid_string,message:i.message}),n.dirty()):i.kind==="jwt"?dh(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),F(s,{validation:"jwt",code:R.invalid_string,message:i.message}),n.dirty()):i.kind==="cidr"?hh(e.data,i.version)||(s=this._getOrReturnCtx(e,s),F(s,{validation:"cidr",code:R.invalid_string,message:i.message}),n.dirty()):i.kind==="base64"?ih.test(e.data)||(s=this._getOrReturnCtx(e,s),F(s,{validation:"base64",code:R.invalid_string,message:i.message}),n.dirty()):i.kind==="base64url"?ah.test(e.data)||(s=this._getOrReturnCtx(e,s),F(s,{validation:"base64url",code:R.invalid_string,message:i.message}),n.dirty()):Y.assertNever(i);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(s=>e.test(s),{validation:r,code:R.invalid_string,...P.errToObj(n)})}_addCheck(e){return new ut({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...P.errToObj(e)})}url(e){return this._addCheck({kind:"url",...P.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...P.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...P.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...P.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...P.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...P.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...P.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...P.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...P.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...P.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...P.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...P.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...P.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...P.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...P.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...P.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...P.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...P.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...P.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...P.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...P.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...P.errToObj(r)})}nonempty(e){return this.min(1,P.errToObj(e))}trim(){return new ut({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ut({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ut({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}}ut.create=t=>new ut({checks:[],typeName:B.ZodString,coerce:t?.coerce??!1,...H(t)});function fh(t,e){const r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=r>n?r:n,i=Number.parseInt(t.toFixed(s).replace(".","")),a=Number.parseInt(e.toFixed(s).replace(".",""));return i%a/10**s}class tr extends K{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==M.number){const i=this._getOrReturnCtx(e);return F(i,{code:R.invalid_type,expected:M.number,received:i.parsedType}),U}let n;const s=new je;for(const i of this._def.checks)i.kind==="int"?Y.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{code:R.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),F(n,{code:R.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),F(n,{code:R.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?fh(e.data,i.value)!==0&&(n=this._getOrReturnCtx(e,n),F(n,{code:R.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{code:R.not_finite,message:i.message}),s.dirty()):Y.assertNever(i);return{status:s.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,P.toString(r))}gt(e,r){return this.setLimit("min",e,!1,P.toString(r))}lte(e,r){return this.setLimit("max",e,!0,P.toString(r))}lt(e,r){return this.setLimit("max",e,!1,P.toString(r))}setLimit(e,r,n,s){return new tr({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:P.toString(s)}]})}_addCheck(e){return new tr({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:P.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:P.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:P.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:P.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:P.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:P.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:P.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:P.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:P.toString(e)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&Y.isInteger(e.value))}get isFinite(){let e=null,r=null;for(const n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}}tr.create=t=>new tr({checks:[],typeName:B.ZodNumber,coerce:t?.coerce||!1,...H(t)});class Ar extends K{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==M.bigint)return this._getInvalidInput(e);let n;const s=new je;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),F(n,{code:R.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),F(n,{code:R.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),F(n,{code:R.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):Y.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){const r=this._getOrReturnCtx(e);return F(r,{code:R.invalid_type,expected:M.bigint,received:r.parsedType}),U}gte(e,r){return this.setLimit("min",e,!0,P.toString(r))}gt(e,r){return this.setLimit("min",e,!1,P.toString(r))}lte(e,r){return this.setLimit("max",e,!0,P.toString(r))}lt(e,r){return this.setLimit("max",e,!1,P.toString(r))}setLimit(e,r,n,s){return new Ar({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:P.toString(s)}]})}_addCheck(e){return new Ar({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:P.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:P.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:P.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:P.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:P.toString(r)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}}Ar.create=t=>new Ar({checks:[],typeName:B.ZodBigInt,coerce:t?.coerce??!1,...H(t)});class xs extends K{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==M.boolean){const n=this._getOrReturnCtx(e);return F(n,{code:R.invalid_type,expected:M.boolean,received:n.parsedType}),U}return Ve(e.data)}}xs.create=t=>new xs({typeName:B.ZodBoolean,coerce:t?.coerce||!1,...H(t)});class ln extends K{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==M.date){const i=this._getOrReturnCtx(e);return F(i,{code:R.invalid_type,expected:M.date,received:i.parsedType}),U}if(Number.isNaN(e.data.getTime())){const i=this._getOrReturnCtx(e);return F(i,{code:R.invalid_date}),U}const n=new je;let s;for(const i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),F(s,{code:R.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),n.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),F(s,{code:R.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),n.dirty()):Y.assertNever(i);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new ln({...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}}ln.create=t=>new ln({checks:[],coerce:t?.coerce||!1,typeName:B.ZodDate,...H(t)});class la extends K{_parse(e){if(this._getType(e)!==M.symbol){const n=this._getOrReturnCtx(e);return F(n,{code:R.invalid_type,expected:M.symbol,received:n.parsedType}),U}return Ve(e.data)}}la.create=t=>new la({typeName:B.ZodSymbol,...H(t)});class Is extends K{_parse(e){if(this._getType(e)!==M.undefined){const n=this._getOrReturnCtx(e);return F(n,{code:R.invalid_type,expected:M.undefined,received:n.parsedType}),U}return Ve(e.data)}}Is.create=t=>new Is({typeName:B.ZodUndefined,...H(t)});class dn extends K{_parse(e){if(this._getType(e)!==M.null){const n=this._getOrReturnCtx(e);return F(n,{code:R.invalid_type,expected:M.null,received:n.parsedType}),U}return Ve(e.data)}}dn.create=t=>new dn({typeName:B.ZodNull,...H(t)});class da extends K{constructor(){super(...arguments),this._any=!0}_parse(e){return Ve(e.data)}}da.create=t=>new da({typeName:B.ZodAny,...H(t)});class ks extends K{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ve(e.data)}}ks.create=t=>new ks({typeName:B.ZodUnknown,...H(t)});class _t extends K{_parse(e){const r=this._getOrReturnCtx(e);return F(r,{code:R.invalid_type,expected:M.never,received:r.parsedType}),U}}_t.create=t=>new _t({typeName:B.ZodNever,...H(t)});class ha extends K{_parse(e){if(this._getType(e)!==M.undefined){const n=this._getOrReturnCtx(e);return F(n,{code:R.invalid_type,expected:M.void,received:n.parsedType}),U}return Ve(e.data)}}ha.create=t=>new ha({typeName:B.ZodVoid,...H(t)});class et extends K{_parse(e){const{ctx:r,status:n}=this._processInputParams(e),s=this._def;if(r.parsedType!==M.array)return F(r,{code:R.invalid_type,expected:M.array,received:r.parsedType}),U;if(s.exactLength!==null){const a=r.data.length>s.exactLength.value,o=r.data.length<s.exactLength.value;(a||o)&&(F(r,{code:a?R.too_big:R.too_small,minimum:o?s.exactLength.value:void 0,maximum:a?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&r.data.length<s.minLength.value&&(F(r,{code:R.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&r.data.length>s.maxLength.value&&(F(r,{code:R.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((a,o)=>s.type._parseAsync(new nt(r,a,r.path,o)))).then(a=>je.mergeArray(n,a));const i=[...r.data].map((a,o)=>s.type._parseSync(new nt(r,a,r.path,o)));return je.mergeArray(n,i)}get element(){return this._def.type}min(e,r){return new et({...this._def,minLength:{value:e,message:P.toString(r)}})}max(e,r){return new et({...this._def,maxLength:{value:e,message:P.toString(r)}})}length(e,r){return new et({...this._def,exactLength:{value:e,message:P.toString(r)}})}nonempty(e){return this.min(1,e)}}et.create=(t,e)=>new et({type:t,minLength:null,maxLength:null,exactLength:null,typeName:B.ZodArray,...H(e)});function Zt(t){if(t instanceof me){const e={};for(const r in t.shape){const n=t.shape[r];e[r]=dt.create(Zt(n))}return new me({...t._def,shape:()=>e})}else return t instanceof et?new et({...t._def,type:Zt(t.element)}):t instanceof dt?dt.create(Zt(t.unwrap())):t instanceof $t?$t.create(Zt(t.unwrap())):t instanceof Dt?Dt.create(t.items.map(e=>Zt(e))):t}class me extends K{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),r=Y.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==M.object){const u=this._getOrReturnCtx(e);return F(u,{code:R.invalid_type,expected:M.object,received:u.parsedType}),U}const{status:n,ctx:s}=this._processInputParams(e),{shape:i,keys:a}=this._getCached(),o=[];if(!(this._def.catchall instanceof _t&&this._def.unknownKeys==="strip"))for(const u in s.data)a.includes(u)||o.push(u);const c=[];for(const u of a){const d=i[u],l=s.data[u];c.push({key:{status:"valid",value:u},value:d._parse(new nt(s,l,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof _t){const u=this._def.unknownKeys;if(u==="passthrough")for(const d of o)c.push({key:{status:"valid",value:d},value:{status:"valid",value:s.data[d]}});else if(u==="strict")o.length>0&&(F(s,{code:R.unrecognized_keys,keys:o}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const u=this._def.catchall;for(const d of o){const l=s.data[d];c.push({key:{status:"valid",value:d},value:u._parse(new nt(s,l,s.path,d)),alwaysSet:d in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const u=[];for(const d of c){const l=await d.key,f=await d.value;u.push({key:l,value:f,alwaysSet:d.alwaysSet})}return u}).then(u=>je.mergeObjectSync(n,u)):je.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return P.errToObj,new me({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{const s=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:P.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new me({...this._def,unknownKeys:"strip"})}passthrough(){return new me({...this._def,unknownKeys:"passthrough"})}extend(e){return new me({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new me({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:B.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new me({...this._def,catchall:e})}pick(e){const r={};for(const n of Y.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new me({...this._def,shape:()=>r})}omit(e){const r={};for(const n of Y.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new me({...this._def,shape:()=>r})}deepPartial(){return Zt(this)}partial(e){const r={};for(const n of Y.objectKeys(this.shape)){const s=this.shape[n];e&&!e[n]?r[n]=s:r[n]=s.optional()}return new me({...this._def,shape:()=>r})}required(e){const r={};for(const n of Y.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let i=this.shape[n];for(;i instanceof dt;)i=i._def.innerType;r[n]=i}return new me({...this._def,shape:()=>r})}keyof(){return Yo(Y.objectKeys(this.shape))}}me.create=(t,e)=>new me({shape:()=>t,unknownKeys:"strip",catchall:_t.create(),typeName:B.ZodObject,...H(e)});me.strictCreate=(t,e)=>new me({shape:()=>t,unknownKeys:"strict",catchall:_t.create(),typeName:B.ZodObject,...H(e)});me.lazycreate=(t,e)=>new me({shape:t,unknownKeys:"strip",catchall:_t.create(),typeName:B.ZodObject,...H(e)});class hn extends K{_parse(e){const{ctx:r}=this._processInputParams(e),n=this._def.options;function s(i){for(const o of i)if(o.result.status==="valid")return o.result;for(const o of i)if(o.result.status==="dirty")return r.common.issues.push(...o.ctx.common.issues),o.result;const a=i.map(o=>new ft(o.ctx.common.issues));return F(r,{code:R.invalid_union,unionErrors:a}),U}if(r.common.async)return Promise.all(n.map(async i=>{const a={...r,common:{...r.common,issues:[]},parent:null};return{result:await i._parseAsync({data:r.data,path:r.path,parent:a}),ctx:a}})).then(s);{let i;const a=[];for(const c of n){const u={...r,common:{...r.common,issues:[]},parent:null},d=c._parseSync({data:r.data,path:r.path,parent:u});if(d.status==="valid")return d;d.status==="dirty"&&!i&&(i={result:d,ctx:u}),u.common.issues.length&&a.push(u.common.issues)}if(i)return r.common.issues.push(...i.ctx.common.issues),i.result;const o=a.map(c=>new ft(c));return F(r,{code:R.invalid_union,unionErrors:o}),U}}get options(){return this._def.options}}hn.create=(t,e)=>new hn({options:t,typeName:B.ZodUnion,...H(e)});const ct=t=>t instanceof Os?ct(t.schema):t instanceof Pt?ct(t.innerType()):t instanceof mn?[t.value]:t instanceof Mt?t.options:t instanceof Cs?Y.objectValues(t.enum):t instanceof yn?ct(t._def.innerType):t instanceof Is?[void 0]:t instanceof dn?[null]:t instanceof dt?[void 0,...ct(t.unwrap())]:t instanceof $t?[null,...ct(t.unwrap())]:t instanceof Xo||t instanceof vn?ct(t.unwrap()):t instanceof bn?ct(t._def.innerType):[];class oi extends K{_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==M.object)return F(r,{code:R.invalid_type,expected:M.object,received:r.parsedType}),U;const n=this.discriminator,s=r.data[n],i=this.optionsMap.get(s);return i?r.common.async?i._parseAsync({data:r.data,path:r.path,parent:r}):i._parseSync({data:r.data,path:r.path,parent:r}):(F(r,{code:R.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),U)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){const s=new Map;for(const i of r){const a=ct(i.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const o of a){if(s.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);s.set(o,i)}}return new oi({typeName:B.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:s,...H(n)})}}function Es(t,e){const r=yt(t),n=yt(e);if(t===e)return{valid:!0,data:t};if(r===M.object&&n===M.object){const s=Y.objectKeys(e),i=Y.objectKeys(t).filter(o=>s.indexOf(o)!==-1),a={...t,...e};for(const o of i){const c=Es(t[o],e[o]);if(!c.valid)return{valid:!1};a[o]=c.data}return{valid:!0,data:a}}else if(r===M.array&&n===M.array){if(t.length!==e.length)return{valid:!1};const s=[];for(let i=0;i<t.length;i++){const a=t[i],o=e[i],c=Es(a,o);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return r===M.date&&n===M.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}class fn extends K{_parse(e){const{status:r,ctx:n}=this._processInputParams(e),s=(i,a)=>{if(oa(i)||oa(a))return U;const o=Es(i.value,a.value);return o.valid?((ca(i)||ca(a))&&r.dirty(),{status:r.value,value:o.data}):(F(n,{code:R.invalid_intersection_types}),U)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([i,a])=>s(i,a)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}fn.create=(t,e,r)=>new fn({left:t,right:e,typeName:B.ZodIntersection,...H(r)});class Dt extends K{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.array)return F(n,{code:R.invalid_type,expected:M.array,received:n.parsedType}),U;if(n.data.length<this._def.items.length)return F(n,{code:R.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),U;!this._def.rest&&n.data.length>this._def.items.length&&(F(n,{code:R.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());const i=[...n.data].map((a,o)=>{const c=this._def.items[o]||this._def.rest;return c?c._parse(new nt(n,a,n.path,o)):null}).filter(a=>!!a);return n.common.async?Promise.all(i).then(a=>je.mergeArray(r,a)):je.mergeArray(r,i)}get items(){return this._def.items}rest(e){return new Dt({...this._def,rest:e})}}Dt.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Dt({items:t,typeName:B.ZodTuple,rest:null,...H(e)})};class pn extends K{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.object)return F(n,{code:R.invalid_type,expected:M.object,received:n.parsedType}),U;const s=[],i=this._def.keyType,a=this._def.valueType;for(const o in n.data)s.push({key:i._parse(new nt(n,o,n.path,o)),value:a._parse(new nt(n,n.data[o],n.path,o)),alwaysSet:o in n.data});return n.common.async?je.mergeObjectAsync(r,s):je.mergeObjectSync(r,s)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof K?new pn({keyType:e,valueType:r,typeName:B.ZodRecord,...H(n)}):new pn({keyType:ut.create(),valueType:e,typeName:B.ZodRecord,...H(r)})}}class fa extends K{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.map)return F(n,{code:R.invalid_type,expected:M.map,received:n.parsedType}),U;const s=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([o,c],u)=>({key:s._parse(new nt(n,o,n.path,[u,"key"])),value:i._parse(new nt(n,c,n.path,[u,"value"]))}));if(n.common.async){const o=new Map;return Promise.resolve().then(async()=>{for(const c of a){const u=await c.key,d=await c.value;if(u.status==="aborted"||d.status==="aborted")return U;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),o.set(u.value,d.value)}return{status:r.value,value:o}})}else{const o=new Map;for(const c of a){const u=c.key,d=c.value;if(u.status==="aborted"||d.status==="aborted")return U;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),o.set(u.value,d.value)}return{status:r.value,value:o}}}}fa.create=(t,e,r)=>new fa({valueType:e,keyType:t,typeName:B.ZodMap,...H(r)});class xr extends K{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.set)return F(n,{code:R.invalid_type,expected:M.set,received:n.parsedType}),U;const s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(F(n,{code:R.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),r.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(F(n,{code:R.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),r.dirty());const i=this._def.valueType;function a(c){const u=new Set;for(const d of c){if(d.status==="aborted")return U;d.status==="dirty"&&r.dirty(),u.add(d.value)}return{status:r.value,value:u}}const o=[...n.data.values()].map((c,u)=>i._parse(new nt(n,c,n.path,u)));return n.common.async?Promise.all(o).then(c=>a(c)):a(o)}min(e,r){return new xr({...this._def,minSize:{value:e,message:P.toString(r)}})}max(e,r){return new xr({...this._def,maxSize:{value:e,message:P.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}}xr.create=(t,e)=>new xr({valueType:t,minSize:null,maxSize:null,typeName:B.ZodSet,...H(e)});class Os 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})}}Os.create=(t,e)=>new Os({getter:t,typeName:B.ZodLazy,...H(e)});class mn extends K{_parse(e){if(e.data!==this._def.value){const r=this._getOrReturnCtx(e);return F(r,{received:r.data,code:R.invalid_literal,expected:this._def.value}),U}return{status:"valid",value:e.data}}get value(){return this._def.value}}mn.create=(t,e)=>new mn({value:t,typeName:B.ZodLiteral,...H(e)});function Yo(t,e){return new Mt({values:t,typeName:B.ZodEnum,...H(e)})}class Mt extends K{_parse(e){if(typeof e.data!="string"){const r=this._getOrReturnCtx(e),n=this._def.values;return F(r,{expected:Y.joinValues(n),received:r.parsedType,code:R.invalid_type}),U}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const r=this._getOrReturnCtx(e),n=this._def.values;return F(r,{received:r.data,code:R.invalid_enum_value,options:n}),U}return Ve(e.data)}get options(){return this._def.values}get enum(){const e={};for(const r of this._def.values)e[r]=r;return e}get Values(){const e={};for(const r of this._def.values)e[r]=r;return e}get Enum(){const e={};for(const r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return Mt.create(e,{...this._def,...r})}exclude(e,r=this._def){return Mt.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}}Mt.create=Yo;class Cs extends K{_parse(e){const r=Y.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==M.string&&n.parsedType!==M.number){const s=Y.objectValues(r);return F(n,{expected:Y.joinValues(s),received:n.parsedType,code:R.invalid_type}),U}if(this._cache||(this._cache=new Set(Y.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const s=Y.objectValues(r);return F(n,{received:n.data,code:R.invalid_enum_value,options:s}),U}return Ve(e.data)}get enum(){return this._def.values}}Cs.create=(t,e)=>new Cs({values:t,typeName:B.ZodNativeEnum,...H(e)});class gn extends K{unwrap(){return this._def.type}_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==M.promise&&r.common.async===!1)return F(r,{code:R.invalid_type,expected:M.promise,received:r.parsedType}),U;const n=r.parsedType===M.promise?r.data:Promise.resolve(r.data);return Ve(n.then(s=>this._def.type.parseAsync(s,{path:r.path,errorMap:r.common.contextualErrorMap})))}}gn.create=(t,e)=>new gn({type:t,typeName:B.ZodPromise,...H(e)});class Pt extends K{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===B.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:r,ctx:n}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:a=>{F(n,a),a.fatal?r.abort():r.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){const a=s.transform(n.data,i);if(n.common.async)return Promise.resolve(a).then(async o=>{if(r.value==="aborted")return U;const c=await this._def.schema._parseAsync({data:o,path:n.path,parent:n});return c.status==="aborted"?U:c.status==="dirty"||r.value==="dirty"?mr(c.value):c});{if(r.value==="aborted")return U;const o=this._def.schema._parseSync({data:a,path:n.path,parent:n});return o.status==="aborted"?U:o.status==="dirty"||r.value==="dirty"?mr(o.value):o}}if(s.type==="refinement"){const a=o=>{const c=s.refinement(o,i);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(n.common.async===!1){const o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?U:(o.status==="dirty"&&r.dirty(),a(o.value),{status:r.value,value:o.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>o.status==="aborted"?U:(o.status==="dirty"&&r.dirty(),a(o.value).then(()=>({status:r.value,value:o.value}))))}if(s.type==="transform")if(n.common.async===!1){const a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!er(a))return U;const o=s.transform(a.value,i);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:o}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>er(a)?Promise.resolve(s.transform(a.value,i)).then(o=>({status:r.value,value:o})):U);Y.assertNever(s)}}Pt.create=(t,e,r)=>new Pt({schema:t,typeName:B.ZodEffects,effect:e,...H(r)});Pt.createWithPreprocess=(t,e,r)=>new Pt({schema:e,effect:{type:"preprocess",transform:t},typeName:B.ZodEffects,...H(r)});class dt extends K{_parse(e){return this._getType(e)===M.undefined?Ve(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}dt.create=(t,e)=>new dt({innerType:t,typeName:B.ZodOptional,...H(e)});class $t extends K{_parse(e){return this._getType(e)===M.null?Ve(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}$t.create=(t,e)=>new $t({innerType:t,typeName:B.ZodNullable,...H(e)});class yn extends K{_parse(e){const{ctx:r}=this._processInputParams(e);let n=r.data;return r.parsedType===M.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}}yn.create=(t,e)=>new yn({innerType:t,typeName:B.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...H(e)});class bn 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 un(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new ft(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new ft(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}bn.create=(t,e)=>new bn({innerType:t,typeName:B.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...H(e)});class pa extends K{_parse(e){if(this._getType(e)!==M.nan){const n=this._getOrReturnCtx(e);return F(n,{code:R.invalid_type,expected:M.nan,received:n.parsedType}),U}return{status:"valid",value:e.data}}}pa.create=t=>new pa({typeName:B.ZodNaN,...H(t)});class Xo 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 ci extends K{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?U:i.status==="dirty"?(r.dirty(),mr(i.value)):this._def.out._parseAsync({data:i.value,path:n.path,parent:n})})();{const s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?U:s.status==="dirty"?(r.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,r){return new ci({in:e,out:r,typeName:B.ZodPipeline})}}class vn extends K{_parse(e){const r=this._def.innerType._parse(e),n=s=>(er(s)&&(s.value=Object.freeze(s.value)),s);return un(r)?r.then(s=>n(s)):n(r)}unwrap(){return this._def.innerType}}vn.create=(t,e)=>new vn({innerType:t,typeName:B.ZodReadonly,...H(e)});var B;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(B||(B={}));const Ft=ut.create,ma=tr.create,ui=xs.create,ph=dn.create,Ir=ks.create;_t.create;const mh=et.create,lt=me.create,li=hn.create,gh=oi.create;fn.create;Dt.create;const kr=pn.create,qr=mn.create,wn=Mt.create;gn.create;dt.create;$t.create;const yh=["get","list","create","update","delete"],bh=lt({uid:Ft(),token:kr(Ir()).optional()}),vh=lt({function:wn(["get","exists"]).describe("Firestore function to mock"),path:Ft().describe('Document path, e.g. "users/alice"'),result:li([kr(Ir()),ui()]).describe("Document data for get, boolean for exists")}),wh=gh("kind",[lt({kind:qr("create")}),lt({kind:qr("set"),merge:ui()}),lt({kind:qr("update")}),lt({kind:qr("delete")})]),Sh=lt({limit:ma().optional(),offset:ma().optional(),orderBy:Ft().optional()});lt({description:Ft().describe("Human-readable description of what this test verifies"),expectation:wn(["ALLOW","DENY"]).describe("Expected outcome"),method:wn(yh).describe("Firestore method to test"),path:Ft().describe('Document path, e.g. "users/alice"'),auth:li([bh,ph()]).optional().describe("Auth context; null or omitted for unauthenticated"),data:kr(Ir()).optional().describe("request.resource.data for write operations"),resource:kr(Ir()).optional().describe("Existing document data (resource.data)"),functionMocks:mh(vh).optional().describe("Mock get()/exists() calls in rules"),query:Sh.optional().describe("request.query payload (list ops only): limit/offset/orderBy."),requestTime:Ft().optional().describe("Override for request.time (ISO-8601). Defaults to wallclock."),writeMode:wh.optional().describe("Optional write-mode override; controls update merge semantics and getAfter() projection.")});function Er(t){if(t.decision==="UNSUPPORTED")return;const e=t.decision==="ALLOW",r=e?t.trace.find(s=>s.verdict==="ALLOW"):t.trace.find(s=>s.verdict==="DENY"||s.verdict==="ERROR")??t.trace[t.trace.length-1];if(!r)return;const n={verdict:e?"allow":"deny"};return r.line!==void 0&&(n.line=r.line),r.conditionText!==void 0&&(n.expression=r.conditionText),r.expressionTrace!==void 0&&(n.expressionTrace=r.expressionTrace),n.line!==void 0||n.expression!==void 0||n.expressionTrace!==void 0?n:void 0}function Se(t){const e=[];for(const r of t.notes)e.push(r);for(const r of t.trace){const n=r.operations.join(","),s=`Rule #${r.ruleIndex} (${n})`;r.verdict==="ALLOW"?e.push(`${s} → ALLOW`):r.verdict==="DENY"?e.push(`${s} → deny`):r.verdict==="UNSUPPORTED"?e.push(`${s} → unsupported: ${r.message??""}`):e.push(`${s} → error: ${r.message??""}`)}return e.push(`Simulated: ${t.decision}`),e}lt({function:wn(["get","exists"]).describe("Cross-service Firestore function to mock"),path:Ft().describe('Firestore document path in collection/doc form, e.g. "users/alice"'),result:li([kr(Ir()),ui()]).describe("Document fields for get, boolean for exists")});const ec={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(ec).sort());const _h={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:[]},tc=["exists","existsAfter","get","getAfter"],Ah=["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"],xh={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"]},rc={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"]},Ih=["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"],kh=["get","hasAll","keys","matches","size","split"],Eh={get:["map"],hasAll:["set"],keys:["map"],matches:["string"],size:["list","map","string"],split:["string"]},nc={duration:["value"],firestore:["exists","get"],timestamp:["date","value"]},Oh=new Set(Ih),Ch=["request.auth.token","request.resource.metadata","resource.metadata"];function Th(t,e){if(e.length===1)return!0;if(t==="firebase.storage"){const r=e.join(".");return Oh.has(r)||Ch.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 Sn(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 Rh(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 ga(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 Nh=new Set(tc),Fh=Object.fromEntries(Object.entries(rc).map(([t,e])=>[t,new Set(e)])),Lh=Object.fromEntries(Object.entries(nc).map(([t,e])=>[t,new Set(e)]));function at(t,e){return t.some(r=>_e(r,e)!==null)?"unknown-ambient":null}function sc(t,e,r){const n=r.declarations?.get(t),s=new Map(n?.aliases),i=new Map(n?.receiverTypes);return t.parameters.forEach((a,o)=>{s.set(a,e[o]?.provenance??null),i.set(a,e[o]?.receiverType??null)}),{aliases:s,receiverTypes:i,functions:n?.functions??r.functions,service:r.service,stack:new Set([...r.stack,t.name]),declarations:r.declarations}}function rr(t,e){return{expression:t,provenance:_e(t,e),receiverType:he(t,e)}}function _e(t,e){if(t.type==="identifier")return t.name==="request"||t.name==="resource"?[t.name]:e.aliases.get(t.name)??null;if(t.type==="memberAccess"){const r=_e(t.object,e);return r==="unknown-ambient"?r:r?[...r,t.property]:null}if(t.type==="bracketAccess"){const r=_e(t.object,e);return!r||r==="unknown-ambient"?r:t.index.type==="literal"&&typeof t.index.value=="string"?[...r,t.index.value]:[...r,"*"]}if(t.type==="ternary"){const r=_e(t.consequent,e),n=_e(t.alternate,e);return!r&&!n?null:Array.isArray(r)&&Array.isArray(n)&&r.join(".")===n.join(".")?r:"unknown-ambient"}if(t.type==="functionCall"){const r=e.functions.get(t.name),n=t.args.map(i=>rr(i,e));if(!r&&Nh.has(t.name))return null;if(!r||e.stack.has(r.name))return n.some(({provenance:i})=>i!==null)?"unknown-ambient":null;const s=sc(r,n,e);for(const i of r.lets){const a=rr(i.value,s);s.aliases.set(i.name,a.provenance),s.receiverTypes.set(i.name,a.receiverType)}return _e(r.body,s)}if(t.type==="methodCall"&&t.object.type==="identifier"&&t.object.name==="firestore"&&(t.method==="get"||t.method==="exists"))return null;switch(t.type){case"literal":return null;case"methodCall":return at([t.object,...t.args],e);case"sliceAccess":return at([t.object,t.start,t.end],e);case"binaryOp":return at([t.left,t.right],e);case"unaryOp":return at([t.operand],e);case"inExpr":return at([t.element,t.collection],e);case"isExpr":return at([t.value],e);case"listLiteral":return at(t.elements,e);case"mapLiteral":return at(t.entries.flatMap(({key:r,value:n})=>[r,n]),e);case"pathLiteral":return at(t.segments.filter(r=>typeof r!="string"),e);default:return null}}function he(t,e){const r=Rh(e.service,_e(t,e));if(r)return r;switch(t.type){case"identifier":{const n=e.receiverTypes.get(t.name);return n||((e.service==="cloud.firestore"?Fh:Lh)[t.name]||t.name==="firestore"?"namespace":null)}case"literal":return t.value===null?"null":typeof t.value=="string"?"string":typeof t.value=="number"?"number":typeof t.value=="boolean"?"boolean":null;case"listLiteral":return"list";case"mapLiteral":return"map";case"pathLiteral":return"path";case"memberAccess":{const n=he(t.object,e);if(n==="mixed")return"mixed";if(t.property==="data"&&n==="document")return"map";if(t.object.type==="mapLiteral"){const s=t.object.entries.find(({key:i})=>i.type==="literal"&&i.value===t.property);return s?he(s.value,e):null}return null}case"bracketAccess":{const n=he(t.object,e);if(n==="mixed")return"mixed";if(t.object.type==="listLiteral"&&t.index.type==="literal"&&typeof t.index.value=="number"&&Number.isInteger(t.index.value)){const i=t.object.elements[t.index.value];return i?he(i,e):null}if(t.object.type==="mapLiteral"&&t.index.type==="literal"){const i=t.index.value,a=t.object.entries.find(({key:o})=>o.type==="literal"&&o.value===i);return a?he(a.value,e):null}if(n==="string")return"string";const s=_e(t.object,e);return e.service==="firebase.storage"&&Array.isArray(s)&&(s.join(".")==="request.resource.metadata"||s.join(".")==="resource.metadata")?"string":null}case"sliceAccess":{const n=he(t.object,e);return n==="mixed"?"mixed":n==="list"||n==="string"?n:null}case"methodCall":{const n=ga(t);if(t.object.type==="identifier"&&n)return n;if(t.method==="get"){const s=_e(t.object,e);if(e.service==="firebase.storage"&&Array.isArray(s)&&(s.join(".")==="request.resource.metadata"||s.join(".")==="resource.metadata"))return"string";const i=t.args[1];if(t.object.type==="mapLiteral"&&t.args[0]?.type==="literal"){const a=t.args[0].value,o=t.object.entries.find(({key:c})=>c.type==="literal"&&c.value===a);return o?he(o.value,e):i?he(i,e):null}return i&&he(i,e)?"mixed":null}return ga(t)}case"binaryOp":{const n=he(t.left,e),s=he(t.right,e);return t.op==="+"&&(n==="string"||s==="string")?"string":["==","!=","<","<=",">",">=","&&","||"].includes(t.op)?"boolean":["+","-","*","/","%"].includes(t.op)&&n==="number"&&s==="number"?"number":null}case"unaryOp":return t.op==="!"?"boolean":t.op==="-"&&he(t.operand,e)==="number"?"number":null;case"inExpr":case"isExpr":return"boolean";case"ternary":{const n=he(t.consequent,e),s=he(t.alternate,e);return!n&&!s?null:n===s?n:"mixed"}case"functionCall":{const n=e.functions.get(t.name);if(!n&&e.service==="cloud.firestore"){if(t.name==="get"||t.name==="getAfter")return"document";if(t.name==="exists")return"boolean"}if(!n||e.stack.has(n.name))return null;const s=sc(n,t.args.map(i=>rr(i,e)),e);for(const i of n.lets){const a=rr(i.value,s);s.aliases.set(i.name,a.provenance),s.receiverTypes.set(i.name,a.receiverType)}return he(n.body,s)}default:return null}}function jh(t){return t.match(/^\.\/stdlib\/(.+?)(?:\.rules)?$/)?.[1]??t}function Dh(t,e,r){const n=jh(e),s=ec[n];return s?s.includes(t)?null:`Function '${r}' from module '${e}' is not compatible with service '${t}'`:null}function Mh(t){throw new Error(`Unhandled Rules expression: ${JSON.stringify(t)}`)}const Ph=new Set(tc),$h=new Set(Ah),qh=Object.fromEntries(Object.entries(rc).map(([t,e])=>[t,new Set(e)])),Uh=new Set(kh),Bh=Object.fromEntries(Object.entries(nc).map(([t,e])=>[t,new Set(e)]));function _n(t,e){return t==="unknown-ambient"?"binding '<derived ambient value>'":t&&!Th(e,t)?`binding '${t.join(".")}'`:null}function zh(t,e,r,n,s){if(e!=="get"&&e!=="keys"&&e!=="values")return null;const i=_e(t,s);if(i==="unknown-ambient")return"binding '<derived ambient value>'";if(!i)return null;if(e==="get"){const a=r[0];if(a?.type==="literal"&&typeof a.value=="string")return _n([...i,a.value],n);if(!Sn(n,i))return`binding '${i.join(".")}.get(...)'`}return(e==="keys"||e==="values")&&!Sn(n,i)?`binding '${i.join(".")}.${e}()'`:null}function Vh(t,e,r,n){const s=_e(t,n),i=he(t,n);if(!i){if(s==="unknown-ambient")return"binding '<derived ambient receiver>'";let c=t;for(;c.type==="memberAccess"||c.type==="bracketAccess"||c.type==="methodCall"&&c.method==="get";)c=c.object;const u=he(c,n);return u==="map"||u==="list"||u==="document"?`method '.${e}()' has an unresolved projected receiver`:null}const o=(r==="cloud.firestore"?xh:Eh)[e];return o?.includes(i)?null:`method '.${e}()' requires ${o?.join("|")??"an accepted"} receiver, got ${i}`}function Wh(t,e,r,n){const s=_e(e,n);return s==="unknown-ambient"?"binding '<derived ambient value>'":s?t.type==="literal"&&typeof t.value=="string"?_n([...s,t.value],r):Sn(r,s)?null:`binding '<value> in ${s.join(".")}'`:null}function ya(t,e,r){const n=s=>{switch(s.type){case"memberAccess":{const i=_n(_e(s,r),e);return i||n(s.object)}case"functionCall":{const i=r.functions.get(s.name);if(!i&&e==="firebase.storage")return`function '${s.name}()'`;if(!i&&!Ph.has(s.name))return`function '${s.name}()'`;for(const a of s.args){const o=n(a);if(o)return o}if(i&&!r.stack.has(i.name)){const a=new Map,o=new Map;i.parameters.forEach((u,d)=>{const l=s.args[d];a.set(u,l?_e(l,r):null),o.set(u,l?he(l,r):null)});const c=ic(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"?qh:Bh)[s.object.name];if(u){if(!u.has(s.method))return`method '${s.object.name}.${s.method}()'`;for(const d of s.args){const l=n(d);if(l)return l}return null}return s.object.name==="firestore"?`method 'firestore.${s.method}()'`:`namespace '${s.object.name}'`}if(!(e==="cloud.firestore"?$h:Uh).has(s.method))return`method '.${s.method}()'`;const a=Vh(s.object,s.method,e,r);if(a)return a;const o=zh(s.object,s.method,s.args,e,r);return o||(n(s.object)??s.args.map(n).find(Boolean)??null)}case"binaryOp":return n(s.left)??n(s.right);case"unaryOp":return n(s.operand);case"bracketAccess":{const i=_e(s.object,r);if(i==="unknown-ambient")return"binding '<derived ambient value>[...]'";const a=s.index.type==="literal"&&typeof s.index.value=="string";if(i&&!a)return Sn(e,i)?n(s.object)??n(s.index):`binding '${i.join(".")}[...]'`;const o=_n(_e(s,r),e);return o||(n(s.object)??n(s.index))}case"sliceAccess":return n(s.object)??n(s.start)??n(s.end);case"ternary":return n(s.condition)??n(s.consequent)??n(s.alternate);case"inExpr":return Wh(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 Mh(s)}};return n(t)}function ic(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=ya(a.value,e,i);if(o)return o;n.set(a.name,_e(a.value,i)),s.set(a.name,he(a.value,i))}return ya(t.body,e,i)}function Hh(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 ic(t,e,{aliases:new Map(t.parameters.map((i,a)=>[i,a<n.length?n[a]?.provenance??null:null])),receiverTypes:new Map(t.parameters.map((i,a)=>[i,n[a]?he(n[a].expression,s)??n[a].receiverType??null:null])),functions:r,service:e,stack:new Set([t.name])})}function Gh(t){throw new Error(`Unhandled Rules expression: ${JSON.stringify(t)}`)}function Kh(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 Gh(t)}}function Zh(t,e){const r=Kh(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 Jh(t){throw new Error(`Unhandled Rules expression: ${JSON.stringify(t)}`)}function di(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:Jh(n)}};return r(t),e}function Qh(t){return{expression:t.expression,provenance:t.provenance,receiverType:!t.receiverType||t.receiverType==="mixed"?"unknown":t.receiverType}}function Yh(t,e){const r=[],n=new Map,s=t.service.name==="firebase.storage"?"firebase.storage":"cloud.firestore",i=(l,f=new Set)=>({aliases:new Map(l.aliases),receiverTypes:new Map(l.receiverTypes),functions:l.functions,service:s,stack:f,declarations:n}),a=(l,f,y)=>{if(y.has(l.name))return;const b=n.get(l);if(!b)return;const S=new Map(b.aliases),j=new Map(b.receiverTypes);l.parameters.forEach((L,k)=>{S.set(L,f[k]?.provenance??null),j.set(L,f[k]?.receiverType??null)});const T=i({aliases:S,receiverTypes:j,functions:b.functions},new Set([...y,l.name]));for(const L of l.lets){o(L.value,T);const k=rr(L.value,T);T.aliases.set(L.name,k.provenance),T.receiverTypes.set(L.name,k.receiverType)}o(l.body,T)},o=(l,f)=>{for(const y of di(l)){const b=y.args.map(j=>rr(j,f));y.name===e&&r.push({arguments:b.map(Qh)});const S=f.functions.get(y.name);S&&a(S,b,f.stack)}},c=new Map((t.functions??[]).map(l=>[l.name,l])),u=new Map(c);for(const l of t.service.functions??[])u.set(l.name,l);for(const l of t.functions??[])n.set(l,{aliases:new Map,receiverTypes:new Map,functions:c});for(const l of t.service.functions??[])n.set(l,{aliases:new Map,receiverTypes:new Map,functions:u});const d=(l,f)=>{const y=new Map(f.receiverTypes);for(const T of l.path.segments)T.type==="wildcard"&&y.set(T.name,"string"),T.type==="recursive"&&y.set(T.name,"path");const b=new Map(f.functions),S={aliases:f.aliases,receiverTypes:y,functions:b};for(const T of l.functions)b.set(T.name,T),n.set(T,S);const j=i(S);for(const{condition:T}of l.allows)o(T,j);l.children.forEach(T=>d(T,S))};return d(t.service.match,{aliases:new Map,receiverTypes:new Map,functions:u}),r}function Et(t){return di(t).map(({name:e})=>e)}function Xh(t,e){return[...t.values()].flatMap(n=>[...n.lets.map(({value:s})=>s),n.body]).flatMap(di).filter(({name:n})=>n===e).map(({args:n})=>n)}function Ur(t,e,r){const n=bl(t);return n?{success:!0,functions:n,bundled:r}:{success:!1,error:{code:"PARSE_FAILED",message:`Failed to parse module '${e}'`}}}function ba(t){return t.startsWith("./")||t.startsWith("../")}function Ts(t){return/^\.\/stdlib\/([A-Za-z0-9_-]+(?:\/[A-Za-z0-9_-]+)*)\.rules$/.exec(t)?.[1]??null}function ef(t,e,r,n=new Set){if(r?.modules&&Object.prototype.hasOwnProperty.call(r.modules,e))return Ur(r.modules[e],e,n.has(e));if(ba(e)&&r?.basePath){const a=`${r.basePath}/${e}${e.endsWith(".rules")?"":".rules"}`,o=t?.readRelative(r.basePath,e)??null;if(o!==null)return Ur(o,e,!1);if(!Ts(e))return{success:!1,error:{code:"UNKNOWN_MODULE",message:`Module '${e}' not found at ${a}`}}}const s=Ts(e);if(s){const a=t?.readStdlib(s)??null;return a===null?{success:!1,error:{code:"UNKNOWN_MODULE",message:`Module '${e}' not found`}}:Ur(a,e,!0)}if(ba(e))return{success:!1,error:{code:"UNKNOWN_MODULE",message:`Module '${e}' requires basePath for relative imports`}};const i=t?.readStdlib(e)??null;return i===null?{success:!1,error:{code:"UNKNOWN_MODULE",message:`Module '${e}' not found`}}:Ur(i,e,!0)}function tf(t,e,r,n=new Set){const s=en(e);if(!s.ok){const{line:I,column:q,message:Z}=s.error;return{success:!1,error:{code:"PARSE_FAILED",message:`Failed to parse source at line ${I}, col ${q}: ${Z}`}}}const i=s.ast;if(i.version!=="2+modules")return{success:!1,error:{code:"NOT_MODULE_SOURCE",message:`Version '${i.version}' is not a module source`}};if(i.service.name!=="cloud.firestore"&&i.service.name!=="firebase.storage")return{success:!1,error:{code:"UNSUPPORTED_SERVICE",message:`Module resolution does not support service '${i.service.name}'`}};if(i.imports.length===0)return i.version="2",{success:!0,data:{resolved:tn(i),modules:[],bundledModules:[],evidenceIds:[]}};const a=i.imports.find(I=>I.functions.length===0);if(a)return{success:!1,error:{code:"UNKNOWN_FUNCTION",message:`Import from '${a.module}' must request at least one function`}};const o=new Map,c=new Map,u=new Map,d=new Map,l=[],f=[],y=new Map;for(const I of i.imports){const q=ef(t,I.module,r,n);if(!q.success)return{success:!1,error:q.error};l.includes(I.module)||l.push(I.module),q.bundled&&!f.includes(I.module)&&f.push(I.module);const Z=new Set,pe=q.functions.find(J=>Z.has(J.name)?!0:(Z.add(J.name),!1));if(pe)return{success:!1,error:{code:"DUPLICATE_FUNCTION",message:`Module '${I.module}' defines duplicate function '${pe.name}'`}};const Q=q.functions.find(J=>Hr.has(J.name));if(Q)return{success:!1,error:{code:"DUPLICATE_FUNCTION",message:`Function '${Q.name}' from module '${I.module}' conflicts with a Rules builtin`}};const ve=new Set;for(const J of q.functions)J.exported||ve.add(J.name);y.set(I.module,ve);const Vn=Zh(q.functions,I.module),Ci=new Set;for(const J of Vn){if(Ci.has(J.name))return{success:!1,error:{code:"DUPLICATE_FUNCTION",message:`Module '${I.module}' defines conflicting function name '${J.name}'`}};Ci.add(J.name)}const pu=new Set(Vn.filter(J=>J.exported).map(J=>J.name));for(const J of Vn){const kt=d.get(J.name);if(kt&&kt!==I.module)return{success:!1,error:{code:"DUPLICATE_FUNCTION",message:`Function '${J.name}' from module '${I.module}' conflicts with module '${kt}'`}};if(d.set(J.name,I.module),c.set(J.name,J),J.exported){if(o.has(J.name)&&u.get(J.name)!==I.module)return{success:!1,error:{code:"DUPLICATE_FUNCTION",message:`Function '${J.name}' exported by both '${u.get(J.name)}' and '${I.module}'`}};o.set(J.name,J),u.set(J.name,I.module)}}for(const J of I.functions){if(!pu.has(J))return{success:!1,error:{code:"UNKNOWN_FUNCTION",message:y.get(I.module)?.has(J)?`Function '${J}' in module '${I.module}' is not exported`:`Function '${J}' not found in module '${I.module}'`}};if(i.service.name==="cloud.firestore"||i.service.name==="firebase.storage"){const kt=q.bundled?Dh(i.service.name,I.module,J):null;if(kt)return{success:!1,error:{code:"INCOMPATIBLE_FUNCTION",message:kt}}}}}const b=new Set(i.imports.flatMap(I=>I.functions)),S=[],j=new Set,T=[],L={cycle:null};function k(I){if(L.cycle)return;const q=T.indexOf(I);if(q>=0){L.cycle=[...T.slice(q),I];return}if(j.has(I))return;const Z=c.get(I);if(!Z)return;T.push(I);const pe=Et(Z.body);for(const Q of Z.lets)pe.push(...Et(Q.value));for(const Q of pe)c.has(Q)&&!Hr.has(Q)&&k(Q);T.pop(),!L.cycle&&(j.add(I),S.push({...Z,exported:!1}))}for(const I of i.imports)for(const q of I.functions)k(q);if(L.cycle)return{success:!1,error:{code:"CIRCULAR_DEPENDENCY",message:`Recursive module function dependency: ${L.cycle.join(" -> ")}`}};for(const I of S){const q=d.get(I.name),pe=[...I.lets.flatMap(({value:Q})=>Et(Q)),...Et(I.body)].find(Q=>{const ve=d.get(Q);return ve&&ve!==q&&!b.has(Q)});if(pe)return{success:!1,error:{code:"UNKNOWN_FUNCTION",message:`Function '${I.name}' in module '${q}' cannot call '${pe}' from another module`}}}const $=new Set(S.map(I=>I.name)),V=new Map((i.functions??[]).map(I=>[I.name,I])),w=new Set((i.service.functions??[]).map(I=>I.name)),x=(I,q)=>I.flatMap(Et).find(Z=>o.has(Z)&&!$.has(Z)&&!q.has(Z))??null,_=I=>I.flatMap(q=>[...q.lets.map(({value:Z})=>Z),q.body]),v=new Set(V.keys());let O=x(_(i.functions??[]),v);const A=new Set([...v,...w]);O??=x(_(i.service.functions??[]),A);const h=(I,q)=>{const Z=new Set([...q,...I.functions.map(Q=>Q.name)]),pe=[..._(I.functions),...I.allows.map(({condition:Q})=>Q)];return x(pe,Z)??I.children.map(Q=>h(Q,Z)).find(Boolean)??null};if(O??=h(i.service.match,A),O)return{success:!1,error:{code:"UNKNOWN_FUNCTION",message:`Source calls function '${O}' from module '${u.get(O)}' without importing it`}};const p=(I,q)=>{if(q.has(I.name))return!1;const Z=new Set([...q,I.name]);return[...I.lets.flatMap(({value:Q})=>Et(Q)),...Et(I.body)].some(Q=>{const ve=V.get(Q);return ve?p(ve,Z):$.has(Q)||w.has(Q)})},g=[...V.values()].find(I=>p(I,new Set));if(g)return{success:!1,error:{code:"INCOMPATIBLE_FUNCTION",message:`Global function '${g.name}' cannot call a service-scoped function`}};if(i.service.name==="firebase.storage"||i.service.name==="cloud.firestore"){const I=new Map(S.map(q=>[q.name,q]));for(const q of S){const Z=[...Yh(i,q.name),...Xh(I,q.name).map(Q=>({arguments:Q.map(ve=>({expression:ve,provenance:null,receiverType:"unknown"}))}))],pe=Z.length>0?Z:[{arguments:[]}];for(const{arguments:Q}of pe){const ve=Hh(q,i.service.name,c,Q);if(ve)return{success:!1,error:{code:"INCOMPATIBLE_FUNCTION",message:`Function '${q.name}' requires unsupported ${ve} for service '${i.service.name}'`}}}}}const m=new Set([...(i.functions??[]).map(I=>I.name),...(i.service.functions??[]).map(I=>I.name)]),D=I=>{I.functions.forEach(q=>m.add(q.name)),I.children.forEach(D)};D(i.service.match);const E=[...m].find(I=>Hr.has(I));if(E)return{success:!1,error:{code:"DUPLICATE_FUNCTION",message:`Source function '${E}' conflicts with a Rules builtin`}};for(const I of S)if(m.has(I.name))return{success:!1,error:{code:"DUPLICATE_FUNCTION",message:`Imported function '${I.name}' conflicts with a function defined in the source`}};i.service.functions=[...S,...i.service.functions??[]],i.version="2",i.imports=[];const C=new Set,N=i.service.name==="firebase.storage"?"storage-rules#":"firestore-rules#";for(const I of f){const q=Ts(I)??I,Z=_h[q]??[];for(const pe of Z)pe.startsWith(N)&&C.add(pe)}return{success:!0,data:{resolved:tn(i),modules:l,bundledModules:f,evidenceIds:[...C].sort()}}}const rf={atomic:`// @pyric-services cloud.firestore
486
+ */var Xi;function ed(){return Xi||(Xi=1,(function(t){(function(){var e="input is invalid type",r=typeof window=="object",n=r?window:{};n.JS_SHA256_NO_WINDOW&&(r=!1);var s=!r&&typeof self=="object",i=!n.JS_SHA256_NO_NODE_JS&&typeof process=="object"&&process.versions&&process.versions.node&&process.type!="renderer";i?n=oo:s&&(n=self);var a=!n.JS_SHA256_NO_COMMON_JS&&!0&&t.exports,o=!n.JS_SHA256_NO_ARRAY_BUFFER&&typeof ArrayBuffer<"u",c="0123456789abcdef".split(""),u=[-2147483648,8388608,32768,128],d=[24,16,8,0],l=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],f=["hex","array","digest","arrayBuffer"],y=[];(n.JS_SHA256_NO_NODE_JS||!Array.isArray)&&(Array.isArray=function(w){return Object.prototype.toString.call(w)==="[object Array]"}),o&&(n.JS_SHA256_NO_ARRAY_BUFFER_IS_VIEW||!ArrayBuffer.isView)&&(ArrayBuffer.isView=function(w){return typeof w=="object"&&w.buffer&&w.buffer.constructor===ArrayBuffer});var b=function(w,x){return function(_){return new k(x,!0).update(_)[w]()}},S=function(w){var x=b("hex",w);i&&(x=j(x,w)),x.create=function(){return new k(w)},x.update=function(O){return x.create().update(O)};for(var _=0;_<f.length;++_){var v=f[_];x[v]=b(v,w)}return x},j=function(w,x){var _=nn,v=nn.Buffer,O=x?"sha224":"sha256",A;v.from&&!n.JS_SHA256_NO_BUFFER_FROM?A=v.from:A=function(p){return new v(p)};var h=function(p){if(typeof p=="string")return _.createHash(O).update(p,"utf8").digest("hex");if(p==null)throw new Error(e);return p.constructor===ArrayBuffer&&(p=new Uint8Array(p)),Array.isArray(p)||ArrayBuffer.isView(p)||p.constructor===v?_.createHash(O).update(A(p)).digest("hex"):w(p)};return h},T=function(w,x){return function(_,v){return new $(_,x,!0).update(v)[w]()}},L=function(w){var x=T("hex",w);x.create=function(O){return new $(O,w)},x.update=function(O,A){return x.create(O).update(A)};for(var _=0;_<f.length;++_){var v=f[_];x[v]=T(v,w)}return x};function k(w,x){x?(y[0]=y[16]=y[1]=y[2]=y[3]=y[4]=y[5]=y[6]=y[7]=y[8]=y[9]=y[10]=y[11]=y[12]=y[13]=y[14]=y[15]=0,this.blocks=y):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],w?(this.h0=3238371032,this.h1=914150663,this.h2=812702999,this.h3=4144912697,this.h4=4290775857,this.h5=1750603025,this.h6=1694076839,this.h7=3204075428):(this.h0=1779033703,this.h1=3144134277,this.h2=1013904242,this.h3=2773480762,this.h4=1359893119,this.h5=2600822924,this.h6=528734635,this.h7=1541459225),this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0,this.is224=w}k.prototype.update=function(w){if(!this.finalized){var x,_=typeof w;if(_!=="string"){if(_==="object"){if(w===null)throw new Error(e);if(o&&w.constructor===ArrayBuffer)w=new Uint8Array(w);else if(!Array.isArray(w)&&(!o||!ArrayBuffer.isView(w)))throw new Error(e)}else throw new Error(e);x=!0}for(var v,O=0,A,h=w.length,p=this.blocks;O<h;){if(this.hashed&&(this.hashed=!1,p[0]=this.block,this.block=p[16]=p[1]=p[2]=p[3]=p[4]=p[5]=p[6]=p[7]=p[8]=p[9]=p[10]=p[11]=p[12]=p[13]=p[14]=p[15]=0),x)for(A=this.start;O<h&&A<64;++O)p[A>>>2]|=w[O]<<d[A++&3];else for(A=this.start;O<h&&A<64;++O)v=w.charCodeAt(O),v<128?p[A>>>2]|=v<<d[A++&3]:v<2048?(p[A>>>2]|=(192|v>>>6)<<d[A++&3],p[A>>>2]|=(128|v&63)<<d[A++&3]):v<55296||v>=57344?(p[A>>>2]|=(224|v>>>12)<<d[A++&3],p[A>>>2]|=(128|v>>>6&63)<<d[A++&3],p[A>>>2]|=(128|v&63)<<d[A++&3]):(v=65536+((v&1023)<<10|w.charCodeAt(++O)&1023),p[A>>>2]|=(240|v>>>18)<<d[A++&3],p[A>>>2]|=(128|v>>>12&63)<<d[A++&3],p[A>>>2]|=(128|v>>>6&63)<<d[A++&3],p[A>>>2]|=(128|v&63)<<d[A++&3]);this.lastByteIndex=A,this.bytes+=A-this.start,A>=64?(this.block=p[16],this.start=A-64,this.hash(),this.hashed=!0):this.start=A}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}},k.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var w=this.blocks,x=this.lastByteIndex;w[16]=this.block,w[x>>>2]|=u[x&3],this.block=w[16],x>=56&&(this.hashed||this.hash(),w[0]=this.block,w[16]=w[1]=w[2]=w[3]=w[4]=w[5]=w[6]=w[7]=w[8]=w[9]=w[10]=w[11]=w[12]=w[13]=w[14]=w[15]=0),w[14]=this.hBytes<<3|this.bytes>>>29,w[15]=this.bytes<<3,this.hash()}},k.prototype.hash=function(){var w=this.h0,x=this.h1,_=this.h2,v=this.h3,O=this.h4,A=this.h5,h=this.h6,p=this.h7,g=this.blocks,m,D,E,C,N,I,q,Z,pe,Q,ve;for(m=16;m<64;++m)N=g[m-15],D=(N>>>7|N<<25)^(N>>>18|N<<14)^N>>>3,N=g[m-2],E=(N>>>17|N<<15)^(N>>>19|N<<13)^N>>>10,g[m]=g[m-16]+D+g[m-7]+E<<0;for(ve=x&_,m=0;m<64;m+=4)this.first?(this.is224?(Z=300032,N=g[0]-1413257819,p=N-150054599<<0,v=N+24177077<<0):(Z=704751109,N=g[0]-210244248,p=N-1521486534<<0,v=N+143694565<<0),this.first=!1):(D=(w>>>2|w<<30)^(w>>>13|w<<19)^(w>>>22|w<<10),E=(O>>>6|O<<26)^(O>>>11|O<<21)^(O>>>25|O<<7),Z=w&x,C=Z^w&_^ve,q=O&A^~O&h,N=p+E+q+l[m]+g[m],I=D+C,p=v+N<<0,v=N+I<<0),D=(v>>>2|v<<30)^(v>>>13|v<<19)^(v>>>22|v<<10),E=(p>>>6|p<<26)^(p>>>11|p<<21)^(p>>>25|p<<7),pe=v&w,C=pe^v&x^Z,q=p&O^~p&A,N=h+E+q+l[m+1]+g[m+1],I=D+C,h=_+N<<0,_=N+I<<0,D=(_>>>2|_<<30)^(_>>>13|_<<19)^(_>>>22|_<<10),E=(h>>>6|h<<26)^(h>>>11|h<<21)^(h>>>25|h<<7),Q=_&v,C=Q^_&w^pe,q=h&p^~h&O,N=A+E+q+l[m+2]+g[m+2],I=D+C,A=x+N<<0,x=N+I<<0,D=(x>>>2|x<<30)^(x>>>13|x<<19)^(x>>>22|x<<10),E=(A>>>6|A<<26)^(A>>>11|A<<21)^(A>>>25|A<<7),ve=x&_,C=ve^x&v^Q,q=A&h^~A&p,N=O+E+q+l[m+3]+g[m+3],I=D+C,O=w+N<<0,w=N+I<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+w<<0,this.h1=this.h1+x<<0,this.h2=this.h2+_<<0,this.h3=this.h3+v<<0,this.h4=this.h4+O<<0,this.h5=this.h5+A<<0,this.h6=this.h6+h<<0,this.h7=this.h7+p<<0},k.prototype.hex=function(){this.finalize();var w=this.h0,x=this.h1,_=this.h2,v=this.h3,O=this.h4,A=this.h5,h=this.h6,p=this.h7,g=c[w>>>28&15]+c[w>>>24&15]+c[w>>>20&15]+c[w>>>16&15]+c[w>>>12&15]+c[w>>>8&15]+c[w>>>4&15]+c[w&15]+c[x>>>28&15]+c[x>>>24&15]+c[x>>>20&15]+c[x>>>16&15]+c[x>>>12&15]+c[x>>>8&15]+c[x>>>4&15]+c[x&15]+c[_>>>28&15]+c[_>>>24&15]+c[_>>>20&15]+c[_>>>16&15]+c[_>>>12&15]+c[_>>>8&15]+c[_>>>4&15]+c[_&15]+c[v>>>28&15]+c[v>>>24&15]+c[v>>>20&15]+c[v>>>16&15]+c[v>>>12&15]+c[v>>>8&15]+c[v>>>4&15]+c[v&15]+c[O>>>28&15]+c[O>>>24&15]+c[O>>>20&15]+c[O>>>16&15]+c[O>>>12&15]+c[O>>>8&15]+c[O>>>4&15]+c[O&15]+c[A>>>28&15]+c[A>>>24&15]+c[A>>>20&15]+c[A>>>16&15]+c[A>>>12&15]+c[A>>>8&15]+c[A>>>4&15]+c[A&15]+c[h>>>28&15]+c[h>>>24&15]+c[h>>>20&15]+c[h>>>16&15]+c[h>>>12&15]+c[h>>>8&15]+c[h>>>4&15]+c[h&15];return this.is224||(g+=c[p>>>28&15]+c[p>>>24&15]+c[p>>>20&15]+c[p>>>16&15]+c[p>>>12&15]+c[p>>>8&15]+c[p>>>4&15]+c[p&15]),g},k.prototype.toString=k.prototype.hex,k.prototype.digest=function(){this.finalize();var w=this.h0,x=this.h1,_=this.h2,v=this.h3,O=this.h4,A=this.h5,h=this.h6,p=this.h7,g=[w>>>24&255,w>>>16&255,w>>>8&255,w&255,x>>>24&255,x>>>16&255,x>>>8&255,x&255,_>>>24&255,_>>>16&255,_>>>8&255,_&255,v>>>24&255,v>>>16&255,v>>>8&255,v&255,O>>>24&255,O>>>16&255,O>>>8&255,O&255,A>>>24&255,A>>>16&255,A>>>8&255,A&255,h>>>24&255,h>>>16&255,h>>>8&255,h&255];return this.is224||g.push(p>>>24&255,p>>>16&255,p>>>8&255,p&255),g},k.prototype.array=k.prototype.digest,k.prototype.arrayBuffer=function(){this.finalize();var w=new ArrayBuffer(this.is224?28:32),x=new DataView(w);return x.setUint32(0,this.h0),x.setUint32(4,this.h1),x.setUint32(8,this.h2),x.setUint32(12,this.h3),x.setUint32(16,this.h4),x.setUint32(20,this.h5),x.setUint32(24,this.h6),this.is224||x.setUint32(28,this.h7),w};function $(w,x,_){var v,O=typeof w;if(O==="string"){var A=[],h=w.length,p=0,g;for(v=0;v<h;++v)g=w.charCodeAt(v),g<128?A[p++]=g:g<2048?(A[p++]=192|g>>>6,A[p++]=128|g&63):g<55296||g>=57344?(A[p++]=224|g>>>12,A[p++]=128|g>>>6&63,A[p++]=128|g&63):(g=65536+((g&1023)<<10|w.charCodeAt(++v)&1023),A[p++]=240|g>>>18,A[p++]=128|g>>>12&63,A[p++]=128|g>>>6&63,A[p++]=128|g&63);w=A}else if(O==="object"){if(w===null)throw new Error(e);if(o&&w.constructor===ArrayBuffer)w=new Uint8Array(w);else if(!Array.isArray(w)&&(!o||!ArrayBuffer.isView(w)))throw new Error(e)}else throw new Error(e);w.length>64&&(w=new k(x,!0).update(w).array());var m=[],D=[];for(v=0;v<64;++v){var E=w[v]||0;m[v]=92^E,D[v]=54^E}k.call(this,x,_),this.update(D),this.oKeyPad=m,this.inner=!0,this.sharedMemory=_}$.prototype=new k,$.prototype.finalize=function(){if(k.prototype.finalize.call(this),this.inner){this.inner=!1;var w=this.array();k.call(this,this.is224,this.sharedMemory),this.update(this.oKeyPad),this.update(w),k.prototype.finalize.call(this)}};var V=S();V.sha256=V,V.sha224=S(!0),V.sha256.hmac=L(),V.sha224.hmac=L(!0),a?t.exports=V:(n.sha256=V.sha256,n.sha224=V.sha224)})()})(Jn)),Jn.exports}var td=ed();function rd(t){if(t instanceof Be)return t;if(typeof t=="string")return Be.fromUtf8(t);throw new G(`hashing.* requires Bytes or String, got ${typeof t}`)}function nd(t,e){const r=rd(e[0]);switch(t){case"md5":return new Be(new Uint8Array(Xl.md5.arrayBuffer(r.data)));case"sha256":return new Be(new Uint8Array(td.sha256.arrayBuffer(r.data)));case"crc32":{const n=id(r.data);return new Be(ea(n))}case"crc32c":{const n=od(r.data);return new Be(ea(n))}}throw new Je(`Unknown hashing method '${t}'`)}function ea(t){return new Uint8Array([t&255,t>>>8&255,t>>>16&255,t>>>24&255])}const sd=(()=>{const t=new Uint32Array(256);for(let e=0;e<256;e++){let r=e;for(let n=0;n<8;n++)r=r&1?3988292384^r>>>1:r>>>1;t[e]=r>>>0}return t})();function id(t){let e=4294967295;for(let r=0;r<t.length;r++)e=sd[(e^t[r])&255]^e>>>8;return(e^4294967295)>>>0}const ad=(()=>{const t=new Uint32Array(256);for(let e=0;e<256;e++){let r=e;for(let n=0;n<8;n++)r=r&1?2197175160^r>>>1:r>>>1;t[e]=r>>>0}return t})();function od(t){let e=4294967295;for(let r=0;r<t.length;r++)e=ad[(e^t[r])&255]^e>>>8;return(e^4294967295)>>>0}function cd(t){if(typeof t=="number")return Math.trunc(t);if(t instanceof oe)return Math.trunc(t.value);if(typeof t=="boolean")return t?1:0;if(typeof t=="string"){if(/^[+-]?\d+$/.test(t.trim()))return parseInt(t.trim(),10);throw new G(`int() cannot convert string '${t}' to an integer`)}throw new G(`int() cannot convert ${typeof t} to an integer`)}function ud(t){if(t instanceof oe)return t;if(typeof t=="number")return new oe(t);if(typeof t=="string"){const e=t.trim();if(/^[+-]?(\d+\.?\d*|\.\d+)$/.test(e))return new oe(parseFloat(e));throw new G(`float() cannot convert string '${t}' to a float`)}throw new G(`float() cannot convert ${typeof t} to a float`)}function ld(t){if(typeof t=="boolean")return t;if(typeof t=="string"){if(t==="true")return!0;if(t==="false")return!1;throw new G(`bool() cannot convert string '${t}' to a boolean`)}throw new G(`bool() cannot convert ${typeof t} to a boolean`)}function dd(t,e,r,n){switch(t){case"get":{const a=String(W(e[0],r,n));return Ji(a,r)}case"exists":{const a=String(W(e[0],r,n));return Qi(a,r)}case"getAfter":{const a=W(e[0],r,n),o=String(a);if(o===r.afterStatePath.toString()){if(r.afterState===null)throw new G(`getAfter() of non-existent document '${o}' (guard with existsAfter() first)`);return Ss(br(o),r.afterState)}const c=br(o);if(r.batchProjection?.has(c)){const u=r.batchProjection.get(c);if(u===null)throw new G(`getAfter() of non-existent document '${o}' (guard with existsAfter() first)`);return Ss(c,u)}return Ji(o,r)}case"existsAfter":{const a=W(e[0],r,n),o=String(a);if(o===r.afterStatePath.toString())return r.existsAfter;const c=br(o);return r.batchProjection?.has(c)?r.batchProjection.get(c)!==null:Qi(o,r)}case"debug":return W(e[0],r,n);case"string":return String(W(e[0],r,n));case"int":return cd(W(e[0],r,n));case"float":return ud(W(e[0],r,n));case"bool":return ld(W(e[0],r,n));case"path":{const a=W(e[0],r,n);if(typeof a=="string")return Xe.fromString(a);throw new G(`path() requires a string argument, got ${typeof a}`)}}const s=r.functions.get(t);if(!s)throw new Je(`Unknown function: ${t}`);const i={...n};for(let a=0;a<s.parameters.length;a++)i[s.parameters[a]]=W(e[a],r,n);r.trace?.enterFrame(t);try{for(const a of s.lets){const o=r.trace?r.trace.entries.length:-1;i[a.name]=W(a.value,r,i),o>=0&&r.trace?.markEntryAsLetBinding(o,a.name)}return W(s.body,r,i)}finally{r.trace?.exitFrame()}}function hd(t,e,r,n,s){if(t.type==="identifier"){const o=t.name;if(ta(o)&&!(o in s)&&!(o in n.pathVariables)){const c=r.map(u=>W(u,n,s));return pd(o,e,c)}if(!ta(o)&&!(o in s)&&!(o in n.pathVariables)&&!Sd(o))throw new Je(`Unknown namespace or method '${o}.${e}()'`)}const i=W(t,n,s),a=r.map(o=>W(o,n,s));if(i instanceof te){const o=i.callMethod(e,a);if(o===ue)throw new Je(`Unknown method '${e}' on ${i.typeName}`);return o}if(e==="diff"&&typeof i=="object"&&i!==null&&!Array.isArray(i)){const o=a[0];if(typeof o=="object"&&o!==null)return new yr(o,i);throw new G("diff() requires a map argument")}if(typeof i=="function")return i(...a);if(i instanceof fe)switch(e){case"hasOnly":return i.hasOnly(a[0]);case"hasAll":return i.hasAll(a[0]);case"hasAny":return i.hasAny(a[0]);case"size":return i.size();case"difference":case"union":case"intersection":{const o=a[0];if(!(o instanceof fe))throw new G(`Unsupported operation: set.${e} requires a Set argument`);return i[e](o)}}if(i instanceof yr)switch(e){case"addedKeys":return i.addedKeys();case"removedKeys":return i.removedKeys();case"changedKeys":return i.changedKeys();case"affectedKeys":return i.affectedKeys();case"unchangedKeys":return i.unchangedKeys()}if(typeof i=="object"&&i!==null&&!Array.isArray(i)){const o=i;switch(e){case"keys":return Object.keys(o);case"values":return Object.values(o);case"size":return Object.keys(o).length;case"hasAll":return a[0].every(c=>Object.hasOwn(o,c));case"hasAny":return a[0].some(c=>Object.hasOwn(o,c));case"hasOnly":return Object.keys(o).every(c=>a[0].includes(c));case"diff":{const c=a[0];return new yr(c,o)}case"get":{const c=a[0],u=a[1];if(Array.isArray(c)){let l=o;for(const f of c){if(l==null||typeof l!="object"||Array.isArray(l)||l instanceof te)return u;const y=String(f);if(!Object.hasOwn(l,y))return u;l=l[y]}return l}const d=String(c);return Object.hasOwn(o,d)?o[d]:u}}}if(Array.isArray(i))switch(e){case"size":return i.length;case"hasAll":return a[0].every(o=>i.some(c=>ye(c,o)));case"hasAny":return a[0].some(o=>i.some(c=>ye(c,o)));case"hasOnly":{const o=a[0];return i.every(c=>o.some(u=>ye(u,c)))}case"join":return i.join(String(a[0]??","));case"concat":{const o=a[0];if(!Array.isArray(o))throw new G(`List.concat requires a list argument, got ${typeof o}`);return[...i,...o]}case"removeAll":{const o=a[0];if(!Array.isArray(o))throw new G(`List.removeAll requires a list argument, got ${typeof o}`);return i.filter(c=>!o.some(u=>ye(c,u)))}case"toSet":return new fe(i);case"difference":case"union":case"intersection":throw new G(`Function not found on List receiver: ${e}`)}if(typeof i=="string")switch(e){case"size":return i.length;case"lower":return i.toLowerCase();case"upper":return i.toUpperCase();case"trim":return i.trim();case"split":return i.split(Qn(String(a[0]),"g"));case"matches":return Qn(`^(?:${String(a[0])})$`).test(i);case"replace":return i.replace(Qn(String(a[0]),"g"),String(a[1]));case"toUtf8":return Be.fromUtf8(i)}throw new Je(`Unknown method '${e}' on ${typeof i}`)}function Qn(t,e=""){try{return new RegExp(t,e)}catch(r){throw new G(`Invalid regex '${t}': ${r.message}`)}}const fd=new Set(["math","timestamp","duration","latlng","hashing"]);function ta(t){return fd.has(t)}function pd(t,e,r){const n=t==="hashing"?r:r.map(md);switch(t){case"math":return yd(e,n);case"timestamp":return bd(e,n);case"duration":return vd(e,n);case"latlng":return gd(e,n);case"hashing":return nd(e,r)}throw new Je(`Unknown namespace '${t}'`)}function md(t){return t instanceof oe?t.value:t}function gd(t,e){switch(t){case"value":{const[r,n]=e;return new rt(r,n)}}throw new Je(`Unknown latlng method '${t}'`)}function yd(t,e){switch(t){case"abs":return Math.abs(e[0]);case"ceil":return Math.ceil(e[0]);case"floor":return Math.floor(e[0]);case"round":return Math.round(e[0]);case"sqrt":return Math.sqrt(e[0]);case"pow":return Math.pow(e[0],e[1]);case"isInfinite":{const r=e[0];return Number.isFinite(r)===!1&&Number.isNaN(r)===!1}case"isNaN":return Number.isNaN(e[0])}throw new Je(`Unknown math method '${t}'`)}function bd(t,e){switch(t){case"date":{const[r,n,s]=e;return xe.fromYMD(r,n,s)}case"value":return xe.fromMillis(e[0])}throw new Je(`Unknown timestamp method '${t}'`)}function vd(t,e){switch(t){case"value":try{return we.fromValue(e[0],e[1])}catch(r){throw new G(r.message)}case"time":{const[r,n,s,i]=e;return we.fromTime(r,n,s,i)}case"abs":{const r=e[0];if(!(r instanceof we))throw new G(`duration.abs() requires a Duration argument, got ${typeof r}`);return we.abs(r)}}throw new Je(`Unknown duration method '${t}'`)}function W(t,e,r={}){return e.trace?e.trace.capture(t,()=>ra(t,e,r)):ra(t,e,r)}function ra(t,e,r){switch(t.type){case"literal":return typeof t.value=="number"&&t.raw.includes(".")?new oe(t.value):t.value;case"identifier":return wd(t.name,e,r);case"binaryOp":return _d(t.op,t.left,t.right,e,r);case"unaryOp":{if(t.op==="!")return!W(t.operand,e,r);if(t.op==="-"){const n=W(t.operand,e,r);return n instanceof oe?new oe(-n.value):-n}throw new G(`Unknown unary op: ${t.op}`,t)}case"ternary":{const n=pr(W(t.condition,e,r),t.condition);return W(n?t.consequent:t.alternate,e,r)}case"memberAccess":{const n=W(t.object,e,r);if(n==null)throw new G(`Property '${t.property}' accessed on ${n===null?"null":"undefined"} value`,t);if(n instanceof te)return n.field(t.property);if(n instanceof yr)switch(t.property){case"addedKeys":return()=>n.addedKeys();case"removedKeys":return()=>n.removedKeys();case"changedKeys":return()=>n.changedKeys();case"affectedKeys":return()=>n.affectedKeys();case"unchangedKeys":return()=>n.unchangedKeys()}if(n instanceof fe)switch(t.property){case"size":return()=>n.size()}if(Object.hasOwn(n,t.property))return n[t.property];throw new G(`No field '${t.property}' on map (use 'in' or .get() to read a possibly-absent field)`,t)}case"bracketAccess":{const n=W(t.object,e,r),s=W(t.index,e,r);if(n==null)throw new G(`Index access on ${n===null?"null":"undefined"} value`,t);if(n instanceof te)return n.field(String(s));const i=String(s);return Object.hasOwn(n,i)?n[i]:null}case"sliceAccess":{const n=W(t.object,e,r),s=W(t.start,e,r),i=W(t.end,e,r);if(n==null)return null;if(typeof s!="number"||!Number.isInteger(s))throw new G(`Slice start must be an integer, got ${typeof s}`);if(typeof i!="number"||!Number.isInteger(i))throw new G(`Slice end must be an integer, got ${typeof i}`);if(s<0||i<0)throw new G(`Slice indices must be non-negative, got [${s}:${i}]`);if(typeof n=="string"||Array.isArray(n)){if(i>n.length)throw new G(`Slice end ${i} exceeds length ${n.length}`);return n.slice(s,i)}throw new G(`Slice not supported on ${typeof n}`)}case"inExpr":{const n=W(t.element,e,r),s=W(t.collection,e,r);return s==null?!1:Array.isArray(s)?s.some(i=>ye(i,n)):typeof s=="object"?Object.hasOwn(s,String(n)):!1}case"isExpr":{const n=W(t.value,e,r);switch(t.typeName){case"string":return typeof n=="string";case"int":return n instanceof te?!1:typeof n=="number";case"float":return n instanceof oe;case"number":return n instanceof oe?!0:n instanceof te?!1:typeof n=="number";case"bool":return typeof n=="boolean";case"null":return n===null;case"list":return Array.isArray(n);case"map":return n instanceof te||n instanceof yr||n instanceof fe?!1:typeof n=="object"&&n!==null&&!Array.isArray(n);default:return n instanceof te?n.typeName===t.typeName:!1}}case"listLiteral":return t.elements.map(n=>W(n,e,r));case"mapLiteral":{const n={};for(const s of t.entries){const i=String(W(s.key,e,r));n[i]=W(s.value,e,r)}return n}case"functionCall":return dd(t.name,t.args,e,r);case"methodCall":return hd(t.object,t.method,t.args,e,r);case"pathLiteral":{const n=[];for(const s of t.segments)typeof s=="string"?n.push(s):n.push(String(W(s,e,r)));return new Xe(n)}default:throw new G(`Unknown expression type: ${t.type}`,t)}}function wd(t,e,r){if(t in r)return r[t];if(t in e.pathVariables)return e.pathVariables[t];switch(t){case"request":return e.request;case"resource":if(e.resource===null)throw new G("Null value error.");return e.resource;case"true":return!0;case"false":return!1;case"null":return null}throw new G(`Undefined variable '${t}'`)}function Sd(t){return t==="request"||t==="resource"||t==="true"||t==="false"||t==="null"}function _d(t,e,r,n,s){if(t==="&&"){let o,c;try{o=pr(W(e,n,s),e)}catch(l){c=l}if(c===void 0&&o===!1)return n.trace?.skip(r),!1;let u,d;try{u=pr(W(r,n,s),r)}catch(l){d=l}if(d===void 0&&u===!1)return!1;if(c!==void 0)throw c;if(d!==void 0)throw d;return u}if(t==="||"){let o,c;try{o=pr(W(e,n,s),e)}catch(l){c=l}if(c===void 0&&o===!0)return n.trace?.skip(r),!0;let u,d;try{u=pr(W(r,n,s),r)}catch(l){d=l}if(d===void 0&&u===!0)return!0;if(c!==void 0)throw c;if(d!==void 0)throw d;return u}const i=W(e,n,s),a=W(r,n,s);if(t!=="=="&&t!=="!="){if(i instanceof te){const o=i.binaryOp(t,a);if(o!==ue)return o}if(typeof i=="number"&&a instanceof oe){const o=new oe(i).binaryOp(t,a);if(o!==ue)return o}if(a instanceof te&&(t==="+"||t==="*")){const o=a.binaryOp(t,i);if(o!==ue)return o}if((t!=="+"||typeof i!="string"&&typeof a!="string")&&(i instanceof te||a instanceof te)){const o=i instanceof te?i.typeName:typeof i,c=a instanceof te?a.typeName:typeof a;throw new G(`Operator '${t}' is not defined between ${o} and ${c}`)}}if((t==="<"||t===">"||t==="<="||t===">=")&&!(typeof i=="number"&&typeof a=="number"||typeof i=="string"&&typeof a=="string"))throw new G(`Operator '${t}' is not defined between ${typeof i} and ${typeof a}`);switch(t){case"==":return i===a||ye(i,a);case"!=":return!(i===a||ye(i,a));case"<":return i<a;case">":return i>a;case"<=":return i<=a;case">=":return i>=a;case"+":{if(Array.isArray(i)&&Array.isArray(a))return[...i,...a];if(typeof i=="string"&&typeof a=="string"||typeof i=="number"&&typeof a=="number")return i+a;if(typeof i=="string"&&a instanceof te)return i+String(a);throw new G(`Operator '+' is not defined between ${Array.isArray(i)?"list":typeof i} and ${Array.isArray(a)?"list":typeof a}`)}case"-":return i-a;case"*":return i*a;case"/":if(a===0)throw new G("Division by zero");return Math.trunc(i/a);case"%":if(a===0)throw new G("Modulo by zero");return i%a;default:throw new G(`Unknown binary op: ${t}`)}}function pr(t,e){if(typeof t=="boolean")return t;throw new G(`Expected a boolean control-flow operand, got ${t===null?"null":typeof t}`,e)}const Ad=new Set(["__proto__","prototype","constructor"]);function sn(t){if(Ad.has(t))throw new Error(`Invalid field-path segment '${t}': the keys __proto__, prototype, and constructor are reserved and cannot appear in a field path.`)}function Wo(t,e){const r={...t};for(const[n,s]of Object.entries(e)){sn(n);const i=Object.hasOwn(r,n)?r[n]:void 0;s!==null&&typeof s=="object"&&!Array.isArray(s)&&i!==null&&typeof i=="object"&&!Array.isArray(i)?r[n]=Wo(i,s):r[n]=s}return r}function xd(t,e,r){let n=t;for(let i=0;i<e.length-1;i++){const a=e[i];sn(a);const o=Object.hasOwn(n,a)?n[a]:void 0;(o===null||typeof o!="object"||Array.isArray(o))&&(n[a]={}),n=n[a]}const s=e[e.length-1];sn(s),n[s]=r}function Id(t,e){const r={...t};for(const[n,s]of Object.entries(e))n.includes(".")?xd(r,n.split("."),s):(sn(n),r[n]=s);return r}function kd(t,e,r){switch(t.kind){case"create":return r;case"set":return t.merge?Wo(e??{},r):r;case"update":return Id(e??{},r);case"delete":return null}}function Ho(t){if(t===null||typeof t!="object"||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function Ed(t){return typeof t=="object"&&t!==null&&t.__type==="serverTimestamp"}function Go(t,e){const r={};for(const[n,s]of Object.entries(t))Ed(s)?r[n]=e:Ho(s)?r[n]=Go(s,e):r[n]=s;return r}function Ct(t){return typeof t=="number"&&!Number.isInteger(t)?new oe(t):Array.isArray(t)?t.map(Ct):Ho(t)?t.__type==="float"&&typeof t.value=="number"?new oe(t.value):Object.fromEntries(Object.entries(t).map(([e,r])=>[e,Ct(r)])):t}function na(t){if(t.method==="list")return{limit:t.query?.limit??null,offset:t.query?.offset??null,orderBy:t.query?.orderBy??null}}function Hr(t){return`/${t.path.segments.map(r=>r.type==="literal"?r.value:r.type==="wildcard"?`{${r.name}}`:`{${r.name}=**}`).join("/")}`}function an(t,e,r,n){const s=[...r,...t.functions],i=t.path.segments,a={},o=[];let c=0,u;for(const f of i)if(f.type==="literal"){if(c>=e.length){u="request-shorter";break}if(e[c]!==f.value){u="literal-mismatch";break}c++}else if(f.type==="wildcard"){if(c>=e.length){u="request-shorter";break}a[f.name]=e[c],c===e.length-1&&o.push(f.name),c++}else a[f.name]=e.slice(c).join("/"),c<e.length&&o.push(f.name),c=e.length;if(u!==void 0)return n?.push({...t.loc?{line:t.loc.line}:{},blockPath:Hr(t),matchedSegments:c,totalSegments:i.length,bindings:a,matched:!1,reason:u}),[];const d=e.slice(c);if(d.length===0)return n?.push({...t.loc?{line:t.loc.line}:{},blockPath:Hr(t),matchedSegments:c,totalSegments:i.length,bindings:a,matched:!0}),[{block:t,pathVariables:a,candidateVariables:o,functions:s}];const l=[];for(const f of t.children)for(const y of an(f,d,s,n))y.pathVariables={...a,...y.pathVariables},y.candidateVariables=[...o,...y.candidateVariables],l.push(y);return n?.push({...t.loc?{line:t.loc.line}:{},blockPath:Hr(t),matchedSegments:c,totalSegments:i.length,bindings:a,...l.length>0?{matched:!0}:{matched:!1,reason:"no-matching-child"}}),l}class Od{attempts=[];push(e){this.attempts.push(e)}}function Cd(t){switch(t){case"get":return["get","read"];case"list":return["list","read"];case"create":return["create","write"];case"update":return["update","write"];case"delete":return["delete","write"];default:return[t]}}function Td(t,e,r){const n=Cd(e),s=[],i=[],a=[];for(let u=0;u<t.allows.length;u++){const d=t.allows[u];d.operations.some(l=>n.includes(l))&&a.push({rule:d,index:u})}if(a.length===0)return i.push(`No allow rules found for operation '${e}'`),{decision:"DENY",trace:s,notes:i};let o=!1;const c=r.trace;for(const{rule:u,index:d}of a){const l=Rd(u,d),f=new Bl;r.trace=f;try{const y=W(u.condition,r);if(l.expressionTrace=f.entries,y)return l.verdict="ALLOW",s.push(l),r.trace=c,{decision:"ALLOW",trace:s,notes:i};l.verdict="DENY",s.push(l)}catch(y){l.expressionTrace=f.entries,y instanceof Je?(o=!0,l.verdict="UNSUPPORTED",l.message=y.message):(l.verdict="ERROR",l.message=y instanceof Error?y.message:String(y)),s.push(l)}}return r.trace=c,{decision:o?"UNSUPPORTED":"DENY",trace:s,notes:i}}function Rd(t,e){const r={ruleIndex:e,operations:[...t.operations],verdict:"DENY",conditionText:Ie(t.condition)};return t.loc&&(r.line=t.loc.line),r}function Nd(t,e,r,n,s){const i=new Map;for(const L of e)i.set(L.name,L);const a=new Map,o=new Set;if(t.functionMocks)for(const L of t.functionMocks)L.function==="get"&&typeof L.result=="object"&&L.result!==null?(a.set(L.path,Ct(L.result)),o.add(L.path)):L.function==="exists"&&L.result===!0&&(a.set(L.path,{}),o.add(L.path));const c=t.requestTime?xe.fromIsoString(t.requestTime):xe.fromMillis(Date.now()),d=["databases","(default)","documents",...(t.path.startsWith("/")?t.path.slice(1):t.path).split("/").filter(Boolean)],l=new Xe(d,r),f=Ct(t.data??{}),y=t.resource===void 0||t.resource===null?null:Ct(t.resource);let b,S;if(t.writeMode)b=kd(t.writeMode,y,f),S=b!==null;else switch(t.method){case"create":case"update":b=f,S=!0;break;case"delete":b=null,S=!1;break;case"get":case"list":default:b=y,S=y!==null;break}const j=b!==null?Ct(Go(b,c)):null,T=j??{};return{request:{auth:t.auth?{uid:t.auth.uid,token:t.auth.token??{}}:null,resource:{data:T},method:t.method,path:l,...na(t)?{query:na(t)}:{},time:c},resource:t.method==="create"||y===null?null:{data:Ct(y)},mockDocuments:a,identitylessFunctionMocks:o,getDoc:n,pathVariables:r,functions:i,database:"(default)",afterStatePath:l,afterState:j,existsAfter:S,...s?{batchProjection:s}:{}}}class Fd{simulate(e,r,n){if(!e||e.trim().length===0)return{success:!1,error:{code:"PARSE_FAILED",message:"Empty rules source — call setRules(sandbox, rules) from pyric/sandbox/firestore before operating, or initialize without rules to use the open-by-default ruleset. See pyric/sandbox docs.",recoverable:!0}};const s=si(e);if(!s)return{success:!1,error:{code:"PARSE_FAILED",message:"Failed to parse rules source",recoverable:!0}};const i=[];let a=0,o=0,c=0;const u={database:"(default)"};for(const d of s.service.match.path.segments)d.type==="wildcard"&&(u[d.name]="(default)");for(const d of r){const l=d.path.split("/").filter(Boolean),f=[...s.functions??[],...s.service.functions??[],...s.service.match.functions];let y=[];const b=new Od;for(const x of s.service.match.children)y.push(...an(x,l,f,b));let S=!1;if(y.length===0&&d.method==="list"){const x=[...l,"__hypothetical_doc__"];for(const _ of s.service.match.children)y.push(...an(_,x,f,b));y.length>0&&(S=!0)}const j={requestPath:d.path,attempts:b.attempts};if(y.length===0){const x=d.expectation==="DENY"?"PASSED":"FAILED";x==="PASSED"?a++:o++,i.push({description:d.description,expectation:d.expectation,state:x,decision:"DENY",trace:[],notes:[`No match block found for path '${d.path}'`],pathResolution:j});continue}let T="DENY";const L=[],k=[];let $=!1,V;for(const x of y){const _={...u,...x.pathVariables},v=Nd(d,x.functions,_,n?.getDoc,n?.batchProjection),O=Hr(x.block),A=Td(x.block,d.method,v);for(const h of A.trace)h.matchPath=O;if(L.push(...A.trace),k.push(...A.notes),A.decision==="ALLOW"){T="ALLOW",V=O;break}A.decision==="UNSUPPORTED"&&($=!0)}T!=="ALLOW"&&$&&(T="UNSUPPORTED"),T==="ALLOW"&&V&&k.push(`Allowed by match block '${V}'`),S&&k.push(`list on collection path '${d.path}' evaluated against the document-level match block (document wildcard hypothetical, resource undefined) — emulator-faithful`);let w;T==="UNSUPPORTED"?(w="UNSUPPORTED",c++):T===d.expectation?(w="PASSED",a++):(w="FAILED",o++),i.push({description:d.description,expectation:d.expectation,state:w,decision:T,trace:L,notes:k,pathResolution:j})}return{success:!0,data:{passed:a,failed:o,unsupported:c,results:i}}}}function Ld(t,e,r=new Map,n){if(on(t,r))return{provable:!0,reason:"list rule does not depend on per-document data; every doc is equally readable"};const s=Dd(t,r,n);if(!s.ok||s.required.length===0){const u="list rule depends on per-document data through a predicate the query cannot discharge (a rule is provable only when its entire doc-dependence reduces to top-level `resource.data.field == value` conjunctions, including through inlined helpers — disjunctions, ranges, `in`, membership/type checks, and nested paths are not provable)";return{provable:!1,reason:`${u} — prod rejects the whole query rather than filtering`,residual:{missing:[],mismatched:[],outOfScope:u}}}const i=s.required,a=e.where??[],o=[],c=[];for(const u of i){if(a.some(f=>f.field===u.field&&f.op==="=="&&qd(f.value,u.value)))continue;const l=a.find(f=>f.field===u.field&&f.op==="==");l?c.push({field:u.field,expectedValue:u.value,actualValue:l.value}):o.push({field:u.field,expectedValue:u.value,fromAuthUid:u.fromAuthUid})}return o.length===0&&c.length===0?{provable:!0,reason:"every per-document predicate the rule requires is guaranteed by a query where(...) constraint"}:{provable:!1,reason:jd(o,c),residual:{missing:o,mismatched:c}}}function jd(t,e){const r=[];if(t.length>0){const n=t.map(s=>`resource.data.${s.field} == ${s.fromAuthUid?"request.auth.uid":JSON.stringify(s.expectedValue)}`).join(", ");r.push(`the query has no matching where(...) equality for [${n}]`)}if(e.length>0){const n=e.map(s=>`resource.data.${s.field} == ${JSON.stringify(s.expectedValue)} but the query pins ${JSON.stringify(s.actualValue)}`).join(", ");r.push(`the query where(...) value does not match [${n}]`)}return`${r.join("; ")} — prod rejects the query ("rules are not filters")`}function on(t,e=new Map,r=new Set){const n=s=>{switch(s.type){case"literal":return!0;case"identifier":return s.name!=="resource";case"memberAccess":return n(s.object);case"bracketAccess":return n(s.object)&&n(s.index);case"sliceAccess":return n(s.object)&&n(s.start)&&n(s.end);case"binaryOp":return n(s.left)&&n(s.right);case"unaryOp":return n(s.operand);case"ternary":return n(s.condition)&&n(s.consequent)&&n(s.alternate);case"inExpr":return n(s.element)&&n(s.collection);case"isExpr":return n(s.value);case"listLiteral":return s.elements.every(n);case"mapLiteral":return s.entries.every(i=>n(i.key)&&n(i.value));case"pathLiteral":return s.segments.every(i=>typeof i=="string"||n(i));case"methodCall":return n(s.object)&&s.args.every(n);case"functionCall":{if(!s.args.every(n))return!1;const i=e.get(s.name);if(!i)return!0;if(r.has(s.name))return!1;const a=new Set(r).add(s.name);return on(i.body,e,a)&&i.lets.every(o=>on(o.value,e,a))}default:return!1}};return n(t)}function Dd(t,e,r){const n=[],s=(i,a)=>{if(i.type==="binaryOp"&&i.op==="&&")return s(i.left,a)&&s(i.right,a);if(i.type==="functionCall"&&e.has(i.name)&&!a.has(i.name)){const c=e.get(i.name),u=new Map;c.parameters.forEach((f,y)=>{const b=i.args[y];b&&u.set(f,b)});for(const f of c.lets)u.set(f.name,sa(f.value,u));const d=sa(c.body,u),l=new Set(a).add(i.name);return s(d,l)}const o=Md(i,r);return o?(n.push(o),!0):on(i,e)};return s(t,new Set)?{ok:!0,required:n}:{ok:!1}}function Md(t,e){if(t.type!=="binaryOp"||t.op!=="==")return null;const r=(n,s)=>{const i=$d(n);return i===null?null:s.type==="literal"?{field:i,value:s.value,fromAuthUid:!1}:e!==void 0&&Pd(s)?{field:i,value:e,fromAuthUid:!0}:null};return r(t.left,t.right)??r(t.right,t.left)}function Pd(t){return t.type==="memberAccess"&&t.property==="uid"&&t.object.type==="memberAccess"&&t.object.property==="auth"&&t.object.object.type==="identifier"&&t.object.object.name==="request"}function sa(t,e){const r=n=>{switch(n.type){case"identifier":return e.get(n.name)??n;case"literal":return n;case"memberAccess":return{...n,object:r(n.object)};case"methodCall":return{...n,object:r(n.object),args:n.args.map(r)};case"bracketAccess":return{...n,object:r(n.object),index:r(n.index)};case"sliceAccess":return{...n,object:r(n.object),start:r(n.start),end:r(n.end)};case"binaryOp":return{...n,left:r(n.left),right:r(n.right)};case"unaryOp":return{...n,operand:r(n.operand)};case"ternary":return{...n,condition:r(n.condition),consequent:r(n.consequent),alternate:r(n.alternate)};case"inExpr":return{...n,element:r(n.element),collection:r(n.collection)};case"isExpr":return{...n,value:r(n.value)};case"listLiteral":return{...n,elements:n.elements.map(r)};case"mapLiteral":return{...n,entries:n.entries.map(s=>({key:r(s.key),value:r(s.value)}))};case"pathLiteral":return{...n,segments:n.segments.map(s=>typeof s=="string"?s:r(s))};case"functionCall":return{...n,args:n.args.map(r)}}};return r(t)}function $d(t){return t.type==="memberAccess"&&t.object.type==="memberAccess"&&t.object.property==="data"&&t.object.object.type==="identifier"&&t.object.object.name==="resource"?t.property:null}function qd(t,e){return t===e}class jt extends te{typeName="reference";path;constructor(e){super(),this.path=Ud(e)}static fromResourceName(e){return new jt(Ko(e))}get id(){const e=this.path.lastIndexOf("/");return e===-1?this.path:this.path.slice(e+1)}get parent(){const e=this.path.lastIndexOf("/");return e===-1?"":this.path.slice(0,e)}valueOf(){return NaN}toString(){return this.path}toJSON(){return{__type:"reference",path:this.path}}equals(e){return e instanceof jt?this.path===e.path:!1}field(e){switch(e){case"path":return this.path;case"id":return this.id;case"parent":return this.parent;default:return null}}callMethod(e,r){return ue}}function Ud(t){let e=Ko(t);return e.startsWith("/")&&(e=e.slice(1)),e.endsWith("/")&&(e=e.slice(0,-1)),e}function Ko(t){const e="/documents/",r=t.indexOf(e);return r===-1?t:t.slice(r+e.length)}class Wt extends te{typeName="vector";value;constructor(e){if(super(),!Array.isArray(e))throw new TypeError("Vector: value must be a number[]");for(let r=0;r<e.length;r++)if(typeof e[r]!="number")throw new TypeError(`Vector: element at index ${r} is not a number (got ${typeof e[r]})`);this.value=Object.freeze(e.slice())}get dimension(){return this.value.length}valueOf(){return NaN}toString(){return`[${this.value.join(", ")}]`}toJSON(){return{__type__:"__vector__",value:this.value.slice()}}equals(e){if(!(e instanceof Wt)||e.value.length!==this.value.length)return!1;for(let r=0;r<this.value.length;r++)if(e.value[r]!==this.value[r])return!1;return!0}callMethod(e,r){return ue}}var Y;(function(t){t.assertEqual=s=>{};function e(s){}t.assertIs=e;function r(s){throw new Error}t.assertNever=r,t.arrayToEnum=s=>{const i={};for(const a of s)i[a]=a;return i},t.getValidEnumValues=s=>{const i=t.objectKeys(s).filter(o=>typeof s[s[o]]!="number"),a={};for(const o of i)a[o]=s[o];return t.objectValues(a)},t.objectValues=s=>t.objectKeys(s).map(function(i){return s[i]}),t.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const i=[];for(const a in s)Object.prototype.hasOwnProperty.call(s,a)&&i.push(a);return i},t.find=(s,i)=>{for(const a of s)if(i(a))return a},t.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,i=" | "){return s.map(a=>typeof a=="string"?`'${a}'`:a).join(i)}t.joinValues=n,t.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(Y||(Y={}));var ia;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(ia||(ia={}));const M=Y.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),yt=t=>{switch(typeof t){case"undefined":return M.undefined;case"string":return M.string;case"number":return Number.isNaN(t)?M.nan:M.number;case"boolean":return M.boolean;case"function":return M.function;case"bigint":return M.bigint;case"symbol":return M.symbol;case"object":return Array.isArray(t)?M.array:t===null?M.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?M.promise:typeof Map<"u"&&t instanceof Map?M.map:typeof Set<"u"&&t instanceof Set?M.set:typeof Date<"u"&&t instanceof Date?M.date:M.object;default:return M.unknown}},R=Y.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class ft extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};const r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){const r=e||function(i){return i.message},n={_errors:[]},s=i=>{for(const a of i.issues)if(a.code==="invalid_union")a.unionErrors.map(s);else if(a.code==="invalid_return_type")s(a.returnTypeError);else if(a.code==="invalid_arguments")s(a.argumentsError);else if(a.path.length===0)n._errors.push(r(a));else{let o=n,c=0;for(;c<a.path.length;){const u=a.path[c];c===a.path.length-1?(o[u]=o[u]||{_errors:[]},o[u]._errors.push(r(a))):o[u]=o[u]||{_errors:[]},o=o[u],c++}}};return s(this),n}static assert(e){if(!(e instanceof ft))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Y.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){const r={},n=[];for(const s of this.issues)if(s.path.length>0){const i=s.path[0];r[i]=r[i]||[],r[i].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}}ft.create=t=>new ft(t);const _s=(t,e)=>{let r;switch(t.code){case R.invalid_type:t.received===M.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case R.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,Y.jsonStringifyReplacer)}`;break;case R.unrecognized_keys:r=`Unrecognized key(s) in object: ${Y.joinValues(t.keys,", ")}`;break;case R.invalid_union:r="Invalid input";break;case R.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Y.joinValues(t.options)}`;break;case R.invalid_enum_value:r=`Invalid enum value. Expected ${Y.joinValues(t.options)}, received '${t.received}'`;break;case R.invalid_arguments:r="Invalid function arguments";break;case R.invalid_return_type:r="Invalid function return type";break;case R.invalid_date:r="Invalid date";break;case R.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:Y.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case R.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case R.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case R.custom:r="Invalid input";break;case R.invalid_intersection_types:r="Intersection results could not be merged";break;case R.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case R.not_finite:r="Number must be finite";break;default:r=e.defaultError,Y.assertNever(t)}return{message:r}};let Bd=_s;function zd(){return Bd}const Vd=t=>{const{data:e,path:r,errorMaps:n,issueData:s}=t,i=[...r,...s.path||[]],a={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let o="";const c=n.filter(u=>!!u).slice().reverse();for(const u of c)o=u(a,{data:e,defaultError:o}).message;return{...s,path:i,message:o}};function F(t,e){const r=zd(),n=Vd({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===_s?void 0:_s].filter(s=>!!s)});t.common.issues.push(n)}class je{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){const n=[];for(const s of r){if(s.status==="aborted")return U;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){const n=[];for(const s of r){const i=await s.key,a=await s.value;n.push({key:i,value:a})}return je.mergeObjectSync(e,n)}static mergeObjectSync(e,r){const n={};for(const s of r){const{key:i,value:a}=s;if(i.status==="aborted"||a.status==="aborted")return U;i.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof a.value<"u"||s.alwaysSet)&&(n[i.value]=a.value)}return{status:e.value,value:n}}}const U=Object.freeze({status:"aborted"}),mr=t=>({status:"dirty",value:t}),Ve=t=>({status:"valid",value:t}),aa=t=>t.status==="aborted",oa=t=>t.status==="dirty",er=t=>t.status==="valid",cn=t=>typeof Promise<"u"&&t instanceof Promise;var P;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(P||(P={}));class nt{constructor(e,r,n,s){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const ca=(t,e)=>{if(er(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const r=new ft(t.common.issues);return this._error=r,this._error}}};function H(t){if(!t)return{};const{errorMap:e,invalid_type_error:r,required_error:n,description:s}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(a,o)=>{const{message:c}=t;return a.code==="invalid_enum_value"?{message:c??o.defaultError}:typeof o.data>"u"?{message:c??n??o.defaultError}:a.code!=="invalid_type"?{message:o.defaultError}:{message:c??r??o.defaultError}},description:s}}class K{get description(){return this._def.description}_getType(e){return yt(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:yt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new je,ctx:{common:e.parent.common,data:e.data,parsedType:yt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const r=this._parse(e);if(cn(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){const r=this._parse(e);return Promise.resolve(r)}parse(e,r){const n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){const n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:yt(e)},s=this._parseSync({data:e,path:n.path,parent:n});return ca(n,s)}"~validate"(e){const r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:yt(e)};if(!this["~standard"].async)try{const n=this._parseSync({data:e,path:[],parent:r});return er(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>er(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){const n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){const n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:yt(e)},s=this._parse({data:e,path:n.path,parent:n}),i=await(cn(s)?s:Promise.resolve(s));return ca(n,i)}refine(e,r){const n=s=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(s):r;return this._refinement((s,i)=>{const a=e(s),o=()=>i.addIssue({code:R.custom,...n(s)});return typeof Promise<"u"&&a instanceof Promise?a.then(c=>c?!0:(o(),!1)):a?!0:(o(),!1)})}refinement(e,r){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof r=="function"?r(n,s):r),!1))}_refinement(e){return new Pt({schema:this,typeName:B.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return dt.create(this,this._def)}nullable(){return $t.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return et.create(this)}promise(){return mn.create(this,this._def)}or(e){return dn.create([this,e],this._def)}and(e){return hn.create(this,e,this._def)}transform(e){return new Pt({...H(this._def),schema:this,typeName:B.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const r=typeof e=="function"?e:()=>e;return new gn({...H(this._def),innerType:this,defaultValue:r,typeName:B.ZodDefault})}brand(){return new Yo({typeName:B.ZodBranded,type:this,...H(this._def)})}catch(e){const r=typeof e=="function"?e:()=>e;return new yn({...H(this._def),innerType:this,catchValue:r,typeName:B.ZodCatch})}describe(e){const r=this.constructor;return new r({...this._def,description:e})}pipe(e){return oi.create(this,e)}readonly(){return bn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Wd=/^c[^\s-]{8,}$/i,Hd=/^[0-9a-z]+$/,Gd=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Kd=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Zd=/^[a-z0-9_-]{21}$/i,Jd=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Qd=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Yd=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Xd="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Yn;const eh=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,th=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,rh=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,nh=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,sh=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ih=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Zo="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",ah=new RegExp(`^${Zo}$`);function Jo(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);const r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function oh(t){return new RegExp(`^${Jo(t)}$`)}function ch(t){let e=`${Zo}T${Jo(t)}`;const r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function uh(t,e){return!!((e==="v4"||!e)&&eh.test(t)||(e==="v6"||!e)&&rh.test(t))}function lh(t,e){if(!Jd.test(t))return!1;try{const[r]=t.split(".");if(!r)return!1;const n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),s=JSON.parse(atob(n));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function dh(t,e){return!!((e==="v4"||!e)&&th.test(t)||(e==="v6"||!e)&&nh.test(t))}class ut extends K{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==M.string){const i=this._getOrReturnCtx(e);return F(i,{code:R.invalid_type,expected:M.string,received:i.parsedType}),U}const n=new je;let s;for(const i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),F(s,{code:R.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),F(s,{code:R.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="length"){const a=e.data.length>i.value,o=e.data.length<i.value;(a||o)&&(s=this._getOrReturnCtx(e,s),a?F(s,{code:R.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):o&&F(s,{code:R.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),n.dirty())}else if(i.kind==="email")Yd.test(e.data)||(s=this._getOrReturnCtx(e,s),F(s,{validation:"email",code:R.invalid_string,message:i.message}),n.dirty());else if(i.kind==="emoji")Yn||(Yn=new RegExp(Xd,"u")),Yn.test(e.data)||(s=this._getOrReturnCtx(e,s),F(s,{validation:"emoji",code:R.invalid_string,message:i.message}),n.dirty());else if(i.kind==="uuid")Kd.test(e.data)||(s=this._getOrReturnCtx(e,s),F(s,{validation:"uuid",code:R.invalid_string,message:i.message}),n.dirty());else if(i.kind==="nanoid")Zd.test(e.data)||(s=this._getOrReturnCtx(e,s),F(s,{validation:"nanoid",code:R.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid")Wd.test(e.data)||(s=this._getOrReturnCtx(e,s),F(s,{validation:"cuid",code:R.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid2")Hd.test(e.data)||(s=this._getOrReturnCtx(e,s),F(s,{validation:"cuid2",code:R.invalid_string,message:i.message}),n.dirty());else if(i.kind==="ulid")Gd.test(e.data)||(s=this._getOrReturnCtx(e,s),F(s,{validation:"ulid",code:R.invalid_string,message:i.message}),n.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),F(s,{validation:"url",code:R.invalid_string,message:i.message}),n.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),F(s,{validation:"regex",code:R.invalid_string,message:i.message}),n.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),F(s,{code:R.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),n.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),F(s,{code:R.invalid_string,validation:{startsWith:i.value},message:i.message}),n.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),F(s,{code:R.invalid_string,validation:{endsWith:i.value},message:i.message}),n.dirty()):i.kind==="datetime"?ch(i).test(e.data)||(s=this._getOrReturnCtx(e,s),F(s,{code:R.invalid_string,validation:"datetime",message:i.message}),n.dirty()):i.kind==="date"?ah.test(e.data)||(s=this._getOrReturnCtx(e,s),F(s,{code:R.invalid_string,validation:"date",message:i.message}),n.dirty()):i.kind==="time"?oh(i).test(e.data)||(s=this._getOrReturnCtx(e,s),F(s,{code:R.invalid_string,validation:"time",message:i.message}),n.dirty()):i.kind==="duration"?Qd.test(e.data)||(s=this._getOrReturnCtx(e,s),F(s,{validation:"duration",code:R.invalid_string,message:i.message}),n.dirty()):i.kind==="ip"?uh(e.data,i.version)||(s=this._getOrReturnCtx(e,s),F(s,{validation:"ip",code:R.invalid_string,message:i.message}),n.dirty()):i.kind==="jwt"?lh(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),F(s,{validation:"jwt",code:R.invalid_string,message:i.message}),n.dirty()):i.kind==="cidr"?dh(e.data,i.version)||(s=this._getOrReturnCtx(e,s),F(s,{validation:"cidr",code:R.invalid_string,message:i.message}),n.dirty()):i.kind==="base64"?sh.test(e.data)||(s=this._getOrReturnCtx(e,s),F(s,{validation:"base64",code:R.invalid_string,message:i.message}),n.dirty()):i.kind==="base64url"?ih.test(e.data)||(s=this._getOrReturnCtx(e,s),F(s,{validation:"base64url",code:R.invalid_string,message:i.message}),n.dirty()):Y.assertNever(i);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(s=>e.test(s),{validation:r,code:R.invalid_string,...P.errToObj(n)})}_addCheck(e){return new ut({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...P.errToObj(e)})}url(e){return this._addCheck({kind:"url",...P.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...P.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...P.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...P.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...P.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...P.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...P.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...P.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...P.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...P.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...P.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...P.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...P.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...P.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...P.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...P.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...P.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...P.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...P.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...P.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...P.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...P.errToObj(r)})}nonempty(e){return this.min(1,P.errToObj(e))}trim(){return new ut({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ut({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ut({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}}ut.create=t=>new ut({checks:[],typeName:B.ZodString,coerce:t?.coerce??!1,...H(t)});function hh(t,e){const r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=r>n?r:n,i=Number.parseInt(t.toFixed(s).replace(".","")),a=Number.parseInt(e.toFixed(s).replace(".",""));return i%a/10**s}class tr extends K{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==M.number){const i=this._getOrReturnCtx(e);return F(i,{code:R.invalid_type,expected:M.number,received:i.parsedType}),U}let n;const s=new je;for(const i of this._def.checks)i.kind==="int"?Y.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{code:R.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),F(n,{code:R.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),F(n,{code:R.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?hh(e.data,i.value)!==0&&(n=this._getOrReturnCtx(e,n),F(n,{code:R.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{code:R.not_finite,message:i.message}),s.dirty()):Y.assertNever(i);return{status:s.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,P.toString(r))}gt(e,r){return this.setLimit("min",e,!1,P.toString(r))}lte(e,r){return this.setLimit("max",e,!0,P.toString(r))}lt(e,r){return this.setLimit("max",e,!1,P.toString(r))}setLimit(e,r,n,s){return new tr({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:P.toString(s)}]})}_addCheck(e){return new tr({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:P.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:P.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:P.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:P.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:P.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:P.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:P.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:P.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:P.toString(e)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&Y.isInteger(e.value))}get isFinite(){let e=null,r=null;for(const n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}}tr.create=t=>new tr({checks:[],typeName:B.ZodNumber,coerce:t?.coerce||!1,...H(t)});class Ar extends K{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==M.bigint)return this._getInvalidInput(e);let n;const s=new je;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),F(n,{code:R.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),F(n,{code:R.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),F(n,{code:R.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):Y.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){const r=this._getOrReturnCtx(e);return F(r,{code:R.invalid_type,expected:M.bigint,received:r.parsedType}),U}gte(e,r){return this.setLimit("min",e,!0,P.toString(r))}gt(e,r){return this.setLimit("min",e,!1,P.toString(r))}lte(e,r){return this.setLimit("max",e,!0,P.toString(r))}lt(e,r){return this.setLimit("max",e,!1,P.toString(r))}setLimit(e,r,n,s){return new Ar({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:P.toString(s)}]})}_addCheck(e){return new Ar({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:P.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:P.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:P.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:P.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:P.toString(r)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}}Ar.create=t=>new Ar({checks:[],typeName:B.ZodBigInt,coerce:t?.coerce??!1,...H(t)});class As extends K{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==M.boolean){const n=this._getOrReturnCtx(e);return F(n,{code:R.invalid_type,expected:M.boolean,received:n.parsedType}),U}return Ve(e.data)}}As.create=t=>new As({typeName:B.ZodBoolean,coerce:t?.coerce||!1,...H(t)});class un extends K{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==M.date){const i=this._getOrReturnCtx(e);return F(i,{code:R.invalid_type,expected:M.date,received:i.parsedType}),U}if(Number.isNaN(e.data.getTime())){const i=this._getOrReturnCtx(e);return F(i,{code:R.invalid_date}),U}const n=new je;let s;for(const i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),F(s,{code:R.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),n.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),F(s,{code:R.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),n.dirty()):Y.assertNever(i);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new un({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:P.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:P.toString(r)})}get minDate(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}}un.create=t=>new un({checks:[],coerce:t?.coerce||!1,typeName:B.ZodDate,...H(t)});class ua extends K{_parse(e){if(this._getType(e)!==M.symbol){const n=this._getOrReturnCtx(e);return F(n,{code:R.invalid_type,expected:M.symbol,received:n.parsedType}),U}return Ve(e.data)}}ua.create=t=>new ua({typeName:B.ZodSymbol,...H(t)});class xs extends K{_parse(e){if(this._getType(e)!==M.undefined){const n=this._getOrReturnCtx(e);return F(n,{code:R.invalid_type,expected:M.undefined,received:n.parsedType}),U}return Ve(e.data)}}xs.create=t=>new xs({typeName:B.ZodUndefined,...H(t)});class ln extends K{_parse(e){if(this._getType(e)!==M.null){const n=this._getOrReturnCtx(e);return F(n,{code:R.invalid_type,expected:M.null,received:n.parsedType}),U}return Ve(e.data)}}ln.create=t=>new ln({typeName:B.ZodNull,...H(t)});class la extends K{constructor(){super(...arguments),this._any=!0}_parse(e){return Ve(e.data)}}la.create=t=>new la({typeName:B.ZodAny,...H(t)});class Is extends K{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ve(e.data)}}Is.create=t=>new Is({typeName:B.ZodUnknown,...H(t)});class _t extends K{_parse(e){const r=this._getOrReturnCtx(e);return F(r,{code:R.invalid_type,expected:M.never,received:r.parsedType}),U}}_t.create=t=>new _t({typeName:B.ZodNever,...H(t)});class da extends K{_parse(e){if(this._getType(e)!==M.undefined){const n=this._getOrReturnCtx(e);return F(n,{code:R.invalid_type,expected:M.void,received:n.parsedType}),U}return Ve(e.data)}}da.create=t=>new da({typeName:B.ZodVoid,...H(t)});class et extends K{_parse(e){const{ctx:r,status:n}=this._processInputParams(e),s=this._def;if(r.parsedType!==M.array)return F(r,{code:R.invalid_type,expected:M.array,received:r.parsedType}),U;if(s.exactLength!==null){const a=r.data.length>s.exactLength.value,o=r.data.length<s.exactLength.value;(a||o)&&(F(r,{code:a?R.too_big:R.too_small,minimum:o?s.exactLength.value:void 0,maximum:a?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&r.data.length<s.minLength.value&&(F(r,{code:R.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&r.data.length>s.maxLength.value&&(F(r,{code:R.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((a,o)=>s.type._parseAsync(new nt(r,a,r.path,o)))).then(a=>je.mergeArray(n,a));const i=[...r.data].map((a,o)=>s.type._parseSync(new nt(r,a,r.path,o)));return je.mergeArray(n,i)}get element(){return this._def.type}min(e,r){return new et({...this._def,minLength:{value:e,message:P.toString(r)}})}max(e,r){return new et({...this._def,maxLength:{value:e,message:P.toString(r)}})}length(e,r){return new et({...this._def,exactLength:{value:e,message:P.toString(r)}})}nonempty(e){return this.min(1,e)}}et.create=(t,e)=>new et({type:t,minLength:null,maxLength:null,exactLength:null,typeName:B.ZodArray,...H(e)});function Zt(t){if(t instanceof me){const e={};for(const r in t.shape){const n=t.shape[r];e[r]=dt.create(Zt(n))}return new me({...t._def,shape:()=>e})}else return t instanceof et?new et({...t._def,type:Zt(t.element)}):t instanceof dt?dt.create(Zt(t.unwrap())):t instanceof $t?$t.create(Zt(t.unwrap())):t instanceof Dt?Dt.create(t.items.map(e=>Zt(e))):t}class me extends K{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),r=Y.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==M.object){const u=this._getOrReturnCtx(e);return F(u,{code:R.invalid_type,expected:M.object,received:u.parsedType}),U}const{status:n,ctx:s}=this._processInputParams(e),{shape:i,keys:a}=this._getCached(),o=[];if(!(this._def.catchall instanceof _t&&this._def.unknownKeys==="strip"))for(const u in s.data)a.includes(u)||o.push(u);const c=[];for(const u of a){const d=i[u],l=s.data[u];c.push({key:{status:"valid",value:u},value:d._parse(new nt(s,l,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof _t){const u=this._def.unknownKeys;if(u==="passthrough")for(const d of o)c.push({key:{status:"valid",value:d},value:{status:"valid",value:s.data[d]}});else if(u==="strict")o.length>0&&(F(s,{code:R.unrecognized_keys,keys:o}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const u=this._def.catchall;for(const d of o){const l=s.data[d];c.push({key:{status:"valid",value:d},value:u._parse(new nt(s,l,s.path,d)),alwaysSet:d in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const u=[];for(const d of c){const l=await d.key,f=await d.value;u.push({key:l,value:f,alwaysSet:d.alwaysSet})}return u}).then(u=>je.mergeObjectSync(n,u)):je.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return P.errToObj,new me({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{const s=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:P.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new me({...this._def,unknownKeys:"strip"})}passthrough(){return new me({...this._def,unknownKeys:"passthrough"})}extend(e){return new me({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new me({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:B.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new me({...this._def,catchall:e})}pick(e){const r={};for(const n of Y.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new me({...this._def,shape:()=>r})}omit(e){const r={};for(const n of Y.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new me({...this._def,shape:()=>r})}deepPartial(){return Zt(this)}partial(e){const r={};for(const n of Y.objectKeys(this.shape)){const s=this.shape[n];e&&!e[n]?r[n]=s:r[n]=s.optional()}return new me({...this._def,shape:()=>r})}required(e){const r={};for(const n of Y.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let i=this.shape[n];for(;i instanceof dt;)i=i._def.innerType;r[n]=i}return new me({...this._def,shape:()=>r})}keyof(){return Qo(Y.objectKeys(this.shape))}}me.create=(t,e)=>new me({shape:()=>t,unknownKeys:"strip",catchall:_t.create(),typeName:B.ZodObject,...H(e)});me.strictCreate=(t,e)=>new me({shape:()=>t,unknownKeys:"strict",catchall:_t.create(),typeName:B.ZodObject,...H(e)});me.lazycreate=(t,e)=>new me({shape:t,unknownKeys:"strip",catchall:_t.create(),typeName:B.ZodObject,...H(e)});class dn extends K{_parse(e){const{ctx:r}=this._processInputParams(e),n=this._def.options;function s(i){for(const o of i)if(o.result.status==="valid")return o.result;for(const o of i)if(o.result.status==="dirty")return r.common.issues.push(...o.ctx.common.issues),o.result;const a=i.map(o=>new ft(o.ctx.common.issues));return F(r,{code:R.invalid_union,unionErrors:a}),U}if(r.common.async)return Promise.all(n.map(async i=>{const a={...r,common:{...r.common,issues:[]},parent:null};return{result:await i._parseAsync({data:r.data,path:r.path,parent:a}),ctx:a}})).then(s);{let i;const a=[];for(const c of n){const u={...r,common:{...r.common,issues:[]},parent:null},d=c._parseSync({data:r.data,path:r.path,parent:u});if(d.status==="valid")return d;d.status==="dirty"&&!i&&(i={result:d,ctx:u}),u.common.issues.length&&a.push(u.common.issues)}if(i)return r.common.issues.push(...i.ctx.common.issues),i.result;const o=a.map(c=>new ft(c));return F(r,{code:R.invalid_union,unionErrors:o}),U}}get options(){return this._def.options}}dn.create=(t,e)=>new dn({options:t,typeName:B.ZodUnion,...H(e)});const ct=t=>t instanceof Es?ct(t.schema):t instanceof Pt?ct(t.innerType()):t instanceof pn?[t.value]:t instanceof Mt?t.options:t instanceof Os?Y.objectValues(t.enum):t instanceof gn?ct(t._def.innerType):t instanceof xs?[void 0]:t instanceof ln?[null]:t instanceof dt?[void 0,...ct(t.unwrap())]:t instanceof $t?[null,...ct(t.unwrap())]:t instanceof Yo||t instanceof bn?ct(t.unwrap()):t instanceof yn?ct(t._def.innerType):[];class ai extends K{_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==M.object)return F(r,{code:R.invalid_type,expected:M.object,received:r.parsedType}),U;const n=this.discriminator,s=r.data[n],i=this.optionsMap.get(s);return i?r.common.async?i._parseAsync({data:r.data,path:r.path,parent:r}):i._parseSync({data:r.data,path:r.path,parent:r}):(F(r,{code:R.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),U)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){const s=new Map;for(const i of r){const a=ct(i.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const o of a){if(s.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);s.set(o,i)}}return new ai({typeName:B.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:s,...H(n)})}}function ks(t,e){const r=yt(t),n=yt(e);if(t===e)return{valid:!0,data:t};if(r===M.object&&n===M.object){const s=Y.objectKeys(e),i=Y.objectKeys(t).filter(o=>s.indexOf(o)!==-1),a={...t,...e};for(const o of i){const c=ks(t[o],e[o]);if(!c.valid)return{valid:!1};a[o]=c.data}return{valid:!0,data:a}}else if(r===M.array&&n===M.array){if(t.length!==e.length)return{valid:!1};const s=[];for(let i=0;i<t.length;i++){const a=t[i],o=e[i],c=ks(a,o);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return r===M.date&&n===M.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}class hn extends K{_parse(e){const{status:r,ctx:n}=this._processInputParams(e),s=(i,a)=>{if(aa(i)||aa(a))return U;const o=ks(i.value,a.value);return o.valid?((oa(i)||oa(a))&&r.dirty(),{status:r.value,value:o.data}):(F(n,{code:R.invalid_intersection_types}),U)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([i,a])=>s(i,a)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}hn.create=(t,e,r)=>new hn({left:t,right:e,typeName:B.ZodIntersection,...H(r)});class Dt extends K{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.array)return F(n,{code:R.invalid_type,expected:M.array,received:n.parsedType}),U;if(n.data.length<this._def.items.length)return F(n,{code:R.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),U;!this._def.rest&&n.data.length>this._def.items.length&&(F(n,{code:R.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());const i=[...n.data].map((a,o)=>{const c=this._def.items[o]||this._def.rest;return c?c._parse(new nt(n,a,n.path,o)):null}).filter(a=>!!a);return n.common.async?Promise.all(i).then(a=>je.mergeArray(r,a)):je.mergeArray(r,i)}get items(){return this._def.items}rest(e){return new Dt({...this._def,rest:e})}}Dt.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Dt({items:t,typeName:B.ZodTuple,rest:null,...H(e)})};class fn extends K{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.object)return F(n,{code:R.invalid_type,expected:M.object,received:n.parsedType}),U;const s=[],i=this._def.keyType,a=this._def.valueType;for(const o in n.data)s.push({key:i._parse(new nt(n,o,n.path,o)),value:a._parse(new nt(n,n.data[o],n.path,o)),alwaysSet:o in n.data});return n.common.async?je.mergeObjectAsync(r,s):je.mergeObjectSync(r,s)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof K?new fn({keyType:e,valueType:r,typeName:B.ZodRecord,...H(n)}):new fn({keyType:ut.create(),valueType:e,typeName:B.ZodRecord,...H(r)})}}class ha extends K{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.map)return F(n,{code:R.invalid_type,expected:M.map,received:n.parsedType}),U;const s=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([o,c],u)=>({key:s._parse(new nt(n,o,n.path,[u,"key"])),value:i._parse(new nt(n,c,n.path,[u,"value"]))}));if(n.common.async){const o=new Map;return Promise.resolve().then(async()=>{for(const c of a){const u=await c.key,d=await c.value;if(u.status==="aborted"||d.status==="aborted")return U;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),o.set(u.value,d.value)}return{status:r.value,value:o}})}else{const o=new Map;for(const c of a){const u=c.key,d=c.value;if(u.status==="aborted"||d.status==="aborted")return U;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),o.set(u.value,d.value)}return{status:r.value,value:o}}}}ha.create=(t,e,r)=>new ha({valueType:e,keyType:t,typeName:B.ZodMap,...H(r)});class xr extends K{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.set)return F(n,{code:R.invalid_type,expected:M.set,received:n.parsedType}),U;const s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(F(n,{code:R.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),r.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(F(n,{code:R.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),r.dirty());const i=this._def.valueType;function a(c){const u=new Set;for(const d of c){if(d.status==="aborted")return U;d.status==="dirty"&&r.dirty(),u.add(d.value)}return{status:r.value,value:u}}const o=[...n.data.values()].map((c,u)=>i._parse(new nt(n,c,n.path,u)));return n.common.async?Promise.all(o).then(c=>a(c)):a(o)}min(e,r){return new xr({...this._def,minSize:{value:e,message:P.toString(r)}})}max(e,r){return new xr({...this._def,maxSize:{value:e,message:P.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}}xr.create=(t,e)=>new xr({valueType:t,minSize:null,maxSize:null,typeName:B.ZodSet,...H(e)});class Es extends K{get schema(){return this._def.getter()}_parse(e){const{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}}Es.create=(t,e)=>new Es({getter:t,typeName:B.ZodLazy,...H(e)});class pn extends K{_parse(e){if(e.data!==this._def.value){const r=this._getOrReturnCtx(e);return F(r,{received:r.data,code:R.invalid_literal,expected:this._def.value}),U}return{status:"valid",value:e.data}}get value(){return this._def.value}}pn.create=(t,e)=>new pn({value:t,typeName:B.ZodLiteral,...H(e)});function Qo(t,e){return new Mt({values:t,typeName:B.ZodEnum,...H(e)})}class Mt extends K{_parse(e){if(typeof e.data!="string"){const r=this._getOrReturnCtx(e),n=this._def.values;return F(r,{expected:Y.joinValues(n),received:r.parsedType,code:R.invalid_type}),U}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const r=this._getOrReturnCtx(e),n=this._def.values;return F(r,{received:r.data,code:R.invalid_enum_value,options:n}),U}return Ve(e.data)}get options(){return this._def.values}get enum(){const e={};for(const r of this._def.values)e[r]=r;return e}get Values(){const e={};for(const r of this._def.values)e[r]=r;return e}get Enum(){const e={};for(const r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return Mt.create(e,{...this._def,...r})}exclude(e,r=this._def){return Mt.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}}Mt.create=Qo;class Os extends K{_parse(e){const r=Y.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==M.string&&n.parsedType!==M.number){const s=Y.objectValues(r);return F(n,{expected:Y.joinValues(s),received:n.parsedType,code:R.invalid_type}),U}if(this._cache||(this._cache=new Set(Y.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const s=Y.objectValues(r);return F(n,{received:n.data,code:R.invalid_enum_value,options:s}),U}return Ve(e.data)}get enum(){return this._def.values}}Os.create=(t,e)=>new Os({values:t,typeName:B.ZodNativeEnum,...H(e)});class mn extends K{unwrap(){return this._def.type}_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==M.promise&&r.common.async===!1)return F(r,{code:R.invalid_type,expected:M.promise,received:r.parsedType}),U;const n=r.parsedType===M.promise?r.data:Promise.resolve(r.data);return Ve(n.then(s=>this._def.type.parseAsync(s,{path:r.path,errorMap:r.common.contextualErrorMap})))}}mn.create=(t,e)=>new mn({type:t,typeName:B.ZodPromise,...H(e)});class Pt extends K{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===B.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:r,ctx:n}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:a=>{F(n,a),a.fatal?r.abort():r.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){const a=s.transform(n.data,i);if(n.common.async)return Promise.resolve(a).then(async o=>{if(r.value==="aborted")return U;const c=await this._def.schema._parseAsync({data:o,path:n.path,parent:n});return c.status==="aborted"?U:c.status==="dirty"||r.value==="dirty"?mr(c.value):c});{if(r.value==="aborted")return U;const o=this._def.schema._parseSync({data:a,path:n.path,parent:n});return o.status==="aborted"?U:o.status==="dirty"||r.value==="dirty"?mr(o.value):o}}if(s.type==="refinement"){const a=o=>{const c=s.refinement(o,i);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(n.common.async===!1){const o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?U:(o.status==="dirty"&&r.dirty(),a(o.value),{status:r.value,value:o.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>o.status==="aborted"?U:(o.status==="dirty"&&r.dirty(),a(o.value).then(()=>({status:r.value,value:o.value}))))}if(s.type==="transform")if(n.common.async===!1){const a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!er(a))return U;const o=s.transform(a.value,i);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:o}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>er(a)?Promise.resolve(s.transform(a.value,i)).then(o=>({status:r.value,value:o})):U);Y.assertNever(s)}}Pt.create=(t,e,r)=>new Pt({schema:t,typeName:B.ZodEffects,effect:e,...H(r)});Pt.createWithPreprocess=(t,e,r)=>new Pt({schema:e,effect:{type:"preprocess",transform:t},typeName:B.ZodEffects,...H(r)});class dt extends K{_parse(e){return this._getType(e)===M.undefined?Ve(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}dt.create=(t,e)=>new dt({innerType:t,typeName:B.ZodOptional,...H(e)});class $t extends K{_parse(e){return this._getType(e)===M.null?Ve(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}$t.create=(t,e)=>new $t({innerType:t,typeName:B.ZodNullable,...H(e)});class gn extends K{_parse(e){const{ctx:r}=this._processInputParams(e);let n=r.data;return r.parsedType===M.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}}gn.create=(t,e)=>new gn({innerType:t,typeName:B.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...H(e)});class yn extends K{_parse(e){const{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return cn(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new ft(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new ft(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}yn.create=(t,e)=>new yn({innerType:t,typeName:B.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...H(e)});class fa extends K{_parse(e){if(this._getType(e)!==M.nan){const n=this._getOrReturnCtx(e);return F(n,{code:R.invalid_type,expected:M.nan,received:n.parsedType}),U}return{status:"valid",value:e.data}}}fa.create=t=>new fa({typeName:B.ZodNaN,...H(t)});class Yo extends K{_parse(e){const{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}}class oi extends K{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?U:i.status==="dirty"?(r.dirty(),mr(i.value)):this._def.out._parseAsync({data:i.value,path:n.path,parent:n})})();{const s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?U:s.status==="dirty"?(r.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,r){return new oi({in:e,out:r,typeName:B.ZodPipeline})}}class bn extends K{_parse(e){const r=this._def.innerType._parse(e),n=s=>(er(s)&&(s.value=Object.freeze(s.value)),s);return cn(r)?r.then(s=>n(s)):n(r)}unwrap(){return this._def.innerType}}bn.create=(t,e)=>new bn({innerType:t,typeName:B.ZodReadonly,...H(e)});var B;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(B||(B={}));const Ft=ut.create,pa=tr.create,ci=As.create,fh=ln.create,Ir=Is.create;_t.create;const ph=et.create,lt=me.create,ui=dn.create,mh=ai.create;hn.create;Dt.create;const kr=fn.create,qr=pn.create,vn=Mt.create;mn.create;dt.create;$t.create;const gh=["get","list","create","update","delete"],yh=lt({uid:Ft(),token:kr(Ir()).optional()}),bh=lt({function:vn(["get","exists"]).describe("Firestore function to mock"),path:Ft().describe('Document path, e.g. "users/alice"'),result:ui([kr(Ir()),ci()]).describe("Document data for get, boolean for exists")}),vh=mh("kind",[lt({kind:qr("create")}),lt({kind:qr("set"),merge:ci()}),lt({kind:qr("update")}),lt({kind:qr("delete")})]),wh=lt({limit:pa().optional(),offset:pa().optional(),orderBy:Ft().optional()});lt({description:Ft().describe("Human-readable description of what this test verifies"),expectation:vn(["ALLOW","DENY"]).describe("Expected outcome"),method:vn(gh).describe("Firestore method to test"),path:Ft().describe('Document path, e.g. "users/alice"'),auth:ui([yh,fh()]).optional().describe("Auth context; null or omitted for unauthenticated"),data:kr(Ir()).optional().describe("request.resource.data for write operations"),resource:kr(Ir()).optional().describe("Existing document data (resource.data)"),functionMocks:ph(bh).optional().describe("Mock get()/exists() calls in rules"),query:wh.optional().describe("request.query payload (list ops only): limit/offset/orderBy."),requestTime:Ft().optional().describe("Override for request.time (ISO-8601). Defaults to wallclock."),writeMode:vh.optional().describe("Optional write-mode override; controls update merge semantics and getAfter() projection.")});function Er(t){if(t.decision==="UNSUPPORTED")return;const e=t.decision==="ALLOW",r=e?t.trace.find(s=>s.verdict==="ALLOW"):t.trace.find(s=>s.verdict==="DENY"||s.verdict==="ERROR")??t.trace[t.trace.length-1];if(!r)return;const n={verdict:e?"allow":"deny"};return r.line!==void 0&&(n.line=r.line),r.conditionText!==void 0&&(n.expression=r.conditionText),r.expressionTrace!==void 0&&(n.expressionTrace=r.expressionTrace),n.line!==void 0||n.expression!==void 0||n.expressionTrace!==void 0?n:void 0}function Se(t){const e=[];for(const r of t.notes)e.push(r);for(const r of t.trace){const n=r.operations.join(","),s=`Rule #${r.ruleIndex} (${n})`;r.verdict==="ALLOW"?e.push(`${s} → ALLOW`):r.verdict==="DENY"?e.push(`${s} → deny`):r.verdict==="UNSUPPORTED"?e.push(`${s} → unsupported: ${r.message??""}`):e.push(`${s} → error: ${r.message??""}`)}return e.push(`Simulated: ${t.decision}`),e}lt({function:vn(["get","exists"]).describe("Cross-service Firestore function to mock"),path:Ft().describe('Firestore document path in collection/doc form, e.g. "users/alice"'),result:ui([kr(Ir()),ci()]).describe("Document fields for get, boolean for exists")});const Xo={atomic:["cloud.firestore"],auth:["cloud.firestore","firebase.storage"],content:["cloud.firestore"],counters:["cloud.firestore"],geometry:["cloud.firestore"],joining:["cloud.firestore"],lifecycle:["cloud.firestore"],lobby:["cloud.firestore"],membership:["cloud.firestore","firebase.storage"],spaces:["cloud.firestore"],state:["cloud.firestore"],"storage/metadata":["firebase.storage"],"storage/objects":["firebase.storage"],"storage/time":["firebase.storage"],"storage/uploads":["firebase.storage"],timing:["cloud.firestore"],transitions:["cloud.firestore"],turns:["cloud.firestore"],validation:["cloud.firestore"]};Object.freeze(Object.keys(Xo).sort());const Sh={atomic:[],auth:["storage-rules#125","firestore-rules#189"],content:[],counters:[],geometry:[],joining:[],lifecycle:[],lobby:[],membership:["storage-rules#125","firestore-rules#189"],spaces:[],state:[],"storage/metadata":["storage-rules#132"],"storage/objects":["storage-rules#132"],"storage/time":["storage-rules#132"],"storage/uploads":["storage-rules#132"],timing:[],transitions:[],turns:[],validation:[]},ec=["exists","existsAfter","get","getAfter"],_h=["addedKeys","affectedKeys","bind","changedKeys","concat","date","day","dayOfWeek","dayOfYear","diff","difference","distance","get","hasAll","hasAny","hasOnly","hours","intersection","join","keys","latitude","longitude","lower","matches","minutes","month","nanos","removeAll","removedKeys","replace","seconds","size","split","time","toBase64","toHexString","toMillis","toSet","toUtf8","trim","unchangedKeys","union","upper","values","year"],Ah={addedKeys:["mapdiff"],affectedKeys:["mapdiff"],bind:["path"],changedKeys:["mapdiff"],concat:["list"],date:["timestamp"],day:["timestamp"],dayOfWeek:["timestamp"],dayOfYear:["timestamp"],diff:["map"],difference:["set"],distance:["latlng"],get:["map"],hasAll:["list","set"],hasAny:["list","set"],hasOnly:["list","set"],hours:["timestamp"],intersection:["set"],join:["list"],keys:["map"],latitude:["latlng"],longitude:["latlng"],lower:["string"],matches:["string"],minutes:["timestamp"],month:["timestamp"],nanos:["duration","timestamp"],removeAll:["list"],removedKeys:["mapdiff"],replace:["string"],seconds:["duration","timestamp"],size:["bytes","list","map","set","string"],split:["string"],time:["timestamp"],toBase64:["bytes"],toHexString:["bytes"],toMillis:["timestamp"],toSet:["list"],toUtf8:["string"],trim:["string"],unchangedKeys:["mapdiff"],union:["set"],upper:["string"],values:["map"],year:["timestamp"]},tc={cast:["float","int","path","string"],duration:["abs","time","value"],hashing:["crc32","crc32c","md5","sha256"],latlng:["value"],math:["abs","ceil","floor","isNaN","pow","round","sqrt"],timestamp:["date","value"]},xh=["request","request.auth","request.auth.token","request.auth.uid","request.method","request.path","request.resource","request.resource.contentType","request.resource.metadata","request.resource.size","request.time","resource","resource.bucket","resource.contentType","resource.generation","resource.metadata","resource.metageneration","resource.name","resource.size","resource.timeCreated","resource.updated"],Ih=["get","hasAll","keys","matches","size","split"],kh={get:["map"],hasAll:["set"],keys:["map"],matches:["string"],size:["list","map","string"],split:["string"]},rc={duration:["value"],firestore:["exists","get"],timestamp:["date","value"]},Eh=new Set(xh),Oh=["request.auth.token","request.resource.metadata","resource.metadata"];function Ch(t,e){if(e.length===1)return!0;if(t==="firebase.storage"){const r=e.join(".");return Eh.has(r)||Oh.some(n=>r.startsWith(`${n}.`))}return e[0]==="request"?e[1]==="auth"||e[1]==="query"?!0:["time","method","path"].includes(e[1])?e.length===2:e[1]==="resource"&&(e.length===2||e[2]==="data"):e[0]==="resource"&&(e.length===1||e[1]==="data")}function wn(t,e){return e[0]==="request"&&e[1]==="auth"&&e[2]==="token"?!0:t==="firebase.storage"?e[0]==="resource"&&e[1]==="metadata"||e[0]==="request"&&e[1]==="resource"&&e[2]==="metadata":e[0]==="resource"&&e[1]==="data"||e[0]==="request"&&e[1]==="resource"&&e[2]==="data"||e[0]==="request"&&e[1]==="query"}function Th(t,e){if(!e||e==="unknown-ambient")return null;const r=e.join(".");return r==="request.resource"||r==="resource"?"resource":r==="request.auth"||r==="request.auth.token"||t==="cloud.firestore"&&(r==="request.resource.data"||r==="resource.data"||r==="request.query")||r==="request.resource.metadata"||r==="resource.metadata"?"map":r==="request.auth.uid"||r==="request.method"||r==="request.resource.contentType"||r==="resource.contentType"||t==="firebase.storage"&&(r.startsWith("request.resource.metadata.")||r.startsWith("resource.metadata."))?"string":r==="request.path"?"path":r==="request.time"||r==="resource.timeCreated"||r==="resource.updated"?"timestamp":["request.resource.size","resource.size","resource.generation","resource.metageneration"].includes(r)?"number":null}function ma(t){if(t.type!=="methodCall")return null;if(t.object.type==="identifier"){if(t.object.name==="firestore"){if(t.method==="get")return"document";if(t.method==="exists")return"boolean"}if(t.object.name==="duration")return"duration";if(t.object.name==="timestamp")return"timestamp";if(t.object.name==="latlng")return"latlng";if(t.object.name==="hashing")return"bytes";if(t.object.name==="math")return"number";if(t.object.name==="cast"){if(t.method==="string")return"string";if(t.method==="path")return"path";if(t.method==="int"||t.method==="float")return"number"}}return["lower","upper","trim","replace","join","toBase64","toHexString"].includes(t.method)?"string":["matches","hasAny","hasAll","hasOnly"].includes(t.method)?"boolean":["concat","removeAll","split","values"].includes(t.method)?"list":["keys","toSet","addedKeys","removedKeys","changedKeys","affectedKeys","unchangedKeys","difference","union","intersection"].includes(t.method)?"set":t.method==="diff"?"mapdiff":t.method==="get"?null:t.method==="toUtf8"?"bytes":t.method==="date"?"timestamp":["size","year","month","day","hours","minutes","seconds","nanos","dayOfWeek","dayOfYear","toMillis","latitude","longitude","distance"].includes(t.method)?"number":null}const Rh=new Set(ec),Nh=Object.fromEntries(Object.entries(tc).map(([t,e])=>[t,new Set(e)])),Fh=Object.fromEntries(Object.entries(rc).map(([t,e])=>[t,new Set(e)]));function at(t,e){return t.some(r=>_e(r,e)!==null)?"unknown-ambient":null}function nc(t,e,r){const n=r.declarations?.get(t),s=new Map(n?.aliases),i=new Map(n?.receiverTypes);return t.parameters.forEach((a,o)=>{s.set(a,e[o]?.provenance??null),i.set(a,e[o]?.receiverType??null)}),{aliases:s,receiverTypes:i,functions:n?.functions??r.functions,service:r.service,stack:new Set([...r.stack,t.name]),declarations:r.declarations}}function rr(t,e){return{expression:t,provenance:_e(t,e),receiverType:he(t,e)}}function _e(t,e){if(t.type==="identifier")return t.name==="request"||t.name==="resource"?[t.name]:e.aliases.get(t.name)??null;if(t.type==="memberAccess"){const r=_e(t.object,e);return r==="unknown-ambient"?r:r?[...r,t.property]:null}if(t.type==="bracketAccess"){const r=_e(t.object,e);return!r||r==="unknown-ambient"?r:t.index.type==="literal"&&typeof t.index.value=="string"?[...r,t.index.value]:[...r,"*"]}if(t.type==="ternary"){const r=_e(t.consequent,e),n=_e(t.alternate,e);return!r&&!n?null:Array.isArray(r)&&Array.isArray(n)&&r.join(".")===n.join(".")?r:"unknown-ambient"}if(t.type==="functionCall"){const r=e.functions.get(t.name),n=t.args.map(i=>rr(i,e));if(!r&&Rh.has(t.name))return null;if(!r||e.stack.has(r.name))return n.some(({provenance:i})=>i!==null)?"unknown-ambient":null;const s=nc(r,n,e);for(const i of r.lets){const a=rr(i.value,s);s.aliases.set(i.name,a.provenance),s.receiverTypes.set(i.name,a.receiverType)}return _e(r.body,s)}if(t.type==="methodCall"&&t.object.type==="identifier"&&t.object.name==="firestore"&&(t.method==="get"||t.method==="exists"))return null;switch(t.type){case"literal":return null;case"methodCall":return at([t.object,...t.args],e);case"sliceAccess":return at([t.object,t.start,t.end],e);case"binaryOp":return at([t.left,t.right],e);case"unaryOp":return at([t.operand],e);case"inExpr":return at([t.element,t.collection],e);case"isExpr":return at([t.value],e);case"listLiteral":return at(t.elements,e);case"mapLiteral":return at(t.entries.flatMap(({key:r,value:n})=>[r,n]),e);case"pathLiteral":return at(t.segments.filter(r=>typeof r!="string"),e);default:return null}}function he(t,e){const r=Th(e.service,_e(t,e));if(r)return r;switch(t.type){case"identifier":{const n=e.receiverTypes.get(t.name);return n||((e.service==="cloud.firestore"?Nh:Fh)[t.name]||t.name==="firestore"?"namespace":null)}case"literal":return t.value===null?"null":typeof t.value=="string"?"string":typeof t.value=="number"?"number":typeof t.value=="boolean"?"boolean":null;case"listLiteral":return"list";case"mapLiteral":return"map";case"pathLiteral":return"path";case"memberAccess":{const n=he(t.object,e);if(n==="mixed")return"mixed";if(t.property==="data"&&n==="document")return"map";if(t.object.type==="mapLiteral"){const s=t.object.entries.find(({key:i})=>i.type==="literal"&&i.value===t.property);return s?he(s.value,e):null}return null}case"bracketAccess":{const n=he(t.object,e);if(n==="mixed")return"mixed";if(t.object.type==="listLiteral"&&t.index.type==="literal"&&typeof t.index.value=="number"&&Number.isInteger(t.index.value)){const i=t.object.elements[t.index.value];return i?he(i,e):null}if(t.object.type==="mapLiteral"&&t.index.type==="literal"){const i=t.index.value,a=t.object.entries.find(({key:o})=>o.type==="literal"&&o.value===i);return a?he(a.value,e):null}if(n==="string")return"string";const s=_e(t.object,e);return e.service==="firebase.storage"&&Array.isArray(s)&&(s.join(".")==="request.resource.metadata"||s.join(".")==="resource.metadata")?"string":null}case"sliceAccess":{const n=he(t.object,e);return n==="mixed"?"mixed":n==="list"||n==="string"?n:null}case"methodCall":{const n=ma(t);if(t.object.type==="identifier"&&n)return n;if(t.method==="get"){const s=_e(t.object,e);if(e.service==="firebase.storage"&&Array.isArray(s)&&(s.join(".")==="request.resource.metadata"||s.join(".")==="resource.metadata"))return"string";const i=t.args[1];if(t.object.type==="mapLiteral"&&t.args[0]?.type==="literal"){const a=t.args[0].value,o=t.object.entries.find(({key:c})=>c.type==="literal"&&c.value===a);return o?he(o.value,e):i?he(i,e):null}return i&&he(i,e)?"mixed":null}return ma(t)}case"binaryOp":{const n=he(t.left,e),s=he(t.right,e);return t.op==="+"&&(n==="string"||s==="string")?"string":["==","!=","<","<=",">",">=","&&","||"].includes(t.op)?"boolean":["+","-","*","/","%"].includes(t.op)&&n==="number"&&s==="number"?"number":null}case"unaryOp":return t.op==="!"?"boolean":t.op==="-"&&he(t.operand,e)==="number"?"number":null;case"inExpr":case"isExpr":return"boolean";case"ternary":{const n=he(t.consequent,e),s=he(t.alternate,e);return!n&&!s?null:n===s?n:"mixed"}case"functionCall":{const n=e.functions.get(t.name);if(!n&&e.service==="cloud.firestore"){if(t.name==="get"||t.name==="getAfter")return"document";if(t.name==="exists")return"boolean"}if(!n||e.stack.has(n.name))return null;const s=nc(n,t.args.map(i=>rr(i,e)),e);for(const i of n.lets){const a=rr(i.value,s);s.aliases.set(i.name,a.provenance),s.receiverTypes.set(i.name,a.receiverType)}return he(n.body,s)}default:return null}}function Lh(t){return t.match(/^\.\/stdlib\/(.+?)(?:\.rules)?$/)?.[1]??t}function jh(t,e,r){const n=Lh(e),s=Xo[n];return s?s.includes(t)?null:`Function '${r}' from module '${e}' is not compatible with service '${t}'`:null}function Dh(t){throw new Error(`Unhandled Rules expression: ${JSON.stringify(t)}`)}const Mh=new Set(ec),Ph=new Set(_h),$h=Object.fromEntries(Object.entries(tc).map(([t,e])=>[t,new Set(e)])),qh=new Set(Ih),Uh=Object.fromEntries(Object.entries(rc).map(([t,e])=>[t,new Set(e)]));function Sn(t,e){return t==="unknown-ambient"?"binding '<derived ambient value>'":t&&!Ch(e,t)?`binding '${t.join(".")}'`:null}function Bh(t,e,r,n,s){if(e!=="get"&&e!=="keys"&&e!=="values")return null;const i=_e(t,s);if(i==="unknown-ambient")return"binding '<derived ambient value>'";if(!i)return null;if(e==="get"){const a=r[0];if(a?.type==="literal"&&typeof a.value=="string")return Sn([...i,a.value],n);if(!wn(n,i))return`binding '${i.join(".")}.get(...)'`}return(e==="keys"||e==="values")&&!wn(n,i)?`binding '${i.join(".")}.${e}()'`:null}function zh(t,e,r,n){const s=_e(t,n),i=he(t,n);if(!i){if(s==="unknown-ambient")return"binding '<derived ambient receiver>'";let c=t;for(;c.type==="memberAccess"||c.type==="bracketAccess"||c.type==="methodCall"&&c.method==="get";)c=c.object;const u=he(c,n);return u==="map"||u==="list"||u==="document"?`method '.${e}()' has an unresolved projected receiver`:null}const o=(r==="cloud.firestore"?Ah:kh)[e];return o?.includes(i)?null:`method '.${e}()' requires ${o?.join("|")??"an accepted"} receiver, got ${i}`}function Vh(t,e,r,n){const s=_e(e,n);return s==="unknown-ambient"?"binding '<derived ambient value>'":s?t.type==="literal"&&typeof t.value=="string"?Sn([...s,t.value],r):wn(r,s)?null:`binding '<value> in ${s.join(".")}'`:null}function ga(t,e,r){const n=s=>{switch(s.type){case"memberAccess":{const i=Sn(_e(s,r),e);return i||n(s.object)}case"functionCall":{const i=r.functions.get(s.name);if(!i&&e==="firebase.storage")return`function '${s.name}()'`;if(!i&&!Mh.has(s.name))return`function '${s.name}()'`;for(const a of s.args){const o=n(a);if(o)return o}if(i&&!r.stack.has(i.name)){const a=new Map,o=new Map;i.parameters.forEach((u,d)=>{const l=s.args[d];a.set(u,l?_e(l,r):null),o.set(u,l?he(l,r):null)});const c=sc(i,e,{aliases:a,receiverTypes:o,functions:r.functions,service:e,stack:new Set([...r.stack,i.name])});if(c)return c}return null}case"methodCall":{if(s.object.type==="identifier"&&!r.aliases.has(s.object.name)){const u=(e==="cloud.firestore"?$h:Uh)[s.object.name];if(u){if(!u.has(s.method))return`method '${s.object.name}.${s.method}()'`;for(const d of s.args){const l=n(d);if(l)return l}return null}return s.object.name==="firestore"?`method 'firestore.${s.method}()'`:`namespace '${s.object.name}'`}if(!(e==="cloud.firestore"?Ph:qh).has(s.method))return`method '.${s.method}()'`;const a=zh(s.object,s.method,e,r);if(a)return a;const o=Bh(s.object,s.method,s.args,e,r);return o||(n(s.object)??s.args.map(n).find(Boolean)??null)}case"binaryOp":return n(s.left)??n(s.right);case"unaryOp":return n(s.operand);case"bracketAccess":{const i=_e(s.object,r);if(i==="unknown-ambient")return"binding '<derived ambient value>[...]'";const a=s.index.type==="literal"&&typeof s.index.value=="string";if(i&&!a)return wn(e,i)?n(s.object)??n(s.index):`binding '${i.join(".")}[...]'`;const o=Sn(_e(s,r),e);return o||(n(s.object)??n(s.index))}case"sliceAccess":return n(s.object)??n(s.start)??n(s.end);case"ternary":return n(s.condition)??n(s.consequent)??n(s.alternate);case"inExpr":return Vh(s.element,s.collection,e,r)??n(s.element)??n(s.collection);case"isExpr":return n(s.value);case"listLiteral":return s.elements.map(n).find(Boolean)??null;case"mapLiteral":for(const i of s.entries){const a=n(i.key)??n(i.value);if(a)return a}return null;case"pathLiteral":for(const i of s.segments)if(typeof i!="string"){const a=n(i);if(a)return a}return null;case"literal":return null;case"identifier":return s.name==="request"||s.name==="resource"||r.aliases.has(s.name)?null:`identifier '${s.name}'`;default:return Dh(s)}};return n(t)}function sc(t,e,r){const n=new Map(r.aliases),s=new Map(r.receiverTypes),i={...r,aliases:n,receiverTypes:s};for(const a of t.lets){const o=ga(a.value,e,i);if(o)return o;n.set(a.name,_e(a.value,i)),s.set(a.name,he(a.value,i))}return ga(t.body,e,i)}function Wh(t,e,r=new Map([[t.name,t]]),n=[]){const s={aliases:new Map,receiverTypes:new Map,functions:r,service:e,stack:new Set([t.name])};return sc(t,e,{aliases:new Map(t.parameters.map((i,a)=>[i,a<n.length?n[a]?.provenance??null:null])),receiverTypes:new Map(t.parameters.map((i,a)=>[i,n[a]?he(n[a].expression,s)??n[a].receiverType??null:null])),functions:r,service:e,stack:new Set([t.name])})}function Hh(t){throw new Error(`Unhandled Rules expression: ${JSON.stringify(t)}`)}function Gh(t){return t.replace(/^\.\.\//,"_").replace(/^\.\//,"").replace(/[.\/-]/g,"_")}function re(t,e){switch(t.type){case"functionCall":{const r=e.get(t.name)??t.name,n=t.args.map(s=>re(s,e));return r===t.name&&n.every((s,i)=>s===t.args[i])?t:{...t,name:r,args:n}}case"binaryOp":{const r=re(t.left,e),n=re(t.right,e);return r===t.left&&n===t.right?t:{...t,left:r,right:n}}case"unaryOp":{const r=re(t.operand,e);return r===t.operand?t:{...t,operand:r}}case"methodCall":{const r=re(t.object,e),n=t.args.map(s=>re(s,e));return r===t.object&&n.every((s,i)=>s===t.args[i])?t:{...t,object:r,args:n}}case"memberAccess":{const r=re(t.object,e);return r===t.object?t:{...t,object:r}}case"bracketAccess":{const r=re(t.object,e),n=re(t.index,e);return r===t.object&&n===t.index?t:{...t,object:r,index:n}}case"sliceAccess":{const r=re(t.object,e),n=re(t.start,e),s=re(t.end,e);return r===t.object&&n===t.start&&s===t.end?t:{...t,object:r,start:n,end:s}}case"ternary":{const r=re(t.condition,e),n=re(t.consequent,e),s=re(t.alternate,e);return r===t.condition&&n===t.consequent&&s===t.alternate?t:{...t,condition:r,consequent:n,alternate:s}}case"inExpr":{const r=re(t.element,e),n=re(t.collection,e);return r===t.element&&n===t.collection?t:{...t,element:r,collection:n}}case"isExpr":{const r=re(t.value,e);return r===t.value?t:{...t,value:r}}case"listLiteral":{const r=t.elements.map(n=>re(n,e));return r.every((n,s)=>n===t.elements[s])?t:{...t,elements:r}}case"mapLiteral":{const r=t.entries.map(n=>{const s=re(n.key,e),i=re(n.value,e);return s===n.key&&i===n.value?n:{key:s,value:i}});return r.every((n,s)=>n===t.entries[s])?t:{...t,entries:r}}case"pathLiteral":{const r=t.segments.map(n=>typeof n=="string"?n:re(n,e));return r.every((n,s)=>n===t.segments[s])?t:{...t,segments:r}}case"literal":case"identifier":return t;default:return Hh(t)}}function Kh(t,e){const r=Gh(e),n=new Map;for(const s of t)s.exported||n.set(s.name,`${r}__${s.name}`);return n.size===0?t:t.map(s=>{const i=re(s.body,n),a=s.lets.map(c=>{const u=re(c.value,n);return u===c.value?c:{...c,value:u}}),o=s.exported?s.name:n.get(s.name)??s.name;return i===s.body&&a===s.lets&&o===s.name?s:{...s,name:o,body:i,lets:a}})}function Zh(t){throw new Error(`Unhandled Rules expression: ${JSON.stringify(t)}`)}function li(t){const e=[],r=n=>{switch(n.type){case"functionCall":e.push(n),n.args.forEach(r);break;case"binaryOp":r(n.left),r(n.right);break;case"unaryOp":r(n.operand);break;case"methodCall":r(n.object),n.args.forEach(r);break;case"memberAccess":r(n.object);break;case"bracketAccess":r(n.object),r(n.index);break;case"sliceAccess":r(n.object),r(n.start),r(n.end);break;case"ternary":r(n.condition),r(n.consequent),r(n.alternate);break;case"inExpr":r(n.element),r(n.collection);break;case"isExpr":r(n.value);break;case"listLiteral":n.elements.forEach(r);break;case"mapLiteral":n.entries.forEach(({key:s,value:i})=>{r(s),r(i)});break;case"pathLiteral":n.segments.forEach(s=>{typeof s!="string"&&r(s)});break;case"literal":case"identifier":break;default:Zh(n)}};return r(t),e}function Jh(t){return{expression:t.expression,provenance:t.provenance,receiverType:!t.receiverType||t.receiverType==="mixed"?"unknown":t.receiverType}}function Qh(t,e){const r=[],n=new Map,s=t.service.name==="firebase.storage"?"firebase.storage":"cloud.firestore",i=(l,f=new Set)=>({aliases:new Map(l.aliases),receiverTypes:new Map(l.receiverTypes),functions:l.functions,service:s,stack:f,declarations:n}),a=(l,f,y)=>{if(y.has(l.name))return;const b=n.get(l);if(!b)return;const S=new Map(b.aliases),j=new Map(b.receiverTypes);l.parameters.forEach((L,k)=>{S.set(L,f[k]?.provenance??null),j.set(L,f[k]?.receiverType??null)});const T=i({aliases:S,receiverTypes:j,functions:b.functions},new Set([...y,l.name]));for(const L of l.lets){o(L.value,T);const k=rr(L.value,T);T.aliases.set(L.name,k.provenance),T.receiverTypes.set(L.name,k.receiverType)}o(l.body,T)},o=(l,f)=>{for(const y of li(l)){const b=y.args.map(j=>rr(j,f));y.name===e&&r.push({arguments:b.map(Jh)});const S=f.functions.get(y.name);S&&a(S,b,f.stack)}},c=new Map((t.functions??[]).map(l=>[l.name,l])),u=new Map(c);for(const l of t.service.functions??[])u.set(l.name,l);for(const l of t.functions??[])n.set(l,{aliases:new Map,receiverTypes:new Map,functions:c});for(const l of t.service.functions??[])n.set(l,{aliases:new Map,receiverTypes:new Map,functions:u});const d=(l,f)=>{const y=new Map(f.receiverTypes);for(const T of l.path.segments)T.type==="wildcard"&&y.set(T.name,"string"),T.type==="recursive"&&y.set(T.name,"path");const b=new Map(f.functions),S={aliases:f.aliases,receiverTypes:y,functions:b};for(const T of l.functions)b.set(T.name,T),n.set(T,S);const j=i(S);for(const{condition:T}of l.allows)o(T,j);l.children.forEach(T=>d(T,S))};return d(t.service.match,{aliases:new Map,receiverTypes:new Map,functions:u}),r}function Et(t){return li(t).map(({name:e})=>e)}function Yh(t,e){return[...t.values()].flatMap(n=>[...n.lets.map(({value:s})=>s),n.body]).flatMap(li).filter(({name:n})=>n===e).map(({args:n})=>n)}function Xh(t,e,r){const n=yl(t);return n?{success:!0,functions:n,bundled:r}:{success:!1,error:{code:"PARSE_FAILED",message:`Failed to parse module '${e}'`}}}function ya(t){return t.startsWith("./")||t.startsWith("../")}function Cs(t){return/^\.\/stdlib\/([A-Za-z0-9_-]+(?:\/[A-Za-z0-9_-]+)*)\.rules$/.exec(t)?.[1]??null}function ef(t,e,r,n=new Set){if(r?.modules&&Object.prototype.hasOwnProperty.call(r.modules,e))return Xh(r.modules[e],e,n.has(e));if(ya(e)&&r?.basePath){const i=`${r.basePath}/${e}${e.endsWith(".rules")?"":".rules"}`;if(!Cs(e))return{success:!1,error:{code:"UNKNOWN_MODULE",message:`Module '${e}' not found at ${i}`}}}return Cs(e)?{success:!1,error:{code:"UNKNOWN_MODULE",message:`Module '${e}' not found`}}:ya(e)?{success:!1,error:{code:"UNKNOWN_MODULE",message:`Module '${e}' requires basePath for relative imports`}}:{success:!1,error:{code:"UNKNOWN_MODULE",message:`Module '${e}' not found`}}}function tf(t,e,r,n=new Set){const s=Xr(e);if(!s.ok){const{line:I,column:q,message:Z}=s.error;return{success:!1,error:{code:"PARSE_FAILED",message:`Failed to parse source at line ${I}, col ${q}: ${Z}`}}}const i=s.ast;if(i.version!=="2+modules")return{success:!1,error:{code:"NOT_MODULE_SOURCE",message:`Version '${i.version}' is not a module source`}};if(i.service.name!=="cloud.firestore"&&i.service.name!=="firebase.storage")return{success:!1,error:{code:"UNSUPPORTED_SERVICE",message:`Module resolution does not support service '${i.service.name}'`}};if(i.imports.length===0)return i.version="2",{success:!0,data:{resolved:en(i),modules:[],bundledModules:[],evidenceIds:[]}};const a=i.imports.find(I=>I.functions.length===0);if(a)return{success:!1,error:{code:"UNKNOWN_FUNCTION",message:`Import from '${a.module}' must request at least one function`}};const o=new Map,c=new Map,u=new Map,d=new Map,l=[],f=[],y=new Map;for(const I of i.imports){const q=ef(t,I.module,r,n);if(!q.success)return{success:!1,error:q.error};l.includes(I.module)||l.push(I.module),q.bundled&&!f.includes(I.module)&&f.push(I.module);const Z=new Set,pe=q.functions.find(J=>Z.has(J.name)?!0:(Z.add(J.name),!1));if(pe)return{success:!1,error:{code:"DUPLICATE_FUNCTION",message:`Module '${I.module}' defines duplicate function '${pe.name}'`}};const Q=q.functions.find(J=>Wr.has(J.name));if(Q)return{success:!1,error:{code:"DUPLICATE_FUNCTION",message:`Function '${Q.name}' from module '${I.module}' conflicts with a Rules builtin`}};const ve=new Set;for(const J of q.functions)J.exported||ve.add(J.name);y.set(I.module,ve);const zn=Kh(q.functions,I.module),Oi=new Set;for(const J of zn){if(Oi.has(J.name))return{success:!1,error:{code:"DUPLICATE_FUNCTION",message:`Module '${I.module}' defines conflicting function name '${J.name}'`}};Oi.add(J.name)}const fu=new Set(zn.filter(J=>J.exported).map(J=>J.name));for(const J of zn){const kt=d.get(J.name);if(kt&&kt!==I.module)return{success:!1,error:{code:"DUPLICATE_FUNCTION",message:`Function '${J.name}' from module '${I.module}' conflicts with module '${kt}'`}};if(d.set(J.name,I.module),c.set(J.name,J),J.exported){if(o.has(J.name)&&u.get(J.name)!==I.module)return{success:!1,error:{code:"DUPLICATE_FUNCTION",message:`Function '${J.name}' exported by both '${u.get(J.name)}' and '${I.module}'`}};o.set(J.name,J),u.set(J.name,I.module)}}for(const J of I.functions){if(!fu.has(J))return{success:!1,error:{code:"UNKNOWN_FUNCTION",message:y.get(I.module)?.has(J)?`Function '${J}' in module '${I.module}' is not exported`:`Function '${J}' not found in module '${I.module}'`}};if(i.service.name==="cloud.firestore"||i.service.name==="firebase.storage"){const kt=q.bundled?jh(i.service.name,I.module,J):null;if(kt)return{success:!1,error:{code:"INCOMPATIBLE_FUNCTION",message:kt}}}}}const b=new Set(i.imports.flatMap(I=>I.functions)),S=[],j=new Set,T=[],L={cycle:null};function k(I){if(L.cycle)return;const q=T.indexOf(I);if(q>=0){L.cycle=[...T.slice(q),I];return}if(j.has(I))return;const Z=c.get(I);if(!Z)return;T.push(I);const pe=Et(Z.body);for(const Q of Z.lets)pe.push(...Et(Q.value));for(const Q of pe)c.has(Q)&&!Wr.has(Q)&&k(Q);T.pop(),!L.cycle&&(j.add(I),S.push({...Z,exported:!1}))}for(const I of i.imports)for(const q of I.functions)k(q);if(L.cycle)return{success:!1,error:{code:"CIRCULAR_DEPENDENCY",message:`Recursive module function dependency: ${L.cycle.join(" -> ")}`}};for(const I of S){const q=d.get(I.name),pe=[...I.lets.flatMap(({value:Q})=>Et(Q)),...Et(I.body)].find(Q=>{const ve=d.get(Q);return ve&&ve!==q&&!b.has(Q)});if(pe)return{success:!1,error:{code:"UNKNOWN_FUNCTION",message:`Function '${I.name}' in module '${q}' cannot call '${pe}' from another module`}}}const $=new Set(S.map(I=>I.name)),V=new Map((i.functions??[]).map(I=>[I.name,I])),w=new Set((i.service.functions??[]).map(I=>I.name)),x=(I,q)=>I.flatMap(Et).find(Z=>o.has(Z)&&!$.has(Z)&&!q.has(Z))??null,_=I=>I.flatMap(q=>[...q.lets.map(({value:Z})=>Z),q.body]),v=new Set(V.keys());let O=x(_(i.functions??[]),v);const A=new Set([...v,...w]);O??=x(_(i.service.functions??[]),A);const h=(I,q)=>{const Z=new Set([...q,...I.functions.map(Q=>Q.name)]),pe=[..._(I.functions),...I.allows.map(({condition:Q})=>Q)];return x(pe,Z)??I.children.map(Q=>h(Q,Z)).find(Boolean)??null};if(O??=h(i.service.match,A),O)return{success:!1,error:{code:"UNKNOWN_FUNCTION",message:`Source calls function '${O}' from module '${u.get(O)}' without importing it`}};const p=(I,q)=>{if(q.has(I.name))return!1;const Z=new Set([...q,I.name]);return[...I.lets.flatMap(({value:Q})=>Et(Q)),...Et(I.body)].some(Q=>{const ve=V.get(Q);return ve?p(ve,Z):$.has(Q)||w.has(Q)})},g=[...V.values()].find(I=>p(I,new Set));if(g)return{success:!1,error:{code:"INCOMPATIBLE_FUNCTION",message:`Global function '${g.name}' cannot call a service-scoped function`}};if(i.service.name==="firebase.storage"||i.service.name==="cloud.firestore"){const I=new Map(S.map(q=>[q.name,q]));for(const q of S){const Z=[...Qh(i,q.name),...Yh(I,q.name).map(Q=>({arguments:Q.map(ve=>({expression:ve,provenance:null,receiverType:"unknown"}))}))],pe=Z.length>0?Z:[{arguments:[]}];for(const{arguments:Q}of pe){const ve=Wh(q,i.service.name,c,Q);if(ve)return{success:!1,error:{code:"INCOMPATIBLE_FUNCTION",message:`Function '${q.name}' requires unsupported ${ve} for service '${i.service.name}'`}}}}}const m=new Set([...(i.functions??[]).map(I=>I.name),...(i.service.functions??[]).map(I=>I.name)]),D=I=>{I.functions.forEach(q=>m.add(q.name)),I.children.forEach(D)};D(i.service.match);const E=[...m].find(I=>Wr.has(I));if(E)return{success:!1,error:{code:"DUPLICATE_FUNCTION",message:`Source function '${E}' conflicts with a Rules builtin`}};for(const I of S)if(m.has(I.name))return{success:!1,error:{code:"DUPLICATE_FUNCTION",message:`Imported function '${I.name}' conflicts with a function defined in the source`}};i.service.functions=[...S,...i.service.functions??[]],i.version="2",i.imports=[];const C=new Set,N=i.service.name==="firebase.storage"?"storage-rules#":"firestore-rules#";for(const I of f){const q=Cs(I)??I,Z=Sh[q]??[];for(const pe of Z)pe.startsWith(N)&&C.add(pe)}return{success:!0,data:{resolved:en(i),modules:l,bundledModules:f,evidenceIds:[...C].sort()}}}const rf={atomic:`// @pyric-services cloud.firestore
487
487
  // Atomic module — cross-document integrity for BATCH writes, via the
488
488
  // get()/getAfter() pair. Firestore evaluates every write in a batch
489
489
  // against rules, and getAfter() returns another document's POST-BATCH
@@ -1135,7 +1135,7 @@ export function validString(field, min, max) {
1135
1135
  export function isOneOf(field, values) {
1136
1136
  return request.resource.data[field] in values;
1137
1137
  }
1138
- `};function nf(){const t={};for(const[e,r]of Object.entries(rf))t[e]=r,t[`./stdlib/${e}.rules`]=r;return t}const ac=nf(),sf=new Set(Object.keys(ac));function ug(t,e){const r=Object.entries({}),n=Object.fromEntries(r),s=new Set(r.map(([a])=>a)),i=new Set([...sf].filter(a=>!s.has(a)));return tf(null,t,{...e,modules:{...ac,...n}},i)}function af(t){return typeof t=="object"&&t!==null&&t.__type==="serverTimestamp"}const of={name:"date-to-timestamp",convert(t){return t instanceof Date?xe.fromMillis(t.getTime()):We}},cf={name:"server-timestamp-sentinel",convert(t,e){return af(t)?e.serverTime instanceof xe?e.serverTime:xe.fromMillis(Date.now()):We}};function uf(t){if(t===null||typeof t!="object"||t instanceof xe)return!1;const e=t;return typeof e.seconds=="number"&&typeof e.nanoseconds=="number"&&typeof e.toMillis=="function"}const lf={name:"user-timestamp-to-rules-timestamp",convert(t){return uf(t)?new xe(t.seconds,t.nanoseconds):We}};function va(t){return typeof t=="object"&&t!==null&&"isEqual"in t&&typeof t.isEqual=="function"}function Rs(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function wa(t){if(typeof t!="object"||t===null||Rs(t))return;const e=t;if(typeof e.seconds=="number"){const r=typeof e.nanoseconds=="number"?e.nanoseconds:e.nanos;if(typeof r=="number")return{kind:"timestamp",seconds:e.seconds,nanoseconds:r}}if(e.data instanceof Uint8Array)return{kind:"bytes",values:Array.from(e.data)};if(typeof e.toUint8Array=="function")return{kind:"bytes",values:Array.from(e.toUint8Array())};if(typeof e.latitude=="number"&&typeof e.longitude=="number")return{kind:"geo-point",latitude:e.latitude,longitude:e.longitude};if(typeof e.lat=="number"&&typeof e.lng=="number")return{kind:"geo-point",latitude:e.lat,longitude:e.lng};if(typeof e.path=="string")return{kind:"reference",path:e.path};if(e.typeName==="vector"&&Array.isArray(e.value))return{kind:"vector",values:e.value};if(typeof e.toArray=="function")return{kind:"vector",values:e.toArray()}}function Ge(t,e){if(Object.is(t,e))return!0;const r=wa(t),n=wa(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(va(t))return t.isEqual(e);if(va(e))return e.isEqual(t);if(Array.isArray(t)||Array.isArray(e))return!Array.isArray(t)||!Array.isArray(e)||t.length!==e.length?!1:t.every((a,o)=>Ge(a,e[o]));if(!Rs(t)||!Rs(e))return!1;const s=Object.keys(t),i=Object.keys(e);return s.length!==i.length?!1:s.every(a=>a in e&&Ge(t[a],e[a]))}function df(t){return typeof t=="object"&&t!==null&&t.__type==="increment"&&typeof t.value=="number"}function hf(t){return typeof t=="object"&&t!==null&&t.__type==="arrayUnion"&&Array.isArray(t.values)}function ff(t){return typeof t=="object"&&t!==null&&t.__type==="arrayRemove"&&Array.isArray(t.values)}function pf(t){return typeof t=="object"&&t!==null&&t.__type==="deleteField"}function hi(t){if(t.prior===null)return;if(t.fieldPath==="")return t.prior;let e=t.prior;for(const r of t.fieldPath.split(".")){const n=/^([^\[]*)/.exec(r),s=n?n[1]:r;if(s){if(typeof e!="object"||e===null)return;e=e[s]}const i=/\[(\d+)\]/g;let a;for(;(a=i.exec(r))!==null;){if(!Array.isArray(e))return;e=e[Number(a[1])]}}return e}const mf={name:"increment-sentinel",convert(t,e){if(!df(t))return We;const r=hi(e);return(typeof r=="number"?r:0)+t.value}},gf={name:"array-union-sentinel",convert(t,e){if(!hf(t))return We;const r=hi(e),n=Array.isArray(r)?r.slice():[];for(const s of t.values)n.some(a=>Ge(a,s))||n.push(s);return n}},yf={name:"array-remove-sentinel",convert(t,e){if(!ff(t))return We;const r=hi(e);return Array.isArray(r)?r.filter(n=>!t.values.some(s=>Ge(n,s))):[]}},bf={name:"delete-field-sentinel",convert(t){return pf(t)?tt:We}},Sa=Symbol.for("pyric.firestore.query-value-registry"),_a=globalThis,Or=_a[Sa]??(_a[Sa]=new WeakMap),Aa=Symbol.for("pyric.firestore.query-value-execution-registry"),xa=globalThis,An=xa[Aa]??(xa[Aa]=new WeakMap),Ia=Symbol.for("pyric.firestore.query-value-owner-registry"),ka=globalThis,xn=ka[Ia]??(ka[Ia]=new WeakMap);function Ht(t,e,r=()=>t){Or.set(t,e),An.set(t,r)}function oc(t){return Or.get(t)}function vf(t){return xn.get(t)}function wf(t){return An.get(t)?.()??t}function Sf(t,e){const r=Or.get(t),n=An.get(t);r!==void 0&&Or.set(e,r),n!==void 0&&An.set(e,n);const s=xn.get(t);s!==void 0&&xn.set(e,s)}const Ns=Symbol.for("pyric.firestore.reference-query-value");class _f{path;[Ns]=!0;constructor(e){this.path=e}isEqual(e){return typeof e=="object"&&e!==null&&Ns in e&&e.path===this.path}}function Af(t){const e=Or.get(t);if(typeof e!="object"||e===null||!(Ns in e))return;const r=e.path;return typeof r=="string"?r:void 0}function fi(t,e,r,n=t){Ht(t,new _f(e),()=>n),xn.set(t,r)}function xf(t){if(t===null||typeof t!="object"||t instanceof jt)return!1;const e=t;return typeof e.path=="string"&&typeof e.id=="string"&&e._path!==void 0&&e._firestore!==void 0}const If={name:"document-reference",convert(t){if(typeof t=="object"&&t!==null){const e=Af(t);if(e!==void 0)return new jt(e)}return xf(t)?new jt(t.path):We}};function kf(t){return Array.isArray(t)&&t.every(e=>typeof e=="number")}function Ef(t){if(t===null||typeof t!="object"||t instanceof Wt)return null;const e=t;return kf(e._values)&&typeof e.toArray=="function"?e._values:null}const Of={name:"vector-value",convert(t){const e=Ef(t);return e===null?We:new Wt(e)}};function Cf(t){if(t===null||typeof t!="object"||t instanceof Be)return!1;const e=t;return typeof e.toBase64=="function"&&typeof e.toUint8Array=="function"&&typeof e.isEqual=="function"}function Tf(t){if(t===null||typeof t!="object"||t instanceof rt)return!1;const e=t;return typeof e.latitude=="number"&&typeof e.longitude=="number"&&typeof e.isEqual=="function"}const Rf={name:"fb-bytes-to-rules-bytes",convert(t){return Cf(t)?new Be(t.toUint8Array()):We}},Nf={name:"fb-geopoint-to-rules-latlng",convert(t){return Tf(t)?new rt(t.latitude,t.longitude):We}},We=Symbol("value-resolver:KEEP"),tt=Symbol("value-resolver:DELETE_MARKER"),Fs=[];function He(t){Fs.some(e=>e.name===t.name)||Fs.push(t)}function Ye(t,e){const r={};for(const[n,s]of Object.entries(t))r[n]=Ls(s,{...e,fieldPath:n});return r}function Ls(t,e){for(const r of Fs){const n=r.convert(t,e);if(n!==We)return n}if(Array.isArray(t))return t.map((r,n)=>Ls(r,{...e,fieldPath:`${e.fieldPath}[${n}]`}));if(Gt(t)){const r={};for(const[n,s]of Object.entries(t)){const i=e.fieldPath?`${e.fieldPath}.${n}`:n;r[n]=Ls(s,{...e,fieldPath:i})}return r}return t}function Gt(t){if(t===null||typeof t!="object")return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function Tt(t){const e={},r=[];for(const[n,s]of Object.entries(t)){if(s===tt){r.push(n);continue}e[n]=In(s)}return{writes:e,deletedKeys:r}}function In(t){if(t!==tt){if(Array.isArray(t))return t.filter(e=>e!==tt).map(In);if(Gt(t)){const e={};for(const[r,n]of Object.entries(t))n!==tt&&(e[r]=In(n));return e}return t}}function Ff(){He(of),He(cf),He(lf),He(mf),He(gf),He(yf),He(bf),He(If),He(Of),He(Rf),He(Nf)}function cc(t){return t.split(".")}const Lf=new Set(["__proto__","prototype","constructor"]);function Ea(t){if(Lf.has(t))throw new Error(`Invalid field-path segment '${t}': the keys __proto__, prototype, and constructor are reserved and cannot appear in a field path.`)}function pi(t){const e={};for(const[r,n]of Object.entries(t))e[r]=uc(n);return e}function uc(t){return Array.isArray(t)?t.map(uc):Gt(t)?pi(t):t}function lc(t,e,r){let n=t;for(let i=0;i<e.length-1;i++){const a=e[i];Ea(a);const o=Object.hasOwn(n,a)?n[a]:void 0;Gt(o)||(n[a]={}),n=n[a]}const s=e[e.length-1];Ea(s),r===tt?delete n[s]:n[s]=In(r)}function Oa(t,e){const r=pi(t);for(const[n,s]of Object.entries(e)){if(s!==tt&&kn(s))throw new dc;lc(r,cc(n),s)}return r}class dc extends Error{constructor(){super("FieldValue.delete() can only appear at the top level of your update data"),this.name="DeleteFieldNestedError"}}function kn(t){return t===tt?!0:Array.isArray(t)?t.some(kn):Gt(t)?Object.values(t).some(kn):!1}function jf(t){for(const e of Object.values(t))if(e!==tt&&kn(e))throw new dc}function Df(t,e,r){const n=pi(t),s=[];if(r!==void 0)for(const i of r){const a=cc(i),o=Mf(e,a);o!==hc&&s.push({segments:a,value:o})}else fc(e,[],s);for(const{segments:i,value:a}of s)lc(n,i,a);return n}const hc=Symbol("field-merge:ABSENT");function Mf(t,e){let r=t;for(const n of e){if(!Gt(r)||!Object.hasOwn(r,n))return hc;r=r[n]}return r}function fc(t,e,r){const n=Object.keys(t);if(n.length===0&&e.length>0){r.push({segments:e,value:{}});return}for(const s of n){const i=t[s],a=[...e,s];Gt(i)&&i!==tt?fc(i,a,r):r.push({segments:a,value:i})}}function Pf(t,e){const r={};for(const n of e)Object.prototype.hasOwnProperty.call(t,n)&&(r[n]=t[n]);return r}class es{documents;versions=new Map;nextVersion=1;constructor(e={},r){this.documents=r??new Map;for(const[n,s]of Object.entries(e)){const i=Ye({...s},{path:n,method:"seed",prior:null}),{writes:a}=Tt(i);this.documents.set(n,a),this.bumpVersion(n)}}get(e){return this.documents.get(e)??null}version(e){return this.versions.get(e)??0}currentVersion(){return this.nextVersion-1}exists(e){return this.documents.has(e)}scan(e,r={}){const n=e===""||e.endsWith("/")?e:e+"/",s=r.projection?c=>Pf(c,r.projection):c=>c,i=[],a=new Set,o=[];for(const[c,u]of this.documents){if(n!==""&&!c.startsWith(n))continue;if(!r.directOnly){i.push({path:c,data:s(u)});continue}const d=c.slice(n.length),l=d.indexOf("/");if(l===-1)i.push({path:c,data:s(u)}),a.add(d);else if(r.phantoms){const f=d.slice(0,l);f.length>0&&!o.includes(f)&&o.push(f)}}if(r.directOnly&&r.phantoms)for(const c of o)a.has(c)||i.push({path:n+c,data:{},phantom:!0});return i}list(e){return this.scan(e,{directOnly:!0,phantoms:!0})}listRootCollections(){const e=new Set,r=[];for(const n of this.documents.keys()){const s=n.split("/",1)[0];s.length!==0&&(e.has(s)||(e.add(s),r.push(s)))}return r}listSubcollections(e){const r=e.endsWith("/")?e:e+"/",n=new Set,s=[];for(const i of this.documents.keys()){if(!i.startsWith(r))continue;const o=i.slice(r.length).split("/",1)[0];o.length!==0&&(n.has(o)||(n.add(o),s.push(o)))}return s}snapshot(){const e={};for(const[r,n]of this.documents)e[r]={...n};return e}size(){return this.documents.size}create(e,r){if(this.documents.has(e))return{success:!1,error:`Document '${e}' already exists`};let n;try{const s=Ye({...r},{path:e,method:"create",prior:null});n=Tt(s).writes}catch(s){return{success:!1,error:s.message}}return this.documents.set(e,n),this.bumpVersion(e),{success:!0}}update(e,r){const n=this.documents.get(e);if(!n)return{success:!1,error:`Document '${e}' does not exist`};let s;try{const i=Ye({...r},{path:e,method:"update",prior:n});s=Oa(n,i)}catch(i){return{success:!1,error:i.message}}return this.documents.set(e,s),this.bumpVersion(e),{success:!0,priorData:{...n}}}setMerge(e,r,n){const s=this.documents.has(e)?{...this.documents.get(e)}:null,i=Ye({...r},{path:e,method:"set",prior:s}),a=Df(s??{},i,n);return this.documents.set(e,a),this.bumpVersion(e),{success:!0,priorData:s,created:s===null}}set(e,r){const n=this.documents.has(e)?{...this.documents.get(e)}:null,s=Ye({...r},{path:e,method:"set",prior:n}),{writes:i}=Tt(s);return this.documents.set(e,i),this.bumpVersion(e),{success:!0,priorData:n,created:n===null}}delete(e){const r=this.documents.get(e);return r?(this.documents.delete(e),this.bumpVersion(e),{success:!0,priorData:{...r}}):{success:!1,error:`Document '${e}' does not exist`}}applyBatch(e){const r=[];for(let s=0;s<e.length;s++){const i=e[s];switch(i.method){case"create":this.documents.has(i.path)&&r.push({index:s,error:`Document '${i.path}' already exists`});break;case"update":this.documents.has(i.path)||r.push({index:s,error:`Document '${i.path}' does not exist`});break}}if(r.length>0)return{success:!1,errors:r};const n=new Map;for(const s of e)n.has(s.path)||n.set(s.path,this.documents.has(s.path)?{...this.documents.get(s.path)}:null);for(const s of e){switch(s.method){case"create":{const i=Ye({...s.data},{path:s.path,method:"create",prior:null}),{writes:a}=Tt(i);this.documents.set(s.path,a);break}case"update":{const i=this.documents.get(s.path),a=Ye({...s.data},{path:s.path,method:"update",prior:i});this.documents.set(s.path,Oa(i,a));break}case"set":{const i=n.get(s.path)??null,a=Ye({...s.data},{path:s.path,method:"set",prior:i}),{writes:o}=Tt(a);this.documents.set(s.path,o);break}case"delete":this.documents.delete(s.path);break}this.bumpVersion(s.path)}return{success:!0,priorStates:n}}restore(e){const r=new Set([...this.documents.keys(),...Object.keys(e)]);this.documents.clear();for(const[n,s]of Object.entries(e))this.documents.set(n,{...s});for(const n of r)this.bumpVersion(n)}restorePaths(e){for(const[r,n]of Object.entries(e))n===null?this.documents.delete(r):this.documents.set(r,{...n}),this.bumpVersion(r)}bumpVersion(e){this.versions.set(e,this.nextVersion++)}}class $f{base;overlay=new Map;tombstones=new Set;baseCache=new Map;cleared=!1;constructor(e){this.base=e}inBase(e){return Object.prototype.hasOwnProperty.call(this.base,e)}baseDoc(e){let r=this.baseCache.get(e);return r===void 0&&(r=structuredClone(this.base[e]),this.baseCache.set(e,r)),r}get(e){if(this.overlay.has(e))return this.overlay.get(e);if(!(this.cleared||this.tombstones.has(e)))return this.inBase(e)?this.baseDoc(e):void 0}set(e,r){this.overlay.set(e,r),this.tombstones.delete(e)}has(e){return this.overlay.has(e)?!0:this.cleared||this.tombstones.has(e)?!1:this.inBase(e)}delete(e){const r=this.has(e);return this.overlay.delete(e),!this.cleared&&this.inBase(e)&&this.tombstones.add(e),r}clear(){this.overlay.clear(),this.tombstones.clear(),this.baseCache.clear(),this.cleared=!0}get size(){let e=0;for(const r of this)e++;return e}*keys(){for(const[e]of this)yield e}*[Symbol.iterator](){const e=new Set;if(!this.cleared)for(const r of Object.keys(this.base))this.tombstones.has(r)||(e.add(r),yield[r,this.overlay.has(r)?this.overlay.get(r):this.baseDoc(r)]);for(const[r,n]of this.overlay)e.has(r)||(yield[r,n])}}class qf{events=[];nextId=1;undoneEvents=[];append(e,r=!1){const n={...e,id:this.nextId++,timestamp:new Date().toISOString()};return this.events.push(n),r||(this.undoneEvents=[]),n}getEvents(){return[...this.events]}getWriteEvents(){return this.events.filter(e=>e.allowed&&e.method!=="get"&&e.method!=="list")}lastWriteEvent(){const e=this.getWriteEvents();return e.length>0?e[e.length-1]:null}popLastWrite(){for(let e=this.events.length-1;e>=0;e--){const r=this.events[e];if(!r.aborted&&r.allowed&&r.method!=="get"&&r.method!=="list")return this.events.splice(e,1),this.undoneEvents.push(r),r}return null}popLastUndo(){return this.undoneEvents.pop()??null}size(){return this.events.length}clear(){this.events=[],this.undoneEvents=[],this.nextId=1}}function Uf(t){return new Date(t.toMillis()).toISOString()}class Fr extends Error{method;path;debugMessages;constructor(e,r,n,s){super(e),this.method=r,this.path=n,this.debugMessages=s,this.name="SimulatorUnsupportedError"}}function Lr(t,e,r){const n=r.filter(i=>i.includes("unsupported:")).map(i=>i.replace(/^.*unsupported:\s*/,"")).join("; "),s=n?` Reason(s): ${n}.`:"";return`Simulator cannot decide ${t} on ${e} — the rule uses a feature the local simulator does not yet implement.${s} Verify this rule against production using TestFirestoreRulesHandler, or file a sim-gap entry in REBUILD_PLAN.md.`}function Bf(t=""){return{description:t,expectation:"ALLOW",state:"PASSED",decision:"ALLOW",trace:[],notes:["admin lens — rules bypassed (Studio Gap #2)"]}}const zf=`rules_version = '2';
1138
+ `};function nf(){const t={};for(const[e,r]of Object.entries(rf))t[e]=r,t[`./stdlib/${e}.rules`]=r;return t}const ic=nf(),sf=new Set(Object.keys(ic));function ug(t,e){const r=Object.entries(e?.modules??{}),n=Object.fromEntries(r),s=new Set(r.map(([a])=>a)),i=new Set([...sf].filter(a=>!s.has(a)));return tf(null,t,{...e,modules:{...ic,...n}},i)}function af(t){return typeof t=="object"&&t!==null&&t.__type==="serverTimestamp"}const of={name:"date-to-timestamp",convert(t){return t instanceof Date?xe.fromMillis(t.getTime()):We}},cf={name:"server-timestamp-sentinel",convert(t,e){return af(t)?e.serverTime instanceof xe?e.serverTime:xe.fromMillis(Date.now()):We}};function uf(t){if(t===null||typeof t!="object"||t instanceof xe)return!1;const e=t;return typeof e.seconds=="number"&&typeof e.nanoseconds=="number"&&typeof e.toMillis=="function"}const lf={name:"user-timestamp-to-rules-timestamp",convert(t){return uf(t)?new xe(t.seconds,t.nanoseconds):We}};function ba(t){return typeof t=="object"&&t!==null&&"isEqual"in t&&typeof t.isEqual=="function"}function Ts(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function va(t){if(typeof t!="object"||t===null||Ts(t))return;const e=t;if(typeof e.seconds=="number"){const r=typeof e.nanoseconds=="number"?e.nanoseconds:e.nanos;if(typeof r=="number")return{kind:"timestamp",seconds:e.seconds,nanoseconds:r}}if(e.data instanceof Uint8Array)return{kind:"bytes",values:Array.from(e.data)};if(typeof e.toUint8Array=="function")return{kind:"bytes",values:Array.from(e.toUint8Array())};if(typeof e.latitude=="number"&&typeof e.longitude=="number")return{kind:"geo-point",latitude:e.latitude,longitude:e.longitude};if(typeof e.lat=="number"&&typeof e.lng=="number")return{kind:"geo-point",latitude:e.lat,longitude:e.lng};if(typeof e.path=="string")return{kind:"reference",path:e.path};if(e.typeName==="vector"&&Array.isArray(e.value))return{kind:"vector",values:e.value};if(typeof e.toArray=="function")return{kind:"vector",values:e.toArray()}}function Ge(t,e){if(Object.is(t,e))return!0;const r=va(t),n=va(e);if(r!==void 0||n!==void 0){if(r===void 0||n===void 0||r.kind!==n.kind)return!1;switch(r.kind){case"timestamp":return n.kind==="timestamp"&&r.seconds===n.seconds&&r.nanoseconds===n.nanoseconds;case"bytes":return n.kind==="bytes"&&r.values.length===n.values.length&&r.values.every((a,o)=>a===n.values[o]);case"vector":return n.kind==="vector"&&r.values.length===n.values.length&&r.values.every((a,o)=>a===n.values[o]);case"geo-point":return n.kind==="geo-point"&&r.latitude===n.latitude&&r.longitude===n.longitude;case"reference":return n.kind==="reference"&&r.path===n.path}}if(ba(t))return t.isEqual(e);if(ba(e))return e.isEqual(t);if(Array.isArray(t)||Array.isArray(e))return!Array.isArray(t)||!Array.isArray(e)||t.length!==e.length?!1:t.every((a,o)=>Ge(a,e[o]));if(!Ts(t)||!Ts(e))return!1;const s=Object.keys(t),i=Object.keys(e);return s.length!==i.length?!1:s.every(a=>a in e&&Ge(t[a],e[a]))}function df(t){return typeof t=="object"&&t!==null&&t.__type==="increment"&&typeof t.value=="number"}function hf(t){return typeof t=="object"&&t!==null&&t.__type==="arrayUnion"&&Array.isArray(t.values)}function ff(t){return typeof t=="object"&&t!==null&&t.__type==="arrayRemove"&&Array.isArray(t.values)}function pf(t){return typeof t=="object"&&t!==null&&t.__type==="deleteField"}function di(t){if(t.prior===null)return;if(t.fieldPath==="")return t.prior;let e=t.prior;for(const r of t.fieldPath.split(".")){const n=/^([^\[]*)/.exec(r),s=n?n[1]:r;if(s){if(typeof e!="object"||e===null)return;e=e[s]}const i=/\[(\d+)\]/g;let a;for(;(a=i.exec(r))!==null;){if(!Array.isArray(e))return;e=e[Number(a[1])]}}return e}const mf={name:"increment-sentinel",convert(t,e){if(!df(t))return We;const r=di(e);return(typeof r=="number"?r:0)+t.value}},gf={name:"array-union-sentinel",convert(t,e){if(!hf(t))return We;const r=di(e),n=Array.isArray(r)?r.slice():[];for(const s of t.values)n.some(a=>Ge(a,s))||n.push(s);return n}},yf={name:"array-remove-sentinel",convert(t,e){if(!ff(t))return We;const r=di(e);return Array.isArray(r)?r.filter(n=>!t.values.some(s=>Ge(n,s))):[]}},bf={name:"delete-field-sentinel",convert(t){return pf(t)?tt:We}},wa=Symbol.for("pyric.firestore.query-value-registry"),Sa=globalThis,Or=Sa[wa]??(Sa[wa]=new WeakMap),_a=Symbol.for("pyric.firestore.query-value-execution-registry"),Aa=globalThis,_n=Aa[_a]??(Aa[_a]=new WeakMap),xa=Symbol.for("pyric.firestore.query-value-owner-registry"),Ia=globalThis,An=Ia[xa]??(Ia[xa]=new WeakMap);function Ht(t,e,r=()=>t){Or.set(t,e),_n.set(t,r)}function ac(t){return Or.get(t)}function vf(t){return An.get(t)}function wf(t){return _n.get(t)?.()??t}function Sf(t,e){const r=Or.get(t),n=_n.get(t);r!==void 0&&Or.set(e,r),n!==void 0&&_n.set(e,n);const s=An.get(t);s!==void 0&&An.set(e,s)}const Rs=Symbol.for("pyric.firestore.reference-query-value");class _f{path;[Rs]=!0;constructor(e){this.path=e}isEqual(e){return typeof e=="object"&&e!==null&&Rs in e&&e.path===this.path}}function Af(t){const e=Or.get(t);if(typeof e!="object"||e===null||!(Rs in e))return;const r=e.path;return typeof r=="string"?r:void 0}function hi(t,e,r,n=t){Ht(t,new _f(e),()=>n),An.set(t,r)}function xf(t){if(t===null||typeof t!="object"||t instanceof jt)return!1;const e=t;return typeof e.path=="string"&&typeof e.id=="string"&&e._path!==void 0&&e._firestore!==void 0}const If={name:"document-reference",convert(t){if(typeof t=="object"&&t!==null){const e=Af(t);if(e!==void 0)return new jt(e)}return xf(t)?new jt(t.path):We}};function kf(t){return Array.isArray(t)&&t.every(e=>typeof e=="number")}function Ef(t){if(t===null||typeof t!="object"||t instanceof Wt)return null;const e=t;return kf(e._values)&&typeof e.toArray=="function"?e._values:null}const Of={name:"vector-value",convert(t){const e=Ef(t);return e===null?We:new Wt(e)}};function Cf(t){if(t===null||typeof t!="object"||t instanceof Be)return!1;const e=t;return typeof e.toBase64=="function"&&typeof e.toUint8Array=="function"&&typeof e.isEqual=="function"}function Tf(t){if(t===null||typeof t!="object"||t instanceof rt)return!1;const e=t;return typeof e.latitude=="number"&&typeof e.longitude=="number"&&typeof e.isEqual=="function"}const Rf={name:"fb-bytes-to-rules-bytes",convert(t){return Cf(t)?new Be(t.toUint8Array()):We}},Nf={name:"fb-geopoint-to-rules-latlng",convert(t){return Tf(t)?new rt(t.latitude,t.longitude):We}},We=Symbol("value-resolver:KEEP"),tt=Symbol("value-resolver:DELETE_MARKER"),Ns=[];function He(t){Ns.some(e=>e.name===t.name)||Ns.push(t)}function Ye(t,e){const r={};for(const[n,s]of Object.entries(t))r[n]=Fs(s,{...e,fieldPath:n});return r}function Fs(t,e){for(const r of Ns){const n=r.convert(t,e);if(n!==We)return n}if(Array.isArray(t))return t.map((r,n)=>Fs(r,{...e,fieldPath:`${e.fieldPath}[${n}]`}));if(Gt(t)){const r={};for(const[n,s]of Object.entries(t)){const i=e.fieldPath?`${e.fieldPath}.${n}`:n;r[n]=Fs(s,{...e,fieldPath:i})}return r}return t}function Gt(t){if(t===null||typeof t!="object")return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function Tt(t){const e={},r=[];for(const[n,s]of Object.entries(t)){if(s===tt){r.push(n);continue}e[n]=xn(s)}return{writes:e,deletedKeys:r}}function xn(t){if(t!==tt){if(Array.isArray(t))return t.filter(e=>e!==tt).map(xn);if(Gt(t)){const e={};for(const[r,n]of Object.entries(t))n!==tt&&(e[r]=xn(n));return e}return t}}function Ff(){He(of),He(cf),He(lf),He(mf),He(gf),He(yf),He(bf),He(If),He(Of),He(Rf),He(Nf)}function oc(t){return t.split(".")}const Lf=new Set(["__proto__","prototype","constructor"]);function ka(t){if(Lf.has(t))throw new Error(`Invalid field-path segment '${t}': the keys __proto__, prototype, and constructor are reserved and cannot appear in a field path.`)}function fi(t){const e={};for(const[r,n]of Object.entries(t))e[r]=cc(n);return e}function cc(t){return Array.isArray(t)?t.map(cc):Gt(t)?fi(t):t}function uc(t,e,r){let n=t;for(let i=0;i<e.length-1;i++){const a=e[i];ka(a);const o=Object.hasOwn(n,a)?n[a]:void 0;Gt(o)||(n[a]={}),n=n[a]}const s=e[e.length-1];ka(s),r===tt?delete n[s]:n[s]=xn(r)}function Ea(t,e){const r=fi(t);for(const[n,s]of Object.entries(e)){if(s!==tt&&In(s))throw new lc;uc(r,oc(n),s)}return r}class lc extends Error{constructor(){super("FieldValue.delete() can only appear at the top level of your update data"),this.name="DeleteFieldNestedError"}}function In(t){return t===tt?!0:Array.isArray(t)?t.some(In):Gt(t)?Object.values(t).some(In):!1}function jf(t){for(const e of Object.values(t))if(e!==tt&&In(e))throw new lc}function Df(t,e,r){const n=fi(t),s=[];if(r!==void 0)for(const i of r){const a=oc(i),o=Mf(e,a);o!==dc&&s.push({segments:a,value:o})}else hc(e,[],s);for(const{segments:i,value:a}of s)uc(n,i,a);return n}const dc=Symbol("field-merge:ABSENT");function Mf(t,e){let r=t;for(const n of e){if(!Gt(r)||!Object.hasOwn(r,n))return dc;r=r[n]}return r}function hc(t,e,r){const n=Object.keys(t);if(n.length===0&&e.length>0){r.push({segments:e,value:{}});return}for(const s of n){const i=t[s],a=[...e,s];Gt(i)&&i!==tt?hc(i,a,r):r.push({segments:a,value:i})}}function Pf(t,e){const r={};for(const n of e)Object.prototype.hasOwnProperty.call(t,n)&&(r[n]=t[n]);return r}class Xn{documents;versions=new Map;nextVersion=1;constructor(e={},r){this.documents=r??new Map;for(const[n,s]of Object.entries(e)){const i=Ye({...s},{path:n,method:"seed",prior:null}),{writes:a}=Tt(i);this.documents.set(n,a),this.bumpVersion(n)}}get(e){return this.documents.get(e)??null}version(e){return this.versions.get(e)??0}currentVersion(){return this.nextVersion-1}exists(e){return this.documents.has(e)}scan(e,r={}){const n=e===""||e.endsWith("/")?e:e+"/",s=r.projection?c=>Pf(c,r.projection):c=>c,i=[],a=new Set,o=[];for(const[c,u]of this.documents){if(n!==""&&!c.startsWith(n))continue;if(!r.directOnly){i.push({path:c,data:s(u)});continue}const d=c.slice(n.length),l=d.indexOf("/");if(l===-1)i.push({path:c,data:s(u)}),a.add(d);else if(r.phantoms){const f=d.slice(0,l);f.length>0&&!o.includes(f)&&o.push(f)}}if(r.directOnly&&r.phantoms)for(const c of o)a.has(c)||i.push({path:n+c,data:{},phantom:!0});return i}list(e){return this.scan(e,{directOnly:!0,phantoms:!0})}listRootCollections(){const e=new Set,r=[];for(const n of this.documents.keys()){const s=n.split("/",1)[0];s.length!==0&&(e.has(s)||(e.add(s),r.push(s)))}return r}listSubcollections(e){const r=e.endsWith("/")?e:e+"/",n=new Set,s=[];for(const i of this.documents.keys()){if(!i.startsWith(r))continue;const o=i.slice(r.length).split("/",1)[0];o.length!==0&&(n.has(o)||(n.add(o),s.push(o)))}return s}snapshot(){const e={};for(const[r,n]of this.documents)e[r]={...n};return e}size(){return this.documents.size}create(e,r){if(this.documents.has(e))return{success:!1,error:`Document '${e}' already exists`};let n;try{const s=Ye({...r},{path:e,method:"create",prior:null});n=Tt(s).writes}catch(s){return{success:!1,error:s.message}}return this.documents.set(e,n),this.bumpVersion(e),{success:!0}}update(e,r){const n=this.documents.get(e);if(!n)return{success:!1,error:`Document '${e}' does not exist`};let s;try{const i=Ye({...r},{path:e,method:"update",prior:n});s=Ea(n,i)}catch(i){return{success:!1,error:i.message}}return this.documents.set(e,s),this.bumpVersion(e),{success:!0,priorData:{...n}}}setMerge(e,r,n){const s=this.documents.has(e)?{...this.documents.get(e)}:null,i=Ye({...r},{path:e,method:"set",prior:s}),a=Df(s??{},i,n);return this.documents.set(e,a),this.bumpVersion(e),{success:!0,priorData:s,created:s===null}}set(e,r){const n=this.documents.has(e)?{...this.documents.get(e)}:null,s=Ye({...r},{path:e,method:"set",prior:n}),{writes:i}=Tt(s);return this.documents.set(e,i),this.bumpVersion(e),{success:!0,priorData:n,created:n===null}}delete(e){const r=this.documents.get(e);return r?(this.documents.delete(e),this.bumpVersion(e),{success:!0,priorData:{...r}}):{success:!1,error:`Document '${e}' does not exist`}}applyBatch(e){const r=[];for(let s=0;s<e.length;s++){const i=e[s];switch(i.method){case"create":this.documents.has(i.path)&&r.push({index:s,error:`Document '${i.path}' already exists`});break;case"update":this.documents.has(i.path)||r.push({index:s,error:`Document '${i.path}' does not exist`});break}}if(r.length>0)return{success:!1,errors:r};const n=new Map;for(const s of e)n.has(s.path)||n.set(s.path,this.documents.has(s.path)?{...this.documents.get(s.path)}:null);for(const s of e){switch(s.method){case"create":{const i=Ye({...s.data},{path:s.path,method:"create",prior:null}),{writes:a}=Tt(i);this.documents.set(s.path,a);break}case"update":{const i=this.documents.get(s.path),a=Ye({...s.data},{path:s.path,method:"update",prior:i});this.documents.set(s.path,Ea(i,a));break}case"set":{const i=n.get(s.path)??null,a=Ye({...s.data},{path:s.path,method:"set",prior:i}),{writes:o}=Tt(a);this.documents.set(s.path,o);break}case"delete":this.documents.delete(s.path);break}this.bumpVersion(s.path)}return{success:!0,priorStates:n}}restore(e){const r=new Set([...this.documents.keys(),...Object.keys(e)]);this.documents.clear();for(const[n,s]of Object.entries(e))this.documents.set(n,{...s});for(const n of r)this.bumpVersion(n)}restorePaths(e){for(const[r,n]of Object.entries(e))n===null?this.documents.delete(r):this.documents.set(r,{...n}),this.bumpVersion(r)}bumpVersion(e){this.versions.set(e,this.nextVersion++)}}class $f{base;overlay=new Map;tombstones=new Set;baseCache=new Map;cleared=!1;constructor(e){this.base=e}inBase(e){return Object.prototype.hasOwnProperty.call(this.base,e)}baseDoc(e){let r=this.baseCache.get(e);return r===void 0&&(r=structuredClone(this.base[e]),this.baseCache.set(e,r)),r}get(e){if(this.overlay.has(e))return this.overlay.get(e);if(!(this.cleared||this.tombstones.has(e)))return this.inBase(e)?this.baseDoc(e):void 0}set(e,r){this.overlay.set(e,r),this.tombstones.delete(e)}has(e){return this.overlay.has(e)?!0:this.cleared||this.tombstones.has(e)?!1:this.inBase(e)}delete(e){const r=this.has(e);return this.overlay.delete(e),!this.cleared&&this.inBase(e)&&this.tombstones.add(e),r}clear(){this.overlay.clear(),this.tombstones.clear(),this.baseCache.clear(),this.cleared=!0}get size(){let e=0;for(const r of this)e++;return e}*keys(){for(const[e]of this)yield e}*[Symbol.iterator](){const e=new Set;if(!this.cleared)for(const r of Object.keys(this.base))this.tombstones.has(r)||(e.add(r),yield[r,this.overlay.has(r)?this.overlay.get(r):this.baseDoc(r)]);for(const[r,n]of this.overlay)e.has(r)||(yield[r,n])}}class qf{events=[];nextId=1;undoneEvents=[];append(e,r=!1){const n={...e,id:this.nextId++,timestamp:new Date().toISOString()};return this.events.push(n),r||(this.undoneEvents=[]),n}getEvents(){return[...this.events]}getWriteEvents(){return this.events.filter(e=>e.allowed&&e.method!=="get"&&e.method!=="list")}lastWriteEvent(){const e=this.getWriteEvents();return e.length>0?e[e.length-1]:null}popLastWrite(){for(let e=this.events.length-1;e>=0;e--){const r=this.events[e];if(!r.aborted&&r.allowed&&r.method!=="get"&&r.method!=="list")return this.events.splice(e,1),this.undoneEvents.push(r),r}return null}popLastUndo(){return this.undoneEvents.pop()??null}size(){return this.events.length}clear(){this.events=[],this.undoneEvents=[],this.nextId=1}}function Uf(t){return new Date(t.toMillis()).toISOString()}class Fr extends Error{method;path;debugMessages;constructor(e,r,n,s){super(e),this.method=r,this.path=n,this.debugMessages=s,this.name="SimulatorUnsupportedError"}}function Lr(t,e,r){const n=r.filter(i=>i.includes("unsupported:")).map(i=>i.replace(/^.*unsupported:\s*/,"")).join("; "),s=n?` Reason(s): ${n}.`:"";return`Simulator cannot decide ${t} on ${e} — the rule uses a feature the local simulator does not yet implement.${s} Verify this rule against production using TestFirestoreRulesHandler, or file a sim-gap entry in REBUILD_PLAN.md.`}function Bf(t=""){return{description:t,expectation:"ALLOW",state:"PASSED",decision:"ALLOW",trace:[],notes:["admin lens — rules bypassed (Studio Gap #2)"]}}const zf=`rules_version = '2';
1139
1139
  service cloud.firestore {
1140
1140
  match /databases/{database}/documents {
1141
1141
  match /{document=**} {
@@ -1143,11 +1143,11 @@ service cloud.firestore {
1143
1143
  }
1144
1144
  }
1145
1145
  }
1146
- `;class Ot{swallowAsyncRejections;subscribers=new Set;constructor(e=!1){this.swallowAsyncRejections=e}get hasSubscribers(){return this.subscribers.size>0}subscribe(e){return this.subscribers.add(e),()=>{this.subscribers.delete(e)}}emit(...e){for(const r of this.subscribers)try{const n=r(...e);this.swallowAsyncRejections&&n&&typeof n.then=="function"&&n.catch(()=>{})}catch{}}clear(){this.subscribers.clear()}}class Vf{denial=new Ot;request=new Ot(!0);write=new Ot(!0);delivery=new Ot;suppressed=new Ot;lifecycle=new Ot;snapshotError=new Ot;clear(){this.denial.clear(),this.request.clear(),this.write.clear(),this.delivery.clear(),this.suppressed.clear(),this.lifecycle.clear(),this.snapshotError.clear()}}class Wf{currentTrigger;run(e,r){const n=this.currentTrigger;this.currentTrigger=e;try{return r()}finally{this.currentTrigger=n}}current(){return this.currentTrigger}}class ce extends Error{code;simError;constructor(e){super(e.message),this.name="FirestoreError",this.code=e.code,this.simError=e}}const Ca=Symbol.for("pyric.firestore.activity-value-registry"),Ta=globalThis,pc=Ta[Ca]??(Ta[Ca]=new WeakMap);function mc(){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 mi(...t){const e=mc();for(const r of t)e.update(r);return e.finish()}function Hf(t){return{type:"string-digest",length:t.length,digest:mi("string\0",t)}}function qt(t,...e){return{type:`${t}-digest`,digest:mi(`${t}\0`,...e)}}function Gf(t){return{type:"bytes-digest",length:t.byteLength,digest:mi("bytes\0",t)}}function Ra(t){const e=mc(),r=(...s)=>{for(const i of s)e.update(i)},n=s=>{if(s===null){r("null;");return}switch(typeof s){case"string":r(`s${s.length}:`,s,";");return;case"number":r(`n${Object.is(s,-0)?"-0":String(s)};`);return;case"boolean":r(s?"b1;":"b0;");return;case"undefined":r("u;");return;case"bigint":r(`i${s.toString()};`);return;case"object":break;default:r(`x${typeof s};`);return}if(Array.isArray(s)){r(`a${s.length}[`);for(const o of s)n(o);r("];");return}const i=s,a=Object.keys(i).sort();r(`o${a.length}{`);for(const o of a)r(`k${o.length}:`,o,"="),n(i[o]);r("};")};return n(t),{type:"wire-value-digest",digest:e.finish()}}function st(t,e){pc.set(t,e)}function Kf(t){return pc.get(t)}class Zf{static serverTimestamp(){return{__type:"serverTimestamp"}}static increment(e){return{__type:"increment",value:e}}static arrayUnion(...e){return{__type:"arrayUnion",values:e}}static arrayRemove(...e){return{__type:"arrayRemove",values:e}}static delete(){return{__type:"deleteField"}}}class bt{seconds;nanoseconds;constructor(e,r){this.seconds=e,this.nanoseconds=r,st(this,qt("timestamp",String(e),"\0",String(r))),Ht(this,Object.freeze({type:"timestamp",seconds:e,nanoseconds:r}),()=>new bt(e,r))}static now(){return bt.fromMillis(Date.now())}static fromDate(e){return bt.fromMillis(e.getTime())}static fromMillis(e){const r=Math.floor(e/1e3),n=Math.floor((e-r*1e3)*1e6);return new bt(r,n)}toDate(){return new Date(this.toMillis())}toMillis(){return this.seconds*1e3+this.nanoseconds/1e6}isEqual(e){return e.seconds===this.seconds&&e.nanoseconds===this.nanoseconds}toString(){return`Timestamp(seconds=${this.seconds}, nanoseconds=${this.nanoseconds})`}toJSON(){return{type:"firestore/timestamp/1.0",seconds:this.seconds,nanoseconds:this.nanoseconds}}valueOf(){const r=this.seconds- -62135596800,n=String(r).padStart(12,"0"),s=String(this.nanoseconds).padStart(9,"0");return`${n}.${s}`}}function js(t){return t instanceof xe?new bt(t.seconds,t.nanos):t instanceof Be||t instanceof rt||t instanceof Wt?t:Array.isArray(t)?t.map(js):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).map(([e,r])=>[e,js(r)])):t}function jr(t){return js(t)}const Jf=/[*~/[\]]/,Qf=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class En{_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 En("__name__");static documentId(){return En.DOCUMENT_ID}isEqual(e){const r=gc(e),n=this._internalPath.segments;return n.length===r.length&&n.every((s,i)=>s===r[i])}toString(){return this._internalPath.segments.map(e=>Qf.test(e)?e:`\`${e.replace(/\\/g,"\\\\").replace(/`/g,"\\`")}\``).join(".")}}function lr(t){return new Error(`Value for argument "field" is not a valid field path. ${t}`)}function gc(t){if(t instanceof En)return t._internalPath.segments;if(typeof t=="object"&&t!==null){const e=t._internalPath;if(Array.isArray(e?.segments)&&e.segments.every(r=>typeof r=="string"))return[...e.segments]}if(t===void 0)throw lr("The path cannot be omitted.");if(typeof t!="string")throw lr("Paths can only be specified as strings or via a FieldPath object.");if(t.includes(".."))throw lr('Paths must not contain ".." in them.');if(t.startsWith(".")||t.endsWith("."))throw lr('Paths must not start or end with ".".');if(t.length===0||Jf.test(t))throw lr(`Paths can't be empty and must not contain
1147
- "*~/[]".`);return t.split(".")}function Yf(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function or(t,e){const r=gc(e);let n=t;for(const s of r){if(!Yf(n))return;n=Object.prototype.hasOwnProperty.call(n,s)?n[s]:void 0}return n}const nr=Object.freeze({hasPendingWrites:!1,fromCache:!1}),Na=Object.freeze({hasPendingWrites:!0,fromCache:!1});function yc(t){const e=t.lastIndexOf("/");return e===-1?t:t.slice(e+1)}function Jt(t,e,r=nr){const n={id:yc(t),path:t},s=e!==null,i=s?jr(e):void 0;return{id:n.id,ref:n,metadata:r,exists:()=>s,data:()=>i,get:a=>or(i,a)}}function bc(t,e,r=nr){const n={id:yc(t),path:t},s=jr(e);return{id:n.id,ref:n,metadata:r,exists:()=>!0,data:()=>s,get:i=>or(s,i)}}function Qt(t,e,r,n,s=nr){const i=e.map(u=>bc(u.path,u.data,s)),a=n?Xf(n,e,i,s):i.map((u,d)=>({type:"added",doc:u,oldIndex:-1,newIndex:d}));let o=null,c=null;return{query:t,metadata:s,size:i.length,empty:i.length===0,docs:i,forEach(u){for(const d of i)u(d)},docChanges(u){const d=!!u?.includeMetadataChanges;if(d&&r.excludesMetadataChanges)throw new Error("To include metadata changes with your document changes, you must also pass { includeMetadataChanges: true } to onSnapshot().");return d?(c||(c=a.slice()),c):(o||(o=a.slice()),o)}}}function Xf(t,e,r,n=nr){const s=new Map;t.forEach((o,c)=>s.set(o.path,c));const i=new Map;e.forEach((o,c)=>i.set(o.path,c));const a=[];for(let o=0;o<t.length;o++){const c=t[o];i.has(c.path)||a.push({type:"removed",doc:bc(c.path,c.data,n),oldIndex:o,newIndex:-1})}for(let o=0;o<e.length;o++){const c=e[o],u=s.get(c.path);if(u===void 0)a.push({type:"added",doc:r[o],oldIndex:-1,newIndex:o});else{const d=t[u].data;JSON.stringify(d)!==JSON.stringify(c.data)&&a.push({type:"modified",doc:r[o],oldIndex:u,newIndex:o})}}return a}function Fa(t,e){return t===null&&e===null?!0:t===null||e===null?!1:JSON.stringify(t)===JSON.stringify(e)}function ep(t,e){const r=`${e}/`;for(const n of t){if(!n.startsWith(r))continue;const s=n.slice(r.length);if(s.length>0&&!s.includes("/"))return!0}return!1}let ts=0;function vr(){return ts=ts+1>>>0,`req-${ts.toString(36)}-${Math.random().toString(36).slice(2,7)}`}function tp(t,e){const r=e==="allow";let n;for(const s of t){const i=/^Rule #(\d+) \(([^)]+)\) → (ALLOW|deny|unsupported)/.exec(s);if(!i)continue;const a={ruleIndex:Number(i[1]),operations:i[2].split(",").map(o=>o.trim())};if(r&&i[3]==="ALLOW")return a;n=a}return n}function Pn(t){const e={kind:"request",id:vr(),at:t.at,evalMs:t.evalMs,method:t.method,path:t.path,auth:t.auth?{uid:t.auth.uid,...t.auth.token?{token:t.auth.token}:{}}:null,result:t.result,reasons:t.debugMessages,origin:t.origin};t.resourceData!==void 0&&(e.request={resourceData:t.resourceData}),t.resourceBefore!==void 0&&(e.resourceBefore=t.resourceBefore),t.resourceAfter!==void 0&&(e.resourceAfter=t.resourceAfter);const r=tp(t.debugMessages,t.result);return r&&(e.matchedRule=r),t.result!=="unsupported"&&t.evaluatedRule&&(e.evaluatedRule=t.evaluatedRule),t.groupId!==void 0&&(e.groupId=t.groupId,t.origin==="batch"?e.groupKind="batch":t.origin==="transaction"&&(e.groupKind="transaction")),t.triggeredBy!==void 0&&(e.triggeredBy=t.triggeredBy),t.detail!==void 0&&(e.detail=t.detail),t.provenance!==void 0&&Object.assign(e,t.provenance),e}class rp{events;triggerScope;host;snapshotListeners=new Map;nextListenerId=0;deliveryQueue=[];deliveryScheduled=!1;constructor(e,r,n){this.events=e,this.triggerScope=r,this.host=n}emitSnapshotDelivery(e){if(!this.events.delivery.hasSubscribers)return;const r={kind:"snapshot_delivery",id:vr().replace(/^req-/,"snd-"),at:Date.now(),listenerId:e.listenerId,target:e.target,auth:e.auth?{uid:e.auth.uid,...e.auth.token?{token:e.auth.token}:{}}:null,addedCount:e.addedCount,modifiedCount:e.modifiedCount,removedCount:e.removedCount,size:e.size,...e.sample?{sample:e.sample}:{},...e.triggeredBy?{triggeredBy:e.triggeredBy}:{}};this.events.delivery.emit(r)}emitSnapshotSuppressed(e){if(!this.events.suppressed.hasSubscribers)return;const r={kind:"snapshot_suppressed",id:vr().replace(/^req-/,"sup-"),at:Date.now(),listenerId:e.listenerId,target:e.target,auth:e.auth?{uid:e.auth.uid,...e.auth.token?{token:e.auth.token}:{}}:null,reason:"no-op",...e.triggeredBy?{triggeredBy:e.triggeredBy}:{}};this.events.suppressed.emit(r)}emitLifecycle(e){if(!this.events.lifecycle.hasSubscribers)return;const r={kind:e.phase,id:vr().replace(/^req-/,"lc-"),at:Date.now(),listenerId:e.listenerId,target:e.target,auth:e.auth?{uid:e.auth.uid,...e.auth.token?{token:e.auth.token}:{}}:null};this.events.lifecycle.emit(r)}emitSnapshotError(e,r,n){this.events.snapshotError.emit(e,r,n)}addSnapshotListener(e,r,n={},s=null,i,a=!1,o=!1,c){const u=String(this.nextListenerId++),d={id:u,target:e,callback:r,auth:s,bypassRules:o,followsCurrentUser:a,...c?{authScope:c}:{},options:n,currentSnapshot:void 0,errored:!1,...i?{errorCallback:i}:{}};return this.snapshotListeners.set(u,d),this.emitLifecycle({phase:"listener_attach",listenerId:u,target:e.kind==="doc"?{kind:"doc",path:e.path}:{kind:"query",collection:e.collection,...e.constraints?.activityQuery?{query:e.constraints.activityQuery}:{}},auth:s}),this.scheduleDelivery(()=>{this.snapshotListeners.has(u)&&this.fireInitialSnapshot(d)}),()=>{const l=this.snapshotListeners.has(u);this.snapshotListeners.delete(u),l&&this.emitLifecycle({phase:"listener_detach",listenerId:u,target:e.kind==="doc"?{kind:"doc",path:e.path}:{kind:"query",collection:e.collection,...e.constraints?.activityQuery?{query:e.constraints.activityQuery}:{}},auth:s})}}fireInitialSnapshot(e){if(e.target.kind==="doc"){const s=this.host.silentReadDoc(e.target.path,e.auth,e.bypassRules);if(!s.allowed){this.markErrored(e,s.error);return}const i=Jt(e.target.path,s.data);e.currentSnapshot=i,e.currentDocData=s.data;try{e.callback(i)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"doc",path:e.target.path},auth:e.auth,addedCount:s.data!==null?1:0,modifiedCount:0,removedCount:0,size:s.data!==null?1:0,sample:{docs:[{path:e.target.path,data:s.data}]}});return}const r=this.host.silentReadCollection(e.target.collection,e.auth,e.target.constraints,e.bypassRules);if(!r.allowed){this.markErrored(e,r.error);return}const n=Qt({path:e.target.collection},r.docs,{excludesMetadataChanges:!e.options.includeMetadataChanges});e.currentSnapshot=n,e.currentDocs=r.docs;try{e.callback(n)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"query",collection:e.target.collection},auth:e.auth,addedCount:r.docs.length,modifiedCount:0,removedCount:0,size:r.docs.length,sample:{docs:r.docs.map(s=>({path:s.path,data:s.data}))}})}scheduleDelivery(e){this.deliveryQueue.push(e),!this.deliveryScheduled&&(this.deliveryScheduled=!0,queueMicrotask(()=>this.drainDeliveries()))}scheduleTriggeredDelivery(e,r){this.scheduleDelivery(()=>this.triggerScope.run(e,r))}drainDeliveries(){for(this.deliveryScheduled=!1;this.deliveryQueue.length>0;)this.deliveryQueue.shift()()}flushListeners(){this.drainDeliveries()}notifyListenersForPaths(e){if(e.size===0||this.snapshotListeners.size===0)return;const r=this.triggerScope.current(),n=Array.from(this.snapshotListeners.values());for(const s of n)this.scheduleTriggeredDelivery(r,()=>{this.snapshotListeners.has(s.id)&&(s.errored||(s.target.kind==="doc"?this.notifyDocListener(s,e):this.notifyQueryListener(s,e)))})}notifyDocListener(e,r){if(e.target.kind!=="doc"||!r.has(e.target.path))return;const n=this.host.silentReadDoc(e.target.path,e.auth,e.bypassRules);if(!n.allowed){this.markErrored(e,n.error);return}const s=e.currentDocData??null;if(Fa(s,n.data)){this.emitSnapshotSuppressed({listenerId:e.id,target:{kind:"doc",path:e.target.path},auth:e.auth,...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}});return}const i=e.target.path,a=Jt(i,n.data,Na);e.currentSnapshot=a,e.currentDocData=n.data;const o=s!==null,c=n.data!==null,u=!o&&c?1:0,d=o&&!c?1:0,l=o&&c?1:0;try{e.callback(a)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"doc",path:i},auth:e.auth,addedCount:u,modifiedCount:l,removedCount:d,size:c?1:0,sample:{docs:[{path:i,data:n.data}]},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),this.scheduleDocMetadataAck(e,i,n.data)}scheduleDocMetadataAck(e,r,n){e.options.includeMetadataChanges&&this.scheduleTriggeredDelivery(this.triggerScope.current(),()=>{if(!this.snapshotListeners.has(e.id)||e.errored)return;const s=Jt(r,n,nr);e.currentSnapshot=s;try{e.callback(s)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"doc",path:r},auth:e.auth,addedCount:0,modifiedCount:0,removedCount:0,size:n!==null?1:0,sample:{docs:[{path:r,data:n}]},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}})})}notifyQueryListener(e,r){if(e.target.kind!=="query"||!ep(r,e.target.collection))return;const n=this.host.silentReadCollection(e.target.collection,e.auth,e.target.constraints,e.bypassRules);if(!n.allowed){this.markErrored(e,n.error);return}const s=e.target.collection,i=e.currentDocs??[],a=Qt({path:s},n.docs,{excludesMetadataChanges:!e.options.includeMetadataChanges},i,Na),o=a.docChanges();if(o.length===0){if(e.options.includeMetadataChanges){e.currentSnapshot=a,e.currentDocs=n.docs;try{e.callback(a)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"query",collection:s},auth:e.auth,addedCount:0,modifiedCount:0,removedCount:0,size:n.docs.length,sample:{docs:n.docs.map(l=>({path:l.path,data:l.data}))},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),this.scheduleQueryMetadataAck(e,s,n.docs);return}this.emitSnapshotSuppressed({listenerId:e.id,target:{kind:"query",collection:s},auth:e.auth,...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}});return}e.currentSnapshot=a,e.currentDocs=n.docs;let c=0,u=0,d=0;for(const l of o)l.type==="added"?c++:l.type==="modified"?u++:l.type==="removed"&&d++;try{e.callback(a)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"query",collection:s},auth:e.auth,addedCount:c,modifiedCount:u,removedCount:d,size:n.docs.length,sample:{docs:n.docs.map(l=>({path:l.path,data:l.data}))},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),this.scheduleQueryMetadataAck(e,s,n.docs)}scheduleQueryMetadataAck(e,r,n){e.options.includeMetadataChanges&&this.scheduleTriggeredDelivery(this.triggerScope.current(),()=>{if(!this.snapshotListeners.has(e.id)||e.errored)return;const s=Qt({path:r},n,{excludesMetadataChanges:!1},n,nr);e.currentSnapshot=s;try{e.callback(s)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"query",collection:r},auth:e.auth,addedCount:0,modifiedCount:0,removedCount:0,size:n.length,sample:{docs:n.map(i=>({path:i.path,data:i.data}))},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}})})}markErrored(e,r){if(e.errored=!0,this.emitSnapshotError(r,e.target,e.id),!!e.errorCallback)try{e.errorCallback(r)}catch{}}reEvaluateAllListeners(){if(this.snapshotListeners.size===0)return;const e=Array.from(this.snapshotListeners.values());for(const r of e)this.snapshotListeners.has(r.id)&&(r.target.kind==="doc"?this.reEvaluateDocListener(r):this.reEvaluateQueryListener(r))}reevaluateLiveListeners(e,r){if(this.snapshotListeners.size===0)return;const n=Array.from(this.snapshotListeners.values());for(const s of n)s.followsCurrentUser&&s.authScope===r&&this.snapshotListeners.has(s.id)&&(s.auth=e,s.target.kind==="doc"?this.reEvaluateDocListener(s):this.reEvaluateQueryListener(s))}reEvaluateDocListener(e){if(e.target.kind!=="doc")return;const r=this.host.silentReadDoc(e.target.path,e.auth,e.bypassRules);if(!r.allowed){if(e.errored)return;this.markErrored(e,r.error);return}if(e.errored){e.errored=!1;const i=Jt(e.target.path,r.data);e.currentSnapshot=i,e.currentDocData=r.data;try{e.callback(i)}catch{}return}const n=e.currentDocData??null;if(Fa(n,r.data))return;const s=Jt(e.target.path,r.data);e.currentSnapshot=s,e.currentDocData=r.data;try{e.callback(s)}catch{}}reEvaluateQueryListener(e){if(e.target.kind!=="query")return;const r=this.host.silentReadCollection(e.target.collection,e.auth,e.target.constraints,e.bypassRules);if(!r.allowed){if(e.errored)return;this.markErrored(e,r.error);return}if(e.errored){e.errored=!1;const a=Qt({path:e.target.collection},r.docs,{excludesMetadataChanges:!e.options.includeMetadataChanges});e.currentSnapshot=a,e.currentDocs=r.docs;try{e.callback(a)}catch{}return}const n=e.currentDocs??[],s=Qt({path:e.target.collection},r.docs,{excludesMetadataChanges:!e.options.includeMetadataChanges},n);if(s.docChanges().length!==0){e.currentSnapshot=s,e.currentDocs=r.docs;try{e.callback(s)}catch{}}}getSnapshotListenerCount(){return this.snapshotListeners.size}dispose(){this.snapshotListeners.clear(),this.deliveryQueue.length=0,this.deliveryScheduled=!1}}class np{eventLog;host;constructor(e,r){this.eventLog=e,this.host=r}undo(){const e=this.eventLog.popLastWrite();if(!e)return null;if(e.priorDocs)this.host.state.restorePaths(e.priorDocs);else if(e.snapshot)this.host.state.restore(e.snapshot);else return null;return e}redo(){const e=this.eventLog.popLastUndo();if(!e)return null;const r=e.type==="batch"&&e.operations?e.operations.map(o=>o.path):e.path?[e.path]:[],n=!!e.snapshot,s=n?void 0:this.host.capturePriors(r),i=n?this.host.state.snapshot():void 0;if(e.type==="batch"&&e.operations)for(const o of e.operations)o.allowed&&this.host.applyWrite(o.method,o.path,o.data);else e.allowed&&this.host.applyWrite(e.method,e.path,e.data);const a=this.eventLog.append({...e,snapshot:i,priorDocs:s},!0);return{allowed:e.allowed,debugMessages:["Redo: "+(e.allowed?"applied":"skipped (was denied)")],event:a}}getEvents(){return this.eventLog.getEvents()}getEventCount(){return this.eventLog.size()}}class sp{currentSource;parsedCache=null;constructor(e){this.currentSource=e}get source(){return this.currentSource}set(e){this.currentSource=e}ast(){return this.parsedCache?.source!==this.currentSource&&(this.parsedCache={source:this.currentSource,ast:ii(this.currentSource)}),this.parsedCache.ast}}function ee(t,e,r){const n={code:t,message:e};return r?.request&&(n.request=r.request),r?.resource&&(n.resource=r.resource),r?.remediation&&(n.remediation=r.remediation),r?.query&&(n.query=r.query),n}function $n(t,e,r){const n=t.get(e.path),s=e.method==="set"?n!==null?"update":"create":e.method;let i=e.data;if(e.method==="get"||e.method==="list")i=void 0;else if(e.method==="update"&&n&&e.data){const{writes:a,deletedKeys:o}=Tt(e.data),c={...n,...a};for(const u of o)delete c[u];i=c}else e.data&&(i=Tt(e.data).writes);return{description:`${e.method} ${e.path}`,expectation:"ALLOW",method:s,path:e.path,auth:e.auth?{uid:e.auth.uid,token:e.auth.token}:null,data:i,resource:n??void 0,...r?{requestTime:Uf(r)}:{}}}function vc(t,e,r,n,s,i){if(s){const a=n.map(o=>Bf(o.description));return{success:!0,data:{passed:a.length,failed:0,unsupported:0,results:a}}}return r.simulate(e.source,n,{getDoc:a=>t.get(a),...i?{batchProjection:i}:{}})}class ip{events;rules;simulator;host;eventLog;constructor(e,r,n,s,i){this.events=e,this.rules=r,this.simulator=n,this.host=s,this.eventLog=i}get state(){return this.host.state}emitRequest(e){this.events.request.hasSubscribers&&this.events.request.emit(Pn(e))}emitDenial(e){this.events.denial.emit(e)}execute(e){const{method:r,path:n,auth:s,bypassRules:i}=e,a=i?{admin:!0}:void 0,o=xe.fromMillis(Date.now()),c=$n(this.state,e,o),u=Date.now(),d=performance.now(),l=vc(this.state,this.rules,this.simulator,[c],i),f=performance.now()-d;if(!l.success){const L=this.eventLog.append({type:"single",method:r,path:n,auth:s?{uid:s.uid}:null,allowed:!1,debugMessages:[`Simulation error: ${l.error.message}`]});return this.emitRequest({at:u,evalMs:f,method:r,path:n,auth:s,result:"deny",debugMessages:[`Simulation error: ${l.error.message}`],origin:"user",...a?{detail:a}:{}}),{allowed:!1,debugMessages:[l.error.message],event:L}}const y=l.data.results[0];if(y.state==="UNSUPPORTED")throw this.emitRequest({at:u,evalMs:f,method:r,path:n,auth:s,result:"unsupported",debugMessages:Se(y),origin:"user",...a?{detail:a}:{}}),new Fr(Lr(r,n,Se(y)),r,n,Se(y));const b=y.state==="PASSED";let S;b&&(S=r==="get"?this.state.get(n):this.state.list(n));const j=this.eventLog.append({type:"single",method:r,path:n,auth:s?{uid:s.uid}:null,allowed:b,debugMessages:Se(y)}),T={allowed:b,data:b?S:void 0,debugMessages:Se(y),event:j};if(!b){const L={method:r,path:n,auth:s},k=r==="get"?{data:this.state.get(n),exists:this.state.get(n)!==null}:void 0;T.error=ee("permission-denied",`${r} ${n} denied by rules`,{request:L,...k?{resource:k}:{}}),this.emitDenial(T.error)}return this.emitRequest({at:u,evalMs:f,method:r,path:n,auth:s,result:b?"allow":"deny",debugMessages:Se(y),evaluatedRule:Er(y),origin:"user",...r==="get"?{resourceBefore:{data:this.state.get(n),exists:this.state.get(n)!==null}}:{},...a?{detail:a}:{}}),T}}function wc(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 Sc(t,e,r,n=ap){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"?!La.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"&&La.has(t.index.value)):o(t.object)||o(t.index);case"sliceAccess":return o(t.object)||o(t.start)||o(t.end);case"binaryOp":return o(t.left)||o(t.right);case"unaryOp":return o(t.operand);case"ternary":return o(t.condition)||o(t.consequent)||o(t.alternate);case"inExpr":return o(t.element)||o(t.collection);case"isExpr":return o(t.value);case"listLiteral":return t.elements.some(o);case"mapLiteral":return t.entries.some(c=>o(c.key)||o(c.value));case"pathLiteral":return t.segments.some(c=>typeof c!="string"&&o(c));case"functionCall":{if(t.args.some(o)||n.has(t.name))return!0;const c=r.get(t.name);if(!c)return!1;if(a.add(c.name),i.has(c.name))return!0;const u=new Set(i).add(c.name),d=new Set(c.parameters);for(const l of c.lets){if(Kr(l.value,e,r,n,d,u,a))return!0;d.add(l.name)}return Kr(c.body,e,r,n,d,u,a)}}}const La=new Set(["auth","method","query","time"]),ap=new Set;function op(t){if(!t)return null;const e=[...t.functions??[],...t.service.functions??[],...t.service.match.functions],r=new Set,n=t.service.match.children.flatMap(i=>{const a=cp(i,e,r);return a?[a]:[]});if(n.length===0)return null;const s=i=>i?.filter(a=>r.has(a.name));return{...t,functions:s(t.functions),service:{...t.service,functions:s(t.service.functions),match:{...t.service.match,functions:s(t.service.match.functions)??[],children:n}}}}function cp(t,e,r){const n=t.path.segments[0];if(t.path.segments.length!==1||n?.type!=="recursive")return null;const s=wc([...e,...t.functions]),i=t.allows.filter(a=>{if(!a.operations.some(c=>c==="list"||c==="read"))return!1;const o=Sc(a.condition,new Set([n.name]),s.functions,s.ambiguousNames);if(o.pathInvariant)for(const c of o.requiredFunctions)r.add(c);return o.pathInvariant});return i.length===0?null:{...t,functions:t.functions.filter(a=>r.has(a.name)),allows:i,children:[]}}function up(t,e,r,n){if(!t)return{kind:"no-rule"};const s=e.split("/").filter(d=>d.length>0),i=[...t.functions??[],...t.service.functions??[],...t.service.match.functions],a=[];for(const d of t.service.match.children)a.push(...on(d,s,i));if(a.length===0)return{kind:"no-rule"};const o=[],c=new Set;let u=0;for(const d of a){const l=wc(d.functions),f=l.functions;for(const y of d.block.allows){if(!y.operations.some(j=>j==="list"||j==="read"))continue;if(u++,!Sc(y.condition,new Set(d.candidateVariables),f,l.ambiguousNames).pathInvariant){o.push({reason:"list rule depends on the candidate document path",residual:{missing:[],mismatched:[]}});continue}const S=jd(y.condition,n,f,r?.uid);S.provable?c.add(y):o.push({reason:S.reason,residual:S.residual})}}if(u===0)return{kind:"no-rule"};if(c.size===0){const d=o[0];return{kind:"unprovable",reason:d?.reason??"list rule depends on per-document data the query cannot guarantee",residual:d?.residual??{missing:[],mismatched:[]}}}return{kind:"provable",evaluationAst:lp(t,c),syntheticResource:dp(n)}}function lp(t,e){const r=n=>({...n,allows:n.allows.filter(s=>e.has(s)),children:n.children.map(r)});return{...t,service:{...t.service,match:r(t.service.match)}}}function dp(t){const e={};for(const r of t.where??[])r.op==="=="&&(e[r.field]=r.value);return e}function hp(t){const e=[];for(const n of t.missing)n.fromAuthUid?e.push(` .where('${n.field}', '==', request.auth.uid) // request.auth.uid is ${JSON.stringify(n.expectedValue)}`):e.push(` .where('${n.field}', '==', ${JSON.stringify(n.expectedValue)})`);for(const n of t.mismatched)e.push(` .where('${n.field}', '==', ${JSON.stringify(n.expectedValue)}) // the query pins ${JSON.stringify(n.actualValue)}, but the rule requires ${JSON.stringify(n.expectedValue)}`);return e.length===0?void 0:`The list rule requires per-document equalities the query does not guarantee. Add the matching where(...) constraint(s) so every returned document satisfies the rule:
1146
+ `;class Ot{swallowAsyncRejections;subscribers=new Set;constructor(e=!1){this.swallowAsyncRejections=e}get hasSubscribers(){return this.subscribers.size>0}subscribe(e){return this.subscribers.add(e),()=>{this.subscribers.delete(e)}}emit(...e){for(const r of this.subscribers)try{const n=r(...e);this.swallowAsyncRejections&&n&&typeof n.then=="function"&&n.catch(()=>{})}catch{}}clear(){this.subscribers.clear()}}class Vf{denial=new Ot;request=new Ot(!0);write=new Ot(!0);delivery=new Ot;suppressed=new Ot;lifecycle=new Ot;snapshotError=new Ot;clear(){this.denial.clear(),this.request.clear(),this.write.clear(),this.delivery.clear(),this.suppressed.clear(),this.lifecycle.clear(),this.snapshotError.clear()}}class Wf{currentTrigger;run(e,r){const n=this.currentTrigger;this.currentTrigger=e;try{return r()}finally{this.currentTrigger=n}}current(){return this.currentTrigger}}class ce extends Error{code;simError;constructor(e){super(e.message),this.name="FirestoreError",this.code=e.code,this.simError=e}}const Oa=Symbol.for("pyric.firestore.activity-value-registry"),Ca=globalThis,fc=Ca[Oa]??(Ca[Oa]=new WeakMap);function pc(){let t=2166136261,e=2654435769,r=2246822507,n=3266489909;const s=i=>{t=Math.imul(t^i,16777619),e=Math.imul(e^i,2246822507),r=Math.imul(r^i,3266489909),n=Math.imul(n^i,668265263)};return{update:i=>{if(typeof i=="string")for(let a=0;a<i.length;a+=1){const o=i.charCodeAt(a);s(o&255),s(o>>>8)}else for(const a of i)s(a)},finish:()=>[t,e,r,n].map(i=>(i>>>0).toString(16).padStart(8,"0")).join("")}}function pi(...t){const e=pc();for(const r of t)e.update(r);return e.finish()}function Hf(t){return{type:"string-digest",length:t.length,digest:pi("string\0",t)}}function qt(t,...e){return{type:`${t}-digest`,digest:pi(`${t}\0`,...e)}}function Gf(t){return{type:"bytes-digest",length:t.byteLength,digest:pi("bytes\0",t)}}function Ta(t){const e=pc(),r=(...s)=>{for(const i of s)e.update(i)},n=s=>{if(s===null){r("null;");return}switch(typeof s){case"string":r(`s${s.length}:`,s,";");return;case"number":r(`n${Object.is(s,-0)?"-0":String(s)};`);return;case"boolean":r(s?"b1;":"b0;");return;case"undefined":r("u;");return;case"bigint":r(`i${s.toString()};`);return;case"object":break;default:r(`x${typeof s};`);return}if(Array.isArray(s)){r(`a${s.length}[`);for(const o of s)n(o);r("];");return}const i=s,a=Object.keys(i).sort();r(`o${a.length}{`);for(const o of a)r(`k${o.length}:`,o,"="),n(i[o]);r("};")};return n(t),{type:"wire-value-digest",digest:e.finish()}}function st(t,e){fc.set(t,e)}function Kf(t){return fc.get(t)}class Zf{static serverTimestamp(){return{__type:"serverTimestamp"}}static increment(e){return{__type:"increment",value:e}}static arrayUnion(...e){return{__type:"arrayUnion",values:e}}static arrayRemove(...e){return{__type:"arrayRemove",values:e}}static delete(){return{__type:"deleteField"}}}class bt{seconds;nanoseconds;constructor(e,r){this.seconds=e,this.nanoseconds=r,st(this,qt("timestamp",String(e),"\0",String(r))),Ht(this,Object.freeze({type:"timestamp",seconds:e,nanoseconds:r}),()=>new bt(e,r))}static now(){return bt.fromMillis(Date.now())}static fromDate(e){return bt.fromMillis(e.getTime())}static fromMillis(e){const r=Math.floor(e/1e3),n=Math.floor((e-r*1e3)*1e6);return new bt(r,n)}toDate(){return new Date(this.toMillis())}toMillis(){return this.seconds*1e3+this.nanoseconds/1e6}isEqual(e){return e.seconds===this.seconds&&e.nanoseconds===this.nanoseconds}toString(){return`Timestamp(seconds=${this.seconds}, nanoseconds=${this.nanoseconds})`}toJSON(){return{type:"firestore/timestamp/1.0",seconds:this.seconds,nanoseconds:this.nanoseconds}}valueOf(){const r=this.seconds- -62135596800,n=String(r).padStart(12,"0"),s=String(this.nanoseconds).padStart(9,"0");return`${n}.${s}`}}function Ls(t){return t instanceof xe?new bt(t.seconds,t.nanos):t instanceof Be||t instanceof rt||t instanceof Wt?t:Array.isArray(t)?t.map(Ls):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).map(([e,r])=>[e,Ls(r)])):t}function jr(t){return Ls(t)}const Jf=/[*~/[\]]/,Qf=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class kn{_internalPath;constructor(...e){if(Array.isArray(e[0]))throw new Error("The FieldPath constructor no longer supports an array as its first argument. Please unpack your array and call FieldPath() with individual arguments.");if(e.length===0)throw new Error('Function "FieldPath()" requires at least 1 argument.');e.forEach((r,n)=>{if(typeof r!="string")throw new Error(`Element at index ${n} is not a valid string.`);if(r.length===0)throw new Error(`Element at index ${n} should not be an empty string.`)}),this._internalPath={segments:[...e],offset:0,len:e.length}}static DOCUMENT_ID=new kn("__name__");static documentId(){return kn.DOCUMENT_ID}isEqual(e){const r=mc(e),n=this._internalPath.segments;return n.length===r.length&&n.every((s,i)=>s===r[i])}toString(){return this._internalPath.segments.map(e=>Qf.test(e)?e:`\`${e.replace(/\\/g,"\\\\").replace(/`/g,"\\`")}\``).join(".")}}function lr(t){return new Error(`Value for argument "field" is not a valid field path. ${t}`)}function mc(t){if(t instanceof kn)return t._internalPath.segments;if(typeof t=="object"&&t!==null){const e=t._internalPath;if(Array.isArray(e?.segments)&&e.segments.every(r=>typeof r=="string"))return[...e.segments]}if(t===void 0)throw lr("The path cannot be omitted.");if(typeof t!="string")throw lr("Paths can only be specified as strings or via a FieldPath object.");if(t.includes(".."))throw lr('Paths must not contain ".." in them.');if(t.startsWith(".")||t.endsWith("."))throw lr('Paths must not start or end with ".".');if(t.length===0||Jf.test(t))throw lr(`Paths can't be empty and must not contain
1147
+ "*~/[]".`);return t.split(".")}function Yf(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function or(t,e){const r=mc(e);let n=t;for(const s of r){if(!Yf(n))return;n=Object.prototype.hasOwnProperty.call(n,s)?n[s]:void 0}return n}const nr=Object.freeze({hasPendingWrites:!1,fromCache:!1}),Ra=Object.freeze({hasPendingWrites:!0,fromCache:!1});function gc(t){const e=t.lastIndexOf("/");return e===-1?t:t.slice(e+1)}function Jt(t,e,r=nr){const n={id:gc(t),path:t},s=e!==null,i=s?jr(e):void 0;return{id:n.id,ref:n,metadata:r,exists:()=>s,data:()=>i,get:a=>or(i,a)}}function yc(t,e,r=nr){const n={id:gc(t),path:t},s=jr(e);return{id:n.id,ref:n,metadata:r,exists:()=>!0,data:()=>s,get:i=>or(s,i)}}function Qt(t,e,r,n,s=nr){const i=e.map(u=>yc(u.path,u.data,s)),a=n?Xf(n,e,i,s):i.map((u,d)=>({type:"added",doc:u,oldIndex:-1,newIndex:d}));let o=null,c=null;return{query:t,metadata:s,size:i.length,empty:i.length===0,docs:i,forEach(u){for(const d of i)u(d)},docChanges(u){const d=!!u?.includeMetadataChanges;if(d&&r.excludesMetadataChanges)throw new Error("To include metadata changes with your document changes, you must also pass { includeMetadataChanges: true } to onSnapshot().");return d?(c||(c=a.slice()),c):(o||(o=a.slice()),o)}}}function Xf(t,e,r,n=nr){const s=new Map;t.forEach((o,c)=>s.set(o.path,c));const i=new Map;e.forEach((o,c)=>i.set(o.path,c));const a=[];for(let o=0;o<t.length;o++){const c=t[o];i.has(c.path)||a.push({type:"removed",doc:yc(c.path,c.data,n),oldIndex:o,newIndex:-1})}for(let o=0;o<e.length;o++){const c=e[o],u=s.get(c.path);if(u===void 0)a.push({type:"added",doc:r[o],oldIndex:-1,newIndex:o});else{const d=t[u].data;JSON.stringify(d)!==JSON.stringify(c.data)&&a.push({type:"modified",doc:r[o],oldIndex:u,newIndex:o})}}return a}function Na(t,e){return t===null&&e===null?!0:t===null||e===null?!1:JSON.stringify(t)===JSON.stringify(e)}function ep(t,e){const r=`${e}/`;for(const n of t){if(!n.startsWith(r))continue;const s=n.slice(r.length);if(s.length>0&&!s.includes("/"))return!0}return!1}let es=0;function vr(){return es=es+1>>>0,`req-${es.toString(36)}-${Math.random().toString(36).slice(2,7)}`}function tp(t,e){const r=e==="allow";let n;for(const s of t){const i=/^Rule #(\d+) \(([^)]+)\) → (ALLOW|deny|unsupported)/.exec(s);if(!i)continue;const a={ruleIndex:Number(i[1]),operations:i[2].split(",").map(o=>o.trim())};if(r&&i[3]==="ALLOW")return a;n=a}return n}function Mn(t){const e={kind:"request",id:vr(),at:t.at,evalMs:t.evalMs,method:t.method,path:t.path,auth:t.auth?{uid:t.auth.uid,...t.auth.token?{token:t.auth.token}:{}}:null,result:t.result,reasons:t.debugMessages,origin:t.origin};t.resourceData!==void 0&&(e.request={resourceData:t.resourceData}),t.resourceBefore!==void 0&&(e.resourceBefore=t.resourceBefore),t.resourceAfter!==void 0&&(e.resourceAfter=t.resourceAfter);const r=tp(t.debugMessages,t.result);return r&&(e.matchedRule=r),t.result!=="unsupported"&&t.evaluatedRule&&(e.evaluatedRule=t.evaluatedRule),t.groupId!==void 0&&(e.groupId=t.groupId,t.origin==="batch"?e.groupKind="batch":t.origin==="transaction"&&(e.groupKind="transaction")),t.triggeredBy!==void 0&&(e.triggeredBy=t.triggeredBy),t.detail!==void 0&&(e.detail=t.detail),t.provenance!==void 0&&Object.assign(e,t.provenance),e}class rp{events;triggerScope;host;snapshotListeners=new Map;nextListenerId=0;deliveryQueue=[];deliveryScheduled=!1;constructor(e,r,n){this.events=e,this.triggerScope=r,this.host=n}emitSnapshotDelivery(e){if(!this.events.delivery.hasSubscribers)return;const r={kind:"snapshot_delivery",id:vr().replace(/^req-/,"snd-"),at:Date.now(),listenerId:e.listenerId,target:e.target,auth:e.auth?{uid:e.auth.uid,...e.auth.token?{token:e.auth.token}:{}}:null,addedCount:e.addedCount,modifiedCount:e.modifiedCount,removedCount:e.removedCount,size:e.size,...e.sample?{sample:e.sample}:{},...e.triggeredBy?{triggeredBy:e.triggeredBy}:{}};this.events.delivery.emit(r)}emitSnapshotSuppressed(e){if(!this.events.suppressed.hasSubscribers)return;const r={kind:"snapshot_suppressed",id:vr().replace(/^req-/,"sup-"),at:Date.now(),listenerId:e.listenerId,target:e.target,auth:e.auth?{uid:e.auth.uid,...e.auth.token?{token:e.auth.token}:{}}:null,reason:"no-op",...e.triggeredBy?{triggeredBy:e.triggeredBy}:{}};this.events.suppressed.emit(r)}emitLifecycle(e){if(!this.events.lifecycle.hasSubscribers)return;const r={kind:e.phase,id:vr().replace(/^req-/,"lc-"),at:Date.now(),listenerId:e.listenerId,target:e.target,auth:e.auth?{uid:e.auth.uid,...e.auth.token?{token:e.auth.token}:{}}:null};this.events.lifecycle.emit(r)}emitSnapshotError(e,r,n){this.events.snapshotError.emit(e,r,n)}addSnapshotListener(e,r,n={},s=null,i,a=!1,o=!1,c){const u=String(this.nextListenerId++),d={id:u,target:e,callback:r,auth:s,bypassRules:o,followsCurrentUser:a,...c?{authScope:c}:{},options:n,currentSnapshot:void 0,errored:!1,...i?{errorCallback:i}:{}};return this.snapshotListeners.set(u,d),this.emitLifecycle({phase:"listener_attach",listenerId:u,target:e.kind==="doc"?{kind:"doc",path:e.path}:{kind:"query",collection:e.collection,...e.constraints?.activityQuery?{query:e.constraints.activityQuery}:{}},auth:s}),this.scheduleDelivery(()=>{this.snapshotListeners.has(u)&&this.fireInitialSnapshot(d)}),()=>{const l=this.snapshotListeners.has(u);this.snapshotListeners.delete(u),l&&this.emitLifecycle({phase:"listener_detach",listenerId:u,target:e.kind==="doc"?{kind:"doc",path:e.path}:{kind:"query",collection:e.collection,...e.constraints?.activityQuery?{query:e.constraints.activityQuery}:{}},auth:s})}}fireInitialSnapshot(e){if(e.target.kind==="doc"){const s=this.host.silentReadDoc(e.target.path,e.auth,e.bypassRules);if(!s.allowed){this.markErrored(e,s.error);return}const i=Jt(e.target.path,s.data);e.currentSnapshot=i,e.currentDocData=s.data;try{e.callback(i)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"doc",path:e.target.path},auth:e.auth,addedCount:s.data!==null?1:0,modifiedCount:0,removedCount:0,size:s.data!==null?1:0,sample:{docs:[{path:e.target.path,data:s.data}]}});return}const r=this.host.silentReadCollection(e.target.collection,e.auth,e.target.constraints,e.bypassRules);if(!r.allowed){this.markErrored(e,r.error);return}const n=Qt({path:e.target.collection},r.docs,{excludesMetadataChanges:!e.options.includeMetadataChanges});e.currentSnapshot=n,e.currentDocs=r.docs;try{e.callback(n)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"query",collection:e.target.collection},auth:e.auth,addedCount:r.docs.length,modifiedCount:0,removedCount:0,size:r.docs.length,sample:{docs:r.docs.map(s=>({path:s.path,data:s.data}))}})}scheduleDelivery(e){this.deliveryQueue.push(e),!this.deliveryScheduled&&(this.deliveryScheduled=!0,queueMicrotask(()=>this.drainDeliveries()))}scheduleTriggeredDelivery(e,r){this.scheduleDelivery(()=>this.triggerScope.run(e,r))}drainDeliveries(){for(this.deliveryScheduled=!1;this.deliveryQueue.length>0;)this.deliveryQueue.shift()()}flushListeners(){this.drainDeliveries()}notifyListenersForPaths(e){if(e.size===0||this.snapshotListeners.size===0)return;const r=this.triggerScope.current(),n=Array.from(this.snapshotListeners.values());for(const s of n)this.scheduleTriggeredDelivery(r,()=>{this.snapshotListeners.has(s.id)&&(s.errored||(s.target.kind==="doc"?this.notifyDocListener(s,e):this.notifyQueryListener(s,e)))})}notifyDocListener(e,r){if(e.target.kind!=="doc"||!r.has(e.target.path))return;const n=this.host.silentReadDoc(e.target.path,e.auth,e.bypassRules);if(!n.allowed){this.markErrored(e,n.error);return}const s=e.currentDocData??null;if(Na(s,n.data)){this.emitSnapshotSuppressed({listenerId:e.id,target:{kind:"doc",path:e.target.path},auth:e.auth,...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}});return}const i=e.target.path,a=Jt(i,n.data,Ra);e.currentSnapshot=a,e.currentDocData=n.data;const o=s!==null,c=n.data!==null,u=!o&&c?1:0,d=o&&!c?1:0,l=o&&c?1:0;try{e.callback(a)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"doc",path:i},auth:e.auth,addedCount:u,modifiedCount:l,removedCount:d,size:c?1:0,sample:{docs:[{path:i,data:n.data}]},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),this.scheduleDocMetadataAck(e,i,n.data)}scheduleDocMetadataAck(e,r,n){e.options.includeMetadataChanges&&this.scheduleTriggeredDelivery(this.triggerScope.current(),()=>{if(!this.snapshotListeners.has(e.id)||e.errored)return;const s=Jt(r,n,nr);e.currentSnapshot=s;try{e.callback(s)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"doc",path:r},auth:e.auth,addedCount:0,modifiedCount:0,removedCount:0,size:n!==null?1:0,sample:{docs:[{path:r,data:n}]},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}})})}notifyQueryListener(e,r){if(e.target.kind!=="query"||!ep(r,e.target.collection))return;const n=this.host.silentReadCollection(e.target.collection,e.auth,e.target.constraints,e.bypassRules);if(!n.allowed){this.markErrored(e,n.error);return}const s=e.target.collection,i=e.currentDocs??[],a=Qt({path:s},n.docs,{excludesMetadataChanges:!e.options.includeMetadataChanges},i,Ra),o=a.docChanges();if(o.length===0){if(e.options.includeMetadataChanges){e.currentSnapshot=a,e.currentDocs=n.docs;try{e.callback(a)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"query",collection:s},auth:e.auth,addedCount:0,modifiedCount:0,removedCount:0,size:n.docs.length,sample:{docs:n.docs.map(l=>({path:l.path,data:l.data}))},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),this.scheduleQueryMetadataAck(e,s,n.docs);return}this.emitSnapshotSuppressed({listenerId:e.id,target:{kind:"query",collection:s},auth:e.auth,...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}});return}e.currentSnapshot=a,e.currentDocs=n.docs;let c=0,u=0,d=0;for(const l of o)l.type==="added"?c++:l.type==="modified"?u++:l.type==="removed"&&d++;try{e.callback(a)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"query",collection:s},auth:e.auth,addedCount:c,modifiedCount:u,removedCount:d,size:n.docs.length,sample:{docs:n.docs.map(l=>({path:l.path,data:l.data}))},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),this.scheduleQueryMetadataAck(e,s,n.docs)}scheduleQueryMetadataAck(e,r,n){e.options.includeMetadataChanges&&this.scheduleTriggeredDelivery(this.triggerScope.current(),()=>{if(!this.snapshotListeners.has(e.id)||e.errored)return;const s=Qt({path:r},n,{excludesMetadataChanges:!1},n,nr);e.currentSnapshot=s;try{e.callback(s)}catch{}this.emitSnapshotDelivery({listenerId:e.id,target:{kind:"query",collection:r},auth:e.auth,addedCount:0,modifiedCount:0,removedCount:0,size:n.length,sample:{docs:n.map(i=>({path:i.path,data:i.data}))},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}})})}markErrored(e,r){if(e.errored=!0,this.emitSnapshotError(r,e.target,e.id),!!e.errorCallback)try{e.errorCallback(r)}catch{}}reEvaluateAllListeners(){if(this.snapshotListeners.size===0)return;const e=Array.from(this.snapshotListeners.values());for(const r of e)this.snapshotListeners.has(r.id)&&(r.target.kind==="doc"?this.reEvaluateDocListener(r):this.reEvaluateQueryListener(r))}reevaluateLiveListeners(e,r){if(this.snapshotListeners.size===0)return;const n=Array.from(this.snapshotListeners.values());for(const s of n)s.followsCurrentUser&&s.authScope===r&&this.snapshotListeners.has(s.id)&&(s.auth=e,s.target.kind==="doc"?this.reEvaluateDocListener(s):this.reEvaluateQueryListener(s))}reEvaluateDocListener(e){if(e.target.kind!=="doc")return;const r=this.host.silentReadDoc(e.target.path,e.auth,e.bypassRules);if(!r.allowed){if(e.errored)return;this.markErrored(e,r.error);return}if(e.errored){e.errored=!1;const i=Jt(e.target.path,r.data);e.currentSnapshot=i,e.currentDocData=r.data;try{e.callback(i)}catch{}return}const n=e.currentDocData??null;if(Na(n,r.data))return;const s=Jt(e.target.path,r.data);e.currentSnapshot=s,e.currentDocData=r.data;try{e.callback(s)}catch{}}reEvaluateQueryListener(e){if(e.target.kind!=="query")return;const r=this.host.silentReadCollection(e.target.collection,e.auth,e.target.constraints,e.bypassRules);if(!r.allowed){if(e.errored)return;this.markErrored(e,r.error);return}if(e.errored){e.errored=!1;const a=Qt({path:e.target.collection},r.docs,{excludesMetadataChanges:!e.options.includeMetadataChanges});e.currentSnapshot=a,e.currentDocs=r.docs;try{e.callback(a)}catch{}return}const n=e.currentDocs??[],s=Qt({path:e.target.collection},r.docs,{excludesMetadataChanges:!e.options.includeMetadataChanges},n);if(s.docChanges().length!==0){e.currentSnapshot=s,e.currentDocs=r.docs;try{e.callback(s)}catch{}}}getSnapshotListenerCount(){return this.snapshotListeners.size}dispose(){this.snapshotListeners.clear(),this.deliveryQueue.length=0,this.deliveryScheduled=!1}}class np{eventLog;host;constructor(e,r){this.eventLog=e,this.host=r}undo(){const e=this.eventLog.popLastWrite();if(!e)return null;if(e.priorDocs)this.host.state.restorePaths(e.priorDocs);else if(e.snapshot)this.host.state.restore(e.snapshot);else return null;return e}redo(){const e=this.eventLog.popLastUndo();if(!e)return null;const r=e.type==="batch"&&e.operations?e.operations.map(o=>o.path):e.path?[e.path]:[],n=!!e.snapshot,s=n?void 0:this.host.capturePriors(r),i=n?this.host.state.snapshot():void 0;if(e.type==="batch"&&e.operations)for(const o of e.operations)o.allowed&&this.host.applyWrite(o.method,o.path,o.data);else e.allowed&&this.host.applyWrite(e.method,e.path,e.data);const a=this.eventLog.append({...e,snapshot:i,priorDocs:s},!0);return{allowed:e.allowed,debugMessages:["Redo: "+(e.allowed?"applied":"skipped (was denied)")],event:a}}getEvents(){return this.eventLog.getEvents()}getEventCount(){return this.eventLog.size()}}class sp{currentSource;parsedCache=null;constructor(e){this.currentSource=e}get source(){return this.currentSource}set(e){this.currentSource=e}ast(){return this.parsedCache?.source!==this.currentSource&&(this.parsedCache={source:this.currentSource,ast:si(this.currentSource)}),this.parsedCache.ast}}function ee(t,e,r){const n={code:t,message:e};return r?.request&&(n.request=r.request),r?.resource&&(n.resource=r.resource),r?.remediation&&(n.remediation=r.remediation),r?.query&&(n.query=r.query),n}function Pn(t,e,r){const n=t.get(e.path),s=e.method==="set"?n!==null?"update":"create":e.method;let i=e.data;if(e.method==="get"||e.method==="list")i=void 0;else if(e.method==="update"&&n&&e.data){const{writes:a,deletedKeys:o}=Tt(e.data),c={...n,...a};for(const u of o)delete c[u];i=c}else e.data&&(i=Tt(e.data).writes);return{description:`${e.method} ${e.path}`,expectation:"ALLOW",method:s,path:e.path,auth:e.auth?{uid:e.auth.uid,token:e.auth.token}:null,data:i,resource:n??void 0,...r?{requestTime:Uf(r)}:{}}}function bc(t,e,r,n,s,i){if(s){const a=n.map(o=>Bf(o.description));return{success:!0,data:{passed:a.length,failed:0,unsupported:0,results:a}}}return r.simulate(e.source,n,{getDoc:a=>t.get(a),...i?{batchProjection:i}:{}})}class ip{events;rules;simulator;host;eventLog;constructor(e,r,n,s,i){this.events=e,this.rules=r,this.simulator=n,this.host=s,this.eventLog=i}get state(){return this.host.state}emitRequest(e){this.events.request.hasSubscribers&&this.events.request.emit(Mn(e))}emitDenial(e){this.events.denial.emit(e)}execute(e){const{method:r,path:n,auth:s,bypassRules:i}=e,a=i?{admin:!0}:void 0,o=xe.fromMillis(Date.now()),c=Pn(this.state,e,o),u=Date.now(),d=performance.now(),l=bc(this.state,this.rules,this.simulator,[c],i),f=performance.now()-d;if(!l.success){const L=this.eventLog.append({type:"single",method:r,path:n,auth:s?{uid:s.uid}:null,allowed:!1,debugMessages:[`Simulation error: ${l.error.message}`]});return this.emitRequest({at:u,evalMs:f,method:r,path:n,auth:s,result:"deny",debugMessages:[`Simulation error: ${l.error.message}`],origin:"user",...a?{detail:a}:{}}),{allowed:!1,debugMessages:[l.error.message],event:L}}const y=l.data.results[0];if(y.state==="UNSUPPORTED")throw this.emitRequest({at:u,evalMs:f,method:r,path:n,auth:s,result:"unsupported",debugMessages:Se(y),origin:"user",...a?{detail:a}:{}}),new Fr(Lr(r,n,Se(y)),r,n,Se(y));const b=y.state==="PASSED";let S;b&&(S=r==="get"?this.state.get(n):this.state.list(n));const j=this.eventLog.append({type:"single",method:r,path:n,auth:s?{uid:s.uid}:null,allowed:b,debugMessages:Se(y)}),T={allowed:b,data:b?S:void 0,debugMessages:Se(y),event:j};if(!b){const L={method:r,path:n,auth:s},k=r==="get"?{data:this.state.get(n),exists:this.state.get(n)!==null}:void 0;T.error=ee("permission-denied",`${r} ${n} denied by rules`,{request:L,...k?{resource:k}:{}}),this.emitDenial(T.error)}return this.emitRequest({at:u,evalMs:f,method:r,path:n,auth:s,result:b?"allow":"deny",debugMessages:Se(y),evaluatedRule:Er(y),origin:"user",...r==="get"?{resourceBefore:{data:this.state.get(n),exists:this.state.get(n)!==null}}:{},...a?{detail:a}:{}}),T}}function vc(t){const e=new Map,r=new Set;for(const n of t)e.has(n.name)&&r.add(n.name),e.set(n.name,n);return{functions:e,ambiguousNames:r}}function wc(t,e,r,n=ap){const s=new Set;return{pathInvariant:!Gr(t,e,r,n,new Set,new Set,s),requiredFunctions:s}}function Gr(t,e,r,n,s,i,a){const o=c=>Gr(c,e,r,n,s,i,a);switch(t.type){case"literal":return!1;case"identifier":return!s.has(t.name)&&(e.has(t.name)||t.name==="request");case"memberAccess":return t.object.type==="identifier"&&t.object.name==="request"?!Fa.has(t.property):o(t.object);case"methodCall":return o(t.object)||t.args.some(o);case"bracketAccess":return t.object.type==="identifier"&&t.object.name==="request"?!(t.index.type==="literal"&&typeof t.index.value=="string"&&Fa.has(t.index.value)):o(t.object)||o(t.index);case"sliceAccess":return o(t.object)||o(t.start)||o(t.end);case"binaryOp":return o(t.left)||o(t.right);case"unaryOp":return o(t.operand);case"ternary":return o(t.condition)||o(t.consequent)||o(t.alternate);case"inExpr":return o(t.element)||o(t.collection);case"isExpr":return o(t.value);case"listLiteral":return t.elements.some(o);case"mapLiteral":return t.entries.some(c=>o(c.key)||o(c.value));case"pathLiteral":return t.segments.some(c=>typeof c!="string"&&o(c));case"functionCall":{if(t.args.some(o)||n.has(t.name))return!0;const c=r.get(t.name);if(!c)return!1;if(a.add(c.name),i.has(c.name))return!0;const u=new Set(i).add(c.name),d=new Set(c.parameters);for(const l of c.lets){if(Gr(l.value,e,r,n,d,u,a))return!0;d.add(l.name)}return Gr(c.body,e,r,n,d,u,a)}}}const Fa=new Set(["auth","method","query","time"]),ap=new Set;function op(t){if(!t)return null;const e=[...t.functions??[],...t.service.functions??[],...t.service.match.functions],r=new Set,n=t.service.match.children.flatMap(i=>{const a=cp(i,e,r);return a?[a]:[]});if(n.length===0)return null;const s=i=>i?.filter(a=>r.has(a.name));return{...t,functions:s(t.functions),service:{...t.service,functions:s(t.service.functions),match:{...t.service.match,functions:s(t.service.match.functions)??[],children:n}}}}function cp(t,e,r){const n=t.path.segments[0];if(t.path.segments.length!==1||n?.type!=="recursive")return null;const s=vc([...e,...t.functions]),i=t.allows.filter(a=>{if(!a.operations.some(c=>c==="list"||c==="read"))return!1;const o=wc(a.condition,new Set([n.name]),s.functions,s.ambiguousNames);if(o.pathInvariant)for(const c of o.requiredFunctions)r.add(c);return o.pathInvariant});return i.length===0?null:{...t,functions:t.functions.filter(a=>r.has(a.name)),allows:i,children:[]}}function up(t,e,r,n){if(!t)return{kind:"no-rule"};const s=e.split("/").filter(d=>d.length>0),i=[...t.functions??[],...t.service.functions??[],...t.service.match.functions],a=[];for(const d of t.service.match.children)a.push(...an(d,s,i));if(a.length===0)return{kind:"no-rule"};const o=[],c=new Set;let u=0;for(const d of a){const l=vc(d.functions),f=l.functions;for(const y of d.block.allows){if(!y.operations.some(j=>j==="list"||j==="read"))continue;if(u++,!wc(y.condition,new Set(d.candidateVariables),f,l.ambiguousNames).pathInvariant){o.push({reason:"list rule depends on the candidate document path",residual:{missing:[],mismatched:[]}});continue}const S=Ld(y.condition,n,f,r?.uid);S.provable?c.add(y):o.push({reason:S.reason,residual:S.residual})}}if(u===0)return{kind:"no-rule"};if(c.size===0){const d=o[0];return{kind:"unprovable",reason:d?.reason??"list rule depends on per-document data the query cannot guarantee",residual:d?.residual??{missing:[],mismatched:[]}}}return{kind:"provable",evaluationAst:lp(t,c),syntheticResource:dp(n)}}function lp(t,e){const r=n=>({...n,allows:n.allows.filter(s=>e.has(s)),children:n.children.map(r)});return{...t,service:{...t.service,match:r(t.service.match)}}}function dp(t){const e={};for(const r of t.where??[])r.op==="=="&&(e[r.field]=r.value);return e}function hp(t){const e=[];for(const n of t.missing)n.fromAuthUid?e.push(` .where('${n.field}', '==', request.auth.uid) // request.auth.uid is ${JSON.stringify(n.expectedValue)}`):e.push(` .where('${n.field}', '==', ${JSON.stringify(n.expectedValue)})`);for(const n of t.mismatched)e.push(` .where('${n.field}', '==', ${JSON.stringify(n.expectedValue)}) // the query pins ${JSON.stringify(n.actualValue)}, but the rule requires ${JSON.stringify(n.expectedValue)}`);return e.length===0?void 0:`The list rule requires per-document equalities the query does not guarantee. Add the matching where(...) constraint(s) so every returned document satisfies the rule:
1148
1148
  ${e.join(`
1149
- `)}`}function fp(t){if(!(t.limit==null&&t.offset==null&&t.orderBy==null))return{...t.limit!=null?{limit:t.limit}:{},...t.offset!=null?{offset:t.offset}:{},...t.orderBy!=null?{orderBy:t.orderBy}:{}}}class pp{events;rules;simulator;host;constructor(e,r,n,s){this.events=e,this.rules=r,this.simulator=n,this.host=s}authorize(e){const{path:r,auth:n,constraints:s,origin:i,triggeredBy:a}=e,o=fp(s),c={...e.bypassRules?{admin:!0}:{},...o?{query:o}:{},...e.activityQuery!==void 0?{activityQuery:e.activityQuery}:{}},u=Object.keys(c).length>0?c:void 0,d=e.timing?.requestTime??(e.bypassRules?void 0:xe.fromMillis(Date.now())),l=e.timing?.at??Date.now();if(e.bypassRules)return this.emitRequest({at:l,evalMs:0,method:"list",path:r,auth:n,result:"allow",debugMessages:[i==="listener"?"admin lens — rules bypassed":"admin lens — rules bypassed (Studio Gap #2)"],origin:i,...u?{detail:u}:{},...a?{triggeredBy:a}:{}}),{allowed:!0};const f=this.rules.ast(),y=e.collectionGroup?op(f):f;if(e.collectionGroup&&!y){const x=`list ${r} denied: symbolic collection-group proof is not supported; the query is rejected rather than authorizing from the currently stored rows`;this.emitRequest({at:l,evalMs:0,method:"list",path:r,auth:n,result:"deny",debugMessages:[x],origin:i,...u?{detail:u}:{},...a?{triggeredBy:a}:{}});const _=ee("permission-denied",x,{request:{method:"list",path:r,auth:n},query:s});return this.emitUserDenial(i,_),{allowed:!1,error:_}}const b=`${r}/__listPlaceholder__`,S=performance.now(),j=up(y,b,n,s);if(j.kind==="unprovable"){const x=`list ${r} denied: the query is statically unprovable for every possible result (rules are not filters), so the whole query is rejected — ${j.reason}`,_=hp(j.residual);this.emitRequest({at:l,evalMs:performance.now()-S,method:"list",path:r,auth:n,result:"deny",debugMessages:[x],origin:i,...u?{detail:u}:{},...a?{triggeredBy:a}:{}});const v=ee("permission-denied",x,{request:{method:"list",path:r,auth:n},query:s,..._?{remediation:_}:{}});return this.emitUserDenial(i,v),{allowed:!1,error:v}}const T=j.kind==="provable"?tn(j.evaluationAst):e.collectionGroup?tn(y):this.rules.source,L=$n(this.host.state,{method:"list",path:b,auth:n},d);this.applyProof(L,j,s);const k=this.simulator.simulate(T,[L],{getDoc:x=>this.host.state.get(x)}),$=performance.now()-S;if(!k.success)return this.emitRequest({at:l,evalMs:$,method:"list",path:r,auth:n,result:"deny",debugMessages:[`Simulation error: ${k.error.message}`],origin:i,...u?{detail:u}:{},...a?{triggeredBy:a}:{}}),{allowed:!1,error:ee("permission-denied",`list ${r} simulator error`,{request:{method:"list",path:r,auth:n}})};const V=k.data.results[0],w=Se(V);if(V.state==="UNSUPPORTED")throw this.emitRequest({at:l,evalMs:$,method:"list",path:r,auth:n,result:"unsupported",debugMessages:w,origin:i,...u?{detail:u}:{},...a?{triggeredBy:a}:{}}),new Fr(Lr("list",r,w),"list",r,w);if(V.state!=="PASSED"){this.emitRequest({at:l,evalMs:$,method:"list",path:r,auth:n,result:"deny",debugMessages:w,evaluatedRule:Er(V),origin:i,...u?{detail:u}:{},...a?{triggeredBy:a}:{}});const x=ee("permission-denied",`list ${r} denied by rules`,{request:{method:"list",path:r,auth:n}});return this.emitUserDenial(i,x),{allowed:!1,error:x}}return this.emitRequest({at:l,evalMs:$,method:"list",path:r,auth:n,result:"allow",debugMessages:w,evaluatedRule:Er(V),origin:i,...u?{detail:u}:{},...a?{triggeredBy:a}:{}}),{allowed:!0}}applyProof(e,r,n){r.kind==="provable"&&(e.resource=r.syntheticResource),(n.limit!=null||n.offset!=null||n.orderBy!=null)&&(e.query={...n.limit!=null?{limit:n.limit}:{},...n.offset!=null?{offset:n.offset}:{},...n.orderBy!=null?{orderBy:n.orderBy}:{}})}emitRequest(e){this.events.request.hasSubscribers&&this.events.request.emit(Pn(e))}emitUserDenial(e,r){e==="user"&&this.events.denial.emit(r)}}function mp(t,e,r){if(e<=0)return[];const n=[];for(const s of t)n.length<e?ja(n,s,r):r(s,n[n.length-1])<0&&(n.pop(),ja(n,s,r));return n}function ja(t,e,r){let n=0,s=t.length;for(;n<s;){const i=n+s>>1;r(e,t[i])<0?s=i:n=i+1}t.splice(n,0,e)}function gp(t){return typeof t.seconds=="number"&&(typeof t.nanos=="number"||typeof t.nanoseconds=="number")}function yp(t){return typeof t.latitude=="number"&&typeof t.longitude=="number"}function bp(t){return t.data instanceof Uint8Array}function vp(t){return typeof t.path=="string"}function On(t){if(t==null)return 0;const e=typeof t;if(e==="boolean")return 1;if(e==="number"||e==="bigint")return 2;if(e==="string")return 4;if(Array.isArray(t))return 8;if(e==="object"){const r=t;return gp(r)?3:bp(r)?5:yp(r)?7:vp(r)?6:9}return 9}function Da(t){const e=typeof t.nanos=="number"?t.nanos:t.nanoseconds??0;return[t.seconds,e]}function wp(t,e){const r=Number.isNaN(t),n=Number.isNaN(e);return r&&n?0:r?-1:n?1:t<e?-1:t>e?1:0}function Ma(t,e){return t<e?-1:t>e?1:0}function At(t,e){const r=On(t),n=On(e);if(r!==n)return r<n?-1:1;switch(r){case 0:return 0;case 1:return t===e?0:t?1:-1;case 2:return wp(Number(t),Number(e));case 3:{const[s,i]=Da(t),[a,o]=Da(e);return s!==a?s<a?-1:1:i<o?-1:i>o?1:0}case 4:return Ma(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 Ma(t.path,e.path);case 7:{const s=t,i=e;return s.latitude!==i.latitude?s.latitude<i.latitude?-1:1:s.longitude<i.longitude?-1:s.longitude>i.longitude?1:0}case 8:{const s=t,i=e,a=Math.min(s.length,i.length);for(let o=0;o<a;o++){const c=At(s[o],i[o]);if(c!==0)return c}return s.length<i.length?-1:s.length>i.length?1:0}case 9:{const s=t,i=e,a=Object.keys(s).sort(),o=Object.keys(i).sort(),c=Math.min(a.length,o.length);for(let u=0;u<c;u++){if(a[u]!==o[u])return a[u]<o[u]?-1:1;const d=At(s[a[u]],i[o[u]]);if(d!==0)return d}return a.length<o.length?-1:a.length>o.length?1:0}default:return 0}}function Sp(t){const e=t.kind;if(e==="collection"){const r=t.path;return Object.freeze({kind:e,path:r})}if(e==="collection-group"){const r=t.collectionId;return Object.freeze({kind:e,collectionId:r})}throw new ce({code:"invalid-argument",message:`Unknown query scope kind: ${String(e)}`})}function Pa(t){const e=u=>{const d=u.kind;if(d==="where"){const f=u.field,y=u.op,b=u.value;return Object.freeze({kind:d,field:f,op:y,value:b})}if(d!=="and"&&d!=="or")throw new ce({code:"invalid-argument",message:`Unknown query filter kind: ${String(d)}`});const l=u.filters;return Object.freeze({kind:d,filters:Object.freeze(Array.from(l,e))})},r=u=>{if(u===void 0)return;const d=u.values,l=u.inclusive,f=u.fromSnapshot;return Object.freeze({values:Object.freeze(Array.from(d)),inclusive:l,fromSnapshot:f})},n=t.filters,s=t.orders,i=t.limitCount,a=t.limitFromEnd,o=t.start,c=t.end;return Object.freeze({filters:Object.freeze(Array.from(n,e)),orders:Object.freeze(Array.from(s,u=>{const d=u.field,l=u.direction;return Object.freeze({field:d,direction:l})})),limitCount:i,limitFromEnd:a,start:r(o),end:r(c)})}function $a(t){const e=[],r=n=>{if(n.kind==="where"){if(n.field===wt)return;const s=n.value;(s===null||typeof s=="string"||typeof s=="number"||typeof s=="boolean")&&e.push(Object.freeze({field:n.field,op:n.op,value:s}));return}n.kind==="and"&&n.filters.forEach(r)};return t.filters.forEach(r),Object.freeze({where:Object.freeze(e),limit:t.limitCount??null,offset:null,orderBy:t.orders.length>0?t.orders[0].field:null})}function _p(t,e){if(e.kind==="collection")return t.scan(e.path,{directOnly:!0});const r=[];for(const[n,s]of Object.entries(t.snapshot())){const i=n.split("/").filter(a=>a.length>0);i.length>0&&i.length%2===0&&i[i.length-2]===e.collectionId&&r.push({path:n,data:s})}return r}const wt="__name__",Ap=new Set(["<","<=",">",">=","!=","not-in"]);function Ds(t,e){return e===wt?{path:t.path}:t.data[e]}function gi(t){return t.kind==="where"?Ap.has(t.op)?[t.field]:[]:t.filters.flatMap(gi)}function xp(t){return gi(t).length>0}function qn(t,e){return On(t)===On(e)}function Ip(t,e){return qn(t,e)&&At(t,e)<0}function kp(t,e){return qn(t,e)&&At(t,e)<=0}function Ep(t,e){return qn(t,e)&&At(t,e)>0}function Op(t,e){return qn(t,e)&&At(t,e)>=0}function Cp(t,e,r){const n=t!==void 0;switch(e){case"==":return n&&Ge(t,r);case"!=":return n&&t!==null&&!Ge(t,r);case"<":return n&&Ip(t,r);case"<=":return n&&kp(t,r);case">":return n&&Ep(t,r);case">=":return n&&Op(t,r);case"in":return n&&Array.isArray(r)&&r.some(s=>Ge(t,s));case"not-in":return!Array.isArray(r)||r.some(s=>s===null)?!1:n&&t!==null&&!r.some(s=>Ge(t,s));case"array-contains":return Array.isArray(t)&&t.some(s=>Ge(s,r));case"array-contains-any":return Array.isArray(t)&&Array.isArray(r)&&r.some(s=>t.some(i=>Ge(i,s)))}}function Tp(t,e){if(e===wt){const r=t.path.split("/");return r[r.length-1]??t.path}return t.data[e]}function _c(t){if(Array.isArray(t))return t.map(_c);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 Ms(t,e){if(e.kind==="where"){const r=Tp(t,e.field),n=e.field===wt?_c(e.value):e.value;return Cp(r,e.op,n)}return e.kind==="and"?e.filters.every(r=>Ms(t,r)):e.filters.some(r=>Ms(t,r))}function Rp(t,e){return t.filter(r=>e.every(n=>Ms(r,n)))}function qa(t,e,r){for(let n=0;n<e.length;n++){const s=At(Ds(t,r[n].field),e[n]);if(s!==0)return r[n].direction==="desc"?-s:s}return 0}function Np(t,e,r,n){return t.filter(s=>{if(r){const i=qa(s,r.values,e);if(r.inclusive?i<0:i<=0)return!1}if(n){const i=qa(s,n.values,e);if(n.inclusive?i>0:i>=0)return!1}return!0})}function Ac(t,e){return t.filter(r=>e.every(n=>n.field===wt||r.data[n.field]!==void 0))}function xc(t){return(e,r)=>{for(const n of t){const s=At(Ds(e,n.field),Ds(r,n.field));if(s!==0)return n.direction==="desc"?-s:s}return 0}}function Fp(t,e){return e.length===0?t:Ac(t,e).sort(xc(e))}function Ic(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 gi(s))i!==wt&&!r.has(i)&&(r.add(i),e.push({field:i,direction:n}));return r.has(wt)||e.push({field:wt,direction:n}),e}function rs(t,e){let r=Rp(t,[...e.filters]);const n=Ic(e),s=e.orders.length>0||e.start!==void 0||e.end!==void 0||e.filters.some(xp);if(s&&e.limitCount!==void 0&&!e.limitFromEnd&&e.start===void 0&&e.end===void 0)return mp(Ac(r,n),e.limitCount,xc(n));if(s&&(r=Fp(r,n)),e.start||e.end){for(const i of[e.start,e.end])if(i&&!i.fromSnapshot&&i.values.length>e.orders.length)throw new ce({code:"invalid-argument",message:"Too many arguments provided to a cursor (startAt / startAfter / endAt / endBefore). The number of cursor values must be less than or equal to the number of orderBy() clauses."});r=Np(r,n,e.start,e.end)}if(e.limitCount!==void 0)if(e.limitFromEnd){if(e.orders.length===0)throw new ce({code:"unimplemented",message:"limitToLast() queries require at least one orderBy clause."});r=r.slice(-e.limitCount)}else r=r.slice(0,e.limitCount);return r}class Lp{events;triggerScope;rules;simulator;host;operationReader;listAuthorizer;constructor(e,r,n,s,i,a){this.events=e,this.triggerScope=r,this.rules=n,this.simulator=s,this.host=i,this.operationReader=new ip(e,n,s,i,a),this.listAuthorizer=new pp(e,n,s,i)}get state(){return this.host.state}emitRequest(e){this.events.request.hasSubscribers&&this.events.request.emit(Pn(e))}execute(e){return this.operationReader.execute(e)}silentReadDoc(e,r,n=!1){if(n){const y=this.state.get(e);return this.emitRequest({at:Date.now(),evalMs:0,method:"get",path:e,auth:r,result:"allow",debugMessages:["admin lens — rules bypassed"],origin:"listener",resourceBefore:{data:y,exists:y!==null},detail:{admin:!0},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),{allowed:!0,data:y}}const s=xe.fromMillis(Date.now()),i=$n(this.state,{method:"get",path:e,auth:r},s),a=Date.now(),o=performance.now(),c=this.simulator.simulate(this.rules.source,[i],{getDoc:y=>this.state.get(y)}),u=performance.now()-o;if(!c.success)return this.emitRequest({at:a,evalMs:u,method:"get",path:e,auth:r,result:"deny",debugMessages:[`Simulation error: ${c.error.message}`],origin:"listener",...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),{allowed:!1,error:ee("permission-denied",`get ${e} simulator error`,{request:{method:"get",path:e,auth:r}})};const d=c.data.results[0];if(d.state==="UNSUPPORTED")throw this.emitRequest({at:a,evalMs:u,method:"get",path:e,auth:r,result:"unsupported",debugMessages:Se(d),origin:"listener",...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),new Fr(Lr("get",e,Se(d)),"get",e,Se(d));const l=d.state==="PASSED",f=this.state.get(e);return this.emitRequest({at:a,evalMs:u,method:"get",path:e,auth:r,result:l?"allow":"deny",debugMessages:Se(d),evaluatedRule:Er(d),origin:"listener",resourceBefore:{data:f,exists:f!==null},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),l?{allowed:!0,data:f}:{allowed:!1,error:ee("permission-denied",`get ${e} denied by rules`,{request:{method:"get",path:e,auth:r},resource:{data:f,exists:f!==null}})}}silentReadCollection(e,r,n,s=!1){if(typeof n=="function")return{allowed:!1,error:ee("invalid-argument","Callable query constraints are no longer executable; pass an immutable QueryConstraintPlan.")};const i=n?Pa(n.execution):void 0,a=i?$a(i):{},o={requestTime:xe.fromMillis(Date.now()),at:Date.now()},c=this.triggerScope.current();if(s){const f=this.state.list(e).filter(S=>!S.phantom).map(S=>({path:S.path,data:S.data})),y=i?rs(f,i):f,b=this.listAuthorizer.authorize({path:e,auth:r,constraints:a,bypassRules:s,...n?.activityQuery?{activityQuery:n.activityQuery}:{},origin:"listener",...c?{triggeredBy:c}:{},timing:o});return b.allowed?{allowed:!0,docs:y}:b}const u=this.listAuthorizer.authorize({path:e,auth:r,constraints:a,...n?.activityQuery?{activityQuery:n.activityQuery}:{},origin:"listener",...c?{triggeredBy:c}:{},timing:o});if(!u.allowed)return u;const d=this.state.list(e).filter(f=>!f.phantom).map(f=>({path:f.path,data:f.data}));return{allowed:!0,docs:i?rs(d,i):d}}runQuery(e){const r=Sp(e.scope),n=Pa(e.execution),s=e.auth,i=e.bypassRules,a=e.activityQuery,o=_p(this.state,r),c=r.kind==="collection"?r.path:r.collectionId,u=$a(n),d=this.listAuthorizer.authorize({path:c,collectionGroup:r.kind==="collection-group",auth:s,constraints:u,bypassRules:i,...a!==void 0?{activityQuery:a}:{},origin:"user"});return d.allowed?{allowed:!0,docs:rs(o,n)}:d}}const Ua="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",Ba=20;function yi(){const t=new Uint8Array(Ba);globalThis.crypto.getRandomValues(t);let e="";for(let r=0;r<Ba;r++)e+=Ua[t[r]%Ua.length];return e}function kc(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),oc(i)!==void 0))return;if(Array.isArray(i)){i.forEach((u,d)=>s(u,`${a}[${d}]`));return}const o=i,c=jp(o);if(c){r.push({field:a,kind:c});return}for(const[u,d]of Object.entries(o)){const l=a?`${a}.${u}`:u;s(d,l)}}}function jp(t){const e=t.__type;return e==="serverTimestamp"?"serverTimestamp":e==="increment"?"increment":e==="arrayUnion"?"arrayUnion":e==="arrayRemove"?"arrayRemove":e==="deleteField"?"delete":null}Ff();class Dp{host;rules;simulator;eventLog;events;triggerScope;constructor(e,r,n,s,i,a){this.host=e,this.rules=r,this.simulator=n,this.eventLog=s,this.events=i,this.triggerScope=a}get state(){return this.host.state}emitDenial(e){this.events.denial.emit(e)}emitRequest(e){this.events.request.hasSubscribers&&this.events.request.emit(Pn(e))}emitWrite(e){this.events.write.hasSubscribers&&this.events.write.emit({kind:"write",id:vr().replace(/^req-/,"wr-"),at:Date.now(),method:e.method,path:e.path,auth:e.auth?{uid:e.auth.uid,...e.auth.token?{token:e.auth.token}:{}}:null,...e.data!==void 0?{data:e.data}:{},priorState:e.priorState,nextState:e.nextState,...e.groupId!==void 0?{groupId:e.groupId}:{},...e.groupKind!==void 0?{groupKind:e.groupKind}:{},...e.sentinels&&e.sentinels.length>0?{sentinels:e.sentinels}:{},...e.autoId!==void 0?{autoId:e.autoId}:{},requestTime:{seconds:e.requestTime.seconds,nanoseconds:e.requestTime.nanos},...e.detail!==void 0?{detail:e.detail}:{},...e.provenance??{}})}capturePriors(e){const r={};for(const n of e){const s=this.state.get(n);r[n]=s?{...s}:null}return r}runSimulate(e,r,n){return vc(this.state,this.rules,this.simulator,e,r,n)}buildBatchProjection(e){const r=new Map;for(const n of e)n.method==="get"||n.method==="list"||r.set(n.path,n.method==="delete"?null:n.data??{});return r}buildTestCase(e,r){return $n(this.state,e,r)}notify(e,r,n){this.triggerScope.run({method:e,path:r},()=>this.host.notifyListenersForPaths(n))}}class Ec{runtime;constructor(e){this.runtime=e}prepare(e,r){const n=xe.fromMillis(Date.now()),s=[];for(let i=0;i<e.length;i++){const a=e[i];try{const o=a.data?Ye({...a.data},{path:a.path,method:a.method,prior:this.runtime.state.get(a.path),serverTime:n}):a.data;s.push({method:a.method,path:a.path,data:o})}catch(o){const c=o.message,u=ee("invalid-argument",c),d=r.snapshot[a.path]??null,l={at:Date.now(),evalMs:0,method:a.ruleMethod,path:a.path,auth:r.auth,result:"deny",debugMessages:[`FieldValue resolve error: ${c}`],...this.includesRequestData(r,a)?{resourceData:a.preData}:{},resourceBefore:{data:d,exists:d!==null},origin:r.origin,groupId:r.groupId,...r.bypassRules?{detail:{admin:!0}}:{},...r.provenance?{provenance:r.provenance}:{}};return{index:i,input:a,message:c,error:u,request:l}}}return{context:r,inputs:e,resolvedOps:s,serverTime:n}}evaluateAndApply(e){const{context:r,inputs:n,resolvedOps:s,serverTime:i}=e,a=s.map((l,f)=>{const y=n[f];return this.runtime.buildTestCase({method:y.ruleMethod,path:l.path,auth:r.auth,data:l.data},i)}),o=this.runtime.buildBatchProjection(a),c=[];let u=!0;for(let l=0;l<s.length;l++){s[l];const f=n[l],y=r.snapshot[f.path]??null,b=Date.now(),S=performance.now(),j=this.runtime.runSimulate([a[l]],r.bypassRules,o),T=performance.now()-S;if(!j.success){const w=ee("invalid-argument",j.error.message);c.push({path:f.path,method:f.ruleMethod,allowed:!1,debugMessages:[j.error.message],error:w,request:this.request(e,f,y,b,T,"deny",[`Simulation error: ${j.error.message}`])}),u=!1;continue}const L=j.data.results[0],k=Se(L);if(L.state==="UNSUPPORTED")throw this.runtime.emitRequest(this.request(e,f,y,b,T,"unsupported",k)),new Fr(Lr(f.ruleMethod,f.path,k),f.ruleMethod,f.path,k);const $=L.state==="PASSED",V={path:f.path,method:f.ruleMethod,allowed:$,debugMessages:k,request:this.request(e,f,y,b,T,$?"allow":"deny",k)};$||(V.error=ee("permission-denied",`${f.ruleMethod} ${f.path} denied by rules`,{request:{method:f.ruleMethod,path:f.path,auth:r.auth,...this.includesRequestData(r,f)?{resourceData:f.preData}:{}},resource:{data:y,exists:y!==null}}),this.runtime.emitDenial(V.error),u=!1),c.push(V)}let d=null;if(u){const l=this.runtime.state.applyBatch(s);if(!l.success){u=!1;const f=l.errors?.[0];if(f!==void 0){const y=s[f.index];d=ee(y?.method==="create"?"already-exists":"not-found",f.error);const b=c[f.index];b&&(b.allowed=!1,b.error=d)}}}return{...e,outcomes:c,allowed:u,structuralError:d}}emitAndNotify(e){const{context:r,inputs:n,outcomes:s,serverTime:i}=e;for(let a=0;a<s.length;a++){const o=s[a],c=n[a],u=e.allowed&&o.allowed,d=r.snapshot[c.path]??null;if(o.request.resourceAfter=u?c.ruleMethod==="delete"?{data:null,exists:!1}:{data:this.runtime.state.get(c.path),exists:this.runtime.state.get(c.path)!==null}:{data:d,exists:d!==null},this.runtime.emitRequest(o.request),u){const l=c.preData?kc(c.preData):void 0;this.runtime.emitWrite({method:c.ruleMethod,path:c.path,auth:r.auth,...c.ruleMethod!=="delete"&&c.preData?{data:c.preData}:{},priorState:d,nextState:c.ruleMethod==="delete"?null:this.runtime.state.get(c.path),groupId:r.groupId,groupKind:r.origin,...l&&l.length>0?{sentinels:l}:{},requestTime:i,...r.bypassRules?{detail:{admin:!0}}:{},...r.provenance?{provenance:r.provenance}:{}})}}e.allowed&&this.runtime.notify(r.origin,n[0]?.path??"",new Set(n.map(a=>a.path)))}request(e,r,n,s,i,a,o){const{context:c}=e;return{at:s,evalMs:i,method:r.ruleMethod,path:r.path,auth:c.auth,result:a,debugMessages:o,...this.includesRequestData(c,r)?{resourceData:r.preData}:{},resourceBefore:{data:n,exists:n!==null},origin:c.origin,groupId:c.groupId,...c.bypassRules?{detail:{admin:!0}}:{},...c.provenance?{provenance:c.provenance}:{}}}includesRequestData(e,r){return r.preData!==void 0&&(e.origin==="batch"||r.ruleMethod!=="delete")}}class Mp{runtime;pipeline;constructor(e){this.runtime=e,this.pipeline=new Ec(e)}batch(e,r,n){const s=this.runtime.capturePriors(e.map(f=>f.path)),i=`batch-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,a=e.map(f=>({...f,ruleMethod:f.method,preData:f.data})),o=this.pipeline.prepare(a,{origin:"batch",groupId:i,auth:r,bypassRules:n,snapshot:s});if(!("resolvedOps"in o)){const f=this.runtime.eventLog.append({type:"batch",method:"batch",path:"",auth:r?{uid:r.uid}:null,allowed:!1,operations:e.map(y=>({method:y.method,path:y.path,data:y.data,allowed:!1})),debugMessages:[`FieldValue resolve error on '${o.input.path}': ${o.message}`]});return this.runtime.emitRequest(o.request),{allowed:!1,results:e.map(y=>({path:y.path,allowed:!1,debugMessages:[o.message],...y.path===o.input.path?{error:o.error}:{}})),event:f,error:o.error}}const c=this.pipeline.evaluateAndApply(o),u=c.outcomes.map(f=>({path:f.path,allowed:f.allowed,debugMessages:f.debugMessages,...f.error?{error:f.error}:{}})),d=this.runtime.eventLog.append({type:"batch",method:"batch",path:"",auth:r?{uid:r.uid}:null,allowed:c.allowed,priorDocs:c.allowed?s:void 0,operations:c.resolvedOps.map((f,y)=>({method:f.method,path:f.path,data:f.data,allowed:u[y]?.allowed??!1})),debugMessages:c.allowed?["Batch committed"]:["Batch rolled back — one or more operations denied"]});this.pipeline.emitAndNotify(c);let l;return c.allowed||(l=c.structuralError??u.find(f=>f.error)?.error??ee("permission-denied","Batch denied")),{allowed:c.allowed,results:u,event:d,...l?{error:l}:{}}}}const Ps="Firestore transactions require all reads to be executed before all writes.";class Oc extends Error{simError;constructor(){super(Ps),this.name="ReadAfterWriteError",this.simError=ee("failed-precondition",Ps)}}class za extends Error{constructor(){super("A document read in the transaction changed before commit."),this.name="RetryableTransactionConflictError"}}class Cc extends Error{simError=ee("failed-precondition","Transaction failed all retries.");constructor(){super("Transaction failed all retries."),this.name="TransactionAttemptsExhaustedError"}}class Pp{versionReader;reader;reads=[];writes=[];readVersions=new Map;writeStarted=!1;constructor(e,r=()=>0){this.versionReader=r,this.reader=e}get(e){this.assertReadsAllowed();const r=this.reader(e);this.readVersions.has(e)||this.readVersions.set(e,this.versionReader(e)),this.reads.push({path:e,data:r});const n=r===null?null:structuredClone(r);return{path:e,exists:n!==null,data:()=>n===null?void 0:n}}getAll(...e){return this.assertReadsAllowed(),e.map(r=>this.get(r))}set(e,r){this.queue({method:"set",path:e,data:r})}create(e,r){this.queue({method:"create",path:e,data:r})}update(e,r){this.queue({method:"update",path:e,data:r})}delete(e){this.queue({method:"delete",path:e})}consume(){return{reads:this.reads,writes:this.writes,readVersions:this.readVersions}}hadWrites(){return this.writeStarted}queue(e){this.writeStarted=!0,this.writes.push(e)}assertReadsAllowed(){if(this.writeStarted)throw new Oc}}class $p extends Error{path;secondMethod;constructor(e,r){super(`Queued ${r} on '${e}' after a delete in the same transaction. This combination is unprobed against production Firestore; refusing to guess. Either drop the delete or split into two transactions.`),this.name="AmbiguousPostDeleteWriteError",this.path=e,this.secondMethod=r}}function qp(t){const e=new Map;for(const r of t){const n=e.get(r.path);if(n===void 0){e.set(r.path,Up(r));continue}if(n.method==="delete")throw new $p(r.path,r.method);e.set(r.path,Bp(n,r))}return Array.from(e.values())}function Up(t){if(t.method==="delete")return{method:"delete",path:t.path};if(t.data===void 0)throw new Error(`internal: queued ${t.method} on ${t.path} has no data — Transaction class invariant violated`);return{method:t.method,path:t.path,data:t.data}}function Bp(t,e){switch(e.method){case"delete":return{method:"delete",path:e.path};case"set":{const r=ns(e);return{method:"set",path:e.path,data:r}}case"update":{const r=ns(e),s={...t.data??{},...r};return{method:t.method,path:e.path,data:s}}case"create":{const r=ns(e),s={...t.data??{},...r};return{method:"create",path:e.path,data:s}}}}function ns(t){if(t.data===void 0)throw new Error(`internal: queued ${t.method} on ${t.path} has no data — Transaction class invariant violated`);return t.data}class zp{runtime;pipeline;constructor(e){this.runtime=e,this.pipeline=new Ec(e)}transaction(e,r){return this.runAttempt(e,r,1)}runAttempt(e,r,n){const s=this.runtime.state.snapshot(),i=this.runtime.state.currentVersion(),a=new Map(Object.keys(s).map(d=>[d,this.runtime.state.version(d)])),o=d=>s[d]??null,c=new Pp(o,d=>{const l=a.get(d);if(l!==void 0)return l;const f=this.runtime.state.version(d);return f<=i?f:-1});let u;try{u=e(c)}catch(d){throw this.logAbortedTransaction(c,r.auth,d),d}if(u!==null&&typeof u?.then=="function")return u.then(d=>{try{return this.commitTransaction(c,s,r,d)}catch(l){return this.retryOrThrow(l,e,r,n)}},d=>{throw this.logAbortedTransaction(c,r.auth,d),d});try{return this.commitTransaction(c,s,r,u)}catch(d){return this.retryOrThrow(d,e,r,n)}}retryOrThrow(e,r,n,s){if(!(e instanceof za))throw e;const i=n.maxAttempts??5;if(s>=i)throw new Cc;return this.runAttempt(r,n,s+1)}commitTransaction(e,r,n,s){const{reads:i,writes:a,readVersions:o}=e.consume();for(const[k,$]of o)if(this.runtime.state.version(k)!==$)throw new za;const c=n.auth;if(a.length===0){const k=this.runtime.eventLog.append({type:"transaction",method:"transaction",path:"",auth:c?{uid:c.uid}:null,allowed:!0,reads:i.map($=>({path:$.path,data:$.data})),operations:[],snapshot:r,debugMessages:["Transaction committed (read-only — no writes queued)"]});return{allowed:!0,reads:[...i],writes:[],returnValue:s,event:k}}let u;try{u=qp(a)}catch(k){const $=k;throw this.runtime.eventLog.append({type:"transaction",method:"transaction",path:"",auth:c?{uid:c.uid}:null,allowed:!1,aborted:!0,reads:i.map(V=>({path:V.path,data:V.data})),error:{name:$.name,message:$.message,code:"failed-precondition"},debugMessages:[`Transaction aborted at merge: ${$.message}`]}),k}const d=Object.fromEntries(u.map(k=>[k.path,r[k.path]??null])),l=u.map(k=>{const $=k.method==="set"?this.runtime.state.get(k.path)!==null?"update":"create":k.method;return{...k,ruleMethod:$,preData:k.data}}),f=`tx-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,y=this.pipeline.prepare(l,{origin:"transaction",groupId:f,auth:c,bypassRules:n.bypassRules,provenance:n.provenance,snapshot:d});if(!("resolvedOps"in y)){const k=this.runtime.eventLog.append({type:"transaction",method:"transaction",path:"",auth:c?{uid:c.uid}:null,allowed:!1,reads:i.map($=>({path:$.path,data:$.data})),operations:u.map($=>({method:$.method,path:$.path,data:$.data,allowed:!1})),debugMessages:[`FieldValue resolve error on '${y.input.path}': ${y.message}`]});return this.runtime.emitRequest(y.request),{allowed:!1,reads:[...i],writes:l.map(($,V)=>({path:$.path,method:$.ruleMethod,allowed:!1,debugMessages:V===y.index?[y.message]:[],...V===y.index?{error:y.error}:{}})),returnValue:s,event:k,error:y.error}}const b=this.pipeline.evaluateAndApply(y),S=b.outcomes.map(k=>({path:k.path,method:k.method,allowed:k.allowed,debugMessages:k.debugMessages,...k.error?{error:k.error}:{}})),j=this.runtime.eventLog.append({type:"transaction",method:"transaction",path:"",auth:c?{uid:c.uid}:null,allowed:b.allowed,reads:i.map(k=>({path:k.path,data:k.data})),operations:b.resolvedOps.map((k,$)=>({method:k.method,path:k.path,data:k.data,allowed:S[$]?.allowed??!1})),snapshot:b.allowed?r:void 0,debugMessages:b.allowed?["Transaction committed"]:["Transaction rolled back — one or more operations denied"]});this.pipeline.emitAndNotify(b);let T;b.allowed||(T=b.structuralError??S.find(k=>k.error)?.error??ee("permission-denied","Transaction denied"));const L={allowed:b.allowed,reads:[...i],writes:S,returnValue:s,event:j,...T?{error:T}:{}};return n.readOnly&&e.hadWrites()&&(L.readOnlyViolation=!0),L}logAbortedTransaction(e,r,n){const s=n,{reads:i}=e.consume();this.runtime.eventLog.append({type:"transaction",method:"transaction",path:"",auth:r?{uid:r.uid}:null,allowed:!1,aborted:!0,reads:i.map(a=>({path:a.path,data:a.data})),error:{name:n.name,message:n.message,...s.code!==void 0?{code:String(s.code)}:{}},debugMessages:[`Transaction aborted: ${n.message}`]})}}class Vp{runtime;batches;transactions;constructor(e,r,n,s,i,a){this.runtime=new Dp(e,r,n,s,i,a),this.batches=new Mp(this.runtime),this.transactions=new zp(this.runtime)}capturePriors(e){return this.runtime.capturePriors(e)}applyWrite(e,r,n,s){if(s!==void 0&&s!==!1&&(e==="create"||e==="update")){const i=s===!0?void 0:s.mergeFields;return this.runtime.state.setMerge(r,n??{},i),null}switch(e){case"create":{const i=this.runtime.state.create(r,n??{});return i.success?null:ee("already-exists",i.error??`Document '${r}' already exists`)}case"update":{const i=this.runtime.state.update(r,n??{});return i.success?null:ee("not-found",i.error??`Document '${r}' does not exist`)}case"set":return this.runtime.state.set(r,n??{}),null;case"delete":return this.runtime.state.delete(r),null;default:return null}}execute(e){const{method:r,path:n,auth:s,data:i,autoId:a,requestTime:o,merge:c,bypassRules:u}=e,d=u?{admin:!0}:void 0,l=this.runtime.capturePriors([n]),f=o??xe.fromMillis(Date.now());let y;try{y=i&&Ye({...i},{path:n,method:r,prior:this.runtime.state.get(n),serverTime:f}),r==="update"&&y&&jf(y)}catch(O){const A=O.message,h=this.runtime.eventLog.append({type:"single",method:r,path:n,auth:s?{uid:s.uid}:null,data:i,allowed:!1,priorDocs:l,debugMessages:[`FieldValue resolve error: ${A}`]});return this.runtime.emitRequest({at:Date.now(),evalMs:0,method:r,path:n,auth:s,result:"deny",debugMessages:[`FieldValue resolve error: ${A}`],...y?{resourceData:y}:i?{resourceData:i}:{},resourceBefore:{data:l[n]??null,exists:(l[n]??null)!==null},origin:"user",...d?{detail:d}:{}}),{allowed:!1,debugMessages:[A],event:h,error:ee("invalid-argument",A)}}const b=this.runtime.buildTestCase({...e,data:y},f),S=Date.now(),j=performance.now(),T=this.runtime.runSimulate([b],u),L=performance.now()-j;if(!T.success){const O=this.runtime.eventLog.append({type:"single",method:r,path:n,auth:s?{uid:s.uid}:null,data:y,allowed:!1,priorDocs:l,debugMessages:[`Simulation error: ${T.error.message}`]});return this.runtime.emitRequest({at:S,evalMs:L,method:r,path:n,auth:s,result:"deny",debugMessages:[`Simulation error: ${T.error.message}`],...i?{resourceData:i}:{},resourceBefore:{data:l[n]??null,exists:(l[n]??null)!==null},origin:"user",...d?{detail:d}:{}}),{allowed:!1,debugMessages:[T.error.message],event:O,error:ee("invalid-argument",T.error.message)}}const k=T.data.results[0];if(k.state==="UNSUPPORTED")throw this.runtime.emitRequest({at:S,evalMs:L,method:r,path:n,auth:s,result:"unsupported",debugMessages:Se(k),...i?{resourceData:i}:{},resourceBefore:{data:l[n]??null,exists:(l[n]??null)!==null},origin:"user",...d?{detail:d}:{}}),new Fr(Lr(r,n,Se(k)),r,n,Se(k));let $=k.state==="PASSED",V=null;$&&(V=this.applyWrite(r,n,y,c),V&&($=!1));const w=this.runtime.eventLog.append({type:"single",method:r,path:n,auth:s?{uid:s.uid}:null,data:y,allowed:$,priorDocs:$?l:void 0,debugMessages:Se(k)}),x={allowed:$,debugMessages:Se(k),event:w};if(!$)if(V)x.error=V;else{const O=l[n]??null,A=r==="set"?O!==null?"update":"create":r;x.error=ee("permission-denied",`${r} ${n} denied by rules`,{request:{method:A,path:n,auth:s,...i?{resourceData:i}:{}},resource:{data:O,exists:O!==null}}),this.runtime.emitDenial(x.error)}const _=l[n]??null,v=$?this.runtime.state.get(n):_;if(this.runtime.emitRequest({at:S,evalMs:L,method:r,path:n,auth:s,result:$?"allow":"deny",debugMessages:Se(k),evaluatedRule:Er(k),...i?{resourceData:i}:{},resourceBefore:{data:_,exists:_!==null},...r!=="delete"?{resourceAfter:{data:v,exists:v!==null}}:{resourceAfter:{data:null,exists:!1}},origin:"user",...d?{detail:d}:{}}),$){const O=i?kc(i):void 0,A=a&&r==="create"?n.split("/").pop():void 0;this.runtime.emitWrite({method:r,path:n,auth:s,...r!=="delete"&&i?{data:i}:{},priorState:_,nextState:r==="delete"?null:v,...O&&O.length>0?{sentinels:O}:{},...A?{autoId:A}:{},requestTime:f,...d?{detail:d}:{}})}return $&&this.runtime.notify(r,n,new Set([n])),x}createWithAutoId(e,r,n,s){const i=e.endsWith("/")?e.slice(0,-1):e,a=yi(),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 Va{state;eventLog;history;simulator;rules;seedSnapshot;events=new Vf;triggerScope=new Wf;reads;writes;listeners;constructor(){this.state=new es,this.eventLog=new qf;const e=this;this.simulator=new Ld,this.rules=new sp(zf),this.reads=new Lp(this.events,this.triggerScope,this.rules,this.simulator,{get state(){return e.state}},this.eventLog),this.listeners=new rp(this.events,this.triggerScope,this.reads),this.writes=new Vp({get state(){return e.state},notifyListenersForPaths:r=>e.listeners.notifyListenersForPaths(r)},this.rules,this.simulator,this.eventLog,this.events,this.triggerScope),this.history=new np(this.eventLog,{get state(){return e.state},capturePriors:r=>this.writes.capturePriors(r),applyWrite:(r,n,s,i)=>this.writes.applyWrite(r,n,s,i)}),this.seedSnapshot={}}onDenial(e){return this.events.denial.subscribe(e)}onRequest(e){return this.events.request.subscribe(e)}onWrite(e){return this.events.write.subscribe(e)}onSnapshotDelivery(e){return this.events.delivery.subscribe(e)}onSnapshotSuppressed(e){return this.events.suppressed.subscribe(e)}onListenerLifecycle(e){return this.events.lifecycle.subscribe(e)}onSnapshotError(e){return this.events.snapshotError.subscribe(e)}addSnapshotListener(e,r,n={},s=null,i,a=!1,o=!1,c){return this.listeners.addSnapshotListener(e,r,n,s,i,a,o,c)}flushListeners(){this.listeners.flushListeners()}getSnapshotListenerCount(){return this.listeners.getSnapshotListenerCount()}dispose(){this.listeners.dispose(),this.events.clear()}seed(e){return this.rules.set(e.rules),this.state=e.baseDocuments?new es({},new $f(e.baseDocuments)):new es(e.documents??{}),this.seedSnapshot=e.baseDocuments??this.state.snapshot(),this.eventLog.clear(),Ss(e.rules)}deployRules(e){const r=Ss(e);return this.rules.set(e),this.listeners.reEvaluateAllListeners(),r}reevaluateLiveListeners(e,r){this.listeners.reevaluateLiveListeners(e,r)}getRules(){return this.rules.source}getDocument(e){return this.state.get(e)}listDocuments(e){return this.state.list(e)}runQuery(e){return this.reads.runQuery(e)}listRootCollections(){return this.state.listRootCollections()}listSubcollections(e){return this.state.listSubcollections(e)}snapshot(){return this.state.snapshot()}adminSetDocument(e,r){this.state.set(e,r??{}),this.listeners.notifyListenersForPaths(new Set([e]))}adminDeleteDocument(e){const r=this.state.delete(e);return r.success&&this.listeners.notifyListenersForPaths(new Set([e])),{deleted:r.success}}execute(e){return e.method==="get"||e.method==="list"?this.reads.execute(e):this.writes.execute(e)}createWithAutoId(e,r,n,s){return this.writes.createWithAutoId(e,r,n,s)}batch(e,r,n){return this.writes.batch(e,r,n)}transaction(e,r){return this.writes.transaction(e,r)}undo(){return this.history.undo()}redo(){return this.history.redo()}getEvents(){return this.history.getEvents()}getEventCount(){return this.history.getEventCount()}}class se extends Error{code;denialContext;remediation;constructor(e,r,n){const s=typeof e=="object",i=s?e.code:e,a=s?e.message:r,o=s?e.denialContext:n,c=s?e.remediation:void 0,u=c!==void 0?`${a}
1149
+ `)}`}function fp(t){if(!(t.limit==null&&t.offset==null&&t.orderBy==null))return{...t.limit!=null?{limit:t.limit}:{},...t.offset!=null?{offset:t.offset}:{},...t.orderBy!=null?{orderBy:t.orderBy}:{}}}class pp{events;rules;simulator;host;constructor(e,r,n,s){this.events=e,this.rules=r,this.simulator=n,this.host=s}authorize(e){const{path:r,auth:n,constraints:s,origin:i,triggeredBy:a}=e,o=fp(s),c={...e.bypassRules?{admin:!0}:{},...o?{query:o}:{},...e.activityQuery!==void 0?{activityQuery:e.activityQuery}:{}},u=Object.keys(c).length>0?c:void 0,d=e.timing?.requestTime??(e.bypassRules?void 0:xe.fromMillis(Date.now())),l=e.timing?.at??Date.now();if(e.bypassRules)return this.emitRequest({at:l,evalMs:0,method:"list",path:r,auth:n,result:"allow",debugMessages:[i==="listener"?"admin lens — rules bypassed":"admin lens — rules bypassed (Studio Gap #2)"],origin:i,...u?{detail:u}:{},...a?{triggeredBy:a}:{}}),{allowed:!0};const f=this.rules.ast(),y=e.collectionGroup?op(f):f;if(e.collectionGroup&&!y){const x=`list ${r} denied: symbolic collection-group proof is not supported; the query is rejected rather than authorizing from the currently stored rows`;this.emitRequest({at:l,evalMs:0,method:"list",path:r,auth:n,result:"deny",debugMessages:[x],origin:i,...u?{detail:u}:{},...a?{triggeredBy:a}:{}});const _=ee("permission-denied",x,{request:{method:"list",path:r,auth:n},query:s});return this.emitUserDenial(i,_),{allowed:!1,error:_}}const b=`${r}/__listPlaceholder__`,S=performance.now(),j=up(y,b,n,s);if(j.kind==="unprovable"){const x=`list ${r} denied: the query is statically unprovable for every possible result (rules are not filters), so the whole query is rejected — ${j.reason}`,_=hp(j.residual);this.emitRequest({at:l,evalMs:performance.now()-S,method:"list",path:r,auth:n,result:"deny",debugMessages:[x],origin:i,...u?{detail:u}:{},...a?{triggeredBy:a}:{}});const v=ee("permission-denied",x,{request:{method:"list",path:r,auth:n},query:s,..._?{remediation:_}:{}});return this.emitUserDenial(i,v),{allowed:!1,error:v}}const T=j.kind==="provable"?en(j.evaluationAst):e.collectionGroup?en(y):this.rules.source,L=Pn(this.host.state,{method:"list",path:b,auth:n},d);this.applyProof(L,j,s);const k=this.simulator.simulate(T,[L],{getDoc:x=>this.host.state.get(x)}),$=performance.now()-S;if(!k.success)return this.emitRequest({at:l,evalMs:$,method:"list",path:r,auth:n,result:"deny",debugMessages:[`Simulation error: ${k.error.message}`],origin:i,...u?{detail:u}:{},...a?{triggeredBy:a}:{}}),{allowed:!1,error:ee("permission-denied",`list ${r} simulator error`,{request:{method:"list",path:r,auth:n}})};const V=k.data.results[0],w=Se(V);if(V.state==="UNSUPPORTED")throw this.emitRequest({at:l,evalMs:$,method:"list",path:r,auth:n,result:"unsupported",debugMessages:w,origin:i,...u?{detail:u}:{},...a?{triggeredBy:a}:{}}),new Fr(Lr("list",r,w),"list",r,w);if(V.state!=="PASSED"){this.emitRequest({at:l,evalMs:$,method:"list",path:r,auth:n,result:"deny",debugMessages:w,evaluatedRule:Er(V),origin:i,...u?{detail:u}:{},...a?{triggeredBy:a}:{}});const x=ee("permission-denied",`list ${r} denied by rules`,{request:{method:"list",path:r,auth:n}});return this.emitUserDenial(i,x),{allowed:!1,error:x}}return this.emitRequest({at:l,evalMs:$,method:"list",path:r,auth:n,result:"allow",debugMessages:w,evaluatedRule:Er(V),origin:i,...u?{detail:u}:{},...a?{triggeredBy:a}:{}}),{allowed:!0}}applyProof(e,r,n){r.kind==="provable"&&(e.resource=r.syntheticResource),(n.limit!=null||n.offset!=null||n.orderBy!=null)&&(e.query={...n.limit!=null?{limit:n.limit}:{},...n.offset!=null?{offset:n.offset}:{},...n.orderBy!=null?{orderBy:n.orderBy}:{}})}emitRequest(e){this.events.request.hasSubscribers&&this.events.request.emit(Mn(e))}emitUserDenial(e,r){e==="user"&&this.events.denial.emit(r)}}function mp(t,e,r){if(e<=0)return[];const n=[];for(const s of t)n.length<e?La(n,s,r):r(s,n[n.length-1])<0&&(n.pop(),La(n,s,r));return n}function La(t,e,r){let n=0,s=t.length;for(;n<s;){const i=n+s>>1;r(e,t[i])<0?s=i:n=i+1}t.splice(n,0,e)}function gp(t){return typeof t.seconds=="number"&&(typeof t.nanos=="number"||typeof t.nanoseconds=="number")}function yp(t){return typeof t.latitude=="number"&&typeof t.longitude=="number"}function bp(t){return t.data instanceof Uint8Array}function vp(t){return typeof t.path=="string"}function En(t){if(t==null)return 0;const e=typeof t;if(e==="boolean")return 1;if(e==="number"||e==="bigint")return 2;if(e==="string")return 4;if(Array.isArray(t))return 8;if(e==="object"){const r=t;return gp(r)?3:bp(r)?5:yp(r)?7:vp(r)?6:9}return 9}function ja(t){const e=typeof t.nanos=="number"?t.nanos:t.nanoseconds??0;return[t.seconds,e]}function wp(t,e){const r=Number.isNaN(t),n=Number.isNaN(e);return r&&n?0:r?-1:n?1:t<e?-1:t>e?1:0}function Da(t,e){return t<e?-1:t>e?1:0}function At(t,e){const r=En(t),n=En(e);if(r!==n)return r<n?-1:1;switch(r){case 0:return 0;case 1:return t===e?0:t?1:-1;case 2:return wp(Number(t),Number(e));case 3:{const[s,i]=ja(t),[a,o]=ja(e);return s!==a?s<a?-1:1:i<o?-1:i>o?1:0}case 4:return Da(t,e);case 5:{const s=t.data,i=e.data,a=Math.min(s.length,i.length);for(let o=0;o<a;o++)if(s[o]!==i[o])return s[o]<i[o]?-1:1;return s.length<i.length?-1:s.length>i.length?1:0}case 6:return Da(t.path,e.path);case 7:{const s=t,i=e;return s.latitude!==i.latitude?s.latitude<i.latitude?-1:1:s.longitude<i.longitude?-1:s.longitude>i.longitude?1:0}case 8:{const s=t,i=e,a=Math.min(s.length,i.length);for(let o=0;o<a;o++){const c=At(s[o],i[o]);if(c!==0)return c}return s.length<i.length?-1:s.length>i.length?1:0}case 9:{const s=t,i=e,a=Object.keys(s).sort(),o=Object.keys(i).sort(),c=Math.min(a.length,o.length);for(let u=0;u<c;u++){if(a[u]!==o[u])return a[u]<o[u]?-1:1;const d=At(s[a[u]],i[o[u]]);if(d!==0)return d}return a.length<o.length?-1:a.length>o.length?1:0}default:return 0}}function Sp(t){const e=t.kind;if(e==="collection"){const r=t.path;return Object.freeze({kind:e,path:r})}if(e==="collection-group"){const r=t.collectionId;return Object.freeze({kind:e,collectionId:r})}throw new ce({code:"invalid-argument",message:`Unknown query scope kind: ${String(e)}`})}function Ma(t){const e=u=>{const d=u.kind;if(d==="where"){const f=u.field,y=u.op,b=u.value;return Object.freeze({kind:d,field:f,op:y,value:b})}if(d!=="and"&&d!=="or")throw new ce({code:"invalid-argument",message:`Unknown query filter kind: ${String(d)}`});const l=u.filters;return Object.freeze({kind:d,filters:Object.freeze(Array.from(l,e))})},r=u=>{if(u===void 0)return;const d=u.values,l=u.inclusive,f=u.fromSnapshot;return Object.freeze({values:Object.freeze(Array.from(d)),inclusive:l,fromSnapshot:f})},n=t.filters,s=t.orders,i=t.limitCount,a=t.limitFromEnd,o=t.start,c=t.end;return Object.freeze({filters:Object.freeze(Array.from(n,e)),orders:Object.freeze(Array.from(s,u=>{const d=u.field,l=u.direction;return Object.freeze({field:d,direction:l})})),limitCount:i,limitFromEnd:a,start:r(o),end:r(c)})}function Pa(t){const e=[],r=n=>{if(n.kind==="where"){if(n.field===wt)return;const s=n.value;(s===null||typeof s=="string"||typeof s=="number"||typeof s=="boolean")&&e.push(Object.freeze({field:n.field,op:n.op,value:s}));return}n.kind==="and"&&n.filters.forEach(r)};return t.filters.forEach(r),Object.freeze({where:Object.freeze(e),limit:t.limitCount??null,offset:null,orderBy:t.orders.length>0?t.orders[0].field:null})}function _p(t,e){if(e.kind==="collection")return t.scan(e.path,{directOnly:!0});const r=[];for(const[n,s]of Object.entries(t.snapshot())){const i=n.split("/").filter(a=>a.length>0);i.length>0&&i.length%2===0&&i[i.length-2]===e.collectionId&&r.push({path:n,data:s})}return r}const wt="__name__",Ap=new Set(["<","<=",">",">=","!=","not-in"]);function js(t,e){return e===wt?{path:t.path}:t.data[e]}function mi(t){return t.kind==="where"?Ap.has(t.op)?[t.field]:[]:t.filters.flatMap(mi)}function xp(t){return mi(t).length>0}function $n(t,e){return En(t)===En(e)}function Ip(t,e){return $n(t,e)&&At(t,e)<0}function kp(t,e){return $n(t,e)&&At(t,e)<=0}function Ep(t,e){return $n(t,e)&&At(t,e)>0}function Op(t,e){return $n(t,e)&&At(t,e)>=0}function Cp(t,e,r){const n=t!==void 0;switch(e){case"==":return n&&Ge(t,r);case"!=":return n&&t!==null&&!Ge(t,r);case"<":return n&&Ip(t,r);case"<=":return n&&kp(t,r);case">":return n&&Ep(t,r);case">=":return n&&Op(t,r);case"in":return n&&Array.isArray(r)&&r.some(s=>Ge(t,s));case"not-in":return!Array.isArray(r)||r.some(s=>s===null)?!1:n&&t!==null&&!r.some(s=>Ge(t,s));case"array-contains":return Array.isArray(t)&&t.some(s=>Ge(s,r));case"array-contains-any":return Array.isArray(t)&&Array.isArray(r)&&r.some(s=>t.some(i=>Ge(i,s)))}}function Tp(t,e){if(e===wt){const r=t.path.split("/");return r[r.length-1]??t.path}return t.data[e]}function Sc(t){if(Array.isArray(t))return t.map(Sc);if(t&&typeof t=="object"){const e=t;if(typeof e.id=="string")return e.id;if(typeof e.path=="string"){const r=e.path.split("/");return r[r.length-1]??e.path}}return t}function Ds(t,e){if(e.kind==="where"){const r=Tp(t,e.field),n=e.field===wt?Sc(e.value):e.value;return Cp(r,e.op,n)}return e.kind==="and"?e.filters.every(r=>Ds(t,r)):e.filters.some(r=>Ds(t,r))}function Rp(t,e){return t.filter(r=>e.every(n=>Ds(r,n)))}function $a(t,e,r){for(let n=0;n<e.length;n++){const s=At(js(t,r[n].field),e[n]);if(s!==0)return r[n].direction==="desc"?-s:s}return 0}function Np(t,e,r,n){return t.filter(s=>{if(r){const i=$a(s,r.values,e);if(r.inclusive?i<0:i<=0)return!1}if(n){const i=$a(s,n.values,e);if(n.inclusive?i>0:i>=0)return!1}return!0})}function _c(t,e){return t.filter(r=>e.every(n=>n.field===wt||r.data[n.field]!==void 0))}function Ac(t){return(e,r)=>{for(const n of t){const s=At(js(e,n.field),js(r,n.field));if(s!==0)return n.direction==="desc"?-s:s}return 0}}function Fp(t,e){return e.length===0?t:_c(t,e).sort(Ac(e))}function xc(t){const e=[...t.orders],r=new Set(e.map(s=>s.field)),n=t.orders.length>0?t.orders[t.orders.length-1].direction:"asc";for(const s of t.filters)for(const i of mi(s))i!==wt&&!r.has(i)&&(r.add(i),e.push({field:i,direction:n}));return r.has(wt)||e.push({field:wt,direction:n}),e}function ts(t,e){let r=Rp(t,[...e.filters]);const n=xc(e),s=e.orders.length>0||e.start!==void 0||e.end!==void 0||e.filters.some(xp);if(s&&e.limitCount!==void 0&&!e.limitFromEnd&&e.start===void 0&&e.end===void 0)return mp(_c(r,n),e.limitCount,Ac(n));if(s&&(r=Fp(r,n)),e.start||e.end){for(const i of[e.start,e.end])if(i&&!i.fromSnapshot&&i.values.length>e.orders.length)throw new ce({code:"invalid-argument",message:"Too many arguments provided to a cursor (startAt / startAfter / endAt / endBefore). The number of cursor values must be less than or equal to the number of orderBy() clauses."});r=Np(r,n,e.start,e.end)}if(e.limitCount!==void 0)if(e.limitFromEnd){if(e.orders.length===0)throw new ce({code:"unimplemented",message:"limitToLast() queries require at least one orderBy clause."});r=r.slice(-e.limitCount)}else r=r.slice(0,e.limitCount);return r}class Lp{events;triggerScope;rules;simulator;host;operationReader;listAuthorizer;constructor(e,r,n,s,i,a){this.events=e,this.triggerScope=r,this.rules=n,this.simulator=s,this.host=i,this.operationReader=new ip(e,n,s,i,a),this.listAuthorizer=new pp(e,n,s,i)}get state(){return this.host.state}emitRequest(e){this.events.request.hasSubscribers&&this.events.request.emit(Mn(e))}execute(e){return this.operationReader.execute(e)}silentReadDoc(e,r,n=!1){if(n){const y=this.state.get(e);return this.emitRequest({at:Date.now(),evalMs:0,method:"get",path:e,auth:r,result:"allow",debugMessages:["admin lens — rules bypassed"],origin:"listener",resourceBefore:{data:y,exists:y!==null},detail:{admin:!0},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),{allowed:!0,data:y}}const s=xe.fromMillis(Date.now()),i=Pn(this.state,{method:"get",path:e,auth:r},s),a=Date.now(),o=performance.now(),c=this.simulator.simulate(this.rules.source,[i],{getDoc:y=>this.state.get(y)}),u=performance.now()-o;if(!c.success)return this.emitRequest({at:a,evalMs:u,method:"get",path:e,auth:r,result:"deny",debugMessages:[`Simulation error: ${c.error.message}`],origin:"listener",...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),{allowed:!1,error:ee("permission-denied",`get ${e} simulator error`,{request:{method:"get",path:e,auth:r}})};const d=c.data.results[0];if(d.state==="UNSUPPORTED")throw this.emitRequest({at:a,evalMs:u,method:"get",path:e,auth:r,result:"unsupported",debugMessages:Se(d),origin:"listener",...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),new Fr(Lr("get",e,Se(d)),"get",e,Se(d));const l=d.state==="PASSED",f=this.state.get(e);return this.emitRequest({at:a,evalMs:u,method:"get",path:e,auth:r,result:l?"allow":"deny",debugMessages:Se(d),evaluatedRule:Er(d),origin:"listener",resourceBefore:{data:f,exists:f!==null},...this.triggerScope.current()?{triggeredBy:this.triggerScope.current()}:{}}),l?{allowed:!0,data:f}:{allowed:!1,error:ee("permission-denied",`get ${e} denied by rules`,{request:{method:"get",path:e,auth:r},resource:{data:f,exists:f!==null}})}}silentReadCollection(e,r,n,s=!1){if(typeof n=="function")return{allowed:!1,error:ee("invalid-argument","Callable query constraints are no longer executable; pass an immutable QueryConstraintPlan.")};const i=n?Ma(n.execution):void 0,a=i?Pa(i):{},o={requestTime:xe.fromMillis(Date.now()),at:Date.now()},c=this.triggerScope.current();if(s){const f=this.state.list(e).filter(S=>!S.phantom).map(S=>({path:S.path,data:S.data})),y=i?ts(f,i):f,b=this.listAuthorizer.authorize({path:e,auth:r,constraints:a,bypassRules:s,...n?.activityQuery?{activityQuery:n.activityQuery}:{},origin:"listener",...c?{triggeredBy:c}:{},timing:o});return b.allowed?{allowed:!0,docs:y}:b}const u=this.listAuthorizer.authorize({path:e,auth:r,constraints:a,...n?.activityQuery?{activityQuery:n.activityQuery}:{},origin:"listener",...c?{triggeredBy:c}:{},timing:o});if(!u.allowed)return u;const d=this.state.list(e).filter(f=>!f.phantom).map(f=>({path:f.path,data:f.data}));return{allowed:!0,docs:i?ts(d,i):d}}runQuery(e){const r=Sp(e.scope),n=Ma(e.execution),s=e.auth,i=e.bypassRules,a=e.activityQuery,o=_p(this.state,r),c=r.kind==="collection"?r.path:r.collectionId,u=Pa(n),d=this.listAuthorizer.authorize({path:c,collectionGroup:r.kind==="collection-group",auth:s,constraints:u,bypassRules:i,...a!==void 0?{activityQuery:a}:{},origin:"user"});return d.allowed?{allowed:!0,docs:ts(o,n)}:d}}const qa="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",Ua=20;function gi(){const t=new Uint8Array(Ua);globalThis.crypto.getRandomValues(t);let e="";for(let r=0;r<Ua;r++)e+=qa[t[r]%qa.length];return e}function Ic(t,e=""){const r=[],n=new WeakSet;return s(t,e),r;function s(i,a){if(i==null||typeof i!="object"||n.has(i)||(n.add(i),ac(i)!==void 0))return;if(Array.isArray(i)){i.forEach((u,d)=>s(u,`${a}[${d}]`));return}const o=i,c=jp(o);if(c){r.push({field:a,kind:c});return}for(const[u,d]of Object.entries(o)){const l=a?`${a}.${u}`:u;s(d,l)}}}function jp(t){const e=t.__type;return e==="serverTimestamp"?"serverTimestamp":e==="increment"?"increment":e==="arrayUnion"?"arrayUnion":e==="arrayRemove"?"arrayRemove":e==="deleteField"?"delete":null}Ff();class Dp{host;rules;simulator;eventLog;events;triggerScope;constructor(e,r,n,s,i,a){this.host=e,this.rules=r,this.simulator=n,this.eventLog=s,this.events=i,this.triggerScope=a}get state(){return this.host.state}emitDenial(e){this.events.denial.emit(e)}emitRequest(e){this.events.request.hasSubscribers&&this.events.request.emit(Mn(e))}emitWrite(e){this.events.write.hasSubscribers&&this.events.write.emit({kind:"write",id:vr().replace(/^req-/,"wr-"),at:Date.now(),method:e.method,path:e.path,auth:e.auth?{uid:e.auth.uid,...e.auth.token?{token:e.auth.token}:{}}:null,...e.data!==void 0?{data:e.data}:{},priorState:e.priorState,nextState:e.nextState,...e.groupId!==void 0?{groupId:e.groupId}:{},...e.groupKind!==void 0?{groupKind:e.groupKind}:{},...e.sentinels&&e.sentinels.length>0?{sentinels:e.sentinels}:{},...e.autoId!==void 0?{autoId:e.autoId}:{},requestTime:{seconds:e.requestTime.seconds,nanoseconds:e.requestTime.nanos},...e.detail!==void 0?{detail:e.detail}:{},...e.provenance??{}})}capturePriors(e){const r={};for(const n of e){const s=this.state.get(n);r[n]=s?{...s}:null}return r}runSimulate(e,r,n){return bc(this.state,this.rules,this.simulator,e,r,n)}buildBatchProjection(e){const r=new Map;for(const n of e)n.method==="get"||n.method==="list"||r.set(n.path,n.method==="delete"?null:n.data??{});return r}buildTestCase(e,r){return Pn(this.state,e,r)}notify(e,r,n){this.triggerScope.run({method:e,path:r},()=>this.host.notifyListenersForPaths(n))}}class kc{runtime;constructor(e){this.runtime=e}prepare(e,r){const n=xe.fromMillis(Date.now()),s=[];for(let i=0;i<e.length;i++){const a=e[i];try{const o=a.data?Ye({...a.data},{path:a.path,method:a.method,prior:this.runtime.state.get(a.path),serverTime:n}):a.data;s.push({method:a.method,path:a.path,data:o})}catch(o){const c=o.message,u=ee("invalid-argument",c),d=r.snapshot[a.path]??null,l={at:Date.now(),evalMs:0,method:a.ruleMethod,path:a.path,auth:r.auth,result:"deny",debugMessages:[`FieldValue resolve error: ${c}`],...this.includesRequestData(r,a)?{resourceData:a.preData}:{},resourceBefore:{data:d,exists:d!==null},origin:r.origin,groupId:r.groupId,...r.bypassRules?{detail:{admin:!0}}:{},...r.provenance?{provenance:r.provenance}:{}};return{index:i,input:a,message:c,error:u,request:l}}}return{context:r,inputs:e,resolvedOps:s,serverTime:n}}evaluateAndApply(e){const{context:r,inputs:n,resolvedOps:s,serverTime:i}=e,a=s.map((l,f)=>{const y=n[f];return this.runtime.buildTestCase({method:y.ruleMethod,path:l.path,auth:r.auth,data:l.data},i)}),o=this.runtime.buildBatchProjection(a),c=[];let u=!0;for(let l=0;l<s.length;l++){s[l];const f=n[l],y=r.snapshot[f.path]??null,b=Date.now(),S=performance.now(),j=this.runtime.runSimulate([a[l]],r.bypassRules,o),T=performance.now()-S;if(!j.success){const w=ee("invalid-argument",j.error.message);c.push({path:f.path,method:f.ruleMethod,allowed:!1,debugMessages:[j.error.message],error:w,request:this.request(e,f,y,b,T,"deny",[`Simulation error: ${j.error.message}`])}),u=!1;continue}const L=j.data.results[0],k=Se(L);if(L.state==="UNSUPPORTED")throw this.runtime.emitRequest(this.request(e,f,y,b,T,"unsupported",k)),new Fr(Lr(f.ruleMethod,f.path,k),f.ruleMethod,f.path,k);const $=L.state==="PASSED",V={path:f.path,method:f.ruleMethod,allowed:$,debugMessages:k,request:this.request(e,f,y,b,T,$?"allow":"deny",k)};$||(V.error=ee("permission-denied",`${f.ruleMethod} ${f.path} denied by rules`,{request:{method:f.ruleMethod,path:f.path,auth:r.auth,...this.includesRequestData(r,f)?{resourceData:f.preData}:{}},resource:{data:y,exists:y!==null}}),this.runtime.emitDenial(V.error),u=!1),c.push(V)}let d=null;if(u){const l=this.runtime.state.applyBatch(s);if(!l.success){u=!1;const f=l.errors?.[0];if(f!==void 0){const y=s[f.index];d=ee(y?.method==="create"?"already-exists":"not-found",f.error);const b=c[f.index];b&&(b.allowed=!1,b.error=d)}}}return{...e,outcomes:c,allowed:u,structuralError:d}}emitAndNotify(e){const{context:r,inputs:n,outcomes:s,serverTime:i}=e;for(let a=0;a<s.length;a++){const o=s[a],c=n[a],u=e.allowed&&o.allowed,d=r.snapshot[c.path]??null;if(o.request.resourceAfter=u?c.ruleMethod==="delete"?{data:null,exists:!1}:{data:this.runtime.state.get(c.path),exists:this.runtime.state.get(c.path)!==null}:{data:d,exists:d!==null},this.runtime.emitRequest(o.request),u){const l=c.preData?Ic(c.preData):void 0;this.runtime.emitWrite({method:c.ruleMethod,path:c.path,auth:r.auth,...c.ruleMethod!=="delete"&&c.preData?{data:c.preData}:{},priorState:d,nextState:c.ruleMethod==="delete"?null:this.runtime.state.get(c.path),groupId:r.groupId,groupKind:r.origin,...l&&l.length>0?{sentinels:l}:{},requestTime:i,...r.bypassRules?{detail:{admin:!0}}:{},...r.provenance?{provenance:r.provenance}:{}})}}e.allowed&&this.runtime.notify(r.origin,n[0]?.path??"",new Set(n.map(a=>a.path)))}request(e,r,n,s,i,a,o){const{context:c}=e;return{at:s,evalMs:i,method:r.ruleMethod,path:r.path,auth:c.auth,result:a,debugMessages:o,...this.includesRequestData(c,r)?{resourceData:r.preData}:{},resourceBefore:{data:n,exists:n!==null},origin:c.origin,groupId:c.groupId,...c.bypassRules?{detail:{admin:!0}}:{},...c.provenance?{provenance:c.provenance}:{}}}includesRequestData(e,r){return r.preData!==void 0&&(e.origin==="batch"||r.ruleMethod!=="delete")}}class Mp{runtime;pipeline;constructor(e){this.runtime=e,this.pipeline=new kc(e)}batch(e,r,n){const s=this.runtime.capturePriors(e.map(f=>f.path)),i=`batch-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,a=e.map(f=>({...f,ruleMethod:f.method,preData:f.data})),o=this.pipeline.prepare(a,{origin:"batch",groupId:i,auth:r,bypassRules:n,snapshot:s});if(!("resolvedOps"in o)){const f=this.runtime.eventLog.append({type:"batch",method:"batch",path:"",auth:r?{uid:r.uid}:null,allowed:!1,operations:e.map(y=>({method:y.method,path:y.path,data:y.data,allowed:!1})),debugMessages:[`FieldValue resolve error on '${o.input.path}': ${o.message}`]});return this.runtime.emitRequest(o.request),{allowed:!1,results:e.map(y=>({path:y.path,allowed:!1,debugMessages:[o.message],...y.path===o.input.path?{error:o.error}:{}})),event:f,error:o.error}}const c=this.pipeline.evaluateAndApply(o),u=c.outcomes.map(f=>({path:f.path,allowed:f.allowed,debugMessages:f.debugMessages,...f.error?{error:f.error}:{}})),d=this.runtime.eventLog.append({type:"batch",method:"batch",path:"",auth:r?{uid:r.uid}:null,allowed:c.allowed,priorDocs:c.allowed?s:void 0,operations:c.resolvedOps.map((f,y)=>({method:f.method,path:f.path,data:f.data,allowed:u[y]?.allowed??!1})),debugMessages:c.allowed?["Batch committed"]:["Batch rolled back — one or more operations denied"]});this.pipeline.emitAndNotify(c);let l;return c.allowed||(l=c.structuralError??u.find(f=>f.error)?.error??ee("permission-denied","Batch denied")),{allowed:c.allowed,results:u,event:d,...l?{error:l}:{}}}}const Ms="Firestore transactions require all reads to be executed before all writes.";class Ec extends Error{simError;constructor(){super(Ms),this.name="ReadAfterWriteError",this.simError=ee("failed-precondition",Ms)}}class Ba extends Error{constructor(){super("A document read in the transaction changed before commit."),this.name="RetryableTransactionConflictError"}}class Oc extends Error{simError=ee("failed-precondition","Transaction failed all retries.");constructor(){super("Transaction failed all retries."),this.name="TransactionAttemptsExhaustedError"}}class Pp{versionReader;reader;reads=[];writes=[];readVersions=new Map;writeStarted=!1;constructor(e,r=()=>0){this.versionReader=r,this.reader=e}get(e){this.assertReadsAllowed();const r=this.reader(e);this.readVersions.has(e)||this.readVersions.set(e,this.versionReader(e)),this.reads.push({path:e,data:r});const n=r===null?null:structuredClone(r);return{path:e,exists:n!==null,data:()=>n===null?void 0:n}}getAll(...e){return this.assertReadsAllowed(),e.map(r=>this.get(r))}set(e,r){this.queue({method:"set",path:e,data:r})}create(e,r){this.queue({method:"create",path:e,data:r})}update(e,r){this.queue({method:"update",path:e,data:r})}delete(e){this.queue({method:"delete",path:e})}consume(){return{reads:this.reads,writes:this.writes,readVersions:this.readVersions}}hadWrites(){return this.writeStarted}queue(e){this.writeStarted=!0,this.writes.push(e)}assertReadsAllowed(){if(this.writeStarted)throw new Ec}}class $p extends Error{path;secondMethod;constructor(e,r){super(`Queued ${r} on '${e}' after a delete in the same transaction. This combination is unprobed against production Firestore; refusing to guess. Either drop the delete or split into two transactions.`),this.name="AmbiguousPostDeleteWriteError",this.path=e,this.secondMethod=r}}function qp(t){const e=new Map;for(const r of t){const n=e.get(r.path);if(n===void 0){e.set(r.path,Up(r));continue}if(n.method==="delete")throw new $p(r.path,r.method);e.set(r.path,Bp(n,r))}return Array.from(e.values())}function Up(t){if(t.method==="delete")return{method:"delete",path:t.path};if(t.data===void 0)throw new Error(`internal: queued ${t.method} on ${t.path} has no data — Transaction class invariant violated`);return{method:t.method,path:t.path,data:t.data}}function Bp(t,e){switch(e.method){case"delete":return{method:"delete",path:e.path};case"set":{const r=rs(e);return{method:"set",path:e.path,data:r}}case"update":{const r=rs(e),s={...t.data??{},...r};return{method:t.method,path:e.path,data:s}}case"create":{const r=rs(e),s={...t.data??{},...r};return{method:"create",path:e.path,data:s}}}}function rs(t){if(t.data===void 0)throw new Error(`internal: queued ${t.method} on ${t.path} has no data — Transaction class invariant violated`);return t.data}class zp{runtime;pipeline;constructor(e){this.runtime=e,this.pipeline=new kc(e)}transaction(e,r){return this.runAttempt(e,r,1)}runAttempt(e,r,n){const s=this.runtime.state.snapshot(),i=this.runtime.state.currentVersion(),a=new Map(Object.keys(s).map(d=>[d,this.runtime.state.version(d)])),o=d=>s[d]??null,c=new Pp(o,d=>{const l=a.get(d);if(l!==void 0)return l;const f=this.runtime.state.version(d);return f<=i?f:-1});let u;try{u=e(c)}catch(d){throw this.logAbortedTransaction(c,r.auth,d),d}if(u!==null&&typeof u?.then=="function")return u.then(d=>{try{return this.commitTransaction(c,s,r,d)}catch(l){return this.retryOrThrow(l,e,r,n)}},d=>{throw this.logAbortedTransaction(c,r.auth,d),d});try{return this.commitTransaction(c,s,r,u)}catch(d){return this.retryOrThrow(d,e,r,n)}}retryOrThrow(e,r,n,s){if(!(e instanceof Ba))throw e;const i=n.maxAttempts??5;if(s>=i)throw new Oc;return this.runAttempt(r,n,s+1)}commitTransaction(e,r,n,s){const{reads:i,writes:a,readVersions:o}=e.consume();for(const[k,$]of o)if(this.runtime.state.version(k)!==$)throw new Ba;const c=n.auth;if(a.length===0){const k=this.runtime.eventLog.append({type:"transaction",method:"transaction",path:"",auth:c?{uid:c.uid}:null,allowed:!0,reads:i.map($=>({path:$.path,data:$.data})),operations:[],snapshot:r,debugMessages:["Transaction committed (read-only — no writes queued)"]});return{allowed:!0,reads:[...i],writes:[],returnValue:s,event:k}}let u;try{u=qp(a)}catch(k){const $=k;throw this.runtime.eventLog.append({type:"transaction",method:"transaction",path:"",auth:c?{uid:c.uid}:null,allowed:!1,aborted:!0,reads:i.map(V=>({path:V.path,data:V.data})),error:{name:$.name,message:$.message,code:"failed-precondition"},debugMessages:[`Transaction aborted at merge: ${$.message}`]}),k}const d=Object.fromEntries(u.map(k=>[k.path,r[k.path]??null])),l=u.map(k=>{const $=k.method==="set"?this.runtime.state.get(k.path)!==null?"update":"create":k.method;return{...k,ruleMethod:$,preData:k.data}}),f=`tx-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,y=this.pipeline.prepare(l,{origin:"transaction",groupId:f,auth:c,bypassRules:n.bypassRules,provenance:n.provenance,snapshot:d});if(!("resolvedOps"in y)){const k=this.runtime.eventLog.append({type:"transaction",method:"transaction",path:"",auth:c?{uid:c.uid}:null,allowed:!1,reads:i.map($=>({path:$.path,data:$.data})),operations:u.map($=>({method:$.method,path:$.path,data:$.data,allowed:!1})),debugMessages:[`FieldValue resolve error on '${y.input.path}': ${y.message}`]});return this.runtime.emitRequest(y.request),{allowed:!1,reads:[...i],writes:l.map(($,V)=>({path:$.path,method:$.ruleMethod,allowed:!1,debugMessages:V===y.index?[y.message]:[],...V===y.index?{error:y.error}:{}})),returnValue:s,event:k,error:y.error}}const b=this.pipeline.evaluateAndApply(y),S=b.outcomes.map(k=>({path:k.path,method:k.method,allowed:k.allowed,debugMessages:k.debugMessages,...k.error?{error:k.error}:{}})),j=this.runtime.eventLog.append({type:"transaction",method:"transaction",path:"",auth:c?{uid:c.uid}:null,allowed:b.allowed,reads:i.map(k=>({path:k.path,data:k.data})),operations:b.resolvedOps.map((k,$)=>({method:k.method,path:k.path,data:k.data,allowed:S[$]?.allowed??!1})),snapshot:b.allowed?r:void 0,debugMessages:b.allowed?["Transaction committed"]:["Transaction rolled back — one or more operations denied"]});this.pipeline.emitAndNotify(b);let T;b.allowed||(T=b.structuralError??S.find(k=>k.error)?.error??ee("permission-denied","Transaction denied"));const L={allowed:b.allowed,reads:[...i],writes:S,returnValue:s,event:j,...T?{error:T}:{}};return n.readOnly&&e.hadWrites()&&(L.readOnlyViolation=!0),L}logAbortedTransaction(e,r,n){const s=n,{reads:i}=e.consume();this.runtime.eventLog.append({type:"transaction",method:"transaction",path:"",auth:r?{uid:r.uid}:null,allowed:!1,aborted:!0,reads:i.map(a=>({path:a.path,data:a.data})),error:{name:n.name,message:n.message,...s.code!==void 0?{code:String(s.code)}:{}},debugMessages:[`Transaction aborted: ${n.message}`]})}}class Vp{runtime;batches;transactions;constructor(e,r,n,s,i,a){this.runtime=new Dp(e,r,n,s,i,a),this.batches=new Mp(this.runtime),this.transactions=new zp(this.runtime)}capturePriors(e){return this.runtime.capturePriors(e)}applyWrite(e,r,n,s){if(s!==void 0&&s!==!1&&(e==="create"||e==="update")){const i=s===!0?void 0:s.mergeFields;return this.runtime.state.setMerge(r,n??{},i),null}switch(e){case"create":{const i=this.runtime.state.create(r,n??{});return i.success?null:ee("already-exists",i.error??`Document '${r}' already exists`)}case"update":{const i=this.runtime.state.update(r,n??{});return i.success?null:ee("not-found",i.error??`Document '${r}' does not exist`)}case"set":return this.runtime.state.set(r,n??{}),null;case"delete":return this.runtime.state.delete(r),null;default:return null}}execute(e){const{method:r,path:n,auth:s,data:i,autoId:a,requestTime:o,merge:c,bypassRules:u}=e,d=u?{admin:!0}:void 0,l=this.runtime.capturePriors([n]),f=o??xe.fromMillis(Date.now());let y;try{y=i&&Ye({...i},{path:n,method:r,prior:this.runtime.state.get(n),serverTime:f}),r==="update"&&y&&jf(y)}catch(O){const A=O.message,h=this.runtime.eventLog.append({type:"single",method:r,path:n,auth:s?{uid:s.uid}:null,data:i,allowed:!1,priorDocs:l,debugMessages:[`FieldValue resolve error: ${A}`]});return this.runtime.emitRequest({at:Date.now(),evalMs:0,method:r,path:n,auth:s,result:"deny",debugMessages:[`FieldValue resolve error: ${A}`],...y?{resourceData:y}:i?{resourceData:i}:{},resourceBefore:{data:l[n]??null,exists:(l[n]??null)!==null},origin:"user",...d?{detail:d}:{}}),{allowed:!1,debugMessages:[A],event:h,error:ee("invalid-argument",A)}}const b=this.runtime.buildTestCase({...e,data:y},f),S=Date.now(),j=performance.now(),T=this.runtime.runSimulate([b],u),L=performance.now()-j;if(!T.success){const O=this.runtime.eventLog.append({type:"single",method:r,path:n,auth:s?{uid:s.uid}:null,data:y,allowed:!1,priorDocs:l,debugMessages:[`Simulation error: ${T.error.message}`]});return this.runtime.emitRequest({at:S,evalMs:L,method:r,path:n,auth:s,result:"deny",debugMessages:[`Simulation error: ${T.error.message}`],...i?{resourceData:i}:{},resourceBefore:{data:l[n]??null,exists:(l[n]??null)!==null},origin:"user",...d?{detail:d}:{}}),{allowed:!1,debugMessages:[T.error.message],event:O,error:ee("invalid-argument",T.error.message)}}const k=T.data.results[0];if(k.state==="UNSUPPORTED")throw this.runtime.emitRequest({at:S,evalMs:L,method:r,path:n,auth:s,result:"unsupported",debugMessages:Se(k),...i?{resourceData:i}:{},resourceBefore:{data:l[n]??null,exists:(l[n]??null)!==null},origin:"user",...d?{detail:d}:{}}),new Fr(Lr(r,n,Se(k)),r,n,Se(k));let $=k.state==="PASSED",V=null;$&&(V=this.applyWrite(r,n,y,c),V&&($=!1));const w=this.runtime.eventLog.append({type:"single",method:r,path:n,auth:s?{uid:s.uid}:null,data:y,allowed:$,priorDocs:$?l:void 0,debugMessages:Se(k)}),x={allowed:$,debugMessages:Se(k),event:w};if(!$)if(V)x.error=V;else{const O=l[n]??null,A=r==="set"?O!==null?"update":"create":r;x.error=ee("permission-denied",`${r} ${n} denied by rules`,{request:{method:A,path:n,auth:s,...i?{resourceData:i}:{}},resource:{data:O,exists:O!==null}}),this.runtime.emitDenial(x.error)}const _=l[n]??null,v=$?this.runtime.state.get(n):_;if(this.runtime.emitRequest({at:S,evalMs:L,method:r,path:n,auth:s,result:$?"allow":"deny",debugMessages:Se(k),evaluatedRule:Er(k),...i?{resourceData:i}:{},resourceBefore:{data:_,exists:_!==null},...r!=="delete"?{resourceAfter:{data:v,exists:v!==null}}:{resourceAfter:{data:null,exists:!1}},origin:"user",...d?{detail:d}:{}}),$){const O=i?Ic(i):void 0,A=a&&r==="create"?n.split("/").pop():void 0;this.runtime.emitWrite({method:r,path:n,auth:s,...r!=="delete"&&i?{data:i}:{},priorState:_,nextState:r==="delete"?null:v,...O&&O.length>0?{sentinels:O}:{},...A?{autoId:A}:{},requestTime:f,...d?{detail:d}:{}})}return $&&this.runtime.notify(r,n,new Set([n])),x}createWithAutoId(e,r,n,s){const i=e.endsWith("/")?e.slice(0,-1):e,a=gi(),o=`${i}/${a}`,c=this.execute({method:"create",path:o,auth:n,data:r,autoId:!0,bypassRules:s});return{path:o,result:c}}batch(e,r,n){return this.batches.batch(e,r,n)}transaction(e,r){return this.transactions.transaction(e,r)}}class za{state;eventLog;history;simulator;rules;seedSnapshot;events=new Vf;triggerScope=new Wf;reads;writes;listeners;constructor(){this.state=new Xn,this.eventLog=new qf;const e=this;this.simulator=new Fd,this.rules=new sp(zf),this.reads=new Lp(this.events,this.triggerScope,this.rules,this.simulator,{get state(){return e.state}},this.eventLog),this.listeners=new rp(this.events,this.triggerScope,this.reads),this.writes=new Vp({get state(){return e.state},notifyListenersForPaths:r=>e.listeners.notifyListenersForPaths(r)},this.rules,this.simulator,this.eventLog,this.events,this.triggerScope),this.history=new np(this.eventLog,{get state(){return e.state},capturePriors:r=>this.writes.capturePriors(r),applyWrite:(r,n,s,i)=>this.writes.applyWrite(r,n,s,i)}),this.seedSnapshot={}}onDenial(e){return this.events.denial.subscribe(e)}onRequest(e){return this.events.request.subscribe(e)}onWrite(e){return this.events.write.subscribe(e)}onSnapshotDelivery(e){return this.events.delivery.subscribe(e)}onSnapshotSuppressed(e){return this.events.suppressed.subscribe(e)}onListenerLifecycle(e){return this.events.lifecycle.subscribe(e)}onSnapshotError(e){return this.events.snapshotError.subscribe(e)}addSnapshotListener(e,r,n={},s=null,i,a=!1,o=!1,c){return this.listeners.addSnapshotListener(e,r,n,s,i,a,o,c)}flushListeners(){this.listeners.flushListeners()}getSnapshotListenerCount(){return this.listeners.getSnapshotListenerCount()}dispose(){this.listeners.dispose(),this.events.clear()}seed(e){return this.rules.set(e.rules),this.state=e.baseDocuments?new Xn({},new $f(e.baseDocuments)):new Xn(e.documents??{}),this.seedSnapshot=e.baseDocuments??this.state.snapshot(),this.eventLog.clear(),ws(e.rules)}deployRules(e){const r=ws(e);return this.rules.set(e),this.listeners.reEvaluateAllListeners(),r}reevaluateLiveListeners(e,r){this.listeners.reevaluateLiveListeners(e,r)}getRules(){return this.rules.source}getDocument(e){return this.state.get(e)}listDocuments(e){return this.state.list(e)}runQuery(e){return this.reads.runQuery(e)}listRootCollections(){return this.state.listRootCollections()}listSubcollections(e){return this.state.listSubcollections(e)}snapshot(){return this.state.snapshot()}adminSetDocument(e,r){this.state.set(e,r??{}),this.listeners.notifyListenersForPaths(new Set([e]))}adminDeleteDocument(e){const r=this.state.delete(e);return r.success&&this.listeners.notifyListenersForPaths(new Set([e])),{deleted:r.success}}execute(e){return e.method==="get"||e.method==="list"?this.reads.execute(e):this.writes.execute(e)}createWithAutoId(e,r,n,s){return this.writes.createWithAutoId(e,r,n,s)}batch(e,r,n){return this.writes.batch(e,r,n)}transaction(e,r){return this.writes.transaction(e,r)}undo(){return this.history.undo()}redo(){return this.history.redo()}getEvents(){return this.history.getEvents()}getEventCount(){return this.history.getEventCount()}}class se extends Error{code;denialContext;remediation;constructor(e,r,n){const s=typeof e=="object",i=s?e.code:e,a=s?e.message:r,o=s?e.denialContext:n,c=s?e.remediation:void 0,u=c!==void 0?`${a}
1150
1150
 
1151
1151
  Remediation:
1152
- ${c}`:a;super(u),this.name="SandboxError",this.code=i,o!==void 0&&(this.denialContext=o),c!==void 0&&(this.remediation=c)}}function $s(t){return t.kind==="request"||t.kind==="operation"}function Dr(t){const e=Object.freeze({...t.source}),r=Object.freeze({...t.authLens});return Object.freeze({source:e,authLens:r,...t.planId===void 0?{}:{planId:t.planId}})}function bi(t){const e=Dr(t);return{actor:e.source,authLens:e.authLens,operationContext:e,...e.planId===void 0?{}:{planId:e.planId}}}function Wa(t){const e=t?.operationContext?.source;if(e&&e.kind!=="unattributed")return e;if(t?.actor&&t.actor.kind!=="unattributed")return t.actor}function vi(t,e){const r=t?.operationContext?.source??t?.actor,n=e?.operationContext?.source??e?.actor;return Dr({source:Wa(t)??Wa(e)??r??n??{kind:"unattributed"},authLens:e?.operationContext?.authLens??e?.authLens??t?.operationContext?.authLens??t?.authLens??{mode:"app-session"},...(t?.operationContext?.planId??t?.planId??e?.operationContext?.planId??e?.planId)===void 0?{}:{planId:t?.operationContext?.planId??t?.planId??e?.operationContext?.planId??e?.planId}})}function Wp(t){return vi(void 0,t)}function Tc(t){return t.rulesDisposition?t.rulesDisposition:t.kind==="operation"&&t.origin==="admin"||t.detail?.admin===!0?{kind:"bypassed",reason:"admin"}:t.result==="unsupported"?{kind:"not-evaluated",reason:"unsupported"}:t.kind==="operation"&&t.result==="error"?{kind:"not-evaluated",reason:"runtime-error"}:t.kind==="operation"&&t.result==="not-applicable"?{kind:"not-evaluated",reason:"not-a-rules-operation"}:t.result==="deny"?{kind:"evaluated",verdict:"deny"}:t.kind==="request"?{kind:"evaluated",verdict:"allow"}:t.rules?{kind:"evaluated",verdict:"allow"}:{kind:"not-evaluated",reason:"no-rules"}}function Hp(t){return t===null?null:Object.freeze({uid:t.uid,...t.token===void 0?{}:{token:Rc(t.token)}})}function Rc(t){const e={};for(const[r,n]of Object.entries(t))e[r]=Nc(n);return Object.freeze(e)}function Nc(t){return Array.isArray(t)?Object.freeze(t.map(Nc)):t&&typeof t=="object"?Rc(t):t}function lg(t){return $s(t)?Object.freeze({id:t.id,at:t.at,eventKind:t.kind,service:t.kind==="request"?t.service??"firestore":t.service,method:t.method,...t.path===void 0?{}:{path:t.path},auth:Hp(t.auth),result:t.result,context:Wp(t),rules:Object.freeze({...Tc(t)})}):null}function Ha(t){return t===null?{mode:"anon"}:t.token===void 0?{mode:"as",uid:t.uid}:{mode:"as",uid:t.uid,token:t.token}}class Mr{sandbox;auth;constructor(e,r,n){this.sandbox=e,this.auth=r,this.operationContext=Dr(n??{source:{kind:"unattributed"},authLens:Ha(r)})}operationContext;withAuth(e){return qs(e),new Mr(this.sandbox,e,{source:this.operationContext.source,authLens:Ha(e),...this.operationContext.planId===void 0?{}:{planId:this.operationContext.planId}})}}function wi(t,e){return new Mr(t.sandbox,t.auth,e)}function qs(t){if(t===null)return;if(t===void 0)throw new se({code:"invalid-argument",message:"withAuth() requires an explicit AuthState argument.",remediation:["For anonymous (unauthenticated) access: withAuth(null)",'For authenticated access: withAuth({ uid: "someUid" })','For custom claims: withAuth({ uid: "someUid", token: { role: "admin" } })'].join(`
1153
- `)});if(typeof t!="object")throw new se("invalid-argument","withAuth() expected null or an object with a `uid` field.");const e=t;if(typeof e.uid!="string"||e.uid.length===0)throw new se("invalid-argument","withAuth() requires `uid` to be a non-empty string.");if("token"in e&&e.token!==void 0&&(e.token===null||typeof e.token!="object"||Array.isArray(e.token)))throw new se("invalid-argument","withAuth() requires `token` (when present) to be a plain object.")}function Gp(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),r=e.length%4===0?"":"=".repeat(4-e.length%4),n=atob(e+r),s=new Uint8Array(n.length);for(let i=0;i<n.length;i++)s[i]=n.charCodeAt(i);return s}function Kp(t){const e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r}function Si(t){return Us(t,!0)}function Us(t,e){if(t===null||typeof t!="object")return t;if(Array.isArray(t)){const a=t.map(o=>Us(o,!1));return e&&st(a,Ra(t)),a}const r=t,n=a=>(e&&st(a,Ra(t)),a),s=(a,o)=>(Ht(a,Object.freeze(o),()=>a),n(a));if(r.__type__==="__vector__"&&Array.isArray(r.value)){const a=Object.freeze(r.value.slice());return s(new Wt(a),{type:"vector",values:a})}if(typeof r.__type=="string")switch(r.__type){case"timestamp":return s(new xe(r.seconds,r.nanos),{type:"timestamp",seconds:r.seconds,nanoseconds:r.nanos});case"bytes":{const a=Gp(r.base64);return s(new Be(a),{type:"bytes",values:Object.freeze(Array.from(a))})}case"latlng":return s(new rt(r.lat,r.lng),{type:"geo-point",latitude:r.lat,longitude:r.lng});case"duration":return n(new we(r.seconds,r.nanos));case"reference":return n(new jt(r.path));case"path":return n(new Xe(r.segments))}if(typeof r.type=="string")switch(r.type){case"firestore/timestamp/1.0":{const a=r.seconds,o=r.nanoseconds;return s(new xe(a,o),{type:"timestamp",seconds:a,nanoseconds:o})}case"firestore/bytes/1.0":{const a=Kp(r.bytes);return s(new Be(a),{type:"bytes",values:Object.freeze(Array.from(a))})}case"firestore/geoPoint/1.0":return s(new rt(r.latitude,r.longitude),{type:"geo-point",latitude:r.latitude,longitude:r.longitude})}const i={};for(const[a,o]of Object.entries(r))i[a]=Us(o,!1);return n(i)}class Br extends Error{constructor(e){super(e),this.name="PersistenceSchemaError"}}function Zp(t){let e;try{e=JSON.parse(t)}catch(s){throw new Br(`Persisted blob is not valid JSON: ${s.message}`)}if(typeof e!="object"||e===null)throw new Br("Persisted blob is not an object");if(e.version!==1&&e.version!==2)throw new Br(`Persisted blob has version ${String(e.version)}, expected 1 or 2`);if(typeof e.firestore!="object"||e.firestore===null)throw new Br("Persisted blob has no firestore field");const r={};for(const[s,i]of Object.entries(e.firestore))r[s]=Si(i);const n=e.services!==void 0&&typeof e.services=="object"&&e.services!==null?e.services:{};return{firestore:r,services:n}}const Jp=3,Qp=256,Bs="meta";function Yp(t){let e=2166136261;for(let r=0;r<t.length;r++)e^=t.charCodeAt(r),e=e+((e<<1)+(e<<4)+(e<<7)+(e<<8)+(e<<24))>>>0;return(e%Qp).toString(16).padStart(2,"0")}function Xp(t){return JSON.parse(JSON.stringify(t))}function Fc(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 Lc(t,e,r){const n=new Map;n.set(Bs,{version:Jp,savedAt:r,services:e});for(const[s,i]of Object.entries(t)){const a=Yp(s);let o=n.get(a);o||(o={docs:{}},n.set(a,o)),o.docs[s]=Xp(i)}for(const[s,i]of n)s!==Bs&&(i.checksum=Fc(i.docs));return n}const jc="pyric-v3-records";function dg(t){return JSON.stringify({format:jc,records:Object.fromEntries(t)})}function hg(t){let e;try{e=JSON.parse(t)}catch{return new Map}const r=e;return r&&typeof r=="object"&&r.format===jc&&typeof r.records=="object"&&r.records!==null?new Map(Object.entries(r.records)):Dc(t)??new Map}function Dc(t){let e;try{e=Zp(t)}catch{return null}return Lc(e.firestore,e.services,0)}function em(t){const e={};let r={};for(const[n,s]of t){if(n===Bs){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"&&Fc(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]=Si(o)}}return{firestore:e,services:r}}const sr="snapshots";function Ga(){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 Mc(t){return new Promise((e,r)=>{const n=indexedDB.open(t,1);n.onupgradeneeded=()=>{const s=n.result;s.objectStoreNames.contains(sr)||s.createObjectStore(sr)},n.onsuccess=()=>e(n.result),n.onerror=()=>r(n.error??new Error(`Failed to open IndexedDB '${t}'`)),n.onblocked=()=>r(new Error(`IndexedDB open blocked for '${t}'`))})}function ss(t,e,r){return Mc(t).then(n=>new Promise((s,i)=>{const a=n.transaction(sr,e),o=a.objectStore(sr),c=r(o);let u=null;c&&(c.onsuccess=()=>{u=c.result??null},c.onerror=()=>i(c.error)),a.oncomplete=()=>{n.close(),s(u)},a.onerror=()=>{n.close(),i(a.error)},a.onabort=()=>{n.close(),i(a.error??new Error("IndexedDB transaction aborted"))}}))}function Ka(t,e){return Mc(t).then(r=>new Promise((n,s)=>{const i=r.transaction(sr,"readwrite");e(i.objectStore(sr)),i.oncomplete=()=>{r.close(),n()},i.onerror=()=>{r.close(),s(i.error)},i.onabort=()=>{r.close(),s(i.error??new Error("IndexedDB transaction aborted"))}}))}function tm(){if(typeof indexedDB>"u")throw new Error('IndexedDB is not available in this environment. Use { backend: "memory" } or supply an injectedBackend.');return{async getRecord(t,e){return await ss(t,"readonly",n=>n.get(e))??null},async listRecords(t){return(await ss(t,"readonly",r=>r.getAllKeys())??[]).map(r=>String(r))},async putRecords(t,e){await Ka(t,r=>{for(const[n,s]of e)r.put(s,n)})},async deleteRecords(t,e){await Ka(t,r=>{for(const n of e)r.delete(n)})},async clear(t){await ss(t,"readwrite",e=>e.clear())},async estimate(){if(typeof navigator>"u"||!navigator.storage?.estimate)return null;const t=await navigator.storage.estimate();return{usage:t.usage??0,quota:t.quota??0}}}}const rm=250,Za="pyric:sandbox:auth-session";function is(t){return t==="auth"||t==="auth-session:[DEFAULT]"?Za:`${Za}:${encodeURIComponent(t)}`}function Pc(t){const e=JSON.stringify(t);let r=2166136261;for(let n=0;n<e.length;n++)r^=e.charCodeAt(n),r=Math.imul(r,16777619)>>>0;return r}function nm(t){if(t&&typeof t=="object"){if(t.name==="QuotaExceededError")return!0;const e=t.message;if(typeof e=="string"&&/quota/i.test(e))return!0}return!1}function sm(t){return t.injectedBackend?t.injectedBackend:(t.backend??"indexedDB")==="memory"||typeof indexedDB>"u"?Ga():tm()}async function im(t,e){const r={...e,flushIntervalMs:e.flushIntervalMs??rm,backend:e.backend??"indexedDB"},n=sm(r),s=new Map,i=await am(t,n,r.key,s);let a=null,o=!1;const c=new Map,u=async()=>{if(o)return;const _=t.snapshot(),v=Lc(_.firestore,_.services,Date.now()),O=new Map,A=new Map;for(const[p,g]of v){const m=Pc(g);A.set(p,m),s.get(p)!==m&&O.set(p,g)}const h=[...s.keys()].filter(p=>!v.has(p));O.size>0&&await n.putRecords(r.key,O),h.length>0&&await n.deleteRecords(r.key,h),s.clear();for(const[p,g]of A)s.set(p,g)};let d=Promise.resolve();const l=()=>(a&&(clearTimeout(a),a=null),d=d.then(u,u),d),f=()=>{o||a||(a=setTimeout(()=>{a=null,l().catch(_=>{if(nm(_)){console.warn("[sandbox/persistence] storage quota exceeded; recent changes are kept in memory only. Free storage or reduce sandbox data to persist them.");return}console.warn("[sandbox/persistence] auto-flush failed, will retry:",_),f()})},r.flushIntervalMs))},y=(_,v)=>{if(!v.subscribe||c.has(_))return;const O=v.subscribe(()=>{f()});c.set(_,O)},b=new Map,S=new Map,j=(_,v)=>{if(!r.sessionStorage)return;const{local:O,session:A}=r.sessionStorage,h=is(_),p=v.currentUid(),g=v.mode();if(p===null||g==="NONE"){O.removeItem(h),A.removeItem(h);return}const m=JSON.stringify({uid:p});g==="LOCAL"?(A.removeItem(h),O.setItem(h,m)):(O.removeItem(h),A.setItem(h,m))},T=_=>{if(!r.sessionStorage)return null;const v=is(_);for(const[O,A]of[["LOCAL",r.sessionStorage.local],["SESSION",r.sessionStorage.session]]){const h=A.getItem(v);if(h)try{const p=JSON.parse(h);if(typeof p?.uid=="string")return{uid:p.uid,mode:O}}catch{A.removeItem(v)}}return null},L=_=>{if(!r.sessionStorage)return;const v=is(_);r.sessionStorage.local.removeItem(v),r.sessionStorage.session.removeItem(v)},k=(_,v,O)=>{if(O.session)try{O.session.restore(v.uid,v.mode),S.delete(_)}catch(A){console.warn(`[sandbox/persistence] session restore for uid '${v.uid}' failed — clearing stored session:`,A),L(_),S.delete(_)}},$=(_,v)=>{if(!r.sessionStorage||!v.session||b.has(_))return;const O=v.session;b.set(_,O.subscribe(()=>j(_,O)))},V=(_,v)=>{if(!v.session)return;const O=S.get(_)??T(_);O&&k(_,O,v)};if(t instanceof xt){for(const[_,v]of t.getServiceRegistry())y(_,v),V(_,v),$(_,v);t.setServiceRegistrationHook((_,v)=>{if(i!==null&&_ in i)try{v.restore(i[_])}catch(A){console.warn(`[sandbox/persistence] late-restore for service '${_}' failed:`,A)}const O=T(_);O&&S.set(_,O),V(_,v),y(_,v),$(_,v),f()}),t.setServiceUnregistrationHook(_=>{c.get(_)?.(),c.delete(_),b.get(_)?.(),b.delete(_),S.delete(_),f()})}const w=t.onEvent(_=>{om(_)&&f()}),x=()=>{l().catch(()=>{})};return typeof window<"u"&&window.addEventListener("beforeunload",x),{options:r,flush:l,async clear(){a&&(clearTimeout(a),a=null),await n.clear(r.key),s.clear()},dispose(){if(!o){o=!0,a&&(clearTimeout(a),a=null),w();for(const _ of c.values())_();c.clear();for(const _ of b.values())_();b.clear(),t instanceof xt&&(t.setServiceRegistrationHook(null),t.setServiceUnregistrationHook(null)),typeof window<"u"&&window.removeEventListener("beforeunload",x)}}}}async function am(t,e,r,n){let s;try{s=await e.listRecords(r)}catch(d){return console.warn("[sandbox/persistence] backend list failed:",d),null}if(s.length===0)return null;const i=[];for(const d of s)try{const l=await e.getRecord(r,d);l!==null&&i.push([d,l])}catch(l){console.warn(`[sandbox/persistence] failed to read persisted record '${d}':`,l)}const a=[],o=[];let c=null;for(const[d,l]of i)if(typeof l=="string"){const f=Dc(l);f&&(o.push(d),c=f)}else a.push([d,l]);if(c){try{await e.putRecords(r,c),o.length>0&&await e.deleteRecords(r,o)}catch(d){console.warn("[sandbox/persistence] v2 migration write failed:",d)}for(const[d,l]of c)a.push([d,l])}for(const[d,l]of a)n.set(d,Pc(l));const u=em(a);for(const[d,l]of Object.entries(u.firestore))t.admin.setDocument(d,l);if(t instanceof xt){const d=t.getServiceRegistry();for(const[l,f]of Object.entries(u.services)){const y=d.get(l);if(y)try{y.restore(f)}catch(b){console.warn(`[sandbox/persistence] service '${l}' restore failed — Firestore state is intact; auth users may need to be re-created:`,b)}}}return u.services}function om(t){return t.kind==="write"||t.kind==="session_boundary"}function cm(t){return typeof t=="object"&&t!==null&&typeof t.kind=="string"&&typeof t.origin=="string"}let um=0;function lm(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`tab-${crypto.randomUUID()}`:`tab-${++um}-${typeof performance<"u"?performance.now().toFixed(3):String(Date.now())}`}function dm(t,e={}){let r,n=!1;if(e.channel)r=e.channel,n=!1;else if(typeof BroadcastChannel<"u")r=new BroadcastChannel("pyric:tabsync"),n=!0;else return()=>{};const s=e.originId??lm();let i=!1,a=!1;const o=t.onEvent(l=>{if(l.kind!=="write"||i)return;const f={kind:"write",origin:s,event:l};r.postMessage(f)}),c=l=>{if(!cm(l.data))return;const f=l.data;if(f.origin!==s){if(f.kind==="write")d(f.event);else if(f.kind==="hello"){const y={kind:"state",origin:s,to:f.origin,snapshot:t.snapshot()};r.postMessage(y)}else if(f.kind==="state"){if(f.to!==s||a)return;if(Object.keys(Ke(t).snapshot()).length>0){a=!0;return}i=!0;try{for(const[b,S]of Object.entries(f.snapshot.firestore))t.admin.setDocument(b,S)}finally{i=!1}a=!0}}};r.addEventListener("message",c);const u={kind:"hello",origin:s};return r.postMessage(u),()=>{o(),r.removeEventListener("message",c),n&&r.close()};function d(l){i=!0;try{if(l.method==="delete")t.admin.deleteDocument(l.path);else{const f=l.nextState;f!=null&&t.admin.setDocument(l.path,f)}}finally{i=!1}}}function hm(t,e){const r={...t};r.service=t.service??e?.service??"firestore";const s="detail"in t&&t.detail?.admin===!0&&t.operationContext===void 0&&t.authLens===void 0?{...t,authLens:{mode:"admin"}}:t,i=$s(r)||t.operationContext!==void 0?vi(e,s):fm(t,e);return r.operationContext=i,r.actor=i.source,r.authLens=i.authLens,i.planId!==void 0&&(r.planId=i.planId),e?.activity!==void 0&&(r.activity={...r.activity,...e.activity}),$s(r)&&(r.rulesDisposition=Object.freeze({...Tc(r)})),r}function fm(t,e){return Dr({source:t.actor??t.operationContext?.source??e?.actor??e?.operationContext?.source??{kind:"unattributed"},authLens:t.authLens??t.operationContext?.authLens??e?.authLens??e?.operationContext?.authLens??{mode:"app-session"},...(t.planId??t.operationContext?.planId??e?.planId??e?.operationContext?.planId)===void 0?{}:{planId:t.planId??t.operationContext?.planId??e?.planId??e?.operationContext?.planId}})}function pm(t,e){if(!t)return e;if(!e)return t;if(e.operationContext!==void 0)return $c(t,e);if(!(t.operationContext!==void 0||t.actor!==void 0||t.authLens!==void 0||t.planId!==void 0||e.actor!==void 0||e.authLens!==void 0||e.planId!==void 0))return{...t,...e};const n=Dr({source:e.actor??t.operationContext?.source??t.actor??{kind:"unattributed"},authLens:e.authLens??t.operationContext?.authLens??t.authLens??{mode:"app-session"},...(e.planId??t.operationContext?.planId??t.planId)===void 0?{}:{planId:e.planId??t.operationContext?.planId??t.planId}});return{...t,...e,operationContext:n,actor:n.source,authLens:n.authLens,...n.planId===void 0?{}:{planId:n.planId}}}function $c(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=vi(t,e);return{...t,...e,operationContext:n,actor:n.source,authLens:n.authLens,...n.planId===void 0?{}:{planId:n.planId}}}let mm=1;function Lt(){const t=(mm++).toString(36),e=Math.random().toString(36).slice(2,7);return`sbe-${t}-${e}`}class xt{_env;eventSubs=new Set;envUnsubs=[];dispatchedCount=0;eventHistory=[];ambientProvenance;_currentUser=null;currentUserSubs=new Set;persistence=null;enablePersistencePromise=null;serviceRegistry=new Map;_onServiceRegistered=null;_onServiceUnregistered=null;constructor(e){this._env=e,this.attachToEnv()}static createRoot(){return new xt(new Va)}getEnv(){return this._env}withAuth(e){return qs(e),new Mr(this,e)}attachToEnv(){this.envUnsubs.push(this._env.onRequest(e=>{this.emitEvent(e)})),this.envUnsubs.push(this._env.onWrite(e=>{this.emitEvent(e)})),this.envUnsubs.push(this._env.onSnapshotDelivery(e=>this.emitEvent(e))),this.envUnsubs.push(this._env.onSnapshotSuppressed(e=>this.emitEvent(e))),this.envUnsubs.push(this._env.onListenerLifecycle(e=>this.emitEvent(e))),this.envUnsubs.push(this._env.onSnapshotError((e,r,n)=>{const s={kind:"listener_errored",id:Lt(),at:Date.now(),listenerId:n,target:r.kind==="doc"?{kind:"doc",path:r.path}:{kind:"query",collection:r.collection},auth:e.request?.auth??null,error:{code:"permission-denied",message:e.message}};this.emitEvent(s)}))}emitEvent(e,r){const n=$c(this.ambientProvenance,r);this.dispatch(hm(e,n))}runWithProvenance(e,r){const n=this.ambientProvenance;this.ambientProvenance=pm(n,e);try{return r()}finally{this.ambientProvenance=n}}dispatch(e){if(this.eventHistory.push(e),this.dispatchedCount++,this.eventSubs.size!==0)for(const r of this.eventSubs)try{const n=r(e);n&&typeof n.then=="function"&&n.catch(()=>{})}catch{}}emitInternal(e,r){this.emitEvent(e,r)}onEvent(e){return this.eventSubs.add(e),()=>{this.eventSubs.delete(e)}}history(){return[...this.eventHistory]}primeEventHistory(e){return this.eventHistory.length>0||e.length===0?0:(this.eventHistory.push(...e),e.length)}get admin(){return{getDocument:e=>this._env.getDocument(e),listDocuments:e=>this._env.listDocuments(e),setDocument:(e,r)=>this._env.adminSetDocument(e,r),deleteDocument:e=>this._env.adminDeleteDocument(e)}}reset(){const e={kind:"session_boundary",id:Lt(),at:Date.now(),phase:"reset",priorOpCount:this.dispatchedCount};this.emitEvent(e),this.eventHistory=[],this._currentUser!==null&&(this._currentUser=null,this.notifyCurrentUserSubs(null));for(const r of this.envUnsubs)r();this.envUnsubs=[],this._env.dispose(),this._env=new Va,this.attachToEnv()}async resetAll(){this.reset();const e=[],r=[];for(const[n,s]of this.serviceRegistry)s.reset&&r.push(Promise.resolve().then(()=>s.reset()).catch(i=>{e.push(`${n}: ${i instanceof Error?i.message:String(i)}`)}));return await Promise.all(r),{errors:e}}dispose(){const e={kind:"session_boundary",id:Lt(),at:Date.now(),phase:"dispose",priorOpCount:this.dispatchedCount};this.emitEvent(e);for(const r of this.envUnsubs)r();this.envUnsubs=[],this._env.dispose(),this.persistence&&(this.persistence.dispose(),this.persistence=null),this.serviceRegistry.clear(),this._onServiceRegistered=null,this._onServiceUnregistered=null,this.eventSubs.clear(),this.currentUserSubs.clear()}snapshot(){const e={};for(const[r,n]of this.serviceRegistry)e[r]=n.snapshot();return{firestore:this._env.snapshot(),services:e}}loadSnapshot(e){this.reset();for(const[r,n]of Object.entries(e.firestore))this._env.adminSetDocument(r,n);for(const[r,n]of this.serviceRegistry)if(r in e.services)try{n.restore(e.services[r])}catch(s){console.warn(`[sandbox] loadSnapshot: service '${r}' restore failed — Firestore is intact; that service's state may be incomplete:`,s)}}get currentUser(){return this._currentUser}set currentUser(e){qs(e),!gm(this._currentUser,e)&&(this._currentUser=e,this.notifyCurrentUserSubs(e))}onCurrentUserChanged(e){return this.currentUserSubs.add(e),()=>{this.currentUserSubs.delete(e)}}notifyCurrentUserSubs(e){if(this._env.reevaluateLiveListeners(e),this.currentUserSubs.size!==0)for(const r of this.currentUserSubs)try{const n=r(e);n&&typeof n.then=="function"&&n.catch(()=>{})}catch{}}async enablePersistence(e){if(this.persistence){if(this.persistence.options.key!==e.key)throw new se("failed-precondition",`Persistence already enabled with key '${this.persistence.options.key}'; cannot re-enable with key '${e.key}'. Dispose and recreate the sandbox.`);return}if(this.enablePersistencePromise)return this.enablePersistencePromise;this.enablePersistencePromise=(async()=>{const r=await im(this,e);this.persistence=r})();try{await this.enablePersistencePromise}finally{this.enablePersistencePromise=null}}enableTabSync(e){return dm(this,e)}async flush(){if(!this.persistence)throw new se("failed-precondition","flush() called before enablePersistence()");await this.persistence.flush()}async clearPersistence(){this.persistence&&await this.persistence.clear()}registerPersistableService(e,r){if(this.serviceRegistry.has(e))throw new se("failed-precondition",`registerPersistableService: a service named '${e}' is already registered on this sandbox. Each service name must be unique — the auth package registers 'auth' exactly once per sandbox.`);return this.serviceRegistry.set(e,r),this._onServiceRegistered&&this._onServiceRegistered(e,r),()=>{this.serviceRegistry.get(e)===r&&(this.serviceRegistry.delete(e),this._onServiceUnregistered?.(e))}}setServiceRegistrationHook(e){this._onServiceRegistered=e}setServiceUnregistrationHook(e){this._onServiceUnregistered=e}getServiceRegistry(){return this.serviceRegistry}}function gm(t,e){if(t===e)return!0;if(t===null||e===null||t.uid!==e.uid)return!1;const r=t.token===void 0?void 0:JSON.stringify(t.token),n=e.token===void 0?void 0:JSON.stringify(e.token);return r===n}function Ke(t){if(!(t instanceof xt))throw new se("invalid-argument","Sandbox handle was not produced by initializeSandbox(); custom Sandbox implementations are not supported.");return t.getEnv()}function fg(t,e,r){if(!(t instanceof xt))throw new se("invalid-argument","Sandbox handle was not produced by initializeSandbox(); custom Sandbox implementations are not supported.");t.emitInternal(e,r)}function pg(t){return{kind:"service_mutation",id:Lt(),at:Date.now(),...t}}function mg(t){const{at:e,...r}=t;return{kind:"operation",id:Lt(),at:e??Date.now(),...r}}function gg(t){const{at:e,...r}=t;return{kind:"commit",id:Lt(),at:e??Date.now(),...r}}function yg(t){const{at:e,...r}=t;return{kind:"listener",id:Lt(),at:e??Date.now(),...r}}function bg(){return xt.createRoot()}const ym=Symbol.for("pyric.remote.sandbox");function _i(t){return t!=null&&t[ym]===!0}function Cr(t){return t.replace(/^\/+|\/+$/g,"").split("/")}function qc(t){return Cr(t).length%2===0&&Cr(t).length>0}function Ai(t){return Cr(t).length%2===1}function Un(t){const e=Cr(t);return e[e.length-1]??""}function Uc(t){return Cr(t).slice(0,-1).join("/")}function Bc(t,e){const r=e!==void 0,n=r?jr(e):void 0;return{id:t.id,ref:t,exists:r,data:()=>r?n:void 0,get:s=>or(n,s)}}const Ja=new WeakMap;let bm=1;function Qa(t){let e=Ja.get(t);return e===void 0&&(e=bm++,Ja.set(t,e)),e}function Cn(t){if(t===null||typeof t=="boolean")return t;if(typeof t=="string")return Hf(t);if(typeof t>"u")return{type:"undefined"};if(typeof t=="bigint")return qt("bigint",t.toString());if(typeof t=="number"){const r=Number.isNaN(t)?"NaN":t===1/0?"Infinity":t===-1/0?"-Infinity":Object.is(t,-0)?"-0":String(t);return qt("number",r)}if(typeof t!="object"&&typeof t!="function")return{type:typeof t,value:String(t)};const e=Kf(t);if(e!==void 0)return e;try{if(Array.isArray(t))return{type:"array",id:Qa(t)}}catch{}return{type:"opaque-object",id:Qa(t)}}function gt(t){return new ce({code:"invalid-argument",message:t})}function zs(t,e,r,n=!1,s=!1){if(t===null||typeof t=="string"||typeof t=="boolean")return{comparison:t,execution:t};if(typeof t=="number")return{comparison:t,execution:t};if(typeof t>"u"||typeof t=="bigint"||typeof t=="function"||typeof t=="symbol")throw gt(`Unsupported Firestore query value: ${typeof t}.`);if(typeof t!="object")throw gt("Unsupported Firestore query value.");const i=oc(t);if(i!==void 0){const o=vf(t);if(o!==void 0&&r!==void 0&&o!==r)throw gt("Document reference belongs to a different Firestore database.");return{comparison:{type:"registered-firestore-value",value:i},execution:wf(t)}}if(t instanceof Date){const o=t.getTime();if(!Number.isFinite(o))throw gt("Invalid Date query value.");const c=Math.floor(o/1e3),u=Object.freeze({seconds:c,nanoseconds:Math.floor((o-c*1e3)*1e6)}),d={type:"timestamp",...u};return Ht(u,d,()=>Object.freeze({...u})),{comparison:{type:"registered-firestore-value",value:d},execution:u}}if(t instanceof Uint8Array){const o=t.slice();return{comparison:{type:"bytes",values:Array.from(o)},execution:o}}if(e.has(t))throw gt("Cyclic query operands are not Firestore values.");const a=Object.getPrototypeOf(t);if(a!==Object.prototype&&a!==null&&!Array.isArray(t))throw gt("Firestore query maps must be plain objects.");e.add(t);try{if(Array.isArray(t)){if(s&&!n)throw gt("Nested arrays are not supported.");const u=t.map(l=>zs(l,e,r,n,!0)),d=u.map(l=>l.execution);return st(d,Cn(t)),{comparison:{type:"array",values:u.map(l=>l.comparison)},execution:d}}const o=Object.keys(t).sort().map(u=>({key:u,captured:zs(t[u],e,r,n,!1)})),c=Object.fromEntries(o.map(({key:u,captured:d})=>[u,d.execution]));return st(c,Cn(t)),{comparison:{type:"map",entries:o.map(({key:u,captured:d})=>[u,d.comparison])},execution:c}}finally{e.delete(t)}}function zc(t,e,r=!1){try{const n=zs(t,new Set,e,r);return Object.freeze({kind:"canonical",value:n.comparison,executionValue:n.execution})}catch(n){if(n instanceof ce)throw n;const s=n instanceof Error?n.message:String(n);throw gt(`Invalid Firestore query value: ${s}`)}}function Vc(t,e){return Ge(t.value,e.value)}function Zr(t,e){if(t.kind==="where"){const r="comparisonValue"in t?t.comparisonValue:zc(t.value,e,t.op==="in"||t.op==="not-in");return Object.freeze({kind:"where",field:t.field,op:t.op,value:r.executionValue,comparisonValue:r})}return Object.freeze({kind:t.kind,filters:Object.freeze(t.filters.map(r=>Zr(r,e)))})}function zr(t,e,r,n){const s=t.map(i=>zc(i,n));return Object.freeze({values:Object.freeze(s.map(i=>i.executionValue)),comparisonValues:Object.freeze(s),inclusive:e,fromSnapshot:r})}function Wc(t,e){return t.length!==e.length?!1:t.every((r,n)=>{const s=e[n];return r.kind!==s.kind?!1:r.kind==="where"&&s.kind==="where"?r.field===s.field&&r.op===s.op&&Vc(r.comparisonValue,s.comparisonValue):r.kind!=="where"&&s.kind!=="where"&&Wc(r.filters,s.filters)})}function Ya(t,e){return t===void 0||e===void 0?t===e:t.inclusive===e.inclusive&&t.comparisonValues.length===e.comparisonValues.length&&t.comparisonValues.every((r,n)=>Vc(r,e.comparisonValues[n]))}function vm(t,e){return t.kind!==e.kind?!1:t.kind==="collection"&&e.kind==="collection"?t.path===e.path:t.kind==="collection-group"&&e.kind==="collection-group"&&t.collectionId===e.collectionId}function Hc(t){return t.kind==="where"?Object.freeze({kind:t.kind,field:t.field,op:t.op,value:t.value}):Object.freeze({kind:t.kind,filters:Object.freeze(t.filters.map(Hc))})}function Xa(t){if(t!==void 0)return Object.freeze({values:t.values,inclusive:t.inclusive,fromSnapshot:t.fromSnapshot})}function wm(t,e){return Wc(t.filters,e.filters)&&t.orders.length===e.orders.length&&t.orders.every((r,n)=>{const s=e.orders[n];return r.field===s.field&&r.direction===s.direction})&&t.limitCount===e.limitCount&&t.limitFromEnd===e.limitFromEnd&&Ya(t.start,e.start)&&Ya(t.end,e.end)}const Gc="__name__";function eo(t,e){const r=t.data();if(r===void 0)throw new ce({code:"not-found",message:`Snapshot-based cursors require an existing document — got an empty snapshot for ${t.id??"<unknown>"}.`});return e.map(n=>n.field===Gc?t.ref:r[n.field])}class Tr{env;auth;collectionPath;clauses;orders;limitCount;limitFromEnd;start;end;bypassRules;documentRef;constructor(e){this.env=e.env,this.auth=e.auth,this.collectionPath=e.collectionPath,this.documentRef=e.documentRef,this.clauses=Object.freeze((e.clauses??[]).map(r=>Zr(r))),this.orders=Object.freeze((e.orders??[]).map(r=>Object.freeze({...r}))),this.limitCount=e.limitCount,this.limitFromEnd=e.limitFromEnd??!1,this.start=e.start===void 0?void 0:Object.freeze({...e.start,values:Object.freeze(e.start.comparisonValues.map(r=>r.executionValue)),comparisonValues:e.start.comparisonValues}),this.end=e.end===void 0?void 0:Object.freeze({...e.end,values:Object.freeze(e.end.comparisonValues.map(r=>r.executionValue)),comparisonValues:e.end.comparisonValues}),this.bypassRules=e.bypassRules??!1}where(e,r,n){return this.clone({clauses:[...this.clauses,Zr({kind:"where",field:e,op:r,value:n})]})}applyFilter(e){return this.clone({clauses:[...this.clauses,Zr(e)]})}orderBy(e,r="asc"){return this.clone({orders:[...this.orders,{field:e,direction:r}]})}limit(e){return this.clone({limitCount:e,limitFromEnd:!1})}limitToLast(e){return this.clone({limitCount:e,limitFromEnd:!0})}startCursor(e,r){return this.clone({start:zr(this.normalizeExplicitCursorValues(e),r,!1)})}endCursor(e,r){return this.clone({end:zr(this.normalizeExplicitCursorValues(e),r,!1)})}startCursorFromSnapshot(e,r){return this.clone({start:zr(eo(e,this.normalizedOrders()),r,!0)})}endCursorFromSnapshot(e,r){return this.clone({end:zr(eo(e,this.normalizedOrders()),r,!0)})}isStructurallyEqual(e){return e instanceof Tr?this.env===e.env&&this.bypassRules===e.bypassRules&&vm(this.queryScope(),e.queryScope())&&wm(this.comparableExecutionSpec(),e.comparableExecutionSpec()):!1}clone(e){return new Tr({env:this.env,auth:this.auth,collectionPath:this.collectionPath,documentRef:this.documentRef,clauses:e.clauses??this.clauses,orders:e.orders??this.orders,limitCount:"limitCount"in e?e.limitCount:this.limitCount,limitFromEnd:e.limitFromEnd??this.limitFromEnd,start:"start"in e?e.start:this.start,end:"end"in e?e.end:this.end,bypassRules:this.bypassRules})}queryScope(){return{kind:"collection",path:this.collectionPath}}readQueryRows(e){const r=e?.auth!==void 0?e.auth:this.auth;let n;try{n=this.env.runQuery({scope:this.queryScope(),auth:r,execution:this.executionSpec(),bypassRules:this.bypassRules,activityQuery:this.activityQuery()})}catch(s){const i=s?.simError;throw i?new ce(i):s}if(!n.allowed)throw new ce(n.error);return n.docs}activityQuery(){const e=n=>n.kind==="where"?{kind:"where",field:n.field,op:n.op,value:Cn(n.value)}:{kind:n.kind,filters:n.filters.map(e)},r=n=>n===void 0?null:{values:n.values.map(s=>Cn(s)),inclusive:n.inclusive,fromSnapshot:n.fromSnapshot};return{scope:this.activityScope(),filters:this.clauses.map(e),orderBy:this.orders.map(n=>({...n})),limit:this.limitCount??null,limitFromEnd:this.limitFromEnd,start:r(this.start),end:r(this.end)}}activityScope(){return{kind:"collection"}}normalizedOrders(){return Ic(this.executionSpec())}normalizeExplicitCursorValues(e){const r=this.orders;return e.map((n,s)=>{if(r[s]?.field!==Gc)return n;if(typeof n!="string")throw new ce({code:"invalid-argument",message:"Expected a string for a document ID cursor value."});const i=n.includes("/")?n:`${this.collectionPath}/${n}`;return this.documentRef(i)})}executionSpec(){const e={filters:Object.freeze(this.clauses.map(Hc)),orders:this.orders,limitCount:this.limitCount,limitFromEnd:this.limitFromEnd,start:Xa(this.start),end:Xa(this.end)};return Object.freeze(e)}comparableExecutionSpec(){return{filters:this.clauses,orders:this.orders,limitCount:this.limitCount,limitFromEnd:this.limitFromEnd,start:this.start,end:this.end}}snapshotConstraints(){return Object.freeze({execution:this.executionSpec(),activityQuery:this.activityQuery()})}async get(e){const n=this.readQueryRows(e).map(s=>{const i=this.documentRef(s.path),a=jr(s.data);return{id:i.id,ref:i,exists:!0,data:()=>a,get:o=>or(a,o)}});return{size:n.length,empty:n.length===0,docs:n,forEach(s){n.forEach(s)}}}async aggregate(e,r){const n=this.readQueryRows(r),s={};for(const i of Object.keys(e))s[i]=_m(e[i],n);return{data:()=>s}}}function Sm(t,e){if(!e.includes("."))return t[e];let r=t;for(const n of e.split(".")){if(typeof r!="object"||r===null||Array.isArray(r))return;r=r[n]}return r}function _m(t,e){if(t.kind==="count")return e.length;let r=0,n=0;for(const s of e){const i=Sm(s.data,t.field);typeof i=="number"&&Number.isFinite(i)&&(r+=i,n++)}return t.kind==="sum"?r:n===0?null:r/n}function Kt(t,e){if(t.error)throw new ce(t.error);const r=t.debugMessages.length>0?t.debugMessages.join("; "):"(no debug message)";throw new ce(ee("permission-denied",`${e}: ${r}`))}class Am{env;auth;bypassRules;collectionRef;id;path;constructor(e,r,n,s=!1,i){this.env=e,this.auth=r,this.bypassRules=s,this.collectionRef=i,this.path=n,this.id=Un(n),st(this,qt("reference",n)),fi(this,n,e)}get parent(){return this.collectionRef(Uc(this.path))}collection(e){return this.collectionRef(`${this.path}/${e}`)}async get(e){const r=this.env.execute({method:"get",path:this.path,auth:e?.auth!==void 0?e.auth:this.auth,bypassRules:this.bypassRules});r.allowed||Kt(r,"get denied");const n=r.data===void 0||r.data===null?void 0:r.data;return Bc(this,n)}async set(e,r){const n=r?.auth!==void 0?r.auth:this.auth;if(r?.mergeFields!==void 0){const i=r.mergeFields.map(u=>String(u)),o=this.env.getDocument(this.path)===null?"create":"update",c=this.env.execute({method:o,path:this.path,data:e,auth:n,merge:{mergeFields:i},bypassRules:this.bypassRules});c.allowed||Kt(c,`set denied (as ${o})`);return}if(r?.merge===!0){const a=this.env.getDocument(this.path)===null?"create":"update",o=this.env.execute({method:a,path:this.path,data:e,auth:n,merge:!0,bypassRules:this.bypassRules});o.allowed||Kt(o,`set denied (as ${a})`);return}const s=this.env.execute({method:"set",path:this.path,data:e,auth:n,bypassRules:this.bypassRules});s.allowed||Kt(s,"set denied")}async update(e,r){const n=this.env.execute({method:"update",path:this.path,data:e,auth:r?.auth!==void 0?r.auth:this.auth,bypassRules:this.bypassRules});n.allowed||Kt(n,"update denied")}async delete(e){const r=this.env.execute({method:"delete",path:this.path,auth:e?.auth!==void 0?e.auth:this.auth,bypassRules:this.bypassRules});r.allowed||Kt(r,"delete denied")}}function Tn(t,e,r,n){return new Am(t,e,r,n,s=>new Kc(t,e,s,n))}class Kc extends Tr{id;path;constructor(e,r,n,s=!1){super({env:e,auth:r,collectionPath:n,bypassRules:s,documentRef:i=>Tn(e,r,i,s)}),this.path=n,this.id=Un(n)}doc(e){const r=e??yi();return Tn(this.env,this.auth,`${this.path}/${r}`,this.bypassRules)}async add(e,r){const n=this.doc();return await n.set(e,r),n}}class xi extends Tr{collectionId;constructor(e){super({...e,collectionPath:"",documentRef:r=>Tn(e.env,e.auth,r,e.bypassRules??!1)}),this.collectionId=e.collectionId}clone(e){return new xi({env:this.env,auth:this.auth,collectionId:this.collectionId,clauses:e.clauses??this.clauses,orders:e.orders??this.orders,limitCount:"limitCount"in e?e.limitCount:this.limitCount,limitFromEnd:e.limitFromEnd??this.limitFromEnd,start:"start"in e?e.start:this.start,end:"end"in e?e.end:this.end,bypassRules:this.bypassRules})}queryScope(){return{kind:"collection-group",collectionId:this.collectionId}}activityScope(){return{kind:"collection-group"}}}class xm{env;auth;bypassRules;ops=[];constructor(e,r,n=!1){this.env=e,this.auth=r,this.bypassRules=n}set(e,r){const s=this.env.getDocument(e.path)===null?"create":"update";return this.ops.push({method:s,path:e.path,data:r}),this}update(e,r){return this.ops.push({method:"update",path:e.path,data:r}),this}delete(e){return this.ops.push({method:"delete",path:e.path}),this}async commit(e){if(this.ops.length===0)return;const r=this.env.batch(this.ops,e?.auth!==void 0?e.auth:this.auth,this.bypassRules);if(r.allowed)return;if(r.error)throw new ce(r.error);const s=r.results.find(i=>!i.allowed)?.debugMessages.join("; ")??"batch denied";throw new ce(ee("permission-denied",`batch failed: ${s}`))}}function Im(t){return typeof t.where=="function"}class km{simTx;constructor(e){this.simTx=e}async get(e){if(Im(e)){const s=await e.get();return s.size>0&&this.simTx.getAll(...s.docs.map(i=>i.ref.path)),s}const n=this.simTx.get(e.path).data();return Bc(e,n)}set(e,r){return this.simTx.set(e.path,r),this}update(e,r){return this.simTx.update(e.path,r),this}delete(e){return this.simTx.delete(e.path),this}}class Em{env;auth;bypassRules;provenance;constructor(e,r,n=!1,s){this.env=e,this.auth=r,this.bypassRules=n,this.provenance=s}collection(e){if(!Ai(e))throw new ce(ee("invalid-argument",`collection path must have an odd number of segments: ${e}`));return new Kc(this.env,this.auth,e,this.bypassRules)}doc(e){if(!qc(e))throw new ce(ee("invalid-argument",`document path must have an even number of segments: ${e}`));return Tn(this.env,this.auth,e,this.bypassRules)}collectionGroup(e){if(e.length===0||e.includes("/"))throw new ce(ee("invalid-argument",`collection group id must be a single non-empty segment with no '/': ${e}`));return new xi({env:this.env,auth:this.auth,collectionId:e,bypassRules:this.bypassRules})}batch(){return new xm(this.env,this.auth,this.bypassRules)}async runTransaction(e,r){let n;try{n=await this.env.transaction(s=>{const i=new km(s);return e(i)},{auth:r?.auth!==void 0?r.auth:this.auth,bypassRules:this.bypassRules,provenance:this.provenance,maxAttempts:r?.maxAttempts})}catch(s){throw s instanceof Oc?new ce(s.simError):s instanceof Cc?new ce(s.simError):s}if(!n.allowed){if(n.error)throw new ce(n.error);const i=n.writes.find(a=>!a.allowed)?.debugMessages.join("; ")??"transaction denied at commit";throw new ce(ee("permission-denied",`transaction failed: ${i}`))}return n.returnValue}}function Om(t,e){return new Em(t,e?.auth??null,e?.bypassRules??!1,e?.provenance)}const Zc=Symbol("pyric/sandbox/context"),Jc=Symbol("pyric/sandbox/bypassRules");let Vs=null;function Cm(t){Vs=t}function Tm(t){const e=t;return typeof e.path=="string"&&e.path.length>0||typeof e.collectionPath=="string"&&e.collectionPath.length>0}function Rm(t){const e=t.trim();if(!e)return[];const r=e.indexOf(": ");if(r!==-1){const s=e.slice(r+2).trim().split("; ").map(i=>i.trim()).filter(i=>i.length>0);if(s.length>0)return s}return[e]}function to(t,e){if(!(t instanceof ce))return t;const r=t.code;if(r!=="permission-denied")return new se(r,t.message);const n={auth:e.auth,reasons:Rm(t.message)},s=t.simError;if(s?.request){const i=s.request;n.request={method:i.method,path:i.path,...i.resourceData?{resourceData:i.resourceData}:{}}}return s?.resource&&(n.resource={data:s.resource.data,exists:s.resource.exists}),s?.query&&(n.query=s.query),s?.remediation!==void 0?new se({code:r,message:t.message,denialContext:n,remediation:s.remediation}):new se(r,t.message,n)}function Rn(t,e,r=!1){return new Proxy(t,{get(n,s,i){if(s===Zc)return e;if(s===Jc)return r;if(s==="onSnapshot"&&Vs!==null&&!(s in n)&&Tm(n))return(...o)=>Vs(i,...o);const a=Reflect.get(n,s,i);return typeof a!="function"?a:function(...o){let c;try{const u=()=>a.apply(n,o);c=e.sandbox.runWithProvenance?.(bi(e.operationContext),u)??u()}catch(u){throw to(u,e)}return c instanceof Promise?c.then(u=>u&&typeof u=="object"?Rn(u,e,r):u).catch(u=>{throw to(u,e)}):c&&typeof c=="object"?Rn(c,e,r):c}}})}function Qc(t,e=!1){if(_i(t.sandbox))throw new Error("pyric/sandbox/admin-firestore: internal — a remote sandbox context reached the local engine builder; remote dispatch should have handled it. Please report this.");const r=()=>Om(Ke(t.sandbox),{auth:t.auth,bypassRules:e,provenance:bi(t.operationContext)});return{collection(n){return r().collection(n)},doc(n){return r().doc(n)},collectionGroup(n){return r().collectionGroup(n)},batch(){return r().batch()},runTransaction(n,s){return r().runTransaction(n,s)},setRules(n){return Ke(t.sandbox).deployRules(n)},seed(n){const s=Ke(t.sandbox);return s.seed({rules:s.getRules(),documents:n?.documents??{}})},snapshot(){return Ke(t.sandbox).snapshot()}}}function Ws(t){if(t instanceof se)return t;if(t!==null&&typeof t=="object"){const e=t;if(typeof e.code=="string"&&typeof e.message=="string"){const r=e.denialContext!==null&&typeof e.denialContext=="object"?e.denialContext:void 0;return new se(e.code,e.message,r)}}return t}function ht(t){return new se("invalid-argument",t)}async function Ze(t,e){try{return await t.sandbox.channel.op({...e,actAs:t.lens})}catch(r){throw Ws(r)}}const Nm=new Set(["serverTimestamp","increment","arrayUnion","arrayRemove","deleteField"]);function Fm(t){return t!==null&&typeof t=="object"&&typeof t.__type=="string"&&Nm.has(t.__type)}function Lm(t){switch(t.__type){case"serverTimestamp":return{__sentinel:"serverTimestamp"};case"increment":return{__sentinel:"increment",n:t.value};case"arrayUnion":return{__sentinel:"arrayUnion",values:t.values.map(pt)};case"arrayRemove":return{__sentinel:"arrayRemove",values:t.values.map(pt)};case"deleteField":return{__sentinel:"deleteField"}}}function pt(t){if(t===null||typeof t!="object")return t;if(Fm(t))return Lm(t);if(t instanceof bt)return t.toJSON();if(t instanceof Date)return bt.fromDate(t).toJSON();if(Array.isArray(t))return t.map(pt);const e=Object.getPrototypeOf(t);if(e!==Object.prototype&&e!==null){const n=t.toJSON;if(typeof n=="function")return n.call(t);throw ht(`remote Firestore: cannot serialize a ${e.constructor?.name??"class"} instance for the wire — use plain data, Timestamp, Date, or FieldValue sentinels.`)}const r={};for(const[n,s]of Object.entries(t))r[n]=pt(s);return r}function Ut(t){return pt(t)}function Hs(t){return Si(JSON.parse(t.json))}function Yc(t){return jr(Hs(t))}function Xc(t,e){const r=e.exists&&e.data?Yc(e.data):void 0;return{id:t.id,ref:t,exists:e.exists,data:()=>r,get:n=>or(r,n)}}function eu(t,e){const r=e.docs.map(n=>{const s=n.path??n.id,i=Nn(t,s),a=n.data?Yc(n.data):{};return{id:i.id,ref:i,exists:!0,data:()=>a,get:o=>or(a,o)}});return{size:r.length,empty:r.length===0,docs:r,forEach(n){r.forEach(s=>n(s))}}}const Ii=Symbol("pyric/sandbox/admin-firestore/remoteSnapshotRegistrar");function jm(t){if(t===null||typeof t!="object")return;const e=t[Ii];return typeof e=="function"?e:void 0}let Gs=null;function Dm(t){Gs=t}function tu(...t){if(Gs===null)throw new se("failed-precondition","remote Firestore: onSnapshot is not wired yet — import pyric-admin/firestore (or pyric/sandbox/admin-firestore) before subscribing.");return Gs(this,...t)}function ru(t,e,r,n,s){const i=r.includeMetadataChanges!==!0;let a,o;try{o=t.sandbox.channel.subscribe({target:e,actAs:t.lens},c=>{if(!n)return;const u=c;if(Array.isArray(u.docs)){const d=u.docs.map(y=>({path:y.path??y.id,data:y.data?Hs(y.data):{}})),l=e.__ref==="query"?e.source.__ref==="group"?e.source.collectionId:e.source.path:e.__ref==="group"?e.collectionId:e.path,f=Qt({path:l},d,{excludesMetadataChanges:i},a);a=d,n(f)}else if(typeof u.id=="string"){const d=u.path??u.id,l=u.exists&&u.data?Hs(u.data):null;n(Jt(d,l))}},c=>{const u=Ws(c);s?s(u):console.error("pyric remote Firestore: uncaught onSnapshot error:",u)})}catch(c){throw Ws(c)}return o}const nu=Symbol("pyric/sandbox/admin-firestore/remoteQueryState");function Mm(t){if(!(t===null||typeof t!="object"))return t[nu]}function su(t){return t.kind==="where"?(iu(t.op),{kind:"where",field:t.field,op:t.op,value:pt(t.value)}):{kind:t.kind,filters:t.filters.map(su)}}const Pm=new Set(["<","<=","==","!=",">=",">","in","not-in","array-contains","array-contains-any"]);function iu(t){if(!Pm.has(t))throw ht(`invalid where operator: ${String(t)}`)}function Jr(t){const e=[...t.filters];for(const r of t.orders)e.push({kind:"orderBy",field:r.field,direction:r.direction});return t.start&&e.push({kind:t.start.inclusive?"startAt":"startAfter",values:t.start.values.map(pt)}),t.end&&e.push({kind:t.end.inclusive?"endAt":"endBefore",values:t.end.values.map(pt)}),t.limitCount!==void 0&&e.push(t.limitFromEnd?{kind:"limitToLast",n:t.limitCount}:{kind:"limit",n:t.limitCount}),e.length===0?t.source:{__ref:"query",source:t.source,constraints:e}}function ro(t,e,r){if(e.length===0)throw ht(`${r}(snapshot) on a remote sandbox requires at least one explicit orderBy() clause — the relay protocol has no document-key cursor.`);if(e.some(s=>s.field==="__name__"))throw ht(`${r}(snapshot) on a remote sandbox does not support orderBy('__name__') — the relay protocol has no document-key cursor, and __name__ is not a data field a value cursor can carry. Order by a real document field instead.`);const n=t.data();if(n===void 0)throw new se("not-found",`Snapshot-based cursors require an existing document — got an empty snapshot for ${t.id??"<unknown>"}.`);return e.map(s=>n[s.field])}function ki(t,e){const r=s=>ki(t,{...e,...s});return{[nu]:e,where(s,i,a){return iu(i),r({filters:[...e.filters,{kind:"where",field:s,op:i,value:pt(a)}]})},applyFilter(s){return r({filters:[...e.filters,su(s)]})},orderBy(s,i="asc"){return r({orders:[...e.orders,{field:s,direction:i}]})},limit(s){return r({limitCount:s,limitFromEnd:!1})},limitToLast(s){return r({limitCount:s,limitFromEnd:!0})},startCursor(s,i){return r({start:{values:[...s],inclusive:i}})},endCursor(s,i){return r({end:{values:[...s],inclusive:i}})},startCursorFromSnapshot(s,i){return r({start:{values:ro(s,e.orders,i?"startAt":"startAfter"),inclusive:i}})},endCursorFromSnapshot(s,i){return r({end:{values:ro(s,e.orders,i?"endAt":"endBefore"),inclusive:i}})},async get(s){Qr(e);const i=await Ze(t,{method:"getDocs",source:Jr(e)});return eu(t,i)},async aggregate(s){Qr(e);const i=await Ze(t,{method:"aggregate",source:Jr(e),spec:s});return{data:()=>i.data}},[Ii]:(s,i,a)=>(Qr(e),ru(t,Jr(e),s,i,a)),onSnapshot:tu}}function Qr(t){if(t.limitFromEnd&&t.orders.length===0)throw ht("limitToLast() queries require at least one orderBy clause.")}function Ks(t,e){const r=ki(t,{source:{__ref:"collection",path:e},filters:[],orders:[],limitFromEnd:!1});return Object.assign(Object.create(Object.getPrototypeOf(r)),r,{id:Un(e),path:e,doc(s){const i=s??yi();return Nn(t,`${e}/${i}`)},async add(s,i){const a=await Ze(t,{method:"addDoc",collectionPath:e,data:Ut(s)});return Nn(t,a.path)}})}function Nn(t,e){const r={id:Un(e),path:e,get parent(){return Ks(t,Uc(e))},collection(n){const s=`${e}/${n}`;if(!Ai(s))throw ht(`collection path must have an odd number of segments: ${s}`);return Ks(t,s)},async get(n){const s=await Ze(t,{method:"getDoc",path:e});return Xc(r,s)},async set(n,s){await Ze(t,{method:"setDoc",path:e,data:Ut(n),...no(s)?{options:no(s)}:{}})},async update(n,s){await Ze(t,{method:"updateDoc",path:e,data:Ut(n)})},async delete(n){await Ze(t,{method:"deleteDoc",path:e})},[Ii]:(n,s,i)=>ru(t,{__ref:"doc",path:e},n,s,i),onSnapshot:tu};return r}function no(t){if(!t)return;const e={};return t.merge!==void 0&&(e.merge=t.merge),t.mergeFields!==void 0&&(e.mergeFields=[...t.mergeFields]),e.merge!==void 0||e.mergeFields!==void 0?e:void 0}function $m(t){const e=[];let r=!1;const n={set(i,a){return s(),e.push({method:"set",path:i.path,data:Ut(a)}),n},update(i,a){return s(),e.push({method:"update",path:i.path,data:Ut(a)}),n},delete(i){return s(),e.push({method:"delete",path:i.path}),n},async commit(i){s(),r=!0,await Ze(t,{method:"batchCommit",writes:e})}};function s(){if(r)throw new se("failed-precondition","WriteBatch has already been committed.")}return n}const qm=5;async function Um(t,e,r=qm){for(let n=0;n<r;n++){const s=[],i=[],a=()=>{if(i.length>0)throw new se("failed-precondition",Ps)},o={get(l){a();const f=Mm(l);return f!==void 0?u(f):c(l)},set(l,f){return i.push({method:"set",path:l.path,data:Ut(f)}),o},update(l,f){return i.push({method:"update",path:l.path,data:Ut(f)}),o},delete(l){return i.push({method:"delete",path:l.path}),o}};async function c(l){const f=await Ze(t,{method:"getDoc",path:l.path});return s.push({path:f.path??l.path,data:f.exists&&f.data?f.data:null}),Xc(l,f)}async function u(l){Qr(l);const f=await Ze(t,{method:"getDocs",source:Jr(l)});for(const y of f.docs)s.push({path:y.path??y.id,data:y.data??null});return eu(t,f)}const d=await e(o);try{return await Ze(t,{method:"txnCommit",reads:s,writes:i}),d}catch(l){if(l instanceof se&&l.code==="aborted")continue;throw l}}throw new se("aborted",`Transaction failed after ${r} attempts due to repeated conflicts. Another writer is concurrently updating the same documents.`)}function as(t,e){return new se("unimplemented",`SandboxFirestore.${t} is not available on a remote sandbox — its return value is synchronous and the data lives in the browser worker. ${e}`)}function au(t,e){const r={sandbox:t,lens:e};return{collection(n){if(!Ai(n))throw ht(`collection path must have an odd number of segments: ${n}`);return Ks(r,n)},doc(n){if(!qc(n))throw ht(`document path must have an even number of segments: ${n}`);return Nn(r,n)},collectionGroup(n){if(n.length===0||n.includes("/"))throw ht(`collection group id must be a single non-empty segment with no '/': ${n}`);return ki(r,{source:{__ref:"group",collectionId:n},filters:[],orders:[],limitFromEnd:!1})},batch(){return $m(r)},runTransaction(n,s){return Um(r,n,s?.maxAttempts)},setRules(){throw as("setRules","Deploy rules asynchronously through the relay instead: `await sandbox.channel.op({ method: 'setFirestoreRules', source })`.")},seed(){throw as("seed","The relay has no atomic seed op; write seed docs through this handle (`db.doc(path).set(data)` / `db.batch()`), or drive `sandbox.channel.op({ method: 'admin.setDocument', path, data })` per document.")},snapshot(){throw as("snapshot","Read the worker state asynchronously instead: `await sandbox.channel.op({ method: 'admin.readState' })`.")}}}const so=new WeakMap;function ou(t){const e=so.get(t);if(e)return e;const r=_i(t.sandbox)?au(t.sandbox,Bm(t.auth)):Rn(Qc(t),t);return so.set(t,r),r}function Bm(t){return t==null?{mode:"anon"}:t.token===void 0?{mode:"as",uid:t.uid}:{mode:"as",uid:t.uid,token:t.token}}const io=new WeakMap;function zm(t){const e=Vm(t)?t:t.withAuth(null),r=io.get(e);if(r)return r;const n=e.operationContext.authLens.mode==="admin"?e:wi(e,{source:e.operationContext.source,authLens:{mode:"admin"},...e.operationContext.planId===void 0?{}:{planId:e.operationContext.planId}}),s=_i(n.sandbox)?au(n.sandbox,{mode:"admin"}):Rn(Qc(n,!0),n,!0);return io.set(e,s),s}function Vm(t){return t!==null&&typeof t=="object"&&"sandbox"in t&&typeof t.withAuth=="function"}const Vr=Symbol("pyric/firestore/followsCurrentUser"),os=Symbol("pyric/firestore/authSessionScope");function Wm(t){if(t===null||typeof t!="object")return null;const e=t;return typeof e.path=="string"&&e.path.length>0?e.path:typeof e.collectionPath=="string"&&e.collectionPath.length>0?e.collectionPath:null}function Hm(t){if(t!==null&&typeof t=="object"){const e=t.snapshotConstraints;if(typeof e=="function")return e.call(t)}}function Gm(t){if(t===null||typeof t!="object")return!1;const e=t;return typeof e.path=="string"&&e.path.length>0&&e.parent!==void 0&&e.parent!==null}function cu(t,e,r,n,s){let i={},a,o;if(typeof e=="object"&&e!==null&&typeof e.next!="function"&&typeof e.error!="function"&&typeof e.complete!="function"){if(i=e,typeof r=="function")a=r,o=n;else if(typeof r=="object"&&r!==null){const T=r;a=T.next,o=T.error}}else if(typeof e=="function")a=e,o=r;else if(typeof e=="object"&&e!==null){const T=e;a=T.next,o=T.error}if(!a&&!o)throw new TypeError("onSnapshot: missing handler. Provide a callback, or an observer with a `next` and/or `error` method.");const u=jm(t);if(u){if(i[Vr]===!0)throw new se("unimplemented","onSnapshot: live (follows-current-user) listeners are not supported on a remote sandbox — remote listeners are frozen to the identity of the context that created the ref.");return u(i,a,o)}const d=Km(t),l=Ke(d.sandbox);let f;if(Gm(t))f={kind:"doc",path:t.path};else{const T=Wm(t);if(T===null)throw new TypeError("onSnapshot: could not determine the collection path for this Query. Pass a CollectionReference or a Query produced by `.where`/`.orderBy`/`.limit` on a CollectionReference obtained from `getFirestore(ctx)`.");const L=Hm(t);f={kind:"query",collection:T,constraints:L}}const y=i[Vr]===!0,b=i[os],S=t[Jc]===!0;if(Vr in i){const{[Vr]:T,...L}=i;i=L}if(os in i){const{[os]:T,...L}=i;i=L}const j=()=>l.addSnapshotListener(f,a??(()=>{}),i,d.auth,o,y,S,b);return d.sandbox.runWithProvenance?.(bi(d.operationContext),j)??j()}function Km(t){if(t===null||typeof t!="object")throw new TypeError("onSnapshot: reference must be a DocumentReference or Query.");const e=t[Zc];if(!e)throw new TypeError("onSnapshot: reference was not produced by a sandbox context — pass a ref obtained from `getFirestore(ctx)`.");return e}Cm(cu);Dm(cu);class Rt{bytes;constructor(e){this.bytes=e,st(this,Gf(e)),Ht(this,Object.freeze({type:"bytes",values:Object.freeze(Array.from(e))}),()=>new Rt(e.slice()))}static fromBase64String(e){const r=atob(e),n=new Uint8Array(r.length);for(let s=0;s<r.length;s+=1)n[s]=r.charCodeAt(s);return new Rt(n)}static fromUint8Array(e){return new Rt(e.slice())}toBase64(){let e="";for(const r of this.bytes)e+=String.fromCharCode(r);return btoa(e)}toUint8Array(){return this.bytes.slice()}toString(){return`Bytes(base64: ${this.toBase64()})`}isEqual(e){return e instanceof Rt&&this.bytes.length===e.bytes.length&&this.bytes.every((r,n)=>r===e.bytes[n])}toJSON(){return{type:"firestore/bytes/1.0",bytes:this.toBase64()}}static fromJSON(e){const r=e;if(r.type!=="firestore/bytes/1.0"||typeof r.bytes!="string")throw new TypeError("Invalid Bytes JSON value.");return Rt.fromBase64String(r.bytes)}}class wr{lat;lng;constructor(e,r){if(this.lat=e,this.lng=r,!Number.isFinite(e)||e<-90||e>90)throw new TypeError("Latitude must be a number between -90 and 90.");if(!Number.isFinite(r)||r<-180||r>180)throw new TypeError("Longitude must be a number between -180 and 180.");st(this,qt("geo-point",String(e),"\0",String(r))),Ht(this,Object.freeze({type:"geo-point",latitude:e,longitude:r}),()=>new wr(e,r))}get latitude(){return this.lat}get longitude(){return this.lng}isEqual(e){return e instanceof wr&&this.lat===e.lat&&this.lng===e.lng}toJSON(){return{latitude:this.lat,longitude:this.lng,type:"firestore/geoPoint/1.0"}}static fromJSON(e){const r=e;if(r.type!=="firestore/geoPoint/1.0"||typeof r.latitude!="number"||typeof r.longitude!="number")throw new TypeError("Invalid GeoPoint JSON value.");return new wr(r.latitude,r.longitude)}}class Xt{_values;constructor(e){this._values=e,Ht(this,Object.freeze({type:"vector",values:Object.freeze(e.slice())}),()=>new Xt(e.slice()))}static create(e){if(!e.every(r=>typeof r=="number"))throw new TypeError("Vector values must be numbers.");return new Xt(e.slice())}toArray(){return this._values.slice()}isEqual(e){const r=e instanceof Xt?e._values:void 0;return r!==void 0&&this._values.length===r.length&&this._values.every((n,s)=>n===r[s])}toJSON(){return{type:"firestore/vectorValue/1.0",vectorValues:this.toArray()}}static fromJSON(e){const r=e;if(r.type!=="firestore/vectorValue/1.0"||!Array.isArray(r.vectorValues)||!r.vectorValues.every(n=>typeof n=="number"))throw new TypeError("Invalid VectorValue JSON value.");return Xt.create(r.vectorValues)}}function Zm(t=[]){return Xt.create(t)}function vg(){return Zf.serverTimestamp()}const St=Symbol("pyric/firestore/target");function Pr(t){return t.kind==="sandbox"?t.db:t.getDb()}const Bn=new WeakMap;function Jm(t,e){return Bn.set(t,e),t}const $r=new WeakMap;function Qm(t,e,r){return Bn.set(t,e),$r.set(t,r),t}function Ei(t,e){const r=ur(e);if(t.kind==="sandbox")return r;const n=$r.get(r);if(!n)throw new TypeError("pyric/firestore: live ref missing rebuild closure — was it produced by a factory in this package?");return n(Pr(t))}function Ym(t,e){const r=ur(e);if(t.kind==="sandbox")return r;const n=$r.get(r);if(!n)throw new TypeError("pyric/firestore: live collection ref missing rebuild closure.");return n(Pr(t))}function wg(t,e){const r=ur(e);if(t.kind==="sandbox")return r;const n=$r.get(r);if(!n)throw new TypeError("pyric/firestore: live query missing rebuild closure.");return n(Pr(t))}function Rr(t,e,r){return e.kind==="sandbox-live"?Qm(t,e,r):Jm(t,e)}function Sg(t){const e=ur(t),r=$r.get(e);return r||(()=>e)}function cr(t){const e=Xm(t);return e.assertUsable?.(),e}function Xm(t){let e;if(St in t?e=t[St]:e=Bn.get(t),!e)throw new TypeError("pyric/firestore: unrecognized reference — was it produced by a factory in this package?");return e}const uu=new WeakMap,lu=new WeakMap;function Oi(t){return uu.get(t)}function ur(t){return lu.get(t)??t}function du(t,e,r){const n={id:t.id??"",path:t.path??""};return uu.set(n,r),lu.set(n,t),Bn.set(n,e),n}function eg(t){return t instanceof Wt?Array.from(t.value):null}function Zs(t){if(t instanceof Be)return Rt.fromUint8Array(t.data);if(t instanceof rt)return new wr(t.lat,t.lng);const e=eg(t);if(e)return Zm(e);if(Array.isArray(t))return t.map(Zs);if(t!==null&&typeof t=="object"){const r=Object.getPrototypeOf(t);if(r===Object.prototype||r===null){const n={};for(const[s,i]of Object.entries(t))n[s]=Zs(i);return n}}return t}function _g(t){if(t!==void 0)return Zs(t)}class ir extends Error{code;customData;name="FirebaseError";constructor(e,r,n){super(r),this.code=e,this.customData=n,Object.setPrototypeOf(this,new.target.prototype)}}Object.defineProperty(ir,"name",{value:"FirebaseError"});let Fn;function Ag(t){Fn=t}function hu(t){return Fn?.resolve(t,!1)}function tg(){if(!Fn)throw new TypeError("No default sandbox app registry is installed - import and initialize pyric/app before calling a service factory without an app.");return Fn.defaultApp()}function rg(t){if(t===void 0)return rg(tg());const e=hu(t);if(e)return e.service("firestore/default",()=>{const{sandbox:r,session:n}=e,s=cs();e.onDelete(s.terminate);const i=e.authScope;i&&s.own(n.onCurrentUserChanged(o=>{Ke(r).reevaluateLiveListeners(o,i)}));const a={kind:"sandbox-live",sandbox:r,getDb:ao(r,()=>n.currentUser),authScope:i,...s};return{[St]:a,app:t}});if(fu(t)){const n={kind:"sandbox",db:ou(t),sandbox:t.sandbox,...cs()};return{[St]:n}}if(sg(t)){const r={kind:"sandbox-live",sandbox:t,getDb:ao(t),...cs()};return{[St]:r}}throw new TypeError("pyric/firestore is a sandbox-only mirror. Package resolution must leave firebase/firestore unchanged for production; activate pyric dev or @pyric/cli/register before importing to select the sandbox.")}function cs(){let t=!1;const e=new Set;return{own(r){return t?(r(),()=>{}):(e.add(r),()=>e.delete(r))},assertUsable(){if(t)throw new ir("failed-precondition","The client has already been terminated.")},terminate(){if(!t){t=!0;for(const r of e)r();e.clear()}}}}function ng(t){const e=hu(t);if(e){e.assertAlive();const a=e.sandbox;return ng(wi(a.withAuth(null),{source:{kind:"app"},authLens:{mode:"admin"}}))}const r=fu(t)?t:t.withAuth(null),n=r.sandbox,i={kind:"sandbox",db:zm(r),sandbox:n};return{[St]:i}}function fu(t){return t instanceof Mr}function sg(t){if(t===null||typeof t!="object")return!1;const e=t;return typeof e.withAuth=="function"&&typeof e.onCurrentUserChanged=="function"&&"currentUser"in e&&"admin"in e}function ao(t,e=()=>t.currentUser){return()=>{const r=wi(t.withAuth(e()),{source:{kind:"app"},authLens:{mode:"app-session"}});return ou(r)}}class ig{started=!1;networkEnabled=!0;persistenceMode;pending=new Set;cachedPaths=new Set;cachedQueries=new WeakSet;syncObservers=new Set;syncScheduled=!1;markStarted(){this.started=!0}enablePersistence(e){if(this.started||this.persistenceMode!==void 0)throw new ir("failed-precondition","Firestore has already been started and persistence can no longer be enabled.");this.persistenceMode=e,this.started=!0}disableNetwork(){this.started=!0,this.networkEnabled=!1}async enableNetwork(){this.started=!0,this.networkEnabled=!0;for(const e of this.pending)e.localDone&&e.resolve(e.value);await Promise.all([...this.pending].map(e=>e.promise))}runWrite(e,r){if(this.started=!0,r&&this.cachedPaths.add(r),this.networkEnabled)return e();let n,s;const i=new Promise((o,c)=>{n=o,s=c}),a={path:r,promise:i,localDone:!1,resolve:n,reject:s};return this.pending.add(a),e().then(o=>{a.localDone=!0,a.value=o,this.networkEnabled&&a.resolve(o)},o=>a.reject(o)),i.then(()=>this.pending.delete(a),()=>this.pending.delete(a)),i}waitForPendingWrites(){this.started=!0;const e=[...this.pending].map(r=>r.promise);return Promise.all(e).then(()=>{})}cachePath(e){this.started=!0,this.cachedPaths.add(e)}assertPathCached(e){if(this.started=!0,!this.cachedPaths.has(e))throw new ir("unavailable","Failed to get document from cache. (However, this document may exist on the server.)")}cacheQuery(e){this.started=!0,this.cachedQueries.add(e)}hasCachedQuery(e){return this.started=!0,this.cachedQueries.has(e)||this.cachedPaths.size>0}snapshotMetadata(e){return Object.freeze({fromCache:!this.networkEnabled,hasPendingWrites:[...this.pending].some(r=>r.path===e)})}querySnapshotMetadata(){return Object.freeze({fromCache:!this.networkEnabled,hasPendingWrites:this.pending.size>0})}addSnapshotsInSyncObserver(e){return this.syncObservers.add(e),e(),()=>this.syncObservers.delete(e)}notifySnapshotDelivered(){this.syncScheduled||this.syncObservers.size===0||(this.syncScheduled=!0,queueMicrotask(()=>{this.syncScheduled=!1;for(const e of[...this.syncObservers])e()}))}}const oo=new WeakMap;function Nr(t){let e=oo.get(t);return e||(e=new ig,oo.set(t,e)),e}function us(t,e,r){return st(t,qt("reference",e)),fi(t,e,r),t}function xg(t,...e){const r=cr(t),n=St in t,s=n?void 0:Oi(t),i=Pr(r);if(n){if(e.length===0)throw new TypeError("doc(db, path) requires at least one path segment.");const d=e.join("/"),l=i.doc(d),f=Rr(l,r,y=>y.doc(d));return us(f,d,r)}const a=ur(t),o=e.length===0?a.doc():a.doc(e.join("/")),c=o.path,u=Rr(o,r,d=>d.doc(c));if(s){const d=du(u,r,s);return us(d,c,r)}return us(u,c,r)}function Ig(t,...e){const r=cr(t),n=St in t;if(e.length===0)throw new TypeError("collection() requires at least one path segment.");if(n){const c=e.join("/"),u=Pr(r).collection(c);return Rr(u,r,d=>d.collection(c))}const s=ur(t),i=e.join("/"),a=s.collection(i),o=a.path;return Rr(a,r,c=>c.collection(o))}function ag(t){return t instanceof Error&&"code"in t&&typeof t.code=="string"}function og(t){if(t instanceof ir||!ag(t))return t;const e={};t.denialContext!==void 0&&(e.denialContext=t.denialContext),t.remediation!==void 0&&(e.remediation=t.remediation);const r=new ir(t.code,t.message,Object.keys(e).length===0?void 0:e);return t.denialContext!==void 0&&Object.assign(r,{denialContext:t.denialContext}),t.remediation!==void 0&&Object.assign(r,{remediation:t.remediation}),r}async function zn(t){try{return await t()}catch(e){throw og(e)}}async function kg(t,e,r){const n=cr(t),s=Oi(t),i=s?s.toFirestore(e):e;return Nr(n).runWrite(()=>zn(()=>Ei(n,t).set(i,r)),t.path)}async function Eg(t,e){const r=cr(t);return Nr(r).runWrite(()=>zn(()=>Ei(r,t).update(e)),t.path)}async function Og(t){const e=cr(t);return Nr(e).runWrite(()=>zn(()=>Ei(e,t).delete()),t.path)}async function Cg(t,e){const r=cr(t),n=Oi(t),s=n?n.toFirestore(e):e,i=await Nr(r).runWrite(async()=>{const c=await zn(()=>Ym(r,t).add(s));return Nr(r).cachePath(c.path),c}),a=i.path,o=Rr(i,r,c=>c.doc(a));if(st(o,qt("reference",a)),fi(o,a,r,o),n){const c=du(o,r,n);return Sf(o,c),c}return o}function Tg(t,e){return Ke(t).deployRules(e)}function Rg(t,e){const r=Ke(t);return r.seed({rules:r.getRules(),documents:e})}function Ng(t){return Ke(t).snapshot()}function Fg(t,e={}){const r=e.recentEventLimit??10,n=Ke(t),s=n.getRules(),i=s?Ss(s):{warnings:[]},a=i.warnings.map(S=>({rule:S.rule,severity:S.severity,message:S.message})),o={errors:0,warnings:0,info:0};for(const S of i.warnings)S.severity==="error"?o.errors++:S.severity==="warning"?o.warnings++:o.info++;const c=n.snapshot(),u={};for(const S of Object.keys(c)){const j=S.split("/")[0]??"";j&&(u[j]=(u[j]??0)+1)}const d=t.history(),l=d.filter(S=>S.kind==="request"),f=l.filter(S=>S.result==="deny"),y=l.slice(-r).map(S=>({path:String(S.path??""),method:String(S.method??""),result:String(S.result??""),auth:S.auth??null})),b=f.slice(-r).map(S=>({path:String(S.path??""),method:String(S.method??""),auth:S.auth??null,debugMessage:typeof S.debugMessage=="string"?S.debugMessage:void 0}));return{rules:{source:s,sizeBytes:new TextEncoder().encode(s).byteLength,isEmpty:s.trim().length===0,lint:{...o,findings:a}},documents:{totalCount:Object.keys(c).length,byCollection:u},events:{totalCount:d.length,recentDenials:b,recentRequests:y}}}export{mg as $,os as A,Og as B,hg as C,dg as D,Ag as E,Vr as F,Si as G,tf as H,lt as I,mh as J,Ir as K,Ft as L,kr as M,li as N,ph as O,wn as P,ui as Q,dt as R,ut as S,tr as T,xs as U,Mt as V,mn as W,hn as X,fg as Y,me as Z,pg as _,Rg as a,gg as a0,yg as a1,ng as a2,Ga as a3,tg as a4,hu as a5,se as a6,en as a7,oe as a8,vi as a9,bi as aa,wi as ab,Mr as ac,lg as ad,bt as ae,wr as af,Rt as ag,Ss as ah,Jm as ai,_g as aj,lu as ak,fi as al,Vc as am,Ei as an,wg as ao,vg as ap,kg as b,Ng as c,xg as d,bg as e,pl as f,rg as g,Ke as h,Fg as i,Oi as j,og as k,Pr as l,Rr as m,du as n,zc as o,Sg as p,Nr as q,ug as r,Tg as s,cr as t,ur as u,$r as v,ir as w,Ig as x,Cg as y,Eg as z};
1152
+ ${c}`:a;super(u),this.name="SandboxError",this.code=i,o!==void 0&&(this.denialContext=o),c!==void 0&&(this.remediation=c)}}function Ps(t){return t.kind==="request"||t.kind==="operation"}function Dr(t){const e=Object.freeze({...t.source}),r=Object.freeze({...t.authLens});return Object.freeze({source:e,authLens:r,...t.planId===void 0?{}:{planId:t.planId}})}function yi(t){const e=Dr(t);return{actor:e.source,authLens:e.authLens,operationContext:e,...e.planId===void 0?{}:{planId:e.planId}}}function Va(t){const e=t?.operationContext?.source;if(e&&e.kind!=="unattributed")return e;if(t?.actor&&t.actor.kind!=="unattributed")return t.actor}function bi(t,e){const r=t?.operationContext?.source??t?.actor,n=e?.operationContext?.source??e?.actor;return Dr({source:Va(t)??Va(e)??r??n??{kind:"unattributed"},authLens:e?.operationContext?.authLens??e?.authLens??t?.operationContext?.authLens??t?.authLens??{mode:"app-session"},...(t?.operationContext?.planId??t?.planId??e?.operationContext?.planId??e?.planId)===void 0?{}:{planId:t?.operationContext?.planId??t?.planId??e?.operationContext?.planId??e?.planId}})}function Wp(t){return bi(void 0,t)}function Cc(t){return t.rulesDisposition?t.rulesDisposition:t.kind==="operation"&&t.origin==="admin"||t.detail?.admin===!0?{kind:"bypassed",reason:"admin"}:t.result==="unsupported"?{kind:"not-evaluated",reason:"unsupported"}:t.kind==="operation"&&t.result==="error"?{kind:"not-evaluated",reason:"runtime-error"}:t.kind==="operation"&&t.result==="not-applicable"?{kind:"not-evaluated",reason:"not-a-rules-operation"}:t.result==="deny"?{kind:"evaluated",verdict:"deny"}:t.kind==="request"?{kind:"evaluated",verdict:"allow"}:t.rules?{kind:"evaluated",verdict:"allow"}:{kind:"not-evaluated",reason:"no-rules"}}function Hp(t){return t===null?null:Object.freeze({uid:t.uid,...t.token===void 0?{}:{token:Tc(t.token)}})}function Tc(t){const e={};for(const[r,n]of Object.entries(t))e[r]=Rc(n);return Object.freeze(e)}function Rc(t){return Array.isArray(t)?Object.freeze(t.map(Rc)):t&&typeof t=="object"?Tc(t):t}function lg(t){return Ps(t)?Object.freeze({id:t.id,at:t.at,eventKind:t.kind,service:t.kind==="request"?t.service??"firestore":t.service,method:t.method,...t.path===void 0?{}:{path:t.path},auth:Hp(t.auth),result:t.result,context:Wp(t),rules:Object.freeze({...Cc(t)})}):null}function Wa(t){return t===null?{mode:"anon"}:t.token===void 0?{mode:"as",uid:t.uid}:{mode:"as",uid:t.uid,token:t.token}}class Mr{sandbox;auth;constructor(e,r,n){this.sandbox=e,this.auth=r,this.operationContext=Dr(n??{source:{kind:"unattributed"},authLens:Wa(r)})}operationContext;withAuth(e){return $s(e),new Mr(this.sandbox,e,{source:this.operationContext.source,authLens:Wa(e),...this.operationContext.planId===void 0?{}:{planId:this.operationContext.planId}})}}function vi(t,e){return new Mr(t.sandbox,t.auth,e)}function $s(t){if(t===null)return;if(t===void 0)throw new se({code:"invalid-argument",message:"withAuth() requires an explicit AuthState argument.",remediation:["For anonymous (unauthenticated) access: withAuth(null)",'For authenticated access: withAuth({ uid: "someUid" })','For custom claims: withAuth({ uid: "someUid", token: { role: "admin" } })'].join(`
1153
+ `)});if(typeof t!="object")throw new se("invalid-argument","withAuth() expected null or an object with a `uid` field.");const e=t;if(typeof e.uid!="string"||e.uid.length===0)throw new se("invalid-argument","withAuth() requires `uid` to be a non-empty string.");if("token"in e&&e.token!==void 0&&(e.token===null||typeof e.token!="object"||Array.isArray(e.token)))throw new se("invalid-argument","withAuth() requires `token` (when present) to be a plain object.")}function Gp(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),r=e.length%4===0?"":"=".repeat(4-e.length%4),n=atob(e+r),s=new Uint8Array(n.length);for(let i=0;i<n.length;i++)s[i]=n.charCodeAt(i);return s}function Kp(t){const e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r}function wi(t){return qs(t,!0)}function qs(t,e){if(t===null||typeof t!="object")return t;if(Array.isArray(t)){const a=t.map(o=>qs(o,!1));return e&&st(a,Ta(t)),a}const r=t,n=a=>(e&&st(a,Ta(t)),a),s=(a,o)=>(Ht(a,Object.freeze(o),()=>a),n(a));if(r.__type__==="__vector__"&&Array.isArray(r.value)){const a=Object.freeze(r.value.slice());return s(new Wt(a),{type:"vector",values:a})}if(typeof r.__type=="string")switch(r.__type){case"timestamp":return s(new xe(r.seconds,r.nanos),{type:"timestamp",seconds:r.seconds,nanoseconds:r.nanos});case"bytes":{const a=Gp(r.base64);return s(new Be(a),{type:"bytes",values:Object.freeze(Array.from(a))})}case"latlng":return s(new rt(r.lat,r.lng),{type:"geo-point",latitude:r.lat,longitude:r.lng});case"duration":return n(new we(r.seconds,r.nanos));case"reference":return n(new jt(r.path));case"path":return n(new Xe(r.segments))}if(typeof r.type=="string")switch(r.type){case"firestore/timestamp/1.0":{const a=r.seconds,o=r.nanoseconds;return s(new xe(a,o),{type:"timestamp",seconds:a,nanoseconds:o})}case"firestore/bytes/1.0":{const a=Kp(r.bytes);return s(new Be(a),{type:"bytes",values:Object.freeze(Array.from(a))})}case"firestore/geoPoint/1.0":return s(new rt(r.latitude,r.longitude),{type:"geo-point",latitude:r.latitude,longitude:r.longitude})}const i={};for(const[a,o]of Object.entries(r))i[a]=qs(o,!1);return n(i)}class Ur extends Error{constructor(e){super(e),this.name="PersistenceSchemaError"}}function Zp(t){let e;try{e=JSON.parse(t)}catch(s){throw new Ur(`Persisted blob is not valid JSON: ${s.message}`)}if(typeof e!="object"||e===null)throw new Ur("Persisted blob is not an object");if(e.version!==1&&e.version!==2)throw new Ur(`Persisted blob has version ${String(e.version)}, expected 1 or 2`);if(typeof e.firestore!="object"||e.firestore===null)throw new Ur("Persisted blob has no firestore field");const r={};for(const[s,i]of Object.entries(e.firestore))r[s]=wi(i);const n=e.services!==void 0&&typeof e.services=="object"&&e.services!==null?e.services:{};return{firestore:r,services:n}}const Jp=3,Qp=256,Us="meta";function Yp(t){let e=2166136261;for(let r=0;r<t.length;r++)e^=t.charCodeAt(r),e=e+((e<<1)+(e<<4)+(e<<7)+(e<<8)+(e<<24))>>>0;return(e%Qp).toString(16).padStart(2,"0")}function Xp(t){return JSON.parse(JSON.stringify(t))}function Nc(t){const e=JSON.stringify(t);let r=2166136261;for(let n=0;n<e.length;n++)r^=e.charCodeAt(n),r=Math.imul(r,16777619)>>>0;return r}function Fc(t,e,r){const n=new Map;n.set(Us,{version:Jp,savedAt:r,services:e});for(const[s,i]of Object.entries(t)){const a=Yp(s);let o=n.get(a);o||(o={docs:{}},n.set(a,o)),o.docs[s]=Xp(i)}for(const[s,i]of n)s!==Us&&(i.checksum=Nc(i.docs));return n}const Lc="pyric-v3-records";function dg(t){return JSON.stringify({format:Lc,records:Object.fromEntries(t)})}function hg(t){let e;try{e=JSON.parse(t)}catch{return new Map}const r=e;return r&&typeof r=="object"&&r.format===Lc&&typeof r.records=="object"&&r.records!==null?new Map(Object.entries(r.records)):jc(t)??new Map}function jc(t){let e;try{e=Zp(t)}catch{return null}return Fc(e.firestore,e.services,0)}function em(t){const e={};let r={};for(const[n,s]of t){if(n===Us){const a=s;a&&typeof a.services=="object"&&a.services!==null&&(r=a.services);continue}const i=s;if(!(!i||typeof i.docs!="object"||i.docs===null)){if(typeof i.checksum=="number"&&Nc(i.docs)!==i.checksum){console.warn(`[sandbox/persistence] checksum mismatch for bucket '${n}'; skipping corrupt bucket`);continue}for(const[a,o]of Object.entries(i.docs))e[a]=wi(o)}}return{firestore:e,services:r}}const sr="snapshots";function Ha(){const t=new Map,e=r=>{let n=t.get(r);return n||(n=new Map,t.set(r,n)),n};return{async getRecord(r,n){const s=t.get(r)?.get(n);return s===void 0?null:structuredClone(s)},async listRecords(r){return[...t.get(r)?.keys()??[]]},async putRecords(r,n){const s=e(r);for(const[i,a]of n)s.set(i,structuredClone(a))},async deleteRecords(r,n){const s=t.get(r);if(s)for(const i of n)s.delete(i)},async clear(r){t.delete(r)}}}function Dc(t){return new Promise((e,r)=>{const n=indexedDB.open(t,1);n.onupgradeneeded=()=>{const s=n.result;s.objectStoreNames.contains(sr)||s.createObjectStore(sr)},n.onsuccess=()=>e(n.result),n.onerror=()=>r(n.error??new Error(`Failed to open IndexedDB '${t}'`)),n.onblocked=()=>r(new Error(`IndexedDB open blocked for '${t}'`))})}function ns(t,e,r){return Dc(t).then(n=>new Promise((s,i)=>{const a=n.transaction(sr,e),o=a.objectStore(sr),c=r(o);let u=null;c&&(c.onsuccess=()=>{u=c.result??null},c.onerror=()=>i(c.error)),a.oncomplete=()=>{n.close(),s(u)},a.onerror=()=>{n.close(),i(a.error)},a.onabort=()=>{n.close(),i(a.error??new Error("IndexedDB transaction aborted"))}}))}function Ga(t,e){return Dc(t).then(r=>new Promise((n,s)=>{const i=r.transaction(sr,"readwrite");e(i.objectStore(sr)),i.oncomplete=()=>{r.close(),n()},i.onerror=()=>{r.close(),s(i.error)},i.onabort=()=>{r.close(),s(i.error??new Error("IndexedDB transaction aborted"))}}))}function tm(){if(typeof indexedDB>"u")throw new Error('IndexedDB is not available in this environment. Use { backend: "memory" } or supply an injectedBackend.');return{async getRecord(t,e){return await ns(t,"readonly",n=>n.get(e))??null},async listRecords(t){return(await ns(t,"readonly",r=>r.getAllKeys())??[]).map(r=>String(r))},async putRecords(t,e){await Ga(t,r=>{for(const[n,s]of e)r.put(s,n)})},async deleteRecords(t,e){await Ga(t,r=>{for(const n of e)r.delete(n)})},async clear(t){await ns(t,"readwrite",e=>e.clear())},async estimate(){if(typeof navigator>"u"||!navigator.storage?.estimate)return null;const t=await navigator.storage.estimate();return{usage:t.usage??0,quota:t.quota??0}}}}const rm=250,Ka="pyric:sandbox:auth-session";function ss(t){return t==="auth"||t==="auth-session:[DEFAULT]"?Ka:`${Ka}:${encodeURIComponent(t)}`}function Mc(t){const e=JSON.stringify(t);let r=2166136261;for(let n=0;n<e.length;n++)r^=e.charCodeAt(n),r=Math.imul(r,16777619)>>>0;return r}function nm(t){if(t&&typeof t=="object"){if(t.name==="QuotaExceededError")return!0;const e=t.message;if(typeof e=="string"&&/quota/i.test(e))return!0}return!1}function sm(t){return t.injectedBackend?t.injectedBackend:(t.backend??"indexedDB")==="memory"||typeof indexedDB>"u"?Ha():tm()}async function im(t,e){const r={...e,flushIntervalMs:e.flushIntervalMs??rm,backend:e.backend??"indexedDB"},n=sm(r),s=new Map,i=await am(t,n,r.key,s);let a=null,o=!1;const c=new Map,u=async()=>{if(o)return;const _=t.snapshot(),v=Fc(_.firestore,_.services,Date.now()),O=new Map,A=new Map;for(const[p,g]of v){const m=Mc(g);A.set(p,m),s.get(p)!==m&&O.set(p,g)}const h=[...s.keys()].filter(p=>!v.has(p));O.size>0&&await n.putRecords(r.key,O),h.length>0&&await n.deleteRecords(r.key,h),s.clear();for(const[p,g]of A)s.set(p,g)};let d=Promise.resolve();const l=()=>(a&&(clearTimeout(a),a=null),d=d.then(u,u),d),f=()=>{o||a||(a=setTimeout(()=>{a=null,l().catch(_=>{if(nm(_)){console.warn("[sandbox/persistence] storage quota exceeded; recent changes are kept in memory only. Free storage or reduce sandbox data to persist them.");return}console.warn("[sandbox/persistence] auto-flush failed, will retry:",_),f()})},r.flushIntervalMs))},y=(_,v)=>{if(!v.subscribe||c.has(_))return;const O=v.subscribe(()=>{f()});c.set(_,O)},b=new Map,S=new Map,j=(_,v)=>{if(!r.sessionStorage)return;const{local:O,session:A}=r.sessionStorage,h=ss(_),p=v.currentUid(),g=v.mode();if(p===null||g==="NONE"){O.removeItem(h),A.removeItem(h);return}const m=JSON.stringify({uid:p});g==="LOCAL"?(A.removeItem(h),O.setItem(h,m)):(O.removeItem(h),A.setItem(h,m))},T=_=>{if(!r.sessionStorage)return null;const v=ss(_);for(const[O,A]of[["LOCAL",r.sessionStorage.local],["SESSION",r.sessionStorage.session]]){const h=A.getItem(v);if(h)try{const p=JSON.parse(h);if(typeof p?.uid=="string")return{uid:p.uid,mode:O}}catch{A.removeItem(v)}}return null},L=_=>{if(!r.sessionStorage)return;const v=ss(_);r.sessionStorage.local.removeItem(v),r.sessionStorage.session.removeItem(v)},k=(_,v,O)=>{if(O.session)try{O.session.restore(v.uid,v.mode),S.delete(_)}catch(A){console.warn(`[sandbox/persistence] session restore for uid '${v.uid}' failed — clearing stored session:`,A),L(_),S.delete(_)}},$=(_,v)=>{if(!r.sessionStorage||!v.session||b.has(_))return;const O=v.session;b.set(_,O.subscribe(()=>j(_,O)))},V=(_,v)=>{if(!v.session)return;const O=S.get(_)??T(_);O&&k(_,O,v)};if(t instanceof xt){for(const[_,v]of t.getServiceRegistry())y(_,v),V(_,v),$(_,v);t.setServiceRegistrationHook((_,v)=>{if(i!==null&&_ in i)try{v.restore(i[_])}catch(A){console.warn(`[sandbox/persistence] late-restore for service '${_}' failed:`,A)}const O=T(_);O&&S.set(_,O),V(_,v),y(_,v),$(_,v),f()}),t.setServiceUnregistrationHook(_=>{c.get(_)?.(),c.delete(_),b.get(_)?.(),b.delete(_),S.delete(_),f()})}const w=t.onEvent(_=>{om(_)&&f()}),x=()=>{l().catch(()=>{})};return typeof window<"u"&&window.addEventListener("beforeunload",x),{options:r,flush:l,async clear(){a&&(clearTimeout(a),a=null),await n.clear(r.key),s.clear()},dispose(){if(!o){o=!0,a&&(clearTimeout(a),a=null),w();for(const _ of c.values())_();c.clear();for(const _ of b.values())_();b.clear(),t instanceof xt&&(t.setServiceRegistrationHook(null),t.setServiceUnregistrationHook(null)),typeof window<"u"&&window.removeEventListener("beforeunload",x)}}}}async function am(t,e,r,n){let s;try{s=await e.listRecords(r)}catch(d){return console.warn("[sandbox/persistence] backend list failed:",d),null}if(s.length===0)return null;const i=[];for(const d of s)try{const l=await e.getRecord(r,d);l!==null&&i.push([d,l])}catch(l){console.warn(`[sandbox/persistence] failed to read persisted record '${d}':`,l)}const a=[],o=[];let c=null;for(const[d,l]of i)if(typeof l=="string"){const f=jc(l);f&&(o.push(d),c=f)}else a.push([d,l]);if(c){try{await e.putRecords(r,c),o.length>0&&await e.deleteRecords(r,o)}catch(d){console.warn("[sandbox/persistence] v2 migration write failed:",d)}for(const[d,l]of c)a.push([d,l])}for(const[d,l]of a)n.set(d,Mc(l));const u=em(a);for(const[d,l]of Object.entries(u.firestore))t.admin.setDocument(d,l);if(t instanceof xt){const d=t.getServiceRegistry();for(const[l,f]of Object.entries(u.services)){const y=d.get(l);if(y)try{y.restore(f)}catch(b){console.warn(`[sandbox/persistence] service '${l}' restore failed — Firestore state is intact; auth users may need to be re-created:`,b)}}}return u.services}function om(t){return t.kind==="write"||t.kind==="session_boundary"}function cm(t){return typeof t=="object"&&t!==null&&typeof t.kind=="string"&&typeof t.origin=="string"}let um=0;function lm(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`tab-${crypto.randomUUID()}`:`tab-${++um}-${typeof performance<"u"?performance.now().toFixed(3):String(Date.now())}`}function dm(t,e={}){let r,n=!1;if(e.channel)r=e.channel,n=!1;else if(typeof BroadcastChannel<"u")r=new BroadcastChannel("pyric:tabsync"),n=!0;else return()=>{};const s=e.originId??lm();let i=!1,a=!1;const o=t.onEvent(l=>{if(l.kind!=="write"||i)return;const f={kind:"write",origin:s,event:l};r.postMessage(f)}),c=l=>{if(!cm(l.data))return;const f=l.data;if(f.origin!==s){if(f.kind==="write")d(f.event);else if(f.kind==="hello"){const y={kind:"state",origin:s,to:f.origin,snapshot:t.snapshot()};r.postMessage(y)}else if(f.kind==="state"){if(f.to!==s||a)return;if(Object.keys(Ke(t).snapshot()).length>0){a=!0;return}i=!0;try{for(const[b,S]of Object.entries(f.snapshot.firestore))t.admin.setDocument(b,S)}finally{i=!1}a=!0}}};r.addEventListener("message",c);const u={kind:"hello",origin:s};return r.postMessage(u),()=>{o(),r.removeEventListener("message",c),n&&r.close()};function d(l){i=!0;try{if(l.method==="delete")t.admin.deleteDocument(l.path);else{const f=l.nextState;f!=null&&t.admin.setDocument(l.path,f)}}finally{i=!1}}}function hm(t,e){const r={...t};r.service=t.service??e?.service??"firestore";const s="detail"in t&&t.detail?.admin===!0&&t.operationContext===void 0&&t.authLens===void 0?{...t,authLens:{mode:"admin"}}:t,i=Ps(r)||t.operationContext!==void 0?bi(e,s):fm(t,e);return r.operationContext=i,r.actor=i.source,r.authLens=i.authLens,i.planId!==void 0&&(r.planId=i.planId),e?.activity!==void 0&&(r.activity={...r.activity,...e.activity}),Ps(r)&&(r.rulesDisposition=Object.freeze({...Cc(r)})),r}function fm(t,e){return Dr({source:t.actor??t.operationContext?.source??e?.actor??e?.operationContext?.source??{kind:"unattributed"},authLens:t.authLens??t.operationContext?.authLens??e?.authLens??e?.operationContext?.authLens??{mode:"app-session"},...(t.planId??t.operationContext?.planId??e?.planId??e?.operationContext?.planId)===void 0?{}:{planId:t.planId??t.operationContext?.planId??e?.planId??e?.operationContext?.planId}})}function pm(t,e){if(!t)return e;if(!e)return t;if(e.operationContext!==void 0)return Pc(t,e);if(!(t.operationContext!==void 0||t.actor!==void 0||t.authLens!==void 0||t.planId!==void 0||e.actor!==void 0||e.authLens!==void 0||e.planId!==void 0))return{...t,...e};const n=Dr({source:e.actor??t.operationContext?.source??t.actor??{kind:"unattributed"},authLens:e.authLens??t.operationContext?.authLens??t.authLens??{mode:"app-session"},...(e.planId??t.operationContext?.planId??t.planId)===void 0?{}:{planId:e.planId??t.operationContext?.planId??t.planId}});return{...t,...e,operationContext:n,actor:n.source,authLens:n.authLens,...n.planId===void 0?{}:{planId:n.planId}}}function Pc(t,e){if(!t)return e;if(!e)return t;if(!(t.operationContext!==void 0||t.actor!==void 0||t.authLens!==void 0||t.planId!==void 0||e.operationContext!==void 0||e.actor!==void 0||e.authLens!==void 0||e.planId!==void 0))return{...t,...e};const n=bi(t,e);return{...t,...e,operationContext:n,actor:n.source,authLens:n.authLens,...n.planId===void 0?{}:{planId:n.planId}}}let mm=1;function Lt(){const t=(mm++).toString(36),e=Math.random().toString(36).slice(2,7);return`sbe-${t}-${e}`}class xt{_env;eventSubs=new Set;envUnsubs=[];dispatchedCount=0;eventHistory=[];ambientProvenance;_currentUser=null;currentUserSubs=new Set;persistence=null;enablePersistencePromise=null;serviceRegistry=new Map;_onServiceRegistered=null;_onServiceUnregistered=null;constructor(e){this._env=e,this.attachToEnv()}static createRoot(){return new xt(new za)}getEnv(){return this._env}withAuth(e){return $s(e),new Mr(this,e)}attachToEnv(){this.envUnsubs.push(this._env.onRequest(e=>{this.emitEvent(e)})),this.envUnsubs.push(this._env.onWrite(e=>{this.emitEvent(e)})),this.envUnsubs.push(this._env.onSnapshotDelivery(e=>this.emitEvent(e))),this.envUnsubs.push(this._env.onSnapshotSuppressed(e=>this.emitEvent(e))),this.envUnsubs.push(this._env.onListenerLifecycle(e=>this.emitEvent(e))),this.envUnsubs.push(this._env.onSnapshotError((e,r,n)=>{const s={kind:"listener_errored",id:Lt(),at:Date.now(),listenerId:n,target:r.kind==="doc"?{kind:"doc",path:r.path}:{kind:"query",collection:r.collection},auth:e.request?.auth??null,error:{code:"permission-denied",message:e.message}};this.emitEvent(s)}))}emitEvent(e,r){const n=Pc(this.ambientProvenance,r);this.dispatch(hm(e,n))}runWithProvenance(e,r){const n=this.ambientProvenance;this.ambientProvenance=pm(n,e);try{return r()}finally{this.ambientProvenance=n}}dispatch(e){if(this.eventHistory.push(e),this.dispatchedCount++,this.eventSubs.size!==0)for(const r of this.eventSubs)try{const n=r(e);n&&typeof n.then=="function"&&n.catch(()=>{})}catch{}}emitInternal(e,r){this.emitEvent(e,r)}onEvent(e){return this.eventSubs.add(e),()=>{this.eventSubs.delete(e)}}history(){return[...this.eventHistory]}primeEventHistory(e){return this.eventHistory.length>0||e.length===0?0:(this.eventHistory.push(...e),e.length)}get admin(){return{getDocument:e=>this._env.getDocument(e),listDocuments:e=>this._env.listDocuments(e),setDocument:(e,r)=>this._env.adminSetDocument(e,r),deleteDocument:e=>this._env.adminDeleteDocument(e)}}reset(){const e={kind:"session_boundary",id:Lt(),at:Date.now(),phase:"reset",priorOpCount:this.dispatchedCount};this.emitEvent(e),this.eventHistory=[],this._currentUser!==null&&(this._currentUser=null,this.notifyCurrentUserSubs(null));for(const r of this.envUnsubs)r();this.envUnsubs=[],this._env.dispose(),this._env=new za,this.attachToEnv()}async resetAll(){this.reset();const e=[],r=[];for(const[n,s]of this.serviceRegistry)s.reset&&r.push(Promise.resolve().then(()=>s.reset()).catch(i=>{e.push(`${n}: ${i instanceof Error?i.message:String(i)}`)}));return await Promise.all(r),{errors:e}}dispose(){const e={kind:"session_boundary",id:Lt(),at:Date.now(),phase:"dispose",priorOpCount:this.dispatchedCount};this.emitEvent(e);for(const r of this.envUnsubs)r();this.envUnsubs=[],this._env.dispose(),this.persistence&&(this.persistence.dispose(),this.persistence=null),this.serviceRegistry.clear(),this._onServiceRegistered=null,this._onServiceUnregistered=null,this.eventSubs.clear(),this.currentUserSubs.clear()}snapshot(){const e={};for(const[r,n]of this.serviceRegistry)e[r]=n.snapshot();return{firestore:this._env.snapshot(),services:e}}loadSnapshot(e){this.reset();for(const[r,n]of Object.entries(e.firestore))this._env.adminSetDocument(r,n);for(const[r,n]of this.serviceRegistry)if(r in e.services)try{n.restore(e.services[r])}catch(s){console.warn(`[sandbox] loadSnapshot: service '${r}' restore failed — Firestore is intact; that service's state may be incomplete:`,s)}}get currentUser(){return this._currentUser}set currentUser(e){$s(e),!gm(this._currentUser,e)&&(this._currentUser=e,this.notifyCurrentUserSubs(e))}onCurrentUserChanged(e){return this.currentUserSubs.add(e),()=>{this.currentUserSubs.delete(e)}}notifyCurrentUserSubs(e){if(this._env.reevaluateLiveListeners(e),this.currentUserSubs.size!==0)for(const r of this.currentUserSubs)try{const n=r(e);n&&typeof n.then=="function"&&n.catch(()=>{})}catch{}}async enablePersistence(e){if(this.persistence){if(this.persistence.options.key!==e.key)throw new se("failed-precondition",`Persistence already enabled with key '${this.persistence.options.key}'; cannot re-enable with key '${e.key}'. Dispose and recreate the sandbox.`);return}if(this.enablePersistencePromise)return this.enablePersistencePromise;this.enablePersistencePromise=(async()=>{const r=await im(this,e);this.persistence=r})();try{await this.enablePersistencePromise}finally{this.enablePersistencePromise=null}}enableTabSync(e){return dm(this,e)}async flush(){if(!this.persistence)throw new se("failed-precondition","flush() called before enablePersistence()");await this.persistence.flush()}async clearPersistence(){this.persistence&&await this.persistence.clear()}registerPersistableService(e,r){if(this.serviceRegistry.has(e))throw new se("failed-precondition",`registerPersistableService: a service named '${e}' is already registered on this sandbox. Each service name must be unique — the auth package registers 'auth' exactly once per sandbox.`);return this.serviceRegistry.set(e,r),this._onServiceRegistered&&this._onServiceRegistered(e,r),()=>{this.serviceRegistry.get(e)===r&&(this.serviceRegistry.delete(e),this._onServiceUnregistered?.(e))}}setServiceRegistrationHook(e){this._onServiceRegistered=e}setServiceUnregistrationHook(e){this._onServiceUnregistered=e}getServiceRegistry(){return this.serviceRegistry}}function gm(t,e){if(t===e)return!0;if(t===null||e===null||t.uid!==e.uid)return!1;const r=t.token===void 0?void 0:JSON.stringify(t.token),n=e.token===void 0?void 0:JSON.stringify(e.token);return r===n}function Ke(t){if(!(t instanceof xt))throw new se("invalid-argument","Sandbox handle was not produced by initializeSandbox(); custom Sandbox implementations are not supported.");return t.getEnv()}function fg(t,e,r){if(!(t instanceof xt))throw new se("invalid-argument","Sandbox handle was not produced by initializeSandbox(); custom Sandbox implementations are not supported.");t.emitInternal(e,r)}function pg(t){return{kind:"service_mutation",id:Lt(),at:Date.now(),...t}}function mg(t){const{at:e,...r}=t;return{kind:"operation",id:Lt(),at:e??Date.now(),...r}}function gg(t){const{at:e,...r}=t;return{kind:"commit",id:Lt(),at:e??Date.now(),...r}}function yg(t){const{at:e,...r}=t;return{kind:"listener",id:Lt(),at:e??Date.now(),...r}}function bg(){return xt.createRoot()}const ym=Symbol.for("pyric.remote.sandbox");function Si(t){return t!=null&&t[ym]===!0}function Cr(t){return t.replace(/^\/+|\/+$/g,"").split("/")}function $c(t){return Cr(t).length%2===0&&Cr(t).length>0}function _i(t){return Cr(t).length%2===1}function qn(t){const e=Cr(t);return e[e.length-1]??""}function qc(t){return Cr(t).slice(0,-1).join("/")}function Uc(t,e){const r=e!==void 0,n=r?jr(e):void 0;return{id:t.id,ref:t,exists:r,data:()=>r?n:void 0,get:s=>or(n,s)}}const Za=new WeakMap;let bm=1;function Ja(t){let e=Za.get(t);return e===void 0&&(e=bm++,Za.set(t,e)),e}function On(t){if(t===null||typeof t=="boolean")return t;if(typeof t=="string")return Hf(t);if(typeof t>"u")return{type:"undefined"};if(typeof t=="bigint")return qt("bigint",t.toString());if(typeof t=="number"){const r=Number.isNaN(t)?"NaN":t===1/0?"Infinity":t===-1/0?"-Infinity":Object.is(t,-0)?"-0":String(t);return qt("number",r)}if(typeof t!="object"&&typeof t!="function")return{type:typeof t,value:String(t)};const e=Kf(t);if(e!==void 0)return e;try{if(Array.isArray(t))return{type:"array",id:Ja(t)}}catch{}return{type:"opaque-object",id:Ja(t)}}function gt(t){return new ce({code:"invalid-argument",message:t})}function Bs(t,e,r,n=!1,s=!1){if(t===null||typeof t=="string"||typeof t=="boolean")return{comparison:t,execution:t};if(typeof t=="number")return{comparison:t,execution:t};if(typeof t>"u"||typeof t=="bigint"||typeof t=="function"||typeof t=="symbol")throw gt(`Unsupported Firestore query value: ${typeof t}.`);if(typeof t!="object")throw gt("Unsupported Firestore query value.");const i=ac(t);if(i!==void 0){const o=vf(t);if(o!==void 0&&r!==void 0&&o!==r)throw gt("Document reference belongs to a different Firestore database.");return{comparison:{type:"registered-firestore-value",value:i},execution:wf(t)}}if(t instanceof Date){const o=t.getTime();if(!Number.isFinite(o))throw gt("Invalid Date query value.");const c=Math.floor(o/1e3),u=Object.freeze({seconds:c,nanoseconds:Math.floor((o-c*1e3)*1e6)}),d={type:"timestamp",...u};return Ht(u,d,()=>Object.freeze({...u})),{comparison:{type:"registered-firestore-value",value:d},execution:u}}if(t instanceof Uint8Array){const o=t.slice();return{comparison:{type:"bytes",values:Array.from(o)},execution:o}}if(e.has(t))throw gt("Cyclic query operands are not Firestore values.");const a=Object.getPrototypeOf(t);if(a!==Object.prototype&&a!==null&&!Array.isArray(t))throw gt("Firestore query maps must be plain objects.");e.add(t);try{if(Array.isArray(t)){if(s&&!n)throw gt("Nested arrays are not supported.");const u=t.map(l=>Bs(l,e,r,n,!0)),d=u.map(l=>l.execution);return st(d,On(t)),{comparison:{type:"array",values:u.map(l=>l.comparison)},execution:d}}const o=Object.keys(t).sort().map(u=>({key:u,captured:Bs(t[u],e,r,n,!1)})),c=Object.fromEntries(o.map(({key:u,captured:d})=>[u,d.execution]));return st(c,On(t)),{comparison:{type:"map",entries:o.map(({key:u,captured:d})=>[u,d.comparison])},execution:c}}finally{e.delete(t)}}function Bc(t,e,r=!1){try{const n=Bs(t,new Set,e,r);return Object.freeze({kind:"canonical",value:n.comparison,executionValue:n.execution})}catch(n){if(n instanceof ce)throw n;const s=n instanceof Error?n.message:String(n);throw gt(`Invalid Firestore query value: ${s}`)}}function zc(t,e){return Ge(t.value,e.value)}function Kr(t,e){if(t.kind==="where"){const r="comparisonValue"in t?t.comparisonValue:Bc(t.value,e,t.op==="in"||t.op==="not-in");return Object.freeze({kind:"where",field:t.field,op:t.op,value:r.executionValue,comparisonValue:r})}return Object.freeze({kind:t.kind,filters:Object.freeze(t.filters.map(r=>Kr(r,e)))})}function Br(t,e,r,n){const s=t.map(i=>Bc(i,n));return Object.freeze({values:Object.freeze(s.map(i=>i.executionValue)),comparisonValues:Object.freeze(s),inclusive:e,fromSnapshot:r})}function Vc(t,e){return t.length!==e.length?!1:t.every((r,n)=>{const s=e[n];return r.kind!==s.kind?!1:r.kind==="where"&&s.kind==="where"?r.field===s.field&&r.op===s.op&&zc(r.comparisonValue,s.comparisonValue):r.kind!=="where"&&s.kind!=="where"&&Vc(r.filters,s.filters)})}function Qa(t,e){return t===void 0||e===void 0?t===e:t.inclusive===e.inclusive&&t.comparisonValues.length===e.comparisonValues.length&&t.comparisonValues.every((r,n)=>zc(r,e.comparisonValues[n]))}function vm(t,e){return t.kind!==e.kind?!1:t.kind==="collection"&&e.kind==="collection"?t.path===e.path:t.kind==="collection-group"&&e.kind==="collection-group"&&t.collectionId===e.collectionId}function Wc(t){return t.kind==="where"?Object.freeze({kind:t.kind,field:t.field,op:t.op,value:t.value}):Object.freeze({kind:t.kind,filters:Object.freeze(t.filters.map(Wc))})}function Ya(t){if(t!==void 0)return Object.freeze({values:t.values,inclusive:t.inclusive,fromSnapshot:t.fromSnapshot})}function wm(t,e){return Vc(t.filters,e.filters)&&t.orders.length===e.orders.length&&t.orders.every((r,n)=>{const s=e.orders[n];return r.field===s.field&&r.direction===s.direction})&&t.limitCount===e.limitCount&&t.limitFromEnd===e.limitFromEnd&&Qa(t.start,e.start)&&Qa(t.end,e.end)}const Hc="__name__";function Xa(t,e){const r=t.data();if(r===void 0)throw new ce({code:"not-found",message:`Snapshot-based cursors require an existing document — got an empty snapshot for ${t.id??"<unknown>"}.`});return e.map(n=>n.field===Hc?t.ref:r[n.field])}class Tr{env;auth;collectionPath;clauses;orders;limitCount;limitFromEnd;start;end;bypassRules;documentRef;constructor(e){this.env=e.env,this.auth=e.auth,this.collectionPath=e.collectionPath,this.documentRef=e.documentRef,this.clauses=Object.freeze((e.clauses??[]).map(r=>Kr(r))),this.orders=Object.freeze((e.orders??[]).map(r=>Object.freeze({...r}))),this.limitCount=e.limitCount,this.limitFromEnd=e.limitFromEnd??!1,this.start=e.start===void 0?void 0:Object.freeze({...e.start,values:Object.freeze(e.start.comparisonValues.map(r=>r.executionValue)),comparisonValues:e.start.comparisonValues}),this.end=e.end===void 0?void 0:Object.freeze({...e.end,values:Object.freeze(e.end.comparisonValues.map(r=>r.executionValue)),comparisonValues:e.end.comparisonValues}),this.bypassRules=e.bypassRules??!1}where(e,r,n){return this.clone({clauses:[...this.clauses,Kr({kind:"where",field:e,op:r,value:n})]})}applyFilter(e){return this.clone({clauses:[...this.clauses,Kr(e)]})}orderBy(e,r="asc"){return this.clone({orders:[...this.orders,{field:e,direction:r}]})}limit(e){return this.clone({limitCount:e,limitFromEnd:!1})}limitToLast(e){return this.clone({limitCount:e,limitFromEnd:!0})}startCursor(e,r){return this.clone({start:Br(this.normalizeExplicitCursorValues(e),r,!1)})}endCursor(e,r){return this.clone({end:Br(this.normalizeExplicitCursorValues(e),r,!1)})}startCursorFromSnapshot(e,r){return this.clone({start:Br(Xa(e,this.normalizedOrders()),r,!0)})}endCursorFromSnapshot(e,r){return this.clone({end:Br(Xa(e,this.normalizedOrders()),r,!0)})}isStructurallyEqual(e){return e instanceof Tr?this.env===e.env&&this.bypassRules===e.bypassRules&&vm(this.queryScope(),e.queryScope())&&wm(this.comparableExecutionSpec(),e.comparableExecutionSpec()):!1}clone(e){return new Tr({env:this.env,auth:this.auth,collectionPath:this.collectionPath,documentRef:this.documentRef,clauses:e.clauses??this.clauses,orders:e.orders??this.orders,limitCount:"limitCount"in e?e.limitCount:this.limitCount,limitFromEnd:e.limitFromEnd??this.limitFromEnd,start:"start"in e?e.start:this.start,end:"end"in e?e.end:this.end,bypassRules:this.bypassRules})}queryScope(){return{kind:"collection",path:this.collectionPath}}readQueryRows(e){const r=e?.auth!==void 0?e.auth:this.auth;let n;try{n=this.env.runQuery({scope:this.queryScope(),auth:r,execution:this.executionSpec(),bypassRules:this.bypassRules,activityQuery:this.activityQuery()})}catch(s){const i=s?.simError;throw i?new ce(i):s}if(!n.allowed)throw new ce(n.error);return n.docs}activityQuery(){const e=n=>n.kind==="where"?{kind:"where",field:n.field,op:n.op,value:On(n.value)}:{kind:n.kind,filters:n.filters.map(e)},r=n=>n===void 0?null:{values:n.values.map(s=>On(s)),inclusive:n.inclusive,fromSnapshot:n.fromSnapshot};return{scope:this.activityScope(),filters:this.clauses.map(e),orderBy:this.orders.map(n=>({...n})),limit:this.limitCount??null,limitFromEnd:this.limitFromEnd,start:r(this.start),end:r(this.end)}}activityScope(){return{kind:"collection"}}normalizedOrders(){return xc(this.executionSpec())}normalizeExplicitCursorValues(e){const r=this.orders;return e.map((n,s)=>{if(r[s]?.field!==Hc)return n;if(typeof n!="string")throw new ce({code:"invalid-argument",message:"Expected a string for a document ID cursor value."});const i=n.includes("/")?n:`${this.collectionPath}/${n}`;return this.documentRef(i)})}executionSpec(){const e={filters:Object.freeze(this.clauses.map(Wc)),orders:this.orders,limitCount:this.limitCount,limitFromEnd:this.limitFromEnd,start:Ya(this.start),end:Ya(this.end)};return Object.freeze(e)}comparableExecutionSpec(){return{filters:this.clauses,orders:this.orders,limitCount:this.limitCount,limitFromEnd:this.limitFromEnd,start:this.start,end:this.end}}snapshotConstraints(){return Object.freeze({execution:this.executionSpec(),activityQuery:this.activityQuery()})}async get(e){const n=this.readQueryRows(e).map(s=>{const i=this.documentRef(s.path),a=jr(s.data);return{id:i.id,ref:i,exists:!0,data:()=>a,get:o=>or(a,o)}});return{size:n.length,empty:n.length===0,docs:n,forEach(s){n.forEach(s)}}}async aggregate(e,r){const n=this.readQueryRows(r),s={};for(const i of Object.keys(e))s[i]=_m(e[i],n);return{data:()=>s}}}function Sm(t,e){if(!e.includes("."))return t[e];let r=t;for(const n of e.split(".")){if(typeof r!="object"||r===null||Array.isArray(r))return;r=r[n]}return r}function _m(t,e){if(t.kind==="count")return e.length;let r=0,n=0;for(const s of e){const i=Sm(s.data,t.field);typeof i=="number"&&Number.isFinite(i)&&(r+=i,n++)}return t.kind==="sum"?r:n===0?null:r/n}function Kt(t,e){if(t.error)throw new ce(t.error);const r=t.debugMessages.length>0?t.debugMessages.join("; "):"(no debug message)";throw new ce(ee("permission-denied",`${e}: ${r}`))}class Am{env;auth;bypassRules;collectionRef;id;path;constructor(e,r,n,s=!1,i){this.env=e,this.auth=r,this.bypassRules=s,this.collectionRef=i,this.path=n,this.id=qn(n),st(this,qt("reference",n)),hi(this,n,e)}get parent(){return this.collectionRef(qc(this.path))}collection(e){return this.collectionRef(`${this.path}/${e}`)}async get(e){const r=this.env.execute({method:"get",path:this.path,auth:e?.auth!==void 0?e.auth:this.auth,bypassRules:this.bypassRules});r.allowed||Kt(r,"get denied");const n=r.data===void 0||r.data===null?void 0:r.data;return Uc(this,n)}async set(e,r){const n=r?.auth!==void 0?r.auth:this.auth;if(r?.mergeFields!==void 0){const i=r.mergeFields.map(u=>String(u)),o=this.env.getDocument(this.path)===null?"create":"update",c=this.env.execute({method:o,path:this.path,data:e,auth:n,merge:{mergeFields:i},bypassRules:this.bypassRules});c.allowed||Kt(c,`set denied (as ${o})`);return}if(r?.merge===!0){const a=this.env.getDocument(this.path)===null?"create":"update",o=this.env.execute({method:a,path:this.path,data:e,auth:n,merge:!0,bypassRules:this.bypassRules});o.allowed||Kt(o,`set denied (as ${a})`);return}const s=this.env.execute({method:"set",path:this.path,data:e,auth:n,bypassRules:this.bypassRules});s.allowed||Kt(s,"set denied")}async update(e,r){const n=this.env.execute({method:"update",path:this.path,data:e,auth:r?.auth!==void 0?r.auth:this.auth,bypassRules:this.bypassRules});n.allowed||Kt(n,"update denied")}async delete(e){const r=this.env.execute({method:"delete",path:this.path,auth:e?.auth!==void 0?e.auth:this.auth,bypassRules:this.bypassRules});r.allowed||Kt(r,"delete denied")}}function Cn(t,e,r,n){return new Am(t,e,r,n,s=>new Gc(t,e,s,n))}class Gc extends Tr{id;path;constructor(e,r,n,s=!1){super({env:e,auth:r,collectionPath:n,bypassRules:s,documentRef:i=>Cn(e,r,i,s)}),this.path=n,this.id=qn(n)}doc(e){const r=e??gi();return Cn(this.env,this.auth,`${this.path}/${r}`,this.bypassRules)}async add(e,r){const n=this.doc();return await n.set(e,r),n}}class Ai extends Tr{collectionId;constructor(e){super({...e,collectionPath:"",documentRef:r=>Cn(e.env,e.auth,r,e.bypassRules??!1)}),this.collectionId=e.collectionId}clone(e){return new Ai({env:this.env,auth:this.auth,collectionId:this.collectionId,clauses:e.clauses??this.clauses,orders:e.orders??this.orders,limitCount:"limitCount"in e?e.limitCount:this.limitCount,limitFromEnd:e.limitFromEnd??this.limitFromEnd,start:"start"in e?e.start:this.start,end:"end"in e?e.end:this.end,bypassRules:this.bypassRules})}queryScope(){return{kind:"collection-group",collectionId:this.collectionId}}activityScope(){return{kind:"collection-group"}}}class xm{env;auth;bypassRules;ops=[];constructor(e,r,n=!1){this.env=e,this.auth=r,this.bypassRules=n}set(e,r){const s=this.env.getDocument(e.path)===null?"create":"update";return this.ops.push({method:s,path:e.path,data:r}),this}update(e,r){return this.ops.push({method:"update",path:e.path,data:r}),this}delete(e){return this.ops.push({method:"delete",path:e.path}),this}async commit(e){if(this.ops.length===0)return;const r=this.env.batch(this.ops,e?.auth!==void 0?e.auth:this.auth,this.bypassRules);if(r.allowed)return;if(r.error)throw new ce(r.error);const s=r.results.find(i=>!i.allowed)?.debugMessages.join("; ")??"batch denied";throw new ce(ee("permission-denied",`batch failed: ${s}`))}}function Im(t){return typeof t.where=="function"}class km{simTx;constructor(e){this.simTx=e}async get(e){if(Im(e)){const s=await e.get();return s.size>0&&this.simTx.getAll(...s.docs.map(i=>i.ref.path)),s}const n=this.simTx.get(e.path).data();return Uc(e,n)}set(e,r){return this.simTx.set(e.path,r),this}update(e,r){return this.simTx.update(e.path,r),this}delete(e){return this.simTx.delete(e.path),this}}class Em{env;auth;bypassRules;provenance;constructor(e,r,n=!1,s){this.env=e,this.auth=r,this.bypassRules=n,this.provenance=s}collection(e){if(!_i(e))throw new ce(ee("invalid-argument",`collection path must have an odd number of segments: ${e}`));return new Gc(this.env,this.auth,e,this.bypassRules)}doc(e){if(!$c(e))throw new ce(ee("invalid-argument",`document path must have an even number of segments: ${e}`));return Cn(this.env,this.auth,e,this.bypassRules)}collectionGroup(e){if(e.length===0||e.includes("/"))throw new ce(ee("invalid-argument",`collection group id must be a single non-empty segment with no '/': ${e}`));return new Ai({env:this.env,auth:this.auth,collectionId:e,bypassRules:this.bypassRules})}batch(){return new xm(this.env,this.auth,this.bypassRules)}async runTransaction(e,r){let n;try{n=await this.env.transaction(s=>{const i=new km(s);return e(i)},{auth:r?.auth!==void 0?r.auth:this.auth,bypassRules:this.bypassRules,provenance:this.provenance,maxAttempts:r?.maxAttempts})}catch(s){throw s instanceof Ec?new ce(s.simError):s instanceof Oc?new ce(s.simError):s}if(!n.allowed){if(n.error)throw new ce(n.error);const i=n.writes.find(a=>!a.allowed)?.debugMessages.join("; ")??"transaction denied at commit";throw new ce(ee("permission-denied",`transaction failed: ${i}`))}return n.returnValue}}function Om(t,e){return new Em(t,e?.auth??null,e?.bypassRules??!1,e?.provenance)}const Kc=Symbol("pyric/sandbox/context"),Zc=Symbol("pyric/sandbox/bypassRules");let zs=null;function Cm(t){zs=t}function Tm(t){const e=t;return typeof e.path=="string"&&e.path.length>0||typeof e.collectionPath=="string"&&e.collectionPath.length>0}function Rm(t){const e=t.trim();if(!e)return[];const r=e.indexOf(": ");if(r!==-1){const s=e.slice(r+2).trim().split("; ").map(i=>i.trim()).filter(i=>i.length>0);if(s.length>0)return s}return[e]}function eo(t,e){if(!(t instanceof ce))return t;const r=t.code;if(r!=="permission-denied")return new se(r,t.message);const n={auth:e.auth,reasons:Rm(t.message)},s=t.simError;if(s?.request){const i=s.request;n.request={method:i.method,path:i.path,...i.resourceData?{resourceData:i.resourceData}:{}}}return s?.resource&&(n.resource={data:s.resource.data,exists:s.resource.exists}),s?.query&&(n.query=s.query),s?.remediation!==void 0?new se({code:r,message:t.message,denialContext:n,remediation:s.remediation}):new se(r,t.message,n)}function Tn(t,e,r=!1){return new Proxy(t,{get(n,s,i){if(s===Kc)return e;if(s===Zc)return r;if(s==="onSnapshot"&&zs!==null&&!(s in n)&&Tm(n))return(...o)=>zs(i,...o);const a=Reflect.get(n,s,i);return typeof a!="function"?a:function(...o){let c;try{const u=()=>a.apply(n,o);c=e.sandbox.runWithProvenance?.(yi(e.operationContext),u)??u()}catch(u){throw eo(u,e)}return c instanceof Promise?c.then(u=>u&&typeof u=="object"?Tn(u,e,r):u).catch(u=>{throw eo(u,e)}):c&&typeof c=="object"?Tn(c,e,r):c}}})}function Jc(t,e=!1){if(Si(t.sandbox))throw new Error("pyric/sandbox/admin-firestore: internal — a remote sandbox context reached the local engine builder; remote dispatch should have handled it. Please report this.");const r=()=>Om(Ke(t.sandbox),{auth:t.auth,bypassRules:e,provenance:yi(t.operationContext)});return{collection(n){return r().collection(n)},doc(n){return r().doc(n)},collectionGroup(n){return r().collectionGroup(n)},batch(){return r().batch()},runTransaction(n,s){return r().runTransaction(n,s)},setRules(n){return Ke(t.sandbox).deployRules(n)},seed(n){const s=Ke(t.sandbox);return s.seed({rules:s.getRules(),documents:n?.documents??{}})},snapshot(){return Ke(t.sandbox).snapshot()}}}function Vs(t){if(t instanceof se)return t;if(t!==null&&typeof t=="object"){const e=t;if(typeof e.code=="string"&&typeof e.message=="string"){const r=e.denialContext!==null&&typeof e.denialContext=="object"?e.denialContext:void 0;return new se(e.code,e.message,r)}}return t}function ht(t){return new se("invalid-argument",t)}async function Ze(t,e){try{return await t.sandbox.channel.op({...e,actAs:t.lens})}catch(r){throw Vs(r)}}const Nm=new Set(["serverTimestamp","increment","arrayUnion","arrayRemove","deleteField"]);function Fm(t){return t!==null&&typeof t=="object"&&typeof t.__type=="string"&&Nm.has(t.__type)}function Lm(t){switch(t.__type){case"serverTimestamp":return{__sentinel:"serverTimestamp"};case"increment":return{__sentinel:"increment",n:t.value};case"arrayUnion":return{__sentinel:"arrayUnion",values:t.values.map(pt)};case"arrayRemove":return{__sentinel:"arrayRemove",values:t.values.map(pt)};case"deleteField":return{__sentinel:"deleteField"}}}function pt(t){if(t===null||typeof t!="object")return t;if(Fm(t))return Lm(t);if(t instanceof bt)return t.toJSON();if(t instanceof Date)return bt.fromDate(t).toJSON();if(Array.isArray(t))return t.map(pt);const e=Object.getPrototypeOf(t);if(e!==Object.prototype&&e!==null){const n=t.toJSON;if(typeof n=="function")return n.call(t);throw ht(`remote Firestore: cannot serialize a ${e.constructor?.name??"class"} instance for the wire — use plain data, Timestamp, Date, or FieldValue sentinels.`)}const r={};for(const[n,s]of Object.entries(t))r[n]=pt(s);return r}function Ut(t){return pt(t)}function Ws(t){return wi(JSON.parse(t.json))}function Qc(t){return jr(Ws(t))}function Yc(t,e){const r=e.exists&&e.data?Qc(e.data):void 0;return{id:t.id,ref:t,exists:e.exists,data:()=>r,get:n=>or(r,n)}}function Xc(t,e){const r=e.docs.map(n=>{const s=n.path??n.id,i=Rn(t,s),a=n.data?Qc(n.data):{};return{id:i.id,ref:i,exists:!0,data:()=>a,get:o=>or(a,o)}});return{size:r.length,empty:r.length===0,docs:r,forEach(n){r.forEach(s=>n(s))}}}const xi=Symbol("pyric/sandbox/admin-firestore/remoteSnapshotRegistrar");function jm(t){if(t===null||typeof t!="object")return;const e=t[xi];return typeof e=="function"?e:void 0}let Hs=null;function Dm(t){Hs=t}function eu(...t){if(Hs===null)throw new se("failed-precondition","remote Firestore: onSnapshot is not wired yet — import pyric-admin/firestore (or pyric/sandbox/admin-firestore) before subscribing.");return Hs(this,...t)}function tu(t,e,r,n,s){const i=r.includeMetadataChanges!==!0;let a,o;try{o=t.sandbox.channel.subscribe({target:e,actAs:t.lens},c=>{if(!n)return;const u=c;if(Array.isArray(u.docs)){const d=u.docs.map(y=>({path:y.path??y.id,data:y.data?Ws(y.data):{}})),l=e.__ref==="query"?e.source.__ref==="group"?e.source.collectionId:e.source.path:e.__ref==="group"?e.collectionId:e.path,f=Qt({path:l},d,{excludesMetadataChanges:i},a);a=d,n(f)}else if(typeof u.id=="string"){const d=u.path??u.id,l=u.exists&&u.data?Ws(u.data):null;n(Jt(d,l))}},c=>{const u=Vs(c);s?s(u):console.error("pyric remote Firestore: uncaught onSnapshot error:",u)})}catch(c){throw Vs(c)}return o}const ru=Symbol("pyric/sandbox/admin-firestore/remoteQueryState");function Mm(t){if(!(t===null||typeof t!="object"))return t[ru]}function nu(t){return t.kind==="where"?(su(t.op),{kind:"where",field:t.field,op:t.op,value:pt(t.value)}):{kind:t.kind,filters:t.filters.map(nu)}}const Pm=new Set(["<","<=","==","!=",">=",">","in","not-in","array-contains","array-contains-any"]);function su(t){if(!Pm.has(t))throw ht(`invalid where operator: ${String(t)}`)}function Zr(t){const e=[...t.filters];for(const r of t.orders)e.push({kind:"orderBy",field:r.field,direction:r.direction});return t.start&&e.push({kind:t.start.inclusive?"startAt":"startAfter",values:t.start.values.map(pt)}),t.end&&e.push({kind:t.end.inclusive?"endAt":"endBefore",values:t.end.values.map(pt)}),t.limitCount!==void 0&&e.push(t.limitFromEnd?{kind:"limitToLast",n:t.limitCount}:{kind:"limit",n:t.limitCount}),e.length===0?t.source:{__ref:"query",source:t.source,constraints:e}}function to(t,e,r){if(e.length===0)throw ht(`${r}(snapshot) on a remote sandbox requires at least one explicit orderBy() clause — the relay protocol has no document-key cursor.`);if(e.some(s=>s.field==="__name__"))throw ht(`${r}(snapshot) on a remote sandbox does not support orderBy('__name__') — the relay protocol has no document-key cursor, and __name__ is not a data field a value cursor can carry. Order by a real document field instead.`);const n=t.data();if(n===void 0)throw new se("not-found",`Snapshot-based cursors require an existing document — got an empty snapshot for ${t.id??"<unknown>"}.`);return e.map(s=>n[s.field])}function Ii(t,e){const r=s=>Ii(t,{...e,...s});return{[ru]:e,where(s,i,a){return su(i),r({filters:[...e.filters,{kind:"where",field:s,op:i,value:pt(a)}]})},applyFilter(s){return r({filters:[...e.filters,nu(s)]})},orderBy(s,i="asc"){return r({orders:[...e.orders,{field:s,direction:i}]})},limit(s){return r({limitCount:s,limitFromEnd:!1})},limitToLast(s){return r({limitCount:s,limitFromEnd:!0})},startCursor(s,i){return r({start:{values:[...s],inclusive:i}})},endCursor(s,i){return r({end:{values:[...s],inclusive:i}})},startCursorFromSnapshot(s,i){return r({start:{values:to(s,e.orders,i?"startAt":"startAfter"),inclusive:i}})},endCursorFromSnapshot(s,i){return r({end:{values:to(s,e.orders,i?"endAt":"endBefore"),inclusive:i}})},async get(s){Jr(e);const i=await Ze(t,{method:"getDocs",source:Zr(e)});return Xc(t,i)},async aggregate(s){Jr(e);const i=await Ze(t,{method:"aggregate",source:Zr(e),spec:s});return{data:()=>i.data}},[xi]:(s,i,a)=>(Jr(e),tu(t,Zr(e),s,i,a)),onSnapshot:eu}}function Jr(t){if(t.limitFromEnd&&t.orders.length===0)throw ht("limitToLast() queries require at least one orderBy clause.")}function Gs(t,e){const r=Ii(t,{source:{__ref:"collection",path:e},filters:[],orders:[],limitFromEnd:!1});return Object.assign(Object.create(Object.getPrototypeOf(r)),r,{id:qn(e),path:e,doc(s){const i=s??gi();return Rn(t,`${e}/${i}`)},async add(s,i){const a=await Ze(t,{method:"addDoc",collectionPath:e,data:Ut(s)});return Rn(t,a.path)}})}function Rn(t,e){const r={id:qn(e),path:e,get parent(){return Gs(t,qc(e))},collection(n){const s=`${e}/${n}`;if(!_i(s))throw ht(`collection path must have an odd number of segments: ${s}`);return Gs(t,s)},async get(n){const s=await Ze(t,{method:"getDoc",path:e});return Yc(r,s)},async set(n,s){await Ze(t,{method:"setDoc",path:e,data:Ut(n),...ro(s)?{options:ro(s)}:{}})},async update(n,s){await Ze(t,{method:"updateDoc",path:e,data:Ut(n)})},async delete(n){await Ze(t,{method:"deleteDoc",path:e})},[xi]:(n,s,i)=>tu(t,{__ref:"doc",path:e},n,s,i),onSnapshot:eu};return r}function ro(t){if(!t)return;const e={};return t.merge!==void 0&&(e.merge=t.merge),t.mergeFields!==void 0&&(e.mergeFields=[...t.mergeFields]),e.merge!==void 0||e.mergeFields!==void 0?e:void 0}function $m(t){const e=[];let r=!1;const n={set(i,a){return s(),e.push({method:"set",path:i.path,data:Ut(a)}),n},update(i,a){return s(),e.push({method:"update",path:i.path,data:Ut(a)}),n},delete(i){return s(),e.push({method:"delete",path:i.path}),n},async commit(i){s(),r=!0,await Ze(t,{method:"batchCommit",writes:e})}};function s(){if(r)throw new se("failed-precondition","WriteBatch has already been committed.")}return n}const qm=5;async function Um(t,e,r=qm){for(let n=0;n<r;n++){const s=[],i=[],a=()=>{if(i.length>0)throw new se("failed-precondition",Ms)},o={get(l){a();const f=Mm(l);return f!==void 0?u(f):c(l)},set(l,f){return i.push({method:"set",path:l.path,data:Ut(f)}),o},update(l,f){return i.push({method:"update",path:l.path,data:Ut(f)}),o},delete(l){return i.push({method:"delete",path:l.path}),o}};async function c(l){const f=await Ze(t,{method:"getDoc",path:l.path});return s.push({path:f.path??l.path,data:f.exists&&f.data?f.data:null}),Yc(l,f)}async function u(l){Jr(l);const f=await Ze(t,{method:"getDocs",source:Zr(l)});for(const y of f.docs)s.push({path:y.path??y.id,data:y.data??null});return Xc(t,f)}const d=await e(o);try{return await Ze(t,{method:"txnCommit",reads:s,writes:i}),d}catch(l){if(l instanceof se&&l.code==="aborted")continue;throw l}}throw new se("aborted",`Transaction failed after ${r} attempts due to repeated conflicts. Another writer is concurrently updating the same documents.`)}function is(t,e){return new se("unimplemented",`SandboxFirestore.${t} is not available on a remote sandbox — its return value is synchronous and the data lives in the browser worker. ${e}`)}function iu(t,e){const r={sandbox:t,lens:e};return{collection(n){if(!_i(n))throw ht(`collection path must have an odd number of segments: ${n}`);return Gs(r,n)},doc(n){if(!$c(n))throw ht(`document path must have an even number of segments: ${n}`);return Rn(r,n)},collectionGroup(n){if(n.length===0||n.includes("/"))throw ht(`collection group id must be a single non-empty segment with no '/': ${n}`);return Ii(r,{source:{__ref:"group",collectionId:n},filters:[],orders:[],limitFromEnd:!1})},batch(){return $m(r)},runTransaction(n,s){return Um(r,n,s?.maxAttempts)},setRules(){throw is("setRules","Deploy rules asynchronously through the relay instead: `await sandbox.channel.op({ method: 'setFirestoreRules', source })`.")},seed(){throw is("seed","The relay has no atomic seed op; write seed docs through this handle (`db.doc(path).set(data)` / `db.batch()`), or drive `sandbox.channel.op({ method: 'admin.setDocument', path, data })` per document.")},snapshot(){throw is("snapshot","Read the worker state asynchronously instead: `await sandbox.channel.op({ method: 'admin.readState' })`.")}}}const no=new WeakMap;function au(t){const e=no.get(t);if(e)return e;const r=Si(t.sandbox)?iu(t.sandbox,Bm(t.auth)):Tn(Jc(t),t);return no.set(t,r),r}function Bm(t){return t==null?{mode:"anon"}:t.token===void 0?{mode:"as",uid:t.uid}:{mode:"as",uid:t.uid,token:t.token}}const so=new WeakMap;function zm(t){const e=Vm(t)?t:t.withAuth(null),r=so.get(e);if(r)return r;const n=e.operationContext.authLens.mode==="admin"?e:vi(e,{source:e.operationContext.source,authLens:{mode:"admin"},...e.operationContext.planId===void 0?{}:{planId:e.operationContext.planId}}),s=Si(n.sandbox)?iu(n.sandbox,{mode:"admin"}):Tn(Jc(n,!0),n,!0);return so.set(e,s),s}function Vm(t){return t!==null&&typeof t=="object"&&"sandbox"in t&&typeof t.withAuth=="function"}const zr=Symbol("pyric/firestore/followsCurrentUser"),as=Symbol("pyric/firestore/authSessionScope");function Wm(t){if(t===null||typeof t!="object")return null;const e=t;return typeof e.path=="string"&&e.path.length>0?e.path:typeof e.collectionPath=="string"&&e.collectionPath.length>0?e.collectionPath:null}function Hm(t){if(t!==null&&typeof t=="object"){const e=t.snapshotConstraints;if(typeof e=="function")return e.call(t)}}function Gm(t){if(t===null||typeof t!="object")return!1;const e=t;return typeof e.path=="string"&&e.path.length>0&&e.parent!==void 0&&e.parent!==null}function ou(t,e,r,n,s){let i={},a,o;if(typeof e=="object"&&e!==null&&typeof e.next!="function"&&typeof e.error!="function"&&typeof e.complete!="function"){if(i=e,typeof r=="function")a=r,o=n;else if(typeof r=="object"&&r!==null){const T=r;a=T.next,o=T.error}}else if(typeof e=="function")a=e,o=r;else if(typeof e=="object"&&e!==null){const T=e;a=T.next,o=T.error}if(!a&&!o)throw new TypeError("onSnapshot: missing handler. Provide a callback, or an observer with a `next` and/or `error` method.");const u=jm(t);if(u){if(i[zr]===!0)throw new se("unimplemented","onSnapshot: live (follows-current-user) listeners are not supported on a remote sandbox — remote listeners are frozen to the identity of the context that created the ref.");return u(i,a,o)}const d=Km(t),l=Ke(d.sandbox);let f;if(Gm(t))f={kind:"doc",path:t.path};else{const T=Wm(t);if(T===null)throw new TypeError("onSnapshot: could not determine the collection path for this Query. Pass a CollectionReference or a Query produced by `.where`/`.orderBy`/`.limit` on a CollectionReference obtained from `getFirestore(ctx)`.");const L=Hm(t);f={kind:"query",collection:T,constraints:L}}const y=i[zr]===!0,b=i[as],S=t[Zc]===!0;if(zr in i){const{[zr]:T,...L}=i;i=L}if(as in i){const{[as]:T,...L}=i;i=L}const j=()=>l.addSnapshotListener(f,a??(()=>{}),i,d.auth,o,y,S,b);return d.sandbox.runWithProvenance?.(yi(d.operationContext),j)??j()}function Km(t){if(t===null||typeof t!="object")throw new TypeError("onSnapshot: reference must be a DocumentReference or Query.");const e=t[Kc];if(!e)throw new TypeError("onSnapshot: reference was not produced by a sandbox context — pass a ref obtained from `getFirestore(ctx)`.");return e}Cm(ou);Dm(ou);class Rt{bytes;constructor(e){this.bytes=e,st(this,Gf(e)),Ht(this,Object.freeze({type:"bytes",values:Object.freeze(Array.from(e))}),()=>new Rt(e.slice()))}static fromBase64String(e){const r=atob(e),n=new Uint8Array(r.length);for(let s=0;s<r.length;s+=1)n[s]=r.charCodeAt(s);return new Rt(n)}static fromUint8Array(e){return new Rt(e.slice())}toBase64(){let e="";for(const r of this.bytes)e+=String.fromCharCode(r);return btoa(e)}toUint8Array(){return this.bytes.slice()}toString(){return`Bytes(base64: ${this.toBase64()})`}isEqual(e){return e instanceof Rt&&this.bytes.length===e.bytes.length&&this.bytes.every((r,n)=>r===e.bytes[n])}toJSON(){return{type:"firestore/bytes/1.0",bytes:this.toBase64()}}static fromJSON(e){const r=e;if(r.type!=="firestore/bytes/1.0"||typeof r.bytes!="string")throw new TypeError("Invalid Bytes JSON value.");return Rt.fromBase64String(r.bytes)}}class wr{lat;lng;constructor(e,r){if(this.lat=e,this.lng=r,!Number.isFinite(e)||e<-90||e>90)throw new TypeError("Latitude must be a number between -90 and 90.");if(!Number.isFinite(r)||r<-180||r>180)throw new TypeError("Longitude must be a number between -180 and 180.");st(this,qt("geo-point",String(e),"\0",String(r))),Ht(this,Object.freeze({type:"geo-point",latitude:e,longitude:r}),()=>new wr(e,r))}get latitude(){return this.lat}get longitude(){return this.lng}isEqual(e){return e instanceof wr&&this.lat===e.lat&&this.lng===e.lng}toJSON(){return{latitude:this.lat,longitude:this.lng,type:"firestore/geoPoint/1.0"}}static fromJSON(e){const r=e;if(r.type!=="firestore/geoPoint/1.0"||typeof r.latitude!="number"||typeof r.longitude!="number")throw new TypeError("Invalid GeoPoint JSON value.");return new wr(r.latitude,r.longitude)}}class Xt{_values;constructor(e){this._values=e,Ht(this,Object.freeze({type:"vector",values:Object.freeze(e.slice())}),()=>new Xt(e.slice()))}static create(e){if(!e.every(r=>typeof r=="number"))throw new TypeError("Vector values must be numbers.");return new Xt(e.slice())}toArray(){return this._values.slice()}isEqual(e){const r=e instanceof Xt?e._values:void 0;return r!==void 0&&this._values.length===r.length&&this._values.every((n,s)=>n===r[s])}toJSON(){return{type:"firestore/vectorValue/1.0",vectorValues:this.toArray()}}static fromJSON(e){const r=e;if(r.type!=="firestore/vectorValue/1.0"||!Array.isArray(r.vectorValues)||!r.vectorValues.every(n=>typeof n=="number"))throw new TypeError("Invalid VectorValue JSON value.");return Xt.create(r.vectorValues)}}function Zm(t=[]){return Xt.create(t)}function vg(){return Zf.serverTimestamp()}const St=Symbol("pyric/firestore/target");function Pr(t){return t.kind==="sandbox"?t.db:t.getDb()}const Un=new WeakMap;function Jm(t,e){return Un.set(t,e),t}const $r=new WeakMap;function Qm(t,e,r){return Un.set(t,e),$r.set(t,r),t}function ki(t,e){const r=ur(e);if(t.kind==="sandbox")return r;const n=$r.get(r);if(!n)throw new TypeError("pyric/firestore: live ref missing rebuild closure — was it produced by a factory in this package?");return n(Pr(t))}function Ym(t,e){const r=ur(e);if(t.kind==="sandbox")return r;const n=$r.get(r);if(!n)throw new TypeError("pyric/firestore: live collection ref missing rebuild closure.");return n(Pr(t))}function wg(t,e){const r=ur(e);if(t.kind==="sandbox")return r;const n=$r.get(r);if(!n)throw new TypeError("pyric/firestore: live query missing rebuild closure.");return n(Pr(t))}function Rr(t,e,r){return e.kind==="sandbox-live"?Qm(t,e,r):Jm(t,e)}function Sg(t){const e=ur(t),r=$r.get(e);return r||(()=>e)}function cr(t){const e=Xm(t);return e.assertUsable?.(),e}function Xm(t){let e;if(St in t?e=t[St]:e=Un.get(t),!e)throw new TypeError("pyric/firestore: unrecognized reference — was it produced by a factory in this package?");return e}const cu=new WeakMap,uu=new WeakMap;function Ei(t){return cu.get(t)}function ur(t){return uu.get(t)??t}function lu(t,e,r){const n={id:t.id??"",path:t.path??""};return cu.set(n,r),uu.set(n,t),Un.set(n,e),n}function eg(t){return t instanceof Wt?Array.from(t.value):null}function Ks(t){if(t instanceof Be)return Rt.fromUint8Array(t.data);if(t instanceof rt)return new wr(t.lat,t.lng);const e=eg(t);if(e)return Zm(e);if(Array.isArray(t))return t.map(Ks);if(t!==null&&typeof t=="object"){const r=Object.getPrototypeOf(t);if(r===Object.prototype||r===null){const n={};for(const[s,i]of Object.entries(t))n[s]=Ks(i);return n}}return t}function _g(t){if(t!==void 0)return Ks(t)}class ir extends Error{code;customData;name="FirebaseError";constructor(e,r,n){super(r),this.code=e,this.customData=n,Object.setPrototypeOf(this,new.target.prototype)}}Object.defineProperty(ir,"name",{value:"FirebaseError"});let Nn;function Ag(t){Nn=t}function du(t){return Nn?.resolve(t,!1)}function tg(){if(!Nn)throw new TypeError("No default sandbox app registry is installed - import and initialize pyric/app before calling a service factory without an app.");return Nn.defaultApp()}function rg(t){if(t===void 0)return rg(tg());const e=du(t);if(e)return e.service("firestore/default",()=>{const{sandbox:r,session:n}=e,s=os();e.onDelete(s.terminate);const i=e.authScope;i&&s.own(n.onCurrentUserChanged(o=>{Ke(r).reevaluateLiveListeners(o,i)}));const a={kind:"sandbox-live",sandbox:r,getDb:io(r,()=>n.currentUser),authScope:i,...s};return{[St]:a,app:t}});if(hu(t)){const n={kind:"sandbox",db:au(t),sandbox:t.sandbox,...os()};return{[St]:n}}if(sg(t)){const r={kind:"sandbox-live",sandbox:t,getDb:io(t),...os()};return{[St]:r}}throw new TypeError("pyric/firestore is a sandbox-only mirror. Package resolution must leave firebase/firestore unchanged for production; activate pyric dev or @pyric/cli/register before importing to select the sandbox.")}function os(){let t=!1;const e=new Set;return{own(r){return t?(r(),()=>{}):(e.add(r),()=>e.delete(r))},assertUsable(){if(t)throw new ir("failed-precondition","The client has already been terminated.")},terminate(){if(!t){t=!0;for(const r of e)r();e.clear()}}}}function ng(t){const e=du(t);if(e){e.assertAlive();const a=e.sandbox;return ng(vi(a.withAuth(null),{source:{kind:"app"},authLens:{mode:"admin"}}))}const r=hu(t)?t:t.withAuth(null),n=r.sandbox,i={kind:"sandbox",db:zm(r),sandbox:n};return{[St]:i}}function hu(t){return t instanceof Mr}function sg(t){if(t===null||typeof t!="object")return!1;const e=t;return typeof e.withAuth=="function"&&typeof e.onCurrentUserChanged=="function"&&"currentUser"in e&&"admin"in e}function io(t,e=()=>t.currentUser){return()=>{const r=vi(t.withAuth(e()),{source:{kind:"app"},authLens:{mode:"app-session"}});return au(r)}}class ig{started=!1;networkEnabled=!0;persistenceMode;pending=new Set;cachedPaths=new Set;cachedQueries=new WeakSet;syncObservers=new Set;syncScheduled=!1;markStarted(){this.started=!0}enablePersistence(e){if(this.started||this.persistenceMode!==void 0)throw new ir("failed-precondition","Firestore has already been started and persistence can no longer be enabled.");this.persistenceMode=e,this.started=!0}disableNetwork(){this.started=!0,this.networkEnabled=!1}async enableNetwork(){this.started=!0,this.networkEnabled=!0;for(const e of this.pending)e.localDone&&e.resolve(e.value);await Promise.all([...this.pending].map(e=>e.promise))}runWrite(e,r){if(this.started=!0,r&&this.cachedPaths.add(r),this.networkEnabled)return e();let n,s;const i=new Promise((o,c)=>{n=o,s=c}),a={path:r,promise:i,localDone:!1,resolve:n,reject:s};return this.pending.add(a),e().then(o=>{a.localDone=!0,a.value=o,this.networkEnabled&&a.resolve(o)},o=>a.reject(o)),i.then(()=>this.pending.delete(a),()=>this.pending.delete(a)),i}waitForPendingWrites(){this.started=!0;const e=[...this.pending].map(r=>r.promise);return Promise.all(e).then(()=>{})}cachePath(e){this.started=!0,this.cachedPaths.add(e)}assertPathCached(e){if(this.started=!0,!this.cachedPaths.has(e))throw new ir("unavailable","Failed to get document from cache. (However, this document may exist on the server.)")}cacheQuery(e){this.started=!0,this.cachedQueries.add(e)}hasCachedQuery(e){return this.started=!0,this.cachedQueries.has(e)||this.cachedPaths.size>0}snapshotMetadata(e){return Object.freeze({fromCache:!this.networkEnabled,hasPendingWrites:[...this.pending].some(r=>r.path===e)})}querySnapshotMetadata(){return Object.freeze({fromCache:!this.networkEnabled,hasPendingWrites:this.pending.size>0})}addSnapshotsInSyncObserver(e){return this.syncObservers.add(e),e(),()=>this.syncObservers.delete(e)}notifySnapshotDelivered(){this.syncScheduled||this.syncObservers.size===0||(this.syncScheduled=!0,queueMicrotask(()=>{this.syncScheduled=!1;for(const e of[...this.syncObservers])e()}))}}const ao=new WeakMap;function Nr(t){let e=ao.get(t);return e||(e=new ig,ao.set(t,e)),e}function cs(t,e,r){return st(t,qt("reference",e)),hi(t,e,r),t}function xg(t,...e){const r=cr(t),n=St in t,s=n?void 0:Ei(t),i=Pr(r);if(n){if(e.length===0)throw new TypeError("doc(db, path) requires at least one path segment.");const d=e.join("/"),l=i.doc(d),f=Rr(l,r,y=>y.doc(d));return cs(f,d,r)}const a=ur(t),o=e.length===0?a.doc():a.doc(e.join("/")),c=o.path,u=Rr(o,r,d=>d.doc(c));if(s){const d=lu(u,r,s);return cs(d,c,r)}return cs(u,c,r)}function Ig(t,...e){const r=cr(t),n=St in t;if(e.length===0)throw new TypeError("collection() requires at least one path segment.");if(n){const c=e.join("/"),u=Pr(r).collection(c);return Rr(u,r,d=>d.collection(c))}const s=ur(t),i=e.join("/"),a=s.collection(i),o=a.path;return Rr(a,r,c=>c.collection(o))}function ag(t){return t instanceof Error&&"code"in t&&typeof t.code=="string"}function og(t){if(t instanceof ir||!ag(t))return t;const e={};t.denialContext!==void 0&&(e.denialContext=t.denialContext),t.remediation!==void 0&&(e.remediation=t.remediation);const r=new ir(t.code,t.message,Object.keys(e).length===0?void 0:e);return t.denialContext!==void 0&&Object.assign(r,{denialContext:t.denialContext}),t.remediation!==void 0&&Object.assign(r,{remediation:t.remediation}),r}async function Bn(t){try{return await t()}catch(e){throw og(e)}}async function kg(t,e,r){const n=cr(t),s=Ei(t),i=s?s.toFirestore(e):e;return Nr(n).runWrite(()=>Bn(()=>ki(n,t).set(i,r)),t.path)}async function Eg(t,e){const r=cr(t);return Nr(r).runWrite(()=>Bn(()=>ki(r,t).update(e)),t.path)}async function Og(t){const e=cr(t);return Nr(e).runWrite(()=>Bn(()=>ki(e,t).delete()),t.path)}async function Cg(t,e){const r=cr(t),n=Ei(t),s=n?n.toFirestore(e):e,i=await Nr(r).runWrite(async()=>{const c=await Bn(()=>Ym(r,t).add(s));return Nr(r).cachePath(c.path),c}),a=i.path,o=Rr(i,r,c=>c.doc(a));if(st(o,qt("reference",a)),hi(o,a,r,o),n){const c=lu(o,r,n);return Sf(o,c),c}return o}function Tg(t,e){return Ke(t).deployRules(e)}function Rg(t,e){const r=Ke(t);return r.seed({rules:r.getRules(),documents:e})}function Ng(t){return Ke(t).snapshot()}function Fg(t,e={}){const r=e.recentEventLimit??10,n=Ke(t),s=n.getRules(),i=s?ws(s):{warnings:[]},a=i.warnings.map(S=>({rule:S.rule,severity:S.severity,message:S.message})),o={errors:0,warnings:0,info:0};for(const S of i.warnings)S.severity==="error"?o.errors++:S.severity==="warning"?o.warnings++:o.info++;const c=n.snapshot(),u={};for(const S of Object.keys(c)){const j=S.split("/")[0]??"";j&&(u[j]=(u[j]??0)+1)}const d=t.history(),l=d.filter(S=>S.kind==="request"),f=l.filter(S=>S.result==="deny"),y=l.slice(-r).map(S=>({path:String(S.path??""),method:String(S.method??""),result:String(S.result??""),auth:S.auth??null})),b=f.slice(-r).map(S=>({path:String(S.path??""),method:String(S.method??""),auth:S.auth??null,debugMessage:typeof S.debugMessage=="string"?S.debugMessage:void 0}));return{rules:{source:s,sizeBytes:new TextEncoder().encode(s).byteLength,isEmpty:s.trim().length===0,lint:{...o,findings:a}},documents:{totalCount:Object.keys(c).length,byCollection:u},events:{totalCount:d.length,recentDenials:b,recentRequests:y}}}export{gg as $,as as A,Og as B,hg as C,dg as D,Ag as E,zr as F,wi as G,lt as H,ph as I,Ir as J,Ft as K,kr as L,ui as M,fh as N,vn as O,ci as P,dt as Q,ut as R,tr as S,As as T,Mt as U,pn as V,dn as W,fg as X,pg as Y,me as Z,mg as _,Rg as a,yg as a0,ng as a1,Ha as a2,tg as a3,du as a4,se as a5,Xr as a6,oe as a7,bi as a8,yi as a9,vi as aa,Mr as ab,lg as ac,bt as ad,wr as ae,Rt as af,ws as ag,Jm as ah,_g as ai,uu as aj,hi as ak,zc as al,ki as am,wg as an,vg as ao,kg as b,Ng as c,xg as d,bg as e,fl as f,rg as g,Ke as h,Fg as i,Ei as j,og as k,Pr as l,Rr as m,lu as n,Bc as o,Sg as p,Nr as q,ug as r,Tg as s,cr as t,ur as u,$r as v,ir as w,Ig as x,Cg as y,Eg as z};