tempest.games 0.1.33 → 0.1.34

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,6 +1,6 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- var zM=Object.create;var{getPrototypeOf:QM,defineProperty:aS,getOwnPropertyNames:DM}=Object;var UM=Object.prototype.hasOwnProperty;var Sk=(o,T,f)=>{f=o!=null?zM(QM(o)):{};let n=T||!o||!o.__esModule?aS(f,"default",{value:o,enumerable:!0}):f;for(let S of DM(o))if(!UM.call(n,S))aS(n,S,{get:()=>o[S],enumerable:!0});return n};var Ak=(o,T)=>()=>(T||o((T={exports:{}}).exports,T),T.exports);var VM=(o,T)=>{for(var f in T)aS(o,f,{get:T[f],enumerable:!0,configurable:!0,set:(n)=>T[f]=()=>n})};var $k=import.meta.require;import{join as Tk,normalize as fk,resolve as C1}from"path";function cn(o=Math.random){return o().toString(36).slice(2)}class Tn extends Promise{fate;resolve;reject;done=!1;constructor(o){let T,f;super((n,S)=>{T=n,f=S});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=no.STORE)=>{return jT(f,{key:`${o.key}:JSON`,get:({get:n})=>T.toJson(n(o)),set:({set:n},S)=>{n(o,T.fromJson(S))}})};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 n={key:T.key,type:"atom_family"},S=o.families.get(T.key);if(S)o.logger.error("\u2757","atom_family",T.key,`Overwriting an existing ${VT(S)} "${S.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,D={key:_,default:X instanceof Function?X(J):X};if(T.effects)D.effects=T.effects(J);let K=FT(w,D,M);return A.next({type:"state_creation",token:K}),K},n,{subject:A,install:(J)=>NT(J,T),internalRoles:f});return o.families.set(T.key,F),o.defaults.set(T.key,T.default),n}function g$(o,T){if("mutable"in T)return fn(o,T);return NT(o,T)}function hT(o,T,f){let n={key:T.key,type:"readonly_selector_family"},S=o.families.get(T.key);if(S)o.logger.error("\u2757","readonly_selector_family",T.key,`Overwriting an existing ${VT(S)} "${S.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=nn(w,{key:_,get:T.get(J)},M);return A.next({type:"state_creation",token:X}),X},n,{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)=>Io(o,M)})}});return o.families.set(T.key,F),n}function Zn(o,T){if("set"in T)return Sn(o,T);return hT(o,T)}class Pn{_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 Pn([...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),n=`${o.key}(${f})`,S=BM[o.type],A={key:n,type:S};return Object.assign(A,{family:{key:o.key,subKey:f}}),Object.assign(A,{counterfeit:!0}),A}function nT(o){let T={key:o.key,type:o.type};if("family"in o)T.family=o.family;return T}function Yf(o){return l$(no.STORE,o)}function Tf(o){return g$(no.STORE,o)}function TA(...o){if(o.length===2)return Ro(no.STORE,...o);return Ro(no.STORE,...o)}function gn(o,T,f=no.STORE){return f.joins.set(o.key,new An(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,no.STORE)}var fA=(o)=>(T,f,n,S,...A)=>{console[o](`${T} ${f} "${n}" ${S}`,...A)},LM={error:fA("error"),info:fA("info"),warn:fA("warn")};class nA{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 Zk=Symbol("claim");class a${store;constructor(o=no.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){nf(this.store,o)}claim(o,T,f){return Ef(this.store,o,T,f)}}class SA{store;realm;constructor(o=no.STORE){this.store=o,this.realm=new a$(o)}allocate(o,T,f){ff(this.store,o,T,f)}deallocate(o){nf(this.store,o)}claim(o,T,f){Ef(this.store,o,T,f)}}function ln(o){return Zn(no.STORE,o)}function jo(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 Sf extends Error{constructor(o,T){super(`${VT(o)} ${fo(o.key)} not found in store "${T.config.name}".`)}}function tf(o,T,f){return(...n)=>{let S=$o(o,T);if(S)return S.run(n,f);throw new Sf(T,o)}}var un=(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"),nF(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 SF=(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)},zf=(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;case"atom":case"selector":case"readonly_selector":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),n=f.selectorAtoms.getRelatedKeys(T.key);if(f.logger.info("\uD83E\uDDF9",T.type,T.key,n?`evicting ${n.size} states downstream:`:"no downstream states",n??"to evict"),n){if(f.operation.open)f.logger.info("\uD83E\uDDF9",T.type,T.key,`[ ${[...f.operation.done].join(", ")} ] already done`);for(let S of n){if($F(f,S))continue;JF(S,f),zf(f,S)}}};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:n}=T,S=C(o);if(!Mo(S)||S.transactionMeta.phase!=="building"){o.logger.error("\uD83D\uDC1E","atom",n,"stowUpdate called outside of a transaction. This is probably a bug.");return}if(!CM(n,f))return;let $={type:"atom_update",key:n,...f};if(T.family)$.family=T.family;S.transactionMeta.update.updates.push($),o.logger.info("\uD83D\uDCC1","atom",n,"stowed (",f.oldValue,"->",f.newValue,")")};var WF=(o,T,f)=>{let n=PT(f,o),S=n;if(o.type==="mutable_atom"&&Mo(f)){let{parent:$}=f;S=Fn(f,o,$)}if(S=un(T)(S),f.logger.info("\uD83D\uDCDD","atom",o.key,"set to",S),S=OT(f,o.key,S,o.subject),OF(f,o.key))kF(f,o.key);zf(f,o.key),AA(f,o);let A={oldValue:n,newValue:S};if(jo(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=Fn(f,F,M)}if(J.do(A.newValue)===null)AA(f,F)}}};var en=(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 Uo(o,...T){let f,n,S,A;if(T.length===2){if(f=T[0],A=T[1],n=_F(o,f)??null,n)S=f.family?vo(f.family.subKey):null,f=i(o,n,S)}else n=T[0],S=T[1],A=T[2],f=i(o,n,S);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:
3
+ var zM=Object.create;var{getPrototypeOf:QM,defineProperty:aS,getOwnPropertyNames:DM}=Object;var UM=Object.prototype.hasOwnProperty;var Sk=(o,T,f)=>{f=o!=null?zM(QM(o)):{};let n=T||!o||!o.__esModule?aS(f,"default",{value:o,enumerable:!0}):f;for(let S of DM(o))if(!UM.call(n,S))aS(n,S,{get:()=>o[S],enumerable:!0});return n};var Ak=(o,T)=>()=>(T||o((T={exports:{}}).exports,T),T.exports);var VM=(o,T)=>{for(var f in T)aS(o,f,{get:T[f],enumerable:!0,configurable:!0,set:(n)=>T[f]=()=>n})};var $k=import.meta.require;import{join as Tk,normalize as fk,resolve as C1}from"path";function cn(o=Math.random){return o().toString(36).slice(2)}class Tn extends Promise{fate;resolve;reject;done=!1;constructor(o){let T,f;super((n,S)=>{T=n,f=S});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=no.STORE)=>{return jT(f,{key:`${o.key}:JSON`,get:({get:n})=>T.toJson(n(o)),set:({set:n},S)=>{n(o,T.fromJson(S))}})};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 n={key:T.key,type:"atom_family"},S=o.families.get(T.key);if(S)o.logger.error("\u2757","atom_family",T.key,`Overwriting an existing ${VT(S)} "${S.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,D={key:_,default:X instanceof Function?X(J):X};if(T.effects)D.effects=T.effects(J);let K=FT(w,D,M);return A.next({type:"state_creation",token:K}),K},n,{subject:A,install:(J)=>NT(J,T),internalRoles:f});return o.families.set(T.key,F),o.defaults.set(T.key,T.default),n}function g$(o,T){if("mutable"in T)return fn(o,T);return NT(o,T)}function hT(o,T,f){let n={key:T.key,type:"readonly_selector_family"},S=o.families.get(T.key);if(S)o.logger.error("\u2757","readonly_selector_family",T.key,`Overwriting an existing ${VT(S)} "${S.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=nn(w,{key:_,get:T.get(J)},M);return A.next({type:"state_creation",token:X}),X},n,{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)=>Io(o,M)})}});return o.families.set(T.key,F),n}function Zn(o,T){if("set"in T)return Sn(o,T);return hT(o,T)}class Pn{_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 Pn([...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),n=`${o.key}(${f})`,S=BM[o.type],A={key:n,type:S};return Object.assign(A,{family:{key:o.key,subKey:f}}),Object.assign(A,{counterfeit:!0}),A}function nT(o){let T={key:o.key,type:o.type};if("family"in o)T.family=o.family;return T}function Gf(o){return l$(no.STORE,o)}function Tf(o){return g$(no.STORE,o)}function TA(...o){if(o.length===2)return Ro(no.STORE,...o);return Ro(no.STORE,...o)}function gn(o,T,f=no.STORE){return f.joins.set(o.key,new An(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,no.STORE)}var fA=(o)=>(T,f,n,S,...A)=>{console[o](`${T} ${f} "${n}" ${S}`,...A)},LM={error:fA("error"),info:fA("info"),warn:fA("warn")};class nA{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 Zk=Symbol("claim");class a${store;constructor(o=no.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){nf(this.store,o)}claim(o,T,f){return Yf(this.store,o,T,f)}}class SA{store;realm;constructor(o=no.STORE){this.store=o,this.realm=new a$(o)}allocate(o,T,f){ff(this.store,o,T,f)}deallocate(o){nf(this.store,o)}claim(o,T,f){Yf(this.store,o,T,f)}}function ln(o){return Zn(no.STORE,o)}function jo(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 Sf extends Error{constructor(o,T){super(`${VT(o)} ${fo(o.key)} not found in store "${T.config.name}".`)}}function tf(o,T,f){return(...n)=>{let S=$o(o,T);if(S)return S.run(n,f);throw new Sf(T,o)}}var un=(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"),nF(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 SF=(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)},zf=(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;case"atom":case"selector":case"readonly_selector":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),n=f.selectorAtoms.getRelatedKeys(T.key);if(f.logger.info("\uD83E\uDDF9",T.type,T.key,n?`evicting ${n.size} states downstream:`:"no downstream states",n??"to evict"),n){if(f.operation.open)f.logger.info("\uD83E\uDDF9",T.type,T.key,`[ ${[...f.operation.done].join(", ")} ] already done`);for(let S of n){if($F(f,S))continue;JF(S,f),zf(f,S)}}};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:n}=T,S=C(o);if(!Mo(S)||S.transactionMeta.phase!=="building"){o.logger.error("\uD83D\uDC1E","atom",n,"stowUpdate called outside of a transaction. This is probably a bug.");return}if(!CM(n,f))return;let $={type:"atom_update",key:n,...f};if(T.family)$.family=T.family;S.transactionMeta.update.updates.push($),o.logger.info("\uD83D\uDCC1","atom",n,"stowed (",f.oldValue,"->",f.newValue,")")};var WF=(o,T,f)=>{let n=PT(f,o),S=n;if(o.type==="mutable_atom"&&Mo(f)){let{parent:$}=f;S=Fn(f,o,$)}if(S=un(T)(S),f.logger.info("\uD83D\uDCDD","atom",o.key,"set to",S),S=OT(f,o.key,S,o.subject),OF(f,o.key))kF(f,o.key);zf(f,o.key),AA(f,o);let A={oldValue:n,newValue:S};if(jo(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=Fn(f,F,M)}if(J.do(A.newValue)===null)AA(f,F)}}};var en=(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 Uo(o,...T){let f,n,S,A;if(T.length===2){if(f=T[0],A=T[1],n=_F(o,f)??null,n)S=f.family?vo(f.family.subKey):null,f=i(o,n,S)}else n=T[0],S=T[1],A=T[2],f=i(o,n,S);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
4
  ${R.trace}`:"No previous disposal trace was found.");return}let $=SF(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-${$}`),Uo(o,f,A)});return}let F=$o(o,f);en(o,F,A),AF(o)}function sn(o,T,f){let{key:n,newValue:S,oldValue:A}=T,$=o==="newValue"?S:A,F={key:n,type:"atom"};if(T.family)Object.assign(F,{family:T.family});Uo(f,F,$)}function wF(o){let{stack:T}=o;if(T)return`
5
5
  `+T.split(`
6
6
  `)?.slice(1)?.join(`
@@ -8,13 +8,13 @@ ${R.trace}`:"No previous disposal trace was found.");return}let $=SF(o,f);if($){
8
8
  ${M} was most recently disposed
9
9
  ${_.trace}`:`No previous disposal trace for ${M} was found.`)}return f}function TF(o,T,f,n){let S=`T$--${T}==${f}++${n}`;return ff(o,[f,n],S,"all"),S}function nf(o,T){let f=fo(T),n=o.molecules.get(f);if(!n){let X=o.disposalTraces.buffer.find((D)=>D?.key===f);o.logger.error("\u274C","molecule",T,"deallocation failed:",`Could not find allocation for ${f} in store "${o.config.name}".`,X?`
10
10
  This state was most recently deallocated
11
- ${X.trace}`:`No previous disposal trace for ${f} was found.`);return}let S=o.moleculeJoins.getRelatedKeys(n.key);if(S)for(let X of S){let D=o.joins.get(X);if(D)D.relations.delete(n.key),D.molecules.delete(n.stringKey)}o.moleculeJoins.delete(n.stringKey);let A=[],$=[],F={type:"molecule_disposal",key:n.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:n.stringKey});if(M)for(let[X,{source:D}]of M)if(D===n.stringKey){let K=vo(X);nf(o,K)}else A.push(D);let _=J.moleculeData.getRelatedKeys(n.stringKey);if(_)for(let X of _){let D=J.families.get(X),K=i(o,D,n.key);$.push([D.key,K]),Af(o,K)}if(J.moleculeGraph.delete(n.stringKey),J.moleculeJoins.delete(n.stringKey),J.moleculeData.delete(n.stringKey),!R)J.on.moleculeDisposal.next(F);J.molecules.delete(n.stringKey);let w=wF(new Error);o.disposalTraces.add({key:f,trace:w})}function Ef(o,T,f,n){let S=fo(f),A=C(o),$=A.molecules.get(S);if(!$){let w=o.disposalTraces.buffer.find((X)=>X?.key===S);return o.logger.error("\u274C","molecule",f,"claim failed:",`Could not allocate to ${S} in store "${o.config.name}".`,w?`
11
+ ${X.trace}`:`No previous disposal trace for ${f} was found.`);return}let S=o.moleculeJoins.getRelatedKeys(n.key);if(S)for(let X of S){let D=o.joins.get(X);if(D)D.relations.delete(n.key),D.molecules.delete(n.stringKey)}o.moleculeJoins.delete(n.stringKey);let A=[],$=[],F={type:"molecule_disposal",key:n.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:n.stringKey});if(M)for(let[X,{source:D}]of M)if(D===n.stringKey){let K=vo(X);nf(o,K)}else A.push(D);let _=J.moleculeData.getRelatedKeys(n.stringKey);if(_)for(let X of _){let D=J.families.get(X),K=i(o,D,n.key);$.push([D.key,K]),Af(o,K)}if(J.moleculeGraph.delete(n.stringKey),J.moleculeJoins.delete(n.stringKey),J.moleculeData.delete(n.stringKey),!R)J.on.moleculeDisposal.next(F);J.molecules.delete(n.stringKey);let w=wF(new Error);o.disposalTraces.add({key:f,trace:w})}function Yf(o,T,f,n){let S=fo(f),A=C(o),$=A.molecules.get(S);if(!$){let w=o.disposalTraces.buffer.find((X)=>X?.key===S);return o.logger.error("\u274C","molecule",f,"claim failed:",`Could not allocate to ${S} in store "${o.config.name}".`,w?`
12
12
  ${S} was most recently disposed
13
13
  ${w.trace}`:`No previous disposal trace for ${S} 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?`
14
14
  ${F} was most recently disposed
15
- ${w.trace}`:`No previous disposal trace for ${F} was found.`),f}let R=o.moleculeGraph.getRelationEntries({downstreamMoleculeKey:$.stringKey}).filter(([,{source:w}])=>w!==S).map(([w])=>vo(w));if(n)A.moleculeGraph.delete(S);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 n=T.families.get(f.key);if(n)i(T,n,vo(f.subKey))}}function XF(o,T,f){switch(T){case"newValue":ff(f,o.provenance,o.key);break;case"oldValue":nf(f,o.key);break}}function HF(o,T,f){switch(T){case"newValue":nf(f,o.key);break;case"oldValue":{let n=o.provenance.map(vo);ff(f,n,o.key);for(let[S,A]of o.values){let $=f.families.get(S);if($){i(f,$,o.key);let F=`${S}(${fo(o.key)})`;f.valueMap.set(F,A)}}}break}}function KF(o,T,f){switch(T){case"newValue":{let n=o.to.length===1?o.to[0]:o.to;Ef(f,n,o.key,"exclusive")}break;case"oldValue":{let n=o.from.length===1?o.from[0]:o.from;Ef(f,n,o.key,"exclusive")}break}}function an(o,T,f){let n=o==="newValue"?T.updates:[...T.updates].reverse();for(let S of n)switch(S.type){case"atom_update":case"selector_update":sn(o,S,f);break;case"state_creation":$A(S,o,f);break;case"state_disposal":FA(S,o,f);break;case"molecule_creation":XF(S,o,f);break;case"molecule_disposal":HF(S,o,f);break;case"molecule_transfer":KF(S,o,f);break;case"transaction_update":an(o,S,f);break}}function GF(o,T,f){if(jo(o)&&T)o.transactionMeta.epoch.set(T,f)}function YF(o,T,f){if(!jo(o))return;let S=o.transactionMeta.actionContinuities.getRelatedKey(T);if(S!==void 0)o.transactionMeta.epoch.set(S,f)}var EF=(o,T)=>{let f=C(T),{parent:n}=f;if(n===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,n.child=null,n.on.transactionApplying.next(f.transactionMeta);let{updates:S}=f.transactionMeta.update;if(T.logger.info("\uD83D\uDEC4","transaction",f.transactionMeta.update.key,`Applying transaction with ${S.length} updates:`,S),an("newValue",f.transactionMeta.update,n),jo(n))YF(n,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(n))n.transactionMeta.update.updates.push(f.transactionMeta.update);n.on.transactionApplying.next(null)};function tF(o,T,f){if(!jo(o))return;let{epoch:S,actionContinuities:A}=o.transactionMeta;if(A.set(T,f),!S.has(T))S.set(T,-1)}function zF(o){return{store:o}}function Ro(o,...T){let f,n,S;if(T.length===1)f=T[0];else n=T[0],S=T[1],f=i(o,n,S);if("counterfeit"in f&&"family"in f){n=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."),n.type){case"atom_family":case"mutable_atom_family":return o.defaults.get(n.key);case"selector_family":case"readonly_selector_family":{if(o.defaults.has(n.key))return o.defaults.get(f.family.key);let F=$o(o,n).default(A);return o.defaults.set(n.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),n=this.relations.get(T);if(f)f.add(T);else f=new Set([T]),this.relations.set(o,f);if(n)n.add(o);else n=new Set([o]),this.relations.set(T,n)}deleteRelation(o,T){let f=this.relations.get(o);if(f){if(f.delete(T),f.size===0)this.relations.delete(o);let n=this.relations.get(T);if(n){if(n.delete(o),n.size===0)this.relations.delete(T)}}}replaceRelationsUnsafely(o,T){this.relations.set(o,new Set(T));for(let f of T){let n=new Set().add(o);this.relations.set(f,n)}}replaceRelationsSafely(o,T){let f=this.relations.get(o),n=this.isAType?.(o)?o:void 0,S=n===void 0?o:void 0;if(f)for(let A of f){n??=A,S??=A;let $=this.relations.get(A);if($){if($.size===1)this.relations.delete(A);else $.delete(o);this.contents.delete(this.makeContentKey(n,S))}}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,n])=>[f,new Set(n)])),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=(n,S)=>f.has(n,S),this.addRelation=(n,S)=>{f.addRelation(n,S)},this.deleteRelation=(n,S)=>{f.deleteRelation(n,S)},this.replaceRelationsSafely=(n,S)=>{f.replaceRelationsSafely(n,S)},this.replaceRelationsUnsafely=(n,S)=>{f.replaceRelationsUnsafely(n,S)},this.getRelatedKeys=(n)=>f.getRelatedKeys(n),f.getContent)this.getContentInternal=(n)=>{return f.getContent(n)},this.setContent=(n,S)=>{f.setContent(n,S)},this.deleteContent=(n)=>{f.deleteContent(n)};for(let[n,S]of o.relations??[]){let A=this.isAType?.(n)?n:void 0,$=A===void 0?n:void 0;for(let F of S)A??=F,$??=F,this.addRelation(A,$)}for(let[n,S]of o.contents??[])this.setContent(n,S)}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,n;switch(o.length){case 1:{let S=o[0];T=S[this.a],f=S[this.b],n=void 0;break}case 2:{let S=o[0];if(typeof S==="string")[T,f]=o;else T=S[this.a],f=S[this.b],n=o[1];break}default:{T=o[0],f=o[1],n=o[2];break}}switch(this.cardinality){case"1:1":{let S=this.getRelatedKey(T);if(S&&S!==f)this.delete(T,S)}case"1:n":{let S=this.getRelatedKey(f);if(S&&S!==T)this.delete(S,f)}break;case"n:n":}if(n){let S=this.makeContentKey(T,f);this.setContent(S,n)}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 n=this.getRelatedKeys(T);if(n)for(let S of n)this.delete(S,T)}if(typeof f==="string"&&T===void 0){let n=this.getRelatedKeys(f);if(n)for(let S of n)this.delete(f,S)}if(typeof f==="string"&&typeof T==="string"){this.deleteRelation(f,T);let n=this.makeContentKey(f,T);this.deleteContent(n)}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((n)=>`"${n}"`).join(", ")}). Only one related key was expected.`);let f;for(let n of T){f=n;break}return f}}replaceRelations(o,T,f){let n=!Array.isArray(T),S=n?Object.keys(T):T;if(f?.reckless)this.replaceRelationsUnsafely(o,S);else this.replaceRelationsSafely(o,S);if(n)for(let A of S){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 n=this.getRelatedKeys(T);if(n)return[...n].map((S)=>{return[S,this.getContent(T,S)]})}if(T===void 0&&f!==void 0){let n=this.getRelatedKeys(f);if(n)return[...n].map((S)=>{return[S,this.getContent(S,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 QF=(o,T,f,n)=>{let S=C(o),A={parent:S,child:null,on:S.on,loggers:S.loggers,logger:S.logger,config:S.config,atoms:new kT(S.atoms),atomsThatAreDefault:new Set(S.atomsThatAreDefault),families:new kT(S.families),joins:new kT(S.joins),operation:{open:!1},readonlySelectors:new kT(S.readonlySelectors),timelines:new kT(S.timelines),timelineTopics:new No(S.timelineTopics.toJSON()),trackers:new Map,transactions:new kT(S.transactions),selectorAtoms:new No(S.selectorAtoms.toJSON()),selectorGraph:new No(S.selectorGraph.toJSON(),{makeContentKey:(...R)=>R.sort().join(":")}),selectors:new kT(S.selectors),valueMap:new kT(S.valueMap),defaults:S.defaults,disposalTraces:o.disposalTraces.copy(),molecules:new kT(S.molecules),moleculeGraph:new No(S.moleculeGraph.toJSON(),{makeContentKey:S.moleculeGraph.makeContentKey}),moleculeData:new No(S.moleculeData.toJSON(),{makeContentKey:S.moleculeData.makeContentKey}),moleculeJoins:new No(S.moleculeJoins.toJSON(),{makeContentKey:S.moleculeJoins.makeContentKey}),miscResources:new kT(S.miscResources)},$=DF(o,T),F={phase:"building",update:{type:"transaction_update",key:T,id:n,epoch:$===void 0?Number.NaN:$+1,updates:[],params:f,output:void 0},toolkit:{get:(...R)=>Ro(J,...R),set:(...R)=>{Uo(J,...R)},run:(R,M=cn())=>tf(J,R,M),find:(R,M)=>i(J,R,M),json:(R)=>Io(J,R),dispose:(...R)=>{Af(J,...R)},env:()=>zF(J)}},J=Object.assign(A,{transactionMeta:F});return S.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=QF(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(n),o.logger.warn("\uD83D\uDCA5","transaction",T.key,"caught:",J),J}},install:(A)=>JA(A,T),subject:new oo},n=C(o);n.transactions.set(f.key,f);let S=nT(f);return o.on.transactionCreation.next(S),S}function DF(o,T){let f=jo(o),n=f?o.transactionMeta.actionContinuities.getRelatedKey(T):void 0;return f&&n!==void 0?o.transactionMeta.epoch.get(n):void 0}function Jn(o){return JA(no.STORE,o)}class UF{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 Pn(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 nA("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},jo(T))this.transactionMeta={epoch:new Map(T?.transactionMeta.epoch),actionContinuities:new No(T?.transactionMeta.actionContinuities.toJSON())};for(let[,n]of T.families){if(n.internalRoles?.includes("mutable")||n.internalRoles?.includes("join"))continue;n.install(this)}let f=new Set;for(let[,n]of T.atoms){if(f.has(n.key))continue;if(n.install(this),n.type==="mutable_atom"){let S=Io(T,n),A=bT(n);f.add(S.key),f.add(A.key)}}for(let[,n]of T.readonlySelectors)n.install(this);for(let[,n]of T.selectors){if(f.has(n.key))continue;n.install(this)}for(let[,n]of T.transactions)n.install(this);for(let[,n]of T.timelines)n.install(this)}}}var no={get STORE(){if(!globalThis.ATOM_IO_IMPLICIT_STORE)globalThis.ATOM_IO_IMPLICIT_STORE=new UF({name:"IMPLICIT_STORE",lifespan:"ephemeral"});return globalThis.ATOM_IO_IMPLICIT_STORE}};function $o(o,T){let f,n=o;while(n!==null){switch(T.type){case"atom":case"mutable_atom":f=n.atoms.get(T.key);break;case"selector":f=n.selectors.get(T.key);break;case"readonly_selector":f=n.readonlySelectors.get(T.key);break;case"atom_family":case"mutable_atom_family":case"selector_family":case"readonly_selector_family":f=n.families.get(T.key);break;case"timeline":f=n.timelines.get(T.key);break;case"transaction":f=n.transactions.get(T.key);break}if(f)return f;n=n.child}throw new Sf(T,o)}function VF(o,T,f){let n=o.families.get(T.key);if(n===void 0)throw new Sf(T,o);let S=n(f),A=C(o);if(S.family){if(jo(A))switch(S.type){case"atom":case"mutable_atom":o.on.atomCreation.next(S);break;case"selector":case"readonly_selector":o.on.selectorCreation.next(S);break}else if(Mo(A)&&A.on.transactionApplying.state===null)A.transactionMeta.update.updates.push({type:"state_creation",token:S})}return S}function BF(o,T,f){let n=fo(f),S=`${T.key}(${n})`,A=C(o),$;switch(T.type){case"atom_family":case"mutable_atom_family":$=A.atoms.get(S);break;case"selector_family":$=A.selectors.get(S);break;case"readonly_selector_family":$=A.readonlySelectors.get(S);break}if($)return nT($);return $}function i(o,T,f){let n=BF(o,T,f);if(n)return n;let S=fo(f),A=o.molecules.get(S);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(n=VF(o,T,f),A)C(o).moleculeData.set(S,T.key);return n}function Af(o,...T){let f;if(T.length===1)f=T[0];else{let n=T[0],S=T[1];f=i(o,n,S)}try{$o(o,f)}catch(n){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 oS=(o,T)=>C(o).atoms.has(T),mM=(o,T)=>C(o).selectors.has(T),IM=(o,T)=>C(o).readonlySelectors.has(T),CF=(o,T)=>oS(o,T)||mM(o,T)||IM(o,T);var TS=(o,T)=>{return C(T).selectorGraph.getRelationEntries({downstreamSelectorKey:o}).filter(([n,{source:S}])=>S!==o).map(([n,{source:S}])=>S).filter((n)=>CF(T,n))};var MA=(o,T,f)=>{let n=[],S=TS(o,f);while(S.length>0){let A=S.shift();if(T.has(A))continue;if(T.add(A),!oS(f,A))S.push(...TS(A,f));else if(!n.includes(A))n.push(A)}return n},mF=(o,T)=>{let f=o.key,n=TS(f,T),S=new Set;return n.flatMap((A)=>oS(T,A)?A:MA(A,S,T))};var IF=(o,T,f,n)=>{let S=C(n);if(T.type==="atom"||T.type==="mutable_atom")S.selectorAtoms.set({selectorKey:o,atomKey:T.key}),n.logger.info("\uD83D\uDD0D","selector",o,`discovers root atom "${T.key}"`);else{let A=MA(T.key,f,n);n.logger.info("\uD83D\uDD0D","selector",o,`discovers root atoms: [ ${A.map(($)=>`"${$}"`).join(", ")} ]`);for(let $ of A)S.selectorAtoms=S.selectorAtoms.set({selectorKey:o,atomKey:$})}f.add(T.key)};var fS=(o,T,f)=>({get:(...n)=>{let S=C(f),A;if(n.length===2){let[J,R]=n;A=i(f,J,R)}else[A]=n;let $=$o(f,A),F=PT(f,$);return f.logger.info("\uD83D\uDD0C","selector",o,`registers dependency ( "${A.key}" =`,F,")"),S.selectorGraph.set({upstreamSelectorKey:A.key,downstreamSelectorKey:o},{source:A.key}),IF(o,A,T,f),F},set:(...n)=>{let S,A;if(n.length===2)S=n[0],A=n[1];else{let J=n[0],R=n[1];A=n[2],S=i(f,J,R)}let $=C(f),F=$o($,S);en($,F,A)},find:(n,S)=>i(f,n,S),json:(n)=>Io(f,n)});var nn=(o,T,f)=>{let n=C(o),S=new oo,A=new Set,{get:$,find:F,json:J}=fS(T.key,A,n),R=()=>{let X=T.get({get:$,find:F,json:J});return OT(C(o),T.key,X,S),A.clear(),X},M={...T,subject:S,install:(X)=>nn(X,T,f),get:R,type:"readonly_selector",...f&&{family:f}};n.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 Rn=(o,T,f)=>{let n=C(o),S=new oo,A=new Set,$=fS(T.key,A,n),{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,S),A.clear(),q},X={...T,subject:S,install:(L)=>Rn(L,T,f),get:_,set:(L)=>{let h=C(o),q=_(T.get,h),P=un(L)(q);if(o.logger.info("\uD83D\uDCDD","selector",T.key,"set (",q,"->",P,")"),OT(h,T.key,P,S),zf(h,T.key),jo(h))S.next({newValue:P,oldValue:q});T.set($,P)},type:"selector",...f&&{family:f}};n.selectors.set(T.key,X);let D=_();o.logger.info("\u2728",X.type,X.key,"=",D);let K={key:T.key,type:"selector"};if(f)K.family=f;return K};function jT(o,T){if("set"in T){let S=Rn(o,T,void 0);return o.on.selectorCreation.next(S),S}let n=nn(o,T,void 0);return o.on.selectorCreation.next(n),n}function LF(o,T){let f=C(o),{key:n}=T,S=$o(f,T);if(!S.family)o.logger.error("\u274C","selector",n,"Standalone selectors cannot be disposed.");else{if(f.molecules.get(S.family.subKey))f.moleculeData.delete(S.family.subKey,S.family.key);let $;switch(T.type){case"selector":f.selectors.delete(n),$={key:S.family.key,type:"selector_family"},$o(o,$).subject.next({type:"state_disposal",subType:"selector",token:T});break;case"readonly_selector":f.readonlySelectors.delete(n),$={key:S.family.key,type:"readonly_selector_family"},$o(o,$).subject.next({type:"state_disposal",subType:"selector",token:T});break}if(f.valueMap.delete(n),f.selectorAtoms.delete(n),f.selectorGraph.delete(n),o.logger.info("\uD83D\uDD25",T.type,n,"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 Sn(o,T,f){let n={key:T.key,type:"selector_family"},S=o.families.get(T.key);if(S)o.logger.error("\u2757","selector_family",T.key,`Overwriting an existing ${VT(S)} "${S.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=Rn(w,{key:_,get:T.get(J),set:T.set(J)},M);return A.next({type:"state_creation",token:X}),X},n,{internalRoles:f,subject:A,install:(J)=>Sn(J,T),default:(J)=>{return T.get(J)({get:(...M)=>Ro(o,...M),find:(M,_)=>i(o,M,_),json:(M)=>Io(o,M)})}});return o.families.set(T.key,F),n}function jF(o,T,f){return Sn(o,{key:`${T.key}:JSON`,get:(S)=>({get:A})=>{let $=A(T,S);return f.toJson($)},set:(S)=>({set:A},$)=>{A(T,S,f.fromJson($))}},["mutable","json"])}var vo=(o)=>JSON.parse(o),fo=(o)=>JSON.stringify(o),S4=[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 mF(T,o).map((S)=>{let A=f.atoms.get(S);if(A===void 0)throw new Error(`Atom "${S}", 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",S,"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,n){function S(_){if(o.operation.open){let w=o.on.operationClose.subscribe(`state subscription ${f}`,()=>{w(),n(_)})}else n(_)}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=S;if($)F=kA(o,A),J=(_)=>{if(F)F.length=0,F.push(...kA(o,A));S(_)};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,n)=>{let S=$o(o,T);o.logger.info("\uD83D\uDC40","timeline",T.key,`Adding subscription "${f}"`);let A=S.subject.subscribe(f,n);return()=>{o.logger.info("\uD83D\uDE48","timeline",T.key,`Removing subscription "${f}" from timeline`),A()}};var OA=(o,T,f,n)=>{let S=$o(o,T);o.logger.info("\uD83D\uDC40","transaction",T.key,`Adding subscription "${f}"`);let A=S.subject.subscribe(f,n);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 n=o.family?{key:`*${o.family.key}`,subKey:o.family.subKey}:void 0,S=FT(T,{key:f,default:null},n);if(T.parent?.valueMap.has(f)){let A=T.parent.valueMap.get(f);T.valueMap.set(f,A)}return S}unsubscribeFromInnerValue;unsubscribeFromState;observeCore(o,T,f){let n=`tracker:${f.config.name}:${Mo(f)?f.transactionMeta.update.key:"main"}:${o.key}`,S=Ro(f,o);this.unsubscribeFromInnerValue=S.subscribe(n,(A)=>{Uo(f,T,A)}),this.unsubscribeFromState=lo(f,o,n,(A)=>{if(A.newValue!==A.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=A.newValue.subscribe(n,($)=>{Uo(f,T,$)})})}updateCore(o,T,f){let n=`tracker:${f.config.name}:${Mo(f)?f.transactionMeta.update.key:"main"}:${o.key}`;lo(f,T,n,({newValue:S,oldValue:A})=>{let $=f.timelineTopics.getRelatedKey(T.key);if($){if(f.timelines.get($)?.timeTraveling){let R=WA(f,{key:$,type:"timeline"},n,(M)=>{R(),Uo(f,o,(_)=>{if(M==="redo"&&S)_.do(S);else if(M==="undo"&&A)_.undo(A);return _})});return}}let F=f.on.operationClose.subscribe(n,()=>{F();let J=Ro(f,o),R=S===null?-1:J.getUpdateNumber(S),M=R-J.cacheUpdateNumber;if(S&&M===1)Uo(f,o,(_)=>(_.do(S),_));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 Mn(o,T,f){o.logger.info("\uD83D\uDD28","atom",T.key,`creating in store "${o.config.name}"`);let n=C(o),S=n.atoms.get(T.key);if(S&&S.type==="mutable_atom")return o.logger.error("\u274C","atom",T.key,"Tried to create atom, but it already exists in the store."),nT(S);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}"`),Mn(R,T,f)},subject:A};if(f)$.family=f;let F=T.default();n.atoms.set($.key,$),nS(o,T.key),OT(n,T.key,F,A);let J=nT($);if(T.effects){let R=0,M=[];for(let _ of T.effects){let w=_({setSelf:(X)=>{Uo(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`,(n)=>{let{type:S,token:A}=n;if(A.family){let $=vo(A.family.subKey);switch(S){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 fn(o,T,f){let n={key:T.key,type:"mutable_atom_family"},S=o.families.get(T.key);if(S)o.logger.error("\u2757","mutable_atom_family",T.key,`Overwriting an existing ${VT(S)} "${S.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 D=Mn(w,X,M);return A.next({type:"state_creation",token:D}),D},n,{subject:A,install:(J)=>fn(J,T),toJson:T.toJson,fromJson:T.fromJson,internalRoles:f});return o.families.set(T.key,F),jF(o,F,T),new _A(F,o),n}var wA=(o,T)=>{let f=C(T),n=`${o.key}:JSON`;return f.families.get(n)};var Io=(o,T)=>{if(T.family){let n=C(o),A={key:`${T.family.key}:JSON`,type:"selector_family"},$=$o(n,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 Fn(o,T,f){let n=f.valueMap.get(T.key),S=o.valueMap.get(T.key);if(n===S){if(n===void 0)return typeof T.default==="function"?T.default():T.default;f.logger.info("\uD83D\uDCC3","atom",T.key,"copying");let A=T.toJson(n),$=T.fromJson(A);return o.valueMap.set(T.key,$),new $f(T,f),$}return S}function OT(o,T,f,n){let S=o.valueMap.get(T);if(S instanceof Tn)S.use(f);if(f instanceof Promise){let A=new Tn(f);return o.valueMap.set(T,A),A.then(($)=>{OT(o,T,$,n),n.next({newValue:$,oldValue:A})}).catch(($)=>{o.logger.error("\uD83D\uDCA5","state",T,"rejected:",$)}),A}return o.valueMap.set(T,f),f}var nF=(o,T)=>{let f=T.valueMap.get(o.key);if(o.type==="mutable_atom"&&Mo(T)){let{parent:n}=T;f=Fn(T,o,n)}return f},JF=(o,T)=>{let f=T.valueMap.get(o);if(f instanceof Tn){let n=f,S=T.selectors.get(o)??T.readonlySelectors.get(o);if(S)n.use(S.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)},nS=(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 n=C(o),S=n.atoms.get(T.key);if(S&&S.type==="atom")return o.logger.error("\u274C","atom",T.key,"Tried to create atom, but it already exists in the store."),nT(S);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();n.atoms.set($.key,$),nS(o,T.key),OT(n,T.key,F,A);let J=nT($);if(T.effects){let R=0,M=[];for(let _ of T.effects){let w=_({setSelf:(X)=>{Uo(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 S=Mn(o,T,void 0);return o.on.atomCreation.next(S),S}let n=FT(o,T,void 0);return o.on.atomCreation.next(n),n}function RA(o,T){let f=C(o),{key:n,family:S}=T,A=$o(f,T);if(!S)o.logger.error("\u274C","atom",n,"Standalone atoms cannot be disposed.");else{A.cleanup?.();let $=o.valueMap.get(A.key),F=$o(o,{key:S.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(n),f.valueMap.delete(n),f.selectorAtoms.delete(n),f.atomsThatAreDefault.delete(n),o.timelineTopics.delete(n),T.type==="mutable_atom"){let M=bT(T);RA(o,M),o.trackers.delete(n)}if(o.logger.info("\uD83D\uDD25","atom",n,"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 n of this.transactionUpdates)this.doStep(n);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),n=o.substring(T+1);switch(f){case"add":this.add(JSON.parse(n));break;case"clear":this.clear();break;case"del":this.delete(JSON.parse(n));break;case"tx":for(let S of n.split(";"))this.doStep(S)}}getUpdateNumber(o){let T=o.indexOf("=");return Number(o.substring(0,T))}do(o){let T=o.indexOf("="),f=Number(o.substring(0,T)),n=f-this.cacheUpdateNumber;if(n>0){if(n===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(n)<this.cacheLimit){let A=this.cacheIdx+n;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),n=o.substring(T+1);switch(f){case"add":this.delete(JSON.parse(n));break;case"del":this.add(JSON.parse(n));break;case"clear":{let S=JSON.parse(n);for(let A of S)this.add(A);break}case"tx":{let S=n.split(";");for(let A=S.length-1;A>=0;A--)this.undoStep(S[A])}}}undo(o){let T=o.indexOf("=");if(Number(o.substring(0,T))===this.cacheUpdateNumber){this.mode="playback";let n=o.substring(T+1);return this.undoStep(n),this.mode="record",this.cacheUpdateNumber--,null}return this.cacheUpdateNumber}}class An{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=no.STORE){this.store=f,this.realm=new SA(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)=>{Uo(f,...Y)},find:(...Y)=>i(f,...Y),json:(Y)=>Io(f,Y)};let n=o.between[0],S=o.between[1],A=fn(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},z)=>Y(A,z),F=({set:Y},z,U)=>{if(!this.store.molecules.has(fo(z)))this.realm.allocate(o.key,z);Y(A,z,(Q)=>Q.add(U)),Y(A,U,(Q)=>Q.add(z))},J=({set:Y},z,U)=>{Y(A,z,(Q)=>{return Q.delete(U),Q}),Y(A,U,(Q)=>{return Q.delete(z),Q})},R=(Y,z,U)=>{let{find:Q,get:v,set:l}=Y,G=Q(A,z),s=v(G);for(let r of s){if(U.includes(r))continue;l(A,r,(ko)=>{return ko.delete(z),ko})}l(G,(r)=>{return r.transaction((a)=>{a.clear();for(let ko of U){let Lo=$(Y,ko),fT=Lo.has(z);if(this.relations.cardinality==="1:n"){let IT=[];for(let E of Lo){if(E===z)continue;let p=$(Y,E);if(p.delete(ko),p.size===0)IT.push(E)}if(!fT&&Lo.size>0)Lo.clear();for(let E of IT){let p=[ko,E].sort(),Fo=`"${p[0]}:${p[1]}"`;this.molecules.delete(Fo)}}if(!fT)Lo.add(z);a.add(ko)}return!0}),r})},M=(Y,z,U)=>{let{set:Q}=Y;Q(A,z,(v)=>{return v.transaction((l)=>{for(let G of U)l.add(G);return!0}),v});for(let v of U)Q(A,v,(l)=>{return l.add(z),l});return!0},_=(Y,z,U)=>{let Q=$(Y,z);return U?Q.has(U):Q.size>0},w={getRelatedKeys:(Y)=>$(this.toolkit,Y),addRelation:(Y,z)=>{this.store.moleculeJoins.set(Y,o.key),this.store.moleculeJoins.set(z,o.key),F(this.toolkit,Y,z)},deleteRelation:(Y,z)=>{J(this.toolkit,Y,z)},replaceRelationsSafely:(Y,z)=>{R(this.toolkit,Y,z)},replaceRelationsUnsafely:(Y,z)=>{M(this.toolkit,Y,z)},has:(Y,z)=>_(this.toolkit,Y,z)},X,D;if(T){D=NT(f,{key:`${o.key}/content`,default:T},["join","content"]);let Y=({get:Q},v)=>Q(D,v),z=({set:Q},v,l)=>{Q(D,v,l)};X=Object.assign(w,{getContent:(Q)=>{return Y(this.toolkit,Q)},setContent:(Q,v)=>{z(this.toolkit,Q,v)},deleteContent:(Q)=>{this.realm.deallocate(Q)}})}else X=w;let K=new No(o,{externalStore:X,isAType:o.isAType,isBType:o.isBType,makeContentKey:(...Y)=>{let[z,U]=Y,Q=Y.sort(),v=`${Q[0]}:${Q[1]}`,l=f.molecules.get(fo(z)),G=f.molecules.get(fo(U));if(!l)this.realm.allocate(o.key,z);if(!G)this.realm.allocate(o.key,U);return this.realm.allocate(z,v,"all"),this.realm.claim(U,v),this.store.moleculeJoins.set(v,o.key),v}}),L=()=>hT(f,{key:`${o.key}/singleRelatedKey`,get:(Y)=>({get:z})=>{let U=z(A,Y);for(let Q of U)return Q;return null}},["join","keys"]),h=()=>{return hT(f,{key:`${o.key}/multipleRelatedKeys`,get:(Y)=>({get:z})=>{let U=wA(A,f);return z(U,Y).members}},["join","keys"])},q=()=>hT(f,{key:`${o.key}/singleRelatedEntry`,get:(Y)=>({get:z})=>{let U=z(A,Y);for(let Q of U){let v=K.isAType?.(Y)?Y:void 0,l=v===void 0?Y:void 0;v??=Q,l??=Q;let G=K.makeContentKey(v,l),s=z(D,G);return[Q,s]}return null}},["join","entries"]),P=()=>hT(f,{key:`${o.key}/multipleRelatedEntries`,get:(Y)=>({get:z})=>{let U=wA(A,f);return z(U,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=z(D,s);return[v,r]})}},["join","entries"]);switch(o.cardinality){case"1:1":{let Y=L(),z=`${n}KeyOf${Wo(S)}`,U=`${S}KeyOf${Wo(n)}`,Q={[z]:Y,[U]:Y},v;if(T){let l=q(),G=`${n}EntryOf${Wo(S)}`,s=`${S}EntryOf${Wo(n)}`,r={[G]:l,[s]:l};v=Object.assign(Q,r)}else v=Q;this.relations=K,this.states=v;break}case"1:n":{let Y=L(),z=h(),U=`${n}KeyOf${Wo(S)}`,Q=`${S}KeysOf${Wo(n)}`,v={[U]:Y,[Q]:z},l;if(T){let G=q(),s=P(),r=`${n}EntryOf${Wo(S)}`,a=`${S}EntriesOf${Wo(n)}`,ko={[r]:G,[a]:s};l=Object.assign(v,ko)}else l=v;this.relations=K,this.states=l;break}case"n:n":{let Y=h(),z=`${n}KeysOf${Wo(S)}`,U=`${S}KeysOf${Wo(n)}`,Q={[z]:Y,[U]:Y},v;if(T){let l=P(),G=`${n}EntriesOf${Wo(S)}`,s=`${S}EntriesOf${Wo(n)}`,r={[G]:l,[s]:l};v=Object.assign(Q,r)}else v=Q;this.relations=K,this.states=v}}}}function Qf(o,T){let f=T.joins.get(o.key);if(f===void 0){let S=no.STORE.joins.get(o.key);if(S===void 0)throw new Error(`Join "${o.key}" not found in store "${T.config.name}"`);f=new An(S.options,S.defaultContent,T),T.joins.set(o.key,f)}return f}function $n(o,T,f){let n=Qf(o,f),S=C(f);if(Mo(S)){let{toolkit:A}=S.transactionMeta;n.transact(A,({relations:$})=>{T($)})}else T(n.relations)}function dn(o,T,f){let n=Qf(o,f),S;switch(o.cardinality){case"1:1":{let A=`${o.a}KeyOf${Wo(o.b)}`,$=`${o.b}KeyOf${Wo(o.a)}`;S={get[A](){let J=n.states[A];return i(f,J,T)},get[$](){let J=n.states[$];return i(f,J,T)}};let F=`${o.a}EntryOf${Wo(o.b)}`;if(F in n.states){let J=`${o.b}EntryOf${Wo(o.a)}`;Object.assign(S,{get[F](){let R=n.states[F];return i(f,R,T)},get[J](){let R=n.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)}`;S={get[A](){let J=n.states[A];return i(f,J,T)},get[$](){let J=n.states[$];return i(f,J,T)}};let F=`${o.a}EntryOf${Wo(o.b)}`;if(F in n.states){let J=`${o.b}EntriesOf${Wo(o.a)}`;Object.assign(S,{get[F](){let R=n.states[F];return i(f,R,T)},get[J](){let R=n.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)}`;S={get[A](){let J=n.states[A];return i(f,J,T)},get[$](){let J=n.states[$];return i(f,J,T)}};let F=`${o.a}EntriesOf${Wo(o.b)}`;if(F in n.states){let J=`${o.b}EntriesOf${Wo(o.a)}`;Object.assign(S,{get[F](){let R=n.states[F];return i(f,R,T)},get[J](){let R=n.states[J];return i(f,R,T)}})}}}return S}function s$(o,T){return Qf(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[n,S]of o.atoms)if(!n.includes("\uD83D\uDD0D")){let A=nT(S);if(S.family){let $=f.get(S.family.key);if(!$||!("familyMembers"in $))$={key:S.family.key,familyMembers:new Map},f.set(S.family.key,$);$.familyMembers.set(S.family.subKey,A)}else f.set(n,A)}return f},effects:[({setSelf:f})=>{o.on.atomCreation.subscribe("introspection",(n)=>{if(n.key.includes("\uD83D\uDD0D"))return;f((S)=>{if(n.family){let{key:A,subKey:$}=n.family,F=S.get(A);if(F===void 0||!("familyMembers"in F))F={key:A,familyMembers:new Map},S.set(A,F);F.familyMembers.set($,n)}else S.set(n.key,n);return S})}),o.on.atomDisposal.subscribe("introspection",(n)=>{f((S)=>{if(n.family){let{key:A,subKey:$}=n.family,F=S.get(A);if(F&&"familyMembers"in F){if(F.familyMembers.delete($),F.familyMembers.size===0)S.delete(A)}}else S.delete(n.key);return S})})}]},void 0);return jT(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 n of[o.readonlySelectors,o.selectors])for(let[S,A]of n)if(!S.includes("\uD83D\uDD0D")){let $=nT(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(S,$)}return f},effects:[({setSelf:f})=>{o.on.selectorCreation.subscribe("introspection",(n)=>{if(n.key.includes("\uD83D\uDD0D"))return;f((S)=>{if(n.family){let{key:A,subKey:$}=n.family,F=S.get(A);if(F===void 0||!("familyMembers"in F))F={key:A,familyMembers:new Map},S.set(A,F);F.familyMembers.set($,n)}else S.set(n.key,n);return S})}),o.on.selectorDisposal.subscribe("introspection",(n)=>{f((S)=>{if(n.family){let{key:A,subKey:$}=n.family,F=S.get(A);if(F&&"familyMembers"in F){if(F.familyMembers.delete($),F.familyMembers.size===0)S.delete(A)}}else S.delete(n.key);return S})})}]},void 0);return jT(o,{key:"\uD83D\uDD0D Selector Token Index",get:({get:f})=>f(T)})};class SS{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(n){try{if(o instanceof f)return{type:T,data:o}}catch(S){}}return null}}var HA=new SS({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 SS({object:KA,array:(o)=>Array.isArray(o)}),jM=new SS({...HA.supported,...GA.supported}),Df=(o)=>{if(o===void 0)return"undefined";let T=jM.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=no.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),n=[...T.values()].filter((F)=>("familyMembers"in F)),S=[...f.values()].filter((F)=>("familyMembers"in F)),A=performance.now(),$=[];if(o.atomFamilies)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])}}if(o.selectorFamilies)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])}}return $}[Symbol.dispose](){this.unsubscribeFromAtomCreation(),this.unsubscribeFromAtomDisposal(),this.unsubscribeFromSelectorCreation(),this.unsubscribeFromSelectorDisposal(),this.disposed=!0}}var YA=(o,T)=>{let f=(n,S)=>{let $=((J,R)=>{let M=T(J,R);if(M)return M;return null})(n,S);if($?.jobComplete??$?.pathComplete)return $;let F=Array.isArray(S)?S.map((J,R)=>[R,J]):KA(S)?Object.entries(S):[];for(let[J,R]of F){let M=f([...n,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 n="",S=[],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)S.push([R,JSON.stringify(J)])}),n=`\uFF5E${$.length} \uFF0B${S.length} \uFF0D${A.length}`,{summary:n,added:S,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 n of Object.keys(o.supported)){let S=f[n];this.leafDiffers[n]=S}for(let n of Object.keys(T.supported)){let S=f[n];this.treeDiffers[n]=S}}diff(o,T){if(o===T)return{summary:"No Change"};let f=this.leafRefinery.refine(o)??this.treeRefinery.refine(o),n=this.leafRefinery.refine(T)??this.treeRefinery.refine(T);if(f!==null&&n!==null){if(f.type===n.type){if(f.type in this.leafDiffers)return this.leafDiffers[f.type](f.data,n.data);if(f.type in this.treeDiffers)return this.treeDiffers[f.type](f.data,n.data,(F,J)=>this.diff(F,J))}}let S=Df(o),A=Df(T);if(S===A)return{summary:`${S} \u2192 ${A}`};return{summary:`Type change: ${S} \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 AS{key;type="continuity";globals=[];actions=[];perspectives=[];constructor(o){this.key=o}static existing=new vF;static create(o,T){let f=new AS(o),{type:n,globals:S,actions:A,perspectives:$}=T(f),F={type:n,key:o,globals:S,actions:A,perspectives:$};return AS.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":case"mutable_atom_family":{let[f,n]=o;this.perspectives.push({type:"realtime_perspective",resourceAtoms:f,viewAtoms:n})}break}return this}}function RK(o){let{key:T,config:f}=o,n=AS.create(T,f),{actions:S}=n;for(let A of S)tF(no.STORE,T,A.key);return GF(no.STORE,T,-1),n}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},Wn=gn({key:"usersInRooms",between:["room","user"],cardinality:"1:n",isAType:(o)=>typeof o==="string",isBType:(o)=>typeof o==="string"},vM),_K=ln({key:"usersInMyRoomView",get:(o)=>({find:T})=>{let f=e$(Wn);return[T(f,o)]}});import{spawn as qM}from"child_process";class Uf{emit;listeners;globalListeners;handleEvent(o,...T){for(let n of this.globalListeners)n(o,...T);let f=this.listeners.get(o);if(f)for(let n of f)n(...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 tA extends Uf{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;default:return}}}constructor(o,T,f){super((n,...S)=>{let A=JSON.stringify([n,...S])+"\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:(...n)=>{console.info(this.id,this.key,...n)},warn:(...n)=>{console.warn(this.id,this.key,...n)},error:(...n)=>{console.error(this.id,this.key,...n)}},this.process.stdout.on("data",(n)=>{let S=n.toString();if(S==="ALIVE")return;this.unprocessedEvents.push(...S.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",(n)=>{let S=n.toString();this.unprocessedLogs.push(...S.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 Uf{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 zA extends Uf{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 n=vo(this.incompleteData);this.logger.info("\uD83C\uDFB0","received",n),this.handleEvent(...n);while(this.unprocessedEvents.length>0){let S=this.unprocessedEvents.shift();if(S){if(this.unprocessedEvents.length===0)this.incompleteData=S;let A=vo(S);this.handleEvent(...A)}}this.incompleteData=""}catch(n){if(n instanceof Error)this.logger.error("\u2757",n.message,n.cause,n.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 n=f(T);if(n)T.disposalFunctions.push(n)}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 QA=Tf({key:"roomArguments",default:["echo",["Hello World!"]]}),rF=ln({key:"room",get:(o)=>async({get:T,find:f})=>{let n=f(QA,o),S=T(n),[A,$]=S,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 tA(F,o)}});var rK=Jn({key:"createRoom",do:({get:o,set:T,find:f},n,S,A)=>{let $=A?[S,A]:[S],F=f(QA,n);T(F,$),T(EA,(M)=>M.add(n));let J=f(rF,n);return o(J)}}),pK=Jn({key:"joinRoom",do:(o,T,f,n)=>{let S={enteredAtEpoch:n};return $n(Wn,(A)=>{A.set({room:T,user:f},S)},o.env().store),S}}),cK=Jn({key:"leaveRoom",do:(o,T,f)=>{$n(Wn,(n)=>{n.delete({room:T,user:f})},o.env().store)}}),ZK=Jn({key:"destroyRoom",do:(o,T)=>{$n(Wn,(f)=>{f.delete({room:T})},o.env().store),o.set(EA,(f)=>(f.delete(T),f))}});function DA(o,T){return T.map((f)=>{switch(f.type){case"transaction_update":{let n=DA(o,f.updates);return{...f,updates:n}}case"atom_update":case"selector_update":case"molecule_creation":case"molecule_disposal":case"molecule_transfer":case"state_creation":case"state_disposal":return f}}).filter((f)=>{switch(f.type){case"atom_update":case"selector_update":return o.includes(f.key);case"state_creation":case"state_disposal":return o.includes(f.token.key);case"molecule_creation":case"transaction_update":case"molecule_disposal":case"molecule_transfer":return!0}})}var gK=Tf({key:"redactor",default:{occlude:(o)=>o}}),Vf=Tf({key:"unacknowledgedUpdates",default:()=>[]});var pF=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)}),UA=gn({key:"usersOfSockets",between:["user","socket"],cardinality:"1:1",isAType:(o)=>o.startsWith("user::"),isBType:(o)=>o.startsWith("socket::")});function cF(o,T,f,n){let S=T.key;return function A(){let $=[];for(let J of T.globals){let R=J.type==="mutable_atom"?Io(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 D=X.type==="mutable_atom"?Io(o,X):X,K=Ro(o,D);$.push(D,K)}}let F=jo(o)?o.transactionMeta.epoch.get(S)??null:null;n?.emit(`continuity-init:${S}`,F,$)}}function ZF(o,T,f){let n=T.key;return function S(A){o.logger.info("\uD83D\uDECE\uFE0F","continuity",n,"received",A);let{key:$,id:F}=A,J=`tx-run:${$}:${F}`,R=`${J}:start`,M=`${J}:end`;performance.mark(R);try{tf(o,{type:"transaction",key:$},F)(...A.params)}catch(w){if(w instanceof Error)o.logger.error("\u274C","continuity",n,`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,n){let S=T.key;return function A($){if(o.logger.info("\uD83D\uDC4D","continuity",S,`${f} acknowledged epoch ${$}`),n[0]?.epoch===$)Uo(o,Vf,f,(J)=>{return J.shift(),o.logger.info("\uD83D\uDC4D","continuity",S,`${f} unacknowledged update queue now has`,J.length,"items"),J})}}function iF(o,T,f,n){let S=T.key,A=[];for(let $ of T.actions){let F=OA(o,$,`sync-continuity:${S}:${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,D=i(o,X,f);return Ro(o,D).map((L)=>{return L.type==="mutable_atom"?"*"+L.key:L.key})})),M=DA(R,J.updates),_={...J,updates:M};Uo(o,Vf,f,(w)=>{if(_)w.push(_),w.sort((X,D)=>X.epoch-D.epoch),o.logger.info("\uD83D\uDC4D","continuity",S,`${f} unacknowledged update queue now has`,w.length,"items");return w}),n?.emit(`tx-new:${S}`,_)}catch(R){if(R instanceof Error)o.logger.error("\u274C","continuity",S,`${f} failed to send update from transaction ${$.key} to ${f}`,R.message)}});A.push(F)}return A}function gF(o,T,f,n){let S=T.key,A=[];for(let $ of T.perspectives){let{viewAtoms:F}=$,J=i(o,F,f),R=lo(o,J,`sync-continuity:${S}:${f}:perspective:${$.resourceAtoms.key}`,({oldValue:M,newValue:_})=>{let w=M.map((L)=>L.key),X=_.map((L)=>L.key),D=M.filter((L)=>!X.includes(L.key)),K=_.filter((L)=>!w.includes(L.key)).flatMap((L)=>{let h=L.type==="mutable_atom"?Io(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:D}),K.length>0)n?.emit(`reveal:${S}`,K);if(D.length>0)n?.emit(`conceal:${S}`,D)});A.push(R)}return A}function U5({socket:o,store:T=no.STORE}){return function f(n){let S=o,A=n.key,$=dn(UA,`socket::${S.id}`,T).userKeyOfSocket,F=Ro(T,$);if(!F)return T.logger.error("\u274C","continuity",A,`Tried to create a synchronizer for a socket (${S.id}) that is not connected to a user.`),()=>{};let J=dn(UA,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,pF,h);S=Ro(T,q);for(let Y of M)S?.emit(`tx-new:${A}`,Y)}),M=Ro(T,Vf,F),_=[],w=gF(T,n,F,S),X=iF(T,n,F,S);_.push(...w,...X);let D=cF(T,n,F,o);S.off(`get:${A}`,D),S.on(`get:${A}`,D);let K=ZF(T,n,F);S.off(`tx-run:${A}`,K),S.on(`tx-run:${A}`,K);let L=PF(T,n,F,M);return S?.on(`ack:${A}`,L),()=>{for(let h of _)h();S?.off(`ack:${A}`,L),S?.off(`get:${A}`,D),S?.off(`tx-run:${A}`,K)}}}var{file:L1,serve:nk}=globalThis.Bun;import{readFileSync as JJ}from"fs";import{resolve as IA}from"path";function rM(o,T){let f={},n=[];for(let S in o){let A=o[S],$=T[S],F=A["~standard"].validate($);if(F instanceof Promise)throw new Error(`Validation must be synchronous, but ${S} returned a Promise.`);if(F.issues){n.push(...F.issues.map((J)=>({...J,path:[S,...J.path??[]]})));continue}f[S]=F.value}if(n.length)return{issues:n};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 S=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,...$,...S}:{...S,...$},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)},D=(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(D(P))return;if(!X(P))return _(P);return Reflect.get(q,P)}})}var Ao;(function(o){o.assertEqual=(S)=>S;function T(S){}o.assertIs=T;function f(S){throw new Error}o.assertNever=f,o.arrayToEnum=(S)=>{let A={};for(let $ of S)A[$]=$;return A},o.getValidEnumValues=(S)=>{let A=o.objectKeys(S).filter((F)=>typeof S[S[F]]!=="number"),$={};for(let F of A)$[F]=S[F];return o.objectValues($)},o.objectValues=(S)=>{return o.objectKeys(S).map(function(A){return S[A]})},o.objectKeys=typeof Object.keys==="function"?(S)=>Object.keys(S):(S)=>{let A=[];for(let $ in S)if(Object.prototype.hasOwnProperty.call(S,$))A.push($);return A},o.find=(S,A)=>{for(let $ of S)if(A($))return $;return},o.isInteger=typeof Number.isInteger==="function"?(S)=>Number.isInteger(S):(S)=>typeof S==="number"&&isFinite(S)&&Math.floor(S)===S;function n(S,A=" | "){return S.map(($)=>typeof $==="string"?`'${$}'`:$).join(A)}o.joinValues=n,o.jsonStringifyReplacer=(S,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}},t=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"]),pM=(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(S){return S.message},f={_errors:[]},n=(S)=>{for(let A of S.issues)if(A.code==="invalid_union")A.unionErrors.map(n);else if(A.code==="invalid_return_type")n(A.returnTypeError);else if(A.code==="invalid_arguments")n(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 n(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 n of this.issues)if(n.path.length>0)T[n.path[0]]=T[n.path[0]]||[],T[n.path[0]].push(o(n));else f.push(o(n));return{formErrors:f,fieldErrors:T}}get formErrors(){return this.flatten()}}JT.create=(o)=>{return new JT(o)};var mf=(o,T)=>{let f;switch(o.code){case t.invalid_type:if(o.received===N.undefined)f="Required";else f=`Expected ${o.expected}, received ${o.received}`;break;case t.invalid_literal:f=`Invalid literal value, expected ${JSON.stringify(o.expected,Ao.jsonStringifyReplacer)}`;break;case t.unrecognized_keys:f=`Unrecognized key(s) in object: ${Ao.joinValues(o.keys,", ")}`;break;case t.invalid_union:f="Invalid input";break;case t.invalid_union_discriminator:f=`Invalid discriminator value. Expected ${Ao.joinValues(o.options)}`;break;case t.invalid_enum_value:f=`Invalid enum value. Expected ${Ao.joinValues(o.options)}, received '${o.received}'`;break;case t.invalid_arguments:f="Invalid function arguments";break;case t.invalid_return_type:f="Invalid function return type";break;case t.invalid_date:f="Invalid date";break;case t.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 t.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 t.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 t.custom:f="Invalid input";break;case t.invalid_intersection_types:f="Intersection results could not be merged";break;case t.not_multiple_of:f=`Number must be a multiple of ${o.multipleOf}`;break;case t.not_finite:f="Number must be finite";break;default:f=T.defaultError,Ao.assertNever(o)}return{message:f}},sF=mf;function cM(o){sF=o}function $S(){return sF}var FS=(o)=>{let{data:T,path:f,errorMaps:n,issueData:S}=o,A=[...f,...S.path||[]],$={...S,path:A};if(S.message!==void 0)return{...S,path:A,message:S.message};let F="",J=n.filter((R)=>!!R).slice().reverse();for(let R of J)F=R($,{data:T,defaultError:F}).message;return{...S,path:A,message:F}},ZM=[];function m(o,T){let f=$S(),n=FS({issueData:T,data:o.data,path:o.path,errorMaps:[o.common.contextualErrorMap,o.schemaErrorMap,f,f===mf?void 0:mf].filter((S)=>!!S)});o.common.issues.push(n)}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 n of T){if(n.status==="aborted")return d;if(n.status==="dirty")o.dirty();f.push(n.value)}return{status:o.value,value:f}}static async mergeObjectAsync(o,T){let f=[];for(let n of T){let S=await n.key,A=await n.value;f.push({key:S,value:A})}return uo.mergeObjectSync(o,f)}static mergeObjectSync(o,T){let f={};for(let n of T){let{key:S,value:A}=n;if(S.status==="aborted")return d;if(A.status==="aborted")return d;if(S.status==="dirty")o.dirty();if(A.status==="dirty")o.dirty();if(S.value!=="__proto__"&&(typeof A.value!=="undefined"||n.alwaysSet))f[S.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",_n=(o)=>typeof Promise!=="undefined"&&o instanceof Promise;function JS(o,T,f,n){if(f==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof T==="function"?o!==T||!n:!T.has(o))throw new TypeError("Cannot read private member from an object whose class did not declare it");return f==="m"?n:f==="a"?n.call(o):n?n.value:T.get(o)}function aF(o,T,f,n,S){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!S)throw new TypeError("Private accessor was defined without a setter");if(typeof T==="function"?o!==T||!S:!T.has(o))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?S.call(o,f):S?S.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 On,kn;class ET{constructor(o,T,f,n){this._cachedPath=[],this.parent=o,this.data=T,this._path=f,this._key=n}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:n,description:S}=o;if(T&&(f||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(T)return{errorMap:T,description:S};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:n)!==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:S}}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(_n(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 n={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)},S=this._parseSync({data:o,path:n.path,parent:n});return lF(n,S)}"~validate"(o){var T,f;let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:o,parsedType:vT(o)};if(!this["~standard"].async)try{let S=this._parseSync({data:o,path:[],parent:n});return Ff(S)?{value:S.value}:{issues:n.common.issues}}catch(S){if((f=(T=S===null||S===void 0?void 0:S.message)===null||T===void 0?void 0:T.toLowerCase())===null||f===void 0?void 0:f.includes("encountered"))this["~standard"].async=!0;n.common={issues:[],async:!0}}return this._parseAsync({data:o,path:[],parent:n}).then((S)=>Ff(S)?{value:S.value}:{issues:n.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)},n=this._parse({data:o,path:f.path,parent:f}),S=await(_n(n)?n:Promise.resolve(n));return lF(f,S)}refine(o,T){let f=(n)=>{if(typeof T==="string"||typeof T==="undefined")return{message:T};else if(typeof T==="function")return T(n);else return T};return this._refinement((n,S)=>{let A=o(n),$=()=>S.addIssue({code:t.custom,...f(n)});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,n)=>{if(!o(f))return n.addIssue(typeof T==="function"?T(f,n):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 MS({typeName:g.ZodBranded,type:this,...u(this._def)})}catch(o){let T=typeof o==="function"?o:()=>o;return new pf({...u(this._def),innerType:this,catchValue:T,typeName:g.ZodCatch})}describe(o){return new this.constructor({...this._def,description:o})}pipe(o){return Gn.create(this,o)}readonly(){return cf.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]))$/,nW=/^(([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])$/,SW=/^([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("."),n=f.replace(/-/g,"+").replace(/_/g,"/").padEnd(f.length+(4-f.length%4)%4,"="),S=JSON.parse(atob(n));if(typeof S!=="object"||S===null)return!1;if(!S.typ||!S.alg)return!1;if(T&&S.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)&&nW.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 S=this._getOrReturnCtx(o);return m(S,{code:t.invalid_type,expected:N.string,received:S.parsedType}),d}let f=new uo,n=void 0;for(let S of this._def.checks)if(S.kind==="min"){if(o.data.length<S.value)n=this._getOrReturnCtx(o,n),m(n,{code:t.too_small,minimum:S.value,type:"string",inclusive:!0,exact:!1,message:S.message}),f.dirty()}else if(S.kind==="max"){if(o.data.length>S.value)n=this._getOrReturnCtx(o,n),m(n,{code:t.too_big,maximum:S.value,type:"string",inclusive:!0,exact:!1,message:S.message}),f.dirty()}else if(S.kind==="length"){let A=o.data.length>S.value,$=o.data.length<S.value;if(A||$){if(n=this._getOrReturnCtx(o,n),A)m(n,{code:t.too_big,maximum:S.value,type:"string",inclusive:!0,exact:!0,message:S.message});else if($)m(n,{code:t.too_small,minimum:S.value,type:"string",inclusive:!0,exact:!0,message:S.message});f.dirty()}}else if(S.kind==="email"){if(!sM.test(o.data))n=this._getOrReturnCtx(o,n),m(n,{validation:"email",code:t.invalid_string,message:S.message}),f.dirty()}else if(S.kind==="emoji"){if(!VA)VA=new RegExp(aM,"u");if(!VA.test(o.data))n=this._getOrReturnCtx(o,n),m(n,{validation:"emoji",code:t.invalid_string,message:S.message}),f.dirty()}else if(S.kind==="uuid"){if(!dM.test(o.data))n=this._getOrReturnCtx(o,n),m(n,{validation:"uuid",code:t.invalid_string,message:S.message}),f.dirty()}else if(S.kind==="nanoid"){if(!lM.test(o.data))n=this._getOrReturnCtx(o,n),m(n,{validation:"nanoid",code:t.invalid_string,message:S.message}),f.dirty()}else if(S.kind==="cuid"){if(!PM.test(o.data))n=this._getOrReturnCtx(o,n),m(n,{validation:"cuid",code:t.invalid_string,message:S.message}),f.dirty()}else if(S.kind==="cuid2"){if(!iM.test(o.data))n=this._getOrReturnCtx(o,n),m(n,{validation:"cuid2",code:t.invalid_string,message:S.message}),f.dirty()}else if(S.kind==="ulid"){if(!gM.test(o.data))n=this._getOrReturnCtx(o,n),m(n,{validation:"ulid",code:t.invalid_string,message:S.message}),f.dirty()}else if(S.kind==="url")try{new URL(o.data)}catch(A){n=this._getOrReturnCtx(o,n),m(n,{validation:"url",code:t.invalid_string,message:S.message}),f.dirty()}else if(S.kind==="regex"){if(S.regex.lastIndex=0,!S.regex.test(o.data))n=this._getOrReturnCtx(o,n),m(n,{validation:"regex",code:t.invalid_string,message:S.message}),f.dirty()}else if(S.kind==="trim")o.data=o.data.trim();else if(S.kind==="includes"){if(!o.data.includes(S.value,S.position))n=this._getOrReturnCtx(o,n),m(n,{code:t.invalid_string,validation:{includes:S.value,position:S.position},message:S.message}),f.dirty()}else if(S.kind==="toLowerCase")o.data=o.data.toLowerCase();else if(S.kind==="toUpperCase")o.data=o.data.toUpperCase();else if(S.kind==="startsWith"){if(!o.data.startsWith(S.value))n=this._getOrReturnCtx(o,n),m(n,{code:t.invalid_string,validation:{startsWith:S.value},message:S.message}),f.dirty()}else if(S.kind==="endsWith"){if(!o.data.endsWith(S.value))n=this._getOrReturnCtx(o,n),m(n,{code:t.invalid_string,validation:{endsWith:S.value},message:S.message}),f.dirty()}else if(S.kind==="datetime"){if(!fJ(S).test(o.data))n=this._getOrReturnCtx(o,n),m(n,{code:t.invalid_string,validation:"datetime",message:S.message}),f.dirty()}else if(S.kind==="date"){if(!$W.test(o.data))n=this._getOrReturnCtx(o,n),m(n,{code:t.invalid_string,validation:"date",message:S.message}),f.dirty()}else if(S.kind==="time"){if(!FW(S).test(o.data))n=this._getOrReturnCtx(o,n),m(n,{code:t.invalid_string,validation:"time",message:S.message}),f.dirty()}else if(S.kind==="duration"){if(!eM.test(o.data))n=this._getOrReturnCtx(o,n),m(n,{validation:"duration",code:t.invalid_string,message:S.message}),f.dirty()}else if(S.kind==="ip"){if(!JW(o.data,S.version))n=this._getOrReturnCtx(o,n),m(n,{validation:"ip",code:t.invalid_string,message:S.message}),f.dirty()}else if(S.kind==="jwt"){if(!RW(o.data,S.alg))n=this._getOrReturnCtx(o,n),m(n,{validation:"jwt",code:t.invalid_string,message:S.message}),f.dirty()}else if(S.kind==="cidr"){if(!MW(o.data,S.version))n=this._getOrReturnCtx(o,n),m(n,{validation:"cidr",code:t.invalid_string,message:S.message}),f.dirty()}else if(S.kind==="base64"){if(!SW.test(o.data))n=this._getOrReturnCtx(o,n),m(n,{validation:"base64",code:t.invalid_string,message:S.message}),f.dirty()}else if(S.kind==="base64url"){if(!AW.test(o.data))n=this._getOrReturnCtx(o,n),m(n,{validation:"base64url",code:t.invalid_string,message:S.message}),f.dirty()}else Ao.assertNever(S);return{status:f.value,value:o.data}}_regex(o,T,f){return this.refinement((n)=>o.test(n),{validation:T,code:t.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,n=(T.toString().split(".")[1]||"").length,S=f>n?f:n,A=parseInt(o.toFixed(S).replace(".","")),$=parseInt(T.toFixed(S).replace(".",""));return A%$/Math.pow(10,S)}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 S=this._getOrReturnCtx(o);return m(S,{code:t.invalid_type,expected:N.number,received:S.parsedType}),d}let f=void 0,n=new uo;for(let S of this._def.checks)if(S.kind==="int"){if(!Ao.isInteger(o.data))f=this._getOrReturnCtx(o,f),m(f,{code:t.invalid_type,expected:"integer",received:"float",message:S.message}),n.dirty()}else if(S.kind==="min"){if(S.inclusive?o.data<S.value:o.data<=S.value)f=this._getOrReturnCtx(o,f),m(f,{code:t.too_small,minimum:S.value,type:"number",inclusive:S.inclusive,exact:!1,message:S.message}),n.dirty()}else if(S.kind==="max"){if(S.inclusive?o.data>S.value:o.data>=S.value)f=this._getOrReturnCtx(o,f),m(f,{code:t.too_big,maximum:S.value,type:"number",inclusive:S.inclusive,exact:!1,message:S.message}),n.dirty()}else if(S.kind==="multipleOf"){if(WW(o.data,S.value)!==0)f=this._getOrReturnCtx(o,f),m(f,{code:t.not_multiple_of,multipleOf:S.value,message:S.message}),n.dirty()}else if(S.kind==="finite"){if(!Number.isFinite(o.data))f=this._getOrReturnCtx(o,f),m(f,{code:t.not_finite,message:S.message}),n.dirty()}else Ao.assertNever(S);return{status:n.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,n){return new gT({...this._def,checks:[...this._def.checks,{kind:o,value:T,inclusive:f,message:x.toString(n)}]})}_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(S){return this._getInvalidInput(o)}if(this._getType(o)!==N.bigint)return this._getInvalidInput(o);let f=void 0,n=new uo;for(let S of this._def.checks)if(S.kind==="min"){if(S.inclusive?o.data<S.value:o.data<=S.value)f=this._getOrReturnCtx(o,f),m(f,{code:t.too_small,type:"bigint",minimum:S.value,inclusive:S.inclusive,message:S.message}),n.dirty()}else if(S.kind==="max"){if(S.inclusive?o.data>S.value:o.data>=S.value)f=this._getOrReturnCtx(o,f),m(f,{code:t.too_big,type:"bigint",maximum:S.value,inclusive:S.inclusive,message:S.message}),n.dirty()}else if(S.kind==="multipleOf"){if(o.data%S.value!==BigInt(0))f=this._getOrReturnCtx(o,f),m(f,{code:t.not_multiple_of,multipleOf:S.value,message:S.message}),n.dirty()}else Ao.assertNever(S);return{status:n.value,value:o.data}}_getInvalidInput(o){let T=this._getOrReturnCtx(o);return m(T,{code:t.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,n){return new dT({...this._def,checks:[...this._def.checks,{kind:o,value:T,inclusive:f,message:x.toString(n)}]})}_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 If 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 m(f,{code:t.invalid_type,expected:N.boolean,received:f.parsedType}),d}return ao(o.data)}}If.create=(o)=>{return new If({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 S=this._getOrReturnCtx(o);return m(S,{code:t.invalid_type,expected:N.date,received:S.parsedType}),d}if(isNaN(o.data.getTime())){let S=this._getOrReturnCtx(o);return m(S,{code:t.invalid_date}),d}let f=new uo,n=void 0;for(let S of this._def.checks)if(S.kind==="min"){if(o.data.getTime()<S.value)n=this._getOrReturnCtx(o,n),m(n,{code:t.too_small,message:S.message,inclusive:!0,exact:!1,minimum:S.value,type:"date"}),f.dirty()}else if(S.kind==="max"){if(o.data.getTime()>S.value)n=this._getOrReturnCtx(o,n),m(n,{code:t.too_big,message:S.message,inclusive:!0,exact:!1,maximum:S.value,type:"date"}),f.dirty()}else Ao.assertNever(S);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 wn extends e{_parse(o){if(this._getType(o)!==N.symbol){let f=this._getOrReturnCtx(o);return m(f,{code:t.invalid_type,expected:N.symbol,received:f.parsedType}),d}return ao(o.data)}}wn.create=(o)=>{return new wn({typeName:g.ZodSymbol,...u(o)})};class jf extends e{_parse(o){if(this._getType(o)!==N.undefined){let f=this._getOrReturnCtx(o);return m(f,{code:t.invalid_type,expected:N.undefined,received:f.parsedType}),d}return ao(o.data)}}jf.create=(o)=>{return new jf({typeName:g.ZodUndefined,...u(o)})};class Nf extends e{_parse(o){if(this._getType(o)!==N.null){let f=this._getOrReturnCtx(o);return m(f,{code:t.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 m(T,{code:t.invalid_type,expected:N.never,received:T.parsedType}),d}}BT.create=(o)=>{return new BT({typeName:g.ZodNever,...u(o)})};class yn extends e{_parse(o){if(this._getType(o)!==N.undefined){let f=this._getOrReturnCtx(o);return m(f,{code:t.invalid_type,expected:N.void,received:f.parsedType}),d}return ao(o.data)}}yn.create=(o)=>{return new yn({typeName:g.ZodVoid,...u(o)})};class GT extends e{_parse(o){let{ctx:T,status:f}=this._processInputParams(o),n=this._def;if(T.parsedType!==N.array)return m(T,{code:t.invalid_type,expected:N.array,received:T.parsedType}),d;if(n.exactLength!==null){let A=T.data.length>n.exactLength.value,$=T.data.length<n.exactLength.value;if(A||$)m(T,{code:A?t.too_big:t.too_small,minimum:$?n.exactLength.value:void 0,maximum:A?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),f.dirty()}if(n.minLength!==null){if(T.data.length<n.minLength.value)m(T,{code:t.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),f.dirty()}if(n.maxLength!==null){if(T.data.length>n.maxLength.value)m(T,{code:t.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),f.dirty()}if(T.common.async)return Promise.all([...T.data].map((A,$)=>{return n.type._parseAsync(new ET(T,A,T.path,$))})).then((A)=>{return uo.mergeArray(f,A)});let S=[...T.data].map((A,$)=>{return n.type._parseSync(new ET(T,A,T.path,$))});return uo.mergeArray(f,S)}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 zo){let T={};for(let f in o.shape){let n=o.shape[f];T[f]=YT.create(Bf(n))}return new zo({...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 zo 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 m(J,{code:t.invalid_type,expected:N.object,received:J.parsedType}),d}let{status:f,ctx:n}=this._processInputParams(o),{shape:S,keys:A}=this._getCached(),$=[];if(!(this._def.catchall instanceof BT&&this._def.unknownKeys==="strip")){for(let J in n.data)if(!A.includes(J))$.push(J)}let F=[];for(let J of A){let R=S[J],M=n.data[J];F.push({key:{status:"valid",value:J},value:R._parse(new ET(n,M,n.path,J)),alwaysSet:J in n.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:n.data[R]}});else if(J==="strict"){if($.length>0)m(n,{code:t.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=n.data[R];F.push({key:{status:"valid",value:R},value:J._parse(new ET(n,M,n.path,R)),alwaysSet:R in n.data})}}if(n.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 zo({...this._def,unknownKeys:"strict",...o!==void 0?{errorMap:(T,f)=>{var n,S,A,$;let F=(A=(S=(n=this._def).errorMap)===null||S===void 0?void 0:S.call(n,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 zo({...this._def,unknownKeys:"strip"})}passthrough(){return new zo({...this._def,unknownKeys:"passthrough"})}extend(o){return new zo({...this._def,shape:()=>({...this._def.shape(),...o})})}merge(o){return new zo({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 zo({...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 zo({...this._def,shape:()=>T})}omit(o){let T={};return Ao.objectKeys(this.shape).forEach((f)=>{if(!o[f])T[f]=this.shape[f]}),new zo({...this._def,shape:()=>T})}deepPartial(){return Bf(this)}partial(o){let T={};return Ao.objectKeys(this.shape).forEach((f)=>{let n=this.shape[f];if(o&&!o[f])T[f]=n;else T[f]=n.optional()}),new zo({...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 S=this.shape[f];while(S instanceof YT)S=S._def.innerType;T[f]=S}}),new zo({...this._def,shape:()=>T})}keyof(){return nJ(Ao.objectKeys(this.shape))}}zo.create=(o,T)=>{return new zo({shape:()=>o,unknownKeys:"strip",catchall:BT.create(),typeName:g.ZodObject,...u(T)})};zo.strictCreate=(o,T)=>{return new zo({shape:()=>o,unknownKeys:"strict",catchall:BT.create(),typeName:g.ZodObject,...u(T)})};zo.lazycreate=(o,T)=>{return new zo({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 n(S){for(let $ of S)if($.result.status==="valid")return $.result;for(let $ of S)if($.result.status==="dirty")return T.common.issues.push(...$.ctx.common.issues),$.result;let A=S.map(($)=>new JT($.ctx.common.issues));return m(T,{code:t.invalid_union,unionErrors:A}),d}if(T.common.async)return Promise.all(f.map(async(S)=>{let A={...T,common:{...T.common,issues:[]},parent:null};return{result:await S._parseAsync({data:T.data,path:T.path,parent:A}),ctx:A}})).then(n);else{let S=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"&&!S)S={result:R,ctx:J};if(J.common.issues.length)A.push(J.common.issues)}if(S)return T.common.issues.push(...S.ctx.common.issues),S.result;let $=A.map((F)=>new JT(F));return m(T,{code:t.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 jf)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 MS)return xT(o.unwrap());else if(o instanceof cf)return xT(o.unwrap());else if(o instanceof pf)return xT(o._def.innerType);else return[]};class RS extends e{_parse(o){let{ctx:T}=this._processInputParams(o);if(T.parsedType!==N.object)return m(T,{code:t.invalid_type,expected:N.object,received:T.parsedType}),d;let f=this.discriminator,n=T.data[f],S=this.optionsMap.get(n);if(!S)return m(T,{code:t.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[f]}),d;if(T.common.async)return S._parseAsync({data:T.data,path:T.path,parent:T});else return S._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 n=new Map;for(let S of T){let A=xT(S.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(n.has($))throw new Error(`Discriminator property ${String(o)} has duplicate value ${String($)}`);n.set($,S)}}return new RS({typeName:g.ZodDiscriminatedUnion,discriminator:o,options:T,optionsMap:n,...u(f)})}}function mA(o,T){let f=vT(o),n=vT(T);if(o===T)return{valid:!0,data:o};else if(f===N.object&&n===N.object){let S=Ao.objectKeys(T),A=Ao.objectKeys(o).filter((F)=>S.indexOf(F)!==-1),$={...o,...T};for(let F of A){let J=mA(o[F],T[F]);if(!J.valid)return{valid:!1};$[F]=J.data}return{valid:!0,data:$}}else if(f===N.array&&n===N.array){if(o.length!==T.length)return{valid:!1};let S=[];for(let A=0;A<o.length;A++){let $=o[A],F=T[A],J=mA($,F);if(!J.valid)return{valid:!1};S.push(J.data)}return{valid:!0,data:S}}else if(f===N.date&&n===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),n=(S,A)=>{if(LA(S)||LA(A))return d;let $=mA(S.value,A.value);if(!$.valid)return m(f,{code:t.invalid_intersection_types}),d;if(CA(S)||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(([S,A])=>n(S,A));else return n(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 m(f,{code:t.invalid_type,expected:N.array,received:f.parsedType}),d;if(f.data.length<this._def.items.length)return m(f,{code:t.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)m(f,{code:t.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),T.dirty();let S=[...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(S).then((A)=>{return uo.mergeArray(T,A)});else return uo.mergeArray(T,S)}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 Xn 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 m(f,{code:t.invalid_type,expected:N.object,received:f.parsedType}),d;let n=[],S=this._def.keyType,A=this._def.valueType;for(let $ in f.data)n.push({key:S._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,n);else return uo.mergeObjectSync(T,n)}get element(){return this._def.valueType}static create(o,T,f){if(T instanceof e)return new Xn({keyType:o,valueType:T,typeName:g.ZodRecord,...u(f)});return new Xn({keyType:KT.create(),valueType:o,typeName:g.ZodRecord,...u(T)})}}class Hn 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 m(f,{code:t.invalid_type,expected:N.map,received:f.parsedType}),d;let n=this._def.keyType,S=this._def.valueType,A=[...f.data.entries()].map(([$,F],J)=>{return{key:n._parse(new ET(f,$,f.path,[J,"key"])),value:S._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:$}}}}Hn.create=(o,T,f)=>{return new Hn({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 m(f,{code:t.invalid_type,expected:N.set,received:f.parsedType}),d;let n=this._def;if(n.minSize!==null){if(f.data.size<n.minSize.value)m(f,{code:t.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),T.dirty()}if(n.maxSize!==null){if(f.data.size>n.maxSize.value)m(f,{code:t.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),T.dirty()}let S=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)=>S._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 m(T,{code:t.invalid_type,expected:N.function,received:T.parsedType}),d;function f($,F){return FS({data:$,path:T.path,errorMaps:[T.common.contextualErrorMap,T.schemaErrorMap,$S(),mf].filter((J)=>!!J),issueData:{code:t.invalid_arguments,argumentsError:F}})}function n($,F){return FS({data:$,path:T.path,errorMaps:[T.common.contextualErrorMap,T.schemaErrorMap,$S(),mf].filter((J)=>!!J),issueData:{code:t.invalid_return_type,returnTypeError:F}})}let S={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,S).catch((w)=>{throw J.addIssue(f(F,w)),J}),M=await Reflect.apply(A,this,R);return await $._def.returns._def.type.parseAsync(M,S).catch((w)=>{throw J.addIssue(n(M,w)),J})})}else{let $=this;return ao(function(...F){let J=$._def.args.safeParse(F,S);if(!J.success)throw new JT([f(F,J.error)]);let R=Reflect.apply(A,this,J.data),M=$._def.returns.safeParse(R,S);if(!M.success)throw new JT([n(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 m(T,{received:T.data,code:t.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 nJ(o,T){return new lT({values:o,typeName:g.ZodEnum,...u(T)})}class lT extends e{constructor(){super(...arguments);On.set(this,void 0)}_parse(o){if(typeof o.data!=="string"){let T=this._getOrReturnCtx(o),f=this._def.values;return m(T,{expected:Ao.joinValues(f),received:T.parsedType,code:t.invalid_type}),d}if(!JS(this,On,"f"))aF(this,On,new Set(this._def.values),"f");if(!JS(this,On,"f").has(o.data)){let T=this._getOrReturnCtx(o),f=this._def.values;return m(T,{received:T.data,code:t.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})}}On=new WeakMap;lT.create=nJ;class qf extends e{constructor(){super(...arguments);kn.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 n=Ao.objectValues(T);return m(f,{expected:Ao.joinValues(n),received:f.parsedType,code:t.invalid_type}),d}if(!JS(this,kn,"f"))aF(this,kn,new Set(Ao.getValidEnumValues(this._def.values)),"f");if(!JS(this,kn,"f").has(o.data)){let n=Ao.objectValues(T);return m(f,{received:f.data,code:t.invalid_enum_value,options:n}),d}return ao(o.data)}get enum(){return this._def.values}}kn=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 m(T,{code:t.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((n)=>{return this._def.type.parseAsync(n,{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),n=this._def.effect||null,S={addIssue:(A)=>{if(m(f,A),A.fatal)T.abort();else T.dirty()},get path(){return f.path}};if(S.addIssue=S.addIssue.bind(S),n.type==="preprocess"){let A=n.transform(f.data,S);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(n.type==="refinement"){let A=($)=>{let F=n.refinement($,S);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(n.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 $=n.transform(A.value,S);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(n.transform(A.value,S)).then(($)=>({status:T.value,value:$}))});Ao.assertNever(n)}}_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 pf extends e{_parse(o){let{ctx:T}=this._processInputParams(o),f={...T,common:{...T.common,issues:[]}},n=this._def.innerType._parse({data:f.data,path:f.path,parent:{...f}});if(_n(n))return n.then((S)=>{return{status:"valid",value:S.status==="valid"?S.value:this._def.catchValue({get error(){return new JT(f.common.issues)},input:f.data})}});else return{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new JT(f.common.issues)},input:f.data})}}removeCatch(){return this._def.innerType}}pf.create=(o,T)=>{return new pf({innerType:o,typeName:g.ZodCatch,catchValue:typeof T.catch==="function"?T.catch:()=>T.catch,...u(T)})};class Kn extends e{_parse(o){if(this._getType(o)!==N.nan){let f=this._getOrReturnCtx(o);return m(f,{code:t.invalid_type,expected:N.nan,received:f.parsedType}),d}return{status:"valid",value:o.data}}}Kn.create=(o)=>{return new Kn({typeName:g.ZodNaN,...u(o)})};var OW=Symbol("zod_brand");class MS 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 Gn extends e{_parse(o){let{status:T,ctx:f}=this._processInputParams(o);if(f.common.async)return(async()=>{let S=await this._def.in._parseAsync({data:f.data,path:f.path,parent:f});if(S.status==="aborted")return d;if(S.status==="dirty")return T.dirty(),Lf(S.value);else return this._def.out._parseAsync({data:S.value,path:f.path,parent:f})})();else{let n=this._def.in._parseSync({data:f.data,path:f.path,parent:f});if(n.status==="aborted")return d;if(n.status==="dirty")return T.dirty(),{status:"dirty",value:n.value};else return this._def.out._parseSync({data:n.value,path:f.path,parent:f})}}static create(o,T){return new Gn({in:o,out:T,typeName:g.ZodPipeline})}}class cf extends e{_parse(o){let T=this._def.innerType._parse(o),f=(n)=>{if(Ff(n))n.value=Object.freeze(n.value);return n};return _n(T)?T.then((n)=>f(n)):f(T)}unwrap(){return this._def.innerType}}cf.create=(o,T)=>{return new cf({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 SJ(o,T={},f){if(o)return Rf.create().superRefine((n,S)=>{var A,$;let F=o(n);if(F instanceof Promise)return F.then((J)=>{var R,M;if(!J){let _=uF(T,n),w=(M=(R=_.fatal)!==null&&R!==void 0?R:f)!==null&&M!==void 0?M:!0;S.addIssue({code:"custom",..._,fatal:w})}});if(!F){let J=uF(T,n),R=($=(A=J.fatal)!==null&&A!==void 0?A:f)!==null&&$!==void 0?$:!0;S.addIssue({code:"custom",...J,fatal:R})}return});return Rf.create()}var kW={object:zo.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}`})=>SJ((f)=>f instanceof o,T),AJ=KT.create,$J=gT.create,wW=Kn.create,yW=dT.create,FJ=If.create,XW=Jf.create,HW=wn.create,KW=jf.create,GW=Nf.create,YW=Rf.create,EW=iT.create,tW=BT.create,zW=yn.create,QW=GT.create,DW=zo.create,UW=zo.strictCreate,VW=hf.create,BW=RS.create,LW=bf.create,CW=LT.create,mW=Xn.create,IW=Hn.create,jW=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,pW=qT.create,cW=_T.createWithPreprocess,ZW=Gn.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)=>If.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:mf,setErrorMap:cM,getErrorMap:$S,makeIssue:FS,EMPTY_PATH:ZM,addIssueToContext:m,ParseStatus:uo,INVALID:d,DIRTY:Lf,OK:ao,isAborted:LA,isDirty:CA,isValid:Ff,isAsync:_n,get util(){return Ao},get objectUtil(){return BA},ZodParsedType:N,getParsedType:vT,ZodType:e,datetimeRegex:fJ,ZodString:KT,ZodNumber:gT,ZodBigInt:dT,ZodBoolean:If,ZodDate:Jf,ZodSymbol:wn,ZodUndefined:jf,ZodNull:Nf,ZodAny:Rf,ZodUnknown:iT,ZodNever:BT,ZodVoid:yn,ZodArray:GT,ZodObject:zo,ZodUnion:hf,ZodDiscriminatedUnion:RS,ZodIntersection:bf,ZodTuple:LT,ZodRecord:Xn,ZodMap:Hn,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:pf,ZodNaN:Kn,BRAND:OW,ZodBranded:MS,ZodPipeline:Gn,ZodReadonly:cf,custom:SJ,Schema:e,ZodSchema:e,late:kW,get ZodFirstPartyTypeKind(){return g},coerce:dW,any:YW,array:QW,bigint:yW,boolean:FJ,date:XW,discriminatedUnion:BW,effect:eF,enum:xW,function:NW,instanceof:_W,intersection:LW,lazy:hW,literal:bW,map:IW,nan:wW,nativeEnum:vW,never:tW,null:GW,nullable:pW,number:$J,object:DW,oboolean:gW,onumber:iW,optional:rW,ostring:PW,pipeline:ZW,preprocess:cW,promise:qW,record:mW,set:jW,strictObject:UW,string:AJ,symbol:HW,transformer:eF,tuple:CW,undefined:KW,union:VW,unknown:EW,void:zW,NEVER:lW,ZodIssueCode:t,quotelessJson:pM,ZodError:JT});var uW="__vite_start_time"in globalThis,eW=typeof window!=="undefined",n6="vitest"in globalThis,tT=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=IA(import.meta.dirname,"../dev"),MJ=tT.VITE_USE_SELF_SIGNED_CERTIFICATE?{cert:JJ(IA(RJ,"./cert.pem"),"utf-8"),key:JJ(IA(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 jA{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 zT=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:n,foreignColumns:S}=o();return{name:f,columns:n,foreignTable:S[0].table,foreignColumns:S}},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(),n=T.map(($)=>$.name),S=f.map(($)=>$.name),A=[this.table[zT],...n,f[0].table[zT],...S];return o??`${A.join("_")}_fk`}}function WS(o,...T){return o(...T)}function OJ(o,T){return`${o[zT]}_${T.join("_")}_unique`}function kJ(o,T,f){for(let n=T;n<o.length;n++){let S=o[n];if(S==="\\"){n++;continue}if(S==='"')return[o.slice(T,n).replace(/\\/g,""),n+1];if(f)continue;if(S===","||S==="}")return[o.slice(T,n).replace(/\\/g,""),n]}return[o.slice(T).replace(/\\/g,""),o.length]}function _J(o,T=0){let f=[],n=T,S=!1;while(n<o.length){let A=o[n];if(A===","){if(S||n===T)f.push("");S=!0,n++;continue}if(S=!1,A==="\\"){n+=2;continue}if(A==='"'){let[J,R]=kJ(o,n+1,!0);f.push(J),n=R;continue}if(A==="}")return[f,n+1];if(A==="{"){let[J,R]=_J(o,n+1);f.push(J),n=R;continue}let[$,F]=kJ(o,n,!1);f.push($),n=F}return[f,n]}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 jA{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:n})=>{return WS((S,A)=>{let $=new NA(()=>{let F=S();return{columns:[o],foreignColumns:[F]}});if(A.onUpdate)$.onUpdate(A.onUpdate);if(A.onDelete)$.onDelete(A.onDelete);return $.build(T)},f,n)})}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 Yn{static[O]="IndexedColumn";constructor(o,T,f,n){this.name=o,this.keyAsName=T,this.type=f,this.indexConfig=n}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,n){super(o,T);this.baseColumn=f,this.range=n,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((n)=>n===null?null:H(this.baseColumn,bA)?this.baseColumn.mapToDriverValue(n,!0):this.baseColumn.mapToDriverValue(n));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 OS(o,T){return sW(o,T,void 0)}function sW(o,T,f){let n=Object.assign((S)=>new KJ(S??"",n),{enumName:o,enumValues:T,schema:f,[xA]:!0});return n}class bo{static[O]="Subquery";constructor(o,T,f,n=!1){this._={brand:"Subquery",sql:o,selectedFields:T,alias:f,isWith:n}}}class En extends bo{static[O]="WithSubquery"}var YJ="0.40.0";var vA,qA,wo={startActiveSpan(o,T){if(!vA)return T();if(!qA)qA=vA.trace.getTracer("drizzle-orm",YJ);return WS((f,n)=>n.startActiveSpan(o,(S)=>{try{return T(S)}catch(A){throw S.setStatus({code:f.SpanStatusCode.ERROR,message:A instanceof Error?A.message:"Unknown error"}),A}finally{S.end()}}),vA,qA)}};var Ho=Symbol.for("drizzle:ViewBaseConfig");var kS=Symbol.for("drizzle:Schema"),_S=Symbol.for("drizzle:Columns"),EJ=Symbol.for("drizzle:ExtraConfigColumns"),rA=Symbol.for("drizzle:OriginalName"),pA=Symbol.for("drizzle:BaseName"),tn=Symbol.for("drizzle:IsAlias"),tJ=Symbol.for("drizzle:ExtraConfigBuilder"),aW=Symbol.for("drizzle:IsDrizzleTable");class I{static[O]="Table";static Symbol={Name:zT,Schema:kS,OriginalName:rA,Columns:_S,ExtraConfigColumns:EJ,BaseName:pA,IsAlias:tn,ExtraConfigBuilder:tJ};[zT];[rA];[kS];[_S];[EJ];[pA];[tn]=!1;[aW]=!0;[tJ]=void 0;constructor(o,T,f){this[zT]=this[rA]=o,this[kS]=T,this[pA]=f}}function qo(o){return o[zT]}function Of(o){return`${o[kS]??"public"}.${o[zT]}`}function cA(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 j([this])}}class j{constructor(o){this.queryChunks=o}static[O]="SQL";decoder=QJ;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:n,escapeName:S,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,wS))return{sql:S(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,j))return this.buildQueryFromSourceParams(R.queryChunks,{...f,inlineParams:F||R.shouldInlineParams});if(H(R,I)){let M=R[I.Symbol.Schema],_=R[I.Symbol.Name];return{sql:M===void 0||R[tn]?S(_):S(M)+"."+S(_),params:[]}}if(H(R,_o)){let M=n.getColumnCasing(R);if(T.invokeSource==="indexes")return{sql:S(M),params:[]};let _=R.table[I.Symbol.Schema];return{sql:R.table[tn]||_===void 0?S(R.table[I.Symbol.Name])+"."+S(M):S(_)+"."+S(R.table[I.Symbol.Name])+"."+S(M),params:[]}}if(H(R,ST)){let M=R[Ho].schema,_=R[Ho].name;return{sql:M===void 0||R[Ho].isAlias?S(_):S(M)+"."+S(_),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,j))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,j.Aliased)&&R.fieldAlias!==void 0)return{sql:S(R.fieldAlias),params:[]};if(H(R,bo)){if(R._.isWith)return{sql:S(R._.alias),params:[]};return this.buildQueryFromSourceParams([new xo("("),R._.sql,new xo(") "),new wS(R._.alias)],f)}if(HJ(R)){if(R.schema)return{sql:S(R.schema)+"."+S(R.enumName),params:[]};return{sql:S(R.enumName),params:[]}}if(cA(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 j.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 wS{constructor(o){this.value=o}static[O]="Name";brand;getSQL(){return new j([this])}}function zJ(o){return typeof o==="object"&&o!==null&&"mapToDriverValue"in o&&typeof o.mapToDriverValue==="function"}var QJ={mapFromDriverValue:(o)=>o},DJ={mapToDriverValue:(o)=>o},e6={...QJ,...DJ};class RT{constructor(o,T=DJ){this.value=o,this.encoder=T}static[O]="Param";brand;getSQL(){return new j([this])}}function k(o,...T){let f=[];if(T.length>0||o.length>0&&o[0]!=="")f.push(new xo(o[0]));for(let[n,S]of T.entries())f.push(S,new xo(o[n+1]));return new j(f)}((o)=>{function T(){return new j([])}o.empty=T;function f(J){return new j(J)}o.fromList=f;function n(J){return new j([new xo(J)])}o.raw=n;function S(J,R){let M=[];for(let[_,w]of J.entries()){if(_>0&&R!==void 0)M.push(R);M.push(w)}return new j(M)}o.join=S;function A(J){return new wS(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,n){this.sql=f,this.fieldAlias=n}static[O]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new T(this.sql,this.fieldAlias)}}o.Aliased=T})(j||(j={}));class uT{constructor(o){this.name=o}static[O]="Placeholder";getSQL(){return new j([this])}}function ZA(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 ST{static[O]="View";[Ho];[TO]=!0;constructor({name:o,schema:T,selectedFields:f,query:n}){this[Ho]={name:o,originalName:o,schema:T,selectedFields:f,query:n,isExisting:!n,isAlias:!1}}getSQL(){return new j([this])}}_o.prototype.getSQL=function(){return new j([this])};I.prototype.getSQL=function(){return new j([this])};bo.prototype.getSQL=function(){return new j([this])};class Zf{constructor(o){this.table=o}static[O]="ColumnAliasProxyHandler";get(o,T){if(T==="table")return this.table;return o[T]}}class zn{constructor(o,T){this.alias=o,this.replaceOriginalName=T}static[O]="TableAliasProxyHandler";get(o,T){if(T===I.Symbol.IsAlias)return!0;if(T===I.Symbol.Name)return this.alias;if(this.replaceOriginalName&&T===I.Symbol.OriginalName)return this.alias;if(T===Ho)return{...o[Ho],name:this.alias,isAlias:!0};if(T===I.Symbol.Columns){let n=o[I.Symbol.Columns];if(!n)return n;let S={};return Object.keys(n).map((A)=>{S[A]=new Proxy(n[A],new Zf(new Proxy(o,this)))}),S}let f=o[T];if(H(f,_o))return new Proxy(f,new Zf(new Proxy(o,this)));return f}}function yS(o,T){return new Proxy(o,new zn(T,!1))}function CT(o,T){return new Proxy(o,new Zf(new Proxy(o.table,new zn(T,!1))))}function PA(o,T){return new j.Aliased(Qn(o.sql,T),o.fieldAlias)}function Qn(o,T){return k.join(o.queryChunks.map((f)=>{if(H(f,_o))return CT(f,T);if(H(f,j))return Qn(f,T);if(H(f,j.Aliased))return PA(f,T);return f}))}class XS extends Error{static[O]="DrizzleError";constructor({message:o,cause:T}){super(o);this.name="DrizzleError",this.cause=T}}class iA extends XS{static[O]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}function AT(o,T){if(zJ(T)&&!cA(o)&&!H(o,RT)&&!H(o,uT)&&!H(o,_o)&&!H(o,I)&&!H(o,ST))return new RT(o,T);return o}var HS=(o,T)=>{return k`${o} = ${AT(T,o)}`},UJ=(o,T)=>{return k`${o} <> ${AT(T,o)}`};function Dn(...o){let T=o.filter((f)=>f!==void 0);if(T.length===0)return;if(T.length===1)return new j(T);return new j([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 j(T);return new j([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)}`},mJ=(o,T)=>{return k`${o} < ${AT(T,o)}`},IJ=(o,T)=>{return k`${o} <= ${AT(T,o)}`};function jJ(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 pJ(o,T){return k`${o} like ${T}`}function cJ(o,T){return k`${o} not like ${T}`}function ZJ(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((S)=>{try{return JSON.stringify(S)}catch{return String(S)}}),n=f.length?` -- params: [${f.join(", ")}]`:"";this.writer.write(`Query: ${o}${n}`)}}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 n={},S=o.reduce((A,{path:$,field:F},J)=>{let R;if(H(F,_o))R=F;else if(H(F,j))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],D=M[w]=X===null?null:R.mapFromDriverValue(X);if(f&&H(F,_o)&&$.length===2){let K=$[0];if(!(K in n))n[K]=D===null?qo(F.table):!1;else if(typeof n[K]==="string"&&n[K]!==qo(F.table))n[K]=!1}}return A},{});if(f&&Object.keys(n).length>0){for(let[A,$]of Object.entries(n))if(typeof $==="string"&&!f[$])S[A]=null}return S}function wT(o,T){return Object.entries(o).reduce((f,[n,S])=>{if(typeof n!=="string")return f;let A=T?[...T,n]:[n];if(H(S,_o)||H(S,j)||H(S,j.Aliased))f.push({path:A,field:S});else if(H(S,I))f.push(...wT(S[I.Symbol.Columns],A));else f.push(...wT(S,A));return f},[])}function Un(o,T){let f=Object.keys(o),n=Object.keys(T);if(f.length!==n.length)return!1;for(let[S,A]of f.entries())if(A!==n[S])return!1;return!0}function KS(o,T){let f=Object.entries(T).filter(([,n])=>n!==void 0).map(([n,S])=>{if(H(S,j)||H(S,_o))return[n,S];else return[n,new RT(S,o[I.Symbol.Columns][n])]});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 n of Object.getOwnPropertyNames(f.prototype)){if(n==="constructor")continue;Object.defineProperty(o.prototype,n,Object.getOwnPropertyDescriptor(f.prototype,n)||Object.create(null))}}function eJ(o){return o[I.Symbol.Columns]}function rT(o){return H(o,bo)?o._.alias:H(o,ST)?o[Ho].name:H(o,j)?void 0:o[I.Symbol.IsAlias]?o[I.Symbol.Name]:o[I.Symbol.BaseName]}function So(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 nR(o,T){let{name:f,config:n}=So(o,T);if(n.mode==="number")return new aJ(f);return new TR(f)}class SR 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:n}=So(o,T);if(n.mode==="number")return new SR(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 Vn(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:n}=So(o,T);return new WR(f,n)}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:n,config:S}=So(T,f);return new XR(n,S,o)}}class pT extends b{static[O]="PgDateColumnBaseBuilder";defaultNow(){return this.default(k`now()`)}}class GR extends pT{static[O]="PgDateBuilder";constructor(o){super(o,"date","PgDate")}build(o){return new GS(o,this.config)}}class GS extends V{static[O]="PgDate";getSQLType(){return"date"}mapFromDriverValue(o){return new Date(o)}mapToDriverValue(o){return o.toISOString()}}class YR extends pT{static[O]="PgDateStringBuilder";constructor(o){super(o,"string","PgDateString")}build(o){return new YS(o,this.config)}}class YS extends V{static[O]="PgDateString";getSQLType(){return"date"}}function ER(o,T){let{name:f,config:n}=So(o,T);if(n?.mode==="date")return new GR(f);return new YR(f)}class tR extends b{static[O]="PgDoublePrecisionBuilder";constructor(o){super(o,"number","PgDoublePrecision")}build(o){return new zR(o,this.config)}}class zR extends V{static[O]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(o){if(typeof o==="string")return Number.parseFloat(o);return o}}function QR(o){return new tR(o??"")}class DR extends b{static[O]="PgInetBuilder";constructor(o){super(o,"string","PgInet")}build(o){return new UR(o,this.config)}}class UR extends V{static[O]="PgInet";getSQLType(){return"inet"}}function VR(o){return new DR(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 ES(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 mR(o,this.config)}}class mR 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 IR(o,T={}){let{name:f,config:n}=So(o,T);return new CR(f,n)}class jR extends b{static[O]="PgJsonBuilder";constructor(o){super(o,"json","PgJson")}build(o){return new tS(o,this.config)}}class tS 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 jR(o??"")}class hR extends b{static[O]="PgJsonbBuilder";constructor(o){super(o,"json","PgJsonb")}build(o){return new zS(o,this.config)}}class zS 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,n]=o.slice(1,-1).split(",");return[Number.parseFloat(T),Number.parseFloat(f),Number.parseFloat(n)]}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,n]=o.slice(1,-1).split(",");return{a:Number.parseFloat(T),b:Number.parseFloat(f),c:Number.parseFloat(n)}}mapToDriverValue(o){return`{${o.a},${o.b},${o.c}}`}}function pR(o,T){let{name:f,config:n}=So(o,T);if(!n?.mode||n.mode==="tuple")return new xR(f);return new qR(f)}class cR extends b{static[O]="PgMacaddrBuilder";constructor(o){super(o,"string","PgMacaddr")}build(o){return new ZR(o,this.config)}}class ZR extends V{static[O]="PgMacaddr";getSQLType(){return"macaddr"}}function PR(o){return new cR(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 QS(o,this.config)}}class QS 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:n}=So(o,T);return new lR(f,n?.precision,n?.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:n}=So(o,T);if(!n?.mode||n.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),n=new DataView(f);for(let S=0;S<8;S++)n.setUint8(S,o[T+S]);return n.getFloat64(0,!0)}function lA(o){let T=fO(o),f=0,n=T[f];f+=1;let S=new DataView(T.buffer),A=S.getUint32(f,n===1);f+=4;let $;if(A&536870912)$=S.getUint32(f,n===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 n0 extends b{static[O]="PgGeometryBuilder";constructor(o){super(o,"array","PgGeometry")}build(o){return new S0(o,this.config)}}class S0 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:n}=So(o,T);if(!n?.mode||n.mode==="tuple")return new n0(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:n}=So(o,T);return new G0(f,n)}class t0 extends pT{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 DS(o,this.config)}}class DS 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 z0(o,T={}){let{name:f,config:n}=So(o,T);return new t0(f,n.withTimezone??!1,n.precision)}class Q0 extends pT{static[O]="PgTimestampBuilder";constructor(o,T,f){super(o,"date","PgTimestamp");this.config.withTimezone=T,this.config.precision=f}build(o){return new US(o,this.config)}}class US 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 D0 extends pT{static[O]="PgTimestampStringBuilder";constructor(o,T,f){super(o,"string","PgTimestampString");this.config.withTimezone=T,this.config.precision=f}build(o){return new VS(o,this.config)}}class VS 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 QT(o,T={}){let{name:f,config:n}=So(o,T);if(n?.mode==="string")return new D0(f,n.withTimezone??!1,n.precision);return new Q0(f,n?.withTimezone??!1,n?.precision)}class U0 extends b{static[O]="PgUUIDBuilder";constructor(o){super(o,"string","PgUUID")}defaultRandom(){return this.default(k`gen_random_uuid()`)}build(o){return new BS(o,this.config)}}class BS extends V{static[O]="PgUUID";getSQLType(){return"uuid"}}function MT(o){return new U0(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 po(o,T={}){let{name:f,config:n}=So(o,T);return new V0(f,n)}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 m0(o,T){let{name:f,config:n}=So(o,T);return new L0(f,n)}class I0 extends b{static[O]="PgHalfVectorBuilder";constructor(o,T){super(o,"array","PgHalfVector");this.config.dimensions=T.dimensions}build(o){return new j0(o,this.config)}}class j0 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:n}=So(o,T);return new I0(f,n)}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:n}=So(o,T);return new h0(f,n)}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:n}=So(o,T);return new v0(f,n)}function p0(){return{bigint:nR,bigserial:JR,boolean:Vn,char:kR,cidr:yR,customType:KR,date:ER,doublePrecision:QR,inet:VR,integer:ES,interval:IR,json:NR,jsonb:bR,line:pR,macaddr:PR,macaddr8:dR,numeric:uR,point:T0,geometry:F0,real:M0,serial:k0,smallint:y0,smallserial:K0,text:E0,time:z0,timestamp:QT,uuid:MT,varchar:po,bit:m0,halfvec:N0,sparsevec:x0,vector:r0}}var uA=Symbol.for("drizzle:PgInlineForeignKeys"),c0=Symbol.for("drizzle:EnableRLS");class co extends I{static[O]="PgTable";static Symbol=Object.assign({},I.Symbol,{InlineForeignKeys:uA,EnableRLS:c0});[uA]=[];[c0]=!1;[I.Symbol.ExtraConfigBuilder]=void 0;[I.Symbol.ExtraConfigColumns]={}}function nO(o,T,f,n,S=o){let A=new co(o,n,S),$=typeof T==="function"?T(p0()):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[I.Symbol.Columns]=F,R[I.Symbol.ExtraConfigColumns]=J,f)R[co.Symbol.ExtraConfigBuilder]=f;return Object.assign(R,{enableRLS:()=>{return R[co.Symbol.EnableRLS]=!0,R}})}var sT=(o,T,f)=>{return nO(o,T,f,void 0)};function Z0(...o){if(o[0].columns)return new Bn(o[0].columns,o[0].name);return new Bn(o)}class Bn{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[co.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[I.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,n){super(o,T,f?.relationName);this.config=f,this.isNullable=n}static[O]="One";withFieldName(o){let T=new aT(this.sourceTable,this.referencedTable,this.config,this.isNullable);return T.fieldName=o,T}}class Ln extends eA{constructor(o,T,f){super(o,T,f?.relationName);this.config=f}static[O]="Many";withFieldName(o){let T=new Ln(this.sourceTable,this.referencedTable,this.config);return T.fieldName=o,T}}function g0(){return{and:Dn,between:qJ,eq:HS,exists:xJ,gt:LJ,gte:CJ,ilike:ZJ,inArray:jJ,isNull:hJ,isNotNull:bJ,like:pJ,lt:mJ,lte:IJ,ne:UJ,not:BJ,notBetween:rJ,notExists:vJ,notLike:cJ,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,I))o=o.default;let f={},n={},S={};for(let[A,$]of Object.entries(o))if(H($,I)){let F=Of($),J=n[F];f[F]=A,S[A]={tsName:A,dbName:$[I.Symbol.Name],schema:$[I.Symbol.Schema],columns:$[I.Symbol.Columns],relations:J?.relations??{},primaryKey:J?.primaryKey??[]};for(let M of Object.values($[I.Symbol.Columns]))if(M.primary)S[A].primaryKey.push(M);let R=$[I.Symbol.ExtraConfigBuilder]?.($[I.Symbol.ExtraConfigColumns]);if(R){for(let M of Object.values(R))if(H(M,Bn))S[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=S[J];if(X.relations[_]=w,M)X.primaryKey.push(...M)}else{if(!(F in n))n[F]={relations:{},primaryKey:M};n[F].relations[_]=w}}return{tables:S,tableNamesMap:f}}function SO(o){return function T(f,n){return new aT(o,f,n,n?.fields.reduce((S,A)=>S&&A.notNull,!0)??!1)}}function AO(o){return function T(f,n){return new Ln(o,f,n)}}function u0(o,T,f){if(H(f,aT)&&f.config)return{fields:f.config.fields,references:f.config.references};let n=T[Of(f.referencedTable)];if(!n)throw new Error(`Table "${f.referencedTable[I.Symbol.Name]}" not found in schema`);let S=o[n];if(!S)throw new Error(`Table "${n}" not found in schema`);let A=f.sourceTable,$=T[Of(A)];if(!$)throw new Error(`Table "${A[I.Symbol.Name]}" not found in schema`);let F=[];for(let J of Object.values(S.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 "${n}"`):new Error(`There are multiple relations between "${n}" and "${f.sourceTable[I.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:SO(o),many:AO(o)}}function LS(o,T,f,n,S=(A)=>A){let A={};for(let[$,F]of n.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&&LS(o,o[F.relationTableTsKey],M,F.selection,S):M.map((_)=>LS(o,o[F.relationTableTsKey],_,F.selection,S))}else{let J=S(f[$]),R=F.field,M;if(H(R,_o))M=R;else if(H(R,j))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 CS=new Map,sA=new Map,aA=Symbol("OriginError"),Pf={};class yT extends Promise{constructor(o,T,f,n,S={}){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=n,this.options=S,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 n=new Promise((S,A)=>{this.cursorFn=($)=>{return S({value:$,done:!1}),new Promise((F)=>f=F)},this.resolve=()=>(this.active=!1,S({done:!0})),this.reject=($)=>(this.active=!1,A($))});return this.execute(),n},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(CS.has(o))return CS.get(o);let T=Error.stackTraceLimit;return Error.stackTraceLimit=4,CS.set(o,new Error),Error.stackTraceLimit=T,CS.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:n,port:S}=f||T,A=Object.assign(new Error("write "+o+" "+(T.path||n+":"+S)),{code:o,errno:o,address:T.path||n},T.path?{}:{port:S});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 jS{then(){o$()}catch(){o$()}finally(){o$()}}class jn extends jS{constructor(o){super();this.value=bS(o)}}class mT extends jS{constructor(o,T,f){super();this.value=o,this.type=T,this.array=f}}class NS extends jS{constructor(o,T){super();this.first=o,this.rest=T}build(o,T,f,n){let S=JO.map(([A,$])=>({fn:$,i:o.search(A)})).sort((A,$)=>A.i-$.i).pop();return S.i===-1?A$(this.first,n):S.fn(this.first,this.rest,T,f,n)}}function hS(o,T,f,n){let S=o instanceof mT?o.value:o;if(S===void 0){if(o instanceof mT?o.value=n.transform.undefined:S=o=n.transform.undefined,S===void 0)throw Bo.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return"$"+f.push(o instanceof mT?(T.push(o.value),o.array?o.array[o.type||IS(o.value)]||o.type||A1(o.value):o.type):(T.push(o),IS(o)))}var n1=F1(FO);function n$(o,T,f,n,S,A){for(let $=1;$<o.strings.length;$++)T+=S$(T,f,n,S,A)+o.strings[$],f=o.args[$];return T}function S$(o,T,f,n,S){return T instanceof NS?T.build(o,f,n,S):T instanceof yT?f$(T,f,n,S):T instanceof jn?T.value:T&&T[0]instanceof yT?T.reduce((A,$)=>A+" "+f$($,f,n,S),""):hS(T,f,n,S)}function f$(o,T,f,n){return o.fragment=!0,n$(o,o.strings[0],o.args[0],T,f,n)}function S1(o,T,f,n,S){return o.map((A)=>"("+n.map(($)=>S$("values",A[$],T,f,S)).join(",")+")").join(",")}function f1(o,T,f,n,S){let A=Array.isArray(o[0]),$=T.length?T.flat():Object.keys(A?o[0]:o);return S1(A?o:[o],f,n,$,S)}function mS(o,T,f,n,S){if(typeof o==="string"&&(o=[o].concat(T)),Array.isArray(o))return A$(o,S);let A;return(T.length?T.flat():Object.keys(o)).map((F)=>{return A=o[F],(A instanceof yT?f$(A,f,n,S):A instanceof jn?A.value:hS(A,f,n,S))+" as "+bS(S.transform.column.to?S.transform.column.to(F):F)}).join(",")}var JO=Object.entries({values:f1,in:(...o)=>{let T=f1(...o);return T==="()"?"(null)":T},select:mS,as:mS,returning:mS,"\\(":mS,update(o,T,f,n,S){return(T.length?T.flat():Object.keys(o)).map((A)=>bS(S.transform.column.to?S.transform.column.to(A):A)+"="+S$("values",o[A],f,n,S))},insert(o,T,f,n,S){let A=T.length?T.flat():Object.keys(Array.isArray(o)?o[0]:o);return"("+A$(A,S)+")values"+S1(Array.isArray(o)?o:[o],f,n,A,S)}}).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}=n1;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((n)=>T.parsers[n]=o[f].parse),o[f].serialize)T.serializers[o[f].to]=o[f].serialize,o[f].from&&[].concat(o[f].from).forEach((n)=>T.serializers[n]=o[f].serialize);return T},{parsers:{},serializers:{}})}function A$(o,{transform:{column:T}}){return o.map((f)=>bS(T.to?T.to(f):f)).join(",")}var bS=function o(T){return'"'+T.replace(/"/g,'""').replace(/\./g,'"."')+'"'},IS=function o(T){return T instanceof mT?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,n,S){if(Array.isArray(T)===!1)return T;if(!T.length)return"{}";let A=T[0],$=S===1020?";":",";if(Array.isArray(A)&&!A.type)return"{"+T.map((F)=>o(F,f,n,S)).join($)+"}";return"{"+T.map((F)=>{if(F===void 0){if(F=n.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,n){return T$.i=T$.last=0,M1(T$,T,f,n)};function M1(o,T,f,n){let S=[],A=n===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==='"')S.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,S.push(M1(o,T,f,n));else if(o.char==="}"){o.quoted=!1,o.last<o.i&&S.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!=='"')S.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&&S.push(f?f(T.slice(o.last,o.i+1)):T.slice(o.last,o.i+1)),S}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,"-"),Cn=(o)=>o.replace(/([A-Z])/g,"_$1").toLowerCase(),mn=(o)=>(o.slice(0,1)+o.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),In=(o)=>o.replace(/-/g,"_");function $$(o){return function T(f,n){return typeof f==="object"&&f!==null&&(n.type===114||n.type===3802)?Array.isArray(f)?f.map((S)=>T(S,n)):Object.entries(f).reduce((S,[A,$])=>Object.assign(S,{[o(A)]:T($,n)}),{}):f}}kf.column={from:kf};kf.value={from:$$(kf)};Cn.column={to:Cn};var F$={...kf};F$.column.to=Cn;_f.column={from:_f};_f.value={from:$$(_f)};mn.column={to:mn};var J$={..._f};J$.column.to=mn;wf.column={from:wf};wf.value={from:$$(wf)};In.column={to:In};var R$={...wf};R$.column.to=In;import W1 from"net";import XO from"tls";import Nn 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:(n)=>{let S=T.indexOf(n);return S===-1?null:(T.splice(S,1),n)},push:(n)=>(T.push(n),n),shift:()=>{let n=T[f++];if(f===T.length)f=0,T=[];else T[f-1]=void 0;return n}}}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 xS(T),Oo.i+=eo.write(o,Oo.i,T,"utf8"),Oo},i16(o){return xS(2),eo.writeUInt16BE(o,Oo.i),Oo.i+=2,Oo},i32(o,T){if(T||T===0)return eo.writeUInt32BE(o,T),Oo;return xS(4),eo.writeUInt32BE(o,Oo.i),Oo.i+=4,Oo},z(o){return xS(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}}),c=Oo;function xS(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=c().S().end(),k1=c().H().end(),KO=c().i32(8).i32(80877103).end(8),GO=Buffer.concat([c().E().str(c.N).i32(0).end(),of]),YO=c().D().str("S").str(c.N).end(),df=()=>{},EO=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),tO={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:n=df,onclose:S=df}={}){let{ssl:A,max:$,user:F,host:J,port:R,database:M,parsers:_,transform:w,onnotice:X,onnotify:D,onparameter:K,max_pipeline:L,keep_alive:h,backoff:q,target_session_attrs:P}=o,Y=WT(),z=HO++,U={pid:null,secret:null},Q=O$(eS,o.idle_timeout),v=O$(eS,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={},IT=Math.random().toString(36).slice(2),E=1,p=0,Fo=0,Eo=0,Co=0,To=0,yo=0,Vo=0,to=null,Ko=null,Zo=!1,Xo=null,XT=null,Po=null,cT=null,mo=null,Go=null,HT=null,DT=null,B=null,sf=null,io={queue:T.closed,idleTimer:Q,connect(W){Po=W||!0,q$()},terminate:on,execute:af,cancel:I1,end:eS,count:0,id:z};return T.closed&&T.closed.push(io),io;async function m1(){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 I1({pid:W,secret:y},Z,Jo){try{s=c().i32(16).i32(80877102).i32(W).i32(y).end(16),await v$(),G.once("error",Jo),G.once("close",Z)}catch(Qo){Jo(Qo)}}function af(W){if(Zo)return pn(W,Bo.connection("CONNECTION_DESTROYED",o));if(W.cancelled)return;try{return W.state=U,B?Y.push(W):(B=W,B.active=!0),h1(W),ro(j1(W))&&!W.describeFirst&&!W.cursorFn&&Y.length<L&&(!W.options.onexecute||W.options.onexecute(io))}catch(y){return Y.length===0&&ro(of),UT(y),!0}}function j1(W){if(W.parameters.length>=65534)throw Bo.generic("MAX_PARAMETERS_EXCEEDED","Max number of parameters (65534) exceeded");return W.options.simple?c().Q().str(W.statement.string+c.N).end():W.describeFirst?Buffer.concat([N$(W),k1]):W.prepare?W.prepared?rn(W):Buffer.concat([N$(W),rn(W)]):N1(W)}function N$(W){return Buffer.concat([c$(W.statement.string,W.parameters,W.statement.types,W.statement.name),YM("S",W.statement.name)])}function rn(W){return Buffer.concat([GM(W.parameters,W.statement.types,W.statement.name,W.cursorName),W.cursorFn?Z$("",W.cursorRows):GO])}function N1(W){return Buffer.concat([c$(W.statement.string,W.parameters,W.statement.types),YO,rn(W)])}function h1(W){let y=[],Z=[],Jo=n$(W,W.strings[0],W.args[0],y,Z,o);!W.tagged&&W.args.forEach((Qo)=>hS(Qo,y,Z,o)),W.prepare=o.prepare&&("prepare"in W.options?W.options.prepare:!0),W.string=Jo,W.signature=W.prepare&&Z+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:Z,name:W.prepare?IT+E++:""},typeof o.debug==="function"&&o.debug(z,Jo,y,Z)}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(){UT(Bo.connection("CONNECT_TIMEOUT",o,G)),G.destroy()}async function b$(){if(ro(KO),!await new Promise((y)=>G.once("data",(Z)=>y(Z[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 uS(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),UT(y)}a=a.subarray(To+1),Fo=0,Xo=null}}async function v$(){if(Zo=!1,Lo={},G||(G=await m1()),!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$,p?p+yo-O1.now():0)}function Kf(){try{fT={},ko=o.fetch_types,IT=Math.random().toString(36).slice(2),E=1,v.start(),G.on("data",uS),h&&G.setKeepAlive&&G.setKeepAlive(!0,1000*h);let W=tM();ro(W)}catch(W){Gf(W)}}function Gf(W){if(io.queue===T.connecting&&o.host[Co+1])return;UT(W);while(Y.length)pn(Y.shift(),W)}function UT(W){mo&&(mo.destroy(W),mo=null),B&&pn(B,W),Po&&(pn(Po,W),Po=null)}function pn(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 eS(){return cT||(!io.reserved&&n(io),!io.reserved&&!Po&&!B&&Y.length===0?(on(),new Promise((W)=>G&&G.readyState!=="closed"?G.once("close",W):W())):cT=new Promise((W)=>HT=W))}function on(){if(Zo=!0,mo||B||Po||Y.length)Gf(Bo.connection("CONNECTION_DESTROYED",o));if(clearImmediate(Ko),G)G.removeListener("data",uS),G.removeListener("connect",Kf),G.readyState==="open"&&G.end(c().X().end());HT&&(HT(),cT=HT=null)}async function r$(W){if(a=Buffer.alloc(0),Fo=0,Xo=null,clearImmediate(Ko),G.removeListener("data",uS),G.removeListener("connect",Kf),Q.cancel(),v.cancel(),l.cancel(),G.removeAllListeners(),G=null,Po)return q$();!W&&(B||Y.length)&&Gf(Bo.connection("CONNECTION_CLOSED",o,G)),p=O1.now(),W&&o.shared.retries++,yo=(typeof q==="function"?q(o.shared.retries):q)*1000,S(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?p1:y===50?p$:y===49?c1:y===116?Z1:y===84?P1:y===82?i1:y===110?s1:y===75?a1:y===69?SM: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,Z,Jo,Qo,go=B.isRaw?new Array(B.statement.columns.length):{};for(let so=0;so<B.statement.columns.length;so++)Jo=B.statement.columns[so],Z=W.readInt32BE(y),y+=4,Qo=Z===-1?null:B.isRaw===!0?W.subarray(y,y+=Z):Jo.parser===void 0?W.toString("utf8",y,y+=Z):Jo.parser.array===!0?Jo.parser(W.toString("utf8",y+1,y+=Z)):Jo.parser(W.toString("utf8",y,y+=Z)),B.isRaw?go[so]=B.isRaw===!0?Qo:w.value.from?w.value.from(Qo,Jo):Qo:go[Jo.name]=w.value.from?w.value.from(Qo,Jo):Qo;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,Z]=W.toString("utf8",5,W.length-1).split(c.N);if(Lo[y]=Z,o.parameters[y]!==Z)o.parameters[y]=Z,K&&K(y,Z)}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 nM();else if(fM(P,Lo))return on()}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?cT?on():(io.reserved=null,f(io)):io.reserved():cT?on():f(io)}function p1(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=U;break}}if(sf&&(sf(),sf=null),r.command==="BEGIN"&&$!==1&&!io.reserved)return UT(Bo.generic("UNSAFE_TRANSACTION","Only use sql.begin, sql.reserved or max: 1"));if(B.options.simple)return p$();if(B.cursorFn)r.count&&B.cursorFn(r),ro(of);B.resolve(r)}function c1(){B.parsing=!1}function p$(){!r.statement&&(r.statement=B.statement),r.columns=B.statement.columns}function Z1(W){let y=W.readUInt16BE(5);for(let Z=0;Z<y;++Z)!B.statement.types[Z]&&(B.statement.types[Z]=W.readUInt32BE(7+Z*4));B.prepare&&(fT[B.signature]=B.statement),B.describeFirst&&!B.onlyDescribe&&(ro(rn(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),Z=7,Jo;B.statement.columns=Array(y);for(let Qo=0;Qo<y;++Qo){Jo=Z;while(W[Z++]!==0);let go=W.readUInt32BE(Z),so=W.readUInt16BE(Z+4),ZT=W.readUInt32BE(Z+6);B.statement.columns[Qo]={name:w.column.from?w.column.from(W.toString("utf8",Jo,Z-1)):W.toString("utf8",Jo,Z-1),parser:_[ZT],table:go,number:so,type:ZT},Z+=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 sS();ro(c().p().str(W).z(1).end())}async function d1(W){let y="md5"+await _1(Buffer.concat([Buffer.from(await _1(await sS()+F)),W.subarray(9)]));ro(c().p().str(y).z(1).end())}async function l1(){DT=(await Nn.randomBytes(18)).toString("base64"),c().p().str("SCRAM-SHA-256"+c.N);let W=c.i;ro(c.inc(4).str("n,,n=*,r="+DT).i32(c.i-W-4,W).end())}async function u1(W){let y=W.toString("utf8",9).split(",").reduce((so,ZT)=>(so[ZT[0]]=ZT.slice(2),so),{}),Z=await Nn.pbkdf2Sync(await sS(),Buffer.from(y.s,"base64"),parseInt(y.i),32,"sha256"),Jo=await vS(Z,"Client Key"),Qo="n=*,r="+DT+",r="+y.r+",s="+y.s+",i="+y.i+",c=biws,r="+y.r;to=(await vS(await vS(Z,"Server Key"),Qo)).toString("base64");let go="c=biws,r="+y.r+",p="+QO(Jo,Buffer.from(await vS(await zO(Jo),Qo))).toString("base64");ro(c().p().str(go).end())}function e1(W){if(W.toString("utf8",9).split(c.N,1)[0].slice(2)===to)return;UT(Bo.generic("SASL_SIGNATURE_MISMATCH","The server did not return the correct signature")),G.destroy()}function sS(){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){U.pid=W.readUInt32BE(5),U.secret=W.readUInt32BE(9)}async function oM(){ko=!1,(await new yT([`
15
+ ${w.trace}`:`No previous disposal trace for ${F} was found.`),f}let R=o.moleculeGraph.getRelationEntries({downstreamMoleculeKey:$.stringKey}).filter(([,{source:w}])=>w!==S).map(([w])=>vo(w));if(n)A.moleculeGraph.delete(S);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 n=T.families.get(f.key);if(n)i(T,n,vo(f.subKey))}}function XF(o,T,f){switch(T){case"newValue":ff(f,o.provenance,o.key);break;case"oldValue":nf(f,o.key);break}}function HF(o,T,f){switch(T){case"newValue":nf(f,o.key);break;case"oldValue":{let n=o.provenance.map(vo);ff(f,n,o.key);for(let[S,A]of o.values){let $=f.families.get(S);if($){i(f,$,o.key);let F=`${S}(${fo(o.key)})`;f.valueMap.set(F,A)}}}break}}function KF(o,T,f){switch(T){case"newValue":{let n=o.to.length===1?o.to[0]:o.to;Yf(f,n,o.key,"exclusive")}break;case"oldValue":{let n=o.from.length===1?o.from[0]:o.from;Yf(f,n,o.key,"exclusive")}break}}function an(o,T,f){let n=o==="newValue"?T.updates:[...T.updates].reverse();for(let S of n)switch(S.type){case"atom_update":case"selector_update":sn(o,S,f);break;case"state_creation":$A(S,o,f);break;case"state_disposal":FA(S,o,f);break;case"molecule_creation":XF(S,o,f);break;case"molecule_disposal":HF(S,o,f);break;case"molecule_transfer":KF(S,o,f);break;case"transaction_update":an(o,S,f);break}}function EF(o,T,f){if(jo(o)&&T)o.transactionMeta.epoch.set(T,f)}function GF(o,T,f){if(!jo(o))return;let S=o.transactionMeta.actionContinuities.getRelatedKey(T);if(S!==void 0)o.transactionMeta.epoch.set(S,f)}var YF=(o,T)=>{let f=C(T),{parent:n}=f;if(n===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,n.child=null,n.on.transactionApplying.next(f.transactionMeta);let{updates:S}=f.transactionMeta.update;if(T.logger.info("\uD83D\uDEC4","transaction",f.transactionMeta.update.key,`Applying transaction with ${S.length} updates:`,S),an("newValue",f.transactionMeta.update,n),jo(n))GF(n,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(n))n.transactionMeta.update.updates.push(f.transactionMeta.update);n.on.transactionApplying.next(null)};function tF(o,T,f){if(!jo(o))return;let{epoch:S,actionContinuities:A}=o.transactionMeta;if(A.set(T,f),!S.has(T))S.set(T,-1)}function zF(o){return{store:o}}function Ro(o,...T){let f,n,S;if(T.length===1)f=T[0];else n=T[0],S=T[1],f=i(o,n,S);if("counterfeit"in f&&"family"in f){n=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."),n.type){case"atom_family":case"mutable_atom_family":return o.defaults.get(n.key);case"selector_family":case"readonly_selector_family":{if(o.defaults.has(n.key))return o.defaults.get(f.family.key);let F=$o(o,n).default(A);return o.defaults.set(n.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),n=this.relations.get(T);if(f)f.add(T);else f=new Set([T]),this.relations.set(o,f);if(n)n.add(o);else n=new Set([o]),this.relations.set(T,n)}deleteRelation(o,T){let f=this.relations.get(o);if(f){if(f.delete(T),f.size===0)this.relations.delete(o);let n=this.relations.get(T);if(n){if(n.delete(o),n.size===0)this.relations.delete(T)}}}replaceRelationsUnsafely(o,T){this.relations.set(o,new Set(T));for(let f of T){let n=new Set().add(o);this.relations.set(f,n)}}replaceRelationsSafely(o,T){let f=this.relations.get(o),n=this.isAType?.(o)?o:void 0,S=n===void 0?o:void 0;if(f)for(let A of f){n??=A,S??=A;let $=this.relations.get(A);if($){if($.size===1)this.relations.delete(A);else $.delete(o);this.contents.delete(this.makeContentKey(n,S))}}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,n])=>[f,new Set(n)])),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=(n,S)=>f.has(n,S),this.addRelation=(n,S)=>{f.addRelation(n,S)},this.deleteRelation=(n,S)=>{f.deleteRelation(n,S)},this.replaceRelationsSafely=(n,S)=>{f.replaceRelationsSafely(n,S)},this.replaceRelationsUnsafely=(n,S)=>{f.replaceRelationsUnsafely(n,S)},this.getRelatedKeys=(n)=>f.getRelatedKeys(n),f.getContent)this.getContentInternal=(n)=>{return f.getContent(n)},this.setContent=(n,S)=>{f.setContent(n,S)},this.deleteContent=(n)=>{f.deleteContent(n)};for(let[n,S]of o.relations??[]){let A=this.isAType?.(n)?n:void 0,$=A===void 0?n:void 0;for(let F of S)A??=F,$??=F,this.addRelation(A,$)}for(let[n,S]of o.contents??[])this.setContent(n,S)}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,n;switch(o.length){case 1:{let S=o[0];T=S[this.a],f=S[this.b],n=void 0;break}case 2:{let S=o[0];if(typeof S==="string")[T,f]=o;else T=S[this.a],f=S[this.b],n=o[1];break}default:{T=o[0],f=o[1],n=o[2];break}}switch(this.cardinality){case"1:1":{let S=this.getRelatedKey(T);if(S&&S!==f)this.delete(T,S)}case"1:n":{let S=this.getRelatedKey(f);if(S&&S!==T)this.delete(S,f)}break;case"n:n":}if(n){let S=this.makeContentKey(T,f);this.setContent(S,n)}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 n=this.getRelatedKeys(T);if(n)for(let S of n)this.delete(S,T)}if(typeof f==="string"&&T===void 0){let n=this.getRelatedKeys(f);if(n)for(let S of n)this.delete(f,S)}if(typeof f==="string"&&typeof T==="string"){this.deleteRelation(f,T);let n=this.makeContentKey(f,T);this.deleteContent(n)}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((n)=>`"${n}"`).join(", ")}). Only one related key was expected.`);let f;for(let n of T){f=n;break}return f}}replaceRelations(o,T,f){let n=!Array.isArray(T),S=n?Object.keys(T):T;if(f?.reckless)this.replaceRelationsUnsafely(o,S);else this.replaceRelationsSafely(o,S);if(n)for(let A of S){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 n=this.getRelatedKeys(T);if(n)return[...n].map((S)=>{return[S,this.getContent(T,S)]})}if(T===void 0&&f!==void 0){let n=this.getRelatedKeys(f);if(n)return[...n].map((S)=>{return[S,this.getContent(S,f)]})}return[]}has(o,T){if(T)return this.getRelatedKeys(o)?.has(T)??!1;return this.relations.has(o)}}class kT extends Map{deleted=new Set;source;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 QF=(o,T,f,n)=>{let S=C(o),A={parent:S,child:null,on:S.on,loggers:S.loggers,logger:S.logger,config:S.config,atoms:new kT(S.atoms),atomsThatAreDefault:new Set(S.atomsThatAreDefault),families:new kT(S.families),joins:new kT(S.joins),operation:{open:!1},readonlySelectors:new kT(S.readonlySelectors),timelines:new kT(S.timelines),timelineTopics:new No(S.timelineTopics.toJSON()),trackers:new Map,transactions:new kT(S.transactions),selectorAtoms:new No(S.selectorAtoms.toJSON()),selectorGraph:new No(S.selectorGraph.toJSON(),{makeContentKey:(...R)=>R.sort().join(":")}),selectors:new kT(S.selectors),valueMap:new kT(S.valueMap),defaults:S.defaults,disposalTraces:o.disposalTraces.copy(),molecules:new kT(S.molecules),moleculeGraph:new No(S.moleculeGraph.toJSON(),{makeContentKey:S.moleculeGraph.makeContentKey}),moleculeData:new No(S.moleculeData.toJSON(),{makeContentKey:S.moleculeData.makeContentKey}),moleculeJoins:new No(S.moleculeJoins.toJSON(),{makeContentKey:S.moleculeJoins.makeContentKey}),miscResources:new kT(S.miscResources)},$=DF(o,T),F={phase:"building",update:{type:"transaction_update",key:T,id:n,epoch:$===void 0?Number.NaN:$+1,updates:[],params:f,output:void 0},toolkit:{get:(...R)=>Ro(J,...R),set:(...R)=>{Uo(J,...R)},run:(R,M=cn())=>tf(J,R,M),find:(R,M)=>i(J,R,M),json:(R)=>Io(J,R),dispose:(...R)=>{Af(J,...R)},env:()=>zF(J)}},J=Object.assign(A,{transactionMeta:F});return S.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=QF(o,T.key,A,$);try{let J=C(o),{toolkit:R}=F.transactionMeta,M=T.do(R,...A);return YF(M,J),M}catch(J){throw fF(n),o.logger.warn("\uD83D\uDCA5","transaction",T.key,"caught:",J),J}},install:(A)=>JA(A,T),subject:new oo},n=C(o);n.transactions.set(f.key,f);let S=nT(f);return o.on.transactionCreation.next(S),S}function DF(o,T){let f=jo(o),n=f?o.transactionMeta.actionContinuities.getRelatedKey(T):void 0;return f&&n!==void 0?o.transactionMeta.epoch.get(n):void 0}function Jn(o){return JA(no.STORE,o)}class UF{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 Pn(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 nA("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},jo(T))this.transactionMeta={epoch:new Map(T?.transactionMeta.epoch),actionContinuities:new No(T?.transactionMeta.actionContinuities.toJSON())};for(let[,n]of T.families){if(n.internalRoles?.includes("mutable")||n.internalRoles?.includes("join"))continue;n.install(this)}let f=new Set;for(let[,n]of T.atoms){if(f.has(n.key))continue;if(n.install(this),n.type==="mutable_atom"){let S=Io(T,n),A=bT(n);f.add(S.key),f.add(A.key)}}for(let[,n]of T.readonlySelectors)n.install(this);for(let[,n]of T.selectors){if(f.has(n.key))continue;n.install(this)}for(let[,n]of T.transactions)n.install(this);for(let[,n]of T.timelines)n.install(this)}}}var no={get STORE(){if(!globalThis.ATOM_IO_IMPLICIT_STORE)globalThis.ATOM_IO_IMPLICIT_STORE=new UF({name:"IMPLICIT_STORE",lifespan:"ephemeral"});return globalThis.ATOM_IO_IMPLICIT_STORE}};function $o(o,T){let f,n=o;while(n!==null){switch(T.type){case"atom":case"mutable_atom":f=n.atoms.get(T.key);break;case"selector":f=n.selectors.get(T.key);break;case"readonly_selector":f=n.readonlySelectors.get(T.key);break;case"atom_family":case"mutable_atom_family":case"selector_family":case"readonly_selector_family":f=n.families.get(T.key);break;case"timeline":f=n.timelines.get(T.key);break;case"transaction":f=n.transactions.get(T.key);break}if(f)return f;n=n.child}throw new Sf(T,o)}function VF(o,T,f){let n=o.families.get(T.key);if(n===void 0)throw new Sf(T,o);let S=n(f),A=C(o);if(S.family){if(jo(A))switch(S.type){case"atom":case"mutable_atom":o.on.atomCreation.next(S);break;case"selector":case"readonly_selector":o.on.selectorCreation.next(S);break}else if(Mo(A)&&A.on.transactionApplying.state===null)A.transactionMeta.update.updates.push({type:"state_creation",token:S})}return S}function BF(o,T,f){let n=fo(f),S=`${T.key}(${n})`,A=C(o),$;switch(T.type){case"atom_family":case"mutable_atom_family":$=A.atoms.get(S);break;case"selector_family":$=A.selectors.get(S);break;case"readonly_selector_family":$=A.readonlySelectors.get(S);break}if($)return nT($);return $}function i(o,T,f){let n=BF(o,T,f);if(n)return n;let S=fo(f),A=o.molecules.get(S);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(n=VF(o,T,f),A)C(o).moleculeData.set(S,T.key);return n}function Af(o,...T){let f;if(T.length===1)f=T[0];else{let n=T[0],S=T[1];f=i(o,n,S)}try{$o(o,f)}catch(n){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 oS=(o,T)=>C(o).atoms.has(T),mM=(o,T)=>C(o).selectors.has(T),IM=(o,T)=>C(o).readonlySelectors.has(T),CF=(o,T)=>oS(o,T)||mM(o,T)||IM(o,T);var TS=(o,T)=>{return C(T).selectorGraph.getRelationEntries({downstreamSelectorKey:o}).filter(([n,{source:S}])=>S!==o).map(([n,{source:S}])=>S).filter((n)=>CF(T,n))};var MA=(o,T,f)=>{let n=[],S=TS(o,f);while(S.length>0){let A=S.shift();if(T.has(A))continue;if(T.add(A),!oS(f,A))S.push(...TS(A,f));else if(!n.includes(A))n.push(A)}return n},mF=(o,T)=>{let f=o.key,n=TS(f,T),S=new Set;return n.flatMap((A)=>oS(T,A)?A:MA(A,S,T))};var IF=(o,T,f,n)=>{let S=C(n);if(T.type==="atom"||T.type==="mutable_atom")S.selectorAtoms.set({selectorKey:o,atomKey:T.key}),n.logger.info("\uD83D\uDD0D","selector",o,`discovers root atom "${T.key}"`);else{let A=MA(T.key,f,n);n.logger.info("\uD83D\uDD0D","selector",o,`discovers root atoms: [ ${A.map(($)=>`"${$}"`).join(", ")} ]`);for(let $ of A)S.selectorAtoms=S.selectorAtoms.set({selectorKey:o,atomKey:$})}f.add(T.key)};var fS=(o,T,f)=>({get:(...n)=>{let S=C(f),A;if(n.length===2){let[J,R]=n;A=i(f,J,R)}else[A]=n;let $=$o(f,A),F=PT(f,$);return f.logger.info("\uD83D\uDD0C","selector",o,`registers dependency ( "${A.key}" =`,F,")"),S.selectorGraph.set({upstreamSelectorKey:A.key,downstreamSelectorKey:o},{source:A.key}),IF(o,A,T,f),F},set:(...n)=>{let S,A;if(n.length===2)S=n[0],A=n[1];else{let J=n[0],R=n[1];A=n[2],S=i(f,J,R)}let $=C(f),F=$o($,S);en($,F,A)},find:(n,S)=>i(f,n,S),json:(n)=>Io(f,n)});var nn=(o,T,f)=>{let n=C(o),S=new oo,A=new Set,{get:$,find:F,json:J}=fS(T.key,A,n),R=()=>{let X=T.get({get:$,find:F,json:J});return OT(C(o),T.key,X,S),A.clear(),X},M={...T,subject:S,install:(X)=>nn(X,T,f),get:R,type:"readonly_selector",...f&&{family:f}};n.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 Rn=(o,T,f)=>{let n=C(o),S=new oo,A=new Set,$=fS(T.key,A,n),{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,S),A.clear(),q},X={...T,subject:S,install:(L)=>Rn(L,T,f),get:_,set:(L)=>{let h=C(o),q=_(T.get,h),P=un(L)(q);if(o.logger.info("\uD83D\uDCDD","selector",T.key,"set (",q,"->",P,")"),OT(h,T.key,P,S),zf(h,T.key),jo(h))S.next({newValue:P,oldValue:q});T.set($,P)},type:"selector",...f&&{family:f}};n.selectors.set(T.key,X);let D=_();o.logger.info("\u2728",X.type,X.key,"=",D);let K={key:T.key,type:"selector"};if(f)K.family=f;return K};function jT(o,T){if("set"in T){let S=Rn(o,T,void 0);return o.on.selectorCreation.next(S),S}let n=nn(o,T,void 0);return o.on.selectorCreation.next(n),n}function LF(o,T){let f=C(o),{key:n}=T,S=$o(f,T);if(!S.family)o.logger.error("\u274C","selector",n,"Standalone selectors cannot be disposed.");else{if(f.molecules.get(S.family.subKey))f.moleculeData.delete(S.family.subKey,S.family.key);let $;switch(T.type){case"selector":f.selectors.delete(n),$={key:S.family.key,type:"selector_family"},$o(o,$).subject.next({type:"state_disposal",subType:"selector",token:T});break;case"readonly_selector":f.readonlySelectors.delete(n),$={key:S.family.key,type:"readonly_selector_family"},$o(o,$).subject.next({type:"state_disposal",subType:"selector",token:T});break}if(f.valueMap.delete(n),f.selectorAtoms.delete(n),f.selectorGraph.delete(n),o.logger.info("\uD83D\uDD25",T.type,n,"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 Sn(o,T,f){let n={key:T.key,type:"selector_family"},S=o.families.get(T.key);if(S)o.logger.error("\u2757","selector_family",T.key,`Overwriting an existing ${VT(S)} "${S.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=Rn(w,{key:_,get:T.get(J),set:T.set(J)},M);return A.next({type:"state_creation",token:X}),X},n,{internalRoles:f,subject:A,install:(J)=>Sn(J,T),default:(J)=>{return T.get(J)({get:(...M)=>Ro(o,...M),find:(M,_)=>i(o,M,_),json:(M)=>Io(o,M)})}});return o.families.set(T.key,F),n}function jF(o,T,f){return Sn(o,{key:`${T.key}:JSON`,get:(S)=>({get:A})=>{let $=A(T,S);return f.toJson($)},set:(S)=>({set:A},$)=>{A(T,S,f.fromJson($))}},["mutable","json"])}var vo=(o)=>JSON.parse(o),fo=(o)=>JSON.stringify(o),S4=[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 mF(T,o).map((S)=>{let A=f.atoms.get(S);if(A===void 0)throw new Error(`Atom "${S}", 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",S,"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,n){function S(_){if(o.operation.open){let w=o.on.operationClose.subscribe(`state subscription ${f}`,()=>{w(),n(_)})}else n(_)}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=S;if($)F=kA(o,A),J=(_)=>{if(F)F.length=0,F.push(...kA(o,A));S(_)};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,n)=>{let S=$o(o,T);o.logger.info("\uD83D\uDC40","timeline",T.key,`Adding subscription "${f}"`);let A=S.subject.subscribe(f,n);return()=>{o.logger.info("\uD83D\uDE48","timeline",T.key,`Removing subscription "${f}" from timeline`),A()}};var OA=(o,T,f,n)=>{let S=$o(o,T);o.logger.info("\uD83D\uDC40","transaction",T.key,`Adding subscription "${f}"`);let A=S.subject.subscribe(f,n);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 n=o.family?{key:`*${o.family.key}`,subKey:o.family.subKey}:void 0,S=FT(T,{key:f,default:null},n);if(T.parent?.valueMap.has(f)){let A=T.parent.valueMap.get(f);T.valueMap.set(f,A)}return S}unsubscribeFromInnerValue;unsubscribeFromState;observeCore(o,T,f){let n=`tracker:${f.config.name}:${Mo(f)?f.transactionMeta.update.key:"main"}:${o.key}`,S=Ro(f,o);this.unsubscribeFromInnerValue=S.subscribe(n,(A)=>{Uo(f,T,A)}),this.unsubscribeFromState=lo(f,o,n,(A)=>{if(A.newValue!==A.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=A.newValue.subscribe(n,($)=>{Uo(f,T,$)})})}updateCore(o,T,f){let n=`tracker:${f.config.name}:${Mo(f)?f.transactionMeta.update.key:"main"}:${o.key}`;lo(f,T,n,({newValue:S,oldValue:A})=>{let $=f.timelineTopics.getRelatedKey(T.key);if($){if(f.timelines.get($)?.timeTraveling){let R=WA(f,{key:$,type:"timeline"},n,(M)=>{R(),Uo(f,o,(_)=>{if(M==="redo"&&S)_.do(S);else if(M==="undo"&&A)_.undo(A);return _})});return}}let F=f.on.operationClose.subscribe(n,()=>{F();let J=Ro(f,o),R=S===null?-1:J.getUpdateNumber(S),M=R-J.cacheUpdateNumber;if(S&&M===1)Uo(f,o,(_)=>(_.do(S),_));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 Mn(o,T,f){o.logger.info("\uD83D\uDD28","atom",T.key,`creating in store "${o.config.name}"`);let n=C(o),S=n.atoms.get(T.key);if(S&&S.type==="mutable_atom")return o.logger.error("\u274C","atom",T.key,"Tried to create atom, but it already exists in the store."),nT(S);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}"`),Mn(R,T,f)},subject:A};if(f)$.family=f;let F=T.default();n.atoms.set($.key,$),nS(o,T.key),OT(n,T.key,F,A);let J=nT($);if(T.effects){let R=0,M=[];for(let _ of T.effects){let w=_({setSelf:(X)=>{Uo(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`,(n)=>{let{type:S,token:A}=n;if(A.family){let $=vo(A.family.subKey);switch(S){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 fn(o,T,f){let n={key:T.key,type:"mutable_atom_family"},S=o.families.get(T.key);if(S)o.logger.error("\u2757","mutable_atom_family",T.key,`Overwriting an existing ${VT(S)} "${S.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 D=Mn(w,X,M);return A.next({type:"state_creation",token:D}),D},n,{subject:A,install:(J)=>fn(J,T),toJson:T.toJson,fromJson:T.fromJson,internalRoles:f});return o.families.set(T.key,F),jF(o,F,T),new _A(F,o),n}var wA=(o,T)=>{let f=C(T),n=`${o.key}:JSON`;return f.families.get(n)};var Io=(o,T)=>{if(T.family){let n=C(o),A={key:`${T.family.key}:JSON`,type:"selector_family"},$=$o(n,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 Fn(o,T,f){let n=f.valueMap.get(T.key),S=o.valueMap.get(T.key);if(n===S){if(n===void 0)return typeof T.default==="function"?T.default():T.default;f.logger.info("\uD83D\uDCC3","atom",T.key,"copying");let A=T.toJson(n),$=T.fromJson(A);return o.valueMap.set(T.key,$),new $f(T,f),$}return S}function OT(o,T,f,n){let S=o.valueMap.get(T);if(S instanceof Tn)S.use(f);if(f instanceof Promise){let A=new Tn(f);return o.valueMap.set(T,A),A.then(($)=>{OT(o,T,$,n),n.next({newValue:$,oldValue:A})}).catch(($)=>{o.logger.error("\uD83D\uDCA5","state",T,"rejected:",$)}),A}return o.valueMap.set(T,f),f}var nF=(o,T)=>{let f=T.valueMap.get(o.key);if(o.type==="mutable_atom"&&Mo(T)){let{parent:n}=T;f=Fn(T,o,n)}return f},JF=(o,T)=>{let f=T.valueMap.get(o);if(f instanceof Tn){let n=f,S=T.selectors.get(o)??T.readonlySelectors.get(o);if(S)n.use(S.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)},nS=(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 n=C(o),S=n.atoms.get(T.key);if(S&&S.type==="atom")return o.logger.error("\u274C","atom",T.key,"Tried to create atom, but it already exists in the store."),nT(S);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();n.atoms.set($.key,$),nS(o,T.key),OT(n,T.key,F,A);let J=nT($);if(T.effects){let R=0,M=[];for(let _ of T.effects){let w=_({setSelf:(X)=>{Uo(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 S=Mn(o,T,void 0);return o.on.atomCreation.next(S),S}let n=FT(o,T,void 0);return o.on.atomCreation.next(n),n}function RA(o,T){let f=C(o),{key:n,family:S}=T,A=$o(f,T);if(!S)o.logger.error("\u274C","atom",n,"Standalone atoms cannot be disposed.");else{A.cleanup?.();let $=o.valueMap.get(A.key),F=$o(o,{key:S.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(n),f.valueMap.delete(n),f.selectorAtoms.delete(n),f.atomsThatAreDefault.delete(n),o.timelineTopics.delete(n),T.type==="mutable_atom"){let M=bT(T);RA(o,M),o.trackers.delete(n)}if(o.logger.info("\uD83D\uDD25","atom",n,"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 n of this.transactionUpdates)this.doStep(n);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),n=o.substring(T+1);switch(f){case"add":this.add(JSON.parse(n));break;case"clear":this.clear();break;case"del":this.delete(JSON.parse(n));break;case"tx":for(let S of n.split(";"))this.doStep(S)}}getUpdateNumber(o){let T=o.indexOf("=");return Number(o.substring(0,T))}do(o){let T=o.indexOf("="),f=Number(o.substring(0,T)),n=f-this.cacheUpdateNumber;if(n>0){if(n===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(n)<this.cacheLimit){let A=this.cacheIdx+n;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),n=o.substring(T+1);switch(f){case"add":this.delete(JSON.parse(n));break;case"del":this.add(JSON.parse(n));break;case"clear":{let S=JSON.parse(n);for(let A of S)this.add(A);break}case"tx":{let S=n.split(";");for(let A=S.length-1;A>=0;A--)this.undoStep(S[A])}}}undo(o){let T=o.indexOf("=");if(Number(o.substring(0,T))===this.cacheUpdateNumber){this.mode="playback";let n=o.substring(T+1);return this.undoStep(n),this.mode="record",this.cacheUpdateNumber--,null}return this.cacheUpdateNumber}}class An{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=no.STORE){this.store=f,this.realm=new SA(f),this.options=o,this.defaultContent=T,this.store.miscResources.set(`join:${o.key}`,this),this.realm.allocate("root",o.key),this.toolkit={get:(...G)=>Ro(f,...G),set:(...G)=>{Uo(f,...G)},find:(...G)=>i(f,...G),json:(G)=>Io(f,G)};let n=o.between[0],S=o.between[1],A=fn(f,{key:`${o.key}/relatedKeys`,default:()=>new ho,mutable:!0,fromJson:(G)=>ho.fromJSON(G),toJson:(G)=>G.toJSON()},["join","relations"]);this.core={relatedKeysAtoms:A};let $=({get:G},z)=>G(A,z),F=({set:G},z,U)=>{if(!this.store.molecules.has(fo(z)))this.realm.allocate(o.key,z);G(A,z,(Q)=>Q.add(U)),G(A,U,(Q)=>Q.add(z))},J=({set:G},z,U)=>{G(A,z,(Q)=>{return Q.delete(U),Q}),G(A,U,(Q)=>{return Q.delete(z),Q})},R=(G,z,U)=>{let{find:Q,get:v,set:l}=G,E=Q(A,z),s=v(E);for(let r of s){if(U.includes(r))continue;l(A,r,(ko)=>{return ko.delete(z),ko})}l(E,(r)=>{return r.transaction((a)=>{a.clear();for(let ko of U){let Lo=$(G,ko),fT=Lo.has(z);if(this.relations.cardinality==="1:n"){let IT=[];for(let Y of Lo){if(Y===z)continue;let p=$(G,Y);if(p.delete(ko),p.size===0)IT.push(Y)}if(!fT&&Lo.size>0)Lo.clear();for(let Y of IT){let p=[ko,Y].sort(),Fo=`"${p[0]}:${p[1]}"`;this.molecules.delete(Fo)}}if(!fT)Lo.add(z);a.add(ko)}return!0}),r})},M=(G,z,U)=>{let{set:Q}=G;Q(A,z,(v)=>{return v.transaction((l)=>{for(let E of U)l.add(E);return!0}),v});for(let v of U)Q(A,v,(l)=>{return l.add(z),l});return!0},_=(G,z,U)=>{let Q=$(G,z);return U?Q.has(U):Q.size>0},w={getRelatedKeys:(G)=>$(this.toolkit,G),addRelation:(G,z)=>{this.store.moleculeJoins.set(G,o.key),this.store.moleculeJoins.set(z,o.key),F(this.toolkit,G,z)},deleteRelation:(G,z)=>{J(this.toolkit,G,z)},replaceRelationsSafely:(G,z)=>{R(this.toolkit,G,z)},replaceRelationsUnsafely:(G,z)=>{M(this.toolkit,G,z)},has:(G,z)=>_(this.toolkit,G,z)},X,D;if(T){D=NT(f,{key:`${o.key}/content`,default:T},["join","content"]);let G=({get:Q},v)=>Q(D,v),z=({set:Q},v,l)=>{Q(D,v,l)};X=Object.assign(w,{getContent:(Q)=>{return G(this.toolkit,Q)},setContent:(Q,v)=>{z(this.toolkit,Q,v)},deleteContent:(Q)=>{this.realm.deallocate(Q)}})}else X=w;let K=new No(o,{externalStore:X,isAType:o.isAType,isBType:o.isBType,makeContentKey:(...G)=>{let[z,U]=G,Q=G.sort(),v=`${Q[0]}:${Q[1]}`,l=f.molecules.get(fo(z)),E=f.molecules.get(fo(U));if(!l)this.realm.allocate(o.key,z);if(!E)this.realm.allocate(o.key,U);return this.realm.allocate(z,v,"all"),this.realm.claim(U,v),this.store.moleculeJoins.set(v,o.key),v}}),L=()=>hT(f,{key:`${o.key}/singleRelatedKey`,get:(G)=>({get:z})=>{let U=z(A,G);for(let Q of U)return Q;return null}},["join","keys"]),h=()=>{return hT(f,{key:`${o.key}/multipleRelatedKeys`,get:(G)=>({get:z})=>{let U=wA(A,f);return z(U,G).members}},["join","keys"])},q=()=>hT(f,{key:`${o.key}/singleRelatedEntry`,get:(G)=>({get:z})=>{let U=z(A,G);for(let Q of U){let v=K.isAType?.(G)?G:void 0,l=v===void 0?G:void 0;v??=Q,l??=Q;let E=K.makeContentKey(v,l),s=z(D,E);return[Q,s]}return null}},["join","entries"]),P=()=>hT(f,{key:`${o.key}/multipleRelatedEntries`,get:(G)=>({get:z})=>{let U=wA(A,f);return z(U,G).members.map((v)=>{let l=K.isAType?.(G)?G:void 0,E=l===void 0?G:void 0;l??=v,E??=v;let s=K.makeContentKey(l,E),r=z(D,s);return[v,r]})}},["join","entries"]);switch(o.cardinality){case"1:1":{let G=L(),z=`${n}KeyOf${Wo(S)}`,U=`${S}KeyOf${Wo(n)}`,Q={[z]:G,[U]:G},v;if(T){let l=q(),E=`${n}EntryOf${Wo(S)}`,s=`${S}EntryOf${Wo(n)}`,r={[E]:l,[s]:l};v=Object.assign(Q,r)}else v=Q;this.relations=K,this.states=v;break}case"1:n":{let G=L(),z=h(),U=`${n}KeyOf${Wo(S)}`,Q=`${S}KeysOf${Wo(n)}`,v={[U]:G,[Q]:z},l;if(T){let E=q(),s=P(),r=`${n}EntryOf${Wo(S)}`,a=`${S}EntriesOf${Wo(n)}`,ko={[r]:E,[a]:s};l=Object.assign(v,ko)}else l=v;this.relations=K,this.states=l;break}case"n:n":{let G=h(),z=`${n}KeysOf${Wo(S)}`,U=`${S}KeysOf${Wo(n)}`,Q={[z]:G,[U]:G},v;if(T){let l=P(),E=`${n}EntriesOf${Wo(S)}`,s=`${S}EntriesOf${Wo(n)}`,r={[E]:l,[s]:l};v=Object.assign(Q,r)}else v=Q;this.relations=K,this.states=v}}}}function Qf(o,T){let f=T.joins.get(o.key);if(f===void 0){let S=no.STORE.joins.get(o.key);if(S===void 0)throw new Error(`Join "${o.key}" not found in store "${T.config.name}"`);f=new An(S.options,S.defaultContent,T),T.joins.set(o.key,f)}return f}function $n(o,T,f){let n=Qf(o,f),S=C(f);if(Mo(S)){let{toolkit:A}=S.transactionMeta;n.transact(A,({relations:$})=>{T($)})}else T(n.relations)}function dn(o,T,f){let n=Qf(o,f),S;switch(o.cardinality){case"1:1":{let A=`${o.a}KeyOf${Wo(o.b)}`,$=`${o.b}KeyOf${Wo(o.a)}`;S={get[A](){let J=n.states[A];return i(f,J,T)},get[$](){let J=n.states[$];return i(f,J,T)}};let F=`${o.a}EntryOf${Wo(o.b)}`;if(F in n.states){let J=`${o.b}EntryOf${Wo(o.a)}`;Object.assign(S,{get[F](){let R=n.states[F];return i(f,R,T)},get[J](){let R=n.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)}`;S={get[A](){let J=n.states[A];return i(f,J,T)},get[$](){let J=n.states[$];return i(f,J,T)}};let F=`${o.a}EntryOf${Wo(o.b)}`;if(F in n.states){let J=`${o.b}EntriesOf${Wo(o.a)}`;Object.assign(S,{get[F](){let R=n.states[F];return i(f,R,T)},get[J](){let R=n.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)}`;S={get[A](){let J=n.states[A];return i(f,J,T)},get[$](){let J=n.states[$];return i(f,J,T)}};let F=`${o.a}EntriesOf${Wo(o.b)}`;if(F in n.states){let J=`${o.b}EntriesOf${Wo(o.a)}`;Object.assign(S,{get[F](){let R=n.states[F];return i(f,R,T)},get[J](){let R=n.states[J];return i(f,R,T)}})}}}return S}function s$(o,T){return Qf(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[n,S]of o.atoms)if(!n.includes("\uD83D\uDD0D")){let A=nT(S);if(S.family){let $=f.get(S.family.key);if(!$||!("familyMembers"in $))$={key:S.family.key,familyMembers:new Map},f.set(S.family.key,$);$.familyMembers.set(S.family.subKey,A)}else f.set(n,A)}return f},effects:[({setSelf:f})=>{o.on.atomCreation.subscribe("introspection",(n)=>{if(n.key.includes("\uD83D\uDD0D"))return;f((S)=>{if(n.family){let{key:A,subKey:$}=n.family,F=S.get(A);if(F===void 0||!("familyMembers"in F))F={key:A,familyMembers:new Map},S.set(A,F);F.familyMembers.set($,n)}else S.set(n.key,n);return S})}),o.on.atomDisposal.subscribe("introspection",(n)=>{f((S)=>{if(n.family){let{key:A,subKey:$}=n.family,F=S.get(A);if(F&&"familyMembers"in F){if(F.familyMembers.delete($),F.familyMembers.size===0)S.delete(A)}}else S.delete(n.key);return S})})}]},void 0);return jT(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 n of[o.readonlySelectors,o.selectors])for(let[S,A]of n)if(!S.includes("\uD83D\uDD0D")){let $=nT(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(S,$)}return f},effects:[({setSelf:f})=>{o.on.selectorCreation.subscribe("introspection",(n)=>{if(n.key.includes("\uD83D\uDD0D"))return;f((S)=>{if(n.family){let{key:A,subKey:$}=n.family,F=S.get(A);if(F===void 0||!("familyMembers"in F))F={key:A,familyMembers:new Map},S.set(A,F);F.familyMembers.set($,n)}else S.set(n.key,n);return S})}),o.on.selectorDisposal.subscribe("introspection",(n)=>{f((S)=>{if(n.family){let{key:A,subKey:$}=n.family,F=S.get(A);if(F&&"familyMembers"in F){if(F.familyMembers.delete($),F.familyMembers.size===0)S.delete(A)}}else S.delete(n.key);return S})})}]},void 0);return jT(o,{key:"\uD83D\uDD0D Selector Token Index",get:({get:f})=>f(T)})};class SS{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(n){try{if(o instanceof f)return{type:T,data:o}}catch(S){}}return null}}var HA=new SS({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 EA=new SS({object:KA,array:(o)=>Array.isArray(o)}),jM=new SS({...HA.supported,...EA.supported}),Df=(o)=>{if(o===void 0)return"undefined";let T=jM.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=no.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),n=[...T.values()].filter((F)=>("familyMembers"in F)),S=[...f.values()].filter((F)=>("familyMembers"in F)),A=performance.now(),$=[];if(o.atomFamilies)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])}}if(o.selectorFamilies)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])}}return $}[Symbol.dispose](){this.unsubscribeFromAtomCreation(),this.unsubscribeFromAtomDisposal(),this.unsubscribeFromSelectorCreation(),this.unsubscribeFromSelectorDisposal(),this.disposed=!0}}var GA=(o,T)=>{let f=(n,S)=>{let $=((J,R)=>{let M=T(J,R);if(M)return M;return null})(n,S);if($?.jobComplete??$?.pathComplete)return $;let F=Array.isArray(S)?S.map((J,R)=>[R,J]):KA(S)?Object.entries(S):[];for(let[J,R]of F){let M=f([...n,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 n="",S=[],A=[],$=[];return GA(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,_])}}}),GA(T,(F,J)=>{let R;for(R of F)if(o[R]===void 0)S.push([R,JSON.stringify(J)])}),n=`\uFF5E${$.length} \uFF0B${S.length} \uFF0D${A.length}`,{summary:n,added:S,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 n of Object.keys(o.supported)){let S=f[n];this.leafDiffers[n]=S}for(let n of Object.keys(T.supported)){let S=f[n];this.treeDiffers[n]=S}}diff(o,T){if(o===T)return{summary:"No Change"};let f=this.leafRefinery.refine(o)??this.treeRefinery.refine(o),n=this.leafRefinery.refine(T)??this.treeRefinery.refine(T);if(f!==null&&n!==null){if(f.type===n.type){if(f.type in this.leafDiffers)return this.leafDiffers[f.type](f.data,n.data);if(f.type in this.treeDiffers)return this.treeDiffers[f.type](f.data,n.data,(F,J)=>this.diff(F,J))}}let S=Df(o),A=Df(T);if(S===A)return{summary:`${S} \u2192 ${A}`};return{summary:`Type change: ${S} \u2192 ${A}`}}}var oK=new xF(HA,EA,{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 AS{type="continuity";globals=[];actions=[];perspectives=[];key;constructor(o){this.key=o}static existing=new vF;static create(o,T){let f=new AS(o),{type:n,globals:S,actions:A,perspectives:$}=T(f),F={type:n,key:o,globals:S,actions:A,perspectives:$};return AS.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":case"mutable_atom_family":{let[f,n]=o;this.perspectives.push({type:"realtime_perspective",resourceAtoms:f,viewAtoms:n})}break}return this}}function RK(o){let{key:T,config:f}=o,n=AS.create(T,f),{actions:S}=n;for(let A of S)tF(no.STORE,T,A.key);return EF(no.STORE,T,-1),n}var kK=Gf({key:"usersInRoomIndex",mutable:!0,default:()=>new ho,toJson:(o)=>o.toJSON(),fromJson:(o)=>ho.fromJSON(o)}),YA=Gf({key:"roomIndex",default:()=>new ho,mutable:!0,toJson:(o)=>o.toJSON(),fromJson:(o)=>ho.fromJSON(o)}),vM={enteredAtEpoch:0},Wn=gn({key:"usersInRooms",between:["room","user"],cardinality:"1:n",isAType:(o)=>typeof o==="string",isBType:(o)=>typeof o==="string"},vM),_K=ln({key:"usersInMyRoomView",get:(o)=>({find:T})=>{let f=e$(Wn);return[T(f,o)]}});import{spawn as qM}from"child_process";class Uf{listeners;globalListeners;handleEvent(o,...T){for(let n of this.globalListeners)n(o,...T);let f=this.listeners.get(o);if(f)for(let n of f)n(...T)}id="no_id_retrieved";emit;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 tA extends Uf{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;default:return}}}constructor(o,T,f){super((n,...S)=>{let A=JSON.stringify([n,...S])+"\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:(...n)=>{console.info(this.id,this.key,...n)},warn:(...n)=>{console.warn(this.id,this.key,...n)},error:(...n)=>{console.error(this.id,this.key,...n)}},this.process.stdout.on("data",(n)=>{let S=n.toString();if(S==="ALIVE")return;this.unprocessedEvents.push(...S.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",(n)=>{let S=n.toString();this.unprocessedLogs.push(...S.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 Uf{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 zA extends Uf{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 n=vo(this.incompleteData);this.logger.info("\uD83C\uDFB0","received",n),this.handleEvent(...n);while(this.unprocessedEvents.length>0){let S=this.unprocessedEvents.shift();if(S){if(this.unprocessedEvents.length===0)this.incompleteData=S;let A=vo(S);this.handleEvent(...A)}}this.incompleteData=""}catch(n){if(n instanceof Error)this.logger.error("\u2757",n.message,n.cause,n.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 n=f(T);if(n)T.disposalFunctions.push(n)}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 QA=Tf({key:"roomArguments",default:["echo",["Hello World!"]]}),rF=ln({key:"room",get:(o)=>async({get:T,find:f})=>{let n=f(QA,o),S=T(n),[A,$]=S,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 tA(F,o)}});var rK=Jn({key:"createRoom",do:({get:o,set:T,find:f},n,S,A)=>{let $=A?[S,A]:[S],F=f(QA,n);T(F,$),T(YA,(M)=>M.add(n));let J=f(rF,n);return o(J)}}),pK=Jn({key:"joinRoom",do:(o,T,f,n)=>{let S={enteredAtEpoch:n};return $n(Wn,(A)=>{A.set({room:T,user:f},S)},o.env().store),S}}),cK=Jn({key:"leaveRoom",do:(o,T,f)=>{$n(Wn,(n)=>{n.delete({room:T,user:f})},o.env().store)}}),ZK=Jn({key:"destroyRoom",do:(o,T)=>{$n(Wn,(f)=>{f.delete({room:T})},o.env().store),o.set(YA,(f)=>(f.delete(T),f))}});function DA(o,T){return T.map((f)=>{switch(f.type){case"transaction_update":{let n=DA(o,f.updates);return{...f,updates:n}}case"atom_update":case"selector_update":case"molecule_creation":case"molecule_disposal":case"molecule_transfer":case"state_creation":case"state_disposal":return f}}).filter((f)=>{switch(f.type){case"atom_update":case"selector_update":return o.includes(f.key);case"state_creation":case"state_disposal":return o.includes(f.token.key);case"molecule_creation":case"transaction_update":case"molecule_disposal":case"molecule_transfer":return!0}})}var gK=Tf({key:"redactor",default:{occlude:(o)=>o}}),Vf=Tf({key:"unacknowledgedUpdates",default:()=>[]});var pF=Tf({key:"sockets",default:null}),eK=Gf({key:"socketsIndex",mutable:!0,default:()=>new ho,toJson:(o)=>o.toJSON(),fromJson:(o)=>ho.fromJSON(o)}),sK=Gf({key:"usersIndex",mutable:!0,default:()=>new ho,toJson:(o)=>o.toJSON(),fromJson:(o)=>ho.fromJSON(o)}),UA=gn({key:"usersOfSockets",between:["user","socket"],cardinality:"1:1",isAType:(o)=>o.startsWith("user::"),isBType:(o)=>o.startsWith("socket::")});function cF(o,T,f,n){let S=T.key;return function A(){let $=[];for(let J of T.globals){let R=J.type==="mutable_atom"?Io(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 D=X.type==="mutable_atom"?Io(o,X):X,K=Ro(o,D);$.push(D,K)}}let F=jo(o)?o.transactionMeta.epoch.get(S)??null:null;n?.emit(`continuity-init:${S}`,F,$)}}function ZF(o,T,f){let n=T.key;return function S(A){o.logger.info("\uD83D\uDECE\uFE0F","continuity",n,"received",A);let{key:$,id:F}=A,J=`tx-run:${$}:${F}`,R=`${J}:start`,M=`${J}:end`;performance.mark(R);try{tf(o,{type:"transaction",key:$},F)(...A.params)}catch(w){if(w instanceof Error)o.logger.error("\u274C","continuity",n,`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,n){let S=T.key;return function A($){if(o.logger.info("\uD83D\uDC4D","continuity",S,`${f} acknowledged epoch ${$}`),n[0]?.epoch===$)Uo(o,Vf,f,(J)=>{return J.shift(),o.logger.info("\uD83D\uDC4D","continuity",S,`${f} unacknowledged update queue now has`,J.length,"items"),J})}}function iF(o,T,f,n){let S=T.key,A=[];for(let $ of T.actions){let F=OA(o,$,`sync-continuity:${S}:${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,D=i(o,X,f);return Ro(o,D).map((L)=>{return L.type==="mutable_atom"?"*"+L.key:L.key})})),M=DA(R,J.updates),_={...J,updates:M};Uo(o,Vf,f,(w)=>{if(_)w.push(_),w.sort((X,D)=>X.epoch-D.epoch),o.logger.info("\uD83D\uDC4D","continuity",S,`${f} unacknowledged update queue now has`,w.length,"items");return w}),n?.emit(`tx-new:${S}`,_)}catch(R){if(R instanceof Error)o.logger.error("\u274C","continuity",S,`${f} failed to send update from transaction ${$.key} to ${f}`,R.message)}});A.push(F)}return A}function gF(o,T,f,n){let S=T.key,A=[];for(let $ of T.perspectives){let{viewAtoms:F}=$,J=i(o,F,f),R=lo(o,J,`sync-continuity:${S}:${f}:perspective:${$.resourceAtoms.key}`,({oldValue:M,newValue:_})=>{let w=M.map((L)=>L.key),X=_.map((L)=>L.key),D=M.filter((L)=>!X.includes(L.key)),K=_.filter((L)=>!w.includes(L.key)).flatMap((L)=>{let h=L.type==="mutable_atom"?Io(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:D}),K.length>0)n?.emit(`reveal:${S}`,K);if(D.length>0)n?.emit(`conceal:${S}`,D)});A.push(R)}return A}function U5({socket:o,store:T=no.STORE}){return function f(n){let S=o,A=n.key,$=dn(UA,`socket::${S.id}`,T).userKeyOfSocket,F=Ro(T,$);if(!F)return T.logger.error("\u274C","continuity",A,`Tried to create a synchronizer for a socket (${S.id}) that is not connected to a user.`),()=>{};let J=dn(UA,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,pF,h);S=Ro(T,q);for(let G of M)S?.emit(`tx-new:${A}`,G)}),M=Ro(T,Vf,F),_=[],w=gF(T,n,F,S),X=iF(T,n,F,S);_.push(...w,...X);let D=cF(T,n,F,o);S.off(`get:${A}`,D),S.on(`get:${A}`,D);let K=ZF(T,n,F);S.off(`tx-run:${A}`,K),S.on(`tx-run:${A}`,K);let L=PF(T,n,F,M);return S?.on(`ack:${A}`,L),()=>{for(let h of _)h();S?.off(`ack:${A}`,L),S?.off(`get:${A}`,D),S?.off(`tx-run:${A}`,K)}}}var{file:L1,serve:nk}=globalThis.Bun;import{readFileSync as JJ}from"fs";import{resolve as IA}from"path";function rM(o,T){let f={},n=[];for(let S in o){let A=o[S],$=T[S],F=A["~standard"].validate($);if(F instanceof Promise)throw new Error(`Validation must be synchronous, but ${S} returned a Promise.`);if(F.issues){n.push(...F.issues.map((J)=>({...J,path:[S,...J.path??[]]})));continue}f[S]=F.value}if(n.length)return{issues:n};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 S=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,...$,...S}:{...S,...$},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)},D=(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(D(P))return;if(!X(P))return _(P);return Reflect.get(q,P)}})}var Ao;(function(o){o.assertEqual=(S)=>S;function T(S){}o.assertIs=T;function f(S){throw new Error}o.assertNever=f,o.arrayToEnum=(S)=>{let A={};for(let $ of S)A[$]=$;return A},o.getValidEnumValues=(S)=>{let A=o.objectKeys(S).filter((F)=>typeof S[S[F]]!=="number"),$={};for(let F of A)$[F]=S[F];return o.objectValues($)},o.objectValues=(S)=>{return o.objectKeys(S).map(function(A){return S[A]})},o.objectKeys=typeof Object.keys==="function"?(S)=>Object.keys(S):(S)=>{let A=[];for(let $ in S)if(Object.prototype.hasOwnProperty.call(S,$))A.push($);return A},o.find=(S,A)=>{for(let $ of S)if(A($))return $;return},o.isInteger=typeof Number.isInteger==="function"?(S)=>Number.isInteger(S):(S)=>typeof S==="number"&&isFinite(S)&&Math.floor(S)===S;function n(S,A=" | "){return S.map(($)=>typeof $==="string"?`'${$}'`:$).join(A)}o.joinValues=n,o.jsonStringifyReplacer=(S,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}},t=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"]),pM=(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(S){return S.message},f={_errors:[]},n=(S)=>{for(let A of S.issues)if(A.code==="invalid_union")A.unionErrors.map(n);else if(A.code==="invalid_return_type")n(A.returnTypeError);else if(A.code==="invalid_arguments")n(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 n(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 n of this.issues)if(n.path.length>0)T[n.path[0]]=T[n.path[0]]||[],T[n.path[0]].push(o(n));else f.push(o(n));return{formErrors:f,fieldErrors:T}}get formErrors(){return this.flatten()}}JT.create=(o)=>{return new JT(o)};var mf=(o,T)=>{let f;switch(o.code){case t.invalid_type:if(o.received===N.undefined)f="Required";else f=`Expected ${o.expected}, received ${o.received}`;break;case t.invalid_literal:f=`Invalid literal value, expected ${JSON.stringify(o.expected,Ao.jsonStringifyReplacer)}`;break;case t.unrecognized_keys:f=`Unrecognized key(s) in object: ${Ao.joinValues(o.keys,", ")}`;break;case t.invalid_union:f="Invalid input";break;case t.invalid_union_discriminator:f=`Invalid discriminator value. Expected ${Ao.joinValues(o.options)}`;break;case t.invalid_enum_value:f=`Invalid enum value. Expected ${Ao.joinValues(o.options)}, received '${o.received}'`;break;case t.invalid_arguments:f="Invalid function arguments";break;case t.invalid_return_type:f="Invalid function return type";break;case t.invalid_date:f="Invalid date";break;case t.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 t.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 t.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 t.custom:f="Invalid input";break;case t.invalid_intersection_types:f="Intersection results could not be merged";break;case t.not_multiple_of:f=`Number must be a multiple of ${o.multipleOf}`;break;case t.not_finite:f="Number must be finite";break;default:f=T.defaultError,Ao.assertNever(o)}return{message:f}},sF=mf;function cM(o){sF=o}function $S(){return sF}var FS=(o)=>{let{data:T,path:f,errorMaps:n,issueData:S}=o,A=[...f,...S.path||[]],$={...S,path:A};if(S.message!==void 0)return{...S,path:A,message:S.message};let F="",J=n.filter((R)=>!!R).slice().reverse();for(let R of J)F=R($,{data:T,defaultError:F}).message;return{...S,path:A,message:F}},ZM=[];function m(o,T){let f=$S(),n=FS({issueData:T,data:o.data,path:o.path,errorMaps:[o.common.contextualErrorMap,o.schemaErrorMap,f,f===mf?void 0:mf].filter((S)=>!!S)});o.common.issues.push(n)}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 n of T){if(n.status==="aborted")return d;if(n.status==="dirty")o.dirty();f.push(n.value)}return{status:o.value,value:f}}static async mergeObjectAsync(o,T){let f=[];for(let n of T){let S=await n.key,A=await n.value;f.push({key:S,value:A})}return uo.mergeObjectSync(o,f)}static mergeObjectSync(o,T){let f={};for(let n of T){let{key:S,value:A}=n;if(S.status==="aborted")return d;if(A.status==="aborted")return d;if(S.status==="dirty")o.dirty();if(A.status==="dirty")o.dirty();if(S.value!=="__proto__"&&(typeof A.value!=="undefined"||n.alwaysSet))f[S.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",_n=(o)=>typeof Promise!=="undefined"&&o instanceof Promise;function JS(o,T,f,n){if(f==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof T==="function"?o!==T||!n:!T.has(o))throw new TypeError("Cannot read private member from an object whose class did not declare it");return f==="m"?n:f==="a"?n.call(o):n?n.value:T.get(o)}function aF(o,T,f,n,S){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!S)throw new TypeError("Private accessor was defined without a setter");if(typeof T==="function"?o!==T||!S:!T.has(o))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?S.call(o,f):S?S.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 On,kn;class YT{constructor(o,T,f,n){this._cachedPath=[],this.parent=o,this.data=T,this._path=f,this._key=n}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:n,description:S}=o;if(T&&(f||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(T)return{errorMap:T,description:S};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:n)!==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:S}}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(_n(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 n={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)},S=this._parseSync({data:o,path:n.path,parent:n});return lF(n,S)}"~validate"(o){var T,f;let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:o,parsedType:vT(o)};if(!this["~standard"].async)try{let S=this._parseSync({data:o,path:[],parent:n});return Ff(S)?{value:S.value}:{issues:n.common.issues}}catch(S){if((f=(T=S===null||S===void 0?void 0:S.message)===null||T===void 0?void 0:T.toLowerCase())===null||f===void 0?void 0:f.includes("encountered"))this["~standard"].async=!0;n.common={issues:[],async:!0}}return this._parseAsync({data:o,path:[],parent:n}).then((S)=>Ff(S)?{value:S.value}:{issues:n.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)},n=this._parse({data:o,path:f.path,parent:f}),S=await(_n(n)?n:Promise.resolve(n));return lF(f,S)}refine(o,T){let f=(n)=>{if(typeof T==="string"||typeof T==="undefined")return{message:T};else if(typeof T==="function")return T(n);else return T};return this._refinement((n,S)=>{let A=o(n),$=()=>S.addIssue({code:t.custom,...f(n)});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,n)=>{if(!o(f))return n.addIssue(typeof T==="function"?T(f,n):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 GT.create(this,this._def)}nullable(){return qT.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ET.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 MS({typeName:g.ZodBranded,type:this,...u(this._def)})}catch(o){let T=typeof o==="function"?o:()=>o;return new pf({...u(this._def),innerType:this,catchValue:T,typeName:g.ZodCatch})}describe(o){return new this.constructor({...this._def,description:o})}pipe(o){return En.create(this,o)}readonly(){return cf.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]))$/,nW=/^(([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])$/,SW=/^([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("."),n=f.replace(/-/g,"+").replace(/_/g,"/").padEnd(f.length+(4-f.length%4)%4,"="),S=JSON.parse(atob(n));if(typeof S!=="object"||S===null)return!1;if(!S.typ||!S.alg)return!1;if(T&&S.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)&&nW.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 S=this._getOrReturnCtx(o);return m(S,{code:t.invalid_type,expected:N.string,received:S.parsedType}),d}let f=new uo,n=void 0;for(let S of this._def.checks)if(S.kind==="min"){if(o.data.length<S.value)n=this._getOrReturnCtx(o,n),m(n,{code:t.too_small,minimum:S.value,type:"string",inclusive:!0,exact:!1,message:S.message}),f.dirty()}else if(S.kind==="max"){if(o.data.length>S.value)n=this._getOrReturnCtx(o,n),m(n,{code:t.too_big,maximum:S.value,type:"string",inclusive:!0,exact:!1,message:S.message}),f.dirty()}else if(S.kind==="length"){let A=o.data.length>S.value,$=o.data.length<S.value;if(A||$){if(n=this._getOrReturnCtx(o,n),A)m(n,{code:t.too_big,maximum:S.value,type:"string",inclusive:!0,exact:!0,message:S.message});else if($)m(n,{code:t.too_small,minimum:S.value,type:"string",inclusive:!0,exact:!0,message:S.message});f.dirty()}}else if(S.kind==="email"){if(!sM.test(o.data))n=this._getOrReturnCtx(o,n),m(n,{validation:"email",code:t.invalid_string,message:S.message}),f.dirty()}else if(S.kind==="emoji"){if(!VA)VA=new RegExp(aM,"u");if(!VA.test(o.data))n=this._getOrReturnCtx(o,n),m(n,{validation:"emoji",code:t.invalid_string,message:S.message}),f.dirty()}else if(S.kind==="uuid"){if(!dM.test(o.data))n=this._getOrReturnCtx(o,n),m(n,{validation:"uuid",code:t.invalid_string,message:S.message}),f.dirty()}else if(S.kind==="nanoid"){if(!lM.test(o.data))n=this._getOrReturnCtx(o,n),m(n,{validation:"nanoid",code:t.invalid_string,message:S.message}),f.dirty()}else if(S.kind==="cuid"){if(!PM.test(o.data))n=this._getOrReturnCtx(o,n),m(n,{validation:"cuid",code:t.invalid_string,message:S.message}),f.dirty()}else if(S.kind==="cuid2"){if(!iM.test(o.data))n=this._getOrReturnCtx(o,n),m(n,{validation:"cuid2",code:t.invalid_string,message:S.message}),f.dirty()}else if(S.kind==="ulid"){if(!gM.test(o.data))n=this._getOrReturnCtx(o,n),m(n,{validation:"ulid",code:t.invalid_string,message:S.message}),f.dirty()}else if(S.kind==="url")try{new URL(o.data)}catch(A){n=this._getOrReturnCtx(o,n),m(n,{validation:"url",code:t.invalid_string,message:S.message}),f.dirty()}else if(S.kind==="regex"){if(S.regex.lastIndex=0,!S.regex.test(o.data))n=this._getOrReturnCtx(o,n),m(n,{validation:"regex",code:t.invalid_string,message:S.message}),f.dirty()}else if(S.kind==="trim")o.data=o.data.trim();else if(S.kind==="includes"){if(!o.data.includes(S.value,S.position))n=this._getOrReturnCtx(o,n),m(n,{code:t.invalid_string,validation:{includes:S.value,position:S.position},message:S.message}),f.dirty()}else if(S.kind==="toLowerCase")o.data=o.data.toLowerCase();else if(S.kind==="toUpperCase")o.data=o.data.toUpperCase();else if(S.kind==="startsWith"){if(!o.data.startsWith(S.value))n=this._getOrReturnCtx(o,n),m(n,{code:t.invalid_string,validation:{startsWith:S.value},message:S.message}),f.dirty()}else if(S.kind==="endsWith"){if(!o.data.endsWith(S.value))n=this._getOrReturnCtx(o,n),m(n,{code:t.invalid_string,validation:{endsWith:S.value},message:S.message}),f.dirty()}else if(S.kind==="datetime"){if(!fJ(S).test(o.data))n=this._getOrReturnCtx(o,n),m(n,{code:t.invalid_string,validation:"datetime",message:S.message}),f.dirty()}else if(S.kind==="date"){if(!$W.test(o.data))n=this._getOrReturnCtx(o,n),m(n,{code:t.invalid_string,validation:"date",message:S.message}),f.dirty()}else if(S.kind==="time"){if(!FW(S).test(o.data))n=this._getOrReturnCtx(o,n),m(n,{code:t.invalid_string,validation:"time",message:S.message}),f.dirty()}else if(S.kind==="duration"){if(!eM.test(o.data))n=this._getOrReturnCtx(o,n),m(n,{validation:"duration",code:t.invalid_string,message:S.message}),f.dirty()}else if(S.kind==="ip"){if(!JW(o.data,S.version))n=this._getOrReturnCtx(o,n),m(n,{validation:"ip",code:t.invalid_string,message:S.message}),f.dirty()}else if(S.kind==="jwt"){if(!RW(o.data,S.alg))n=this._getOrReturnCtx(o,n),m(n,{validation:"jwt",code:t.invalid_string,message:S.message}),f.dirty()}else if(S.kind==="cidr"){if(!MW(o.data,S.version))n=this._getOrReturnCtx(o,n),m(n,{validation:"cidr",code:t.invalid_string,message:S.message}),f.dirty()}else if(S.kind==="base64"){if(!SW.test(o.data))n=this._getOrReturnCtx(o,n),m(n,{validation:"base64",code:t.invalid_string,message:S.message}),f.dirty()}else if(S.kind==="base64url"){if(!AW.test(o.data))n=this._getOrReturnCtx(o,n),m(n,{validation:"base64url",code:t.invalid_string,message:S.message}),f.dirty()}else Ao.assertNever(S);return{status:f.value,value:o.data}}_regex(o,T,f){return this.refinement((n)=>o.test(n),{validation:T,code:t.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,n=(T.toString().split(".")[1]||"").length,S=f>n?f:n,A=parseInt(o.toFixed(S).replace(".","")),$=parseInt(T.toFixed(S).replace(".",""));return A%$/Math.pow(10,S)}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 S=this._getOrReturnCtx(o);return m(S,{code:t.invalid_type,expected:N.number,received:S.parsedType}),d}let f=void 0,n=new uo;for(let S of this._def.checks)if(S.kind==="int"){if(!Ao.isInteger(o.data))f=this._getOrReturnCtx(o,f),m(f,{code:t.invalid_type,expected:"integer",received:"float",message:S.message}),n.dirty()}else if(S.kind==="min"){if(S.inclusive?o.data<S.value:o.data<=S.value)f=this._getOrReturnCtx(o,f),m(f,{code:t.too_small,minimum:S.value,type:"number",inclusive:S.inclusive,exact:!1,message:S.message}),n.dirty()}else if(S.kind==="max"){if(S.inclusive?o.data>S.value:o.data>=S.value)f=this._getOrReturnCtx(o,f),m(f,{code:t.too_big,maximum:S.value,type:"number",inclusive:S.inclusive,exact:!1,message:S.message}),n.dirty()}else if(S.kind==="multipleOf"){if(WW(o.data,S.value)!==0)f=this._getOrReturnCtx(o,f),m(f,{code:t.not_multiple_of,multipleOf:S.value,message:S.message}),n.dirty()}else if(S.kind==="finite"){if(!Number.isFinite(o.data))f=this._getOrReturnCtx(o,f),m(f,{code:t.not_finite,message:S.message}),n.dirty()}else Ao.assertNever(S);return{status:n.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,n){return new gT({...this._def,checks:[...this._def.checks,{kind:o,value:T,inclusive:f,message:x.toString(n)}]})}_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(S){return this._getInvalidInput(o)}if(this._getType(o)!==N.bigint)return this._getInvalidInput(o);let f=void 0,n=new uo;for(let S of this._def.checks)if(S.kind==="min"){if(S.inclusive?o.data<S.value:o.data<=S.value)f=this._getOrReturnCtx(o,f),m(f,{code:t.too_small,type:"bigint",minimum:S.value,inclusive:S.inclusive,message:S.message}),n.dirty()}else if(S.kind==="max"){if(S.inclusive?o.data>S.value:o.data>=S.value)f=this._getOrReturnCtx(o,f),m(f,{code:t.too_big,type:"bigint",maximum:S.value,inclusive:S.inclusive,message:S.message}),n.dirty()}else if(S.kind==="multipleOf"){if(o.data%S.value!==BigInt(0))f=this._getOrReturnCtx(o,f),m(f,{code:t.not_multiple_of,multipleOf:S.value,message:S.message}),n.dirty()}else Ao.assertNever(S);return{status:n.value,value:o.data}}_getInvalidInput(o){let T=this._getOrReturnCtx(o);return m(T,{code:t.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,n){return new dT({...this._def,checks:[...this._def.checks,{kind:o,value:T,inclusive:f,message:x.toString(n)}]})}_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 If 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 m(f,{code:t.invalid_type,expected:N.boolean,received:f.parsedType}),d}return ao(o.data)}}If.create=(o)=>{return new If({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 S=this._getOrReturnCtx(o);return m(S,{code:t.invalid_type,expected:N.date,received:S.parsedType}),d}if(isNaN(o.data.getTime())){let S=this._getOrReturnCtx(o);return m(S,{code:t.invalid_date}),d}let f=new uo,n=void 0;for(let S of this._def.checks)if(S.kind==="min"){if(o.data.getTime()<S.value)n=this._getOrReturnCtx(o,n),m(n,{code:t.too_small,message:S.message,inclusive:!0,exact:!1,minimum:S.value,type:"date"}),f.dirty()}else if(S.kind==="max"){if(o.data.getTime()>S.value)n=this._getOrReturnCtx(o,n),m(n,{code:t.too_big,message:S.message,inclusive:!0,exact:!1,maximum:S.value,type:"date"}),f.dirty()}else Ao.assertNever(S);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 wn extends e{_parse(o){if(this._getType(o)!==N.symbol){let f=this._getOrReturnCtx(o);return m(f,{code:t.invalid_type,expected:N.symbol,received:f.parsedType}),d}return ao(o.data)}}wn.create=(o)=>{return new wn({typeName:g.ZodSymbol,...u(o)})};class jf extends e{_parse(o){if(this._getType(o)!==N.undefined){let f=this._getOrReturnCtx(o);return m(f,{code:t.invalid_type,expected:N.undefined,received:f.parsedType}),d}return ao(o.data)}}jf.create=(o)=>{return new jf({typeName:g.ZodUndefined,...u(o)})};class Nf extends e{_parse(o){if(this._getType(o)!==N.null){let f=this._getOrReturnCtx(o);return m(f,{code:t.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 m(T,{code:t.invalid_type,expected:N.never,received:T.parsedType}),d}}BT.create=(o)=>{return new BT({typeName:g.ZodNever,...u(o)})};class yn extends e{_parse(o){if(this._getType(o)!==N.undefined){let f=this._getOrReturnCtx(o);return m(f,{code:t.invalid_type,expected:N.void,received:f.parsedType}),d}return ao(o.data)}}yn.create=(o)=>{return new yn({typeName:g.ZodVoid,...u(o)})};class ET extends e{_parse(o){let{ctx:T,status:f}=this._processInputParams(o),n=this._def;if(T.parsedType!==N.array)return m(T,{code:t.invalid_type,expected:N.array,received:T.parsedType}),d;if(n.exactLength!==null){let A=T.data.length>n.exactLength.value,$=T.data.length<n.exactLength.value;if(A||$)m(T,{code:A?t.too_big:t.too_small,minimum:$?n.exactLength.value:void 0,maximum:A?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),f.dirty()}if(n.minLength!==null){if(T.data.length<n.minLength.value)m(T,{code:t.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),f.dirty()}if(n.maxLength!==null){if(T.data.length>n.maxLength.value)m(T,{code:t.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),f.dirty()}if(T.common.async)return Promise.all([...T.data].map((A,$)=>{return n.type._parseAsync(new YT(T,A,T.path,$))})).then((A)=>{return uo.mergeArray(f,A)});let S=[...T.data].map((A,$)=>{return n.type._parseSync(new YT(T,A,T.path,$))});return uo.mergeArray(f,S)}get element(){return this._def.type}min(o,T){return new ET({...this._def,minLength:{value:o,message:x.toString(T)}})}max(o,T){return new ET({...this._def,maxLength:{value:o,message:x.toString(T)}})}length(o,T){return new ET({...this._def,exactLength:{value:o,message:x.toString(T)}})}nonempty(o){return this.min(1,o)}}ET.create=(o,T)=>{return new ET({type:o,minLength:null,maxLength:null,exactLength:null,typeName:g.ZodArray,...u(T)})};function Bf(o){if(o instanceof zo){let T={};for(let f in o.shape){let n=o.shape[f];T[f]=GT.create(Bf(n))}return new zo({...o._def,shape:()=>T})}else if(o instanceof ET)return new ET({...o._def,type:Bf(o.element)});else if(o instanceof GT)return GT.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 zo 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 m(J,{code:t.invalid_type,expected:N.object,received:J.parsedType}),d}let{status:f,ctx:n}=this._processInputParams(o),{shape:S,keys:A}=this._getCached(),$=[];if(!(this._def.catchall instanceof BT&&this._def.unknownKeys==="strip")){for(let J in n.data)if(!A.includes(J))$.push(J)}let F=[];for(let J of A){let R=S[J],M=n.data[J];F.push({key:{status:"valid",value:J},value:R._parse(new YT(n,M,n.path,J)),alwaysSet:J in n.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:n.data[R]}});else if(J==="strict"){if($.length>0)m(n,{code:t.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=n.data[R];F.push({key:{status:"valid",value:R},value:J._parse(new YT(n,M,n.path,R)),alwaysSet:R in n.data})}}if(n.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 zo({...this._def,unknownKeys:"strict",...o!==void 0?{errorMap:(T,f)=>{var n,S,A,$;let F=(A=(S=(n=this._def).errorMap)===null||S===void 0?void 0:S.call(n,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 zo({...this._def,unknownKeys:"strip"})}passthrough(){return new zo({...this._def,unknownKeys:"passthrough"})}extend(o){return new zo({...this._def,shape:()=>({...this._def.shape(),...o})})}merge(o){return new zo({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 zo({...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 zo({...this._def,shape:()=>T})}omit(o){let T={};return Ao.objectKeys(this.shape).forEach((f)=>{if(!o[f])T[f]=this.shape[f]}),new zo({...this._def,shape:()=>T})}deepPartial(){return Bf(this)}partial(o){let T={};return Ao.objectKeys(this.shape).forEach((f)=>{let n=this.shape[f];if(o&&!o[f])T[f]=n;else T[f]=n.optional()}),new zo({...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 S=this.shape[f];while(S instanceof GT)S=S._def.innerType;T[f]=S}}),new zo({...this._def,shape:()=>T})}keyof(){return nJ(Ao.objectKeys(this.shape))}}zo.create=(o,T)=>{return new zo({shape:()=>o,unknownKeys:"strip",catchall:BT.create(),typeName:g.ZodObject,...u(T)})};zo.strictCreate=(o,T)=>{return new zo({shape:()=>o,unknownKeys:"strict",catchall:BT.create(),typeName:g.ZodObject,...u(T)})};zo.lazycreate=(o,T)=>{return new zo({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 n(S){for(let $ of S)if($.result.status==="valid")return $.result;for(let $ of S)if($.result.status==="dirty")return T.common.issues.push(...$.ctx.common.issues),$.result;let A=S.map(($)=>new JT($.ctx.common.issues));return m(T,{code:t.invalid_union,unionErrors:A}),d}if(T.common.async)return Promise.all(f.map(async(S)=>{let A={...T,common:{...T.common,issues:[]},parent:null};return{result:await S._parseAsync({data:T.data,path:T.path,parent:A}),ctx:A}})).then(n);else{let S=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"&&!S)S={result:R,ctx:J};if(J.common.issues.length)A.push(J.common.issues)}if(S)return T.common.issues.push(...S.ctx.common.issues),S.result;let $=A.map((F)=>new JT(F));return m(T,{code:t.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 jf)return[void 0];else if(o instanceof Nf)return[null];else if(o instanceof GT)return[void 0,...xT(o.unwrap())];else if(o instanceof qT)return[null,...xT(o.unwrap())];else if(o instanceof MS)return xT(o.unwrap());else if(o instanceof cf)return xT(o.unwrap());else if(o instanceof pf)return xT(o._def.innerType);else return[]};class RS extends e{_parse(o){let{ctx:T}=this._processInputParams(o);if(T.parsedType!==N.object)return m(T,{code:t.invalid_type,expected:N.object,received:T.parsedType}),d;let f=this.discriminator,n=T.data[f],S=this.optionsMap.get(n);if(!S)return m(T,{code:t.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[f]}),d;if(T.common.async)return S._parseAsync({data:T.data,path:T.path,parent:T});else return S._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 n=new Map;for(let S of T){let A=xT(S.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(n.has($))throw new Error(`Discriminator property ${String(o)} has duplicate value ${String($)}`);n.set($,S)}}return new RS({typeName:g.ZodDiscriminatedUnion,discriminator:o,options:T,optionsMap:n,...u(f)})}}function mA(o,T){let f=vT(o),n=vT(T);if(o===T)return{valid:!0,data:o};else if(f===N.object&&n===N.object){let S=Ao.objectKeys(T),A=Ao.objectKeys(o).filter((F)=>S.indexOf(F)!==-1),$={...o,...T};for(let F of A){let J=mA(o[F],T[F]);if(!J.valid)return{valid:!1};$[F]=J.data}return{valid:!0,data:$}}else if(f===N.array&&n===N.array){if(o.length!==T.length)return{valid:!1};let S=[];for(let A=0;A<o.length;A++){let $=o[A],F=T[A],J=mA($,F);if(!J.valid)return{valid:!1};S.push(J.data)}return{valid:!0,data:S}}else if(f===N.date&&n===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),n=(S,A)=>{if(LA(S)||LA(A))return d;let $=mA(S.value,A.value);if(!$.valid)return m(f,{code:t.invalid_intersection_types}),d;if(CA(S)||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(([S,A])=>n(S,A));else return n(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 m(f,{code:t.invalid_type,expected:N.array,received:f.parsedType}),d;if(f.data.length<this._def.items.length)return m(f,{code:t.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)m(f,{code:t.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),T.dirty();let S=[...f.data].map((A,$)=>{let F=this._def.items[$]||this._def.rest;if(!F)return null;return F._parse(new YT(f,A,f.path,$))}).filter((A)=>!!A);if(f.common.async)return Promise.all(S).then((A)=>{return uo.mergeArray(T,A)});else return uo.mergeArray(T,S)}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 Xn 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 m(f,{code:t.invalid_type,expected:N.object,received:f.parsedType}),d;let n=[],S=this._def.keyType,A=this._def.valueType;for(let $ in f.data)n.push({key:S._parse(new YT(f,$,f.path,$)),value:A._parse(new YT(f,f.data[$],f.path,$)),alwaysSet:$ in f.data});if(f.common.async)return uo.mergeObjectAsync(T,n);else return uo.mergeObjectSync(T,n)}get element(){return this._def.valueType}static create(o,T,f){if(T instanceof e)return new Xn({keyType:o,valueType:T,typeName:g.ZodRecord,...u(f)});return new Xn({keyType:KT.create(),valueType:o,typeName:g.ZodRecord,...u(T)})}}class Hn 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 m(f,{code:t.invalid_type,expected:N.map,received:f.parsedType}),d;let n=this._def.keyType,S=this._def.valueType,A=[...f.data.entries()].map(([$,F],J)=>{return{key:n._parse(new YT(f,$,f.path,[J,"key"])),value:S._parse(new YT(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:$}}}}Hn.create=(o,T,f)=>{return new Hn({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 m(f,{code:t.invalid_type,expected:N.set,received:f.parsedType}),d;let n=this._def;if(n.minSize!==null){if(f.data.size<n.minSize.value)m(f,{code:t.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),T.dirty()}if(n.maxSize!==null){if(f.data.size>n.maxSize.value)m(f,{code:t.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),T.dirty()}let S=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)=>S._parse(new YT(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 m(T,{code:t.invalid_type,expected:N.function,received:T.parsedType}),d;function f($,F){return FS({data:$,path:T.path,errorMaps:[T.common.contextualErrorMap,T.schemaErrorMap,$S(),mf].filter((J)=>!!J),issueData:{code:t.invalid_arguments,argumentsError:F}})}function n($,F){return FS({data:$,path:T.path,errorMaps:[T.common.contextualErrorMap,T.schemaErrorMap,$S(),mf].filter((J)=>!!J),issueData:{code:t.invalid_return_type,returnTypeError:F}})}let S={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,S).catch((w)=>{throw J.addIssue(f(F,w)),J}),M=await Reflect.apply(A,this,R);return await $._def.returns._def.type.parseAsync(M,S).catch((w)=>{throw J.addIssue(n(M,w)),J})})}else{let $=this;return ao(function(...F){let J=$._def.args.safeParse(F,S);if(!J.success)throw new JT([f(F,J.error)]);let R=Reflect.apply(A,this,J.data),M=$._def.returns.safeParse(R,S);if(!M.success)throw new JT([n(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 m(T,{received:T.data,code:t.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 nJ(o,T){return new lT({values:o,typeName:g.ZodEnum,...u(T)})}class lT extends e{constructor(){super(...arguments);On.set(this,void 0)}_parse(o){if(typeof o.data!=="string"){let T=this._getOrReturnCtx(o),f=this._def.values;return m(T,{expected:Ao.joinValues(f),received:T.parsedType,code:t.invalid_type}),d}if(!JS(this,On,"f"))aF(this,On,new Set(this._def.values),"f");if(!JS(this,On,"f").has(o.data)){let T=this._getOrReturnCtx(o),f=this._def.values;return m(T,{received:T.data,code:t.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})}}On=new WeakMap;lT.create=nJ;class qf extends e{constructor(){super(...arguments);kn.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 n=Ao.objectValues(T);return m(f,{expected:Ao.joinValues(n),received:f.parsedType,code:t.invalid_type}),d}if(!JS(this,kn,"f"))aF(this,kn,new Set(Ao.getValidEnumValues(this._def.values)),"f");if(!JS(this,kn,"f").has(o.data)){let n=Ao.objectValues(T);return m(f,{received:f.data,code:t.invalid_enum_value,options:n}),d}return ao(o.data)}get enum(){return this._def.values}}kn=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 m(T,{code:t.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((n)=>{return this._def.type.parseAsync(n,{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),n=this._def.effect||null,S={addIssue:(A)=>{if(m(f,A),A.fatal)T.abort();else T.dirty()},get path(){return f.path}};if(S.addIssue=S.addIssue.bind(S),n.type==="preprocess"){let A=n.transform(f.data,S);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(n.type==="refinement"){let A=($)=>{let F=n.refinement($,S);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(n.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 $=n.transform(A.value,S);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(n.transform(A.value,S)).then(($)=>({status:T.value,value:$}))});Ao.assertNever(n)}}_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 GT 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}}GT.create=(o,T)=>{return new GT({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 pf extends e{_parse(o){let{ctx:T}=this._processInputParams(o),f={...T,common:{...T.common,issues:[]}},n=this._def.innerType._parse({data:f.data,path:f.path,parent:{...f}});if(_n(n))return n.then((S)=>{return{status:"valid",value:S.status==="valid"?S.value:this._def.catchValue({get error(){return new JT(f.common.issues)},input:f.data})}});else return{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new JT(f.common.issues)},input:f.data})}}removeCatch(){return this._def.innerType}}pf.create=(o,T)=>{return new pf({innerType:o,typeName:g.ZodCatch,catchValue:typeof T.catch==="function"?T.catch:()=>T.catch,...u(T)})};class Kn extends e{_parse(o){if(this._getType(o)!==N.nan){let f=this._getOrReturnCtx(o);return m(f,{code:t.invalid_type,expected:N.nan,received:f.parsedType}),d}return{status:"valid",value:o.data}}}Kn.create=(o)=>{return new Kn({typeName:g.ZodNaN,...u(o)})};var OW=Symbol("zod_brand");class MS 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 En extends e{_parse(o){let{status:T,ctx:f}=this._processInputParams(o);if(f.common.async)return(async()=>{let S=await this._def.in._parseAsync({data:f.data,path:f.path,parent:f});if(S.status==="aborted")return d;if(S.status==="dirty")return T.dirty(),Lf(S.value);else return this._def.out._parseAsync({data:S.value,path:f.path,parent:f})})();else{let n=this._def.in._parseSync({data:f.data,path:f.path,parent:f});if(n.status==="aborted")return d;if(n.status==="dirty")return T.dirty(),{status:"dirty",value:n.value};else return this._def.out._parseSync({data:n.value,path:f.path,parent:f})}}static create(o,T){return new En({in:o,out:T,typeName:g.ZodPipeline})}}class cf extends e{_parse(o){let T=this._def.innerType._parse(o),f=(n)=>{if(Ff(n))n.value=Object.freeze(n.value);return n};return _n(T)?T.then((n)=>f(n)):f(T)}unwrap(){return this._def.innerType}}cf.create=(o,T)=>{return new cf({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 SJ(o,T={},f){if(o)return Rf.create().superRefine((n,S)=>{var A,$;let F=o(n);if(F instanceof Promise)return F.then((J)=>{var R,M;if(!J){let _=uF(T,n),w=(M=(R=_.fatal)!==null&&R!==void 0?R:f)!==null&&M!==void 0?M:!0;S.addIssue({code:"custom",..._,fatal:w})}});if(!F){let J=uF(T,n),R=($=(A=J.fatal)!==null&&A!==void 0?A:f)!==null&&$!==void 0?$:!0;S.addIssue({code:"custom",...J,fatal:R})}return});return Rf.create()}var kW={object:zo.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}`})=>SJ((f)=>f instanceof o,T),AJ=KT.create,$J=gT.create,wW=Kn.create,yW=dT.create,FJ=If.create,XW=Jf.create,HW=wn.create,KW=jf.create,EW=Nf.create,GW=Rf.create,YW=iT.create,tW=BT.create,zW=yn.create,QW=ET.create,DW=zo.create,UW=zo.strictCreate,VW=hf.create,BW=RS.create,LW=bf.create,CW=LT.create,mW=Xn.create,IW=Hn.create,jW=Mf.create,NW=Cf.create,hW=xf.create,bW=vf.create,xW=lT.create,vW=qf.create,qW=Wf.create,eF=_T.create,rW=GT.create,pW=qT.create,cW=_T.createWithPreprocess,ZW=En.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)=>If.create({...o,coerce:!0}),bigint:(o)=>dT.create({...o,coerce:!0}),date:(o)=>Jf.create({...o,coerce:!0})},lW=d,Go=Object.freeze({__proto__:null,defaultErrorMap:mf,setErrorMap:cM,getErrorMap:$S,makeIssue:FS,EMPTY_PATH:ZM,addIssueToContext:m,ParseStatus:uo,INVALID:d,DIRTY:Lf,OK:ao,isAborted:LA,isDirty:CA,isValid:Ff,isAsync:_n,get util(){return Ao},get objectUtil(){return BA},ZodParsedType:N,getParsedType:vT,ZodType:e,datetimeRegex:fJ,ZodString:KT,ZodNumber:gT,ZodBigInt:dT,ZodBoolean:If,ZodDate:Jf,ZodSymbol:wn,ZodUndefined:jf,ZodNull:Nf,ZodAny:Rf,ZodUnknown:iT,ZodNever:BT,ZodVoid:yn,ZodArray:ET,ZodObject:zo,ZodUnion:hf,ZodDiscriminatedUnion:RS,ZodIntersection:bf,ZodTuple:LT,ZodRecord:Xn,ZodMap:Hn,ZodSet:Mf,ZodFunction:Cf,ZodLazy:xf,ZodLiteral:vf,ZodEnum:lT,ZodNativeEnum:qf,ZodPromise:Wf,ZodEffects:_T,ZodTransformer:_T,ZodOptional:GT,ZodNullable:qT,ZodDefault:rf,ZodCatch:pf,ZodNaN:Kn,BRAND:OW,ZodBranded:MS,ZodPipeline:En,ZodReadonly:cf,custom:SJ,Schema:e,ZodSchema:e,late:kW,get ZodFirstPartyTypeKind(){return g},coerce:dW,any:GW,array:QW,bigint:yW,boolean:FJ,date:XW,discriminatedUnion:BW,effect:eF,enum:xW,function:NW,instanceof:_W,intersection:LW,lazy:hW,literal:bW,map:IW,nan:wW,nativeEnum:vW,never:tW,null:EW,nullable:pW,number:$J,object:DW,oboolean:gW,onumber:iW,optional:rW,ostring:PW,pipeline:ZW,preprocess:cW,promise:qW,record:mW,set:jW,strictObject:UW,string:AJ,symbol:HW,transformer:eF,tuple:CW,undefined:KW,union:VW,unknown:YW,void:zW,NEVER:lW,ZodIssueCode:t,quotelessJson:pM,ZodError:JT});var uW="__vite_start_time"in globalThis,eW=typeof window!=="undefined",n6="vitest"in globalThis,tT=dF({isServer:!uW&&!eW,server:{CI:Go.string().transform((o)=>!0).optional(),POSTGRES_USER:Go.string(),POSTGRES_PASSWORD:Go.string(),POSTGRES_DATABASE:Go.string(),POSTGRES_HOST:Go.string(),POSTGRES_PORT:Go.string().transform((o)=>Number.parseInt(o,10)),BACKEND_PORT:Go.string().transform((o)=>Number.parseInt(o,10)),RUN_WORKERS_FROM_SOURCE:Go.union([Go.literal("true"),Go.literal("false")]).optional().transform((o)=>o==="true"),FRONTEND_PORT:Go.string().transform((o)=>Number.parseInt(o,10)),FRONTEND_ORIGINS:Go.string().transform((o)=>JSON.parse(o)).pipe(Go.array(Go.string())),OPENAI_API_KEY:Go.string().optional()},clientPrefix:"VITE_",client:{VITE_BACKEND_ORIGIN:Go.string(),VITE_USE_SELF_SIGNED_CERTIFICATE:Go.union([Go.literal("true"),Go.literal("false")]).optional().transform((o)=>o==="true")},runtimeEnv:import.meta.env,emptyStringAsUndefined:!0});var RJ=IA(import.meta.dirname,"../dev"),MJ=tT.VITE_USE_SELF_SIGNED_CERTIFICATE?{cert:JJ(IA(RJ,"./cert.pem"),"utf-8"),key:JJ(IA(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 jA{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 zT=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:n,foreignColumns:S}=o();return{name:f,columns:n,foreignTable:S[0].table,foreignColumns:S}},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(),n=T.map(($)=>$.name),S=f.map(($)=>$.name),A=[this.table[zT],...n,f[0].table[zT],...S];return o??`${A.join("_")}_fk`}}function WS(o,...T){return o(...T)}function OJ(o,T){return`${o[zT]}_${T.join("_")}_unique`}function kJ(o,T,f){for(let n=T;n<o.length;n++){let S=o[n];if(S==="\\"){n++;continue}if(S==='"')return[o.slice(T,n).replace(/\\/g,""),n+1];if(f)continue;if(S===","||S==="}")return[o.slice(T,n).replace(/\\/g,""),n]}return[o.slice(T).replace(/\\/g,""),o.length]}function _J(o,T=0){let f=[],n=T,S=!1;while(n<o.length){let A=o[n];if(A===","){if(S||n===T)f.push("");S=!0,n++;continue}if(S=!1,A==="\\"){n+=2;continue}if(A==='"'){let[J,R]=kJ(o,n+1,!0);f.push(J),n=R;continue}if(A==="}")return[f,n+1];if(A==="{"){let[J,R]=_J(o,n+1);f.push(J),n=R;continue}let[$,F]=kJ(o,n,!1);f.push($),n=F}return[f,n]}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 jA{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:n})=>{return WS((S,A)=>{let $=new NA(()=>{let F=S();return{columns:[o],foreignColumns:[F]}});if(A.onUpdate)$.onUpdate(A.onUpdate);if(A.onDelete)$.onDelete(A.onDelete);return $.build(T)},f,n)})}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 Gn{static[O]="IndexedColumn";constructor(o,T,f,n){this.name=o,this.keyAsName=T,this.type=f,this.indexConfig=n}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,n){super(o,T);this.baseColumn=f,this.range=n,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((n)=>n===null?null:H(this.baseColumn,bA)?this.baseColumn.mapToDriverValue(n,!0):this.baseColumn.mapToDriverValue(n));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 EJ(o,this.config)}}class EJ 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 OS(o,T){return sW(o,T,void 0)}function sW(o,T,f){let n=Object.assign((S)=>new KJ(S??"",n),{enumName:o,enumValues:T,schema:f,[xA]:!0});return n}class bo{static[O]="Subquery";constructor(o,T,f,n=!1){this._={brand:"Subquery",sql:o,selectedFields:T,alias:f,isWith:n}}}class Yn extends bo{static[O]="WithSubquery"}var GJ="0.40.0";var vA,qA,wo={startActiveSpan(o,T){if(!vA)return T();if(!qA)qA=vA.trace.getTracer("drizzle-orm",GJ);return WS((f,n)=>n.startActiveSpan(o,(S)=>{try{return T(S)}catch(A){throw S.setStatus({code:f.SpanStatusCode.ERROR,message:A instanceof Error?A.message:"Unknown error"}),A}finally{S.end()}}),vA,qA)}};var Ho=Symbol.for("drizzle:ViewBaseConfig");var kS=Symbol.for("drizzle:Schema"),_S=Symbol.for("drizzle:Columns"),YJ=Symbol.for("drizzle:ExtraConfigColumns"),rA=Symbol.for("drizzle:OriginalName"),pA=Symbol.for("drizzle:BaseName"),tn=Symbol.for("drizzle:IsAlias"),tJ=Symbol.for("drizzle:ExtraConfigBuilder"),aW=Symbol.for("drizzle:IsDrizzleTable");class I{static[O]="Table";static Symbol={Name:zT,Schema:kS,OriginalName:rA,Columns:_S,ExtraConfigColumns:YJ,BaseName:pA,IsAlias:tn,ExtraConfigBuilder:tJ};[zT];[rA];[kS];[_S];[YJ];[pA];[tn]=!1;[aW]=!0;[tJ]=void 0;constructor(o,T,f){this[zT]=this[rA]=o,this[kS]=T,this[pA]=f}}function qo(o){return o[zT]}function Of(o){return`${o[kS]??"public"}.${o[zT]}`}function cA(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 j([this])}}class j{constructor(o){this.queryChunks=o}static[O]="SQL";decoder=QJ;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:n,escapeName:S,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,wS))return{sql:S(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,j))return this.buildQueryFromSourceParams(R.queryChunks,{...f,inlineParams:F||R.shouldInlineParams});if(H(R,I)){let M=R[I.Symbol.Schema],_=R[I.Symbol.Name];return{sql:M===void 0||R[tn]?S(_):S(M)+"."+S(_),params:[]}}if(H(R,_o)){let M=n.getColumnCasing(R);if(T.invokeSource==="indexes")return{sql:S(M),params:[]};let _=R.table[I.Symbol.Schema];return{sql:R.table[tn]||_===void 0?S(R.table[I.Symbol.Name])+"."+S(M):S(_)+"."+S(R.table[I.Symbol.Name])+"."+S(M),params:[]}}if(H(R,ST)){let M=R[Ho].schema,_=R[Ho].name;return{sql:M===void 0||R[Ho].isAlias?S(_):S(M)+"."+S(_),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,j))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,j.Aliased)&&R.fieldAlias!==void 0)return{sql:S(R.fieldAlias),params:[]};if(H(R,bo)){if(R._.isWith)return{sql:S(R._.alias),params:[]};return this.buildQueryFromSourceParams([new xo("("),R._.sql,new xo(") "),new wS(R._.alias)],f)}if(HJ(R)){if(R.schema)return{sql:S(R.schema)+"."+S(R.enumName),params:[]};return{sql:S(R.enumName),params:[]}}if(cA(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 j.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 wS{constructor(o){this.value=o}static[O]="Name";brand;getSQL(){return new j([this])}}function zJ(o){return typeof o==="object"&&o!==null&&"mapToDriverValue"in o&&typeof o.mapToDriverValue==="function"}var QJ={mapFromDriverValue:(o)=>o},DJ={mapToDriverValue:(o)=>o},e6={...QJ,...DJ};class RT{constructor(o,T=DJ){this.value=o,this.encoder=T}static[O]="Param";brand;getSQL(){return new j([this])}}function k(o,...T){let f=[];if(T.length>0||o.length>0&&o[0]!=="")f.push(new xo(o[0]));for(let[n,S]of T.entries())f.push(S,new xo(o[n+1]));return new j(f)}((o)=>{function T(){return new j([])}o.empty=T;function f(J){return new j(J)}o.fromList=f;function n(J){return new j([new xo(J)])}o.raw=n;function S(J,R){let M=[];for(let[_,w]of J.entries()){if(_>0&&R!==void 0)M.push(R);M.push(w)}return new j(M)}o.join=S;function A(J){return new wS(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,n){this.sql=f,this.fieldAlias=n}static[O]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new T(this.sql,this.fieldAlias)}}o.Aliased=T})(j||(j={}));class uT{constructor(o){this.name=o}static[O]="Placeholder";getSQL(){return new j([this])}}function ZA(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 ST{static[O]="View";[Ho];[TO]=!0;constructor({name:o,schema:T,selectedFields:f,query:n}){this[Ho]={name:o,originalName:o,schema:T,selectedFields:f,query:n,isExisting:!n,isAlias:!1}}getSQL(){return new j([this])}}_o.prototype.getSQL=function(){return new j([this])};I.prototype.getSQL=function(){return new j([this])};bo.prototype.getSQL=function(){return new j([this])};class Zf{constructor(o){this.table=o}static[O]="ColumnAliasProxyHandler";get(o,T){if(T==="table")return this.table;return o[T]}}class zn{constructor(o,T){this.alias=o,this.replaceOriginalName=T}static[O]="TableAliasProxyHandler";get(o,T){if(T===I.Symbol.IsAlias)return!0;if(T===I.Symbol.Name)return this.alias;if(this.replaceOriginalName&&T===I.Symbol.OriginalName)return this.alias;if(T===Ho)return{...o[Ho],name:this.alias,isAlias:!0};if(T===I.Symbol.Columns){let n=o[I.Symbol.Columns];if(!n)return n;let S={};return Object.keys(n).map((A)=>{S[A]=new Proxy(n[A],new Zf(new Proxy(o,this)))}),S}let f=o[T];if(H(f,_o))return new Proxy(f,new Zf(new Proxy(o,this)));return f}}function yS(o,T){return new Proxy(o,new zn(T,!1))}function CT(o,T){return new Proxy(o,new Zf(new Proxy(o.table,new zn(T,!1))))}function PA(o,T){return new j.Aliased(Qn(o.sql,T),o.fieldAlias)}function Qn(o,T){return k.join(o.queryChunks.map((f)=>{if(H(f,_o))return CT(f,T);if(H(f,j))return Qn(f,T);if(H(f,j.Aliased))return PA(f,T);return f}))}class XS extends Error{static[O]="DrizzleError";constructor({message:o,cause:T}){super(o);this.name="DrizzleError",this.cause=T}}class iA extends XS{static[O]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}function AT(o,T){if(zJ(T)&&!cA(o)&&!H(o,RT)&&!H(o,uT)&&!H(o,_o)&&!H(o,I)&&!H(o,ST))return new RT(o,T);return o}var HS=(o,T)=>{return k`${o} = ${AT(T,o)}`},UJ=(o,T)=>{return k`${o} <> ${AT(T,o)}`};function Dn(...o){let T=o.filter((f)=>f!==void 0);if(T.length===0)return;if(T.length===1)return new j(T);return new j([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 j(T);return new j([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)}`},mJ=(o,T)=>{return k`${o} < ${AT(T,o)}`},IJ=(o,T)=>{return k`${o} <= ${AT(T,o)}`};function jJ(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 pJ(o,T){return k`${o} like ${T}`}function cJ(o,T){return k`${o} not like ${T}`}function ZJ(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((S)=>{try{return JSON.stringify(S)}catch{return String(S)}}),n=f.length?` -- params: [${f.join(", ")}]`:"";this.writer.write(`Query: ${o}${n}`)}}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 n={},S=o.reduce((A,{path:$,field:F},J)=>{let R;if(H(F,_o))R=F;else if(H(F,j))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],D=M[w]=X===null?null:R.mapFromDriverValue(X);if(f&&H(F,_o)&&$.length===2){let K=$[0];if(!(K in n))n[K]=D===null?qo(F.table):!1;else if(typeof n[K]==="string"&&n[K]!==qo(F.table))n[K]=!1}}return A},{});if(f&&Object.keys(n).length>0){for(let[A,$]of Object.entries(n))if(typeof $==="string"&&!f[$])S[A]=null}return S}function wT(o,T){return Object.entries(o).reduce((f,[n,S])=>{if(typeof n!=="string")return f;let A=T?[...T,n]:[n];if(H(S,_o)||H(S,j)||H(S,j.Aliased))f.push({path:A,field:S});else if(H(S,I))f.push(...wT(S[I.Symbol.Columns],A));else f.push(...wT(S,A));return f},[])}function Un(o,T){let f=Object.keys(o),n=Object.keys(T);if(f.length!==n.length)return!1;for(let[S,A]of f.entries())if(A!==n[S])return!1;return!0}function KS(o,T){let f=Object.entries(T).filter(([,n])=>n!==void 0).map(([n,S])=>{if(H(S,j)||H(S,_o))return[n,S];else return[n,new RT(S,o[I.Symbol.Columns][n])]});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 n of Object.getOwnPropertyNames(f.prototype)){if(n==="constructor")continue;Object.defineProperty(o.prototype,n,Object.getOwnPropertyDescriptor(f.prototype,n)||Object.create(null))}}function eJ(o){return o[I.Symbol.Columns]}function rT(o){return H(o,bo)?o._.alias:H(o,ST)?o[Ho].name:H(o,j)?void 0:o[I.Symbol.IsAlias]?o[I.Symbol.Name]:o[I.Symbol.BaseName]}function So(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 nR(o,T){let{name:f,config:n}=So(o,T);if(n.mode==="number")return new aJ(f);return new TR(f)}class SR 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:n}=So(o,T);if(n.mode==="number")return new SR(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 Vn(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:n}=So(o,T);return new WR(f,n)}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:n,config:S}=So(T,f);return new XR(n,S,o)}}class pT extends b{static[O]="PgDateColumnBaseBuilder";defaultNow(){return this.default(k`now()`)}}class ER extends pT{static[O]="PgDateBuilder";constructor(o){super(o,"date","PgDate")}build(o){return new ES(o,this.config)}}class ES extends V{static[O]="PgDate";getSQLType(){return"date"}mapFromDriverValue(o){return new Date(o)}mapToDriverValue(o){return o.toISOString()}}class GR extends pT{static[O]="PgDateStringBuilder";constructor(o){super(o,"string","PgDateString")}build(o){return new GS(o,this.config)}}class GS extends V{static[O]="PgDateString";getSQLType(){return"date"}}function YR(o,T){let{name:f,config:n}=So(o,T);if(n?.mode==="date")return new ER(f);return new GR(f)}class tR extends b{static[O]="PgDoublePrecisionBuilder";constructor(o){super(o,"number","PgDoublePrecision")}build(o){return new zR(o,this.config)}}class zR extends V{static[O]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(o){if(typeof o==="string")return Number.parseFloat(o);return o}}function QR(o){return new tR(o??"")}class DR extends b{static[O]="PgInetBuilder";constructor(o){super(o,"string","PgInet")}build(o){return new UR(o,this.config)}}class UR extends V{static[O]="PgInet";getSQLType(){return"inet"}}function VR(o){return new DR(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 YS(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 mR(o,this.config)}}class mR 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 IR(o,T={}){let{name:f,config:n}=So(o,T);return new CR(f,n)}class jR extends b{static[O]="PgJsonBuilder";constructor(o){super(o,"json","PgJson")}build(o){return new tS(o,this.config)}}class tS 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 jR(o??"")}class hR extends b{static[O]="PgJsonbBuilder";constructor(o){super(o,"json","PgJsonb")}build(o){return new zS(o,this.config)}}class zS 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,n]=o.slice(1,-1).split(",");return[Number.parseFloat(T),Number.parseFloat(f),Number.parseFloat(n)]}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,n]=o.slice(1,-1).split(",");return{a:Number.parseFloat(T),b:Number.parseFloat(f),c:Number.parseFloat(n)}}mapToDriverValue(o){return`{${o.a},${o.b},${o.c}}`}}function pR(o,T){let{name:f,config:n}=So(o,T);if(!n?.mode||n.mode==="tuple")return new xR(f);return new qR(f)}class cR extends b{static[O]="PgMacaddrBuilder";constructor(o){super(o,"string","PgMacaddr")}build(o){return new ZR(o,this.config)}}class ZR extends V{static[O]="PgMacaddr";getSQLType(){return"macaddr"}}function PR(o){return new cR(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 QS(o,this.config)}}class QS 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:n}=So(o,T);return new lR(f,n?.precision,n?.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:n}=So(o,T);if(!n?.mode||n.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),n=new DataView(f);for(let S=0;S<8;S++)n.setUint8(S,o[T+S]);return n.getFloat64(0,!0)}function lA(o){let T=fO(o),f=0,n=T[f];f+=1;let S=new DataView(T.buffer),A=S.getUint32(f,n===1);f+=4;let $;if(A&536870912)$=S.getUint32(f,n===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 n0 extends b{static[O]="PgGeometryBuilder";constructor(o){super(o,"array","PgGeometry")}build(o){return new S0(o,this.config)}}class S0 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:n}=So(o,T);if(!n?.mode||n.mode==="tuple")return new n0(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 E0 extends b{static[O]="PgTextBuilder";constructor(o,T){super(o,"string","PgText");this.config.enumValues=T.enum}build(o){return new G0(o,this.config)}}class G0 extends V{static[O]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function Y0(o,T={}){let{name:f,config:n}=So(o,T);return new E0(f,n)}class t0 extends pT{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 DS(o,this.config)}}class DS 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 z0(o,T={}){let{name:f,config:n}=So(o,T);return new t0(f,n.withTimezone??!1,n.precision)}class Q0 extends pT{static[O]="PgTimestampBuilder";constructor(o,T,f){super(o,"date","PgTimestamp");this.config.withTimezone=T,this.config.precision=f}build(o){return new US(o,this.config)}}class US 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 D0 extends pT{static[O]="PgTimestampStringBuilder";constructor(o,T,f){super(o,"string","PgTimestampString");this.config.withTimezone=T,this.config.precision=f}build(o){return new VS(o,this.config)}}class VS 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 QT(o,T={}){let{name:f,config:n}=So(o,T);if(n?.mode==="string")return new D0(f,n.withTimezone??!1,n.precision);return new Q0(f,n?.withTimezone??!1,n?.precision)}class U0 extends b{static[O]="PgUUIDBuilder";constructor(o){super(o,"string","PgUUID")}defaultRandom(){return this.default(k`gen_random_uuid()`)}build(o){return new BS(o,this.config)}}class BS extends V{static[O]="PgUUID";getSQLType(){return"uuid"}}function MT(o){return new U0(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 po(o,T={}){let{name:f,config:n}=So(o,T);return new V0(f,n)}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 m0(o,T){let{name:f,config:n}=So(o,T);return new L0(f,n)}class I0 extends b{static[O]="PgHalfVectorBuilder";constructor(o,T){super(o,"array","PgHalfVector");this.config.dimensions=T.dimensions}build(o){return new j0(o,this.config)}}class j0 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:n}=So(o,T);return new I0(f,n)}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:n}=So(o,T);return new h0(f,n)}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:n}=So(o,T);return new v0(f,n)}function p0(){return{bigint:nR,bigserial:JR,boolean:Vn,char:kR,cidr:yR,customType:KR,date:YR,doublePrecision:QR,inet:VR,integer:YS,interval:IR,json:NR,jsonb:bR,line:pR,macaddr:PR,macaddr8:dR,numeric:uR,point:T0,geometry:F0,real:M0,serial:k0,smallint:y0,smallserial:K0,text:Y0,time:z0,timestamp:QT,uuid:MT,varchar:po,bit:m0,halfvec:N0,sparsevec:x0,vector:r0}}var uA=Symbol.for("drizzle:PgInlineForeignKeys"),c0=Symbol.for("drizzle:EnableRLS");class co extends I{static[O]="PgTable";static Symbol=Object.assign({},I.Symbol,{InlineForeignKeys:uA,EnableRLS:c0});[uA]=[];[c0]=!1;[I.Symbol.ExtraConfigBuilder]=void 0;[I.Symbol.ExtraConfigColumns]={}}function nO(o,T,f,n,S=o){let A=new co(o,n,S),$=typeof T==="function"?T(p0()):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[I.Symbol.Columns]=F,R[I.Symbol.ExtraConfigColumns]=J,f)R[co.Symbol.ExtraConfigBuilder]=f;return Object.assign(R,{enableRLS:()=>{return R[co.Symbol.EnableRLS]=!0,R}})}var sT=(o,T,f)=>{return nO(o,T,f,void 0)};function Z0(...o){if(o[0].columns)return new Bn(o[0].columns,o[0].name);return new Bn(o)}class Bn{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[co.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[I.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,n){super(o,T,f?.relationName);this.config=f,this.isNullable=n}static[O]="One";withFieldName(o){let T=new aT(this.sourceTable,this.referencedTable,this.config,this.isNullable);return T.fieldName=o,T}}class Ln extends eA{constructor(o,T,f){super(o,T,f?.relationName);this.config=f}static[O]="Many";withFieldName(o){let T=new Ln(this.sourceTable,this.referencedTable,this.config);return T.fieldName=o,T}}function g0(){return{and:Dn,between:qJ,eq:HS,exists:xJ,gt:LJ,gte:CJ,ilike:ZJ,inArray:jJ,isNull:hJ,isNotNull:bJ,like:pJ,lt:mJ,lte:IJ,ne:UJ,not:BJ,notBetween:rJ,notExists:vJ,notLike:cJ,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,I))o=o.default;let f={},n={},S={};for(let[A,$]of Object.entries(o))if(H($,I)){let F=Of($),J=n[F];f[F]=A,S[A]={tsName:A,dbName:$[I.Symbol.Name],schema:$[I.Symbol.Schema],columns:$[I.Symbol.Columns],relations:J?.relations??{},primaryKey:J?.primaryKey??[]};for(let M of Object.values($[I.Symbol.Columns]))if(M.primary)S[A].primaryKey.push(M);let R=$[I.Symbol.ExtraConfigBuilder]?.($[I.Symbol.ExtraConfigColumns]);if(R){for(let M of Object.values(R))if(H(M,Bn))S[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=S[J];if(X.relations[_]=w,M)X.primaryKey.push(...M)}else{if(!(F in n))n[F]={relations:{},primaryKey:M};n[F].relations[_]=w}}return{tables:S,tableNamesMap:f}}function SO(o){return function T(f,n){return new aT(o,f,n,n?.fields.reduce((S,A)=>S&&A.notNull,!0)??!1)}}function AO(o){return function T(f,n){return new Ln(o,f,n)}}function u0(o,T,f){if(H(f,aT)&&f.config)return{fields:f.config.fields,references:f.config.references};let n=T[Of(f.referencedTable)];if(!n)throw new Error(`Table "${f.referencedTable[I.Symbol.Name]}" not found in schema`);let S=o[n];if(!S)throw new Error(`Table "${n}" not found in schema`);let A=f.sourceTable,$=T[Of(A)];if(!$)throw new Error(`Table "${A[I.Symbol.Name]}" not found in schema`);let F=[];for(let J of Object.values(S.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 "${n}"`):new Error(`There are multiple relations between "${n}" and "${f.sourceTable[I.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:SO(o),many:AO(o)}}function LS(o,T,f,n,S=(A)=>A){let A={};for(let[$,F]of n.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&&LS(o,o[F.relationTableTsKey],M,F.selection,S):M.map((_)=>LS(o,o[F.relationTableTsKey],_,F.selection,S))}else{let J=S(f[$]),R=F.field,M;if(H(R,_o))M=R;else if(H(R,j))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 CS=new Map,sA=new Map,aA=Symbol("OriginError"),Pf={};class yT extends Promise{constructor(o,T,f,n,S={}){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=n,this.options=S,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 n=new Promise((S,A)=>{this.cursorFn=($)=>{return S({value:$,done:!1}),new Promise((F)=>f=F)},this.resolve=()=>(this.active=!1,S({done:!0})),this.reject=($)=>(this.active=!1,A($))});return this.execute(),n},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(CS.has(o))return CS.get(o);let T=Error.stackTraceLimit;return Error.stackTraceLimit=4,CS.set(o,new Error),Error.stackTraceLimit=T,CS.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:n,port:S}=f||T,A=Object.assign(new Error("write "+o+" "+(T.path||n+":"+S)),{code:o,errno:o,address:T.path||n},T.path?{}:{port:S});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 jS{then(){o$()}catch(){o$()}finally(){o$()}}class jn extends jS{constructor(o){super();this.value=bS(o)}}class mT extends jS{constructor(o,T,f){super();this.value=o,this.type=T,this.array=f}}class NS extends jS{constructor(o,T){super();this.first=o,this.rest=T}build(o,T,f,n){let S=JO.map(([A,$])=>({fn:$,i:o.search(A)})).sort((A,$)=>A.i-$.i).pop();return S.i===-1?A$(this.first,n):S.fn(this.first,this.rest,T,f,n)}}function hS(o,T,f,n){let S=o instanceof mT?o.value:o;if(S===void 0){if(o instanceof mT?o.value=n.transform.undefined:S=o=n.transform.undefined,S===void 0)throw Bo.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return"$"+f.push(o instanceof mT?(T.push(o.value),o.array?o.array[o.type||IS(o.value)]||o.type||A1(o.value):o.type):(T.push(o),IS(o)))}var n1=F1(FO);function n$(o,T,f,n,S,A){for(let $=1;$<o.strings.length;$++)T+=S$(T,f,n,S,A)+o.strings[$],f=o.args[$];return T}function S$(o,T,f,n,S){return T instanceof NS?T.build(o,f,n,S):T instanceof yT?f$(T,f,n,S):T instanceof jn?T.value:T&&T[0]instanceof yT?T.reduce((A,$)=>A+" "+f$($,f,n,S),""):hS(T,f,n,S)}function f$(o,T,f,n){return o.fragment=!0,n$(o,o.strings[0],o.args[0],T,f,n)}function S1(o,T,f,n,S){return o.map((A)=>"("+n.map(($)=>S$("values",A[$],T,f,S)).join(",")+")").join(",")}function f1(o,T,f,n,S){let A=Array.isArray(o[0]),$=T.length?T.flat():Object.keys(A?o[0]:o);return S1(A?o:[o],f,n,$,S)}function mS(o,T,f,n,S){if(typeof o==="string"&&(o=[o].concat(T)),Array.isArray(o))return A$(o,S);let A;return(T.length?T.flat():Object.keys(o)).map((F)=>{return A=o[F],(A instanceof yT?f$(A,f,n,S):A instanceof jn?A.value:hS(A,f,n,S))+" as "+bS(S.transform.column.to?S.transform.column.to(F):F)}).join(",")}var JO=Object.entries({values:f1,in:(...o)=>{let T=f1(...o);return T==="()"?"(null)":T},select:mS,as:mS,returning:mS,"\\(":mS,update(o,T,f,n,S){return(T.length?T.flat():Object.keys(o)).map((A)=>bS(S.transform.column.to?S.transform.column.to(A):A)+"="+S$("values",o[A],f,n,S))},insert(o,T,f,n,S){let A=T.length?T.flat():Object.keys(Array.isArray(o)?o[0]:o);return"("+A$(A,S)+")values"+S1(Array.isArray(o)?o:[o],f,n,A,S)}}).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}=n1;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((n)=>T.parsers[n]=o[f].parse),o[f].serialize)T.serializers[o[f].to]=o[f].serialize,o[f].from&&[].concat(o[f].from).forEach((n)=>T.serializers[n]=o[f].serialize);return T},{parsers:{},serializers:{}})}function A$(o,{transform:{column:T}}){return o.map((f)=>bS(T.to?T.to(f):f)).join(",")}var bS=function o(T){return'"'+T.replace(/"/g,'""').replace(/\./g,'"."')+'"'},IS=function o(T){return T instanceof mT?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,n,S){if(Array.isArray(T)===!1)return T;if(!T.length)return"{}";let A=T[0],$=S===1020?";":",";if(Array.isArray(A)&&!A.type)return"{"+T.map((F)=>o(F,f,n,S)).join($)+"}";return"{"+T.map((F)=>{if(F===void 0){if(F=n.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,n){return T$.i=T$.last=0,M1(T$,T,f,n)};function M1(o,T,f,n){let S=[],A=n===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==='"')S.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,S.push(M1(o,T,f,n));else if(o.char==="}"){o.quoted=!1,o.last<o.i&&S.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!=='"')S.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&&S.push(f?f(T.slice(o.last,o.i+1)):T.slice(o.last,o.i+1)),S}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,"-"),Cn=(o)=>o.replace(/([A-Z])/g,"_$1").toLowerCase(),mn=(o)=>(o.slice(0,1)+o.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),In=(o)=>o.replace(/-/g,"_");function $$(o){return function T(f,n){return typeof f==="object"&&f!==null&&(n.type===114||n.type===3802)?Array.isArray(f)?f.map((S)=>T(S,n)):Object.entries(f).reduce((S,[A,$])=>Object.assign(S,{[o(A)]:T($,n)}),{}):f}}kf.column={from:kf};kf.value={from:$$(kf)};Cn.column={to:Cn};var F$={...kf};F$.column.to=Cn;_f.column={from:_f};_f.value={from:$$(_f)};mn.column={to:mn};var J$={..._f};J$.column.to=mn;wf.column={from:wf};wf.value={from:$$(wf)};In.column={to:In};var R$={...wf};R$.column.to=In;import W1 from"net";import XO from"tls";import Nn 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:(n)=>{let S=T.indexOf(n);return S===-1?null:(T.splice(S,1),n)},push:(n)=>(T.push(n),n),shift:()=>{let n=T[f++];if(f===T.length)f=0,T=[];else T[f-1]=void 0;return n}}}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 xS(T),Oo.i+=eo.write(o,Oo.i,T,"utf8"),Oo},i16(o){return xS(2),eo.writeUInt16BE(o,Oo.i),Oo.i+=2,Oo},i32(o,T){if(T||T===0)return eo.writeUInt32BE(o,T),Oo;return xS(4),eo.writeUInt32BE(o,Oo.i),Oo.i+=4,Oo},z(o){return xS(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}}),c=Oo;function xS(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=c().S().end(),k1=c().H().end(),KO=c().i32(8).i32(80877103).end(8),EO=Buffer.concat([c().E().str(c.N).i32(0).end(),of]),GO=c().D().str("S").str(c.N).end(),df=()=>{},YO=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),tO={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:n=df,onclose:S=df}={}){let{ssl:A,max:$,user:F,host:J,port:R,database:M,parsers:_,transform:w,onnotice:X,onnotify:D,onparameter:K,max_pipeline:L,keep_alive:h,backoff:q,target_session_attrs:P}=o,G=WT(),z=HO++,U={pid:null,secret:null},Q=O$(eS,o.idle_timeout),v=O$(eS,o.max_lifetime),l=O$(b1,o.connect_timeout),E=null,s,r=new yf,a=Buffer.alloc(0),ko=o.fetch_types,Lo={},fT={},IT=Math.random().toString(36).slice(2),Y=1,p=0,Fo=0,Yo=0,Co=0,To=0,yo=0,Vo=0,to=null,Ko=null,Zo=!1,Xo=null,XT=null,Po=null,cT=null,mo=null,Eo=null,HT=null,DT=null,B=null,sf=null,io={queue:T.closed,idleTimer:Q,connect(W){Po=W||!0,q$()},terminate:on,execute:af,cancel:I1,end:eS,count:0,id:z};return T.closed&&T.closed.push(io),io;async function m1(){let W;try{W=o.socket?await Promise.resolve(o.socket(o)):new W1.Socket}catch(y){Ef(y);return}return W.on("error",Ef),W.on("close",r$),W.on("drain",x$),W}async function I1({pid:W,secret:y},Z,Jo){try{s=c().i32(16).i32(80877102).i32(W).i32(y).end(16),await v$(),E.once("error",Jo),E.once("close",Z)}catch(Qo){Jo(Qo)}}function af(W){if(Zo)return pn(W,Bo.connection("CONNECTION_DESTROYED",o));if(W.cancelled)return;try{return W.state=U,B?G.push(W):(B=W,B.active=!0),h1(W),ro(j1(W))&&!W.describeFirst&&!W.cursorFn&&G.length<L&&(!W.options.onexecute||W.options.onexecute(io))}catch(y){return G.length===0&&ro(of),UT(y),!0}}function j1(W){if(W.parameters.length>=65534)throw Bo.generic("MAX_PARAMETERS_EXCEEDED","Max number of parameters (65534) exceeded");return W.options.simple?c().Q().str(W.statement.string+c.N).end():W.describeFirst?Buffer.concat([N$(W),k1]):W.prepare?W.prepared?rn(W):Buffer.concat([N$(W),rn(W)]):N1(W)}function N$(W){return Buffer.concat([c$(W.statement.string,W.parameters,W.statement.types,W.statement.name),GM("S",W.statement.name)])}function rn(W){return Buffer.concat([EM(W.parameters,W.statement.types,W.statement.name,W.cursorName),W.cursorFn?Z$("",W.cursorRows):EO])}function N1(W){return Buffer.concat([c$(W.statement.string,W.parameters,W.statement.types),GO,rn(W)])}function h1(W){let y=[],Z=[],Jo=n$(W,W.strings[0],W.args[0],y,Z,o);!W.tagged&&W.args.forEach((Qo)=>hS(Qo,y,Z,o)),W.prepare=o.prepare&&("prepare"in W.options?W.options.prepare:!0),W.string=Jo,W.signature=W.prepare&&Z+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:Z,name:W.prepare?IT+Y++:""},typeof o.debug==="function"&&o.debug(z,Jo,y,Z)}function ro(W,y){if(Eo=Eo?Buffer.concat([Eo,W]):Buffer.from(W),y||Eo.length>=1024)return h$(y);return Ko===null&&(Ko=setImmediate(h$)),!0}function h$(W){let y=E.write(Eo,W);return Ko!==null&&clearImmediate(Ko),Eo=Ko=null,y}function b1(){UT(Bo.connection("CONNECT_TIMEOUT",o,E)),E.destroy()}async function b$(){if(ro(KO),!await new Promise((y)=>E.once("data",(Z)=>y(Z[0]===83)))&&A==="prefer")return Kf();E.removeAllListeners(),E=XO.connect({socket:E,servername:W1.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",Kf),E.on("error",Ef),E.on("close",r$),E.on("drain",x$)}function x$(){!B&&f(io)}function uS(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),UT(y)}a=a.subarray(To+1),Fo=0,Xo=null}}async function v$(){if(Zo=!1,Lo={},E||(E=await m1()),!E)return;if(l.start(),o.socket)return A?b$():Kf();if(E.on("connect",A?b$:Kf),o.path)return E.connect(o.path);E.ssl=A,E.connect(R[Yo],J[Yo]),E.host=J[Yo],E.port=R[Yo],Yo=(Yo+1)%R.length}function q$(){setTimeout(v$,p?p+yo-O1.now():0)}function Kf(){try{fT={},ko=o.fetch_types,IT=Math.random().toString(36).slice(2),Y=1,v.start(),E.on("data",uS),h&&E.setKeepAlive&&E.setKeepAlive(!0,1000*h);let W=tM();ro(W)}catch(W){Ef(W)}}function Ef(W){if(io.queue===T.connecting&&o.host[Co+1])return;UT(W);while(G.length)pn(G.shift(),W)}function UT(W){mo&&(mo.destroy(W),mo=null),B&&pn(B,W),Po&&(pn(Po,W),Po=null)}function pn(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 eS(){return cT||(!io.reserved&&n(io),!io.reserved&&!Po&&!B&&G.length===0?(on(),new Promise((W)=>E&&E.readyState!=="closed"?E.once("close",W):W())):cT=new Promise((W)=>HT=W))}function on(){if(Zo=!0,mo||B||Po||G.length)Ef(Bo.connection("CONNECTION_DESTROYED",o));if(clearImmediate(Ko),E)E.removeListener("data",uS),E.removeListener("connect",Kf),E.readyState==="open"&&E.end(c().X().end());HT&&(HT(),cT=HT=null)}async function r$(W){if(a=Buffer.alloc(0),Fo=0,Xo=null,clearImmediate(Ko),E.removeListener("data",uS),E.removeListener("connect",Kf),Q.cancel(),v.cancel(),l.cancel(),E.removeAllListeners(),E=null,Po)return q$();!W&&(B||G.length)&&Ef(Bo.connection("CONNECTION_CLOSED",o,E)),p=O1.now(),W&&o.shared.retries++,yo=(typeof q==="function"?q(o.shared.retries):q)*1000,S(io,Bo.connection("CONNECTION_CLOSED",o,E))}function x1(W,y=W[0]){(y===68?v1:y===100?OM:y===65?$M:y===83?q1:y===90?r1:y===67?p1:y===50?p$:y===49?c1:y===116?Z1:y===84?P1:y===82?i1:y===110?s1:y===75?a1:y===69?SM: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,Z,Jo,Qo,go=B.isRaw?new Array(B.statement.columns.length):{};for(let so=0;so<B.statement.columns.length;so++)Jo=B.statement.columns[so],Z=W.readInt32BE(y),y+=4,Qo=Z===-1?null:B.isRaw===!0?W.subarray(y,y+=Z):Jo.parser===void 0?W.toString("utf8",y,y+=Z):Jo.parser.array===!0?Jo.parser(W.toString("utf8",y+1,y+=Z)):Jo.parser(W.toString("utf8",y,y+=Z)),B.isRaw?go[so]=B.isRaw===!0?Qo:w.value.from?w.value.from(Qo,Jo):Qo:go[Jo.name]=w.value.from?w.value.from(Qo,Jo):Qo;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,Z]=W.toString("utf8",5,W.length-1).split(c.N);if(Lo[y]=Z,o.parameters[y]!==Z)o.parameters[y]=Z,K&&K(y,Z)}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 nM();else if(fM(P,Lo))return on()}if(ko)return Po===!0&&(Po=null),oM();Po!==!0&&af(Po),o.shared.retries=Co=0,Po=null;return}while(G.length&&(B=G.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?cT?on():(io.reserved=null,f(io)):io.reserved():cT?on():f(io)}function p1(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=U;break}}if(sf&&(sf(),sf=null),r.command==="BEGIN"&&$!==1&&!io.reserved)return UT(Bo.generic("UNSAFE_TRANSACTION","Only use sql.begin, sql.reserved or max: 1"));if(B.options.simple)return p$();if(B.cursorFn)r.count&&B.cursorFn(r),ro(of);B.resolve(r)}function c1(){B.parsing=!1}function p$(){!r.statement&&(r.statement=B.statement),r.columns=B.statement.columns}function Z1(W){let y=W.readUInt16BE(5);for(let Z=0;Z<y;++Z)!B.statement.types[Z]&&(B.statement.types[Z]=W.readUInt32BE(7+Z*4));B.prepare&&(fT[B.signature]=B.statement),B.describeFirst&&!B.onlyDescribe&&(ro(rn(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),Z=7,Jo;B.statement.columns=Array(y);for(let Qo=0;Qo<y;++Qo){Jo=Z;while(W[Z++]!==0);let go=W.readUInt32BE(Z),so=W.readUInt16BE(Z+4),ZT=W.readUInt32BE(Z+6);B.statement.columns[Qo]={name:w.column.from?w.column.from(W.toString("utf8",Jo,Z-1)):W.toString("utf8",Jo,Z-1),parser:_[ZT],table:go,number:so,type:ZT},Z+=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 sS();ro(c().p().str(W).z(1).end())}async function d1(W){let y="md5"+await _1(Buffer.concat([Buffer.from(await _1(await sS()+F)),W.subarray(9)]));ro(c().p().str(y).z(1).end())}async function l1(){DT=(await Nn.randomBytes(18)).toString("base64"),c().p().str("SCRAM-SHA-256"+c.N);let W=c.i;ro(c.inc(4).str("n,,n=*,r="+DT).i32(c.i-W-4,W).end())}async function u1(W){let y=W.toString("utf8",9).split(",").reduce((so,ZT)=>(so[ZT[0]]=ZT.slice(2),so),{}),Z=await Nn.pbkdf2Sync(await sS(),Buffer.from(y.s,"base64"),parseInt(y.i),32,"sha256"),Jo=await vS(Z,"Client Key"),Qo="n=*,r="+DT+",r="+y.r+",s="+y.s+",i="+y.i+",c=biws,r="+y.r;to=(await vS(await vS(Z,"Server Key"),Qo)).toString("base64");let go="c=biws,r="+y.r+",p="+QO(Jo,Buffer.from(await vS(await zO(Jo),Qo))).toString("base64");ro(c().p().str(go).end())}function e1(W){if(W.toString("utf8",9).split(c.N,1)[0].slice(2)===to)return;UT(Bo.generic("SASL_SIGNATURE_MISMATCH","The server did not return the correct signature")),E.destroy()}function sS(){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){U.pid=W.readUInt32BE(5),U.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
@@ -24,7 +24,7 @@ ${$.trace}`:"No previous disposal trace was found."),n.type){case"atom_family":c
24
24
  `],[],af)).forEach(({oid:y,typarray:Z})=>TM(y,Z))}function TM(W,y){if(!!o.parsers[y]&&!!o.serializers[y])return;let Z=o.parsers[W];o.shared.typeArrayMap[W]=y,o.parsers[y]=(Jo)=>R1(Jo,Z,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 nM(){let W=new yT([`
25
25
  show transaction_read_only;
26
26
  select pg_catalog.pg_is_in_recovery()
27
- `],[],af,null,{simple:!0});W.resolve=([[y],[Z]])=>{Lo.default_transaction_read_only=y.transaction_read_only,Lo.in_hot_standby=Z.pg_is_in_recovery?"on":"off"},W.execute()}function SM(W){B&&(B.cursorFn||B.describeFirst)&&ro(of);let y=Bo.postgres(W$(W));B&&B.retried?UT(B.retried):B&&B.prepared&&EO.has(y.routine)?AM(B,y):UT(y)}function AM(W,y){delete fT[W.signature],W.retried=y,af(W)}function $M(W){if(!D)return;let y=9;while(W[y++]!==0);D(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(Z$("",B.cursorRows)))}catch(W){ro(of),B.reject(W)}}function JM(){r.count&&B.cursorFn(r),B.resolve(r)}function RM(){mo=new M$.Writable({autoDestroy:!0,write(W,y,Z){G.write(c().d().raw(W).end(),Z)},destroy(W,y){y(W),G.write(c().f().str(W+c.N).end()),mo=null},final(W){G.write(c().c().end()),sf=W}}),B.resolve(mo)}function MM(){mo=new M$.Readable({read(){G.resume()}}),B.resolve(mo)}function WM(){mo=new M$.Duplex({autoDestroy:!0,read(){G.resume()},write(W,y,Z){G.write(c().d().raw(W).end(),Z)},destroy(W,y){y(W),G.write(c().f().str(W+c.N).end()),mo=null},final(W){G.write(c().c().end()),sf=W}}),B.resolve(mo)}function OM(W){mo&&(mo.push(W.subarray(5))||G.pause())}function kM(){mo&&mo.push(null),mo=null}function _M(W){X?X(W$(W)):console.log(W$(W))}function wM(){}function yM(){UT(Bo.notSupported("FunctionCallResponse"))}function XM(){UT(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,Z="",Jo=""){let Qo,go;return c().B().str(Jo+c.N).str(Z+c.N).i16(0).i16(W.length),W.forEach((so,ZT)=>{if(so===null)return c.i32(4294967295);go=y[ZT],W[ZT]=so=go in o.serializers?o.serializers[go](so):""+so,Qo=c.i,c.inc(4).str(so).i32(c.i-Qo-4,Qo)}),c.i16(0),c.end()}function c$(W,y,Z,Jo=""){return c().P().str(Jo+c.N).str(W+c.N).i16(y.length),y.forEach((Qo,go)=>c.i32(Z[go]||0)),c.end()}function YM(W,y=""){return c().D().str(W).str(y+c.N).end()}function Z$(W="",y=0){return Buffer.concat([c().E().str(W+c.N).i32(y).end(),k1])}function EM(W=""){return Buffer.concat([c().C().str("P").str(W+c.N).end(),c().S().end()])}function tM(){return s||c().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+c.N+y).join(c.N)).z(2).end(0)}}function W$(o){let T={},f=5;for(let n=5;n<o.length-1;n++)if(o[n]===0)T[tO[o[f]]]=o.toString("utf8",f+1,n),f=n+1;return T}function _1(o){return Nn.createHash("md5").update(o).digest("hex")}function vS(o,T){return Nn.createHmac("sha256",o).update(T).digest()}function zO(o){return Nn.createHash("sha256").update(o).digest()}function QO(o,T){let f=Math.max(o.length,T.length),n=Buffer.allocUnsafe(f);for(let S=0;S<f;S++)n[S]=o[S]^T[S];return n}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(n,T*1000,arguments)}};function n(S){o.apply(null,S),f=null}}var y1=()=>{};function _$(o,T){let f=new Map,n="postgresjs_"+Math.random().toString(36).slice(2),S={},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,S.pid=S.secret=void 0,w(await X(J,n,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,n,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),z=()=>{Y.delete(P),Y.size===0&&f.delete(K)};return A.then((U)=>{return w(U),h(),$&&$.on("error",q),{unsubscribe:z,state:S,sql:J}})}function w(K){$=K.stream,S.pid=K.state.pid,S.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(),z={lsn:Buffer.concat(P.consistent_point.split("/").map((G)=>Buffer.from(("00000000"+G).slice(-8),"hex")))};return Y.on("data",Q),Y.on("error",U),Y.on("close",K.close),{stream:Y,state:q.state};function U(G){console.error("Unexpected error during logical streaming - reconnecting",G)}function Q(G){if(G[0]===119)UO(G.subarray(25),z,K.options.parsers,v,T.transform);else if(G[0]===107&&G[17])z.lsn=G.subarray(1,9),l()}function v(G,s){let r=s.relation.schema+"."+s.relation.table;D("*",G,s),D("*:"+r,G,s),s.relation.keys.length&&D("*:"+r+"="+s.relation.keys.map((a)=>G[a.name]),G,s),D(s.command,G,s),D(s.command+":"+r,G,s),s.relation.keys.length&&D(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(z.lsn,1),G.writeBigInt64BE(BigInt(Date.now()-Date.UTC(2000,0,1))*BigInt(1000),25),Y.write(G)}}function D(K,L,h){f.has(K)&&f.get(K).forEach(({fn:q})=>q(L,h,K))}}function DO(o){return new Date(Date.UTC(2000,0,1)+Number(o/BigInt(1000)))}function UO(o,T,f,n,S){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:S.column.from?S.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=DO($.readBigInt64BE(9)),T.lsn=$.subarray(1,9)},I:($)=>{let F=1,J=T[$.readUInt32BE(F)],{row:R}=qS($,J.columns,F+=7,S);n(R,{command:"insert",relation:J})},D:($)=>{let F=1,J=T[$.readUInt32BE(F)];F+=4;let R=$[F]===75;n(R||$[F]===79?qS($,J.columns,F+=3,S).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?qS($,J.columns,F+=3,S):null;M&&(F=M.i);let{row:_}=qS($,J.columns,F+3,S);n(_,{command:"update",relation:J,key:R,old:M&&M.row})},T:()=>{},C:()=>{}}).reduce(A,{})[o[0]](o)}function qS(o,T,f,n){let S,A,$,F=n.raw?new Array(T.length):{};for(let J=0;J<T.length;J++)S=o[f++],A=T[J],$=S===110?null:S===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))),n.raw?F[J]=n.raw===!0?$:n.value.from?n.value.from($,A):$:F[A.name]=n.value.from?n.value.from($,A):$;return{i:f,row:n.row.from?n.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,n,S]=T;return(f||"*")+(n?":"+(n.indexOf(".")===-1?"public."+n:n):"")+(S?"="+S:"")}import X1 from"stream";function w$(o,T,f=393216){return new Promise(async(n,S)=>{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`
27
+ `],[],af,null,{simple:!0});W.resolve=([[y],[Z]])=>{Lo.default_transaction_read_only=y.transaction_read_only,Lo.in_hot_standby=Z.pg_is_in_recovery?"on":"off"},W.execute()}function SM(W){B&&(B.cursorFn||B.describeFirst)&&ro(of);let y=Bo.postgres(W$(W));B&&B.retried?UT(B.retried):B&&B.prepared&&YO.has(y.routine)?AM(B,y):UT(y)}function AM(W,y){delete fT[W.signature],W.retried=y,af(W)}function $M(W){if(!D)return;let y=9;while(W[y++]!==0);D(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(YM(B.portal)):(r=new yf,ro(Z$("",B.cursorRows)))}catch(W){ro(of),B.reject(W)}}function JM(){r.count&&B.cursorFn(r),B.resolve(r)}function RM(){mo=new M$.Writable({autoDestroy:!0,write(W,y,Z){E.write(c().d().raw(W).end(),Z)},destroy(W,y){y(W),E.write(c().f().str(W+c.N).end()),mo=null},final(W){E.write(c().c().end()),sf=W}}),B.resolve(mo)}function MM(){mo=new M$.Readable({read(){E.resume()}}),B.resolve(mo)}function WM(){mo=new M$.Duplex({autoDestroy:!0,read(){E.resume()},write(W,y,Z){E.write(c().d().raw(W).end(),Z)},destroy(W,y){y(W),E.write(c().f().str(W+c.N).end()),mo=null},final(W){E.write(c().c().end()),sf=W}}),B.resolve(mo)}function OM(W){mo&&(mo.push(W.subarray(5))||E.pause())}function kM(){mo&&mo.push(null),mo=null}function _M(W){X?X(W$(W)):console.log(W$(W))}function wM(){}function yM(){UT(Bo.notSupported("FunctionCallResponse"))}function XM(){UT(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 EM(W,y,Z="",Jo=""){let Qo,go;return c().B().str(Jo+c.N).str(Z+c.N).i16(0).i16(W.length),W.forEach((so,ZT)=>{if(so===null)return c.i32(4294967295);go=y[ZT],W[ZT]=so=go in o.serializers?o.serializers[go](so):""+so,Qo=c.i,c.inc(4).str(so).i32(c.i-Qo-4,Qo)}),c.i16(0),c.end()}function c$(W,y,Z,Jo=""){return c().P().str(Jo+c.N).str(W+c.N).i16(y.length),y.forEach((Qo,go)=>c.i32(Z[go]||0)),c.end()}function GM(W,y=""){return c().D().str(W).str(y+c.N).end()}function Z$(W="",y=0){return Buffer.concat([c().E().str(W+c.N).i32(y).end(),k1])}function YM(W=""){return Buffer.concat([c().C().str("P").str(W+c.N).end(),c().S().end()])}function tM(){return s||c().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+c.N+y).join(c.N)).z(2).end(0)}}function W$(o){let T={},f=5;for(let n=5;n<o.length-1;n++)if(o[n]===0)T[tO[o[f]]]=o.toString("utf8",f+1,n),f=n+1;return T}function _1(o){return Nn.createHash("md5").update(o).digest("hex")}function vS(o,T){return Nn.createHmac("sha256",o).update(T).digest()}function zO(o){return Nn.createHash("sha256").update(o).digest()}function QO(o,T){let f=Math.max(o.length,T.length),n=Buffer.allocUnsafe(f);for(let S=0;S<f;S++)n[S]=o[S]^T[S];return n}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(n,T*1000,arguments)}};function n(S){o.apply(null,S),f=null}}var y1=()=>{};function _$(o,T){let f=new Map,n="postgresjs_"+Math.random().toString(36).slice(2),S={},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,S.pid=S.secret=void 0,w(await X(J,n,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,n,T.publications);let P={fn:L,onsubscribe:h},G=f.has(K)?f.get(K).add(P):f.set(K,new Set([P])).get(K),z=()=>{G.delete(P),G.size===0&&f.delete(K)};return A.then((U)=>{return w(U),h(),$&&$.on("error",q),{unsubscribe:z,state:S,sql:J}})}function w(K){$=K.stream,S.pid=K.state.pid,S.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,G=await K.unsafe(`START_REPLICATION SLOT ${L} LOGICAL ${P.consistent_point} (proto_version '1', publication_names '${h}')`).writable(),z={lsn:Buffer.concat(P.consistent_point.split("/").map((E)=>Buffer.from(("00000000"+E).slice(-8),"hex")))};return G.on("data",Q),G.on("error",U),G.on("close",K.close),{stream:G,state:q.state};function U(E){console.error("Unexpected error during logical streaming - reconnecting",E)}function Q(E){if(E[0]===119)UO(E.subarray(25),z,K.options.parsers,v,T.transform);else if(E[0]===107&&E[17])z.lsn=E.subarray(1,9),l()}function v(E,s){let r=s.relation.schema+"."+s.relation.table;D("*",E,s),D("*:"+r,E,s),s.relation.keys.length&&D("*:"+r+"="+s.relation.keys.map((a)=>E[a.name]),E,s),D(s.command,E,s),D(s.command+":"+r,E,s),s.relation.keys.length&&D(s.command+":"+r+"="+s.relation.keys.map((a)=>E[a.name]),E,s)}function l(){let E=Buffer.alloc(34);E[0]=114,E.fill(z.lsn,1),E.writeBigInt64BE(BigInt(Date.now()-Date.UTC(2000,0,1))*BigInt(1000),25),G.write(E)}}function D(K,L,h){f.has(K)&&f.get(K).forEach(({fn:q})=>q(L,h,K))}}function DO(o){return new Date(Date.UTC(2000,0,1)+Number(o/BigInt(1000)))}function UO(o,T,f,n,S){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:S.column.from?S.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=DO($.readBigInt64BE(9)),T.lsn=$.subarray(1,9)},I:($)=>{let F=1,J=T[$.readUInt32BE(F)],{row:R}=qS($,J.columns,F+=7,S);n(R,{command:"insert",relation:J})},D:($)=>{let F=1,J=T[$.readUInt32BE(F)];F+=4;let R=$[F]===75;n(R||$[F]===79?qS($,J.columns,F+=3,S).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?qS($,J.columns,F+=3,S):null;M&&(F=M.i);let{row:_}=qS($,J.columns,F+3,S);n(_,{command:"update",relation:J,key:R,old:M&&M.row})},T:()=>{},C:()=>{}}).reduce(A,{})[o[0]](o)}function qS(o,T,f,n){let S,A,$,F=n.raw?new Array(T.length):{};for(let J=0;J<T.length;J++)S=o[f++],A=T[J],$=S===110?null:S===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))),n.raw?F[J]=n.raw===!0?$:n.value.from?n.value.from($,A):$:F[A.name]=n.value.from?n.value.from($,A):$;return{i:f,row:n.row.from?n.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,n,S]=T;return(f||"*")+(n?":"+(n.indexOf(".")===-1?"public."+n:n):"")+(S?"="+S:"")}import X1 from"stream";function w$(o,T,f=393216){return new Promise(async(n,S)=>{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."),n.type){case"atom_family":c
34
34
  tell.location
35
35
  from (select lo_tell64($1) as location) tell
36
36
  ) seek
37
- `};return n(J),new Promise(async(_)=>$=_);async function R({highWaterMark:_=16384,start:w=0,end:X=1/0}={}){let D=X-w;return w&&await J.seek(w),new X1.Readable({highWaterMark:_,async read(K){let L=K>D?K-D:K;D-=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,D,K){J.write(X).then(()=>K(),K)}})}}).catch(S)})}Object.assign(rS,{PostgresError:gf,toPascal:_f,pascal:J$,toCamel:kf,camel:F$,toKebab:wf,kebab:R$,fromPascal:mn,fromCamel:Cn,fromKebab:In,BigInt:{to:20,from:[20],parse:(o)=>BigInt(o),serialize:(o)=>o.toString()}});var lf=rS;function rS(o,T){let f=CO(o,T),n=f.no_subscribe||_$(rS,{...f}),S=!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},D=[...Array(f.max)].map(()=>k$(f,X,{onopen:fT,onend:Lo,onclose:IT})),K=L(v);return Object.assign(K,{get parameters(){return f.parameters},largeObject:w$.bind(null,K),subscribe:n,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]=(to)=>new mT(to,Vo.to),To},p),Object.assign(Fo,{types:p,typed:p,unsafe:Eo,notify:q,array:Q,json:U,file:Co}),Fo;function p(To,yo){return new mT(To,yo)}function Fo(To,...yo){return To&&Array.isArray(To.raw)?new yT(To,yo,E,G):typeof To==="string"&&!yo.length?new jn(f.transform.column.to?f.transform.column.to(To):To):new NS(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",(Zo,Xo)=>{if(Zo)return Ko.reject(Zo);Ko.strings=[Xo],E(Ko)})},G,{...Vo,simple:"simple"in Vo?Vo.simple:yo.length===0})}}async function h(E,p,Fo){let Eo={fn:p,onlisten:Fo},Co=h.sql||(h.sql=rS({...f,max:1,idle_timeout:null,max_lifetime:null,fetch_types:!1,onclose(){Object.entries(h.channels).forEach(([Ko,{listeners:Zo}])=>{delete h.channels[Ko],Promise.all(Zo.map((Xo)=>h(Ko,Xo.fn,Xo.onlisten).catch(()=>{})))})},onnotify(Ko,Zo){Ko in h.channels&&h.channels[Ko].listeners.forEach((Xo)=>Xo.fn(Zo))}})),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:to}}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:to};async function to(){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,p){return await K`select pg_notify(${E}, ${""+p})`}async function P(){let E=WT(),p=M.length?M.shift():await new Promise((Co)=>{A.push({reserve:Co}),J.length&&ko(J.shift())});z(p,F),p.reserved=()=>E.length?p.execute(E.shift()):z(p,F),p.reserved.release=!0;let Fo=L(Eo);return Fo.release=()=>{p.reserved=null,fT(p)},Fo;function Eo(Co){p.queue===w?E.push(Co):p.execute(Co)||z(p,w)}}async function Y(E,p){!p&&(p=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,p),new Promise((to,Ko)=>Co.onclose=Ko)])}catch(to){throw to}async function yo(to,Ko,Zo){let Xo=L(mo);Xo.savepoint=cT,Xo.prepare=(Go)=>To=Go.replace(/[^a-z0-9$-_. ]/gi);let XT,Po;Zo&&await Xo`savepoint ${Xo(Zo)}`;try{if(Po=await new Promise((Go,HT)=>{let DT=Ko(Xo);Promise.resolve(Array.isArray(DT)?Promise.all(DT):DT).then(Go,HT)}),XT)throw XT}catch(Go){throw await(Zo?Xo`rollback to ${Xo(Zo)}`:Xo`rollback`),Go instanceof gf&&Go.code==="25P02"&&XT||Go}if(!Zo)To?await Xo`prepare transaction '${Xo.unsafe(To)}'`:await Xo`commit`;return Po;function cT(Go,HT){if(Go&&Array.isArray(Go.raw))return cT((DT)=>DT.apply(DT,arguments));return arguments.length===1&&(HT=Go,Go=null),yo(to,HT,"s"+Eo+++(Go?"_"+Go:""))}function mo(Go){Go.catch((HT)=>XT||(XT=HT)),to.queue===w?Fo.push(Go):to.execute(Go)||z(to,w)}}function Vo(to){Co=to,z(to,F),to.reserved=()=>Fo.length?to.execute(Fo.shift()):z(to,F)}}function z(E,p){return E.queue.remove(E),p.push(E),E.queue=p,p===M?E.idleTimer.start():E.idleTimer.cancel(),E}function U(E){return new mT(E,3802)}function Q(E,p){if(!Array.isArray(E))return Q(Array.from(arguments));return new mT(E,p||(E.length?IS(E)||25:0),f.shared.typeArrayMap)}function v(E){if(S)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,p){return E.execute(p)?z(E,_):z(E,w)}function G(E){return new Promise((p,Fo)=>{E.state?E.active?k$(f).cancel(E.state,p,Fo):E.cancelled={resolve:p,reject:Fo}:(A.remove(E),E.cancelled=!0,E.reject(Bo.generic("57014","canceling statement due to user request")),p())})}async function s({timeout:E=null}={}){if(S)return S;await 1;let p;return S=Promise.race([new Promise((Fo)=>E!==null&&(p=setTimeout(a,E*1000,Fo))),Promise.all(D.map((Fo)=>Fo.end()).concat(h.sql?h.sql.end({timeout:0}):[],n.sql?n.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(p))}async function r(){await Promise.all(D.map((E)=>E.end()))}async function a(E){await Promise.all(D.map((p)=>p.terminate()));while(A.length)A.shift().reject(Bo.connection("CONNECTION_DESTROYED",f));E()}function ko(E,p){return z(E,$),E.connect(p),E}function Lo(E){z(E,R)}function fT(E){if(A.length===0)return z(E,M);let p=Math.ceil(A.length/($.length+1)),Fo=!0;while(Fo&&A.length&&p-- >0){let Eo=A.shift();if(Eo.reserve)return Eo.reserve(E);Fo=E.execute(Eo)}Fo?z(E,_):z(E,w)}function IT(E,p){z(E,J),E.reserved=null,E.onclose&&(E.onclose(p),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,n=(!o||typeof o==="string"?T:o)||{},{url:S,multihost:A}=hO(o),$=[...S.searchParams].reduce((w,[X,D])=>(w[X]=D,w),{}),F=n.hostname||n.host||A||S.hostname||f.PGHOST||"localhost",J=n.port||S.port||f.PGPORT||5432,R=n.user||n.username||S.username||f.PGUSERNAME||f.PGUSER||bO();n.no_prepare&&(n.prepare=!1),$.sslmode&&($.ssl=$.sslmode,delete $.sslmode),"timeout"in n&&(console.log("The timeout option is deprecated, use idle_timeout instead"),n.idle_timeout=n.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:jO,max_pipeline:100,backoff:IO,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:n.path||F.indexOf("/")>-1&&F+"/.s.PGSQL."+J,database:n.database||n.db||(S.pathname||"").slice(1)||f.PGDATABASE||R,user:R,pass:n.pass||n.password||S.password||f.PGPASSWORD||"",...Object.entries(_).reduce((w,[X,D])=>{let K=X in n?n[X]:(X in $)?$[X]==="disable"||$[X]==="false"?!1:$[X]:f["PG"+X.toUpperCase()]||D;return w[X]=typeof K==="string"&&M.includes(X)?+K:K,w},{}),connection:{application_name:"postgres.js",...n.connection,...Object.entries($).reduce((w,[X,D])=>((X in _)||(w[X]=D),w),{})},types:n.types||{},target_session_attrs:mO(n,S,f),onnotice:n.onnotice,onnotify:n.onnotify,onclose:n.onclose,onparameter:n.onparameter,socket:n.socket,transform:NO(n.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...$1(n.types)}}function mO(o,T,f){let n=o.target_session_attrs||T.searchParams.get("target_session_attrs")||f.PGTARGETSESSIONATTRS;if(!n||["read-write","read-only","primary","standby","prefer-standby"].includes(n))return n;throw new Error("target_session_attrs "+n+" is not supported")}function IO(o){return(0.5+Math.random()/2)*Math.min(3**o/100,20)}function jO(){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 Do{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 n=(H(o,bo)?o._.selectedFields:H(o,ST)?o[Ho].selectedFields:o)[T];if(H(n,j.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!n.isSelectionField)return n.sql;let S=n.clone();return S.isSelectionField=!0,S}if(H(n,j)){if(this.config.sqlBehavior==="sql")return n;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(n,_o)){if(this.config.alias)return new Proxy(n,new Zf(new Proxy(n.table,new zn(this.config.alias,this.config.replaceOriginalName??!1))));return n}if(typeof n!=="object"||n===null)return n;return new Proxy(n,new Do(this.config))}}class pS extends oT{constructor(o,T,f,n){super();this.session=T,this.dialect=f,this.config={table:o,withList:n}}static[O]="PgDelete";config;where(o){return this.config.where=o,this}returning(o=this.config.table[I.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 Do({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,n,S)=>{let A=S===0?n.toLowerCase():`${n[0].toUpperCase()}${n.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[I.Symbol.Schema]??"public",f=o.table[I.Symbol.OriginalName],n=`${T}.${f}.${o.name}`;if(!this.cache[n])this.cacheTable(o.table);return this.cache[n]}cacheTable(o){let T=o[I.Symbol.Schema]??"public",f=o[I.Symbol.OriginalName],n=`${T}.${f}`;if(!this.cachedTables[n]){for(let S of Object.values(o[I.Symbol.Columns])){let A=`${n}.${S.name}`;this.cache[A]=this.convert(S.name)}this.cachedTables[n]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class hn extends ST{static[O]="PgViewBase"}class Xf{static[O]="PgDialect";casing;constructor(o){this.casing=new y$(o?.casing)}async migrate(o,T,f){let n=typeof f==="string"?"__drizzle_migrations":f.migrationsTable??"__drizzle_migrations",S=typeof f==="string"?"drizzle":f.migrationsSchema??"drizzle",A=k`
37
+ `};return n(J),new Promise(async(_)=>$=_);async function R({highWaterMark:_=16384,start:w=0,end:X=1/0}={}){let D=X-w;return w&&await J.seek(w),new X1.Readable({highWaterMark:_,async read(K){let L=K>D?K-D:K;D-=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,D,K){J.write(X).then(()=>K(),K)}})}}).catch(S)})}Object.assign(rS,{PostgresError:gf,toPascal:_f,pascal:J$,toCamel:kf,camel:F$,toKebab:wf,kebab:R$,fromPascal:mn,fromCamel:Cn,fromKebab:In,BigInt:{to:20,from:[20],parse:(o)=>BigInt(o),serialize:(o)=>o.toString()}});var lf=rS;function rS(o,T){let f=CO(o,T),n=f.no_subscribe||_$(rS,{...f}),S=!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},D=[...Array(f.max)].map(()=>k$(f,X,{onopen:fT,onend:Lo,onclose:IT})),K=L(v);return Object.assign(K,{get parameters(){return f.parameters},largeObject:w$.bind(null,K),subscribe:n,CLOSE:Pf,END:Pf,PostgresError:gf,options:f,reserve:P,listen:h,begin:G,close:r,end:s}),K;function L(Y){return Y.debug=f.debug,Object.entries(f.types).reduce((To,[yo,Vo])=>{return To[yo]=(to)=>new mT(to,Vo.to),To},p),Object.assign(Fo,{types:p,typed:p,unsafe:Yo,notify:q,array:Q,json:U,file:Co}),Fo;function p(To,yo){return new mT(To,yo)}function Fo(To,...yo){return To&&Array.isArray(To.raw)?new yT(To,yo,Y,E):typeof To==="string"&&!yo.length?new jn(f.transform.column.to?f.transform.column.to(To):To):new NS(To,yo)}function Yo(To,yo=[],Vo={}){return arguments.length===2&&!Array.isArray(yo)&&(Vo=yo,yo=[]),new yT([To],yo,Y,E,{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",(Zo,Xo)=>{if(Zo)return Ko.reject(Zo);Ko.strings=[Xo],Y(Ko)})},E,{...Vo,simple:"simple"in Vo?Vo.simple:yo.length===0})}}async function h(Y,p,Fo){let Yo={fn:p,onlisten:Fo},Co=h.sql||(h.sql=rS({...f,max:1,idle_timeout:null,max_lifetime:null,fetch_types:!1,onclose(){Object.entries(h.channels).forEach(([Ko,{listeners:Zo}])=>{delete h.channels[Ko],Promise.all(Zo.map((Xo)=>h(Ko,Xo.fn,Xo.onlisten).catch(()=>{})))})},onnotify(Ko,Zo){Ko in h.channels&&h.channels[Ko].listeners.forEach((Xo)=>Xo.fn(Zo))}})),To=h.channels||(h.channels={});if(Y in To){To[Y].listeners.push(Yo);let Ko=await To[Y].result;return Yo.onlisten&&Yo.onlisten(),{state:Ko.state,unlisten:to}}To[Y]={result:Co`listen ${Co.unsafe('"'+Y.replace(/"/g,'""')+'"')}`,listeners:[Yo]};let Vo=await To[Y].result;return Yo.onlisten&&Yo.onlisten(),{state:Vo.state,unlisten:to};async function to(){if(Y in To===!1)return;if(To[Y].listeners=To[Y].listeners.filter((Ko)=>Ko!==Yo),To[Y].listeners.length)return;return delete To[Y],Co`unlisten ${Co.unsafe('"'+Y.replace(/"/g,'""')+'"')}`}}async function q(Y,p){return await K`select pg_notify(${Y}, ${""+p})`}async function P(){let Y=WT(),p=M.length?M.shift():await new Promise((Co)=>{A.push({reserve:Co}),J.length&&ko(J.shift())});z(p,F),p.reserved=()=>Y.length?p.execute(Y.shift()):z(p,F),p.reserved.release=!0;let Fo=L(Yo);return Fo.release=()=>{p.reserved=null,fT(p)},Fo;function Yo(Co){p.queue===w?Y.push(Co):p.execute(Co)||z(p,w)}}async function G(Y,p){!p&&(p=Y,Y="");let Fo=WT(),Yo=0,Co,To=null;try{return await K.unsafe("begin "+Y.replace(/[^a-z ]/ig,""),[],{onexecute:Vo}).execute(),await Promise.race([yo(Co,p),new Promise((to,Ko)=>Co.onclose=Ko)])}catch(to){throw to}async function yo(to,Ko,Zo){let Xo=L(mo);Xo.savepoint=cT,Xo.prepare=(Eo)=>To=Eo.replace(/[^a-z0-9$-_. ]/gi);let XT,Po;Zo&&await Xo`savepoint ${Xo(Zo)}`;try{if(Po=await new Promise((Eo,HT)=>{let DT=Ko(Xo);Promise.resolve(Array.isArray(DT)?Promise.all(DT):DT).then(Eo,HT)}),XT)throw XT}catch(Eo){throw await(Zo?Xo`rollback to ${Xo(Zo)}`:Xo`rollback`),Eo instanceof gf&&Eo.code==="25P02"&&XT||Eo}if(!Zo)To?await Xo`prepare transaction '${Xo.unsafe(To)}'`:await Xo`commit`;return Po;function cT(Eo,HT){if(Eo&&Array.isArray(Eo.raw))return cT((DT)=>DT.apply(DT,arguments));return arguments.length===1&&(HT=Eo,Eo=null),yo(to,HT,"s"+Yo+++(Eo?"_"+Eo:""))}function mo(Eo){Eo.catch((HT)=>XT||(XT=HT)),to.queue===w?Fo.push(Eo):to.execute(Eo)||z(to,w)}}function Vo(to){Co=to,z(to,F),to.reserved=()=>Fo.length?to.execute(Fo.shift()):z(to,F)}}function z(Y,p){return Y.queue.remove(Y),p.push(Y),Y.queue=p,p===M?Y.idleTimer.start():Y.idleTimer.cancel(),Y}function U(Y){return new mT(Y,3802)}function Q(Y,p){if(!Array.isArray(Y))return Q(Array.from(arguments));return new mT(Y,p||(Y.length?IS(Y)||25:0),f.shared.typeArrayMap)}function v(Y){if(S)return Y.reject(Bo.connection("CONNECTION_ENDED",f,f));if(M.length)return l(M.shift(),Y);if(J.length)return ko(J.shift(),Y);_.length?l(_.shift(),Y):A.push(Y)}function l(Y,p){return Y.execute(p)?z(Y,_):z(Y,w)}function E(Y){return new Promise((p,Fo)=>{Y.state?Y.active?k$(f).cancel(Y.state,p,Fo):Y.cancelled={resolve:p,reject:Fo}:(A.remove(Y),Y.cancelled=!0,Y.reject(Bo.generic("57014","canceling statement due to user request")),p())})}async function s({timeout:Y=null}={}){if(S)return S;await 1;let p;return S=Promise.race([new Promise((Fo)=>Y!==null&&(p=setTimeout(a,Y*1000,Fo))),Promise.all(D.map((Fo)=>Fo.end()).concat(h.sql?h.sql.end({timeout:0}):[],n.sql?n.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(p))}async function r(){await Promise.all(D.map((Y)=>Y.end()))}async function a(Y){await Promise.all(D.map((p)=>p.terminate()));while(A.length)A.shift().reject(Bo.connection("CONNECTION_DESTROYED",f));Y()}function ko(Y,p){return z(Y,$),Y.connect(p),Y}function Lo(Y){z(Y,R)}function fT(Y){if(A.length===0)return z(Y,M);let p=Math.ceil(A.length/($.length+1)),Fo=!0;while(Fo&&A.length&&p-- >0){let Yo=A.shift();if(Yo.reserve)return Yo.reserve(Y);Fo=Y.execute(Yo)}Fo?z(Y,_):z(Y,w)}function IT(Y,p){z(Y,J),Y.reserved=null,Y.onclose&&(Y.onclose(p),Y.onclose=null),f.onclose&&f.onclose(Y.id),A.length&&ko(Y,A.shift())}}function CO(o,T){if(o&&o.shared)return o;let f=process.env,n=(!o||typeof o==="string"?T:o)||{},{url:S,multihost:A}=hO(o),$=[...S.searchParams].reduce((w,[X,D])=>(w[X]=D,w),{}),F=n.hostname||n.host||A||S.hostname||f.PGHOST||"localhost",J=n.port||S.port||f.PGPORT||5432,R=n.user||n.username||S.username||f.PGUSERNAME||f.PGUSER||bO();n.no_prepare&&(n.prepare=!1),$.sslmode&&($.ssl=$.sslmode,delete $.sslmode),"timeout"in n&&(console.log("The timeout option is deprecated, use idle_timeout instead"),n.idle_timeout=n.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:jO,max_pipeline:100,backoff:IO,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:n.path||F.indexOf("/")>-1&&F+"/.s.PGSQL."+J,database:n.database||n.db||(S.pathname||"").slice(1)||f.PGDATABASE||R,user:R,pass:n.pass||n.password||S.password||f.PGPASSWORD||"",...Object.entries(_).reduce((w,[X,D])=>{let K=X in n?n[X]:(X in $)?$[X]==="disable"||$[X]==="false"?!1:$[X]:f["PG"+X.toUpperCase()]||D;return w[X]=typeof K==="string"&&M.includes(X)?+K:K,w},{}),connection:{application_name:"postgres.js",...n.connection,...Object.entries($).reduce((w,[X,D])=>((X in _)||(w[X]=D),w),{})},types:n.types||{},target_session_attrs:mO(n,S,f),onnotice:n.onnotice,onnotify:n.onnotify,onclose:n.onclose,onparameter:n.onparameter,socket:n.socket,transform:NO(n.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...$1(n.types)}}function mO(o,T,f){let n=o.target_session_attrs||T.searchParams.get("target_session_attrs")||f.PGTARGETSESSIONATTRS;if(!n||["read-write","read-only","primary","standby","prefer-standby"].includes(n))return n;throw new Error("target_session_attrs "+n+" is not supported")}function IO(o){return(0.5+Math.random()/2)*Math.min(3**o/100,20)}function jO(){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 Do{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 n=(H(o,bo)?o._.selectedFields:H(o,ST)?o[Ho].selectedFields:o)[T];if(H(n,j.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!n.isSelectionField)return n.sql;let S=n.clone();return S.isSelectionField=!0,S}if(H(n,j)){if(this.config.sqlBehavior==="sql")return n;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(n,_o)){if(this.config.alias)return new Proxy(n,new Zf(new Proxy(n.table,new zn(this.config.alias,this.config.replaceOriginalName??!1))));return n}if(typeof n!=="object"||n===null)return n;return new Proxy(n,new Do(this.config))}}class pS extends oT{constructor(o,T,f,n){super();this.session=T,this.dialect=f,this.config={table:o,withList:n}}static[O]="PgDelete";config;where(o){return this.config.where=o,this}returning(o=this.config.table[I.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 Do({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,n,S)=>{let A=S===0?n.toLowerCase():`${n[0].toUpperCase()}${n.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[I.Symbol.Schema]??"public",f=o.table[I.Symbol.OriginalName],n=`${T}.${f}.${o.name}`;if(!this.cache[n])this.cacheTable(o.table);return this.cache[n]}cacheTable(o){let T=o[I.Symbol.Schema]??"public",f=o[I.Symbol.OriginalName],n=`${T}.${f}`;if(!this.cachedTables[n]){for(let S of Object.values(o[I.Symbol.Columns])){let A=`${n}.${S.name}`;this.cache[A]=this.convert(S.name)}this.cachedTables[n]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class hn extends ST{static[O]="PgViewBase"}class Xf{static[O]="PgDialect";casing;constructor(o){this.casing=new y$(o?.casing)}async migrate(o,T,f){let n=typeof f==="string"?"__drizzle_migrations":f.migrationsTable??"__drizzle_migrations",S=typeof f==="string"?"drizzle":f.migrationsSchema??"drizzle",A=k`
38
38
  CREATE TABLE IF NOT EXISTS ${k.identifier(S)}.${k.identifier(n)} (
39
39
  id SERIAL PRIMARY KEY,
40
40
  hash text NOT NULL,
41
41
  created_at bigint
42
42
  )
43
- `;await T.execute(k`CREATE SCHEMA IF NOT EXISTS ${k.identifier(S)}`),await T.execute(A);let F=(await T.all(k`select id, hash, created_at from ${k.identifier(S)}.${k.identifier(n)} 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(S)}.${k.identifier(n)} ("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,n]of o.entries())if(T.push(k`${k.identifier(n._.alias)} as (${n._.sql})`),f<o.length-1)T.push(k`, `);return T.push(k` `),k.join(T)}buildDeleteQuery({table:o,where:T,returning:f,withList:n}){let S=this.buildWithCTE(n),A=f?k` returning ${this.buildSelection(f,{isSingleTable:!0})}`:void 0,$=T?k` where ${T}`:void 0;return k`${S}delete from ${o}${$}${A}`}buildUpdateSet(o,T){let f=o[I.Symbol.Columns],n=Object.keys(f).filter((A)=>T[A]!==void 0||f[A]?.onUpdateFn!==void 0),S=n.length;return k.join(n.flatMap((A,$)=>{let F=f[A],J=T[A]??k.param(F.onUpdateFn(),F),R=k`${k.identifier(this.casing.getColumnCasing(F))} = ${J}`;if($<S-1)return[R,k.raw(", ")];return[R]}))}buildUpdateQuery({table:o,set:T,where:f,returning:n,withList:S,from:A,joins:$}){let F=this.buildWithCTE(S),J=o[co.Symbol.Name],R=o[co.Symbol.Schema],M=o[co.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),D=A&&k.join([k.raw(" from "),this.buildFromTable(A)]),K=this.buildJoins($),L=n?k` returning ${this.buildSelection(n,{isSingleTable:!A})}`:void 0,h=f?k` where ${f}`:void 0;return k`${F}update ${w} set ${X}${D}${K}${h}${L}`}buildSelection(o,{isSingleTable:T=!1}={}){let f=o.length,n=o.flatMap(({field:S},A)=>{let $=[];if(H(S,j.Aliased)&&S.isSelectionField)$.push(k.identifier(S.fieldAlias));else if(H(S,j.Aliased)||H(S,j)){let F=H(S,j.Aliased)?S.sql:S;if(T)$.push(new j(F.queryChunks.map((J)=>{if(H(J,V))return k.identifier(this.casing.getColumnCasing(J));return J})));else $.push(F);if(H(S,j.Aliased))$.push(k` as ${k.identifier(S.fieldAlias)}`)}else if(H(S,_o))if(T)$.push(k.identifier(this.casing.getColumnCasing(S)));else $.push(S);if(A<f-1)$.push(k`, `);return $});return k.join(n)}buildJoins(o){if(!o||o.length===0)return;let T=[];for(let[f,n]of o.entries()){if(f===0)T.push(k` `);let S=n.table,A=n.lateral?k` lateral`:void 0;if(H(S,co)){let $=S[co.Symbol.Name],F=S[co.Symbol.Schema],J=S[co.Symbol.OriginalName],R=$===J?void 0:n.alias;T.push(k`${k.raw(n.joinType)} join${A} ${F?k`${k.identifier(F)}.`:void 0}${k.identifier(J)}${R&&k` ${k.identifier(R)}`} on ${n.on}`)}else if(H(S,ST)){let $=S[Ho].name,F=S[Ho].schema,J=S[Ho].originalName,R=$===J?void 0:n.alias;T.push(k`${k.raw(n.joinType)} join${A} ${F?k`${k.identifier(F)}.`:void 0}${k.identifier(J)}${R&&k` ${k.identifier(R)}`} on ${n.on}`)}else T.push(k`${k.raw(n.joinType)} join${A} ${S} on ${n.on}`);if(f<o.length-1)T.push(k` `)}return k.join(T)}buildFromTable(o){if(H(o,I)&&o[I.Symbol.OriginalName]!==o[I.Symbol.Name]){let T=k`${k.identifier(o[I.Symbol.OriginalName])}`;if(o[I.Symbol.Schema])T=k`${k.identifier(o[I.Symbol.Schema])}.${T}`;return k`${T} ${k.identifier(o[I.Symbol.Name])}`}return o}buildSelectQuery({withList:o,fields:T,fieldsFlat:f,where:n,having:S,table:A,joins:$,orderBy:F,groupBy:J,limit:R,offset:M,lockingClause:_,distinct:w,setOperators:X}){let D=f??wT(T);for(let a of D)if(H(a.field,_o)&&qo(a.field.table)!==(H(A,bo)?A._.alias:H(A,hn)?A[Ho].name:H(A,j)?void 0:qo(A))&&!((ko)=>$?.some(({alias:Lo})=>Lo===(ko[I.Symbol.IsAlias]?qo(ko):ko[I.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(D,{isSingleTable:K}),P=this.buildFromTable(A),Y=this.buildJoins($),z=n?k` where ${n}`:void 0,U=S?k` having ${S}`:void 0,Q;if(F&&F.length>0)Q=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}${z}${v}${U}${Q}${l}${G}${s}`;if(X.length>0)return this.buildSetOperations(r,X);return r}buildSetOperations(o,T){let[f,...n]=T;if(!f)throw new Error("Cannot pass undefined values to any set operator");if(n.length===0)return this.buildSetOperationQuery({leftSelect:o,setOperator:f});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:o,setOperator:f}),n)}buildSetOperationQuery({leftSelect:o,setOperator:{type:T,isAll:f,rightSelect:n,limit:S,orderBy:A,offset:$}}){let F=k`(${o.getSQL()}) `,J=k`(${n.getSQL()})`,R;if(A&&A.length>0){let X=[];for(let D of A)if(H(D,V))X.push(k.identifier(D.name));else if(H(D,j)){for(let K=0;K<D.queryChunks.length;K++){let L=D.queryChunks[K];if(H(L,V))D.queryChunks[K]=k.identifier(L.name)}X.push(k`${D}`)}else X.push(k`${D}`);R=k` order by ${k.join(X,k`, `)} `}let M=typeof S==="object"||typeof S==="number"&&S>=0?k` limit ${S}`: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:n,withList:S,select:A,overridingSystemValue_:$}){let F=[],J=o[I.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,j))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,z]of R){let U=q[Y];if(U===void 0||H(U,RT)&&U.value===void 0)if(z.defaultFn!==void 0){let Q=z.defaultFn(),v=H(Q,j)?Q:k.param(Q,z);P.push(v)}else if(!z.default&&z.onUpdateFn!==void 0){let Q=z.onUpdateFn(),v=H(Q,j)?Q:k.param(Q,z);P.push(v)}else P.push(k`default`);else P.push(U)}if(F.push(P),h<L.length-1)F.push(k`, `)}}let _=this.buildWithCTE(S),w=k.join(F),X=n?k` returning ${this.buildSelection(n,{isSingleTable:!0})}`:void 0,D=f?k` on conflict ${f}`:void 0,K=$===!0?k`overriding system value `:void 0;return k`${_}insert into ${o} ${M} ${K}${w}${D}${X}`}buildRefreshMaterializedViewQuery({view:o,concurrently:T,withNoData:f}){let n=T?k` concurrently`:void 0,S=f?k` with no data`:void 0;return k`refresh materialized view${n} ${o}${S}`}prepareTyping(o){if(H(o,zS)||H(o,tS))return"json";else if(H(o,QS))return"decimal";else if(H(o,DS))return"time";else if(H(o,US)||H(o,VS))return"timestamp";else if(H(o,GS)||H(o,YS))return"date";else if(H(o,BS))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:n,tableConfig:S,queryConfig:A,tableAlias:$,nestedQueryRelation:F,joinOn:J}){let R=[],M,_,w=[],X,D=[];if(A===!0)R=Object.entries(S.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(S.columns).map(([U,Q])=>[U,CT(Q,$)]));if(A.where){let U=typeof A.where==="function"?A.where(L,g0()):A.where;X=U&&Qn(U,$)}let h=[],q=[];if(A.columns){let U=!1;for(let[Q,v]of Object.entries(A.columns)){if(v===void 0)continue;if(Q in S.columns){if(!U&&v===!0)U=!0;q.push(Q)}}if(q.length>0)q=U?q.filter((Q)=>A.columns?.[Q]===!0):Object.keys(S.columns).filter((Q)=>!q.includes(Q))}else q=Object.keys(S.columns);for(let U of q){let Q=S.columns[U];h.push({tsKey:U,value:Q})}let P=[];if(A.with)P=Object.entries(A.with).filter((U)=>!!U[1]).map(([U,Q])=>({tsKey:U,queryConfig:Q,relation:S.relations[U]}));let Y;if(A.extras){Y=typeof A.extras==="function"?A.extras(L,{sql:k}):A.extras;for(let[U,Q]of Object.entries(Y))h.push({tsKey:U,value:PA(Q,$)})}for(let{tsKey:U,value:Q}of h)R.push({dbKey:H(Q,j.Aliased)?Q.fieldAlias:S.columns[U].name,tsKey:U,field:H(Q,_o)?CT(Q,$):Q,relationTableTsKey:void 0,isJson:!1,selection:[]});let z=typeof A.orderBy==="function"?A.orderBy(L,d0()):A.orderBy??[];if(!Array.isArray(z))z=[z];w=z.map((U)=>{if(H(U,_o))return CT(U,$);return Qn(U,$)}),M=A.limit,_=A.offset;for(let{tsKey:U,queryConfig:Q,relation:v}of P){let l=u0(T,f,v),G=Of(v.referencedTable),s=f[G],r=`${$}_${U}`,a=Dn(...l.fields.map((fT,IT)=>HS(CT(l.references[IT],r),CT(fT,$)))),ko=this.buildRelationalQueryWithoutPK({fullSchema:o,schema:T,tableNamesMap:f,table:o[s],tableConfig:T[s],queryConfig:H(v,aT)?Q===!0?{limit:1}:{...Q,limit:1}:Q,tableAlias:r,joinOn:a,nestedQueryRelation:v}),Lo=k`${k.identifier(r)}.${k.identifier("data")}`.as(U);D.push({on:k`true`,table:new bo(ko.sql,{},r),alias:r,joinType:"left",lateral:!0}),R.push({dbKey:U,tsKey:U,field:Lo,relationTableTsKey:s,isJson:!0,selection:ko.selection})}}if(R.length===0)throw new XS({message:`No fields selected for table "${S.tsName}" ("${$}")`});let K;if(X=Dn(J,X),F){let L=k`json_build_array(${k.join(R.map(({field:P,tsKey:Y,isJson:z})=>z?k`${k.identifier(`${$}_${Y}`)}.${k.identifier("data")}`:H(P,j.Aliased)?P.sql:P),k`, `)})`;if(H(F,Ln))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:S.tsName,selection:R}];if(M!==void 0||_!==void 0||w.length>0)K=this.buildSelectQuery({table:yS(n,$),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=yS(n,$);K=this.buildSelectQuery({table:H(K,co)?K:new bo(K,{},$),fields:{},fieldsFlat:h.map(({field:P})=>({path:[],field:H(P,_o)?CT(P,$):P})),joins:D,where:X,limit:M,offset:_,orderBy:w,setOperators:[]})}else K=this.buildSelectQuery({table:yS(n,$),fields:{},fieldsFlat:R.map(({field:L})=>({path:[],field:H(L,_o)?CT(L,$):L})),joins:D,where:X,limit:M,offset:_,orderBy:w,setOperators:[]});return{tableTsKey:S.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,n;if(this.fields)n=this.fields;else if(H(f,bo))n=Object.fromEntries(Object.keys(f._.selectedFields).map((S)=>[S,f[S]]));else if(H(f,hn))n=f[Ho].selectedFields;else if(H(f,j))n={};else n=eJ(f);return new H$({table:f,fields:n,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:n,dialect:S,withList:A,distinct:$}){super();this.config={withList:A,table:o,fields:{...T},distinct:$,setOperators:[]},this.isPartialSelect=f,this.session=n,this.dialect=S,this._={selectedFields:T},this.tableName=rT(o),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}createJoin(o){return(T,f)=>{let n=this.tableName,S=rT(T);if(typeof S==="string"&&this.config.joins?.some((A)=>A.alias===S))throw new Error(`Alias "${S}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof n==="string")this.config.fields={[n]:this.config.fields};if(typeof S==="string"&&!H(T,j)){let A=H(T,bo)?T._.selectedFields:H(T,ST)?T[Ho].selectedFields:T[I.Symbol.Columns];this.config.fields[S]=A}}if(typeof f==="function")f=f(new Proxy(this.config.fields,new Do({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];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(([A])=>[A,!1])),this.joinsNotNullableMap[S]=!0;break}case"inner":{this.joinsNotNullableMap[S]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([A])=>[A,!1])),this.joinsNotNullableMap[S]=!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 n=typeof f==="function"?f(rO()):f;if(!Un(this.getSelectedFields(),n.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:n}),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 Do({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=o,this}having(o){if(typeof o==="function")o=o(new Proxy(this.config.fields,new Do({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 Do({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 Do({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 Do({alias:o,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new Do({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:n,joinsNotNullableMap:S,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(n.sqlToQuery(this.getSQL()),$,o,!0);return F.joinsNotNullableMap=S,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,n,...S)=>{let A=[n,...S].map(($)=>({type:o,isAll:T,rightSelect:$}));for(let $ of A)if(!Un(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:pO,unionAll:cO,intersect:ZO,intersectAll:PO,except:iO,exceptAll:gO}),pO=uf("union",!1),cO=uf("union",!0),ZO=uf("intersect",!1),PO=uf("intersect",!0),iO=uf("except",!1),gO=uf("except",!0);class bn{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:(S)=>{if(typeof S==="function")S=S(f);return new Proxy(new En(S.getSQL(),T??("getSelectedFields"in S?S.getSelectedFields()??{}:{}),o,!0),new Do({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 n(A){return new TT({fields:A??void 0,session:void 0,dialect:T.getDialect(),distinct:!0})}function S(A,$){return new TT({fields:$??void 0,session:void 0,dialect:T.getDialect(),distinct:{on:A}})}return{select:f,selectDistinct:n,selectDistinctOn:S}}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 cS{constructor(o,T,f,n,S){this.table=o,this.session=T,this.dialect=f,this.withList=n,this.overridingSystemValue_=S}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 n={},S=this.table[I.Symbol.Columns];for(let A of Object.keys(f)){let $=f[A];n[A]=H($,j)?$:new RT($,S[A])}return n});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 bn):o;if(!H(T,j)&&!Un(this.table[_S],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,n,S,A,$){super();this.session=f,this.dialect=n,this.config={table:o,values:T,withList:S,select:A,overridingSystemValue_:$}}static[O]="PgInsert";config;returning(o=this.config.table[I.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((n)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(n))).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,n=o.setWhere?k` where ${o.setWhere}`:void 0,S=this.dialect.buildUpdateSet(this.config.table,KS(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 ${S}${T}${n}`,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 Do({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 ZS{constructor(o,T,f,n){this.table=o,this.session=T,this.dialect=f,this.withList=n}static[O]="PgUpdateBuilder";authToken;setToken(o){return this.authToken=o,this}set(o){return new K1(this.table,KS(this.table,o),this.session,this.dialect,this.withList).setToken(this.authToken)}}class K1 extends oT{constructor(o,T,f,n,S){super();this.session=f,this.dialect=n,this.config={set:T,table:o,withList:S,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,co))return o[I.Symbol.Columns];else if(H(o,bo))return o._.selectedFields;return o[Ho].selectedFields}createJoin(o){return(T,f)=>{let n=rT(T);if(typeof n==="string"&&this.config.joins.some((S)=>S.alias===n))throw new Error(`Alias "${n}" is already used in this query`);if(typeof f==="function"){let S=this.config.from&&!H(this.config.from,j)?this.getTableLikeFields(this.config.from):void 0;f=f(new Proxy(this.config.table[I.Symbol.Columns],new Do({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),S&&new Proxy(S,new Do({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}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(([S])=>[S,!1])),this.joinsNotNullableMap[n]=!0;break}case"inner":{this.joinsNotNullableMap[n]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([S])=>[S,!1])),this.joinsNotNullableMap[n]=!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[I.Symbol.Columns]),this.config.from){let T=rT(this.config.from);if(typeof T==="string"&&this.config.from&&!H(this.config.from,j)){let f=this.getTableLikeFields(this.config.from);o[T]=f}for(let f of this.config.joins){let n=rT(f.table);if(typeof n==="string"&&!H(f.table,j)){let S=this.getTableLikeFields(f.table);o[n]=S}}}}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 Do({alias:qo(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class xn extends j{constructor(o){super(xn.buildEmbeddedCount(o.source,o.filters).queryChunks);this.params=o,this.mapWith(Number),this.session=o.session,this.sql=xn.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,n,S,A,$){this.fullSchema=o,this.schema=T,this.tableNamesMap=f,this.table=n,this.tableConfig=S,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,n,S,A,$,F,J){super();this.fullSchema=o,this.schema=T,this.tableNamesMap=f,this.table=n,this.tableConfig=S,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,(n,S)=>{let A=n.map(($)=>LS(this.schema,this.tableConfig,$,T.selection,S));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 t$ extends oT{constructor(o,T,f,n){super();this.execute=o,this.sql=T,this.query=f,this.mapBatchResult=n}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 vn{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[n,S]of Object.entries(this._.schema))this.query[n]=new E$(f.fullSchema,this._.schema,this._.tableNamesMap,f.fullSchema[n],S,o,T)}static[O]="PgDatabase";query;$with=(o,T)=>{let f=this;return{as:(S)=>{if(typeof S==="function")S=S(new bn(f.dialect));return new Proxy(new En(S.getSQL(),T??("getSelectedFields"in S?S.getSelectedFields()??{}:{}),o,!0),new Do({alias:o,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(o,T){return new xn({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 n(J){return new TT({fields:J??void 0,session:T.session,dialect:T.dialect,withList:o,distinct:!0})}function S(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 ZS(J,T.session,T.dialect,o)}function $(J){return new cS(J,T.session,T.dialect,o)}function F(J){return new pS(J,T.session,T.dialect,o)}return{select:f,selectDistinct:n,selectDistinctOn:S,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 ZS(o,this.session,this.dialect)}insert(o){return new cS(o,this.session,this.dialect)}delete(o){return new pS(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),n=this.session.prepareQuery(f,void 0,void 0,!1);return new t$(()=>n.execute(void 0,this.authToken),T,f,(S)=>n.mapResult(S,!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 PS(o.map((T)=>{if(H(T,j))return T;T=T;let f=new Yn(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 PS(o.map((T)=>{if(H(T,j))return T;T=T;let f=new Yn(T.name,!!T.keyAsName,T.columnType,T.indexConfig);return T.indexConfig=T.defaultConfig,f}),this.unique,!0,this.name)}using(o,...T){return new PS(T.map((f)=>{if(H(f,j))return f;f=f;let n=new Yn(f.name,!!f.keyAsName,f.columnType,f.indexConfig);return f.indexConfig=JSON.parse(JSON.stringify(f.defaultConfig)),n}),this.unique,!0,this.name,o)}}class PS{static[O]="PgIndexBuilder";config;constructor(o,T,f,n,S="btree"){this.config={name:n,columns:o,unique:T,only:f,method:S}}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 z$(o){return new G1(!0,o)}class Q${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 D${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 U$ extends vn{constructor(o,T,f,n=0){super(o,T,f);this.schema=f,this.nestedIndex=n}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 Q${constructor(o,T,f,n,S,A,$){super({sql:T,params:f});this.client=o,this.queryString=T,this.params=f,this.logger=n,this.fields=S,this._isResponseInArrayMode=A,this.customResultMapper=$}static[O]="PostgresJsPreparedQuery";async execute(o={}){return wo.startActiveSpan("drizzle.execute",async(T)=>{let f=ZA(this.params,o);T?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(f)}),this.logger.logQuery(this.queryString,f);let{fields:n,queryString:S,client:A,joinsNotNullableMap:$,customResultMapper:F}=this;if(!n&&!F)return wo.startActiveSpan("drizzle.driver.execute",()=>{return A.unsafe(S,f)});let J=await wo.startActiveSpan("drizzle.driver.execute",()=>{return T?.setAttributes({"drizzle.query.text":S,"drizzle.query.params":JSON.stringify(f)}),A.unsafe(S,f).values()});return wo.startActiveSpan("drizzle.mapResponse",()=>{return F?F(J):J.map((R)=>lJ(n,R,$))})})}all(o={}){return wo.startActiveSpan("drizzle.execute",async(T)=>{let f=ZA(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 qn extends D${constructor(o,T,f,n={}){super(T);this.client=o,this.schema=f,this.options=n,this.logger=n.logger??new dA}static[O]="PostgresJsSession";logger;prepareQuery(o,T,f,n,S){return new E1(this.client,o.sql,o.params,this.logger,T,n,S)}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 n=new qn(f,this.dialect,this.schema,this.options),S=new V$(this.dialect,n,this.schema);if(T)await S.setTransaction(T);return o(S)})}}class V$ extends U${constructor(o,T,f,n=0){super(o,T,f,n);this.session=T}static[O]="PostgresJsTransaction";transaction(o){return this.session.client.savepoint((T)=>{let f=new qn(T,this.dialect,this.schema,this.session.options),n=new V$(this.dialect,f,this.schema);return o(n)})}}class t1 extends vn{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 n=new Xf({casing:T.casing}),S;if(T.logger===!0)S=new gA;else if(T.logger!==!1)S=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 qn(o,n,A,{logger:S}),F=new t1(n,$,A);return F.$client=o,F}function iS(...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,...n}=o[0];if(f)return ef(f,n);if(typeof T==="object"&&T.url!==void 0){let{url:A,...$}=T,F=lf(A,$);return ef(F,n)}let S=lf(T);return ef(S,n)}return ef(o[0],o[1])}((o)=>{function T(f){return ef({options:{parsers:{},serializers:{}}},f)}o.mock=T})(iS||(iS={}));var L$={};VM(L$,{users:()=>Hf,userChanges:()=>lO,untrackedUserColumnNames:()=>dO,twoFactorMethod:()=>V1,trackedUserColumnName:()=>U1,trackableUserColumnNames:()=>D1,role:()=>Q1,players:()=>B$,passwordResetAttempts:()=>eO,loginHistory:()=>uO,games:()=>gS,banishedIps:()=>sO});function z1(o){return k`lower(${o})`}var Q1=OS("role",["admin","user"]),Hf=sT("users",{id:MT().primaryKey().defaultRandom(),username:po({length:16}).notNull(),email:po({length:254}).notNull(),hash:po({length:64}).notNull(),salt:po({length:36}).notNull(),createdAt:QT({withTimezone:!0}).notNull().defaultNow(),createdIp:po({length:45}).notNull(),isActive:Vn().notNull().default(!1),verifiedAt:QT({withTimezone:!0}),userRole:Q1().default("user")},(o)=>[z$("usernameUniqueIndex").on(z1(o.username)),z$("emailUniqueIndex").on(z1(o.email))]),dO=["id","createdAt","createdIp","isActive","salt","verifiedAt"],D1=["username","email","hash","userRole"],U1=OS("trackedUserColumnName",D1),lO=sT("userChanges",{id:MT().primaryKey().defaultRandom(),userId:MT().notNull().references(()=>Hf.id),changedAt:QT({withTimezone:!0}).notNull().defaultNow(),changedIp:po({length:45}).notNull(),changedColumn:U1().notNull(),oldValue:po({length:255}),newValue:po({length:255})}),gS=sT("games",{id:MT().primaryKey().defaultRandom()}),B$=sT("players",{userId:MT().notNull().references(()=>Hf.id),gameId:MT().notNull().references(()=>gS.id),score:ES().notNull()},(o)=>[Z0({name:"players_userId_gameId_pk",columns:[o.userId,o.gameId]})]),uO=sT("loginHistory",{id:MT().primaryKey().defaultRandom(),userId:MT().references(()=>Hf.id),loginTime:QT({withTimezone:!0}).notNull().defaultNow(),ipAddress:po({length:45}).notNull(),userAgent:po({length:1024}),successful:Vn().notNull().default(!1)}),V1=OS("twoFactorMethod",["email","phone"]),eO=sT("passwordResetAttempts",{id:MT().primaryKey().defaultRandom(),userId:MT().notNull().references(()=>Hf.id),requestedIp:po({length:45}).notNull(),requestedAt:QT({withTimezone:!0}).notNull().defaultNow(),succeededIp:po({length:45}),succeededAt:QT({withTimezone:!0}),verificationMethod:V1().notNull()}),sO=sT("banishedIps",{ip:po({length:45}).primaryKey(),reason:po({length:2048}).notNull(),banishedAt:QT({withTimezone:!0}).notNull().defaultNow(),banishedUntil:QT({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(gS),qo(B$)];await this.sql`SELECT create_notify_triggers(${this.sql.array(o)})`,await this.sql.listen("table_update",(T)=>{let f=T.split(","),n=f[0],S=f[1],A=`${n}("${S}")`;if(this.observers.has(A))this.observers.get(A).next(A)})}constructor(o=!1,T={host:tT.POSTGRES_HOST,port:tT.POSTGRES_PORT,user:tT.POSTGRES_USER,password:tT.POSTGRES_PASSWORD,database:tT.POSTGRES_DATABASE}){this.options=T,this.sql=lf(T),this.drizzle=iS(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 dS={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"},m$=P$(dS).map(([o])=>Yo.literal(Number(o))),ok=Yo.union([m$[0],m$[1],...m$]),B1=Yo.tuple([ok,Yo.string()]);var j$=new zA,{logger:$T}=j$;Object.assign(console,$T,{log:$T.info});$T.info("ready");var I$=C1(import.meta.dir,"..","app"),$z=new C$({logQuery(o,T){$T.info("\uD83D\uDCDD query",o,T)}});nk({hostname:"0.0.0.0",port:tT.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(I$,"index.html")));if(f.pathname==="/index.html")return Response.redirect("/");let n=Tk(I$,f.pathname),S=fk(n);if(!S.startsWith(I$))throw[403,"Access Denied"];if(!await L1(S).exists())return Response.redirect("/");return new Response(L1(S))}catch(T){let f=B1.safeParse(T);if(f.success){let[n,S]=f.data,$=`${dS[n]}. ${S}`;return $T.info(`\u274C ${n}: ${$}`),new Response($,{status:n})}if(T instanceof Error)$T.error(T.message);else{let n=Df(T);$T.error("frontend server threw",n)}return new Response(dS[500],{status:500})}}});function lS(){$T.info("\uD83D\uDEEC frontend server exiting"),process.exit(0)}process.on("SIGINT",()=>{$T.info("\u2757 received SIGINT; exiting gracefully"),lS()});process.on("SIGTERM",()=>{$T.info("\u2757 received SIGTERM; exiting gracefully"),lS()});process.on("exit",()=>{$T.info("\u2757 received exit; exiting gracefully"),lS()});j$.on("timeToStop",()=>{$T.info('\u2757 backend server received signal "timeToStop"; exiting gracefully'),lS()});$T.info(`\uD83D\uDEEB frontend server running at http://localhost:${tT.FRONTEND_PORT}/`);j$.emit("alive");
43
+ `;await T.execute(k`CREATE SCHEMA IF NOT EXISTS ${k.identifier(S)}`),await T.execute(A);let F=(await T.all(k`select id, hash, created_at from ${k.identifier(S)}.${k.identifier(n)} 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(S)}.${k.identifier(n)} ("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,n]of o.entries())if(T.push(k`${k.identifier(n._.alias)} as (${n._.sql})`),f<o.length-1)T.push(k`, `);return T.push(k` `),k.join(T)}buildDeleteQuery({table:o,where:T,returning:f,withList:n}){let S=this.buildWithCTE(n),A=f?k` returning ${this.buildSelection(f,{isSingleTable:!0})}`:void 0,$=T?k` where ${T}`:void 0;return k`${S}delete from ${o}${$}${A}`}buildUpdateSet(o,T){let f=o[I.Symbol.Columns],n=Object.keys(f).filter((A)=>T[A]!==void 0||f[A]?.onUpdateFn!==void 0),S=n.length;return k.join(n.flatMap((A,$)=>{let F=f[A],J=T[A]??k.param(F.onUpdateFn(),F),R=k`${k.identifier(this.casing.getColumnCasing(F))} = ${J}`;if($<S-1)return[R,k.raw(", ")];return[R]}))}buildUpdateQuery({table:o,set:T,where:f,returning:n,withList:S,from:A,joins:$}){let F=this.buildWithCTE(S),J=o[co.Symbol.Name],R=o[co.Symbol.Schema],M=o[co.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),D=A&&k.join([k.raw(" from "),this.buildFromTable(A)]),K=this.buildJoins($),L=n?k` returning ${this.buildSelection(n,{isSingleTable:!A})}`:void 0,h=f?k` where ${f}`:void 0;return k`${F}update ${w} set ${X}${D}${K}${h}${L}`}buildSelection(o,{isSingleTable:T=!1}={}){let f=o.length,n=o.flatMap(({field:S},A)=>{let $=[];if(H(S,j.Aliased)&&S.isSelectionField)$.push(k.identifier(S.fieldAlias));else if(H(S,j.Aliased)||H(S,j)){let F=H(S,j.Aliased)?S.sql:S;if(T)$.push(new j(F.queryChunks.map((J)=>{if(H(J,V))return k.identifier(this.casing.getColumnCasing(J));return J})));else $.push(F);if(H(S,j.Aliased))$.push(k` as ${k.identifier(S.fieldAlias)}`)}else if(H(S,_o))if(T)$.push(k.identifier(this.casing.getColumnCasing(S)));else $.push(S);if(A<f-1)$.push(k`, `);return $});return k.join(n)}buildJoins(o){if(!o||o.length===0)return;let T=[];for(let[f,n]of o.entries()){if(f===0)T.push(k` `);let S=n.table,A=n.lateral?k` lateral`:void 0;if(H(S,co)){let $=S[co.Symbol.Name],F=S[co.Symbol.Schema],J=S[co.Symbol.OriginalName],R=$===J?void 0:n.alias;T.push(k`${k.raw(n.joinType)} join${A} ${F?k`${k.identifier(F)}.`:void 0}${k.identifier(J)}${R&&k` ${k.identifier(R)}`} on ${n.on}`)}else if(H(S,ST)){let $=S[Ho].name,F=S[Ho].schema,J=S[Ho].originalName,R=$===J?void 0:n.alias;T.push(k`${k.raw(n.joinType)} join${A} ${F?k`${k.identifier(F)}.`:void 0}${k.identifier(J)}${R&&k` ${k.identifier(R)}`} on ${n.on}`)}else T.push(k`${k.raw(n.joinType)} join${A} ${S} on ${n.on}`);if(f<o.length-1)T.push(k` `)}return k.join(T)}buildFromTable(o){if(H(o,I)&&o[I.Symbol.OriginalName]!==o[I.Symbol.Name]){let T=k`${k.identifier(o[I.Symbol.OriginalName])}`;if(o[I.Symbol.Schema])T=k`${k.identifier(o[I.Symbol.Schema])}.${T}`;return k`${T} ${k.identifier(o[I.Symbol.Name])}`}return o}buildSelectQuery({withList:o,fields:T,fieldsFlat:f,where:n,having:S,table:A,joins:$,orderBy:F,groupBy:J,limit:R,offset:M,lockingClause:_,distinct:w,setOperators:X}){let D=f??wT(T);for(let a of D)if(H(a.field,_o)&&qo(a.field.table)!==(H(A,bo)?A._.alias:H(A,hn)?A[Ho].name:H(A,j)?void 0:qo(A))&&!((ko)=>$?.some(({alias:Lo})=>Lo===(ko[I.Symbol.IsAlias]?qo(ko):ko[I.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(D,{isSingleTable:K}),P=this.buildFromTable(A),G=this.buildJoins($),z=n?k` where ${n}`:void 0,U=S?k` having ${S}`:void 0,Q;if(F&&F.length>0)Q=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=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}${G}${z}${v}${U}${Q}${l}${E}${s}`;if(X.length>0)return this.buildSetOperations(r,X);return r}buildSetOperations(o,T){let[f,...n]=T;if(!f)throw new Error("Cannot pass undefined values to any set operator");if(n.length===0)return this.buildSetOperationQuery({leftSelect:o,setOperator:f});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:o,setOperator:f}),n)}buildSetOperationQuery({leftSelect:o,setOperator:{type:T,isAll:f,rightSelect:n,limit:S,orderBy:A,offset:$}}){let F=k`(${o.getSQL()}) `,J=k`(${n.getSQL()})`,R;if(A&&A.length>0){let X=[];for(let D of A)if(H(D,V))X.push(k.identifier(D.name));else if(H(D,j)){for(let K=0;K<D.queryChunks.length;K++){let L=D.queryChunks[K];if(H(L,V))D.queryChunks[K]=k.identifier(L.name)}X.push(k`${D}`)}else X.push(k`${D}`);R=k` order by ${k.join(X,k`, `)} `}let M=typeof S==="object"||typeof S==="number"&&S>=0?k` limit ${S}`: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:n,withList:S,select:A,overridingSystemValue_:$}){let F=[],J=o[I.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,j))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[G,z]of R){let U=q[G];if(U===void 0||H(U,RT)&&U.value===void 0)if(z.defaultFn!==void 0){let Q=z.defaultFn(),v=H(Q,j)?Q:k.param(Q,z);P.push(v)}else if(!z.default&&z.onUpdateFn!==void 0){let Q=z.onUpdateFn(),v=H(Q,j)?Q:k.param(Q,z);P.push(v)}else P.push(k`default`);else P.push(U)}if(F.push(P),h<L.length-1)F.push(k`, `)}}let _=this.buildWithCTE(S),w=k.join(F),X=n?k` returning ${this.buildSelection(n,{isSingleTable:!0})}`:void 0,D=f?k` on conflict ${f}`:void 0,K=$===!0?k`overriding system value `:void 0;return k`${_}insert into ${o} ${M} ${K}${w}${D}${X}`}buildRefreshMaterializedViewQuery({view:o,concurrently:T,withNoData:f}){let n=T?k` concurrently`:void 0,S=f?k` with no data`:void 0;return k`refresh materialized view${n} ${o}${S}`}prepareTyping(o){if(H(o,zS)||H(o,tS))return"json";else if(H(o,QS))return"decimal";else if(H(o,DS))return"time";else if(H(o,US)||H(o,VS))return"timestamp";else if(H(o,ES)||H(o,GS))return"date";else if(H(o,BS))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:n,tableConfig:S,queryConfig:A,tableAlias:$,nestedQueryRelation:F,joinOn:J}){let R=[],M,_,w=[],X,D=[];if(A===!0)R=Object.entries(S.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(S.columns).map(([U,Q])=>[U,CT(Q,$)]));if(A.where){let U=typeof A.where==="function"?A.where(L,g0()):A.where;X=U&&Qn(U,$)}let h=[],q=[];if(A.columns){let U=!1;for(let[Q,v]of Object.entries(A.columns)){if(v===void 0)continue;if(Q in S.columns){if(!U&&v===!0)U=!0;q.push(Q)}}if(q.length>0)q=U?q.filter((Q)=>A.columns?.[Q]===!0):Object.keys(S.columns).filter((Q)=>!q.includes(Q))}else q=Object.keys(S.columns);for(let U of q){let Q=S.columns[U];h.push({tsKey:U,value:Q})}let P=[];if(A.with)P=Object.entries(A.with).filter((U)=>!!U[1]).map(([U,Q])=>({tsKey:U,queryConfig:Q,relation:S.relations[U]}));let G;if(A.extras){G=typeof A.extras==="function"?A.extras(L,{sql:k}):A.extras;for(let[U,Q]of Object.entries(G))h.push({tsKey:U,value:PA(Q,$)})}for(let{tsKey:U,value:Q}of h)R.push({dbKey:H(Q,j.Aliased)?Q.fieldAlias:S.columns[U].name,tsKey:U,field:H(Q,_o)?CT(Q,$):Q,relationTableTsKey:void 0,isJson:!1,selection:[]});let z=typeof A.orderBy==="function"?A.orderBy(L,d0()):A.orderBy??[];if(!Array.isArray(z))z=[z];w=z.map((U)=>{if(H(U,_o))return CT(U,$);return Qn(U,$)}),M=A.limit,_=A.offset;for(let{tsKey:U,queryConfig:Q,relation:v}of P){let l=u0(T,f,v),E=Of(v.referencedTable),s=f[E],r=`${$}_${U}`,a=Dn(...l.fields.map((fT,IT)=>HS(CT(l.references[IT],r),CT(fT,$)))),ko=this.buildRelationalQueryWithoutPK({fullSchema:o,schema:T,tableNamesMap:f,table:o[s],tableConfig:T[s],queryConfig:H(v,aT)?Q===!0?{limit:1}:{...Q,limit:1}:Q,tableAlias:r,joinOn:a,nestedQueryRelation:v}),Lo=k`${k.identifier(r)}.${k.identifier("data")}`.as(U);D.push({on:k`true`,table:new bo(ko.sql,{},r),alias:r,joinType:"left",lateral:!0}),R.push({dbKey:U,tsKey:U,field:Lo,relationTableTsKey:s,isJson:!0,selection:ko.selection})}}if(R.length===0)throw new XS({message:`No fields selected for table "${S.tsName}" ("${$}")`});let K;if(X=Dn(J,X),F){let L=k`json_build_array(${k.join(R.map(({field:P,tsKey:G,isJson:z})=>z?k`${k.identifier(`${$}_${G}`)}.${k.identifier("data")}`:H(P,j.Aliased)?P.sql:P),k`, `)})`;if(H(F,Ln))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:S.tsName,selection:R}];if(M!==void 0||_!==void 0||w.length>0)K=this.buildSelectQuery({table:yS(n,$),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=yS(n,$);K=this.buildSelectQuery({table:H(K,co)?K:new bo(K,{},$),fields:{},fieldsFlat:h.map(({field:P})=>({path:[],field:H(P,_o)?CT(P,$):P})),joins:D,where:X,limit:M,offset:_,orderBy:w,setOperators:[]})}else K=this.buildSelectQuery({table:yS(n,$),fields:{},fieldsFlat:R.map(({field:L})=>({path:[],field:H(L,_o)?CT(L,$):L})),joins:D,where:X,limit:M,offset:_,orderBy:w,setOperators:[]});return{tableTsKey:S.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,n;if(this.fields)n=this.fields;else if(H(f,bo))n=Object.fromEntries(Object.keys(f._.selectedFields).map((S)=>[S,f[S]]));else if(H(f,hn))n=f[Ho].selectedFields;else if(H(f,j))n={};else n=eJ(f);return new H$({table:f,fields:n,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:n,dialect:S,withList:A,distinct:$}){super();this.config={withList:A,table:o,fields:{...T},distinct:$,setOperators:[]},this.isPartialSelect=f,this.session=n,this.dialect=S,this._={selectedFields:T},this.tableName=rT(o),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}createJoin(o){return(T,f)=>{let n=this.tableName,S=rT(T);if(typeof S==="string"&&this.config.joins?.some((A)=>A.alias===S))throw new Error(`Alias "${S}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof n==="string")this.config.fields={[n]:this.config.fields};if(typeof S==="string"&&!H(T,j)){let A=H(T,bo)?T._.selectedFields:H(T,ST)?T[Ho].selectedFields:T[I.Symbol.Columns];this.config.fields[S]=A}}if(typeof f==="function")f=f(new Proxy(this.config.fields,new Do({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];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(([A])=>[A,!1])),this.joinsNotNullableMap[S]=!0;break}case"inner":{this.joinsNotNullableMap[S]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([A])=>[A,!1])),this.joinsNotNullableMap[S]=!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 n=typeof f==="function"?f(rO()):f;if(!Un(this.getSelectedFields(),n.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:n}),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 Do({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=o,this}having(o){if(typeof o==="function")o=o(new Proxy(this.config.fields,new Do({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 Do({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 Do({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 Do({alias:o,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new Do({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:n,joinsNotNullableMap:S,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(n.sqlToQuery(this.getSQL()),$,o,!0);return F.joinsNotNullableMap=S,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,n,...S)=>{let A=[n,...S].map(($)=>({type:o,isAll:T,rightSelect:$}));for(let $ of A)if(!Un(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:pO,unionAll:cO,intersect:ZO,intersectAll:PO,except:iO,exceptAll:gO}),pO=uf("union",!1),cO=uf("union",!0),ZO=uf("intersect",!1),PO=uf("intersect",!0),iO=uf("except",!1),gO=uf("except",!0);class bn{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:(S)=>{if(typeof S==="function")S=S(f);return new Proxy(new Yn(S.getSQL(),T??("getSelectedFields"in S?S.getSelectedFields()??{}:{}),o,!0),new Do({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 n(A){return new TT({fields:A??void 0,session:void 0,dialect:T.getDialect(),distinct:!0})}function S(A,$){return new TT({fields:$??void 0,session:void 0,dialect:T.getDialect(),distinct:{on:A}})}return{select:f,selectDistinct:n,selectDistinctOn:S}}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 cS{constructor(o,T,f,n,S){this.table=o,this.session=T,this.dialect=f,this.withList=n,this.overridingSystemValue_=S}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 n={},S=this.table[I.Symbol.Columns];for(let A of Object.keys(f)){let $=f[A];n[A]=H($,j)?$:new RT($,S[A])}return n});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 bn):o;if(!H(T,j)&&!Un(this.table[_S],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,n,S,A,$){super();this.session=f,this.dialect=n,this.config={table:o,values:T,withList:S,select:A,overridingSystemValue_:$}}static[O]="PgInsert";config;returning(o=this.config.table[I.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((n)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(n))).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,n=o.setWhere?k` where ${o.setWhere}`:void 0,S=this.dialect.buildUpdateSet(this.config.table,KS(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 ${S}${T}${n}`,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 Do({alias:qo(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class E$ 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 ZS{constructor(o,T,f,n){this.table=o,this.session=T,this.dialect=f,this.withList=n}static[O]="PgUpdateBuilder";authToken;setToken(o){return this.authToken=o,this}set(o){return new K1(this.table,KS(this.table,o),this.session,this.dialect,this.withList).setToken(this.authToken)}}class K1 extends oT{constructor(o,T,f,n,S){super();this.session=f,this.dialect=n,this.config={set:T,table:o,withList:S,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,co))return o[I.Symbol.Columns];else if(H(o,bo))return o._.selectedFields;return o[Ho].selectedFields}createJoin(o){return(T,f)=>{let n=rT(T);if(typeof n==="string"&&this.config.joins.some((S)=>S.alias===n))throw new Error(`Alias "${n}" is already used in this query`);if(typeof f==="function"){let S=this.config.from&&!H(this.config.from,j)?this.getTableLikeFields(this.config.from):void 0;f=f(new Proxy(this.config.table[I.Symbol.Columns],new Do({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),S&&new Proxy(S,new Do({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}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(([S])=>[S,!1])),this.joinsNotNullableMap[n]=!0;break}case"inner":{this.joinsNotNullableMap[n]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([S])=>[S,!1])),this.joinsNotNullableMap[n]=!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[I.Symbol.Columns]),this.config.from){let T=rT(this.config.from);if(typeof T==="string"&&this.config.from&&!H(this.config.from,j)){let f=this.getTableLikeFields(this.config.from);o[T]=f}for(let f of this.config.joins){let n=rT(f.table);if(typeof n==="string"&&!H(f.table,j)){let S=this.getTableLikeFields(f.table);o[n]=S}}}}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 Do({alias:qo(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class xn extends j{constructor(o){super(xn.buildEmbeddedCount(o.source,o.filters).queryChunks);this.params=o,this.mapWith(Number),this.session=o.session,this.sql=xn.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 Y${constructor(o,T,f,n,S,A,$){this.fullSchema=o,this.schema=T,this.tableNamesMap=f,this.table=n,this.tableConfig=S,this.dialect=A,this.session=$}static[O]="PgRelationalQueryBuilder";findMany(o){return new G$(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,o?o:{},"many")}findFirst(o){return new G$(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,o?{...o,limit:1}:{limit:1},"first")}}class G$ extends oT{constructor(o,T,f,n,S,A,$,F,J){super();this.fullSchema=o,this.schema=T,this.tableNamesMap=f,this.table=n,this.tableConfig=S,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,(n,S)=>{let A=n.map(($)=>LS(this.schema,this.tableConfig,$,T.selection,S));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 t$ extends oT{constructor(o,T,f,n){super();this.execute=o,this.sql=T,this.query=f,this.mapBatchResult=n}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 vn{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[n,S]of Object.entries(this._.schema))this.query[n]=new Y$(f.fullSchema,this._.schema,this._.tableNamesMap,f.fullSchema[n],S,o,T)}static[O]="PgDatabase";query;$with=(o,T)=>{let f=this;return{as:(S)=>{if(typeof S==="function")S=S(new bn(f.dialect));return new Proxy(new Yn(S.getSQL(),T??("getSelectedFields"in S?S.getSelectedFields()??{}:{}),o,!0),new Do({alias:o,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(o,T){return new xn({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 n(J){return new TT({fields:J??void 0,session:T.session,dialect:T.dialect,withList:o,distinct:!0})}function S(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 ZS(J,T.session,T.dialect,o)}function $(J){return new cS(J,T.session,T.dialect,o)}function F(J){return new pS(J,T.session,T.dialect,o)}return{select:f,selectDistinct:n,selectDistinctOn:S,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 ZS(o,this.session,this.dialect)}insert(o){return new cS(o,this.session,this.dialect)}delete(o){return new pS(o,this.session,this.dialect)}refreshMaterializedView(o){return new E$(o,this.session,this.dialect)}authToken;execute(o){let T=typeof o==="string"?k.raw(o):o.getSQL(),f=this.dialect.sqlToQuery(T),n=this.session.prepareQuery(f,void 0,void 0,!1);return new t$(()=>n.execute(void 0,this.authToken),T,f,(S)=>n.mapResult(S,!0))}transaction(o,T){return this.session.transaction(o,T)}}class E1{constructor(o,T){this.unique=o,this.name=T}static[O]="PgIndexBuilderOn";on(...o){return new PS(o.map((T)=>{if(H(T,j))return T;T=T;let f=new Gn(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 PS(o.map((T)=>{if(H(T,j))return T;T=T;let f=new Gn(T.name,!!T.keyAsName,T.columnType,T.indexConfig);return T.indexConfig=T.defaultConfig,f}),this.unique,!0,this.name)}using(o,...T){return new PS(T.map((f)=>{if(H(f,j))return f;f=f;let n=new Gn(f.name,!!f.keyAsName,f.columnType,f.indexConfig);return f.indexConfig=JSON.parse(JSON.stringify(f.defaultConfig)),n}),this.unique,!0,this.name,o)}}class PS{static[O]="PgIndexBuilder";config;constructor(o,T,f,n,S="btree"){this.config={name:n,columns:o,unique:T,only:f,method:S}}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 G1(this.config,o)}}class G1{static[O]="PgIndex";config;constructor(o,T){this.config={...o,table:T}}}function z$(o){return new E1(!0,o)}class Q${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 D${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 U$ extends vn{constructor(o,T,f,n=0){super(o,T,f);this.schema=f,this.nestedIndex=n}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 Y1 extends Q${constructor(o,T,f,n,S,A,$){super({sql:T,params:f});this.client=o,this.queryString=T,this.params=f,this.logger=n,this.fields=S,this._isResponseInArrayMode=A,this.customResultMapper=$}static[O]="PostgresJsPreparedQuery";async execute(o={}){return wo.startActiveSpan("drizzle.execute",async(T)=>{let f=ZA(this.params,o);T?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(f)}),this.logger.logQuery(this.queryString,f);let{fields:n,queryString:S,client:A,joinsNotNullableMap:$,customResultMapper:F}=this;if(!n&&!F)return wo.startActiveSpan("drizzle.driver.execute",()=>{return A.unsafe(S,f)});let J=await wo.startActiveSpan("drizzle.driver.execute",()=>{return T?.setAttributes({"drizzle.query.text":S,"drizzle.query.params":JSON.stringify(f)}),A.unsafe(S,f).values()});return wo.startActiveSpan("drizzle.mapResponse",()=>{return F?F(J):J.map((R)=>lJ(n,R,$))})})}all(o={}){return wo.startActiveSpan("drizzle.execute",async(T)=>{let f=ZA(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 qn extends D${constructor(o,T,f,n={}){super(T);this.client=o,this.schema=f,this.options=n,this.logger=n.logger??new dA}static[O]="PostgresJsSession";logger;prepareQuery(o,T,f,n,S){return new Y1(this.client,o.sql,o.params,this.logger,T,n,S)}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 n=new qn(f,this.dialect,this.schema,this.options),S=new V$(this.dialect,n,this.schema);if(T)await S.setTransaction(T);return o(S)})}}class V$ extends U${constructor(o,T,f,n=0){super(o,T,f,n);this.session=T}static[O]="PostgresJsTransaction";transaction(o){return this.session.client.savepoint((T)=>{let f=new qn(T,this.dialect,this.schema,this.session.options),n=new V$(this.dialect,f,this.schema);return o(n)})}}class t1 extends vn{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 n=new Xf({casing:T.casing}),S;if(T.logger===!0)S=new gA;else if(T.logger!==!1)S=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 qn(o,n,A,{logger:S}),F=new t1(n,$,A);return F.$client=o,F}function iS(...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,...n}=o[0];if(f)return ef(f,n);if(typeof T==="object"&&T.url!==void 0){let{url:A,...$}=T,F=lf(A,$);return ef(F,n)}let S=lf(T);return ef(S,n)}return ef(o[0],o[1])}((o)=>{function T(f){return ef({options:{parsers:{},serializers:{}}},f)}o.mock=T})(iS||(iS={}));var L$={};VM(L$,{users:()=>Hf,userChanges:()=>lO,untrackedUserColumnNames:()=>dO,twoFactorMethod:()=>V1,trackedUserColumnName:()=>U1,trackableUserColumnNames:()=>D1,role:()=>Q1,players:()=>B$,passwordResetAttempts:()=>eO,loginHistory:()=>uO,games:()=>gS,banishedIps:()=>sO});function z1(o){return k`lower(${o})`}var Q1=OS("role",["admin","user"]),Hf=sT("users",{id:MT().primaryKey().defaultRandom(),username:po({length:16}).notNull(),email:po({length:254}).notNull(),hash:po({length:64}).notNull(),salt:po({length:36}).notNull(),createdAt:QT({withTimezone:!0}).notNull().defaultNow(),createdIp:po({length:45}).notNull(),isActive:Vn().notNull().default(!1),verifiedAt:QT({withTimezone:!0}),userRole:Q1().default("user")},(o)=>[z$("usernameUniqueIndex").on(z1(o.username)),z$("emailUniqueIndex").on(z1(o.email))]),dO=["id","createdAt","createdIp","isActive","salt","verifiedAt"],D1=["username","email","hash","userRole"],U1=OS("trackedUserColumnName",D1),lO=sT("userChanges",{id:MT().primaryKey().defaultRandom(),userId:MT().notNull().references(()=>Hf.id),changedAt:QT({withTimezone:!0}).notNull().defaultNow(),changedIp:po({length:45}).notNull(),changedColumn:U1().notNull(),oldValue:po({length:255}),newValue:po({length:255})}),gS=sT("games",{id:MT().primaryKey().defaultRandom()}),B$=sT("players",{userId:MT().notNull().references(()=>Hf.id),gameId:MT().notNull().references(()=>gS.id),score:YS().notNull()},(o)=>[Z0({name:"players_userId_gameId_pk",columns:[o.userId,o.gameId]})]),uO=sT("loginHistory",{id:MT().primaryKey().defaultRandom(),userId:MT().references(()=>Hf.id),loginTime:QT({withTimezone:!0}).notNull().defaultNow(),ipAddress:po({length:45}).notNull(),userAgent:po({length:1024}),successful:Vn().notNull().default(!1)}),V1=OS("twoFactorMethod",["email","phone"]),eO=sT("passwordResetAttempts",{id:MT().primaryKey().defaultRandom(),userId:MT().notNull().references(()=>Hf.id),requestedIp:po({length:45}).notNull(),requestedAt:QT({withTimezone:!0}).notNull().defaultNow(),succeededIp:po({length:45}),succeededAt:QT({withTimezone:!0}),verificationMethod:V1().notNull()}),sO=sT("banishedIps",{ip:po({length:45}).primaryKey(),reason:po({length:2048}).notNull(),banishedAt:QT({withTimezone:!0}).notNull().defaultNow(),banishedUntil:QT({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(gS),qo(B$)];await this.sql`SELECT create_notify_triggers(${this.sql.array(o)})`,await this.sql.listen("table_update",(T)=>{let f=T.split(","),n=f[0],S=f[1],A=`${n}("${S}")`;if(this.observers.has(A))this.observers.get(A).next(A)})}constructor(o=!1,T={host:tT.POSTGRES_HOST,port:tT.POSTGRES_PORT,user:tT.POSTGRES_USER,password:tT.POSTGRES_PASSWORD,database:tT.POSTGRES_DATABASE}){this.options=T,this.sql=lf(T),this.drizzle=iS(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 dS={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"},m$=P$(dS).map(([o])=>Go.literal(Number(o))),ok=Go.union([m$[0],m$[1],...m$]),B1=Go.tuple([ok,Go.string()]);var j$=new zA,{logger:$T}=j$;Object.assign(console,$T,{log:$T.info});$T.info("ready");var I$=C1(import.meta.dir,"..","app"),$z=new C$({logQuery(o,T){$T.info("\uD83D\uDCDD query",o,T)}});nk({hostname:"0.0.0.0",port:tT.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(I$,"index.html")));if(f.pathname==="/index.html")return Response.redirect("/");let n=Tk(I$,f.pathname),S=fk(n);if(!S.startsWith(I$))throw[403,"Access Denied"];if(!await L1(S).exists())return Response.redirect("/");return new Response(L1(S))}catch(T){let f=B1.safeParse(T);if(f.success){let[n,S]=f.data,$=`${dS[n]}. ${S}`;return $T.info(`\u274C ${n}: ${$}`),new Response($,{status:n})}if(T instanceof Error)$T.error(T.message);else{let n=Df(T);$T.error("frontend server threw",n)}return new Response(dS[500],{status:500})}}});function lS(){$T.info("\uD83D\uDEEC frontend server exiting"),process.exit(0)}process.on("SIGINT",()=>{$T.info("\u2757 received SIGINT; exiting gracefully"),lS()});process.on("SIGTERM",()=>{$T.info("\u2757 received SIGTERM; exiting gracefully"),lS()});process.on("exit",()=>{$T.info("\u2757 received exit; exiting gracefully"),lS()});j$.on("timeToStop",()=>{$T.info('\u2757 backend server received signal "timeToStop"; exiting gracefully'),lS()});$T.info(`\uD83D\uDEEB frontend server running at http://localhost:${tT.FRONTEND_PORT}/`);j$.emit("alive");