tempest.games 0.1.35 → 0.1.37
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 +25 -0
- package/app/assets/index-i-9D4V9Z.js +62 -0
- package/app/index.html +1 -1
- package/bin/backend.bun.js +27 -27
- package/bin/backend.worker.game.bun.js +5 -5
- package/bin/backend.worker.tribunal.bun.js +41 -41
- package/bin/frontend.bun.js +14 -14
- package/bin/interactive-db.bun.js +1 -1
- package/bin/setup-db.bun.js +72 -67
- package/package.json +21 -21
- package/app/assets/index-CpVfnMp6.js +0 -62
package/bin/frontend.bun.js
CHANGED
|
@@ -1,30 +1,30 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
var
|
|
4
|
-
${t.trace}`:"No previous disposal trace was found.");return}let $=$F(o,
|
|
5
|
-
`+
|
|
3
|
+
var BM=Object.create;var{getPrototypeOf:mM,defineProperty:oA,getOwnPropertyNames:LM}=Object;var CM=Object.prototype.hasOwnProperty;var tk=(o,T,n)=>{n=o!=null?BM(mM(o)):{};let f=T||!o||!o.__esModule?oA(n,"default",{value:o,enumerable:!0}):n;for(let S of LM(o))if(!CM.call(f,S))oA(f,S,{get:()=>o[S],enumerable:!0});return f};var Rk=(o,T)=>()=>(T||o((T={exports:{}}).exports,T),T.exports);var IM=(o,T)=>{for(var n in T)oA(o,n,{get:T[n],enumerable:!0,configurable:!0,set:(f)=>T[n]=()=>f})};var Mk=import.meta.require;import{join as $k,normalize as Fk,resolve as N0}from"node:path";function Zf(o=Math.random){return o().toString(36).slice(2)}class nf extends Promise{fate;resolve;reject;done=!1;constructor(o){let T,n;super((f,S)=>{T=f,n=S});this.resolve=T,this.reject=n,this.use(o instanceof Promise?o:new Promise(o))}pass(o,T){if(o===this.fate)this.resolve(T),this.done=!0}fail(o,T){if(o===this.fate)this.reject(T),this.done=!0}use(o){if(o instanceof Promise){let T=o;this.fate=T,T.then((n)=>{this.pass(T,n)},(n)=>{this.fail(T,n)})}else this.resolve(o),this.fate=void 0}}function g$(o){return Object.entries(o)}var d$=(o,T,n=fo.STORE)=>{return jT(n,{key:`${o.key}:JSON`,get:({get:f})=>T.toJson(f(o)),set:({set:f},S)=>{f(o,T.fromJson(S))}})};function C(o){while(o.child!==null)o=o.child;return o}class oo{Subscriber;subscribers=new Map;subscribe(o,T){return this.subscribers.set(o,T),()=>{this.unsubscribe(o)}}unsubscribe(o){this.subscribers.delete(o)}next(o){let T=this.subscribers.values();for(let n of T)n(o)}}class TA extends oo{state;constructor(o){super();this.state=o}next(o){this.state=o,super.next(o)}}function hT(o,T,n){let f={key:T.key,type:"atom_family"},S=o.families.get(T.key);if(S)o.logger.error("\u2757","atom_family",T.key,`Overwriting an existing ${VT(S)} "${S.key}" in store "${o.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let A=new oo,F=Object.assign((J)=>{let t=no(J),R={key:T.key,subKey:t},W=`${T.key}(${t})`,O=C(o),_=T.default,Q={key:W,default:_ instanceof Function?_(J):_};if(T.effects)Q.effects=T.effects(J);let H=FT(O,Q,R);return A.next({type:"state_creation",token:H}),H},f,{subject:A,install:(J)=>hT(J,T),internalRoles:n});return o.families.set(T.key,F),o.defaults.set(T.key,T.default),f}function l$(o,T){if("mutable"in T)return ff(o,T);return hT(o,T)}function NT(o,T,n){let f={key:T.key,type:"readonly_selector_family"},S=o.families.get(T.key);if(S)o.logger.error("\u2757","readonly_selector_family",T.key,`Overwriting an existing ${VT(S)} "${S.key}" in store "${o.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let A=new oo,F=Object.assign((J)=>{let t=no(J),R={key:T.key,subKey:t},W=`${T.key}(${t})`,O=C(o),_=Sf(O,{key:W,get:T.get(J)},R);return A.next({type:"state_creation",token:_}),_},f,{internalRoles:n,subject:A,install:(J)=>NT(J,T),default:(J)=>{return T.get(J)({get:(...R)=>to(o,...R),find:(...R)=>i(o,...R),json:(R)=>Io(o,R)})}});return o.families.set(T.key,F),f}function Pf(o,T){if("set"in T)return Af(o,T);return NT(o,T)}class gf{_buffer;_index=0;constructor(o){let T;if(typeof o==="number")T=o;else T=o.length;this._buffer=Array.from({length:T})}get buffer(){return this._buffer}get index(){return this._index}add(o){this._buffer[this._index]=o,this._index=(this._index+1)%this._buffer.length}copy(){let o=new gf([...this._buffer]);return o._index=this._index,o}}var jM={atom_family:"atom",mutable_atom_family:"mutable_atom",selector_family:"selector",readonly_selector_family:"readonly_selector",molecule_family:"molecule"};function u$(o,T){let n=no(T),f=`${o.key}(${n})`,S=jM[o.type],A={key:f,type:S};return Object.assign(A,{family:{key:o.key,subKey:n}}),Object.assign(A,{counterfeit:!0}),A}function fT(o){let T={key:o.key,type:o.type};if("family"in o)T.family=o.family;return T}function Gn(o){return e$(fo.STORE,o)}function nn(o){return l$(fo.STORE,o)}function nA(...o){if(o.length===2)return to(fo.STORE,...o);return to(fo.STORE,...o)}function df(o,T,n=fo.STORE){return n.joins.set(o.key,new $f(o,T,n)),{key:o.key,type:"join",a:o.between[0],b:o.between[1],cardinality:o.cardinality}}function a$(o){return oF(o,fo.STORE)}var fA=(o)=>(T,n,f,S,...A)=>{console[o](`${T} ${n} "${f}" ${S}`,...A)},hM={error:fA("error"),info:fA("info"),warn:fA("warn")};class SA{logLevel;filter;logger;constructor(o,T,n=hM){this.logLevel=o,this.filter=T,this.logger=n}error=(...o)=>{if((this.filter?.(...o)??!0)&&this.logLevel!==null)this.logger.error(...o)};info=(...o)=>{if((this.filter?.(...o)??!0)&&this.logLevel==="info")this.logger.info(...o)};warn=(...o)=>{if((this.filter?.(...o)??!0)&&this.logLevel!=="error"&&this.logLevel!==null)this.logger.warn(...o)}}var lk=Symbol("claim");class TF{store;constructor(o=fo.STORE){this.store=o,nF("root",o)}allocate(o,T,n){return fn(this.store,o,T,n)}fuse(o,T,n){return fF(this.store,o,T,n)}deallocate(o){Sn(this.store,o)}claim(o,T,n){return Yn(this.store,o,T,n)}}class AA{store;realm;constructor(o=fo.STORE){this.store=o,this.realm=new TF(o)}allocate(o,T,n){fn(this.store,o,T,n)}deallocate(o){Sn(this.store,o)}claim(o,T,n){Yn(this.store,o,T,n)}}function uf(o){return Pf(fo.STORE,o)}function qo(o){return"epoch"in o.transactionMeta}function Ro(o){return"phase"in o.transactionMeta}var SF=(o)=>{let T=C(o);if(!Ro(T)){o.logger.warn("\uD83D\uDC1E","transaction","???","abortTransaction called outside of a transaction. This is probably a bug in AtomIO.");return}o.logger.info("\uD83E\uDE82","transaction",T.transactionMeta.update.key,"Aborting transaction"),T.parent.child=null};function Mo(o){return o[0].toUpperCase()+o.slice(1)}function VT(o){return o.type.split("_").map(Mo).join(" ")}class An extends Error{constructor(o,T){super(`${VT(o)} ${no(o.key)} not found in store "${T.config.name}".`)}}function zn(o,T,n){return(...f)=>{let S=$o(o,T);if(S)return S.run(f,n);throw new An(T,o)}}var ef=(o)=>(T)=>o instanceof Function?o(T):o;var PT=(o,T)=>{if(o.valueMap.has(T.key))return o.logger.info("\uD83D\uDCD6",T.type,T.key,"reading cached value"),AF(T,o);switch(T.type){case"selector":case"readonly_selector":return o.logger.info("\uD83E\uDDEE",T.type,T.key,"computing value"),T.get();case"atom":case"mutable_atom":{let n=T.default,f;if(n instanceof Function)f=n();else f=n;return o.logger.info("\uD83D\uDC81","atom",T.key,"could not find cached value; using default",f),f}}};var $F=(o,T)=>{if(o.operation.open){let n=performance.now();return o.logger.info("\u2757",T.type,T.key,`deferring setState at T-${n} until setState for "${o.operation.token.key}" is done`),n}o.operation={open:!0,done:new Set,prev:new Map,time:Date.now(),token:T},o.logger.info("\u2B55",T.type,T.key,`operation start in store "${o.config.name}"${!Ro(o)?"":` ${o.transactionMeta.phase} "${o.transactionMeta.update.key}"`}`)},FF=(o)=>{if(o.operation.open)o.logger.info("\uD83D\uDD34",o.operation.token.type,o.operation.token.key,`operation done in store "${o.config.name}"`);o.operation={open:!1},o.on.operationClose.next(o.operation)},JF=(o,T)=>{if(!o.operation.open)return o.logger.error("\uD83D\uDC1E","unknown",T,"isDone called outside of an operation. This is probably a bug in AtomIO."),!0;return o.operation.done.has(T)},Dn=(o,T)=>{if(!o.operation.open){o.logger.error("\uD83D\uDC1E","unknown",T,"markDone called outside of an operation. This is probably a bug in AtomIO.");return}o.operation.done.add(T)};var tF=(o,T,n)=>{switch(T.type){case"mutable_atom":o.logger.info("\uD83D\uDCE2",T.type,T.key,"is now (",n.newValue,") subscribers:",T.subject.subscribers);break;case"atom":case"selector":case"readonly_selector":o.logger.info("\uD83D\uDCE2",T.type,T.key,"went (",n.oldValue,"->",n.newValue,") subscribers:",T.subject.subscribers)}T.subject.next(n)};var $A=(o,T)=>{let n=C(o),f=n.selectorAtoms.getRelatedKeys(T.key);if(n.logger.info("\uD83E\uDDF9",T.type,T.key,f?`evicting ${f.size} states downstream:`:"no downstream states",f??"to evict"),f){if(n.operation.open)n.logger.info("\uD83E\uDDF9",T.type,T.key,`[ ${[...n.operation.done].join(", ")} ] already done`);for(let S of f){if(JF(n,S))continue;RF(S,n),Dn(n,S)}}};var MF=(o,T,n)=>{let f=PT(o,T),S=f;if(T.type==="mutable_atom"&&Ro(o)){let{parent:$}=o;S=Jf(o,T,$)}if(S=ef(n)(S),o.logger.info("\uD83D\uDCDD","atom",T.key,"set to",S),S=yT(o,T.key,S,T.subject),kF(o,T.key))WF(o,T.key);Dn(o,T.key),$A(o,T);let A={oldValue:f,newValue:S};if(!Ro(o)){tF(o,T,A);return}if(o.on.transactionApplying.state===null){let{key:$}=T;if(yF(A.newValue))return;let F={type:"atom_update",key:$,...A};if(T.family)F.family=T.family;o.transactionMeta.update.updates.push(F),o.logger.info("\uD83D\uDCC1","atom",$,"stowed (",A.oldValue,"->",A.newValue,")")}else if(T.key.startsWith("*")){let $=T.key.slice(1),F=o.atoms.get($),J=o.valueMap.get($);if(F.type==="mutable_atom"&&Ro(o)){let{parent:R}=o;J=Jf(o,F,R)}if(J.do(A.newValue)===null)$A(o,F)}};var sf=(o,T,n)=>{switch(T.type){case"atom":case"mutable_atom":MF(o,T,n);break;case"selector":T.set(n);break}};function OF(o,T){if(T.family){let n=o.families.get(T.family.key);if(n)return n}}function Uo(o,...T){let n,f,S,A;if(T.length===2){if(n=T[0],A=T[1],f=OF(o,n)??null,f)S=n.family?xo(n.family.subKey):null,n=i(o,f,S)}else f=T[0],S=T[1],A=T[2],n=i(o,f,S);if("counterfeit"in n&&"family"in n){let J=n.family.subKey,t=o.disposalTraces.buffer.find((R)=>R?.key===J);o.logger.error("\u274C",n.type,n.key,`could not be set because it was not found in the store "${o.config.name}".`,t?`This state was previously disposed:
|
|
4
|
+
${t.trace}`:"No previous disposal trace was found.");return}let $=$F(o,n);if($){let J=o.on.operationClose.subscribe(`waiting to set "${n.key}" at T-${$}`,()=>{J(),o.logger.info("\uD83D\uDFE2",n.type,n.key,`resuming deferred setState from T-${$}`),Uo(o,n,A)});return}let F=$o(o,n);sf(o,F,A),FF(o)}function af(o,T,n){let{key:f,newValue:S,oldValue:A}=T,$=o==="newValue"?S:A,F={key:f,type:"atom"};if(T.family)Object.assign(F,{family:T.family});Uo(n,F,$)}function wF(o){let{stack:T}=o;if(T)return`
|
|
5
|
+
`+T.split(`
|
|
6
6
|
`)?.slice(1)?.join(`
|
|
7
|
-
`);return""}function
|
|
7
|
+
`);return""}function nF(o,T=fo.STORE){let n={key:o,stringKey:no(o),dependsOn:"any"};return T.molecules.set(no(o),n),o}function fn(o,T,n,f="any"){let S=T,A=no(n),$=[],F=C(o);if(Array.isArray(S))for(let R of S){let W=no(R);if(F.molecules.get(W))o.moleculeGraph.set(W,A,{source:W});else $.push(W)}else{let R=no(S);if(F.molecules.get(R))o.moleculeGraph.set(R,A,{source:R});else $.push(R)}if($.length===0)F.molecules.set(A,{key:n,stringKey:A,dependsOn:f});let J={type:"molecule_creation",key:n,provenance:S};if(Ro(F)&&F.transactionMeta.phase==="building")F.transactionMeta.update.updates.push(J);else F.on.moleculeCreation.next(J);for(let R of $){let W=o.disposalTraces.buffer.find((O)=>O?.key===R);o.logger.error("\u274C","molecule",n,"allocation failed:",`Could not allocate to ${R} in store "${o.config.name}".`,W?`
|
|
8
8
|
${R} was most recently disposed
|
|
9
|
-
${W.trace}`:`No previous disposal trace for ${R} was found.`)}return
|
|
9
|
+
${W.trace}`:`No previous disposal trace for ${R} was found.`)}return n}function fF(o,T,n,f){let S=`T$--${T}==${n}++${f}`;return fn(o,[n,f],S,"all"),S}function Sn(o,T){let n=no(T),f=o.molecules.get(n);if(!f){let _=o.disposalTraces.buffer.find((Q)=>Q?.key===n);o.logger.error("\u274C","molecule",T,"deallocation failed:",`Could not find allocation for ${n} in store "${o.config.name}".`,_?`
|
|
10
10
|
This state was most recently deallocated
|
|
11
|
-
${_.trace}`:`No previous disposal trace for ${
|
|
11
|
+
${_.trace}`:`No previous disposal trace for ${n} was found.`);return}let S=o.moleculeJoins.getRelatedKeys(f.key);if(S)for(let _ of S){let Q=o.joins.get(_);if(Q)Q.relations.delete(f.key),Q.molecules.delete(f.stringKey)}o.moleculeJoins.delete(f.stringKey);let A=[],$=[],F={type:"molecule_disposal",key:f.key,values:$,provenance:A},J=C(o);J.molecules.delete(n);let t=Ro(J)&&J.transactionMeta.phase==="building";if(t)J.transactionMeta.update.updates.push(F);let R=o.moleculeGraph.getRelationEntries({downstreamMoleculeKey:f.stringKey});if(R)for(let[_,{source:Q}]of R)if(Q===f.stringKey){let H=xo(_);Sn(o,H)}else A.push(Q);let W=J.moleculeData.getRelatedKeys(f.stringKey);if(W)for(let _ of W){let Q=J.families.get(_),H=i(o,Q,f.key);$.push([Q.key,H]),$n(o,H)}if(J.moleculeGraph.delete(f.stringKey),J.moleculeJoins.delete(f.stringKey),J.moleculeData.delete(f.stringKey),!t)J.on.moleculeDisposal.next(F);J.molecules.delete(f.stringKey);let O=wF(new Error);o.disposalTraces.add({key:n,trace:O})}function Yn(o,T,n,f){let S=no(n),A=C(o),$=A.molecules.get(S);if(!$){let O=o.disposalTraces.buffer.find((_)=>_?.key===S);return o.logger.error("\u274C","molecule",n,"claim failed:",`Could not allocate to ${S} in store "${o.config.name}".`,O?`
|
|
12
12
|
${S} was most recently disposed
|
|
13
|
-
${O.trace}`:`No previous disposal trace for ${S} was found.`),
|
|
13
|
+
${O.trace}`:`No previous disposal trace for ${S} was found.`),n}let F=no(T),J=A.molecules.get(F);if(!J){let O=o.disposalTraces.buffer.find((_)=>_?.key===F);return o.logger.error("\u274C","molecule",n,"claim failed:",`Could not allocate to ${F} in store "${o.config.name}".`,O?`
|
|
14
14
|
${F} was most recently disposed
|
|
15
|
-
${O.trace}`:`No previous disposal trace for ${F} was found.`),
|
|
16
|
-
${$.trace}`:"No previous disposal trace was found."),f.type){case"atom_family":case"mutable_atom_family":return o.defaults.get(f.key);case"selector_family":case"readonly_selector_family":{if(o.defaults.has(f.key))return o.defaults.get(T.family.key);let F=$o(o,f).default(A);return o.defaults.set(f.key,F),F}}}return Pn(o,$o(o,T))}class jo{a;b;cardinality;relations=new Map;contents=new Map;isAType;isBType;isContent;makeContentKey=(o,n)=>`${o}:${n}`;warn;getRelatedKeys(o){return this.relations.get(o)}addRelation(o,n){let T=this.relations.get(o),f=this.relations.get(n);if(T)T.add(n);else T=new Set([n]),this.relations.set(o,T);if(f)f.add(o);else f=new Set([o]),this.relations.set(n,f)}deleteRelation(o,n){let T=this.relations.get(o);if(T){if(T.delete(n),T.size===0)this.relations.delete(o);let f=this.relations.get(n);if(f){if(f.delete(o),f.size===0)this.relations.delete(n)}}}replaceRelationsUnsafely(o,n){this.relations.set(o,new Set(n));for(let T of n){let f=new Set().add(o);this.relations.set(T,f)}}replaceRelationsSafely(o,n){let T=this.relations.get(o),f=this.isAType?.(o)?o:void 0,S=f===void 0?o:void 0;if(T)for(let A of T){f??=A,S??=A;let $=this.relations.get(A);if($){if($.size===1)this.relations.delete(A);else $.delete(o);this.contents.delete(this.makeContentKey(f,S))}}this.relations.set(o,new Set(n));for(let A of n){let $=this.relations.get(A);if($)$.add(o);else $=new Set().add(o),this.relations.set(A,$)}}getContentInternal(o){return this.contents.get(o)}setContent(o,n){this.contents.set(o,n)}deleteContent(o){this.contents.delete(o)}constructor(o,n){if(this.a=o.between[0],this.b=o.between[1],this.cardinality=o.cardinality,!n?.externalStore)this.relations=new Map(o.relations?.map(([T,f])=>[T,new Set(f)])),this.contents=new Map(o.contents);if(this.isAType=n?.isAType??null,this.isBType=n?.isBType??null,this.isContent=n?.isContent??null,n?.makeContentKey)this.makeContentKey=n.makeContentKey;if(n?.externalStore){let T=n.externalStore;if(this.has=(f,S)=>T.has(f,S),this.addRelation=(f,S)=>{T.addRelation(f,S)},this.deleteRelation=(f,S)=>{T.deleteRelation(f,S)},this.replaceRelationsSafely=(f,S)=>{T.replaceRelationsSafely(f,S)},this.replaceRelationsUnsafely=(f,S)=>{T.replaceRelationsUnsafely(f,S)},this.getRelatedKeys=(f)=>T.getRelatedKeys(f),T.getContent)this.getContentInternal=(f)=>{return T.getContent(f)},this.setContent=(f,S)=>{T.setContent(f,S)},this.deleteContent=(f)=>{T.deleteContent(f)};for(let[f,S]of o.relations??[]){let A=this.isAType?.(f)?f:void 0,$=A===void 0?f:void 0;for(let F of S)A??=F,$??=F,this.addRelation(A,$)}for(let[f,S]of o.contents??[])this.setContent(f,S)}if(n?.warn)this.warn=n.warn}toJSON(){return{between:[this.a,this.b],cardinality:this.cardinality,relations:[...this.relations.entries()].map(([o,n])=>[o,[...n]]),contents:[...this.contents.entries()]}}set(...o){let n,T,f;switch(o.length){case 1:{let S=o[0];n=S[this.a],T=S[this.b],f=void 0;break}case 2:{let S=o[0];if(typeof S==="string")[n,T]=o;else n=S[this.a],T=S[this.b],f=o[1];break}default:{n=o[0],T=o[1],f=o[2];break}}switch(this.cardinality){case"1:1":{let S=this.getRelatedKey(n);if(S&&S!==T)this.delete(n,S)}case"1:n":{let S=this.getRelatedKey(T);if(S&&S!==n)this.delete(S,T)}break;case"n:n":}if(f){let S=this.makeContentKey(n,T);this.setContent(S,f)}return this.addRelation(n,T),this}delete(o,n){n=typeof n==="string"?n:o[this.b];let T=typeof o==="string"?o:o[this.a];if(T===void 0&&typeof n==="string"){let f=this.getRelatedKeys(n);if(f)for(let S of f)this.delete(S,n)}if(typeof T==="string"&&n===void 0){let f=this.getRelatedKeys(T);if(f)for(let S of f)this.delete(T,S)}if(typeof T==="string"&&typeof n==="string"){this.deleteRelation(T,n);let f=this.makeContentKey(T,n);this.deleteContent(f)}return this}getRelatedKey(o){let n=this.getRelatedKeys(o);if(n){if(n.size>1)this.warn?.(`${n.size} related keys were found for key "${o}": (${[...n].map((f)=>`"${f}"`).join(", ")}). Only one related key was expected.`);let T;for(let f of n){T=f;break}return T}}replaceRelations(o,n,T){let f=!Array.isArray(n),S=f?Object.keys(n):n;if(T?.reckless)this.replaceRelationsUnsafely(o,S);else this.replaceRelationsSafely(o,S);if(f)for(let A of S){let $=this.makeContentKey(o,A),F=n[A];this.setContent($,F)}return this}getContent(o,n){let T=this.makeContentKey(o,n);return this.getContentInternal(T)}getRelationEntries(o){let n=o[this.a],T=o[this.b];if(n!==void 0&&T===void 0){let f=this.getRelatedKeys(n);if(f)return[...f].map((S)=>{return[S,this.getContent(n,S)]})}if(n===void 0&&T!==void 0){let f=this.getRelatedKeys(T);if(f)return[...f].map((S)=>{return[S,this.getContent(S,T)]})}return[]}has(o,n){if(n)return this.getRelatedKeys(o)?.has(n)??!1;return this.relations.has(o)}}class kn extends Map{deleted=new Set;source;constructor(o){super();this.source=o}get(o){if(super.has(o))return super.get(o);if(!this.deleted.has(o)&&this.source.has(o))return this.source.get(o);return}set(o,n){return this.deleted.delete(o),super.set(o,n)}hasOwn(o){return super.has(o)}has(o){return!this.deleted.has(o)&&(super.has(o)||this.source.has(o))}delete(o){return this.deleted.add(o),super.delete(o)}}var UF=(o,n,T,f)=>{let S=C(o),A={parent:S,child:null,on:S.on,loggers:S.loggers,logger:S.logger,config:S.config,atoms:new kn(S.atoms),atomsThatAreDefault:new Set(S.atomsThatAreDefault),families:new kn(S.families),joins:new kn(S.joins),operation:{open:!1},readonlySelectors:new kn(S.readonlySelectors),timelines:new kn(S.timelines),timelineTopics:new jo(S.timelineTopics.toJSON()),trackers:new Map,transactions:new kn(S.transactions),selectorAtoms:new jo(S.selectorAtoms.toJSON()),selectorGraph:new jo(S.selectorGraph.toJSON(),{makeContentKey:(...t)=>t.sort().join(":")}),selectors:new kn(S.selectors),valueMap:new kn(S.valueMap),defaults:S.defaults,disposalTraces:o.disposalTraces.copy(),molecules:new kn(S.molecules),moleculeGraph:new jo(S.moleculeGraph.toJSON(),{makeContentKey:S.moleculeGraph.makeContentKey}),moleculeData:new jo(S.moleculeData.toJSON(),{makeContentKey:S.moleculeData.makeContentKey}),moleculeJoins:new jo(S.moleculeJoins.toJSON(),{makeContentKey:S.moleculeJoins.makeContentKey}),miscResources:new kn(S.miscResources)},$=EF(o,n),F={phase:"building",update:{type:"transaction_update",key:n,id:f,epoch:$===void 0?Number.NaN:$+1,updates:[],params:T,output:void 0},toolkit:{get:(...t)=>to(J,...t),set:(...t)=>{Uo(J,...t)},run:(t,R=Zf())=>DT(J,t,R),find:(t,R)=>i(J,t,R),json:(t)=>Io(J,t),dispose:(...t)=>{FT(J,...t)},env:()=>QF(J)}},J=Object.assign(A,{transactionMeta:F});return S.child=J,o.logger.info("\uD83D\uDEEB","transaction",n,"Building transaction with params:",T),J};function RA(o,n){let T={key:n.key,type:"transaction",run:(A,$)=>{let F=UF(o,n.key,A,$);try{let J=C(o),{toolkit:t}=F.transactionMeta,R=n.do(t,...A);return zF(R,J),R}catch(J){throw SF(f),o.logger.warn("\uD83D\uDCA5","transaction",n.key,"caught:",J),J}},install:(A)=>RA(A,n),subject:new oo},f=C(o);f.transactions.set(T.key,T);let S=fn(T);return o.on.transactionCreation.next(S),S}function tf(o){return RA(fo.STORE,o)}class VF{parent=null;child=null;valueMap=new Map;defaults=new Map;atoms=new Map;selectors=new Map;readonlySelectors=new Map;atomsThatAreDefault=new Set;selectorAtoms=new jo({between:["selectorKey","atomKey"],cardinality:"n:n"});selectorGraph=new jo({between:["upstreamSelectorKey","downstreamSelectorKey"],cardinality:"n:n"},{makeContentKey:(...o)=>o.sort().join(":")});trackers=new Map;families=new Map;joins=new Map;transactions=new Map;transactionMeta={epoch:new Map,actionContinuities:new jo({between:["continuity","action"],cardinality:"1:n"})};timelines=new Map;timelineTopics=new jo({between:["timelineKey","topicKey"],cardinality:"1:n"});disposalTraces=new gf(100);molecules=new Map;moleculeJoins=new jo({between:["moleculeKey","joinKey"],cardinality:"n:n"},{makeContentKey:(...o)=>o.sort().join(":")});moleculeGraph=new jo({between:["upstreamMoleculeKey","downstreamMoleculeKey"],cardinality:"n:n"},{makeContentKey:(...o)=>o.sort().join(":")});moleculeData=new jo({between:["moleculeKey","stateFamilyKey"],cardinality:"n:n"},{makeContentKey:(...o)=>o.sort().join(":")});miscResources=new Map;on={atomCreation:new oo,atomDisposal:new oo,selectorCreation:new oo,selectorDisposal:new oo,timelineCreation:new oo,transactionCreation:new oo,transactionApplying:new nA(null),operationClose:new oo,moleculeCreation:new oo,moleculeDisposal:new oo};operation={open:!1};config={name:"IMPLICIT_STORE",lifespan:"ephemeral"};loggers=[new SA("warn",(o,n,T)=>!gn(T))];logger={error:(...o)=>{for(let n of this.loggers)n.error(...o)},info:(...o)=>{for(let n of this.loggers)n.info(...o)},warn:(...o)=>{for(let n of this.loggers)n.warn(...o)}};constructor(o,n=null){if(this.config={...n?.config,...o},n!==null){if(this.valueMap=new Map(n?.valueMap),this.operation={...n?.operation},qo(n))this.transactionMeta={epoch:new Map(n?.transactionMeta.epoch),actionContinuities:new jo(n?.transactionMeta.actionContinuities.toJSON())};for(let[,f]of n.families){if(f.internalRoles?.includes("mutable")||f.internalRoles?.includes("join"))continue;f.install(this)}let T=new Set;for(let[,f]of n.atoms){if(T.has(f.key))continue;if(f.install(this),f.type==="mutable_atom"){let S=Io(n,f),A=bn(f);T.add(S.key),T.add(A.key)}}for(let[,f]of n.readonlySelectors)f.install(this);for(let[,f]of n.selectors){if(T.has(f.key))continue;f.install(this)}for(let[,f]of n.transactions)f.install(this);for(let[,f]of n.timelines)f.install(this)}}}var fo={get STORE(){if(!globalThis.ATOM_IO_IMPLICIT_STORE)globalThis.ATOM_IO_IMPLICIT_STORE=new VF({name:"IMPLICIT_STORE",lifespan:"ephemeral"});return globalThis.ATOM_IO_IMPLICIT_STORE}};function $o(o,n){let T,f=o;while(f!==null){switch(n.type){case"atom":case"mutable_atom":T=f.atoms.get(n.key);break;case"selector":T=f.selectors.get(n.key);break;case"readonly_selector":T=f.readonlySelectors.get(n.key);break;case"atom_family":case"mutable_atom_family":case"selector_family":case"readonly_selector_family":T=f.families.get(n.key);break;case"timeline":T=f.timelines.get(n.key);break;case"transaction":T=f.transactions.get(n.key);break}if(T)return T;f=f.child}throw new $T(n,o)}function mF(o,n,T){let f=o.families.get(n.key);if(f===void 0)throw new $T(n,o);let S=f(T),A=C(o);if(S.family){if(qo(A))switch(S.type){case"atom":case"mutable_atom":o.on.atomCreation.next(S);break;case"selector":case"readonly_selector":o.on.selectorCreation.next(S);break}else if(Ro(A)&&A.on.transactionApplying.state===null)A.transactionMeta.update.updates.push({type:"state_creation",token:S})}return S}function BF(o,n,T){let f=To(T),S=`${n.key}(${f})`,A=C(o),$;switch(n.type){case"atom_family":case"mutable_atom_family":$=A.atoms.get(S);break;case"selector_family":$=A.selectors.get(S);break;case"readonly_selector_family":$=A.readonlySelectors.get(S);break}if($)return fn($);return $}function i(o,n,T){let f=BF(o,n,T);if(f)return f;let S=To(T),A=o.molecules.get(S);if(!A&&o.config.lifespan==="immortal"){let $=u$(n,T);return o.logger.error("\u274C",$.type,$.key,`was not found in store "${o.config.name}"; returned a counterfeit token.`),$}if(f=mF(o,n,T),A)C(o).moleculeData.set(S,n.key);return f}function FT(o,...n){let T;if(n.length===1)T=n[0];else{let f=n[0],S=n[1];T=i(o,f,S)}try{$o(o,T)}catch(f){o.logger.error("\u274C",T.type,T.key,`could not be disposed because it was not found in the store "${o.config.name}".`);return}switch(T.type){case"atom":case"mutable_atom":MA(o,T);break;case"selector":case"readonly_selector":LF(o,T);break}}var nS=(o,n)=>C(o).atoms.has(n),IM=(o,n)=>C(o).selectors.has(n),jM=(o,n)=>C(o).readonlySelectors.has(n),CF=(o,n)=>nS(o,n)||IM(o,n)||jM(o,n);var TS=(o,n)=>{return C(n).selectorGraph.getRelationEntries({downstreamSelectorKey:o}).filter(([f,{source:S}])=>S!==o).map(([f,{source:S}])=>S).filter((f)=>CF(n,f))};var yA=(o,n,T)=>{let f=[],S=TS(o,T);while(S.length>0){let A=S.shift();if(n.has(A))continue;if(n.add(A),!nS(T,A))S.push(...TS(A,T));else if(!f.includes(A))f.push(A)}return f},IF=(o,n)=>{let T=o.key,f=TS(T,n),S=new Set;return f.flatMap((A)=>nS(n,A)?A:yA(A,S,n))};var jF=(o,n,T,f)=>{let S=C(f);if(n.type==="atom"||n.type==="mutable_atom")S.selectorAtoms.set({selectorKey:o,atomKey:n.key}),f.logger.info("\uD83D\uDD0D","selector",o,`discovers root atom "${n.key}"`);else{let A=yA(n.key,T,f);f.logger.info("\uD83D\uDD0D","selector",o,`discovers root atoms: [ ${A.map(($)=>`"${$}"`).join(", ")} ]`);for(let $ of A)S.selectorAtoms=S.selectorAtoms.set({selectorKey:o,atomKey:$})}T.add(n.key)};var fS=(o,n,T)=>({get:(...f)=>{let S=C(T),A;if(f.length===2){let[J,t]=f;A=i(T,J,t)}else[A]=f;let $=$o(T,A),F=Pn(T,$);return T.logger.info("\uD83D\uDD0C","selector",o,`registers dependency ( "${A.key}" =`,F,")"),S.selectorGraph.set({upstreamSelectorKey:A.key,downstreamSelectorKey:o},{source:A.key}),jF(o,A,n,T),F},set:(...f)=>{let S,A;if(f.length===2)S=f[0],A=f[1];else{let J=f[0],t=f[1];A=f[2],S=i(T,J,t)}let $=C(T),F=$o($,S);sf($,F,A)},find:(f,S)=>i(T,f,S),json:(f)=>Io(T,f)});var Sf=(o,n,T)=>{let f=C(o),S=new oo,A=new Set,{get:$,find:F,json:J}=fS(n.key,A,f),t=()=>{let _=n.get({get:$,find:F,json:J});return yn(C(o),n.key,_,S),A.clear(),_},R={...n,subject:S,install:(_)=>Sf(_,n,T),get:t,type:"readonly_selector",...T&&{family:T}};f.readonlySelectors.set(n.key,R);let W=t();o.logger.info("\u2728",R.type,R.key,"=",W);let O={key:n.key,type:"readonly_selector"};if(T)O.family=T;return O};var Rf=(o,n,T)=>{let f=C(o),S=new oo,A=new Set,$=fS(n.key,A,f),{find:F,get:J,json:t}=$,R={find:F,get:J,json:t},W=(B=n.get,h=C(o))=>{let r=B(R);return yn(h,n.key,r,S),A.clear(),r},_={...n,subject:S,install:(B)=>Rf(B,n,T),get:W,set:(B)=>{let h=C(o),r=W(n.get,h),P=ef(B)(r);if(o.logger.info("\uD83D\uDCDD","selector",n.key,"set (",r,"->",P,")"),yn(h,n.key,P,S),QT(h,n.key),qo(h))S.next({newValue:P,oldValue:r});n.set($,P)},type:"selector",...T&&{family:T}};f.selectors.set(n.key,_);let Q=W();o.logger.info("\u2728",_.type,_.key,"=",Q);let K={key:n.key,type:"selector"};if(T)K.family=T;return K};function jn(o,n){if("set"in n){let S=Rf(o,n,void 0);return o.on.selectorCreation.next(S),S}let f=Sf(o,n,void 0);return o.on.selectorCreation.next(f),f}function LF(o,n){let T=C(o),{key:f}=n,S=$o(T,n);if(!S.family)o.logger.error("\u274C","selector",f,"Standalone selectors cannot be disposed.");else{if(T.molecules.get(S.family.subKey))T.moleculeData.delete(S.family.subKey,S.family.key);let $;switch(n.type){case"selector":T.selectors.delete(f),$={key:S.family.key,type:"selector_family"},$o(o,$).subject.next({type:"state_disposal",subType:"selector",token:n});break;case"readonly_selector":T.readonlySelectors.delete(f),$={key:S.family.key,type:"readonly_selector_family"},$o(o,$).subject.next({type:"state_disposal",subType:"selector",token:n});break}if(T.valueMap.delete(f),T.selectorAtoms.delete(f),T.selectorGraph.delete(f),o.logger.info("\uD83D\uDD25",n.type,f,"deleted"),Ro(T)&&T.transactionMeta.phase==="building")T.transactionMeta.update.updates.push({type:"state_disposal",subType:"selector",token:n});else o.on.selectorDisposal.next(n)}}function Af(o,n,T){let f={key:n.key,type:"selector_family"},S=o.families.get(n.key);if(S)o.logger.error("\u2757","selector_family",n.key,`Overwriting an existing ${Vn(S)} "${S.key}" in store "${o.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let A=new oo,F=Object.assign((J)=>{let t=To(J),R={key:n.key,subKey:t},W=`${n.key}(${t})`,O=C(o),_=Rf(O,{key:W,get:n.get(J),set:n.set(J)},R);return A.next({type:"state_creation",token:_}),_},f,{internalRoles:T,subject:A,install:(J)=>Af(J,n),default:(J)=>{return n.get(J)({get:(...R)=>to(o,...R),find:(R,W)=>i(o,R,W),json:(R)=>Io(o,R)})}});return o.families.set(n.key,F),f}function NF(o,n,T){return Af(o,{key:`${n.key}:JSON`,get:(S)=>({get:A})=>{let $=A(n,S);return T.toJson($)},set:(S)=>({set:A},$)=>{A(n,S,T.fromJson($))}},["mutable","json"])}var xo=(o)=>JSON.parse(o),To=(o)=>JSON.stringify(o),f2=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];var hF=(o,n)=>{let T=C(o);if(T.operation.open)return T.operation.prev.get(n.key);return T.valueMap.get(n.key)};var OA=(o,n)=>{let T=C(o);return IF(n,o).map((S)=>{let A=T.atoms.get(S);if(A===void 0)throw new Error(`Atom "${S}", a dependency of selector "${n.key}", not found in store "${o.config.name}".`);return A.subject.subscribe(`${n.type}:${n.key}`,($)=>{o.logger.info("\uD83D\uDCE2",n.type,n.key,"root",S,"went",$.oldValue,"->",$.newValue);let F=hF(T,n),J=Pn(T,n);o.logger.info("\u2728",n.type,n.key,"went",F,"->",J),n.subject.next({newValue:J,oldValue:F})})})};function lo(o,n,T,f){function S(W){if(o.operation.open){let O=o.on.operationClose.subscribe(`state subscription ${T}`,()=>{O(),f(W)})}else f(W)}let A=$o(o,n);o.logger.info("\uD83D\uDC40",A.type,A.key,`Adding subscription "${T}"`);let $=A.type==="selector"||A.type==="readonly_selector",F=null,J=S;if($)F=OA(o,A),J=(W)=>{if(F)F.length=0,F.push(...OA(o,A));S(W)};let t=A.subject.subscribe(T,J);return()=>{if(o.logger.info("\uD83D\uDE48",A.type,A.key,`Removing subscription "${T}"`),t(),F)for(let W of F)W()}}var kA=(o,n,T,f)=>{let S=$o(o,n);o.logger.info("\uD83D\uDC40","timeline",n.key,`Adding subscription "${T}"`);let A=S.subject.subscribe(T,f);return()=>{o.logger.info("\uD83D\uDE48","timeline",n.key,`Removing subscription "${T}" from timeline`),A()}};var WA=(o,n,T,f)=>{let S=$o(o,n);o.logger.info("\uD83D\uDC40","transaction",n.key,`Adding subscription "${T}"`);let A=S.subject.subscribe(T,f);return()=>{o.logger.info("\uD83D\uDE48","transaction",n.key,`Removing subscription "${T}"`),A()}};class JT{Update;initializeState(o,n){let T=`*${o.key}`;n.atoms.delete(T),n.valueMap.delete(T);let f=o.family?{key:`*${o.family.key}`,subKey:o.family.subKey}:void 0,S=Fn(n,{key:T,default:null},f);if(n.parent?.valueMap.has(T)){let A=n.parent.valueMap.get(T);n.valueMap.set(T,A)}return S}unsubscribeFromInnerValue;unsubscribeFromState;observeCore(o,n,T){let f=`tracker:${T.config.name}:${Ro(T)?T.transactionMeta.update.key:"main"}:${o.key}`,S=to(T,o);this.unsubscribeFromInnerValue=S.subscribe(f,(A)=>{Uo(T,n,A)}),this.unsubscribeFromState=lo(T,o,f,(A)=>{if(A.newValue!==A.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=A.newValue.subscribe(f,($)=>{Uo(T,n,$)})})}updateCore(o,n,T){let f=`tracker:${T.config.name}:${Ro(T)?T.transactionMeta.update.key:"main"}:${o.key}`;lo(T,n,f,({newValue:S,oldValue:A})=>{let $=T.timelineTopics.getRelatedKey(n.key);if($){if(T.timelines.get($)?.timeTraveling){let t=kA(T,{key:$,type:"timeline"},f,(R)=>{t(),Uo(T,o,(W)=>{if(R==="redo"&&S)W.do(S);else if(R==="undo"&&A)W.undo(A);return W})});return}}let F=T.on.operationClose.subscribe(f,()=>{F();let J=to(T,o),t=S===null?-1:J.getUpdateNumber(S),R=t-J.cacheUpdateNumber;if(S&&R===1)Uo(T,o,(W)=>(W.do(S),W));else T.logger.info("\u274C","mutable_atom",o.key,`could not be updated. Expected update number ${J.cacheUpdateNumber+1}, but got ${t}`)})})}mutableState;latestUpdateState;[Symbol.dispose];constructor(o,n){this.mutableState=o;let T=C(n);this.latestUpdateState=this.initializeState(o,T),this.observeCore(o,this.latestUpdateState,T),this.updateCore(o,this.latestUpdateState,T),T.trackers.set(o.key,this),this[Symbol.dispose]=()=>{this.unsubscribeFromInnerValue(),this.unsubscribeFromState(),T.trackers.delete(o.key)}}}function Mf(o,n,T){o.logger.info("\uD83D\uDD28","atom",n.key,`creating in store "${o.config.name}"`);let f=C(o),S=f.atoms.get(n.key);if(S&&S.type==="mutable_atom")return o.logger.error("\u274C","atom",n.key,"Tried to create atom, but it already exists in the store."),fn(S);let A=new oo,$={...n,type:"mutable_atom",install:(t)=>{return t.logger.info("\uD83D\uDEE0\uFE0F","atom",n.key,`installing in store "${t.config.name}"`),Mf(t,n,T)},subject:A};if(T)$.family=T;let F=n.default();f.atoms.set($.key,$),SS(o,n.key),yn(f,n.key,F,A);let J=fn($);if(n.effects){let t=0,R=[];for(let W of n.effects){let O=W({setSelf:(_)=>{Uo(o,J,_)},onSet:(_)=>lo(o,J,`effect[${t}]`,_)});if(O)R.push(O);++t}$.cleanup=()=>{for(let W of R)W()}}if(new JT(J,o),!T)d$(J,n,o);return J}class wA{trackers=new Map;Update;latestUpdateAtoms;mutableAtoms;constructor(o,n){let T=Nn(n,{key:`*${o.key}`,default:null},["mutable","updates"]);this.latestUpdateAtoms=$o(n,T),this.mutableAtoms=o,this.mutableAtoms.subject.subscribe(`store=${n.config.name}::tracker-atom-family`,(f)=>{let{type:S,token:A}=f;if(A.family){let $=xo(A.family.subKey);switch(S){case"state_creation":this.trackers.set($,new JT(A,n));break;case"state_disposal":{let F=this.trackers.get($);if(F)F[Symbol.dispose](),this.trackers.delete($)}break}}})}}function ff(o,n,T){let f={key:n.key,type:"mutable_atom_family"},S=o.families.get(n.key);if(S)o.logger.error("\u2757","mutable_atom_family",n.key,`Overwriting an existing ${Vn(S)} "${S.key}" in store "${o.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let A=new oo,F=Object.assign((J)=>{let t=To(J),R={key:n.key,subKey:t},W=`${n.key}(${t})`,O=C(o),_={key:W,default:()=>n.default(J),toJson:n.toJson,fromJson:n.fromJson,mutable:!0};if(n.effects)_.effects=n.effects(J);let Q=Mf(O,_,R);return A.next({type:"state_creation",token:Q}),Q},f,{subject:A,install:(J)=>ff(J,n),toJson:n.toJson,fromJson:n.fromJson,internalRoles:T});return o.families.set(n.key,F),NF(o,F,n),new wA(F,o),f}var _A=(o,n)=>{let T=C(n),f=`${o.key}:JSON`;return T.families.get(f)};var Io=(o,n)=>{if(n.family){let f=C(o),A={key:`${n.family.key}:JSON`,type:"selector_family"},$=$o(f,A),F=JSON.parse(n.family.subKey);return i(o,$,F)}return{type:"selector",key:`${n.key}:JSON`}};var bn=(o)=>{let T={type:"atom",key:`*${o.key}`};if(o.family)T.family={key:`*${o.family.key}`,subKey:o.family.subKey};return T};function yF(o){return typeof o==="object"&&o!==null&&"do"in o&&"undo"in o&&"subscribe"in o}function Jf(o,n,T){let f=T.valueMap.get(n.key),S=o.valueMap.get(n.key);if(f!==S)return S;if(f===void 0)return n.default();T.logger.info("\uD83D\uDCC3","atom",n.key,"copying");let A=n.toJson(f),$=n.fromJson(A);return o.valueMap.set(n.key,$),new JT(n,T),$}function yn(o,n,T,f){let S=o.valueMap.get(n);if(S instanceof Tf)S.use(T);if(T instanceof Promise){let A=new Tf(T);return o.valueMap.set(n,A),A.then(($)=>{yn(o,n,$,f),f.next({newValue:$,oldValue:A})}).catch(($)=>{o.logger.error("\uD83D\uDCA5","state",n,"rejected:",$)}),A}return o.valueMap.set(n,T),T}var AF=(o,n)=>{let T=n.valueMap.get(o.key);if(o.type==="mutable_atom"&&Ro(n)){let{parent:f}=n;T=Jf(n,o,f)}return T},RF=(o,n)=>{let T=n.valueMap.get(o);if(T instanceof Tf){let f=T,S=n.selectors.get(o)??n.readonlySelectors.get(o);if(S)f.use(S.get());return}if(n.operation.open)n.operation.prev.set(o,T);n.valueMap.delete(o),n.logger.info("\uD83D\uDDD1","state",o,"evicted")};var kF=(o,n)=>{return C(o).atomsThatAreDefault.has(n)},SS=(o,n)=>{let T=C(o);T.atomsThatAreDefault=new Set(T.atomsThatAreDefault).add(n)},WF=(o,n)=>{let T=C(o);T.atomsThatAreDefault=new Set(C(o).atomsThatAreDefault),T.atomsThatAreDefault.delete(n)};function Fn(o,n,T){o.logger.info("\uD83D\uDD28","atom",n.key,`creating in store "${o.config.name}"`);let f=C(o),S=f.atoms.get(n.key);if(S&&S.type==="atom")return o.logger.error("\u274C","atom",n.key,"Tried to create atom, but it already exists in the store."),fn(S);let A=new oo,$={...n,type:"atom",install:(t)=>{return t.logger.info("\uD83D\uDEE0\uFE0F","atom",n.key,`installing in store "${t.config.name}"`),Fn(t,n,T)},subject:A};if(T)$.family=T;let F=n.default;if(n.default instanceof Function)F=n.default();f.atoms.set($.key,$),SS(o,n.key),yn(f,n.key,F,A);let J=fn($);if(n.effects){let t=0,R=[];for(let W of n.effects){let O=W({setSelf:(_)=>{Uo(o,J,_)},onSet:(_)=>lo(o,J,`effect[${t}]`,_)});if(O)R.push(O);++t}$.cleanup=()=>{for(let W of R)W()}}return J}function e$(o,n){if("mutable"in n){let S=Mf(o,n,void 0);return o.on.atomCreation.next(S),S}let f=Fn(o,n,void 0);return o.on.atomCreation.next(f),f}function MA(o,n){let T=C(o),{key:f,family:S}=n,A=$o(T,n);if(!S)o.logger.error("\u274C","atom",f,"Standalone atoms cannot be disposed.");else{A.cleanup?.();let $=o.valueMap.get(A.key),F=$o(o,{key:S.key,type:"atom_family"}),J={type:"state_disposal",subType:"atom",token:n,value:$};F.subject.next(J);let t=Ro(T);if(T.atoms.delete(f),T.valueMap.delete(f),T.selectorAtoms.delete(f),T.atomsThatAreDefault.delete(f),o.timelineTopics.delete(f),n.type==="mutable_atom"){let R=bn(n);MA(o,R),o.trackers.delete(f)}if(o.logger.info("\uD83D\uDD25","atom",f,"deleted"),t&&T.transactionMeta.phase==="building"){let R=T.transactionMeta.update.updates.at(-1);if(!(R?.type==="molecule_disposal"&&R.values.some(([_])=>_===A.family?.key)))T.transactionMeta.update.updates.push(J)}else o.on.atomDisposal.next(n)}}class No extends Set{mode="record";subject=new oo;cacheLimit=0;cache=[];cacheIdx=-1;cacheUpdateNumber=-1;constructor(o,n=0){super(o);if(o instanceof No)this.parent=o,this.cacheUpdateNumber=o.cacheUpdateNumber;if(n)this.cacheLimit=n,this.cache=new Array(n),this.subscribe("auto cache",(T)=>{this.cacheIdx++,this.cacheIdx%=this.cacheLimit,this.cache[this.cacheIdx]=T})}toJSON(){return{members:[...this],cache:this.cache,cacheLimit:this.cacheLimit,cacheIdx:this.cacheIdx,cacheUpdateNumber:this.cacheUpdateNumber}}static fromJSON(o){let n=new No(o.members,o.cacheLimit);return n.cache=o.cache,n.cacheIdx=o.cacheIdx,n.cacheUpdateNumber=o.cacheUpdateNumber,n}add(o){let n=super.add(o);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`add:${To(o)}`);return n}clear(){let o=this.mode==="record"?[...this]:null;if(super.clear(),o)this.cacheUpdateNumber++,this.emit(`clear:${JSON.stringify(o)}`)}delete(o){let n=super.delete(o);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`del:${To(o)}`);return n}parent;child=null;transactionUpdates=null;transaction(o){this.mode="transaction",this.transactionUpdates=[],this.child=new No(this);let n=this.child._subscribe("transaction",(T)=>{this.transactionUpdates?.push(T)});try{if(o(this.child)){for(let f of this.transactionUpdates)this.doStep(f);this.cacheUpdateNumber++,this.emit(`tx:${this.transactionUpdates.join(";")}`)}}catch(T){throw console.warn("Did not apply transaction to SetRTX; this error was thrown:",T),T}finally{n(),this.child=null,this.transactionUpdates=null,this.mode="record"}}_subscribe(o,n){return this.subject.subscribe(o,n)}subscribe(o,n){return this.subject.subscribe(o,(T)=>{n(`${this.cacheUpdateNumber}=${T}`)})}emit(o){this.subject.next(o)}doStep(o){let n=o.indexOf(":"),T=o.substring(0,n),f=o.substring(n+1);switch(T){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 S of f.split(";"))this.doStep(S)}}getUpdateNumber(o){let n=o.indexOf("=");return Number(o.substring(0,n))}do(o){let n=o.indexOf("="),T=Number(o.substring(0,n)),f=T-this.cacheUpdateNumber;if(f>0){if(f===1){this.mode="playback";let A=o.substring(n+1);return this.doStep(A),this.mode="record",this.cacheUpdateNumber=T,null}return this.cacheUpdateNumber+1}if(Math.abs(f)<this.cacheLimit){let A=this.cacheIdx+f;if(this.cache[A]===o)return null;this.mode="playback";let F=!1;while(!F){this.cacheIdx%=this.cacheLimit;let t=this.cache[this.cacheIdx];if(this.cacheIdx--,!t)return"OUT_OF_RANGE";this.undo(t),F=this.cacheIdx===A-1}let J=o.substring(n+1);return this.doStep(J),this.mode="record",this.cacheUpdateNumber=T,null}return"OUT_OF_RANGE"}undoStep(o){let n=o.indexOf(":"),T=o.substring(0,n),f=o.substring(n+1);switch(T){case"add":this.delete(JSON.parse(f));break;case"del":this.add(JSON.parse(f));break;case"clear":{let S=JSON.parse(f);for(let A of S)this.add(A);break}case"tx":{let S=f.split(";");for(let A=S.length-1;A>=0;A--)this.undoStep(S[A])}}}undo(o){let n=o.indexOf("=");if(Number(o.substring(0,n))===this.cacheUpdateNumber){this.mode="playback";let f=o.substring(n+1);return this.undoStep(f),this.mode="record",this.cacheUpdateNumber--,null}return this.cacheUpdateNumber}}class $f{toolkit;options;defaultContent;molecules=new Map;relations;states;core;transact(o,n){let T=this.toolkit;this.toolkit=o,n(this),this.toolkit=T}store;realm;[Symbol.dispose](){}constructor(o,n,T=fo.STORE){this.store=T,this.realm=new AA(T),this.options=o,this.defaultContent=n,this.store.miscResources.set(`join:${o.key}`,this),this.realm.allocate("root",o.key),this.toolkit={get:(...E)=>to(T,...E),set:(...E)=>{Uo(T,...E)},find:(...E)=>i(T,...E),json:(E)=>Io(T,E)};let f=o.between[0],S=o.between[1],A=ff(T,{key:`${o.key}/relatedKeys`,default:()=>new No,mutable:!0,fromJson:(E)=>No.fromJSON(E),toJson:(E)=>E.toJSON()},["join","relations"]);this.core={relatedKeysAtoms:A};let $=({get:E},z)=>E(A,z),F=({set:E},z,U)=>{if(!this.store.molecules.has(To(z)))this.realm.allocate(o.key,z);E(A,z,(D)=>D.add(U)),E(A,U,(D)=>D.add(z))},J=({set:E},z,U)=>{E(A,z,(D)=>{return D.delete(U),D}),E(A,U,(D)=>{return D.delete(z),D})},t=(E,z,U)=>{let{find:D,get:v,set:l}=E,H=D(A,z),s=v(H);for(let q of s){if(U.includes(q))continue;l(A,q,(ko)=>{return ko.delete(z),ko})}l(H,(q)=>{return q.transaction((a)=>{a.clear();for(let ko of U){let Bo=$(E,ko),Tn=Bo.has(z);if(this.relations.cardinality==="1:n"){let In=[];for(let G of Bo){if(G===z)continue;let p=$(E,G);if(p.delete(ko),p.size===0)In.push(G)}if(!Tn&&Bo.size>0)Bo.clear();for(let G of In){let p=[ko,G].sort(),Fo=`"${p[0]}:${p[1]}"`;this.molecules.delete(Fo)}}if(!Tn)Bo.add(z);a.add(ko)}return!0}),q})},R=(E,z,U)=>{let{set:D}=E;D(A,z,(v)=>{return v.transaction((l)=>{for(let H of U)l.add(H);return!0}),v});for(let v of U)D(A,v,(l)=>{return l.add(z),l});return!0},W=(E,z,U)=>{let D=$(E,z);return U?D.has(U):D.size>0},O={getRelatedKeys:(E)=>$(this.toolkit,E),addRelation:(E,z)=>{this.store.moleculeJoins.set(E,o.key),this.store.moleculeJoins.set(z,o.key),F(this.toolkit,E,z)},deleteRelation:(E,z)=>{J(this.toolkit,E,z)},replaceRelationsSafely:(E,z)=>{t(this.toolkit,E,z)},replaceRelationsUnsafely:(E,z)=>{R(this.toolkit,E,z)},has:(E,z)=>W(this.toolkit,E,z)},_,Q;if(n){Q=Nn(T,{key:`${o.key}/content`,default:n},["join","content"]);let E=({get:D},v)=>D(Q,v),z=({set:D},v,l)=>{D(Q,v,l)};_=Object.assign(O,{getContent:(D)=>{return E(this.toolkit,D)},setContent:(D,v)=>{z(this.toolkit,D,v)},deleteContent:(D)=>{this.realm.deallocate(D)}})}else _=O;let K=new jo(o,{externalStore:_,isAType:o.isAType,isBType:o.isBType,makeContentKey:(...E)=>{let[z,U]=E,D=E.sort(),v=`${D[0]}:${D[1]}`,l=T.molecules.get(To(z)),H=T.molecules.get(To(U));if(!l)this.realm.allocate(o.key,z);if(!H)this.realm.allocate(o.key,U);return this.realm.allocate(z,v,"all"),this.realm.claim(U,v),this.store.moleculeJoins.set(v,o.key),v}}),B=()=>hn(T,{key:`${o.key}/singleRelatedKey`,get:(E)=>({get:z})=>{let U=z(A,E);for(let D of U)return D;return null}},["join","keys"]),h=()=>{return hn(T,{key:`${o.key}/multipleRelatedKeys`,get:(E)=>({get:z})=>{let U=_A(A,T);return z(U,E).members}},["join","keys"])},r=()=>hn(T,{key:`${o.key}/singleRelatedEntry`,get:(E)=>({get:z})=>{let U=z(A,E);for(let D of U){let v=K.isAType?.(E)?E:void 0,l=v===void 0?E:void 0;v??=D,l??=D;let H=K.makeContentKey(v,l),s=z(Q,H);return[D,s]}return null}},["join","entries"]),P=()=>hn(T,{key:`${o.key}/multipleRelatedEntries`,get:(E)=>({get:z})=>{let U=_A(A,T);return z(U,E).members.map((v)=>{let l=K.isAType?.(E)?E:void 0,H=l===void 0?E:void 0;l??=v,H??=v;let s=K.makeContentKey(l,H),q=z(Q,s);return[v,q]})}},["join","entries"]);switch(o.cardinality){case"1:1":{let E=B(),z=`${f}KeyOf${Mo(S)}`,U=`${S}KeyOf${Mo(f)}`,D={[z]:E,[U]:E},v;if(n){let l=r(),H=`${f}EntryOf${Mo(S)}`,s=`${S}EntryOf${Mo(f)}`,q={[H]:l,[s]:l};v=Object.assign(D,q)}else v=D;this.relations=K,this.states=v;break}case"1:n":{let E=B(),z=h(),U=`${f}KeyOf${Mo(S)}`,D=`${S}KeysOf${Mo(f)}`,v={[U]:E,[D]:z},l;if(n){let H=r(),s=P(),q=`${f}EntryOf${Mo(S)}`,a=`${S}EntriesOf${Mo(f)}`,ko={[q]:H,[a]:s};l=Object.assign(v,ko)}else l=v;this.relations=K,this.states=l;break}case"n:n":{let E=h(),z=`${f}KeysOf${Mo(S)}`,U=`${S}KeysOf${Mo(f)}`,D={[z]:E,[U]:E},v;if(n){let l=P(),H=`${f}EntriesOf${Mo(S)}`,s=`${S}EntriesOf${Mo(f)}`,q={[H]:l,[s]:l};v=Object.assign(D,q)}else v=D;this.relations=K,this.states=v}}}}function UT(o,n){let T=n.joins.get(o.key);if(T===void 0){let S=fo.STORE.joins.get(o.key);if(S===void 0)throw new Error(`Join "${o.key}" not found in store "${n.config.name}"`);T=new $f(S.options,S.defaultContent,n),n.joins.set(o.key,T)}return T}function Ff(o,n,T){let f=UT(o,T),S=C(T);if(Ro(S)){let{toolkit:A}=S.transactionMeta;f.transact(A,({relations:$})=>{n($)})}else n(f.relations)}function lf(o,n,T){let f=UT(o,T),S;switch(o.cardinality){case"1:1":{let A=`${o.a}KeyOf${Mo(o.b)}`,$=`${o.b}KeyOf${Mo(o.a)}`;S={get[A](){let J=f.states[A];return i(T,J,n)},get[$](){let J=f.states[$];return i(T,J,n)}};let F=`${o.a}EntryOf${Mo(o.b)}`;if(F in f.states){let J=`${o.b}EntryOf${Mo(o.a)}`;Object.assign(S,{get[F](){let t=f.states[F];return i(T,t,n)},get[J](){let t=f.states[J];return i(T,t,n)}})}break}case"1:n":{let A=`${o.a}KeyOf${Mo(o.b)}`,$=`${o.b}KeysOf${Mo(o.a)}`;S={get[A](){let J=f.states[A];return i(T,J,n)},get[$](){let J=f.states[$];return i(T,J,n)}};let F=`${o.a}EntryOf${Mo(o.b)}`;if(F in f.states){let J=`${o.b}EntriesOf${Mo(o.a)}`;Object.assign(S,{get[F](){let t=f.states[F];return i(T,t,n)},get[J](){let t=f.states[J];return i(T,t,n)}})}break}case"n:n":{let A=`${o.a}KeysOf${Mo(o.b)}`,$=`${o.b}KeysOf${Mo(o.a)}`;S={get[A](){let J=f.states[A];return i(T,J,n)},get[$](){let J=f.states[$];return i(T,J,n)}};let F=`${o.a}EntriesOf${Mo(o.b)}`;if(F in f.states){let J=`${o.b}EntriesOf${Mo(o.a)}`;Object.assign(S,{get[F](){let t=f.states[F];return i(T,t,n)},get[J](){let t=f.states[J];return i(T,t,n)}})}}}return S}function oF(o,n){return UT(o,n).core.relatedKeysAtoms}function gn(o){return o.startsWith("\uD83D\uDD0D ")}var XA=(o)=>{let n=Fn(o,{key:"\uD83D\uDD0D Atom Token Index (Internal)",default:()=>{let T=new Map;for(let[f,S]of o.atoms){if(gn(f))continue;let A=fn(S);if(S.family){let $=T.get(S.family.key);if(!$||!("familyMembers"in $))$={key:S.family.key,familyMembers:new Map},T.set(S.family.key,$);$.familyMembers.set(S.family.subKey,A)}else T.set(f,A)}return T},effects:[({setSelf:T})=>{o.on.atomCreation.subscribe("introspection",(f)=>{if(gn(f.key))return;T((S)=>{if(f.family){let{key:A,subKey:$}=f.family,F=S.get(A);if(F===void 0||!("familyMembers"in F))F={key:A,familyMembers:new Map},S.set(A,F);F.familyMembers.set($,f)}else S.set(f.key,f);return S})}),o.on.atomDisposal.subscribe("introspection",(f)=>{T((S)=>{if(f.family){let{key:A,subKey:$}=f.family,F=S.get(A);if(F&&"familyMembers"in F){if(F.familyMembers.delete($),F.familyMembers.size===0)S.delete(A)}}else S.delete(f.key);return S})})}]},void 0);return jn(o,{key:"\uD83D\uDD0D Atom Token Index",get:({get:T})=>T(n)})};var KA=(o)=>{let n=Fn(o,{key:"\uD83D\uDD0D Selector Token Index (Internal)",default:()=>{let T=new Map;for(let f of[o.readonlySelectors,o.selectors])for(let[S,A]of f){if(gn(S))continue;let $=fn(A);if(A.family){let F=T.get(A.family.key);if(!F||!("familyMembers"in F))F={key:A.family.key,familyMembers:new Map},T.set(A.family.key,F);F.familyMembers.set(A.family.subKey,$)}else T.set(S,$)}return T},effects:[({setSelf:T})=>{o.on.selectorCreation.subscribe("introspection",(f)=>{if(gn(f.key))return;T((S)=>{if(f.family){let{key:A,subKey:$}=f.family,F=S.get(A);if(F===void 0||!("familyMembers"in F))F={key:A,familyMembers:new Map},S.set(A,F);F.familyMembers.set($,f)}else S.set(f.key,f);return S})}),o.on.selectorDisposal.subscribe("introspection",(f)=>{T((S)=>{if(f.family){let{key:A,subKey:$}=f.family,F=S.get(A);if(F&&"familyMembers"in F){if(F.familyMembers.delete($),F.familyMembers.size===0)S.delete(A)}}else S.delete(f.key);return S})})}]},void 0);return jn(o,{key:"\uD83D\uDD0D Selector Token Index",get:({get:T})=>T(n)})};class AS{supported;constructor(o){this.supported=o}refine(o){for(let[n,T]of Object.entries(this.supported))try{if(T(o)===!0&&T!==Boolean)return{type:n,data:o}}catch(f){try{if(o instanceof T)return{type:n,data:o}}catch(S){}}return null}}var HA=new AS({number:(o)=>typeof o==="number",string:(o)=>typeof o==="string",boolean:(o)=>typeof o==="boolean",null:(o)=>o===null});function EA(o){if(!o)return!1;return Object.getPrototypeOf(o)===Object.prototype}var GA=new AS({object:EA,array:(o)=>Array.isArray(o)}),NM=new AS({...HA.supported,...GA.supported}),VT=(o)=>{if(o===void 0)return"undefined";let n=NM.refine(o);if(n)return n.type;return Object.getPrototypeOf(o).constructor.name};class bF{store;auditorCreatedAt=performance.now();statesCreatedAt=new Map;atomIndex;selectorIndex;disposed=!1;unsubscribeFromAtomCreation;unsubscribeFromAtomDisposal;unsubscribeFromSelectorCreation;unsubscribeFromSelectorDisposal;constructor(o=fo.STORE){this.store=o,this.atomIndex=XA(this.store),this.selectorIndex=KA(this.store),this.unsubscribeFromAtomCreation=this.store.on.atomCreation.subscribe(`auditor-${this.auditorCreatedAt}`,({key:n})=>{this.statesCreatedAt.set(n,performance.now()-this.auditorCreatedAt)}),this.unsubscribeFromAtomDisposal=this.store.on.atomDisposal.subscribe(`auditor-${this.auditorCreatedAt}`,({key:n})=>{this.statesCreatedAt.delete(n)}),this.unsubscribeFromSelectorCreation=this.store.on.selectorCreation.subscribe(`auditor-${this.auditorCreatedAt}`,({key:n})=>{this.statesCreatedAt.set(n,performance.now()-this.auditorCreatedAt)}),this.unsubscribeFromSelectorDisposal=this.store.on.selectorDisposal.subscribe(`auditor-${this.auditorCreatedAt}`,({key:n})=>{this.statesCreatedAt.delete(n)})}static DEFAULT_LIST_RESOURCES_PARAM={atomFamilies:!0,selectorFamilies:!0};listResources(o=bF.DEFAULT_LIST_RESOURCES_PARAM){if(this.disposed)throw new Error("This Auditor has been disposed");let n=TA(this.atomIndex),T=TA(this.selectorIndex),f=[...n.values()].filter((F)=>("familyMembers"in F)),S=[...T.values()].filter((F)=>("familyMembers"in F)),A=performance.now(),$=[];if(o.atomFamilies)for(let F of f){let J=F.familyMembers.values();for(let t of J){let W=this.statesCreatedAt.get(t.key)??this.auditorCreatedAt,O=A-W;$.push([t,O])}}if(o.selectorFamilies)for(let F of S){let J=F.familyMembers.values();for(let t of J){let W=this.statesCreatedAt.get(t.key)??this.auditorCreatedAt,O=A-W;$.push([t,O])}}return $}[Symbol.dispose](){this.unsubscribeFromAtomCreation(),this.unsubscribeFromAtomDisposal(),this.unsubscribeFromSelectorCreation(),this.unsubscribeFromSelectorDisposal(),this.disposed=!0}}var YA=(o,n)=>{let T=(f,S)=>{let $=((J,t)=>{let R=n(J,t);if(R)return R;return null})(f,S);if($?.jobComplete??$?.pathComplete)return $;let F=Array.isArray(S)?S.map((J,t)=>[t,J]):EA(S)?Object.entries(S):[];for(let[J,t]of F){let R=T([...f,J],t);if(R?.jobComplete)return R}return{}};T([],o)};function hM(o,n){return{summary:`${o<n?"+":"-"}${Math.abs(o-n)} (${o} \u2192 ${n})`}}function bM(o,n){return{summary:`${o.length<n.length?"+":"-"}${Math.abs(o.length-n.length)} ("${o}" \u2192 "${n}")`}}function xM(o,n){return{summary:`${o} \u2192 ${n}`}}function xF(o,n,T){let f="",S=[],A=[],$=[];return YA(o,(F,J)=>{let t;for(t of F){let R=n[t];if(R===void 0)A.push([t,JSON.stringify(J)]);else{let W=T(J,R);if(W.summary!=="No Change")$.push([t,W])}}}),YA(n,(F,J)=>{let t;for(t of F)if(o[t]===void 0)S.push([t,JSON.stringify(J)])}),f=`\uFF5E${$.length} \uFF0B${S.length} \uFF0D${A.length}`,{summary:f,added:S,removed:A,changed:$}}function vM(o,n,T){return xF(o,n,T)}class vF{leafRefinery;treeRefinery;leafDiffers;treeDiffers;constructor(o,n,T){this.leafRefinery=o,this.treeRefinery=n,this.leafDiffers={},this.treeDiffers={};for(let f of Object.keys(o.supported)){let S=T[f];this.leafDiffers[f]=S}for(let f of Object.keys(n.supported)){let S=T[f];this.treeDiffers[f]=S}}diff(o,n){if(o===n)return{summary:"No Change"};let T=this.leafRefinery.refine(o)??this.treeRefinery.refine(o),f=this.leafRefinery.refine(n)??this.treeRefinery.refine(n);if(T!==null&&f!==null){if(T.type===f.type){if(T.type in this.leafDiffers)return this.leafDiffers[T.type](T.data,f.data);if(T.type in this.treeDiffers)return this.treeDiffers[T.type](T.data,f.data,(F,J)=>this.diff(F,J))}}let S=VT(o),A=VT(n);if(S===A)return{summary:`${S} \u2192 ${A}`};return{summary:`Type change: ${S} \u2192 ${A}`}}}var nH=new vF(HA,GA,{number:hM,string:bM,boolean:xM,null:()=>({summary:"No Change"}),object:xF,array:vM});class rF extends Map{set(o,n){if(this.has(o))return console.warn("Tried to set a key that already exists in an InvariantMap",{key:o,value:n}),this;return super.set(o,n)}clear(){throw new Error("Cannot clear an InvariantMap")}}class $S{type="continuity";globals=[];actions=[];perspectives=[];key;constructor(o){this.key=o}static existing=new rF;static create(o,n){let T=new $S(o),{type:f,globals:S,actions:A,perspectives:$}=n(T),F={type:f,key:o,globals:S,actions:A,perspectives:$};return $S.existing.set(o,F),F}add(...o){switch(o[0].type){case"atom":case"mutable_atom":this.globals.push(...o);break;case"transaction":this.actions.push(...o);break;case"atom_family":case"mutable_atom_family":{let[T,f]=o;this.perspectives.push({type:"realtime_perspective",resourceAtoms:T,viewAtoms:f})}break}return this}}function RH(o){let{key:n,config:T}=o,f=$S.create(n,T),{actions:S}=f;for(let A of S)DF(fo.STORE,n,A.key);return GF(fo.STORE,n,-1),f}var WH=YT({key:"usersInRoomIndex",mutable:!0,default:()=>new No,toJson:(o)=>o.toJSON(),fromJson:(o)=>No.fromJSON(o)}),zA=YT({key:"roomIndex",default:()=>new No,mutable:!0,toJson:(o)=>o.toJSON(),fromJson:(o)=>No.fromJSON(o)}),rM={enteredAtEpoch:0},yf=df({key:"usersInRooms",between:["room","user"],cardinality:"1:n",isAType:(o)=>typeof o==="string",isBType:(o)=>typeof o==="string"},rM),OH=uf({key:"usersInMyRoomView",get:(o)=>({find:n})=>{let T=a$(yf);return[n(T,o)]}});import{spawn as qM}from"child_process";class mT{listeners;globalListeners;handleEvent(o,...n){for(let f of this.globalListeners)f(o,...n);let T=this.listeners.get(o);if(T)for(let f of T)f(...n)}id="no_id_retrieved";emit;constructor(o){this.emit=o,this.listeners=new Map,this.globalListeners=new Set}on(o,n){let T=this.listeners.get(o);if(T)T.add(n);else this.listeners.set(o,new Set([n]));return this}onAny(o){return this.globalListeners.add(o),this}off(o,n){let T=this.listeners.get(o);if(T)if(n)T.delete(n);else this.listeners.delete(o);return this}offAny(o){return this.globalListeners.delete(o),this}}class DA extends mT{incompleteData="";unprocessedEvents=[];incompleteLog="";unprocessedLogs=[];id="#####";process;key;logger;handleLog(o){if(Array.isArray(o)){let[n,...T]=o;switch(n){case"i":this.logger.info(...T);break;case"w":this.logger.warn(...T);break;case"e":this.logger.error(...T);break;default:return}}}constructor(o,n,T){super((f,...S)=>{let A=JSON.stringify([f,...S])+"\x03",$=(F)=>{if(F.code==="EPIPE")console.error("EPIPE error during write",this.process.stdin);this.process.stdin.removeListener("error",$)};return this.process.stdin.once("error",$),this.process.stdin.write(A),this});if(this.process=o,this.key=n,this.logger=T??{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 S=f.toString();if(S==="ALIVE")return;this.unprocessedEvents.push(...S.split("\x03"));let A=this.unprocessedEvents.shift();this.incompleteData+=A??"";try{if(this.incompleteData.startsWith("error"))console.log("\u2757",this.incompleteData);let $=xo(this.incompleteData);this.handleEvent(...$);while(this.unprocessedEvents.length>0){let F=this.unprocessedEvents.shift();if(F){if(this.unprocessedEvents.length===0)this.incompleteData=F;$=xo(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 S=f.toString();this.unprocessedLogs.push(...S.split("\x03"));let A=this.unprocessedLogs.shift();this.incompleteLog+=A??"";try{let $=xo(this.incompleteLog);this.handleLog($);while(this.unprocessedLogs.length>0)if(this.incompleteLog=this.unprocessedLogs.shift()??"",this.incompleteLog)$=xo(this.incompleteLog),this.handleLog($)}catch($){console.error("\u274C\u274C\u274C"),console.error(this.incompleteLog),console.error($),console.error("\u274C\u274C\u274C\uFE0F")}}),o.pid)this.id=o.pid.toString()}}class qF extends mT{in;out;id="no_id_retrieved";disposalFunctions=[];constructor(o){super((...n)=>{return this.out.next(n),this});this.id=o,this.in=new oo,this.out=new oo,this.in.subscribe("socket",(n)=>{this.handleEvent(...n)})}dispose(){for(let o of this.disposalFunctions)o()}}class QA extends mT{incompleteData="";unprocessedEvents=[];relays;relayServices;process;id="#####";log(...o){this.process.stderr.write(To(o.map((n)=>n instanceof No?`{ ${n.toJSON().members.join(" | ")} }`:n))+"\x03")}logger={info:(...o)=>{this.log("i",...o)},warn:(...o)=>{this.log("w",...o)},error:(...o)=>{this.log("e",...o)}};constructor(){super((o,...n)=>{let T=JSON.stringify([o,...n]);return this.process.stdout.write(T+"\x03"),this});if(this.process=process,this.process.stdin.resume(),this.relays=new Map,this.relayServices=[],this.process.stdin.on("data",(o)=>{let n=o.toString();this.unprocessedEvents.push(...n.split("\x03"));let T=this.unprocessedEvents.shift();this.incompleteData+=T??"";try{let f=xo(this.incompleteData);this.logger.info("\uD83C\uDFB0","received",f),this.handleEvent(...f);while(this.unprocessedEvents.length>0){let S=this.unprocessedEvents.shift();if(S){if(this.unprocessedEvents.length===0)this.incompleteData=S;let A=xo(S);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",(o)=>{this.logger.info("\uD83D\uDD25",this.id,`exited with code ${o}`)}),process.on("end",()=>{this.logger.info("\uD83D\uDD25",this.id,"ended"),process.exit(0)}),process.on("SIGTERM",()=>{this.logger.error("\uD83D\uDD25",this.id,"terminated"),process.exit(0)}),process.on("SIGINT",()=>{this.logger.error("\uD83D\uDD25",this.id,"interrupted"),process.exit(0)}),process.pid)this.id=process.pid?.toString();this.on("user-joins",(o)=>{this.logger.info("\uD83D\uDC64","user",o,"joined");let n=new qF(`user:${o}`);this.relays.set(o,n),this.logger.info("\uD83D\uDD17","attaching services:",`[${[...this.relayServices.keys()].join(", ")}]`);for(let T of this.relayServices){let f=T(n);if(f)n.disposalFunctions.push(f)}this.on(`user:${o}`,(...T)=>{n.in.next(T)}),n.out.subscribe("socket",(T)=>{this.emit(...T)})}),this.on("user-leaves",(o)=>{let n=this.relays.get(o);if(this.off(`relay:${o}`),n)n.dispose(),this.relays.delete(o)}),process.stdout.write("ALIVE")}relay(o){this.logger.info("\uD83D\uDD17","running relay method"),this.relayServices.push(o)}}var UA=fT({key:"roomArguments",default:["echo",["Hello World!"]]}),pF=uf({key:"room",get:(o)=>async({get:n,find:T})=>{let f=T(UA,o),S=n(f),[A,$]=S,F=await new Promise((J)=>{let t=qM(A,$,{env:process.env}),R=(W)=>{if(W.toString()==="ALIVE")t.stdout.off("data",R),J(t)};t.stdout.on("data",R)});return new DA(F,o)}});var pH=tf({key:"createRoom",do:({get:o,set:n,find:T},f,S,A)=>{let $=A?[S,A]:[S],F=T(UA,f);n(F,$),n(zA,(R)=>R.add(f));let J=T(pF,f);return o(J)}}),cH=tf({key:"joinRoom",do:(o,n,T,f)=>{let S={enteredAtEpoch:f};return Ff(yf,(A)=>{A.set({room:n,user:T},S)},o.env().store),S}}),ZH=tf({key:"leaveRoom",do:(o,n,T)=>{Ff(yf,(f)=>{f.delete({room:n,user:T})},o.env().store)}}),PH=tf({key:"destroyRoom",do:(o,n)=>{Ff(yf,(T)=>{T.delete({room:n})},o.env().store),o.set(zA,(T)=>(T.delete(n),T))}});function VA(o,n){return n.map((T)=>{switch(T.type){case"transaction_update":{let f=VA(o,T.updates);return{...T,updates:f}}case"atom_update":case"selector_update":case"molecule_creation":case"molecule_disposal":case"molecule_transfer":case"state_creation":case"state_disposal":return T}}).filter((T)=>{switch(T.type){case"atom_update":case"selector_update":return o.includes(T.key);case"state_creation":case"state_disposal":return o.includes(T.token.key);case"molecule_creation":case"transaction_update":case"molecule_disposal":case"molecule_transfer":return!0}})}var dH=fT({key:"redactor",default:{occlude:(o)=>o}}),BT=fT({key:"unacknowledgedUpdates",default:()=>[]});var cF=fT({key:"sockets",default:null}),sH=YT({key:"socketsIndex",mutable:!0,default:()=>new No,toJson:(o)=>o.toJSON(),fromJson:(o)=>No.fromJSON(o)}),aH=YT({key:"usersIndex",mutable:!0,default:()=>new No,toJson:(o)=>o.toJSON(),fromJson:(o)=>No.fromJSON(o)}),mA=df({key:"usersOfSockets",between:["user","socket"],cardinality:"1:1",isAType:(o)=>o.startsWith("user::"),isBType:(o)=>o.startsWith("socket::")});function ZF(o,n,T,f){let S=n.key;return function A(){let $=[];for(let J of n.globals){let t=J.type==="mutable_atom"?Io(o,J):J,R=to(o,t);$.push(t,R)}for(let J of n.perspectives){let{viewAtoms:t,resourceAtoms:R}=J,W=i(o,t,T),O=to(o,W);o.logger.info("\uD83D\uDC41","atom",R.key,`${T} can see`,{viewAtoms:t,resourceAtoms:R,userView:O});for(let _ of O){let Q=_.type==="mutable_atom"?Io(o,_):_,K=to(o,Q);$.push(Q,K)}}let F=qo(o)?o.transactionMeta.epoch.get(S)??null:null;f?.emit(`continuity-init:${S}`,F,$)}}function PF(o,n,T){let f=n.key;return function S(A){o.logger.info("\uD83D\uDECE\uFE0F","continuity",f,"received",A);let{key:$,id:F}=A,J=`tx-run:${$}:${F}`,t=`${J}:start`,R=`${J}:end`;performance.mark(t);try{DT(o,{type:"transaction",key:$},F)(...A.params)}catch(O){if(O instanceof Error)o.logger.error("\u274C","continuity",f,`failed to run transaction ${$} from ${T} with update ${F}`,O.message)}performance.mark(R);let W=performance.measure(J,t,R);o?.logger.info("\uD83D\uDE80","transaction",$,F,T,W.duration)}}function iF(o,n,T,f){let S=n.key;return function A($){if(o.logger.info("\uD83D\uDC4D","continuity",S,`${T} acknowledged epoch ${$}`),f[0]?.epoch===$)Uo(o,BT,T,(J)=>{return J.shift(),o.logger.info("\uD83D\uDC4D","continuity",S,`${T} unacknowledged update queue now has`,J.length,"items"),J})}}function gF(o,n,T,f){let S=n.key,A=[];for(let $ of n.actions){let F=WA(o,$,`sync-continuity:${S}:${T}`,(J)=>{try{let t=n.globals.map((O)=>{if(O.type==="atom")return O.key;return bn(O).key}).concat(n.perspectives.flatMap((O)=>{let{viewAtoms:_}=O,Q=i(o,_,T);return to(o,Q).map((B)=>{return B.type==="mutable_atom"?"*"+B.key:B.key})})),R=VA(t,J.updates),W={...J,updates:R};Uo(o,BT,T,(O)=>{if(W)O.push(W),O.sort((_,Q)=>_.epoch-Q.epoch),o.logger.info("\uD83D\uDC4D","continuity",S,`${T} unacknowledged update queue now has`,O.length,"items");return O}),f?.emit(`tx-new:${S}`,W)}catch(t){if(t instanceof Error)o.logger.error("\u274C","continuity",S,`${T} failed to send update from transaction ${$.key} to ${T}`,t.message)}});A.push(F)}return A}function dF(o,n,T,f){let S=n.key,A=[];for(let $ of n.perspectives){let{viewAtoms:F}=$,J=i(o,F,T),t=lo(o,J,`sync-continuity:${S}:${T}:perspective:${$.resourceAtoms.key}`,({oldValue:R,newValue:W})=>{let O=R.map((B)=>B.key),_=W.map((B)=>B.key),Q=R.filter((B)=>!_.includes(B.key)),K=W.filter((B)=>!O.includes(B.key)).flatMap((B)=>{let h=B.type==="mutable_atom"?Io(o,B):B,r=to(o,h);return[h,r]});if(o.logger.info("\uD83D\uDC41","atom",$.resourceAtoms.key,`${T} has a new perspective`,{oldKeys:O,newKeys:_,revealed:K,concealed:Q}),K.length>0)f?.emit(`reveal:${S}`,K);if(Q.length>0)f?.emit(`conceal:${S}`,Q)});A.push(t)}return A}function V8({socket:o,store:n=fo.STORE}){return function T(f){let S=o,A=f.key,$=lf(mA,`socket::${S.id}`,n).userKeyOfSocket,F=to(n,$);if(!F)return n.logger.error("\u274C","continuity",A,`Tried to create a synchronizer for a socket (${S.id}) that is not connected to a user.`),()=>{};let J=lf(mA,F,n).socketKeyOfUser,t=lo(n,J,`sync-continuity:${A}:${F}`,({newValue:h})=>{if(n.logger.info("\uD83D\uDC4B","continuity",A,`seeing ${F} on new socket ${h}`),h===null){n.logger.warn("\u274C","continuity",A,`User (${F}) is not connected to a socket, waiting for them to reappear.`);return}let r=i(n,cF,h);S=to(n,r);for(let E of R)S?.emit(`tx-new:${A}`,E)}),R=to(n,BT,F),W=[],O=dF(n,f,F,S),_=gF(n,f,F,S);W.push(...O,..._);let Q=ZF(n,f,F,o);S.off(`get:${A}`,Q),S.on(`get:${A}`,Q);let K=PF(n,f,F);S.off(`tx-run:${A}`,K),S.on(`tx-run:${A}`,K);let B=iF(n,f,F,R);return S?.on(`ack:${A}`,B),()=>{for(let h of W)h();S?.off(`ack:${A}`,B),S?.off(`get:${A}`,Q),S?.off(`tx-run:${A}`,K)}}}var{file:L0,serve:Sk}=globalThis.Bun;import{readFileSync as tJ}from"fs";import{resolve as NA}from"path";function pM(o,n){let T={},f=[];for(let S in o){let A=o[S],$=n[S],F=A["~standard"].validate($);if(F instanceof Promise)throw new Error(`Validation must be synchronous, but ${S} returned a Promise.`);if(F.issues){f.push(...F.issues.map((J)=>({...J,path:[S,...J.path??[]]})));continue}T[S]=F.value}if(f.length)return{issues:f};return{value:T}}function lF(o){let n=o.runtimeEnvStrict??o.runtimeEnv??process.env;if(o.emptyStringAsUndefined??!1){for(let[r,P]of Object.entries(n))if(P==="")delete n[r]}if(!!o.skipValidation)return n;let S=typeof o.client==="object"?o.client:{},A=typeof o.server==="object"?o.server:{},$=typeof o.shared==="object"?o.shared:{},F=o.isServer??(typeof window==="undefined"||("Deno"in window)),J=F?{...A,...$,...S}:{...S,...$},t=pM(J,n),R=o.onValidationError??((r)=>{throw console.error("\u274C Invalid environment variables:",r),new Error("Invalid environment variables")}),W=o.onInvalidAccess??(()=>{throw new Error("\u274C Attempted to access a server-side environment variable on the client")});if(t.issues)return R(t.issues);let O=(r)=>{if(!o.clientPrefix)return!0;return!r.startsWith(o.clientPrefix)&&!(r in $)},_=(r)=>{return F||!O(r)},Q=(r)=>{return r==="__esModule"||r==="$$typeof"},K=(o.extends??[]).reduce((r,P)=>{return Object.assign(r,P)},{}),B=Object.assign(t.value,K);return new Proxy(B,{get(r,P){if(typeof P!=="string")return;if(Q(P))return;if(!_(P))return W(P);return Reflect.get(r,P)}})}var Ao;(function(o){o.assertEqual=(S)=>S;function n(S){}o.assertIs=n;function T(S){throw new Error}o.assertNever=T,o.arrayToEnum=(S)=>{let A={};for(let $ of S)A[$]=$;return A},o.getValidEnumValues=(S)=>{let A=o.objectKeys(S).filter((F)=>typeof S[S[F]]!=="number"),$={};for(let F of A)$[F]=S[F];return o.objectValues($)},o.objectValues=(S)=>{return o.objectKeys(S).map(function(A){return S[A]})},o.objectKeys=typeof Object.keys==="function"?(S)=>Object.keys(S):(S)=>{let A=[];for(let $ in S)if(Object.prototype.hasOwnProperty.call(S,$))A.push($);return A},o.find=(S,A)=>{for(let $ of S)if(A($))return $;return},o.isInteger=typeof Number.isInteger==="function"?(S)=>Number.isInteger(S):(S)=>typeof S==="number"&&isFinite(S)&&Math.floor(S)===S;function f(S,A=" | "){return S.map(($)=>typeof $==="string"?`'${$}'`:$).join(A)}o.joinValues=f,o.jsonStringifyReplacer=(S,A)=>{if(typeof A==="bigint")return A.toString();return A}})(Ao||(Ao={}));var LA;(function(o){o.mergeShapes=(n,T)=>{return{...n,...T}}})(LA||(LA={}));var N=Ao.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),vn=(o)=>{switch(typeof o){case"undefined":return N.undefined;case"string":return N.string;case"number":return isNaN(o)?N.nan:N.number;case"boolean":return N.boolean;case"function":return N.function;case"bigint":return N.bigint;case"symbol":return N.symbol;case"object":if(Array.isArray(o))return N.array;if(o===null)return N.null;if(o.then&&typeof o.then==="function"&&o.catch&&typeof o.catch==="function")return N.promise;if(typeof Map!=="undefined"&&o instanceof Map)return N.map;if(typeof Set!=="undefined"&&o instanceof Set)return N.set;if(typeof Date!=="undefined"&&o instanceof Date)return N.date;return N.object;default:return N.unknown}},Y=Ao.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),cM=(o)=>{return JSON.stringify(o,null,2).replace(/"([^"]+)":/g,"$1:")};class Jn extends Error{get errors(){return this.issues}constructor(o){super();this.issues=[],this.addIssue=(T)=>{this.issues=[...this.issues,T]},this.addIssues=(T=[])=>{this.issues=[...this.issues,...T]};let n=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,n);else this.__proto__=n;this.name="ZodError",this.issues=o}format(o){let n=o||function(S){return S.message},T={_errors:[]},f=(S)=>{for(let A of S.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)T._errors.push(n(A));else{let $=T,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(n(A));$=$[J],F++}}};return f(this),T}static assert(o){if(!(o instanceof Jn))throw new Error(`Not a ZodError: ${o}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Ao.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(o=(n)=>n.message){let n={},T=[];for(let f of this.issues)if(f.path.length>0)n[f.path[0]]=n[f.path[0]]||[],n[f.path[0]].push(o(f));else T.push(o(f));return{formErrors:T,fieldErrors:n}}get formErrors(){return this.flatten()}}Jn.create=(o)=>{return new Jn(o)};var jT=(o,n)=>{let T;switch(o.code){case Y.invalid_type:if(o.received===N.undefined)T="Required";else T=`Expected ${o.expected}, received ${o.received}`;break;case Y.invalid_literal:T=`Invalid literal value, expected ${JSON.stringify(o.expected,Ao.jsonStringifyReplacer)}`;break;case Y.unrecognized_keys:T=`Unrecognized key(s) in object: ${Ao.joinValues(o.keys,", ")}`;break;case Y.invalid_union:T="Invalid input";break;case Y.invalid_union_discriminator:T=`Invalid discriminator value. Expected ${Ao.joinValues(o.options)}`;break;case Y.invalid_enum_value:T=`Invalid enum value. Expected ${Ao.joinValues(o.options)}, received '${o.received}'`;break;case Y.invalid_arguments:T="Invalid function arguments";break;case Y.invalid_return_type:T="Invalid function return type";break;case Y.invalid_date:T="Invalid date";break;case Y.invalid_string:if(typeof o.validation==="object")if("includes"in o.validation){if(T=`Invalid input: must include "${o.validation.includes}"`,typeof o.validation.position==="number")T=`${T} at one or more positions greater than or equal to ${o.validation.position}`}else if("startsWith"in o.validation)T=`Invalid input: must start with "${o.validation.startsWith}"`;else if("endsWith"in o.validation)T=`Invalid input: must end with "${o.validation.endsWith}"`;else Ao.assertNever(o.validation);else if(o.validation!=="regex")T=`Invalid ${o.validation}`;else T="Invalid";break;case Y.too_small:if(o.type==="array")T=`Array must contain ${o.exact?"exactly":o.inclusive?"at least":"more than"} ${o.minimum} element(s)`;else if(o.type==="string")T=`String must contain ${o.exact?"exactly":o.inclusive?"at least":"over"} ${o.minimum} character(s)`;else if(o.type==="number")T=`Number must be ${o.exact?"exactly equal to ":o.inclusive?"greater than or equal to ":"greater than "}${o.minimum}`;else if(o.type==="date")T=`Date must be ${o.exact?"exactly equal to ":o.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(o.minimum))}`;else T="Invalid input";break;case Y.too_big:if(o.type==="array")T=`Array must contain ${o.exact?"exactly":o.inclusive?"at most":"less than"} ${o.maximum} element(s)`;else if(o.type==="string")T=`String must contain ${o.exact?"exactly":o.inclusive?"at most":"under"} ${o.maximum} character(s)`;else if(o.type==="number")T=`Number must be ${o.exact?"exactly":o.inclusive?"less than or equal to":"less than"} ${o.maximum}`;else if(o.type==="bigint")T=`BigInt must be ${o.exact?"exactly":o.inclusive?"less than or equal to":"less than"} ${o.maximum}`;else if(o.type==="date")T=`Date must be ${o.exact?"exactly":o.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(o.maximum))}`;else T="Invalid input";break;case Y.custom:T="Invalid input";break;case Y.invalid_intersection_types:T="Intersection results could not be merged";break;case Y.not_multiple_of:T=`Number must be a multiple of ${o.multipleOf}`;break;case Y.not_finite:T="Number must be finite";break;default:T=n.defaultError,Ao.assertNever(o)}return{message:T}},aF=jT;function ZM(o){aF=o}function FS(){return aF}var JS=(o)=>{let{data:n,path:T,errorMaps:f,issueData:S}=o,A=[...T,...S.path||[]],$={...S,path:A};if(S.message!==void 0)return{...S,path:A,message:S.message};let F="",J=f.filter((t)=>!!t).slice().reverse();for(let t of J)F=t($,{data:n,defaultError:F}).message;return{...S,path:A,message:F}},PM=[];function L(o,n){let T=FS(),f=JS({issueData:n,data:o.data,path:o.path,errorMaps:[o.common.contextualErrorMap,o.schemaErrorMap,T,T===jT?void 0:jT].filter((S)=>!!S)});o.common.issues.push(f)}class uo{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(o,n){let T=[];for(let f of n){if(f.status==="aborted")return d;if(f.status==="dirty")o.dirty();T.push(f.value)}return{status:o.value,value:T}}static async mergeObjectAsync(o,n){let T=[];for(let f of n){let S=await f.key,A=await f.value;T.push({key:S,value:A})}return uo.mergeObjectSync(o,T)}static mergeObjectSync(o,n){let T={};for(let f of n){let{key:S,value:A}=f;if(S.status==="aborted")return d;if(A.status==="aborted")return d;if(S.status==="dirty")o.dirty();if(A.status==="dirty")o.dirty();if(S.value!=="__proto__"&&(typeof A.value!=="undefined"||f.alwaysSet))T[S.value]=A.value}return{status:o.value,value:T}}}var d=Object.freeze({status:"aborted"}),CT=(o)=>({status:"dirty",value:o}),ao=(o)=>({status:"valid",value:o}),CA=(o)=>o.status==="aborted",IA=(o)=>o.status==="dirty",tT=(o)=>o.status==="valid",Of=(o)=>typeof Promise!=="undefined"&&o instanceof Promise;function tS(o,n,T,f){if(T==="a"&&!f)throw new TypeError("Private accessor was defined without a getter");if(typeof n==="function"?o!==n||!f:!n.has(o))throw new TypeError("Cannot read private member from an object whose class did not declare it");return T==="m"?f:T==="a"?f.call(o):f?f.value:n.get(o)}function oJ(o,n,T,f,S){if(f==="m")throw new TypeError("Private method is not writable");if(f==="a"&&!S)throw new TypeError("Private accessor was defined without a setter");if(typeof n==="function"?o!==n||!S:!n.has(o))throw new TypeError("Cannot write private member to an object whose class did not declare it");return f==="a"?S.call(o,T):S?S.value=T:n.set(o,T),T}var x;(function(o){o.errToObj=(n)=>typeof n==="string"?{message:n}:n||{},o.toString=(n)=>typeof n==="string"?n:n===null||n===void 0?void 0:n.message})(x||(x={}));var kf,Wf;class Gn{constructor(o,n,T,f){this._cachedPath=[],this.parent=o,this.data=n,this._path=T,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 uF=(o,n)=>{if(tT(n))return{success:!0,data:n.value};else{if(!o.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let T=new Jn(o.common.issues);return this._error=T,this._error}}}};function u(o){if(!o)return{};let{errorMap:n,invalid_type_error:T,required_error:f,description:S}=o;if(n&&(T||f))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(n)return{errorMap:n,description:S};return{errorMap:($,F)=>{var J,t;let{message:R}=o;if($.code==="invalid_enum_value")return{message:R!==null&&R!==void 0?R:F.defaultError};if(typeof F.data==="undefined")return{message:(J=R!==null&&R!==void 0?R:f)!==null&&J!==void 0?J:F.defaultError};if($.code!=="invalid_type")return{message:F.defaultError};return{message:(t=R!==null&&R!==void 0?R:T)!==null&&t!==void 0?t:F.defaultError}},description:S}}class e{get description(){return this._def.description}_getType(o){return vn(o.data)}_getOrReturnCtx(o,n){return n||{common:o.parent.common,data:o.data,parsedType:vn(o.data),schemaErrorMap:this._def.errorMap,path:o.path,parent:o.parent}}_processInputParams(o){return{status:new uo,ctx:{common:o.parent.common,data:o.data,parsedType:vn(o.data),schemaErrorMap:this._def.errorMap,path:o.path,parent:o.parent}}}_parseSync(o){let n=this._parse(o);if(Of(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(o){let n=this._parse(o);return Promise.resolve(n)}parse(o,n){let T=this.safeParse(o,n);if(T.success)return T.data;throw T.error}safeParse(o,n){var T;let f={common:{issues:[],async:(T=n===null||n===void 0?void 0:n.async)!==null&&T!==void 0?T:!1,contextualErrorMap:n===null||n===void 0?void 0:n.errorMap},path:(n===null||n===void 0?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:o,parsedType:vn(o)},S=this._parseSync({data:o,path:f.path,parent:f});return uF(f,S)}"~validate"(o){var n,T;let f={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:o,parsedType:vn(o)};if(!this["~standard"].async)try{let S=this._parseSync({data:o,path:[],parent:f});return tT(S)?{value:S.value}:{issues:f.common.issues}}catch(S){if((T=(n=S===null||S===void 0?void 0:S.message)===null||n===void 0?void 0:n.toLowerCase())===null||T===void 0?void 0:T.includes("encountered"))this["~standard"].async=!0;f.common={issues:[],async:!0}}return this._parseAsync({data:o,path:[],parent:f}).then((S)=>tT(S)?{value:S.value}:{issues:f.common.issues})}async parseAsync(o,n){let T=await this.safeParseAsync(o,n);if(T.success)return T.data;throw T.error}async safeParseAsync(o,n){let T={common:{issues:[],contextualErrorMap:n===null||n===void 0?void 0:n.errorMap,async:!0},path:(n===null||n===void 0?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:o,parsedType:vn(o)},f=this._parse({data:o,path:T.path,parent:T}),S=await(Of(f)?f:Promise.resolve(f));return uF(T,S)}refine(o,n){let T=(f)=>{if(typeof n==="string"||typeof n==="undefined")return{message:n};else if(typeof n==="function")return n(f);else return n};return this._refinement((f,S)=>{let A=o(f),$=()=>S.addIssue({code:Y.custom,...T(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(o,n){return this._refinement((T,f)=>{if(!o(T))return f.addIssue(typeof n==="function"?n(T,f):n),!1;else return!0})}_refinement(o){return new Wn({schema:this,typeName:g.ZodEffects,effect:{type:"refinement",refinement:o}})}superRefine(o){return this._refinement(o)}constructor(o){this.spa=this.safeParseAsync,this._def=o,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:(n)=>this["~validate"](n)}}optional(){return En.create(this,this._def)}nullable(){return rn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Hn.create(this)}promise(){return kT.create(this,this._def)}or(o){return xT.create([this,o],this._def)}and(o){return vT.create(this,o,this._def)}transform(o){return new Wn({...u(this._def),schema:this,typeName:g.ZodEffects,effect:{type:"transform",transform:o}})}default(o){let n=typeof o==="function"?o:()=>o;return new cT({...u(this._def),innerType:this,defaultValue:n,typeName:g.ZodDefault})}brand(){return new MS({typeName:g.ZodBranded,type:this,...u(this._def)})}catch(o){let n=typeof o==="function"?o:()=>o;return new ZT({...u(this._def),innerType:this,catchValue:n,typeName:g.ZodCatch})}describe(o){return new this.constructor({...this._def,description:o})}pipe(o){return Ef.create(this,o)}readonly(){return PT.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var iM=/^c[^\s-]{8,}$/i,gM=/^[0-9a-z]+$/,dM=/^[0-9A-HJKMNP-TV-Z]{26}$/i,lM=/^[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,uM=/^[a-z0-9_-]{21}$/i,eM=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,sM=/^[-+]?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)?)??$/,aM=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,oy="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",BA,ny=/^(?:(?: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])$/,Ty=/^(?:(?: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])$/,fy=/^(([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]))$/,Sy=/^(([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])$/,Ay=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,$y=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nJ="((\\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])))",Fy=new RegExp(`^${nJ}$`);function TJ(o){let n="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";if(o.precision)n=`${n}\\.\\d{${o.precision}}`;else if(o.precision==null)n=`${n}(\\.\\d+)?`;return n}function Jy(o){return new RegExp(`^${TJ(o)}$`)}function fJ(o){let n=`${nJ}T${TJ(o)}`,T=[];if(T.push(o.local?"Z?":"Z"),o.offset)T.push("([+-]\\d{2}:?\\d{2})");return n=`${n}(${T.join("|")})`,new RegExp(`^${n}$`)}function ty(o,n){if((n==="v4"||!n)&&ny.test(o))return!0;if((n==="v6"||!n)&&fy.test(o))return!0;return!1}function Ry(o,n){if(!eM.test(o))return!1;try{let[T]=o.split("."),f=T.replace(/-/g,"+").replace(/_/g,"/").padEnd(T.length+(4-T.length%4)%4,"="),S=JSON.parse(atob(f));if(typeof S!=="object"||S===null)return!1;if(!S.typ||!S.alg)return!1;if(n&&S.alg!==n)return!1;return!0}catch(T){return!1}}function My(o,n){if((n==="v4"||!n)&&Ty.test(o))return!0;if((n==="v6"||!n)&&Sy.test(o))return!0;return!1}class Kn extends e{_parse(o){if(this._def.coerce)o.data=String(o.data);if(this._getType(o)!==N.string){let S=this._getOrReturnCtx(o);return L(S,{code:Y.invalid_type,expected:N.string,received:S.parsedType}),d}let T=new uo,f=void 0;for(let S of this._def.checks)if(S.kind==="min"){if(o.data.length<S.value)f=this._getOrReturnCtx(o,f),L(f,{code:Y.too_small,minimum:S.value,type:"string",inclusive:!0,exact:!1,message:S.message}),T.dirty()}else if(S.kind==="max"){if(o.data.length>S.value)f=this._getOrReturnCtx(o,f),L(f,{code:Y.too_big,maximum:S.value,type:"string",inclusive:!0,exact:!1,message:S.message}),T.dirty()}else if(S.kind==="length"){let A=o.data.length>S.value,$=o.data.length<S.value;if(A||$){if(f=this._getOrReturnCtx(o,f),A)L(f,{code:Y.too_big,maximum:S.value,type:"string",inclusive:!0,exact:!0,message:S.message});else if($)L(f,{code:Y.too_small,minimum:S.value,type:"string",inclusive:!0,exact:!0,message:S.message});T.dirty()}}else if(S.kind==="email"){if(!aM.test(o.data))f=this._getOrReturnCtx(o,f),L(f,{validation:"email",code:Y.invalid_string,message:S.message}),T.dirty()}else if(S.kind==="emoji"){if(!BA)BA=new RegExp(oy,"u");if(!BA.test(o.data))f=this._getOrReturnCtx(o,f),L(f,{validation:"emoji",code:Y.invalid_string,message:S.message}),T.dirty()}else if(S.kind==="uuid"){if(!lM.test(o.data))f=this._getOrReturnCtx(o,f),L(f,{validation:"uuid",code:Y.invalid_string,message:S.message}),T.dirty()}else if(S.kind==="nanoid"){if(!uM.test(o.data))f=this._getOrReturnCtx(o,f),L(f,{validation:"nanoid",code:Y.invalid_string,message:S.message}),T.dirty()}else if(S.kind==="cuid"){if(!iM.test(o.data))f=this._getOrReturnCtx(o,f),L(f,{validation:"cuid",code:Y.invalid_string,message:S.message}),T.dirty()}else if(S.kind==="cuid2"){if(!gM.test(o.data))f=this._getOrReturnCtx(o,f),L(f,{validation:"cuid2",code:Y.invalid_string,message:S.message}),T.dirty()}else if(S.kind==="ulid"){if(!dM.test(o.data))f=this._getOrReturnCtx(o,f),L(f,{validation:"ulid",code:Y.invalid_string,message:S.message}),T.dirty()}else if(S.kind==="url")try{new URL(o.data)}catch(A){f=this._getOrReturnCtx(o,f),L(f,{validation:"url",code:Y.invalid_string,message:S.message}),T.dirty()}else if(S.kind==="regex"){if(S.regex.lastIndex=0,!S.regex.test(o.data))f=this._getOrReturnCtx(o,f),L(f,{validation:"regex",code:Y.invalid_string,message:S.message}),T.dirty()}else if(S.kind==="trim")o.data=o.data.trim();else if(S.kind==="includes"){if(!o.data.includes(S.value,S.position))f=this._getOrReturnCtx(o,f),L(f,{code:Y.invalid_string,validation:{includes:S.value,position:S.position},message:S.message}),T.dirty()}else if(S.kind==="toLowerCase")o.data=o.data.toLowerCase();else if(S.kind==="toUpperCase")o.data=o.data.toUpperCase();else if(S.kind==="startsWith"){if(!o.data.startsWith(S.value))f=this._getOrReturnCtx(o,f),L(f,{code:Y.invalid_string,validation:{startsWith:S.value},message:S.message}),T.dirty()}else if(S.kind==="endsWith"){if(!o.data.endsWith(S.value))f=this._getOrReturnCtx(o,f),L(f,{code:Y.invalid_string,validation:{endsWith:S.value},message:S.message}),T.dirty()}else if(S.kind==="datetime"){if(!fJ(S).test(o.data))f=this._getOrReturnCtx(o,f),L(f,{code:Y.invalid_string,validation:"datetime",message:S.message}),T.dirty()}else if(S.kind==="date"){if(!Fy.test(o.data))f=this._getOrReturnCtx(o,f),L(f,{code:Y.invalid_string,validation:"date",message:S.message}),T.dirty()}else if(S.kind==="time"){if(!Jy(S).test(o.data))f=this._getOrReturnCtx(o,f),L(f,{code:Y.invalid_string,validation:"time",message:S.message}),T.dirty()}else if(S.kind==="duration"){if(!sM.test(o.data))f=this._getOrReturnCtx(o,f),L(f,{validation:"duration",code:Y.invalid_string,message:S.message}),T.dirty()}else if(S.kind==="ip"){if(!ty(o.data,S.version))f=this._getOrReturnCtx(o,f),L(f,{validation:"ip",code:Y.invalid_string,message:S.message}),T.dirty()}else if(S.kind==="jwt"){if(!Ry(o.data,S.alg))f=this._getOrReturnCtx(o,f),L(f,{validation:"jwt",code:Y.invalid_string,message:S.message}),T.dirty()}else if(S.kind==="cidr"){if(!My(o.data,S.version))f=this._getOrReturnCtx(o,f),L(f,{validation:"cidr",code:Y.invalid_string,message:S.message}),T.dirty()}else if(S.kind==="base64"){if(!Ay.test(o.data))f=this._getOrReturnCtx(o,f),L(f,{validation:"base64",code:Y.invalid_string,message:S.message}),T.dirty()}else if(S.kind==="base64url"){if(!$y.test(o.data))f=this._getOrReturnCtx(o,f),L(f,{validation:"base64url",code:Y.invalid_string,message:S.message}),T.dirty()}else Ao.assertNever(S);return{status:T.value,value:o.data}}_regex(o,n,T){return this.refinement((f)=>o.test(f),{validation:n,code:Y.invalid_string,...x.errToObj(T)})}_addCheck(o){return new Kn({...this._def,checks:[...this._def.checks,o]})}email(o){return this._addCheck({kind:"email",...x.errToObj(o)})}url(o){return this._addCheck({kind:"url",...x.errToObj(o)})}emoji(o){return this._addCheck({kind:"emoji",...x.errToObj(o)})}uuid(o){return this._addCheck({kind:"uuid",...x.errToObj(o)})}nanoid(o){return this._addCheck({kind:"nanoid",...x.errToObj(o)})}cuid(o){return this._addCheck({kind:"cuid",...x.errToObj(o)})}cuid2(o){return this._addCheck({kind:"cuid2",...x.errToObj(o)})}ulid(o){return this._addCheck({kind:"ulid",...x.errToObj(o)})}base64(o){return this._addCheck({kind:"base64",...x.errToObj(o)})}base64url(o){return this._addCheck({kind:"base64url",...x.errToObj(o)})}jwt(o){return this._addCheck({kind:"jwt",...x.errToObj(o)})}ip(o){return this._addCheck({kind:"ip",...x.errToObj(o)})}cidr(o){return this._addCheck({kind:"cidr",...x.errToObj(o)})}datetime(o){var n,T;if(typeof o==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:o});return this._addCheck({kind:"datetime",precision:typeof(o===null||o===void 0?void 0:o.precision)==="undefined"?null:o===null||o===void 0?void 0:o.precision,offset:(n=o===null||o===void 0?void 0:o.offset)!==null&&n!==void 0?n:!1,local:(T=o===null||o===void 0?void 0:o.local)!==null&&T!==void 0?T:!1,...x.errToObj(o===null||o===void 0?void 0:o.message)})}date(o){return this._addCheck({kind:"date",message:o})}time(o){if(typeof o==="string")return this._addCheck({kind:"time",precision:null,message:o});return this._addCheck({kind:"time",precision:typeof(o===null||o===void 0?void 0:o.precision)==="undefined"?null:o===null||o===void 0?void 0:o.precision,...x.errToObj(o===null||o===void 0?void 0:o.message)})}duration(o){return this._addCheck({kind:"duration",...x.errToObj(o)})}regex(o,n){return this._addCheck({kind:"regex",regex:o,...x.errToObj(n)})}includes(o,n){return this._addCheck({kind:"includes",value:o,position:n===null||n===void 0?void 0:n.position,...x.errToObj(n===null||n===void 0?void 0:n.message)})}startsWith(o,n){return this._addCheck({kind:"startsWith",value:o,...x.errToObj(n)})}endsWith(o,n){return this._addCheck({kind:"endsWith",value:o,...x.errToObj(n)})}min(o,n){return this._addCheck({kind:"min",value:o,...x.errToObj(n)})}max(o,n){return this._addCheck({kind:"max",value:o,...x.errToObj(n)})}length(o,n){return this._addCheck({kind:"length",value:o,...x.errToObj(n)})}nonempty(o){return this.min(1,x.errToObj(o))}trim(){return new Kn({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Kn({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Kn({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((o)=>o.kind==="datetime")}get isDate(){return!!this._def.checks.find((o)=>o.kind==="date")}get isTime(){return!!this._def.checks.find((o)=>o.kind==="time")}get isDuration(){return!!this._def.checks.find((o)=>o.kind==="duration")}get isEmail(){return!!this._def.checks.find((o)=>o.kind==="email")}get isURL(){return!!this._def.checks.find((o)=>o.kind==="url")}get isEmoji(){return!!this._def.checks.find((o)=>o.kind==="emoji")}get isUUID(){return!!this._def.checks.find((o)=>o.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((o)=>o.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((o)=>o.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((o)=>o.kind==="cuid2")}get isULID(){return!!this._def.checks.find((o)=>o.kind==="ulid")}get isIP(){return!!this._def.checks.find((o)=>o.kind==="ip")}get isCIDR(){return!!this._def.checks.find((o)=>o.kind==="cidr")}get isBase64(){return!!this._def.checks.find((o)=>o.kind==="base64")}get isBase64url(){return!!this._def.checks.find((o)=>o.kind==="base64url")}get minLength(){let o=null;for(let n of this._def.checks)if(n.kind==="min"){if(o===null||n.value>o)o=n.value}return o}get maxLength(){let o=null;for(let n of this._def.checks)if(n.kind==="max"){if(o===null||n.value<o)o=n.value}return o}}Kn.create=(o)=>{var n;return new Kn({checks:[],typeName:g.ZodString,coerce:(n=o===null||o===void 0?void 0:o.coerce)!==null&&n!==void 0?n:!1,...u(o)})};function yy(o,n){let T=(o.toString().split(".")[1]||"").length,f=(n.toString().split(".")[1]||"").length,S=T>f?T:f,A=parseInt(o.toFixed(S).replace(".","")),$=parseInt(n.toFixed(S).replace(".",""));return A%$/Math.pow(10,S)}class ln extends e{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(o){if(this._def.coerce)o.data=Number(o.data);if(this._getType(o)!==N.number){let S=this._getOrReturnCtx(o);return L(S,{code:Y.invalid_type,expected:N.number,received:S.parsedType}),d}let T=void 0,f=new uo;for(let S of this._def.checks)if(S.kind==="int"){if(!Ao.isInteger(o.data))T=this._getOrReturnCtx(o,T),L(T,{code:Y.invalid_type,expected:"integer",received:"float",message:S.message}),f.dirty()}else if(S.kind==="min"){if(S.inclusive?o.data<S.value:o.data<=S.value)T=this._getOrReturnCtx(o,T),L(T,{code:Y.too_small,minimum:S.value,type:"number",inclusive:S.inclusive,exact:!1,message:S.message}),f.dirty()}else if(S.kind==="max"){if(S.inclusive?o.data>S.value:o.data>=S.value)T=this._getOrReturnCtx(o,T),L(T,{code:Y.too_big,maximum:S.value,type:"number",inclusive:S.inclusive,exact:!1,message:S.message}),f.dirty()}else if(S.kind==="multipleOf"){if(yy(o.data,S.value)!==0)T=this._getOrReturnCtx(o,T),L(T,{code:Y.not_multiple_of,multipleOf:S.value,message:S.message}),f.dirty()}else if(S.kind==="finite"){if(!Number.isFinite(o.data))T=this._getOrReturnCtx(o,T),L(T,{code:Y.not_finite,message:S.message}),f.dirty()}else Ao.assertNever(S);return{status:f.value,value:o.data}}gte(o,n){return this.setLimit("min",o,!0,x.toString(n))}gt(o,n){return this.setLimit("min",o,!1,x.toString(n))}lte(o,n){return this.setLimit("max",o,!0,x.toString(n))}lt(o,n){return this.setLimit("max",o,!1,x.toString(n))}setLimit(o,n,T,f){return new ln({...this._def,checks:[...this._def.checks,{kind:o,value:n,inclusive:T,message:x.toString(f)}]})}_addCheck(o){return new ln({...this._def,checks:[...this._def.checks,o]})}int(o){return this._addCheck({kind:"int",message:x.toString(o)})}positive(o){return this._addCheck({kind:"min",value:0,inclusive:!1,message:x.toString(o)})}negative(o){return this._addCheck({kind:"max",value:0,inclusive:!1,message:x.toString(o)})}nonpositive(o){return this._addCheck({kind:"max",value:0,inclusive:!0,message:x.toString(o)})}nonnegative(o){return this._addCheck({kind:"min",value:0,inclusive:!0,message:x.toString(o)})}multipleOf(o,n){return this._addCheck({kind:"multipleOf",value:o,message:x.toString(n)})}finite(o){return this._addCheck({kind:"finite",message:x.toString(o)})}safe(o){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:x.toString(o)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:x.toString(o)})}get minValue(){let o=null;for(let n of this._def.checks)if(n.kind==="min"){if(o===null||n.value>o)o=n.value}return o}get maxValue(){let o=null;for(let n of this._def.checks)if(n.kind==="max"){if(o===null||n.value<o)o=n.value}return o}get isInt(){return!!this._def.checks.find((o)=>o.kind==="int"||o.kind==="multipleOf"&&Ao.isInteger(o.value))}get isFinite(){let o=null,n=null;for(let T of this._def.checks)if(T.kind==="finite"||T.kind==="int"||T.kind==="multipleOf")return!0;else if(T.kind==="min"){if(n===null||T.value>n)n=T.value}else if(T.kind==="max"){if(o===null||T.value<o)o=T.value}return Number.isFinite(n)&&Number.isFinite(o)}}ln.create=(o)=>{return new ln({checks:[],typeName:g.ZodNumber,coerce:(o===null||o===void 0?void 0:o.coerce)||!1,...u(o)})};class un extends e{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(o){if(this._def.coerce)try{o.data=BigInt(o.data)}catch(S){return this._getInvalidInput(o)}if(this._getType(o)!==N.bigint)return this._getInvalidInput(o);let T=void 0,f=new uo;for(let S of this._def.checks)if(S.kind==="min"){if(S.inclusive?o.data<S.value:o.data<=S.value)T=this._getOrReturnCtx(o,T),L(T,{code:Y.too_small,type:"bigint",minimum:S.value,inclusive:S.inclusive,message:S.message}),f.dirty()}else if(S.kind==="max"){if(S.inclusive?o.data>S.value:o.data>=S.value)T=this._getOrReturnCtx(o,T),L(T,{code:Y.too_big,type:"bigint",maximum:S.value,inclusive:S.inclusive,message:S.message}),f.dirty()}else if(S.kind==="multipleOf"){if(o.data%S.value!==BigInt(0))T=this._getOrReturnCtx(o,T),L(T,{code:Y.not_multiple_of,multipleOf:S.value,message:S.message}),f.dirty()}else Ao.assertNever(S);return{status:f.value,value:o.data}}_getInvalidInput(o){let n=this._getOrReturnCtx(o);return L(n,{code:Y.invalid_type,expected:N.bigint,received:n.parsedType}),d}gte(o,n){return this.setLimit("min",o,!0,x.toString(n))}gt(o,n){return this.setLimit("min",o,!1,x.toString(n))}lte(o,n){return this.setLimit("max",o,!0,x.toString(n))}lt(o,n){return this.setLimit("max",o,!1,x.toString(n))}setLimit(o,n,T,f){return new un({...this._def,checks:[...this._def.checks,{kind:o,value:n,inclusive:T,message:x.toString(f)}]})}_addCheck(o){return new un({...this._def,checks:[...this._def.checks,o]})}positive(o){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:x.toString(o)})}negative(o){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:x.toString(o)})}nonpositive(o){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:x.toString(o)})}nonnegative(o){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:x.toString(o)})}multipleOf(o,n){return this._addCheck({kind:"multipleOf",value:o,message:x.toString(n)})}get minValue(){let o=null;for(let n of this._def.checks)if(n.kind==="min"){if(o===null||n.value>o)o=n.value}return o}get maxValue(){let o=null;for(let n of this._def.checks)if(n.kind==="max"){if(o===null||n.value<o)o=n.value}return o}}un.create=(o)=>{var n;return new un({checks:[],typeName:g.ZodBigInt,coerce:(n=o===null||o===void 0?void 0:o.coerce)!==null&&n!==void 0?n:!1,...u(o)})};class NT extends e{_parse(o){if(this._def.coerce)o.data=Boolean(o.data);if(this._getType(o)!==N.boolean){let T=this._getOrReturnCtx(o);return L(T,{code:Y.invalid_type,expected:N.boolean,received:T.parsedType}),d}return ao(o.data)}}NT.create=(o)=>{return new NT({typeName:g.ZodBoolean,coerce:(o===null||o===void 0?void 0:o.coerce)||!1,...u(o)})};class RT extends e{_parse(o){if(this._def.coerce)o.data=new Date(o.data);if(this._getType(o)!==N.date){let S=this._getOrReturnCtx(o);return L(S,{code:Y.invalid_type,expected:N.date,received:S.parsedType}),d}if(isNaN(o.data.getTime())){let S=this._getOrReturnCtx(o);return L(S,{code:Y.invalid_date}),d}let T=new uo,f=void 0;for(let S of this._def.checks)if(S.kind==="min"){if(o.data.getTime()<S.value)f=this._getOrReturnCtx(o,f),L(f,{code:Y.too_small,message:S.message,inclusive:!0,exact:!1,minimum:S.value,type:"date"}),T.dirty()}else if(S.kind==="max"){if(o.data.getTime()>S.value)f=this._getOrReturnCtx(o,f),L(f,{code:Y.too_big,message:S.message,inclusive:!0,exact:!1,maximum:S.value,type:"date"}),T.dirty()}else Ao.assertNever(S);return{status:T.value,value:new Date(o.data.getTime())}}_addCheck(o){return new RT({...this._def,checks:[...this._def.checks,o]})}min(o,n){return this._addCheck({kind:"min",value:o.getTime(),message:x.toString(n)})}max(o,n){return this._addCheck({kind:"max",value:o.getTime(),message:x.toString(n)})}get minDate(){let o=null;for(let n of this._def.checks)if(n.kind==="min"){if(o===null||n.value>o)o=n.value}return o!=null?new Date(o):null}get maxDate(){let o=null;for(let n of this._def.checks)if(n.kind==="max"){if(o===null||n.value<o)o=n.value}return o!=null?new Date(o):null}}RT.create=(o)=>{return new RT({checks:[],coerce:(o===null||o===void 0?void 0:o.coerce)||!1,typeName:g.ZodDate,...u(o)})};class wf extends e{_parse(o){if(this._getType(o)!==N.symbol){let T=this._getOrReturnCtx(o);return L(T,{code:Y.invalid_type,expected:N.symbol,received:T.parsedType}),d}return ao(o.data)}}wf.create=(o)=>{return new wf({typeName:g.ZodSymbol,...u(o)})};class hT extends e{_parse(o){if(this._getType(o)!==N.undefined){let T=this._getOrReturnCtx(o);return L(T,{code:Y.invalid_type,expected:N.undefined,received:T.parsedType}),d}return ao(o.data)}}hT.create=(o)=>{return new hT({typeName:g.ZodUndefined,...u(o)})};class bT extends e{_parse(o){if(this._getType(o)!==N.null){let T=this._getOrReturnCtx(o);return L(T,{code:Y.invalid_type,expected:N.null,received:T.parsedType}),d}return ao(o.data)}}bT.create=(o)=>{return new bT({typeName:g.ZodNull,...u(o)})};class MT extends e{constructor(){super(...arguments);this._any=!0}_parse(o){return ao(o.data)}}MT.create=(o)=>{return new MT({typeName:g.ZodAny,...u(o)})};class dn extends e{constructor(){super(...arguments);this._unknown=!0}_parse(o){return ao(o.data)}}dn.create=(o)=>{return new dn({typeName:g.ZodUnknown,...u(o)})};class mn extends e{_parse(o){let n=this._getOrReturnCtx(o);return L(n,{code:Y.invalid_type,expected:N.never,received:n.parsedType}),d}}mn.create=(o)=>{return new mn({typeName:g.ZodNever,...u(o)})};class _f extends e{_parse(o){if(this._getType(o)!==N.undefined){let T=this._getOrReturnCtx(o);return L(T,{code:Y.invalid_type,expected:N.void,received:T.parsedType}),d}return ao(o.data)}}_f.create=(o)=>{return new _f({typeName:g.ZodVoid,...u(o)})};class Hn extends e{_parse(o){let{ctx:n,status:T}=this._processInputParams(o),f=this._def;if(n.parsedType!==N.array)return L(n,{code:Y.invalid_type,expected:N.array,received:n.parsedType}),d;if(f.exactLength!==null){let A=n.data.length>f.exactLength.value,$=n.data.length<f.exactLength.value;if(A||$)L(n,{code:A?Y.too_big:Y.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}),T.dirty()}if(f.minLength!==null){if(n.data.length<f.minLength.value)L(n,{code:Y.too_small,minimum:f.minLength.value,type:"array",inclusive:!0,exact:!1,message:f.minLength.message}),T.dirty()}if(f.maxLength!==null){if(n.data.length>f.maxLength.value)L(n,{code:Y.too_big,maximum:f.maxLength.value,type:"array",inclusive:!0,exact:!1,message:f.maxLength.message}),T.dirty()}if(n.common.async)return Promise.all([...n.data].map((A,$)=>{return f.type._parseAsync(new Gn(n,A,n.path,$))})).then((A)=>{return uo.mergeArray(T,A)});let S=[...n.data].map((A,$)=>{return f.type._parseSync(new Gn(n,A,n.path,$))});return uo.mergeArray(T,S)}get element(){return this._def.type}min(o,n){return new Hn({...this._def,minLength:{value:o,message:x.toString(n)}})}max(o,n){return new Hn({...this._def,maxLength:{value:o,message:x.toString(n)}})}length(o,n){return new Hn({...this._def,exactLength:{value:o,message:x.toString(n)}})}nonempty(o){return this.min(1,o)}}Hn.create=(o,n)=>{return new Hn({type:o,minLength:null,maxLength:null,exactLength:null,typeName:g.ZodArray,...u(n)})};function LT(o){if(o instanceof zo){let n={};for(let T in o.shape){let f=o.shape[T];n[T]=En.create(LT(f))}return new zo({...o._def,shape:()=>n})}else if(o instanceof Hn)return new Hn({...o._def,type:LT(o.element)});else if(o instanceof En)return En.create(LT(o.unwrap()));else if(o instanceof rn)return rn.create(LT(o.unwrap()));else if(o instanceof Bn)return Bn.create(o.items.map((n)=>LT(n)));else return o}class zo extends e{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let o=this._def.shape(),n=Ao.objectKeys(o);return this._cached={shape:o,keys:n}}_parse(o){if(this._getType(o)!==N.object){let J=this._getOrReturnCtx(o);return L(J,{code:Y.invalid_type,expected:N.object,received:J.parsedType}),d}let{status:T,ctx:f}=this._processInputParams(o),{shape:S,keys:A}=this._getCached(),$=[];if(!(this._def.catchall instanceof mn&&this._def.unknownKeys==="strip")){for(let J in f.data)if(!A.includes(J))$.push(J)}let F=[];for(let J of A){let t=S[J],R=f.data[J];F.push({key:{status:"valid",value:J},value:t._parse(new Gn(f,R,f.path,J)),alwaysSet:J in f.data})}if(this._def.catchall instanceof mn){let J=this._def.unknownKeys;if(J==="passthrough")for(let t of $)F.push({key:{status:"valid",value:t},value:{status:"valid",value:f.data[t]}});else if(J==="strict"){if($.length>0)L(f,{code:Y.unrecognized_keys,keys:$}),T.dirty()}else if(J==="strip");else throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let J=this._def.catchall;for(let t of $){let R=f.data[t];F.push({key:{status:"valid",value:t},value:J._parse(new Gn(f,R,f.path,t)),alwaysSet:t in f.data})}}if(f.common.async)return Promise.resolve().then(async()=>{let J=[];for(let t of F){let R=await t.key,W=await t.value;J.push({key:R,value:W,alwaysSet:t.alwaysSet})}return J}).then((J)=>{return uo.mergeObjectSync(T,J)});else return uo.mergeObjectSync(T,F)}get shape(){return this._def.shape()}strict(o){return x.errToObj,new zo({...this._def,unknownKeys:"strict",...o!==void 0?{errorMap:(n,T)=>{var f,S,A,$;let F=(A=(S=(f=this._def).errorMap)===null||S===void 0?void 0:S.call(f,n,T).message)!==null&&A!==void 0?A:T.defaultError;if(n.code==="unrecognized_keys")return{message:($=x.errToObj(o).message)!==null&&$!==void 0?$:F};return{message:F}}}:{}})}strip(){return new zo({...this._def,unknownKeys:"strip"})}passthrough(){return new zo({...this._def,unknownKeys:"passthrough"})}extend(o){return new zo({...this._def,shape:()=>({...this._def.shape(),...o})})}merge(o){return new zo({unknownKeys:o._def.unknownKeys,catchall:o._def.catchall,shape:()=>({...this._def.shape(),...o._def.shape()}),typeName:g.ZodObject})}setKey(o,n){return this.augment({[o]:n})}catchall(o){return new zo({...this._def,catchall:o})}pick(o){let n={};return Ao.objectKeys(o).forEach((T)=>{if(o[T]&&this.shape[T])n[T]=this.shape[T]}),new zo({...this._def,shape:()=>n})}omit(o){let n={};return Ao.objectKeys(this.shape).forEach((T)=>{if(!o[T])n[T]=this.shape[T]}),new zo({...this._def,shape:()=>n})}deepPartial(){return LT(this)}partial(o){let n={};return Ao.objectKeys(this.shape).forEach((T)=>{let f=this.shape[T];if(o&&!o[T])n[T]=f;else n[T]=f.optional()}),new zo({...this._def,shape:()=>n})}required(o){let n={};return Ao.objectKeys(this.shape).forEach((T)=>{if(o&&!o[T])n[T]=this.shape[T];else{let S=this.shape[T];while(S instanceof En)S=S._def.innerType;n[T]=S}}),new zo({...this._def,shape:()=>n})}keyof(){return SJ(Ao.objectKeys(this.shape))}}zo.create=(o,n)=>{return new zo({shape:()=>o,unknownKeys:"strip",catchall:mn.create(),typeName:g.ZodObject,...u(n)})};zo.strictCreate=(o,n)=>{return new zo({shape:()=>o,unknownKeys:"strict",catchall:mn.create(),typeName:g.ZodObject,...u(n)})};zo.lazycreate=(o,n)=>{return new zo({shape:o,unknownKeys:"strip",catchall:mn.create(),typeName:g.ZodObject,...u(n)})};class xT extends e{_parse(o){let{ctx:n}=this._processInputParams(o),T=this._def.options;function f(S){for(let $ of S)if($.result.status==="valid")return $.result;for(let $ of S)if($.result.status==="dirty")return n.common.issues.push(...$.ctx.common.issues),$.result;let A=S.map(($)=>new Jn($.ctx.common.issues));return L(n,{code:Y.invalid_union,unionErrors:A}),d}if(n.common.async)return Promise.all(T.map(async(S)=>{let A={...n,common:{...n.common,issues:[]},parent:null};return{result:await S._parseAsync({data:n.data,path:n.path,parent:A}),ctx:A}})).then(f);else{let S=void 0,A=[];for(let F of T){let J={...n,common:{...n.common,issues:[]},parent:null},t=F._parseSync({data:n.data,path:n.path,parent:J});if(t.status==="valid")return t;else if(t.status==="dirty"&&!S)S={result:t,ctx:J};if(J.common.issues.length)A.push(J.common.issues)}if(S)return n.common.issues.push(...S.ctx.common.issues),S.result;let $=A.map((F)=>new Jn(F));return L(n,{code:Y.invalid_union,unionErrors:$}),d}}get options(){return this._def.options}}xT.create=(o,n)=>{return new xT({options:o,typeName:g.ZodUnion,...u(n)})};var xn=(o)=>{if(o instanceof rT)return xn(o.schema);else if(o instanceof Wn)return xn(o.innerType());else if(o instanceof qT)return[o.value];else if(o instanceof en)return o.options;else if(o instanceof pT)return Ao.objectValues(o.enum);else if(o instanceof cT)return xn(o._def.innerType);else if(o instanceof hT)return[void 0];else if(o instanceof bT)return[null];else if(o instanceof En)return[void 0,...xn(o.unwrap())];else if(o instanceof rn)return[null,...xn(o.unwrap())];else if(o instanceof MS)return xn(o.unwrap());else if(o instanceof PT)return xn(o.unwrap());else if(o instanceof ZT)return xn(o._def.innerType);else return[]};class RS extends e{_parse(o){let{ctx:n}=this._processInputParams(o);if(n.parsedType!==N.object)return L(n,{code:Y.invalid_type,expected:N.object,received:n.parsedType}),d;let T=this.discriminator,f=n.data[T],S=this.optionsMap.get(f);if(!S)return L(n,{code:Y.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[T]}),d;if(n.common.async)return S._parseAsync({data:n.data,path:n.path,parent:n});else return S._parseSync({data:n.data,path:n.path,parent:n})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(o,n,T){let f=new Map;for(let S of n){let A=xn(S.shape[o]);if(!A.length)throw new Error(`A discriminator value for key \`${o}\` could not be extracted from all schema options`);for(let $ of A){if(f.has($))throw new Error(`Discriminator property ${String(o)} has duplicate value ${String($)}`);f.set($,S)}}return new RS({typeName:g.ZodDiscriminatedUnion,discriminator:o,options:n,optionsMap:f,...u(T)})}}function jA(o,n){let T=vn(o),f=vn(n);if(o===n)return{valid:!0,data:o};else if(T===N.object&&f===N.object){let S=Ao.objectKeys(n),A=Ao.objectKeys(o).filter((F)=>S.indexOf(F)!==-1),$={...o,...n};for(let F of A){let J=jA(o[F],n[F]);if(!J.valid)return{valid:!1};$[F]=J.data}return{valid:!0,data:$}}else if(T===N.array&&f===N.array){if(o.length!==n.length)return{valid:!1};let S=[];for(let A=0;A<o.length;A++){let $=o[A],F=n[A],J=jA($,F);if(!J.valid)return{valid:!1};S.push(J.data)}return{valid:!0,data:S}}else if(T===N.date&&f===N.date&&+o===+n)return{valid:!0,data:o};else return{valid:!1}}class vT extends e{_parse(o){let{status:n,ctx:T}=this._processInputParams(o),f=(S,A)=>{if(CA(S)||CA(A))return d;let $=jA(S.value,A.value);if(!$.valid)return L(T,{code:Y.invalid_intersection_types}),d;if(IA(S)||IA(A))n.dirty();return{status:n.value,value:$.data}};if(T.common.async)return Promise.all([this._def.left._parseAsync({data:T.data,path:T.path,parent:T}),this._def.right._parseAsync({data:T.data,path:T.path,parent:T})]).then(([S,A])=>f(S,A));else return f(this._def.left._parseSync({data:T.data,path:T.path,parent:T}),this._def.right._parseSync({data:T.data,path:T.path,parent:T}))}}vT.create=(o,n,T)=>{return new vT({left:o,right:n,typeName:g.ZodIntersection,...u(T)})};class Bn extends e{_parse(o){let{status:n,ctx:T}=this._processInputParams(o);if(T.parsedType!==N.array)return L(T,{code:Y.invalid_type,expected:N.array,received:T.parsedType}),d;if(T.data.length<this._def.items.length)return L(T,{code:Y.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),d;if(!this._def.rest&&T.data.length>this._def.items.length)L(T,{code:Y.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty();let S=[...T.data].map((A,$)=>{let F=this._def.items[$]||this._def.rest;if(!F)return null;return F._parse(new Gn(T,A,T.path,$))}).filter((A)=>!!A);if(T.common.async)return Promise.all(S).then((A)=>{return uo.mergeArray(n,A)});else return uo.mergeArray(n,S)}get items(){return this._def.items}rest(o){return new Bn({...this._def,rest:o})}}Bn.create=(o,n)=>{if(!Array.isArray(o))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Bn({items:o,typeName:g.ZodTuple,rest:null,...u(n)})};class Xf extends e{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(o){let{status:n,ctx:T}=this._processInputParams(o);if(T.parsedType!==N.object)return L(T,{code:Y.invalid_type,expected:N.object,received:T.parsedType}),d;let f=[],S=this._def.keyType,A=this._def.valueType;for(let $ in T.data)f.push({key:S._parse(new Gn(T,$,T.path,$)),value:A._parse(new Gn(T,T.data[$],T.path,$)),alwaysSet:$ in T.data});if(T.common.async)return uo.mergeObjectAsync(n,f);else return uo.mergeObjectSync(n,f)}get element(){return this._def.valueType}static create(o,n,T){if(n instanceof e)return new Xf({keyType:o,valueType:n,typeName:g.ZodRecord,...u(T)});return new Xf({keyType:Kn.create(),valueType:o,typeName:g.ZodRecord,...u(n)})}}class Kf extends e{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(o){let{status:n,ctx:T}=this._processInputParams(o);if(T.parsedType!==N.map)return L(T,{code:Y.invalid_type,expected:N.map,received:T.parsedType}),d;let f=this._def.keyType,S=this._def.valueType,A=[...T.data.entries()].map(([$,F],J)=>{return{key:f._parse(new Gn(T,$,T.path,[J,"key"])),value:S._parse(new Gn(T,F,T.path,[J,"value"]))}});if(T.common.async){let $=new Map;return Promise.resolve().then(async()=>{for(let F of A){let J=await F.key,t=await F.value;if(J.status==="aborted"||t.status==="aborted")return d;if(J.status==="dirty"||t.status==="dirty")n.dirty();$.set(J.value,t.value)}return{status:n.value,value:$}})}else{let $=new Map;for(let F of A){let{key:J,value:t}=F;if(J.status==="aborted"||t.status==="aborted")return d;if(J.status==="dirty"||t.status==="dirty")n.dirty();$.set(J.value,t.value)}return{status:n.value,value:$}}}}Kf.create=(o,n,T)=>{return new Kf({valueType:n,keyType:o,typeName:g.ZodMap,...u(T)})};class yT extends e{_parse(o){let{status:n,ctx:T}=this._processInputParams(o);if(T.parsedType!==N.set)return L(T,{code:Y.invalid_type,expected:N.set,received:T.parsedType}),d;let f=this._def;if(f.minSize!==null){if(T.data.size<f.minSize.value)L(T,{code:Y.too_small,minimum:f.minSize.value,type:"set",inclusive:!0,exact:!1,message:f.minSize.message}),n.dirty()}if(f.maxSize!==null){if(T.data.size>f.maxSize.value)L(T,{code:Y.too_big,maximum:f.maxSize.value,type:"set",inclusive:!0,exact:!1,message:f.maxSize.message}),n.dirty()}let S=this._def.valueType;function A(F){let J=new Set;for(let t of F){if(t.status==="aborted")return d;if(t.status==="dirty")n.dirty();J.add(t.value)}return{status:n.value,value:J}}let $=[...T.data.values()].map((F,J)=>S._parse(new Gn(T,F,T.path,J)));if(T.common.async)return Promise.all($).then((F)=>A(F));else return A($)}min(o,n){return new yT({...this._def,minSize:{value:o,message:x.toString(n)}})}max(o,n){return new yT({...this._def,maxSize:{value:o,message:x.toString(n)}})}size(o,n){return this.min(o,n).max(o,n)}nonempty(o){return this.min(1,o)}}yT.create=(o,n)=>{return new yT({valueType:o,minSize:null,maxSize:null,typeName:g.ZodSet,...u(n)})};class IT extends e{constructor(){super(...arguments);this.validate=this.implement}_parse(o){let{ctx:n}=this._processInputParams(o);if(n.parsedType!==N.function)return L(n,{code:Y.invalid_type,expected:N.function,received:n.parsedType}),d;function T($,F){return JS({data:$,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,FS(),jT].filter((J)=>!!J),issueData:{code:Y.invalid_arguments,argumentsError:F}})}function f($,F){return JS({data:$,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,FS(),jT].filter((J)=>!!J),issueData:{code:Y.invalid_return_type,returnTypeError:F}})}let S={errorMap:n.common.contextualErrorMap},A=n.data;if(this._def.returns instanceof kT){let $=this;return ao(async function(...F){let J=new Jn([]),t=await $._def.args.parseAsync(F,S).catch((O)=>{throw J.addIssue(T(F,O)),J}),R=await Reflect.apply(A,this,t);return await $._def.returns._def.type.parseAsync(R,S).catch((O)=>{throw J.addIssue(f(R,O)),J})})}else{let $=this;return ao(function(...F){let J=$._def.args.safeParse(F,S);if(!J.success)throw new Jn([T(F,J.error)]);let t=Reflect.apply(A,this,J.data),R=$._def.returns.safeParse(t,S);if(!R.success)throw new Jn([f(t,R.error)]);return R.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...o){return new IT({...this._def,args:Bn.create(o).rest(dn.create())})}returns(o){return new IT({...this._def,returns:o})}implement(o){return this.parse(o)}strictImplement(o){return this.parse(o)}static create(o,n,T){return new IT({args:o?o:Bn.create([]).rest(dn.create()),returns:n||dn.create(),typeName:g.ZodFunction,...u(T)})}}class rT extends e{get schema(){return this._def.getter()}_parse(o){let{ctx:n}=this._processInputParams(o);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}rT.create=(o,n)=>{return new rT({getter:o,typeName:g.ZodLazy,...u(n)})};class qT extends e{_parse(o){if(o.data!==this._def.value){let n=this._getOrReturnCtx(o);return L(n,{received:n.data,code:Y.invalid_literal,expected:this._def.value}),d}return{status:"valid",value:o.data}}get value(){return this._def.value}}qT.create=(o,n)=>{return new qT({value:o,typeName:g.ZodLiteral,...u(n)})};function SJ(o,n){return new en({values:o,typeName:g.ZodEnum,...u(n)})}class en extends e{constructor(){super(...arguments);kf.set(this,void 0)}_parse(o){if(typeof o.data!=="string"){let n=this._getOrReturnCtx(o),T=this._def.values;return L(n,{expected:Ao.joinValues(T),received:n.parsedType,code:Y.invalid_type}),d}if(!tS(this,kf,"f"))oJ(this,kf,new Set(this._def.values),"f");if(!tS(this,kf,"f").has(o.data)){let n=this._getOrReturnCtx(o),T=this._def.values;return L(n,{received:n.data,code:Y.invalid_enum_value,options:T}),d}return ao(o.data)}get options(){return this._def.values}get enum(){let o={};for(let n of this._def.values)o[n]=n;return o}get Values(){let o={};for(let n of this._def.values)o[n]=n;return o}get Enum(){let o={};for(let n of this._def.values)o[n]=n;return o}extract(o,n=this._def){return en.create(o,{...this._def,...n})}exclude(o,n=this._def){return en.create(this.options.filter((T)=>!o.includes(T)),{...this._def,...n})}}kf=new WeakMap;en.create=SJ;class pT extends e{constructor(){super(...arguments);Wf.set(this,void 0)}_parse(o){let n=Ao.getValidEnumValues(this._def.values),T=this._getOrReturnCtx(o);if(T.parsedType!==N.string&&T.parsedType!==N.number){let f=Ao.objectValues(n);return L(T,{expected:Ao.joinValues(f),received:T.parsedType,code:Y.invalid_type}),d}if(!tS(this,Wf,"f"))oJ(this,Wf,new Set(Ao.getValidEnumValues(this._def.values)),"f");if(!tS(this,Wf,"f").has(o.data)){let f=Ao.objectValues(n);return L(T,{received:T.data,code:Y.invalid_enum_value,options:f}),d}return ao(o.data)}get enum(){return this._def.values}}Wf=new WeakMap;pT.create=(o,n)=>{return new pT({values:o,typeName:g.ZodNativeEnum,...u(n)})};class kT extends e{unwrap(){return this._def.type}_parse(o){let{ctx:n}=this._processInputParams(o);if(n.parsedType!==N.promise&&n.common.async===!1)return L(n,{code:Y.invalid_type,expected:N.promise,received:n.parsedType}),d;let T=n.parsedType===N.promise?n.data:Promise.resolve(n.data);return ao(T.then((f)=>{return this._def.type.parseAsync(f,{path:n.path,errorMap:n.common.contextualErrorMap})}))}}kT.create=(o,n)=>{return new kT({type:o,typeName:g.ZodPromise,...u(n)})};class Wn extends e{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===g.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(o){let{status:n,ctx:T}=this._processInputParams(o),f=this._def.effect||null,S={addIssue:(A)=>{if(L(T,A),A.fatal)n.abort();else n.dirty()},get path(){return T.path}};if(S.addIssue=S.addIssue.bind(S),f.type==="preprocess"){let A=f.transform(T.data,S);if(T.common.async)return Promise.resolve(A).then(async($)=>{if(n.value==="aborted")return d;let F=await this._def.schema._parseAsync({data:$,path:T.path,parent:T});if(F.status==="aborted")return d;if(F.status==="dirty")return CT(F.value);if(n.value==="dirty")return CT(F.value);return F});else{if(n.value==="aborted")return d;let $=this._def.schema._parseSync({data:A,path:T.path,parent:T});if($.status==="aborted")return d;if($.status==="dirty")return CT($.value);if(n.value==="dirty")return CT($.value);return $}}if(f.type==="refinement"){let A=($)=>{let F=f.refinement($,S);if(T.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(T.common.async===!1){let $=this._def.schema._parseSync({data:T.data,path:T.path,parent:T});if($.status==="aborted")return d;if($.status==="dirty")n.dirty();return A($.value),{status:n.value,value:$.value}}else return this._def.schema._parseAsync({data:T.data,path:T.path,parent:T}).then(($)=>{if($.status==="aborted")return d;if($.status==="dirty")n.dirty();return A($.value).then(()=>{return{status:n.value,value:$.value}})})}if(f.type==="transform")if(T.common.async===!1){let A=this._def.schema._parseSync({data:T.data,path:T.path,parent:T});if(!tT(A))return A;let $=f.transform(A.value,S);if($ instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:$}}else return this._def.schema._parseAsync({data:T.data,path:T.path,parent:T}).then((A)=>{if(!tT(A))return A;return Promise.resolve(f.transform(A.value,S)).then(($)=>({status:n.value,value:$}))});Ao.assertNever(f)}}Wn.create=(o,n,T)=>{return new Wn({schema:o,typeName:g.ZodEffects,effect:n,...u(T)})};Wn.createWithPreprocess=(o,n,T)=>{return new Wn({schema:n,effect:{type:"preprocess",transform:o},typeName:g.ZodEffects,...u(T)})};class En extends e{_parse(o){if(this._getType(o)===N.undefined)return ao(void 0);return this._def.innerType._parse(o)}unwrap(){return this._def.innerType}}En.create=(o,n)=>{return new En({innerType:o,typeName:g.ZodOptional,...u(n)})};class rn extends e{_parse(o){if(this._getType(o)===N.null)return ao(null);return this._def.innerType._parse(o)}unwrap(){return this._def.innerType}}rn.create=(o,n)=>{return new rn({innerType:o,typeName:g.ZodNullable,...u(n)})};class cT extends e{_parse(o){let{ctx:n}=this._processInputParams(o),T=n.data;if(n.parsedType===N.undefined)T=this._def.defaultValue();return this._def.innerType._parse({data:T,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}cT.create=(o,n)=>{return new cT({innerType:o,typeName:g.ZodDefault,defaultValue:typeof n.default==="function"?n.default:()=>n.default,...u(n)})};class ZT extends e{_parse(o){let{ctx:n}=this._processInputParams(o),T={...n,common:{...n.common,issues:[]}},f=this._def.innerType._parse({data:T.data,path:T.path,parent:{...T}});if(Of(f))return f.then((S)=>{return{status:"valid",value:S.status==="valid"?S.value:this._def.catchValue({get error(){return new Jn(T.common.issues)},input:T.data})}});else return{status:"valid",value:f.status==="valid"?f.value:this._def.catchValue({get error(){return new Jn(T.common.issues)},input:T.data})}}removeCatch(){return this._def.innerType}}ZT.create=(o,n)=>{return new ZT({innerType:o,typeName:g.ZodCatch,catchValue:typeof n.catch==="function"?n.catch:()=>n.catch,...u(n)})};class Hf extends e{_parse(o){if(this._getType(o)!==N.nan){let T=this._getOrReturnCtx(o);return L(T,{code:Y.invalid_type,expected:N.nan,received:T.parsedType}),d}return{status:"valid",value:o.data}}}Hf.create=(o)=>{return new Hf({typeName:g.ZodNaN,...u(o)})};var ky=Symbol("zod_brand");class MS extends e{_parse(o){let{ctx:n}=this._processInputParams(o),T=n.data;return this._def.type._parse({data:T,path:n.path,parent:n})}unwrap(){return this._def.type}}class Ef extends e{_parse(o){let{status:n,ctx:T}=this._processInputParams(o);if(T.common.async)return(async()=>{let S=await this._def.in._parseAsync({data:T.data,path:T.path,parent:T});if(S.status==="aborted")return d;if(S.status==="dirty")return n.dirty(),CT(S.value);else return this._def.out._parseAsync({data:S.value,path:T.path,parent:T})})();else{let f=this._def.in._parseSync({data:T.data,path:T.path,parent:T});if(f.status==="aborted")return d;if(f.status==="dirty")return n.dirty(),{status:"dirty",value:f.value};else return this._def.out._parseSync({data:f.value,path:T.path,parent:T})}}static create(o,n){return new Ef({in:o,out:n,typeName:g.ZodPipeline})}}class PT extends e{_parse(o){let n=this._def.innerType._parse(o),T=(f)=>{if(tT(f))f.value=Object.freeze(f.value);return f};return Of(n)?n.then((f)=>T(f)):T(n)}unwrap(){return this._def.innerType}}PT.create=(o,n)=>{return new PT({innerType:o,typeName:g.ZodReadonly,...u(n)})};function eF(o,n){let T=typeof o==="function"?o(n):typeof o==="string"?{message:o}:o;return typeof T==="string"?{message:T}:T}function AJ(o,n={},T){if(o)return MT.create().superRefine((f,S)=>{var A,$;let F=o(f);if(F instanceof Promise)return F.then((J)=>{var t,R;if(!J){let W=eF(n,f),O=(R=(t=W.fatal)!==null&&t!==void 0?t:T)!==null&&R!==void 0?R:!0;S.addIssue({code:"custom",...W,fatal:O})}});if(!F){let J=eF(n,f),t=($=(A=J.fatal)!==null&&A!==void 0?A:T)!==null&&$!==void 0?$:!0;S.addIssue({code:"custom",...J,fatal:t})}return});return MT.create()}var Wy={object:zo.lazycreate},g;(function(o){o.ZodString="ZodString",o.ZodNumber="ZodNumber",o.ZodNaN="ZodNaN",o.ZodBigInt="ZodBigInt",o.ZodBoolean="ZodBoolean",o.ZodDate="ZodDate",o.ZodSymbol="ZodSymbol",o.ZodUndefined="ZodUndefined",o.ZodNull="ZodNull",o.ZodAny="ZodAny",o.ZodUnknown="ZodUnknown",o.ZodNever="ZodNever",o.ZodVoid="ZodVoid",o.ZodArray="ZodArray",o.ZodObject="ZodObject",o.ZodUnion="ZodUnion",o.ZodDiscriminatedUnion="ZodDiscriminatedUnion",o.ZodIntersection="ZodIntersection",o.ZodTuple="ZodTuple",o.ZodRecord="ZodRecord",o.ZodMap="ZodMap",o.ZodSet="ZodSet",o.ZodFunction="ZodFunction",o.ZodLazy="ZodLazy",o.ZodLiteral="ZodLiteral",o.ZodEnum="ZodEnum",o.ZodEffects="ZodEffects",o.ZodNativeEnum="ZodNativeEnum",o.ZodOptional="ZodOptional",o.ZodNullable="ZodNullable",o.ZodDefault="ZodDefault",o.ZodCatch="ZodCatch",o.ZodPromise="ZodPromise",o.ZodBranded="ZodBranded",o.ZodPipeline="ZodPipeline",o.ZodReadonly="ZodReadonly"})(g||(g={}));var Oy=(o,n={message:`Input not instance of ${o.name}`})=>AJ((T)=>T instanceof o,n),$J=Kn.create,FJ=ln.create,wy=Hf.create,_y=un.create,JJ=NT.create,Xy=RT.create,Ky=wf.create,Hy=hT.create,Ey=bT.create,Gy=MT.create,Yy=dn.create,zy=mn.create,Dy=_f.create,Qy=Hn.create,Uy=zo.create,Vy=zo.strictCreate,my=xT.create,By=RS.create,Ly=vT.create,Cy=Bn.create,Iy=Xf.create,jy=Kf.create,Ny=yT.create,hy=IT.create,by=rT.create,xy=qT.create,vy=en.create,ry=pT.create,qy=kT.create,sF=Wn.create,py=En.create,cy=rn.create,Zy=Wn.createWithPreprocess,Py=Ef.create,iy=()=>$J().optional(),gy=()=>FJ().optional(),dy=()=>JJ().optional(),ly={string:(o)=>Kn.create({...o,coerce:!0}),number:(o)=>ln.create({...o,coerce:!0}),boolean:(o)=>NT.create({...o,coerce:!0}),bigint:(o)=>un.create({...o,coerce:!0}),date:(o)=>RT.create({...o,coerce:!0})},uy=d,Eo=Object.freeze({__proto__:null,defaultErrorMap:jT,setErrorMap:ZM,getErrorMap:FS,makeIssue:JS,EMPTY_PATH:PM,addIssueToContext:L,ParseStatus:uo,INVALID:d,DIRTY:CT,OK:ao,isAborted:CA,isDirty:IA,isValid:tT,isAsync:Of,get util(){return Ao},get objectUtil(){return LA},ZodParsedType:N,getParsedType:vn,ZodType:e,datetimeRegex:fJ,ZodString:Kn,ZodNumber:ln,ZodBigInt:un,ZodBoolean:NT,ZodDate:RT,ZodSymbol:wf,ZodUndefined:hT,ZodNull:bT,ZodAny:MT,ZodUnknown:dn,ZodNever:mn,ZodVoid:_f,ZodArray:Hn,ZodObject:zo,ZodUnion:xT,ZodDiscriminatedUnion:RS,ZodIntersection:vT,ZodTuple:Bn,ZodRecord:Xf,ZodMap:Kf,ZodSet:yT,ZodFunction:IT,ZodLazy:rT,ZodLiteral:qT,ZodEnum:en,ZodNativeEnum:pT,ZodPromise:kT,ZodEffects:Wn,ZodTransformer:Wn,ZodOptional:En,ZodNullable:rn,ZodDefault:cT,ZodCatch:ZT,ZodNaN:Hf,BRAND:ky,ZodBranded:MS,ZodPipeline:Ef,ZodReadonly:PT,custom:AJ,Schema:e,ZodSchema:e,late:Wy,get ZodFirstPartyTypeKind(){return g},coerce:ly,any:Gy,array:Qy,bigint:_y,boolean:JJ,date:Xy,discriminatedUnion:By,effect:sF,enum:vy,function:hy,instanceof:Oy,intersection:Ly,lazy:by,literal:xy,map:jy,nan:wy,nativeEnum:ry,never:zy,null:Ey,nullable:cy,number:FJ,object:Uy,oboolean:dy,onumber:gy,optional:py,ostring:iy,pipeline:Py,preprocess:Zy,promise:qy,record:Iy,set:Ny,strictObject:Vy,string:$J,symbol:Ky,transformer:sF,tuple:Cy,undefined:Hy,union:my,unknown:Yy,void:Dy,NEVER:uy,ZodIssueCode:Y,quotelessJson:cM,ZodError:Jn});var ey="__vite_start_time"in globalThis,sy=typeof window!=="undefined",SE="vitest"in globalThis,Yn=lF({isServer:!ey&&!sy,server:{CI:Eo.string().transform((o)=>!0).optional(),POSTGRES_USER:Eo.string(),POSTGRES_PASSWORD:Eo.string(),POSTGRES_DATABASE:Eo.string(),POSTGRES_HOST:Eo.string(),POSTGRES_PORT:Eo.string().transform((o)=>Number.parseInt(o,10)),BACKEND_PORT:Eo.string().transform((o)=>Number.parseInt(o,10)),RUN_WORKERS_FROM_SOURCE:Eo.union([Eo.literal("true"),Eo.literal("false")]).optional().transform((o)=>o==="true"),FRONTEND_PORT:Eo.string().transform((o)=>Number.parseInt(o,10)),FRONTEND_ORIGINS:Eo.string().transform((o)=>JSON.parse(o)).pipe(Eo.array(Eo.string())),OPENAI_API_KEY:Eo.string().optional()},clientPrefix:"VITE_",client:{VITE_BACKEND_ORIGIN:Eo.string(),VITE_USE_SELF_SIGNED_CERTIFICATE:Eo.union([Eo.literal("true"),Eo.literal("false")]).optional().transform((o)=>o==="true")},runtimeEnv:import.meta.env,emptyStringAsUndefined:!0});var RJ=NA(import.meta.dirname,"../dev"),MJ=Yn.VITE_USE_SELF_SIGNED_CERTIFICATE?{cert:tJ(NA(RJ,"./cert.pem"),"utf-8"),key:tJ(NA(RJ,"./key.pem"),"utf-8")}:void 0;import ok from"path";var y=Symbol.for("drizzle:entityKind"),RE=Symbol.for("drizzle:hasOwnEntityKind");function X(o,n){if(!o||typeof o!=="object")return!1;if(o instanceof n)return!0;if(!Object.prototype.hasOwnProperty.call(n,y))throw new Error(`Class "${n.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 T=Object.getPrototypeOf(o).constructor;if(T)while(T){if(y in T&&T[y]===n[y])return!0;T=Object.getPrototypeOf(T)}return!1}class Wo{constructor(o,n){this.table=o,this.config=n,this.name=n.name,this.keyAsName=n.keyAsName,this.notNull=n.notNull,this.default=n.default,this.defaultFn=n.defaultFn,this.onUpdateFn=n.onUpdateFn,this.hasDefault=n.hasDefault,this.primary=n.primaryKey,this.isUnique=n.isUnique,this.uniqueName=n.uniqueName,this.uniqueType=n.uniqueType,this.dataType=n.dataType,this.columnType=n.columnType,this.generated=n.generated,this.generatedIdentity=n.generatedIdentity}static[y]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue(o){return o}mapToDriverValue(o){return o}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}class hA{static[y]="ColumnBuilder";config;constructor(o,n,T){this.config={name:o,keyAsName:o==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:n,columnType:T,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(o){return this.config.default=o,this.config.hasDefault=!0,this}$defaultFn(o){return this.config.defaultFn=o,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(o){return this.config.onUpdateFn=o,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(o){if(this.config.name!=="")return;this.config.name=o}}var zn=Symbol.for("drizzle:Name");class bA{static[y]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(o,n){if(this.reference=()=>{let{name:T,columns:f,foreignColumns:S}=o();return{name:T,columns:f,foreignTable:S[0].table,foreignColumns:S}},n)this._onUpdate=n.onUpdate,this._onDelete=n.onDelete}onUpdate(o){return this._onUpdate=o===void 0?"no action":o,this}onDelete(o){return this._onDelete=o===void 0?"no action":o,this}build(o){return new yJ(o,this)}}class yJ{constructor(o,n){this.table=o,this.reference=n.reference,this.onUpdate=n._onUpdate,this.onDelete=n._onDelete}static[y]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:o,columns:n,foreignColumns:T}=this.reference(),f=n.map(($)=>$.name),S=T.map(($)=>$.name),A=[this.table[zn],...f,T[0].table[zn],...S];return o??`${A.join("_")}_fk`}}function yS(o,...n){return o(...n)}function kJ(o,n){return`${o[zn]}_${n.join("_")}_unique`}function WJ(o,n,T){for(let f=n;f<o.length;f++){let S=o[f];if(S==="\\"){f++;continue}if(S==='"')return[o.slice(n,f).replace(/\\/g,""),f+1];if(T)continue;if(S===","||S==="}")return[o.slice(n,f).replace(/\\/g,""),f]}return[o.slice(n).replace(/\\/g,""),o.length]}function OJ(o,n=0){let T=[],f=n,S=!1;while(f<o.length){let A=o[f];if(A===","){if(S||f===n)T.push("");S=!0,f++;continue}if(S=!1,A==="\\"){f+=2;continue}if(A==='"'){let[J,t]=WJ(o,f+1,!0);T.push(J),f=t;continue}if(A==="}")return[T,f+1];if(A==="{"){let[J,t]=OJ(o,f+1);T.push(J),f=t;continue}let[$,F]=WJ(o,f,!1);T.push($),f=F}return[T,f]}function wJ(o){let[n]=OJ(o,1);return n}function xA(o){return`{${o.map((n)=>{if(Array.isArray(n))return xA(n);if(typeof n==="string")return`"${n.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${n}`}).join(",")}}`}class b extends hA{foreignKeyConfigs=[];static[y]="PgColumnBuilder";array(o){return new XJ(this.config.name,this,o)}references(o,n={}){return this.foreignKeyConfigs.push({ref:o,actions:n}),this}unique(o,n){return this.config.isUnique=!0,this.config.uniqueName=o,this.config.uniqueType=n?.nulls,this}generatedAlwaysAs(o){return this.config.generated={as:o,type:"always",mode:"stored"},this}buildForeignKeys(o,n){return this.foreignKeyConfigs.map(({ref:T,actions:f})=>{return yS((S,A)=>{let $=new bA(()=>{let F=S();return{columns:[o],foreignColumns:[F]}});if(A.onUpdate)$.onUpdate(A.onUpdate);if(A.onDelete)$.onDelete(A.onDelete);return $.build(n)},T,f)})}buildExtraConfigColumn(o){return new _J(o,this.config)}}class V extends Wo{constructor(o,n){if(!n.uniqueName)n.uniqueName=kJ(o,[n.name]);super(o,n);this.table=o}static[y]="PgColumn"}class _J extends V{static[y]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op(o){return this.indexConfig.opClass=o,this}}class Gf{static[y]="IndexedColumn";constructor(o,n,T,f){this.name=o,this.keyAsName=n,this.type=T,this.indexConfig=f}name;keyAsName;type;indexConfig}class XJ extends b{static[y]="PgArrayBuilder";constructor(o,n,T){super(o,"array","PgArray");this.config.baseBuilder=n,this.config.size=T}build(o){let n=this.config.baseBuilder.build(o);return new vA(o,this.config,n)}}class vA extends V{constructor(o,n,T,f){super(o,n);this.baseColumn=T,this.range=f,this.size=n.size}size;static[y]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(o){if(typeof o==="string")o=wJ(o);return o.map((n)=>this.baseColumn.mapFromDriverValue(n))}mapToDriverValue(o,n=!1){let T=o.map((f)=>f===null?null:X(this.baseColumn,vA)?this.baseColumn.mapToDriverValue(f,!0):this.baseColumn.mapToDriverValue(f));if(n)return T;return xA(T)}}var rA=Symbol.for("drizzle:isPgEnum");function KJ(o){return!!o&&typeof o==="function"&&rA in o&&o[rA]===!0}class HJ extends b{static[y]="PgEnumColumnBuilder";constructor(o,n){super(o,"string","PgEnumColumn");this.config.enum=n}build(o){return new EJ(o,this.config)}}class EJ extends V{static[y]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(o,n){super(o,n);this.enum=n.enum}getSQLType(){return this.enum.enumName}}function kS(o,n){return ay(o,n,void 0)}function ay(o,n,T){let f=Object.assign((S)=>new HJ(S??"",f),{enumName:o,enumValues:n,schema:T,[rA]:!0});return f}class ho{static[y]="Subquery";constructor(o,n,T,f=!1){this._={brand:"Subquery",sql:o,selectedFields:n,alias:T,isWith:f}}}class Yf extends ho{static[y]="WithSubquery"}var GJ="0.40.0";var qA,pA,Oo={startActiveSpan(o,n){if(!qA)return n();if(!pA)pA=qA.trace.getTracer("drizzle-orm",GJ);return yS((T,f)=>f.startActiveSpan(o,(S)=>{try{return n(S)}catch(A){throw S.setStatus({code:T.SpanStatusCode.ERROR,message:A instanceof Error?A.message:"Unknown error"}),A}finally{S.end()}}),qA,pA)}};var Xo=Symbol.for("drizzle:ViewBaseConfig");var WS=Symbol.for("drizzle:Schema"),OS=Symbol.for("drizzle:Columns"),YJ=Symbol.for("drizzle:ExtraConfigColumns"),cA=Symbol.for("drizzle:OriginalName"),ZA=Symbol.for("drizzle:BaseName"),zf=Symbol.for("drizzle:IsAlias"),zJ=Symbol.for("drizzle:ExtraConfigBuilder"),o1=Symbol.for("drizzle:IsDrizzleTable");class I{static[y]="Table";static Symbol={Name:zn,Schema:WS,OriginalName:cA,Columns:OS,ExtraConfigColumns:YJ,BaseName:ZA,IsAlias:zf,ExtraConfigBuilder:zJ};[zn];[cA];[WS];[OS];[YJ];[ZA];[zf]=!1;[o1]=!0;[zJ]=void 0;constructor(o,n,T){this[zn]=this[cA]=o,this[WS]=n,this[ZA]=T}}function vo(o){return o[zn]}function WT(o){return`${o[WS]??"public"}.${o[zn]}`}function PA(o){return o!==null&&o!==void 0&&typeof o.getSQL==="function"}function n1(o){let n={sql:"",params:[]};for(let T of o)if(n.sql+=T.sql,n.params.push(...T.params),T.typings?.length){if(!n.typings)n.typings=[];n.typings.push(...T.typings)}return n}class bo{static[y]="StringChunk";value;constructor(o){this.value=Array.isArray(o)?o:[o]}getSQL(){return new j([this])}}class j{constructor(o){this.queryChunks=o}static[y]="SQL";decoder=QJ;shouldInlineParams=!1;append(o){return this.queryChunks.push(...o.queryChunks),this}toQuery(o){return Oo.startActiveSpan("drizzle.buildSQL",(n)=>{let T=this.buildQueryFromSourceParams(this.queryChunks,o);return n?.setAttributes({"drizzle.query.text":T.sql,"drizzle.query.params":JSON.stringify(T.params)}),T})}buildQueryFromSourceParams(o,n){let T=Object.assign({},n,{inlineParams:n.inlineParams||this.shouldInlineParams,paramStartIndex:n.paramStartIndex||{value:0}}),{casing:f,escapeName:S,escapeParam:A,prepareTyping:$,inlineParams:F,paramStartIndex:J}=T;return n1(o.map((t)=>{if(X(t,bo))return{sql:t.value.join(""),params:[]};if(X(t,wS))return{sql:S(t.value),params:[]};if(t===void 0)return{sql:"",params:[]};if(Array.isArray(t)){let R=[new bo("(")];for(let[W,O]of t.entries())if(R.push(O),W<t.length-1)R.push(new bo(", "));return R.push(new bo(")")),this.buildQueryFromSourceParams(R,T)}if(X(t,j))return this.buildQueryFromSourceParams(t.queryChunks,{...T,inlineParams:F||t.shouldInlineParams});if(X(t,I)){let R=t[I.Symbol.Schema],W=t[I.Symbol.Name];return{sql:R===void 0||t[zf]?S(W):S(R)+"."+S(W),params:[]}}if(X(t,Wo)){let R=f.getColumnCasing(t);if(n.invokeSource==="indexes")return{sql:S(R),params:[]};let W=t.table[I.Symbol.Schema];return{sql:t.table[zf]||W===void 0?S(t.table[I.Symbol.Name])+"."+S(R):S(W)+"."+S(t.table[I.Symbol.Name])+"."+S(R),params:[]}}if(X(t,Sn)){let R=t[Xo].schema,W=t[Xo].name;return{sql:R===void 0||t[Xo].isAlias?S(W):S(R)+"."+S(W),params:[]}}if(X(t,tn)){if(X(t.value,sn))return{sql:A(J.value++,t),params:[t],typings:["none"]};let R=t.value===null?null:t.encoder.mapToDriverValue(t.value);if(X(R,j))return this.buildQueryFromSourceParams([R],T);if(F)return{sql:this.mapInlineParam(R,T),params:[]};let W=["none"];if($)W=[$(t.encoder)];return{sql:A(J.value++,R),params:[R],typings:W}}if(X(t,sn))return{sql:A(J.value++,t),params:[t],typings:["none"]};if(X(t,j.Aliased)&&t.fieldAlias!==void 0)return{sql:S(t.fieldAlias),params:[]};if(X(t,ho)){if(t._.isWith)return{sql:S(t._.alias),params:[]};return this.buildQueryFromSourceParams([new bo("("),t._.sql,new bo(") "),new wS(t._.alias)],T)}if(KJ(t)){if(t.schema)return{sql:S(t.schema)+"."+S(t.enumName),params:[]};return{sql:S(t.enumName),params:[]}}if(PA(t)){if(t.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([t.getSQL()],T);return this.buildQueryFromSourceParams([new bo("("),t.getSQL(),new bo(")")],T)}if(F)return{sql:this.mapInlineParam(t,T),params:[]};return{sql:A(J.value++,t),params:[t],typings:["none"]}}))}mapInlineParam(o,{escapeString:n}){if(o===null)return"null";if(typeof o==="number"||typeof o==="boolean")return o.toString();if(typeof o==="string")return n(o);if(typeof o==="object"){let T=o.toString();if(T==="[object Object]")return n(JSON.stringify(o));return n(T)}throw new Error("Unexpected param value: "+o)}getSQL(){return this}as(o){if(o===void 0)return this;return new j.Aliased(this,o)}mapWith(o){return this.decoder=typeof o==="function"?{mapFromDriverValue:o}:o,this}inlineParams(){return this.shouldInlineParams=!0,this}if(o){return o?this:void 0}}class wS{constructor(o){this.value=o}static[y]="Name";brand;getSQL(){return new j([this])}}function DJ(o){return typeof o==="object"&&o!==null&&"mapToDriverValue"in o&&typeof o.mapToDriverValue==="function"}var QJ={mapFromDriverValue:(o)=>o},UJ={mapToDriverValue:(o)=>o},sE={...QJ,...UJ};class tn{constructor(o,n=UJ){this.value=o,this.encoder=n}static[y]="Param";brand;getSQL(){return new j([this])}}function k(o,...n){let T=[];if(n.length>0||o.length>0&&o[0]!=="")T.push(new bo(o[0]));for(let[f,S]of n.entries())T.push(S,new bo(o[f+1]));return new j(T)}((o)=>{function n(){return new j([])}o.empty=n;function T(J){return new j(J)}o.fromList=T;function f(J){return new j([new bo(J)])}o.raw=f;function S(J,t){let R=[];for(let[W,O]of J.entries()){if(W>0&&t!==void 0)R.push(t);R.push(O)}return new j(R)}o.join=S;function A(J){return new wS(J)}o.identifier=A;function $(J){return new sn(J)}o.placeholder=$;function F(J,t){return new tn(J,t)}o.param=F})(k||(k={}));((o)=>{class n{constructor(T,f){this.sql=T,this.fieldAlias=f}static[y]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new n(this.sql,this.fieldAlias)}}o.Aliased=n})(j||(j={}));class sn{constructor(o){this.name=o}static[y]="Placeholder";getSQL(){return new j([this])}}function iA(o,n){return o.map((T)=>{if(X(T,sn)){if(!(T.name in n))throw new Error(`No value for placeholder "${T.name}" was provided`);return n[T.name]}if(X(T,tn)&&X(T.value,sn)){if(!(T.value.name in n))throw new Error(`No value for placeholder "${T.value.name}" was provided`);return T.encoder.mapToDriverValue(n[T.value.name])}return T})}var T1=Symbol.for("drizzle:IsDrizzleView");class Sn{static[y]="View";[Xo];[T1]=!0;constructor({name:o,schema:n,selectedFields:T,query:f}){this[Xo]={name:o,originalName:o,schema:n,selectedFields:T,query:f,isExisting:!f,isAlias:!1}}getSQL(){return new j([this])}}Wo.prototype.getSQL=function(){return new j([this])};I.prototype.getSQL=function(){return new j([this])};ho.prototype.getSQL=function(){return new j([this])};class iT{constructor(o){this.table=o}static[y]="ColumnAliasProxyHandler";get(o,n){if(n==="table")return this.table;return o[n]}}class Df{constructor(o,n){this.alias=o,this.replaceOriginalName=n}static[y]="TableAliasProxyHandler";get(o,n){if(n===I.Symbol.IsAlias)return!0;if(n===I.Symbol.Name)return this.alias;if(this.replaceOriginalName&&n===I.Symbol.OriginalName)return this.alias;if(n===Xo)return{...o[Xo],name:this.alias,isAlias:!0};if(n===I.Symbol.Columns){let f=o[I.Symbol.Columns];if(!f)return f;let S={};return Object.keys(f).map((A)=>{S[A]=new Proxy(f[A],new iT(new Proxy(o,this)))}),S}let T=o[n];if(X(T,Wo))return new Proxy(T,new iT(new Proxy(o,this)));return T}}function _S(o,n){return new Proxy(o,new Df(n,!1))}function Ln(o,n){return new Proxy(o,new iT(new Proxy(o.table,new Df(n,!1))))}function gA(o,n){return new j.Aliased(Qf(o.sql,n),o.fieldAlias)}function Qf(o,n){return k.join(o.queryChunks.map((T)=>{if(X(T,Wo))return Ln(T,n);if(X(T,j))return Qf(T,n);if(X(T,j.Aliased))return gA(T,n);return T}))}class XS extends Error{static[y]="DrizzleError";constructor({message:o,cause:n}){super(o);this.name="DrizzleError",this.cause=n}}class dA extends XS{static[y]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}function An(o,n){if(DJ(n)&&!PA(o)&&!X(o,tn)&&!X(o,sn)&&!X(o,Wo)&&!X(o,I)&&!X(o,Sn))return new tn(o,n);return o}var KS=(o,n)=>{return k`${o} = ${An(n,o)}`},VJ=(o,n)=>{return k`${o} <> ${An(n,o)}`};function Uf(...o){let n=o.filter((T)=>T!==void 0);if(n.length===0)return;if(n.length===1)return new j(n);return new j([new bo("("),k.join(n,new bo(" and ")),new bo(")")])}function mJ(...o){let n=o.filter((T)=>T!==void 0);if(n.length===0)return;if(n.length===1)return new j(n);return new j([new bo("("),k.join(n,new bo(" or ")),new bo(")")])}function BJ(o){return k`not ${o}`}var LJ=(o,n)=>{return k`${o} > ${An(n,o)}`},CJ=(o,n)=>{return k`${o} >= ${An(n,o)}`},IJ=(o,n)=>{return k`${o} < ${An(n,o)}`},jJ=(o,n)=>{return k`${o} <= ${An(n,o)}`};function NJ(o,n){if(Array.isArray(n)){if(n.length===0)return k`false`;return k`${o} in ${n.map((T)=>An(T,o))}`}return k`${o} in ${An(n,o)}`}function hJ(o,n){if(Array.isArray(n)){if(n.length===0)return k`true`;return k`${o} not in ${n.map((T)=>An(T,o))}`}return k`${o} not in ${An(n,o)}`}function bJ(o){return k`${o} is null`}function xJ(o){return k`${o} is not null`}function vJ(o){return k`exists ${o}`}function rJ(o){return k`not exists ${o}`}function qJ(o,n,T){return k`${o} between ${An(n,o)} and ${An(T,o)}`}function pJ(o,n,T){return k`${o} not between ${An(n,o)} and ${An(T,o)}`}function cJ(o,n){return k`${o} like ${n}`}function ZJ(o,n){return k`${o} not like ${n}`}function PJ(o,n){return k`${o} ilike ${n}`}function iJ(o,n){return k`${o} not ilike ${n}`}function gJ(o){return k`${o} asc`}function dJ(o){return k`${o} desc`}class lJ{static[y]="ConsoleLogWriter";write(o){console.log(o)}}class lA{static[y]="DefaultLogger";writer;constructor(o){this.writer=o?.writer??new lJ}logQuery(o,n){let T=n.map((S)=>{try{return JSON.stringify(S)}catch{return String(S)}}),f=T.length?` -- params: [${T.join(", ")}]`:"";this.writer.write(`Query: ${o}${f}`)}}class uA{static[y]="NoopLogger";logQuery(){}}class on{static[y]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(o){return this.then(void 0,o)}finally(o){return this.then((n)=>{return o?.(),n},(n)=>{throw o?.(),n})}then(o,n){return this.execute().then(o,n)}}function uJ(o,n,T){let f={},S=o.reduce((A,{path:$,field:F},J)=>{let t;if(X(F,Wo))t=F;else if(X(F,j))t=F.decoder;else t=F.sql.decoder;let R=A;for(let[W,O]of $.entries())if(W<$.length-1){if(!(O in R))R[O]={};R=R[O]}else{let _=n[J],Q=R[O]=_===null?null:t.mapFromDriverValue(_);if(T&&X(F,Wo)&&$.length===2){let K=$[0];if(!(K in f))f[K]=Q===null?vo(F.table):!1;else if(typeof f[K]==="string"&&f[K]!==vo(F.table))f[K]=!1}}return A},{});if(T&&Object.keys(f).length>0){for(let[A,$]of Object.entries(f))if(typeof $==="string"&&!T[$])S[A]=null}return S}function On(o,n){return Object.entries(o).reduce((T,[f,S])=>{if(typeof f!=="string")return T;let A=n?[...n,f]:[f];if(X(S,Wo)||X(S,j)||X(S,j.Aliased))T.push({path:A,field:S});else if(X(S,I))T.push(...On(S[I.Symbol.Columns],A));else T.push(...On(S,A));return T},[])}function Vf(o,n){let T=Object.keys(o),f=Object.keys(n);if(T.length!==f.length)return!1;for(let[S,A]of T.entries())if(A!==f[S])return!1;return!0}function HS(o,n){let T=Object.entries(n).filter(([,f])=>f!==void 0).map(([f,S])=>{if(X(S,j)||X(S,Wo))return[f,S];else return[f,new tn(S,o[I.Symbol.Columns][f])]});if(T.length===0)throw new Error("No values to set");return Object.fromEntries(T)}function eJ(o,n){for(let T of n)for(let f of Object.getOwnPropertyNames(T.prototype)){if(f==="constructor")continue;Object.defineProperty(o.prototype,f,Object.getOwnPropertyDescriptor(T.prototype,f)||Object.create(null))}}function sJ(o){return o[I.Symbol.Columns]}function qn(o){return X(o,ho)?o._.alias:X(o,Sn)?o[Xo].name:X(o,j)?void 0:o[I.Symbol.IsAlias]?o[I.Symbol.Name]:o[I.Symbol.BaseName]}function So(o,n){return{name:typeof o==="string"&&o.length>0?o:"",config:typeof o==="object"?o:n}}function aJ(o){if(typeof o!=="object"||o===null)return!1;if(o.constructor.name!=="Object")return!1;if("logger"in o){let n=typeof o.logger;if(n!=="boolean"&&(n!=="object"||typeof o.logger.logQuery!=="function")&&n!=="undefined")return!1;return!0}if("schema"in o){let n=typeof o.logger;if(n!=="object"&&n!=="undefined")return!1;return!0}if("casing"in o){let n=typeof o.logger;if(n!=="string"&&n!=="undefined")return!1;return!0}if("mode"in o){if(o.mode!=="default"||o.mode!=="planetscale"||o.mode!==void 0)return!1;return!0}if("connection"in o){let n=typeof o.connection;if(n!=="string"&&n!=="object"&&n!=="undefined")return!1;return!0}if("client"in o){let n=typeof o.client;if(n!=="object"&&n!=="function"&&n!=="undefined")return!1;return!0}if(Object.keys(o).length===0)return!0;return!1}class an extends b{static[y]="PgIntColumnBaseBuilder";generatedAlwaysAsIdentity(o){if(o){let{name:n,...T}=o;this.config.generatedIdentity={type:"always",sequenceName:n,sequenceOptions:T}}else this.config.generatedIdentity={type:"always"};return this.config.hasDefault=!0,this.config.notNull=!0,this}generatedByDefaultAsIdentity(o){if(o){let{name:n,...T}=o;this.config.generatedIdentity={type:"byDefault",sequenceName:n,sequenceOptions:T}}else this.config.generatedIdentity={type:"byDefault"};return this.config.hasDefault=!0,this.config.notNull=!0,this}}class ot extends an{static[y]="PgBigInt53Builder";constructor(o){super(o,"number","PgBigInt53")}build(o){return new nt(o,this.config)}}class nt extends V{static[y]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(o){if(typeof o==="number")return o;return Number(o)}}class Tt extends an{static[y]="PgBigInt64Builder";constructor(o){super(o,"bigint","PgBigInt64")}build(o){return new ft(o,this.config)}}class ft extends V{static[y]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(o){return BigInt(o)}}function St(o,n){let{name:T,config:f}=So(o,n);if(f.mode==="number")return new ot(T);return new Tt(T)}class At extends b{static[y]="PgBigSerial53Builder";constructor(o){super(o,"number","PgBigSerial53");this.config.hasDefault=!0,this.config.notNull=!0}build(o){return new $t(o,this.config)}}class $t extends V{static[y]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(o){if(typeof o==="number")return o;return Number(o)}}class Ft extends b{static[y]="PgBigSerial64Builder";constructor(o){super(o,"bigint","PgBigSerial64");this.config.hasDefault=!0}build(o){return new Jt(o,this.config)}}class Jt extends V{static[y]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(o){return BigInt(o)}}function tt(o,n){let{name:T,config:f}=So(o,n);if(f.mode==="number")return new At(T);return new Ft(T)}class Rt extends b{static[y]="PgBooleanBuilder";constructor(o){super(o,"boolean","PgBoolean")}build(o){return new Mt(o,this.config)}}class Mt extends V{static[y]="PgBoolean";getSQLType(){return"boolean"}}function mf(o){return new Rt(o??"")}class yt extends b{static[y]="PgCharBuilder";constructor(o,n){super(o,"string","PgChar");this.config.length=n.length,this.config.enumValues=n.enum}build(o){return new kt(o,this.config)}}class kt extends V{static[y]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}}function Wt(o,n={}){let{name:T,config:f}=So(o,n);return new yt(T,f)}class Ot extends b{static[y]="PgCidrBuilder";constructor(o){super(o,"string","PgCidr")}build(o){return new wt(o,this.config)}}class wt extends V{static[y]="PgCidr";getSQLType(){return"cidr"}}function _t(o){return new Ot(o??"")}class Xt extends b{static[y]="PgCustomColumnBuilder";constructor(o,n,T){super(o,"custom","PgCustomColumn");this.config.fieldConfig=n,this.config.customTypeParams=T}build(o){return new Kt(o,this.config)}}class Kt extends V{static[y]="PgCustomColumn";sqlName;mapTo;mapFrom;constructor(o,n){super(o,n);this.sqlName=n.customTypeParams.dataType(n.fieldConfig),this.mapTo=n.customTypeParams.toDriver,this.mapFrom=n.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(o){return typeof this.mapFrom==="function"?this.mapFrom(o):o}mapToDriverValue(o){return typeof this.mapTo==="function"?this.mapTo(o):o}}function Ht(o){return(n,T)=>{let{name:f,config:S}=So(n,T);return new Xt(f,S,o)}}class pn extends b{static[y]="PgDateColumnBaseBuilder";defaultNow(){return this.default(k`now()`)}}class Et extends pn{static[y]="PgDateBuilder";constructor(o){super(o,"date","PgDate")}build(o){return new ES(o,this.config)}}class ES extends V{static[y]="PgDate";getSQLType(){return"date"}mapFromDriverValue(o){return new Date(o)}mapToDriverValue(o){return o.toISOString()}}class Gt extends pn{static[y]="PgDateStringBuilder";constructor(o){super(o,"string","PgDateString")}build(o){return new GS(o,this.config)}}class GS extends V{static[y]="PgDateString";getSQLType(){return"date"}}function Yt(o,n){let{name:T,config:f}=So(o,n);if(f?.mode==="date")return new Et(T);return new Gt(T)}class zt extends b{static[y]="PgDoublePrecisionBuilder";constructor(o){super(o,"number","PgDoublePrecision")}build(o){return new Dt(o,this.config)}}class Dt extends V{static[y]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(o){if(typeof o==="string")return Number.parseFloat(o);return o}}function Qt(o){return new zt(o??"")}class Ut extends b{static[y]="PgInetBuilder";constructor(o){super(o,"string","PgInet")}build(o){return new Vt(o,this.config)}}class Vt extends V{static[y]="PgInet";getSQLType(){return"inet"}}function mt(o){return new Ut(o??"")}class Bt extends an{static[y]="PgIntegerBuilder";constructor(o){super(o,"number","PgInteger")}build(o){return new Lt(o,this.config)}}class Lt extends V{static[y]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(o){if(typeof o==="string")return Number.parseInt(o);return o}}function YS(o){return new Bt(o??"")}class Ct extends b{static[y]="PgIntervalBuilder";constructor(o,n){super(o,"string","PgInterval");this.config.intervalConfig=n}build(o){return new It(o,this.config)}}class It extends V{static[y]="PgInterval";fields=this.config.intervalConfig.fields;precision=this.config.intervalConfig.precision;getSQLType(){let o=this.fields?` ${this.fields}`:"",n=this.precision?`(${this.precision})`:"";return`interval${o}${n}`}}function jt(o,n={}){let{name:T,config:f}=So(o,n);return new Ct(T,f)}class Nt extends b{static[y]="PgJsonBuilder";constructor(o){super(o,"json","PgJson")}build(o){return new zS(o,this.config)}}class zS extends V{static[y]="PgJson";constructor(o,n){super(o,n)}getSQLType(){return"json"}mapToDriverValue(o){return JSON.stringify(o)}mapFromDriverValue(o){if(typeof o==="string")try{return JSON.parse(o)}catch{return o}return o}}function ht(o){return new Nt(o??"")}class bt extends b{static[y]="PgJsonbBuilder";constructor(o){super(o,"json","PgJsonb")}build(o){return new DS(o,this.config)}}class DS extends V{static[y]="PgJsonb";constructor(o,n){super(o,n)}getSQLType(){return"jsonb"}mapToDriverValue(o){return JSON.stringify(o)}mapFromDriverValue(o){if(typeof o==="string")try{return JSON.parse(o)}catch{return o}return o}}function xt(o){return new bt(o??"")}class vt extends b{static[y]="PgLineBuilder";constructor(o){super(o,"array","PgLine")}build(o){return new rt(o,this.config)}}class rt extends V{static[y]="PgLine";getSQLType(){return"line"}mapFromDriverValue(o){let[n,T,f]=o.slice(1,-1).split(",");return[Number.parseFloat(n),Number.parseFloat(T),Number.parseFloat(f)]}mapToDriverValue(o){return`{${o[0]},${o[1]},${o[2]}}`}}class qt extends b{static[y]="PgLineABCBuilder";constructor(o){super(o,"json","PgLineABC")}build(o){return new pt(o,this.config)}}class pt extends V{static[y]="PgLineABC";getSQLType(){return"line"}mapFromDriverValue(o){let[n,T,f]=o.slice(1,-1).split(",");return{a:Number.parseFloat(n),b:Number.parseFloat(T),c:Number.parseFloat(f)}}mapToDriverValue(o){return`{${o.a},${o.b},${o.c}}`}}function ct(o,n){let{name:T,config:f}=So(o,n);if(!f?.mode||f.mode==="tuple")return new vt(T);return new qt(T)}class Zt extends b{static[y]="PgMacaddrBuilder";constructor(o){super(o,"string","PgMacaddr")}build(o){return new Pt(o,this.config)}}class Pt extends V{static[y]="PgMacaddr";getSQLType(){return"macaddr"}}function it(o){return new Zt(o??"")}class gt extends b{static[y]="PgMacaddr8Builder";constructor(o){super(o,"string","PgMacaddr8")}build(o){return new dt(o,this.config)}}class dt extends V{static[y]="PgMacaddr8";getSQLType(){return"macaddr8"}}function lt(o){return new gt(o??"")}class ut extends b{static[y]="PgNumericBuilder";constructor(o,n,T){super(o,"string","PgNumeric");this.config.precision=n,this.config.scale=T}build(o){return new QS(o,this.config)}}class QS extends V{static[y]="PgNumeric";precision;scale;constructor(o,n){super(o,n);this.precision=n.precision,this.scale=n.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 et(o,n){let{name:T,config:f}=So(o,n);return new ut(T,f?.precision,f?.scale)}class st extends b{static[y]="PgPointTupleBuilder";constructor(o){super(o,"array","PgPointTuple")}build(o){return new at(o,this.config)}}class at extends V{static[y]="PgPointTuple";getSQLType(){return"point"}mapFromDriverValue(o){if(typeof o==="string"){let[n,T]=o.slice(1,-1).split(",");return[Number.parseFloat(n),Number.parseFloat(T)]}return[o.x,o.y]}mapToDriverValue(o){return`(${o[0]},${o[1]})`}}class oR extends b{static[y]="PgPointObjectBuilder";constructor(o){super(o,"json","PgPointObject")}build(o){return new nR(o,this.config)}}class nR extends V{static[y]="PgPointObject";getSQLType(){return"point"}mapFromDriverValue(o){if(typeof o==="string"){let[n,T]=o.slice(1,-1).split(",");return{x:Number.parseFloat(n),y:Number.parseFloat(T)}}return o}mapToDriverValue(o){return`(${o.x},${o.y})`}}function TR(o,n){let{name:T,config:f}=So(o,n);if(!f?.mode||f.mode==="tuple")return new st(T);return new oR(T)}function f1(o){let n=[];for(let T=0;T<o.length;T+=2)n.push(Number.parseInt(o.slice(T,T+2),16));return new Uint8Array(n)}function fR(o,n){let T=new ArrayBuffer(8),f=new DataView(T);for(let S=0;S<8;S++)f.setUint8(S,o[n+S]);return f.getFloat64(0,!0)}function eA(o){let n=f1(o),T=0,f=n[T];T+=1;let S=new DataView(n.buffer),A=S.getUint32(T,f===1);T+=4;let $;if(A&536870912)$=S.getUint32(T,f===1),T+=4;if((A&65535)===1){let F=fR(n,T);T+=8;let J=fR(n,T);return T+=8,[F,J]}throw new Error("Unsupported geometry type")}class SR extends b{static[y]="PgGeometryBuilder";constructor(o){super(o,"array","PgGeometry")}build(o){return new AR(o,this.config)}}class AR extends V{static[y]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(o){return eA(o)}mapToDriverValue(o){return`point(${o[0]} ${o[1]})`}}class $R extends b{static[y]="PgGeometryObjectBuilder";constructor(o){super(o,"json","PgGeometryObject")}build(o){return new FR(o,this.config)}}class FR extends V{static[y]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(o){let n=eA(o);return{x:n[0],y:n[1]}}mapToDriverValue(o){return`point(${o.x} ${o.y})`}}function JR(o,n){let{name:T,config:f}=So(o,n);if(!f?.mode||f.mode==="tuple")return new SR(T);return new $R(T)}class tR extends b{static[y]="PgRealBuilder";constructor(o,n){super(o,"number","PgReal");this.config.length=n}build(o){return new RR(o,this.config)}}class RR extends V{static[y]="PgReal";constructor(o,n){super(o,n)}getSQLType(){return"real"}mapFromDriverValue=(o)=>{if(typeof o==="string")return Number.parseFloat(o);return o}}function MR(o){return new tR(o??"")}class yR extends b{static[y]="PgSerialBuilder";constructor(o){super(o,"number","PgSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(o){return new kR(o,this.config)}}class kR extends V{static[y]="PgSerial";getSQLType(){return"serial"}}function WR(o){return new yR(o??"")}class OR extends an{static[y]="PgSmallIntBuilder";constructor(o){super(o,"number","PgSmallInt")}build(o){return new wR(o,this.config)}}class wR extends V{static[y]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=(o)=>{if(typeof o==="string")return Number(o);return o}}function _R(o){return new OR(o??"")}class XR extends b{static[y]="PgSmallSerialBuilder";constructor(o){super(o,"number","PgSmallSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(o){return new KR(o,this.config)}}class KR extends V{static[y]="PgSmallSerial";getSQLType(){return"smallserial"}}function HR(o){return new XR(o??"")}class ER extends b{static[y]="PgTextBuilder";constructor(o,n){super(o,"string","PgText");this.config.enumValues=n.enum}build(o){return new GR(o,this.config)}}class GR extends V{static[y]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function YR(o,n={}){let{name:T,config:f}=So(o,n);return new ER(T,f)}class zR extends pn{constructor(o,n,T){super(o,"string","PgTime");this.withTimezone=n,this.precision=T,this.config.withTimezone=n,this.config.precision=T}static[y]="PgTimeBuilder";build(o){return new US(o,this.config)}}class US extends V{static[y]="PgTime";withTimezone;precision;constructor(o,n){super(o,n);this.withTimezone=n.withTimezone,this.precision=n.precision}getSQLType(){return`time${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function DR(o,n={}){let{name:T,config:f}=So(o,n);return new zR(T,f.withTimezone??!1,f.precision)}class QR extends pn{static[y]="PgTimestampBuilder";constructor(o,n,T){super(o,"date","PgTimestamp");this.config.withTimezone=n,this.config.precision=T}build(o){return new VS(o,this.config)}}class VS extends V{static[y]="PgTimestamp";withTimezone;precision;constructor(o,n){super(o,n);this.withTimezone=n.withTimezone,this.precision=n.precision}getSQLType(){return`timestamp${this.precision===void 0?"":` (${this.precision})`}${this.withTimezone?" with time zone":""}`}mapFromDriverValue=(o)=>{return new Date(this.withTimezone?o:o+"+0000")};mapToDriverValue=(o)=>{return o.toISOString()}}class UR extends pn{static[y]="PgTimestampStringBuilder";constructor(o,n,T){super(o,"string","PgTimestampString");this.config.withTimezone=n,this.config.precision=T}build(o){return new mS(o,this.config)}}class mS extends V{static[y]="PgTimestampString";withTimezone;precision;constructor(o,n){super(o,n);this.withTimezone=n.withTimezone,this.precision=n.precision}getSQLType(){return`timestamp${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function Dn(o,n={}){let{name:T,config:f}=So(o,n);if(f?.mode==="string")return new UR(T,f.withTimezone??!1,f.precision);return new QR(T,f?.withTimezone??!1,f?.precision)}class VR extends b{static[y]="PgUUIDBuilder";constructor(o){super(o,"string","PgUUID")}defaultRandom(){return this.default(k`gen_random_uuid()`)}build(o){return new BS(o,this.config)}}class BS extends V{static[y]="PgUUID";getSQLType(){return"uuid"}}function Rn(o){return new VR(o??"")}class mR extends b{static[y]="PgVarcharBuilder";constructor(o,n){super(o,"string","PgVarchar");this.config.length=n.length,this.config.enumValues=n.enum}build(o){return new BR(o,this.config)}}class BR extends V{static[y]="PgVarchar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"varchar":`varchar(${this.length})`}}function po(o,n={}){let{name:T,config:f}=So(o,n);return new mR(T,f)}class LR extends b{static[y]="PgBinaryVectorBuilder";constructor(o,n){super(o,"string","PgBinaryVector");this.config.dimensions=n.dimensions}build(o){return new CR(o,this.config)}}class CR extends V{static[y]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}}function IR(o,n){let{name:T,config:f}=So(o,n);return new LR(T,f)}class jR extends b{static[y]="PgHalfVectorBuilder";constructor(o,n){super(o,"array","PgHalfVector");this.config.dimensions=n.dimensions}build(o){return new NR(o,this.config)}}class NR extends V{static[y]="PgHalfVector";dimensions=this.config.dimensions;getSQLType(){return`halfvec(${this.dimensions})`}mapToDriverValue(o){return JSON.stringify(o)}mapFromDriverValue(o){return o.slice(1,-1).split(",").map((n)=>Number.parseFloat(n))}}function hR(o,n){let{name:T,config:f}=So(o,n);return new jR(T,f)}class bR extends b{static[y]="PgSparseVectorBuilder";constructor(o,n){super(o,"string","PgSparseVector");this.config.dimensions=n.dimensions}build(o){return new xR(o,this.config)}}class xR extends V{static[y]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function vR(o,n){let{name:T,config:f}=So(o,n);return new bR(T,f)}class rR extends b{static[y]="PgVectorBuilder";constructor(o,n){super(o,"array","PgVector");this.config.dimensions=n.dimensions}build(o){return new qR(o,this.config)}}class qR extends V{static[y]="PgVector";dimensions=this.config.dimensions;getSQLType(){return`vector(${this.dimensions})`}mapToDriverValue(o){return JSON.stringify(o)}mapFromDriverValue(o){return o.slice(1,-1).split(",").map((n)=>Number.parseFloat(n))}}function pR(o,n){let{name:T,config:f}=So(o,n);return new rR(T,f)}function cR(){return{bigint:St,bigserial:tt,boolean:mf,char:Wt,cidr:_t,customType:Ht,date:Yt,doublePrecision:Qt,inet:mt,integer:YS,interval:jt,json:ht,jsonb:xt,line:ct,macaddr:it,macaddr8:lt,numeric:et,point:TR,geometry:JR,real:MR,serial:WR,smallint:_R,smallserial:HR,text:YR,time:DR,timestamp:Dn,uuid:Rn,varchar:po,bit:IR,halfvec:hR,sparsevec:vR,vector:pR}}var sA=Symbol.for("drizzle:PgInlineForeignKeys"),ZR=Symbol.for("drizzle:EnableRLS");class co extends I{static[y]="PgTable";static Symbol=Object.assign({},I.Symbol,{InlineForeignKeys:sA,EnableRLS:ZR});[sA]=[];[ZR]=!1;[I.Symbol.ExtraConfigBuilder]=void 0;[I.Symbol.ExtraConfigColumns]={}}function S1(o,n,T,f,S=o){let A=new co(o,f,S),$=typeof n==="function"?n(cR()):n,F=Object.fromEntries(Object.entries($).map(([R,W])=>{let O=W;O.setName(R);let _=O.build(A);return A[sA].push(...O.buildForeignKeys(_,A)),[R,_]})),J=Object.fromEntries(Object.entries($).map(([R,W])=>{let O=W;O.setName(R);let _=O.buildExtraConfigColumn(A);return[R,_]})),t=Object.assign(A,F);if(t[I.Symbol.Columns]=F,t[I.Symbol.ExtraConfigColumns]=J,T)t[co.Symbol.ExtraConfigBuilder]=T;return Object.assign(t,{enableRLS:()=>{return t[co.Symbol.EnableRLS]=!0,t}})}var oT=(o,n,T)=>{return S1(o,n,T,void 0)};function PR(...o){if(o[0].columns)return new Bf(o[0].columns,o[0].name);return new Bf(o)}class Bf{static[y]="PgPrimaryKeyBuilder";columns;name;constructor(o,n){this.columns=o,this.name=n}build(o){return new iR(o,this.columns,this.name)}}class iR{constructor(o,n,T){this.table=o,this.columns=n,this.name=T}static[y]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[co.Symbol.Name]}_${this.columns.map((o)=>o.name).join("_")}_pk`}}class aA{constructor(o,n,T){this.sourceTable=o,this.referencedTable=n,this.relationName=T,this.referencedTableName=n[I.Symbol.Name]}static[y]="Relation";referencedTableName;fieldName}class gR{constructor(o,n){this.table=o,this.config=n}static[y]="Relations"}class nT extends aA{constructor(o,n,T,f){super(o,n,T?.relationName);this.config=T,this.isNullable=f}static[y]="One";withFieldName(o){let n=new nT(this.sourceTable,this.referencedTable,this.config,this.isNullable);return n.fieldName=o,n}}class Lf extends aA{constructor(o,n,T){super(o,n,T?.relationName);this.config=T}static[y]="Many";withFieldName(o){let n=new Lf(this.sourceTable,this.referencedTable,this.config);return n.fieldName=o,n}}function dR(){return{and:Uf,between:qJ,eq:KS,exists:vJ,gt:LJ,gte:CJ,ilike:PJ,inArray:NJ,isNull:bJ,isNotNull:xJ,like:cJ,lt:IJ,lte:jJ,ne:VJ,not:BJ,notBetween:pJ,notExists:rJ,notLike:ZJ,notIlike:iJ,notInArray:hJ,or:mJ,sql:k}}function lR(){return{sql:k,asc:gJ,desc:dJ}}function uR(o,n){if(Object.keys(o).length===1&&"default"in o&&!X(o.default,I))o=o.default;let T={},f={},S={};for(let[A,$]of Object.entries(o))if(X($,I)){let F=WT($),J=f[F];T[F]=A,S[A]={tsName:A,dbName:$[I.Symbol.Name],schema:$[I.Symbol.Schema],columns:$[I.Symbol.Columns],relations:J?.relations??{},primaryKey:J?.primaryKey??[]};for(let R of Object.values($[I.Symbol.Columns]))if(R.primary)S[A].primaryKey.push(R);let t=$[I.Symbol.ExtraConfigBuilder]?.($[I.Symbol.ExtraConfigColumns]);if(t){for(let R of Object.values(t))if(X(R,Bf))S[A].primaryKey.push(...R.columns)}}else if(X($,gR)){let F=WT($.table),J=T[F],t=$.config(n($.table)),R;for(let[W,O]of Object.entries(t))if(J){let _=S[J];if(_.relations[W]=O,R)_.primaryKey.push(...R)}else{if(!(F in f))f[F]={relations:{},primaryKey:R};f[F].relations[W]=O}}return{tables:S,tableNamesMap:T}}function A1(o){return function n(T,f){return new nT(o,T,f,f?.fields.reduce((S,A)=>S&&A.notNull,!0)??!1)}}function $1(o){return function n(T,f){return new Lf(o,T,f)}}function eR(o,n,T){if(X(T,nT)&&T.config)return{fields:T.config.fields,references:T.config.references};let f=n[WT(T.referencedTable)];if(!f)throw new Error(`Table "${T.referencedTable[I.Symbol.Name]}" not found in schema`);let S=o[f];if(!S)throw new Error(`Table "${f}" not found in schema`);let A=T.sourceTable,$=n[WT(A)];if(!$)throw new Error(`Table "${A[I.Symbol.Name]}" not found in schema`);let F=[];for(let J of Object.values(S.relations))if(T.relationName&&T!==J&&J.relationName===T.relationName||!T.relationName&&J.referencedTable===T.sourceTable)F.push(J);if(F.length>1)throw T.relationName?new Error(`There are multiple relations with name "${T.relationName}" in table "${f}"`):new Error(`There are multiple relations between "${f}" and "${T.sourceTable[I.Symbol.Name]}". Please specify relation name`);if(F[0]&&X(F[0],nT)&&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 "${$}.${T.fieldName}"`)}function sR(o){return{one:A1(o),many:$1(o)}}function LS(o,n,T,f,S=(A)=>A){let A={};for(let[$,F]of f.entries())if(F.isJson){let J=n.relations[F.tsKey],t=T[$],R=typeof t==="string"?JSON.parse(t):t;A[F.tsKey]=X(J,nT)?R&&LS(o,o[F.relationTableTsKey],R,F.selection,S):R.map((W)=>LS(o,o[F.relationTableTsKey],W,F.selection,S))}else{let J=S(T[$]),t=F.field,R;if(X(t,Wo))R=t;else if(X(t,j))R=t.decoder;else R=t.sql.decoder;A[F.tsKey]=J===null?null:R.mapFromDriverValue(J)}return A}import B1 from"os";import L1 from"fs";var CS=new Map,o$=new Map,n$=Symbol("OriginError"),gT={};class wn extends Promise{constructor(o,n,T,f,S={}){let A,$;super((F,J)=>{A=F,$=J});this.tagged=Array.isArray(o.raw),this.strings=o,this.args=n,this.handler=T,this.canceller=f,this.options=S,this.state=null,this.statement=null,this.resolve=(F)=>(this.active=!1,A(F)),this.reject=(F)=>(this.active=!1,$(F)),this.active=!1,this.cancelled=null,this.executed=!1,this.signature="",this[n$]=this.handler.debug?new Error:this.tagged&&F1(this.strings)}get origin(){return(this.handler.debug?this[n$].stack:this.tagged&&o$.has(this.strings)?o$.get(this.strings):o$.set(this.strings,this[n$].stack).get(this.strings))||""}static get[Symbol.species](){return Promise}cancel(){return this.canceller&&(this.canceller(this),this.canceller=null)}simple(){return this.options.simple=!0,this.options.prepare=!1,this}async readable(){return this.simple(),this.streaming=!0,this}async writable(){return this.simple(),this.streaming=!0,this}cursor(o=1,n){if(this.options.simple=!1,typeof o==="function")n=o,o=1;if(this.cursorRows=o,typeof n==="function")return this.cursorFn=n,this;let T;return{[Symbol.asyncIterator]:()=>({next:()=>{if(this.executed&&!this.active)return{done:!0};T&&T();let f=new Promise((S,A)=>{this.cursorFn=($)=>{return S({value:$,done:!1}),new Promise((F)=>T=F)},this.resolve=()=>(this.active=!1,S({done:!0})),this.reject=($)=>(this.active=!1,A($))});return this.execute(),f},return(){return T&&T(gT),{done:!0}}})}}describe(){return this.options.simple=!1,this.onlyDescribe=this.options.prepare=!0,this}stream(){throw new Error(".stream has been renamed to .forEach")}forEach(o){return this.forEachFn=o,this.handle(),this}raw(){return this.isRaw=!0,this}values(){return this.isRaw="values",this}async handle(){!this.executed&&(this.executed=!0)&&await 1&&this.handler(this)}execute(){return this.handle(),this}then(){return this.handle(),super.then.apply(this,arguments)}catch(){return this.handle(),super.catch.apply(this,arguments)}finally(){return this.handle(),super.finally.apply(this,arguments)}}function F1(o){if(CS.has(o))return CS.get(o);let n=Error.stackTraceLimit;return Error.stackTraceLimit=4,CS.set(o,new Error),Error.stackTraceLimit=n,CS.get(o)}class dT extends Error{constructor(o){super(o.message);this.name=this.constructor.name,Object.assign(this,o)}}var mo={connection:aR,postgres:o0,generic:n0,notSupported:T0};function aR(o,n,T){let{host:f,port:S}=T||n,A=Object.assign(new Error("write "+o+" "+(n.path||f+":"+S)),{code:o,errno:o,address:n.path||f},n.path?{}:{port:S});return Error.captureStackTrace(A,aR),A}function o0(o){let n=new dT(o);return Error.captureStackTrace(n,o0),n}function n0(o,n){let T=Object.assign(new Error(o+": "+n),{code:o});return Error.captureStackTrace(T,n0),T}function T0(o){let n=Object.assign(new Error(o+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:o});return Error.captureStackTrace(n,T0),n}var J1={string:{to:25,from:null,serialize:(o)=>""+o},number:{to:0,from:[21,23,26,700,701],serialize:(o)=>""+o,parse:(o)=>+o},json:{to:114,from:[114,3802],serialize:(o)=>JSON.stringify(o),parse:(o)=>JSON.parse(o)},boolean:{to:16,from:16,serialize:(o)=>o===!0?"t":"f",parse:(o)=>o==="t"},date:{to:1184,from:[1082,1114,1184],serialize:(o)=>(o instanceof Date?o:new Date(o)).toISOString(),parse:(o)=>new Date(o)},bytea:{to:17,from:17,serialize:(o)=>"\\x"+Buffer.from(o).toString("hex"),parse:(o)=>Buffer.from(o.slice(2),"hex")}};class NS{then(){T$()}catch(){T$()}finally(){T$()}}class Nf extends NS{constructor(o){super();this.value=xS(o)}}class Cn extends NS{constructor(o,n,T){super();this.value=o,this.type=n,this.array=T}}class hS extends NS{constructor(o,n){super();this.first=o,this.rest=n}build(o,n,T,f){let S=t1.map(([A,$])=>({fn:$,i:o.search(A)})).sort((A,$)=>A.i-$.i).pop();return S.i===-1?F$(this.first,f):S.fn(this.first,this.rest,n,T,f)}}function bS(o,n,T,f){let S=o instanceof Cn?o.value:o;if(S===void 0){if(o instanceof Cn?o.value=f.transform.undefined:S=o=f.transform.undefined,S===void 0)throw mo.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return"$"+T.push(o instanceof Cn?(n.push(o.value),o.array?o.array[o.type||jS(o.value)]||o.type||$0(o.value):o.type):(n.push(o),jS(o)))}var S0=J0(J1);function A$(o,n,T,f,S,A){for(let $=1;$<o.strings.length;$++)n+=$$(n,T,f,S,A)+o.strings[$],T=o.args[$];return n}function $$(o,n,T,f,S){return n instanceof hS?n.build(o,T,f,S):n instanceof wn?S$(n,T,f,S):n instanceof Nf?n.value:n&&n[0]instanceof wn?n.reduce((A,$)=>A+" "+S$($,T,f,S),""):bS(n,T,f,S)}function S$(o,n,T,f){return o.fragment=!0,A$(o,o.strings[0],o.args[0],n,T,f)}function A0(o,n,T,f,S){return o.map((A)=>"("+f.map(($)=>$$("values",A[$],n,T,S)).join(",")+")").join(",")}function f0(o,n,T,f,S){let A=Array.isArray(o[0]),$=n.length?n.flat():Object.keys(A?o[0]:o);return A0(A?o:[o],T,f,$,S)}function IS(o,n,T,f,S){if(typeof o==="string"&&(o=[o].concat(n)),Array.isArray(o))return F$(o,S);let A;return(n.length?n.flat():Object.keys(o)).map((F)=>{return A=o[F],(A instanceof wn?S$(A,T,f,S):A instanceof Nf?A.value:bS(A,T,f,S))+" as "+xS(S.transform.column.to?S.transform.column.to(F):F)}).join(",")}var t1=Object.entries({values:f0,in:(...o)=>{let n=f0(...o);return n==="()"?"(null)":n},select:IS,as:IS,returning:IS,"\\(":IS,update(o,n,T,f,S){return(n.length?n.flat():Object.keys(o)).map((A)=>xS(S.transform.column.to?S.transform.column.to(A):A)+"="+$$("values",o[A],T,f,S))},insert(o,n,T,f,S){let A=n.length?n.flat():Object.keys(Array.isArray(o)?o[0]:o);return"("+F$(A,S)+")values"+A0(Array.isArray(o)?o:[o],T,f,A,S)}}).map(([o,n])=>[new RegExp("((?:^|[\\s(])"+o+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),n]);function T$(){throw mo.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}var{serializers:R1,parsers:M1}=S0;function $0(o){if(Array.isArray(o))return $0(o[0]);return typeof o==="string"?1009:0}var F0=function(o){let n=J0(o||{});return{serializers:Object.assign({},R1,n.serializers),parsers:Object.assign({},M1,n.parsers)}};function J0(o){return Object.keys(o).reduce((n,T)=>{if(o[T].from&&[].concat(o[T].from).forEach((f)=>n.parsers[f]=o[T].parse),o[T].serialize)n.serializers[o[T].to]=o[T].serialize,o[T].from&&[].concat(o[T].from).forEach((f)=>n.serializers[f]=o[T].serialize);return n},{parsers:{},serializers:{}})}function F$(o,{transform:{column:n}}){return o.map((T)=>xS(n.to?n.to(T):T)).join(",")}var xS=function o(n){return'"'+n.replace(/"/g,'""').replace(/\./g,'"."')+'"'},jS=function o(n){return n instanceof Cn?n.type:n instanceof Date?1184:n instanceof Uint8Array?17:n===!0||n===!1?16:typeof n==="bigint"?20:Array.isArray(n)?o(n[0]):0},y1=/\\/g,k1=/"/g;function W1(o){return o.replace(y1,"\\\\").replace(k1,"\\\"")}var t0=function o(n,T,f,S){if(Array.isArray(n)===!1)return n;if(!n.length)return"{}";let A=n[0],$=S===1020?";":",";if(Array.isArray(A)&&!A.type)return"{"+n.map((F)=>o(F,T,f,S)).join($)+"}";return"{"+n.map((F)=>{if(F===void 0){if(F=f.transform.undefined,F===void 0)throw mo.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return F===null?"null":'"'+W1(T?T(F.type?F.value:F):""+F)+'"'}).join($)+"}"},f$={i:0,char:null,str:"",quoted:!1,last:0},R0=function o(n,T,f){return f$.i=f$.last=0,M0(f$,n,T,f)};function M0(o,n,T,f){let S=[],A=f===1020?";":",";for(;o.i<n.length;o.i++){if(o.char=n[o.i],o.quoted)if(o.char==="\\")o.str+=n[++o.i];else if(o.char==='"')S.push(T?T(o.str):o.str),o.str="",o.quoted=n[o.i+1]==='"',o.last=o.i+2;else o.str+=o.char;else if(o.char==='"')o.quoted=!0;else if(o.char==="{")o.last=++o.i,S.push(M0(o,n,T,f));else if(o.char==="}"){o.quoted=!1,o.last<o.i&&S.push(T?T(n.slice(o.last,o.i)):n.slice(o.last,o.i)),o.last=o.i+1;break}else if(o.char===A&&o.p!=="}"&&o.p!=='"')S.push(T?T(n.slice(o.last,o.i)):n.slice(o.last,o.i)),o.last=o.i+1;o.p=o.char}return o.last<o.i&&S.push(T?T(n.slice(o.last,o.i+1)):n.slice(o.last,o.i+1)),S}var OT=(o)=>{let n=o[0];for(let T=1;T<o.length;T++)n+=o[T]==="_"?o[++T].toUpperCase():o[T];return n},wT=(o)=>{let n=o[0].toUpperCase();for(let T=1;T<o.length;T++)n+=o[T]==="_"?o[++T].toUpperCase():o[T];return n},_T=(o)=>o.replace(/_/g,"-"),Cf=(o)=>o.replace(/([A-Z])/g,"_$1").toLowerCase(),If=(o)=>(o.slice(0,1)+o.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),jf=(o)=>o.replace(/-/g,"_");function J$(o){return function n(T,f){return typeof T==="object"&&T!==null&&(f.type===114||f.type===3802)?Array.isArray(T)?T.map((S)=>n(S,f)):Object.entries(T).reduce((S,[A,$])=>Object.assign(S,{[o(A)]:n($,f)}),{}):T}}OT.column={from:OT};OT.value={from:J$(OT)};Cf.column={to:Cf};var t$={...OT};t$.column.to=Cf;wT.column={from:wT};wT.value={from:J$(wT)};If.column={to:If};var R$={...wT};R$.column.to=If;_T.column={from:_T};_T.value={from:J$(_T)};jf.column={to:jf};var M$={..._T};M$.column.to=jf;import y0 from"net";import X1 from"tls";import hf from"crypto";import y$ from"stream";import{performance as k0}from"perf_hooks";class XT 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 Mn=O1;function O1(o=[]){let n=o.slice(),T=0;return{get length(){return n.length-T},remove:(f)=>{let S=n.indexOf(f);return S===-1?null:(n.splice(S,1),f)},push:(f)=>(n.push(f),f),shift:()=>{let f=n[T++];if(T===n.length)T=0,n=[];else n[T-1]=void 0;return f}}}var eo=Buffer.allocUnsafe(256),w1="BCcDdEFfHPpQSX".split("").reduce((o,n)=>{let T=n.charCodeAt(0);return o[n]=()=>{return eo[0]=T,yo.i=5,yo},o},{}),yo=Object.assign(_1,w1,{N:String.fromCharCode(0),i:0,inc(o){return yo.i+=o,yo},str(o){let n=Buffer.byteLength(o);return vS(n),yo.i+=eo.write(o,yo.i,n,"utf8"),yo},i16(o){return vS(2),eo.writeUInt16BE(o,yo.i),yo.i+=2,yo},i32(o,n){if(n||n===0)return eo.writeUInt32BE(o,n),yo;return vS(4),eo.writeUInt32BE(o,yo.i),yo.i+=4,yo},z(o){return vS(o),eo.fill(0,yo.i,yo.i+o),yo.i+=o,yo},raw(o){return eo=Buffer.concat([eo.subarray(0,yo.i),o]),yo.i=eo.length,yo},end(o=1){eo.writeUInt32BE(yo.i-o,o);let n=eo.subarray(0,yo.i);return yo.i=0,eo=Buffer.allocUnsafe(256),n}}),c=yo;function vS(o){if(eo.length-yo.i<o){let n=eo,T=n.length;eo=Buffer.allocUnsafe(T+(T>>1)+o),n.copy(eo)}}function _1(){return yo.i=0,yo}var O$=w0,K1=1,TT=c().S().end(),W0=c().H().end(),H1=c().i32(8).i32(80877103).end(8),E1=Buffer.concat([c().E().str(c.N).i32(0).end(),TT]),G1=c().D().str("S").str(c.N).end(),lT=()=>{},Y1=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),z1={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 w0(o,n={},{onopen:T=lT,onend:f=lT,onclose:S=lT}={}){let{ssl:A,max:$,user:F,host:J,port:t,database:R,parsers:W,transform:O,onnotice:_,onnotify:Q,onparameter:K,max_pipeline:B,keep_alive:h,backoff:r,target_session_attrs:P}=o,E=Mn(),z=K1++,U={pid:null,secret:null},D=W$(sS,o.idle_timeout),v=W$(sS,o.max_lifetime),l=W$(x0,o.connect_timeout),H=null,s,q=new XT,a=Buffer.alloc(0),ko=o.fetch_types,Bo={},Tn={},In=Math.random().toString(36).slice(2),G=1,p=0,Fo=0,Go=0,Lo=0,no=0,wo=0,Vo=0,Yo=null,Ko=null,Zo=!1,_o=null,_n=null,Po=null,cn=null,Co=null,Ho=null,Xn=null,Qn=null,m=null,aT=null,io={queue:n.closed,idleTimer:D,connect(M){Po=M||!0,p$()},terminate:nf,execute:of,cancel:j0,end:sS,count:0,id:z};return n.closed&&n.closed.push(io),io;async function I0(){let M;try{M=o.socket?await Promise.resolve(o.socket(o)):new y0.Socket}catch(w){GT(w);return}return M.on("error",GT),M.on("close",c$),M.on("drain",r$),M}async function j0({pid:M,secret:w},Z,Jo){try{s=c().i32(16).i32(80877102).i32(M).i32(w).end(16),await q$(),H.once("error",Jo),H.once("close",Z)}catch(Do){Jo(Do)}}function of(M){if(Zo)return cf(M,mo.connection("CONNECTION_DESTROYED",o));if(M.cancelled)return;try{return M.state=U,m?E.push(M):(m=M,m.active=!0),b0(M),ro(N0(M))&&!M.describeFirst&&!M.cursorFn&&E.length<B&&(!M.options.onexecute||M.options.onexecute(io))}catch(w){return E.length===0&&ro(TT),Un(w),!0}}function N0(M){if(M.parameters.length>=65534)throw mo.generic("MAX_PARAMETERS_EXCEEDED","Max number of parameters (65534) exceeded");return M.options.simple?c().Q().str(M.statement.string+c.N).end():M.describeFirst?Buffer.concat([b$(M),W0]):M.prepare?M.prepared?pf(M):Buffer.concat([b$(M),pf(M)]):h0(M)}function b$(M){return Buffer.concat([P$(M.statement.string,M.parameters,M.statement.types,M.statement.name),GM("S",M.statement.name)])}function pf(M){return Buffer.concat([EM(M.parameters,M.statement.types,M.statement.name,M.cursorName),M.cursorFn?i$("",M.cursorRows):E1])}function h0(M){return Buffer.concat([P$(M.statement.string,M.parameters,M.statement.types),G1,pf(M)])}function b0(M){let w=[],Z=[],Jo=A$(M,M.strings[0],M.args[0],w,Z,o);!M.tagged&&M.args.forEach((Do)=>bS(Do,w,Z,o)),M.prepare=o.prepare&&("prepare"in M.options?M.options.prepare:!0),M.string=Jo,M.signature=M.prepare&&Z+Jo,M.onlyDescribe&&delete Tn[M.signature],M.parameters=M.parameters||w,M.prepared=M.prepare&&M.signature in Tn,M.describeFirst=M.onlyDescribe||w.length&&!M.prepared,M.statement=M.prepared?Tn[M.signature]:{string:Jo,types:Z,name:M.prepare?In+G++:""},typeof o.debug==="function"&&o.debug(z,Jo,w,Z)}function ro(M,w){if(Ho=Ho?Buffer.concat([Ho,M]):Buffer.from(M),w||Ho.length>=1024)return x$(w);return Ko===null&&(Ko=setImmediate(x$)),!0}function x$(M){let w=H.write(Ho,M);return Ko!==null&&clearImmediate(Ko),Ho=Ko=null,w}function x0(){Un(mo.connection("CONNECT_TIMEOUT",o,H)),H.destroy()}async function v$(){if(ro(H1),!await new Promise((w)=>H.once("data",(Z)=>w(Z[0]===83)))&&A==="prefer")return ET();H.removeAllListeners(),H=X1.connect({socket:H,servername:y0.isIP(H.host)?void 0:H.host,...A==="require"||A==="allow"||A==="prefer"?{rejectUnauthorized:!1}:A==="verify-full"?{}:typeof A==="object"?A:{}}),H.on("secureConnect",ET),H.on("error",GT),H.on("close",c$),H.on("drain",r$)}function r$(){!m&&T(io)}function eS(M){if(_o){if(_o.push(M),Fo-=M.length,Fo>=0)return}a=_o?Buffer.concat(_o,no-Fo):a.length===0?M:Buffer.concat([a,M],a.length+M.length);while(a.length>4){if(no=a.readUInt32BE(1),no>=a.length){Fo=no-a.length,_o=[a];break}try{v0(a.subarray(0,no+1))}catch(w){m&&(m.cursorFn||m.describeFirst)&&ro(TT),Un(w)}a=a.subarray(no+1),Fo=0,_o=null}}async function q$(){if(Zo=!1,Bo={},H||(H=await I0()),!H)return;if(l.start(),o.socket)return A?v$():ET();if(H.on("connect",A?v$:ET),o.path)return H.connect(o.path);H.ssl=A,H.connect(t[Go],J[Go]),H.host=J[Go],H.port=t[Go],Go=(Go+1)%t.length}function p$(){setTimeout(q$,p?p+wo-k0.now():0)}function ET(){try{Tn={},ko=o.fetch_types,In=Math.random().toString(36).slice(2),G=1,v.start(),H.on("data",eS),h&&H.setKeepAlive&&H.setKeepAlive(!0,1000*h);let M=zM();ro(M)}catch(M){GT(M)}}function GT(M){if(io.queue===n.connecting&&o.host[Lo+1])return;Un(M);while(E.length)cf(E.shift(),M)}function Un(M){Co&&(Co.destroy(M),Co=null),m&&cf(m,M),Po&&(cf(Po,M),Po=null)}function cf(M,w){"query"in w||"parameters"in w||Object.defineProperties(w,{stack:{value:w.stack+M.origin.replace(/.*\n/,`
|
|
17
|
-
`),enumerable:o.debug},query:{value:M.string,enumerable:o.debug},parameters:{value:M.parameters,enumerable:o.debug},args:{value:M.args,enumerable:o.debug},types:{value:M.statement&&M.statement.types,enumerable:o.debug}}),M.reject(w)}function sS(){return
|
|
15
|
+
${O.trace}`:`No previous disposal trace for ${F} was found.`),n}let t=o.moleculeGraph.getRelationEntries({downstreamMoleculeKey:$.stringKey}).filter(([,{source:O}])=>O!==S).map(([O])=>xo(O));if(f)A.moleculeGraph.delete(S);A.moleculeGraph.set({upstreamMoleculeKey:J.stringKey,downstreamMoleculeKey:$.stringKey},{source:J.stringKey});let R={type:"molecule_transfer",key:$.key,from:t,to:[J.key]};if(Ro(A)&&A.transactionMeta.phase==="building")A.transactionMeta.update.updates.push(R);return n}function FA(o,T,n){switch(T){case"newValue":{_F(o,n);break}case"oldValue":{$n(n,o.token);break}}}function JA(o,T,n){switch(T){case"newValue":{$n(n,o.token);break}case"oldValue":{if(_F(o,n),o.subType==="atom")n.valueMap.set(o.token.key,o.value);break}}}function _F(o,T){let{family:n}=o.token;if(n){let f=T.families.get(n.key);if(f)i(T,f,xo(n.subKey))}}function XF(o,T,n){switch(T){case"newValue":fn(n,o.provenance,o.key);break;case"oldValue":Sn(n,o.key);break}}function HF(o,T,n){switch(T){case"newValue":Sn(n,o.key);break;case"oldValue":{let f=o.provenance.map(xo);fn(n,f,o.key);for(let[S,A]of o.values){let $=n.families.get(S);if($){i(n,$,o.key);let F=`${S}(${no(o.key)})`;n.valueMap.set(F,A)}}}break}}function KF(o,T,n){switch(T){case"newValue":{let f=o.to.length===1?o.to[0]:o.to;Yn(n,f,o.key,"exclusive")}break;case"oldValue":{let f=o.from.length===1?o.from[0]:o.from;Yn(n,f,o.key,"exclusive")}break}}function oS(o,T,n){let f=o==="newValue"?T.updates:[...T.updates].reverse();for(let S of f)switch(S.type){case"atom_update":case"selector_update":af(o,S,n);break;case"state_creation":FA(S,o,n);break;case"state_disposal":JA(S,o,n);break;case"molecule_creation":XF(S,o,n);break;case"molecule_disposal":HF(S,o,n);break;case"molecule_transfer":KF(S,o,n);break;case"transaction_update":oS(o,S,n);break}}function tA(o,T){return o.transactionMeta.actionContinuities.getRelatedKey(T)}function NM(o,T){return o.transactionMeta.epoch.get(T)}function EF(o,T){if(!qo(o))return;let f=tA(o,T);if(f===void 0)return;return NM(o,f)}function GF(o,T,n){if(qo(o)&&T)o.transactionMeta.epoch.set(T,n)}function YF(o,T,n){if(!qo(o))return;let S=tA(o,T);if(S!==void 0)o.transactionMeta.epoch.set(S,n)}var zF=(o,T)=>{let n=C(T),{parent:f}=n;if(f===null||!Ro(n)||n.transactionMeta?.phase!=="building"){T.logger.warn("\uD83D\uDC1E","transaction","???","applyTransaction called outside of a transaction. This is probably a bug in AtomIO.");return}n.transactionMeta.phase="applying",n.transactionMeta.update.output=o,f.child=null,f.on.transactionApplying.next(n.transactionMeta);let{updates:S}=n.transactionMeta.update;if(T.logger.info("\uD83D\uDEC4","transaction",n.transactionMeta.update.key,`Applying transaction with ${S.length} updates:`,S),oS("newValue",n.transactionMeta.update,f),qo(f))YF(f,n.transactionMeta.update.key,n.transactionMeta.update.epoch),$o(T,{key:n.transactionMeta.update.key,type:"transaction"})?.subject.next(n.transactionMeta.update),T.logger.info("\uD83D\uDEEC","transaction",n.transactionMeta.update.key,"Finished applying transaction.");else if(Ro(f))f.transactionMeta.update.updates.push(n.transactionMeta.update);f.on.transactionApplying.next(null)};function DF(o,T,n){if(!qo(o))return;let{epoch:S,actionContinuities:A}=o.transactionMeta;if(A.set(T,n),!S.has(T))S.set(T,-1)}function QF(o){return{store:o}}function to(o,...T){let n,f,S;if(T.length===1)n=T[0];else f=T[0],S=T[1],n=i(o,f,S);if("counterfeit"in n&&"family"in n){f=o.families.get(n.family.key);let A=n.family.subKey,$=o.disposalTraces.buffer.find((F)=>F?.key===A);switch(o.logger.error("\u274C",n.type,n.key,`could not be retrieved because it was not found in the store "${o.config.name}".`,$?`This state was previously disposed:
|
|
16
|
+
${$.trace}`:"No previous disposal trace was found."),f.type){case"atom_family":case"mutable_atom_family":return o.defaults.get(f.key);case"selector_family":case"readonly_selector_family":{if(o.defaults.has(f.key))return o.defaults.get(n.family.key);let F=$o(o,f).default(A);return o.defaults.set(f.key,F),F}}}return PT(o,$o(o,n))}class jo{a;b;cardinality;relations=new Map;contents=new Map;isAType;isBType;isContent;makeContentKey=(o,T)=>`${o}:${T}`;warn;getRelatedKeys(o){return this.relations.get(o)}addRelation(o,T){let n=this.relations.get(o),f=this.relations.get(T);if(n)n.add(T);else n=new Set([T]),this.relations.set(o,n);if(f)f.add(o);else f=new Set([o]),this.relations.set(T,f)}deleteRelation(o,T){let n=this.relations.get(o);if(n){if(n.delete(T),n.size===0)this.relations.delete(o);let f=this.relations.get(T);if(f){if(f.delete(o),f.size===0)this.relations.delete(T)}}}replaceRelationsUnsafely(o,T){this.relations.set(o,new Set(T));for(let n of T){let f=new Set().add(o);this.relations.set(n,f)}}replaceRelationsSafely(o,T){let n=this.relations.get(o),f=this.isAType?.(o)?o:void 0,S=f===void 0?o:void 0;if(n)for(let A of n){f??=A,S??=A;let $=this.relations.get(A);if($){if($.size===1)this.relations.delete(A);else $.delete(o);this.contents.delete(this.makeContentKey(f,S))}}this.relations.set(o,new Set(T));for(let A of T){let $=this.relations.get(A);if($)$.add(o);else $=new Set().add(o),this.relations.set(A,$)}}getContentInternal(o){return this.contents.get(o)}setContent(o,T){this.contents.set(o,T)}deleteContent(o){this.contents.delete(o)}constructor(o,T){if(this.a=o.between[0],this.b=o.between[1],this.cardinality=o.cardinality,!T?.externalStore)this.relations=new Map(o.relations?.map(([n,f])=>[n,new Set(f)])),this.contents=new Map(o.contents);if(this.isAType=T?.isAType??null,this.isBType=T?.isBType??null,this.isContent=T?.isContent??null,T?.makeContentKey)this.makeContentKey=T.makeContentKey;if(T?.externalStore){let n=T.externalStore;if(this.has=(f,S)=>n.has(f,S),this.addRelation=(f,S)=>{n.addRelation(f,S)},this.deleteRelation=(f,S)=>{n.deleteRelation(f,S)},this.replaceRelationsSafely=(f,S)=>{n.replaceRelationsSafely(f,S)},this.replaceRelationsUnsafely=(f,S)=>{n.replaceRelationsUnsafely(f,S)},this.getRelatedKeys=(f)=>n.getRelatedKeys(f),n.getContent)this.getContentInternal=(f)=>{return n.getContent(f)},this.setContent=(f,S)=>{n.setContent(f,S)},this.deleteContent=(f)=>{n.deleteContent(f)};for(let[f,S]of o.relations??[]){let A=this.isAType?.(f)?f:void 0,$=A===void 0?f:void 0;for(let F of S)A??=F,$??=F,this.addRelation(A,$)}for(let[f,S]of o.contents??[])this.setContent(f,S)}if(T?.warn)this.warn=T.warn}toJSON(){return{between:[this.a,this.b],cardinality:this.cardinality,relations:[...this.relations.entries()].map(([o,T])=>[o,[...T]]),contents:[...this.contents.entries()]}}set(...o){let T,n,f;switch(o.length){case 1:{let S=o[0];T=S[this.a],n=S[this.b],f=void 0;break}case 2:{let S=o[0];if(typeof S==="string")[T,n]=o;else T=S[this.a],n=S[this.b],f=o[1];break}default:{T=o[0],n=o[1],f=o[2];break}}switch(this.cardinality){case"1:1":{let S=this.getRelatedKey(T);if(S&&S!==n)this.delete(T,S)}case"1:n":{let S=this.getRelatedKey(n);if(S&&S!==T)this.delete(S,n)}break;case"n:n":}if(f){let S=this.makeContentKey(T,n);this.setContent(S,f)}return this.addRelation(T,n),this}delete(o,T){T=typeof T==="string"?T:o[this.b];let n=typeof o==="string"?o:o[this.a];if(n===void 0&&typeof T==="string"){let f=this.getRelatedKeys(T);if(f)for(let S of f)this.delete(S,T)}if(typeof n==="string"&&T===void 0){let f=this.getRelatedKeys(n);if(f)for(let S of f)this.delete(n,S)}if(typeof n==="string"&&typeof T==="string"){this.deleteRelation(n,T);let f=this.makeContentKey(n,T);this.deleteContent(f)}return this}getRelatedKey(o){let T=this.getRelatedKeys(o);if(T){if(T.size>1)this.warn?.(`${T.size} related keys were found for key "${o}": (${[...T].map((f)=>`"${f}"`).join(", ")}). Only one related key was expected.`);let n;for(let f of T){n=f;break}return n}}replaceRelations(o,T,n){let f=!Array.isArray(T),S=f?Object.keys(T):T;if(n?.reckless)this.replaceRelationsUnsafely(o,S);else this.replaceRelationsSafely(o,S);if(f)for(let A of S){let $=this.makeContentKey(o,A),F=T[A];this.setContent($,F)}return this}getContent(o,T){let n=this.makeContentKey(o,T);return this.getContentInternal(n)}getRelationEntries(o){let T=o[this.a],n=o[this.b];if(T!==void 0&&n===void 0){let f=this.getRelatedKeys(T);if(f)return[...f].map((S)=>{return[S,this.getContent(T,S)]})}if(T===void 0&&n!==void 0){let f=this.getRelatedKeys(n);if(f)return[...f].map((S)=>{return[S,this.getContent(S,n)]})}return[]}has(o,T){if(T)return this.getRelatedKeys(o)?.has(T)??!1;return this.relations.has(o)}}class kT extends Map{deleted=new Set;source;constructor(o){super();this.source=o}get(o){if(super.has(o))return super.get(o);if(!this.deleted.has(o)&&this.source.has(o))return this.source.get(o);return}set(o,T){return this.deleted.delete(o),super.set(o,T)}hasOwn(o){return super.has(o)}has(o){return!this.deleted.has(o)&&(super.has(o)||this.source.has(o))}delete(o){return this.deleted.add(o),super.delete(o)}}var UF=(o,T,n,f)=>{let S=C(o),A={parent:S,child:null,on:S.on,loggers:S.loggers,logger:S.logger,config:S.config,atoms:new kT(S.atoms),atomsThatAreDefault:new Set(S.atomsThatAreDefault),families:new kT(S.families),joins:new kT(S.joins),operation:{open:!1},readonlySelectors:new kT(S.readonlySelectors),timelines:new kT(S.timelines),timelineTopics:new jo(S.timelineTopics.toJSON()),trackers:new Map,transactions:new kT(S.transactions),selectorAtoms:new jo(S.selectorAtoms.toJSON()),selectorGraph:new jo(S.selectorGraph.toJSON(),{makeContentKey:(...t)=>t.sort().join(":")}),selectors:new kT(S.selectors),valueMap:new kT(S.valueMap),defaults:S.defaults,disposalTraces:o.disposalTraces.copy(),molecules:new kT(S.molecules),moleculeGraph:new jo(S.moleculeGraph.toJSON(),{makeContentKey:S.moleculeGraph.makeContentKey}),moleculeData:new jo(S.moleculeData.toJSON(),{makeContentKey:S.moleculeData.makeContentKey}),moleculeJoins:new jo(S.moleculeJoins.toJSON(),{makeContentKey:S.moleculeJoins.makeContentKey}),miscResources:new kT(S.miscResources)},$=EF(o,T),F={phase:"building",update:{type:"transaction_update",key:T,id:f,epoch:$===void 0?Number.NaN:$+1,updates:[],params:n,output:void 0},toolkit:{get:(...t)=>to(J,...t),set:(...t)=>{Uo(J,...t)},run:(t,R=Zf())=>zn(J,t,R),find:(t,R)=>i(J,t,R),json:(t)=>Io(J,t),dispose:(...t)=>{$n(J,...t)},env:()=>QF(J)}},J=Object.assign(A,{transactionMeta:F});return S.child=J,o.logger.info("\uD83D\uDEEB","transaction",T,"Building transaction with params:",n),J};function RA(o,T){let n={key:T.key,type:"transaction",run:(A,$)=>{let F=UF(o,T.key,A,$);try{let J=C(o),{toolkit:t}=F.transactionMeta,R=T.do(t,...A);return zF(R,J),R}catch(J){throw SF(f),o.logger.warn("\uD83D\uDCA5","transaction",T.key,"caught:",J),J}},install:(A)=>RA(A,T),subject:new oo},f=C(o);f.transactions.set(n.key,n);let S=fT(n);return o.on.transactionCreation.next(S),S}function tf(o){return RA(fo.STORE,o)}class VF{parent=null;child=null;valueMap=new Map;defaults=new Map;atoms=new Map;selectors=new Map;readonlySelectors=new Map;atomsThatAreDefault=new Set;selectorAtoms=new jo({between:["selectorKey","atomKey"],cardinality:"n:n"});selectorGraph=new jo({between:["upstreamSelectorKey","downstreamSelectorKey"],cardinality:"n:n"},{makeContentKey:(...o)=>o.sort().join(":")});trackers=new Map;families=new Map;joins=new Map;transactions=new Map;transactionMeta={epoch:new Map,actionContinuities:new jo({between:["continuity","action"],cardinality:"1:n"})};timelines=new Map;timelineTopics=new jo({between:["timelineKey","topicKey"],cardinality:"1:n"});disposalTraces=new gf(100);molecules=new Map;moleculeJoins=new jo({between:["moleculeKey","joinKey"],cardinality:"n:n"},{makeContentKey:(...o)=>o.sort().join(":")});moleculeGraph=new jo({between:["upstreamMoleculeKey","downstreamMoleculeKey"],cardinality:"n:n"},{makeContentKey:(...o)=>o.sort().join(":")});moleculeData=new jo({between:["moleculeKey","stateFamilyKey"],cardinality:"n:n"},{makeContentKey:(...o)=>o.sort().join(":")});miscResources=new Map;on={atomCreation:new oo,atomDisposal:new oo,selectorCreation:new oo,selectorDisposal:new oo,timelineCreation:new oo,transactionCreation:new oo,transactionApplying:new TA(null),operationClose:new oo,moleculeCreation:new oo,moleculeDisposal:new oo};operation={open:!1};config={name:"IMPLICIT_STORE",lifespan:"ephemeral"};loggers=[new SA("warn",(o,T,n)=>!iT(n))];logger={error:(...o)=>{for(let T of this.loggers)T.error(...o)},info:(...o)=>{for(let T of this.loggers)T.info(...o)},warn:(...o)=>{for(let T of this.loggers)T.warn(...o)}};constructor(o,T=null){if(this.config={...T?.config,...o},T!==null){if(this.valueMap=new Map(T?.valueMap),this.operation={...T?.operation},qo(T))this.transactionMeta={epoch:new Map(T?.transactionMeta.epoch),actionContinuities:new jo(T?.transactionMeta.actionContinuities.toJSON())};for(let[,f]of T.families){if(f.internalRoles?.includes("mutable")||f.internalRoles?.includes("join"))continue;f.install(this)}let n=new Set;for(let[,f]of T.atoms){if(n.has(f.key))continue;if(f.install(this),f.type==="mutable_atom"){let S=Io(T,f),A=bT(f);n.add(S.key),n.add(A.key)}}for(let[,f]of T.readonlySelectors)f.install(this);for(let[,f]of T.selectors){if(n.has(f.key))continue;f.install(this)}for(let[,f]of T.transactions)f.install(this);for(let[,f]of T.timelines)f.install(this)}}}var fo={get STORE(){return globalThis.ATOM_IO_IMPLICIT_STORE??=new VF({name:"IMPLICIT_STORE",lifespan:"ephemeral"}),globalThis.ATOM_IO_IMPLICIT_STORE}};function $o(o,T){let n,f=o;while(f!==null){switch(T.type){case"atom":case"mutable_atom":n=f.atoms.get(T.key);break;case"selector":n=f.selectors.get(T.key);break;case"readonly_selector":n=f.readonlySelectors.get(T.key);break;case"atom_family":case"mutable_atom_family":case"selector_family":case"readonly_selector_family":n=f.families.get(T.key);break;case"timeline":n=f.timelines.get(T.key);break;case"transaction":n=f.transactions.get(T.key);break}if(n)return n;f=f.child}throw new An(T,o)}function BF(o,T,n){let f=o.families.get(T.key);if(f===void 0)throw new An(T,o);let S=f(n),A=C(o);if(S.family){if(qo(A))switch(S.type){case"atom":case"mutable_atom":o.on.atomCreation.next(S);break;case"selector":case"readonly_selector":o.on.selectorCreation.next(S);break}else if(Ro(A)&&A.on.transactionApplying.state===null)A.transactionMeta.update.updates.push({type:"state_creation",token:S})}return S}function mF(o,T,n){let f=no(n),S=`${T.key}(${f})`,A=C(o),$;switch(T.type){case"atom_family":case"mutable_atom_family":$=A.atoms.get(S);break;case"selector_family":$=A.selectors.get(S);break;case"readonly_selector_family":$=A.readonlySelectors.get(S);break}if($)return fT($);return $}function i(o,T,n){let f=mF(o,T,n);if(f)return f;let S=no(n),A=o.molecules.get(S);if(!A&&o.config.lifespan==="immortal"){let $=u$(T,n);return o.logger.error("\u274C",$.type,$.key,`was not found in store "${o.config.name}"; returned a counterfeit token.`),$}if(f=BF(o,T,n),A)C(o).moleculeData.set(S,T.key);return f}function $n(o,...T){let n;if(T.length===1)n=T[0];else{let f=T[0],S=T[1];n=i(o,f,S)}try{$o(o,n)}catch(f){o.logger.error("\u274C",n.type,n.key,`could not be disposed because it was not found in the store "${o.config.name}".`);return}switch(n.type){case"atom":case"mutable_atom":MA(o,n);break;case"selector":case"readonly_selector":LF(o,n);break}}var TS=(o,T)=>C(o).atoms.has(T),bM=(o,T)=>C(o).selectors.has(T),xM=(o,T)=>C(o).readonlySelectors.has(T),CF=(o,T)=>TS(o,T)||bM(o,T)||xM(o,T);var nS=(o,T)=>{return C(T).selectorGraph.getRelationEntries({downstreamSelectorKey:o}).filter(([f,{source:S}])=>S!==o).map(([f,{source:S}])=>S).filter((f)=>CF(T,f))};var yA=(o,T,n)=>{let f=[],S=nS(o,n);while(S.length>0){let A=S.shift();if(T.has(A))continue;if(T.add(A),!TS(n,A))S.push(...nS(A,n));else if(!f.includes(A))f.push(A)}return f},IF=(o,T)=>{let n=o.key,f=nS(n,T),S=new Set;return f.flatMap((A)=>TS(T,A)?A:yA(A,S,T))};var jF=(o,T,n,f)=>{let S=C(f);if(T.type==="atom"||T.type==="mutable_atom")S.selectorAtoms.set({selectorKey:o,atomKey:T.key}),f.logger.info("\uD83D\uDD0D","selector",o,`discovers root atom "${T.key}"`);else{let A=yA(T.key,n,f);f.logger.info("\uD83D\uDD0D","selector",o,`discovers root atoms: [ ${A.map(($)=>`"${$}"`).join(", ")} ]`);for(let $ of A)S.selectorAtoms=S.selectorAtoms.set({selectorKey:o,atomKey:$})}n.add(T.key)};var fS=(o,T,n)=>({get:(...f)=>{let S=C(n),A;if(f.length===2){let[J,t]=f;A=i(n,J,t)}else[A]=f;let $=$o(n,A),F=PT(n,$);return n.logger.info("\uD83D\uDD0C","selector",o,`registers dependency ( "${A.key}" =`,F,")"),S.selectorGraph.set({upstreamSelectorKey:A.key,downstreamSelectorKey:o},{source:A.key}),jF(o,A,T,n),F},set:(...f)=>{let S,A;if(f.length===2)S=f[0],A=f[1];else{let J=f[0],t=f[1];A=f[2],S=i(n,J,t)}let $=C(n),F=$o($,S);sf($,F,A)},find:(f,S)=>i(n,f,S),json:(f)=>Io(n,f)});var Sf=(o,T,n)=>{let f=C(o),S=new oo,A=new Set,{get:$,find:F,json:J}=fS(T.key,A,f),t=()=>{let _=T.get({get:$,find:F,json:J});return yT(C(o),T.key,_,S),A.clear(),_},R={...T,subject:S,install:(_)=>Sf(_,T,n),get:t,type:"readonly_selector",...n&&{family:n}};f.readonlySelectors.set(T.key,R);let W=t();o.logger.info("\u2728",R.type,R.key,"=",W);let O={key:T.key,type:"readonly_selector"};if(n)O.family=n;return O};var Rf=(o,T,n)=>{let f=C(o),S=new oo,A=new Set,$=fS(T.key,A,f),{find:F,get:J,json:t}=$,R={find:F,get:J,json:t},W=(m=T.get,b=C(o))=>{let r=m(R);return yT(b,T.key,r,S),A.clear(),r},_={...T,subject:S,install:(m)=>Rf(m,T,n),get:W,set:(m)=>{let b=C(o),r=W(T.get,b),P=ef(m)(r);if(o.logger.info("\uD83D\uDCDD","selector",T.key,"set (",r,"->",P,")"),yT(b,T.key,P,S),Dn(b,T.key),qo(b))S.next({newValue:P,oldValue:r});T.set($,P)},type:"selector",...n&&{family:n}};f.selectors.set(T.key,_);let Q=W();o.logger.info("\u2728",_.type,_.key,"=",Q);let H={key:T.key,type:"selector"};if(n)H.family=n;return H};function jT(o,T){if("set"in T){let S=Rf(o,T,void 0);return o.on.selectorCreation.next(S),S}let f=Sf(o,T,void 0);return o.on.selectorCreation.next(f),f}function LF(o,T){let n=C(o),{key:f}=T,S=$o(n,T);if(!S.family)o.logger.error("\u274C","selector",f,"Standalone selectors cannot be disposed.");else{if(n.molecules.get(S.family.subKey))n.moleculeData.delete(S.family.subKey,S.family.key);let $;switch(T.type){case"selector":n.selectors.delete(f),$={key:S.family.key,type:"selector_family"},$o(o,$).subject.next({type:"state_disposal",subType:"selector",token:T});break;case"readonly_selector":n.readonlySelectors.delete(f),$={key:S.family.key,type:"readonly_selector_family"},$o(o,$).subject.next({type:"state_disposal",subType:"selector",token:T});break}if(n.valueMap.delete(f),n.selectorAtoms.delete(f),n.selectorGraph.delete(f),o.logger.info("\uD83D\uDD25",T.type,f,"deleted"),Ro(n)&&n.transactionMeta.phase==="building")n.transactionMeta.update.updates.push({type:"state_disposal",subType:"selector",token:T});else o.on.selectorDisposal.next(T)}}function Af(o,T,n){let f={key:T.key,type:"selector_family"},S=o.families.get(T.key);if(S)o.logger.error("\u2757","selector_family",T.key,`Overwriting an existing ${VT(S)} "${S.key}" in store "${o.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let A=new oo,F=Object.assign((J)=>{let t=no(J),R={key:T.key,subKey:t},W=`${T.key}(${t})`,O=C(o),_=Rf(O,{key:W,get:T.get(J),set:T.set(J)},R);return A.next({type:"state_creation",token:_}),_},f,{internalRoles:n,subject:A,install:(J)=>Af(J,T),default:(J)=>{return T.get(J)({get:(...R)=>to(o,...R),find:(R,W)=>i(o,R,W),json:(R)=>Io(o,R)})}});return o.families.set(T.key,F),f}function hF(o,T,n){return Af(o,{key:`${T.key}:JSON`,get:(S)=>({get:A})=>{let $=A(T,S);return n.toJson($)},set:(S)=>({set:A},$)=>{A(T,S,n.fromJson($))}},["mutable","json"])}var xo=(o)=>JSON.parse(o),no=(o)=>JSON.stringify(o),F2=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];var NF=(o,T)=>{let n=C(o);if(n.operation.open)return n.operation.prev.get(T.key);return n.valueMap.get(T.key)};var OA=(o,T)=>{let n=C(o);return IF(T,o).map((S)=>{let A=n.atoms.get(S);if(A===void 0)throw new Error(`Atom "${S}", a dependency of selector "${T.key}", not found in store "${o.config.name}".`);return A.subject.subscribe(`${T.type}:${T.key}`,($)=>{o.logger.info("\uD83D\uDCE2",T.type,T.key,"root",S,"went",$.oldValue,"->",$.newValue);let F=NF(n,T),J=PT(n,T);o.logger.info("\u2728",T.type,T.key,"went",F,"->",J),T.subject.next({newValue:J,oldValue:F})})})};function lo(o,T,n,f){function S(W){if(o.operation.open){let O=o.on.operationClose.subscribe(`state subscription ${n}`,()=>{O(),f(W)})}else f(W)}let A=$o(o,T);o.logger.info("\uD83D\uDC40",A.type,A.key,`Adding subscription "${n}"`);let $=A.type==="selector"||A.type==="readonly_selector",F=null,J=S;if($)F=OA(o,A),J=(W)=>{if(F)F.length=0,F.push(...OA(o,A));S(W)};let t=A.subject.subscribe(n,J);return()=>{if(o.logger.info("\uD83D\uDE48",A.type,A.key,`Removing subscription "${n}"`),t(),F)for(let W of F)W()}}var kA=(o,T,n,f)=>{let S=$o(o,T);o.logger.info("\uD83D\uDC40","timeline",T.key,`Adding subscription "${n}"`);let A=S.subject.subscribe(n,f);return()=>{o.logger.info("\uD83D\uDE48","timeline",T.key,`Removing subscription "${n}" from timeline`),A()}};var WA=(o,T,n,f)=>{let S=$o(o,T);o.logger.info("\uD83D\uDC40","transaction",T.key,`Adding subscription "${n}"`);let A=S.subject.subscribe(n,f);return()=>{o.logger.info("\uD83D\uDE48","transaction",T.key,`Removing subscription "${n}"`),A()}};class Fn{Update;initializeState(o,T){let n=`*${o.key}`;T.atoms.delete(n),T.valueMap.delete(n);let f=o.family?{key:`*${o.family.key}`,subKey:o.family.subKey}:void 0,S=FT(T,{key:n,default:null},f);if(T.parent?.valueMap.has(n)){let A=T.parent.valueMap.get(n);T.valueMap.set(n,A)}return S}unsubscribeFromInnerValue;unsubscribeFromState;observeCore(o,T,n){let f=`tracker:${n.config.name}:${Ro(n)?n.transactionMeta.update.key:"main"}:${o.key}`,S=to(n,o);this.unsubscribeFromInnerValue=S.subscribe(f,(A)=>{Uo(n,T,A)}),this.unsubscribeFromState=lo(n,o,f,(A)=>{if(A.newValue!==A.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=A.newValue.subscribe(f,($)=>{Uo(n,T,$)})})}updateCore(o,T,n){let f=`tracker:${n.config.name}:${Ro(n)?n.transactionMeta.update.key:"main"}:${o.key}`;lo(n,T,f,({newValue:S,oldValue:A})=>{let $=n.timelineTopics.getRelatedKey(T.key);if($){if(n.timelines.get($)?.timeTraveling){let t=kA(n,{key:$,type:"timeline"},f,(R)=>{t(),Uo(n,o,(W)=>{if(R==="redo"&&S)W.do(S);else if(R==="undo"&&A)W.undo(A);return W})});return}}let F=n.on.operationClose.subscribe(f,()=>{F();let J=to(n,o),t=S===null?-1:J.getUpdateNumber(S),R=t-J.cacheUpdateNumber;if(S&&R===1)Uo(n,o,(W)=>(W.do(S),W));else n.logger.info("\u274C","mutable_atom",o.key,`could not be updated. Expected update number ${J.cacheUpdateNumber+1}, but got ${t}`)})})}mutableState;latestUpdateState;[Symbol.dispose];constructor(o,T){this.mutableState=o;let n=C(T);this.latestUpdateState=this.initializeState(o,n),this.observeCore(o,this.latestUpdateState,n),this.updateCore(o,this.latestUpdateState,n),n.trackers.set(o.key,this),this[Symbol.dispose]=()=>{this.unsubscribeFromInnerValue(),this.unsubscribeFromState(),n.trackers.delete(o.key)}}}function Mf(o,T,n){o.logger.info("\uD83D\uDD28","atom",T.key,`creating in store "${o.config.name}"`);let f=C(o),S=f.atoms.get(T.key);if(S&&S.type==="mutable_atom")return o.logger.error("\u274C","atom",T.key,"Tried to create atom, but it already exists in the store."),fT(S);let A=new oo,$={...T,type:"mutable_atom",install:(t)=>{return t.logger.info("\uD83D\uDEE0\uFE0F","atom",T.key,`installing in store "${t.config.name}"`),Mf(t,T,n)},subject:A};if(n)$.family=n;let F=T.default();f.atoms.set($.key,$),SS(o,T.key),yT(f,T.key,F,A);let J=fT($);if(T.effects){let t=0,R=[];for(let W of T.effects){let O=W({setSelf:(_)=>{Uo(o,J,_)},onSet:(_)=>lo(o,J,`effect[${t}]`,_)});if(O)R.push(O);++t}$.cleanup=()=>{for(let W of R)W()}}if(new Fn(J,o),!n)d$(J,T,o);return J}class wA{trackers=new Map;Update;latestUpdateAtoms;mutableAtoms;constructor(o,T){let n=hT(T,{key:`*${o.key}`,default:null},["mutable","updates"]);this.latestUpdateAtoms=$o(T,n),this.mutableAtoms=o,this.mutableAtoms.subject.subscribe(`store=${T.config.name}::tracker-atom-family`,(f)=>{let{type:S,token:A}=f;if(A.family){let $=xo(A.family.subKey);switch(S){case"state_creation":this.trackers.set($,new Fn(A,T));break;case"state_disposal":{let F=this.trackers.get($);if(F)F[Symbol.dispose](),this.trackers.delete($)}break}}})}}function ff(o,T,n){let f={key:T.key,type:"mutable_atom_family"},S=o.families.get(T.key);if(S)o.logger.error("\u2757","mutable_atom_family",T.key,`Overwriting an existing ${VT(S)} "${S.key}" in store "${o.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let A=new oo,F=Object.assign((J)=>{let t=no(J),R={key:T.key,subKey:t},W=`${T.key}(${t})`,O=C(o),_={key:W,default:()=>T.default(J),toJson:T.toJson,fromJson:T.fromJson,mutable:!0};if(T.effects)_.effects=T.effects(J);let Q=Mf(O,_,R);return A.next({type:"state_creation",token:Q}),Q},f,{subject:A,install:(J)=>ff(J,T),toJson:T.toJson,fromJson:T.fromJson,internalRoles:n});return o.families.set(T.key,F),hF(o,F,T),new wA(F,o),f}var _A=(o,T)=>{let n=C(T),f=`${o.key}:JSON`;return n.families.get(f)};var Io=(o,T)=>{if(T.family){let f=C(o),A={key:`${T.family.key}:JSON`,type:"selector_family"},$=$o(f,A),F=JSON.parse(T.family.subKey);return i(o,$,F)}return{type:"selector",key:`${T.key}:JSON`}};var bT=(o)=>{let n={type:"atom",key:`*${o.key}`};if(o.family)n.family={key:`*${o.family.key}`,subKey:o.family.subKey};return n};function yF(o){return typeof o==="object"&&o!==null&&"do"in o&&"undo"in o&&"subscribe"in o}function Jf(o,T,n){let f=n.valueMap.get(T.key),S=o.valueMap.get(T.key);if(f!==S)return S;if(f===void 0)return T.default();n.logger.info("\uD83D\uDCC3","atom",T.key,"copying");let A=T.toJson(f),$=T.fromJson(A);return o.valueMap.set(T.key,$),new Fn(T,n),$}function yT(o,T,n,f){let S=o.valueMap.get(T);if(S instanceof nf)S.use(n);if(n instanceof Promise){let A=new nf(n);return o.valueMap.set(T,A),A.then(($)=>{yT(o,T,$,f),f.next({newValue:$,oldValue:A})}).catch(($)=>{o.logger.error("\uD83D\uDCA5","state",T,"rejected:",$)}),A}return o.valueMap.set(T,n),n}var AF=(o,T)=>{let n=T.valueMap.get(o.key);if(o.type==="mutable_atom"&&Ro(T)){let{parent:f}=T;n=Jf(T,o,f)}return n},RF=(o,T)=>{let n=T.valueMap.get(o);if(n instanceof nf){let f=n,S=T.selectors.get(o)??T.readonlySelectors.get(o);if(S)f.use(S.get());return}if(T.operation.open)T.operation.prev.set(o,n);T.valueMap.delete(o),T.logger.info("\uD83D\uDDD1","state",o,"evicted")};var kF=(o,T)=>{return C(o).atomsThatAreDefault.has(T)},SS=(o,T)=>{let n=C(o);n.atomsThatAreDefault=new Set(n.atomsThatAreDefault).add(T)},WF=(o,T)=>{let n=C(o);n.atomsThatAreDefault=new Set(C(o).atomsThatAreDefault),n.atomsThatAreDefault.delete(T)};function FT(o,T,n){o.logger.info("\uD83D\uDD28","atom",T.key,`creating in store "${o.config.name}"`);let f=C(o),S=f.atoms.get(T.key);if(S&&S.type==="atom")return o.logger.error("\u274C","atom",T.key,"Tried to create atom, but it already exists in the store."),fT(S);let A=new oo,$={...T,type:"atom",install:(t)=>{return t.logger.info("\uD83D\uDEE0\uFE0F","atom",T.key,`installing in store "${t.config.name}"`),FT(t,T,n)},subject:A};if(n)$.family=n;let F=T.default;if(T.default instanceof Function)F=T.default();f.atoms.set($.key,$),SS(o,T.key),yT(f,T.key,F,A);let J=fT($);if(T.effects){let t=0,R=[];for(let W of T.effects){let O=W({setSelf:(_)=>{Uo(o,J,_)},onSet:(_)=>lo(o,J,`effect[${t}]`,_)});if(O)R.push(O);++t}$.cleanup=()=>{for(let W of R)W()}}return J}function e$(o,T){if("mutable"in T){let S=Mf(o,T,void 0);return o.on.atomCreation.next(S),S}let f=FT(o,T,void 0);return o.on.atomCreation.next(f),f}function MA(o,T){let n=C(o),{key:f,family:S}=T,A=$o(n,T);if(!S)o.logger.error("\u274C","atom",f,"Standalone atoms cannot be disposed.");else{A.cleanup?.();let $=o.valueMap.get(A.key),F=$o(o,{key:S.key,type:"atom_family"}),J={type:"state_disposal",subType:"atom",token:T,value:$};F.subject.next(J);let t=Ro(n);if(n.atoms.delete(f),n.valueMap.delete(f),n.selectorAtoms.delete(f),n.atomsThatAreDefault.delete(f),o.timelineTopics.delete(f),T.type==="mutable_atom"){let R=bT(T);MA(o,R),o.trackers.delete(f)}if(o.logger.info("\uD83D\uDD25","atom",f,"deleted"),t&&n.transactionMeta.phase==="building"){let R=n.transactionMeta.update.updates.at(-1);if(!(R?.type==="molecule_disposal"&&R.values.some(([_])=>_===A.family?.key)))n.transactionMeta.update.updates.push(J)}else o.on.atomDisposal.next(T)}}class ho extends Set{mode="record";subject=new oo;cacheLimit=0;cache=[];cacheIdx=-1;cacheUpdateNumber=-1;constructor(o,T=0){super(o);if(o instanceof ho)this.parent=o,this.cacheUpdateNumber=o.cacheUpdateNumber;if(T)this.cacheLimit=T,this.cache=new Array(T),this.subscribe("auto cache",(n)=>{this.cacheIdx++,this.cacheIdx%=this.cacheLimit,this.cache[this.cacheIdx]=n})}toJSON(){return{members:[...this],cache:this.cache,cacheLimit:this.cacheLimit,cacheIdx:this.cacheIdx,cacheUpdateNumber:this.cacheUpdateNumber}}static fromJSON(o){let T=new ho(o.members,o.cacheLimit);return T.cache=o.cache,T.cacheIdx=o.cacheIdx,T.cacheUpdateNumber=o.cacheUpdateNumber,T}add(o){let T=super.add(o);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`add:${no(o)}`);return T}clear(){let o=this.mode==="record"?[...this]:null;if(super.clear(),o)this.cacheUpdateNumber++,this.emit(`clear:${JSON.stringify(o)}`)}delete(o){let T=super.delete(o);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`del:${no(o)}`);return T}parent;child=null;transactionUpdates=null;transaction(o){this.mode="transaction",this.transactionUpdates=[],this.child=new ho(this);let T=this.child._subscribe("transaction",(n)=>{this.transactionUpdates?.push(n)});try{if(o(this.child)){for(let f of this.transactionUpdates)this.doStep(f);this.cacheUpdateNumber++,this.emit(`tx:${this.transactionUpdates.join(";")}`)}}catch(n){throw console.warn("Did not apply transaction to SetRTX; this error was thrown:",n),n}finally{T(),this.child=null,this.transactionUpdates=null,this.mode="record"}}_subscribe(o,T){return this.subject.subscribe(o,T)}subscribe(o,T){return this.subject.subscribe(o,(n)=>{T(`${this.cacheUpdateNumber}=${n}`)})}emit(o){this.subject.next(o)}doStep(o){let T=o.indexOf(":"),n=o.substring(0,T),f=o.substring(T+1);switch(n){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 S of f.split(";"))this.doStep(S)}}getUpdateNumber(o){let T=o.indexOf("=");return Number(o.substring(0,T))}do(o){let T=o.indexOf("="),n=Number(o.substring(0,T)),f=n-this.cacheUpdateNumber;if(f>0){if(f===1){this.mode="playback";let A=o.substring(T+1);return this.doStep(A),this.mode="record",this.cacheUpdateNumber=n,null}return this.cacheUpdateNumber+1}if(Math.abs(f)<this.cacheLimit){let A=this.cacheIdx+f;if(this.cache[A]===o)return null;this.mode="playback";let F=!1;while(!F){this.cacheIdx%=this.cacheLimit;let t=this.cache[this.cacheIdx];if(this.cacheIdx--,!t)return"OUT_OF_RANGE";this.undo(t),F=this.cacheIdx===A-1}let J=o.substring(T+1);return this.doStep(J),this.mode="record",this.cacheUpdateNumber=n,null}return"OUT_OF_RANGE"}undoStep(o){let T=o.indexOf(":"),n=o.substring(0,T),f=o.substring(T+1);switch(n){case"add":this.delete(JSON.parse(f));break;case"del":this.add(JSON.parse(f));break;case"clear":{let S=JSON.parse(f);for(let A of S)this.add(A);break}case"tx":{let S=f.split(";");for(let A=S.length-1;A>=0;A--)this.undoStep(S[A])}}}undo(o){let T=o.indexOf("=");if(Number(o.substring(0,T))===this.cacheUpdateNumber){this.mode="playback";let f=o.substring(T+1);return this.undoStep(f),this.mode="record",this.cacheUpdateNumber--,null}return this.cacheUpdateNumber}}class $f{toolkit;options;defaultContent;molecules=new Map;relations;states;core;transact(o,T){let n=this.toolkit;this.toolkit=o,T(this),this.toolkit=n}store;realm;[Symbol.dispose](){}constructor(o,T,n=fo.STORE){this.store=n,this.realm=new AA(n),this.options=o,this.defaultContent=T,this.store.miscResources.set(`join:${o.key}`,this),this.realm.allocate("root",o.key),this.toolkit={get:(...E)=>to(n,...E),set:(...E)=>{Uo(n,...E)},find:(...E)=>i(n,...E),json:(E)=>Io(n,E)};let f=o.between[0],S=o.between[1],A=ff(n,{key:`${o.key}/relatedKeys`,default:()=>new ho,mutable:!0,fromJson:(E)=>ho.fromJSON(E),toJson:(E)=>E.toJSON()},["join","relations"]);this.core={relatedKeysAtoms:A};let $=({get:E},z)=>E(A,z),F=({set:E},z,U)=>{if(!this.store.molecules.has(no(z)))this.realm.allocate(o.key,z);E(A,z,(D)=>D.add(U)),E(A,U,(D)=>D.add(z))},J=({set:E},z,U)=>{E(A,z,(D)=>{return D.delete(U),D}),E(A,U,(D)=>{return D.delete(z),D})},t=(E,z,U)=>{let{find:D,get:v,set:l}=E,K=D(A,z),s=v(K);for(let q of s){if(U.includes(q))continue;l(A,q,(ko)=>{return ko.delete(z),ko})}l(K,(q)=>{return q.transaction((a)=>{a.clear();for(let ko of U){let mo=$(E,ko),nT=mo.has(z);if(this.relations.cardinality==="1:n"){let IT=[];for(let G of mo){if(G===z)continue;let p=$(E,G);if(p.delete(ko),p.size===0)IT.push(G)}if(!nT&&mo.size>0)mo.clear();for(let G of IT){let p=[ko,G].sort(),Fo=`"${p[0]}:${p[1]}"`;this.molecules.delete(Fo)}}if(!nT)mo.add(z);a.add(ko)}return!0}),q})},R=(E,z,U)=>{let{set:D}=E;D(A,z,(v)=>{return v.transaction((l)=>{for(let K of U)l.add(K);return!0}),v});for(let v of U)D(A,v,(l)=>{return l.add(z),l});return!0},W=(E,z,U)=>{let D=$(E,z);return U?D.has(U):D.size>0},O={getRelatedKeys:(E)=>$(this.toolkit,E),addRelation:(E,z)=>{this.store.moleculeJoins.set(E,o.key),this.store.moleculeJoins.set(z,o.key),F(this.toolkit,E,z)},deleteRelation:(E,z)=>{J(this.toolkit,E,z)},replaceRelationsSafely:(E,z)=>{t(this.toolkit,E,z)},replaceRelationsUnsafely:(E,z)=>{R(this.toolkit,E,z)},has:(E,z)=>W(this.toolkit,E,z)},_,Q;if(T){Q=hT(n,{key:`${o.key}/content`,default:T},["join","content"]);let E=({get:D},v)=>D(Q,v),z=({set:D},v,l)=>{D(Q,v,l)};_=Object.assign(O,{getContent:(D)=>{return E(this.toolkit,D)},setContent:(D,v)=>{z(this.toolkit,D,v)},deleteContent:(D)=>{this.realm.deallocate(D)}})}else _=O;let H=new jo(o,{externalStore:_,isAType:o.isAType,isBType:o.isBType,makeContentKey:(...E)=>{let[z,U]=E,D=E.sort(),v=`${D[0]}:${D[1]}`,l=n.molecules.get(no(z)),K=n.molecules.get(no(U));if(!l)this.realm.allocate(o.key,z);if(!K)this.realm.allocate(o.key,U);return this.realm.allocate(z,v,"all"),this.realm.claim(U,v),this.store.moleculeJoins.set(v,o.key),v}}),m=()=>NT(n,{key:`${o.key}/singleRelatedKey`,get:(E)=>({get:z})=>{let U=z(A,E);for(let D of U)return D;return null}},["join","keys"]),b=()=>{return NT(n,{key:`${o.key}/multipleRelatedKeys`,get:(E)=>({get:z})=>{let U=_A(A,n);return z(U,E).members}},["join","keys"])},r=()=>NT(n,{key:`${o.key}/singleRelatedEntry`,get:(E)=>({get:z})=>{let U=z(A,E);for(let D of U){let v=H.isAType?.(E)?E:void 0,l=v===void 0?E:void 0;v??=D,l??=D;let K=H.makeContentKey(v,l),s=z(Q,K);return[D,s]}return null}},["join","entries"]),P=()=>NT(n,{key:`${o.key}/multipleRelatedEntries`,get:(E)=>({get:z})=>{let U=_A(A,n);return z(U,E).members.map((v)=>{let l=H.isAType?.(E)?E:void 0,K=l===void 0?E:void 0;l??=v,K??=v;let s=H.makeContentKey(l,K),q=z(Q,s);return[v,q]})}},["join","entries"]);switch(o.cardinality){case"1:1":{let E=m(),z=`${f}KeyOf${Mo(S)}`,U=`${S}KeyOf${Mo(f)}`,D={[z]:E,[U]:E},v;if(T){let l=r(),K=`${f}EntryOf${Mo(S)}`,s=`${S}EntryOf${Mo(f)}`,q={[K]:l,[s]:l};v=Object.assign(D,q)}else v=D;this.relations=H,this.states=v;break}case"1:n":{let E=m(),z=b(),U=`${f}KeyOf${Mo(S)}`,D=`${S}KeysOf${Mo(f)}`,v={[U]:E,[D]:z},l;if(T){let K=r(),s=P(),q=`${f}EntryOf${Mo(S)}`,a=`${S}EntriesOf${Mo(f)}`,ko={[q]:K,[a]:s};l=Object.assign(v,ko)}else l=v;this.relations=H,this.states=l;break}case"n:n":{let E=b(),z=`${f}KeysOf${Mo(S)}`,U=`${S}KeysOf${Mo(f)}`,D={[z]:E,[U]:E},v;if(T){let l=P(),K=`${f}EntriesOf${Mo(S)}`,s=`${S}EntriesOf${Mo(f)}`,q={[K]:l,[s]:l};v=Object.assign(D,q)}else v=D;this.relations=H,this.states=v}}}}function Qn(o,T){let n=T.joins.get(o.key);if(n===void 0){let S=fo.STORE.joins.get(o.key);if(S===void 0)throw new Error(`Join "${o.key}" not found in store "${T.config.name}"`);n=new $f(S.options,S.defaultContent,T),T.joins.set(o.key,n)}return n}function Ff(o,T,n){let f=Qn(o,n),S=C(n);if(Ro(S)){let{toolkit:A}=S.transactionMeta;f.transact(A,({relations:$})=>{T($)})}else T(f.relations)}function lf(o,T,n){let f=Qn(o,n),S;switch(o.cardinality){case"1:1":{let A=`${o.a}KeyOf${Mo(o.b)}`,$=`${o.b}KeyOf${Mo(o.a)}`;S={get[A](){let J=f.states[A];return i(n,J,T)},get[$](){let J=f.states[$];return i(n,J,T)}};let F=`${o.a}EntryOf${Mo(o.b)}`;if(F in f.states){let J=`${o.b}EntryOf${Mo(o.a)}`;Object.assign(S,{get[F](){let t=f.states[F];return i(n,t,T)},get[J](){let t=f.states[J];return i(n,t,T)}})}break}case"1:n":{let A=`${o.a}KeyOf${Mo(o.b)}`,$=`${o.b}KeysOf${Mo(o.a)}`;S={get[A](){let J=f.states[A];return i(n,J,T)},get[$](){let J=f.states[$];return i(n,J,T)}};let F=`${o.a}EntryOf${Mo(o.b)}`;if(F in f.states){let J=`${o.b}EntriesOf${Mo(o.a)}`;Object.assign(S,{get[F](){let t=f.states[F];return i(n,t,T)},get[J](){let t=f.states[J];return i(n,t,T)}})}break}case"n:n":{let A=`${o.a}KeysOf${Mo(o.b)}`,$=`${o.b}KeysOf${Mo(o.a)}`;S={get[A](){let J=f.states[A];return i(n,J,T)},get[$](){let J=f.states[$];return i(n,J,T)}};let F=`${o.a}EntriesOf${Mo(o.b)}`;if(F in f.states){let J=`${o.b}EntriesOf${Mo(o.a)}`;Object.assign(S,{get[F](){let t=f.states[F];return i(n,t,T)},get[J](){let t=f.states[J];return i(n,t,T)}})}}}return S}function oF(o,T){return Qn(o,T).core.relatedKeysAtoms}function iT(o){return o.startsWith("\uD83D\uDD0D ")}var XA=(o)=>{let T=FT(o,{key:"\uD83D\uDD0D Atom Token Index (Internal)",default:()=>{let n=new Map;for(let[f,S]of o.atoms){if(iT(f))continue;let A=fT(S);if(S.family){let $=n.get(S.family.key);if(!$||!("familyMembers"in $))$={key:S.family.key,familyMembers:new Map},n.set(S.family.key,$);$.familyMembers.set(S.family.subKey,A)}else n.set(f,A)}return n},effects:[({setSelf:n})=>{o.on.atomCreation.subscribe("introspection",(f)=>{if(iT(f.key))return;n((S)=>{if(f.family){let{key:A,subKey:$}=f.family,F=S.get(A);if(F===void 0||!("familyMembers"in F))F={key:A,familyMembers:new Map},S.set(A,F);F.familyMembers.set($,f)}else S.set(f.key,f);return S})}),o.on.atomDisposal.subscribe("introspection",(f)=>{n((S)=>{if(f.family){let{key:A,subKey:$}=f.family,F=S.get(A);if(F&&"familyMembers"in F){if(F.familyMembers.delete($),F.familyMembers.size===0)S.delete(A)}}else S.delete(f.key);return S})})}]},void 0);return jT(o,{key:"\uD83D\uDD0D Atom Token Index",get:({get:n})=>n(T)})};var HA=(o)=>{let T=FT(o,{key:"\uD83D\uDD0D Selector Token Index (Internal)",default:()=>{let n=new Map;for(let f of[o.readonlySelectors,o.selectors])for(let[S,A]of f){if(iT(S))continue;let $=fT(A);if(A.family){let F=n.get(A.family.key);if(!F||!("familyMembers"in F))F={key:A.family.key,familyMembers:new Map},n.set(A.family.key,F);F.familyMembers.set(A.family.subKey,$)}else n.set(S,$)}return n},effects:[({setSelf:n})=>{o.on.selectorCreation.subscribe("introspection",(f)=>{if(iT(f.key))return;n((S)=>{if(f.family){let{key:A,subKey:$}=f.family,F=S.get(A);if(F===void 0||!("familyMembers"in F))F={key:A,familyMembers:new Map},S.set(A,F);F.familyMembers.set($,f)}else S.set(f.key,f);return S})}),o.on.selectorDisposal.subscribe("introspection",(f)=>{n((S)=>{if(f.family){let{key:A,subKey:$}=f.family,F=S.get(A);if(F&&"familyMembers"in F){if(F.familyMembers.delete($),F.familyMembers.size===0)S.delete(A)}}else S.delete(f.key);return S})})}]},void 0);return jT(o,{key:"\uD83D\uDD0D Selector Token Index",get:({get:n})=>n(T)})};class AS{supported;constructor(o){this.supported=o}refine(o){for(let[T,n]of Object.entries(this.supported))try{if(n(o)===!0&&n!==Boolean)return{type:T,data:o}}catch(f){try{if(o instanceof n)return{type:T,data:o}}catch(S){}}return null}}var KA=new AS({number:(o)=>typeof o==="number",string:(o)=>typeof o==="string",boolean:(o)=>typeof o==="boolean",null:(o)=>o===null});function EA(o){if(!o)return!1;return Object.getPrototypeOf(o)===Object.prototype}var GA=new AS({object:EA,array:(o)=>Array.isArray(o)}),vM=new AS({...KA.supported,...GA.supported}),Un=(o)=>{if(o===void 0)return"undefined";let T=vM.refine(o);if(T)return T.type;return Object.getPrototypeOf(o).constructor.name};class bF{store;auditorCreatedAt=performance.now();statesCreatedAt=new Map;atomIndex;selectorIndex;disposed=!1;unsubscribeFromAtomCreation;unsubscribeFromAtomDisposal;unsubscribeFromSelectorCreation;unsubscribeFromSelectorDisposal;constructor(o=fo.STORE){this.store=o,this.atomIndex=XA(this.store),this.selectorIndex=HA(this.store),this.unsubscribeFromAtomCreation=this.store.on.atomCreation.subscribe(`auditor-${this.auditorCreatedAt}`,({key:T})=>{this.statesCreatedAt.set(T,performance.now()-this.auditorCreatedAt)}),this.unsubscribeFromAtomDisposal=this.store.on.atomDisposal.subscribe(`auditor-${this.auditorCreatedAt}`,({key:T})=>{this.statesCreatedAt.delete(T)}),this.unsubscribeFromSelectorCreation=this.store.on.selectorCreation.subscribe(`auditor-${this.auditorCreatedAt}`,({key:T})=>{this.statesCreatedAt.set(T,performance.now()-this.auditorCreatedAt)}),this.unsubscribeFromSelectorDisposal=this.store.on.selectorDisposal.subscribe(`auditor-${this.auditorCreatedAt}`,({key:T})=>{this.statesCreatedAt.delete(T)})}static DEFAULT_LIST_RESOURCES_PARAM={atomFamilies:!0,selectorFamilies:!0};listResources(o=bF.DEFAULT_LIST_RESOURCES_PARAM){if(this.disposed)throw new Error("This Auditor has been disposed");let T=nA(this.atomIndex),n=nA(this.selectorIndex),f=[...T.values()].filter((F)=>("familyMembers"in F)),S=[...n.values()].filter((F)=>("familyMembers"in F)),A=performance.now(),$=[];if(o.atomFamilies)for(let F of f){let J=F.familyMembers.values();for(let t of J){let W=this.statesCreatedAt.get(t.key)??this.auditorCreatedAt,O=A-W;$.push([t,O])}}if(o.selectorFamilies)for(let F of S){let J=F.familyMembers.values();for(let t of J){let W=this.statesCreatedAt.get(t.key)??this.auditorCreatedAt,O=A-W;$.push([t,O])}}return $}[Symbol.dispose](){this.unsubscribeFromAtomCreation(),this.unsubscribeFromAtomDisposal(),this.unsubscribeFromSelectorCreation(),this.unsubscribeFromSelectorDisposal(),this.disposed=!0}}var YA=(o,T)=>{let n=(f,S)=>{let $=((J,t)=>{let R=T(J,t);if(R)return R;return null})(f,S);if($?.jobComplete??$?.pathComplete)return $;let F=Array.isArray(S)?S.map((J,t)=>[t,J]):EA(S)?Object.entries(S):[];for(let[J,t]of F){let R=n([...f,J],t);if(R?.jobComplete)return R}return{}};n([],o)};function rM(o,T){return{summary:`${o<T?"+":"-"}${Math.abs(o-T)} (${o} \u2192 ${T})`}}function qM(o,T){return{summary:`${o.length<T.length?"+":"-"}${Math.abs(o.length-T.length)} ("${o}" \u2192 "${T}")`}}function pM(o,T){return{summary:`${o} \u2192 ${T}`}}function xF(o,T,n){let f="",S=[],A=[],$=[];return YA(o,(F,J)=>{let t;for(t of F){let R=T[t];if(R===void 0)A.push([t,JSON.stringify(J)]);else{let W=n(J,R);if(W.summary!=="No Change")$.push([t,W])}}}),YA(T,(F,J)=>{let t;for(t of F)if(o[t]===void 0)S.push([t,JSON.stringify(J)])}),f=`\uFF5E${$.length} \uFF0B${S.length} \uFF0D${A.length}`,{summary:f,added:S,removed:A,changed:$}}function cM(o,T,n){return xF(o,T,n)}class vF{leafRefinery;treeRefinery;leafDiffers;treeDiffers;constructor(o,T,n){this.leafRefinery=o,this.treeRefinery=T,this.leafDiffers={},this.treeDiffers={};for(let f of Object.keys(o.supported)){let S=n[f];this.leafDiffers[f]=S}for(let f of Object.keys(T.supported)){let S=n[f];this.treeDiffers[f]=S}}diff(o,T){if(o===T)return{summary:"No Change"};let n=this.leafRefinery.refine(o)??this.treeRefinery.refine(o),f=this.leafRefinery.refine(T)??this.treeRefinery.refine(T);if(n!==null&&f!==null){if(n.type===f.type){if(n.type in this.leafDiffers)return this.leafDiffers[n.type](n.data,f.data);if(n.type in this.treeDiffers)return this.treeDiffers[n.type](n.data,f.data,(F,J)=>this.diff(F,J))}}let S=Un(o),A=Un(T);if(S===A)return{summary:`${S} \u2192 ${A}`};return{summary:`Type change: ${S} \u2192 ${A}`}}}var A8=new vF(KA,GA,{number:rM,string:qM,boolean:pM,null:()=>({summary:"No Change"}),object:xF,array:cM});class rF extends Map{set(o,T){if(this.has(o))return console.warn("Tried to set a key that already exists in an InvariantMap",{key:o,value:T}),this;return super.set(o,T)}clear(){throw new Error("Cannot clear an InvariantMap")}}class $S{type="continuity";globals=[];actions=[];perspectives=[];key;constructor(o){this.key=o}static existing=new rF;static create(o,T){let n=new $S(o),{type:f,globals:S,actions:A,perspectives:$}=T(n),F={type:f,key:o,globals:S,actions:A,perspectives:$};return $S.existing.set(o,F),F}add(...o){switch(o[0].type){case"atom":case"mutable_atom":this.globals.push(...o);break;case"transaction":this.actions.push(...o);break;case"atom_family":case"mutable_atom_family":{let[n,f]=o;this.perspectives.push({type:"realtime_perspective",resourceAtoms:n,viewAtoms:f})}break}return this}}function W8(o){let{key:T,config:n}=o,f=$S.create(T,n),{actions:S}=f;for(let A of S)DF(fo.STORE,T,A.key);return GF(fo.STORE,T,-1),f}var X8=Gn({key:"usersInRoomIndex",mutable:!0,default:()=>new ho,toJson:(o)=>o.toJSON(),fromJson:(o)=>ho.fromJSON(o)}),zA=Gn({key:"roomIndex",default:()=>new ho,mutable:!0,toJson:(o)=>o.toJSON(),fromJson:(o)=>ho.fromJSON(o)}),ZM={enteredAtEpoch:0},yf=df({key:"usersInRooms",between:["room","user"],cardinality:"1:n",isAType:(o)=>typeof o==="string",isBType:(o)=>typeof o==="string"},ZM),H8=uf({key:"usersInMyRoomView",get:(o)=>({find:T})=>{let n=a$(yf);return[T(n,o)]}});import{spawn as PM}from"node:child_process";class Vn{listeners;globalListeners;handleEvent(o,...T){for(let f of this.globalListeners)f(o,...T);let n=this.listeners.get(o);if(n)for(let f of n)f(...T)}id="no_id_retrieved";emit;constructor(o){this.emit=o,this.listeners=new Map,this.globalListeners=new Set}on(o,T){let n=this.listeners.get(o);if(n)n.add(T);else this.listeners.set(o,new Set([T]));return this}onAny(o){return this.globalListeners.add(o),this}off(o,T){let n=this.listeners.get(o);if(n)if(T)n.delete(T);else this.listeners.delete(o);return this}offAny(o){return this.globalListeners.delete(o),this}}class DA extends Vn{incompleteData="";unprocessedEvents=[];incompleteLog="";unprocessedLogs=[];id="#####";process;key;logger;handleLog(o){if(Array.isArray(o)){let[T,...n]=o;switch(T){case"i":this.logger.info(...n);break;case"w":this.logger.warn(...n);break;case"e":this.logger.error(...n);break;default:return}}}constructor(o,T,n){super((f,...S)=>{let A=JSON.stringify([f,...S])+"\x03",$=(F)=>{if(F.code==="EPIPE")console.error("EPIPE error during write",this.process.stdin);this.process.stdin.removeListener("error",$)};return this.process.stdin.once("error",$),this.process.stdin.write(A),this});if(this.process=o,this.key=T,this.logger=n??{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 S=f.toString();if(S==="ALIVE")return;this.unprocessedEvents.push(...S.split("\x03"));let A=this.unprocessedEvents.shift();this.incompleteData+=A??"";try{if(this.incompleteData.startsWith("error"))console.log("\u2757",this.incompleteData);let $=xo(this.incompleteData);this.handleEvent(...$);while(this.unprocessedEvents.length>0){let F=this.unprocessedEvents.shift();if(F){if(this.unprocessedEvents.length===0)this.incompleteData=F;$=xo(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 S=f.toString();this.unprocessedLogs.push(...S.split("\x03"));let A=this.unprocessedLogs.shift();this.incompleteLog+=A??"";try{let $=xo(this.incompleteLog);this.handleLog($);while(this.unprocessedLogs.length>0)if(this.incompleteLog=this.unprocessedLogs.shift()??"",this.incompleteLog)$=xo(this.incompleteLog),this.handleLog($)}catch($){console.error("\u274C\u274C\u274C"),console.error(this.incompleteLog),console.error($),console.error("\u274C\u274C\u274C\uFE0F")}}),o.pid)this.id=o.pid.toString()}}class qF extends Vn{in;out;id="no_id_retrieved";disposalFunctions=[];constructor(o){super((...T)=>{return this.out.next(T),this});this.id=o,this.in=new oo,this.out=new oo,this.in.subscribe("socket",(T)=>{this.handleEvent(...T)})}dispose(){for(let o of this.disposalFunctions)o()}}class QA extends Vn{incompleteData="";unprocessedEvents=[];relays;relayServices;process;id="#####";log(...o){this.process.stderr.write(no(o.map((T)=>T instanceof ho?`{ ${T.toJSON().members.join(" | ")} }`:T))+"\x03")}logger={info:(...o)=>{this.log("i",...o)},warn:(...o)=>{this.log("w",...o)},error:(...o)=>{this.log("e",...o)}};constructor(){super((o,...T)=>{let n=JSON.stringify([o,...T]);return this.process.stdout.write(n+"\x03"),this});if(this.process=process,this.process.stdin.resume(),this.relays=new Map,this.relayServices=[],this.process.stdin.on("data",(o)=>{let T=o.toString();this.unprocessedEvents.push(...T.split("\x03"));let n=this.unprocessedEvents.shift();this.incompleteData+=n??"";try{let f=xo(this.incompleteData);this.logger.info("\uD83C\uDFB0","received",f),this.handleEvent(...f);while(this.unprocessedEvents.length>0){let S=this.unprocessedEvents.shift();if(S){if(this.unprocessedEvents.length===0)this.incompleteData=S;let A=xo(S);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",(o)=>{this.logger.info("\uD83D\uDD25",this.id,`exited with code ${o}`)}),process.on("end",()=>{this.logger.info("\uD83D\uDD25",this.id,"ended"),process.exit(0)}),process.on("SIGTERM",()=>{this.logger.error("\uD83D\uDD25",this.id,"terminated"),process.exit(0)}),process.on("SIGINT",()=>{this.logger.error("\uD83D\uDD25",this.id,"interrupted"),process.exit(0)}),process.pid)this.id=process.pid?.toString();this.on("user-joins",(o)=>{this.logger.info("\uD83D\uDC64","user",o,"joined");let T=new qF(`user:${o}`);this.relays.set(o,T),this.logger.info("\uD83D\uDD17","attaching services:",`[${[...this.relayServices.keys()].join(", ")}]`);for(let n of this.relayServices){let f=n(T);if(f)T.disposalFunctions.push(f)}this.on(`user:${o}`,(...n)=>{T.in.next(n)}),T.out.subscribe("socket",(n)=>{this.emit(...n)})}),this.on("user-leaves",(o)=>{let T=this.relays.get(o);if(this.off(`relay:${o}`),T)T.dispose(),this.relays.delete(o)}),process.stdout.write("ALIVE")}relay(o){this.logger.info("\uD83D\uDD17","running relay method"),this.relayServices.push(o)}}var UA=nn({key:"roomArguments",default:["echo",["Hello World!"]]}),pF=uf({key:"room",get:(o)=>async({get:T,find:n})=>{let f=n(UA,o),S=T(f),[A,$]=S,F=await new Promise((J)=>{let t=PM(A,$,{env:process.env}),R=(W)=>{if(W.toString()==="ALIVE")t.stdout.off("data",R),J(t)};t.stdout.on("data",R)});return new DA(F,o)}});var i8=tf({key:"createRoom",do:({get:o,set:T,find:n},f,S,A)=>{let $=A?[S,A]:[S],F=n(UA,f);T(F,$),T(zA,(R)=>R.add(f));let J=n(pF,f);return o(J)}}),g8=tf({key:"joinRoom",do:(o,T,n,f)=>{let S={enteredAtEpoch:f};return Ff(yf,(A)=>{A.set({room:T,user:n},S)},o.env().store),S}}),d8=tf({key:"leaveRoom",do:(o,T,n)=>{Ff(yf,(f)=>{f.delete({room:T,user:n})},o.env().store)}}),l8=tf({key:"destroyRoom",do:(o,T)=>{Ff(yf,(n)=>{n.delete({room:T})},o.env().store),o.set(zA,(n)=>(n.delete(T),n))}});function VA(o,T){return T.map((n)=>{switch(n.type){case"transaction_update":{let f=VA(o,n.updates);return{...n,updates:f}}case"atom_update":case"selector_update":case"molecule_creation":case"molecule_disposal":case"molecule_transfer":case"state_creation":case"state_disposal":return n}}).filter((n)=>{switch(n.type){case"atom_update":case"selector_update":return o.includes(n.key);case"state_creation":case"state_disposal":return o.includes(n.token.key);case"molecule_creation":case"transaction_update":case"molecule_disposal":case"molecule_transfer":return!0}})}var s8=nn({key:"redactor",default:{occlude:(o)=>o}}),Bn=nn({key:"unacknowledgedUpdates",default:()=>[]});var cF=nn({key:"sockets",default:null}),nK=Gn({key:"socketsIndex",mutable:!0,default:()=>new ho,toJson:(o)=>o.toJSON(),fromJson:(o)=>ho.fromJSON(o)}),fK=Gn({key:"usersIndex",mutable:!0,default:()=>new ho,toJson:(o)=>o.toJSON(),fromJson:(o)=>ho.fromJSON(o)}),BA=df({key:"usersOfSockets",between:["user","socket"],cardinality:"1:1",isAType:(o)=>o.startsWith("user::"),isBType:(o)=>o.startsWith("socket::")});function ZF(o,T,n,f){let S=T.key;return function A(){let $=[];for(let J of T.globals){let t=J.type==="mutable_atom"?Io(o,J):J,R=to(o,t);$.push(t,R)}for(let J of T.perspectives){let{viewAtoms:t,resourceAtoms:R}=J,W=i(o,t,n),O=to(o,W);o.logger.info("\uD83D\uDC41","atom",R.key,`${n} can see`,{viewAtoms:t,resourceAtoms:R,userView:O});for(let _ of O){let Q=_.type==="mutable_atom"?Io(o,_):_,H=to(o,Q);$.push(Q,H)}}let F=qo(o)?o.transactionMeta.epoch.get(S)??null:null;f?.emit(`continuity-init:${S}`,F,$)}}function PF(o,T,n){let f=T.key;return function S(A){o.logger.info("\uD83D\uDECE\uFE0F","continuity",f,"received",A);let{key:$,id:F}=A,J=`tx-run:${$}:${F}`,t=`${J}:start`,R=`${J}:end`;performance.mark(t);try{zn(o,{type:"transaction",key:$},F)(...A.params)}catch(O){if(O instanceof Error)o.logger.error("\u274C","continuity",f,`failed to run transaction ${$} from ${n} with update ${F}`,O.message)}performance.mark(R);let W=performance.measure(J,t,R);o?.logger.info("\uD83D\uDE80","transaction",$,F,n,W.duration)}}function iF(o,T,n,f){let S=T.key;return function A($){if(o.logger.info("\uD83D\uDC4D","continuity",S,`${n} acknowledged epoch ${$}`),f[0]?.epoch===$)Uo(o,Bn,n,(J)=>{return J.shift(),o.logger.info("\uD83D\uDC4D","continuity",S,`${n} unacknowledged update queue now has`,J.length,"items"),J})}}function gF(o,T,n,f){let S=T.key,A=[];for(let $ of T.actions){let F=WA(o,$,`sync-continuity:${S}:${n}`,(J)=>{try{let t=T.globals.map((O)=>{if(O.type==="atom")return O.key;return bT(O).key}).concat(T.perspectives.flatMap((O)=>{let{viewAtoms:_}=O,Q=i(o,_,n);return to(o,Q).map((m)=>{return m.type==="mutable_atom"?"*"+m.key:m.key})})),R=VA(t,J.updates),W={...J,updates:R};Uo(o,Bn,n,(O)=>{if(W)O.push(W),O.sort((_,Q)=>_.epoch-Q.epoch),o.logger.info("\uD83D\uDC4D","continuity",S,`${n} unacknowledged update queue now has`,O.length,"items");return O}),f?.emit(`tx-new:${S}`,W)}catch(t){if(t instanceof Error)o.logger.error("\u274C","continuity",S,`${n} failed to send update from transaction ${$.key} to ${n}`,t.message)}});A.push(F)}return A}function dF(o,T,n,f){let S=T.key,A=[];for(let $ of T.perspectives){let{viewAtoms:F}=$,J=i(o,F,n),t=lo(o,J,`sync-continuity:${S}:${n}:perspective:${$.resourceAtoms.key}`,({oldValue:R,newValue:W})=>{let O=R.map((m)=>m.key),_=W.map((m)=>m.key),Q=R.filter((m)=>!_.includes(m.key)),H=W.filter((m)=>!O.includes(m.key)).flatMap((m)=>{let b=m.type==="mutable_atom"?Io(o,m):m,r=to(o,b);return[b,r]});if(o.logger.info("\uD83D\uDC41","atom",$.resourceAtoms.key,`${n} has a new perspective`,{oldKeys:O,newKeys:_,revealed:H,concealed:Q}),H.length>0)f?.emit(`reveal:${S}`,H);if(Q.length>0)f?.emit(`conceal:${S}`,Q)});A.push(t)}return A}function CK({socket:o,store:T=fo.STORE}){return function n(f){let S=o,A=f.key,$=lf(BA,`socket::${S.id}`,T).userKeyOfSocket,F=to(T,$);if(!F)return T.logger.error("\u274C","continuity",A,`Tried to create a synchronizer for a socket (${S.id}) that is not connected to a user.`),()=>{};let J=lf(BA,F,T).socketKeyOfUser,t=lo(T,J,`sync-continuity:${A}:${F}`,({newValue:b})=>{if(T.logger.info("\uD83D\uDC4B","continuity",A,`seeing ${F} on new socket ${b}`),b===null){T.logger.warn("\u274C","continuity",A,`User (${F}) is not connected to a socket, waiting for them to reappear.`);return}let r=i(T,cF,b);S=to(T,r);for(let E of R)S?.emit(`tx-new:${A}`,E)}),R=to(T,Bn,F),W=[],O=dF(T,f,F,S),_=gF(T,f,F,S);W.push(...O,..._);let Q=ZF(T,f,F,o);S.off(`get:${A}`,Q),S.on(`get:${A}`,Q);let H=PF(T,f,F);S.off(`tx-run:${A}`,H),S.on(`tx-run:${A}`,H);let m=iF(T,f,F,R);return S?.on(`ack:${A}`,m),()=>{for(let b of W)b();S?.off(`ack:${A}`,m),S?.off(`get:${A}`,Q),S?.off(`tx-run:${A}`,H)}}}var{file:h0,serve:Jk}=globalThis.Bun;import{readFileSync as tJ}from"node:fs";import{resolve as hA}from"node:path";function iM(o,T){let n={},f=[];for(let S in o){let A=o[S],$=T[S],F=A["~standard"].validate($);if(F instanceof Promise)throw new Error(`Validation must be synchronous, but ${S} returned a Promise.`);if(F.issues){f.push(...F.issues.map((J)=>({...J,path:[S,...J.path??[]]})));continue}n[S]=F.value}if(f.length)return{issues:f};return{value:n}}function lF(o){let T=o.runtimeEnvStrict??o.runtimeEnv??process.env;if(o.emptyStringAsUndefined??!1){for(let[r,P]of Object.entries(T))if(P==="")delete T[r]}if(!!o.skipValidation)return T;let S=typeof o.client==="object"?o.client:{},A=typeof o.server==="object"?o.server:{},$=typeof o.shared==="object"?o.shared:{},F=o.isServer??(typeof window==="undefined"||("Deno"in window)),J=F?{...A,...$,...S}:{...S,...$},t=iM(J,T),R=o.onValidationError??((r)=>{throw console.error("\u274C Invalid environment variables:",r),new Error("Invalid environment variables")}),W=o.onInvalidAccess??(()=>{throw new Error("\u274C Attempted to access a server-side environment variable on the client")});if(t.issues)return R(t.issues);let O=(r)=>{if(!o.clientPrefix)return!0;return!r.startsWith(o.clientPrefix)&&!(r in $)},_=(r)=>{return F||!O(r)},Q=(r)=>{return r==="__esModule"||r==="$$typeof"},H=(o.extends??[]).reduce((r,P)=>{return Object.assign(r,P)},{}),m=Object.assign(t.value,H);return new Proxy(m,{get(r,P){if(typeof P!=="string")return;if(Q(P))return;if(!_(P))return W(P);return Reflect.get(r,P)}})}var Ao;(function(o){o.assertEqual=(S)=>S;function T(S){}o.assertIs=T;function n(S){throw new Error}o.assertNever=n,o.arrayToEnum=(S)=>{let A={};for(let $ of S)A[$]=$;return A},o.getValidEnumValues=(S)=>{let A=o.objectKeys(S).filter((F)=>typeof S[S[F]]!=="number"),$={};for(let F of A)$[F]=S[F];return o.objectValues($)},o.objectValues=(S)=>{return o.objectKeys(S).map(function(A){return S[A]})},o.objectKeys=typeof Object.keys==="function"?(S)=>Object.keys(S):(S)=>{let A=[];for(let $ in S)if(Object.prototype.hasOwnProperty.call(S,$))A.push($);return A},o.find=(S,A)=>{for(let $ of S)if(A($))return $;return},o.isInteger=typeof Number.isInteger==="function"?(S)=>Number.isInteger(S):(S)=>typeof S==="number"&&isFinite(S)&&Math.floor(S)===S;function f(S,A=" | "){return S.map(($)=>typeof $==="string"?`'${$}'`:$).join(A)}o.joinValues=f,o.jsonStringifyReplacer=(S,A)=>{if(typeof A==="bigint")return A.toString();return A}})(Ao||(Ao={}));var LA;(function(o){o.mergeShapes=(T,n)=>{return{...T,...n}}})(LA||(LA={}));var h=Ao.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),vT=(o)=>{switch(typeof o){case"undefined":return h.undefined;case"string":return h.string;case"number":return isNaN(o)?h.nan:h.number;case"boolean":return h.boolean;case"function":return h.function;case"bigint":return h.bigint;case"symbol":return h.symbol;case"object":if(Array.isArray(o))return h.array;if(o===null)return h.null;if(o.then&&typeof o.then==="function"&&o.catch&&typeof o.catch==="function")return h.promise;if(typeof Map!=="undefined"&&o instanceof Map)return h.map;if(typeof Set!=="undefined"&&o instanceof Set)return h.set;if(typeof Date!=="undefined"&&o instanceof Date)return h.date;return h.object;default:return h.unknown}},Y=Ao.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),gM=(o)=>{return JSON.stringify(o,null,2).replace(/"([^"]+)":/g,"$1:")};class JT extends Error{get errors(){return this.issues}constructor(o){super();this.issues=[],this.addIssue=(n)=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let T=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,T);else this.__proto__=T;this.name="ZodError",this.issues=o}format(o){let T=o||function(S){return S.message},n={_errors:[]},f=(S)=>{for(let A of S.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)n._errors.push(T(A));else{let $=n,F=0;while(F<A.path.length){let J=A.path[F];if(F!==A.path.length-1)$[J]=$[J]||{_errors:[]};else $[J]=$[J]||{_errors:[]},$[J]._errors.push(T(A));$=$[J],F++}}};return f(this),n}static assert(o){if(!(o instanceof JT))throw new Error(`Not a ZodError: ${o}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Ao.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(o=(T)=>T.message){let T={},n=[];for(let f of this.issues)if(f.path.length>0)T[f.path[0]]=T[f.path[0]]||[],T[f.path[0]].push(o(f));else n.push(o(f));return{formErrors:n,fieldErrors:T}}get formErrors(){return this.flatten()}}JT.create=(o)=>{return new JT(o)};var In=(o,T)=>{let n;switch(o.code){case Y.invalid_type:if(o.received===h.undefined)n="Required";else n=`Expected ${o.expected}, received ${o.received}`;break;case Y.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(o.expected,Ao.jsonStringifyReplacer)}`;break;case Y.unrecognized_keys:n=`Unrecognized key(s) in object: ${Ao.joinValues(o.keys,", ")}`;break;case Y.invalid_union:n="Invalid input";break;case Y.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${Ao.joinValues(o.options)}`;break;case Y.invalid_enum_value:n=`Invalid enum value. Expected ${Ao.joinValues(o.options)}, received '${o.received}'`;break;case Y.invalid_arguments:n="Invalid function arguments";break;case Y.invalid_return_type:n="Invalid function return type";break;case Y.invalid_date:n="Invalid date";break;case Y.invalid_string:if(typeof o.validation==="object")if("includes"in o.validation){if(n=`Invalid input: must include "${o.validation.includes}"`,typeof o.validation.position==="number")n=`${n} at one or more positions greater than or equal to ${o.validation.position}`}else if("startsWith"in o.validation)n=`Invalid input: must start with "${o.validation.startsWith}"`;else if("endsWith"in o.validation)n=`Invalid input: must end with "${o.validation.endsWith}"`;else Ao.assertNever(o.validation);else if(o.validation!=="regex")n=`Invalid ${o.validation}`;else n="Invalid";break;case Y.too_small:if(o.type==="array")n=`Array must contain ${o.exact?"exactly":o.inclusive?"at least":"more than"} ${o.minimum} element(s)`;else if(o.type==="string")n=`String must contain ${o.exact?"exactly":o.inclusive?"at least":"over"} ${o.minimum} character(s)`;else if(o.type==="number")n=`Number must be ${o.exact?"exactly equal to ":o.inclusive?"greater than or equal to ":"greater than "}${o.minimum}`;else if(o.type==="date")n=`Date must be ${o.exact?"exactly equal to ":o.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(o.minimum))}`;else n="Invalid input";break;case Y.too_big:if(o.type==="array")n=`Array must contain ${o.exact?"exactly":o.inclusive?"at most":"less than"} ${o.maximum} element(s)`;else if(o.type==="string")n=`String must contain ${o.exact?"exactly":o.inclusive?"at most":"under"} ${o.maximum} character(s)`;else if(o.type==="number")n=`Number must be ${o.exact?"exactly":o.inclusive?"less than or equal to":"less than"} ${o.maximum}`;else if(o.type==="bigint")n=`BigInt must be ${o.exact?"exactly":o.inclusive?"less than or equal to":"less than"} ${o.maximum}`;else if(o.type==="date")n=`Date must be ${o.exact?"exactly":o.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(o.maximum))}`;else n="Invalid input";break;case Y.custom:n="Invalid input";break;case Y.invalid_intersection_types:n="Intersection results could not be merged";break;case Y.not_multiple_of:n=`Number must be a multiple of ${o.multipleOf}`;break;case Y.not_finite:n="Number must be finite";break;default:n=T.defaultError,Ao.assertNever(o)}return{message:n}},aF=In;function dM(o){aF=o}function FS(){return aF}var JS=(o)=>{let{data:T,path:n,errorMaps:f,issueData:S}=o,A=[...n,...S.path||[]],$={...S,path:A};if(S.message!==void 0)return{...S,path:A,message:S.message};let F="",J=f.filter((t)=>!!t).slice().reverse();for(let t of J)F=t($,{data:T,defaultError:F}).message;return{...S,path:A,message:F}},lM=[];function L(o,T){let n=FS(),f=JS({issueData:T,data:o.data,path:o.path,errorMaps:[o.common.contextualErrorMap,o.schemaErrorMap,n,n===In?void 0:In].filter((S)=>!!S)});o.common.issues.push(f)}class uo{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(o,T){let n=[];for(let f of T){if(f.status==="aborted")return d;if(f.status==="dirty")o.dirty();n.push(f.value)}return{status:o.value,value:n}}static async mergeObjectAsync(o,T){let n=[];for(let f of T){let S=await f.key,A=await f.value;n.push({key:S,value:A})}return uo.mergeObjectSync(o,n)}static mergeObjectSync(o,T){let n={};for(let f of T){let{key:S,value:A}=f;if(S.status==="aborted")return d;if(A.status==="aborted")return d;if(S.status==="dirty")o.dirty();if(A.status==="dirty")o.dirty();if(S.value!=="__proto__"&&(typeof A.value!=="undefined"||f.alwaysSet))n[S.value]=A.value}return{status:o.value,value:n}}}var d=Object.freeze({status:"aborted"}),Ln=(o)=>({status:"dirty",value:o}),ao=(o)=>({status:"valid",value:o}),CA=(o)=>o.status==="aborted",IA=(o)=>o.status==="dirty",Jn=(o)=>o.status==="valid",Of=(o)=>typeof Promise!=="undefined"&&o instanceof Promise;function tS(o,T,n,f){if(n==="a"&&!f)throw new TypeError("Private accessor was defined without a getter");if(typeof T==="function"?o!==T||!f:!T.has(o))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?f:n==="a"?f.call(o):f?f.value:T.get(o)}function oJ(o,T,n,f,S){if(f==="m")throw new TypeError("Private method is not writable");if(f==="a"&&!S)throw new TypeError("Private accessor was defined without a setter");if(typeof T==="function"?o!==T||!S:!T.has(o))throw new TypeError("Cannot write private member to an object whose class did not declare it");return f==="a"?S.call(o,n):S?S.value=n:T.set(o,n),n}var x;(function(o){o.errToObj=(T)=>typeof T==="string"?{message:T}:T||{},o.toString=(T)=>typeof T==="string"?T:T===null||T===void 0?void 0:T.message})(x||(x={}));var kf,Wf;class GT{constructor(o,T,n,f){this._cachedPath=[],this.parent=o,this.data=T,this._path=n,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 uF=(o,T)=>{if(Jn(T))return{success:!0,data:T.value};else{if(!o.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new JT(o.common.issues);return this._error=n,this._error}}}};function u(o){if(!o)return{};let{errorMap:T,invalid_type_error:n,required_error:f,description:S}=o;if(T&&(n||f))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(T)return{errorMap:T,description:S};return{errorMap:($,F)=>{var J,t;let{message:R}=o;if($.code==="invalid_enum_value")return{message:R!==null&&R!==void 0?R:F.defaultError};if(typeof F.data==="undefined")return{message:(J=R!==null&&R!==void 0?R:f)!==null&&J!==void 0?J:F.defaultError};if($.code!=="invalid_type")return{message:F.defaultError};return{message:(t=R!==null&&R!==void 0?R:n)!==null&&t!==void 0?t:F.defaultError}},description:S}}class e{get description(){return this._def.description}_getType(o){return vT(o.data)}_getOrReturnCtx(o,T){return T||{common:o.parent.common,data:o.data,parsedType:vT(o.data),schemaErrorMap:this._def.errorMap,path:o.path,parent:o.parent}}_processInputParams(o){return{status:new uo,ctx:{common:o.parent.common,data:o.data,parsedType:vT(o.data),schemaErrorMap:this._def.errorMap,path:o.path,parent:o.parent}}}_parseSync(o){let T=this._parse(o);if(Of(T))throw new Error("Synchronous parse encountered promise.");return T}_parseAsync(o){let T=this._parse(o);return Promise.resolve(T)}parse(o,T){let n=this.safeParse(o,T);if(n.success)return n.data;throw n.error}safeParse(o,T){var n;let f={common:{issues:[],async:(n=T===null||T===void 0?void 0:T.async)!==null&&n!==void 0?n:!1,contextualErrorMap:T===null||T===void 0?void 0:T.errorMap},path:(T===null||T===void 0?void 0:T.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:o,parsedType:vT(o)},S=this._parseSync({data:o,path:f.path,parent:f});return uF(f,S)}"~validate"(o){var T,n;let f={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:o,parsedType:vT(o)};if(!this["~standard"].async)try{let S=this._parseSync({data:o,path:[],parent:f});return Jn(S)?{value:S.value}:{issues:f.common.issues}}catch(S){if((n=(T=S===null||S===void 0?void 0:S.message)===null||T===void 0?void 0:T.toLowerCase())===null||n===void 0?void 0:n.includes("encountered"))this["~standard"].async=!0;f.common={issues:[],async:!0}}return this._parseAsync({data:o,path:[],parent:f}).then((S)=>Jn(S)?{value:S.value}:{issues:f.common.issues})}async parseAsync(o,T){let n=await this.safeParseAsync(o,T);if(n.success)return n.data;throw n.error}async safeParseAsync(o,T){let n={common:{issues:[],contextualErrorMap:T===null||T===void 0?void 0:T.errorMap,async:!0},path:(T===null||T===void 0?void 0:T.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:o,parsedType:vT(o)},f=this._parse({data:o,path:n.path,parent:n}),S=await(Of(f)?f:Promise.resolve(f));return uF(n,S)}refine(o,T){let n=(f)=>{if(typeof T==="string"||typeof T==="undefined")return{message:T};else if(typeof T==="function")return T(f);else return T};return this._refinement((f,S)=>{let A=o(f),$=()=>S.addIssue({code:Y.custom,...n(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(o,T){return this._refinement((n,f)=>{if(!o(n))return f.addIssue(typeof T==="function"?T(n,f):T),!1;else return!0})}_refinement(o){return new WT({schema:this,typeName:g.ZodEffects,effect:{type:"refinement",refinement:o}})}superRefine(o){return this._refinement(o)}constructor(o){this.spa=this.safeParseAsync,this._def=o,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:(T)=>this["~validate"](T)}}optional(){return ET.create(this,this._def)}nullable(){return rT.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return KT.create(this)}promise(){return yn.create(this,this._def)}or(o){return bn.create([this,o],this._def)}and(o){return xn.create(this,o,this._def)}transform(o){return new WT({...u(this._def),schema:this,typeName:g.ZodEffects,effect:{type:"transform",transform:o}})}default(o){let T=typeof o==="function"?o:()=>o;return new pn({...u(this._def),innerType:this,defaultValue:T,typeName:g.ZodDefault})}brand(){return new MS({typeName:g.ZodBranded,type:this,...u(this._def)})}catch(o){let T=typeof o==="function"?o:()=>o;return new cn({...u(this._def),innerType:this,catchValue:T,typeName:g.ZodCatch})}describe(o){return new this.constructor({...this._def,description:o})}pipe(o){return Ef.create(this,o)}readonly(){return Zn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var uM=/^c[^\s-]{8,}$/i,eM=/^[0-9a-z]+$/,sM=/^[0-9A-HJKMNP-TV-Z]{26}$/i,aM=/^[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,o1=/^[a-z0-9_-]{21}$/i,T1=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,n1=/^[-+]?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)?)??$/,f1=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,S1="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",mA,A1=/^(?:(?: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])$/,$1=/^(?:(?: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])$/,F1=/^(([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]))$/,J1=/^(([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])$/,t1=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,R1=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,TJ="((\\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])))",M1=new RegExp(`^${TJ}$`);function nJ(o){let T="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";if(o.precision)T=`${T}\\.\\d{${o.precision}}`;else if(o.precision==null)T=`${T}(\\.\\d+)?`;return T}function y1(o){return new RegExp(`^${nJ(o)}$`)}function fJ(o){let T=`${TJ}T${nJ(o)}`,n=[];if(n.push(o.local?"Z?":"Z"),o.offset)n.push("([+-]\\d{2}:?\\d{2})");return T=`${T}(${n.join("|")})`,new RegExp(`^${T}$`)}function k1(o,T){if((T==="v4"||!T)&&A1.test(o))return!0;if((T==="v6"||!T)&&F1.test(o))return!0;return!1}function W1(o,T){if(!T1.test(o))return!1;try{let[n]=o.split("."),f=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),S=JSON.parse(atob(f));if(typeof S!=="object"||S===null)return!1;if(!S.typ||!S.alg)return!1;if(T&&S.alg!==T)return!1;return!0}catch(n){return!1}}function O1(o,T){if((T==="v4"||!T)&&$1.test(o))return!0;if((T==="v6"||!T)&&J1.test(o))return!0;return!1}class HT extends e{_parse(o){if(this._def.coerce)o.data=String(o.data);if(this._getType(o)!==h.string){let S=this._getOrReturnCtx(o);return L(S,{code:Y.invalid_type,expected:h.string,received:S.parsedType}),d}let n=new uo,f=void 0;for(let S of this._def.checks)if(S.kind==="min"){if(o.data.length<S.value)f=this._getOrReturnCtx(o,f),L(f,{code:Y.too_small,minimum:S.value,type:"string",inclusive:!0,exact:!1,message:S.message}),n.dirty()}else if(S.kind==="max"){if(o.data.length>S.value)f=this._getOrReturnCtx(o,f),L(f,{code:Y.too_big,maximum:S.value,type:"string",inclusive:!0,exact:!1,message:S.message}),n.dirty()}else if(S.kind==="length"){let A=o.data.length>S.value,$=o.data.length<S.value;if(A||$){if(f=this._getOrReturnCtx(o,f),A)L(f,{code:Y.too_big,maximum:S.value,type:"string",inclusive:!0,exact:!0,message:S.message});else if($)L(f,{code:Y.too_small,minimum:S.value,type:"string",inclusive:!0,exact:!0,message:S.message});n.dirty()}}else if(S.kind==="email"){if(!f1.test(o.data))f=this._getOrReturnCtx(o,f),L(f,{validation:"email",code:Y.invalid_string,message:S.message}),n.dirty()}else if(S.kind==="emoji"){if(!mA)mA=new RegExp(S1,"u");if(!mA.test(o.data))f=this._getOrReturnCtx(o,f),L(f,{validation:"emoji",code:Y.invalid_string,message:S.message}),n.dirty()}else if(S.kind==="uuid"){if(!aM.test(o.data))f=this._getOrReturnCtx(o,f),L(f,{validation:"uuid",code:Y.invalid_string,message:S.message}),n.dirty()}else if(S.kind==="nanoid"){if(!o1.test(o.data))f=this._getOrReturnCtx(o,f),L(f,{validation:"nanoid",code:Y.invalid_string,message:S.message}),n.dirty()}else if(S.kind==="cuid"){if(!uM.test(o.data))f=this._getOrReturnCtx(o,f),L(f,{validation:"cuid",code:Y.invalid_string,message:S.message}),n.dirty()}else if(S.kind==="cuid2"){if(!eM.test(o.data))f=this._getOrReturnCtx(o,f),L(f,{validation:"cuid2",code:Y.invalid_string,message:S.message}),n.dirty()}else if(S.kind==="ulid"){if(!sM.test(o.data))f=this._getOrReturnCtx(o,f),L(f,{validation:"ulid",code:Y.invalid_string,message:S.message}),n.dirty()}else if(S.kind==="url")try{new URL(o.data)}catch(A){f=this._getOrReturnCtx(o,f),L(f,{validation:"url",code:Y.invalid_string,message:S.message}),n.dirty()}else if(S.kind==="regex"){if(S.regex.lastIndex=0,!S.regex.test(o.data))f=this._getOrReturnCtx(o,f),L(f,{validation:"regex",code:Y.invalid_string,message:S.message}),n.dirty()}else if(S.kind==="trim")o.data=o.data.trim();else if(S.kind==="includes"){if(!o.data.includes(S.value,S.position))f=this._getOrReturnCtx(o,f),L(f,{code:Y.invalid_string,validation:{includes:S.value,position:S.position},message:S.message}),n.dirty()}else if(S.kind==="toLowerCase")o.data=o.data.toLowerCase();else if(S.kind==="toUpperCase")o.data=o.data.toUpperCase();else if(S.kind==="startsWith"){if(!o.data.startsWith(S.value))f=this._getOrReturnCtx(o,f),L(f,{code:Y.invalid_string,validation:{startsWith:S.value},message:S.message}),n.dirty()}else if(S.kind==="endsWith"){if(!o.data.endsWith(S.value))f=this._getOrReturnCtx(o,f),L(f,{code:Y.invalid_string,validation:{endsWith:S.value},message:S.message}),n.dirty()}else if(S.kind==="datetime"){if(!fJ(S).test(o.data))f=this._getOrReturnCtx(o,f),L(f,{code:Y.invalid_string,validation:"datetime",message:S.message}),n.dirty()}else if(S.kind==="date"){if(!M1.test(o.data))f=this._getOrReturnCtx(o,f),L(f,{code:Y.invalid_string,validation:"date",message:S.message}),n.dirty()}else if(S.kind==="time"){if(!y1(S).test(o.data))f=this._getOrReturnCtx(o,f),L(f,{code:Y.invalid_string,validation:"time",message:S.message}),n.dirty()}else if(S.kind==="duration"){if(!n1.test(o.data))f=this._getOrReturnCtx(o,f),L(f,{validation:"duration",code:Y.invalid_string,message:S.message}),n.dirty()}else if(S.kind==="ip"){if(!k1(o.data,S.version))f=this._getOrReturnCtx(o,f),L(f,{validation:"ip",code:Y.invalid_string,message:S.message}),n.dirty()}else if(S.kind==="jwt"){if(!W1(o.data,S.alg))f=this._getOrReturnCtx(o,f),L(f,{validation:"jwt",code:Y.invalid_string,message:S.message}),n.dirty()}else if(S.kind==="cidr"){if(!O1(o.data,S.version))f=this._getOrReturnCtx(o,f),L(f,{validation:"cidr",code:Y.invalid_string,message:S.message}),n.dirty()}else if(S.kind==="base64"){if(!t1.test(o.data))f=this._getOrReturnCtx(o,f),L(f,{validation:"base64",code:Y.invalid_string,message:S.message}),n.dirty()}else if(S.kind==="base64url"){if(!R1.test(o.data))f=this._getOrReturnCtx(o,f),L(f,{validation:"base64url",code:Y.invalid_string,message:S.message}),n.dirty()}else Ao.assertNever(S);return{status:n.value,value:o.data}}_regex(o,T,n){return this.refinement((f)=>o.test(f),{validation:T,code:Y.invalid_string,...x.errToObj(n)})}_addCheck(o){return new HT({...this._def,checks:[...this._def.checks,o]})}email(o){return this._addCheck({kind:"email",...x.errToObj(o)})}url(o){return this._addCheck({kind:"url",...x.errToObj(o)})}emoji(o){return this._addCheck({kind:"emoji",...x.errToObj(o)})}uuid(o){return this._addCheck({kind:"uuid",...x.errToObj(o)})}nanoid(o){return this._addCheck({kind:"nanoid",...x.errToObj(o)})}cuid(o){return this._addCheck({kind:"cuid",...x.errToObj(o)})}cuid2(o){return this._addCheck({kind:"cuid2",...x.errToObj(o)})}ulid(o){return this._addCheck({kind:"ulid",...x.errToObj(o)})}base64(o){return this._addCheck({kind:"base64",...x.errToObj(o)})}base64url(o){return this._addCheck({kind:"base64url",...x.errToObj(o)})}jwt(o){return this._addCheck({kind:"jwt",...x.errToObj(o)})}ip(o){return this._addCheck({kind:"ip",...x.errToObj(o)})}cidr(o){return this._addCheck({kind:"cidr",...x.errToObj(o)})}datetime(o){var T,n;if(typeof o==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:o});return this._addCheck({kind:"datetime",precision:typeof(o===null||o===void 0?void 0:o.precision)==="undefined"?null:o===null||o===void 0?void 0:o.precision,offset:(T=o===null||o===void 0?void 0:o.offset)!==null&&T!==void 0?T:!1,local:(n=o===null||o===void 0?void 0:o.local)!==null&&n!==void 0?n:!1,...x.errToObj(o===null||o===void 0?void 0:o.message)})}date(o){return this._addCheck({kind:"date",message:o})}time(o){if(typeof o==="string")return this._addCheck({kind:"time",precision:null,message:o});return this._addCheck({kind:"time",precision:typeof(o===null||o===void 0?void 0:o.precision)==="undefined"?null:o===null||o===void 0?void 0:o.precision,...x.errToObj(o===null||o===void 0?void 0:o.message)})}duration(o){return this._addCheck({kind:"duration",...x.errToObj(o)})}regex(o,T){return this._addCheck({kind:"regex",regex:o,...x.errToObj(T)})}includes(o,T){return this._addCheck({kind:"includes",value:o,position:T===null||T===void 0?void 0:T.position,...x.errToObj(T===null||T===void 0?void 0:T.message)})}startsWith(o,T){return this._addCheck({kind:"startsWith",value:o,...x.errToObj(T)})}endsWith(o,T){return this._addCheck({kind:"endsWith",value:o,...x.errToObj(T)})}min(o,T){return this._addCheck({kind:"min",value:o,...x.errToObj(T)})}max(o,T){return this._addCheck({kind:"max",value:o,...x.errToObj(T)})}length(o,T){return this._addCheck({kind:"length",value:o,...x.errToObj(T)})}nonempty(o){return this.min(1,x.errToObj(o))}trim(){return new HT({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new HT({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new HT({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((o)=>o.kind==="datetime")}get isDate(){return!!this._def.checks.find((o)=>o.kind==="date")}get isTime(){return!!this._def.checks.find((o)=>o.kind==="time")}get isDuration(){return!!this._def.checks.find((o)=>o.kind==="duration")}get isEmail(){return!!this._def.checks.find((o)=>o.kind==="email")}get isURL(){return!!this._def.checks.find((o)=>o.kind==="url")}get isEmoji(){return!!this._def.checks.find((o)=>o.kind==="emoji")}get isUUID(){return!!this._def.checks.find((o)=>o.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((o)=>o.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((o)=>o.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((o)=>o.kind==="cuid2")}get isULID(){return!!this._def.checks.find((o)=>o.kind==="ulid")}get isIP(){return!!this._def.checks.find((o)=>o.kind==="ip")}get isCIDR(){return!!this._def.checks.find((o)=>o.kind==="cidr")}get isBase64(){return!!this._def.checks.find((o)=>o.kind==="base64")}get isBase64url(){return!!this._def.checks.find((o)=>o.kind==="base64url")}get minLength(){let o=null;for(let T of this._def.checks)if(T.kind==="min"){if(o===null||T.value>o)o=T.value}return o}get maxLength(){let o=null;for(let T of this._def.checks)if(T.kind==="max"){if(o===null||T.value<o)o=T.value}return o}}HT.create=(o)=>{var T;return new HT({checks:[],typeName:g.ZodString,coerce:(T=o===null||o===void 0?void 0:o.coerce)!==null&&T!==void 0?T:!1,...u(o)})};function w1(o,T){let n=(o.toString().split(".")[1]||"").length,f=(T.toString().split(".")[1]||"").length,S=n>f?n:f,A=parseInt(o.toFixed(S).replace(".","")),$=parseInt(T.toFixed(S).replace(".",""));return A%$/Math.pow(10,S)}class dT extends e{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(o){if(this._def.coerce)o.data=Number(o.data);if(this._getType(o)!==h.number){let S=this._getOrReturnCtx(o);return L(S,{code:Y.invalid_type,expected:h.number,received:S.parsedType}),d}let n=void 0,f=new uo;for(let S of this._def.checks)if(S.kind==="int"){if(!Ao.isInteger(o.data))n=this._getOrReturnCtx(o,n),L(n,{code:Y.invalid_type,expected:"integer",received:"float",message:S.message}),f.dirty()}else if(S.kind==="min"){if(S.inclusive?o.data<S.value:o.data<=S.value)n=this._getOrReturnCtx(o,n),L(n,{code:Y.too_small,minimum:S.value,type:"number",inclusive:S.inclusive,exact:!1,message:S.message}),f.dirty()}else if(S.kind==="max"){if(S.inclusive?o.data>S.value:o.data>=S.value)n=this._getOrReturnCtx(o,n),L(n,{code:Y.too_big,maximum:S.value,type:"number",inclusive:S.inclusive,exact:!1,message:S.message}),f.dirty()}else if(S.kind==="multipleOf"){if(w1(o.data,S.value)!==0)n=this._getOrReturnCtx(o,n),L(n,{code:Y.not_multiple_of,multipleOf:S.value,message:S.message}),f.dirty()}else if(S.kind==="finite"){if(!Number.isFinite(o.data))n=this._getOrReturnCtx(o,n),L(n,{code:Y.not_finite,message:S.message}),f.dirty()}else Ao.assertNever(S);return{status:f.value,value:o.data}}gte(o,T){return this.setLimit("min",o,!0,x.toString(T))}gt(o,T){return this.setLimit("min",o,!1,x.toString(T))}lte(o,T){return this.setLimit("max",o,!0,x.toString(T))}lt(o,T){return this.setLimit("max",o,!1,x.toString(T))}setLimit(o,T,n,f){return new dT({...this._def,checks:[...this._def.checks,{kind:o,value:T,inclusive:n,message:x.toString(f)}]})}_addCheck(o){return new dT({...this._def,checks:[...this._def.checks,o]})}int(o){return this._addCheck({kind:"int",message:x.toString(o)})}positive(o){return this._addCheck({kind:"min",value:0,inclusive:!1,message:x.toString(o)})}negative(o){return this._addCheck({kind:"max",value:0,inclusive:!1,message:x.toString(o)})}nonpositive(o){return this._addCheck({kind:"max",value:0,inclusive:!0,message:x.toString(o)})}nonnegative(o){return this._addCheck({kind:"min",value:0,inclusive:!0,message:x.toString(o)})}multipleOf(o,T){return this._addCheck({kind:"multipleOf",value:o,message:x.toString(T)})}finite(o){return this._addCheck({kind:"finite",message:x.toString(o)})}safe(o){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:x.toString(o)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:x.toString(o)})}get minValue(){let o=null;for(let T of this._def.checks)if(T.kind==="min"){if(o===null||T.value>o)o=T.value}return o}get maxValue(){let o=null;for(let T of this._def.checks)if(T.kind==="max"){if(o===null||T.value<o)o=T.value}return o}get isInt(){return!!this._def.checks.find((o)=>o.kind==="int"||o.kind==="multipleOf"&&Ao.isInteger(o.value))}get isFinite(){let o=null,T=null;for(let n of this._def.checks)if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;else if(n.kind==="min"){if(T===null||n.value>T)T=n.value}else if(n.kind==="max"){if(o===null||n.value<o)o=n.value}return Number.isFinite(T)&&Number.isFinite(o)}}dT.create=(o)=>{return new dT({checks:[],typeName:g.ZodNumber,coerce:(o===null||o===void 0?void 0:o.coerce)||!1,...u(o)})};class lT extends e{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(o){if(this._def.coerce)try{o.data=BigInt(o.data)}catch(S){return this._getInvalidInput(o)}if(this._getType(o)!==h.bigint)return this._getInvalidInput(o);let n=void 0,f=new uo;for(let S of this._def.checks)if(S.kind==="min"){if(S.inclusive?o.data<S.value:o.data<=S.value)n=this._getOrReturnCtx(o,n),L(n,{code:Y.too_small,type:"bigint",minimum:S.value,inclusive:S.inclusive,message:S.message}),f.dirty()}else if(S.kind==="max"){if(S.inclusive?o.data>S.value:o.data>=S.value)n=this._getOrReturnCtx(o,n),L(n,{code:Y.too_big,type:"bigint",maximum:S.value,inclusive:S.inclusive,message:S.message}),f.dirty()}else if(S.kind==="multipleOf"){if(o.data%S.value!==BigInt(0))n=this._getOrReturnCtx(o,n),L(n,{code:Y.not_multiple_of,multipleOf:S.value,message:S.message}),f.dirty()}else Ao.assertNever(S);return{status:f.value,value:o.data}}_getInvalidInput(o){let T=this._getOrReturnCtx(o);return L(T,{code:Y.invalid_type,expected:h.bigint,received:T.parsedType}),d}gte(o,T){return this.setLimit("min",o,!0,x.toString(T))}gt(o,T){return this.setLimit("min",o,!1,x.toString(T))}lte(o,T){return this.setLimit("max",o,!0,x.toString(T))}lt(o,T){return this.setLimit("max",o,!1,x.toString(T))}setLimit(o,T,n,f){return new lT({...this._def,checks:[...this._def.checks,{kind:o,value:T,inclusive:n,message:x.toString(f)}]})}_addCheck(o){return new lT({...this._def,checks:[...this._def.checks,o]})}positive(o){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:x.toString(o)})}negative(o){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:x.toString(o)})}nonpositive(o){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:x.toString(o)})}nonnegative(o){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:x.toString(o)})}multipleOf(o,T){return this._addCheck({kind:"multipleOf",value:o,message:x.toString(T)})}get minValue(){let o=null;for(let T of this._def.checks)if(T.kind==="min"){if(o===null||T.value>o)o=T.value}return o}get maxValue(){let o=null;for(let T of this._def.checks)if(T.kind==="max"){if(o===null||T.value<o)o=T.value}return o}}lT.create=(o)=>{var T;return new lT({checks:[],typeName:g.ZodBigInt,coerce:(T=o===null||o===void 0?void 0:o.coerce)!==null&&T!==void 0?T:!1,...u(o)})};class jn extends e{_parse(o){if(this._def.coerce)o.data=Boolean(o.data);if(this._getType(o)!==h.boolean){let n=this._getOrReturnCtx(o);return L(n,{code:Y.invalid_type,expected:h.boolean,received:n.parsedType}),d}return ao(o.data)}}jn.create=(o)=>{return new jn({typeName:g.ZodBoolean,coerce:(o===null||o===void 0?void 0:o.coerce)||!1,...u(o)})};class tn extends e{_parse(o){if(this._def.coerce)o.data=new Date(o.data);if(this._getType(o)!==h.date){let S=this._getOrReturnCtx(o);return L(S,{code:Y.invalid_type,expected:h.date,received:S.parsedType}),d}if(isNaN(o.data.getTime())){let S=this._getOrReturnCtx(o);return L(S,{code:Y.invalid_date}),d}let n=new uo,f=void 0;for(let S of this._def.checks)if(S.kind==="min"){if(o.data.getTime()<S.value)f=this._getOrReturnCtx(o,f),L(f,{code:Y.too_small,message:S.message,inclusive:!0,exact:!1,minimum:S.value,type:"date"}),n.dirty()}else if(S.kind==="max"){if(o.data.getTime()>S.value)f=this._getOrReturnCtx(o,f),L(f,{code:Y.too_big,message:S.message,inclusive:!0,exact:!1,maximum:S.value,type:"date"}),n.dirty()}else Ao.assertNever(S);return{status:n.value,value:new Date(o.data.getTime())}}_addCheck(o){return new tn({...this._def,checks:[...this._def.checks,o]})}min(o,T){return this._addCheck({kind:"min",value:o.getTime(),message:x.toString(T)})}max(o,T){return this._addCheck({kind:"max",value:o.getTime(),message:x.toString(T)})}get minDate(){let o=null;for(let T of this._def.checks)if(T.kind==="min"){if(o===null||T.value>o)o=T.value}return o!=null?new Date(o):null}get maxDate(){let o=null;for(let T of this._def.checks)if(T.kind==="max"){if(o===null||T.value<o)o=T.value}return o!=null?new Date(o):null}}tn.create=(o)=>{return new tn({checks:[],coerce:(o===null||o===void 0?void 0:o.coerce)||!1,typeName:g.ZodDate,...u(o)})};class wf extends e{_parse(o){if(this._getType(o)!==h.symbol){let n=this._getOrReturnCtx(o);return L(n,{code:Y.invalid_type,expected:h.symbol,received:n.parsedType}),d}return ao(o.data)}}wf.create=(o)=>{return new wf({typeName:g.ZodSymbol,...u(o)})};class hn extends e{_parse(o){if(this._getType(o)!==h.undefined){let n=this._getOrReturnCtx(o);return L(n,{code:Y.invalid_type,expected:h.undefined,received:n.parsedType}),d}return ao(o.data)}}hn.create=(o)=>{return new hn({typeName:g.ZodUndefined,...u(o)})};class Nn extends e{_parse(o){if(this._getType(o)!==h.null){let n=this._getOrReturnCtx(o);return L(n,{code:Y.invalid_type,expected:h.null,received:n.parsedType}),d}return ao(o.data)}}Nn.create=(o)=>{return new Nn({typeName:g.ZodNull,...u(o)})};class Rn extends e{constructor(){super(...arguments);this._any=!0}_parse(o){return ao(o.data)}}Rn.create=(o)=>{return new Rn({typeName:g.ZodAny,...u(o)})};class gT extends e{constructor(){super(...arguments);this._unknown=!0}_parse(o){return ao(o.data)}}gT.create=(o)=>{return new gT({typeName:g.ZodUnknown,...u(o)})};class BT extends e{_parse(o){let T=this._getOrReturnCtx(o);return L(T,{code:Y.invalid_type,expected:h.never,received:T.parsedType}),d}}BT.create=(o)=>{return new BT({typeName:g.ZodNever,...u(o)})};class _f extends e{_parse(o){if(this._getType(o)!==h.undefined){let n=this._getOrReturnCtx(o);return L(n,{code:Y.invalid_type,expected:h.void,received:n.parsedType}),d}return ao(o.data)}}_f.create=(o)=>{return new _f({typeName:g.ZodVoid,...u(o)})};class KT extends e{_parse(o){let{ctx:T,status:n}=this._processInputParams(o),f=this._def;if(T.parsedType!==h.array)return L(T,{code:Y.invalid_type,expected:h.array,received:T.parsedType}),d;if(f.exactLength!==null){let A=T.data.length>f.exactLength.value,$=T.data.length<f.exactLength.value;if(A||$)L(T,{code:A?Y.too_big:Y.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}),n.dirty()}if(f.minLength!==null){if(T.data.length<f.minLength.value)L(T,{code:Y.too_small,minimum:f.minLength.value,type:"array",inclusive:!0,exact:!1,message:f.minLength.message}),n.dirty()}if(f.maxLength!==null){if(T.data.length>f.maxLength.value)L(T,{code:Y.too_big,maximum:f.maxLength.value,type:"array",inclusive:!0,exact:!1,message:f.maxLength.message}),n.dirty()}if(T.common.async)return Promise.all([...T.data].map((A,$)=>{return f.type._parseAsync(new GT(T,A,T.path,$))})).then((A)=>{return uo.mergeArray(n,A)});let S=[...T.data].map((A,$)=>{return f.type._parseSync(new GT(T,A,T.path,$))});return uo.mergeArray(n,S)}get element(){return this._def.type}min(o,T){return new KT({...this._def,minLength:{value:o,message:x.toString(T)}})}max(o,T){return new KT({...this._def,maxLength:{value:o,message:x.toString(T)}})}length(o,T){return new KT({...this._def,exactLength:{value:o,message:x.toString(T)}})}nonempty(o){return this.min(1,o)}}KT.create=(o,T)=>{return new KT({type:o,minLength:null,maxLength:null,exactLength:null,typeName:g.ZodArray,...u(T)})};function mn(o){if(o instanceof zo){let T={};for(let n in o.shape){let f=o.shape[n];T[n]=ET.create(mn(f))}return new zo({...o._def,shape:()=>T})}else if(o instanceof KT)return new KT({...o._def,type:mn(o.element)});else if(o instanceof ET)return ET.create(mn(o.unwrap()));else if(o instanceof rT)return rT.create(mn(o.unwrap()));else if(o instanceof mT)return mT.create(o.items.map((T)=>mn(T)));else return o}class zo extends e{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let o=this._def.shape(),T=Ao.objectKeys(o);return this._cached={shape:o,keys:T}}_parse(o){if(this._getType(o)!==h.object){let J=this._getOrReturnCtx(o);return L(J,{code:Y.invalid_type,expected:h.object,received:J.parsedType}),d}let{status:n,ctx:f}=this._processInputParams(o),{shape:S,keys:A}=this._getCached(),$=[];if(!(this._def.catchall instanceof BT&&this._def.unknownKeys==="strip")){for(let J in f.data)if(!A.includes(J))$.push(J)}let F=[];for(let J of A){let t=S[J],R=f.data[J];F.push({key:{status:"valid",value:J},value:t._parse(new GT(f,R,f.path,J)),alwaysSet:J in f.data})}if(this._def.catchall instanceof BT){let J=this._def.unknownKeys;if(J==="passthrough")for(let t of $)F.push({key:{status:"valid",value:t},value:{status:"valid",value:f.data[t]}});else if(J==="strict"){if($.length>0)L(f,{code:Y.unrecognized_keys,keys:$}),n.dirty()}else if(J==="strip");else throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let J=this._def.catchall;for(let t of $){let R=f.data[t];F.push({key:{status:"valid",value:t},value:J._parse(new GT(f,R,f.path,t)),alwaysSet:t in f.data})}}if(f.common.async)return Promise.resolve().then(async()=>{let J=[];for(let t of F){let R=await t.key,W=await t.value;J.push({key:R,value:W,alwaysSet:t.alwaysSet})}return J}).then((J)=>{return uo.mergeObjectSync(n,J)});else return uo.mergeObjectSync(n,F)}get shape(){return this._def.shape()}strict(o){return x.errToObj,new zo({...this._def,unknownKeys:"strict",...o!==void 0?{errorMap:(T,n)=>{var f,S,A,$;let F=(A=(S=(f=this._def).errorMap)===null||S===void 0?void 0:S.call(f,T,n).message)!==null&&A!==void 0?A:n.defaultError;if(T.code==="unrecognized_keys")return{message:($=x.errToObj(o).message)!==null&&$!==void 0?$:F};return{message:F}}}:{}})}strip(){return new zo({...this._def,unknownKeys:"strip"})}passthrough(){return new zo({...this._def,unknownKeys:"passthrough"})}extend(o){return new zo({...this._def,shape:()=>({...this._def.shape(),...o})})}merge(o){return new zo({unknownKeys:o._def.unknownKeys,catchall:o._def.catchall,shape:()=>({...this._def.shape(),...o._def.shape()}),typeName:g.ZodObject})}setKey(o,T){return this.augment({[o]:T})}catchall(o){return new zo({...this._def,catchall:o})}pick(o){let T={};return Ao.objectKeys(o).forEach((n)=>{if(o[n]&&this.shape[n])T[n]=this.shape[n]}),new zo({...this._def,shape:()=>T})}omit(o){let T={};return Ao.objectKeys(this.shape).forEach((n)=>{if(!o[n])T[n]=this.shape[n]}),new zo({...this._def,shape:()=>T})}deepPartial(){return mn(this)}partial(o){let T={};return Ao.objectKeys(this.shape).forEach((n)=>{let f=this.shape[n];if(o&&!o[n])T[n]=f;else T[n]=f.optional()}),new zo({...this._def,shape:()=>T})}required(o){let T={};return Ao.objectKeys(this.shape).forEach((n)=>{if(o&&!o[n])T[n]=this.shape[n];else{let S=this.shape[n];while(S instanceof ET)S=S._def.innerType;T[n]=S}}),new zo({...this._def,shape:()=>T})}keyof(){return SJ(Ao.objectKeys(this.shape))}}zo.create=(o,T)=>{return new zo({shape:()=>o,unknownKeys:"strip",catchall:BT.create(),typeName:g.ZodObject,...u(T)})};zo.strictCreate=(o,T)=>{return new zo({shape:()=>o,unknownKeys:"strict",catchall:BT.create(),typeName:g.ZodObject,...u(T)})};zo.lazycreate=(o,T)=>{return new zo({shape:o,unknownKeys:"strip",catchall:BT.create(),typeName:g.ZodObject,...u(T)})};class bn extends e{_parse(o){let{ctx:T}=this._processInputParams(o),n=this._def.options;function f(S){for(let $ of S)if($.result.status==="valid")return $.result;for(let $ of S)if($.result.status==="dirty")return T.common.issues.push(...$.ctx.common.issues),$.result;let A=S.map(($)=>new JT($.ctx.common.issues));return L(T,{code:Y.invalid_union,unionErrors:A}),d}if(T.common.async)return Promise.all(n.map(async(S)=>{let A={...T,common:{...T.common,issues:[]},parent:null};return{result:await S._parseAsync({data:T.data,path:T.path,parent:A}),ctx:A}})).then(f);else{let S=void 0,A=[];for(let F of n){let J={...T,common:{...T.common,issues:[]},parent:null},t=F._parseSync({data:T.data,path:T.path,parent:J});if(t.status==="valid")return t;else if(t.status==="dirty"&&!S)S={result:t,ctx:J};if(J.common.issues.length)A.push(J.common.issues)}if(S)return T.common.issues.push(...S.ctx.common.issues),S.result;let $=A.map((F)=>new JT(F));return L(T,{code:Y.invalid_union,unionErrors:$}),d}}get options(){return this._def.options}}bn.create=(o,T)=>{return new bn({options:o,typeName:g.ZodUnion,...u(T)})};var xT=(o)=>{if(o instanceof vn)return xT(o.schema);else if(o instanceof WT)return xT(o.innerType());else if(o instanceof rn)return[o.value];else if(o instanceof uT)return o.options;else if(o instanceof qn)return Ao.objectValues(o.enum);else if(o instanceof pn)return xT(o._def.innerType);else if(o instanceof hn)return[void 0];else if(o instanceof Nn)return[null];else if(o instanceof ET)return[void 0,...xT(o.unwrap())];else if(o instanceof rT)return[null,...xT(o.unwrap())];else if(o instanceof MS)return xT(o.unwrap());else if(o instanceof Zn)return xT(o.unwrap());else if(o instanceof cn)return xT(o._def.innerType);else return[]};class RS extends e{_parse(o){let{ctx:T}=this._processInputParams(o);if(T.parsedType!==h.object)return L(T,{code:Y.invalid_type,expected:h.object,received:T.parsedType}),d;let n=this.discriminator,f=T.data[n],S=this.optionsMap.get(f);if(!S)return L(T,{code:Y.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),d;if(T.common.async)return S._parseAsync({data:T.data,path:T.path,parent:T});else return S._parseSync({data:T.data,path:T.path,parent:T})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(o,T,n){let f=new Map;for(let S of T){let A=xT(S.shape[o]);if(!A.length)throw new Error(`A discriminator value for key \`${o}\` could not be extracted from all schema options`);for(let $ of A){if(f.has($))throw new Error(`Discriminator property ${String(o)} has duplicate value ${String($)}`);f.set($,S)}}return new RS({typeName:g.ZodDiscriminatedUnion,discriminator:o,options:T,optionsMap:f,...u(n)})}}function jA(o,T){let n=vT(o),f=vT(T);if(o===T)return{valid:!0,data:o};else if(n===h.object&&f===h.object){let S=Ao.objectKeys(T),A=Ao.objectKeys(o).filter((F)=>S.indexOf(F)!==-1),$={...o,...T};for(let F of A){let J=jA(o[F],T[F]);if(!J.valid)return{valid:!1};$[F]=J.data}return{valid:!0,data:$}}else if(n===h.array&&f===h.array){if(o.length!==T.length)return{valid:!1};let S=[];for(let A=0;A<o.length;A++){let $=o[A],F=T[A],J=jA($,F);if(!J.valid)return{valid:!1};S.push(J.data)}return{valid:!0,data:S}}else if(n===h.date&&f===h.date&&+o===+T)return{valid:!0,data:o};else return{valid:!1}}class xn extends e{_parse(o){let{status:T,ctx:n}=this._processInputParams(o),f=(S,A)=>{if(CA(S)||CA(A))return d;let $=jA(S.value,A.value);if(!$.valid)return L(n,{code:Y.invalid_intersection_types}),d;if(IA(S)||IA(A))T.dirty();return{status:T.value,value:$.data}};if(n.common.async)return Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([S,A])=>f(S,A));else return f(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}xn.create=(o,T,n)=>{return new xn({left:o,right:T,typeName:g.ZodIntersection,...u(n)})};class mT extends e{_parse(o){let{status:T,ctx:n}=this._processInputParams(o);if(n.parsedType!==h.array)return L(n,{code:Y.invalid_type,expected:h.array,received:n.parsedType}),d;if(n.data.length<this._def.items.length)return L(n,{code:Y.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),d;if(!this._def.rest&&n.data.length>this._def.items.length)L(n,{code:Y.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),T.dirty();let S=[...n.data].map((A,$)=>{let F=this._def.items[$]||this._def.rest;if(!F)return null;return F._parse(new GT(n,A,n.path,$))}).filter((A)=>!!A);if(n.common.async)return Promise.all(S).then((A)=>{return uo.mergeArray(T,A)});else return uo.mergeArray(T,S)}get items(){return this._def.items}rest(o){return new mT({...this._def,rest:o})}}mT.create=(o,T)=>{if(!Array.isArray(o))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new mT({items:o,typeName:g.ZodTuple,rest:null,...u(T)})};class Xf extends e{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(o){let{status:T,ctx:n}=this._processInputParams(o);if(n.parsedType!==h.object)return L(n,{code:Y.invalid_type,expected:h.object,received:n.parsedType}),d;let f=[],S=this._def.keyType,A=this._def.valueType;for(let $ in n.data)f.push({key:S._parse(new GT(n,$,n.path,$)),value:A._parse(new GT(n,n.data[$],n.path,$)),alwaysSet:$ in n.data});if(n.common.async)return uo.mergeObjectAsync(T,f);else return uo.mergeObjectSync(T,f)}get element(){return this._def.valueType}static create(o,T,n){if(T instanceof e)return new Xf({keyType:o,valueType:T,typeName:g.ZodRecord,...u(n)});return new Xf({keyType:HT.create(),valueType:o,typeName:g.ZodRecord,...u(T)})}}class Hf extends e{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(o){let{status:T,ctx:n}=this._processInputParams(o);if(n.parsedType!==h.map)return L(n,{code:Y.invalid_type,expected:h.map,received:n.parsedType}),d;let f=this._def.keyType,S=this._def.valueType,A=[...n.data.entries()].map(([$,F],J)=>{return{key:f._parse(new GT(n,$,n.path,[J,"key"])),value:S._parse(new GT(n,F,n.path,[J,"value"]))}});if(n.common.async){let $=new Map;return Promise.resolve().then(async()=>{for(let F of A){let J=await F.key,t=await F.value;if(J.status==="aborted"||t.status==="aborted")return d;if(J.status==="dirty"||t.status==="dirty")T.dirty();$.set(J.value,t.value)}return{status:T.value,value:$}})}else{let $=new Map;for(let F of A){let{key:J,value:t}=F;if(J.status==="aborted"||t.status==="aborted")return d;if(J.status==="dirty"||t.status==="dirty")T.dirty();$.set(J.value,t.value)}return{status:T.value,value:$}}}}Hf.create=(o,T,n)=>{return new Hf({valueType:T,keyType:o,typeName:g.ZodMap,...u(n)})};class Mn extends e{_parse(o){let{status:T,ctx:n}=this._processInputParams(o);if(n.parsedType!==h.set)return L(n,{code:Y.invalid_type,expected:h.set,received:n.parsedType}),d;let f=this._def;if(f.minSize!==null){if(n.data.size<f.minSize.value)L(n,{code:Y.too_small,minimum:f.minSize.value,type:"set",inclusive:!0,exact:!1,message:f.minSize.message}),T.dirty()}if(f.maxSize!==null){if(n.data.size>f.maxSize.value)L(n,{code:Y.too_big,maximum:f.maxSize.value,type:"set",inclusive:!0,exact:!1,message:f.maxSize.message}),T.dirty()}let S=this._def.valueType;function A(F){let J=new Set;for(let t of F){if(t.status==="aborted")return d;if(t.status==="dirty")T.dirty();J.add(t.value)}return{status:T.value,value:J}}let $=[...n.data.values()].map((F,J)=>S._parse(new GT(n,F,n.path,J)));if(n.common.async)return Promise.all($).then((F)=>A(F));else return A($)}min(o,T){return new Mn({...this._def,minSize:{value:o,message:x.toString(T)}})}max(o,T){return new Mn({...this._def,maxSize:{value:o,message:x.toString(T)}})}size(o,T){return this.min(o,T).max(o,T)}nonempty(o){return this.min(1,o)}}Mn.create=(o,T)=>{return new Mn({valueType:o,minSize:null,maxSize:null,typeName:g.ZodSet,...u(T)})};class Cn extends e{constructor(){super(...arguments);this.validate=this.implement}_parse(o){let{ctx:T}=this._processInputParams(o);if(T.parsedType!==h.function)return L(T,{code:Y.invalid_type,expected:h.function,received:T.parsedType}),d;function n($,F){return JS({data:$,path:T.path,errorMaps:[T.common.contextualErrorMap,T.schemaErrorMap,FS(),In].filter((J)=>!!J),issueData:{code:Y.invalid_arguments,argumentsError:F}})}function f($,F){return JS({data:$,path:T.path,errorMaps:[T.common.contextualErrorMap,T.schemaErrorMap,FS(),In].filter((J)=>!!J),issueData:{code:Y.invalid_return_type,returnTypeError:F}})}let S={errorMap:T.common.contextualErrorMap},A=T.data;if(this._def.returns instanceof yn){let $=this;return ao(async function(...F){let J=new JT([]),t=await $._def.args.parseAsync(F,S).catch((O)=>{throw J.addIssue(n(F,O)),J}),R=await Reflect.apply(A,this,t);return await $._def.returns._def.type.parseAsync(R,S).catch((O)=>{throw J.addIssue(f(R,O)),J})})}else{let $=this;return ao(function(...F){let J=$._def.args.safeParse(F,S);if(!J.success)throw new JT([n(F,J.error)]);let t=Reflect.apply(A,this,J.data),R=$._def.returns.safeParse(t,S);if(!R.success)throw new JT([f(t,R.error)]);return R.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...o){return new Cn({...this._def,args:mT.create(o).rest(gT.create())})}returns(o){return new Cn({...this._def,returns:o})}implement(o){return this.parse(o)}strictImplement(o){return this.parse(o)}static create(o,T,n){return new Cn({args:o?o:mT.create([]).rest(gT.create()),returns:T||gT.create(),typeName:g.ZodFunction,...u(n)})}}class vn extends e{get schema(){return this._def.getter()}_parse(o){let{ctx:T}=this._processInputParams(o);return this._def.getter()._parse({data:T.data,path:T.path,parent:T})}}vn.create=(o,T)=>{return new vn({getter:o,typeName:g.ZodLazy,...u(T)})};class rn extends e{_parse(o){if(o.data!==this._def.value){let T=this._getOrReturnCtx(o);return L(T,{received:T.data,code:Y.invalid_literal,expected:this._def.value}),d}return{status:"valid",value:o.data}}get value(){return this._def.value}}rn.create=(o,T)=>{return new rn({value:o,typeName:g.ZodLiteral,...u(T)})};function SJ(o,T){return new uT({values:o,typeName:g.ZodEnum,...u(T)})}class uT extends e{constructor(){super(...arguments);kf.set(this,void 0)}_parse(o){if(typeof o.data!=="string"){let T=this._getOrReturnCtx(o),n=this._def.values;return L(T,{expected:Ao.joinValues(n),received:T.parsedType,code:Y.invalid_type}),d}if(!tS(this,kf,"f"))oJ(this,kf,new Set(this._def.values),"f");if(!tS(this,kf,"f").has(o.data)){let T=this._getOrReturnCtx(o),n=this._def.values;return L(T,{received:T.data,code:Y.invalid_enum_value,options:n}),d}return ao(o.data)}get options(){return this._def.values}get enum(){let o={};for(let T of this._def.values)o[T]=T;return o}get Values(){let o={};for(let T of this._def.values)o[T]=T;return o}get Enum(){let o={};for(let T of this._def.values)o[T]=T;return o}extract(o,T=this._def){return uT.create(o,{...this._def,...T})}exclude(o,T=this._def){return uT.create(this.options.filter((n)=>!o.includes(n)),{...this._def,...T})}}kf=new WeakMap;uT.create=SJ;class qn extends e{constructor(){super(...arguments);Wf.set(this,void 0)}_parse(o){let T=Ao.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(o);if(n.parsedType!==h.string&&n.parsedType!==h.number){let f=Ao.objectValues(T);return L(n,{expected:Ao.joinValues(f),received:n.parsedType,code:Y.invalid_type}),d}if(!tS(this,Wf,"f"))oJ(this,Wf,new Set(Ao.getValidEnumValues(this._def.values)),"f");if(!tS(this,Wf,"f").has(o.data)){let f=Ao.objectValues(T);return L(n,{received:n.data,code:Y.invalid_enum_value,options:f}),d}return ao(o.data)}get enum(){return this._def.values}}Wf=new WeakMap;qn.create=(o,T)=>{return new qn({values:o,typeName:g.ZodNativeEnum,...u(T)})};class yn extends e{unwrap(){return this._def.type}_parse(o){let{ctx:T}=this._processInputParams(o);if(T.parsedType!==h.promise&&T.common.async===!1)return L(T,{code:Y.invalid_type,expected:h.promise,received:T.parsedType}),d;let n=T.parsedType===h.promise?T.data:Promise.resolve(T.data);return ao(n.then((f)=>{return this._def.type.parseAsync(f,{path:T.path,errorMap:T.common.contextualErrorMap})}))}}yn.create=(o,T)=>{return new yn({type:o,typeName:g.ZodPromise,...u(T)})};class WT extends e{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===g.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(o){let{status:T,ctx:n}=this._processInputParams(o),f=this._def.effect||null,S={addIssue:(A)=>{if(L(n,A),A.fatal)T.abort();else T.dirty()},get path(){return n.path}};if(S.addIssue=S.addIssue.bind(S),f.type==="preprocess"){let A=f.transform(n.data,S);if(n.common.async)return Promise.resolve(A).then(async($)=>{if(T.value==="aborted")return d;let F=await this._def.schema._parseAsync({data:$,path:n.path,parent:n});if(F.status==="aborted")return d;if(F.status==="dirty")return Ln(F.value);if(T.value==="dirty")return Ln(F.value);return F});else{if(T.value==="aborted")return d;let $=this._def.schema._parseSync({data:A,path:n.path,parent:n});if($.status==="aborted")return d;if($.status==="dirty")return Ln($.value);if(T.value==="dirty")return Ln($.value);return $}}if(f.type==="refinement"){let A=($)=>{let F=f.refinement($,S);if(n.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(n.common.async===!1){let $=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if($.status==="aborted")return d;if($.status==="dirty")T.dirty();return A($.value),{status:T.value,value:$.value}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(($)=>{if($.status==="aborted")return d;if($.status==="dirty")T.dirty();return A($.value).then(()=>{return{status:T.value,value:$.value}})})}if(f.type==="transform")if(n.common.async===!1){let A=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Jn(A))return A;let $=f.transform(A.value,S);if($ instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:T.value,value:$}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then((A)=>{if(!Jn(A))return A;return Promise.resolve(f.transform(A.value,S)).then(($)=>({status:T.value,value:$}))});Ao.assertNever(f)}}WT.create=(o,T,n)=>{return new WT({schema:o,typeName:g.ZodEffects,effect:T,...u(n)})};WT.createWithPreprocess=(o,T,n)=>{return new WT({schema:T,effect:{type:"preprocess",transform:o},typeName:g.ZodEffects,...u(n)})};class ET extends e{_parse(o){if(this._getType(o)===h.undefined)return ao(void 0);return this._def.innerType._parse(o)}unwrap(){return this._def.innerType}}ET.create=(o,T)=>{return new ET({innerType:o,typeName:g.ZodOptional,...u(T)})};class rT extends e{_parse(o){if(this._getType(o)===h.null)return ao(null);return this._def.innerType._parse(o)}unwrap(){return this._def.innerType}}rT.create=(o,T)=>{return new rT({innerType:o,typeName:g.ZodNullable,...u(T)})};class pn extends e{_parse(o){let{ctx:T}=this._processInputParams(o),n=T.data;if(T.parsedType===h.undefined)n=this._def.defaultValue();return this._def.innerType._parse({data:n,path:T.path,parent:T})}removeDefault(){return this._def.innerType}}pn.create=(o,T)=>{return new pn({innerType:o,typeName:g.ZodDefault,defaultValue:typeof T.default==="function"?T.default:()=>T.default,...u(T)})};class cn extends e{_parse(o){let{ctx:T}=this._processInputParams(o),n={...T,common:{...T.common,issues:[]}},f=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});if(Of(f))return f.then((S)=>{return{status:"valid",value:S.status==="valid"?S.value:this._def.catchValue({get error(){return new JT(n.common.issues)},input:n.data})}});else return{status:"valid",value:f.status==="valid"?f.value:this._def.catchValue({get error(){return new JT(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}cn.create=(o,T)=>{return new cn({innerType:o,typeName:g.ZodCatch,catchValue:typeof T.catch==="function"?T.catch:()=>T.catch,...u(T)})};class Kf extends e{_parse(o){if(this._getType(o)!==h.nan){let n=this._getOrReturnCtx(o);return L(n,{code:Y.invalid_type,expected:h.nan,received:n.parsedType}),d}return{status:"valid",value:o.data}}}Kf.create=(o)=>{return new Kf({typeName:g.ZodNaN,...u(o)})};var _1=Symbol("zod_brand");class MS extends e{_parse(o){let{ctx:T}=this._processInputParams(o),n=T.data;return this._def.type._parse({data:n,path:T.path,parent:T})}unwrap(){return this._def.type}}class Ef extends e{_parse(o){let{status:T,ctx:n}=this._processInputParams(o);if(n.common.async)return(async()=>{let S=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});if(S.status==="aborted")return d;if(S.status==="dirty")return T.dirty(),Ln(S.value);else return this._def.out._parseAsync({data:S.value,path:n.path,parent:n})})();else{let f=this._def.in._parseSync({data:n.data,path:n.path,parent:n});if(f.status==="aborted")return d;if(f.status==="dirty")return T.dirty(),{status:"dirty",value:f.value};else return this._def.out._parseSync({data:f.value,path:n.path,parent:n})}}static create(o,T){return new Ef({in:o,out:T,typeName:g.ZodPipeline})}}class Zn extends e{_parse(o){let T=this._def.innerType._parse(o),n=(f)=>{if(Jn(f))f.value=Object.freeze(f.value);return f};return Of(T)?T.then((f)=>n(f)):n(T)}unwrap(){return this._def.innerType}}Zn.create=(o,T)=>{return new Zn({innerType:o,typeName:g.ZodReadonly,...u(T)})};function eF(o,T){let n=typeof o==="function"?o(T):typeof o==="string"?{message:o}:o;return typeof n==="string"?{message:n}:n}function AJ(o,T={},n){if(o)return Rn.create().superRefine((f,S)=>{var A,$;let F=o(f);if(F instanceof Promise)return F.then((J)=>{var t,R;if(!J){let W=eF(T,f),O=(R=(t=W.fatal)!==null&&t!==void 0?t:n)!==null&&R!==void 0?R:!0;S.addIssue({code:"custom",...W,fatal:O})}});if(!F){let J=eF(T,f),t=($=(A=J.fatal)!==null&&A!==void 0?A:n)!==null&&$!==void 0?$:!0;S.addIssue({code:"custom",...J,fatal:t})}return});return Rn.create()}var X1={object:zo.lazycreate},g;(function(o){o.ZodString="ZodString",o.ZodNumber="ZodNumber",o.ZodNaN="ZodNaN",o.ZodBigInt="ZodBigInt",o.ZodBoolean="ZodBoolean",o.ZodDate="ZodDate",o.ZodSymbol="ZodSymbol",o.ZodUndefined="ZodUndefined",o.ZodNull="ZodNull",o.ZodAny="ZodAny",o.ZodUnknown="ZodUnknown",o.ZodNever="ZodNever",o.ZodVoid="ZodVoid",o.ZodArray="ZodArray",o.ZodObject="ZodObject",o.ZodUnion="ZodUnion",o.ZodDiscriminatedUnion="ZodDiscriminatedUnion",o.ZodIntersection="ZodIntersection",o.ZodTuple="ZodTuple",o.ZodRecord="ZodRecord",o.ZodMap="ZodMap",o.ZodSet="ZodSet",o.ZodFunction="ZodFunction",o.ZodLazy="ZodLazy",o.ZodLiteral="ZodLiteral",o.ZodEnum="ZodEnum",o.ZodEffects="ZodEffects",o.ZodNativeEnum="ZodNativeEnum",o.ZodOptional="ZodOptional",o.ZodNullable="ZodNullable",o.ZodDefault="ZodDefault",o.ZodCatch="ZodCatch",o.ZodPromise="ZodPromise",o.ZodBranded="ZodBranded",o.ZodPipeline="ZodPipeline",o.ZodReadonly="ZodReadonly"})(g||(g={}));var H1=(o,T={message:`Input not instance of ${o.name}`})=>AJ((n)=>n instanceof o,T),$J=HT.create,FJ=dT.create,K1=Kf.create,E1=lT.create,JJ=jn.create,G1=tn.create,Y1=wf.create,z1=hn.create,D1=Nn.create,Q1=Rn.create,U1=gT.create,V1=BT.create,B1=_f.create,m1=KT.create,L1=zo.create,C1=zo.strictCreate,I1=bn.create,j1=RS.create,h1=xn.create,N1=mT.create,b1=Xf.create,x1=Hf.create,v1=Mn.create,r1=Cn.create,q1=vn.create,p1=rn.create,c1=uT.create,Z1=qn.create,P1=yn.create,sF=WT.create,i1=ET.create,g1=rT.create,d1=WT.createWithPreprocess,l1=Ef.create,u1=()=>$J().optional(),e1=()=>FJ().optional(),s1=()=>JJ().optional(),a1={string:(o)=>HT.create({...o,coerce:!0}),number:(o)=>dT.create({...o,coerce:!0}),boolean:(o)=>jn.create({...o,coerce:!0}),bigint:(o)=>lT.create({...o,coerce:!0}),date:(o)=>tn.create({...o,coerce:!0})},oy=d,Eo=Object.freeze({__proto__:null,defaultErrorMap:In,setErrorMap:dM,getErrorMap:FS,makeIssue:JS,EMPTY_PATH:lM,addIssueToContext:L,ParseStatus:uo,INVALID:d,DIRTY:Ln,OK:ao,isAborted:CA,isDirty:IA,isValid:Jn,isAsync:Of,get util(){return Ao},get objectUtil(){return LA},ZodParsedType:h,getParsedType:vT,ZodType:e,datetimeRegex:fJ,ZodString:HT,ZodNumber:dT,ZodBigInt:lT,ZodBoolean:jn,ZodDate:tn,ZodSymbol:wf,ZodUndefined:hn,ZodNull:Nn,ZodAny:Rn,ZodUnknown:gT,ZodNever:BT,ZodVoid:_f,ZodArray:KT,ZodObject:zo,ZodUnion:bn,ZodDiscriminatedUnion:RS,ZodIntersection:xn,ZodTuple:mT,ZodRecord:Xf,ZodMap:Hf,ZodSet:Mn,ZodFunction:Cn,ZodLazy:vn,ZodLiteral:rn,ZodEnum:uT,ZodNativeEnum:qn,ZodPromise:yn,ZodEffects:WT,ZodTransformer:WT,ZodOptional:ET,ZodNullable:rT,ZodDefault:pn,ZodCatch:cn,ZodNaN:Kf,BRAND:_1,ZodBranded:MS,ZodPipeline:Ef,ZodReadonly:Zn,custom:AJ,Schema:e,ZodSchema:e,late:X1,get ZodFirstPartyTypeKind(){return g},coerce:a1,any:Q1,array:m1,bigint:E1,boolean:JJ,date:G1,discriminatedUnion:j1,effect:sF,enum:c1,function:r1,instanceof:H1,intersection:h1,lazy:q1,literal:p1,map:x1,nan:K1,nativeEnum:Z1,never:V1,null:D1,nullable:g1,number:FJ,object:L1,oboolean:s1,onumber:e1,optional:i1,ostring:u1,pipeline:l1,preprocess:d1,promise:P1,record:b1,set:v1,strictObject:C1,string:$J,symbol:Y1,transformer:sF,tuple:N1,undefined:z1,union:I1,unknown:U1,void:B1,NEVER:oy,ZodIssueCode:Y,quotelessJson:gM,ZodError:JT});var Ty="__vite_start_time"in globalThis,ny=typeof window!=="undefined",JE="vitest"in globalThis,YT=lF({isServer:!Ty&&!ny,server:{CI:Eo.string().transform((o)=>!0).optional(),POSTGRES_USER:Eo.string(),POSTGRES_PASSWORD:Eo.string(),POSTGRES_DATABASE:Eo.string(),POSTGRES_HOST:Eo.string(),POSTGRES_PORT:Eo.string().transform((o)=>Number.parseInt(o,10)),BACKEND_PORT:Eo.string().transform((o)=>Number.parseInt(o,10)),RUN_WORKERS_FROM_SOURCE:Eo.union([Eo.literal("true"),Eo.literal("false")]).optional().transform((o)=>o==="true"),FRONTEND_PORT:Eo.string().transform((o)=>Number.parseInt(o,10)),FRONTEND_ORIGINS:Eo.string().transform((o)=>JSON.parse(o)).pipe(Eo.array(Eo.string())),OPENAI_API_KEY:Eo.string().optional()},clientPrefix:"VITE_",client:{VITE_BACKEND_ORIGIN:Eo.string(),VITE_USE_SELF_SIGNED_CERTIFICATE:Eo.union([Eo.literal("true"),Eo.literal("false")]).optional().transform((o)=>o==="true")},runtimeEnv:import.meta.env,emptyStringAsUndefined:!0});var RJ=hA(import.meta.dirname,"../dev"),MJ=YT.VITE_USE_SELF_SIGNED_CERTIFICATE?{cert:tJ(hA(RJ,"./cert.pem"),"utf-8"),key:tJ(hA(RJ,"./key.pem"),"utf-8")}:void 0;import Sk from"node:path";var y=Symbol.for("drizzle:entityKind"),WE=Symbol.for("drizzle:hasOwnEntityKind");function X(o,T){if(!o||typeof o!=="object")return!1;if(o instanceof T)return!0;if(!Object.prototype.hasOwnProperty.call(T,y))throw new Error(`Class "${T.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let n=Object.getPrototypeOf(o).constructor;if(n)while(n){if(y in n&&n[y]===T[y])return!0;n=Object.getPrototypeOf(n)}return!1}class Wo{constructor(o,T){this.table=o,this.config=T,this.name=T.name,this.keyAsName=T.keyAsName,this.notNull=T.notNull,this.default=T.default,this.defaultFn=T.defaultFn,this.onUpdateFn=T.onUpdateFn,this.hasDefault=T.hasDefault,this.primary=T.primaryKey,this.isUnique=T.isUnique,this.uniqueName=T.uniqueName,this.uniqueType=T.uniqueType,this.dataType=T.dataType,this.columnType=T.columnType,this.generated=T.generated,this.generatedIdentity=T.generatedIdentity}static[y]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue(o){return o}mapToDriverValue(o){return o}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}class NA{static[y]="ColumnBuilder";config;constructor(o,T,n){this.config={name:o,keyAsName:o==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:T,columnType:n,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(o){return this.config.default=o,this.config.hasDefault=!0,this}$defaultFn(o){return this.config.defaultFn=o,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(o){return this.config.onUpdateFn=o,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(o){if(this.config.name!=="")return;this.config.name=o}}var zT=Symbol.for("drizzle:Name");class bA{static[y]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(o,T){if(this.reference=()=>{let{name:n,columns:f,foreignColumns:S}=o();return{name:n,columns:f,foreignTable:S[0].table,foreignColumns:S}},T)this._onUpdate=T.onUpdate,this._onDelete=T.onDelete}onUpdate(o){return this._onUpdate=o===void 0?"no action":o,this}onDelete(o){return this._onDelete=o===void 0?"no action":o,this}build(o){return new yJ(o,this)}}class yJ{constructor(o,T){this.table=o,this.reference=T.reference,this.onUpdate=T._onUpdate,this.onDelete=T._onDelete}static[y]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:o,columns:T,foreignColumns:n}=this.reference(),f=T.map(($)=>$.name),S=n.map(($)=>$.name),A=[this.table[zT],...f,n[0].table[zT],...S];return o??`${A.join("_")}_fk`}}function yS(o,...T){return o(...T)}function kJ(o,T){return`${o[zT]}_${T.join("_")}_unique`}function WJ(o,T,n){for(let f=T;f<o.length;f++){let S=o[f];if(S==="\\"){f++;continue}if(S==='"')return[o.slice(T,f).replace(/\\/g,""),f+1];if(n)continue;if(S===","||S==="}")return[o.slice(T,f).replace(/\\/g,""),f]}return[o.slice(T).replace(/\\/g,""),o.length]}function OJ(o,T=0){let n=[],f=T,S=!1;while(f<o.length){let A=o[f];if(A===","){if(S||f===T)n.push("");S=!0,f++;continue}if(S=!1,A==="\\"){f+=2;continue}if(A==='"'){let[J,t]=WJ(o,f+1,!0);n.push(J),f=t;continue}if(A==="}")return[n,f+1];if(A==="{"){let[J,t]=OJ(o,f+1);n.push(J),f=t;continue}let[$,F]=WJ(o,f,!1);n.push($),f=F}return[n,f]}function wJ(o){let[T]=OJ(o,1);return T}function xA(o){return`{${o.map((T)=>{if(Array.isArray(T))return xA(T);if(typeof T==="string")return`"${T.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${T}`}).join(",")}}`}class N extends NA{foreignKeyConfigs=[];static[y]="PgColumnBuilder";array(o){return new XJ(this.config.name,this,o)}references(o,T={}){return this.foreignKeyConfigs.push({ref:o,actions:T}),this}unique(o,T){return this.config.isUnique=!0,this.config.uniqueName=o,this.config.uniqueType=T?.nulls,this}generatedAlwaysAs(o){return this.config.generated={as:o,type:"always",mode:"stored"},this}buildForeignKeys(o,T){return this.foreignKeyConfigs.map(({ref:n,actions:f})=>{return yS((S,A)=>{let $=new bA(()=>{let F=S();return{columns:[o],foreignColumns:[F]}});if(A.onUpdate)$.onUpdate(A.onUpdate);if(A.onDelete)$.onDelete(A.onDelete);return $.build(T)},n,f)})}buildExtraConfigColumn(o){return new _J(o,this.config)}}class V extends Wo{constructor(o,T){if(!T.uniqueName)T.uniqueName=kJ(o,[T.name]);super(o,T);this.table=o}static[y]="PgColumn"}class _J extends V{static[y]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op(o){return this.indexConfig.opClass=o,this}}class Gf{static[y]="IndexedColumn";constructor(o,T,n,f){this.name=o,this.keyAsName=T,this.type=n,this.indexConfig=f}name;keyAsName;type;indexConfig}class XJ extends N{static[y]="PgArrayBuilder";constructor(o,T,n){super(o,"array","PgArray");this.config.baseBuilder=T,this.config.size=n}build(o){let T=this.config.baseBuilder.build(o);return new vA(o,this.config,T)}}class vA extends V{constructor(o,T,n,f){super(o,T);this.baseColumn=n,this.range=f,this.size=T.size}size;static[y]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(o){if(typeof o==="string")o=wJ(o);return o.map((T)=>this.baseColumn.mapFromDriverValue(T))}mapToDriverValue(o,T=!1){let n=o.map((f)=>f===null?null:X(this.baseColumn,vA)?this.baseColumn.mapToDriverValue(f,!0):this.baseColumn.mapToDriverValue(f));if(T)return n;return xA(n)}}var rA=Symbol.for("drizzle:isPgEnum");function HJ(o){return!!o&&typeof o==="function"&&rA in o&&o[rA]===!0}class KJ extends N{static[y]="PgEnumColumnBuilder";constructor(o,T){super(o,"string","PgEnumColumn");this.config.enum=T}build(o){return new EJ(o,this.config)}}class EJ extends V{static[y]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(o,T){super(o,T);this.enum=T.enum}getSQLType(){return this.enum.enumName}}function kS(o,T){return fy(o,T,void 0)}function fy(o,T,n){let f=Object.assign((S)=>new KJ(S??"",f),{enumName:o,enumValues:T,schema:n,[rA]:!0});return f}class No{static[y]="Subquery";constructor(o,T,n,f=!1){this._={brand:"Subquery",sql:o,selectedFields:T,alias:n,isWith:f}}}class Yf extends No{static[y]="WithSubquery"}var GJ="0.41.0";var qA,pA,Oo={startActiveSpan(o,T){if(!qA)return T();if(!pA)pA=qA.trace.getTracer("drizzle-orm",GJ);return yS((n,f)=>f.startActiveSpan(o,(S)=>{try{return T(S)}catch(A){throw S.setStatus({code:n.SpanStatusCode.ERROR,message:A instanceof Error?A.message:"Unknown error"}),A}finally{S.end()}}),qA,pA)}};var Xo=Symbol.for("drizzle:ViewBaseConfig");var WS=Symbol.for("drizzle:Schema"),OS=Symbol.for("drizzle:Columns"),YJ=Symbol.for("drizzle:ExtraConfigColumns"),cA=Symbol.for("drizzle:OriginalName"),ZA=Symbol.for("drizzle:BaseName"),zf=Symbol.for("drizzle:IsAlias"),zJ=Symbol.for("drizzle:ExtraConfigBuilder"),Sy=Symbol.for("drizzle:IsDrizzleTable");class I{static[y]="Table";static Symbol={Name:zT,Schema:WS,OriginalName:cA,Columns:OS,ExtraConfigColumns:YJ,BaseName:ZA,IsAlias:zf,ExtraConfigBuilder:zJ};[zT];[cA];[WS];[OS];[YJ];[ZA];[zf]=!1;[Sy]=!0;[zJ]=void 0;constructor(o,T,n){this[zT]=this[cA]=o,this[WS]=T,this[ZA]=n}}function vo(o){return o[zT]}function kn(o){return`${o[WS]??"public"}.${o[zT]}`}function PA(o){return o!==null&&o!==void 0&&typeof o.getSQL==="function"}function Ay(o){let T={sql:"",params:[]};for(let n of o)if(T.sql+=n.sql,T.params.push(...n.params),n.typings?.length){if(!T.typings)T.typings=[];T.typings.push(...n.typings)}return T}class bo{static[y]="StringChunk";value;constructor(o){this.value=Array.isArray(o)?o:[o]}getSQL(){return new j([this])}}class j{constructor(o){this.queryChunks=o}static[y]="SQL";decoder=QJ;shouldInlineParams=!1;append(o){return this.queryChunks.push(...o.queryChunks),this}toQuery(o){return Oo.startActiveSpan("drizzle.buildSQL",(T)=>{let n=this.buildQueryFromSourceParams(this.queryChunks,o);return T?.setAttributes({"drizzle.query.text":n.sql,"drizzle.query.params":JSON.stringify(n.params)}),n})}buildQueryFromSourceParams(o,T){let n=Object.assign({},T,{inlineParams:T.inlineParams||this.shouldInlineParams,paramStartIndex:T.paramStartIndex||{value:0}}),{casing:f,escapeName:S,escapeParam:A,prepareTyping:$,inlineParams:F,paramStartIndex:J}=n;return Ay(o.map((t)=>{if(X(t,bo))return{sql:t.value.join(""),params:[]};if(X(t,wS))return{sql:S(t.value),params:[]};if(t===void 0)return{sql:"",params:[]};if(Array.isArray(t)){let R=[new bo("(")];for(let[W,O]of t.entries())if(R.push(O),W<t.length-1)R.push(new bo(", "));return R.push(new bo(")")),this.buildQueryFromSourceParams(R,n)}if(X(t,j))return this.buildQueryFromSourceParams(t.queryChunks,{...n,inlineParams:F||t.shouldInlineParams});if(X(t,I)){let R=t[I.Symbol.Schema],W=t[I.Symbol.Name];return{sql:R===void 0||t[zf]?S(W):S(R)+"."+S(W),params:[]}}if(X(t,Wo)){let R=f.getColumnCasing(t);if(T.invokeSource==="indexes")return{sql:S(R),params:[]};let W=t.table[I.Symbol.Schema];return{sql:t.table[zf]||W===void 0?S(t.table[I.Symbol.Name])+"."+S(R):S(W)+"."+S(t.table[I.Symbol.Name])+"."+S(R),params:[]}}if(X(t,ST)){let R=t[Xo].schema,W=t[Xo].name;return{sql:R===void 0||t[Xo].isAlias?S(W):S(R)+"."+S(W),params:[]}}if(X(t,tT)){if(X(t.value,eT))return{sql:A(J.value++,t),params:[t],typings:["none"]};let R=t.value===null?null:t.encoder.mapToDriverValue(t.value);if(X(R,j))return this.buildQueryFromSourceParams([R],n);if(F)return{sql:this.mapInlineParam(R,n),params:[]};let W=["none"];if($)W=[$(t.encoder)];return{sql:A(J.value++,R),params:[R],typings:W}}if(X(t,eT))return{sql:A(J.value++,t),params:[t],typings:["none"]};if(X(t,j.Aliased)&&t.fieldAlias!==void 0)return{sql:S(t.fieldAlias),params:[]};if(X(t,No)){if(t._.isWith)return{sql:S(t._.alias),params:[]};return this.buildQueryFromSourceParams([new bo("("),t._.sql,new bo(") "),new wS(t._.alias)],n)}if(HJ(t)){if(t.schema)return{sql:S(t.schema)+"."+S(t.enumName),params:[]};return{sql:S(t.enumName),params:[]}}if(PA(t)){if(t.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([t.getSQL()],n);return this.buildQueryFromSourceParams([new bo("("),t.getSQL(),new bo(")")],n)}if(F)return{sql:this.mapInlineParam(t,n),params:[]};return{sql:A(J.value++,t),params:[t],typings:["none"]}}))}mapInlineParam(o,{escapeString:T}){if(o===null)return"null";if(typeof o==="number"||typeof o==="boolean")return o.toString();if(typeof o==="string")return T(o);if(typeof o==="object"){let n=o.toString();if(n==="[object Object]")return T(JSON.stringify(o));return T(n)}throw new Error("Unexpected param value: "+o)}getSQL(){return this}as(o){if(o===void 0)return this;return new j.Aliased(this,o)}mapWith(o){return this.decoder=typeof o==="function"?{mapFromDriverValue:o}:o,this}inlineParams(){return this.shouldInlineParams=!0,this}if(o){return o?this:void 0}}class wS{constructor(o){this.value=o}static[y]="Name";brand;getSQL(){return new j([this])}}function DJ(o){return typeof o==="object"&&o!==null&&"mapToDriverValue"in o&&typeof o.mapToDriverValue==="function"}var QJ={mapFromDriverValue:(o)=>o},UJ={mapToDriverValue:(o)=>o},n5={...QJ,...UJ};class tT{constructor(o,T=UJ){this.value=o,this.encoder=T}static[y]="Param";brand;getSQL(){return new j([this])}}function k(o,...T){let n=[];if(T.length>0||o.length>0&&o[0]!=="")n.push(new bo(o[0]));for(let[f,S]of T.entries())n.push(S,new bo(o[f+1]));return new j(n)}((o)=>{function T(){return new j([])}o.empty=T;function n(J){return new j(J)}o.fromList=n;function f(J){return new j([new bo(J)])}o.raw=f;function S(J,t){let R=[];for(let[W,O]of J.entries()){if(W>0&&t!==void 0)R.push(t);R.push(O)}return new j(R)}o.join=S;function A(J){return new wS(J)}o.identifier=A;function $(J){return new eT(J)}o.placeholder=$;function F(J,t){return new tT(J,t)}o.param=F})(k||(k={}));((o)=>{class T{constructor(n,f){this.sql=n,this.fieldAlias=f}static[y]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new T(this.sql,this.fieldAlias)}}o.Aliased=T})(j||(j={}));class eT{constructor(o){this.name=o}static[y]="Placeholder";getSQL(){return new j([this])}}function iA(o,T){return o.map((n)=>{if(X(n,eT)){if(!(n.name in T))throw new Error(`No value for placeholder "${n.name}" was provided`);return T[n.name]}if(X(n,tT)&&X(n.value,eT)){if(!(n.value.name in T))throw new Error(`No value for placeholder "${n.value.name}" was provided`);return n.encoder.mapToDriverValue(T[n.value.name])}return n})}var $y=Symbol.for("drizzle:IsDrizzleView");class ST{static[y]="View";[Xo];[$y]=!0;constructor({name:o,schema:T,selectedFields:n,query:f}){this[Xo]={name:o,originalName:o,schema:T,selectedFields:n,query:f,isExisting:!f,isAlias:!1}}getSQL(){return new j([this])}}Wo.prototype.getSQL=function(){return new j([this])};I.prototype.getSQL=function(){return new j([this])};No.prototype.getSQL=function(){return new j([this])};class Pn{constructor(o){this.table=o}static[y]="ColumnAliasProxyHandler";get(o,T){if(T==="table")return this.table;return o[T]}}class Df{constructor(o,T){this.alias=o,this.replaceOriginalName=T}static[y]="TableAliasProxyHandler";get(o,T){if(T===I.Symbol.IsAlias)return!0;if(T===I.Symbol.Name)return this.alias;if(this.replaceOriginalName&&T===I.Symbol.OriginalName)return this.alias;if(T===Xo)return{...o[Xo],name:this.alias,isAlias:!0};if(T===I.Symbol.Columns){let f=o[I.Symbol.Columns];if(!f)return f;let S={};return Object.keys(f).map((A)=>{S[A]=new Proxy(f[A],new Pn(new Proxy(o,this)))}),S}let n=o[T];if(X(n,Wo))return new Proxy(n,new Pn(new Proxy(o,this)));return n}}function _S(o,T){return new Proxy(o,new Df(T,!1))}function LT(o,T){return new Proxy(o,new Pn(new Proxy(o.table,new Df(T,!1))))}function gA(o,T){return new j.Aliased(Qf(o.sql,T),o.fieldAlias)}function Qf(o,T){return k.join(o.queryChunks.map((n)=>{if(X(n,Wo))return LT(n,T);if(X(n,j))return Qf(n,T);if(X(n,j.Aliased))return gA(n,T);return n}))}class XS extends Error{static[y]="DrizzleError";constructor({message:o,cause:T}){super(o);this.name="DrizzleError",this.cause=T}}class dA extends XS{static[y]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}function AT(o,T){if(DJ(T)&&!PA(o)&&!X(o,tT)&&!X(o,eT)&&!X(o,Wo)&&!X(o,I)&&!X(o,ST))return new tT(o,T);return o}var HS=(o,T)=>{return k`${o} = ${AT(T,o)}`},VJ=(o,T)=>{return k`${o} <> ${AT(T,o)}`};function Uf(...o){let T=o.filter((n)=>n!==void 0);if(T.length===0)return;if(T.length===1)return new j(T);return new j([new bo("("),k.join(T,new bo(" and ")),new bo(")")])}function BJ(...o){let T=o.filter((n)=>n!==void 0);if(T.length===0)return;if(T.length===1)return new j(T);return new j([new bo("("),k.join(T,new bo(" or ")),new bo(")")])}function mJ(o){return k`not ${o}`}var LJ=(o,T)=>{return k`${o} > ${AT(T,o)}`},CJ=(o,T)=>{return k`${o} >= ${AT(T,o)}`},IJ=(o,T)=>{return k`${o} < ${AT(T,o)}`},jJ=(o,T)=>{return k`${o} <= ${AT(T,o)}`};function hJ(o,T){if(Array.isArray(T)){if(T.length===0)return k`false`;return k`${o} in ${T.map((n)=>AT(n,o))}`}return k`${o} in ${AT(T,o)}`}function NJ(o,T){if(Array.isArray(T)){if(T.length===0)return k`true`;return k`${o} not in ${T.map((n)=>AT(n,o))}`}return k`${o} not in ${AT(T,o)}`}function bJ(o){return k`${o} is null`}function xJ(o){return k`${o} is not null`}function vJ(o){return k`exists ${o}`}function rJ(o){return k`not exists ${o}`}function qJ(o,T,n){return k`${o} between ${AT(T,o)} and ${AT(n,o)}`}function pJ(o,T,n){return k`${o} not between ${AT(T,o)} and ${AT(n,o)}`}function cJ(o,T){return k`${o} like ${T}`}function ZJ(o,T){return k`${o} not like ${T}`}function PJ(o,T){return k`${o} ilike ${T}`}function iJ(o,T){return k`${o} not ilike ${T}`}function gJ(o){return k`${o} asc`}function dJ(o){return k`${o} desc`}class lJ{static[y]="ConsoleLogWriter";write(o){console.log(o)}}class lA{static[y]="DefaultLogger";writer;constructor(o){this.writer=o?.writer??new lJ}logQuery(o,T){let n=T.map((S)=>{try{return JSON.stringify(S)}catch{return String(S)}}),f=n.length?` -- params: [${n.join(", ")}]`:"";this.writer.write(`Query: ${o}${f}`)}}class uA{static[y]="NoopLogger";logQuery(){}}class oT{static[y]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(o){return this.then(void 0,o)}finally(o){return this.then((T)=>{return o?.(),T},(T)=>{throw o?.(),T})}then(o,T){return this.execute().then(o,T)}}function uJ(o,T,n){let f={},S=o.reduce((A,{path:$,field:F},J)=>{let t;if(X(F,Wo))t=F;else if(X(F,j))t=F.decoder;else t=F.sql.decoder;let R=A;for(let[W,O]of $.entries())if(W<$.length-1){if(!(O in R))R[O]={};R=R[O]}else{let _=T[J],Q=R[O]=_===null?null:t.mapFromDriverValue(_);if(n&&X(F,Wo)&&$.length===2){let H=$[0];if(!(H in f))f[H]=Q===null?vo(F.table):!1;else if(typeof f[H]==="string"&&f[H]!==vo(F.table))f[H]=!1}}return A},{});if(n&&Object.keys(f).length>0){for(let[A,$]of Object.entries(f))if(typeof $==="string"&&!n[$])S[A]=null}return S}function OT(o,T){return Object.entries(o).reduce((n,[f,S])=>{if(typeof f!=="string")return n;let A=T?[...T,f]:[f];if(X(S,Wo)||X(S,j)||X(S,j.Aliased))n.push({path:A,field:S});else if(X(S,I))n.push(...OT(S[I.Symbol.Columns],A));else n.push(...OT(S,A));return n},[])}function Vf(o,T){let n=Object.keys(o),f=Object.keys(T);if(n.length!==f.length)return!1;for(let[S,A]of n.entries())if(A!==f[S])return!1;return!0}function KS(o,T){let n=Object.entries(T).filter(([,f])=>f!==void 0).map(([f,S])=>{if(X(S,j)||X(S,Wo))return[f,S];else return[f,new tT(S,o[I.Symbol.Columns][f])]});if(n.length===0)throw new Error("No values to set");return Object.fromEntries(n)}function eJ(o,T){for(let n of T)for(let f of Object.getOwnPropertyNames(n.prototype)){if(f==="constructor")continue;Object.defineProperty(o.prototype,f,Object.getOwnPropertyDescriptor(n.prototype,f)||Object.create(null))}}function sJ(o){return o[I.Symbol.Columns]}function qT(o){return X(o,No)?o._.alias:X(o,ST)?o[Xo].name:X(o,j)?void 0:o[I.Symbol.IsAlias]?o[I.Symbol.Name]:o[I.Symbol.BaseName]}function So(o,T){return{name:typeof o==="string"&&o.length>0?o:"",config:typeof o==="object"?o:T}}function aJ(o){if(typeof o!=="object"||o===null)return!1;if(o.constructor.name!=="Object")return!1;if("logger"in o){let T=typeof o.logger;if(T!=="boolean"&&(T!=="object"||typeof o.logger.logQuery!=="function")&&T!=="undefined")return!1;return!0}if("schema"in o){let T=typeof o.schema;if(T!=="object"&&T!=="undefined")return!1;return!0}if("casing"in o){let T=typeof o.casing;if(T!=="string"&&T!=="undefined")return!1;return!0}if("mode"in o){if(o.mode!=="default"||o.mode!=="planetscale"||o.mode!==void 0)return!1;return!0}if("connection"in o){let T=typeof o.connection;if(T!=="string"&&T!=="object"&&T!=="undefined")return!1;return!0}if("client"in o){let T=typeof o.client;if(T!=="object"&&T!=="function"&&T!=="undefined")return!1;return!0}if(Object.keys(o).length===0)return!0;return!1}class sT extends N{static[y]="PgIntColumnBaseBuilder";generatedAlwaysAsIdentity(o){if(o){let{name:T,...n}=o;this.config.generatedIdentity={type:"always",sequenceName:T,sequenceOptions:n}}else this.config.generatedIdentity={type:"always"};return this.config.hasDefault=!0,this.config.notNull=!0,this}generatedByDefaultAsIdentity(o){if(o){let{name:T,...n}=o;this.config.generatedIdentity={type:"byDefault",sequenceName:T,sequenceOptions:n}}else this.config.generatedIdentity={type:"byDefault"};return this.config.hasDefault=!0,this.config.notNull=!0,this}}class ot extends sT{static[y]="PgBigInt53Builder";constructor(o){super(o,"number","PgBigInt53")}build(o){return new Tt(o,this.config)}}class Tt extends V{static[y]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(o){if(typeof o==="number")return o;return Number(o)}}class nt extends sT{static[y]="PgBigInt64Builder";constructor(o){super(o,"bigint","PgBigInt64")}build(o){return new ft(o,this.config)}}class ft extends V{static[y]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(o){return BigInt(o)}}function St(o,T){let{name:n,config:f}=So(o,T);if(f.mode==="number")return new ot(n);return new nt(n)}class At extends N{static[y]="PgBigSerial53Builder";constructor(o){super(o,"number","PgBigSerial53");this.config.hasDefault=!0,this.config.notNull=!0}build(o){return new $t(o,this.config)}}class $t extends V{static[y]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(o){if(typeof o==="number")return o;return Number(o)}}class Ft extends N{static[y]="PgBigSerial64Builder";constructor(o){super(o,"bigint","PgBigSerial64");this.config.hasDefault=!0}build(o){return new Jt(o,this.config)}}class Jt extends V{static[y]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(o){return BigInt(o)}}function tt(o,T){let{name:n,config:f}=So(o,T);if(f.mode==="number")return new At(n);return new Ft(n)}class Rt extends N{static[y]="PgBooleanBuilder";constructor(o){super(o,"boolean","PgBoolean")}build(o){return new Mt(o,this.config)}}class Mt extends V{static[y]="PgBoolean";getSQLType(){return"boolean"}}function Bf(o){return new Rt(o??"")}class yt extends N{static[y]="PgCharBuilder";constructor(o,T){super(o,"string","PgChar");this.config.length=T.length,this.config.enumValues=T.enum}build(o){return new kt(o,this.config)}}class kt extends V{static[y]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}}function Wt(o,T={}){let{name:n,config:f}=So(o,T);return new yt(n,f)}class Ot extends N{static[y]="PgCidrBuilder";constructor(o){super(o,"string","PgCidr")}build(o){return new wt(o,this.config)}}class wt extends V{static[y]="PgCidr";getSQLType(){return"cidr"}}function _t(o){return new Ot(o??"")}class Xt extends N{static[y]="PgCustomColumnBuilder";constructor(o,T,n){super(o,"custom","PgCustomColumn");this.config.fieldConfig=T,this.config.customTypeParams=n}build(o){return new Ht(o,this.config)}}class Ht extends V{static[y]="PgCustomColumn";sqlName;mapTo;mapFrom;constructor(o,T){super(o,T);this.sqlName=T.customTypeParams.dataType(T.fieldConfig),this.mapTo=T.customTypeParams.toDriver,this.mapFrom=T.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(o){return typeof this.mapFrom==="function"?this.mapFrom(o):o}mapToDriverValue(o){return typeof this.mapTo==="function"?this.mapTo(o):o}}function Kt(o){return(T,n)=>{let{name:f,config:S}=So(T,n);return new Xt(f,S,o)}}class pT extends N{static[y]="PgDateColumnBaseBuilder";defaultNow(){return this.default(k`now()`)}}class Et extends pT{static[y]="PgDateBuilder";constructor(o){super(o,"date","PgDate")}build(o){return new ES(o,this.config)}}class ES extends V{static[y]="PgDate";getSQLType(){return"date"}mapFromDriverValue(o){return new Date(o)}mapToDriverValue(o){return o.toISOString()}}class Gt extends pT{static[y]="PgDateStringBuilder";constructor(o){super(o,"string","PgDateString")}build(o){return new GS(o,this.config)}}class GS extends V{static[y]="PgDateString";getSQLType(){return"date"}}function Yt(o,T){let{name:n,config:f}=So(o,T);if(f?.mode==="date")return new Et(n);return new Gt(n)}class zt extends N{static[y]="PgDoublePrecisionBuilder";constructor(o){super(o,"number","PgDoublePrecision")}build(o){return new Dt(o,this.config)}}class Dt extends V{static[y]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(o){if(typeof o==="string")return Number.parseFloat(o);return o}}function Qt(o){return new zt(o??"")}class Ut extends N{static[y]="PgInetBuilder";constructor(o){super(o,"string","PgInet")}build(o){return new Vt(o,this.config)}}class Vt extends V{static[y]="PgInet";getSQLType(){return"inet"}}function Bt(o){return new Ut(o??"")}class mt extends sT{static[y]="PgIntegerBuilder";constructor(o){super(o,"number","PgInteger")}build(o){return new Lt(o,this.config)}}class Lt extends V{static[y]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(o){if(typeof o==="string")return Number.parseInt(o);return o}}function YS(o){return new mt(o??"")}class Ct extends N{static[y]="PgIntervalBuilder";constructor(o,T){super(o,"string","PgInterval");this.config.intervalConfig=T}build(o){return new It(o,this.config)}}class It extends V{static[y]="PgInterval";fields=this.config.intervalConfig.fields;precision=this.config.intervalConfig.precision;getSQLType(){let o=this.fields?` ${this.fields}`:"",T=this.precision?`(${this.precision})`:"";return`interval${o}${T}`}}function jt(o,T={}){let{name:n,config:f}=So(o,T);return new Ct(n,f)}class ht extends N{static[y]="PgJsonBuilder";constructor(o){super(o,"json","PgJson")}build(o){return new zS(o,this.config)}}class zS extends V{static[y]="PgJson";constructor(o,T){super(o,T)}getSQLType(){return"json"}mapToDriverValue(o){return JSON.stringify(o)}mapFromDriverValue(o){if(typeof o==="string")try{return JSON.parse(o)}catch{return o}return o}}function Nt(o){return new ht(o??"")}class bt extends N{static[y]="PgJsonbBuilder";constructor(o){super(o,"json","PgJsonb")}build(o){return new DS(o,this.config)}}class DS extends V{static[y]="PgJsonb";constructor(o,T){super(o,T)}getSQLType(){return"jsonb"}mapToDriverValue(o){return JSON.stringify(o)}mapFromDriverValue(o){if(typeof o==="string")try{return JSON.parse(o)}catch{return o}return o}}function xt(o){return new bt(o??"")}class vt extends N{static[y]="PgLineBuilder";constructor(o){super(o,"array","PgLine")}build(o){return new rt(o,this.config)}}class rt extends V{static[y]="PgLine";getSQLType(){return"line"}mapFromDriverValue(o){let[T,n,f]=o.slice(1,-1).split(",");return[Number.parseFloat(T),Number.parseFloat(n),Number.parseFloat(f)]}mapToDriverValue(o){return`{${o[0]},${o[1]},${o[2]}}`}}class qt extends N{static[y]="PgLineABCBuilder";constructor(o){super(o,"json","PgLineABC")}build(o){return new pt(o,this.config)}}class pt extends V{static[y]="PgLineABC";getSQLType(){return"line"}mapFromDriverValue(o){let[T,n,f]=o.slice(1,-1).split(",");return{a:Number.parseFloat(T),b:Number.parseFloat(n),c:Number.parseFloat(f)}}mapToDriverValue(o){return`{${o.a},${o.b},${o.c}}`}}function ct(o,T){let{name:n,config:f}=So(o,T);if(!f?.mode||f.mode==="tuple")return new vt(n);return new qt(n)}class Zt extends N{static[y]="PgMacaddrBuilder";constructor(o){super(o,"string","PgMacaddr")}build(o){return new Pt(o,this.config)}}class Pt extends V{static[y]="PgMacaddr";getSQLType(){return"macaddr"}}function it(o){return new Zt(o??"")}class gt extends N{static[y]="PgMacaddr8Builder";constructor(o){super(o,"string","PgMacaddr8")}build(o){return new dt(o,this.config)}}class dt extends V{static[y]="PgMacaddr8";getSQLType(){return"macaddr8"}}function lt(o){return new gt(o??"")}class ut extends N{static[y]="PgNumericBuilder";constructor(o,T,n){super(o,"string","PgNumeric");this.config.precision=T,this.config.scale=n}build(o){return new QS(o,this.config)}}class QS extends V{static[y]="PgNumeric";precision;scale;constructor(o,T){super(o,T);this.precision=T.precision,this.scale=T.scale}mapFromDriverValue(o){if(typeof o==="string")return o;return String(o)}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})`}}class et extends N{static[y]="PgNumericNumberBuilder";constructor(o,T,n){super(o,"number","PgNumericNumber");this.config.precision=T,this.config.scale=n}build(o){return new st(o,this.config)}}class st extends V{static[y]="PgNumericNumber";precision;scale;constructor(o,T){super(o,T);this.precision=T.precision,this.scale=T.scale}mapFromDriverValue(o){if(typeof o==="number")return o;return Number(o)}mapToDriverValue=String;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})`}}class at extends N{static[y]="PgNumericBigIntBuilder";constructor(o,T,n){super(o,"bigint","PgNumericBigInt");this.config.precision=T,this.config.scale=n}build(o){return new oR(o,this.config)}}class oR extends V{static[y]="PgNumericBigInt";precision;scale;constructor(o,T){super(o,T);this.precision=T.precision,this.scale=T.scale}mapFromDriverValue=BigInt;mapToDriverValue=String;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 TR(o,T){let{name:n,config:f}=So(o,T),S=f?.mode;return S==="number"?new et(n,f?.precision,f?.scale):S==="bigint"?new at(n,f?.precision,f?.scale):new ut(n,f?.precision,f?.scale)}class nR extends N{static[y]="PgPointTupleBuilder";constructor(o){super(o,"array","PgPointTuple")}build(o){return new fR(o,this.config)}}class fR extends V{static[y]="PgPointTuple";getSQLType(){return"point"}mapFromDriverValue(o){if(typeof o==="string"){let[T,n]=o.slice(1,-1).split(",");return[Number.parseFloat(T),Number.parseFloat(n)]}return[o.x,o.y]}mapToDriverValue(o){return`(${o[0]},${o[1]})`}}class SR extends N{static[y]="PgPointObjectBuilder";constructor(o){super(o,"json","PgPointObject")}build(o){return new AR(o,this.config)}}class AR extends V{static[y]="PgPointObject";getSQLType(){return"point"}mapFromDriverValue(o){if(typeof o==="string"){let[T,n]=o.slice(1,-1).split(",");return{x:Number.parseFloat(T),y:Number.parseFloat(n)}}return o}mapToDriverValue(o){return`(${o.x},${o.y})`}}function $R(o,T){let{name:n,config:f}=So(o,T);if(!f?.mode||f.mode==="tuple")return new nR(n);return new SR(n)}function Fy(o){let T=[];for(let n=0;n<o.length;n+=2)T.push(Number.parseInt(o.slice(n,n+2),16));return new Uint8Array(T)}function FR(o,T){let n=new ArrayBuffer(8),f=new DataView(n);for(let S=0;S<8;S++)f.setUint8(S,o[T+S]);return f.getFloat64(0,!0)}function eA(o){let T=Fy(o),n=0,f=T[n];n+=1;let S=new DataView(T.buffer),A=S.getUint32(n,f===1);n+=4;let $;if(A&536870912)$=S.getUint32(n,f===1),n+=4;if((A&65535)===1){let F=FR(T,n);n+=8;let J=FR(T,n);return n+=8,[F,J]}throw new Error("Unsupported geometry type")}class JR extends N{static[y]="PgGeometryBuilder";constructor(o){super(o,"array","PgGeometry")}build(o){return new tR(o,this.config)}}class tR extends V{static[y]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(o){return eA(o)}mapToDriverValue(o){return`point(${o[0]} ${o[1]})`}}class RR extends N{static[y]="PgGeometryObjectBuilder";constructor(o){super(o,"json","PgGeometryObject")}build(o){return new MR(o,this.config)}}class MR extends V{static[y]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(o){let T=eA(o);return{x:T[0],y:T[1]}}mapToDriverValue(o){return`point(${o.x} ${o.y})`}}function yR(o,T){let{name:n,config:f}=So(o,T);if(!f?.mode||f.mode==="tuple")return new JR(n);return new RR(n)}class kR extends N{static[y]="PgRealBuilder";constructor(o,T){super(o,"number","PgReal");this.config.length=T}build(o){return new WR(o,this.config)}}class WR extends V{static[y]="PgReal";constructor(o,T){super(o,T)}getSQLType(){return"real"}mapFromDriverValue=(o)=>{if(typeof o==="string")return Number.parseFloat(o);return o}}function OR(o){return new kR(o??"")}class wR extends N{static[y]="PgSerialBuilder";constructor(o){super(o,"number","PgSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(o){return new _R(o,this.config)}}class _R extends V{static[y]="PgSerial";getSQLType(){return"serial"}}function XR(o){return new wR(o??"")}class HR extends sT{static[y]="PgSmallIntBuilder";constructor(o){super(o,"number","PgSmallInt")}build(o){return new KR(o,this.config)}}class KR extends V{static[y]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=(o)=>{if(typeof o==="string")return Number(o);return o}}function ER(o){return new HR(o??"")}class GR extends N{static[y]="PgSmallSerialBuilder";constructor(o){super(o,"number","PgSmallSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(o){return new YR(o,this.config)}}class YR extends V{static[y]="PgSmallSerial";getSQLType(){return"smallserial"}}function zR(o){return new GR(o??"")}class DR extends N{static[y]="PgTextBuilder";constructor(o,T){super(o,"string","PgText");this.config.enumValues=T.enum}build(o){return new QR(o,this.config)}}class QR extends V{static[y]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function UR(o,T={}){let{name:n,config:f}=So(o,T);return new DR(n,f)}class VR extends pT{constructor(o,T,n){super(o,"string","PgTime");this.withTimezone=T,this.precision=n,this.config.withTimezone=T,this.config.precision=n}static[y]="PgTimeBuilder";build(o){return new US(o,this.config)}}class US extends V{static[y]="PgTime";withTimezone;precision;constructor(o,T){super(o,T);this.withTimezone=T.withTimezone,this.precision=T.precision}getSQLType(){return`time${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function BR(o,T={}){let{name:n,config:f}=So(o,T);return new VR(n,f.withTimezone??!1,f.precision)}class mR extends pT{static[y]="PgTimestampBuilder";constructor(o,T,n){super(o,"date","PgTimestamp");this.config.withTimezone=T,this.config.precision=n}build(o){return new VS(o,this.config)}}class VS extends V{static[y]="PgTimestamp";withTimezone;precision;constructor(o,T){super(o,T);this.withTimezone=T.withTimezone,this.precision=T.precision}getSQLType(){return`timestamp${this.precision===void 0?"":` (${this.precision})`}${this.withTimezone?" with time zone":""}`}mapFromDriverValue=(o)=>{return new Date(this.withTimezone?o:o+"+0000")};mapToDriverValue=(o)=>{return o.toISOString()}}class LR extends pT{static[y]="PgTimestampStringBuilder";constructor(o,T,n){super(o,"string","PgTimestampString");this.config.withTimezone=T,this.config.precision=n}build(o){return new BS(o,this.config)}}class BS extends V{static[y]="PgTimestampString";withTimezone;precision;constructor(o,T){super(o,T);this.withTimezone=T.withTimezone,this.precision=T.precision}getSQLType(){return`timestamp${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function DT(o,T={}){let{name:n,config:f}=So(o,T);if(f?.mode==="string")return new LR(n,f.withTimezone??!1,f.precision);return new mR(n,f?.withTimezone??!1,f?.precision)}class CR extends N{static[y]="PgUUIDBuilder";constructor(o){super(o,"string","PgUUID")}defaultRandom(){return this.default(k`gen_random_uuid()`)}build(o){return new mS(o,this.config)}}class mS extends V{static[y]="PgUUID";getSQLType(){return"uuid"}}function RT(o){return new CR(o??"")}class IR extends N{static[y]="PgVarcharBuilder";constructor(o,T){super(o,"string","PgVarchar");this.config.length=T.length,this.config.enumValues=T.enum}build(o){return new jR(o,this.config)}}class jR extends V{static[y]="PgVarchar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"varchar":`varchar(${this.length})`}}function po(o,T={}){let{name:n,config:f}=So(o,T);return new IR(n,f)}class hR extends N{static[y]="PgBinaryVectorBuilder";constructor(o,T){super(o,"string","PgBinaryVector");this.config.dimensions=T.dimensions}build(o){return new NR(o,this.config)}}class NR extends V{static[y]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}}function bR(o,T){let{name:n,config:f}=So(o,T);return new hR(n,f)}class xR extends N{static[y]="PgHalfVectorBuilder";constructor(o,T){super(o,"array","PgHalfVector");this.config.dimensions=T.dimensions}build(o){return new vR(o,this.config)}}class vR extends V{static[y]="PgHalfVector";dimensions=this.config.dimensions;getSQLType(){return`halfvec(${this.dimensions})`}mapToDriverValue(o){return JSON.stringify(o)}mapFromDriverValue(o){return o.slice(1,-1).split(",").map((T)=>Number.parseFloat(T))}}function rR(o,T){let{name:n,config:f}=So(o,T);return new xR(n,f)}class qR extends N{static[y]="PgSparseVectorBuilder";constructor(o,T){super(o,"string","PgSparseVector");this.config.dimensions=T.dimensions}build(o){return new pR(o,this.config)}}class pR extends V{static[y]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function cR(o,T){let{name:n,config:f}=So(o,T);return new qR(n,f)}class ZR extends N{static[y]="PgVectorBuilder";constructor(o,T){super(o,"array","PgVector");this.config.dimensions=T.dimensions}build(o){return new PR(o,this.config)}}class PR extends V{static[y]="PgVector";dimensions=this.config.dimensions;getSQLType(){return`vector(${this.dimensions})`}mapToDriverValue(o){return JSON.stringify(o)}mapFromDriverValue(o){return o.slice(1,-1).split(",").map((T)=>Number.parseFloat(T))}}function iR(o,T){let{name:n,config:f}=So(o,T);return new ZR(n,f)}function gR(){return{bigint:St,bigserial:tt,boolean:Bf,char:Wt,cidr:_t,customType:Kt,date:Yt,doublePrecision:Qt,inet:Bt,integer:YS,interval:jt,json:Nt,jsonb:xt,line:ct,macaddr:it,macaddr8:lt,numeric:TR,point:$R,geometry:yR,real:OR,serial:XR,smallint:ER,smallserial:zR,text:UR,time:BR,timestamp:DT,uuid:RT,varchar:po,bit:bR,halfvec:rR,sparsevec:cR,vector:iR}}var sA=Symbol.for("drizzle:PgInlineForeignKeys"),dR=Symbol.for("drizzle:EnableRLS");class co extends I{static[y]="PgTable";static Symbol=Object.assign({},I.Symbol,{InlineForeignKeys:sA,EnableRLS:dR});[sA]=[];[dR]=!1;[I.Symbol.ExtraConfigBuilder]=void 0;[I.Symbol.ExtraConfigColumns]={}}function Jy(o,T,n,f,S=o){let A=new co(o,f,S),$=typeof T==="function"?T(gR()):T,F=Object.fromEntries(Object.entries($).map(([R,W])=>{let O=W;O.setName(R);let _=O.build(A);return A[sA].push(...O.buildForeignKeys(_,A)),[R,_]})),J=Object.fromEntries(Object.entries($).map(([R,W])=>{let O=W;O.setName(R);let _=O.buildExtraConfigColumn(A);return[R,_]})),t=Object.assign(A,F);if(t[I.Symbol.Columns]=F,t[I.Symbol.ExtraConfigColumns]=J,n)t[co.Symbol.ExtraConfigBuilder]=n;return Object.assign(t,{enableRLS:()=>{return t[co.Symbol.EnableRLS]=!0,t}})}var aT=(o,T,n)=>{return Jy(o,T,n,void 0)};function lR(...o){if(o[0].columns)return new mf(o[0].columns,o[0].name);return new mf(o)}class mf{static[y]="PgPrimaryKeyBuilder";columns;name;constructor(o,T){this.columns=o,this.name=T}build(o){return new uR(o,this.columns,this.name)}}class uR{constructor(o,T,n){this.table=o,this.columns=T,this.name=n}static[y]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[co.Symbol.Name]}_${this.columns.map((o)=>o.name).join("_")}_pk`}}class aA{constructor(o,T,n){this.sourceTable=o,this.referencedTable=T,this.relationName=n,this.referencedTableName=T[I.Symbol.Name]}static[y]="Relation";referencedTableName;fieldName}class eR{constructor(o,T){this.table=o,this.config=T}static[y]="Relations"}class on extends aA{constructor(o,T,n,f){super(o,T,n?.relationName);this.config=n,this.isNullable=f}static[y]="One";withFieldName(o){let T=new on(this.sourceTable,this.referencedTable,this.config,this.isNullable);return T.fieldName=o,T}}class Lf extends aA{constructor(o,T,n){super(o,T,n?.relationName);this.config=n}static[y]="Many";withFieldName(o){let T=new Lf(this.sourceTable,this.referencedTable,this.config);return T.fieldName=o,T}}function sR(){return{and:Uf,between:qJ,eq:HS,exists:vJ,gt:LJ,gte:CJ,ilike:PJ,inArray:hJ,isNull:bJ,isNotNull:xJ,like:cJ,lt:IJ,lte:jJ,ne:VJ,not:mJ,notBetween:pJ,notExists:rJ,notLike:ZJ,notIlike:iJ,notInArray:NJ,or:BJ,sql:k}}function aR(){return{sql:k,asc:gJ,desc:dJ}}function o0(o,T){if(Object.keys(o).length===1&&"default"in o&&!X(o.default,I))o=o.default;let n={},f={},S={};for(let[A,$]of Object.entries(o))if(X($,I)){let F=kn($),J=f[F];n[F]=A,S[A]={tsName:A,dbName:$[I.Symbol.Name],schema:$[I.Symbol.Schema],columns:$[I.Symbol.Columns],relations:J?.relations??{},primaryKey:J?.primaryKey??[]};for(let R of Object.values($[I.Symbol.Columns]))if(R.primary)S[A].primaryKey.push(R);let t=$[I.Symbol.ExtraConfigBuilder]?.($[I.Symbol.ExtraConfigColumns]);if(t){for(let R of Object.values(t))if(X(R,mf))S[A].primaryKey.push(...R.columns)}}else if(X($,eR)){let F=kn($.table),J=n[F],t=$.config(T($.table)),R;for(let[W,O]of Object.entries(t))if(J){let _=S[J];if(_.relations[W]=O,R)_.primaryKey.push(...R)}else{if(!(F in f))f[F]={relations:{},primaryKey:R};f[F].relations[W]=O}}return{tables:S,tableNamesMap:n}}function ty(o){return function T(n,f){return new on(o,n,f,f?.fields.reduce((S,A)=>S&&A.notNull,!0)??!1)}}function Ry(o){return function T(n,f){return new Lf(o,n,f)}}function T0(o,T,n){if(X(n,on)&&n.config)return{fields:n.config.fields,references:n.config.references};let f=T[kn(n.referencedTable)];if(!f)throw new Error(`Table "${n.referencedTable[I.Symbol.Name]}" not found in schema`);let S=o[f];if(!S)throw new Error(`Table "${f}" not found in schema`);let A=n.sourceTable,$=T[kn(A)];if(!$)throw new Error(`Table "${A[I.Symbol.Name]}" not found in schema`);let F=[];for(let J of Object.values(S.relations))if(n.relationName&&n!==J&&J.relationName===n.relationName||!n.relationName&&J.referencedTable===n.sourceTable)F.push(J);if(F.length>1)throw n.relationName?new Error(`There are multiple relations with name "${n.relationName}" in table "${f}"`):new Error(`There are multiple relations between "${f}" and "${n.sourceTable[I.Symbol.Name]}". Please specify relation name`);if(F[0]&&X(F[0],on)&&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 "${$}.${n.fieldName}"`)}function n0(o){return{one:ty(o),many:Ry(o)}}function LS(o,T,n,f,S=(A)=>A){let A={};for(let[$,F]of f.entries())if(F.isJson){let J=T.relations[F.tsKey],t=n[$],R=typeof t==="string"?JSON.parse(t):t;A[F.tsKey]=X(J,on)?R&&LS(o,o[F.relationTableTsKey],R,F.selection,S):R.map((W)=>LS(o,o[F.relationTableTsKey],W,F.selection,S))}else{let J=S(n[$]),t=F.field,R;if(X(t,Wo))R=t;else if(X(t,j))R=t.decoder;else R=t.sql.decoder;A[F.tsKey]=J===null?null:R.mapFromDriverValue(J)}return A}import jy from"node:os";import hy from"node:fs";var CS=new Map,o$=new Map,T$=Symbol("OriginError"),gn={};class wT extends Promise{constructor(o,T,n,f,S={}){let A,$;super((F,J)=>{A=F,$=J});this.tagged=Array.isArray(o.raw),this.strings=o,this.args=T,this.handler=n,this.canceller=f,this.options=S,this.state=null,this.statement=null,this.resolve=(F)=>(this.active=!1,A(F)),this.reject=(F)=>(this.active=!1,$(F)),this.active=!1,this.cancelled=null,this.executed=!1,this.signature="",this[T$]=this.handler.debug?new Error:this.tagged&&My(this.strings)}get origin(){return(this.handler.debug?this[T$].stack:this.tagged&&o$.has(this.strings)?o$.get(this.strings):o$.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(o=1,T){if(this.options.simple=!1,typeof o==="function")T=o,o=1;if(this.cursorRows=o,typeof T==="function")return this.cursorFn=T,this;let n;return{[Symbol.asyncIterator]:()=>({next:()=>{if(this.executed&&!this.active)return{done:!0};n&&n();let f=new Promise((S,A)=>{this.cursorFn=($)=>{return S({value:$,done:!1}),new Promise((F)=>n=F)},this.resolve=()=>(this.active=!1,S({done:!0})),this.reject=($)=>(this.active=!1,A($))});return this.execute(),f},return(){return n&&n(gn),{done:!0}}})}}describe(){return this.options.simple=!1,this.onlyDescribe=this.options.prepare=!0,this}stream(){throw new Error(".stream has been renamed to .forEach")}forEach(o){return this.forEachFn=o,this.handle(),this}raw(){return this.isRaw=!0,this}values(){return this.isRaw="values",this}async handle(){!this.executed&&(this.executed=!0)&&await 1&&this.handler(this)}execute(){return this.handle(),this}then(){return this.handle(),super.then.apply(this,arguments)}catch(){return this.handle(),super.catch.apply(this,arguments)}finally(){return this.handle(),super.finally.apply(this,arguments)}}function My(o){if(CS.has(o))return CS.get(o);let T=Error.stackTraceLimit;return Error.stackTraceLimit=4,CS.set(o,new Error),Error.stackTraceLimit=T,CS.get(o)}class dn extends Error{constructor(o){super(o.message);this.name=this.constructor.name,Object.assign(this,o)}}var Bo={connection:f0,postgres:S0,generic:A0,notSupported:$0};function f0(o,T,n){let{host:f,port:S}=n||T,A=Object.assign(new Error("write "+o+" "+(T.path||f+":"+S)),{code:o,errno:o,address:T.path||f},T.path?{}:{port:S});return Error.captureStackTrace(A,f0),A}function S0(o){let T=new dn(o);return Error.captureStackTrace(T,S0),T}function A0(o,T){let n=Object.assign(new Error(o+": "+T),{code:o});return Error.captureStackTrace(n,A0),n}function $0(o){let T=Object.assign(new Error(o+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:o});return Error.captureStackTrace(T,$0),T}var yy={string:{to:25,from:null,serialize:(o)=>""+o},number:{to:0,from:[21,23,26,700,701],serialize:(o)=>""+o,parse:(o)=>+o},json:{to:114,from:[114,3802],serialize:(o)=>JSON.stringify(o),parse:(o)=>JSON.parse(o)},boolean:{to:16,from:16,serialize:(o)=>o===!0?"t":"f",parse:(o)=>o==="t"},date:{to:1184,from:[1082,1114,1184],serialize:(o)=>(o instanceof Date?o:new Date(o)).toISOString(),parse:(o)=>new Date(o)},bytea:{to:17,from:17,serialize:(o)=>"\\x"+Buffer.from(o).toString("hex"),parse:(o)=>Buffer.from(o.slice(2),"hex")}};class hS{then(){n$()}catch(){n$()}finally(){n$()}}class hf extends hS{constructor(o){super();this.value=xS(o)}}class CT extends hS{constructor(o,T,n){super();this.value=o,this.type=T,this.array=n}}class NS extends hS{constructor(o,T){super();this.first=o,this.rest=T}build(o,T,n,f){let S=ky.map(([A,$])=>({fn:$,i:o.search(A)})).sort((A,$)=>A.i-$.i).pop();return S.i===-1?F$(this.first,f):S.fn(this.first,this.rest,T,n,f)}}function bS(o,T,n,f){let S=o instanceof CT?o.value:o;if(S===void 0){if(o instanceof CT?o.value=f.transform.undefined:S=o=f.transform.undefined,S===void 0)throw Bo.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return"$"+n.push(o instanceof CT?(T.push(o.value),o.array?o.array[o.type||jS(o.value)]||o.type||R0(o.value):o.type):(T.push(o),jS(o)))}var J0=y0(yy);function A$(o,T,n,f,S,A){for(let $=1;$<o.strings.length;$++)T+=$$(T,n,f,S,A)+o.strings[$],n=o.args[$];return T}function $$(o,T,n,f,S){return T instanceof NS?T.build(o,n,f,S):T instanceof wT?S$(T,n,f,S):T instanceof hf?T.value:T&&T[0]instanceof wT?T.reduce((A,$)=>A+" "+S$($,n,f,S),""):bS(T,n,f,S)}function S$(o,T,n,f){return o.fragment=!0,A$(o,o.strings[0],o.args[0],T,n,f)}function t0(o,T,n,f,S){return o.map((A)=>"("+f.map(($)=>$$("values",A[$],T,n,S)).join(",")+")").join(",")}function F0(o,T,n,f,S){let A=Array.isArray(o[0]),$=T.length?T.flat():Object.keys(A?o[0]:o);return t0(A?o:[o],n,f,$,S)}function IS(o,T,n,f,S){if(typeof o==="string"&&(o=[o].concat(T)),Array.isArray(o))return F$(o,S);let A;return(T.length?T.flat():Object.keys(o)).map((F)=>{return A=o[F],(A instanceof wT?S$(A,n,f,S):A instanceof hf?A.value:bS(A,n,f,S))+" as "+xS(S.transform.column.to?S.transform.column.to(F):F)}).join(",")}var ky=Object.entries({values:F0,in:(...o)=>{let T=F0(...o);return T==="()"?"(null)":T},select:IS,as:IS,returning:IS,"\\(":IS,update(o,T,n,f,S){return(T.length?T.flat():Object.keys(o)).map((A)=>xS(S.transform.column.to?S.transform.column.to(A):A)+"="+$$("values",o[A],n,f,S))},insert(o,T,n,f,S){let A=T.length?T.flat():Object.keys(Array.isArray(o)?o[0]:o);return"("+F$(A,S)+")values"+t0(Array.isArray(o)?o:[o],n,f,A,S)}}).map(([o,T])=>[new RegExp("((?:^|[\\s(])"+o+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),T]);function n$(){throw Bo.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}var{serializers:Wy,parsers:Oy}=J0;function R0(o){if(Array.isArray(o))return R0(o[0]);return typeof o==="string"?1009:0}var M0=function(o){let T=y0(o||{});return{serializers:Object.assign({},Wy,T.serializers),parsers:Object.assign({},Oy,T.parsers)}};function y0(o){return Object.keys(o).reduce((T,n)=>{if(o[n].from&&[].concat(o[n].from).forEach((f)=>T.parsers[f]=o[n].parse),o[n].serialize)T.serializers[o[n].to]=o[n].serialize,o[n].from&&[].concat(o[n].from).forEach((f)=>T.serializers[f]=o[n].serialize);return T},{parsers:{},serializers:{}})}function F$(o,{transform:{column:T}}){return o.map((n)=>xS(T.to?T.to(n):n)).join(",")}var xS=function o(T){return'"'+T.replace(/"/g,'""').replace(/\./g,'"."')+'"'},jS=function o(T){return T instanceof CT?T.type:T instanceof Date?1184:T instanceof Uint8Array?17:T===!0||T===!1?16:typeof T==="bigint"?20:Array.isArray(T)?o(T[0]):0},wy=/\\/g,_y=/"/g;function Xy(o){return o.replace(wy,"\\\\").replace(_y,"\\\"")}var k0=function o(T,n,f,S){if(Array.isArray(T)===!1)return T;if(!T.length)return"{}";let A=T[0],$=S===1020?";":",";if(Array.isArray(A)&&!A.type)return"{"+T.map((F)=>o(F,n,f,S)).join($)+"}";return"{"+T.map((F)=>{if(F===void 0){if(F=f.transform.undefined,F===void 0)throw Bo.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return F===null?"null":'"'+Xy(n?n(F.type?F.value:F):""+F)+'"'}).join($)+"}"},f$={i:0,char:null,str:"",quoted:!1,last:0},W0=function o(T,n,f){return f$.i=f$.last=0,O0(f$,T,n,f)};function O0(o,T,n,f){let S=[],A=f===1020?";":",";for(;o.i<T.length;o.i++){if(o.char=T[o.i],o.quoted)if(o.char==="\\")o.str+=T[++o.i];else if(o.char==='"')S.push(n?n(o.str):o.str),o.str="",o.quoted=T[o.i+1]==='"',o.last=o.i+2;else o.str+=o.char;else if(o.char==='"')o.quoted=!0;else if(o.char==="{")o.last=++o.i,S.push(O0(o,T,n,f));else if(o.char==="}"){o.quoted=!1,o.last<o.i&&S.push(n?n(T.slice(o.last,o.i)):T.slice(o.last,o.i)),o.last=o.i+1;break}else if(o.char===A&&o.p!=="}"&&o.p!=='"')S.push(n?n(T.slice(o.last,o.i)):T.slice(o.last,o.i)),o.last=o.i+1;o.p=o.char}return o.last<o.i&&S.push(n?n(T.slice(o.last,o.i+1)):T.slice(o.last,o.i+1)),S}var Wn=(o)=>{let T=o[0];for(let n=1;n<o.length;n++)T+=o[n]==="_"?o[++n].toUpperCase():o[n];return T},On=(o)=>{let T=o[0].toUpperCase();for(let n=1;n<o.length;n++)T+=o[n]==="_"?o[++n].toUpperCase():o[n];return T},wn=(o)=>o.replace(/_/g,"-"),Cf=(o)=>o.replace(/([A-Z])/g,"_$1").toLowerCase(),If=(o)=>(o.slice(0,1)+o.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),jf=(o)=>o.replace(/-/g,"_");function J$(o){return function T(n,f){return typeof n==="object"&&n!==null&&(f.type===114||f.type===3802)?Array.isArray(n)?n.map((S)=>T(S,f)):Object.entries(n).reduce((S,[A,$])=>Object.assign(S,{[o(A)]:T($,f)}),{}):n}}Wn.column={from:Wn};Wn.value={from:J$(Wn)};Cf.column={to:Cf};var t$={...Wn};t$.column.to=Cf;On.column={from:On};On.value={from:J$(On)};If.column={to:If};var R$={...On};R$.column.to=If;wn.column={from:wn};wn.value={from:J$(wn)};jf.column={to:jf};var M$={...wn};M$.column.to=jf;import w0 from"node:net";import Gy from"node:tls";import Nf from"node:crypto";import y$ from"node:stream";import{performance as _0}from"node:perf_hooks";class _n 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 MT=Hy;function Hy(o=[]){let T=o.slice(),n=0;return{get length(){return T.length-n},remove:(f)=>{let S=T.indexOf(f);return S===-1?null:(T.splice(S,1),f)},push:(f)=>(T.push(f),f),shift:()=>{let f=T[n++];if(n===T.length)n=0,T=[];else T[n-1]=void 0;return f}}}var eo=Buffer.allocUnsafe(256),Ky="BCcDdEFfHPpQSX".split("").reduce((o,T)=>{let n=T.charCodeAt(0);return o[T]=()=>{return eo[0]=n,yo.i=5,yo},o},{}),yo=Object.assign(Ey,Ky,{N:String.fromCharCode(0),i:0,inc(o){return yo.i+=o,yo},str(o){let T=Buffer.byteLength(o);return vS(T),yo.i+=eo.write(o,yo.i,T,"utf8"),yo},i16(o){return vS(2),eo.writeUInt16BE(o,yo.i),yo.i+=2,yo},i32(o,T){if(T||T===0)return eo.writeUInt32BE(o,T),yo;return vS(4),eo.writeUInt32BE(o,yo.i),yo.i+=4,yo},z(o){return vS(o),eo.fill(0,yo.i,yo.i+o),yo.i+=o,yo},raw(o){return eo=Buffer.concat([eo.subarray(0,yo.i),o]),yo.i=eo.length,yo},end(o=1){eo.writeUInt32BE(yo.i-o,o);let T=eo.subarray(0,yo.i);return yo.i=0,eo=Buffer.allocUnsafe(256),T}}),c=yo;function vS(o){if(eo.length-yo.i<o){let T=eo,n=T.length;eo=Buffer.allocUnsafe(n+(n>>1)+o),T.copy(eo)}}function Ey(){return yo.i=0,yo}var O$=K0,Yy=1,Tn=c().S().end(),X0=c().H().end(),zy=c().i32(8).i32(80877103).end(8),Dy=Buffer.concat([c().E().str(c.N).i32(0).end(),Tn]),Qy=c().D().str("S").str(c.N).end(),ln=()=>{},Uy=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),Vy={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 K0(o,T={},{onopen:n=ln,onend:f=ln,onclose:S=ln}={}){let{ssl:A,max:$,user:F,host:J,port:t,database:R,parsers:W,transform:O,onnotice:_,onnotify:Q,onparameter:H,max_pipeline:m,keep_alive:b,backoff:r,target_session_attrs:P}=o,E=MT(),z=Yy++,U={pid:null,secret:null},D=W$(sS,o.idle_timeout),v=W$(sS,o.max_lifetime),l=W$(p0,o.connect_timeout),K=null,s,q=new _n,a=Buffer.alloc(0),ko=o.fetch_types,mo={},nT={},IT=Math.random().toString(36).slice(2),G=1,p=0,Fo=0,Go=0,Lo=0,To=0,wo=0,Vo=0,Yo=null,Ho=null,Zo=!1,_o=null,_T=null,Po=null,cT=null,Co=null,Ko=null,XT=null,QT=null,B=null,an=null,io={queue:T.closed,idleTimer:D,connect(M){Po=M||!0,p$()},terminate:Tf,execute:of,cancel:x0,end:sS,count:0,id:z};return T.closed&&T.closed.push(io),io;async function b0(){let M;try{M=o.socket?await Promise.resolve(o.socket(o)):new w0.Socket}catch(w){En(w);return}return M.on("error",En),M.on("close",c$),M.on("drain",r$),M}async function x0({pid:M,secret:w},Z,Jo){try{s=c().i32(16).i32(80877102).i32(M).i32(w).end(16),await q$(),K.once("error",Jo),K.once("close",Z)}catch(Do){Jo(Do)}}function of(M){if(Zo)return cf(M,Bo.connection("CONNECTION_DESTROYED",o));if(M.cancelled)return;try{return M.state=U,B?E.push(M):(B=M,B.active=!0),q0(M),ro(v0(M))&&!M.describeFirst&&!M.cursorFn&&E.length<m&&(!M.options.onexecute||M.options.onexecute(io))}catch(w){return E.length===0&&ro(Tn),UT(w),!0}}function v0(M){if(M.parameters.length>=65534)throw Bo.generic("MAX_PARAMETERS_EXCEEDED","Max number of parameters (65534) exceeded");return M.options.simple?c().Q().str(M.statement.string+c.N).end():M.describeFirst?Buffer.concat([b$(M),X0]):M.prepare?M.prepared?pf(M):Buffer.concat([b$(M),pf(M)]):r0(M)}function b$(M){return Buffer.concat([P$(M.statement.string,M.parameters,M.statement.types,M.statement.name),QM("S",M.statement.name)])}function pf(M){return Buffer.concat([DM(M.parameters,M.statement.types,M.statement.name,M.cursorName),M.cursorFn?i$("",M.cursorRows):Dy])}function r0(M){return Buffer.concat([P$(M.statement.string,M.parameters,M.statement.types),Qy,pf(M)])}function q0(M){let w=[],Z=[],Jo=A$(M,M.strings[0],M.args[0],w,Z,o);!M.tagged&&M.args.forEach((Do)=>bS(Do,w,Z,o)),M.prepare=o.prepare&&("prepare"in M.options?M.options.prepare:!0),M.string=Jo,M.signature=M.prepare&&Z+Jo,M.onlyDescribe&&delete nT[M.signature],M.parameters=M.parameters||w,M.prepared=M.prepare&&M.signature in nT,M.describeFirst=M.onlyDescribe||w.length&&!M.prepared,M.statement=M.prepared?nT[M.signature]:{string:Jo,types:Z,name:M.prepare?IT+G++:""},typeof o.debug==="function"&&o.debug(z,Jo,w,Z)}function ro(M,w){if(Ko=Ko?Buffer.concat([Ko,M]):Buffer.from(M),w||Ko.length>=1024)return x$(w);return Ho===null&&(Ho=setImmediate(x$)),!0}function x$(M){let w=K.write(Ko,M);return Ho!==null&&clearImmediate(Ho),Ko=Ho=null,w}function p0(){UT(Bo.connection("CONNECT_TIMEOUT",o,K)),K.destroy()}async function v$(){if(ro(zy),!await new Promise((w)=>K.once("data",(Z)=>w(Z[0]===83)))&&A==="prefer")return Kn();K.removeAllListeners(),K=Gy.connect({socket:K,servername:w0.isIP(K.host)?void 0:K.host,...A==="require"||A==="allow"||A==="prefer"?{rejectUnauthorized:!1}:A==="verify-full"?{}:typeof A==="object"?A:{}}),K.on("secureConnect",Kn),K.on("error",En),K.on("close",c$),K.on("drain",r$)}function r$(){!B&&n(io)}function eS(M){if(_o){if(_o.push(M),Fo-=M.length,Fo>=0)return}a=_o?Buffer.concat(_o,To-Fo):a.length===0?M:Buffer.concat([a,M],a.length+M.length);while(a.length>4){if(To=a.readUInt32BE(1),To>=a.length){Fo=To-a.length,_o=[a];break}try{c0(a.subarray(0,To+1))}catch(w){B&&(B.cursorFn||B.describeFirst)&&ro(Tn),UT(w)}a=a.subarray(To+1),Fo=0,_o=null}}async function q$(){if(Zo=!1,mo={},K||(K=await b0()),!K)return;if(l.start(),o.socket)return A?v$():Kn();if(K.on("connect",A?v$:Kn),o.path)return K.connect(o.path);K.ssl=A,K.connect(t[Go],J[Go]),K.host=J[Go],K.port=t[Go],Go=(Go+1)%t.length}function p$(){setTimeout(q$,p?p+wo-_0.now():0)}function Kn(){try{nT={},ko=o.fetch_types,IT=Math.random().toString(36).slice(2),G=1,v.start(),K.on("data",eS),b&&K.setKeepAlive&&K.setKeepAlive(!0,1000*b);let M=VM();ro(M)}catch(M){En(M)}}function En(M){if(io.queue===T.connecting&&o.host[Lo+1])return;UT(M);while(E.length)cf(E.shift(),M)}function UT(M){Co&&(Co.destroy(M),Co=null),B&&cf(B,M),Po&&(cf(Po,M),Po=null)}function cf(M,w){"query"in w||"parameters"in w||Object.defineProperties(w,{stack:{value:w.stack+M.origin.replace(/.*\n/,`
|
|
17
|
+
`),enumerable:o.debug},query:{value:M.string,enumerable:o.debug},parameters:{value:M.parameters,enumerable:o.debug},args:{value:M.args,enumerable:o.debug},types:{value:M.statement&&M.statement.types,enumerable:o.debug}}),M.reject(w)}function sS(){return cT||(!io.reserved&&f(io),!io.reserved&&!Po&&!B&&E.length===0?(Tf(),new Promise((M)=>K&&K.readyState!=="closed"?K.once("close",M):M())):cT=new Promise((M)=>XT=M))}function Tf(){if(Zo=!0,Co||B||Po||E.length)En(Bo.connection("CONNECTION_DESTROYED",o));if(clearImmediate(Ho),K)K.removeListener("data",eS),K.removeListener("connect",Kn),K.readyState==="open"&&K.end(c().X().end());XT&&(XT(),cT=XT=null)}async function c$(M){if(a=Buffer.alloc(0),Fo=0,_o=null,clearImmediate(Ho),K.removeListener("data",eS),K.removeListener("connect",Kn),D.cancel(),v.cancel(),l.cancel(),K.removeAllListeners(),K=null,Po)return p$();!M&&(B||E.length)&&En(Bo.connection("CONNECTION_CLOSED",o,K)),p=_0.now(),M&&o.shared.retries++,wo=(typeof r==="function"?r(o.shared.retries):r)*1000,S(io,Bo.connection("CONNECTION_CLOSED",o,K))}function c0(M,w=M[0]){(w===68?Z0:w===100?_M:w===65?MM:w===83?P0:w===90?i0:w===67?g0:w===50?Z$:w===49?d0:w===116?l0:w===84?u0:w===82?e0:w===110?fM:w===75?SM:w===69?tM:w===115?yM:w===51?kM:w===71?WM:w===78?HM:w===72?OM:w===99?XM:w===73?KM:w===86?EM:w===118?GM:w===87?wM:YM)(M)}function Z0(M){let w=7,Z,Jo,Do,go=B.isRaw?new Array(B.statement.columns.length):{};for(let so=0;so<B.statement.columns.length;so++)Jo=B.statement.columns[so],Z=M.readInt32BE(w),w+=4,Do=Z===-1?null:B.isRaw===!0?M.subarray(w,w+=Z):Jo.parser===void 0?M.toString("utf8",w,w+=Z):Jo.parser.array===!0?Jo.parser(M.toString("utf8",w+1,w+=Z)):Jo.parser(M.toString("utf8",w,w+=Z)),B.isRaw?go[so]=B.isRaw===!0?Do:O.value.from?O.value.from(Do,Jo):Do:go[Jo.name]=O.value.from?O.value.from(Do,Jo):Do;B.forEachFn?B.forEachFn(O.row.from?O.row.from(go):go,q):q[Vo++]=O.row.from?O.row.from(go):go}function P0(M){let[w,Z]=M.toString("utf8",5,M.length-1).split(c.N);if(mo[w]=Z,o.parameters[w]!==Z)o.parameters[w]=Z,H&&H(w,Z)}function i0(M){if(B&&B.options.simple&&B.resolve(_T||q),B=_T=null,q=new _n,l.cancel(),Po){if(P){if(!mo.in_hot_standby||!mo.default_transaction_read_only)return JM();else if(FM(P,mo))return Tf()}if(ko)return Po===!0&&(Po=null),AM();Po!==!0&&of(Po),o.shared.retries=Lo=0,Po=null;return}while(E.length&&(B=E.shift())&&(B.active=!0,B.cancelled))K0(o).cancel(B.state,B.cancelled.resolve,B.cancelled.reject);if(B)return;io.reserved?!io.reserved.release&&M[5]===73?cT?Tf():(io.reserved=null,n(io)):io.reserved():cT?Tf():n(io)}function g0(M){Vo=0;for(let w=M.length-1;w>0;w--){if(M[w]===32&&M[w+1]<58&&q.count===null)q.count=+M.toString("utf8",w+1,M.length-1);if(M[w-1]>=65){q.command=M.toString("utf8",5,w),q.state=U;break}}if(an&&(an(),an=null),q.command==="BEGIN"&&$!==1&&!io.reserved)return UT(Bo.generic("UNSAFE_TRANSACTION","Only use sql.begin, sql.reserved or max: 1"));if(B.options.simple)return Z$();if(B.cursorFn)q.count&&B.cursorFn(q),ro(Tn);B.resolve(q)}function d0(){B.parsing=!1}function Z$(){!q.statement&&(q.statement=B.statement),q.columns=B.statement.columns}function l0(M){let w=M.readUInt16BE(5);for(let Z=0;Z<w;++Z)!B.statement.types[Z]&&(B.statement.types[Z]=M.readUInt32BE(7+Z*4));B.prepare&&(nT[B.signature]=B.statement),B.describeFirst&&!B.onlyDescribe&&(ro(pf(B)),B.describeFirst=!1)}function u0(M){if(q.command)_T=_T||[q],_T.push(q=new _n),q.count=null,B.statement.columns=null;let w=M.readUInt16BE(5),Z=7,Jo;B.statement.columns=Array(w);for(let Do=0;Do<w;++Do){Jo=Z;while(M[Z++]!==0);let go=M.readUInt32BE(Z),so=M.readUInt16BE(Z+4),ZT=M.readUInt32BE(Z+6);B.statement.columns[Do]={name:O.column.from?O.column.from(M.toString("utf8",Jo,Z-1)):M.toString("utf8",Jo,Z-1),parser:W[ZT],table:go,number:so,type:ZT},Z+=18}if(q.statement=B.statement,B.onlyDescribe)return B.resolve(B.statement),ro(Tn)}async function e0(M,w=M.readUInt32BE(5)){(w===3?s0:w===5?a0:w===10?oM:w===11?TM:w===12?nM:w!==0?zM:ln)(M,w)}async function s0(){let M=await aS();ro(c().p().str(M).z(1).end())}async function a0(M){let w="md5"+await H0(Buffer.concat([Buffer.from(await H0(await aS()+F)),M.subarray(9)]));ro(c().p().str(w).z(1).end())}async function oM(){QT=(await Nf.randomBytes(18)).toString("base64"),c().p().str("SCRAM-SHA-256"+c.N);let M=c.i;ro(c.inc(4).str("n,,n=*,r="+QT).i32(c.i-M-4,M).end())}async function TM(M){let w=M.toString("utf8",9).split(",").reduce((so,ZT)=>(so[ZT[0]]=ZT.slice(2),so),{}),Z=await Nf.pbkdf2Sync(await aS(),Buffer.from(w.s,"base64"),parseInt(w.i),32,"sha256"),Jo=await rS(Z,"Client Key"),Do="n=*,r="+QT+",r="+w.r+",s="+w.s+",i="+w.i+",c=biws,r="+w.r;Yo=(await rS(await rS(Z,"Server Key"),Do)).toString("base64");let go="c=biws,r="+w.r+",p="+my(Jo,Buffer.from(await rS(await By(Jo),Do))).toString("base64");ro(c().p().str(go).end())}function nM(M){if(M.toString("utf8",9).split(c.N,1)[0].slice(2)===Yo)return;UT(Bo.generic("SASL_SIGNATURE_MISMATCH","The server did not return the correct signature")),K.destroy()}function aS(){return Promise.resolve(typeof o.pass==="function"?o.pass():o.pass)}function fM(){if(q.statement=B.statement,q.statement.columns=[],B.onlyDescribe)return B.resolve(B.statement),ro(Tn)}function SM(M){U.pid=M.readUInt32BE(5),U.secret=M.readUInt32BE(9)}async function AM(){ko=!1,(await new wT([`
|
|
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
|
-
`],[],of)).forEach(({oid:w,typarray:Z})
|
|
24
|
+
`],[],of)).forEach(({oid:w,typarray:Z})=>$M(w,Z))}function $M(M,w){if(!!o.parsers[w]&&!!o.serializers[w])return;let Z=o.parsers[M];o.shared.typeArrayMap[M]=w,o.parsers[w]=(Jo)=>W0(Jo,Z,w),o.parsers[w].array=!0,o.serializers[w]=(Jo)=>k0(Jo,o.serializers[M],o,w)}function FM(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"&&o.host[Lo]}function JM(){let M=new wT([`
|
|
25
25
|
show transaction_read_only;
|
|
26
26
|
select pg_catalog.pg_is_in_recovery()
|
|
27
|
-
`],[],of,null,{simple:!0});M.resolve=([[w],[Z]])=>{
|
|
27
|
+
`],[],of,null,{simple:!0});M.resolve=([[w],[Z]])=>{mo.default_transaction_read_only=w.transaction_read_only,mo.in_hot_standby=Z.pg_is_in_recovery?"on":"off"},M.execute()}function tM(M){B&&(B.cursorFn||B.describeFirst)&&ro(Tn);let w=Bo.postgres(k$(M));B&&B.retried?UT(B.retried):B&&B.prepared&&Uy.has(w.routine)?RM(B,w):UT(w)}function RM(M,w){delete nT[M.signature],M.retried=w,of(M)}function MM(M){if(!Q)return;let w=9;while(M[w++]!==0);Q(M.toString("utf8",9,w-1),M.toString("utf8",w,M.length-1))}async function yM(){try{let M=await Promise.resolve(B.cursorFn(q));Vo=0,M===gn?ro(UM(B.portal)):(q=new _n,ro(i$("",B.cursorRows)))}catch(M){ro(Tn),B.reject(M)}}function kM(){q.count&&B.cursorFn(q),B.resolve(q)}function WM(){Co=new y$.Writable({autoDestroy:!0,write(M,w,Z){K.write(c().d().raw(M).end(),Z)},destroy(M,w){w(M),K.write(c().f().str(M+c.N).end()),Co=null},final(M){K.write(c().c().end()),an=M}}),B.resolve(Co)}function OM(){Co=new y$.Readable({read(){K.resume()}}),B.resolve(Co)}function wM(){Co=new y$.Duplex({autoDestroy:!0,read(){K.resume()},write(M,w,Z){K.write(c().d().raw(M).end(),Z)},destroy(M,w){w(M),K.write(c().f().str(M+c.N).end()),Co=null},final(M){K.write(c().c().end()),an=M}}),B.resolve(Co)}function _M(M){Co&&(Co.push(M.subarray(5))||K.pause())}function XM(){Co&&Co.push(null),Co=null}function HM(M){_?_(k$(M)):console.log(k$(M))}function KM(){}function EM(){UT(Bo.notSupported("FunctionCallResponse"))}function GM(){UT(Bo.notSupported("NegotiateProtocolVersion"))}function YM(M){console.error("Postgres.js : Unknown Message:",M[0])}function zM(M,w){console.error("Postgres.js : Unknown Auth:",w)}function DM(M,w,Z="",Jo=""){let Do,go;return c().B().str(Jo+c.N).str(Z+c.N).i16(0).i16(M.length),M.forEach((so,ZT)=>{if(so===null)return c.i32(4294967295);go=w[ZT],M[ZT]=so=go in o.serializers?o.serializers[go](so):""+so,Do=c.i,c.inc(4).str(so).i32(c.i-Do-4,Do)}),c.i16(0),c.end()}function P$(M,w,Z,Jo=""){return c().P().str(Jo+c.N).str(M+c.N).i16(w.length),w.forEach((Do,go)=>c.i32(Z[go]||0)),c.end()}function QM(M,w=""){return c().D().str(M).str(w+c.N).end()}function i$(M="",w=0){return Buffer.concat([c().E().str(M+c.N).i32(w).end(),X0])}function UM(M=""){return Buffer.concat([c().C().str("P").str(M+c.N).end(),c().S().end()])}function VM(){return s||c().inc(4).i16(3).z(2).str(Object.entries(Object.assign({user:F,database:R,client_encoding:"UTF8"},o.connection)).filter(([,M])=>M).map(([M,w])=>M+c.N+w).join(c.N)).z(2).end(0)}}function k$(o){let T={},n=5;for(let f=5;f<o.length-1;f++)if(o[f]===0)T[Vy[o[n]]]=o.toString("utf8",n+1,f),n=f+1;return T}function H0(o){return Nf.createHash("md5").update(o).digest("hex")}function rS(o,T){return Nf.createHmac("sha256",o).update(T).digest()}function By(o){return Nf.createHash("sha256").update(o).digest()}function my(o,T){let n=Math.max(o.length,T.length),f=Buffer.allocUnsafe(n);for(let S=0;S<n;S++)f[S]=o[S]^T[S];return f}function W$(o,T){if(T=typeof T==="function"?T():T,!T)return{cancel:ln,start:ln};let n;return{cancel(){n&&(clearTimeout(n),n=null)},start(){n&&clearTimeout(n),n=setTimeout(f,T*1000,arguments)}};function f(S){o.apply(null,S),n=null}}var E0=()=>{};function w$(o,T){let n=new Map,f="postgresjs_"+Math.random().toString(36).slice(2),S={},A,$,F=!1,J=W.sql=o({...T,transform:{column:{},value:{},row:{}},max:1,fetch_types:!1,idle_timeout:null,max_lifetime:null,connection:{...T.connection,replication:"database"},onclose:async function(){if(F)return;$=null,S.pid=S.secret=void 0,O(await _(J,f,T.publications)),n.forEach((H)=>H.forEach(({onsubscribe:m})=>m()))},no_subscribe:!0}),t=J.end,R=J.close;return J.end=async()=>{return F=!0,$&&await new Promise((H)=>($.once("close",H),$.end())),t()},J.close=async()=>{return $&&await new Promise((H)=>($.once("close",H),$.end())),R()},W;async function W(H,m,b=E0,r=E0){if(H=Iy(H),!A)A=_(J,f,T.publications);let P={fn:m,onsubscribe:b},E=n.has(H)?n.get(H).add(P):n.set(H,new Set([P])).get(H),z=()=>{E.delete(P),E.size===0&&n.delete(H)};return A.then((U)=>{return O(U),b(),$&&$.on("error",r),{unsubscribe:z,state:S,sql:J}})}function O(H){$=H.stream,S.pid=H.state.pid,S.secret=H.state.secret}async function _(H,m,b){if(!b)throw new Error("Missing publication names");let r=await H.unsafe(`CREATE_REPLICATION_SLOT ${m} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT`),[P]=r,E=await H.unsafe(`START_REPLICATION SLOT ${m} LOGICAL ${P.consistent_point} (proto_version '1', publication_names '${b}')`).writable(),z={lsn:Buffer.concat(P.consistent_point.split("/").map((K)=>Buffer.from(("00000000"+K).slice(-8),"hex")))};return E.on("data",D),E.on("error",U),E.on("close",H.close),{stream:E,state:r.state};function U(K){console.error("Unexpected error during logical streaming - reconnecting",K)}function D(K){if(K[0]===119)Cy(K.subarray(25),z,H.options.parsers,v,T.transform);else if(K[0]===107&&K[17])z.lsn=K.subarray(1,9),l()}function v(K,s){let q=s.relation.schema+"."+s.relation.table;Q("*",K,s),Q("*:"+q,K,s),s.relation.keys.length&&Q("*:"+q+"="+s.relation.keys.map((a)=>K[a.name]),K,s),Q(s.command,K,s),Q(s.command+":"+q,K,s),s.relation.keys.length&&Q(s.command+":"+q+"="+s.relation.keys.map((a)=>K[a.name]),K,s)}function l(){let K=Buffer.alloc(34);K[0]=114,K.fill(z.lsn,1),K.writeBigInt64BE(BigInt(Date.now()-Date.UTC(2000,0,1))*BigInt(1000),25),E.write(K)}}function Q(H,m,b){n.has(H)&&n.get(H).forEach(({fn:r})=>r(m,b,H))}}function Ly(o){return new Date(Date.UTC(2000,0,1)+Number(o/BigInt(1000)))}function Cy(o,T,n,f,S){let A=($,[F,J])=>($[F.charCodeAt(0)]=J,$);Object.entries({R:($)=>{let F=1,J=T[$.readUInt32BE(F)]={schema:$.toString("utf8",F+=4,F=$.indexOf(0,F))||"pg_catalog",table:$.toString("utf8",F+1,F=$.indexOf(0,F+1)),columns:Array($.readUInt16BE(F+=2)),keys:[]};F+=2;let t=0,R;while(F<$.length)R=J.columns[t++]={key:$[F++],name:S.column.from?S.column.from($.toString("utf8",F,F=$.indexOf(0,F))):$.toString("utf8",F,F=$.indexOf(0,F)),type:$.readUInt32BE(F+=1),parser:n[$.readUInt32BE(F)],atttypmod:$.readUInt32BE(F+=4)},R.key&&J.keys.push(R),F+=4},Y:()=>{},O:()=>{},B:($)=>{T.date=Ly($.readBigInt64BE(9)),T.lsn=$.subarray(1,9)},I:($)=>{let F=1,J=T[$.readUInt32BE(F)],{row:t}=qS($,J.columns,F+=7,S);f(t,{command:"insert",relation:J})},D:($)=>{let F=1,J=T[$.readUInt32BE(F)];F+=4;let t=$[F]===75;f(t||$[F]===79?qS($,J.columns,F+=3,S).row:null,{command:"delete",relation:J,key:t})},U:($)=>{let F=1,J=T[$.readUInt32BE(F)];F+=4;let t=$[F]===75,R=t||$[F]===79?qS($,J.columns,F+=3,S):null;R&&(F=R.i);let{row:W}=qS($,J.columns,F+3,S);f(W,{command:"update",relation:J,key:t,old:R&&R.row})},T:()=>{},C:()=>{}}).reduce(A,{})[o[0]](o)}function qS(o,T,n,f){let S,A,$,F=f.raw?new Array(T.length):{};for(let J=0;J<T.length;J++)S=o[n++],A=T[J],$=S===110?null:S===117?void 0:A.parser===void 0?o.toString("utf8",n+4,n+=4+o.readUInt32BE(n)):A.parser.array===!0?A.parser(o.toString("utf8",n+5,n+=4+o.readUInt32BE(n))):A.parser(o.toString("utf8",n+4,n+=4+o.readUInt32BE(n))),f.raw?F[J]=f.raw===!0?$:f.value.from?f.value.from($,A):$:F[A.name]=f.value.from?f.value.from($,A):$;return{i:n,row:f.row.from?f.row.from(F):F}}function Iy(o){let T=o.match(/^(\*|insert|update|delete)?:?([^.]+?\.?[^=]+)?=?(.+)?/i)||[];if(!T)throw new Error("Malformed subscribe pattern: "+o);let[,n,f,S]=T;return(n||"*")+(f?":"+(f.indexOf(".")===-1?"public."+f:f):"")+(S?"="+S:"")}import G0 from"node:stream";function _$(o,T,n=393216){return new Promise(async(f,S)=>{await o.begin(async(A)=>{let $;!T&&([{oid:T}]=await A`select lo_creat(-1) as oid`);let[{fd:F}]=await A`select lo_open(${T}, ${n}) as fd`,J={writable:R,readable:t,close:()=>A`select lo_close(${F})`.then($),tell:()=>A`select lo_tell64(${F})`,read:(W)=>A`select loread(${F}, ${W}) as data`,write:(W)=>A`select lowrite(${F}, ${W})`,truncate:(W)=>A`select lo_truncate64(${F}, ${W})`,seek:(W,O=0)=>A`select lo_lseek64(${F}, ${W}, ${O})`,size:()=>A`
|
|
28
28
|
select
|
|
29
29
|
lo_lseek64(${F}, location, 0) as position,
|
|
30
30
|
seek.size
|
|
@@ -34,10 +34,10 @@ ${$.trace}`:"No previous disposal trace was found."),f.type){case"atom_family":c
|
|
|
34
34
|
tell.location
|
|
35
35
|
from (select lo_tell64($1) as location) tell
|
|
36
36
|
) seek
|
|
37
|
-
`};return f(J),new Promise(async(W)=>$=W);async function t({highWaterMark:W=16384,start:O=0,end:_=1/0}={}){let Q=_-O;return O&&await J.seek(O),new X0.Readable({highWaterMark:W,async read(K){let B=K>Q?K-Q:K;Q-=K;let[{data:h}]=await J.read(B);if(this.push(h),h.length<K)this.push(null)}})}async function R({highWaterMark:W=16384,start:O=0}={}){return O&&await J.seek(O),new X0.Writable({highWaterMark:W,write(_,Q,K){J.write(_).then(()=>K(),K)}})}}).catch(S)})}Object.assign(pS,{PostgresError:dT,toPascal:wT,pascal:R$,toCamel:OT,camel:t$,toKebab:_T,kebab:M$,fromPascal:If,fromCamel:Cf,fromKebab:jf,BigInt:{to:20,from:[20],parse:(o)=>BigInt(o),serialize:(o)=>o.toString()}});var uT=pS;function pS(o,n){let T=C1(o,n),f=T.no_subscribe||w$(pS,{...T}),S=!1,A=Mn(),$=Mn(),F=Mn(),J=Mn(),t=Mn(),R=Mn(),W=Mn(),O=Mn(),_={connecting:$,reserved:F,closed:J,ended:t,open:R,busy:W,full:O},Q=[...Array(T.max)].map(()=>O$(T,_,{onopen:Tn,onend:Bo,onclose:In})),K=B(v);return Object.assign(K,{get parameters(){return T.parameters},largeObject:_$.bind(null,K),subscribe:f,CLOSE:gT,END:gT,PostgresError:dT,options:T,reserve:P,listen:h,begin:E,close:q,end:s}),K;function B(G){return G.debug=T.debug,Object.entries(T.types).reduce((no,[wo,Vo])=>{return no[wo]=(Yo)=>new Cn(Yo,Vo.to),no},p),Object.assign(Fo,{types:p,typed:p,unsafe:Go,notify:r,array:D,json:U,file:Lo}),Fo;function p(no,wo){return new Cn(no,wo)}function Fo(no,...wo){return no&&Array.isArray(no.raw)?new wn(no,wo,G,H):typeof no==="string"&&!wo.length?new Nf(T.transform.column.to?T.transform.column.to(no):no):new hS(no,wo)}function Go(no,wo=[],Vo={}){return arguments.length===2&&!Array.isArray(wo)&&(Vo=wo,wo=[]),new wn([no],wo,G,H,{prepare:!1,...Vo,simple:"simple"in Vo?Vo.simple:wo.length===0})}function Lo(no,wo=[],Vo={}){return arguments.length===2&&!Array.isArray(wo)&&(Vo=wo,wo=[]),new wn([],wo,(Ko)=>{L1.readFile(no,"utf8",(Zo,_o)=>{if(Zo)return Ko.reject(Zo);Ko.strings=[_o],G(Ko)})},H,{...Vo,simple:"simple"in Vo?Vo.simple:wo.length===0})}}async function h(G,p,Fo){let Go={fn:p,onlisten:Fo},Lo=h.sql||(h.sql=pS({...T,max:1,idle_timeout:null,max_lifetime:null,fetch_types:!1,onclose(){Object.entries(h.channels).forEach(([Ko,{listeners:Zo}])=>{delete h.channels[Ko],Promise.all(Zo.map((_o)=>h(Ko,_o.fn,_o.onlisten).catch(()=>{})))})},onnotify(Ko,Zo){Ko in h.channels&&h.channels[Ko].listeners.forEach((_o)=>_o.fn(Zo))}})),no=h.channels||(h.channels={});if(G in no){no[G].listeners.push(Go);let Ko=await no[G].result;return Go.onlisten&&Go.onlisten(),{state:Ko.state,unlisten:Yo}}no[G]={result:Lo`listen ${Lo.unsafe('"'+G.replace(/"/g,'""')+'"')}`,listeners:[Go]};let Vo=await no[G].result;return Go.onlisten&&Go.onlisten(),{state:Vo.state,unlisten:Yo};async function Yo(){if(G in no===!1)return;if(no[G].listeners=no[G].listeners.filter((Ko)=>Ko!==Go),no[G].listeners.length)return;return delete no[G],Lo`unlisten ${Lo.unsafe('"'+G.replace(/"/g,'""')+'"')}`}}async function r(G,p){return await K`select pg_notify(${G}, ${""+p})`}async function P(){let G=Mn(),p=R.length?R.shift():await new Promise((Lo)=>{A.push({reserve:Lo}),J.length&&ko(J.shift())});z(p,F),p.reserved=()=>G.length?p.execute(G.shift()):z(p,F),p.reserved.release=!0;let Fo=B(Go);return Fo.release=()=>{p.reserved=null,Tn(p)},Fo;function Go(Lo){p.queue===O?G.push(Lo):p.execute(Lo)||z(p,O)}}async function E(G,p){!p&&(p=G,G="");let Fo=Mn(),Go=0,Lo,no=null;try{return await K.unsafe("begin "+G.replace(/[^a-z ]/ig,""),[],{onexecute:Vo}).execute(),await Promise.race([wo(Lo,p),new Promise((Yo,Ko)=>Lo.onclose=Ko)])}catch(Yo){throw Yo}async function wo(Yo,Ko,Zo){let _o=B(Co);_o.savepoint=cn,_o.prepare=(Ho)=>no=Ho.replace(/[^a-z0-9$-_. ]/gi);let _n,Po;Zo&&await _o`savepoint ${_o(Zo)}`;try{if(Po=await new Promise((Ho,Xn)=>{let Qn=Ko(_o);Promise.resolve(Array.isArray(Qn)?Promise.all(Qn):Qn).then(Ho,Xn)}),_n)throw _n}catch(Ho){throw await(Zo?_o`rollback to ${_o(Zo)}`:_o`rollback`),Ho instanceof dT&&Ho.code==="25P02"&&_n||Ho}if(!Zo)no?await _o`prepare transaction '${_o.unsafe(no)}'`:await _o`commit`;return Po;function cn(Ho,Xn){if(Ho&&Array.isArray(Ho.raw))return cn((Qn)=>Qn.apply(Qn,arguments));return arguments.length===1&&(Xn=Ho,Ho=null),wo(Yo,Xn,"s"+Go+++(Ho?"_"+Ho:""))}function Co(Ho){Ho.catch((Xn)=>_n||(_n=Xn)),Yo.queue===O?Fo.push(Ho):Yo.execute(Ho)||z(Yo,O)}}function Vo(Yo){Lo=Yo,z(Yo,F),Yo.reserved=()=>Fo.length?Yo.execute(Fo.shift()):z(Yo,F)}}function z(G,p){return G.queue.remove(G),p.push(G),G.queue=p,p===R?G.idleTimer.start():G.idleTimer.cancel(),G}function U(G){return new Cn(G,3802)}function D(G,p){if(!Array.isArray(G))return D(Array.from(arguments));return new Cn(G,p||(G.length?jS(G)||25:0),T.shared.typeArrayMap)}function v(G){if(S)return G.reject(mo.connection("CONNECTION_ENDED",T,T));if(R.length)return l(R.shift(),G);if(J.length)return ko(J.shift(),G);W.length?l(W.shift(),G):A.push(G)}function l(G,p){return G.execute(p)?z(G,W):z(G,O)}function H(G){return new Promise((p,Fo)=>{G.state?G.active?O$(T).cancel(G.state,p,Fo):G.cancelled={resolve:p,reject:Fo}:(A.remove(G),G.cancelled=!0,G.reject(mo.generic("57014","canceling statement due to user request")),p())})}async function s({timeout:G=null}={}){if(S)return S;await 1;let p;return S=Promise.race([new Promise((Fo)=>G!==null&&(p=setTimeout(a,G*1000,Fo))),Promise.all(Q.map((Fo)=>Fo.end()).concat(h.sql?h.sql.end({timeout:0}):[],f.sql?f.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(p))}async function q(){await Promise.all(Q.map((G)=>G.end()))}async function a(G){await Promise.all(Q.map((p)=>p.terminate()));while(A.length)A.shift().reject(mo.connection("CONNECTION_DESTROYED",T));G()}function ko(G,p){return z(G,$),G.connect(p),G}function Bo(G){z(G,t)}function Tn(G){if(A.length===0)return z(G,R);let p=Math.ceil(A.length/($.length+1)),Fo=!0;while(Fo&&A.length&&p-- >0){let Go=A.shift();if(Go.reserve)return Go.reserve(G);Fo=G.execute(Go)}Fo?z(G,W):z(G,O)}function In(G,p){z(G,J),G.reserved=null,G.onclose&&(G.onclose(p),G.onclose=null),T.onclose&&T.onclose(G.id),A.length&&ko(G,A.shift())}}function C1(o,n){if(o&&o.shared)return o;let T=process.env,f=(!o||typeof o==="string"?n:o)||{},{url:S,multihost:A}=b1(o),$=[...S.searchParams].reduce((O,[_,Q])=>(O[_]=Q,O),{}),F=f.hostname||f.host||A||S.hostname||T.PGHOST||"localhost",J=f.port||S.port||T.PGPORT||5432,t=f.user||f.username||S.username||T.PGUSERNAME||T.PGUSER||x1();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 R=["idle_timeout","connect_timeout","max_lifetime","max_pipeline","backoff","keep_alive"],W={max:10,ssl:!1,idle_timeout:null,connect_timeout:30,max_lifetime:N1,max_pipeline:100,backoff:j1,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((O)=>O.split(":")[0]),port:Array.isArray(J)?J:F.split(",").map((O)=>parseInt(O.split(":")[1]||J)),path:f.path||F.indexOf("/")>-1&&F+"/.s.PGSQL."+J,database:f.database||f.db||(S.pathname||"").slice(1)||T.PGDATABASE||t,user:t,pass:f.pass||f.password||S.password||T.PGPASSWORD||"",...Object.entries(W).reduce((O,[_,Q])=>{let K=_ in f?f[_]:(_ in $)?$[_]==="disable"||$[_]==="false"?!1:$[_]:T["PG"+_.toUpperCase()]||Q;return O[_]=typeof K==="string"&&R.includes(_)?+K:K,O},{}),connection:{application_name:"postgres.js",...f.connection,...Object.entries($).reduce((O,[_,Q])=>((_ in W)||(O[_]=Q),O),{})},types:f.types||{},target_session_attrs:I1(f,S,T),onnotice:f.onnotice,onnotify:f.onnotify,onclose:f.onclose,onparameter:f.onparameter,socket:f.socket,transform:h1(f.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...F0(f.types)}}function I1(o,n,T){let f=o.target_session_attrs||n.searchParams.get("target_session_attrs")||T.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 j1(o){return(0.5+Math.random()/2)*Math.min(3**o/100,20)}function N1(){return 60*(30+Math.random()*30)}function h1(o){return{undefined:o.undefined,column:{from:typeof o.column==="function"?o.column:o.column&&o.column.from,to:o.column&&o.column.to},value:{from:typeof o.value==="function"?o.value:o.value&&o.value.from,to:o.value&&o.value.to},row:{from:typeof o.row==="function"?o.row:o.row&&o.row.from,to:o.row&&o.row.to}}}function b1(o){if(!o||typeof o!=="string")return{url:{searchParams:new Map}};let n=o;n=n.slice(n.indexOf("://")+3).split(/[?/]/)[0],n=decodeURIComponent(n.slice(n.indexOf("@")+1));let T=new URL(o.replace(n,n.split(",")[0]));return{url:{username:decodeURIComponent(T.username),password:decodeURIComponent(T.password),host:T.host,hostname:T.hostname,port:T.port,pathname:T.pathname,searchParams:T.searchParams},multihost:n.indexOf(",")>-1&&n}}function x1(){try{return B1.userInfo().username}catch(o){return process.env.USERNAME||process.env.USER||process.env.LOGNAME}}class Qo{static[y]="SelectionProxyHandler";config;constructor(o){this.config={...o}}get(o,n){if(n==="_")return{...o._,selectedFields:new Proxy(o._.selectedFields,this)};if(n===Xo)return{...o[Xo],selectedFields:new Proxy(o[Xo].selectedFields,this)};if(typeof n==="symbol")return o[n];let f=(X(o,ho)?o._.selectedFields:X(o,Sn)?o[Xo].selectedFields:o)[n];if(X(f,j.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!f.isSelectionField)return f.sql;let S=f.clone();return S.isSelectionField=!0,S}if(X(f,j)){if(this.config.sqlBehavior==="sql")return f;throw new Error(`You tried to reference "${n}" 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,Wo)){if(this.config.alias)return new Proxy(f,new iT(new Proxy(f.table,new Df(this.config.alias,this.config.replaceOriginalName??!1))));return f}if(typeof f!=="object"||f===null)return f;return new Proxy(f,new Qo(this.config))}}class cS extends on{constructor(o,n,T,f){super();this.session=n,this.dialect=T,this.config={table:o,withList:f}}static[y]="PgDelete";config;where(o){return this.config.where=o,this}returning(o=this.config.table[I.Symbol.Columns]){return this.config.returningFields=o,this.config.returning=On(o),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:o,...n}=this.dialect.sqlToQuery(this.getSQL());return n}_prepare(o){return Oo.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,o,!0)})}prepare(o){return this._prepare(o)}authToken;setToken(o){return this.authToken=o,this}execute=(o)=>{return Oo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(o,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new Qo({alias:vo(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}function v1(o){return(o.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((T)=>T.toLowerCase()).join("_")}function r1(o){return(o.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((T,f,S)=>{let A=S===0?f.toLowerCase():`${f[0].toUpperCase()}${f.slice(1)}`;return T+A},"")}function q1(o){return o}class X${static[y]="CasingCache";cache={};cachedTables={};convert;constructor(o){this.convert=o==="snake_case"?v1:o==="camelCase"?r1:q1}getColumnCasing(o){if(!o.keyAsName)return o.name;let n=o.table[I.Symbol.Schema]??"public",T=o.table[I.Symbol.OriginalName],f=`${n}.${T}.${o.name}`;if(!this.cache[f])this.cacheTable(o.table);return this.cache[f]}cacheTable(o){let n=o[I.Symbol.Schema]??"public",T=o[I.Symbol.OriginalName],f=`${n}.${T}`;if(!this.cachedTables[f]){for(let S of Object.values(o[I.Symbol.Columns])){let A=`${f}.${S.name}`;this.cache[A]=this.convert(S.name)}this.cachedTables[f]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class bf extends Sn{static[y]="PgViewBase"}class KT{static[y]="PgDialect";casing;constructor(o){this.casing=new X$(o?.casing)}async migrate(o,n,T){let f=typeof T==="string"?"__drizzle_migrations":T.migrationsTable??"__drizzle_migrations",S=typeof T==="string"?"drizzle":T.migrationsSchema??"drizzle",A=k`
|
|
37
|
+
`};return f(J),new Promise(async(W)=>$=W);async function t({highWaterMark:W=16384,start:O=0,end:_=1/0}={}){let Q=_-O;return O&&await J.seek(O),new G0.Readable({highWaterMark:W,async read(H){let m=H>Q?H-Q:H;Q-=H;let[{data:b}]=await J.read(m);if(this.push(b),b.length<H)this.push(null)}})}async function R({highWaterMark:W=16384,start:O=0}={}){return O&&await J.seek(O),new G0.Writable({highWaterMark:W,write(_,Q,H){J.write(_).then(()=>H(),H)}})}}).catch(S)})}Object.assign(pS,{PostgresError:dn,toPascal:On,pascal:R$,toCamel:Wn,camel:t$,toKebab:wn,kebab:M$,fromPascal:If,fromCamel:Cf,fromKebab:jf,BigInt:{to:20,from:[20],parse:(o)=>BigInt(o),serialize:(o)=>o.toString()}});var un=pS;function pS(o,T){let n=Ny(o,T),f=n.no_subscribe||w$(pS,{...n}),S=!1,A=MT(),$=MT(),F=MT(),J=MT(),t=MT(),R=MT(),W=MT(),O=MT(),_={connecting:$,reserved:F,closed:J,ended:t,open:R,busy:W,full:O},Q=[...Array(n.max)].map(()=>O$(n,_,{onopen:nT,onend:mo,onclose:IT})),H=m(v);return Object.assign(H,{get parameters(){return n.parameters},largeObject:_$.bind(null,H),subscribe:f,CLOSE:gn,END:gn,PostgresError:dn,options:n,reserve:P,listen:b,begin:E,close:q,end:s}),H;function m(G){return G.debug=n.debug,Object.entries(n.types).reduce((To,[wo,Vo])=>{return To[wo]=(Yo)=>new CT(Yo,Vo.to),To},p),Object.assign(Fo,{types:p,typed:p,unsafe:Go,notify:r,array:D,json:U,file:Lo}),Fo;function p(To,wo){return new CT(To,wo)}function Fo(To,...wo){return To&&Array.isArray(To.raw)?new wT(To,wo,G,K):typeof To==="string"&&!wo.length?new hf(n.transform.column.to?n.transform.column.to(To):To):new NS(To,wo)}function Go(To,wo=[],Vo={}){return arguments.length===2&&!Array.isArray(wo)&&(Vo=wo,wo=[]),new wT([To],wo,G,K,{prepare:!1,...Vo,simple:"simple"in Vo?Vo.simple:wo.length===0})}function Lo(To,wo=[],Vo={}){return arguments.length===2&&!Array.isArray(wo)&&(Vo=wo,wo=[]),new wT([],wo,(Ho)=>{hy.readFile(To,"utf8",(Zo,_o)=>{if(Zo)return Ho.reject(Zo);Ho.strings=[_o],G(Ho)})},K,{...Vo,simple:"simple"in Vo?Vo.simple:wo.length===0})}}async function b(G,p,Fo){let Go={fn:p,onlisten:Fo},Lo=b.sql||(b.sql=pS({...n,max:1,idle_timeout:null,max_lifetime:null,fetch_types:!1,onclose(){Object.entries(b.channels).forEach(([Ho,{listeners:Zo}])=>{delete b.channels[Ho],Promise.all(Zo.map((_o)=>b(Ho,_o.fn,_o.onlisten).catch(()=>{})))})},onnotify(Ho,Zo){Ho in b.channels&&b.channels[Ho].listeners.forEach((_o)=>_o.fn(Zo))}})),To=b.channels||(b.channels={});if(G in To){To[G].listeners.push(Go);let Ho=await To[G].result;return Go.onlisten&&Go.onlisten(),{state:Ho.state,unlisten:Yo}}To[G]={result:Lo`listen ${Lo.unsafe('"'+G.replace(/"/g,'""')+'"')}`,listeners:[Go]};let Vo=await To[G].result;return Go.onlisten&&Go.onlisten(),{state:Vo.state,unlisten:Yo};async function Yo(){if(G in To===!1)return;if(To[G].listeners=To[G].listeners.filter((Ho)=>Ho!==Go),To[G].listeners.length)return;return delete To[G],Lo`unlisten ${Lo.unsafe('"'+G.replace(/"/g,'""')+'"')}`}}async function r(G,p){return await H`select pg_notify(${G}, ${""+p})`}async function P(){let G=MT(),p=R.length?R.shift():await new Promise((Lo)=>{A.push({reserve:Lo}),J.length&&ko(J.shift())});z(p,F),p.reserved=()=>G.length?p.execute(G.shift()):z(p,F),p.reserved.release=!0;let Fo=m(Go);return Fo.release=()=>{p.reserved=null,nT(p)},Fo;function Go(Lo){p.queue===O?G.push(Lo):p.execute(Lo)||z(p,O)}}async function E(G,p){!p&&(p=G,G="");let Fo=MT(),Go=0,Lo,To=null;try{return await H.unsafe("begin "+G.replace(/[^a-z ]/ig,""),[],{onexecute:Vo}).execute(),await Promise.race([wo(Lo,p),new Promise((Yo,Ho)=>Lo.onclose=Ho)])}catch(Yo){throw Yo}async function wo(Yo,Ho,Zo){let _o=m(Co);_o.savepoint=cT,_o.prepare=(Ko)=>To=Ko.replace(/[^a-z0-9$-_. ]/gi);let _T,Po;Zo&&await _o`savepoint ${_o(Zo)}`;try{if(Po=await new Promise((Ko,XT)=>{let QT=Ho(_o);Promise.resolve(Array.isArray(QT)?Promise.all(QT):QT).then(Ko,XT)}),_T)throw _T}catch(Ko){throw await(Zo?_o`rollback to ${_o(Zo)}`:_o`rollback`),Ko instanceof dn&&Ko.code==="25P02"&&_T||Ko}if(!Zo)To?await _o`prepare transaction '${_o.unsafe(To)}'`:await _o`commit`;return Po;function cT(Ko,XT){if(Ko&&Array.isArray(Ko.raw))return cT((QT)=>QT.apply(QT,arguments));return arguments.length===1&&(XT=Ko,Ko=null),wo(Yo,XT,"s"+Go+++(Ko?"_"+Ko:""))}function Co(Ko){Ko.catch((XT)=>_T||(_T=XT)),Yo.queue===O?Fo.push(Ko):Yo.execute(Ko)||z(Yo,O)}}function Vo(Yo){Lo=Yo,z(Yo,F),Yo.reserved=()=>Fo.length?Yo.execute(Fo.shift()):z(Yo,F)}}function z(G,p){return G.queue.remove(G),p.push(G),G.queue=p,p===R?G.idleTimer.start():G.idleTimer.cancel(),G}function U(G){return new CT(G,3802)}function D(G,p){if(!Array.isArray(G))return D(Array.from(arguments));return new CT(G,p||(G.length?jS(G)||25:0),n.shared.typeArrayMap)}function v(G){if(S)return G.reject(Bo.connection("CONNECTION_ENDED",n,n));if(R.length)return l(R.shift(),G);if(J.length)return ko(J.shift(),G);W.length?l(W.shift(),G):A.push(G)}function l(G,p){return G.execute(p)?z(G,W):z(G,O)}function K(G){return new Promise((p,Fo)=>{G.state?G.active?O$(n).cancel(G.state,p,Fo):G.cancelled={resolve:p,reject:Fo}:(A.remove(G),G.cancelled=!0,G.reject(Bo.generic("57014","canceling statement due to user request")),p())})}async function s({timeout:G=null}={}){if(S)return S;await 1;let p;return S=Promise.race([new Promise((Fo)=>G!==null&&(p=setTimeout(a,G*1000,Fo))),Promise.all(Q.map((Fo)=>Fo.end()).concat(b.sql?b.sql.end({timeout:0}):[],f.sql?f.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(p))}async function q(){await Promise.all(Q.map((G)=>G.end()))}async function a(G){await Promise.all(Q.map((p)=>p.terminate()));while(A.length)A.shift().reject(Bo.connection("CONNECTION_DESTROYED",n));G()}function ko(G,p){return z(G,$),G.connect(p),G}function mo(G){z(G,t)}function nT(G){if(A.length===0)return z(G,R);let p=Math.ceil(A.length/($.length+1)),Fo=!0;while(Fo&&A.length&&p-- >0){let Go=A.shift();if(Go.reserve)return Go.reserve(G);Fo=G.execute(Go)}Fo?z(G,W):z(G,O)}function IT(G,p){z(G,J),G.reserved=null,G.onclose&&(G.onclose(p),G.onclose=null),n.onclose&&n.onclose(G.id),A.length&&ko(G,A.shift())}}function Ny(o,T){if(o&&o.shared)return o;let n=process.env,f=(!o||typeof o==="string"?T:o)||{},{url:S,multihost:A}=qy(o),$=[...S.searchParams].reduce((O,[_,Q])=>(O[_]=Q,O),{}),F=f.hostname||f.host||A||S.hostname||n.PGHOST||"localhost",J=f.port||S.port||n.PGPORT||5432,t=f.user||f.username||S.username||n.PGUSERNAME||n.PGUSER||py();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 R=["idle_timeout","connect_timeout","max_lifetime","max_pipeline","backoff","keep_alive"],W={max:10,ssl:!1,idle_timeout:null,connect_timeout:30,max_lifetime:vy,max_pipeline:100,backoff:xy,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((O)=>O.split(":")[0]),port:Array.isArray(J)?J:F.split(",").map((O)=>parseInt(O.split(":")[1]||J)),path:f.path||F.indexOf("/")>-1&&F+"/.s.PGSQL."+J,database:f.database||f.db||(S.pathname||"").slice(1)||n.PGDATABASE||t,user:t,pass:f.pass||f.password||S.password||n.PGPASSWORD||"",...Object.entries(W).reduce((O,[_,Q])=>{let H=_ in f?f[_]:(_ in $)?$[_]==="disable"||$[_]==="false"?!1:$[_]:n["PG"+_.toUpperCase()]||Q;return O[_]=typeof H==="string"&&R.includes(_)?+H:H,O},{}),connection:{application_name:"postgres.js",...f.connection,...Object.entries($).reduce((O,[_,Q])=>((_ in W)||(O[_]=Q),O),{})},types:f.types||{},target_session_attrs:by(f,S,n),onnotice:f.onnotice,onnotify:f.onnotify,onclose:f.onclose,onparameter:f.onparameter,socket:f.socket,transform:ry(f.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...M0(f.types)}}function by(o,T,n){let f=o.target_session_attrs||T.searchParams.get("target_session_attrs")||n.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 xy(o){return(0.5+Math.random()/2)*Math.min(3**o/100,20)}function vy(){return 60*(30+Math.random()*30)}function ry(o){return{undefined:o.undefined,column:{from:typeof o.column==="function"?o.column:o.column&&o.column.from,to:o.column&&o.column.to},value:{from:typeof o.value==="function"?o.value:o.value&&o.value.from,to:o.value&&o.value.to},row:{from:typeof o.row==="function"?o.row:o.row&&o.row.from,to:o.row&&o.row.to}}}function qy(o){if(!o||typeof o!=="string")return{url:{searchParams:new Map}};let T=o;T=T.slice(T.indexOf("://")+3).split(/[?/]/)[0],T=decodeURIComponent(T.slice(T.indexOf("@")+1));let n=new URL(o.replace(T,T.split(",")[0]));return{url:{username:decodeURIComponent(n.username),password:decodeURIComponent(n.password),host:n.host,hostname:n.hostname,port:n.port,pathname:n.pathname,searchParams:n.searchParams},multihost:T.indexOf(",")>-1&&T}}function py(){try{return jy.userInfo().username}catch(o){return process.env.USERNAME||process.env.USER||process.env.LOGNAME}}class Qo{static[y]="SelectionProxyHandler";config;constructor(o){this.config={...o}}get(o,T){if(T==="_")return{...o._,selectedFields:new Proxy(o._.selectedFields,this)};if(T===Xo)return{...o[Xo],selectedFields:new Proxy(o[Xo].selectedFields,this)};if(typeof T==="symbol")return o[T];let f=(X(o,No)?o._.selectedFields:X(o,ST)?o[Xo].selectedFields:o)[T];if(X(f,j.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!f.isSelectionField)return f.sql;let S=f.clone();return S.isSelectionField=!0,S}if(X(f,j)){if(this.config.sqlBehavior==="sql")return f;throw new Error(`You tried to reference "${T}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}if(X(f,Wo)){if(this.config.alias)return new Proxy(f,new Pn(new Proxy(f.table,new Df(this.config.alias,this.config.replaceOriginalName??!1))));return f}if(typeof f!=="object"||f===null)return f;return new Proxy(f,new Qo(this.config))}}class cS extends oT{constructor(o,T,n,f){super();this.session=T,this.dialect=n,this.config={table:o,withList:f}}static[y]="PgDelete";config;where(o){return this.config.where=o,this}returning(o=this.config.table[I.Symbol.Columns]){return this.config.returningFields=o,this.config.returning=OT(o),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:o,...T}=this.dialect.sqlToQuery(this.getSQL());return T}_prepare(o){return Oo.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,o,!0)})}prepare(o){return this._prepare(o)}authToken;setToken(o){return this.authToken=o,this}execute=(o)=>{return Oo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(o,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new Qo({alias:vo(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}function cy(o){return(o.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((n)=>n.toLowerCase()).join("_")}function Zy(o){return(o.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((n,f,S)=>{let A=S===0?f.toLowerCase():`${f[0].toUpperCase()}${f.slice(1)}`;return n+A},"")}function Py(o){return o}class X${static[y]="CasingCache";cache={};cachedTables={};convert;constructor(o){this.convert=o==="snake_case"?cy:o==="camelCase"?Zy:Py}getColumnCasing(o){if(!o.keyAsName)return o.name;let T=o.table[I.Symbol.Schema]??"public",n=o.table[I.Symbol.OriginalName],f=`${T}.${n}.${o.name}`;if(!this.cache[f])this.cacheTable(o.table);return this.cache[f]}cacheTable(o){let T=o[I.Symbol.Schema]??"public",n=o[I.Symbol.OriginalName],f=`${T}.${n}`;if(!this.cachedTables[f]){for(let S of Object.values(o[I.Symbol.Columns])){let A=`${f}.${S.name}`;this.cache[A]=this.convert(S.name)}this.cachedTables[f]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class bf extends ST{static[y]="PgViewBase"}class Xn{static[y]="PgDialect";casing;constructor(o){this.casing=new X$(o?.casing)}async migrate(o,T,n){let f=typeof n==="string"?"__drizzle_migrations":n.migrationsTable??"__drizzle_migrations",S=typeof n==="string"?"drizzle":n.migrationsSchema??"drizzle",A=k`
|
|
38
38
|
CREATE TABLE IF NOT EXISTS ${k.identifier(S)}.${k.identifier(f)} (
|
|
39
39
|
id SERIAL PRIMARY KEY,
|
|
40
40
|
hash text NOT NULL,
|
|
41
41
|
created_at bigint
|
|
42
42
|
)
|
|
43
|
-
`;await n.execute(k`CREATE SCHEMA IF NOT EXISTS ${k.identifier(S)}`),await n.execute(A);let F=(await n.all(k`select id, hash, created_at from ${k.identifier(S)}.${k.identifier(f)} order by created_at desc limit 1`))[0];await n.transaction(async(J)=>{for await(let t of o)if(!F||Number(F.created_at)<t.folderMillis){for(let R of t.sql)await J.execute(k.raw(R));await J.execute(k`insert into ${k.identifier(S)}.${k.identifier(f)} ("hash", "created_at") values(${t.hash}, ${t.folderMillis})`)}})}escapeName(o){return`"${o}"`}escapeParam(o){return`$${o+1}`}escapeString(o){return`'${o.replace(/'/g,"''")}'`}buildWithCTE(o){if(!o?.length)return;let n=[k`with `];for(let[T,f]of o.entries())if(n.push(k`${k.identifier(f._.alias)} as (${f._.sql})`),T<o.length-1)n.push(k`, `);return n.push(k` `),k.join(n)}buildDeleteQuery({table:o,where:n,returning:T,withList:f}){let S=this.buildWithCTE(f),A=T?k` returning ${this.buildSelection(T,{isSingleTable:!0})}`:void 0,$=n?k` where ${n}`:void 0;return k`${S}delete from ${o}${$}${A}`}buildUpdateSet(o,n){let T=o[I.Symbol.Columns],f=Object.keys(T).filter((A)=>n[A]!==void 0||T[A]?.onUpdateFn!==void 0),S=f.length;return k.join(f.flatMap((A,$)=>{let F=T[A],J=n[A]??k.param(F.onUpdateFn(),F),t=k`${k.identifier(this.casing.getColumnCasing(F))} = ${J}`;if($<S-1)return[t,k.raw(", ")];return[t]}))}buildUpdateQuery({table:o,set:n,where:T,returning:f,withList:S,from:A,joins:$}){let F=this.buildWithCTE(S),J=o[co.Symbol.Name],t=o[co.Symbol.Schema],R=o[co.Symbol.OriginalName],W=J===R?void 0:J,O=k`${t?k`${k.identifier(t)}.`:void 0}${k.identifier(R)}${W&&k` ${k.identifier(W)}`}`,_=this.buildUpdateSet(o,n),Q=A&&k.join([k.raw(" from "),this.buildFromTable(A)]),K=this.buildJoins($),B=f?k` returning ${this.buildSelection(f,{isSingleTable:!A})}`:void 0,h=T?k` where ${T}`:void 0;return k`${F}update ${O} set ${_}${Q}${K}${h}${B}`}buildSelection(o,{isSingleTable:n=!1}={}){let T=o.length,f=o.flatMap(({field:S},A)=>{let $=[];if(X(S,j.Aliased)&&S.isSelectionField)$.push(k.identifier(S.fieldAlias));else if(X(S,j.Aliased)||X(S,j)){let F=X(S,j.Aliased)?S.sql:S;if(n)$.push(new j(F.queryChunks.map((J)=>{if(X(J,V))return k.identifier(this.casing.getColumnCasing(J));return J})));else $.push(F);if(X(S,j.Aliased))$.push(k` as ${k.identifier(S.fieldAlias)}`)}else if(X(S,Wo))if(n)$.push(k.identifier(this.casing.getColumnCasing(S)));else $.push(S);if(A<T-1)$.push(k`, `);return $});return k.join(f)}buildJoins(o){if(!o||o.length===0)return;let n=[];for(let[T,f]of o.entries()){if(T===0)n.push(k` `);let S=f.table,A=f.lateral?k` lateral`:void 0;if(X(S,co)){let $=S[co.Symbol.Name],F=S[co.Symbol.Schema],J=S[co.Symbol.OriginalName],t=$===J?void 0:f.alias;n.push(k`${k.raw(f.joinType)} join${A} ${F?k`${k.identifier(F)}.`:void 0}${k.identifier(J)}${t&&k` ${k.identifier(t)}`} on ${f.on}`)}else if(X(S,Sn)){let $=S[Xo].name,F=S[Xo].schema,J=S[Xo].originalName,t=$===J?void 0:f.alias;n.push(k`${k.raw(f.joinType)} join${A} ${F?k`${k.identifier(F)}.`:void 0}${k.identifier(J)}${t&&k` ${k.identifier(t)}`} on ${f.on}`)}else n.push(k`${k.raw(f.joinType)} join${A} ${S} on ${f.on}`);if(T<o.length-1)n.push(k` `)}return k.join(n)}buildFromTable(o){if(X(o,I)&&o[I.Symbol.OriginalName]!==o[I.Symbol.Name]){let n=k`${k.identifier(o[I.Symbol.OriginalName])}`;if(o[I.Symbol.Schema])n=k`${k.identifier(o[I.Symbol.Schema])}.${n}`;return k`${n} ${k.identifier(o[I.Symbol.Name])}`}return o}buildSelectQuery({withList:o,fields:n,fieldsFlat:T,where:f,having:S,table:A,joins:$,orderBy:F,groupBy:J,limit:t,offset:R,lockingClause:W,distinct:O,setOperators:_}){let Q=T??On(n);for(let a of Q)if(X(a.field,Wo)&&vo(a.field.table)!==(X(A,ho)?A._.alias:X(A,bf)?A[Xo].name:X(A,j)?void 0:vo(A))&&!((ko)=>$?.some(({alias:Bo})=>Bo===(ko[I.Symbol.IsAlias]?vo(ko):ko[I.Symbol.BaseName])))(a.field.table)){let ko=vo(a.field.table);throw new Error(`Your "${a.path.join("->")}" field references a column "${ko}"."${a.field.name}", but the table "${ko}" is not part of the query! Did you forget to join it?`)}let K=!$||$.length===0,B=this.buildWithCTE(o),h;if(O)h=O===!0?k` distinct`:k` distinct on (${k.join(O.on,k`, `)})`;let r=this.buildSelection(Q,{isSingleTable:K}),P=this.buildFromTable(A),E=this.buildJoins($),z=f?k` where ${f}`:void 0,U=S?k` having ${S}`:void 0,D;if(F&&F.length>0)D=k` order by ${k.join(F,k`, `)}`;let v;if(J&&J.length>0)v=k` group by ${k.join(J,k`, `)}`;let l=typeof t==="object"||typeof t==="number"&&t>=0?k` limit ${t}`:void 0,H=R?k` offset ${R}`:void 0,s=k.empty();if(W){let a=k` for ${k.raw(W.strength)}`;if(W.config.of)a.append(k` of ${k.join(Array.isArray(W.config.of)?W.config.of:[W.config.of],k`, `)}`);if(W.config.noWait)a.append(k` no wait`);else if(W.config.skipLocked)a.append(k` skip locked`);s.append(a)}let q=k`${B}select${h} ${r} from ${P}${E}${z}${v}${U}${D}${l}${H}${s}`;if(_.length>0)return this.buildSetOperations(q,_);return q}buildSetOperations(o,n){let[T,...f]=n;if(!T)throw new Error("Cannot pass undefined values to any set operator");if(f.length===0)return this.buildSetOperationQuery({leftSelect:o,setOperator:T});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:o,setOperator:T}),f)}buildSetOperationQuery({leftSelect:o,setOperator:{type:n,isAll:T,rightSelect:f,limit:S,orderBy:A,offset:$}}){let F=k`(${o.getSQL()}) `,J=k`(${f.getSQL()})`,t;if(A&&A.length>0){let _=[];for(let Q of A)if(X(Q,V))_.push(k.identifier(Q.name));else if(X(Q,j)){for(let K=0;K<Q.queryChunks.length;K++){let B=Q.queryChunks[K];if(X(B,V))Q.queryChunks[K]=k.identifier(B.name)}_.push(k`${Q}`)}else _.push(k`${Q}`);t=k` order by ${k.join(_,k`, `)} `}let R=typeof S==="object"||typeof S==="number"&&S>=0?k` limit ${S}`:void 0,W=k.raw(`${n} ${T?"all ":""}`),O=$?k` offset ${$}`:void 0;return k`${F}${W}${J}${t}${R}${O}`}buildInsertQuery({table:o,values:n,onConflict:T,returning:f,withList:S,select:A,overridingSystemValue_:$}){let F=[],J=o[I.Symbol.Columns],t=Object.entries(J).filter(([B,h])=>!h.shouldDisableInsert()),R=t.map(([,B])=>k.identifier(this.casing.getColumnCasing(B)));if(A){let B=n;if(X(B,j))F.push(B);else F.push(B.getSQL())}else{let B=n;F.push(k.raw("values "));for(let[h,r]of B.entries()){let P=[];for(let[E,z]of t){let U=r[E];if(U===void 0||X(U,tn)&&U.value===void 0)if(z.defaultFn!==void 0){let D=z.defaultFn(),v=X(D,j)?D:k.param(D,z);P.push(v)}else if(!z.default&&z.onUpdateFn!==void 0){let D=z.onUpdateFn(),v=X(D,j)?D:k.param(D,z);P.push(v)}else P.push(k`default`);else P.push(U)}if(F.push(P),h<B.length-1)F.push(k`, `)}}let W=this.buildWithCTE(S),O=k.join(F),_=f?k` returning ${this.buildSelection(f,{isSingleTable:!0})}`:void 0,Q=T?k` on conflict ${T}`:void 0,K=$===!0?k`overriding system value `:void 0;return k`${W}insert into ${o} ${R} ${K}${O}${Q}${_}`}buildRefreshMaterializedViewQuery({view:o,concurrently:n,withNoData:T}){let f=n?k` concurrently`:void 0,S=T?k` with no data`:void 0;return k`refresh materialized view${f} ${o}${S}`}prepareTyping(o){if(X(o,DS)||X(o,zS))return"json";else if(X(o,QS))return"decimal";else if(X(o,US))return"time";else if(X(o,VS)||X(o,mS))return"timestamp";else if(X(o,ES)||X(o,GS))return"date";else if(X(o,BS))return"uuid";else return"none"}sqlToQuery(o,n){return o.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,prepareTyping:this.prepareTyping,invokeSource:n})}buildRelationalQueryWithoutPK({fullSchema:o,schema:n,tableNamesMap:T,table:f,tableConfig:S,queryConfig:A,tableAlias:$,nestedQueryRelation:F,joinOn:J}){let t=[],R,W,O=[],_,Q=[];if(A===!0)t=Object.entries(S.columns).map(([h,r])=>({dbKey:r.name,tsKey:h,field:Ln(r,$),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let B=Object.fromEntries(Object.entries(S.columns).map(([U,D])=>[U,Ln(D,$)]));if(A.where){let U=typeof A.where==="function"?A.where(B,dR()):A.where;_=U&&Qf(U,$)}let h=[],r=[];if(A.columns){let U=!1;for(let[D,v]of Object.entries(A.columns)){if(v===void 0)continue;if(D in S.columns){if(!U&&v===!0)U=!0;r.push(D)}}if(r.length>0)r=U?r.filter((D)=>A.columns?.[D]===!0):Object.keys(S.columns).filter((D)=>!r.includes(D))}else r=Object.keys(S.columns);for(let U of r){let D=S.columns[U];h.push({tsKey:U,value:D})}let P=[];if(A.with)P=Object.entries(A.with).filter((U)=>!!U[1]).map(([U,D])=>({tsKey:U,queryConfig:D,relation:S.relations[U]}));let E;if(A.extras){E=typeof A.extras==="function"?A.extras(B,{sql:k}):A.extras;for(let[U,D]of Object.entries(E))h.push({tsKey:U,value:gA(D,$)})}for(let{tsKey:U,value:D}of h)t.push({dbKey:X(D,j.Aliased)?D.fieldAlias:S.columns[U].name,tsKey:U,field:X(D,Wo)?Ln(D,$):D,relationTableTsKey:void 0,isJson:!1,selection:[]});let z=typeof A.orderBy==="function"?A.orderBy(B,lR()):A.orderBy??[];if(!Array.isArray(z))z=[z];O=z.map((U)=>{if(X(U,Wo))return Ln(U,$);return Qf(U,$)}),R=A.limit,W=A.offset;for(let{tsKey:U,queryConfig:D,relation:v}of P){let l=eR(n,T,v),H=WT(v.referencedTable),s=T[H],q=`${$}_${U}`,a=Uf(...l.fields.map((Tn,In)=>KS(Ln(l.references[In],q),Ln(Tn,$)))),ko=this.buildRelationalQueryWithoutPK({fullSchema:o,schema:n,tableNamesMap:T,table:o[s],tableConfig:n[s],queryConfig:X(v,nT)?D===!0?{limit:1}:{...D,limit:1}:D,tableAlias:q,joinOn:a,nestedQueryRelation:v}),Bo=k`${k.identifier(q)}.${k.identifier("data")}`.as(U);Q.push({on:k`true`,table:new ho(ko.sql,{},q),alias:q,joinType:"left",lateral:!0}),t.push({dbKey:U,tsKey:U,field:Bo,relationTableTsKey:s,isJson:!0,selection:ko.selection})}}if(t.length===0)throw new XS({message:`No fields selected for table "${S.tsName}" ("${$}")`});let K;if(_=Uf(J,_),F){let B=k`json_build_array(${k.join(t.map(({field:P,tsKey:E,isJson:z})=>z?k`${k.identifier(`${$}_${E}`)}.${k.identifier("data")}`:X(P,j.Aliased)?P.sql:P),k`, `)})`;if(X(F,Lf))B=k`coalesce(json_agg(${B}${O.length>0?k` order by ${k.join(O,k`, `)}`:void 0}), '[]'::json)`;let h=[{dbKey:"data",tsKey:"data",field:B.as("data"),isJson:!0,relationTableTsKey:S.tsName,selection:t}];if(R!==void 0||W!==void 0||O.length>0)K=this.buildSelectQuery({table:_S(f,$),fields:{},fieldsFlat:[{path:[],field:k.raw("*")}],where:_,limit:R,offset:W,orderBy:O,setOperators:[]}),_=void 0,R=void 0,W=void 0,O=[];else K=_S(f,$);K=this.buildSelectQuery({table:X(K,co)?K:new ho(K,{},$),fields:{},fieldsFlat:h.map(({field:P})=>({path:[],field:X(P,Wo)?Ln(P,$):P})),joins:Q,where:_,limit:R,offset:W,orderBy:O,setOperators:[]})}else K=this.buildSelectQuery({table:_S(f,$),fields:{},fieldsFlat:t.map(({field:B})=>({path:[],field:X(B,Wo)?Ln(B,$):B})),joins:Q,where:_,limit:R,offset:W,orderBy:O,setOperators:[]});return{tableTsKey:S.tsName,sql:K,selection:t}}}class K${static[y]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class nn{static[y]="PgSelectBuilder";fields;session;dialect;withList=[];distinct;constructor(o){if(this.fields=o.fields,this.session=o.session,this.dialect=o.dialect,o.withList)this.withList=o.withList;this.distinct=o.distinct}authToken;setToken(o){return this.authToken=o,this}from(o){let n=!!this.fields,T=o,f;if(this.fields)f=this.fields;else if(X(T,ho))f=Object.fromEntries(Object.keys(T._.selectedFields).map((S)=>[S,T[S]]));else if(X(T,bf))f=T[Xo].selectedFields;else if(X(T,j))f={};else f=sJ(T);return new H$({table:T,fields:f,isPartialSelect:n,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}}class K0 extends K${static[y]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;constructor({table:o,fields:n,isPartialSelect:T,session:f,dialect:S,withList:A,distinct:$}){super();this.config={withList:A,table:o,fields:{...n},distinct:$,setOperators:[]},this.isPartialSelect=T,this.session=f,this.dialect=S,this._={selectedFields:n},this.tableName=qn(o),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}createJoin(o){return(n,T)=>{let f=this.tableName,S=qn(n);if(typeof S==="string"&&this.config.joins?.some((A)=>A.alias===S))throw new Error(`Alias "${S}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof f==="string")this.config.fields={[f]:this.config.fields};if(typeof S==="string"&&!X(n,j)){let A=X(n,ho)?n._.selectedFields:X(n,Sn)?n[Xo].selectedFields:n[I.Symbol.Columns];this.config.fields[S]=A}}if(typeof T==="function")T=T(new Proxy(this.config.fields,new Qo({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:T,table:n,joinType:o,alias:S}),typeof S==="string")switch(o){case"left":{this.joinsNotNullableMap[S]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([A])=>[A,!1])),this.joinsNotNullableMap[S]=!0;break}case"inner":{this.joinsNotNullableMap[S]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([A])=>[A,!1])),this.joinsNotNullableMap[S]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");createSetOperator(o,n){return(T)=>{let f=typeof T==="function"?T(p1()):T;if(!Vf(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:o,isAll:n,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(o){return this.config.setOperators.push(...o),this}where(o){if(typeof o==="function")o=o(new Proxy(this.config.fields,new Qo({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=o,this}having(o){if(typeof o==="function")o=o(new Proxy(this.config.fields,new Qo({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=o,this}groupBy(...o){if(typeof o[0]==="function"){let n=o[0](new Proxy(this.config.fields,new Qo({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(n)?n:[n]}else this.config.groupBy=o;return this}orderBy(...o){if(typeof o[0]==="function"){let n=o[0](new Proxy(this.config.fields,new Qo({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),T=Array.isArray(n)?n:[n];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=T;else this.config.orderBy=T}else{let n=o;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=n;else this.config.orderBy=n}return this}limit(o){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=o;else this.config.limit=o;return this}offset(o){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=o;else this.config.offset=o;return this}for(o,n={}){return this.config.lockingClause={strength:o,config:n},this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:o,...n}=this.dialect.sqlToQuery(this.getSQL());return n}as(o){return new Proxy(new ho(this.getSQL(),this.config.fields,o),new Qo({alias:o,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new Qo({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}}class H$ extends K0{static[y]="PgSelect";_prepare(o){let{session:n,config:T,dialect:f,joinsNotNullableMap:S,authToken:A}=this;if(!n)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");return Oo.startActiveSpan("drizzle.prepareQuery",()=>{let $=On(T.fields),F=n.prepareQuery(f.sqlToQuery(this.getSQL()),$,o,!0);return F.joinsNotNullableMap=S,F.setToken(A)})}prepare(o){return this._prepare(o)}authToken;setToken(o){return this.authToken=o,this}execute=(o)=>{return Oo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(o,this.authToken)})}}eJ(H$,[on]);function eT(o,n){return(T,f,...S)=>{let A=[f,...S].map(($)=>({type:o,isAll:n,rightSelect:$}));for(let $ of A)if(!Vf(T.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 T.addSetOperators(A)}}var p1=()=>({union:c1,unionAll:Z1,intersect:P1,intersectAll:i1,except:g1,exceptAll:d1}),c1=eT("union",!1),Z1=eT("union",!0),P1=eT("intersect",!1),i1=eT("intersect",!0),g1=eT("except",!1),d1=eT("except",!0);class xf{static[y]="PgQueryBuilder";dialect;dialectConfig;constructor(o){this.dialect=X(o,KT)?o:void 0,this.dialectConfig=X(o,KT)?void 0:o}$with=(o,n)=>{let T=this;return{as:(S)=>{if(typeof S==="function")S=S(T);return new Proxy(new Yf(S.getSQL(),n??("getSelectedFields"in S?S.getSelectedFields()??{}:{}),o,!0),new Qo({alias:o,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...o){let n=this;function T(A){return new nn({fields:A??void 0,session:void 0,dialect:n.getDialect(),withList:o})}function f(A){return new nn({fields:A??void 0,session:void 0,dialect:n.getDialect(),distinct:!0})}function S(A,$){return new nn({fields:$??void 0,session:void 0,dialect:n.getDialect(),distinct:{on:A}})}return{select:T,selectDistinct:f,selectDistinctOn:S}}select(o){return new nn({fields:o??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(o){return new nn({fields:o??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(o,n){return new nn({fields:n??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:o}})}getDialect(){if(!this.dialect)this.dialect=new KT(this.dialectConfig);return this.dialect}}class ZS{constructor(o,n,T,f,S){this.table=o,this.session=n,this.dialect=T,this.withList=f,this.overridingSystemValue_=S}static[y]="PgInsertBuilder";authToken;setToken(o){return this.authToken=o,this}overridingSystemValue(){return this.overridingSystemValue_=!0,this}values(o){if(o=Array.isArray(o)?o:[o],o.length===0)throw new Error("values() must be called with at least one value");let n=o.map((T)=>{let f={},S=this.table[I.Symbol.Columns];for(let A of Object.keys(T)){let $=T[A];f[A]=X($,j)?$:new tn($,S[A])}return f});return new E$(this.table,n,this.session,this.dialect,this.withList,!1,this.overridingSystemValue_).setToken(this.authToken)}select(o){let n=typeof o==="function"?o(new xf):o;if(!X(n,j)&&!Vf(this.table[OS],n._.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 E$(this.table,n,this.session,this.dialect,this.withList,!0)}}class E$ extends on{constructor(o,n,T,f,S,A,$){super();this.session=T,this.dialect=f,this.config={table:o,values:n,withList:S,select:A,overridingSystemValue_:$}}static[y]="PgInsert";config;returning(o=this.config.table[I.Symbol.Columns]){return this.config.returningFields=o,this.config.returning=On(o),this}onConflictDoNothing(o={}){if(o.target===void 0)this.config.onConflict=k`do nothing`;else{let n="";n=Array.isArray(o.target)?o.target.map((f)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(f))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(o.target));let T=o.where?k` where ${o.where}`:void 0;this.config.onConflict=k`(${k.raw(n)})${T} do nothing`}return this}onConflictDoUpdate(o){if(o.where&&(o.targetWhere||o.setWhere))throw new Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');let n=o.where?k` where ${o.where}`:void 0,T=o.targetWhere?k` where ${o.targetWhere}`:void 0,f=o.setWhere?k` where ${o.setWhere}`:void 0,S=this.dialect.buildUpdateSet(this.config.table,HS(this.config.table,o.set)),A="";return A=Array.isArray(o.target)?o.target.map(($)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing($))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(o.target)),this.config.onConflict=k`(${k.raw(A)})${T} do update set ${S}${n}${f}`,this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:o,...n}=this.dialect.sqlToQuery(this.getSQL());return n}_prepare(o){return Oo.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,o,!0)})}prepare(o){return this._prepare(o)}authToken;setToken(o){return this.authToken=o,this}execute=(o)=>{return Oo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(o,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new Qo({alias:vo(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class G$ extends on{constructor(o,n,T){super();this.session=n,this.dialect=T,this.config={view:o}}static[y]="PgRefreshMaterializedView";config;concurrently(){if(this.config.withNoData!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.concurrently=!0,this}withNoData(){if(this.config.concurrently!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.withNoData=!0,this}getSQL(){return this.dialect.buildRefreshMaterializedViewQuery(this.config)}toSQL(){let{typings:o,...n}=this.dialect.sqlToQuery(this.getSQL());return n}_prepare(o){return Oo.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),void 0,o,!0)})}prepare(o){return this._prepare(o)}authToken;setToken(o){return this.authToken=o,this}execute=(o)=>{return Oo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(o,this.authToken)})}}class PS{constructor(o,n,T,f){this.table=o,this.session=n,this.dialect=T,this.withList=f}static[y]="PgUpdateBuilder";authToken;setToken(o){return this.authToken=o,this}set(o){return new H0(this.table,HS(this.table,o),this.session,this.dialect,this.withList).setToken(this.authToken)}}class H0 extends on{constructor(o,n,T,f,S){super();this.session=T,this.dialect=f,this.config={set:n,table:o,withList:S,joins:[]},this.tableName=qn(o),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}static[y]="PgUpdate";config;tableName;joinsNotNullableMap;from(o){let n=o,T=qn(n);if(typeof T==="string")this.joinsNotNullableMap[T]=!0;return this.config.from=n,this}getTableLikeFields(o){if(X(o,co))return o[I.Symbol.Columns];else if(X(o,ho))return o._.selectedFields;return o[Xo].selectedFields}createJoin(o){return(n,T)=>{let f=qn(n);if(typeof f==="string"&&this.config.joins.some((S)=>S.alias===f))throw new Error(`Alias "${f}" is already used in this query`);if(typeof T==="function"){let S=this.config.from&&!X(this.config.from,j)?this.getTableLikeFields(this.config.from):void 0;T=T(new Proxy(this.config.table[I.Symbol.Columns],new Qo({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),S&&new Proxy(S,new Qo({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}if(this.config.joins.push({on:T,table:n,joinType:o,alias:f}),typeof f==="string")switch(o){case"left":{this.joinsNotNullableMap[f]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([S])=>[S,!1])),this.joinsNotNullableMap[f]=!0;break}case"inner":{this.joinsNotNullableMap[f]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([S])=>[S,!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(o){return this.config.where=o,this}returning(o){if(!o){if(o=Object.assign({},this.config.table[I.Symbol.Columns]),this.config.from){let n=qn(this.config.from);if(typeof n==="string"&&this.config.from&&!X(this.config.from,j)){let T=this.getTableLikeFields(this.config.from);o[n]=T}for(let T of this.config.joins){let f=qn(T.table);if(typeof f==="string"&&!X(T.table,j)){let S=this.getTableLikeFields(T.table);o[f]=S}}}}return this.config.returningFields=o,this.config.returning=On(o),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:o,...n}=this.dialect.sqlToQuery(this.getSQL());return n}_prepare(o){let n=this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,o,!0);return n.joinsNotNullableMap=this.joinsNotNullableMap,n}prepare(o){return this._prepare(o)}authToken;setToken(o){return this.authToken=o,this}execute=(o)=>{return this._prepare().execute(o,this.authToken)};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new Qo({alias:vo(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class vf extends j{constructor(o){super(vf.buildEmbeddedCount(o.source,o.filters).queryChunks);this.params=o,this.mapWith(Number),this.session=o.session,this.sql=vf.buildCount(o.source,o.filters)}sql;token;static[y]="PgCountBuilder";[Symbol.toStringTag]="PgCountBuilder";session;static buildEmbeddedCount(o,n){return k`(select count(*) from ${o}${k.raw(" where ").if(n)}${n})`}static buildCount(o,n){return k`select count(*) as count from ${o}${k.raw(" where ").if(n)}${n};`}setToken(o){return this.token=o,this}then(o,n){return Promise.resolve(this.session.count(this.sql,this.token)).then(o,n)}catch(o){return this.then(void 0,o)}finally(o){return this.then((n)=>{return o?.(),n},(n)=>{throw o?.(),n})}}class z${constructor(o,n,T,f,S,A,$){this.fullSchema=o,this.schema=n,this.tableNamesMap=T,this.table=f,this.tableConfig=S,this.dialect=A,this.session=$}static[y]="PgRelationalQueryBuilder";findMany(o){return new Y$(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,o?o:{},"many")}findFirst(o){return new Y$(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,o?{...o,limit:1}:{limit:1},"first")}}class Y$ extends on{constructor(o,n,T,f,S,A,$,F,J){super();this.fullSchema=o,this.schema=n,this.tableNamesMap=T,this.table=f,this.tableConfig=S,this.dialect=A,this.session=$,this.config=F,this.mode=J}static[y]="PgRelationalQuery";_prepare(o){return Oo.startActiveSpan("drizzle.prepareQuery",()=>{let{query:n,builtQuery:T}=this._toSQL();return this.session.prepareQuery(T,void 0,o,!0,(f,S)=>{let A=f.map(($)=>LS(this.schema,this.tableConfig,$,n.selection,S));if(this.mode==="first")return A[0];return A})})}prepare(o){return this._prepare(o)}_getQuery(){return this.dialect.buildRelationalQueryWithoutPK({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName})}getSQL(){return this._getQuery().sql}_toSQL(){let o=this._getQuery(),n=this.dialect.sqlToQuery(o.sql);return{query:o,builtQuery:n}}toSQL(){return this._toSQL().builtQuery}authToken;setToken(o){return this.authToken=o,this}execute(){return Oo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(void 0,this.authToken)})}}class D$ extends on{constructor(o,n,T,f){super();this.execute=o,this.sql=n,this.query=T,this.mapBatchResult=f}static[y]="PgRaw";getSQL(){return this.sql}getQuery(){return this.query}mapResult(o,n){return n?this.mapBatchResult(o):o}_prepare(){return this}isResponseInArrayMode(){return!1}}class rf{constructor(o,n,T){if(this.dialect=o,this.session=n,this._=T?{schema:T.schema,fullSchema:T.fullSchema,tableNamesMap:T.tableNamesMap,session:n}:{schema:void 0,fullSchema:{},tableNamesMap:{},session:n},this.query={},this._.schema)for(let[f,S]of Object.entries(this._.schema))this.query[f]=new z$(T.fullSchema,this._.schema,this._.tableNamesMap,T.fullSchema[f],S,o,n)}static[y]="PgDatabase";query;$with=(o,n)=>{let T=this;return{as:(S)=>{if(typeof S==="function")S=S(new xf(T.dialect));return new Proxy(new Yf(S.getSQL(),n??("getSelectedFields"in S?S.getSelectedFields()??{}:{}),o,!0),new Qo({alias:o,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(o,n){return new vf({source:o,filters:n,session:this.session})}with(...o){let n=this;function T(J){return new nn({fields:J??void 0,session:n.session,dialect:n.dialect,withList:o})}function f(J){return new nn({fields:J??void 0,session:n.session,dialect:n.dialect,withList:o,distinct:!0})}function S(J,t){return new nn({fields:t??void 0,session:n.session,dialect:n.dialect,withList:o,distinct:{on:J}})}function A(J){return new PS(J,n.session,n.dialect,o)}function $(J){return new ZS(J,n.session,n.dialect,o)}function F(J){return new cS(J,n.session,n.dialect,o)}return{select:T,selectDistinct:f,selectDistinctOn:S,update:A,insert:$,delete:F}}select(o){return new nn({fields:o??void 0,session:this.session,dialect:this.dialect})}selectDistinct(o){return new nn({fields:o??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(o,n){return new nn({fields:n??void 0,session:this.session,dialect:this.dialect,distinct:{on:o}})}update(o){return new PS(o,this.session,this.dialect)}insert(o){return new ZS(o,this.session,this.dialect)}delete(o){return new cS(o,this.session,this.dialect)}refreshMaterializedView(o){return new G$(o,this.session,this.dialect)}authToken;execute(o){let n=typeof o==="string"?k.raw(o):o.getSQL(),T=this.dialect.sqlToQuery(n),f=this.session.prepareQuery(T,void 0,void 0,!1);return new D$(()=>f.execute(void 0,this.authToken),n,T,(S)=>f.mapResult(S,!0))}transaction(o,n){return this.session.transaction(o,n)}}class E0{constructor(o,n){this.unique=o,this.name=n}static[y]="PgIndexBuilderOn";on(...o){return new iS(o.map((n)=>{if(X(n,j))return n;n=n;let T=new Gf(n.name,!!n.keyAsName,n.columnType,n.indexConfig);return n.indexConfig=JSON.parse(JSON.stringify(n.defaultConfig)),T}),this.unique,!1,this.name)}onOnly(...o){return new iS(o.map((n)=>{if(X(n,j))return n;n=n;let T=new Gf(n.name,!!n.keyAsName,n.columnType,n.indexConfig);return n.indexConfig=n.defaultConfig,T}),this.unique,!0,this.name)}using(o,...n){return new iS(n.map((T)=>{if(X(T,j))return T;T=T;let f=new Gf(T.name,!!T.keyAsName,T.columnType,T.indexConfig);return T.indexConfig=JSON.parse(JSON.stringify(T.defaultConfig)),f}),this.unique,!0,this.name,o)}}class iS{static[y]="PgIndexBuilder";config;constructor(o,n,T,f,S="btree"){this.config={name:f,columns:o,unique:n,only:T,method:S}}concurrently(){return this.config.concurrently=!0,this}with(o){return this.config.with=o,this}where(o){return this.config.where=o,this}build(o){return new G0(this.config,o)}}class G0{static[y]="PgIndex";config;constructor(o,n){this.config={...o,table:n}}}function Q$(o){return new E0(!0,o)}class U${constructor(o){this.query=o}authToken;getQuery(){return this.query}mapResult(o,n){return o}setToken(o){return this.authToken=o,this}static[y]="PgPreparedQuery";joinsNotNullableMap}class V${constructor(o){this.dialect=o}static[y]="PgSession";execute(o,n){return Oo.startActiveSpan("drizzle.operation",()=>{return Oo.startActiveSpan("drizzle.prepareQuery",()=>{return this.prepareQuery(this.dialect.sqlToQuery(o),void 0,void 0,!1)}).setToken(n).execute(void 0,n)})}all(o){return this.prepareQuery(this.dialect.sqlToQuery(o),void 0,void 0,!1).all()}async count(o,n){let T=await this.execute(o,n);return Number(T[0].count)}}class m$ extends rf{constructor(o,n,T,f=0){super(o,n,T);this.schema=T,this.nestedIndex=f}static[y]="PgTransaction";rollback(){throw new dA}getTransactionConfigSQL(o){let n=[];if(o.isolationLevel)n.push(`isolation level ${o.isolationLevel}`);if(o.accessMode)n.push(o.accessMode);if(typeof o.deferrable==="boolean")n.push(o.deferrable?"deferrable":"not deferrable");return k.raw(n.join(" "))}setTransaction(o){return this.session.execute(k`set transaction ${this.getTransactionConfigSQL(o)}`)}}class Y0 extends U${constructor(o,n,T,f,S,A,$){super({sql:n,params:T});this.client=o,this.queryString=n,this.params=T,this.logger=f,this.fields=S,this._isResponseInArrayMode=A,this.customResultMapper=$}static[y]="PostgresJsPreparedQuery";async execute(o={}){return Oo.startActiveSpan("drizzle.execute",async(n)=>{let T=iA(this.params,o);n?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(T)}),this.logger.logQuery(this.queryString,T);let{fields:f,queryString:S,client:A,joinsNotNullableMap:$,customResultMapper:F}=this;if(!f&&!F)return Oo.startActiveSpan("drizzle.driver.execute",()=>{return A.unsafe(S,T)});let J=await Oo.startActiveSpan("drizzle.driver.execute",()=>{return n?.setAttributes({"drizzle.query.text":S,"drizzle.query.params":JSON.stringify(T)}),A.unsafe(S,T).values()});return Oo.startActiveSpan("drizzle.mapResponse",()=>{return F?F(J):J.map((t)=>uJ(f,t,$))})})}all(o={}){return Oo.startActiveSpan("drizzle.execute",async(n)=>{let T=iA(this.params,o);return n?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(T)}),this.logger.logQuery(this.queryString,T),Oo.startActiveSpan("drizzle.driver.execute",()=>{return n?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(T)}),this.client.unsafe(this.queryString,T)})})}isResponseInArrayMode(){return this._isResponseInArrayMode}}class qf extends V${constructor(o,n,T,f={}){super(n);this.client=o,this.schema=T,this.options=f,this.logger=f.logger??new uA}static[y]="PostgresJsSession";logger;prepareQuery(o,n,T,f,S){return new Y0(this.client,o.sql,o.params,this.logger,n,f,S)}query(o,n){return this.logger.logQuery(o,n),this.client.unsafe(o,n).values()}queryObjects(o,n){return this.client.unsafe(o,n)}transaction(o,n){return this.client.begin(async(T)=>{let f=new qf(T,this.dialect,this.schema,this.options),S=new B$(this.dialect,f,this.schema);if(n)await S.setTransaction(n);return o(S)})}}class B$ extends m${constructor(o,n,T,f=0){super(o,n,T,f);this.session=n}static[y]="PostgresJsTransaction";transaction(o){return this.session.client.savepoint((n)=>{let T=new qf(n,this.dialect,this.schema,this.session.options),f=new B$(this.dialect,T,this.schema);return o(f)})}}class z0 extends rf{static[y]="PostgresJsDatabase"}function sT(o,n={}){let T=(J)=>J;for(let J of["1184","1082","1083","1114"])o.options.parsers[J]=T,o.options.serializers[J]=T;o.options.serializers["114"]=T,o.options.serializers["3802"]=T;let f=new KT({casing:n.casing}),S;if(n.logger===!0)S=new lA;else if(n.logger!==!1)S=n.logger;let A;if(n.schema){let J=uR(n.schema,sR);A={fullSchema:n.schema,schema:J.tables,tableNamesMap:J.tableNamesMap}}let $=new qf(o,f,A,{logger:S}),F=new z0(f,$,A);return F.$client=o,F}function gS(...o){if(typeof o[0]==="string"){let n=uT(o[0]);return sT(n,o[1])}if(aJ(o[0])){let{connection:n,client:T,...f}=o[0];if(T)return sT(T,f);if(typeof n==="object"&&n.url!==void 0){let{url:A,...$}=n,F=uT(A,$);return sT(F,f)}let S=uT(n);return sT(S,f)}return sT(o[0],o[1])}((o)=>{function n(T){return sT({options:{parsers:{},serializers:{}}},T)}o.mock=n})(gS||(gS={}));var C$={};mM(C$,{users:()=>HT,userChanges:()=>u1,untrackedUserColumnNames:()=>l1,twoFactorMethod:()=>m0,trackedUserColumnName:()=>V0,trackableUserColumnNames:()=>U0,role:()=>Q0,players:()=>L$,passwordResetAttempts:()=>s1,loginHistory:()=>e1,games:()=>dS,banishedIps:()=>a1});function D0(o){return k`lower(${o})`}var Q0=kS("role",["admin","user"]),HT=oT("users",{id:Rn().primaryKey().defaultRandom(),username:po({length:16}).notNull(),email:po({length:254}).notNull(),hash:po({length:64}).notNull(),salt:po({length:36}).notNull(),createdAt:Dn({withTimezone:!0}).notNull().defaultNow(),createdIp:po({length:45}).notNull(),isActive:mf().notNull().default(!1),verifiedAt:Dn({withTimezone:!0}),userRole:Q0().default("user")},(o)=>[Q$("usernameUniqueIndex").on(D0(o.username)),Q$("emailUniqueIndex").on(D0(o.email))]),l1=["id","createdAt","createdIp","isActive","salt","verifiedAt"],U0=["username","email","hash","userRole"],V0=kS("trackedUserColumnName",U0),u1=oT("userChanges",{id:Rn().primaryKey().defaultRandom(),userId:Rn().notNull().references(()=>HT.id),changedAt:Dn({withTimezone:!0}).notNull().defaultNow(),changedIp:po({length:45}).notNull(),changedColumn:V0().notNull(),oldValue:po({length:255}),newValue:po({length:255})}),dS=oT("games",{id:Rn().primaryKey().defaultRandom()}),L$=oT("players",{userId:Rn().notNull().references(()=>HT.id),gameId:Rn().notNull().references(()=>dS.id),score:YS().notNull()},(o)=>[PR({name:"players_userId_gameId_pk",columns:[o.userId,o.gameId]})]),e1=oT("loginHistory",{id:Rn().primaryKey().defaultRandom(),userId:Rn().references(()=>HT.id),loginTime:Dn({withTimezone:!0}).notNull().defaultNow(),ipAddress:po({length:45}).notNull(),userAgent:po({length:1024}),successful:mf().notNull().default(!1)}),m0=kS("twoFactorMethod",["email","phone"]),s1=oT("passwordResetAttempts",{id:Rn().primaryKey().defaultRandom(),userId:Rn().notNull().references(()=>HT.id),requestedIp:po({length:45}).notNull(),requestedAt:Dn({withTimezone:!0}).notNull().defaultNow(),succeededIp:po({length:45}),succeededAt:Dn({withTimezone:!0}),verificationMethod:m0().notNull()}),a1=oT("banishedIps",{ip:po({length:45}).primaryKey(),reason:po({length:2048}).notNull(),banishedAt:Dn({withTimezone:!0}).notNull().defaultNow(),banishedUntil:Dn({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(ok.resolve(__dirname,"notify_update.sql"));let o=[vo(HT),vo(dS),vo(L$)];await this.sql`SELECT create_notify_triggers(${this.sql.array(o)})`,await this.sql.listen("table_update",(n)=>{let T=n.split(","),f=T[0],S=T[1],A=`${f}("${S}")`;if(this.observers.has(A))this.observers.get(A).next(A)})}constructor(o=!1,n={host:Yn.POSTGRES_HOST,port:Yn.POSTGRES_PORT,user:Yn.POSTGRES_USER,password:Yn.POSTGRES_PASSWORD,database:Yn.POSTGRES_DATABASE}){this.options=n,this.sql=uT(n),this.drizzle=gS(this.sql,{schema:C$,logger:o})}observe(o,n){if(!this.observers.has(o))this.observers.set(o,new oo);this.observers.get(o).subscribe("SINGLETON",n)}}var lS={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$(lS).map(([o])=>Eo.literal(Number(o))),nk=Eo.union([j$[0],j$[1],...j$]),B0=Eo.tuple([nk,Eo.string()]);var h$=new QA,{logger:$n}=h$;Object.assign(console,$n,{log:$n.info});$n.info("ready");var N$=C0(import.meta.dir,"..","app"),Fz=new I$({logQuery(o,n){$n.info("\uD83D\uDCDD query",o,n)}});Sk({hostname:"0.0.0.0",port:Yn.FRONTEND_PORT??3333,...MJ??void 0,async fetch(o){try{let n=new Date,T=new URL(o.url);if($n.info(o.method,T.pathname),T.pathname==="/")return new Response(Bun.file(C0(N$,"index.html")));if(T.pathname==="/index.html")return Response.redirect("/");let f=Tk(N$,T.pathname),S=fk(f);if(!S.startsWith(N$))throw[403,"Access Denied"];if(!await L0(S).exists())return Response.redirect("/");return new Response(L0(S))}catch(n){let T=B0.safeParse(n);if(T.success){let[f,S]=T.data,$=`${lS[f]}. ${S}`;return $n.info(`\u274C ${f}: ${$}`),new Response($,{status:f})}if(n instanceof Error)$n.error(n.message);else{let f=VT(n);$n.error("frontend server threw",f)}return new Response(lS[500],{status:500})}}});function uS(){$n.info("\uD83D\uDEEC frontend server exiting"),process.exit(0)}process.on("SIGINT",()=>{$n.info("\u2757 received SIGINT; exiting gracefully"),uS()});process.on("SIGTERM",()=>{$n.info("\u2757 received SIGTERM; exiting gracefully"),uS()});process.on("exit",()=>{$n.info("\u2757 received exit; exiting gracefully"),uS()});h$.on("timeToStop",()=>{$n.info('\u2757 backend server received signal "timeToStop"; exiting gracefully'),uS()});$n.info(`\uD83D\uDEEB frontend server running at http://localhost:${Yn.FRONTEND_PORT}/`);h$.emit("alive");
|
|
43
|
+
`;await T.execute(k`CREATE SCHEMA IF NOT EXISTS ${k.identifier(S)}`),await T.execute(A);let F=(await T.all(k`select id, hash, created_at from ${k.identifier(S)}.${k.identifier(f)} order by created_at desc limit 1`))[0];await T.transaction(async(J)=>{for await(let t of o)if(!F||Number(F.created_at)<t.folderMillis){for(let R of t.sql)await J.execute(k.raw(R));await J.execute(k`insert into ${k.identifier(S)}.${k.identifier(f)} ("hash", "created_at") values(${t.hash}, ${t.folderMillis})`)}})}escapeName(o){return`"${o}"`}escapeParam(o){return`$${o+1}`}escapeString(o){return`'${o.replace(/'/g,"''")}'`}buildWithCTE(o){if(!o?.length)return;let T=[k`with `];for(let[n,f]of o.entries())if(T.push(k`${k.identifier(f._.alias)} as (${f._.sql})`),n<o.length-1)T.push(k`, `);return T.push(k` `),k.join(T)}buildDeleteQuery({table:o,where:T,returning:n,withList:f}){let S=this.buildWithCTE(f),A=n?k` returning ${this.buildSelection(n,{isSingleTable:!0})}`:void 0,$=T?k` where ${T}`:void 0;return k`${S}delete from ${o}${$}${A}`}buildUpdateSet(o,T){let n=o[I.Symbol.Columns],f=Object.keys(n).filter((A)=>T[A]!==void 0||n[A]?.onUpdateFn!==void 0),S=f.length;return k.join(f.flatMap((A,$)=>{let F=n[A],J=T[A]??k.param(F.onUpdateFn(),F),t=k`${k.identifier(this.casing.getColumnCasing(F))} = ${J}`;if($<S-1)return[t,k.raw(", ")];return[t]}))}buildUpdateQuery({table:o,set:T,where:n,returning:f,withList:S,from:A,joins:$}){let F=this.buildWithCTE(S),J=o[co.Symbol.Name],t=o[co.Symbol.Schema],R=o[co.Symbol.OriginalName],W=J===R?void 0:J,O=k`${t?k`${k.identifier(t)}.`:void 0}${k.identifier(R)}${W&&k` ${k.identifier(W)}`}`,_=this.buildUpdateSet(o,T),Q=A&&k.join([k.raw(" from "),this.buildFromTable(A)]),H=this.buildJoins($),m=f?k` returning ${this.buildSelection(f,{isSingleTable:!A})}`:void 0,b=n?k` where ${n}`:void 0;return k`${F}update ${O} set ${_}${Q}${H}${b}${m}`}buildSelection(o,{isSingleTable:T=!1}={}){let n=o.length,f=o.flatMap(({field:S},A)=>{let $=[];if(X(S,j.Aliased)&&S.isSelectionField)$.push(k.identifier(S.fieldAlias));else if(X(S,j.Aliased)||X(S,j)){let F=X(S,j.Aliased)?S.sql:S;if(T)$.push(new j(F.queryChunks.map((J)=>{if(X(J,V))return k.identifier(this.casing.getColumnCasing(J));return J})));else $.push(F);if(X(S,j.Aliased))$.push(k` as ${k.identifier(S.fieldAlias)}`)}else if(X(S,Wo))if(T)$.push(k.identifier(this.casing.getColumnCasing(S)));else $.push(S);if(A<n-1)$.push(k`, `);return $});return k.join(f)}buildJoins(o){if(!o||o.length===0)return;let T=[];for(let[n,f]of o.entries()){if(n===0)T.push(k` `);let S=f.table,A=f.lateral?k` lateral`:void 0;if(X(S,co)){let $=S[co.Symbol.Name],F=S[co.Symbol.Schema],J=S[co.Symbol.OriginalName],t=$===J?void 0:f.alias;T.push(k`${k.raw(f.joinType)} join${A} ${F?k`${k.identifier(F)}.`:void 0}${k.identifier(J)}${t&&k` ${k.identifier(t)}`} on ${f.on}`)}else if(X(S,ST)){let $=S[Xo].name,F=S[Xo].schema,J=S[Xo].originalName,t=$===J?void 0:f.alias;T.push(k`${k.raw(f.joinType)} join${A} ${F?k`${k.identifier(F)}.`:void 0}${k.identifier(J)}${t&&k` ${k.identifier(t)}`} on ${f.on}`)}else T.push(k`${k.raw(f.joinType)} join${A} ${S} on ${f.on}`);if(n<o.length-1)T.push(k` `)}return k.join(T)}buildFromTable(o){if(X(o,I)&&o[I.Symbol.IsAlias]){let T=k`${k.identifier(o[I.Symbol.OriginalName])}`;if(o[I.Symbol.Schema])T=k`${k.identifier(o[I.Symbol.Schema])}.${T}`;return k`${T} ${k.identifier(o[I.Symbol.Name])}`}return o}buildSelectQuery({withList:o,fields:T,fieldsFlat:n,where:f,having:S,table:A,joins:$,orderBy:F,groupBy:J,limit:t,offset:R,lockingClause:W,distinct:O,setOperators:_}){let Q=n??OT(T);for(let a of Q)if(X(a.field,Wo)&&vo(a.field.table)!==(X(A,No)?A._.alias:X(A,bf)?A[Xo].name:X(A,j)?void 0:vo(A))&&!((ko)=>$?.some(({alias:mo})=>mo===(ko[I.Symbol.IsAlias]?vo(ko):ko[I.Symbol.BaseName])))(a.field.table)){let ko=vo(a.field.table);throw new Error(`Your "${a.path.join("->")}" field references a column "${ko}"."${a.field.name}", but the table "${ko}" is not part of the query! Did you forget to join it?`)}let H=!$||$.length===0,m=this.buildWithCTE(o),b;if(O)b=O===!0?k` distinct`:k` distinct on (${k.join(O.on,k`, `)})`;let r=this.buildSelection(Q,{isSingleTable:H}),P=this.buildFromTable(A),E=this.buildJoins($),z=f?k` where ${f}`:void 0,U=S?k` having ${S}`:void 0,D;if(F&&F.length>0)D=k` order by ${k.join(F,k`, `)}`;let v;if(J&&J.length>0)v=k` group by ${k.join(J,k`, `)}`;let l=typeof t==="object"||typeof t==="number"&&t>=0?k` limit ${t}`:void 0,K=R?k` offset ${R}`:void 0,s=k.empty();if(W){let a=k` for ${k.raw(W.strength)}`;if(W.config.of)a.append(k` of ${k.join(Array.isArray(W.config.of)?W.config.of:[W.config.of],k`, `)}`);if(W.config.noWait)a.append(k` no wait`);else if(W.config.skipLocked)a.append(k` skip locked`);s.append(a)}let q=k`${m}select${b} ${r} from ${P}${E}${z}${v}${U}${D}${l}${K}${s}`;if(_.length>0)return this.buildSetOperations(q,_);return q}buildSetOperations(o,T){let[n,...f]=T;if(!n)throw new Error("Cannot pass undefined values to any set operator");if(f.length===0)return this.buildSetOperationQuery({leftSelect:o,setOperator:n});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:o,setOperator:n}),f)}buildSetOperationQuery({leftSelect:o,setOperator:{type:T,isAll:n,rightSelect:f,limit:S,orderBy:A,offset:$}}){let F=k`(${o.getSQL()}) `,J=k`(${f.getSQL()})`,t;if(A&&A.length>0){let _=[];for(let Q of A)if(X(Q,V))_.push(k.identifier(Q.name));else if(X(Q,j)){for(let H=0;H<Q.queryChunks.length;H++){let m=Q.queryChunks[H];if(X(m,V))Q.queryChunks[H]=k.identifier(m.name)}_.push(k`${Q}`)}else _.push(k`${Q}`);t=k` order by ${k.join(_,k`, `)} `}let R=typeof S==="object"||typeof S==="number"&&S>=0?k` limit ${S}`:void 0,W=k.raw(`${T} ${n?"all ":""}`),O=$?k` offset ${$}`:void 0;return k`${F}${W}${J}${t}${R}${O}`}buildInsertQuery({table:o,values:T,onConflict:n,returning:f,withList:S,select:A,overridingSystemValue_:$}){let F=[],J=o[I.Symbol.Columns],t=Object.entries(J).filter(([m,b])=>!b.shouldDisableInsert()),R=t.map(([,m])=>k.identifier(this.casing.getColumnCasing(m)));if(A){let m=T;if(X(m,j))F.push(m);else F.push(m.getSQL())}else{let m=T;F.push(k.raw("values "));for(let[b,r]of m.entries()){let P=[];for(let[E,z]of t){let U=r[E];if(U===void 0||X(U,tT)&&U.value===void 0)if(z.defaultFn!==void 0){let D=z.defaultFn(),v=X(D,j)?D:k.param(D,z);P.push(v)}else if(!z.default&&z.onUpdateFn!==void 0){let D=z.onUpdateFn(),v=X(D,j)?D:k.param(D,z);P.push(v)}else P.push(k`default`);else P.push(U)}if(F.push(P),b<m.length-1)F.push(k`, `)}}let W=this.buildWithCTE(S),O=k.join(F),_=f?k` returning ${this.buildSelection(f,{isSingleTable:!0})}`:void 0,Q=n?k` on conflict ${n}`:void 0,H=$===!0?k`overriding system value `:void 0;return k`${W}insert into ${o} ${R} ${H}${O}${Q}${_}`}buildRefreshMaterializedViewQuery({view:o,concurrently:T,withNoData:n}){let f=T?k` concurrently`:void 0,S=n?k` with no data`:void 0;return k`refresh materialized view${f} ${o}${S}`}prepareTyping(o){if(X(o,DS)||X(o,zS))return"json";else if(X(o,QS))return"decimal";else if(X(o,US))return"time";else if(X(o,VS)||X(o,BS))return"timestamp";else if(X(o,ES)||X(o,GS))return"date";else if(X(o,mS))return"uuid";else return"none"}sqlToQuery(o,T){return o.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,prepareTyping:this.prepareTyping,invokeSource:T})}buildRelationalQueryWithoutPK({fullSchema:o,schema:T,tableNamesMap:n,table:f,tableConfig:S,queryConfig:A,tableAlias:$,nestedQueryRelation:F,joinOn:J}){let t=[],R,W,O=[],_,Q=[];if(A===!0)t=Object.entries(S.columns).map(([b,r])=>({dbKey:r.name,tsKey:b,field:LT(r,$),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let m=Object.fromEntries(Object.entries(S.columns).map(([U,D])=>[U,LT(D,$)]));if(A.where){let U=typeof A.where==="function"?A.where(m,sR()):A.where;_=U&&Qf(U,$)}let b=[],r=[];if(A.columns){let U=!1;for(let[D,v]of Object.entries(A.columns)){if(v===void 0)continue;if(D in S.columns){if(!U&&v===!0)U=!0;r.push(D)}}if(r.length>0)r=U?r.filter((D)=>A.columns?.[D]===!0):Object.keys(S.columns).filter((D)=>!r.includes(D))}else r=Object.keys(S.columns);for(let U of r){let D=S.columns[U];b.push({tsKey:U,value:D})}let P=[];if(A.with)P=Object.entries(A.with).filter((U)=>!!U[1]).map(([U,D])=>({tsKey:U,queryConfig:D,relation:S.relations[U]}));let E;if(A.extras){E=typeof A.extras==="function"?A.extras(m,{sql:k}):A.extras;for(let[U,D]of Object.entries(E))b.push({tsKey:U,value:gA(D,$)})}for(let{tsKey:U,value:D}of b)t.push({dbKey:X(D,j.Aliased)?D.fieldAlias:S.columns[U].name,tsKey:U,field:X(D,Wo)?LT(D,$):D,relationTableTsKey:void 0,isJson:!1,selection:[]});let z=typeof A.orderBy==="function"?A.orderBy(m,aR()):A.orderBy??[];if(!Array.isArray(z))z=[z];O=z.map((U)=>{if(X(U,Wo))return LT(U,$);return Qf(U,$)}),R=A.limit,W=A.offset;for(let{tsKey:U,queryConfig:D,relation:v}of P){let l=T0(T,n,v),K=kn(v.referencedTable),s=n[K],q=`${$}_${U}`,a=Uf(...l.fields.map((nT,IT)=>HS(LT(l.references[IT],q),LT(nT,$)))),ko=this.buildRelationalQueryWithoutPK({fullSchema:o,schema:T,tableNamesMap:n,table:o[s],tableConfig:T[s],queryConfig:X(v,on)?D===!0?{limit:1}:{...D,limit:1}:D,tableAlias:q,joinOn:a,nestedQueryRelation:v}),mo=k`${k.identifier(q)}.${k.identifier("data")}`.as(U);Q.push({on:k`true`,table:new No(ko.sql,{},q),alias:q,joinType:"left",lateral:!0}),t.push({dbKey:U,tsKey:U,field:mo,relationTableTsKey:s,isJson:!0,selection:ko.selection})}}if(t.length===0)throw new XS({message:`No fields selected for table "${S.tsName}" ("${$}")`});let H;if(_=Uf(J,_),F){let m=k`json_build_array(${k.join(t.map(({field:P,tsKey:E,isJson:z})=>z?k`${k.identifier(`${$}_${E}`)}.${k.identifier("data")}`:X(P,j.Aliased)?P.sql:P),k`, `)})`;if(X(F,Lf))m=k`coalesce(json_agg(${m}${O.length>0?k` order by ${k.join(O,k`, `)}`:void 0}), '[]'::json)`;let b=[{dbKey:"data",tsKey:"data",field:m.as("data"),isJson:!0,relationTableTsKey:S.tsName,selection:t}];if(R!==void 0||W!==void 0||O.length>0)H=this.buildSelectQuery({table:_S(f,$),fields:{},fieldsFlat:[{path:[],field:k.raw("*")}],where:_,limit:R,offset:W,orderBy:O,setOperators:[]}),_=void 0,R=void 0,W=void 0,O=[];else H=_S(f,$);H=this.buildSelectQuery({table:X(H,co)?H:new No(H,{},$),fields:{},fieldsFlat:b.map(({field:P})=>({path:[],field:X(P,Wo)?LT(P,$):P})),joins:Q,where:_,limit:R,offset:W,orderBy:O,setOperators:[]})}else H=this.buildSelectQuery({table:_S(f,$),fields:{},fieldsFlat:t.map(({field:m})=>({path:[],field:X(m,Wo)?LT(m,$):m})),joins:Q,where:_,limit:R,offset:W,orderBy:O,setOperators:[]});return{tableTsKey:S.tsName,sql:H,selection:t}}}class H${static[y]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class TT{static[y]="PgSelectBuilder";fields;session;dialect;withList=[];distinct;constructor(o){if(this.fields=o.fields,this.session=o.session,this.dialect=o.dialect,o.withList)this.withList=o.withList;this.distinct=o.distinct}authToken;setToken(o){return this.authToken=o,this}from(o){let T=!!this.fields,n=o,f;if(this.fields)f=this.fields;else if(X(n,No))f=Object.fromEntries(Object.keys(n._.selectedFields).map((S)=>[S,n[S]]));else if(X(n,bf))f=n[Xo].selectedFields;else if(X(n,j))f={};else f=sJ(n);return new K$({table:n,fields:f,isPartialSelect:T,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}}class Y0 extends H${static[y]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;constructor({table:o,fields:T,isPartialSelect:n,session:f,dialect:S,withList:A,distinct:$}){super();this.config={withList:A,table:o,fields:{...T},distinct:$,setOperators:[]},this.isPartialSelect=n,this.session=f,this.dialect=S,this._={selectedFields:T},this.tableName=qT(o),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}createJoin(o){return(T,n)=>{let f=this.tableName,S=qT(T);if(typeof S==="string"&&this.config.joins?.some((A)=>A.alias===S))throw new Error(`Alias "${S}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof f==="string")this.config.fields={[f]:this.config.fields};if(typeof S==="string"&&!X(T,j)){let A=X(T,No)?T._.selectedFields:X(T,ST)?T[Xo].selectedFields:T[I.Symbol.Columns];this.config.fields[S]=A}}if(typeof n==="function")n=n(new Proxy(this.config.fields,new Qo({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:n,table:T,joinType:o,alias:S}),typeof S==="string")switch(o){case"left":{this.joinsNotNullableMap[S]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([A])=>[A,!1])),this.joinsNotNullableMap[S]=!0;break}case"inner":{this.joinsNotNullableMap[S]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([A])=>[A,!1])),this.joinsNotNullableMap[S]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");createSetOperator(o,T){return(n)=>{let f=typeof n==="function"?n(iy()):n;if(!Vf(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:o,isAll:T,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(o){return this.config.setOperators.push(...o),this}where(o){if(typeof o==="function")o=o(new Proxy(this.config.fields,new Qo({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=o,this}having(o){if(typeof o==="function")o=o(new Proxy(this.config.fields,new Qo({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=o,this}groupBy(...o){if(typeof o[0]==="function"){let T=o[0](new Proxy(this.config.fields,new Qo({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(T)?T:[T]}else this.config.groupBy=o;return this}orderBy(...o){if(typeof o[0]==="function"){let T=o[0](new Proxy(this.config.fields,new Qo({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),n=Array.isArray(T)?T:[T];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=n;else this.config.orderBy=n}else{let T=o;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=T;else this.config.orderBy=T}return this}limit(o){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=o;else this.config.limit=o;return this}offset(o){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=o;else this.config.offset=o;return this}for(o,T={}){return this.config.lockingClause={strength:o,config:T},this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:o,...T}=this.dialect.sqlToQuery(this.getSQL());return T}as(o){return new Proxy(new No(this.getSQL(),this.config.fields,o),new Qo({alias:o,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new Qo({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}}class K$ extends Y0{static[y]="PgSelect";_prepare(o){let{session:T,config:n,dialect:f,joinsNotNullableMap:S,authToken:A}=this;if(!T)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");return Oo.startActiveSpan("drizzle.prepareQuery",()=>{let $=OT(n.fields),F=T.prepareQuery(f.sqlToQuery(this.getSQL()),$,o,!0);return F.joinsNotNullableMap=S,F.setToken(A)})}prepare(o){return this._prepare(o)}authToken;setToken(o){return this.authToken=o,this}execute=(o)=>{return Oo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(o,this.authToken)})}}eJ(K$,[oT]);function en(o,T){return(n,f,...S)=>{let A=[f,...S].map(($)=>({type:o,isAll:T,rightSelect:$}));for(let $ of A)if(!Vf(n.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 n.addSetOperators(A)}}var iy=()=>({union:gy,unionAll:dy,intersect:ly,intersectAll:uy,except:ey,exceptAll:sy}),gy=en("union",!1),dy=en("union",!0),ly=en("intersect",!1),uy=en("intersect",!0),ey=en("except",!1),sy=en("except",!0);class xf{static[y]="PgQueryBuilder";dialect;dialectConfig;constructor(o){this.dialect=X(o,Xn)?o:void 0,this.dialectConfig=X(o,Xn)?void 0:o}$with=(o,T)=>{let n=this;return{as:(S)=>{if(typeof S==="function")S=S(n);return new Proxy(new Yf(S.getSQL(),T??("getSelectedFields"in S?S.getSelectedFields()??{}:{}),o,!0),new Qo({alias:o,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...o){let T=this;function n(A){return new TT({fields:A??void 0,session:void 0,dialect:T.getDialect(),withList:o})}function f(A){return new TT({fields:A??void 0,session:void 0,dialect:T.getDialect(),distinct:!0})}function S(A,$){return new TT({fields:$??void 0,session:void 0,dialect:T.getDialect(),distinct:{on:A}})}return{select:n,selectDistinct:f,selectDistinctOn:S}}select(o){return new TT({fields:o??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(o){return new TT({fields:o??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(o,T){return new TT({fields:T??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:o}})}getDialect(){if(!this.dialect)this.dialect=new Xn(this.dialectConfig);return this.dialect}}class ZS{constructor(o,T,n,f,S){this.table=o,this.session=T,this.dialect=n,this.withList=f,this.overridingSystemValue_=S}static[y]="PgInsertBuilder";authToken;setToken(o){return this.authToken=o,this}overridingSystemValue(){return this.overridingSystemValue_=!0,this}values(o){if(o=Array.isArray(o)?o:[o],o.length===0)throw new Error("values() must be called with at least one value");let T=o.map((n)=>{let f={},S=this.table[I.Symbol.Columns];for(let A of Object.keys(n)){let $=n[A];f[A]=X($,j)?$:new tT($,S[A])}return f});return new E$(this.table,T,this.session,this.dialect,this.withList,!1,this.overridingSystemValue_).setToken(this.authToken)}select(o){let T=typeof o==="function"?o(new xf):o;if(!X(T,j)&&!Vf(this.table[OS],T._.selectedFields))throw new Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");return new E$(this.table,T,this.session,this.dialect,this.withList,!0)}}class E$ extends oT{constructor(o,T,n,f,S,A,$){super();this.session=n,this.dialect=f,this.config={table:o,values:T,withList:S,select:A,overridingSystemValue_:$}}static[y]="PgInsert";config;returning(o=this.config.table[I.Symbol.Columns]){return this.config.returningFields=o,this.config.returning=OT(o),this}onConflictDoNothing(o={}){if(o.target===void 0)this.config.onConflict=k`do nothing`;else{let T="";T=Array.isArray(o.target)?o.target.map((f)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(f))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(o.target));let n=o.where?k` where ${o.where}`:void 0;this.config.onConflict=k`(${k.raw(T)})${n} do nothing`}return this}onConflictDoUpdate(o){if(o.where&&(o.targetWhere||o.setWhere))throw new Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');let T=o.where?k` where ${o.where}`:void 0,n=o.targetWhere?k` where ${o.targetWhere}`:void 0,f=o.setWhere?k` where ${o.setWhere}`:void 0,S=this.dialect.buildUpdateSet(this.config.table,KS(this.config.table,o.set)),A="";return A=Array.isArray(o.target)?o.target.map(($)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing($))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(o.target)),this.config.onConflict=k`(${k.raw(A)})${n} do update set ${S}${T}${f}`,this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:o,...T}=this.dialect.sqlToQuery(this.getSQL());return T}_prepare(o){return Oo.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,o,!0)})}prepare(o){return this._prepare(o)}authToken;setToken(o){return this.authToken=o,this}execute=(o)=>{return Oo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(o,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new Qo({alias:vo(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class G$ extends oT{constructor(o,T,n){super();this.session=T,this.dialect=n,this.config={view:o}}static[y]="PgRefreshMaterializedView";config;concurrently(){if(this.config.withNoData!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.concurrently=!0,this}withNoData(){if(this.config.concurrently!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.withNoData=!0,this}getSQL(){return this.dialect.buildRefreshMaterializedViewQuery(this.config)}toSQL(){let{typings:o,...T}=this.dialect.sqlToQuery(this.getSQL());return T}_prepare(o){return Oo.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),void 0,o,!0)})}prepare(o){return this._prepare(o)}authToken;setToken(o){return this.authToken=o,this}execute=(o)=>{return Oo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(o,this.authToken)})}}class PS{constructor(o,T,n,f){this.table=o,this.session=T,this.dialect=n,this.withList=f}static[y]="PgUpdateBuilder";authToken;setToken(o){return this.authToken=o,this}set(o){return new z0(this.table,KS(this.table,o),this.session,this.dialect,this.withList).setToken(this.authToken)}}class z0 extends oT{constructor(o,T,n,f,S){super();this.session=n,this.dialect=f,this.config={set:T,table:o,withList:S,joins:[]},this.tableName=qT(o),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}static[y]="PgUpdate";config;tableName;joinsNotNullableMap;from(o){let T=o,n=qT(T);if(typeof n==="string")this.joinsNotNullableMap[n]=!0;return this.config.from=T,this}getTableLikeFields(o){if(X(o,co))return o[I.Symbol.Columns];else if(X(o,No))return o._.selectedFields;return o[Xo].selectedFields}createJoin(o){return(T,n)=>{let f=qT(T);if(typeof f==="string"&&this.config.joins.some((S)=>S.alias===f))throw new Error(`Alias "${f}" is already used in this query`);if(typeof n==="function"){let S=this.config.from&&!X(this.config.from,j)?this.getTableLikeFields(this.config.from):void 0;n=n(new Proxy(this.config.table[I.Symbol.Columns],new Qo({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),S&&new Proxy(S,new Qo({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}if(this.config.joins.push({on:n,table:T,joinType:o,alias:f}),typeof f==="string")switch(o){case"left":{this.joinsNotNullableMap[f]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([S])=>[S,!1])),this.joinsNotNullableMap[f]=!0;break}case"inner":{this.joinsNotNullableMap[f]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([S])=>[S,!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(o){return this.config.where=o,this}returning(o){if(!o){if(o=Object.assign({},this.config.table[I.Symbol.Columns]),this.config.from){let T=qT(this.config.from);if(typeof T==="string"&&this.config.from&&!X(this.config.from,j)){let n=this.getTableLikeFields(this.config.from);o[T]=n}for(let n of this.config.joins){let f=qT(n.table);if(typeof f==="string"&&!X(n.table,j)){let S=this.getTableLikeFields(n.table);o[f]=S}}}}return this.config.returningFields=o,this.config.returning=OT(o),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:o,...T}=this.dialect.sqlToQuery(this.getSQL());return T}_prepare(o){let T=this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,o,!0);return T.joinsNotNullableMap=this.joinsNotNullableMap,T}prepare(o){return this._prepare(o)}authToken;setToken(o){return this.authToken=o,this}execute=(o)=>{return this._prepare().execute(o,this.authToken)};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new Qo({alias:vo(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class vf extends j{constructor(o){super(vf.buildEmbeddedCount(o.source,o.filters).queryChunks);this.params=o,this.mapWith(Number),this.session=o.session,this.sql=vf.buildCount(o.source,o.filters)}sql;token;static[y]="PgCountBuilder";[Symbol.toStringTag]="PgCountBuilder";session;static buildEmbeddedCount(o,T){return k`(select count(*) from ${o}${k.raw(" where ").if(T)}${T})`}static buildCount(o,T){return k`select count(*) as count from ${o}${k.raw(" where ").if(T)}${T};`}setToken(o){return this.token=o,this}then(o,T){return Promise.resolve(this.session.count(this.sql,this.token)).then(o,T)}catch(o){return this.then(void 0,o)}finally(o){return this.then((T)=>{return o?.(),T},(T)=>{throw o?.(),T})}}class z${constructor(o,T,n,f,S,A,$){this.fullSchema=o,this.schema=T,this.tableNamesMap=n,this.table=f,this.tableConfig=S,this.dialect=A,this.session=$}static[y]="PgRelationalQueryBuilder";findMany(o){return new Y$(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,o?o:{},"many")}findFirst(o){return new Y$(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,o?{...o,limit:1}:{limit:1},"first")}}class Y$ extends oT{constructor(o,T,n,f,S,A,$,F,J){super();this.fullSchema=o,this.schema=T,this.tableNamesMap=n,this.table=f,this.tableConfig=S,this.dialect=A,this.session=$,this.config=F,this.mode=J}static[y]="PgRelationalQuery";_prepare(o){return Oo.startActiveSpan("drizzle.prepareQuery",()=>{let{query:T,builtQuery:n}=this._toSQL();return this.session.prepareQuery(n,void 0,o,!0,(f,S)=>{let A=f.map(($)=>LS(this.schema,this.tableConfig,$,T.selection,S));if(this.mode==="first")return A[0];return A})})}prepare(o){return this._prepare(o)}_getQuery(){return this.dialect.buildRelationalQueryWithoutPK({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName})}getSQL(){return this._getQuery().sql}_toSQL(){let o=this._getQuery(),T=this.dialect.sqlToQuery(o.sql);return{query:o,builtQuery:T}}toSQL(){return this._toSQL().builtQuery}authToken;setToken(o){return this.authToken=o,this}execute(){return Oo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(void 0,this.authToken)})}}class D$ extends oT{constructor(o,T,n,f){super();this.execute=o,this.sql=T,this.query=n,this.mapBatchResult=f}static[y]="PgRaw";getSQL(){return this.sql}getQuery(){return this.query}mapResult(o,T){return T?this.mapBatchResult(o):o}_prepare(){return this}isResponseInArrayMode(){return!1}}class rf{constructor(o,T,n){if(this.dialect=o,this.session=T,this._=n?{schema:n.schema,fullSchema:n.fullSchema,tableNamesMap:n.tableNamesMap,session:T}:{schema:void 0,fullSchema:{},tableNamesMap:{},session:T},this.query={},this._.schema)for(let[f,S]of Object.entries(this._.schema))this.query[f]=new z$(n.fullSchema,this._.schema,this._.tableNamesMap,n.fullSchema[f],S,o,T)}static[y]="PgDatabase";query;$with=(o,T)=>{let n=this;return{as:(S)=>{if(typeof S==="function")S=S(new xf(n.dialect));return new Proxy(new Yf(S.getSQL(),T??("getSelectedFields"in S?S.getSelectedFields()??{}:{}),o,!0),new Qo({alias:o,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(o,T){return new vf({source:o,filters:T,session:this.session})}with(...o){let T=this;function n(J){return new TT({fields:J??void 0,session:T.session,dialect:T.dialect,withList:o})}function f(J){return new TT({fields:J??void 0,session:T.session,dialect:T.dialect,withList:o,distinct:!0})}function S(J,t){return new TT({fields:t??void 0,session:T.session,dialect:T.dialect,withList:o,distinct:{on:J}})}function A(J){return new PS(J,T.session,T.dialect,o)}function $(J){return new ZS(J,T.session,T.dialect,o)}function F(J){return new cS(J,T.session,T.dialect,o)}return{select:n,selectDistinct:f,selectDistinctOn:S,update:A,insert:$,delete:F}}select(o){return new TT({fields:o??void 0,session:this.session,dialect:this.dialect})}selectDistinct(o){return new TT({fields:o??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(o,T){return new TT({fields:T??void 0,session:this.session,dialect:this.dialect,distinct:{on:o}})}update(o){return new PS(o,this.session,this.dialect)}insert(o){return new ZS(o,this.session,this.dialect)}delete(o){return new cS(o,this.session,this.dialect)}refreshMaterializedView(o){return new G$(o,this.session,this.dialect)}authToken;execute(o){let T=typeof o==="string"?k.raw(o):o.getSQL(),n=this.dialect.sqlToQuery(T),f=this.session.prepareQuery(n,void 0,void 0,!1);return new D$(()=>f.execute(void 0,this.authToken),T,n,(S)=>f.mapResult(S,!0))}transaction(o,T){return this.session.transaction(o,T)}}class D0{constructor(o,T){this.unique=o,this.name=T}static[y]="PgIndexBuilderOn";on(...o){return new iS(o.map((T)=>{if(X(T,j))return T;T=T;let n=new Gf(T.name,!!T.keyAsName,T.columnType,T.indexConfig);return T.indexConfig=JSON.parse(JSON.stringify(T.defaultConfig)),n}),this.unique,!1,this.name)}onOnly(...o){return new iS(o.map((T)=>{if(X(T,j))return T;T=T;let n=new Gf(T.name,!!T.keyAsName,T.columnType,T.indexConfig);return T.indexConfig=T.defaultConfig,n}),this.unique,!0,this.name)}using(o,...T){return new iS(T.map((n)=>{if(X(n,j))return n;n=n;let f=new Gf(n.name,!!n.keyAsName,n.columnType,n.indexConfig);return n.indexConfig=JSON.parse(JSON.stringify(n.defaultConfig)),f}),this.unique,!0,this.name,o)}}class iS{static[y]="PgIndexBuilder";config;constructor(o,T,n,f,S="btree"){this.config={name:f,columns:o,unique:T,only:n,method:S}}concurrently(){return this.config.concurrently=!0,this}with(o){return this.config.with=o,this}where(o){return this.config.where=o,this}build(o){return new Q0(this.config,o)}}class Q0{static[y]="PgIndex";config;constructor(o,T){this.config={...o,table:T}}}function Q$(o){return new D0(!0,o)}class U${constructor(o){this.query=o}authToken;getQuery(){return this.query}mapResult(o,T){return o}setToken(o){return this.authToken=o,this}static[y]="PgPreparedQuery";joinsNotNullableMap}class V${constructor(o){this.dialect=o}static[y]="PgSession";execute(o,T){return Oo.startActiveSpan("drizzle.operation",()=>{return Oo.startActiveSpan("drizzle.prepareQuery",()=>{return this.prepareQuery(this.dialect.sqlToQuery(o),void 0,void 0,!1)}).setToken(T).execute(void 0,T)})}all(o){return this.prepareQuery(this.dialect.sqlToQuery(o),void 0,void 0,!1).all()}async count(o,T){let n=await this.execute(o,T);return Number(n[0].count)}}class B$ extends rf{constructor(o,T,n,f=0){super(o,T,n);this.schema=n,this.nestedIndex=f}static[y]="PgTransaction";rollback(){throw new dA}getTransactionConfigSQL(o){let T=[];if(o.isolationLevel)T.push(`isolation level ${o.isolationLevel}`);if(o.accessMode)T.push(o.accessMode);if(typeof o.deferrable==="boolean")T.push(o.deferrable?"deferrable":"not deferrable");return k.raw(T.join(" "))}setTransaction(o){return this.session.execute(k`set transaction ${this.getTransactionConfigSQL(o)}`)}}class U0 extends U${constructor(o,T,n,f,S,A,$){super({sql:T,params:n});this.client=o,this.queryString=T,this.params=n,this.logger=f,this.fields=S,this._isResponseInArrayMode=A,this.customResultMapper=$}static[y]="PostgresJsPreparedQuery";async execute(o={}){return Oo.startActiveSpan("drizzle.execute",async(T)=>{let n=iA(this.params,o);T?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(n)}),this.logger.logQuery(this.queryString,n);let{fields:f,queryString:S,client:A,joinsNotNullableMap:$,customResultMapper:F}=this;if(!f&&!F)return Oo.startActiveSpan("drizzle.driver.execute",()=>{return A.unsafe(S,n)});let J=await Oo.startActiveSpan("drizzle.driver.execute",()=>{return T?.setAttributes({"drizzle.query.text":S,"drizzle.query.params":JSON.stringify(n)}),A.unsafe(S,n).values()});return Oo.startActiveSpan("drizzle.mapResponse",()=>{return F?F(J):J.map((t)=>uJ(f,t,$))})})}all(o={}){return Oo.startActiveSpan("drizzle.execute",async(T)=>{let n=iA(this.params,o);return T?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(n)}),this.logger.logQuery(this.queryString,n),Oo.startActiveSpan("drizzle.driver.execute",()=>{return T?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(n)}),this.client.unsafe(this.queryString,n)})})}isResponseInArrayMode(){return this._isResponseInArrayMode}}class qf extends V${constructor(o,T,n,f={}){super(T);this.client=o,this.schema=n,this.options=f,this.logger=f.logger??new uA}static[y]="PostgresJsSession";logger;prepareQuery(o,T,n,f,S){return new U0(this.client,o.sql,o.params,this.logger,T,f,S)}query(o,T){return this.logger.logQuery(o,T),this.client.unsafe(o,T).values()}queryObjects(o,T){return this.client.unsafe(o,T)}transaction(o,T){return this.client.begin(async(n)=>{let f=new qf(n,this.dialect,this.schema,this.options),S=new m$(this.dialect,f,this.schema);if(T)await S.setTransaction(T);return o(S)})}}class m$ extends B${constructor(o,T,n,f=0){super(o,T,n,f);this.session=T}static[y]="PostgresJsTransaction";transaction(o){return this.session.client.savepoint((T)=>{let n=new qf(T,this.dialect,this.schema,this.session.options),f=new m$(this.dialect,n,this.schema);return o(f)})}}class V0 extends rf{static[y]="PostgresJsDatabase"}function sn(o,T={}){let n=(J)=>J;for(let J of["1184","1082","1083","1114","1182","1185","1115","1231"])o.options.parsers[J]=n,o.options.serializers[J]=n;o.options.serializers["114"]=n,o.options.serializers["3802"]=n;let f=new Xn({casing:T.casing}),S;if(T.logger===!0)S=new lA;else if(T.logger!==!1)S=T.logger;let A;if(T.schema){let J=o0(T.schema,n0);A={fullSchema:T.schema,schema:J.tables,tableNamesMap:J.tableNamesMap}}let $=new qf(o,f,A,{logger:S}),F=new V0(f,$,A);return F.$client=o,F}function gS(...o){if(typeof o[0]==="string"){let T=un(o[0]);return sn(T,o[1])}if(aJ(o[0])){let{connection:T,client:n,...f}=o[0];if(n)return sn(n,f);if(typeof T==="object"&&T.url!==void 0){let{url:A,...$}=T,F=un(A,$);return sn(F,f)}let S=un(T);return sn(S,f)}return sn(o[0],o[1])}((o)=>{function T(n){return sn({options:{parsers:{},serializers:{}}},n)}o.mock=T})(gS||(gS={}));var C$={};IM(C$,{users:()=>Hn,userChanges:()=>ok,untrackedUserColumnNames:()=>ay,twoFactorMethod:()=>I0,trackedUserColumnName:()=>C0,trackableUserColumnNames:()=>L0,role:()=>m0,players:()=>L$,passwordResetAttempts:()=>nk,loginHistory:()=>Tk,games:()=>dS,banishedIps:()=>fk});function B0(o){return k`lower(${o})`}var m0=kS("role",["admin","user"]),Hn=aT("users",{id:RT().primaryKey().defaultRandom(),username:po({length:16}).notNull(),email:po({length:254}).notNull(),hash:po({length:64}).notNull(),salt:po({length:36}).notNull(),createdAt:DT({withTimezone:!0}).notNull().defaultNow(),createdIp:po({length:45}).notNull(),isActive:Bf().notNull().default(!1),verifiedAt:DT({withTimezone:!0}),userRole:m0().default("user")},(o)=>[Q$("usernameUniqueIndex").on(B0(o.username)),Q$("emailUniqueIndex").on(B0(o.email))]),ay=["id","createdAt","createdIp","isActive","salt","verifiedAt"],L0=["username","email","hash","userRole"],C0=kS("trackedUserColumnName",L0),ok=aT("userChanges",{id:RT().primaryKey().defaultRandom(),userId:RT().notNull().references(()=>Hn.id),changedAt:DT({withTimezone:!0}).notNull().defaultNow(),changedIp:po({length:45}).notNull(),changedColumn:C0().notNull(),oldValue:po({length:255}),newValue:po({length:255})}),dS=aT("games",{id:RT().primaryKey().defaultRandom()}),L$=aT("players",{userId:RT().notNull().references(()=>Hn.id),gameId:RT().notNull().references(()=>dS.id),score:YS().notNull()},(o)=>[lR({name:"players_userId_gameId_pk",columns:[o.userId,o.gameId]})]),Tk=aT("loginHistory",{id:RT().primaryKey().defaultRandom(),userId:RT().references(()=>Hn.id),loginTime:DT({withTimezone:!0}).notNull().defaultNow(),ipAddress:po({length:45}).notNull(),userAgent:po({length:1024}),successful:Bf().notNull().default(!1)}),I0=kS("twoFactorMethod",["email","phone"]),nk=aT("passwordResetAttempts",{id:RT().primaryKey().defaultRandom(),userId:RT().notNull().references(()=>Hn.id),requestedIp:po({length:45}).notNull(),requestedAt:DT({withTimezone:!0}).notNull().defaultNow(),succeededIp:po({length:45}),succeededAt:DT({withTimezone:!0}),verificationMethod:I0().notNull()}),fk=aT("banishedIps",{ip:po({length:45}).primaryKey(),reason:po({length:2048}).notNull(),banishedAt:DT({withTimezone:!0}).notNull().defaultNow(),banishedUntil:DT({withTimezone:!0})});var __dirname="/home/runner/work/wayforge/wayforge/apps/tempest.games/src/database";class I${options;sql;drizzle;observers=new Map;async setupTriggersAndNotifications(){await this.sql.file(Sk.resolve(__dirname,"notify_update.sql"));let o=[vo(Hn),vo(dS),vo(L$)];await this.sql`SELECT create_notify_triggers(${this.sql.array(o)})`,await this.sql.listen("table_update",(T)=>{let n=T.split(","),f=n[0],S=n[1],A=`${f}("${S}")`;if(this.observers.has(A))this.observers.get(A).next(A)})}constructor(o=!1,T={host:YT.POSTGRES_HOST,port:YT.POSTGRES_PORT,user:YT.POSTGRES_USER,password:YT.POSTGRES_PASSWORD,database:YT.POSTGRES_DATABASE}){this.options=T,this.sql=un(T),this.drizzle=gS(this.sql,{schema:C$,logger:o})}observe(o,T){if(!this.observers.has(o))this.observers.set(o,new oo);this.observers.get(o).subscribe("SINGLETON",T)}}var lS={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$(lS).map(([o])=>Eo.literal(Number(o))),Ak=Eo.union([j$[0],j$[1],...j$]),j0=Eo.tuple([Ak,Eo.string()]);var N$=new QA,{logger:$T}=N$;Object.assign(console,$T,{log:$T.info});$T.info("ready");var h$=N0(import.meta.dir,"..","app"),Mz=new I$({logQuery(o,T){$T.info("\uD83D\uDCDD query",o,T)}});Jk({hostname:"0.0.0.0",port:YT.FRONTEND_PORT??3333,...MJ??void 0,async fetch(o){try{let T=new Date,n=new URL(o.url);if($T.info(o.method,n.pathname),n.pathname==="/")return new Response(Bun.file(N0(h$,"index.html")));if(n.pathname==="/index.html")return Response.redirect("/");let f=$k(h$,n.pathname),S=Fk(f);if(!S.startsWith(h$))throw[403,"Access Denied"];if(!await h0(S).exists())return Response.redirect("/");return new Response(h0(S))}catch(T){let n=j0.safeParse(T);if(n.success){let[f,S]=n.data,$=`${lS[f]}. ${S}`;return $T.info(`\u274C ${f}: ${$}`),new Response($,{status:f})}if(T instanceof Error)$T.error(T.message);else{let f=Un(T);$T.error("frontend server threw",f)}return new Response(lS[500],{status:500})}}});function uS(){$T.info("\uD83D\uDEEC frontend server exiting"),process.exit(0)}process.on("SIGINT",()=>{$T.info("\u2757 received SIGINT; exiting gracefully"),uS()});process.on("SIGTERM",()=>{$T.info("\u2757 received SIGTERM; exiting gracefully"),uS()});process.on("exit",()=>{$T.info("\u2757 received exit; exiting gracefully"),uS()});N$.on("timeToStop",()=>{$T.info('\u2757 backend server received signal "timeToStop"; exiting gracefully'),uS()});$T.info(`\uD83D\uDEEB frontend server running at http://localhost:${YT.FRONTEND_PORT}/`);N$.emit("alive");
|