tempest.games 0.1.30 → 0.1.32

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.
@@ -1,30 +1,30 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- var HW=Object.create;var{getPrototypeOf:zW,defineProperty:en,getOwnPropertyNames:QW}=Object;var DW=Object.prototype.hasOwnProperty;var Ak=(T,o,S)=>{S=T!=null?HW(zW(T)):{};let f=o||!T||!T.__esModule?en(S,"default",{value:T,enumerable:!0}):S;for(let n of QW(T))if(!DW.call(f,n))en(f,n,{get:()=>T[n],enumerable:!0});return f};var $k=(T,o)=>()=>(o||T((o={exports:{}}).exports,o),o.exports);var UW=(T,o)=>{for(var S in o)en(T,S,{get:o[S],enumerable:!0,configurable:!0,set:(f)=>o[S]=()=>f})};var Fk=import.meta.require;import{join as Sk,normalize as fk,resolve as B1}from"path";function Zf(T=Math.random){return T().toString(36).slice(2)}class sS extends Promise{fate;resolve;reject;done=!1;constructor(T){let o,S;super((f,n)=>{o=f,S=n});this.resolve=o,this.reject=S,this.use(T instanceof Promise?T:new Promise(T))}pass(T,o){if(T===this.fate)this.resolve(o),this.done=!0}fail(T,o){if(T===this.fate)this.reject(o),this.done=!0}use(T){if(T instanceof Promise){let o=T;this.fate=o,o.then((S)=>{this.pass(o,S)},(S)=>{this.fail(o,S)})}else this.resolve(T),this.fate=void 0}}function i$(T){return Object.entries(T)}var g$=(T,o,S=a.STORE)=>{return Go(S,{key:`${T.key}:JSON`,get:({get:f})=>o.toJson(f(T)),set:({set:f},n)=>{f(T,o.fromJson(n))}})};function L(T){while(T.child!==null)T=T.child;return T}class ST{Subscriber;subscribers=new Map;subscribe(T,o){return this.subscribers.set(T,o),()=>{this.unsubscribe(T)}}unsubscribe(T){this.subscribers.delete(T)}next(T){let o=this.subscribers.values();for(let S of o)S(T)}}class an extends ST{state;constructor(T){super();this.state=T}next(T){this.state=T,super.next(T)}}function Lo(T,o,S){let f={key:o.key,type:"atom_family"},n=T.families.get(o.key);if(n)T.logger.error("\u2757","atom_family",o.key,`Overwriting an existing ${Yo(n)} "${n.key}" in store "${T.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let A=new ST,F=Object.assign((J)=>{let R=s(J),W={key:o.key,subKey:R},y=`${o.key}(${R})`,_=L(T),K=o.default,H={key:y,default:K instanceof Function?K(J):K};if(o.effects)H.effects=o.effects(J);let Y=fo(_,H,W);return A.next({type:"state_creation",token:Y}),Y},f,{subject:A,install:(J)=>Lo(J,o),internalRoles:S});return T.families.set(o.key,F),T.defaults.set(o.key,o.default),f}function d$(T,o){if("mutable"in o)return Tf(T,o);return Lo(T,o)}function ho(T,o,S){let f={key:o.key,type:"readonly_selector_family"},n=T.families.get(o.key);if(n)T.logger.error("\u2757","readonly_selector_family",o.key,`Overwriting an existing ${Yo(n)} "${n.key}" in store "${T.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let A=new ST,F=Object.assign((J)=>{let R=s(J),W={key:o.key,subKey:R},y=`${o.key}(${R})`,_=L(T),K=of(_,{key:y,get:o.get(J)},W);return A.next({type:"state_creation",token:K}),K},f,{internalRoles:S,subject:A,install:(J)=>ho(J,o),default:(J)=>{return o.get(J)({get:(...W)=>RT(T,...W),find:(W,y)=>i(T,W,y),seek:(W,y)=>qT(T,W,y),json:(W)=>mT(T,W)})}});return T.families.set(o.key,F),f}function Sf(T,o){if("set"in o)return ff(T,o);return ho(T,o)}class cf{_buffer;_index=0;constructor(T){let o;if(typeof T==="number")o=T;else o=T.length;this._buffer=Array.from({length:o})}get buffer(){return this._buffer}get index(){return this._index}add(T){this._buffer[this._index]=T,this._index=(this._index+1)%this._buffer.length}copy(){let T=new cf([...this._buffer]);return T._index=this._index,T}}var tW={atom_family:"atom",mutable_atom_family:"mutable_atom",selector_family:"selector",readonly_selector_family:"readonly_selector",molecule_family:"molecule"};function l$(T,o){let S=s(o),f=`${T.key}(${S})`,n=tW[T.type],A={key:f,type:n};return Object.assign(A,{family:{key:T.key,subKey:S}}),Object.assign(A,{counterfeit:!0}),A}function no(T){let o={key:T.key,type:T.type};if("family"in T)o.family=T.family;return o}function u$(T,o=a.STORE){let S={key:T,stringKey:s(T),dependsOn:"any"};return o.molecules.set(s(T),S),T}var Pk=Symbol("claim");function YS(T,o,S,f="any"){let n=o,A=s(S),$=[],F=L(T);if(Array.isArray(n))for(let W of n){let y=s(W);if(F.molecules.get(y))T.moleculeGraph.set(y,A,{source:y});else $.push(y)}else{let W=s(n);if(F.molecules.get(W))T.moleculeGraph.set(W,A,{source:W});else $.push(W)}if($.length===0)F.molecules.set(A,{key:S,stringKey:A,dependsOn:f});let J={type:"molecule_creation",key:S,provenance:n};if(WT(F)&&F.transactionMeta.phase==="building")F.transactionMeta.update.updates.push(J);else F.on.moleculeCreation.next(J);for(let W of $){let y=T.disposalTraces.buffer.find((_)=>_?.key===W);T.logger.error("\u274C","molecule",S,"allocation failed:",`Could not allocate to ${W} in store "${T.config.name}".`,y?`
4
- ${W} was most recently disposed
5
- ${y.trace}`:`No previous disposal trace for ${W} was found.`)}return S}function VW(T,o,S,f){let n=`T$--${o}==${S}++${f}`;return YS(T,[S,f],n,"all"),n}function ES(T,o){let S=s(o),f=T.molecules.get(S);if(!f){let K=T.disposalTraces.buffer.find((H)=>H?.key===S);T.logger.error("\u274C","molecule",o,"deallocation failed:",`Could not find allocation for ${S} in store "${T.config.name}".`,K?`
3
+ var QM=Object.create;var{getPrototypeOf:DM,defineProperty:an,getOwnPropertyNames:UM}=Object;var tM=Object.prototype.hasOwnProperty;var nk=(o,T,f)=>{f=o!=null?QM(DM(o)):{};let S=T||!o||!o.__esModule?an(f,"default",{value:o,enumerable:!0}):f;for(let n of UM(o))if(!tM.call(S,n))an(S,n,{get:()=>o[n],enumerable:!0});return S};var Ak=(o,T)=>()=>(T||o((T={exports:{}}).exports,T),T.exports);var VM=(o,T)=>{for(var f in T)an(o,f,{get:T[f],enumerable:!0,configurable:!0,set:(S)=>T[f]=()=>S})};var $k=import.meta.require;import{join as Tk,normalize as fk,resolve as C1}from"path";function pS(o=Math.random){return o().toString(36).slice(2)}class TS extends Promise{fate;resolve;reject;done=!1;constructor(o){let T,f;super((S,n)=>{T=S,f=n});this.resolve=T,this.reject=f,this.use(o instanceof Promise?o:new Promise(o))}pass(o,T){if(o===this.fate)this.resolve(T),this.done=!0}fail(o,T){if(o===this.fate)this.reject(T),this.done=!0}use(o){if(o instanceof Promise){let T=o;this.fate=T,T.then((f)=>{this.pass(T,f)},(f)=>{this.fail(T,f)})}else this.resolve(o),this.fate=void 0}}function P$(o){return Object.entries(o)}var i$=(o,T,f=So.STORE)=>{return mT(f,{key:`${o.key}:JSON`,get:({get:S})=>T.toJson(S(o)),set:({set:S},n)=>{S(o,T.fromJson(n))}})};function C(o){while(o.child!==null)o=o.child;return o}class oo{Subscriber;subscribers=new Map;subscribe(o,T){return this.subscribers.set(o,T),()=>{this.unsubscribe(o)}}unsubscribe(o){this.subscribers.delete(o)}next(o){let T=this.subscribers.values();for(let f of T)f(o)}}class oA extends oo{state;constructor(o){super();this.state=o}next(o){this.state=o,super.next(o)}}function NT(o,T,f){let S={key:T.key,type:"atom_family"},n=o.families.get(T.key);if(n)o.logger.error("\u2757","atom_family",T.key,`Overwriting an existing ${VT(n)} "${n.key}" in store "${o.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let A=new oo,F=Object.assign((J)=>{let R=fo(J),M={key:T.key,subKey:R},_=`${T.key}(${R})`,w=C(o),X=T.default,U={key:_,default:X instanceof Function?X(J):X};if(T.effects)U.effects=T.effects(J);let K=FT(w,U,M);return A.next({type:"state_creation",token:K}),K},S,{subject:A,install:(J)=>NT(J,T),internalRoles:f});return o.families.set(T.key,F),o.defaults.set(T.key,T.default),S}function g$(o,T){if("mutable"in T)return fS(o,T);return NT(o,T)}function hT(o,T,f){let S={key:T.key,type:"readonly_selector_family"},n=o.families.get(T.key);if(n)o.logger.error("\u2757","readonly_selector_family",T.key,`Overwriting an existing ${VT(n)} "${n.key}" in store "${o.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let A=new oo,F=Object.assign((J)=>{let R=fo(J),M={key:T.key,subKey:R},_=`${T.key}(${R})`,w=C(o),X=SS(w,{key:_,get:T.get(J)},M);return A.next({type:"state_creation",token:X}),X},S,{internalRoles:f,subject:A,install:(J)=>hT(J,T),default:(J)=>{return T.get(J)({get:(...M)=>Ro(o,...M),find:(...M)=>i(o,...M),json:(M)=>jo(o,M)})}});return o.families.set(T.key,F),S}function cS(o,T){if("set"in T)return nS(o,T);return hT(o,T)}class PS{_buffer;_index=0;constructor(o){let T;if(typeof o==="number")T=o;else T=o.length;this._buffer=Array.from({length:T})}get buffer(){return this._buffer}get index(){return this._index}add(o){this._buffer[this._index]=o,this._index=(this._index+1)%this._buffer.length}copy(){let o=new PS([...this._buffer]);return o._index=this._index,o}}var BM={atom_family:"atom",mutable_atom_family:"mutable_atom",selector_family:"selector",readonly_selector_family:"readonly_selector",molecule_family:"molecule"};function d$(o,T){let f=fo(T),S=`${o.key}(${f})`,n=BM[o.type],A={key:S,type:n};return Object.assign(A,{family:{key:o.key,subKey:f}}),Object.assign(A,{counterfeit:!0}),A}function ST(o){let T={key:o.key,type:o.type};if("family"in o)T.family=o.family;return T}function Yf(o){return l$(So.STORE,o)}function Tf(o){return g$(So.STORE,o)}function TA(...o){if(o.length===2)return Ro(So.STORE,...o);return Ro(So.STORE,...o)}function iS(o,T,f=So.STORE){return f.joins.set(o.key,new AS(o,T,f)),{key:o.key,type:"join",a:o.between[0],b:o.between[1],cardinality:o.cardinality}}function e$(o){return s$(o,So.STORE)}var fA=(o)=>(T,f,S,n,...A)=>{console[o](`${T} ${f} "${S}" ${n}`,...A)},LM={error:fA("error"),info:fA("info"),warn:fA("warn")};class SA{logLevel;filter;logger;constructor(o,T,f=LM){this.logLevel=o;this.filter=T;this.logger=f}error=(...o)=>{if((this.filter?.(...o)??!0)&&this.logLevel!==null)this.logger.error(...o)};info=(...o)=>{if((this.filter?.(...o)??!0)&&this.logLevel==="info")this.logger.info(...o)};warn=(...o)=>{if((this.filter?.(...o)??!0)&&this.logLevel!=="error"&&this.logLevel!==null)this.logger.warn(...o)}}var ck=Symbol("claim");class a${store;constructor(o=So.STORE){this.store=o,oF("root",o)}allocate(o,T,f){return ff(this.store,o,T,f)}fuse(o,T,f){return TF(this.store,o,T,f)}deallocate(o){Sf(this.store,o)}claim(o,T,f){return Ef(this.store,o,T,f)}}class nA{store;realm;constructor(o=So.STORE){this.store=o,this.realm=new a$(o)}allocate(o,T,f){ff(this.store,o,T,f)}deallocate(o){Sf(this.store,o)}claim(o,T,f){Ef(this.store,o,T,f)}}function dS(o){return cS(So.STORE,o)}function mo(o){return"epoch"in o.transactionMeta}function Mo(o){return"phase"in o.transactionMeta}var fF=(o)=>{let T=C(o);if(!Mo(T)){o.logger.warn("\uD83D\uDC1E","transaction","???","abortTransaction called outside of a transaction. This is probably a bug in AtomIO.");return}o.logger.info("\uD83E\uDE82","transaction",T.transactionMeta.update.key,"Aborting transaction"),T.parent.child=null};function Wo(o){return o[0].toUpperCase()+o.slice(1)}function VT(o){return o.type.split("_").map(Wo).join(" ")}class nf extends Error{constructor(o,T){super(`${VT(o)} ${fo(o.key)} not found in store "${T.config.name}".`)}}function zf(o,T,f){return(...S)=>{let n=$o(o,T);if(n)return n.run(S,f);throw new nf(T,o)}}var lS=(o)=>(T)=>o instanceof Function?o(T):o;var PT=(o,T)=>{if(o.valueMap.has(T.key))return o.logger.info("\uD83D\uDCD6",T.type,T.key,"reading cached value"),SF(T,o);if(T.type==="selector"||T.type==="readonly_selector")return o.logger.info("\uD83E\uDDEE",T.type,T.key,"computing value"),T.get();let f=T.default instanceof Function?T.default():T.default;return o.logger.info("\uD83D\uDC81","atom",T.key,"could not find cached value; using default",f),T.default instanceof Function?T.default():T.default};var nF=(o,T)=>{if(o.operation.open){let f=performance.now();return o.logger.info("\u2757",T.type,T.key,`deferring setState at T-${f} until setState for "${o.operation.token.key}" is done`),f}o.operation={open:!0,done:new Set,prev:new Map,time:Date.now(),token:T},o.logger.info("\u2B55",T.type,T.key,`operation start in store "${o.config.name}"${!Mo(o)?"":` ${o.transactionMeta.phase} "${o.transactionMeta.update.key}"`}`)},AF=(o)=>{if(o.operation.open)o.logger.info("\uD83D\uDD34",o.operation.token.type,o.operation.token.key,`operation done in store "${o.config.name}"`);o.operation={open:!1},o.on.operationClose.next(o.operation)},$F=(o,T)=>{if(!o.operation.open)return o.logger.error("\uD83D\uDC1E","unknown",T,"isDone called outside of an operation. This is probably a bug in AtomIO."),!0;return o.operation.done.has(T)},Qf=(o,T)=>{if(!o.operation.open){o.logger.error("\uD83D\uDC1E","unknown",T,"markDone called outside of an operation. This is probably a bug in AtomIO.");return}o.operation.done.add(T)};var FF=(o,T,f)=>{switch(T.type){case"mutable_atom":o.logger.info("\uD83D\uDCE2",T.type,T.key,"is now (",f.newValue,") subscribers:",T.subject.subscribers);break;default:o.logger.info("\uD83D\uDCE2",T.type,T.key,"went (",f.oldValue,"->",f.newValue,") subscribers:",T.subject.subscribers)}T.subject.next(f)};var AA=(o,T)=>{let f=C(o),S=f.selectorAtoms.getRelatedKeys(T.key);if(f.logger.info("\uD83E\uDDF9",T.type,T.key,S?`evicting ${S.size} states downstream:`:"no downstream states",S??"to evict"),S){if(f.operation.open)f.logger.info("\uD83E\uDDF9",T.type,T.key,`[ ${[...f.operation.done].join(", ")} ] already done`);for(let n of S){if($F(f,n))continue;JF(n,f),Qf(f,n)}}};function CM(o,T){if(MF(T.newValue))return!1;if(o.includes("\uD83D\uDD0D"))return!1;return!0}var RF=(o,T,f)=>{let{key:S}=T,n=C(o);if(!Mo(n)||n.transactionMeta.phase!=="building"){o.logger.error("\uD83D\uDC1E","atom",S,"stowUpdate called outside of a transaction. This is probably a bug.");return}if(!CM(S,f))return;let $={type:"atom_update",key:S,...f};if(T.family)$.family=T.family;n.transactionMeta.update.updates.push($),o.logger.info("\uD83D\uDCC1","atom",S,"stowed (",f.oldValue,"->",f.newValue,")")};var WF=(o,T,f)=>{let S=PT(f,o),n=S;if(o.type==="mutable_atom"&&Mo(f)){let{parent:$}=f;n=FS(f,o,$)}if(n=lS(T)(n),f.logger.info("\uD83D\uDCDD","atom",o.key,"set to",n),n=OT(f,o.key,n,o.subject),OF(f,o.key))kF(f,o.key);Qf(f,o.key),AA(f,o);let A={oldValue:S,newValue:n};if(mo(f))FF(f,o,A);else if(f.parent){if(f.on.transactionApplying.state===null)RF(f,o,A);else if(o.key.startsWith("*")){let $=o.key.slice(1),F=f.atoms.get($),J=f.valueMap.get($);if(F.type==="mutable_atom"&&Mo(f)){let{parent:M}=f;J=FS(f,F,M)}if(J.do(A.newValue)===null)AA(f,F)}}};var uS=(o,T,f)=>{switch(T.type){case"atom":case"mutable_atom":WF(T,f,o);break;case"selector":T.set(f);break}};function _F(o,T){if(T.family){let f=o.families.get(T.family.key);if(f)return f}}function to(o,...T){let f,S,n,A;if(T.length===2){if(f=T[0],A=T[1],S=_F(o,f)??null,S)n=f.family?vo(f.family.subKey):null,f=i(o,S,n)}else S=T[0],n=T[1],A=T[2],f=i(o,S,n);if("counterfeit"in f&&"family"in f){let J=f.family.subKey,R=o.disposalTraces.buffer.find((M)=>M?.key===J);o.logger.error("\u274C",f.type,f.key,`could not be set because it was not found in the store "${o.config.name}".`,R?`This state was previously disposed:
4
+ ${R.trace}`:"No previous disposal trace was found.");return}let $=nF(o,f);if($){let J=o.on.operationClose.subscribe(`waiting to set "${f.key}" at T-${$}`,()=>{J(),o.logger.info("\uD83D\uDFE2",f.type,f.key,`resuming deferred setState from T-${$}`),to(o,f,A)});return}let F=$o(o,f);uS(o,F,A),AF(o)}function eS(o,T,f){let{key:S,newValue:n,oldValue:A}=T,$=o==="newValue"?n:A,F={key:S,type:"atom"};if(T.family)Object.assign(F,{family:T.family});to(f,F,$)}function wF(o){let{stack:T}=o;if(T)return`
5
+ `+T.split(`
6
+ `)?.slice(1)?.join(`
7
+ `);return""}function oF(o,T=So.STORE){let f={key:o,stringKey:fo(o),dependsOn:"any"};return T.molecules.set(fo(o),f),o}function ff(o,T,f,S="any"){let n=T,A=fo(f),$=[],F=C(o);if(Array.isArray(n))for(let M of n){let _=fo(M);if(F.molecules.get(_))o.moleculeGraph.set(_,A,{source:_});else $.push(_)}else{let M=fo(n);if(F.molecules.get(M))o.moleculeGraph.set(M,A,{source:M});else $.push(M)}if($.length===0)F.molecules.set(A,{key:f,stringKey:A,dependsOn:S});let J={type:"molecule_creation",key:f,provenance:n};if(Mo(F)&&F.transactionMeta.phase==="building")F.transactionMeta.update.updates.push(J);else F.on.moleculeCreation.next(J);for(let M of $){let _=o.disposalTraces.buffer.find((w)=>w?.key===M);o.logger.error("\u274C","molecule",f,"allocation failed:",`Could not allocate to ${M} in store "${o.config.name}".`,_?`
8
+ ${M} was most recently disposed
9
+ ${_.trace}`:`No previous disposal trace for ${M} was found.`)}return f}function TF(o,T,f,S){let n=`T$--${T}==${f}++${S}`;return ff(o,[f,S],n,"all"),n}function Sf(o,T){let f=fo(T),S=o.molecules.get(f);if(!S){let X=o.disposalTraces.buffer.find((U)=>U?.key===f);o.logger.error("\u274C","molecule",T,"deallocation failed:",`Could not find allocation for ${f} in store "${o.config.name}".`,X?`
6
10
  This state was most recently deallocated
7
- ${K.trace}`:`No previous disposal trace for ${S} was found.`);return}let n=T.moleculeJoins.getRelatedKeys(f.key);if(n)for(let K of n){let H=T.joins.get(K);if(H)H.relations.delete(f.key),H.molecules.delete(f.stringKey)}T.moleculeJoins.delete(f.stringKey);let A=[],$=[],F={type:"molecule_disposal",key:f.key,values:$,provenance:A},J=L(T);J.molecules.delete(S);let R=WT(J)&&J.transactionMeta.phase==="building";if(R)J.transactionMeta.update.updates.push(F);let W=T.moleculeGraph.getRelationEntries({downstreamMoleculeKey:f.stringKey});if(W)for(let[K,{source:H}]of W)if(H===f.stringKey){let Y=tT(K);ES(T,Y)}else A.push(H);let y=J.moleculeData.getRelatedKeys(f.stringKey);if(y)for(let K of y){let H=J.families.get(K),Y=i(T,H,f.key);$.push([H.key,Y]),nS(T,Y)}if(J.moleculeGraph.delete(f.stringKey),J.moleculeJoins.delete(f.stringKey),J.moleculeData.delete(f.stringKey),!R)J.on.moleculeDisposal.next(F);J.molecules.delete(f.stringKey);let _=a$(new Error);T.disposalTraces.add({key:S,trace:_})}function nf(T,o,S,f){let n=s(S),A=L(T),$=A.molecules.get(n);if(!$){let _=T.disposalTraces.buffer.find((K)=>K?.key===n);return T.logger.error("\u274C","molecule",S,"claim failed:",`Could not allocate to ${n} in store "${T.config.name}".`,_?`
11
+ ${X.trace}`:`No previous disposal trace for ${f} was found.`);return}let n=o.moleculeJoins.getRelatedKeys(S.key);if(n)for(let X of n){let U=o.joins.get(X);if(U)U.relations.delete(S.key),U.molecules.delete(S.stringKey)}o.moleculeJoins.delete(S.stringKey);let A=[],$=[],F={type:"molecule_disposal",key:S.key,values:$,provenance:A},J=C(o);J.molecules.delete(f);let R=Mo(J)&&J.transactionMeta.phase==="building";if(R)J.transactionMeta.update.updates.push(F);let M=o.moleculeGraph.getRelationEntries({downstreamMoleculeKey:S.stringKey});if(M)for(let[X,{source:U}]of M)if(U===S.stringKey){let K=vo(X);Sf(o,K)}else A.push(U);let _=J.moleculeData.getRelatedKeys(S.stringKey);if(_)for(let X of _){let U=J.families.get(X),K=i(o,U,S.key);$.push([U.key,K]),Af(o,K)}if(J.moleculeGraph.delete(S.stringKey),J.moleculeJoins.delete(S.stringKey),J.moleculeData.delete(S.stringKey),!R)J.on.moleculeDisposal.next(F);J.molecules.delete(S.stringKey);let w=wF(new Error);o.disposalTraces.add({key:f,trace:w})}function Ef(o,T,f,S){let n=fo(f),A=C(o),$=A.molecules.get(n);if(!$){let w=o.disposalTraces.buffer.find((X)=>X?.key===n);return o.logger.error("\u274C","molecule",f,"claim failed:",`Could not allocate to ${n} in store "${o.config.name}".`,w?`
8
12
  ${n} was most recently disposed
9
- ${_.trace}`:`No previous disposal trace for ${n} was found.`),S}let F=s(o),J=A.molecules.get(F);if(!J){let _=T.disposalTraces.buffer.find((K)=>K?.key===F);return T.logger.error("\u274C","molecule",S,"claim failed:",`Could not allocate to ${F} in store "${T.config.name}".`,_?`
13
+ ${w.trace}`:`No previous disposal trace for ${n} was found.`),f}let F=fo(T),J=A.molecules.get(F);if(!J){let w=o.disposalTraces.buffer.find((X)=>X?.key===F);return o.logger.error("\u274C","molecule",f,"claim failed:",`Could not allocate to ${F} in store "${o.config.name}".`,w?`
10
14
  ${F} was most recently disposed
11
- ${_.trace}`:`No previous disposal trace for ${F} was found.`),S}let R=T.moleculeGraph.getRelationEntries({downstreamMoleculeKey:$.stringKey}).filter(([,{source:_}])=>_!==n).map(([_])=>tT(_));if(f)A.moleculeGraph.delete(n);A.moleculeGraph.set({upstreamMoleculeKey:J.stringKey,downstreamMoleculeKey:$.stringKey},{source:J.stringKey});let W={type:"molecule_transfer",key:$.key,from:R,to:[J.key]};if(WT(A)&&A.transactionMeta.phase==="building")A.transactionMeta.update.updates.push(W);return S}class e${store;constructor(T=a.STORE){this.store=T,u$("root",T)}allocate(T,o,S){return YS(this.store,T,o,S)}fuse(T,o,S){return VW(this.store,T,o,S)}deallocate(T){ES(this.store,T)}claim(T,o,S){return nf(this.store,T,o,S)}}class sn{store;realm;constructor(T=a.STORE){this.store=T,this.realm=new e$(T)}allocate(T,o,S){YS(this.store,T,o,S)}deallocate(T){ES(this.store,T)}claim(T,o,S){nf(this.store,T,o,S)}}function HS(T){return s$(a.STORE,T)}function AS(T){return d$(a.STORE,T)}function TA(...T){if(T.length===2)return RT(a.STORE,...T);return RT(a.STORE,...T)}var oA=(T)=>(o,S,f,n,...A)=>{console[T](`${o} ${S} "${f}" ${n}`,...A)},BW={error:oA("error"),info:oA("info"),warn:oA("warn")};class SA{logLevel;filter;logger;constructor(T,o,S=BW){this.logLevel=T;this.filter=o;this.logger=S}error=(...T)=>{if((this.filter?.(...T)??!0)&&this.logLevel!==null)this.logger.error(...T)};info=(...T)=>{if((this.filter?.(...T)??!0)&&this.logLevel==="info")this.logger.info(...T)};warn=(...T)=>{if((this.filter?.(...T)??!0)&&this.logLevel!=="error"&&this.logLevel!==null)this.logger.warn(...T)}}function rf(T){return Sf(a.STORE,T)}function Af(T){return fA(T,a.STORE)}class NT{a;b;cardinality;relations=new Map;contents=new Map;isAType;isBType;isContent;makeContentKey=(T,o)=>`${T}:${o}`;warn;getRelatedKeys(T){return this.relations.get(T)}addRelation(T,o){let S=this.relations.get(T),f=this.relations.get(o);if(S)S.add(o);else S=new Set([o]),this.relations.set(T,S);if(f)f.add(T);else f=new Set([T]),this.relations.set(o,f)}deleteRelation(T,o){let S=this.relations.get(T);if(S){if(S.delete(o),S.size===0)this.relations.delete(T);let f=this.relations.get(o);if(f){if(f.delete(T),f.size===0)this.relations.delete(o)}}}replaceRelationsUnsafely(T,o){this.relations.set(T,new Set(o));for(let S of o){let f=new Set().add(T);this.relations.set(S,f)}}replaceRelationsSafely(T,o){let S=this.relations.get(T),f=this.isAType?.(T)?T:void 0,n=f===void 0?T:void 0;if(S)for(let A of S){f??=A,n??=A;let $=this.relations.get(A);if($){if($.size===1)this.relations.delete(A);else $.delete(T);this.contents.delete(this.makeContentKey(f,n))}}this.relations.set(T,new Set(o));for(let A of o){let $=this.relations.get(A);if($)$.add(T);else $=new Set().add(T),this.relations.set(A,$)}}getContentInternal(T){return this.contents.get(T)}setContent(T,o){this.contents.set(T,o)}deleteContent(T){this.contents.delete(T)}constructor(T,o){if(this.a=T.between[0],this.b=T.between[1],this.cardinality=T.cardinality,!o?.externalStore)this.relations=new Map(T.relations?.map(([S,f])=>[S,new Set(f)])),this.contents=new Map(T.contents);if(this.isAType=o?.isAType??null,this.isBType=o?.isBType??null,this.isContent=o?.isContent??null,o?.makeContentKey)this.makeContentKey=o.makeContentKey;if(o?.externalStore){let S=o.externalStore;if(this.has=(f,n)=>S.has(f,n),this.addRelation=(f,n)=>{S.addRelation(f,n)},this.deleteRelation=(f,n)=>{S.deleteRelation(f,n)},this.replaceRelationsSafely=(f,n)=>{S.replaceRelationsSafely(f,n)},this.replaceRelationsUnsafely=(f,n)=>{S.replaceRelationsUnsafely(f,n)},this.getRelatedKeys=(f)=>S.getRelatedKeys(f),S.getContent)this.getContentInternal=(f)=>{return S.getContent(f)},this.setContent=(f,n)=>{S.setContent(f,n)},this.deleteContent=(f)=>{S.deleteContent(f)};for(let[f,n]of T.relations??[]){let A=this.isAType?.(f)?f:void 0,$=A===void 0?f:void 0;for(let F of n)A??=F,$??=F,this.addRelation(A,$)}for(let[f,n]of T.contents??[])this.setContent(f,n)}if(o?.warn)this.warn=o.warn}toJSON(){return{between:[this.a,this.b],cardinality:this.cardinality,relations:[...this.relations.entries()].map(([T,o])=>[T,[...o]]),contents:[...this.contents.entries()]}}set(...T){let o,S,f;switch(T.length){case 1:{let n=T[0];o=n[this.a],S=n[this.b],f=void 0;break}case 2:{let n=T[0];if(typeof n==="string")[o,S]=T;else o=n[this.a],S=n[this.b],f=T[1];break}default:{o=T[0],S=T[1],f=T[2];break}}switch(this.cardinality){case"1:1":{let n=this.getRelatedKey(o);if(n&&n!==S)this.delete(o,n)}case"1:n":{let n=this.getRelatedKey(S);if(n&&n!==o)this.delete(n,S)}}if(f){let n=this.makeContentKey(o,S);this.setContent(n,f)}return this.addRelation(o,S),this}delete(T,o){o=typeof o==="string"?o:T[this.b];let S=typeof T==="string"?T:T[this.a];if(S===void 0&&typeof o==="string"){let f=this.getRelatedKeys(o);if(f)for(let n of f)this.delete(n,o)}if(typeof S==="string"&&o===void 0){let f=this.getRelatedKeys(S);if(f)for(let n of f)this.delete(S,n)}if(typeof S==="string"&&typeof o==="string"){this.deleteRelation(S,o);let f=this.makeContentKey(S,o);this.deleteContent(f)}return this}getRelatedKey(T){let o=this.getRelatedKeys(T);if(o){if(o.size>1)this.warn?.(`${o.size} related keys were found for key "${T}": (${[...o].map((f)=>`"${f}"`).join(", ")}). Only one related key was expected.`);let S;for(let f of o){S=f;break}return S}}replaceRelations(T,o,S){let f=!Array.isArray(o),n=f?Object.keys(o):o;if(S?.reckless)this.replaceRelationsUnsafely(T,n);else this.replaceRelationsSafely(T,n);if(f)for(let A of n){let $=this.makeContentKey(T,A),F=o[A];this.setContent($,F)}return this}getContent(T,o){let S=this.makeContentKey(T,o);return this.getContentInternal(S)}getRelationEntries(T){let o=T[this.a],S=T[this.b];if(o!==void 0&&S===void 0){let f=this.getRelatedKeys(o);if(f)return[...f].map((n)=>{return[n,this.getContent(o,n)]})}if(o===void 0&&S!==void 0){let f=this.getRelatedKeys(S);if(f)return[...f].map((n)=>{return[n,this.getContent(n,S)]})}return[]}has(T,o){if(o)return this.getRelatedKeys(T)?.has(o)??!1;return this.relations.has(T)}}function hT(T){return"epoch"in T.transactionMeta}function WT(T){return"phase"in T.transactionMeta}var oF=(T)=>{let o=L(T);if(!WT(o)){T.logger.warn("\uD83D\uDC1E","transaction","???","abortTransaction called outside of a transaction. This is probably a bug in AtomIO.");return}T.logger.info("\uD83E\uDE82","transaction",o.transactionMeta.update.key,"Aborting transaction"),o.parent.child=null};var LW=(T)=>T[0].toUpperCase()+T.slice(1);function Yo(T){return T.type.split("_").map(LW).join(" ")}class bo extends Error{constructor(...T){let o=T[0],S=T.length===2?T[1]:T[2];if(T.length===2)super(`${Yo(o)} ${s(o.key)} not found in store "${S.config.name}".`);else{let f=T[1];super(`${Yo(o)} "${o.key}" member ${s(f)} not found in store "${S.config.name}".`)}}}function zS(T,o,S){return(...f)=>{let n=AT(T,S);if(n)return n.run(f,o);throw new bo(T,S)}}var Pf=(T)=>(o)=>T instanceof Function?T(o):T;var io=(T,o)=>{if(o.valueMap.has(T.key))return o.logger.info("\uD83D\uDCD6",T.type,T.key,"reading cached value"),SF(T,o);if(T.type==="selector"||T.type==="readonly_selector")return o.logger.info("\uD83E\uDDEE",T.type,T.key,"computing value"),T.get();let S=T.default instanceof Function?T.default():T.default;return o.logger.info("\uD83D\uDC81","atom",T.key,"could not find cached value; using default",S),T.default instanceof Function?T.default():T.default};var fF=(T,o)=>{if(T.operation.open){let S=performance.now();return T.logger.info("\u2757",o.type,o.key,`deferring setState at T-${S} until setState for "${T.operation.token.key}" is done`),S}T.operation={open:!0,done:new Set,prev:new Map,time:Date.now(),token:o},T.logger.info("\u2B55",o.type,o.key,`operation start in store "${T.config.name}"${!WT(T)?"":` ${T.transactionMeta.phase} "${T.transactionMeta.update.key}"`}`)},nF=(T)=>{if(T.operation.open)T.logger.info("\uD83D\uDD34",T.operation.token.type,T.operation.token.key,`operation done in store "${T.config.name}"`);T.operation={open:!1},T.on.operationClose.next(T.operation)},AF=(T,o)=>{if(!T.operation.open)return T.logger.error("\uD83D\uDC1E","unknown",o,"isDone called outside of an operation. This is probably a bug in AtomIO."),!0;return T.operation.done.has(o)},QS=(T,o)=>{if(!T.operation.open){T.logger.error("\uD83D\uDC1E","unknown",o,"markDone called outside of an operation. This is probably a bug in AtomIO.");return}T.operation.done.add(o)};var $F=(T,o,S)=>{switch(T.type){case"mutable_atom":S.logger.info("\uD83D\uDCE2",T.type,T.key,"is now (",o.newValue,") subscribers:",T.subject.subscribers);break;default:S.logger.info("\uD83D\uDCE2",T.type,T.key,"went (",o.oldValue,"->",o.newValue,") subscribers:",T.subject.subscribers)}T.subject.next(o)};var nA=(T,o)=>{let S=L(o),f=S.selectorAtoms.getRelatedKeys(T.key);if(S.logger.info("\uD83E\uDDF9",T.type,T.key,f?`evicting ${f.size} states downstream:`:"no downstream states",f??"to evict"),f){if(S.operation.open)S.logger.info("\uD83E\uDDF9",T.type,T.key,`[ ${[...S.operation.done].join(", ")} ] already done`);for(let n of f){if(AF(S,n))continue;FF(n,S),QS(S,n)}}};function CW(T,o){if(RF(o.newValue))return!1;if(T.includes("\uD83D\uDD0D"))return!1;return!0}var JF=(T,o,S)=>{let{key:f}=T,n=L(S);if(!WT(n)||n.transactionMeta.phase!=="building"){S.logger.error("\uD83D\uDC1E","atom",f,"stowUpdate called outside of a transaction. This is probably a bug.");return}if(!CW(f,o))return;let $={type:"atom_update",key:f,...o};if(T.family)$.family=T.family;n.transactionMeta.update.updates.push($),S.logger.info("\uD83D\uDCC1","atom",f,"stowed (",o.oldValue,"->",o.newValue,")")};var WF=(T,o,S)=>{let f=io(T,S),n=f;if(T.type==="mutable_atom"&&WT(S)){let{parent:$}=S;n=$f(T,$,S)}if(n=Pf(o)(n),S.logger.info("\uD83D\uDCDD","atom",T.key,"set to",n),n=Mo(T.key,n,T.subject,S),OF(T.key,S))MF(T.key,S);QS(S,T.key),nA(T,S);let A={oldValue:f,newValue:n};if(hT(S))$F(T,A,S);else if(S.parent){if(S.on.transactionApplying.state===null)JF(T,A,S);else if(T.key.startsWith("*")){let $=T.key.slice(1),F=S.atoms.get($),J=S.valueMap.get($);if(F.type==="mutable_atom"&&WT(S)){let{parent:W}=S;J=$f(F,W,S)}if(J.do(A.newValue)===null)nA(F,S)}}};var pf=(T,o,S)=>{switch(T.type){case"atom":case"mutable_atom":WF(T,o,S);break;case"selector":T.set(o);break}};function kF(T,o){if(o.family){let S=T.families.get(o.family.key);if(S)return S}}function VT(T,...o){let S,f,n,A;if(o.length===2){if(S=o[0],A=o[1],f=kF(T,S)??null,f)n=S.family?tT(S.family.subKey):null,S=i(T,f,n)}else f=o[0],n=o[1],A=o[2],S=i(T,f,n);if("counterfeit"in S&&"family"in S){let J=S.family.subKey,R=T.disposalTraces.buffer.find((W)=>W?.key===J);T.logger.error("\u274C",S.type,S.key,`could not be set because it was not found in the store "${T.config.name}".`,R?`This state was previously disposed:
12
- ${R.trace}`:"No previous disposal trace was found.");return}let $=fF(T,S);if($){let J=T.on.operationClose.subscribe(`waiting to set "${S.key}" at T-${$}`,()=>{J(),T.logger.info("\uD83D\uDFE2",S.type,S.key,`resuming deferred setState from T-${$}`),VT(T,S,A)});return}let F=AT(S,T);pf(F,A,T),nF(T)}function gf(T,o,S){let{key:f,newValue:n,oldValue:A}=o,$=T==="newValue"?n:A,F={key:f,type:"atom"};if(o.family)Object.assign(F,{family:o.family});VT(S,F,$)}function AA(T,o,S){switch(o){case"newValue":{yF(T,S);break}case"oldValue":{nS(S,T.token);break}}}function $A(T,o,S){switch(o){case"newValue":{nS(S,T.token);break}case"oldValue":{if(yF(T,S),T.subType==="atom")S.valueMap.set(T.token.key,T.value);break}}}function yF(T,o){let{family:S}=T.token;if(S){let f=o.families.get(S.key);if(f)i(o,f,tT(S.subKey))}}function _F(T,o,S){switch(o){case"newValue":YS(S,T.provenance,T.key);break;case"oldValue":ES(S,T.key);break}}function wF(T,o,S){switch(o){case"newValue":ES(S,T.key);break;case"oldValue":{let f=T.provenance.map(tT);YS(S,f,T.key);for(let[n,A]of T.values){let $=S.families.get(n);if($){i(S,$,T.key);let F=`${n}(${s(T.key)})`;S.valueMap.set(F,A)}}}break}}function XF(T,o,S){switch(o){case"newValue":{let f=T.to.length===1?T.to[0]:T.to;nf(S,f,T.key,"exclusive")}break;case"oldValue":{let f=T.from.length===1?T.from[0]:T.from;nf(S,f,T.key,"exclusive")}break}}function df(T,o,S){let f=T==="newValue"?o.updates:[...o.updates].reverse();for(let n of f)switch(n.type){case"atom_update":case"selector_update":gf(T,n,S);break;case"state_creation":AA(n,T,S);break;case"state_disposal":$A(n,T,S);break;case"molecule_creation":_F(n,T,S);break;case"molecule_disposal":wF(n,T,S);break;case"molecule_transfer":XF(n,T,S);break;case"transaction_update":df(T,n,S);break}}function KF(T,o,S){if(hT(S)&&T)S.transactionMeta.epoch.set(T,o)}function GF(T,o,S){if(!hT(S))return;let n=S.transactionMeta.actionContinuities.getRelatedKey(T);if(n!==void 0)S.transactionMeta.epoch.set(n,o)}var YF=(T,o)=>{let S=L(o),{parent:f}=S;if(f===null||!WT(S)||S.transactionMeta?.phase!=="building"){o.logger.warn("\uD83D\uDC1E","transaction","???","applyTransaction called outside of a transaction. This is probably a bug in AtomIO.");return}S.transactionMeta.phase="applying",S.transactionMeta.update.output=T,f.child=null,f.on.transactionApplying.next(S.transactionMeta);let{updates:n}=S.transactionMeta.update;if(o.logger.info("\uD83D\uDEC4","transaction",S.transactionMeta.update.key,`Applying transaction with ${n.length} updates:`,n),df("newValue",S.transactionMeta.update,f),hT(f))GF(S.transactionMeta.update.key,S.transactionMeta.update.epoch,f),AT({key:S.transactionMeta.update.key,type:"transaction"},o)?.subject.next(S.transactionMeta.update),o.logger.info("\uD83D\uDEEC","transaction",S.transactionMeta.update.key,"Finished applying transaction.");else if(WT(f))f.transactionMeta.update.updates.push(S.transactionMeta.update);f.on.transactionApplying.next(null)};function EF(T,o,S){if(!hT(S))return;let{epoch:n,actionContinuities:A}=S.transactionMeta;if(A.set(T,o),!n.has(T))n.set(T,-1)}function HF(T){return{store:T}}function RT(T,...o){let S,f,n;if(o.length===1)S=o[0];else f=o[0],n=o[1],S=i(T,f,n);if("counterfeit"in S&&"family"in S){f=T.families.get(S.family.key);let A=S.family.subKey,$=T.disposalTraces.buffer.find((F)=>F?.key===A);switch(T.logger.error("\u274C",S.type,S.key,`could not be retrieved because it was not found in the store "${T.config.name}".`,$?`This state was previously disposed:
13
- ${$.trace}`:"No previous disposal trace was found."),f.type){case"atom_family":case"mutable_atom_family":return T.defaults.get(f.key);case"selector_family":case"readonly_selector_family":{if(T.defaults.has(f.key))return T.defaults.get(S.family.key);let F=AT(f,T).default(A);return T.defaults.set(f.key,F),F}}}return io(AT(S,T),T)}class ko extends Map{source;deleted=new Set;constructor(T){super();this.source=T}get(T){if(super.has(T))return super.get(T);if(!this.deleted.has(T)&&this.source.has(T))return this.source.get(T);return}set(T,o){return this.deleted.delete(T),super.set(T,o)}hasOwn(T){return super.has(T)}has(T){return!this.deleted.has(T)&&(super.has(T)||this.source.has(T))}delete(T){return this.deleted.add(T),super.delete(T)}}var zF=(T,o,S,f)=>{let n=L(S),A={parent:n,child:null,on:n.on,loggers:n.loggers,logger:n.logger,config:n.config,atoms:new ko(n.atoms),atomsThatAreDefault:new Set(n.atomsThatAreDefault),families:new ko(n.families),joins:new ko(n.joins),operation:{open:!1},readonlySelectors:new ko(n.readonlySelectors),timelines:new ko(n.timelines),timelineTopics:new NT(n.timelineTopics.toJSON()),trackers:new Map,transactions:new ko(n.transactions),selectorAtoms:new NT(n.selectorAtoms.toJSON()),selectorGraph:new NT(n.selectorGraph.toJSON(),{makeContentKey:(...R)=>R.sort().join(":")}),selectors:new ko(n.selectors),valueMap:new ko(n.valueMap),defaults:n.defaults,disposalTraces:S.disposalTraces.copy(),molecules:new ko(n.molecules),moleculeGraph:new NT(n.moleculeGraph.toJSON(),{makeContentKey:n.moleculeGraph.makeContentKey}),moleculeData:new NT(n.moleculeData.toJSON(),{makeContentKey:n.moleculeData.makeContentKey}),moleculeJoins:new NT(n.moleculeJoins.toJSON(),{makeContentKey:n.moleculeJoins.makeContentKey}),miscResources:new ko(n.miscResources)},$=QF(T,S),F={phase:"building",update:{type:"transaction_update",key:T,id:f,epoch:$===void 0?Number.NaN:$+1,updates:[],params:o,output:void 0},toolkit:{get:(...R)=>RT(J,...R),set:(...R)=>{VT(J,...R)},run:(R,W=Zf())=>zS(R,W,J),find:(R,W)=>i(J,R,W),seek:(R,W)=>qT(J,R,W),json:(R)=>mT(J,R),dispose:(...R)=>{nS(J,...R)},env:()=>HF(J)}},J=Object.assign(A,{transactionMeta:F});return n.child=J,S.logger.info("\uD83D\uDEEB","transaction",T,"Building transaction with params:",o),J};function fA(T,o){let S={key:T.key,type:"transaction",run:(A,$)=>{let F=zF(T.key,A,o,$);try{let J=L(o),{toolkit:R}=F.transactionMeta,W=T.do(R,...A);return YF(W,J),W}catch(J){throw oF(f),o.logger.warn("\uD83D\uDCA5","transaction",T.key,"caught:",J),J}},install:(A)=>fA(T,A),subject:new ST},f=L(o);f.transactions.set(S.key,S);let n=no(S);return o.on.transactionCreation.next(n),n}function QF(T,o){let S=hT(o),f=S?o.transactionMeta.actionContinuities.getRelatedKey(T):void 0;return S&&f!==void 0?o.transactionMeta.epoch.get(f):void 0}class DF{parent=null;child=null;valueMap=new Map;defaults=new Map;atoms=new Map;selectors=new Map;readonlySelectors=new Map;atomsThatAreDefault=new Set;selectorAtoms=new NT({between:["selectorKey","atomKey"],cardinality:"n:n"});selectorGraph=new NT({between:["upstreamSelectorKey","downstreamSelectorKey"],cardinality:"n:n"},{makeContentKey:(...T)=>T.sort().join(":")});trackers=new Map;families=new Map;joins=new Map;transactions=new Map;transactionMeta={epoch:new Map,actionContinuities:new NT({between:["continuity","action"],cardinality:"1:n"})};timelines=new Map;timelineTopics=new NT({between:["timelineKey","topicKey"],cardinality:"1:n"});disposalTraces=new cf(100);molecules=new Map;moleculeJoins=new NT({between:["moleculeKey","joinKey"],cardinality:"n:n"},{makeContentKey:(...T)=>T.sort().join(":")});moleculeGraph=new NT({between:["upstreamMoleculeKey","downstreamMoleculeKey"],cardinality:"n:n"},{makeContentKey:(...T)=>T.sort().join(":")});moleculeData=new NT({between:["moleculeKey","stateFamilyKey"],cardinality:"n:n"},{makeContentKey:(...T)=>T.sort().join(":")});miscResources=new Map;on={atomCreation:new ST,atomDisposal:new ST,selectorCreation:new ST,selectorDisposal:new ST,timelineCreation:new ST,transactionCreation:new ST,transactionApplying:new an(null),operationClose:new ST,moleculeCreation:new ST,moleculeDisposal:new ST};operation={open:!1};config={name:"IMPLICIT_STORE",lifespan:"ephemeral"};loggers=[new SA("warn",(T,o,S)=>!S.includes("\uD83D\uDD0D"))];logger={error:(...T)=>{for(let o of this.loggers)o.error(...T)},info:(...T)=>{for(let o of this.loggers)o.info(...T)},warn:(...T)=>{for(let o of this.loggers)o.warn(...T)}};constructor(T,o=null){if(this.config={...o?.config,...T},o!==null){if(this.valueMap=new Map(o?.valueMap),this.operation={...o?.operation},hT(o))this.transactionMeta={epoch:new Map(o?.transactionMeta.epoch),actionContinuities:new NT(o?.transactionMeta.actionContinuities.toJSON())};for(let[,f]of o.families){if(f.internalRoles?.includes("mutable")||f.internalRoles?.includes("join"))continue;f.install(this)}let S=new Set;for(let[,f]of o.atoms){if(S.has(f.key))continue;if(f.install(this),f.type==="mutable_atom"){let n=mT(o,f),A=xo(f);S.add(n.key),S.add(A.key)}}for(let[,f]of o.readonlySelectors)f.install(this);for(let[,f]of o.selectors){if(S.has(f.key))continue;f.install(this)}for(let[,f]of o.transactions)f.install(this);for(let[,f]of o.timelines)f.install(this)}}}var a={get STORE(){if(!globalThis.ATOM_IO_IMPLICIT_STORE)globalThis.ATOM_IO_IMPLICIT_STORE=new DF({name:"IMPLICIT_STORE",lifespan:"ephemeral"});return globalThis.ATOM_IO_IMPLICIT_STORE}};function AT(T,o){let S,f=o;while(f!==null){switch(T.type){case"atom":case"mutable_atom":S=f.atoms.get(T.key);break;case"selector":S=f.selectors.get(T.key);break;case"readonly_selector":S=f.readonlySelectors.get(T.key);break;case"atom_family":case"mutable_atom_family":case"selector_family":case"readonly_selector_family":S=f.families.get(T.key);break;case"timeline":S=f.timelines.get(T.key);break;case"transaction":S=f.transactions.get(T.key);break}if(S)return S;f=f.child}throw new bo(T,o)}function UF(T,o,S){let f=T.families.get(o.key);if(f===void 0)throw new bo(o,T);let n=f(S),A=L(T);if(n.family){if(hT(A))switch(n.type){case"atom":case"mutable_atom":T.on.atomCreation.next(n);break;case"selector":case"readonly_selector":T.on.selectorCreation.next(n);break}else if(WT(A)&&A.on.transactionApplying.state===null)A.transactionMeta.update.updates.push({type:"state_creation",token:n})}return n}function qT(T,o,S){let f=s(S),n=`${o.key}(${f})`,A=L(T),$;switch(o.type){case"atom_family":case"mutable_atom_family":$=A.atoms.get(n);break;case"selector_family":$=A.selectors.get(n);break;case"readonly_selector_family":$=A.readonlySelectors.get(n);break}if($)return no($);return $}function i(T,o,S){let f=qT(T,o,S);if(f)return f;let n=s(S),A=T.molecules.get(n);if(!A&&T.config.lifespan==="immortal"){let $=l$(o,S);return T.logger.error("\u274C",$.type,$.key,`was not found in store "${T.config.name}"; returned a counterfeit token.`),$}if(f=UF(T,o,S),A)L(T).moleculeData.set(n,o.key);return f}function nS(T,...o){let S;if(o.length===1)S=o[0];else{let f=o[0],n=o[1];S=i(T,f,n)}try{AT(S,T)}catch(f){T.logger.error("\u274C",S.type,S.key,`could not be disposed because it was not found in the store "${T.config.name}".`);return}switch(S.type){case"atom":case"mutable_atom":FA(S,T);break;case"selector":case"readonly_selector":tF(S,T);break}}var lf=(T,o)=>L(o).atoms.has(T),IW=(T,o)=>L(o).selectors.has(T),jW=(T,o)=>L(o).readonlySelectors.has(T),VF=(T,o)=>lf(T,o)||IW(T,o)||jW(T,o);var uf=(T,o)=>{return L(o).selectorGraph.getRelationEntries({downstreamSelectorKey:T}).filter(([f,{source:n}])=>n!==T).map(([f,{source:n}])=>n).filter((f)=>VF(f,o))};var JA=(T,o,S)=>{let f=[],n=uf(T,S);while(n.length>0){let A=n.shift();if(o.has(A))continue;if(o.add(A),!lf(A,S))n.push(...uf(A,S));else if(!f.includes(A))f.push(A)}return f},BF=(T,o)=>{let S=T.key,f=uf(S,o),n=new Set;return f.flatMap((A)=>lf(A,o)?A:JA(A,n,o))};var LF=(T,o,S,f)=>{let n=L(f);if(o.type==="atom"||o.type==="mutable_atom")n.selectorAtoms.set({selectorKey:T,atomKey:o.key}),f.logger.info("\uD83D\uDD0D","selector",T,`discovers root atom "${o.key}"`);else{let A=JA(o.key,S,f);f.logger.info("\uD83D\uDD0D","selector",T,`discovers root atoms: [ ${A.map(($)=>`"${$}"`).join(", ")} ]`);for(let $ of A)n.selectorAtoms=n.selectorAtoms.set({selectorKey:T,atomKey:$})}S.add(o.key)};var ef=(T,o,S)=>({get:(...f)=>{let n=L(S),A;if(f.length===2){let[J,R]=f;A=i(S,J,R)}else[A]=f;let $=AT(A,S),F=io($,S);return S.logger.info("\uD83D\uDD0C","selector",T,`registers dependency ( "${A.key}" =`,F,")"),n.selectorGraph.set({upstreamSelectorKey:A.key,downstreamSelectorKey:T},{source:A.key}),LF(T,A,o,S),F},set:(...f)=>{let n,A;if(f.length===2)n=f[0],A=f[1];else{let J=f[0],R=f[1];A=f[2];let W=S.config.lifespan==="ephemeral"?i(S,J,R):qT(S,J,R);if(!W)throw new bo(J,R,S);n=W}let $=L(S),F=AT(n,$);pf(F,A,$)},find:(f,n)=>i(S,f,n),seek:(f,n)=>qT(S,f,n),json:(f)=>mT(S,f)});var of=(T,o,S)=>{let f=L(T),n=new ST,A=new Set,{get:$,find:F,seek:J,json:R}=ef(o.key,A,f),W=()=>{let H=o.get({get:$,find:F,seek:J,json:R});return Mo(o.key,H,n,L(T)),A.clear(),H},y={...o,subject:n,install:(H)=>of(H,o,S),get:W,type:"readonly_selector",...S&&{family:S}};f.readonlySelectors.set(o.key,y);let _=W();T.logger.info("\u2728",y.type,y.key,"=",_);let K={key:o.key,type:"readonly_selector"};if(S)K.family=S;return K};var Ff=(T,o,S)=>{let f=L(T),n=new ST,A=new Set,$=ef(o.key,A,f),{find:F,get:J,seek:R,json:W}=$,y={find:F,get:J,seek:R,json:W},_=(b=o.get,q=L(T))=>{let p=b(y);return Mo(o.key,p,n,q),A.clear(),p},H={...o,subject:n,install:(b)=>Ff(b,o,S),get:_,set:(b)=>{let q=L(T),p=_(o.get,q),G=Pf(b)(p);if(T.logger.info("\uD83D\uDCDD","selector",o.key,"set (",p,"->",G,")"),Mo(o.key,G,n,q),QS(q,o.key),hT(q))n.next({newValue:G,oldValue:p});o.set($,G)},type:"selector",...S&&{family:S}};f.selectors.set(o.key,H);let Y=_();T.logger.info("\u2728",H.type,H.key,"=",Y);let I={key:o.key,type:"selector"};if(S)I.family=S;return I};function Go(T,o){if("set"in o){let n=Ff(T,o,void 0);return T.on.selectorCreation.next(n),n}let f=of(T,o,void 0);return T.on.selectorCreation.next(f),f}function tF(T,o){let S=L(o),{key:f}=T,n=AT(T,S);if(!n.family)o.logger.error("\u274C","selector",f,"Standalone selectors cannot be disposed.");else{if(S.molecules.get(n.family.subKey))S.moleculeData.delete(n.family.subKey,n.family.key);switch(T.type){case"selector":{S.selectors.delete(f);let $=AT({key:n.family.key,type:"selector_family"},o)}break;case"readonly_selector":S.readonlySelectors.delete(f),AT({key:n.family.key,type:"readonly_selector_family"},o).subject.next({type:"state_disposal",subType:"selector",token:T});break}if(S.valueMap.delete(f),S.selectorAtoms.delete(f),S.selectorGraph.delete(f),o.logger.info("\uD83D\uDD25",T.type,f,"deleted"),WT(S)&&S.transactionMeta.phase==="building")S.transactionMeta.update.updates.push({type:"state_disposal",subType:"selector",token:T});else o.on.selectorDisposal.next(T)}}function ff(T,o,S){let f={key:o.key,type:"selector_family"},n=T.families.get(o.key);if(n)T.logger.error("\u2757","selector_family",o.key,`Overwriting an existing ${Yo(n)} "${n.key}" in store "${T.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let A=new ST,F=Object.assign((J)=>{let R=s(J),W={key:o.key,subKey:R},y=`${o.key}(${R})`,_=L(T),K=Ff(_,{key:y,get:o.get(J),set:o.set(J)},W);return A.next({type:"state_creation",token:K}),K},f,{internalRoles:S,subject:A,install:(J)=>ff(J,o),default:(J)=>{return o.get(J)({get:(...W)=>RT(T,...W),find:(W,y)=>i(T,W,y),seek:(W,y)=>qT(T,W,y),json:(W)=>mT(T,W)})}});return T.families.set(o.key,F),f}function CF(T,o,S=a.STORE){let f=ff(S,{key:`${T.key}:JSON`,get:(A)=>({get:$})=>{let F=$(T,A);return o.toJson(F)},set:(A)=>({set:$},F)=>{$(T,A,o.fromJson(F))}},["mutable","json"]);return AT(T,S).subject.subscribe(`store=${S.config.name}::json-selector-family`,(A)=>{if(A.token.family)qT(S,f,tT(A.token.family.subKey))}),f}var tT=(T)=>JSON.parse(T),s=(T)=>JSON.stringify(T),Sw=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];var IF=(T,o)=>{let S=L(o);if(S.operation.open)return S.operation.prev.get(T.key);return S.valueMap.get(T.key)};var OA=(T,o)=>{let S=L(o);return BF(T,o).map((n)=>{let A=S.atoms.get(n);if(A===void 0)throw new Error(`Atom "${n}", a dependency of selector "${T.key}", not found in store "${o.config.name}".`);return A.subject.subscribe(`${T.type}:${T.key}`,($)=>{o.logger.info("\uD83D\uDCE2",T.type,T.key,"root",n,"went",$.oldValue,"->",$.newValue);let F=IF(T,S),J=io(T,S);o.logger.info("\u2728",T.type,T.key,"went",F,"->",J),T.subject.next({newValue:J,oldValue:F})})})};function lT(T,o,S,f){function n(y){if(f.operation.open){let _=f.on.operationClose.subscribe(`state subscription ${S}`,()=>{_(),o(y)})}else o(y)}let A=AT(T,f);f.logger.info("\uD83D\uDC40",A.type,A.key,`Adding subscription "${S}"`);let $=A.type==="selector"||A.type==="readonly_selector",F=null,J=n;if($)F=OA(A,f),J=(y)=>{if(F)F.length=0,F.push(...OA(A,f));n(y)};let R=A.subject.subscribe(S,J);return()=>{if(f.logger.info("\uD83D\uDE48",A.type,A.key,`Removing subscription "${S}"`),R(),F)for(let y of F)y()}}var RA=(T,o,S,f)=>{let n=AT(T,f);f.logger.info("\uD83D\uDC40","timeline",T.key,`Adding subscription "${S}"`);let A=n.subject.subscribe(S,o);return()=>{f.logger.info("\uD83D\uDE48","timeline",T.key,`Removing subscription "${S}" from timeline`),A()}};var WA=(T,o,S,f)=>{let n=AT(T,f);f.logger.info("\uD83D\uDC40","transaction",T.key,`Adding subscription "${S}"`);let A=n.subject.subscribe(S,o);return()=>{f.logger.info("\uD83D\uDE48","transaction",T.key,`Removing subscription "${S}"`),A()}};class go{Update;initializeState(T,o){let S=`*${T.key}`;o.atoms.delete(S),o.valueMap.delete(S);let f=T.family?{key:`*${T.family.key}`,subKey:T.family.subKey}:void 0,n=fo(o,{key:S,default:null},f);if(o.parent?.valueMap.has(S)){let A=o.parent.valueMap.get(S);o.valueMap.set(S,A)}return n}unsubscribeFromInnerValue;unsubscribeFromState;observeCore(T,o,S){let f=`tracker:${S.config.name}:${WT(S)?S.transactionMeta.update.key:"main"}:${T.key}`,n=RT(S,T);this.unsubscribeFromInnerValue=n.subscribe(f,(A)=>{VT(S,o,A)}),this.unsubscribeFromState=lT(T,(A)=>{if(A.newValue!==A.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=A.newValue.subscribe(f,($)=>{VT(S,o,$)})},f,S)}updateCore(T,o,S){let f=`tracker:${S.config.name}:${WT(S)?S.transactionMeta.update.key:"main"}:${T.key}`;lT(o,({newValue:n,oldValue:A})=>{let $=S.timelineTopics.getRelatedKey(o.key);if($){if(S.timelines.get($)?.timeTraveling){let R=RA({key:$,type:"timeline"},(W)=>{R(),VT(S,T,(y)=>{if(W==="redo"&&n)y.do(n);else if(W==="undo"&&A)y.undo(A);return y})},f,S);return}}let F=S.on.operationClose.subscribe(f,()=>{F();let J=RT(S,T),R=n===null?-1:J.getUpdateNumber(n),W=R-J.cacheUpdateNumber;if(n&&W===1)VT(S,T,(y)=>(y.do(n),y));else S.logger.info("\u274C","mutable_atom",T.key,`could not be updated. Expected update number ${J.cacheUpdateNumber+1}, but got ${R}`)})},f,S)}mutableState;latestUpdateState;dispose;constructor(T,o){this.mutableState=T;let S=L(o);this.latestUpdateState=this.initializeState(T,S),this.observeCore(T,this.latestUpdateState,S),this.updateCore(T,this.latestUpdateState,S),S.trackers.set(T.key,this),this.dispose=()=>{this.unsubscribeFromInnerValue(),this.unsubscribeFromState(),S.trackers.delete(T.key)}}}function Jf(T,o,S){T.logger.info("\uD83D\uDD28","atom",o.key,`creating in store "${T.config.name}"`);let f=L(T),n=f.atoms.get(o.key);if(n&&n.type==="mutable_atom")return T.logger.error("\u274C","atom",o.key,"Tried to create atom, but it already exists in the store."),no(n);let A=new ST,$={...o,type:"mutable_atom",install:(R)=>{return R.logger.info("\uD83D\uDEE0\uFE0F","atom",o.key,`installing in store "${R.config.name}"`),Jf(R,o,S)},subject:A};if(S)$.family=S;let F=o.default();f.atoms.set($.key,$),af(o.key,T),Mo(o.key,F,A,f);let J=no($);if(o.effects){let R=0,W=[];for(let y of o.effects){let _=y({setSelf:(K)=>{VT(T,J,K)},onSet:(K)=>lT(J,K,`effect[${R}]`,T)});if(_)W.push(_);++R}$.cleanup=()=>{for(let y of W)y()}}if(new go(J,T),!S)g$(J,o,T);return J}class MA{Update;latestUpdateAtoms;mutableAtoms;constructor(T,o){let S=Lo(o,{key:`*${T.key}`,default:null},["mutable","updates"]);this.latestUpdateAtoms=AT(S,o),this.mutableAtoms=T,this.mutableAtoms.subject.subscribe(`store=${o.config.name}::tracker-atom-family`,(f)=>{if(f.token.family){let n=tT(f.token.family.subKey);qT(o,this.latestUpdateAtoms,n),new go(f.token,o)}}),this.latestUpdateAtoms.subject.subscribe(`store=${o.config.name}::tracker-atom-family`,(f)=>{if(f.token.family){let n=tT(f.token.family.subKey),A=qT(o,this.mutableAtoms,n);if(A)new go(A,o)}})}}function Tf(T,o,S){let f={key:o.key,type:"mutable_atom_family"},n=T.families.get(o.key);if(n)T.logger.error("\u2757","mutable_atom_family",o.key,`Overwriting an existing ${Yo(n)} "${n.key}" in store "${T.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let A=new ST,F=Object.assign((J)=>{let R=s(J),W={key:o.key,subKey:R},y=`${o.key}(${R})`,_=L(T),K={key:y,default:()=>o.default(J),toJson:o.toJson,fromJson:o.fromJson,mutable:!0};if(o.effects)K.effects=o.effects(J);let H=Jf(_,K,W);return A.next({type:"state_creation",token:H}),H},f,{subject:A,install:(J)=>Tf(J,o),toJson:o.toJson,fromJson:o.fromJson,internalRoles:S});return T.families.set(o.key,F),CF(F,o,T),new MA(F,T),f}var kA=(T,o)=>{let S=L(o),f=`${T.key}:JSON`;return S.families.get(f)};var mT=(T,o)=>{if(o.family){let f=L(T),A={key:`${o.family.key}:JSON`,type:"selector_family"},$=AT(A,f),F=JSON.parse(o.family.subKey);return i(T,$,F)}return{type:"selector",key:`${o.key}:JSON`}};var xo=(T)=>{let S={type:"atom",key:`*${T.key}`};if(T.family)S.family={key:`*${T.family.key}`,subKey:T.family.subKey};return S};function RF(T){return typeof T==="object"&&T!==null&&"do"in T&&"undo"in T&&"subscribe"in T}function $f(T,o,S){let f=o.valueMap.get(T.key),n=S.valueMap.get(T.key);if(f===n){if(f===void 0)return typeof T.default==="function"?T.default():T.default;o.logger.info("\uD83D\uDCC3","atom",T.key,"copying");let A=T.toJson(f),$=T.fromJson(A);return S.valueMap.set(T.key,$),new go(T,o),$}return n}function Mo(T,o,S,f){let n=f.valueMap.get(T);if(n instanceof sS)n.use(o);if(o instanceof Promise){let A=new sS(o);return f.valueMap.set(T,A),A.then(($)=>{Mo(T,$,S,f),S.next({newValue:$,oldValue:A})}).catch(($)=>{f.logger.error("\uD83D\uDCA5","state",T,"rejected:",$)}),A}return f.valueMap.set(T,o),o}var SF=(T,o)=>{let S=o.valueMap.get(T.key);if(T.type==="mutable_atom"&&WT(o)){let{parent:f}=o;S=$f(T,f,o)}return S},FF=(T,o)=>{let S=o.valueMap.get(T);if(S instanceof sS){let f=S,n=o.selectors.get(T)??o.readonlySelectors.get(T);if(n)f.use(n.get());return}if(o.operation.open)o.operation.prev.set(T,S);o.valueMap.delete(T),o.logger.info("\uD83D\uDDD1","state",T,"evicted")};var OF=(T,o)=>{return L(o).atomsThatAreDefault.has(T)},af=(T,o)=>{let S=L(o);S.atomsThatAreDefault=new Set(S.atomsThatAreDefault).add(T)},MF=(T,o)=>{let S=L(o);S.atomsThatAreDefault=new Set(L(o).atomsThatAreDefault),S.atomsThatAreDefault.delete(T)};function fo(T,o,S){T.logger.info("\uD83D\uDD28","atom",o.key,`creating in store "${T.config.name}"`);let f=L(T),n=f.atoms.get(o.key);if(n&&n.type==="atom")return T.logger.error("\u274C","atom",o.key,"Tried to create atom, but it already exists in the store."),no(n);let A=new ST,$={...o,type:"atom",install:(R)=>{return R.logger.info("\uD83D\uDEE0\uFE0F","atom",o.key,`installing in store "${R.config.name}"`),fo(R,o,S)},subject:A};if(S)$.family=S;let F=o.default;if(o.default instanceof Function)F=o.default();f.atoms.set($.key,$),af(o.key,T),Mo(o.key,F,A,f);let J=no($);if(o.effects){let R=0,W=[];for(let y of o.effects){let _=y({setSelf:(K)=>{VT(T,J,K)},onSet:(K)=>lT(J,K,`effect[${R}]`,T)});if(_)W.push(_);++R}$.cleanup=()=>{for(let y of W)y()}}return J}function s$(T,o){if("mutable"in o){let n=Jf(T,o,void 0);return T.on.atomCreation.next(n),n}let f=fo(T,o,void 0);return T.on.atomCreation.next(f),f}function FA(T,o){let S=L(o),{key:f,family:n}=T,A=AT(T,S);if(!n)o.logger.error("\u274C","atom",f,"Standalone atoms cannot be disposed.");else{A.cleanup?.();let $=o.valueMap.get(A.key),F=AT({key:n.key,type:"atom_family"},o),J={type:"state_disposal",subType:"atom",token:T,value:$};F.subject.next(J);let R=WT(S);if(S.atoms.delete(f),S.valueMap.delete(f),S.selectorAtoms.delete(f),S.atomsThatAreDefault.delete(f),o.timelineTopics.delete(f),T.type==="mutable_atom"){let W=xo(T);FA(W,o),o.trackers.delete(f)}if(o.logger.info("\uD83D\uDD25","atom",f,"deleted"),R&&S.transactionMeta.phase==="building"){let W=S.transactionMeta.update.updates.at(-1);if(!(W?.type==="molecule_disposal"&&W.values.some(([K])=>K===A.family?.key)))S.transactionMeta.update.updates.push(J)}else o.on.atomDisposal.next(T)}}function a$(T){let{stack:o}=T;if(o)return`
14
- `+o.split(`
15
- `)?.slice(1)?.join(`
16
- `);return""}var yA=(T)=>{let o=fo(T,{key:"\uD83D\uDD0D Atom Token Index (Internal)",default:()=>{let S=new Map;for(let[f,n]of T.atoms)if(!f.includes("\uD83D\uDD0D")){let A=no(n);if(n.family){let $=S.get(n.family.key);if(!$||!("familyMembers"in $))$={key:n.family.key,familyMembers:new Map},S.set(n.family.key,$);$.familyMembers.set(n.family.subKey,A)}else S.set(f,A)}return S},effects:[({setSelf:S})=>{T.on.atomCreation.subscribe("introspection",(f)=>{if(f.key.includes("\uD83D\uDD0D"))return;S((n)=>{if(f.family){let{key:A,subKey:$}=f.family,F=n.get(A);if(F===void 0||!("familyMembers"in F))F={key:A,familyMembers:new Map},n.set(A,F);F.familyMembers.set($,f)}else n.set(f.key,f);return n})}),T.on.atomDisposal.subscribe("introspection",(f)=>{S((n)=>{if(f.family){let{key:A,subKey:$}=f.family,F=n.get(A);if(F&&"familyMembers"in F){if(F.familyMembers.delete($),F.familyMembers.size===0)n.delete(A)}}else n.delete(f.key);return n})})}]},void 0);return Go(T,{key:"\uD83D\uDD0D Atom Token Index",get:({get:S})=>S(o)})};var _A=(T)=>{let o=fo(T,{key:"\uD83D\uDD0D Selector Token Index (Internal)",default:()=>{let S=new Map;for(let f of[T.readonlySelectors,T.selectors])for(let[n,A]of f)if(!n.includes("\uD83D\uDD0D")){let $=no(A);if(A.family){let F=S.get(A.family.key);if(!F||!("familyMembers"in F))F={key:A.family.key,familyMembers:new Map},S.set(A.family.key,F);F.familyMembers.set(A.family.subKey,$)}else S.set(n,$)}return S},effects:[({setSelf:S})=>{T.on.selectorCreation.subscribe("introspection",(f)=>{if(f.key.includes("\uD83D\uDD0D"))return;S((n)=>{if(f.family){let{key:A,subKey:$}=f.family,F=n.get(A);if(F===void 0||!("familyMembers"in F))F={key:A,familyMembers:new Map},n.set(A,F);F.familyMembers.set($,f)}else n.set(f.key,f);return n})}),T.on.selectorDisposal.subscribe("introspection",(f)=>{S((n)=>{if(f.family){let{key:A,subKey:$}=f.family,F=n.get(A);if(F&&"familyMembers"in F){if(F.familyMembers.delete($),F.familyMembers.size===0)n.delete(A)}}else n.delete(f.key);return n})})}]},void 0);return Go(T,{key:"\uD83D\uDD0D Selector Token Index",get:({get:S})=>S(o)})};class sf{supported;constructor(T){this.supported=T}refine(T){for(let[o,S]of Object.entries(this.supported))try{if(S(T)===!0&&S!==Boolean)return{type:o,data:T}}catch(f){try{if(T instanceof S)return{type:o,data:T}}catch(n){}}return null}}var wA=new sf({number:(T)=>typeof T==="number",string:(T)=>typeof T==="string",boolean:(T)=>typeof T==="boolean",null:(T)=>T===null});function XA(T){if(!T)return!1;return Object.getPrototypeOf(T)===Object.prototype}var KA=new sf({object:XA,array:(T)=>Array.isArray(T)}),mW=new sf({...wA.supported,...KA.supported}),DS=(T)=>{if(T===void 0)return"undefined";let o=mW.refine(T);if(o)return o.type;return Object.getPrototypeOf(T).constructor.name};class jF{store;auditorCreatedAt=performance.now();statesCreatedAt=new Map;atomIndex;selectorIndex;disposed=!1;unsubscribeFromAtomCreation;unsubscribeFromAtomDisposal;unsubscribeFromSelectorCreation;unsubscribeFromSelectorDisposal;constructor(T=a.STORE){this.store=T;this.atomIndex=yA(this.store),this.selectorIndex=_A(this.store),this.unsubscribeFromAtomCreation=this.store.on.atomCreation.subscribe(`auditor-${this.auditorCreatedAt}`,({key:o})=>{this.statesCreatedAt.set(o,performance.now()-this.auditorCreatedAt)}),this.unsubscribeFromAtomDisposal=this.store.on.atomDisposal.subscribe(`auditor-${this.auditorCreatedAt}`,({key:o})=>{this.statesCreatedAt.delete(o)}),this.unsubscribeFromSelectorCreation=this.store.on.selectorCreation.subscribe(`auditor-${this.auditorCreatedAt}`,({key:o})=>{this.statesCreatedAt.set(o,performance.now()-this.auditorCreatedAt)}),this.unsubscribeFromSelectorDisposal=this.store.on.selectorDisposal.subscribe(`auditor-${this.auditorCreatedAt}`,({key:o})=>{this.statesCreatedAt.delete(o)})}static DEFAULT_LIST_RESOURCES_PARAM={atomFamilies:!0,selectorFamilies:!0};listResources(T=jF.DEFAULT_LIST_RESOURCES_PARAM){if(this.disposed)throw new Error("This Auditor has been disposed");let o=TA(this.atomIndex),S=TA(this.selectorIndex),f=[...o.values()].filter((F)=>("familyMembers"in F)),n=[...S.values()].filter((F)=>("familyMembers"in F)),A=performance.now(),$=[];if(T.atomFamilies)for(let F of f){let J=F.familyMembers.values();for(let R of J){let y=this.statesCreatedAt.get(R.key)??this.auditorCreatedAt,_=A-y;$.push([R,_])}}if(T.selectorFamilies)for(let F of n){let J=F.familyMembers.values();for(let R of J){let y=this.statesCreatedAt.get(R.key)??this.auditorCreatedAt,_=A-y;$.push([R,_])}}return $}[Symbol.dispose](){this.unsubscribeFromAtomCreation(),this.unsubscribeFromAtomDisposal(),this.unsubscribeFromSelectorCreation(),this.unsubscribeFromSelectorDisposal(),this.disposed=!0}}var GA=(T,o)=>{let S=(f,n)=>{let $=((J,R)=>{let W=o(J,R);if(W)return W;return null})(f,n);if($?.jobComplete??$?.pathComplete)return $;let F=Array.isArray(n)?n.map((J,R)=>[R,J]):XA(n)?Object.entries(n):[];for(let[J,R]of F){let W=S([...f,J],R);if(W?.jobComplete)return W}return{}};S([],T)};function NW(T,o){return{summary:`${T<o?"+":"-"}${Math.abs(T-o)} (${T} \u2192 ${o})`}}function hW(T,o){return{summary:`${T.length<o.length?"+":"-"}${Math.abs(T.length-o.length)} ("${T}" \u2192 "${o}")`}}function bW(T,o){return{summary:`${T} \u2192 ${o}`}}function mF(T,o,S){let f="",n=[],A=[],$=[];return GA(T,(F,J)=>{let R;for(R of F){let W=o[R];if(W===void 0)A.push([R,JSON.stringify(J)]);else{let y=S(J,W);if(y.summary!=="No Change")$.push([R,y])}}}),GA(o,(F,J)=>{let R;for(R of F)if(T[R]===void 0)n.push([R,JSON.stringify(J)])}),f=`\uFF5E${$.length} \uFF0B${n.length} \uFF0D${A.length}`,{summary:f,added:n,removed:A,changed:$}}function xW(T,o,S){return mF(T,o,S)}class NF{leafRefinery;treeRefinery;leafDiffers;treeDiffers;constructor(T,o,S){this.leafRefinery=T,this.treeRefinery=o,this.leafDiffers={},this.treeDiffers={};for(let f of Object.keys(T.supported)){let n=S[f];this.leafDiffers[f]=n}for(let f of Object.keys(o.supported)){let n=S[f];this.treeDiffers[f]=n}}diff(T,o){if(T===o)return{summary:"No Change"};let S=this.leafRefinery.refine(T)??this.treeRefinery.refine(T),f=this.leafRefinery.refine(o)??this.treeRefinery.refine(o);if(S!==null&&f!==null){if(S.type===f.type){if(S.type in this.leafDiffers)return this.leafDiffers[S.type](S.data,f.data);if(S.type in this.treeDiffers)return this.treeDiffers[S.type](S.data,f.data,(F,J)=>this.diff(F,J))}}let n=DS(T),A=DS(o);if(n===A)return{summary:`${n} \u2192 ${A}`};return{summary:`Type change: ${n} \u2192 ${A}`}}}var _K=new NF(wA,KA,{number:NW,string:hW,boolean:bW,null:()=>({summary:"No Change"}),object:mF,array:xW});class bT extends Set{mode="record";subject=new ST;cacheLimit=0;cache=[];cacheIdx=-1;cacheUpdateNumber=-1;constructor(T,o=0){super(T);if(T instanceof bT)this.parent=T,this.cacheUpdateNumber=T.cacheUpdateNumber;if(o)this.cacheLimit=o,this.cache=new Array(o),this.subscribe("auto cache",(S)=>{this.cacheIdx++,this.cacheIdx%=this.cacheLimit,this.cache[this.cacheIdx]=S})}toJSON(){return{members:[...this],cache:this.cache,cacheLimit:this.cacheLimit,cacheIdx:this.cacheIdx,cacheUpdateNumber:this.cacheUpdateNumber}}static fromJSON(T){let o=new bT(T.members,T.cacheLimit);return o.cache=T.cache,o.cacheIdx=T.cacheIdx,o.cacheUpdateNumber=T.cacheUpdateNumber,o}add(T){let o=super.add(T);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`add:${s(T)}`);return o}clear(){let T=this.mode==="record"?[...this]:null;if(super.clear(),T)this.cacheUpdateNumber++,this.emit(`clear:${JSON.stringify(T)}`)}delete(T){let o=super.delete(T);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`del:${s(T)}`);return o}parent;child=null;transactionUpdates=null;transaction(T){this.mode="transaction",this.transactionUpdates=[],this.child=new bT(this);let o=this.child._subscribe("transaction",(S)=>{this.transactionUpdates?.push(S)});try{if(T(this.child)){for(let f of this.transactionUpdates)this.doStep(f);this.cacheUpdateNumber++,this.emit(`tx:${this.transactionUpdates.join(";")}`)}}catch(S){throw console.error("Failed to apply transaction to SetRTX:",S),S}finally{o(),this.child=null,this.transactionUpdates=null,this.mode="record"}}_subscribe(T,o){return this.subject.subscribe(T,o)}subscribe(T,o){return this.subject.subscribe(T,(S)=>{o(`${this.cacheUpdateNumber}=${S}`)})}emit(T){this.subject.next(T)}doStep(T){let o=T.indexOf(":"),S=T.substring(0,o),f=T.substring(o+1);switch(S){case"add":this.add(JSON.parse(f));break;case"clear":this.clear();break;case"del":this.delete(JSON.parse(f));break;case"tx":for(let n of f.split(";"))this.doStep(n)}}getUpdateNumber(T){let o=T.indexOf("=");return Number(T.substring(0,o))}do(T){let o=T.indexOf("="),S=Number(T.substring(0,o)),f=S-this.cacheUpdateNumber;if(f>0){if(f===1){this.mode="playback";let A=T.substring(o+1);return this.doStep(A),this.mode="record",this.cacheUpdateNumber=S,null}return this.cacheUpdateNumber+1}if(Math.abs(f)<this.cacheLimit){let A=this.cacheIdx+f;if(this.cache[A]===T)return null;this.mode="playback";let F=!1;while(!F){this.cacheIdx%=this.cacheLimit;let R=this.cache[this.cacheIdx];if(this.cacheIdx--,!R)return"OUT_OF_RANGE";this.undo(R),F=this.cacheIdx===A-1}let J=T.substring(o+1);return this.doStep(J),this.mode="record",this.cacheUpdateNumber=S,null}return"OUT_OF_RANGE"}undoStep(T){let o=T.indexOf(":"),S=T.substring(0,o),f=T.substring(o+1);switch(S){case"add":this.delete(JSON.parse(f));break;case"del":this.add(JSON.parse(f));break;case"clear":{let n=JSON.parse(f);for(let A of n)this.add(A);break}case"tx":{let n=f.split(";");for(let A=n.length-1;A>=0;A--)this.undoStep(n[A])}}}undo(T){let o=T.indexOf("=");if(Number(T.substring(0,o))===this.cacheUpdateNumber){this.mode="playback";let f=T.substring(o+1);return this.undoStep(f),this.mode="record",this.cacheUpdateNumber--,null}return this.cacheUpdateNumber}}function HT(T){return T[0].toUpperCase()+T.slice(1)}class YA{toolkit;options;defaultContent;molecules=new Map;relations;states;core;transact(T,o){let S=this.toolkit;this.toolkit=T,o(this),this.toolkit=S}store;realm;[Symbol.dispose](){}constructor(T,o,S=a.STORE){this.store=S,this.realm=new sn(S),this.options=T,this.defaultContent=o,this.store.miscResources.set(`join:${T.key}`,this),this.realm.allocate("root",T.key),this.toolkit={get:(...G)=>RT(S,...G),set:(...G)=>{VT(S,...G)},find:(...G)=>i(S,...G),seek:(...G)=>qT(S,...G),json:(G)=>mT(S,G)};let f=T.between[0],n=T.between[1],A=Tf(S,{key:`${T.key}/relatedKeys`,default:()=>new bT,mutable:!0,fromJson:(G)=>bT.fromJSON(G),toJson:(G)=>G.toJSON()},["join","relations"]);this.core={relatedKeysAtoms:A};let $=({get:G},D)=>G(A,D),F=({set:G},D,t)=>{if(!this.store.molecules.has(s(D)))this.realm.allocate(T.key,D);G(A,D,(U)=>U.add(t)),G(A,t,(U)=>U.add(D))},J=({set:G},D,t)=>{G(A,D,(U)=>{return U.delete(t),U}),G(A,t,(U)=>{return U.delete(D),U})},R=(G,D,t)=>{let{find:U,get:v,set:l}=G,E=U(A,D),TT=v(E);for(let Z of TT){if(t.includes(Z))continue;l(A,Z,(MT)=>{return MT.delete(D),MT})}l(E,(Z)=>{return Z.transaction((oT)=>{oT.clear();for(let MT of t){let CT=$(G,MT),So=CT.has(D);if(this.relations.cardinality==="1:n"){let No=[];for(let z of CT){if(z===D)continue;let c=$(G,z);if(c.delete(MT),c.size===0)No.push(z)}if(!So&&CT.size>0)CT.clear();for(let z of No){let c=[MT,z].sort(),FT=`"${c[0]}:${c[1]}"`;this.molecules.delete(FT)}}if(!So)CT.add(D);oT.add(MT)}return!0}),Z})},W=(G,D,t)=>{let{set:U}=G;U(A,D,(v)=>{return v.transaction((l)=>{for(let E of t)l.add(E);return!0}),v});for(let v of t)U(A,v,(l)=>{return l.add(D),l});return!0},y=(G,D,t)=>{let U=$(G,D);return t?U.has(t):U.size>0},_={getRelatedKeys:(G)=>$(this.toolkit,G),addRelation:(G,D)=>{this.store.moleculeJoins.set(G,T.key),this.store.moleculeJoins.set(D,T.key),F(this.toolkit,G,D)},deleteRelation:(G,D)=>{J(this.toolkit,G,D)},replaceRelationsSafely:(G,D)=>{R(this.toolkit,G,D)},replaceRelationsUnsafely:(G,D)=>{W(this.toolkit,G,D)},has:(G,D)=>y(this.toolkit,G,D)},K,H;if(o){H=Lo(S,{key:`${T.key}/content`,default:o},["join","content"]);let G=({get:U},v)=>U(H,v),D=({set:U},v,l)=>{U(H,v,l)};K=Object.assign(_,{getContent:(U)=>{return G(this.toolkit,U)},setContent:(U,v)=>{D(this.toolkit,U,v)},deleteContent:(U)=>{this.realm.deallocate(U)}})}else K=_;let Y=new NT(T,{externalStore:K,isAType:T.isAType,isBType:T.isBType,makeContentKey:(...G)=>{let[D,t]=G,U=G.sort(),v=`${U[0]}:${U[1]}`,l=S.molecules.get(s(D)),E=S.molecules.get(s(t));if(!l)this.realm.allocate(T.key,D);if(!E)this.realm.allocate(T.key,t);return this.realm.allocate(D,v,"all"),this.realm.claim(t,v),this.store.moleculeJoins.set(v,T.key),v}}),I=()=>ho(S,{key:`${T.key}/singleRelatedKey`,get:(G)=>({get:D})=>{let t=D(A,G);for(let U of t)return U;return null}},["join","keys"]),b=()=>{return ho(S,{key:`${T.key}/multipleRelatedKeys`,get:(G)=>({get:D})=>{let t=kA(A,S);return D(t,G).members}},["join","keys"])},q=()=>ho(S,{key:`${T.key}/singleRelatedEntry`,get:(G)=>({get:D})=>{let t=D(A,G);for(let U of t){let v=Y.isAType?.(G)?G:void 0,l=v===void 0?G:void 0;v??=U,l??=U;let E=Y.makeContentKey(v,l),TT=D(H,E);return[U,TT]}return null}},["join","entries"]),p=()=>ho(S,{key:`${T.key}/multipleRelatedEntries`,get:(G)=>({get:D})=>{let t=kA(A,S);return D(t,G).members.map((v)=>{let l=Y.isAType?.(G)?G:void 0,E=l===void 0?G:void 0;l??=v,E??=v;let TT=Y.makeContentKey(l,E),Z=D(H,TT);return[v,Z]})}},["join","entries"]);switch(T.cardinality){case"1:1":{let G=I(),D=`${f}KeyOf${HT(n)}`,t=`${n}KeyOf${HT(f)}`,U={[D]:G,[t]:G},v;if(o){let l=q(),E=`${f}EntryOf${HT(n)}`,TT=`${n}EntryOf${HT(f)}`,Z={[E]:l,[TT]:l};v=Object.assign(U,Z)}else v=U;this.relations=Y,this.states=v;break}case"1:n":{let G=I(),D=b(),t=`${f}KeyOf${HT(n)}`,U=`${n}KeysOf${HT(f)}`,v={[t]:G,[U]:D},l;if(o){let E=q(),TT=p(),Z=`${f}EntryOf${HT(n)}`,oT=`${n}EntriesOf${HT(f)}`,MT={[Z]:E,[oT]:TT};l=Object.assign(v,MT)}else l=v;this.relations=Y,this.states=l;break}default:{let G=b(),D=`${f}KeysOf${HT(n)}`,t=`${n}KeysOf${HT(f)}`,U={[D]:G,[t]:G},v;if(o){let l=p(),E=`${f}EntriesOf${HT(n)}`,TT=`${n}EntriesOf${HT(f)}`,Z={[E]:l,[TT]:l};v=Object.assign(U,Z)}else v=U;this.relations=Y,this.states=v}}}}function Tn(T,o,S=a.STORE){return S.joins.set(T.key,new YA(T,o,S)),{key:T.key,type:"join",a:T.between[0],b:T.between[1],cardinality:T.cardinality}}function EA(T,o){let S=o.joins.get(T.key);if(S===void 0){let n=a.STORE.joins.get(T.key);if(n===void 0)throw new Error(`Join "${T.key}" not found in store "${o.config.name}"`);S=new YA(n.options,n.defaultContent,o),o.joins.set(T.key,S)}return S}function HA(T,o,S){let f=EA(T,S),n;switch(T.cardinality){case"1:1":{let A=`${T.a}KeyOf${HT(T.b)}`,$=`${T.b}KeyOf${HT(T.a)}`;n={get[A](){let J=f.states[A];return i(S,J,o)},get[$](){let J=f.states[$];return i(S,J,o)}};let F=`${T.a}EntryOf${HT(T.b)}`;if(F in f.states){let J=`${T.b}EntryOf${HT(T.a)}`;Object.assign(n,{get[F](){let R=f.states[F];return i(S,R,o)},get[J](){let R=f.states[J];return i(S,R,o)}})}break}case"1:n":{let A=`${T.a}KeyOf${HT(T.b)}`,$=`${T.b}KeysOf${HT(T.a)}`;n={get[A](){let J=f.states[A];return i(S,J,o)},get[$](){let J=f.states[$];return i(S,J,o)}};let F=`${T.a}EntryOf${HT(T.b)}`;if(F in f.states){let J=`${T.b}EntriesOf${HT(T.a)}`;Object.assign(n,{get[F](){let R=f.states[F];return i(S,R,o)},get[J](){let R=f.states[J];return i(S,R,o)}})}break}case"n:n":{let A=`${T.a}KeysOf${HT(T.b)}`,$=`${T.b}KeysOf${HT(T.a)}`;n={get[A](){let J=f.states[A];return i(S,J,o)},get[$](){let J=f.states[$];return i(S,J,o)}};let F=`${T.a}EntriesOf${HT(T.b)}`;if(F in f.states){let J=`${T.b}EntriesOf${HT(T.a)}`;Object.assign(n,{get[F](){let R=f.states[F];return i(S,R,o)},get[J](){let R=f.states[J];return i(S,R,o)}})}}}return n}function on(T,o,S){let f=EA(T,S),n=L(S);if(WT(n)){let{toolkit:A}=n.transactionMeta;f.transact(A,({relations:$})=>{o($)})}else o(f.relations)}function vW(T,o){return EA(T,o).core.relatedKeysAtoms}function hF(T){return vW(T,a.STORE)}class bF extends Map{set(T,o){if(this.has(T))return console.warn("Tried to set a key that already exists in an InvariantMap",{key:T,value:o}),this;return super.set(T,o)}clear(){throw new Error("Cannot clear an InvariantMap")}}class Sn{key;type="continuity";globals=[];actions=[];perspectives=[];constructor(T){this.key=T}static existing=new bF;static create(T,o){let S=new Sn(T),{type:f,globals:n,actions:A,perspectives:$}=o(S),F={type:f,key:T,globals:n,actions:A,perspectives:$};return Sn.existing.set(T,F),F}add(...T){switch(T[0].type){case"atom":case"mutable_atom":this.globals.push(...T);break;case"transaction":this.actions.push(...T);break;case"atom_family":{let[S,f]=T;this.perspectives.push({type:"realtime_perspective",resourceAtoms:S,viewAtoms:f})}break}return this}}function dK(T){let{key:o,config:S}=T,f=Sn.create(o,S),{actions:n}=f;for(let A of n)EF(o,A.key,a.STORE);return KF(o,-1,a.STORE),f}var sK=HS({key:"usersInRoomIndex",mutable:!0,default:()=>new bT,toJson:(T)=>T.toJSON(),fromJson:(T)=>bT.fromJSON(T)}),zA=HS({key:"roomIndex",default:()=>new bT,mutable:!0,toJson:(T)=>T.toJSON(),fromJson:(T)=>bT.fromJSON(T)}),qW={enteredAtEpoch:0},Rf=Tn({key:"usersInRooms",between:["room","user"],cardinality:"1:n",isAType:(T)=>typeof T==="string",isBType:(T)=>typeof T==="string"},qW),T5=rf({key:"usersInMyRoomView",get:(T)=>({find:o})=>{let S=hF(Rf);return[o(S,T)]}});import{spawn as ZW}from"child_process";class US{emit;listeners;globalListeners;handleEvent(T,...o){for(let f of this.globalListeners)f(T,...o);let S=this.listeners.get(T);if(S)for(let f of S)f(...o)}id="no_id_retrieved";constructor(T){this.emit=T;this.listeners=new Map,this.globalListeners=new Set}on(T,o){let S=this.listeners.get(T);if(S)S.add(o);else this.listeners.set(T,new Set([o]));return this}onAny(T){return this.globalListeners.add(T),this}off(T,o){let S=this.listeners.get(T);if(S)if(o)S.delete(o);else this.listeners.delete(T);return this}offAny(T){return this.globalListeners.delete(T),this}}class QA extends US{incompleteData="";unprocessedEvents=[];incompleteLog="";unprocessedLogs=[];id="#####";process;key;logger;handleLog(T){if(Array.isArray(T)){let[o,...S]=T;switch(o){case"i":this.logger.info(...S);break;case"w":this.logger.warn(...S);break;case"e":this.logger.error(...S);break}}}constructor(T,o,S){super((f,...n)=>{let A=JSON.stringify([f,...n])+"\x03",$=(F)=>{if(F.code==="EPIPE")console.error("EPIPE error during write",this.process.stdin);this.process.stdin.removeListener("error",$)};return this.process.stdin.once("error",$),this.process.stdin.write(A),this});if(this.process=T,this.key=o,this.logger=S??{info:(...f)=>{console.info(this.id,this.key,...f)},warn:(...f)=>{console.warn(this.id,this.key,...f)},error:(...f)=>{console.error(this.id,this.key,...f)}},this.process.stdout.on("data",(f)=>{let n=f.toString();if(n==="ALIVE")return;this.unprocessedEvents.push(...n.split("\x03"));let A=this.unprocessedEvents.shift();this.incompleteData+=A??"";try{if(this.incompleteData.startsWith("error"))console.log("\u2757",this.incompleteData);let $=tT(this.incompleteData);this.handleEvent(...$);while(this.unprocessedEvents.length>0){let F=this.unprocessedEvents.shift();if(F){if(this.unprocessedEvents.length===0)this.incompleteData=F;$=tT(F),this.handleEvent(...$)}}this.incompleteData=""}catch($){console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.warn(this.incompleteData),console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.error($)}}),this.process.stderr.on("data",(f)=>{let n=f.toString();this.unprocessedLogs.push(...n.split("\x03"));let A=this.unprocessedLogs.shift();this.incompleteLog+=A??"";try{let $=tT(this.incompleteLog);this.handleLog($);while(this.unprocessedLogs.length>0)if(this.incompleteLog=this.unprocessedLogs.shift()??"",this.incompleteLog)$=tT(this.incompleteLog),this.handleLog($)}catch($){console.error("\u274C\u274C\u274C"),console.error(this.incompleteLog),console.error($),console.error("\u274C\u274C\u274C\uFE0F")}}),T.pid)this.id=T.pid.toString()}}class xF extends US{in;out;id="no_id_retrieved";disposalFunctions=[];constructor(T){super((...o)=>{return this.out.next(o),this});this.id=T,this.in=new ST,this.out=new ST,this.in.subscribe("socket",(o)=>{this.handleEvent(...o)})}dispose(){for(let T of this.disposalFunctions)T()}}class DA extends US{incompleteData="";unprocessedEvents=[];relays;relayServices;process;id="#####";log(...T){this.process.stderr.write(s(T.map((o)=>o instanceof bT?`{ ${o.toJSON().members.join(" | ")} }`:o))+"\x03")}logger={info:(...T)=>{this.log("i",...T)},warn:(...T)=>{this.log("w",...T)},error:(...T)=>{this.log("e",...T)}};constructor(){super((T,...o)=>{let S=JSON.stringify([T,...o]);return this.process.stdout.write(S+"\x03"),this});if(this.process=process,this.process.stdin.resume(),this.relays=new Map,this.relayServices=[],this.process.stdin.on("data",(T)=>{let o=T.toString();this.unprocessedEvents.push(...o.split("\x03"));let S=this.unprocessedEvents.shift();this.incompleteData+=S??"";try{let f=tT(this.incompleteData);this.logger.info("\uD83C\uDFB0","received",f),this.handleEvent(...f);while(this.unprocessedEvents.length>0){let n=this.unprocessedEvents.shift();if(n){if(this.unprocessedEvents.length===0)this.incompleteData=n;let A=tT(n);this.handleEvent(...A)}}this.incompleteData=""}catch(f){if(f instanceof Error)this.logger.error("\u2757",f.message,f.cause,f.stack)}}),this.on("exit",()=>{this.logger.info("\uD83D\uDD25",this.id,'received "exit"'),process.exit(0)}),process.on("exit",(T)=>{this.logger.info("\uD83D\uDD25",this.id,`exited with code ${T}`)}),process.on("end",()=>{this.logger.info("\uD83D\uDD25",this.id,"ended"),process.exit(0)}),process.on("SIGTERM",()=>{this.logger.error("\uD83D\uDD25",this.id,"terminated"),process.exit(0)}),process.on("SIGINT",()=>{this.logger.error("\uD83D\uDD25",this.id,"interrupted"),process.exit(0)}),process.pid)this.id=process.pid?.toString();this.on("user-joins",(T)=>{this.logger.info("\uD83D\uDC64","user",T,"joined");let o=new xF(`user:${T}`);this.relays.set(T,o),this.logger.info("\uD83D\uDD17","attaching services:",`[${[...this.relayServices.keys()].join(", ")}]`);for(let S of this.relayServices){let f=S(o);if(f)o.disposalFunctions.push(f)}this.on(`user:${T}`,(...S)=>{o.in.next(S)}),o.out.subscribe("socket",(S)=>{this.emit(...S)})}),this.on("user-leaves",(T)=>{let o=this.relays.get(T);if(this.off(`relay:${T}`),o)o.dispose(),this.relays.delete(T)}),process.stdout.write("ALIVE")}relay(T){this.logger.info("\uD83D\uDD17","running relay method"),this.relayServices.push(T)}}var UA=AS({key:"roomArguments",default:["echo",["Hello World!"]]}),vF=rf({key:"room",get:(T)=>async({get:o,find:S})=>{let f=S(UA,T),n=o(f),[A,$]=n,F=await new Promise((J)=>{let R=ZW(A,$,{env:process.env}),W=(y)=>{if(y.toString()==="ALIVE")R.stdout.off("data",W),J(R)};R.stdout.on("data",W)});return new QA(F,T)}});var V5=Af({key:"createRoom",do:({get:T,set:o,find:S},f,n,A)=>{let $=A?[n,A]:[n],F=S(UA,f);o(F,$),o(zA,(W)=>W.add(f));let J=S(vF,f);return T(J)}}),B5=Af({key:"joinRoom",do:(T,o,S,f)=>{let n={enteredAtEpoch:f};return on(Rf,(A)=>{A.set({room:o,user:S},n)},T.env().store),n}}),L5=Af({key:"leaveRoom",do:(T,o,S)=>{on(Rf,(f)=>{f.delete({room:o,user:S})},T.env().store)}}),C5=Af({key:"destroyRoom",do:(T,o)=>{on(Rf,(S)=>{S.delete({room:o})},T.env().store),T.set(zA,(S)=>(S.delete(o),S))}});function tA(T,o){return o.map((S)=>{switch(S.type){case"transaction_update":{let f=tA(T,S.updates);return{...S,updates:f}}default:return S}}).filter((S)=>{switch(S.type){case"atom_update":case"selector_update":return T.includes(S.key);case"state_creation":return T.includes(S.token.key);case"molecule_creation":return!0;case"transaction_update":return!0}})}var m5=AS({key:"redactor",default:{occlude:(T)=>T}}),tS=AS({key:"unacknowledgedUpdates",default:()=>[]});var qF=AS({key:"sockets",default:null}),v5=HS({key:"socketsIndex",mutable:!0,default:()=>new bT,toJson:(T)=>T.toJSON(),fromJson:(T)=>bT.fromJSON(T)}),q5=HS({key:"usersIndex",mutable:!0,default:()=>new bT,toJson:(T)=>T.toJSON(),fromJson:(T)=>bT.fromJSON(T)}),VA=Tn({key:"usersOfSockets",between:["user","socket"],cardinality:"1:1",isAType:(T)=>T.startsWith("user::"),isBType:(T)=>T.startsWith("socket::")});function ZF(T,o,S,f){let n=o.key;return function A(){let $=[];for(let J of o.globals){let R=J.type==="mutable_atom"?mT(T,J):J,W=RT(T,R);$.push(R,W)}for(let J of o.perspectives){let{viewAtoms:R,resourceAtoms:W}=J,y=i(T,R,S),_=RT(T,y);T.logger.info("\uD83D\uDC41","atom",W.key,`${S} can see`,{viewAtoms:R,resourceAtoms:W,userView:_});for(let K of _){let H=K.type==="mutable_atom"?mT(T,K):K,Y=RT(T,H);$.push(H,Y)}}let F=hT(T)?T.transactionMeta.epoch.get(n)??null:null;f?.emit(`continuity-init:${n}`,F,$)}}function cF(T,o,S){let f=o.key;return function n(A){T.logger.info("\uD83D\uDECE\uFE0F","continuity",f,"received",A);let{key:$,id:F}=A,J=`tx-run:${$}:${F}`,R=`${J}:start`,W=`${J}:end`;performance.mark(R);try{zS({type:"transaction",key:$},F,T)(...A.params)}catch(_){if(_ instanceof Error)T.logger.error("\u274C","continuity",f,`failed to run transaction ${$} from ${S} with update ${F}`,_.message)}performance.mark(W);let y=performance.measure(J,R,W);T?.logger.info("\uD83D\uDE80","transaction",$,F,S,y.duration)}}function rF(T,o,S,f){let n=o.key;return function A($){if(T.logger.info("\uD83D\uDC4D","continuity",n,`${S} acknowledged epoch ${$}`),f[0]?.epoch===$)VT(T,tS,S,(J)=>{return J.shift(),T.logger.info("\uD83D\uDC4D","continuity",n,`${S} unacknowledged update queue now has`,J.length,"items"),J})}}function PF(T,o,S,f){let n=o.key,A=[];for(let $ of o.actions){let F=WA($,(J)=>{try{let R=o.globals.map((_)=>{if(_.type==="atom")return _.key;return xo(_).key}).concat(o.perspectives.flatMap((_)=>{let{viewAtoms:K}=_,H=i(T,K,S);return RT(T,H).map((I)=>{return I.type==="mutable_atom"?"*"+I.key:I.key})})),W=tA(R,J.updates),y={...J,updates:W};VT(T,tS,S,(_)=>{if(y)_.push(y),_.sort((K,H)=>K.epoch-H.epoch),T.logger.info("\uD83D\uDC4D","continuity",n,`${S} unacknowledged update queue now has`,_.length,"items");return _}),f?.emit(`tx-new:${n}`,y)}catch(R){if(R instanceof Error)T.logger.error("\u274C","continuity",n,`${S} failed to send update from transaction ${$.key} to ${S}`,R.message)}},`sync-continuity:${n}:${S}`,T);A.push(F)}return A}function pF(T,o,S,f){let n=o.key,A=[];for(let $ of o.perspectives){let{viewAtoms:F}=$,J=i(T,F,S),R=lT(J,({oldValue:W,newValue:y})=>{let _=W.map((I)=>I.key),K=y.map((I)=>I.key),H=W.filter((I)=>!K.includes(I.key)),Y=y.filter((I)=>!_.includes(I.key)).flatMap((I)=>{let b=I.type==="mutable_atom"?mT(T,I):I,q=RT(T,b);return[b,q]});if(T.logger.info("\uD83D\uDC41","atom",$.resourceAtoms.key,`${S} has a new perspective`,{oldKeys:_,newKeys:K,revealed:Y,concealed:H}),Y.length>0)f?.emit(`reveal:${n}`,Y);if(H.length>0)f?.emit(`conceal:${n}`,H)},`sync-continuity:${n}:${S}:perspective:${$.resourceAtoms.key}`,T);A.push(R)}return A}function wG({socket:T,store:o=a.STORE}){return function S(f){let n=T,A=f.key,$=HA(VA,`socket::${n.id}`,o).userKeyOfSocket,F=RT(o,$);if(!F)return o.logger.error("\u274C","continuity",A,`Tried to create a synchronizer for a socket (${n.id}) that is not connected to a user.`),()=>{};let J=HA(VA,F,o).socketKeyOfUser,R=lT(J,({newValue:b})=>{if(o.logger.info("\uD83D\uDC4B","continuity",A,`seeing ${F} on new socket ${b}`),b===null){o.logger.warn("\u274C","continuity",A,`User (${F}) is not connected to a socket, waiting for them to reappear.`);return}let q=i(o,qF,b);n=RT(o,q);for(let G of W)n?.emit(`tx-new:${A}`,G)},`sync-continuity:${A}:${F}`,o),W=RT(o,tS,F),y=[],_=pF(o,f,F,n),K=PF(o,f,F,n);y.push(..._,...K);let H=ZF(o,f,F,T);n.off(`get:${A}`,H),n.on(`get:${A}`,H);let Y=cF(o,f,F);n.off(`tx-run:${A}`,Y),n.on(`tx-run:${A}`,Y);let I=rF(o,f,F,W);return n?.on(`ack:${A}`,I),()=>{for(let b of y)b();n?.off(`ack:${A}`,I),n?.off(`get:${A}`,H),n?.off(`tx-run:${A}`,Y)}}}var{file:V1,serve:nk}=globalThis.Bun;import{readFileSync as $J}from"fs";import{resolve as mA}from"path";function cW(T,o){let S={},f=[];for(let n in T){let A=T[n],$=o[n],F=A["~standard"].validate($);if(F instanceof Promise)throw new Error(`Validation must be synchronous, but ${n} returned a Promise.`);if(F.issues){f.push(...F.issues.map((J)=>({...J,path:[n,...J.path??[]]})));continue}S[n]=F.value}if(f.length)return{issues:f};return{value:S}}function iF(T){let o=T.runtimeEnvStrict??T.runtimeEnv??process.env;if(T.emptyStringAsUndefined??!1){for(let[q,p]of Object.entries(o))if(p==="")delete o[q]}if(!!T.skipValidation)return o;let n=typeof T.client==="object"?T.client:{},A=typeof T.server==="object"?T.server:{},$=typeof T.shared==="object"?T.shared:{},F=T.isServer??(typeof window==="undefined"||("Deno"in window)),J=F?{...A,...$,...n}:{...n,...$},R=cW(J,o),W=T.onValidationError??((q)=>{throw console.error("\u274C Invalid environment variables:",q),new Error("Invalid environment variables")}),y=T.onInvalidAccess??(()=>{throw new Error("\u274C Attempted to access a server-side environment variable on the client")});if(R.issues)return W(R.issues);let _=(q)=>{if(!T.clientPrefix)return!0;return!q.startsWith(T.clientPrefix)&&!(q in $)},K=(q)=>{return F||!_(q)},H=(q)=>{return q==="__esModule"||q==="$$typeof"},Y=(T.extends??[]).reduce((q,p)=>{return Object.assign(q,p)},{}),I=Object.assign(R.value,Y);return new Proxy(I,{get(q,p){if(typeof p!=="string")return;if(H(p))return;if(!K(p))return y(p);return Reflect.get(q,p)}})}var $T;(function(T){T.assertEqual=(n)=>n;function o(n){}T.assertIs=o;function S(n){throw new Error}T.assertNever=S,T.arrayToEnum=(n)=>{let A={};for(let $ of n)A[$]=$;return A},T.getValidEnumValues=(n)=>{let A=T.objectKeys(n).filter((F)=>typeof n[n[F]]!=="number"),$={};for(let F of A)$[F]=n[F];return T.objectValues($)},T.objectValues=(n)=>{return T.objectKeys(n).map(function(A){return n[A]})},T.objectKeys=typeof Object.keys==="function"?(n)=>Object.keys(n):(n)=>{let A=[];for(let $ in n)if(Object.prototype.hasOwnProperty.call(n,$))A.push($);return A},T.find=(n,A)=>{for(let $ of n)if(A($))return $;return},T.isInteger=typeof Number.isInteger==="function"?(n)=>Number.isInteger(n):(n)=>typeof n==="number"&&isFinite(n)&&Math.floor(n)===n;function f(n,A=" | "){return n.map(($)=>typeof $==="string"?`'${$}'`:$).join(A)}T.joinValues=f,T.jsonStringifyReplacer=(n,A)=>{if(typeof A==="bigint")return A.toString();return A}})($T||($T={}));var LA;(function(T){T.mergeShapes=(o,S)=>{return{...o,...S}}})(LA||(LA={}));var N=$T.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),qo=(T)=>{switch(typeof T){case"undefined":return N.undefined;case"string":return N.string;case"number":return isNaN(T)?N.nan:N.number;case"boolean":return N.boolean;case"function":return N.function;case"bigint":return N.bigint;case"symbol":return N.symbol;case"object":if(Array.isArray(T))return N.array;if(T===null)return N.null;if(T.then&&typeof T.then==="function"&&T.catch&&typeof T.catch==="function")return N.promise;if(typeof Map!=="undefined"&&T instanceof Map)return N.map;if(typeof Set!=="undefined"&&T instanceof Set)return N.set;if(typeof Date!=="undefined"&&T instanceof Date)return N.date;return N.object;default:return N.unknown}},Q=$T.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"]),rW=(T)=>{return JSON.stringify(T,null,2).replace(/"([^"]+)":/g,"$1:")};class Jo extends Error{get errors(){return this.issues}constructor(T){super();this.issues=[],this.addIssue=(S)=>{this.issues=[...this.issues,S]},this.addIssues=(S=[])=>{this.issues=[...this.issues,...S]};let o=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,o);else this.__proto__=o;this.name="ZodError",this.issues=T}format(T){let o=T||function(n){return n.message},S={_errors:[]},f=(n)=>{for(let A of n.issues)if(A.code==="invalid_union")A.unionErrors.map(f);else if(A.code==="invalid_return_type")f(A.returnTypeError);else if(A.code==="invalid_arguments")f(A.argumentsError);else if(A.path.length===0)S._errors.push(o(A));else{let $=S,F=0;while(F<A.path.length){let J=A.path[F];if(F!==A.path.length-1)$[J]=$[J]||{_errors:[]};else $[J]=$[J]||{_errors:[]},$[J]._errors.push(o(A));$=$[J],F++}}};return f(this),S}static assert(T){if(!(T instanceof Jo))throw new Error(`Not a ZodError: ${T}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,$T.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(T=(o)=>o.message){let o={},S=[];for(let f of this.issues)if(f.path.length>0)o[f.path[0]]=o[f.path[0]]||[],o[f.path[0]].push(T(f));else S.push(T(f));return{formErrors:S,fieldErrors:o}}get formErrors(){return this.flatten()}}Jo.create=(T)=>{return new Jo(T)};var CS=(T,o)=>{let S;switch(T.code){case Q.invalid_type:if(T.received===N.undefined)S="Required";else S=`Expected ${T.expected}, received ${T.received}`;break;case Q.invalid_literal:S=`Invalid literal value, expected ${JSON.stringify(T.expected,$T.jsonStringifyReplacer)}`;break;case Q.unrecognized_keys:S=`Unrecognized key(s) in object: ${$T.joinValues(T.keys,", ")}`;break;case Q.invalid_union:S="Invalid input";break;case Q.invalid_union_discriminator:S=`Invalid discriminator value. Expected ${$T.joinValues(T.options)}`;break;case Q.invalid_enum_value:S=`Invalid enum value. Expected ${$T.joinValues(T.options)}, received '${T.received}'`;break;case Q.invalid_arguments:S="Invalid function arguments";break;case Q.invalid_return_type:S="Invalid function return type";break;case Q.invalid_date:S="Invalid date";break;case Q.invalid_string:if(typeof T.validation==="object")if("includes"in T.validation){if(S=`Invalid input: must include "${T.validation.includes}"`,typeof T.validation.position==="number")S=`${S} at one or more positions greater than or equal to ${T.validation.position}`}else if("startsWith"in T.validation)S=`Invalid input: must start with "${T.validation.startsWith}"`;else if("endsWith"in T.validation)S=`Invalid input: must end with "${T.validation.endsWith}"`;else $T.assertNever(T.validation);else if(T.validation!=="regex")S=`Invalid ${T.validation}`;else S="Invalid";break;case Q.too_small:if(T.type==="array")S=`Array must contain ${T.exact?"exactly":T.inclusive?"at least":"more than"} ${T.minimum} element(s)`;else if(T.type==="string")S=`String must contain ${T.exact?"exactly":T.inclusive?"at least":"over"} ${T.minimum} character(s)`;else if(T.type==="number")S=`Number must be ${T.exact?"exactly equal to ":T.inclusive?"greater than or equal to ":"greater than "}${T.minimum}`;else if(T.type==="date")S=`Date must be ${T.exact?"exactly equal to ":T.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(T.minimum))}`;else S="Invalid input";break;case Q.too_big:if(T.type==="array")S=`Array must contain ${T.exact?"exactly":T.inclusive?"at most":"less than"} ${T.maximum} element(s)`;else if(T.type==="string")S=`String must contain ${T.exact?"exactly":T.inclusive?"at most":"under"} ${T.maximum} character(s)`;else if(T.type==="number")S=`Number must be ${T.exact?"exactly":T.inclusive?"less than or equal to":"less than"} ${T.maximum}`;else if(T.type==="bigint")S=`BigInt must be ${T.exact?"exactly":T.inclusive?"less than or equal to":"less than"} ${T.maximum}`;else if(T.type==="date")S=`Date must be ${T.exact?"exactly":T.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(T.maximum))}`;else S="Invalid input";break;case Q.custom:S="Invalid input";break;case Q.invalid_intersection_types:S="Intersection results could not be merged";break;case Q.not_multiple_of:S=`Number must be a multiple of ${T.multipleOf}`;break;case Q.not_finite:S="Number must be finite";break;default:S=o.defaultError,$T.assertNever(T)}return{message:S}},uF=CS;function PW(T){uF=T}function fn(){return uF}var nn=(T)=>{let{data:o,path:S,errorMaps:f,issueData:n}=T,A=[...S,...n.path||[]],$={...n,path:A};if(n.message!==void 0)return{...n,path:A,message:n.message};let F="",J=f.filter((R)=>!!R).slice().reverse();for(let R of J)F=R($,{data:o,defaultError:F}).message;return{...n,path:A,message:F}},pW=[];function C(T,o){let S=fn(),f=nn({issueData:o,data:T.data,path:T.path,errorMaps:[T.common.contextualErrorMap,T.schemaErrorMap,S,S===CS?void 0:CS].filter((n)=>!!n)});T.common.issues.push(f)}class uT{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(T,o){let S=[];for(let f of o){if(f.status==="aborted")return d;if(f.status==="dirty")T.dirty();S.push(f.value)}return{status:T.value,value:S}}static async mergeObjectAsync(T,o){let S=[];for(let f of o){let n=await f.key,A=await f.value;S.push({key:n,value:A})}return uT.mergeObjectSync(T,S)}static mergeObjectSync(T,o){let S={};for(let f of o){let{key:n,value:A}=f;if(n.status==="aborted")return d;if(A.status==="aborted")return d;if(n.status==="dirty")T.dirty();if(A.status==="dirty")T.dirty();if(n.value!=="__proto__"&&(typeof A.value!=="undefined"||f.alwaysSet))S[n.value]=A.value}return{status:T.value,value:S}}}var d=Object.freeze({status:"aborted"}),BS=(T)=>({status:"dirty",value:T}),sT=(T)=>({status:"valid",value:T}),CA=(T)=>T.status==="aborted",IA=(T)=>T.status==="dirty",$S=(T)=>T.status==="valid",Mf=(T)=>typeof Promise!=="undefined"&&T instanceof Promise;function An(T,o,S,f){if(S==="a"&&!f)throw new TypeError("Private accessor was defined without a getter");if(typeof o==="function"?T!==o||!f:!o.has(T))throw new TypeError("Cannot read private member from an object whose class did not declare it");return S==="m"?f:S==="a"?f.call(T):f?f.value:o.get(T)}function eF(T,o,S,f,n){if(f==="m")throw new TypeError("Private method is not writable");if(f==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof o==="function"?T!==o||!n:!o.has(T))throw new TypeError("Cannot write private member to an object whose class did not declare it");return f==="a"?n.call(T,S):n?n.value=S:o.set(T,S),S}var x;(function(T){T.errToObj=(o)=>typeof o==="string"?{message:o}:o||{},T.toString=(o)=>typeof o==="string"?o:o===null||o===void 0?void 0:o.message})(x||(x={}));var Wf,Of;class Qo{constructor(T,o,S,f){this._cachedPath=[],this.parent=T,this.data=o,this._path=S,this._key=f}get path(){if(!this._cachedPath.length)if(this._key instanceof Array)this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var gF=(T,o)=>{if($S(o))return{success:!0,data:o.value};else{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;let S=new Jo(T.common.issues);return this._error=S,this._error}}}};function u(T){if(!T)return{};let{errorMap:o,invalid_type_error:S,required_error:f,description:n}=T;if(o&&(S||f))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(o)return{errorMap:o,description:n};return{errorMap:($,F)=>{var J,R;let{message:W}=T;if($.code==="invalid_enum_value")return{message:W!==null&&W!==void 0?W:F.defaultError};if(typeof F.data==="undefined")return{message:(J=W!==null&&W!==void 0?W:f)!==null&&J!==void 0?J:F.defaultError};if($.code!=="invalid_type")return{message:F.defaultError};return{message:(R=W!==null&&W!==void 0?W:S)!==null&&R!==void 0?R:F.defaultError}},description:n}}class e{get description(){return this._def.description}_getType(T){return qo(T.data)}_getOrReturnCtx(T,o){return o||{common:T.parent.common,data:T.data,parsedType:qo(T.data),schemaErrorMap:this._def.errorMap,path:T.path,parent:T.parent}}_processInputParams(T){return{status:new uT,ctx:{common:T.parent.common,data:T.data,parsedType:qo(T.data),schemaErrorMap:this._def.errorMap,path:T.path,parent:T.parent}}}_parseSync(T){let o=this._parse(T);if(Mf(o))throw new Error("Synchronous parse encountered promise.");return o}_parseAsync(T){let o=this._parse(T);return Promise.resolve(o)}parse(T,o){let S=this.safeParse(T,o);if(S.success)return S.data;throw S.error}safeParse(T,o){var S;let f={common:{issues:[],async:(S=o===null||o===void 0?void 0:o.async)!==null&&S!==void 0?S:!1,contextualErrorMap:o===null||o===void 0?void 0:o.errorMap},path:(o===null||o===void 0?void 0:o.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:T,parsedType:qo(T)},n=this._parseSync({data:T,path:f.path,parent:f});return gF(f,n)}"~validate"(T){var o,S;let f={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:T,parsedType:qo(T)};if(!this["~standard"].async)try{let n=this._parseSync({data:T,path:[],parent:f});return $S(n)?{value:n.value}:{issues:f.common.issues}}catch(n){if((S=(o=n===null||n===void 0?void 0:n.message)===null||o===void 0?void 0:o.toLowerCase())===null||S===void 0?void 0:S.includes("encountered"))this["~standard"].async=!0;f.common={issues:[],async:!0}}return this._parseAsync({data:T,path:[],parent:f}).then((n)=>$S(n)?{value:n.value}:{issues:f.common.issues})}async parseAsync(T,o){let S=await this.safeParseAsync(T,o);if(S.success)return S.data;throw S.error}async safeParseAsync(T,o){let S={common:{issues:[],contextualErrorMap:o===null||o===void 0?void 0:o.errorMap,async:!0},path:(o===null||o===void 0?void 0:o.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:T,parsedType:qo(T)},f=this._parse({data:T,path:S.path,parent:S}),n=await(Mf(f)?f:Promise.resolve(f));return gF(S,n)}refine(T,o){let S=(f)=>{if(typeof o==="string"||typeof o==="undefined")return{message:o};else if(typeof o==="function")return o(f);else return o};return this._refinement((f,n)=>{let A=T(f),$=()=>n.addIssue({code:Q.custom,...S(f)});if(typeof Promise!=="undefined"&&A instanceof Promise)return A.then((F)=>{if(!F)return $(),!1;else return!0});if(!A)return $(),!1;else return!0})}refinement(T,o){return this._refinement((S,f)=>{if(!T(S))return f.addIssue(typeof o==="function"?o(S,f):o),!1;else return!0})}_refinement(T){return new yo({schema:this,typeName:g.ZodEffects,effect:{type:"refinement",refinement:T}})}superRefine(T){return this._refinement(T)}constructor(T){this.spa=this.safeParseAsync,this._def=T,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:(o)=>this["~validate"](o)}}optional(){return zo.create(this,this._def)}nullable(){return Zo.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ho.create(this)}promise(){return WS.create(this,this._def)}or(T){return NS.create([this,T],this._def)}and(T){return hS.create(this,T,this._def)}transform(T){return new yo({...u(this._def),schema:this,typeName:g.ZodEffects,effect:{type:"transform",transform:T}})}default(T){let o=typeof T==="function"?T:()=>T;return new qS({...u(this._def),innerType:this,defaultValue:o,typeName:g.ZodDefault})}brand(){return new Fn({typeName:g.ZodBranded,type:this,...u(this._def)})}catch(T){let o=typeof T==="function"?T:()=>T;return new ZS({...u(this._def),innerType:this,catchValue:o,typeName:g.ZodCatch})}describe(T){return new this.constructor({...this._def,description:T})}pipe(T){return Kf.create(this,T)}readonly(){return cS.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var iW=/^c[^\s-]{8,}$/i,gW=/^[0-9a-z]+$/,dW=/^[0-9A-HJKMNP-TV-Z]{26}$/i,lW=/^[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,uW=/^[a-z0-9_-]{21}$/i,eW=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,aW=/^[-+]?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)?)??$/,sW=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,TO="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",BA,oO=/^(?:(?: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])$/,SO=/^(?:(?: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])$/,fO=/^(([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]))$/,nO=/^(([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])$/,AO=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,$O=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,aF="((\\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])))",FO=new RegExp(`^${aF}$`);function sF(T){let o="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";if(T.precision)o=`${o}\\.\\d{${T.precision}}`;else if(T.precision==null)o=`${o}(\\.\\d+)?`;return o}function JO(T){return new RegExp(`^${sF(T)}$`)}function TJ(T){let o=`${aF}T${sF(T)}`,S=[];if(S.push(T.local?"Z?":"Z"),T.offset)S.push("([+-]\\d{2}:?\\d{2})");return o=`${o}(${S.join("|")})`,new RegExp(`^${o}$`)}function RO(T,o){if((o==="v4"||!o)&&oO.test(T))return!0;if((o==="v6"||!o)&&fO.test(T))return!0;return!1}function WO(T,o){if(!eW.test(T))return!1;try{let[S]=T.split("."),f=S.replace(/-/g,"+").replace(/_/g,"/").padEnd(S.length+(4-S.length%4)%4,"="),n=JSON.parse(atob(f));if(typeof n!=="object"||n===null)return!1;if(!n.typ||!n.alg)return!1;if(o&&n.alg!==o)return!1;return!0}catch(S){return!1}}function OO(T,o){if((o==="v4"||!o)&&SO.test(T))return!0;if((o==="v6"||!o)&&nO.test(T))return!0;return!1}class Eo extends e{_parse(T){if(this._def.coerce)T.data=String(T.data);if(this._getType(T)!==N.string){let n=this._getOrReturnCtx(T);return C(n,{code:Q.invalid_type,expected:N.string,received:n.parsedType}),d}let S=new uT,f=void 0;for(let n of this._def.checks)if(n.kind==="min"){if(T.data.length<n.value)f=this._getOrReturnCtx(T,f),C(f,{code:Q.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),S.dirty()}else if(n.kind==="max"){if(T.data.length>n.value)f=this._getOrReturnCtx(T,f),C(f,{code:Q.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),S.dirty()}else if(n.kind==="length"){let A=T.data.length>n.value,$=T.data.length<n.value;if(A||$){if(f=this._getOrReturnCtx(T,f),A)C(f,{code:Q.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message});else if($)C(f,{code:Q.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message});S.dirty()}}else if(n.kind==="email"){if(!sW.test(T.data))f=this._getOrReturnCtx(T,f),C(f,{validation:"email",code:Q.invalid_string,message:n.message}),S.dirty()}else if(n.kind==="emoji"){if(!BA)BA=new RegExp(TO,"u");if(!BA.test(T.data))f=this._getOrReturnCtx(T,f),C(f,{validation:"emoji",code:Q.invalid_string,message:n.message}),S.dirty()}else if(n.kind==="uuid"){if(!lW.test(T.data))f=this._getOrReturnCtx(T,f),C(f,{validation:"uuid",code:Q.invalid_string,message:n.message}),S.dirty()}else if(n.kind==="nanoid"){if(!uW.test(T.data))f=this._getOrReturnCtx(T,f),C(f,{validation:"nanoid",code:Q.invalid_string,message:n.message}),S.dirty()}else if(n.kind==="cuid"){if(!iW.test(T.data))f=this._getOrReturnCtx(T,f),C(f,{validation:"cuid",code:Q.invalid_string,message:n.message}),S.dirty()}else if(n.kind==="cuid2"){if(!gW.test(T.data))f=this._getOrReturnCtx(T,f),C(f,{validation:"cuid2",code:Q.invalid_string,message:n.message}),S.dirty()}else if(n.kind==="ulid"){if(!dW.test(T.data))f=this._getOrReturnCtx(T,f),C(f,{validation:"ulid",code:Q.invalid_string,message:n.message}),S.dirty()}else if(n.kind==="url")try{new URL(T.data)}catch(A){f=this._getOrReturnCtx(T,f),C(f,{validation:"url",code:Q.invalid_string,message:n.message}),S.dirty()}else if(n.kind==="regex"){if(n.regex.lastIndex=0,!n.regex.test(T.data))f=this._getOrReturnCtx(T,f),C(f,{validation:"regex",code:Q.invalid_string,message:n.message}),S.dirty()}else if(n.kind==="trim")T.data=T.data.trim();else if(n.kind==="includes"){if(!T.data.includes(n.value,n.position))f=this._getOrReturnCtx(T,f),C(f,{code:Q.invalid_string,validation:{includes:n.value,position:n.position},message:n.message}),S.dirty()}else if(n.kind==="toLowerCase")T.data=T.data.toLowerCase();else if(n.kind==="toUpperCase")T.data=T.data.toUpperCase();else if(n.kind==="startsWith"){if(!T.data.startsWith(n.value))f=this._getOrReturnCtx(T,f),C(f,{code:Q.invalid_string,validation:{startsWith:n.value},message:n.message}),S.dirty()}else if(n.kind==="endsWith"){if(!T.data.endsWith(n.value))f=this._getOrReturnCtx(T,f),C(f,{code:Q.invalid_string,validation:{endsWith:n.value},message:n.message}),S.dirty()}else if(n.kind==="datetime"){if(!TJ(n).test(T.data))f=this._getOrReturnCtx(T,f),C(f,{code:Q.invalid_string,validation:"datetime",message:n.message}),S.dirty()}else if(n.kind==="date"){if(!FO.test(T.data))f=this._getOrReturnCtx(T,f),C(f,{code:Q.invalid_string,validation:"date",message:n.message}),S.dirty()}else if(n.kind==="time"){if(!JO(n).test(T.data))f=this._getOrReturnCtx(T,f),C(f,{code:Q.invalid_string,validation:"time",message:n.message}),S.dirty()}else if(n.kind==="duration"){if(!aW.test(T.data))f=this._getOrReturnCtx(T,f),C(f,{validation:"duration",code:Q.invalid_string,message:n.message}),S.dirty()}else if(n.kind==="ip"){if(!RO(T.data,n.version))f=this._getOrReturnCtx(T,f),C(f,{validation:"ip",code:Q.invalid_string,message:n.message}),S.dirty()}else if(n.kind==="jwt"){if(!WO(T.data,n.alg))f=this._getOrReturnCtx(T,f),C(f,{validation:"jwt",code:Q.invalid_string,message:n.message}),S.dirty()}else if(n.kind==="cidr"){if(!OO(T.data,n.version))f=this._getOrReturnCtx(T,f),C(f,{validation:"cidr",code:Q.invalid_string,message:n.message}),S.dirty()}else if(n.kind==="base64"){if(!AO.test(T.data))f=this._getOrReturnCtx(T,f),C(f,{validation:"base64",code:Q.invalid_string,message:n.message}),S.dirty()}else if(n.kind==="base64url"){if(!$O.test(T.data))f=this._getOrReturnCtx(T,f),C(f,{validation:"base64url",code:Q.invalid_string,message:n.message}),S.dirty()}else $T.assertNever(n);return{status:S.value,value:T.data}}_regex(T,o,S){return this.refinement((f)=>T.test(f),{validation:o,code:Q.invalid_string,...x.errToObj(S)})}_addCheck(T){return new Eo({...this._def,checks:[...this._def.checks,T]})}email(T){return this._addCheck({kind:"email",...x.errToObj(T)})}url(T){return this._addCheck({kind:"url",...x.errToObj(T)})}emoji(T){return this._addCheck({kind:"emoji",...x.errToObj(T)})}uuid(T){return this._addCheck({kind:"uuid",...x.errToObj(T)})}nanoid(T){return this._addCheck({kind:"nanoid",...x.errToObj(T)})}cuid(T){return this._addCheck({kind:"cuid",...x.errToObj(T)})}cuid2(T){return this._addCheck({kind:"cuid2",...x.errToObj(T)})}ulid(T){return this._addCheck({kind:"ulid",...x.errToObj(T)})}base64(T){return this._addCheck({kind:"base64",...x.errToObj(T)})}base64url(T){return this._addCheck({kind:"base64url",...x.errToObj(T)})}jwt(T){return this._addCheck({kind:"jwt",...x.errToObj(T)})}ip(T){return this._addCheck({kind:"ip",...x.errToObj(T)})}cidr(T){return this._addCheck({kind:"cidr",...x.errToObj(T)})}datetime(T){var o,S;if(typeof T==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:T});return this._addCheck({kind:"datetime",precision:typeof(T===null||T===void 0?void 0:T.precision)==="undefined"?null:T===null||T===void 0?void 0:T.precision,offset:(o=T===null||T===void 0?void 0:T.offset)!==null&&o!==void 0?o:!1,local:(S=T===null||T===void 0?void 0:T.local)!==null&&S!==void 0?S:!1,...x.errToObj(T===null||T===void 0?void 0:T.message)})}date(T){return this._addCheck({kind:"date",message:T})}time(T){if(typeof T==="string")return this._addCheck({kind:"time",precision:null,message:T});return this._addCheck({kind:"time",precision:typeof(T===null||T===void 0?void 0:T.precision)==="undefined"?null:T===null||T===void 0?void 0:T.precision,...x.errToObj(T===null||T===void 0?void 0:T.message)})}duration(T){return this._addCheck({kind:"duration",...x.errToObj(T)})}regex(T,o){return this._addCheck({kind:"regex",regex:T,...x.errToObj(o)})}includes(T,o){return this._addCheck({kind:"includes",value:T,position:o===null||o===void 0?void 0:o.position,...x.errToObj(o===null||o===void 0?void 0:o.message)})}startsWith(T,o){return this._addCheck({kind:"startsWith",value:T,...x.errToObj(o)})}endsWith(T,o){return this._addCheck({kind:"endsWith",value:T,...x.errToObj(o)})}min(T,o){return this._addCheck({kind:"min",value:T,...x.errToObj(o)})}max(T,o){return this._addCheck({kind:"max",value:T,...x.errToObj(o)})}length(T,o){return this._addCheck({kind:"length",value:T,...x.errToObj(o)})}nonempty(T){return this.min(1,x.errToObj(T))}trim(){return new Eo({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Eo({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Eo({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((T)=>T.kind==="datetime")}get isDate(){return!!this._def.checks.find((T)=>T.kind==="date")}get isTime(){return!!this._def.checks.find((T)=>T.kind==="time")}get isDuration(){return!!this._def.checks.find((T)=>T.kind==="duration")}get isEmail(){return!!this._def.checks.find((T)=>T.kind==="email")}get isURL(){return!!this._def.checks.find((T)=>T.kind==="url")}get isEmoji(){return!!this._def.checks.find((T)=>T.kind==="emoji")}get isUUID(){return!!this._def.checks.find((T)=>T.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((T)=>T.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((T)=>T.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((T)=>T.kind==="cuid2")}get isULID(){return!!this._def.checks.find((T)=>T.kind==="ulid")}get isIP(){return!!this._def.checks.find((T)=>T.kind==="ip")}get isCIDR(){return!!this._def.checks.find((T)=>T.kind==="cidr")}get isBase64(){return!!this._def.checks.find((T)=>T.kind==="base64")}get isBase64url(){return!!this._def.checks.find((T)=>T.kind==="base64url")}get minLength(){let T=null;for(let o of this._def.checks)if(o.kind==="min"){if(T===null||o.value>T)T=o.value}return T}get maxLength(){let T=null;for(let o of this._def.checks)if(o.kind==="max"){if(T===null||o.value<T)T=o.value}return T}}Eo.create=(T)=>{var o;return new Eo({checks:[],typeName:g.ZodString,coerce:(o=T===null||T===void 0?void 0:T.coerce)!==null&&o!==void 0?o:!1,...u(T)})};function MO(T,o){let S=(T.toString().split(".")[1]||"").length,f=(o.toString().split(".")[1]||"").length,n=S>f?S:f,A=parseInt(T.toFixed(n).replace(".","")),$=parseInt(o.toFixed(n).replace(".",""));return A%$/Math.pow(10,n)}class uo extends e{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(T){if(this._def.coerce)T.data=Number(T.data);if(this._getType(T)!==N.number){let n=this._getOrReturnCtx(T);return C(n,{code:Q.invalid_type,expected:N.number,received:n.parsedType}),d}let S=void 0,f=new uT;for(let n of this._def.checks)if(n.kind==="int"){if(!$T.isInteger(T.data))S=this._getOrReturnCtx(T,S),C(S,{code:Q.invalid_type,expected:"integer",received:"float",message:n.message}),f.dirty()}else if(n.kind==="min"){if(n.inclusive?T.data<n.value:T.data<=n.value)S=this._getOrReturnCtx(T,S),C(S,{code:Q.too_small,minimum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),f.dirty()}else if(n.kind==="max"){if(n.inclusive?T.data>n.value:T.data>=n.value)S=this._getOrReturnCtx(T,S),C(S,{code:Q.too_big,maximum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),f.dirty()}else if(n.kind==="multipleOf"){if(MO(T.data,n.value)!==0)S=this._getOrReturnCtx(T,S),C(S,{code:Q.not_multiple_of,multipleOf:n.value,message:n.message}),f.dirty()}else if(n.kind==="finite"){if(!Number.isFinite(T.data))S=this._getOrReturnCtx(T,S),C(S,{code:Q.not_finite,message:n.message}),f.dirty()}else $T.assertNever(n);return{status:f.value,value:T.data}}gte(T,o){return this.setLimit("min",T,!0,x.toString(o))}gt(T,o){return this.setLimit("min",T,!1,x.toString(o))}lte(T,o){return this.setLimit("max",T,!0,x.toString(o))}lt(T,o){return this.setLimit("max",T,!1,x.toString(o))}setLimit(T,o,S,f){return new uo({...this._def,checks:[...this._def.checks,{kind:T,value:o,inclusive:S,message:x.toString(f)}]})}_addCheck(T){return new uo({...this._def,checks:[...this._def.checks,T]})}int(T){return this._addCheck({kind:"int",message:x.toString(T)})}positive(T){return this._addCheck({kind:"min",value:0,inclusive:!1,message:x.toString(T)})}negative(T){return this._addCheck({kind:"max",value:0,inclusive:!1,message:x.toString(T)})}nonpositive(T){return this._addCheck({kind:"max",value:0,inclusive:!0,message:x.toString(T)})}nonnegative(T){return this._addCheck({kind:"min",value:0,inclusive:!0,message:x.toString(T)})}multipleOf(T,o){return this._addCheck({kind:"multipleOf",value:T,message:x.toString(o)})}finite(T){return this._addCheck({kind:"finite",message:x.toString(T)})}safe(T){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:x.toString(T)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:x.toString(T)})}get minValue(){let T=null;for(let o of this._def.checks)if(o.kind==="min"){if(T===null||o.value>T)T=o.value}return T}get maxValue(){let T=null;for(let o of this._def.checks)if(o.kind==="max"){if(T===null||o.value<T)T=o.value}return T}get isInt(){return!!this._def.checks.find((T)=>T.kind==="int"||T.kind==="multipleOf"&&$T.isInteger(T.value))}get isFinite(){let T=null,o=null;for(let S of this._def.checks)if(S.kind==="finite"||S.kind==="int"||S.kind==="multipleOf")return!0;else if(S.kind==="min"){if(o===null||S.value>o)o=S.value}else if(S.kind==="max"){if(T===null||S.value<T)T=S.value}return Number.isFinite(o)&&Number.isFinite(T)}}uo.create=(T)=>{return new uo({checks:[],typeName:g.ZodNumber,coerce:(T===null||T===void 0?void 0:T.coerce)||!1,...u(T)})};class eo extends e{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(T){if(this._def.coerce)try{T.data=BigInt(T.data)}catch(n){return this._getInvalidInput(T)}if(this._getType(T)!==N.bigint)return this._getInvalidInput(T);let S=void 0,f=new uT;for(let n of this._def.checks)if(n.kind==="min"){if(n.inclusive?T.data<n.value:T.data<=n.value)S=this._getOrReturnCtx(T,S),C(S,{code:Q.too_small,type:"bigint",minimum:n.value,inclusive:n.inclusive,message:n.message}),f.dirty()}else if(n.kind==="max"){if(n.inclusive?T.data>n.value:T.data>=n.value)S=this._getOrReturnCtx(T,S),C(S,{code:Q.too_big,type:"bigint",maximum:n.value,inclusive:n.inclusive,message:n.message}),f.dirty()}else if(n.kind==="multipleOf"){if(T.data%n.value!==BigInt(0))S=this._getOrReturnCtx(T,S),C(S,{code:Q.not_multiple_of,multipleOf:n.value,message:n.message}),f.dirty()}else $T.assertNever(n);return{status:f.value,value:T.data}}_getInvalidInput(T){let o=this._getOrReturnCtx(T);return C(o,{code:Q.invalid_type,expected:N.bigint,received:o.parsedType}),d}gte(T,o){return this.setLimit("min",T,!0,x.toString(o))}gt(T,o){return this.setLimit("min",T,!1,x.toString(o))}lte(T,o){return this.setLimit("max",T,!0,x.toString(o))}lt(T,o){return this.setLimit("max",T,!1,x.toString(o))}setLimit(T,o,S,f){return new eo({...this._def,checks:[...this._def.checks,{kind:T,value:o,inclusive:S,message:x.toString(f)}]})}_addCheck(T){return new eo({...this._def,checks:[...this._def.checks,T]})}positive(T){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:x.toString(T)})}negative(T){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:x.toString(T)})}nonpositive(T){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:x.toString(T)})}nonnegative(T){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:x.toString(T)})}multipleOf(T,o){return this._addCheck({kind:"multipleOf",value:T,message:x.toString(o)})}get minValue(){let T=null;for(let o of this._def.checks)if(o.kind==="min"){if(T===null||o.value>T)T=o.value}return T}get maxValue(){let T=null;for(let o of this._def.checks)if(o.kind==="max"){if(T===null||o.value<T)T=o.value}return T}}eo.create=(T)=>{var o;return new eo({checks:[],typeName:g.ZodBigInt,coerce:(o=T===null||T===void 0?void 0:T.coerce)!==null&&o!==void 0?o:!1,...u(T)})};class IS extends e{_parse(T){if(this._def.coerce)T.data=Boolean(T.data);if(this._getType(T)!==N.boolean){let S=this._getOrReturnCtx(T);return C(S,{code:Q.invalid_type,expected:N.boolean,received:S.parsedType}),d}return sT(T.data)}}IS.create=(T)=>{return new IS({typeName:g.ZodBoolean,coerce:(T===null||T===void 0?void 0:T.coerce)||!1,...u(T)})};class FS extends e{_parse(T){if(this._def.coerce)T.data=new Date(T.data);if(this._getType(T)!==N.date){let n=this._getOrReturnCtx(T);return C(n,{code:Q.invalid_type,expected:N.date,received:n.parsedType}),d}if(isNaN(T.data.getTime())){let n=this._getOrReturnCtx(T);return C(n,{code:Q.invalid_date}),d}let S=new uT,f=void 0;for(let n of this._def.checks)if(n.kind==="min"){if(T.data.getTime()<n.value)f=this._getOrReturnCtx(T,f),C(f,{code:Q.too_small,message:n.message,inclusive:!0,exact:!1,minimum:n.value,type:"date"}),S.dirty()}else if(n.kind==="max"){if(T.data.getTime()>n.value)f=this._getOrReturnCtx(T,f),C(f,{code:Q.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),S.dirty()}else $T.assertNever(n);return{status:S.value,value:new Date(T.data.getTime())}}_addCheck(T){return new FS({...this._def,checks:[...this._def.checks,T]})}min(T,o){return this._addCheck({kind:"min",value:T.getTime(),message:x.toString(o)})}max(T,o){return this._addCheck({kind:"max",value:T.getTime(),message:x.toString(o)})}get minDate(){let T=null;for(let o of this._def.checks)if(o.kind==="min"){if(T===null||o.value>T)T=o.value}return T!=null?new Date(T):null}get maxDate(){let T=null;for(let o of this._def.checks)if(o.kind==="max"){if(T===null||o.value<T)T=o.value}return T!=null?new Date(T):null}}FS.create=(T)=>{return new FS({checks:[],coerce:(T===null||T===void 0?void 0:T.coerce)||!1,typeName:g.ZodDate,...u(T)})};class kf extends e{_parse(T){if(this._getType(T)!==N.symbol){let S=this._getOrReturnCtx(T);return C(S,{code:Q.invalid_type,expected:N.symbol,received:S.parsedType}),d}return sT(T.data)}}kf.create=(T)=>{return new kf({typeName:g.ZodSymbol,...u(T)})};class jS extends e{_parse(T){if(this._getType(T)!==N.undefined){let S=this._getOrReturnCtx(T);return C(S,{code:Q.invalid_type,expected:N.undefined,received:S.parsedType}),d}return sT(T.data)}}jS.create=(T)=>{return new jS({typeName:g.ZodUndefined,...u(T)})};class mS extends e{_parse(T){if(this._getType(T)!==N.null){let S=this._getOrReturnCtx(T);return C(S,{code:Q.invalid_type,expected:N.null,received:S.parsedType}),d}return sT(T.data)}}mS.create=(T)=>{return new mS({typeName:g.ZodNull,...u(T)})};class JS extends e{constructor(){super(...arguments);this._any=!0}_parse(T){return sT(T.data)}}JS.create=(T)=>{return new JS({typeName:g.ZodAny,...u(T)})};class lo extends e{constructor(){super(...arguments);this._unknown=!0}_parse(T){return sT(T.data)}}lo.create=(T)=>{return new lo({typeName:g.ZodUnknown,...u(T)})};class Co extends e{_parse(T){let o=this._getOrReturnCtx(T);return C(o,{code:Q.invalid_type,expected:N.never,received:o.parsedType}),d}}Co.create=(T)=>{return new Co({typeName:g.ZodNever,...u(T)})};class yf extends e{_parse(T){if(this._getType(T)!==N.undefined){let S=this._getOrReturnCtx(T);return C(S,{code:Q.invalid_type,expected:N.void,received:S.parsedType}),d}return sT(T.data)}}yf.create=(T)=>{return new yf({typeName:g.ZodVoid,...u(T)})};class Ho extends e{_parse(T){let{ctx:o,status:S}=this._processInputParams(T),f=this._def;if(o.parsedType!==N.array)return C(o,{code:Q.invalid_type,expected:N.array,received:o.parsedType}),d;if(f.exactLength!==null){let A=o.data.length>f.exactLength.value,$=o.data.length<f.exactLength.value;if(A||$)C(o,{code:A?Q.too_big:Q.too_small,minimum:$?f.exactLength.value:void 0,maximum:A?f.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:f.exactLength.message}),S.dirty()}if(f.minLength!==null){if(o.data.length<f.minLength.value)C(o,{code:Q.too_small,minimum:f.minLength.value,type:"array",inclusive:!0,exact:!1,message:f.minLength.message}),S.dirty()}if(f.maxLength!==null){if(o.data.length>f.maxLength.value)C(o,{code:Q.too_big,maximum:f.maxLength.value,type:"array",inclusive:!0,exact:!1,message:f.maxLength.message}),S.dirty()}if(o.common.async)return Promise.all([...o.data].map((A,$)=>{return f.type._parseAsync(new Qo(o,A,o.path,$))})).then((A)=>{return uT.mergeArray(S,A)});let n=[...o.data].map((A,$)=>{return f.type._parseSync(new Qo(o,A,o.path,$))});return uT.mergeArray(S,n)}get element(){return this._def.type}min(T,o){return new Ho({...this._def,minLength:{value:T,message:x.toString(o)}})}max(T,o){return new Ho({...this._def,maxLength:{value:T,message:x.toString(o)}})}length(T,o){return new Ho({...this._def,exactLength:{value:T,message:x.toString(o)}})}nonempty(T){return this.min(1,T)}}Ho.create=(T,o)=>{return new Ho({type:T,minLength:null,maxLength:null,exactLength:null,typeName:g.ZodArray,...u(o)})};function VS(T){if(T instanceof QT){let o={};for(let S in T.shape){let f=T.shape[S];o[S]=zo.create(VS(f))}return new QT({...T._def,shape:()=>o})}else if(T instanceof Ho)return new Ho({...T._def,type:VS(T.element)});else if(T instanceof zo)return zo.create(VS(T.unwrap()));else if(T instanceof Zo)return Zo.create(VS(T.unwrap()));else if(T instanceof Io)return Io.create(T.items.map((o)=>VS(o)));else return T}class QT extends e{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let T=this._def.shape(),o=$T.objectKeys(T);return this._cached={shape:T,keys:o}}_parse(T){if(this._getType(T)!==N.object){let J=this._getOrReturnCtx(T);return C(J,{code:Q.invalid_type,expected:N.object,received:J.parsedType}),d}let{status:S,ctx:f}=this._processInputParams(T),{shape:n,keys:A}=this._getCached(),$=[];if(!(this._def.catchall instanceof Co&&this._def.unknownKeys==="strip")){for(let J in f.data)if(!A.includes(J))$.push(J)}let F=[];for(let J of A){let R=n[J],W=f.data[J];F.push({key:{status:"valid",value:J},value:R._parse(new Qo(f,W,f.path,J)),alwaysSet:J in f.data})}if(this._def.catchall instanceof Co){let J=this._def.unknownKeys;if(J==="passthrough")for(let R of $)F.push({key:{status:"valid",value:R},value:{status:"valid",value:f.data[R]}});else if(J==="strict"){if($.length>0)C(f,{code:Q.unrecognized_keys,keys:$}),S.dirty()}else if(J==="strip");else throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let J=this._def.catchall;for(let R of $){let W=f.data[R];F.push({key:{status:"valid",value:R},value:J._parse(new Qo(f,W,f.path,R)),alwaysSet:R in f.data})}}if(f.common.async)return Promise.resolve().then(async()=>{let J=[];for(let R of F){let W=await R.key,y=await R.value;J.push({key:W,value:y,alwaysSet:R.alwaysSet})}return J}).then((J)=>{return uT.mergeObjectSync(S,J)});else return uT.mergeObjectSync(S,F)}get shape(){return this._def.shape()}strict(T){return x.errToObj,new QT({...this._def,unknownKeys:"strict",...T!==void 0?{errorMap:(o,S)=>{var f,n,A,$;let F=(A=(n=(f=this._def).errorMap)===null||n===void 0?void 0:n.call(f,o,S).message)!==null&&A!==void 0?A:S.defaultError;if(o.code==="unrecognized_keys")return{message:($=x.errToObj(T).message)!==null&&$!==void 0?$:F};return{message:F}}}:{}})}strip(){return new QT({...this._def,unknownKeys:"strip"})}passthrough(){return new QT({...this._def,unknownKeys:"passthrough"})}extend(T){return new QT({...this._def,shape:()=>({...this._def.shape(),...T})})}merge(T){return new QT({unknownKeys:T._def.unknownKeys,catchall:T._def.catchall,shape:()=>({...this._def.shape(),...T._def.shape()}),typeName:g.ZodObject})}setKey(T,o){return this.augment({[T]:o})}catchall(T){return new QT({...this._def,catchall:T})}pick(T){let o={};return $T.objectKeys(T).forEach((S)=>{if(T[S]&&this.shape[S])o[S]=this.shape[S]}),new QT({...this._def,shape:()=>o})}omit(T){let o={};return $T.objectKeys(this.shape).forEach((S)=>{if(!T[S])o[S]=this.shape[S]}),new QT({...this._def,shape:()=>o})}deepPartial(){return VS(this)}partial(T){let o={};return $T.objectKeys(this.shape).forEach((S)=>{let f=this.shape[S];if(T&&!T[S])o[S]=f;else o[S]=f.optional()}),new QT({...this._def,shape:()=>o})}required(T){let o={};return $T.objectKeys(this.shape).forEach((S)=>{if(T&&!T[S])o[S]=this.shape[S];else{let n=this.shape[S];while(n instanceof zo)n=n._def.innerType;o[S]=n}}),new QT({...this._def,shape:()=>o})}keyof(){return oJ($T.objectKeys(this.shape))}}QT.create=(T,o)=>{return new QT({shape:()=>T,unknownKeys:"strip",catchall:Co.create(),typeName:g.ZodObject,...u(o)})};QT.strictCreate=(T,o)=>{return new QT({shape:()=>T,unknownKeys:"strict",catchall:Co.create(),typeName:g.ZodObject,...u(o)})};QT.lazycreate=(T,o)=>{return new QT({shape:T,unknownKeys:"strip",catchall:Co.create(),typeName:g.ZodObject,...u(o)})};class NS extends e{_parse(T){let{ctx:o}=this._processInputParams(T),S=this._def.options;function f(n){for(let $ of n)if($.result.status==="valid")return $.result;for(let $ of n)if($.result.status==="dirty")return o.common.issues.push(...$.ctx.common.issues),$.result;let A=n.map(($)=>new Jo($.ctx.common.issues));return C(o,{code:Q.invalid_union,unionErrors:A}),d}if(o.common.async)return Promise.all(S.map(async(n)=>{let A={...o,common:{...o.common,issues:[]},parent:null};return{result:await n._parseAsync({data:o.data,path:o.path,parent:A}),ctx:A}})).then(f);else{let n=void 0,A=[];for(let F of S){let J={...o,common:{...o.common,issues:[]},parent:null},R=F._parseSync({data:o.data,path:o.path,parent:J});if(R.status==="valid")return R;else if(R.status==="dirty"&&!n)n={result:R,ctx:J};if(J.common.issues.length)A.push(J.common.issues)}if(n)return o.common.issues.push(...n.ctx.common.issues),n.result;let $=A.map((F)=>new Jo(F));return C(o,{code:Q.invalid_union,unionErrors:$}),d}}get options(){return this._def.options}}NS.create=(T,o)=>{return new NS({options:T,typeName:g.ZodUnion,...u(o)})};var vo=(T)=>{if(T instanceof bS)return vo(T.schema);else if(T instanceof yo)return vo(T.innerType());else if(T instanceof xS)return[T.value];else if(T instanceof ao)return T.options;else if(T instanceof vS)return $T.objectValues(T.enum);else if(T instanceof qS)return vo(T._def.innerType);else if(T instanceof jS)return[void 0];else if(T instanceof mS)return[null];else if(T instanceof zo)return[void 0,...vo(T.unwrap())];else if(T instanceof Zo)return[null,...vo(T.unwrap())];else if(T instanceof Fn)return vo(T.unwrap());else if(T instanceof cS)return vo(T.unwrap());else if(T instanceof ZS)return vo(T._def.innerType);else return[]};class $n extends e{_parse(T){let{ctx:o}=this._processInputParams(T);if(o.parsedType!==N.object)return C(o,{code:Q.invalid_type,expected:N.object,received:o.parsedType}),d;let S=this.discriminator,f=o.data[S],n=this.optionsMap.get(f);if(!n)return C(o,{code:Q.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[S]}),d;if(o.common.async)return n._parseAsync({data:o.data,path:o.path,parent:o});else return n._parseSync({data:o.data,path:o.path,parent:o})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(T,o,S){let f=new Map;for(let n of o){let A=vo(n.shape[T]);if(!A.length)throw new Error(`A discriminator value for key \`${T}\` could not be extracted from all schema options`);for(let $ of A){if(f.has($))throw new Error(`Discriminator property ${String(T)} has duplicate value ${String($)}`);f.set($,n)}}return new $n({typeName:g.ZodDiscriminatedUnion,discriminator:T,options:o,optionsMap:f,...u(S)})}}function jA(T,o){let S=qo(T),f=qo(o);if(T===o)return{valid:!0,data:T};else if(S===N.object&&f===N.object){let n=$T.objectKeys(o),A=$T.objectKeys(T).filter((F)=>n.indexOf(F)!==-1),$={...T,...o};for(let F of A){let J=jA(T[F],o[F]);if(!J.valid)return{valid:!1};$[F]=J.data}return{valid:!0,data:$}}else if(S===N.array&&f===N.array){if(T.length!==o.length)return{valid:!1};let n=[];for(let A=0;A<T.length;A++){let $=T[A],F=o[A],J=jA($,F);if(!J.valid)return{valid:!1};n.push(J.data)}return{valid:!0,data:n}}else if(S===N.date&&f===N.date&&+T===+o)return{valid:!0,data:T};else return{valid:!1}}class hS extends e{_parse(T){let{status:o,ctx:S}=this._processInputParams(T),f=(n,A)=>{if(CA(n)||CA(A))return d;let $=jA(n.value,A.value);if(!$.valid)return C(S,{code:Q.invalid_intersection_types}),d;if(IA(n)||IA(A))o.dirty();return{status:o.value,value:$.data}};if(S.common.async)return Promise.all([this._def.left._parseAsync({data:S.data,path:S.path,parent:S}),this._def.right._parseAsync({data:S.data,path:S.path,parent:S})]).then(([n,A])=>f(n,A));else return f(this._def.left._parseSync({data:S.data,path:S.path,parent:S}),this._def.right._parseSync({data:S.data,path:S.path,parent:S}))}}hS.create=(T,o,S)=>{return new hS({left:T,right:o,typeName:g.ZodIntersection,...u(S)})};class Io extends e{_parse(T){let{status:o,ctx:S}=this._processInputParams(T);if(S.parsedType!==N.array)return C(S,{code:Q.invalid_type,expected:N.array,received:S.parsedType}),d;if(S.data.length<this._def.items.length)return C(S,{code:Q.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),d;if(!this._def.rest&&S.data.length>this._def.items.length)C(S,{code:Q.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),o.dirty();let n=[...S.data].map((A,$)=>{let F=this._def.items[$]||this._def.rest;if(!F)return null;return F._parse(new Qo(S,A,S.path,$))}).filter((A)=>!!A);if(S.common.async)return Promise.all(n).then((A)=>{return uT.mergeArray(o,A)});else return uT.mergeArray(o,n)}get items(){return this._def.items}rest(T){return new Io({...this._def,rest:T})}}Io.create=(T,o)=>{if(!Array.isArray(T))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Io({items:T,typeName:g.ZodTuple,rest:null,...u(o)})};class _f extends e{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(T){let{status:o,ctx:S}=this._processInputParams(T);if(S.parsedType!==N.object)return C(S,{code:Q.invalid_type,expected:N.object,received:S.parsedType}),d;let f=[],n=this._def.keyType,A=this._def.valueType;for(let $ in S.data)f.push({key:n._parse(new Qo(S,$,S.path,$)),value:A._parse(new Qo(S,S.data[$],S.path,$)),alwaysSet:$ in S.data});if(S.common.async)return uT.mergeObjectAsync(o,f);else return uT.mergeObjectSync(o,f)}get element(){return this._def.valueType}static create(T,o,S){if(o instanceof e)return new _f({keyType:T,valueType:o,typeName:g.ZodRecord,...u(S)});return new _f({keyType:Eo.create(),valueType:T,typeName:g.ZodRecord,...u(o)})}}class wf extends e{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(T){let{status:o,ctx:S}=this._processInputParams(T);if(S.parsedType!==N.map)return C(S,{code:Q.invalid_type,expected:N.map,received:S.parsedType}),d;let f=this._def.keyType,n=this._def.valueType,A=[...S.data.entries()].map(([$,F],J)=>{return{key:f._parse(new Qo(S,$,S.path,[J,"key"])),value:n._parse(new Qo(S,F,S.path,[J,"value"]))}});if(S.common.async){let $=new Map;return Promise.resolve().then(async()=>{for(let F of A){let J=await F.key,R=await F.value;if(J.status==="aborted"||R.status==="aborted")return d;if(J.status==="dirty"||R.status==="dirty")o.dirty();$.set(J.value,R.value)}return{status:o.value,value:$}})}else{let $=new Map;for(let F of A){let{key:J,value:R}=F;if(J.status==="aborted"||R.status==="aborted")return d;if(J.status==="dirty"||R.status==="dirty")o.dirty();$.set(J.value,R.value)}return{status:o.value,value:$}}}}wf.create=(T,o,S)=>{return new wf({valueType:o,keyType:T,typeName:g.ZodMap,...u(S)})};class RS extends e{_parse(T){let{status:o,ctx:S}=this._processInputParams(T);if(S.parsedType!==N.set)return C(S,{code:Q.invalid_type,expected:N.set,received:S.parsedType}),d;let f=this._def;if(f.minSize!==null){if(S.data.size<f.minSize.value)C(S,{code:Q.too_small,minimum:f.minSize.value,type:"set",inclusive:!0,exact:!1,message:f.minSize.message}),o.dirty()}if(f.maxSize!==null){if(S.data.size>f.maxSize.value)C(S,{code:Q.too_big,maximum:f.maxSize.value,type:"set",inclusive:!0,exact:!1,message:f.maxSize.message}),o.dirty()}let n=this._def.valueType;function A(F){let J=new Set;for(let R of F){if(R.status==="aborted")return d;if(R.status==="dirty")o.dirty();J.add(R.value)}return{status:o.value,value:J}}let $=[...S.data.values()].map((F,J)=>n._parse(new Qo(S,F,S.path,J)));if(S.common.async)return Promise.all($).then((F)=>A(F));else return A($)}min(T,o){return new RS({...this._def,minSize:{value:T,message:x.toString(o)}})}max(T,o){return new RS({...this._def,maxSize:{value:T,message:x.toString(o)}})}size(T,o){return this.min(T,o).max(T,o)}nonempty(T){return this.min(1,T)}}RS.create=(T,o)=>{return new RS({valueType:T,minSize:null,maxSize:null,typeName:g.ZodSet,...u(o)})};class LS extends e{constructor(){super(...arguments);this.validate=this.implement}_parse(T){let{ctx:o}=this._processInputParams(T);if(o.parsedType!==N.function)return C(o,{code:Q.invalid_type,expected:N.function,received:o.parsedType}),d;function S($,F){return nn({data:$,path:o.path,errorMaps:[o.common.contextualErrorMap,o.schemaErrorMap,fn(),CS].filter((J)=>!!J),issueData:{code:Q.invalid_arguments,argumentsError:F}})}function f($,F){return nn({data:$,path:o.path,errorMaps:[o.common.contextualErrorMap,o.schemaErrorMap,fn(),CS].filter((J)=>!!J),issueData:{code:Q.invalid_return_type,returnTypeError:F}})}let n={errorMap:o.common.contextualErrorMap},A=o.data;if(this._def.returns instanceof WS){let $=this;return sT(async function(...F){let J=new Jo([]),R=await $._def.args.parseAsync(F,n).catch((_)=>{throw J.addIssue(S(F,_)),J}),W=await Reflect.apply(A,this,R);return await $._def.returns._def.type.parseAsync(W,n).catch((_)=>{throw J.addIssue(f(W,_)),J})})}else{let $=this;return sT(function(...F){let J=$._def.args.safeParse(F,n);if(!J.success)throw new Jo([S(F,J.error)]);let R=Reflect.apply(A,this,J.data),W=$._def.returns.safeParse(R,n);if(!W.success)throw new Jo([f(R,W.error)]);return W.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...T){return new LS({...this._def,args:Io.create(T).rest(lo.create())})}returns(T){return new LS({...this._def,returns:T})}implement(T){return this.parse(T)}strictImplement(T){return this.parse(T)}static create(T,o,S){return new LS({args:T?T:Io.create([]).rest(lo.create()),returns:o||lo.create(),typeName:g.ZodFunction,...u(S)})}}class bS extends e{get schema(){return this._def.getter()}_parse(T){let{ctx:o}=this._processInputParams(T);return this._def.getter()._parse({data:o.data,path:o.path,parent:o})}}bS.create=(T,o)=>{return new bS({getter:T,typeName:g.ZodLazy,...u(o)})};class xS extends e{_parse(T){if(T.data!==this._def.value){let o=this._getOrReturnCtx(T);return C(o,{received:o.data,code:Q.invalid_literal,expected:this._def.value}),d}return{status:"valid",value:T.data}}get value(){return this._def.value}}xS.create=(T,o)=>{return new xS({value:T,typeName:g.ZodLiteral,...u(o)})};function oJ(T,o){return new ao({values:T,typeName:g.ZodEnum,...u(o)})}class ao extends e{constructor(){super(...arguments);Wf.set(this,void 0)}_parse(T){if(typeof T.data!=="string"){let o=this._getOrReturnCtx(T),S=this._def.values;return C(o,{expected:$T.joinValues(S),received:o.parsedType,code:Q.invalid_type}),d}if(!An(this,Wf,"f"))eF(this,Wf,new Set(this._def.values),"f");if(!An(this,Wf,"f").has(T.data)){let o=this._getOrReturnCtx(T),S=this._def.values;return C(o,{received:o.data,code:Q.invalid_enum_value,options:S}),d}return sT(T.data)}get options(){return this._def.values}get enum(){let T={};for(let o of this._def.values)T[o]=o;return T}get Values(){let T={};for(let o of this._def.values)T[o]=o;return T}get Enum(){let T={};for(let o of this._def.values)T[o]=o;return T}extract(T,o=this._def){return ao.create(T,{...this._def,...o})}exclude(T,o=this._def){return ao.create(this.options.filter((S)=>!T.includes(S)),{...this._def,...o})}}Wf=new WeakMap;ao.create=oJ;class vS extends e{constructor(){super(...arguments);Of.set(this,void 0)}_parse(T){let o=$T.getValidEnumValues(this._def.values),S=this._getOrReturnCtx(T);if(S.parsedType!==N.string&&S.parsedType!==N.number){let f=$T.objectValues(o);return C(S,{expected:$T.joinValues(f),received:S.parsedType,code:Q.invalid_type}),d}if(!An(this,Of,"f"))eF(this,Of,new Set($T.getValidEnumValues(this._def.values)),"f");if(!An(this,Of,"f").has(T.data)){let f=$T.objectValues(o);return C(S,{received:S.data,code:Q.invalid_enum_value,options:f}),d}return sT(T.data)}get enum(){return this._def.values}}Of=new WeakMap;vS.create=(T,o)=>{return new vS({values:T,typeName:g.ZodNativeEnum,...u(o)})};class WS extends e{unwrap(){return this._def.type}_parse(T){let{ctx:o}=this._processInputParams(T);if(o.parsedType!==N.promise&&o.common.async===!1)return C(o,{code:Q.invalid_type,expected:N.promise,received:o.parsedType}),d;let S=o.parsedType===N.promise?o.data:Promise.resolve(o.data);return sT(S.then((f)=>{return this._def.type.parseAsync(f,{path:o.path,errorMap:o.common.contextualErrorMap})}))}}WS.create=(T,o)=>{return new WS({type:T,typeName:g.ZodPromise,...u(o)})};class yo extends e{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===g.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(T){let{status:o,ctx:S}=this._processInputParams(T),f=this._def.effect||null,n={addIssue:(A)=>{if(C(S,A),A.fatal)o.abort();else o.dirty()},get path(){return S.path}};if(n.addIssue=n.addIssue.bind(n),f.type==="preprocess"){let A=f.transform(S.data,n);if(S.common.async)return Promise.resolve(A).then(async($)=>{if(o.value==="aborted")return d;let F=await this._def.schema._parseAsync({data:$,path:S.path,parent:S});if(F.status==="aborted")return d;if(F.status==="dirty")return BS(F.value);if(o.value==="dirty")return BS(F.value);return F});else{if(o.value==="aborted")return d;let $=this._def.schema._parseSync({data:A,path:S.path,parent:S});if($.status==="aborted")return d;if($.status==="dirty")return BS($.value);if(o.value==="dirty")return BS($.value);return $}}if(f.type==="refinement"){let A=($)=>{let F=f.refinement($,n);if(S.common.async)return Promise.resolve(F);if(F instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return $};if(S.common.async===!1){let $=this._def.schema._parseSync({data:S.data,path:S.path,parent:S});if($.status==="aborted")return d;if($.status==="dirty")o.dirty();return A($.value),{status:o.value,value:$.value}}else return this._def.schema._parseAsync({data:S.data,path:S.path,parent:S}).then(($)=>{if($.status==="aborted")return d;if($.status==="dirty")o.dirty();return A($.value).then(()=>{return{status:o.value,value:$.value}})})}if(f.type==="transform")if(S.common.async===!1){let A=this._def.schema._parseSync({data:S.data,path:S.path,parent:S});if(!$S(A))return A;let $=f.transform(A.value,n);if($ instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:o.value,value:$}}else return this._def.schema._parseAsync({data:S.data,path:S.path,parent:S}).then((A)=>{if(!$S(A))return A;return Promise.resolve(f.transform(A.value,n)).then(($)=>({status:o.value,value:$}))});$T.assertNever(f)}}yo.create=(T,o,S)=>{return new yo({schema:T,typeName:g.ZodEffects,effect:o,...u(S)})};yo.createWithPreprocess=(T,o,S)=>{return new yo({schema:o,effect:{type:"preprocess",transform:T},typeName:g.ZodEffects,...u(S)})};class zo extends e{_parse(T){if(this._getType(T)===N.undefined)return sT(void 0);return this._def.innerType._parse(T)}unwrap(){return this._def.innerType}}zo.create=(T,o)=>{return new zo({innerType:T,typeName:g.ZodOptional,...u(o)})};class Zo extends e{_parse(T){if(this._getType(T)===N.null)return sT(null);return this._def.innerType._parse(T)}unwrap(){return this._def.innerType}}Zo.create=(T,o)=>{return new Zo({innerType:T,typeName:g.ZodNullable,...u(o)})};class qS extends e{_parse(T){let{ctx:o}=this._processInputParams(T),S=o.data;if(o.parsedType===N.undefined)S=this._def.defaultValue();return this._def.innerType._parse({data:S,path:o.path,parent:o})}removeDefault(){return this._def.innerType}}qS.create=(T,o)=>{return new qS({innerType:T,typeName:g.ZodDefault,defaultValue:typeof o.default==="function"?o.default:()=>o.default,...u(o)})};class ZS extends e{_parse(T){let{ctx:o}=this._processInputParams(T),S={...o,common:{...o.common,issues:[]}},f=this._def.innerType._parse({data:S.data,path:S.path,parent:{...S}});if(Mf(f))return f.then((n)=>{return{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new Jo(S.common.issues)},input:S.data})}});else return{status:"valid",value:f.status==="valid"?f.value:this._def.catchValue({get error(){return new Jo(S.common.issues)},input:S.data})}}removeCatch(){return this._def.innerType}}ZS.create=(T,o)=>{return new ZS({innerType:T,typeName:g.ZodCatch,catchValue:typeof o.catch==="function"?o.catch:()=>o.catch,...u(o)})};class Xf extends e{_parse(T){if(this._getType(T)!==N.nan){let S=this._getOrReturnCtx(T);return C(S,{code:Q.invalid_type,expected:N.nan,received:S.parsedType}),d}return{status:"valid",value:T.data}}}Xf.create=(T)=>{return new Xf({typeName:g.ZodNaN,...u(T)})};var kO=Symbol("zod_brand");class Fn extends e{_parse(T){let{ctx:o}=this._processInputParams(T),S=o.data;return this._def.type._parse({data:S,path:o.path,parent:o})}unwrap(){return this._def.type}}class Kf extends e{_parse(T){let{status:o,ctx:S}=this._processInputParams(T);if(S.common.async)return(async()=>{let n=await this._def.in._parseAsync({data:S.data,path:S.path,parent:S});if(n.status==="aborted")return d;if(n.status==="dirty")return o.dirty(),BS(n.value);else return this._def.out._parseAsync({data:n.value,path:S.path,parent:S})})();else{let f=this._def.in._parseSync({data:S.data,path:S.path,parent:S});if(f.status==="aborted")return d;if(f.status==="dirty")return o.dirty(),{status:"dirty",value:f.value};else return this._def.out._parseSync({data:f.value,path:S.path,parent:S})}}static create(T,o){return new Kf({in:T,out:o,typeName:g.ZodPipeline})}}class cS extends e{_parse(T){let o=this._def.innerType._parse(T),S=(f)=>{if($S(f))f.value=Object.freeze(f.value);return f};return Mf(o)?o.then((f)=>S(f)):S(o)}unwrap(){return this._def.innerType}}cS.create=(T,o)=>{return new cS({innerType:T,typeName:g.ZodReadonly,...u(o)})};function dF(T,o){let S=typeof T==="function"?T(o):typeof T==="string"?{message:T}:T;return typeof S==="string"?{message:S}:S}function SJ(T,o={},S){if(T)return JS.create().superRefine((f,n)=>{var A,$;let F=T(f);if(F instanceof Promise)return F.then((J)=>{var R,W;if(!J){let y=dF(o,f),_=(W=(R=y.fatal)!==null&&R!==void 0?R:S)!==null&&W!==void 0?W:!0;n.addIssue({code:"custom",...y,fatal:_})}});if(!F){let J=dF(o,f),R=($=(A=J.fatal)!==null&&A!==void 0?A:S)!==null&&$!==void 0?$:!0;n.addIssue({code:"custom",...J,fatal:R})}return});return JS.create()}var yO={object:QT.lazycreate},g;(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"})(g||(g={}));var _O=(T,o={message:`Input not instance of ${T.name}`})=>SJ((S)=>S instanceof T,o),fJ=Eo.create,nJ=uo.create,wO=Xf.create,XO=eo.create,AJ=IS.create,KO=FS.create,GO=kf.create,YO=jS.create,EO=mS.create,HO=JS.create,zO=lo.create,QO=Co.create,DO=yf.create,UO=Ho.create,tO=QT.create,VO=QT.strictCreate,BO=NS.create,LO=$n.create,CO=hS.create,IO=Io.create,jO=_f.create,mO=wf.create,NO=RS.create,hO=LS.create,bO=bS.create,xO=xS.create,vO=ao.create,qO=vS.create,ZO=WS.create,lF=yo.create,cO=zo.create,rO=Zo.create,PO=yo.createWithPreprocess,pO=Kf.create,iO=()=>fJ().optional(),gO=()=>nJ().optional(),dO=()=>AJ().optional(),lO={string:(T)=>Eo.create({...T,coerce:!0}),number:(T)=>uo.create({...T,coerce:!0}),boolean:(T)=>IS.create({...T,coerce:!0}),bigint:(T)=>eo.create({...T,coerce:!0}),date:(T)=>FS.create({...T,coerce:!0})},uO=d,YT=Object.freeze({__proto__:null,defaultErrorMap:CS,setErrorMap:PW,getErrorMap:fn,makeIssue:nn,EMPTY_PATH:pW,addIssueToContext:C,ParseStatus:uT,INVALID:d,DIRTY:BS,OK:sT,isAborted:CA,isDirty:IA,isValid:$S,isAsync:Mf,get util(){return $T},get objectUtil(){return LA},ZodParsedType:N,getParsedType:qo,ZodType:e,datetimeRegex:TJ,ZodString:Eo,ZodNumber:uo,ZodBigInt:eo,ZodBoolean:IS,ZodDate:FS,ZodSymbol:kf,ZodUndefined:jS,ZodNull:mS,ZodAny:JS,ZodUnknown:lo,ZodNever:Co,ZodVoid:yf,ZodArray:Ho,ZodObject:QT,ZodUnion:NS,ZodDiscriminatedUnion:$n,ZodIntersection:hS,ZodTuple:Io,ZodRecord:_f,ZodMap:wf,ZodSet:RS,ZodFunction:LS,ZodLazy:bS,ZodLiteral:xS,ZodEnum:ao,ZodNativeEnum:vS,ZodPromise:WS,ZodEffects:yo,ZodTransformer:yo,ZodOptional:zo,ZodNullable:Zo,ZodDefault:qS,ZodCatch:ZS,ZodNaN:Xf,BRAND:kO,ZodBranded:Fn,ZodPipeline:Kf,ZodReadonly:cS,custom:SJ,Schema:e,ZodSchema:e,late:yO,get ZodFirstPartyTypeKind(){return g},coerce:lO,any:HO,array:UO,bigint:XO,boolean:AJ,date:KO,discriminatedUnion:LO,effect:lF,enum:vO,function:hO,instanceof:_O,intersection:CO,lazy:bO,literal:xO,map:mO,nan:wO,nativeEnum:qO,never:QO,null:EO,nullable:rO,number:nJ,object:tO,oboolean:dO,onumber:gO,optional:cO,ostring:iO,pipeline:pO,preprocess:PO,promise:ZO,record:jO,set:NO,strictObject:VO,string:fJ,symbol:GO,transformer:lF,tuple:IO,undefined:YO,union:BO,unknown:zO,void:DO,NEVER:uO,ZodIssueCode:Q,quotelessJson:rW,ZodError:Jo});var eO="__vite_start_time"in globalThis,aO=typeof window!=="undefined",iG="vitest"in globalThis,Do=iF({isServer:!eO&&!aO,server:{CI:YT.string().transform((T)=>!0).optional(),POSTGRES_USER:YT.string(),POSTGRES_PASSWORD:YT.string(),POSTGRES_DATABASE:YT.string(),POSTGRES_HOST:YT.string(),POSTGRES_PORT:YT.string().transform((T)=>Number.parseInt(T,10)),BACKEND_PORT:YT.string().transform((T)=>Number.parseInt(T,10)),RUN_WORKERS_FROM_SOURCE:YT.union([YT.literal("true"),YT.literal("false")]).optional().transform((T)=>T==="true"),FRONTEND_PORT:YT.string().transform((T)=>Number.parseInt(T,10)),FRONTEND_ORIGINS:YT.string().transform((T)=>JSON.parse(T)).pipe(YT.array(YT.string())),OPENAI_API_KEY:YT.string().optional()},clientPrefix:"VITE_",client:{VITE_BACKEND_ORIGIN:YT.string(),VITE_USE_SELF_SIGNED_CERTIFICATE:YT.union([YT.literal("true"),YT.literal("false")]).optional().transform((T)=>T==="true")},runtimeEnv:import.meta.env,emptyStringAsUndefined:!0});var FJ=mA(import.meta.dirname,"../dev"),JJ=Do.VITE_USE_SELF_SIGNED_CERTIFICATE?{cert:$J(mA(FJ,"./cert.pem"),"utf-8"),key:$J(mA(FJ,"./key.pem"),"utf-8")}:void 0;import Tk from"path";var M=Symbol.for("drizzle:entityKind"),aG=Symbol.for("drizzle:hasOwnEntityKind");function X(T,o){if(!T||typeof T!=="object")return!1;if(T instanceof o)return!0;if(!Object.prototype.hasOwnProperty.call(o,M))throw new Error(`Class "${o.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let S=Object.getPrototypeOf(T).constructor;if(S)while(S){if(M in S&&S[M]===o[M])return!0;S=Object.getPrototypeOf(S)}return!1}class kT{constructor(T,o){this.table=T,this.config=o,this.name=o.name,this.keyAsName=o.keyAsName,this.notNull=o.notNull,this.default=o.default,this.defaultFn=o.defaultFn,this.onUpdateFn=o.onUpdateFn,this.hasDefault=o.hasDefault,this.primary=o.primaryKey,this.isUnique=o.isUnique,this.uniqueName=o.uniqueName,this.uniqueType=o.uniqueType,this.dataType=o.dataType,this.columnType=o.columnType,this.generated=o.generated,this.generatedIdentity=o.generatedIdentity}static[M]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue(T){return T}mapToDriverValue(T){return T}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}class NA{static[M]="ColumnBuilder";config;constructor(T,o,S){this.config={name:T,keyAsName:T==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:o,columnType:S,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(T){return this.config.default=T,this.config.hasDefault=!0,this}$defaultFn(T){return this.config.defaultFn=T,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(T){return this.config.onUpdateFn=T,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(T){if(this.config.name!=="")return;this.config.name=T}}var Uo=Symbol.for("drizzle:Name");class hA{static[M]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(T,o){if(this.reference=()=>{let{name:S,columns:f,foreignColumns:n}=T();return{name:S,columns:f,foreignTable:n[0].table,foreignColumns:n}},o)this._onUpdate=o.onUpdate,this._onDelete=o.onDelete}onUpdate(T){return this._onUpdate=T===void 0?"no action":T,this}onDelete(T){return this._onDelete=T===void 0?"no action":T,this}build(T){return new RJ(T,this)}}class RJ{constructor(T,o){this.table=T,this.reference=o.reference,this.onUpdate=o._onUpdate,this.onDelete=o._onDelete}static[M]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:T,columns:o,foreignColumns:S}=this.reference(),f=o.map(($)=>$.name),n=S.map(($)=>$.name),A=[this.table[Uo],...f,S[0].table[Uo],...n];return T??`${A.join("_")}_fk`}}function Jn(T,...o){return T(...o)}function WJ(T,o){return`${T[Uo]}_${o.join("_")}_unique`}function OJ(T,o,S){for(let f=o;f<T.length;f++){let n=T[f];if(n==="\\"){f++;continue}if(n==='"')return[T.slice(o,f).replace(/\\/g,""),f+1];if(S)continue;if(n===","||n==="}")return[T.slice(o,f).replace(/\\/g,""),f]}return[T.slice(o).replace(/\\/g,""),T.length]}function MJ(T,o=0){let S=[],f=o,n=!1;while(f<T.length){let A=T[f];if(A===","){if(n||f===o)S.push("");n=!0,f++;continue}if(n=!1,A==="\\"){f+=2;continue}if(A==='"'){let[J,R]=OJ(T,f+1,!0);S.push(J),f=R;continue}if(A==="}")return[S,f+1];if(A==="{"){let[J,R]=MJ(T,f+1);S.push(J),f=R;continue}let[$,F]=OJ(T,f,!1);S.push($),f=F}return[S,f]}function kJ(T){let[o]=MJ(T,1);return o}function bA(T){return`{${T.map((o)=>{if(Array.isArray(o))return bA(o);if(typeof o==="string")return`"${o.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${o}`}).join(",")}}`}class h extends NA{foreignKeyConfigs=[];static[M]="PgColumnBuilder";array(T){return new _J(this.config.name,this,T)}references(T,o={}){return this.foreignKeyConfigs.push({ref:T,actions:o}),this}unique(T,o){return this.config.isUnique=!0,this.config.uniqueName=T,this.config.uniqueType=o?.nulls,this}generatedAlwaysAs(T){return this.config.generated={as:T,type:"always",mode:"stored"},this}buildForeignKeys(T,o){return this.foreignKeyConfigs.map(({ref:S,actions:f})=>{return Jn((n,A)=>{let $=new hA(()=>{let F=n();return{columns:[T],foreignColumns:[F]}});if(A.onUpdate)$.onUpdate(A.onUpdate);if(A.onDelete)$.onDelete(A.onDelete);return $.build(o)},S,f)})}buildExtraConfigColumn(T){return new yJ(T,this.config)}}class V extends kT{constructor(T,o){if(!o.uniqueName)o.uniqueName=WJ(T,[o.name]);super(T,o);this.table=T}static[M]="PgColumn"}class yJ extends V{static[M]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op(T){return this.indexConfig.opClass=T,this}}class Gf{static[M]="IndexedColumn";constructor(T,o,S,f){this.name=T,this.keyAsName=o,this.type=S,this.indexConfig=f}name;keyAsName;type;indexConfig}class _J extends h{static[M]="PgArrayBuilder";constructor(T,o,S){super(T,"array","PgArray");this.config.baseBuilder=o,this.config.size=S}build(T){let o=this.config.baseBuilder.build(T);return new xA(T,this.config,o)}}class xA extends V{constructor(T,o,S,f){super(T,o);this.baseColumn=S,this.range=f,this.size=o.size}size;static[M]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(T){if(typeof T==="string")T=kJ(T);return T.map((o)=>this.baseColumn.mapFromDriverValue(o))}mapToDriverValue(T,o=!1){let S=T.map((f)=>f===null?null:X(this.baseColumn,xA)?this.baseColumn.mapToDriverValue(f,!0):this.baseColumn.mapToDriverValue(f));if(o)return S;return bA(S)}}var vA=Symbol.for("drizzle:isPgEnum");function wJ(T){return!!T&&typeof T==="function"&&vA in T&&T[vA]===!0}class XJ extends h{static[M]="PgEnumColumnBuilder";constructor(T,o){super(T,"string","PgEnumColumn");this.config.enum=o}build(T){return new KJ(T,this.config)}}class KJ extends V{static[M]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(T,o){super(T,o);this.enum=o.enum}getSQLType(){return this.enum.enumName}}function Rn(T,o){return sO(T,o,void 0)}function sO(T,o,S){let f=Object.assign((n)=>new XJ(n??"",f),{enumName:T,enumValues:o,schema:S,[vA]:!0});return f}class xT{static[M]="Subquery";constructor(T,o,S,f=!1){this._={brand:"Subquery",sql:T,selectedFields:o,alias:S,isWith:f}}}class Yf extends xT{static[M]="WithSubquery"}var GJ="0.39.3";var qA,ZA,yT={startActiveSpan(T,o){if(!qA)return o();if(!ZA)ZA=qA.trace.getTracer("drizzle-orm",GJ);return Jn((S,f)=>f.startActiveSpan(T,(n)=>{try{return o(n)}catch(A){throw n.setStatus({code:S.SpanStatusCode.ERROR,message:A instanceof Error?A.message:"Unknown error"}),A}finally{n.end()}}),qA,ZA)}};var XT=Symbol.for("drizzle:ViewBaseConfig");var Wn=Symbol.for("drizzle:Schema"),On=Symbol.for("drizzle:Columns"),YJ=Symbol.for("drizzle:ExtraConfigColumns"),cA=Symbol.for("drizzle:OriginalName"),rA=Symbol.for("drizzle:BaseName"),Ef=Symbol.for("drizzle:IsAlias"),EJ=Symbol.for("drizzle:ExtraConfigBuilder"),TM=Symbol.for("drizzle:IsDrizzleTable");class j{static[M]="Table";static Symbol={Name:Uo,Schema:Wn,OriginalName:cA,Columns:On,ExtraConfigColumns:YJ,BaseName:rA,IsAlias:Ef,ExtraConfigBuilder:EJ};[Uo];[cA];[Wn];[On];[YJ];[rA];[Ef]=!1;[TM]=!0;[EJ]=void 0;constructor(T,o,S){this[Uo]=this[cA]=T,this[Wn]=o,this[rA]=S}}function ZT(T){return T[Uo]}function OS(T){return`${T[Wn]??"public"}.${T[Uo]}`}function PA(T){return T!==null&&T!==void 0&&typeof T.getSQL==="function"}function oM(T){let o={sql:"",params:[]};for(let S of T)if(o.sql+=S.sql,o.params.push(...S.params),S.typings?.length){if(!o.typings)o.typings=[];o.typings.push(...S.typings)}return o}class vT{static[M]="StringChunk";value;constructor(T){this.value=Array.isArray(T)?T:[T]}getSQL(){return new m([this])}}class m{constructor(T){this.queryChunks=T}static[M]="SQL";decoder=zJ;shouldInlineParams=!1;append(T){return this.queryChunks.push(...T.queryChunks),this}toQuery(T){return yT.startActiveSpan("drizzle.buildSQL",(o)=>{let S=this.buildQueryFromSourceParams(this.queryChunks,T);return o?.setAttributes({"drizzle.query.text":S.sql,"drizzle.query.params":JSON.stringify(S.params)}),S})}buildQueryFromSourceParams(T,o){let S=Object.assign({},o,{inlineParams:o.inlineParams||this.shouldInlineParams,paramStartIndex:o.paramStartIndex||{value:0}}),{casing:f,escapeName:n,escapeParam:A,prepareTyping:$,inlineParams:F,paramStartIndex:J}=S;return oM(T.map((R)=>{if(X(R,vT))return{sql:R.value.join(""),params:[]};if(X(R,Mn))return{sql:n(R.value),params:[]};if(R===void 0)return{sql:"",params:[]};if(Array.isArray(R)){let W=[new vT("(")];for(let[y,_]of R.entries())if(W.push(_),y<R.length-1)W.push(new vT(", "));return W.push(new vT(")")),this.buildQueryFromSourceParams(W,S)}if(X(R,m))return this.buildQueryFromSourceParams(R.queryChunks,{...S,inlineParams:F||R.shouldInlineParams});if(X(R,j)){let W=R[j.Symbol.Schema],y=R[j.Symbol.Name];return{sql:W===void 0||R[Ef]?n(y):n(W)+"."+n(y),params:[]}}if(X(R,kT)){let W=f.getColumnCasing(R);if(o.invokeSource==="indexes")return{sql:n(W),params:[]};let y=R.table[j.Symbol.Schema];return{sql:R.table[Ef]||y===void 0?n(R.table[j.Symbol.Name])+"."+n(W):n(y)+"."+n(R.table[j.Symbol.Name])+"."+n(W),params:[]}}if(X(R,Ao)){let W=R[XT].schema,y=R[XT].name;return{sql:W===void 0||R[XT].isAlias?n(y):n(W)+"."+n(y),params:[]}}if(X(R,Ro)){if(X(R.value,so))return{sql:A(J.value++,R),params:[R],typings:["none"]};let W=R.value===null?null:R.encoder.mapToDriverValue(R.value);if(X(W,m))return this.buildQueryFromSourceParams([W],S);if(F)return{sql:this.mapInlineParam(W,S),params:[]};let y=["none"];if($)y=[$(R.encoder)];return{sql:A(J.value++,W),params:[W],typings:y}}if(X(R,so))return{sql:A(J.value++,R),params:[R],typings:["none"]};if(X(R,m.Aliased)&&R.fieldAlias!==void 0)return{sql:n(R.fieldAlias),params:[]};if(X(R,xT)){if(R._.isWith)return{sql:n(R._.alias),params:[]};return this.buildQueryFromSourceParams([new vT("("),R._.sql,new vT(") "),new Mn(R._.alias)],S)}if(wJ(R)){if(R.schema)return{sql:n(R.schema)+"."+n(R.enumName),params:[]};return{sql:n(R.enumName),params:[]}}if(PA(R)){if(R.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([R.getSQL()],S);return this.buildQueryFromSourceParams([new vT("("),R.getSQL(),new vT(")")],S)}if(F)return{sql:this.mapInlineParam(R,S),params:[]};return{sql:A(J.value++,R),params:[R],typings:["none"]}}))}mapInlineParam(T,{escapeString:o}){if(T===null)return"null";if(typeof T==="number"||typeof T==="boolean")return T.toString();if(typeof T==="string")return o(T);if(typeof T==="object"){let S=T.toString();if(S==="[object Object]")return o(JSON.stringify(T));return o(S)}throw new Error("Unexpected param value: "+T)}getSQL(){return this}as(T){if(T===void 0)return this;return new m.Aliased(this,T)}mapWith(T){return this.decoder=typeof T==="function"?{mapFromDriverValue:T}:T,this}inlineParams(){return this.shouldInlineParams=!0,this}if(T){return T?this:void 0}}class Mn{constructor(T){this.value=T}static[M]="Name";brand;getSQL(){return new m([this])}}function HJ(T){return typeof T==="object"&&T!==null&&"mapToDriverValue"in T&&typeof T.mapToDriverValue==="function"}var zJ={mapFromDriverValue:(T)=>T},QJ={mapToDriverValue:(T)=>T},q6={...zJ,...QJ};class Ro{constructor(T,o=QJ){this.value=T,this.encoder=o}static[M]="Param";brand;getSQL(){return new m([this])}}function k(T,...o){let S=[];if(o.length>0||T.length>0&&T[0]!=="")S.push(new vT(T[0]));for(let[f,n]of o.entries())S.push(n,new vT(T[f+1]));return new m(S)}((T)=>{function o(){return new m([])}T.empty=o;function S(J){return new m(J)}T.fromList=S;function f(J){return new m([new vT(J)])}T.raw=f;function n(J,R){let W=[];for(let[y,_]of J.entries()){if(y>0&&R!==void 0)W.push(R);W.push(_)}return new m(W)}T.join=n;function A(J){return new Mn(J)}T.identifier=A;function $(J){return new so(J)}T.placeholder=$;function F(J,R){return new Ro(J,R)}T.param=F})(k||(k={}));((T)=>{class o{constructor(S,f){this.sql=S,this.fieldAlias=f}static[M]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new o(this.sql,this.fieldAlias)}}T.Aliased=o})(m||(m={}));class so{constructor(T){this.name=T}static[M]="Placeholder";getSQL(){return new m([this])}}function pA(T,o){return T.map((S)=>{if(X(S,so)){if(!(S.name in o))throw new Error(`No value for placeholder "${S.name}" was provided`);return o[S.name]}if(X(S,Ro)&&X(S.value,so)){if(!(S.value.name in o))throw new Error(`No value for placeholder "${S.value.name}" was provided`);return S.encoder.mapToDriverValue(o[S.value.name])}return S})}var SM=Symbol.for("drizzle:IsDrizzleView");class Ao{static[M]="View";[XT];[SM]=!0;constructor({name:T,schema:o,selectedFields:S,query:f}){this[XT]={name:T,originalName:T,schema:o,selectedFields:S,query:f,isExisting:!f,isAlias:!1}}getSQL(){return new m([this])}}kT.prototype.getSQL=function(){return new m([this])};j.prototype.getSQL=function(){return new m([this])};xT.prototype.getSQL=function(){return new m([this])};class rS{constructor(T){this.table=T}static[M]="ColumnAliasProxyHandler";get(T,o){if(o==="table")return this.table;return T[o]}}class Hf{constructor(T,o){this.alias=T,this.replaceOriginalName=o}static[M]="TableAliasProxyHandler";get(T,o){if(o===j.Symbol.IsAlias)return!0;if(o===j.Symbol.Name)return this.alias;if(this.replaceOriginalName&&o===j.Symbol.OriginalName)return this.alias;if(o===XT)return{...T[XT],name:this.alias,isAlias:!0};if(o===j.Symbol.Columns){let f=T[j.Symbol.Columns];if(!f)return f;let n={};return Object.keys(f).map((A)=>{n[A]=new Proxy(f[A],new rS(new Proxy(T,this)))}),n}let S=T[o];if(X(S,kT))return new Proxy(S,new rS(new Proxy(T,this)));return S}}function kn(T,o){return new Proxy(T,new Hf(o,!1))}function jo(T,o){return new Proxy(T,new rS(new Proxy(T.table,new Hf(o,!1))))}function iA(T,o){return new m.Aliased(zf(T.sql,o),T.fieldAlias)}function zf(T,o){return k.join(T.queryChunks.map((S)=>{if(X(S,kT))return jo(S,o);if(X(S,m))return zf(S,o);if(X(S,m.Aliased))return iA(S,o);return S}))}class yn extends Error{static[M]="DrizzleError";constructor({message:T,cause:o}){super(T);this.name="DrizzleError",this.cause=o}}class gA extends yn{static[M]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}function $o(T,o){if(HJ(o)&&!PA(T)&&!X(T,Ro)&&!X(T,so)&&!X(T,kT)&&!X(T,j)&&!X(T,Ao))return new Ro(T,o);return T}var _n=(T,o)=>{return k`${T} = ${$o(o,T)}`},DJ=(T,o)=>{return k`${T} <> ${$o(o,T)}`};function Qf(...T){let o=T.filter((S)=>S!==void 0);if(o.length===0)return;if(o.length===1)return new m(o);return new m([new vT("("),k.join(o,new vT(" and ")),new vT(")")])}function UJ(...T){let o=T.filter((S)=>S!==void 0);if(o.length===0)return;if(o.length===1)return new m(o);return new m([new vT("("),k.join(o,new vT(" or ")),new vT(")")])}function tJ(T){return k`not ${T}`}var VJ=(T,o)=>{return k`${T} > ${$o(o,T)}`},BJ=(T,o)=>{return k`${T} >= ${$o(o,T)}`},LJ=(T,o)=>{return k`${T} < ${$o(o,T)}`},CJ=(T,o)=>{return k`${T} <= ${$o(o,T)}`};function IJ(T,o){if(Array.isArray(o)){if(o.length===0)return k`false`;return k`${T} in ${o.map((S)=>$o(S,T))}`}return k`${T} in ${$o(o,T)}`}function jJ(T,o){if(Array.isArray(o)){if(o.length===0)return k`true`;return k`${T} not in ${o.map((S)=>$o(S,T))}`}return k`${T} not in ${$o(o,T)}`}function mJ(T){return k`${T} is null`}function NJ(T){return k`${T} is not null`}function hJ(T){return k`exists ${T}`}function bJ(T){return k`not exists ${T}`}function xJ(T,o,S){return k`${T} between ${$o(o,T)} and ${$o(S,T)}`}function vJ(T,o,S){return k`${T} not between ${$o(o,T)} and ${$o(S,T)}`}function qJ(T,o){return k`${T} like ${o}`}function ZJ(T,o){return k`${T} not like ${o}`}function cJ(T,o){return k`${T} ilike ${o}`}function rJ(T,o){return k`${T} not ilike ${o}`}function PJ(T){return k`${T} asc`}function pJ(T){return k`${T} desc`}class iJ{static[M]="ConsoleLogWriter";write(T){console.log(T)}}class dA{static[M]="DefaultLogger";writer;constructor(T){this.writer=T?.writer??new iJ}logQuery(T,o){let S=o.map((n)=>{try{return JSON.stringify(n)}catch{return String(n)}}),f=S.length?` -- params: [${S.join(", ")}]`:"";this.writer.write(`Query: ${T}${f}`)}}class lA{static[M]="NoopLogger";logQuery(){}}class To{static[M]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(T){return this.then(void 0,T)}finally(T){return this.then((o)=>{return T?.(),o},(o)=>{throw T?.(),o})}then(T,o){return this.execute().then(T,o)}}function gJ(T,o,S){let f={},n=T.reduce((A,{path:$,field:F},J)=>{let R;if(X(F,kT))R=F;else if(X(F,m))R=F.decoder;else R=F.sql.decoder;let W=A;for(let[y,_]of $.entries())if(y<$.length-1){if(!(_ in W))W[_]={};W=W[_]}else{let K=o[J],H=W[_]=K===null?null:R.mapFromDriverValue(K);if(S&&X(F,kT)&&$.length===2){let Y=$[0];if(!(Y in f))f[Y]=H===null?ZT(F.table):!1;else if(typeof f[Y]==="string"&&f[Y]!==ZT(F.table))f[Y]=!1}}return A},{});if(S&&Object.keys(f).length>0){for(let[A,$]of Object.entries(f))if(typeof $==="string"&&!S[$])n[A]=null}return n}function _o(T,o){return Object.entries(T).reduce((S,[f,n])=>{if(typeof f!=="string")return S;let A=o?[...o,f]:[f];if(X(n,kT)||X(n,m)||X(n,m.Aliased))S.push({path:A,field:n});else if(X(n,j))S.push(..._o(n[j.Symbol.Columns],A));else S.push(..._o(n,A));return S},[])}function Df(T,o){let S=Object.keys(T),f=Object.keys(o);if(S.length!==f.length)return!1;for(let[n,A]of S.entries())if(A!==f[n])return!1;return!0}function wn(T,o){let S=Object.entries(o).filter(([,f])=>f!==void 0).map(([f,n])=>{if(X(n,m)||X(n,kT))return[f,n];else return[f,new Ro(n,T[j.Symbol.Columns][f])]});if(S.length===0)throw new Error("No values to set");return Object.fromEntries(S)}function dJ(T,o){for(let S of o)for(let f of Object.getOwnPropertyNames(S.prototype)){if(f==="constructor")continue;Object.defineProperty(T.prototype,f,Object.getOwnPropertyDescriptor(S.prototype,f)||Object.create(null))}}function lJ(T){return T[j.Symbol.Columns]}function co(T){return X(T,xT)?T._.alias:X(T,Ao)?T[XT].name:X(T,m)?void 0:T[j.Symbol.IsAlias]?T[j.Symbol.Name]:T[j.Symbol.BaseName]}function nT(T,o){return{name:typeof T==="string"&&T.length>0?T:"",config:typeof T==="object"?T:o}}function uJ(T){if(typeof T!=="object"||T===null)return!1;if(T.constructor.name!=="Object")return!1;if("logger"in T){let o=typeof T.logger;if(o!=="boolean"&&(o!=="object"||typeof T.logger.logQuery!=="function")&&o!=="undefined")return!1;return!0}if("schema"in T){let o=typeof T.logger;if(o!=="object"&&o!=="undefined")return!1;return!0}if("casing"in T){let o=typeof T.logger;if(o!=="string"&&o!=="undefined")return!1;return!0}if("mode"in T){if(T.mode!=="default"||T.mode!=="planetscale"||T.mode!==void 0)return!1;return!0}if("connection"in T){let o=typeof T.connection;if(o!=="string"&&o!=="object"&&o!=="undefined")return!1;return!0}if("client"in T){let o=typeof T.client;if(o!=="object"&&o!=="function"&&o!=="undefined")return!1;return!0}if(Object.keys(T).length===0)return!0;return!1}class TS extends h{static[M]="PgIntColumnBaseBuilder";generatedAlwaysAsIdentity(T){if(T){let{name:o,...S}=T;this.config.generatedIdentity={type:"always",sequenceName:o,sequenceOptions:S}}else this.config.generatedIdentity={type:"always"};return this.config.hasDefault=!0,this.config.notNull=!0,this}generatedByDefaultAsIdentity(T){if(T){let{name:o,...S}=T;this.config.generatedIdentity={type:"byDefault",sequenceName:o,sequenceOptions:S}}else this.config.generatedIdentity={type:"byDefault"};return this.config.hasDefault=!0,this.config.notNull=!0,this}}class eJ extends TS{static[M]="PgBigInt53Builder";constructor(T){super(T,"number","PgBigInt53")}build(T){return new aJ(T,this.config)}}class aJ extends V{static[M]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(T){if(typeof T==="number")return T;return Number(T)}}class sJ extends TS{static[M]="PgBigInt64Builder";constructor(T){super(T,"bigint","PgBigInt64")}build(T){return new TR(T,this.config)}}class TR extends V{static[M]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(T){return BigInt(T)}}function oR(T,o){let{name:S,config:f}=nT(T,o);if(f.mode==="number")return new eJ(S);return new sJ(S)}class SR extends h{static[M]="PgBigSerial53Builder";constructor(T){super(T,"number","PgBigSerial53");this.config.hasDefault=!0,this.config.notNull=!0}build(T){return new fR(T,this.config)}}class fR extends V{static[M]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(T){if(typeof T==="number")return T;return Number(T)}}class nR extends h{static[M]="PgBigSerial64Builder";constructor(T){super(T,"bigint","PgBigSerial64");this.config.hasDefault=!0}build(T){return new AR(T,this.config)}}class AR extends V{static[M]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(T){return BigInt(T)}}function $R(T,o){let{name:S,config:f}=nT(T,o);if(f.mode==="number")return new SR(S);return new nR(S)}class FR extends h{static[M]="PgBooleanBuilder";constructor(T){super(T,"boolean","PgBoolean")}build(T){return new JR(T,this.config)}}class JR extends V{static[M]="PgBoolean";getSQLType(){return"boolean"}}function Uf(T){return new FR(T??"")}class RR extends h{static[M]="PgCharBuilder";constructor(T,o){super(T,"string","PgChar");this.config.length=o.length,this.config.enumValues=o.enum}build(T){return new WR(T,this.config)}}class WR extends V{static[M]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}}function OR(T,o={}){let{name:S,config:f}=nT(T,o);return new RR(S,f)}class MR extends h{static[M]="PgCidrBuilder";constructor(T){super(T,"string","PgCidr")}build(T){return new kR(T,this.config)}}class kR extends V{static[M]="PgCidr";getSQLType(){return"cidr"}}function yR(T){return new MR(T??"")}class _R extends h{static[M]="PgCustomColumnBuilder";constructor(T,o,S){super(T,"custom","PgCustomColumn");this.config.fieldConfig=o,this.config.customTypeParams=S}build(T){return new wR(T,this.config)}}class wR extends V{static[M]="PgCustomColumn";sqlName;mapTo;mapFrom;constructor(T,o){super(T,o);this.sqlName=o.customTypeParams.dataType(o.fieldConfig),this.mapTo=o.customTypeParams.toDriver,this.mapFrom=o.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(T){return typeof this.mapFrom==="function"?this.mapFrom(T):T}mapToDriverValue(T){return typeof this.mapTo==="function"?this.mapTo(T):T}}function XR(T){return(o,S)=>{let{name:f,config:n}=nT(o,S);return new _R(f,n,T)}}class ro extends h{static[M]="PgDateColumnBaseBuilder";defaultNow(){return this.default(k`now()`)}}class KR extends ro{static[M]="PgDateBuilder";constructor(T){super(T,"date","PgDate")}build(T){return new Xn(T,this.config)}}class Xn extends V{static[M]="PgDate";getSQLType(){return"date"}mapFromDriverValue(T){return new Date(T)}mapToDriverValue(T){return T.toISOString()}}class GR extends ro{static[M]="PgDateStringBuilder";constructor(T){super(T,"string","PgDateString")}build(T){return new Kn(T,this.config)}}class Kn extends V{static[M]="PgDateString";getSQLType(){return"date"}}function YR(T,o){let{name:S,config:f}=nT(T,o);if(f?.mode==="date")return new KR(S);return new GR(S)}class ER extends h{static[M]="PgDoublePrecisionBuilder";constructor(T){super(T,"number","PgDoublePrecision")}build(T){return new HR(T,this.config)}}class HR extends V{static[M]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(T){if(typeof T==="string")return Number.parseFloat(T);return T}}function zR(T){return new ER(T??"")}class QR extends h{static[M]="PgInetBuilder";constructor(T){super(T,"string","PgInet")}build(T){return new DR(T,this.config)}}class DR extends V{static[M]="PgInet";getSQLType(){return"inet"}}function UR(T){return new QR(T??"")}class tR extends TS{static[M]="PgIntegerBuilder";constructor(T){super(T,"number","PgInteger")}build(T){return new VR(T,this.config)}}class VR extends V{static[M]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(T){if(typeof T==="string")return Number.parseInt(T);return T}}function Gn(T){return new tR(T??"")}class BR extends h{static[M]="PgIntervalBuilder";constructor(T,o){super(T,"string","PgInterval");this.config.intervalConfig=o}build(T){return new LR(T,this.config)}}class LR extends V{static[M]="PgInterval";fields=this.config.intervalConfig.fields;precision=this.config.intervalConfig.precision;getSQLType(){let T=this.fields?` ${this.fields}`:"",o=this.precision?`(${this.precision})`:"";return`interval${T}${o}`}}function CR(T,o={}){let{name:S,config:f}=nT(T,o);return new BR(S,f)}class IR extends h{static[M]="PgJsonBuilder";constructor(T){super(T,"json","PgJson")}build(T){return new Yn(T,this.config)}}class Yn extends V{static[M]="PgJson";constructor(T,o){super(T,o)}getSQLType(){return"json"}mapToDriverValue(T){return JSON.stringify(T)}mapFromDriverValue(T){if(typeof T==="string")try{return JSON.parse(T)}catch{return T}return T}}function jR(T){return new IR(T??"")}class mR extends h{static[M]="PgJsonbBuilder";constructor(T){super(T,"json","PgJsonb")}build(T){return new En(T,this.config)}}class En extends V{static[M]="PgJsonb";constructor(T,o){super(T,o)}getSQLType(){return"jsonb"}mapToDriverValue(T){return JSON.stringify(T)}mapFromDriverValue(T){if(typeof T==="string")try{return JSON.parse(T)}catch{return T}return T}}function NR(T){return new mR(T??"")}class hR extends h{static[M]="PgLineBuilder";constructor(T){super(T,"array","PgLine")}build(T){return new bR(T,this.config)}}class bR extends V{static[M]="PgLine";getSQLType(){return"line"}mapFromDriverValue(T){let[o,S,f]=T.slice(1,-1).split(",");return[Number.parseFloat(o),Number.parseFloat(S),Number.parseFloat(f)]}mapToDriverValue(T){return`{${T[0]},${T[1]},${T[2]}}`}}class xR extends h{static[M]="PgLineABCBuilder";constructor(T){super(T,"json","PgLineABC")}build(T){return new vR(T,this.config)}}class vR extends V{static[M]="PgLineABC";getSQLType(){return"line"}mapFromDriverValue(T){let[o,S,f]=T.slice(1,-1).split(",");return{a:Number.parseFloat(o),b:Number.parseFloat(S),c:Number.parseFloat(f)}}mapToDriverValue(T){return`{${T.a},${T.b},${T.c}}`}}function qR(T,o){let{name:S,config:f}=nT(T,o);if(!f?.mode||f.mode==="tuple")return new hR(S);return new xR(S)}class ZR extends h{static[M]="PgMacaddrBuilder";constructor(T){super(T,"string","PgMacaddr")}build(T){return new cR(T,this.config)}}class cR extends V{static[M]="PgMacaddr";getSQLType(){return"macaddr"}}function rR(T){return new ZR(T??"")}class PR extends h{static[M]="PgMacaddr8Builder";constructor(T){super(T,"string","PgMacaddr8")}build(T){return new pR(T,this.config)}}class pR extends V{static[M]="PgMacaddr8";getSQLType(){return"macaddr8"}}function iR(T){return new PR(T??"")}class gR extends h{static[M]="PgNumericBuilder";constructor(T,o,S){super(T,"string","PgNumeric");this.config.precision=o,this.config.scale=S}build(T){return new Hn(T,this.config)}}class Hn extends V{static[M]="PgNumeric";precision;scale;constructor(T,o){super(T,o);this.precision=o.precision,this.scale=o.scale}getSQLType(){if(this.precision!==void 0&&this.scale!==void 0)return`numeric(${this.precision}, ${this.scale})`;else if(this.precision===void 0)return"numeric";else return`numeric(${this.precision})`}}function dR(T,o){let{name:S,config:f}=nT(T,o);return new gR(S,f?.precision,f?.scale)}class lR extends h{static[M]="PgPointTupleBuilder";constructor(T){super(T,"array","PgPointTuple")}build(T){return new uR(T,this.config)}}class uR extends V{static[M]="PgPointTuple";getSQLType(){return"point"}mapFromDriverValue(T){if(typeof T==="string"){let[o,S]=T.slice(1,-1).split(",");return[Number.parseFloat(o),Number.parseFloat(S)]}return[T.x,T.y]}mapToDriverValue(T){return`(${T[0]},${T[1]})`}}class eR extends h{static[M]="PgPointObjectBuilder";constructor(T){super(T,"json","PgPointObject")}build(T){return new aR(T,this.config)}}class aR extends V{static[M]="PgPointObject";getSQLType(){return"point"}mapFromDriverValue(T){if(typeof T==="string"){let[o,S]=T.slice(1,-1).split(",");return{x:Number.parseFloat(o),y:Number.parseFloat(S)}}return T}mapToDriverValue(T){return`(${T.x},${T.y})`}}function sR(T,o){let{name:S,config:f}=nT(T,o);if(!f?.mode||f.mode==="tuple")return new lR(S);return new eR(S)}function fM(T){let o=[];for(let S=0;S<T.length;S+=2)o.push(Number.parseInt(T.slice(S,S+2),16));return new Uint8Array(o)}function T0(T,o){let S=new ArrayBuffer(8),f=new DataView(S);for(let n=0;n<8;n++)f.setUint8(n,T[o+n]);return f.getFloat64(0,!0)}function uA(T){let o=fM(T),S=0,f=o[S];S+=1;let n=new DataView(o.buffer),A=n.getUint32(S,f===1);S+=4;let $;if(A&536870912)$=n.getUint32(S,f===1),S+=4;if((A&65535)===1){let F=T0(o,S);S+=8;let J=T0(o,S);return S+=8,[F,J]}throw new Error("Unsupported geometry type")}class o0 extends h{static[M]="PgGeometryBuilder";constructor(T){super(T,"array","PgGeometry")}build(T){return new S0(T,this.config)}}class S0 extends V{static[M]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(T){return uA(T)}mapToDriverValue(T){return`point(${T[0]} ${T[1]})`}}class f0 extends h{static[M]="PgGeometryObjectBuilder";constructor(T){super(T,"json","PgGeometryObject")}build(T){return new n0(T,this.config)}}class n0 extends V{static[M]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(T){let o=uA(T);return{x:o[0],y:o[1]}}mapToDriverValue(T){return`point(${T.x} ${T.y})`}}function A0(T,o){let{name:S,config:f}=nT(T,o);if(!f?.mode||f.mode==="tuple")return new o0(S);return new f0(S)}class $0 extends h{static[M]="PgRealBuilder";constructor(T,o){super(T,"number","PgReal");this.config.length=o}build(T){return new F0(T,this.config)}}class F0 extends V{static[M]="PgReal";constructor(T,o){super(T,o)}getSQLType(){return"real"}mapFromDriverValue=(T)=>{if(typeof T==="string")return Number.parseFloat(T);return T}}function J0(T){return new $0(T??"")}class R0 extends h{static[M]="PgSerialBuilder";constructor(T){super(T,"number","PgSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(T){return new W0(T,this.config)}}class W0 extends V{static[M]="PgSerial";getSQLType(){return"serial"}}function O0(T){return new R0(T??"")}class M0 extends TS{static[M]="PgSmallIntBuilder";constructor(T){super(T,"number","PgSmallInt")}build(T){return new k0(T,this.config)}}class k0 extends V{static[M]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=(T)=>{if(typeof T==="string")return Number(T);return T}}function y0(T){return new M0(T??"")}class _0 extends h{static[M]="PgSmallSerialBuilder";constructor(T){super(T,"number","PgSmallSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(T){return new w0(T,this.config)}}class w0 extends V{static[M]="PgSmallSerial";getSQLType(){return"smallserial"}}function X0(T){return new _0(T??"")}class K0 extends h{static[M]="PgTextBuilder";constructor(T,o){super(T,"string","PgText");this.config.enumValues=o.enum}build(T){return new G0(T,this.config)}}class G0 extends V{static[M]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function Y0(T,o={}){let{name:S,config:f}=nT(T,o);return new K0(S,f)}class E0 extends ro{constructor(T,o,S){super(T,"string","PgTime");this.withTimezone=o,this.precision=S,this.config.withTimezone=o,this.config.precision=S}static[M]="PgTimeBuilder";build(T){return new zn(T,this.config)}}class zn extends V{static[M]="PgTime";withTimezone;precision;constructor(T,o){super(T,o);this.withTimezone=o.withTimezone,this.precision=o.precision}getSQLType(){return`time${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function H0(T,o={}){let{name:S,config:f}=nT(T,o);return new E0(S,f.withTimezone??!1,f.precision)}class z0 extends ro{static[M]="PgTimestampBuilder";constructor(T,o,S){super(T,"date","PgTimestamp");this.config.withTimezone=o,this.config.precision=S}build(T){return new Qn(T,this.config)}}class Qn extends V{static[M]="PgTimestamp";withTimezone;precision;constructor(T,o){super(T,o);this.withTimezone=o.withTimezone,this.precision=o.precision}getSQLType(){return`timestamp${this.precision===void 0?"":` (${this.precision})`}${this.withTimezone?" with time zone":""}`}mapFromDriverValue=(T)=>{return new Date(this.withTimezone?T:T+"+0000")};mapToDriverValue=(T)=>{return T.toISOString()}}class Q0 extends ro{static[M]="PgTimestampStringBuilder";constructor(T,o,S){super(T,"string","PgTimestampString");this.config.withTimezone=o,this.config.precision=S}build(T){return new Dn(T,this.config)}}class Dn extends V{static[M]="PgTimestampString";withTimezone;precision;constructor(T,o){super(T,o);this.withTimezone=o.withTimezone,this.precision=o.precision}getSQLType(){return`timestamp${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function to(T,o={}){let{name:S,config:f}=nT(T,o);if(f?.mode==="string")return new Q0(S,f.withTimezone??!1,f.precision);return new z0(S,f?.withTimezone??!1,f?.precision)}class D0 extends h{static[M]="PgUUIDBuilder";constructor(T){super(T,"string","PgUUID")}defaultRandom(){return this.default(k`gen_random_uuid()`)}build(T){return new Un(T,this.config)}}class Un extends V{static[M]="PgUUID";getSQLType(){return"uuid"}}function Wo(T){return new D0(T??"")}class U0 extends h{static[M]="PgVarcharBuilder";constructor(T,o){super(T,"string","PgVarchar");this.config.length=o.length,this.config.enumValues=o.enum}build(T){return new t0(T,this.config)}}class t0 extends V{static[M]="PgVarchar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"varchar":`varchar(${this.length})`}}function rT(T,o={}){let{name:S,config:f}=nT(T,o);return new U0(S,f)}class V0 extends h{static[M]="PgBinaryVectorBuilder";constructor(T,o){super(T,"string","PgBinaryVector");this.config.dimensions=o.dimensions}build(T){return new B0(T,this.config)}}class B0 extends V{static[M]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}}function L0(T,o){let{name:S,config:f}=nT(T,o);return new V0(S,f)}class C0 extends h{static[M]="PgHalfVectorBuilder";constructor(T,o){super(T,"array","PgHalfVector");this.config.dimensions=o.dimensions}build(T){return new I0(T,this.config)}}class I0 extends V{static[M]="PgHalfVector";dimensions=this.config.dimensions;getSQLType(){return`halfvec(${this.dimensions})`}mapToDriverValue(T){return JSON.stringify(T)}mapFromDriverValue(T){return T.slice(1,-1).split(",").map((o)=>Number.parseFloat(o))}}function j0(T,o){let{name:S,config:f}=nT(T,o);return new C0(S,f)}class m0 extends h{static[M]="PgSparseVectorBuilder";constructor(T,o){super(T,"string","PgSparseVector");this.config.dimensions=o.dimensions}build(T){return new N0(T,this.config)}}class N0 extends V{static[M]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function h0(T,o){let{name:S,config:f}=nT(T,o);return new m0(S,f)}class b0 extends h{static[M]="PgVectorBuilder";constructor(T,o){super(T,"array","PgVector");this.config.dimensions=o.dimensions}build(T){return new x0(T,this.config)}}class x0 extends V{static[M]="PgVector";dimensions=this.config.dimensions;getSQLType(){return`vector(${this.dimensions})`}mapToDriverValue(T){return JSON.stringify(T)}mapFromDriverValue(T){return T.slice(1,-1).split(",").map((o)=>Number.parseFloat(o))}}function v0(T,o){let{name:S,config:f}=nT(T,o);return new b0(S,f)}function q0(){return{bigint:oR,bigserial:$R,boolean:Uf,char:OR,cidr:yR,customType:XR,date:YR,doublePrecision:zR,inet:UR,integer:Gn,interval:CR,json:jR,jsonb:NR,line:qR,macaddr:rR,macaddr8:iR,numeric:dR,point:sR,geometry:A0,real:J0,serial:O0,smallint:y0,smallserial:X0,text:Y0,time:H0,timestamp:to,uuid:Wo,varchar:rT,bit:L0,halfvec:j0,sparsevec:h0,vector:v0}}var eA=Symbol.for("drizzle:PgInlineForeignKeys"),Z0=Symbol.for("drizzle:EnableRLS");class PT extends j{static[M]="PgTable";static Symbol=Object.assign({},j.Symbol,{InlineForeignKeys:eA,EnableRLS:Z0});[eA]=[];[Z0]=!1;[j.Symbol.ExtraConfigBuilder]=void 0}function nM(T,o,S,f,n=T){let A=new PT(T,f,n),$=typeof o==="function"?o(q0()):o,F=Object.fromEntries(Object.entries($).map(([W,y])=>{let _=y;_.setName(W);let K=_.build(A);return A[eA].push(..._.buildForeignKeys(K,A)),[W,K]})),J=Object.fromEntries(Object.entries($).map(([W,y])=>{let _=y;_.setName(W);let K=_.buildExtraConfigColumn(A);return[W,K]})),R=Object.assign(A,F);if(R[j.Symbol.Columns]=F,R[j.Symbol.ExtraConfigColumns]=J,S)R[PT.Symbol.ExtraConfigBuilder]=S;return Object.assign(R,{enableRLS:()=>{return R[PT.Symbol.EnableRLS]=!0,R}})}var oS=(T,o,S)=>{return nM(T,o,S,void 0)};function c0(...T){if(T[0].columns)return new tf(T[0].columns,T[0].name);return new tf(T)}class tf{static[M]="PgPrimaryKeyBuilder";columns;name;constructor(T,o){this.columns=T,this.name=o}build(T){return new r0(T,this.columns,this.name)}}class r0{constructor(T,o,S){this.table=T,this.columns=o,this.name=S}static[M]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[PT.Symbol.Name]}_${this.columns.map((T)=>T.name).join("_")}_pk`}}class aA{constructor(T,o,S){this.sourceTable=T,this.referencedTable=o,this.relationName=S,this.referencedTableName=o[j.Symbol.Name]}static[M]="Relation";referencedTableName;fieldName}class P0{constructor(T,o){this.table=T,this.config=o}static[M]="Relations"}class SS extends aA{constructor(T,o,S,f){super(T,o,S?.relationName);this.config=S,this.isNullable=f}static[M]="One";withFieldName(T){let o=new SS(this.sourceTable,this.referencedTable,this.config,this.isNullable);return o.fieldName=T,o}}class Vf extends aA{constructor(T,o,S){super(T,o,S?.relationName);this.config=S}static[M]="Many";withFieldName(T){let o=new Vf(this.sourceTable,this.referencedTable,this.config);return o.fieldName=T,o}}function p0(){return{and:Qf,between:xJ,eq:_n,exists:hJ,gt:VJ,gte:BJ,ilike:cJ,inArray:IJ,isNull:mJ,isNotNull:NJ,like:qJ,lt:LJ,lte:CJ,ne:DJ,not:tJ,notBetween:vJ,notExists:bJ,notLike:ZJ,notIlike:rJ,notInArray:jJ,or:UJ,sql:k}}function i0(){return{sql:k,asc:PJ,desc:pJ}}function g0(T,o){if(Object.keys(T).length===1&&"default"in T&&!X(T.default,j))T=T.default;let S={},f={},n={};for(let[A,$]of Object.entries(T))if(X($,j)){let F=OS($),J=f[F];S[F]=A,n[A]={tsName:A,dbName:$[j.Symbol.Name],schema:$[j.Symbol.Schema],columns:$[j.Symbol.Columns],relations:J?.relations??{},primaryKey:J?.primaryKey??[]};for(let W of Object.values($[j.Symbol.Columns]))if(W.primary)n[A].primaryKey.push(W);let R=$[j.Symbol.ExtraConfigBuilder]?.($[j.Symbol.ExtraConfigColumns]);if(R){for(let W of Object.values(R))if(X(W,tf))n[A].primaryKey.push(...W.columns)}}else if(X($,P0)){let F=OS($.table),J=S[F],R=$.config(o($.table)),W;for(let[y,_]of Object.entries(R))if(J){let K=n[J];if(K.relations[y]=_,W)K.primaryKey.push(...W)}else{if(!(F in f))f[F]={relations:{},primaryKey:W};f[F].relations[y]=_}}return{tables:n,tableNamesMap:S}}function AM(T){return function o(S,f){return new SS(T,S,f,f?.fields.reduce((n,A)=>n&&A.notNull,!0)??!1)}}function $M(T){return function o(S,f){return new Vf(T,S,f)}}function d0(T,o,S){if(X(S,SS)&&S.config)return{fields:S.config.fields,references:S.config.references};let f=o[OS(S.referencedTable)];if(!f)throw new Error(`Table "${S.referencedTable[j.Symbol.Name]}" not found in schema`);let n=T[f];if(!n)throw new Error(`Table "${f}" not found in schema`);let A=S.sourceTable,$=o[OS(A)];if(!$)throw new Error(`Table "${A[j.Symbol.Name]}" not found in schema`);let F=[];for(let J of Object.values(n.relations))if(S.relationName&&S!==J&&J.relationName===S.relationName||!S.relationName&&J.referencedTable===S.sourceTable)F.push(J);if(F.length>1)throw S.relationName?new Error(`There are multiple relations with name "${S.relationName}" in table "${f}"`):new Error(`There are multiple relations between "${f}" and "${S.sourceTable[j.Symbol.Name]}". Please specify relation name`);if(F[0]&&X(F[0],SS)&&F[0].config)return{fields:F[0].config.references,references:F[0].config.fields};throw new Error(`There is not enough information to infer relation "${$}.${S.fieldName}"`)}function l0(T){return{one:AM(T),many:$M(T)}}function tn(T,o,S,f,n=(A)=>A){let A={};for(let[$,F]of f.entries())if(F.isJson){let J=o.relations[F.tsKey],R=S[$],W=typeof R==="string"?JSON.parse(R):R;A[F.tsKey]=X(J,SS)?W&&tn(T,T[F.relationTableTsKey],W,F.selection,n):W.map((y)=>tn(T,T[F.relationTableTsKey],y,F.selection,n))}else{let J=n(S[$]),R=F.field,W;if(X(R,kT))W=R;else if(X(R,m))W=R.decoder;else W=R.sql.decoder;A[F.tsKey]=J===null?null:W.mapFromDriverValue(J)}return A}import LM from"os";import CM from"fs";var Vn=new Map,sA=new Map,T$=Symbol("OriginError"),PS={};class wo extends Promise{constructor(T,o,S,f,n={}){let A,$;super((F,J)=>{A=F,$=J});this.tagged=Array.isArray(T.raw),this.strings=T,this.args=o,this.handler=S,this.canceller=f,this.options=n,this.state=null,this.statement=null,this.resolve=(F)=>(this.active=!1,A(F)),this.reject=(F)=>(this.active=!1,$(F)),this.active=!1,this.cancelled=null,this.executed=!1,this.signature="",this[T$]=this.handler.debug?new Error:this.tagged&&FM(this.strings)}get origin(){return(this.handler.debug?this[T$].stack:this.tagged&&sA.has(this.strings)?sA.get(this.strings):sA.set(this.strings,this[T$].stack).get(this.strings))||""}static get[Symbol.species](){return Promise}cancel(){return this.canceller&&(this.canceller(this),this.canceller=null)}simple(){return this.options.simple=!0,this.options.prepare=!1,this}async readable(){return this.simple(),this.streaming=!0,this}async writable(){return this.simple(),this.streaming=!0,this}cursor(T=1,o){if(this.options.simple=!1,typeof T==="function")o=T,T=1;if(this.cursorRows=T,typeof o==="function")return this.cursorFn=o,this;let S;return{[Symbol.asyncIterator]:()=>({next:()=>{if(this.executed&&!this.active)return{done:!0};S&&S();let f=new Promise((n,A)=>{this.cursorFn=($)=>{return n({value:$,done:!1}),new Promise((F)=>S=F)},this.resolve=()=>(this.active=!1,n({done:!0})),this.reject=($)=>(this.active=!1,A($))});return this.execute(),f},return(){return S&&S(PS),{done:!0}}})}}describe(){return this.options.simple=!1,this.onlyDescribe=this.options.prepare=!0,this}stream(){throw new Error(".stream has been renamed to .forEach")}forEach(T){return this.forEachFn=T,this.handle(),this}raw(){return this.isRaw=!0,this}values(){return this.isRaw="values",this}async handle(){!this.executed&&(this.executed=!0)&&await 1&&this.handler(this)}execute(){return this.handle(),this}then(){return this.handle(),super.then.apply(this,arguments)}catch(){return this.handle(),super.catch.apply(this,arguments)}finally(){return this.handle(),super.finally.apply(this,arguments)}}function FM(T){if(Vn.has(T))return Vn.get(T);let o=Error.stackTraceLimit;return Error.stackTraceLimit=4,Vn.set(T,new Error),Error.stackTraceLimit=o,Vn.get(T)}class pS extends Error{constructor(T){super(T.message);this.name=this.constructor.name,Object.assign(this,T)}}var LT={connection:u0,postgres:e0,generic:a0,notSupported:s0};function u0(T,o,S){let{host:f,port:n}=S||o,A=Object.assign(new Error("write "+T+" "+(o.path||f+":"+n)),{code:T,errno:T,address:o.path||f},o.path?{}:{port:n});return Error.captureStackTrace(A,u0),A}function e0(T){let o=new pS(T);return Error.captureStackTrace(o,e0),o}function a0(T,o){let S=Object.assign(new Error(T+": "+o),{code:T});return Error.captureStackTrace(S,a0),S}function s0(T){let o=Object.assign(new Error(T+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:T});return Error.captureStackTrace(o,s0),o}var JM={string:{to:25,from:null,serialize:(T)=>""+T},number:{to:0,from:[21,23,26,700,701],serialize:(T)=>""+T,parse:(T)=>+T},json:{to:114,from:[114,3802],serialize:(T)=>JSON.stringify(T),parse:(T)=>JSON.parse(T)},boolean:{to:16,from:16,serialize:(T)=>T===!0?"t":"f",parse:(T)=>T==="t"},date:{to:1184,from:[1082,1114,1184],serialize:(T)=>(T instanceof Date?T:new Date(T)).toISOString(),parse:(T)=>new Date(T)},bytea:{to:17,from:17,serialize:(T)=>"\\x"+Buffer.from(T).toString("hex"),parse:(T)=>Buffer.from(T.slice(2),"hex")}};class Cn{then(){o$()}catch(){o$()}finally(){o$()}}class If extends Cn{constructor(T){super();this.value=mn(T)}}class mo extends Cn{constructor(T,o,S){super();this.value=T,this.type=o,this.array=S}}class In extends Cn{constructor(T,o){super();this.first=T,this.rest=o}build(T,o,S,f){let n=RM.map(([A,$])=>({fn:$,i:T.search(A)})).sort((A,$)=>A.i-$.i).pop();return n.i===-1?$$(this.first,f):n.fn(this.first,this.rest,o,S,f)}}function jn(T,o,S,f){let n=T instanceof mo?T.value:T;if(n===void 0){if(T instanceof mo?T.value=f.transform.undefined:n=T=f.transform.undefined,n===void 0)throw LT.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return"$"+S.push(T instanceof mo?(o.push(T.value),T.array?T.array[T.type||Ln(T.value)]||T.type||f1(T.value):T.type):(o.push(T),Ln(T)))}var o1=A1(JM);function n$(T,o,S,f,n,A){for(let $=1;$<T.strings.length;$++)o+=A$(o,S,f,n,A)+T.strings[$],S=T.args[$];return o}function A$(T,o,S,f,n){return o instanceof In?o.build(T,S,f,n):o instanceof wo?f$(o,S,f,n):o instanceof If?o.value:o&&o[0]instanceof wo?o.reduce((A,$)=>A+" "+f$($,S,f,n),""):jn(o,S,f,n)}function f$(T,o,S,f){return T.fragment=!0,n$(T,T.strings[0],T.args[0],o,S,f)}function S1(T,o,S,f,n){return T.map((A)=>"("+f.map(($)=>A$("values",A[$],o,S,n)).join(",")+")").join(",")}function T1(T,o,S,f,n){let A=Array.isArray(T[0]),$=o.length?o.flat():Object.keys(A?T[0]:T);return S1(A?T:[T],S,f,$,n)}function Bn(T,o,S,f,n){if(typeof T==="string"&&(T=[T].concat(o)),Array.isArray(T))return $$(T,n);let A;return(o.length?o.flat():Object.keys(T)).map((F)=>{return A=T[F],(A instanceof wo?f$(A,S,f,n):A instanceof If?A.value:jn(A,S,f,n))+" as "+mn(n.transform.column.to?n.transform.column.to(F):F)}).join(",")}var RM=Object.entries({values:T1,in:(...T)=>{let o=T1(...T);return o==="()"?"(null)":o},select:Bn,as:Bn,returning:Bn,"\\(":Bn,update(T,o,S,f,n){return(o.length?o.flat():Object.keys(T)).map((A)=>mn(n.transform.column.to?n.transform.column.to(A):A)+"="+A$("values",T[A],S,f,n))},insert(T,o,S,f,n){let A=o.length?o.flat():Object.keys(Array.isArray(T)?T[0]:T);return"("+$$(A,n)+")values"+S1(Array.isArray(T)?T:[T],S,f,A,n)}}).map(([T,o])=>[new RegExp("((?:^|[\\s(])"+T+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),o]);function o$(){throw LT.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}var{serializers:WM,parsers:OM}=o1;function f1(T){if(Array.isArray(T))return f1(T[0]);return typeof T==="string"?1009:0}var n1=function(T){let o=A1(T||{});return{serializers:Object.assign({},WM,o.serializers),parsers:Object.assign({},OM,o.parsers)}};function A1(T){return Object.keys(T).reduce((o,S)=>{if(T[S].from&&[].concat(T[S].from).forEach((f)=>o.parsers[f]=T[S].parse),T[S].serialize)o.serializers[T[S].to]=T[S].serialize,T[S].from&&[].concat(T[S].from).forEach((f)=>o.serializers[f]=T[S].serialize);return o},{parsers:{},serializers:{}})}function $$(T,{transform:{column:o}}){return T.map((S)=>mn(o.to?o.to(S):S)).join(",")}var mn=function T(o){return'"'+o.replace(/"/g,'""').replace(/\./g,'"."')+'"'},Ln=function T(o){return o instanceof mo?o.type:o instanceof Date?1184:o instanceof Uint8Array?17:o===!0||o===!1?16:typeof o==="bigint"?20:Array.isArray(o)?T(o[0]):0},MM=/\\/g,kM=/"/g;function yM(T){return T.replace(MM,"\\\\").replace(kM,"\\\"")}var $1=function T(o,S,f,n){if(Array.isArray(o)===!1)return o;if(!o.length)return"{}";let A=o[0],$=n===1020?";":",";if(Array.isArray(A)&&!A.type)return"{"+o.map((F)=>T(F,S,f,n)).join($)+"}";return"{"+o.map((F)=>{if(F===void 0){if(F=f.transform.undefined,F===void 0)throw LT.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return F===null?"null":'"'+yM(S?S(F.type?F.value:F):""+F)+'"'}).join($)+"}"},S$={i:0,char:null,str:"",quoted:!1,last:0},F1=function T(o,S,f){return S$.i=S$.last=0,J1(S$,o,S,f)};function J1(T,o,S,f){let n=[],A=f===1020?";":",";for(;T.i<o.length;T.i++){if(T.char=o[T.i],T.quoted)if(T.char==="\\")T.str+=o[++T.i];else if(T.char==='"')n.push(S?S(T.str):T.str),T.str="",T.quoted=o[T.i+1]==='"',T.last=T.i+2;else T.str+=T.char;else if(T.char==='"')T.quoted=!0;else if(T.char==="{")T.last=++T.i,n.push(J1(T,o,S,f));else if(T.char==="}"){T.quoted=!1,T.last<T.i&&n.push(S?S(o.slice(T.last,T.i)):o.slice(T.last,T.i)),T.last=T.i+1;break}else if(T.char===A&&T.p!=="}"&&T.p!=='"')n.push(S?S(o.slice(T.last,T.i)):o.slice(T.last,T.i)),T.last=T.i+1;T.p=T.char}return T.last<T.i&&n.push(S?S(o.slice(T.last,T.i+1)):o.slice(T.last,T.i+1)),n}var MS=(T)=>{let o=T[0];for(let S=1;S<T.length;S++)o+=T[S]==="_"?T[++S].toUpperCase():T[S];return o},kS=(T)=>{let o=T[0].toUpperCase();for(let S=1;S<T.length;S++)o+=T[S]==="_"?T[++S].toUpperCase():T[S];return o},yS=(T)=>T.replace(/_/g,"-"),Bf=(T)=>T.replace(/([A-Z])/g,"_$1").toLowerCase(),Lf=(T)=>(T.slice(0,1)+T.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),Cf=(T)=>T.replace(/-/g,"_");function F$(T){return function o(S,f){return typeof S==="object"&&S!==null&&(f.type===114||f.type===3802)?Array.isArray(S)?S.map((n)=>o(n,f)):Object.entries(S).reduce((n,[A,$])=>Object.assign(n,{[T(A)]:o($,f)}),{}):S}}MS.column={from:MS};MS.value={from:F$(MS)};Bf.column={to:Bf};var J$={...MS};J$.column.to=Bf;kS.column={from:kS};kS.value={from:F$(kS)};Lf.column={to:Lf};var R$={...kS};R$.column.to=Lf;yS.column={from:yS};yS.value={from:F$(yS)};Cf.column={to:Cf};var W$={...yS};W$.column.to=Cf;import R1 from"net";import KM from"tls";import jf from"crypto";import O$ from"stream";import{performance as W1}from"perf_hooks";class _S extends Array{constructor(){super();Object.defineProperties(this,{count:{value:null,writable:!0},state:{value:null,writable:!0},command:{value:null,writable:!0},columns:{value:null,writable:!0},statement:{value:null,writable:!0}})}static get[Symbol.species](){return Array}}var Oo=_M;function _M(T=[]){let o=T.slice(),S=0;return{get length(){return o.length-S},remove:(f)=>{let n=o.indexOf(f);return n===-1?null:(o.splice(n,1),f)},push:(f)=>(o.push(f),f),shift:()=>{let f=o[S++];if(S===o.length)S=0,o=[];else o[S-1]=void 0;return f}}}var eT=Buffer.allocUnsafe(256),wM="BCcDdEFfHPpQSX".split("").reduce((T,o)=>{let S=o.charCodeAt(0);return T[o]=()=>{return eT[0]=S,OT.i=5,OT},T},{}),OT=Object.assign(XM,wM,{N:String.fromCharCode(0),i:0,inc(T){return OT.i+=T,OT},str(T){let o=Buffer.byteLength(T);return Nn(o),OT.i+=eT.write(T,OT.i,o,"utf8"),OT},i16(T){return Nn(2),eT.writeUInt16BE(T,OT.i),OT.i+=2,OT},i32(T,o){if(o||o===0)return eT.writeUInt32BE(T,o),OT;return Nn(4),eT.writeUInt32BE(T,OT.i),OT.i+=4,OT},z(T){return Nn(T),eT.fill(0,OT.i,OT.i+T),OT.i+=T,OT},raw(T){return eT=Buffer.concat([eT.subarray(0,OT.i),T]),OT.i=eT.length,OT},end(T=1){eT.writeUInt32BE(OT.i-T,T);let o=eT.subarray(0,OT.i);return OT.i=0,eT=Buffer.allocUnsafe(256),o}}),r=OT;function Nn(T){if(eT.length-OT.i<T){let o=eT,S=o.length;eT=Buffer.allocUnsafe(S+(S>>1)+T),o.copy(eT)}}function XM(){return OT.i=0,OT}var y$=k1,GM=1,fS=r().S().end(),O1=r().H().end(),YM=r().i32(8).i32(80877103).end(8),EM=Buffer.concat([r().E().str(r.N).i32(0).end(),fS]),HM=r().D().str("S").str(r.N).end(),iS=()=>{},zM=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),QM={83:"severity_local",86:"severity",67:"code",77:"message",68:"detail",72:"hint",80:"position",112:"internal_position",113:"internal_query",87:"where",115:"schema_name",116:"table_name",99:"column_name",100:"data type_name",110:"constraint_name",70:"file",76:"line",82:"routine"};function k1(T,o={},{onopen:S=iS,onend:f=iS,onclose:n=iS}={}){let{ssl:A,max:$,user:F,host:J,port:R,database:W,parsers:y,transform:_,onnotice:K,onnotify:H,onparameter:Y,max_pipeline:I,keep_alive:b,backoff:q,target_session_attrs:p}=T,G=Oo(),D=GM++,t={pid:null,secret:null},U=k$(ln,T.idle_timeout),v=k$(ln,T.max_lifetime),l=k$(N1,T.connect_timeout),E=null,TT,Z=new _S,oT=Buffer.alloc(0),MT=T.fetch_types,CT={},So={},No=Math.random().toString(36).slice(2),z=1,c=0,FT=0,ET=0,IT=0,fT=0,_T=0,BT=0,zT=null,KT=null,pT=!1,wT=null,Xo=null,iT=null,Po=null,jT=null,GT=null,Ko=null,Vo=null,B=null,uS=null,gT={queue:o.closed,idleTimer:U,connect(O){iT=O||!0,Z$()},terminate:aS,execute:eS,cancel:C1,end:ln,count:0,id:D};return o.closed&&o.closed.push(gT),gT;async function L1(){let O;try{O=T.socket?await Promise.resolve(T.socket(T)):new R1.Socket}catch(w){GS(w);return}return O.on("error",GS),O.on("close",c$),O.on("drain",v$),O}async function C1({pid:O,secret:w},P,JT){try{TT=r().i32(16).i32(80877102).i32(O).i32(w).end(16),await q$(),E.once("error",JT),E.once("close",P)}catch(DT){JT(DT)}}function eS(O){if(pT)return qf(O,LT.connection("CONNECTION_DESTROYED",T));if(O.cancelled)return;try{return O.state=t,B?G.push(O):(B=O,B.active=!0),m1(O),cT(I1(O))&&!O.describeFirst&&!O.cursorFn&&G.length<I&&(!O.options.onexecute||O.options.onexecute(gT))}catch(w){return G.length===0&&cT(fS),Bo(w),!0}}function I1(O){if(O.parameters.length>=65534)throw LT.generic("MAX_PARAMETERS_EXCEEDED","Max number of parameters (65534) exceeded");return O.options.simple?r().Q().str(O.statement.string+r.N).end():O.describeFirst?Buffer.concat([h$(O),O1]):O.prepare?O.prepared?vf(O):Buffer.concat([h$(O),vf(O)]):j1(O)}function h$(O){return Buffer.concat([P$(O.statement.string,O.parameters,O.statement.types,O.statement.name),GW("S",O.statement.name)])}function vf(O){return Buffer.concat([KW(O.parameters,O.statement.types,O.statement.name,O.cursorName),O.cursorFn?p$("",O.cursorRows):EM])}function j1(O){return Buffer.concat([P$(O.statement.string,O.parameters,O.statement.types),HM,vf(O)])}function m1(O){let w=[],P=[],JT=n$(O,O.strings[0],O.args[0],w,P,T);!O.tagged&&O.args.forEach((DT)=>jn(DT,w,P,T)),O.prepare=T.prepare&&("prepare"in O.options?O.options.prepare:!0),O.string=JT,O.signature=O.prepare&&P+JT,O.onlyDescribe&&delete So[O.signature],O.parameters=O.parameters||w,O.prepared=O.prepare&&O.signature in So,O.describeFirst=O.onlyDescribe||w.length&&!O.prepared,O.statement=O.prepared?So[O.signature]:{string:JT,types:P,name:O.prepare?No+z++:""},typeof T.debug==="function"&&T.debug(D,JT,w,P)}function cT(O,w){if(GT=GT?Buffer.concat([GT,O]):Buffer.from(O),w||GT.length>=1024)return b$(w);return KT===null&&(KT=setImmediate(b$)),!0}function b$(O){let w=E.write(GT,O);return KT!==null&&clearImmediate(KT),GT=KT=null,w}function N1(){Bo(LT.connection("CONNECT_TIMEOUT",T,E)),E.destroy()}async function x$(){if(cT(YM),!await new Promise((w)=>E.once("data",(P)=>w(P[0]===83)))&&A==="prefer")return KS();E.removeAllListeners(),E=KM.connect({socket:E,servername:R1.isIP(E.host)?void 0:E.host,...A==="require"||A==="allow"||A==="prefer"?{rejectUnauthorized:!1}:A==="verify-full"?{}:typeof A==="object"?A:{}}),E.on("secureConnect",KS),E.on("error",GS),E.on("close",c$),E.on("drain",v$)}function v$(){!B&&S(gT)}function dn(O){if(wT){if(wT.push(O),FT-=O.length,FT>=0)return}oT=wT?Buffer.concat(wT,fT-FT):oT.length===0?O:Buffer.concat([oT,O],oT.length+O.length);while(oT.length>4){if(fT=oT.readUInt32BE(1),fT>=oT.length){FT=fT-oT.length,wT=[oT];break}try{h1(oT.subarray(0,fT+1))}catch(w){B&&(B.cursorFn||B.describeFirst)&&cT(fS),Bo(w)}oT=oT.subarray(fT+1),FT=0,wT=null}}async function q$(){if(pT=!1,CT={},E||(E=await L1()),!E)return;if(l.start(),T.socket)return A?x$():KS();if(E.on("connect",A?x$:KS),T.path)return E.connect(T.path);E.ssl=A,E.connect(R[ET],J[ET]),E.host=J[ET],E.port=R[ET],ET=(ET+1)%R.length}function Z$(){setTimeout(q$,c?c+_T-W1.now():0)}function KS(){try{So={},MT=T.fetch_types,No=Math.random().toString(36).slice(2),z=1,v.start(),E.on("data",dn),b&&E.setKeepAlive&&E.setKeepAlive(!0,1000*b);let O=EW();cT(O)}catch(O){GS(O)}}function GS(O){if(gT.queue===o.connecting&&T.host[IT+1])return;Bo(O);while(G.length)qf(G.shift(),O)}function Bo(O){jT&&(jT.destroy(O),jT=null),B&&qf(B,O),iT&&(qf(iT,O),iT=null)}function qf(O,w){"query"in w||"parameters"in w||Object.defineProperties(w,{stack:{value:w.stack+O.origin.replace(/.*\n/,`
17
- `),enumerable:T.debug},query:{value:O.string,enumerable:T.debug},parameters:{value:O.parameters,enumerable:T.debug},args:{value:O.args,enumerable:T.debug},types:{value:O.statement&&O.statement.types,enumerable:T.debug}}),O.reject(w)}function ln(){return Po||(!gT.reserved&&f(gT),!gT.reserved&&!iT&&!B&&G.length===0?(aS(),new Promise((O)=>E&&E.readyState!=="closed"?E.once("close",O):O())):Po=new Promise((O)=>Ko=O))}function aS(){if(pT=!0,jT||B||iT||G.length)GS(LT.connection("CONNECTION_DESTROYED",T));if(clearImmediate(KT),E)E.removeListener("data",dn),E.removeListener("connect",KS),E.readyState==="open"&&E.end(r().X().end());Ko&&(Ko(),Po=Ko=null)}async function c$(O){if(oT=Buffer.alloc(0),FT=0,wT=null,clearImmediate(KT),E.removeListener("data",dn),E.removeListener("connect",KS),U.cancel(),v.cancel(),l.cancel(),E.removeAllListeners(),E=null,iT)return Z$();!O&&(B||G.length)&&GS(LT.connection("CONNECTION_CLOSED",T,E)),c=W1.now(),O&&T.shared.retries++,_T=(typeof q==="function"?q(T.shared.retries):q)*1000,n(gT,LT.connection("CONNECTION_CLOSED",T,E))}function h1(O,w=O[0]){(w===68?b1:w===100?WW:w===65?nW:w===83?x1:w===90?v1:w===67?q1:w===50?r$:w===49?Z1:w===116?c1:w===84?r1:w===82?P1:w===110?u1:w===75?e1:w===69?SW:w===115?AW:w===51?$W:w===71?FW:w===78?MW:w===72?JW:w===99?OW:w===73?kW:w===86?yW:w===118?_W:w===87?RW:wW)(O)}function b1(O){let w=7,P,JT,DT,dT=B.isRaw?new Array(B.statement.columns.length):{};for(let aT=0;aT<B.statement.columns.length;aT++)JT=B.statement.columns[aT],P=O.readInt32BE(w),w+=4,DT=P===-1?null:B.isRaw===!0?O.subarray(w,w+=P):JT.parser===void 0?O.toString("utf8",w,w+=P):JT.parser.array===!0?JT.parser(O.toString("utf8",w+1,w+=P)):JT.parser(O.toString("utf8",w,w+=P)),B.isRaw?dT[aT]=B.isRaw===!0?DT:_.value.from?_.value.from(DT,JT):DT:dT[JT.name]=_.value.from?_.value.from(DT,JT):DT;B.forEachFn?B.forEachFn(_.row.from?_.row.from(dT):dT,Z):Z[BT++]=_.row.from?_.row.from(dT):dT}function x1(O){let[w,P]=O.toString("utf8",5,O.length-1).split(r.N);if(CT[w]=P,T.parameters[w]!==P)T.parameters[w]=P,Y&&Y(w,P)}function v1(O){if(B&&B.options.simple&&B.resolve(Xo||Z),B=Xo=null,Z=new _S,l.cancel(),iT){if(p){if(!CT.in_hot_standby||!CT.default_transaction_read_only)return oW();else if(TW(p,CT))return aS()}if(MT)return iT===!0&&(iT=null),a1();iT!==!0&&eS(iT),T.shared.retries=IT=0,iT=null;return}while(G.length&&(B=G.shift())&&(B.active=!0,B.cancelled))k1(T).cancel(B.state,B.cancelled.resolve,B.cancelled.reject);if(B)return;gT.reserved?!gT.reserved.release&&O[5]===73?Po?aS():(gT.reserved=null,S(gT)):gT.reserved():Po?aS():S(gT)}function q1(O){BT=0;for(let w=O.length-1;w>0;w--){if(O[w]===32&&O[w+1]<58&&Z.count===null)Z.count=+O.toString("utf8",w+1,O.length-1);if(O[w-1]>=65){Z.command=O.toString("utf8",5,w),Z.state=t;break}}if(uS&&(uS(),uS=null),Z.command==="BEGIN"&&$!==1&&!gT.reserved)return Bo(LT.generic("UNSAFE_TRANSACTION","Only use sql.begin, sql.reserved or max: 1"));if(B.options.simple)return r$();if(B.cursorFn)Z.count&&B.cursorFn(Z),cT(fS);B.resolve(Z)}function Z1(){B.parsing=!1}function r$(){!Z.statement&&(Z.statement=B.statement),Z.columns=B.statement.columns}function c1(O){let w=O.readUInt16BE(5);for(let P=0;P<w;++P)!B.statement.types[P]&&(B.statement.types[P]=O.readUInt32BE(7+P*4));B.prepare&&(So[B.signature]=B.statement),B.describeFirst&&!B.onlyDescribe&&(cT(vf(B)),B.describeFirst=!1)}function r1(O){if(Z.command)Xo=Xo||[Z],Xo.push(Z=new _S),Z.count=null,B.statement.columns=null;let w=O.readUInt16BE(5),P=7,JT;B.statement.columns=Array(w);for(let DT=0;DT<w;++DT){JT=P;while(O[P++]!==0);let dT=O.readUInt32BE(P),aT=O.readUInt16BE(P+4),po=O.readUInt32BE(P+6);B.statement.columns[DT]={name:_.column.from?_.column.from(O.toString("utf8",JT,P-1)):O.toString("utf8",JT,P-1),parser:y[po],table:dT,number:aT,type:po},P+=18}if(Z.statement=B.statement,B.onlyDescribe)return B.resolve(B.statement),cT(fS)}async function P1(O,w=O.readUInt32BE(5)){(w===3?p1:w===5?i1:w===10?g1:w===11?d1:w===12?l1:w!==0?XW:iS)(O,w)}async function p1(){let O=await un();cT(r().p().str(O).z(1).end())}async function i1(O){let w="md5"+await M1(Buffer.concat([Buffer.from(await M1(await un()+F)),O.subarray(9)]));cT(r().p().str(w).z(1).end())}async function g1(){Vo=(await jf.randomBytes(18)).toString("base64"),r().p().str("SCRAM-SHA-256"+r.N);let O=r.i;cT(r.inc(4).str("n,,n=*,r="+Vo).i32(r.i-O-4,O).end())}async function d1(O){let w=O.toString("utf8",9).split(",").reduce((aT,po)=>(aT[po[0]]=po.slice(2),aT),{}),P=await jf.pbkdf2Sync(await un(),Buffer.from(w.s,"base64"),parseInt(w.i),32,"sha256"),JT=await hn(P,"Client Key"),DT="n=*,r="+Vo+",r="+w.r+",s="+w.s+",i="+w.i+",c=biws,r="+w.r;zT=(await hn(await hn(P,"Server Key"),DT)).toString("base64");let dT="c=biws,r="+w.r+",p="+UM(JT,Buffer.from(await hn(await DM(JT),DT))).toString("base64");cT(r().p().str(dT).end())}function l1(O){if(O.toString("utf8",9).split(r.N,1)[0].slice(2)===zT)return;Bo(LT.generic("SASL_SIGNATURE_MISMATCH","The server did not return the correct signature")),E.destroy()}function un(){return Promise.resolve(typeof T.pass==="function"?T.pass():T.pass)}function u1(){if(Z.statement=B.statement,Z.statement.columns=[],B.onlyDescribe)return B.resolve(B.statement),cT(fS)}function e1(O){t.pid=O.readUInt32BE(5),t.secret=O.readUInt32BE(9)}async function a1(){MT=!1,(await new wo([`
15
+ ${w.trace}`:`No previous disposal trace for ${F} was found.`),f}let R=o.moleculeGraph.getRelationEntries({downstreamMoleculeKey:$.stringKey}).filter(([,{source:w}])=>w!==n).map(([w])=>vo(w));if(S)A.moleculeGraph.delete(n);A.moleculeGraph.set({upstreamMoleculeKey:J.stringKey,downstreamMoleculeKey:$.stringKey},{source:J.stringKey});let M={type:"molecule_transfer",key:$.key,from:R,to:[J.key]};if(Mo(A)&&A.transactionMeta.phase==="building")A.transactionMeta.update.updates.push(M);return f}function $A(o,T,f){switch(T){case"newValue":{yF(o,f);break}case"oldValue":{Af(f,o.token);break}}}function FA(o,T,f){switch(T){case"newValue":{Af(f,o.token);break}case"oldValue":{if(yF(o,f),o.subType==="atom")f.valueMap.set(o.token.key,o.value);break}}}function yF(o,T){let{family:f}=o.token;if(f){let S=T.families.get(f.key);if(S)i(T,S,vo(f.subKey))}}function XF(o,T,f){switch(T){case"newValue":ff(f,o.provenance,o.key);break;case"oldValue":Sf(f,o.key);break}}function HF(o,T,f){switch(T){case"newValue":Sf(f,o.key);break;case"oldValue":{let S=o.provenance.map(vo);ff(f,S,o.key);for(let[n,A]of o.values){let $=f.families.get(n);if($){i(f,$,o.key);let F=`${n}(${fo(o.key)})`;f.valueMap.set(F,A)}}}break}}function KF(o,T,f){switch(T){case"newValue":{let S=o.to.length===1?o.to[0]:o.to;Ef(f,S,o.key,"exclusive")}break;case"oldValue":{let S=o.from.length===1?o.from[0]:o.from;Ef(f,S,o.key,"exclusive")}break}}function sS(o,T,f){let S=o==="newValue"?T.updates:[...T.updates].reverse();for(let n of S)switch(n.type){case"atom_update":case"selector_update":eS(o,n,f);break;case"state_creation":$A(n,o,f);break;case"state_disposal":FA(n,o,f);break;case"molecule_creation":XF(n,o,f);break;case"molecule_disposal":HF(n,o,f);break;case"molecule_transfer":KF(n,o,f);break;case"transaction_update":sS(o,n,f);break}}function GF(o,T,f){if(mo(o)&&T)o.transactionMeta.epoch.set(T,f)}function YF(o,T,f){if(!mo(o))return;let n=o.transactionMeta.actionContinuities.getRelatedKey(T);if(n!==void 0)o.transactionMeta.epoch.set(n,f)}var EF=(o,T)=>{let f=C(T),{parent:S}=f;if(S===null||!Mo(f)||f.transactionMeta?.phase!=="building"){T.logger.warn("\uD83D\uDC1E","transaction","???","applyTransaction called outside of a transaction. This is probably a bug in AtomIO.");return}f.transactionMeta.phase="applying",f.transactionMeta.update.output=o,S.child=null,S.on.transactionApplying.next(f.transactionMeta);let{updates:n}=f.transactionMeta.update;if(T.logger.info("\uD83D\uDEC4","transaction",f.transactionMeta.update.key,`Applying transaction with ${n.length} updates:`,n),sS("newValue",f.transactionMeta.update,S),mo(S))YF(S,f.transactionMeta.update.key,f.transactionMeta.update.epoch),$o(T,{key:f.transactionMeta.update.key,type:"transaction"})?.subject.next(f.transactionMeta.update),T.logger.info("\uD83D\uDEEC","transaction",f.transactionMeta.update.key,"Finished applying transaction.");else if(Mo(S))S.transactionMeta.update.updates.push(f.transactionMeta.update);S.on.transactionApplying.next(null)};function zF(o,T,f){if(!mo(o))return;let{epoch:n,actionContinuities:A}=o.transactionMeta;if(A.set(T,f),!n.has(T))n.set(T,-1)}function QF(o){return{store:o}}function Ro(o,...T){let f,S,n;if(T.length===1)f=T[0];else S=T[0],n=T[1],f=i(o,S,n);if("counterfeit"in f&&"family"in f){S=o.families.get(f.family.key);let A=f.family.subKey,$=o.disposalTraces.buffer.find((F)=>F?.key===A);switch(o.logger.error("\u274C",f.type,f.key,`could not be retrieved because it was not found in the store "${o.config.name}".`,$?`This state was previously disposed:
16
+ ${$.trace}`:"No previous disposal trace was found."),S.type){case"atom_family":case"mutable_atom_family":return o.defaults.get(S.key);case"selector_family":case"readonly_selector_family":{if(o.defaults.has(S.key))return o.defaults.get(f.family.key);let F=$o(o,S).default(A);return o.defaults.set(S.key,F),F}}}return PT(o,$o(o,f))}class No{a;b;cardinality;relations=new Map;contents=new Map;isAType;isBType;isContent;makeContentKey=(o,T)=>`${o}:${T}`;warn;getRelatedKeys(o){return this.relations.get(o)}addRelation(o,T){let f=this.relations.get(o),S=this.relations.get(T);if(f)f.add(T);else f=new Set([T]),this.relations.set(o,f);if(S)S.add(o);else S=new Set([o]),this.relations.set(T,S)}deleteRelation(o,T){let f=this.relations.get(o);if(f){if(f.delete(T),f.size===0)this.relations.delete(o);let S=this.relations.get(T);if(S){if(S.delete(o),S.size===0)this.relations.delete(T)}}}replaceRelationsUnsafely(o,T){this.relations.set(o,new Set(T));for(let f of T){let S=new Set().add(o);this.relations.set(f,S)}}replaceRelationsSafely(o,T){let f=this.relations.get(o),S=this.isAType?.(o)?o:void 0,n=S===void 0?o:void 0;if(f)for(let A of f){S??=A,n??=A;let $=this.relations.get(A);if($){if($.size===1)this.relations.delete(A);else $.delete(o);this.contents.delete(this.makeContentKey(S,n))}}this.relations.set(o,new Set(T));for(let A of T){let $=this.relations.get(A);if($)$.add(o);else $=new Set().add(o),this.relations.set(A,$)}}getContentInternal(o){return this.contents.get(o)}setContent(o,T){this.contents.set(o,T)}deleteContent(o){this.contents.delete(o)}constructor(o,T){if(this.a=o.between[0],this.b=o.between[1],this.cardinality=o.cardinality,!T?.externalStore)this.relations=new Map(o.relations?.map(([f,S])=>[f,new Set(S)])),this.contents=new Map(o.contents);if(this.isAType=T?.isAType??null,this.isBType=T?.isBType??null,this.isContent=T?.isContent??null,T?.makeContentKey)this.makeContentKey=T.makeContentKey;if(T?.externalStore){let f=T.externalStore;if(this.has=(S,n)=>f.has(S,n),this.addRelation=(S,n)=>{f.addRelation(S,n)},this.deleteRelation=(S,n)=>{f.deleteRelation(S,n)},this.replaceRelationsSafely=(S,n)=>{f.replaceRelationsSafely(S,n)},this.replaceRelationsUnsafely=(S,n)=>{f.replaceRelationsUnsafely(S,n)},this.getRelatedKeys=(S)=>f.getRelatedKeys(S),f.getContent)this.getContentInternal=(S)=>{return f.getContent(S)},this.setContent=(S,n)=>{f.setContent(S,n)},this.deleteContent=(S)=>{f.deleteContent(S)};for(let[S,n]of o.relations??[]){let A=this.isAType?.(S)?S:void 0,$=A===void 0?S:void 0;for(let F of n)A??=F,$??=F,this.addRelation(A,$)}for(let[S,n]of o.contents??[])this.setContent(S,n)}if(T?.warn)this.warn=T.warn}toJSON(){return{between:[this.a,this.b],cardinality:this.cardinality,relations:[...this.relations.entries()].map(([o,T])=>[o,[...T]]),contents:[...this.contents.entries()]}}set(...o){let T,f,S;switch(o.length){case 1:{let n=o[0];T=n[this.a],f=n[this.b],S=void 0;break}case 2:{let n=o[0];if(typeof n==="string")[T,f]=o;else T=n[this.a],f=n[this.b],S=o[1];break}default:{T=o[0],f=o[1],S=o[2];break}}switch(this.cardinality){case"1:1":{let n=this.getRelatedKey(T);if(n&&n!==f)this.delete(T,n)}case"1:n":{let n=this.getRelatedKey(f);if(n&&n!==T)this.delete(n,f)}}if(S){let n=this.makeContentKey(T,f);this.setContent(n,S)}return this.addRelation(T,f),this}delete(o,T){T=typeof T==="string"?T:o[this.b];let f=typeof o==="string"?o:o[this.a];if(f===void 0&&typeof T==="string"){let S=this.getRelatedKeys(T);if(S)for(let n of S)this.delete(n,T)}if(typeof f==="string"&&T===void 0){let S=this.getRelatedKeys(f);if(S)for(let n of S)this.delete(f,n)}if(typeof f==="string"&&typeof T==="string"){this.deleteRelation(f,T);let S=this.makeContentKey(f,T);this.deleteContent(S)}return this}getRelatedKey(o){let T=this.getRelatedKeys(o);if(T){if(T.size>1)this.warn?.(`${T.size} related keys were found for key "${o}": (${[...T].map((S)=>`"${S}"`).join(", ")}). Only one related key was expected.`);let f;for(let S of T){f=S;break}return f}}replaceRelations(o,T,f){let S=!Array.isArray(T),n=S?Object.keys(T):T;if(f?.reckless)this.replaceRelationsUnsafely(o,n);else this.replaceRelationsSafely(o,n);if(S)for(let A of n){let $=this.makeContentKey(o,A),F=T[A];this.setContent($,F)}return this}getContent(o,T){let f=this.makeContentKey(o,T);return this.getContentInternal(f)}getRelationEntries(o){let T=o[this.a],f=o[this.b];if(T!==void 0&&f===void 0){let S=this.getRelatedKeys(T);if(S)return[...S].map((n)=>{return[n,this.getContent(T,n)]})}if(T===void 0&&f!==void 0){let S=this.getRelatedKeys(f);if(S)return[...S].map((n)=>{return[n,this.getContent(n,f)]})}return[]}has(o,T){if(T)return this.getRelatedKeys(o)?.has(T)??!1;return this.relations.has(o)}}class kT extends Map{source;deleted=new Set;constructor(o){super();this.source=o}get(o){if(super.has(o))return super.get(o);if(!this.deleted.has(o)&&this.source.has(o))return this.source.get(o);return}set(o,T){return this.deleted.delete(o),super.set(o,T)}hasOwn(o){return super.has(o)}has(o){return!this.deleted.has(o)&&(super.has(o)||this.source.has(o))}delete(o){return this.deleted.add(o),super.delete(o)}}var DF=(o,T,f,S)=>{let n=C(o),A={parent:n,child:null,on:n.on,loggers:n.loggers,logger:n.logger,config:n.config,atoms:new kT(n.atoms),atomsThatAreDefault:new Set(n.atomsThatAreDefault),families:new kT(n.families),joins:new kT(n.joins),operation:{open:!1},readonlySelectors:new kT(n.readonlySelectors),timelines:new kT(n.timelines),timelineTopics:new No(n.timelineTopics.toJSON()),trackers:new Map,transactions:new kT(n.transactions),selectorAtoms:new No(n.selectorAtoms.toJSON()),selectorGraph:new No(n.selectorGraph.toJSON(),{makeContentKey:(...R)=>R.sort().join(":")}),selectors:new kT(n.selectors),valueMap:new kT(n.valueMap),defaults:n.defaults,disposalTraces:o.disposalTraces.copy(),molecules:new kT(n.molecules),moleculeGraph:new No(n.moleculeGraph.toJSON(),{makeContentKey:n.moleculeGraph.makeContentKey}),moleculeData:new No(n.moleculeData.toJSON(),{makeContentKey:n.moleculeData.makeContentKey}),moleculeJoins:new No(n.moleculeJoins.toJSON(),{makeContentKey:n.moleculeJoins.makeContentKey}),miscResources:new kT(n.miscResources)},$=UF(o,T),F={phase:"building",update:{type:"transaction_update",key:T,id:S,epoch:$===void 0?Number.NaN:$+1,updates:[],params:f,output:void 0},toolkit:{get:(...R)=>Ro(J,...R),set:(...R)=>{to(J,...R)},run:(R,M=pS())=>zf(J,R,M),find:(R,M)=>i(J,R,M),json:(R)=>jo(J,R),dispose:(...R)=>{Af(J,...R)},env:()=>QF(J)}},J=Object.assign(A,{transactionMeta:F});return n.child=J,o.logger.info("\uD83D\uDEEB","transaction",T,"Building transaction with params:",f),J};function JA(o,T){let f={key:T.key,type:"transaction",run:(A,$)=>{let F=DF(o,T.key,A,$);try{let J=C(o),{toolkit:R}=F.transactionMeta,M=T.do(R,...A);return EF(M,J),M}catch(J){throw fF(S),o.logger.warn("\uD83D\uDCA5","transaction",T.key,"caught:",J),J}},install:(A)=>JA(A,T),subject:new oo},S=C(o);S.transactions.set(f.key,f);let n=ST(f);return o.on.transactionCreation.next(n),n}function UF(o,T){let f=mo(o),S=f?o.transactionMeta.actionContinuities.getRelatedKey(T):void 0;return f&&S!==void 0?o.transactionMeta.epoch.get(S):void 0}function JS(o){return JA(So.STORE,o)}class tF{parent=null;child=null;valueMap=new Map;defaults=new Map;atoms=new Map;selectors=new Map;readonlySelectors=new Map;atomsThatAreDefault=new Set;selectorAtoms=new No({between:["selectorKey","atomKey"],cardinality:"n:n"});selectorGraph=new No({between:["upstreamSelectorKey","downstreamSelectorKey"],cardinality:"n:n"},{makeContentKey:(...o)=>o.sort().join(":")});trackers=new Map;families=new Map;joins=new Map;transactions=new Map;transactionMeta={epoch:new Map,actionContinuities:new No({between:["continuity","action"],cardinality:"1:n"})};timelines=new Map;timelineTopics=new No({between:["timelineKey","topicKey"],cardinality:"1:n"});disposalTraces=new PS(100);molecules=new Map;moleculeJoins=new No({between:["moleculeKey","joinKey"],cardinality:"n:n"},{makeContentKey:(...o)=>o.sort().join(":")});moleculeGraph=new No({between:["upstreamMoleculeKey","downstreamMoleculeKey"],cardinality:"n:n"},{makeContentKey:(...o)=>o.sort().join(":")});moleculeData=new No({between:["moleculeKey","stateFamilyKey"],cardinality:"n:n"},{makeContentKey:(...o)=>o.sort().join(":")});miscResources=new Map;on={atomCreation:new oo,atomDisposal:new oo,selectorCreation:new oo,selectorDisposal:new oo,timelineCreation:new oo,transactionCreation:new oo,transactionApplying:new oA(null),operationClose:new oo,moleculeCreation:new oo,moleculeDisposal:new oo};operation={open:!1};config={name:"IMPLICIT_STORE",lifespan:"ephemeral"};loggers=[new SA("warn",(o,T,f)=>!f.includes("\uD83D\uDD0D"))];logger={error:(...o)=>{for(let T of this.loggers)T.error(...o)},info:(...o)=>{for(let T of this.loggers)T.info(...o)},warn:(...o)=>{for(let T of this.loggers)T.warn(...o)}};constructor(o,T=null){if(this.config={...T?.config,...o},T!==null){if(this.valueMap=new Map(T?.valueMap),this.operation={...T?.operation},mo(T))this.transactionMeta={epoch:new Map(T?.transactionMeta.epoch),actionContinuities:new No(T?.transactionMeta.actionContinuities.toJSON())};for(let[,S]of T.families){if(S.internalRoles?.includes("mutable")||S.internalRoles?.includes("join"))continue;S.install(this)}let f=new Set;for(let[,S]of T.atoms){if(f.has(S.key))continue;if(S.install(this),S.type==="mutable_atom"){let n=jo(T,S),A=bT(S);f.add(n.key),f.add(A.key)}}for(let[,S]of T.readonlySelectors)S.install(this);for(let[,S]of T.selectors){if(f.has(S.key))continue;S.install(this)}for(let[,S]of T.transactions)S.install(this);for(let[,S]of T.timelines)S.install(this)}}}var So={get STORE(){if(!globalThis.ATOM_IO_IMPLICIT_STORE)globalThis.ATOM_IO_IMPLICIT_STORE=new tF({name:"IMPLICIT_STORE",lifespan:"ephemeral"});return globalThis.ATOM_IO_IMPLICIT_STORE}};function $o(o,T){let f,S=o;while(S!==null){switch(T.type){case"atom":case"mutable_atom":f=S.atoms.get(T.key);break;case"selector":f=S.selectors.get(T.key);break;case"readonly_selector":f=S.readonlySelectors.get(T.key);break;case"atom_family":case"mutable_atom_family":case"selector_family":case"readonly_selector_family":f=S.families.get(T.key);break;case"timeline":f=S.timelines.get(T.key);break;case"transaction":f=S.transactions.get(T.key);break}if(f)return f;S=S.child}throw new nf(T,o)}function VF(o,T,f){let S=o.families.get(T.key);if(S===void 0)throw new nf(T,o);let n=S(f),A=C(o);if(n.family){if(mo(A))switch(n.type){case"atom":case"mutable_atom":o.on.atomCreation.next(n);break;case"selector":case"readonly_selector":o.on.selectorCreation.next(n);break}else if(Mo(A)&&A.on.transactionApplying.state===null)A.transactionMeta.update.updates.push({type:"state_creation",token:n})}return n}function BF(o,T,f){let S=fo(f),n=`${T.key}(${S})`,A=C(o),$;switch(T.type){case"atom_family":case"mutable_atom_family":$=A.atoms.get(n);break;case"selector_family":$=A.selectors.get(n);break;case"readonly_selector_family":$=A.readonlySelectors.get(n);break}if($)return ST($);return $}function i(o,T,f){let S=BF(o,T,f);if(S)return S;let n=fo(f),A=o.molecules.get(n);if(!A&&o.config.lifespan==="immortal"){let $=d$(T,f);return o.logger.error("\u274C",$.type,$.key,`was not found in store "${o.config.name}"; returned a counterfeit token.`),$}if(S=VF(o,T,f),A)C(o).moleculeData.set(n,T.key);return S}function Af(o,...T){let f;if(T.length===1)f=T[0];else{let S=T[0],n=T[1];f=i(o,S,n)}try{$o(o,f)}catch(S){o.logger.error("\u274C",f.type,f.key,`could not be disposed because it was not found in the store "${o.config.name}".`);return}switch(f.type){case"atom":case"mutable_atom":RA(o,f);break;case"selector":case"readonly_selector":LF(o,f);break}}var aS=(o,T)=>C(o).atoms.has(T),IM=(o,T)=>C(o).selectors.has(T),jM=(o,T)=>C(o).readonlySelectors.has(T),CF=(o,T)=>aS(o,T)||IM(o,T)||jM(o,T);var on=(o,T)=>{return C(T).selectorGraph.getRelationEntries({downstreamSelectorKey:o}).filter(([S,{source:n}])=>n!==o).map(([S,{source:n}])=>n).filter((S)=>CF(T,S))};var MA=(o,T,f)=>{let S=[],n=on(o,f);while(n.length>0){let A=n.shift();if(T.has(A))continue;if(T.add(A),!aS(f,A))n.push(...on(A,f));else if(!S.includes(A))S.push(A)}return S},IF=(o,T)=>{let f=o.key,S=on(f,T),n=new Set;return S.flatMap((A)=>aS(T,A)?A:MA(A,n,T))};var jF=(o,T,f,S)=>{let n=C(S);if(T.type==="atom"||T.type==="mutable_atom")n.selectorAtoms.set({selectorKey:o,atomKey:T.key}),S.logger.info("\uD83D\uDD0D","selector",o,`discovers root atom "${T.key}"`);else{let A=MA(T.key,f,S);S.logger.info("\uD83D\uDD0D","selector",o,`discovers root atoms: [ ${A.map(($)=>`"${$}"`).join(", ")} ]`);for(let $ of A)n.selectorAtoms=n.selectorAtoms.set({selectorKey:o,atomKey:$})}f.add(T.key)};var Tn=(o,T,f)=>({get:(...S)=>{let n=C(f),A;if(S.length===2){let[J,R]=S;A=i(f,J,R)}else[A]=S;let $=$o(f,A),F=PT(f,$);return f.logger.info("\uD83D\uDD0C","selector",o,`registers dependency ( "${A.key}" =`,F,")"),n.selectorGraph.set({upstreamSelectorKey:A.key,downstreamSelectorKey:o},{source:A.key}),jF(o,A,T,f),F},set:(...S)=>{let n,A;if(S.length===2)n=S[0],A=S[1];else{let J=S[0],R=S[1];A=S[2],n=i(f,J,R)}let $=C(f),F=$o($,n);uS($,F,A)},find:(S,n)=>i(f,S,n),json:(S)=>jo(f,S)});var SS=(o,T,f)=>{let S=C(o),n=new oo,A=new Set,{get:$,find:F,json:J}=Tn(T.key,A,S),R=()=>{let X=T.get({get:$,find:F,json:J});return OT(C(o),T.key,X,n),A.clear(),X},M={...T,subject:n,install:(X)=>SS(X,T,f),get:R,type:"readonly_selector",...f&&{family:f}};S.readonlySelectors.set(T.key,M);let _=R();o.logger.info("\u2728",M.type,M.key,"=",_);let w={key:T.key,type:"readonly_selector"};if(f)w.family=f;return w};var RS=(o,T,f)=>{let S=C(o),n=new oo,A=new Set,$=Tn(T.key,A,S),{find:F,get:J,json:R}=$,M={find:F,get:J,json:R},_=(L=T.get,h=C(o))=>{let q=L(M);return OT(h,T.key,q,n),A.clear(),q},X={...T,subject:n,install:(L)=>RS(L,T,f),get:_,set:(L)=>{let h=C(o),q=_(T.get,h),P=lS(L)(q);if(o.logger.info("\uD83D\uDCDD","selector",T.key,"set (",q,"->",P,")"),OT(h,T.key,P,n),Qf(h,T.key),mo(h))n.next({newValue:P,oldValue:q});T.set($,P)},type:"selector",...f&&{family:f}};S.selectors.set(T.key,X);let U=_();o.logger.info("\u2728",X.type,X.key,"=",U);let K={key:T.key,type:"selector"};if(f)K.family=f;return K};function mT(o,T){if("set"in T){let n=RS(o,T,void 0);return o.on.selectorCreation.next(n),n}let S=SS(o,T,void 0);return o.on.selectorCreation.next(S),S}function LF(o,T){let f=C(o),{key:S}=T,n=$o(f,T);if(!n.family)o.logger.error("\u274C","selector",S,"Standalone selectors cannot be disposed.");else{if(f.molecules.get(n.family.subKey))f.moleculeData.delete(n.family.subKey,n.family.key);let $;switch(T.type){case"selector":f.selectors.delete(S),$={key:n.family.key,type:"selector_family"},$o(o,$).subject.next({type:"state_disposal",subType:"selector",token:T});break;case"readonly_selector":f.readonlySelectors.delete(S),$={key:n.family.key,type:"readonly_selector_family"},$o(o,$).subject.next({type:"state_disposal",subType:"selector",token:T});break}if(f.valueMap.delete(S),f.selectorAtoms.delete(S),f.selectorGraph.delete(S),o.logger.info("\uD83D\uDD25",T.type,S,"deleted"),Mo(f)&&f.transactionMeta.phase==="building")f.transactionMeta.update.updates.push({type:"state_disposal",subType:"selector",token:T});else o.on.selectorDisposal.next(T)}}function nS(o,T,f){let S={key:T.key,type:"selector_family"},n=o.families.get(T.key);if(n)o.logger.error("\u2757","selector_family",T.key,`Overwriting an existing ${VT(n)} "${n.key}" in store "${o.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let A=new oo,F=Object.assign((J)=>{let R=fo(J),M={key:T.key,subKey:R},_=`${T.key}(${R})`,w=C(o),X=RS(w,{key:_,get:T.get(J),set:T.set(J)},M);return A.next({type:"state_creation",token:X}),X},S,{internalRoles:f,subject:A,install:(J)=>nS(J,T),default:(J)=>{return T.get(J)({get:(...M)=>Ro(o,...M),find:(M,_)=>i(o,M,_),json:(M)=>jo(o,M)})}});return o.families.set(T.key,F),S}function mF(o,T,f){return nS(o,{key:`${T.key}:JSON`,get:(n)=>({get:A})=>{let $=A(T,n);return f.toJson($)},set:(n)=>({set:A},$)=>{A(T,n,f.fromJson($))}},["mutable","json"])}var vo=(o)=>JSON.parse(o),fo=(o)=>JSON.stringify(o),n4=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];var NF=(o,T)=>{let f=C(o);if(f.operation.open)return f.operation.prev.get(T.key);return f.valueMap.get(T.key)};var kA=(o,T)=>{let f=C(o);return IF(T,o).map((n)=>{let A=f.atoms.get(n);if(A===void 0)throw new Error(`Atom "${n}", a dependency of selector "${T.key}", not found in store "${o.config.name}".`);return A.subject.subscribe(`${T.type}:${T.key}`,($)=>{o.logger.info("\uD83D\uDCE2",T.type,T.key,"root",n,"went",$.oldValue,"->",$.newValue);let F=NF(f,T),J=PT(f,T);o.logger.info("\u2728",T.type,T.key,"went",F,"->",J),T.subject.next({newValue:J,oldValue:F})})})};function lo(o,T,f,S){function n(_){if(o.operation.open){let w=o.on.operationClose.subscribe(`state subscription ${f}`,()=>{w(),S(_)})}else S(_)}let A=$o(o,T);o.logger.info("\uD83D\uDC40",A.type,A.key,`Adding subscription "${f}"`);let $=A.type==="selector"||A.type==="readonly_selector",F=null,J=n;if($)F=kA(o,A),J=(_)=>{if(F)F.length=0,F.push(...kA(o,A));n(_)};let R=A.subject.subscribe(f,J);return()=>{if(o.logger.info("\uD83D\uDE48",A.type,A.key,`Removing subscription "${f}"`),R(),F)for(let _ of F)_()}}var WA=(o,T,f,S)=>{let n=$o(o,T);o.logger.info("\uD83D\uDC40","timeline",T.key,`Adding subscription "${f}"`);let A=n.subject.subscribe(f,S);return()=>{o.logger.info("\uD83D\uDE48","timeline",T.key,`Removing subscription "${f}" from timeline`),A()}};var OA=(o,T,f,S)=>{let n=$o(o,T);o.logger.info("\uD83D\uDC40","transaction",T.key,`Adding subscription "${f}"`);let A=n.subject.subscribe(f,S);return()=>{o.logger.info("\uD83D\uDE48","transaction",T.key,`Removing subscription "${f}"`),A()}};class $f{Update;initializeState(o,T){let f=`*${o.key}`;T.atoms.delete(f),T.valueMap.delete(f);let S=o.family?{key:`*${o.family.key}`,subKey:o.family.subKey}:void 0,n=FT(T,{key:f,default:null},S);if(T.parent?.valueMap.has(f)){let A=T.parent.valueMap.get(f);T.valueMap.set(f,A)}return n}unsubscribeFromInnerValue;unsubscribeFromState;observeCore(o,T,f){let S=`tracker:${f.config.name}:${Mo(f)?f.transactionMeta.update.key:"main"}:${o.key}`,n=Ro(f,o);this.unsubscribeFromInnerValue=n.subscribe(S,(A)=>{to(f,T,A)}),this.unsubscribeFromState=lo(f,o,S,(A)=>{if(A.newValue!==A.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=A.newValue.subscribe(S,($)=>{to(f,T,$)})})}updateCore(o,T,f){let S=`tracker:${f.config.name}:${Mo(f)?f.transactionMeta.update.key:"main"}:${o.key}`;lo(f,T,S,({newValue:n,oldValue:A})=>{let $=f.timelineTopics.getRelatedKey(T.key);if($){if(f.timelines.get($)?.timeTraveling){let R=WA(f,{key:$,type:"timeline"},S,(M)=>{R(),to(f,o,(_)=>{if(M==="redo"&&n)_.do(n);else if(M==="undo"&&A)_.undo(A);return _})});return}}let F=f.on.operationClose.subscribe(S,()=>{F();let J=Ro(f,o),R=n===null?-1:J.getUpdateNumber(n),M=R-J.cacheUpdateNumber;if(n&&M===1)to(f,o,(_)=>(_.do(n),_));else f.logger.info("\u274C","mutable_atom",o.key,`could not be updated. Expected update number ${J.cacheUpdateNumber+1}, but got ${R}`)})})}mutableState;latestUpdateState;[Symbol.dispose];constructor(o,T){this.mutableState=o;let f=C(T);this.latestUpdateState=this.initializeState(o,f),this.observeCore(o,this.latestUpdateState,f),this.updateCore(o,this.latestUpdateState,f),f.trackers.set(o.key,this),this[Symbol.dispose]=()=>{this.unsubscribeFromInnerValue(),this.unsubscribeFromState(),f.trackers.delete(o.key)}}}function MS(o,T,f){o.logger.info("\uD83D\uDD28","atom",T.key,`creating in store "${o.config.name}"`);let S=C(o),n=S.atoms.get(T.key);if(n&&n.type==="mutable_atom")return o.logger.error("\u274C","atom",T.key,"Tried to create atom, but it already exists in the store."),ST(n);let A=new oo,$={...T,type:"mutable_atom",install:(R)=>{return R.logger.info("\uD83D\uDEE0\uFE0F","atom",T.key,`installing in store "${R.config.name}"`),MS(R,T,f)},subject:A};if(f)$.family=f;let F=T.default();S.atoms.set($.key,$),fn(o,T.key),OT(S,T.key,F,A);let J=ST($);if(T.effects){let R=0,M=[];for(let _ of T.effects){let w=_({setSelf:(X)=>{to(o,J,X)},onSet:(X)=>lo(o,J,`effect[${R}]`,X)});if(w)M.push(w);++R}$.cleanup=()=>{for(let _ of M)_()}}if(new $f(J,o),!f)i$(J,T,o);return J}class _A{trackers=new Map;Update;latestUpdateAtoms;mutableAtoms;constructor(o,T){let f=NT(T,{key:`*${o.key}`,default:null},["mutable","updates"]);this.latestUpdateAtoms=$o(T,f),this.mutableAtoms=o,this.mutableAtoms.subject.subscribe(`store=${T.config.name}::tracker-atom-family`,(S)=>{let{type:n,token:A}=S;if(A.family){let $=vo(A.family.subKey);switch(n){case"state_creation":this.trackers.set($,new $f(A,T));break;case"state_disposal":{let F=this.trackers.get($);if(F)F[Symbol.dispose](),this.trackers.delete($)}break}}})}}function fS(o,T,f){let S={key:T.key,type:"mutable_atom_family"},n=o.families.get(T.key);if(n)o.logger.error("\u2757","mutable_atom_family",T.key,`Overwriting an existing ${VT(n)} "${n.key}" in store "${o.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let A=new oo,F=Object.assign((J)=>{let R=fo(J),M={key:T.key,subKey:R},_=`${T.key}(${R})`,w=C(o),X={key:_,default:()=>T.default(J),toJson:T.toJson,fromJson:T.fromJson,mutable:!0};if(T.effects)X.effects=T.effects(J);let U=MS(w,X,M);return A.next({type:"state_creation",token:U}),U},S,{subject:A,install:(J)=>fS(J,T),toJson:T.toJson,fromJson:T.fromJson,internalRoles:f});return o.families.set(T.key,F),mF(o,F,T),new _A(F,o),S}var wA=(o,T)=>{let f=C(T),S=`${o.key}:JSON`;return f.families.get(S)};var jo=(o,T)=>{if(T.family){let S=C(o),A={key:`${T.family.key}:JSON`,type:"selector_family"},$=$o(S,A),F=JSON.parse(T.family.subKey);return i(o,$,F)}return{type:"selector",key:`${T.key}:JSON`}};var bT=(o)=>{let f={type:"atom",key:`*${o.key}`};if(o.family)f.family={key:`*${o.family.key}`,subKey:o.family.subKey};return f};function MF(o){return typeof o==="object"&&o!==null&&"do"in o&&"undo"in o&&"subscribe"in o}function FS(o,T,f){let S=f.valueMap.get(T.key),n=o.valueMap.get(T.key);if(S===n){if(S===void 0)return typeof T.default==="function"?T.default():T.default;f.logger.info("\uD83D\uDCC3","atom",T.key,"copying");let A=T.toJson(S),$=T.fromJson(A);return o.valueMap.set(T.key,$),new $f(T,f),$}return n}function OT(o,T,f,S){let n=o.valueMap.get(T);if(n instanceof TS)n.use(f);if(f instanceof Promise){let A=new TS(f);return o.valueMap.set(T,A),A.then(($)=>{OT(o,T,$,S),S.next({newValue:$,oldValue:A})}).catch(($)=>{o.logger.error("\uD83D\uDCA5","state",T,"rejected:",$)}),A}return o.valueMap.set(T,f),f}var SF=(o,T)=>{let f=T.valueMap.get(o.key);if(o.type==="mutable_atom"&&Mo(T)){let{parent:S}=T;f=FS(T,o,S)}return f},JF=(o,T)=>{let f=T.valueMap.get(o);if(f instanceof TS){let S=f,n=T.selectors.get(o)??T.readonlySelectors.get(o);if(n)S.use(n.get());return}if(T.operation.open)T.operation.prev.set(o,f);T.valueMap.delete(o),T.logger.info("\uD83D\uDDD1","state",o,"evicted")};var OF=(o,T)=>{return C(o).atomsThatAreDefault.has(T)},fn=(o,T)=>{let f=C(o);f.atomsThatAreDefault=new Set(f.atomsThatAreDefault).add(T)},kF=(o,T)=>{let f=C(o);f.atomsThatAreDefault=new Set(C(o).atomsThatAreDefault),f.atomsThatAreDefault.delete(T)};function FT(o,T,f){o.logger.info("\uD83D\uDD28","atom",T.key,`creating in store "${o.config.name}"`);let S=C(o),n=S.atoms.get(T.key);if(n&&n.type==="atom")return o.logger.error("\u274C","atom",T.key,"Tried to create atom, but it already exists in the store."),ST(n);let A=new oo,$={...T,type:"atom",install:(R)=>{return R.logger.info("\uD83D\uDEE0\uFE0F","atom",T.key,`installing in store "${R.config.name}"`),FT(R,T,f)},subject:A};if(f)$.family=f;let F=T.default;if(T.default instanceof Function)F=T.default();S.atoms.set($.key,$),fn(o,T.key),OT(S,T.key,F,A);let J=ST($);if(T.effects){let R=0,M=[];for(let _ of T.effects){let w=_({setSelf:(X)=>{to(o,J,X)},onSet:(X)=>lo(o,J,`effect[${R}]`,X)});if(w)M.push(w);++R}$.cleanup=()=>{for(let _ of M)_()}}return J}function l$(o,T){if("mutable"in T){let n=MS(o,T,void 0);return o.on.atomCreation.next(n),n}let S=FT(o,T,void 0);return o.on.atomCreation.next(S),S}function RA(o,T){let f=C(o),{key:S,family:n}=T,A=$o(f,T);if(!n)o.logger.error("\u274C","atom",S,"Standalone atoms cannot be disposed.");else{A.cleanup?.();let $=o.valueMap.get(A.key),F=$o(o,{key:n.key,type:"atom_family"}),J={type:"state_disposal",subType:"atom",token:T,value:$};F.subject.next(J);let R=Mo(f);if(f.atoms.delete(S),f.valueMap.delete(S),f.selectorAtoms.delete(S),f.atomsThatAreDefault.delete(S),o.timelineTopics.delete(S),T.type==="mutable_atom"){let M=bT(T);RA(o,M),o.trackers.delete(S)}if(o.logger.info("\uD83D\uDD25","atom",S,"deleted"),R&&f.transactionMeta.phase==="building"){let M=f.transactionMeta.update.updates.at(-1);if(!(M?.type==="molecule_disposal"&&M.values.some(([X])=>X===A.family?.key)))f.transactionMeta.update.updates.push(J)}else o.on.atomDisposal.next(T)}}class ho extends Set{mode="record";subject=new oo;cacheLimit=0;cache=[];cacheIdx=-1;cacheUpdateNumber=-1;constructor(o,T=0){super(o);if(o instanceof ho)this.parent=o,this.cacheUpdateNumber=o.cacheUpdateNumber;if(T)this.cacheLimit=T,this.cache=new Array(T),this.subscribe("auto cache",(f)=>{this.cacheIdx++,this.cacheIdx%=this.cacheLimit,this.cache[this.cacheIdx]=f})}toJSON(){return{members:[...this],cache:this.cache,cacheLimit:this.cacheLimit,cacheIdx:this.cacheIdx,cacheUpdateNumber:this.cacheUpdateNumber}}static fromJSON(o){let T=new ho(o.members,o.cacheLimit);return T.cache=o.cache,T.cacheIdx=o.cacheIdx,T.cacheUpdateNumber=o.cacheUpdateNumber,T}add(o){let T=super.add(o);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`add:${fo(o)}`);return T}clear(){let o=this.mode==="record"?[...this]:null;if(super.clear(),o)this.cacheUpdateNumber++,this.emit(`clear:${JSON.stringify(o)}`)}delete(o){let T=super.delete(o);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`del:${fo(o)}`);return T}parent;child=null;transactionUpdates=null;transaction(o){this.mode="transaction",this.transactionUpdates=[],this.child=new ho(this);let T=this.child._subscribe("transaction",(f)=>{this.transactionUpdates?.push(f)});try{if(o(this.child)){for(let S of this.transactionUpdates)this.doStep(S);this.cacheUpdateNumber++,this.emit(`tx:${this.transactionUpdates.join(";")}`)}}catch(f){throw console.warn("Did not apply transaction to SetRTX; this error was thrown:",f),f}finally{T(),this.child=null,this.transactionUpdates=null,this.mode="record"}}_subscribe(o,T){return this.subject.subscribe(o,T)}subscribe(o,T){return this.subject.subscribe(o,(f)=>{T(`${this.cacheUpdateNumber}=${f}`)})}emit(o){this.subject.next(o)}doStep(o){let T=o.indexOf(":"),f=o.substring(0,T),S=o.substring(T+1);switch(f){case"add":this.add(JSON.parse(S));break;case"clear":this.clear();break;case"del":this.delete(JSON.parse(S));break;case"tx":for(let n of S.split(";"))this.doStep(n)}}getUpdateNumber(o){let T=o.indexOf("=");return Number(o.substring(0,T))}do(o){let T=o.indexOf("="),f=Number(o.substring(0,T)),S=f-this.cacheUpdateNumber;if(S>0){if(S===1){this.mode="playback";let A=o.substring(T+1);return this.doStep(A),this.mode="record",this.cacheUpdateNumber=f,null}return this.cacheUpdateNumber+1}if(Math.abs(S)<this.cacheLimit){let A=this.cacheIdx+S;if(this.cache[A]===o)return null;this.mode="playback";let F=!1;while(!F){this.cacheIdx%=this.cacheLimit;let R=this.cache[this.cacheIdx];if(this.cacheIdx--,!R)return"OUT_OF_RANGE";this.undo(R),F=this.cacheIdx===A-1}let J=o.substring(T+1);return this.doStep(J),this.mode="record",this.cacheUpdateNumber=f,null}return"OUT_OF_RANGE"}undoStep(o){let T=o.indexOf(":"),f=o.substring(0,T),S=o.substring(T+1);switch(f){case"add":this.delete(JSON.parse(S));break;case"del":this.add(JSON.parse(S));break;case"clear":{let n=JSON.parse(S);for(let A of n)this.add(A);break}case"tx":{let n=S.split(";");for(let A=n.length-1;A>=0;A--)this.undoStep(n[A])}}}undo(o){let T=o.indexOf("=");if(Number(o.substring(0,T))===this.cacheUpdateNumber){this.mode="playback";let S=o.substring(T+1);return this.undoStep(S),this.mode="record",this.cacheUpdateNumber--,null}return this.cacheUpdateNumber}}class AS{toolkit;options;defaultContent;molecules=new Map;relations;states;core;transact(o,T){let f=this.toolkit;this.toolkit=o,T(this),this.toolkit=f}store;realm;[Symbol.dispose](){}constructor(o,T,f=So.STORE){this.store=f,this.realm=new nA(f),this.options=o,this.defaultContent=T,this.store.miscResources.set(`join:${o.key}`,this),this.realm.allocate("root",o.key),this.toolkit={get:(...Y)=>Ro(f,...Y),set:(...Y)=>{to(f,...Y)},find:(...Y)=>i(f,...Y),json:(Y)=>jo(f,Y)};let S=o.between[0],n=o.between[1],A=fS(f,{key:`${o.key}/relatedKeys`,default:()=>new ho,mutable:!0,fromJson:(Y)=>ho.fromJSON(Y),toJson:(Y)=>Y.toJSON()},["join","relations"]);this.core={relatedKeysAtoms:A};let $=({get:Y},Q)=>Y(A,Q),F=({set:Y},Q,t)=>{if(!this.store.molecules.has(fo(Q)))this.realm.allocate(o.key,Q);Y(A,Q,(D)=>D.add(t)),Y(A,t,(D)=>D.add(Q))},J=({set:Y},Q,t)=>{Y(A,Q,(D)=>{return D.delete(t),D}),Y(A,t,(D)=>{return D.delete(Q),D})},R=(Y,Q,t)=>{let{find:D,get:v,set:l}=Y,G=D(A,Q),s=v(G);for(let r of s){if(t.includes(r))continue;l(A,r,(ko)=>{return ko.delete(Q),ko})}l(G,(r)=>{return r.transaction((a)=>{a.clear();for(let ko of t){let Lo=$(Y,ko),fT=Lo.has(Q);if(this.relations.cardinality==="1:n"){let jT=[];for(let E of Lo){if(E===Q)continue;let Z=$(Y,E);if(Z.delete(ko),Z.size===0)jT.push(E)}if(!fT&&Lo.size>0)Lo.clear();for(let E of jT){let Z=[ko,E].sort(),Fo=`"${Z[0]}:${Z[1]}"`;this.molecules.delete(Fo)}}if(!fT)Lo.add(Q);a.add(ko)}return!0}),r})},M=(Y,Q,t)=>{let{set:D}=Y;D(A,Q,(v)=>{return v.transaction((l)=>{for(let G of t)l.add(G);return!0}),v});for(let v of t)D(A,v,(l)=>{return l.add(Q),l});return!0},_=(Y,Q,t)=>{let D=$(Y,Q);return t?D.has(t):D.size>0},w={getRelatedKeys:(Y)=>$(this.toolkit,Y),addRelation:(Y,Q)=>{this.store.moleculeJoins.set(Y,o.key),this.store.moleculeJoins.set(Q,o.key),F(this.toolkit,Y,Q)},deleteRelation:(Y,Q)=>{J(this.toolkit,Y,Q)},replaceRelationsSafely:(Y,Q)=>{R(this.toolkit,Y,Q)},replaceRelationsUnsafely:(Y,Q)=>{M(this.toolkit,Y,Q)},has:(Y,Q)=>_(this.toolkit,Y,Q)},X,U;if(T){U=NT(f,{key:`${o.key}/content`,default:T},["join","content"]);let Y=({get:D},v)=>D(U,v),Q=({set:D},v,l)=>{D(U,v,l)};X=Object.assign(w,{getContent:(D)=>{return Y(this.toolkit,D)},setContent:(D,v)=>{Q(this.toolkit,D,v)},deleteContent:(D)=>{this.realm.deallocate(D)}})}else X=w;let K=new No(o,{externalStore:X,isAType:o.isAType,isBType:o.isBType,makeContentKey:(...Y)=>{let[Q,t]=Y,D=Y.sort(),v=`${D[0]}:${D[1]}`,l=f.molecules.get(fo(Q)),G=f.molecules.get(fo(t));if(!l)this.realm.allocate(o.key,Q);if(!G)this.realm.allocate(o.key,t);return this.realm.allocate(Q,v,"all"),this.realm.claim(t,v),this.store.moleculeJoins.set(v,o.key),v}}),L=()=>hT(f,{key:`${o.key}/singleRelatedKey`,get:(Y)=>({get:Q})=>{let t=Q(A,Y);for(let D of t)return D;return null}},["join","keys"]),h=()=>{return hT(f,{key:`${o.key}/multipleRelatedKeys`,get:(Y)=>({get:Q})=>{let t=wA(A,f);return Q(t,Y).members}},["join","keys"])},q=()=>hT(f,{key:`${o.key}/singleRelatedEntry`,get:(Y)=>({get:Q})=>{let t=Q(A,Y);for(let D of t){let v=K.isAType?.(Y)?Y:void 0,l=v===void 0?Y:void 0;v??=D,l??=D;let G=K.makeContentKey(v,l),s=Q(U,G);return[D,s]}return null}},["join","entries"]),P=()=>hT(f,{key:`${o.key}/multipleRelatedEntries`,get:(Y)=>({get:Q})=>{let t=wA(A,f);return Q(t,Y).members.map((v)=>{let l=K.isAType?.(Y)?Y:void 0,G=l===void 0?Y:void 0;l??=v,G??=v;let s=K.makeContentKey(l,G),r=Q(U,s);return[v,r]})}},["join","entries"]);switch(o.cardinality){case"1:1":{let Y=L(),Q=`${S}KeyOf${Wo(n)}`,t=`${n}KeyOf${Wo(S)}`,D={[Q]:Y,[t]:Y},v;if(T){let l=q(),G=`${S}EntryOf${Wo(n)}`,s=`${n}EntryOf${Wo(S)}`,r={[G]:l,[s]:l};v=Object.assign(D,r)}else v=D;this.relations=K,this.states=v;break}case"1:n":{let Y=L(),Q=h(),t=`${S}KeyOf${Wo(n)}`,D=`${n}KeysOf${Wo(S)}`,v={[t]:Y,[D]:Q},l;if(T){let G=q(),s=P(),r=`${S}EntryOf${Wo(n)}`,a=`${n}EntriesOf${Wo(S)}`,ko={[r]:G,[a]:s};l=Object.assign(v,ko)}else l=v;this.relations=K,this.states=l;break}default:{let Y=h(),Q=`${S}KeysOf${Wo(n)}`,t=`${n}KeysOf${Wo(S)}`,D={[Q]:Y,[t]:Y},v;if(T){let l=P(),G=`${S}EntriesOf${Wo(n)}`,s=`${n}EntriesOf${Wo(S)}`,r={[G]:l,[s]:l};v=Object.assign(D,r)}else v=D;this.relations=K,this.states=v}}}}function Df(o,T){let f=T.joins.get(o.key);if(f===void 0){let n=So.STORE.joins.get(o.key);if(n===void 0)throw new Error(`Join "${o.key}" not found in store "${T.config.name}"`);f=new AS(n.options,n.defaultContent,T),T.joins.set(o.key,f)}return f}function $S(o,T,f){let S=Df(o,f),n=C(f);if(Mo(n)){let{toolkit:A}=n.transactionMeta;S.transact(A,({relations:$})=>{T($)})}else T(S.relations)}function gS(o,T,f){let S=Df(o,f),n;switch(o.cardinality){case"1:1":{let A=`${o.a}KeyOf${Wo(o.b)}`,$=`${o.b}KeyOf${Wo(o.a)}`;n={get[A](){let J=S.states[A];return i(f,J,T)},get[$](){let J=S.states[$];return i(f,J,T)}};let F=`${o.a}EntryOf${Wo(o.b)}`;if(F in S.states){let J=`${o.b}EntryOf${Wo(o.a)}`;Object.assign(n,{get[F](){let R=S.states[F];return i(f,R,T)},get[J](){let R=S.states[J];return i(f,R,T)}})}break}case"1:n":{let A=`${o.a}KeyOf${Wo(o.b)}`,$=`${o.b}KeysOf${Wo(o.a)}`;n={get[A](){let J=S.states[A];return i(f,J,T)},get[$](){let J=S.states[$];return i(f,J,T)}};let F=`${o.a}EntryOf${Wo(o.b)}`;if(F in S.states){let J=`${o.b}EntriesOf${Wo(o.a)}`;Object.assign(n,{get[F](){let R=S.states[F];return i(f,R,T)},get[J](){let R=S.states[J];return i(f,R,T)}})}break}case"n:n":{let A=`${o.a}KeysOf${Wo(o.b)}`,$=`${o.b}KeysOf${Wo(o.a)}`;n={get[A](){let J=S.states[A];return i(f,J,T)},get[$](){let J=S.states[$];return i(f,J,T)}};let F=`${o.a}EntriesOf${Wo(o.b)}`;if(F in S.states){let J=`${o.b}EntriesOf${Wo(o.a)}`;Object.assign(n,{get[F](){let R=S.states[F];return i(f,R,T)},get[J](){let R=S.states[J];return i(f,R,T)}})}}}return n}function s$(o,T){return Df(o,T).core.relatedKeysAtoms}var yA=(o)=>{let T=FT(o,{key:"\uD83D\uDD0D Atom Token Index (Internal)",default:()=>{let f=new Map;for(let[S,n]of o.atoms)if(!S.includes("\uD83D\uDD0D")){let A=ST(n);if(n.family){let $=f.get(n.family.key);if(!$||!("familyMembers"in $))$={key:n.family.key,familyMembers:new Map},f.set(n.family.key,$);$.familyMembers.set(n.family.subKey,A)}else f.set(S,A)}return f},effects:[({setSelf:f})=>{o.on.atomCreation.subscribe("introspection",(S)=>{if(S.key.includes("\uD83D\uDD0D"))return;f((n)=>{if(S.family){let{key:A,subKey:$}=S.family,F=n.get(A);if(F===void 0||!("familyMembers"in F))F={key:A,familyMembers:new Map},n.set(A,F);F.familyMembers.set($,S)}else n.set(S.key,S);return n})}),o.on.atomDisposal.subscribe("introspection",(S)=>{f((n)=>{if(S.family){let{key:A,subKey:$}=S.family,F=n.get(A);if(F&&"familyMembers"in F){if(F.familyMembers.delete($),F.familyMembers.size===0)n.delete(A)}}else n.delete(S.key);return n})})}]},void 0);return mT(o,{key:"\uD83D\uDD0D Atom Token Index",get:({get:f})=>f(T)})};var XA=(o)=>{let T=FT(o,{key:"\uD83D\uDD0D Selector Token Index (Internal)",default:()=>{let f=new Map;for(let S of[o.readonlySelectors,o.selectors])for(let[n,A]of S)if(!n.includes("\uD83D\uDD0D")){let $=ST(A);if(A.family){let F=f.get(A.family.key);if(!F||!("familyMembers"in F))F={key:A.family.key,familyMembers:new Map},f.set(A.family.key,F);F.familyMembers.set(A.family.subKey,$)}else f.set(n,$)}return f},effects:[({setSelf:f})=>{o.on.selectorCreation.subscribe("introspection",(S)=>{if(S.key.includes("\uD83D\uDD0D"))return;f((n)=>{if(S.family){let{key:A,subKey:$}=S.family,F=n.get(A);if(F===void 0||!("familyMembers"in F))F={key:A,familyMembers:new Map},n.set(A,F);F.familyMembers.set($,S)}else n.set(S.key,S);return n})}),o.on.selectorDisposal.subscribe("introspection",(S)=>{f((n)=>{if(S.family){let{key:A,subKey:$}=S.family,F=n.get(A);if(F&&"familyMembers"in F){if(F.familyMembers.delete($),F.familyMembers.size===0)n.delete(A)}}else n.delete(S.key);return n})})}]},void 0);return mT(o,{key:"\uD83D\uDD0D Selector Token Index",get:({get:f})=>f(T)})};class Sn{supported;constructor(o){this.supported=o}refine(o){for(let[T,f]of Object.entries(this.supported))try{if(f(o)===!0&&f!==Boolean)return{type:T,data:o}}catch(S){try{if(o instanceof f)return{type:T,data:o}}catch(n){}}return null}}var HA=new Sn({number:(o)=>typeof o==="number",string:(o)=>typeof o==="string",boolean:(o)=>typeof o==="boolean",null:(o)=>o===null});function KA(o){if(!o)return!1;return Object.getPrototypeOf(o)===Object.prototype}var GA=new Sn({object:KA,array:(o)=>Array.isArray(o)}),mM=new Sn({...HA.supported,...GA.supported}),Uf=(o)=>{if(o===void 0)return"undefined";let T=mM.refine(o);if(T)return T.type;return Object.getPrototypeOf(o).constructor.name};class hF{store;auditorCreatedAt=performance.now();statesCreatedAt=new Map;atomIndex;selectorIndex;disposed=!1;unsubscribeFromAtomCreation;unsubscribeFromAtomDisposal;unsubscribeFromSelectorCreation;unsubscribeFromSelectorDisposal;constructor(o=So.STORE){this.store=o;this.atomIndex=yA(this.store),this.selectorIndex=XA(this.store),this.unsubscribeFromAtomCreation=this.store.on.atomCreation.subscribe(`auditor-${this.auditorCreatedAt}`,({key:T})=>{this.statesCreatedAt.set(T,performance.now()-this.auditorCreatedAt)}),this.unsubscribeFromAtomDisposal=this.store.on.atomDisposal.subscribe(`auditor-${this.auditorCreatedAt}`,({key:T})=>{this.statesCreatedAt.delete(T)}),this.unsubscribeFromSelectorCreation=this.store.on.selectorCreation.subscribe(`auditor-${this.auditorCreatedAt}`,({key:T})=>{this.statesCreatedAt.set(T,performance.now()-this.auditorCreatedAt)}),this.unsubscribeFromSelectorDisposal=this.store.on.selectorDisposal.subscribe(`auditor-${this.auditorCreatedAt}`,({key:T})=>{this.statesCreatedAt.delete(T)})}static DEFAULT_LIST_RESOURCES_PARAM={atomFamilies:!0,selectorFamilies:!0};listResources(o=hF.DEFAULT_LIST_RESOURCES_PARAM){if(this.disposed)throw new Error("This Auditor has been disposed");let T=TA(this.atomIndex),f=TA(this.selectorIndex),S=[...T.values()].filter((F)=>("familyMembers"in F)),n=[...f.values()].filter((F)=>("familyMembers"in F)),A=performance.now(),$=[];if(o.atomFamilies)for(let F of S){let J=F.familyMembers.values();for(let R of J){let _=this.statesCreatedAt.get(R.key)??this.auditorCreatedAt,w=A-_;$.push([R,w])}}if(o.selectorFamilies)for(let F of n){let J=F.familyMembers.values();for(let R of J){let _=this.statesCreatedAt.get(R.key)??this.auditorCreatedAt,w=A-_;$.push([R,w])}}return $}[Symbol.dispose](){this.unsubscribeFromAtomCreation(),this.unsubscribeFromAtomDisposal(),this.unsubscribeFromSelectorCreation(),this.unsubscribeFromSelectorDisposal(),this.disposed=!0}}var YA=(o,T)=>{let f=(S,n)=>{let $=((J,R)=>{let M=T(J,R);if(M)return M;return null})(S,n);if($?.jobComplete??$?.pathComplete)return $;let F=Array.isArray(n)?n.map((J,R)=>[R,J]):KA(n)?Object.entries(n):[];for(let[J,R]of F){let M=f([...S,J],R);if(M?.jobComplete)return M}return{}};f([],o)};function NM(o,T){return{summary:`${o<T?"+":"-"}${Math.abs(o-T)} (${o} \u2192 ${T})`}}function hM(o,T){return{summary:`${o.length<T.length?"+":"-"}${Math.abs(o.length-T.length)} ("${o}" \u2192 "${T}")`}}function bM(o,T){return{summary:`${o} \u2192 ${T}`}}function bF(o,T,f){let S="",n=[],A=[],$=[];return YA(o,(F,J)=>{let R;for(R of F){let M=T[R];if(M===void 0)A.push([R,JSON.stringify(J)]);else{let _=f(J,M);if(_.summary!=="No Change")$.push([R,_])}}}),YA(T,(F,J)=>{let R;for(R of F)if(o[R]===void 0)n.push([R,JSON.stringify(J)])}),S=`\uFF5E${$.length} \uFF0B${n.length} \uFF0D${A.length}`,{summary:S,added:n,removed:A,changed:$}}function xM(o,T,f){return bF(o,T,f)}class xF{leafRefinery;treeRefinery;leafDiffers;treeDiffers;constructor(o,T,f){this.leafRefinery=o,this.treeRefinery=T,this.leafDiffers={},this.treeDiffers={};for(let S of Object.keys(o.supported)){let n=f[S];this.leafDiffers[S]=n}for(let S of Object.keys(T.supported)){let n=f[S];this.treeDiffers[S]=n}}diff(o,T){if(o===T)return{summary:"No Change"};let f=this.leafRefinery.refine(o)??this.treeRefinery.refine(o),S=this.leafRefinery.refine(T)??this.treeRefinery.refine(T);if(f!==null&&S!==null){if(f.type===S.type){if(f.type in this.leafDiffers)return this.leafDiffers[f.type](f.data,S.data);if(f.type in this.treeDiffers)return this.treeDiffers[f.type](f.data,S.data,(F,J)=>this.diff(F,J))}}let n=Uf(o),A=Uf(T);if(n===A)return{summary:`${n} \u2192 ${A}`};return{summary:`Type change: ${n} \u2192 ${A}`}}}var oK=new xF(HA,GA,{number:NM,string:hM,boolean:bM,null:()=>({summary:"No Change"}),object:bF,array:xM});class vF extends Map{set(o,T){if(this.has(o))return console.warn("Tried to set a key that already exists in an InvariantMap",{key:o,value:T}),this;return super.set(o,T)}clear(){throw new Error("Cannot clear an InvariantMap")}}class nn{key;type="continuity";globals=[];actions=[];perspectives=[];constructor(o){this.key=o}static existing=new vF;static create(o,T){let f=new nn(o),{type:S,globals:n,actions:A,perspectives:$}=T(f),F={type:S,key:o,globals:n,actions:A,perspectives:$};return nn.existing.set(o,F),F}add(...o){switch(o[0].type){case"atom":case"mutable_atom":this.globals.push(...o);break;case"transaction":this.actions.push(...o);break;case"atom_family":{let[f,S]=o;this.perspectives.push({type:"realtime_perspective",resourceAtoms:f,viewAtoms:S})}break}return this}}function RK(o){let{key:T,config:f}=o,S=nn.create(T,f),{actions:n}=S;for(let A of n)zF(So.STORE,T,A.key);return GF(So.STORE,T,-1),S}var kK=Yf({key:"usersInRoomIndex",mutable:!0,default:()=>new ho,toJson:(o)=>o.toJSON(),fromJson:(o)=>ho.fromJSON(o)}),EA=Yf({key:"roomIndex",default:()=>new ho,mutable:!0,toJson:(o)=>o.toJSON(),fromJson:(o)=>ho.fromJSON(o)}),vM={enteredAtEpoch:0},WS=iS({key:"usersInRooms",between:["room","user"],cardinality:"1:n",isAType:(o)=>typeof o==="string",isBType:(o)=>typeof o==="string"},vM),_K=dS({key:"usersInMyRoomView",get:(o)=>({find:T})=>{let f=e$(WS);return[T(f,o)]}});import{spawn as qM}from"child_process";class tf{emit;listeners;globalListeners;handleEvent(o,...T){for(let S of this.globalListeners)S(o,...T);let f=this.listeners.get(o);if(f)for(let S of f)S(...T)}id="no_id_retrieved";constructor(o){this.emit=o;this.listeners=new Map,this.globalListeners=new Set}on(o,T){let f=this.listeners.get(o);if(f)f.add(T);else this.listeners.set(o,new Set([T]));return this}onAny(o){return this.globalListeners.add(o),this}off(o,T){let f=this.listeners.get(o);if(f)if(T)f.delete(T);else this.listeners.delete(o);return this}offAny(o){return this.globalListeners.delete(o),this}}class zA extends tf{incompleteData="";unprocessedEvents=[];incompleteLog="";unprocessedLogs=[];id="#####";process;key;logger;handleLog(o){if(Array.isArray(o)){let[T,...f]=o;switch(T){case"i":this.logger.info(...f);break;case"w":this.logger.warn(...f);break;case"e":this.logger.error(...f);break}}}constructor(o,T,f){super((S,...n)=>{let A=JSON.stringify([S,...n])+"\x03",$=(F)=>{if(F.code==="EPIPE")console.error("EPIPE error during write",this.process.stdin);this.process.stdin.removeListener("error",$)};return this.process.stdin.once("error",$),this.process.stdin.write(A),this});if(this.process=o,this.key=T,this.logger=f??{info:(...S)=>{console.info(this.id,this.key,...S)},warn:(...S)=>{console.warn(this.id,this.key,...S)},error:(...S)=>{console.error(this.id,this.key,...S)}},this.process.stdout.on("data",(S)=>{let n=S.toString();if(n==="ALIVE")return;this.unprocessedEvents.push(...n.split("\x03"));let A=this.unprocessedEvents.shift();this.incompleteData+=A??"";try{if(this.incompleteData.startsWith("error"))console.log("\u2757",this.incompleteData);let $=vo(this.incompleteData);this.handleEvent(...$);while(this.unprocessedEvents.length>0){let F=this.unprocessedEvents.shift();if(F){if(this.unprocessedEvents.length===0)this.incompleteData=F;$=vo(F),this.handleEvent(...$)}}this.incompleteData=""}catch($){console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.warn(this.incompleteData),console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.error($)}}),this.process.stderr.on("data",(S)=>{let n=S.toString();this.unprocessedLogs.push(...n.split("\x03"));let A=this.unprocessedLogs.shift();this.incompleteLog+=A??"";try{let $=vo(this.incompleteLog);this.handleLog($);while(this.unprocessedLogs.length>0)if(this.incompleteLog=this.unprocessedLogs.shift()??"",this.incompleteLog)$=vo(this.incompleteLog),this.handleLog($)}catch($){console.error("\u274C\u274C\u274C"),console.error(this.incompleteLog),console.error($),console.error("\u274C\u274C\u274C\uFE0F")}}),o.pid)this.id=o.pid.toString()}}class qF extends tf{in;out;id="no_id_retrieved";disposalFunctions=[];constructor(o){super((...T)=>{return this.out.next(T),this});this.id=o,this.in=new oo,this.out=new oo,this.in.subscribe("socket",(T)=>{this.handleEvent(...T)})}dispose(){for(let o of this.disposalFunctions)o()}}class QA extends tf{incompleteData="";unprocessedEvents=[];relays;relayServices;process;id="#####";log(...o){this.process.stderr.write(fo(o.map((T)=>T instanceof ho?`{ ${T.toJSON().members.join(" | ")} }`:T))+"\x03")}logger={info:(...o)=>{this.log("i",...o)},warn:(...o)=>{this.log("w",...o)},error:(...o)=>{this.log("e",...o)}};constructor(){super((o,...T)=>{let f=JSON.stringify([o,...T]);return this.process.stdout.write(f+"\x03"),this});if(this.process=process,this.process.stdin.resume(),this.relays=new Map,this.relayServices=[],this.process.stdin.on("data",(o)=>{let T=o.toString();this.unprocessedEvents.push(...T.split("\x03"));let f=this.unprocessedEvents.shift();this.incompleteData+=f??"";try{let S=vo(this.incompleteData);this.logger.info("\uD83C\uDFB0","received",S),this.handleEvent(...S);while(this.unprocessedEvents.length>0){let n=this.unprocessedEvents.shift();if(n){if(this.unprocessedEvents.length===0)this.incompleteData=n;let A=vo(n);this.handleEvent(...A)}}this.incompleteData=""}catch(S){if(S instanceof Error)this.logger.error("\u2757",S.message,S.cause,S.stack)}}),this.on("exit",()=>{this.logger.info("\uD83D\uDD25",this.id,'received "exit"'),process.exit(0)}),process.on("exit",(o)=>{this.logger.info("\uD83D\uDD25",this.id,`exited with code ${o}`)}),process.on("end",()=>{this.logger.info("\uD83D\uDD25",this.id,"ended"),process.exit(0)}),process.on("SIGTERM",()=>{this.logger.error("\uD83D\uDD25",this.id,"terminated"),process.exit(0)}),process.on("SIGINT",()=>{this.logger.error("\uD83D\uDD25",this.id,"interrupted"),process.exit(0)}),process.pid)this.id=process.pid?.toString();this.on("user-joins",(o)=>{this.logger.info("\uD83D\uDC64","user",o,"joined");let T=new qF(`user:${o}`);this.relays.set(o,T),this.logger.info("\uD83D\uDD17","attaching services:",`[${[...this.relayServices.keys()].join(", ")}]`);for(let f of this.relayServices){let S=f(T);if(S)T.disposalFunctions.push(S)}this.on(`user:${o}`,(...f)=>{T.in.next(f)}),T.out.subscribe("socket",(f)=>{this.emit(...f)})}),this.on("user-leaves",(o)=>{let T=this.relays.get(o);if(this.off(`relay:${o}`),T)T.dispose(),this.relays.delete(o)}),process.stdout.write("ALIVE")}relay(o){this.logger.info("\uD83D\uDD17","running relay method"),this.relayServices.push(o)}}var DA=Tf({key:"roomArguments",default:["echo",["Hello World!"]]}),rF=dS({key:"room",get:(o)=>async({get:T,find:f})=>{let S=f(DA,o),n=T(S),[A,$]=n,F=await new Promise((J)=>{let R=qM(A,$,{env:process.env}),M=(_)=>{if(_.toString()==="ALIVE")R.stdout.off("data",M),J(R)};R.stdout.on("data",M)});return new zA(F,o)}});var rK=JS({key:"createRoom",do:({get:o,set:T,find:f},S,n,A)=>{let $=A?[n,A]:[n],F=f(DA,S);T(F,$),T(EA,(M)=>M.add(S));let J=f(rF,S);return o(J)}}),ZK=JS({key:"joinRoom",do:(o,T,f,S)=>{let n={enteredAtEpoch:S};return $S(WS,(A)=>{A.set({room:T,user:f},n)},o.env().store),n}}),pK=JS({key:"leaveRoom",do:(o,T,f)=>{$S(WS,(S)=>{S.delete({room:T,user:f})},o.env().store)}}),cK=JS({key:"destroyRoom",do:(o,T)=>{$S(WS,(f)=>{f.delete({room:T})},o.env().store),o.set(EA,(f)=>(f.delete(T),f))}});function UA(o,T){return T.map((f)=>{switch(f.type){case"transaction_update":{let S=UA(o,f.updates);return{...f,updates:S}}default:return f}}).filter((f)=>{switch(f.type){case"atom_update":case"selector_update":return o.includes(f.key);case"state_creation":return o.includes(f.token.key);case"molecule_creation":return!0;case"transaction_update":return!0}})}var gK=Tf({key:"redactor",default:{occlude:(o)=>o}}),Vf=Tf({key:"unacknowledgedUpdates",default:()=>[]});var ZF=Tf({key:"sockets",default:null}),eK=Yf({key:"socketsIndex",mutable:!0,default:()=>new ho,toJson:(o)=>o.toJSON(),fromJson:(o)=>ho.fromJSON(o)}),sK=Yf({key:"usersIndex",mutable:!0,default:()=>new ho,toJson:(o)=>o.toJSON(),fromJson:(o)=>ho.fromJSON(o)}),tA=iS({key:"usersOfSockets",between:["user","socket"],cardinality:"1:1",isAType:(o)=>o.startsWith("user::"),isBType:(o)=>o.startsWith("socket::")});function pF(o,T,f,S){let n=T.key;return function A(){let $=[];for(let J of T.globals){let R=J.type==="mutable_atom"?jo(o,J):J,M=Ro(o,R);$.push(R,M)}for(let J of T.perspectives){let{viewAtoms:R,resourceAtoms:M}=J,_=i(o,R,f),w=Ro(o,_);o.logger.info("\uD83D\uDC41","atom",M.key,`${f} can see`,{viewAtoms:R,resourceAtoms:M,userView:w});for(let X of w){let U=X.type==="mutable_atom"?jo(o,X):X,K=Ro(o,U);$.push(U,K)}}let F=mo(o)?o.transactionMeta.epoch.get(n)??null:null;S?.emit(`continuity-init:${n}`,F,$)}}function cF(o,T,f){let S=T.key;return function n(A){o.logger.info("\uD83D\uDECE\uFE0F","continuity",S,"received",A);let{key:$,id:F}=A,J=`tx-run:${$}:${F}`,R=`${J}:start`,M=`${J}:end`;performance.mark(R);try{zf(o,{type:"transaction",key:$},F)(...A.params)}catch(w){if(w instanceof Error)o.logger.error("\u274C","continuity",S,`failed to run transaction ${$} from ${f} with update ${F}`,w.message)}performance.mark(M);let _=performance.measure(J,R,M);o?.logger.info("\uD83D\uDE80","transaction",$,F,f,_.duration)}}function PF(o,T,f,S){let n=T.key;return function A($){if(o.logger.info("\uD83D\uDC4D","continuity",n,`${f} acknowledged epoch ${$}`),S[0]?.epoch===$)to(o,Vf,f,(J)=>{return J.shift(),o.logger.info("\uD83D\uDC4D","continuity",n,`${f} unacknowledged update queue now has`,J.length,"items"),J})}}function iF(o,T,f,S){let n=T.key,A=[];for(let $ of T.actions){let F=OA(o,$,`sync-continuity:${n}:${f}`,(J)=>{try{let R=T.globals.map((w)=>{if(w.type==="atom")return w.key;return bT(w).key}).concat(T.perspectives.flatMap((w)=>{let{viewAtoms:X}=w,U=i(o,X,f);return Ro(o,U).map((L)=>{return L.type==="mutable_atom"?"*"+L.key:L.key})})),M=UA(R,J.updates),_={...J,updates:M};to(o,Vf,f,(w)=>{if(_)w.push(_),w.sort((X,U)=>X.epoch-U.epoch),o.logger.info("\uD83D\uDC4D","continuity",n,`${f} unacknowledged update queue now has`,w.length,"items");return w}),S?.emit(`tx-new:${n}`,_)}catch(R){if(R instanceof Error)o.logger.error("\u274C","continuity",n,`${f} failed to send update from transaction ${$.key} to ${f}`,R.message)}});A.push(F)}return A}function gF(o,T,f,S){let n=T.key,A=[];for(let $ of T.perspectives){let{viewAtoms:F}=$,J=i(o,F,f),R=lo(o,J,`sync-continuity:${n}:${f}:perspective:${$.resourceAtoms.key}`,({oldValue:M,newValue:_})=>{let w=M.map((L)=>L.key),X=_.map((L)=>L.key),U=M.filter((L)=>!X.includes(L.key)),K=_.filter((L)=>!w.includes(L.key)).flatMap((L)=>{let h=L.type==="mutable_atom"?jo(o,L):L,q=Ro(o,h);return[h,q]});if(o.logger.info("\uD83D\uDC41","atom",$.resourceAtoms.key,`${f} has a new perspective`,{oldKeys:w,newKeys:X,revealed:K,concealed:U}),K.length>0)S?.emit(`reveal:${n}`,K);if(U.length>0)S?.emit(`conceal:${n}`,U)});A.push(R)}return A}function t5({socket:o,store:T=So.STORE}){return function f(S){let n=o,A=S.key,$=gS(tA,`socket::${n.id}`,T).userKeyOfSocket,F=Ro(T,$);if(!F)return T.logger.error("\u274C","continuity",A,`Tried to create a synchronizer for a socket (${n.id}) that is not connected to a user.`),()=>{};let J=gS(tA,F,T).socketKeyOfUser,R=lo(T,J,`sync-continuity:${A}:${F}`,({newValue:h})=>{if(T.logger.info("\uD83D\uDC4B","continuity",A,`seeing ${F} on new socket ${h}`),h===null){T.logger.warn("\u274C","continuity",A,`User (${F}) is not connected to a socket, waiting for them to reappear.`);return}let q=i(T,ZF,h);n=Ro(T,q);for(let Y of M)n?.emit(`tx-new:${A}`,Y)}),M=Ro(T,Vf,F),_=[],w=gF(T,S,F,n),X=iF(T,S,F,n);_.push(...w,...X);let U=pF(T,S,F,o);n.off(`get:${A}`,U),n.on(`get:${A}`,U);let K=cF(T,S,F);n.off(`tx-run:${A}`,K),n.on(`tx-run:${A}`,K);let L=PF(T,S,F,M);return n?.on(`ack:${A}`,L),()=>{for(let h of _)h();n?.off(`ack:${A}`,L),n?.off(`get:${A}`,U),n?.off(`tx-run:${A}`,K)}}}var{file:L1,serve:Sk}=globalThis.Bun;import{readFileSync as JJ}from"fs";import{resolve as jA}from"path";function rM(o,T){let f={},S=[];for(let n in o){let A=o[n],$=T[n],F=A["~standard"].validate($);if(F instanceof Promise)throw new Error(`Validation must be synchronous, but ${n} returned a Promise.`);if(F.issues){S.push(...F.issues.map((J)=>({...J,path:[n,...J.path??[]]})));continue}f[n]=F.value}if(S.length)return{issues:S};return{value:f}}function dF(o){let T=o.runtimeEnvStrict??o.runtimeEnv??process.env;if(o.emptyStringAsUndefined??!1){for(let[q,P]of Object.entries(T))if(P==="")delete T[q]}if(!!o.skipValidation)return T;let n=typeof o.client==="object"?o.client:{},A=typeof o.server==="object"?o.server:{},$=typeof o.shared==="object"?o.shared:{},F=o.isServer??(typeof window==="undefined"||("Deno"in window)),J=F?{...A,...$,...n}:{...n,...$},R=rM(J,T),M=o.onValidationError??((q)=>{throw console.error("\u274C Invalid environment variables:",q),new Error("Invalid environment variables")}),_=o.onInvalidAccess??(()=>{throw new Error("\u274C Attempted to access a server-side environment variable on the client")});if(R.issues)return M(R.issues);let w=(q)=>{if(!o.clientPrefix)return!0;return!q.startsWith(o.clientPrefix)&&!(q in $)},X=(q)=>{return F||!w(q)},U=(q)=>{return q==="__esModule"||q==="$$typeof"},K=(o.extends??[]).reduce((q,P)=>{return Object.assign(q,P)},{}),L=Object.assign(R.value,K);return new Proxy(L,{get(q,P){if(typeof P!=="string")return;if(U(P))return;if(!X(P))return _(P);return Reflect.get(q,P)}})}var Ao;(function(o){o.assertEqual=(n)=>n;function T(n){}o.assertIs=T;function f(n){throw new Error}o.assertNever=f,o.arrayToEnum=(n)=>{let A={};for(let $ of n)A[$]=$;return A},o.getValidEnumValues=(n)=>{let A=o.objectKeys(n).filter((F)=>typeof n[n[F]]!=="number"),$={};for(let F of A)$[F]=n[F];return o.objectValues($)},o.objectValues=(n)=>{return o.objectKeys(n).map(function(A){return n[A]})},o.objectKeys=typeof Object.keys==="function"?(n)=>Object.keys(n):(n)=>{let A=[];for(let $ in n)if(Object.prototype.hasOwnProperty.call(n,$))A.push($);return A},o.find=(n,A)=>{for(let $ of n)if(A($))return $;return},o.isInteger=typeof Number.isInteger==="function"?(n)=>Number.isInteger(n):(n)=>typeof n==="number"&&isFinite(n)&&Math.floor(n)===n;function S(n,A=" | "){return n.map(($)=>typeof $==="string"?`'${$}'`:$).join(A)}o.joinValues=S,o.jsonStringifyReplacer=(n,A)=>{if(typeof A==="bigint")return A.toString();return A}})(Ao||(Ao={}));var BA;(function(o){o.mergeShapes=(T,f)=>{return{...T,...f}}})(BA||(BA={}));var N=Ao.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),vT=(o)=>{switch(typeof o){case"undefined":return N.undefined;case"string":return N.string;case"number":return isNaN(o)?N.nan:N.number;case"boolean":return N.boolean;case"function":return N.function;case"bigint":return N.bigint;case"symbol":return N.symbol;case"object":if(Array.isArray(o))return N.array;if(o===null)return N.null;if(o.then&&typeof o.then==="function"&&o.catch&&typeof o.catch==="function")return N.promise;if(typeof Map!=="undefined"&&o instanceof Map)return N.map;if(typeof Set!=="undefined"&&o instanceof Set)return N.set;if(typeof Date!=="undefined"&&o instanceof Date)return N.date;return N.object;default:return N.unknown}},z=Ao.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"]),ZM=(o)=>{return JSON.stringify(o,null,2).replace(/"([^"]+)":/g,"$1:")};class JT extends Error{get errors(){return this.issues}constructor(o){super();this.issues=[],this.addIssue=(f)=>{this.issues=[...this.issues,f]},this.addIssues=(f=[])=>{this.issues=[...this.issues,...f]};let T=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,T);else this.__proto__=T;this.name="ZodError",this.issues=o}format(o){let T=o||function(n){return n.message},f={_errors:[]},S=(n)=>{for(let A of n.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)f._errors.push(T(A));else{let $=f,F=0;while(F<A.path.length){let J=A.path[F];if(F!==A.path.length-1)$[J]=$[J]||{_errors:[]};else $[J]=$[J]||{_errors:[]},$[J]._errors.push(T(A));$=$[J],F++}}};return S(this),f}static assert(o){if(!(o instanceof JT))throw new Error(`Not a ZodError: ${o}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Ao.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(o=(T)=>T.message){let T={},f=[];for(let S of this.issues)if(S.path.length>0)T[S.path[0]]=T[S.path[0]]||[],T[S.path[0]].push(o(S));else f.push(o(S));return{formErrors:f,fieldErrors:T}}get formErrors(){return this.flatten()}}JT.create=(o)=>{return new JT(o)};var If=(o,T)=>{let f;switch(o.code){case z.invalid_type:if(o.received===N.undefined)f="Required";else f=`Expected ${o.expected}, received ${o.received}`;break;case z.invalid_literal:f=`Invalid literal value, expected ${JSON.stringify(o.expected,Ao.jsonStringifyReplacer)}`;break;case z.unrecognized_keys:f=`Unrecognized key(s) in object: ${Ao.joinValues(o.keys,", ")}`;break;case z.invalid_union:f="Invalid input";break;case z.invalid_union_discriminator:f=`Invalid discriminator value. Expected ${Ao.joinValues(o.options)}`;break;case z.invalid_enum_value:f=`Invalid enum value. Expected ${Ao.joinValues(o.options)}, received '${o.received}'`;break;case z.invalid_arguments:f="Invalid function arguments";break;case z.invalid_return_type:f="Invalid function return type";break;case z.invalid_date:f="Invalid date";break;case z.invalid_string:if(typeof o.validation==="object")if("includes"in o.validation){if(f=`Invalid input: must include "${o.validation.includes}"`,typeof o.validation.position==="number")f=`${f} at one or more positions greater than or equal to ${o.validation.position}`}else if("startsWith"in o.validation)f=`Invalid input: must start with "${o.validation.startsWith}"`;else if("endsWith"in o.validation)f=`Invalid input: must end with "${o.validation.endsWith}"`;else Ao.assertNever(o.validation);else if(o.validation!=="regex")f=`Invalid ${o.validation}`;else f="Invalid";break;case z.too_small:if(o.type==="array")f=`Array must contain ${o.exact?"exactly":o.inclusive?"at least":"more than"} ${o.minimum} element(s)`;else if(o.type==="string")f=`String must contain ${o.exact?"exactly":o.inclusive?"at least":"over"} ${o.minimum} character(s)`;else if(o.type==="number")f=`Number must be ${o.exact?"exactly equal to ":o.inclusive?"greater than or equal to ":"greater than "}${o.minimum}`;else if(o.type==="date")f=`Date must be ${o.exact?"exactly equal to ":o.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(o.minimum))}`;else f="Invalid input";break;case z.too_big:if(o.type==="array")f=`Array must contain ${o.exact?"exactly":o.inclusive?"at most":"less than"} ${o.maximum} element(s)`;else if(o.type==="string")f=`String must contain ${o.exact?"exactly":o.inclusive?"at most":"under"} ${o.maximum} character(s)`;else if(o.type==="number")f=`Number must be ${o.exact?"exactly":o.inclusive?"less than or equal to":"less than"} ${o.maximum}`;else if(o.type==="bigint")f=`BigInt must be ${o.exact?"exactly":o.inclusive?"less than or equal to":"less than"} ${o.maximum}`;else if(o.type==="date")f=`Date must be ${o.exact?"exactly":o.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(o.maximum))}`;else f="Invalid input";break;case z.custom:f="Invalid input";break;case z.invalid_intersection_types:f="Intersection results could not be merged";break;case z.not_multiple_of:f=`Number must be a multiple of ${o.multipleOf}`;break;case z.not_finite:f="Number must be finite";break;default:f=T.defaultError,Ao.assertNever(o)}return{message:f}},sF=If;function pM(o){sF=o}function An(){return sF}var $n=(o)=>{let{data:T,path:f,errorMaps:S,issueData:n}=o,A=[...f,...n.path||[]],$={...n,path:A};if(n.message!==void 0)return{...n,path:A,message:n.message};let F="",J=S.filter((R)=>!!R).slice().reverse();for(let R of J)F=R($,{data:T,defaultError:F}).message;return{...n,path:A,message:F}},cM=[];function I(o,T){let f=An(),S=$n({issueData:T,data:o.data,path:o.path,errorMaps:[o.common.contextualErrorMap,o.schemaErrorMap,f,f===If?void 0:If].filter((n)=>!!n)});o.common.issues.push(S)}class uo{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(o,T){let f=[];for(let S of T){if(S.status==="aborted")return d;if(S.status==="dirty")o.dirty();f.push(S.value)}return{status:o.value,value:f}}static async mergeObjectAsync(o,T){let f=[];for(let S of T){let n=await S.key,A=await S.value;f.push({key:n,value:A})}return uo.mergeObjectSync(o,f)}static mergeObjectSync(o,T){let f={};for(let S of T){let{key:n,value:A}=S;if(n.status==="aborted")return d;if(A.status==="aborted")return d;if(n.status==="dirty")o.dirty();if(A.status==="dirty")o.dirty();if(n.value!=="__proto__"&&(typeof A.value!=="undefined"||S.alwaysSet))f[n.value]=A.value}return{status:o.value,value:f}}}var d=Object.freeze({status:"aborted"}),Lf=(o)=>({status:"dirty",value:o}),ao=(o)=>({status:"valid",value:o}),LA=(o)=>o.status==="aborted",CA=(o)=>o.status==="dirty",Ff=(o)=>o.status==="valid",_S=(o)=>typeof Promise!=="undefined"&&o instanceof Promise;function Fn(o,T,f,S){if(f==="a"&&!S)throw new TypeError("Private accessor was defined without a getter");if(typeof T==="function"?o!==T||!S:!T.has(o))throw new TypeError("Cannot read private member from an object whose class did not declare it");return f==="m"?S:f==="a"?S.call(o):S?S.value:T.get(o)}function aF(o,T,f,S,n){if(S==="m")throw new TypeError("Private method is not writable");if(S==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof T==="function"?o!==T||!n:!T.has(o))throw new TypeError("Cannot write private member to an object whose class did not declare it");return S==="a"?n.call(o,f):n?n.value=f:T.set(o,f),f}var x;(function(o){o.errToObj=(T)=>typeof T==="string"?{message:T}:T||{},o.toString=(T)=>typeof T==="string"?T:T===null||T===void 0?void 0:T.message})(x||(x={}));var OS,kS;class ET{constructor(o,T,f,S){this._cachedPath=[],this.parent=o,this.data=T,this._path=f,this._key=S}get path(){if(!this._cachedPath.length)if(this._key instanceof Array)this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var lF=(o,T)=>{if(Ff(T))return{success:!0,data:T.value};else{if(!o.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let f=new JT(o.common.issues);return this._error=f,this._error}}}};function u(o){if(!o)return{};let{errorMap:T,invalid_type_error:f,required_error:S,description:n}=o;if(T&&(f||S))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(T)return{errorMap:T,description:n};return{errorMap:($,F)=>{var J,R;let{message:M}=o;if($.code==="invalid_enum_value")return{message:M!==null&&M!==void 0?M:F.defaultError};if(typeof F.data==="undefined")return{message:(J=M!==null&&M!==void 0?M:S)!==null&&J!==void 0?J:F.defaultError};if($.code!=="invalid_type")return{message:F.defaultError};return{message:(R=M!==null&&M!==void 0?M:f)!==null&&R!==void 0?R:F.defaultError}},description:n}}class e{get description(){return this._def.description}_getType(o){return vT(o.data)}_getOrReturnCtx(o,T){return T||{common:o.parent.common,data:o.data,parsedType:vT(o.data),schemaErrorMap:this._def.errorMap,path:o.path,parent:o.parent}}_processInputParams(o){return{status:new uo,ctx:{common:o.parent.common,data:o.data,parsedType:vT(o.data),schemaErrorMap:this._def.errorMap,path:o.path,parent:o.parent}}}_parseSync(o){let T=this._parse(o);if(_S(T))throw new Error("Synchronous parse encountered promise.");return T}_parseAsync(o){let T=this._parse(o);return Promise.resolve(T)}parse(o,T){let f=this.safeParse(o,T);if(f.success)return f.data;throw f.error}safeParse(o,T){var f;let S={common:{issues:[],async:(f=T===null||T===void 0?void 0:T.async)!==null&&f!==void 0?f:!1,contextualErrorMap:T===null||T===void 0?void 0:T.errorMap},path:(T===null||T===void 0?void 0:T.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:o,parsedType:vT(o)},n=this._parseSync({data:o,path:S.path,parent:S});return lF(S,n)}"~validate"(o){var T,f;let S={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:o,parsedType:vT(o)};if(!this["~standard"].async)try{let n=this._parseSync({data:o,path:[],parent:S});return Ff(n)?{value:n.value}:{issues:S.common.issues}}catch(n){if((f=(T=n===null||n===void 0?void 0:n.message)===null||T===void 0?void 0:T.toLowerCase())===null||f===void 0?void 0:f.includes("encountered"))this["~standard"].async=!0;S.common={issues:[],async:!0}}return this._parseAsync({data:o,path:[],parent:S}).then((n)=>Ff(n)?{value:n.value}:{issues:S.common.issues})}async parseAsync(o,T){let f=await this.safeParseAsync(o,T);if(f.success)return f.data;throw f.error}async safeParseAsync(o,T){let f={common:{issues:[],contextualErrorMap:T===null||T===void 0?void 0:T.errorMap,async:!0},path:(T===null||T===void 0?void 0:T.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:o,parsedType:vT(o)},S=this._parse({data:o,path:f.path,parent:f}),n=await(_S(S)?S:Promise.resolve(S));return lF(f,n)}refine(o,T){let f=(S)=>{if(typeof T==="string"||typeof T==="undefined")return{message:T};else if(typeof T==="function")return T(S);else return T};return this._refinement((S,n)=>{let A=o(S),$=()=>n.addIssue({code:z.custom,...f(S)});if(typeof Promise!=="undefined"&&A instanceof Promise)return A.then((F)=>{if(!F)return $(),!1;else return!0});if(!A)return $(),!1;else return!0})}refinement(o,T){return this._refinement((f,S)=>{if(!o(f))return S.addIssue(typeof T==="function"?T(f,S):T),!1;else return!0})}_refinement(o){return new _T({schema:this,typeName:g.ZodEffects,effect:{type:"refinement",refinement:o}})}superRefine(o){return this._refinement(o)}constructor(o){this.spa=this.safeParseAsync,this._def=o,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:(T)=>this["~validate"](T)}}optional(){return YT.create(this,this._def)}nullable(){return qT.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return GT.create(this)}promise(){return Wf.create(this,this._def)}or(o){return hf.create([this,o],this._def)}and(o){return bf.create(this,o,this._def)}transform(o){return new _T({...u(this._def),schema:this,typeName:g.ZodEffects,effect:{type:"transform",transform:o}})}default(o){let T=typeof o==="function"?o:()=>o;return new rf({...u(this._def),innerType:this,defaultValue:T,typeName:g.ZodDefault})}brand(){return new Rn({typeName:g.ZodBranded,type:this,...u(this._def)})}catch(o){let T=typeof o==="function"?o:()=>o;return new Zf({...u(this._def),innerType:this,catchValue:T,typeName:g.ZodCatch})}describe(o){return new this.constructor({...this._def,description:o})}pipe(o){return GS.create(this,o)}readonly(){return pf.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var PM=/^c[^\s-]{8,}$/i,iM=/^[0-9a-z]+$/,gM=/^[0-9A-HJKMNP-TV-Z]{26}$/i,dM=/^[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,lM=/^[a-z0-9_-]{21}$/i,uM=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,eM=/^[-+]?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)?)??$/,sM=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,aM="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",VA,oW=/^(?:(?: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])$/,TW=/^(?:(?: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])$/,fW=/^(([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]))$/,SW=/^(([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])$/,nW=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,AW=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,oJ="((\\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])))",$W=new RegExp(`^${oJ}$`);function TJ(o){let T="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";if(o.precision)T=`${T}\\.\\d{${o.precision}}`;else if(o.precision==null)T=`${T}(\\.\\d+)?`;return T}function FW(o){return new RegExp(`^${TJ(o)}$`)}function fJ(o){let T=`${oJ}T${TJ(o)}`,f=[];if(f.push(o.local?"Z?":"Z"),o.offset)f.push("([+-]\\d{2}:?\\d{2})");return T=`${T}(${f.join("|")})`,new RegExp(`^${T}$`)}function JW(o,T){if((T==="v4"||!T)&&oW.test(o))return!0;if((T==="v6"||!T)&&fW.test(o))return!0;return!1}function RW(o,T){if(!uM.test(o))return!1;try{let[f]=o.split("."),S=f.replace(/-/g,"+").replace(/_/g,"/").padEnd(f.length+(4-f.length%4)%4,"="),n=JSON.parse(atob(S));if(typeof n!=="object"||n===null)return!1;if(!n.typ||!n.alg)return!1;if(T&&n.alg!==T)return!1;return!0}catch(f){return!1}}function MW(o,T){if((T==="v4"||!T)&&TW.test(o))return!0;if((T==="v6"||!T)&&SW.test(o))return!0;return!1}class KT extends e{_parse(o){if(this._def.coerce)o.data=String(o.data);if(this._getType(o)!==N.string){let n=this._getOrReturnCtx(o);return I(n,{code:z.invalid_type,expected:N.string,received:n.parsedType}),d}let f=new uo,S=void 0;for(let n of this._def.checks)if(n.kind==="min"){if(o.data.length<n.value)S=this._getOrReturnCtx(o,S),I(S,{code:z.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),f.dirty()}else if(n.kind==="max"){if(o.data.length>n.value)S=this._getOrReturnCtx(o,S),I(S,{code:z.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),f.dirty()}else if(n.kind==="length"){let A=o.data.length>n.value,$=o.data.length<n.value;if(A||$){if(S=this._getOrReturnCtx(o,S),A)I(S,{code:z.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message});else if($)I(S,{code:z.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message});f.dirty()}}else if(n.kind==="email"){if(!sM.test(o.data))S=this._getOrReturnCtx(o,S),I(S,{validation:"email",code:z.invalid_string,message:n.message}),f.dirty()}else if(n.kind==="emoji"){if(!VA)VA=new RegExp(aM,"u");if(!VA.test(o.data))S=this._getOrReturnCtx(o,S),I(S,{validation:"emoji",code:z.invalid_string,message:n.message}),f.dirty()}else if(n.kind==="uuid"){if(!dM.test(o.data))S=this._getOrReturnCtx(o,S),I(S,{validation:"uuid",code:z.invalid_string,message:n.message}),f.dirty()}else if(n.kind==="nanoid"){if(!lM.test(o.data))S=this._getOrReturnCtx(o,S),I(S,{validation:"nanoid",code:z.invalid_string,message:n.message}),f.dirty()}else if(n.kind==="cuid"){if(!PM.test(o.data))S=this._getOrReturnCtx(o,S),I(S,{validation:"cuid",code:z.invalid_string,message:n.message}),f.dirty()}else if(n.kind==="cuid2"){if(!iM.test(o.data))S=this._getOrReturnCtx(o,S),I(S,{validation:"cuid2",code:z.invalid_string,message:n.message}),f.dirty()}else if(n.kind==="ulid"){if(!gM.test(o.data))S=this._getOrReturnCtx(o,S),I(S,{validation:"ulid",code:z.invalid_string,message:n.message}),f.dirty()}else if(n.kind==="url")try{new URL(o.data)}catch(A){S=this._getOrReturnCtx(o,S),I(S,{validation:"url",code:z.invalid_string,message:n.message}),f.dirty()}else if(n.kind==="regex"){if(n.regex.lastIndex=0,!n.regex.test(o.data))S=this._getOrReturnCtx(o,S),I(S,{validation:"regex",code:z.invalid_string,message:n.message}),f.dirty()}else if(n.kind==="trim")o.data=o.data.trim();else if(n.kind==="includes"){if(!o.data.includes(n.value,n.position))S=this._getOrReturnCtx(o,S),I(S,{code:z.invalid_string,validation:{includes:n.value,position:n.position},message:n.message}),f.dirty()}else if(n.kind==="toLowerCase")o.data=o.data.toLowerCase();else if(n.kind==="toUpperCase")o.data=o.data.toUpperCase();else if(n.kind==="startsWith"){if(!o.data.startsWith(n.value))S=this._getOrReturnCtx(o,S),I(S,{code:z.invalid_string,validation:{startsWith:n.value},message:n.message}),f.dirty()}else if(n.kind==="endsWith"){if(!o.data.endsWith(n.value))S=this._getOrReturnCtx(o,S),I(S,{code:z.invalid_string,validation:{endsWith:n.value},message:n.message}),f.dirty()}else if(n.kind==="datetime"){if(!fJ(n).test(o.data))S=this._getOrReturnCtx(o,S),I(S,{code:z.invalid_string,validation:"datetime",message:n.message}),f.dirty()}else if(n.kind==="date"){if(!$W.test(o.data))S=this._getOrReturnCtx(o,S),I(S,{code:z.invalid_string,validation:"date",message:n.message}),f.dirty()}else if(n.kind==="time"){if(!FW(n).test(o.data))S=this._getOrReturnCtx(o,S),I(S,{code:z.invalid_string,validation:"time",message:n.message}),f.dirty()}else if(n.kind==="duration"){if(!eM.test(o.data))S=this._getOrReturnCtx(o,S),I(S,{validation:"duration",code:z.invalid_string,message:n.message}),f.dirty()}else if(n.kind==="ip"){if(!JW(o.data,n.version))S=this._getOrReturnCtx(o,S),I(S,{validation:"ip",code:z.invalid_string,message:n.message}),f.dirty()}else if(n.kind==="jwt"){if(!RW(o.data,n.alg))S=this._getOrReturnCtx(o,S),I(S,{validation:"jwt",code:z.invalid_string,message:n.message}),f.dirty()}else if(n.kind==="cidr"){if(!MW(o.data,n.version))S=this._getOrReturnCtx(o,S),I(S,{validation:"cidr",code:z.invalid_string,message:n.message}),f.dirty()}else if(n.kind==="base64"){if(!nW.test(o.data))S=this._getOrReturnCtx(o,S),I(S,{validation:"base64",code:z.invalid_string,message:n.message}),f.dirty()}else if(n.kind==="base64url"){if(!AW.test(o.data))S=this._getOrReturnCtx(o,S),I(S,{validation:"base64url",code:z.invalid_string,message:n.message}),f.dirty()}else Ao.assertNever(n);return{status:f.value,value:o.data}}_regex(o,T,f){return this.refinement((S)=>o.test(S),{validation:T,code:z.invalid_string,...x.errToObj(f)})}_addCheck(o){return new KT({...this._def,checks:[...this._def.checks,o]})}email(o){return this._addCheck({kind:"email",...x.errToObj(o)})}url(o){return this._addCheck({kind:"url",...x.errToObj(o)})}emoji(o){return this._addCheck({kind:"emoji",...x.errToObj(o)})}uuid(o){return this._addCheck({kind:"uuid",...x.errToObj(o)})}nanoid(o){return this._addCheck({kind:"nanoid",...x.errToObj(o)})}cuid(o){return this._addCheck({kind:"cuid",...x.errToObj(o)})}cuid2(o){return this._addCheck({kind:"cuid2",...x.errToObj(o)})}ulid(o){return this._addCheck({kind:"ulid",...x.errToObj(o)})}base64(o){return this._addCheck({kind:"base64",...x.errToObj(o)})}base64url(o){return this._addCheck({kind:"base64url",...x.errToObj(o)})}jwt(o){return this._addCheck({kind:"jwt",...x.errToObj(o)})}ip(o){return this._addCheck({kind:"ip",...x.errToObj(o)})}cidr(o){return this._addCheck({kind:"cidr",...x.errToObj(o)})}datetime(o){var T,f;if(typeof o==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:o});return this._addCheck({kind:"datetime",precision:typeof(o===null||o===void 0?void 0:o.precision)==="undefined"?null:o===null||o===void 0?void 0:o.precision,offset:(T=o===null||o===void 0?void 0:o.offset)!==null&&T!==void 0?T:!1,local:(f=o===null||o===void 0?void 0:o.local)!==null&&f!==void 0?f:!1,...x.errToObj(o===null||o===void 0?void 0:o.message)})}date(o){return this._addCheck({kind:"date",message:o})}time(o){if(typeof o==="string")return this._addCheck({kind:"time",precision:null,message:o});return this._addCheck({kind:"time",precision:typeof(o===null||o===void 0?void 0:o.precision)==="undefined"?null:o===null||o===void 0?void 0:o.precision,...x.errToObj(o===null||o===void 0?void 0:o.message)})}duration(o){return this._addCheck({kind:"duration",...x.errToObj(o)})}regex(o,T){return this._addCheck({kind:"regex",regex:o,...x.errToObj(T)})}includes(o,T){return this._addCheck({kind:"includes",value:o,position:T===null||T===void 0?void 0:T.position,...x.errToObj(T===null||T===void 0?void 0:T.message)})}startsWith(o,T){return this._addCheck({kind:"startsWith",value:o,...x.errToObj(T)})}endsWith(o,T){return this._addCheck({kind:"endsWith",value:o,...x.errToObj(T)})}min(o,T){return this._addCheck({kind:"min",value:o,...x.errToObj(T)})}max(o,T){return this._addCheck({kind:"max",value:o,...x.errToObj(T)})}length(o,T){return this._addCheck({kind:"length",value:o,...x.errToObj(T)})}nonempty(o){return this.min(1,x.errToObj(o))}trim(){return new KT({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new KT({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new KT({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((o)=>o.kind==="datetime")}get isDate(){return!!this._def.checks.find((o)=>o.kind==="date")}get isTime(){return!!this._def.checks.find((o)=>o.kind==="time")}get isDuration(){return!!this._def.checks.find((o)=>o.kind==="duration")}get isEmail(){return!!this._def.checks.find((o)=>o.kind==="email")}get isURL(){return!!this._def.checks.find((o)=>o.kind==="url")}get isEmoji(){return!!this._def.checks.find((o)=>o.kind==="emoji")}get isUUID(){return!!this._def.checks.find((o)=>o.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((o)=>o.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((o)=>o.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((o)=>o.kind==="cuid2")}get isULID(){return!!this._def.checks.find((o)=>o.kind==="ulid")}get isIP(){return!!this._def.checks.find((o)=>o.kind==="ip")}get isCIDR(){return!!this._def.checks.find((o)=>o.kind==="cidr")}get isBase64(){return!!this._def.checks.find((o)=>o.kind==="base64")}get isBase64url(){return!!this._def.checks.find((o)=>o.kind==="base64url")}get minLength(){let o=null;for(let T of this._def.checks)if(T.kind==="min"){if(o===null||T.value>o)o=T.value}return o}get maxLength(){let o=null;for(let T of this._def.checks)if(T.kind==="max"){if(o===null||T.value<o)o=T.value}return o}}KT.create=(o)=>{var T;return new KT({checks:[],typeName:g.ZodString,coerce:(T=o===null||o===void 0?void 0:o.coerce)!==null&&T!==void 0?T:!1,...u(o)})};function WW(o,T){let f=(o.toString().split(".")[1]||"").length,S=(T.toString().split(".")[1]||"").length,n=f>S?f:S,A=parseInt(o.toFixed(n).replace(".","")),$=parseInt(T.toFixed(n).replace(".",""));return A%$/Math.pow(10,n)}class gT extends e{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(o){if(this._def.coerce)o.data=Number(o.data);if(this._getType(o)!==N.number){let n=this._getOrReturnCtx(o);return I(n,{code:z.invalid_type,expected:N.number,received:n.parsedType}),d}let f=void 0,S=new uo;for(let n of this._def.checks)if(n.kind==="int"){if(!Ao.isInteger(o.data))f=this._getOrReturnCtx(o,f),I(f,{code:z.invalid_type,expected:"integer",received:"float",message:n.message}),S.dirty()}else if(n.kind==="min"){if(n.inclusive?o.data<n.value:o.data<=n.value)f=this._getOrReturnCtx(o,f),I(f,{code:z.too_small,minimum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),S.dirty()}else if(n.kind==="max"){if(n.inclusive?o.data>n.value:o.data>=n.value)f=this._getOrReturnCtx(o,f),I(f,{code:z.too_big,maximum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),S.dirty()}else if(n.kind==="multipleOf"){if(WW(o.data,n.value)!==0)f=this._getOrReturnCtx(o,f),I(f,{code:z.not_multiple_of,multipleOf:n.value,message:n.message}),S.dirty()}else if(n.kind==="finite"){if(!Number.isFinite(o.data))f=this._getOrReturnCtx(o,f),I(f,{code:z.not_finite,message:n.message}),S.dirty()}else Ao.assertNever(n);return{status:S.value,value:o.data}}gte(o,T){return this.setLimit("min",o,!0,x.toString(T))}gt(o,T){return this.setLimit("min",o,!1,x.toString(T))}lte(o,T){return this.setLimit("max",o,!0,x.toString(T))}lt(o,T){return this.setLimit("max",o,!1,x.toString(T))}setLimit(o,T,f,S){return new gT({...this._def,checks:[...this._def.checks,{kind:o,value:T,inclusive:f,message:x.toString(S)}]})}_addCheck(o){return new gT({...this._def,checks:[...this._def.checks,o]})}int(o){return this._addCheck({kind:"int",message:x.toString(o)})}positive(o){return this._addCheck({kind:"min",value:0,inclusive:!1,message:x.toString(o)})}negative(o){return this._addCheck({kind:"max",value:0,inclusive:!1,message:x.toString(o)})}nonpositive(o){return this._addCheck({kind:"max",value:0,inclusive:!0,message:x.toString(o)})}nonnegative(o){return this._addCheck({kind:"min",value:0,inclusive:!0,message:x.toString(o)})}multipleOf(o,T){return this._addCheck({kind:"multipleOf",value:o,message:x.toString(T)})}finite(o){return this._addCheck({kind:"finite",message:x.toString(o)})}safe(o){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:x.toString(o)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:x.toString(o)})}get minValue(){let o=null;for(let T of this._def.checks)if(T.kind==="min"){if(o===null||T.value>o)o=T.value}return o}get maxValue(){let o=null;for(let T of this._def.checks)if(T.kind==="max"){if(o===null||T.value<o)o=T.value}return o}get isInt(){return!!this._def.checks.find((o)=>o.kind==="int"||o.kind==="multipleOf"&&Ao.isInteger(o.value))}get isFinite(){let o=null,T=null;for(let f of this._def.checks)if(f.kind==="finite"||f.kind==="int"||f.kind==="multipleOf")return!0;else if(f.kind==="min"){if(T===null||f.value>T)T=f.value}else if(f.kind==="max"){if(o===null||f.value<o)o=f.value}return Number.isFinite(T)&&Number.isFinite(o)}}gT.create=(o)=>{return new gT({checks:[],typeName:g.ZodNumber,coerce:(o===null||o===void 0?void 0:o.coerce)||!1,...u(o)})};class dT extends e{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(o){if(this._def.coerce)try{o.data=BigInt(o.data)}catch(n){return this._getInvalidInput(o)}if(this._getType(o)!==N.bigint)return this._getInvalidInput(o);let f=void 0,S=new uo;for(let n of this._def.checks)if(n.kind==="min"){if(n.inclusive?o.data<n.value:o.data<=n.value)f=this._getOrReturnCtx(o,f),I(f,{code:z.too_small,type:"bigint",minimum:n.value,inclusive:n.inclusive,message:n.message}),S.dirty()}else if(n.kind==="max"){if(n.inclusive?o.data>n.value:o.data>=n.value)f=this._getOrReturnCtx(o,f),I(f,{code:z.too_big,type:"bigint",maximum:n.value,inclusive:n.inclusive,message:n.message}),S.dirty()}else if(n.kind==="multipleOf"){if(o.data%n.value!==BigInt(0))f=this._getOrReturnCtx(o,f),I(f,{code:z.not_multiple_of,multipleOf:n.value,message:n.message}),S.dirty()}else Ao.assertNever(n);return{status:S.value,value:o.data}}_getInvalidInput(o){let T=this._getOrReturnCtx(o);return I(T,{code:z.invalid_type,expected:N.bigint,received:T.parsedType}),d}gte(o,T){return this.setLimit("min",o,!0,x.toString(T))}gt(o,T){return this.setLimit("min",o,!1,x.toString(T))}lte(o,T){return this.setLimit("max",o,!0,x.toString(T))}lt(o,T){return this.setLimit("max",o,!1,x.toString(T))}setLimit(o,T,f,S){return new dT({...this._def,checks:[...this._def.checks,{kind:o,value:T,inclusive:f,message:x.toString(S)}]})}_addCheck(o){return new dT({...this._def,checks:[...this._def.checks,o]})}positive(o){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:x.toString(o)})}negative(o){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:x.toString(o)})}nonpositive(o){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:x.toString(o)})}nonnegative(o){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:x.toString(o)})}multipleOf(o,T){return this._addCheck({kind:"multipleOf",value:o,message:x.toString(T)})}get minValue(){let o=null;for(let T of this._def.checks)if(T.kind==="min"){if(o===null||T.value>o)o=T.value}return o}get maxValue(){let o=null;for(let T of this._def.checks)if(T.kind==="max"){if(o===null||T.value<o)o=T.value}return o}}dT.create=(o)=>{var T;return new dT({checks:[],typeName:g.ZodBigInt,coerce:(T=o===null||o===void 0?void 0:o.coerce)!==null&&T!==void 0?T:!1,...u(o)})};class jf extends e{_parse(o){if(this._def.coerce)o.data=Boolean(o.data);if(this._getType(o)!==N.boolean){let f=this._getOrReturnCtx(o);return I(f,{code:z.invalid_type,expected:N.boolean,received:f.parsedType}),d}return ao(o.data)}}jf.create=(o)=>{return new jf({typeName:g.ZodBoolean,coerce:(o===null||o===void 0?void 0:o.coerce)||!1,...u(o)})};class Jf extends e{_parse(o){if(this._def.coerce)o.data=new Date(o.data);if(this._getType(o)!==N.date){let n=this._getOrReturnCtx(o);return I(n,{code:z.invalid_type,expected:N.date,received:n.parsedType}),d}if(isNaN(o.data.getTime())){let n=this._getOrReturnCtx(o);return I(n,{code:z.invalid_date}),d}let f=new uo,S=void 0;for(let n of this._def.checks)if(n.kind==="min"){if(o.data.getTime()<n.value)S=this._getOrReturnCtx(o,S),I(S,{code:z.too_small,message:n.message,inclusive:!0,exact:!1,minimum:n.value,type:"date"}),f.dirty()}else if(n.kind==="max"){if(o.data.getTime()>n.value)S=this._getOrReturnCtx(o,S),I(S,{code:z.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),f.dirty()}else Ao.assertNever(n);return{status:f.value,value:new Date(o.data.getTime())}}_addCheck(o){return new Jf({...this._def,checks:[...this._def.checks,o]})}min(o,T){return this._addCheck({kind:"min",value:o.getTime(),message:x.toString(T)})}max(o,T){return this._addCheck({kind:"max",value:o.getTime(),message:x.toString(T)})}get minDate(){let o=null;for(let T of this._def.checks)if(T.kind==="min"){if(o===null||T.value>o)o=T.value}return o!=null?new Date(o):null}get maxDate(){let o=null;for(let T of this._def.checks)if(T.kind==="max"){if(o===null||T.value<o)o=T.value}return o!=null?new Date(o):null}}Jf.create=(o)=>{return new Jf({checks:[],coerce:(o===null||o===void 0?void 0:o.coerce)||!1,typeName:g.ZodDate,...u(o)})};class wS extends e{_parse(o){if(this._getType(o)!==N.symbol){let f=this._getOrReturnCtx(o);return I(f,{code:z.invalid_type,expected:N.symbol,received:f.parsedType}),d}return ao(o.data)}}wS.create=(o)=>{return new wS({typeName:g.ZodSymbol,...u(o)})};class mf extends e{_parse(o){if(this._getType(o)!==N.undefined){let f=this._getOrReturnCtx(o);return I(f,{code:z.invalid_type,expected:N.undefined,received:f.parsedType}),d}return ao(o.data)}}mf.create=(o)=>{return new mf({typeName:g.ZodUndefined,...u(o)})};class Nf extends e{_parse(o){if(this._getType(o)!==N.null){let f=this._getOrReturnCtx(o);return I(f,{code:z.invalid_type,expected:N.null,received:f.parsedType}),d}return ao(o.data)}}Nf.create=(o)=>{return new Nf({typeName:g.ZodNull,...u(o)})};class Rf extends e{constructor(){super(...arguments);this._any=!0}_parse(o){return ao(o.data)}}Rf.create=(o)=>{return new Rf({typeName:g.ZodAny,...u(o)})};class iT extends e{constructor(){super(...arguments);this._unknown=!0}_parse(o){return ao(o.data)}}iT.create=(o)=>{return new iT({typeName:g.ZodUnknown,...u(o)})};class BT extends e{_parse(o){let T=this._getOrReturnCtx(o);return I(T,{code:z.invalid_type,expected:N.never,received:T.parsedType}),d}}BT.create=(o)=>{return new BT({typeName:g.ZodNever,...u(o)})};class yS extends e{_parse(o){if(this._getType(o)!==N.undefined){let f=this._getOrReturnCtx(o);return I(f,{code:z.invalid_type,expected:N.void,received:f.parsedType}),d}return ao(o.data)}}yS.create=(o)=>{return new yS({typeName:g.ZodVoid,...u(o)})};class GT extends e{_parse(o){let{ctx:T,status:f}=this._processInputParams(o),S=this._def;if(T.parsedType!==N.array)return I(T,{code:z.invalid_type,expected:N.array,received:T.parsedType}),d;if(S.exactLength!==null){let A=T.data.length>S.exactLength.value,$=T.data.length<S.exactLength.value;if(A||$)I(T,{code:A?z.too_big:z.too_small,minimum:$?S.exactLength.value:void 0,maximum:A?S.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:S.exactLength.message}),f.dirty()}if(S.minLength!==null){if(T.data.length<S.minLength.value)I(T,{code:z.too_small,minimum:S.minLength.value,type:"array",inclusive:!0,exact:!1,message:S.minLength.message}),f.dirty()}if(S.maxLength!==null){if(T.data.length>S.maxLength.value)I(T,{code:z.too_big,maximum:S.maxLength.value,type:"array",inclusive:!0,exact:!1,message:S.maxLength.message}),f.dirty()}if(T.common.async)return Promise.all([...T.data].map((A,$)=>{return S.type._parseAsync(new ET(T,A,T.path,$))})).then((A)=>{return uo.mergeArray(f,A)});let n=[...T.data].map((A,$)=>{return S.type._parseSync(new ET(T,A,T.path,$))});return uo.mergeArray(f,n)}get element(){return this._def.type}min(o,T){return new GT({...this._def,minLength:{value:o,message:x.toString(T)}})}max(o,T){return new GT({...this._def,maxLength:{value:o,message:x.toString(T)}})}length(o,T){return new GT({...this._def,exactLength:{value:o,message:x.toString(T)}})}nonempty(o){return this.min(1,o)}}GT.create=(o,T)=>{return new GT({type:o,minLength:null,maxLength:null,exactLength:null,typeName:g.ZodArray,...u(T)})};function Bf(o){if(o instanceof Qo){let T={};for(let f in o.shape){let S=o.shape[f];T[f]=YT.create(Bf(S))}return new Qo({...o._def,shape:()=>T})}else if(o instanceof GT)return new GT({...o._def,type:Bf(o.element)});else if(o instanceof YT)return YT.create(Bf(o.unwrap()));else if(o instanceof qT)return qT.create(Bf(o.unwrap()));else if(o instanceof LT)return LT.create(o.items.map((T)=>Bf(T)));else return o}class Qo extends e{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let o=this._def.shape(),T=Ao.objectKeys(o);return this._cached={shape:o,keys:T}}_parse(o){if(this._getType(o)!==N.object){let J=this._getOrReturnCtx(o);return I(J,{code:z.invalid_type,expected:N.object,received:J.parsedType}),d}let{status:f,ctx:S}=this._processInputParams(o),{shape:n,keys:A}=this._getCached(),$=[];if(!(this._def.catchall instanceof BT&&this._def.unknownKeys==="strip")){for(let J in S.data)if(!A.includes(J))$.push(J)}let F=[];for(let J of A){let R=n[J],M=S.data[J];F.push({key:{status:"valid",value:J},value:R._parse(new ET(S,M,S.path,J)),alwaysSet:J in S.data})}if(this._def.catchall instanceof BT){let J=this._def.unknownKeys;if(J==="passthrough")for(let R of $)F.push({key:{status:"valid",value:R},value:{status:"valid",value:S.data[R]}});else if(J==="strict"){if($.length>0)I(S,{code:z.unrecognized_keys,keys:$}),f.dirty()}else if(J==="strip");else throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let J=this._def.catchall;for(let R of $){let M=S.data[R];F.push({key:{status:"valid",value:R},value:J._parse(new ET(S,M,S.path,R)),alwaysSet:R in S.data})}}if(S.common.async)return Promise.resolve().then(async()=>{let J=[];for(let R of F){let M=await R.key,_=await R.value;J.push({key:M,value:_,alwaysSet:R.alwaysSet})}return J}).then((J)=>{return uo.mergeObjectSync(f,J)});else return uo.mergeObjectSync(f,F)}get shape(){return this._def.shape()}strict(o){return x.errToObj,new Qo({...this._def,unknownKeys:"strict",...o!==void 0?{errorMap:(T,f)=>{var S,n,A,$;let F=(A=(n=(S=this._def).errorMap)===null||n===void 0?void 0:n.call(S,T,f).message)!==null&&A!==void 0?A:f.defaultError;if(T.code==="unrecognized_keys")return{message:($=x.errToObj(o).message)!==null&&$!==void 0?$:F};return{message:F}}}:{}})}strip(){return new Qo({...this._def,unknownKeys:"strip"})}passthrough(){return new Qo({...this._def,unknownKeys:"passthrough"})}extend(o){return new Qo({...this._def,shape:()=>({...this._def.shape(),...o})})}merge(o){return new Qo({unknownKeys:o._def.unknownKeys,catchall:o._def.catchall,shape:()=>({...this._def.shape(),...o._def.shape()}),typeName:g.ZodObject})}setKey(o,T){return this.augment({[o]:T})}catchall(o){return new Qo({...this._def,catchall:o})}pick(o){let T={};return Ao.objectKeys(o).forEach((f)=>{if(o[f]&&this.shape[f])T[f]=this.shape[f]}),new Qo({...this._def,shape:()=>T})}omit(o){let T={};return Ao.objectKeys(this.shape).forEach((f)=>{if(!o[f])T[f]=this.shape[f]}),new Qo({...this._def,shape:()=>T})}deepPartial(){return Bf(this)}partial(o){let T={};return Ao.objectKeys(this.shape).forEach((f)=>{let S=this.shape[f];if(o&&!o[f])T[f]=S;else T[f]=S.optional()}),new Qo({...this._def,shape:()=>T})}required(o){let T={};return Ao.objectKeys(this.shape).forEach((f)=>{if(o&&!o[f])T[f]=this.shape[f];else{let n=this.shape[f];while(n instanceof YT)n=n._def.innerType;T[f]=n}}),new Qo({...this._def,shape:()=>T})}keyof(){return SJ(Ao.objectKeys(this.shape))}}Qo.create=(o,T)=>{return new Qo({shape:()=>o,unknownKeys:"strip",catchall:BT.create(),typeName:g.ZodObject,...u(T)})};Qo.strictCreate=(o,T)=>{return new Qo({shape:()=>o,unknownKeys:"strict",catchall:BT.create(),typeName:g.ZodObject,...u(T)})};Qo.lazycreate=(o,T)=>{return new Qo({shape:o,unknownKeys:"strip",catchall:BT.create(),typeName:g.ZodObject,...u(T)})};class hf extends e{_parse(o){let{ctx:T}=this._processInputParams(o),f=this._def.options;function S(n){for(let $ of n)if($.result.status==="valid")return $.result;for(let $ of n)if($.result.status==="dirty")return T.common.issues.push(...$.ctx.common.issues),$.result;let A=n.map(($)=>new JT($.ctx.common.issues));return I(T,{code:z.invalid_union,unionErrors:A}),d}if(T.common.async)return Promise.all(f.map(async(n)=>{let A={...T,common:{...T.common,issues:[]},parent:null};return{result:await n._parseAsync({data:T.data,path:T.path,parent:A}),ctx:A}})).then(S);else{let n=void 0,A=[];for(let F of f){let J={...T,common:{...T.common,issues:[]},parent:null},R=F._parseSync({data:T.data,path:T.path,parent:J});if(R.status==="valid")return R;else if(R.status==="dirty"&&!n)n={result:R,ctx:J};if(J.common.issues.length)A.push(J.common.issues)}if(n)return T.common.issues.push(...n.ctx.common.issues),n.result;let $=A.map((F)=>new JT(F));return I(T,{code:z.invalid_union,unionErrors:$}),d}}get options(){return this._def.options}}hf.create=(o,T)=>{return new hf({options:o,typeName:g.ZodUnion,...u(T)})};var xT=(o)=>{if(o instanceof xf)return xT(o.schema);else if(o instanceof _T)return xT(o.innerType());else if(o instanceof vf)return[o.value];else if(o instanceof lT)return o.options;else if(o instanceof qf)return Ao.objectValues(o.enum);else if(o instanceof rf)return xT(o._def.innerType);else if(o instanceof mf)return[void 0];else if(o instanceof Nf)return[null];else if(o instanceof YT)return[void 0,...xT(o.unwrap())];else if(o instanceof qT)return[null,...xT(o.unwrap())];else if(o instanceof Rn)return xT(o.unwrap());else if(o instanceof pf)return xT(o.unwrap());else if(o instanceof Zf)return xT(o._def.innerType);else return[]};class Jn extends e{_parse(o){let{ctx:T}=this._processInputParams(o);if(T.parsedType!==N.object)return I(T,{code:z.invalid_type,expected:N.object,received:T.parsedType}),d;let f=this.discriminator,S=T.data[f],n=this.optionsMap.get(S);if(!n)return I(T,{code:z.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[f]}),d;if(T.common.async)return n._parseAsync({data:T.data,path:T.path,parent:T});else return n._parseSync({data:T.data,path:T.path,parent:T})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(o,T,f){let S=new Map;for(let n of T){let A=xT(n.shape[o]);if(!A.length)throw new Error(`A discriminator value for key \`${o}\` could not be extracted from all schema options`);for(let $ of A){if(S.has($))throw new Error(`Discriminator property ${String(o)} has duplicate value ${String($)}`);S.set($,n)}}return new Jn({typeName:g.ZodDiscriminatedUnion,discriminator:o,options:T,optionsMap:S,...u(f)})}}function IA(o,T){let f=vT(o),S=vT(T);if(o===T)return{valid:!0,data:o};else if(f===N.object&&S===N.object){let n=Ao.objectKeys(T),A=Ao.objectKeys(o).filter((F)=>n.indexOf(F)!==-1),$={...o,...T};for(let F of A){let J=IA(o[F],T[F]);if(!J.valid)return{valid:!1};$[F]=J.data}return{valid:!0,data:$}}else if(f===N.array&&S===N.array){if(o.length!==T.length)return{valid:!1};let n=[];for(let A=0;A<o.length;A++){let $=o[A],F=T[A],J=IA($,F);if(!J.valid)return{valid:!1};n.push(J.data)}return{valid:!0,data:n}}else if(f===N.date&&S===N.date&&+o===+T)return{valid:!0,data:o};else return{valid:!1}}class bf extends e{_parse(o){let{status:T,ctx:f}=this._processInputParams(o),S=(n,A)=>{if(LA(n)||LA(A))return d;let $=IA(n.value,A.value);if(!$.valid)return I(f,{code:z.invalid_intersection_types}),d;if(CA(n)||CA(A))T.dirty();return{status:T.value,value:$.data}};if(f.common.async)return Promise.all([this._def.left._parseAsync({data:f.data,path:f.path,parent:f}),this._def.right._parseAsync({data:f.data,path:f.path,parent:f})]).then(([n,A])=>S(n,A));else return S(this._def.left._parseSync({data:f.data,path:f.path,parent:f}),this._def.right._parseSync({data:f.data,path:f.path,parent:f}))}}bf.create=(o,T,f)=>{return new bf({left:o,right:T,typeName:g.ZodIntersection,...u(f)})};class LT extends e{_parse(o){let{status:T,ctx:f}=this._processInputParams(o);if(f.parsedType!==N.array)return I(f,{code:z.invalid_type,expected:N.array,received:f.parsedType}),d;if(f.data.length<this._def.items.length)return I(f,{code:z.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),d;if(!this._def.rest&&f.data.length>this._def.items.length)I(f,{code:z.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),T.dirty();let n=[...f.data].map((A,$)=>{let F=this._def.items[$]||this._def.rest;if(!F)return null;return F._parse(new ET(f,A,f.path,$))}).filter((A)=>!!A);if(f.common.async)return Promise.all(n).then((A)=>{return uo.mergeArray(T,A)});else return uo.mergeArray(T,n)}get items(){return this._def.items}rest(o){return new LT({...this._def,rest:o})}}LT.create=(o,T)=>{if(!Array.isArray(o))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new LT({items:o,typeName:g.ZodTuple,rest:null,...u(T)})};class XS extends e{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(o){let{status:T,ctx:f}=this._processInputParams(o);if(f.parsedType!==N.object)return I(f,{code:z.invalid_type,expected:N.object,received:f.parsedType}),d;let S=[],n=this._def.keyType,A=this._def.valueType;for(let $ in f.data)S.push({key:n._parse(new ET(f,$,f.path,$)),value:A._parse(new ET(f,f.data[$],f.path,$)),alwaysSet:$ in f.data});if(f.common.async)return uo.mergeObjectAsync(T,S);else return uo.mergeObjectSync(T,S)}get element(){return this._def.valueType}static create(o,T,f){if(T instanceof e)return new XS({keyType:o,valueType:T,typeName:g.ZodRecord,...u(f)});return new XS({keyType:KT.create(),valueType:o,typeName:g.ZodRecord,...u(T)})}}class HS extends e{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(o){let{status:T,ctx:f}=this._processInputParams(o);if(f.parsedType!==N.map)return I(f,{code:z.invalid_type,expected:N.map,received:f.parsedType}),d;let S=this._def.keyType,n=this._def.valueType,A=[...f.data.entries()].map(([$,F],J)=>{return{key:S._parse(new ET(f,$,f.path,[J,"key"])),value:n._parse(new ET(f,F,f.path,[J,"value"]))}});if(f.common.async){let $=new Map;return Promise.resolve().then(async()=>{for(let F of A){let J=await F.key,R=await F.value;if(J.status==="aborted"||R.status==="aborted")return d;if(J.status==="dirty"||R.status==="dirty")T.dirty();$.set(J.value,R.value)}return{status:T.value,value:$}})}else{let $=new Map;for(let F of A){let{key:J,value:R}=F;if(J.status==="aborted"||R.status==="aborted")return d;if(J.status==="dirty"||R.status==="dirty")T.dirty();$.set(J.value,R.value)}return{status:T.value,value:$}}}}HS.create=(o,T,f)=>{return new HS({valueType:T,keyType:o,typeName:g.ZodMap,...u(f)})};class Mf extends e{_parse(o){let{status:T,ctx:f}=this._processInputParams(o);if(f.parsedType!==N.set)return I(f,{code:z.invalid_type,expected:N.set,received:f.parsedType}),d;let S=this._def;if(S.minSize!==null){if(f.data.size<S.minSize.value)I(f,{code:z.too_small,minimum:S.minSize.value,type:"set",inclusive:!0,exact:!1,message:S.minSize.message}),T.dirty()}if(S.maxSize!==null){if(f.data.size>S.maxSize.value)I(f,{code:z.too_big,maximum:S.maxSize.value,type:"set",inclusive:!0,exact:!1,message:S.maxSize.message}),T.dirty()}let n=this._def.valueType;function A(F){let J=new Set;for(let R of F){if(R.status==="aborted")return d;if(R.status==="dirty")T.dirty();J.add(R.value)}return{status:T.value,value:J}}let $=[...f.data.values()].map((F,J)=>n._parse(new ET(f,F,f.path,J)));if(f.common.async)return Promise.all($).then((F)=>A(F));else return A($)}min(o,T){return new Mf({...this._def,minSize:{value:o,message:x.toString(T)}})}max(o,T){return new Mf({...this._def,maxSize:{value:o,message:x.toString(T)}})}size(o,T){return this.min(o,T).max(o,T)}nonempty(o){return this.min(1,o)}}Mf.create=(o,T)=>{return new Mf({valueType:o,minSize:null,maxSize:null,typeName:g.ZodSet,...u(T)})};class Cf extends e{constructor(){super(...arguments);this.validate=this.implement}_parse(o){let{ctx:T}=this._processInputParams(o);if(T.parsedType!==N.function)return I(T,{code:z.invalid_type,expected:N.function,received:T.parsedType}),d;function f($,F){return $n({data:$,path:T.path,errorMaps:[T.common.contextualErrorMap,T.schemaErrorMap,An(),If].filter((J)=>!!J),issueData:{code:z.invalid_arguments,argumentsError:F}})}function S($,F){return $n({data:$,path:T.path,errorMaps:[T.common.contextualErrorMap,T.schemaErrorMap,An(),If].filter((J)=>!!J),issueData:{code:z.invalid_return_type,returnTypeError:F}})}let n={errorMap:T.common.contextualErrorMap},A=T.data;if(this._def.returns instanceof Wf){let $=this;return ao(async function(...F){let J=new JT([]),R=await $._def.args.parseAsync(F,n).catch((w)=>{throw J.addIssue(f(F,w)),J}),M=await Reflect.apply(A,this,R);return await $._def.returns._def.type.parseAsync(M,n).catch((w)=>{throw J.addIssue(S(M,w)),J})})}else{let $=this;return ao(function(...F){let J=$._def.args.safeParse(F,n);if(!J.success)throw new JT([f(F,J.error)]);let R=Reflect.apply(A,this,J.data),M=$._def.returns.safeParse(R,n);if(!M.success)throw new JT([S(R,M.error)]);return M.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...o){return new Cf({...this._def,args:LT.create(o).rest(iT.create())})}returns(o){return new Cf({...this._def,returns:o})}implement(o){return this.parse(o)}strictImplement(o){return this.parse(o)}static create(o,T,f){return new Cf({args:o?o:LT.create([]).rest(iT.create()),returns:T||iT.create(),typeName:g.ZodFunction,...u(f)})}}class xf extends e{get schema(){return this._def.getter()}_parse(o){let{ctx:T}=this._processInputParams(o);return this._def.getter()._parse({data:T.data,path:T.path,parent:T})}}xf.create=(o,T)=>{return new xf({getter:o,typeName:g.ZodLazy,...u(T)})};class vf extends e{_parse(o){if(o.data!==this._def.value){let T=this._getOrReturnCtx(o);return I(T,{received:T.data,code:z.invalid_literal,expected:this._def.value}),d}return{status:"valid",value:o.data}}get value(){return this._def.value}}vf.create=(o,T)=>{return new vf({value:o,typeName:g.ZodLiteral,...u(T)})};function SJ(o,T){return new lT({values:o,typeName:g.ZodEnum,...u(T)})}class lT extends e{constructor(){super(...arguments);OS.set(this,void 0)}_parse(o){if(typeof o.data!=="string"){let T=this._getOrReturnCtx(o),f=this._def.values;return I(T,{expected:Ao.joinValues(f),received:T.parsedType,code:z.invalid_type}),d}if(!Fn(this,OS,"f"))aF(this,OS,new Set(this._def.values),"f");if(!Fn(this,OS,"f").has(o.data)){let T=this._getOrReturnCtx(o),f=this._def.values;return I(T,{received:T.data,code:z.invalid_enum_value,options:f}),d}return ao(o.data)}get options(){return this._def.values}get enum(){let o={};for(let T of this._def.values)o[T]=T;return o}get Values(){let o={};for(let T of this._def.values)o[T]=T;return o}get Enum(){let o={};for(let T of this._def.values)o[T]=T;return o}extract(o,T=this._def){return lT.create(o,{...this._def,...T})}exclude(o,T=this._def){return lT.create(this.options.filter((f)=>!o.includes(f)),{...this._def,...T})}}OS=new WeakMap;lT.create=SJ;class qf extends e{constructor(){super(...arguments);kS.set(this,void 0)}_parse(o){let T=Ao.getValidEnumValues(this._def.values),f=this._getOrReturnCtx(o);if(f.parsedType!==N.string&&f.parsedType!==N.number){let S=Ao.objectValues(T);return I(f,{expected:Ao.joinValues(S),received:f.parsedType,code:z.invalid_type}),d}if(!Fn(this,kS,"f"))aF(this,kS,new Set(Ao.getValidEnumValues(this._def.values)),"f");if(!Fn(this,kS,"f").has(o.data)){let S=Ao.objectValues(T);return I(f,{received:f.data,code:z.invalid_enum_value,options:S}),d}return ao(o.data)}get enum(){return this._def.values}}kS=new WeakMap;qf.create=(o,T)=>{return new qf({values:o,typeName:g.ZodNativeEnum,...u(T)})};class Wf extends e{unwrap(){return this._def.type}_parse(o){let{ctx:T}=this._processInputParams(o);if(T.parsedType!==N.promise&&T.common.async===!1)return I(T,{code:z.invalid_type,expected:N.promise,received:T.parsedType}),d;let f=T.parsedType===N.promise?T.data:Promise.resolve(T.data);return ao(f.then((S)=>{return this._def.type.parseAsync(S,{path:T.path,errorMap:T.common.contextualErrorMap})}))}}Wf.create=(o,T)=>{return new Wf({type:o,typeName:g.ZodPromise,...u(T)})};class _T extends e{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===g.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(o){let{status:T,ctx:f}=this._processInputParams(o),S=this._def.effect||null,n={addIssue:(A)=>{if(I(f,A),A.fatal)T.abort();else T.dirty()},get path(){return f.path}};if(n.addIssue=n.addIssue.bind(n),S.type==="preprocess"){let A=S.transform(f.data,n);if(f.common.async)return Promise.resolve(A).then(async($)=>{if(T.value==="aborted")return d;let F=await this._def.schema._parseAsync({data:$,path:f.path,parent:f});if(F.status==="aborted")return d;if(F.status==="dirty")return Lf(F.value);if(T.value==="dirty")return Lf(F.value);return F});else{if(T.value==="aborted")return d;let $=this._def.schema._parseSync({data:A,path:f.path,parent:f});if($.status==="aborted")return d;if($.status==="dirty")return Lf($.value);if(T.value==="dirty")return Lf($.value);return $}}if(S.type==="refinement"){let A=($)=>{let F=S.refinement($,n);if(f.common.async)return Promise.resolve(F);if(F instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return $};if(f.common.async===!1){let $=this._def.schema._parseSync({data:f.data,path:f.path,parent:f});if($.status==="aborted")return d;if($.status==="dirty")T.dirty();return A($.value),{status:T.value,value:$.value}}else return this._def.schema._parseAsync({data:f.data,path:f.path,parent:f}).then(($)=>{if($.status==="aborted")return d;if($.status==="dirty")T.dirty();return A($.value).then(()=>{return{status:T.value,value:$.value}})})}if(S.type==="transform")if(f.common.async===!1){let A=this._def.schema._parseSync({data:f.data,path:f.path,parent:f});if(!Ff(A))return A;let $=S.transform(A.value,n);if($ instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:T.value,value:$}}else return this._def.schema._parseAsync({data:f.data,path:f.path,parent:f}).then((A)=>{if(!Ff(A))return A;return Promise.resolve(S.transform(A.value,n)).then(($)=>({status:T.value,value:$}))});Ao.assertNever(S)}}_T.create=(o,T,f)=>{return new _T({schema:o,typeName:g.ZodEffects,effect:T,...u(f)})};_T.createWithPreprocess=(o,T,f)=>{return new _T({schema:T,effect:{type:"preprocess",transform:o},typeName:g.ZodEffects,...u(f)})};class YT extends e{_parse(o){if(this._getType(o)===N.undefined)return ao(void 0);return this._def.innerType._parse(o)}unwrap(){return this._def.innerType}}YT.create=(o,T)=>{return new YT({innerType:o,typeName:g.ZodOptional,...u(T)})};class qT extends e{_parse(o){if(this._getType(o)===N.null)return ao(null);return this._def.innerType._parse(o)}unwrap(){return this._def.innerType}}qT.create=(o,T)=>{return new qT({innerType:o,typeName:g.ZodNullable,...u(T)})};class rf extends e{_parse(o){let{ctx:T}=this._processInputParams(o),f=T.data;if(T.parsedType===N.undefined)f=this._def.defaultValue();return this._def.innerType._parse({data:f,path:T.path,parent:T})}removeDefault(){return this._def.innerType}}rf.create=(o,T)=>{return new rf({innerType:o,typeName:g.ZodDefault,defaultValue:typeof T.default==="function"?T.default:()=>T.default,...u(T)})};class Zf extends e{_parse(o){let{ctx:T}=this._processInputParams(o),f={...T,common:{...T.common,issues:[]}},S=this._def.innerType._parse({data:f.data,path:f.path,parent:{...f}});if(_S(S))return S.then((n)=>{return{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new JT(f.common.issues)},input:f.data})}});else return{status:"valid",value:S.status==="valid"?S.value:this._def.catchValue({get error(){return new JT(f.common.issues)},input:f.data})}}removeCatch(){return this._def.innerType}}Zf.create=(o,T)=>{return new Zf({innerType:o,typeName:g.ZodCatch,catchValue:typeof T.catch==="function"?T.catch:()=>T.catch,...u(T)})};class KS extends e{_parse(o){if(this._getType(o)!==N.nan){let f=this._getOrReturnCtx(o);return I(f,{code:z.invalid_type,expected:N.nan,received:f.parsedType}),d}return{status:"valid",value:o.data}}}KS.create=(o)=>{return new KS({typeName:g.ZodNaN,...u(o)})};var OW=Symbol("zod_brand");class Rn extends e{_parse(o){let{ctx:T}=this._processInputParams(o),f=T.data;return this._def.type._parse({data:f,path:T.path,parent:T})}unwrap(){return this._def.type}}class GS extends e{_parse(o){let{status:T,ctx:f}=this._processInputParams(o);if(f.common.async)return(async()=>{let n=await this._def.in._parseAsync({data:f.data,path:f.path,parent:f});if(n.status==="aborted")return d;if(n.status==="dirty")return T.dirty(),Lf(n.value);else return this._def.out._parseAsync({data:n.value,path:f.path,parent:f})})();else{let S=this._def.in._parseSync({data:f.data,path:f.path,parent:f});if(S.status==="aborted")return d;if(S.status==="dirty")return T.dirty(),{status:"dirty",value:S.value};else return this._def.out._parseSync({data:S.value,path:f.path,parent:f})}}static create(o,T){return new GS({in:o,out:T,typeName:g.ZodPipeline})}}class pf extends e{_parse(o){let T=this._def.innerType._parse(o),f=(S)=>{if(Ff(S))S.value=Object.freeze(S.value);return S};return _S(T)?T.then((S)=>f(S)):f(T)}unwrap(){return this._def.innerType}}pf.create=(o,T)=>{return new pf({innerType:o,typeName:g.ZodReadonly,...u(T)})};function uF(o,T){let f=typeof o==="function"?o(T):typeof o==="string"?{message:o}:o;return typeof f==="string"?{message:f}:f}function nJ(o,T={},f){if(o)return Rf.create().superRefine((S,n)=>{var A,$;let F=o(S);if(F instanceof Promise)return F.then((J)=>{var R,M;if(!J){let _=uF(T,S),w=(M=(R=_.fatal)!==null&&R!==void 0?R:f)!==null&&M!==void 0?M:!0;n.addIssue({code:"custom",..._,fatal:w})}});if(!F){let J=uF(T,S),R=($=(A=J.fatal)!==null&&A!==void 0?A:f)!==null&&$!==void 0?$:!0;n.addIssue({code:"custom",...J,fatal:R})}return});return Rf.create()}var kW={object:Qo.lazycreate},g;(function(o){o.ZodString="ZodString",o.ZodNumber="ZodNumber",o.ZodNaN="ZodNaN",o.ZodBigInt="ZodBigInt",o.ZodBoolean="ZodBoolean",o.ZodDate="ZodDate",o.ZodSymbol="ZodSymbol",o.ZodUndefined="ZodUndefined",o.ZodNull="ZodNull",o.ZodAny="ZodAny",o.ZodUnknown="ZodUnknown",o.ZodNever="ZodNever",o.ZodVoid="ZodVoid",o.ZodArray="ZodArray",o.ZodObject="ZodObject",o.ZodUnion="ZodUnion",o.ZodDiscriminatedUnion="ZodDiscriminatedUnion",o.ZodIntersection="ZodIntersection",o.ZodTuple="ZodTuple",o.ZodRecord="ZodRecord",o.ZodMap="ZodMap",o.ZodSet="ZodSet",o.ZodFunction="ZodFunction",o.ZodLazy="ZodLazy",o.ZodLiteral="ZodLiteral",o.ZodEnum="ZodEnum",o.ZodEffects="ZodEffects",o.ZodNativeEnum="ZodNativeEnum",o.ZodOptional="ZodOptional",o.ZodNullable="ZodNullable",o.ZodDefault="ZodDefault",o.ZodCatch="ZodCatch",o.ZodPromise="ZodPromise",o.ZodBranded="ZodBranded",o.ZodPipeline="ZodPipeline",o.ZodReadonly="ZodReadonly"})(g||(g={}));var _W=(o,T={message:`Input not instance of ${o.name}`})=>nJ((f)=>f instanceof o,T),AJ=KT.create,$J=gT.create,wW=KS.create,yW=dT.create,FJ=jf.create,XW=Jf.create,HW=wS.create,KW=mf.create,GW=Nf.create,YW=Rf.create,EW=iT.create,zW=BT.create,QW=yS.create,DW=GT.create,UW=Qo.create,tW=Qo.strictCreate,VW=hf.create,BW=Jn.create,LW=bf.create,CW=LT.create,IW=XS.create,jW=HS.create,mW=Mf.create,NW=Cf.create,hW=xf.create,bW=vf.create,xW=lT.create,vW=qf.create,qW=Wf.create,eF=_T.create,rW=YT.create,ZW=qT.create,pW=_T.createWithPreprocess,cW=GS.create,PW=()=>AJ().optional(),iW=()=>$J().optional(),gW=()=>FJ().optional(),dW={string:(o)=>KT.create({...o,coerce:!0}),number:(o)=>gT.create({...o,coerce:!0}),boolean:(o)=>jf.create({...o,coerce:!0}),bigint:(o)=>dT.create({...o,coerce:!0}),date:(o)=>Jf.create({...o,coerce:!0})},lW=d,Yo=Object.freeze({__proto__:null,defaultErrorMap:If,setErrorMap:pM,getErrorMap:An,makeIssue:$n,EMPTY_PATH:cM,addIssueToContext:I,ParseStatus:uo,INVALID:d,DIRTY:Lf,OK:ao,isAborted:LA,isDirty:CA,isValid:Ff,isAsync:_S,get util(){return Ao},get objectUtil(){return BA},ZodParsedType:N,getParsedType:vT,ZodType:e,datetimeRegex:fJ,ZodString:KT,ZodNumber:gT,ZodBigInt:dT,ZodBoolean:jf,ZodDate:Jf,ZodSymbol:wS,ZodUndefined:mf,ZodNull:Nf,ZodAny:Rf,ZodUnknown:iT,ZodNever:BT,ZodVoid:yS,ZodArray:GT,ZodObject:Qo,ZodUnion:hf,ZodDiscriminatedUnion:Jn,ZodIntersection:bf,ZodTuple:LT,ZodRecord:XS,ZodMap:HS,ZodSet:Mf,ZodFunction:Cf,ZodLazy:xf,ZodLiteral:vf,ZodEnum:lT,ZodNativeEnum:qf,ZodPromise:Wf,ZodEffects:_T,ZodTransformer:_T,ZodOptional:YT,ZodNullable:qT,ZodDefault:rf,ZodCatch:Zf,ZodNaN:KS,BRAND:OW,ZodBranded:Rn,ZodPipeline:GS,ZodReadonly:pf,custom:nJ,Schema:e,ZodSchema:e,late:kW,get ZodFirstPartyTypeKind(){return g},coerce:dW,any:YW,array:DW,bigint:yW,boolean:FJ,date:XW,discriminatedUnion:BW,effect:eF,enum:xW,function:NW,instanceof:_W,intersection:LW,lazy:hW,literal:bW,map:jW,nan:wW,nativeEnum:vW,never:zW,null:GW,nullable:ZW,number:$J,object:UW,oboolean:gW,onumber:iW,optional:rW,ostring:PW,pipeline:cW,preprocess:pW,promise:qW,record:IW,set:mW,strictObject:tW,string:AJ,symbol:HW,transformer:eF,tuple:CW,undefined:KW,union:VW,unknown:EW,void:QW,NEVER:lW,ZodIssueCode:z,quotelessJson:ZM,ZodError:JT});var uW="__vite_start_time"in globalThis,eW=typeof window!=="undefined",S6="vitest"in globalThis,zT=dF({isServer:!uW&&!eW,server:{CI:Yo.string().transform((o)=>!0).optional(),POSTGRES_USER:Yo.string(),POSTGRES_PASSWORD:Yo.string(),POSTGRES_DATABASE:Yo.string(),POSTGRES_HOST:Yo.string(),POSTGRES_PORT:Yo.string().transform((o)=>Number.parseInt(o,10)),BACKEND_PORT:Yo.string().transform((o)=>Number.parseInt(o,10)),RUN_WORKERS_FROM_SOURCE:Yo.union([Yo.literal("true"),Yo.literal("false")]).optional().transform((o)=>o==="true"),FRONTEND_PORT:Yo.string().transform((o)=>Number.parseInt(o,10)),FRONTEND_ORIGINS:Yo.string().transform((o)=>JSON.parse(o)).pipe(Yo.array(Yo.string())),OPENAI_API_KEY:Yo.string().optional()},clientPrefix:"VITE_",client:{VITE_BACKEND_ORIGIN:Yo.string(),VITE_USE_SELF_SIGNED_CERTIFICATE:Yo.union([Yo.literal("true"),Yo.literal("false")]).optional().transform((o)=>o==="true")},runtimeEnv:import.meta.env,emptyStringAsUndefined:!0});var RJ=jA(import.meta.dirname,"../dev"),MJ=zT.VITE_USE_SELF_SIGNED_CERTIFICATE?{cert:JJ(jA(RJ,"./cert.pem"),"utf-8"),key:JJ(jA(RJ,"./key.pem"),"utf-8")}:void 0;import aO from"path";var O=Symbol.for("drizzle:entityKind"),R6=Symbol.for("drizzle:hasOwnEntityKind");function H(o,T){if(!o||typeof o!=="object")return!1;if(o instanceof T)return!0;if(!Object.prototype.hasOwnProperty.call(T,O))throw new Error(`Class "${T.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let f=Object.getPrototypeOf(o).constructor;if(f)while(f){if(O in f&&f[O]===T[O])return!0;f=Object.getPrototypeOf(f)}return!1}class _o{constructor(o,T){this.table=o,this.config=T,this.name=T.name,this.keyAsName=T.keyAsName,this.notNull=T.notNull,this.default=T.default,this.defaultFn=T.defaultFn,this.onUpdateFn=T.onUpdateFn,this.hasDefault=T.hasDefault,this.primary=T.primaryKey,this.isUnique=T.isUnique,this.uniqueName=T.uniqueName,this.uniqueType=T.uniqueType,this.dataType=T.dataType,this.columnType=T.columnType,this.generated=T.generated,this.generatedIdentity=T.generatedIdentity}static[O]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue(o){return o}mapToDriverValue(o){return o}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}class mA{static[O]="ColumnBuilder";config;constructor(o,T,f){this.config={name:o,keyAsName:o==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:T,columnType:f,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(o){return this.config.default=o,this.config.hasDefault=!0,this}$defaultFn(o){return this.config.defaultFn=o,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(o){return this.config.onUpdateFn=o,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(o){if(this.config.name!=="")return;this.config.name=o}}var QT=Symbol.for("drizzle:Name");class NA{static[O]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(o,T){if(this.reference=()=>{let{name:f,columns:S,foreignColumns:n}=o();return{name:f,columns:S,foreignTable:n[0].table,foreignColumns:n}},T)this._onUpdate=T.onUpdate,this._onDelete=T.onDelete}onUpdate(o){return this._onUpdate=o===void 0?"no action":o,this}onDelete(o){return this._onDelete=o===void 0?"no action":o,this}build(o){return new WJ(o,this)}}class WJ{constructor(o,T){this.table=o,this.reference=T.reference,this.onUpdate=T._onUpdate,this.onDelete=T._onDelete}static[O]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:o,columns:T,foreignColumns:f}=this.reference(),S=T.map(($)=>$.name),n=f.map(($)=>$.name),A=[this.table[QT],...S,f[0].table[QT],...n];return o??`${A.join("_")}_fk`}}function Mn(o,...T){return o(...T)}function OJ(o,T){return`${o[QT]}_${T.join("_")}_unique`}function kJ(o,T,f){for(let S=T;S<o.length;S++){let n=o[S];if(n==="\\"){S++;continue}if(n==='"')return[o.slice(T,S).replace(/\\/g,""),S+1];if(f)continue;if(n===","||n==="}")return[o.slice(T,S).replace(/\\/g,""),S]}return[o.slice(T).replace(/\\/g,""),o.length]}function _J(o,T=0){let f=[],S=T,n=!1;while(S<o.length){let A=o[S];if(A===","){if(n||S===T)f.push("");n=!0,S++;continue}if(n=!1,A==="\\"){S+=2;continue}if(A==='"'){let[J,R]=kJ(o,S+1,!0);f.push(J),S=R;continue}if(A==="}")return[f,S+1];if(A==="{"){let[J,R]=_J(o,S+1);f.push(J),S=R;continue}let[$,F]=kJ(o,S,!1);f.push($),S=F}return[f,S]}function wJ(o){let[T]=_J(o,1);return T}function hA(o){return`{${o.map((T)=>{if(Array.isArray(T))return hA(T);if(typeof T==="string")return`"${T.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${T}`}).join(",")}}`}class b extends mA{foreignKeyConfigs=[];static[O]="PgColumnBuilder";array(o){return new XJ(this.config.name,this,o)}references(o,T={}){return this.foreignKeyConfigs.push({ref:o,actions:T}),this}unique(o,T){return this.config.isUnique=!0,this.config.uniqueName=o,this.config.uniqueType=T?.nulls,this}generatedAlwaysAs(o){return this.config.generated={as:o,type:"always",mode:"stored"},this}buildForeignKeys(o,T){return this.foreignKeyConfigs.map(({ref:f,actions:S})=>{return Mn((n,A)=>{let $=new NA(()=>{let F=n();return{columns:[o],foreignColumns:[F]}});if(A.onUpdate)$.onUpdate(A.onUpdate);if(A.onDelete)$.onDelete(A.onDelete);return $.build(T)},f,S)})}buildExtraConfigColumn(o){return new yJ(o,this.config)}}class V extends _o{constructor(o,T){if(!T.uniqueName)T.uniqueName=OJ(o,[T.name]);super(o,T);this.table=o}static[O]="PgColumn"}class yJ extends V{static[O]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op(o){return this.indexConfig.opClass=o,this}}class YS{static[O]="IndexedColumn";constructor(o,T,f,S){this.name=o,this.keyAsName=T,this.type=f,this.indexConfig=S}name;keyAsName;type;indexConfig}class XJ extends b{static[O]="PgArrayBuilder";constructor(o,T,f){super(o,"array","PgArray");this.config.baseBuilder=T,this.config.size=f}build(o){let T=this.config.baseBuilder.build(o);return new bA(o,this.config,T)}}class bA extends V{constructor(o,T,f,S){super(o,T);this.baseColumn=f,this.range=S,this.size=T.size}size;static[O]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(o){if(typeof o==="string")o=wJ(o);return o.map((T)=>this.baseColumn.mapFromDriverValue(T))}mapToDriverValue(o,T=!1){let f=o.map((S)=>S===null?null:H(this.baseColumn,bA)?this.baseColumn.mapToDriverValue(S,!0):this.baseColumn.mapToDriverValue(S));if(T)return f;return hA(f)}}var xA=Symbol.for("drizzle:isPgEnum");function HJ(o){return!!o&&typeof o==="function"&&xA in o&&o[xA]===!0}class KJ extends b{static[O]="PgEnumColumnBuilder";constructor(o,T){super(o,"string","PgEnumColumn");this.config.enum=T}build(o){return new GJ(o,this.config)}}class GJ extends V{static[O]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(o,T){super(o,T);this.enum=T.enum}getSQLType(){return this.enum.enumName}}function Wn(o,T){return sW(o,T,void 0)}function sW(o,T,f){let S=Object.assign((n)=>new KJ(n??"",S),{enumName:o,enumValues:T,schema:f,[xA]:!0});return S}class bo{static[O]="Subquery";constructor(o,T,f,S=!1){this._={brand:"Subquery",sql:o,selectedFields:T,alias:f,isWith:S}}}class ES extends bo{static[O]="WithSubquery"}var YJ="0.39.3";var vA,qA,wo={startActiveSpan(o,T){if(!vA)return T();if(!qA)qA=vA.trace.getTracer("drizzle-orm",YJ);return Mn((f,S)=>S.startActiveSpan(o,(n)=>{try{return T(n)}catch(A){throw n.setStatus({code:f.SpanStatusCode.ERROR,message:A instanceof Error?A.message:"Unknown error"}),A}finally{n.end()}}),vA,qA)}};var Ho=Symbol.for("drizzle:ViewBaseConfig");var On=Symbol.for("drizzle:Schema"),kn=Symbol.for("drizzle:Columns"),EJ=Symbol.for("drizzle:ExtraConfigColumns"),rA=Symbol.for("drizzle:OriginalName"),ZA=Symbol.for("drizzle:BaseName"),zS=Symbol.for("drizzle:IsAlias"),zJ=Symbol.for("drizzle:ExtraConfigBuilder"),aW=Symbol.for("drizzle:IsDrizzleTable");class j{static[O]="Table";static Symbol={Name:QT,Schema:On,OriginalName:rA,Columns:kn,ExtraConfigColumns:EJ,BaseName:ZA,IsAlias:zS,ExtraConfigBuilder:zJ};[QT];[rA];[On];[kn];[EJ];[ZA];[zS]=!1;[aW]=!0;[zJ]=void 0;constructor(o,T,f){this[QT]=this[rA]=o,this[On]=T,this[ZA]=f}}function qo(o){return o[QT]}function Of(o){return`${o[On]??"public"}.${o[QT]}`}function pA(o){return o!==null&&o!==void 0&&typeof o.getSQL==="function"}function oO(o){let T={sql:"",params:[]};for(let f of o)if(T.sql+=f.sql,T.params.push(...f.params),f.typings?.length){if(!T.typings)T.typings=[];T.typings.push(...f.typings)}return T}class xo{static[O]="StringChunk";value;constructor(o){this.value=Array.isArray(o)?o:[o]}getSQL(){return new m([this])}}class m{constructor(o){this.queryChunks=o}static[O]="SQL";decoder=DJ;shouldInlineParams=!1;append(o){return this.queryChunks.push(...o.queryChunks),this}toQuery(o){return wo.startActiveSpan("drizzle.buildSQL",(T)=>{let f=this.buildQueryFromSourceParams(this.queryChunks,o);return T?.setAttributes({"drizzle.query.text":f.sql,"drizzle.query.params":JSON.stringify(f.params)}),f})}buildQueryFromSourceParams(o,T){let f=Object.assign({},T,{inlineParams:T.inlineParams||this.shouldInlineParams,paramStartIndex:T.paramStartIndex||{value:0}}),{casing:S,escapeName:n,escapeParam:A,prepareTyping:$,inlineParams:F,paramStartIndex:J}=f;return oO(o.map((R)=>{if(H(R,xo))return{sql:R.value.join(""),params:[]};if(H(R,_n))return{sql:n(R.value),params:[]};if(R===void 0)return{sql:"",params:[]};if(Array.isArray(R)){let M=[new xo("(")];for(let[_,w]of R.entries())if(M.push(w),_<R.length-1)M.push(new xo(", "));return M.push(new xo(")")),this.buildQueryFromSourceParams(M,f)}if(H(R,m))return this.buildQueryFromSourceParams(R.queryChunks,{...f,inlineParams:F||R.shouldInlineParams});if(H(R,j)){let M=R[j.Symbol.Schema],_=R[j.Symbol.Name];return{sql:M===void 0||R[zS]?n(_):n(M)+"."+n(_),params:[]}}if(H(R,_o)){let M=S.getColumnCasing(R);if(T.invokeSource==="indexes")return{sql:n(M),params:[]};let _=R.table[j.Symbol.Schema];return{sql:R.table[zS]||_===void 0?n(R.table[j.Symbol.Name])+"."+n(M):n(_)+"."+n(R.table[j.Symbol.Name])+"."+n(M),params:[]}}if(H(R,nT)){let M=R[Ho].schema,_=R[Ho].name;return{sql:M===void 0||R[Ho].isAlias?n(_):n(M)+"."+n(_),params:[]}}if(H(R,RT)){if(H(R.value,uT))return{sql:A(J.value++,R),params:[R],typings:["none"]};let M=R.value===null?null:R.encoder.mapToDriverValue(R.value);if(H(M,m))return this.buildQueryFromSourceParams([M],f);if(F)return{sql:this.mapInlineParam(M,f),params:[]};let _=["none"];if($)_=[$(R.encoder)];return{sql:A(J.value++,M),params:[M],typings:_}}if(H(R,uT))return{sql:A(J.value++,R),params:[R],typings:["none"]};if(H(R,m.Aliased)&&R.fieldAlias!==void 0)return{sql:n(R.fieldAlias),params:[]};if(H(R,bo)){if(R._.isWith)return{sql:n(R._.alias),params:[]};return this.buildQueryFromSourceParams([new xo("("),R._.sql,new xo(") "),new _n(R._.alias)],f)}if(HJ(R)){if(R.schema)return{sql:n(R.schema)+"."+n(R.enumName),params:[]};return{sql:n(R.enumName),params:[]}}if(pA(R)){if(R.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([R.getSQL()],f);return this.buildQueryFromSourceParams([new xo("("),R.getSQL(),new xo(")")],f)}if(F)return{sql:this.mapInlineParam(R,f),params:[]};return{sql:A(J.value++,R),params:[R],typings:["none"]}}))}mapInlineParam(o,{escapeString:T}){if(o===null)return"null";if(typeof o==="number"||typeof o==="boolean")return o.toString();if(typeof o==="string")return T(o);if(typeof o==="object"){let f=o.toString();if(f==="[object Object]")return T(JSON.stringify(o));return T(f)}throw new Error("Unexpected param value: "+o)}getSQL(){return this}as(o){if(o===void 0)return this;return new m.Aliased(this,o)}mapWith(o){return this.decoder=typeof o==="function"?{mapFromDriverValue:o}:o,this}inlineParams(){return this.shouldInlineParams=!0,this}if(o){return o?this:void 0}}class _n{constructor(o){this.value=o}static[O]="Name";brand;getSQL(){return new m([this])}}function QJ(o){return typeof o==="object"&&o!==null&&"mapToDriverValue"in o&&typeof o.mapToDriverValue==="function"}var DJ={mapFromDriverValue:(o)=>o},UJ={mapToDriverValue:(o)=>o},e6={...DJ,...UJ};class RT{constructor(o,T=UJ){this.value=o,this.encoder=T}static[O]="Param";brand;getSQL(){return new m([this])}}function k(o,...T){let f=[];if(T.length>0||o.length>0&&o[0]!=="")f.push(new xo(o[0]));for(let[S,n]of T.entries())f.push(n,new xo(o[S+1]));return new m(f)}((o)=>{function T(){return new m([])}o.empty=T;function f(J){return new m(J)}o.fromList=f;function S(J){return new m([new xo(J)])}o.raw=S;function n(J,R){let M=[];for(let[_,w]of J.entries()){if(_>0&&R!==void 0)M.push(R);M.push(w)}return new m(M)}o.join=n;function A(J){return new _n(J)}o.identifier=A;function $(J){return new uT(J)}o.placeholder=$;function F(J,R){return new RT(J,R)}o.param=F})(k||(k={}));((o)=>{class T{constructor(f,S){this.sql=f,this.fieldAlias=S}static[O]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new T(this.sql,this.fieldAlias)}}o.Aliased=T})(m||(m={}));class uT{constructor(o){this.name=o}static[O]="Placeholder";getSQL(){return new m([this])}}function cA(o,T){return o.map((f)=>{if(H(f,uT)){if(!(f.name in T))throw new Error(`No value for placeholder "${f.name}" was provided`);return T[f.name]}if(H(f,RT)&&H(f.value,uT)){if(!(f.value.name in T))throw new Error(`No value for placeholder "${f.value.name}" was provided`);return f.encoder.mapToDriverValue(T[f.value.name])}return f})}var TO=Symbol.for("drizzle:IsDrizzleView");class nT{static[O]="View";[Ho];[TO]=!0;constructor({name:o,schema:T,selectedFields:f,query:S}){this[Ho]={name:o,originalName:o,schema:T,selectedFields:f,query:S,isExisting:!S,isAlias:!1}}getSQL(){return new m([this])}}_o.prototype.getSQL=function(){return new m([this])};j.prototype.getSQL=function(){return new m([this])};bo.prototype.getSQL=function(){return new m([this])};class cf{constructor(o){this.table=o}static[O]="ColumnAliasProxyHandler";get(o,T){if(T==="table")return this.table;return o[T]}}class QS{constructor(o,T){this.alias=o,this.replaceOriginalName=T}static[O]="TableAliasProxyHandler";get(o,T){if(T===j.Symbol.IsAlias)return!0;if(T===j.Symbol.Name)return this.alias;if(this.replaceOriginalName&&T===j.Symbol.OriginalName)return this.alias;if(T===Ho)return{...o[Ho],name:this.alias,isAlias:!0};if(T===j.Symbol.Columns){let S=o[j.Symbol.Columns];if(!S)return S;let n={};return Object.keys(S).map((A)=>{n[A]=new Proxy(S[A],new cf(new Proxy(o,this)))}),n}let f=o[T];if(H(f,_o))return new Proxy(f,new cf(new Proxy(o,this)));return f}}function wn(o,T){return new Proxy(o,new QS(T,!1))}function CT(o,T){return new Proxy(o,new cf(new Proxy(o.table,new QS(T,!1))))}function PA(o,T){return new m.Aliased(DS(o.sql,T),o.fieldAlias)}function DS(o,T){return k.join(o.queryChunks.map((f)=>{if(H(f,_o))return CT(f,T);if(H(f,m))return DS(f,T);if(H(f,m.Aliased))return PA(f,T);return f}))}class yn extends Error{static[O]="DrizzleError";constructor({message:o,cause:T}){super(o);this.name="DrizzleError",this.cause=T}}class iA extends yn{static[O]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}function AT(o,T){if(QJ(T)&&!pA(o)&&!H(o,RT)&&!H(o,uT)&&!H(o,_o)&&!H(o,j)&&!H(o,nT))return new RT(o,T);return o}var Xn=(o,T)=>{return k`${o} = ${AT(T,o)}`},tJ=(o,T)=>{return k`${o} <> ${AT(T,o)}`};function US(...o){let T=o.filter((f)=>f!==void 0);if(T.length===0)return;if(T.length===1)return new m(T);return new m([new xo("("),k.join(T,new xo(" and ")),new xo(")")])}function VJ(...o){let T=o.filter((f)=>f!==void 0);if(T.length===0)return;if(T.length===1)return new m(T);return new m([new xo("("),k.join(T,new xo(" or ")),new xo(")")])}function BJ(o){return k`not ${o}`}var LJ=(o,T)=>{return k`${o} > ${AT(T,o)}`},CJ=(o,T)=>{return k`${o} >= ${AT(T,o)}`},IJ=(o,T)=>{return k`${o} < ${AT(T,o)}`},jJ=(o,T)=>{return k`${o} <= ${AT(T,o)}`};function mJ(o,T){if(Array.isArray(T)){if(T.length===0)return k`false`;return k`${o} in ${T.map((f)=>AT(f,o))}`}return k`${o} in ${AT(T,o)}`}function NJ(o,T){if(Array.isArray(T)){if(T.length===0)return k`true`;return k`${o} not in ${T.map((f)=>AT(f,o))}`}return k`${o} not in ${AT(T,o)}`}function hJ(o){return k`${o} is null`}function bJ(o){return k`${o} is not null`}function xJ(o){return k`exists ${o}`}function vJ(o){return k`not exists ${o}`}function qJ(o,T,f){return k`${o} between ${AT(T,o)} and ${AT(f,o)}`}function rJ(o,T,f){return k`${o} not between ${AT(T,o)} and ${AT(f,o)}`}function ZJ(o,T){return k`${o} like ${T}`}function pJ(o,T){return k`${o} not like ${T}`}function cJ(o,T){return k`${o} ilike ${T}`}function PJ(o,T){return k`${o} not ilike ${T}`}function iJ(o){return k`${o} asc`}function gJ(o){return k`${o} desc`}class dJ{static[O]="ConsoleLogWriter";write(o){console.log(o)}}class gA{static[O]="DefaultLogger";writer;constructor(o){this.writer=o?.writer??new dJ}logQuery(o,T){let f=T.map((n)=>{try{return JSON.stringify(n)}catch{return String(n)}}),S=f.length?` -- params: [${f.join(", ")}]`:"";this.writer.write(`Query: ${o}${S}`)}}class dA{static[O]="NoopLogger";logQuery(){}}class oT{static[O]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(o){return this.then(void 0,o)}finally(o){return this.then((T)=>{return o?.(),T},(T)=>{throw o?.(),T})}then(o,T){return this.execute().then(o,T)}}function lJ(o,T,f){let S={},n=o.reduce((A,{path:$,field:F},J)=>{let R;if(H(F,_o))R=F;else if(H(F,m))R=F.decoder;else R=F.sql.decoder;let M=A;for(let[_,w]of $.entries())if(_<$.length-1){if(!(w in M))M[w]={};M=M[w]}else{let X=T[J],U=M[w]=X===null?null:R.mapFromDriverValue(X);if(f&&H(F,_o)&&$.length===2){let K=$[0];if(!(K in S))S[K]=U===null?qo(F.table):!1;else if(typeof S[K]==="string"&&S[K]!==qo(F.table))S[K]=!1}}return A},{});if(f&&Object.keys(S).length>0){for(let[A,$]of Object.entries(S))if(typeof $==="string"&&!f[$])n[A]=null}return n}function wT(o,T){return Object.entries(o).reduce((f,[S,n])=>{if(typeof S!=="string")return f;let A=T?[...T,S]:[S];if(H(n,_o)||H(n,m)||H(n,m.Aliased))f.push({path:A,field:n});else if(H(n,j))f.push(...wT(n[j.Symbol.Columns],A));else f.push(...wT(n,A));return f},[])}function tS(o,T){let f=Object.keys(o),S=Object.keys(T);if(f.length!==S.length)return!1;for(let[n,A]of f.entries())if(A!==S[n])return!1;return!0}function Hn(o,T){let f=Object.entries(T).filter(([,S])=>S!==void 0).map(([S,n])=>{if(H(n,m)||H(n,_o))return[S,n];else return[S,new RT(n,o[j.Symbol.Columns][S])]});if(f.length===0)throw new Error("No values to set");return Object.fromEntries(f)}function uJ(o,T){for(let f of T)for(let S of Object.getOwnPropertyNames(f.prototype)){if(S==="constructor")continue;Object.defineProperty(o.prototype,S,Object.getOwnPropertyDescriptor(f.prototype,S)||Object.create(null))}}function eJ(o){return o[j.Symbol.Columns]}function rT(o){return H(o,bo)?o._.alias:H(o,nT)?o[Ho].name:H(o,m)?void 0:o[j.Symbol.IsAlias]?o[j.Symbol.Name]:o[j.Symbol.BaseName]}function no(o,T){return{name:typeof o==="string"&&o.length>0?o:"",config:typeof o==="object"?o:T}}function sJ(o){if(typeof o!=="object"||o===null)return!1;if(o.constructor.name!=="Object")return!1;if("logger"in o){let T=typeof o.logger;if(T!=="boolean"&&(T!=="object"||typeof o.logger.logQuery!=="function")&&T!=="undefined")return!1;return!0}if("schema"in o){let T=typeof o.logger;if(T!=="object"&&T!=="undefined")return!1;return!0}if("casing"in o){let T=typeof o.logger;if(T!=="string"&&T!=="undefined")return!1;return!0}if("mode"in o){if(o.mode!=="default"||o.mode!=="planetscale"||o.mode!==void 0)return!1;return!0}if("connection"in o){let T=typeof o.connection;if(T!=="string"&&T!=="object"&&T!=="undefined")return!1;return!0}if("client"in o){let T=typeof o.client;if(T!=="object"&&T!=="function"&&T!=="undefined")return!1;return!0}if(Object.keys(o).length===0)return!0;return!1}class eT extends b{static[O]="PgIntColumnBaseBuilder";generatedAlwaysAsIdentity(o){if(o){let{name:T,...f}=o;this.config.generatedIdentity={type:"always",sequenceName:T,sequenceOptions:f}}else this.config.generatedIdentity={type:"always"};return this.config.hasDefault=!0,this.config.notNull=!0,this}generatedByDefaultAsIdentity(o){if(o){let{name:T,...f}=o;this.config.generatedIdentity={type:"byDefault",sequenceName:T,sequenceOptions:f}}else this.config.generatedIdentity={type:"byDefault"};return this.config.hasDefault=!0,this.config.notNull=!0,this}}class aJ extends eT{static[O]="PgBigInt53Builder";constructor(o){super(o,"number","PgBigInt53")}build(o){return new oR(o,this.config)}}class oR extends V{static[O]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(o){if(typeof o==="number")return o;return Number(o)}}class TR extends eT{static[O]="PgBigInt64Builder";constructor(o){super(o,"bigint","PgBigInt64")}build(o){return new fR(o,this.config)}}class fR extends V{static[O]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(o){return BigInt(o)}}function SR(o,T){let{name:f,config:S}=no(o,T);if(S.mode==="number")return new aJ(f);return new TR(f)}class nR extends b{static[O]="PgBigSerial53Builder";constructor(o){super(o,"number","PgBigSerial53");this.config.hasDefault=!0,this.config.notNull=!0}build(o){return new AR(o,this.config)}}class AR extends V{static[O]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(o){if(typeof o==="number")return o;return Number(o)}}class $R extends b{static[O]="PgBigSerial64Builder";constructor(o){super(o,"bigint","PgBigSerial64");this.config.hasDefault=!0}build(o){return new FR(o,this.config)}}class FR extends V{static[O]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(o){return BigInt(o)}}function JR(o,T){let{name:f,config:S}=no(o,T);if(S.mode==="number")return new nR(f);return new $R(f)}class RR extends b{static[O]="PgBooleanBuilder";constructor(o){super(o,"boolean","PgBoolean")}build(o){return new MR(o,this.config)}}class MR extends V{static[O]="PgBoolean";getSQLType(){return"boolean"}}function VS(o){return new RR(o??"")}class WR extends b{static[O]="PgCharBuilder";constructor(o,T){super(o,"string","PgChar");this.config.length=T.length,this.config.enumValues=T.enum}build(o){return new OR(o,this.config)}}class OR extends V{static[O]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}}function kR(o,T={}){let{name:f,config:S}=no(o,T);return new WR(f,S)}class _R extends b{static[O]="PgCidrBuilder";constructor(o){super(o,"string","PgCidr")}build(o){return new wR(o,this.config)}}class wR extends V{static[O]="PgCidr";getSQLType(){return"cidr"}}function yR(o){return new _R(o??"")}class XR extends b{static[O]="PgCustomColumnBuilder";constructor(o,T,f){super(o,"custom","PgCustomColumn");this.config.fieldConfig=T,this.config.customTypeParams=f}build(o){return new HR(o,this.config)}}class HR extends V{static[O]="PgCustomColumn";sqlName;mapTo;mapFrom;constructor(o,T){super(o,T);this.sqlName=T.customTypeParams.dataType(T.fieldConfig),this.mapTo=T.customTypeParams.toDriver,this.mapFrom=T.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(o){return typeof this.mapFrom==="function"?this.mapFrom(o):o}mapToDriverValue(o){return typeof this.mapTo==="function"?this.mapTo(o):o}}function KR(o){return(T,f)=>{let{name:S,config:n}=no(T,f);return new XR(S,n,o)}}class ZT extends b{static[O]="PgDateColumnBaseBuilder";defaultNow(){return this.default(k`now()`)}}class GR extends ZT{static[O]="PgDateBuilder";constructor(o){super(o,"date","PgDate")}build(o){return new Kn(o,this.config)}}class Kn extends V{static[O]="PgDate";getSQLType(){return"date"}mapFromDriverValue(o){return new Date(o)}mapToDriverValue(o){return o.toISOString()}}class YR extends ZT{static[O]="PgDateStringBuilder";constructor(o){super(o,"string","PgDateString")}build(o){return new Gn(o,this.config)}}class Gn extends V{static[O]="PgDateString";getSQLType(){return"date"}}function ER(o,T){let{name:f,config:S}=no(o,T);if(S?.mode==="date")return new GR(f);return new YR(f)}class zR extends b{static[O]="PgDoublePrecisionBuilder";constructor(o){super(o,"number","PgDoublePrecision")}build(o){return new QR(o,this.config)}}class QR extends V{static[O]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(o){if(typeof o==="string")return Number.parseFloat(o);return o}}function DR(o){return new zR(o??"")}class UR extends b{static[O]="PgInetBuilder";constructor(o){super(o,"string","PgInet")}build(o){return new tR(o,this.config)}}class tR extends V{static[O]="PgInet";getSQLType(){return"inet"}}function VR(o){return new UR(o??"")}class BR extends eT{static[O]="PgIntegerBuilder";constructor(o){super(o,"number","PgInteger")}build(o){return new LR(o,this.config)}}class LR extends V{static[O]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(o){if(typeof o==="string")return Number.parseInt(o);return o}}function Yn(o){return new BR(o??"")}class CR extends b{static[O]="PgIntervalBuilder";constructor(o,T){super(o,"string","PgInterval");this.config.intervalConfig=T}build(o){return new IR(o,this.config)}}class IR extends V{static[O]="PgInterval";fields=this.config.intervalConfig.fields;precision=this.config.intervalConfig.precision;getSQLType(){let o=this.fields?` ${this.fields}`:"",T=this.precision?`(${this.precision})`:"";return`interval${o}${T}`}}function jR(o,T={}){let{name:f,config:S}=no(o,T);return new CR(f,S)}class mR extends b{static[O]="PgJsonBuilder";constructor(o){super(o,"json","PgJson")}build(o){return new En(o,this.config)}}class En extends V{static[O]="PgJson";constructor(o,T){super(o,T)}getSQLType(){return"json"}mapToDriverValue(o){return JSON.stringify(o)}mapFromDriverValue(o){if(typeof o==="string")try{return JSON.parse(o)}catch{return o}return o}}function NR(o){return new mR(o??"")}class hR extends b{static[O]="PgJsonbBuilder";constructor(o){super(o,"json","PgJsonb")}build(o){return new zn(o,this.config)}}class zn extends V{static[O]="PgJsonb";constructor(o,T){super(o,T)}getSQLType(){return"jsonb"}mapToDriverValue(o){return JSON.stringify(o)}mapFromDriverValue(o){if(typeof o==="string")try{return JSON.parse(o)}catch{return o}return o}}function bR(o){return new hR(o??"")}class xR extends b{static[O]="PgLineBuilder";constructor(o){super(o,"array","PgLine")}build(o){return new vR(o,this.config)}}class vR extends V{static[O]="PgLine";getSQLType(){return"line"}mapFromDriverValue(o){let[T,f,S]=o.slice(1,-1).split(",");return[Number.parseFloat(T),Number.parseFloat(f),Number.parseFloat(S)]}mapToDriverValue(o){return`{${o[0]},${o[1]},${o[2]}}`}}class qR extends b{static[O]="PgLineABCBuilder";constructor(o){super(o,"json","PgLineABC")}build(o){return new rR(o,this.config)}}class rR extends V{static[O]="PgLineABC";getSQLType(){return"line"}mapFromDriverValue(o){let[T,f,S]=o.slice(1,-1).split(",");return{a:Number.parseFloat(T),b:Number.parseFloat(f),c:Number.parseFloat(S)}}mapToDriverValue(o){return`{${o.a},${o.b},${o.c}}`}}function ZR(o,T){let{name:f,config:S}=no(o,T);if(!S?.mode||S.mode==="tuple")return new xR(f);return new qR(f)}class pR extends b{static[O]="PgMacaddrBuilder";constructor(o){super(o,"string","PgMacaddr")}build(o){return new cR(o,this.config)}}class cR extends V{static[O]="PgMacaddr";getSQLType(){return"macaddr"}}function PR(o){return new pR(o??"")}class iR extends b{static[O]="PgMacaddr8Builder";constructor(o){super(o,"string","PgMacaddr8")}build(o){return new gR(o,this.config)}}class gR extends V{static[O]="PgMacaddr8";getSQLType(){return"macaddr8"}}function dR(o){return new iR(o??"")}class lR extends b{static[O]="PgNumericBuilder";constructor(o,T,f){super(o,"string","PgNumeric");this.config.precision=T,this.config.scale=f}build(o){return new Qn(o,this.config)}}class Qn extends V{static[O]="PgNumeric";precision;scale;constructor(o,T){super(o,T);this.precision=T.precision,this.scale=T.scale}getSQLType(){if(this.precision!==void 0&&this.scale!==void 0)return`numeric(${this.precision}, ${this.scale})`;else if(this.precision===void 0)return"numeric";else return`numeric(${this.precision})`}}function uR(o,T){let{name:f,config:S}=no(o,T);return new lR(f,S?.precision,S?.scale)}class eR extends b{static[O]="PgPointTupleBuilder";constructor(o){super(o,"array","PgPointTuple")}build(o){return new sR(o,this.config)}}class sR extends V{static[O]="PgPointTuple";getSQLType(){return"point"}mapFromDriverValue(o){if(typeof o==="string"){let[T,f]=o.slice(1,-1).split(",");return[Number.parseFloat(T),Number.parseFloat(f)]}return[o.x,o.y]}mapToDriverValue(o){return`(${o[0]},${o[1]})`}}class aR extends b{static[O]="PgPointObjectBuilder";constructor(o){super(o,"json","PgPointObject")}build(o){return new o0(o,this.config)}}class o0 extends V{static[O]="PgPointObject";getSQLType(){return"point"}mapFromDriverValue(o){if(typeof o==="string"){let[T,f]=o.slice(1,-1).split(",");return{x:Number.parseFloat(T),y:Number.parseFloat(f)}}return o}mapToDriverValue(o){return`(${o.x},${o.y})`}}function T0(o,T){let{name:f,config:S}=no(o,T);if(!S?.mode||S.mode==="tuple")return new eR(f);return new aR(f)}function fO(o){let T=[];for(let f=0;f<o.length;f+=2)T.push(Number.parseInt(o.slice(f,f+2),16));return new Uint8Array(T)}function f0(o,T){let f=new ArrayBuffer(8),S=new DataView(f);for(let n=0;n<8;n++)S.setUint8(n,o[T+n]);return S.getFloat64(0,!0)}function lA(o){let T=fO(o),f=0,S=T[f];f+=1;let n=new DataView(T.buffer),A=n.getUint32(f,S===1);f+=4;let $;if(A&536870912)$=n.getUint32(f,S===1),f+=4;if((A&65535)===1){let F=f0(T,f);f+=8;let J=f0(T,f);return f+=8,[F,J]}throw new Error("Unsupported geometry type")}class S0 extends b{static[O]="PgGeometryBuilder";constructor(o){super(o,"array","PgGeometry")}build(o){return new n0(o,this.config)}}class n0 extends V{static[O]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(o){return lA(o)}mapToDriverValue(o){return`point(${o[0]} ${o[1]})`}}class A0 extends b{static[O]="PgGeometryObjectBuilder";constructor(o){super(o,"json","PgGeometryObject")}build(o){return new $0(o,this.config)}}class $0 extends V{static[O]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(o){let T=lA(o);return{x:T[0],y:T[1]}}mapToDriverValue(o){return`point(${o.x} ${o.y})`}}function F0(o,T){let{name:f,config:S}=no(o,T);if(!S?.mode||S.mode==="tuple")return new S0(f);return new A0(f)}class J0 extends b{static[O]="PgRealBuilder";constructor(o,T){super(o,"number","PgReal");this.config.length=T}build(o){return new R0(o,this.config)}}class R0 extends V{static[O]="PgReal";constructor(o,T){super(o,T)}getSQLType(){return"real"}mapFromDriverValue=(o)=>{if(typeof o==="string")return Number.parseFloat(o);return o}}function M0(o){return new J0(o??"")}class W0 extends b{static[O]="PgSerialBuilder";constructor(o){super(o,"number","PgSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(o){return new O0(o,this.config)}}class O0 extends V{static[O]="PgSerial";getSQLType(){return"serial"}}function k0(o){return new W0(o??"")}class _0 extends eT{static[O]="PgSmallIntBuilder";constructor(o){super(o,"number","PgSmallInt")}build(o){return new w0(o,this.config)}}class w0 extends V{static[O]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=(o)=>{if(typeof o==="string")return Number(o);return o}}function y0(o){return new _0(o??"")}class X0 extends b{static[O]="PgSmallSerialBuilder";constructor(o){super(o,"number","PgSmallSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(o){return new H0(o,this.config)}}class H0 extends V{static[O]="PgSmallSerial";getSQLType(){return"smallserial"}}function K0(o){return new X0(o??"")}class G0 extends b{static[O]="PgTextBuilder";constructor(o,T){super(o,"string","PgText");this.config.enumValues=T.enum}build(o){return new Y0(o,this.config)}}class Y0 extends V{static[O]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function E0(o,T={}){let{name:f,config:S}=no(o,T);return new G0(f,S)}class z0 extends ZT{constructor(o,T,f){super(o,"string","PgTime");this.withTimezone=T,this.precision=f,this.config.withTimezone=T,this.config.precision=f}static[O]="PgTimeBuilder";build(o){return new Dn(o,this.config)}}class Dn extends V{static[O]="PgTime";withTimezone;precision;constructor(o,T){super(o,T);this.withTimezone=T.withTimezone,this.precision=T.precision}getSQLType(){return`time${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function Q0(o,T={}){let{name:f,config:S}=no(o,T);return new z0(f,S.withTimezone??!1,S.precision)}class D0 extends ZT{static[O]="PgTimestampBuilder";constructor(o,T,f){super(o,"date","PgTimestamp");this.config.withTimezone=T,this.config.precision=f}build(o){return new Un(o,this.config)}}class Un extends V{static[O]="PgTimestamp";withTimezone;precision;constructor(o,T){super(o,T);this.withTimezone=T.withTimezone,this.precision=T.precision}getSQLType(){return`timestamp${this.precision===void 0?"":` (${this.precision})`}${this.withTimezone?" with time zone":""}`}mapFromDriverValue=(o)=>{return new Date(this.withTimezone?o:o+"+0000")};mapToDriverValue=(o)=>{return o.toISOString()}}class U0 extends ZT{static[O]="PgTimestampStringBuilder";constructor(o,T,f){super(o,"string","PgTimestampString");this.config.withTimezone=T,this.config.precision=f}build(o){return new tn(o,this.config)}}class tn extends V{static[O]="PgTimestampString";withTimezone;precision;constructor(o,T){super(o,T);this.withTimezone=T.withTimezone,this.precision=T.precision}getSQLType(){return`timestamp${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function DT(o,T={}){let{name:f,config:S}=no(o,T);if(S?.mode==="string")return new U0(f,S.withTimezone??!1,S.precision);return new D0(f,S?.withTimezone??!1,S?.precision)}class t0 extends b{static[O]="PgUUIDBuilder";constructor(o){super(o,"string","PgUUID")}defaultRandom(){return this.default(k`gen_random_uuid()`)}build(o){return new Vn(o,this.config)}}class Vn extends V{static[O]="PgUUID";getSQLType(){return"uuid"}}function MT(o){return new t0(o??"")}class V0 extends b{static[O]="PgVarcharBuilder";constructor(o,T){super(o,"string","PgVarchar");this.config.length=T.length,this.config.enumValues=T.enum}build(o){return new B0(o,this.config)}}class B0 extends V{static[O]="PgVarchar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"varchar":`varchar(${this.length})`}}function Zo(o,T={}){let{name:f,config:S}=no(o,T);return new V0(f,S)}class L0 extends b{static[O]="PgBinaryVectorBuilder";constructor(o,T){super(o,"string","PgBinaryVector");this.config.dimensions=T.dimensions}build(o){return new C0(o,this.config)}}class C0 extends V{static[O]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}}function I0(o,T){let{name:f,config:S}=no(o,T);return new L0(f,S)}class j0 extends b{static[O]="PgHalfVectorBuilder";constructor(o,T){super(o,"array","PgHalfVector");this.config.dimensions=T.dimensions}build(o){return new m0(o,this.config)}}class m0 extends V{static[O]="PgHalfVector";dimensions=this.config.dimensions;getSQLType(){return`halfvec(${this.dimensions})`}mapToDriverValue(o){return JSON.stringify(o)}mapFromDriverValue(o){return o.slice(1,-1).split(",").map((T)=>Number.parseFloat(T))}}function N0(o,T){let{name:f,config:S}=no(o,T);return new j0(f,S)}class h0 extends b{static[O]="PgSparseVectorBuilder";constructor(o,T){super(o,"string","PgSparseVector");this.config.dimensions=T.dimensions}build(o){return new b0(o,this.config)}}class b0 extends V{static[O]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function x0(o,T){let{name:f,config:S}=no(o,T);return new h0(f,S)}class v0 extends b{static[O]="PgVectorBuilder";constructor(o,T){super(o,"array","PgVector");this.config.dimensions=T.dimensions}build(o){return new q0(o,this.config)}}class q0 extends V{static[O]="PgVector";dimensions=this.config.dimensions;getSQLType(){return`vector(${this.dimensions})`}mapToDriverValue(o){return JSON.stringify(o)}mapFromDriverValue(o){return o.slice(1,-1).split(",").map((T)=>Number.parseFloat(T))}}function r0(o,T){let{name:f,config:S}=no(o,T);return new v0(f,S)}function Z0(){return{bigint:SR,bigserial:JR,boolean:VS,char:kR,cidr:yR,customType:KR,date:ER,doublePrecision:DR,inet:VR,integer:Yn,interval:jR,json:NR,jsonb:bR,line:ZR,macaddr:PR,macaddr8:dR,numeric:uR,point:T0,geometry:F0,real:M0,serial:k0,smallint:y0,smallserial:K0,text:E0,time:Q0,timestamp:DT,uuid:MT,varchar:Zo,bit:I0,halfvec:N0,sparsevec:x0,vector:r0}}var uA=Symbol.for("drizzle:PgInlineForeignKeys"),p0=Symbol.for("drizzle:EnableRLS");class po extends j{static[O]="PgTable";static Symbol=Object.assign({},j.Symbol,{InlineForeignKeys:uA,EnableRLS:p0});[uA]=[];[p0]=!1;[j.Symbol.ExtraConfigBuilder]=void 0}function SO(o,T,f,S,n=o){let A=new po(o,S,n),$=typeof T==="function"?T(Z0()):T,F=Object.fromEntries(Object.entries($).map(([M,_])=>{let w=_;w.setName(M);let X=w.build(A);return A[uA].push(...w.buildForeignKeys(X,A)),[M,X]})),J=Object.fromEntries(Object.entries($).map(([M,_])=>{let w=_;w.setName(M);let X=w.buildExtraConfigColumn(A);return[M,X]})),R=Object.assign(A,F);if(R[j.Symbol.Columns]=F,R[j.Symbol.ExtraConfigColumns]=J,f)R[po.Symbol.ExtraConfigBuilder]=f;return Object.assign(R,{enableRLS:()=>{return R[po.Symbol.EnableRLS]=!0,R}})}var sT=(o,T,f)=>{return SO(o,T,f,void 0)};function c0(...o){if(o[0].columns)return new BS(o[0].columns,o[0].name);return new BS(o)}class BS{static[O]="PgPrimaryKeyBuilder";columns;name;constructor(o,T){this.columns=o,this.name=T}build(o){return new P0(o,this.columns,this.name)}}class P0{constructor(o,T,f){this.table=o,this.columns=T,this.name=f}static[O]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[po.Symbol.Name]}_${this.columns.map((o)=>o.name).join("_")}_pk`}}class eA{constructor(o,T,f){this.sourceTable=o,this.referencedTable=T,this.relationName=f,this.referencedTableName=T[j.Symbol.Name]}static[O]="Relation";referencedTableName;fieldName}class i0{constructor(o,T){this.table=o,this.config=T}static[O]="Relations"}class aT extends eA{constructor(o,T,f,S){super(o,T,f?.relationName);this.config=f,this.isNullable=S}static[O]="One";withFieldName(o){let T=new aT(this.sourceTable,this.referencedTable,this.config,this.isNullable);return T.fieldName=o,T}}class LS extends eA{constructor(o,T,f){super(o,T,f?.relationName);this.config=f}static[O]="Many";withFieldName(o){let T=new LS(this.sourceTable,this.referencedTable,this.config);return T.fieldName=o,T}}function g0(){return{and:US,between:qJ,eq:Xn,exists:xJ,gt:LJ,gte:CJ,ilike:cJ,inArray:mJ,isNull:hJ,isNotNull:bJ,like:ZJ,lt:IJ,lte:jJ,ne:tJ,not:BJ,notBetween:rJ,notExists:vJ,notLike:pJ,notIlike:PJ,notInArray:NJ,or:VJ,sql:k}}function d0(){return{sql:k,asc:iJ,desc:gJ}}function l0(o,T){if(Object.keys(o).length===1&&"default"in o&&!H(o.default,j))o=o.default;let f={},S={},n={};for(let[A,$]of Object.entries(o))if(H($,j)){let F=Of($),J=S[F];f[F]=A,n[A]={tsName:A,dbName:$[j.Symbol.Name],schema:$[j.Symbol.Schema],columns:$[j.Symbol.Columns],relations:J?.relations??{},primaryKey:J?.primaryKey??[]};for(let M of Object.values($[j.Symbol.Columns]))if(M.primary)n[A].primaryKey.push(M);let R=$[j.Symbol.ExtraConfigBuilder]?.($[j.Symbol.ExtraConfigColumns]);if(R){for(let M of Object.values(R))if(H(M,BS))n[A].primaryKey.push(...M.columns)}}else if(H($,i0)){let F=Of($.table),J=f[F],R=$.config(T($.table)),M;for(let[_,w]of Object.entries(R))if(J){let X=n[J];if(X.relations[_]=w,M)X.primaryKey.push(...M)}else{if(!(F in S))S[F]={relations:{},primaryKey:M};S[F].relations[_]=w}}return{tables:n,tableNamesMap:f}}function nO(o){return function T(f,S){return new aT(o,f,S,S?.fields.reduce((n,A)=>n&&A.notNull,!0)??!1)}}function AO(o){return function T(f,S){return new LS(o,f,S)}}function u0(o,T,f){if(H(f,aT)&&f.config)return{fields:f.config.fields,references:f.config.references};let S=T[Of(f.referencedTable)];if(!S)throw new Error(`Table "${f.referencedTable[j.Symbol.Name]}" not found in schema`);let n=o[S];if(!n)throw new Error(`Table "${S}" not found in schema`);let A=f.sourceTable,$=T[Of(A)];if(!$)throw new Error(`Table "${A[j.Symbol.Name]}" not found in schema`);let F=[];for(let J of Object.values(n.relations))if(f.relationName&&f!==J&&J.relationName===f.relationName||!f.relationName&&J.referencedTable===f.sourceTable)F.push(J);if(F.length>1)throw f.relationName?new Error(`There are multiple relations with name "${f.relationName}" in table "${S}"`):new Error(`There are multiple relations between "${S}" and "${f.sourceTable[j.Symbol.Name]}". Please specify relation name`);if(F[0]&&H(F[0],aT)&&F[0].config)return{fields:F[0].config.references,references:F[0].config.fields};throw new Error(`There is not enough information to infer relation "${$}.${f.fieldName}"`)}function e0(o){return{one:nO(o),many:AO(o)}}function Bn(o,T,f,S,n=(A)=>A){let A={};for(let[$,F]of S.entries())if(F.isJson){let J=T.relations[F.tsKey],R=f[$],M=typeof R==="string"?JSON.parse(R):R;A[F.tsKey]=H(J,aT)?M&&Bn(o,o[F.relationTableTsKey],M,F.selection,n):M.map((_)=>Bn(o,o[F.relationTableTsKey],_,F.selection,n))}else{let J=n(f[$]),R=F.field,M;if(H(R,_o))M=R;else if(H(R,m))M=R.decoder;else M=R.sql.decoder;A[F.tsKey]=J===null?null:M.mapFromDriverValue(J)}return A}import BO from"os";import LO from"fs";var Ln=new Map,sA=new Map,aA=Symbol("OriginError"),Pf={};class yT extends Promise{constructor(o,T,f,S,n={}){let A,$;super((F,J)=>{A=F,$=J});this.tagged=Array.isArray(o.raw),this.strings=o,this.args=T,this.handler=f,this.canceller=S,this.options=n,this.state=null,this.statement=null,this.resolve=(F)=>(this.active=!1,A(F)),this.reject=(F)=>(this.active=!1,$(F)),this.active=!1,this.cancelled=null,this.executed=!1,this.signature="",this[aA]=this.handler.debug?new Error:this.tagged&&$O(this.strings)}get origin(){return(this.handler.debug?this[aA].stack:this.tagged&&sA.has(this.strings)?sA.get(this.strings):sA.set(this.strings,this[aA].stack).get(this.strings))||""}static get[Symbol.species](){return Promise}cancel(){return this.canceller&&(this.canceller(this),this.canceller=null)}simple(){return this.options.simple=!0,this.options.prepare=!1,this}async readable(){return this.simple(),this.streaming=!0,this}async writable(){return this.simple(),this.streaming=!0,this}cursor(o=1,T){if(this.options.simple=!1,typeof o==="function")T=o,o=1;if(this.cursorRows=o,typeof T==="function")return this.cursorFn=T,this;let f;return{[Symbol.asyncIterator]:()=>({next:()=>{if(this.executed&&!this.active)return{done:!0};f&&f();let S=new Promise((n,A)=>{this.cursorFn=($)=>{return n({value:$,done:!1}),new Promise((F)=>f=F)},this.resolve=()=>(this.active=!1,n({done:!0})),this.reject=($)=>(this.active=!1,A($))});return this.execute(),S},return(){return f&&f(Pf),{done:!0}}})}}describe(){return this.options.simple=!1,this.onlyDescribe=this.options.prepare=!0,this}stream(){throw new Error(".stream has been renamed to .forEach")}forEach(o){return this.forEachFn=o,this.handle(),this}raw(){return this.isRaw=!0,this}values(){return this.isRaw="values",this}async handle(){!this.executed&&(this.executed=!0)&&await 1&&this.handler(this)}execute(){return this.handle(),this}then(){return this.handle(),super.then.apply(this,arguments)}catch(){return this.handle(),super.catch.apply(this,arguments)}finally(){return this.handle(),super.finally.apply(this,arguments)}}function $O(o){if(Ln.has(o))return Ln.get(o);let T=Error.stackTraceLimit;return Error.stackTraceLimit=4,Ln.set(o,new Error),Error.stackTraceLimit=T,Ln.get(o)}class gf extends Error{constructor(o){super(o.message);this.name=this.constructor.name,Object.assign(this,o)}}var Bo={connection:s0,postgres:a0,generic:o1,notSupported:T1};function s0(o,T,f){let{host:S,port:n}=f||T,A=Object.assign(new Error("write "+o+" "+(T.path||S+":"+n)),{code:o,errno:o,address:T.path||S},T.path?{}:{port:n});return Error.captureStackTrace(A,s0),A}function a0(o){let T=new gf(o);return Error.captureStackTrace(T,a0),T}function o1(o,T){let f=Object.assign(new Error(o+": "+T),{code:o});return Error.captureStackTrace(f,o1),f}function T1(o){let T=Object.assign(new Error(o+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:o});return Error.captureStackTrace(T,T1),T}var FO={string:{to:25,from:null,serialize:(o)=>""+o},number:{to:0,from:[21,23,26,700,701],serialize:(o)=>""+o,parse:(o)=>+o},json:{to:114,from:[114,3802],serialize:(o)=>JSON.stringify(o),parse:(o)=>JSON.parse(o)},boolean:{to:16,from:16,serialize:(o)=>o===!0?"t":"f",parse:(o)=>o==="t"},date:{to:1184,from:[1082,1114,1184],serialize:(o)=>(o instanceof Date?o:new Date(o)).toISOString(),parse:(o)=>new Date(o)},bytea:{to:17,from:17,serialize:(o)=>"\\x"+Buffer.from(o).toString("hex"),parse:(o)=>Buffer.from(o.slice(2),"hex")}};class jn{then(){o$()}catch(){o$()}finally(){o$()}}class mS extends jn{constructor(o){super();this.value=hn(o)}}class IT extends jn{constructor(o,T,f){super();this.value=o,this.type=T,this.array=f}}class mn extends jn{constructor(o,T){super();this.first=o,this.rest=T}build(o,T,f,S){let n=JO.map(([A,$])=>({fn:$,i:o.search(A)})).sort((A,$)=>A.i-$.i).pop();return n.i===-1?A$(this.first,S):n.fn(this.first,this.rest,T,f,S)}}function Nn(o,T,f,S){let n=o instanceof IT?o.value:o;if(n===void 0){if(o instanceof IT?o.value=S.transform.undefined:n=o=S.transform.undefined,n===void 0)throw Bo.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return"$"+f.push(o instanceof IT?(T.push(o.value),o.array?o.array[o.type||In(o.value)]||o.type||A1(o.value):o.type):(T.push(o),In(o)))}var S1=F1(FO);function S$(o,T,f,S,n,A){for(let $=1;$<o.strings.length;$++)T+=n$(T,f,S,n,A)+o.strings[$],f=o.args[$];return T}function n$(o,T,f,S,n){return T instanceof mn?T.build(o,f,S,n):T instanceof yT?f$(T,f,S,n):T instanceof mS?T.value:T&&T[0]instanceof yT?T.reduce((A,$)=>A+" "+f$($,f,S,n),""):Nn(T,f,S,n)}function f$(o,T,f,S){return o.fragment=!0,S$(o,o.strings[0],o.args[0],T,f,S)}function n1(o,T,f,S,n){return o.map((A)=>"("+S.map(($)=>n$("values",A[$],T,f,n)).join(",")+")").join(",")}function f1(o,T,f,S,n){let A=Array.isArray(o[0]),$=T.length?T.flat():Object.keys(A?o[0]:o);return n1(A?o:[o],f,S,$,n)}function Cn(o,T,f,S,n){if(typeof o==="string"&&(o=[o].concat(T)),Array.isArray(o))return A$(o,n);let A;return(T.length?T.flat():Object.keys(o)).map((F)=>{return A=o[F],(A instanceof yT?f$(A,f,S,n):A instanceof mS?A.value:Nn(A,f,S,n))+" as "+hn(n.transform.column.to?n.transform.column.to(F):F)}).join(",")}var JO=Object.entries({values:f1,in:(...o)=>{let T=f1(...o);return T==="()"?"(null)":T},select:Cn,as:Cn,returning:Cn,"\\(":Cn,update(o,T,f,S,n){return(T.length?T.flat():Object.keys(o)).map((A)=>hn(n.transform.column.to?n.transform.column.to(A):A)+"="+n$("values",o[A],f,S,n))},insert(o,T,f,S,n){let A=T.length?T.flat():Object.keys(Array.isArray(o)?o[0]:o);return"("+A$(A,n)+")values"+n1(Array.isArray(o)?o:[o],f,S,A,n)}}).map(([o,T])=>[new RegExp("((?:^|[\\s(])"+o+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),T]);function o$(){throw Bo.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}var{serializers:RO,parsers:MO}=S1;function A1(o){if(Array.isArray(o))return A1(o[0]);return typeof o==="string"?1009:0}var $1=function(o){let T=F1(o||{});return{serializers:Object.assign({},RO,T.serializers),parsers:Object.assign({},MO,T.parsers)}};function F1(o){return Object.keys(o).reduce((T,f)=>{if(o[f].from&&[].concat(o[f].from).forEach((S)=>T.parsers[S]=o[f].parse),o[f].serialize)T.serializers[o[f].to]=o[f].serialize,o[f].from&&[].concat(o[f].from).forEach((S)=>T.serializers[S]=o[f].serialize);return T},{parsers:{},serializers:{}})}function A$(o,{transform:{column:T}}){return o.map((f)=>hn(T.to?T.to(f):f)).join(",")}var hn=function o(T){return'"'+T.replace(/"/g,'""').replace(/\./g,'"."')+'"'},In=function o(T){return T instanceof IT?T.type:T instanceof Date?1184:T instanceof Uint8Array?17:T===!0||T===!1?16:typeof T==="bigint"?20:Array.isArray(T)?o(T[0]):0},WO=/\\/g,OO=/"/g;function kO(o){return o.replace(WO,"\\\\").replace(OO,"\\\"")}var J1=function o(T,f,S,n){if(Array.isArray(T)===!1)return T;if(!T.length)return"{}";let A=T[0],$=n===1020?";":",";if(Array.isArray(A)&&!A.type)return"{"+T.map((F)=>o(F,f,S,n)).join($)+"}";return"{"+T.map((F)=>{if(F===void 0){if(F=S.transform.undefined,F===void 0)throw Bo.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return F===null?"null":'"'+kO(f?f(F.type?F.value:F):""+F)+'"'}).join($)+"}"},T$={i:0,char:null,str:"",quoted:!1,last:0},R1=function o(T,f,S){return T$.i=T$.last=0,M1(T$,T,f,S)};function M1(o,T,f,S){let n=[],A=S===1020?";":",";for(;o.i<T.length;o.i++){if(o.char=T[o.i],o.quoted)if(o.char==="\\")o.str+=T[++o.i];else if(o.char==='"')n.push(f?f(o.str):o.str),o.str="",o.quoted=T[o.i+1]==='"',o.last=o.i+2;else o.str+=o.char;else if(o.char==='"')o.quoted=!0;else if(o.char==="{")o.last=++o.i,n.push(M1(o,T,f,S));else if(o.char==="}"){o.quoted=!1,o.last<o.i&&n.push(f?f(T.slice(o.last,o.i)):T.slice(o.last,o.i)),o.last=o.i+1;break}else if(o.char===A&&o.p!=="}"&&o.p!=='"')n.push(f?f(T.slice(o.last,o.i)):T.slice(o.last,o.i)),o.last=o.i+1;o.p=o.char}return o.last<o.i&&n.push(f?f(T.slice(o.last,o.i+1)):T.slice(o.last,o.i+1)),n}var kf=(o)=>{let T=o[0];for(let f=1;f<o.length;f++)T+=o[f]==="_"?o[++f].toUpperCase():o[f];return T},_f=(o)=>{let T=o[0].toUpperCase();for(let f=1;f<o.length;f++)T+=o[f]==="_"?o[++f].toUpperCase():o[f];return T},wf=(o)=>o.replace(/_/g,"-"),CS=(o)=>o.replace(/([A-Z])/g,"_$1").toLowerCase(),IS=(o)=>(o.slice(0,1)+o.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),jS=(o)=>o.replace(/-/g,"_");function $$(o){return function T(f,S){return typeof f==="object"&&f!==null&&(S.type===114||S.type===3802)?Array.isArray(f)?f.map((n)=>T(n,S)):Object.entries(f).reduce((n,[A,$])=>Object.assign(n,{[o(A)]:T($,S)}),{}):f}}kf.column={from:kf};kf.value={from:$$(kf)};CS.column={to:CS};var F$={...kf};F$.column.to=CS;_f.column={from:_f};_f.value={from:$$(_f)};IS.column={to:IS};var J$={..._f};J$.column.to=IS;wf.column={from:wf};wf.value={from:$$(wf)};jS.column={to:jS};var R$={...wf};R$.column.to=jS;import W1 from"net";import XO from"tls";import NS from"crypto";import M$ from"stream";import{performance as O1}from"perf_hooks";class yf extends Array{constructor(){super();Object.defineProperties(this,{count:{value:null,writable:!0},state:{value:null,writable:!0},command:{value:null,writable:!0},columns:{value:null,writable:!0},statement:{value:null,writable:!0}})}static get[Symbol.species](){return Array}}var WT=_O;function _O(o=[]){let T=o.slice(),f=0;return{get length(){return T.length-f},remove:(S)=>{let n=T.indexOf(S);return n===-1?null:(T.splice(n,1),S)},push:(S)=>(T.push(S),S),shift:()=>{let S=T[f++];if(f===T.length)f=0,T=[];else T[f-1]=void 0;return S}}}var eo=Buffer.allocUnsafe(256),wO="BCcDdEFfHPpQSX".split("").reduce((o,T)=>{let f=T.charCodeAt(0);return o[T]=()=>{return eo[0]=f,Oo.i=5,Oo},o},{}),Oo=Object.assign(yO,wO,{N:String.fromCharCode(0),i:0,inc(o){return Oo.i+=o,Oo},str(o){let T=Buffer.byteLength(o);return bn(T),Oo.i+=eo.write(o,Oo.i,T,"utf8"),Oo},i16(o){return bn(2),eo.writeUInt16BE(o,Oo.i),Oo.i+=2,Oo},i32(o,T){if(T||T===0)return eo.writeUInt32BE(o,T),Oo;return bn(4),eo.writeUInt32BE(o,Oo.i),Oo.i+=4,Oo},z(o){return bn(o),eo.fill(0,Oo.i,Oo.i+o),Oo.i+=o,Oo},raw(o){return eo=Buffer.concat([eo.subarray(0,Oo.i),o]),Oo.i=eo.length,Oo},end(o=1){eo.writeUInt32BE(Oo.i-o,o);let T=eo.subarray(0,Oo.i);return Oo.i=0,eo=Buffer.allocUnsafe(256),T}}),p=Oo;function bn(o){if(eo.length-Oo.i<o){let T=eo,f=T.length;eo=Buffer.allocUnsafe(f+(f>>1)+o),T.copy(eo)}}function yO(){return Oo.i=0,Oo}var k$=w1,HO=1,of=p().S().end(),k1=p().H().end(),KO=p().i32(8).i32(80877103).end(8),GO=Buffer.concat([p().E().str(p.N).i32(0).end(),of]),YO=p().D().str("S").str(p.N).end(),df=()=>{},EO=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),zO={83:"severity_local",86:"severity",67:"code",77:"message",68:"detail",72:"hint",80:"position",112:"internal_position",113:"internal_query",87:"where",115:"schema_name",116:"table_name",99:"column_name",100:"data type_name",110:"constraint_name",70:"file",76:"line",82:"routine"};function w1(o,T={},{onopen:f=df,onend:S=df,onclose:n=df}={}){let{ssl:A,max:$,user:F,host:J,port:R,database:M,parsers:_,transform:w,onnotice:X,onnotify:U,onparameter:K,max_pipeline:L,keep_alive:h,backoff:q,target_session_attrs:P}=o,Y=WT(),Q=HO++,t={pid:null,secret:null},D=O$(en,o.idle_timeout),v=O$(en,o.max_lifetime),l=O$(b1,o.connect_timeout),G=null,s,r=new yf,a=Buffer.alloc(0),ko=o.fetch_types,Lo={},fT={},jT=Math.random().toString(36).slice(2),E=1,Z=0,Fo=0,Eo=0,Co=0,To=0,yo=0,Vo=0,zo=null,Ko=null,co=!1,Xo=null,XT=null,Po=null,pT=null,Io=null,Go=null,HT=null,UT=null,B=null,sf=null,io={queue:T.closed,idleTimer:D,connect(W){Po=W||!0,q$()},terminate:oS,execute:af,cancel:j1,end:en,count:0,id:Q};return T.closed&&T.closed.push(io),io;async function I1(){let W;try{W=o.socket?await Promise.resolve(o.socket(o)):new W1.Socket}catch(y){Gf(y);return}return W.on("error",Gf),W.on("close",r$),W.on("drain",x$),W}async function j1({pid:W,secret:y},c,Jo){try{s=p().i32(16).i32(80877102).i32(W).i32(y).end(16),await v$(),G.once("error",Jo),G.once("close",c)}catch(Do){Jo(Do)}}function af(W){if(co)return ZS(W,Bo.connection("CONNECTION_DESTROYED",o));if(W.cancelled)return;try{return W.state=t,B?Y.push(W):(B=W,B.active=!0),h1(W),ro(m1(W))&&!W.describeFirst&&!W.cursorFn&&Y.length<L&&(!W.options.onexecute||W.options.onexecute(io))}catch(y){return Y.length===0&&ro(of),tT(y),!0}}function m1(W){if(W.parameters.length>=65534)throw Bo.generic("MAX_PARAMETERS_EXCEEDED","Max number of parameters (65534) exceeded");return W.options.simple?p().Q().str(W.statement.string+p.N).end():W.describeFirst?Buffer.concat([N$(W),k1]):W.prepare?W.prepared?rS(W):Buffer.concat([N$(W),rS(W)]):N1(W)}function N$(W){return Buffer.concat([p$(W.statement.string,W.parameters,W.statement.types,W.statement.name),YM("S",W.statement.name)])}function rS(W){return Buffer.concat([GM(W.parameters,W.statement.types,W.statement.name,W.cursorName),W.cursorFn?c$("",W.cursorRows):GO])}function N1(W){return Buffer.concat([p$(W.statement.string,W.parameters,W.statement.types),YO,rS(W)])}function h1(W){let y=[],c=[],Jo=S$(W,W.strings[0],W.args[0],y,c,o);!W.tagged&&W.args.forEach((Do)=>Nn(Do,y,c,o)),W.prepare=o.prepare&&("prepare"in W.options?W.options.prepare:!0),W.string=Jo,W.signature=W.prepare&&c+Jo,W.onlyDescribe&&delete fT[W.signature],W.parameters=W.parameters||y,W.prepared=W.prepare&&W.signature in fT,W.describeFirst=W.onlyDescribe||y.length&&!W.prepared,W.statement=W.prepared?fT[W.signature]:{string:Jo,types:c,name:W.prepare?jT+E++:""},typeof o.debug==="function"&&o.debug(Q,Jo,y,c)}function ro(W,y){if(Go=Go?Buffer.concat([Go,W]):Buffer.from(W),y||Go.length>=1024)return h$(y);return Ko===null&&(Ko=setImmediate(h$)),!0}function h$(W){let y=G.write(Go,W);return Ko!==null&&clearImmediate(Ko),Go=Ko=null,y}function b1(){tT(Bo.connection("CONNECT_TIMEOUT",o,G)),G.destroy()}async function b$(){if(ro(KO),!await new Promise((y)=>G.once("data",(c)=>y(c[0]===83)))&&A==="prefer")return Kf();G.removeAllListeners(),G=XO.connect({socket:G,servername:W1.isIP(G.host)?void 0:G.host,...A==="require"||A==="allow"||A==="prefer"?{rejectUnauthorized:!1}:A==="verify-full"?{}:typeof A==="object"?A:{}}),G.on("secureConnect",Kf),G.on("error",Gf),G.on("close",r$),G.on("drain",x$)}function x$(){!B&&f(io)}function un(W){if(Xo){if(Xo.push(W),Fo-=W.length,Fo>=0)return}a=Xo?Buffer.concat(Xo,To-Fo):a.length===0?W:Buffer.concat([a,W],a.length+W.length);while(a.length>4){if(To=a.readUInt32BE(1),To>=a.length){Fo=To-a.length,Xo=[a];break}try{x1(a.subarray(0,To+1))}catch(y){B&&(B.cursorFn||B.describeFirst)&&ro(of),tT(y)}a=a.subarray(To+1),Fo=0,Xo=null}}async function v$(){if(co=!1,Lo={},G||(G=await I1()),!G)return;if(l.start(),o.socket)return A?b$():Kf();if(G.on("connect",A?b$:Kf),o.path)return G.connect(o.path);G.ssl=A,G.connect(R[Eo],J[Eo]),G.host=J[Eo],G.port=R[Eo],Eo=(Eo+1)%R.length}function q$(){setTimeout(v$,Z?Z+yo-O1.now():0)}function Kf(){try{fT={},ko=o.fetch_types,jT=Math.random().toString(36).slice(2),E=1,v.start(),G.on("data",un),h&&G.setKeepAlive&&G.setKeepAlive(!0,1000*h);let W=zM();ro(W)}catch(W){Gf(W)}}function Gf(W){if(io.queue===T.connecting&&o.host[Co+1])return;tT(W);while(Y.length)ZS(Y.shift(),W)}function tT(W){Io&&(Io.destroy(W),Io=null),B&&ZS(B,W),Po&&(ZS(Po,W),Po=null)}function ZS(W,y){"query"in y||"parameters"in y||Object.defineProperties(y,{stack:{value:y.stack+W.origin.replace(/.*\n/,`
17
+ `),enumerable:o.debug},query:{value:W.string,enumerable:o.debug},parameters:{value:W.parameters,enumerable:o.debug},args:{value:W.args,enumerable:o.debug},types:{value:W.statement&&W.statement.types,enumerable:o.debug}}),W.reject(y)}function en(){return pT||(!io.reserved&&S(io),!io.reserved&&!Po&&!B&&Y.length===0?(oS(),new Promise((W)=>G&&G.readyState!=="closed"?G.once("close",W):W())):pT=new Promise((W)=>HT=W))}function oS(){if(co=!0,Io||B||Po||Y.length)Gf(Bo.connection("CONNECTION_DESTROYED",o));if(clearImmediate(Ko),G)G.removeListener("data",un),G.removeListener("connect",Kf),G.readyState==="open"&&G.end(p().X().end());HT&&(HT(),pT=HT=null)}async function r$(W){if(a=Buffer.alloc(0),Fo=0,Xo=null,clearImmediate(Ko),G.removeListener("data",un),G.removeListener("connect",Kf),D.cancel(),v.cancel(),l.cancel(),G.removeAllListeners(),G=null,Po)return q$();!W&&(B||Y.length)&&Gf(Bo.connection("CONNECTION_CLOSED",o,G)),Z=O1.now(),W&&o.shared.retries++,yo=(typeof q==="function"?q(o.shared.retries):q)*1000,n(io,Bo.connection("CONNECTION_CLOSED",o,G))}function x1(W,y=W[0]){(y===68?v1:y===100?OM:y===65?$M:y===83?q1:y===90?r1:y===67?Z1:y===50?Z$:y===49?p1:y===116?c1:y===84?P1:y===82?i1:y===110?s1:y===75?a1:y===69?nM:y===115?FM:y===51?JM:y===71?RM:y===78?_M:y===72?MM:y===99?kM:y===73?wM:y===86?yM:y===118?XM:y===87?WM:HM)(W)}function v1(W){let y=7,c,Jo,Do,go=B.isRaw?new Array(B.statement.columns.length):{};for(let so=0;so<B.statement.columns.length;so++)Jo=B.statement.columns[so],c=W.readInt32BE(y),y+=4,Do=c===-1?null:B.isRaw===!0?W.subarray(y,y+=c):Jo.parser===void 0?W.toString("utf8",y,y+=c):Jo.parser.array===!0?Jo.parser(W.toString("utf8",y+1,y+=c)):Jo.parser(W.toString("utf8",y,y+=c)),B.isRaw?go[so]=B.isRaw===!0?Do:w.value.from?w.value.from(Do,Jo):Do:go[Jo.name]=w.value.from?w.value.from(Do,Jo):Do;B.forEachFn?B.forEachFn(w.row.from?w.row.from(go):go,r):r[Vo++]=w.row.from?w.row.from(go):go}function q1(W){let[y,c]=W.toString("utf8",5,W.length-1).split(p.N);if(Lo[y]=c,o.parameters[y]!==c)o.parameters[y]=c,K&&K(y,c)}function r1(W){if(B&&B.options.simple&&B.resolve(XT||r),B=XT=null,r=new yf,l.cancel(),Po){if(P){if(!Lo.in_hot_standby||!Lo.default_transaction_read_only)return SM();else if(fM(P,Lo))return oS()}if(ko)return Po===!0&&(Po=null),oM();Po!==!0&&af(Po),o.shared.retries=Co=0,Po=null;return}while(Y.length&&(B=Y.shift())&&(B.active=!0,B.cancelled))w1(o).cancel(B.state,B.cancelled.resolve,B.cancelled.reject);if(B)return;io.reserved?!io.reserved.release&&W[5]===73?pT?oS():(io.reserved=null,f(io)):io.reserved():pT?oS():f(io)}function Z1(W){Vo=0;for(let y=W.length-1;y>0;y--){if(W[y]===32&&W[y+1]<58&&r.count===null)r.count=+W.toString("utf8",y+1,W.length-1);if(W[y-1]>=65){r.command=W.toString("utf8",5,y),r.state=t;break}}if(sf&&(sf(),sf=null),r.command==="BEGIN"&&$!==1&&!io.reserved)return tT(Bo.generic("UNSAFE_TRANSACTION","Only use sql.begin, sql.reserved or max: 1"));if(B.options.simple)return Z$();if(B.cursorFn)r.count&&B.cursorFn(r),ro(of);B.resolve(r)}function p1(){B.parsing=!1}function Z$(){!r.statement&&(r.statement=B.statement),r.columns=B.statement.columns}function c1(W){let y=W.readUInt16BE(5);for(let c=0;c<y;++c)!B.statement.types[c]&&(B.statement.types[c]=W.readUInt32BE(7+c*4));B.prepare&&(fT[B.signature]=B.statement),B.describeFirst&&!B.onlyDescribe&&(ro(rS(B)),B.describeFirst=!1)}function P1(W){if(r.command)XT=XT||[r],XT.push(r=new yf),r.count=null,B.statement.columns=null;let y=W.readUInt16BE(5),c=7,Jo;B.statement.columns=Array(y);for(let Do=0;Do<y;++Do){Jo=c;while(W[c++]!==0);let go=W.readUInt32BE(c),so=W.readUInt16BE(c+4),cT=W.readUInt32BE(c+6);B.statement.columns[Do]={name:w.column.from?w.column.from(W.toString("utf8",Jo,c-1)):W.toString("utf8",Jo,c-1),parser:_[cT],table:go,number:so,type:cT},c+=18}if(r.statement=B.statement,B.onlyDescribe)return B.resolve(B.statement),ro(of)}async function i1(W,y=W.readUInt32BE(5)){(y===3?g1:y===5?d1:y===10?l1:y===11?u1:y===12?e1:y!==0?KM:df)(W,y)}async function g1(){let W=await sn();ro(p().p().str(W).z(1).end())}async function d1(W){let y="md5"+await _1(Buffer.concat([Buffer.from(await _1(await sn()+F)),W.subarray(9)]));ro(p().p().str(y).z(1).end())}async function l1(){UT=(await NS.randomBytes(18)).toString("base64"),p().p().str("SCRAM-SHA-256"+p.N);let W=p.i;ro(p.inc(4).str("n,,n=*,r="+UT).i32(p.i-W-4,W).end())}async function u1(W){let y=W.toString("utf8",9).split(",").reduce((so,cT)=>(so[cT[0]]=cT.slice(2),so),{}),c=await NS.pbkdf2Sync(await sn(),Buffer.from(y.s,"base64"),parseInt(y.i),32,"sha256"),Jo=await xn(c,"Client Key"),Do="n=*,r="+UT+",r="+y.r+",s="+y.s+",i="+y.i+",c=biws,r="+y.r;zo=(await xn(await xn(c,"Server Key"),Do)).toString("base64");let go="c=biws,r="+y.r+",p="+DO(Jo,Buffer.from(await xn(await QO(Jo),Do))).toString("base64");ro(p().p().str(go).end())}function e1(W){if(W.toString("utf8",9).split(p.N,1)[0].slice(2)===zo)return;tT(Bo.generic("SASL_SIGNATURE_MISMATCH","The server did not return the correct signature")),G.destroy()}function sn(){return Promise.resolve(typeof o.pass==="function"?o.pass():o.pass)}function s1(){if(r.statement=B.statement,r.statement.columns=[],B.onlyDescribe)return B.resolve(B.statement),ro(of)}function a1(W){t.pid=W.readUInt32BE(5),t.secret=W.readUInt32BE(9)}async function oM(){ko=!1,(await new yT([`
18
18
  select b.oid, b.typarray
19
19
  from pg_catalog.pg_type a
20
20
  left join pg_catalog.pg_type b on b.oid = a.typelem
21
21
  where a.typcategory = 'A'
22
22
  group by b.oid, b.typarray
23
23
  order by b.oid
24
- `],[],eS)).forEach(({oid:w,typarray:P})=>s1(w,P))}function s1(O,w){if(!!T.parsers[w]&&!!T.serializers[w])return;let P=T.parsers[O];T.shared.typeArrayMap[O]=w,T.parsers[w]=(JT)=>F1(JT,P,w),T.parsers[w].array=!0,T.serializers[w]=(JT)=>$1(JT,T.serializers[O],T,w)}function TW(O,w){return O==="read-write"&&w.default_transaction_read_only==="on"||O==="read-only"&&w.default_transaction_read_only==="off"||O==="primary"&&w.in_hot_standby==="on"||O==="standby"&&w.in_hot_standby==="off"||O==="prefer-standby"&&w.in_hot_standby==="off"&&T.host[IT]}function oW(){let O=new wo([`
24
+ `],[],af)).forEach(({oid:y,typarray:c})=>TM(y,c))}function TM(W,y){if(!!o.parsers[y]&&!!o.serializers[y])return;let c=o.parsers[W];o.shared.typeArrayMap[W]=y,o.parsers[y]=(Jo)=>R1(Jo,c,y),o.parsers[y].array=!0,o.serializers[y]=(Jo)=>J1(Jo,o.serializers[W],o,y)}function fM(W,y){return W==="read-write"&&y.default_transaction_read_only==="on"||W==="read-only"&&y.default_transaction_read_only==="off"||W==="primary"&&y.in_hot_standby==="on"||W==="standby"&&y.in_hot_standby==="off"||W==="prefer-standby"&&y.in_hot_standby==="off"&&o.host[Co]}function SM(){let W=new yT([`
25
25
  show transaction_read_only;
26
26
  select pg_catalog.pg_is_in_recovery()
27
- `],[],eS,null,{simple:!0});O.resolve=([[w],[P]])=>{CT.default_transaction_read_only=w.transaction_read_only,CT.in_hot_standby=P.pg_is_in_recovery?"on":"off"},O.execute()}function SW(O){B&&(B.cursorFn||B.describeFirst)&&cT(fS);let w=LT.postgres(M$(O));B&&B.retried?Bo(B.retried):B&&B.prepared&&zM.has(w.routine)?fW(B,w):Bo(w)}function fW(O,w){delete So[O.signature],O.retried=w,eS(O)}function nW(O){if(!H)return;let w=9;while(O[w++]!==0);H(O.toString("utf8",9,w-1),O.toString("utf8",w,O.length-1))}async function AW(){try{let O=await Promise.resolve(B.cursorFn(Z));BT=0,O===PS?cT(YW(B.portal)):(Z=new _S,cT(p$("",B.cursorRows)))}catch(O){cT(fS),B.reject(O)}}function $W(){Z.count&&B.cursorFn(Z),B.resolve(Z)}function FW(){jT=new O$.Writable({autoDestroy:!0,write(O,w,P){E.write(r().d().raw(O).end(),P)},destroy(O,w){w(O),E.write(r().f().str(O+r.N).end()),jT=null},final(O){E.write(r().c().end()),uS=O}}),B.resolve(jT)}function JW(){jT=new O$.Readable({read(){E.resume()}}),B.resolve(jT)}function RW(){jT=new O$.Duplex({autoDestroy:!0,read(){E.resume()},write(O,w,P){E.write(r().d().raw(O).end(),P)},destroy(O,w){w(O),E.write(r().f().str(O+r.N).end()),jT=null},final(O){E.write(r().c().end()),uS=O}}),B.resolve(jT)}function WW(O){jT&&(jT.push(O.subarray(5))||E.pause())}function OW(){jT&&jT.push(null),jT=null}function MW(O){K?K(M$(O)):console.log(M$(O))}function kW(){}function yW(){Bo(LT.notSupported("FunctionCallResponse"))}function _W(){Bo(LT.notSupported("NegotiateProtocolVersion"))}function wW(O){console.error("Postgres.js : Unknown Message:",O[0])}function XW(O,w){console.error("Postgres.js : Unknown Auth:",w)}function KW(O,w,P="",JT=""){let DT,dT;return r().B().str(JT+r.N).str(P+r.N).i16(0).i16(O.length),O.forEach((aT,po)=>{if(aT===null)return r.i32(4294967295);dT=w[po],O[po]=aT=dT in T.serializers?T.serializers[dT](aT):""+aT,DT=r.i,r.inc(4).str(aT).i32(r.i-DT-4,DT)}),r.i16(0),r.end()}function P$(O,w,P,JT=""){return r().P().str(JT+r.N).str(O+r.N).i16(w.length),w.forEach((DT,dT)=>r.i32(P[dT]||0)),r.end()}function GW(O,w=""){return r().D().str(O).str(w+r.N).end()}function p$(O="",w=0){return Buffer.concat([r().E().str(O+r.N).i32(w).end(),O1])}function YW(O=""){return Buffer.concat([r().C().str("P").str(O+r.N).end(),r().S().end()])}function EW(){return TT||r().inc(4).i16(3).z(2).str(Object.entries(Object.assign({user:F,database:W,client_encoding:"UTF8"},T.connection)).filter(([,O])=>O).map(([O,w])=>O+r.N+w).join(r.N)).z(2).end(0)}}function M$(T){let o={},S=5;for(let f=5;f<T.length-1;f++)if(T[f]===0)o[QM[T[S]]]=T.toString("utf8",S+1,f),S=f+1;return o}function M1(T){return jf.createHash("md5").update(T).digest("hex")}function hn(T,o){return jf.createHmac("sha256",T).update(o).digest()}function DM(T){return jf.createHash("sha256").update(T).digest()}function UM(T,o){let S=Math.max(T.length,o.length),f=Buffer.allocUnsafe(S);for(let n=0;n<S;n++)f[n]=T[n]^o[n];return f}function k$(T,o){if(o=typeof o==="function"?o():o,!o)return{cancel:iS,start:iS};let S;return{cancel(){S&&(clearTimeout(S),S=null)},start(){S&&clearTimeout(S),S=setTimeout(f,o*1000,arguments)}};function f(n){T.apply(null,n),S=null}}var y1=()=>{};function _$(T,o){let S=new Map,f="postgresjs_"+Math.random().toString(36).slice(2),n={},A,$,F=!1,J=y.sql=T({...o,transform:{column:{},value:{},row:{}},max:1,fetch_types:!1,idle_timeout:null,max_lifetime:null,connection:{...o.connection,replication:"database"},onclose:async function(){if(F)return;$=null,n.pid=n.secret=void 0,_(await K(J,f,o.publications)),S.forEach((Y)=>Y.forEach(({onsubscribe:I})=>I()))},no_subscribe:!0}),R=J.end,W=J.close;return J.end=async()=>{return F=!0,$&&await new Promise((Y)=>($.once("close",Y),$.end())),R()},J.close=async()=>{return $&&await new Promise((Y)=>($.once("close",Y),$.end())),W()},y;async function y(Y,I,b=y1,q=y1){if(Y=BM(Y),!A)A=K(J,f,o.publications);let p={fn:I,onsubscribe:b},G=S.has(Y)?S.get(Y).add(p):S.set(Y,new Set([p])).get(Y),D=()=>{G.delete(p),G.size===0&&S.delete(Y)};return A.then((t)=>{return _(t),b(),$&&$.on("error",q),{unsubscribe:D,state:n,sql:J}})}function _(Y){$=Y.stream,n.pid=Y.state.pid,n.secret=Y.state.secret}async function K(Y,I,b){if(!b)throw new Error("Missing publication names");let q=await Y.unsafe(`CREATE_REPLICATION_SLOT ${I} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT`),[p]=q,G=await Y.unsafe(`START_REPLICATION SLOT ${I} LOGICAL ${p.consistent_point} (proto_version '1', publication_names '${b}')`).writable(),D={lsn:Buffer.concat(p.consistent_point.split("/").map((E)=>Buffer.from(("00000000"+E).slice(-8),"hex")))};return G.on("data",U),G.on("error",t),G.on("close",Y.close),{stream:G,state:q.state};function t(E){console.error("Unexpected error during logical streaming - reconnecting",E)}function U(E){if(E[0]===119)VM(E.subarray(25),D,Y.options.parsers,v,o.transform);else if(E[0]===107&&E[17])D.lsn=E.subarray(1,9),l()}function v(E,TT){let Z=TT.relation.schema+"."+TT.relation.table;H("*",E,TT),H("*:"+Z,E,TT),TT.relation.keys.length&&H("*:"+Z+"="+TT.relation.keys.map((oT)=>E[oT.name]),E,TT),H(TT.command,E,TT),H(TT.command+":"+Z,E,TT),TT.relation.keys.length&&H(TT.command+":"+Z+"="+TT.relation.keys.map((oT)=>E[oT.name]),E,TT)}function l(){let E=Buffer.alloc(34);E[0]=114,E.fill(D.lsn,1),E.writeBigInt64BE(BigInt(Date.now()-Date.UTC(2000,0,1))*BigInt(1000),25),G.write(E)}}function H(Y,I,b){S.has(Y)&&S.get(Y).forEach(({fn:q})=>q(I,b,Y))}}function tM(T){return new Date(Date.UTC(2000,0,1)+Number(T/BigInt(1000)))}function VM(T,o,S,f,n){let A=($,[F,J])=>($[F.charCodeAt(0)]=J,$);Object.entries({R:($)=>{let F=1,J=o[$.readUInt32BE(F)]={schema:$.toString("utf8",F+=4,F=$.indexOf(0,F))||"pg_catalog",table:$.toString("utf8",F+1,F=$.indexOf(0,F+1)),columns:Array($.readUInt16BE(F+=2)),keys:[]};F+=2;let R=0,W;while(F<$.length)W=J.columns[R++]={key:$[F++],name:n.column.from?n.column.from($.toString("utf8",F,F=$.indexOf(0,F))):$.toString("utf8",F,F=$.indexOf(0,F)),type:$.readUInt32BE(F+=1),parser:S[$.readUInt32BE(F)],atttypmod:$.readUInt32BE(F+=4)},W.key&&J.keys.push(W),F+=4},Y:()=>{},O:()=>{},B:($)=>{o.date=tM($.readBigInt64BE(9)),o.lsn=$.subarray(1,9)},I:($)=>{let F=1,J=o[$.readUInt32BE(F)],{row:R}=bn($,J.columns,F+=7,n);f(R,{command:"insert",relation:J})},D:($)=>{let F=1,J=o[$.readUInt32BE(F)];F+=4;let R=$[F]===75;f(R||$[F]===79?bn($,J.columns,F+=3,n).row:null,{command:"delete",relation:J,key:R})},U:($)=>{let F=1,J=o[$.readUInt32BE(F)];F+=4;let R=$[F]===75,W=R||$[F]===79?bn($,J.columns,F+=3,n):null;W&&(F=W.i);let{row:y}=bn($,J.columns,F+3,n);f(y,{command:"update",relation:J,key:R,old:W&&W.row})},T:()=>{},C:()=>{}}).reduce(A,{})[T[0]](T)}function bn(T,o,S,f){let n,A,$,F=f.raw?new Array(o.length):{};for(let J=0;J<o.length;J++)n=T[S++],A=o[J],$=n===110?null:n===117?void 0:A.parser===void 0?T.toString("utf8",S+4,S+=4+T.readUInt32BE(S)):A.parser.array===!0?A.parser(T.toString("utf8",S+5,S+=4+T.readUInt32BE(S))):A.parser(T.toString("utf8",S+4,S+=4+T.readUInt32BE(S))),f.raw?F[J]=f.raw===!0?$:f.value.from?f.value.from($,A):$:F[A.name]=f.value.from?f.value.from($,A):$;return{i:S,row:f.row.from?f.row.from(F):F}}function BM(T){let o=T.match(/^(\*|insert|update|delete)?:?([^.]+?\.?[^=]+)?=?(.+)?/i)||[];if(!o)throw new Error("Malformed subscribe pattern: "+T);let[,S,f,n]=o;return(S||"*")+(f?":"+(f.indexOf(".")===-1?"public."+f:f):"")+(n?"="+n:"")}import _1 from"stream";function w$(T,o,S=393216){return new Promise(async(f,n)=>{await T.begin(async(A)=>{let $;!o&&([{oid:o}]=await A`select lo_creat(-1) as oid`);let[{fd:F}]=await A`select lo_open(${o}, ${S}) as fd`,J={writable:W,readable:R,close:()=>A`select lo_close(${F})`.then($),tell:()=>A`select lo_tell64(${F})`,read:(y)=>A`select loread(${F}, ${y}) as data`,write:(y)=>A`select lowrite(${F}, ${y})`,truncate:(y)=>A`select lo_truncate64(${F}, ${y})`,seek:(y,_=0)=>A`select lo_lseek64(${F}, ${y}, ${_})`,size:()=>A`
27
+ `],[],af,null,{simple:!0});W.resolve=([[y],[c]])=>{Lo.default_transaction_read_only=y.transaction_read_only,Lo.in_hot_standby=c.pg_is_in_recovery?"on":"off"},W.execute()}function nM(W){B&&(B.cursorFn||B.describeFirst)&&ro(of);let y=Bo.postgres(W$(W));B&&B.retried?tT(B.retried):B&&B.prepared&&EO.has(y.routine)?AM(B,y):tT(y)}function AM(W,y){delete fT[W.signature],W.retried=y,af(W)}function $M(W){if(!U)return;let y=9;while(W[y++]!==0);U(W.toString("utf8",9,y-1),W.toString("utf8",y,W.length-1))}async function FM(){try{let W=await Promise.resolve(B.cursorFn(r));Vo=0,W===Pf?ro(EM(B.portal)):(r=new yf,ro(c$("",B.cursorRows)))}catch(W){ro(of),B.reject(W)}}function JM(){r.count&&B.cursorFn(r),B.resolve(r)}function RM(){Io=new M$.Writable({autoDestroy:!0,write(W,y,c){G.write(p().d().raw(W).end(),c)},destroy(W,y){y(W),G.write(p().f().str(W+p.N).end()),Io=null},final(W){G.write(p().c().end()),sf=W}}),B.resolve(Io)}function MM(){Io=new M$.Readable({read(){G.resume()}}),B.resolve(Io)}function WM(){Io=new M$.Duplex({autoDestroy:!0,read(){G.resume()},write(W,y,c){G.write(p().d().raw(W).end(),c)},destroy(W,y){y(W),G.write(p().f().str(W+p.N).end()),Io=null},final(W){G.write(p().c().end()),sf=W}}),B.resolve(Io)}function OM(W){Io&&(Io.push(W.subarray(5))||G.pause())}function kM(){Io&&Io.push(null),Io=null}function _M(W){X?X(W$(W)):console.log(W$(W))}function wM(){}function yM(){tT(Bo.notSupported("FunctionCallResponse"))}function XM(){tT(Bo.notSupported("NegotiateProtocolVersion"))}function HM(W){console.error("Postgres.js : Unknown Message:",W[0])}function KM(W,y){console.error("Postgres.js : Unknown Auth:",y)}function GM(W,y,c="",Jo=""){let Do,go;return p().B().str(Jo+p.N).str(c+p.N).i16(0).i16(W.length),W.forEach((so,cT)=>{if(so===null)return p.i32(4294967295);go=y[cT],W[cT]=so=go in o.serializers?o.serializers[go](so):""+so,Do=p.i,p.inc(4).str(so).i32(p.i-Do-4,Do)}),p.i16(0),p.end()}function p$(W,y,c,Jo=""){return p().P().str(Jo+p.N).str(W+p.N).i16(y.length),y.forEach((Do,go)=>p.i32(c[go]||0)),p.end()}function YM(W,y=""){return p().D().str(W).str(y+p.N).end()}function c$(W="",y=0){return Buffer.concat([p().E().str(W+p.N).i32(y).end(),k1])}function EM(W=""){return Buffer.concat([p().C().str("P").str(W+p.N).end(),p().S().end()])}function zM(){return s||p().inc(4).i16(3).z(2).str(Object.entries(Object.assign({user:F,database:M,client_encoding:"UTF8"},o.connection)).filter(([,W])=>W).map(([W,y])=>W+p.N+y).join(p.N)).z(2).end(0)}}function W$(o){let T={},f=5;for(let S=5;S<o.length-1;S++)if(o[S]===0)T[zO[o[f]]]=o.toString("utf8",f+1,S),f=S+1;return T}function _1(o){return NS.createHash("md5").update(o).digest("hex")}function xn(o,T){return NS.createHmac("sha256",o).update(T).digest()}function QO(o){return NS.createHash("sha256").update(o).digest()}function DO(o,T){let f=Math.max(o.length,T.length),S=Buffer.allocUnsafe(f);for(let n=0;n<f;n++)S[n]=o[n]^T[n];return S}function O$(o,T){if(T=typeof T==="function"?T():T,!T)return{cancel:df,start:df};let f;return{cancel(){f&&(clearTimeout(f),f=null)},start(){f&&clearTimeout(f),f=setTimeout(S,T*1000,arguments)}};function S(n){o.apply(null,n),f=null}}var y1=()=>{};function _$(o,T){let f=new Map,S="postgresjs_"+Math.random().toString(36).slice(2),n={},A,$,F=!1,J=_.sql=o({...T,transform:{column:{},value:{},row:{}},max:1,fetch_types:!1,idle_timeout:null,max_lifetime:null,connection:{...T.connection,replication:"database"},onclose:async function(){if(F)return;$=null,n.pid=n.secret=void 0,w(await X(J,S,T.publications)),f.forEach((K)=>K.forEach(({onsubscribe:L})=>L()))},no_subscribe:!0}),R=J.end,M=J.close;return J.end=async()=>{return F=!0,$&&await new Promise((K)=>($.once("close",K),$.end())),R()},J.close=async()=>{return $&&await new Promise((K)=>($.once("close",K),$.end())),M()},_;async function _(K,L,h=y1,q=y1){if(K=VO(K),!A)A=X(J,S,T.publications);let P={fn:L,onsubscribe:h},Y=f.has(K)?f.get(K).add(P):f.set(K,new Set([P])).get(K),Q=()=>{Y.delete(P),Y.size===0&&f.delete(K)};return A.then((t)=>{return w(t),h(),$&&$.on("error",q),{unsubscribe:Q,state:n,sql:J}})}function w(K){$=K.stream,n.pid=K.state.pid,n.secret=K.state.secret}async function X(K,L,h){if(!h)throw new Error("Missing publication names");let q=await K.unsafe(`CREATE_REPLICATION_SLOT ${L} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT`),[P]=q,Y=await K.unsafe(`START_REPLICATION SLOT ${L} LOGICAL ${P.consistent_point} (proto_version '1', publication_names '${h}')`).writable(),Q={lsn:Buffer.concat(P.consistent_point.split("/").map((G)=>Buffer.from(("00000000"+G).slice(-8),"hex")))};return Y.on("data",D),Y.on("error",t),Y.on("close",K.close),{stream:Y,state:q.state};function t(G){console.error("Unexpected error during logical streaming - reconnecting",G)}function D(G){if(G[0]===119)tO(G.subarray(25),Q,K.options.parsers,v,T.transform);else if(G[0]===107&&G[17])Q.lsn=G.subarray(1,9),l()}function v(G,s){let r=s.relation.schema+"."+s.relation.table;U("*",G,s),U("*:"+r,G,s),s.relation.keys.length&&U("*:"+r+"="+s.relation.keys.map((a)=>G[a.name]),G,s),U(s.command,G,s),U(s.command+":"+r,G,s),s.relation.keys.length&&U(s.command+":"+r+"="+s.relation.keys.map((a)=>G[a.name]),G,s)}function l(){let G=Buffer.alloc(34);G[0]=114,G.fill(Q.lsn,1),G.writeBigInt64BE(BigInt(Date.now()-Date.UTC(2000,0,1))*BigInt(1000),25),Y.write(G)}}function U(K,L,h){f.has(K)&&f.get(K).forEach(({fn:q})=>q(L,h,K))}}function UO(o){return new Date(Date.UTC(2000,0,1)+Number(o/BigInt(1000)))}function tO(o,T,f,S,n){let A=($,[F,J])=>($[F.charCodeAt(0)]=J,$);Object.entries({R:($)=>{let F=1,J=T[$.readUInt32BE(F)]={schema:$.toString("utf8",F+=4,F=$.indexOf(0,F))||"pg_catalog",table:$.toString("utf8",F+1,F=$.indexOf(0,F+1)),columns:Array($.readUInt16BE(F+=2)),keys:[]};F+=2;let R=0,M;while(F<$.length)M=J.columns[R++]={key:$[F++],name:n.column.from?n.column.from($.toString("utf8",F,F=$.indexOf(0,F))):$.toString("utf8",F,F=$.indexOf(0,F)),type:$.readUInt32BE(F+=1),parser:f[$.readUInt32BE(F)],atttypmod:$.readUInt32BE(F+=4)},M.key&&J.keys.push(M),F+=4},Y:()=>{},O:()=>{},B:($)=>{T.date=UO($.readBigInt64BE(9)),T.lsn=$.subarray(1,9)},I:($)=>{let F=1,J=T[$.readUInt32BE(F)],{row:R}=vn($,J.columns,F+=7,n);S(R,{command:"insert",relation:J})},D:($)=>{let F=1,J=T[$.readUInt32BE(F)];F+=4;let R=$[F]===75;S(R||$[F]===79?vn($,J.columns,F+=3,n).row:null,{command:"delete",relation:J,key:R})},U:($)=>{let F=1,J=T[$.readUInt32BE(F)];F+=4;let R=$[F]===75,M=R||$[F]===79?vn($,J.columns,F+=3,n):null;M&&(F=M.i);let{row:_}=vn($,J.columns,F+3,n);S(_,{command:"update",relation:J,key:R,old:M&&M.row})},T:()=>{},C:()=>{}}).reduce(A,{})[o[0]](o)}function vn(o,T,f,S){let n,A,$,F=S.raw?new Array(T.length):{};for(let J=0;J<T.length;J++)n=o[f++],A=T[J],$=n===110?null:n===117?void 0:A.parser===void 0?o.toString("utf8",f+4,f+=4+o.readUInt32BE(f)):A.parser.array===!0?A.parser(o.toString("utf8",f+5,f+=4+o.readUInt32BE(f))):A.parser(o.toString("utf8",f+4,f+=4+o.readUInt32BE(f))),S.raw?F[J]=S.raw===!0?$:S.value.from?S.value.from($,A):$:F[A.name]=S.value.from?S.value.from($,A):$;return{i:f,row:S.row.from?S.row.from(F):F}}function VO(o){let T=o.match(/^(\*|insert|update|delete)?:?([^.]+?\.?[^=]+)?=?(.+)?/i)||[];if(!T)throw new Error("Malformed subscribe pattern: "+o);let[,f,S,n]=T;return(f||"*")+(S?":"+(S.indexOf(".")===-1?"public."+S:S):"")+(n?"="+n:"")}import X1 from"stream";function w$(o,T,f=393216){return new Promise(async(S,n)=>{await o.begin(async(A)=>{let $;!T&&([{oid:T}]=await A`select lo_creat(-1) as oid`);let[{fd:F}]=await A`select lo_open(${T}, ${f}) as fd`,J={writable:M,readable:R,close:()=>A`select lo_close(${F})`.then($),tell:()=>A`select lo_tell64(${F})`,read:(_)=>A`select loread(${F}, ${_}) as data`,write:(_)=>A`select lowrite(${F}, ${_})`,truncate:(_)=>A`select lo_truncate64(${F}, ${_})`,seek:(_,w=0)=>A`select lo_lseek64(${F}, ${_}, ${w})`,size:()=>A`
28
28
  select
29
29
  lo_lseek64(${F}, location, 0) as position,
30
30
  seek.size
@@ -34,10 +34,10 @@ ${$.trace}`:"No previous disposal trace was found."),f.type){case"atom_family":c
34
34
  tell.location
35
35
  from (select lo_tell64($1) as location) tell
36
36
  ) seek
37
- `};return f(J),new Promise(async(y)=>$=y);async function R({highWaterMark:y=16384,start:_=0,end:K=1/0}={}){let H=K-_;return _&&await J.seek(_),new _1.Readable({highWaterMark:y,async read(Y){let I=Y>H?Y-H:Y;H-=Y;let[{data:b}]=await J.read(I);if(this.push(b),b.length<Y)this.push(null)}})}async function W({highWaterMark:y=16384,start:_=0}={}){return _&&await J.seek(_),new _1.Writable({highWaterMark:y,write(K,H,Y){J.write(K).then(()=>Y(),Y)}})}}).catch(n)})}Object.assign(xn,{PostgresError:pS,toPascal:kS,pascal:R$,toCamel:MS,camel:J$,toKebab:yS,kebab:W$,fromPascal:Lf,fromCamel:Bf,fromKebab:Cf,BigInt:{to:20,from:[20],parse:(T)=>BigInt(T),serialize:(T)=>T.toString()}});var gS=xn;function xn(T,o){let S=IM(T,o),f=S.no_subscribe||_$(xn,{...S}),n=!1,A=Oo(),$=Oo(),F=Oo(),J=Oo(),R=Oo(),W=Oo(),y=Oo(),_=Oo(),K={connecting:$,reserved:F,closed:J,ended:R,open:W,busy:y,full:_},H=[...Array(S.max)].map(()=>y$(S,K,{onopen:So,onend:CT,onclose:No})),Y=I(v);return Object.assign(Y,{get parameters(){return S.parameters},largeObject:w$.bind(null,Y),subscribe:f,CLOSE:PS,END:PS,PostgresError:pS,options:S,reserve:p,listen:b,begin:G,close:Z,end:TT}),Y;function I(z){return z.debug=S.debug,Object.entries(S.types).reduce((fT,[_T,BT])=>{return fT[_T]=(zT)=>new mo(zT,BT.to),fT},c),Object.assign(FT,{types:c,typed:c,unsafe:ET,notify:q,array:U,json:t,file:IT}),FT;function c(fT,_T){return new mo(fT,_T)}function FT(fT,..._T){return fT&&Array.isArray(fT.raw)?new wo(fT,_T,z,E):typeof fT==="string"&&!_T.length?new If(S.transform.column.to?S.transform.column.to(fT):fT):new In(fT,_T)}function ET(fT,_T=[],BT={}){return arguments.length===2&&!Array.isArray(_T)&&(BT=_T,_T=[]),new wo([fT],_T,z,E,{prepare:!1,...BT,simple:"simple"in BT?BT.simple:_T.length===0})}function IT(fT,_T=[],BT={}){return arguments.length===2&&!Array.isArray(_T)&&(BT=_T,_T=[]),new wo([],_T,(KT)=>{CM.readFile(fT,"utf8",(pT,wT)=>{if(pT)return KT.reject(pT);KT.strings=[wT],z(KT)})},E,{...BT,simple:"simple"in BT?BT.simple:_T.length===0})}}async function b(z,c,FT){let ET={fn:c,onlisten:FT},IT=b.sql||(b.sql=xn({...S,max:1,idle_timeout:null,max_lifetime:null,fetch_types:!1,onclose(){Object.entries(b.channels).forEach(([KT,{listeners:pT}])=>{delete b.channels[KT],Promise.all(pT.map((wT)=>b(KT,wT.fn,wT.onlisten).catch(()=>{})))})},onnotify(KT,pT){KT in b.channels&&b.channels[KT].listeners.forEach((wT)=>wT.fn(pT))}})),fT=b.channels||(b.channels={});if(z in fT){fT[z].listeners.push(ET);let KT=await fT[z].result;return ET.onlisten&&ET.onlisten(),{state:KT.state,unlisten:zT}}fT[z]={result:IT`listen ${IT.unsafe('"'+z.replace(/"/g,'""')+'"')}`,listeners:[ET]};let BT=await fT[z].result;return ET.onlisten&&ET.onlisten(),{state:BT.state,unlisten:zT};async function zT(){if(z in fT===!1)return;if(fT[z].listeners=fT[z].listeners.filter((KT)=>KT!==ET),fT[z].listeners.length)return;return delete fT[z],IT`unlisten ${IT.unsafe('"'+z.replace(/"/g,'""')+'"')}`}}async function q(z,c){return await Y`select pg_notify(${z}, ${""+c})`}async function p(){let z=Oo(),c=W.length?W.shift():await new Promise((IT)=>{A.push({reserve:IT}),J.length&&MT(J.shift())});D(c,F),c.reserved=()=>z.length?c.execute(z.shift()):D(c,F),c.reserved.release=!0;let FT=I(ET);return FT.release=()=>{c.reserved=null,So(c)},FT;function ET(IT){c.queue===_?z.push(IT):c.execute(IT)||D(c,_)}}async function G(z,c){!c&&(c=z,z="");let FT=Oo(),ET=0,IT,fT=null;try{return await Y.unsafe("begin "+z.replace(/[^a-z ]/ig,""),[],{onexecute:BT}).execute(),await Promise.race([_T(IT,c),new Promise((zT,KT)=>IT.onclose=KT)])}catch(zT){throw zT}async function _T(zT,KT,pT){let wT=I(jT);wT.savepoint=Po,wT.prepare=(GT)=>fT=GT.replace(/[^a-z0-9$-_. ]/gi);let Xo,iT;pT&&await wT`savepoint ${wT(pT)}`;try{if(iT=await new Promise((GT,Ko)=>{let Vo=KT(wT);Promise.resolve(Array.isArray(Vo)?Promise.all(Vo):Vo).then(GT,Ko)}),Xo)throw Xo}catch(GT){throw await(pT?wT`rollback to ${wT(pT)}`:wT`rollback`),GT instanceof pS&&GT.code==="25P02"&&Xo||GT}if(!pT)fT?await wT`prepare transaction '${wT.unsafe(fT)}'`:await wT`commit`;return iT;function Po(GT,Ko){if(GT&&Array.isArray(GT.raw))return Po((Vo)=>Vo.apply(Vo,arguments));return arguments.length===1&&(Ko=GT,GT=null),_T(zT,Ko,"s"+ET+++(GT?"_"+GT:""))}function jT(GT){GT.catch((Ko)=>Xo||(Xo=Ko)),zT.queue===_?FT.push(GT):zT.execute(GT)||D(zT,_)}}function BT(zT){IT=zT,D(zT,F),zT.reserved=()=>FT.length?zT.execute(FT.shift()):D(zT,F)}}function D(z,c){return z.queue.remove(z),c.push(z),z.queue=c,c===W?z.idleTimer.start():z.idleTimer.cancel(),z}function t(z){return new mo(z,3802)}function U(z,c){if(!Array.isArray(z))return U(Array.from(arguments));return new mo(z,c||(z.length?Ln(z)||25:0),S.shared.typeArrayMap)}function v(z){if(n)return z.reject(LT.connection("CONNECTION_ENDED",S,S));if(W.length)return l(W.shift(),z);if(J.length)return MT(J.shift(),z);y.length?l(y.shift(),z):A.push(z)}function l(z,c){return z.execute(c)?D(z,y):D(z,_)}function E(z){return new Promise((c,FT)=>{z.state?z.active?y$(S).cancel(z.state,c,FT):z.cancelled={resolve:c,reject:FT}:(A.remove(z),z.cancelled=!0,z.reject(LT.generic("57014","canceling statement due to user request")),c())})}async function TT({timeout:z=null}={}){if(n)return n;await 1;let c;return n=Promise.race([new Promise((FT)=>z!==null&&(c=setTimeout(oT,z*1000,FT))),Promise.all(H.map((FT)=>FT.end()).concat(b.sql?b.sql.end({timeout:0}):[],f.sql?f.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(c))}async function Z(){await Promise.all(H.map((z)=>z.end()))}async function oT(z){await Promise.all(H.map((c)=>c.terminate()));while(A.length)A.shift().reject(LT.connection("CONNECTION_DESTROYED",S));z()}function MT(z,c){return D(z,$),z.connect(c),z}function CT(z){D(z,R)}function So(z){if(A.length===0)return D(z,W);let c=Math.ceil(A.length/($.length+1)),FT=!0;while(FT&&A.length&&c-- >0){let ET=A.shift();if(ET.reserve)return ET.reserve(z);FT=z.execute(ET)}FT?D(z,y):D(z,_)}function No(z,c){D(z,J),z.reserved=null,z.onclose&&(z.onclose(c),z.onclose=null),S.onclose&&S.onclose(z.id),A.length&&MT(z,A.shift())}}function IM(T,o){if(T&&T.shared)return T;let S=process.env,f=(!T||typeof T==="string"?o:T)||{},{url:n,multihost:A}=bM(T),$=[...n.searchParams].reduce((_,[K,H])=>(_[K]=H,_),{}),F=f.hostname||f.host||A||n.hostname||S.PGHOST||"localhost",J=f.port||n.port||S.PGPORT||5432,R=f.user||f.username||n.username||S.PGUSERNAME||S.PGUSER||xM();f.no_prepare&&(f.prepare=!1),$.sslmode&&($.ssl=$.sslmode,delete $.sslmode),"timeout"in f&&(console.log("The timeout option is deprecated, use idle_timeout instead"),f.idle_timeout=f.timeout),$.sslrootcert==="system"&&($.ssl="verify-full");let W=["idle_timeout","connect_timeout","max_lifetime","max_pipeline","backoff","keep_alive"],y={max:10,ssl:!1,idle_timeout:null,connect_timeout:30,max_lifetime:NM,max_pipeline:100,backoff:mM,keep_alive:60,prepare:!0,debug:!1,fetch_types:!0,publications:"alltables",target_session_attrs:null};return{host:Array.isArray(F)?F:F.split(",").map((_)=>_.split(":")[0]),port:Array.isArray(J)?J:F.split(",").map((_)=>parseInt(_.split(":")[1]||J)),path:f.path||F.indexOf("/")>-1&&F+"/.s.PGSQL."+J,database:f.database||f.db||(n.pathname||"").slice(1)||S.PGDATABASE||R,user:R,pass:f.pass||f.password||n.password||S.PGPASSWORD||"",...Object.entries(y).reduce((_,[K,H])=>{let Y=K in f?f[K]:(K in $)?$[K]==="disable"||$[K]==="false"?!1:$[K]:S["PG"+K.toUpperCase()]||H;return _[K]=typeof Y==="string"&&W.includes(K)?+Y:Y,_},{}),connection:{application_name:"postgres.js",...f.connection,...Object.entries($).reduce((_,[K,H])=>((K in y)||(_[K]=H),_),{})},types:f.types||{},target_session_attrs:jM(f,n,S),onnotice:f.onnotice,onnotify:f.onnotify,onclose:f.onclose,onparameter:f.onparameter,socket:f.socket,transform:hM(f.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...n1(f.types)}}function jM(T,o,S){let f=T.target_session_attrs||o.searchParams.get("target_session_attrs")||S.PGTARGETSESSIONATTRS;if(!f||["read-write","read-only","primary","standby","prefer-standby"].includes(f))return f;throw new Error("target_session_attrs "+f+" is not supported")}function mM(T){return(0.5+Math.random()/2)*Math.min(3**T/100,20)}function NM(){return 60*(30+Math.random()*30)}function hM(T){return{undefined:T.undefined,column:{from:typeof T.column==="function"?T.column:T.column&&T.column.from,to:T.column&&T.column.to},value:{from:typeof T.value==="function"?T.value:T.value&&T.value.from,to:T.value&&T.value.to},row:{from:typeof T.row==="function"?T.row:T.row&&T.row.from,to:T.row&&T.row.to}}}function bM(T){if(!T||typeof T!=="string")return{url:{searchParams:new Map}};let o=T;o=o.slice(o.indexOf("://")+3).split(/[?/]/)[0],o=decodeURIComponent(o.slice(o.indexOf("@")+1));let S=new URL(T.replace(o,o.split(",")[0]));return{url:{username:decodeURIComponent(S.username),password:decodeURIComponent(S.password),host:S.host,hostname:S.hostname,port:S.port,pathname:S.pathname,searchParams:S.searchParams},multihost:o.indexOf(",")>-1&&o}}function xM(){try{return LM.userInfo().username}catch(T){return process.env.USERNAME||process.env.USER||process.env.LOGNAME}}class UT{static[M]="SelectionProxyHandler";config;constructor(T){this.config={...T}}get(T,o){if(o==="_")return{...T._,selectedFields:new Proxy(T._.selectedFields,this)};if(o===XT)return{...T[XT],selectedFields:new Proxy(T[XT].selectedFields,this)};if(typeof o==="symbol")return T[o];let f=(X(T,xT)?T._.selectedFields:X(T,Ao)?T[XT].selectedFields:T)[o];if(X(f,m.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!f.isSelectionField)return f.sql;let n=f.clone();return n.isSelectionField=!0,n}if(X(f,m)){if(this.config.sqlBehavior==="sql")return f;throw new Error(`You tried to reference "${o}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}if(X(f,kT)){if(this.config.alias)return new Proxy(f,new rS(new Proxy(f.table,new Hf(this.config.alias,this.config.replaceOriginalName??!1))));return f}if(typeof f!=="object"||f===null)return f;return new Proxy(f,new UT(this.config))}}class vn extends To{constructor(T,o,S,f){super();this.session=o,this.dialect=S,this.config={table:T,withList:f}}static[M]="PgDelete";config;where(T){return this.config.where=T,this}returning(T=this.config.table[j.Symbol.Columns]){return this.config.returningFields=T,this.config.returning=_o(T),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:T,...o}=this.dialect.sqlToQuery(this.getSQL());return o}_prepare(T){return yT.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,T,!0)})}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return yT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new UT({alias:ZT(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}function vM(T){return(T.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((S)=>S.toLowerCase()).join("_")}function qM(T){return(T.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((S,f,n)=>{let A=n===0?f.toLowerCase():`${f[0].toUpperCase()}${f.slice(1)}`;return S+A},"")}function ZM(T){return T}class X${static[M]="CasingCache";cache={};cachedTables={};convert;constructor(T){this.convert=T==="snake_case"?vM:T==="camelCase"?qM:ZM}getColumnCasing(T){if(!T.keyAsName)return T.name;let o=T.table[j.Symbol.Schema]??"public",S=T.table[j.Symbol.OriginalName],f=`${o}.${S}.${T.name}`;if(!this.cache[f])this.cacheTable(T.table);return this.cache[f]}cacheTable(T){let o=T[j.Symbol.Schema]??"public",S=T[j.Symbol.OriginalName],f=`${o}.${S}`;if(!this.cachedTables[f]){for(let n of Object.values(T[j.Symbol.Columns])){let A=`${f}.${n.name}`;this.cache[A]=this.convert(n.name)}this.cachedTables[f]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class mf extends Ao{static[M]="PgViewBase"}class wS{static[M]="PgDialect";casing;constructor(T){this.casing=new X$(T?.casing)}async migrate(T,o,S){let f=typeof S==="string"?"__drizzle_migrations":S.migrationsTable??"__drizzle_migrations",n=typeof S==="string"?"drizzle":S.migrationsSchema??"drizzle",A=k`
38
- CREATE TABLE IF NOT EXISTS ${k.identifier(n)}.${k.identifier(f)} (
37
+ `};return S(J),new Promise(async(_)=>$=_);async function R({highWaterMark:_=16384,start:w=0,end:X=1/0}={}){let U=X-w;return w&&await J.seek(w),new X1.Readable({highWaterMark:_,async read(K){let L=K>U?K-U:K;U-=K;let[{data:h}]=await J.read(L);if(this.push(h),h.length<K)this.push(null)}})}async function M({highWaterMark:_=16384,start:w=0}={}){return w&&await J.seek(w),new X1.Writable({highWaterMark:_,write(X,U,K){J.write(X).then(()=>K(),K)}})}}).catch(n)})}Object.assign(qn,{PostgresError:gf,toPascal:_f,pascal:J$,toCamel:kf,camel:F$,toKebab:wf,kebab:R$,fromPascal:IS,fromCamel:CS,fromKebab:jS,BigInt:{to:20,from:[20],parse:(o)=>BigInt(o),serialize:(o)=>o.toString()}});var lf=qn;function qn(o,T){let f=CO(o,T),S=f.no_subscribe||_$(qn,{...f}),n=!1,A=WT(),$=WT(),F=WT(),J=WT(),R=WT(),M=WT(),_=WT(),w=WT(),X={connecting:$,reserved:F,closed:J,ended:R,open:M,busy:_,full:w},U=[...Array(f.max)].map(()=>k$(f,X,{onopen:fT,onend:Lo,onclose:jT})),K=L(v);return Object.assign(K,{get parameters(){return f.parameters},largeObject:w$.bind(null,K),subscribe:S,CLOSE:Pf,END:Pf,PostgresError:gf,options:f,reserve:P,listen:h,begin:Y,close:r,end:s}),K;function L(E){return E.debug=f.debug,Object.entries(f.types).reduce((To,[yo,Vo])=>{return To[yo]=(zo)=>new IT(zo,Vo.to),To},Z),Object.assign(Fo,{types:Z,typed:Z,unsafe:Eo,notify:q,array:D,json:t,file:Co}),Fo;function Z(To,yo){return new IT(To,yo)}function Fo(To,...yo){return To&&Array.isArray(To.raw)?new yT(To,yo,E,G):typeof To==="string"&&!yo.length?new mS(f.transform.column.to?f.transform.column.to(To):To):new mn(To,yo)}function Eo(To,yo=[],Vo={}){return arguments.length===2&&!Array.isArray(yo)&&(Vo=yo,yo=[]),new yT([To],yo,E,G,{prepare:!1,...Vo,simple:"simple"in Vo?Vo.simple:yo.length===0})}function Co(To,yo=[],Vo={}){return arguments.length===2&&!Array.isArray(yo)&&(Vo=yo,yo=[]),new yT([],yo,(Ko)=>{LO.readFile(To,"utf8",(co,Xo)=>{if(co)return Ko.reject(co);Ko.strings=[Xo],E(Ko)})},G,{...Vo,simple:"simple"in Vo?Vo.simple:yo.length===0})}}async function h(E,Z,Fo){let Eo={fn:Z,onlisten:Fo},Co=h.sql||(h.sql=qn({...f,max:1,idle_timeout:null,max_lifetime:null,fetch_types:!1,onclose(){Object.entries(h.channels).forEach(([Ko,{listeners:co}])=>{delete h.channels[Ko],Promise.all(co.map((Xo)=>h(Ko,Xo.fn,Xo.onlisten).catch(()=>{})))})},onnotify(Ko,co){Ko in h.channels&&h.channels[Ko].listeners.forEach((Xo)=>Xo.fn(co))}})),To=h.channels||(h.channels={});if(E in To){To[E].listeners.push(Eo);let Ko=await To[E].result;return Eo.onlisten&&Eo.onlisten(),{state:Ko.state,unlisten:zo}}To[E]={result:Co`listen ${Co.unsafe('"'+E.replace(/"/g,'""')+'"')}`,listeners:[Eo]};let Vo=await To[E].result;return Eo.onlisten&&Eo.onlisten(),{state:Vo.state,unlisten:zo};async function zo(){if(E in To===!1)return;if(To[E].listeners=To[E].listeners.filter((Ko)=>Ko!==Eo),To[E].listeners.length)return;return delete To[E],Co`unlisten ${Co.unsafe('"'+E.replace(/"/g,'""')+'"')}`}}async function q(E,Z){return await K`select pg_notify(${E}, ${""+Z})`}async function P(){let E=WT(),Z=M.length?M.shift():await new Promise((Co)=>{A.push({reserve:Co}),J.length&&ko(J.shift())});Q(Z,F),Z.reserved=()=>E.length?Z.execute(E.shift()):Q(Z,F),Z.reserved.release=!0;let Fo=L(Eo);return Fo.release=()=>{Z.reserved=null,fT(Z)},Fo;function Eo(Co){Z.queue===w?E.push(Co):Z.execute(Co)||Q(Z,w)}}async function Y(E,Z){!Z&&(Z=E,E="");let Fo=WT(),Eo=0,Co,To=null;try{return await K.unsafe("begin "+E.replace(/[^a-z ]/ig,""),[],{onexecute:Vo}).execute(),await Promise.race([yo(Co,Z),new Promise((zo,Ko)=>Co.onclose=Ko)])}catch(zo){throw zo}async function yo(zo,Ko,co){let Xo=L(Io);Xo.savepoint=pT,Xo.prepare=(Go)=>To=Go.replace(/[^a-z0-9$-_. ]/gi);let XT,Po;co&&await Xo`savepoint ${Xo(co)}`;try{if(Po=await new Promise((Go,HT)=>{let UT=Ko(Xo);Promise.resolve(Array.isArray(UT)?Promise.all(UT):UT).then(Go,HT)}),XT)throw XT}catch(Go){throw await(co?Xo`rollback to ${Xo(co)}`:Xo`rollback`),Go instanceof gf&&Go.code==="25P02"&&XT||Go}if(!co)To?await Xo`prepare transaction '${Xo.unsafe(To)}'`:await Xo`commit`;return Po;function pT(Go,HT){if(Go&&Array.isArray(Go.raw))return pT((UT)=>UT.apply(UT,arguments));return arguments.length===1&&(HT=Go,Go=null),yo(zo,HT,"s"+Eo+++(Go?"_"+Go:""))}function Io(Go){Go.catch((HT)=>XT||(XT=HT)),zo.queue===w?Fo.push(Go):zo.execute(Go)||Q(zo,w)}}function Vo(zo){Co=zo,Q(zo,F),zo.reserved=()=>Fo.length?zo.execute(Fo.shift()):Q(zo,F)}}function Q(E,Z){return E.queue.remove(E),Z.push(E),E.queue=Z,Z===M?E.idleTimer.start():E.idleTimer.cancel(),E}function t(E){return new IT(E,3802)}function D(E,Z){if(!Array.isArray(E))return D(Array.from(arguments));return new IT(E,Z||(E.length?In(E)||25:0),f.shared.typeArrayMap)}function v(E){if(n)return E.reject(Bo.connection("CONNECTION_ENDED",f,f));if(M.length)return l(M.shift(),E);if(J.length)return ko(J.shift(),E);_.length?l(_.shift(),E):A.push(E)}function l(E,Z){return E.execute(Z)?Q(E,_):Q(E,w)}function G(E){return new Promise((Z,Fo)=>{E.state?E.active?k$(f).cancel(E.state,Z,Fo):E.cancelled={resolve:Z,reject:Fo}:(A.remove(E),E.cancelled=!0,E.reject(Bo.generic("57014","canceling statement due to user request")),Z())})}async function s({timeout:E=null}={}){if(n)return n;await 1;let Z;return n=Promise.race([new Promise((Fo)=>E!==null&&(Z=setTimeout(a,E*1000,Fo))),Promise.all(U.map((Fo)=>Fo.end()).concat(h.sql?h.sql.end({timeout:0}):[],S.sql?S.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(Z))}async function r(){await Promise.all(U.map((E)=>E.end()))}async function a(E){await Promise.all(U.map((Z)=>Z.terminate()));while(A.length)A.shift().reject(Bo.connection("CONNECTION_DESTROYED",f));E()}function ko(E,Z){return Q(E,$),E.connect(Z),E}function Lo(E){Q(E,R)}function fT(E){if(A.length===0)return Q(E,M);let Z=Math.ceil(A.length/($.length+1)),Fo=!0;while(Fo&&A.length&&Z-- >0){let Eo=A.shift();if(Eo.reserve)return Eo.reserve(E);Fo=E.execute(Eo)}Fo?Q(E,_):Q(E,w)}function jT(E,Z){Q(E,J),E.reserved=null,E.onclose&&(E.onclose(Z),E.onclose=null),f.onclose&&f.onclose(E.id),A.length&&ko(E,A.shift())}}function CO(o,T){if(o&&o.shared)return o;let f=process.env,S=(!o||typeof o==="string"?T:o)||{},{url:n,multihost:A}=hO(o),$=[...n.searchParams].reduce((w,[X,U])=>(w[X]=U,w),{}),F=S.hostname||S.host||A||n.hostname||f.PGHOST||"localhost",J=S.port||n.port||f.PGPORT||5432,R=S.user||S.username||n.username||f.PGUSERNAME||f.PGUSER||bO();S.no_prepare&&(S.prepare=!1),$.sslmode&&($.ssl=$.sslmode,delete $.sslmode),"timeout"in S&&(console.log("The timeout option is deprecated, use idle_timeout instead"),S.idle_timeout=S.timeout),$.sslrootcert==="system"&&($.ssl="verify-full");let M=["idle_timeout","connect_timeout","max_lifetime","max_pipeline","backoff","keep_alive"],_={max:10,ssl:!1,idle_timeout:null,connect_timeout:30,max_lifetime:mO,max_pipeline:100,backoff:jO,keep_alive:60,prepare:!0,debug:!1,fetch_types:!0,publications:"alltables",target_session_attrs:null};return{host:Array.isArray(F)?F:F.split(",").map((w)=>w.split(":")[0]),port:Array.isArray(J)?J:F.split(",").map((w)=>parseInt(w.split(":")[1]||J)),path:S.path||F.indexOf("/")>-1&&F+"/.s.PGSQL."+J,database:S.database||S.db||(n.pathname||"").slice(1)||f.PGDATABASE||R,user:R,pass:S.pass||S.password||n.password||f.PGPASSWORD||"",...Object.entries(_).reduce((w,[X,U])=>{let K=X in S?S[X]:(X in $)?$[X]==="disable"||$[X]==="false"?!1:$[X]:f["PG"+X.toUpperCase()]||U;return w[X]=typeof K==="string"&&M.includes(X)?+K:K,w},{}),connection:{application_name:"postgres.js",...S.connection,...Object.entries($).reduce((w,[X,U])=>((X in _)||(w[X]=U),w),{})},types:S.types||{},target_session_attrs:IO(S,n,f),onnotice:S.onnotice,onnotify:S.onnotify,onclose:S.onclose,onparameter:S.onparameter,socket:S.socket,transform:NO(S.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...$1(S.types)}}function IO(o,T,f){let S=o.target_session_attrs||T.searchParams.get("target_session_attrs")||f.PGTARGETSESSIONATTRS;if(!S||["read-write","read-only","primary","standby","prefer-standby"].includes(S))return S;throw new Error("target_session_attrs "+S+" is not supported")}function jO(o){return(0.5+Math.random()/2)*Math.min(3**o/100,20)}function mO(){return 60*(30+Math.random()*30)}function NO(o){return{undefined:o.undefined,column:{from:typeof o.column==="function"?o.column:o.column&&o.column.from,to:o.column&&o.column.to},value:{from:typeof o.value==="function"?o.value:o.value&&o.value.from,to:o.value&&o.value.to},row:{from:typeof o.row==="function"?o.row:o.row&&o.row.from,to:o.row&&o.row.to}}}function hO(o){if(!o||typeof o!=="string")return{url:{searchParams:new Map}};let T=o;T=T.slice(T.indexOf("://")+3).split(/[?/]/)[0],T=decodeURIComponent(T.slice(T.indexOf("@")+1));let f=new URL(o.replace(T,T.split(",")[0]));return{url:{username:decodeURIComponent(f.username),password:decodeURIComponent(f.password),host:f.host,hostname:f.hostname,port:f.port,pathname:f.pathname,searchParams:f.searchParams},multihost:T.indexOf(",")>-1&&T}}function bO(){try{return BO.userInfo().username}catch(o){return process.env.USERNAME||process.env.USER||process.env.LOGNAME}}class Uo{static[O]="SelectionProxyHandler";config;constructor(o){this.config={...o}}get(o,T){if(T==="_")return{...o._,selectedFields:new Proxy(o._.selectedFields,this)};if(T===Ho)return{...o[Ho],selectedFields:new Proxy(o[Ho].selectedFields,this)};if(typeof T==="symbol")return o[T];let S=(H(o,bo)?o._.selectedFields:H(o,nT)?o[Ho].selectedFields:o)[T];if(H(S,m.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!S.isSelectionField)return S.sql;let n=S.clone();return n.isSelectionField=!0,n}if(H(S,m)){if(this.config.sqlBehavior==="sql")return S;throw new Error(`You tried to reference "${T}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}if(H(S,_o)){if(this.config.alias)return new Proxy(S,new cf(new Proxy(S.table,new QS(this.config.alias,this.config.replaceOriginalName??!1))));return S}if(typeof S!=="object"||S===null)return S;return new Proxy(S,new Uo(this.config))}}class rn extends oT{constructor(o,T,f,S){super();this.session=T,this.dialect=f,this.config={table:o,withList:S}}static[O]="PgDelete";config;where(o){return this.config.where=o,this}returning(o=this.config.table[j.Symbol.Columns]){return this.config.returningFields=o,this.config.returning=wT(o),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:o,...T}=this.dialect.sqlToQuery(this.getSQL());return T}_prepare(o){return wo.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,o,!0)})}prepare(o){return this._prepare(o)}authToken;setToken(o){return this.authToken=o,this}execute=(o)=>{return wo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(o,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new Uo({alias:qo(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}function xO(o){return(o.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((f)=>f.toLowerCase()).join("_")}function vO(o){return(o.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((f,S,n)=>{let A=n===0?S.toLowerCase():`${S[0].toUpperCase()}${S.slice(1)}`;return f+A},"")}function qO(o){return o}class y${static[O]="CasingCache";cache={};cachedTables={};convert;constructor(o){this.convert=o==="snake_case"?xO:o==="camelCase"?vO:qO}getColumnCasing(o){if(!o.keyAsName)return o.name;let T=o.table[j.Symbol.Schema]??"public",f=o.table[j.Symbol.OriginalName],S=`${T}.${f}.${o.name}`;if(!this.cache[S])this.cacheTable(o.table);return this.cache[S]}cacheTable(o){let T=o[j.Symbol.Schema]??"public",f=o[j.Symbol.OriginalName],S=`${T}.${f}`;if(!this.cachedTables[S]){for(let n of Object.values(o[j.Symbol.Columns])){let A=`${S}.${n.name}`;this.cache[A]=this.convert(n.name)}this.cachedTables[S]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class hS extends nT{static[O]="PgViewBase"}class Xf{static[O]="PgDialect";casing;constructor(o){this.casing=new y$(o?.casing)}async migrate(o,T,f){let S=typeof f==="string"?"__drizzle_migrations":f.migrationsTable??"__drizzle_migrations",n=typeof f==="string"?"drizzle":f.migrationsSchema??"drizzle",A=k`
38
+ CREATE TABLE IF NOT EXISTS ${k.identifier(n)}.${k.identifier(S)} (
39
39
  id SERIAL PRIMARY KEY,
40
40
  hash text NOT NULL,
41
41
  created_at bigint
42
42
  )
43
- `;await o.execute(k`CREATE SCHEMA IF NOT EXISTS ${k.identifier(n)}`),await o.execute(A);let F=(await o.all(k`select id, hash, created_at from ${k.identifier(n)}.${k.identifier(f)} order by created_at desc limit 1`))[0];await o.transaction(async(J)=>{for await(let R of T)if(!F||Number(F.created_at)<R.folderMillis){for(let W of R.sql)await J.execute(k.raw(W));await J.execute(k`insert into ${k.identifier(n)}.${k.identifier(f)} ("hash", "created_at") values(${R.hash}, ${R.folderMillis})`)}})}escapeName(T){return`"${T}"`}escapeParam(T){return`$${T+1}`}escapeString(T){return`'${T.replace(/'/g,"''")}'`}buildWithCTE(T){if(!T?.length)return;let o=[k`with `];for(let[S,f]of T.entries())if(o.push(k`${k.identifier(f._.alias)} as (${f._.sql})`),S<T.length-1)o.push(k`, `);return o.push(k` `),k.join(o)}buildDeleteQuery({table:T,where:o,returning:S,withList:f}){let n=this.buildWithCTE(f),A=S?k` returning ${this.buildSelection(S,{isSingleTable:!0})}`:void 0,$=o?k` where ${o}`:void 0;return k`${n}delete from ${T}${$}${A}`}buildUpdateSet(T,o){let S=T[j.Symbol.Columns],f=Object.keys(S).filter((A)=>o[A]!==void 0||S[A]?.onUpdateFn!==void 0),n=f.length;return k.join(f.flatMap((A,$)=>{let F=S[A],J=o[A]??k.param(F.onUpdateFn(),F),R=k`${k.identifier(this.casing.getColumnCasing(F))} = ${J}`;if($<n-1)return[R,k.raw(", ")];return[R]}))}buildUpdateQuery({table:T,set:o,where:S,returning:f,withList:n,from:A,joins:$}){let F=this.buildWithCTE(n),J=T[PT.Symbol.Name],R=T[PT.Symbol.Schema],W=T[PT.Symbol.OriginalName],y=J===W?void 0:J,_=k`${R?k`${k.identifier(R)}.`:void 0}${k.identifier(W)}${y&&k` ${k.identifier(y)}`}`,K=this.buildUpdateSet(T,o),H=A&&k.join([k.raw(" from "),this.buildFromTable(A)]),Y=this.buildJoins($),I=f?k` returning ${this.buildSelection(f,{isSingleTable:!A})}`:void 0,b=S?k` where ${S}`:void 0;return k`${F}update ${_} set ${K}${H}${Y}${b}${I}`}buildSelection(T,{isSingleTable:o=!1}={}){let S=T.length,f=T.flatMap(({field:n},A)=>{let $=[];if(X(n,m.Aliased)&&n.isSelectionField)$.push(k.identifier(n.fieldAlias));else if(X(n,m.Aliased)||X(n,m)){let F=X(n,m.Aliased)?n.sql:n;if(o)$.push(new m(F.queryChunks.map((J)=>{if(X(J,V))return k.identifier(this.casing.getColumnCasing(J));return J})));else $.push(F);if(X(n,m.Aliased))$.push(k` as ${k.identifier(n.fieldAlias)}`)}else if(X(n,kT))if(o)$.push(k.identifier(this.casing.getColumnCasing(n)));else $.push(n);if(A<S-1)$.push(k`, `);return $});return k.join(f)}buildJoins(T){if(!T||T.length===0)return;let o=[];for(let[S,f]of T.entries()){if(S===0)o.push(k` `);let n=f.table,A=f.lateral?k` lateral`:void 0;if(X(n,PT)){let $=n[PT.Symbol.Name],F=n[PT.Symbol.Schema],J=n[PT.Symbol.OriginalName],R=$===J?void 0:f.alias;o.push(k`${k.raw(f.joinType)} join${A} ${F?k`${k.identifier(F)}.`:void 0}${k.identifier(J)}${R&&k` ${k.identifier(R)}`} on ${f.on}`)}else if(X(n,Ao)){let $=n[XT].name,F=n[XT].schema,J=n[XT].originalName,R=$===J?void 0:f.alias;o.push(k`${k.raw(f.joinType)} join${A} ${F?k`${k.identifier(F)}.`:void 0}${k.identifier(J)}${R&&k` ${k.identifier(R)}`} on ${f.on}`)}else o.push(k`${k.raw(f.joinType)} join${A} ${n} on ${f.on}`);if(S<T.length-1)o.push(k` `)}return k.join(o)}buildFromTable(T){if(X(T,j)&&T[j.Symbol.OriginalName]!==T[j.Symbol.Name]){let o=k`${k.identifier(T[j.Symbol.OriginalName])}`;if(T[j.Symbol.Schema])o=k`${k.identifier(T[j.Symbol.Schema])}.${o}`;return k`${o} ${k.identifier(T[j.Symbol.Name])}`}return T}buildSelectQuery({withList:T,fields:o,fieldsFlat:S,where:f,having:n,table:A,joins:$,orderBy:F,groupBy:J,limit:R,offset:W,lockingClause:y,distinct:_,setOperators:K}){let H=S??_o(o);for(let oT of H)if(X(oT.field,kT)&&ZT(oT.field.table)!==(X(A,xT)?A._.alias:X(A,mf)?A[XT].name:X(A,m)?void 0:ZT(A))&&!((MT)=>$?.some(({alias:CT})=>CT===(MT[j.Symbol.IsAlias]?ZT(MT):MT[j.Symbol.BaseName])))(oT.field.table)){let MT=ZT(oT.field.table);throw new Error(`Your "${oT.path.join("->")}" field references a column "${MT}"."${oT.field.name}", but the table "${MT}" is not part of the query! Did you forget to join it?`)}let Y=!$||$.length===0,I=this.buildWithCTE(T),b;if(_)b=_===!0?k` distinct`:k` distinct on (${k.join(_.on,k`, `)})`;let q=this.buildSelection(H,{isSingleTable:Y}),p=this.buildFromTable(A),G=this.buildJoins($),D=f?k` where ${f}`:void 0,t=n?k` having ${n}`:void 0,U;if(F&&F.length>0)U=k` order by ${k.join(F,k`, `)}`;let v;if(J&&J.length>0)v=k` group by ${k.join(J,k`, `)}`;let l=typeof R==="object"||typeof R==="number"&&R>=0?k` limit ${R}`:void 0,E=W?k` offset ${W}`:void 0,TT=k.empty();if(y){let oT=k` for ${k.raw(y.strength)}`;if(y.config.of)oT.append(k` of ${k.join(Array.isArray(y.config.of)?y.config.of:[y.config.of],k`, `)}`);if(y.config.noWait)oT.append(k` no wait`);else if(y.config.skipLocked)oT.append(k` skip locked`);TT.append(oT)}let Z=k`${I}select${b} ${q} from ${p}${G}${D}${v}${t}${U}${l}${E}${TT}`;if(K.length>0)return this.buildSetOperations(Z,K);return Z}buildSetOperations(T,o){let[S,...f]=o;if(!S)throw new Error("Cannot pass undefined values to any set operator");if(f.length===0)return this.buildSetOperationQuery({leftSelect:T,setOperator:S});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:T,setOperator:S}),f)}buildSetOperationQuery({leftSelect:T,setOperator:{type:o,isAll:S,rightSelect:f,limit:n,orderBy:A,offset:$}}){let F=k`(${T.getSQL()}) `,J=k`(${f.getSQL()})`,R;if(A&&A.length>0){let K=[];for(let H of A)if(X(H,V))K.push(k.identifier(H.name));else if(X(H,m)){for(let Y=0;Y<H.queryChunks.length;Y++){let I=H.queryChunks[Y];if(X(I,V))H.queryChunks[Y]=k.identifier(I.name)}K.push(k`${H}`)}else K.push(k`${H}`);R=k` order by ${k.join(K,k`, `)} `}let W=typeof n==="object"||typeof n==="number"&&n>=0?k` limit ${n}`:void 0,y=k.raw(`${o} ${S?"all ":""}`),_=$?k` offset ${$}`:void 0;return k`${F}${y}${J}${R}${W}${_}`}buildInsertQuery({table:T,values:o,onConflict:S,returning:f,withList:n,select:A,overridingSystemValue_:$}){let F=[],J=T[j.Symbol.Columns],R=Object.entries(J).filter(([I,b])=>!b.shouldDisableInsert()),W=R.map(([,I])=>k.identifier(this.casing.getColumnCasing(I)));if(A){let I=o;if(X(I,m))F.push(I);else F.push(I.getSQL())}else{let I=o;F.push(k.raw("values "));for(let[b,q]of I.entries()){let p=[];for(let[G,D]of R){let t=q[G];if(t===void 0||X(t,Ro)&&t.value===void 0)if(D.defaultFn!==void 0){let U=D.defaultFn(),v=X(U,m)?U:k.param(U,D);p.push(v)}else if(!D.default&&D.onUpdateFn!==void 0){let U=D.onUpdateFn(),v=X(U,m)?U:k.param(U,D);p.push(v)}else p.push(k`default`);else p.push(t)}if(F.push(p),b<I.length-1)F.push(k`, `)}}let y=this.buildWithCTE(n),_=k.join(F),K=f?k` returning ${this.buildSelection(f,{isSingleTable:!0})}`:void 0,H=S?k` on conflict ${S}`:void 0,Y=$===!0?k`overriding system value `:void 0;return k`${y}insert into ${T} ${W} ${Y}${_}${H}${K}`}buildRefreshMaterializedViewQuery({view:T,concurrently:o,withNoData:S}){let f=o?k` concurrently`:void 0,n=S?k` with no data`:void 0;return k`refresh materialized view${f} ${T}${n}`}prepareTyping(T){if(X(T,En)||X(T,Yn))return"json";else if(X(T,Hn))return"decimal";else if(X(T,zn))return"time";else if(X(T,Qn)||X(T,Dn))return"timestamp";else if(X(T,Xn)||X(T,Kn))return"date";else if(X(T,Un))return"uuid";else return"none"}sqlToQuery(T,o){return T.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,prepareTyping:this.prepareTyping,invokeSource:o})}buildRelationalQueryWithoutPK({fullSchema:T,schema:o,tableNamesMap:S,table:f,tableConfig:n,queryConfig:A,tableAlias:$,nestedQueryRelation:F,joinOn:J}){let R=[],W,y,_=[],K,H=[];if(A===!0)R=Object.entries(n.columns).map(([b,q])=>({dbKey:q.name,tsKey:b,field:jo(q,$),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let I=Object.fromEntries(Object.entries(n.columns).map(([t,U])=>[t,jo(U,$)]));if(A.where){let t=typeof A.where==="function"?A.where(I,p0()):A.where;K=t&&zf(t,$)}let b=[],q=[];if(A.columns){let t=!1;for(let[U,v]of Object.entries(A.columns)){if(v===void 0)continue;if(U in n.columns){if(!t&&v===!0)t=!0;q.push(U)}}if(q.length>0)q=t?q.filter((U)=>A.columns?.[U]===!0):Object.keys(n.columns).filter((U)=>!q.includes(U))}else q=Object.keys(n.columns);for(let t of q){let U=n.columns[t];b.push({tsKey:t,value:U})}let p=[];if(A.with)p=Object.entries(A.with).filter((t)=>!!t[1]).map(([t,U])=>({tsKey:t,queryConfig:U,relation:n.relations[t]}));let G;if(A.extras){G=typeof A.extras==="function"?A.extras(I,{sql:k}):A.extras;for(let[t,U]of Object.entries(G))b.push({tsKey:t,value:iA(U,$)})}for(let{tsKey:t,value:U}of b)R.push({dbKey:X(U,m.Aliased)?U.fieldAlias:n.columns[t].name,tsKey:t,field:X(U,kT)?jo(U,$):U,relationTableTsKey:void 0,isJson:!1,selection:[]});let D=typeof A.orderBy==="function"?A.orderBy(I,i0()):A.orderBy??[];if(!Array.isArray(D))D=[D];_=D.map((t)=>{if(X(t,kT))return jo(t,$);return zf(t,$)}),W=A.limit,y=A.offset;for(let{tsKey:t,queryConfig:U,relation:v}of p){let l=d0(o,S,v),E=OS(v.referencedTable),TT=S[E],Z=`${$}_${t}`,oT=Qf(...l.fields.map((So,No)=>_n(jo(l.references[No],Z),jo(So,$)))),MT=this.buildRelationalQueryWithoutPK({fullSchema:T,schema:o,tableNamesMap:S,table:T[TT],tableConfig:o[TT],queryConfig:X(v,SS)?U===!0?{limit:1}:{...U,limit:1}:U,tableAlias:Z,joinOn:oT,nestedQueryRelation:v}),CT=k`${k.identifier(Z)}.${k.identifier("data")}`.as(t);H.push({on:k`true`,table:new xT(MT.sql,{},Z),alias:Z,joinType:"left",lateral:!0}),R.push({dbKey:t,tsKey:t,field:CT,relationTableTsKey:TT,isJson:!0,selection:MT.selection})}}if(R.length===0)throw new yn({message:`No fields selected for table "${n.tsName}" ("${$}")`});let Y;if(K=Qf(J,K),F){let I=k`json_build_array(${k.join(R.map(({field:p,tsKey:G,isJson:D})=>D?k`${k.identifier(`${$}_${G}`)}.${k.identifier("data")}`:X(p,m.Aliased)?p.sql:p),k`, `)})`;if(X(F,Vf))I=k`coalesce(json_agg(${I}${_.length>0?k` order by ${k.join(_,k`, `)}`:void 0}), '[]'::json)`;let b=[{dbKey:"data",tsKey:"data",field:I.as("data"),isJson:!0,relationTableTsKey:n.tsName,selection:R}];if(W!==void 0||y!==void 0||_.length>0)Y=this.buildSelectQuery({table:kn(f,$),fields:{},fieldsFlat:[{path:[],field:k.raw("*")}],where:K,limit:W,offset:y,orderBy:_,setOperators:[]}),K=void 0,W=void 0,y=void 0,_=[];else Y=kn(f,$);Y=this.buildSelectQuery({table:X(Y,PT)?Y:new xT(Y,{},$),fields:{},fieldsFlat:b.map(({field:p})=>({path:[],field:X(p,kT)?jo(p,$):p})),joins:H,where:K,limit:W,offset:y,orderBy:_,setOperators:[]})}else Y=this.buildSelectQuery({table:kn(f,$),fields:{},fieldsFlat:R.map(({field:I})=>({path:[],field:X(I,kT)?jo(I,$):I})),joins:H,where:K,limit:W,offset:y,orderBy:_,setOperators:[]});return{tableTsKey:n.tsName,sql:Y,selection:R}}}class K${static[M]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class oo{static[M]="PgSelectBuilder";fields;session;dialect;withList=[];distinct;constructor(T){if(this.fields=T.fields,this.session=T.session,this.dialect=T.dialect,T.withList)this.withList=T.withList;this.distinct=T.distinct}authToken;setToken(T){return this.authToken=T,this}from(T){let o=!!this.fields,S=T,f;if(this.fields)f=this.fields;else if(X(S,xT))f=Object.fromEntries(Object.keys(S._.selectedFields).map((n)=>[n,S[n]]));else if(X(S,mf))f=S[XT].selectedFields;else if(X(S,m))f={};else f=lJ(S);return new G$({table:S,fields:f,isPartialSelect:o,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}}class w1 extends K${static[M]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;constructor({table:T,fields:o,isPartialSelect:S,session:f,dialect:n,withList:A,distinct:$}){super();this.config={withList:A,table:T,fields:{...o},distinct:$,setOperators:[]},this.isPartialSelect=S,this.session=f,this.dialect=n,this._={selectedFields:o},this.tableName=co(T),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}createJoin(T){return(o,S)=>{let f=this.tableName,n=co(o);if(typeof n==="string"&&this.config.joins?.some((A)=>A.alias===n))throw new Error(`Alias "${n}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof f==="string")this.config.fields={[f]:this.config.fields};if(typeof n==="string"&&!X(o,m)){let A=X(o,xT)?o._.selectedFields:X(o,Ao)?o[XT].selectedFields:o[j.Symbol.Columns];this.config.fields[n]=A}}if(typeof S==="function")S=S(new Proxy(this.config.fields,new UT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:S,table:o,joinType:T,alias:n}),typeof n==="string")switch(T){case"left":{this.joinsNotNullableMap[n]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([A])=>[A,!1])),this.joinsNotNullableMap[n]=!0;break}case"inner":{this.joinsNotNullableMap[n]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([A])=>[A,!1])),this.joinsNotNullableMap[n]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");createSetOperator(T,o){return(S)=>{let f=typeof S==="function"?S(cM()):S;if(!Df(this.getSelectedFields(),f.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return this.config.setOperators.push({type:T,isAll:o,rightSelect:f}),this}}union=this.createSetOperator("union",!1);unionAll=this.createSetOperator("union",!0);intersect=this.createSetOperator("intersect",!1);intersectAll=this.createSetOperator("intersect",!0);except=this.createSetOperator("except",!1);exceptAll=this.createSetOperator("except",!0);addSetOperators(T){return this.config.setOperators.push(...T),this}where(T){if(typeof T==="function")T=T(new Proxy(this.config.fields,new UT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=T,this}having(T){if(typeof T==="function")T=T(new Proxy(this.config.fields,new UT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=T,this}groupBy(...T){if(typeof T[0]==="function"){let o=T[0](new Proxy(this.config.fields,new UT({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(o)?o:[o]}else this.config.groupBy=T;return this}orderBy(...T){if(typeof T[0]==="function"){let o=T[0](new Proxy(this.config.fields,new UT({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),S=Array.isArray(o)?o:[o];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=S;else this.config.orderBy=S}else{let o=T;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=o;else this.config.orderBy=o}return this}limit(T){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=T;else this.config.limit=T;return this}offset(T){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=T;else this.config.offset=T;return this}for(T,o={}){return this.config.lockingClause={strength:T,config:o},this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:T,...o}=this.dialect.sqlToQuery(this.getSQL());return o}as(T){return new Proxy(new xT(this.getSQL(),this.config.fields,T),new UT({alias:T,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new UT({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}}class G$ extends w1{static[M]="PgSelect";_prepare(T){let{session:o,config:S,dialect:f,joinsNotNullableMap:n,authToken:A}=this;if(!o)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");return yT.startActiveSpan("drizzle.prepareQuery",()=>{let $=_o(S.fields),F=o.prepareQuery(f.sqlToQuery(this.getSQL()),$,T,!0);return F.joinsNotNullableMap=n,F.setToken(A)})}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return yT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T,this.authToken)})}}dJ(G$,[To]);function dS(T,o){return(S,f,...n)=>{let A=[f,...n].map(($)=>({type:T,isAll:o,rightSelect:$}));for(let $ of A)if(!Df(S.getSelectedFields(),$.rightSelect.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return S.addSetOperators(A)}}var cM=()=>({union:rM,unionAll:PM,intersect:pM,intersectAll:iM,except:gM,exceptAll:dM}),rM=dS("union",!1),PM=dS("union",!0),pM=dS("intersect",!1),iM=dS("intersect",!0),gM=dS("except",!1),dM=dS("except",!0);class Nf{static[M]="PgQueryBuilder";dialect;dialectConfig;constructor(T){this.dialect=X(T,wS)?T:void 0,this.dialectConfig=X(T,wS)?void 0:T}$with=(T,o)=>{let S=this;return{as:(n)=>{if(typeof n==="function")n=n(S);return new Proxy(new Yf(n.getSQL(),o??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),T,!0),new UT({alias:T,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...T){let o=this;function S(A){return new oo({fields:A??void 0,session:void 0,dialect:o.getDialect(),withList:T})}function f(A){return new oo({fields:A??void 0,session:void 0,dialect:o.getDialect(),distinct:!0})}function n(A,$){return new oo({fields:$??void 0,session:void 0,dialect:o.getDialect(),distinct:{on:A}})}return{select:S,selectDistinct:f,selectDistinctOn:n}}select(T){return new oo({fields:T??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(T){return new oo({fields:T??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(T,o){return new oo({fields:o??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:T}})}getDialect(){if(!this.dialect)this.dialect=new wS(this.dialectConfig);return this.dialect}}class qn{constructor(T,o,S,f,n){this.table=T,this.session=o,this.dialect=S,this.withList=f,this.overridingSystemValue_=n}static[M]="PgInsertBuilder";authToken;setToken(T){return this.authToken=T,this}overridingSystemValue(){return this.overridingSystemValue_=!0,this}values(T){if(T=Array.isArray(T)?T:[T],T.length===0)throw new Error("values() must be called with at least one value");let o=T.map((S)=>{let f={},n=this.table[j.Symbol.Columns];for(let A of Object.keys(S)){let $=S[A];f[A]=X($,m)?$:new Ro($,n[A])}return f});return new Y$(this.table,o,this.session,this.dialect,this.withList,!1,this.overridingSystemValue_).setToken(this.authToken)}select(T){let o=typeof T==="function"?T(new Nf):T;if(!X(o,m)&&!Df(this.table[On],o._.selectedFields))throw new Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");return new Y$(this.table,o,this.session,this.dialect,this.withList,!0)}}class Y$ extends To{constructor(T,o,S,f,n,A,$){super();this.session=S,this.dialect=f,this.config={table:T,values:o,withList:n,select:A,overridingSystemValue_:$}}static[M]="PgInsert";config;returning(T=this.config.table[j.Symbol.Columns]){return this.config.returningFields=T,this.config.returning=_o(T),this}onConflictDoNothing(T={}){if(T.target===void 0)this.config.onConflict=k`do nothing`;else{let o="";o=Array.isArray(T.target)?T.target.map((f)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(f))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(T.target));let S=T.where?k` where ${T.where}`:void 0;this.config.onConflict=k`(${k.raw(o)})${S} do nothing`}return this}onConflictDoUpdate(T){if(T.where&&(T.targetWhere||T.setWhere))throw new Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');let o=T.where?k` where ${T.where}`:void 0,S=T.targetWhere?k` where ${T.targetWhere}`:void 0,f=T.setWhere?k` where ${T.setWhere}`:void 0,n=this.dialect.buildUpdateSet(this.config.table,wn(this.config.table,T.set)),A="";return A=Array.isArray(T.target)?T.target.map(($)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing($))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(T.target)),this.config.onConflict=k`(${k.raw(A)})${S} do update set ${n}${o}${f}`,this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:T,...o}=this.dialect.sqlToQuery(this.getSQL());return o}_prepare(T){return yT.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,T,!0)})}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return yT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new UT({alias:ZT(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class E$ extends To{constructor(T,o,S){super();this.session=o,this.dialect=S,this.config={view:T}}static[M]="PgRefreshMaterializedView";config;concurrently(){if(this.config.withNoData!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.concurrently=!0,this}withNoData(){if(this.config.concurrently!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.withNoData=!0,this}getSQL(){return this.dialect.buildRefreshMaterializedViewQuery(this.config)}toSQL(){let{typings:T,...o}=this.dialect.sqlToQuery(this.getSQL());return o}_prepare(T){return yT.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),void 0,T,!0)})}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return yT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T,this.authToken)})}}class Zn{constructor(T,o,S,f){this.table=T,this.session=o,this.dialect=S,this.withList=f}static[M]="PgUpdateBuilder";authToken;setToken(T){return this.authToken=T,this}set(T){return new X1(this.table,wn(this.table,T),this.session,this.dialect,this.withList).setToken(this.authToken)}}class X1 extends To{constructor(T,o,S,f,n){super();this.session=S,this.dialect=f,this.config={set:o,table:T,withList:n,joins:[]},this.tableName=co(T),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}static[M]="PgUpdate";config;tableName;joinsNotNullableMap;from(T){let o=T,S=co(o);if(typeof S==="string")this.joinsNotNullableMap[S]=!0;return this.config.from=o,this}getTableLikeFields(T){if(X(T,PT))return T[j.Symbol.Columns];else if(X(T,xT))return T._.selectedFields;return T[XT].selectedFields}createJoin(T){return(o,S)=>{let f=co(o);if(typeof f==="string"&&this.config.joins.some((n)=>n.alias===f))throw new Error(`Alias "${f}" is already used in this query`);if(typeof S==="function"){let n=this.config.from&&!X(this.config.from,m)?this.getTableLikeFields(this.config.from):void 0;S=S(new Proxy(this.config.table[j.Symbol.Columns],new UT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),n&&new Proxy(n,new UT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}if(this.config.joins.push({on:S,table:o,joinType:T,alias:f}),typeof f==="string")switch(T){case"left":{this.joinsNotNullableMap[f]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([n])=>[n,!1])),this.joinsNotNullableMap[f]=!0;break}case"inner":{this.joinsNotNullableMap[f]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([n])=>[n,!1])),this.joinsNotNullableMap[f]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(T){return this.config.where=T,this}returning(T){if(!T){if(T=Object.assign({},this.config.table[j.Symbol.Columns]),this.config.from){let o=co(this.config.from);if(typeof o==="string"&&this.config.from&&!X(this.config.from,m)){let S=this.getTableLikeFields(this.config.from);T[o]=S}for(let S of this.config.joins){let f=co(S.table);if(typeof f==="string"&&!X(S.table,m)){let n=this.getTableLikeFields(S.table);T[f]=n}}}}return this.config.returningFields=T,this.config.returning=_o(T),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:T,...o}=this.dialect.sqlToQuery(this.getSQL());return o}_prepare(T){let o=this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,T,!0);return o.joinsNotNullableMap=this.joinsNotNullableMap,o}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return this._prepare().execute(T,this.authToken)};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new UT({alias:ZT(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class hf extends m{constructor(T){super(hf.buildEmbeddedCount(T.source,T.filters).queryChunks);this.params=T,this.mapWith(Number),this.session=T.session,this.sql=hf.buildCount(T.source,T.filters)}sql;token;static[M]="PgCountBuilder";[Symbol.toStringTag]="PgCountBuilder";session;static buildEmbeddedCount(T,o){return k`(select count(*) from ${T}${k.raw(" where ").if(o)}${o})`}static buildCount(T,o){return k`select count(*) as count from ${T}${k.raw(" where ").if(o)}${o};`}setToken(T){return this.token=T,this}then(T,o){return Promise.resolve(this.session.count(this.sql,this.token)).then(T,o)}catch(T){return this.then(void 0,T)}finally(T){return this.then((o)=>{return T?.(),o},(o)=>{throw T?.(),o})}}class z${constructor(T,o,S,f,n,A,$){this.fullSchema=T,this.schema=o,this.tableNamesMap=S,this.table=f,this.tableConfig=n,this.dialect=A,this.session=$}static[M]="PgRelationalQueryBuilder";findMany(T){return new H$(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,T?T:{},"many")}findFirst(T){return new H$(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,T?{...T,limit:1}:{limit:1},"first")}}class H$ extends To{constructor(T,o,S,f,n,A,$,F,J){super();this.fullSchema=T,this.schema=o,this.tableNamesMap=S,this.table=f,this.tableConfig=n,this.dialect=A,this.session=$,this.config=F,this.mode=J}static[M]="PgRelationalQuery";_prepare(T){return yT.startActiveSpan("drizzle.prepareQuery",()=>{let{query:o,builtQuery:S}=this._toSQL();return this.session.prepareQuery(S,void 0,T,!0,(f,n)=>{let A=f.map(($)=>tn(this.schema,this.tableConfig,$,o.selection,n));if(this.mode==="first")return A[0];return A})})}prepare(T){return this._prepare(T)}_getQuery(){return this.dialect.buildRelationalQueryWithoutPK({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName})}getSQL(){return this._getQuery().sql}_toSQL(){let T=this._getQuery(),o=this.dialect.sqlToQuery(T.sql);return{query:T,builtQuery:o}}toSQL(){return this._toSQL().builtQuery}authToken;setToken(T){return this.authToken=T,this}execute(){return yT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(void 0,this.authToken)})}}class Q$ extends To{constructor(T,o,S,f){super();this.execute=T,this.sql=o,this.query=S,this.mapBatchResult=f}static[M]="PgRaw";getSQL(){return this.sql}getQuery(){return this.query}mapResult(T,o){return o?this.mapBatchResult(T):T}_prepare(){return this}isResponseInArrayMode(){return!1}}class bf{constructor(T,o,S){if(this.dialect=T,this.session=o,this._=S?{schema:S.schema,fullSchema:S.fullSchema,tableNamesMap:S.tableNamesMap,session:o}:{schema:void 0,fullSchema:{},tableNamesMap:{},session:o},this.query={},this._.schema)for(let[f,n]of Object.entries(this._.schema))this.query[f]=new z$(S.fullSchema,this._.schema,this._.tableNamesMap,S.fullSchema[f],n,T,o)}static[M]="PgDatabase";query;$with=(T,o)=>{let S=this;return{as:(n)=>{if(typeof n==="function")n=n(new Nf(S.dialect));return new Proxy(new Yf(n.getSQL(),o??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),T,!0),new UT({alias:T,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(T,o){return new hf({source:T,filters:o,session:this.session})}with(...T){let o=this;function S(J){return new oo({fields:J??void 0,session:o.session,dialect:o.dialect,withList:T})}function f(J){return new oo({fields:J??void 0,session:o.session,dialect:o.dialect,withList:T,distinct:!0})}function n(J,R){return new oo({fields:R??void 0,session:o.session,dialect:o.dialect,withList:T,distinct:{on:J}})}function A(J){return new Zn(J,o.session,o.dialect,T)}function $(J){return new qn(J,o.session,o.dialect,T)}function F(J){return new vn(J,o.session,o.dialect,T)}return{select:S,selectDistinct:f,selectDistinctOn:n,update:A,insert:$,delete:F}}select(T){return new oo({fields:T??void 0,session:this.session,dialect:this.dialect})}selectDistinct(T){return new oo({fields:T??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(T,o){return new oo({fields:o??void 0,session:this.session,dialect:this.dialect,distinct:{on:T}})}update(T){return new Zn(T,this.session,this.dialect)}insert(T){return new qn(T,this.session,this.dialect)}delete(T){return new vn(T,this.session,this.dialect)}refreshMaterializedView(T){return new E$(T,this.session,this.dialect)}authToken;execute(T){let o=typeof T==="string"?k.raw(T):T.getSQL(),S=this.dialect.sqlToQuery(o),f=this.session.prepareQuery(S,void 0,void 0,!1);return new Q$(()=>f.execute(void 0,this.authToken),o,S,(n)=>f.mapResult(n,!0))}transaction(T,o){return this.session.transaction(T,o)}}class K1{constructor(T,o){this.unique=T,this.name=o}static[M]="PgIndexBuilderOn";on(...T){return new cn(T.map((o)=>{if(X(o,m))return o;o=o;let S=new Gf(o.name,!!o.keyAsName,o.columnType,o.indexConfig);return o.indexConfig=JSON.parse(JSON.stringify(o.defaultConfig)),S}),this.unique,!1,this.name)}onOnly(...T){return new cn(T.map((o)=>{if(X(o,m))return o;o=o;let S=new Gf(o.name,!!o.keyAsName,o.columnType,o.indexConfig);return o.indexConfig=o.defaultConfig,S}),this.unique,!0,this.name)}using(T,...o){return new cn(o.map((S)=>{if(X(S,m))return S;S=S;let f=new Gf(S.name,!!S.keyAsName,S.columnType,S.indexConfig);return S.indexConfig=JSON.parse(JSON.stringify(S.defaultConfig)),f}),this.unique,!0,this.name,T)}}class cn{static[M]="PgIndexBuilder";config;constructor(T,o,S,f,n="btree"){this.config={name:f,columns:T,unique:o,only:S,method:n}}concurrently(){return this.config.concurrently=!0,this}with(T){return this.config.with=T,this}where(T){return this.config.where=T,this}build(T){return new G1(this.config,T)}}class G1{static[M]="PgIndex";config;constructor(T,o){this.config={...T,table:o}}}function D$(T){return new K1(!0,T)}class U${constructor(T){this.query=T}authToken;getQuery(){return this.query}mapResult(T,o){return T}setToken(T){return this.authToken=T,this}static[M]="PgPreparedQuery";joinsNotNullableMap}class t${constructor(T){this.dialect=T}static[M]="PgSession";execute(T,o){return yT.startActiveSpan("drizzle.operation",()=>{return yT.startActiveSpan("drizzle.prepareQuery",()=>{return this.prepareQuery(this.dialect.sqlToQuery(T),void 0,void 0,!1)}).setToken(o).execute(void 0,o)})}all(T){return this.prepareQuery(this.dialect.sqlToQuery(T),void 0,void 0,!1).all()}async count(T,o){let S=await this.execute(T,o);return Number(S[0].count)}}class V$ extends bf{constructor(T,o,S,f=0){super(T,o,S);this.schema=S,this.nestedIndex=f}static[M]="PgTransaction";rollback(){throw new gA}getTransactionConfigSQL(T){let o=[];if(T.isolationLevel)o.push(`isolation level ${T.isolationLevel}`);if(T.accessMode)o.push(T.accessMode);if(typeof T.deferrable==="boolean")o.push(T.deferrable?"deferrable":"not deferrable");return k.raw(o.join(" "))}setTransaction(T){return this.session.execute(k`set transaction ${this.getTransactionConfigSQL(T)}`)}}class Y1 extends U${constructor(T,o,S,f,n,A,$){super({sql:o,params:S});this.client=T,this.queryString=o,this.params=S,this.logger=f,this.fields=n,this._isResponseInArrayMode=A,this.customResultMapper=$}static[M]="PostgresJsPreparedQuery";async execute(T={}){return yT.startActiveSpan("drizzle.execute",async(o)=>{let S=pA(this.params,T);o?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(S)}),this.logger.logQuery(this.queryString,S);let{fields:f,queryString:n,client:A,joinsNotNullableMap:$,customResultMapper:F}=this;if(!f&&!F)return yT.startActiveSpan("drizzle.driver.execute",()=>{return A.unsafe(n,S)});let J=await yT.startActiveSpan("drizzle.driver.execute",()=>{return o?.setAttributes({"drizzle.query.text":n,"drizzle.query.params":JSON.stringify(S)}),A.unsafe(n,S).values()});return yT.startActiveSpan("drizzle.mapResponse",()=>{return F?F(J):J.map((R)=>gJ(f,R,$))})})}all(T={}){return yT.startActiveSpan("drizzle.execute",async(o)=>{let S=pA(this.params,T);return o?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(S)}),this.logger.logQuery(this.queryString,S),yT.startActiveSpan("drizzle.driver.execute",()=>{return o?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(S)}),this.client.unsafe(this.queryString,S)})})}isResponseInArrayMode(){return this._isResponseInArrayMode}}class xf extends t${constructor(T,o,S,f={}){super(o);this.client=T,this.schema=S,this.options=f,this.logger=f.logger??new lA}static[M]="PostgresJsSession";logger;prepareQuery(T,o,S,f,n){return new Y1(this.client,T.sql,T.params,this.logger,o,f,n)}query(T,o){return this.logger.logQuery(T,o),this.client.unsafe(T,o).values()}queryObjects(T,o){return this.client.unsafe(T,o)}transaction(T,o){return this.client.begin(async(S)=>{let f=new xf(S,this.dialect,this.schema,this.options),n=new B$(this.dialect,f,this.schema);if(o)await n.setTransaction(o);return T(n)})}}class B$ extends V${constructor(T,o,S,f=0){super(T,o,S,f);this.session=o}static[M]="PostgresJsTransaction";transaction(T){return this.session.client.savepoint((o)=>{let S=new xf(o,this.dialect,this.schema,this.session.options),f=new B$(this.dialect,S,this.schema);return T(f)})}}class E1 extends bf{static[M]="PostgresJsDatabase"}function lS(T,o={}){let S=(J)=>J;for(let J of["1184","1082","1083","1114"])T.options.parsers[J]=S,T.options.serializers[J]=S;T.options.serializers["114"]=S,T.options.serializers["3802"]=S;let f=new wS({casing:o.casing}),n;if(o.logger===!0)n=new dA;else if(o.logger!==!1)n=o.logger;let A;if(o.schema){let J=g0(o.schema,l0);A={fullSchema:o.schema,schema:J.tables,tableNamesMap:J.tableNamesMap}}let $=new xf(T,f,A,{logger:n}),F=new E1(f,$,A);return F.$client=T,F}function rn(...T){if(typeof T[0]==="string"){let o=gS(T[0]);return lS(o,T[1])}if(uJ(T[0])){let{connection:o,client:S,...f}=T[0];if(S)return lS(S,f);if(typeof o==="object"&&o.url!==void 0){let{url:A,...$}=o,F=gS(A,$);return lS(F,f)}let n=gS(o);return lS(n,f)}return lS(T[0],T[1])}((T)=>{function o(S){return lS({options:{parsers:{},serializers:{}}},S)}T.mock=o})(rn||(rn={}));var C$={};UW(C$,{users:()=>XS,userChanges:()=>uM,untrackedUserColumnNames:()=>lM,twoFactorMethod:()=>U1,trackedUserColumnName:()=>D1,trackableUserColumnNames:()=>Q1,role:()=>z1,players:()=>L$,passwordResetAttempts:()=>aM,loginHistory:()=>eM,games:()=>Pn,banishedIps:()=>sM});function H1(T){return k`lower(${T})`}var z1=Rn("role",["admin","user"]),XS=oS("users",{id:Wo().primaryKey().defaultRandom(),username:rT({length:16}).notNull(),email:rT({length:254}).notNull(),hash:rT({length:64}).notNull(),salt:rT({length:36}).notNull(),createdAt:to({withTimezone:!0}).notNull().defaultNow(),createdIp:rT({length:45}).notNull(),isActive:Uf().notNull().default(!1),verifiedAt:to({withTimezone:!0}),userRole:z1().default("user")},(T)=>[D$("usernameUniqueIndex").on(H1(T.username)),D$("emailUniqueIndex").on(H1(T.email))]),lM=["id","createdAt","createdIp","isActive","salt","verifiedAt"],Q1=["username","email","hash","userRole"],D1=Rn("trackedUserColumnName",Q1),uM=oS("userChanges",{id:Wo().primaryKey().defaultRandom(),userId:Wo().notNull().references(()=>XS.id),changedAt:to({withTimezone:!0}).notNull().defaultNow(),changedIp:rT({length:45}).notNull(),changedColumn:D1().notNull(),oldValue:rT({length:255}),newValue:rT({length:255})}),Pn=oS("games",{id:Wo().primaryKey().defaultRandom()}),L$=oS("players",{userId:Wo().notNull().references(()=>XS.id),gameId:Wo().notNull().references(()=>Pn.id),score:Gn().notNull()},(T)=>[c0({name:"players_userId_gameId_pk",columns:[T.userId,T.gameId]})]),eM=oS("loginHistory",{id:Wo().primaryKey().defaultRandom(),userId:Wo().references(()=>XS.id),loginTime:to({withTimezone:!0}).notNull().defaultNow(),ipAddress:rT({length:45}).notNull(),userAgent:rT({length:1024}),successful:Uf().notNull().default(!1)}),U1=Rn("twoFactorMethod",["email","phone"]),aM=oS("passwordResetAttempts",{id:Wo().primaryKey().defaultRandom(),userId:Wo().notNull().references(()=>XS.id),requestedIp:rT({length:45}).notNull(),requestedAt:to({withTimezone:!0}).notNull().defaultNow(),succeededIp:rT({length:45}),succeededAt:to({withTimezone:!0}),verificationMethod:U1().notNull()}),sM=oS("banishedIps",{ip:rT({length:45}).primaryKey(),reason:rT({length:2048}).notNull(),banishedAt:to({withTimezone:!0}).notNull().defaultNow(),banishedUntil:to({withTimezone:!0})});var __dirname="/home/runner/work/wayforge/wayforge/apps/tempest.games/src/database";class I${options;sql;drizzle;observers=new Map;async setupTriggersAndNotifications(){await this.sql.file(Tk.resolve(__dirname,"notify_update.sql"));let T=[ZT(XS),ZT(Pn),ZT(L$)];await this.sql`SELECT create_notify_triggers(${this.sql.array(T)})`,await this.sql.listen("table_update",(o)=>{let S=o.split(","),f=S[0],n=S[1],A=`${f}("${n}")`;if(this.observers.has(A))this.observers.get(A).next(A)})}constructor(T=!1,o={host:Do.POSTGRES_HOST,port:Do.POSTGRES_PORT,user:Do.POSTGRES_USER,password:Do.POSTGRES_PASSWORD,database:Do.POSTGRES_DATABASE}){this.options=o,this.sql=gS(o),this.drizzle=rn(this.sql,{schema:C$,logger:T})}observe(T,o){if(!this.observers.has(T))this.observers.set(T,new ST);this.observers.get(T).subscribe("SINGLETON",o)}}var pn={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"},j$=i$(pn).map(([T])=>YT.literal(Number(T))),ok=YT.union([j$[0],j$[1],...j$]),t1=YT.tuple([ok,YT.string()]);var N$=new DA,{logger:Fo}=N$;Object.assign(console,Fo,{log:Fo.info});Fo.info("ready");var m$=B1(import.meta.dir,"..","app"),l3=new I$({logQuery(T,o){Fo.info("\uD83D\uDCDD query",T,o)}});nk({hostname:"0.0.0.0",port:Do.FRONTEND_PORT??3333,...JJ??void 0,async fetch(T){try{let o=new Date,S=new URL(T.url);if(Fo.info(T.method,S.pathname),S.pathname==="/")return new Response(Bun.file(B1(m$,"index.html")));if(S.pathname==="/index.html")return Response.redirect("/");let f=Sk(m$,S.pathname),n=fk(f);if(!n.startsWith(m$))throw[403,"Access Denied"];if(!await V1(n).exists())return Response.redirect("/");return new Response(V1(n))}catch(o){let S=t1.safeParse(o);if(S.success){let[f,n]=S.data,$=`${pn[f]}. ${n}`;return Fo.info(`\u274C ${f}: ${$}`),new Response($,{status:f})}if(o instanceof Error)Fo.error(o.message);else{let f=DS(o);Fo.error("frontend server threw",f)}return new Response(pn[500],{status:500})}}});function gn(){Fo.info("\uD83D\uDEEC frontend server exiting"),process.exit(0)}process.on("SIGINT",()=>{Fo.info("\u2757 received SIGINT; exiting gracefully"),gn()});process.on("SIGTERM",()=>{Fo.info("\u2757 received SIGTERM; exiting gracefully"),gn()});process.on("exit",()=>{Fo.info("\u2757 received exit; exiting gracefully"),gn()});N$.on("timeToStop",()=>{Fo.info('\u2757 backend server received signal "timeToStop"; exiting gracefully'),gn()});Fo.info(`\uD83D\uDEEB frontend server running at http://localhost:${Do.FRONTEND_PORT}/`);N$.emit("alive");
43
+ `;await T.execute(k`CREATE SCHEMA IF NOT EXISTS ${k.identifier(n)}`),await T.execute(A);let F=(await T.all(k`select id, hash, created_at from ${k.identifier(n)}.${k.identifier(S)} order by created_at desc limit 1`))[0];await T.transaction(async(J)=>{for await(let R of o)if(!F||Number(F.created_at)<R.folderMillis){for(let M of R.sql)await J.execute(k.raw(M));await J.execute(k`insert into ${k.identifier(n)}.${k.identifier(S)} ("hash", "created_at") values(${R.hash}, ${R.folderMillis})`)}})}escapeName(o){return`"${o}"`}escapeParam(o){return`$${o+1}`}escapeString(o){return`'${o.replace(/'/g,"''")}'`}buildWithCTE(o){if(!o?.length)return;let T=[k`with `];for(let[f,S]of o.entries())if(T.push(k`${k.identifier(S._.alias)} as (${S._.sql})`),f<o.length-1)T.push(k`, `);return T.push(k` `),k.join(T)}buildDeleteQuery({table:o,where:T,returning:f,withList:S}){let n=this.buildWithCTE(S),A=f?k` returning ${this.buildSelection(f,{isSingleTable:!0})}`:void 0,$=T?k` where ${T}`:void 0;return k`${n}delete from ${o}${$}${A}`}buildUpdateSet(o,T){let f=o[j.Symbol.Columns],S=Object.keys(f).filter((A)=>T[A]!==void 0||f[A]?.onUpdateFn!==void 0),n=S.length;return k.join(S.flatMap((A,$)=>{let F=f[A],J=T[A]??k.param(F.onUpdateFn(),F),R=k`${k.identifier(this.casing.getColumnCasing(F))} = ${J}`;if($<n-1)return[R,k.raw(", ")];return[R]}))}buildUpdateQuery({table:o,set:T,where:f,returning:S,withList:n,from:A,joins:$}){let F=this.buildWithCTE(n),J=o[po.Symbol.Name],R=o[po.Symbol.Schema],M=o[po.Symbol.OriginalName],_=J===M?void 0:J,w=k`${R?k`${k.identifier(R)}.`:void 0}${k.identifier(M)}${_&&k` ${k.identifier(_)}`}`,X=this.buildUpdateSet(o,T),U=A&&k.join([k.raw(" from "),this.buildFromTable(A)]),K=this.buildJoins($),L=S?k` returning ${this.buildSelection(S,{isSingleTable:!A})}`:void 0,h=f?k` where ${f}`:void 0;return k`${F}update ${w} set ${X}${U}${K}${h}${L}`}buildSelection(o,{isSingleTable:T=!1}={}){let f=o.length,S=o.flatMap(({field:n},A)=>{let $=[];if(H(n,m.Aliased)&&n.isSelectionField)$.push(k.identifier(n.fieldAlias));else if(H(n,m.Aliased)||H(n,m)){let F=H(n,m.Aliased)?n.sql:n;if(T)$.push(new m(F.queryChunks.map((J)=>{if(H(J,V))return k.identifier(this.casing.getColumnCasing(J));return J})));else $.push(F);if(H(n,m.Aliased))$.push(k` as ${k.identifier(n.fieldAlias)}`)}else if(H(n,_o))if(T)$.push(k.identifier(this.casing.getColumnCasing(n)));else $.push(n);if(A<f-1)$.push(k`, `);return $});return k.join(S)}buildJoins(o){if(!o||o.length===0)return;let T=[];for(let[f,S]of o.entries()){if(f===0)T.push(k` `);let n=S.table,A=S.lateral?k` lateral`:void 0;if(H(n,po)){let $=n[po.Symbol.Name],F=n[po.Symbol.Schema],J=n[po.Symbol.OriginalName],R=$===J?void 0:S.alias;T.push(k`${k.raw(S.joinType)} join${A} ${F?k`${k.identifier(F)}.`:void 0}${k.identifier(J)}${R&&k` ${k.identifier(R)}`} on ${S.on}`)}else if(H(n,nT)){let $=n[Ho].name,F=n[Ho].schema,J=n[Ho].originalName,R=$===J?void 0:S.alias;T.push(k`${k.raw(S.joinType)} join${A} ${F?k`${k.identifier(F)}.`:void 0}${k.identifier(J)}${R&&k` ${k.identifier(R)}`} on ${S.on}`)}else T.push(k`${k.raw(S.joinType)} join${A} ${n} on ${S.on}`);if(f<o.length-1)T.push(k` `)}return k.join(T)}buildFromTable(o){if(H(o,j)&&o[j.Symbol.OriginalName]!==o[j.Symbol.Name]){let T=k`${k.identifier(o[j.Symbol.OriginalName])}`;if(o[j.Symbol.Schema])T=k`${k.identifier(o[j.Symbol.Schema])}.${T}`;return k`${T} ${k.identifier(o[j.Symbol.Name])}`}return o}buildSelectQuery({withList:o,fields:T,fieldsFlat:f,where:S,having:n,table:A,joins:$,orderBy:F,groupBy:J,limit:R,offset:M,lockingClause:_,distinct:w,setOperators:X}){let U=f??wT(T);for(let a of U)if(H(a.field,_o)&&qo(a.field.table)!==(H(A,bo)?A._.alias:H(A,hS)?A[Ho].name:H(A,m)?void 0:qo(A))&&!((ko)=>$?.some(({alias:Lo})=>Lo===(ko[j.Symbol.IsAlias]?qo(ko):ko[j.Symbol.BaseName])))(a.field.table)){let ko=qo(a.field.table);throw new Error(`Your "${a.path.join("->")}" field references a column "${ko}"."${a.field.name}", but the table "${ko}" is not part of the query! Did you forget to join it?`)}let K=!$||$.length===0,L=this.buildWithCTE(o),h;if(w)h=w===!0?k` distinct`:k` distinct on (${k.join(w.on,k`, `)})`;let q=this.buildSelection(U,{isSingleTable:K}),P=this.buildFromTable(A),Y=this.buildJoins($),Q=S?k` where ${S}`:void 0,t=n?k` having ${n}`:void 0,D;if(F&&F.length>0)D=k` order by ${k.join(F,k`, `)}`;let v;if(J&&J.length>0)v=k` group by ${k.join(J,k`, `)}`;let l=typeof R==="object"||typeof R==="number"&&R>=0?k` limit ${R}`:void 0,G=M?k` offset ${M}`:void 0,s=k.empty();if(_){let a=k` for ${k.raw(_.strength)}`;if(_.config.of)a.append(k` of ${k.join(Array.isArray(_.config.of)?_.config.of:[_.config.of],k`, `)}`);if(_.config.noWait)a.append(k` no wait`);else if(_.config.skipLocked)a.append(k` skip locked`);s.append(a)}let r=k`${L}select${h} ${q} from ${P}${Y}${Q}${v}${t}${D}${l}${G}${s}`;if(X.length>0)return this.buildSetOperations(r,X);return r}buildSetOperations(o,T){let[f,...S]=T;if(!f)throw new Error("Cannot pass undefined values to any set operator");if(S.length===0)return this.buildSetOperationQuery({leftSelect:o,setOperator:f});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:o,setOperator:f}),S)}buildSetOperationQuery({leftSelect:o,setOperator:{type:T,isAll:f,rightSelect:S,limit:n,orderBy:A,offset:$}}){let F=k`(${o.getSQL()}) `,J=k`(${S.getSQL()})`,R;if(A&&A.length>0){let X=[];for(let U of A)if(H(U,V))X.push(k.identifier(U.name));else if(H(U,m)){for(let K=0;K<U.queryChunks.length;K++){let L=U.queryChunks[K];if(H(L,V))U.queryChunks[K]=k.identifier(L.name)}X.push(k`${U}`)}else X.push(k`${U}`);R=k` order by ${k.join(X,k`, `)} `}let M=typeof n==="object"||typeof n==="number"&&n>=0?k` limit ${n}`:void 0,_=k.raw(`${T} ${f?"all ":""}`),w=$?k` offset ${$}`:void 0;return k`${F}${_}${J}${R}${M}${w}`}buildInsertQuery({table:o,values:T,onConflict:f,returning:S,withList:n,select:A,overridingSystemValue_:$}){let F=[],J=o[j.Symbol.Columns],R=Object.entries(J).filter(([L,h])=>!h.shouldDisableInsert()),M=R.map(([,L])=>k.identifier(this.casing.getColumnCasing(L)));if(A){let L=T;if(H(L,m))F.push(L);else F.push(L.getSQL())}else{let L=T;F.push(k.raw("values "));for(let[h,q]of L.entries()){let P=[];for(let[Y,Q]of R){let t=q[Y];if(t===void 0||H(t,RT)&&t.value===void 0)if(Q.defaultFn!==void 0){let D=Q.defaultFn(),v=H(D,m)?D:k.param(D,Q);P.push(v)}else if(!Q.default&&Q.onUpdateFn!==void 0){let D=Q.onUpdateFn(),v=H(D,m)?D:k.param(D,Q);P.push(v)}else P.push(k`default`);else P.push(t)}if(F.push(P),h<L.length-1)F.push(k`, `)}}let _=this.buildWithCTE(n),w=k.join(F),X=S?k` returning ${this.buildSelection(S,{isSingleTable:!0})}`:void 0,U=f?k` on conflict ${f}`:void 0,K=$===!0?k`overriding system value `:void 0;return k`${_}insert into ${o} ${M} ${K}${w}${U}${X}`}buildRefreshMaterializedViewQuery({view:o,concurrently:T,withNoData:f}){let S=T?k` concurrently`:void 0,n=f?k` with no data`:void 0;return k`refresh materialized view${S} ${o}${n}`}prepareTyping(o){if(H(o,zn)||H(o,En))return"json";else if(H(o,Qn))return"decimal";else if(H(o,Dn))return"time";else if(H(o,Un)||H(o,tn))return"timestamp";else if(H(o,Kn)||H(o,Gn))return"date";else if(H(o,Vn))return"uuid";else return"none"}sqlToQuery(o,T){return o.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,prepareTyping:this.prepareTyping,invokeSource:T})}buildRelationalQueryWithoutPK({fullSchema:o,schema:T,tableNamesMap:f,table:S,tableConfig:n,queryConfig:A,tableAlias:$,nestedQueryRelation:F,joinOn:J}){let R=[],M,_,w=[],X,U=[];if(A===!0)R=Object.entries(n.columns).map(([h,q])=>({dbKey:q.name,tsKey:h,field:CT(q,$),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let L=Object.fromEntries(Object.entries(n.columns).map(([t,D])=>[t,CT(D,$)]));if(A.where){let t=typeof A.where==="function"?A.where(L,g0()):A.where;X=t&&DS(t,$)}let h=[],q=[];if(A.columns){let t=!1;for(let[D,v]of Object.entries(A.columns)){if(v===void 0)continue;if(D in n.columns){if(!t&&v===!0)t=!0;q.push(D)}}if(q.length>0)q=t?q.filter((D)=>A.columns?.[D]===!0):Object.keys(n.columns).filter((D)=>!q.includes(D))}else q=Object.keys(n.columns);for(let t of q){let D=n.columns[t];h.push({tsKey:t,value:D})}let P=[];if(A.with)P=Object.entries(A.with).filter((t)=>!!t[1]).map(([t,D])=>({tsKey:t,queryConfig:D,relation:n.relations[t]}));let Y;if(A.extras){Y=typeof A.extras==="function"?A.extras(L,{sql:k}):A.extras;for(let[t,D]of Object.entries(Y))h.push({tsKey:t,value:PA(D,$)})}for(let{tsKey:t,value:D}of h)R.push({dbKey:H(D,m.Aliased)?D.fieldAlias:n.columns[t].name,tsKey:t,field:H(D,_o)?CT(D,$):D,relationTableTsKey:void 0,isJson:!1,selection:[]});let Q=typeof A.orderBy==="function"?A.orderBy(L,d0()):A.orderBy??[];if(!Array.isArray(Q))Q=[Q];w=Q.map((t)=>{if(H(t,_o))return CT(t,$);return DS(t,$)}),M=A.limit,_=A.offset;for(let{tsKey:t,queryConfig:D,relation:v}of P){let l=u0(T,f,v),G=Of(v.referencedTable),s=f[G],r=`${$}_${t}`,a=US(...l.fields.map((fT,jT)=>Xn(CT(l.references[jT],r),CT(fT,$)))),ko=this.buildRelationalQueryWithoutPK({fullSchema:o,schema:T,tableNamesMap:f,table:o[s],tableConfig:T[s],queryConfig:H(v,aT)?D===!0?{limit:1}:{...D,limit:1}:D,tableAlias:r,joinOn:a,nestedQueryRelation:v}),Lo=k`${k.identifier(r)}.${k.identifier("data")}`.as(t);U.push({on:k`true`,table:new bo(ko.sql,{},r),alias:r,joinType:"left",lateral:!0}),R.push({dbKey:t,tsKey:t,field:Lo,relationTableTsKey:s,isJson:!0,selection:ko.selection})}}if(R.length===0)throw new yn({message:`No fields selected for table "${n.tsName}" ("${$}")`});let K;if(X=US(J,X),F){let L=k`json_build_array(${k.join(R.map(({field:P,tsKey:Y,isJson:Q})=>Q?k`${k.identifier(`${$}_${Y}`)}.${k.identifier("data")}`:H(P,m.Aliased)?P.sql:P),k`, `)})`;if(H(F,LS))L=k`coalesce(json_agg(${L}${w.length>0?k` order by ${k.join(w,k`, `)}`:void 0}), '[]'::json)`;let h=[{dbKey:"data",tsKey:"data",field:L.as("data"),isJson:!0,relationTableTsKey:n.tsName,selection:R}];if(M!==void 0||_!==void 0||w.length>0)K=this.buildSelectQuery({table:wn(S,$),fields:{},fieldsFlat:[{path:[],field:k.raw("*")}],where:X,limit:M,offset:_,orderBy:w,setOperators:[]}),X=void 0,M=void 0,_=void 0,w=[];else K=wn(S,$);K=this.buildSelectQuery({table:H(K,po)?K:new bo(K,{},$),fields:{},fieldsFlat:h.map(({field:P})=>({path:[],field:H(P,_o)?CT(P,$):P})),joins:U,where:X,limit:M,offset:_,orderBy:w,setOperators:[]})}else K=this.buildSelectQuery({table:wn(S,$),fields:{},fieldsFlat:R.map(({field:L})=>({path:[],field:H(L,_o)?CT(L,$):L})),joins:U,where:X,limit:M,offset:_,orderBy:w,setOperators:[]});return{tableTsKey:n.tsName,sql:K,selection:R}}}class X${static[O]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class TT{static[O]="PgSelectBuilder";fields;session;dialect;withList=[];distinct;constructor(o){if(this.fields=o.fields,this.session=o.session,this.dialect=o.dialect,o.withList)this.withList=o.withList;this.distinct=o.distinct}authToken;setToken(o){return this.authToken=o,this}from(o){let T=!!this.fields,f=o,S;if(this.fields)S=this.fields;else if(H(f,bo))S=Object.fromEntries(Object.keys(f._.selectedFields).map((n)=>[n,f[n]]));else if(H(f,hS))S=f[Ho].selectedFields;else if(H(f,m))S={};else S=eJ(f);return new H$({table:f,fields:S,isPartialSelect:T,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}}class H1 extends X${static[O]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;constructor({table:o,fields:T,isPartialSelect:f,session:S,dialect:n,withList:A,distinct:$}){super();this.config={withList:A,table:o,fields:{...T},distinct:$,setOperators:[]},this.isPartialSelect=f,this.session=S,this.dialect=n,this._={selectedFields:T},this.tableName=rT(o),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}createJoin(o){return(T,f)=>{let S=this.tableName,n=rT(T);if(typeof n==="string"&&this.config.joins?.some((A)=>A.alias===n))throw new Error(`Alias "${n}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof S==="string")this.config.fields={[S]:this.config.fields};if(typeof n==="string"&&!H(T,m)){let A=H(T,bo)?T._.selectedFields:H(T,nT)?T[Ho].selectedFields:T[j.Symbol.Columns];this.config.fields[n]=A}}if(typeof f==="function")f=f(new Proxy(this.config.fields,new Uo({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:f,table:T,joinType:o,alias:n}),typeof n==="string")switch(o){case"left":{this.joinsNotNullableMap[n]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([A])=>[A,!1])),this.joinsNotNullableMap[n]=!0;break}case"inner":{this.joinsNotNullableMap[n]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([A])=>[A,!1])),this.joinsNotNullableMap[n]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");createSetOperator(o,T){return(f)=>{let S=typeof f==="function"?f(rO()):f;if(!tS(this.getSelectedFields(),S.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return this.config.setOperators.push({type:o,isAll:T,rightSelect:S}),this}}union=this.createSetOperator("union",!1);unionAll=this.createSetOperator("union",!0);intersect=this.createSetOperator("intersect",!1);intersectAll=this.createSetOperator("intersect",!0);except=this.createSetOperator("except",!1);exceptAll=this.createSetOperator("except",!0);addSetOperators(o){return this.config.setOperators.push(...o),this}where(o){if(typeof o==="function")o=o(new Proxy(this.config.fields,new Uo({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=o,this}having(o){if(typeof o==="function")o=o(new Proxy(this.config.fields,new Uo({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=o,this}groupBy(...o){if(typeof o[0]==="function"){let T=o[0](new Proxy(this.config.fields,new Uo({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(T)?T:[T]}else this.config.groupBy=o;return this}orderBy(...o){if(typeof o[0]==="function"){let T=o[0](new Proxy(this.config.fields,new Uo({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),f=Array.isArray(T)?T:[T];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=f;else this.config.orderBy=f}else{let T=o;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=T;else this.config.orderBy=T}return this}limit(o){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=o;else this.config.limit=o;return this}offset(o){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=o;else this.config.offset=o;return this}for(o,T={}){return this.config.lockingClause={strength:o,config:T},this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:o,...T}=this.dialect.sqlToQuery(this.getSQL());return T}as(o){return new Proxy(new bo(this.getSQL(),this.config.fields,o),new Uo({alias:o,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new Uo({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}}class H$ extends H1{static[O]="PgSelect";_prepare(o){let{session:T,config:f,dialect:S,joinsNotNullableMap:n,authToken:A}=this;if(!T)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");return wo.startActiveSpan("drizzle.prepareQuery",()=>{let $=wT(f.fields),F=T.prepareQuery(S.sqlToQuery(this.getSQL()),$,o,!0);return F.joinsNotNullableMap=n,F.setToken(A)})}prepare(o){return this._prepare(o)}authToken;setToken(o){return this.authToken=o,this}execute=(o)=>{return wo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(o,this.authToken)})}}uJ(H$,[oT]);function uf(o,T){return(f,S,...n)=>{let A=[S,...n].map(($)=>({type:o,isAll:T,rightSelect:$}));for(let $ of A)if(!tS(f.getSelectedFields(),$.rightSelect.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return f.addSetOperators(A)}}var rO=()=>({union:ZO,unionAll:pO,intersect:cO,intersectAll:PO,except:iO,exceptAll:gO}),ZO=uf("union",!1),pO=uf("union",!0),cO=uf("intersect",!1),PO=uf("intersect",!0),iO=uf("except",!1),gO=uf("except",!0);class bS{static[O]="PgQueryBuilder";dialect;dialectConfig;constructor(o){this.dialect=H(o,Xf)?o:void 0,this.dialectConfig=H(o,Xf)?void 0:o}$with=(o,T)=>{let f=this;return{as:(n)=>{if(typeof n==="function")n=n(f);return new Proxy(new ES(n.getSQL(),T??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),o,!0),new Uo({alias:o,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...o){let T=this;function f(A){return new TT({fields:A??void 0,session:void 0,dialect:T.getDialect(),withList:o})}function S(A){return new TT({fields:A??void 0,session:void 0,dialect:T.getDialect(),distinct:!0})}function n(A,$){return new TT({fields:$??void 0,session:void 0,dialect:T.getDialect(),distinct:{on:A}})}return{select:f,selectDistinct:S,selectDistinctOn:n}}select(o){return new TT({fields:o??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(o){return new TT({fields:o??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(o,T){return new TT({fields:T??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:o}})}getDialect(){if(!this.dialect)this.dialect=new Xf(this.dialectConfig);return this.dialect}}class Zn{constructor(o,T,f,S,n){this.table=o,this.session=T,this.dialect=f,this.withList=S,this.overridingSystemValue_=n}static[O]="PgInsertBuilder";authToken;setToken(o){return this.authToken=o,this}overridingSystemValue(){return this.overridingSystemValue_=!0,this}values(o){if(o=Array.isArray(o)?o:[o],o.length===0)throw new Error("values() must be called with at least one value");let T=o.map((f)=>{let S={},n=this.table[j.Symbol.Columns];for(let A of Object.keys(f)){let $=f[A];S[A]=H($,m)?$:new RT($,n[A])}return S});return new K$(this.table,T,this.session,this.dialect,this.withList,!1,this.overridingSystemValue_).setToken(this.authToken)}select(o){let T=typeof o==="function"?o(new bS):o;if(!H(T,m)&&!tS(this.table[kn],T._.selectedFields))throw new Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");return new K$(this.table,T,this.session,this.dialect,this.withList,!0)}}class K$ extends oT{constructor(o,T,f,S,n,A,$){super();this.session=f,this.dialect=S,this.config={table:o,values:T,withList:n,select:A,overridingSystemValue_:$}}static[O]="PgInsert";config;returning(o=this.config.table[j.Symbol.Columns]){return this.config.returningFields=o,this.config.returning=wT(o),this}onConflictDoNothing(o={}){if(o.target===void 0)this.config.onConflict=k`do nothing`;else{let T="";T=Array.isArray(o.target)?o.target.map((S)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(S))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(o.target));let f=o.where?k` where ${o.where}`:void 0;this.config.onConflict=k`(${k.raw(T)})${f} do nothing`}return this}onConflictDoUpdate(o){if(o.where&&(o.targetWhere||o.setWhere))throw new Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');let T=o.where?k` where ${o.where}`:void 0,f=o.targetWhere?k` where ${o.targetWhere}`:void 0,S=o.setWhere?k` where ${o.setWhere}`:void 0,n=this.dialect.buildUpdateSet(this.config.table,Hn(this.config.table,o.set)),A="";return A=Array.isArray(o.target)?o.target.map(($)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing($))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(o.target)),this.config.onConflict=k`(${k.raw(A)})${f} do update set ${n}${T}${S}`,this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:o,...T}=this.dialect.sqlToQuery(this.getSQL());return T}_prepare(o){return wo.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,o,!0)})}prepare(o){return this._prepare(o)}authToken;setToken(o){return this.authToken=o,this}execute=(o)=>{return wo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(o,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new Uo({alias:qo(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class G$ extends oT{constructor(o,T,f){super();this.session=T,this.dialect=f,this.config={view:o}}static[O]="PgRefreshMaterializedView";config;concurrently(){if(this.config.withNoData!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.concurrently=!0,this}withNoData(){if(this.config.concurrently!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.withNoData=!0,this}getSQL(){return this.dialect.buildRefreshMaterializedViewQuery(this.config)}toSQL(){let{typings:o,...T}=this.dialect.sqlToQuery(this.getSQL());return T}_prepare(o){return wo.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),void 0,o,!0)})}prepare(o){return this._prepare(o)}authToken;setToken(o){return this.authToken=o,this}execute=(o)=>{return wo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(o,this.authToken)})}}class pn{constructor(o,T,f,S){this.table=o,this.session=T,this.dialect=f,this.withList=S}static[O]="PgUpdateBuilder";authToken;setToken(o){return this.authToken=o,this}set(o){return new K1(this.table,Hn(this.table,o),this.session,this.dialect,this.withList).setToken(this.authToken)}}class K1 extends oT{constructor(o,T,f,S,n){super();this.session=f,this.dialect=S,this.config={set:T,table:o,withList:n,joins:[]},this.tableName=rT(o),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}static[O]="PgUpdate";config;tableName;joinsNotNullableMap;from(o){let T=o,f=rT(T);if(typeof f==="string")this.joinsNotNullableMap[f]=!0;return this.config.from=T,this}getTableLikeFields(o){if(H(o,po))return o[j.Symbol.Columns];else if(H(o,bo))return o._.selectedFields;return o[Ho].selectedFields}createJoin(o){return(T,f)=>{let S=rT(T);if(typeof S==="string"&&this.config.joins.some((n)=>n.alias===S))throw new Error(`Alias "${S}" is already used in this query`);if(typeof f==="function"){let n=this.config.from&&!H(this.config.from,m)?this.getTableLikeFields(this.config.from):void 0;f=f(new Proxy(this.config.table[j.Symbol.Columns],new Uo({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),n&&new Proxy(n,new Uo({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}if(this.config.joins.push({on:f,table:T,joinType:o,alias:S}),typeof S==="string")switch(o){case"left":{this.joinsNotNullableMap[S]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([n])=>[n,!1])),this.joinsNotNullableMap[S]=!0;break}case"inner":{this.joinsNotNullableMap[S]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([n])=>[n,!1])),this.joinsNotNullableMap[S]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(o){return this.config.where=o,this}returning(o){if(!o){if(o=Object.assign({},this.config.table[j.Symbol.Columns]),this.config.from){let T=rT(this.config.from);if(typeof T==="string"&&this.config.from&&!H(this.config.from,m)){let f=this.getTableLikeFields(this.config.from);o[T]=f}for(let f of this.config.joins){let S=rT(f.table);if(typeof S==="string"&&!H(f.table,m)){let n=this.getTableLikeFields(f.table);o[S]=n}}}}return this.config.returningFields=o,this.config.returning=wT(o),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:o,...T}=this.dialect.sqlToQuery(this.getSQL());return T}_prepare(o){let T=this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,o,!0);return T.joinsNotNullableMap=this.joinsNotNullableMap,T}prepare(o){return this._prepare(o)}authToken;setToken(o){return this.authToken=o,this}execute=(o)=>{return this._prepare().execute(o,this.authToken)};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new Uo({alias:qo(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class xS extends m{constructor(o){super(xS.buildEmbeddedCount(o.source,o.filters).queryChunks);this.params=o,this.mapWith(Number),this.session=o.session,this.sql=xS.buildCount(o.source,o.filters)}sql;token;static[O]="PgCountBuilder";[Symbol.toStringTag]="PgCountBuilder";session;static buildEmbeddedCount(o,T){return k`(select count(*) from ${o}${k.raw(" where ").if(T)}${T})`}static buildCount(o,T){return k`select count(*) as count from ${o}${k.raw(" where ").if(T)}${T};`}setToken(o){return this.token=o,this}then(o,T){return Promise.resolve(this.session.count(this.sql,this.token)).then(o,T)}catch(o){return this.then(void 0,o)}finally(o){return this.then((T)=>{return o?.(),T},(T)=>{throw o?.(),T})}}class E${constructor(o,T,f,S,n,A,$){this.fullSchema=o,this.schema=T,this.tableNamesMap=f,this.table=S,this.tableConfig=n,this.dialect=A,this.session=$}static[O]="PgRelationalQueryBuilder";findMany(o){return new Y$(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,o?o:{},"many")}findFirst(o){return new Y$(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,o?{...o,limit:1}:{limit:1},"first")}}class Y$ extends oT{constructor(o,T,f,S,n,A,$,F,J){super();this.fullSchema=o,this.schema=T,this.tableNamesMap=f,this.table=S,this.tableConfig=n,this.dialect=A,this.session=$,this.config=F,this.mode=J}static[O]="PgRelationalQuery";_prepare(o){return wo.startActiveSpan("drizzle.prepareQuery",()=>{let{query:T,builtQuery:f}=this._toSQL();return this.session.prepareQuery(f,void 0,o,!0,(S,n)=>{let A=S.map(($)=>Bn(this.schema,this.tableConfig,$,T.selection,n));if(this.mode==="first")return A[0];return A})})}prepare(o){return this._prepare(o)}_getQuery(){return this.dialect.buildRelationalQueryWithoutPK({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName})}getSQL(){return this._getQuery().sql}_toSQL(){let o=this._getQuery(),T=this.dialect.sqlToQuery(o.sql);return{query:o,builtQuery:T}}toSQL(){return this._toSQL().builtQuery}authToken;setToken(o){return this.authToken=o,this}execute(){return wo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(void 0,this.authToken)})}}class z$ extends oT{constructor(o,T,f,S){super();this.execute=o,this.sql=T,this.query=f,this.mapBatchResult=S}static[O]="PgRaw";getSQL(){return this.sql}getQuery(){return this.query}mapResult(o,T){return T?this.mapBatchResult(o):o}_prepare(){return this}isResponseInArrayMode(){return!1}}class vS{constructor(o,T,f){if(this.dialect=o,this.session=T,this._=f?{schema:f.schema,fullSchema:f.fullSchema,tableNamesMap:f.tableNamesMap,session:T}:{schema:void 0,fullSchema:{},tableNamesMap:{},session:T},this.query={},this._.schema)for(let[S,n]of Object.entries(this._.schema))this.query[S]=new E$(f.fullSchema,this._.schema,this._.tableNamesMap,f.fullSchema[S],n,o,T)}static[O]="PgDatabase";query;$with=(o,T)=>{let f=this;return{as:(n)=>{if(typeof n==="function")n=n(new bS(f.dialect));return new Proxy(new ES(n.getSQL(),T??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),o,!0),new Uo({alias:o,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(o,T){return new xS({source:o,filters:T,session:this.session})}with(...o){let T=this;function f(J){return new TT({fields:J??void 0,session:T.session,dialect:T.dialect,withList:o})}function S(J){return new TT({fields:J??void 0,session:T.session,dialect:T.dialect,withList:o,distinct:!0})}function n(J,R){return new TT({fields:R??void 0,session:T.session,dialect:T.dialect,withList:o,distinct:{on:J}})}function A(J){return new pn(J,T.session,T.dialect,o)}function $(J){return new Zn(J,T.session,T.dialect,o)}function F(J){return new rn(J,T.session,T.dialect,o)}return{select:f,selectDistinct:S,selectDistinctOn:n,update:A,insert:$,delete:F}}select(o){return new TT({fields:o??void 0,session:this.session,dialect:this.dialect})}selectDistinct(o){return new TT({fields:o??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(o,T){return new TT({fields:T??void 0,session:this.session,dialect:this.dialect,distinct:{on:o}})}update(o){return new pn(o,this.session,this.dialect)}insert(o){return new Zn(o,this.session,this.dialect)}delete(o){return new rn(o,this.session,this.dialect)}refreshMaterializedView(o){return new G$(o,this.session,this.dialect)}authToken;execute(o){let T=typeof o==="string"?k.raw(o):o.getSQL(),f=this.dialect.sqlToQuery(T),S=this.session.prepareQuery(f,void 0,void 0,!1);return new z$(()=>S.execute(void 0,this.authToken),T,f,(n)=>S.mapResult(n,!0))}transaction(o,T){return this.session.transaction(o,T)}}class G1{constructor(o,T){this.unique=o,this.name=T}static[O]="PgIndexBuilderOn";on(...o){return new cn(o.map((T)=>{if(H(T,m))return T;T=T;let f=new YS(T.name,!!T.keyAsName,T.columnType,T.indexConfig);return T.indexConfig=JSON.parse(JSON.stringify(T.defaultConfig)),f}),this.unique,!1,this.name)}onOnly(...o){return new cn(o.map((T)=>{if(H(T,m))return T;T=T;let f=new YS(T.name,!!T.keyAsName,T.columnType,T.indexConfig);return T.indexConfig=T.defaultConfig,f}),this.unique,!0,this.name)}using(o,...T){return new cn(T.map((f)=>{if(H(f,m))return f;f=f;let S=new YS(f.name,!!f.keyAsName,f.columnType,f.indexConfig);return f.indexConfig=JSON.parse(JSON.stringify(f.defaultConfig)),S}),this.unique,!0,this.name,o)}}class cn{static[O]="PgIndexBuilder";config;constructor(o,T,f,S,n="btree"){this.config={name:S,columns:o,unique:T,only:f,method:n}}concurrently(){return this.config.concurrently=!0,this}with(o){return this.config.with=o,this}where(o){return this.config.where=o,this}build(o){return new Y1(this.config,o)}}class Y1{static[O]="PgIndex";config;constructor(o,T){this.config={...o,table:T}}}function Q$(o){return new G1(!0,o)}class D${constructor(o){this.query=o}authToken;getQuery(){return this.query}mapResult(o,T){return o}setToken(o){return this.authToken=o,this}static[O]="PgPreparedQuery";joinsNotNullableMap}class U${constructor(o){this.dialect=o}static[O]="PgSession";execute(o,T){return wo.startActiveSpan("drizzle.operation",()=>{return wo.startActiveSpan("drizzle.prepareQuery",()=>{return this.prepareQuery(this.dialect.sqlToQuery(o),void 0,void 0,!1)}).setToken(T).execute(void 0,T)})}all(o){return this.prepareQuery(this.dialect.sqlToQuery(o),void 0,void 0,!1).all()}async count(o,T){let f=await this.execute(o,T);return Number(f[0].count)}}class t$ extends vS{constructor(o,T,f,S=0){super(o,T,f);this.schema=f,this.nestedIndex=S}static[O]="PgTransaction";rollback(){throw new iA}getTransactionConfigSQL(o){let T=[];if(o.isolationLevel)T.push(`isolation level ${o.isolationLevel}`);if(o.accessMode)T.push(o.accessMode);if(typeof o.deferrable==="boolean")T.push(o.deferrable?"deferrable":"not deferrable");return k.raw(T.join(" "))}setTransaction(o){return this.session.execute(k`set transaction ${this.getTransactionConfigSQL(o)}`)}}class E1 extends D${constructor(o,T,f,S,n,A,$){super({sql:T,params:f});this.client=o,this.queryString=T,this.params=f,this.logger=S,this.fields=n,this._isResponseInArrayMode=A,this.customResultMapper=$}static[O]="PostgresJsPreparedQuery";async execute(o={}){return wo.startActiveSpan("drizzle.execute",async(T)=>{let f=cA(this.params,o);T?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(f)}),this.logger.logQuery(this.queryString,f);let{fields:S,queryString:n,client:A,joinsNotNullableMap:$,customResultMapper:F}=this;if(!S&&!F)return wo.startActiveSpan("drizzle.driver.execute",()=>{return A.unsafe(n,f)});let J=await wo.startActiveSpan("drizzle.driver.execute",()=>{return T?.setAttributes({"drizzle.query.text":n,"drizzle.query.params":JSON.stringify(f)}),A.unsafe(n,f).values()});return wo.startActiveSpan("drizzle.mapResponse",()=>{return F?F(J):J.map((R)=>lJ(S,R,$))})})}all(o={}){return wo.startActiveSpan("drizzle.execute",async(T)=>{let f=cA(this.params,o);return T?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(f)}),this.logger.logQuery(this.queryString,f),wo.startActiveSpan("drizzle.driver.execute",()=>{return T?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(f)}),this.client.unsafe(this.queryString,f)})})}isResponseInArrayMode(){return this._isResponseInArrayMode}}class qS extends U${constructor(o,T,f,S={}){super(T);this.client=o,this.schema=f,this.options=S,this.logger=S.logger??new dA}static[O]="PostgresJsSession";logger;prepareQuery(o,T,f,S,n){return new E1(this.client,o.sql,o.params,this.logger,T,S,n)}query(o,T){return this.logger.logQuery(o,T),this.client.unsafe(o,T).values()}queryObjects(o,T){return this.client.unsafe(o,T)}transaction(o,T){return this.client.begin(async(f)=>{let S=new qS(f,this.dialect,this.schema,this.options),n=new V$(this.dialect,S,this.schema);if(T)await n.setTransaction(T);return o(n)})}}class V$ extends t${constructor(o,T,f,S=0){super(o,T,f,S);this.session=T}static[O]="PostgresJsTransaction";transaction(o){return this.session.client.savepoint((T)=>{let f=new qS(T,this.dialect,this.schema,this.session.options),S=new V$(this.dialect,f,this.schema);return o(S)})}}class z1 extends vS{static[O]="PostgresJsDatabase"}function ef(o,T={}){let f=(J)=>J;for(let J of["1184","1082","1083","1114"])o.options.parsers[J]=f,o.options.serializers[J]=f;o.options.serializers["114"]=f,o.options.serializers["3802"]=f;let S=new Xf({casing:T.casing}),n;if(T.logger===!0)n=new gA;else if(T.logger!==!1)n=T.logger;let A;if(T.schema){let J=l0(T.schema,e0);A={fullSchema:T.schema,schema:J.tables,tableNamesMap:J.tableNamesMap}}let $=new qS(o,S,A,{logger:n}),F=new z1(S,$,A);return F.$client=o,F}function Pn(...o){if(typeof o[0]==="string"){let T=lf(o[0]);return ef(T,o[1])}if(sJ(o[0])){let{connection:T,client:f,...S}=o[0];if(f)return ef(f,S);if(typeof T==="object"&&T.url!==void 0){let{url:A,...$}=T,F=lf(A,$);return ef(F,S)}let n=lf(T);return ef(n,S)}return ef(o[0],o[1])}((o)=>{function T(f){return ef({options:{parsers:{},serializers:{}}},f)}o.mock=T})(Pn||(Pn={}));var L$={};VM(L$,{users:()=>Hf,userChanges:()=>lO,untrackedUserColumnNames:()=>dO,twoFactorMethod:()=>V1,trackedUserColumnName:()=>t1,trackableUserColumnNames:()=>U1,role:()=>D1,players:()=>B$,passwordResetAttempts:()=>eO,loginHistory:()=>uO,games:()=>gn,banishedIps:()=>sO});function Q1(o){return k`lower(${o})`}var D1=Wn("role",["admin","user"]),Hf=sT("users",{id:MT().primaryKey().defaultRandom(),username:Zo({length:16}).notNull(),email:Zo({length:254}).notNull(),hash:Zo({length:64}).notNull(),salt:Zo({length:36}).notNull(),createdAt:DT({withTimezone:!0}).notNull().defaultNow(),createdIp:Zo({length:45}).notNull(),isActive:VS().notNull().default(!1),verifiedAt:DT({withTimezone:!0}),userRole:D1().default("user")},(o)=>[Q$("usernameUniqueIndex").on(Q1(o.username)),Q$("emailUniqueIndex").on(Q1(o.email))]),dO=["id","createdAt","createdIp","isActive","salt","verifiedAt"],U1=["username","email","hash","userRole"],t1=Wn("trackedUserColumnName",U1),lO=sT("userChanges",{id:MT().primaryKey().defaultRandom(),userId:MT().notNull().references(()=>Hf.id),changedAt:DT({withTimezone:!0}).notNull().defaultNow(),changedIp:Zo({length:45}).notNull(),changedColumn:t1().notNull(),oldValue:Zo({length:255}),newValue:Zo({length:255})}),gn=sT("games",{id:MT().primaryKey().defaultRandom()}),B$=sT("players",{userId:MT().notNull().references(()=>Hf.id),gameId:MT().notNull().references(()=>gn.id),score:Yn().notNull()},(o)=>[c0({name:"players_userId_gameId_pk",columns:[o.userId,o.gameId]})]),uO=sT("loginHistory",{id:MT().primaryKey().defaultRandom(),userId:MT().references(()=>Hf.id),loginTime:DT({withTimezone:!0}).notNull().defaultNow(),ipAddress:Zo({length:45}).notNull(),userAgent:Zo({length:1024}),successful:VS().notNull().default(!1)}),V1=Wn("twoFactorMethod",["email","phone"]),eO=sT("passwordResetAttempts",{id:MT().primaryKey().defaultRandom(),userId:MT().notNull().references(()=>Hf.id),requestedIp:Zo({length:45}).notNull(),requestedAt:DT({withTimezone:!0}).notNull().defaultNow(),succeededIp:Zo({length:45}),succeededAt:DT({withTimezone:!0}),verificationMethod:V1().notNull()}),sO=sT("banishedIps",{ip:Zo({length:45}).primaryKey(),reason:Zo({length:2048}).notNull(),banishedAt:DT({withTimezone:!0}).notNull().defaultNow(),banishedUntil:DT({withTimezone:!0})});var __dirname="/home/runner/work/wayforge/wayforge/apps/tempest.games/src/database";class C${options;sql;drizzle;observers=new Map;async setupTriggersAndNotifications(){await this.sql.file(aO.resolve(__dirname,"notify_update.sql"));let o=[qo(Hf),qo(gn),qo(B$)];await this.sql`SELECT create_notify_triggers(${this.sql.array(o)})`,await this.sql.listen("table_update",(T)=>{let f=T.split(","),S=f[0],n=f[1],A=`${S}("${n}")`;if(this.observers.has(A))this.observers.get(A).next(A)})}constructor(o=!1,T={host:zT.POSTGRES_HOST,port:zT.POSTGRES_PORT,user:zT.POSTGRES_USER,password:zT.POSTGRES_PASSWORD,database:zT.POSTGRES_DATABASE}){this.options=T,this.sql=lf(T),this.drizzle=Pn(this.sql,{schema:L$,logger:o})}observe(o,T){if(!this.observers.has(o))this.observers.set(o,new oo);this.observers.get(o).subscribe("SINGLETON",T)}}var dn={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"},I$=P$(dn).map(([o])=>Yo.literal(Number(o))),ok=Yo.union([I$[0],I$[1],...I$]),B1=Yo.tuple([ok,Yo.string()]);var m$=new QA,{logger:$T}=m$;Object.assign(console,$T,{log:$T.info});$T.info("ready");var j$=C1(import.meta.dir,"..","app"),$Q=new C$({logQuery(o,T){$T.info("\uD83D\uDCDD query",o,T)}});Sk({hostname:"0.0.0.0",port:zT.FRONTEND_PORT??3333,...MJ??void 0,async fetch(o){try{let T=new Date,f=new URL(o.url);if($T.info(o.method,f.pathname),f.pathname==="/")return new Response(Bun.file(C1(j$,"index.html")));if(f.pathname==="/index.html")return Response.redirect("/");let S=Tk(j$,f.pathname),n=fk(S);if(!n.startsWith(j$))throw[403,"Access Denied"];if(!await L1(n).exists())return Response.redirect("/");return new Response(L1(n))}catch(T){let f=B1.safeParse(T);if(f.success){let[S,n]=f.data,$=`${dn[S]}. ${n}`;return $T.info(`\u274C ${S}: ${$}`),new Response($,{status:S})}if(T instanceof Error)$T.error(T.message);else{let S=Uf(T);$T.error("frontend server threw",S)}return new Response(dn[500],{status:500})}}});function ln(){$T.info("\uD83D\uDEEC frontend server exiting"),process.exit(0)}process.on("SIGINT",()=>{$T.info("\u2757 received SIGINT; exiting gracefully"),ln()});process.on("SIGTERM",()=>{$T.info("\u2757 received SIGTERM; exiting gracefully"),ln()});process.on("exit",()=>{$T.info("\u2757 received exit; exiting gracefully"),ln()});m$.on("timeToStop",()=>{$T.info('\u2757 backend server received signal "timeToStop"; exiting gracefully'),ln()});$T.info(`\uD83D\uDEEB frontend server running at http://localhost:${zT.FRONTEND_PORT}/`);m$.emit("alive");