tempest.games 0.1.30 → 0.1.31
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.
- package/CHANGELOG.md +7 -0
- package/app/assets/{index-Bi0ww1qK.js → index-BU9K6Wtr.js} +17 -17
- package/app/index.html +1 -1
- package/bin/backend.bun.js +27 -27
- package/bin/backend.worker.game.bun.js +10 -10
- package/bin/backend.worker.tribunal.bun.js +44 -44
- package/bin/frontend.bun.js +18 -18
- package/bin/setup-db.bun.js +50 -50
- package/package.json +9 -9
package/bin/frontend.bun.js
CHANGED
|
@@ -1,30 +1,30 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
var
|
|
4
|
-
|
|
5
|
-
|
|
3
|
+
var zO=Object.create;var{getPrototypeOf:QO,defineProperty:uA,getOwnPropertyNames:DO}=Object;var UO=Object.prototype.hasOwnProperty;var n_=(T,S,o)=>{o=T!=null?zO(QO(T)):{};let f=S||!T||!T.__esModule?uA(o,"default",{value:T,enumerable:!0}):o;for(let A of DO(T))if(!UO.call(f,A))uA(f,A,{get:()=>T[A],enumerable:!0});return f};var $_=(T,S)=>()=>(S||T((S={exports:{}}).exports,S),S.exports);var VO=(T,S)=>{for(var o in S)uA(T,o,{get:S[o],enumerable:!0,configurable:!0,set:(f)=>S[o]=()=>f})};var F_=import.meta.require;import{join as o_,normalize as f_,resolve as L1}from"path";function Zf(T=Math.random){return T().toString(36).slice(2)}class Tf extends Promise{fate;resolve;reject;done=!1;constructor(T){let S,o;super((f,A)=>{S=f,o=A});this.resolve=S,this.reject=o,this.use(T instanceof Promise?T:new Promise(T))}pass(T,S){if(T===this.fate)this.resolve(S),this.done=!0}fail(T,S){if(T===this.fate)this.reject(S),this.done=!0}use(T){if(T instanceof Promise){let S=T;this.fate=S,S.then((o)=>{this.pass(S,o)},(o)=>{this.fail(S,o)})}else this.resolve(T),this.fate=void 0}}function g$(T){return Object.entries(T)}var i$=(T,S,o=s.STORE)=>{return XS(o,{key:`${T.key}:JSON`,get:({get:f})=>S.toJson(f(T)),set:({set:f},A)=>{f(T,S.fromJson(A))}})};function L(T){while(T.child!==null)T=T.child;return T}class ST{Subscriber;subscribers=new Map;subscribe(T,S){return this.subscribers.set(T,S),()=>{this.unsubscribe(T)}}unsubscribe(T){this.subscribers.delete(T)}next(T){let S=this.subscribers.values();for(let o of S)o(T)}}class eA extends ST{state;constructor(T){super();this.state=T}next(T){this.state=T,super.next(T)}}function tS(T,S,o){let f={key:S.key,type:"atom_family"},A=T.families.get(S.key);if(A)T.logger.error("\u2757","atom_family",S.key,`Overwriting an existing ${LS(A)} "${A.key}" in store "${T.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let n=new ST,F=Object.assign((J)=>{let R=fT(J),O={key:S.key,subKey:R},k=`${S.key}(${R})`,y=L(T),H=S.default,E={key:k,default:H instanceof Function?H(J):H};if(S.effects)E.effects=S.effects(J);let G=fS(y,E,O);return n.next({type:"state_creation",token:G}),G},f,{subject:n,install:(J)=>tS(J,S),internalRoles:o});return T.families.set(S.key,F),T.defaults.set(S.key,S.default),f}function d$(T,S){if("mutable"in S)return Sf(T,S);return tS(T,S)}function hS(T,S,o){let f={key:S.key,type:"readonly_selector_family"},A=T.families.get(S.key);if(A)T.logger.error("\u2757","readonly_selector_family",S.key,`Overwriting an existing ${LS(A)} "${A.key}" in store "${T.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let n=new ST,F=Object.assign((J)=>{let R=fT(J),O={key:S.key,subKey:R},k=`${S.key}(${R})`,y=L(T),H=of(y,{key:k,get:S.get(J)},O);return n.next({type:"state_creation",token:H}),H},f,{internalRoles:o,subject:n,install:(J)=>hS(J,S),default:(J)=>{return S.get(J)({get:(...O)=>RT(T,...O),find:(O,k)=>g(T,O,k),seek:(O,k)=>cT(T,O,k),json:(O)=>NT(T,O)})}});return T.families.set(S.key,F),f}function ff(T,S){if("set"in S)return Af(T,S);return hS(T,S)}class cf{_buffer;_index=0;constructor(T){let S;if(typeof T==="number")S=T;else S=T.length;this._buffer=Array.from({length:S})}get buffer(){return this._buffer}get index(){return this._index}add(T){this._buffer[this._index]=T,this._index=(this._index+1)%this._buffer.length}copy(){let T=new cf([...this._buffer]);return T._index=this._index,T}}var BO={atom_family:"atom",mutable_atom_family:"mutable_atom",selector_family:"selector",readonly_selector_family:"readonly_selector",molecule_family:"molecule"};function l$(T,S){let o=fT(S),f=`${T.key}(${o})`,A=BO[T.type],n={key:f,type:A};return Object.assign(n,{family:{key:T.key,subKey:o}}),Object.assign(n,{counterfeit:!0}),n}function AS(T){let S={key:T.key,type:T.type};if("family"in T)S.family=T.family;return S}function Yo(T){return u$(s.STORE,T)}function oo(T){return d$(s.STORE,T)}function sA(...T){if(T.length===2)return RT(s.STORE,...T);return RT(s.STORE,...T)}var aA=(T)=>(S,o,f,A,...n)=>{console[T](`${S} ${o} "${f}" ${A}`,...n)},tO={error:aA("error"),info:aA("info"),warn:aA("warn")};class Tn{logLevel;filter;logger;constructor(T,S,o=tO){this.logLevel=T;this.filter=S;this.logger=o}error=(...T)=>{if((this.filter?.(...T)??!0)&&this.logLevel!==null)this.logger.error(...T)};info=(...T)=>{if((this.filter?.(...T)??!0)&&this.logLevel==="info")this.logger.info(...T)};warn=(...T)=>{if((this.filter?.(...T)??!0)&&this.logLevel!=="error"&&this.logLevel!==null)this.logger.warn(...T)}}var r_=Symbol("claim");class s${store;constructor(T=s.STORE){this.store=T,a$("root",T)}allocate(T,S,o){return fo(this.store,T,S,o)}fuse(T,S,o){return TF(this.store,T,S,o)}deallocate(T){Ao(this.store,T)}claim(T,S,o){return Eo(this.store,T,S,o)}}class Sn{store;realm;constructor(T=s.STORE){this.store=T,this.realm=new s$(T)}allocate(T,S,o){fo(this.store,T,S,o)}deallocate(T){Ao(this.store,T)}claim(T,S,o){Eo(this.store,T,S,o)}}function rf(T){return ff(s.STORE,T)}function mT(T){return"epoch"in T.transactionMeta}function OT(T){return"phase"in T.transactionMeta}var SF=(T)=>{let S=L(T);if(!OT(S)){T.logger.warn("\uD83D\uDC1E","transaction","???","abortTransaction called outside of a transaction. This is probably a bug in AtomIO.");return}T.logger.info("\uD83E\uDE82","transaction",S.transactionMeta.update.key,"Aborting transaction"),S.parent.child=null};var LO=(T)=>T[0].toUpperCase()+T.slice(1);function LS(T){return T.type.split("_").map(LO).join(" ")}class no extends Error{constructor(T,S){super(`${LS(T)} ${fT(T.key)} not found in store "${S.config.name}".`)}}function zo(T,S,o){return(...f)=>{let A=nT(T,o);if(A)return A.run(f,S);throw new no(T,o)}}var pf=(T)=>(S)=>T instanceof Function?T(S):T;var PS=(T,S)=>{if(S.valueMap.has(T.key))return S.logger.info("\uD83D\uDCD6",T.type,T.key,"reading cached value"),oF(T,S);if(T.type==="selector"||T.type==="readonly_selector")return S.logger.info("\uD83E\uDDEE",T.type,T.key,"computing value"),T.get();let o=T.default instanceof Function?T.default():T.default;return S.logger.info("\uD83D\uDC81","atom",T.key,"could not find cached value; using default",o),T.default instanceof Function?T.default():T.default};var fF=(T,S)=>{if(T.operation.open){let o=performance.now();return T.logger.info("\u2757",S.type,S.key,`deferring setState at T-${o} until setState for "${T.operation.token.key}" is done`),o}T.operation={open:!0,done:new Set,prev:new Map,time:Date.now(),token:S},T.logger.info("\u2B55",S.type,S.key,`operation start in store "${T.config.name}"${!OT(T)?"":` ${T.transactionMeta.phase} "${T.transactionMeta.update.key}"`}`)},AF=(T)=>{if(T.operation.open)T.logger.info("\uD83D\uDD34",T.operation.token.type,T.operation.token.key,`operation done in store "${T.config.name}"`);T.operation={open:!1},T.on.operationClose.next(T.operation)},nF=(T,S)=>{if(!T.operation.open)return T.logger.error("\uD83D\uDC1E","unknown",S,"isDone called outside of an operation. This is probably a bug in AtomIO."),!0;return T.operation.done.has(S)},Qo=(T,S)=>{if(!T.operation.open){T.logger.error("\uD83D\uDC1E","unknown",S,"markDone called outside of an operation. This is probably a bug in AtomIO.");return}T.operation.done.add(S)};var $F=(T,S,o)=>{switch(T.type){case"mutable_atom":o.logger.info("\uD83D\uDCE2",T.type,T.key,"is now (",S.newValue,") subscribers:",T.subject.subscribers);break;default:o.logger.info("\uD83D\uDCE2",T.type,T.key,"went (",S.oldValue,"->",S.newValue,") subscribers:",T.subject.subscribers)}T.subject.next(S)};var on=(T,S)=>{let o=L(S),f=o.selectorAtoms.getRelatedKeys(T.key);if(o.logger.info("\uD83E\uDDF9",T.type,T.key,f?`evicting ${f.size} states downstream:`:"no downstream states",f??"to evict"),f){if(o.operation.open)o.logger.info("\uD83E\uDDF9",T.type,T.key,`[ ${[...o.operation.done].join(", ")} ] already done`);for(let A of f){if(nF(o,A))continue;FF(A,o),Qo(o,A)}}};function CO(T,S){if(RF(S.newValue))return!1;if(T.includes("\uD83D\uDD0D"))return!1;return!0}var JF=(T,S,o)=>{let{key:f}=T,A=L(o);if(!OT(A)||A.transactionMeta.phase!=="building"){o.logger.error("\uD83D\uDC1E","atom",f,"stowUpdate called outside of a transaction. This is probably a bug.");return}if(!CO(f,S))return;let $={type:"atom_update",key:f,...S};if(T.family)$.family=T.family;A.transactionMeta.update.updates.push($),o.logger.info("\uD83D\uDCC1","atom",f,"stowed (",S.oldValue,"->",S.newValue,")")};var OF=(T,S,o)=>{let f=PS(T,o),A=f;if(T.type==="mutable_atom"&&OT(o)){let{parent:$}=o;A=nf(T,$,o)}if(A=pf(S)(A),o.logger.info("\uD83D\uDCDD","atom",T.key,"set to",A),A=WS(T.key,A,T.subject,o),MF(T.key,o))WF(T.key,o);Qo(o,T.key),on(T,o);let n={oldValue:f,newValue:A};if(mT(o))$F(T,n,o);else if(o.parent){if(o.on.transactionApplying.state===null)JF(T,n,o);else if(T.key.startsWith("*")){let $=T.key.slice(1),F=o.atoms.get($),J=o.valueMap.get($);if(F.type==="mutable_atom"&&OT(o)){let{parent:O}=o;J=nf(F,O,o)}if(J.do(n.newValue)===null)on(F,o)}}};var Pf=(T,S,o)=>{switch(T.type){case"atom":case"mutable_atom":OF(T,S,o);break;case"selector":T.set(S);break}};function _F(T,S){if(S.family){let o=T.families.get(S.family.key);if(o)return o}}function VT(T,...S){let o,f,A,n;if(S.length===2){if(o=S[0],n=S[1],f=_F(T,o)??null,f)A=o.family?BT(o.family.subKey):null,o=g(T,f,A)}else f=S[0],A=S[1],n=S[2],o=g(T,f,A);if("counterfeit"in o&&"family"in o){let J=o.family.subKey,R=T.disposalTraces.buffer.find((O)=>O?.key===J);T.logger.error("\u274C",o.type,o.key,`could not be set because it was not found in the store "${T.config.name}".`,R?`This state was previously disposed:
|
|
4
|
+
${R.trace}`:"No previous disposal trace was found.");return}let $=fF(T,o);if($){let J=T.on.operationClose.subscribe(`waiting to set "${o.key}" at T-${$}`,()=>{J(),T.logger.info("\uD83D\uDFE2",o.type,o.key,`resuming deferred setState from T-${$}`),VT(T,o,n)});return}let F=nT(o,T);Pf(F,n,T),AF(T)}function gf(T,S,o){let{key:f,newValue:A,oldValue:n}=S,$=T==="newValue"?A:n,F={key:f,type:"atom"};if(S.family)Object.assign(F,{family:S.family});VT(o,F,$)}function kF(T){let{stack:S}=T;if(S)return`
|
|
5
|
+
`+S.split(`
|
|
6
|
+
`)?.slice(1)?.join(`
|
|
7
|
+
`);return""}function a$(T,S=s.STORE){let o={key:T,stringKey:fT(T),dependsOn:"any"};return S.molecules.set(fT(T),o),T}function fo(T,S,o,f="any"){let A=S,n=fT(o),$=[],F=L(T);if(Array.isArray(A))for(let O of A){let k=fT(O);if(F.molecules.get(k))T.moleculeGraph.set(k,n,{source:k});else $.push(k)}else{let O=fT(A);if(F.molecules.get(O))T.moleculeGraph.set(O,n,{source:O});else $.push(O)}if($.length===0)F.molecules.set(n,{key:o,stringKey:n,dependsOn:f});let J={type:"molecule_creation",key:o,provenance:A};if(OT(F)&&F.transactionMeta.phase==="building")F.transactionMeta.update.updates.push(J);else F.on.moleculeCreation.next(J);for(let O of $){let k=T.disposalTraces.buffer.find((y)=>y?.key===O);T.logger.error("\u274C","molecule",o,"allocation failed:",`Could not allocate to ${O} in store "${T.config.name}".`,k?`
|
|
8
|
+
${O} was most recently disposed
|
|
9
|
+
${k.trace}`:`No previous disposal trace for ${O} was found.`)}return o}function TF(T,S,o,f){let A=`T$--${S}==${o}++${f}`;return fo(T,[o,f],A,"all"),A}function Ao(T,S){let o=fT(S),f=T.molecules.get(o);if(!f){let H=T.disposalTraces.buffer.find((E)=>E?.key===o);T.logger.error("\u274C","molecule",S,"deallocation failed:",`Could not find allocation for ${o} in store "${T.config.name}".`,H?`
|
|
6
10
|
This state was most recently deallocated
|
|
7
|
-
${
|
|
8
|
-
${
|
|
9
|
-
${
|
|
11
|
+
${H.trace}`:`No previous disposal trace for ${o} was found.`);return}let A=T.moleculeJoins.getRelatedKeys(f.key);if(A)for(let H of A){let E=T.joins.get(H);if(E)E.relations.delete(f.key),E.molecules.delete(f.stringKey)}T.moleculeJoins.delete(f.stringKey);let n=[],$=[],F={type:"molecule_disposal",key:f.key,values:$,provenance:n},J=L(T);J.molecules.delete(o);let R=OT(J)&&J.transactionMeta.phase==="building";if(R)J.transactionMeta.update.updates.push(F);let O=T.moleculeGraph.getRelationEntries({downstreamMoleculeKey:f.stringKey});if(O)for(let[H,{source:E}]of O)if(E===f.stringKey){let G=BT(H);Ao(T,G)}else n.push(E);let k=J.moleculeData.getRelatedKeys(f.stringKey);if(k)for(let H of k){let E=J.families.get(H),G=g(T,E,f.key);$.push([E.key,G]),$o(T,G)}if(J.moleculeGraph.delete(f.stringKey),J.moleculeJoins.delete(f.stringKey),J.moleculeData.delete(f.stringKey),!R)J.on.moleculeDisposal.next(F);J.molecules.delete(f.stringKey);let y=kF(new Error);T.disposalTraces.add({key:o,trace:y})}function Eo(T,S,o,f){let A=fT(o),n=L(T),$=n.molecules.get(A);if(!$){let y=T.disposalTraces.buffer.find((H)=>H?.key===A);return T.logger.error("\u274C","molecule",o,"claim failed:",`Could not allocate to ${A} in store "${T.config.name}".`,y?`
|
|
12
|
+
${A} was most recently disposed
|
|
13
|
+
${y.trace}`:`No previous disposal trace for ${A} was found.`),o}let F=fT(S),J=n.molecules.get(F);if(!J){let y=T.disposalTraces.buffer.find((H)=>H?.key===F);return T.logger.error("\u274C","molecule",o,"claim failed:",`Could not allocate to ${F} in store "${T.config.name}".`,y?`
|
|
10
14
|
${F} was most recently disposed
|
|
11
|
-
${_.trace}`:`No previous disposal trace for ${F} was found.`),S}let R=T.moleculeGraph.getRelationEntries({downstreamMoleculeKey:$.stringKey}).filter(([,{source:_}])=>_!==n).map(([_])=>tT(_));if(f)A.moleculeGraph.delete(n);A.moleculeGraph.set({upstreamMoleculeKey:J.stringKey,downstreamMoleculeKey:$.stringKey},{source:J.stringKey});let W={type:"molecule_transfer",key:$.key,from:R,to:[J.key]};if(WT(A)&&A.transactionMeta.phase==="building")A.transactionMeta.update.updates.push(W);return S}class e${store;constructor(T=a.STORE){this.store=T,u$("root",T)}allocate(T,o,S){return YS(this.store,T,o,S)}fuse(T,o,S){return VW(this.store,T,o,S)}deallocate(T){ES(this.store,T)}claim(T,o,S){return nf(this.store,T,o,S)}}class sn{store;realm;constructor(T=a.STORE){this.store=T,this.realm=new e$(T)}allocate(T,o,S){YS(this.store,T,o,S)}deallocate(T){ES(this.store,T)}claim(T,o,S){nf(this.store,T,o,S)}}function HS(T){return s$(a.STORE,T)}function AS(T){return d$(a.STORE,T)}function TA(...T){if(T.length===2)return RT(a.STORE,...T);return RT(a.STORE,...T)}var oA=(T)=>(o,S,f,n,...A)=>{console[T](`${o} ${S} "${f}" ${n}`,...A)},BW={error:oA("error"),info:oA("info"),warn:oA("warn")};class SA{logLevel;filter;logger;constructor(T,o,S=BW){this.logLevel=T;this.filter=o;this.logger=S}error=(...T)=>{if((this.filter?.(...T)??!0)&&this.logLevel!==null)this.logger.error(...T)};info=(...T)=>{if((this.filter?.(...T)??!0)&&this.logLevel==="info")this.logger.info(...T)};warn=(...T)=>{if((this.filter?.(...T)??!0)&&this.logLevel!=="error"&&this.logLevel!==null)this.logger.warn(...T)}}function rf(T){return Sf(a.STORE,T)}function Af(T){return fA(T,a.STORE)}class NT{a;b;cardinality;relations=new Map;contents=new Map;isAType;isBType;isContent;makeContentKey=(T,o)=>`${T}:${o}`;warn;getRelatedKeys(T){return this.relations.get(T)}addRelation(T,o){let S=this.relations.get(T),f=this.relations.get(o);if(S)S.add(o);else S=new Set([o]),this.relations.set(T,S);if(f)f.add(T);else f=new Set([T]),this.relations.set(o,f)}deleteRelation(T,o){let S=this.relations.get(T);if(S){if(S.delete(o),S.size===0)this.relations.delete(T);let f=this.relations.get(o);if(f){if(f.delete(T),f.size===0)this.relations.delete(o)}}}replaceRelationsUnsafely(T,o){this.relations.set(T,new Set(o));for(let S of o){let f=new Set().add(T);this.relations.set(S,f)}}replaceRelationsSafely(T,o){let S=this.relations.get(T),f=this.isAType?.(T)?T:void 0,n=f===void 0?T:void 0;if(S)for(let A of S){f??=A,n??=A;let $=this.relations.get(A);if($){if($.size===1)this.relations.delete(A);else $.delete(T);this.contents.delete(this.makeContentKey(f,n))}}this.relations.set(T,new Set(o));for(let A of o){let $=this.relations.get(A);if($)$.add(T);else $=new Set().add(T),this.relations.set(A,$)}}getContentInternal(T){return this.contents.get(T)}setContent(T,o){this.contents.set(T,o)}deleteContent(T){this.contents.delete(T)}constructor(T,o){if(this.a=T.between[0],this.b=T.between[1],this.cardinality=T.cardinality,!o?.externalStore)this.relations=new Map(T.relations?.map(([S,f])=>[S,new Set(f)])),this.contents=new Map(T.contents);if(this.isAType=o?.isAType??null,this.isBType=o?.isBType??null,this.isContent=o?.isContent??null,o?.makeContentKey)this.makeContentKey=o.makeContentKey;if(o?.externalStore){let S=o.externalStore;if(this.has=(f,n)=>S.has(f,n),this.addRelation=(f,n)=>{S.addRelation(f,n)},this.deleteRelation=(f,n)=>{S.deleteRelation(f,n)},this.replaceRelationsSafely=(f,n)=>{S.replaceRelationsSafely(f,n)},this.replaceRelationsUnsafely=(f,n)=>{S.replaceRelationsUnsafely(f,n)},this.getRelatedKeys=(f)=>S.getRelatedKeys(f),S.getContent)this.getContentInternal=(f)=>{return S.getContent(f)},this.setContent=(f,n)=>{S.setContent(f,n)},this.deleteContent=(f)=>{S.deleteContent(f)};for(let[f,n]of T.relations??[]){let A=this.isAType?.(f)?f:void 0,$=A===void 0?f:void 0;for(let F of n)A??=F,$??=F,this.addRelation(A,$)}for(let[f,n]of T.contents??[])this.setContent(f,n)}if(o?.warn)this.warn=o.warn}toJSON(){return{between:[this.a,this.b],cardinality:this.cardinality,relations:[...this.relations.entries()].map(([T,o])=>[T,[...o]]),contents:[...this.contents.entries()]}}set(...T){let o,S,f;switch(T.length){case 1:{let n=T[0];o=n[this.a],S=n[this.b],f=void 0;break}case 2:{let n=T[0];if(typeof n==="string")[o,S]=T;else o=n[this.a],S=n[this.b],f=T[1];break}default:{o=T[0],S=T[1],f=T[2];break}}switch(this.cardinality){case"1:1":{let n=this.getRelatedKey(o);if(n&&n!==S)this.delete(o,n)}case"1:n":{let n=this.getRelatedKey(S);if(n&&n!==o)this.delete(n,S)}}if(f){let n=this.makeContentKey(o,S);this.setContent(n,f)}return this.addRelation(o,S),this}delete(T,o){o=typeof o==="string"?o:T[this.b];let S=typeof T==="string"?T:T[this.a];if(S===void 0&&typeof o==="string"){let f=this.getRelatedKeys(o);if(f)for(let n of f)this.delete(n,o)}if(typeof S==="string"&&o===void 0){let f=this.getRelatedKeys(S);if(f)for(let n of f)this.delete(S,n)}if(typeof S==="string"&&typeof o==="string"){this.deleteRelation(S,o);let f=this.makeContentKey(S,o);this.deleteContent(f)}return this}getRelatedKey(T){let o=this.getRelatedKeys(T);if(o){if(o.size>1)this.warn?.(`${o.size} related keys were found for key "${T}": (${[...o].map((f)=>`"${f}"`).join(", ")}). Only one related key was expected.`);let S;for(let f of o){S=f;break}return S}}replaceRelations(T,o,S){let f=!Array.isArray(o),n=f?Object.keys(o):o;if(S?.reckless)this.replaceRelationsUnsafely(T,n);else this.replaceRelationsSafely(T,n);if(f)for(let A of n){let $=this.makeContentKey(T,A),F=o[A];this.setContent($,F)}return this}getContent(T,o){let S=this.makeContentKey(T,o);return this.getContentInternal(S)}getRelationEntries(T){let o=T[this.a],S=T[this.b];if(o!==void 0&&S===void 0){let f=this.getRelatedKeys(o);if(f)return[...f].map((n)=>{return[n,this.getContent(o,n)]})}if(o===void 0&&S!==void 0){let f=this.getRelatedKeys(S);if(f)return[...f].map((n)=>{return[n,this.getContent(n,S)]})}return[]}has(T,o){if(o)return this.getRelatedKeys(T)?.has(o)??!1;return this.relations.has(T)}}function hT(T){return"epoch"in T.transactionMeta}function WT(T){return"phase"in T.transactionMeta}var oF=(T)=>{let o=L(T);if(!WT(o)){T.logger.warn("\uD83D\uDC1E","transaction","???","abortTransaction called outside of a transaction. This is probably a bug in AtomIO.");return}T.logger.info("\uD83E\uDE82","transaction",o.transactionMeta.update.key,"Aborting transaction"),o.parent.child=null};var LW=(T)=>T[0].toUpperCase()+T.slice(1);function Yo(T){return T.type.split("_").map(LW).join(" ")}class bo extends Error{constructor(...T){let o=T[0],S=T.length===2?T[1]:T[2];if(T.length===2)super(`${Yo(o)} ${s(o.key)} not found in store "${S.config.name}".`);else{let f=T[1];super(`${Yo(o)} "${o.key}" member ${s(f)} not found in store "${S.config.name}".`)}}}function zS(T,o,S){return(...f)=>{let n=AT(T,S);if(n)return n.run(f,o);throw new bo(T,S)}}var Pf=(T)=>(o)=>T instanceof Function?T(o):T;var io=(T,o)=>{if(o.valueMap.has(T.key))return o.logger.info("\uD83D\uDCD6",T.type,T.key,"reading cached value"),SF(T,o);if(T.type==="selector"||T.type==="readonly_selector")return o.logger.info("\uD83E\uDDEE",T.type,T.key,"computing value"),T.get();let S=T.default instanceof Function?T.default():T.default;return o.logger.info("\uD83D\uDC81","atom",T.key,"could not find cached value; using default",S),T.default instanceof Function?T.default():T.default};var fF=(T,o)=>{if(T.operation.open){let S=performance.now();return T.logger.info("\u2757",o.type,o.key,`deferring setState at T-${S} until setState for "${T.operation.token.key}" is done`),S}T.operation={open:!0,done:new Set,prev:new Map,time:Date.now(),token:o},T.logger.info("\u2B55",o.type,o.key,`operation start in store "${T.config.name}"${!WT(T)?"":` ${T.transactionMeta.phase} "${T.transactionMeta.update.key}"`}`)},nF=(T)=>{if(T.operation.open)T.logger.info("\uD83D\uDD34",T.operation.token.type,T.operation.token.key,`operation done in store "${T.config.name}"`);T.operation={open:!1},T.on.operationClose.next(T.operation)},AF=(T,o)=>{if(!T.operation.open)return T.logger.error("\uD83D\uDC1E","unknown",o,"isDone called outside of an operation. This is probably a bug in AtomIO."),!0;return T.operation.done.has(o)},QS=(T,o)=>{if(!T.operation.open){T.logger.error("\uD83D\uDC1E","unknown",o,"markDone called outside of an operation. This is probably a bug in AtomIO.");return}T.operation.done.add(o)};var $F=(T,o,S)=>{switch(T.type){case"mutable_atom":S.logger.info("\uD83D\uDCE2",T.type,T.key,"is now (",o.newValue,") subscribers:",T.subject.subscribers);break;default:S.logger.info("\uD83D\uDCE2",T.type,T.key,"went (",o.oldValue,"->",o.newValue,") subscribers:",T.subject.subscribers)}T.subject.next(o)};var nA=(T,o)=>{let S=L(o),f=S.selectorAtoms.getRelatedKeys(T.key);if(S.logger.info("\uD83E\uDDF9",T.type,T.key,f?`evicting ${f.size} states downstream:`:"no downstream states",f??"to evict"),f){if(S.operation.open)S.logger.info("\uD83E\uDDF9",T.type,T.key,`[ ${[...S.operation.done].join(", ")} ] already done`);for(let n of f){if(AF(S,n))continue;FF(n,S),QS(S,n)}}};function CW(T,o){if(RF(o.newValue))return!1;if(T.includes("\uD83D\uDD0D"))return!1;return!0}var JF=(T,o,S)=>{let{key:f}=T,n=L(S);if(!WT(n)||n.transactionMeta.phase!=="building"){S.logger.error("\uD83D\uDC1E","atom",f,"stowUpdate called outside of a transaction. This is probably a bug.");return}if(!CW(f,o))return;let $={type:"atom_update",key:f,...o};if(T.family)$.family=T.family;n.transactionMeta.update.updates.push($),S.logger.info("\uD83D\uDCC1","atom",f,"stowed (",o.oldValue,"->",o.newValue,")")};var WF=(T,o,S)=>{let f=io(T,S),n=f;if(T.type==="mutable_atom"&&WT(S)){let{parent:$}=S;n=$f(T,$,S)}if(n=Pf(o)(n),S.logger.info("\uD83D\uDCDD","atom",T.key,"set to",n),n=Mo(T.key,n,T.subject,S),OF(T.key,S))MF(T.key,S);QS(S,T.key),nA(T,S);let A={oldValue:f,newValue:n};if(hT(S))$F(T,A,S);else if(S.parent){if(S.on.transactionApplying.state===null)JF(T,A,S);else if(T.key.startsWith("*")){let $=T.key.slice(1),F=S.atoms.get($),J=S.valueMap.get($);if(F.type==="mutable_atom"&&WT(S)){let{parent:W}=S;J=$f(F,W,S)}if(J.do(A.newValue)===null)nA(F,S)}}};var pf=(T,o,S)=>{switch(T.type){case"atom":case"mutable_atom":WF(T,o,S);break;case"selector":T.set(o);break}};function kF(T,o){if(o.family){let S=T.families.get(o.family.key);if(S)return S}}function VT(T,...o){let S,f,n,A;if(o.length===2){if(S=o[0],A=o[1],f=kF(T,S)??null,f)n=S.family?tT(S.family.subKey):null,S=i(T,f,n)}else f=o[0],n=o[1],A=o[2],S=i(T,f,n);if("counterfeit"in S&&"family"in S){let J=S.family.subKey,R=T.disposalTraces.buffer.find((W)=>W?.key===J);T.logger.error("\u274C",S.type,S.key,`could not be set because it was not found in the store "${T.config.name}".`,R?`This state was previously disposed:
|
|
12
|
-
${R.trace}`:"No previous disposal trace was found.");return}let $=fF(T,S);if($){let J=T.on.operationClose.subscribe(`waiting to set "${S.key}" at T-${$}`,()=>{J(),T.logger.info("\uD83D\uDFE2",S.type,S.key,`resuming deferred setState from T-${$}`),VT(T,S,A)});return}let F=AT(S,T);pf(F,A,T),nF(T)}function gf(T,o,S){let{key:f,newValue:n,oldValue:A}=o,$=T==="newValue"?n:A,F={key:f,type:"atom"};if(o.family)Object.assign(F,{family:o.family});VT(S,F,$)}function AA(T,o,S){switch(o){case"newValue":{yF(T,S);break}case"oldValue":{nS(S,T.token);break}}}function $A(T,o,S){switch(o){case"newValue":{nS(S,T.token);break}case"oldValue":{if(yF(T,S),T.subType==="atom")S.valueMap.set(T.token.key,T.value);break}}}function yF(T,o){let{family:S}=T.token;if(S){let f=o.families.get(S.key);if(f)i(o,f,tT(S.subKey))}}function _F(T,o,S){switch(o){case"newValue":YS(S,T.provenance,T.key);break;case"oldValue":ES(S,T.key);break}}function wF(T,o,S){switch(o){case"newValue":ES(S,T.key);break;case"oldValue":{let f=T.provenance.map(tT);YS(S,f,T.key);for(let[n,A]of T.values){let $=S.families.get(n);if($){i(S,$,T.key);let F=`${n}(${s(T.key)})`;S.valueMap.set(F,A)}}}break}}function XF(T,o,S){switch(o){case"newValue":{let f=T.to.length===1?T.to[0]:T.to;nf(S,f,T.key,"exclusive")}break;case"oldValue":{let f=T.from.length===1?T.from[0]:T.from;nf(S,f,T.key,"exclusive")}break}}function df(T,o,S){let f=T==="newValue"?o.updates:[...o.updates].reverse();for(let n of f)switch(n.type){case"atom_update":case"selector_update":gf(T,n,S);break;case"state_creation":AA(n,T,S);break;case"state_disposal":$A(n,T,S);break;case"molecule_creation":_F(n,T,S);break;case"molecule_disposal":wF(n,T,S);break;case"molecule_transfer":XF(n,T,S);break;case"transaction_update":df(T,n,S);break}}function KF(T,o,S){if(hT(S)&&T)S.transactionMeta.epoch.set(T,o)}function GF(T,o,S){if(!hT(S))return;let n=S.transactionMeta.actionContinuities.getRelatedKey(T);if(n!==void 0)S.transactionMeta.epoch.set(n,o)}var YF=(T,o)=>{let S=L(o),{parent:f}=S;if(f===null||!WT(S)||S.transactionMeta?.phase!=="building"){o.logger.warn("\uD83D\uDC1E","transaction","???","applyTransaction called outside of a transaction. This is probably a bug in AtomIO.");return}S.transactionMeta.phase="applying",S.transactionMeta.update.output=T,f.child=null,f.on.transactionApplying.next(S.transactionMeta);let{updates:n}=S.transactionMeta.update;if(o.logger.info("\uD83D\uDEC4","transaction",S.transactionMeta.update.key,`Applying transaction with ${n.length} updates:`,n),df("newValue",S.transactionMeta.update,f),hT(f))GF(S.transactionMeta.update.key,S.transactionMeta.update.epoch,f),AT({key:S.transactionMeta.update.key,type:"transaction"},o)?.subject.next(S.transactionMeta.update),o.logger.info("\uD83D\uDEEC","transaction",S.transactionMeta.update.key,"Finished applying transaction.");else if(WT(f))f.transactionMeta.update.updates.push(S.transactionMeta.update);f.on.transactionApplying.next(null)};function EF(T,o,S){if(!hT(S))return;let{epoch:n,actionContinuities:A}=S.transactionMeta;if(A.set(T,o),!n.has(T))n.set(T,-1)}function HF(T){return{store:T}}function RT(T,...o){let S,f,n;if(o.length===1)S=o[0];else f=o[0],n=o[1],S=i(T,f,n);if("counterfeit"in S&&"family"in S){f=T.families.get(S.family.key);let A=S.family.subKey,$=T.disposalTraces.buffer.find((F)=>F?.key===A);switch(T.logger.error("\u274C",S.type,S.key,`could not be retrieved because it was not found in the store "${T.config.name}".`,$?`This state was previously disposed:
|
|
13
|
-
${$.trace}`:"No previous disposal trace was found."),f.type){case"atom_family":case"mutable_atom_family":return T.defaults.get(f.key);case"selector_family":case"readonly_selector_family":{if(T.defaults.has(f.key))return T.defaults.get(S.family.key);let F=AT(f,T).default(A);return T.defaults.set(f.key,F),F}}}return io(AT(S,T),T)}class ko extends Map{source;deleted=new Set;constructor(T){super();this.source=T}get(T){if(super.has(T))return super.get(T);if(!this.deleted.has(T)&&this.source.has(T))return this.source.get(T);return}set(T,o){return this.deleted.delete(T),super.set(T,o)}hasOwn(T){return super.has(T)}has(T){return!this.deleted.has(T)&&(super.has(T)||this.source.has(T))}delete(T){return this.deleted.add(T),super.delete(T)}}var zF=(T,o,S,f)=>{let n=L(S),A={parent:n,child:null,on:n.on,loggers:n.loggers,logger:n.logger,config:n.config,atoms:new ko(n.atoms),atomsThatAreDefault:new Set(n.atomsThatAreDefault),families:new ko(n.families),joins:new ko(n.joins),operation:{open:!1},readonlySelectors:new ko(n.readonlySelectors),timelines:new ko(n.timelines),timelineTopics:new NT(n.timelineTopics.toJSON()),trackers:new Map,transactions:new ko(n.transactions),selectorAtoms:new NT(n.selectorAtoms.toJSON()),selectorGraph:new NT(n.selectorGraph.toJSON(),{makeContentKey:(...R)=>R.sort().join(":")}),selectors:new ko(n.selectors),valueMap:new ko(n.valueMap),defaults:n.defaults,disposalTraces:S.disposalTraces.copy(),molecules:new ko(n.molecules),moleculeGraph:new NT(n.moleculeGraph.toJSON(),{makeContentKey:n.moleculeGraph.makeContentKey}),moleculeData:new NT(n.moleculeData.toJSON(),{makeContentKey:n.moleculeData.makeContentKey}),moleculeJoins:new NT(n.moleculeJoins.toJSON(),{makeContentKey:n.moleculeJoins.makeContentKey}),miscResources:new ko(n.miscResources)},$=QF(T,S),F={phase:"building",update:{type:"transaction_update",key:T,id:f,epoch:$===void 0?Number.NaN:$+1,updates:[],params:o,output:void 0},toolkit:{get:(...R)=>RT(J,...R),set:(...R)=>{VT(J,...R)},run:(R,W=Zf())=>zS(R,W,J),find:(R,W)=>i(J,R,W),seek:(R,W)=>qT(J,R,W),json:(R)=>mT(J,R),dispose:(...R)=>{nS(J,...R)},env:()=>HF(J)}},J=Object.assign(A,{transactionMeta:F});return n.child=J,S.logger.info("\uD83D\uDEEB","transaction",T,"Building transaction with params:",o),J};function fA(T,o){let S={key:T.key,type:"transaction",run:(A,$)=>{let F=zF(T.key,A,o,$);try{let J=L(o),{toolkit:R}=F.transactionMeta,W=T.do(R,...A);return YF(W,J),W}catch(J){throw oF(f),o.logger.warn("\uD83D\uDCA5","transaction",T.key,"caught:",J),J}},install:(A)=>fA(T,A),subject:new ST},f=L(o);f.transactions.set(S.key,S);let n=no(S);return o.on.transactionCreation.next(n),n}function QF(T,o){let S=hT(o),f=S?o.transactionMeta.actionContinuities.getRelatedKey(T):void 0;return S&&f!==void 0?o.transactionMeta.epoch.get(f):void 0}class DF{parent=null;child=null;valueMap=new Map;defaults=new Map;atoms=new Map;selectors=new Map;readonlySelectors=new Map;atomsThatAreDefault=new Set;selectorAtoms=new NT({between:["selectorKey","atomKey"],cardinality:"n:n"});selectorGraph=new NT({between:["upstreamSelectorKey","downstreamSelectorKey"],cardinality:"n:n"},{makeContentKey:(...T)=>T.sort().join(":")});trackers=new Map;families=new Map;joins=new Map;transactions=new Map;transactionMeta={epoch:new Map,actionContinuities:new NT({between:["continuity","action"],cardinality:"1:n"})};timelines=new Map;timelineTopics=new NT({between:["timelineKey","topicKey"],cardinality:"1:n"});disposalTraces=new cf(100);molecules=new Map;moleculeJoins=new NT({between:["moleculeKey","joinKey"],cardinality:"n:n"},{makeContentKey:(...T)=>T.sort().join(":")});moleculeGraph=new NT({between:["upstreamMoleculeKey","downstreamMoleculeKey"],cardinality:"n:n"},{makeContentKey:(...T)=>T.sort().join(":")});moleculeData=new NT({between:["moleculeKey","stateFamilyKey"],cardinality:"n:n"},{makeContentKey:(...T)=>T.sort().join(":")});miscResources=new Map;on={atomCreation:new ST,atomDisposal:new ST,selectorCreation:new ST,selectorDisposal:new ST,timelineCreation:new ST,transactionCreation:new ST,transactionApplying:new an(null),operationClose:new ST,moleculeCreation:new ST,moleculeDisposal:new ST};operation={open:!1};config={name:"IMPLICIT_STORE",lifespan:"ephemeral"};loggers=[new SA("warn",(T,o,S)=>!S.includes("\uD83D\uDD0D"))];logger={error:(...T)=>{for(let o of this.loggers)o.error(...T)},info:(...T)=>{for(let o of this.loggers)o.info(...T)},warn:(...T)=>{for(let o of this.loggers)o.warn(...T)}};constructor(T,o=null){if(this.config={...o?.config,...T},o!==null){if(this.valueMap=new Map(o?.valueMap),this.operation={...o?.operation},hT(o))this.transactionMeta={epoch:new Map(o?.transactionMeta.epoch),actionContinuities:new NT(o?.transactionMeta.actionContinuities.toJSON())};for(let[,f]of o.families){if(f.internalRoles?.includes("mutable")||f.internalRoles?.includes("join"))continue;f.install(this)}let S=new Set;for(let[,f]of o.atoms){if(S.has(f.key))continue;if(f.install(this),f.type==="mutable_atom"){let n=mT(o,f),A=xo(f);S.add(n.key),S.add(A.key)}}for(let[,f]of o.readonlySelectors)f.install(this);for(let[,f]of o.selectors){if(S.has(f.key))continue;f.install(this)}for(let[,f]of o.transactions)f.install(this);for(let[,f]of o.timelines)f.install(this)}}}var a={get STORE(){if(!globalThis.ATOM_IO_IMPLICIT_STORE)globalThis.ATOM_IO_IMPLICIT_STORE=new DF({name:"IMPLICIT_STORE",lifespan:"ephemeral"});return globalThis.ATOM_IO_IMPLICIT_STORE}};function AT(T,o){let S,f=o;while(f!==null){switch(T.type){case"atom":case"mutable_atom":S=f.atoms.get(T.key);break;case"selector":S=f.selectors.get(T.key);break;case"readonly_selector":S=f.readonlySelectors.get(T.key);break;case"atom_family":case"mutable_atom_family":case"selector_family":case"readonly_selector_family":S=f.families.get(T.key);break;case"timeline":S=f.timelines.get(T.key);break;case"transaction":S=f.transactions.get(T.key);break}if(S)return S;f=f.child}throw new bo(T,o)}function UF(T,o,S){let f=T.families.get(o.key);if(f===void 0)throw new bo(o,T);let n=f(S),A=L(T);if(n.family){if(hT(A))switch(n.type){case"atom":case"mutable_atom":T.on.atomCreation.next(n);break;case"selector":case"readonly_selector":T.on.selectorCreation.next(n);break}else if(WT(A)&&A.on.transactionApplying.state===null)A.transactionMeta.update.updates.push({type:"state_creation",token:n})}return n}function qT(T,o,S){let f=s(S),n=`${o.key}(${f})`,A=L(T),$;switch(o.type){case"atom_family":case"mutable_atom_family":$=A.atoms.get(n);break;case"selector_family":$=A.selectors.get(n);break;case"readonly_selector_family":$=A.readonlySelectors.get(n);break}if($)return no($);return $}function i(T,o,S){let f=qT(T,o,S);if(f)return f;let n=s(S),A=T.molecules.get(n);if(!A&&T.config.lifespan==="immortal"){let $=l$(o,S);return T.logger.error("\u274C",$.type,$.key,`was not found in store "${T.config.name}"; returned a counterfeit token.`),$}if(f=UF(T,o,S),A)L(T).moleculeData.set(n,o.key);return f}function nS(T,...o){let S;if(o.length===1)S=o[0];else{let f=o[0],n=o[1];S=i(T,f,n)}try{AT(S,T)}catch(f){T.logger.error("\u274C",S.type,S.key,`could not be disposed because it was not found in the store "${T.config.name}".`);return}switch(S.type){case"atom":case"mutable_atom":FA(S,T);break;case"selector":case"readonly_selector":tF(S,T);break}}var lf=(T,o)=>L(o).atoms.has(T),IW=(T,o)=>L(o).selectors.has(T),jW=(T,o)=>L(o).readonlySelectors.has(T),VF=(T,o)=>lf(T,o)||IW(T,o)||jW(T,o);var uf=(T,o)=>{return L(o).selectorGraph.getRelationEntries({downstreamSelectorKey:T}).filter(([f,{source:n}])=>n!==T).map(([f,{source:n}])=>n).filter((f)=>VF(f,o))};var JA=(T,o,S)=>{let f=[],n=uf(T,S);while(n.length>0){let A=n.shift();if(o.has(A))continue;if(o.add(A),!lf(A,S))n.push(...uf(A,S));else if(!f.includes(A))f.push(A)}return f},BF=(T,o)=>{let S=T.key,f=uf(S,o),n=new Set;return f.flatMap((A)=>lf(A,o)?A:JA(A,n,o))};var LF=(T,o,S,f)=>{let n=L(f);if(o.type==="atom"||o.type==="mutable_atom")n.selectorAtoms.set({selectorKey:T,atomKey:o.key}),f.logger.info("\uD83D\uDD0D","selector",T,`discovers root atom "${o.key}"`);else{let A=JA(o.key,S,f);f.logger.info("\uD83D\uDD0D","selector",T,`discovers root atoms: [ ${A.map(($)=>`"${$}"`).join(", ")} ]`);for(let $ of A)n.selectorAtoms=n.selectorAtoms.set({selectorKey:T,atomKey:$})}S.add(o.key)};var ef=(T,o,S)=>({get:(...f)=>{let n=L(S),A;if(f.length===2){let[J,R]=f;A=i(S,J,R)}else[A]=f;let $=AT(A,S),F=io($,S);return S.logger.info("\uD83D\uDD0C","selector",T,`registers dependency ( "${A.key}" =`,F,")"),n.selectorGraph.set({upstreamSelectorKey:A.key,downstreamSelectorKey:T},{source:A.key}),LF(T,A,o,S),F},set:(...f)=>{let n,A;if(f.length===2)n=f[0],A=f[1];else{let J=f[0],R=f[1];A=f[2];let W=S.config.lifespan==="ephemeral"?i(S,J,R):qT(S,J,R);if(!W)throw new bo(J,R,S);n=W}let $=L(S),F=AT(n,$);pf(F,A,$)},find:(f,n)=>i(S,f,n),seek:(f,n)=>qT(S,f,n),json:(f)=>mT(S,f)});var of=(T,o,S)=>{let f=L(T),n=new ST,A=new Set,{get:$,find:F,seek:J,json:R}=ef(o.key,A,f),W=()=>{let H=o.get({get:$,find:F,seek:J,json:R});return Mo(o.key,H,n,L(T)),A.clear(),H},y={...o,subject:n,install:(H)=>of(H,o,S),get:W,type:"readonly_selector",...S&&{family:S}};f.readonlySelectors.set(o.key,y);let _=W();T.logger.info("\u2728",y.type,y.key,"=",_);let K={key:o.key,type:"readonly_selector"};if(S)K.family=S;return K};var Ff=(T,o,S)=>{let f=L(T),n=new ST,A=new Set,$=ef(o.key,A,f),{find:F,get:J,seek:R,json:W}=$,y={find:F,get:J,seek:R,json:W},_=(b=o.get,q=L(T))=>{let p=b(y);return Mo(o.key,p,n,q),A.clear(),p},H={...o,subject:n,install:(b)=>Ff(b,o,S),get:_,set:(b)=>{let q=L(T),p=_(o.get,q),G=Pf(b)(p);if(T.logger.info("\uD83D\uDCDD","selector",o.key,"set (",p,"->",G,")"),Mo(o.key,G,n,q),QS(q,o.key),hT(q))n.next({newValue:G,oldValue:p});o.set($,G)},type:"selector",...S&&{family:S}};f.selectors.set(o.key,H);let Y=_();T.logger.info("\u2728",H.type,H.key,"=",Y);let I={key:o.key,type:"selector"};if(S)I.family=S;return I};function Go(T,o){if("set"in o){let n=Ff(T,o,void 0);return T.on.selectorCreation.next(n),n}let f=of(T,o,void 0);return T.on.selectorCreation.next(f),f}function tF(T,o){let S=L(o),{key:f}=T,n=AT(T,S);if(!n.family)o.logger.error("\u274C","selector",f,"Standalone selectors cannot be disposed.");else{if(S.molecules.get(n.family.subKey))S.moleculeData.delete(n.family.subKey,n.family.key);switch(T.type){case"selector":{S.selectors.delete(f);let $=AT({key:n.family.key,type:"selector_family"},o)}break;case"readonly_selector":S.readonlySelectors.delete(f),AT({key:n.family.key,type:"readonly_selector_family"},o).subject.next({type:"state_disposal",subType:"selector",token:T});break}if(S.valueMap.delete(f),S.selectorAtoms.delete(f),S.selectorGraph.delete(f),o.logger.info("\uD83D\uDD25",T.type,f,"deleted"),WT(S)&&S.transactionMeta.phase==="building")S.transactionMeta.update.updates.push({type:"state_disposal",subType:"selector",token:T});else o.on.selectorDisposal.next(T)}}function ff(T,o,S){let f={key:o.key,type:"selector_family"},n=T.families.get(o.key);if(n)T.logger.error("\u2757","selector_family",o.key,`Overwriting an existing ${Yo(n)} "${n.key}" in store "${T.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let A=new ST,F=Object.assign((J)=>{let R=s(J),W={key:o.key,subKey:R},y=`${o.key}(${R})`,_=L(T),K=Ff(_,{key:y,get:o.get(J),set:o.set(J)},W);return A.next({type:"state_creation",token:K}),K},f,{internalRoles:S,subject:A,install:(J)=>ff(J,o),default:(J)=>{return o.get(J)({get:(...W)=>RT(T,...W),find:(W,y)=>i(T,W,y),seek:(W,y)=>qT(T,W,y),json:(W)=>mT(T,W)})}});return T.families.set(o.key,F),f}function CF(T,o,S=a.STORE){let f=ff(S,{key:`${T.key}:JSON`,get:(A)=>({get:$})=>{let F=$(T,A);return o.toJson(F)},set:(A)=>({set:$},F)=>{$(T,A,o.fromJson(F))}},["mutable","json"]);return AT(T,S).subject.subscribe(`store=${S.config.name}::json-selector-family`,(A)=>{if(A.token.family)qT(S,f,tT(A.token.family.subKey))}),f}var tT=(T)=>JSON.parse(T),s=(T)=>JSON.stringify(T),Sw=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];var IF=(T,o)=>{let S=L(o);if(S.operation.open)return S.operation.prev.get(T.key);return S.valueMap.get(T.key)};var OA=(T,o)=>{let S=L(o);return BF(T,o).map((n)=>{let A=S.atoms.get(n);if(A===void 0)throw new Error(`Atom "${n}", a dependency of selector "${T.key}", not found in store "${o.config.name}".`);return A.subject.subscribe(`${T.type}:${T.key}`,($)=>{o.logger.info("\uD83D\uDCE2",T.type,T.key,"root",n,"went",$.oldValue,"->",$.newValue);let F=IF(T,S),J=io(T,S);o.logger.info("\u2728",T.type,T.key,"went",F,"->",J),T.subject.next({newValue:J,oldValue:F})})})};function lT(T,o,S,f){function n(y){if(f.operation.open){let _=f.on.operationClose.subscribe(`state subscription ${S}`,()=>{_(),o(y)})}else o(y)}let A=AT(T,f);f.logger.info("\uD83D\uDC40",A.type,A.key,`Adding subscription "${S}"`);let $=A.type==="selector"||A.type==="readonly_selector",F=null,J=n;if($)F=OA(A,f),J=(y)=>{if(F)F.length=0,F.push(...OA(A,f));n(y)};let R=A.subject.subscribe(S,J);return()=>{if(f.logger.info("\uD83D\uDE48",A.type,A.key,`Removing subscription "${S}"`),R(),F)for(let y of F)y()}}var RA=(T,o,S,f)=>{let n=AT(T,f);f.logger.info("\uD83D\uDC40","timeline",T.key,`Adding subscription "${S}"`);let A=n.subject.subscribe(S,o);return()=>{f.logger.info("\uD83D\uDE48","timeline",T.key,`Removing subscription "${S}" from timeline`),A()}};var WA=(T,o,S,f)=>{let n=AT(T,f);f.logger.info("\uD83D\uDC40","transaction",T.key,`Adding subscription "${S}"`);let A=n.subject.subscribe(S,o);return()=>{f.logger.info("\uD83D\uDE48","transaction",T.key,`Removing subscription "${S}"`),A()}};class go{Update;initializeState(T,o){let S=`*${T.key}`;o.atoms.delete(S),o.valueMap.delete(S);let f=T.family?{key:`*${T.family.key}`,subKey:T.family.subKey}:void 0,n=fo(o,{key:S,default:null},f);if(o.parent?.valueMap.has(S)){let A=o.parent.valueMap.get(S);o.valueMap.set(S,A)}return n}unsubscribeFromInnerValue;unsubscribeFromState;observeCore(T,o,S){let f=`tracker:${S.config.name}:${WT(S)?S.transactionMeta.update.key:"main"}:${T.key}`,n=RT(S,T);this.unsubscribeFromInnerValue=n.subscribe(f,(A)=>{VT(S,o,A)}),this.unsubscribeFromState=lT(T,(A)=>{if(A.newValue!==A.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=A.newValue.subscribe(f,($)=>{VT(S,o,$)})},f,S)}updateCore(T,o,S){let f=`tracker:${S.config.name}:${WT(S)?S.transactionMeta.update.key:"main"}:${T.key}`;lT(o,({newValue:n,oldValue:A})=>{let $=S.timelineTopics.getRelatedKey(o.key);if($){if(S.timelines.get($)?.timeTraveling){let R=RA({key:$,type:"timeline"},(W)=>{R(),VT(S,T,(y)=>{if(W==="redo"&&n)y.do(n);else if(W==="undo"&&A)y.undo(A);return y})},f,S);return}}let F=S.on.operationClose.subscribe(f,()=>{F();let J=RT(S,T),R=n===null?-1:J.getUpdateNumber(n),W=R-J.cacheUpdateNumber;if(n&&W===1)VT(S,T,(y)=>(y.do(n),y));else S.logger.info("\u274C","mutable_atom",T.key,`could not be updated. Expected update number ${J.cacheUpdateNumber+1}, but got ${R}`)})},f,S)}mutableState;latestUpdateState;dispose;constructor(T,o){this.mutableState=T;let S=L(o);this.latestUpdateState=this.initializeState(T,S),this.observeCore(T,this.latestUpdateState,S),this.updateCore(T,this.latestUpdateState,S),S.trackers.set(T.key,this),this.dispose=()=>{this.unsubscribeFromInnerValue(),this.unsubscribeFromState(),S.trackers.delete(T.key)}}}function Jf(T,o,S){T.logger.info("\uD83D\uDD28","atom",o.key,`creating in store "${T.config.name}"`);let f=L(T),n=f.atoms.get(o.key);if(n&&n.type==="mutable_atom")return T.logger.error("\u274C","atom",o.key,"Tried to create atom, but it already exists in the store."),no(n);let A=new ST,$={...o,type:"mutable_atom",install:(R)=>{return R.logger.info("\uD83D\uDEE0\uFE0F","atom",o.key,`installing in store "${R.config.name}"`),Jf(R,o,S)},subject:A};if(S)$.family=S;let F=o.default();f.atoms.set($.key,$),af(o.key,T),Mo(o.key,F,A,f);let J=no($);if(o.effects){let R=0,W=[];for(let y of o.effects){let _=y({setSelf:(K)=>{VT(T,J,K)},onSet:(K)=>lT(J,K,`effect[${R}]`,T)});if(_)W.push(_);++R}$.cleanup=()=>{for(let y of W)y()}}if(new go(J,T),!S)g$(J,o,T);return J}class MA{Update;latestUpdateAtoms;mutableAtoms;constructor(T,o){let S=Lo(o,{key:`*${T.key}`,default:null},["mutable","updates"]);this.latestUpdateAtoms=AT(S,o),this.mutableAtoms=T,this.mutableAtoms.subject.subscribe(`store=${o.config.name}::tracker-atom-family`,(f)=>{if(f.token.family){let n=tT(f.token.family.subKey);qT(o,this.latestUpdateAtoms,n),new go(f.token,o)}}),this.latestUpdateAtoms.subject.subscribe(`store=${o.config.name}::tracker-atom-family`,(f)=>{if(f.token.family){let n=tT(f.token.family.subKey),A=qT(o,this.mutableAtoms,n);if(A)new go(A,o)}})}}function Tf(T,o,S){let f={key:o.key,type:"mutable_atom_family"},n=T.families.get(o.key);if(n)T.logger.error("\u2757","mutable_atom_family",o.key,`Overwriting an existing ${Yo(n)} "${n.key}" in store "${T.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let A=new ST,F=Object.assign((J)=>{let R=s(J),W={key:o.key,subKey:R},y=`${o.key}(${R})`,_=L(T),K={key:y,default:()=>o.default(J),toJson:o.toJson,fromJson:o.fromJson,mutable:!0};if(o.effects)K.effects=o.effects(J);let H=Jf(_,K,W);return A.next({type:"state_creation",token:H}),H},f,{subject:A,install:(J)=>Tf(J,o),toJson:o.toJson,fromJson:o.fromJson,internalRoles:S});return T.families.set(o.key,F),CF(F,o,T),new MA(F,T),f}var kA=(T,o)=>{let S=L(o),f=`${T.key}:JSON`;return S.families.get(f)};var mT=(T,o)=>{if(o.family){let f=L(T),A={key:`${o.family.key}:JSON`,type:"selector_family"},$=AT(A,f),F=JSON.parse(o.family.subKey);return i(T,$,F)}return{type:"selector",key:`${o.key}:JSON`}};var xo=(T)=>{let S={type:"atom",key:`*${T.key}`};if(T.family)S.family={key:`*${T.family.key}`,subKey:T.family.subKey};return S};function RF(T){return typeof T==="object"&&T!==null&&"do"in T&&"undo"in T&&"subscribe"in T}function $f(T,o,S){let f=o.valueMap.get(T.key),n=S.valueMap.get(T.key);if(f===n){if(f===void 0)return typeof T.default==="function"?T.default():T.default;o.logger.info("\uD83D\uDCC3","atom",T.key,"copying");let A=T.toJson(f),$=T.fromJson(A);return S.valueMap.set(T.key,$),new go(T,o),$}return n}function Mo(T,o,S,f){let n=f.valueMap.get(T);if(n instanceof sS)n.use(o);if(o instanceof Promise){let A=new sS(o);return f.valueMap.set(T,A),A.then(($)=>{Mo(T,$,S,f),S.next({newValue:$,oldValue:A})}).catch(($)=>{f.logger.error("\uD83D\uDCA5","state",T,"rejected:",$)}),A}return f.valueMap.set(T,o),o}var SF=(T,o)=>{let S=o.valueMap.get(T.key);if(T.type==="mutable_atom"&&WT(o)){let{parent:f}=o;S=$f(T,f,o)}return S},FF=(T,o)=>{let S=o.valueMap.get(T);if(S instanceof sS){let f=S,n=o.selectors.get(T)??o.readonlySelectors.get(T);if(n)f.use(n.get());return}if(o.operation.open)o.operation.prev.set(T,S);o.valueMap.delete(T),o.logger.info("\uD83D\uDDD1","state",T,"evicted")};var OF=(T,o)=>{return L(o).atomsThatAreDefault.has(T)},af=(T,o)=>{let S=L(o);S.atomsThatAreDefault=new Set(S.atomsThatAreDefault).add(T)},MF=(T,o)=>{let S=L(o);S.atomsThatAreDefault=new Set(L(o).atomsThatAreDefault),S.atomsThatAreDefault.delete(T)};function fo(T,o,S){T.logger.info("\uD83D\uDD28","atom",o.key,`creating in store "${T.config.name}"`);let f=L(T),n=f.atoms.get(o.key);if(n&&n.type==="atom")return T.logger.error("\u274C","atom",o.key,"Tried to create atom, but it already exists in the store."),no(n);let A=new ST,$={...o,type:"atom",install:(R)=>{return R.logger.info("\uD83D\uDEE0\uFE0F","atom",o.key,`installing in store "${R.config.name}"`),fo(R,o,S)},subject:A};if(S)$.family=S;let F=o.default;if(o.default instanceof Function)F=o.default();f.atoms.set($.key,$),af(o.key,T),Mo(o.key,F,A,f);let J=no($);if(o.effects){let R=0,W=[];for(let y of o.effects){let _=y({setSelf:(K)=>{VT(T,J,K)},onSet:(K)=>lT(J,K,`effect[${R}]`,T)});if(_)W.push(_);++R}$.cleanup=()=>{for(let y of W)y()}}return J}function s$(T,o){if("mutable"in o){let n=Jf(T,o,void 0);return T.on.atomCreation.next(n),n}let f=fo(T,o,void 0);return T.on.atomCreation.next(f),f}function FA(T,o){let S=L(o),{key:f,family:n}=T,A=AT(T,S);if(!n)o.logger.error("\u274C","atom",f,"Standalone atoms cannot be disposed.");else{A.cleanup?.();let $=o.valueMap.get(A.key),F=AT({key:n.key,type:"atom_family"},o),J={type:"state_disposal",subType:"atom",token:T,value:$};F.subject.next(J);let R=WT(S);if(S.atoms.delete(f),S.valueMap.delete(f),S.selectorAtoms.delete(f),S.atomsThatAreDefault.delete(f),o.timelineTopics.delete(f),T.type==="mutable_atom"){let W=xo(T);FA(W,o),o.trackers.delete(f)}if(o.logger.info("\uD83D\uDD25","atom",f,"deleted"),R&&S.transactionMeta.phase==="building"){let W=S.transactionMeta.update.updates.at(-1);if(!(W?.type==="molecule_disposal"&&W.values.some(([K])=>K===A.family?.key)))S.transactionMeta.update.updates.push(J)}else o.on.atomDisposal.next(T)}}function a$(T){let{stack:o}=T;if(o)return`
|
|
14
|
-
`+o.split(`
|
|
15
|
-
`)?.slice(1)?.join(`
|
|
16
|
-
`);return""}var yA=(T)=>{let o=fo(T,{key:"\uD83D\uDD0D Atom Token Index (Internal)",default:()=>{let S=new Map;for(let[f,n]of T.atoms)if(!f.includes("\uD83D\uDD0D")){let A=no(n);if(n.family){let $=S.get(n.family.key);if(!$||!("familyMembers"in $))$={key:n.family.key,familyMembers:new Map},S.set(n.family.key,$);$.familyMembers.set(n.family.subKey,A)}else S.set(f,A)}return S},effects:[({setSelf:S})=>{T.on.atomCreation.subscribe("introspection",(f)=>{if(f.key.includes("\uD83D\uDD0D"))return;S((n)=>{if(f.family){let{key:A,subKey:$}=f.family,F=n.get(A);if(F===void 0||!("familyMembers"in F))F={key:A,familyMembers:new Map},n.set(A,F);F.familyMembers.set($,f)}else n.set(f.key,f);return n})}),T.on.atomDisposal.subscribe("introspection",(f)=>{S((n)=>{if(f.family){let{key:A,subKey:$}=f.family,F=n.get(A);if(F&&"familyMembers"in F){if(F.familyMembers.delete($),F.familyMembers.size===0)n.delete(A)}}else n.delete(f.key);return n})})}]},void 0);return Go(T,{key:"\uD83D\uDD0D Atom Token Index",get:({get:S})=>S(o)})};var _A=(T)=>{let o=fo(T,{key:"\uD83D\uDD0D Selector Token Index (Internal)",default:()=>{let S=new Map;for(let f of[T.readonlySelectors,T.selectors])for(let[n,A]of f)if(!n.includes("\uD83D\uDD0D")){let $=no(A);if(A.family){let F=S.get(A.family.key);if(!F||!("familyMembers"in F))F={key:A.family.key,familyMembers:new Map},S.set(A.family.key,F);F.familyMembers.set(A.family.subKey,$)}else S.set(n,$)}return S},effects:[({setSelf:S})=>{T.on.selectorCreation.subscribe("introspection",(f)=>{if(f.key.includes("\uD83D\uDD0D"))return;S((n)=>{if(f.family){let{key:A,subKey:$}=f.family,F=n.get(A);if(F===void 0||!("familyMembers"in F))F={key:A,familyMembers:new Map},n.set(A,F);F.familyMembers.set($,f)}else n.set(f.key,f);return n})}),T.on.selectorDisposal.subscribe("introspection",(f)=>{S((n)=>{if(f.family){let{key:A,subKey:$}=f.family,F=n.get(A);if(F&&"familyMembers"in F){if(F.familyMembers.delete($),F.familyMembers.size===0)n.delete(A)}}else n.delete(f.key);return n})})}]},void 0);return Go(T,{key:"\uD83D\uDD0D Selector Token Index",get:({get:S})=>S(o)})};class sf{supported;constructor(T){this.supported=T}refine(T){for(let[o,S]of Object.entries(this.supported))try{if(S(T)===!0&&S!==Boolean)return{type:o,data:T}}catch(f){try{if(T instanceof S)return{type:o,data:T}}catch(n){}}return null}}var wA=new sf({number:(T)=>typeof T==="number",string:(T)=>typeof T==="string",boolean:(T)=>typeof T==="boolean",null:(T)=>T===null});function XA(T){if(!T)return!1;return Object.getPrototypeOf(T)===Object.prototype}var KA=new sf({object:XA,array:(T)=>Array.isArray(T)}),mW=new sf({...wA.supported,...KA.supported}),DS=(T)=>{if(T===void 0)return"undefined";let o=mW.refine(T);if(o)return o.type;return Object.getPrototypeOf(T).constructor.name};class jF{store;auditorCreatedAt=performance.now();statesCreatedAt=new Map;atomIndex;selectorIndex;disposed=!1;unsubscribeFromAtomCreation;unsubscribeFromAtomDisposal;unsubscribeFromSelectorCreation;unsubscribeFromSelectorDisposal;constructor(T=a.STORE){this.store=T;this.atomIndex=yA(this.store),this.selectorIndex=_A(this.store),this.unsubscribeFromAtomCreation=this.store.on.atomCreation.subscribe(`auditor-${this.auditorCreatedAt}`,({key:o})=>{this.statesCreatedAt.set(o,performance.now()-this.auditorCreatedAt)}),this.unsubscribeFromAtomDisposal=this.store.on.atomDisposal.subscribe(`auditor-${this.auditorCreatedAt}`,({key:o})=>{this.statesCreatedAt.delete(o)}),this.unsubscribeFromSelectorCreation=this.store.on.selectorCreation.subscribe(`auditor-${this.auditorCreatedAt}`,({key:o})=>{this.statesCreatedAt.set(o,performance.now()-this.auditorCreatedAt)}),this.unsubscribeFromSelectorDisposal=this.store.on.selectorDisposal.subscribe(`auditor-${this.auditorCreatedAt}`,({key:o})=>{this.statesCreatedAt.delete(o)})}static DEFAULT_LIST_RESOURCES_PARAM={atomFamilies:!0,selectorFamilies:!0};listResources(T=jF.DEFAULT_LIST_RESOURCES_PARAM){if(this.disposed)throw new Error("This Auditor has been disposed");let o=TA(this.atomIndex),S=TA(this.selectorIndex),f=[...o.values()].filter((F)=>("familyMembers"in F)),n=[...S.values()].filter((F)=>("familyMembers"in F)),A=performance.now(),$=[];if(T.atomFamilies)for(let F of f){let J=F.familyMembers.values();for(let R of J){let y=this.statesCreatedAt.get(R.key)??this.auditorCreatedAt,_=A-y;$.push([R,_])}}if(T.selectorFamilies)for(let F of n){let J=F.familyMembers.values();for(let R of J){let y=this.statesCreatedAt.get(R.key)??this.auditorCreatedAt,_=A-y;$.push([R,_])}}return $}[Symbol.dispose](){this.unsubscribeFromAtomCreation(),this.unsubscribeFromAtomDisposal(),this.unsubscribeFromSelectorCreation(),this.unsubscribeFromSelectorDisposal(),this.disposed=!0}}var GA=(T,o)=>{let S=(f,n)=>{let $=((J,R)=>{let W=o(J,R);if(W)return W;return null})(f,n);if($?.jobComplete??$?.pathComplete)return $;let F=Array.isArray(n)?n.map((J,R)=>[R,J]):XA(n)?Object.entries(n):[];for(let[J,R]of F){let W=S([...f,J],R);if(W?.jobComplete)return W}return{}};S([],T)};function NW(T,o){return{summary:`${T<o?"+":"-"}${Math.abs(T-o)} (${T} \u2192 ${o})`}}function hW(T,o){return{summary:`${T.length<o.length?"+":"-"}${Math.abs(T.length-o.length)} ("${T}" \u2192 "${o}")`}}function bW(T,o){return{summary:`${T} \u2192 ${o}`}}function mF(T,o,S){let f="",n=[],A=[],$=[];return GA(T,(F,J)=>{let R;for(R of F){let W=o[R];if(W===void 0)A.push([R,JSON.stringify(J)]);else{let y=S(J,W);if(y.summary!=="No Change")$.push([R,y])}}}),GA(o,(F,J)=>{let R;for(R of F)if(T[R]===void 0)n.push([R,JSON.stringify(J)])}),f=`\uFF5E${$.length} \uFF0B${n.length} \uFF0D${A.length}`,{summary:f,added:n,removed:A,changed:$}}function xW(T,o,S){return mF(T,o,S)}class NF{leafRefinery;treeRefinery;leafDiffers;treeDiffers;constructor(T,o,S){this.leafRefinery=T,this.treeRefinery=o,this.leafDiffers={},this.treeDiffers={};for(let f of Object.keys(T.supported)){let n=S[f];this.leafDiffers[f]=n}for(let f of Object.keys(o.supported)){let n=S[f];this.treeDiffers[f]=n}}diff(T,o){if(T===o)return{summary:"No Change"};let S=this.leafRefinery.refine(T)??this.treeRefinery.refine(T),f=this.leafRefinery.refine(o)??this.treeRefinery.refine(o);if(S!==null&&f!==null){if(S.type===f.type){if(S.type in this.leafDiffers)return this.leafDiffers[S.type](S.data,f.data);if(S.type in this.treeDiffers)return this.treeDiffers[S.type](S.data,f.data,(F,J)=>this.diff(F,J))}}let n=DS(T),A=DS(o);if(n===A)return{summary:`${n} \u2192 ${A}`};return{summary:`Type change: ${n} \u2192 ${A}`}}}var _K=new NF(wA,KA,{number:NW,string:hW,boolean:bW,null:()=>({summary:"No Change"}),object:mF,array:xW});class bT extends Set{mode="record";subject=new ST;cacheLimit=0;cache=[];cacheIdx=-1;cacheUpdateNumber=-1;constructor(T,o=0){super(T);if(T instanceof bT)this.parent=T,this.cacheUpdateNumber=T.cacheUpdateNumber;if(o)this.cacheLimit=o,this.cache=new Array(o),this.subscribe("auto cache",(S)=>{this.cacheIdx++,this.cacheIdx%=this.cacheLimit,this.cache[this.cacheIdx]=S})}toJSON(){return{members:[...this],cache:this.cache,cacheLimit:this.cacheLimit,cacheIdx:this.cacheIdx,cacheUpdateNumber:this.cacheUpdateNumber}}static fromJSON(T){let o=new bT(T.members,T.cacheLimit);return o.cache=T.cache,o.cacheIdx=T.cacheIdx,o.cacheUpdateNumber=T.cacheUpdateNumber,o}add(T){let o=super.add(T);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`add:${s(T)}`);return o}clear(){let T=this.mode==="record"?[...this]:null;if(super.clear(),T)this.cacheUpdateNumber++,this.emit(`clear:${JSON.stringify(T)}`)}delete(T){let o=super.delete(T);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`del:${s(T)}`);return o}parent;child=null;transactionUpdates=null;transaction(T){this.mode="transaction",this.transactionUpdates=[],this.child=new bT(this);let o=this.child._subscribe("transaction",(S)=>{this.transactionUpdates?.push(S)});try{if(T(this.child)){for(let f of this.transactionUpdates)this.doStep(f);this.cacheUpdateNumber++,this.emit(`tx:${this.transactionUpdates.join(";")}`)}}catch(S){throw console.error("Failed to apply transaction to SetRTX:",S),S}finally{o(),this.child=null,this.transactionUpdates=null,this.mode="record"}}_subscribe(T,o){return this.subject.subscribe(T,o)}subscribe(T,o){return this.subject.subscribe(T,(S)=>{o(`${this.cacheUpdateNumber}=${S}`)})}emit(T){this.subject.next(T)}doStep(T){let o=T.indexOf(":"),S=T.substring(0,o),f=T.substring(o+1);switch(S){case"add":this.add(JSON.parse(f));break;case"clear":this.clear();break;case"del":this.delete(JSON.parse(f));break;case"tx":for(let n of f.split(";"))this.doStep(n)}}getUpdateNumber(T){let o=T.indexOf("=");return Number(T.substring(0,o))}do(T){let o=T.indexOf("="),S=Number(T.substring(0,o)),f=S-this.cacheUpdateNumber;if(f>0){if(f===1){this.mode="playback";let A=T.substring(o+1);return this.doStep(A),this.mode="record",this.cacheUpdateNumber=S,null}return this.cacheUpdateNumber+1}if(Math.abs(f)<this.cacheLimit){let A=this.cacheIdx+f;if(this.cache[A]===T)return null;this.mode="playback";let F=!1;while(!F){this.cacheIdx%=this.cacheLimit;let R=this.cache[this.cacheIdx];if(this.cacheIdx--,!R)return"OUT_OF_RANGE";this.undo(R),F=this.cacheIdx===A-1}let J=T.substring(o+1);return this.doStep(J),this.mode="record",this.cacheUpdateNumber=S,null}return"OUT_OF_RANGE"}undoStep(T){let o=T.indexOf(":"),S=T.substring(0,o),f=T.substring(o+1);switch(S){case"add":this.delete(JSON.parse(f));break;case"del":this.add(JSON.parse(f));break;case"clear":{let n=JSON.parse(f);for(let A of n)this.add(A);break}case"tx":{let n=f.split(";");for(let A=n.length-1;A>=0;A--)this.undoStep(n[A])}}}undo(T){let o=T.indexOf("=");if(Number(T.substring(0,o))===this.cacheUpdateNumber){this.mode="playback";let f=T.substring(o+1);return this.undoStep(f),this.mode="record",this.cacheUpdateNumber--,null}return this.cacheUpdateNumber}}function HT(T){return T[0].toUpperCase()+T.slice(1)}class YA{toolkit;options;defaultContent;molecules=new Map;relations;states;core;transact(T,o){let S=this.toolkit;this.toolkit=T,o(this),this.toolkit=S}store;realm;[Symbol.dispose](){}constructor(T,o,S=a.STORE){this.store=S,this.realm=new sn(S),this.options=T,this.defaultContent=o,this.store.miscResources.set(`join:${T.key}`,this),this.realm.allocate("root",T.key),this.toolkit={get:(...G)=>RT(S,...G),set:(...G)=>{VT(S,...G)},find:(...G)=>i(S,...G),seek:(...G)=>qT(S,...G),json:(G)=>mT(S,G)};let f=T.between[0],n=T.between[1],A=Tf(S,{key:`${T.key}/relatedKeys`,default:()=>new bT,mutable:!0,fromJson:(G)=>bT.fromJSON(G),toJson:(G)=>G.toJSON()},["join","relations"]);this.core={relatedKeysAtoms:A};let $=({get:G},D)=>G(A,D),F=({set:G},D,t)=>{if(!this.store.molecules.has(s(D)))this.realm.allocate(T.key,D);G(A,D,(U)=>U.add(t)),G(A,t,(U)=>U.add(D))},J=({set:G},D,t)=>{G(A,D,(U)=>{return U.delete(t),U}),G(A,t,(U)=>{return U.delete(D),U})},R=(G,D,t)=>{let{find:U,get:v,set:l}=G,E=U(A,D),TT=v(E);for(let Z of TT){if(t.includes(Z))continue;l(A,Z,(MT)=>{return MT.delete(D),MT})}l(E,(Z)=>{return Z.transaction((oT)=>{oT.clear();for(let MT of t){let CT=$(G,MT),So=CT.has(D);if(this.relations.cardinality==="1:n"){let No=[];for(let z of CT){if(z===D)continue;let c=$(G,z);if(c.delete(MT),c.size===0)No.push(z)}if(!So&&CT.size>0)CT.clear();for(let z of No){let c=[MT,z].sort(),FT=`"${c[0]}:${c[1]}"`;this.molecules.delete(FT)}}if(!So)CT.add(D);oT.add(MT)}return!0}),Z})},W=(G,D,t)=>{let{set:U}=G;U(A,D,(v)=>{return v.transaction((l)=>{for(let E of t)l.add(E);return!0}),v});for(let v of t)U(A,v,(l)=>{return l.add(D),l});return!0},y=(G,D,t)=>{let U=$(G,D);return t?U.has(t):U.size>0},_={getRelatedKeys:(G)=>$(this.toolkit,G),addRelation:(G,D)=>{this.store.moleculeJoins.set(G,T.key),this.store.moleculeJoins.set(D,T.key),F(this.toolkit,G,D)},deleteRelation:(G,D)=>{J(this.toolkit,G,D)},replaceRelationsSafely:(G,D)=>{R(this.toolkit,G,D)},replaceRelationsUnsafely:(G,D)=>{W(this.toolkit,G,D)},has:(G,D)=>y(this.toolkit,G,D)},K,H;if(o){H=Lo(S,{key:`${T.key}/content`,default:o},["join","content"]);let G=({get:U},v)=>U(H,v),D=({set:U},v,l)=>{U(H,v,l)};K=Object.assign(_,{getContent:(U)=>{return G(this.toolkit,U)},setContent:(U,v)=>{D(this.toolkit,U,v)},deleteContent:(U)=>{this.realm.deallocate(U)}})}else K=_;let Y=new NT(T,{externalStore:K,isAType:T.isAType,isBType:T.isBType,makeContentKey:(...G)=>{let[D,t]=G,U=G.sort(),v=`${U[0]}:${U[1]}`,l=S.molecules.get(s(D)),E=S.molecules.get(s(t));if(!l)this.realm.allocate(T.key,D);if(!E)this.realm.allocate(T.key,t);return this.realm.allocate(D,v,"all"),this.realm.claim(t,v),this.store.moleculeJoins.set(v,T.key),v}}),I=()=>ho(S,{key:`${T.key}/singleRelatedKey`,get:(G)=>({get:D})=>{let t=D(A,G);for(let U of t)return U;return null}},["join","keys"]),b=()=>{return ho(S,{key:`${T.key}/multipleRelatedKeys`,get:(G)=>({get:D})=>{let t=kA(A,S);return D(t,G).members}},["join","keys"])},q=()=>ho(S,{key:`${T.key}/singleRelatedEntry`,get:(G)=>({get:D})=>{let t=D(A,G);for(let U of t){let v=Y.isAType?.(G)?G:void 0,l=v===void 0?G:void 0;v??=U,l??=U;let E=Y.makeContentKey(v,l),TT=D(H,E);return[U,TT]}return null}},["join","entries"]),p=()=>ho(S,{key:`${T.key}/multipleRelatedEntries`,get:(G)=>({get:D})=>{let t=kA(A,S);return D(t,G).members.map((v)=>{let l=Y.isAType?.(G)?G:void 0,E=l===void 0?G:void 0;l??=v,E??=v;let TT=Y.makeContentKey(l,E),Z=D(H,TT);return[v,Z]})}},["join","entries"]);switch(T.cardinality){case"1:1":{let G=I(),D=`${f}KeyOf${HT(n)}`,t=`${n}KeyOf${HT(f)}`,U={[D]:G,[t]:G},v;if(o){let l=q(),E=`${f}EntryOf${HT(n)}`,TT=`${n}EntryOf${HT(f)}`,Z={[E]:l,[TT]:l};v=Object.assign(U,Z)}else v=U;this.relations=Y,this.states=v;break}case"1:n":{let G=I(),D=b(),t=`${f}KeyOf${HT(n)}`,U=`${n}KeysOf${HT(f)}`,v={[t]:G,[U]:D},l;if(o){let E=q(),TT=p(),Z=`${f}EntryOf${HT(n)}`,oT=`${n}EntriesOf${HT(f)}`,MT={[Z]:E,[oT]:TT};l=Object.assign(v,MT)}else l=v;this.relations=Y,this.states=l;break}default:{let G=b(),D=`${f}KeysOf${HT(n)}`,t=`${n}KeysOf${HT(f)}`,U={[D]:G,[t]:G},v;if(o){let l=p(),E=`${f}EntriesOf${HT(n)}`,TT=`${n}EntriesOf${HT(f)}`,Z={[E]:l,[TT]:l};v=Object.assign(U,Z)}else v=U;this.relations=Y,this.states=v}}}}function Tn(T,o,S=a.STORE){return S.joins.set(T.key,new YA(T,o,S)),{key:T.key,type:"join",a:T.between[0],b:T.between[1],cardinality:T.cardinality}}function EA(T,o){let S=o.joins.get(T.key);if(S===void 0){let n=a.STORE.joins.get(T.key);if(n===void 0)throw new Error(`Join "${T.key}" not found in store "${o.config.name}"`);S=new YA(n.options,n.defaultContent,o),o.joins.set(T.key,S)}return S}function HA(T,o,S){let f=EA(T,S),n;switch(T.cardinality){case"1:1":{let A=`${T.a}KeyOf${HT(T.b)}`,$=`${T.b}KeyOf${HT(T.a)}`;n={get[A](){let J=f.states[A];return i(S,J,o)},get[$](){let J=f.states[$];return i(S,J,o)}};let F=`${T.a}EntryOf${HT(T.b)}`;if(F in f.states){let J=`${T.b}EntryOf${HT(T.a)}`;Object.assign(n,{get[F](){let R=f.states[F];return i(S,R,o)},get[J](){let R=f.states[J];return i(S,R,o)}})}break}case"1:n":{let A=`${T.a}KeyOf${HT(T.b)}`,$=`${T.b}KeysOf${HT(T.a)}`;n={get[A](){let J=f.states[A];return i(S,J,o)},get[$](){let J=f.states[$];return i(S,J,o)}};let F=`${T.a}EntryOf${HT(T.b)}`;if(F in f.states){let J=`${T.b}EntriesOf${HT(T.a)}`;Object.assign(n,{get[F](){let R=f.states[F];return i(S,R,o)},get[J](){let R=f.states[J];return i(S,R,o)}})}break}case"n:n":{let A=`${T.a}KeysOf${HT(T.b)}`,$=`${T.b}KeysOf${HT(T.a)}`;n={get[A](){let J=f.states[A];return i(S,J,o)},get[$](){let J=f.states[$];return i(S,J,o)}};let F=`${T.a}EntriesOf${HT(T.b)}`;if(F in f.states){let J=`${T.b}EntriesOf${HT(T.a)}`;Object.assign(n,{get[F](){let R=f.states[F];return i(S,R,o)},get[J](){let R=f.states[J];return i(S,R,o)}})}}}return n}function on(T,o,S){let f=EA(T,S),n=L(S);if(WT(n)){let{toolkit:A}=n.transactionMeta;f.transact(A,({relations:$})=>{o($)})}else o(f.relations)}function vW(T,o){return EA(T,o).core.relatedKeysAtoms}function hF(T){return vW(T,a.STORE)}class bF extends Map{set(T,o){if(this.has(T))return console.warn("Tried to set a key that already exists in an InvariantMap",{key:T,value:o}),this;return super.set(T,o)}clear(){throw new Error("Cannot clear an InvariantMap")}}class Sn{key;type="continuity";globals=[];actions=[];perspectives=[];constructor(T){this.key=T}static existing=new bF;static create(T,o){let S=new Sn(T),{type:f,globals:n,actions:A,perspectives:$}=o(S),F={type:f,key:T,globals:n,actions:A,perspectives:$};return Sn.existing.set(T,F),F}add(...T){switch(T[0].type){case"atom":case"mutable_atom":this.globals.push(...T);break;case"transaction":this.actions.push(...T);break;case"atom_family":{let[S,f]=T;this.perspectives.push({type:"realtime_perspective",resourceAtoms:S,viewAtoms:f})}break}return this}}function dK(T){let{key:o,config:S}=T,f=Sn.create(o,S),{actions:n}=f;for(let A of n)EF(o,A.key,a.STORE);return KF(o,-1,a.STORE),f}var sK=HS({key:"usersInRoomIndex",mutable:!0,default:()=>new bT,toJson:(T)=>T.toJSON(),fromJson:(T)=>bT.fromJSON(T)}),zA=HS({key:"roomIndex",default:()=>new bT,mutable:!0,toJson:(T)=>T.toJSON(),fromJson:(T)=>bT.fromJSON(T)}),qW={enteredAtEpoch:0},Rf=Tn({key:"usersInRooms",between:["room","user"],cardinality:"1:n",isAType:(T)=>typeof T==="string",isBType:(T)=>typeof T==="string"},qW),T5=rf({key:"usersInMyRoomView",get:(T)=>({find:o})=>{let S=hF(Rf);return[o(S,T)]}});import{spawn as ZW}from"child_process";class US{emit;listeners;globalListeners;handleEvent(T,...o){for(let f of this.globalListeners)f(T,...o);let S=this.listeners.get(T);if(S)for(let f of S)f(...o)}id="no_id_retrieved";constructor(T){this.emit=T;this.listeners=new Map,this.globalListeners=new Set}on(T,o){let S=this.listeners.get(T);if(S)S.add(o);else this.listeners.set(T,new Set([o]));return this}onAny(T){return this.globalListeners.add(T),this}off(T,o){let S=this.listeners.get(T);if(S)if(o)S.delete(o);else this.listeners.delete(T);return this}offAny(T){return this.globalListeners.delete(T),this}}class QA extends US{incompleteData="";unprocessedEvents=[];incompleteLog="";unprocessedLogs=[];id="#####";process;key;logger;handleLog(T){if(Array.isArray(T)){let[o,...S]=T;switch(o){case"i":this.logger.info(...S);break;case"w":this.logger.warn(...S);break;case"e":this.logger.error(...S);break}}}constructor(T,o,S){super((f,...n)=>{let A=JSON.stringify([f,...n])+"\x03",$=(F)=>{if(F.code==="EPIPE")console.error("EPIPE error during write",this.process.stdin);this.process.stdin.removeListener("error",$)};return this.process.stdin.once("error",$),this.process.stdin.write(A),this});if(this.process=T,this.key=o,this.logger=S??{info:(...f)=>{console.info(this.id,this.key,...f)},warn:(...f)=>{console.warn(this.id,this.key,...f)},error:(...f)=>{console.error(this.id,this.key,...f)}},this.process.stdout.on("data",(f)=>{let n=f.toString();if(n==="ALIVE")return;this.unprocessedEvents.push(...n.split("\x03"));let A=this.unprocessedEvents.shift();this.incompleteData+=A??"";try{if(this.incompleteData.startsWith("error"))console.log("\u2757",this.incompleteData);let $=tT(this.incompleteData);this.handleEvent(...$);while(this.unprocessedEvents.length>0){let F=this.unprocessedEvents.shift();if(F){if(this.unprocessedEvents.length===0)this.incompleteData=F;$=tT(F),this.handleEvent(...$)}}this.incompleteData=""}catch($){console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.warn(this.incompleteData),console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.error($)}}),this.process.stderr.on("data",(f)=>{let n=f.toString();this.unprocessedLogs.push(...n.split("\x03"));let A=this.unprocessedLogs.shift();this.incompleteLog+=A??"";try{let $=tT(this.incompleteLog);this.handleLog($);while(this.unprocessedLogs.length>0)if(this.incompleteLog=this.unprocessedLogs.shift()??"",this.incompleteLog)$=tT(this.incompleteLog),this.handleLog($)}catch($){console.error("\u274C\u274C\u274C"),console.error(this.incompleteLog),console.error($),console.error("\u274C\u274C\u274C\uFE0F")}}),T.pid)this.id=T.pid.toString()}}class xF extends US{in;out;id="no_id_retrieved";disposalFunctions=[];constructor(T){super((...o)=>{return this.out.next(o),this});this.id=T,this.in=new ST,this.out=new ST,this.in.subscribe("socket",(o)=>{this.handleEvent(...o)})}dispose(){for(let T of this.disposalFunctions)T()}}class DA extends US{incompleteData="";unprocessedEvents=[];relays;relayServices;process;id="#####";log(...T){this.process.stderr.write(s(T.map((o)=>o instanceof bT?`{ ${o.toJSON().members.join(" | ")} }`:o))+"\x03")}logger={info:(...T)=>{this.log("i",...T)},warn:(...T)=>{this.log("w",...T)},error:(...T)=>{this.log("e",...T)}};constructor(){super((T,...o)=>{let S=JSON.stringify([T,...o]);return this.process.stdout.write(S+"\x03"),this});if(this.process=process,this.process.stdin.resume(),this.relays=new Map,this.relayServices=[],this.process.stdin.on("data",(T)=>{let o=T.toString();this.unprocessedEvents.push(...o.split("\x03"));let S=this.unprocessedEvents.shift();this.incompleteData+=S??"";try{let f=tT(this.incompleteData);this.logger.info("\uD83C\uDFB0","received",f),this.handleEvent(...f);while(this.unprocessedEvents.length>0){let n=this.unprocessedEvents.shift();if(n){if(this.unprocessedEvents.length===0)this.incompleteData=n;let A=tT(n);this.handleEvent(...A)}}this.incompleteData=""}catch(f){if(f instanceof Error)this.logger.error("\u2757",f.message,f.cause,f.stack)}}),this.on("exit",()=>{this.logger.info("\uD83D\uDD25",this.id,'received "exit"'),process.exit(0)}),process.on("exit",(T)=>{this.logger.info("\uD83D\uDD25",this.id,`exited with code ${T}`)}),process.on("end",()=>{this.logger.info("\uD83D\uDD25",this.id,"ended"),process.exit(0)}),process.on("SIGTERM",()=>{this.logger.error("\uD83D\uDD25",this.id,"terminated"),process.exit(0)}),process.on("SIGINT",()=>{this.logger.error("\uD83D\uDD25",this.id,"interrupted"),process.exit(0)}),process.pid)this.id=process.pid?.toString();this.on("user-joins",(T)=>{this.logger.info("\uD83D\uDC64","user",T,"joined");let o=new xF(`user:${T}`);this.relays.set(T,o),this.logger.info("\uD83D\uDD17","attaching services:",`[${[...this.relayServices.keys()].join(", ")}]`);for(let S of this.relayServices){let f=S(o);if(f)o.disposalFunctions.push(f)}this.on(`user:${T}`,(...S)=>{o.in.next(S)}),o.out.subscribe("socket",(S)=>{this.emit(...S)})}),this.on("user-leaves",(T)=>{let o=this.relays.get(T);if(this.off(`relay:${T}`),o)o.dispose(),this.relays.delete(T)}),process.stdout.write("ALIVE")}relay(T){this.logger.info("\uD83D\uDD17","running relay method"),this.relayServices.push(T)}}var UA=AS({key:"roomArguments",default:["echo",["Hello World!"]]}),vF=rf({key:"room",get:(T)=>async({get:o,find:S})=>{let f=S(UA,T),n=o(f),[A,$]=n,F=await new Promise((J)=>{let R=ZW(A,$,{env:process.env}),W=(y)=>{if(y.toString()==="ALIVE")R.stdout.off("data",W),J(R)};R.stdout.on("data",W)});return new QA(F,T)}});var V5=Af({key:"createRoom",do:({get:T,set:o,find:S},f,n,A)=>{let $=A?[n,A]:[n],F=S(UA,f);o(F,$),o(zA,(W)=>W.add(f));let J=S(vF,f);return T(J)}}),B5=Af({key:"joinRoom",do:(T,o,S,f)=>{let n={enteredAtEpoch:f};return on(Rf,(A)=>{A.set({room:o,user:S},n)},T.env().store),n}}),L5=Af({key:"leaveRoom",do:(T,o,S)=>{on(Rf,(f)=>{f.delete({room:o,user:S})},T.env().store)}}),C5=Af({key:"destroyRoom",do:(T,o)=>{on(Rf,(S)=>{S.delete({room:o})},T.env().store),T.set(zA,(S)=>(S.delete(o),S))}});function tA(T,o){return o.map((S)=>{switch(S.type){case"transaction_update":{let f=tA(T,S.updates);return{...S,updates:f}}default:return S}}).filter((S)=>{switch(S.type){case"atom_update":case"selector_update":return T.includes(S.key);case"state_creation":return T.includes(S.token.key);case"molecule_creation":return!0;case"transaction_update":return!0}})}var m5=AS({key:"redactor",default:{occlude:(T)=>T}}),tS=AS({key:"unacknowledgedUpdates",default:()=>[]});var qF=AS({key:"sockets",default:null}),v5=HS({key:"socketsIndex",mutable:!0,default:()=>new bT,toJson:(T)=>T.toJSON(),fromJson:(T)=>bT.fromJSON(T)}),q5=HS({key:"usersIndex",mutable:!0,default:()=>new bT,toJson:(T)=>T.toJSON(),fromJson:(T)=>bT.fromJSON(T)}),VA=Tn({key:"usersOfSockets",between:["user","socket"],cardinality:"1:1",isAType:(T)=>T.startsWith("user::"),isBType:(T)=>T.startsWith("socket::")});function ZF(T,o,S,f){let n=o.key;return function A(){let $=[];for(let J of o.globals){let R=J.type==="mutable_atom"?mT(T,J):J,W=RT(T,R);$.push(R,W)}for(let J of o.perspectives){let{viewAtoms:R,resourceAtoms:W}=J,y=i(T,R,S),_=RT(T,y);T.logger.info("\uD83D\uDC41","atom",W.key,`${S} can see`,{viewAtoms:R,resourceAtoms:W,userView:_});for(let K of _){let H=K.type==="mutable_atom"?mT(T,K):K,Y=RT(T,H);$.push(H,Y)}}let F=hT(T)?T.transactionMeta.epoch.get(n)??null:null;f?.emit(`continuity-init:${n}`,F,$)}}function cF(T,o,S){let f=o.key;return function n(A){T.logger.info("\uD83D\uDECE\uFE0F","continuity",f,"received",A);let{key:$,id:F}=A,J=`tx-run:${$}:${F}`,R=`${J}:start`,W=`${J}:end`;performance.mark(R);try{zS({type:"transaction",key:$},F,T)(...A.params)}catch(_){if(_ instanceof Error)T.logger.error("\u274C","continuity",f,`failed to run transaction ${$} from ${S} with update ${F}`,_.message)}performance.mark(W);let y=performance.measure(J,R,W);T?.logger.info("\uD83D\uDE80","transaction",$,F,S,y.duration)}}function rF(T,o,S,f){let n=o.key;return function A($){if(T.logger.info("\uD83D\uDC4D","continuity",n,`${S} acknowledged epoch ${$}`),f[0]?.epoch===$)VT(T,tS,S,(J)=>{return J.shift(),T.logger.info("\uD83D\uDC4D","continuity",n,`${S} unacknowledged update queue now has`,J.length,"items"),J})}}function PF(T,o,S,f){let n=o.key,A=[];for(let $ of o.actions){let F=WA($,(J)=>{try{let R=o.globals.map((_)=>{if(_.type==="atom")return _.key;return xo(_).key}).concat(o.perspectives.flatMap((_)=>{let{viewAtoms:K}=_,H=i(T,K,S);return RT(T,H).map((I)=>{return I.type==="mutable_atom"?"*"+I.key:I.key})})),W=tA(R,J.updates),y={...J,updates:W};VT(T,tS,S,(_)=>{if(y)_.push(y),_.sort((K,H)=>K.epoch-H.epoch),T.logger.info("\uD83D\uDC4D","continuity",n,`${S} unacknowledged update queue now has`,_.length,"items");return _}),f?.emit(`tx-new:${n}`,y)}catch(R){if(R instanceof Error)T.logger.error("\u274C","continuity",n,`${S} failed to send update from transaction ${$.key} to ${S}`,R.message)}},`sync-continuity:${n}:${S}`,T);A.push(F)}return A}function pF(T,o,S,f){let n=o.key,A=[];for(let $ of o.perspectives){let{viewAtoms:F}=$,J=i(T,F,S),R=lT(J,({oldValue:W,newValue:y})=>{let _=W.map((I)=>I.key),K=y.map((I)=>I.key),H=W.filter((I)=>!K.includes(I.key)),Y=y.filter((I)=>!_.includes(I.key)).flatMap((I)=>{let b=I.type==="mutable_atom"?mT(T,I):I,q=RT(T,b);return[b,q]});if(T.logger.info("\uD83D\uDC41","atom",$.resourceAtoms.key,`${S} has a new perspective`,{oldKeys:_,newKeys:K,revealed:Y,concealed:H}),Y.length>0)f?.emit(`reveal:${n}`,Y);if(H.length>0)f?.emit(`conceal:${n}`,H)},`sync-continuity:${n}:${S}:perspective:${$.resourceAtoms.key}`,T);A.push(R)}return A}function wG({socket:T,store:o=a.STORE}){return function S(f){let n=T,A=f.key,$=HA(VA,`socket::${n.id}`,o).userKeyOfSocket,F=RT(o,$);if(!F)return o.logger.error("\u274C","continuity",A,`Tried to create a synchronizer for a socket (${n.id}) that is not connected to a user.`),()=>{};let J=HA(VA,F,o).socketKeyOfUser,R=lT(J,({newValue:b})=>{if(o.logger.info("\uD83D\uDC4B","continuity",A,`seeing ${F} on new socket ${b}`),b===null){o.logger.warn("\u274C","continuity",A,`User (${F}) is not connected to a socket, waiting for them to reappear.`);return}let q=i(o,qF,b);n=RT(o,q);for(let G of W)n?.emit(`tx-new:${A}`,G)},`sync-continuity:${A}:${F}`,o),W=RT(o,tS,F),y=[],_=pF(o,f,F,n),K=PF(o,f,F,n);y.push(..._,...K);let H=ZF(o,f,F,T);n.off(`get:${A}`,H),n.on(`get:${A}`,H);let Y=cF(o,f,F);n.off(`tx-run:${A}`,Y),n.on(`tx-run:${A}`,Y);let I=rF(o,f,F,W);return n?.on(`ack:${A}`,I),()=>{for(let b of y)b();n?.off(`ack:${A}`,I),n?.off(`get:${A}`,H),n?.off(`tx-run:${A}`,Y)}}}var{file:V1,serve:nk}=globalThis.Bun;import{readFileSync as $J}from"fs";import{resolve as mA}from"path";function cW(T,o){let S={},f=[];for(let n in T){let A=T[n],$=o[n],F=A["~standard"].validate($);if(F instanceof Promise)throw new Error(`Validation must be synchronous, but ${n} returned a Promise.`);if(F.issues){f.push(...F.issues.map((J)=>({...J,path:[n,...J.path??[]]})));continue}S[n]=F.value}if(f.length)return{issues:f};return{value:S}}function iF(T){let o=T.runtimeEnvStrict??T.runtimeEnv??process.env;if(T.emptyStringAsUndefined??!1){for(let[q,p]of Object.entries(o))if(p==="")delete o[q]}if(!!T.skipValidation)return o;let n=typeof T.client==="object"?T.client:{},A=typeof T.server==="object"?T.server:{},$=typeof T.shared==="object"?T.shared:{},F=T.isServer??(typeof window==="undefined"||("Deno"in window)),J=F?{...A,...$,...n}:{...n,...$},R=cW(J,o),W=T.onValidationError??((q)=>{throw console.error("\u274C Invalid environment variables:",q),new Error("Invalid environment variables")}),y=T.onInvalidAccess??(()=>{throw new Error("\u274C Attempted to access a server-side environment variable on the client")});if(R.issues)return W(R.issues);let _=(q)=>{if(!T.clientPrefix)return!0;return!q.startsWith(T.clientPrefix)&&!(q in $)},K=(q)=>{return F||!_(q)},H=(q)=>{return q==="__esModule"||q==="$$typeof"},Y=(T.extends??[]).reduce((q,p)=>{return Object.assign(q,p)},{}),I=Object.assign(R.value,Y);return new Proxy(I,{get(q,p){if(typeof p!=="string")return;if(H(p))return;if(!K(p))return y(p);return Reflect.get(q,p)}})}var $T;(function(T){T.assertEqual=(n)=>n;function o(n){}T.assertIs=o;function S(n){throw new Error}T.assertNever=S,T.arrayToEnum=(n)=>{let A={};for(let $ of n)A[$]=$;return A},T.getValidEnumValues=(n)=>{let A=T.objectKeys(n).filter((F)=>typeof n[n[F]]!=="number"),$={};for(let F of A)$[F]=n[F];return T.objectValues($)},T.objectValues=(n)=>{return T.objectKeys(n).map(function(A){return n[A]})},T.objectKeys=typeof Object.keys==="function"?(n)=>Object.keys(n):(n)=>{let A=[];for(let $ in n)if(Object.prototype.hasOwnProperty.call(n,$))A.push($);return A},T.find=(n,A)=>{for(let $ of n)if(A($))return $;return},T.isInteger=typeof Number.isInteger==="function"?(n)=>Number.isInteger(n):(n)=>typeof n==="number"&&isFinite(n)&&Math.floor(n)===n;function f(n,A=" | "){return n.map(($)=>typeof $==="string"?`'${$}'`:$).join(A)}T.joinValues=f,T.jsonStringifyReplacer=(n,A)=>{if(typeof A==="bigint")return A.toString();return A}})($T||($T={}));var LA;(function(T){T.mergeShapes=(o,S)=>{return{...o,...S}}})(LA||(LA={}));var N=$T.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),qo=(T)=>{switch(typeof T){case"undefined":return N.undefined;case"string":return N.string;case"number":return isNaN(T)?N.nan:N.number;case"boolean":return N.boolean;case"function":return N.function;case"bigint":return N.bigint;case"symbol":return N.symbol;case"object":if(Array.isArray(T))return N.array;if(T===null)return N.null;if(T.then&&typeof T.then==="function"&&T.catch&&typeof T.catch==="function")return N.promise;if(typeof Map!=="undefined"&&T instanceof Map)return N.map;if(typeof Set!=="undefined"&&T instanceof Set)return N.set;if(typeof Date!=="undefined"&&T instanceof Date)return N.date;return N.object;default:return N.unknown}},Q=$T.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),rW=(T)=>{return JSON.stringify(T,null,2).replace(/"([^"]+)":/g,"$1:")};class Jo extends Error{get errors(){return this.issues}constructor(T){super();this.issues=[],this.addIssue=(S)=>{this.issues=[...this.issues,S]},this.addIssues=(S=[])=>{this.issues=[...this.issues,...S]};let o=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,o);else this.__proto__=o;this.name="ZodError",this.issues=T}format(T){let o=T||function(n){return n.message},S={_errors:[]},f=(n)=>{for(let A of n.issues)if(A.code==="invalid_union")A.unionErrors.map(f);else if(A.code==="invalid_return_type")f(A.returnTypeError);else if(A.code==="invalid_arguments")f(A.argumentsError);else if(A.path.length===0)S._errors.push(o(A));else{let $=S,F=0;while(F<A.path.length){let J=A.path[F];if(F!==A.path.length-1)$[J]=$[J]||{_errors:[]};else $[J]=$[J]||{_errors:[]},$[J]._errors.push(o(A));$=$[J],F++}}};return f(this),S}static assert(T){if(!(T instanceof Jo))throw new Error(`Not a ZodError: ${T}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,$T.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(T=(o)=>o.message){let o={},S=[];for(let f of this.issues)if(f.path.length>0)o[f.path[0]]=o[f.path[0]]||[],o[f.path[0]].push(T(f));else S.push(T(f));return{formErrors:S,fieldErrors:o}}get formErrors(){return this.flatten()}}Jo.create=(T)=>{return new Jo(T)};var CS=(T,o)=>{let S;switch(T.code){case Q.invalid_type:if(T.received===N.undefined)S="Required";else S=`Expected ${T.expected}, received ${T.received}`;break;case Q.invalid_literal:S=`Invalid literal value, expected ${JSON.stringify(T.expected,$T.jsonStringifyReplacer)}`;break;case Q.unrecognized_keys:S=`Unrecognized key(s) in object: ${$T.joinValues(T.keys,", ")}`;break;case Q.invalid_union:S="Invalid input";break;case Q.invalid_union_discriminator:S=`Invalid discriminator value. Expected ${$T.joinValues(T.options)}`;break;case Q.invalid_enum_value:S=`Invalid enum value. Expected ${$T.joinValues(T.options)}, received '${T.received}'`;break;case Q.invalid_arguments:S="Invalid function arguments";break;case Q.invalid_return_type:S="Invalid function return type";break;case Q.invalid_date:S="Invalid date";break;case Q.invalid_string:if(typeof T.validation==="object")if("includes"in T.validation){if(S=`Invalid input: must include "${T.validation.includes}"`,typeof T.validation.position==="number")S=`${S} at one or more positions greater than or equal to ${T.validation.position}`}else if("startsWith"in T.validation)S=`Invalid input: must start with "${T.validation.startsWith}"`;else if("endsWith"in T.validation)S=`Invalid input: must end with "${T.validation.endsWith}"`;else $T.assertNever(T.validation);else if(T.validation!=="regex")S=`Invalid ${T.validation}`;else S="Invalid";break;case Q.too_small:if(T.type==="array")S=`Array must contain ${T.exact?"exactly":T.inclusive?"at least":"more than"} ${T.minimum} element(s)`;else if(T.type==="string")S=`String must contain ${T.exact?"exactly":T.inclusive?"at least":"over"} ${T.minimum} character(s)`;else if(T.type==="number")S=`Number must be ${T.exact?"exactly equal to ":T.inclusive?"greater than or equal to ":"greater than "}${T.minimum}`;else if(T.type==="date")S=`Date must be ${T.exact?"exactly equal to ":T.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(T.minimum))}`;else S="Invalid input";break;case Q.too_big:if(T.type==="array")S=`Array must contain ${T.exact?"exactly":T.inclusive?"at most":"less than"} ${T.maximum} element(s)`;else if(T.type==="string")S=`String must contain ${T.exact?"exactly":T.inclusive?"at most":"under"} ${T.maximum} character(s)`;else if(T.type==="number")S=`Number must be ${T.exact?"exactly":T.inclusive?"less than or equal to":"less than"} ${T.maximum}`;else if(T.type==="bigint")S=`BigInt must be ${T.exact?"exactly":T.inclusive?"less than or equal to":"less than"} ${T.maximum}`;else if(T.type==="date")S=`Date must be ${T.exact?"exactly":T.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(T.maximum))}`;else S="Invalid input";break;case Q.custom:S="Invalid input";break;case Q.invalid_intersection_types:S="Intersection results could not be merged";break;case Q.not_multiple_of:S=`Number must be a multiple of ${T.multipleOf}`;break;case Q.not_finite:S="Number must be finite";break;default:S=o.defaultError,$T.assertNever(T)}return{message:S}},uF=CS;function PW(T){uF=T}function fn(){return uF}var nn=(T)=>{let{data:o,path:S,errorMaps:f,issueData:n}=T,A=[...S,...n.path||[]],$={...n,path:A};if(n.message!==void 0)return{...n,path:A,message:n.message};let F="",J=f.filter((R)=>!!R).slice().reverse();for(let R of J)F=R($,{data:o,defaultError:F}).message;return{...n,path:A,message:F}},pW=[];function C(T,o){let S=fn(),f=nn({issueData:o,data:T.data,path:T.path,errorMaps:[T.common.contextualErrorMap,T.schemaErrorMap,S,S===CS?void 0:CS].filter((n)=>!!n)});T.common.issues.push(f)}class uT{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(T,o){let S=[];for(let f of o){if(f.status==="aborted")return d;if(f.status==="dirty")T.dirty();S.push(f.value)}return{status:T.value,value:S}}static async mergeObjectAsync(T,o){let S=[];for(let f of o){let n=await f.key,A=await f.value;S.push({key:n,value:A})}return uT.mergeObjectSync(T,S)}static mergeObjectSync(T,o){let S={};for(let f of o){let{key:n,value:A}=f;if(n.status==="aborted")return d;if(A.status==="aborted")return d;if(n.status==="dirty")T.dirty();if(A.status==="dirty")T.dirty();if(n.value!=="__proto__"&&(typeof A.value!=="undefined"||f.alwaysSet))S[n.value]=A.value}return{status:T.value,value:S}}}var d=Object.freeze({status:"aborted"}),BS=(T)=>({status:"dirty",value:T}),sT=(T)=>({status:"valid",value:T}),CA=(T)=>T.status==="aborted",IA=(T)=>T.status==="dirty",$S=(T)=>T.status==="valid",Mf=(T)=>typeof Promise!=="undefined"&&T instanceof Promise;function An(T,o,S,f){if(S==="a"&&!f)throw new TypeError("Private accessor was defined without a getter");if(typeof o==="function"?T!==o||!f:!o.has(T))throw new TypeError("Cannot read private member from an object whose class did not declare it");return S==="m"?f:S==="a"?f.call(T):f?f.value:o.get(T)}function eF(T,o,S,f,n){if(f==="m")throw new TypeError("Private method is not writable");if(f==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof o==="function"?T!==o||!n:!o.has(T))throw new TypeError("Cannot write private member to an object whose class did not declare it");return f==="a"?n.call(T,S):n?n.value=S:o.set(T,S),S}var x;(function(T){T.errToObj=(o)=>typeof o==="string"?{message:o}:o||{},T.toString=(o)=>typeof o==="string"?o:o===null||o===void 0?void 0:o.message})(x||(x={}));var Wf,Of;class Qo{constructor(T,o,S,f){this._cachedPath=[],this.parent=T,this.data=o,this._path=S,this._key=f}get path(){if(!this._cachedPath.length)if(this._key instanceof Array)this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var gF=(T,o)=>{if($S(o))return{success:!0,data:o.value};else{if(!T.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let S=new Jo(T.common.issues);return this._error=S,this._error}}}};function u(T){if(!T)return{};let{errorMap:o,invalid_type_error:S,required_error:f,description:n}=T;if(o&&(S||f))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(o)return{errorMap:o,description:n};return{errorMap:($,F)=>{var J,R;let{message:W}=T;if($.code==="invalid_enum_value")return{message:W!==null&&W!==void 0?W:F.defaultError};if(typeof F.data==="undefined")return{message:(J=W!==null&&W!==void 0?W:f)!==null&&J!==void 0?J:F.defaultError};if($.code!=="invalid_type")return{message:F.defaultError};return{message:(R=W!==null&&W!==void 0?W:S)!==null&&R!==void 0?R:F.defaultError}},description:n}}class e{get description(){return this._def.description}_getType(T){return qo(T.data)}_getOrReturnCtx(T,o){return o||{common:T.parent.common,data:T.data,parsedType:qo(T.data),schemaErrorMap:this._def.errorMap,path:T.path,parent:T.parent}}_processInputParams(T){return{status:new uT,ctx:{common:T.parent.common,data:T.data,parsedType:qo(T.data),schemaErrorMap:this._def.errorMap,path:T.path,parent:T.parent}}}_parseSync(T){let o=this._parse(T);if(Mf(o))throw new Error("Synchronous parse encountered promise.");return o}_parseAsync(T){let o=this._parse(T);return Promise.resolve(o)}parse(T,o){let S=this.safeParse(T,o);if(S.success)return S.data;throw S.error}safeParse(T,o){var S;let f={common:{issues:[],async:(S=o===null||o===void 0?void 0:o.async)!==null&&S!==void 0?S:!1,contextualErrorMap:o===null||o===void 0?void 0:o.errorMap},path:(o===null||o===void 0?void 0:o.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:T,parsedType:qo(T)},n=this._parseSync({data:T,path:f.path,parent:f});return gF(f,n)}"~validate"(T){var o,S;let f={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:T,parsedType:qo(T)};if(!this["~standard"].async)try{let n=this._parseSync({data:T,path:[],parent:f});return $S(n)?{value:n.value}:{issues:f.common.issues}}catch(n){if((S=(o=n===null||n===void 0?void 0:n.message)===null||o===void 0?void 0:o.toLowerCase())===null||S===void 0?void 0:S.includes("encountered"))this["~standard"].async=!0;f.common={issues:[],async:!0}}return this._parseAsync({data:T,path:[],parent:f}).then((n)=>$S(n)?{value:n.value}:{issues:f.common.issues})}async parseAsync(T,o){let S=await this.safeParseAsync(T,o);if(S.success)return S.data;throw S.error}async safeParseAsync(T,o){let S={common:{issues:[],contextualErrorMap:o===null||o===void 0?void 0:o.errorMap,async:!0},path:(o===null||o===void 0?void 0:o.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:T,parsedType:qo(T)},f=this._parse({data:T,path:S.path,parent:S}),n=await(Mf(f)?f:Promise.resolve(f));return gF(S,n)}refine(T,o){let S=(f)=>{if(typeof o==="string"||typeof o==="undefined")return{message:o};else if(typeof o==="function")return o(f);else return o};return this._refinement((f,n)=>{let A=T(f),$=()=>n.addIssue({code:Q.custom,...S(f)});if(typeof Promise!=="undefined"&&A instanceof Promise)return A.then((F)=>{if(!F)return $(),!1;else return!0});if(!A)return $(),!1;else return!0})}refinement(T,o){return this._refinement((S,f)=>{if(!T(S))return f.addIssue(typeof o==="function"?o(S,f):o),!1;else return!0})}_refinement(T){return new yo({schema:this,typeName:g.ZodEffects,effect:{type:"refinement",refinement:T}})}superRefine(T){return this._refinement(T)}constructor(T){this.spa=this.safeParseAsync,this._def=T,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:(o)=>this["~validate"](o)}}optional(){return zo.create(this,this._def)}nullable(){return Zo.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ho.create(this)}promise(){return WS.create(this,this._def)}or(T){return NS.create([this,T],this._def)}and(T){return hS.create(this,T,this._def)}transform(T){return new yo({...u(this._def),schema:this,typeName:g.ZodEffects,effect:{type:"transform",transform:T}})}default(T){let o=typeof T==="function"?T:()=>T;return new qS({...u(this._def),innerType:this,defaultValue:o,typeName:g.ZodDefault})}brand(){return new Fn({typeName:g.ZodBranded,type:this,...u(this._def)})}catch(T){let o=typeof T==="function"?T:()=>T;return new ZS({...u(this._def),innerType:this,catchValue:o,typeName:g.ZodCatch})}describe(T){return new this.constructor({...this._def,description:T})}pipe(T){return Kf.create(this,T)}readonly(){return cS.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var iW=/^c[^\s-]{8,}$/i,gW=/^[0-9a-z]+$/,dW=/^[0-9A-HJKMNP-TV-Z]{26}$/i,lW=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,uW=/^[a-z0-9_-]{21}$/i,eW=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,aW=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,sW=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,TO="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",BA,oO=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,SO=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,fO=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,nO=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,AO=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,$O=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,aF="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",FO=new RegExp(`^${aF}$`);function sF(T){let o="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";if(T.precision)o=`${o}\\.\\d{${T.precision}}`;else if(T.precision==null)o=`${o}(\\.\\d+)?`;return o}function JO(T){return new RegExp(`^${sF(T)}$`)}function TJ(T){let o=`${aF}T${sF(T)}`,S=[];if(S.push(T.local?"Z?":"Z"),T.offset)S.push("([+-]\\d{2}:?\\d{2})");return o=`${o}(${S.join("|")})`,new RegExp(`^${o}$`)}function RO(T,o){if((o==="v4"||!o)&&oO.test(T))return!0;if((o==="v6"||!o)&&fO.test(T))return!0;return!1}function WO(T,o){if(!eW.test(T))return!1;try{let[S]=T.split("."),f=S.replace(/-/g,"+").replace(/_/g,"/").padEnd(S.length+(4-S.length%4)%4,"="),n=JSON.parse(atob(f));if(typeof n!=="object"||n===null)return!1;if(!n.typ||!n.alg)return!1;if(o&&n.alg!==o)return!1;return!0}catch(S){return!1}}function OO(T,o){if((o==="v4"||!o)&&SO.test(T))return!0;if((o==="v6"||!o)&&nO.test(T))return!0;return!1}class Eo extends e{_parse(T){if(this._def.coerce)T.data=String(T.data);if(this._getType(T)!==N.string){let n=this._getOrReturnCtx(T);return C(n,{code:Q.invalid_type,expected:N.string,received:n.parsedType}),d}let S=new uT,f=void 0;for(let n of this._def.checks)if(n.kind==="min"){if(T.data.length<n.value)f=this._getOrReturnCtx(T,f),C(f,{code:Q.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),S.dirty()}else if(n.kind==="max"){if(T.data.length>n.value)f=this._getOrReturnCtx(T,f),C(f,{code:Q.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),S.dirty()}else if(n.kind==="length"){let A=T.data.length>n.value,$=T.data.length<n.value;if(A||$){if(f=this._getOrReturnCtx(T,f),A)C(f,{code:Q.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message});else if($)C(f,{code:Q.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message});S.dirty()}}else if(n.kind==="email"){if(!sW.test(T.data))f=this._getOrReturnCtx(T,f),C(f,{validation:"email",code:Q.invalid_string,message:n.message}),S.dirty()}else if(n.kind==="emoji"){if(!BA)BA=new RegExp(TO,"u");if(!BA.test(T.data))f=this._getOrReturnCtx(T,f),C(f,{validation:"emoji",code:Q.invalid_string,message:n.message}),S.dirty()}else if(n.kind==="uuid"){if(!lW.test(T.data))f=this._getOrReturnCtx(T,f),C(f,{validation:"uuid",code:Q.invalid_string,message:n.message}),S.dirty()}else if(n.kind==="nanoid"){if(!uW.test(T.data))f=this._getOrReturnCtx(T,f),C(f,{validation:"nanoid",code:Q.invalid_string,message:n.message}),S.dirty()}else if(n.kind==="cuid"){if(!iW.test(T.data))f=this._getOrReturnCtx(T,f),C(f,{validation:"cuid",code:Q.invalid_string,message:n.message}),S.dirty()}else if(n.kind==="cuid2"){if(!gW.test(T.data))f=this._getOrReturnCtx(T,f),C(f,{validation:"cuid2",code:Q.invalid_string,message:n.message}),S.dirty()}else if(n.kind==="ulid"){if(!dW.test(T.data))f=this._getOrReturnCtx(T,f),C(f,{validation:"ulid",code:Q.invalid_string,message:n.message}),S.dirty()}else if(n.kind==="url")try{new URL(T.data)}catch(A){f=this._getOrReturnCtx(T,f),C(f,{validation:"url",code:Q.invalid_string,message:n.message}),S.dirty()}else if(n.kind==="regex"){if(n.regex.lastIndex=0,!n.regex.test(T.data))f=this._getOrReturnCtx(T,f),C(f,{validation:"regex",code:Q.invalid_string,message:n.message}),S.dirty()}else if(n.kind==="trim")T.data=T.data.trim();else if(n.kind==="includes"){if(!T.data.includes(n.value,n.position))f=this._getOrReturnCtx(T,f),C(f,{code:Q.invalid_string,validation:{includes:n.value,position:n.position},message:n.message}),S.dirty()}else if(n.kind==="toLowerCase")T.data=T.data.toLowerCase();else if(n.kind==="toUpperCase")T.data=T.data.toUpperCase();else if(n.kind==="startsWith"){if(!T.data.startsWith(n.value))f=this._getOrReturnCtx(T,f),C(f,{code:Q.invalid_string,validation:{startsWith:n.value},message:n.message}),S.dirty()}else if(n.kind==="endsWith"){if(!T.data.endsWith(n.value))f=this._getOrReturnCtx(T,f),C(f,{code:Q.invalid_string,validation:{endsWith:n.value},message:n.message}),S.dirty()}else if(n.kind==="datetime"){if(!TJ(n).test(T.data))f=this._getOrReturnCtx(T,f),C(f,{code:Q.invalid_string,validation:"datetime",message:n.message}),S.dirty()}else if(n.kind==="date"){if(!FO.test(T.data))f=this._getOrReturnCtx(T,f),C(f,{code:Q.invalid_string,validation:"date",message:n.message}),S.dirty()}else if(n.kind==="time"){if(!JO(n).test(T.data))f=this._getOrReturnCtx(T,f),C(f,{code:Q.invalid_string,validation:"time",message:n.message}),S.dirty()}else if(n.kind==="duration"){if(!aW.test(T.data))f=this._getOrReturnCtx(T,f),C(f,{validation:"duration",code:Q.invalid_string,message:n.message}),S.dirty()}else if(n.kind==="ip"){if(!RO(T.data,n.version))f=this._getOrReturnCtx(T,f),C(f,{validation:"ip",code:Q.invalid_string,message:n.message}),S.dirty()}else if(n.kind==="jwt"){if(!WO(T.data,n.alg))f=this._getOrReturnCtx(T,f),C(f,{validation:"jwt",code:Q.invalid_string,message:n.message}),S.dirty()}else if(n.kind==="cidr"){if(!OO(T.data,n.version))f=this._getOrReturnCtx(T,f),C(f,{validation:"cidr",code:Q.invalid_string,message:n.message}),S.dirty()}else if(n.kind==="base64"){if(!AO.test(T.data))f=this._getOrReturnCtx(T,f),C(f,{validation:"base64",code:Q.invalid_string,message:n.message}),S.dirty()}else if(n.kind==="base64url"){if(!$O.test(T.data))f=this._getOrReturnCtx(T,f),C(f,{validation:"base64url",code:Q.invalid_string,message:n.message}),S.dirty()}else $T.assertNever(n);return{status:S.value,value:T.data}}_regex(T,o,S){return this.refinement((f)=>T.test(f),{validation:o,code:Q.invalid_string,...x.errToObj(S)})}_addCheck(T){return new Eo({...this._def,checks:[...this._def.checks,T]})}email(T){return this._addCheck({kind:"email",...x.errToObj(T)})}url(T){return this._addCheck({kind:"url",...x.errToObj(T)})}emoji(T){return this._addCheck({kind:"emoji",...x.errToObj(T)})}uuid(T){return this._addCheck({kind:"uuid",...x.errToObj(T)})}nanoid(T){return this._addCheck({kind:"nanoid",...x.errToObj(T)})}cuid(T){return this._addCheck({kind:"cuid",...x.errToObj(T)})}cuid2(T){return this._addCheck({kind:"cuid2",...x.errToObj(T)})}ulid(T){return this._addCheck({kind:"ulid",...x.errToObj(T)})}base64(T){return this._addCheck({kind:"base64",...x.errToObj(T)})}base64url(T){return this._addCheck({kind:"base64url",...x.errToObj(T)})}jwt(T){return this._addCheck({kind:"jwt",...x.errToObj(T)})}ip(T){return this._addCheck({kind:"ip",...x.errToObj(T)})}cidr(T){return this._addCheck({kind:"cidr",...x.errToObj(T)})}datetime(T){var o,S;if(typeof T==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:T});return this._addCheck({kind:"datetime",precision:typeof(T===null||T===void 0?void 0:T.precision)==="undefined"?null:T===null||T===void 0?void 0:T.precision,offset:(o=T===null||T===void 0?void 0:T.offset)!==null&&o!==void 0?o:!1,local:(S=T===null||T===void 0?void 0:T.local)!==null&&S!==void 0?S:!1,...x.errToObj(T===null||T===void 0?void 0:T.message)})}date(T){return this._addCheck({kind:"date",message:T})}time(T){if(typeof T==="string")return this._addCheck({kind:"time",precision:null,message:T});return this._addCheck({kind:"time",precision:typeof(T===null||T===void 0?void 0:T.precision)==="undefined"?null:T===null||T===void 0?void 0:T.precision,...x.errToObj(T===null||T===void 0?void 0:T.message)})}duration(T){return this._addCheck({kind:"duration",...x.errToObj(T)})}regex(T,o){return this._addCheck({kind:"regex",regex:T,...x.errToObj(o)})}includes(T,o){return this._addCheck({kind:"includes",value:T,position:o===null||o===void 0?void 0:o.position,...x.errToObj(o===null||o===void 0?void 0:o.message)})}startsWith(T,o){return this._addCheck({kind:"startsWith",value:T,...x.errToObj(o)})}endsWith(T,o){return this._addCheck({kind:"endsWith",value:T,...x.errToObj(o)})}min(T,o){return this._addCheck({kind:"min",value:T,...x.errToObj(o)})}max(T,o){return this._addCheck({kind:"max",value:T,...x.errToObj(o)})}length(T,o){return this._addCheck({kind:"length",value:T,...x.errToObj(o)})}nonempty(T){return this.min(1,x.errToObj(T))}trim(){return new Eo({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Eo({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Eo({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((T)=>T.kind==="datetime")}get isDate(){return!!this._def.checks.find((T)=>T.kind==="date")}get isTime(){return!!this._def.checks.find((T)=>T.kind==="time")}get isDuration(){return!!this._def.checks.find((T)=>T.kind==="duration")}get isEmail(){return!!this._def.checks.find((T)=>T.kind==="email")}get isURL(){return!!this._def.checks.find((T)=>T.kind==="url")}get isEmoji(){return!!this._def.checks.find((T)=>T.kind==="emoji")}get isUUID(){return!!this._def.checks.find((T)=>T.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((T)=>T.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((T)=>T.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((T)=>T.kind==="cuid2")}get isULID(){return!!this._def.checks.find((T)=>T.kind==="ulid")}get isIP(){return!!this._def.checks.find((T)=>T.kind==="ip")}get isCIDR(){return!!this._def.checks.find((T)=>T.kind==="cidr")}get isBase64(){return!!this._def.checks.find((T)=>T.kind==="base64")}get isBase64url(){return!!this._def.checks.find((T)=>T.kind==="base64url")}get minLength(){let T=null;for(let o of this._def.checks)if(o.kind==="min"){if(T===null||o.value>T)T=o.value}return T}get maxLength(){let T=null;for(let o of this._def.checks)if(o.kind==="max"){if(T===null||o.value<T)T=o.value}return T}}Eo.create=(T)=>{var o;return new Eo({checks:[],typeName:g.ZodString,coerce:(o=T===null||T===void 0?void 0:T.coerce)!==null&&o!==void 0?o:!1,...u(T)})};function MO(T,o){let S=(T.toString().split(".")[1]||"").length,f=(o.toString().split(".")[1]||"").length,n=S>f?S:f,A=parseInt(T.toFixed(n).replace(".","")),$=parseInt(o.toFixed(n).replace(".",""));return A%$/Math.pow(10,n)}class uo extends e{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(T){if(this._def.coerce)T.data=Number(T.data);if(this._getType(T)!==N.number){let n=this._getOrReturnCtx(T);return C(n,{code:Q.invalid_type,expected:N.number,received:n.parsedType}),d}let S=void 0,f=new uT;for(let n of this._def.checks)if(n.kind==="int"){if(!$T.isInteger(T.data))S=this._getOrReturnCtx(T,S),C(S,{code:Q.invalid_type,expected:"integer",received:"float",message:n.message}),f.dirty()}else if(n.kind==="min"){if(n.inclusive?T.data<n.value:T.data<=n.value)S=this._getOrReturnCtx(T,S),C(S,{code:Q.too_small,minimum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),f.dirty()}else if(n.kind==="max"){if(n.inclusive?T.data>n.value:T.data>=n.value)S=this._getOrReturnCtx(T,S),C(S,{code:Q.too_big,maximum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),f.dirty()}else if(n.kind==="multipleOf"){if(MO(T.data,n.value)!==0)S=this._getOrReturnCtx(T,S),C(S,{code:Q.not_multiple_of,multipleOf:n.value,message:n.message}),f.dirty()}else if(n.kind==="finite"){if(!Number.isFinite(T.data))S=this._getOrReturnCtx(T,S),C(S,{code:Q.not_finite,message:n.message}),f.dirty()}else $T.assertNever(n);return{status:f.value,value:T.data}}gte(T,o){return this.setLimit("min",T,!0,x.toString(o))}gt(T,o){return this.setLimit("min",T,!1,x.toString(o))}lte(T,o){return this.setLimit("max",T,!0,x.toString(o))}lt(T,o){return this.setLimit("max",T,!1,x.toString(o))}setLimit(T,o,S,f){return new uo({...this._def,checks:[...this._def.checks,{kind:T,value:o,inclusive:S,message:x.toString(f)}]})}_addCheck(T){return new uo({...this._def,checks:[...this._def.checks,T]})}int(T){return this._addCheck({kind:"int",message:x.toString(T)})}positive(T){return this._addCheck({kind:"min",value:0,inclusive:!1,message:x.toString(T)})}negative(T){return this._addCheck({kind:"max",value:0,inclusive:!1,message:x.toString(T)})}nonpositive(T){return this._addCheck({kind:"max",value:0,inclusive:!0,message:x.toString(T)})}nonnegative(T){return this._addCheck({kind:"min",value:0,inclusive:!0,message:x.toString(T)})}multipleOf(T,o){return this._addCheck({kind:"multipleOf",value:T,message:x.toString(o)})}finite(T){return this._addCheck({kind:"finite",message:x.toString(T)})}safe(T){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:x.toString(T)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:x.toString(T)})}get minValue(){let T=null;for(let o of this._def.checks)if(o.kind==="min"){if(T===null||o.value>T)T=o.value}return T}get maxValue(){let T=null;for(let o of this._def.checks)if(o.kind==="max"){if(T===null||o.value<T)T=o.value}return T}get isInt(){return!!this._def.checks.find((T)=>T.kind==="int"||T.kind==="multipleOf"&&$T.isInteger(T.value))}get isFinite(){let T=null,o=null;for(let S of this._def.checks)if(S.kind==="finite"||S.kind==="int"||S.kind==="multipleOf")return!0;else if(S.kind==="min"){if(o===null||S.value>o)o=S.value}else if(S.kind==="max"){if(T===null||S.value<T)T=S.value}return Number.isFinite(o)&&Number.isFinite(T)}}uo.create=(T)=>{return new uo({checks:[],typeName:g.ZodNumber,coerce:(T===null||T===void 0?void 0:T.coerce)||!1,...u(T)})};class eo extends e{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(T){if(this._def.coerce)try{T.data=BigInt(T.data)}catch(n){return this._getInvalidInput(T)}if(this._getType(T)!==N.bigint)return this._getInvalidInput(T);let S=void 0,f=new uT;for(let n of this._def.checks)if(n.kind==="min"){if(n.inclusive?T.data<n.value:T.data<=n.value)S=this._getOrReturnCtx(T,S),C(S,{code:Q.too_small,type:"bigint",minimum:n.value,inclusive:n.inclusive,message:n.message}),f.dirty()}else if(n.kind==="max"){if(n.inclusive?T.data>n.value:T.data>=n.value)S=this._getOrReturnCtx(T,S),C(S,{code:Q.too_big,type:"bigint",maximum:n.value,inclusive:n.inclusive,message:n.message}),f.dirty()}else if(n.kind==="multipleOf"){if(T.data%n.value!==BigInt(0))S=this._getOrReturnCtx(T,S),C(S,{code:Q.not_multiple_of,multipleOf:n.value,message:n.message}),f.dirty()}else $T.assertNever(n);return{status:f.value,value:T.data}}_getInvalidInput(T){let o=this._getOrReturnCtx(T);return C(o,{code:Q.invalid_type,expected:N.bigint,received:o.parsedType}),d}gte(T,o){return this.setLimit("min",T,!0,x.toString(o))}gt(T,o){return this.setLimit("min",T,!1,x.toString(o))}lte(T,o){return this.setLimit("max",T,!0,x.toString(o))}lt(T,o){return this.setLimit("max",T,!1,x.toString(o))}setLimit(T,o,S,f){return new eo({...this._def,checks:[...this._def.checks,{kind:T,value:o,inclusive:S,message:x.toString(f)}]})}_addCheck(T){return new eo({...this._def,checks:[...this._def.checks,T]})}positive(T){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:x.toString(T)})}negative(T){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:x.toString(T)})}nonpositive(T){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:x.toString(T)})}nonnegative(T){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:x.toString(T)})}multipleOf(T,o){return this._addCheck({kind:"multipleOf",value:T,message:x.toString(o)})}get minValue(){let T=null;for(let o of this._def.checks)if(o.kind==="min"){if(T===null||o.value>T)T=o.value}return T}get maxValue(){let T=null;for(let o of this._def.checks)if(o.kind==="max"){if(T===null||o.value<T)T=o.value}return T}}eo.create=(T)=>{var o;return new eo({checks:[],typeName:g.ZodBigInt,coerce:(o=T===null||T===void 0?void 0:T.coerce)!==null&&o!==void 0?o:!1,...u(T)})};class IS extends e{_parse(T){if(this._def.coerce)T.data=Boolean(T.data);if(this._getType(T)!==N.boolean){let S=this._getOrReturnCtx(T);return C(S,{code:Q.invalid_type,expected:N.boolean,received:S.parsedType}),d}return sT(T.data)}}IS.create=(T)=>{return new IS({typeName:g.ZodBoolean,coerce:(T===null||T===void 0?void 0:T.coerce)||!1,...u(T)})};class FS extends e{_parse(T){if(this._def.coerce)T.data=new Date(T.data);if(this._getType(T)!==N.date){let n=this._getOrReturnCtx(T);return C(n,{code:Q.invalid_type,expected:N.date,received:n.parsedType}),d}if(isNaN(T.data.getTime())){let n=this._getOrReturnCtx(T);return C(n,{code:Q.invalid_date}),d}let S=new uT,f=void 0;for(let n of this._def.checks)if(n.kind==="min"){if(T.data.getTime()<n.value)f=this._getOrReturnCtx(T,f),C(f,{code:Q.too_small,message:n.message,inclusive:!0,exact:!1,minimum:n.value,type:"date"}),S.dirty()}else if(n.kind==="max"){if(T.data.getTime()>n.value)f=this._getOrReturnCtx(T,f),C(f,{code:Q.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),S.dirty()}else $T.assertNever(n);return{status:S.value,value:new Date(T.data.getTime())}}_addCheck(T){return new FS({...this._def,checks:[...this._def.checks,T]})}min(T,o){return this._addCheck({kind:"min",value:T.getTime(),message:x.toString(o)})}max(T,o){return this._addCheck({kind:"max",value:T.getTime(),message:x.toString(o)})}get minDate(){let T=null;for(let o of this._def.checks)if(o.kind==="min"){if(T===null||o.value>T)T=o.value}return T!=null?new Date(T):null}get maxDate(){let T=null;for(let o of this._def.checks)if(o.kind==="max"){if(T===null||o.value<T)T=o.value}return T!=null?new Date(T):null}}FS.create=(T)=>{return new FS({checks:[],coerce:(T===null||T===void 0?void 0:T.coerce)||!1,typeName:g.ZodDate,...u(T)})};class kf extends e{_parse(T){if(this._getType(T)!==N.symbol){let S=this._getOrReturnCtx(T);return C(S,{code:Q.invalid_type,expected:N.symbol,received:S.parsedType}),d}return sT(T.data)}}kf.create=(T)=>{return new kf({typeName:g.ZodSymbol,...u(T)})};class jS extends e{_parse(T){if(this._getType(T)!==N.undefined){let S=this._getOrReturnCtx(T);return C(S,{code:Q.invalid_type,expected:N.undefined,received:S.parsedType}),d}return sT(T.data)}}jS.create=(T)=>{return new jS({typeName:g.ZodUndefined,...u(T)})};class mS extends e{_parse(T){if(this._getType(T)!==N.null){let S=this._getOrReturnCtx(T);return C(S,{code:Q.invalid_type,expected:N.null,received:S.parsedType}),d}return sT(T.data)}}mS.create=(T)=>{return new mS({typeName:g.ZodNull,...u(T)})};class JS extends e{constructor(){super(...arguments);this._any=!0}_parse(T){return sT(T.data)}}JS.create=(T)=>{return new JS({typeName:g.ZodAny,...u(T)})};class lo extends e{constructor(){super(...arguments);this._unknown=!0}_parse(T){return sT(T.data)}}lo.create=(T)=>{return new lo({typeName:g.ZodUnknown,...u(T)})};class Co extends e{_parse(T){let o=this._getOrReturnCtx(T);return C(o,{code:Q.invalid_type,expected:N.never,received:o.parsedType}),d}}Co.create=(T)=>{return new Co({typeName:g.ZodNever,...u(T)})};class yf extends e{_parse(T){if(this._getType(T)!==N.undefined){let S=this._getOrReturnCtx(T);return C(S,{code:Q.invalid_type,expected:N.void,received:S.parsedType}),d}return sT(T.data)}}yf.create=(T)=>{return new yf({typeName:g.ZodVoid,...u(T)})};class Ho extends e{_parse(T){let{ctx:o,status:S}=this._processInputParams(T),f=this._def;if(o.parsedType!==N.array)return C(o,{code:Q.invalid_type,expected:N.array,received:o.parsedType}),d;if(f.exactLength!==null){let A=o.data.length>f.exactLength.value,$=o.data.length<f.exactLength.value;if(A||$)C(o,{code:A?Q.too_big:Q.too_small,minimum:$?f.exactLength.value:void 0,maximum:A?f.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:f.exactLength.message}),S.dirty()}if(f.minLength!==null){if(o.data.length<f.minLength.value)C(o,{code:Q.too_small,minimum:f.minLength.value,type:"array",inclusive:!0,exact:!1,message:f.minLength.message}),S.dirty()}if(f.maxLength!==null){if(o.data.length>f.maxLength.value)C(o,{code:Q.too_big,maximum:f.maxLength.value,type:"array",inclusive:!0,exact:!1,message:f.maxLength.message}),S.dirty()}if(o.common.async)return Promise.all([...o.data].map((A,$)=>{return f.type._parseAsync(new Qo(o,A,o.path,$))})).then((A)=>{return uT.mergeArray(S,A)});let n=[...o.data].map((A,$)=>{return f.type._parseSync(new Qo(o,A,o.path,$))});return uT.mergeArray(S,n)}get element(){return this._def.type}min(T,o){return new Ho({...this._def,minLength:{value:T,message:x.toString(o)}})}max(T,o){return new Ho({...this._def,maxLength:{value:T,message:x.toString(o)}})}length(T,o){return new Ho({...this._def,exactLength:{value:T,message:x.toString(o)}})}nonempty(T){return this.min(1,T)}}Ho.create=(T,o)=>{return new Ho({type:T,minLength:null,maxLength:null,exactLength:null,typeName:g.ZodArray,...u(o)})};function VS(T){if(T instanceof QT){let o={};for(let S in T.shape){let f=T.shape[S];o[S]=zo.create(VS(f))}return new QT({...T._def,shape:()=>o})}else if(T instanceof Ho)return new Ho({...T._def,type:VS(T.element)});else if(T instanceof zo)return zo.create(VS(T.unwrap()));else if(T instanceof Zo)return Zo.create(VS(T.unwrap()));else if(T instanceof Io)return Io.create(T.items.map((o)=>VS(o)));else return T}class QT extends e{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let T=this._def.shape(),o=$T.objectKeys(T);return this._cached={shape:T,keys:o}}_parse(T){if(this._getType(T)!==N.object){let J=this._getOrReturnCtx(T);return C(J,{code:Q.invalid_type,expected:N.object,received:J.parsedType}),d}let{status:S,ctx:f}=this._processInputParams(T),{shape:n,keys:A}=this._getCached(),$=[];if(!(this._def.catchall instanceof Co&&this._def.unknownKeys==="strip")){for(let J in f.data)if(!A.includes(J))$.push(J)}let F=[];for(let J of A){let R=n[J],W=f.data[J];F.push({key:{status:"valid",value:J},value:R._parse(new Qo(f,W,f.path,J)),alwaysSet:J in f.data})}if(this._def.catchall instanceof Co){let J=this._def.unknownKeys;if(J==="passthrough")for(let R of $)F.push({key:{status:"valid",value:R},value:{status:"valid",value:f.data[R]}});else if(J==="strict"){if($.length>0)C(f,{code:Q.unrecognized_keys,keys:$}),S.dirty()}else if(J==="strip");else throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let J=this._def.catchall;for(let R of $){let W=f.data[R];F.push({key:{status:"valid",value:R},value:J._parse(new Qo(f,W,f.path,R)),alwaysSet:R in f.data})}}if(f.common.async)return Promise.resolve().then(async()=>{let J=[];for(let R of F){let W=await R.key,y=await R.value;J.push({key:W,value:y,alwaysSet:R.alwaysSet})}return J}).then((J)=>{return uT.mergeObjectSync(S,J)});else return uT.mergeObjectSync(S,F)}get shape(){return this._def.shape()}strict(T){return x.errToObj,new QT({...this._def,unknownKeys:"strict",...T!==void 0?{errorMap:(o,S)=>{var f,n,A,$;let F=(A=(n=(f=this._def).errorMap)===null||n===void 0?void 0:n.call(f,o,S).message)!==null&&A!==void 0?A:S.defaultError;if(o.code==="unrecognized_keys")return{message:($=x.errToObj(T).message)!==null&&$!==void 0?$:F};return{message:F}}}:{}})}strip(){return new QT({...this._def,unknownKeys:"strip"})}passthrough(){return new QT({...this._def,unknownKeys:"passthrough"})}extend(T){return new QT({...this._def,shape:()=>({...this._def.shape(),...T})})}merge(T){return new QT({unknownKeys:T._def.unknownKeys,catchall:T._def.catchall,shape:()=>({...this._def.shape(),...T._def.shape()}),typeName:g.ZodObject})}setKey(T,o){return this.augment({[T]:o})}catchall(T){return new QT({...this._def,catchall:T})}pick(T){let o={};return $T.objectKeys(T).forEach((S)=>{if(T[S]&&this.shape[S])o[S]=this.shape[S]}),new QT({...this._def,shape:()=>o})}omit(T){let o={};return $T.objectKeys(this.shape).forEach((S)=>{if(!T[S])o[S]=this.shape[S]}),new QT({...this._def,shape:()=>o})}deepPartial(){return VS(this)}partial(T){let o={};return $T.objectKeys(this.shape).forEach((S)=>{let f=this.shape[S];if(T&&!T[S])o[S]=f;else o[S]=f.optional()}),new QT({...this._def,shape:()=>o})}required(T){let o={};return $T.objectKeys(this.shape).forEach((S)=>{if(T&&!T[S])o[S]=this.shape[S];else{let n=this.shape[S];while(n instanceof zo)n=n._def.innerType;o[S]=n}}),new QT({...this._def,shape:()=>o})}keyof(){return oJ($T.objectKeys(this.shape))}}QT.create=(T,o)=>{return new QT({shape:()=>T,unknownKeys:"strip",catchall:Co.create(),typeName:g.ZodObject,...u(o)})};QT.strictCreate=(T,o)=>{return new QT({shape:()=>T,unknownKeys:"strict",catchall:Co.create(),typeName:g.ZodObject,...u(o)})};QT.lazycreate=(T,o)=>{return new QT({shape:T,unknownKeys:"strip",catchall:Co.create(),typeName:g.ZodObject,...u(o)})};class NS extends e{_parse(T){let{ctx:o}=this._processInputParams(T),S=this._def.options;function f(n){for(let $ of n)if($.result.status==="valid")return $.result;for(let $ of n)if($.result.status==="dirty")return o.common.issues.push(...$.ctx.common.issues),$.result;let A=n.map(($)=>new Jo($.ctx.common.issues));return C(o,{code:Q.invalid_union,unionErrors:A}),d}if(o.common.async)return Promise.all(S.map(async(n)=>{let A={...o,common:{...o.common,issues:[]},parent:null};return{result:await n._parseAsync({data:o.data,path:o.path,parent:A}),ctx:A}})).then(f);else{let n=void 0,A=[];for(let F of S){let J={...o,common:{...o.common,issues:[]},parent:null},R=F._parseSync({data:o.data,path:o.path,parent:J});if(R.status==="valid")return R;else if(R.status==="dirty"&&!n)n={result:R,ctx:J};if(J.common.issues.length)A.push(J.common.issues)}if(n)return o.common.issues.push(...n.ctx.common.issues),n.result;let $=A.map((F)=>new Jo(F));return C(o,{code:Q.invalid_union,unionErrors:$}),d}}get options(){return this._def.options}}NS.create=(T,o)=>{return new NS({options:T,typeName:g.ZodUnion,...u(o)})};var vo=(T)=>{if(T instanceof bS)return vo(T.schema);else if(T instanceof yo)return vo(T.innerType());else if(T instanceof xS)return[T.value];else if(T instanceof ao)return T.options;else if(T instanceof vS)return $T.objectValues(T.enum);else if(T instanceof qS)return vo(T._def.innerType);else if(T instanceof jS)return[void 0];else if(T instanceof mS)return[null];else if(T instanceof zo)return[void 0,...vo(T.unwrap())];else if(T instanceof Zo)return[null,...vo(T.unwrap())];else if(T instanceof Fn)return vo(T.unwrap());else if(T instanceof cS)return vo(T.unwrap());else if(T instanceof ZS)return vo(T._def.innerType);else return[]};class $n extends e{_parse(T){let{ctx:o}=this._processInputParams(T);if(o.parsedType!==N.object)return C(o,{code:Q.invalid_type,expected:N.object,received:o.parsedType}),d;let S=this.discriminator,f=o.data[S],n=this.optionsMap.get(f);if(!n)return C(o,{code:Q.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[S]}),d;if(o.common.async)return n._parseAsync({data:o.data,path:o.path,parent:o});else return n._parseSync({data:o.data,path:o.path,parent:o})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(T,o,S){let f=new Map;for(let n of o){let A=vo(n.shape[T]);if(!A.length)throw new Error(`A discriminator value for key \`${T}\` could not be extracted from all schema options`);for(let $ of A){if(f.has($))throw new Error(`Discriminator property ${String(T)} has duplicate value ${String($)}`);f.set($,n)}}return new $n({typeName:g.ZodDiscriminatedUnion,discriminator:T,options:o,optionsMap:f,...u(S)})}}function jA(T,o){let S=qo(T),f=qo(o);if(T===o)return{valid:!0,data:T};else if(S===N.object&&f===N.object){let n=$T.objectKeys(o),A=$T.objectKeys(T).filter((F)=>n.indexOf(F)!==-1),$={...T,...o};for(let F of A){let J=jA(T[F],o[F]);if(!J.valid)return{valid:!1};$[F]=J.data}return{valid:!0,data:$}}else if(S===N.array&&f===N.array){if(T.length!==o.length)return{valid:!1};let n=[];for(let A=0;A<T.length;A++){let $=T[A],F=o[A],J=jA($,F);if(!J.valid)return{valid:!1};n.push(J.data)}return{valid:!0,data:n}}else if(S===N.date&&f===N.date&&+T===+o)return{valid:!0,data:T};else return{valid:!1}}class hS extends e{_parse(T){let{status:o,ctx:S}=this._processInputParams(T),f=(n,A)=>{if(CA(n)||CA(A))return d;let $=jA(n.value,A.value);if(!$.valid)return C(S,{code:Q.invalid_intersection_types}),d;if(IA(n)||IA(A))o.dirty();return{status:o.value,value:$.data}};if(S.common.async)return Promise.all([this._def.left._parseAsync({data:S.data,path:S.path,parent:S}),this._def.right._parseAsync({data:S.data,path:S.path,parent:S})]).then(([n,A])=>f(n,A));else return f(this._def.left._parseSync({data:S.data,path:S.path,parent:S}),this._def.right._parseSync({data:S.data,path:S.path,parent:S}))}}hS.create=(T,o,S)=>{return new hS({left:T,right:o,typeName:g.ZodIntersection,...u(S)})};class Io extends e{_parse(T){let{status:o,ctx:S}=this._processInputParams(T);if(S.parsedType!==N.array)return C(S,{code:Q.invalid_type,expected:N.array,received:S.parsedType}),d;if(S.data.length<this._def.items.length)return C(S,{code:Q.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),d;if(!this._def.rest&&S.data.length>this._def.items.length)C(S,{code:Q.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),o.dirty();let n=[...S.data].map((A,$)=>{let F=this._def.items[$]||this._def.rest;if(!F)return null;return F._parse(new Qo(S,A,S.path,$))}).filter((A)=>!!A);if(S.common.async)return Promise.all(n).then((A)=>{return uT.mergeArray(o,A)});else return uT.mergeArray(o,n)}get items(){return this._def.items}rest(T){return new Io({...this._def,rest:T})}}Io.create=(T,o)=>{if(!Array.isArray(T))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Io({items:T,typeName:g.ZodTuple,rest:null,...u(o)})};class _f extends e{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(T){let{status:o,ctx:S}=this._processInputParams(T);if(S.parsedType!==N.object)return C(S,{code:Q.invalid_type,expected:N.object,received:S.parsedType}),d;let f=[],n=this._def.keyType,A=this._def.valueType;for(let $ in S.data)f.push({key:n._parse(new Qo(S,$,S.path,$)),value:A._parse(new Qo(S,S.data[$],S.path,$)),alwaysSet:$ in S.data});if(S.common.async)return uT.mergeObjectAsync(o,f);else return uT.mergeObjectSync(o,f)}get element(){return this._def.valueType}static create(T,o,S){if(o instanceof e)return new _f({keyType:T,valueType:o,typeName:g.ZodRecord,...u(S)});return new _f({keyType:Eo.create(),valueType:T,typeName:g.ZodRecord,...u(o)})}}class wf extends e{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(T){let{status:o,ctx:S}=this._processInputParams(T);if(S.parsedType!==N.map)return C(S,{code:Q.invalid_type,expected:N.map,received:S.parsedType}),d;let f=this._def.keyType,n=this._def.valueType,A=[...S.data.entries()].map(([$,F],J)=>{return{key:f._parse(new Qo(S,$,S.path,[J,"key"])),value:n._parse(new Qo(S,F,S.path,[J,"value"]))}});if(S.common.async){let $=new Map;return Promise.resolve().then(async()=>{for(let F of A){let J=await F.key,R=await F.value;if(J.status==="aborted"||R.status==="aborted")return d;if(J.status==="dirty"||R.status==="dirty")o.dirty();$.set(J.value,R.value)}return{status:o.value,value:$}})}else{let $=new Map;for(let F of A){let{key:J,value:R}=F;if(J.status==="aborted"||R.status==="aborted")return d;if(J.status==="dirty"||R.status==="dirty")o.dirty();$.set(J.value,R.value)}return{status:o.value,value:$}}}}wf.create=(T,o,S)=>{return new wf({valueType:o,keyType:T,typeName:g.ZodMap,...u(S)})};class RS extends e{_parse(T){let{status:o,ctx:S}=this._processInputParams(T);if(S.parsedType!==N.set)return C(S,{code:Q.invalid_type,expected:N.set,received:S.parsedType}),d;let f=this._def;if(f.minSize!==null){if(S.data.size<f.minSize.value)C(S,{code:Q.too_small,minimum:f.minSize.value,type:"set",inclusive:!0,exact:!1,message:f.minSize.message}),o.dirty()}if(f.maxSize!==null){if(S.data.size>f.maxSize.value)C(S,{code:Q.too_big,maximum:f.maxSize.value,type:"set",inclusive:!0,exact:!1,message:f.maxSize.message}),o.dirty()}let n=this._def.valueType;function A(F){let J=new Set;for(let R of F){if(R.status==="aborted")return d;if(R.status==="dirty")o.dirty();J.add(R.value)}return{status:o.value,value:J}}let $=[...S.data.values()].map((F,J)=>n._parse(new Qo(S,F,S.path,J)));if(S.common.async)return Promise.all($).then((F)=>A(F));else return A($)}min(T,o){return new RS({...this._def,minSize:{value:T,message:x.toString(o)}})}max(T,o){return new RS({...this._def,maxSize:{value:T,message:x.toString(o)}})}size(T,o){return this.min(T,o).max(T,o)}nonempty(T){return this.min(1,T)}}RS.create=(T,o)=>{return new RS({valueType:T,minSize:null,maxSize:null,typeName:g.ZodSet,...u(o)})};class LS extends e{constructor(){super(...arguments);this.validate=this.implement}_parse(T){let{ctx:o}=this._processInputParams(T);if(o.parsedType!==N.function)return C(o,{code:Q.invalid_type,expected:N.function,received:o.parsedType}),d;function S($,F){return nn({data:$,path:o.path,errorMaps:[o.common.contextualErrorMap,o.schemaErrorMap,fn(),CS].filter((J)=>!!J),issueData:{code:Q.invalid_arguments,argumentsError:F}})}function f($,F){return nn({data:$,path:o.path,errorMaps:[o.common.contextualErrorMap,o.schemaErrorMap,fn(),CS].filter((J)=>!!J),issueData:{code:Q.invalid_return_type,returnTypeError:F}})}let n={errorMap:o.common.contextualErrorMap},A=o.data;if(this._def.returns instanceof WS){let $=this;return sT(async function(...F){let J=new Jo([]),R=await $._def.args.parseAsync(F,n).catch((_)=>{throw J.addIssue(S(F,_)),J}),W=await Reflect.apply(A,this,R);return await $._def.returns._def.type.parseAsync(W,n).catch((_)=>{throw J.addIssue(f(W,_)),J})})}else{let $=this;return sT(function(...F){let J=$._def.args.safeParse(F,n);if(!J.success)throw new Jo([S(F,J.error)]);let R=Reflect.apply(A,this,J.data),W=$._def.returns.safeParse(R,n);if(!W.success)throw new Jo([f(R,W.error)]);return W.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...T){return new LS({...this._def,args:Io.create(T).rest(lo.create())})}returns(T){return new LS({...this._def,returns:T})}implement(T){return this.parse(T)}strictImplement(T){return this.parse(T)}static create(T,o,S){return new LS({args:T?T:Io.create([]).rest(lo.create()),returns:o||lo.create(),typeName:g.ZodFunction,...u(S)})}}class bS extends e{get schema(){return this._def.getter()}_parse(T){let{ctx:o}=this._processInputParams(T);return this._def.getter()._parse({data:o.data,path:o.path,parent:o})}}bS.create=(T,o)=>{return new bS({getter:T,typeName:g.ZodLazy,...u(o)})};class xS extends e{_parse(T){if(T.data!==this._def.value){let o=this._getOrReturnCtx(T);return C(o,{received:o.data,code:Q.invalid_literal,expected:this._def.value}),d}return{status:"valid",value:T.data}}get value(){return this._def.value}}xS.create=(T,o)=>{return new xS({value:T,typeName:g.ZodLiteral,...u(o)})};function oJ(T,o){return new ao({values:T,typeName:g.ZodEnum,...u(o)})}class ao extends e{constructor(){super(...arguments);Wf.set(this,void 0)}_parse(T){if(typeof T.data!=="string"){let o=this._getOrReturnCtx(T),S=this._def.values;return C(o,{expected:$T.joinValues(S),received:o.parsedType,code:Q.invalid_type}),d}if(!An(this,Wf,"f"))eF(this,Wf,new Set(this._def.values),"f");if(!An(this,Wf,"f").has(T.data)){let o=this._getOrReturnCtx(T),S=this._def.values;return C(o,{received:o.data,code:Q.invalid_enum_value,options:S}),d}return sT(T.data)}get options(){return this._def.values}get enum(){let T={};for(let o of this._def.values)T[o]=o;return T}get Values(){let T={};for(let o of this._def.values)T[o]=o;return T}get Enum(){let T={};for(let o of this._def.values)T[o]=o;return T}extract(T,o=this._def){return ao.create(T,{...this._def,...o})}exclude(T,o=this._def){return ao.create(this.options.filter((S)=>!T.includes(S)),{...this._def,...o})}}Wf=new WeakMap;ao.create=oJ;class vS extends e{constructor(){super(...arguments);Of.set(this,void 0)}_parse(T){let o=$T.getValidEnumValues(this._def.values),S=this._getOrReturnCtx(T);if(S.parsedType!==N.string&&S.parsedType!==N.number){let f=$T.objectValues(o);return C(S,{expected:$T.joinValues(f),received:S.parsedType,code:Q.invalid_type}),d}if(!An(this,Of,"f"))eF(this,Of,new Set($T.getValidEnumValues(this._def.values)),"f");if(!An(this,Of,"f").has(T.data)){let f=$T.objectValues(o);return C(S,{received:S.data,code:Q.invalid_enum_value,options:f}),d}return sT(T.data)}get enum(){return this._def.values}}Of=new WeakMap;vS.create=(T,o)=>{return new vS({values:T,typeName:g.ZodNativeEnum,...u(o)})};class WS extends e{unwrap(){return this._def.type}_parse(T){let{ctx:o}=this._processInputParams(T);if(o.parsedType!==N.promise&&o.common.async===!1)return C(o,{code:Q.invalid_type,expected:N.promise,received:o.parsedType}),d;let S=o.parsedType===N.promise?o.data:Promise.resolve(o.data);return sT(S.then((f)=>{return this._def.type.parseAsync(f,{path:o.path,errorMap:o.common.contextualErrorMap})}))}}WS.create=(T,o)=>{return new WS({type:T,typeName:g.ZodPromise,...u(o)})};class yo extends e{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===g.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(T){let{status:o,ctx:S}=this._processInputParams(T),f=this._def.effect||null,n={addIssue:(A)=>{if(C(S,A),A.fatal)o.abort();else o.dirty()},get path(){return S.path}};if(n.addIssue=n.addIssue.bind(n),f.type==="preprocess"){let A=f.transform(S.data,n);if(S.common.async)return Promise.resolve(A).then(async($)=>{if(o.value==="aborted")return d;let F=await this._def.schema._parseAsync({data:$,path:S.path,parent:S});if(F.status==="aborted")return d;if(F.status==="dirty")return BS(F.value);if(o.value==="dirty")return BS(F.value);return F});else{if(o.value==="aborted")return d;let $=this._def.schema._parseSync({data:A,path:S.path,parent:S});if($.status==="aborted")return d;if($.status==="dirty")return BS($.value);if(o.value==="dirty")return BS($.value);return $}}if(f.type==="refinement"){let A=($)=>{let F=f.refinement($,n);if(S.common.async)return Promise.resolve(F);if(F instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return $};if(S.common.async===!1){let $=this._def.schema._parseSync({data:S.data,path:S.path,parent:S});if($.status==="aborted")return d;if($.status==="dirty")o.dirty();return A($.value),{status:o.value,value:$.value}}else return this._def.schema._parseAsync({data:S.data,path:S.path,parent:S}).then(($)=>{if($.status==="aborted")return d;if($.status==="dirty")o.dirty();return A($.value).then(()=>{return{status:o.value,value:$.value}})})}if(f.type==="transform")if(S.common.async===!1){let A=this._def.schema._parseSync({data:S.data,path:S.path,parent:S});if(!$S(A))return A;let $=f.transform(A.value,n);if($ instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:o.value,value:$}}else return this._def.schema._parseAsync({data:S.data,path:S.path,parent:S}).then((A)=>{if(!$S(A))return A;return Promise.resolve(f.transform(A.value,n)).then(($)=>({status:o.value,value:$}))});$T.assertNever(f)}}yo.create=(T,o,S)=>{return new yo({schema:T,typeName:g.ZodEffects,effect:o,...u(S)})};yo.createWithPreprocess=(T,o,S)=>{return new yo({schema:o,effect:{type:"preprocess",transform:T},typeName:g.ZodEffects,...u(S)})};class zo extends e{_parse(T){if(this._getType(T)===N.undefined)return sT(void 0);return this._def.innerType._parse(T)}unwrap(){return this._def.innerType}}zo.create=(T,o)=>{return new zo({innerType:T,typeName:g.ZodOptional,...u(o)})};class Zo extends e{_parse(T){if(this._getType(T)===N.null)return sT(null);return this._def.innerType._parse(T)}unwrap(){return this._def.innerType}}Zo.create=(T,o)=>{return new Zo({innerType:T,typeName:g.ZodNullable,...u(o)})};class qS extends e{_parse(T){let{ctx:o}=this._processInputParams(T),S=o.data;if(o.parsedType===N.undefined)S=this._def.defaultValue();return this._def.innerType._parse({data:S,path:o.path,parent:o})}removeDefault(){return this._def.innerType}}qS.create=(T,o)=>{return new qS({innerType:T,typeName:g.ZodDefault,defaultValue:typeof o.default==="function"?o.default:()=>o.default,...u(o)})};class ZS extends e{_parse(T){let{ctx:o}=this._processInputParams(T),S={...o,common:{...o.common,issues:[]}},f=this._def.innerType._parse({data:S.data,path:S.path,parent:{...S}});if(Mf(f))return f.then((n)=>{return{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new Jo(S.common.issues)},input:S.data})}});else return{status:"valid",value:f.status==="valid"?f.value:this._def.catchValue({get error(){return new Jo(S.common.issues)},input:S.data})}}removeCatch(){return this._def.innerType}}ZS.create=(T,o)=>{return new ZS({innerType:T,typeName:g.ZodCatch,catchValue:typeof o.catch==="function"?o.catch:()=>o.catch,...u(o)})};class Xf extends e{_parse(T){if(this._getType(T)!==N.nan){let S=this._getOrReturnCtx(T);return C(S,{code:Q.invalid_type,expected:N.nan,received:S.parsedType}),d}return{status:"valid",value:T.data}}}Xf.create=(T)=>{return new Xf({typeName:g.ZodNaN,...u(T)})};var kO=Symbol("zod_brand");class Fn extends e{_parse(T){let{ctx:o}=this._processInputParams(T),S=o.data;return this._def.type._parse({data:S,path:o.path,parent:o})}unwrap(){return this._def.type}}class Kf extends e{_parse(T){let{status:o,ctx:S}=this._processInputParams(T);if(S.common.async)return(async()=>{let n=await this._def.in._parseAsync({data:S.data,path:S.path,parent:S});if(n.status==="aborted")return d;if(n.status==="dirty")return o.dirty(),BS(n.value);else return this._def.out._parseAsync({data:n.value,path:S.path,parent:S})})();else{let f=this._def.in._parseSync({data:S.data,path:S.path,parent:S});if(f.status==="aborted")return d;if(f.status==="dirty")return o.dirty(),{status:"dirty",value:f.value};else return this._def.out._parseSync({data:f.value,path:S.path,parent:S})}}static create(T,o){return new Kf({in:T,out:o,typeName:g.ZodPipeline})}}class cS extends e{_parse(T){let o=this._def.innerType._parse(T),S=(f)=>{if($S(f))f.value=Object.freeze(f.value);return f};return Mf(o)?o.then((f)=>S(f)):S(o)}unwrap(){return this._def.innerType}}cS.create=(T,o)=>{return new cS({innerType:T,typeName:g.ZodReadonly,...u(o)})};function dF(T,o){let S=typeof T==="function"?T(o):typeof T==="string"?{message:T}:T;return typeof S==="string"?{message:S}:S}function SJ(T,o={},S){if(T)return JS.create().superRefine((f,n)=>{var A,$;let F=T(f);if(F instanceof Promise)return F.then((J)=>{var R,W;if(!J){let y=dF(o,f),_=(W=(R=y.fatal)!==null&&R!==void 0?R:S)!==null&&W!==void 0?W:!0;n.addIssue({code:"custom",...y,fatal:_})}});if(!F){let J=dF(o,f),R=($=(A=J.fatal)!==null&&A!==void 0?A:S)!==null&&$!==void 0?$:!0;n.addIssue({code:"custom",...J,fatal:R})}return});return JS.create()}var yO={object:QT.lazycreate},g;(function(T){T.ZodString="ZodString",T.ZodNumber="ZodNumber",T.ZodNaN="ZodNaN",T.ZodBigInt="ZodBigInt",T.ZodBoolean="ZodBoolean",T.ZodDate="ZodDate",T.ZodSymbol="ZodSymbol",T.ZodUndefined="ZodUndefined",T.ZodNull="ZodNull",T.ZodAny="ZodAny",T.ZodUnknown="ZodUnknown",T.ZodNever="ZodNever",T.ZodVoid="ZodVoid",T.ZodArray="ZodArray",T.ZodObject="ZodObject",T.ZodUnion="ZodUnion",T.ZodDiscriminatedUnion="ZodDiscriminatedUnion",T.ZodIntersection="ZodIntersection",T.ZodTuple="ZodTuple",T.ZodRecord="ZodRecord",T.ZodMap="ZodMap",T.ZodSet="ZodSet",T.ZodFunction="ZodFunction",T.ZodLazy="ZodLazy",T.ZodLiteral="ZodLiteral",T.ZodEnum="ZodEnum",T.ZodEffects="ZodEffects",T.ZodNativeEnum="ZodNativeEnum",T.ZodOptional="ZodOptional",T.ZodNullable="ZodNullable",T.ZodDefault="ZodDefault",T.ZodCatch="ZodCatch",T.ZodPromise="ZodPromise",T.ZodBranded="ZodBranded",T.ZodPipeline="ZodPipeline",T.ZodReadonly="ZodReadonly"})(g||(g={}));var _O=(T,o={message:`Input not instance of ${T.name}`})=>SJ((S)=>S instanceof T,o),fJ=Eo.create,nJ=uo.create,wO=Xf.create,XO=eo.create,AJ=IS.create,KO=FS.create,GO=kf.create,YO=jS.create,EO=mS.create,HO=JS.create,zO=lo.create,QO=Co.create,DO=yf.create,UO=Ho.create,tO=QT.create,VO=QT.strictCreate,BO=NS.create,LO=$n.create,CO=hS.create,IO=Io.create,jO=_f.create,mO=wf.create,NO=RS.create,hO=LS.create,bO=bS.create,xO=xS.create,vO=ao.create,qO=vS.create,ZO=WS.create,lF=yo.create,cO=zo.create,rO=Zo.create,PO=yo.createWithPreprocess,pO=Kf.create,iO=()=>fJ().optional(),gO=()=>nJ().optional(),dO=()=>AJ().optional(),lO={string:(T)=>Eo.create({...T,coerce:!0}),number:(T)=>uo.create({...T,coerce:!0}),boolean:(T)=>IS.create({...T,coerce:!0}),bigint:(T)=>eo.create({...T,coerce:!0}),date:(T)=>FS.create({...T,coerce:!0})},uO=d,YT=Object.freeze({__proto__:null,defaultErrorMap:CS,setErrorMap:PW,getErrorMap:fn,makeIssue:nn,EMPTY_PATH:pW,addIssueToContext:C,ParseStatus:uT,INVALID:d,DIRTY:BS,OK:sT,isAborted:CA,isDirty:IA,isValid:$S,isAsync:Mf,get util(){return $T},get objectUtil(){return LA},ZodParsedType:N,getParsedType:qo,ZodType:e,datetimeRegex:TJ,ZodString:Eo,ZodNumber:uo,ZodBigInt:eo,ZodBoolean:IS,ZodDate:FS,ZodSymbol:kf,ZodUndefined:jS,ZodNull:mS,ZodAny:JS,ZodUnknown:lo,ZodNever:Co,ZodVoid:yf,ZodArray:Ho,ZodObject:QT,ZodUnion:NS,ZodDiscriminatedUnion:$n,ZodIntersection:hS,ZodTuple:Io,ZodRecord:_f,ZodMap:wf,ZodSet:RS,ZodFunction:LS,ZodLazy:bS,ZodLiteral:xS,ZodEnum:ao,ZodNativeEnum:vS,ZodPromise:WS,ZodEffects:yo,ZodTransformer:yo,ZodOptional:zo,ZodNullable:Zo,ZodDefault:qS,ZodCatch:ZS,ZodNaN:Xf,BRAND:kO,ZodBranded:Fn,ZodPipeline:Kf,ZodReadonly:cS,custom:SJ,Schema:e,ZodSchema:e,late:yO,get ZodFirstPartyTypeKind(){return g},coerce:lO,any:HO,array:UO,bigint:XO,boolean:AJ,date:KO,discriminatedUnion:LO,effect:lF,enum:vO,function:hO,instanceof:_O,intersection:CO,lazy:bO,literal:xO,map:mO,nan:wO,nativeEnum:qO,never:QO,null:EO,nullable:rO,number:nJ,object:tO,oboolean:dO,onumber:gO,optional:cO,ostring:iO,pipeline:pO,preprocess:PO,promise:ZO,record:jO,set:NO,strictObject:VO,string:fJ,symbol:GO,transformer:lF,tuple:IO,undefined:YO,union:BO,unknown:zO,void:DO,NEVER:uO,ZodIssueCode:Q,quotelessJson:rW,ZodError:Jo});var eO="__vite_start_time"in globalThis,aO=typeof window!=="undefined",iG="vitest"in globalThis,Do=iF({isServer:!eO&&!aO,server:{CI:YT.string().transform((T)=>!0).optional(),POSTGRES_USER:YT.string(),POSTGRES_PASSWORD:YT.string(),POSTGRES_DATABASE:YT.string(),POSTGRES_HOST:YT.string(),POSTGRES_PORT:YT.string().transform((T)=>Number.parseInt(T,10)),BACKEND_PORT:YT.string().transform((T)=>Number.parseInt(T,10)),RUN_WORKERS_FROM_SOURCE:YT.union([YT.literal("true"),YT.literal("false")]).optional().transform((T)=>T==="true"),FRONTEND_PORT:YT.string().transform((T)=>Number.parseInt(T,10)),FRONTEND_ORIGINS:YT.string().transform((T)=>JSON.parse(T)).pipe(YT.array(YT.string())),OPENAI_API_KEY:YT.string().optional()},clientPrefix:"VITE_",client:{VITE_BACKEND_ORIGIN:YT.string(),VITE_USE_SELF_SIGNED_CERTIFICATE:YT.union([YT.literal("true"),YT.literal("false")]).optional().transform((T)=>T==="true")},runtimeEnv:import.meta.env,emptyStringAsUndefined:!0});var FJ=mA(import.meta.dirname,"../dev"),JJ=Do.VITE_USE_SELF_SIGNED_CERTIFICATE?{cert:$J(mA(FJ,"./cert.pem"),"utf-8"),key:$J(mA(FJ,"./key.pem"),"utf-8")}:void 0;import Tk from"path";var M=Symbol.for("drizzle:entityKind"),aG=Symbol.for("drizzle:hasOwnEntityKind");function X(T,o){if(!T||typeof T!=="object")return!1;if(T instanceof o)return!0;if(!Object.prototype.hasOwnProperty.call(o,M))throw new Error(`Class "${o.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let S=Object.getPrototypeOf(T).constructor;if(S)while(S){if(M in S&&S[M]===o[M])return!0;S=Object.getPrototypeOf(S)}return!1}class kT{constructor(T,o){this.table=T,this.config=o,this.name=o.name,this.keyAsName=o.keyAsName,this.notNull=o.notNull,this.default=o.default,this.defaultFn=o.defaultFn,this.onUpdateFn=o.onUpdateFn,this.hasDefault=o.hasDefault,this.primary=o.primaryKey,this.isUnique=o.isUnique,this.uniqueName=o.uniqueName,this.uniqueType=o.uniqueType,this.dataType=o.dataType,this.columnType=o.columnType,this.generated=o.generated,this.generatedIdentity=o.generatedIdentity}static[M]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue(T){return T}mapToDriverValue(T){return T}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}class NA{static[M]="ColumnBuilder";config;constructor(T,o,S){this.config={name:T,keyAsName:T==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:o,columnType:S,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(T){return this.config.default=T,this.config.hasDefault=!0,this}$defaultFn(T){return this.config.defaultFn=T,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(T){return this.config.onUpdateFn=T,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(T){if(this.config.name!=="")return;this.config.name=T}}var Uo=Symbol.for("drizzle:Name");class hA{static[M]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(T,o){if(this.reference=()=>{let{name:S,columns:f,foreignColumns:n}=T();return{name:S,columns:f,foreignTable:n[0].table,foreignColumns:n}},o)this._onUpdate=o.onUpdate,this._onDelete=o.onDelete}onUpdate(T){return this._onUpdate=T===void 0?"no action":T,this}onDelete(T){return this._onDelete=T===void 0?"no action":T,this}build(T){return new RJ(T,this)}}class RJ{constructor(T,o){this.table=T,this.reference=o.reference,this.onUpdate=o._onUpdate,this.onDelete=o._onDelete}static[M]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:T,columns:o,foreignColumns:S}=this.reference(),f=o.map(($)=>$.name),n=S.map(($)=>$.name),A=[this.table[Uo],...f,S[0].table[Uo],...n];return T??`${A.join("_")}_fk`}}function Jn(T,...o){return T(...o)}function WJ(T,o){return`${T[Uo]}_${o.join("_")}_unique`}function OJ(T,o,S){for(let f=o;f<T.length;f++){let n=T[f];if(n==="\\"){f++;continue}if(n==='"')return[T.slice(o,f).replace(/\\/g,""),f+1];if(S)continue;if(n===","||n==="}")return[T.slice(o,f).replace(/\\/g,""),f]}return[T.slice(o).replace(/\\/g,""),T.length]}function MJ(T,o=0){let S=[],f=o,n=!1;while(f<T.length){let A=T[f];if(A===","){if(n||f===o)S.push("");n=!0,f++;continue}if(n=!1,A==="\\"){f+=2;continue}if(A==='"'){let[J,R]=OJ(T,f+1,!0);S.push(J),f=R;continue}if(A==="}")return[S,f+1];if(A==="{"){let[J,R]=MJ(T,f+1);S.push(J),f=R;continue}let[$,F]=OJ(T,f,!1);S.push($),f=F}return[S,f]}function kJ(T){let[o]=MJ(T,1);return o}function bA(T){return`{${T.map((o)=>{if(Array.isArray(o))return bA(o);if(typeof o==="string")return`"${o.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${o}`}).join(",")}}`}class h extends NA{foreignKeyConfigs=[];static[M]="PgColumnBuilder";array(T){return new _J(this.config.name,this,T)}references(T,o={}){return this.foreignKeyConfigs.push({ref:T,actions:o}),this}unique(T,o){return this.config.isUnique=!0,this.config.uniqueName=T,this.config.uniqueType=o?.nulls,this}generatedAlwaysAs(T){return this.config.generated={as:T,type:"always",mode:"stored"},this}buildForeignKeys(T,o){return this.foreignKeyConfigs.map(({ref:S,actions:f})=>{return Jn((n,A)=>{let $=new hA(()=>{let F=n();return{columns:[T],foreignColumns:[F]}});if(A.onUpdate)$.onUpdate(A.onUpdate);if(A.onDelete)$.onDelete(A.onDelete);return $.build(o)},S,f)})}buildExtraConfigColumn(T){return new yJ(T,this.config)}}class V extends kT{constructor(T,o){if(!o.uniqueName)o.uniqueName=WJ(T,[o.name]);super(T,o);this.table=T}static[M]="PgColumn"}class yJ extends V{static[M]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op(T){return this.indexConfig.opClass=T,this}}class Gf{static[M]="IndexedColumn";constructor(T,o,S,f){this.name=T,this.keyAsName=o,this.type=S,this.indexConfig=f}name;keyAsName;type;indexConfig}class _J extends h{static[M]="PgArrayBuilder";constructor(T,o,S){super(T,"array","PgArray");this.config.baseBuilder=o,this.config.size=S}build(T){let o=this.config.baseBuilder.build(T);return new xA(T,this.config,o)}}class xA extends V{constructor(T,o,S,f){super(T,o);this.baseColumn=S,this.range=f,this.size=o.size}size;static[M]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(T){if(typeof T==="string")T=kJ(T);return T.map((o)=>this.baseColumn.mapFromDriverValue(o))}mapToDriverValue(T,o=!1){let S=T.map((f)=>f===null?null:X(this.baseColumn,xA)?this.baseColumn.mapToDriverValue(f,!0):this.baseColumn.mapToDriverValue(f));if(o)return S;return bA(S)}}var vA=Symbol.for("drizzle:isPgEnum");function wJ(T){return!!T&&typeof T==="function"&&vA in T&&T[vA]===!0}class XJ extends h{static[M]="PgEnumColumnBuilder";constructor(T,o){super(T,"string","PgEnumColumn");this.config.enum=o}build(T){return new KJ(T,this.config)}}class KJ extends V{static[M]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(T,o){super(T,o);this.enum=o.enum}getSQLType(){return this.enum.enumName}}function Rn(T,o){return sO(T,o,void 0)}function sO(T,o,S){let f=Object.assign((n)=>new XJ(n??"",f),{enumName:T,enumValues:o,schema:S,[vA]:!0});return f}class xT{static[M]="Subquery";constructor(T,o,S,f=!1){this._={brand:"Subquery",sql:T,selectedFields:o,alias:S,isWith:f}}}class Yf extends xT{static[M]="WithSubquery"}var GJ="0.39.3";var qA,ZA,yT={startActiveSpan(T,o){if(!qA)return o();if(!ZA)ZA=qA.trace.getTracer("drizzle-orm",GJ);return Jn((S,f)=>f.startActiveSpan(T,(n)=>{try{return o(n)}catch(A){throw n.setStatus({code:S.SpanStatusCode.ERROR,message:A instanceof Error?A.message:"Unknown error"}),A}finally{n.end()}}),qA,ZA)}};var XT=Symbol.for("drizzle:ViewBaseConfig");var Wn=Symbol.for("drizzle:Schema"),On=Symbol.for("drizzle:Columns"),YJ=Symbol.for("drizzle:ExtraConfigColumns"),cA=Symbol.for("drizzle:OriginalName"),rA=Symbol.for("drizzle:BaseName"),Ef=Symbol.for("drizzle:IsAlias"),EJ=Symbol.for("drizzle:ExtraConfigBuilder"),TM=Symbol.for("drizzle:IsDrizzleTable");class j{static[M]="Table";static Symbol={Name:Uo,Schema:Wn,OriginalName:cA,Columns:On,ExtraConfigColumns:YJ,BaseName:rA,IsAlias:Ef,ExtraConfigBuilder:EJ};[Uo];[cA];[Wn];[On];[YJ];[rA];[Ef]=!1;[TM]=!0;[EJ]=void 0;constructor(T,o,S){this[Uo]=this[cA]=T,this[Wn]=o,this[rA]=S}}function ZT(T){return T[Uo]}function OS(T){return`${T[Wn]??"public"}.${T[Uo]}`}function PA(T){return T!==null&&T!==void 0&&typeof T.getSQL==="function"}function oM(T){let o={sql:"",params:[]};for(let S of T)if(o.sql+=S.sql,o.params.push(...S.params),S.typings?.length){if(!o.typings)o.typings=[];o.typings.push(...S.typings)}return o}class vT{static[M]="StringChunk";value;constructor(T){this.value=Array.isArray(T)?T:[T]}getSQL(){return new m([this])}}class m{constructor(T){this.queryChunks=T}static[M]="SQL";decoder=zJ;shouldInlineParams=!1;append(T){return this.queryChunks.push(...T.queryChunks),this}toQuery(T){return yT.startActiveSpan("drizzle.buildSQL",(o)=>{let S=this.buildQueryFromSourceParams(this.queryChunks,T);return o?.setAttributes({"drizzle.query.text":S.sql,"drizzle.query.params":JSON.stringify(S.params)}),S})}buildQueryFromSourceParams(T,o){let S=Object.assign({},o,{inlineParams:o.inlineParams||this.shouldInlineParams,paramStartIndex:o.paramStartIndex||{value:0}}),{casing:f,escapeName:n,escapeParam:A,prepareTyping:$,inlineParams:F,paramStartIndex:J}=S;return oM(T.map((R)=>{if(X(R,vT))return{sql:R.value.join(""),params:[]};if(X(R,Mn))return{sql:n(R.value),params:[]};if(R===void 0)return{sql:"",params:[]};if(Array.isArray(R)){let W=[new vT("(")];for(let[y,_]of R.entries())if(W.push(_),y<R.length-1)W.push(new vT(", "));return W.push(new vT(")")),this.buildQueryFromSourceParams(W,S)}if(X(R,m))return this.buildQueryFromSourceParams(R.queryChunks,{...S,inlineParams:F||R.shouldInlineParams});if(X(R,j)){let W=R[j.Symbol.Schema],y=R[j.Symbol.Name];return{sql:W===void 0||R[Ef]?n(y):n(W)+"."+n(y),params:[]}}if(X(R,kT)){let W=f.getColumnCasing(R);if(o.invokeSource==="indexes")return{sql:n(W),params:[]};let y=R.table[j.Symbol.Schema];return{sql:R.table[Ef]||y===void 0?n(R.table[j.Symbol.Name])+"."+n(W):n(y)+"."+n(R.table[j.Symbol.Name])+"."+n(W),params:[]}}if(X(R,Ao)){let W=R[XT].schema,y=R[XT].name;return{sql:W===void 0||R[XT].isAlias?n(y):n(W)+"."+n(y),params:[]}}if(X(R,Ro)){if(X(R.value,so))return{sql:A(J.value++,R),params:[R],typings:["none"]};let W=R.value===null?null:R.encoder.mapToDriverValue(R.value);if(X(W,m))return this.buildQueryFromSourceParams([W],S);if(F)return{sql:this.mapInlineParam(W,S),params:[]};let y=["none"];if($)y=[$(R.encoder)];return{sql:A(J.value++,W),params:[W],typings:y}}if(X(R,so))return{sql:A(J.value++,R),params:[R],typings:["none"]};if(X(R,m.Aliased)&&R.fieldAlias!==void 0)return{sql:n(R.fieldAlias),params:[]};if(X(R,xT)){if(R._.isWith)return{sql:n(R._.alias),params:[]};return this.buildQueryFromSourceParams([new vT("("),R._.sql,new vT(") "),new Mn(R._.alias)],S)}if(wJ(R)){if(R.schema)return{sql:n(R.schema)+"."+n(R.enumName),params:[]};return{sql:n(R.enumName),params:[]}}if(PA(R)){if(R.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([R.getSQL()],S);return this.buildQueryFromSourceParams([new vT("("),R.getSQL(),new vT(")")],S)}if(F)return{sql:this.mapInlineParam(R,S),params:[]};return{sql:A(J.value++,R),params:[R],typings:["none"]}}))}mapInlineParam(T,{escapeString:o}){if(T===null)return"null";if(typeof T==="number"||typeof T==="boolean")return T.toString();if(typeof T==="string")return o(T);if(typeof T==="object"){let S=T.toString();if(S==="[object Object]")return o(JSON.stringify(T));return o(S)}throw new Error("Unexpected param value: "+T)}getSQL(){return this}as(T){if(T===void 0)return this;return new m.Aliased(this,T)}mapWith(T){return this.decoder=typeof T==="function"?{mapFromDriverValue:T}:T,this}inlineParams(){return this.shouldInlineParams=!0,this}if(T){return T?this:void 0}}class Mn{constructor(T){this.value=T}static[M]="Name";brand;getSQL(){return new m([this])}}function HJ(T){return typeof T==="object"&&T!==null&&"mapToDriverValue"in T&&typeof T.mapToDriverValue==="function"}var zJ={mapFromDriverValue:(T)=>T},QJ={mapToDriverValue:(T)=>T},q6={...zJ,...QJ};class Ro{constructor(T,o=QJ){this.value=T,this.encoder=o}static[M]="Param";brand;getSQL(){return new m([this])}}function k(T,...o){let S=[];if(o.length>0||T.length>0&&T[0]!=="")S.push(new vT(T[0]));for(let[f,n]of o.entries())S.push(n,new vT(T[f+1]));return new m(S)}((T)=>{function o(){return new m([])}T.empty=o;function S(J){return new m(J)}T.fromList=S;function f(J){return new m([new vT(J)])}T.raw=f;function n(J,R){let W=[];for(let[y,_]of J.entries()){if(y>0&&R!==void 0)W.push(R);W.push(_)}return new m(W)}T.join=n;function A(J){return new Mn(J)}T.identifier=A;function $(J){return new so(J)}T.placeholder=$;function F(J,R){return new Ro(J,R)}T.param=F})(k||(k={}));((T)=>{class o{constructor(S,f){this.sql=S,this.fieldAlias=f}static[M]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new o(this.sql,this.fieldAlias)}}T.Aliased=o})(m||(m={}));class so{constructor(T){this.name=T}static[M]="Placeholder";getSQL(){return new m([this])}}function pA(T,o){return T.map((S)=>{if(X(S,so)){if(!(S.name in o))throw new Error(`No value for placeholder "${S.name}" was provided`);return o[S.name]}if(X(S,Ro)&&X(S.value,so)){if(!(S.value.name in o))throw new Error(`No value for placeholder "${S.value.name}" was provided`);return S.encoder.mapToDriverValue(o[S.value.name])}return S})}var SM=Symbol.for("drizzle:IsDrizzleView");class Ao{static[M]="View";[XT];[SM]=!0;constructor({name:T,schema:o,selectedFields:S,query:f}){this[XT]={name:T,originalName:T,schema:o,selectedFields:S,query:f,isExisting:!f,isAlias:!1}}getSQL(){return new m([this])}}kT.prototype.getSQL=function(){return new m([this])};j.prototype.getSQL=function(){return new m([this])};xT.prototype.getSQL=function(){return new m([this])};class rS{constructor(T){this.table=T}static[M]="ColumnAliasProxyHandler";get(T,o){if(o==="table")return this.table;return T[o]}}class Hf{constructor(T,o){this.alias=T,this.replaceOriginalName=o}static[M]="TableAliasProxyHandler";get(T,o){if(o===j.Symbol.IsAlias)return!0;if(o===j.Symbol.Name)return this.alias;if(this.replaceOriginalName&&o===j.Symbol.OriginalName)return this.alias;if(o===XT)return{...T[XT],name:this.alias,isAlias:!0};if(o===j.Symbol.Columns){let f=T[j.Symbol.Columns];if(!f)return f;let n={};return Object.keys(f).map((A)=>{n[A]=new Proxy(f[A],new rS(new Proxy(T,this)))}),n}let S=T[o];if(X(S,kT))return new Proxy(S,new rS(new Proxy(T,this)));return S}}function kn(T,o){return new Proxy(T,new Hf(o,!1))}function jo(T,o){return new Proxy(T,new rS(new Proxy(T.table,new Hf(o,!1))))}function iA(T,o){return new m.Aliased(zf(T.sql,o),T.fieldAlias)}function zf(T,o){return k.join(T.queryChunks.map((S)=>{if(X(S,kT))return jo(S,o);if(X(S,m))return zf(S,o);if(X(S,m.Aliased))return iA(S,o);return S}))}class yn extends Error{static[M]="DrizzleError";constructor({message:T,cause:o}){super(T);this.name="DrizzleError",this.cause=o}}class gA extends yn{static[M]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}function $o(T,o){if(HJ(o)&&!PA(T)&&!X(T,Ro)&&!X(T,so)&&!X(T,kT)&&!X(T,j)&&!X(T,Ao))return new Ro(T,o);return T}var _n=(T,o)=>{return k`${T} = ${$o(o,T)}`},DJ=(T,o)=>{return k`${T} <> ${$o(o,T)}`};function Qf(...T){let o=T.filter((S)=>S!==void 0);if(o.length===0)return;if(o.length===1)return new m(o);return new m([new vT("("),k.join(o,new vT(" and ")),new vT(")")])}function UJ(...T){let o=T.filter((S)=>S!==void 0);if(o.length===0)return;if(o.length===1)return new m(o);return new m([new vT("("),k.join(o,new vT(" or ")),new vT(")")])}function tJ(T){return k`not ${T}`}var VJ=(T,o)=>{return k`${T} > ${$o(o,T)}`},BJ=(T,o)=>{return k`${T} >= ${$o(o,T)}`},LJ=(T,o)=>{return k`${T} < ${$o(o,T)}`},CJ=(T,o)=>{return k`${T} <= ${$o(o,T)}`};function IJ(T,o){if(Array.isArray(o)){if(o.length===0)return k`false`;return k`${T} in ${o.map((S)=>$o(S,T))}`}return k`${T} in ${$o(o,T)}`}function jJ(T,o){if(Array.isArray(o)){if(o.length===0)return k`true`;return k`${T} not in ${o.map((S)=>$o(S,T))}`}return k`${T} not in ${$o(o,T)}`}function mJ(T){return k`${T} is null`}function NJ(T){return k`${T} is not null`}function hJ(T){return k`exists ${T}`}function bJ(T){return k`not exists ${T}`}function xJ(T,o,S){return k`${T} between ${$o(o,T)} and ${$o(S,T)}`}function vJ(T,o,S){return k`${T} not between ${$o(o,T)} and ${$o(S,T)}`}function qJ(T,o){return k`${T} like ${o}`}function ZJ(T,o){return k`${T} not like ${o}`}function cJ(T,o){return k`${T} ilike ${o}`}function rJ(T,o){return k`${T} not ilike ${o}`}function PJ(T){return k`${T} asc`}function pJ(T){return k`${T} desc`}class iJ{static[M]="ConsoleLogWriter";write(T){console.log(T)}}class dA{static[M]="DefaultLogger";writer;constructor(T){this.writer=T?.writer??new iJ}logQuery(T,o){let S=o.map((n)=>{try{return JSON.stringify(n)}catch{return String(n)}}),f=S.length?` -- params: [${S.join(", ")}]`:"";this.writer.write(`Query: ${T}${f}`)}}class lA{static[M]="NoopLogger";logQuery(){}}class To{static[M]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(T){return this.then(void 0,T)}finally(T){return this.then((o)=>{return T?.(),o},(o)=>{throw T?.(),o})}then(T,o){return this.execute().then(T,o)}}function gJ(T,o,S){let f={},n=T.reduce((A,{path:$,field:F},J)=>{let R;if(X(F,kT))R=F;else if(X(F,m))R=F.decoder;else R=F.sql.decoder;let W=A;for(let[y,_]of $.entries())if(y<$.length-1){if(!(_ in W))W[_]={};W=W[_]}else{let K=o[J],H=W[_]=K===null?null:R.mapFromDriverValue(K);if(S&&X(F,kT)&&$.length===2){let Y=$[0];if(!(Y in f))f[Y]=H===null?ZT(F.table):!1;else if(typeof f[Y]==="string"&&f[Y]!==ZT(F.table))f[Y]=!1}}return A},{});if(S&&Object.keys(f).length>0){for(let[A,$]of Object.entries(f))if(typeof $==="string"&&!S[$])n[A]=null}return n}function _o(T,o){return Object.entries(T).reduce((S,[f,n])=>{if(typeof f!=="string")return S;let A=o?[...o,f]:[f];if(X(n,kT)||X(n,m)||X(n,m.Aliased))S.push({path:A,field:n});else if(X(n,j))S.push(..._o(n[j.Symbol.Columns],A));else S.push(..._o(n,A));return S},[])}function Df(T,o){let S=Object.keys(T),f=Object.keys(o);if(S.length!==f.length)return!1;for(let[n,A]of S.entries())if(A!==f[n])return!1;return!0}function wn(T,o){let S=Object.entries(o).filter(([,f])=>f!==void 0).map(([f,n])=>{if(X(n,m)||X(n,kT))return[f,n];else return[f,new Ro(n,T[j.Symbol.Columns][f])]});if(S.length===0)throw new Error("No values to set");return Object.fromEntries(S)}function dJ(T,o){for(let S of o)for(let f of Object.getOwnPropertyNames(S.prototype)){if(f==="constructor")continue;Object.defineProperty(T.prototype,f,Object.getOwnPropertyDescriptor(S.prototype,f)||Object.create(null))}}function lJ(T){return T[j.Symbol.Columns]}function co(T){return X(T,xT)?T._.alias:X(T,Ao)?T[XT].name:X(T,m)?void 0:T[j.Symbol.IsAlias]?T[j.Symbol.Name]:T[j.Symbol.BaseName]}function nT(T,o){return{name:typeof T==="string"&&T.length>0?T:"",config:typeof T==="object"?T:o}}function uJ(T){if(typeof T!=="object"||T===null)return!1;if(T.constructor.name!=="Object")return!1;if("logger"in T){let o=typeof T.logger;if(o!=="boolean"&&(o!=="object"||typeof T.logger.logQuery!=="function")&&o!=="undefined")return!1;return!0}if("schema"in T){let o=typeof T.logger;if(o!=="object"&&o!=="undefined")return!1;return!0}if("casing"in T){let o=typeof T.logger;if(o!=="string"&&o!=="undefined")return!1;return!0}if("mode"in T){if(T.mode!=="default"||T.mode!=="planetscale"||T.mode!==void 0)return!1;return!0}if("connection"in T){let o=typeof T.connection;if(o!=="string"&&o!=="object"&&o!=="undefined")return!1;return!0}if("client"in T){let o=typeof T.client;if(o!=="object"&&o!=="function"&&o!=="undefined")return!1;return!0}if(Object.keys(T).length===0)return!0;return!1}class TS extends h{static[M]="PgIntColumnBaseBuilder";generatedAlwaysAsIdentity(T){if(T){let{name:o,...S}=T;this.config.generatedIdentity={type:"always",sequenceName:o,sequenceOptions:S}}else this.config.generatedIdentity={type:"always"};return this.config.hasDefault=!0,this.config.notNull=!0,this}generatedByDefaultAsIdentity(T){if(T){let{name:o,...S}=T;this.config.generatedIdentity={type:"byDefault",sequenceName:o,sequenceOptions:S}}else this.config.generatedIdentity={type:"byDefault"};return this.config.hasDefault=!0,this.config.notNull=!0,this}}class eJ extends TS{static[M]="PgBigInt53Builder";constructor(T){super(T,"number","PgBigInt53")}build(T){return new aJ(T,this.config)}}class aJ extends V{static[M]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(T){if(typeof T==="number")return T;return Number(T)}}class sJ extends TS{static[M]="PgBigInt64Builder";constructor(T){super(T,"bigint","PgBigInt64")}build(T){return new TR(T,this.config)}}class TR extends V{static[M]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(T){return BigInt(T)}}function oR(T,o){let{name:S,config:f}=nT(T,o);if(f.mode==="number")return new eJ(S);return new sJ(S)}class SR extends h{static[M]="PgBigSerial53Builder";constructor(T){super(T,"number","PgBigSerial53");this.config.hasDefault=!0,this.config.notNull=!0}build(T){return new fR(T,this.config)}}class fR extends V{static[M]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(T){if(typeof T==="number")return T;return Number(T)}}class nR extends h{static[M]="PgBigSerial64Builder";constructor(T){super(T,"bigint","PgBigSerial64");this.config.hasDefault=!0}build(T){return new AR(T,this.config)}}class AR extends V{static[M]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(T){return BigInt(T)}}function $R(T,o){let{name:S,config:f}=nT(T,o);if(f.mode==="number")return new SR(S);return new nR(S)}class FR extends h{static[M]="PgBooleanBuilder";constructor(T){super(T,"boolean","PgBoolean")}build(T){return new JR(T,this.config)}}class JR extends V{static[M]="PgBoolean";getSQLType(){return"boolean"}}function Uf(T){return new FR(T??"")}class RR extends h{static[M]="PgCharBuilder";constructor(T,o){super(T,"string","PgChar");this.config.length=o.length,this.config.enumValues=o.enum}build(T){return new WR(T,this.config)}}class WR extends V{static[M]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}}function OR(T,o={}){let{name:S,config:f}=nT(T,o);return new RR(S,f)}class MR extends h{static[M]="PgCidrBuilder";constructor(T){super(T,"string","PgCidr")}build(T){return new kR(T,this.config)}}class kR extends V{static[M]="PgCidr";getSQLType(){return"cidr"}}function yR(T){return new MR(T??"")}class _R extends h{static[M]="PgCustomColumnBuilder";constructor(T,o,S){super(T,"custom","PgCustomColumn");this.config.fieldConfig=o,this.config.customTypeParams=S}build(T){return new wR(T,this.config)}}class wR extends V{static[M]="PgCustomColumn";sqlName;mapTo;mapFrom;constructor(T,o){super(T,o);this.sqlName=o.customTypeParams.dataType(o.fieldConfig),this.mapTo=o.customTypeParams.toDriver,this.mapFrom=o.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(T){return typeof this.mapFrom==="function"?this.mapFrom(T):T}mapToDriverValue(T){return typeof this.mapTo==="function"?this.mapTo(T):T}}function XR(T){return(o,S)=>{let{name:f,config:n}=nT(o,S);return new _R(f,n,T)}}class ro extends h{static[M]="PgDateColumnBaseBuilder";defaultNow(){return this.default(k`now()`)}}class KR extends ro{static[M]="PgDateBuilder";constructor(T){super(T,"date","PgDate")}build(T){return new Xn(T,this.config)}}class Xn extends V{static[M]="PgDate";getSQLType(){return"date"}mapFromDriverValue(T){return new Date(T)}mapToDriverValue(T){return T.toISOString()}}class GR extends ro{static[M]="PgDateStringBuilder";constructor(T){super(T,"string","PgDateString")}build(T){return new Kn(T,this.config)}}class Kn extends V{static[M]="PgDateString";getSQLType(){return"date"}}function YR(T,o){let{name:S,config:f}=nT(T,o);if(f?.mode==="date")return new KR(S);return new GR(S)}class ER extends h{static[M]="PgDoublePrecisionBuilder";constructor(T){super(T,"number","PgDoublePrecision")}build(T){return new HR(T,this.config)}}class HR extends V{static[M]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(T){if(typeof T==="string")return Number.parseFloat(T);return T}}function zR(T){return new ER(T??"")}class QR extends h{static[M]="PgInetBuilder";constructor(T){super(T,"string","PgInet")}build(T){return new DR(T,this.config)}}class DR extends V{static[M]="PgInet";getSQLType(){return"inet"}}function UR(T){return new QR(T??"")}class tR extends TS{static[M]="PgIntegerBuilder";constructor(T){super(T,"number","PgInteger")}build(T){return new VR(T,this.config)}}class VR extends V{static[M]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(T){if(typeof T==="string")return Number.parseInt(T);return T}}function Gn(T){return new tR(T??"")}class BR extends h{static[M]="PgIntervalBuilder";constructor(T,o){super(T,"string","PgInterval");this.config.intervalConfig=o}build(T){return new LR(T,this.config)}}class LR extends V{static[M]="PgInterval";fields=this.config.intervalConfig.fields;precision=this.config.intervalConfig.precision;getSQLType(){let T=this.fields?` ${this.fields}`:"",o=this.precision?`(${this.precision})`:"";return`interval${T}${o}`}}function CR(T,o={}){let{name:S,config:f}=nT(T,o);return new BR(S,f)}class IR extends h{static[M]="PgJsonBuilder";constructor(T){super(T,"json","PgJson")}build(T){return new Yn(T,this.config)}}class Yn extends V{static[M]="PgJson";constructor(T,o){super(T,o)}getSQLType(){return"json"}mapToDriverValue(T){return JSON.stringify(T)}mapFromDriverValue(T){if(typeof T==="string")try{return JSON.parse(T)}catch{return T}return T}}function jR(T){return new IR(T??"")}class mR extends h{static[M]="PgJsonbBuilder";constructor(T){super(T,"json","PgJsonb")}build(T){return new En(T,this.config)}}class En extends V{static[M]="PgJsonb";constructor(T,o){super(T,o)}getSQLType(){return"jsonb"}mapToDriverValue(T){return JSON.stringify(T)}mapFromDriverValue(T){if(typeof T==="string")try{return JSON.parse(T)}catch{return T}return T}}function NR(T){return new mR(T??"")}class hR extends h{static[M]="PgLineBuilder";constructor(T){super(T,"array","PgLine")}build(T){return new bR(T,this.config)}}class bR extends V{static[M]="PgLine";getSQLType(){return"line"}mapFromDriverValue(T){let[o,S,f]=T.slice(1,-1).split(",");return[Number.parseFloat(o),Number.parseFloat(S),Number.parseFloat(f)]}mapToDriverValue(T){return`{${T[0]},${T[1]},${T[2]}}`}}class xR extends h{static[M]="PgLineABCBuilder";constructor(T){super(T,"json","PgLineABC")}build(T){return new vR(T,this.config)}}class vR extends V{static[M]="PgLineABC";getSQLType(){return"line"}mapFromDriverValue(T){let[o,S,f]=T.slice(1,-1).split(",");return{a:Number.parseFloat(o),b:Number.parseFloat(S),c:Number.parseFloat(f)}}mapToDriverValue(T){return`{${T.a},${T.b},${T.c}}`}}function qR(T,o){let{name:S,config:f}=nT(T,o);if(!f?.mode||f.mode==="tuple")return new hR(S);return new xR(S)}class ZR extends h{static[M]="PgMacaddrBuilder";constructor(T){super(T,"string","PgMacaddr")}build(T){return new cR(T,this.config)}}class cR extends V{static[M]="PgMacaddr";getSQLType(){return"macaddr"}}function rR(T){return new ZR(T??"")}class PR extends h{static[M]="PgMacaddr8Builder";constructor(T){super(T,"string","PgMacaddr8")}build(T){return new pR(T,this.config)}}class pR extends V{static[M]="PgMacaddr8";getSQLType(){return"macaddr8"}}function iR(T){return new PR(T??"")}class gR extends h{static[M]="PgNumericBuilder";constructor(T,o,S){super(T,"string","PgNumeric");this.config.precision=o,this.config.scale=S}build(T){return new Hn(T,this.config)}}class Hn extends V{static[M]="PgNumeric";precision;scale;constructor(T,o){super(T,o);this.precision=o.precision,this.scale=o.scale}getSQLType(){if(this.precision!==void 0&&this.scale!==void 0)return`numeric(${this.precision}, ${this.scale})`;else if(this.precision===void 0)return"numeric";else return`numeric(${this.precision})`}}function dR(T,o){let{name:S,config:f}=nT(T,o);return new gR(S,f?.precision,f?.scale)}class lR extends h{static[M]="PgPointTupleBuilder";constructor(T){super(T,"array","PgPointTuple")}build(T){return new uR(T,this.config)}}class uR extends V{static[M]="PgPointTuple";getSQLType(){return"point"}mapFromDriverValue(T){if(typeof T==="string"){let[o,S]=T.slice(1,-1).split(",");return[Number.parseFloat(o),Number.parseFloat(S)]}return[T.x,T.y]}mapToDriverValue(T){return`(${T[0]},${T[1]})`}}class eR extends h{static[M]="PgPointObjectBuilder";constructor(T){super(T,"json","PgPointObject")}build(T){return new aR(T,this.config)}}class aR extends V{static[M]="PgPointObject";getSQLType(){return"point"}mapFromDriverValue(T){if(typeof T==="string"){let[o,S]=T.slice(1,-1).split(",");return{x:Number.parseFloat(o),y:Number.parseFloat(S)}}return T}mapToDriverValue(T){return`(${T.x},${T.y})`}}function sR(T,o){let{name:S,config:f}=nT(T,o);if(!f?.mode||f.mode==="tuple")return new lR(S);return new eR(S)}function fM(T){let o=[];for(let S=0;S<T.length;S+=2)o.push(Number.parseInt(T.slice(S,S+2),16));return new Uint8Array(o)}function T0(T,o){let S=new ArrayBuffer(8),f=new DataView(S);for(let n=0;n<8;n++)f.setUint8(n,T[o+n]);return f.getFloat64(0,!0)}function uA(T){let o=fM(T),S=0,f=o[S];S+=1;let n=new DataView(o.buffer),A=n.getUint32(S,f===1);S+=4;let $;if(A&536870912)$=n.getUint32(S,f===1),S+=4;if((A&65535)===1){let F=T0(o,S);S+=8;let J=T0(o,S);return S+=8,[F,J]}throw new Error("Unsupported geometry type")}class o0 extends h{static[M]="PgGeometryBuilder";constructor(T){super(T,"array","PgGeometry")}build(T){return new S0(T,this.config)}}class S0 extends V{static[M]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(T){return uA(T)}mapToDriverValue(T){return`point(${T[0]} ${T[1]})`}}class f0 extends h{static[M]="PgGeometryObjectBuilder";constructor(T){super(T,"json","PgGeometryObject")}build(T){return new n0(T,this.config)}}class n0 extends V{static[M]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(T){let o=uA(T);return{x:o[0],y:o[1]}}mapToDriverValue(T){return`point(${T.x} ${T.y})`}}function A0(T,o){let{name:S,config:f}=nT(T,o);if(!f?.mode||f.mode==="tuple")return new o0(S);return new f0(S)}class $0 extends h{static[M]="PgRealBuilder";constructor(T,o){super(T,"number","PgReal");this.config.length=o}build(T){return new F0(T,this.config)}}class F0 extends V{static[M]="PgReal";constructor(T,o){super(T,o)}getSQLType(){return"real"}mapFromDriverValue=(T)=>{if(typeof T==="string")return Number.parseFloat(T);return T}}function J0(T){return new $0(T??"")}class R0 extends h{static[M]="PgSerialBuilder";constructor(T){super(T,"number","PgSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(T){return new W0(T,this.config)}}class W0 extends V{static[M]="PgSerial";getSQLType(){return"serial"}}function O0(T){return new R0(T??"")}class M0 extends TS{static[M]="PgSmallIntBuilder";constructor(T){super(T,"number","PgSmallInt")}build(T){return new k0(T,this.config)}}class k0 extends V{static[M]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=(T)=>{if(typeof T==="string")return Number(T);return T}}function y0(T){return new M0(T??"")}class _0 extends h{static[M]="PgSmallSerialBuilder";constructor(T){super(T,"number","PgSmallSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(T){return new w0(T,this.config)}}class w0 extends V{static[M]="PgSmallSerial";getSQLType(){return"smallserial"}}function X0(T){return new _0(T??"")}class K0 extends h{static[M]="PgTextBuilder";constructor(T,o){super(T,"string","PgText");this.config.enumValues=o.enum}build(T){return new G0(T,this.config)}}class G0 extends V{static[M]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function Y0(T,o={}){let{name:S,config:f}=nT(T,o);return new K0(S,f)}class E0 extends ro{constructor(T,o,S){super(T,"string","PgTime");this.withTimezone=o,this.precision=S,this.config.withTimezone=o,this.config.precision=S}static[M]="PgTimeBuilder";build(T){return new zn(T,this.config)}}class zn extends V{static[M]="PgTime";withTimezone;precision;constructor(T,o){super(T,o);this.withTimezone=o.withTimezone,this.precision=o.precision}getSQLType(){return`time${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function H0(T,o={}){let{name:S,config:f}=nT(T,o);return new E0(S,f.withTimezone??!1,f.precision)}class z0 extends ro{static[M]="PgTimestampBuilder";constructor(T,o,S){super(T,"date","PgTimestamp");this.config.withTimezone=o,this.config.precision=S}build(T){return new Qn(T,this.config)}}class Qn extends V{static[M]="PgTimestamp";withTimezone;precision;constructor(T,o){super(T,o);this.withTimezone=o.withTimezone,this.precision=o.precision}getSQLType(){return`timestamp${this.precision===void 0?"":` (${this.precision})`}${this.withTimezone?" with time zone":""}`}mapFromDriverValue=(T)=>{return new Date(this.withTimezone?T:T+"+0000")};mapToDriverValue=(T)=>{return T.toISOString()}}class Q0 extends ro{static[M]="PgTimestampStringBuilder";constructor(T,o,S){super(T,"string","PgTimestampString");this.config.withTimezone=o,this.config.precision=S}build(T){return new Dn(T,this.config)}}class Dn extends V{static[M]="PgTimestampString";withTimezone;precision;constructor(T,o){super(T,o);this.withTimezone=o.withTimezone,this.precision=o.precision}getSQLType(){return`timestamp${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function to(T,o={}){let{name:S,config:f}=nT(T,o);if(f?.mode==="string")return new Q0(S,f.withTimezone??!1,f.precision);return new z0(S,f?.withTimezone??!1,f?.precision)}class D0 extends h{static[M]="PgUUIDBuilder";constructor(T){super(T,"string","PgUUID")}defaultRandom(){return this.default(k`gen_random_uuid()`)}build(T){return new Un(T,this.config)}}class Un extends V{static[M]="PgUUID";getSQLType(){return"uuid"}}function Wo(T){return new D0(T??"")}class U0 extends h{static[M]="PgVarcharBuilder";constructor(T,o){super(T,"string","PgVarchar");this.config.length=o.length,this.config.enumValues=o.enum}build(T){return new t0(T,this.config)}}class t0 extends V{static[M]="PgVarchar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"varchar":`varchar(${this.length})`}}function rT(T,o={}){let{name:S,config:f}=nT(T,o);return new U0(S,f)}class V0 extends h{static[M]="PgBinaryVectorBuilder";constructor(T,o){super(T,"string","PgBinaryVector");this.config.dimensions=o.dimensions}build(T){return new B0(T,this.config)}}class B0 extends V{static[M]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}}function L0(T,o){let{name:S,config:f}=nT(T,o);return new V0(S,f)}class C0 extends h{static[M]="PgHalfVectorBuilder";constructor(T,o){super(T,"array","PgHalfVector");this.config.dimensions=o.dimensions}build(T){return new I0(T,this.config)}}class I0 extends V{static[M]="PgHalfVector";dimensions=this.config.dimensions;getSQLType(){return`halfvec(${this.dimensions})`}mapToDriverValue(T){return JSON.stringify(T)}mapFromDriverValue(T){return T.slice(1,-1).split(",").map((o)=>Number.parseFloat(o))}}function j0(T,o){let{name:S,config:f}=nT(T,o);return new C0(S,f)}class m0 extends h{static[M]="PgSparseVectorBuilder";constructor(T,o){super(T,"string","PgSparseVector");this.config.dimensions=o.dimensions}build(T){return new N0(T,this.config)}}class N0 extends V{static[M]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function h0(T,o){let{name:S,config:f}=nT(T,o);return new m0(S,f)}class b0 extends h{static[M]="PgVectorBuilder";constructor(T,o){super(T,"array","PgVector");this.config.dimensions=o.dimensions}build(T){return new x0(T,this.config)}}class x0 extends V{static[M]="PgVector";dimensions=this.config.dimensions;getSQLType(){return`vector(${this.dimensions})`}mapToDriverValue(T){return JSON.stringify(T)}mapFromDriverValue(T){return T.slice(1,-1).split(",").map((o)=>Number.parseFloat(o))}}function v0(T,o){let{name:S,config:f}=nT(T,o);return new b0(S,f)}function q0(){return{bigint:oR,bigserial:$R,boolean:Uf,char:OR,cidr:yR,customType:XR,date:YR,doublePrecision:zR,inet:UR,integer:Gn,interval:CR,json:jR,jsonb:NR,line:qR,macaddr:rR,macaddr8:iR,numeric:dR,point:sR,geometry:A0,real:J0,serial:O0,smallint:y0,smallserial:X0,text:Y0,time:H0,timestamp:to,uuid:Wo,varchar:rT,bit:L0,halfvec:j0,sparsevec:h0,vector:v0}}var eA=Symbol.for("drizzle:PgInlineForeignKeys"),Z0=Symbol.for("drizzle:EnableRLS");class PT extends j{static[M]="PgTable";static Symbol=Object.assign({},j.Symbol,{InlineForeignKeys:eA,EnableRLS:Z0});[eA]=[];[Z0]=!1;[j.Symbol.ExtraConfigBuilder]=void 0}function nM(T,o,S,f,n=T){let A=new PT(T,f,n),$=typeof o==="function"?o(q0()):o,F=Object.fromEntries(Object.entries($).map(([W,y])=>{let _=y;_.setName(W);let K=_.build(A);return A[eA].push(..._.buildForeignKeys(K,A)),[W,K]})),J=Object.fromEntries(Object.entries($).map(([W,y])=>{let _=y;_.setName(W);let K=_.buildExtraConfigColumn(A);return[W,K]})),R=Object.assign(A,F);if(R[j.Symbol.Columns]=F,R[j.Symbol.ExtraConfigColumns]=J,S)R[PT.Symbol.ExtraConfigBuilder]=S;return Object.assign(R,{enableRLS:()=>{return R[PT.Symbol.EnableRLS]=!0,R}})}var oS=(T,o,S)=>{return nM(T,o,S,void 0)};function c0(...T){if(T[0].columns)return new tf(T[0].columns,T[0].name);return new tf(T)}class tf{static[M]="PgPrimaryKeyBuilder";columns;name;constructor(T,o){this.columns=T,this.name=o}build(T){return new r0(T,this.columns,this.name)}}class r0{constructor(T,o,S){this.table=T,this.columns=o,this.name=S}static[M]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[PT.Symbol.Name]}_${this.columns.map((T)=>T.name).join("_")}_pk`}}class aA{constructor(T,o,S){this.sourceTable=T,this.referencedTable=o,this.relationName=S,this.referencedTableName=o[j.Symbol.Name]}static[M]="Relation";referencedTableName;fieldName}class P0{constructor(T,o){this.table=T,this.config=o}static[M]="Relations"}class SS extends aA{constructor(T,o,S,f){super(T,o,S?.relationName);this.config=S,this.isNullable=f}static[M]="One";withFieldName(T){let o=new SS(this.sourceTable,this.referencedTable,this.config,this.isNullable);return o.fieldName=T,o}}class Vf extends aA{constructor(T,o,S){super(T,o,S?.relationName);this.config=S}static[M]="Many";withFieldName(T){let o=new Vf(this.sourceTable,this.referencedTable,this.config);return o.fieldName=T,o}}function p0(){return{and:Qf,between:xJ,eq:_n,exists:hJ,gt:VJ,gte:BJ,ilike:cJ,inArray:IJ,isNull:mJ,isNotNull:NJ,like:qJ,lt:LJ,lte:CJ,ne:DJ,not:tJ,notBetween:vJ,notExists:bJ,notLike:ZJ,notIlike:rJ,notInArray:jJ,or:UJ,sql:k}}function i0(){return{sql:k,asc:PJ,desc:pJ}}function g0(T,o){if(Object.keys(T).length===1&&"default"in T&&!X(T.default,j))T=T.default;let S={},f={},n={};for(let[A,$]of Object.entries(T))if(X($,j)){let F=OS($),J=f[F];S[F]=A,n[A]={tsName:A,dbName:$[j.Symbol.Name],schema:$[j.Symbol.Schema],columns:$[j.Symbol.Columns],relations:J?.relations??{},primaryKey:J?.primaryKey??[]};for(let W of Object.values($[j.Symbol.Columns]))if(W.primary)n[A].primaryKey.push(W);let R=$[j.Symbol.ExtraConfigBuilder]?.($[j.Symbol.ExtraConfigColumns]);if(R){for(let W of Object.values(R))if(X(W,tf))n[A].primaryKey.push(...W.columns)}}else if(X($,P0)){let F=OS($.table),J=S[F],R=$.config(o($.table)),W;for(let[y,_]of Object.entries(R))if(J){let K=n[J];if(K.relations[y]=_,W)K.primaryKey.push(...W)}else{if(!(F in f))f[F]={relations:{},primaryKey:W};f[F].relations[y]=_}}return{tables:n,tableNamesMap:S}}function AM(T){return function o(S,f){return new SS(T,S,f,f?.fields.reduce((n,A)=>n&&A.notNull,!0)??!1)}}function $M(T){return function o(S,f){return new Vf(T,S,f)}}function d0(T,o,S){if(X(S,SS)&&S.config)return{fields:S.config.fields,references:S.config.references};let f=o[OS(S.referencedTable)];if(!f)throw new Error(`Table "${S.referencedTable[j.Symbol.Name]}" not found in schema`);let n=T[f];if(!n)throw new Error(`Table "${f}" not found in schema`);let A=S.sourceTable,$=o[OS(A)];if(!$)throw new Error(`Table "${A[j.Symbol.Name]}" not found in schema`);let F=[];for(let J of Object.values(n.relations))if(S.relationName&&S!==J&&J.relationName===S.relationName||!S.relationName&&J.referencedTable===S.sourceTable)F.push(J);if(F.length>1)throw S.relationName?new Error(`There are multiple relations with name "${S.relationName}" in table "${f}"`):new Error(`There are multiple relations between "${f}" and "${S.sourceTable[j.Symbol.Name]}". Please specify relation name`);if(F[0]&&X(F[0],SS)&&F[0].config)return{fields:F[0].config.references,references:F[0].config.fields};throw new Error(`There is not enough information to infer relation "${$}.${S.fieldName}"`)}function l0(T){return{one:AM(T),many:$M(T)}}function tn(T,o,S,f,n=(A)=>A){let A={};for(let[$,F]of f.entries())if(F.isJson){let J=o.relations[F.tsKey],R=S[$],W=typeof R==="string"?JSON.parse(R):R;A[F.tsKey]=X(J,SS)?W&&tn(T,T[F.relationTableTsKey],W,F.selection,n):W.map((y)=>tn(T,T[F.relationTableTsKey],y,F.selection,n))}else{let J=n(S[$]),R=F.field,W;if(X(R,kT))W=R;else if(X(R,m))W=R.decoder;else W=R.sql.decoder;A[F.tsKey]=J===null?null:W.mapFromDriverValue(J)}return A}import LM from"os";import CM from"fs";var Vn=new Map,sA=new Map,T$=Symbol("OriginError"),PS={};class wo extends Promise{constructor(T,o,S,f,n={}){let A,$;super((F,J)=>{A=F,$=J});this.tagged=Array.isArray(T.raw),this.strings=T,this.args=o,this.handler=S,this.canceller=f,this.options=n,this.state=null,this.statement=null,this.resolve=(F)=>(this.active=!1,A(F)),this.reject=(F)=>(this.active=!1,$(F)),this.active=!1,this.cancelled=null,this.executed=!1,this.signature="",this[T$]=this.handler.debug?new Error:this.tagged&&FM(this.strings)}get origin(){return(this.handler.debug?this[T$].stack:this.tagged&&sA.has(this.strings)?sA.get(this.strings):sA.set(this.strings,this[T$].stack).get(this.strings))||""}static get[Symbol.species](){return Promise}cancel(){return this.canceller&&(this.canceller(this),this.canceller=null)}simple(){return this.options.simple=!0,this.options.prepare=!1,this}async readable(){return this.simple(),this.streaming=!0,this}async writable(){return this.simple(),this.streaming=!0,this}cursor(T=1,o){if(this.options.simple=!1,typeof T==="function")o=T,T=1;if(this.cursorRows=T,typeof o==="function")return this.cursorFn=o,this;let S;return{[Symbol.asyncIterator]:()=>({next:()=>{if(this.executed&&!this.active)return{done:!0};S&&S();let f=new Promise((n,A)=>{this.cursorFn=($)=>{return n({value:$,done:!1}),new Promise((F)=>S=F)},this.resolve=()=>(this.active=!1,n({done:!0})),this.reject=($)=>(this.active=!1,A($))});return this.execute(),f},return(){return S&&S(PS),{done:!0}}})}}describe(){return this.options.simple=!1,this.onlyDescribe=this.options.prepare=!0,this}stream(){throw new Error(".stream has been renamed to .forEach")}forEach(T){return this.forEachFn=T,this.handle(),this}raw(){return this.isRaw=!0,this}values(){return this.isRaw="values",this}async handle(){!this.executed&&(this.executed=!0)&&await 1&&this.handler(this)}execute(){return this.handle(),this}then(){return this.handle(),super.then.apply(this,arguments)}catch(){return this.handle(),super.catch.apply(this,arguments)}finally(){return this.handle(),super.finally.apply(this,arguments)}}function FM(T){if(Vn.has(T))return Vn.get(T);let o=Error.stackTraceLimit;return Error.stackTraceLimit=4,Vn.set(T,new Error),Error.stackTraceLimit=o,Vn.get(T)}class pS extends Error{constructor(T){super(T.message);this.name=this.constructor.name,Object.assign(this,T)}}var LT={connection:u0,postgres:e0,generic:a0,notSupported:s0};function u0(T,o,S){let{host:f,port:n}=S||o,A=Object.assign(new Error("write "+T+" "+(o.path||f+":"+n)),{code:T,errno:T,address:o.path||f},o.path?{}:{port:n});return Error.captureStackTrace(A,u0),A}function e0(T){let o=new pS(T);return Error.captureStackTrace(o,e0),o}function a0(T,o){let S=Object.assign(new Error(T+": "+o),{code:T});return Error.captureStackTrace(S,a0),S}function s0(T){let o=Object.assign(new Error(T+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:T});return Error.captureStackTrace(o,s0),o}var JM={string:{to:25,from:null,serialize:(T)=>""+T},number:{to:0,from:[21,23,26,700,701],serialize:(T)=>""+T,parse:(T)=>+T},json:{to:114,from:[114,3802],serialize:(T)=>JSON.stringify(T),parse:(T)=>JSON.parse(T)},boolean:{to:16,from:16,serialize:(T)=>T===!0?"t":"f",parse:(T)=>T==="t"},date:{to:1184,from:[1082,1114,1184],serialize:(T)=>(T instanceof Date?T:new Date(T)).toISOString(),parse:(T)=>new Date(T)},bytea:{to:17,from:17,serialize:(T)=>"\\x"+Buffer.from(T).toString("hex"),parse:(T)=>Buffer.from(T.slice(2),"hex")}};class Cn{then(){o$()}catch(){o$()}finally(){o$()}}class If extends Cn{constructor(T){super();this.value=mn(T)}}class mo extends Cn{constructor(T,o,S){super();this.value=T,this.type=o,this.array=S}}class In extends Cn{constructor(T,o){super();this.first=T,this.rest=o}build(T,o,S,f){let n=RM.map(([A,$])=>({fn:$,i:T.search(A)})).sort((A,$)=>A.i-$.i).pop();return n.i===-1?$$(this.first,f):n.fn(this.first,this.rest,o,S,f)}}function jn(T,o,S,f){let n=T instanceof mo?T.value:T;if(n===void 0){if(T instanceof mo?T.value=f.transform.undefined:n=T=f.transform.undefined,n===void 0)throw LT.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return"$"+S.push(T instanceof mo?(o.push(T.value),T.array?T.array[T.type||Ln(T.value)]||T.type||f1(T.value):T.type):(o.push(T),Ln(T)))}var o1=A1(JM);function n$(T,o,S,f,n,A){for(let $=1;$<T.strings.length;$++)o+=A$(o,S,f,n,A)+T.strings[$],S=T.args[$];return o}function A$(T,o,S,f,n){return o instanceof In?o.build(T,S,f,n):o instanceof wo?f$(o,S,f,n):o instanceof If?o.value:o&&o[0]instanceof wo?o.reduce((A,$)=>A+" "+f$($,S,f,n),""):jn(o,S,f,n)}function f$(T,o,S,f){return T.fragment=!0,n$(T,T.strings[0],T.args[0],o,S,f)}function S1(T,o,S,f,n){return T.map((A)=>"("+f.map(($)=>A$("values",A[$],o,S,n)).join(",")+")").join(",")}function T1(T,o,S,f,n){let A=Array.isArray(T[0]),$=o.length?o.flat():Object.keys(A?T[0]:T);return S1(A?T:[T],S,f,$,n)}function Bn(T,o,S,f,n){if(typeof T==="string"&&(T=[T].concat(o)),Array.isArray(T))return $$(T,n);let A;return(o.length?o.flat():Object.keys(T)).map((F)=>{return A=T[F],(A instanceof wo?f$(A,S,f,n):A instanceof If?A.value:jn(A,S,f,n))+" as "+mn(n.transform.column.to?n.transform.column.to(F):F)}).join(",")}var RM=Object.entries({values:T1,in:(...T)=>{let o=T1(...T);return o==="()"?"(null)":o},select:Bn,as:Bn,returning:Bn,"\\(":Bn,update(T,o,S,f,n){return(o.length?o.flat():Object.keys(T)).map((A)=>mn(n.transform.column.to?n.transform.column.to(A):A)+"="+A$("values",T[A],S,f,n))},insert(T,o,S,f,n){let A=o.length?o.flat():Object.keys(Array.isArray(T)?T[0]:T);return"("+$$(A,n)+")values"+S1(Array.isArray(T)?T:[T],S,f,A,n)}}).map(([T,o])=>[new RegExp("((?:^|[\\s(])"+T+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),o]);function o$(){throw LT.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}var{serializers:WM,parsers:OM}=o1;function f1(T){if(Array.isArray(T))return f1(T[0]);return typeof T==="string"?1009:0}var n1=function(T){let o=A1(T||{});return{serializers:Object.assign({},WM,o.serializers),parsers:Object.assign({},OM,o.parsers)}};function A1(T){return Object.keys(T).reduce((o,S)=>{if(T[S].from&&[].concat(T[S].from).forEach((f)=>o.parsers[f]=T[S].parse),T[S].serialize)o.serializers[T[S].to]=T[S].serialize,T[S].from&&[].concat(T[S].from).forEach((f)=>o.serializers[f]=T[S].serialize);return o},{parsers:{},serializers:{}})}function $$(T,{transform:{column:o}}){return T.map((S)=>mn(o.to?o.to(S):S)).join(",")}var mn=function T(o){return'"'+o.replace(/"/g,'""').replace(/\./g,'"."')+'"'},Ln=function T(o){return o instanceof mo?o.type:o instanceof Date?1184:o instanceof Uint8Array?17:o===!0||o===!1?16:typeof o==="bigint"?20:Array.isArray(o)?T(o[0]):0},MM=/\\/g,kM=/"/g;function yM(T){return T.replace(MM,"\\\\").replace(kM,"\\\"")}var $1=function T(o,S,f,n){if(Array.isArray(o)===!1)return o;if(!o.length)return"{}";let A=o[0],$=n===1020?";":",";if(Array.isArray(A)&&!A.type)return"{"+o.map((F)=>T(F,S,f,n)).join($)+"}";return"{"+o.map((F)=>{if(F===void 0){if(F=f.transform.undefined,F===void 0)throw LT.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return F===null?"null":'"'+yM(S?S(F.type?F.value:F):""+F)+'"'}).join($)+"}"},S$={i:0,char:null,str:"",quoted:!1,last:0},F1=function T(o,S,f){return S$.i=S$.last=0,J1(S$,o,S,f)};function J1(T,o,S,f){let n=[],A=f===1020?";":",";for(;T.i<o.length;T.i++){if(T.char=o[T.i],T.quoted)if(T.char==="\\")T.str+=o[++T.i];else if(T.char==='"')n.push(S?S(T.str):T.str),T.str="",T.quoted=o[T.i+1]==='"',T.last=T.i+2;else T.str+=T.char;else if(T.char==='"')T.quoted=!0;else if(T.char==="{")T.last=++T.i,n.push(J1(T,o,S,f));else if(T.char==="}"){T.quoted=!1,T.last<T.i&&n.push(S?S(o.slice(T.last,T.i)):o.slice(T.last,T.i)),T.last=T.i+1;break}else if(T.char===A&&T.p!=="}"&&T.p!=='"')n.push(S?S(o.slice(T.last,T.i)):o.slice(T.last,T.i)),T.last=T.i+1;T.p=T.char}return T.last<T.i&&n.push(S?S(o.slice(T.last,T.i+1)):o.slice(T.last,T.i+1)),n}var MS=(T)=>{let o=T[0];for(let S=1;S<T.length;S++)o+=T[S]==="_"?T[++S].toUpperCase():T[S];return o},kS=(T)=>{let o=T[0].toUpperCase();for(let S=1;S<T.length;S++)o+=T[S]==="_"?T[++S].toUpperCase():T[S];return o},yS=(T)=>T.replace(/_/g,"-"),Bf=(T)=>T.replace(/([A-Z])/g,"_$1").toLowerCase(),Lf=(T)=>(T.slice(0,1)+T.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),Cf=(T)=>T.replace(/-/g,"_");function F$(T){return function o(S,f){return typeof S==="object"&&S!==null&&(f.type===114||f.type===3802)?Array.isArray(S)?S.map((n)=>o(n,f)):Object.entries(S).reduce((n,[A,$])=>Object.assign(n,{[T(A)]:o($,f)}),{}):S}}MS.column={from:MS};MS.value={from:F$(MS)};Bf.column={to:Bf};var J$={...MS};J$.column.to=Bf;kS.column={from:kS};kS.value={from:F$(kS)};Lf.column={to:Lf};var R$={...kS};R$.column.to=Lf;yS.column={from:yS};yS.value={from:F$(yS)};Cf.column={to:Cf};var W$={...yS};W$.column.to=Cf;import R1 from"net";import KM from"tls";import jf from"crypto";import O$ from"stream";import{performance as W1}from"perf_hooks";class _S extends Array{constructor(){super();Object.defineProperties(this,{count:{value:null,writable:!0},state:{value:null,writable:!0},command:{value:null,writable:!0},columns:{value:null,writable:!0},statement:{value:null,writable:!0}})}static get[Symbol.species](){return Array}}var Oo=_M;function _M(T=[]){let o=T.slice(),S=0;return{get length(){return o.length-S},remove:(f)=>{let n=o.indexOf(f);return n===-1?null:(o.splice(n,1),f)},push:(f)=>(o.push(f),f),shift:()=>{let f=o[S++];if(S===o.length)S=0,o=[];else o[S-1]=void 0;return f}}}var eT=Buffer.allocUnsafe(256),wM="BCcDdEFfHPpQSX".split("").reduce((T,o)=>{let S=o.charCodeAt(0);return T[o]=()=>{return eT[0]=S,OT.i=5,OT},T},{}),OT=Object.assign(XM,wM,{N:String.fromCharCode(0),i:0,inc(T){return OT.i+=T,OT},str(T){let o=Buffer.byteLength(T);return Nn(o),OT.i+=eT.write(T,OT.i,o,"utf8"),OT},i16(T){return Nn(2),eT.writeUInt16BE(T,OT.i),OT.i+=2,OT},i32(T,o){if(o||o===0)return eT.writeUInt32BE(T,o),OT;return Nn(4),eT.writeUInt32BE(T,OT.i),OT.i+=4,OT},z(T){return Nn(T),eT.fill(0,OT.i,OT.i+T),OT.i+=T,OT},raw(T){return eT=Buffer.concat([eT.subarray(0,OT.i),T]),OT.i=eT.length,OT},end(T=1){eT.writeUInt32BE(OT.i-T,T);let o=eT.subarray(0,OT.i);return OT.i=0,eT=Buffer.allocUnsafe(256),o}}),r=OT;function Nn(T){if(eT.length-OT.i<T){let o=eT,S=o.length;eT=Buffer.allocUnsafe(S+(S>>1)+T),o.copy(eT)}}function XM(){return OT.i=0,OT}var y$=k1,GM=1,fS=r().S().end(),O1=r().H().end(),YM=r().i32(8).i32(80877103).end(8),EM=Buffer.concat([r().E().str(r.N).i32(0).end(),fS]),HM=r().D().str("S").str(r.N).end(),iS=()=>{},zM=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),QM={83:"severity_local",86:"severity",67:"code",77:"message",68:"detail",72:"hint",80:"position",112:"internal_position",113:"internal_query",87:"where",115:"schema_name",116:"table_name",99:"column_name",100:"data type_name",110:"constraint_name",70:"file",76:"line",82:"routine"};function k1(T,o={},{onopen:S=iS,onend:f=iS,onclose:n=iS}={}){let{ssl:A,max:$,user:F,host:J,port:R,database:W,parsers:y,transform:_,onnotice:K,onnotify:H,onparameter:Y,max_pipeline:I,keep_alive:b,backoff:q,target_session_attrs:p}=T,G=Oo(),D=GM++,t={pid:null,secret:null},U=k$(ln,T.idle_timeout),v=k$(ln,T.max_lifetime),l=k$(N1,T.connect_timeout),E=null,TT,Z=new _S,oT=Buffer.alloc(0),MT=T.fetch_types,CT={},So={},No=Math.random().toString(36).slice(2),z=1,c=0,FT=0,ET=0,IT=0,fT=0,_T=0,BT=0,zT=null,KT=null,pT=!1,wT=null,Xo=null,iT=null,Po=null,jT=null,GT=null,Ko=null,Vo=null,B=null,uS=null,gT={queue:o.closed,idleTimer:U,connect(O){iT=O||!0,Z$()},terminate:aS,execute:eS,cancel:C1,end:ln,count:0,id:D};return o.closed&&o.closed.push(gT),gT;async function L1(){let O;try{O=T.socket?await Promise.resolve(T.socket(T)):new R1.Socket}catch(w){GS(w);return}return O.on("error",GS),O.on("close",c$),O.on("drain",v$),O}async function C1({pid:O,secret:w},P,JT){try{TT=r().i32(16).i32(80877102).i32(O).i32(w).end(16),await q$(),E.once("error",JT),E.once("close",P)}catch(DT){JT(DT)}}function eS(O){if(pT)return qf(O,LT.connection("CONNECTION_DESTROYED",T));if(O.cancelled)return;try{return O.state=t,B?G.push(O):(B=O,B.active=!0),m1(O),cT(I1(O))&&!O.describeFirst&&!O.cursorFn&&G.length<I&&(!O.options.onexecute||O.options.onexecute(gT))}catch(w){return G.length===0&&cT(fS),Bo(w),!0}}function I1(O){if(O.parameters.length>=65534)throw LT.generic("MAX_PARAMETERS_EXCEEDED","Max number of parameters (65534) exceeded");return O.options.simple?r().Q().str(O.statement.string+r.N).end():O.describeFirst?Buffer.concat([h$(O),O1]):O.prepare?O.prepared?vf(O):Buffer.concat([h$(O),vf(O)]):j1(O)}function h$(O){return Buffer.concat([P$(O.statement.string,O.parameters,O.statement.types,O.statement.name),GW("S",O.statement.name)])}function vf(O){return Buffer.concat([KW(O.parameters,O.statement.types,O.statement.name,O.cursorName),O.cursorFn?p$("",O.cursorRows):EM])}function j1(O){return Buffer.concat([P$(O.statement.string,O.parameters,O.statement.types),HM,vf(O)])}function m1(O){let w=[],P=[],JT=n$(O,O.strings[0],O.args[0],w,P,T);!O.tagged&&O.args.forEach((DT)=>jn(DT,w,P,T)),O.prepare=T.prepare&&("prepare"in O.options?O.options.prepare:!0),O.string=JT,O.signature=O.prepare&&P+JT,O.onlyDescribe&&delete So[O.signature],O.parameters=O.parameters||w,O.prepared=O.prepare&&O.signature in So,O.describeFirst=O.onlyDescribe||w.length&&!O.prepared,O.statement=O.prepared?So[O.signature]:{string:JT,types:P,name:O.prepare?No+z++:""},typeof T.debug==="function"&&T.debug(D,JT,w,P)}function cT(O,w){if(GT=GT?Buffer.concat([GT,O]):Buffer.from(O),w||GT.length>=1024)return b$(w);return KT===null&&(KT=setImmediate(b$)),!0}function b$(O){let w=E.write(GT,O);return KT!==null&&clearImmediate(KT),GT=KT=null,w}function N1(){Bo(LT.connection("CONNECT_TIMEOUT",T,E)),E.destroy()}async function x$(){if(cT(YM),!await new Promise((w)=>E.once("data",(P)=>w(P[0]===83)))&&A==="prefer")return KS();E.removeAllListeners(),E=KM.connect({socket:E,servername:R1.isIP(E.host)?void 0:E.host,...A==="require"||A==="allow"||A==="prefer"?{rejectUnauthorized:!1}:A==="verify-full"?{}:typeof A==="object"?A:{}}),E.on("secureConnect",KS),E.on("error",GS),E.on("close",c$),E.on("drain",v$)}function v$(){!B&&S(gT)}function dn(O){if(wT){if(wT.push(O),FT-=O.length,FT>=0)return}oT=wT?Buffer.concat(wT,fT-FT):oT.length===0?O:Buffer.concat([oT,O],oT.length+O.length);while(oT.length>4){if(fT=oT.readUInt32BE(1),fT>=oT.length){FT=fT-oT.length,wT=[oT];break}try{h1(oT.subarray(0,fT+1))}catch(w){B&&(B.cursorFn||B.describeFirst)&&cT(fS),Bo(w)}oT=oT.subarray(fT+1),FT=0,wT=null}}async function q$(){if(pT=!1,CT={},E||(E=await L1()),!E)return;if(l.start(),T.socket)return A?x$():KS();if(E.on("connect",A?x$:KS),T.path)return E.connect(T.path);E.ssl=A,E.connect(R[ET],J[ET]),E.host=J[ET],E.port=R[ET],ET=(ET+1)%R.length}function Z$(){setTimeout(q$,c?c+_T-W1.now():0)}function KS(){try{So={},MT=T.fetch_types,No=Math.random().toString(36).slice(2),z=1,v.start(),E.on("data",dn),b&&E.setKeepAlive&&E.setKeepAlive(!0,1000*b);let O=EW();cT(O)}catch(O){GS(O)}}function GS(O){if(gT.queue===o.connecting&&T.host[IT+1])return;Bo(O);while(G.length)qf(G.shift(),O)}function Bo(O){jT&&(jT.destroy(O),jT=null),B&&qf(B,O),iT&&(qf(iT,O),iT=null)}function qf(O,w){"query"in w||"parameters"in w||Object.defineProperties(w,{stack:{value:w.stack+O.origin.replace(/.*\n/,`
|
|
17
|
-
`),enumerable:T.debug},query:{value:O.string,enumerable:T.debug},parameters:{value:O.parameters,enumerable:T.debug},args:{value:O.args,enumerable:T.debug},types:{value:O.statement&&O.statement.types,enumerable:T.debug}}),O.reject(w)}function ln(){return Po||(!gT.reserved&&f(gT),!gT.reserved&&!iT&&!B&&G.length===0?(aS(),new Promise((O)=>E&&E.readyState!=="closed"?E.once("close",O):O())):Po=new Promise((O)=>Ko=O))}function aS(){if(pT=!0,jT||B||iT||G.length)GS(LT.connection("CONNECTION_DESTROYED",T));if(clearImmediate(KT),E)E.removeListener("data",dn),E.removeListener("connect",KS),E.readyState==="open"&&E.end(r().X().end());Ko&&(Ko(),Po=Ko=null)}async function c$(O){if(oT=Buffer.alloc(0),FT=0,wT=null,clearImmediate(KT),E.removeListener("data",dn),E.removeListener("connect",KS),U.cancel(),v.cancel(),l.cancel(),E.removeAllListeners(),E=null,iT)return Z$();!O&&(B||G.length)&&GS(LT.connection("CONNECTION_CLOSED",T,E)),c=W1.now(),O&&T.shared.retries++,_T=(typeof q==="function"?q(T.shared.retries):q)*1000,n(gT,LT.connection("CONNECTION_CLOSED",T,E))}function h1(O,w=O[0]){(w===68?b1:w===100?WW:w===65?nW:w===83?x1:w===90?v1:w===67?q1:w===50?r$:w===49?Z1:w===116?c1:w===84?r1:w===82?P1:w===110?u1:w===75?e1:w===69?SW:w===115?AW:w===51?$W:w===71?FW:w===78?MW:w===72?JW:w===99?OW:w===73?kW:w===86?yW:w===118?_W:w===87?RW:wW)(O)}function b1(O){let w=7,P,JT,DT,dT=B.isRaw?new Array(B.statement.columns.length):{};for(let aT=0;aT<B.statement.columns.length;aT++)JT=B.statement.columns[aT],P=O.readInt32BE(w),w+=4,DT=P===-1?null:B.isRaw===!0?O.subarray(w,w+=P):JT.parser===void 0?O.toString("utf8",w,w+=P):JT.parser.array===!0?JT.parser(O.toString("utf8",w+1,w+=P)):JT.parser(O.toString("utf8",w,w+=P)),B.isRaw?dT[aT]=B.isRaw===!0?DT:_.value.from?_.value.from(DT,JT):DT:dT[JT.name]=_.value.from?_.value.from(DT,JT):DT;B.forEachFn?B.forEachFn(_.row.from?_.row.from(dT):dT,Z):Z[BT++]=_.row.from?_.row.from(dT):dT}function x1(O){let[w,P]=O.toString("utf8",5,O.length-1).split(r.N);if(CT[w]=P,T.parameters[w]!==P)T.parameters[w]=P,Y&&Y(w,P)}function v1(O){if(B&&B.options.simple&&B.resolve(Xo||Z),B=Xo=null,Z=new _S,l.cancel(),iT){if(p){if(!CT.in_hot_standby||!CT.default_transaction_read_only)return oW();else if(TW(p,CT))return aS()}if(MT)return iT===!0&&(iT=null),a1();iT!==!0&&eS(iT),T.shared.retries=IT=0,iT=null;return}while(G.length&&(B=G.shift())&&(B.active=!0,B.cancelled))k1(T).cancel(B.state,B.cancelled.resolve,B.cancelled.reject);if(B)return;gT.reserved?!gT.reserved.release&&O[5]===73?Po?aS():(gT.reserved=null,S(gT)):gT.reserved():Po?aS():S(gT)}function q1(O){BT=0;for(let w=O.length-1;w>0;w--){if(O[w]===32&&O[w+1]<58&&Z.count===null)Z.count=+O.toString("utf8",w+1,O.length-1);if(O[w-1]>=65){Z.command=O.toString("utf8",5,w),Z.state=t;break}}if(uS&&(uS(),uS=null),Z.command==="BEGIN"&&$!==1&&!gT.reserved)return Bo(LT.generic("UNSAFE_TRANSACTION","Only use sql.begin, sql.reserved or max: 1"));if(B.options.simple)return r$();if(B.cursorFn)Z.count&&B.cursorFn(Z),cT(fS);B.resolve(Z)}function Z1(){B.parsing=!1}function r$(){!Z.statement&&(Z.statement=B.statement),Z.columns=B.statement.columns}function c1(O){let w=O.readUInt16BE(5);for(let P=0;P<w;++P)!B.statement.types[P]&&(B.statement.types[P]=O.readUInt32BE(7+P*4));B.prepare&&(So[B.signature]=B.statement),B.describeFirst&&!B.onlyDescribe&&(cT(vf(B)),B.describeFirst=!1)}function r1(O){if(Z.command)Xo=Xo||[Z],Xo.push(Z=new _S),Z.count=null,B.statement.columns=null;let w=O.readUInt16BE(5),P=7,JT;B.statement.columns=Array(w);for(let DT=0;DT<w;++DT){JT=P;while(O[P++]!==0);let dT=O.readUInt32BE(P),aT=O.readUInt16BE(P+4),po=O.readUInt32BE(P+6);B.statement.columns[DT]={name:_.column.from?_.column.from(O.toString("utf8",JT,P-1)):O.toString("utf8",JT,P-1),parser:y[po],table:dT,number:aT,type:po},P+=18}if(Z.statement=B.statement,B.onlyDescribe)return B.resolve(B.statement),cT(fS)}async function P1(O,w=O.readUInt32BE(5)){(w===3?p1:w===5?i1:w===10?g1:w===11?d1:w===12?l1:w!==0?XW:iS)(O,w)}async function p1(){let O=await un();cT(r().p().str(O).z(1).end())}async function i1(O){let w="md5"+await M1(Buffer.concat([Buffer.from(await M1(await un()+F)),O.subarray(9)]));cT(r().p().str(w).z(1).end())}async function g1(){Vo=(await jf.randomBytes(18)).toString("base64"),r().p().str("SCRAM-SHA-256"+r.N);let O=r.i;cT(r.inc(4).str("n,,n=*,r="+Vo).i32(r.i-O-4,O).end())}async function d1(O){let w=O.toString("utf8",9).split(",").reduce((aT,po)=>(aT[po[0]]=po.slice(2),aT),{}),P=await jf.pbkdf2Sync(await un(),Buffer.from(w.s,"base64"),parseInt(w.i),32,"sha256"),JT=await hn(P,"Client Key"),DT="n=*,r="+Vo+",r="+w.r+",s="+w.s+",i="+w.i+",c=biws,r="+w.r;zT=(await hn(await hn(P,"Server Key"),DT)).toString("base64");let dT="c=biws,r="+w.r+",p="+UM(JT,Buffer.from(await hn(await DM(JT),DT))).toString("base64");cT(r().p().str(dT).end())}function l1(O){if(O.toString("utf8",9).split(r.N,1)[0].slice(2)===zT)return;Bo(LT.generic("SASL_SIGNATURE_MISMATCH","The server did not return the correct signature")),E.destroy()}function un(){return Promise.resolve(typeof T.pass==="function"?T.pass():T.pass)}function u1(){if(Z.statement=B.statement,Z.statement.columns=[],B.onlyDescribe)return B.resolve(B.statement),cT(fS)}function e1(O){t.pid=O.readUInt32BE(5),t.secret=O.readUInt32BE(9)}async function a1(){MT=!1,(await new wo([`
|
|
15
|
+
${y.trace}`:`No previous disposal trace for ${F} was found.`),o}let R=T.moleculeGraph.getRelationEntries({downstreamMoleculeKey:$.stringKey}).filter(([,{source:y}])=>y!==A).map(([y])=>BT(y));if(f)n.moleculeGraph.delete(A);n.moleculeGraph.set({upstreamMoleculeKey:J.stringKey,downstreamMoleculeKey:$.stringKey},{source:J.stringKey});let O={type:"molecule_transfer",key:$.key,from:R,to:[J.key]};if(OT(n)&&n.transactionMeta.phase==="building")n.transactionMeta.update.updates.push(O);return o}function fn(T,S,o){switch(S){case"newValue":{yF(T,o);break}case"oldValue":{$o(o,T.token);break}}}function An(T,S,o){switch(S){case"newValue":{$o(o,T.token);break}case"oldValue":{if(yF(T,o),T.subType==="atom")o.valueMap.set(T.token.key,T.value);break}}}function yF(T,S){let{family:o}=T.token;if(o){let f=S.families.get(o.key);if(f)g(S,f,BT(o.subKey))}}function wF(T,S,o){switch(S){case"newValue":fo(o,T.provenance,T.key);break;case"oldValue":Ao(o,T.key);break}}function KF(T,S,o){switch(S){case"newValue":Ao(o,T.key);break;case"oldValue":{let f=T.provenance.map(BT);fo(o,f,T.key);for(let[A,n]of T.values){let $=o.families.get(A);if($){g(o,$,T.key);let F=`${A}(${fT(T.key)})`;o.valueMap.set(F,n)}}}break}}function HF(T,S,o){switch(S){case"newValue":{let f=T.to.length===1?T.to[0]:T.to;Eo(o,f,T.key,"exclusive")}break;case"oldValue":{let f=T.from.length===1?T.from[0]:T.from;Eo(o,f,T.key,"exclusive")}break}}function df(T,S,o){let f=T==="newValue"?S.updates:[...S.updates].reverse();for(let A of f)switch(A.type){case"atom_update":case"selector_update":gf(T,A,o);break;case"state_creation":fn(A,T,o);break;case"state_disposal":An(A,T,o);break;case"molecule_creation":wF(A,T,o);break;case"molecule_disposal":KF(A,T,o);break;case"molecule_transfer":HF(A,T,o);break;case"transaction_update":df(T,A,o);break}}function XF(T,S,o){if(mT(o)&&T)o.transactionMeta.epoch.set(T,S)}function GF(T,S,o){if(!mT(o))return;let A=o.transactionMeta.actionContinuities.getRelatedKey(T);if(A!==void 0)o.transactionMeta.epoch.set(A,S)}var YF=(T,S)=>{let o=L(S),{parent:f}=o;if(f===null||!OT(o)||o.transactionMeta?.phase!=="building"){S.logger.warn("\uD83D\uDC1E","transaction","???","applyTransaction called outside of a transaction. This is probably a bug in AtomIO.");return}o.transactionMeta.phase="applying",o.transactionMeta.update.output=T,f.child=null,f.on.transactionApplying.next(o.transactionMeta);let{updates:A}=o.transactionMeta.update;if(S.logger.info("\uD83D\uDEC4","transaction",o.transactionMeta.update.key,`Applying transaction with ${A.length} updates:`,A),df("newValue",o.transactionMeta.update,f),mT(f))GF(o.transactionMeta.update.key,o.transactionMeta.update.epoch,f),nT({key:o.transactionMeta.update.key,type:"transaction"},S)?.subject.next(o.transactionMeta.update),S.logger.info("\uD83D\uDEEC","transaction",o.transactionMeta.update.key,"Finished applying transaction.");else if(OT(f))f.transactionMeta.update.updates.push(o.transactionMeta.update);f.on.transactionApplying.next(null)};function EF(T,S,o){if(!mT(o))return;let{epoch:A,actionContinuities:n}=o.transactionMeta;if(n.set(T,S),!A.has(T))A.set(T,-1)}function zF(T){return{store:T}}function RT(T,...S){let o,f,A;if(S.length===1)o=S[0];else f=S[0],A=S[1],o=g(T,f,A);if("counterfeit"in o&&"family"in o){f=T.families.get(o.family.key);let n=o.family.subKey,$=T.disposalTraces.buffer.find((F)=>F?.key===n);switch(T.logger.error("\u274C",o.type,o.key,`could not be retrieved because it was not found in the store "${T.config.name}".`,$?`This state was previously disposed:
|
|
16
|
+
${$.trace}`:"No previous disposal trace was found."),f.type){case"atom_family":case"mutable_atom_family":return T.defaults.get(f.key);case"selector_family":case"readonly_selector_family":{if(T.defaults.has(f.key))return T.defaults.get(o.family.key);let F=nT(f,T).default(n);return T.defaults.set(f.key,F),F}}}return PS(nT(o,T),T)}class hT{a;b;cardinality;relations=new Map;contents=new Map;isAType;isBType;isContent;makeContentKey=(T,S)=>`${T}:${S}`;warn;getRelatedKeys(T){return this.relations.get(T)}addRelation(T,S){let o=this.relations.get(T),f=this.relations.get(S);if(o)o.add(S);else o=new Set([S]),this.relations.set(T,o);if(f)f.add(T);else f=new Set([T]),this.relations.set(S,f)}deleteRelation(T,S){let o=this.relations.get(T);if(o){if(o.delete(S),o.size===0)this.relations.delete(T);let f=this.relations.get(S);if(f){if(f.delete(T),f.size===0)this.relations.delete(S)}}}replaceRelationsUnsafely(T,S){this.relations.set(T,new Set(S));for(let o of S){let f=new Set().add(T);this.relations.set(o,f)}}replaceRelationsSafely(T,S){let o=this.relations.get(T),f=this.isAType?.(T)?T:void 0,A=f===void 0?T:void 0;if(o)for(let n of o){f??=n,A??=n;let $=this.relations.get(n);if($){if($.size===1)this.relations.delete(n);else $.delete(T);this.contents.delete(this.makeContentKey(f,A))}}this.relations.set(T,new Set(S));for(let n of S){let $=this.relations.get(n);if($)$.add(T);else $=new Set().add(T),this.relations.set(n,$)}}getContentInternal(T){return this.contents.get(T)}setContent(T,S){this.contents.set(T,S)}deleteContent(T){this.contents.delete(T)}constructor(T,S){if(this.a=T.between[0],this.b=T.between[1],this.cardinality=T.cardinality,!S?.externalStore)this.relations=new Map(T.relations?.map(([o,f])=>[o,new Set(f)])),this.contents=new Map(T.contents);if(this.isAType=S?.isAType??null,this.isBType=S?.isBType??null,this.isContent=S?.isContent??null,S?.makeContentKey)this.makeContentKey=S.makeContentKey;if(S?.externalStore){let o=S.externalStore;if(this.has=(f,A)=>o.has(f,A),this.addRelation=(f,A)=>{o.addRelation(f,A)},this.deleteRelation=(f,A)=>{o.deleteRelation(f,A)},this.replaceRelationsSafely=(f,A)=>{o.replaceRelationsSafely(f,A)},this.replaceRelationsUnsafely=(f,A)=>{o.replaceRelationsUnsafely(f,A)},this.getRelatedKeys=(f)=>o.getRelatedKeys(f),o.getContent)this.getContentInternal=(f)=>{return o.getContent(f)},this.setContent=(f,A)=>{o.setContent(f,A)},this.deleteContent=(f)=>{o.deleteContent(f)};for(let[f,A]of T.relations??[]){let n=this.isAType?.(f)?f:void 0,$=n===void 0?f:void 0;for(let F of A)n??=F,$??=F,this.addRelation(n,$)}for(let[f,A]of T.contents??[])this.setContent(f,A)}if(S?.warn)this.warn=S.warn}toJSON(){return{between:[this.a,this.b],cardinality:this.cardinality,relations:[...this.relations.entries()].map(([T,S])=>[T,[...S]]),contents:[...this.contents.entries()]}}set(...T){let S,o,f;switch(T.length){case 1:{let A=T[0];S=A[this.a],o=A[this.b],f=void 0;break}case 2:{let A=T[0];if(typeof A==="string")[S,o]=T;else S=A[this.a],o=A[this.b],f=T[1];break}default:{S=T[0],o=T[1],f=T[2];break}}switch(this.cardinality){case"1:1":{let A=this.getRelatedKey(S);if(A&&A!==o)this.delete(S,A)}case"1:n":{let A=this.getRelatedKey(o);if(A&&A!==S)this.delete(A,o)}}if(f){let A=this.makeContentKey(S,o);this.setContent(A,f)}return this.addRelation(S,o),this}delete(T,S){S=typeof S==="string"?S:T[this.b];let o=typeof T==="string"?T:T[this.a];if(o===void 0&&typeof S==="string"){let f=this.getRelatedKeys(S);if(f)for(let A of f)this.delete(A,S)}if(typeof o==="string"&&S===void 0){let f=this.getRelatedKeys(o);if(f)for(let A of f)this.delete(o,A)}if(typeof o==="string"&&typeof S==="string"){this.deleteRelation(o,S);let f=this.makeContentKey(o,S);this.deleteContent(f)}return this}getRelatedKey(T){let S=this.getRelatedKeys(T);if(S){if(S.size>1)this.warn?.(`${S.size} related keys were found for key "${T}": (${[...S].map((f)=>`"${f}"`).join(", ")}). Only one related key was expected.`);let o;for(let f of S){o=f;break}return o}}replaceRelations(T,S,o){let f=!Array.isArray(S),A=f?Object.keys(S):S;if(o?.reckless)this.replaceRelationsUnsafely(T,A);else this.replaceRelationsSafely(T,A);if(f)for(let n of A){let $=this.makeContentKey(T,n),F=S[n];this.setContent($,F)}return this}getContent(T,S){let o=this.makeContentKey(T,S);return this.getContentInternal(o)}getRelationEntries(T){let S=T[this.a],o=T[this.b];if(S!==void 0&&o===void 0){let f=this.getRelatedKeys(S);if(f)return[...f].map((A)=>{return[A,this.getContent(S,A)]})}if(S===void 0&&o!==void 0){let f=this.getRelatedKeys(o);if(f)return[...f].map((A)=>{return[A,this.getContent(A,o)]})}return[]}has(T,S){if(S)return this.getRelatedKeys(T)?.has(S)??!1;return this.relations.has(T)}}class _S extends Map{source;deleted=new Set;constructor(T){super();this.source=T}get(T){if(super.has(T))return super.get(T);if(!this.deleted.has(T)&&this.source.has(T))return this.source.get(T);return}set(T,S){return this.deleted.delete(T),super.set(T,S)}hasOwn(T){return super.has(T)}has(T){return!this.deleted.has(T)&&(super.has(T)||this.source.has(T))}delete(T){return this.deleted.add(T),super.delete(T)}}var QF=(T,S,o,f)=>{let A=L(o),n={parent:A,child:null,on:A.on,loggers:A.loggers,logger:A.logger,config:A.config,atoms:new _S(A.atoms),atomsThatAreDefault:new Set(A.atomsThatAreDefault),families:new _S(A.families),joins:new _S(A.joins),operation:{open:!1},readonlySelectors:new _S(A.readonlySelectors),timelines:new _S(A.timelines),timelineTopics:new hT(A.timelineTopics.toJSON()),trackers:new Map,transactions:new _S(A.transactions),selectorAtoms:new hT(A.selectorAtoms.toJSON()),selectorGraph:new hT(A.selectorGraph.toJSON(),{makeContentKey:(...R)=>R.sort().join(":")}),selectors:new _S(A.selectors),valueMap:new _S(A.valueMap),defaults:A.defaults,disposalTraces:o.disposalTraces.copy(),molecules:new _S(A.molecules),moleculeGraph:new hT(A.moleculeGraph.toJSON(),{makeContentKey:A.moleculeGraph.makeContentKey}),moleculeData:new hT(A.moleculeData.toJSON(),{makeContentKey:A.moleculeData.makeContentKey}),moleculeJoins:new hT(A.moleculeJoins.toJSON(),{makeContentKey:A.moleculeJoins.makeContentKey}),miscResources:new _S(A.miscResources)},$=DF(T,o),F={phase:"building",update:{type:"transaction_update",key:T,id:f,epoch:$===void 0?Number.NaN:$+1,updates:[],params:S,output:void 0},toolkit:{get:(...R)=>RT(J,...R),set:(...R)=>{VT(J,...R)},run:(R,O=Zf())=>zo(R,O,J),find:(R,O)=>g(J,R,O),seek:(R,O)=>cT(J,R,O),json:(R)=>NT(J,R),dispose:(...R)=>{$o(J,...R)},env:()=>zF(J)}},J=Object.assign(n,{transactionMeta:F});return A.child=J,o.logger.info("\uD83D\uDEEB","transaction",T,"Building transaction with params:",S),J};function nn(T,S){let o={key:T.key,type:"transaction",run:(n,$)=>{let F=QF(T.key,n,S,$);try{let J=L(S),{toolkit:R}=F.transactionMeta,O=T.do(R,...n);return YF(O,J),O}catch(J){throw SF(f),S.logger.warn("\uD83D\uDCA5","transaction",T.key,"caught:",J),J}},install:(n)=>nn(T,n),subject:new ST},f=L(S);f.transactions.set(o.key,o);let A=AS(o);return S.on.transactionCreation.next(A),A}function DF(T,S){let o=mT(S),f=o?S.transactionMeta.actionContinuities.getRelatedKey(T):void 0;return o&&f!==void 0?S.transactionMeta.epoch.get(f):void 0}function $f(T){return nn(T,s.STORE)}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 hT({between:["selectorKey","atomKey"],cardinality:"n:n"});selectorGraph=new hT({between:["upstreamSelectorKey","downstreamSelectorKey"],cardinality:"n:n"},{makeContentKey:(...T)=>T.sort().join(":")});trackers=new Map;families=new Map;joins=new Map;transactions=new Map;transactionMeta={epoch:new Map,actionContinuities:new hT({between:["continuity","action"],cardinality:"1:n"})};timelines=new Map;timelineTopics=new hT({between:["timelineKey","topicKey"],cardinality:"1:n"});disposalTraces=new cf(100);molecules=new Map;moleculeJoins=new hT({between:["moleculeKey","joinKey"],cardinality:"n:n"},{makeContentKey:(...T)=>T.sort().join(":")});moleculeGraph=new hT({between:["upstreamMoleculeKey","downstreamMoleculeKey"],cardinality:"n:n"},{makeContentKey:(...T)=>T.sort().join(":")});moleculeData=new hT({between:["moleculeKey","stateFamilyKey"],cardinality:"n:n"},{makeContentKey:(...T)=>T.sort().join(":")});miscResources=new Map;on={atomCreation:new ST,atomDisposal:new ST,selectorCreation:new ST,selectorDisposal:new ST,timelineCreation:new ST,transactionCreation:new ST,transactionApplying:new eA(null),operationClose:new ST,moleculeCreation:new ST,moleculeDisposal:new ST};operation={open:!1};config={name:"IMPLICIT_STORE",lifespan:"ephemeral"};loggers=[new Tn("warn",(T,S,o)=>!o.includes("\uD83D\uDD0D"))];logger={error:(...T)=>{for(let S of this.loggers)S.error(...T)},info:(...T)=>{for(let S of this.loggers)S.info(...T)},warn:(...T)=>{for(let S of this.loggers)S.warn(...T)}};constructor(T,S=null){if(this.config={...S?.config,...T},S!==null){if(this.valueMap=new Map(S?.valueMap),this.operation={...S?.operation},mT(S))this.transactionMeta={epoch:new Map(S?.transactionMeta.epoch),actionContinuities:new hT(S?.transactionMeta.actionContinuities.toJSON())};for(let[,f]of S.families){if(f.internalRoles?.includes("mutable")||f.internalRoles?.includes("join"))continue;f.install(this)}let o=new Set;for(let[,f]of S.atoms){if(o.has(f.key))continue;if(f.install(this),f.type==="mutable_atom"){let A=NT(S,f),n=bS(f);o.add(A.key),o.add(n.key)}}for(let[,f]of S.readonlySelectors)f.install(this);for(let[,f]of S.selectors){if(o.has(f.key))continue;f.install(this)}for(let[,f]of S.transactions)f.install(this);for(let[,f]of S.timelines)f.install(this)}}}var s={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 nT(T,S){let o,f=S;while(f!==null){switch(T.type){case"atom":case"mutable_atom":o=f.atoms.get(T.key);break;case"selector":o=f.selectors.get(T.key);break;case"readonly_selector":o=f.readonlySelectors.get(T.key);break;case"atom_family":case"mutable_atom_family":case"selector_family":case"readonly_selector_family":o=f.families.get(T.key);break;case"timeline":o=f.timelines.get(T.key);break;case"transaction":o=f.transactions.get(T.key);break}if(o)return o;f=f.child}throw new no(T,S)}function VF(T,S,o){let f=T.families.get(S.key);if(f===void 0)throw new no(S,T);let A=f(o),n=L(T);if(A.family){if(mT(n))switch(A.type){case"atom":case"mutable_atom":T.on.atomCreation.next(A);break;case"selector":case"readonly_selector":T.on.selectorCreation.next(A);break}else if(OT(n)&&n.on.transactionApplying.state===null)n.transactionMeta.update.updates.push({type:"state_creation",token:A})}return A}function cT(T,S,o){let f=fT(o),A=`${S.key}(${f})`,n=L(T),$;switch(S.type){case"atom_family":case"mutable_atom_family":$=n.atoms.get(A);break;case"selector_family":$=n.selectors.get(A);break;case"readonly_selector_family":$=n.readonlySelectors.get(A);break}if($)return AS($);return $}function g(T,S,o){let f=cT(T,S,o);if(f)return f;let A=fT(o),n=T.molecules.get(A);if(!n&&T.config.lifespan==="immortal"){let $=l$(S,o);return T.logger.error("\u274C",$.type,$.key,`was not found in store "${T.config.name}"; returned a counterfeit token.`),$}if(f=VF(T,S,o),n)L(T).moleculeData.set(A,S.key);return f}function $o(T,...S){let o;if(S.length===1)o=S[0];else{let f=S[0],A=S[1];o=g(T,f,A)}try{nT(o,T)}catch(f){T.logger.error("\u274C",o.type,o.key,`could not be disposed because it was not found in the store "${T.config.name}".`);return}switch(o.type){case"atom":case"mutable_atom":$n(o,T);break;case"selector":case"readonly_selector":BF(o,T);break}}var lf=(T,S)=>L(S).atoms.has(T),IO=(T,S)=>L(S).selectors.has(T),jO=(T,S)=>L(S).readonlySelectors.has(T),tF=(T,S)=>lf(T,S)||IO(T,S)||jO(T,S);var uf=(T,S)=>{return L(S).selectorGraph.getRelationEntries({downstreamSelectorKey:T}).filter(([f,{source:A}])=>A!==T).map(([f,{source:A}])=>A).filter((f)=>tF(f,S))};var Fn=(T,S,o)=>{let f=[],A=uf(T,o);while(A.length>0){let n=A.shift();if(S.has(n))continue;if(S.add(n),!lf(n,o))A.push(...uf(n,o));else if(!f.includes(n))f.push(n)}return f},LF=(T,S)=>{let o=T.key,f=uf(o,S),A=new Set;return f.flatMap((n)=>lf(n,S)?n:Fn(n,A,S))};var CF=(T,S,o,f)=>{let A=L(f);if(S.type==="atom"||S.type==="mutable_atom")A.selectorAtoms.set({selectorKey:T,atomKey:S.key}),f.logger.info("\uD83D\uDD0D","selector",T,`discovers root atom "${S.key}"`);else{let n=Fn(S.key,o,f);f.logger.info("\uD83D\uDD0D","selector",T,`discovers root atoms: [ ${n.map(($)=>`"${$}"`).join(", ")} ]`);for(let $ of n)A.selectorAtoms=A.selectorAtoms.set({selectorKey:T,atomKey:$})}o.add(S.key)};var ef=(T,S,o)=>({get:(...f)=>{let A=L(o),n;if(f.length===2){let[J,R]=f;n=g(o,J,R)}else[n]=f;let $=nT(n,o),F=PS($,o);return o.logger.info("\uD83D\uDD0C","selector",T,`registers dependency ( "${n.key}" =`,F,")"),A.selectorGraph.set({upstreamSelectorKey:n.key,downstreamSelectorKey:T},{source:n.key}),CF(T,n,S,o),F},set:(...f)=>{let A,n;if(f.length===2)A=f[0],n=f[1];else{let J=f[0],R=f[1];n=f[2],A=g(o,J,R)}let $=L(o),F=nT(A,$);Pf(F,n,$)},find:(f,A)=>g(o,f,A),seek:(f,A)=>cT(o,f,A),json:(f)=>NT(o,f)});var of=(T,S,o)=>{let f=L(T),A=new ST,n=new Set,{get:$,find:F,seek:J,json:R}=ef(S.key,n,f),O=()=>{let E=S.get({get:$,find:F,seek:J,json:R});return WS(S.key,E,A,L(T)),n.clear(),E},k={...S,subject:A,install:(E)=>of(E,S,o),get:O,type:"readonly_selector",...o&&{family:o}};f.readonlySelectors.set(S.key,k);let y=O();T.logger.info("\u2728",k.type,k.key,"=",y);let H={key:S.key,type:"readonly_selector"};if(o)H.family=o;return H};var Ff=(T,S,o)=>{let f=L(T),A=new ST,n=new Set,$=ef(S.key,n,f),{find:F,get:J,seek:R,json:O}=$,k={find:F,get:J,seek:R,json:O},y=(b=S.get,q=L(T))=>{let P=b(k);return WS(S.key,P,A,q),n.clear(),P},E={...S,subject:A,install:(b)=>Ff(b,S,o),get:y,set:(b)=>{let q=L(T),P=y(S.get,q),X=pf(b)(P);if(T.logger.info("\uD83D\uDCDD","selector",S.key,"set (",P,"->",X,")"),WS(S.key,X,A,q),Qo(q,S.key),mT(q))A.next({newValue:X,oldValue:P});S.set($,X)},type:"selector",...o&&{family:o}};f.selectors.set(S.key,E);let G=y();T.logger.info("\u2728",E.type,E.key,"=",G);let I={key:S.key,type:"selector"};if(o)I.family=o;return I};function XS(T,S){if("set"in S){let A=Ff(T,S,void 0);return T.on.selectorCreation.next(A),A}let f=of(T,S,void 0);return T.on.selectorCreation.next(f),f}function BF(T,S){let o=L(S),{key:f}=T,A=nT(T,o);if(!A.family)S.logger.error("\u274C","selector",f,"Standalone selectors cannot be disposed.");else{if(o.molecules.get(A.family.subKey))o.moleculeData.delete(A.family.subKey,A.family.key);switch(T.type){case"selector":{o.selectors.delete(f);let $=nT({key:A.family.key,type:"selector_family"},S)}break;case"readonly_selector":o.readonlySelectors.delete(f),nT({key:A.family.key,type:"readonly_selector_family"},S).subject.next({type:"state_disposal",subType:"selector",token:T});break}if(o.valueMap.delete(f),o.selectorAtoms.delete(f),o.selectorGraph.delete(f),S.logger.info("\uD83D\uDD25",T.type,f,"deleted"),OT(o)&&o.transactionMeta.phase==="building")o.transactionMeta.update.updates.push({type:"state_disposal",subType:"selector",token:T});else S.on.selectorDisposal.next(T)}}function Af(T,S,o){let f={key:S.key,type:"selector_family"},A=T.families.get(S.key);if(A)T.logger.error("\u2757","selector_family",S.key,`Overwriting an existing ${LS(A)} "${A.key}" in store "${T.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let n=new ST,F=Object.assign((J)=>{let R=fT(J),O={key:S.key,subKey:R},k=`${S.key}(${R})`,y=L(T),H=Ff(y,{key:k,get:S.get(J),set:S.set(J)},O);return n.next({type:"state_creation",token:H}),H},f,{internalRoles:o,subject:n,install:(J)=>Af(J,S),default:(J)=>{return S.get(J)({get:(...O)=>RT(T,...O),find:(O,k)=>g(T,O,k),seek:(O,k)=>cT(T,O,k),json:(O)=>NT(T,O)})}});return T.families.set(S.key,F),f}function IF(T,S,o=s.STORE){let f=Af(o,{key:`${T.key}:JSON`,get:(n)=>({get:$})=>{let F=$(T,n);return S.toJson(F)},set:(n)=>({set:$},F)=>{$(T,n,S.fromJson(F))}},["mutable","json"]);return nT(T,o).subject.subscribe(`store=${o.config.name}::json-selector-family`,(n)=>{if(n.token.family)cT(o,f,BT(n.token.family.subKey))}),f}var BT=(T)=>JSON.parse(T),fT=(T)=>JSON.stringify(T),fK=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];var jF=(T,S)=>{let o=L(S);if(o.operation.open)return o.operation.prev.get(T.key);return o.valueMap.get(T.key)};var On=(T,S)=>{let o=L(S);return LF(T,S).map((A)=>{let n=o.atoms.get(A);if(n===void 0)throw new Error(`Atom "${A}", a dependency of selector "${T.key}", not found in store "${S.config.name}".`);return n.subject.subscribe(`${T.type}:${T.key}`,($)=>{S.logger.info("\uD83D\uDCE2",T.type,T.key,"root",A,"went",$.oldValue,"->",$.newValue);let F=jF(T,o),J=PS(T,o);S.logger.info("\u2728",T.type,T.key,"went",F,"->",J),T.subject.next({newValue:J,oldValue:F})})})};function lT(T,S,o,f){function A(k){if(f.operation.open){let y=f.on.operationClose.subscribe(`state subscription ${o}`,()=>{y(),S(k)})}else S(k)}let n=nT(T,f);f.logger.info("\uD83D\uDC40",n.type,n.key,`Adding subscription "${o}"`);let $=n.type==="selector"||n.type==="readonly_selector",F=null,J=A;if($)F=On(n,f),J=(k)=>{if(F)F.length=0,F.push(...On(n,f));A(k)};let R=n.subject.subscribe(o,J);return()=>{if(f.logger.info("\uD83D\uDE48",n.type,n.key,`Removing subscription "${o}"`),R(),F)for(let k of F)k()}}var Jn=(T,S,o,f)=>{let A=nT(T,f);f.logger.info("\uD83D\uDC40","timeline",T.key,`Adding subscription "${o}"`);let n=A.subject.subscribe(o,S);return()=>{f.logger.info("\uD83D\uDE48","timeline",T.key,`Removing subscription "${o}" from timeline`),n()}};var Rn=(T,S,o,f)=>{let A=nT(T,f);f.logger.info("\uD83D\uDC40","transaction",T.key,`Adding subscription "${o}"`);let n=A.subject.subscribe(o,S);return()=>{f.logger.info("\uD83D\uDE48","transaction",T.key,`Removing subscription "${o}"`),n()}};class gS{Update;initializeState(T,S){let o=`*${T.key}`;S.atoms.delete(o),S.valueMap.delete(o);let f=T.family?{key:`*${T.family.key}`,subKey:T.family.subKey}:void 0,A=fS(S,{key:o,default:null},f);if(S.parent?.valueMap.has(o)){let n=S.parent.valueMap.get(o);S.valueMap.set(o,n)}return A}unsubscribeFromInnerValue;unsubscribeFromState;observeCore(T,S,o){let f=`tracker:${o.config.name}:${OT(o)?o.transactionMeta.update.key:"main"}:${T.key}`,A=RT(o,T);this.unsubscribeFromInnerValue=A.subscribe(f,(n)=>{VT(o,S,n)}),this.unsubscribeFromState=lT(T,(n)=>{if(n.newValue!==n.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=n.newValue.subscribe(f,($)=>{VT(o,S,$)})},f,o)}updateCore(T,S,o){let f=`tracker:${o.config.name}:${OT(o)?o.transactionMeta.update.key:"main"}:${T.key}`;lT(S,({newValue:A,oldValue:n})=>{let $=o.timelineTopics.getRelatedKey(S.key);if($){if(o.timelines.get($)?.timeTraveling){let R=Jn({key:$,type:"timeline"},(O)=>{R(),VT(o,T,(k)=>{if(O==="redo"&&A)k.do(A);else if(O==="undo"&&n)k.undo(n);return k})},f,o);return}}let F=o.on.operationClose.subscribe(f,()=>{F();let J=RT(o,T),R=A===null?-1:J.getUpdateNumber(A),O=R-J.cacheUpdateNumber;if(A&&O===1)VT(o,T,(k)=>(k.do(A),k));else o.logger.info("\u274C","mutable_atom",T.key,`could not be updated. Expected update number ${J.cacheUpdateNumber+1}, but got ${R}`)})},f,o)}mutableState;latestUpdateState;dispose;constructor(T,S){this.mutableState=T;let o=L(S);this.latestUpdateState=this.initializeState(T,o),this.observeCore(T,this.latestUpdateState,o),this.updateCore(T,this.latestUpdateState,o),o.trackers.set(T.key,this),this.dispose=()=>{this.unsubscribeFromInnerValue(),this.unsubscribeFromState(),o.trackers.delete(T.key)}}}function Jf(T,S,o){T.logger.info("\uD83D\uDD28","atom",S.key,`creating in store "${T.config.name}"`);let f=L(T),A=f.atoms.get(S.key);if(A&&A.type==="mutable_atom")return T.logger.error("\u274C","atom",S.key,"Tried to create atom, but it already exists in the store."),AS(A);let n=new ST,$={...S,type:"mutable_atom",install:(R)=>{return R.logger.info("\uD83D\uDEE0\uFE0F","atom",S.key,`installing in store "${R.config.name}"`),Jf(R,S,o)},subject:n};if(o)$.family=o;let F=S.default();f.atoms.set($.key,$),sf(S.key,T),WS(S.key,F,n,f);let J=AS($);if(S.effects){let R=0,O=[];for(let k of S.effects){let y=k({setSelf:(H)=>{VT(T,J,H)},onSet:(H)=>lT(J,H,`effect[${R}]`,T)});if(y)O.push(y);++R}$.cleanup=()=>{for(let k of O)k()}}if(new gS(J,T),!o)i$(J,S,T);return J}class Mn{Update;latestUpdateAtoms;mutableAtoms;constructor(T,S){let o=tS(S,{key:`*${T.key}`,default:null},["mutable","updates"]);this.latestUpdateAtoms=nT(o,S),this.mutableAtoms=T,this.mutableAtoms.subject.subscribe(`store=${S.config.name}::tracker-atom-family`,(f)=>{if(f.token.family){let A=BT(f.token.family.subKey);cT(S,this.latestUpdateAtoms,A),new gS(f.token,S)}}),this.latestUpdateAtoms.subject.subscribe(`store=${S.config.name}::tracker-atom-family`,(f)=>{if(f.token.family){let A=BT(f.token.family.subKey),n=cT(S,this.mutableAtoms,A);if(n)new gS(n,S)}})}}function Sf(T,S,o){let f={key:S.key,type:"mutable_atom_family"},A=T.families.get(S.key);if(A)T.logger.error("\u2757","mutable_atom_family",S.key,`Overwriting an existing ${LS(A)} "${A.key}" in store "${T.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let n=new ST,F=Object.assign((J)=>{let R=fT(J),O={key:S.key,subKey:R},k=`${S.key}(${R})`,y=L(T),H={key:k,default:()=>S.default(J),toJson:S.toJson,fromJson:S.fromJson,mutable:!0};if(S.effects)H.effects=S.effects(J);let E=Jf(y,H,O);return n.next({type:"state_creation",token:E}),E},f,{subject:n,install:(J)=>Sf(J,S),toJson:S.toJson,fromJson:S.fromJson,internalRoles:o});return T.families.set(S.key,F),IF(F,S,T),new Mn(F,T),f}var Wn=(T,S)=>{let o=L(S),f=`${T.key}:JSON`;return o.families.get(f)};var NT=(T,S)=>{if(S.family){let f=L(T),n={key:`${S.family.key}:JSON`,type:"selector_family"},$=nT(n,f),F=JSON.parse(S.family.subKey);return g(T,$,F)}return{type:"selector",key:`${S.key}:JSON`}};var bS=(T)=>{let o={type:"atom",key:`*${T.key}`};if(T.family)o.family={key:`*${T.family.key}`,subKey:T.family.subKey};return o};function RF(T){return typeof T==="object"&&T!==null&&"do"in T&&"undo"in T&&"subscribe"in T}function nf(T,S,o){let f=S.valueMap.get(T.key),A=o.valueMap.get(T.key);if(f===A){if(f===void 0)return typeof T.default==="function"?T.default():T.default;S.logger.info("\uD83D\uDCC3","atom",T.key,"copying");let n=T.toJson(f),$=T.fromJson(n);return o.valueMap.set(T.key,$),new gS(T,S),$}return A}function WS(T,S,o,f){let A=f.valueMap.get(T);if(A instanceof Tf)A.use(S);if(S instanceof Promise){let n=new Tf(S);return f.valueMap.set(T,n),n.then(($)=>{WS(T,$,o,f),o.next({newValue:$,oldValue:n})}).catch(($)=>{f.logger.error("\uD83D\uDCA5","state",T,"rejected:",$)}),n}return f.valueMap.set(T,S),S}var oF=(T,S)=>{let o=S.valueMap.get(T.key);if(T.type==="mutable_atom"&&OT(S)){let{parent:f}=S;o=nf(T,f,S)}return o},FF=(T,S)=>{let o=S.valueMap.get(T);if(o instanceof Tf){let f=o,A=S.selectors.get(T)??S.readonlySelectors.get(T);if(A)f.use(A.get());return}if(S.operation.open)S.operation.prev.set(T,o);S.valueMap.delete(T),S.logger.info("\uD83D\uDDD1","state",T,"evicted")};var MF=(T,S)=>{return L(S).atomsThatAreDefault.has(T)},sf=(T,S)=>{let o=L(S);o.atomsThatAreDefault=new Set(o.atomsThatAreDefault).add(T)},WF=(T,S)=>{let o=L(S);o.atomsThatAreDefault=new Set(L(S).atomsThatAreDefault),o.atomsThatAreDefault.delete(T)};function fS(T,S,o){T.logger.info("\uD83D\uDD28","atom",S.key,`creating in store "${T.config.name}"`);let f=L(T),A=f.atoms.get(S.key);if(A&&A.type==="atom")return T.logger.error("\u274C","atom",S.key,"Tried to create atom, but it already exists in the store."),AS(A);let n=new ST,$={...S,type:"atom",install:(R)=>{return R.logger.info("\uD83D\uDEE0\uFE0F","atom",S.key,`installing in store "${R.config.name}"`),fS(R,S,o)},subject:n};if(o)$.family=o;let F=S.default;if(S.default instanceof Function)F=S.default();f.atoms.set($.key,$),sf(S.key,T),WS(S.key,F,n,f);let J=AS($);if(S.effects){let R=0,O=[];for(let k of S.effects){let y=k({setSelf:(H)=>{VT(T,J,H)},onSet:(H)=>lT(J,H,`effect[${R}]`,T)});if(y)O.push(y);++R}$.cleanup=()=>{for(let k of O)k()}}return J}function u$(T,S){if("mutable"in S){let A=Jf(T,S,void 0);return T.on.atomCreation.next(A),A}let f=fS(T,S,void 0);return T.on.atomCreation.next(f),f}function $n(T,S){let o=L(S),{key:f,family:A}=T,n=nT(T,o);if(!A)S.logger.error("\u274C","atom",f,"Standalone atoms cannot be disposed.");else{n.cleanup?.();let $=S.valueMap.get(n.key),F=nT({key:A.key,type:"atom_family"},S),J={type:"state_disposal",subType:"atom",token:T,value:$};F.subject.next(J);let R=OT(o);if(o.atoms.delete(f),o.valueMap.delete(f),o.selectorAtoms.delete(f),o.atomsThatAreDefault.delete(f),S.timelineTopics.delete(f),T.type==="mutable_atom"){let O=bS(T);$n(O,S),S.trackers.delete(f)}if(S.logger.info("\uD83D\uDD25","atom",f,"deleted"),R&&o.transactionMeta.phase==="building"){let O=o.transactionMeta.update.updates.at(-1);if(!(O?.type==="molecule_disposal"&&O.values.some(([H])=>H===n.family?.key)))o.transactionMeta.update.updates.push(J)}else S.on.atomDisposal.next(T)}}var _n=(T)=>{let S=fS(T,{key:"\uD83D\uDD0D Atom Token Index (Internal)",default:()=>{let o=new Map;for(let[f,A]of T.atoms)if(!f.includes("\uD83D\uDD0D")){let n=AS(A);if(A.family){let $=o.get(A.family.key);if(!$||!("familyMembers"in $))$={key:A.family.key,familyMembers:new Map},o.set(A.family.key,$);$.familyMembers.set(A.family.subKey,n)}else o.set(f,n)}return o},effects:[({setSelf:o})=>{T.on.atomCreation.subscribe("introspection",(f)=>{if(f.key.includes("\uD83D\uDD0D"))return;o((A)=>{if(f.family){let{key:n,subKey:$}=f.family,F=A.get(n);if(F===void 0||!("familyMembers"in F))F={key:n,familyMembers:new Map},A.set(n,F);F.familyMembers.set($,f)}else A.set(f.key,f);return A})}),T.on.atomDisposal.subscribe("introspection",(f)=>{o((A)=>{if(f.family){let{key:n,subKey:$}=f.family,F=A.get(n);if(F&&"familyMembers"in F){if(F.familyMembers.delete($),F.familyMembers.size===0)A.delete(n)}}else A.delete(f.key);return A})})}]},void 0);return XS(T,{key:"\uD83D\uDD0D Atom Token Index",get:({get:o})=>o(S)})};var kn=(T)=>{let S=fS(T,{key:"\uD83D\uDD0D Selector Token Index (Internal)",default:()=>{let o=new Map;for(let f of[T.readonlySelectors,T.selectors])for(let[A,n]of f)if(!A.includes("\uD83D\uDD0D")){let $=AS(n);if(n.family){let F=o.get(n.family.key);if(!F||!("familyMembers"in F))F={key:n.family.key,familyMembers:new Map},o.set(n.family.key,F);F.familyMembers.set(n.family.subKey,$)}else o.set(A,$)}return o},effects:[({setSelf:o})=>{T.on.selectorCreation.subscribe("introspection",(f)=>{if(f.key.includes("\uD83D\uDD0D"))return;o((A)=>{if(f.family){let{key:n,subKey:$}=f.family,F=A.get(n);if(F===void 0||!("familyMembers"in F))F={key:n,familyMembers:new Map},A.set(n,F);F.familyMembers.set($,f)}else A.set(f.key,f);return A})}),T.on.selectorDisposal.subscribe("introspection",(f)=>{o((A)=>{if(f.family){let{key:n,subKey:$}=f.family,F=A.get(n);if(F&&"familyMembers"in F){if(F.familyMembers.delete($),F.familyMembers.size===0)A.delete(n)}}else A.delete(f.key);return A})})}]},void 0);return XS(T,{key:"\uD83D\uDD0D Selector Token Index",get:({get:o})=>o(S)})};class af{supported;constructor(T){this.supported=T}refine(T){for(let[S,o]of Object.entries(this.supported))try{if(o(T)===!0&&o!==Boolean)return{type:S,data:T}}catch(f){try{if(T instanceof o)return{type:S,data:T}}catch(A){}}return null}}var yn=new af({number:(T)=>typeof T==="number",string:(T)=>typeof T==="string",boolean:(T)=>typeof T==="boolean",null:(T)=>T===null});function wn(T){if(!T)return!1;return Object.getPrototypeOf(T)===Object.prototype}var Kn=new af({object:wn,array:(T)=>Array.isArray(T)}),NO=new af({...yn.supported,...Kn.supported}),Do=(T)=>{if(T===void 0)return"undefined";let S=NO.refine(T);if(S)return S.type;return Object.getPrototypeOf(T).constructor.name};class NF{store;auditorCreatedAt=performance.now();statesCreatedAt=new Map;atomIndex;selectorIndex;disposed=!1;unsubscribeFromAtomCreation;unsubscribeFromAtomDisposal;unsubscribeFromSelectorCreation;unsubscribeFromSelectorDisposal;constructor(T=s.STORE){this.store=T;this.atomIndex=_n(this.store),this.selectorIndex=kn(this.store),this.unsubscribeFromAtomCreation=this.store.on.atomCreation.subscribe(`auditor-${this.auditorCreatedAt}`,({key:S})=>{this.statesCreatedAt.set(S,performance.now()-this.auditorCreatedAt)}),this.unsubscribeFromAtomDisposal=this.store.on.atomDisposal.subscribe(`auditor-${this.auditorCreatedAt}`,({key:S})=>{this.statesCreatedAt.delete(S)}),this.unsubscribeFromSelectorCreation=this.store.on.selectorCreation.subscribe(`auditor-${this.auditorCreatedAt}`,({key:S})=>{this.statesCreatedAt.set(S,performance.now()-this.auditorCreatedAt)}),this.unsubscribeFromSelectorDisposal=this.store.on.selectorDisposal.subscribe(`auditor-${this.auditorCreatedAt}`,({key:S})=>{this.statesCreatedAt.delete(S)})}static DEFAULT_LIST_RESOURCES_PARAM={atomFamilies:!0,selectorFamilies:!0};listResources(T=NF.DEFAULT_LIST_RESOURCES_PARAM){if(this.disposed)throw new Error("This Auditor has been disposed");let S=sA(this.atomIndex),o=sA(this.selectorIndex),f=[...S.values()].filter((F)=>("familyMembers"in F)),A=[...o.values()].filter((F)=>("familyMembers"in F)),n=performance.now(),$=[];if(T.atomFamilies)for(let F of f){let J=F.familyMembers.values();for(let R of J){let k=this.statesCreatedAt.get(R.key)??this.auditorCreatedAt,y=n-k;$.push([R,y])}}if(T.selectorFamilies)for(let F of A){let J=F.familyMembers.values();for(let R of J){let k=this.statesCreatedAt.get(R.key)??this.auditorCreatedAt,y=n-k;$.push([R,y])}}return $}[Symbol.dispose](){this.unsubscribeFromAtomCreation(),this.unsubscribeFromAtomDisposal(),this.unsubscribeFromSelectorCreation(),this.unsubscribeFromSelectorDisposal(),this.disposed=!0}}var Hn=(T,S)=>{let o=(f,A)=>{let $=((J,R)=>{let O=S(J,R);if(O)return O;return null})(f,A);if($?.jobComplete??$?.pathComplete)return $;let F=Array.isArray(A)?A.map((J,R)=>[R,J]):wn(A)?Object.entries(A):[];for(let[J,R]of F){let O=o([...f,J],R);if(O?.jobComplete)return O}return{}};o([],T)};function mO(T,S){return{summary:`${T<S?"+":"-"}${Math.abs(T-S)} (${T} \u2192 ${S})`}}function hO(T,S){return{summary:`${T.length<S.length?"+":"-"}${Math.abs(T.length-S.length)} ("${T}" \u2192 "${S}")`}}function bO(T,S){return{summary:`${T} \u2192 ${S}`}}function mF(T,S,o){let f="",A=[],n=[],$=[];return Hn(T,(F,J)=>{let R;for(R of F){let O=S[R];if(O===void 0)n.push([R,JSON.stringify(J)]);else{let k=o(J,O);if(k.summary!=="No Change")$.push([R,k])}}}),Hn(S,(F,J)=>{let R;for(R of F)if(T[R]===void 0)A.push([R,JSON.stringify(J)])}),f=`\uFF5E${$.length} \uFF0B${A.length} \uFF0D${n.length}`,{summary:f,added:A,removed:n,changed:$}}function xO(T,S,o){return mF(T,S,o)}class hF{leafRefinery;treeRefinery;leafDiffers;treeDiffers;constructor(T,S,o){this.leafRefinery=T,this.treeRefinery=S,this.leafDiffers={},this.treeDiffers={};for(let f of Object.keys(T.supported)){let A=o[f];this.leafDiffers[f]=A}for(let f of Object.keys(S.supported)){let A=o[f];this.treeDiffers[f]=A}}diff(T,S){if(T===S)return{summary:"No Change"};let o=this.leafRefinery.refine(T)??this.treeRefinery.refine(T),f=this.leafRefinery.refine(S)??this.treeRefinery.refine(S);if(o!==null&&f!==null){if(o.type===f.type){if(o.type in this.leafDiffers)return this.leafDiffers[o.type](o.data,f.data);if(o.type in this.treeDiffers)return this.treeDiffers[o.type](o.data,f.data,(F,J)=>this.diff(F,J))}}let A=Do(T),n=Do(S);if(A===n)return{summary:`${A} \u2192 ${n}`};return{summary:`Type change: ${A} \u2192 ${n}`}}}var wX=new hF(yn,Kn,{number:mO,string:hO,boolean:bO,null:()=>({summary:"No Change"}),object:mF,array:xO});class bT extends Set{mode="record";subject=new ST;cacheLimit=0;cache=[];cacheIdx=-1;cacheUpdateNumber=-1;constructor(T,S=0){super(T);if(T instanceof bT)this.parent=T,this.cacheUpdateNumber=T.cacheUpdateNumber;if(S)this.cacheLimit=S,this.cache=new Array(S),this.subscribe("auto cache",(o)=>{this.cacheIdx++,this.cacheIdx%=this.cacheLimit,this.cache[this.cacheIdx]=o})}toJSON(){return{members:[...this],cache:this.cache,cacheLimit:this.cacheLimit,cacheIdx:this.cacheIdx,cacheUpdateNumber:this.cacheUpdateNumber}}static fromJSON(T){let S=new bT(T.members,T.cacheLimit);return S.cache=T.cache,S.cacheIdx=T.cacheIdx,S.cacheUpdateNumber=T.cacheUpdateNumber,S}add(T){let S=super.add(T);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`add:${fT(T)}`);return S}clear(){let T=this.mode==="record"?[...this]:null;if(super.clear(),T)this.cacheUpdateNumber++,this.emit(`clear:${JSON.stringify(T)}`)}delete(T){let S=super.delete(T);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`del:${fT(T)}`);return S}parent;child=null;transactionUpdates=null;transaction(T){this.mode="transaction",this.transactionUpdates=[],this.child=new bT(this);let S=this.child._subscribe("transaction",(o)=>{this.transactionUpdates?.push(o)});try{if(T(this.child)){for(let f of this.transactionUpdates)this.doStep(f);this.cacheUpdateNumber++,this.emit(`tx:${this.transactionUpdates.join(";")}`)}}catch(o){throw console.warn("Did not apply transaction to SetRTX; this error was thrown:",o),o}finally{S(),this.child=null,this.transactionUpdates=null,this.mode="record"}}_subscribe(T,S){return this.subject.subscribe(T,S)}subscribe(T,S){return this.subject.subscribe(T,(o)=>{S(`${this.cacheUpdateNumber}=${o}`)})}emit(T){this.subject.next(T)}doStep(T){let S=T.indexOf(":"),o=T.substring(0,S),f=T.substring(S+1);switch(o){case"add":this.add(JSON.parse(f));break;case"clear":this.clear();break;case"del":this.delete(JSON.parse(f));break;case"tx":for(let A of f.split(";"))this.doStep(A)}}getUpdateNumber(T){let S=T.indexOf("=");return Number(T.substring(0,S))}do(T){let S=T.indexOf("="),o=Number(T.substring(0,S)),f=o-this.cacheUpdateNumber;if(f>0){if(f===1){this.mode="playback";let n=T.substring(S+1);return this.doStep(n),this.mode="record",this.cacheUpdateNumber=o,null}return this.cacheUpdateNumber+1}if(Math.abs(f)<this.cacheLimit){let n=this.cacheIdx+f;if(this.cache[n]===T)return null;this.mode="playback";let F=!1;while(!F){this.cacheIdx%=this.cacheLimit;let R=this.cache[this.cacheIdx];if(this.cacheIdx--,!R)return"OUT_OF_RANGE";this.undo(R),F=this.cacheIdx===n-1}let J=T.substring(S+1);return this.doStep(J),this.mode="record",this.cacheUpdateNumber=o,null}return"OUT_OF_RANGE"}undoStep(T){let S=T.indexOf(":"),o=T.substring(0,S),f=T.substring(S+1);switch(o){case"add":this.delete(JSON.parse(f));break;case"del":this.add(JSON.parse(f));break;case"clear":{let A=JSON.parse(f);for(let n of A)this.add(n);break}case"tx":{let A=f.split(";");for(let n=A.length-1;n>=0;n--)this.undoStep(A[n])}}}undo(T){let S=T.indexOf("=");if(Number(T.substring(0,S))===this.cacheUpdateNumber){this.mode="playback";let f=T.substring(S+1);return this.undoStep(f),this.mode="record",this.cacheUpdateNumber--,null}return this.cacheUpdateNumber}}function ET(T){return T[0].toUpperCase()+T.slice(1)}class Xn{toolkit;options;defaultContent;molecules=new Map;relations;states;core;transact(T,S){let o=this.toolkit;this.toolkit=T,S(this),this.toolkit=o}store;realm;[Symbol.dispose](){}constructor(T,S,o=s.STORE){this.store=o,this.realm=new Sn(o),this.options=T,this.defaultContent=S,this.store.miscResources.set(`join:${T.key}`,this),this.realm.allocate("root",T.key),this.toolkit={get:(...X)=>RT(o,...X),set:(...X)=>{VT(o,...X)},find:(...X)=>g(o,...X),seek:(...X)=>cT(o,...X),json:(X)=>NT(o,X)};let f=T.between[0],A=T.between[1],n=Sf(o,{key:`${T.key}/relatedKeys`,default:()=>new bT,mutable:!0,fromJson:(X)=>bT.fromJSON(X),toJson:(X)=>X.toJSON()},["join","relations"]);this.core={relatedKeysAtoms:n};let $=({get:X},D)=>X(n,D),F=({set:X},D,V)=>{if(!this.store.molecules.has(fT(D)))this.realm.allocate(T.key,D);X(n,D,(U)=>U.add(V)),X(n,V,(U)=>U.add(D))},J=({set:X},D,V)=>{X(n,D,(U)=>{return U.delete(V),U}),X(n,V,(U)=>{return U.delete(D),U})},R=(X,D,V)=>{let{find:U,get:v,set:l}=X,Y=U(n,D),a=v(Y);for(let Z of a){if(V.includes(Z))continue;l(n,Z,(WT)=>{return WT.delete(D),WT})}l(Y,(Z)=>{return Z.transaction((TT)=>{TT.clear();for(let WT of V){let CT=$(X,WT),oS=CT.has(D);if(this.relations.cardinality==="1:n"){let mS=[];for(let z of CT){if(z===D)continue;let c=$(X,z);if(c.delete(WT),c.size===0)mS.push(z)}if(!oS&&CT.size>0)CT.clear();for(let z of mS){let c=[WT,z].sort(),FT=`"${c[0]}:${c[1]}"`;this.molecules.delete(FT)}}if(!oS)CT.add(D);TT.add(WT)}return!0}),Z})},O=(X,D,V)=>{let{set:U}=X;U(n,D,(v)=>{return v.transaction((l)=>{for(let Y of V)l.add(Y);return!0}),v});for(let v of V)U(n,v,(l)=>{return l.add(D),l});return!0},k=(X,D,V)=>{let U=$(X,D);return V?U.has(V):U.size>0},y={getRelatedKeys:(X)=>$(this.toolkit,X),addRelation:(X,D)=>{this.store.moleculeJoins.set(X,T.key),this.store.moleculeJoins.set(D,T.key),F(this.toolkit,X,D)},deleteRelation:(X,D)=>{J(this.toolkit,X,D)},replaceRelationsSafely:(X,D)=>{R(this.toolkit,X,D)},replaceRelationsUnsafely:(X,D)=>{O(this.toolkit,X,D)},has:(X,D)=>k(this.toolkit,X,D)},H,E;if(S){E=tS(o,{key:`${T.key}/content`,default:S},["join","content"]);let X=({get:U},v)=>U(E,v),D=({set:U},v,l)=>{U(E,v,l)};H=Object.assign(y,{getContent:(U)=>{return X(this.toolkit,U)},setContent:(U,v)=>{D(this.toolkit,U,v)},deleteContent:(U)=>{this.realm.deallocate(U)}})}else H=y;let G=new hT(T,{externalStore:H,isAType:T.isAType,isBType:T.isBType,makeContentKey:(...X)=>{let[D,V]=X,U=X.sort(),v=`${U[0]}:${U[1]}`,l=o.molecules.get(fT(D)),Y=o.molecules.get(fT(V));if(!l)this.realm.allocate(T.key,D);if(!Y)this.realm.allocate(T.key,V);return this.realm.allocate(D,v,"all"),this.realm.claim(V,v),this.store.moleculeJoins.set(v,T.key),v}}),I=()=>hS(o,{key:`${T.key}/singleRelatedKey`,get:(X)=>({get:D})=>{let V=D(n,X);for(let U of V)return U;return null}},["join","keys"]),b=()=>{return hS(o,{key:`${T.key}/multipleRelatedKeys`,get:(X)=>({get:D})=>{let V=Wn(n,o);return D(V,X).members}},["join","keys"])},q=()=>hS(o,{key:`${T.key}/singleRelatedEntry`,get:(X)=>({get:D})=>{let V=D(n,X);for(let U of V){let v=G.isAType?.(X)?X:void 0,l=v===void 0?X:void 0;v??=U,l??=U;let Y=G.makeContentKey(v,l),a=D(E,Y);return[U,a]}return null}},["join","entries"]),P=()=>hS(o,{key:`${T.key}/multipleRelatedEntries`,get:(X)=>({get:D})=>{let V=Wn(n,o);return D(V,X).members.map((v)=>{let l=G.isAType?.(X)?X:void 0,Y=l===void 0?X:void 0;l??=v,Y??=v;let a=G.makeContentKey(l,Y),Z=D(E,a);return[v,Z]})}},["join","entries"]);switch(T.cardinality){case"1:1":{let X=I(),D=`${f}KeyOf${ET(A)}`,V=`${A}KeyOf${ET(f)}`,U={[D]:X,[V]:X},v;if(S){let l=q(),Y=`${f}EntryOf${ET(A)}`,a=`${A}EntryOf${ET(f)}`,Z={[Y]:l,[a]:l};v=Object.assign(U,Z)}else v=U;this.relations=G,this.states=v;break}case"1:n":{let X=I(),D=b(),V=`${f}KeyOf${ET(A)}`,U=`${A}KeysOf${ET(f)}`,v={[V]:X,[U]:D},l;if(S){let Y=q(),a=P(),Z=`${f}EntryOf${ET(A)}`,TT=`${A}EntriesOf${ET(f)}`,WT={[Z]:Y,[TT]:a};l=Object.assign(v,WT)}else l=v;this.relations=G,this.states=l;break}default:{let X=b(),D=`${f}KeysOf${ET(A)}`,V=`${A}KeysOf${ET(f)}`,U={[D]:X,[V]:X},v;if(S){let l=P(),Y=`${f}EntriesOf${ET(A)}`,a=`${A}EntriesOf${ET(f)}`,Z={[Y]:l,[a]:l};v=Object.assign(U,Z)}else v=U;this.relations=G,this.states=v}}}}function TA(T,S,o=s.STORE){return o.joins.set(T.key,new Xn(T,S,o)),{key:T.key,type:"join",a:T.between[0],b:T.between[1],cardinality:T.cardinality}}function Gn(T,S){let o=S.joins.get(T.key);if(o===void 0){let A=s.STORE.joins.get(T.key);if(A===void 0)throw new Error(`Join "${T.key}" not found in store "${S.config.name}"`);o=new Xn(A.options,A.defaultContent,S),S.joins.set(T.key,o)}return o}function Yn(T,S,o){let f=Gn(T,o),A;switch(T.cardinality){case"1:1":{let n=`${T.a}KeyOf${ET(T.b)}`,$=`${T.b}KeyOf${ET(T.a)}`;A={get[n](){let J=f.states[n];return g(o,J,S)},get[$](){let J=f.states[$];return g(o,J,S)}};let F=`${T.a}EntryOf${ET(T.b)}`;if(F in f.states){let J=`${T.b}EntryOf${ET(T.a)}`;Object.assign(A,{get[F](){let R=f.states[F];return g(o,R,S)},get[J](){let R=f.states[J];return g(o,R,S)}})}break}case"1:n":{let n=`${T.a}KeyOf${ET(T.b)}`,$=`${T.b}KeysOf${ET(T.a)}`;A={get[n](){let J=f.states[n];return g(o,J,S)},get[$](){let J=f.states[$];return g(o,J,S)}};let F=`${T.a}EntryOf${ET(T.b)}`;if(F in f.states){let J=`${T.b}EntriesOf${ET(T.a)}`;Object.assign(A,{get[F](){let R=f.states[F];return g(o,R,S)},get[J](){let R=f.states[J];return g(o,R,S)}})}break}case"n:n":{let n=`${T.a}KeysOf${ET(T.b)}`,$=`${T.b}KeysOf${ET(T.a)}`;A={get[n](){let J=f.states[n];return g(o,J,S)},get[$](){let J=f.states[$];return g(o,J,S)}};let F=`${T.a}EntriesOf${ET(T.b)}`;if(F in f.states){let J=`${T.b}EntriesOf${ET(T.a)}`;Object.assign(A,{get[F](){let R=f.states[F];return g(o,R,S)},get[J](){let R=f.states[J];return g(o,R,S)}})}}}return A}function SA(T,S,o){let f=Gn(T,o),A=L(o);if(OT(A)){let{toolkit:n}=A.transactionMeta;f.transact(n,({relations:$})=>{S($)})}else S(f.relations)}function vO(T,S){return Gn(T,S).core.relatedKeysAtoms}function bF(T){return vO(T,s.STORE)}class xF extends Map{set(T,S){if(this.has(T))return console.warn("Tried to set a key that already exists in an InvariantMap",{key:T,value:S}),this;return super.set(T,S)}clear(){throw new Error("Cannot clear an InvariantMap")}}class oA{key;type="continuity";globals=[];actions=[];perspectives=[];constructor(T){this.key=T}static existing=new xF;static create(T,S){let o=new oA(T),{type:f,globals:A,actions:n,perspectives:$}=S(o),F={type:f,key:T,globals:A,actions:n,perspectives:$};return oA.existing.set(T,F),F}add(...T){switch(T[0].type){case"atom":case"mutable_atom":this.globals.push(...T);break;case"transaction":this.actions.push(...T);break;case"atom_family":{let[o,f]=T;this.perspectives.push({type:"realtime_perspective",resourceAtoms:o,viewAtoms:f})}break}return this}}function lX(T){let{key:S,config:o}=T,f=oA.create(S,o),{actions:A}=f;for(let n of A)EF(S,n.key,s.STORE);return XF(S,-1,s.STORE),f}var T8=Yo({key:"usersInRoomIndex",mutable:!0,default:()=>new bT,toJson:(T)=>T.toJSON(),fromJson:(T)=>bT.fromJSON(T)}),En=Yo({key:"roomIndex",default:()=>new bT,mutable:!0,toJson:(T)=>T.toJSON(),fromJson:(T)=>bT.fromJSON(T)}),qO={enteredAtEpoch:0},Rf=TA({key:"usersInRooms",between:["room","user"],cardinality:"1:n",isAType:(T)=>typeof T==="string",isBType:(T)=>typeof T==="string"},qO),S8=rf({key:"usersInMyRoomView",get:(T)=>({find:S})=>{let o=bF(Rf);return[S(o,T)]}});import{spawn as ZO}from"child_process";class Uo{emit;listeners;globalListeners;handleEvent(T,...S){for(let f of this.globalListeners)f(T,...S);let o=this.listeners.get(T);if(o)for(let f of o)f(...S)}id="no_id_retrieved";constructor(T){this.emit=T;this.listeners=new Map,this.globalListeners=new Set}on(T,S){let o=this.listeners.get(T);if(o)o.add(S);else this.listeners.set(T,new Set([S]));return this}onAny(T){return this.globalListeners.add(T),this}off(T,S){let o=this.listeners.get(T);if(o)if(S)o.delete(S);else this.listeners.delete(T);return this}offAny(T){return this.globalListeners.delete(T),this}}class zn extends Uo{incompleteData="";unprocessedEvents=[];incompleteLog="";unprocessedLogs=[];id="#####";process;key;logger;handleLog(T){if(Array.isArray(T)){let[S,...o]=T;switch(S){case"i":this.logger.info(...o);break;case"w":this.logger.warn(...o);break;case"e":this.logger.error(...o);break}}}constructor(T,S,o){super((f,...A)=>{let n=JSON.stringify([f,...A])+"\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(n),this});if(this.process=T,this.key=S,this.logger=o??{info:(...f)=>{console.info(this.id,this.key,...f)},warn:(...f)=>{console.warn(this.id,this.key,...f)},error:(...f)=>{console.error(this.id,this.key,...f)}},this.process.stdout.on("data",(f)=>{let A=f.toString();if(A==="ALIVE")return;this.unprocessedEvents.push(...A.split("\x03"));let n=this.unprocessedEvents.shift();this.incompleteData+=n??"";try{if(this.incompleteData.startsWith("error"))console.log("\u2757",this.incompleteData);let $=BT(this.incompleteData);this.handleEvent(...$);while(this.unprocessedEvents.length>0){let F=this.unprocessedEvents.shift();if(F){if(this.unprocessedEvents.length===0)this.incompleteData=F;$=BT(F),this.handleEvent(...$)}}this.incompleteData=""}catch($){console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.warn(this.incompleteData),console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.error($)}}),this.process.stderr.on("data",(f)=>{let A=f.toString();this.unprocessedLogs.push(...A.split("\x03"));let n=this.unprocessedLogs.shift();this.incompleteLog+=n??"";try{let $=BT(this.incompleteLog);this.handleLog($);while(this.unprocessedLogs.length>0)if(this.incompleteLog=this.unprocessedLogs.shift()??"",this.incompleteLog)$=BT(this.incompleteLog),this.handleLog($)}catch($){console.error("\u274C\u274C\u274C"),console.error(this.incompleteLog),console.error($),console.error("\u274C\u274C\u274C\uFE0F")}}),T.pid)this.id=T.pid.toString()}}class vF extends Uo{in;out;id="no_id_retrieved";disposalFunctions=[];constructor(T){super((...S)=>{return this.out.next(S),this});this.id=T,this.in=new ST,this.out=new ST,this.in.subscribe("socket",(S)=>{this.handleEvent(...S)})}dispose(){for(let T of this.disposalFunctions)T()}}class Qn extends Uo{incompleteData="";unprocessedEvents=[];relays;relayServices;process;id="#####";log(...T){this.process.stderr.write(fT(T.map((S)=>S instanceof bT?`{ ${S.toJSON().members.join(" | ")} }`:S))+"\x03")}logger={info:(...T)=>{this.log("i",...T)},warn:(...T)=>{this.log("w",...T)},error:(...T)=>{this.log("e",...T)}};constructor(){super((T,...S)=>{let o=JSON.stringify([T,...S]);return this.process.stdout.write(o+"\x03"),this});if(this.process=process,this.process.stdin.resume(),this.relays=new Map,this.relayServices=[],this.process.stdin.on("data",(T)=>{let S=T.toString();this.unprocessedEvents.push(...S.split("\x03"));let o=this.unprocessedEvents.shift();this.incompleteData+=o??"";try{let f=BT(this.incompleteData);this.logger.info("\uD83C\uDFB0","received",f),this.handleEvent(...f);while(this.unprocessedEvents.length>0){let A=this.unprocessedEvents.shift();if(A){if(this.unprocessedEvents.length===0)this.incompleteData=A;let n=BT(A);this.handleEvent(...n)}}this.incompleteData=""}catch(f){if(f instanceof Error)this.logger.error("\u2757",f.message,f.cause,f.stack)}}),this.on("exit",()=>{this.logger.info("\uD83D\uDD25",this.id,'received "exit"'),process.exit(0)}),process.on("exit",(T)=>{this.logger.info("\uD83D\uDD25",this.id,`exited with code ${T}`)}),process.on("end",()=>{this.logger.info("\uD83D\uDD25",this.id,"ended"),process.exit(0)}),process.on("SIGTERM",()=>{this.logger.error("\uD83D\uDD25",this.id,"terminated"),process.exit(0)}),process.on("SIGINT",()=>{this.logger.error("\uD83D\uDD25",this.id,"interrupted"),process.exit(0)}),process.pid)this.id=process.pid?.toString();this.on("user-joins",(T)=>{this.logger.info("\uD83D\uDC64","user",T,"joined");let S=new vF(`user:${T}`);this.relays.set(T,S),this.logger.info("\uD83D\uDD17","attaching services:",`[${[...this.relayServices.keys()].join(", ")}]`);for(let o of this.relayServices){let f=o(S);if(f)S.disposalFunctions.push(f)}this.on(`user:${T}`,(...o)=>{S.in.next(o)}),S.out.subscribe("socket",(o)=>{this.emit(...o)})}),this.on("user-leaves",(T)=>{let S=this.relays.get(T);if(this.off(`relay:${T}`),S)S.dispose(),this.relays.delete(T)}),process.stdout.write("ALIVE")}relay(T){this.logger.info("\uD83D\uDD17","running relay method"),this.relayServices.push(T)}}var Dn=oo({key:"roomArguments",default:["echo",["Hello World!"]]}),qF=rf({key:"room",get:(T)=>async({get:S,find:o})=>{let f=o(Dn,T),A=S(f),[n,$]=A,F=await new Promise((J)=>{let R=ZO(n,$,{env:process.env}),O=(k)=>{if(k.toString()==="ALIVE")R.stdout.off("data",O),J(R)};R.stdout.on("data",O)});return new zn(F,T)}});var B8=$f({key:"createRoom",do:({get:T,set:S,find:o},f,A,n)=>{let $=n?[A,n]:[A],F=o(Dn,f);S(F,$),S(En,(O)=>O.add(f));let J=o(qF,f);return T(J)}}),t8=$f({key:"joinRoom",do:(T,S,o,f)=>{let A={enteredAtEpoch:f};return SA(Rf,(n)=>{n.set({room:S,user:o},A)},T.env().store),A}}),L8=$f({key:"leaveRoom",do:(T,S,o)=>{SA(Rf,(f)=>{f.delete({room:S,user:o})},T.env().store)}}),C8=$f({key:"destroyRoom",do:(T,S)=>{SA(Rf,(o)=>{o.delete({room:S})},T.env().store),T.set(En,(o)=>(o.delete(S),o))}});function Un(T,S){return S.map((o)=>{switch(o.type){case"transaction_update":{let f=Un(T,o.updates);return{...o,updates:f}}default:return o}}).filter((o)=>{switch(o.type){case"atom_update":case"selector_update":return T.includes(o.key);case"state_creation":return T.includes(o.token.key);case"molecule_creation":return!0;case"transaction_update":return!0}})}var N8=oo({key:"redactor",default:{occlude:(T)=>T}}),Vo=oo({key:"unacknowledgedUpdates",default:()=>[]});var ZF=oo({key:"sockets",default:null}),v8=Yo({key:"socketsIndex",mutable:!0,default:()=>new bT,toJson:(T)=>T.toJSON(),fromJson:(T)=>bT.fromJSON(T)}),q8=Yo({key:"usersIndex",mutable:!0,default:()=>new bT,toJson:(T)=>T.toJSON(),fromJson:(T)=>bT.fromJSON(T)}),Vn=TA({key:"usersOfSockets",between:["user","socket"],cardinality:"1:1",isAType:(T)=>T.startsWith("user::"),isBType:(T)=>T.startsWith("socket::")});function cF(T,S,o,f){let A=S.key;return function n(){let $=[];for(let J of S.globals){let R=J.type==="mutable_atom"?NT(T,J):J,O=RT(T,R);$.push(R,O)}for(let J of S.perspectives){let{viewAtoms:R,resourceAtoms:O}=J,k=g(T,R,o),y=RT(T,k);T.logger.info("\uD83D\uDC41","atom",O.key,`${o} can see`,{viewAtoms:R,resourceAtoms:O,userView:y});for(let H of y){let E=H.type==="mutable_atom"?NT(T,H):H,G=RT(T,E);$.push(E,G)}}let F=mT(T)?T.transactionMeta.epoch.get(A)??null:null;f?.emit(`continuity-init:${A}`,F,$)}}function rF(T,S,o){let f=S.key;return function A(n){T.logger.info("\uD83D\uDECE\uFE0F","continuity",f,"received",n);let{key:$,id:F}=n,J=`tx-run:${$}:${F}`,R=`${J}:start`,O=`${J}:end`;performance.mark(R);try{zo({type:"transaction",key:$},F,T)(...n.params)}catch(y){if(y instanceof Error)T.logger.error("\u274C","continuity",f,`failed to run transaction ${$} from ${o} with update ${F}`,y.message)}performance.mark(O);let k=performance.measure(J,R,O);T?.logger.info("\uD83D\uDE80","transaction",$,F,o,k.duration)}}function pF(T,S,o,f){let A=S.key;return function n($){if(T.logger.info("\uD83D\uDC4D","continuity",A,`${o} acknowledged epoch ${$}`),f[0]?.epoch===$)VT(T,Vo,o,(J)=>{return J.shift(),T.logger.info("\uD83D\uDC4D","continuity",A,`${o} unacknowledged update queue now has`,J.length,"items"),J})}}function PF(T,S,o,f){let A=S.key,n=[];for(let $ of S.actions){let F=Rn($,(J)=>{try{let R=S.globals.map((y)=>{if(y.type==="atom")return y.key;return bS(y).key}).concat(S.perspectives.flatMap((y)=>{let{viewAtoms:H}=y,E=g(T,H,o);return RT(T,E).map((I)=>{return I.type==="mutable_atom"?"*"+I.key:I.key})})),O=Un(R,J.updates),k={...J,updates:O};VT(T,Vo,o,(y)=>{if(k)y.push(k),y.sort((H,E)=>H.epoch-E.epoch),T.logger.info("\uD83D\uDC4D","continuity",A,`${o} unacknowledged update queue now has`,y.length,"items");return y}),f?.emit(`tx-new:${A}`,k)}catch(R){if(R instanceof Error)T.logger.error("\u274C","continuity",A,`${o} failed to send update from transaction ${$.key} to ${o}`,R.message)}},`sync-continuity:${A}:${o}`,T);n.push(F)}return n}function gF(T,S,o,f){let A=S.key,n=[];for(let $ of S.perspectives){let{viewAtoms:F}=$,J=g(T,F,o),R=lT(J,({oldValue:O,newValue:k})=>{let y=O.map((I)=>I.key),H=k.map((I)=>I.key),E=O.filter((I)=>!H.includes(I.key)),G=k.filter((I)=>!y.includes(I.key)).flatMap((I)=>{let b=I.type==="mutable_atom"?NT(T,I):I,q=RT(T,b);return[b,q]});if(T.logger.info("\uD83D\uDC41","atom",$.resourceAtoms.key,`${o} has a new perspective`,{oldKeys:y,newKeys:H,revealed:G,concealed:E}),G.length>0)f?.emit(`reveal:${A}`,G);if(E.length>0)f?.emit(`conceal:${A}`,E)},`sync-continuity:${A}:${o}:perspective:${$.resourceAtoms.key}`,T);n.push(R)}return n}function w5({socket:T,store:S=s.STORE}){return function o(f){let A=T,n=f.key,$=Yn(Vn,`socket::${A.id}`,S).userKeyOfSocket,F=RT(S,$);if(!F)return S.logger.error("\u274C","continuity",n,`Tried to create a synchronizer for a socket (${A.id}) that is not connected to a user.`),()=>{};let J=Yn(Vn,F,S).socketKeyOfUser,R=lT(J,({newValue:b})=>{if(S.logger.info("\uD83D\uDC4B","continuity",n,`seeing ${F} on new socket ${b}`),b===null){S.logger.warn("\u274C","continuity",n,`User (${F}) is not connected to a socket, waiting for them to reappear.`);return}let q=g(S,ZF,b);A=RT(S,q);for(let X of O)A?.emit(`tx-new:${n}`,X)},`sync-continuity:${n}:${F}`,S),O=RT(S,Vo,F),k=[],y=gF(S,f,F,A),H=PF(S,f,F,A);k.push(...y,...H);let E=cF(S,f,F,T);A.off(`get:${n}`,E),A.on(`get:${n}`,E);let G=rF(S,f,F);A.off(`tx-run:${n}`,G),A.on(`tx-run:${n}`,G);let I=pF(S,f,F,O);return A?.on(`ack:${n}`,I),()=>{for(let b of k)b();A?.off(`ack:${n}`,I),A?.off(`get:${n}`,E),A?.off(`tx-run:${n}`,G)}}}var{file:t1,serve:A_}=globalThis.Bun;import{readFileSync as FJ}from"fs";import{resolve as jn}from"path";function cO(T,S){let o={},f=[];for(let A in T){let n=T[A],$=S[A],F=n["~standard"].validate($);if(F instanceof Promise)throw new Error(`Validation must be synchronous, but ${A} returned a Promise.`);if(F.issues){f.push(...F.issues.map((J)=>({...J,path:[A,...J.path??[]]})));continue}o[A]=F.value}if(f.length)return{issues:f};return{value:o}}function iF(T){let S=T.runtimeEnvStrict??T.runtimeEnv??process.env;if(T.emptyStringAsUndefined??!1){for(let[q,P]of Object.entries(S))if(P==="")delete S[q]}if(!!T.skipValidation)return S;let A=typeof T.client==="object"?T.client:{},n=typeof T.server==="object"?T.server:{},$=typeof T.shared==="object"?T.shared:{},F=T.isServer??(typeof window==="undefined"||("Deno"in window)),J=F?{...n,...$,...A}:{...A,...$},R=cO(J,S),O=T.onValidationError??((q)=>{throw console.error("\u274C Invalid environment variables:",q),new Error("Invalid environment variables")}),k=T.onInvalidAccess??(()=>{throw new Error("\u274C Attempted to access a server-side environment variable on the client")});if(R.issues)return O(R.issues);let y=(q)=>{if(!T.clientPrefix)return!0;return!q.startsWith(T.clientPrefix)&&!(q in $)},H=(q)=>{return F||!y(q)},E=(q)=>{return q==="__esModule"||q==="$$typeof"},G=(T.extends??[]).reduce((q,P)=>{return Object.assign(q,P)},{}),I=Object.assign(R.value,G);return new Proxy(I,{get(q,P){if(typeof P!=="string")return;if(E(P))return;if(!H(P))return k(P);return Reflect.get(q,P)}})}var $T;(function(T){T.assertEqual=(A)=>A;function S(A){}T.assertIs=S;function o(A){throw new Error}T.assertNever=o,T.arrayToEnum=(A)=>{let n={};for(let $ of A)n[$]=$;return n},T.getValidEnumValues=(A)=>{let n=T.objectKeys(A).filter((F)=>typeof A[A[F]]!=="number"),$={};for(let F of n)$[F]=A[F];return T.objectValues($)},T.objectValues=(A)=>{return T.objectKeys(A).map(function(n){return A[n]})},T.objectKeys=typeof Object.keys==="function"?(A)=>Object.keys(A):(A)=>{let n=[];for(let $ in A)if(Object.prototype.hasOwnProperty.call(A,$))n.push($);return n},T.find=(A,n)=>{for(let $ of A)if(n($))return $;return},T.isInteger=typeof Number.isInteger==="function"?(A)=>Number.isInteger(A):(A)=>typeof A==="number"&&isFinite(A)&&Math.floor(A)===A;function f(A,n=" | "){return A.map(($)=>typeof $==="string"?`'${$}'`:$).join(n)}T.joinValues=f,T.jsonStringifyReplacer=(A,n)=>{if(typeof n==="bigint")return n.toString();return n}})($T||($T={}));var tn;(function(T){T.mergeShapes=(S,o)=>{return{...S,...o}}})(tn||(tn={}));var m=$T.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),vS=(T)=>{switch(typeof T){case"undefined":return m.undefined;case"string":return m.string;case"number":return isNaN(T)?m.nan:m.number;case"boolean":return m.boolean;case"function":return m.function;case"bigint":return m.bigint;case"symbol":return m.symbol;case"object":if(Array.isArray(T))return m.array;if(T===null)return m.null;if(T.then&&typeof T.then==="function"&&T.catch&&typeof T.catch==="function")return m.promise;if(typeof Map!=="undefined"&&T instanceof Map)return m.map;if(typeof Set!=="undefined"&&T instanceof Set)return m.set;if(typeof Date!=="undefined"&&T instanceof Date)return m.date;return m.object;default:return m.unknown}},Q=$T.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),rO=(T)=>{return JSON.stringify(T,null,2).replace(/"([^"]+)":/g,"$1:")};class JS extends Error{get errors(){return this.issues}constructor(T){super();this.issues=[],this.addIssue=(o)=>{this.issues=[...this.issues,o]},this.addIssues=(o=[])=>{this.issues=[...this.issues,...o]};let S=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,S);else this.__proto__=S;this.name="ZodError",this.issues=T}format(T){let S=T||function(A){return A.message},o={_errors:[]},f=(A)=>{for(let n of A.issues)if(n.code==="invalid_union")n.unionErrors.map(f);else if(n.code==="invalid_return_type")f(n.returnTypeError);else if(n.code==="invalid_arguments")f(n.argumentsError);else if(n.path.length===0)o._errors.push(S(n));else{let $=o,F=0;while(F<n.path.length){let J=n.path[F];if(F!==n.path.length-1)$[J]=$[J]||{_errors:[]};else $[J]=$[J]||{_errors:[]},$[J]._errors.push(S(n));$=$[J],F++}}};return f(this),o}static assert(T){if(!(T instanceof JS))throw new Error(`Not a ZodError: ${T}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,$T.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(T=(S)=>S.message){let S={},o=[];for(let f of this.issues)if(f.path.length>0)S[f.path[0]]=S[f.path[0]]||[],S[f.path[0]].push(T(f));else o.push(T(f));return{formErrors:o,fieldErrors:S}}get formErrors(){return this.flatten()}}JS.create=(T)=>{return new JS(T)};var Co=(T,S)=>{let o;switch(T.code){case Q.invalid_type:if(T.received===m.undefined)o="Required";else o=`Expected ${T.expected}, received ${T.received}`;break;case Q.invalid_literal:o=`Invalid literal value, expected ${JSON.stringify(T.expected,$T.jsonStringifyReplacer)}`;break;case Q.unrecognized_keys:o=`Unrecognized key(s) in object: ${$T.joinValues(T.keys,", ")}`;break;case Q.invalid_union:o="Invalid input";break;case Q.invalid_union_discriminator:o=`Invalid discriminator value. Expected ${$T.joinValues(T.options)}`;break;case Q.invalid_enum_value:o=`Invalid enum value. Expected ${$T.joinValues(T.options)}, received '${T.received}'`;break;case Q.invalid_arguments:o="Invalid function arguments";break;case Q.invalid_return_type:o="Invalid function return type";break;case Q.invalid_date:o="Invalid date";break;case Q.invalid_string:if(typeof T.validation==="object")if("includes"in T.validation){if(o=`Invalid input: must include "${T.validation.includes}"`,typeof T.validation.position==="number")o=`${o} at one or more positions greater than or equal to ${T.validation.position}`}else if("startsWith"in T.validation)o=`Invalid input: must start with "${T.validation.startsWith}"`;else if("endsWith"in T.validation)o=`Invalid input: must end with "${T.validation.endsWith}"`;else $T.assertNever(T.validation);else if(T.validation!=="regex")o=`Invalid ${T.validation}`;else o="Invalid";break;case Q.too_small:if(T.type==="array")o=`Array must contain ${T.exact?"exactly":T.inclusive?"at least":"more than"} ${T.minimum} element(s)`;else if(T.type==="string")o=`String must contain ${T.exact?"exactly":T.inclusive?"at least":"over"} ${T.minimum} character(s)`;else if(T.type==="number")o=`Number must be ${T.exact?"exactly equal to ":T.inclusive?"greater than or equal to ":"greater than "}${T.minimum}`;else if(T.type==="date")o=`Date must be ${T.exact?"exactly equal to ":T.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(T.minimum))}`;else o="Invalid input";break;case Q.too_big:if(T.type==="array")o=`Array must contain ${T.exact?"exactly":T.inclusive?"at most":"less than"} ${T.maximum} element(s)`;else if(T.type==="string")o=`String must contain ${T.exact?"exactly":T.inclusive?"at most":"under"} ${T.maximum} character(s)`;else if(T.type==="number")o=`Number must be ${T.exact?"exactly":T.inclusive?"less than or equal to":"less than"} ${T.maximum}`;else if(T.type==="bigint")o=`BigInt must be ${T.exact?"exactly":T.inclusive?"less than or equal to":"less than"} ${T.maximum}`;else if(T.type==="date")o=`Date must be ${T.exact?"exactly":T.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(T.maximum))}`;else o="Invalid input";break;case Q.custom:o="Invalid input";break;case Q.invalid_intersection_types:o="Intersection results could not be merged";break;case Q.not_multiple_of:o=`Number must be a multiple of ${T.multipleOf}`;break;case Q.not_finite:o="Number must be finite";break;default:o=S.defaultError,$T.assertNever(T)}return{message:o}},eF=Co;function pO(T){eF=T}function fA(){return eF}var AA=(T)=>{let{data:S,path:o,errorMaps:f,issueData:A}=T,n=[...o,...A.path||[]],$={...A,path:n};if(A.message!==void 0)return{...A,path:n,message:A.message};let F="",J=f.filter((R)=>!!R).slice().reverse();for(let R of J)F=R($,{data:S,defaultError:F}).message;return{...A,path:n,message:F}},PO=[];function C(T,S){let o=fA(),f=AA({issueData:S,data:T.data,path:T.path,errorMaps:[T.common.contextualErrorMap,T.schemaErrorMap,o,o===Co?void 0:Co].filter((A)=>!!A)});T.common.issues.push(f)}class uT{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(T,S){let o=[];for(let f of S){if(f.status==="aborted")return d;if(f.status==="dirty")T.dirty();o.push(f.value)}return{status:T.value,value:o}}static async mergeObjectAsync(T,S){let o=[];for(let f of S){let A=await f.key,n=await f.value;o.push({key:A,value:n})}return uT.mergeObjectSync(T,o)}static mergeObjectSync(T,S){let o={};for(let f of S){let{key:A,value:n}=f;if(A.status==="aborted")return d;if(n.status==="aborted")return d;if(A.status==="dirty")T.dirty();if(n.status==="dirty")T.dirty();if(A.value!=="__proto__"&&(typeof n.value!=="undefined"||f.alwaysSet))o[A.value]=n.value}return{status:T.value,value:o}}}var d=Object.freeze({status:"aborted"}),to=(T)=>({status:"dirty",value:T}),aT=(T)=>({status:"valid",value:T}),Ln=(T)=>T.status==="aborted",Cn=(T)=>T.status==="dirty",Fo=(T)=>T.status==="valid",Wf=(T)=>typeof Promise!=="undefined"&&T instanceof Promise;function nA(T,S,o,f){if(o==="a"&&!f)throw new TypeError("Private accessor was defined without a getter");if(typeof S==="function"?T!==S||!f:!S.has(T))throw new TypeError("Cannot read private member from an object whose class did not declare it");return o==="m"?f:o==="a"?f.call(T):f?f.value:S.get(T)}function sF(T,S,o,f,A){if(f==="m")throw new TypeError("Private method is not writable");if(f==="a"&&!A)throw new TypeError("Private accessor was defined without a setter");if(typeof S==="function"?T!==S||!A:!S.has(T))throw new TypeError("Cannot write private member to an object whose class did not declare it");return f==="a"?A.call(T,o):A?A.value=o:S.set(T,o),o}var x;(function(T){T.errToObj=(S)=>typeof S==="string"?{message:S}:S||{},T.toString=(S)=>typeof S==="string"?S:S===null||S===void 0?void 0:S.message})(x||(x={}));var Of,Mf;class zS{constructor(T,S,o,f){this._cachedPath=[],this.parent=T,this.data=S,this._path=o,this._key=f}get path(){if(!this._cachedPath.length)if(this._key instanceof Array)this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var dF=(T,S)=>{if(Fo(S))return{success:!0,data:S.value};else{if(!T.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let o=new JS(T.common.issues);return this._error=o,this._error}}}};function u(T){if(!T)return{};let{errorMap:S,invalid_type_error:o,required_error:f,description:A}=T;if(S&&(o||f))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(S)return{errorMap:S,description:A};return{errorMap:($,F)=>{var J,R;let{message:O}=T;if($.code==="invalid_enum_value")return{message:O!==null&&O!==void 0?O:F.defaultError};if(typeof F.data==="undefined")return{message:(J=O!==null&&O!==void 0?O:f)!==null&&J!==void 0?J:F.defaultError};if($.code!=="invalid_type")return{message:F.defaultError};return{message:(R=O!==null&&O!==void 0?O:o)!==null&&R!==void 0?R:F.defaultError}},description:A}}class e{get description(){return this._def.description}_getType(T){return vS(T.data)}_getOrReturnCtx(T,S){return S||{common:T.parent.common,data:T.data,parsedType:vS(T.data),schemaErrorMap:this._def.errorMap,path:T.path,parent:T.parent}}_processInputParams(T){return{status:new uT,ctx:{common:T.parent.common,data:T.data,parsedType:vS(T.data),schemaErrorMap:this._def.errorMap,path:T.path,parent:T.parent}}}_parseSync(T){let S=this._parse(T);if(Wf(S))throw new Error("Synchronous parse encountered promise.");return S}_parseAsync(T){let S=this._parse(T);return Promise.resolve(S)}parse(T,S){let o=this.safeParse(T,S);if(o.success)return o.data;throw o.error}safeParse(T,S){var o;let f={common:{issues:[],async:(o=S===null||S===void 0?void 0:S.async)!==null&&o!==void 0?o:!1,contextualErrorMap:S===null||S===void 0?void 0:S.errorMap},path:(S===null||S===void 0?void 0:S.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:T,parsedType:vS(T)},A=this._parseSync({data:T,path:f.path,parent:f});return dF(f,A)}"~validate"(T){var S,o;let f={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:T,parsedType:vS(T)};if(!this["~standard"].async)try{let A=this._parseSync({data:T,path:[],parent:f});return Fo(A)?{value:A.value}:{issues:f.common.issues}}catch(A){if((o=(S=A===null||A===void 0?void 0:A.message)===null||S===void 0?void 0:S.toLowerCase())===null||o===void 0?void 0:o.includes("encountered"))this["~standard"].async=!0;f.common={issues:[],async:!0}}return this._parseAsync({data:T,path:[],parent:f}).then((A)=>Fo(A)?{value:A.value}:{issues:f.common.issues})}async parseAsync(T,S){let o=await this.safeParseAsync(T,S);if(o.success)return o.data;throw o.error}async safeParseAsync(T,S){let o={common:{issues:[],contextualErrorMap:S===null||S===void 0?void 0:S.errorMap,async:!0},path:(S===null||S===void 0?void 0:S.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:T,parsedType:vS(T)},f=this._parse({data:T,path:o.path,parent:o}),A=await(Wf(f)?f:Promise.resolve(f));return dF(o,A)}refine(T,S){let o=(f)=>{if(typeof S==="string"||typeof S==="undefined")return{message:S};else if(typeof S==="function")return S(f);else return S};return this._refinement((f,A)=>{let n=T(f),$=()=>A.addIssue({code:Q.custom,...o(f)});if(typeof Promise!=="undefined"&&n instanceof Promise)return n.then((F)=>{if(!F)return $(),!1;else return!0});if(!n)return $(),!1;else return!0})}refinement(T,S){return this._refinement((o,f)=>{if(!T(o))return f.addIssue(typeof S==="function"?S(o,f):S),!1;else return!0})}_refinement(T){return new kS({schema:this,typeName:i.ZodEffects,effect:{type:"refinement",refinement:T}})}superRefine(T){return this._refinement(T)}constructor(T){this.spa=this.safeParseAsync,this._def=T,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:(S)=>this["~validate"](S)}}optional(){return ES.create(this,this._def)}nullable(){return qS.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return YS.create(this)}promise(){return Mo.create(this,this._def)}or(T){return mo.create([this,T],this._def)}and(T){return ho.create(this,T,this._def)}transform(T){return new kS({...u(this._def),schema:this,typeName:i.ZodEffects,effect:{type:"transform",transform:T}})}default(T){let S=typeof T==="function"?T:()=>T;return new qo({...u(this._def),innerType:this,defaultValue:S,typeName:i.ZodDefault})}brand(){return new FA({typeName:i.ZodBranded,type:this,...u(this._def)})}catch(T){let S=typeof T==="function"?T:()=>T;return new Zo({...u(this._def),innerType:this,catchValue:S,typeName:i.ZodCatch})}describe(T){return new this.constructor({...this._def,description:T})}pipe(T){return Hf.create(this,T)}readonly(){return co.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var gO=/^c[^\s-]{8,}$/i,iO=/^[0-9a-z]+$/,dO=/^[0-9A-HJKMNP-TV-Z]{26}$/i,lO=/^[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,uO=/^[a-z0-9_-]{21}$/i,eO=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,sO=/^[-+]?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)?)??$/,aO=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,TM="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Bn,SM=/^(?:(?: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])$/,oM=/^(?:(?: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])$/,fM=/^(([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]))$/,AM=/^(([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])$/,nM=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,$M=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,aF="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",FM=new RegExp(`^${aF}$`);function TJ(T){let S="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";if(T.precision)S=`${S}\\.\\d{${T.precision}}`;else if(T.precision==null)S=`${S}(\\.\\d+)?`;return S}function JM(T){return new RegExp(`^${TJ(T)}$`)}function SJ(T){let S=`${aF}T${TJ(T)}`,o=[];if(o.push(T.local?"Z?":"Z"),T.offset)o.push("([+-]\\d{2}:?\\d{2})");return S=`${S}(${o.join("|")})`,new RegExp(`^${S}$`)}function RM(T,S){if((S==="v4"||!S)&&SM.test(T))return!0;if((S==="v6"||!S)&&fM.test(T))return!0;return!1}function OM(T,S){if(!eO.test(T))return!1;try{let[o]=T.split("."),f=o.replace(/-/g,"+").replace(/_/g,"/").padEnd(o.length+(4-o.length%4)%4,"="),A=JSON.parse(atob(f));if(typeof A!=="object"||A===null)return!1;if(!A.typ||!A.alg)return!1;if(S&&A.alg!==S)return!1;return!0}catch(o){return!1}}function MM(T,S){if((S==="v4"||!S)&&oM.test(T))return!0;if((S==="v6"||!S)&&AM.test(T))return!0;return!1}class GS extends e{_parse(T){if(this._def.coerce)T.data=String(T.data);if(this._getType(T)!==m.string){let A=this._getOrReturnCtx(T);return C(A,{code:Q.invalid_type,expected:m.string,received:A.parsedType}),d}let o=new uT,f=void 0;for(let A of this._def.checks)if(A.kind==="min"){if(T.data.length<A.value)f=this._getOrReturnCtx(T,f),C(f,{code:Q.too_small,minimum:A.value,type:"string",inclusive:!0,exact:!1,message:A.message}),o.dirty()}else if(A.kind==="max"){if(T.data.length>A.value)f=this._getOrReturnCtx(T,f),C(f,{code:Q.too_big,maximum:A.value,type:"string",inclusive:!0,exact:!1,message:A.message}),o.dirty()}else if(A.kind==="length"){let n=T.data.length>A.value,$=T.data.length<A.value;if(n||$){if(f=this._getOrReturnCtx(T,f),n)C(f,{code:Q.too_big,maximum:A.value,type:"string",inclusive:!0,exact:!0,message:A.message});else if($)C(f,{code:Q.too_small,minimum:A.value,type:"string",inclusive:!0,exact:!0,message:A.message});o.dirty()}}else if(A.kind==="email"){if(!aO.test(T.data))f=this._getOrReturnCtx(T,f),C(f,{validation:"email",code:Q.invalid_string,message:A.message}),o.dirty()}else if(A.kind==="emoji"){if(!Bn)Bn=new RegExp(TM,"u");if(!Bn.test(T.data))f=this._getOrReturnCtx(T,f),C(f,{validation:"emoji",code:Q.invalid_string,message:A.message}),o.dirty()}else if(A.kind==="uuid"){if(!lO.test(T.data))f=this._getOrReturnCtx(T,f),C(f,{validation:"uuid",code:Q.invalid_string,message:A.message}),o.dirty()}else if(A.kind==="nanoid"){if(!uO.test(T.data))f=this._getOrReturnCtx(T,f),C(f,{validation:"nanoid",code:Q.invalid_string,message:A.message}),o.dirty()}else if(A.kind==="cuid"){if(!gO.test(T.data))f=this._getOrReturnCtx(T,f),C(f,{validation:"cuid",code:Q.invalid_string,message:A.message}),o.dirty()}else if(A.kind==="cuid2"){if(!iO.test(T.data))f=this._getOrReturnCtx(T,f),C(f,{validation:"cuid2",code:Q.invalid_string,message:A.message}),o.dirty()}else if(A.kind==="ulid"){if(!dO.test(T.data))f=this._getOrReturnCtx(T,f),C(f,{validation:"ulid",code:Q.invalid_string,message:A.message}),o.dirty()}else if(A.kind==="url")try{new URL(T.data)}catch(n){f=this._getOrReturnCtx(T,f),C(f,{validation:"url",code:Q.invalid_string,message:A.message}),o.dirty()}else if(A.kind==="regex"){if(A.regex.lastIndex=0,!A.regex.test(T.data))f=this._getOrReturnCtx(T,f),C(f,{validation:"regex",code:Q.invalid_string,message:A.message}),o.dirty()}else if(A.kind==="trim")T.data=T.data.trim();else if(A.kind==="includes"){if(!T.data.includes(A.value,A.position))f=this._getOrReturnCtx(T,f),C(f,{code:Q.invalid_string,validation:{includes:A.value,position:A.position},message:A.message}),o.dirty()}else if(A.kind==="toLowerCase")T.data=T.data.toLowerCase();else if(A.kind==="toUpperCase")T.data=T.data.toUpperCase();else if(A.kind==="startsWith"){if(!T.data.startsWith(A.value))f=this._getOrReturnCtx(T,f),C(f,{code:Q.invalid_string,validation:{startsWith:A.value},message:A.message}),o.dirty()}else if(A.kind==="endsWith"){if(!T.data.endsWith(A.value))f=this._getOrReturnCtx(T,f),C(f,{code:Q.invalid_string,validation:{endsWith:A.value},message:A.message}),o.dirty()}else if(A.kind==="datetime"){if(!SJ(A).test(T.data))f=this._getOrReturnCtx(T,f),C(f,{code:Q.invalid_string,validation:"datetime",message:A.message}),o.dirty()}else if(A.kind==="date"){if(!FM.test(T.data))f=this._getOrReturnCtx(T,f),C(f,{code:Q.invalid_string,validation:"date",message:A.message}),o.dirty()}else if(A.kind==="time"){if(!JM(A).test(T.data))f=this._getOrReturnCtx(T,f),C(f,{code:Q.invalid_string,validation:"time",message:A.message}),o.dirty()}else if(A.kind==="duration"){if(!sO.test(T.data))f=this._getOrReturnCtx(T,f),C(f,{validation:"duration",code:Q.invalid_string,message:A.message}),o.dirty()}else if(A.kind==="ip"){if(!RM(T.data,A.version))f=this._getOrReturnCtx(T,f),C(f,{validation:"ip",code:Q.invalid_string,message:A.message}),o.dirty()}else if(A.kind==="jwt"){if(!OM(T.data,A.alg))f=this._getOrReturnCtx(T,f),C(f,{validation:"jwt",code:Q.invalid_string,message:A.message}),o.dirty()}else if(A.kind==="cidr"){if(!MM(T.data,A.version))f=this._getOrReturnCtx(T,f),C(f,{validation:"cidr",code:Q.invalid_string,message:A.message}),o.dirty()}else if(A.kind==="base64"){if(!nM.test(T.data))f=this._getOrReturnCtx(T,f),C(f,{validation:"base64",code:Q.invalid_string,message:A.message}),o.dirty()}else if(A.kind==="base64url"){if(!$M.test(T.data))f=this._getOrReturnCtx(T,f),C(f,{validation:"base64url",code:Q.invalid_string,message:A.message}),o.dirty()}else $T.assertNever(A);return{status:o.value,value:T.data}}_regex(T,S,o){return this.refinement((f)=>T.test(f),{validation:S,code:Q.invalid_string,...x.errToObj(o)})}_addCheck(T){return new GS({...this._def,checks:[...this._def.checks,T]})}email(T){return this._addCheck({kind:"email",...x.errToObj(T)})}url(T){return this._addCheck({kind:"url",...x.errToObj(T)})}emoji(T){return this._addCheck({kind:"emoji",...x.errToObj(T)})}uuid(T){return this._addCheck({kind:"uuid",...x.errToObj(T)})}nanoid(T){return this._addCheck({kind:"nanoid",...x.errToObj(T)})}cuid(T){return this._addCheck({kind:"cuid",...x.errToObj(T)})}cuid2(T){return this._addCheck({kind:"cuid2",...x.errToObj(T)})}ulid(T){return this._addCheck({kind:"ulid",...x.errToObj(T)})}base64(T){return this._addCheck({kind:"base64",...x.errToObj(T)})}base64url(T){return this._addCheck({kind:"base64url",...x.errToObj(T)})}jwt(T){return this._addCheck({kind:"jwt",...x.errToObj(T)})}ip(T){return this._addCheck({kind:"ip",...x.errToObj(T)})}cidr(T){return this._addCheck({kind:"cidr",...x.errToObj(T)})}datetime(T){var S,o;if(typeof T==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:T});return this._addCheck({kind:"datetime",precision:typeof(T===null||T===void 0?void 0:T.precision)==="undefined"?null:T===null||T===void 0?void 0:T.precision,offset:(S=T===null||T===void 0?void 0:T.offset)!==null&&S!==void 0?S:!1,local:(o=T===null||T===void 0?void 0:T.local)!==null&&o!==void 0?o:!1,...x.errToObj(T===null||T===void 0?void 0:T.message)})}date(T){return this._addCheck({kind:"date",message:T})}time(T){if(typeof T==="string")return this._addCheck({kind:"time",precision:null,message:T});return this._addCheck({kind:"time",precision:typeof(T===null||T===void 0?void 0:T.precision)==="undefined"?null:T===null||T===void 0?void 0:T.precision,...x.errToObj(T===null||T===void 0?void 0:T.message)})}duration(T){return this._addCheck({kind:"duration",...x.errToObj(T)})}regex(T,S){return this._addCheck({kind:"regex",regex:T,...x.errToObj(S)})}includes(T,S){return this._addCheck({kind:"includes",value:T,position:S===null||S===void 0?void 0:S.position,...x.errToObj(S===null||S===void 0?void 0:S.message)})}startsWith(T,S){return this._addCheck({kind:"startsWith",value:T,...x.errToObj(S)})}endsWith(T,S){return this._addCheck({kind:"endsWith",value:T,...x.errToObj(S)})}min(T,S){return this._addCheck({kind:"min",value:T,...x.errToObj(S)})}max(T,S){return this._addCheck({kind:"max",value:T,...x.errToObj(S)})}length(T,S){return this._addCheck({kind:"length",value:T,...x.errToObj(S)})}nonempty(T){return this.min(1,x.errToObj(T))}trim(){return new GS({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new GS({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new GS({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((T)=>T.kind==="datetime")}get isDate(){return!!this._def.checks.find((T)=>T.kind==="date")}get isTime(){return!!this._def.checks.find((T)=>T.kind==="time")}get isDuration(){return!!this._def.checks.find((T)=>T.kind==="duration")}get isEmail(){return!!this._def.checks.find((T)=>T.kind==="email")}get isURL(){return!!this._def.checks.find((T)=>T.kind==="url")}get isEmoji(){return!!this._def.checks.find((T)=>T.kind==="emoji")}get isUUID(){return!!this._def.checks.find((T)=>T.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((T)=>T.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((T)=>T.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((T)=>T.kind==="cuid2")}get isULID(){return!!this._def.checks.find((T)=>T.kind==="ulid")}get isIP(){return!!this._def.checks.find((T)=>T.kind==="ip")}get isCIDR(){return!!this._def.checks.find((T)=>T.kind==="cidr")}get isBase64(){return!!this._def.checks.find((T)=>T.kind==="base64")}get isBase64url(){return!!this._def.checks.find((T)=>T.kind==="base64url")}get minLength(){let T=null;for(let S of this._def.checks)if(S.kind==="min"){if(T===null||S.value>T)T=S.value}return T}get maxLength(){let T=null;for(let S of this._def.checks)if(S.kind==="max"){if(T===null||S.value<T)T=S.value}return T}}GS.create=(T)=>{var S;return new GS({checks:[],typeName:i.ZodString,coerce:(S=T===null||T===void 0?void 0:T.coerce)!==null&&S!==void 0?S:!1,...u(T)})};function WM(T,S){let o=(T.toString().split(".")[1]||"").length,f=(S.toString().split(".")[1]||"").length,A=o>f?o:f,n=parseInt(T.toFixed(A).replace(".","")),$=parseInt(S.toFixed(A).replace(".",""));return n%$/Math.pow(10,A)}class dS extends e{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(T){if(this._def.coerce)T.data=Number(T.data);if(this._getType(T)!==m.number){let A=this._getOrReturnCtx(T);return C(A,{code:Q.invalid_type,expected:m.number,received:A.parsedType}),d}let o=void 0,f=new uT;for(let A of this._def.checks)if(A.kind==="int"){if(!$T.isInteger(T.data))o=this._getOrReturnCtx(T,o),C(o,{code:Q.invalid_type,expected:"integer",received:"float",message:A.message}),f.dirty()}else if(A.kind==="min"){if(A.inclusive?T.data<A.value:T.data<=A.value)o=this._getOrReturnCtx(T,o),C(o,{code:Q.too_small,minimum:A.value,type:"number",inclusive:A.inclusive,exact:!1,message:A.message}),f.dirty()}else if(A.kind==="max"){if(A.inclusive?T.data>A.value:T.data>=A.value)o=this._getOrReturnCtx(T,o),C(o,{code:Q.too_big,maximum:A.value,type:"number",inclusive:A.inclusive,exact:!1,message:A.message}),f.dirty()}else if(A.kind==="multipleOf"){if(WM(T.data,A.value)!==0)o=this._getOrReturnCtx(T,o),C(o,{code:Q.not_multiple_of,multipleOf:A.value,message:A.message}),f.dirty()}else if(A.kind==="finite"){if(!Number.isFinite(T.data))o=this._getOrReturnCtx(T,o),C(o,{code:Q.not_finite,message:A.message}),f.dirty()}else $T.assertNever(A);return{status:f.value,value:T.data}}gte(T,S){return this.setLimit("min",T,!0,x.toString(S))}gt(T,S){return this.setLimit("min",T,!1,x.toString(S))}lte(T,S){return this.setLimit("max",T,!0,x.toString(S))}lt(T,S){return this.setLimit("max",T,!1,x.toString(S))}setLimit(T,S,o,f){return new dS({...this._def,checks:[...this._def.checks,{kind:T,value:S,inclusive:o,message:x.toString(f)}]})}_addCheck(T){return new dS({...this._def,checks:[...this._def.checks,T]})}int(T){return this._addCheck({kind:"int",message:x.toString(T)})}positive(T){return this._addCheck({kind:"min",value:0,inclusive:!1,message:x.toString(T)})}negative(T){return this._addCheck({kind:"max",value:0,inclusive:!1,message:x.toString(T)})}nonpositive(T){return this._addCheck({kind:"max",value:0,inclusive:!0,message:x.toString(T)})}nonnegative(T){return this._addCheck({kind:"min",value:0,inclusive:!0,message:x.toString(T)})}multipleOf(T,S){return this._addCheck({kind:"multipleOf",value:T,message:x.toString(S)})}finite(T){return this._addCheck({kind:"finite",message:x.toString(T)})}safe(T){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:x.toString(T)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:x.toString(T)})}get minValue(){let T=null;for(let S of this._def.checks)if(S.kind==="min"){if(T===null||S.value>T)T=S.value}return T}get maxValue(){let T=null;for(let S of this._def.checks)if(S.kind==="max"){if(T===null||S.value<T)T=S.value}return T}get isInt(){return!!this._def.checks.find((T)=>T.kind==="int"||T.kind==="multipleOf"&&$T.isInteger(T.value))}get isFinite(){let T=null,S=null;for(let o of this._def.checks)if(o.kind==="finite"||o.kind==="int"||o.kind==="multipleOf")return!0;else if(o.kind==="min"){if(S===null||o.value>S)S=o.value}else if(o.kind==="max"){if(T===null||o.value<T)T=o.value}return Number.isFinite(S)&&Number.isFinite(T)}}dS.create=(T)=>{return new dS({checks:[],typeName:i.ZodNumber,coerce:(T===null||T===void 0?void 0:T.coerce)||!1,...u(T)})};class lS extends e{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(T){if(this._def.coerce)try{T.data=BigInt(T.data)}catch(A){return this._getInvalidInput(T)}if(this._getType(T)!==m.bigint)return this._getInvalidInput(T);let o=void 0,f=new uT;for(let A of this._def.checks)if(A.kind==="min"){if(A.inclusive?T.data<A.value:T.data<=A.value)o=this._getOrReturnCtx(T,o),C(o,{code:Q.too_small,type:"bigint",minimum:A.value,inclusive:A.inclusive,message:A.message}),f.dirty()}else if(A.kind==="max"){if(A.inclusive?T.data>A.value:T.data>=A.value)o=this._getOrReturnCtx(T,o),C(o,{code:Q.too_big,type:"bigint",maximum:A.value,inclusive:A.inclusive,message:A.message}),f.dirty()}else if(A.kind==="multipleOf"){if(T.data%A.value!==BigInt(0))o=this._getOrReturnCtx(T,o),C(o,{code:Q.not_multiple_of,multipleOf:A.value,message:A.message}),f.dirty()}else $T.assertNever(A);return{status:f.value,value:T.data}}_getInvalidInput(T){let S=this._getOrReturnCtx(T);return C(S,{code:Q.invalid_type,expected:m.bigint,received:S.parsedType}),d}gte(T,S){return this.setLimit("min",T,!0,x.toString(S))}gt(T,S){return this.setLimit("min",T,!1,x.toString(S))}lte(T,S){return this.setLimit("max",T,!0,x.toString(S))}lt(T,S){return this.setLimit("max",T,!1,x.toString(S))}setLimit(T,S,o,f){return new lS({...this._def,checks:[...this._def.checks,{kind:T,value:S,inclusive:o,message:x.toString(f)}]})}_addCheck(T){return new lS({...this._def,checks:[...this._def.checks,T]})}positive(T){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:x.toString(T)})}negative(T){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:x.toString(T)})}nonpositive(T){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:x.toString(T)})}nonnegative(T){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:x.toString(T)})}multipleOf(T,S){return this._addCheck({kind:"multipleOf",value:T,message:x.toString(S)})}get minValue(){let T=null;for(let S of this._def.checks)if(S.kind==="min"){if(T===null||S.value>T)T=S.value}return T}get maxValue(){let T=null;for(let S of this._def.checks)if(S.kind==="max"){if(T===null||S.value<T)T=S.value}return T}}lS.create=(T)=>{var S;return new lS({checks:[],typeName:i.ZodBigInt,coerce:(S=T===null||T===void 0?void 0:T.coerce)!==null&&S!==void 0?S:!1,...u(T)})};class Io extends e{_parse(T){if(this._def.coerce)T.data=Boolean(T.data);if(this._getType(T)!==m.boolean){let o=this._getOrReturnCtx(T);return C(o,{code:Q.invalid_type,expected:m.boolean,received:o.parsedType}),d}return aT(T.data)}}Io.create=(T)=>{return new Io({typeName:i.ZodBoolean,coerce:(T===null||T===void 0?void 0:T.coerce)||!1,...u(T)})};class Jo extends e{_parse(T){if(this._def.coerce)T.data=new Date(T.data);if(this._getType(T)!==m.date){let A=this._getOrReturnCtx(T);return C(A,{code:Q.invalid_type,expected:m.date,received:A.parsedType}),d}if(isNaN(T.data.getTime())){let A=this._getOrReturnCtx(T);return C(A,{code:Q.invalid_date}),d}let o=new uT,f=void 0;for(let A of this._def.checks)if(A.kind==="min"){if(T.data.getTime()<A.value)f=this._getOrReturnCtx(T,f),C(f,{code:Q.too_small,message:A.message,inclusive:!0,exact:!1,minimum:A.value,type:"date"}),o.dirty()}else if(A.kind==="max"){if(T.data.getTime()>A.value)f=this._getOrReturnCtx(T,f),C(f,{code:Q.too_big,message:A.message,inclusive:!0,exact:!1,maximum:A.value,type:"date"}),o.dirty()}else $T.assertNever(A);return{status:o.value,value:new Date(T.data.getTime())}}_addCheck(T){return new Jo({...this._def,checks:[...this._def.checks,T]})}min(T,S){return this._addCheck({kind:"min",value:T.getTime(),message:x.toString(S)})}max(T,S){return this._addCheck({kind:"max",value:T.getTime(),message:x.toString(S)})}get minDate(){let T=null;for(let S of this._def.checks)if(S.kind==="min"){if(T===null||S.value>T)T=S.value}return T!=null?new Date(T):null}get maxDate(){let T=null;for(let S of this._def.checks)if(S.kind==="max"){if(T===null||S.value<T)T=S.value}return T!=null?new Date(T):null}}Jo.create=(T)=>{return new Jo({checks:[],coerce:(T===null||T===void 0?void 0:T.coerce)||!1,typeName:i.ZodDate,...u(T)})};class _f extends e{_parse(T){if(this._getType(T)!==m.symbol){let o=this._getOrReturnCtx(T);return C(o,{code:Q.invalid_type,expected:m.symbol,received:o.parsedType}),d}return aT(T.data)}}_f.create=(T)=>{return new _f({typeName:i.ZodSymbol,...u(T)})};class jo extends e{_parse(T){if(this._getType(T)!==m.undefined){let o=this._getOrReturnCtx(T);return C(o,{code:Q.invalid_type,expected:m.undefined,received:o.parsedType}),d}return aT(T.data)}}jo.create=(T)=>{return new jo({typeName:i.ZodUndefined,...u(T)})};class No extends e{_parse(T){if(this._getType(T)!==m.null){let o=this._getOrReturnCtx(T);return C(o,{code:Q.invalid_type,expected:m.null,received:o.parsedType}),d}return aT(T.data)}}No.create=(T)=>{return new No({typeName:i.ZodNull,...u(T)})};class Ro extends e{constructor(){super(...arguments);this._any=!0}_parse(T){return aT(T.data)}}Ro.create=(T)=>{return new Ro({typeName:i.ZodAny,...u(T)})};class iS extends e{constructor(){super(...arguments);this._unknown=!0}_parse(T){return aT(T.data)}}iS.create=(T)=>{return new iS({typeName:i.ZodUnknown,...u(T)})};class CS extends e{_parse(T){let S=this._getOrReturnCtx(T);return C(S,{code:Q.invalid_type,expected:m.never,received:S.parsedType}),d}}CS.create=(T)=>{return new CS({typeName:i.ZodNever,...u(T)})};class kf extends e{_parse(T){if(this._getType(T)!==m.undefined){let o=this._getOrReturnCtx(T);return C(o,{code:Q.invalid_type,expected:m.void,received:o.parsedType}),d}return aT(T.data)}}kf.create=(T)=>{return new kf({typeName:i.ZodVoid,...u(T)})};class YS extends e{_parse(T){let{ctx:S,status:o}=this._processInputParams(T),f=this._def;if(S.parsedType!==m.array)return C(S,{code:Q.invalid_type,expected:m.array,received:S.parsedType}),d;if(f.exactLength!==null){let n=S.data.length>f.exactLength.value,$=S.data.length<f.exactLength.value;if(n||$)C(S,{code:n?Q.too_big:Q.too_small,minimum:$?f.exactLength.value:void 0,maximum:n?f.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:f.exactLength.message}),o.dirty()}if(f.minLength!==null){if(S.data.length<f.minLength.value)C(S,{code:Q.too_small,minimum:f.minLength.value,type:"array",inclusive:!0,exact:!1,message:f.minLength.message}),o.dirty()}if(f.maxLength!==null){if(S.data.length>f.maxLength.value)C(S,{code:Q.too_big,maximum:f.maxLength.value,type:"array",inclusive:!0,exact:!1,message:f.maxLength.message}),o.dirty()}if(S.common.async)return Promise.all([...S.data].map((n,$)=>{return f.type._parseAsync(new zS(S,n,S.path,$))})).then((n)=>{return uT.mergeArray(o,n)});let A=[...S.data].map((n,$)=>{return f.type._parseSync(new zS(S,n,S.path,$))});return uT.mergeArray(o,A)}get element(){return this._def.type}min(T,S){return new YS({...this._def,minLength:{value:T,message:x.toString(S)}})}max(T,S){return new YS({...this._def,maxLength:{value:T,message:x.toString(S)}})}length(T,S){return new YS({...this._def,exactLength:{value:T,message:x.toString(S)}})}nonempty(T){return this.min(1,T)}}YS.create=(T,S)=>{return new YS({type:T,minLength:null,maxLength:null,exactLength:null,typeName:i.ZodArray,...u(S)})};function Bo(T){if(T instanceof QT){let S={};for(let o in T.shape){let f=T.shape[o];S[o]=ES.create(Bo(f))}return new QT({...T._def,shape:()=>S})}else if(T instanceof YS)return new YS({...T._def,type:Bo(T.element)});else if(T instanceof ES)return ES.create(Bo(T.unwrap()));else if(T instanceof qS)return qS.create(Bo(T.unwrap()));else if(T instanceof IS)return IS.create(T.items.map((S)=>Bo(S)));else return T}class QT extends e{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let T=this._def.shape(),S=$T.objectKeys(T);return this._cached={shape:T,keys:S}}_parse(T){if(this._getType(T)!==m.object){let J=this._getOrReturnCtx(T);return C(J,{code:Q.invalid_type,expected:m.object,received:J.parsedType}),d}let{status:o,ctx:f}=this._processInputParams(T),{shape:A,keys:n}=this._getCached(),$=[];if(!(this._def.catchall instanceof CS&&this._def.unknownKeys==="strip")){for(let J in f.data)if(!n.includes(J))$.push(J)}let F=[];for(let J of n){let R=A[J],O=f.data[J];F.push({key:{status:"valid",value:J},value:R._parse(new zS(f,O,f.path,J)),alwaysSet:J in f.data})}if(this._def.catchall instanceof CS){let J=this._def.unknownKeys;if(J==="passthrough")for(let R of $)F.push({key:{status:"valid",value:R},value:{status:"valid",value:f.data[R]}});else if(J==="strict"){if($.length>0)C(f,{code:Q.unrecognized_keys,keys:$}),o.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 O=f.data[R];F.push({key:{status:"valid",value:R},value:J._parse(new zS(f,O,f.path,R)),alwaysSet:R in f.data})}}if(f.common.async)return Promise.resolve().then(async()=>{let J=[];for(let R of F){let O=await R.key,k=await R.value;J.push({key:O,value:k,alwaysSet:R.alwaysSet})}return J}).then((J)=>{return uT.mergeObjectSync(o,J)});else return uT.mergeObjectSync(o,F)}get shape(){return this._def.shape()}strict(T){return x.errToObj,new QT({...this._def,unknownKeys:"strict",...T!==void 0?{errorMap:(S,o)=>{var f,A,n,$;let F=(n=(A=(f=this._def).errorMap)===null||A===void 0?void 0:A.call(f,S,o).message)!==null&&n!==void 0?n:o.defaultError;if(S.code==="unrecognized_keys")return{message:($=x.errToObj(T).message)!==null&&$!==void 0?$:F};return{message:F}}}:{}})}strip(){return new QT({...this._def,unknownKeys:"strip"})}passthrough(){return new QT({...this._def,unknownKeys:"passthrough"})}extend(T){return new QT({...this._def,shape:()=>({...this._def.shape(),...T})})}merge(T){return new QT({unknownKeys:T._def.unknownKeys,catchall:T._def.catchall,shape:()=>({...this._def.shape(),...T._def.shape()}),typeName:i.ZodObject})}setKey(T,S){return this.augment({[T]:S})}catchall(T){return new QT({...this._def,catchall:T})}pick(T){let S={};return $T.objectKeys(T).forEach((o)=>{if(T[o]&&this.shape[o])S[o]=this.shape[o]}),new QT({...this._def,shape:()=>S})}omit(T){let S={};return $T.objectKeys(this.shape).forEach((o)=>{if(!T[o])S[o]=this.shape[o]}),new QT({...this._def,shape:()=>S})}deepPartial(){return Bo(this)}partial(T){let S={};return $T.objectKeys(this.shape).forEach((o)=>{let f=this.shape[o];if(T&&!T[o])S[o]=f;else S[o]=f.optional()}),new QT({...this._def,shape:()=>S})}required(T){let S={};return $T.objectKeys(this.shape).forEach((o)=>{if(T&&!T[o])S[o]=this.shape[o];else{let A=this.shape[o];while(A instanceof ES)A=A._def.innerType;S[o]=A}}),new QT({...this._def,shape:()=>S})}keyof(){return oJ($T.objectKeys(this.shape))}}QT.create=(T,S)=>{return new QT({shape:()=>T,unknownKeys:"strip",catchall:CS.create(),typeName:i.ZodObject,...u(S)})};QT.strictCreate=(T,S)=>{return new QT({shape:()=>T,unknownKeys:"strict",catchall:CS.create(),typeName:i.ZodObject,...u(S)})};QT.lazycreate=(T,S)=>{return new QT({shape:T,unknownKeys:"strip",catchall:CS.create(),typeName:i.ZodObject,...u(S)})};class mo extends e{_parse(T){let{ctx:S}=this._processInputParams(T),o=this._def.options;function f(A){for(let $ of A)if($.result.status==="valid")return $.result;for(let $ of A)if($.result.status==="dirty")return S.common.issues.push(...$.ctx.common.issues),$.result;let n=A.map(($)=>new JS($.ctx.common.issues));return C(S,{code:Q.invalid_union,unionErrors:n}),d}if(S.common.async)return Promise.all(o.map(async(A)=>{let n={...S,common:{...S.common,issues:[]},parent:null};return{result:await A._parseAsync({data:S.data,path:S.path,parent:n}),ctx:n}})).then(f);else{let A=void 0,n=[];for(let F of o){let J={...S,common:{...S.common,issues:[]},parent:null},R=F._parseSync({data:S.data,path:S.path,parent:J});if(R.status==="valid")return R;else if(R.status==="dirty"&&!A)A={result:R,ctx:J};if(J.common.issues.length)n.push(J.common.issues)}if(A)return S.common.issues.push(...A.ctx.common.issues),A.result;let $=n.map((F)=>new JS(F));return C(S,{code:Q.invalid_union,unionErrors:$}),d}}get options(){return this._def.options}}mo.create=(T,S)=>{return new mo({options:T,typeName:i.ZodUnion,...u(S)})};var xS=(T)=>{if(T instanceof bo)return xS(T.schema);else if(T instanceof kS)return xS(T.innerType());else if(T instanceof xo)return[T.value];else if(T instanceof uS)return T.options;else if(T instanceof vo)return $T.objectValues(T.enum);else if(T instanceof qo)return xS(T._def.innerType);else if(T instanceof jo)return[void 0];else if(T instanceof No)return[null];else if(T instanceof ES)return[void 0,...xS(T.unwrap())];else if(T instanceof qS)return[null,...xS(T.unwrap())];else if(T instanceof FA)return xS(T.unwrap());else if(T instanceof co)return xS(T.unwrap());else if(T instanceof Zo)return xS(T._def.innerType);else return[]};class $A extends e{_parse(T){let{ctx:S}=this._processInputParams(T);if(S.parsedType!==m.object)return C(S,{code:Q.invalid_type,expected:m.object,received:S.parsedType}),d;let o=this.discriminator,f=S.data[o],A=this.optionsMap.get(f);if(!A)return C(S,{code:Q.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[o]}),d;if(S.common.async)return A._parseAsync({data:S.data,path:S.path,parent:S});else return A._parseSync({data:S.data,path:S.path,parent:S})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(T,S,o){let f=new Map;for(let A of S){let n=xS(A.shape[T]);if(!n.length)throw new Error(`A discriminator value for key \`${T}\` could not be extracted from all schema options`);for(let $ of n){if(f.has($))throw new Error(`Discriminator property ${String(T)} has duplicate value ${String($)}`);f.set($,A)}}return new $A({typeName:i.ZodDiscriminatedUnion,discriminator:T,options:S,optionsMap:f,...u(o)})}}function In(T,S){let o=vS(T),f=vS(S);if(T===S)return{valid:!0,data:T};else if(o===m.object&&f===m.object){let A=$T.objectKeys(S),n=$T.objectKeys(T).filter((F)=>A.indexOf(F)!==-1),$={...T,...S};for(let F of n){let J=In(T[F],S[F]);if(!J.valid)return{valid:!1};$[F]=J.data}return{valid:!0,data:$}}else if(o===m.array&&f===m.array){if(T.length!==S.length)return{valid:!1};let A=[];for(let n=0;n<T.length;n++){let $=T[n],F=S[n],J=In($,F);if(!J.valid)return{valid:!1};A.push(J.data)}return{valid:!0,data:A}}else if(o===m.date&&f===m.date&&+T===+S)return{valid:!0,data:T};else return{valid:!1}}class ho extends e{_parse(T){let{status:S,ctx:o}=this._processInputParams(T),f=(A,n)=>{if(Ln(A)||Ln(n))return d;let $=In(A.value,n.value);if(!$.valid)return C(o,{code:Q.invalid_intersection_types}),d;if(Cn(A)||Cn(n))S.dirty();return{status:S.value,value:$.data}};if(o.common.async)return Promise.all([this._def.left._parseAsync({data:o.data,path:o.path,parent:o}),this._def.right._parseAsync({data:o.data,path:o.path,parent:o})]).then(([A,n])=>f(A,n));else return f(this._def.left._parseSync({data:o.data,path:o.path,parent:o}),this._def.right._parseSync({data:o.data,path:o.path,parent:o}))}}ho.create=(T,S,o)=>{return new ho({left:T,right:S,typeName:i.ZodIntersection,...u(o)})};class IS extends e{_parse(T){let{status:S,ctx:o}=this._processInputParams(T);if(o.parsedType!==m.array)return C(o,{code:Q.invalid_type,expected:m.array,received:o.parsedType}),d;if(o.data.length<this._def.items.length)return C(o,{code:Q.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),d;if(!this._def.rest&&o.data.length>this._def.items.length)C(o,{code:Q.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),S.dirty();let A=[...o.data].map((n,$)=>{let F=this._def.items[$]||this._def.rest;if(!F)return null;return F._parse(new zS(o,n,o.path,$))}).filter((n)=>!!n);if(o.common.async)return Promise.all(A).then((n)=>{return uT.mergeArray(S,n)});else return uT.mergeArray(S,A)}get items(){return this._def.items}rest(T){return new IS({...this._def,rest:T})}}IS.create=(T,S)=>{if(!Array.isArray(T))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new IS({items:T,typeName:i.ZodTuple,rest:null,...u(S)})};class yf extends e{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(T){let{status:S,ctx:o}=this._processInputParams(T);if(o.parsedType!==m.object)return C(o,{code:Q.invalid_type,expected:m.object,received:o.parsedType}),d;let f=[],A=this._def.keyType,n=this._def.valueType;for(let $ in o.data)f.push({key:A._parse(new zS(o,$,o.path,$)),value:n._parse(new zS(o,o.data[$],o.path,$)),alwaysSet:$ in o.data});if(o.common.async)return uT.mergeObjectAsync(S,f);else return uT.mergeObjectSync(S,f)}get element(){return this._def.valueType}static create(T,S,o){if(S instanceof e)return new yf({keyType:T,valueType:S,typeName:i.ZodRecord,...u(o)});return new yf({keyType:GS.create(),valueType:T,typeName:i.ZodRecord,...u(S)})}}class wf extends e{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(T){let{status:S,ctx:o}=this._processInputParams(T);if(o.parsedType!==m.map)return C(o,{code:Q.invalid_type,expected:m.map,received:o.parsedType}),d;let f=this._def.keyType,A=this._def.valueType,n=[...o.data.entries()].map(([$,F],J)=>{return{key:f._parse(new zS(o,$,o.path,[J,"key"])),value:A._parse(new zS(o,F,o.path,[J,"value"]))}});if(o.common.async){let $=new Map;return Promise.resolve().then(async()=>{for(let F of n){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")S.dirty();$.set(J.value,R.value)}return{status:S.value,value:$}})}else{let $=new Map;for(let F of n){let{key:J,value:R}=F;if(J.status==="aborted"||R.status==="aborted")return d;if(J.status==="dirty"||R.status==="dirty")S.dirty();$.set(J.value,R.value)}return{status:S.value,value:$}}}}wf.create=(T,S,o)=>{return new wf({valueType:S,keyType:T,typeName:i.ZodMap,...u(o)})};class Oo extends e{_parse(T){let{status:S,ctx:o}=this._processInputParams(T);if(o.parsedType!==m.set)return C(o,{code:Q.invalid_type,expected:m.set,received:o.parsedType}),d;let f=this._def;if(f.minSize!==null){if(o.data.size<f.minSize.value)C(o,{code:Q.too_small,minimum:f.minSize.value,type:"set",inclusive:!0,exact:!1,message:f.minSize.message}),S.dirty()}if(f.maxSize!==null){if(o.data.size>f.maxSize.value)C(o,{code:Q.too_big,maximum:f.maxSize.value,type:"set",inclusive:!0,exact:!1,message:f.maxSize.message}),S.dirty()}let A=this._def.valueType;function n(F){let J=new Set;for(let R of F){if(R.status==="aborted")return d;if(R.status==="dirty")S.dirty();J.add(R.value)}return{status:S.value,value:J}}let $=[...o.data.values()].map((F,J)=>A._parse(new zS(o,F,o.path,J)));if(o.common.async)return Promise.all($).then((F)=>n(F));else return n($)}min(T,S){return new Oo({...this._def,minSize:{value:T,message:x.toString(S)}})}max(T,S){return new Oo({...this._def,maxSize:{value:T,message:x.toString(S)}})}size(T,S){return this.min(T,S).max(T,S)}nonempty(T){return this.min(1,T)}}Oo.create=(T,S)=>{return new Oo({valueType:T,minSize:null,maxSize:null,typeName:i.ZodSet,...u(S)})};class Lo extends e{constructor(){super(...arguments);this.validate=this.implement}_parse(T){let{ctx:S}=this._processInputParams(T);if(S.parsedType!==m.function)return C(S,{code:Q.invalid_type,expected:m.function,received:S.parsedType}),d;function o($,F){return AA({data:$,path:S.path,errorMaps:[S.common.contextualErrorMap,S.schemaErrorMap,fA(),Co].filter((J)=>!!J),issueData:{code:Q.invalid_arguments,argumentsError:F}})}function f($,F){return AA({data:$,path:S.path,errorMaps:[S.common.contextualErrorMap,S.schemaErrorMap,fA(),Co].filter((J)=>!!J),issueData:{code:Q.invalid_return_type,returnTypeError:F}})}let A={errorMap:S.common.contextualErrorMap},n=S.data;if(this._def.returns instanceof Mo){let $=this;return aT(async function(...F){let J=new JS([]),R=await $._def.args.parseAsync(F,A).catch((y)=>{throw J.addIssue(o(F,y)),J}),O=await Reflect.apply(n,this,R);return await $._def.returns._def.type.parseAsync(O,A).catch((y)=>{throw J.addIssue(f(O,y)),J})})}else{let $=this;return aT(function(...F){let J=$._def.args.safeParse(F,A);if(!J.success)throw new JS([o(F,J.error)]);let R=Reflect.apply(n,this,J.data),O=$._def.returns.safeParse(R,A);if(!O.success)throw new JS([f(R,O.error)]);return O.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...T){return new Lo({...this._def,args:IS.create(T).rest(iS.create())})}returns(T){return new Lo({...this._def,returns:T})}implement(T){return this.parse(T)}strictImplement(T){return this.parse(T)}static create(T,S,o){return new Lo({args:T?T:IS.create([]).rest(iS.create()),returns:S||iS.create(),typeName:i.ZodFunction,...u(o)})}}class bo extends e{get schema(){return this._def.getter()}_parse(T){let{ctx:S}=this._processInputParams(T);return this._def.getter()._parse({data:S.data,path:S.path,parent:S})}}bo.create=(T,S)=>{return new bo({getter:T,typeName:i.ZodLazy,...u(S)})};class xo extends e{_parse(T){if(T.data!==this._def.value){let S=this._getOrReturnCtx(T);return C(S,{received:S.data,code:Q.invalid_literal,expected:this._def.value}),d}return{status:"valid",value:T.data}}get value(){return this._def.value}}xo.create=(T,S)=>{return new xo({value:T,typeName:i.ZodLiteral,...u(S)})};function oJ(T,S){return new uS({values:T,typeName:i.ZodEnum,...u(S)})}class uS extends e{constructor(){super(...arguments);Of.set(this,void 0)}_parse(T){if(typeof T.data!=="string"){let S=this._getOrReturnCtx(T),o=this._def.values;return C(S,{expected:$T.joinValues(o),received:S.parsedType,code:Q.invalid_type}),d}if(!nA(this,Of,"f"))sF(this,Of,new Set(this._def.values),"f");if(!nA(this,Of,"f").has(T.data)){let S=this._getOrReturnCtx(T),o=this._def.values;return C(S,{received:S.data,code:Q.invalid_enum_value,options:o}),d}return aT(T.data)}get options(){return this._def.values}get enum(){let T={};for(let S of this._def.values)T[S]=S;return T}get Values(){let T={};for(let S of this._def.values)T[S]=S;return T}get Enum(){let T={};for(let S of this._def.values)T[S]=S;return T}extract(T,S=this._def){return uS.create(T,{...this._def,...S})}exclude(T,S=this._def){return uS.create(this.options.filter((o)=>!T.includes(o)),{...this._def,...S})}}Of=new WeakMap;uS.create=oJ;class vo extends e{constructor(){super(...arguments);Mf.set(this,void 0)}_parse(T){let S=$T.getValidEnumValues(this._def.values),o=this._getOrReturnCtx(T);if(o.parsedType!==m.string&&o.parsedType!==m.number){let f=$T.objectValues(S);return C(o,{expected:$T.joinValues(f),received:o.parsedType,code:Q.invalid_type}),d}if(!nA(this,Mf,"f"))sF(this,Mf,new Set($T.getValidEnumValues(this._def.values)),"f");if(!nA(this,Mf,"f").has(T.data)){let f=$T.objectValues(S);return C(o,{received:o.data,code:Q.invalid_enum_value,options:f}),d}return aT(T.data)}get enum(){return this._def.values}}Mf=new WeakMap;vo.create=(T,S)=>{return new vo({values:T,typeName:i.ZodNativeEnum,...u(S)})};class Mo extends e{unwrap(){return this._def.type}_parse(T){let{ctx:S}=this._processInputParams(T);if(S.parsedType!==m.promise&&S.common.async===!1)return C(S,{code:Q.invalid_type,expected:m.promise,received:S.parsedType}),d;let o=S.parsedType===m.promise?S.data:Promise.resolve(S.data);return aT(o.then((f)=>{return this._def.type.parseAsync(f,{path:S.path,errorMap:S.common.contextualErrorMap})}))}}Mo.create=(T,S)=>{return new Mo({type:T,typeName:i.ZodPromise,...u(S)})};class kS extends e{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===i.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(T){let{status:S,ctx:o}=this._processInputParams(T),f=this._def.effect||null,A={addIssue:(n)=>{if(C(o,n),n.fatal)S.abort();else S.dirty()},get path(){return o.path}};if(A.addIssue=A.addIssue.bind(A),f.type==="preprocess"){let n=f.transform(o.data,A);if(o.common.async)return Promise.resolve(n).then(async($)=>{if(S.value==="aborted")return d;let F=await this._def.schema._parseAsync({data:$,path:o.path,parent:o});if(F.status==="aborted")return d;if(F.status==="dirty")return to(F.value);if(S.value==="dirty")return to(F.value);return F});else{if(S.value==="aborted")return d;let $=this._def.schema._parseSync({data:n,path:o.path,parent:o});if($.status==="aborted")return d;if($.status==="dirty")return to($.value);if(S.value==="dirty")return to($.value);return $}}if(f.type==="refinement"){let n=($)=>{let F=f.refinement($,A);if(o.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(o.common.async===!1){let $=this._def.schema._parseSync({data:o.data,path:o.path,parent:o});if($.status==="aborted")return d;if($.status==="dirty")S.dirty();return n($.value),{status:S.value,value:$.value}}else return this._def.schema._parseAsync({data:o.data,path:o.path,parent:o}).then(($)=>{if($.status==="aborted")return d;if($.status==="dirty")S.dirty();return n($.value).then(()=>{return{status:S.value,value:$.value}})})}if(f.type==="transform")if(o.common.async===!1){let n=this._def.schema._parseSync({data:o.data,path:o.path,parent:o});if(!Fo(n))return n;let $=f.transform(n.value,A);if($ instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:S.value,value:$}}else return this._def.schema._parseAsync({data:o.data,path:o.path,parent:o}).then((n)=>{if(!Fo(n))return n;return Promise.resolve(f.transform(n.value,A)).then(($)=>({status:S.value,value:$}))});$T.assertNever(f)}}kS.create=(T,S,o)=>{return new kS({schema:T,typeName:i.ZodEffects,effect:S,...u(o)})};kS.createWithPreprocess=(T,S,o)=>{return new kS({schema:S,effect:{type:"preprocess",transform:T},typeName:i.ZodEffects,...u(o)})};class ES extends e{_parse(T){if(this._getType(T)===m.undefined)return aT(void 0);return this._def.innerType._parse(T)}unwrap(){return this._def.innerType}}ES.create=(T,S)=>{return new ES({innerType:T,typeName:i.ZodOptional,...u(S)})};class qS extends e{_parse(T){if(this._getType(T)===m.null)return aT(null);return this._def.innerType._parse(T)}unwrap(){return this._def.innerType}}qS.create=(T,S)=>{return new qS({innerType:T,typeName:i.ZodNullable,...u(S)})};class qo extends e{_parse(T){let{ctx:S}=this._processInputParams(T),o=S.data;if(S.parsedType===m.undefined)o=this._def.defaultValue();return this._def.innerType._parse({data:o,path:S.path,parent:S})}removeDefault(){return this._def.innerType}}qo.create=(T,S)=>{return new qo({innerType:T,typeName:i.ZodDefault,defaultValue:typeof S.default==="function"?S.default:()=>S.default,...u(S)})};class Zo extends e{_parse(T){let{ctx:S}=this._processInputParams(T),o={...S,common:{...S.common,issues:[]}},f=this._def.innerType._parse({data:o.data,path:o.path,parent:{...o}});if(Wf(f))return f.then((A)=>{return{status:"valid",value:A.status==="valid"?A.value:this._def.catchValue({get error(){return new JS(o.common.issues)},input:o.data})}});else return{status:"valid",value:f.status==="valid"?f.value:this._def.catchValue({get error(){return new JS(o.common.issues)},input:o.data})}}removeCatch(){return this._def.innerType}}Zo.create=(T,S)=>{return new Zo({innerType:T,typeName:i.ZodCatch,catchValue:typeof S.catch==="function"?S.catch:()=>S.catch,...u(S)})};class Kf extends e{_parse(T){if(this._getType(T)!==m.nan){let o=this._getOrReturnCtx(T);return C(o,{code:Q.invalid_type,expected:m.nan,received:o.parsedType}),d}return{status:"valid",value:T.data}}}Kf.create=(T)=>{return new Kf({typeName:i.ZodNaN,...u(T)})};var _M=Symbol("zod_brand");class FA extends e{_parse(T){let{ctx:S}=this._processInputParams(T),o=S.data;return this._def.type._parse({data:o,path:S.path,parent:S})}unwrap(){return this._def.type}}class Hf extends e{_parse(T){let{status:S,ctx:o}=this._processInputParams(T);if(o.common.async)return(async()=>{let A=await this._def.in._parseAsync({data:o.data,path:o.path,parent:o});if(A.status==="aborted")return d;if(A.status==="dirty")return S.dirty(),to(A.value);else return this._def.out._parseAsync({data:A.value,path:o.path,parent:o})})();else{let f=this._def.in._parseSync({data:o.data,path:o.path,parent:o});if(f.status==="aborted")return d;if(f.status==="dirty")return S.dirty(),{status:"dirty",value:f.value};else return this._def.out._parseSync({data:f.value,path:o.path,parent:o})}}static create(T,S){return new Hf({in:T,out:S,typeName:i.ZodPipeline})}}class co extends e{_parse(T){let S=this._def.innerType._parse(T),o=(f)=>{if(Fo(f))f.value=Object.freeze(f.value);return f};return Wf(S)?S.then((f)=>o(f)):o(S)}unwrap(){return this._def.innerType}}co.create=(T,S)=>{return new co({innerType:T,typeName:i.ZodReadonly,...u(S)})};function lF(T,S){let o=typeof T==="function"?T(S):typeof T==="string"?{message:T}:T;return typeof o==="string"?{message:o}:o}function fJ(T,S={},o){if(T)return Ro.create().superRefine((f,A)=>{var n,$;let F=T(f);if(F instanceof Promise)return F.then((J)=>{var R,O;if(!J){let k=lF(S,f),y=(O=(R=k.fatal)!==null&&R!==void 0?R:o)!==null&&O!==void 0?O:!0;A.addIssue({code:"custom",...k,fatal:y})}});if(!F){let J=lF(S,f),R=($=(n=J.fatal)!==null&&n!==void 0?n:o)!==null&&$!==void 0?$:!0;A.addIssue({code:"custom",...J,fatal:R})}return});return Ro.create()}var kM={object:QT.lazycreate},i;(function(T){T.ZodString="ZodString",T.ZodNumber="ZodNumber",T.ZodNaN="ZodNaN",T.ZodBigInt="ZodBigInt",T.ZodBoolean="ZodBoolean",T.ZodDate="ZodDate",T.ZodSymbol="ZodSymbol",T.ZodUndefined="ZodUndefined",T.ZodNull="ZodNull",T.ZodAny="ZodAny",T.ZodUnknown="ZodUnknown",T.ZodNever="ZodNever",T.ZodVoid="ZodVoid",T.ZodArray="ZodArray",T.ZodObject="ZodObject",T.ZodUnion="ZodUnion",T.ZodDiscriminatedUnion="ZodDiscriminatedUnion",T.ZodIntersection="ZodIntersection",T.ZodTuple="ZodTuple",T.ZodRecord="ZodRecord",T.ZodMap="ZodMap",T.ZodSet="ZodSet",T.ZodFunction="ZodFunction",T.ZodLazy="ZodLazy",T.ZodLiteral="ZodLiteral",T.ZodEnum="ZodEnum",T.ZodEffects="ZodEffects",T.ZodNativeEnum="ZodNativeEnum",T.ZodOptional="ZodOptional",T.ZodNullable="ZodNullable",T.ZodDefault="ZodDefault",T.ZodCatch="ZodCatch",T.ZodPromise="ZodPromise",T.ZodBranded="ZodBranded",T.ZodPipeline="ZodPipeline",T.ZodReadonly="ZodReadonly"})(i||(i={}));var yM=(T,S={message:`Input not instance of ${T.name}`})=>fJ((o)=>o instanceof T,S),AJ=GS.create,nJ=dS.create,wM=Kf.create,KM=lS.create,$J=Io.create,HM=Jo.create,XM=_f.create,GM=jo.create,YM=No.create,EM=Ro.create,zM=iS.create,QM=CS.create,DM=kf.create,UM=YS.create,VM=QT.create,BM=QT.strictCreate,tM=mo.create,LM=$A.create,CM=ho.create,IM=IS.create,jM=yf.create,NM=wf.create,mM=Oo.create,hM=Lo.create,bM=bo.create,xM=xo.create,vM=uS.create,qM=vo.create,ZM=Mo.create,uF=kS.create,cM=ES.create,rM=qS.create,pM=kS.createWithPreprocess,PM=Hf.create,gM=()=>AJ().optional(),iM=()=>nJ().optional(),dM=()=>$J().optional(),lM={string:(T)=>GS.create({...T,coerce:!0}),number:(T)=>dS.create({...T,coerce:!0}),boolean:(T)=>Io.create({...T,coerce:!0}),bigint:(T)=>lS.create({...T,coerce:!0}),date:(T)=>Jo.create({...T,coerce:!0})},uM=d,GT=Object.freeze({__proto__:null,defaultErrorMap:Co,setErrorMap:pO,getErrorMap:fA,makeIssue:AA,EMPTY_PATH:PO,addIssueToContext:C,ParseStatus:uT,INVALID:d,DIRTY:to,OK:aT,isAborted:Ln,isDirty:Cn,isValid:Fo,isAsync:Wf,get util(){return $T},get objectUtil(){return tn},ZodParsedType:m,getParsedType:vS,ZodType:e,datetimeRegex:SJ,ZodString:GS,ZodNumber:dS,ZodBigInt:lS,ZodBoolean:Io,ZodDate:Jo,ZodSymbol:_f,ZodUndefined:jo,ZodNull:No,ZodAny:Ro,ZodUnknown:iS,ZodNever:CS,ZodVoid:kf,ZodArray:YS,ZodObject:QT,ZodUnion:mo,ZodDiscriminatedUnion:$A,ZodIntersection:ho,ZodTuple:IS,ZodRecord:yf,ZodMap:wf,ZodSet:Oo,ZodFunction:Lo,ZodLazy:bo,ZodLiteral:xo,ZodEnum:uS,ZodNativeEnum:vo,ZodPromise:Mo,ZodEffects:kS,ZodTransformer:kS,ZodOptional:ES,ZodNullable:qS,ZodDefault:qo,ZodCatch:Zo,ZodNaN:Kf,BRAND:_M,ZodBranded:FA,ZodPipeline:Hf,ZodReadonly:co,custom:fJ,Schema:e,ZodSchema:e,late:kM,get ZodFirstPartyTypeKind(){return i},coerce:lM,any:EM,array:UM,bigint:KM,boolean:$J,date:HM,discriminatedUnion:LM,effect:uF,enum:vM,function:hM,instanceof:yM,intersection:CM,lazy:bM,literal:xM,map:NM,nan:wM,nativeEnum:qM,never:QM,null:YM,nullable:rM,number:nJ,object:VM,oboolean:dM,onumber:iM,optional:cM,ostring:gM,pipeline:PM,preprocess:pM,promise:ZM,record:jM,set:mM,strictObject:BM,string:AJ,symbol:XM,transformer:uF,tuple:IM,undefined:GM,union:tM,unknown:zM,void:DM,NEVER:uM,ZodIssueCode:Q,quotelessJson:rO,ZodError:JS});var eM="__vite_start_time"in globalThis,sM=typeof window!=="undefined",g5="vitest"in globalThis,QS=iF({isServer:!eM&&!sM,server:{CI:GT.string().transform((T)=>!0).optional(),POSTGRES_USER:GT.string(),POSTGRES_PASSWORD:GT.string(),POSTGRES_DATABASE:GT.string(),POSTGRES_HOST:GT.string(),POSTGRES_PORT:GT.string().transform((T)=>Number.parseInt(T,10)),BACKEND_PORT:GT.string().transform((T)=>Number.parseInt(T,10)),RUN_WORKERS_FROM_SOURCE:GT.union([GT.literal("true"),GT.literal("false")]).optional().transform((T)=>T==="true"),FRONTEND_PORT:GT.string().transform((T)=>Number.parseInt(T,10)),FRONTEND_ORIGINS:GT.string().transform((T)=>JSON.parse(T)).pipe(GT.array(GT.string())),OPENAI_API_KEY:GT.string().optional()},clientPrefix:"VITE_",client:{VITE_BACKEND_ORIGIN:GT.string(),VITE_USE_SELF_SIGNED_CERTIFICATE:GT.union([GT.literal("true"),GT.literal("false")]).optional().transform((T)=>T==="true")},runtimeEnv:import.meta.env,emptyStringAsUndefined:!0});var JJ=jn(import.meta.dirname,"../dev"),RJ=QS.VITE_USE_SELF_SIGNED_CERTIFICATE?{cert:FJ(jn(JJ,"./cert.pem"),"utf-8"),key:FJ(jn(JJ,"./key.pem"),"utf-8")}:void 0;import T_ from"path";var W=Symbol.for("drizzle:entityKind"),s5=Symbol.for("drizzle:hasOwnEntityKind");function K(T,S){if(!T||typeof T!=="object")return!1;if(T instanceof S)return!0;if(!Object.prototype.hasOwnProperty.call(S,W))throw new Error(`Class "${S.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 o=Object.getPrototypeOf(T).constructor;if(o)while(o){if(W in o&&o[W]===S[W])return!0;o=Object.getPrototypeOf(o)}return!1}class _T{constructor(T,S){this.table=T,this.config=S,this.name=S.name,this.keyAsName=S.keyAsName,this.notNull=S.notNull,this.default=S.default,this.defaultFn=S.defaultFn,this.onUpdateFn=S.onUpdateFn,this.hasDefault=S.hasDefault,this.primary=S.primaryKey,this.isUnique=S.isUnique,this.uniqueName=S.uniqueName,this.uniqueType=S.uniqueType,this.dataType=S.dataType,this.columnType=S.columnType,this.generated=S.generated,this.generatedIdentity=S.generatedIdentity}static[W]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue(T){return T}mapToDriverValue(T){return T}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}class Nn{static[W]="ColumnBuilder";config;constructor(T,S,o){this.config={name:T,keyAsName:T==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:S,columnType:o,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(T){return this.config.default=T,this.config.hasDefault=!0,this}$defaultFn(T){return this.config.defaultFn=T,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(T){return this.config.onUpdateFn=T,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(T){if(this.config.name!=="")return;this.config.name=T}}var DS=Symbol.for("drizzle:Name");class mn{static[W]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(T,S){if(this.reference=()=>{let{name:o,columns:f,foreignColumns:A}=T();return{name:o,columns:f,foreignTable:A[0].table,foreignColumns:A}},S)this._onUpdate=S.onUpdate,this._onDelete=S.onDelete}onUpdate(T){return this._onUpdate=T===void 0?"no action":T,this}onDelete(T){return this._onDelete=T===void 0?"no action":T,this}build(T){return new OJ(T,this)}}class OJ{constructor(T,S){this.table=T,this.reference=S.reference,this.onUpdate=S._onUpdate,this.onDelete=S._onDelete}static[W]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:T,columns:S,foreignColumns:o}=this.reference(),f=S.map(($)=>$.name),A=o.map(($)=>$.name),n=[this.table[DS],...f,o[0].table[DS],...A];return T??`${n.join("_")}_fk`}}function JA(T,...S){return T(...S)}function MJ(T,S){return`${T[DS]}_${S.join("_")}_unique`}function WJ(T,S,o){for(let f=S;f<T.length;f++){let A=T[f];if(A==="\\"){f++;continue}if(A==='"')return[T.slice(S,f).replace(/\\/g,""),f+1];if(o)continue;if(A===","||A==="}")return[T.slice(S,f).replace(/\\/g,""),f]}return[T.slice(S).replace(/\\/g,""),T.length]}function _J(T,S=0){let o=[],f=S,A=!1;while(f<T.length){let n=T[f];if(n===","){if(A||f===S)o.push("");A=!0,f++;continue}if(A=!1,n==="\\"){f+=2;continue}if(n==='"'){let[J,R]=WJ(T,f+1,!0);o.push(J),f=R;continue}if(n==="}")return[o,f+1];if(n==="{"){let[J,R]=_J(T,f+1);o.push(J),f=R;continue}let[$,F]=WJ(T,f,!1);o.push($),f=F}return[o,f]}function kJ(T){let[S]=_J(T,1);return S}function hn(T){return`{${T.map((S)=>{if(Array.isArray(S))return hn(S);if(typeof S==="string")return`"${S.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${S}`}).join(",")}}`}class h extends Nn{foreignKeyConfigs=[];static[W]="PgColumnBuilder";array(T){return new wJ(this.config.name,this,T)}references(T,S={}){return this.foreignKeyConfigs.push({ref:T,actions:S}),this}unique(T,S){return this.config.isUnique=!0,this.config.uniqueName=T,this.config.uniqueType=S?.nulls,this}generatedAlwaysAs(T){return this.config.generated={as:T,type:"always",mode:"stored"},this}buildForeignKeys(T,S){return this.foreignKeyConfigs.map(({ref:o,actions:f})=>{return JA((A,n)=>{let $=new mn(()=>{let F=A();return{columns:[T],foreignColumns:[F]}});if(n.onUpdate)$.onUpdate(n.onUpdate);if(n.onDelete)$.onDelete(n.onDelete);return $.build(S)},o,f)})}buildExtraConfigColumn(T){return new yJ(T,this.config)}}class B extends _T{constructor(T,S){if(!S.uniqueName)S.uniqueName=MJ(T,[S.name]);super(T,S);this.table=T}static[W]="PgColumn"}class yJ extends B{static[W]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op(T){return this.indexConfig.opClass=T,this}}class Xf{static[W]="IndexedColumn";constructor(T,S,o,f){this.name=T,this.keyAsName=S,this.type=o,this.indexConfig=f}name;keyAsName;type;indexConfig}class wJ extends h{static[W]="PgArrayBuilder";constructor(T,S,o){super(T,"array","PgArray");this.config.baseBuilder=S,this.config.size=o}build(T){let S=this.config.baseBuilder.build(T);return new bn(T,this.config,S)}}class bn extends B{constructor(T,S,o,f){super(T,S);this.baseColumn=o,this.range=f,this.size=S.size}size;static[W]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(T){if(typeof T==="string")T=kJ(T);return T.map((S)=>this.baseColumn.mapFromDriverValue(S))}mapToDriverValue(T,S=!1){let o=T.map((f)=>f===null?null:K(this.baseColumn,bn)?this.baseColumn.mapToDriverValue(f,!0):this.baseColumn.mapToDriverValue(f));if(S)return o;return hn(o)}}var xn=Symbol.for("drizzle:isPgEnum");function KJ(T){return!!T&&typeof T==="function"&&xn in T&&T[xn]===!0}class HJ extends h{static[W]="PgEnumColumnBuilder";constructor(T,S){super(T,"string","PgEnumColumn");this.config.enum=S}build(T){return new XJ(T,this.config)}}class XJ extends B{static[W]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(T,S){super(T,S);this.enum=S.enum}getSQLType(){return this.enum.enumName}}function RA(T,S){return aM(T,S,void 0)}function aM(T,S,o){let f=Object.assign((A)=>new HJ(A??"",f),{enumName:T,enumValues:S,schema:o,[xn]:!0});return f}class xT{static[W]="Subquery";constructor(T,S,o,f=!1){this._={brand:"Subquery",sql:T,selectedFields:S,alias:o,isWith:f}}}class Gf extends xT{static[W]="WithSubquery"}var GJ="0.39.3";var vn,qn,kT={startActiveSpan(T,S){if(!vn)return S();if(!qn)qn=vn.trace.getTracer("drizzle-orm",GJ);return JA((o,f)=>f.startActiveSpan(T,(A)=>{try{return S(A)}catch(n){throw A.setStatus({code:o.SpanStatusCode.ERROR,message:n instanceof Error?n.message:"Unknown error"}),n}finally{A.end()}}),vn,qn)}};var KT=Symbol.for("drizzle:ViewBaseConfig");var OA=Symbol.for("drizzle:Schema"),MA=Symbol.for("drizzle:Columns"),YJ=Symbol.for("drizzle:ExtraConfigColumns"),Zn=Symbol.for("drizzle:OriginalName"),cn=Symbol.for("drizzle:BaseName"),Yf=Symbol.for("drizzle:IsAlias"),EJ=Symbol.for("drizzle:ExtraConfigBuilder"),TW=Symbol.for("drizzle:IsDrizzleTable");class j{static[W]="Table";static Symbol={Name:DS,Schema:OA,OriginalName:Zn,Columns:MA,ExtraConfigColumns:YJ,BaseName:cn,IsAlias:Yf,ExtraConfigBuilder:EJ};[DS];[Zn];[OA];[MA];[YJ];[cn];[Yf]=!1;[TW]=!0;[EJ]=void 0;constructor(T,S,o){this[DS]=this[Zn]=T,this[OA]=S,this[cn]=o}}function qT(T){return T[DS]}function Wo(T){return`${T[OA]??"public"}.${T[DS]}`}function rn(T){return T!==null&&T!==void 0&&typeof T.getSQL==="function"}function SW(T){let S={sql:"",params:[]};for(let o of T)if(S.sql+=o.sql,S.params.push(...o.params),o.typings?.length){if(!S.typings)S.typings=[];S.typings.push(...o.typings)}return S}class vT{static[W]="StringChunk";value;constructor(T){this.value=Array.isArray(T)?T:[T]}getSQL(){return new N([this])}}class N{constructor(T){this.queryChunks=T}static[W]="SQL";decoder=QJ;shouldInlineParams=!1;append(T){return this.queryChunks.push(...T.queryChunks),this}toQuery(T){return kT.startActiveSpan("drizzle.buildSQL",(S)=>{let o=this.buildQueryFromSourceParams(this.queryChunks,T);return S?.setAttributes({"drizzle.query.text":o.sql,"drizzle.query.params":JSON.stringify(o.params)}),o})}buildQueryFromSourceParams(T,S){let o=Object.assign({},S,{inlineParams:S.inlineParams||this.shouldInlineParams,paramStartIndex:S.paramStartIndex||{value:0}}),{casing:f,escapeName:A,escapeParam:n,prepareTyping:$,inlineParams:F,paramStartIndex:J}=o;return SW(T.map((R)=>{if(K(R,vT))return{sql:R.value.join(""),params:[]};if(K(R,WA))return{sql:A(R.value),params:[]};if(R===void 0)return{sql:"",params:[]};if(Array.isArray(R)){let O=[new vT("(")];for(let[k,y]of R.entries())if(O.push(y),k<R.length-1)O.push(new vT(", "));return O.push(new vT(")")),this.buildQueryFromSourceParams(O,o)}if(K(R,N))return this.buildQueryFromSourceParams(R.queryChunks,{...o,inlineParams:F||R.shouldInlineParams});if(K(R,j)){let O=R[j.Symbol.Schema],k=R[j.Symbol.Name];return{sql:O===void 0||R[Yf]?A(k):A(O)+"."+A(k),params:[]}}if(K(R,_T)){let O=f.getColumnCasing(R);if(S.invokeSource==="indexes")return{sql:A(O),params:[]};let k=R.table[j.Symbol.Schema];return{sql:R.table[Yf]||k===void 0?A(R.table[j.Symbol.Name])+"."+A(O):A(k)+"."+A(R.table[j.Symbol.Name])+"."+A(O),params:[]}}if(K(R,nS)){let O=R[KT].schema,k=R[KT].name;return{sql:O===void 0||R[KT].isAlias?A(k):A(O)+"."+A(k),params:[]}}if(K(R,RS)){if(K(R.value,eS))return{sql:n(J.value++,R),params:[R],typings:["none"]};let O=R.value===null?null:R.encoder.mapToDriverValue(R.value);if(K(O,N))return this.buildQueryFromSourceParams([O],o);if(F)return{sql:this.mapInlineParam(O,o),params:[]};let k=["none"];if($)k=[$(R.encoder)];return{sql:n(J.value++,O),params:[O],typings:k}}if(K(R,eS))return{sql:n(J.value++,R),params:[R],typings:["none"]};if(K(R,N.Aliased)&&R.fieldAlias!==void 0)return{sql:A(R.fieldAlias),params:[]};if(K(R,xT)){if(R._.isWith)return{sql:A(R._.alias),params:[]};return this.buildQueryFromSourceParams([new vT("("),R._.sql,new vT(") "),new WA(R._.alias)],o)}if(KJ(R)){if(R.schema)return{sql:A(R.schema)+"."+A(R.enumName),params:[]};return{sql:A(R.enumName),params:[]}}if(rn(R)){if(R.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([R.getSQL()],o);return this.buildQueryFromSourceParams([new vT("("),R.getSQL(),new vT(")")],o)}if(F)return{sql:this.mapInlineParam(R,o),params:[]};return{sql:n(J.value++,R),params:[R],typings:["none"]}}))}mapInlineParam(T,{escapeString:S}){if(T===null)return"null";if(typeof T==="number"||typeof T==="boolean")return T.toString();if(typeof T==="string")return S(T);if(typeof T==="object"){let o=T.toString();if(o==="[object Object]")return S(JSON.stringify(T));return S(o)}throw new Error("Unexpected param value: "+T)}getSQL(){return this}as(T){if(T===void 0)return this;return new N.Aliased(this,T)}mapWith(T){return this.decoder=typeof T==="function"?{mapFromDriverValue:T}:T,this}inlineParams(){return this.shouldInlineParams=!0,this}if(T){return T?this:void 0}}class WA{constructor(T){this.value=T}static[W]="Name";brand;getSQL(){return new N([this])}}function zJ(T){return typeof T==="object"&&T!==null&&"mapToDriverValue"in T&&typeof T.mapToDriverValue==="function"}var QJ={mapFromDriverValue:(T)=>T},DJ={mapToDriverValue:(T)=>T},q6={...QJ,...DJ};class RS{constructor(T,S=DJ){this.value=T,this.encoder=S}static[W]="Param";brand;getSQL(){return new N([this])}}function _(T,...S){let o=[];if(S.length>0||T.length>0&&T[0]!=="")o.push(new vT(T[0]));for(let[f,A]of S.entries())o.push(A,new vT(T[f+1]));return new N(o)}((T)=>{function S(){return new N([])}T.empty=S;function o(J){return new N(J)}T.fromList=o;function f(J){return new N([new vT(J)])}T.raw=f;function A(J,R){let O=[];for(let[k,y]of J.entries()){if(k>0&&R!==void 0)O.push(R);O.push(y)}return new N(O)}T.join=A;function n(J){return new WA(J)}T.identifier=n;function $(J){return new eS(J)}T.placeholder=$;function F(J,R){return new RS(J,R)}T.param=F})(_||(_={}));((T)=>{class S{constructor(o,f){this.sql=o,this.fieldAlias=f}static[W]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new S(this.sql,this.fieldAlias)}}T.Aliased=S})(N||(N={}));class eS{constructor(T){this.name=T}static[W]="Placeholder";getSQL(){return new N([this])}}function pn(T,S){return T.map((o)=>{if(K(o,eS)){if(!(o.name in S))throw new Error(`No value for placeholder "${o.name}" was provided`);return S[o.name]}if(K(o,RS)&&K(o.value,eS)){if(!(o.value.name in S))throw new Error(`No value for placeholder "${o.value.name}" was provided`);return o.encoder.mapToDriverValue(S[o.value.name])}return o})}var oW=Symbol.for("drizzle:IsDrizzleView");class nS{static[W]="View";[KT];[oW]=!0;constructor({name:T,schema:S,selectedFields:o,query:f}){this[KT]={name:T,originalName:T,schema:S,selectedFields:o,query:f,isExisting:!f,isAlias:!1}}getSQL(){return new N([this])}}_T.prototype.getSQL=function(){return new N([this])};j.prototype.getSQL=function(){return new N([this])};xT.prototype.getSQL=function(){return new N([this])};class ro{constructor(T){this.table=T}static[W]="ColumnAliasProxyHandler";get(T,S){if(S==="table")return this.table;return T[S]}}class Ef{constructor(T,S){this.alias=T,this.replaceOriginalName=S}static[W]="TableAliasProxyHandler";get(T,S){if(S===j.Symbol.IsAlias)return!0;if(S===j.Symbol.Name)return this.alias;if(this.replaceOriginalName&&S===j.Symbol.OriginalName)return this.alias;if(S===KT)return{...T[KT],name:this.alias,isAlias:!0};if(S===j.Symbol.Columns){let f=T[j.Symbol.Columns];if(!f)return f;let A={};return Object.keys(f).map((n)=>{A[n]=new Proxy(f[n],new ro(new Proxy(T,this)))}),A}let o=T[S];if(K(o,_T))return new Proxy(o,new ro(new Proxy(T,this)));return o}}function _A(T,S){return new Proxy(T,new Ef(S,!1))}function jS(T,S){return new Proxy(T,new ro(new Proxy(T.table,new Ef(S,!1))))}function Pn(T,S){return new N.Aliased(zf(T.sql,S),T.fieldAlias)}function zf(T,S){return _.join(T.queryChunks.map((o)=>{if(K(o,_T))return jS(o,S);if(K(o,N))return zf(o,S);if(K(o,N.Aliased))return Pn(o,S);return o}))}class kA extends Error{static[W]="DrizzleError";constructor({message:T,cause:S}){super(T);this.name="DrizzleError",this.cause=S}}class gn extends kA{static[W]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}function $S(T,S){if(zJ(S)&&!rn(T)&&!K(T,RS)&&!K(T,eS)&&!K(T,_T)&&!K(T,j)&&!K(T,nS))return new RS(T,S);return T}var yA=(T,S)=>{return _`${T} = ${$S(S,T)}`},UJ=(T,S)=>{return _`${T} <> ${$S(S,T)}`};function Qf(...T){let S=T.filter((o)=>o!==void 0);if(S.length===0)return;if(S.length===1)return new N(S);return new N([new vT("("),_.join(S,new vT(" and ")),new vT(")")])}function VJ(...T){let S=T.filter((o)=>o!==void 0);if(S.length===0)return;if(S.length===1)return new N(S);return new N([new vT("("),_.join(S,new vT(" or ")),new vT(")")])}function BJ(T){return _`not ${T}`}var tJ=(T,S)=>{return _`${T} > ${$S(S,T)}`},LJ=(T,S)=>{return _`${T} >= ${$S(S,T)}`},CJ=(T,S)=>{return _`${T} < ${$S(S,T)}`},IJ=(T,S)=>{return _`${T} <= ${$S(S,T)}`};function jJ(T,S){if(Array.isArray(S)){if(S.length===0)return _`false`;return _`${T} in ${S.map((o)=>$S(o,T))}`}return _`${T} in ${$S(S,T)}`}function NJ(T,S){if(Array.isArray(S)){if(S.length===0)return _`true`;return _`${T} not in ${S.map((o)=>$S(o,T))}`}return _`${T} not in ${$S(S,T)}`}function mJ(T){return _`${T} is null`}function hJ(T){return _`${T} is not null`}function bJ(T){return _`exists ${T}`}function xJ(T){return _`not exists ${T}`}function vJ(T,S,o){return _`${T} between ${$S(S,T)} and ${$S(o,T)}`}function qJ(T,S,o){return _`${T} not between ${$S(S,T)} and ${$S(o,T)}`}function ZJ(T,S){return _`${T} like ${S}`}function cJ(T,S){return _`${T} not like ${S}`}function rJ(T,S){return _`${T} ilike ${S}`}function pJ(T,S){return _`${T} not ilike ${S}`}function PJ(T){return _`${T} asc`}function gJ(T){return _`${T} desc`}class iJ{static[W]="ConsoleLogWriter";write(T){console.log(T)}}class dn{static[W]="DefaultLogger";writer;constructor(T){this.writer=T?.writer??new iJ}logQuery(T,S){let o=S.map((A)=>{try{return JSON.stringify(A)}catch{return String(A)}}),f=o.length?` -- params: [${o.join(", ")}]`:"";this.writer.write(`Query: ${T}${f}`)}}class ln{static[W]="NoopLogger";logQuery(){}}class TS{static[W]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(T){return this.then(void 0,T)}finally(T){return this.then((S)=>{return T?.(),S},(S)=>{throw T?.(),S})}then(T,S){return this.execute().then(T,S)}}function dJ(T,S,o){let f={},A=T.reduce((n,{path:$,field:F},J)=>{let R;if(K(F,_T))R=F;else if(K(F,N))R=F.decoder;else R=F.sql.decoder;let O=n;for(let[k,y]of $.entries())if(k<$.length-1){if(!(y in O))O[y]={};O=O[y]}else{let H=S[J],E=O[y]=H===null?null:R.mapFromDriverValue(H);if(o&&K(F,_T)&&$.length===2){let G=$[0];if(!(G in f))f[G]=E===null?qT(F.table):!1;else if(typeof f[G]==="string"&&f[G]!==qT(F.table))f[G]=!1}}return n},{});if(o&&Object.keys(f).length>0){for(let[n,$]of Object.entries(f))if(typeof $==="string"&&!o[$])A[n]=null}return A}function yS(T,S){return Object.entries(T).reduce((o,[f,A])=>{if(typeof f!=="string")return o;let n=S?[...S,f]:[f];if(K(A,_T)||K(A,N)||K(A,N.Aliased))o.push({path:n,field:A});else if(K(A,j))o.push(...yS(A[j.Symbol.Columns],n));else o.push(...yS(A,n));return o},[])}function Df(T,S){let o=Object.keys(T),f=Object.keys(S);if(o.length!==f.length)return!1;for(let[A,n]of o.entries())if(n!==f[A])return!1;return!0}function wA(T,S){let o=Object.entries(S).filter(([,f])=>f!==void 0).map(([f,A])=>{if(K(A,N)||K(A,_T))return[f,A];else return[f,new RS(A,T[j.Symbol.Columns][f])]});if(o.length===0)throw new Error("No values to set");return Object.fromEntries(o)}function lJ(T,S){for(let o of S)for(let f of Object.getOwnPropertyNames(o.prototype)){if(f==="constructor")continue;Object.defineProperty(T.prototype,f,Object.getOwnPropertyDescriptor(o.prototype,f)||Object.create(null))}}function uJ(T){return T[j.Symbol.Columns]}function ZS(T){return K(T,xT)?T._.alias:K(T,nS)?T[KT].name:K(T,N)?void 0:T[j.Symbol.IsAlias]?T[j.Symbol.Name]:T[j.Symbol.BaseName]}function AT(T,S){return{name:typeof T==="string"&&T.length>0?T:"",config:typeof T==="object"?T:S}}function eJ(T){if(typeof T!=="object"||T===null)return!1;if(T.constructor.name!=="Object")return!1;if("logger"in T){let S=typeof T.logger;if(S!=="boolean"&&(S!=="object"||typeof T.logger.logQuery!=="function")&&S!=="undefined")return!1;return!0}if("schema"in T){let S=typeof T.logger;if(S!=="object"&&S!=="undefined")return!1;return!0}if("casing"in T){let S=typeof T.logger;if(S!=="string"&&S!=="undefined")return!1;return!0}if("mode"in T){if(T.mode!=="default"||T.mode!=="planetscale"||T.mode!==void 0)return!1;return!0}if("connection"in T){let S=typeof T.connection;if(S!=="string"&&S!=="object"&&S!=="undefined")return!1;return!0}if("client"in T){let S=typeof T.client;if(S!=="object"&&S!=="function"&&S!=="undefined")return!1;return!0}if(Object.keys(T).length===0)return!0;return!1}class sS extends h{static[W]="PgIntColumnBaseBuilder";generatedAlwaysAsIdentity(T){if(T){let{name:S,...o}=T;this.config.generatedIdentity={type:"always",sequenceName:S,sequenceOptions:o}}else this.config.generatedIdentity={type:"always"};return this.config.hasDefault=!0,this.config.notNull=!0,this}generatedByDefaultAsIdentity(T){if(T){let{name:S,...o}=T;this.config.generatedIdentity={type:"byDefault",sequenceName:S,sequenceOptions:o}}else this.config.generatedIdentity={type:"byDefault"};return this.config.hasDefault=!0,this.config.notNull=!0,this}}class sJ extends sS{static[W]="PgBigInt53Builder";constructor(T){super(T,"number","PgBigInt53")}build(T){return new aJ(T,this.config)}}class aJ extends B{static[W]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(T){if(typeof T==="number")return T;return Number(T)}}class TR extends sS{static[W]="PgBigInt64Builder";constructor(T){super(T,"bigint","PgBigInt64")}build(T){return new SR(T,this.config)}}class SR extends B{static[W]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(T){return BigInt(T)}}function oR(T,S){let{name:o,config:f}=AT(T,S);if(f.mode==="number")return new sJ(o);return new TR(o)}class fR extends h{static[W]="PgBigSerial53Builder";constructor(T){super(T,"number","PgBigSerial53");this.config.hasDefault=!0,this.config.notNull=!0}build(T){return new AR(T,this.config)}}class AR extends B{static[W]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(T){if(typeof T==="number")return T;return Number(T)}}class nR extends h{static[W]="PgBigSerial64Builder";constructor(T){super(T,"bigint","PgBigSerial64");this.config.hasDefault=!0}build(T){return new $R(T,this.config)}}class $R extends B{static[W]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(T){return BigInt(T)}}function FR(T,S){let{name:o,config:f}=AT(T,S);if(f.mode==="number")return new fR(o);return new nR(o)}class JR extends h{static[W]="PgBooleanBuilder";constructor(T){super(T,"boolean","PgBoolean")}build(T){return new RR(T,this.config)}}class RR extends B{static[W]="PgBoolean";getSQLType(){return"boolean"}}function Uf(T){return new JR(T??"")}class OR extends h{static[W]="PgCharBuilder";constructor(T,S){super(T,"string","PgChar");this.config.length=S.length,this.config.enumValues=S.enum}build(T){return new MR(T,this.config)}}class MR extends B{static[W]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}}function WR(T,S={}){let{name:o,config:f}=AT(T,S);return new OR(o,f)}class _R extends h{static[W]="PgCidrBuilder";constructor(T){super(T,"string","PgCidr")}build(T){return new kR(T,this.config)}}class kR extends B{static[W]="PgCidr";getSQLType(){return"cidr"}}function yR(T){return new _R(T??"")}class wR extends h{static[W]="PgCustomColumnBuilder";constructor(T,S,o){super(T,"custom","PgCustomColumn");this.config.fieldConfig=S,this.config.customTypeParams=o}build(T){return new KR(T,this.config)}}class KR extends B{static[W]="PgCustomColumn";sqlName;mapTo;mapFrom;constructor(T,S){super(T,S);this.sqlName=S.customTypeParams.dataType(S.fieldConfig),this.mapTo=S.customTypeParams.toDriver,this.mapFrom=S.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(T){return typeof this.mapFrom==="function"?this.mapFrom(T):T}mapToDriverValue(T){return typeof this.mapTo==="function"?this.mapTo(T):T}}function HR(T){return(S,o)=>{let{name:f,config:A}=AT(S,o);return new wR(f,A,T)}}class cS extends h{static[W]="PgDateColumnBaseBuilder";defaultNow(){return this.default(_`now()`)}}class XR extends cS{static[W]="PgDateBuilder";constructor(T){super(T,"date","PgDate")}build(T){return new KA(T,this.config)}}class KA extends B{static[W]="PgDate";getSQLType(){return"date"}mapFromDriverValue(T){return new Date(T)}mapToDriverValue(T){return T.toISOString()}}class GR extends cS{static[W]="PgDateStringBuilder";constructor(T){super(T,"string","PgDateString")}build(T){return new HA(T,this.config)}}class HA extends B{static[W]="PgDateString";getSQLType(){return"date"}}function YR(T,S){let{name:o,config:f}=AT(T,S);if(f?.mode==="date")return new XR(o);return new GR(o)}class ER extends h{static[W]="PgDoublePrecisionBuilder";constructor(T){super(T,"number","PgDoublePrecision")}build(T){return new zR(T,this.config)}}class zR extends B{static[W]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(T){if(typeof T==="string")return Number.parseFloat(T);return T}}function QR(T){return new ER(T??"")}class DR extends h{static[W]="PgInetBuilder";constructor(T){super(T,"string","PgInet")}build(T){return new UR(T,this.config)}}class UR extends B{static[W]="PgInet";getSQLType(){return"inet"}}function VR(T){return new DR(T??"")}class BR extends sS{static[W]="PgIntegerBuilder";constructor(T){super(T,"number","PgInteger")}build(T){return new tR(T,this.config)}}class tR extends B{static[W]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(T){if(typeof T==="string")return Number.parseInt(T);return T}}function XA(T){return new BR(T??"")}class LR extends h{static[W]="PgIntervalBuilder";constructor(T,S){super(T,"string","PgInterval");this.config.intervalConfig=S}build(T){return new CR(T,this.config)}}class CR extends B{static[W]="PgInterval";fields=this.config.intervalConfig.fields;precision=this.config.intervalConfig.precision;getSQLType(){let T=this.fields?` ${this.fields}`:"",S=this.precision?`(${this.precision})`:"";return`interval${T}${S}`}}function IR(T,S={}){let{name:o,config:f}=AT(T,S);return new LR(o,f)}class jR extends h{static[W]="PgJsonBuilder";constructor(T){super(T,"json","PgJson")}build(T){return new GA(T,this.config)}}class GA extends B{static[W]="PgJson";constructor(T,S){super(T,S)}getSQLType(){return"json"}mapToDriverValue(T){return JSON.stringify(T)}mapFromDriverValue(T){if(typeof T==="string")try{return JSON.parse(T)}catch{return T}return T}}function NR(T){return new jR(T??"")}class mR extends h{static[W]="PgJsonbBuilder";constructor(T){super(T,"json","PgJsonb")}build(T){return new YA(T,this.config)}}class YA extends B{static[W]="PgJsonb";constructor(T,S){super(T,S)}getSQLType(){return"jsonb"}mapToDriverValue(T){return JSON.stringify(T)}mapFromDriverValue(T){if(typeof T==="string")try{return JSON.parse(T)}catch{return T}return T}}function hR(T){return new mR(T??"")}class bR extends h{static[W]="PgLineBuilder";constructor(T){super(T,"array","PgLine")}build(T){return new xR(T,this.config)}}class xR extends B{static[W]="PgLine";getSQLType(){return"line"}mapFromDriverValue(T){let[S,o,f]=T.slice(1,-1).split(",");return[Number.parseFloat(S),Number.parseFloat(o),Number.parseFloat(f)]}mapToDriverValue(T){return`{${T[0]},${T[1]},${T[2]}}`}}class vR extends h{static[W]="PgLineABCBuilder";constructor(T){super(T,"json","PgLineABC")}build(T){return new qR(T,this.config)}}class qR extends B{static[W]="PgLineABC";getSQLType(){return"line"}mapFromDriverValue(T){let[S,o,f]=T.slice(1,-1).split(",");return{a:Number.parseFloat(S),b:Number.parseFloat(o),c:Number.parseFloat(f)}}mapToDriverValue(T){return`{${T.a},${T.b},${T.c}}`}}function ZR(T,S){let{name:o,config:f}=AT(T,S);if(!f?.mode||f.mode==="tuple")return new bR(o);return new vR(o)}class cR extends h{static[W]="PgMacaddrBuilder";constructor(T){super(T,"string","PgMacaddr")}build(T){return new rR(T,this.config)}}class rR extends B{static[W]="PgMacaddr";getSQLType(){return"macaddr"}}function pR(T){return new cR(T??"")}class PR extends h{static[W]="PgMacaddr8Builder";constructor(T){super(T,"string","PgMacaddr8")}build(T){return new gR(T,this.config)}}class gR extends B{static[W]="PgMacaddr8";getSQLType(){return"macaddr8"}}function iR(T){return new PR(T??"")}class dR extends h{static[W]="PgNumericBuilder";constructor(T,S,o){super(T,"string","PgNumeric");this.config.precision=S,this.config.scale=o}build(T){return new EA(T,this.config)}}class EA extends B{static[W]="PgNumeric";precision;scale;constructor(T,S){super(T,S);this.precision=S.precision,this.scale=S.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 lR(T,S){let{name:o,config:f}=AT(T,S);return new dR(o,f?.precision,f?.scale)}class uR extends h{static[W]="PgPointTupleBuilder";constructor(T){super(T,"array","PgPointTuple")}build(T){return new eR(T,this.config)}}class eR extends B{static[W]="PgPointTuple";getSQLType(){return"point"}mapFromDriverValue(T){if(typeof T==="string"){let[S,o]=T.slice(1,-1).split(",");return[Number.parseFloat(S),Number.parseFloat(o)]}return[T.x,T.y]}mapToDriverValue(T){return`(${T[0]},${T[1]})`}}class sR extends h{static[W]="PgPointObjectBuilder";constructor(T){super(T,"json","PgPointObject")}build(T){return new aR(T,this.config)}}class aR extends B{static[W]="PgPointObject";getSQLType(){return"point"}mapFromDriverValue(T){if(typeof T==="string"){let[S,o]=T.slice(1,-1).split(",");return{x:Number.parseFloat(S),y:Number.parseFloat(o)}}return T}mapToDriverValue(T){return`(${T.x},${T.y})`}}function T0(T,S){let{name:o,config:f}=AT(T,S);if(!f?.mode||f.mode==="tuple")return new uR(o);return new sR(o)}function fW(T){let S=[];for(let o=0;o<T.length;o+=2)S.push(Number.parseInt(T.slice(o,o+2),16));return new Uint8Array(S)}function S0(T,S){let o=new ArrayBuffer(8),f=new DataView(o);for(let A=0;A<8;A++)f.setUint8(A,T[S+A]);return f.getFloat64(0,!0)}function un(T){let S=fW(T),o=0,f=S[o];o+=1;let A=new DataView(S.buffer),n=A.getUint32(o,f===1);o+=4;let $;if(n&536870912)$=A.getUint32(o,f===1),o+=4;if((n&65535)===1){let F=S0(S,o);o+=8;let J=S0(S,o);return o+=8,[F,J]}throw new Error("Unsupported geometry type")}class o0 extends h{static[W]="PgGeometryBuilder";constructor(T){super(T,"array","PgGeometry")}build(T){return new f0(T,this.config)}}class f0 extends B{static[W]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(T){return un(T)}mapToDriverValue(T){return`point(${T[0]} ${T[1]})`}}class A0 extends h{static[W]="PgGeometryObjectBuilder";constructor(T){super(T,"json","PgGeometryObject")}build(T){return new n0(T,this.config)}}class n0 extends B{static[W]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(T){let S=un(T);return{x:S[0],y:S[1]}}mapToDriverValue(T){return`point(${T.x} ${T.y})`}}function $0(T,S){let{name:o,config:f}=AT(T,S);if(!f?.mode||f.mode==="tuple")return new o0(o);return new A0(o)}class F0 extends h{static[W]="PgRealBuilder";constructor(T,S){super(T,"number","PgReal");this.config.length=S}build(T){return new J0(T,this.config)}}class J0 extends B{static[W]="PgReal";constructor(T,S){super(T,S)}getSQLType(){return"real"}mapFromDriverValue=(T)=>{if(typeof T==="string")return Number.parseFloat(T);return T}}function R0(T){return new F0(T??"")}class O0 extends h{static[W]="PgSerialBuilder";constructor(T){super(T,"number","PgSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(T){return new M0(T,this.config)}}class M0 extends B{static[W]="PgSerial";getSQLType(){return"serial"}}function W0(T){return new O0(T??"")}class _0 extends sS{static[W]="PgSmallIntBuilder";constructor(T){super(T,"number","PgSmallInt")}build(T){return new k0(T,this.config)}}class k0 extends B{static[W]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=(T)=>{if(typeof T==="string")return Number(T);return T}}function y0(T){return new _0(T??"")}class w0 extends h{static[W]="PgSmallSerialBuilder";constructor(T){super(T,"number","PgSmallSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(T){return new K0(T,this.config)}}class K0 extends B{static[W]="PgSmallSerial";getSQLType(){return"smallserial"}}function H0(T){return new w0(T??"")}class X0 extends h{static[W]="PgTextBuilder";constructor(T,S){super(T,"string","PgText");this.config.enumValues=S.enum}build(T){return new G0(T,this.config)}}class G0 extends B{static[W]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function Y0(T,S={}){let{name:o,config:f}=AT(T,S);return new X0(o,f)}class E0 extends cS{constructor(T,S,o){super(T,"string","PgTime");this.withTimezone=S,this.precision=o,this.config.withTimezone=S,this.config.precision=o}static[W]="PgTimeBuilder";build(T){return new zA(T,this.config)}}class zA extends B{static[W]="PgTime";withTimezone;precision;constructor(T,S){super(T,S);this.withTimezone=S.withTimezone,this.precision=S.precision}getSQLType(){return`time${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function z0(T,S={}){let{name:o,config:f}=AT(T,S);return new E0(o,f.withTimezone??!1,f.precision)}class Q0 extends cS{static[W]="PgTimestampBuilder";constructor(T,S,o){super(T,"date","PgTimestamp");this.config.withTimezone=S,this.config.precision=o}build(T){return new QA(T,this.config)}}class QA extends B{static[W]="PgTimestamp";withTimezone;precision;constructor(T,S){super(T,S);this.withTimezone=S.withTimezone,this.precision=S.precision}getSQLType(){return`timestamp${this.precision===void 0?"":` (${this.precision})`}${this.withTimezone?" with time zone":""}`}mapFromDriverValue=(T)=>{return new Date(this.withTimezone?T:T+"+0000")};mapToDriverValue=(T)=>{return T.toISOString()}}class D0 extends cS{static[W]="PgTimestampStringBuilder";constructor(T,S,o){super(T,"string","PgTimestampString");this.config.withTimezone=S,this.config.precision=o}build(T){return new DA(T,this.config)}}class DA extends B{static[W]="PgTimestampString";withTimezone;precision;constructor(T,S){super(T,S);this.withTimezone=S.withTimezone,this.precision=S.precision}getSQLType(){return`timestamp${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function US(T,S={}){let{name:o,config:f}=AT(T,S);if(f?.mode==="string")return new D0(o,f.withTimezone??!1,f.precision);return new Q0(o,f?.withTimezone??!1,f?.precision)}class U0 extends h{static[W]="PgUUIDBuilder";constructor(T){super(T,"string","PgUUID")}defaultRandom(){return this.default(_`gen_random_uuid()`)}build(T){return new UA(T,this.config)}}class UA extends B{static[W]="PgUUID";getSQLType(){return"uuid"}}function OS(T){return new U0(T??"")}class V0 extends h{static[W]="PgVarcharBuilder";constructor(T,S){super(T,"string","PgVarchar");this.config.length=S.length,this.config.enumValues=S.enum}build(T){return new B0(T,this.config)}}class B0 extends B{static[W]="PgVarchar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"varchar":`varchar(${this.length})`}}function rT(T,S={}){let{name:o,config:f}=AT(T,S);return new V0(o,f)}class t0 extends h{static[W]="PgBinaryVectorBuilder";constructor(T,S){super(T,"string","PgBinaryVector");this.config.dimensions=S.dimensions}build(T){return new L0(T,this.config)}}class L0 extends B{static[W]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}}function C0(T,S){let{name:o,config:f}=AT(T,S);return new t0(o,f)}class I0 extends h{static[W]="PgHalfVectorBuilder";constructor(T,S){super(T,"array","PgHalfVector");this.config.dimensions=S.dimensions}build(T){return new j0(T,this.config)}}class j0 extends B{static[W]="PgHalfVector";dimensions=this.config.dimensions;getSQLType(){return`halfvec(${this.dimensions})`}mapToDriverValue(T){return JSON.stringify(T)}mapFromDriverValue(T){return T.slice(1,-1).split(",").map((S)=>Number.parseFloat(S))}}function N0(T,S){let{name:o,config:f}=AT(T,S);return new I0(o,f)}class m0 extends h{static[W]="PgSparseVectorBuilder";constructor(T,S){super(T,"string","PgSparseVector");this.config.dimensions=S.dimensions}build(T){return new h0(T,this.config)}}class h0 extends B{static[W]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function b0(T,S){let{name:o,config:f}=AT(T,S);return new m0(o,f)}class x0 extends h{static[W]="PgVectorBuilder";constructor(T,S){super(T,"array","PgVector");this.config.dimensions=S.dimensions}build(T){return new v0(T,this.config)}}class v0 extends B{static[W]="PgVector";dimensions=this.config.dimensions;getSQLType(){return`vector(${this.dimensions})`}mapToDriverValue(T){return JSON.stringify(T)}mapFromDriverValue(T){return T.slice(1,-1).split(",").map((S)=>Number.parseFloat(S))}}function q0(T,S){let{name:o,config:f}=AT(T,S);return new x0(o,f)}function Z0(){return{bigint:oR,bigserial:FR,boolean:Uf,char:WR,cidr:yR,customType:HR,date:YR,doublePrecision:QR,inet:VR,integer:XA,interval:IR,json:NR,jsonb:hR,line:ZR,macaddr:pR,macaddr8:iR,numeric:lR,point:T0,geometry:$0,real:R0,serial:W0,smallint:y0,smallserial:H0,text:Y0,time:z0,timestamp:US,uuid:OS,varchar:rT,bit:C0,halfvec:N0,sparsevec:b0,vector:q0}}var en=Symbol.for("drizzle:PgInlineForeignKeys"),c0=Symbol.for("drizzle:EnableRLS");class pT extends j{static[W]="PgTable";static Symbol=Object.assign({},j.Symbol,{InlineForeignKeys:en,EnableRLS:c0});[en]=[];[c0]=!1;[j.Symbol.ExtraConfigBuilder]=void 0}function AW(T,S,o,f,A=T){let n=new pT(T,f,A),$=typeof S==="function"?S(Z0()):S,F=Object.fromEntries(Object.entries($).map(([O,k])=>{let y=k;y.setName(O);let H=y.build(n);return n[en].push(...y.buildForeignKeys(H,n)),[O,H]})),J=Object.fromEntries(Object.entries($).map(([O,k])=>{let y=k;y.setName(O);let H=y.buildExtraConfigColumn(n);return[O,H]})),R=Object.assign(n,F);if(R[j.Symbol.Columns]=F,R[j.Symbol.ExtraConfigColumns]=J,o)R[pT.Symbol.ExtraConfigBuilder]=o;return Object.assign(R,{enableRLS:()=>{return R[pT.Symbol.EnableRLS]=!0,R}})}var aS=(T,S,o)=>{return AW(T,S,o,void 0)};function r0(...T){if(T[0].columns)return new Vf(T[0].columns,T[0].name);return new Vf(T)}class Vf{static[W]="PgPrimaryKeyBuilder";columns;name;constructor(T,S){this.columns=T,this.name=S}build(T){return new p0(T,this.columns,this.name)}}class p0{constructor(T,S,o){this.table=T,this.columns=S,this.name=o}static[W]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[pT.Symbol.Name]}_${this.columns.map((T)=>T.name).join("_")}_pk`}}class sn{constructor(T,S,o){this.sourceTable=T,this.referencedTable=S,this.relationName=o,this.referencedTableName=S[j.Symbol.Name]}static[W]="Relation";referencedTableName;fieldName}class P0{constructor(T,S){this.table=T,this.config=S}static[W]="Relations"}class To extends sn{constructor(T,S,o,f){super(T,S,o?.relationName);this.config=o,this.isNullable=f}static[W]="One";withFieldName(T){let S=new To(this.sourceTable,this.referencedTable,this.config,this.isNullable);return S.fieldName=T,S}}class Bf extends sn{constructor(T,S,o){super(T,S,o?.relationName);this.config=o}static[W]="Many";withFieldName(T){let S=new Bf(this.sourceTable,this.referencedTable,this.config);return S.fieldName=T,S}}function g0(){return{and:Qf,between:vJ,eq:yA,exists:bJ,gt:tJ,gte:LJ,ilike:rJ,inArray:jJ,isNull:mJ,isNotNull:hJ,like:ZJ,lt:CJ,lte:IJ,ne:UJ,not:BJ,notBetween:qJ,notExists:xJ,notLike:cJ,notIlike:pJ,notInArray:NJ,or:VJ,sql:_}}function i0(){return{sql:_,asc:PJ,desc:gJ}}function d0(T,S){if(Object.keys(T).length===1&&"default"in T&&!K(T.default,j))T=T.default;let o={},f={},A={};for(let[n,$]of Object.entries(T))if(K($,j)){let F=Wo($),J=f[F];o[F]=n,A[n]={tsName:n,dbName:$[j.Symbol.Name],schema:$[j.Symbol.Schema],columns:$[j.Symbol.Columns],relations:J?.relations??{},primaryKey:J?.primaryKey??[]};for(let O of Object.values($[j.Symbol.Columns]))if(O.primary)A[n].primaryKey.push(O);let R=$[j.Symbol.ExtraConfigBuilder]?.($[j.Symbol.ExtraConfigColumns]);if(R){for(let O of Object.values(R))if(K(O,Vf))A[n].primaryKey.push(...O.columns)}}else if(K($,P0)){let F=Wo($.table),J=o[F],R=$.config(S($.table)),O;for(let[k,y]of Object.entries(R))if(J){let H=A[J];if(H.relations[k]=y,O)H.primaryKey.push(...O)}else{if(!(F in f))f[F]={relations:{},primaryKey:O};f[F].relations[k]=y}}return{tables:A,tableNamesMap:o}}function nW(T){return function S(o,f){return new To(T,o,f,f?.fields.reduce((A,n)=>A&&n.notNull,!0)??!1)}}function $W(T){return function S(o,f){return new Bf(T,o,f)}}function l0(T,S,o){if(K(o,To)&&o.config)return{fields:o.config.fields,references:o.config.references};let f=S[Wo(o.referencedTable)];if(!f)throw new Error(`Table "${o.referencedTable[j.Symbol.Name]}" not found in schema`);let A=T[f];if(!A)throw new Error(`Table "${f}" not found in schema`);let n=o.sourceTable,$=S[Wo(n)];if(!$)throw new Error(`Table "${n[j.Symbol.Name]}" not found in schema`);let F=[];for(let J of Object.values(A.relations))if(o.relationName&&o!==J&&J.relationName===o.relationName||!o.relationName&&J.referencedTable===o.sourceTable)F.push(J);if(F.length>1)throw o.relationName?new Error(`There are multiple relations with name "${o.relationName}" in table "${f}"`):new Error(`There are multiple relations between "${f}" and "${o.sourceTable[j.Symbol.Name]}". Please specify relation name`);if(F[0]&&K(F[0],To)&&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 "${$}.${o.fieldName}"`)}function u0(T){return{one:nW(T),many:$W(T)}}function VA(T,S,o,f,A=(n)=>n){let n={};for(let[$,F]of f.entries())if(F.isJson){let J=S.relations[F.tsKey],R=o[$],O=typeof R==="string"?JSON.parse(R):R;n[F.tsKey]=K(J,To)?O&&VA(T,T[F.relationTableTsKey],O,F.selection,A):O.map((k)=>VA(T,T[F.relationTableTsKey],k,F.selection,A))}else{let J=A(o[$]),R=F.field,O;if(K(R,_T))O=R;else if(K(R,N))O=R.decoder;else O=R.sql.decoder;n[F.tsKey]=J===null?null:O.mapFromDriverValue(J)}return n}import LW from"os";import CW from"fs";var BA=new Map,an=new Map,T$=Symbol("OriginError"),po={};class wS extends Promise{constructor(T,S,o,f,A={}){let n,$;super((F,J)=>{n=F,$=J});this.tagged=Array.isArray(T.raw),this.strings=T,this.args=S,this.handler=o,this.canceller=f,this.options=A,this.state=null,this.statement=null,this.resolve=(F)=>(this.active=!1,n(F)),this.reject=(F)=>(this.active=!1,$(F)),this.active=!1,this.cancelled=null,this.executed=!1,this.signature="",this[T$]=this.handler.debug?new Error:this.tagged&&FW(this.strings)}get origin(){return(this.handler.debug?this[T$].stack:this.tagged&&an.has(this.strings)?an.get(this.strings):an.set(this.strings,this[T$].stack).get(this.strings))||""}static get[Symbol.species](){return Promise}cancel(){return this.canceller&&(this.canceller(this),this.canceller=null)}simple(){return this.options.simple=!0,this.options.prepare=!1,this}async readable(){return this.simple(),this.streaming=!0,this}async writable(){return this.simple(),this.streaming=!0,this}cursor(T=1,S){if(this.options.simple=!1,typeof T==="function")S=T,T=1;if(this.cursorRows=T,typeof S==="function")return this.cursorFn=S,this;let o;return{[Symbol.asyncIterator]:()=>({next:()=>{if(this.executed&&!this.active)return{done:!0};o&&o();let f=new Promise((A,n)=>{this.cursorFn=($)=>{return A({value:$,done:!1}),new Promise((F)=>o=F)},this.resolve=()=>(this.active=!1,A({done:!0})),this.reject=($)=>(this.active=!1,n($))});return this.execute(),f},return(){return o&&o(po),{done:!0}}})}}describe(){return this.options.simple=!1,this.onlyDescribe=this.options.prepare=!0,this}stream(){throw new Error(".stream has been renamed to .forEach")}forEach(T){return this.forEachFn=T,this.handle(),this}raw(){return this.isRaw=!0,this}values(){return this.isRaw="values",this}async handle(){!this.executed&&(this.executed=!0)&&await 1&&this.handler(this)}execute(){return this.handle(),this}then(){return this.handle(),super.then.apply(this,arguments)}catch(){return this.handle(),super.catch.apply(this,arguments)}finally(){return this.handle(),super.finally.apply(this,arguments)}}function FW(T){if(BA.has(T))return BA.get(T);let S=Error.stackTraceLimit;return Error.stackTraceLimit=4,BA.set(T,new Error),Error.stackTraceLimit=S,BA.get(T)}class Po extends Error{constructor(T){super(T.message);this.name=this.constructor.name,Object.assign(this,T)}}var LT={connection:e0,postgres:s0,generic:a0,notSupported:T1};function e0(T,S,o){let{host:f,port:A}=o||S,n=Object.assign(new Error("write "+T+" "+(S.path||f+":"+A)),{code:T,errno:T,address:S.path||f},S.path?{}:{port:A});return Error.captureStackTrace(n,e0),n}function s0(T){let S=new Po(T);return Error.captureStackTrace(S,s0),S}function a0(T,S){let o=Object.assign(new Error(T+": "+S),{code:T});return Error.captureStackTrace(o,a0),o}function T1(T){let S=Object.assign(new Error(T+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:T});return Error.captureStackTrace(S,T1),S}var JW={string:{to:25,from:null,serialize:(T)=>""+T},number:{to:0,from:[21,23,26,700,701],serialize:(T)=>""+T,parse:(T)=>+T},json:{to:114,from:[114,3802],serialize:(T)=>JSON.stringify(T),parse:(T)=>JSON.parse(T)},boolean:{to:16,from:16,serialize:(T)=>T===!0?"t":"f",parse:(T)=>T==="t"},date:{to:1184,from:[1082,1114,1184],serialize:(T)=>(T instanceof Date?T:new Date(T)).toISOString(),parse:(T)=>new Date(T)},bytea:{to:17,from:17,serialize:(T)=>"\\x"+Buffer.from(T).toString("hex"),parse:(T)=>Buffer.from(T.slice(2),"hex")}};class CA{then(){S$()}catch(){S$()}finally(){S$()}}class If extends CA{constructor(T){super();this.value=NA(T)}}class NS extends CA{constructor(T,S,o){super();this.value=T,this.type=S,this.array=o}}class IA extends CA{constructor(T,S){super();this.first=T,this.rest=S}build(T,S,o,f){let A=RW.map(([n,$])=>({fn:$,i:T.search(n)})).sort((n,$)=>n.i-$.i).pop();return A.i===-1?$$(this.first,f):A.fn(this.first,this.rest,S,o,f)}}function jA(T,S,o,f){let A=T instanceof NS?T.value:T;if(A===void 0){if(T instanceof NS?T.value=f.transform.undefined:A=T=f.transform.undefined,A===void 0)throw LT.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return"$"+o.push(T instanceof NS?(S.push(T.value),T.array?T.array[T.type||LA(T.value)]||T.type||A1(T.value):T.type):(S.push(T),LA(T)))}var o1=$1(JW);function A$(T,S,o,f,A,n){for(let $=1;$<T.strings.length;$++)S+=n$(S,o,f,A,n)+T.strings[$],o=T.args[$];return S}function n$(T,S,o,f,A){return S instanceof IA?S.build(T,o,f,A):S instanceof wS?f$(S,o,f,A):S instanceof If?S.value:S&&S[0]instanceof wS?S.reduce((n,$)=>n+" "+f$($,o,f,A),""):jA(S,o,f,A)}function f$(T,S,o,f){return T.fragment=!0,A$(T,T.strings[0],T.args[0],S,o,f)}function f1(T,S,o,f,A){return T.map((n)=>"("+f.map(($)=>n$("values",n[$],S,o,A)).join(",")+")").join(",")}function S1(T,S,o,f,A){let n=Array.isArray(T[0]),$=S.length?S.flat():Object.keys(n?T[0]:T);return f1(n?T:[T],o,f,$,A)}function tA(T,S,o,f,A){if(typeof T==="string"&&(T=[T].concat(S)),Array.isArray(T))return $$(T,A);let n;return(S.length?S.flat():Object.keys(T)).map((F)=>{return n=T[F],(n instanceof wS?f$(n,o,f,A):n instanceof If?n.value:jA(n,o,f,A))+" as "+NA(A.transform.column.to?A.transform.column.to(F):F)}).join(",")}var RW=Object.entries({values:S1,in:(...T)=>{let S=S1(...T);return S==="()"?"(null)":S},select:tA,as:tA,returning:tA,"\\(":tA,update(T,S,o,f,A){return(S.length?S.flat():Object.keys(T)).map((n)=>NA(A.transform.column.to?A.transform.column.to(n):n)+"="+n$("values",T[n],o,f,A))},insert(T,S,o,f,A){let n=S.length?S.flat():Object.keys(Array.isArray(T)?T[0]:T);return"("+$$(n,A)+")values"+f1(Array.isArray(T)?T:[T],o,f,n,A)}}).map(([T,S])=>[new RegExp("((?:^|[\\s(])"+T+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),S]);function S$(){throw LT.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}var{serializers:OW,parsers:MW}=o1;function A1(T){if(Array.isArray(T))return A1(T[0]);return typeof T==="string"?1009:0}var n1=function(T){let S=$1(T||{});return{serializers:Object.assign({},OW,S.serializers),parsers:Object.assign({},MW,S.parsers)}};function $1(T){return Object.keys(T).reduce((S,o)=>{if(T[o].from&&[].concat(T[o].from).forEach((f)=>S.parsers[f]=T[o].parse),T[o].serialize)S.serializers[T[o].to]=T[o].serialize,T[o].from&&[].concat(T[o].from).forEach((f)=>S.serializers[f]=T[o].serialize);return S},{parsers:{},serializers:{}})}function $$(T,{transform:{column:S}}){return T.map((o)=>NA(S.to?S.to(o):o)).join(",")}var NA=function T(S){return'"'+S.replace(/"/g,'""').replace(/\./g,'"."')+'"'},LA=function T(S){return S instanceof NS?S.type:S instanceof Date?1184:S instanceof Uint8Array?17:S===!0||S===!1?16:typeof S==="bigint"?20:Array.isArray(S)?T(S[0]):0},WW=/\\/g,_W=/"/g;function kW(T){return T.replace(WW,"\\\\").replace(_W,"\\\"")}var F1=function T(S,o,f,A){if(Array.isArray(S)===!1)return S;if(!S.length)return"{}";let n=S[0],$=A===1020?";":",";if(Array.isArray(n)&&!n.type)return"{"+S.map((F)=>T(F,o,f,A)).join($)+"}";return"{"+S.map((F)=>{if(F===void 0){if(F=f.transform.undefined,F===void 0)throw LT.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return F===null?"null":'"'+kW(o?o(F.type?F.value:F):""+F)+'"'}).join($)+"}"},o$={i:0,char:null,str:"",quoted:!1,last:0},J1=function T(S,o,f){return o$.i=o$.last=0,R1(o$,S,o,f)};function R1(T,S,o,f){let A=[],n=f===1020?";":",";for(;T.i<S.length;T.i++){if(T.char=S[T.i],T.quoted)if(T.char==="\\")T.str+=S[++T.i];else if(T.char==='"')A.push(o?o(T.str):T.str),T.str="",T.quoted=S[T.i+1]==='"',T.last=T.i+2;else T.str+=T.char;else if(T.char==='"')T.quoted=!0;else if(T.char==="{")T.last=++T.i,A.push(R1(T,S,o,f));else if(T.char==="}"){T.quoted=!1,T.last<T.i&&A.push(o?o(S.slice(T.last,T.i)):S.slice(T.last,T.i)),T.last=T.i+1;break}else if(T.char===n&&T.p!=="}"&&T.p!=='"')A.push(o?o(S.slice(T.last,T.i)):S.slice(T.last,T.i)),T.last=T.i+1;T.p=T.char}return T.last<T.i&&A.push(o?o(S.slice(T.last,T.i+1)):S.slice(T.last,T.i+1)),A}var _o=(T)=>{let S=T[0];for(let o=1;o<T.length;o++)S+=T[o]==="_"?T[++o].toUpperCase():T[o];return S},ko=(T)=>{let S=T[0].toUpperCase();for(let o=1;o<T.length;o++)S+=T[o]==="_"?T[++o].toUpperCase():T[o];return S},yo=(T)=>T.replace(/_/g,"-"),tf=(T)=>T.replace(/([A-Z])/g,"_$1").toLowerCase(),Lf=(T)=>(T.slice(0,1)+T.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),Cf=(T)=>T.replace(/-/g,"_");function F$(T){return function S(o,f){return typeof o==="object"&&o!==null&&(f.type===114||f.type===3802)?Array.isArray(o)?o.map((A)=>S(A,f)):Object.entries(o).reduce((A,[n,$])=>Object.assign(A,{[T(n)]:S($,f)}),{}):o}}_o.column={from:_o};_o.value={from:F$(_o)};tf.column={to:tf};var J$={..._o};J$.column.to=tf;ko.column={from:ko};ko.value={from:F$(ko)};Lf.column={to:Lf};var R$={...ko};R$.column.to=Lf;yo.column={from:yo};yo.value={from:F$(yo)};Cf.column={to:Cf};var O$={...yo};O$.column.to=Cf;import O1 from"net";import HW from"tls";import jf from"crypto";import M$ from"stream";import{performance as M1}from"perf_hooks";class wo 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 MS=yW;function yW(T=[]){let S=T.slice(),o=0;return{get length(){return S.length-o},remove:(f)=>{let A=S.indexOf(f);return A===-1?null:(S.splice(A,1),f)},push:(f)=>(S.push(f),f),shift:()=>{let f=S[o++];if(o===S.length)o=0,S=[];else S[o-1]=void 0;return f}}}var eT=Buffer.allocUnsafe(256),wW="BCcDdEFfHPpQSX".split("").reduce((T,S)=>{let o=S.charCodeAt(0);return T[S]=()=>{return eT[0]=o,MT.i=5,MT},T},{}),MT=Object.assign(KW,wW,{N:String.fromCharCode(0),i:0,inc(T){return MT.i+=T,MT},str(T){let S=Buffer.byteLength(T);return mA(S),MT.i+=eT.write(T,MT.i,S,"utf8"),MT},i16(T){return mA(2),eT.writeUInt16BE(T,MT.i),MT.i+=2,MT},i32(T,S){if(S||S===0)return eT.writeUInt32BE(T,S),MT;return mA(4),eT.writeUInt32BE(T,MT.i),MT.i+=4,MT},z(T){return mA(T),eT.fill(0,MT.i,MT.i+T),MT.i+=T,MT},raw(T){return eT=Buffer.concat([eT.subarray(0,MT.i),T]),MT.i=eT.length,MT},end(T=1){eT.writeUInt32BE(MT.i-T,T);let S=eT.subarray(0,MT.i);return MT.i=0,eT=Buffer.allocUnsafe(256),S}}),r=MT;function mA(T){if(eT.length-MT.i<T){let S=eT,o=S.length;eT=Buffer.allocUnsafe(o+(o>>1)+T),S.copy(eT)}}function KW(){return MT.i=0,MT}var k$=k1,XW=1,So=r().S().end(),W1=r().H().end(),GW=r().i32(8).i32(80877103).end(8),YW=Buffer.concat([r().E().str(r.N).i32(0).end(),So]),EW=r().D().str("S").str(r.N).end(),go=()=>{},zW=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),QW={83:"severity_local",86:"severity",67:"code",77:"message",68:"detail",72:"hint",80:"position",112:"internal_position",113:"internal_query",87:"where",115:"schema_name",116:"table_name",99:"column_name",100:"data type_name",110:"constraint_name",70:"file",76:"line",82:"routine"};function k1(T,S={},{onopen:o=go,onend:f=go,onclose:A=go}={}){let{ssl:n,max:$,user:F,host:J,port:R,database:O,parsers:k,transform:y,onnotice:H,onnotify:E,onparameter:G,max_pipeline:I,keep_alive:b,backoff:q,target_session_attrs:P}=T,X=MS(),D=XW++,V={pid:null,secret:null},U=_$(dA,T.idle_timeout),v=_$(dA,T.max_lifetime),l=_$(h1,T.connect_timeout),Y=null,a,Z=new wo,TT=Buffer.alloc(0),WT=T.fetch_types,CT={},oS={},mS=Math.random().toString(36).slice(2),z=1,c=0,FT=0,YT=0,IT=0,oT=0,yT=0,tT=0,zT=null,HT=null,PT=!1,wT=null,KS=null,gT=null,rS=null,jT=null,XT=null,HS=null,VS=null,t=null,eo=null,iT={queue:S.closed,idleTimer:U,connect(M){gT=M||!0,Z$()},terminate:ao,execute:so,cancel:I1,end:dA,count:0,id:D};return S.closed&&S.closed.push(iT),iT;async function C1(){let M;try{M=T.socket?await Promise.resolve(T.socket(T)):new O1.Socket}catch(w){Go(w);return}return M.on("error",Go),M.on("close",c$),M.on("drain",v$),M}async function I1({pid:M,secret:w},p,JT){try{a=r().i32(16).i32(80877102).i32(M).i32(w).end(16),await q$(),Y.once("error",JT),Y.once("close",p)}catch(DT){JT(DT)}}function so(M){if(PT)return qf(M,LT.connection("CONNECTION_DESTROYED",T));if(M.cancelled)return;try{return M.state=V,t?X.push(M):(t=M,t.active=!0),m1(M),ZT(j1(M))&&!M.describeFirst&&!M.cursorFn&&X.length<I&&(!M.options.onexecute||M.options.onexecute(iT))}catch(w){return X.length===0&&ZT(So),BS(w),!0}}function j1(M){if(M.parameters.length>=65534)throw LT.generic("MAX_PARAMETERS_EXCEEDED","Max number of parameters (65534) exceeded");return M.options.simple?r().Q().str(M.statement.string+r.N).end():M.describeFirst?Buffer.concat([h$(M),W1]):M.prepare?M.prepared?vf(M):Buffer.concat([h$(M),vf(M)]):N1(M)}function h$(M){return Buffer.concat([p$(M.statement.string,M.parameters,M.statement.types,M.statement.name),GO("S",M.statement.name)])}function vf(M){return Buffer.concat([XO(M.parameters,M.statement.types,M.statement.name,M.cursorName),M.cursorFn?P$("",M.cursorRows):YW])}function N1(M){return Buffer.concat([p$(M.statement.string,M.parameters,M.statement.types),EW,vf(M)])}function m1(M){let w=[],p=[],JT=A$(M,M.strings[0],M.args[0],w,p,T);!M.tagged&&M.args.forEach((DT)=>jA(DT,w,p,T)),M.prepare=T.prepare&&("prepare"in M.options?M.options.prepare:!0),M.string=JT,M.signature=M.prepare&&p+JT,M.onlyDescribe&&delete oS[M.signature],M.parameters=M.parameters||w,M.prepared=M.prepare&&M.signature in oS,M.describeFirst=M.onlyDescribe||w.length&&!M.prepared,M.statement=M.prepared?oS[M.signature]:{string:JT,types:p,name:M.prepare?mS+z++:""},typeof T.debug==="function"&&T.debug(D,JT,w,p)}function ZT(M,w){if(XT=XT?Buffer.concat([XT,M]):Buffer.from(M),w||XT.length>=1024)return b$(w);return HT===null&&(HT=setImmediate(b$)),!0}function b$(M){let w=Y.write(XT,M);return HT!==null&&clearImmediate(HT),XT=HT=null,w}function h1(){BS(LT.connection("CONNECT_TIMEOUT",T,Y)),Y.destroy()}async function x$(){if(ZT(GW),!await new Promise((w)=>Y.once("data",(p)=>w(p[0]===83)))&&n==="prefer")return Xo();Y.removeAllListeners(),Y=HW.connect({socket:Y,servername:O1.isIP(Y.host)?void 0:Y.host,...n==="require"||n==="allow"||n==="prefer"?{rejectUnauthorized:!1}:n==="verify-full"?{}:typeof n==="object"?n:{}}),Y.on("secureConnect",Xo),Y.on("error",Go),Y.on("close",c$),Y.on("drain",v$)}function v$(){!t&&o(iT)}function iA(M){if(wT){if(wT.push(M),FT-=M.length,FT>=0)return}TT=wT?Buffer.concat(wT,oT-FT):TT.length===0?M:Buffer.concat([TT,M],TT.length+M.length);while(TT.length>4){if(oT=TT.readUInt32BE(1),oT>=TT.length){FT=oT-TT.length,wT=[TT];break}try{b1(TT.subarray(0,oT+1))}catch(w){t&&(t.cursorFn||t.describeFirst)&&ZT(So),BS(w)}TT=TT.subarray(oT+1),FT=0,wT=null}}async function q$(){if(PT=!1,CT={},Y||(Y=await C1()),!Y)return;if(l.start(),T.socket)return n?x$():Xo();if(Y.on("connect",n?x$:Xo),T.path)return Y.connect(T.path);Y.ssl=n,Y.connect(R[YT],J[YT]),Y.host=J[YT],Y.port=R[YT],YT=(YT+1)%R.length}function Z$(){setTimeout(q$,c?c+yT-M1.now():0)}function Xo(){try{oS={},WT=T.fetch_types,mS=Math.random().toString(36).slice(2),z=1,v.start(),Y.on("data",iA),b&&Y.setKeepAlive&&Y.setKeepAlive(!0,1000*b);let M=EO();ZT(M)}catch(M){Go(M)}}function Go(M){if(iT.queue===S.connecting&&T.host[IT+1])return;BS(M);while(X.length)qf(X.shift(),M)}function BS(M){jT&&(jT.destroy(M),jT=null),t&&qf(t,M),gT&&(qf(gT,M),gT=null)}function qf(M,w){"query"in w||"parameters"in w||Object.defineProperties(w,{stack:{value:w.stack+M.origin.replace(/.*\n/,`
|
|
17
|
+
`),enumerable:T.debug},query:{value:M.string,enumerable:T.debug},parameters:{value:M.parameters,enumerable:T.debug},args:{value:M.args,enumerable:T.debug},types:{value:M.statement&&M.statement.types,enumerable:T.debug}}),M.reject(w)}function dA(){return rS||(!iT.reserved&&f(iT),!iT.reserved&&!gT&&!t&&X.length===0?(ao(),new Promise((M)=>Y&&Y.readyState!=="closed"?Y.once("close",M):M())):rS=new Promise((M)=>HS=M))}function ao(){if(PT=!0,jT||t||gT||X.length)Go(LT.connection("CONNECTION_DESTROYED",T));if(clearImmediate(HT),Y)Y.removeListener("data",iA),Y.removeListener("connect",Xo),Y.readyState==="open"&&Y.end(r().X().end());HS&&(HS(),rS=HS=null)}async function c$(M){if(TT=Buffer.alloc(0),FT=0,wT=null,clearImmediate(HT),Y.removeListener("data",iA),Y.removeListener("connect",Xo),U.cancel(),v.cancel(),l.cancel(),Y.removeAllListeners(),Y=null,gT)return Z$();!M&&(t||X.length)&&Go(LT.connection("CONNECTION_CLOSED",T,Y)),c=M1.now(),M&&T.shared.retries++,yT=(typeof q==="function"?q(T.shared.retries):q)*1000,A(iT,LT.connection("CONNECTION_CLOSED",T,Y))}function b1(M,w=M[0]){(w===68?x1:w===100?MO:w===65?nO:w===83?v1:w===90?q1:w===67?Z1:w===50?r$:w===49?c1:w===116?r1:w===84?p1:w===82?P1:w===110?e1:w===75?s1:w===69?fO:w===115?$O:w===51?FO:w===71?JO:w===78?_O:w===72?RO:w===99?WO:w===73?kO:w===86?yO:w===118?wO:w===87?OO:KO)(M)}function x1(M){let w=7,p,JT,DT,dT=t.isRaw?new Array(t.statement.columns.length):{};for(let sT=0;sT<t.statement.columns.length;sT++)JT=t.statement.columns[sT],p=M.readInt32BE(w),w+=4,DT=p===-1?null:t.isRaw===!0?M.subarray(w,w+=p):JT.parser===void 0?M.toString("utf8",w,w+=p):JT.parser.array===!0?JT.parser(M.toString("utf8",w+1,w+=p)):JT.parser(M.toString("utf8",w,w+=p)),t.isRaw?dT[sT]=t.isRaw===!0?DT:y.value.from?y.value.from(DT,JT):DT:dT[JT.name]=y.value.from?y.value.from(DT,JT):DT;t.forEachFn?t.forEachFn(y.row.from?y.row.from(dT):dT,Z):Z[tT++]=y.row.from?y.row.from(dT):dT}function v1(M){let[w,p]=M.toString("utf8",5,M.length-1).split(r.N);if(CT[w]=p,T.parameters[w]!==p)T.parameters[w]=p,G&&G(w,p)}function q1(M){if(t&&t.options.simple&&t.resolve(KS||Z),t=KS=null,Z=new wo,l.cancel(),gT){if(P){if(!CT.in_hot_standby||!CT.default_transaction_read_only)return oO();else if(SO(P,CT))return ao()}if(WT)return gT===!0&&(gT=null),a1();gT!==!0&&so(gT),T.shared.retries=IT=0,gT=null;return}while(X.length&&(t=X.shift())&&(t.active=!0,t.cancelled))k1(T).cancel(t.state,t.cancelled.resolve,t.cancelled.reject);if(t)return;iT.reserved?!iT.reserved.release&&M[5]===73?rS?ao():(iT.reserved=null,o(iT)):iT.reserved():rS?ao():o(iT)}function Z1(M){tT=0;for(let w=M.length-1;w>0;w--){if(M[w]===32&&M[w+1]<58&&Z.count===null)Z.count=+M.toString("utf8",w+1,M.length-1);if(M[w-1]>=65){Z.command=M.toString("utf8",5,w),Z.state=V;break}}if(eo&&(eo(),eo=null),Z.command==="BEGIN"&&$!==1&&!iT.reserved)return BS(LT.generic("UNSAFE_TRANSACTION","Only use sql.begin, sql.reserved or max: 1"));if(t.options.simple)return r$();if(t.cursorFn)Z.count&&t.cursorFn(Z),ZT(So);t.resolve(Z)}function c1(){t.parsing=!1}function r$(){!Z.statement&&(Z.statement=t.statement),Z.columns=t.statement.columns}function r1(M){let w=M.readUInt16BE(5);for(let p=0;p<w;++p)!t.statement.types[p]&&(t.statement.types[p]=M.readUInt32BE(7+p*4));t.prepare&&(oS[t.signature]=t.statement),t.describeFirst&&!t.onlyDescribe&&(ZT(vf(t)),t.describeFirst=!1)}function p1(M){if(Z.command)KS=KS||[Z],KS.push(Z=new wo),Z.count=null,t.statement.columns=null;let w=M.readUInt16BE(5),p=7,JT;t.statement.columns=Array(w);for(let DT=0;DT<w;++DT){JT=p;while(M[p++]!==0);let dT=M.readUInt32BE(p),sT=M.readUInt16BE(p+4),pS=M.readUInt32BE(p+6);t.statement.columns[DT]={name:y.column.from?y.column.from(M.toString("utf8",JT,p-1)):M.toString("utf8",JT,p-1),parser:k[pS],table:dT,number:sT,type:pS},p+=18}if(Z.statement=t.statement,t.onlyDescribe)return t.resolve(t.statement),ZT(So)}async function P1(M,w=M.readUInt32BE(5)){(w===3?g1:w===5?i1:w===10?d1:w===11?l1:w===12?u1:w!==0?HO:go)(M,w)}async function g1(){let M=await lA();ZT(r().p().str(M).z(1).end())}async function i1(M){let w="md5"+await _1(Buffer.concat([Buffer.from(await _1(await lA()+F)),M.subarray(9)]));ZT(r().p().str(w).z(1).end())}async function d1(){VS=(await jf.randomBytes(18)).toString("base64"),r().p().str("SCRAM-SHA-256"+r.N);let M=r.i;ZT(r.inc(4).str("n,,n=*,r="+VS).i32(r.i-M-4,M).end())}async function l1(M){let w=M.toString("utf8",9).split(",").reduce((sT,pS)=>(sT[pS[0]]=pS.slice(2),sT),{}),p=await jf.pbkdf2Sync(await lA(),Buffer.from(w.s,"base64"),parseInt(w.i),32,"sha256"),JT=await hA(p,"Client Key"),DT="n=*,r="+VS+",r="+w.r+",s="+w.s+",i="+w.i+",c=biws,r="+w.r;zT=(await hA(await hA(p,"Server Key"),DT)).toString("base64");let dT="c=biws,r="+w.r+",p="+UW(JT,Buffer.from(await hA(await DW(JT),DT))).toString("base64");ZT(r().p().str(dT).end())}function u1(M){if(M.toString("utf8",9).split(r.N,1)[0].slice(2)===zT)return;BS(LT.generic("SASL_SIGNATURE_MISMATCH","The server did not return the correct signature")),Y.destroy()}function lA(){return Promise.resolve(typeof T.pass==="function"?T.pass():T.pass)}function e1(){if(Z.statement=t.statement,Z.statement.columns=[],t.onlyDescribe)return t.resolve(t.statement),ZT(So)}function s1(M){V.pid=M.readUInt32BE(5),V.secret=M.readUInt32BE(9)}async function a1(){WT=!1,(await new wS([`
|
|
18
18
|
select b.oid, b.typarray
|
|
19
19
|
from pg_catalog.pg_type a
|
|
20
20
|
left join pg_catalog.pg_type b on b.oid = a.typelem
|
|
21
21
|
where a.typcategory = 'A'
|
|
22
22
|
group by b.oid, b.typarray
|
|
23
23
|
order by b.oid
|
|
24
|
-
`],[],
|
|
24
|
+
`],[],so)).forEach(({oid:w,typarray:p})=>TO(w,p))}function TO(M,w){if(!!T.parsers[w]&&!!T.serializers[w])return;let p=T.parsers[M];T.shared.typeArrayMap[M]=w,T.parsers[w]=(JT)=>J1(JT,p,w),T.parsers[w].array=!0,T.serializers[w]=(JT)=>F1(JT,T.serializers[M],T,w)}function SO(M,w){return M==="read-write"&&w.default_transaction_read_only==="on"||M==="read-only"&&w.default_transaction_read_only==="off"||M==="primary"&&w.in_hot_standby==="on"||M==="standby"&&w.in_hot_standby==="off"||M==="prefer-standby"&&w.in_hot_standby==="off"&&T.host[IT]}function oO(){let M=new wS([`
|
|
25
25
|
show transaction_read_only;
|
|
26
26
|
select pg_catalog.pg_is_in_recovery()
|
|
27
|
-
`],[],
|
|
27
|
+
`],[],so,null,{simple:!0});M.resolve=([[w],[p]])=>{CT.default_transaction_read_only=w.transaction_read_only,CT.in_hot_standby=p.pg_is_in_recovery?"on":"off"},M.execute()}function fO(M){t&&(t.cursorFn||t.describeFirst)&&ZT(So);let w=LT.postgres(W$(M));t&&t.retried?BS(t.retried):t&&t.prepared&&zW.has(w.routine)?AO(t,w):BS(w)}function AO(M,w){delete oS[M.signature],M.retried=w,so(M)}function nO(M){if(!E)return;let w=9;while(M[w++]!==0);E(M.toString("utf8",9,w-1),M.toString("utf8",w,M.length-1))}async function $O(){try{let M=await Promise.resolve(t.cursorFn(Z));tT=0,M===po?ZT(YO(t.portal)):(Z=new wo,ZT(P$("",t.cursorRows)))}catch(M){ZT(So),t.reject(M)}}function FO(){Z.count&&t.cursorFn(Z),t.resolve(Z)}function JO(){jT=new M$.Writable({autoDestroy:!0,write(M,w,p){Y.write(r().d().raw(M).end(),p)},destroy(M,w){w(M),Y.write(r().f().str(M+r.N).end()),jT=null},final(M){Y.write(r().c().end()),eo=M}}),t.resolve(jT)}function RO(){jT=new M$.Readable({read(){Y.resume()}}),t.resolve(jT)}function OO(){jT=new M$.Duplex({autoDestroy:!0,read(){Y.resume()},write(M,w,p){Y.write(r().d().raw(M).end(),p)},destroy(M,w){w(M),Y.write(r().f().str(M+r.N).end()),jT=null},final(M){Y.write(r().c().end()),eo=M}}),t.resolve(jT)}function MO(M){jT&&(jT.push(M.subarray(5))||Y.pause())}function WO(){jT&&jT.push(null),jT=null}function _O(M){H?H(W$(M)):console.log(W$(M))}function kO(){}function yO(){BS(LT.notSupported("FunctionCallResponse"))}function wO(){BS(LT.notSupported("NegotiateProtocolVersion"))}function KO(M){console.error("Postgres.js : Unknown Message:",M[0])}function HO(M,w){console.error("Postgres.js : Unknown Auth:",w)}function XO(M,w,p="",JT=""){let DT,dT;return r().B().str(JT+r.N).str(p+r.N).i16(0).i16(M.length),M.forEach((sT,pS)=>{if(sT===null)return r.i32(4294967295);dT=w[pS],M[pS]=sT=dT in T.serializers?T.serializers[dT](sT):""+sT,DT=r.i,r.inc(4).str(sT).i32(r.i-DT-4,DT)}),r.i16(0),r.end()}function p$(M,w,p,JT=""){return r().P().str(JT+r.N).str(M+r.N).i16(w.length),w.forEach((DT,dT)=>r.i32(p[dT]||0)),r.end()}function GO(M,w=""){return r().D().str(M).str(w+r.N).end()}function P$(M="",w=0){return Buffer.concat([r().E().str(M+r.N).i32(w).end(),W1])}function YO(M=""){return Buffer.concat([r().C().str("P").str(M+r.N).end(),r().S().end()])}function EO(){return a||r().inc(4).i16(3).z(2).str(Object.entries(Object.assign({user:F,database:O,client_encoding:"UTF8"},T.connection)).filter(([,M])=>M).map(([M,w])=>M+r.N+w).join(r.N)).z(2).end(0)}}function W$(T){let S={},o=5;for(let f=5;f<T.length-1;f++)if(T[f]===0)S[QW[T[o]]]=T.toString("utf8",o+1,f),o=f+1;return S}function _1(T){return jf.createHash("md5").update(T).digest("hex")}function hA(T,S){return jf.createHmac("sha256",T).update(S).digest()}function DW(T){return jf.createHash("sha256").update(T).digest()}function UW(T,S){let o=Math.max(T.length,S.length),f=Buffer.allocUnsafe(o);for(let A=0;A<o;A++)f[A]=T[A]^S[A];return f}function _$(T,S){if(S=typeof S==="function"?S():S,!S)return{cancel:go,start:go};let o;return{cancel(){o&&(clearTimeout(o),o=null)},start(){o&&clearTimeout(o),o=setTimeout(f,S*1000,arguments)}};function f(A){T.apply(null,A),o=null}}var y1=()=>{};function y$(T,S){let o=new Map,f="postgresjs_"+Math.random().toString(36).slice(2),A={},n,$,F=!1,J=k.sql=T({...S,transform:{column:{},value:{},row:{}},max:1,fetch_types:!1,idle_timeout:null,max_lifetime:null,connection:{...S.connection,replication:"database"},onclose:async function(){if(F)return;$=null,A.pid=A.secret=void 0,y(await H(J,f,S.publications)),o.forEach((G)=>G.forEach(({onsubscribe:I})=>I()))},no_subscribe:!0}),R=J.end,O=J.close;return J.end=async()=>{return F=!0,$&&await new Promise((G)=>($.once("close",G),$.end())),R()},J.close=async()=>{return $&&await new Promise((G)=>($.once("close",G),$.end())),O()},k;async function k(G,I,b=y1,q=y1){if(G=tW(G),!n)n=H(J,f,S.publications);let P={fn:I,onsubscribe:b},X=o.has(G)?o.get(G).add(P):o.set(G,new Set([P])).get(G),D=()=>{X.delete(P),X.size===0&&o.delete(G)};return n.then((V)=>{return y(V),b(),$&&$.on("error",q),{unsubscribe:D,state:A,sql:J}})}function y(G){$=G.stream,A.pid=G.state.pid,A.secret=G.state.secret}async function H(G,I,b){if(!b)throw new Error("Missing publication names");let q=await G.unsafe(`CREATE_REPLICATION_SLOT ${I} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT`),[P]=q,X=await G.unsafe(`START_REPLICATION SLOT ${I} LOGICAL ${P.consistent_point} (proto_version '1', publication_names '${b}')`).writable(),D={lsn:Buffer.concat(P.consistent_point.split("/").map((Y)=>Buffer.from(("00000000"+Y).slice(-8),"hex")))};return X.on("data",U),X.on("error",V),X.on("close",G.close),{stream:X,state:q.state};function V(Y){console.error("Unexpected error during logical streaming - reconnecting",Y)}function U(Y){if(Y[0]===119)BW(Y.subarray(25),D,G.options.parsers,v,S.transform);else if(Y[0]===107&&Y[17])D.lsn=Y.subarray(1,9),l()}function v(Y,a){let Z=a.relation.schema+"."+a.relation.table;E("*",Y,a),E("*:"+Z,Y,a),a.relation.keys.length&&E("*:"+Z+"="+a.relation.keys.map((TT)=>Y[TT.name]),Y,a),E(a.command,Y,a),E(a.command+":"+Z,Y,a),a.relation.keys.length&&E(a.command+":"+Z+"="+a.relation.keys.map((TT)=>Y[TT.name]),Y,a)}function l(){let Y=Buffer.alloc(34);Y[0]=114,Y.fill(D.lsn,1),Y.writeBigInt64BE(BigInt(Date.now()-Date.UTC(2000,0,1))*BigInt(1000),25),X.write(Y)}}function E(G,I,b){o.has(G)&&o.get(G).forEach(({fn:q})=>q(I,b,G))}}function VW(T){return new Date(Date.UTC(2000,0,1)+Number(T/BigInt(1000)))}function BW(T,S,o,f,A){let n=($,[F,J])=>($[F.charCodeAt(0)]=J,$);Object.entries({R:($)=>{let F=1,J=S[$.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,O;while(F<$.length)O=J.columns[R++]={key:$[F++],name:A.column.from?A.column.from($.toString("utf8",F,F=$.indexOf(0,F))):$.toString("utf8",F,F=$.indexOf(0,F)),type:$.readUInt32BE(F+=1),parser:o[$.readUInt32BE(F)],atttypmod:$.readUInt32BE(F+=4)},O.key&&J.keys.push(O),F+=4},Y:()=>{},O:()=>{},B:($)=>{S.date=VW($.readBigInt64BE(9)),S.lsn=$.subarray(1,9)},I:($)=>{let F=1,J=S[$.readUInt32BE(F)],{row:R}=bA($,J.columns,F+=7,A);f(R,{command:"insert",relation:J})},D:($)=>{let F=1,J=S[$.readUInt32BE(F)];F+=4;let R=$[F]===75;f(R||$[F]===79?bA($,J.columns,F+=3,A).row:null,{command:"delete",relation:J,key:R})},U:($)=>{let F=1,J=S[$.readUInt32BE(F)];F+=4;let R=$[F]===75,O=R||$[F]===79?bA($,J.columns,F+=3,A):null;O&&(F=O.i);let{row:k}=bA($,J.columns,F+3,A);f(k,{command:"update",relation:J,key:R,old:O&&O.row})},T:()=>{},C:()=>{}}).reduce(n,{})[T[0]](T)}function bA(T,S,o,f){let A,n,$,F=f.raw?new Array(S.length):{};for(let J=0;J<S.length;J++)A=T[o++],n=S[J],$=A===110?null:A===117?void 0:n.parser===void 0?T.toString("utf8",o+4,o+=4+T.readUInt32BE(o)):n.parser.array===!0?n.parser(T.toString("utf8",o+5,o+=4+T.readUInt32BE(o))):n.parser(T.toString("utf8",o+4,o+=4+T.readUInt32BE(o))),f.raw?F[J]=f.raw===!0?$:f.value.from?f.value.from($,n):$:F[n.name]=f.value.from?f.value.from($,n):$;return{i:o,row:f.row.from?f.row.from(F):F}}function tW(T){let S=T.match(/^(\*|insert|update|delete)?:?([^.]+?\.?[^=]+)?=?(.+)?/i)||[];if(!S)throw new Error("Malformed subscribe pattern: "+T);let[,o,f,A]=S;return(o||"*")+(f?":"+(f.indexOf(".")===-1?"public."+f:f):"")+(A?"="+A:"")}import w1 from"stream";function w$(T,S,o=393216){return new Promise(async(f,A)=>{await T.begin(async(n)=>{let $;!S&&([{oid:S}]=await n`select lo_creat(-1) as oid`);let[{fd:F}]=await n`select lo_open(${S}, ${o}) as fd`,J={writable:O,readable:R,close:()=>n`select lo_close(${F})`.then($),tell:()=>n`select lo_tell64(${F})`,read:(k)=>n`select loread(${F}, ${k}) as data`,write:(k)=>n`select lowrite(${F}, ${k})`,truncate:(k)=>n`select lo_truncate64(${F}, ${k})`,seek:(k,y=0)=>n`select lo_lseek64(${F}, ${k}, ${y})`,size:()=>n`
|
|
28
28
|
select
|
|
29
29
|
lo_lseek64(${F}, location, 0) as position,
|
|
30
30
|
seek.size
|
|
@@ -34,10 +34,10 @@ ${$.trace}`:"No previous disposal trace was found."),f.type){case"atom_family":c
|
|
|
34
34
|
tell.location
|
|
35
35
|
from (select lo_tell64($1) as location) tell
|
|
36
36
|
) seek
|
|
37
|
-
`};return f(J),new Promise(async(y)=>$=y);async function R({highWaterMark:y=16384,start:_=0,end:K=1/0}={}){let H=K-_;return _&&await J.seek(_),new _1.Readable({highWaterMark:y,async read(Y){let I=Y>H?Y-H:Y;H-=Y;let[{data:b}]=await J.read(I);if(this.push(b),b.length<Y)this.push(null)}})}async function W({highWaterMark:y=16384,start:_=0}={}){return _&&await J.seek(_),new _1.Writable({highWaterMark:y,write(K,H,Y){J.write(K).then(()=>Y(),Y)}})}}).catch(n)})}Object.assign(xn,{PostgresError:pS,toPascal:kS,pascal:R$,toCamel:MS,camel:J$,toKebab:yS,kebab:W$,fromPascal:Lf,fromCamel:Bf,fromKebab:Cf,BigInt:{to:20,from:[20],parse:(T)=>BigInt(T),serialize:(T)=>T.toString()}});var gS=xn;function xn(T,o){let S=IM(T,o),f=S.no_subscribe||_$(xn,{...S}),n=!1,A=Oo(),$=Oo(),F=Oo(),J=Oo(),R=Oo(),W=Oo(),y=Oo(),_=Oo(),K={connecting:$,reserved:F,closed:J,ended:R,open:W,busy:y,full:_},H=[...Array(S.max)].map(()=>y$(S,K,{onopen:So,onend:CT,onclose:No})),Y=I(v);return Object.assign(Y,{get parameters(){return S.parameters},largeObject:w$.bind(null,Y),subscribe:f,CLOSE:PS,END:PS,PostgresError:pS,options:S,reserve:p,listen:b,begin:G,close:Z,end:TT}),Y;function I(z){return z.debug=S.debug,Object.entries(S.types).reduce((fT,[_T,BT])=>{return fT[_T]=(zT)=>new mo(zT,BT.to),fT},c),Object.assign(FT,{types:c,typed:c,unsafe:ET,notify:q,array:U,json:t,file:IT}),FT;function c(fT,_T){return new mo(fT,_T)}function FT(fT,..._T){return fT&&Array.isArray(fT.raw)?new wo(fT,_T,z,E):typeof fT==="string"&&!_T.length?new If(S.transform.column.to?S.transform.column.to(fT):fT):new In(fT,_T)}function ET(fT,_T=[],BT={}){return arguments.length===2&&!Array.isArray(_T)&&(BT=_T,_T=[]),new wo([fT],_T,z,E,{prepare:!1,...BT,simple:"simple"in BT?BT.simple:_T.length===0})}function IT(fT,_T=[],BT={}){return arguments.length===2&&!Array.isArray(_T)&&(BT=_T,_T=[]),new wo([],_T,(KT)=>{CM.readFile(fT,"utf8",(pT,wT)=>{if(pT)return KT.reject(pT);KT.strings=[wT],z(KT)})},E,{...BT,simple:"simple"in BT?BT.simple:_T.length===0})}}async function b(z,c,FT){let ET={fn:c,onlisten:FT},IT=b.sql||(b.sql=xn({...S,max:1,idle_timeout:null,max_lifetime:null,fetch_types:!1,onclose(){Object.entries(b.channels).forEach(([KT,{listeners:pT}])=>{delete b.channels[KT],Promise.all(pT.map((wT)=>b(KT,wT.fn,wT.onlisten).catch(()=>{})))})},onnotify(KT,pT){KT in b.channels&&b.channels[KT].listeners.forEach((wT)=>wT.fn(pT))}})),fT=b.channels||(b.channels={});if(z in fT){fT[z].listeners.push(ET);let KT=await fT[z].result;return ET.onlisten&&ET.onlisten(),{state:KT.state,unlisten:zT}}fT[z]={result:IT`listen ${IT.unsafe('"'+z.replace(/"/g,'""')+'"')}`,listeners:[ET]};let BT=await fT[z].result;return ET.onlisten&&ET.onlisten(),{state:BT.state,unlisten:zT};async function zT(){if(z in fT===!1)return;if(fT[z].listeners=fT[z].listeners.filter((KT)=>KT!==ET),fT[z].listeners.length)return;return delete fT[z],IT`unlisten ${IT.unsafe('"'+z.replace(/"/g,'""')+'"')}`}}async function q(z,c){return await Y`select pg_notify(${z}, ${""+c})`}async function p(){let z=Oo(),c=W.length?W.shift():await new Promise((IT)=>{A.push({reserve:IT}),J.length&&MT(J.shift())});D(c,F),c.reserved=()=>z.length?c.execute(z.shift()):D(c,F),c.reserved.release=!0;let FT=I(ET);return FT.release=()=>{c.reserved=null,So(c)},FT;function ET(IT){c.queue===_?z.push(IT):c.execute(IT)||D(c,_)}}async function G(z,c){!c&&(c=z,z="");let FT=Oo(),ET=0,IT,fT=null;try{return await Y.unsafe("begin "+z.replace(/[^a-z ]/ig,""),[],{onexecute:BT}).execute(),await Promise.race([_T(IT,c),new Promise((zT,KT)=>IT.onclose=KT)])}catch(zT){throw zT}async function _T(zT,KT,pT){let wT=I(jT);wT.savepoint=Po,wT.prepare=(GT)=>fT=GT.replace(/[^a-z0-9$-_. ]/gi);let Xo,iT;pT&&await wT`savepoint ${wT(pT)}`;try{if(iT=await new Promise((GT,Ko)=>{let Vo=KT(wT);Promise.resolve(Array.isArray(Vo)?Promise.all(Vo):Vo).then(GT,Ko)}),Xo)throw Xo}catch(GT){throw await(pT?wT`rollback to ${wT(pT)}`:wT`rollback`),GT instanceof pS&>.code==="25P02"&&Xo||GT}if(!pT)fT?await wT`prepare transaction '${wT.unsafe(fT)}'`:await wT`commit`;return iT;function Po(GT,Ko){if(GT&&Array.isArray(GT.raw))return Po((Vo)=>Vo.apply(Vo,arguments));return arguments.length===1&&(Ko=GT,GT=null),_T(zT,Ko,"s"+ET+++(GT?"_"+GT:""))}function jT(GT){GT.catch((Ko)=>Xo||(Xo=Ko)),zT.queue===_?FT.push(GT):zT.execute(GT)||D(zT,_)}}function BT(zT){IT=zT,D(zT,F),zT.reserved=()=>FT.length?zT.execute(FT.shift()):D(zT,F)}}function D(z,c){return z.queue.remove(z),c.push(z),z.queue=c,c===W?z.idleTimer.start():z.idleTimer.cancel(),z}function t(z){return new mo(z,3802)}function U(z,c){if(!Array.isArray(z))return U(Array.from(arguments));return new mo(z,c||(z.length?Ln(z)||25:0),S.shared.typeArrayMap)}function v(z){if(n)return z.reject(LT.connection("CONNECTION_ENDED",S,S));if(W.length)return l(W.shift(),z);if(J.length)return MT(J.shift(),z);y.length?l(y.shift(),z):A.push(z)}function l(z,c){return z.execute(c)?D(z,y):D(z,_)}function E(z){return new Promise((c,FT)=>{z.state?z.active?y$(S).cancel(z.state,c,FT):z.cancelled={resolve:c,reject:FT}:(A.remove(z),z.cancelled=!0,z.reject(LT.generic("57014","canceling statement due to user request")),c())})}async function TT({timeout:z=null}={}){if(n)return n;await 1;let c;return n=Promise.race([new Promise((FT)=>z!==null&&(c=setTimeout(oT,z*1000,FT))),Promise.all(H.map((FT)=>FT.end()).concat(b.sql?b.sql.end({timeout:0}):[],f.sql?f.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(c))}async function Z(){await Promise.all(H.map((z)=>z.end()))}async function oT(z){await Promise.all(H.map((c)=>c.terminate()));while(A.length)A.shift().reject(LT.connection("CONNECTION_DESTROYED",S));z()}function MT(z,c){return D(z,$),z.connect(c),z}function CT(z){D(z,R)}function So(z){if(A.length===0)return D(z,W);let c=Math.ceil(A.length/($.length+1)),FT=!0;while(FT&&A.length&&c-- >0){let ET=A.shift();if(ET.reserve)return ET.reserve(z);FT=z.execute(ET)}FT?D(z,y):D(z,_)}function No(z,c){D(z,J),z.reserved=null,z.onclose&&(z.onclose(c),z.onclose=null),S.onclose&&S.onclose(z.id),A.length&&MT(z,A.shift())}}function IM(T,o){if(T&&T.shared)return T;let S=process.env,f=(!T||typeof T==="string"?o:T)||{},{url:n,multihost:A}=bM(T),$=[...n.searchParams].reduce((_,[K,H])=>(_[K]=H,_),{}),F=f.hostname||f.host||A||n.hostname||S.PGHOST||"localhost",J=f.port||n.port||S.PGPORT||5432,R=f.user||f.username||n.username||S.PGUSERNAME||S.PGUSER||xM();f.no_prepare&&(f.prepare=!1),$.sslmode&&($.ssl=$.sslmode,delete $.sslmode),"timeout"in f&&(console.log("The timeout option is deprecated, use idle_timeout instead"),f.idle_timeout=f.timeout),$.sslrootcert==="system"&&($.ssl="verify-full");let W=["idle_timeout","connect_timeout","max_lifetime","max_pipeline","backoff","keep_alive"],y={max:10,ssl:!1,idle_timeout:null,connect_timeout:30,max_lifetime:NM,max_pipeline:100,backoff:mM,keep_alive:60,prepare:!0,debug:!1,fetch_types:!0,publications:"alltables",target_session_attrs:null};return{host:Array.isArray(F)?F:F.split(",").map((_)=>_.split(":")[0]),port:Array.isArray(J)?J:F.split(",").map((_)=>parseInt(_.split(":")[1]||J)),path:f.path||F.indexOf("/")>-1&&F+"/.s.PGSQL."+J,database:f.database||f.db||(n.pathname||"").slice(1)||S.PGDATABASE||R,user:R,pass:f.pass||f.password||n.password||S.PGPASSWORD||"",...Object.entries(y).reduce((_,[K,H])=>{let Y=K in f?f[K]:(K in $)?$[K]==="disable"||$[K]==="false"?!1:$[K]:S["PG"+K.toUpperCase()]||H;return _[K]=typeof Y==="string"&&W.includes(K)?+Y:Y,_},{}),connection:{application_name:"postgres.js",...f.connection,...Object.entries($).reduce((_,[K,H])=>((K in y)||(_[K]=H),_),{})},types:f.types||{},target_session_attrs:jM(f,n,S),onnotice:f.onnotice,onnotify:f.onnotify,onclose:f.onclose,onparameter:f.onparameter,socket:f.socket,transform:hM(f.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...n1(f.types)}}function jM(T,o,S){let f=T.target_session_attrs||o.searchParams.get("target_session_attrs")||S.PGTARGETSESSIONATTRS;if(!f||["read-write","read-only","primary","standby","prefer-standby"].includes(f))return f;throw new Error("target_session_attrs "+f+" is not supported")}function mM(T){return(0.5+Math.random()/2)*Math.min(3**T/100,20)}function NM(){return 60*(30+Math.random()*30)}function hM(T){return{undefined:T.undefined,column:{from:typeof T.column==="function"?T.column:T.column&&T.column.from,to:T.column&&T.column.to},value:{from:typeof T.value==="function"?T.value:T.value&&T.value.from,to:T.value&&T.value.to},row:{from:typeof T.row==="function"?T.row:T.row&&T.row.from,to:T.row&&T.row.to}}}function bM(T){if(!T||typeof T!=="string")return{url:{searchParams:new Map}};let o=T;o=o.slice(o.indexOf("://")+3).split(/[?/]/)[0],o=decodeURIComponent(o.slice(o.indexOf("@")+1));let S=new URL(T.replace(o,o.split(",")[0]));return{url:{username:decodeURIComponent(S.username),password:decodeURIComponent(S.password),host:S.host,hostname:S.hostname,port:S.port,pathname:S.pathname,searchParams:S.searchParams},multihost:o.indexOf(",")>-1&&o}}function xM(){try{return LM.userInfo().username}catch(T){return process.env.USERNAME||process.env.USER||process.env.LOGNAME}}class UT{static[M]="SelectionProxyHandler";config;constructor(T){this.config={...T}}get(T,o){if(o==="_")return{...T._,selectedFields:new Proxy(T._.selectedFields,this)};if(o===XT)return{...T[XT],selectedFields:new Proxy(T[XT].selectedFields,this)};if(typeof o==="symbol")return T[o];let f=(X(T,xT)?T._.selectedFields:X(T,Ao)?T[XT].selectedFields:T)[o];if(X(f,m.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!f.isSelectionField)return f.sql;let n=f.clone();return n.isSelectionField=!0,n}if(X(f,m)){if(this.config.sqlBehavior==="sql")return f;throw new Error(`You tried to reference "${o}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}if(X(f,kT)){if(this.config.alias)return new Proxy(f,new rS(new Proxy(f.table,new Hf(this.config.alias,this.config.replaceOriginalName??!1))));return f}if(typeof f!=="object"||f===null)return f;return new Proxy(f,new UT(this.config))}}class vn extends To{constructor(T,o,S,f){super();this.session=o,this.dialect=S,this.config={table:T,withList:f}}static[M]="PgDelete";config;where(T){return this.config.where=T,this}returning(T=this.config.table[j.Symbol.Columns]){return this.config.returningFields=T,this.config.returning=_o(T),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:T,...o}=this.dialect.sqlToQuery(this.getSQL());return o}_prepare(T){return yT.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,T,!0)})}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return yT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new UT({alias:ZT(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}function vM(T){return(T.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((S)=>S.toLowerCase()).join("_")}function qM(T){return(T.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((S,f,n)=>{let A=n===0?f.toLowerCase():`${f[0].toUpperCase()}${f.slice(1)}`;return S+A},"")}function ZM(T){return T}class X${static[M]="CasingCache";cache={};cachedTables={};convert;constructor(T){this.convert=T==="snake_case"?vM:T==="camelCase"?qM:ZM}getColumnCasing(T){if(!T.keyAsName)return T.name;let o=T.table[j.Symbol.Schema]??"public",S=T.table[j.Symbol.OriginalName],f=`${o}.${S}.${T.name}`;if(!this.cache[f])this.cacheTable(T.table);return this.cache[f]}cacheTable(T){let o=T[j.Symbol.Schema]??"public",S=T[j.Symbol.OriginalName],f=`${o}.${S}`;if(!this.cachedTables[f]){for(let n of Object.values(T[j.Symbol.Columns])){let A=`${f}.${n.name}`;this.cache[A]=this.convert(n.name)}this.cachedTables[f]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class mf extends Ao{static[M]="PgViewBase"}class wS{static[M]="PgDialect";casing;constructor(T){this.casing=new X$(T?.casing)}async migrate(T,o,S){let f=typeof S==="string"?"__drizzle_migrations":S.migrationsTable??"__drizzle_migrations",n=typeof S==="string"?"drizzle":S.migrationsSchema??"drizzle",A=k`
|
|
38
|
-
CREATE TABLE IF NOT EXISTS ${
|
|
37
|
+
`};return f(J),new Promise(async(k)=>$=k);async function R({highWaterMark:k=16384,start:y=0,end:H=1/0}={}){let E=H-y;return y&&await J.seek(y),new w1.Readable({highWaterMark:k,async read(G){let I=G>E?G-E:G;E-=G;let[{data:b}]=await J.read(I);if(this.push(b),b.length<G)this.push(null)}})}async function O({highWaterMark:k=16384,start:y=0}={}){return y&&await J.seek(y),new w1.Writable({highWaterMark:k,write(H,E,G){J.write(H).then(()=>G(),G)}})}}).catch(A)})}Object.assign(xA,{PostgresError:Po,toPascal:ko,pascal:R$,toCamel:_o,camel:J$,toKebab:yo,kebab:O$,fromPascal:Lf,fromCamel:tf,fromKebab:Cf,BigInt:{to:20,from:[20],parse:(T)=>BigInt(T),serialize:(T)=>T.toString()}});var io=xA;function xA(T,S){let o=IW(T,S),f=o.no_subscribe||y$(xA,{...o}),A=!1,n=MS(),$=MS(),F=MS(),J=MS(),R=MS(),O=MS(),k=MS(),y=MS(),H={connecting:$,reserved:F,closed:J,ended:R,open:O,busy:k,full:y},E=[...Array(o.max)].map(()=>k$(o,H,{onopen:oS,onend:CT,onclose:mS})),G=I(v);return Object.assign(G,{get parameters(){return o.parameters},largeObject:w$.bind(null,G),subscribe:f,CLOSE:po,END:po,PostgresError:Po,options:o,reserve:P,listen:b,begin:X,close:Z,end:a}),G;function I(z){return z.debug=o.debug,Object.entries(o.types).reduce((oT,[yT,tT])=>{return oT[yT]=(zT)=>new NS(zT,tT.to),oT},c),Object.assign(FT,{types:c,typed:c,unsafe:YT,notify:q,array:U,json:V,file:IT}),FT;function c(oT,yT){return new NS(oT,yT)}function FT(oT,...yT){return oT&&Array.isArray(oT.raw)?new wS(oT,yT,z,Y):typeof oT==="string"&&!yT.length?new If(o.transform.column.to?o.transform.column.to(oT):oT):new IA(oT,yT)}function YT(oT,yT=[],tT={}){return arguments.length===2&&!Array.isArray(yT)&&(tT=yT,yT=[]),new wS([oT],yT,z,Y,{prepare:!1,...tT,simple:"simple"in tT?tT.simple:yT.length===0})}function IT(oT,yT=[],tT={}){return arguments.length===2&&!Array.isArray(yT)&&(tT=yT,yT=[]),new wS([],yT,(HT)=>{CW.readFile(oT,"utf8",(PT,wT)=>{if(PT)return HT.reject(PT);HT.strings=[wT],z(HT)})},Y,{...tT,simple:"simple"in tT?tT.simple:yT.length===0})}}async function b(z,c,FT){let YT={fn:c,onlisten:FT},IT=b.sql||(b.sql=xA({...o,max:1,idle_timeout:null,max_lifetime:null,fetch_types:!1,onclose(){Object.entries(b.channels).forEach(([HT,{listeners:PT}])=>{delete b.channels[HT],Promise.all(PT.map((wT)=>b(HT,wT.fn,wT.onlisten).catch(()=>{})))})},onnotify(HT,PT){HT in b.channels&&b.channels[HT].listeners.forEach((wT)=>wT.fn(PT))}})),oT=b.channels||(b.channels={});if(z in oT){oT[z].listeners.push(YT);let HT=await oT[z].result;return YT.onlisten&&YT.onlisten(),{state:HT.state,unlisten:zT}}oT[z]={result:IT`listen ${IT.unsafe('"'+z.replace(/"/g,'""')+'"')}`,listeners:[YT]};let tT=await oT[z].result;return YT.onlisten&&YT.onlisten(),{state:tT.state,unlisten:zT};async function zT(){if(z in oT===!1)return;if(oT[z].listeners=oT[z].listeners.filter((HT)=>HT!==YT),oT[z].listeners.length)return;return delete oT[z],IT`unlisten ${IT.unsafe('"'+z.replace(/"/g,'""')+'"')}`}}async function q(z,c){return await G`select pg_notify(${z}, ${""+c})`}async function P(){let z=MS(),c=O.length?O.shift():await new Promise((IT)=>{n.push({reserve:IT}),J.length&&WT(J.shift())});D(c,F),c.reserved=()=>z.length?c.execute(z.shift()):D(c,F),c.reserved.release=!0;let FT=I(YT);return FT.release=()=>{c.reserved=null,oS(c)},FT;function YT(IT){c.queue===y?z.push(IT):c.execute(IT)||D(c,y)}}async function X(z,c){!c&&(c=z,z="");let FT=MS(),YT=0,IT,oT=null;try{return await G.unsafe("begin "+z.replace(/[^a-z ]/ig,""),[],{onexecute:tT}).execute(),await Promise.race([yT(IT,c),new Promise((zT,HT)=>IT.onclose=HT)])}catch(zT){throw zT}async function yT(zT,HT,PT){let wT=I(jT);wT.savepoint=rS,wT.prepare=(XT)=>oT=XT.replace(/[^a-z0-9$-_. ]/gi);let KS,gT;PT&&await wT`savepoint ${wT(PT)}`;try{if(gT=await new Promise((XT,HS)=>{let VS=HT(wT);Promise.resolve(Array.isArray(VS)?Promise.all(VS):VS).then(XT,HS)}),KS)throw KS}catch(XT){throw await(PT?wT`rollback to ${wT(PT)}`:wT`rollback`),XT instanceof Po&&XT.code==="25P02"&&KS||XT}if(!PT)oT?await wT`prepare transaction '${wT.unsafe(oT)}'`:await wT`commit`;return gT;function rS(XT,HS){if(XT&&Array.isArray(XT.raw))return rS((VS)=>VS.apply(VS,arguments));return arguments.length===1&&(HS=XT,XT=null),yT(zT,HS,"s"+YT+++(XT?"_"+XT:""))}function jT(XT){XT.catch((HS)=>KS||(KS=HS)),zT.queue===y?FT.push(XT):zT.execute(XT)||D(zT,y)}}function tT(zT){IT=zT,D(zT,F),zT.reserved=()=>FT.length?zT.execute(FT.shift()):D(zT,F)}}function D(z,c){return z.queue.remove(z),c.push(z),z.queue=c,c===O?z.idleTimer.start():z.idleTimer.cancel(),z}function V(z){return new NS(z,3802)}function U(z,c){if(!Array.isArray(z))return U(Array.from(arguments));return new NS(z,c||(z.length?LA(z)||25:0),o.shared.typeArrayMap)}function v(z){if(A)return z.reject(LT.connection("CONNECTION_ENDED",o,o));if(O.length)return l(O.shift(),z);if(J.length)return WT(J.shift(),z);k.length?l(k.shift(),z):n.push(z)}function l(z,c){return z.execute(c)?D(z,k):D(z,y)}function Y(z){return new Promise((c,FT)=>{z.state?z.active?k$(o).cancel(z.state,c,FT):z.cancelled={resolve:c,reject:FT}:(n.remove(z),z.cancelled=!0,z.reject(LT.generic("57014","canceling statement due to user request")),c())})}async function a({timeout:z=null}={}){if(A)return A;await 1;let c;return A=Promise.race([new Promise((FT)=>z!==null&&(c=setTimeout(TT,z*1000,FT))),Promise.all(E.map((FT)=>FT.end()).concat(b.sql?b.sql.end({timeout:0}):[],f.sql?f.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(c))}async function Z(){await Promise.all(E.map((z)=>z.end()))}async function TT(z){await Promise.all(E.map((c)=>c.terminate()));while(n.length)n.shift().reject(LT.connection("CONNECTION_DESTROYED",o));z()}function WT(z,c){return D(z,$),z.connect(c),z}function CT(z){D(z,R)}function oS(z){if(n.length===0)return D(z,O);let c=Math.ceil(n.length/($.length+1)),FT=!0;while(FT&&n.length&&c-- >0){let YT=n.shift();if(YT.reserve)return YT.reserve(z);FT=z.execute(YT)}FT?D(z,k):D(z,y)}function mS(z,c){D(z,J),z.reserved=null,z.onclose&&(z.onclose(c),z.onclose=null),o.onclose&&o.onclose(z.id),n.length&&WT(z,n.shift())}}function IW(T,S){if(T&&T.shared)return T;let o=process.env,f=(!T||typeof T==="string"?S:T)||{},{url:A,multihost:n}=bW(T),$=[...A.searchParams].reduce((y,[H,E])=>(y[H]=E,y),{}),F=f.hostname||f.host||n||A.hostname||o.PGHOST||"localhost",J=f.port||A.port||o.PGPORT||5432,R=f.user||f.username||A.username||o.PGUSERNAME||o.PGUSER||xW();f.no_prepare&&(f.prepare=!1),$.sslmode&&($.ssl=$.sslmode,delete $.sslmode),"timeout"in f&&(console.log("The timeout option is deprecated, use idle_timeout instead"),f.idle_timeout=f.timeout),$.sslrootcert==="system"&&($.ssl="verify-full");let O=["idle_timeout","connect_timeout","max_lifetime","max_pipeline","backoff","keep_alive"],k={max:10,ssl:!1,idle_timeout:null,connect_timeout:30,max_lifetime:mW,max_pipeline:100,backoff:NW,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((y)=>y.split(":")[0]),port:Array.isArray(J)?J:F.split(",").map((y)=>parseInt(y.split(":")[1]||J)),path:f.path||F.indexOf("/")>-1&&F+"/.s.PGSQL."+J,database:f.database||f.db||(A.pathname||"").slice(1)||o.PGDATABASE||R,user:R,pass:f.pass||f.password||A.password||o.PGPASSWORD||"",...Object.entries(k).reduce((y,[H,E])=>{let G=H in f?f[H]:(H in $)?$[H]==="disable"||$[H]==="false"?!1:$[H]:o["PG"+H.toUpperCase()]||E;return y[H]=typeof G==="string"&&O.includes(H)?+G:G,y},{}),connection:{application_name:"postgres.js",...f.connection,...Object.entries($).reduce((y,[H,E])=>((H in k)||(y[H]=E),y),{})},types:f.types||{},target_session_attrs:jW(f,A,o),onnotice:f.onnotice,onnotify:f.onnotify,onclose:f.onclose,onparameter:f.onparameter,socket:f.socket,transform:hW(f.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...n1(f.types)}}function jW(T,S,o){let f=T.target_session_attrs||S.searchParams.get("target_session_attrs")||o.PGTARGETSESSIONATTRS;if(!f||["read-write","read-only","primary","standby","prefer-standby"].includes(f))return f;throw new Error("target_session_attrs "+f+" is not supported")}function NW(T){return(0.5+Math.random()/2)*Math.min(3**T/100,20)}function mW(){return 60*(30+Math.random()*30)}function hW(T){return{undefined:T.undefined,column:{from:typeof T.column==="function"?T.column:T.column&&T.column.from,to:T.column&&T.column.to},value:{from:typeof T.value==="function"?T.value:T.value&&T.value.from,to:T.value&&T.value.to},row:{from:typeof T.row==="function"?T.row:T.row&&T.row.from,to:T.row&&T.row.to}}}function bW(T){if(!T||typeof T!=="string")return{url:{searchParams:new Map}};let S=T;S=S.slice(S.indexOf("://")+3).split(/[?/]/)[0],S=decodeURIComponent(S.slice(S.indexOf("@")+1));let o=new URL(T.replace(S,S.split(",")[0]));return{url:{username:decodeURIComponent(o.username),password:decodeURIComponent(o.password),host:o.host,hostname:o.hostname,port:o.port,pathname:o.pathname,searchParams:o.searchParams},multihost:S.indexOf(",")>-1&&S}}function xW(){try{return LW.userInfo().username}catch(T){return process.env.USERNAME||process.env.USER||process.env.LOGNAME}}class UT{static[W]="SelectionProxyHandler";config;constructor(T){this.config={...T}}get(T,S){if(S==="_")return{...T._,selectedFields:new Proxy(T._.selectedFields,this)};if(S===KT)return{...T[KT],selectedFields:new Proxy(T[KT].selectedFields,this)};if(typeof S==="symbol")return T[S];let f=(K(T,xT)?T._.selectedFields:K(T,nS)?T[KT].selectedFields:T)[S];if(K(f,N.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!f.isSelectionField)return f.sql;let A=f.clone();return A.isSelectionField=!0,A}if(K(f,N)){if(this.config.sqlBehavior==="sql")return f;throw new Error(`You tried to reference "${S}" 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(K(f,_T)){if(this.config.alias)return new Proxy(f,new ro(new Proxy(f.table,new Ef(this.config.alias,this.config.replaceOriginalName??!1))));return f}if(typeof f!=="object"||f===null)return f;return new Proxy(f,new UT(this.config))}}class vA extends TS{constructor(T,S,o,f){super();this.session=S,this.dialect=o,this.config={table:T,withList:f}}static[W]="PgDelete";config;where(T){return this.config.where=T,this}returning(T=this.config.table[j.Symbol.Columns]){return this.config.returningFields=T,this.config.returning=yS(T),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:T,...S}=this.dialect.sqlToQuery(this.getSQL());return S}_prepare(T){return kT.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,T,!0)})}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return kT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new UT({alias:qT(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}function vW(T){return(T.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((o)=>o.toLowerCase()).join("_")}function qW(T){return(T.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((o,f,A)=>{let n=A===0?f.toLowerCase():`${f[0].toUpperCase()}${f.slice(1)}`;return o+n},"")}function ZW(T){return T}class K${static[W]="CasingCache";cache={};cachedTables={};convert;constructor(T){this.convert=T==="snake_case"?vW:T==="camelCase"?qW:ZW}getColumnCasing(T){if(!T.keyAsName)return T.name;let S=T.table[j.Symbol.Schema]??"public",o=T.table[j.Symbol.OriginalName],f=`${S}.${o}.${T.name}`;if(!this.cache[f])this.cacheTable(T.table);return this.cache[f]}cacheTable(T){let S=T[j.Symbol.Schema]??"public",o=T[j.Symbol.OriginalName],f=`${S}.${o}`;if(!this.cachedTables[f]){for(let A of Object.values(T[j.Symbol.Columns])){let n=`${f}.${A.name}`;this.cache[n]=this.convert(A.name)}this.cachedTables[f]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class Nf extends nS{static[W]="PgViewBase"}class Ko{static[W]="PgDialect";casing;constructor(T){this.casing=new K$(T?.casing)}async migrate(T,S,o){let f=typeof o==="string"?"__drizzle_migrations":o.migrationsTable??"__drizzle_migrations",A=typeof o==="string"?"drizzle":o.migrationsSchema??"drizzle",n=_`
|
|
38
|
+
CREATE TABLE IF NOT EXISTS ${_.identifier(A)}.${_.identifier(f)} (
|
|
39
39
|
id SERIAL PRIMARY KEY,
|
|
40
40
|
hash text NOT NULL,
|
|
41
41
|
created_at bigint
|
|
42
42
|
)
|
|
43
|
-
`;await o.execute(k`CREATE SCHEMA IF NOT EXISTS ${k.identifier(n)}`),await o.execute(A);let F=(await o.all(k`select id, hash, created_at from ${k.identifier(n)}.${k.identifier(f)} order by created_at desc limit 1`))[0];await o.transaction(async(J)=>{for await(let R of T)if(!F||Number(F.created_at)<R.folderMillis){for(let W of R.sql)await J.execute(k.raw(W));await J.execute(k`insert into ${k.identifier(n)}.${k.identifier(f)} ("hash", "created_at") values(${R.hash}, ${R.folderMillis})`)}})}escapeName(T){return`"${T}"`}escapeParam(T){return`$${T+1}`}escapeString(T){return`'${T.replace(/'/g,"''")}'`}buildWithCTE(T){if(!T?.length)return;let o=[k`with `];for(let[S,f]of T.entries())if(o.push(k`${k.identifier(f._.alias)} as (${f._.sql})`),S<T.length-1)o.push(k`, `);return o.push(k` `),k.join(o)}buildDeleteQuery({table:T,where:o,returning:S,withList:f}){let n=this.buildWithCTE(f),A=S?k` returning ${this.buildSelection(S,{isSingleTable:!0})}`:void 0,$=o?k` where ${o}`:void 0;return k`${n}delete from ${T}${$}${A}`}buildUpdateSet(T,o){let S=T[j.Symbol.Columns],f=Object.keys(S).filter((A)=>o[A]!==void 0||S[A]?.onUpdateFn!==void 0),n=f.length;return k.join(f.flatMap((A,$)=>{let F=S[A],J=o[A]??k.param(F.onUpdateFn(),F),R=k`${k.identifier(this.casing.getColumnCasing(F))} = ${J}`;if($<n-1)return[R,k.raw(", ")];return[R]}))}buildUpdateQuery({table:T,set:o,where:S,returning:f,withList:n,from:A,joins:$}){let F=this.buildWithCTE(n),J=T[PT.Symbol.Name],R=T[PT.Symbol.Schema],W=T[PT.Symbol.OriginalName],y=J===W?void 0:J,_=k`${R?k`${k.identifier(R)}.`:void 0}${k.identifier(W)}${y&&k` ${k.identifier(y)}`}`,K=this.buildUpdateSet(T,o),H=A&&k.join([k.raw(" from "),this.buildFromTable(A)]),Y=this.buildJoins($),I=f?k` returning ${this.buildSelection(f,{isSingleTable:!A})}`:void 0,b=S?k` where ${S}`:void 0;return k`${F}update ${_} set ${K}${H}${Y}${b}${I}`}buildSelection(T,{isSingleTable:o=!1}={}){let S=T.length,f=T.flatMap(({field:n},A)=>{let $=[];if(X(n,m.Aliased)&&n.isSelectionField)$.push(k.identifier(n.fieldAlias));else if(X(n,m.Aliased)||X(n,m)){let F=X(n,m.Aliased)?n.sql:n;if(o)$.push(new m(F.queryChunks.map((J)=>{if(X(J,V))return k.identifier(this.casing.getColumnCasing(J));return J})));else $.push(F);if(X(n,m.Aliased))$.push(k` as ${k.identifier(n.fieldAlias)}`)}else if(X(n,kT))if(o)$.push(k.identifier(this.casing.getColumnCasing(n)));else $.push(n);if(A<S-1)$.push(k`, `);return $});return k.join(f)}buildJoins(T){if(!T||T.length===0)return;let o=[];for(let[S,f]of T.entries()){if(S===0)o.push(k` `);let n=f.table,A=f.lateral?k` lateral`:void 0;if(X(n,PT)){let $=n[PT.Symbol.Name],F=n[PT.Symbol.Schema],J=n[PT.Symbol.OriginalName],R=$===J?void 0:f.alias;o.push(k`${k.raw(f.joinType)} join${A} ${F?k`${k.identifier(F)}.`:void 0}${k.identifier(J)}${R&&k` ${k.identifier(R)}`} on ${f.on}`)}else if(X(n,Ao)){let $=n[XT].name,F=n[XT].schema,J=n[XT].originalName,R=$===J?void 0:f.alias;o.push(k`${k.raw(f.joinType)} join${A} ${F?k`${k.identifier(F)}.`:void 0}${k.identifier(J)}${R&&k` ${k.identifier(R)}`} on ${f.on}`)}else o.push(k`${k.raw(f.joinType)} join${A} ${n} on ${f.on}`);if(S<T.length-1)o.push(k` `)}return k.join(o)}buildFromTable(T){if(X(T,j)&&T[j.Symbol.OriginalName]!==T[j.Symbol.Name]){let o=k`${k.identifier(T[j.Symbol.OriginalName])}`;if(T[j.Symbol.Schema])o=k`${k.identifier(T[j.Symbol.Schema])}.${o}`;return k`${o} ${k.identifier(T[j.Symbol.Name])}`}return T}buildSelectQuery({withList:T,fields:o,fieldsFlat:S,where:f,having:n,table:A,joins:$,orderBy:F,groupBy:J,limit:R,offset:W,lockingClause:y,distinct:_,setOperators:K}){let H=S??_o(o);for(let oT of H)if(X(oT.field,kT)&&ZT(oT.field.table)!==(X(A,xT)?A._.alias:X(A,mf)?A[XT].name:X(A,m)?void 0:ZT(A))&&!((MT)=>$?.some(({alias:CT})=>CT===(MT[j.Symbol.IsAlias]?ZT(MT):MT[j.Symbol.BaseName])))(oT.field.table)){let MT=ZT(oT.field.table);throw new Error(`Your "${oT.path.join("->")}" field references a column "${MT}"."${oT.field.name}", but the table "${MT}" is not part of the query! Did you forget to join it?`)}let Y=!$||$.length===0,I=this.buildWithCTE(T),b;if(_)b=_===!0?k` distinct`:k` distinct on (${k.join(_.on,k`, `)})`;let q=this.buildSelection(H,{isSingleTable:Y}),p=this.buildFromTable(A),G=this.buildJoins($),D=f?k` where ${f}`:void 0,t=n?k` having ${n}`:void 0,U;if(F&&F.length>0)U=k` order by ${k.join(F,k`, `)}`;let v;if(J&&J.length>0)v=k` group by ${k.join(J,k`, `)}`;let l=typeof R==="object"||typeof R==="number"&&R>=0?k` limit ${R}`:void 0,E=W?k` offset ${W}`:void 0,TT=k.empty();if(y){let oT=k` for ${k.raw(y.strength)}`;if(y.config.of)oT.append(k` of ${k.join(Array.isArray(y.config.of)?y.config.of:[y.config.of],k`, `)}`);if(y.config.noWait)oT.append(k` no wait`);else if(y.config.skipLocked)oT.append(k` skip locked`);TT.append(oT)}let Z=k`${I}select${b} ${q} from ${p}${G}${D}${v}${t}${U}${l}${E}${TT}`;if(K.length>0)return this.buildSetOperations(Z,K);return Z}buildSetOperations(T,o){let[S,...f]=o;if(!S)throw new Error("Cannot pass undefined values to any set operator");if(f.length===0)return this.buildSetOperationQuery({leftSelect:T,setOperator:S});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:T,setOperator:S}),f)}buildSetOperationQuery({leftSelect:T,setOperator:{type:o,isAll:S,rightSelect:f,limit:n,orderBy:A,offset:$}}){let F=k`(${T.getSQL()}) `,J=k`(${f.getSQL()})`,R;if(A&&A.length>0){let K=[];for(let H of A)if(X(H,V))K.push(k.identifier(H.name));else if(X(H,m)){for(let Y=0;Y<H.queryChunks.length;Y++){let I=H.queryChunks[Y];if(X(I,V))H.queryChunks[Y]=k.identifier(I.name)}K.push(k`${H}`)}else K.push(k`${H}`);R=k` order by ${k.join(K,k`, `)} `}let W=typeof n==="object"||typeof n==="number"&&n>=0?k` limit ${n}`:void 0,y=k.raw(`${o} ${S?"all ":""}`),_=$?k` offset ${$}`:void 0;return k`${F}${y}${J}${R}${W}${_}`}buildInsertQuery({table:T,values:o,onConflict:S,returning:f,withList:n,select:A,overridingSystemValue_:$}){let F=[],J=T[j.Symbol.Columns],R=Object.entries(J).filter(([I,b])=>!b.shouldDisableInsert()),W=R.map(([,I])=>k.identifier(this.casing.getColumnCasing(I)));if(A){let I=o;if(X(I,m))F.push(I);else F.push(I.getSQL())}else{let I=o;F.push(k.raw("values "));for(let[b,q]of I.entries()){let p=[];for(let[G,D]of R){let t=q[G];if(t===void 0||X(t,Ro)&&t.value===void 0)if(D.defaultFn!==void 0){let U=D.defaultFn(),v=X(U,m)?U:k.param(U,D);p.push(v)}else if(!D.default&&D.onUpdateFn!==void 0){let U=D.onUpdateFn(),v=X(U,m)?U:k.param(U,D);p.push(v)}else p.push(k`default`);else p.push(t)}if(F.push(p),b<I.length-1)F.push(k`, `)}}let y=this.buildWithCTE(n),_=k.join(F),K=f?k` returning ${this.buildSelection(f,{isSingleTable:!0})}`:void 0,H=S?k` on conflict ${S}`:void 0,Y=$===!0?k`overriding system value `:void 0;return k`${y}insert into ${T} ${W} ${Y}${_}${H}${K}`}buildRefreshMaterializedViewQuery({view:T,concurrently:o,withNoData:S}){let f=o?k` concurrently`:void 0,n=S?k` with no data`:void 0;return k`refresh materialized view${f} ${T}${n}`}prepareTyping(T){if(X(T,En)||X(T,Yn))return"json";else if(X(T,Hn))return"decimal";else if(X(T,zn))return"time";else if(X(T,Qn)||X(T,Dn))return"timestamp";else if(X(T,Xn)||X(T,Kn))return"date";else if(X(T,Un))return"uuid";else return"none"}sqlToQuery(T,o){return T.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,prepareTyping:this.prepareTyping,invokeSource:o})}buildRelationalQueryWithoutPK({fullSchema:T,schema:o,tableNamesMap:S,table:f,tableConfig:n,queryConfig:A,tableAlias:$,nestedQueryRelation:F,joinOn:J}){let R=[],W,y,_=[],K,H=[];if(A===!0)R=Object.entries(n.columns).map(([b,q])=>({dbKey:q.name,tsKey:b,field:jo(q,$),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let I=Object.fromEntries(Object.entries(n.columns).map(([t,U])=>[t,jo(U,$)]));if(A.where){let t=typeof A.where==="function"?A.where(I,p0()):A.where;K=t&&zf(t,$)}let b=[],q=[];if(A.columns){let t=!1;for(let[U,v]of Object.entries(A.columns)){if(v===void 0)continue;if(U in n.columns){if(!t&&v===!0)t=!0;q.push(U)}}if(q.length>0)q=t?q.filter((U)=>A.columns?.[U]===!0):Object.keys(n.columns).filter((U)=>!q.includes(U))}else q=Object.keys(n.columns);for(let t of q){let U=n.columns[t];b.push({tsKey:t,value:U})}let p=[];if(A.with)p=Object.entries(A.with).filter((t)=>!!t[1]).map(([t,U])=>({tsKey:t,queryConfig:U,relation:n.relations[t]}));let G;if(A.extras){G=typeof A.extras==="function"?A.extras(I,{sql:k}):A.extras;for(let[t,U]of Object.entries(G))b.push({tsKey:t,value:iA(U,$)})}for(let{tsKey:t,value:U}of b)R.push({dbKey:X(U,m.Aliased)?U.fieldAlias:n.columns[t].name,tsKey:t,field:X(U,kT)?jo(U,$):U,relationTableTsKey:void 0,isJson:!1,selection:[]});let D=typeof A.orderBy==="function"?A.orderBy(I,i0()):A.orderBy??[];if(!Array.isArray(D))D=[D];_=D.map((t)=>{if(X(t,kT))return jo(t,$);return zf(t,$)}),W=A.limit,y=A.offset;for(let{tsKey:t,queryConfig:U,relation:v}of p){let l=d0(o,S,v),E=OS(v.referencedTable),TT=S[E],Z=`${$}_${t}`,oT=Qf(...l.fields.map((So,No)=>_n(jo(l.references[No],Z),jo(So,$)))),MT=this.buildRelationalQueryWithoutPK({fullSchema:T,schema:o,tableNamesMap:S,table:T[TT],tableConfig:o[TT],queryConfig:X(v,SS)?U===!0?{limit:1}:{...U,limit:1}:U,tableAlias:Z,joinOn:oT,nestedQueryRelation:v}),CT=k`${k.identifier(Z)}.${k.identifier("data")}`.as(t);H.push({on:k`true`,table:new xT(MT.sql,{},Z),alias:Z,joinType:"left",lateral:!0}),R.push({dbKey:t,tsKey:t,field:CT,relationTableTsKey:TT,isJson:!0,selection:MT.selection})}}if(R.length===0)throw new yn({message:`No fields selected for table "${n.tsName}" ("${$}")`});let Y;if(K=Qf(J,K),F){let I=k`json_build_array(${k.join(R.map(({field:p,tsKey:G,isJson:D})=>D?k`${k.identifier(`${$}_${G}`)}.${k.identifier("data")}`:X(p,m.Aliased)?p.sql:p),k`, `)})`;if(X(F,Vf))I=k`coalesce(json_agg(${I}${_.length>0?k` order by ${k.join(_,k`, `)}`:void 0}), '[]'::json)`;let b=[{dbKey:"data",tsKey:"data",field:I.as("data"),isJson:!0,relationTableTsKey:n.tsName,selection:R}];if(W!==void 0||y!==void 0||_.length>0)Y=this.buildSelectQuery({table:kn(f,$),fields:{},fieldsFlat:[{path:[],field:k.raw("*")}],where:K,limit:W,offset:y,orderBy:_,setOperators:[]}),K=void 0,W=void 0,y=void 0,_=[];else Y=kn(f,$);Y=this.buildSelectQuery({table:X(Y,PT)?Y:new xT(Y,{},$),fields:{},fieldsFlat:b.map(({field:p})=>({path:[],field:X(p,kT)?jo(p,$):p})),joins:H,where:K,limit:W,offset:y,orderBy:_,setOperators:[]})}else Y=this.buildSelectQuery({table:kn(f,$),fields:{},fieldsFlat:R.map(({field:I})=>({path:[],field:X(I,kT)?jo(I,$):I})),joins:H,where:K,limit:W,offset:y,orderBy:_,setOperators:[]});return{tableTsKey:n.tsName,sql:Y,selection:R}}}class K${static[M]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class oo{static[M]="PgSelectBuilder";fields;session;dialect;withList=[];distinct;constructor(T){if(this.fields=T.fields,this.session=T.session,this.dialect=T.dialect,T.withList)this.withList=T.withList;this.distinct=T.distinct}authToken;setToken(T){return this.authToken=T,this}from(T){let o=!!this.fields,S=T,f;if(this.fields)f=this.fields;else if(X(S,xT))f=Object.fromEntries(Object.keys(S._.selectedFields).map((n)=>[n,S[n]]));else if(X(S,mf))f=S[XT].selectedFields;else if(X(S,m))f={};else f=lJ(S);return new G$({table:S,fields:f,isPartialSelect:o,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}}class w1 extends K${static[M]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;constructor({table:T,fields:o,isPartialSelect:S,session:f,dialect:n,withList:A,distinct:$}){super();this.config={withList:A,table:T,fields:{...o},distinct:$,setOperators:[]},this.isPartialSelect=S,this.session=f,this.dialect=n,this._={selectedFields:o},this.tableName=co(T),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}createJoin(T){return(o,S)=>{let f=this.tableName,n=co(o);if(typeof n==="string"&&this.config.joins?.some((A)=>A.alias===n))throw new Error(`Alias "${n}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof f==="string")this.config.fields={[f]:this.config.fields};if(typeof n==="string"&&!X(o,m)){let A=X(o,xT)?o._.selectedFields:X(o,Ao)?o[XT].selectedFields:o[j.Symbol.Columns];this.config.fields[n]=A}}if(typeof S==="function")S=S(new Proxy(this.config.fields,new UT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:S,table:o,joinType:T,alias:n}),typeof n==="string")switch(T){case"left":{this.joinsNotNullableMap[n]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([A])=>[A,!1])),this.joinsNotNullableMap[n]=!0;break}case"inner":{this.joinsNotNullableMap[n]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([A])=>[A,!1])),this.joinsNotNullableMap[n]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");createSetOperator(T,o){return(S)=>{let f=typeof S==="function"?S(cM()):S;if(!Df(this.getSelectedFields(),f.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return this.config.setOperators.push({type:T,isAll:o,rightSelect:f}),this}}union=this.createSetOperator("union",!1);unionAll=this.createSetOperator("union",!0);intersect=this.createSetOperator("intersect",!1);intersectAll=this.createSetOperator("intersect",!0);except=this.createSetOperator("except",!1);exceptAll=this.createSetOperator("except",!0);addSetOperators(T){return this.config.setOperators.push(...T),this}where(T){if(typeof T==="function")T=T(new Proxy(this.config.fields,new UT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=T,this}having(T){if(typeof T==="function")T=T(new Proxy(this.config.fields,new UT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=T,this}groupBy(...T){if(typeof T[0]==="function"){let o=T[0](new Proxy(this.config.fields,new UT({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(o)?o:[o]}else this.config.groupBy=T;return this}orderBy(...T){if(typeof T[0]==="function"){let o=T[0](new Proxy(this.config.fields,new UT({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),S=Array.isArray(o)?o:[o];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=S;else this.config.orderBy=S}else{let o=T;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=o;else this.config.orderBy=o}return this}limit(T){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=T;else this.config.limit=T;return this}offset(T){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=T;else this.config.offset=T;return this}for(T,o={}){return this.config.lockingClause={strength:T,config:o},this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:T,...o}=this.dialect.sqlToQuery(this.getSQL());return o}as(T){return new Proxy(new xT(this.getSQL(),this.config.fields,T),new UT({alias:T,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new UT({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}}class G$ extends w1{static[M]="PgSelect";_prepare(T){let{session:o,config:S,dialect:f,joinsNotNullableMap:n,authToken:A}=this;if(!o)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");return yT.startActiveSpan("drizzle.prepareQuery",()=>{let $=_o(S.fields),F=o.prepareQuery(f.sqlToQuery(this.getSQL()),$,T,!0);return F.joinsNotNullableMap=n,F.setToken(A)})}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return yT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T,this.authToken)})}}dJ(G$,[To]);function dS(T,o){return(S,f,...n)=>{let A=[f,...n].map(($)=>({type:T,isAll:o,rightSelect:$}));for(let $ of A)if(!Df(S.getSelectedFields(),$.rightSelect.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return S.addSetOperators(A)}}var cM=()=>({union:rM,unionAll:PM,intersect:pM,intersectAll:iM,except:gM,exceptAll:dM}),rM=dS("union",!1),PM=dS("union",!0),pM=dS("intersect",!1),iM=dS("intersect",!0),gM=dS("except",!1),dM=dS("except",!0);class Nf{static[M]="PgQueryBuilder";dialect;dialectConfig;constructor(T){this.dialect=X(T,wS)?T:void 0,this.dialectConfig=X(T,wS)?void 0:T}$with=(T,o)=>{let S=this;return{as:(n)=>{if(typeof n==="function")n=n(S);return new Proxy(new Yf(n.getSQL(),o??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),T,!0),new UT({alias:T,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...T){let o=this;function S(A){return new oo({fields:A??void 0,session:void 0,dialect:o.getDialect(),withList:T})}function f(A){return new oo({fields:A??void 0,session:void 0,dialect:o.getDialect(),distinct:!0})}function n(A,$){return new oo({fields:$??void 0,session:void 0,dialect:o.getDialect(),distinct:{on:A}})}return{select:S,selectDistinct:f,selectDistinctOn:n}}select(T){return new oo({fields:T??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(T){return new oo({fields:T??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(T,o){return new oo({fields:o??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:T}})}getDialect(){if(!this.dialect)this.dialect=new wS(this.dialectConfig);return this.dialect}}class qn{constructor(T,o,S,f,n){this.table=T,this.session=o,this.dialect=S,this.withList=f,this.overridingSystemValue_=n}static[M]="PgInsertBuilder";authToken;setToken(T){return this.authToken=T,this}overridingSystemValue(){return this.overridingSystemValue_=!0,this}values(T){if(T=Array.isArray(T)?T:[T],T.length===0)throw new Error("values() must be called with at least one value");let o=T.map((S)=>{let f={},n=this.table[j.Symbol.Columns];for(let A of Object.keys(S)){let $=S[A];f[A]=X($,m)?$:new Ro($,n[A])}return f});return new Y$(this.table,o,this.session,this.dialect,this.withList,!1,this.overridingSystemValue_).setToken(this.authToken)}select(T){let o=typeof T==="function"?T(new Nf):T;if(!X(o,m)&&!Df(this.table[On],o._.selectedFields))throw new Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");return new Y$(this.table,o,this.session,this.dialect,this.withList,!0)}}class Y$ extends To{constructor(T,o,S,f,n,A,$){super();this.session=S,this.dialect=f,this.config={table:T,values:o,withList:n,select:A,overridingSystemValue_:$}}static[M]="PgInsert";config;returning(T=this.config.table[j.Symbol.Columns]){return this.config.returningFields=T,this.config.returning=_o(T),this}onConflictDoNothing(T={}){if(T.target===void 0)this.config.onConflict=k`do nothing`;else{let o="";o=Array.isArray(T.target)?T.target.map((f)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(f))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(T.target));let S=T.where?k` where ${T.where}`:void 0;this.config.onConflict=k`(${k.raw(o)})${S} do nothing`}return this}onConflictDoUpdate(T){if(T.where&&(T.targetWhere||T.setWhere))throw new Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');let o=T.where?k` where ${T.where}`:void 0,S=T.targetWhere?k` where ${T.targetWhere}`:void 0,f=T.setWhere?k` where ${T.setWhere}`:void 0,n=this.dialect.buildUpdateSet(this.config.table,wn(this.config.table,T.set)),A="";return A=Array.isArray(T.target)?T.target.map(($)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing($))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(T.target)),this.config.onConflict=k`(${k.raw(A)})${S} do update set ${n}${o}${f}`,this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:T,...o}=this.dialect.sqlToQuery(this.getSQL());return o}_prepare(T){return yT.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,T,!0)})}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return yT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new UT({alias:ZT(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class E$ extends To{constructor(T,o,S){super();this.session=o,this.dialect=S,this.config={view:T}}static[M]="PgRefreshMaterializedView";config;concurrently(){if(this.config.withNoData!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.concurrently=!0,this}withNoData(){if(this.config.concurrently!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.withNoData=!0,this}getSQL(){return this.dialect.buildRefreshMaterializedViewQuery(this.config)}toSQL(){let{typings:T,...o}=this.dialect.sqlToQuery(this.getSQL());return o}_prepare(T){return yT.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),void 0,T,!0)})}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return yT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T,this.authToken)})}}class Zn{constructor(T,o,S,f){this.table=T,this.session=o,this.dialect=S,this.withList=f}static[M]="PgUpdateBuilder";authToken;setToken(T){return this.authToken=T,this}set(T){return new X1(this.table,wn(this.table,T),this.session,this.dialect,this.withList).setToken(this.authToken)}}class X1 extends To{constructor(T,o,S,f,n){super();this.session=S,this.dialect=f,this.config={set:o,table:T,withList:n,joins:[]},this.tableName=co(T),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}static[M]="PgUpdate";config;tableName;joinsNotNullableMap;from(T){let o=T,S=co(o);if(typeof S==="string")this.joinsNotNullableMap[S]=!0;return this.config.from=o,this}getTableLikeFields(T){if(X(T,PT))return T[j.Symbol.Columns];else if(X(T,xT))return T._.selectedFields;return T[XT].selectedFields}createJoin(T){return(o,S)=>{let f=co(o);if(typeof f==="string"&&this.config.joins.some((n)=>n.alias===f))throw new Error(`Alias "${f}" is already used in this query`);if(typeof S==="function"){let n=this.config.from&&!X(this.config.from,m)?this.getTableLikeFields(this.config.from):void 0;S=S(new Proxy(this.config.table[j.Symbol.Columns],new UT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),n&&new Proxy(n,new UT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}if(this.config.joins.push({on:S,table:o,joinType:T,alias:f}),typeof f==="string")switch(T){case"left":{this.joinsNotNullableMap[f]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([n])=>[n,!1])),this.joinsNotNullableMap[f]=!0;break}case"inner":{this.joinsNotNullableMap[f]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([n])=>[n,!1])),this.joinsNotNullableMap[f]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(T){return this.config.where=T,this}returning(T){if(!T){if(T=Object.assign({},this.config.table[j.Symbol.Columns]),this.config.from){let o=co(this.config.from);if(typeof o==="string"&&this.config.from&&!X(this.config.from,m)){let S=this.getTableLikeFields(this.config.from);T[o]=S}for(let S of this.config.joins){let f=co(S.table);if(typeof f==="string"&&!X(S.table,m)){let n=this.getTableLikeFields(S.table);T[f]=n}}}}return this.config.returningFields=T,this.config.returning=_o(T),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:T,...o}=this.dialect.sqlToQuery(this.getSQL());return o}_prepare(T){let o=this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,T,!0);return o.joinsNotNullableMap=this.joinsNotNullableMap,o}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return this._prepare().execute(T,this.authToken)};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new UT({alias:ZT(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class hf extends m{constructor(T){super(hf.buildEmbeddedCount(T.source,T.filters).queryChunks);this.params=T,this.mapWith(Number),this.session=T.session,this.sql=hf.buildCount(T.source,T.filters)}sql;token;static[M]="PgCountBuilder";[Symbol.toStringTag]="PgCountBuilder";session;static buildEmbeddedCount(T,o){return k`(select count(*) from ${T}${k.raw(" where ").if(o)}${o})`}static buildCount(T,o){return k`select count(*) as count from ${T}${k.raw(" where ").if(o)}${o};`}setToken(T){return this.token=T,this}then(T,o){return Promise.resolve(this.session.count(this.sql,this.token)).then(T,o)}catch(T){return this.then(void 0,T)}finally(T){return this.then((o)=>{return T?.(),o},(o)=>{throw T?.(),o})}}class z${constructor(T,o,S,f,n,A,$){this.fullSchema=T,this.schema=o,this.tableNamesMap=S,this.table=f,this.tableConfig=n,this.dialect=A,this.session=$}static[M]="PgRelationalQueryBuilder";findMany(T){return new H$(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,T?T:{},"many")}findFirst(T){return new H$(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,T?{...T,limit:1}:{limit:1},"first")}}class H$ extends To{constructor(T,o,S,f,n,A,$,F,J){super();this.fullSchema=T,this.schema=o,this.tableNamesMap=S,this.table=f,this.tableConfig=n,this.dialect=A,this.session=$,this.config=F,this.mode=J}static[M]="PgRelationalQuery";_prepare(T){return yT.startActiveSpan("drizzle.prepareQuery",()=>{let{query:o,builtQuery:S}=this._toSQL();return this.session.prepareQuery(S,void 0,T,!0,(f,n)=>{let A=f.map(($)=>tn(this.schema,this.tableConfig,$,o.selection,n));if(this.mode==="first")return A[0];return A})})}prepare(T){return this._prepare(T)}_getQuery(){return this.dialect.buildRelationalQueryWithoutPK({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName})}getSQL(){return this._getQuery().sql}_toSQL(){let T=this._getQuery(),o=this.dialect.sqlToQuery(T.sql);return{query:T,builtQuery:o}}toSQL(){return this._toSQL().builtQuery}authToken;setToken(T){return this.authToken=T,this}execute(){return yT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(void 0,this.authToken)})}}class Q$ extends To{constructor(T,o,S,f){super();this.execute=T,this.sql=o,this.query=S,this.mapBatchResult=f}static[M]="PgRaw";getSQL(){return this.sql}getQuery(){return this.query}mapResult(T,o){return o?this.mapBatchResult(T):T}_prepare(){return this}isResponseInArrayMode(){return!1}}class bf{constructor(T,o,S){if(this.dialect=T,this.session=o,this._=S?{schema:S.schema,fullSchema:S.fullSchema,tableNamesMap:S.tableNamesMap,session:o}:{schema:void 0,fullSchema:{},tableNamesMap:{},session:o},this.query={},this._.schema)for(let[f,n]of Object.entries(this._.schema))this.query[f]=new z$(S.fullSchema,this._.schema,this._.tableNamesMap,S.fullSchema[f],n,T,o)}static[M]="PgDatabase";query;$with=(T,o)=>{let S=this;return{as:(n)=>{if(typeof n==="function")n=n(new Nf(S.dialect));return new Proxy(new Yf(n.getSQL(),o??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),T,!0),new UT({alias:T,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(T,o){return new hf({source:T,filters:o,session:this.session})}with(...T){let o=this;function S(J){return new oo({fields:J??void 0,session:o.session,dialect:o.dialect,withList:T})}function f(J){return new oo({fields:J??void 0,session:o.session,dialect:o.dialect,withList:T,distinct:!0})}function n(J,R){return new oo({fields:R??void 0,session:o.session,dialect:o.dialect,withList:T,distinct:{on:J}})}function A(J){return new Zn(J,o.session,o.dialect,T)}function $(J){return new qn(J,o.session,o.dialect,T)}function F(J){return new vn(J,o.session,o.dialect,T)}return{select:S,selectDistinct:f,selectDistinctOn:n,update:A,insert:$,delete:F}}select(T){return new oo({fields:T??void 0,session:this.session,dialect:this.dialect})}selectDistinct(T){return new oo({fields:T??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(T,o){return new oo({fields:o??void 0,session:this.session,dialect:this.dialect,distinct:{on:T}})}update(T){return new Zn(T,this.session,this.dialect)}insert(T){return new qn(T,this.session,this.dialect)}delete(T){return new vn(T,this.session,this.dialect)}refreshMaterializedView(T){return new E$(T,this.session,this.dialect)}authToken;execute(T){let o=typeof T==="string"?k.raw(T):T.getSQL(),S=this.dialect.sqlToQuery(o),f=this.session.prepareQuery(S,void 0,void 0,!1);return new Q$(()=>f.execute(void 0,this.authToken),o,S,(n)=>f.mapResult(n,!0))}transaction(T,o){return this.session.transaction(T,o)}}class K1{constructor(T,o){this.unique=T,this.name=o}static[M]="PgIndexBuilderOn";on(...T){return new cn(T.map((o)=>{if(X(o,m))return o;o=o;let S=new Gf(o.name,!!o.keyAsName,o.columnType,o.indexConfig);return o.indexConfig=JSON.parse(JSON.stringify(o.defaultConfig)),S}),this.unique,!1,this.name)}onOnly(...T){return new cn(T.map((o)=>{if(X(o,m))return o;o=o;let S=new Gf(o.name,!!o.keyAsName,o.columnType,o.indexConfig);return o.indexConfig=o.defaultConfig,S}),this.unique,!0,this.name)}using(T,...o){return new cn(o.map((S)=>{if(X(S,m))return S;S=S;let f=new Gf(S.name,!!S.keyAsName,S.columnType,S.indexConfig);return S.indexConfig=JSON.parse(JSON.stringify(S.defaultConfig)),f}),this.unique,!0,this.name,T)}}class cn{static[M]="PgIndexBuilder";config;constructor(T,o,S,f,n="btree"){this.config={name:f,columns:T,unique:o,only:S,method:n}}concurrently(){return this.config.concurrently=!0,this}with(T){return this.config.with=T,this}where(T){return this.config.where=T,this}build(T){return new G1(this.config,T)}}class G1{static[M]="PgIndex";config;constructor(T,o){this.config={...T,table:o}}}function D$(T){return new K1(!0,T)}class U${constructor(T){this.query=T}authToken;getQuery(){return this.query}mapResult(T,o){return T}setToken(T){return this.authToken=T,this}static[M]="PgPreparedQuery";joinsNotNullableMap}class t${constructor(T){this.dialect=T}static[M]="PgSession";execute(T,o){return yT.startActiveSpan("drizzle.operation",()=>{return yT.startActiveSpan("drizzle.prepareQuery",()=>{return this.prepareQuery(this.dialect.sqlToQuery(T),void 0,void 0,!1)}).setToken(o).execute(void 0,o)})}all(T){return this.prepareQuery(this.dialect.sqlToQuery(T),void 0,void 0,!1).all()}async count(T,o){let S=await this.execute(T,o);return Number(S[0].count)}}class V$ extends bf{constructor(T,o,S,f=0){super(T,o,S);this.schema=S,this.nestedIndex=f}static[M]="PgTransaction";rollback(){throw new gA}getTransactionConfigSQL(T){let o=[];if(T.isolationLevel)o.push(`isolation level ${T.isolationLevel}`);if(T.accessMode)o.push(T.accessMode);if(typeof T.deferrable==="boolean")o.push(T.deferrable?"deferrable":"not deferrable");return k.raw(o.join(" "))}setTransaction(T){return this.session.execute(k`set transaction ${this.getTransactionConfigSQL(T)}`)}}class Y1 extends U${constructor(T,o,S,f,n,A,$){super({sql:o,params:S});this.client=T,this.queryString=o,this.params=S,this.logger=f,this.fields=n,this._isResponseInArrayMode=A,this.customResultMapper=$}static[M]="PostgresJsPreparedQuery";async execute(T={}){return yT.startActiveSpan("drizzle.execute",async(o)=>{let S=pA(this.params,T);o?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(S)}),this.logger.logQuery(this.queryString,S);let{fields:f,queryString:n,client:A,joinsNotNullableMap:$,customResultMapper:F}=this;if(!f&&!F)return yT.startActiveSpan("drizzle.driver.execute",()=>{return A.unsafe(n,S)});let J=await yT.startActiveSpan("drizzle.driver.execute",()=>{return o?.setAttributes({"drizzle.query.text":n,"drizzle.query.params":JSON.stringify(S)}),A.unsafe(n,S).values()});return yT.startActiveSpan("drizzle.mapResponse",()=>{return F?F(J):J.map((R)=>gJ(f,R,$))})})}all(T={}){return yT.startActiveSpan("drizzle.execute",async(o)=>{let S=pA(this.params,T);return o?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(S)}),this.logger.logQuery(this.queryString,S),yT.startActiveSpan("drizzle.driver.execute",()=>{return o?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(S)}),this.client.unsafe(this.queryString,S)})})}isResponseInArrayMode(){return this._isResponseInArrayMode}}class xf extends t${constructor(T,o,S,f={}){super(o);this.client=T,this.schema=S,this.options=f,this.logger=f.logger??new lA}static[M]="PostgresJsSession";logger;prepareQuery(T,o,S,f,n){return new Y1(this.client,T.sql,T.params,this.logger,o,f,n)}query(T,o){return this.logger.logQuery(T,o),this.client.unsafe(T,o).values()}queryObjects(T,o){return this.client.unsafe(T,o)}transaction(T,o){return this.client.begin(async(S)=>{let f=new xf(S,this.dialect,this.schema,this.options),n=new B$(this.dialect,f,this.schema);if(o)await n.setTransaction(o);return T(n)})}}class B$ extends V${constructor(T,o,S,f=0){super(T,o,S,f);this.session=o}static[M]="PostgresJsTransaction";transaction(T){return this.session.client.savepoint((o)=>{let S=new xf(o,this.dialect,this.schema,this.session.options),f=new B$(this.dialect,S,this.schema);return T(f)})}}class E1 extends bf{static[M]="PostgresJsDatabase"}function lS(T,o={}){let S=(J)=>J;for(let J of["1184","1082","1083","1114"])T.options.parsers[J]=S,T.options.serializers[J]=S;T.options.serializers["114"]=S,T.options.serializers["3802"]=S;let f=new wS({casing:o.casing}),n;if(o.logger===!0)n=new dA;else if(o.logger!==!1)n=o.logger;let A;if(o.schema){let J=g0(o.schema,l0);A={fullSchema:o.schema,schema:J.tables,tableNamesMap:J.tableNamesMap}}let $=new xf(T,f,A,{logger:n}),F=new E1(f,$,A);return F.$client=T,F}function rn(...T){if(typeof T[0]==="string"){let o=gS(T[0]);return lS(o,T[1])}if(uJ(T[0])){let{connection:o,client:S,...f}=T[0];if(S)return lS(S,f);if(typeof o==="object"&&o.url!==void 0){let{url:A,...$}=o,F=gS(A,$);return lS(F,f)}let n=gS(o);return lS(n,f)}return lS(T[0],T[1])}((T)=>{function o(S){return lS({options:{parsers:{},serializers:{}}},S)}T.mock=o})(rn||(rn={}));var C$={};UW(C$,{users:()=>XS,userChanges:()=>uM,untrackedUserColumnNames:()=>lM,twoFactorMethod:()=>U1,trackedUserColumnName:()=>D1,trackableUserColumnNames:()=>Q1,role:()=>z1,players:()=>L$,passwordResetAttempts:()=>aM,loginHistory:()=>eM,games:()=>Pn,banishedIps:()=>sM});function H1(T){return k`lower(${T})`}var z1=Rn("role",["admin","user"]),XS=oS("users",{id:Wo().primaryKey().defaultRandom(),username:rT({length:16}).notNull(),email:rT({length:254}).notNull(),hash:rT({length:64}).notNull(),salt:rT({length:36}).notNull(),createdAt:to({withTimezone:!0}).notNull().defaultNow(),createdIp:rT({length:45}).notNull(),isActive:Uf().notNull().default(!1),verifiedAt:to({withTimezone:!0}),userRole:z1().default("user")},(T)=>[D$("usernameUniqueIndex").on(H1(T.username)),D$("emailUniqueIndex").on(H1(T.email))]),lM=["id","createdAt","createdIp","isActive","salt","verifiedAt"],Q1=["username","email","hash","userRole"],D1=Rn("trackedUserColumnName",Q1),uM=oS("userChanges",{id:Wo().primaryKey().defaultRandom(),userId:Wo().notNull().references(()=>XS.id),changedAt:to({withTimezone:!0}).notNull().defaultNow(),changedIp:rT({length:45}).notNull(),changedColumn:D1().notNull(),oldValue:rT({length:255}),newValue:rT({length:255})}),Pn=oS("games",{id:Wo().primaryKey().defaultRandom()}),L$=oS("players",{userId:Wo().notNull().references(()=>XS.id),gameId:Wo().notNull().references(()=>Pn.id),score:Gn().notNull()},(T)=>[c0({name:"players_userId_gameId_pk",columns:[T.userId,T.gameId]})]),eM=oS("loginHistory",{id:Wo().primaryKey().defaultRandom(),userId:Wo().references(()=>XS.id),loginTime:to({withTimezone:!0}).notNull().defaultNow(),ipAddress:rT({length:45}).notNull(),userAgent:rT({length:1024}),successful:Uf().notNull().default(!1)}),U1=Rn("twoFactorMethod",["email","phone"]),aM=oS("passwordResetAttempts",{id:Wo().primaryKey().defaultRandom(),userId:Wo().notNull().references(()=>XS.id),requestedIp:rT({length:45}).notNull(),requestedAt:to({withTimezone:!0}).notNull().defaultNow(),succeededIp:rT({length:45}),succeededAt:to({withTimezone:!0}),verificationMethod:U1().notNull()}),sM=oS("banishedIps",{ip:rT({length:45}).primaryKey(),reason:rT({length:2048}).notNull(),banishedAt:to({withTimezone:!0}).notNull().defaultNow(),banishedUntil:to({withTimezone:!0})});var __dirname="/home/runner/work/wayforge/wayforge/apps/tempest.games/src/database";class I${options;sql;drizzle;observers=new Map;async setupTriggersAndNotifications(){await this.sql.file(Tk.resolve(__dirname,"notify_update.sql"));let T=[ZT(XS),ZT(Pn),ZT(L$)];await this.sql`SELECT create_notify_triggers(${this.sql.array(T)})`,await this.sql.listen("table_update",(o)=>{let S=o.split(","),f=S[0],n=S[1],A=`${f}("${n}")`;if(this.observers.has(A))this.observers.get(A).next(A)})}constructor(T=!1,o={host:Do.POSTGRES_HOST,port:Do.POSTGRES_PORT,user:Do.POSTGRES_USER,password:Do.POSTGRES_PASSWORD,database:Do.POSTGRES_DATABASE}){this.options=o,this.sql=gS(o),this.drizzle=rn(this.sql,{schema:C$,logger:T})}observe(T,o){if(!this.observers.has(T))this.observers.set(T,new ST);this.observers.get(T).subscribe("SINGLETON",o)}}var pn={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"},j$=i$(pn).map(([T])=>YT.literal(Number(T))),ok=YT.union([j$[0],j$[1],...j$]),t1=YT.tuple([ok,YT.string()]);var N$=new DA,{logger:Fo}=N$;Object.assign(console,Fo,{log:Fo.info});Fo.info("ready");var m$=B1(import.meta.dir,"..","app"),l3=new I$({logQuery(T,o){Fo.info("\uD83D\uDCDD query",T,o)}});nk({hostname:"0.0.0.0",port:Do.FRONTEND_PORT??3333,...JJ??void 0,async fetch(T){try{let o=new Date,S=new URL(T.url);if(Fo.info(T.method,S.pathname),S.pathname==="/")return new Response(Bun.file(B1(m$,"index.html")));if(S.pathname==="/index.html")return Response.redirect("/");let f=Sk(m$,S.pathname),n=fk(f);if(!n.startsWith(m$))throw[403,"Access Denied"];if(!await V1(n).exists())return Response.redirect("/");return new Response(V1(n))}catch(o){let S=t1.safeParse(o);if(S.success){let[f,n]=S.data,$=`${pn[f]}. ${n}`;return Fo.info(`\u274C ${f}: ${$}`),new Response($,{status:f})}if(o instanceof Error)Fo.error(o.message);else{let f=DS(o);Fo.error("frontend server threw",f)}return new Response(pn[500],{status:500})}}});function gn(){Fo.info("\uD83D\uDEEC frontend server exiting"),process.exit(0)}process.on("SIGINT",()=>{Fo.info("\u2757 received SIGINT; exiting gracefully"),gn()});process.on("SIGTERM",()=>{Fo.info("\u2757 received SIGTERM; exiting gracefully"),gn()});process.on("exit",()=>{Fo.info("\u2757 received exit; exiting gracefully"),gn()});N$.on("timeToStop",()=>{Fo.info('\u2757 backend server received signal "timeToStop"; exiting gracefully'),gn()});Fo.info(`\uD83D\uDEEB frontend server running at http://localhost:${Do.FRONTEND_PORT}/`);N$.emit("alive");
|
|
43
|
+
`;await S.execute(_`CREATE SCHEMA IF NOT EXISTS ${_.identifier(A)}`),await S.execute(n);let F=(await S.all(_`select id, hash, created_at from ${_.identifier(A)}.${_.identifier(f)} order by created_at desc limit 1`))[0];await S.transaction(async(J)=>{for await(let R of T)if(!F||Number(F.created_at)<R.folderMillis){for(let O of R.sql)await J.execute(_.raw(O));await J.execute(_`insert into ${_.identifier(A)}.${_.identifier(f)} ("hash", "created_at") values(${R.hash}, ${R.folderMillis})`)}})}escapeName(T){return`"${T}"`}escapeParam(T){return`$${T+1}`}escapeString(T){return`'${T.replace(/'/g,"''")}'`}buildWithCTE(T){if(!T?.length)return;let S=[_`with `];for(let[o,f]of T.entries())if(S.push(_`${_.identifier(f._.alias)} as (${f._.sql})`),o<T.length-1)S.push(_`, `);return S.push(_` `),_.join(S)}buildDeleteQuery({table:T,where:S,returning:o,withList:f}){let A=this.buildWithCTE(f),n=o?_` returning ${this.buildSelection(o,{isSingleTable:!0})}`:void 0,$=S?_` where ${S}`:void 0;return _`${A}delete from ${T}${$}${n}`}buildUpdateSet(T,S){let o=T[j.Symbol.Columns],f=Object.keys(o).filter((n)=>S[n]!==void 0||o[n]?.onUpdateFn!==void 0),A=f.length;return _.join(f.flatMap((n,$)=>{let F=o[n],J=S[n]??_.param(F.onUpdateFn(),F),R=_`${_.identifier(this.casing.getColumnCasing(F))} = ${J}`;if($<A-1)return[R,_.raw(", ")];return[R]}))}buildUpdateQuery({table:T,set:S,where:o,returning:f,withList:A,from:n,joins:$}){let F=this.buildWithCTE(A),J=T[pT.Symbol.Name],R=T[pT.Symbol.Schema],O=T[pT.Symbol.OriginalName],k=J===O?void 0:J,y=_`${R?_`${_.identifier(R)}.`:void 0}${_.identifier(O)}${k&&_` ${_.identifier(k)}`}`,H=this.buildUpdateSet(T,S),E=n&&_.join([_.raw(" from "),this.buildFromTable(n)]),G=this.buildJoins($),I=f?_` returning ${this.buildSelection(f,{isSingleTable:!n})}`:void 0,b=o?_` where ${o}`:void 0;return _`${F}update ${y} set ${H}${E}${G}${b}${I}`}buildSelection(T,{isSingleTable:S=!1}={}){let o=T.length,f=T.flatMap(({field:A},n)=>{let $=[];if(K(A,N.Aliased)&&A.isSelectionField)$.push(_.identifier(A.fieldAlias));else if(K(A,N.Aliased)||K(A,N)){let F=K(A,N.Aliased)?A.sql:A;if(S)$.push(new N(F.queryChunks.map((J)=>{if(K(J,B))return _.identifier(this.casing.getColumnCasing(J));return J})));else $.push(F);if(K(A,N.Aliased))$.push(_` as ${_.identifier(A.fieldAlias)}`)}else if(K(A,_T))if(S)$.push(_.identifier(this.casing.getColumnCasing(A)));else $.push(A);if(n<o-1)$.push(_`, `);return $});return _.join(f)}buildJoins(T){if(!T||T.length===0)return;let S=[];for(let[o,f]of T.entries()){if(o===0)S.push(_` `);let A=f.table,n=f.lateral?_` lateral`:void 0;if(K(A,pT)){let $=A[pT.Symbol.Name],F=A[pT.Symbol.Schema],J=A[pT.Symbol.OriginalName],R=$===J?void 0:f.alias;S.push(_`${_.raw(f.joinType)} join${n} ${F?_`${_.identifier(F)}.`:void 0}${_.identifier(J)}${R&&_` ${_.identifier(R)}`} on ${f.on}`)}else if(K(A,nS)){let $=A[KT].name,F=A[KT].schema,J=A[KT].originalName,R=$===J?void 0:f.alias;S.push(_`${_.raw(f.joinType)} join${n} ${F?_`${_.identifier(F)}.`:void 0}${_.identifier(J)}${R&&_` ${_.identifier(R)}`} on ${f.on}`)}else S.push(_`${_.raw(f.joinType)} join${n} ${A} on ${f.on}`);if(o<T.length-1)S.push(_` `)}return _.join(S)}buildFromTable(T){if(K(T,j)&&T[j.Symbol.OriginalName]!==T[j.Symbol.Name]){let S=_`${_.identifier(T[j.Symbol.OriginalName])}`;if(T[j.Symbol.Schema])S=_`${_.identifier(T[j.Symbol.Schema])}.${S}`;return _`${S} ${_.identifier(T[j.Symbol.Name])}`}return T}buildSelectQuery({withList:T,fields:S,fieldsFlat:o,where:f,having:A,table:n,joins:$,orderBy:F,groupBy:J,limit:R,offset:O,lockingClause:k,distinct:y,setOperators:H}){let E=o??yS(S);for(let TT of E)if(K(TT.field,_T)&&qT(TT.field.table)!==(K(n,xT)?n._.alias:K(n,Nf)?n[KT].name:K(n,N)?void 0:qT(n))&&!((WT)=>$?.some(({alias:CT})=>CT===(WT[j.Symbol.IsAlias]?qT(WT):WT[j.Symbol.BaseName])))(TT.field.table)){let WT=qT(TT.field.table);throw new Error(`Your "${TT.path.join("->")}" field references a column "${WT}"."${TT.field.name}", but the table "${WT}" is not part of the query! Did you forget to join it?`)}let G=!$||$.length===0,I=this.buildWithCTE(T),b;if(y)b=y===!0?_` distinct`:_` distinct on (${_.join(y.on,_`, `)})`;let q=this.buildSelection(E,{isSingleTable:G}),P=this.buildFromTable(n),X=this.buildJoins($),D=f?_` where ${f}`:void 0,V=A?_` having ${A}`:void 0,U;if(F&&F.length>0)U=_` order by ${_.join(F,_`, `)}`;let v;if(J&&J.length>0)v=_` group by ${_.join(J,_`, `)}`;let l=typeof R==="object"||typeof R==="number"&&R>=0?_` limit ${R}`:void 0,Y=O?_` offset ${O}`:void 0,a=_.empty();if(k){let TT=_` for ${_.raw(k.strength)}`;if(k.config.of)TT.append(_` of ${_.join(Array.isArray(k.config.of)?k.config.of:[k.config.of],_`, `)}`);if(k.config.noWait)TT.append(_` no wait`);else if(k.config.skipLocked)TT.append(_` skip locked`);a.append(TT)}let Z=_`${I}select${b} ${q} from ${P}${X}${D}${v}${V}${U}${l}${Y}${a}`;if(H.length>0)return this.buildSetOperations(Z,H);return Z}buildSetOperations(T,S){let[o,...f]=S;if(!o)throw new Error("Cannot pass undefined values to any set operator");if(f.length===0)return this.buildSetOperationQuery({leftSelect:T,setOperator:o});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:T,setOperator:o}),f)}buildSetOperationQuery({leftSelect:T,setOperator:{type:S,isAll:o,rightSelect:f,limit:A,orderBy:n,offset:$}}){let F=_`(${T.getSQL()}) `,J=_`(${f.getSQL()})`,R;if(n&&n.length>0){let H=[];for(let E of n)if(K(E,B))H.push(_.identifier(E.name));else if(K(E,N)){for(let G=0;G<E.queryChunks.length;G++){let I=E.queryChunks[G];if(K(I,B))E.queryChunks[G]=_.identifier(I.name)}H.push(_`${E}`)}else H.push(_`${E}`);R=_` order by ${_.join(H,_`, `)} `}let O=typeof A==="object"||typeof A==="number"&&A>=0?_` limit ${A}`:void 0,k=_.raw(`${S} ${o?"all ":""}`),y=$?_` offset ${$}`:void 0;return _`${F}${k}${J}${R}${O}${y}`}buildInsertQuery({table:T,values:S,onConflict:o,returning:f,withList:A,select:n,overridingSystemValue_:$}){let F=[],J=T[j.Symbol.Columns],R=Object.entries(J).filter(([I,b])=>!b.shouldDisableInsert()),O=R.map(([,I])=>_.identifier(this.casing.getColumnCasing(I)));if(n){let I=S;if(K(I,N))F.push(I);else F.push(I.getSQL())}else{let I=S;F.push(_.raw("values "));for(let[b,q]of I.entries()){let P=[];for(let[X,D]of R){let V=q[X];if(V===void 0||K(V,RS)&&V.value===void 0)if(D.defaultFn!==void 0){let U=D.defaultFn(),v=K(U,N)?U:_.param(U,D);P.push(v)}else if(!D.default&&D.onUpdateFn!==void 0){let U=D.onUpdateFn(),v=K(U,N)?U:_.param(U,D);P.push(v)}else P.push(_`default`);else P.push(V)}if(F.push(P),b<I.length-1)F.push(_`, `)}}let k=this.buildWithCTE(A),y=_.join(F),H=f?_` returning ${this.buildSelection(f,{isSingleTable:!0})}`:void 0,E=o?_` on conflict ${o}`:void 0,G=$===!0?_`overriding system value `:void 0;return _`${k}insert into ${T} ${O} ${G}${y}${E}${H}`}buildRefreshMaterializedViewQuery({view:T,concurrently:S,withNoData:o}){let f=S?_` concurrently`:void 0,A=o?_` with no data`:void 0;return _`refresh materialized view${f} ${T}${A}`}prepareTyping(T){if(K(T,YA)||K(T,GA))return"json";else if(K(T,EA))return"decimal";else if(K(T,zA))return"time";else if(K(T,QA)||K(T,DA))return"timestamp";else if(K(T,KA)||K(T,HA))return"date";else if(K(T,UA))return"uuid";else return"none"}sqlToQuery(T,S){return T.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,prepareTyping:this.prepareTyping,invokeSource:S})}buildRelationalQueryWithoutPK({fullSchema:T,schema:S,tableNamesMap:o,table:f,tableConfig:A,queryConfig:n,tableAlias:$,nestedQueryRelation:F,joinOn:J}){let R=[],O,k,y=[],H,E=[];if(n===!0)R=Object.entries(A.columns).map(([b,q])=>({dbKey:q.name,tsKey:b,field:jS(q,$),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let I=Object.fromEntries(Object.entries(A.columns).map(([V,U])=>[V,jS(U,$)]));if(n.where){let V=typeof n.where==="function"?n.where(I,g0()):n.where;H=V&&zf(V,$)}let b=[],q=[];if(n.columns){let V=!1;for(let[U,v]of Object.entries(n.columns)){if(v===void 0)continue;if(U in A.columns){if(!V&&v===!0)V=!0;q.push(U)}}if(q.length>0)q=V?q.filter((U)=>n.columns?.[U]===!0):Object.keys(A.columns).filter((U)=>!q.includes(U))}else q=Object.keys(A.columns);for(let V of q){let U=A.columns[V];b.push({tsKey:V,value:U})}let P=[];if(n.with)P=Object.entries(n.with).filter((V)=>!!V[1]).map(([V,U])=>({tsKey:V,queryConfig:U,relation:A.relations[V]}));let X;if(n.extras){X=typeof n.extras==="function"?n.extras(I,{sql:_}):n.extras;for(let[V,U]of Object.entries(X))b.push({tsKey:V,value:Pn(U,$)})}for(let{tsKey:V,value:U}of b)R.push({dbKey:K(U,N.Aliased)?U.fieldAlias:A.columns[V].name,tsKey:V,field:K(U,_T)?jS(U,$):U,relationTableTsKey:void 0,isJson:!1,selection:[]});let D=typeof n.orderBy==="function"?n.orderBy(I,i0()):n.orderBy??[];if(!Array.isArray(D))D=[D];y=D.map((V)=>{if(K(V,_T))return jS(V,$);return zf(V,$)}),O=n.limit,k=n.offset;for(let{tsKey:V,queryConfig:U,relation:v}of P){let l=l0(S,o,v),Y=Wo(v.referencedTable),a=o[Y],Z=`${$}_${V}`,TT=Qf(...l.fields.map((oS,mS)=>yA(jS(l.references[mS],Z),jS(oS,$)))),WT=this.buildRelationalQueryWithoutPK({fullSchema:T,schema:S,tableNamesMap:o,table:T[a],tableConfig:S[a],queryConfig:K(v,To)?U===!0?{limit:1}:{...U,limit:1}:U,tableAlias:Z,joinOn:TT,nestedQueryRelation:v}),CT=_`${_.identifier(Z)}.${_.identifier("data")}`.as(V);E.push({on:_`true`,table:new xT(WT.sql,{},Z),alias:Z,joinType:"left",lateral:!0}),R.push({dbKey:V,tsKey:V,field:CT,relationTableTsKey:a,isJson:!0,selection:WT.selection})}}if(R.length===0)throw new kA({message:`No fields selected for table "${A.tsName}" ("${$}")`});let G;if(H=Qf(J,H),F){let I=_`json_build_array(${_.join(R.map(({field:P,tsKey:X,isJson:D})=>D?_`${_.identifier(`${$}_${X}`)}.${_.identifier("data")}`:K(P,N.Aliased)?P.sql:P),_`, `)})`;if(K(F,Bf))I=_`coalesce(json_agg(${I}${y.length>0?_` order by ${_.join(y,_`, `)}`:void 0}), '[]'::json)`;let b=[{dbKey:"data",tsKey:"data",field:I.as("data"),isJson:!0,relationTableTsKey:A.tsName,selection:R}];if(O!==void 0||k!==void 0||y.length>0)G=this.buildSelectQuery({table:_A(f,$),fields:{},fieldsFlat:[{path:[],field:_.raw("*")}],where:H,limit:O,offset:k,orderBy:y,setOperators:[]}),H=void 0,O=void 0,k=void 0,y=[];else G=_A(f,$);G=this.buildSelectQuery({table:K(G,pT)?G:new xT(G,{},$),fields:{},fieldsFlat:b.map(({field:P})=>({path:[],field:K(P,_T)?jS(P,$):P})),joins:E,where:H,limit:O,offset:k,orderBy:y,setOperators:[]})}else G=this.buildSelectQuery({table:_A(f,$),fields:{},fieldsFlat:R.map(({field:I})=>({path:[],field:K(I,_T)?jS(I,$):I})),joins:E,where:H,limit:O,offset:k,orderBy:y,setOperators:[]});return{tableTsKey:A.tsName,sql:G,selection:R}}}class H${static[W]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class SS{static[W]="PgSelectBuilder";fields;session;dialect;withList=[];distinct;constructor(T){if(this.fields=T.fields,this.session=T.session,this.dialect=T.dialect,T.withList)this.withList=T.withList;this.distinct=T.distinct}authToken;setToken(T){return this.authToken=T,this}from(T){let S=!!this.fields,o=T,f;if(this.fields)f=this.fields;else if(K(o,xT))f=Object.fromEntries(Object.keys(o._.selectedFields).map((A)=>[A,o[A]]));else if(K(o,Nf))f=o[KT].selectedFields;else if(K(o,N))f={};else f=uJ(o);return new X$({table:o,fields:f,isPartialSelect:S,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}}class K1 extends H${static[W]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;constructor({table:T,fields:S,isPartialSelect:o,session:f,dialect:A,withList:n,distinct:$}){super();this.config={withList:n,table:T,fields:{...S},distinct:$,setOperators:[]},this.isPartialSelect=o,this.session=f,this.dialect=A,this._={selectedFields:S},this.tableName=ZS(T),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}createJoin(T){return(S,o)=>{let f=this.tableName,A=ZS(S);if(typeof A==="string"&&this.config.joins?.some((n)=>n.alias===A))throw new Error(`Alias "${A}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof f==="string")this.config.fields={[f]:this.config.fields};if(typeof A==="string"&&!K(S,N)){let n=K(S,xT)?S._.selectedFields:K(S,nS)?S[KT].selectedFields:S[j.Symbol.Columns];this.config.fields[A]=n}}if(typeof o==="function")o=o(new Proxy(this.config.fields,new UT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:o,table:S,joinType:T,alias:A}),typeof A==="string")switch(T){case"left":{this.joinsNotNullableMap[A]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([n])=>[n,!1])),this.joinsNotNullableMap[A]=!0;break}case"inner":{this.joinsNotNullableMap[A]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([n])=>[n,!1])),this.joinsNotNullableMap[A]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");createSetOperator(T,S){return(o)=>{let f=typeof o==="function"?o(cW()):o;if(!Df(this.getSelectedFields(),f.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return this.config.setOperators.push({type:T,isAll:S,rightSelect:f}),this}}union=this.createSetOperator("union",!1);unionAll=this.createSetOperator("union",!0);intersect=this.createSetOperator("intersect",!1);intersectAll=this.createSetOperator("intersect",!0);except=this.createSetOperator("except",!1);exceptAll=this.createSetOperator("except",!0);addSetOperators(T){return this.config.setOperators.push(...T),this}where(T){if(typeof T==="function")T=T(new Proxy(this.config.fields,new UT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=T,this}having(T){if(typeof T==="function")T=T(new Proxy(this.config.fields,new UT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=T,this}groupBy(...T){if(typeof T[0]==="function"){let S=T[0](new Proxy(this.config.fields,new UT({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(S)?S:[S]}else this.config.groupBy=T;return this}orderBy(...T){if(typeof T[0]==="function"){let S=T[0](new Proxy(this.config.fields,new UT({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),o=Array.isArray(S)?S:[S];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=o;else this.config.orderBy=o}else{let S=T;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=S;else this.config.orderBy=S}return this}limit(T){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=T;else this.config.limit=T;return this}offset(T){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=T;else this.config.offset=T;return this}for(T,S={}){return this.config.lockingClause={strength:T,config:S},this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:T,...S}=this.dialect.sqlToQuery(this.getSQL());return S}as(T){return new Proxy(new xT(this.getSQL(),this.config.fields,T),new UT({alias:T,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new UT({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}}class X$ extends K1{static[W]="PgSelect";_prepare(T){let{session:S,config:o,dialect:f,joinsNotNullableMap:A,authToken:n}=this;if(!S)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");return kT.startActiveSpan("drizzle.prepareQuery",()=>{let $=yS(o.fields),F=S.prepareQuery(f.sqlToQuery(this.getSQL()),$,T,!0);return F.joinsNotNullableMap=A,F.setToken(n)})}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return kT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T,this.authToken)})}}lJ(X$,[TS]);function lo(T,S){return(o,f,...A)=>{let n=[f,...A].map(($)=>({type:T,isAll:S,rightSelect:$}));for(let $ of n)if(!Df(o.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 o.addSetOperators(n)}}var cW=()=>({union:rW,unionAll:pW,intersect:PW,intersectAll:gW,except:iW,exceptAll:dW}),rW=lo("union",!1),pW=lo("union",!0),PW=lo("intersect",!1),gW=lo("intersect",!0),iW=lo("except",!1),dW=lo("except",!0);class mf{static[W]="PgQueryBuilder";dialect;dialectConfig;constructor(T){this.dialect=K(T,Ko)?T:void 0,this.dialectConfig=K(T,Ko)?void 0:T}$with=(T,S)=>{let o=this;return{as:(A)=>{if(typeof A==="function")A=A(o);return new Proxy(new Gf(A.getSQL(),S??("getSelectedFields"in A?A.getSelectedFields()??{}:{}),T,!0),new UT({alias:T,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...T){let S=this;function o(n){return new SS({fields:n??void 0,session:void 0,dialect:S.getDialect(),withList:T})}function f(n){return new SS({fields:n??void 0,session:void 0,dialect:S.getDialect(),distinct:!0})}function A(n,$){return new SS({fields:$??void 0,session:void 0,dialect:S.getDialect(),distinct:{on:n}})}return{select:o,selectDistinct:f,selectDistinctOn:A}}select(T){return new SS({fields:T??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(T){return new SS({fields:T??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(T,S){return new SS({fields:S??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:T}})}getDialect(){if(!this.dialect)this.dialect=new Ko(this.dialectConfig);return this.dialect}}class qA{constructor(T,S,o,f,A){this.table=T,this.session=S,this.dialect=o,this.withList=f,this.overridingSystemValue_=A}static[W]="PgInsertBuilder";authToken;setToken(T){return this.authToken=T,this}overridingSystemValue(){return this.overridingSystemValue_=!0,this}values(T){if(T=Array.isArray(T)?T:[T],T.length===0)throw new Error("values() must be called with at least one value");let S=T.map((o)=>{let f={},A=this.table[j.Symbol.Columns];for(let n of Object.keys(o)){let $=o[n];f[n]=K($,N)?$:new RS($,A[n])}return f});return new G$(this.table,S,this.session,this.dialect,this.withList,!1,this.overridingSystemValue_).setToken(this.authToken)}select(T){let S=typeof T==="function"?T(new mf):T;if(!K(S,N)&&!Df(this.table[MA],S._.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 G$(this.table,S,this.session,this.dialect,this.withList,!0)}}class G$ extends TS{constructor(T,S,o,f,A,n,$){super();this.session=o,this.dialect=f,this.config={table:T,values:S,withList:A,select:n,overridingSystemValue_:$}}static[W]="PgInsert";config;returning(T=this.config.table[j.Symbol.Columns]){return this.config.returningFields=T,this.config.returning=yS(T),this}onConflictDoNothing(T={}){if(T.target===void 0)this.config.onConflict=_`do nothing`;else{let S="";S=Array.isArray(T.target)?T.target.map((f)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(f))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(T.target));let o=T.where?_` where ${T.where}`:void 0;this.config.onConflict=_`(${_.raw(S)})${o} do nothing`}return this}onConflictDoUpdate(T){if(T.where&&(T.targetWhere||T.setWhere))throw new Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');let S=T.where?_` where ${T.where}`:void 0,o=T.targetWhere?_` where ${T.targetWhere}`:void 0,f=T.setWhere?_` where ${T.setWhere}`:void 0,A=this.dialect.buildUpdateSet(this.config.table,wA(this.config.table,T.set)),n="";return n=Array.isArray(T.target)?T.target.map(($)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing($))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(T.target)),this.config.onConflict=_`(${_.raw(n)})${o} do update set ${A}${S}${f}`,this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:T,...S}=this.dialect.sqlToQuery(this.getSQL());return S}_prepare(T){return kT.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,T,!0)})}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return kT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new UT({alias:qT(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class Y$ extends TS{constructor(T,S,o){super();this.session=S,this.dialect=o,this.config={view:T}}static[W]="PgRefreshMaterializedView";config;concurrently(){if(this.config.withNoData!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.concurrently=!0,this}withNoData(){if(this.config.concurrently!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.withNoData=!0,this}getSQL(){return this.dialect.buildRefreshMaterializedViewQuery(this.config)}toSQL(){let{typings:T,...S}=this.dialect.sqlToQuery(this.getSQL());return S}_prepare(T){return kT.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),void 0,T,!0)})}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return kT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T,this.authToken)})}}class ZA{constructor(T,S,o,f){this.table=T,this.session=S,this.dialect=o,this.withList=f}static[W]="PgUpdateBuilder";authToken;setToken(T){return this.authToken=T,this}set(T){return new H1(this.table,wA(this.table,T),this.session,this.dialect,this.withList).setToken(this.authToken)}}class H1 extends TS{constructor(T,S,o,f,A){super();this.session=o,this.dialect=f,this.config={set:S,table:T,withList:A,joins:[]},this.tableName=ZS(T),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}static[W]="PgUpdate";config;tableName;joinsNotNullableMap;from(T){let S=T,o=ZS(S);if(typeof o==="string")this.joinsNotNullableMap[o]=!0;return this.config.from=S,this}getTableLikeFields(T){if(K(T,pT))return T[j.Symbol.Columns];else if(K(T,xT))return T._.selectedFields;return T[KT].selectedFields}createJoin(T){return(S,o)=>{let f=ZS(S);if(typeof f==="string"&&this.config.joins.some((A)=>A.alias===f))throw new Error(`Alias "${f}" is already used in this query`);if(typeof o==="function"){let A=this.config.from&&!K(this.config.from,N)?this.getTableLikeFields(this.config.from):void 0;o=o(new Proxy(this.config.table[j.Symbol.Columns],new UT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),A&&new Proxy(A,new UT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}if(this.config.joins.push({on:o,table:S,joinType:T,alias:f}),typeof f==="string")switch(T){case"left":{this.joinsNotNullableMap[f]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([A])=>[A,!1])),this.joinsNotNullableMap[f]=!0;break}case"inner":{this.joinsNotNullableMap[f]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([A])=>[A,!1])),this.joinsNotNullableMap[f]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(T){return this.config.where=T,this}returning(T){if(!T){if(T=Object.assign({},this.config.table[j.Symbol.Columns]),this.config.from){let S=ZS(this.config.from);if(typeof S==="string"&&this.config.from&&!K(this.config.from,N)){let o=this.getTableLikeFields(this.config.from);T[S]=o}for(let o of this.config.joins){let f=ZS(o.table);if(typeof f==="string"&&!K(o.table,N)){let A=this.getTableLikeFields(o.table);T[f]=A}}}}return this.config.returningFields=T,this.config.returning=yS(T),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:T,...S}=this.dialect.sqlToQuery(this.getSQL());return S}_prepare(T){let S=this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,T,!0);return S.joinsNotNullableMap=this.joinsNotNullableMap,S}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return this._prepare().execute(T,this.authToken)};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new UT({alias:qT(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class hf extends N{constructor(T){super(hf.buildEmbeddedCount(T.source,T.filters).queryChunks);this.params=T,this.mapWith(Number),this.session=T.session,this.sql=hf.buildCount(T.source,T.filters)}sql;token;static[W]="PgCountBuilder";[Symbol.toStringTag]="PgCountBuilder";session;static buildEmbeddedCount(T,S){return _`(select count(*) from ${T}${_.raw(" where ").if(S)}${S})`}static buildCount(T,S){return _`select count(*) as count from ${T}${_.raw(" where ").if(S)}${S};`}setToken(T){return this.token=T,this}then(T,S){return Promise.resolve(this.session.count(this.sql,this.token)).then(T,S)}catch(T){return this.then(void 0,T)}finally(T){return this.then((S)=>{return T?.(),S},(S)=>{throw T?.(),S})}}class z${constructor(T,S,o,f,A,n,$){this.fullSchema=T,this.schema=S,this.tableNamesMap=o,this.table=f,this.tableConfig=A,this.dialect=n,this.session=$}static[W]="PgRelationalQueryBuilder";findMany(T){return new E$(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,T?T:{},"many")}findFirst(T){return new E$(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,T?{...T,limit:1}:{limit:1},"first")}}class E$ extends TS{constructor(T,S,o,f,A,n,$,F,J){super();this.fullSchema=T,this.schema=S,this.tableNamesMap=o,this.table=f,this.tableConfig=A,this.dialect=n,this.session=$,this.config=F,this.mode=J}static[W]="PgRelationalQuery";_prepare(T){return kT.startActiveSpan("drizzle.prepareQuery",()=>{let{query:S,builtQuery:o}=this._toSQL();return this.session.prepareQuery(o,void 0,T,!0,(f,A)=>{let n=f.map(($)=>VA(this.schema,this.tableConfig,$,S.selection,A));if(this.mode==="first")return n[0];return n})})}prepare(T){return this._prepare(T)}_getQuery(){return this.dialect.buildRelationalQueryWithoutPK({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName})}getSQL(){return this._getQuery().sql}_toSQL(){let T=this._getQuery(),S=this.dialect.sqlToQuery(T.sql);return{query:T,builtQuery:S}}toSQL(){return this._toSQL().builtQuery}authToken;setToken(T){return this.authToken=T,this}execute(){return kT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(void 0,this.authToken)})}}class Q$ extends TS{constructor(T,S,o,f){super();this.execute=T,this.sql=S,this.query=o,this.mapBatchResult=f}static[W]="PgRaw";getSQL(){return this.sql}getQuery(){return this.query}mapResult(T,S){return S?this.mapBatchResult(T):T}_prepare(){return this}isResponseInArrayMode(){return!1}}class bf{constructor(T,S,o){if(this.dialect=T,this.session=S,this._=o?{schema:o.schema,fullSchema:o.fullSchema,tableNamesMap:o.tableNamesMap,session:S}:{schema:void 0,fullSchema:{},tableNamesMap:{},session:S},this.query={},this._.schema)for(let[f,A]of Object.entries(this._.schema))this.query[f]=new z$(o.fullSchema,this._.schema,this._.tableNamesMap,o.fullSchema[f],A,T,S)}static[W]="PgDatabase";query;$with=(T,S)=>{let o=this;return{as:(A)=>{if(typeof A==="function")A=A(new mf(o.dialect));return new Proxy(new Gf(A.getSQL(),S??("getSelectedFields"in A?A.getSelectedFields()??{}:{}),T,!0),new UT({alias:T,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(T,S){return new hf({source:T,filters:S,session:this.session})}with(...T){let S=this;function o(J){return new SS({fields:J??void 0,session:S.session,dialect:S.dialect,withList:T})}function f(J){return new SS({fields:J??void 0,session:S.session,dialect:S.dialect,withList:T,distinct:!0})}function A(J,R){return new SS({fields:R??void 0,session:S.session,dialect:S.dialect,withList:T,distinct:{on:J}})}function n(J){return new ZA(J,S.session,S.dialect,T)}function $(J){return new qA(J,S.session,S.dialect,T)}function F(J){return new vA(J,S.session,S.dialect,T)}return{select:o,selectDistinct:f,selectDistinctOn:A,update:n,insert:$,delete:F}}select(T){return new SS({fields:T??void 0,session:this.session,dialect:this.dialect})}selectDistinct(T){return new SS({fields:T??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(T,S){return new SS({fields:S??void 0,session:this.session,dialect:this.dialect,distinct:{on:T}})}update(T){return new ZA(T,this.session,this.dialect)}insert(T){return new qA(T,this.session,this.dialect)}delete(T){return new vA(T,this.session,this.dialect)}refreshMaterializedView(T){return new Y$(T,this.session,this.dialect)}authToken;execute(T){let S=typeof T==="string"?_.raw(T):T.getSQL(),o=this.dialect.sqlToQuery(S),f=this.session.prepareQuery(o,void 0,void 0,!1);return new Q$(()=>f.execute(void 0,this.authToken),S,o,(A)=>f.mapResult(A,!0))}transaction(T,S){return this.session.transaction(T,S)}}class X1{constructor(T,S){this.unique=T,this.name=S}static[W]="PgIndexBuilderOn";on(...T){return new cA(T.map((S)=>{if(K(S,N))return S;S=S;let o=new Xf(S.name,!!S.keyAsName,S.columnType,S.indexConfig);return S.indexConfig=JSON.parse(JSON.stringify(S.defaultConfig)),o}),this.unique,!1,this.name)}onOnly(...T){return new cA(T.map((S)=>{if(K(S,N))return S;S=S;let o=new Xf(S.name,!!S.keyAsName,S.columnType,S.indexConfig);return S.indexConfig=S.defaultConfig,o}),this.unique,!0,this.name)}using(T,...S){return new cA(S.map((o)=>{if(K(o,N))return o;o=o;let f=new Xf(o.name,!!o.keyAsName,o.columnType,o.indexConfig);return o.indexConfig=JSON.parse(JSON.stringify(o.defaultConfig)),f}),this.unique,!0,this.name,T)}}class cA{static[W]="PgIndexBuilder";config;constructor(T,S,o,f,A="btree"){this.config={name:f,columns:T,unique:S,only:o,method:A}}concurrently(){return this.config.concurrently=!0,this}with(T){return this.config.with=T,this}where(T){return this.config.where=T,this}build(T){return new G1(this.config,T)}}class G1{static[W]="PgIndex";config;constructor(T,S){this.config={...T,table:S}}}function D$(T){return new X1(!0,T)}class U${constructor(T){this.query=T}authToken;getQuery(){return this.query}mapResult(T,S){return T}setToken(T){return this.authToken=T,this}static[W]="PgPreparedQuery";joinsNotNullableMap}class V${constructor(T){this.dialect=T}static[W]="PgSession";execute(T,S){return kT.startActiveSpan("drizzle.operation",()=>{return kT.startActiveSpan("drizzle.prepareQuery",()=>{return this.prepareQuery(this.dialect.sqlToQuery(T),void 0,void 0,!1)}).setToken(S).execute(void 0,S)})}all(T){return this.prepareQuery(this.dialect.sqlToQuery(T),void 0,void 0,!1).all()}async count(T,S){let o=await this.execute(T,S);return Number(o[0].count)}}class B$ extends bf{constructor(T,S,o,f=0){super(T,S,o);this.schema=o,this.nestedIndex=f}static[W]="PgTransaction";rollback(){throw new gn}getTransactionConfigSQL(T){let S=[];if(T.isolationLevel)S.push(`isolation level ${T.isolationLevel}`);if(T.accessMode)S.push(T.accessMode);if(typeof T.deferrable==="boolean")S.push(T.deferrable?"deferrable":"not deferrable");return _.raw(S.join(" "))}setTransaction(T){return this.session.execute(_`set transaction ${this.getTransactionConfigSQL(T)}`)}}class Y1 extends U${constructor(T,S,o,f,A,n,$){super({sql:S,params:o});this.client=T,this.queryString=S,this.params=o,this.logger=f,this.fields=A,this._isResponseInArrayMode=n,this.customResultMapper=$}static[W]="PostgresJsPreparedQuery";async execute(T={}){return kT.startActiveSpan("drizzle.execute",async(S)=>{let o=pn(this.params,T);S?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(o)}),this.logger.logQuery(this.queryString,o);let{fields:f,queryString:A,client:n,joinsNotNullableMap:$,customResultMapper:F}=this;if(!f&&!F)return kT.startActiveSpan("drizzle.driver.execute",()=>{return n.unsafe(A,o)});let J=await kT.startActiveSpan("drizzle.driver.execute",()=>{return S?.setAttributes({"drizzle.query.text":A,"drizzle.query.params":JSON.stringify(o)}),n.unsafe(A,o).values()});return kT.startActiveSpan("drizzle.mapResponse",()=>{return F?F(J):J.map((R)=>dJ(f,R,$))})})}all(T={}){return kT.startActiveSpan("drizzle.execute",async(S)=>{let o=pn(this.params,T);return S?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(o)}),this.logger.logQuery(this.queryString,o),kT.startActiveSpan("drizzle.driver.execute",()=>{return S?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(o)}),this.client.unsafe(this.queryString,o)})})}isResponseInArrayMode(){return this._isResponseInArrayMode}}class xf extends V${constructor(T,S,o,f={}){super(S);this.client=T,this.schema=o,this.options=f,this.logger=f.logger??new ln}static[W]="PostgresJsSession";logger;prepareQuery(T,S,o,f,A){return new Y1(this.client,T.sql,T.params,this.logger,S,f,A)}query(T,S){return this.logger.logQuery(T,S),this.client.unsafe(T,S).values()}queryObjects(T,S){return this.client.unsafe(T,S)}transaction(T,S){return this.client.begin(async(o)=>{let f=new xf(o,this.dialect,this.schema,this.options),A=new t$(this.dialect,f,this.schema);if(S)await A.setTransaction(S);return T(A)})}}class t$ extends B${constructor(T,S,o,f=0){super(T,S,o,f);this.session=S}static[W]="PostgresJsTransaction";transaction(T){return this.session.client.savepoint((S)=>{let o=new xf(S,this.dialect,this.schema,this.session.options),f=new t$(this.dialect,o,this.schema);return T(f)})}}class E1 extends bf{static[W]="PostgresJsDatabase"}function uo(T,S={}){let o=(J)=>J;for(let J of["1184","1082","1083","1114"])T.options.parsers[J]=o,T.options.serializers[J]=o;T.options.serializers["114"]=o,T.options.serializers["3802"]=o;let f=new Ko({casing:S.casing}),A;if(S.logger===!0)A=new dn;else if(S.logger!==!1)A=S.logger;let n;if(S.schema){let J=d0(S.schema,u0);n={fullSchema:S.schema,schema:J.tables,tableNamesMap:J.tableNamesMap}}let $=new xf(T,f,n,{logger:A}),F=new E1(f,$,n);return F.$client=T,F}function rA(...T){if(typeof T[0]==="string"){let S=io(T[0]);return uo(S,T[1])}if(eJ(T[0])){let{connection:S,client:o,...f}=T[0];if(o)return uo(o,f);if(typeof S==="object"&&S.url!==void 0){let{url:n,...$}=S,F=io(n,$);return uo(F,f)}let A=io(S);return uo(A,f)}return uo(T[0],T[1])}((T)=>{function S(o){return uo({options:{parsers:{},serializers:{}}},o)}T.mock=S})(rA||(rA={}));var C$={};VO(C$,{users:()=>Ho,userChanges:()=>uW,untrackedUserColumnNames:()=>lW,twoFactorMethod:()=>V1,trackedUserColumnName:()=>U1,trackableUserColumnNames:()=>D1,role:()=>Q1,players:()=>L$,passwordResetAttempts:()=>sW,loginHistory:()=>eW,games:()=>pA,banishedIps:()=>aW});function z1(T){return _`lower(${T})`}var Q1=RA("role",["admin","user"]),Ho=aS("users",{id:OS().primaryKey().defaultRandom(),username:rT({length:16}).notNull(),email:rT({length:254}).notNull(),hash:rT({length:64}).notNull(),salt:rT({length:36}).notNull(),createdAt:US({withTimezone:!0}).notNull().defaultNow(),createdIp:rT({length:45}).notNull(),isActive:Uf().notNull().default(!1),verifiedAt:US({withTimezone:!0}),userRole:Q1().default("user")},(T)=>[D$("usernameUniqueIndex").on(z1(T.username)),D$("emailUniqueIndex").on(z1(T.email))]),lW=["id","createdAt","createdIp","isActive","salt","verifiedAt"],D1=["username","email","hash","userRole"],U1=RA("trackedUserColumnName",D1),uW=aS("userChanges",{id:OS().primaryKey().defaultRandom(),userId:OS().notNull().references(()=>Ho.id),changedAt:US({withTimezone:!0}).notNull().defaultNow(),changedIp:rT({length:45}).notNull(),changedColumn:U1().notNull(),oldValue:rT({length:255}),newValue:rT({length:255})}),pA=aS("games",{id:OS().primaryKey().defaultRandom()}),L$=aS("players",{userId:OS().notNull().references(()=>Ho.id),gameId:OS().notNull().references(()=>pA.id),score:XA().notNull()},(T)=>[r0({name:"players_userId_gameId_pk",columns:[T.userId,T.gameId]})]),eW=aS("loginHistory",{id:OS().primaryKey().defaultRandom(),userId:OS().references(()=>Ho.id),loginTime:US({withTimezone:!0}).notNull().defaultNow(),ipAddress:rT({length:45}).notNull(),userAgent:rT({length:1024}),successful:Uf().notNull().default(!1)}),V1=RA("twoFactorMethod",["email","phone"]),sW=aS("passwordResetAttempts",{id:OS().primaryKey().defaultRandom(),userId:OS().notNull().references(()=>Ho.id),requestedIp:rT({length:45}).notNull(),requestedAt:US({withTimezone:!0}).notNull().defaultNow(),succeededIp:rT({length:45}),succeededAt:US({withTimezone:!0}),verificationMethod:V1().notNull()}),aW=aS("banishedIps",{ip:rT({length:45}).primaryKey(),reason:rT({length:2048}).notNull(),banishedAt:US({withTimezone:!0}).notNull().defaultNow(),banishedUntil:US({withTimezone:!0})});var __dirname="/home/runner/work/wayforge/wayforge/apps/tempest.games/src/database";class I${options;sql;drizzle;observers=new Map;async setupTriggersAndNotifications(){await this.sql.file(T_.resolve(__dirname,"notify_update.sql"));let T=[qT(Ho),qT(pA),qT(L$)];await this.sql`SELECT create_notify_triggers(${this.sql.array(T)})`,await this.sql.listen("table_update",(S)=>{let o=S.split(","),f=o[0],A=o[1],n=`${f}("${A}")`;if(this.observers.has(n))this.observers.get(n).next(n)})}constructor(T=!1,S={host:QS.POSTGRES_HOST,port:QS.POSTGRES_PORT,user:QS.POSTGRES_USER,password:QS.POSTGRES_PASSWORD,database:QS.POSTGRES_DATABASE}){this.options=S,this.sql=io(S),this.drizzle=rA(this.sql,{schema:C$,logger:T})}observe(T,S){if(!this.observers.has(T))this.observers.set(T,new ST);this.observers.get(T).subscribe("SINGLETON",S)}}var PA={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"},j$=g$(PA).map(([T])=>GT.literal(Number(T))),S_=GT.union([j$[0],j$[1],...j$]),B1=GT.tuple([S_,GT.string()]);var m$=new Qn,{logger:FS}=m$;Object.assign(console,FS,{log:FS.info});FS.info("ready");var N$=L1(import.meta.dir,"..","app"),l3=new I$({logQuery(T,S){FS.info("\uD83D\uDCDD query",T,S)}});A_({hostname:"0.0.0.0",port:QS.FRONTEND_PORT??3333,...RJ??void 0,async fetch(T){try{let S=new Date,o=new URL(T.url);if(FS.info(T.method,o.pathname),o.pathname==="/")return new Response(Bun.file(L1(N$,"index.html")));if(o.pathname==="/index.html")return Response.redirect("/");let f=o_(N$,o.pathname),A=f_(f);if(!A.startsWith(N$))throw[403,"Access Denied"];if(!await t1(A).exists())return Response.redirect("/");return new Response(t1(A))}catch(S){let o=B1.safeParse(S);if(o.success){let[f,A]=o.data,$=`${PA[f]}. ${A}`;return FS.info(`\u274C ${f}: ${$}`),new Response($,{status:f})}if(S instanceof Error)FS.error(S.message);else{let f=Do(S);FS.error("frontend server threw",f)}return new Response(PA[500],{status:500})}}});function gA(){FS.info("\uD83D\uDEEC frontend server exiting"),process.exit(0)}process.on("SIGINT",()=>{FS.info("\u2757 received SIGINT; exiting gracefully"),gA()});process.on("SIGTERM",()=>{FS.info("\u2757 received SIGTERM; exiting gracefully"),gA()});process.on("exit",()=>{FS.info("\u2757 received exit; exiting gracefully"),gA()});m$.on("timeToStop",()=>{FS.info('\u2757 backend server received signal "timeToStop"; exiting gracefully'),gA()});FS.info(`\uD83D\uDEEB frontend server running at http://localhost:${QS.FRONTEND_PORT}/`);m$.emit("alive");
|