tempest.games 0.1.13 → 0.1.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,16 +1,16 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- var mJ=Object.create;var{getPrototypeOf:QJ,defineProperty:of,getOwnPropertyNames:DJ}=Object;var UJ=Object.prototype.hasOwnProperty;var s0=(o,n,t)=>{t=o!=null?mJ(QJ(o)):{};let T=n||!o||!o.__esModule?of(t,"default",{value:o,enumerable:!0}):t;for(let S of DJ(o))if(!UJ.call(T,S))of(T,S,{get:()=>o[S],enumerable:!0});return T};var oW=(o,n)=>()=>(n||o((n={exports:{}}).exports,n),n.exports);var VJ=(o,n)=>{for(var t in n)of(o,t,{get:n[t],enumerable:!0,configurable:!0,set:(T)=>n[t]=()=>T})};import{join as g0,normalize as d0,resolve as B$}from"path";function zt(o=Math.random){return o().toString(36).slice(2)}class TT extends Promise{fate;resolve;reject;done=!1;constructor(o){let n,t;super((T,S)=>{n=T,t=S});this.resolve=n,this.reject=t,this.use(o instanceof Promise?o:new Promise(o))}pass(o,n){if(o===this.fate)this.resolve(n),this.done=!0}fail(o,n){if(o===this.fate)this.reject(n),this.done=!0}use(o){if(o instanceof Promise){let n=o;this.fate=n,n.then((t)=>{this.pass(n,t)},(t)=>{this.fail(n,t)})}else this.resolve(o),this.fate=void 0}}function sy(o){return Object.entries(o)}var oA=(o,n,t=yo.STORE)=>{return zn(t,{key:`${o.key}:JSON`,get:({get:T})=>n.toJson(T(o)),set:({set:T},S)=>{T(o,n.fromJson(S))}})};function D(o){while(o.child!==null)o=o.child;return o}function nA(o){while(o.parent!==null)o=o.parent;return o}class s{Subscriber;subscribers=new Map;subscribe(o,n){return this.subscribers.set(o,n),()=>{this.unsubscribe(o)}}unsubscribe(o){this.subscribers.delete(o)}next(o){let n=this.subscribers.values();for(let t of n)t(o)}}class nf extends s{state;constructor(o){super();this.state=o}next(o){this.state=o,super.next(o)}}function jn(o,n,t){let T={key:n.key,type:"atom_family"},S=o.families.get(n.key);if(S)o.logger.error("\u2757","atom_family",n.key,`Overwriting an existing ${Hn(S)} "${S.key}" in store "${o.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let f=new s,A=Object.assign((M)=>{let F=l(M),k={key:n.key,subKey:F},W=`${n.key}(${F})`,O=D(o),E=n.default,Q={key:W,default:E instanceof Function?E(M):E};if(n.effects)Q.effects=n.effects(M);let z=tn(O,Q,k);return f.next({type:"state_creation",token:z}),z},T,{subject:f,install:(M)=>jn(M,n),internalRoles:t});return o.families.set(n.key,A),o.defaults.set(n.key,n.default),T}function tA(o,n){if("mutable"in n)return ST(o,n);return jn(o,n)}function xn(o,n,t){let T={key:n.key,type:"readonly_selector_family"},S=o.families.get(n.key);if(S)o.logger.error("\u2757","readonly_selector_family",n.key,`Overwriting an existing ${Hn(S)} "${S.key}" in store "${o.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let f=new s,A=Object.assign((M)=>{let F=l(M),k={key:n.key,subKey:F},W=`${n.key}(${F})`,O=D(o),E=fT(O,{key:W,get:n.get(M)},k);return f.next({type:"state_creation",token:E}),E},T,{internalRoles:t,subject:f,install:(M)=>xn(M,n),default:(M)=>{return n.get(M)({get:(...k)=>Mo(o,...k),find:(k,W)=>ko(o,k,W),seek:(k,W)=>Go(o,k,W),json:(k)=>ro(o,k)})}});return o.families.set(n.key,A),T}function yT(o,n){if("set"in n)return AT(o,n);return xn(o,n)}var rJ={atom_family:"atom",mutable_atom_family:"mutable_atom",selector_family:"selector",readonly_selector_family:"readonly_selector",molecule_family:"molecule"};function Ht(o,n){let t=l(n),T=`${o.key}(${t})`,S=rJ[o.type],f={key:T,type:S};if(S==="molecule")Object.assign(f,{key:n,family:o});else Object.assign(f,{family:{key:o.key,subKey:t}});return Object.assign(f,{counterfeit:!0}),f}function Po(o){let n={key:o.key,type:o.type};if("family"in o)n.family=o.family;return n}var CW=Symbol("provenance");function tf(o,n,t){let T=l(t);try{let S=[],f;if(n==="root")S.push(o.molecules.get('"root"')),f="all";else if(typeof n==="string"&&n.startsWith(BJ)){f="any";let k=l(n),W=o.molecules.get(k);if(!W)throw new Error(`Molecule ${k} not found in store "${o.config.name}"`);S.push(W)}else if(t.startsWith("T$--")){f="all";for(let W of n){let O=l(W),E=o.molecules.get(O);if(!E)throw new Error(`Molecule ${O} not found in store "${o.config.name}"`);S.push(E)}}else{f="any";let W=l(n),O=o.molecules.get(W);if(!O)throw new Error(`Molecule ${W} not found in store "${o.config.name}"`);S.push(O)}let y=new mt(S,t);y._dependsOn=f,o.molecules.set(T,y);for(let k of S)k.below.set(y.stringKey,y);let A={type:"molecule_creation",subType:"modern",key:y.key,provenance:n},M=D(o);if(Fo(M)&&M.transactionMeta.phase==="building")M.transactionMeta.update.updates.push(A);else M.on.moleculeCreationStart.next(A)}catch(S){if(S instanceof Error)o.logger.error("\u274C","molecule",T,"allocation failed:",S.message)}return t}function MT(o,n){let t=l(n),T=o.molecules.get(t);if(!T)throw new Error(`Molecule ${t} not found in store "${o.config.name}"`);for(let F of T.joins.values())F.relations.delete(T.key),F.molecules.delete(T.stringKey);let S;if(T.above.size===1)S=T.above.values().next().value.key;else S=[...T.above.values()].map(({key:F})=>F);let f=[];for(let F of T.tokens.values()){let k=F.family;f.push([k.key,o.valueMap.get(F.key)])}for(let F of T.tokens.values())ao(o,F);for(let F of T.below.values())if(F.dependsOn==="all")MT(o,F.key);else if(F.above.delete(T.stringKey),F.above.size===0)MT(o,F.key);T.below.clear();let y={type:"molecule_disposal",subType:"modern",key:T.key,values:f,provenance:S},A=D(o);if(Fo(A)&&A.transactionMeta.phase==="building")A.transactionMeta.update.updates.push(y);else A.on.moleculeDisposal.next(y);A.molecules.delete(T.stringKey);for(let F of T.above.values())F.below.delete(T.stringKey)}var BJ="T$";function Qt(o){return TA(yo.STORE,o)}function Ft(o){return tA(yo.STORE,o)}function Tf(...o){if(o.length===2)return Mo(yo.STORE,...o);return Mo(yo.STORE,...o)}var Sf=(o)=>(n,t,T,S,...f)=>{console[o](`${n} ${t} "${T}" ${S}`,...f)},CJ={error:Sf("error"),info:Sf("info"),warn:Sf("warn")};class ff{o;n;t;constructor(o,n,t=CJ){this.logLevel=o;this.filter=n;this.logger=t}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)}}function PT(o){return yT(yo.STORE,o)}function FT(o){return yf(o,yo.STORE)}class Mn{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),T=this.relations.get(n);if(t)t.add(n);else t=new Set([n]),this.relations.set(o,t);if(T)T.add(o);else T=new Set([o]),this.relations.set(n,T)}deleteRelation(o,n){let t=this.relations.get(o);if(t){if(t.delete(n),t.size===0)this.relations.delete(o);let T=this.relations.get(n);if(T){if(T.delete(o),T.size===0)this.relations.delete(n)}}}replaceRelationsUnsafely(o,n){this.relations.set(o,new Set(n));for(let t of n){let T=new Set().add(o);this.relations.set(t,T)}}replaceRelationsSafely(o,n){let t=this.relations.get(o),T=this.isAType?.(o)?o:void 0,S=T===void 0?o:void 0;if(t)for(let f of t){T??=f,S??=f;let y=this.relations.get(f);if(y){if(y.size===1)this.relations.delete(f);else y.delete(o);this.contents.delete(this.makeContentKey(T,S))}}this.relations.set(o,new Set(n));for(let f of n){let y=this.relations.get(f);if(y)y.add(o);else y=new Set().add(o),this.relations.set(f,y)}}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,T])=>[t,new Set(T)])),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=(T,S)=>t.has(T,S),this.addRelation=(T,S)=>{t.addRelation(T,S)},this.deleteRelation=(T,S)=>{t.deleteRelation(T,S)},this.replaceRelationsSafely=(T,S)=>{t.replaceRelationsSafely(T,S)},this.replaceRelationsUnsafely=(T,S)=>{t.replaceRelationsUnsafely(T,S)},this.getRelatedKeys=(T)=>t.getRelatedKeys(T),t.getContent)this.getContentInternal=(T)=>{return t.getContent(T)},this.setContent=(T,S)=>{t.setContent(T,S)},this.deleteContent=(T)=>{t.deleteContent(T)};for(let[T,S]of o.relations??[]){let f=this.isAType?.(T)?T:void 0,y=f===void 0?T:void 0;for(let A of S)f??=A,y??=A,this.addRelation(f,y)}for(let[T,S]of o.contents??[])this.setContent(T,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,...n){let t=typeof n[0]==="string"?n[0]:o[this.b],T=n[1]??typeof n[0]==="string"?void 0:n[0];switch(o=typeof o==="string"?o:o[this.a],this.cardinality){case"1:1":{let S=this.getRelatedKey(o);if(S&&S!==t)this.delete(o,S)}case"1:n":{let S=this.getRelatedKey(t);if(S&&S!==o)this.delete(S,t)}}if(T){let S=this.makeContentKey(o,t);this.setContent(S,T)}return this.addRelation(o,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 T=this.getRelatedKeys(n);if(T)for(let S of T)this.delete(S,n)}if(typeof t==="string"&&n===void 0){let T=this.getRelatedKeys(t);if(T)for(let S of T)this.delete(t,S)}if(typeof t==="string"&&typeof n==="string"){this.deleteRelation(t,n);let T=this.makeContentKey(t,n);this.deleteContent(T)}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((T)=>`"${T}"`).join(", ")}). Only one related key was expected.`);let t;for(let T of n){t=T;break}return t}}replaceRelations(o,n,t){let T=!Array.isArray(n),S=T?Object.keys(n):n;if(t?.reckless)this.replaceRelationsUnsafely(o,S);else this.replaceRelationsSafely(o,S);if(T)for(let f of S){let y=this.makeContentKey(o,f),A=n[f];this.setContent(y,A)}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 T=this.getRelatedKeys(n);if(T)return[...T].map((S)=>{return[S,this.getContent(n,S)]})}if(n===void 0&&t!==void 0){let T=this.getRelatedKeys(t);if(T)return[...T].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)}}function Bo(o){return"epoch"in o.transactionMeta}function Fo(o){return"phase"in o.transactionMeta}var fA=(o)=>{let n=D(o);if(!Fo(n)){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",n.transactionMeta.update.key,"Aborting transaction"),n.parent.child=null};var LJ=(o)=>o[0].toUpperCase()+o.slice(1);function Hn(o){return o.type.split("_").map(LJ).join(" ")}class Tn extends Error{constructor(...o){let n=o[0],t=o.length===2?o[1]:o[2];if(o.length===2)super(`${Hn(n)} ${l(n.key)} not found in store "${t.config.name}".`);else{let T=o[1];super(`${Hn(n)} "${n.key}" member ${l(T)} not found in store "${t.config.name}".`)}}}function dn(o,n,t){return(...T)=>{let S=d(o,t);if(S)return S.run(T,n);throw new Tn(o,t)}}var eT=(o)=>(n)=>o instanceof Function?o(n):o;var un=(o,n)=>{if(n.valueMap.has(o.key))return n.logger.info("\uD83D\uDCD6",o.type,o.key,"reading cached value"),yA(o,n);if(o.type==="selector"||o.type==="readonly_selector")return n.logger.info("\uD83E\uDDEE",o.type,o.key,"computing value"),o.get();let t=o.default instanceof Function?o.default():o.default;return n.logger.info("\uD83D\uDC81","atom",o.key,"could not find cached value; using default",t),o.default instanceof Function?o.default():o.default};var AA=(o,n)=>{if(o.operation.open){let t=performance.now();return o.logger.info("\u2757",n.type,n.key,`deferring setState at T-${t} until setState for "${o.operation.token.key}" is done`),t}o.operation={open:!0,done:new Set,prev:new Map,time:Date.now(),token:n},o.logger.info("\u2B55",n.type,n.key,`operation start in store "${o.config.name}"${!Fo(o)?"":` ${o.transactionMeta.phase} "${o.transactionMeta.update.key}"`}`)},MA=(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)},FA=(o,n)=>{if(!o.operation.open)return o.logger.error("\uD83D\uDC1E","unknown",n,"isDone called outside of an operation. This is probably a bug in AtomIO."),!0;return o.operation.done.has(n)},Dt=(o,n)=>{if(!o.operation.open){o.logger.error("\uD83D\uDC1E","unknown",n,"markDone called outside of an operation. This is probably a bug in AtomIO.");return}o.operation.done.add(n)};var kA=(o,n,t)=>{switch(o.type){case"mutable_atom":t.logger.info("\uD83D\uDCE2",o.type,o.key,"is now (",n.newValue,") subscribers:",o.subject.subscribers);break;default:t.logger.info("\uD83D\uDCE2",o.type,o.key,"went (",n.oldValue,"->",n.newValue,") subscribers:",o.subject.subscribers)}o.subject.next(n)};var Af=(o,n)=>{let t=D(n),T=t.selectorAtoms.getRelatedKeys(o.key);if(t.logger.info("\uD83E\uDDF9",o.type,o.key,T?`evicting ${T.size} states downstream:`:"no downstream states",T??"to evict"),T){if(t.operation.open)t.logger.info("\uD83E\uDDF9",o.type,o.key,`[ ${[...t.operation.done].join(", ")} ] already done`);for(let S of T){if(FA(t,S))continue;$A(S,t),Dt(t,S)}}};function IJ(o,n){if(RA(n.newValue))return!1;if(o.includes("\uD83D\uDD0D"))return!1;return!0}var JA=(o,n,t)=>{let{key:T}=o,S=D(t);if(!Fo(S)||S.transactionMeta.phase!=="building"){t.logger.error("\uD83D\uDC1E","atom",T,"stowUpdate called outside of a transaction. This is probably a bug.");return}if(!IJ(T,n))return;let y={type:"atom_update",key:T,...n};if(o.family)y.family=o.family;S.transactionMeta.update.updates.push(y),t.logger.info("\uD83D\uDCC1","atom",T,"stowed (",n.oldValue,"->",n.newValue,")")};var WA=(o,n,t)=>{let T=un(o,t),S=T;if(o.type==="mutable_atom"&&Fo(t)){let{parent:y}=t;S=kT(o,y,t)}if(S=eT(n)(S),t.logger.info("\uD83D\uDCDD","atom",o.key,"set to",S),S=Rn(o.key,S,o.subject,t),OA(o.key,t))_A(o.key,t);Dt(t,o.key),Af(o,t);let f={oldValue:T,newValue:S};if(Bo(t))kA(o,f,t);else if(t.parent){if(t.on.transactionApplying.state===null)JA(o,f,t);else if(o.key.startsWith("*")){let y=o.key.slice(1),A=t.atoms.get(y),M=t.valueMap.get(y);if(A.type==="mutable_atom"&&Fo(t)){let{parent:k}=t;M=kT(A,k,t)}if(M.do(f.newValue)===null)Af(A,t)}}};var lT=(o,n,t)=>{switch(o.type){case"atom":case"mutable_atom":WA(o,n,t);break;case"selector":o.set(n);break}};function gT(o,n){if(n.family){let t=o.families.get(n.family.key);if(t)return t}}function Qo(o,...n){let t,T,S,f;if(n.length===2){if(t=n[0],f=n[1],T=gT(o,t)??null,T)S=t.family?bo(t.family.subKey):null,t=ko(o,T,S)}else T=n[0],S=n[1],f=n[2],t=ko(o,T,S);if("counterfeit"in t){let M=o.disposalTraces.buffer.find((F)=>F?.key===t.key);o.logger.error("\u274C",t.type,t.key,`could not be set because it was not found in the store "${o.config.name}".`,M?`This state was previously disposed:\n${M.trace}`:"No previous disposal trace was found.");return}let y=AA(o,t);if(y){let M=o.on.operationClose.subscribe(`waiting to set "${t.key}" at T-${y}`,()=>{M(),o.logger.info("\uD83D\uDFE2",t.type,t.key,`resuming deferred setState from T-${y}`),Qo(o,t,f)});return}let A=d(t,o);lT(A,f,o),MA(o)}function dT(o,n,t){let{key:T,newValue:S,oldValue:f}=n,y=o==="newValue"?S:f,A={key:T,type:"atom"};if(n.family)Object.assign(A,{family:n.family});Qo(t,A,y)}function wA(o,n){let t=new s,T={type:"molecule_family",key:n.key,dependsOn:n.dependsOn??"all"},S={...T,subject:t,new:n.new};return o.moleculeFamilies.set(n.key,S),T}function mn(o,n,t){let T=vn(t,n,o.key);o.tokens.set(T.key,T);let S=Fo(t)&&t.transactionMeta.phase==="building",f=t.moleculeInProgress===o.key;if(!S&&!f)o.subject.next({type:"state_creation",token:T});return T}class No extends Set{mode="record";subject=new s;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:${l(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:${l(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 T of this.transactionUpdates)this.doStep(T);this.cacheUpdateNumber++,this.emit(`tx:${this.transactionUpdates.join(";")}`)}}catch(t){throw console.error("Failed to apply transaction to SetRTX:",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),T=o.substring(n+1);switch(t){case"add":this.add(JSON.parse(T));break;case"clear":this.clear();break;case"del":this.delete(JSON.parse(T));break;case"tx":for(let S of T.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)),T=t-this.cacheUpdateNumber;if(T>0){if(T===1){this.mode="playback";let f=o.substring(n+1);return this.doStep(f),this.mode="record",this.cacheUpdateNumber=t,null}return this.cacheUpdateNumber+1}if(Math.abs(T)<this.cacheLimit){let f=this.cacheIdx+T;if(this.cache[f]===o)return null;this.mode="playback";let A=!1;while(!A){this.cacheIdx%=this.cacheLimit;let F=this.cache[this.cacheIdx];if(this.cacheIdx--,!F)return"OUT_OF_RANGE";this.undo(F),A=this.cacheIdx===f-1}let M=o.substring(n+1);return this.doStep(M),this.mode="record",this.cacheUpdateNumber=t,null}return"OUT_OF_RANGE"}undoStep(o){let n=o.indexOf(":"),t=o.substring(0,n),T=o.substring(n+1);switch(t){case"add":this.delete(JSON.parse(T));break;case"del":this.add(JSON.parse(T));break;case"clear":{let S=JSON.parse(T);for(let f of S)this.add(f);break}case"tx":{let S=T.split(";");for(let f=S.length-1;f>=0;f--)this.undoStep(S[f])}}}undo(o){let n=o.indexOf("=");if(Number(o.substring(0,n))===this.cacheUpdateNumber){this.mode="playback";let T=o.substring(n+1);return this.undoStep(T),this.mode="record",this.cacheUpdateNumber--,null}return this.cacheUpdateNumber}}function Ho(o){return o[0].toUpperCase()+o.slice(1)}class kf{options;defaultContent;toolkit;retrieve;molecules=new Map;relations;states;core;transact(o,n){let t=this.toolkit;this.toolkit=o,n(this),this.toolkit=t}store;alternates;[Symbol.dispose](){this.alternates.delete(this.store.config.name)}in(o){let n=o.config.name,t=this.alternates.get(n);if(t)return t;let T=new kf(this.options,this.defaultContent,o);return this.alternates.set(n,T),T.alternates=this.alternates,T}constructor(o,n,t=yo.STORE){this.store=t,this.options=o,this.defaultContent=n,this.alternates=new Map,this.alternates.set(t.config.name,this),this.store.miscResources.set(`join:${o.key}`,this),this.retrieve=(Y,K)=>{let U=this.toolkit.seek(Y,K);if(U)return U;let p=this.store.molecules.get(l(K));if(p){let b=d(Y,t);return mn(p,b,t)}if(t.config.lifespan==="immortal")throw new Tn(Y,K,t);return vn(t,Y,K)},this.toolkit={get:(...Y)=>Mo(t,...Y),set:(...Y)=>{Qo(t,...Y)},find:this.retrieve,seek:(...Y)=>Go(t,...Y),json:(Y)=>ro(t,Y),dispose:(...Y)=>{ao(t,...Y)}};let T=o.between[0],S=o.between[1],f=ST(t,{key:`${o.key}/relatedKeys`,default:()=>new No,mutable:!0,fromJson:(Y)=>No.fromJSON(Y),toJson:(Y)=>Y.toJSON()},["join","relations"]);this.core={findRelatedKeysState:f};let y=({get:Y},K)=>Y(this.retrieve(f,K)),A=(Y,K,U)=>{let{set:p}=Y,b=this.retrieve(f,K),w=this.retrieve(f,U);p(b,(v)=>v.add(U)),p(w,(v)=>v.add(K))},M=(Y,K,U)=>{let{set:p}=Y,b=this.retrieve(f,K),w=this.retrieve(f,U),v,j;p(b,(a)=>{if(a.delete(U),a.size===0)v=`"${K}"`;return a}),p(w,(a)=>{if(a.delete(K),a.size===0)j=`"${U}"`;return a})},F=(Y,K,U)=>{let{get:p,set:b}=Y,w=this.retrieve(f,K),v=p(w);for(let j of v){if(U.includes(j))continue;let oo=this.retrieve(f,j);b(oo,(no)=>{return no.delete(K),no})}b(w,(j)=>{return j.transaction((a)=>{a.clear();for(let oo of U){let no=y(Y,oo),_o=no.has(K);if(this.relations.cardinality==="1:n"){let An=[];for(let H of no){if(H===K)continue;let i=y(Y,H);if(i.delete(oo),i.size===0)An.push(H)}if(!_o&&no.size>0)no.clear();for(let H of An){let i=[oo,H].sort(),fo=`"${i[0]}:${i[1]}"`;this.molecules.delete(fo)}}if(!_o)no.add(K);a.add(oo)}return!0}),j})},k=(Y,K,U)=>{let{set:p}=Y,b=this.retrieve(f,K);p(b,(w)=>{return w.transaction((v)=>{for(let j of U)v.add(j);return!0}),w});for(let w of U){let v=this.retrieve(f,w);p(v,(j)=>{return j.add(K),j})}return!0},W=(Y,K,U)=>{let p=y(Y,K);return U?p.has(U):p.size>0},O={getRelatedKeys:(Y)=>y(this.toolkit,Y),addRelation:(Y,K)=>{A(this.toolkit,Y,K)},deleteRelation:(Y,K)=>{M(this.toolkit,Y,K)},replaceRelationsSafely:(Y,K)=>{F(this.toolkit,Y,K)},replaceRelationsUnsafely:(Y,K)=>{k(this.toolkit,Y,K)},has:(Y,K)=>W(this.toolkit,Y,K)},E,Q,z;if(n){Q=jn(t,{key:`${o.key}/content`,default:n},["join","content"]),z=wA(t,{key:`${o.key}/content-molecules`,new:class b{v;constructor(w,v){this.key=v}}});let Y=({get:b},w)=>b(this.retrieve(Q,w)),K=({set:b},w,v)=>{b(this.retrieve(Q,w),v)},U=(b,w)=>{let v=t.molecules.get(`"${w}"`);if(v)this.toolkit.dispose(v),this.molecules.delete(`"${w}"`)};E=Object.assign(O,{getContent:(b)=>{return Y(this.toolkit,b)},setContent:(b,w)=>{K(this.toolkit,b,w)},deleteContent:(b)=>{U(this.toolkit,b)}})}else E=O;let G=new Mn(o,{externalStore:E,isAType:o.isAType,isBType:o.isBType,makeContentKey:(...Y)=>{let K=Y.sort(),U=`${K[0]}:${K[1]}`,[p,b]=K.map((w)=>this.molecules.get(l(w)));if(t.config.lifespan==="immortal"&&p&&b){let w=D(t),v=pn(w,[p,b],z,U);this.molecules.set(`"${U}"`,d(v,w))}return U}}),V=()=>xn(t,{key:`${o.key}/singleRelatedKey`,get:(Y)=>({get:K})=>{let U=this.retrieve(f,Y),p=K(U);for(let b of p)return b;return null}},["join","keys"]),x=()=>{return xn(t,{key:`${o.key}/multipleRelatedKeys`,get:(Y)=>({get:K})=>{let U=Ff(f,t),p=this.retrieve(U,Y);return K(p).members}},["join","keys"])},c=()=>xn(t,{key:`${o.key}/singleRelatedEntry`,get:(Y)=>({get:K})=>{let U=this.retrieve(f,Y),p=K(U);for(let b of p){let w=G.isAType?.(Y)?Y:void 0,v=w===void 0?Y:void 0;w??=b,v??=b;let j=G.makeContentKey(w,v),a=this.retrieve(Q,j),oo=K(a);return[b,oo]}return null}},["join","entries"]),P=()=>xn(t,{key:`${o.key}/multipleRelatedEntries`,get:(Y)=>({get:K})=>{let U=Ff(f,t),p=this.retrieve(U,Y);return K(p).members.map((w)=>{let v=G.isAType?.(Y)?Y:void 0,j=v===void 0?Y:void 0;v??=w,j??=w;let a=G.makeContentKey(v,j),oo=this.retrieve(Q,a),no=K(oo);return[w,no]})}},["join","entries"]);switch(o.cardinality){case"1:1":{let Y=V(),K=`${T}KeyOf${Ho(S)}`,U=`${S}KeyOf${Ho(T)}`,p={[K]:Y,[U]:Y},b;if(n){let w=c(),v=`${T}EntryOf${Ho(S)}`,j=`${S}EntryOf${Ho(T)}`,a={[v]:w,[j]:w};b=Object.assign(p,a)}else b=p;this.relations=G,this.states=b;break}case"1:n":{let Y=V(),K=x(),U=`${T}KeyOf${Ho(S)}`,p=`${S}KeysOf${Ho(T)}`,b={[U]:Y,[p]:K},w;if(n){let v=c(),j=P(),a=`${T}EntryOf${Ho(S)}`,oo=`${S}EntriesOf${Ho(T)}`,no={[a]:v,[oo]:j};w=Object.assign(b,no)}else w=b;this.relations=G,this.states=w;break}default:{let Y=x(),K=`${T}KeysOf${Ho(S)}`,U=`${S}KeysOf${Ho(T)}`,p={[K]:Y,[U]:Y},b;if(n){let w=P(),v=`${T}EntriesOf${Ho(S)}`,j=`${S}EntriesOf${Ho(T)}`,a={[v]:w,[j]:w};b=Object.assign(p,a)}else b=p;this.relations=G,this.states=b}}}}function uT(o,n,t=yo.STORE){return Mf(t).set(o.key,new kf(o,n,t)),{key:o.key,type:"join",a:o.between[0],b:o.between[1],cardinality:o.cardinality}}function Mf(o){if("joins"in o&&o.joins instanceof Map)return o.joins;let n=new Map;return o.joins=n,n}function $T(o,n){let t=Mf(n),T=t.get(o.key);if(T===void 0){if(T=Mf(yo.STORE).get(o.key)?.in(n),T===void 0)throw new Error(`Join "${o.key}" not found in store "${n.config.name}"`);t.set(o.key,T)}return T}function aT(o,n,t){let T=$T(o,t),S;switch(o.cardinality){case"1:1":{let f=`${o.a}KeyOf${Ho(o.b)}`,y=`${o.b}KeyOf${Ho(o.a)}`;S={get[f](){let M=T.states[f];return T.retrieve(M,n)},get[y](){let M=T.states[y];return T.retrieve(M,n)}};let A=`${o.a}EntryOf${Ho(o.b)}`;if(A in T.states){let M=`${o.b}EntryOf${Ho(o.a)}`;Object.assign(S,{get[A](){let F=T.states[A];return T.retrieve(F,n)},get[M](){let F=T.states[M];return T.retrieve(F,n)}})}break}case"1:n":{let f=`${o.a}KeyOf${Ho(o.b)}`,y=`${o.b}KeysOf${Ho(o.a)}`;S={get[f](){let M=T.states[f];return T.retrieve(M,n)},get[y](){let M=T.states[y];return T.retrieve(M,n)}};let A=`${o.a}EntryOf${Ho(o.b)}`;if(A in T.states){let M=`${o.b}EntriesOf${Ho(o.a)}`;Object.assign(S,{get[A](){let F=T.states[A];return T.retrieve(F,n)},get[M](){let F=T.states[M];return T.retrieve(F,n)}})}break}case"n:n":{let f=`${o.a}KeysOf${Ho(o.b)}`,y=`${o.b}KeysOf${Ho(o.a)}`;S={get[f](){let M=T.states[f];return T.retrieve(M,n)},get[y](){let M=T.states[y];return T.retrieve(M,n)}};let A=`${o.a}EntriesOf${Ho(o.b)}`;if(A in T.states){let M=`${o.b}EntriesOf${Ho(o.a)}`;Object.assign(S,{get[A](){let F=T.states[A];return T.retrieve(F,n)},get[M](){let F=T.states[M];return T.retrieve(F,n)}})}}}return S}function KA(o,n){return aT(o,n,yo.STORE)}function sT(o,n,t){let T=$T(o,t),S=D(t);if(Fo(S)){let{toolkit:f}=S.transactionMeta;T.transact(f,({relations:y})=>{n(y)})}else n(T.relations)}function jJ(o,n){return $T(o,n).core.findRelatedKeysState}function XA(o){return jJ(o,yo.STORE)}function oS(o){return{store:o}}function Mo(o,...n){let t,T,S;if(n.length===1){if(t=n[0],t.type!=="molecule"){if(T=gT(o,t)??null,T)S=t.family?bo(t.family.subKey):null,t=ko(o,T,S)}}else{T=n[0],S=n[1];let f;if(T.type==="molecule_family")f=Go(o,T,S)??Ht(T,S);else f=ko(o,T,S);t=f}if("counterfeit"in t&&"family"in t){T=t.type==="molecule"?d(t.family,o):o.families.get(t.family.key);let f=t.type==="molecule"?t.key:t.family.subKey,y=o.disposalTraces.buffer.find((A)=>A?.key===t.key);switch(o.logger.error("\u274C",t.type,t.key,`could not be retrieved because it was not found in the store "${o.config.name}".`,y?`This state was previously disposed:\n${y.trace}`:"No previous disposal trace was found."),T.type){case"atom_family":case"mutable_atom_family":return o.defaults.get(T.key);case"selector_family":case"readonly_selector_family":{if(o.defaults.has(T.key))return o.defaults.get(t.family.key);let A=d(T,o).default(f);return o.defaults.set(T.key,A),A}case"molecule_family":throw new Tn(T,f,o)}}switch(t.type){case"atom":case"mutable_atom":case"selector":case"readonly_selector":return un(d(t,o),o);case"molecule":return d(t,o).instance}}class mt{n;type="molecule";stringKey;family;_dependsOn;get dependsOn(){if(this.family)return this.family.dependsOn;return this._dependsOn}subject=new s;tokens=new Map;above=new Map;below=new Map;joins=new Map;instance;constructor(o,n,t){this.key=n;if(this.stringKey=l(n),t)this.family=t,this._dependsOn=t.dependsOn;if(o)for(let T of o)this.above.set(T.stringKey,T)}}function EA(o){return o[0].toUpperCase()+o.slice(1)}function pn(o,n,t,T,...S){let f=nA(o),y=D(o),A=l(T);y.moleculeInProgress=A;let M=Array.isArray(n)?n:[n],F=M.map((G)=>{if(G instanceof mt)return G;let V=l(G.key),x=o.molecules.get(V);if(!x)throw new Error(`Molecule ${V} not found in store "${o.config.name}"`);return x}),k=new mt(F,T,t);y.molecules.set(A,k);for(let G of F)G.below.set(k.stringKey,k);let W={get:(...G)=>Mo(D(f),...G),set:(...G)=>{Qo(D(f),...G)},seek:(G,V)=>Go(D(f),G,V),json:(G)=>ro(D(f),G),run:(G,V=zt())=>dn(G,V,D(o)),make:(G,V,x,...c)=>pn(D(f),G,V,x,...c),dispose:(G)=>{ao(D(f),G)},env:()=>oS(D(f)),bond:(G,V)=>{if(G.type==="join"){let{as:x}=V,c=$T(G,f);c.molecules.set(A,k),k.joins.set(G.key,c);let P=O.subject.subscribe(`join:${G.key}-${A}`,(w)=>{if(w.type==="molecule_disposal"){if(l(w.token.key)===A)P(),c.molecules.delete(A)}});if(x===null)return;let Y=G.a===x?G.b:G.a,K=KA(G,T),U=K[`${Y}KeysOf${EA(x)}`],p=K[`${Y}EntriesOf${EA(x)}`],b={relatedKeys:U};if(p)b=Object.assign(b,{relatedEntries:p});return b}return mn(k,d(G,f),D(f))},claim:(G,V)=>{let{exclusive:x}=V,c=D(o).molecules.get(l(G.key));if(c)if(x){for(let P of c.above.values())P.below.delete(c.stringKey);c.above.clear(),c.above.set(k.stringKey,k),k.below.set(c.stringKey,c)}else c.above.set(k.stringKey,k),k.below.set(c.stringKey,c)},spawn:(G,V,...x)=>pn(D(o),[k],d(G,o),V,...x)},O=d(t,o),E=O.new;k.instance=new E(W,T,...S);let Q={type:"molecule",key:T,family:t},z={type:"molecule_creation",subType:"classic",token:Q,family:t,context:M,params:S};if(Bo(y))O.subject.next(z);else if(Fo(y)&&y.on.transactionApplying.state===null)y.transactionMeta.update.updates.push(z);return y.moleculeInProgress=null,Q}function $f(o,n,t){switch(n){case"newValue":{YA(o,t);break}case"oldValue":{ao(t,o.token);break}}}function Jf(o,n,t){switch(n){case"newValue":{ao(t,o.token);break}case"oldValue":{YA(o,t),t.valueMap.set(o.token.key,o.value);break}}}function YA(o,n){let{family:t}=o.token;if(t){let T=n.families.get(t.key);if(T)ko(n,T,bo(t.subKey))}}function Rf(o,n,t){switch(n){case"newValue":switch(o.subType){case"classic":pn(t,o.context,o.family,o.token.key,...o.params);break;case"modern":tf(t,o.provenance,o.key);break}break;case"oldValue":switch(o.subType){case"classic":ao(t,o.token);break;case"modern":MT(t,o.key);break}break}}function Wf(o,n,t){switch(n){case"newValue":switch(o.subType){case"classic":ao(t,o.token);break;case"modern":MT(t,o.key);break}break;case"oldValue":switch(o.subType){case"classic":{let T=pn(t,o.context,o.family,o.token.key);for(let[S,f]of o.values){let y=`${S}(${l(T.key)})`,A=d(T,t),M=A.tokens.has(y),F=t.families.get(S);if(F&&!M)mn(A,F,t);t.valueMap.set(y,f)}}break;case"modern":{tf(t,o.provenance,o.key);for(let[T,S]of o.values){let f=t.families.get(T);if(f){ko(t,f,o.key);let y=`${T}(${l(o.key)})`;t.valueMap.set(y,S)}}}}break}}function nS(o,n,t){let T=o==="newValue"?n.updates:[...n.updates].reverse();for(let S of T)switch(S.type){case"atom_update":case"selector_update":dT(o,S,t);break;case"state_creation":$f(S,o,t);break;case"state_disposal":Jf(S,o,t);break;case"molecule_creation":Rf(S,o,t);break;case"molecule_disposal":Wf(S,o,t);break;case"transaction_update":nS(o,S,t);break}}function GA(o,n,t){if(Bo(t)&&o)t.transactionMeta.epoch.set(o,n)}function zA(o,n,t){if(!Bo(t))return;let S=t.transactionMeta.actionContinuities.getRelatedKey(o);if(S!==void 0)t.transactionMeta.epoch.set(S,n)}var HA=(o,n)=>{let t=D(n),{parent:T}=t;if(T===null||!Fo(t)||t.transactionMeta?.phase!=="building"){n.logger.warn("\uD83D\uDC1E","transaction","???","applyTransaction called outside of a transaction. This is probably a bug in AtomIO.");return}t.transactionMeta.phase="applying",t.transactionMeta.update.output=o,T.child=null,T.on.transactionApplying.next(t.transactionMeta);let{updates:S}=t.transactionMeta.update;if(n.logger.info("\uD83D\uDEC4","transaction",t.transactionMeta.update.key,`Applying transaction with ${S.length} updates:`,S),nS("newValue",t.transactionMeta.update,T),Bo(T))zA(t.transactionMeta.update.key,t.transactionMeta.update.epoch,T),d({key:t.transactionMeta.update.key,type:"transaction"},n)?.subject.next(t.transactionMeta.update),n.logger.info("\uD83D\uDEEC","transaction",t.transactionMeta.update.key,"Finished applying transaction.");else if(Fo(T))T.transactionMeta.update.updates.push(t.transactionMeta.update);T.on.transactionApplying.next(null)};function mA(o,n,t){if(!Bo(t))return;let{epoch:S,actionContinuities:f}=t.transactionMeta;if(f.set(o,n),!S.has(o))S.set(o,-1)}class Wn extends Map{o;deleted=new Set;constructor(o){super();this.source=o}get(o){if(super.has(o))return super.get(o);if(!this.deleted.has(o)&&this.source.has(o))return this.source.get(o);return}set(o,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 QA=(o,n,t,T)=>{let S=D(t),f={parent:S,child:null,on:S.on,loggers:S.loggers,logger:S.logger,config:S.config,atoms:new Wn(S.atoms),atomsThatAreDefault:new Set(S.atomsThatAreDefault),families:new Wn(S.families),operation:{open:!1},readonlySelectors:new Wn(S.readonlySelectors),timelines:new Wn(S.timelines),timelineTopics:new Mn(S.timelineTopics.toJSON()),trackers:new Map,transactions:new Wn(S.transactions),selectorAtoms:new Mn(S.selectorAtoms.toJSON()),selectorGraph:new Mn(S.selectorGraph.toJSON(),{makeContentKey:(...F)=>F.sort().join(":")}),selectors:new Wn(S.selectors),valueMap:new Wn(S.valueMap),defaults:S.defaults,disposalTraces:t.disposalTraces.copy(),molecules:new Wn(S.molecules),moleculeFamilies:new Wn(S.moleculeFamilies),moleculeInProgress:S.moleculeInProgress,miscResources:new Wn(S.miscResources)},y=DA(o,t),A={phase:"building",update:{type:"transaction_update",key:o,id:T,epoch:y===void 0?Number.NaN:y+1,updates:[],params:n,output:void 0},toolkit:{get:(...F)=>Mo(M,...F),set:(...F)=>{Qo(M,...F)},run:(F,k=zt())=>dn(F,k,M),find:(F,k)=>ko(M,F,k),seek:(F,k)=>Go(M,F,k),json:(F)=>ro(M,F),make:(F,k,W,...O)=>pn(M,F,k,W,...O),dispose:(...F)=>{ao(M,...F)},env:()=>oS(M)}},M=Object.assign(f,{transactionMeta:A});return S.child=M,t.logger.info("\uD83D\uDEEB","transaction",o,"Building transaction with params:",n),M};function yf(o,n){let t={key:o.key,type:"transaction",run:(f,y)=>{let A=QA(o.key,f,n,y);try{let M=D(n),{toolkit:F}=A.transactionMeta,k=o.do(F,...f);return HA(k,M),k}catch(M){throw fA(T),n.logger.warn("\uD83D\uDCA5","transaction",o.key,"caught:",M),M}},install:(f)=>yf(o,f),subject:new s},T=D(n);T.transactions.set(t.key,t);let S=Po(t);return n.on.transactionCreation.next(S),S}function DA(o,n){let t=Bo(n),T=t?n.transactionMeta.actionContinuities.getRelatedKey(o):void 0;return t&&T!==void 0?n.transactionMeta.epoch.get(T):void 0}class tS{_buffer;_index=0;constructor(o){let n;if(typeof o==="number")n=o;else n=o.length;this._buffer=Array.from({length:n})}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 tS([...this._buffer]);return o._index=this._index,o}}class UA{parent=null;child=null;valueMap=new Map;defaults=new Map;atoms=new Map;selectors=new Map;readonlySelectors=new Map;atomsThatAreDefault=new Set;selectorAtoms=new Mn({between:["selectorKey","atomKey"],cardinality:"n:n"});selectorGraph=new Mn({between:["upstreamSelectorKey","downstreamSelectorKey"],cardinality:"n:n"},{makeContentKey:(...o)=>o.sort().join(":")});trackers=new Map;families=new Map;transactions=new Map;transactionMeta={epoch:new Map,actionContinuities:new Mn({between:["continuity","action"],cardinality:"1:n"})};timelines=new Map;timelineTopics=new Mn({between:["timelineKey","topicKey"],cardinality:"1:n"});disposalTraces=new tS(100);molecules=new Map;moleculeFamilies=new Map;moleculeInProgress=null;miscResources=new Map;on={atomCreation:new s,atomDisposal:new s,selectorCreation:new s,selectorDisposal:new s,timelineCreation:new s,transactionCreation:new s,transactionApplying:new nf(null),operationClose:new s,moleculeCreationStart:new s,moleculeCreationDone:new s,moleculeDisposal:new s};operation={open:!1};config={name:"IMPLICIT_STORE",lifespan:"ephemeral"};loggers=[new ff("warn",(o,n,t)=>!t.includes("\uD83D\uDD0D"))];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},Bo(n))this.transactionMeta={epoch:new Map(n?.transactionMeta.epoch),actionContinuities:new Mn(n?.transactionMeta.actionContinuities.toJSON())};for(let[,T]of n.families){if(T.internalRoles?.includes("mutable")||T.internalRoles?.includes("join"))continue;T.install(this)}let t=new Set;for(let[,T]of n.atoms){if(t.has(T.key))continue;if(T.install(this),T.type==="mutable_atom"){let S=ro(n,T),f=qn(T);t.add(S.key),t.add(f.key)}}for(let[,T]of n.readonlySelectors)T.install(this);for(let[,T]of n.selectors){if(t.has(T.key))continue;T.install(this)}for(let[,T]of n.transactions)T.install(this);for(let[,T]of n.timelines)T.install(this)}}}var yo={get STORE(){if(!globalThis.ATOM_IO_IMPLICIT_STORE)globalThis.ATOM_IO_IMPLICIT_STORE=new UA({name:"IMPLICIT_STORE",lifespan:"ephemeral"});return globalThis.ATOM_IO_IMPLICIT_STORE}};function d(o,n){let t,T=n;while(T!==null){switch(o.type){case"atom":case"mutable_atom":t=T.atoms.get(o.key);break;case"selector":t=T.selectors.get(o.key);break;case"readonly_selector":t=T.readonlySelectors.get(o.key);break;case"atom_family":case"mutable_atom_family":case"selector_family":case"readonly_selector_family":t=T.families.get(o.key);break;case"timeline":t=T.timelines.get(o.key);break;case"transaction":t=T.transactions.get(o.key);break;case"molecule":t=T.molecules.get(l(o.key));break;case"molecule_family":t=T.moleculeFamilies.get(o.key);break}if(t)return t;T=T.child}throw new Tn(o,n)}function TS(o,n){let t;t=d(o,n);let{family:T}=o;for(let y of t.joins.values())y.relations.delete(t.key),y.molecules.delete(t.stringKey);let S=[];for(let y of t.above.values())S.push(Po(y));let f=[];for(let y of t.tokens.values()){let A=y.family;f.push([A.key,n.valueMap.get(y.key)])}if(T){let y=d(T,n),A={type:"molecule_disposal",subType:"classic",token:o,family:T,context:S,values:f};if(o.family)A.family=o.family;for(let F of t.tokens.values())ao(n,F);for(let F of t.below.values())if(F.dependsOn==="all")TS(F,n);else if(F.above.delete(t.stringKey),F.above.size===0)TS(F,n);if(t.below.clear(),Fo(n)&&n.transactionMeta.phase==="building")n.transactionMeta.update.updates.push(A);else y.subject.next(A);n.molecules.delete(t.stringKey)}for(let y of t.above.values())y.below.delete(t.stringKey)}function vn(o,n,t){let T=o.families.get(n.key);if(T===void 0)throw new Tn(n,o);let S=T(t),f=D(o);if(S.family&&f.moleculeInProgress===null){if(Bo(f))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(Fo(f)&&f.on.transactionApplying.state===null)f.transactionMeta.update.updates.push({type:"state_creation",token:S})}return S}function Go(o,n,t){let T=l(t),S=`${n.key}(${T})`,f=D(o),y;switch(n.type){case"atom_family":case"mutable_atom_family":y=f.atoms.get(S);break;case"selector_family":y=f.selectors.get(S);break;case"readonly_selector_family":y=f.readonlySelectors.get(S);break;case"molecule_family":y=f.molecules.get(l(t))}if(y)return Po(y);return y}function ko(o,n,t){let T=Go(o,n,t);if(T)return T;let S=o.molecules.get(l(t));if(S)return mn(S,n,o);if(o.config.lifespan==="immortal"){let f=Ht(n,t);return o.logger.error("\u274C",f.type,f.key,`was not found in store "${o.config.name}"; returned a counterfeit token.`),f}return T=vn(o,n,t),T}function ao(o,...n){let t,T;if(n.length===1)t=n[0],T=t.key;else{let f=n[0],y=n[1];t=f.type==="molecule_family"?Go(o,f,y)??Ht(f,y):ko(o,f,y)}try{d(t,o)}catch(f){let y=o.disposalTraces.buffer.find((A)=>A?.key===t.key);o.logger.error("\u274C",t.type,t.key,`could not be disposed because it was not found in the store "${o.config.name}".`,y?`\n This state was most recently disposed\n${y.trace}`:"No previous disposal trace was found.");return}switch(t.type){case"atom":case"mutable_atom":Of(t,o);break;case"selector":case"readonly_selector":VA(t,o);break;case"molecule":TS(t,o);break}let{stack:S}=new Error;if(S){let f=S?.split("\n")?.slice(3)?.join("\n");o.disposalTraces.add({key:t.key,trace:f})}}var SS=(o,n)=>D(n).atoms.has(o),bJ=(o,n)=>D(n).selectors.has(o),NJ=(o,n)=>D(n).readonlySelectors.has(o),rA=(o,n)=>SS(o,n)||bJ(o,n)||NJ(o,n);var fS=(o,n)=>{return D(n).selectorGraph.getRelationEntries({downstreamSelectorKey:o}).filter(([T,{source:S}])=>S!==o).map(([T,{source:S}])=>S).filter((T)=>rA(T,n))};var _f=(o,n,t)=>{let T=[],S=fS(o,t);while(S.length>0){let f=S.shift();if(n.has(f))continue;if(n.add(f),!SS(f,t))S.push(...fS(f,t));else if(!T.includes(f))T.push(f)}return T},BA=(o,n)=>{let t=o.key,T=fS(t,n),S=new Set;return T.flatMap((f)=>SS(f,n)?f:_f(f,S,n))};var CA=(o,n,t,T)=>{let S=D(T);if(n.type==="atom"||n.type==="mutable_atom")S.selectorAtoms.set({selectorKey:o,atomKey:n.key}),T.logger.info("\uD83D\uDD0D","selector",o,`discovers root atom "${n.key}"`);else{let f=_f(n.key,t,T);T.logger.info("\uD83D\uDD0D","selector",o,`discovers root atoms: [ ${f.map((y)=>`"${y}"`).join(", ")} ]`);for(let y of f)S.selectorAtoms=S.selectorAtoms.set({selectorKey:o,atomKey:y})}t.add(n.key)};var yS=(o,n,t)=>({get:(...T)=>{let S=D(t),f;if(T.length===2){let[M,F]=T;switch(M.type){case"molecule_family":return Mo(t,M,F);default:if(t.config.lifespan==="ephemeral")f=ko(t,M,F);else{let k=Go(t,M,F);if(k)f=k;else throw new Tn(M,F,t)}}}else[f]=T;if(f.type==="molecule")return Mo(t,f);let y=d(f,t),A=un(y,t);return t.logger.info("\uD83D\uDD0C","selector",o,`registers dependency ( "${f.key}" =`,A,")"),S.selectorGraph.set({upstreamSelectorKey:f.key,downstreamSelectorKey:o},{source:f.key}),CA(o,f,n,t),A},set:(...T)=>{let S,f;if(T.length===2)S=T[0],f=T[1];else{let M=T[0],F=T[1];f=T[2];let k=t.config.lifespan==="ephemeral"?ko(t,M,F):Go(t,M,F);if(!k)throw new Tn(M,F,t);S=k}let y=D(t),A=d(S,y);lT(A,f,y)},find:(T,S)=>ko(t,T,S),seek:(T,S)=>Go(t,T,S),json:(T)=>ro(t,T)});var fT=(o,n,t)=>{let T=D(o),S=new s,f=new Set,{get:y,find:A,seek:M,json:F}=yS(n.key,f,T),k=()=>{let Q=n.get({get:y,find:A,seek:M,json:F});return Rn(n.key,Q,S,D(o)),f.clear(),Q},W={...n,subject:S,install:(Q)=>fT(Q,n,t),get:k,type:"readonly_selector",...t&&{family:t}};T.readonlySelectors.set(n.key,W);let O=k();o.logger.info("\u2728",W.type,W.key,"=",O);let E={key:n.key,type:"readonly_selector"};if(t)E.family=t;return E};var JT=(o,n,t)=>{let T=D(o),S=new s,f=new Set,y=yS(n.key,f,T),{find:A,get:M,seek:F,json:k}=y,W={find:A,get:M,seek:F,json:k},O=(V=n.get,x=D(o))=>{let c=V(W);return Rn(n.key,c,S,x),f.clear(),c},Q={...n,subject:S,install:(V)=>JT(V,n,t),get:O,set:(V)=>{let x=D(o),c=O(n.get,x),P=eT(V)(c);if(o.logger.info("\uD83D\uDCDD","selector",n.key,"set (",c,"->",P,")"),Rn(n.key,P,S,x),Dt(x,n.key),Bo(x))S.next({newValue:P,oldValue:c});n.set(y,P)},type:"selector",...t&&{family:t}};T.selectors.set(n.key,Q);let z=O();o.logger.info("\u2728",Q.type,Q.key,"=",z);let G={key:n.key,type:"selector"};if(t)G.family=t;return G};function zn(o,n){if("set"in n){let S=JT(o,n,void 0);return o.on.selectorCreation.next(S),S}let T=fT(o,n,void 0);return o.on.selectorCreation.next(T),T}function VA(o,n){let t=D(n),{key:T}=o,S=d(o,t);if(!S.family)n.logger.error("\u274C","selector",T,"Standalone selectors cannot be disposed.");else{let f=t.molecules.get(S.family.subKey);if(f)f.tokens.delete(T);switch(o.type){case"selector":t.selectors.delete(T),d({key:S.family.key,type:"selector_family"},n).subject.next({type:"state_disposal",token:o});break;case"readonly_selector":t.readonlySelectors.delete(T),d({key:S.family.key,type:"readonly_selector_family"},n).subject.next({type:"state_disposal",token:o});break}if(t.valueMap.delete(T),t.selectorAtoms.delete(T),t.selectorGraph.delete(T),n.logger.info("\uD83D\uDD25",o.type,T,"deleted"),Fo(t)&&t.transactionMeta.phase==="building")t.transactionMeta.update.updates.push({type:"state_disposal",token:o});else n.on.selectorDisposal.next(o)}}function AT(o,n,t){let T={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 ${Hn(S)} "${S.key}" in store "${o.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let f=new s,A=Object.assign((M)=>{let F=l(M),k={key:n.key,subKey:F},W=`${n.key}(${F})`,O=D(o),E=JT(O,{key:W,get:n.get(M),set:n.set(M)},k);return f.next({type:"state_creation",token:E}),E},T,{internalRoles:t,subject:f,install:(M)=>AT(M,n),default:(M)=>{return n.get(M)({get:(...k)=>Mo(o,...k),find:(k,W)=>ko(o,k,W),seek:(k,W)=>Go(o,k,W),json:(k)=>ro(o,k)})}});return o.families.set(n.key,A),T}function LA(o,n,t=yo.STORE){let T=AT(t,{key:`${o.key}:JSON`,get:(f)=>({seek:y,get:A})=>{let M=y(o,f);if(M)return n.toJson(A(M));let F=l(f),k=t.molecules.get(F);if(k){let O=mn(k,o,t);return n.toJson(A(O))}if(t.config.lifespan==="immortal")throw new Error(`No molecule found for key "${F}"`);let W=vn(t,o,f);return n.toJson(A(W))},set:(f)=>({seek:y,set:A},M)=>{let F=y(o,f);if(F)A(F,n.fromJson(M));else{let k=l(f),W=t.molecules.get(k);if(W){let O=mn(W,o,t);A(O,n.fromJson(M))}else{if(t.config.lifespan==="immortal")throw new Error(`No molecule found for key "${k}"`);A(vn(t,o,f),n.fromJson(M))}}}},["mutable","json"]);return d(o,t).subject.subscribe(`store=${t.config.name}::json-selector-family`,(f)=>{if(f.token.family)Go(t,T,bo(f.token.family.subKey))}),T}var bo=(o)=>JSON.parse(o),l=(o)=>JSON.stringify(o),s2=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];var IA=(o,n)=>{let t=D(n);if(t.operation.open)return t.operation.prev.get(o.key);return t.valueMap.get(o.key)};var Xf=(o,n)=>{let t=D(n);return BA(o,n).map((S)=>{let f=t.atoms.get(S);if(f===void 0)throw new Error(`Atom "${S}", a dependency of selector "${o.key}", not found in store "${n.config.name}".`);return f.subject.subscribe(`${o.type}:${o.key}`,(y)=>{n.logger.info("\uD83D\uDCE2",o.type,o.key,"root",S,"went",y.oldValue,"->",y.newValue);let A=IA(o,t),M=un(o,t);n.logger.info("\u2728",o.type,o.key,"went",A,"->",M),o.subject.next({newValue:M,oldValue:A})})})};function eo(o,n,t,T){function S(W){if(T.operation.open){let O=T.on.operationClose.subscribe(`state subscription ${t}`,()=>{O(),n(W)})}else n(W)}let f=d(o,T);T.logger.info("\uD83D\uDC40",f.type,f.key,`Adding subscription "${t}"`);let y=f.type==="selector"||f.type==="readonly_selector",A=null,M=S;if(y)A=Xf(f,T),M=(W)=>{if(A)A.length=0,A.push(...Xf(f,T));S(W)};let F=f.subject.subscribe(t,M);return()=>{if(T.logger.info("\uD83D\uDE48",f.type,f.key,`Removing subscription "${t}"`),F(),A)for(let W of A)W()}}var wf=(o,n,t,T)=>{let S=d(o,T);T.logger.info("\uD83D\uDC40","timeline",o.key,`Adding subscription "${t}"`);let f=S.subject.subscribe(t,n);return()=>{T.logger.info("\uD83D\uDE48","timeline",o.key,`Removing subscription "${t}" from timeline`),f()}};var Kf=(o,n,t,T)=>{let S=d(o,T);T.logger.info("\uD83D\uDC40","transaction",o.key,`Adding subscription "${t}"`);let f=S.subject.subscribe(t,n);return()=>{T.logger.info("\uD83D\uDE48","transaction",o.key,`Removing subscription "${t}"`),f()}};class an{Update;initializeState(o,n){let t=`*${o.key}`;n.atoms.delete(t),n.valueMap.delete(t);let T=o.family?{key:`*${o.family.key}`,subKey:o.family.subKey}:void 0,S=tn(n,{key:t,default:null},T);if(n.parent?.valueMap.has(t)){let f=n.parent.valueMap.get(t);n.valueMap.set(t,f)}return S}unsubscribeFromInnerValue;unsubscribeFromState;observeCore(o,n,t){let T=`tracker:${t.config.name}:${Fo(t)?t.transactionMeta.update.key:"main"}:${o.key}`,S=Mo(t,o);this.unsubscribeFromInnerValue=S.subscribe(T,(f)=>{Qo(t,n,f)}),this.unsubscribeFromState=eo(o,(f)=>{if(f.newValue!==f.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=f.newValue.subscribe(T,(y)=>{Qo(t,n,y)})},T,t)}updateCore(o,n,t){let T=`tracker:${t.config.name}:${Fo(t)?t.transactionMeta.update.key:"main"}:${o.key}`;eo(n,({newValue:S,oldValue:f})=>{let y=t.timelineTopics.getRelatedKey(n.key);if(y){if(t.timelines.get(y)?.timeTraveling){let F=wf({key:y,type:"timeline"},(k)=>{F(),Qo(t,o,(W)=>{if(k==="redo"&&S)W.do(S);else if(k==="undo"&&f)W.undo(f);return W})},T,t);return}}let A=t.on.operationClose.subscribe(T,()=>{A();let M=Mo(t,o),F=S===null?-1:M.getUpdateNumber(S),k=F-M.cacheUpdateNumber;if(S&&k===1)Qo(t,o,(W)=>(W.do(S),W));else t.logger.info("\u274C","mutable_atom",o.key,`could not be updated. Expected update number ${M.cacheUpdateNumber+1}, but got ${F}`)})},T,t)}mutableState;latestUpdateState;dispose;constructor(o,n){this.mutableState=o;let t=D(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.dispose=()=>{this.unsubscribeFromInnerValue(),this.unsubscribeFromState(),t.trackers.delete(o.key)}}}function RT(o,n,t){o.logger.info("\uD83D\uDD28","atom",n.key,`creating in store "${o.config.name}"`);let T=D(o),S=T.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."),Po(S);let f=new s,y={...n,type:"mutable_atom",install:(F)=>{return F.logger.info("\uD83D\uDEE0\uFE0F","atom",n.key,`installing in store "${F.config.name}"`),RT(F,n,t)},subject:f};if(t)y.family=t;let A=n.default();T.atoms.set(y.key,y),AS(n.key,o),Rn(n.key,A,f,T);let M=Po(y);if(n.effects){let F=0,k=[];for(let W of n.effects){let O=W({setSelf:(E)=>{Qo(o,M,E)},onSet:(E)=>eo(M,E,`effect[${F}]`,o)});if(O)k.push(O);++F}y.cleanup=()=>{for(let W of k)W()}}if(new an(M,o),!t)oA(M,n,o);return M}class Ef{Update;latestUpdateAtoms;mutableAtoms;constructor(o,n){let t=jn(n,{key:`*${o.key}`,default:null},["mutable","updates"]);this.latestUpdateAtoms=d(t,n),this.mutableAtoms=o,this.mutableAtoms.subject.subscribe(`store=${n.config.name}::tracker-atom-family`,(T)=>{if(T.token.family){let S=bo(T.token.family.subKey);Go(n,this.latestUpdateAtoms,S),new an(T.token,n)}}),this.latestUpdateAtoms.subject.subscribe(`store=${n.config.name}::tracker-atom-family`,(T)=>{if(T.token.family){let S=bo(T.token.family.subKey),f=Go(n,this.mutableAtoms,S);if(f)new an(f,n)}})}}function ST(o,n,t){let T={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 ${Hn(S)} "${S.key}" in store "${o.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let f=new s,A=Object.assign((M)=>{let F=l(M),k={key:n.key,subKey:F},W=`${n.key}(${F})`,O=D(o),E={key:W,default:()=>n.default(M),toJson:n.toJson,fromJson:n.fromJson,mutable:!0};if(n.effects)E.effects=n.effects(M);let Q=RT(O,E,k);return f.next({type:"state_creation",token:Q}),Q},T,{subject:f,install:(M)=>ST(M,n),toJson:n.toJson,fromJson:n.fromJson,internalRoles:t});return o.families.set(n.key,A),LA(A,n,o),new Ef(A,o),T}var Ff=(o,n)=>{let t=D(n),T=`${o.key}:JSON`;return t.families.get(T)};var ro=(o,n)=>{if(n.family){let T=D(o),f={key:`${n.family.key}:JSON`,type:"selector_family"},y=d(f,T),A=JSON.parse(n.family.subKey);return ko(o,y,A)}return{type:"selector",key:`${n.key}:JSON`}};var qn=(o)=>{let t={type:"atom",key:`*${o.key}`};if(o.family)t.family={key:`*${o.family.key}`,subKey:o.family.subKey};return t};function RA(o){return typeof o==="object"&&o!==null&&"do"in o&&"undo"in o&&"subscribe"in o}function kT(o,n,t){let T=n.valueMap.get(o.key),S=t.valueMap.get(o.key);if(T===S){if(T===void 0)return typeof o.default==="function"?o.default():o.default;n.logger.info("\uD83D\uDCC3","atom",o.key,"copying");let f=o.toJson(T),y=o.fromJson(f);return t.valueMap.set(o.key,y),new an(o,n),y}return S}function Rn(o,n,t,T){let S=T.valueMap.get(o);if(S instanceof TT)S.use(n);if(n instanceof Promise){let f=new TT(n);return T.valueMap.set(o,f),f.then((y)=>{Rn(o,y,t,T),t.next({newValue:y,oldValue:f})}).catch((y)=>{T.logger.error("\uD83D\uDCA5","state",o,"rejected:",y)}),f}return T.valueMap.set(o,n),n}var yA=(o,n)=>{let t=n.valueMap.get(o.key);if(o.type==="mutable_atom"&&Fo(n)){let{parent:T}=n;t=kT(o,T,n)}return t},$A=(o,n)=>{let t=n.valueMap.get(o);if(t instanceof TT){let T=t,S=n.selectors.get(o)??n.readonlySelectors.get(o);if(S)T.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 OA=(o,n)=>{return D(n).atomsThatAreDefault.has(o)},AS=(o,n)=>{let t=D(n);t.atomsThatAreDefault=new Set(t.atomsThatAreDefault).add(o)},_A=(o,n)=>{let t=D(n);t.atomsThatAreDefault=new Set(D(n).atomsThatAreDefault),t.atomsThatAreDefault.delete(o)};function tn(o,n,t){o.logger.info("\uD83D\uDD28","atom",n.key,`creating in store "${o.config.name}"`);let T=D(o),S=T.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."),Po(S);let f=new s,y={...n,type:"atom",install:(F)=>{return F.logger.info("\uD83D\uDEE0\uFE0F","atom",n.key,`installing in store "${F.config.name}"`),tn(F,n,t)},subject:f};if(t)y.family=t;let A=n.default;if(n.default instanceof Function)A=n.default();T.atoms.set(y.key,y),AS(n.key,o),Rn(n.key,A,f,T);let M=Po(y);if(n.effects){let F=0,k=[];for(let W of n.effects){let O=W({setSelf:(E)=>{Qo(o,M,E)},onSet:(E)=>eo(M,E,`effect[${F}]`,o)});if(O)k.push(O);++F}y.cleanup=()=>{for(let W of k)W()}}return M}function TA(o,n){if("mutable"in n){let S=RT(o,n,void 0);return o.on.atomCreation.next(S),S}let T=tn(o,n,void 0);return o.on.atomCreation.next(T),T}function Of(o,n){let t=D(n),{key:T}=o,S=d(o,t);if(!S.family)n.logger.error("\u274C","atom",T,"Standalone atoms cannot be disposed.");else{S.cleanup?.();let f=n.valueMap.get(S.key);d({key:S.family.key,type:"atom_family"},n).subject.next({type:"state_disposal",token:o,value:f});let A=t.molecules.get(S.family.subKey);if(A)A.tokens.delete(T);if(t.atoms.delete(T),t.valueMap.delete(T),t.selectorAtoms.delete(T),t.atomsThatAreDefault.delete(T),n.timelineTopics.delete(T),o.type==="mutable_atom"){let M=qn(o);Of(M,n),n.trackers.delete(T)}if(n.logger.info("\uD83D\uDD25","atom",T,"deleted"),Fo(t)&&t.transactionMeta.phase==="building")t.transactionMeta.update.updates.push({type:"state_disposal",token:o});else n.on.atomDisposal.next(o)}}var Yf=(o)=>{let n=tn(o,{key:"\uD83D\uDD0D Atom Token Index (Internal)",default:()=>{let t=new Map;for(let[T,S]of o.atoms)if(!T.includes("\uD83D\uDD0D")){let f=Po(S);if(S.family){let y=t.get(S.family.key);if(!y||!("familyMembers"in y))y={key:S.family.key,familyMembers:new Map},t.set(S.family.key,y);y.familyMembers.set(S.family.subKey,f)}else t.set(T,f)}return t},effects:[({setSelf:t})=>{o.on.atomCreation.subscribe("introspection",(T)=>{if(T.key.includes("\uD83D\uDD0D"))return;t((S)=>{if(T.family){let{key:f,subKey:y}=T.family,A=S.get(f);if(A===void 0||!("familyMembers"in A))A={key:f,familyMembers:new Map},S.set(f,A);A.familyMembers.set(y,T)}else S.set(T.key,T);return S})}),o.on.atomDisposal.subscribe("introspection",(T)=>{t((S)=>{if(T.family){let{key:f,subKey:y}=T.family,A=S.get(f);if(A&&"familyMembers"in A){if(A.familyMembers.delete(y),A.familyMembers.size===0)S.delete(f)}}else S.delete(T.key);return S})})}]},void 0);return zn(o,{key:"\uD83D\uDD0D Atom Token Index",get:({get:t})=>t(n)})};var Gf=(o)=>{let n=tn(o,{key:"\uD83D\uDD0D Selector Token Index (Internal)",default:()=>{let t=new Map;for(let T of[o.readonlySelectors,o.selectors])for(let[S,f]of T)if(!S.includes("\uD83D\uDD0D")){let y=Po(f);if(f.family){let A=t.get(f.family.key);if(!A||!("familyMembers"in A))A={key:f.family.key,familyMembers:new Map},t.set(f.family.key,A);A.familyMembers.set(f.family.subKey,y)}else t.set(S,y)}return t},effects:[({setSelf:t})=>{o.on.selectorCreation.subscribe("introspection",(T)=>{if(T.key.includes("\uD83D\uDD0D"))return;t((S)=>{if(T.family){let{key:f,subKey:y}=T.family,A=S.get(f);if(A===void 0||!("familyMembers"in A))A={key:f,familyMembers:new Map},S.set(f,A);A.familyMembers.set(y,T)}else S.set(T.key,T);return S})}),o.on.selectorDisposal.subscribe("introspection",(T)=>{t((S)=>{if(T.family){let{key:f,subKey:y}=T.family,A=S.get(f);if(A&&"familyMembers"in A){if(A.familyMembers.delete(y),A.familyMembers.size===0)S.delete(f)}}else S.delete(T.key);return S})})}]},void 0);return zn(o,{key:"\uD83D\uDD0D Selector Token Index",get:({get:t})=>t(n)})};class MS{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(T){try{if(o instanceof t)return{type:n,data:o}}catch(S){}}return null}}var zf=new MS({number:(o)=>typeof o==="number",string:(o)=>typeof o==="string",boolean:(o)=>typeof o==="boolean",null:(o)=>o===null});function Hf(o){if(!o)return!1;return Object.getPrototypeOf(o)===Object.prototype}var mf=new MS({object:Hf,array:(o)=>Array.isArray(o)}),hJ=new MS({...zf.supported,...mf.supported}),Ut=(o)=>{if(o===void 0)return"undefined";let n=hJ.refine(o);if(n)return n.type;return Object.getPrototypeOf(o).constructor.name};class jA{o;auditorCreatedAt=performance.now();statesCreatedAt=new Map;atomIndex;selectorIndex;disposed=!1;unsubscribeFromAtomCreation;unsubscribeFromAtomDisposal;unsubscribeFromSelectorCreation;unsubscribeFromSelectorDisposal;constructor(o=yo.STORE){this.store=o;this.atomIndex=Yf(this.store),this.selectorIndex=Gf(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=jA.DEFAULT_LIST_RESOURCES_PARAM){if(this.disposed)throw new Error("This Auditor has been disposed");let n=Tf(this.atomIndex),t=Tf(this.selectorIndex),T=[...n.values()].filter((A)=>("familyMembers"in A)),S=[...t.values()].filter((A)=>("familyMembers"in A)),f=performance.now(),y=[];if(o.atomFamilies)for(let A of T){let M=A.familyMembers.values();for(let F of M){let W=this.statesCreatedAt.get(F.key)??this.auditorCreatedAt,O=f-W;y.push([F,O])}}if(o.selectorFamilies)for(let A of S){let M=A.familyMembers.values();for(let F of M){let W=this.statesCreatedAt.get(F.key)??this.auditorCreatedAt,O=f-W;y.push([F,O])}}return y}[Symbol.dispose](){this.unsubscribeFromAtomCreation(),this.unsubscribeFromAtomDisposal(),this.unsubscribeFromSelectorCreation(),this.unsubscribeFromSelectorDisposal(),this.disposed=!0}}var Qf=(o,n)=>{let t=(T,S)=>{let y=((M,F)=>{let k=n(M,F);if(k)return k;return null})(T,S);if(y?.jobComplete??y?.pathComplete)return y;let A=Array.isArray(S)?S.map((M,F)=>[F,M]):Hf(S)?Object.entries(S):[];for(let[M,F]of A){let k=t([...T,M],F);if(k?.jobComplete)return k}return{}};t([],o)};function cJ(o,n){return{summary:`${o<n?"+":"-"}${Math.abs(o-n)} (${o} \u2192 ${n})`}}function xJ(o,n){return{summary:`${o.length<n.length?"+":"-"}${Math.abs(o.length-n.length)} ("${o}" \u2192 "${n}")`}}function iJ(o,n){return{summary:`${o} \u2192 ${n}`}}function bA(o,n,t){let T="",S=[],f=[],y=[];return Qf(o,(A,M)=>{let F;for(F of A){let k=n[F];if(k===void 0)f.push([F,JSON.stringify(M)]);else{let W=t(M,k);if(W.summary!=="No Change")y.push([F,W])}}}),Qf(n,(A,M)=>{let F;for(F of A)if(o[F]===void 0)S.push([F,JSON.stringify(M)])}),T=`\uFF5E${y.length} \uFF0B${S.length} \uFF0D${f.length}`,{summary:T,added:S,removed:f,changed:y}}function vJ(o,n,t){return bA(o,n,t)}class NA{leafRefinery;treeRefinery;leafDiffers;treeDiffers;constructor(o,n,t){this.leafRefinery=o,this.treeRefinery=n,this.leafDiffers={},this.treeDiffers={};for(let T of Object.keys(o.supported)){let S=t[T];this.leafDiffers[T]=S}for(let T of Object.keys(n.supported)){let S=t[T];this.treeDiffers[T]=S}}diff(o,n){if(o===n)return{summary:"No Change"};let t=this.leafRefinery.refine(o)??this.treeRefinery.refine(o),T=this.leafRefinery.refine(n)??this.treeRefinery.refine(n);if(t!==null&&T!==null){if(t.type===T.type){if(t.type in this.leafDiffers)return this.leafDiffers[t.type](t.data,T.data);if(t.type in this.treeDiffers)return this.treeDiffers[t.type](t.data,T.data,(A,M)=>this.diff(A,M))}}let S=Ut(o),f=Ut(n);if(S===f)return{summary:`${S} \u2192 ${f}`};return{summary:`Type change: ${S} \u2192 ${f}`}}}var k8=new NA(zf,mf,{number:cJ,string:xJ,boolean:iJ,null:()=>({summary:"No Change"}),object:bA,array:vJ});class hA 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 FS{o;type="continuity";globals=[];actions=[];perspectives=[];constructor(o){this.key=o}static existing=new hA;static create(o,n){let t=new FS(o),{type:T,globals:S,actions:f,perspectives:y}=n(t),A={type:T,key:o,globals:S,actions:f,perspectives:y};return FS.existing.set(o,A),A}add(...o){switch(o[0].type){case"atom":case"mutable_atom":this.globals.push(...o);break;case"transaction":this.actions.push(...o);break;case"atom_family":{let[t,T]=o;this.perspectives.push({type:"realtime_perspective",resourceAtoms:t,viewAtoms:T})}break}return this}}function X8(o){let{key:n,config:t}=o,T=FS.create(n,t),{actions:S}=T;for(let f of S)mA(n,f.key,yo.STORE);return GA(n,-1,yo.STORE),T}var H8=Qt({key:"usersInRoomIndex",mutable:!0,default:()=>new No,toJson:(o)=>o.toJSON(),fromJson:(o)=>No.fromJSON(o)}),Df=Qt({key:"roomIndex",default:()=>new No,mutable:!0,toJson:(o)=>o.toJSON(),fromJson:(o)=>No.fromJSON(o)}),pJ={enteredAtEpoch:0},WT=uT({key:"usersInRooms",between:["room","user"],cardinality:"1:n",isAType:(o)=>typeof o==="string",isBType:(o)=>typeof o==="string"},pJ),m8=PT({key:"usersInMyRoomView",get:(o)=>({find:n})=>{let t=XA(WT);return[n(t,o)]}});import{spawn as qJ}from"child_process";class Vt{o;listeners;globalListeners;handleEvent(o,...n){for(let T of this.globalListeners)T(o,...n);let t=this.listeners.get(o);if(t)for(let T of t)T(...n)}id="no_id_retrieved";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 Uf extends Vt{o;n;t;incompleteData="";unprocessedEvents=[];incompleteLog="";unprocessedLogs=[];id="#####";handleLog(o){if(Array.isArray(o)){let[n,...t]=o;switch(n){case"i":this.logger.info(this.id,this.key,...t);break;case"w":this.logger.warn(this.id,this.key,...t);break;case"e":this.logger.error(this.id,this.key,...t);break}}}constructor(o,n,t=console){super((T,...S)=>{let f=JSON.stringify([T,...S])+"\x03",y=(A)=>{if(A.code==="EPIPE")console.error("EPIPE error during write",this.process.stdin);this.process.stdin.removeListener("error",y)};return this.process.stdin.once("error",y),this.process.stdin.write(f),this});this.process=o;this.key=n;this.logger=t;if(this.process=o,this.process.stdout.on("data",(T)=>{let S=T.toString();if(S==="\u2728")return;this.unprocessedEvents.push(...S.split("\x03"));let f=this.unprocessedEvents.shift();this.incompleteData+=f??"";try{if(this.incompleteData.startsWith("error"))console.log("\u2757",this.incompleteData);let y=bo(this.incompleteData);this.handleEvent(...y);while(this.unprocessedEvents.length>0){let A=this.unprocessedEvents.shift();if(A){if(this.unprocessedEvents.length===0)this.incompleteData=A;y=bo(A),this.handleEvent(...y)}}this.incompleteData=""}catch(y){console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.warn(this.incompleteData),console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.error(y)}}),this.process.stderr.on("data",(T)=>{let S=T.toString();this.unprocessedLogs.push(...S.split("\x03"));let f=this.unprocessedLogs.shift();this.incompleteLog+=f??"";try{let y=bo(this.incompleteLog);this.handleLog(y);while(this.unprocessedLogs.length>0)if(this.incompleteLog=this.unprocessedLogs.shift()??"",this.incompleteLog)y=bo(this.incompleteLog),this.handleLog(y)}catch(y){console.error("\u274C\u274C\u274C"),console.error(this.incompleteLog),console.error(y),console.error("\u274C\u274C\u274C\uFE0F")}}),o.pid)this.id=o.pid.toString()}}class cA extends Vt{in;out;id="no_id_retrieved";disposalFunctions=[];constructor(o){super((...n)=>{return this.out.next(n),this});this.id=o,this.in=new s,this.out=new s,this.in.subscribe("socket",(n)=>{this.handleEvent(...n)})}dispose(){for(let o of this.disposalFunctions)o()}}class Vf extends Vt{incompleteData="";unprocessedEvents=[];relays;relayServices;process;id="#####";log(...o){this.process.stderr.write(l(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 T=bo(this.incompleteData);this.logger.info("\uD83C\uDFB0","received",T),this.handleEvent(...T);while(this.unprocessedEvents.length>0){let S=this.unprocessedEvents.shift();if(S){if(this.unprocessedEvents.length===0)this.incompleteData=S;let f=bo(S);this.handleEvent(...f)}}this.incompleteData=""}catch(T){if(T instanceof Error)this.logger.error("\u2757",T.message,T.cause,T.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 cA(`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 T=t(n);if(T)n.disposalFunctions.push(T)}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("\u2728")}relay(o){this.logger.info("\uD83D\uDD17","running relay method"),this.relayServices.push(o)}}var rf=Ft({key:"roomArguments",default:["echo",["Hello World!"]]}),xA=PT({key:"room",get:(o)=>async({get:n,find:t})=>{let T=t(rf,o),S=n(T),[f,y]=S,A=await new Promise((M)=>{let F=qJ(f,y,{env:process.env}),k=(W)=>{if(W.toString()==="\u2728")F.stdout.off("data",k),M(F)};F.stdout.on("data",k)});return new Uf(A,o)}});var s8=FT({key:"createRoom",do:({get:o,set:n,find:t},T,S,f)=>{let y=f?[S,f]:[S],A=t(rf,T);n(A,y),n(Df,(k)=>k.add(T));let M=t(xA,T);return o(M)}}),o5=FT({key:"joinRoom",do:(o,n,t,T)=>{let S={enteredAtEpoch:T};return sT(WT,(f)=>{f.set({room:n,user:t},S)},o.env().store),S}}),n5=FT({key:"leaveRoom",do:(o,n,t)=>{sT(WT,(T)=>{T.delete({room:n,user:t})},o.env().store)}}),t5=FT({key:"destroyRoom",do:(o,n)=>{sT(WT,(t)=>{t.delete({room:n})},o.env().store),o.set(Df,(t)=>(t.delete(n),t))}});function Bf(o,n){return n.map((t)=>{switch(t.type){case"transaction_update":{let T=Bf(o,t.updates);return{...t,updates:T}}default:return t}}).filter((t)=>{switch(t.type){case"atom_update":case"selector_update":return o.includes(t.key);case"state_creation":return o.includes(t.token.key);case"molecule_creation":return!0;case"transaction_update":return!0}})}var f5=Ft({key:"redactor",default:{occlude:(o)=>o}}),rt=Ft({key:"unacknowledgedUpdates",default:()=>[]});var iA=Ft({key:"sockets",default:null}),k5=Qt({key:"socketsIndex",mutable:!0,default:()=>new No,toJson:(o)=>o.toJSON(),fromJson:(o)=>No.fromJSON(o)}),$5=Qt({key:"usersIndex",mutable:!0,default:()=>new No,toJson:(o)=>o.toJSON(),fromJson:(o)=>No.fromJSON(o)}),Cf=uT({key:"usersOfSockets",between:["user","socket"],cardinality:"1:1",isAType:(o)=>o.startsWith("user::"),isBType:(o)=>o.startsWith("socket::")});function vA(o,n,t,T){let S=n.key;return function f(){let y=[];for(let M of n.globals){let F=M.type==="mutable_atom"?ro(o,M):M,k=Mo(o,F);y.push(F,k)}for(let M of n.perspectives){let{viewAtoms:F,resourceAtoms:k}=M,W=ko(o,F,t),O=Mo(o,W);o.logger.info("\uD83D\uDC41","atom",k.key,`${t} can see`,{viewAtoms:F,resourceAtoms:k,userView:O});for(let E of O){let Q=E.type==="mutable_atom"?ro(o,E):E,z=Mo(o,Q);y.push(Q,z)}}let A=Bo(o)?o.transactionMeta.epoch.get(S)??null:null;T?.emit(`continuity-init:${S}`,A,y)}}function pA(o,n,t){let T=n.key;return function S(f){o.logger.info("\uD83D\uDECE\uFE0F","continuity",T,"received",f);let{key:y,id:A}=f,M=`tx-run:${y}:${A}`,F=`${M}:start`,k=`${M}:end`;performance.mark(F);try{dn({type:"transaction",key:y},A,o)(...f.params)}catch(O){if(O instanceof Error)o.logger.error("\u274C","continuity",T,`failed to run transaction ${y} from ${t} with update ${A}`,O.message)}performance.mark(k);let W=performance.measure(M,F,k);o?.logger.info("\uD83D\uDE80","transaction",y,A,t,W.duration)}}function qA(o,n,t,T){let S=n.key;return function f(y){if(o.logger.info("\uD83D\uDC4D","continuity",S,`${t} acknowledged epoch ${y}`),T[0]?.epoch===y)Qo(o,rt,t,(M)=>{return M.shift(),o.logger.info("\uD83D\uDC4D","continuity",S,`${t} unacknowledged update queue now has`,M.length,"items"),M})}}function ZA(o,n,t,T){let S=n.key,f=[];for(let y of n.actions){let A=Kf(y,(M)=>{try{let F=n.globals.map((O)=>{if(O.type==="atom")return O.key;return qn(O).key}).concat(n.perspectives.flatMap((O)=>{let{viewAtoms:E}=O,Q=ko(o,E,t);return Mo(o,Q).map((G)=>{return G.type==="mutable_atom"?"*"+G.key:G.key})})),k=Bf(F,M.updates),W={...M,updates:k};Qo(o,rt,t,(O)=>{if(W)O.push(W),O.sort((E,Q)=>E.epoch-Q.epoch),o.logger.info("\uD83D\uDC4D","continuity",S,`${t} unacknowledged update queue now has`,O.length,"items");return O}),T?.emit(`tx-new:${S}`,W)}catch(F){if(F instanceof Error)o.logger.error("\u274C","continuity",S,`${t} failed to send update from transaction ${y.key} to ${t}`,F.message)}},`sync-continuity:${S}:${t}`,o);f.push(A)}return f}function PA(o,n,t,T){let S=n.key,f=[];for(let y of n.perspectives){let{viewAtoms:A}=y,M=ko(o,A,t),F=eo(M,({oldValue:k,newValue:W})=>{let O=k.map((G)=>G.key),E=W.map((G)=>G.key),Q=k.filter((G)=>!E.includes(G.key)),z=W.filter((G)=>!O.includes(G.key)).flatMap((G)=>{let V=G.type==="mutable_atom"?ro(o,G):G,x=Mo(o,V);return[V,x]});if(o.logger.info("\uD83D\uDC41","atom",y.resourceAtoms.key,`${t} has a new perspective`,{oldKeys:O,newKeys:E,revealed:z,concealed:Q}),z.length>0)T?.emit(`reveal:${S}`,z);if(Q.length>0)T?.emit(`conceal:${S}`,Q)},`sync-continuity:${S}:${t}:perspective:${y.resourceAtoms.key}`,o);f.push(F)}return f}function i5({socket:o,store:n=yo.STORE}){return function t(T){let S=o,f=T.key,y=aT(Cf,`socket::${S.id}`,n).userKeyOfSocket,A=Mo(n,y);if(!A)return n.logger.error("\u274C","continuity",f,`Tried to create a synchronizer for a socket (${S.id}) that is not connected to a user.`),()=>{};let M=aT(Cf,A,n).socketKeyOfUser,F=eo(M,({newValue:V})=>{if(n.logger.info("\uD83D\uDC4B","continuity",f,`seeing ${A} on new socket ${V}`),V===null){n.logger.warn("\u274C","continuity",f,`User (${A}) is not connected to a socket, waiting for them to reappear.`);return}let x=ko(n,iA,V);S=Mo(n,x);for(let P of k)S?.emit(`tx-new:${f}`,P)},`sync-continuity:${f}:${A}`,n),k=Mo(n,rt,A),W=[],O=PA(n,T,A,S),E=ZA(n,T,A,S);W.push(...O,...E);let Q=vA(n,T,A,o);S.off(`get:${f}`,Q),S.on(`get:${f}`,Q);let z=pA(n,T,A);S.off(`tx-run:${f}`,z),S.on(`tx-run:${f}`,z);let G=qA(n,T,A,k);return S?.on(`ack:${f}`,G),()=>{for(let V of W)V();S?.off(`ack:${f}`,G),S?.off(`get:${f}`,Q),S?.off(`tx-run:${f}`,z)}}}var{file:r$,serve:u0}=globalThis.Bun;var J=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,J))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(J in t&&t[J]===n[J])return!0;t=Object.getPrototypeOf(t)}return!1}class Xo{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[J]="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 Lf{static[J]="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 Qn=Symbol.for("drizzle:Name");class If{static[J]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(o,n){if(this.reference=()=>{let{name:t,columns:T,foreignColumns:S}=o();return{name:t,columns:T,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 eA(o,this)}}class eA{constructor(o,n){this.table=o,this.reference=n.reference,this.onUpdate=n._onUpdate,this.onDelete=n._onDelete}static[J]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:o,columns:n,foreignColumns:t}=this.reference(),T=n.map((y)=>y.name),S=t.map((y)=>y.name),f=[this.table[Qn],...T,t[0].table[Qn],...S];return o??`${f.join("_")}_fk`}}function kS(o,...n){return o(...n)}function lA(o,n){return`${o[Qn]}_${n.join("_")}_unique`}function gA(o,n,t){for(let T=n;T<o.length;T++){let S=o[T];if(S==="\\"){T++;continue}if(S==='"')return[o.slice(n,T).replace(/\\/g,""),T+1];if(t)continue;if(S===","||S==="}")return[o.slice(n,T).replace(/\\/g,""),T]}return[o.slice(n).replace(/\\/g,""),o.length]}function dA(o,n=0){let t=[],T=n,S=!1;while(T<o.length){let f=o[T];if(f===","){if(S||T===n)t.push("");S=!0,T++;continue}if(S=!1,f==="\\"){T+=2;continue}if(f==='"'){let[M,F]=gA(o,T+1,!0);t.push(M),T=F;continue}if(f==="}")return[t,T+1];if(f==="{"){let[M,F]=dA(o,T+1);t.push(M),T=F;continue}let[y,A]=gA(o,T,!1);t.push(y),T=A}return[t,T]}function uA(o){let[n]=dA(o,1);return n}function jf(o){return`{${o.map((n)=>{if(Array.isArray(n))return jf(n);if(typeof n==="string")return`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`;return`${n}`}).join(",")}}`}class N extends Lf{foreignKeyConfigs=[];static[J]="PgColumnBuilder";array(o){return new sA(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:T})=>{return kS((S,f)=>{let y=new If(()=>{let A=S();return{columns:[o],foreignColumns:[A]}});if(f.onUpdate)y.onUpdate(f.onUpdate);if(f.onDelete)y.onDelete(f.onDelete);return y.build(n)},t,T)})}buildExtraConfigColumn(o){return new aA(o,this.config)}}class r extends Xo{constructor(o,n){if(!n.uniqueName)n.uniqueName=lA(o,[n.name]);super(o,n);this.table=o}static[J]="PgColumn"}class aA extends r{static[J]="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 OT{static[J]="IndexedColumn";constructor(o,n,t,T){this.name=o,this.keyAsName=n,this.type=t,this.indexConfig=T}name;keyAsName;type;indexConfig}class sA extends N{static[J]="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 bf(o,this.config,n)}}class bf extends r{constructor(o,n,t,T){super(o,n);this.baseColumn=t,this.range=T,this.size=n.size}size;static[J]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(o){if(typeof o==="string")o=uA(o);return o.map((n)=>this.baseColumn.mapFromDriverValue(n))}mapToDriverValue(o,n=!1){let t=o.map((T)=>T===null?null:X(this.baseColumn,bf)?this.baseColumn.mapToDriverValue(T,!0):this.baseColumn.mapToDriverValue(T));if(n)return t;return jf(t)}}var Nf=Symbol.for("drizzle:isPgEnum");function oM(o){return!!o&&typeof o==="function"&&Nf in o&&o[Nf]===!0}class nM extends N{static[J]="PgEnumColumnBuilder";constructor(o,n){super(o,"string","PgEnumColumn");this.config.enum=n}build(o){return new tM(o,this.config)}}class tM extends r{static[J]="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 $S(o,n){return ZJ(o,n,void 0)}function ZJ(o,n,t){let T=Object.assign((S)=>new nM(S??"",T),{enumName:o,enumValues:n,schema:t,[Nf]:!0});return T}class xo{static[J]="Subquery";constructor(o,n,t,T=!1){this._={brand:"Subquery",sql:o,selectedFields:n,alias:t,isWith:T}}}class _T extends xo{static[J]="WithSubquery"}var TM="0.36.1";var hf,cf,Oo={startActiveSpan(o,n){if(!hf)return n();if(!cf)cf=hf.trace.getTracer("drizzle-orm",TM);return kS((t,T)=>T.startActiveSpan(o,(S)=>{try{return n(S)}catch(f){throw S.setStatus({code:t.SpanStatusCode.ERROR,message:f instanceof Error?f.message:"Unknown error"}),f}finally{S.end()}}),hf,cf)}};var Do=Symbol.for("drizzle:ViewBaseConfig");var JS=Symbol.for("drizzle:Schema"),SM=Symbol.for("drizzle:Columns"),fM=Symbol.for("drizzle:ExtraConfigColumns"),xf=Symbol.for("drizzle:OriginalName"),vf=Symbol.for("drizzle:BaseName"),yM=Symbol.for("drizzle:IsAlias"),AM=Symbol.for("drizzle:ExtraConfigBuilder"),PJ=Symbol.for("drizzle:IsDrizzleTable");class L{static[J]="Table";static Symbol={Name:Qn,Schema:JS,OriginalName:xf,Columns:SM,ExtraConfigColumns:fM,BaseName:vf,IsAlias:yM,ExtraConfigBuilder:AM};[Qn];[xf];[JS];[SM];[fM];[vf];[yM]=!1;[PJ]=!0;[AM]=void 0;constructor(o,n,t){this[Qn]=this[xf]=o,this[JS]=n,this[vf]=t}}function On(o){return o[Qn]}function kt(o){return`${o[JS]??"public"}.${o[Qn]}`}function pf(o){return o!==null&&o!==void 0&&typeof o.getSQL==="function"}function eJ(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 ho{static[J]="StringChunk";value;constructor(o){this.value=Array.isArray(o)?o:[o]}getSQL(){return new h([this])}}class h{constructor(o){this.queryChunks=o}static[J]="SQL";decoder=FM;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:T,escapeName:S,escapeParam:f,prepareTyping:y,inlineParams:A,paramStartIndex:M}=t;return eJ(o.map((F)=>{if(X(F,ho))return{sql:F.value.join(""),params:[]};if(X(F,RS))return{sql:S(F.value),params:[]};if(F===void 0)return{sql:"",params:[]};if(Array.isArray(F)){let k=[new ho("(")];for(let[W,O]of F.entries())if(k.push(O),W<F.length-1)k.push(new ho(", "));return k.push(new ho(")")),this.buildQueryFromSourceParams(k,t)}if(X(F,h))return this.buildQueryFromSourceParams(F.queryChunks,{...t,inlineParams:A||F.shouldInlineParams});if(X(F,L)){let k=F[L.Symbol.Schema],W=F[L.Symbol.Name];return{sql:k===void 0?S(W):S(k)+"."+S(W),params:[]}}if(X(F,Xo)){let k=T.getColumnCasing(F);if(n.invokeSource==="indexes")return{sql:S(k),params:[]};return{sql:S(F.table[L.Symbol.Name])+"."+S(k),params:[]}}if(X(F,Sn)){let k=F[Do].schema,W=F[Do].name;return{sql:k===void 0?S(W):S(k)+"."+S(W),params:[]}}if(X(F,Fn)){if(X(F.value,sn))return{sql:f(M.value++,F),params:[F],typings:["none"]};let k=F.value===null?null:F.encoder.mapToDriverValue(F.value);if(X(k,h))return this.buildQueryFromSourceParams([k],t);if(A)return{sql:this.mapInlineParam(k,t),params:[]};let W=["none"];if(y)W=[y(F.encoder)];return{sql:f(M.value++,k),params:[k],typings:W}}if(X(F,sn))return{sql:f(M.value++,F),params:[F],typings:["none"]};if(X(F,h.Aliased)&&F.fieldAlias!==void 0)return{sql:S(F.fieldAlias),params:[]};if(X(F,xo)){if(F._.isWith)return{sql:S(F._.alias),params:[]};return this.buildQueryFromSourceParams([new ho("("),F._.sql,new ho(") "),new RS(F._.alias)],t)}if(oM(F)){if(F.schema)return{sql:S(F.schema)+"."+S(F.enumName),params:[]};return{sql:S(F.enumName),params:[]}}if(pf(F)){if(F.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([F.getSQL()],t);return this.buildQueryFromSourceParams([new ho("("),F.getSQL(),new ho(")")],t)}if(A)return{sql:this.mapInlineParam(F,t),params:[]};return{sql:f(M.value++,F),params:[F],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 h.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 RS{constructor(o){this.value=o}static[J]="Name";brand;getSQL(){return new h([this])}}function MM(o){return typeof o==="object"&&o!==null&&"mapToDriverValue"in o&&typeof o.mapToDriverValue==="function"}var FM={mapFromDriverValue:(o)=>o},kM={mapToDriverValue:(o)=>o},nY={...FM,...kM};class Fn{constructor(o,n=kM){this.value=o,this.encoder=n}static[J]="Param";brand;getSQL(){return new h([this])}}function R(o,...n){let t=[];if(n.length>0||o.length>0&&o[0]!=="")t.push(new ho(o[0]));for(let[T,S]of n.entries())t.push(S,new ho(o[T+1]));return new h(t)}((o)=>{function n(){return new h([])}o.empty=n;function t(M){return new h(M)}o.fromList=t;function T(M){return new h([new ho(M)])}o.raw=T;function S(M,F){let k=[];for(let[W,O]of M.entries()){if(W>0&&F!==void 0)k.push(F);k.push(O)}return new h(k)}o.join=S;function f(M){return new RS(M)}o.identifier=f;function y(M){return new sn(M)}o.placeholder=y;function A(M,F){return new Fn(M,F)}o.param=A})(R||(R={}));((o)=>{class n{constructor(t,T){this.sql=t,this.fieldAlias=T}static[J]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new n(this.sql,this.fieldAlias)}}o.Aliased=n})(h||(h={}));class sn{constructor(o){this.name=o}static[J]="Placeholder";getSQL(){return new h([this])}}function qf(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,Fn)&&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})}class Sn{static[J]="View";[Do];constructor({name:o,schema:n,selectedFields:t,query:T}){this[Do]={name:o,originalName:o,schema:n,selectedFields:t,query:T,isExisting:!T,isAlias:!1}}getSQL(){return new h([this])}}Xo.prototype.getSQL=function(){return new h([this])};L.prototype.getSQL=function(){return new h([this])};xo.prototype.getSQL=function(){return new h([this])};class Bt{constructor(o){this.table=o}static[J]="ColumnAliasProxyHandler";get(o,n){if(n==="table")return this.table;return o[n]}}class wT{constructor(o,n){this.alias=o,this.replaceOriginalName=n}static[J]="TableAliasProxyHandler";get(o,n){if(n===L.Symbol.IsAlias)return!0;if(n===L.Symbol.Name)return this.alias;if(this.replaceOriginalName&&n===L.Symbol.OriginalName)return this.alias;if(n===Do)return{...o[Do],name:this.alias,isAlias:!0};if(n===L.Symbol.Columns){let T=o[L.Symbol.Columns];if(!T)return T;let S={};return Object.keys(T).map((f)=>{S[f]=new Proxy(T[f],new Bt(new Proxy(o,this)))}),S}let t=o[n];if(X(t,Xo))return new Proxy(t,new Bt(new Proxy(o,this)));return t}}function WS(o,n){return new Proxy(o,new wT(n,!1))}function bn(o,n){return new Proxy(o,new Bt(new Proxy(o.table,new wT(n,!1))))}function Zf(o,n){return new h.Aliased(KT(o.sql,n),o.fieldAlias)}function KT(o,n){return R.join(o.queryChunks.map((t)=>{if(X(t,Xo))return bn(t,n);if(X(t,h))return KT(t,n);if(X(t,h.Aliased))return Zf(t,n);return t}))}class OS extends Error{static[J]="DrizzleError";constructor({message:o,cause:n}){super(o);this.name="DrizzleError",this.cause=n}}class Pf extends OS{static[J]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}function fn(o,n){if(MM(n)&&!pf(o)&&!X(o,Fn)&&!X(o,sn)&&!X(o,Xo)&&!X(o,L)&&!X(o,Sn))return new Fn(o,n);return o}var Ct=(o,n)=>{return R`${o} = ${fn(n,o)}`},$M=(o,n)=>{return R`${o} <> ${fn(n,o)}`};function XT(...o){let n=o.filter((t)=>t!==void 0);if(n.length===0)return;if(n.length===1)return new h(n);return new h([new ho("("),R.join(n,new ho(" and ")),new ho(")")])}function JM(...o){let n=o.filter((t)=>t!==void 0);if(n.length===0)return;if(n.length===1)return new h(n);return new h([new ho("("),R.join(n,new ho(" or ")),new ho(")")])}function RM(o){return R`not ${o}`}var WM=(o,n)=>{return R`${o} > ${fn(n,o)}`},OM=(o,n)=>{return R`${o} >= ${fn(n,o)}`},_M=(o,n)=>{return R`${o} < ${fn(n,o)}`},wM=(o,n)=>{return R`${o} <= ${fn(n,o)}`};function KM(o,n){if(Array.isArray(n)){if(n.length===0)return R`false`;return R`${o} in ${n.map((t)=>fn(t,o))}`}return R`${o} in ${fn(n,o)}`}function XM(o,n){if(Array.isArray(n)){if(n.length===0)return R`true`;return R`${o} not in ${n.map((t)=>fn(t,o))}`}return R`${o} not in ${fn(n,o)}`}function EM(o){return R`${o} is null`}function YM(o){return R`${o} is not null`}function GM(o){return R`exists ${o}`}function zM(o){return R`not exists ${o}`}function HM(o,n,t){return R`${o} between ${fn(n,o)} and ${fn(t,o)}`}function mM(o,n,t){return R`${o} not between ${fn(n,o)} and ${fn(t,o)}`}function QM(o,n){return R`${o} like ${n}`}function DM(o,n){return R`${o} not like ${n}`}function UM(o,n){return R`${o} ilike ${n}`}function VM(o,n){return R`${o} not ilike ${n}`}function rM(o){return R`${o} asc`}function BM(o){return R`${o} desc`}class CM{static[J]="ConsoleLogWriter";write(o){console.log(o)}}class ef{static[J]="DefaultLogger";writer;constructor(o){this.writer=o?.writer??new CM}logQuery(o,n){let t=n.map((S)=>{try{return JSON.stringify(S)}catch{return String(S)}}),T=t.length?` -- params: [${t.join(", ")}]`:"";this.writer.write(`Query: ${o}${T}`)}}class lf{static[J]="NoopLogger";logQuery(){}}class so{static[J]="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 LM(o,n,t){let T={},S=o.reduce((f,{path:y,field:A},M)=>{let F;if(X(A,Xo))F=A;else if(X(A,h))F=A.decoder;else F=A.sql.decoder;let k=f;for(let[W,O]of y.entries())if(W<y.length-1){if(!(O in k))k[O]={};k=k[O]}else{let E=n[M],Q=k[O]=E===null?null:F.mapFromDriverValue(E);if(t&&X(A,Xo)&&y.length===2){let z=y[0];if(!(z in T))T[z]=Q===null?On(A.table):!1;else if(typeof T[z]==="string"&&T[z]!==On(A.table))T[z]=!1}}return f},{});if(t&&Object.keys(T).length>0){for(let[f,y]of Object.entries(T))if(typeof y==="string"&&!t[y])S[f]=null}return S}function _n(o,n){return Object.entries(o).reduce((t,[T,S])=>{if(typeof T!=="string")return t;let f=n?[...n,T]:[T];if(X(S,Xo)||X(S,h)||X(S,h.Aliased))t.push({path:f,field:S});else if(X(S,L))t.push(..._n(S[L.Symbol.Columns],f));else t.push(..._n(S,f));return t},[])}function gf(o,n){let t=Object.keys(o),T=Object.keys(n);if(t.length!==T.length)return!1;for(let[S,f]of t.entries())if(f!==T[S])return!1;return!0}function _S(o,n){let t=Object.entries(n).filter(([,T])=>T!==void 0).map(([T,S])=>{if(X(S,h))return[T,S];else return[T,new Fn(S,o[L.Symbol.Columns][T])]});if(t.length===0)throw new Error("No values to set");return Object.fromEntries(t)}function IM(o,n){for(let t of n)for(let T of Object.getOwnPropertyNames(t.prototype)){if(T==="constructor")continue;Object.defineProperty(o.prototype,T,Object.getOwnPropertyDescriptor(t.prototype,T)||Object.create(null))}}function jM(o){return o[L.Symbol.Columns]}function df(o){return X(o,xo)?o._.alias:X(o,Sn)?o[Do].name:X(o,h)?void 0:o[L.Symbol.IsAlias]?o[L.Symbol.Name]:o[L.Symbol.BaseName]}function Ao(o,n){return{name:typeof o==="string"&&o.length>0?o:"",config:typeof o==="object"?o:n}}function bM(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 ot extends N{static[J]="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 NM extends ot{static[J]="PgBigInt53Builder";constructor(o){super(o,"number","PgBigInt53")}build(o){return new hM(o,this.config)}}class hM extends r{static[J]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(o){if(typeof o==="number")return o;return Number(o)}}class cM extends ot{static[J]="PgBigInt64Builder";constructor(o){super(o,"bigint","PgBigInt64")}build(o){return new xM(o,this.config)}}class xM extends r{static[J]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(o){return BigInt(o)}}function iM(o,n){let{name:t,config:T}=Ao(o,n);if(T.mode==="number")return new NM(t);return new cM(t)}class vM extends N{static[J]="PgBigSerial53Builder";constructor(o){super(o,"number","PgBigSerial53");this.config.hasDefault=!0,this.config.notNull=!0}build(o){return new pM(o,this.config)}}class pM extends r{static[J]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(o){if(typeof o==="number")return o;return Number(o)}}class qM extends N{static[J]="PgBigSerial64Builder";constructor(o){super(o,"bigint","PgBigSerial64");this.config.hasDefault=!0}build(o){return new ZM(o,this.config)}}class ZM extends r{static[J]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(o){return BigInt(o)}}function PM(o,n){let{name:t,config:T}=Ao(o,n);if(T.mode==="number")return new vM(t);return new qM(t)}class eM extends N{static[J]="PgBooleanBuilder";constructor(o){super(o,"boolean","PgBoolean")}build(o){return new lM(o,this.config)}}class lM extends r{static[J]="PgBoolean";getSQLType(){return"boolean"}}function ET(o){return new eM(o??"")}class gM extends N{static[J]="PgCharBuilder";constructor(o,n){super(o,"string","PgChar");this.config.length=n.length,this.config.enumValues=n.enum}build(o){return new dM(o,this.config)}}class dM extends r{static[J]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}}function uM(o,n={}){let{name:t,config:T}=Ao(o,n);return new gM(t,T)}class aM extends N{static[J]="PgCidrBuilder";constructor(o){super(o,"string","PgCidr")}build(o){return new sM(o,this.config)}}class sM extends r{static[J]="PgCidr";getSQLType(){return"cidr"}}function oF(o){return new aM(o??"")}class nF extends N{static[J]="PgCustomColumnBuilder";constructor(o,n,t){super(o,"custom","PgCustomColumn");this.config.fieldConfig=n,this.config.customTypeParams=t}build(o){return new tF(o,this.config)}}class tF extends r{static[J]="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 TF(o){return(n,t)=>{let{name:T,config:S}=Ao(n,t);return new nF(T,S,o)}}class Zn extends N{static[J]="PgDateColumnBaseBuilder";defaultNow(){return this.default(R`now()`)}}class SF extends Zn{static[J]="PgDateBuilder";constructor(o){super(o,"date","PgDate")}build(o){return new wS(o,this.config)}}class wS extends r{static[J]="PgDate";getSQLType(){return"date"}mapFromDriverValue(o){return new Date(o)}mapToDriverValue(o){return o.toISOString()}}class fF extends Zn{static[J]="PgDateStringBuilder";constructor(o){super(o,"string","PgDateString")}build(o){return new KS(o,this.config)}}class KS extends r{static[J]="PgDateString";getSQLType(){return"date"}}function yF(o,n){let{name:t,config:T}=Ao(o,n);if(T?.mode==="date")return new SF(t);return new fF(t)}class AF extends N{static[J]="PgDoublePrecisionBuilder";constructor(o){super(o,"number","PgDoublePrecision")}build(o){return new MF(o,this.config)}}class MF extends r{static[J]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(o){if(typeof o==="string")return Number.parseFloat(o);return o}}function FF(o){return new AF(o??"")}class kF extends N{static[J]="PgInetBuilder";constructor(o){super(o,"string","PgInet")}build(o){return new $F(o,this.config)}}class $F extends r{static[J]="PgInet";getSQLType(){return"inet"}}function JF(o){return new kF(o??"")}class RF extends ot{static[J]="PgIntegerBuilder";constructor(o){super(o,"number","PgInteger")}build(o){return new WF(o,this.config)}}class WF extends r{static[J]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(o){if(typeof o==="string")return Number.parseInt(o);return o}}function XS(o){return new RF(o??"")}class OF extends N{static[J]="PgIntervalBuilder";constructor(o,n){super(o,"string","PgInterval");this.config.intervalConfig=n}build(o){return new _F(o,this.config)}}class _F extends r{static[J]="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 wF(o,n={}){let{name:t,config:T}=Ao(o,n);return new OF(t,T)}class KF extends N{static[J]="PgJsonBuilder";constructor(o){super(o,"json","PgJson")}build(o){return new ES(o,this.config)}}class ES extends r{static[J]="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 XF(o){return new KF(o??"")}class EF extends N{static[J]="PgJsonbBuilder";constructor(o){super(o,"json","PgJsonb")}build(o){return new YS(o,this.config)}}class YS extends r{static[J]="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 YF(o){return new EF(o??"")}class GF extends N{static[J]="PgLineBuilder";constructor(o){super(o,"array","PgLine")}build(o){return new zF(o,this.config)}}class zF extends r{static[J]="PgLine";getSQLType(){return"line"}mapFromDriverValue(o){let[n,t,T]=o.slice(1,-1).split(",");return[Number.parseFloat(n),Number.parseFloat(t),Number.parseFloat(T)]}mapToDriverValue(o){return`{${o[0]},${o[1]},${o[2]}}`}}class HF extends N{static[J]="PgLineABCBuilder";constructor(o){super(o,"json","PgLineABC")}build(o){return new mF(o,this.config)}}class mF extends r{static[J]="PgLineABC";getSQLType(){return"line"}mapFromDriverValue(o){let[n,t,T]=o.slice(1,-1).split(",");return{a:Number.parseFloat(n),b:Number.parseFloat(t),c:Number.parseFloat(T)}}mapToDriverValue(o){return`{${o.a},${o.b},${o.c}}`}}function QF(o,n){let{name:t,config:T}=Ao(o,n);if(!T?.mode||T.mode==="tuple")return new GF(t);return new HF(t)}class DF extends N{static[J]="PgMacaddrBuilder";constructor(o){super(o,"string","PgMacaddr")}build(o){return new UF(o,this.config)}}class UF extends r{static[J]="PgMacaddr";getSQLType(){return"macaddr"}}function VF(o){return new DF(o??"")}class rF extends N{static[J]="PgMacaddr8Builder";constructor(o){super(o,"string","PgMacaddr8")}build(o){return new BF(o,this.config)}}class BF extends r{static[J]="PgMacaddr8";getSQLType(){return"macaddr8"}}function CF(o){return new rF(o??"")}class LF extends N{static[J]="PgNumericBuilder";constructor(o,n,t){super(o,"string","PgNumeric");this.config.precision=n,this.config.scale=t}build(o){return new GS(o,this.config)}}class GS extends r{static[J]="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 IF(o,n){let{name:t,config:T}=Ao(o,n);return new LF(t,T?.precision,T?.scale)}class jF extends N{static[J]="PgPointTupleBuilder";constructor(o){super(o,"array","PgPointTuple")}build(o){return new bF(o,this.config)}}class bF extends r{static[J]="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 NF extends N{static[J]="PgPointObjectBuilder";constructor(o){super(o,"json","PgPointObject")}build(o){return new hF(o,this.config)}}class hF extends r{static[J]="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 cF(o,n){let{name:t,config:T}=Ao(o,n);if(!T?.mode||T.mode==="tuple")return new jF(t);return new NF(t)}function lJ(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 xF(o,n){let t=new ArrayBuffer(8),T=new DataView(t);for(let S=0;S<8;S++)T.setUint8(S,o[n+S]);return T.getFloat64(0,!0)}function uf(o){let n=lJ(o),t=0,T=n[t];t+=1;let S=new DataView(n.buffer),f=S.getUint32(t,T===1);t+=4;let y;if(f&536870912)y=S.getUint32(t,T===1),t+=4;if((f&65535)===1){let A=xF(n,t);t+=8;let M=xF(n,t);return t+=8,[A,M]}throw new Error("Unsupported geometry type")}class iF extends N{static[J]="PgGeometryBuilder";constructor(o){super(o,"array","PgGeometry")}build(o){return new vF(o,this.config)}}class vF extends r{static[J]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(o){return uf(o)}mapToDriverValue(o){return`point(${o[0]} ${o[1]})`}}class pF extends N{static[J]="PgGeometryObjectBuilder";constructor(o){super(o,"json","PgGeometryObject")}build(o){return new qF(o,this.config)}}class qF extends r{static[J]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(o){let n=uf(o);return{x:n[0],y:n[1]}}mapToDriverValue(o){return`point(${o.x} ${o.y})`}}function ZF(o,n){let{name:t,config:T}=Ao(o,n);if(!T?.mode||T.mode==="tuple")return new iF(t);return new pF(t)}class PF extends N{static[J]="PgRealBuilder";constructor(o,n){super(o,"number","PgReal");this.config.length=n}build(o){return new eF(o,this.config)}}class eF extends r{static[J]="PgReal";constructor(o,n){super(o,n)}getSQLType(){return"real"}mapFromDriverValue=(o)=>{if(typeof o==="string")return Number.parseFloat(o);return o}}function lF(o){return new PF(o??"")}class gF extends N{static[J]="PgSerialBuilder";constructor(o){super(o,"number","PgSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(o){return new dF(o,this.config)}}class dF extends r{static[J]="PgSerial";getSQLType(){return"serial"}}function uF(o){return new gF(o??"")}class aF extends ot{static[J]="PgSmallIntBuilder";constructor(o){super(o,"number","PgSmallInt")}build(o){return new sF(o,this.config)}}class sF extends r{static[J]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=(o)=>{if(typeof o==="string")return Number(o);return o}}function ok(o){return new aF(o??"")}class nk extends N{static[J]="PgSmallSerialBuilder";constructor(o){super(o,"number","PgSmallSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(o){return new tk(o,this.config)}}class tk extends r{static[J]="PgSmallSerial";getSQLType(){return"smallserial"}}function Tk(o){return new nk(o??"")}class Sk extends N{static[J]="PgTextBuilder";constructor(o,n){super(o,"string","PgText");this.config.enumValues=n.enum}build(o){return new fk(o,this.config)}}class fk extends r{static[J]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function yk(o,n={}){let{name:t,config:T}=Ao(o,n);return new Sk(t,T)}class Ak extends Zn{constructor(o,n,t){super(o,"string","PgTime");this.withTimezone=n,this.precision=t,this.config.withTimezone=n,this.config.precision=t}static[J]="PgTimeBuilder";build(o){return new zS(o,this.config)}}class zS extends r{static[J]="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 Mk(o,n={}){let{name:t,config:T}=Ao(o,n);return new Ak(t,T.withTimezone??!1,T.precision)}class Fk extends Zn{static[J]="PgTimestampBuilder";constructor(o,n,t){super(o,"date","PgTimestamp");this.config.withTimezone=n,this.config.precision=t}build(o){return new HS(o,this.config)}}class HS extends r{static[J]="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 kk extends Zn{static[J]="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 r{static[J]="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:T}=Ao(o,n);if(T?.mode==="string")return new kk(t,T.withTimezone??!1,T.precision);return new Fk(t,T?.withTimezone??!1,T?.precision)}class $k extends N{static[J]="PgUUIDBuilder";constructor(o){super(o,"string","PgUUID")}defaultRandom(){return this.default(R`gen_random_uuid()`)}build(o){return new QS(o,this.config)}}class QS extends r{static[J]="PgUUID";getSQLType(){return"uuid"}}function kn(o){return new $k(o??"")}class Jk extends N{static[J]="PgVarcharBuilder";constructor(o,n){super(o,"string","PgVarchar");this.config.length=n.length,this.config.enumValues=n.enum}build(o){return new Rk(o,this.config)}}class Rk extends r{static[J]="PgVarchar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"varchar":`varchar(${this.length})`}}function io(o,n={}){let{name:t,config:T}=Ao(o,n);return new Jk(t,T)}class Wk extends N{static[J]="PgBinaryVectorBuilder";constructor(o,n){super(o,"string","PgBinaryVector");this.config.dimensions=n.dimensions}build(o){return new Ok(o,this.config)}}class Ok extends r{static[J]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}}function _k(o,n){let{name:t,config:T}=Ao(o,n);return new Wk(t,T)}class wk extends N{static[J]="PgHalfVectorBuilder";constructor(o,n){super(o,"array","PgHalfVector");this.config.dimensions=n.dimensions}build(o){return new Kk(o,this.config)}}class Kk extends r{static[J]="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 Xk(o,n){let{name:t,config:T}=Ao(o,n);return new wk(t,T)}class Ek extends N{static[J]="PgSparseVectorBuilder";constructor(o,n){super(o,"string","PgSparseVector");this.config.dimensions=n.dimensions}build(o){return new Yk(o,this.config)}}class Yk extends r{static[J]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function Gk(o,n){let{name:t,config:T}=Ao(o,n);return new Ek(t,T)}class zk extends N{static[J]="PgVectorBuilder";constructor(o,n){super(o,"array","PgVector");this.config.dimensions=n.dimensions}build(o){return new Hk(o,this.config)}}class Hk extends r{static[J]="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 mk(o,n){let{name:t,config:T}=Ao(o,n);return new zk(t,T)}function Qk(){return{bigint:iM,bigserial:PM,boolean:ET,char:uM,cidr:oF,customType:TF,date:yF,doublePrecision:FF,inet:JF,integer:XS,interval:wF,json:XF,jsonb:YF,line:QF,macaddr:VF,macaddr8:CF,numeric:IF,point:cF,geometry:ZF,real:lF,serial:uF,smallint:ok,smallserial:Tk,text:yk,time:Mk,timestamp:Dn,uuid:kn,varchar:io,bit:_k,halfvec:Xk,sparsevec:Gk,vector:mk}}var af=Symbol.for("drizzle:PgInlineForeignKeys"),Dk=Symbol.for("drizzle:EnableRLS");class wn extends L{static[J]="PgTable";static Symbol=Object.assign({},L.Symbol,{InlineForeignKeys:af,EnableRLS:Dk});[af]=[];[Dk]=!1;[L.Symbol.ExtraConfigBuilder]=void 0}function gJ(o,n,t,T,S=o){let f=new wn(o,T,S),y=typeof n==="function"?n(Qk()):n,A=Object.fromEntries(Object.entries(y).map(([k,W])=>{let O=W;O.setName(k);let E=O.build(f);return f[af].push(...O.buildForeignKeys(E,f)),[k,E]})),M=Object.fromEntries(Object.entries(y).map(([k,W])=>{let O=W;O.setName(k);let E=O.buildExtraConfigColumn(f);return[k,E]})),F=Object.assign(f,A);if(F[L.Symbol.Columns]=A,F[L.Symbol.ExtraConfigColumns]=M,t)F[wn.Symbol.ExtraConfigBuilder]=t;return Object.assign(F,{enableRLS:()=>{return F[wn.Symbol.EnableRLS]=!0,F}})}var nt=(o,n,t)=>{return gJ(o,n,t,void 0)};function Uk(...o){if(o[0].columns)return new YT(o[0].columns,o[0].name);return new YT(o)}class YT{static[J]="PgPrimaryKeyBuilder";columns;name;constructor(o,n){this.columns=o,this.name=n}build(o){return new Vk(o,this.columns,this.name)}}class Vk{constructor(o,n,t){this.table=o,this.columns=n,this.name=t}static[J]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[wn.Symbol.Name]}_${this.columns.map((o)=>o.name).join("_")}_pk`}}class sf{constructor(o,n,t){this.sourceTable=o,this.referencedTable=n,this.relationName=t,this.referencedTableName=n[L.Symbol.Name]}static[J]="Relation";referencedTableName;fieldName}class rk{constructor(o,n){this.table=o,this.config=n}static[J]="Relations"}class tt extends sf{constructor(o,n,t,T){super(o,n,t?.relationName);this.config=t,this.isNullable=T}static[J]="One";withFieldName(o){let n=new tt(this.sourceTable,this.referencedTable,this.config,this.isNullable);return n.fieldName=o,n}}class GT extends sf{constructor(o,n,t){super(o,n,t?.relationName);this.config=t}static[J]="Many";withFieldName(o){let n=new GT(this.sourceTable,this.referencedTable,this.config);return n.fieldName=o,n}}function Bk(){return{and:XT,between:HM,eq:Ct,exists:GM,gt:WM,gte:OM,ilike:UM,inArray:KM,isNull:EM,isNotNull:YM,like:QM,lt:_M,lte:wM,ne:$M,not:RM,notBetween:mM,notExists:zM,notLike:DM,notIlike:VM,notInArray:XM,or:JM,sql:R}}function Ck(){return{sql:R,asc:rM,desc:BM}}function Lk(o,n){if(Object.keys(o).length===1&&"default"in o&&!X(o.default,L))o=o.default;let t={},T={},S={};for(let[f,y]of Object.entries(o))if(X(y,L)){let A=kt(y),M=T[A];t[A]=f,S[f]={tsName:f,dbName:y[L.Symbol.Name],schema:y[L.Symbol.Schema],columns:y[L.Symbol.Columns],relations:M?.relations??{},primaryKey:M?.primaryKey??[]};for(let k of Object.values(y[L.Symbol.Columns]))if(k.primary)S[f].primaryKey.push(k);let F=y[L.Symbol.ExtraConfigBuilder]?.(y[L.Symbol.ExtraConfigColumns]);if(F){for(let k of Object.values(F))if(X(k,YT))S[f].primaryKey.push(...k.columns)}}else if(X(y,rk)){let A=kt(y.table),M=t[A],F=y.config(n(y.table)),k;for(let[W,O]of Object.entries(F))if(M){let E=S[M];if(E.relations[W]=O,k)E.primaryKey.push(...k)}else{if(!(A in T))T[A]={relations:{},primaryKey:k};T[A].relations[W]=O}}return{tables:S,tableNamesMap:t}}function dJ(o){return function n(t,T){return new tt(o,t,T,T?.fields.reduce((S,f)=>S&&f.notNull,!0)??!1)}}function uJ(o){return function n(t,T){return new GT(o,t,T)}}function Ik(o,n,t){if(X(t,tt)&&t.config)return{fields:t.config.fields,references:t.config.references};let T=n[kt(t.referencedTable)];if(!T)throw new Error(`Table "${t.referencedTable[L.Symbol.Name]}" not found in schema`);let S=o[T];if(!S)throw new Error(`Table "${T}" not found in schema`);let f=t.sourceTable,y=n[kt(f)];if(!y)throw new Error(`Table "${f[L.Symbol.Name]}" not found in schema`);let A=[];for(let M of Object.values(S.relations))if(t.relationName&&t!==M&&M.relationName===t.relationName||!t.relationName&&M.referencedTable===t.sourceTable)A.push(M);if(A.length>1)throw t.relationName?new Error(`There are multiple relations with name "${t.relationName}" in table "${T}"`):new Error(`There are multiple relations between "${T}" and "${t.sourceTable[L.Symbol.Name]}". Please specify relation name`);if(A[0]&&X(A[0],tt)&&A[0].config)return{fields:A[0].config.references,references:A[0].config.fields};throw new Error(`There is not enough information to infer relation "${y}.${t.fieldName}"`)}function jk(o){return{one:dJ(o),many:uJ(o)}}function DS(o,n,t,T,S=(f)=>f){let f={};for(let[y,A]of T.entries())if(A.isJson){let M=n.relations[A.tsKey],F=t[y],k=typeof F==="string"?JSON.parse(F):F;f[A.tsKey]=X(M,tt)?k&&DS(o,o[A.relationTableTsKey],k,A.selection,S):k.map((W)=>DS(o,o[A.relationTableTsKey],W,A.selection,S))}else{let M=S(t[y]),F=A.field,k;if(X(F,Xo))k=F;else if(X(F,h))k=F.decoder;else k=F.sql.decoder;f[A.tsKey]=M===null?null:k.mapFromDriverValue(M)}return f}import{readFileSync as gk}from"fs";import{resolve as fy}from"path";var $o;(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 f={};for(let y of S)f[y]=y;return f},o.getValidEnumValues=(S)=>{let f=o.objectKeys(S).filter((A)=>typeof S[S[A]]!=="number"),y={};for(let A of f)y[A]=S[A];return o.objectValues(y)},o.objectValues=(S)=>{return o.objectKeys(S).map(function(f){return S[f]})},o.objectKeys=typeof Object.keys==="function"?(S)=>Object.keys(S):(S)=>{let f=[];for(let y in S)if(Object.prototype.hasOwnProperty.call(S,y))f.push(y);return f},o.find=(S,f)=>{for(let y of S)if(f(y))return y;return},o.isInteger=typeof Number.isInteger==="function"?(S)=>Number.isInteger(S):(S)=>typeof S==="number"&&isFinite(S)&&Math.floor(S)===S;function T(S,f=" | "){return S.map((y)=>typeof y==="string"?`'${y}'`:y).join(f)}o.joinValues=T,o.jsonStringifyReplacer=(S,f)=>{if(typeof f==="bigint")return f.toString();return f}})($o||($o={}));var ny;(function(o){o.mergeShapes=(n,t)=>{return{...n,...t}}})(ny||(ny={}));var I=$o.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Tt=(o)=>{switch(typeof o){case"undefined":return I.undefined;case"string":return I.string;case"number":return isNaN(o)?I.nan:I.number;case"boolean":return I.boolean;case"function":return I.function;case"bigint":return I.bigint;case"symbol":return I.symbol;case"object":if(Array.isArray(o))return I.array;if(o===null)return I.null;if(o.then&&typeof o.then==="function"&&o.catch&&typeof o.catch==="function")return I.promise;if(typeof Map!=="undefined"&&o instanceof Map)return I.map;if(typeof Set!=="undefined"&&o instanceof Set)return I.set;if(typeof Date!=="undefined"&&o instanceof Date)return I.date;return I.object;default:return I.unknown}},m=$o.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"]),aJ=(o)=>{return JSON.stringify(o,null,2).replace(/"([^"]+)":/g,"$1:")};class $n extends Error{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}get errors(){return this.issues}format(o){let n=o||function(S){return S.message},t={_errors:[]},T=(S)=>{for(let f of S.issues)if(f.code==="invalid_union")f.unionErrors.map(T);else if(f.code==="invalid_return_type")T(f.returnTypeError);else if(f.code==="invalid_arguments")T(f.argumentsError);else if(f.path.length===0)t._errors.push(n(f));else{let y=t,A=0;while(A<f.path.length){let M=f.path[A];if(A!==f.path.length-1)y[M]=y[M]||{_errors:[]};else y[M]=y[M]||{_errors:[]},y[M]._errors.push(n(f));y=y[M],A++}}};return T(this),t}static assert(o){if(!(o instanceof $n))throw new Error(`Not a ZodError: ${o}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,$o.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(o=(n)=>n.message){let n={},t=[];for(let T of this.issues)if(T.path.length>0)n[T.path[0]]=n[T.path[0]]||[],n[T.path[0]].push(o(T));else t.push(o(T));return{formErrors:t,fieldErrors:n}}get formErrors(){return this.flatten()}}$n.create=(o)=>{return new $n(o)};var bt=(o,n)=>{let t;switch(o.code){case m.invalid_type:if(o.received===I.undefined)t="Required";else t=`Expected ${o.expected}, received ${o.received}`;break;case m.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(o.expected,$o.jsonStringifyReplacer)}`;break;case m.unrecognized_keys:t=`Unrecognized key(s) in object: ${$o.joinValues(o.keys,", ")}`;break;case m.invalid_union:t="Invalid input";break;case m.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${$o.joinValues(o.options)}`;break;case m.invalid_enum_value:t=`Invalid enum value. Expected ${$o.joinValues(o.options)}, received '${o.received}'`;break;case m.invalid_arguments:t="Invalid function arguments";break;case m.invalid_return_type:t="Invalid function return type";break;case m.invalid_date:t="Invalid date";break;case m.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 $o.assertNever(o.validation);else if(o.validation!=="regex")t=`Invalid ${o.validation}`;else t="Invalid";break;case m.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 m.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 m.custom:t="Invalid input";break;case m.invalid_intersection_types:t="Intersection results could not be merged";break;case m.not_multiple_of:t=`Number must be a multiple of ${o.multipleOf}`;break;case m.not_finite:t="Number must be finite";break;default:t=n.defaultError,$o.assertNever(o)}return{message:t}},hk=bt;function sJ(o){hk=o}function US(){return hk}var VS=(o)=>{let{data:n,path:t,errorMaps:T,issueData:S}=o,f=[...t,...S.path||[]],y={...S,path:f};if(S.message!==void 0)return{...S,path:f,message:S.message};let A="",M=T.filter((F)=>!!F).slice().reverse();for(let F of M)A=F(y,{data:n,defaultError:A}).message;return{...S,path:f,message:A}},oR=[];function C(o,n){let t=US(),T=VS({issueData:n,data:o.data,path:o.path,errorMaps:[o.common.contextualErrorMap,o.schemaErrorMap,t,t===bt?void 0:bt].filter((S)=>!!S)});o.common.issues.push(T)}class lo{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 T of n){if(T.status==="aborted")return u;if(T.status==="dirty")o.dirty();t.push(T.value)}return{status:o.value,value:t}}static async mergeObjectAsync(o,n){let t=[];for(let T of n){let S=await T.key,f=await T.value;t.push({key:S,value:f})}return lo.mergeObjectSync(o,t)}static mergeObjectSync(o,n){let t={};for(let T of n){let{key:S,value:f}=T;if(S.status==="aborted")return u;if(f.status==="aborted")return u;if(S.status==="dirty")o.dirty();if(f.status==="dirty")o.dirty();if(S.value!=="__proto__"&&(typeof f.value!=="undefined"||T.alwaysSet))t[S.value]=f.value}return{status:o.value,value:t}}}var u=Object.freeze({status:"aborted"}),It=(o)=>({status:"dirty",value:o}),on=(o)=>({status:"valid",value:o}),ty=(o)=>o.status==="aborted",Ty=(o)=>o.status==="dirty",mT=(o)=>o.status==="valid",QT=(o)=>typeof Promise!=="undefined"&&o instanceof Promise;function rS(o,n,t,T){if(t==="a"&&!T)throw new TypeError("Private accessor was defined without a getter");if(typeof n==="function"?o!==n||!T:!n.has(o))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?T:t==="a"?T.call(o):T?T.value:n.get(o)}function ck(o,n,t,T,S){if(T==="m")throw new TypeError("Private method is not writable");if(T==="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 T==="a"?S.call(o,t):S?S.value=t:n.set(o,t),t}var q;(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})(q||(q={}));var zT,HT;class Bn{constructor(o,n,t,T){this._cachedPath=[],this.parent=o,this.data=n,this._path=t,this._key=T}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 bk=(o,n)=>{if(mT(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 $n(o.common.issues);return this._error=t,this._error}}}};function to(o){if(!o)return{};let{errorMap:n,invalid_type_error:t,required_error:T,description:S}=o;if(n&&(t||T))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:(y,A)=>{var M,F;let{message:k}=o;if(y.code==="invalid_enum_value")return{message:k!==null&&k!==void 0?k:A.defaultError};if(typeof A.data==="undefined")return{message:(M=k!==null&&k!==void 0?k:T)!==null&&M!==void 0?M:A.defaultError};if(y.code!=="invalid_type")return{message:A.defaultError};return{message:(F=k!==null&&k!==void 0?k:t)!==null&&F!==void 0?F:A.defaultError}},description:S}}class To{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)}get description(){return this._def.description}_getType(o){return Tt(o.data)}_getOrReturnCtx(o,n){return n||{common:o.parent.common,data:o.data,parsedType:Tt(o.data),schemaErrorMap:this._def.errorMap,path:o.path,parent:o.parent}}_processInputParams(o){return{status:new lo,ctx:{common:o.parent.common,data:o.data,parsedType:Tt(o.data),schemaErrorMap:this._def.errorMap,path:o.path,parent:o.parent}}}_parseSync(o){let n=this._parse(o);if(QT(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 T={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:Tt(o)},S=this._parseSync({data:o,path:T.path,parent:T});return bk(T,S)}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:Tt(o)},T=this._parse({data:o,path:t.path,parent:t}),S=await(QT(T)?T:Promise.resolve(T));return bk(t,S)}refine(o,n){let t=(T)=>{if(typeof n==="string"||typeof n==="undefined")return{message:n};else if(typeof n==="function")return n(T);else return n};return this._refinement((T,S)=>{let f=o(T),y=()=>S.addIssue({code:m.custom,...t(T)});if(typeof Promise!=="undefined"&&f instanceof Promise)return f.then((A)=>{if(!A)return y(),!1;else return!0});if(!f)return y(),!1;else return!0})}refinement(o,n){return this._refinement((t,T)=>{if(!o(t))return T.addIssue(typeof n==="function"?n(t,T):n),!1;else return!0})}_refinement(o){return new Kn({schema:this,typeName:g.ZodEffects,effect:{type:"refinement",refinement:o}})}superRefine(o){return this._refinement(o)}optional(){return rn.create(this,this._def)}nullable(){return en.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Vn.create(this,this._def)}promise(){return Wt.create(this,this._def)}or(o){return xt.create([this,o],this._def)}and(o){return it.create(this,o,this._def)}transform(o){return new Kn({...to(this._def),schema:this,typeName:g.ZodEffects,effect:{type:"transform",transform:o}})}default(o){let n=typeof o==="function"?o:()=>o;return new Zt({...to(this._def),innerType:this,defaultValue:n,typeName:g.ZodDefault})}brand(){return new CS({typeName:g.ZodBranded,type:this,...to(this._def)})}catch(o){let n=typeof o==="function"?o:()=>o;return new Pt({...to(this._def),innerType:this,catchValue:n,typeName:g.ZodCatch})}describe(o){return new this.constructor({...this._def,description:o})}pipe(o){return CT.create(this,o)}readonly(){return et.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var nR=/^c[^\s-]{8,}$/i,tR=/^[0-9a-z]+$/,TR=/^[0-9A-HJKMNP-TV-Z]{26}$/,SR=/^[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,fR=/^[a-z0-9_-]{21}$/i,yR=/^[-+]?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)?)??$/,AR=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,MR="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",oy,FR=/^(?:(?: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])$/,kR=/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,$R=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,xk="((\\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])))",JR=new RegExp(`^${xk}\$`);function ik(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 RR(o){return new RegExp(`^${ik(o)}\$`)}function vk(o){let n=`${xk}T${ik(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 WR(o,n){if((n==="v4"||!n)&&FR.test(o))return!0;if((n==="v6"||!n)&&kR.test(o))return!0;return!1}class Un extends To{_parse(o){if(this._def.coerce)o.data=String(o.data);if(this._getType(o)!==I.string){let S=this._getOrReturnCtx(o);return C(S,{code:m.invalid_type,expected:I.string,received:S.parsedType}),u}let t=new lo,T=void 0;for(let S of this._def.checks)if(S.kind==="min"){if(o.data.length<S.value)T=this._getOrReturnCtx(o,T),C(T,{code:m.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)T=this._getOrReturnCtx(o,T),C(T,{code:m.too_big,maximum:S.value,type:"string",inclusive:!0,exact:!1,message:S.message}),t.dirty()}else if(S.kind==="length"){let f=o.data.length>S.value,y=o.data.length<S.value;if(f||y){if(T=this._getOrReturnCtx(o,T),f)C(T,{code:m.too_big,maximum:S.value,type:"string",inclusive:!0,exact:!0,message:S.message});else if(y)C(T,{code:m.too_small,minimum:S.value,type:"string",inclusive:!0,exact:!0,message:S.message});t.dirty()}}else if(S.kind==="email"){if(!AR.test(o.data))T=this._getOrReturnCtx(o,T),C(T,{validation:"email",code:m.invalid_string,message:S.message}),t.dirty()}else if(S.kind==="emoji"){if(!oy)oy=new RegExp(MR,"u");if(!oy.test(o.data))T=this._getOrReturnCtx(o,T),C(T,{validation:"emoji",code:m.invalid_string,message:S.message}),t.dirty()}else if(S.kind==="uuid"){if(!SR.test(o.data))T=this._getOrReturnCtx(o,T),C(T,{validation:"uuid",code:m.invalid_string,message:S.message}),t.dirty()}else if(S.kind==="nanoid"){if(!fR.test(o.data))T=this._getOrReturnCtx(o,T),C(T,{validation:"nanoid",code:m.invalid_string,message:S.message}),t.dirty()}else if(S.kind==="cuid"){if(!nR.test(o.data))T=this._getOrReturnCtx(o,T),C(T,{validation:"cuid",code:m.invalid_string,message:S.message}),t.dirty()}else if(S.kind==="cuid2"){if(!tR.test(o.data))T=this._getOrReturnCtx(o,T),C(T,{validation:"cuid2",code:m.invalid_string,message:S.message}),t.dirty()}else if(S.kind==="ulid"){if(!TR.test(o.data))T=this._getOrReturnCtx(o,T),C(T,{validation:"ulid",code:m.invalid_string,message:S.message}),t.dirty()}else if(S.kind==="url")try{new URL(o.data)}catch(f){T=this._getOrReturnCtx(o,T),C(T,{validation:"url",code:m.invalid_string,message:S.message}),t.dirty()}else if(S.kind==="regex"){if(S.regex.lastIndex=0,!S.regex.test(o.data))T=this._getOrReturnCtx(o,T),C(T,{validation:"regex",code:m.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))T=this._getOrReturnCtx(o,T),C(T,{code:m.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))T=this._getOrReturnCtx(o,T),C(T,{code:m.invalid_string,validation:{startsWith:S.value},message:S.message}),t.dirty()}else if(S.kind==="endsWith"){if(!o.data.endsWith(S.value))T=this._getOrReturnCtx(o,T),C(T,{code:m.invalid_string,validation:{endsWith:S.value},message:S.message}),t.dirty()}else if(S.kind==="datetime"){if(!vk(S).test(o.data))T=this._getOrReturnCtx(o,T),C(T,{code:m.invalid_string,validation:"datetime",message:S.message}),t.dirty()}else if(S.kind==="date"){if(!JR.test(o.data))T=this._getOrReturnCtx(o,T),C(T,{code:m.invalid_string,validation:"date",message:S.message}),t.dirty()}else if(S.kind==="time"){if(!RR(S).test(o.data))T=this._getOrReturnCtx(o,T),C(T,{code:m.invalid_string,validation:"time",message:S.message}),t.dirty()}else if(S.kind==="duration"){if(!yR.test(o.data))T=this._getOrReturnCtx(o,T),C(T,{validation:"duration",code:m.invalid_string,message:S.message}),t.dirty()}else if(S.kind==="ip"){if(!WR(o.data,S.version))T=this._getOrReturnCtx(o,T),C(T,{validation:"ip",code:m.invalid_string,message:S.message}),t.dirty()}else if(S.kind==="base64"){if(!$R.test(o.data))T=this._getOrReturnCtx(o,T),C(T,{validation:"base64",code:m.invalid_string,message:S.message}),t.dirty()}else $o.assertNever(S);return{status:t.value,value:o.data}}_regex(o,n,t){return this.refinement((T)=>o.test(T),{validation:n,code:m.invalid_string,...q.errToObj(t)})}_addCheck(o){return new Un({...this._def,checks:[...this._def.checks,o]})}email(o){return this._addCheck({kind:"email",...q.errToObj(o)})}url(o){return this._addCheck({kind:"url",...q.errToObj(o)})}emoji(o){return this._addCheck({kind:"emoji",...q.errToObj(o)})}uuid(o){return this._addCheck({kind:"uuid",...q.errToObj(o)})}nanoid(o){return this._addCheck({kind:"nanoid",...q.errToObj(o)})}cuid(o){return this._addCheck({kind:"cuid",...q.errToObj(o)})}cuid2(o){return this._addCheck({kind:"cuid2",...q.errToObj(o)})}ulid(o){return this._addCheck({kind:"ulid",...q.errToObj(o)})}base64(o){return this._addCheck({kind:"base64",...q.errToObj(o)})}ip(o){return this._addCheck({kind:"ip",...q.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,...q.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,...q.errToObj(o===null||o===void 0?void 0:o.message)})}duration(o){return this._addCheck({kind:"duration",...q.errToObj(o)})}regex(o,n){return this._addCheck({kind:"regex",regex:o,...q.errToObj(n)})}includes(o,n){return this._addCheck({kind:"includes",value:o,position:n===null||n===void 0?void 0:n.position,...q.errToObj(n===null||n===void 0?void 0:n.message)})}startsWith(o,n){return this._addCheck({kind:"startsWith",value:o,...q.errToObj(n)})}endsWith(o,n){return this._addCheck({kind:"endsWith",value:o,...q.errToObj(n)})}min(o,n){return this._addCheck({kind:"min",value:o,...q.errToObj(n)})}max(o,n){return this._addCheck({kind:"max",value:o,...q.errToObj(n)})}length(o,n){return this._addCheck({kind:"length",value:o,...q.errToObj(n)})}nonempty(o){return this.min(1,q.errToObj(o))}trim(){return new Un({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Un({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Un({...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 isBase64(){return!!this._def.checks.find((o)=>o.kind==="base64")}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}}Un.create=(o)=>{var n;return new Un({checks:[],typeName:g.ZodString,coerce:(n=o===null||o===void 0?void 0:o.coerce)!==null&&n!==void 0?n:!1,...to(o)})};function OR(o,n){let t=(o.toString().split(".")[1]||"").length,T=(n.toString().split(".")[1]||"").length,S=t>T?t:T,f=parseInt(o.toFixed(S).replace(".","")),y=parseInt(n.toFixed(S).replace(".",""));return f%y/Math.pow(10,S)}class ft extends To{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)!==I.number){let S=this._getOrReturnCtx(o);return C(S,{code:m.invalid_type,expected:I.number,received:S.parsedType}),u}let t=void 0,T=new lo;for(let S of this._def.checks)if(S.kind==="int"){if(!$o.isInteger(o.data))t=this._getOrReturnCtx(o,t),C(t,{code:m.invalid_type,expected:"integer",received:"float",message:S.message}),T.dirty()}else if(S.kind==="min"){if(S.inclusive?o.data<S.value:o.data<=S.value)t=this._getOrReturnCtx(o,t),C(t,{code:m.too_small,minimum:S.value,type:"number",inclusive:S.inclusive,exact:!1,message:S.message}),T.dirty()}else if(S.kind==="max"){if(S.inclusive?o.data>S.value:o.data>=S.value)t=this._getOrReturnCtx(o,t),C(t,{code:m.too_big,maximum:S.value,type:"number",inclusive:S.inclusive,exact:!1,message:S.message}),T.dirty()}else if(S.kind==="multipleOf"){if(OR(o.data,S.value)!==0)t=this._getOrReturnCtx(o,t),C(t,{code:m.not_multiple_of,multipleOf:S.value,message:S.message}),T.dirty()}else if(S.kind==="finite"){if(!Number.isFinite(o.data))t=this._getOrReturnCtx(o,t),C(t,{code:m.not_finite,message:S.message}),T.dirty()}else $o.assertNever(S);return{status:T.value,value:o.data}}gte(o,n){return this.setLimit("min",o,!0,q.toString(n))}gt(o,n){return this.setLimit("min",o,!1,q.toString(n))}lte(o,n){return this.setLimit("max",o,!0,q.toString(n))}lt(o,n){return this.setLimit("max",o,!1,q.toString(n))}setLimit(o,n,t,T){return new ft({...this._def,checks:[...this._def.checks,{kind:o,value:n,inclusive:t,message:q.toString(T)}]})}_addCheck(o){return new ft({...this._def,checks:[...this._def.checks,o]})}int(o){return this._addCheck({kind:"int",message:q.toString(o)})}positive(o){return this._addCheck({kind:"min",value:0,inclusive:!1,message:q.toString(o)})}negative(o){return this._addCheck({kind:"max",value:0,inclusive:!1,message:q.toString(o)})}nonpositive(o){return this._addCheck({kind:"max",value:0,inclusive:!0,message:q.toString(o)})}nonnegative(o){return this._addCheck({kind:"min",value:0,inclusive:!0,message:q.toString(o)})}multipleOf(o,n){return this._addCheck({kind:"multipleOf",value:o,message:q.toString(n)})}finite(o){return this._addCheck({kind:"finite",message:q.toString(o)})}safe(o){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:q.toString(o)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:q.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"&&$o.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)}}ft.create=(o)=>{return new ft({checks:[],typeName:g.ZodNumber,coerce:(o===null||o===void 0?void 0:o.coerce)||!1,...to(o)})};class yt extends To{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(o){if(this._def.coerce)o.data=BigInt(o.data);if(this._getType(o)!==I.bigint){let S=this._getOrReturnCtx(o);return C(S,{code:m.invalid_type,expected:I.bigint,received:S.parsedType}),u}let t=void 0,T=new lo;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),C(t,{code:m.too_small,type:"bigint",minimum:S.value,inclusive:S.inclusive,message:S.message}),T.dirty()}else if(S.kind==="max"){if(S.inclusive?o.data>S.value:o.data>=S.value)t=this._getOrReturnCtx(o,t),C(t,{code:m.too_big,type:"bigint",maximum:S.value,inclusive:S.inclusive,message:S.message}),T.dirty()}else if(S.kind==="multipleOf"){if(o.data%S.value!==BigInt(0))t=this._getOrReturnCtx(o,t),C(t,{code:m.not_multiple_of,multipleOf:S.value,message:S.message}),T.dirty()}else $o.assertNever(S);return{status:T.value,value:o.data}}gte(o,n){return this.setLimit("min",o,!0,q.toString(n))}gt(o,n){return this.setLimit("min",o,!1,q.toString(n))}lte(o,n){return this.setLimit("max",o,!0,q.toString(n))}lt(o,n){return this.setLimit("max",o,!1,q.toString(n))}setLimit(o,n,t,T){return new yt({...this._def,checks:[...this._def.checks,{kind:o,value:n,inclusive:t,message:q.toString(T)}]})}_addCheck(o){return new yt({...this._def,checks:[...this._def.checks,o]})}positive(o){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:q.toString(o)})}negative(o){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:q.toString(o)})}nonpositive(o){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:q.toString(o)})}nonnegative(o){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:q.toString(o)})}multipleOf(o,n){return this._addCheck({kind:"multipleOf",value:o,message:q.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}}yt.create=(o)=>{var n;return new yt({checks:[],typeName:g.ZodBigInt,coerce:(n=o===null||o===void 0?void 0:o.coerce)!==null&&n!==void 0?n:!1,...to(o)})};class Nt extends To{_parse(o){if(this._def.coerce)o.data=Boolean(o.data);if(this._getType(o)!==I.boolean){let t=this._getOrReturnCtx(o);return C(t,{code:m.invalid_type,expected:I.boolean,received:t.parsedType}),u}return on(o.data)}}Nt.create=(o)=>{return new Nt({typeName:g.ZodBoolean,coerce:(o===null||o===void 0?void 0:o.coerce)||!1,...to(o)})};class $t extends To{_parse(o){if(this._def.coerce)o.data=new Date(o.data);if(this._getType(o)!==I.date){let S=this._getOrReturnCtx(o);return C(S,{code:m.invalid_type,expected:I.date,received:S.parsedType}),u}if(isNaN(o.data.getTime())){let S=this._getOrReturnCtx(o);return C(S,{code:m.invalid_date}),u}let t=new lo,T=void 0;for(let S of this._def.checks)if(S.kind==="min"){if(o.data.getTime()<S.value)T=this._getOrReturnCtx(o,T),C(T,{code:m.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)T=this._getOrReturnCtx(o,T),C(T,{code:m.too_big,message:S.message,inclusive:!0,exact:!1,maximum:S.value,type:"date"}),t.dirty()}else $o.assertNever(S);return{status:t.value,value:new Date(o.data.getTime())}}_addCheck(o){return new $t({...this._def,checks:[...this._def.checks,o]})}min(o,n){return this._addCheck({kind:"min",value:o.getTime(),message:q.toString(n)})}max(o,n){return this._addCheck({kind:"max",value:o.getTime(),message:q.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}}$t.create=(o)=>{return new $t({checks:[],coerce:(o===null||o===void 0?void 0:o.coerce)||!1,typeName:g.ZodDate,...to(o)})};class DT extends To{_parse(o){if(this._getType(o)!==I.symbol){let t=this._getOrReturnCtx(o);return C(t,{code:m.invalid_type,expected:I.symbol,received:t.parsedType}),u}return on(o.data)}}DT.create=(o)=>{return new DT({typeName:g.ZodSymbol,...to(o)})};class ht extends To{_parse(o){if(this._getType(o)!==I.undefined){let t=this._getOrReturnCtx(o);return C(t,{code:m.invalid_type,expected:I.undefined,received:t.parsedType}),u}return on(o.data)}}ht.create=(o)=>{return new ht({typeName:g.ZodUndefined,...to(o)})};class ct extends To{_parse(o){if(this._getType(o)!==I.null){let t=this._getOrReturnCtx(o);return C(t,{code:m.invalid_type,expected:I.null,received:t.parsedType}),u}return on(o.data)}}ct.create=(o)=>{return new ct({typeName:g.ZodNull,...to(o)})};class Jt extends To{constructor(){super(...arguments);this._any=!0}_parse(o){return on(o.data)}}Jt.create=(o)=>{return new Jt({typeName:g.ZodAny,...to(o)})};class St extends To{constructor(){super(...arguments);this._unknown=!0}_parse(o){return on(o.data)}}St.create=(o)=>{return new St({typeName:g.ZodUnknown,...to(o)})};class Nn extends To{_parse(o){let n=this._getOrReturnCtx(o);return C(n,{code:m.invalid_type,expected:I.never,received:n.parsedType}),u}}Nn.create=(o)=>{return new Nn({typeName:g.ZodNever,...to(o)})};class UT extends To{_parse(o){if(this._getType(o)!==I.undefined){let t=this._getOrReturnCtx(o);return C(t,{code:m.invalid_type,expected:I.void,received:t.parsedType}),u}return on(o.data)}}UT.create=(o)=>{return new UT({typeName:g.ZodVoid,...to(o)})};class Vn extends To{_parse(o){let{ctx:n,status:t}=this._processInputParams(o),T=this._def;if(n.parsedType!==I.array)return C(n,{code:m.invalid_type,expected:I.array,received:n.parsedType}),u;if(T.exactLength!==null){let f=n.data.length>T.exactLength.value,y=n.data.length<T.exactLength.value;if(f||y)C(n,{code:f?m.too_big:m.too_small,minimum:y?T.exactLength.value:void 0,maximum:f?T.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:T.exactLength.message}),t.dirty()}if(T.minLength!==null){if(n.data.length<T.minLength.value)C(n,{code:m.too_small,minimum:T.minLength.value,type:"array",inclusive:!0,exact:!1,message:T.minLength.message}),t.dirty()}if(T.maxLength!==null){if(n.data.length>T.maxLength.value)C(n,{code:m.too_big,maximum:T.maxLength.value,type:"array",inclusive:!0,exact:!1,message:T.maxLength.message}),t.dirty()}if(n.common.async)return Promise.all([...n.data].map((f,y)=>{return T.type._parseAsync(new Bn(n,f,n.path,y))})).then((f)=>{return lo.mergeArray(t,f)});let S=[...n.data].map((f,y)=>{return T.type._parseSync(new Bn(n,f,n.path,y))});return lo.mergeArray(t,S)}get element(){return this._def.type}min(o,n){return new Vn({...this._def,minLength:{value:o,message:q.toString(n)}})}max(o,n){return new Vn({...this._def,maxLength:{value:o,message:q.toString(n)}})}length(o,n){return new Vn({...this._def,exactLength:{value:o,message:q.toString(n)}})}nonempty(o){return this.min(1,o)}}Vn.create=(o,n)=>{return new Vn({type:o,minLength:null,maxLength:null,exactLength:null,typeName:g.ZodArray,...to(n)})};function Lt(o){if(o instanceof Uo){let n={};for(let t in o.shape){let T=o.shape[t];n[t]=rn.create(Lt(T))}return new Uo({...o._def,shape:()=>n})}else if(o instanceof Vn)return new Vn({...o._def,type:Lt(o.element)});else if(o instanceof rn)return rn.create(Lt(o.unwrap()));else if(o instanceof en)return en.create(Lt(o.unwrap()));else if(o instanceof hn)return hn.create(o.items.map((n)=>Lt(n)));else return o}class Uo extends To{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=$o.objectKeys(o);return this._cached={shape:o,keys:n}}_parse(o){if(this._getType(o)!==I.object){let M=this._getOrReturnCtx(o);return C(M,{code:m.invalid_type,expected:I.object,received:M.parsedType}),u}let{status:t,ctx:T}=this._processInputParams(o),{shape:S,keys:f}=this._getCached(),y=[];if(!(this._def.catchall instanceof Nn&&this._def.unknownKeys==="strip")){for(let M in T.data)if(!f.includes(M))y.push(M)}let A=[];for(let M of f){let F=S[M],k=T.data[M];A.push({key:{status:"valid",value:M},value:F._parse(new Bn(T,k,T.path,M)),alwaysSet:M in T.data})}if(this._def.catchall instanceof Nn){let M=this._def.unknownKeys;if(M==="passthrough")for(let F of y)A.push({key:{status:"valid",value:F},value:{status:"valid",value:T.data[F]}});else if(M==="strict"){if(y.length>0)C(T,{code:m.unrecognized_keys,keys:y}),t.dirty()}else if(M==="strip");else throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let M=this._def.catchall;for(let F of y){let k=T.data[F];A.push({key:{status:"valid",value:F},value:M._parse(new Bn(T,k,T.path,F)),alwaysSet:F in T.data})}}if(T.common.async)return Promise.resolve().then(async()=>{let M=[];for(let F of A){let k=await F.key,W=await F.value;M.push({key:k,value:W,alwaysSet:F.alwaysSet})}return M}).then((M)=>{return lo.mergeObjectSync(t,M)});else return lo.mergeObjectSync(t,A)}get shape(){return this._def.shape()}strict(o){return q.errToObj,new Uo({...this._def,unknownKeys:"strict",...o!==void 0?{errorMap:(n,t)=>{var T,S,f,y;let A=(f=(S=(T=this._def).errorMap)===null||S===void 0?void 0:S.call(T,n,t).message)!==null&&f!==void 0?f:t.defaultError;if(n.code==="unrecognized_keys")return{message:(y=q.errToObj(o).message)!==null&&y!==void 0?y:A};return{message:A}}}:{}})}strip(){return new Uo({...this._def,unknownKeys:"strip"})}passthrough(){return new Uo({...this._def,unknownKeys:"passthrough"})}extend(o){return new Uo({...this._def,shape:()=>({...this._def.shape(),...o})})}merge(o){return new Uo({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 Uo({...this._def,catchall:o})}pick(o){let n={};return $o.objectKeys(o).forEach((t)=>{if(o[t]&&this.shape[t])n[t]=this.shape[t]}),new Uo({...this._def,shape:()=>n})}omit(o){let n={};return $o.objectKeys(this.shape).forEach((t)=>{if(!o[t])n[t]=this.shape[t]}),new Uo({...this._def,shape:()=>n})}deepPartial(){return Lt(this)}partial(o){let n={};return $o.objectKeys(this.shape).forEach((t)=>{let T=this.shape[t];if(o&&!o[t])n[t]=T;else n[t]=T.optional()}),new Uo({...this._def,shape:()=>n})}required(o){let n={};return $o.objectKeys(this.shape).forEach((t)=>{if(o&&!o[t])n[t]=this.shape[t];else{let S=this.shape[t];while(S instanceof rn)S=S._def.innerType;n[t]=S}}),new Uo({...this._def,shape:()=>n})}keyof(){return pk($o.objectKeys(this.shape))}}Uo.create=(o,n)=>{return new Uo({shape:()=>o,unknownKeys:"strip",catchall:Nn.create(),typeName:g.ZodObject,...to(n)})};Uo.strictCreate=(o,n)=>{return new Uo({shape:()=>o,unknownKeys:"strict",catchall:Nn.create(),typeName:g.ZodObject,...to(n)})};Uo.lazycreate=(o,n)=>{return new Uo({shape:o,unknownKeys:"strip",catchall:Nn.create(),typeName:g.ZodObject,...to(n)})};class xt extends To{_parse(o){let{ctx:n}=this._processInputParams(o),t=this._def.options;function T(S){for(let y of S)if(y.result.status==="valid")return y.result;for(let y of S)if(y.result.status==="dirty")return n.common.issues.push(...y.ctx.common.issues),y.result;let f=S.map((y)=>new $n(y.ctx.common.issues));return C(n,{code:m.invalid_union,unionErrors:f}),u}if(n.common.async)return Promise.all(t.map(async(S)=>{let f={...n,common:{...n.common,issues:[]},parent:null};return{result:await S._parseAsync({data:n.data,path:n.path,parent:f}),ctx:f}})).then(T);else{let S=void 0,f=[];for(let A of t){let M={...n,common:{...n.common,issues:[]},parent:null},F=A._parseSync({data:n.data,path:n.path,parent:M});if(F.status==="valid")return F;else if(F.status==="dirty"&&!S)S={result:F,ctx:M};if(M.common.issues.length)f.push(M.common.issues)}if(S)return n.common.issues.push(...S.ctx.common.issues),S.result;let y=f.map((A)=>new $n(A));return C(n,{code:m.invalid_union,unionErrors:y}),u}}get options(){return this._def.options}}xt.create=(o,n)=>{return new xt({options:o,typeName:g.ZodUnion,...to(n)})};var Pn=(o)=>{if(o instanceof vt)return Pn(o.schema);else if(o instanceof Kn)return Pn(o.innerType());else if(o instanceof pt)return[o.value];else if(o instanceof At)return o.options;else if(o instanceof qt)return $o.objectValues(o.enum);else if(o instanceof Zt)return Pn(o._def.innerType);else if(o instanceof ht)return[void 0];else if(o instanceof ct)return[null];else if(o instanceof rn)return[void 0,...Pn(o.unwrap())];else if(o instanceof en)return[null,...Pn(o.unwrap())];else if(o instanceof CS)return Pn(o.unwrap());else if(o instanceof et)return Pn(o.unwrap());else if(o instanceof Pt)return Pn(o._def.innerType);else return[]};class BS extends To{_parse(o){let{ctx:n}=this._processInputParams(o);if(n.parsedType!==I.object)return C(n,{code:m.invalid_type,expected:I.object,received:n.parsedType}),u;let t=this.discriminator,T=n.data[t],S=this.optionsMap.get(T);if(!S)return C(n,{code:m.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[t]}),u;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 T=new Map;for(let S of n){let f=Pn(S.shape[o]);if(!f.length)throw new Error(`A discriminator value for key \`${o}\` could not be extracted from all schema options`);for(let y of f){if(T.has(y))throw new Error(`Discriminator property ${String(o)} has duplicate value ${String(y)}`);T.set(y,S)}}return new BS({typeName:g.ZodDiscriminatedUnion,discriminator:o,options:n,optionsMap:T,...to(t)})}}function Sy(o,n){let t=Tt(o),T=Tt(n);if(o===n)return{valid:!0,data:o};else if(t===I.object&&T===I.object){let S=$o.objectKeys(n),f=$o.objectKeys(o).filter((A)=>S.indexOf(A)!==-1),y={...o,...n};for(let A of f){let M=Sy(o[A],n[A]);if(!M.valid)return{valid:!1};y[A]=M.data}return{valid:!0,data:y}}else if(t===I.array&&T===I.array){if(o.length!==n.length)return{valid:!1};let S=[];for(let f=0;f<o.length;f++){let y=o[f],A=n[f],M=Sy(y,A);if(!M.valid)return{valid:!1};S.push(M.data)}return{valid:!0,data:S}}else if(t===I.date&&T===I.date&&+o===+n)return{valid:!0,data:o};else return{valid:!1}}class it extends To{_parse(o){let{status:n,ctx:t}=this._processInputParams(o),T=(S,f)=>{if(ty(S)||ty(f))return u;let y=Sy(S.value,f.value);if(!y.valid)return C(t,{code:m.invalid_intersection_types}),u;if(Ty(S)||Ty(f))n.dirty();return{status:n.value,value:y.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,f])=>T(S,f));else return T(this._def.left._parseSync({data:t.data,path:t.path,parent:t}),this._def.right._parseSync({data:t.data,path:t.path,parent:t}))}}it.create=(o,n,t)=>{return new it({left:o,right:n,typeName:g.ZodIntersection,...to(t)})};class hn extends To{_parse(o){let{status:n,ctx:t}=this._processInputParams(o);if(t.parsedType!==I.array)return C(t,{code:m.invalid_type,expected:I.array,received:t.parsedType}),u;if(t.data.length<this._def.items.length)return C(t,{code:m.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),u;if(!this._def.rest&&t.data.length>this._def.items.length)C(t,{code:m.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty();let S=[...t.data].map((f,y)=>{let A=this._def.items[y]||this._def.rest;if(!A)return null;return A._parse(new Bn(t,f,t.path,y))}).filter((f)=>!!f);if(t.common.async)return Promise.all(S).then((f)=>{return lo.mergeArray(n,f)});else return lo.mergeArray(n,S)}get items(){return this._def.items}rest(o){return new hn({...this._def,rest:o})}}hn.create=(o,n)=>{if(!Array.isArray(o))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new hn({items:o,typeName:g.ZodTuple,rest:null,...to(n)})};class VT extends To{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!==I.object)return C(t,{code:m.invalid_type,expected:I.object,received:t.parsedType}),u;let T=[],S=this._def.keyType,f=this._def.valueType;for(let y in t.data)T.push({key:S._parse(new Bn(t,y,t.path,y)),value:f._parse(new Bn(t,t.data[y],t.path,y)),alwaysSet:y in t.data});if(t.common.async)return lo.mergeObjectAsync(n,T);else return lo.mergeObjectSync(n,T)}get element(){return this._def.valueType}static create(o,n,t){if(n instanceof To)return new VT({keyType:o,valueType:n,typeName:g.ZodRecord,...to(t)});return new VT({keyType:Un.create(),valueType:o,typeName:g.ZodRecord,...to(n)})}}class rT extends To{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!==I.map)return C(t,{code:m.invalid_type,expected:I.map,received:t.parsedType}),u;let T=this._def.keyType,S=this._def.valueType,f=[...t.data.entries()].map(([y,A],M)=>{return{key:T._parse(new Bn(t,y,t.path,[M,"key"])),value:S._parse(new Bn(t,A,t.path,[M,"value"]))}});if(t.common.async){let y=new Map;return Promise.resolve().then(async()=>{for(let A of f){let M=await A.key,F=await A.value;if(M.status==="aborted"||F.status==="aborted")return u;if(M.status==="dirty"||F.status==="dirty")n.dirty();y.set(M.value,F.value)}return{status:n.value,value:y}})}else{let y=new Map;for(let A of f){let{key:M,value:F}=A;if(M.status==="aborted"||F.status==="aborted")return u;if(M.status==="dirty"||F.status==="dirty")n.dirty();y.set(M.value,F.value)}return{status:n.value,value:y}}}}rT.create=(o,n,t)=>{return new rT({valueType:n,keyType:o,typeName:g.ZodMap,...to(t)})};class Rt extends To{_parse(o){let{status:n,ctx:t}=this._processInputParams(o);if(t.parsedType!==I.set)return C(t,{code:m.invalid_type,expected:I.set,received:t.parsedType}),u;let T=this._def;if(T.minSize!==null){if(t.data.size<T.minSize.value)C(t,{code:m.too_small,minimum:T.minSize.value,type:"set",inclusive:!0,exact:!1,message:T.minSize.message}),n.dirty()}if(T.maxSize!==null){if(t.data.size>T.maxSize.value)C(t,{code:m.too_big,maximum:T.maxSize.value,type:"set",inclusive:!0,exact:!1,message:T.maxSize.message}),n.dirty()}let S=this._def.valueType;function f(A){let M=new Set;for(let F of A){if(F.status==="aborted")return u;if(F.status==="dirty")n.dirty();M.add(F.value)}return{status:n.value,value:M}}let y=[...t.data.values()].map((A,M)=>S._parse(new Bn(t,A,t.path,M)));if(t.common.async)return Promise.all(y).then((A)=>f(A));else return f(y)}min(o,n){return new Rt({...this._def,minSize:{value:o,message:q.toString(n)}})}max(o,n){return new Rt({...this._def,maxSize:{value:o,message:q.toString(n)}})}size(o,n){return this.min(o,n).max(o,n)}nonempty(o){return this.min(1,o)}}Rt.create=(o,n)=>{return new Rt({valueType:o,minSize:null,maxSize:null,typeName:g.ZodSet,...to(n)})};class jt extends To{constructor(){super(...arguments);this.validate=this.implement}_parse(o){let{ctx:n}=this._processInputParams(o);if(n.parsedType!==I.function)return C(n,{code:m.invalid_type,expected:I.function,received:n.parsedType}),u;function t(y,A){return VS({data:y,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,US(),bt].filter((M)=>!!M),issueData:{code:m.invalid_arguments,argumentsError:A}})}function T(y,A){return VS({data:y,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,US(),bt].filter((M)=>!!M),issueData:{code:m.invalid_return_type,returnTypeError:A}})}let S={errorMap:n.common.contextualErrorMap},f=n.data;if(this._def.returns instanceof Wt){let y=this;return on(async function(...A){let M=new $n([]),F=await y._def.args.parseAsync(A,S).catch((O)=>{throw M.addIssue(t(A,O)),M}),k=await Reflect.apply(f,this,F);return await y._def.returns._def.type.parseAsync(k,S).catch((O)=>{throw M.addIssue(T(k,O)),M})})}else{let y=this;return on(function(...A){let M=y._def.args.safeParse(A,S);if(!M.success)throw new $n([t(A,M.error)]);let F=Reflect.apply(f,this,M.data),k=y._def.returns.safeParse(F,S);if(!k.success)throw new $n([T(F,k.error)]);return k.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...o){return new jt({...this._def,args:hn.create(o).rest(St.create())})}returns(o){return new jt({...this._def,returns:o})}implement(o){return this.parse(o)}strictImplement(o){return this.parse(o)}static create(o,n,t){return new jt({args:o?o:hn.create([]).rest(St.create()),returns:n||St.create(),typeName:g.ZodFunction,...to(t)})}}class vt extends To{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})}}vt.create=(o,n)=>{return new vt({getter:o,typeName:g.ZodLazy,...to(n)})};class pt extends To{_parse(o){if(o.data!==this._def.value){let n=this._getOrReturnCtx(o);return C(n,{received:n.data,code:m.invalid_literal,expected:this._def.value}),u}return{status:"valid",value:o.data}}get value(){return this._def.value}}pt.create=(o,n)=>{return new pt({value:o,typeName:g.ZodLiteral,...to(n)})};function pk(o,n){return new At({values:o,typeName:g.ZodEnum,...to(n)})}class At extends To{constructor(){super(...arguments);zT.set(this,void 0)}_parse(o){if(typeof o.data!=="string"){let n=this._getOrReturnCtx(o),t=this._def.values;return C(n,{expected:$o.joinValues(t),received:n.parsedType,code:m.invalid_type}),u}if(!rS(this,zT,"f"))ck(this,zT,new Set(this._def.values),"f");if(!rS(this,zT,"f").has(o.data)){let n=this._getOrReturnCtx(o),t=this._def.values;return C(n,{received:n.data,code:m.invalid_enum_value,options:t}),u}return on(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 At.create(o,{...this._def,...n})}exclude(o,n=this._def){return At.create(this.options.filter((t)=>!o.includes(t)),{...this._def,...n})}}zT=new WeakMap;At.create=pk;class qt extends To{constructor(){super(...arguments);HT.set(this,void 0)}_parse(o){let n=$o.getValidEnumValues(this._def.values),t=this._getOrReturnCtx(o);if(t.parsedType!==I.string&&t.parsedType!==I.number){let T=$o.objectValues(n);return C(t,{expected:$o.joinValues(T),received:t.parsedType,code:m.invalid_type}),u}if(!rS(this,HT,"f"))ck(this,HT,new Set($o.getValidEnumValues(this._def.values)),"f");if(!rS(this,HT,"f").has(o.data)){let T=$o.objectValues(n);return C(t,{received:t.data,code:m.invalid_enum_value,options:T}),u}return on(o.data)}get enum(){return this._def.values}}HT=new WeakMap;qt.create=(o,n)=>{return new qt({values:o,typeName:g.ZodNativeEnum,...to(n)})};class Wt extends To{unwrap(){return this._def.type}_parse(o){let{ctx:n}=this._processInputParams(o);if(n.parsedType!==I.promise&&n.common.async===!1)return C(n,{code:m.invalid_type,expected:I.promise,received:n.parsedType}),u;let t=n.parsedType===I.promise?n.data:Promise.resolve(n.data);return on(t.then((T)=>{return this._def.type.parseAsync(T,{path:n.path,errorMap:n.common.contextualErrorMap})}))}}Wt.create=(o,n)=>{return new Wt({type:o,typeName:g.ZodPromise,...to(n)})};class Kn extends To{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),T=this._def.effect||null,S={addIssue:(f)=>{if(C(t,f),f.fatal)n.abort();else n.dirty()},get path(){return t.path}};if(S.addIssue=S.addIssue.bind(S),T.type==="preprocess"){let f=T.transform(t.data,S);if(t.common.async)return Promise.resolve(f).then(async(y)=>{if(n.value==="aborted")return u;let A=await this._def.schema._parseAsync({data:y,path:t.path,parent:t});if(A.status==="aborted")return u;if(A.status==="dirty")return It(A.value);if(n.value==="dirty")return It(A.value);return A});else{if(n.value==="aborted")return u;let y=this._def.schema._parseSync({data:f,path:t.path,parent:t});if(y.status==="aborted")return u;if(y.status==="dirty")return It(y.value);if(n.value==="dirty")return It(y.value);return y}}if(T.type==="refinement"){let f=(y)=>{let A=T.refinement(y,S);if(t.common.async)return Promise.resolve(A);if(A instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return y};if(t.common.async===!1){let y=this._def.schema._parseSync({data:t.data,path:t.path,parent:t});if(y.status==="aborted")return u;if(y.status==="dirty")n.dirty();return f(y.value),{status:n.value,value:y.value}}else return this._def.schema._parseAsync({data:t.data,path:t.path,parent:t}).then((y)=>{if(y.status==="aborted")return u;if(y.status==="dirty")n.dirty();return f(y.value).then(()=>{return{status:n.value,value:y.value}})})}if(T.type==="transform")if(t.common.async===!1){let f=this._def.schema._parseSync({data:t.data,path:t.path,parent:t});if(!mT(f))return f;let y=T.transform(f.value,S);if(y instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:y}}else return this._def.schema._parseAsync({data:t.data,path:t.path,parent:t}).then((f)=>{if(!mT(f))return f;return Promise.resolve(T.transform(f.value,S)).then((y)=>({status:n.value,value:y}))});$o.assertNever(T)}}Kn.create=(o,n,t)=>{return new Kn({schema:o,typeName:g.ZodEffects,effect:n,...to(t)})};Kn.createWithPreprocess=(o,n,t)=>{return new Kn({schema:n,effect:{type:"preprocess",transform:o},typeName:g.ZodEffects,...to(t)})};class rn extends To{_parse(o){if(this._getType(o)===I.undefined)return on(void 0);return this._def.innerType._parse(o)}unwrap(){return this._def.innerType}}rn.create=(o,n)=>{return new rn({innerType:o,typeName:g.ZodOptional,...to(n)})};class en extends To{_parse(o){if(this._getType(o)===I.null)return on(null);return this._def.innerType._parse(o)}unwrap(){return this._def.innerType}}en.create=(o,n)=>{return new en({innerType:o,typeName:g.ZodNullable,...to(n)})};class Zt extends To{_parse(o){let{ctx:n}=this._processInputParams(o),t=n.data;if(n.parsedType===I.undefined)t=this._def.defaultValue();return this._def.innerType._parse({data:t,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}Zt.create=(o,n)=>{return new Zt({innerType:o,typeName:g.ZodDefault,defaultValue:typeof n.default==="function"?n.default:()=>n.default,...to(n)})};class Pt extends To{_parse(o){let{ctx:n}=this._processInputParams(o),t={...n,common:{...n.common,issues:[]}},T=this._def.innerType._parse({data:t.data,path:t.path,parent:{...t}});if(QT(T))return T.then((S)=>{return{status:"valid",value:S.status==="valid"?S.value:this._def.catchValue({get error(){return new $n(t.common.issues)},input:t.data})}});else return{status:"valid",value:T.status==="valid"?T.value:this._def.catchValue({get error(){return new $n(t.common.issues)},input:t.data})}}removeCatch(){return this._def.innerType}}Pt.create=(o,n)=>{return new Pt({innerType:o,typeName:g.ZodCatch,catchValue:typeof n.catch==="function"?n.catch:()=>n.catch,...to(n)})};class BT extends To{_parse(o){if(this._getType(o)!==I.nan){let t=this._getOrReturnCtx(o);return C(t,{code:m.invalid_type,expected:I.nan,received:t.parsedType}),u}return{status:"valid",value:o.data}}}BT.create=(o)=>{return new BT({typeName:g.ZodNaN,...to(o)})};var _R=Symbol("zod_brand");class CS extends To{_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 CT extends To{_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 u;if(S.status==="dirty")return n.dirty(),It(S.value);else return this._def.out._parseAsync({data:S.value,path:t.path,parent:t})})();else{let T=this._def.in._parseSync({data:t.data,path:t.path,parent:t});if(T.status==="aborted")return u;if(T.status==="dirty")return n.dirty(),{status:"dirty",value:T.value};else return this._def.out._parseSync({data:T.value,path:t.path,parent:t})}}static create(o,n){return new CT({in:o,out:n,typeName:g.ZodPipeline})}}class et extends To{_parse(o){let n=this._def.innerType._parse(o),t=(T)=>{if(mT(T))T.value=Object.freeze(T.value);return T};return QT(n)?n.then((T)=>t(T)):t(n)}unwrap(){return this._def.innerType}}et.create=(o,n)=>{return new et({innerType:o,typeName:g.ZodReadonly,...to(n)})};function qk(o,n={},t){if(o)return Jt.create().superRefine((T,S)=>{var f,y;if(!o(T)){let A=typeof n==="function"?n(T):typeof n==="string"?{message:n}:n,M=(y=(f=A.fatal)!==null&&f!==void 0?f:t)!==null&&y!==void 0?y:!0,F=typeof A==="string"?{message:A}:A;S.addIssue({code:"custom",...F,fatal:M})}});return Jt.create()}var wR={object:Uo.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 KR=(o,n={message:`Input not instance of ${o.name}`})=>qk((t)=>t instanceof o,n),Zk=Un.create,Pk=ft.create,XR=BT.create,ER=yt.create,ek=Nt.create,YR=$t.create,GR=DT.create,zR=ht.create,HR=ct.create,mR=Jt.create,QR=St.create,DR=Nn.create,UR=UT.create,VR=Vn.create,LT=Uo.create,rR=Uo.strictCreate,BR=xt.create,CR=BS.create,LR=it.create,IR=hn.create,jR=VT.create,bR=rT.create,NR=Rt.create,hR=jt.create,cR=vt.create,xR=pt.create,iR=At.create,vR=qt.create,pR=Wt.create,Nk=Kn.create,qR=rn.create,ZR=en.create,PR=Kn.createWithPreprocess,eR=CT.create,lR=()=>Zk().optional(),gR=()=>Pk().optional(),dR=()=>ek().optional(),uR={string:(o)=>Un.create({...o,coerce:!0}),number:(o)=>ft.create({...o,coerce:!0}),boolean:(o)=>Nt.create({...o,coerce:!0}),bigint:(o)=>yt.create({...o,coerce:!0}),date:(o)=>$t.create({...o,coerce:!0})},aR=u,zo=Object.freeze({__proto__:null,defaultErrorMap:bt,setErrorMap:sJ,getErrorMap:US,makeIssue:VS,EMPTY_PATH:oR,addIssueToContext:C,ParseStatus:lo,INVALID:u,DIRTY:It,OK:on,isAborted:ty,isDirty:Ty,isValid:mT,isAsync:QT,get util(){return $o},get objectUtil(){return ny},ZodParsedType:I,getParsedType:Tt,ZodType:To,datetimeRegex:vk,ZodString:Un,ZodNumber:ft,ZodBigInt:yt,ZodBoolean:Nt,ZodDate:$t,ZodSymbol:DT,ZodUndefined:ht,ZodNull:ct,ZodAny:Jt,ZodUnknown:St,ZodNever:Nn,ZodVoid:UT,ZodArray:Vn,ZodObject:Uo,ZodUnion:xt,ZodDiscriminatedUnion:BS,ZodIntersection:it,ZodTuple:hn,ZodRecord:VT,ZodMap:rT,ZodSet:Rt,ZodFunction:jt,ZodLazy:vt,ZodLiteral:pt,ZodEnum:At,ZodNativeEnum:qt,ZodPromise:Wt,ZodEffects:Kn,ZodTransformer:Kn,ZodOptional:rn,ZodNullable:en,ZodDefault:Zt,ZodCatch:Pt,ZodNaN:BT,BRAND:_R,ZodBranded:CS,ZodPipeline:CT,ZodReadonly:et,custom:qk,Schema:To,ZodSchema:To,late:wR,get ZodFirstPartyTypeKind(){return g},coerce:uR,any:mR,array:VR,bigint:ER,boolean:ek,date:YR,discriminatedUnion:CR,effect:Nk,enum:iR,function:hR,instanceof:KR,intersection:LR,lazy:cR,literal:xR,map:bR,nan:XR,nativeEnum:vR,never:DR,null:HR,nullable:ZR,number:Pk,object:LT,oboolean:dR,onumber:gR,optional:qR,ostring:lR,pipeline:eR,preprocess:PR,promise:pR,record:jR,set:NR,strictObject:rR,string:Zk,symbol:GR,transformer:Nk,tuple:IR,undefined:zR,union:BR,unknown:QR,void:UR,NEVER:aR,ZodIssueCode:m,quotelessJson:aJ,ZodError:$n});function lk(o){let n=o.runtimeEnvStrict??o.runtimeEnv??process.env;if(o.emptyStringAsUndefined??!1){for(let[K,U]of Object.entries(n))if(U==="")delete n[K]}if(!!o.skipValidation)return n;let S=typeof o.client==="object"?o.client:{},f=typeof o.server==="object"?o.server:{},y=typeof o.shared==="object"?o.shared:{},A=LT(S),M=LT(f),F=LT(y),k=o.isServer??(typeof window==="undefined"||("Deno"in window)),W=A.merge(F),O=M.merge(F).merge(A),E=k?O.safeParse(n):W.safeParse(n),Q=o.onValidationError??((K)=>{throw console.error("\u274C Invalid environment variables:",K.flatten().fieldErrors),new Error("Invalid environment variables")}),z=o.onInvalidAccess??((K)=>{throw new Error("\u274C Attempted to access a server-side environment variable on the client")});if(E.success===!1)return Q(E.error);let G=(K)=>{if(!o.clientPrefix)return!0;return!K.startsWith(o.clientPrefix)&&!(K in F.shape)},V=(K)=>{return k||!G(K)},x=(K)=>{return K==="__esModule"||K==="$$typeof"},c=(o.extends??[]).reduce((K,U)=>{return Object.assign(K,U)},{}),P=Object.assign(E.data,c);return new Proxy(P,{get(K,U){if(typeof U!=="string")return;if(x(U))return;if(!V(U))return z(U);return Reflect.get(K,U)}})}var sR="__vite_start_time"in globalThis,o0=typeof window!=="undefined",g7="vitest"in globalThis,Cn=lk({isServer:!sR&&!o0,server:{CI:zo.string().transform((o)=>!0).optional(),POSTGRES_USER:zo.string(),POSTGRES_PASSWORD:zo.string(),POSTGRES_DATABASE:zo.string(),POSTGRES_HOST:zo.string(),POSTGRES_PORT:zo.string().transform((o)=>Number.parseInt(o,10)),BACKEND_PORT:zo.string().transform((o)=>Number.parseInt(o,10)),RUN_WORKERS_FROM_SOURCE:zo.union([zo.literal("true"),zo.literal("false")]).optional().transform((o)=>o==="true"),FRONTEND_PORT:zo.string().transform((o)=>Number.parseInt(o,10)),FRONTEND_ORIGINS:zo.string().transform((o)=>JSON.parse(o)).pipe(zo.array(zo.string())),OPENAI_API_KEY:zo.string().optional()},clientPrefix:"VITE_",client:{VITE_BACKEND_ORIGIN:zo.string(),VITE_USE_SELF_SIGNED_CERTIFICATE:zo.union([zo.literal("true"),zo.literal("false")]).optional().transform((o)=>o==="true")},runtimeEnv:import.meta.env,emptyStringAsUndefined:!0});var dk=fy(import.meta.dirname,"../dev"),uk=Cn.VITE_USE_SELF_SIGNED_CERTIFICATE?{cert:gk(fy(dk,"./cert.pem"),"utf-8"),key:gk(fy(dk,"./key.pem"),"utf-8")}:void 0;import e0 from"path";import H0 from"os";import m0 from"fs";var LS=new Map,yy=new Map,Ay=Symbol("OriginError"),lt={};class Xn extends Promise{constructor(o,n,t,T,S={}){let f,y;super((A,M)=>{f=A,y=M});this.tagged=Array.isArray(o.raw),this.strings=o,this.args=n,this.handler=t,this.canceller=T,this.options=S,this.state=null,this.statement=null,this.resolve=(A)=>(this.active=!1,f(A)),this.reject=(A)=>(this.active=!1,y(A)),this.active=!1,this.cancelled=null,this.executed=!1,this.signature="",this[Ay]=this.handler.debug?new Error:this.tagged&&n0(this.strings)}get origin(){return(this.handler.debug?this[Ay].stack:this.tagged&&yy.has(this.strings)?yy.get(this.strings):yy.set(this.strings,this[Ay].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 T=new Promise((S,f)=>{this.cursorFn=(y)=>{return S({value:y,done:!1}),new Promise((A)=>t=A)},this.resolve=()=>(this.active=!1,S({done:!0})),this.reject=(y)=>(this.active=!1,f(y))});return this.execute(),T},return(){return t&&t(lt),{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 n0(o){if(LS.has(o))return LS.get(o);let n=Error.stackTraceLimit;return Error.stackTraceLimit=4,LS.set(o,new Error),Error.stackTraceLimit=n,LS.get(o)}class gt extends Error{constructor(o){super(o.message);this.name=this.constructor.name,Object.assign(this,o)}}var Lo={connection:ak,postgres:sk,generic:o$,notSupported:n$};function ak(o,n,t){let{host:T,port:S}=t||n,f=Object.assign(new Error("write "+o+" "+(n.path||T+":"+S)),{code:o,errno:o,address:n.path||T},n.path?{}:{port:S});return Error.captureStackTrace(f,ak),f}function sk(o){let n=new gt(o);return Error.captureStackTrace(n,sk),n}function o$(o,n){let t=Object.assign(new Error(o+": "+n),{code:o});return Error.captureStackTrace(t,o$),t}function n$(o){let n=Object.assign(new Error(o+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:o});return Error.captureStackTrace(n,n$),n}var t0={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 bS{then(){My()}catch(){My()}finally(){My()}}class NT extends bS{constructor(o){super();this.value=cS(o)}}class cn extends bS{constructor(o,n,t){super();this.value=o,this.type=n,this.array=t}}class NS extends bS{constructor(o,n){super();this.first=o,this.rest=n}build(o,n,t,T){let S=T0.map(([f,y])=>({fn:y,i:o.search(f)})).sort((f,y)=>f.i-y.i).pop();return S.i===-1?Ry(this.first,T):S.fn(this.first,this.rest,n,t,T)}}function hS(o,n,t,T){let S=o instanceof cn?o.value:o;if(S===void 0){if(o instanceof cn?o.value=T.transform.undefined:S=o=T.transform.undefined,S===void 0)throw Lo.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||f$(o.value):o.type):(n.push(o),jS(o)))}var T$=A$(t0);function $y(o,n,t,T,S,f){for(let y=1;y<o.strings.length;y++)n+=Jy(n,t,T,S,f)+o.strings[y],t=o.args[y];return n}function Jy(o,n,t,T,S){return n instanceof NS?n.build(o,t,T,S):n instanceof Xn?ky(n,t,T,S):n instanceof NT?n.value:n&&n[0]instanceof Xn?n.reduce((f,y)=>f+" "+ky(y,t,T,S),""):hS(n,t,T,S)}function ky(o,n,t,T){return o.fragment=!0,$y(o,o.strings[0],o.args[0],n,t,T)}function S$(o,n,t,T,S){return o.map((f)=>"("+T.map((y)=>Jy("values",f[y],n,t,S)).join(",")+")").join(",")}function t$(o,n,t,T,S){let f=Array.isArray(o[0]),y=n.length?n.flat():Object.keys(f?o[0]:o);return S$(f?o:[o],t,T,y,S)}function IS(o,n,t,T,S){if(typeof o==="string"&&(o=[o].concat(n)),Array.isArray(o))return Ry(o,S);let f;return(n.length?n.flat():Object.keys(o)).map((A)=>{return f=o[A],(f instanceof Xn?ky(f,t,T,S):f instanceof NT?f.value:hS(f,t,T,S))+" as "+cS(S.transform.column.to?S.transform.column.to(A):A)}).join(",")}var T0=Object.entries({values:t$,in:(...o)=>{let n=t$(...o);return n==="()"?"(null)":n},select:IS,as:IS,returning:IS,"\\(":IS,update(o,n,t,T,S){return(n.length?n.flat():Object.keys(o)).map((f)=>cS(S.transform.column.to?S.transform.column.to(f):f)+"="+Jy("values",o[f],t,T,S))},insert(o,n,t,T,S){let f=n.length?n.flat():Object.keys(Array.isArray(o)?o[0]:o);return"("+Ry(f,S)+")values"+S$(Array.isArray(o)?o:[o],t,T,f,S)}}).map(([o,n])=>[new RegExp("((?:^|[\\s(])"+o+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),n]);function My(){throw Lo.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}var{serializers:S0,parsers:f0}=T$;function f$(o){if(Array.isArray(o))return f$(o[0]);return typeof o==="string"?1009:0}var y$=function(o){let n=A$(o||{});return{serializers:Object.assign({},S0,n.serializers),parsers:Object.assign({},f0,n.parsers)}};function A$(o){return Object.keys(o).reduce((n,t)=>{if(o[t].from&&[].concat(o[t].from).forEach((T)=>n.parsers[T]=o[t].parse),o[t].serialize)n.serializers[o[t].to]=o[t].serialize,o[t].from&&[].concat(o[t].from).forEach((T)=>n.serializers[T]=o[t].serialize);return n},{parsers:{},serializers:{}})}function Ry(o,{transform:{column:n}}){return o.map((t)=>cS(n.to?n.to(t):t)).join(",")}var cS=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},y0=/\\/g,A0=/"/g;function M0(o){return o.replace(y0,"\\\\").replace(A0,'\\"')}var M$=function o(n,t,T,S){if(Array.isArray(n)===!1)return n;if(!n.length)return"{}";let f=n[0],y=S===1020?";":",";if(Array.isArray(f)&&!f.type)return"{"+n.map((A)=>o(A,t,T,S)).join(y)+"}";return"{"+n.map((A)=>{if(A===void 0){if(A=T.transform.undefined,A===void 0)throw Lo.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return A===null?"null":'"'+M0(t?t(A.type?A.value:A):""+A)+'"'}).join(y)+"}"},Fy={i:0,char:null,str:"",quoted:!1,last:0},F$=function o(n,t,T){return Fy.i=Fy.last=0,k$(Fy,n,t,T)};function k$(o,n,t,T){let S=[],f=T===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(k$(o,n,t,T));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===f&&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},_t=(o)=>{let n=o[0].toUpperCase();for(let t=1;t<o.length;t++)n+=o[t]==="_"?o[++t].toUpperCase():o[t];return n},wt=(o)=>o.replace(/_/g,"-"),IT=(o)=>o.replace(/([A-Z])/g,"_$1").toLowerCase(),jT=(o)=>(o.slice(0,1)+o.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),bT=(o)=>o.replace(/-/g,"_");function Wy(o){return function n(t,T){return typeof t==="object"&&t!==null&&(T.type===114||T.type===3802)?Array.isArray(t)?t.map((S)=>n(S,T)):Object.entries(t).reduce((S,[f,y])=>Object.assign(S,{[o(f)]:n(y,T)}),{}):t}}Ot.column={from:Ot};Ot.value={from:Wy(Ot)};IT.column={to:IT};var Oy={...Ot};Oy.column.to=IT;_t.column={from:_t};_t.value={from:Wy(_t)};jT.column={to:jT};var _y={..._t};_y.column.to=jT;wt.column={from:wt};wt.value={from:Wy(wt)};bT.column={to:bT};var wy={...wt};wy.column.to=bT;import $$ from"net";import J0 from"tls";import hT from"crypto";import Ky from"stream";import{performance as J$}from"perf_hooks";class Kt 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 Jn=F0;function F0(o=[]){let n=o.slice(),t=0;return{get length(){return n.length-t},remove:(T)=>{let S=n.indexOf(T);return S===-1?null:(n.splice(S,1),T)},push:(T)=>(n.push(T),T),shift:()=>{let T=n[t++];if(t===n.length)t=0,n=[];else n[t-1]=void 0;return T}}}var go=Buffer.allocUnsafe(256),k0="BCcDdEFfHPpQSX".split("").reduce((o,n)=>{let t=n.charCodeAt(0);return o[n]=()=>{return go[0]=t,Wo.i=5,Wo},o},{}),Wo=Object.assign($0,k0,{N:String.fromCharCode(0),i:0,inc(o){return Wo.i+=o,Wo},str(o){let n=Buffer.byteLength(o);return xS(n),Wo.i+=go.write(o,Wo.i,n,"utf8"),Wo},i16(o){return xS(2),go.writeUInt16BE(o,Wo.i),Wo.i+=2,Wo},i32(o,n){if(n||n===0)return go.writeUInt32BE(o,n),Wo;return xS(4),go.writeUInt32BE(o,Wo.i),Wo.i+=4,Wo},z(o){return xS(o),go.fill(0,Wo.i,Wo.i+o),Wo.i+=o,Wo},raw(o){return go=Buffer.concat([go.subarray(0,Wo.i),o]),Wo.i=go.length,Wo},end(o=1){go.writeUInt32BE(Wo.i-o,o);let n=go.subarray(0,Wo.i);return Wo.i=0,go=Buffer.allocUnsafe(256),n}}),Z=Wo;function xS(o){if(go.length-Wo.i<o){let n=go,t=n.length;go=Buffer.allocUnsafe(t+(t>>1)+o),n.copy(go)}}function $0(){return Wo.i=0,Wo}var Yy=O$,R0=1,Mt=Z().S().end(),R$=Z().H().end(),W0=Z().i32(8).i32(80877103).end(8),O0=Buffer.concat([Z().E().str(Z.N).i32(0).end(),Mt]),_0=Z().D().str("S").str(Z.N).end(),dt=()=>{},w0=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),K0={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 O$(o,n={},{onopen:t=dt,onend:T=dt,onclose:S=dt}={}){let{ssl:f,max:y,user:A,host:M,port:F,database:k,parsers:W,transform:O,onnotice:E,onnotify:Q,onparameter:z,max_pipeline:G,keep_alive:V,backoff:x,target_session_attrs:c}=o,P=Jn(),Y=R0++,K={pid:null,secret:null},U=Ey(aS,o.idle_timeout),p=Ey(aS,o.max_lifetime),b=Ey(h$,o.connect_timeout),w=null,v,j=new Kt,a=Buffer.alloc(0),oo=o.fetch_types,no={},_o={},An=Math.random().toString(36).slice(2),H=1,i=0,fo=0,Ro=0,Io=0,So=0,wo=0,Co=0,mo=null,Eo=null,vo=!1,Ko=null,Yn=null,po=null,ln=null,jo=null,Yo=null,Gn=null,Ln=null,B=null,oT=null,qo={queue:n.closed,idleTimer:U,connect($){po=$||!0,ly()},terminate:tT,execute:nT,cancel:I$,end:aS,count:0,id:Y};return n.closed&&n.closed.push(qo),qo;async function L$(){let $;try{$=o.socket?await Promise.resolve(o.socket(o)):new $$.Socket}catch(_){Gt(_);return}return $.on("error",Gt),$.on("close",gy),$.on("drain",Py),$}async function I$({pid:$,secret:_},e,Jo){try{v=Z().i32(16).i32(80877102).i32($).i32(_).end(16),await ey(),w.once("error",Jo),w.once("close",e)}catch(Vo){Jo(Vo)}}function nT($){if(vo)return ZT($,Lo.connection("CONNECTION_DESTROYED",o));if($.cancelled)return;try{return $.state=K,B?P.push($):(B=$,B.active=!0),N$($),co(j$($))&&!$.describeFirst&&!$.cursorFn&&P.length<G&&(!$.options.onexecute||$.options.onexecute(qo))}catch(_){return P.length===0&&co(Mt),In(_),!0}}function j$($){if($.parameters.length>=65534)throw Lo.generic("MAX_PARAMETERS_EXCEEDED","Max number of parameters (65534) exceeded");return $.options.simple?Z().Q().str($.statement.string+Z.N).end():$.describeFirst?Buffer.concat([py($),R$]):$.prepare?$.prepared?qT($):Buffer.concat([py($),qT($)]):b$($)}function py($){return Buffer.concat([uy($.statement.string,$.parameters,$.statement.types,$.statement.name),GJ("S",$.statement.name)])}function qT($){return Buffer.concat([YJ($.parameters,$.statement.types,$.statement.name,$.cursorName),$.cursorFn?ay("",$.cursorRows):O0])}function b$($){return Buffer.concat([uy($.statement.string,$.parameters,$.statement.types),_0,qT($)])}function N$($){let _=[],e=[],Jo=$y($,$.strings[0],$.args[0],_,e,o);!$.tagged&&$.args.forEach((Vo)=>hS(Vo,_,e,o)),$.prepare=o.prepare&&("prepare"in $.options?$.options.prepare:!0),$.string=Jo,$.signature=$.prepare&&e+Jo,$.onlyDescribe&&delete _o[$.signature],$.parameters=$.parameters||_,$.prepared=$.prepare&&$.signature in _o,$.describeFirst=$.onlyDescribe||_.length&&!$.prepared,$.statement=$.prepared?_o[$.signature]:{string:Jo,types:e,name:$.prepare?An+H++:""},typeof o.debug==="function"&&o.debug(Y,Jo,_,e)}function co($,_){if(Yo=Yo?Buffer.concat([Yo,$]):Buffer.from($),_||Yo.length>=1024)return qy(_);return Eo===null&&(Eo=setImmediate(qy)),!0}function qy($){let _=w.write(Yo,$);return Eo!==null&&clearImmediate(Eo),Yo=Eo=null,_}function h$(){In(Lo.connection("CONNECT_TIMEOUT",o,w)),w.destroy()}async function Zy(){if(co(W0),!await new Promise((_)=>w.once("data",(e)=>_(e[0]===83)))&&f==="prefer")return Yt();w.removeAllListeners(),w=J0.connect({socket:w,servername:$$.isIP(w.host)?void 0:w.host,...f==="require"||f==="allow"||f==="prefer"?{rejectUnauthorized:!1}:f==="verify-full"?{}:typeof f==="object"?f:{}}),w.on("secureConnect",Yt),w.on("error",Gt),w.on("close",gy),w.on("drain",Py)}function Py(){!B&&t(qo)}function uS($){if(Ko){if(Ko.push($),fo-=$.length,fo>=0)return}a=Ko?Buffer.concat(Ko,So-fo):a.length===0?$:Buffer.concat([a,$],a.length+$.length);while(a.length>4){if(So=a.readUInt32BE(1),So>=a.length){fo=So-a.length,Ko=[a];break}try{c$(a.subarray(0,So+1))}catch(_){B&&(B.cursorFn||B.describeFirst)&&co(Mt),In(_)}a=a.subarray(So+1),fo=0,Ko=null}}async function ey(){if(vo=!1,no={},w||(w=await L$()),!w)return;if(b.start(),o.socket)return f?Zy():Yt();if(w.on("connect",f?Zy:Yt),o.path)return w.connect(o.path);w.ssl=f,w.connect(F[Ro],M[Ro]),w.host=M[Ro],w.port=F[Ro],Ro=(Ro+1)%F.length}function ly(){setTimeout(ey,i?i+wo-J$.now():0)}function Yt(){try{_o={},oo=o.fetch_types,An=Math.random().toString(36).slice(2),H=1,p.start(),w.on("data",uS),V&&w.setKeepAlive&&w.setKeepAlive(!0,1000*V);let $=HJ();co($)}catch($){Gt($)}}function Gt($){if(qo.queue===n.connecting&&o.host[Io+1])return;In($);while(P.length)ZT(P.shift(),$)}function In($){jo&&(jo.destroy($),jo=null),B&&ZT(B,$),po&&(ZT(po,$),po=null)}function ZT($,_){"query"in _||"parameters"in _||Object.defineProperties(_,{stack:{value:_.stack+$.origin.replace(/.*\n/,"\n"),enumerable:o.debug},query:{value:$.string,enumerable:o.debug},parameters:{value:$.parameters,enumerable:o.debug},args:{value:$.args,enumerable:o.debug},types:{value:$.statement&&$.statement.types,enumerable:o.debug}}),$.reject(_)}function aS(){return ln||(!qo.reserved&&T(qo),!qo.reserved&&!po&&!B&&P.length===0?(tT(),new Promise(($)=>w&&w.readyState!=="closed"?w.once("close",$):$())):ln=new Promise(($)=>Gn=$))}function tT(){if(vo=!0,jo||B||po||P.length)Gt(Lo.connection("CONNECTION_DESTROYED",o));if(clearImmediate(Eo),w)w.removeListener("data",uS),w.removeListener("connect",Yt),w.readyState==="open"&&w.end(Z().X().end());Gn&&(Gn(),ln=Gn=null)}async function gy($){if(a=Buffer.alloc(0),fo=0,Ko=null,clearImmediate(Eo),w.removeListener("data",uS),w.removeListener("connect",Yt),U.cancel(),p.cancel(),b.cancel(),w.removeAllListeners(),w=null,po)return ly();!$&&(B||P.length)&&Gt(Lo.connection("CONNECTION_CLOSED",o,w)),i=J$.now(),$&&o.shared.retries++,wo=(typeof x==="function"?x(o.shared.retries):x)*1000,S(qo,Lo.connection("CONNECTION_CLOSED",o,w))}function c$($,_=$[0]){(_===68?x$:_===100?RJ:_===65?AJ:_===83?i$:_===90?v$:_===67?p$:_===50?dy:_===49?q$:_===116?Z$:_===84?P$:_===82?e$:_===110?s$:_===75?oJ:_===69?fJ:_===115?MJ:_===51?FJ:_===71?kJ:_===78?OJ:_===72?$J:_===99?WJ:_===73?_J:_===86?wJ:_===118?KJ:_===87?JJ:XJ)($)}function x$($){let _=7,e,Jo,Vo,Zo=B.isRaw?new Array(B.statement.columns.length):{};for(let uo=0;uo<B.statement.columns.length;uo++)Jo=B.statement.columns[uo],e=$.readInt32BE(_),_+=4,Vo=e===-1?null:B.isRaw===!0?$.subarray(_,_+=e):Jo.parser===void 0?$.toString("utf8",_,_+=e):Jo.parser.array===!0?Jo.parser($.toString("utf8",_+1,_+=e)):Jo.parser($.toString("utf8",_,_+=e)),B.isRaw?Zo[uo]=B.isRaw===!0?Vo:O.value.from?O.value.from(Vo,Jo):Vo:Zo[Jo.name]=O.value.from?O.value.from(Vo,Jo):Vo;B.forEachFn?B.forEachFn(O.row.from?O.row.from(Zo):Zo,j):j[Co++]=O.row.from?O.row.from(Zo):Zo}function i$($){let[_,e]=$.toString("utf8",5,$.length-1).split(Z.N);if(no[_]=e,o.parameters[_]!==e)o.parameters[_]=e,z&&z(_,e)}function v$($){if(B&&B.options.simple&&B.resolve(Yn||j),B=Yn=null,j=new Kt,b.cancel(),po){if(c){if(!no.in_hot_standby||!no.default_transaction_read_only)return SJ();else if(TJ(c,no))return tT()}if(oo)return po===!0&&(po=null),nJ();po!==!0&&nT(po),o.shared.retries=Io=0,po=null;return}while(P.length&&(B=P.shift())&&(B.active=!0,B.cancelled))O$(o).cancel(B.state,B.cancelled.resolve,B.cancelled.reject);if(B)return;qo.reserved?!qo.reserved.release&&$[5]===73?ln?tT():(qo.reserved=null,t(qo)):qo.reserved():ln?tT():t(qo)}function p$($){Co=0;for(let _=$.length-1;_>0;_--){if($[_]===32&&$[_+1]<58&&j.count===null)j.count=+$.toString("utf8",_+1,$.length-1);if($[_-1]>=65){j.command=$.toString("utf8",5,_),j.state=K;break}}if(oT&&(oT(),oT=null),j.command==="BEGIN"&&y!==1&&!qo.reserved)return In(Lo.generic("UNSAFE_TRANSACTION","Only use sql.begin, sql.reserved or max: 1"));if(B.options.simple)return dy();if(B.cursorFn)j.count&&B.cursorFn(j),co(Mt);B.resolve(j)}function q$(){B.parsing=!1}function dy(){!j.statement&&(j.statement=B.statement),j.columns=B.statement.columns}function Z$($){let _=$.readUInt16BE(5);for(let e=0;e<_;++e)!B.statement.types[e]&&(B.statement.types[e]=$.readUInt32BE(7+e*4));B.prepare&&(_o[B.signature]=B.statement),B.describeFirst&&!B.onlyDescribe&&(co(qT(B)),B.describeFirst=!1)}function P$($){if(j.command)Yn=Yn||[j],Yn.push(j=new Kt),j.count=null,B.statement.columns=null;let _=$.readUInt16BE(5),e=7,Jo;B.statement.columns=Array(_);for(let Vo=0;Vo<_;++Vo){Jo=e;while($[e++]!==0);let Zo=$.readUInt32BE(e),uo=$.readUInt16BE(e+4),gn=$.readUInt32BE(e+6);B.statement.columns[Vo]={name:O.column.from?O.column.from($.toString("utf8",Jo,e-1)):$.toString("utf8",Jo,e-1),parser:W[gn],table:Zo,number:uo,type:gn},e+=18}if(j.statement=B.statement,B.onlyDescribe)return B.resolve(B.statement),co(Mt)}async function e$($,_=$.readUInt32BE(5)){(_===3?l$:_===5?g$:_===10?d$:_===11?u$:_===12?a$:_!==0?EJ:dt)($,_)}async function l$(){let $=await sS();co(Z().p().str($).z(1).end())}async function g$($){let _="md5"+await W$(Buffer.concat([Buffer.from(await W$(await sS()+A)),$.subarray(9)]));co(Z().p().str(_).z(1).end())}async function d$(){Ln=(await hT.randomBytes(18)).toString("base64"),Z().p().str("SCRAM-SHA-256"+Z.N);let $=Z.i;co(Z.inc(4).str("n,,n=*,r="+Ln).i32(Z.i-$-4,$).end())}async function u$($){let _=$.toString("utf8",9).split(",").reduce((uo,gn)=>(uo[gn[0]]=gn.slice(2),uo),{}),e=await hT.pbkdf2Sync(await sS(),Buffer.from(_.s,"base64"),parseInt(_.i),32,"sha256"),Jo=await iS(e,"Client Key"),Vo="n=*,r="+Ln+",r="+_.r+",s="+_.s+",i="+_.i+",c=biws,r="+_.r;mo=(await iS(await iS(e,"Server Key"),Vo)).toString("base64");let Zo="c=biws,r="+_.r+",p="+E0(Jo,Buffer.from(await iS(await X0(Jo),Vo))).toString("base64");co(Z().p().str(Zo).end())}function a$($){if($.toString("utf8",9).split(Z.N,1)[0].slice(2)===mo)return;In(Lo.generic("SASL_SIGNATURE_MISMATCH","The server did not return the correct signature")),w.destroy()}function sS(){return Promise.resolve(typeof o.pass==="function"?o.pass():o.pass)}function s$(){if(j.statement=B.statement,j.statement.columns=[],B.onlyDescribe)return B.resolve(B.statement),co(Mt)}function oJ($){K.pid=$.readUInt32BE(5),K.secret=$.readUInt32BE(9)}async function nJ(){oo=!1,(await new Xn([`
3
+ var QJ=Object.create;var{getPrototypeOf:DJ,defineProperty:of,getOwnPropertyNames:UJ}=Object;var VJ=Object.prototype.hasOwnProperty;var oW=(o,n,t)=>{t=o!=null?QJ(DJ(o)):{};let T=n||!o||!o.__esModule?of(t,"default",{value:o,enumerable:!0}):t;for(let S of UJ(o))if(!VJ.call(T,S))of(T,S,{get:()=>o[S],enumerable:!0});return T};var nW=(o,n)=>()=>(n||o((n={exports:{}}).exports,n),n.exports);var rJ=(o,n)=>{for(var t in n)of(o,t,{get:n[t],enumerable:!0,configurable:!0,set:(T)=>n[t]=()=>T})};import{join as d0,normalize as u0,resolve as C$}from"path";function zt(o=Math.random){return o().toString(36).slice(2)}class TT extends Promise{fate;resolve;reject;done=!1;constructor(o){let n,t;super((T,S)=>{n=T,t=S});this.resolve=n,this.reject=t,this.use(o instanceof Promise?o:new Promise(o))}pass(o,n){if(o===this.fate)this.resolve(n),this.done=!0}fail(o,n){if(o===this.fate)this.reject(n),this.done=!0}use(o){if(o instanceof Promise){let n=o;this.fate=n,n.then((t)=>{this.pass(n,t)},(t)=>{this.fail(n,t)})}else this.resolve(o),this.fate=void 0}}function sy(o){return Object.entries(o)}var oA=(o,n,t=yo.STORE)=>{return zn(t,{key:`${o.key}:JSON`,get:({get:T})=>n.toJson(T(o)),set:({set:T},S)=>{T(o,n.fromJson(S))}})};function D(o){while(o.child!==null)o=o.child;return o}function nA(o){while(o.parent!==null)o=o.parent;return o}class s{Subscriber;subscribers=new Map;subscribe(o,n){return this.subscribers.set(o,n),()=>{this.unsubscribe(o)}}unsubscribe(o){this.subscribers.delete(o)}next(o){let n=this.subscribers.values();for(let t of n)t(o)}}class nf extends s{state;constructor(o){super();this.state=o}next(o){this.state=o,super.next(o)}}function jn(o,n,t){let T={key:n.key,type:"atom_family"},S=o.families.get(n.key);if(S)o.logger.error("\u2757","atom_family",n.key,`Overwriting an existing ${Hn(S)} "${S.key}" in store "${o.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let f=new s,A=Object.assign((M)=>{let F=l(M),k={key:n.key,subKey:F},W=`${n.key}(${F})`,O=D(o),E=n.default,Q={key:W,default:E instanceof Function?E(M):E};if(n.effects)Q.effects=n.effects(M);let z=tn(O,Q,k);return f.next({type:"state_creation",token:z}),z},T,{subject:f,install:(M)=>jn(M,n),internalRoles:t});return o.families.set(n.key,A),o.defaults.set(n.key,n.default),T}function tA(o,n){if("mutable"in n)return ST(o,n);return jn(o,n)}function xn(o,n,t){let T={key:n.key,type:"readonly_selector_family"},S=o.families.get(n.key);if(S)o.logger.error("\u2757","readonly_selector_family",n.key,`Overwriting an existing ${Hn(S)} "${S.key}" in store "${o.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let f=new s,A=Object.assign((M)=>{let F=l(M),k={key:n.key,subKey:F},W=`${n.key}(${F})`,O=D(o),E=fT(O,{key:W,get:n.get(M)},k);return f.next({type:"state_creation",token:E}),E},T,{internalRoles:t,subject:f,install:(M)=>xn(M,n),default:(M)=>{return n.get(M)({get:(...k)=>Mo(o,...k),find:(k,W)=>ko(o,k,W),seek:(k,W)=>Go(o,k,W),json:(k)=>ro(o,k)})}});return o.families.set(n.key,A),T}function yT(o,n){if("set"in n)return AT(o,n);return xn(o,n)}var BJ={atom_family:"atom",mutable_atom_family:"mutable_atom",selector_family:"selector",readonly_selector_family:"readonly_selector",molecule_family:"molecule"};function Ht(o,n){let t=l(n),T=`${o.key}(${t})`,S=BJ[o.type],f={key:T,type:S};if(S==="molecule")Object.assign(f,{key:n,family:o});else Object.assign(f,{family:{key:o.key,subKey:t}});return Object.assign(f,{counterfeit:!0}),f}function Po(o){let n={key:o.key,type:o.type};if("family"in o)n.family=o.family;return n}var LW=Symbol("provenance");function tf(o,n,t){let T=l(t);try{let S=[],f;if(n==="root")S.push(o.molecules.get('"root"')),f="all";else if(typeof n==="string"&&n.startsWith(CJ)){f="any";let k=l(n),W=o.molecules.get(k);if(!W)throw new Error(`Molecule ${k} not found in store "${o.config.name}"`);S.push(W)}else if(t.startsWith("T$--")){f="all";for(let W of n){let O=l(W),E=o.molecules.get(O);if(!E)throw new Error(`Molecule ${O} not found in store "${o.config.name}"`);S.push(E)}}else{f="any";let W=l(n),O=o.molecules.get(W);if(!O)throw new Error(`Molecule ${W} not found in store "${o.config.name}"`);S.push(O)}let y=new mt(S,t);y._dependsOn=f,o.molecules.set(T,y);for(let k of S)k.below.set(y.stringKey,y);let A={type:"molecule_creation",subType:"modern",key:y.key,provenance:n},M=D(o);if(Fo(M)&&M.transactionMeta.phase==="building")M.transactionMeta.update.updates.push(A);else M.on.moleculeCreationStart.next(A)}catch(S){if(S instanceof Error)o.logger.error("\u274C","molecule",T,"allocation failed:",S.message)}return t}function MT(o,n){let t=l(n),T=o.molecules.get(t);if(!T)throw new Error(`Molecule ${t} not found in store "${o.config.name}"`);for(let F of T.joins.values())F.relations.delete(T.key),F.molecules.delete(T.stringKey);let S;if(T.above.size===1)S=T.above.values().next().value.key;else S=[...T.above.values()].map(({key:F})=>F);let f=[];for(let F of T.tokens.values()){let k=F.family;f.push([k.key,o.valueMap.get(F.key)])}for(let F of T.tokens.values())ao(o,F);for(let F of T.below.values())if(F.dependsOn==="all")MT(o,F.key);else if(F.above.delete(T.stringKey),F.above.size===0)MT(o,F.key);T.below.clear();let y={type:"molecule_disposal",subType:"modern",key:T.key,values:f,provenance:S},A=D(o);if(Fo(A)&&A.transactionMeta.phase==="building")A.transactionMeta.update.updates.push(y);else A.on.moleculeDisposal.next(y);A.molecules.delete(T.stringKey);for(let F of T.above.values())F.below.delete(T.stringKey)}var CJ="T$";function Qt(o){return TA(yo.STORE,o)}function Ft(o){return tA(yo.STORE,o)}function Tf(...o){if(o.length===2)return Mo(yo.STORE,...o);return Mo(yo.STORE,...o)}var Sf=(o)=>(n,t,T,S,...f)=>{console[o](`${n} ${t} "${T}" ${S}`,...f)},LJ={error:Sf("error"),info:Sf("info"),warn:Sf("warn")};class ff{o;n;t;constructor(o,n,t=LJ){this.logLevel=o;this.filter=n;this.logger=t}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)}}function PT(o){return yT(yo.STORE,o)}function FT(o){return yf(o,yo.STORE)}class Mn{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),T=this.relations.get(n);if(t)t.add(n);else t=new Set([n]),this.relations.set(o,t);if(T)T.add(o);else T=new Set([o]),this.relations.set(n,T)}deleteRelation(o,n){let t=this.relations.get(o);if(t){if(t.delete(n),t.size===0)this.relations.delete(o);let T=this.relations.get(n);if(T){if(T.delete(o),T.size===0)this.relations.delete(n)}}}replaceRelationsUnsafely(o,n){this.relations.set(o,new Set(n));for(let t of n){let T=new Set().add(o);this.relations.set(t,T)}}replaceRelationsSafely(o,n){let t=this.relations.get(o),T=this.isAType?.(o)?o:void 0,S=T===void 0?o:void 0;if(t)for(let f of t){T??=f,S??=f;let y=this.relations.get(f);if(y){if(y.size===1)this.relations.delete(f);else y.delete(o);this.contents.delete(this.makeContentKey(T,S))}}this.relations.set(o,new Set(n));for(let f of n){let y=this.relations.get(f);if(y)y.add(o);else y=new Set().add(o),this.relations.set(f,y)}}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,T])=>[t,new Set(T)])),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=(T,S)=>t.has(T,S),this.addRelation=(T,S)=>{t.addRelation(T,S)},this.deleteRelation=(T,S)=>{t.deleteRelation(T,S)},this.replaceRelationsSafely=(T,S)=>{t.replaceRelationsSafely(T,S)},this.replaceRelationsUnsafely=(T,S)=>{t.replaceRelationsUnsafely(T,S)},this.getRelatedKeys=(T)=>t.getRelatedKeys(T),t.getContent)this.getContentInternal=(T)=>{return t.getContent(T)},this.setContent=(T,S)=>{t.setContent(T,S)},this.deleteContent=(T)=>{t.deleteContent(T)};for(let[T,S]of o.relations??[]){let f=this.isAType?.(T)?T:void 0,y=f===void 0?T:void 0;for(let A of S)f??=A,y??=A,this.addRelation(f,y)}for(let[T,S]of o.contents??[])this.setContent(T,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,...n){let t=typeof n[0]==="string"?n[0]:o[this.b],T=n[1]??typeof n[0]==="string"?void 0:n[0];switch(o=typeof o==="string"?o:o[this.a],this.cardinality){case"1:1":{let S=this.getRelatedKey(o);if(S&&S!==t)this.delete(o,S)}case"1:n":{let S=this.getRelatedKey(t);if(S&&S!==o)this.delete(S,t)}}if(T){let S=this.makeContentKey(o,t);this.setContent(S,T)}return this.addRelation(o,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 T=this.getRelatedKeys(n);if(T)for(let S of T)this.delete(S,n)}if(typeof t==="string"&&n===void 0){let T=this.getRelatedKeys(t);if(T)for(let S of T)this.delete(t,S)}if(typeof t==="string"&&typeof n==="string"){this.deleteRelation(t,n);let T=this.makeContentKey(t,n);this.deleteContent(T)}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((T)=>`"${T}"`).join(", ")}). Only one related key was expected.`);let t;for(let T of n){t=T;break}return t}}replaceRelations(o,n,t){let T=!Array.isArray(n),S=T?Object.keys(n):n;if(t?.reckless)this.replaceRelationsUnsafely(o,S);else this.replaceRelationsSafely(o,S);if(T)for(let f of S){let y=this.makeContentKey(o,f),A=n[f];this.setContent(y,A)}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 T=this.getRelatedKeys(n);if(T)return[...T].map((S)=>{return[S,this.getContent(n,S)]})}if(n===void 0&&t!==void 0){let T=this.getRelatedKeys(t);if(T)return[...T].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)}}function Bo(o){return"epoch"in o.transactionMeta}function Fo(o){return"phase"in o.transactionMeta}var fA=(o)=>{let n=D(o);if(!Fo(n)){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",n.transactionMeta.update.key,"Aborting transaction"),n.parent.child=null};var IJ=(o)=>o[0].toUpperCase()+o.slice(1);function Hn(o){return o.type.split("_").map(IJ).join(" ")}class Tn extends Error{constructor(...o){let n=o[0],t=o.length===2?o[1]:o[2];if(o.length===2)super(`${Hn(n)} ${l(n.key)} not found in store "${t.config.name}".`);else{let T=o[1];super(`${Hn(n)} "${n.key}" member ${l(T)} not found in store "${t.config.name}".`)}}}function dn(o,n,t){return(...T)=>{let S=d(o,t);if(S)return S.run(T,n);throw new Tn(o,t)}}var eT=(o)=>(n)=>o instanceof Function?o(n):o;var un=(o,n)=>{if(n.valueMap.has(o.key))return n.logger.info("\uD83D\uDCD6",o.type,o.key,"reading cached value"),yA(o,n);if(o.type==="selector"||o.type==="readonly_selector")return n.logger.info("\uD83E\uDDEE",o.type,o.key,"computing value"),o.get();let t=o.default instanceof Function?o.default():o.default;return n.logger.info("\uD83D\uDC81","atom",o.key,"could not find cached value; using default",t),o.default instanceof Function?o.default():o.default};var AA=(o,n)=>{if(o.operation.open){let t=performance.now();return o.logger.info("\u2757",n.type,n.key,`deferring setState at T-${t} until setState for "${o.operation.token.key}" is done`),t}o.operation={open:!0,done:new Set,prev:new Map,time:Date.now(),token:n},o.logger.info("\u2B55",n.type,n.key,`operation start in store "${o.config.name}"${!Fo(o)?"":` ${o.transactionMeta.phase} "${o.transactionMeta.update.key}"`}`)},MA=(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)},FA=(o,n)=>{if(!o.operation.open)return o.logger.error("\uD83D\uDC1E","unknown",n,"isDone called outside of an operation. This is probably a bug in AtomIO."),!0;return o.operation.done.has(n)},Dt=(o,n)=>{if(!o.operation.open){o.logger.error("\uD83D\uDC1E","unknown",n,"markDone called outside of an operation. This is probably a bug in AtomIO.");return}o.operation.done.add(n)};var kA=(o,n,t)=>{switch(o.type){case"mutable_atom":t.logger.info("\uD83D\uDCE2",o.type,o.key,"is now (",n.newValue,") subscribers:",o.subject.subscribers);break;default:t.logger.info("\uD83D\uDCE2",o.type,o.key,"went (",n.oldValue,"->",n.newValue,") subscribers:",o.subject.subscribers)}o.subject.next(n)};var Af=(o,n)=>{let t=D(n),T=t.selectorAtoms.getRelatedKeys(o.key);if(t.logger.info("\uD83E\uDDF9",o.type,o.key,T?`evicting ${T.size} states downstream:`:"no downstream states",T??"to evict"),T){if(t.operation.open)t.logger.info("\uD83E\uDDF9",o.type,o.key,`[ ${[...t.operation.done].join(", ")} ] already done`);for(let S of T){if(FA(t,S))continue;$A(S,t),Dt(t,S)}}};function jJ(o,n){if(RA(n.newValue))return!1;if(o.includes("\uD83D\uDD0D"))return!1;return!0}var JA=(o,n,t)=>{let{key:T}=o,S=D(t);if(!Fo(S)||S.transactionMeta.phase!=="building"){t.logger.error("\uD83D\uDC1E","atom",T,"stowUpdate called outside of a transaction. This is probably a bug.");return}if(!jJ(T,n))return;let y={type:"atom_update",key:T,...n};if(o.family)y.family=o.family;S.transactionMeta.update.updates.push(y),t.logger.info("\uD83D\uDCC1","atom",T,"stowed (",n.oldValue,"->",n.newValue,")")};var WA=(o,n,t)=>{let T=un(o,t),S=T;if(o.type==="mutable_atom"&&Fo(t)){let{parent:y}=t;S=kT(o,y,t)}if(S=eT(n)(S),t.logger.info("\uD83D\uDCDD","atom",o.key,"set to",S),S=Rn(o.key,S,o.subject,t),OA(o.key,t))_A(o.key,t);Dt(t,o.key),Af(o,t);let f={oldValue:T,newValue:S};if(Bo(t))kA(o,f,t);else if(t.parent){if(t.on.transactionApplying.state===null)JA(o,f,t);else if(o.key.startsWith("*")){let y=o.key.slice(1),A=t.atoms.get(y),M=t.valueMap.get(y);if(A.type==="mutable_atom"&&Fo(t)){let{parent:k}=t;M=kT(A,k,t)}if(M.do(f.newValue)===null)Af(A,t)}}};var lT=(o,n,t)=>{switch(o.type){case"atom":case"mutable_atom":WA(o,n,t);break;case"selector":o.set(n);break}};function gT(o,n){if(n.family){let t=o.families.get(n.family.key);if(t)return t}}function Qo(o,...n){let t,T,S,f;if(n.length===2){if(t=n[0],f=n[1],T=gT(o,t)??null,T)S=t.family?bo(t.family.subKey):null,t=ko(o,T,S)}else T=n[0],S=n[1],f=n[2],t=ko(o,T,S);if("counterfeit"in t){let M=o.disposalTraces.buffer.find((F)=>F?.key===t.key);o.logger.error("\u274C",t.type,t.key,`could not be set because it was not found in the store "${o.config.name}".`,M?`This state was previously disposed:\n${M.trace}`:"No previous disposal trace was found.");return}let y=AA(o,t);if(y){let M=o.on.operationClose.subscribe(`waiting to set "${t.key}" at T-${y}`,()=>{M(),o.logger.info("\uD83D\uDFE2",t.type,t.key,`resuming deferred setState from T-${y}`),Qo(o,t,f)});return}let A=d(t,o);lT(A,f,o),MA(o)}function dT(o,n,t){let{key:T,newValue:S,oldValue:f}=n,y=o==="newValue"?S:f,A={key:T,type:"atom"};if(n.family)Object.assign(A,{family:n.family});Qo(t,A,y)}function wA(o,n){let t=new s,T={type:"molecule_family",key:n.key,dependsOn:n.dependsOn??"all"},S={...T,subject:t,new:n.new};return o.moleculeFamilies.set(n.key,S),T}function mn(o,n,t){let T=vn(t,n,o.key);o.tokens.set(T.key,T);let S=Fo(t)&&t.transactionMeta.phase==="building",f=t.moleculeInProgress===o.key;if(!S&&!f)o.subject.next({type:"state_creation",token:T});return T}class No extends Set{mode="record";subject=new s;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:${l(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:${l(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 T of this.transactionUpdates)this.doStep(T);this.cacheUpdateNumber++,this.emit(`tx:${this.transactionUpdates.join(";")}`)}}catch(t){throw console.error("Failed to apply transaction to SetRTX:",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),T=o.substring(n+1);switch(t){case"add":this.add(JSON.parse(T));break;case"clear":this.clear();break;case"del":this.delete(JSON.parse(T));break;case"tx":for(let S of T.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)),T=t-this.cacheUpdateNumber;if(T>0){if(T===1){this.mode="playback";let f=o.substring(n+1);return this.doStep(f),this.mode="record",this.cacheUpdateNumber=t,null}return this.cacheUpdateNumber+1}if(Math.abs(T)<this.cacheLimit){let f=this.cacheIdx+T;if(this.cache[f]===o)return null;this.mode="playback";let A=!1;while(!A){this.cacheIdx%=this.cacheLimit;let F=this.cache[this.cacheIdx];if(this.cacheIdx--,!F)return"OUT_OF_RANGE";this.undo(F),A=this.cacheIdx===f-1}let M=o.substring(n+1);return this.doStep(M),this.mode="record",this.cacheUpdateNumber=t,null}return"OUT_OF_RANGE"}undoStep(o){let n=o.indexOf(":"),t=o.substring(0,n),T=o.substring(n+1);switch(t){case"add":this.delete(JSON.parse(T));break;case"del":this.add(JSON.parse(T));break;case"clear":{let S=JSON.parse(T);for(let f of S)this.add(f);break}case"tx":{let S=T.split(";");for(let f=S.length-1;f>=0;f--)this.undoStep(S[f])}}}undo(o){let n=o.indexOf("=");if(Number(o.substring(0,n))===this.cacheUpdateNumber){this.mode="playback";let T=o.substring(n+1);return this.undoStep(T),this.mode="record",this.cacheUpdateNumber--,null}return this.cacheUpdateNumber}}function Ho(o){return o[0].toUpperCase()+o.slice(1)}class kf{options;defaultContent;toolkit;retrieve;molecules=new Map;relations;states;core;transact(o,n){let t=this.toolkit;this.toolkit=o,n(this),this.toolkit=t}store;alternates;[Symbol.dispose](){this.alternates.delete(this.store.config.name)}in(o){let n=o.config.name,t=this.alternates.get(n);if(t)return t;let T=new kf(this.options,this.defaultContent,o);return this.alternates.set(n,T),T.alternates=this.alternates,T}constructor(o,n,t=yo.STORE){this.store=t,this.options=o,this.defaultContent=n,this.alternates=new Map,this.alternates.set(t.config.name,this),this.store.miscResources.set(`join:${o.key}`,this),this.retrieve=(Y,K)=>{let U=this.toolkit.seek(Y,K);if(U)return U;let p=this.store.molecules.get(l(K));if(p){let b=d(Y,t);return mn(p,b,t)}if(t.config.lifespan==="immortal")throw new Tn(Y,K,t);return vn(t,Y,K)},this.toolkit={get:(...Y)=>Mo(t,...Y),set:(...Y)=>{Qo(t,...Y)},find:this.retrieve,seek:(...Y)=>Go(t,...Y),json:(Y)=>ro(t,Y),dispose:(...Y)=>{ao(t,...Y)}};let T=o.between[0],S=o.between[1],f=ST(t,{key:`${o.key}/relatedKeys`,default:()=>new No,mutable:!0,fromJson:(Y)=>No.fromJSON(Y),toJson:(Y)=>Y.toJSON()},["join","relations"]);this.core={findRelatedKeysState:f};let y=({get:Y},K)=>Y(this.retrieve(f,K)),A=(Y,K,U)=>{let{set:p}=Y,b=this.retrieve(f,K),w=this.retrieve(f,U);p(b,(v)=>v.add(U)),p(w,(v)=>v.add(K))},M=(Y,K,U)=>{let{set:p}=Y,b=this.retrieve(f,K),w=this.retrieve(f,U),v,j;p(b,(a)=>{if(a.delete(U),a.size===0)v=`"${K}"`;return a}),p(w,(a)=>{if(a.delete(K),a.size===0)j=`"${U}"`;return a})},F=(Y,K,U)=>{let{get:p,set:b}=Y,w=this.retrieve(f,K),v=p(w);for(let j of v){if(U.includes(j))continue;let oo=this.retrieve(f,j);b(oo,(no)=>{return no.delete(K),no})}b(w,(j)=>{return j.transaction((a)=>{a.clear();for(let oo of U){let no=y(Y,oo),_o=no.has(K);if(this.relations.cardinality==="1:n"){let An=[];for(let H of no){if(H===K)continue;let i=y(Y,H);if(i.delete(oo),i.size===0)An.push(H)}if(!_o&&no.size>0)no.clear();for(let H of An){let i=[oo,H].sort(),fo=`"${i[0]}:${i[1]}"`;this.molecules.delete(fo)}}if(!_o)no.add(K);a.add(oo)}return!0}),j})},k=(Y,K,U)=>{let{set:p}=Y,b=this.retrieve(f,K);p(b,(w)=>{return w.transaction((v)=>{for(let j of U)v.add(j);return!0}),w});for(let w of U){let v=this.retrieve(f,w);p(v,(j)=>{return j.add(K),j})}return!0},W=(Y,K,U)=>{let p=y(Y,K);return U?p.has(U):p.size>0},O={getRelatedKeys:(Y)=>y(this.toolkit,Y),addRelation:(Y,K)=>{A(this.toolkit,Y,K)},deleteRelation:(Y,K)=>{M(this.toolkit,Y,K)},replaceRelationsSafely:(Y,K)=>{F(this.toolkit,Y,K)},replaceRelationsUnsafely:(Y,K)=>{k(this.toolkit,Y,K)},has:(Y,K)=>W(this.toolkit,Y,K)},E,Q,z;if(n){Q=jn(t,{key:`${o.key}/content`,default:n},["join","content"]),z=wA(t,{key:`${o.key}/content-molecules`,new:class b{v;constructor(w,v){this.key=v}}});let Y=({get:b},w)=>b(this.retrieve(Q,w)),K=({set:b},w,v)=>{b(this.retrieve(Q,w),v)},U=(b,w)=>{let v=t.molecules.get(`"${w}"`);if(v)this.toolkit.dispose(v),this.molecules.delete(`"${w}"`)};E=Object.assign(O,{getContent:(b)=>{return Y(this.toolkit,b)},setContent:(b,w)=>{K(this.toolkit,b,w)},deleteContent:(b)=>{U(this.toolkit,b)}})}else E=O;let G=new Mn(o,{externalStore:E,isAType:o.isAType,isBType:o.isBType,makeContentKey:(...Y)=>{let K=Y.sort(),U=`${K[0]}:${K[1]}`,[p,b]=K.map((w)=>this.molecules.get(l(w)));if(t.config.lifespan==="immortal"&&p&&b){let w=D(t),v=pn(w,[p,b],z,U);this.molecules.set(`"${U}"`,d(v,w))}return U}}),V=()=>xn(t,{key:`${o.key}/singleRelatedKey`,get:(Y)=>({get:K})=>{let U=this.retrieve(f,Y),p=K(U);for(let b of p)return b;return null}},["join","keys"]),x=()=>{return xn(t,{key:`${o.key}/multipleRelatedKeys`,get:(Y)=>({get:K})=>{let U=Ff(f,t),p=this.retrieve(U,Y);return K(p).members}},["join","keys"])},c=()=>xn(t,{key:`${o.key}/singleRelatedEntry`,get:(Y)=>({get:K})=>{let U=this.retrieve(f,Y),p=K(U);for(let b of p){let w=G.isAType?.(Y)?Y:void 0,v=w===void 0?Y:void 0;w??=b,v??=b;let j=G.makeContentKey(w,v),a=this.retrieve(Q,j),oo=K(a);return[b,oo]}return null}},["join","entries"]),P=()=>xn(t,{key:`${o.key}/multipleRelatedEntries`,get:(Y)=>({get:K})=>{let U=Ff(f,t),p=this.retrieve(U,Y);return K(p).members.map((w)=>{let v=G.isAType?.(Y)?Y:void 0,j=v===void 0?Y:void 0;v??=w,j??=w;let a=G.makeContentKey(v,j),oo=this.retrieve(Q,a),no=K(oo);return[w,no]})}},["join","entries"]);switch(o.cardinality){case"1:1":{let Y=V(),K=`${T}KeyOf${Ho(S)}`,U=`${S}KeyOf${Ho(T)}`,p={[K]:Y,[U]:Y},b;if(n){let w=c(),v=`${T}EntryOf${Ho(S)}`,j=`${S}EntryOf${Ho(T)}`,a={[v]:w,[j]:w};b=Object.assign(p,a)}else b=p;this.relations=G,this.states=b;break}case"1:n":{let Y=V(),K=x(),U=`${T}KeyOf${Ho(S)}`,p=`${S}KeysOf${Ho(T)}`,b={[U]:Y,[p]:K},w;if(n){let v=c(),j=P(),a=`${T}EntryOf${Ho(S)}`,oo=`${S}EntriesOf${Ho(T)}`,no={[a]:v,[oo]:j};w=Object.assign(b,no)}else w=b;this.relations=G,this.states=w;break}default:{let Y=x(),K=`${T}KeysOf${Ho(S)}`,U=`${S}KeysOf${Ho(T)}`,p={[K]:Y,[U]:Y},b;if(n){let w=P(),v=`${T}EntriesOf${Ho(S)}`,j=`${S}EntriesOf${Ho(T)}`,a={[v]:w,[j]:w};b=Object.assign(p,a)}else b=p;this.relations=G,this.states=b}}}}function uT(o,n,t=yo.STORE){return Mf(t).set(o.key,new kf(o,n,t)),{key:o.key,type:"join",a:o.between[0],b:o.between[1],cardinality:o.cardinality}}function Mf(o){if("joins"in o&&o.joins instanceof Map)return o.joins;let n=new Map;return o.joins=n,n}function $T(o,n){let t=Mf(n),T=t.get(o.key);if(T===void 0){if(T=Mf(yo.STORE).get(o.key)?.in(n),T===void 0)throw new Error(`Join "${o.key}" not found in store "${n.config.name}"`);t.set(o.key,T)}return T}function aT(o,n,t){let T=$T(o,t),S;switch(o.cardinality){case"1:1":{let f=`${o.a}KeyOf${Ho(o.b)}`,y=`${o.b}KeyOf${Ho(o.a)}`;S={get[f](){let M=T.states[f];return T.retrieve(M,n)},get[y](){let M=T.states[y];return T.retrieve(M,n)}};let A=`${o.a}EntryOf${Ho(o.b)}`;if(A in T.states){let M=`${o.b}EntryOf${Ho(o.a)}`;Object.assign(S,{get[A](){let F=T.states[A];return T.retrieve(F,n)},get[M](){let F=T.states[M];return T.retrieve(F,n)}})}break}case"1:n":{let f=`${o.a}KeyOf${Ho(o.b)}`,y=`${o.b}KeysOf${Ho(o.a)}`;S={get[f](){let M=T.states[f];return T.retrieve(M,n)},get[y](){let M=T.states[y];return T.retrieve(M,n)}};let A=`${o.a}EntryOf${Ho(o.b)}`;if(A in T.states){let M=`${o.b}EntriesOf${Ho(o.a)}`;Object.assign(S,{get[A](){let F=T.states[A];return T.retrieve(F,n)},get[M](){let F=T.states[M];return T.retrieve(F,n)}})}break}case"n:n":{let f=`${o.a}KeysOf${Ho(o.b)}`,y=`${o.b}KeysOf${Ho(o.a)}`;S={get[f](){let M=T.states[f];return T.retrieve(M,n)},get[y](){let M=T.states[y];return T.retrieve(M,n)}};let A=`${o.a}EntriesOf${Ho(o.b)}`;if(A in T.states){let M=`${o.b}EntriesOf${Ho(o.a)}`;Object.assign(S,{get[A](){let F=T.states[A];return T.retrieve(F,n)},get[M](){let F=T.states[M];return T.retrieve(F,n)}})}}}return S}function KA(o,n){return aT(o,n,yo.STORE)}function sT(o,n,t){let T=$T(o,t),S=D(t);if(Fo(S)){let{toolkit:f}=S.transactionMeta;T.transact(f,({relations:y})=>{n(y)})}else n(T.relations)}function bJ(o,n){return $T(o,n).core.findRelatedKeysState}function XA(o){return bJ(o,yo.STORE)}function oS(o){return{store:o}}function Mo(o,...n){let t,T,S;if(n.length===1){if(t=n[0],t.type!=="molecule"){if(T=gT(o,t)??null,T)S=t.family?bo(t.family.subKey):null,t=ko(o,T,S)}}else{T=n[0],S=n[1];let f;if(T.type==="molecule_family")f=Go(o,T,S)??Ht(T,S);else f=ko(o,T,S);t=f}if("counterfeit"in t&&"family"in t){T=t.type==="molecule"?d(t.family,o):o.families.get(t.family.key);let f=t.type==="molecule"?t.key:t.family.subKey,y=o.disposalTraces.buffer.find((A)=>A?.key===t.key);switch(o.logger.error("\u274C",t.type,t.key,`could not be retrieved because it was not found in the store "${o.config.name}".`,y?`This state was previously disposed:\n${y.trace}`:"No previous disposal trace was found."),T.type){case"atom_family":case"mutable_atom_family":return o.defaults.get(T.key);case"selector_family":case"readonly_selector_family":{if(o.defaults.has(T.key))return o.defaults.get(t.family.key);let A=d(T,o).default(f);return o.defaults.set(T.key,A),A}case"molecule_family":throw new Tn(T,f,o)}}switch(t.type){case"atom":case"mutable_atom":case"selector":case"readonly_selector":return un(d(t,o),o);case"molecule":return d(t,o).instance}}class mt{n;type="molecule";stringKey;family;_dependsOn;get dependsOn(){if(this.family)return this.family.dependsOn;return this._dependsOn}subject=new s;tokens=new Map;above=new Map;below=new Map;joins=new Map;instance;constructor(o,n,t){this.key=n;if(this.stringKey=l(n),t)this.family=t,this._dependsOn=t.dependsOn;if(o)for(let T of o)this.above.set(T.stringKey,T)}}function EA(o){return o[0].toUpperCase()+o.slice(1)}function pn(o,n,t,T,...S){let f=nA(o),y=D(o),A=l(T);y.moleculeInProgress=A;let M=Array.isArray(n)?n:[n],F=M.map((G)=>{if(G instanceof mt)return G;let V=l(G.key),x=o.molecules.get(V);if(!x)throw new Error(`Molecule ${V} not found in store "${o.config.name}"`);return x}),k=new mt(F,T,t);y.molecules.set(A,k);for(let G of F)G.below.set(k.stringKey,k);let W={get:(...G)=>Mo(D(f),...G),set:(...G)=>{Qo(D(f),...G)},seek:(G,V)=>Go(D(f),G,V),json:(G)=>ro(D(f),G),run:(G,V=zt())=>dn(G,V,D(o)),make:(G,V,x,...c)=>pn(D(f),G,V,x,...c),dispose:(G)=>{ao(D(f),G)},env:()=>oS(D(f)),bond:(G,V)=>{if(G.type==="join"){let{as:x}=V,c=$T(G,f);c.molecules.set(A,k),k.joins.set(G.key,c);let P=O.subject.subscribe(`join:${G.key}-${A}`,(w)=>{if(w.type==="molecule_disposal"){if(l(w.token.key)===A)P(),c.molecules.delete(A)}});if(x===null)return;let Y=G.a===x?G.b:G.a,K=KA(G,T),U=K[`${Y}KeysOf${EA(x)}`],p=K[`${Y}EntriesOf${EA(x)}`],b={relatedKeys:U};if(p)b=Object.assign(b,{relatedEntries:p});return b}return mn(k,d(G,f),D(f))},claim:(G,V)=>{let{exclusive:x}=V,c=D(o).molecules.get(l(G.key));if(c)if(x){for(let P of c.above.values())P.below.delete(c.stringKey);c.above.clear(),c.above.set(k.stringKey,k),k.below.set(c.stringKey,c)}else c.above.set(k.stringKey,k),k.below.set(c.stringKey,c)},spawn:(G,V,...x)=>pn(D(o),[k],d(G,o),V,...x)},O=d(t,o),E=O.new;k.instance=new E(W,T,...S);let Q={type:"molecule",key:T,family:t},z={type:"molecule_creation",subType:"classic",token:Q,family:t,context:M,params:S};if(Bo(y))O.subject.next(z);else if(Fo(y)&&y.on.transactionApplying.state===null)y.transactionMeta.update.updates.push(z);return y.moleculeInProgress=null,Q}function $f(o,n,t){switch(n){case"newValue":{YA(o,t);break}case"oldValue":{ao(t,o.token);break}}}function Jf(o,n,t){switch(n){case"newValue":{ao(t,o.token);break}case"oldValue":{YA(o,t),t.valueMap.set(o.token.key,o.value);break}}}function YA(o,n){let{family:t}=o.token;if(t){let T=n.families.get(t.key);if(T)ko(n,T,bo(t.subKey))}}function Rf(o,n,t){switch(n){case"newValue":switch(o.subType){case"classic":pn(t,o.context,o.family,o.token.key,...o.params);break;case"modern":tf(t,o.provenance,o.key);break}break;case"oldValue":switch(o.subType){case"classic":ao(t,o.token);break;case"modern":MT(t,o.key);break}break}}function Wf(o,n,t){switch(n){case"newValue":switch(o.subType){case"classic":ao(t,o.token);break;case"modern":MT(t,o.key);break}break;case"oldValue":switch(o.subType){case"classic":{let T=pn(t,o.context,o.family,o.token.key);for(let[S,f]of o.values){let y=`${S}(${l(T.key)})`,A=d(T,t),M=A.tokens.has(y),F=t.families.get(S);if(F&&!M)mn(A,F,t);t.valueMap.set(y,f)}}break;case"modern":{tf(t,o.provenance,o.key);for(let[T,S]of o.values){let f=t.families.get(T);if(f){ko(t,f,o.key);let y=`${T}(${l(o.key)})`;t.valueMap.set(y,S)}}}}break}}function nS(o,n,t){let T=o==="newValue"?n.updates:[...n.updates].reverse();for(let S of T)switch(S.type){case"atom_update":case"selector_update":dT(o,S,t);break;case"state_creation":$f(S,o,t);break;case"state_disposal":Jf(S,o,t);break;case"molecule_creation":Rf(S,o,t);break;case"molecule_disposal":Wf(S,o,t);break;case"transaction_update":nS(o,S,t);break}}function GA(o,n,t){if(Bo(t)&&o)t.transactionMeta.epoch.set(o,n)}function zA(o,n,t){if(!Bo(t))return;let S=t.transactionMeta.actionContinuities.getRelatedKey(o);if(S!==void 0)t.transactionMeta.epoch.set(S,n)}var HA=(o,n)=>{let t=D(n),{parent:T}=t;if(T===null||!Fo(t)||t.transactionMeta?.phase!=="building"){n.logger.warn("\uD83D\uDC1E","transaction","???","applyTransaction called outside of a transaction. This is probably a bug in AtomIO.");return}t.transactionMeta.phase="applying",t.transactionMeta.update.output=o,T.child=null,T.on.transactionApplying.next(t.transactionMeta);let{updates:S}=t.transactionMeta.update;if(n.logger.info("\uD83D\uDEC4","transaction",t.transactionMeta.update.key,`Applying transaction with ${S.length} updates:`,S),nS("newValue",t.transactionMeta.update,T),Bo(T))zA(t.transactionMeta.update.key,t.transactionMeta.update.epoch,T),d({key:t.transactionMeta.update.key,type:"transaction"},n)?.subject.next(t.transactionMeta.update),n.logger.info("\uD83D\uDEEC","transaction",t.transactionMeta.update.key,"Finished applying transaction.");else if(Fo(T))T.transactionMeta.update.updates.push(t.transactionMeta.update);T.on.transactionApplying.next(null)};function mA(o,n,t){if(!Bo(t))return;let{epoch:S,actionContinuities:f}=t.transactionMeta;if(f.set(o,n),!S.has(o))S.set(o,-1)}class Wn extends Map{o;deleted=new Set;constructor(o){super();this.source=o}get(o){if(super.has(o))return super.get(o);if(!this.deleted.has(o)&&this.source.has(o))return this.source.get(o);return}set(o,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 QA=(o,n,t,T)=>{let S=D(t),f={parent:S,child:null,on:S.on,loggers:S.loggers,logger:S.logger,config:S.config,atoms:new Wn(S.atoms),atomsThatAreDefault:new Set(S.atomsThatAreDefault),families:new Wn(S.families),operation:{open:!1},readonlySelectors:new Wn(S.readonlySelectors),timelines:new Wn(S.timelines),timelineTopics:new Mn(S.timelineTopics.toJSON()),trackers:new Map,transactions:new Wn(S.transactions),selectorAtoms:new Mn(S.selectorAtoms.toJSON()),selectorGraph:new Mn(S.selectorGraph.toJSON(),{makeContentKey:(...F)=>F.sort().join(":")}),selectors:new Wn(S.selectors),valueMap:new Wn(S.valueMap),defaults:S.defaults,disposalTraces:t.disposalTraces.copy(),molecules:new Wn(S.molecules),moleculeFamilies:new Wn(S.moleculeFamilies),moleculeInProgress:S.moleculeInProgress,miscResources:new Wn(S.miscResources)},y=DA(o,t),A={phase:"building",update:{type:"transaction_update",key:o,id:T,epoch:y===void 0?Number.NaN:y+1,updates:[],params:n,output:void 0},toolkit:{get:(...F)=>Mo(M,...F),set:(...F)=>{Qo(M,...F)},run:(F,k=zt())=>dn(F,k,M),find:(F,k)=>ko(M,F,k),seek:(F,k)=>Go(M,F,k),json:(F)=>ro(M,F),make:(F,k,W,...O)=>pn(M,F,k,W,...O),dispose:(...F)=>{ao(M,...F)},env:()=>oS(M)}},M=Object.assign(f,{transactionMeta:A});return S.child=M,t.logger.info("\uD83D\uDEEB","transaction",o,"Building transaction with params:",n),M};function yf(o,n){let t={key:o.key,type:"transaction",run:(f,y)=>{let A=QA(o.key,f,n,y);try{let M=D(n),{toolkit:F}=A.transactionMeta,k=o.do(F,...f);return HA(k,M),k}catch(M){throw fA(T),n.logger.warn("\uD83D\uDCA5","transaction",o.key,"caught:",M),M}},install:(f)=>yf(o,f),subject:new s},T=D(n);T.transactions.set(t.key,t);let S=Po(t);return n.on.transactionCreation.next(S),S}function DA(o,n){let t=Bo(n),T=t?n.transactionMeta.actionContinuities.getRelatedKey(o):void 0;return t&&T!==void 0?n.transactionMeta.epoch.get(T):void 0}class tS{_buffer;_index=0;constructor(o){let n;if(typeof o==="number")n=o;else n=o.length;this._buffer=Array.from({length:n})}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 tS([...this._buffer]);return o._index=this._index,o}}class UA{parent=null;child=null;valueMap=new Map;defaults=new Map;atoms=new Map;selectors=new Map;readonlySelectors=new Map;atomsThatAreDefault=new Set;selectorAtoms=new Mn({between:["selectorKey","atomKey"],cardinality:"n:n"});selectorGraph=new Mn({between:["upstreamSelectorKey","downstreamSelectorKey"],cardinality:"n:n"},{makeContentKey:(...o)=>o.sort().join(":")});trackers=new Map;families=new Map;transactions=new Map;transactionMeta={epoch:new Map,actionContinuities:new Mn({between:["continuity","action"],cardinality:"1:n"})};timelines=new Map;timelineTopics=new Mn({between:["timelineKey","topicKey"],cardinality:"1:n"});disposalTraces=new tS(100);molecules=new Map;moleculeFamilies=new Map;moleculeInProgress=null;miscResources=new Map;on={atomCreation:new s,atomDisposal:new s,selectorCreation:new s,selectorDisposal:new s,timelineCreation:new s,transactionCreation:new s,transactionApplying:new nf(null),operationClose:new s,moleculeCreationStart:new s,moleculeCreationDone:new s,moleculeDisposal:new s};operation={open:!1};config={name:"IMPLICIT_STORE",lifespan:"ephemeral"};loggers=[new ff("warn",(o,n,t)=>!t.includes("\uD83D\uDD0D"))];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},Bo(n))this.transactionMeta={epoch:new Map(n?.transactionMeta.epoch),actionContinuities:new Mn(n?.transactionMeta.actionContinuities.toJSON())};for(let[,T]of n.families){if(T.internalRoles?.includes("mutable")||T.internalRoles?.includes("join"))continue;T.install(this)}let t=new Set;for(let[,T]of n.atoms){if(t.has(T.key))continue;if(T.install(this),T.type==="mutable_atom"){let S=ro(n,T),f=qn(T);t.add(S.key),t.add(f.key)}}for(let[,T]of n.readonlySelectors)T.install(this);for(let[,T]of n.selectors){if(t.has(T.key))continue;T.install(this)}for(let[,T]of n.transactions)T.install(this);for(let[,T]of n.timelines)T.install(this)}}}var yo={get STORE(){if(!globalThis.ATOM_IO_IMPLICIT_STORE)globalThis.ATOM_IO_IMPLICIT_STORE=new UA({name:"IMPLICIT_STORE",lifespan:"ephemeral"});return globalThis.ATOM_IO_IMPLICIT_STORE}};function d(o,n){let t,T=n;while(T!==null){switch(o.type){case"atom":case"mutable_atom":t=T.atoms.get(o.key);break;case"selector":t=T.selectors.get(o.key);break;case"readonly_selector":t=T.readonlySelectors.get(o.key);break;case"atom_family":case"mutable_atom_family":case"selector_family":case"readonly_selector_family":t=T.families.get(o.key);break;case"timeline":t=T.timelines.get(o.key);break;case"transaction":t=T.transactions.get(o.key);break;case"molecule":t=T.molecules.get(l(o.key));break;case"molecule_family":t=T.moleculeFamilies.get(o.key);break}if(t)return t;T=T.child}throw new Tn(o,n)}function TS(o,n){let t;t=d(o,n);let{family:T}=o;for(let y of t.joins.values())y.relations.delete(t.key),y.molecules.delete(t.stringKey);let S=[];for(let y of t.above.values())S.push(Po(y));let f=[];for(let y of t.tokens.values()){let A=y.family;f.push([A.key,n.valueMap.get(y.key)])}if(T){let y=d(T,n),A={type:"molecule_disposal",subType:"classic",token:o,family:T,context:S,values:f};if(o.family)A.family=o.family;for(let F of t.tokens.values())ao(n,F);for(let F of t.below.values())if(F.dependsOn==="all")TS(F,n);else if(F.above.delete(t.stringKey),F.above.size===0)TS(F,n);if(t.below.clear(),Fo(n)&&n.transactionMeta.phase==="building")n.transactionMeta.update.updates.push(A);else y.subject.next(A);n.molecules.delete(t.stringKey)}for(let y of t.above.values())y.below.delete(t.stringKey)}function vn(o,n,t){let T=o.families.get(n.key);if(T===void 0)throw new Tn(n,o);let S=T(t),f=D(o);if(S.family&&f.moleculeInProgress===null){if(Bo(f))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(Fo(f)&&f.on.transactionApplying.state===null)f.transactionMeta.update.updates.push({type:"state_creation",token:S})}return S}function Go(o,n,t){let T=l(t),S=`${n.key}(${T})`,f=D(o),y;switch(n.type){case"atom_family":case"mutable_atom_family":y=f.atoms.get(S);break;case"selector_family":y=f.selectors.get(S);break;case"readonly_selector_family":y=f.readonlySelectors.get(S);break;case"molecule_family":y=f.molecules.get(l(t))}if(y)return Po(y);return y}function ko(o,n,t){let T=Go(o,n,t);if(T)return T;let S=o.molecules.get(l(t));if(S)return mn(S,n,o);if(o.config.lifespan==="immortal"){let f=Ht(n,t);return o.logger.error("\u274C",f.type,f.key,`was not found in store "${o.config.name}"; returned a counterfeit token.`),f}return T=vn(o,n,t),T}function ao(o,...n){let t,T;if(n.length===1)t=n[0],T=t.key;else{let f=n[0],y=n[1];t=f.type==="molecule_family"?Go(o,f,y)??Ht(f,y):ko(o,f,y)}try{d(t,o)}catch(f){let y=o.disposalTraces.buffer.find((A)=>A?.key===t.key);o.logger.error("\u274C",t.type,t.key,`could not be disposed because it was not found in the store "${o.config.name}".`,y?`\n This state was most recently disposed\n${y.trace}`:"No previous disposal trace was found.");return}switch(t.type){case"atom":case"mutable_atom":Of(t,o);break;case"selector":case"readonly_selector":VA(t,o);break;case"molecule":TS(t,o);break}let{stack:S}=new Error;if(S){let f=S?.split("\n")?.slice(3)?.join("\n");o.disposalTraces.add({key:t.key,trace:f})}}var SS=(o,n)=>D(n).atoms.has(o),NJ=(o,n)=>D(n).selectors.has(o),hJ=(o,n)=>D(n).readonlySelectors.has(o),rA=(o,n)=>SS(o,n)||NJ(o,n)||hJ(o,n);var fS=(o,n)=>{return D(n).selectorGraph.getRelationEntries({downstreamSelectorKey:o}).filter(([T,{source:S}])=>S!==o).map(([T,{source:S}])=>S).filter((T)=>rA(T,n))};var _f=(o,n,t)=>{let T=[],S=fS(o,t);while(S.length>0){let f=S.shift();if(n.has(f))continue;if(n.add(f),!SS(f,t))S.push(...fS(f,t));else if(!T.includes(f))T.push(f)}return T},BA=(o,n)=>{let t=o.key,T=fS(t,n),S=new Set;return T.flatMap((f)=>SS(f,n)?f:_f(f,S,n))};var CA=(o,n,t,T)=>{let S=D(T);if(n.type==="atom"||n.type==="mutable_atom")S.selectorAtoms.set({selectorKey:o,atomKey:n.key}),T.logger.info("\uD83D\uDD0D","selector",o,`discovers root atom "${n.key}"`);else{let f=_f(n.key,t,T);T.logger.info("\uD83D\uDD0D","selector",o,`discovers root atoms: [ ${f.map((y)=>`"${y}"`).join(", ")} ]`);for(let y of f)S.selectorAtoms=S.selectorAtoms.set({selectorKey:o,atomKey:y})}t.add(n.key)};var yS=(o,n,t)=>({get:(...T)=>{let S=D(t),f;if(T.length===2){let[M,F]=T;switch(M.type){case"molecule_family":return Mo(t,M,F);default:if(t.config.lifespan==="ephemeral")f=ko(t,M,F);else{let k=Go(t,M,F);if(k)f=k;else throw new Tn(M,F,t)}}}else[f]=T;if(f.type==="molecule")return Mo(t,f);let y=d(f,t),A=un(y,t);return t.logger.info("\uD83D\uDD0C","selector",o,`registers dependency ( "${f.key}" =`,A,")"),S.selectorGraph.set({upstreamSelectorKey:f.key,downstreamSelectorKey:o},{source:f.key}),CA(o,f,n,t),A},set:(...T)=>{let S,f;if(T.length===2)S=T[0],f=T[1];else{let M=T[0],F=T[1];f=T[2];let k=t.config.lifespan==="ephemeral"?ko(t,M,F):Go(t,M,F);if(!k)throw new Tn(M,F,t);S=k}let y=D(t),A=d(S,y);lT(A,f,y)},find:(T,S)=>ko(t,T,S),seek:(T,S)=>Go(t,T,S),json:(T)=>ro(t,T)});var fT=(o,n,t)=>{let T=D(o),S=new s,f=new Set,{get:y,find:A,seek:M,json:F}=yS(n.key,f,T),k=()=>{let Q=n.get({get:y,find:A,seek:M,json:F});return Rn(n.key,Q,S,D(o)),f.clear(),Q},W={...n,subject:S,install:(Q)=>fT(Q,n,t),get:k,type:"readonly_selector",...t&&{family:t}};T.readonlySelectors.set(n.key,W);let O=k();o.logger.info("\u2728",W.type,W.key,"=",O);let E={key:n.key,type:"readonly_selector"};if(t)E.family=t;return E};var JT=(o,n,t)=>{let T=D(o),S=new s,f=new Set,y=yS(n.key,f,T),{find:A,get:M,seek:F,json:k}=y,W={find:A,get:M,seek:F,json:k},O=(V=n.get,x=D(o))=>{let c=V(W);return Rn(n.key,c,S,x),f.clear(),c},Q={...n,subject:S,install:(V)=>JT(V,n,t),get:O,set:(V)=>{let x=D(o),c=O(n.get,x),P=eT(V)(c);if(o.logger.info("\uD83D\uDCDD","selector",n.key,"set (",c,"->",P,")"),Rn(n.key,P,S,x),Dt(x,n.key),Bo(x))S.next({newValue:P,oldValue:c});n.set(y,P)},type:"selector",...t&&{family:t}};T.selectors.set(n.key,Q);let z=O();o.logger.info("\u2728",Q.type,Q.key,"=",z);let G={key:n.key,type:"selector"};if(t)G.family=t;return G};function zn(o,n){if("set"in n){let S=JT(o,n,void 0);return o.on.selectorCreation.next(S),S}let T=fT(o,n,void 0);return o.on.selectorCreation.next(T),T}function VA(o,n){let t=D(n),{key:T}=o,S=d(o,t);if(!S.family)n.logger.error("\u274C","selector",T,"Standalone selectors cannot be disposed.");else{let f=t.molecules.get(S.family.subKey);if(f)f.tokens.delete(T);switch(o.type){case"selector":t.selectors.delete(T),d({key:S.family.key,type:"selector_family"},n).subject.next({type:"state_disposal",token:o});break;case"readonly_selector":t.readonlySelectors.delete(T),d({key:S.family.key,type:"readonly_selector_family"},n).subject.next({type:"state_disposal",token:o});break}if(t.valueMap.delete(T),t.selectorAtoms.delete(T),t.selectorGraph.delete(T),n.logger.info("\uD83D\uDD25",o.type,T,"deleted"),Fo(t)&&t.transactionMeta.phase==="building")t.transactionMeta.update.updates.push({type:"state_disposal",token:o});else n.on.selectorDisposal.next(o)}}function AT(o,n,t){let T={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 ${Hn(S)} "${S.key}" in store "${o.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let f=new s,A=Object.assign((M)=>{let F=l(M),k={key:n.key,subKey:F},W=`${n.key}(${F})`,O=D(o),E=JT(O,{key:W,get:n.get(M),set:n.set(M)},k);return f.next({type:"state_creation",token:E}),E},T,{internalRoles:t,subject:f,install:(M)=>AT(M,n),default:(M)=>{return n.get(M)({get:(...k)=>Mo(o,...k),find:(k,W)=>ko(o,k,W),seek:(k,W)=>Go(o,k,W),json:(k)=>ro(o,k)})}});return o.families.set(n.key,A),T}function LA(o,n,t=yo.STORE){let T=AT(t,{key:`${o.key}:JSON`,get:(f)=>({seek:y,get:A})=>{let M=y(o,f);if(M)return n.toJson(A(M));let F=l(f),k=t.molecules.get(F);if(k){let O=mn(k,o,t);return n.toJson(A(O))}if(t.config.lifespan==="immortal")throw new Error(`No molecule found for key "${F}"`);let W=vn(t,o,f);return n.toJson(A(W))},set:(f)=>({seek:y,set:A},M)=>{let F=y(o,f);if(F)A(F,n.fromJson(M));else{let k=l(f),W=t.molecules.get(k);if(W){let O=mn(W,o,t);A(O,n.fromJson(M))}else{if(t.config.lifespan==="immortal")throw new Error(`No molecule found for key "${k}"`);A(vn(t,o,f),n.fromJson(M))}}}},["mutable","json"]);return d(o,t).subject.subscribe(`store=${t.config.name}::json-selector-family`,(f)=>{if(f.token.family)Go(t,T,bo(f.token.family.subKey))}),T}var bo=(o)=>JSON.parse(o),l=(o)=>JSON.stringify(o),oK=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];var IA=(o,n)=>{let t=D(n);if(t.operation.open)return t.operation.prev.get(o.key);return t.valueMap.get(o.key)};var Xf=(o,n)=>{let t=D(n);return BA(o,n).map((S)=>{let f=t.atoms.get(S);if(f===void 0)throw new Error(`Atom "${S}", a dependency of selector "${o.key}", not found in store "${n.config.name}".`);return f.subject.subscribe(`${o.type}:${o.key}`,(y)=>{n.logger.info("\uD83D\uDCE2",o.type,o.key,"root",S,"went",y.oldValue,"->",y.newValue);let A=IA(o,t),M=un(o,t);n.logger.info("\u2728",o.type,o.key,"went",A,"->",M),o.subject.next({newValue:M,oldValue:A})})})};function eo(o,n,t,T){function S(W){if(T.operation.open){let O=T.on.operationClose.subscribe(`state subscription ${t}`,()=>{O(),n(W)})}else n(W)}let f=d(o,T);T.logger.info("\uD83D\uDC40",f.type,f.key,`Adding subscription "${t}"`);let y=f.type==="selector"||f.type==="readonly_selector",A=null,M=S;if(y)A=Xf(f,T),M=(W)=>{if(A)A.length=0,A.push(...Xf(f,T));S(W)};let F=f.subject.subscribe(t,M);return()=>{if(T.logger.info("\uD83D\uDE48",f.type,f.key,`Removing subscription "${t}"`),F(),A)for(let W of A)W()}}var wf=(o,n,t,T)=>{let S=d(o,T);T.logger.info("\uD83D\uDC40","timeline",o.key,`Adding subscription "${t}"`);let f=S.subject.subscribe(t,n);return()=>{T.logger.info("\uD83D\uDE48","timeline",o.key,`Removing subscription "${t}" from timeline`),f()}};var Kf=(o,n,t,T)=>{let S=d(o,T);T.logger.info("\uD83D\uDC40","transaction",o.key,`Adding subscription "${t}"`);let f=S.subject.subscribe(t,n);return()=>{T.logger.info("\uD83D\uDE48","transaction",o.key,`Removing subscription "${t}"`),f()}};class an{Update;initializeState(o,n){let t=`*${o.key}`;n.atoms.delete(t),n.valueMap.delete(t);let T=o.family?{key:`*${o.family.key}`,subKey:o.family.subKey}:void 0,S=tn(n,{key:t,default:null},T);if(n.parent?.valueMap.has(t)){let f=n.parent.valueMap.get(t);n.valueMap.set(t,f)}return S}unsubscribeFromInnerValue;unsubscribeFromState;observeCore(o,n,t){let T=`tracker:${t.config.name}:${Fo(t)?t.transactionMeta.update.key:"main"}:${o.key}`,S=Mo(t,o);this.unsubscribeFromInnerValue=S.subscribe(T,(f)=>{Qo(t,n,f)}),this.unsubscribeFromState=eo(o,(f)=>{if(f.newValue!==f.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=f.newValue.subscribe(T,(y)=>{Qo(t,n,y)})},T,t)}updateCore(o,n,t){let T=`tracker:${t.config.name}:${Fo(t)?t.transactionMeta.update.key:"main"}:${o.key}`;eo(n,({newValue:S,oldValue:f})=>{let y=t.timelineTopics.getRelatedKey(n.key);if(y){if(t.timelines.get(y)?.timeTraveling){let F=wf({key:y,type:"timeline"},(k)=>{F(),Qo(t,o,(W)=>{if(k==="redo"&&S)W.do(S);else if(k==="undo"&&f)W.undo(f);return W})},T,t);return}}let A=t.on.operationClose.subscribe(T,()=>{A();let M=Mo(t,o),F=S===null?-1:M.getUpdateNumber(S),k=F-M.cacheUpdateNumber;if(S&&k===1)Qo(t,o,(W)=>(W.do(S),W));else t.logger.info("\u274C","mutable_atom",o.key,`could not be updated. Expected update number ${M.cacheUpdateNumber+1}, but got ${F}`)})},T,t)}mutableState;latestUpdateState;dispose;constructor(o,n){this.mutableState=o;let t=D(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.dispose=()=>{this.unsubscribeFromInnerValue(),this.unsubscribeFromState(),t.trackers.delete(o.key)}}}function RT(o,n,t){o.logger.info("\uD83D\uDD28","atom",n.key,`creating in store "${o.config.name}"`);let T=D(o),S=T.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."),Po(S);let f=new s,y={...n,type:"mutable_atom",install:(F)=>{return F.logger.info("\uD83D\uDEE0\uFE0F","atom",n.key,`installing in store "${F.config.name}"`),RT(F,n,t)},subject:f};if(t)y.family=t;let A=n.default();T.atoms.set(y.key,y),AS(n.key,o),Rn(n.key,A,f,T);let M=Po(y);if(n.effects){let F=0,k=[];for(let W of n.effects){let O=W({setSelf:(E)=>{Qo(o,M,E)},onSet:(E)=>eo(M,E,`effect[${F}]`,o)});if(O)k.push(O);++F}y.cleanup=()=>{for(let W of k)W()}}if(new an(M,o),!t)oA(M,n,o);return M}class Ef{Update;latestUpdateAtoms;mutableAtoms;constructor(o,n){let t=jn(n,{key:`*${o.key}`,default:null},["mutable","updates"]);this.latestUpdateAtoms=d(t,n),this.mutableAtoms=o,this.mutableAtoms.subject.subscribe(`store=${n.config.name}::tracker-atom-family`,(T)=>{if(T.token.family){let S=bo(T.token.family.subKey);Go(n,this.latestUpdateAtoms,S),new an(T.token,n)}}),this.latestUpdateAtoms.subject.subscribe(`store=${n.config.name}::tracker-atom-family`,(T)=>{if(T.token.family){let S=bo(T.token.family.subKey),f=Go(n,this.mutableAtoms,S);if(f)new an(f,n)}})}}function ST(o,n,t){let T={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 ${Hn(S)} "${S.key}" in store "${o.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let f=new s,A=Object.assign((M)=>{let F=l(M),k={key:n.key,subKey:F},W=`${n.key}(${F})`,O=D(o),E={key:W,default:()=>n.default(M),toJson:n.toJson,fromJson:n.fromJson,mutable:!0};if(n.effects)E.effects=n.effects(M);let Q=RT(O,E,k);return f.next({type:"state_creation",token:Q}),Q},T,{subject:f,install:(M)=>ST(M,n),toJson:n.toJson,fromJson:n.fromJson,internalRoles:t});return o.families.set(n.key,A),LA(A,n,o),new Ef(A,o),T}var Ff=(o,n)=>{let t=D(n),T=`${o.key}:JSON`;return t.families.get(T)};var ro=(o,n)=>{if(n.family){let T=D(o),f={key:`${n.family.key}:JSON`,type:"selector_family"},y=d(f,T),A=JSON.parse(n.family.subKey);return ko(o,y,A)}return{type:"selector",key:`${n.key}:JSON`}};var qn=(o)=>{let t={type:"atom",key:`*${o.key}`};if(o.family)t.family={key:`*${o.family.key}`,subKey:o.family.subKey};return t};function RA(o){return typeof o==="object"&&o!==null&&"do"in o&&"undo"in o&&"subscribe"in o}function kT(o,n,t){let T=n.valueMap.get(o.key),S=t.valueMap.get(o.key);if(T===S){if(T===void 0)return typeof o.default==="function"?o.default():o.default;n.logger.info("\uD83D\uDCC3","atom",o.key,"copying");let f=o.toJson(T),y=o.fromJson(f);return t.valueMap.set(o.key,y),new an(o,n),y}return S}function Rn(o,n,t,T){let S=T.valueMap.get(o);if(S instanceof TT)S.use(n);if(n instanceof Promise){let f=new TT(n);return T.valueMap.set(o,f),f.then((y)=>{Rn(o,y,t,T),t.next({newValue:y,oldValue:f})}).catch((y)=>{T.logger.error("\uD83D\uDCA5","state",o,"rejected:",y)}),f}return T.valueMap.set(o,n),n}var yA=(o,n)=>{let t=n.valueMap.get(o.key);if(o.type==="mutable_atom"&&Fo(n)){let{parent:T}=n;t=kT(o,T,n)}return t},$A=(o,n)=>{let t=n.valueMap.get(o);if(t instanceof TT){let T=t,S=n.selectors.get(o)??n.readonlySelectors.get(o);if(S)T.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 OA=(o,n)=>{return D(n).atomsThatAreDefault.has(o)},AS=(o,n)=>{let t=D(n);t.atomsThatAreDefault=new Set(t.atomsThatAreDefault).add(o)},_A=(o,n)=>{let t=D(n);t.atomsThatAreDefault=new Set(D(n).atomsThatAreDefault),t.atomsThatAreDefault.delete(o)};function tn(o,n,t){o.logger.info("\uD83D\uDD28","atom",n.key,`creating in store "${o.config.name}"`);let T=D(o),S=T.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."),Po(S);let f=new s,y={...n,type:"atom",install:(F)=>{return F.logger.info("\uD83D\uDEE0\uFE0F","atom",n.key,`installing in store "${F.config.name}"`),tn(F,n,t)},subject:f};if(t)y.family=t;let A=n.default;if(n.default instanceof Function)A=n.default();T.atoms.set(y.key,y),AS(n.key,o),Rn(n.key,A,f,T);let M=Po(y);if(n.effects){let F=0,k=[];for(let W of n.effects){let O=W({setSelf:(E)=>{Qo(o,M,E)},onSet:(E)=>eo(M,E,`effect[${F}]`,o)});if(O)k.push(O);++F}y.cleanup=()=>{for(let W of k)W()}}return M}function TA(o,n){if("mutable"in n){let S=RT(o,n,void 0);return o.on.atomCreation.next(S),S}let T=tn(o,n,void 0);return o.on.atomCreation.next(T),T}function Of(o,n){let t=D(n),{key:T}=o,S=d(o,t);if(!S.family)n.logger.error("\u274C","atom",T,"Standalone atoms cannot be disposed.");else{S.cleanup?.();let f=n.valueMap.get(S.key);d({key:S.family.key,type:"atom_family"},n).subject.next({type:"state_disposal",token:o,value:f});let A=t.molecules.get(S.family.subKey);if(A)A.tokens.delete(T);if(t.atoms.delete(T),t.valueMap.delete(T),t.selectorAtoms.delete(T),t.atomsThatAreDefault.delete(T),n.timelineTopics.delete(T),o.type==="mutable_atom"){let M=qn(o);Of(M,n),n.trackers.delete(T)}if(n.logger.info("\uD83D\uDD25","atom",T,"deleted"),Fo(t)&&t.transactionMeta.phase==="building")t.transactionMeta.update.updates.push({type:"state_disposal",token:o});else n.on.atomDisposal.next(o)}}var Yf=(o)=>{let n=tn(o,{key:"\uD83D\uDD0D Atom Token Index (Internal)",default:()=>{let t=new Map;for(let[T,S]of o.atoms)if(!T.includes("\uD83D\uDD0D")){let f=Po(S);if(S.family){let y=t.get(S.family.key);if(!y||!("familyMembers"in y))y={key:S.family.key,familyMembers:new Map},t.set(S.family.key,y);y.familyMembers.set(S.family.subKey,f)}else t.set(T,f)}return t},effects:[({setSelf:t})=>{o.on.atomCreation.subscribe("introspection",(T)=>{if(T.key.includes("\uD83D\uDD0D"))return;t((S)=>{if(T.family){let{key:f,subKey:y}=T.family,A=S.get(f);if(A===void 0||!("familyMembers"in A))A={key:f,familyMembers:new Map},S.set(f,A);A.familyMembers.set(y,T)}else S.set(T.key,T);return S})}),o.on.atomDisposal.subscribe("introspection",(T)=>{t((S)=>{if(T.family){let{key:f,subKey:y}=T.family,A=S.get(f);if(A&&"familyMembers"in A){if(A.familyMembers.delete(y),A.familyMembers.size===0)S.delete(f)}}else S.delete(T.key);return S})})}]},void 0);return zn(o,{key:"\uD83D\uDD0D Atom Token Index",get:({get:t})=>t(n)})};var Gf=(o)=>{let n=tn(o,{key:"\uD83D\uDD0D Selector Token Index (Internal)",default:()=>{let t=new Map;for(let T of[o.readonlySelectors,o.selectors])for(let[S,f]of T)if(!S.includes("\uD83D\uDD0D")){let y=Po(f);if(f.family){let A=t.get(f.family.key);if(!A||!("familyMembers"in A))A={key:f.family.key,familyMembers:new Map},t.set(f.family.key,A);A.familyMembers.set(f.family.subKey,y)}else t.set(S,y)}return t},effects:[({setSelf:t})=>{o.on.selectorCreation.subscribe("introspection",(T)=>{if(T.key.includes("\uD83D\uDD0D"))return;t((S)=>{if(T.family){let{key:f,subKey:y}=T.family,A=S.get(f);if(A===void 0||!("familyMembers"in A))A={key:f,familyMembers:new Map},S.set(f,A);A.familyMembers.set(y,T)}else S.set(T.key,T);return S})}),o.on.selectorDisposal.subscribe("introspection",(T)=>{t((S)=>{if(T.family){let{key:f,subKey:y}=T.family,A=S.get(f);if(A&&"familyMembers"in A){if(A.familyMembers.delete(y),A.familyMembers.size===0)S.delete(f)}}else S.delete(T.key);return S})})}]},void 0);return zn(o,{key:"\uD83D\uDD0D Selector Token Index",get:({get:t})=>t(n)})};class MS{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(T){try{if(o instanceof t)return{type:n,data:o}}catch(S){}}return null}}var zf=new MS({number:(o)=>typeof o==="number",string:(o)=>typeof o==="string",boolean:(o)=>typeof o==="boolean",null:(o)=>o===null});function Hf(o){if(!o)return!1;return Object.getPrototypeOf(o)===Object.prototype}var mf=new MS({object:Hf,array:(o)=>Array.isArray(o)}),cJ=new MS({...zf.supported,...mf.supported}),Ut=(o)=>{if(o===void 0)return"undefined";let n=cJ.refine(o);if(n)return n.type;return Object.getPrototypeOf(o).constructor.name};class jA{o;auditorCreatedAt=performance.now();statesCreatedAt=new Map;atomIndex;selectorIndex;disposed=!1;unsubscribeFromAtomCreation;unsubscribeFromAtomDisposal;unsubscribeFromSelectorCreation;unsubscribeFromSelectorDisposal;constructor(o=yo.STORE){this.store=o;this.atomIndex=Yf(this.store),this.selectorIndex=Gf(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=jA.DEFAULT_LIST_RESOURCES_PARAM){if(this.disposed)throw new Error("This Auditor has been disposed");let n=Tf(this.atomIndex),t=Tf(this.selectorIndex),T=[...n.values()].filter((A)=>("familyMembers"in A)),S=[...t.values()].filter((A)=>("familyMembers"in A)),f=performance.now(),y=[];if(o.atomFamilies)for(let A of T){let M=A.familyMembers.values();for(let F of M){let W=this.statesCreatedAt.get(F.key)??this.auditorCreatedAt,O=f-W;y.push([F,O])}}if(o.selectorFamilies)for(let A of S){let M=A.familyMembers.values();for(let F of M){let W=this.statesCreatedAt.get(F.key)??this.auditorCreatedAt,O=f-W;y.push([F,O])}}return y}[Symbol.dispose](){this.unsubscribeFromAtomCreation(),this.unsubscribeFromAtomDisposal(),this.unsubscribeFromSelectorCreation(),this.unsubscribeFromSelectorDisposal(),this.disposed=!0}}var Qf=(o,n)=>{let t=(T,S)=>{let y=((M,F)=>{let k=n(M,F);if(k)return k;return null})(T,S);if(y?.jobComplete??y?.pathComplete)return y;let A=Array.isArray(S)?S.map((M,F)=>[F,M]):Hf(S)?Object.entries(S):[];for(let[M,F]of A){let k=t([...T,M],F);if(k?.jobComplete)return k}return{}};t([],o)};function xJ(o,n){return{summary:`${o<n?"+":"-"}${Math.abs(o-n)} (${o} \u2192 ${n})`}}function iJ(o,n){return{summary:`${o.length<n.length?"+":"-"}${Math.abs(o.length-n.length)} ("${o}" \u2192 "${n}")`}}function vJ(o,n){return{summary:`${o} \u2192 ${n}`}}function bA(o,n,t){let T="",S=[],f=[],y=[];return Qf(o,(A,M)=>{let F;for(F of A){let k=n[F];if(k===void 0)f.push([F,JSON.stringify(M)]);else{let W=t(M,k);if(W.summary!=="No Change")y.push([F,W])}}}),Qf(n,(A,M)=>{let F;for(F of A)if(o[F]===void 0)S.push([F,JSON.stringify(M)])}),T=`\uFF5E${y.length} \uFF0B${S.length} \uFF0D${f.length}`,{summary:T,added:S,removed:f,changed:y}}function pJ(o,n,t){return bA(o,n,t)}class NA{leafRefinery;treeRefinery;leafDiffers;treeDiffers;constructor(o,n,t){this.leafRefinery=o,this.treeRefinery=n,this.leafDiffers={},this.treeDiffers={};for(let T of Object.keys(o.supported)){let S=t[T];this.leafDiffers[T]=S}for(let T of Object.keys(n.supported)){let S=t[T];this.treeDiffers[T]=S}}diff(o,n){if(o===n)return{summary:"No Change"};let t=this.leafRefinery.refine(o)??this.treeRefinery.refine(o),T=this.leafRefinery.refine(n)??this.treeRefinery.refine(n);if(t!==null&&T!==null){if(t.type===T.type){if(t.type in this.leafDiffers)return this.leafDiffers[t.type](t.data,T.data);if(t.type in this.treeDiffers)return this.treeDiffers[t.type](t.data,T.data,(A,M)=>this.diff(A,M))}}let S=Ut(o),f=Ut(n);if(S===f)return{summary:`${S} \u2192 ${f}`};return{summary:`Type change: ${S} \u2192 ${f}`}}}var $8=new NA(zf,mf,{number:xJ,string:iJ,boolean:vJ,null:()=>({summary:"No Change"}),object:bA,array:pJ});class hA 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 FS{o;type="continuity";globals=[];actions=[];perspectives=[];constructor(o){this.key=o}static existing=new hA;static create(o,n){let t=new FS(o),{type:T,globals:S,actions:f,perspectives:y}=n(t),A={type:T,key:o,globals:S,actions:f,perspectives:y};return FS.existing.set(o,A),A}add(...o){switch(o[0].type){case"atom":case"mutable_atom":this.globals.push(...o);break;case"transaction":this.actions.push(...o);break;case"atom_family":{let[t,T]=o;this.perspectives.push({type:"realtime_perspective",resourceAtoms:t,viewAtoms:T})}break}return this}}function E8(o){let{key:n,config:t}=o,T=FS.create(n,t),{actions:S}=T;for(let f of S)mA(n,f.key,yo.STORE);return GA(n,-1,yo.STORE),T}var m8=Qt({key:"usersInRoomIndex",mutable:!0,default:()=>new No,toJson:(o)=>o.toJSON(),fromJson:(o)=>No.fromJSON(o)}),Df=Qt({key:"roomIndex",default:()=>new No,mutable:!0,toJson:(o)=>o.toJSON(),fromJson:(o)=>No.fromJSON(o)}),qJ={enteredAtEpoch:0},WT=uT({key:"usersInRooms",between:["room","user"],cardinality:"1:n",isAType:(o)=>typeof o==="string",isBType:(o)=>typeof o==="string"},qJ),Q8=PT({key:"usersInMyRoomView",get:(o)=>({find:n})=>{let t=XA(WT);return[n(t,o)]}});import{spawn as ZJ}from"child_process";class Vt{o;listeners;globalListeners;handleEvent(o,...n){for(let T of this.globalListeners)T(o,...n);let t=this.listeners.get(o);if(t)for(let T of t)T(...n)}id="no_id_retrieved";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 Uf extends Vt{o;n;t;incompleteData="";unprocessedEvents=[];incompleteLog="";unprocessedLogs=[];id="#####";handleLog(o){if(Array.isArray(o)){let[n,...t]=o;switch(n){case"i":this.logger.info(this.id,this.key,...t);break;case"w":this.logger.warn(this.id,this.key,...t);break;case"e":this.logger.error(this.id,this.key,...t);break}}}constructor(o,n,t=console){super((T,...S)=>{let f=JSON.stringify([T,...S])+"\x03",y=(A)=>{if(A.code==="EPIPE")console.error("EPIPE error during write",this.process.stdin);this.process.stdin.removeListener("error",y)};return this.process.stdin.once("error",y),this.process.stdin.write(f),this});this.process=o;this.key=n;this.logger=t;if(this.process=o,this.process.stdout.on("data",(T)=>{let S=T.toString();if(S==="\u2728")return;this.unprocessedEvents.push(...S.split("\x03"));let f=this.unprocessedEvents.shift();this.incompleteData+=f??"";try{if(this.incompleteData.startsWith("error"))console.log("\u2757",this.incompleteData);let y=bo(this.incompleteData);this.handleEvent(...y);while(this.unprocessedEvents.length>0){let A=this.unprocessedEvents.shift();if(A){if(this.unprocessedEvents.length===0)this.incompleteData=A;y=bo(A),this.handleEvent(...y)}}this.incompleteData=""}catch(y){console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.warn(this.incompleteData),console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.error(y)}}),this.process.stderr.on("data",(T)=>{let S=T.toString();this.unprocessedLogs.push(...S.split("\x03"));let f=this.unprocessedLogs.shift();this.incompleteLog+=f??"";try{let y=bo(this.incompleteLog);this.handleLog(y);while(this.unprocessedLogs.length>0)if(this.incompleteLog=this.unprocessedLogs.shift()??"",this.incompleteLog)y=bo(this.incompleteLog),this.handleLog(y)}catch(y){console.error("\u274C\u274C\u274C"),console.error(this.incompleteLog),console.error(y),console.error("\u274C\u274C\u274C\uFE0F")}}),o.pid)this.id=o.pid.toString()}}class cA extends Vt{in;out;id="no_id_retrieved";disposalFunctions=[];constructor(o){super((...n)=>{return this.out.next(n),this});this.id=o,this.in=new s,this.out=new s,this.in.subscribe("socket",(n)=>{this.handleEvent(...n)})}dispose(){for(let o of this.disposalFunctions)o()}}class Vf extends Vt{incompleteData="";unprocessedEvents=[];relays;relayServices;process;id="#####";log(...o){this.process.stderr.write(l(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 T=bo(this.incompleteData);this.logger.info("\uD83C\uDFB0","received",T),this.handleEvent(...T);while(this.unprocessedEvents.length>0){let S=this.unprocessedEvents.shift();if(S){if(this.unprocessedEvents.length===0)this.incompleteData=S;let f=bo(S);this.handleEvent(...f)}}this.incompleteData=""}catch(T){if(T instanceof Error)this.logger.error("\u2757",T.message,T.cause,T.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 cA(`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 T=t(n);if(T)n.disposalFunctions.push(T)}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("\u2728")}relay(o){this.logger.info("\uD83D\uDD17","running relay method"),this.relayServices.push(o)}}var rf=Ft({key:"roomArguments",default:["echo",["Hello World!"]]}),xA=PT({key:"room",get:(o)=>async({get:n,find:t})=>{let T=t(rf,o),S=n(T),[f,y]=S,A=await new Promise((M)=>{let F=ZJ(f,y,{env:process.env}),k=(W)=>{if(W.toString()==="\u2728")F.stdout.off("data",k),M(F)};F.stdout.on("data",k)});return new Uf(A,o)}});var o5=FT({key:"createRoom",do:({get:o,set:n,find:t},T,S,f)=>{let y=f?[S,f]:[S],A=t(rf,T);n(A,y),n(Df,(k)=>k.add(T));let M=t(xA,T);return o(M)}}),n5=FT({key:"joinRoom",do:(o,n,t,T)=>{let S={enteredAtEpoch:T};return sT(WT,(f)=>{f.set({room:n,user:t},S)},o.env().store),S}}),t5=FT({key:"leaveRoom",do:(o,n,t)=>{sT(WT,(T)=>{T.delete({room:n,user:t})},o.env().store)}}),T5=FT({key:"destroyRoom",do:(o,n)=>{sT(WT,(t)=>{t.delete({room:n})},o.env().store),o.set(Df,(t)=>(t.delete(n),t))}});function Bf(o,n){return n.map((t)=>{switch(t.type){case"transaction_update":{let T=Bf(o,t.updates);return{...t,updates:T}}default:return t}}).filter((t)=>{switch(t.type){case"atom_update":case"selector_update":return o.includes(t.key);case"state_creation":return o.includes(t.token.key);case"molecule_creation":return!0;case"transaction_update":return!0}})}var y5=Ft({key:"redactor",default:{occlude:(o)=>o}}),rt=Ft({key:"unacknowledgedUpdates",default:()=>[]});var iA=Ft({key:"sockets",default:null}),$5=Qt({key:"socketsIndex",mutable:!0,default:()=>new No,toJson:(o)=>o.toJSON(),fromJson:(o)=>No.fromJSON(o)}),J5=Qt({key:"usersIndex",mutable:!0,default:()=>new No,toJson:(o)=>o.toJSON(),fromJson:(o)=>No.fromJSON(o)}),Cf=uT({key:"usersOfSockets",between:["user","socket"],cardinality:"1:1",isAType:(o)=>o.startsWith("user::"),isBType:(o)=>o.startsWith("socket::")});function vA(o,n,t,T){let S=n.key;return function f(){let y=[];for(let M of n.globals){let F=M.type==="mutable_atom"?ro(o,M):M,k=Mo(o,F);y.push(F,k)}for(let M of n.perspectives){let{viewAtoms:F,resourceAtoms:k}=M,W=ko(o,F,t),O=Mo(o,W);o.logger.info("\uD83D\uDC41","atom",k.key,`${t} can see`,{viewAtoms:F,resourceAtoms:k,userView:O});for(let E of O){let Q=E.type==="mutable_atom"?ro(o,E):E,z=Mo(o,Q);y.push(Q,z)}}let A=Bo(o)?o.transactionMeta.epoch.get(S)??null:null;T?.emit(`continuity-init:${S}`,A,y)}}function pA(o,n,t){let T=n.key;return function S(f){o.logger.info("\uD83D\uDECE\uFE0F","continuity",T,"received",f);let{key:y,id:A}=f,M=`tx-run:${y}:${A}`,F=`${M}:start`,k=`${M}:end`;performance.mark(F);try{dn({type:"transaction",key:y},A,o)(...f.params)}catch(O){if(O instanceof Error)o.logger.error("\u274C","continuity",T,`failed to run transaction ${y} from ${t} with update ${A}`,O.message)}performance.mark(k);let W=performance.measure(M,F,k);o?.logger.info("\uD83D\uDE80","transaction",y,A,t,W.duration)}}function qA(o,n,t,T){let S=n.key;return function f(y){if(o.logger.info("\uD83D\uDC4D","continuity",S,`${t} acknowledged epoch ${y}`),T[0]?.epoch===y)Qo(o,rt,t,(M)=>{return M.shift(),o.logger.info("\uD83D\uDC4D","continuity",S,`${t} unacknowledged update queue now has`,M.length,"items"),M})}}function ZA(o,n,t,T){let S=n.key,f=[];for(let y of n.actions){let A=Kf(y,(M)=>{try{let F=n.globals.map((O)=>{if(O.type==="atom")return O.key;return qn(O).key}).concat(n.perspectives.flatMap((O)=>{let{viewAtoms:E}=O,Q=ko(o,E,t);return Mo(o,Q).map((G)=>{return G.type==="mutable_atom"?"*"+G.key:G.key})})),k=Bf(F,M.updates),W={...M,updates:k};Qo(o,rt,t,(O)=>{if(W)O.push(W),O.sort((E,Q)=>E.epoch-Q.epoch),o.logger.info("\uD83D\uDC4D","continuity",S,`${t} unacknowledged update queue now has`,O.length,"items");return O}),T?.emit(`tx-new:${S}`,W)}catch(F){if(F instanceof Error)o.logger.error("\u274C","continuity",S,`${t} failed to send update from transaction ${y.key} to ${t}`,F.message)}},`sync-continuity:${S}:${t}`,o);f.push(A)}return f}function PA(o,n,t,T){let S=n.key,f=[];for(let y of n.perspectives){let{viewAtoms:A}=y,M=ko(o,A,t),F=eo(M,({oldValue:k,newValue:W})=>{let O=k.map((G)=>G.key),E=W.map((G)=>G.key),Q=k.filter((G)=>!E.includes(G.key)),z=W.filter((G)=>!O.includes(G.key)).flatMap((G)=>{let V=G.type==="mutable_atom"?ro(o,G):G,x=Mo(o,V);return[V,x]});if(o.logger.info("\uD83D\uDC41","atom",y.resourceAtoms.key,`${t} has a new perspective`,{oldKeys:O,newKeys:E,revealed:z,concealed:Q}),z.length>0)T?.emit(`reveal:${S}`,z);if(Q.length>0)T?.emit(`conceal:${S}`,Q)},`sync-continuity:${S}:${t}:perspective:${y.resourceAtoms.key}`,o);f.push(F)}return f}function v5({socket:o,store:n=yo.STORE}){return function t(T){let S=o,f=T.key,y=aT(Cf,`socket::${S.id}`,n).userKeyOfSocket,A=Mo(n,y);if(!A)return n.logger.error("\u274C","continuity",f,`Tried to create a synchronizer for a socket (${S.id}) that is not connected to a user.`),()=>{};let M=aT(Cf,A,n).socketKeyOfUser,F=eo(M,({newValue:V})=>{if(n.logger.info("\uD83D\uDC4B","continuity",f,`seeing ${A} on new socket ${V}`),V===null){n.logger.warn("\u274C","continuity",f,`User (${A}) is not connected to a socket, waiting for them to reappear.`);return}let x=ko(n,iA,V);S=Mo(n,x);for(let P of k)S?.emit(`tx-new:${f}`,P)},`sync-continuity:${f}:${A}`,n),k=Mo(n,rt,A),W=[],O=PA(n,T,A,S),E=ZA(n,T,A,S);W.push(...O,...E);let Q=vA(n,T,A,o);S.off(`get:${f}`,Q),S.on(`get:${f}`,Q);let z=pA(n,T,A);S.off(`tx-run:${f}`,z),S.on(`tx-run:${f}`,z);let G=qA(n,T,A,k);return S?.on(`ack:${f}`,G),()=>{for(let V of W)V();S?.off(`ack:${f}`,G),S?.off(`get:${f}`,Q),S?.off(`tx-run:${f}`,z)}}}var{file:B$,serve:a0}=globalThis.Bun;var J=Symbol.for("drizzle:entityKind"),WE=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,J))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(J in t&&t[J]===n[J])return!0;t=Object.getPrototypeOf(t)}return!1}class Xo{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[J]="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 Lf{static[J]="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 Qn=Symbol.for("drizzle:Name");class If{static[J]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(o,n){if(this.reference=()=>{let{name:t,columns:T,foreignColumns:S}=o();return{name:t,columns:T,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 eA(o,this)}}class eA{constructor(o,n){this.table=o,this.reference=n.reference,this.onUpdate=n._onUpdate,this.onDelete=n._onDelete}static[J]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:o,columns:n,foreignColumns:t}=this.reference(),T=n.map((y)=>y.name),S=t.map((y)=>y.name),f=[this.table[Qn],...T,t[0].table[Qn],...S];return o??`${f.join("_")}_fk`}}function kS(o,...n){return o(...n)}function lA(o,n){return`${o[Qn]}_${n.join("_")}_unique`}function gA(o,n,t){for(let T=n;T<o.length;T++){let S=o[T];if(S==="\\"){T++;continue}if(S==='"')return[o.slice(n,T).replace(/\\/g,""),T+1];if(t)continue;if(S===","||S==="}")return[o.slice(n,T).replace(/\\/g,""),T]}return[o.slice(n).replace(/\\/g,""),o.length]}function dA(o,n=0){let t=[],T=n,S=!1;while(T<o.length){let f=o[T];if(f===","){if(S||T===n)t.push("");S=!0,T++;continue}if(S=!1,f==="\\"){T+=2;continue}if(f==='"'){let[M,F]=gA(o,T+1,!0);t.push(M),T=F;continue}if(f==="}")return[t,T+1];if(f==="{"){let[M,F]=dA(o,T+1);t.push(M),T=F;continue}let[y,A]=gA(o,T,!1);t.push(y),T=A}return[t,T]}function uA(o){let[n]=dA(o,1);return n}function jf(o){return`{${o.map((n)=>{if(Array.isArray(n))return jf(n);if(typeof n==="string")return`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`;return`${n}`}).join(",")}}`}class N extends Lf{foreignKeyConfigs=[];static[J]="PgColumnBuilder";array(o){return new sA(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:T})=>{return kS((S,f)=>{let y=new If(()=>{let A=S();return{columns:[o],foreignColumns:[A]}});if(f.onUpdate)y.onUpdate(f.onUpdate);if(f.onDelete)y.onDelete(f.onDelete);return y.build(n)},t,T)})}buildExtraConfigColumn(o){return new aA(o,this.config)}}class r extends Xo{constructor(o,n){if(!n.uniqueName)n.uniqueName=lA(o,[n.name]);super(o,n);this.table=o}static[J]="PgColumn"}class aA extends r{static[J]="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 OT{static[J]="IndexedColumn";constructor(o,n,t,T){this.name=o,this.keyAsName=n,this.type=t,this.indexConfig=T}name;keyAsName;type;indexConfig}class sA extends N{static[J]="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 bf(o,this.config,n)}}class bf extends r{constructor(o,n,t,T){super(o,n);this.baseColumn=t,this.range=T,this.size=n.size}size;static[J]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(o){if(typeof o==="string")o=uA(o);return o.map((n)=>this.baseColumn.mapFromDriverValue(n))}mapToDriverValue(o,n=!1){let t=o.map((T)=>T===null?null:X(this.baseColumn,bf)?this.baseColumn.mapToDriverValue(T,!0):this.baseColumn.mapToDriverValue(T));if(n)return t;return jf(t)}}var Nf=Symbol.for("drizzle:isPgEnum");function oM(o){return!!o&&typeof o==="function"&&Nf in o&&o[Nf]===!0}class nM extends N{static[J]="PgEnumColumnBuilder";constructor(o,n){super(o,"string","PgEnumColumn");this.config.enum=n}build(o){return new tM(o,this.config)}}class tM extends r{static[J]="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 $S(o,n){return PJ(o,n,void 0)}function PJ(o,n,t){let T=Object.assign((S)=>new nM(S??"",T),{enumName:o,enumValues:n,schema:t,[Nf]:!0});return T}class xo{static[J]="Subquery";constructor(o,n,t,T=!1){this._={brand:"Subquery",sql:o,selectedFields:n,alias:t,isWith:T}}}class _T extends xo{static[J]="WithSubquery"}var TM="0.36.1";var hf,cf,Oo={startActiveSpan(o,n){if(!hf)return n();if(!cf)cf=hf.trace.getTracer("drizzle-orm",TM);return kS((t,T)=>T.startActiveSpan(o,(S)=>{try{return n(S)}catch(f){throw S.setStatus({code:t.SpanStatusCode.ERROR,message:f instanceof Error?f.message:"Unknown error"}),f}finally{S.end()}}),hf,cf)}};var Do=Symbol.for("drizzle:ViewBaseConfig");var JS=Symbol.for("drizzle:Schema"),SM=Symbol.for("drizzle:Columns"),fM=Symbol.for("drizzle:ExtraConfigColumns"),xf=Symbol.for("drizzle:OriginalName"),vf=Symbol.for("drizzle:BaseName"),yM=Symbol.for("drizzle:IsAlias"),AM=Symbol.for("drizzle:ExtraConfigBuilder"),eJ=Symbol.for("drizzle:IsDrizzleTable");class L{static[J]="Table";static Symbol={Name:Qn,Schema:JS,OriginalName:xf,Columns:SM,ExtraConfigColumns:fM,BaseName:vf,IsAlias:yM,ExtraConfigBuilder:AM};[Qn];[xf];[JS];[SM];[fM];[vf];[yM]=!1;[eJ]=!0;[AM]=void 0;constructor(o,n,t){this[Qn]=this[xf]=o,this[JS]=n,this[vf]=t}}function On(o){return o[Qn]}function kt(o){return`${o[JS]??"public"}.${o[Qn]}`}function pf(o){return o!==null&&o!==void 0&&typeof o.getSQL==="function"}function lJ(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 ho{static[J]="StringChunk";value;constructor(o){this.value=Array.isArray(o)?o:[o]}getSQL(){return new h([this])}}class h{constructor(o){this.queryChunks=o}static[J]="SQL";decoder=FM;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:T,escapeName:S,escapeParam:f,prepareTyping:y,inlineParams:A,paramStartIndex:M}=t;return lJ(o.map((F)=>{if(X(F,ho))return{sql:F.value.join(""),params:[]};if(X(F,RS))return{sql:S(F.value),params:[]};if(F===void 0)return{sql:"",params:[]};if(Array.isArray(F)){let k=[new ho("(")];for(let[W,O]of F.entries())if(k.push(O),W<F.length-1)k.push(new ho(", "));return k.push(new ho(")")),this.buildQueryFromSourceParams(k,t)}if(X(F,h))return this.buildQueryFromSourceParams(F.queryChunks,{...t,inlineParams:A||F.shouldInlineParams});if(X(F,L)){let k=F[L.Symbol.Schema],W=F[L.Symbol.Name];return{sql:k===void 0?S(W):S(k)+"."+S(W),params:[]}}if(X(F,Xo)){let k=T.getColumnCasing(F);if(n.invokeSource==="indexes")return{sql:S(k),params:[]};return{sql:S(F.table[L.Symbol.Name])+"."+S(k),params:[]}}if(X(F,Sn)){let k=F[Do].schema,W=F[Do].name;return{sql:k===void 0?S(W):S(k)+"."+S(W),params:[]}}if(X(F,Fn)){if(X(F.value,sn))return{sql:f(M.value++,F),params:[F],typings:["none"]};let k=F.value===null?null:F.encoder.mapToDriverValue(F.value);if(X(k,h))return this.buildQueryFromSourceParams([k],t);if(A)return{sql:this.mapInlineParam(k,t),params:[]};let W=["none"];if(y)W=[y(F.encoder)];return{sql:f(M.value++,k),params:[k],typings:W}}if(X(F,sn))return{sql:f(M.value++,F),params:[F],typings:["none"]};if(X(F,h.Aliased)&&F.fieldAlias!==void 0)return{sql:S(F.fieldAlias),params:[]};if(X(F,xo)){if(F._.isWith)return{sql:S(F._.alias),params:[]};return this.buildQueryFromSourceParams([new ho("("),F._.sql,new ho(") "),new RS(F._.alias)],t)}if(oM(F)){if(F.schema)return{sql:S(F.schema)+"."+S(F.enumName),params:[]};return{sql:S(F.enumName),params:[]}}if(pf(F)){if(F.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([F.getSQL()],t);return this.buildQueryFromSourceParams([new ho("("),F.getSQL(),new ho(")")],t)}if(A)return{sql:this.mapInlineParam(F,t),params:[]};return{sql:f(M.value++,F),params:[F],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 h.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 RS{constructor(o){this.value=o}static[J]="Name";brand;getSQL(){return new h([this])}}function MM(o){return typeof o==="object"&&o!==null&&"mapToDriverValue"in o&&typeof o.mapToDriverValue==="function"}var FM={mapFromDriverValue:(o)=>o},kM={mapToDriverValue:(o)=>o},tY={...FM,...kM};class Fn{constructor(o,n=kM){this.value=o,this.encoder=n}static[J]="Param";brand;getSQL(){return new h([this])}}function R(o,...n){let t=[];if(n.length>0||o.length>0&&o[0]!=="")t.push(new ho(o[0]));for(let[T,S]of n.entries())t.push(S,new ho(o[T+1]));return new h(t)}((o)=>{function n(){return new h([])}o.empty=n;function t(M){return new h(M)}o.fromList=t;function T(M){return new h([new ho(M)])}o.raw=T;function S(M,F){let k=[];for(let[W,O]of M.entries()){if(W>0&&F!==void 0)k.push(F);k.push(O)}return new h(k)}o.join=S;function f(M){return new RS(M)}o.identifier=f;function y(M){return new sn(M)}o.placeholder=y;function A(M,F){return new Fn(M,F)}o.param=A})(R||(R={}));((o)=>{class n{constructor(t,T){this.sql=t,this.fieldAlias=T}static[J]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new n(this.sql,this.fieldAlias)}}o.Aliased=n})(h||(h={}));class sn{constructor(o){this.name=o}static[J]="Placeholder";getSQL(){return new h([this])}}function qf(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,Fn)&&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})}class Sn{static[J]="View";[Do];constructor({name:o,schema:n,selectedFields:t,query:T}){this[Do]={name:o,originalName:o,schema:n,selectedFields:t,query:T,isExisting:!T,isAlias:!1}}getSQL(){return new h([this])}}Xo.prototype.getSQL=function(){return new h([this])};L.prototype.getSQL=function(){return new h([this])};xo.prototype.getSQL=function(){return new h([this])};class Bt{constructor(o){this.table=o}static[J]="ColumnAliasProxyHandler";get(o,n){if(n==="table")return this.table;return o[n]}}class wT{constructor(o,n){this.alias=o,this.replaceOriginalName=n}static[J]="TableAliasProxyHandler";get(o,n){if(n===L.Symbol.IsAlias)return!0;if(n===L.Symbol.Name)return this.alias;if(this.replaceOriginalName&&n===L.Symbol.OriginalName)return this.alias;if(n===Do)return{...o[Do],name:this.alias,isAlias:!0};if(n===L.Symbol.Columns){let T=o[L.Symbol.Columns];if(!T)return T;let S={};return Object.keys(T).map((f)=>{S[f]=new Proxy(T[f],new Bt(new Proxy(o,this)))}),S}let t=o[n];if(X(t,Xo))return new Proxy(t,new Bt(new Proxy(o,this)));return t}}function WS(o,n){return new Proxy(o,new wT(n,!1))}function bn(o,n){return new Proxy(o,new Bt(new Proxy(o.table,new wT(n,!1))))}function Zf(o,n){return new h.Aliased(KT(o.sql,n),o.fieldAlias)}function KT(o,n){return R.join(o.queryChunks.map((t)=>{if(X(t,Xo))return bn(t,n);if(X(t,h))return KT(t,n);if(X(t,h.Aliased))return Zf(t,n);return t}))}class OS extends Error{static[J]="DrizzleError";constructor({message:o,cause:n}){super(o);this.name="DrizzleError",this.cause=n}}class Pf extends OS{static[J]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}function fn(o,n){if(MM(n)&&!pf(o)&&!X(o,Fn)&&!X(o,sn)&&!X(o,Xo)&&!X(o,L)&&!X(o,Sn))return new Fn(o,n);return o}var Ct=(o,n)=>{return R`${o} = ${fn(n,o)}`},$M=(o,n)=>{return R`${o} <> ${fn(n,o)}`};function XT(...o){let n=o.filter((t)=>t!==void 0);if(n.length===0)return;if(n.length===1)return new h(n);return new h([new ho("("),R.join(n,new ho(" and ")),new ho(")")])}function JM(...o){let n=o.filter((t)=>t!==void 0);if(n.length===0)return;if(n.length===1)return new h(n);return new h([new ho("("),R.join(n,new ho(" or ")),new ho(")")])}function RM(o){return R`not ${o}`}var WM=(o,n)=>{return R`${o} > ${fn(n,o)}`},OM=(o,n)=>{return R`${o} >= ${fn(n,o)}`},_M=(o,n)=>{return R`${o} < ${fn(n,o)}`},wM=(o,n)=>{return R`${o} <= ${fn(n,o)}`};function KM(o,n){if(Array.isArray(n)){if(n.length===0)return R`false`;return R`${o} in ${n.map((t)=>fn(t,o))}`}return R`${o} in ${fn(n,o)}`}function XM(o,n){if(Array.isArray(n)){if(n.length===0)return R`true`;return R`${o} not in ${n.map((t)=>fn(t,o))}`}return R`${o} not in ${fn(n,o)}`}function EM(o){return R`${o} is null`}function YM(o){return R`${o} is not null`}function GM(o){return R`exists ${o}`}function zM(o){return R`not exists ${o}`}function HM(o,n,t){return R`${o} between ${fn(n,o)} and ${fn(t,o)}`}function mM(o,n,t){return R`${o} not between ${fn(n,o)} and ${fn(t,o)}`}function QM(o,n){return R`${o} like ${n}`}function DM(o,n){return R`${o} not like ${n}`}function UM(o,n){return R`${o} ilike ${n}`}function VM(o,n){return R`${o} not ilike ${n}`}function rM(o){return R`${o} asc`}function BM(o){return R`${o} desc`}class CM{static[J]="ConsoleLogWriter";write(o){console.log(o)}}class ef{static[J]="DefaultLogger";writer;constructor(o){this.writer=o?.writer??new CM}logQuery(o,n){let t=n.map((S)=>{try{return JSON.stringify(S)}catch{return String(S)}}),T=t.length?` -- params: [${t.join(", ")}]`:"";this.writer.write(`Query: ${o}${T}`)}}class lf{static[J]="NoopLogger";logQuery(){}}class so{static[J]="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 LM(o,n,t){let T={},S=o.reduce((f,{path:y,field:A},M)=>{let F;if(X(A,Xo))F=A;else if(X(A,h))F=A.decoder;else F=A.sql.decoder;let k=f;for(let[W,O]of y.entries())if(W<y.length-1){if(!(O in k))k[O]={};k=k[O]}else{let E=n[M],Q=k[O]=E===null?null:F.mapFromDriverValue(E);if(t&&X(A,Xo)&&y.length===2){let z=y[0];if(!(z in T))T[z]=Q===null?On(A.table):!1;else if(typeof T[z]==="string"&&T[z]!==On(A.table))T[z]=!1}}return f},{});if(t&&Object.keys(T).length>0){for(let[f,y]of Object.entries(T))if(typeof y==="string"&&!t[y])S[f]=null}return S}function _n(o,n){return Object.entries(o).reduce((t,[T,S])=>{if(typeof T!=="string")return t;let f=n?[...n,T]:[T];if(X(S,Xo)||X(S,h)||X(S,h.Aliased))t.push({path:f,field:S});else if(X(S,L))t.push(..._n(S[L.Symbol.Columns],f));else t.push(..._n(S,f));return t},[])}function gf(o,n){let t=Object.keys(o),T=Object.keys(n);if(t.length!==T.length)return!1;for(let[S,f]of t.entries())if(f!==T[S])return!1;return!0}function _S(o,n){let t=Object.entries(n).filter(([,T])=>T!==void 0).map(([T,S])=>{if(X(S,h))return[T,S];else return[T,new Fn(S,o[L.Symbol.Columns][T])]});if(t.length===0)throw new Error("No values to set");return Object.fromEntries(t)}function IM(o,n){for(let t of n)for(let T of Object.getOwnPropertyNames(t.prototype)){if(T==="constructor")continue;Object.defineProperty(o.prototype,T,Object.getOwnPropertyDescriptor(t.prototype,T)||Object.create(null))}}function jM(o){return o[L.Symbol.Columns]}function df(o){return X(o,xo)?o._.alias:X(o,Sn)?o[Do].name:X(o,h)?void 0:o[L.Symbol.IsAlias]?o[L.Symbol.Name]:o[L.Symbol.BaseName]}function Ao(o,n){return{name:typeof o==="string"&&o.length>0?o:"",config:typeof o==="object"?o:n}}function bM(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 ot extends N{static[J]="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 NM extends ot{static[J]="PgBigInt53Builder";constructor(o){super(o,"number","PgBigInt53")}build(o){return new hM(o,this.config)}}class hM extends r{static[J]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(o){if(typeof o==="number")return o;return Number(o)}}class cM extends ot{static[J]="PgBigInt64Builder";constructor(o){super(o,"bigint","PgBigInt64")}build(o){return new xM(o,this.config)}}class xM extends r{static[J]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(o){return BigInt(o)}}function iM(o,n){let{name:t,config:T}=Ao(o,n);if(T.mode==="number")return new NM(t);return new cM(t)}class vM extends N{static[J]="PgBigSerial53Builder";constructor(o){super(o,"number","PgBigSerial53");this.config.hasDefault=!0,this.config.notNull=!0}build(o){return new pM(o,this.config)}}class pM extends r{static[J]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(o){if(typeof o==="number")return o;return Number(o)}}class qM extends N{static[J]="PgBigSerial64Builder";constructor(o){super(o,"bigint","PgBigSerial64");this.config.hasDefault=!0}build(o){return new ZM(o,this.config)}}class ZM extends r{static[J]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(o){return BigInt(o)}}function PM(o,n){let{name:t,config:T}=Ao(o,n);if(T.mode==="number")return new vM(t);return new qM(t)}class eM extends N{static[J]="PgBooleanBuilder";constructor(o){super(o,"boolean","PgBoolean")}build(o){return new lM(o,this.config)}}class lM extends r{static[J]="PgBoolean";getSQLType(){return"boolean"}}function ET(o){return new eM(o??"")}class gM extends N{static[J]="PgCharBuilder";constructor(o,n){super(o,"string","PgChar");this.config.length=n.length,this.config.enumValues=n.enum}build(o){return new dM(o,this.config)}}class dM extends r{static[J]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}}function uM(o,n={}){let{name:t,config:T}=Ao(o,n);return new gM(t,T)}class aM extends N{static[J]="PgCidrBuilder";constructor(o){super(o,"string","PgCidr")}build(o){return new sM(o,this.config)}}class sM extends r{static[J]="PgCidr";getSQLType(){return"cidr"}}function oF(o){return new aM(o??"")}class nF extends N{static[J]="PgCustomColumnBuilder";constructor(o,n,t){super(o,"custom","PgCustomColumn");this.config.fieldConfig=n,this.config.customTypeParams=t}build(o){return new tF(o,this.config)}}class tF extends r{static[J]="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 TF(o){return(n,t)=>{let{name:T,config:S}=Ao(n,t);return new nF(T,S,o)}}class Zn extends N{static[J]="PgDateColumnBaseBuilder";defaultNow(){return this.default(R`now()`)}}class SF extends Zn{static[J]="PgDateBuilder";constructor(o){super(o,"date","PgDate")}build(o){return new wS(o,this.config)}}class wS extends r{static[J]="PgDate";getSQLType(){return"date"}mapFromDriverValue(o){return new Date(o)}mapToDriverValue(o){return o.toISOString()}}class fF extends Zn{static[J]="PgDateStringBuilder";constructor(o){super(o,"string","PgDateString")}build(o){return new KS(o,this.config)}}class KS extends r{static[J]="PgDateString";getSQLType(){return"date"}}function yF(o,n){let{name:t,config:T}=Ao(o,n);if(T?.mode==="date")return new SF(t);return new fF(t)}class AF extends N{static[J]="PgDoublePrecisionBuilder";constructor(o){super(o,"number","PgDoublePrecision")}build(o){return new MF(o,this.config)}}class MF extends r{static[J]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(o){if(typeof o==="string")return Number.parseFloat(o);return o}}function FF(o){return new AF(o??"")}class kF extends N{static[J]="PgInetBuilder";constructor(o){super(o,"string","PgInet")}build(o){return new $F(o,this.config)}}class $F extends r{static[J]="PgInet";getSQLType(){return"inet"}}function JF(o){return new kF(o??"")}class RF extends ot{static[J]="PgIntegerBuilder";constructor(o){super(o,"number","PgInteger")}build(o){return new WF(o,this.config)}}class WF extends r{static[J]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(o){if(typeof o==="string")return Number.parseInt(o);return o}}function XS(o){return new RF(o??"")}class OF extends N{static[J]="PgIntervalBuilder";constructor(o,n){super(o,"string","PgInterval");this.config.intervalConfig=n}build(o){return new _F(o,this.config)}}class _F extends r{static[J]="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 wF(o,n={}){let{name:t,config:T}=Ao(o,n);return new OF(t,T)}class KF extends N{static[J]="PgJsonBuilder";constructor(o){super(o,"json","PgJson")}build(o){return new ES(o,this.config)}}class ES extends r{static[J]="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 XF(o){return new KF(o??"")}class EF extends N{static[J]="PgJsonbBuilder";constructor(o){super(o,"json","PgJsonb")}build(o){return new YS(o,this.config)}}class YS extends r{static[J]="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 YF(o){return new EF(o??"")}class GF extends N{static[J]="PgLineBuilder";constructor(o){super(o,"array","PgLine")}build(o){return new zF(o,this.config)}}class zF extends r{static[J]="PgLine";getSQLType(){return"line"}mapFromDriverValue(o){let[n,t,T]=o.slice(1,-1).split(",");return[Number.parseFloat(n),Number.parseFloat(t),Number.parseFloat(T)]}mapToDriverValue(o){return`{${o[0]},${o[1]},${o[2]}}`}}class HF extends N{static[J]="PgLineABCBuilder";constructor(o){super(o,"json","PgLineABC")}build(o){return new mF(o,this.config)}}class mF extends r{static[J]="PgLineABC";getSQLType(){return"line"}mapFromDriverValue(o){let[n,t,T]=o.slice(1,-1).split(",");return{a:Number.parseFloat(n),b:Number.parseFloat(t),c:Number.parseFloat(T)}}mapToDriverValue(o){return`{${o.a},${o.b},${o.c}}`}}function QF(o,n){let{name:t,config:T}=Ao(o,n);if(!T?.mode||T.mode==="tuple")return new GF(t);return new HF(t)}class DF extends N{static[J]="PgMacaddrBuilder";constructor(o){super(o,"string","PgMacaddr")}build(o){return new UF(o,this.config)}}class UF extends r{static[J]="PgMacaddr";getSQLType(){return"macaddr"}}function VF(o){return new DF(o??"")}class rF extends N{static[J]="PgMacaddr8Builder";constructor(o){super(o,"string","PgMacaddr8")}build(o){return new BF(o,this.config)}}class BF extends r{static[J]="PgMacaddr8";getSQLType(){return"macaddr8"}}function CF(o){return new rF(o??"")}class LF extends N{static[J]="PgNumericBuilder";constructor(o,n,t){super(o,"string","PgNumeric");this.config.precision=n,this.config.scale=t}build(o){return new GS(o,this.config)}}class GS extends r{static[J]="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 IF(o,n){let{name:t,config:T}=Ao(o,n);return new LF(t,T?.precision,T?.scale)}class jF extends N{static[J]="PgPointTupleBuilder";constructor(o){super(o,"array","PgPointTuple")}build(o){return new bF(o,this.config)}}class bF extends r{static[J]="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 NF extends N{static[J]="PgPointObjectBuilder";constructor(o){super(o,"json","PgPointObject")}build(o){return new hF(o,this.config)}}class hF extends r{static[J]="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 cF(o,n){let{name:t,config:T}=Ao(o,n);if(!T?.mode||T.mode==="tuple")return new jF(t);return new NF(t)}function gJ(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 xF(o,n){let t=new ArrayBuffer(8),T=new DataView(t);for(let S=0;S<8;S++)T.setUint8(S,o[n+S]);return T.getFloat64(0,!0)}function uf(o){let n=gJ(o),t=0,T=n[t];t+=1;let S=new DataView(n.buffer),f=S.getUint32(t,T===1);t+=4;let y;if(f&536870912)y=S.getUint32(t,T===1),t+=4;if((f&65535)===1){let A=xF(n,t);t+=8;let M=xF(n,t);return t+=8,[A,M]}throw new Error("Unsupported geometry type")}class iF extends N{static[J]="PgGeometryBuilder";constructor(o){super(o,"array","PgGeometry")}build(o){return new vF(o,this.config)}}class vF extends r{static[J]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(o){return uf(o)}mapToDriverValue(o){return`point(${o[0]} ${o[1]})`}}class pF extends N{static[J]="PgGeometryObjectBuilder";constructor(o){super(o,"json","PgGeometryObject")}build(o){return new qF(o,this.config)}}class qF extends r{static[J]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(o){let n=uf(o);return{x:n[0],y:n[1]}}mapToDriverValue(o){return`point(${o.x} ${o.y})`}}function ZF(o,n){let{name:t,config:T}=Ao(o,n);if(!T?.mode||T.mode==="tuple")return new iF(t);return new pF(t)}class PF extends N{static[J]="PgRealBuilder";constructor(o,n){super(o,"number","PgReal");this.config.length=n}build(o){return new eF(o,this.config)}}class eF extends r{static[J]="PgReal";constructor(o,n){super(o,n)}getSQLType(){return"real"}mapFromDriverValue=(o)=>{if(typeof o==="string")return Number.parseFloat(o);return o}}function lF(o){return new PF(o??"")}class gF extends N{static[J]="PgSerialBuilder";constructor(o){super(o,"number","PgSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(o){return new dF(o,this.config)}}class dF extends r{static[J]="PgSerial";getSQLType(){return"serial"}}function uF(o){return new gF(o??"")}class aF extends ot{static[J]="PgSmallIntBuilder";constructor(o){super(o,"number","PgSmallInt")}build(o){return new sF(o,this.config)}}class sF extends r{static[J]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=(o)=>{if(typeof o==="string")return Number(o);return o}}function ok(o){return new aF(o??"")}class nk extends N{static[J]="PgSmallSerialBuilder";constructor(o){super(o,"number","PgSmallSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(o){return new tk(o,this.config)}}class tk extends r{static[J]="PgSmallSerial";getSQLType(){return"smallserial"}}function Tk(o){return new nk(o??"")}class Sk extends N{static[J]="PgTextBuilder";constructor(o,n){super(o,"string","PgText");this.config.enumValues=n.enum}build(o){return new fk(o,this.config)}}class fk extends r{static[J]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function yk(o,n={}){let{name:t,config:T}=Ao(o,n);return new Sk(t,T)}class Ak extends Zn{constructor(o,n,t){super(o,"string","PgTime");this.withTimezone=n,this.precision=t,this.config.withTimezone=n,this.config.precision=t}static[J]="PgTimeBuilder";build(o){return new zS(o,this.config)}}class zS extends r{static[J]="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 Mk(o,n={}){let{name:t,config:T}=Ao(o,n);return new Ak(t,T.withTimezone??!1,T.precision)}class Fk extends Zn{static[J]="PgTimestampBuilder";constructor(o,n,t){super(o,"date","PgTimestamp");this.config.withTimezone=n,this.config.precision=t}build(o){return new HS(o,this.config)}}class HS extends r{static[J]="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 kk extends Zn{static[J]="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 r{static[J]="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:T}=Ao(o,n);if(T?.mode==="string")return new kk(t,T.withTimezone??!1,T.precision);return new Fk(t,T?.withTimezone??!1,T?.precision)}class $k extends N{static[J]="PgUUIDBuilder";constructor(o){super(o,"string","PgUUID")}defaultRandom(){return this.default(R`gen_random_uuid()`)}build(o){return new QS(o,this.config)}}class QS extends r{static[J]="PgUUID";getSQLType(){return"uuid"}}function kn(o){return new $k(o??"")}class Jk extends N{static[J]="PgVarcharBuilder";constructor(o,n){super(o,"string","PgVarchar");this.config.length=n.length,this.config.enumValues=n.enum}build(o){return new Rk(o,this.config)}}class Rk extends r{static[J]="PgVarchar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"varchar":`varchar(${this.length})`}}function io(o,n={}){let{name:t,config:T}=Ao(o,n);return new Jk(t,T)}class Wk extends N{static[J]="PgBinaryVectorBuilder";constructor(o,n){super(o,"string","PgBinaryVector");this.config.dimensions=n.dimensions}build(o){return new Ok(o,this.config)}}class Ok extends r{static[J]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}}function _k(o,n){let{name:t,config:T}=Ao(o,n);return new Wk(t,T)}class wk extends N{static[J]="PgHalfVectorBuilder";constructor(o,n){super(o,"array","PgHalfVector");this.config.dimensions=n.dimensions}build(o){return new Kk(o,this.config)}}class Kk extends r{static[J]="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 Xk(o,n){let{name:t,config:T}=Ao(o,n);return new wk(t,T)}class Ek extends N{static[J]="PgSparseVectorBuilder";constructor(o,n){super(o,"string","PgSparseVector");this.config.dimensions=n.dimensions}build(o){return new Yk(o,this.config)}}class Yk extends r{static[J]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function Gk(o,n){let{name:t,config:T}=Ao(o,n);return new Ek(t,T)}class zk extends N{static[J]="PgVectorBuilder";constructor(o,n){super(o,"array","PgVector");this.config.dimensions=n.dimensions}build(o){return new Hk(o,this.config)}}class Hk extends r{static[J]="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 mk(o,n){let{name:t,config:T}=Ao(o,n);return new zk(t,T)}function Qk(){return{bigint:iM,bigserial:PM,boolean:ET,char:uM,cidr:oF,customType:TF,date:yF,doublePrecision:FF,inet:JF,integer:XS,interval:wF,json:XF,jsonb:YF,line:QF,macaddr:VF,macaddr8:CF,numeric:IF,point:cF,geometry:ZF,real:lF,serial:uF,smallint:ok,smallserial:Tk,text:yk,time:Mk,timestamp:Dn,uuid:kn,varchar:io,bit:_k,halfvec:Xk,sparsevec:Gk,vector:mk}}var af=Symbol.for("drizzle:PgInlineForeignKeys"),Dk=Symbol.for("drizzle:EnableRLS");class wn extends L{static[J]="PgTable";static Symbol=Object.assign({},L.Symbol,{InlineForeignKeys:af,EnableRLS:Dk});[af]=[];[Dk]=!1;[L.Symbol.ExtraConfigBuilder]=void 0}function dJ(o,n,t,T,S=o){let f=new wn(o,T,S),y=typeof n==="function"?n(Qk()):n,A=Object.fromEntries(Object.entries(y).map(([k,W])=>{let O=W;O.setName(k);let E=O.build(f);return f[af].push(...O.buildForeignKeys(E,f)),[k,E]})),M=Object.fromEntries(Object.entries(y).map(([k,W])=>{let O=W;O.setName(k);let E=O.buildExtraConfigColumn(f);return[k,E]})),F=Object.assign(f,A);if(F[L.Symbol.Columns]=A,F[L.Symbol.ExtraConfigColumns]=M,t)F[wn.Symbol.ExtraConfigBuilder]=t;return Object.assign(F,{enableRLS:()=>{return F[wn.Symbol.EnableRLS]=!0,F}})}var nt=(o,n,t)=>{return dJ(o,n,t,void 0)};function Uk(...o){if(o[0].columns)return new YT(o[0].columns,o[0].name);return new YT(o)}class YT{static[J]="PgPrimaryKeyBuilder";columns;name;constructor(o,n){this.columns=o,this.name=n}build(o){return new Vk(o,this.columns,this.name)}}class Vk{constructor(o,n,t){this.table=o,this.columns=n,this.name=t}static[J]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[wn.Symbol.Name]}_${this.columns.map((o)=>o.name).join("_")}_pk`}}class sf{constructor(o,n,t){this.sourceTable=o,this.referencedTable=n,this.relationName=t,this.referencedTableName=n[L.Symbol.Name]}static[J]="Relation";referencedTableName;fieldName}class rk{constructor(o,n){this.table=o,this.config=n}static[J]="Relations"}class tt extends sf{constructor(o,n,t,T){super(o,n,t?.relationName);this.config=t,this.isNullable=T}static[J]="One";withFieldName(o){let n=new tt(this.sourceTable,this.referencedTable,this.config,this.isNullable);return n.fieldName=o,n}}class GT extends sf{constructor(o,n,t){super(o,n,t?.relationName);this.config=t}static[J]="Many";withFieldName(o){let n=new GT(this.sourceTable,this.referencedTable,this.config);return n.fieldName=o,n}}function Bk(){return{and:XT,between:HM,eq:Ct,exists:GM,gt:WM,gte:OM,ilike:UM,inArray:KM,isNull:EM,isNotNull:YM,like:QM,lt:_M,lte:wM,ne:$M,not:RM,notBetween:mM,notExists:zM,notLike:DM,notIlike:VM,notInArray:XM,or:JM,sql:R}}function Ck(){return{sql:R,asc:rM,desc:BM}}function Lk(o,n){if(Object.keys(o).length===1&&"default"in o&&!X(o.default,L))o=o.default;let t={},T={},S={};for(let[f,y]of Object.entries(o))if(X(y,L)){let A=kt(y),M=T[A];t[A]=f,S[f]={tsName:f,dbName:y[L.Symbol.Name],schema:y[L.Symbol.Schema],columns:y[L.Symbol.Columns],relations:M?.relations??{},primaryKey:M?.primaryKey??[]};for(let k of Object.values(y[L.Symbol.Columns]))if(k.primary)S[f].primaryKey.push(k);let F=y[L.Symbol.ExtraConfigBuilder]?.(y[L.Symbol.ExtraConfigColumns]);if(F){for(let k of Object.values(F))if(X(k,YT))S[f].primaryKey.push(...k.columns)}}else if(X(y,rk)){let A=kt(y.table),M=t[A],F=y.config(n(y.table)),k;for(let[W,O]of Object.entries(F))if(M){let E=S[M];if(E.relations[W]=O,k)E.primaryKey.push(...k)}else{if(!(A in T))T[A]={relations:{},primaryKey:k};T[A].relations[W]=O}}return{tables:S,tableNamesMap:t}}function uJ(o){return function n(t,T){return new tt(o,t,T,T?.fields.reduce((S,f)=>S&&f.notNull,!0)??!1)}}function aJ(o){return function n(t,T){return new GT(o,t,T)}}function Ik(o,n,t){if(X(t,tt)&&t.config)return{fields:t.config.fields,references:t.config.references};let T=n[kt(t.referencedTable)];if(!T)throw new Error(`Table "${t.referencedTable[L.Symbol.Name]}" not found in schema`);let S=o[T];if(!S)throw new Error(`Table "${T}" not found in schema`);let f=t.sourceTable,y=n[kt(f)];if(!y)throw new Error(`Table "${f[L.Symbol.Name]}" not found in schema`);let A=[];for(let M of Object.values(S.relations))if(t.relationName&&t!==M&&M.relationName===t.relationName||!t.relationName&&M.referencedTable===t.sourceTable)A.push(M);if(A.length>1)throw t.relationName?new Error(`There are multiple relations with name "${t.relationName}" in table "${T}"`):new Error(`There are multiple relations between "${T}" and "${t.sourceTable[L.Symbol.Name]}". Please specify relation name`);if(A[0]&&X(A[0],tt)&&A[0].config)return{fields:A[0].config.references,references:A[0].config.fields};throw new Error(`There is not enough information to infer relation "${y}.${t.fieldName}"`)}function jk(o){return{one:uJ(o),many:aJ(o)}}function DS(o,n,t,T,S=(f)=>f){let f={};for(let[y,A]of T.entries())if(A.isJson){let M=n.relations[A.tsKey],F=t[y],k=typeof F==="string"?JSON.parse(F):F;f[A.tsKey]=X(M,tt)?k&&DS(o,o[A.relationTableTsKey],k,A.selection,S):k.map((W)=>DS(o,o[A.relationTableTsKey],W,A.selection,S))}else{let M=S(t[y]),F=A.field,k;if(X(F,Xo))k=F;else if(X(F,h))k=F.decoder;else k=F.sql.decoder;f[A.tsKey]=M===null?null:k.mapFromDriverValue(M)}return f}import{readFileSync as gk}from"fs";import{resolve as fy}from"path";var $o;(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 f={};for(let y of S)f[y]=y;return f},o.getValidEnumValues=(S)=>{let f=o.objectKeys(S).filter((A)=>typeof S[S[A]]!=="number"),y={};for(let A of f)y[A]=S[A];return o.objectValues(y)},o.objectValues=(S)=>{return o.objectKeys(S).map(function(f){return S[f]})},o.objectKeys=typeof Object.keys==="function"?(S)=>Object.keys(S):(S)=>{let f=[];for(let y in S)if(Object.prototype.hasOwnProperty.call(S,y))f.push(y);return f},o.find=(S,f)=>{for(let y of S)if(f(y))return y;return},o.isInteger=typeof Number.isInteger==="function"?(S)=>Number.isInteger(S):(S)=>typeof S==="number"&&isFinite(S)&&Math.floor(S)===S;function T(S,f=" | "){return S.map((y)=>typeof y==="string"?`'${y}'`:y).join(f)}o.joinValues=T,o.jsonStringifyReplacer=(S,f)=>{if(typeof f==="bigint")return f.toString();return f}})($o||($o={}));var ny;(function(o){o.mergeShapes=(n,t)=>{return{...n,...t}}})(ny||(ny={}));var I=$o.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Tt=(o)=>{switch(typeof o){case"undefined":return I.undefined;case"string":return I.string;case"number":return isNaN(o)?I.nan:I.number;case"boolean":return I.boolean;case"function":return I.function;case"bigint":return I.bigint;case"symbol":return I.symbol;case"object":if(Array.isArray(o))return I.array;if(o===null)return I.null;if(o.then&&typeof o.then==="function"&&o.catch&&typeof o.catch==="function")return I.promise;if(typeof Map!=="undefined"&&o instanceof Map)return I.map;if(typeof Set!=="undefined"&&o instanceof Set)return I.set;if(typeof Date!=="undefined"&&o instanceof Date)return I.date;return I.object;default:return I.unknown}},m=$o.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"]),sJ=(o)=>{return JSON.stringify(o,null,2).replace(/"([^"]+)":/g,"$1:")};class $n extends Error{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}get errors(){return this.issues}format(o){let n=o||function(S){return S.message},t={_errors:[]},T=(S)=>{for(let f of S.issues)if(f.code==="invalid_union")f.unionErrors.map(T);else if(f.code==="invalid_return_type")T(f.returnTypeError);else if(f.code==="invalid_arguments")T(f.argumentsError);else if(f.path.length===0)t._errors.push(n(f));else{let y=t,A=0;while(A<f.path.length){let M=f.path[A];if(A!==f.path.length-1)y[M]=y[M]||{_errors:[]};else y[M]=y[M]||{_errors:[]},y[M]._errors.push(n(f));y=y[M],A++}}};return T(this),t}static assert(o){if(!(o instanceof $n))throw new Error(`Not a ZodError: ${o}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,$o.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(o=(n)=>n.message){let n={},t=[];for(let T of this.issues)if(T.path.length>0)n[T.path[0]]=n[T.path[0]]||[],n[T.path[0]].push(o(T));else t.push(o(T));return{formErrors:t,fieldErrors:n}}get formErrors(){return this.flatten()}}$n.create=(o)=>{return new $n(o)};var bt=(o,n)=>{let t;switch(o.code){case m.invalid_type:if(o.received===I.undefined)t="Required";else t=`Expected ${o.expected}, received ${o.received}`;break;case m.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(o.expected,$o.jsonStringifyReplacer)}`;break;case m.unrecognized_keys:t=`Unrecognized key(s) in object: ${$o.joinValues(o.keys,", ")}`;break;case m.invalid_union:t="Invalid input";break;case m.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${$o.joinValues(o.options)}`;break;case m.invalid_enum_value:t=`Invalid enum value. Expected ${$o.joinValues(o.options)}, received '${o.received}'`;break;case m.invalid_arguments:t="Invalid function arguments";break;case m.invalid_return_type:t="Invalid function return type";break;case m.invalid_date:t="Invalid date";break;case m.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 $o.assertNever(o.validation);else if(o.validation!=="regex")t=`Invalid ${o.validation}`;else t="Invalid";break;case m.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 m.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 m.custom:t="Invalid input";break;case m.invalid_intersection_types:t="Intersection results could not be merged";break;case m.not_multiple_of:t=`Number must be a multiple of ${o.multipleOf}`;break;case m.not_finite:t="Number must be finite";break;default:t=n.defaultError,$o.assertNever(o)}return{message:t}},hk=bt;function oR(o){hk=o}function US(){return hk}var VS=(o)=>{let{data:n,path:t,errorMaps:T,issueData:S}=o,f=[...t,...S.path||[]],y={...S,path:f};if(S.message!==void 0)return{...S,path:f,message:S.message};let A="",M=T.filter((F)=>!!F).slice().reverse();for(let F of M)A=F(y,{data:n,defaultError:A}).message;return{...S,path:f,message:A}},nR=[];function C(o,n){let t=US(),T=VS({issueData:n,data:o.data,path:o.path,errorMaps:[o.common.contextualErrorMap,o.schemaErrorMap,t,t===bt?void 0:bt].filter((S)=>!!S)});o.common.issues.push(T)}class lo{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 T of n){if(T.status==="aborted")return u;if(T.status==="dirty")o.dirty();t.push(T.value)}return{status:o.value,value:t}}static async mergeObjectAsync(o,n){let t=[];for(let T of n){let S=await T.key,f=await T.value;t.push({key:S,value:f})}return lo.mergeObjectSync(o,t)}static mergeObjectSync(o,n){let t={};for(let T of n){let{key:S,value:f}=T;if(S.status==="aborted")return u;if(f.status==="aborted")return u;if(S.status==="dirty")o.dirty();if(f.status==="dirty")o.dirty();if(S.value!=="__proto__"&&(typeof f.value!=="undefined"||T.alwaysSet))t[S.value]=f.value}return{status:o.value,value:t}}}var u=Object.freeze({status:"aborted"}),It=(o)=>({status:"dirty",value:o}),on=(o)=>({status:"valid",value:o}),ty=(o)=>o.status==="aborted",Ty=(o)=>o.status==="dirty",mT=(o)=>o.status==="valid",QT=(o)=>typeof Promise!=="undefined"&&o instanceof Promise;function rS(o,n,t,T){if(t==="a"&&!T)throw new TypeError("Private accessor was defined without a getter");if(typeof n==="function"?o!==n||!T:!n.has(o))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?T:t==="a"?T.call(o):T?T.value:n.get(o)}function ck(o,n,t,T,S){if(T==="m")throw new TypeError("Private method is not writable");if(T==="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 T==="a"?S.call(o,t):S?S.value=t:n.set(o,t),t}var q;(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})(q||(q={}));var zT,HT;class Bn{constructor(o,n,t,T){this._cachedPath=[],this.parent=o,this.data=n,this._path=t,this._key=T}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 bk=(o,n)=>{if(mT(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 $n(o.common.issues);return this._error=t,this._error}}}};function to(o){if(!o)return{};let{errorMap:n,invalid_type_error:t,required_error:T,description:S}=o;if(n&&(t||T))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:(y,A)=>{var M,F;let{message:k}=o;if(y.code==="invalid_enum_value")return{message:k!==null&&k!==void 0?k:A.defaultError};if(typeof A.data==="undefined")return{message:(M=k!==null&&k!==void 0?k:T)!==null&&M!==void 0?M:A.defaultError};if(y.code!=="invalid_type")return{message:A.defaultError};return{message:(F=k!==null&&k!==void 0?k:t)!==null&&F!==void 0?F:A.defaultError}},description:S}}class To{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)}get description(){return this._def.description}_getType(o){return Tt(o.data)}_getOrReturnCtx(o,n){return n||{common:o.parent.common,data:o.data,parsedType:Tt(o.data),schemaErrorMap:this._def.errorMap,path:o.path,parent:o.parent}}_processInputParams(o){return{status:new lo,ctx:{common:o.parent.common,data:o.data,parsedType:Tt(o.data),schemaErrorMap:this._def.errorMap,path:o.path,parent:o.parent}}}_parseSync(o){let n=this._parse(o);if(QT(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 T={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:Tt(o)},S=this._parseSync({data:o,path:T.path,parent:T});return bk(T,S)}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:Tt(o)},T=this._parse({data:o,path:t.path,parent:t}),S=await(QT(T)?T:Promise.resolve(T));return bk(t,S)}refine(o,n){let t=(T)=>{if(typeof n==="string"||typeof n==="undefined")return{message:n};else if(typeof n==="function")return n(T);else return n};return this._refinement((T,S)=>{let f=o(T),y=()=>S.addIssue({code:m.custom,...t(T)});if(typeof Promise!=="undefined"&&f instanceof Promise)return f.then((A)=>{if(!A)return y(),!1;else return!0});if(!f)return y(),!1;else return!0})}refinement(o,n){return this._refinement((t,T)=>{if(!o(t))return T.addIssue(typeof n==="function"?n(t,T):n),!1;else return!0})}_refinement(o){return new Kn({schema:this,typeName:g.ZodEffects,effect:{type:"refinement",refinement:o}})}superRefine(o){return this._refinement(o)}optional(){return rn.create(this,this._def)}nullable(){return en.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Vn.create(this,this._def)}promise(){return Wt.create(this,this._def)}or(o){return xt.create([this,o],this._def)}and(o){return it.create(this,o,this._def)}transform(o){return new Kn({...to(this._def),schema:this,typeName:g.ZodEffects,effect:{type:"transform",transform:o}})}default(o){let n=typeof o==="function"?o:()=>o;return new Zt({...to(this._def),innerType:this,defaultValue:n,typeName:g.ZodDefault})}brand(){return new CS({typeName:g.ZodBranded,type:this,...to(this._def)})}catch(o){let n=typeof o==="function"?o:()=>o;return new Pt({...to(this._def),innerType:this,catchValue:n,typeName:g.ZodCatch})}describe(o){return new this.constructor({...this._def,description:o})}pipe(o){return CT.create(this,o)}readonly(){return et.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var tR=/^c[^\s-]{8,}$/i,TR=/^[0-9a-z]+$/,SR=/^[0-9A-HJKMNP-TV-Z]{26}$/,fR=/^[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,yR=/^[a-z0-9_-]{21}$/i,AR=/^[-+]?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)?)??$/,MR=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,FR="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",oy,kR=/^(?:(?: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])$/,$R=/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,JR=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,xk="((\\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])))",RR=new RegExp(`^${xk}\$`);function ik(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 WR(o){return new RegExp(`^${ik(o)}\$`)}function vk(o){let n=`${xk}T${ik(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 OR(o,n){if((n==="v4"||!n)&&kR.test(o))return!0;if((n==="v6"||!n)&&$R.test(o))return!0;return!1}class Un extends To{_parse(o){if(this._def.coerce)o.data=String(o.data);if(this._getType(o)!==I.string){let S=this._getOrReturnCtx(o);return C(S,{code:m.invalid_type,expected:I.string,received:S.parsedType}),u}let t=new lo,T=void 0;for(let S of this._def.checks)if(S.kind==="min"){if(o.data.length<S.value)T=this._getOrReturnCtx(o,T),C(T,{code:m.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)T=this._getOrReturnCtx(o,T),C(T,{code:m.too_big,maximum:S.value,type:"string",inclusive:!0,exact:!1,message:S.message}),t.dirty()}else if(S.kind==="length"){let f=o.data.length>S.value,y=o.data.length<S.value;if(f||y){if(T=this._getOrReturnCtx(o,T),f)C(T,{code:m.too_big,maximum:S.value,type:"string",inclusive:!0,exact:!0,message:S.message});else if(y)C(T,{code:m.too_small,minimum:S.value,type:"string",inclusive:!0,exact:!0,message:S.message});t.dirty()}}else if(S.kind==="email"){if(!MR.test(o.data))T=this._getOrReturnCtx(o,T),C(T,{validation:"email",code:m.invalid_string,message:S.message}),t.dirty()}else if(S.kind==="emoji"){if(!oy)oy=new RegExp(FR,"u");if(!oy.test(o.data))T=this._getOrReturnCtx(o,T),C(T,{validation:"emoji",code:m.invalid_string,message:S.message}),t.dirty()}else if(S.kind==="uuid"){if(!fR.test(o.data))T=this._getOrReturnCtx(o,T),C(T,{validation:"uuid",code:m.invalid_string,message:S.message}),t.dirty()}else if(S.kind==="nanoid"){if(!yR.test(o.data))T=this._getOrReturnCtx(o,T),C(T,{validation:"nanoid",code:m.invalid_string,message:S.message}),t.dirty()}else if(S.kind==="cuid"){if(!tR.test(o.data))T=this._getOrReturnCtx(o,T),C(T,{validation:"cuid",code:m.invalid_string,message:S.message}),t.dirty()}else if(S.kind==="cuid2"){if(!TR.test(o.data))T=this._getOrReturnCtx(o,T),C(T,{validation:"cuid2",code:m.invalid_string,message:S.message}),t.dirty()}else if(S.kind==="ulid"){if(!SR.test(o.data))T=this._getOrReturnCtx(o,T),C(T,{validation:"ulid",code:m.invalid_string,message:S.message}),t.dirty()}else if(S.kind==="url")try{new URL(o.data)}catch(f){T=this._getOrReturnCtx(o,T),C(T,{validation:"url",code:m.invalid_string,message:S.message}),t.dirty()}else if(S.kind==="regex"){if(S.regex.lastIndex=0,!S.regex.test(o.data))T=this._getOrReturnCtx(o,T),C(T,{validation:"regex",code:m.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))T=this._getOrReturnCtx(o,T),C(T,{code:m.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))T=this._getOrReturnCtx(o,T),C(T,{code:m.invalid_string,validation:{startsWith:S.value},message:S.message}),t.dirty()}else if(S.kind==="endsWith"){if(!o.data.endsWith(S.value))T=this._getOrReturnCtx(o,T),C(T,{code:m.invalid_string,validation:{endsWith:S.value},message:S.message}),t.dirty()}else if(S.kind==="datetime"){if(!vk(S).test(o.data))T=this._getOrReturnCtx(o,T),C(T,{code:m.invalid_string,validation:"datetime",message:S.message}),t.dirty()}else if(S.kind==="date"){if(!RR.test(o.data))T=this._getOrReturnCtx(o,T),C(T,{code:m.invalid_string,validation:"date",message:S.message}),t.dirty()}else if(S.kind==="time"){if(!WR(S).test(o.data))T=this._getOrReturnCtx(o,T),C(T,{code:m.invalid_string,validation:"time",message:S.message}),t.dirty()}else if(S.kind==="duration"){if(!AR.test(o.data))T=this._getOrReturnCtx(o,T),C(T,{validation:"duration",code:m.invalid_string,message:S.message}),t.dirty()}else if(S.kind==="ip"){if(!OR(o.data,S.version))T=this._getOrReturnCtx(o,T),C(T,{validation:"ip",code:m.invalid_string,message:S.message}),t.dirty()}else if(S.kind==="base64"){if(!JR.test(o.data))T=this._getOrReturnCtx(o,T),C(T,{validation:"base64",code:m.invalid_string,message:S.message}),t.dirty()}else $o.assertNever(S);return{status:t.value,value:o.data}}_regex(o,n,t){return this.refinement((T)=>o.test(T),{validation:n,code:m.invalid_string,...q.errToObj(t)})}_addCheck(o){return new Un({...this._def,checks:[...this._def.checks,o]})}email(o){return this._addCheck({kind:"email",...q.errToObj(o)})}url(o){return this._addCheck({kind:"url",...q.errToObj(o)})}emoji(o){return this._addCheck({kind:"emoji",...q.errToObj(o)})}uuid(o){return this._addCheck({kind:"uuid",...q.errToObj(o)})}nanoid(o){return this._addCheck({kind:"nanoid",...q.errToObj(o)})}cuid(o){return this._addCheck({kind:"cuid",...q.errToObj(o)})}cuid2(o){return this._addCheck({kind:"cuid2",...q.errToObj(o)})}ulid(o){return this._addCheck({kind:"ulid",...q.errToObj(o)})}base64(o){return this._addCheck({kind:"base64",...q.errToObj(o)})}ip(o){return this._addCheck({kind:"ip",...q.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,...q.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,...q.errToObj(o===null||o===void 0?void 0:o.message)})}duration(o){return this._addCheck({kind:"duration",...q.errToObj(o)})}regex(o,n){return this._addCheck({kind:"regex",regex:o,...q.errToObj(n)})}includes(o,n){return this._addCheck({kind:"includes",value:o,position:n===null||n===void 0?void 0:n.position,...q.errToObj(n===null||n===void 0?void 0:n.message)})}startsWith(o,n){return this._addCheck({kind:"startsWith",value:o,...q.errToObj(n)})}endsWith(o,n){return this._addCheck({kind:"endsWith",value:o,...q.errToObj(n)})}min(o,n){return this._addCheck({kind:"min",value:o,...q.errToObj(n)})}max(o,n){return this._addCheck({kind:"max",value:o,...q.errToObj(n)})}length(o,n){return this._addCheck({kind:"length",value:o,...q.errToObj(n)})}nonempty(o){return this.min(1,q.errToObj(o))}trim(){return new Un({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Un({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Un({...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 isBase64(){return!!this._def.checks.find((o)=>o.kind==="base64")}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}}Un.create=(o)=>{var n;return new Un({checks:[],typeName:g.ZodString,coerce:(n=o===null||o===void 0?void 0:o.coerce)!==null&&n!==void 0?n:!1,...to(o)})};function _R(o,n){let t=(o.toString().split(".")[1]||"").length,T=(n.toString().split(".")[1]||"").length,S=t>T?t:T,f=parseInt(o.toFixed(S).replace(".","")),y=parseInt(n.toFixed(S).replace(".",""));return f%y/Math.pow(10,S)}class ft extends To{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)!==I.number){let S=this._getOrReturnCtx(o);return C(S,{code:m.invalid_type,expected:I.number,received:S.parsedType}),u}let t=void 0,T=new lo;for(let S of this._def.checks)if(S.kind==="int"){if(!$o.isInteger(o.data))t=this._getOrReturnCtx(o,t),C(t,{code:m.invalid_type,expected:"integer",received:"float",message:S.message}),T.dirty()}else if(S.kind==="min"){if(S.inclusive?o.data<S.value:o.data<=S.value)t=this._getOrReturnCtx(o,t),C(t,{code:m.too_small,minimum:S.value,type:"number",inclusive:S.inclusive,exact:!1,message:S.message}),T.dirty()}else if(S.kind==="max"){if(S.inclusive?o.data>S.value:o.data>=S.value)t=this._getOrReturnCtx(o,t),C(t,{code:m.too_big,maximum:S.value,type:"number",inclusive:S.inclusive,exact:!1,message:S.message}),T.dirty()}else if(S.kind==="multipleOf"){if(_R(o.data,S.value)!==0)t=this._getOrReturnCtx(o,t),C(t,{code:m.not_multiple_of,multipleOf:S.value,message:S.message}),T.dirty()}else if(S.kind==="finite"){if(!Number.isFinite(o.data))t=this._getOrReturnCtx(o,t),C(t,{code:m.not_finite,message:S.message}),T.dirty()}else $o.assertNever(S);return{status:T.value,value:o.data}}gte(o,n){return this.setLimit("min",o,!0,q.toString(n))}gt(o,n){return this.setLimit("min",o,!1,q.toString(n))}lte(o,n){return this.setLimit("max",o,!0,q.toString(n))}lt(o,n){return this.setLimit("max",o,!1,q.toString(n))}setLimit(o,n,t,T){return new ft({...this._def,checks:[...this._def.checks,{kind:o,value:n,inclusive:t,message:q.toString(T)}]})}_addCheck(o){return new ft({...this._def,checks:[...this._def.checks,o]})}int(o){return this._addCheck({kind:"int",message:q.toString(o)})}positive(o){return this._addCheck({kind:"min",value:0,inclusive:!1,message:q.toString(o)})}negative(o){return this._addCheck({kind:"max",value:0,inclusive:!1,message:q.toString(o)})}nonpositive(o){return this._addCheck({kind:"max",value:0,inclusive:!0,message:q.toString(o)})}nonnegative(o){return this._addCheck({kind:"min",value:0,inclusive:!0,message:q.toString(o)})}multipleOf(o,n){return this._addCheck({kind:"multipleOf",value:o,message:q.toString(n)})}finite(o){return this._addCheck({kind:"finite",message:q.toString(o)})}safe(o){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:q.toString(o)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:q.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"&&$o.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)}}ft.create=(o)=>{return new ft({checks:[],typeName:g.ZodNumber,coerce:(o===null||o===void 0?void 0:o.coerce)||!1,...to(o)})};class yt extends To{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(o){if(this._def.coerce)o.data=BigInt(o.data);if(this._getType(o)!==I.bigint){let S=this._getOrReturnCtx(o);return C(S,{code:m.invalid_type,expected:I.bigint,received:S.parsedType}),u}let t=void 0,T=new lo;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),C(t,{code:m.too_small,type:"bigint",minimum:S.value,inclusive:S.inclusive,message:S.message}),T.dirty()}else if(S.kind==="max"){if(S.inclusive?o.data>S.value:o.data>=S.value)t=this._getOrReturnCtx(o,t),C(t,{code:m.too_big,type:"bigint",maximum:S.value,inclusive:S.inclusive,message:S.message}),T.dirty()}else if(S.kind==="multipleOf"){if(o.data%S.value!==BigInt(0))t=this._getOrReturnCtx(o,t),C(t,{code:m.not_multiple_of,multipleOf:S.value,message:S.message}),T.dirty()}else $o.assertNever(S);return{status:T.value,value:o.data}}gte(o,n){return this.setLimit("min",o,!0,q.toString(n))}gt(o,n){return this.setLimit("min",o,!1,q.toString(n))}lte(o,n){return this.setLimit("max",o,!0,q.toString(n))}lt(o,n){return this.setLimit("max",o,!1,q.toString(n))}setLimit(o,n,t,T){return new yt({...this._def,checks:[...this._def.checks,{kind:o,value:n,inclusive:t,message:q.toString(T)}]})}_addCheck(o){return new yt({...this._def,checks:[...this._def.checks,o]})}positive(o){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:q.toString(o)})}negative(o){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:q.toString(o)})}nonpositive(o){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:q.toString(o)})}nonnegative(o){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:q.toString(o)})}multipleOf(o,n){return this._addCheck({kind:"multipleOf",value:o,message:q.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}}yt.create=(o)=>{var n;return new yt({checks:[],typeName:g.ZodBigInt,coerce:(n=o===null||o===void 0?void 0:o.coerce)!==null&&n!==void 0?n:!1,...to(o)})};class Nt extends To{_parse(o){if(this._def.coerce)o.data=Boolean(o.data);if(this._getType(o)!==I.boolean){let t=this._getOrReturnCtx(o);return C(t,{code:m.invalid_type,expected:I.boolean,received:t.parsedType}),u}return on(o.data)}}Nt.create=(o)=>{return new Nt({typeName:g.ZodBoolean,coerce:(o===null||o===void 0?void 0:o.coerce)||!1,...to(o)})};class $t extends To{_parse(o){if(this._def.coerce)o.data=new Date(o.data);if(this._getType(o)!==I.date){let S=this._getOrReturnCtx(o);return C(S,{code:m.invalid_type,expected:I.date,received:S.parsedType}),u}if(isNaN(o.data.getTime())){let S=this._getOrReturnCtx(o);return C(S,{code:m.invalid_date}),u}let t=new lo,T=void 0;for(let S of this._def.checks)if(S.kind==="min"){if(o.data.getTime()<S.value)T=this._getOrReturnCtx(o,T),C(T,{code:m.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)T=this._getOrReturnCtx(o,T),C(T,{code:m.too_big,message:S.message,inclusive:!0,exact:!1,maximum:S.value,type:"date"}),t.dirty()}else $o.assertNever(S);return{status:t.value,value:new Date(o.data.getTime())}}_addCheck(o){return new $t({...this._def,checks:[...this._def.checks,o]})}min(o,n){return this._addCheck({kind:"min",value:o.getTime(),message:q.toString(n)})}max(o,n){return this._addCheck({kind:"max",value:o.getTime(),message:q.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}}$t.create=(o)=>{return new $t({checks:[],coerce:(o===null||o===void 0?void 0:o.coerce)||!1,typeName:g.ZodDate,...to(o)})};class DT extends To{_parse(o){if(this._getType(o)!==I.symbol){let t=this._getOrReturnCtx(o);return C(t,{code:m.invalid_type,expected:I.symbol,received:t.parsedType}),u}return on(o.data)}}DT.create=(o)=>{return new DT({typeName:g.ZodSymbol,...to(o)})};class ht extends To{_parse(o){if(this._getType(o)!==I.undefined){let t=this._getOrReturnCtx(o);return C(t,{code:m.invalid_type,expected:I.undefined,received:t.parsedType}),u}return on(o.data)}}ht.create=(o)=>{return new ht({typeName:g.ZodUndefined,...to(o)})};class ct extends To{_parse(o){if(this._getType(o)!==I.null){let t=this._getOrReturnCtx(o);return C(t,{code:m.invalid_type,expected:I.null,received:t.parsedType}),u}return on(o.data)}}ct.create=(o)=>{return new ct({typeName:g.ZodNull,...to(o)})};class Jt extends To{constructor(){super(...arguments);this._any=!0}_parse(o){return on(o.data)}}Jt.create=(o)=>{return new Jt({typeName:g.ZodAny,...to(o)})};class St extends To{constructor(){super(...arguments);this._unknown=!0}_parse(o){return on(o.data)}}St.create=(o)=>{return new St({typeName:g.ZodUnknown,...to(o)})};class Nn extends To{_parse(o){let n=this._getOrReturnCtx(o);return C(n,{code:m.invalid_type,expected:I.never,received:n.parsedType}),u}}Nn.create=(o)=>{return new Nn({typeName:g.ZodNever,...to(o)})};class UT extends To{_parse(o){if(this._getType(o)!==I.undefined){let t=this._getOrReturnCtx(o);return C(t,{code:m.invalid_type,expected:I.void,received:t.parsedType}),u}return on(o.data)}}UT.create=(o)=>{return new UT({typeName:g.ZodVoid,...to(o)})};class Vn extends To{_parse(o){let{ctx:n,status:t}=this._processInputParams(o),T=this._def;if(n.parsedType!==I.array)return C(n,{code:m.invalid_type,expected:I.array,received:n.parsedType}),u;if(T.exactLength!==null){let f=n.data.length>T.exactLength.value,y=n.data.length<T.exactLength.value;if(f||y)C(n,{code:f?m.too_big:m.too_small,minimum:y?T.exactLength.value:void 0,maximum:f?T.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:T.exactLength.message}),t.dirty()}if(T.minLength!==null){if(n.data.length<T.minLength.value)C(n,{code:m.too_small,minimum:T.minLength.value,type:"array",inclusive:!0,exact:!1,message:T.minLength.message}),t.dirty()}if(T.maxLength!==null){if(n.data.length>T.maxLength.value)C(n,{code:m.too_big,maximum:T.maxLength.value,type:"array",inclusive:!0,exact:!1,message:T.maxLength.message}),t.dirty()}if(n.common.async)return Promise.all([...n.data].map((f,y)=>{return T.type._parseAsync(new Bn(n,f,n.path,y))})).then((f)=>{return lo.mergeArray(t,f)});let S=[...n.data].map((f,y)=>{return T.type._parseSync(new Bn(n,f,n.path,y))});return lo.mergeArray(t,S)}get element(){return this._def.type}min(o,n){return new Vn({...this._def,minLength:{value:o,message:q.toString(n)}})}max(o,n){return new Vn({...this._def,maxLength:{value:o,message:q.toString(n)}})}length(o,n){return new Vn({...this._def,exactLength:{value:o,message:q.toString(n)}})}nonempty(o){return this.min(1,o)}}Vn.create=(o,n)=>{return new Vn({type:o,minLength:null,maxLength:null,exactLength:null,typeName:g.ZodArray,...to(n)})};function Lt(o){if(o instanceof Uo){let n={};for(let t in o.shape){let T=o.shape[t];n[t]=rn.create(Lt(T))}return new Uo({...o._def,shape:()=>n})}else if(o instanceof Vn)return new Vn({...o._def,type:Lt(o.element)});else if(o instanceof rn)return rn.create(Lt(o.unwrap()));else if(o instanceof en)return en.create(Lt(o.unwrap()));else if(o instanceof hn)return hn.create(o.items.map((n)=>Lt(n)));else return o}class Uo extends To{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=$o.objectKeys(o);return this._cached={shape:o,keys:n}}_parse(o){if(this._getType(o)!==I.object){let M=this._getOrReturnCtx(o);return C(M,{code:m.invalid_type,expected:I.object,received:M.parsedType}),u}let{status:t,ctx:T}=this._processInputParams(o),{shape:S,keys:f}=this._getCached(),y=[];if(!(this._def.catchall instanceof Nn&&this._def.unknownKeys==="strip")){for(let M in T.data)if(!f.includes(M))y.push(M)}let A=[];for(let M of f){let F=S[M],k=T.data[M];A.push({key:{status:"valid",value:M},value:F._parse(new Bn(T,k,T.path,M)),alwaysSet:M in T.data})}if(this._def.catchall instanceof Nn){let M=this._def.unknownKeys;if(M==="passthrough")for(let F of y)A.push({key:{status:"valid",value:F},value:{status:"valid",value:T.data[F]}});else if(M==="strict"){if(y.length>0)C(T,{code:m.unrecognized_keys,keys:y}),t.dirty()}else if(M==="strip");else throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let M=this._def.catchall;for(let F of y){let k=T.data[F];A.push({key:{status:"valid",value:F},value:M._parse(new Bn(T,k,T.path,F)),alwaysSet:F in T.data})}}if(T.common.async)return Promise.resolve().then(async()=>{let M=[];for(let F of A){let k=await F.key,W=await F.value;M.push({key:k,value:W,alwaysSet:F.alwaysSet})}return M}).then((M)=>{return lo.mergeObjectSync(t,M)});else return lo.mergeObjectSync(t,A)}get shape(){return this._def.shape()}strict(o){return q.errToObj,new Uo({...this._def,unknownKeys:"strict",...o!==void 0?{errorMap:(n,t)=>{var T,S,f,y;let A=(f=(S=(T=this._def).errorMap)===null||S===void 0?void 0:S.call(T,n,t).message)!==null&&f!==void 0?f:t.defaultError;if(n.code==="unrecognized_keys")return{message:(y=q.errToObj(o).message)!==null&&y!==void 0?y:A};return{message:A}}}:{}})}strip(){return new Uo({...this._def,unknownKeys:"strip"})}passthrough(){return new Uo({...this._def,unknownKeys:"passthrough"})}extend(o){return new Uo({...this._def,shape:()=>({...this._def.shape(),...o})})}merge(o){return new Uo({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 Uo({...this._def,catchall:o})}pick(o){let n={};return $o.objectKeys(o).forEach((t)=>{if(o[t]&&this.shape[t])n[t]=this.shape[t]}),new Uo({...this._def,shape:()=>n})}omit(o){let n={};return $o.objectKeys(this.shape).forEach((t)=>{if(!o[t])n[t]=this.shape[t]}),new Uo({...this._def,shape:()=>n})}deepPartial(){return Lt(this)}partial(o){let n={};return $o.objectKeys(this.shape).forEach((t)=>{let T=this.shape[t];if(o&&!o[t])n[t]=T;else n[t]=T.optional()}),new Uo({...this._def,shape:()=>n})}required(o){let n={};return $o.objectKeys(this.shape).forEach((t)=>{if(o&&!o[t])n[t]=this.shape[t];else{let S=this.shape[t];while(S instanceof rn)S=S._def.innerType;n[t]=S}}),new Uo({...this._def,shape:()=>n})}keyof(){return pk($o.objectKeys(this.shape))}}Uo.create=(o,n)=>{return new Uo({shape:()=>o,unknownKeys:"strip",catchall:Nn.create(),typeName:g.ZodObject,...to(n)})};Uo.strictCreate=(o,n)=>{return new Uo({shape:()=>o,unknownKeys:"strict",catchall:Nn.create(),typeName:g.ZodObject,...to(n)})};Uo.lazycreate=(o,n)=>{return new Uo({shape:o,unknownKeys:"strip",catchall:Nn.create(),typeName:g.ZodObject,...to(n)})};class xt extends To{_parse(o){let{ctx:n}=this._processInputParams(o),t=this._def.options;function T(S){for(let y of S)if(y.result.status==="valid")return y.result;for(let y of S)if(y.result.status==="dirty")return n.common.issues.push(...y.ctx.common.issues),y.result;let f=S.map((y)=>new $n(y.ctx.common.issues));return C(n,{code:m.invalid_union,unionErrors:f}),u}if(n.common.async)return Promise.all(t.map(async(S)=>{let f={...n,common:{...n.common,issues:[]},parent:null};return{result:await S._parseAsync({data:n.data,path:n.path,parent:f}),ctx:f}})).then(T);else{let S=void 0,f=[];for(let A of t){let M={...n,common:{...n.common,issues:[]},parent:null},F=A._parseSync({data:n.data,path:n.path,parent:M});if(F.status==="valid")return F;else if(F.status==="dirty"&&!S)S={result:F,ctx:M};if(M.common.issues.length)f.push(M.common.issues)}if(S)return n.common.issues.push(...S.ctx.common.issues),S.result;let y=f.map((A)=>new $n(A));return C(n,{code:m.invalid_union,unionErrors:y}),u}}get options(){return this._def.options}}xt.create=(o,n)=>{return new xt({options:o,typeName:g.ZodUnion,...to(n)})};var Pn=(o)=>{if(o instanceof vt)return Pn(o.schema);else if(o instanceof Kn)return Pn(o.innerType());else if(o instanceof pt)return[o.value];else if(o instanceof At)return o.options;else if(o instanceof qt)return $o.objectValues(o.enum);else if(o instanceof Zt)return Pn(o._def.innerType);else if(o instanceof ht)return[void 0];else if(o instanceof ct)return[null];else if(o instanceof rn)return[void 0,...Pn(o.unwrap())];else if(o instanceof en)return[null,...Pn(o.unwrap())];else if(o instanceof CS)return Pn(o.unwrap());else if(o instanceof et)return Pn(o.unwrap());else if(o instanceof Pt)return Pn(o._def.innerType);else return[]};class BS extends To{_parse(o){let{ctx:n}=this._processInputParams(o);if(n.parsedType!==I.object)return C(n,{code:m.invalid_type,expected:I.object,received:n.parsedType}),u;let t=this.discriminator,T=n.data[t],S=this.optionsMap.get(T);if(!S)return C(n,{code:m.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[t]}),u;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 T=new Map;for(let S of n){let f=Pn(S.shape[o]);if(!f.length)throw new Error(`A discriminator value for key \`${o}\` could not be extracted from all schema options`);for(let y of f){if(T.has(y))throw new Error(`Discriminator property ${String(o)} has duplicate value ${String(y)}`);T.set(y,S)}}return new BS({typeName:g.ZodDiscriminatedUnion,discriminator:o,options:n,optionsMap:T,...to(t)})}}function Sy(o,n){let t=Tt(o),T=Tt(n);if(o===n)return{valid:!0,data:o};else if(t===I.object&&T===I.object){let S=$o.objectKeys(n),f=$o.objectKeys(o).filter((A)=>S.indexOf(A)!==-1),y={...o,...n};for(let A of f){let M=Sy(o[A],n[A]);if(!M.valid)return{valid:!1};y[A]=M.data}return{valid:!0,data:y}}else if(t===I.array&&T===I.array){if(o.length!==n.length)return{valid:!1};let S=[];for(let f=0;f<o.length;f++){let y=o[f],A=n[f],M=Sy(y,A);if(!M.valid)return{valid:!1};S.push(M.data)}return{valid:!0,data:S}}else if(t===I.date&&T===I.date&&+o===+n)return{valid:!0,data:o};else return{valid:!1}}class it extends To{_parse(o){let{status:n,ctx:t}=this._processInputParams(o),T=(S,f)=>{if(ty(S)||ty(f))return u;let y=Sy(S.value,f.value);if(!y.valid)return C(t,{code:m.invalid_intersection_types}),u;if(Ty(S)||Ty(f))n.dirty();return{status:n.value,value:y.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,f])=>T(S,f));else return T(this._def.left._parseSync({data:t.data,path:t.path,parent:t}),this._def.right._parseSync({data:t.data,path:t.path,parent:t}))}}it.create=(o,n,t)=>{return new it({left:o,right:n,typeName:g.ZodIntersection,...to(t)})};class hn extends To{_parse(o){let{status:n,ctx:t}=this._processInputParams(o);if(t.parsedType!==I.array)return C(t,{code:m.invalid_type,expected:I.array,received:t.parsedType}),u;if(t.data.length<this._def.items.length)return C(t,{code:m.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),u;if(!this._def.rest&&t.data.length>this._def.items.length)C(t,{code:m.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty();let S=[...t.data].map((f,y)=>{let A=this._def.items[y]||this._def.rest;if(!A)return null;return A._parse(new Bn(t,f,t.path,y))}).filter((f)=>!!f);if(t.common.async)return Promise.all(S).then((f)=>{return lo.mergeArray(n,f)});else return lo.mergeArray(n,S)}get items(){return this._def.items}rest(o){return new hn({...this._def,rest:o})}}hn.create=(o,n)=>{if(!Array.isArray(o))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new hn({items:o,typeName:g.ZodTuple,rest:null,...to(n)})};class VT extends To{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!==I.object)return C(t,{code:m.invalid_type,expected:I.object,received:t.parsedType}),u;let T=[],S=this._def.keyType,f=this._def.valueType;for(let y in t.data)T.push({key:S._parse(new Bn(t,y,t.path,y)),value:f._parse(new Bn(t,t.data[y],t.path,y)),alwaysSet:y in t.data});if(t.common.async)return lo.mergeObjectAsync(n,T);else return lo.mergeObjectSync(n,T)}get element(){return this._def.valueType}static create(o,n,t){if(n instanceof To)return new VT({keyType:o,valueType:n,typeName:g.ZodRecord,...to(t)});return new VT({keyType:Un.create(),valueType:o,typeName:g.ZodRecord,...to(n)})}}class rT extends To{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!==I.map)return C(t,{code:m.invalid_type,expected:I.map,received:t.parsedType}),u;let T=this._def.keyType,S=this._def.valueType,f=[...t.data.entries()].map(([y,A],M)=>{return{key:T._parse(new Bn(t,y,t.path,[M,"key"])),value:S._parse(new Bn(t,A,t.path,[M,"value"]))}});if(t.common.async){let y=new Map;return Promise.resolve().then(async()=>{for(let A of f){let M=await A.key,F=await A.value;if(M.status==="aborted"||F.status==="aborted")return u;if(M.status==="dirty"||F.status==="dirty")n.dirty();y.set(M.value,F.value)}return{status:n.value,value:y}})}else{let y=new Map;for(let A of f){let{key:M,value:F}=A;if(M.status==="aborted"||F.status==="aborted")return u;if(M.status==="dirty"||F.status==="dirty")n.dirty();y.set(M.value,F.value)}return{status:n.value,value:y}}}}rT.create=(o,n,t)=>{return new rT({valueType:n,keyType:o,typeName:g.ZodMap,...to(t)})};class Rt extends To{_parse(o){let{status:n,ctx:t}=this._processInputParams(o);if(t.parsedType!==I.set)return C(t,{code:m.invalid_type,expected:I.set,received:t.parsedType}),u;let T=this._def;if(T.minSize!==null){if(t.data.size<T.minSize.value)C(t,{code:m.too_small,minimum:T.minSize.value,type:"set",inclusive:!0,exact:!1,message:T.minSize.message}),n.dirty()}if(T.maxSize!==null){if(t.data.size>T.maxSize.value)C(t,{code:m.too_big,maximum:T.maxSize.value,type:"set",inclusive:!0,exact:!1,message:T.maxSize.message}),n.dirty()}let S=this._def.valueType;function f(A){let M=new Set;for(let F of A){if(F.status==="aborted")return u;if(F.status==="dirty")n.dirty();M.add(F.value)}return{status:n.value,value:M}}let y=[...t.data.values()].map((A,M)=>S._parse(new Bn(t,A,t.path,M)));if(t.common.async)return Promise.all(y).then((A)=>f(A));else return f(y)}min(o,n){return new Rt({...this._def,minSize:{value:o,message:q.toString(n)}})}max(o,n){return new Rt({...this._def,maxSize:{value:o,message:q.toString(n)}})}size(o,n){return this.min(o,n).max(o,n)}nonempty(o){return this.min(1,o)}}Rt.create=(o,n)=>{return new Rt({valueType:o,minSize:null,maxSize:null,typeName:g.ZodSet,...to(n)})};class jt extends To{constructor(){super(...arguments);this.validate=this.implement}_parse(o){let{ctx:n}=this._processInputParams(o);if(n.parsedType!==I.function)return C(n,{code:m.invalid_type,expected:I.function,received:n.parsedType}),u;function t(y,A){return VS({data:y,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,US(),bt].filter((M)=>!!M),issueData:{code:m.invalid_arguments,argumentsError:A}})}function T(y,A){return VS({data:y,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,US(),bt].filter((M)=>!!M),issueData:{code:m.invalid_return_type,returnTypeError:A}})}let S={errorMap:n.common.contextualErrorMap},f=n.data;if(this._def.returns instanceof Wt){let y=this;return on(async function(...A){let M=new $n([]),F=await y._def.args.parseAsync(A,S).catch((O)=>{throw M.addIssue(t(A,O)),M}),k=await Reflect.apply(f,this,F);return await y._def.returns._def.type.parseAsync(k,S).catch((O)=>{throw M.addIssue(T(k,O)),M})})}else{let y=this;return on(function(...A){let M=y._def.args.safeParse(A,S);if(!M.success)throw new $n([t(A,M.error)]);let F=Reflect.apply(f,this,M.data),k=y._def.returns.safeParse(F,S);if(!k.success)throw new $n([T(F,k.error)]);return k.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...o){return new jt({...this._def,args:hn.create(o).rest(St.create())})}returns(o){return new jt({...this._def,returns:o})}implement(o){return this.parse(o)}strictImplement(o){return this.parse(o)}static create(o,n,t){return new jt({args:o?o:hn.create([]).rest(St.create()),returns:n||St.create(),typeName:g.ZodFunction,...to(t)})}}class vt extends To{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})}}vt.create=(o,n)=>{return new vt({getter:o,typeName:g.ZodLazy,...to(n)})};class pt extends To{_parse(o){if(o.data!==this._def.value){let n=this._getOrReturnCtx(o);return C(n,{received:n.data,code:m.invalid_literal,expected:this._def.value}),u}return{status:"valid",value:o.data}}get value(){return this._def.value}}pt.create=(o,n)=>{return new pt({value:o,typeName:g.ZodLiteral,...to(n)})};function pk(o,n){return new At({values:o,typeName:g.ZodEnum,...to(n)})}class At extends To{constructor(){super(...arguments);zT.set(this,void 0)}_parse(o){if(typeof o.data!=="string"){let n=this._getOrReturnCtx(o),t=this._def.values;return C(n,{expected:$o.joinValues(t),received:n.parsedType,code:m.invalid_type}),u}if(!rS(this,zT,"f"))ck(this,zT,new Set(this._def.values),"f");if(!rS(this,zT,"f").has(o.data)){let n=this._getOrReturnCtx(o),t=this._def.values;return C(n,{received:n.data,code:m.invalid_enum_value,options:t}),u}return on(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 At.create(o,{...this._def,...n})}exclude(o,n=this._def){return At.create(this.options.filter((t)=>!o.includes(t)),{...this._def,...n})}}zT=new WeakMap;At.create=pk;class qt extends To{constructor(){super(...arguments);HT.set(this,void 0)}_parse(o){let n=$o.getValidEnumValues(this._def.values),t=this._getOrReturnCtx(o);if(t.parsedType!==I.string&&t.parsedType!==I.number){let T=$o.objectValues(n);return C(t,{expected:$o.joinValues(T),received:t.parsedType,code:m.invalid_type}),u}if(!rS(this,HT,"f"))ck(this,HT,new Set($o.getValidEnumValues(this._def.values)),"f");if(!rS(this,HT,"f").has(o.data)){let T=$o.objectValues(n);return C(t,{received:t.data,code:m.invalid_enum_value,options:T}),u}return on(o.data)}get enum(){return this._def.values}}HT=new WeakMap;qt.create=(o,n)=>{return new qt({values:o,typeName:g.ZodNativeEnum,...to(n)})};class Wt extends To{unwrap(){return this._def.type}_parse(o){let{ctx:n}=this._processInputParams(o);if(n.parsedType!==I.promise&&n.common.async===!1)return C(n,{code:m.invalid_type,expected:I.promise,received:n.parsedType}),u;let t=n.parsedType===I.promise?n.data:Promise.resolve(n.data);return on(t.then((T)=>{return this._def.type.parseAsync(T,{path:n.path,errorMap:n.common.contextualErrorMap})}))}}Wt.create=(o,n)=>{return new Wt({type:o,typeName:g.ZodPromise,...to(n)})};class Kn extends To{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),T=this._def.effect||null,S={addIssue:(f)=>{if(C(t,f),f.fatal)n.abort();else n.dirty()},get path(){return t.path}};if(S.addIssue=S.addIssue.bind(S),T.type==="preprocess"){let f=T.transform(t.data,S);if(t.common.async)return Promise.resolve(f).then(async(y)=>{if(n.value==="aborted")return u;let A=await this._def.schema._parseAsync({data:y,path:t.path,parent:t});if(A.status==="aborted")return u;if(A.status==="dirty")return It(A.value);if(n.value==="dirty")return It(A.value);return A});else{if(n.value==="aborted")return u;let y=this._def.schema._parseSync({data:f,path:t.path,parent:t});if(y.status==="aborted")return u;if(y.status==="dirty")return It(y.value);if(n.value==="dirty")return It(y.value);return y}}if(T.type==="refinement"){let f=(y)=>{let A=T.refinement(y,S);if(t.common.async)return Promise.resolve(A);if(A instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return y};if(t.common.async===!1){let y=this._def.schema._parseSync({data:t.data,path:t.path,parent:t});if(y.status==="aborted")return u;if(y.status==="dirty")n.dirty();return f(y.value),{status:n.value,value:y.value}}else return this._def.schema._parseAsync({data:t.data,path:t.path,parent:t}).then((y)=>{if(y.status==="aborted")return u;if(y.status==="dirty")n.dirty();return f(y.value).then(()=>{return{status:n.value,value:y.value}})})}if(T.type==="transform")if(t.common.async===!1){let f=this._def.schema._parseSync({data:t.data,path:t.path,parent:t});if(!mT(f))return f;let y=T.transform(f.value,S);if(y instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:y}}else return this._def.schema._parseAsync({data:t.data,path:t.path,parent:t}).then((f)=>{if(!mT(f))return f;return Promise.resolve(T.transform(f.value,S)).then((y)=>({status:n.value,value:y}))});$o.assertNever(T)}}Kn.create=(o,n,t)=>{return new Kn({schema:o,typeName:g.ZodEffects,effect:n,...to(t)})};Kn.createWithPreprocess=(o,n,t)=>{return new Kn({schema:n,effect:{type:"preprocess",transform:o},typeName:g.ZodEffects,...to(t)})};class rn extends To{_parse(o){if(this._getType(o)===I.undefined)return on(void 0);return this._def.innerType._parse(o)}unwrap(){return this._def.innerType}}rn.create=(o,n)=>{return new rn({innerType:o,typeName:g.ZodOptional,...to(n)})};class en extends To{_parse(o){if(this._getType(o)===I.null)return on(null);return this._def.innerType._parse(o)}unwrap(){return this._def.innerType}}en.create=(o,n)=>{return new en({innerType:o,typeName:g.ZodNullable,...to(n)})};class Zt extends To{_parse(o){let{ctx:n}=this._processInputParams(o),t=n.data;if(n.parsedType===I.undefined)t=this._def.defaultValue();return this._def.innerType._parse({data:t,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}Zt.create=(o,n)=>{return new Zt({innerType:o,typeName:g.ZodDefault,defaultValue:typeof n.default==="function"?n.default:()=>n.default,...to(n)})};class Pt extends To{_parse(o){let{ctx:n}=this._processInputParams(o),t={...n,common:{...n.common,issues:[]}},T=this._def.innerType._parse({data:t.data,path:t.path,parent:{...t}});if(QT(T))return T.then((S)=>{return{status:"valid",value:S.status==="valid"?S.value:this._def.catchValue({get error(){return new $n(t.common.issues)},input:t.data})}});else return{status:"valid",value:T.status==="valid"?T.value:this._def.catchValue({get error(){return new $n(t.common.issues)},input:t.data})}}removeCatch(){return this._def.innerType}}Pt.create=(o,n)=>{return new Pt({innerType:o,typeName:g.ZodCatch,catchValue:typeof n.catch==="function"?n.catch:()=>n.catch,...to(n)})};class BT extends To{_parse(o){if(this._getType(o)!==I.nan){let t=this._getOrReturnCtx(o);return C(t,{code:m.invalid_type,expected:I.nan,received:t.parsedType}),u}return{status:"valid",value:o.data}}}BT.create=(o)=>{return new BT({typeName:g.ZodNaN,...to(o)})};var wR=Symbol("zod_brand");class CS extends To{_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 CT extends To{_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 u;if(S.status==="dirty")return n.dirty(),It(S.value);else return this._def.out._parseAsync({data:S.value,path:t.path,parent:t})})();else{let T=this._def.in._parseSync({data:t.data,path:t.path,parent:t});if(T.status==="aborted")return u;if(T.status==="dirty")return n.dirty(),{status:"dirty",value:T.value};else return this._def.out._parseSync({data:T.value,path:t.path,parent:t})}}static create(o,n){return new CT({in:o,out:n,typeName:g.ZodPipeline})}}class et extends To{_parse(o){let n=this._def.innerType._parse(o),t=(T)=>{if(mT(T))T.value=Object.freeze(T.value);return T};return QT(n)?n.then((T)=>t(T)):t(n)}unwrap(){return this._def.innerType}}et.create=(o,n)=>{return new et({innerType:o,typeName:g.ZodReadonly,...to(n)})};function qk(o,n={},t){if(o)return Jt.create().superRefine((T,S)=>{var f,y;if(!o(T)){let A=typeof n==="function"?n(T):typeof n==="string"?{message:n}:n,M=(y=(f=A.fatal)!==null&&f!==void 0?f:t)!==null&&y!==void 0?y:!0,F=typeof A==="string"?{message:A}:A;S.addIssue({code:"custom",...F,fatal:M})}});return Jt.create()}var KR={object:Uo.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 XR=(o,n={message:`Input not instance of ${o.name}`})=>qk((t)=>t instanceof o,n),Zk=Un.create,Pk=ft.create,ER=BT.create,YR=yt.create,ek=Nt.create,GR=$t.create,zR=DT.create,HR=ht.create,mR=ct.create,QR=Jt.create,DR=St.create,UR=Nn.create,VR=UT.create,rR=Vn.create,LT=Uo.create,BR=Uo.strictCreate,CR=xt.create,LR=BS.create,IR=it.create,jR=hn.create,bR=VT.create,NR=rT.create,hR=Rt.create,cR=jt.create,xR=vt.create,iR=pt.create,vR=At.create,pR=qt.create,qR=Wt.create,Nk=Kn.create,ZR=rn.create,PR=en.create,eR=Kn.createWithPreprocess,lR=CT.create,gR=()=>Zk().optional(),dR=()=>Pk().optional(),uR=()=>ek().optional(),aR={string:(o)=>Un.create({...o,coerce:!0}),number:(o)=>ft.create({...o,coerce:!0}),boolean:(o)=>Nt.create({...o,coerce:!0}),bigint:(o)=>yt.create({...o,coerce:!0}),date:(o)=>$t.create({...o,coerce:!0})},sR=u,zo=Object.freeze({__proto__:null,defaultErrorMap:bt,setErrorMap:oR,getErrorMap:US,makeIssue:VS,EMPTY_PATH:nR,addIssueToContext:C,ParseStatus:lo,INVALID:u,DIRTY:It,OK:on,isAborted:ty,isDirty:Ty,isValid:mT,isAsync:QT,get util(){return $o},get objectUtil(){return ny},ZodParsedType:I,getParsedType:Tt,ZodType:To,datetimeRegex:vk,ZodString:Un,ZodNumber:ft,ZodBigInt:yt,ZodBoolean:Nt,ZodDate:$t,ZodSymbol:DT,ZodUndefined:ht,ZodNull:ct,ZodAny:Jt,ZodUnknown:St,ZodNever:Nn,ZodVoid:UT,ZodArray:Vn,ZodObject:Uo,ZodUnion:xt,ZodDiscriminatedUnion:BS,ZodIntersection:it,ZodTuple:hn,ZodRecord:VT,ZodMap:rT,ZodSet:Rt,ZodFunction:jt,ZodLazy:vt,ZodLiteral:pt,ZodEnum:At,ZodNativeEnum:qt,ZodPromise:Wt,ZodEffects:Kn,ZodTransformer:Kn,ZodOptional:rn,ZodNullable:en,ZodDefault:Zt,ZodCatch:Pt,ZodNaN:BT,BRAND:wR,ZodBranded:CS,ZodPipeline:CT,ZodReadonly:et,custom:qk,Schema:To,ZodSchema:To,late:KR,get ZodFirstPartyTypeKind(){return g},coerce:aR,any:QR,array:rR,bigint:YR,boolean:ek,date:GR,discriminatedUnion:LR,effect:Nk,enum:vR,function:cR,instanceof:XR,intersection:IR,lazy:xR,literal:iR,map:NR,nan:ER,nativeEnum:pR,never:UR,null:mR,nullable:PR,number:Pk,object:LT,oboolean:uR,onumber:dR,optional:ZR,ostring:gR,pipeline:lR,preprocess:eR,promise:qR,record:bR,set:hR,strictObject:BR,string:Zk,symbol:zR,transformer:Nk,tuple:jR,undefined:HR,union:CR,unknown:DR,void:VR,NEVER:sR,ZodIssueCode:m,quotelessJson:sJ,ZodError:$n});function lk(o){let n=o.runtimeEnvStrict??o.runtimeEnv??process.env;if(o.emptyStringAsUndefined??!1){for(let[K,U]of Object.entries(n))if(U==="")delete n[K]}if(!!o.skipValidation)return n;let S=typeof o.client==="object"?o.client:{},f=typeof o.server==="object"?o.server:{},y=typeof o.shared==="object"?o.shared:{},A=LT(S),M=LT(f),F=LT(y),k=o.isServer??(typeof window==="undefined"||("Deno"in window)),W=A.merge(F),O=M.merge(F).merge(A),E=k?O.safeParse(n):W.safeParse(n),Q=o.onValidationError??((K)=>{throw console.error("\u274C Invalid environment variables:",K.flatten().fieldErrors),new Error("Invalid environment variables")}),z=o.onInvalidAccess??((K)=>{throw new Error("\u274C Attempted to access a server-side environment variable on the client")});if(E.success===!1)return Q(E.error);let G=(K)=>{if(!o.clientPrefix)return!0;return!K.startsWith(o.clientPrefix)&&!(K in F.shape)},V=(K)=>{return k||!G(K)},x=(K)=>{return K==="__esModule"||K==="$$typeof"},c=(o.extends??[]).reduce((K,U)=>{return Object.assign(K,U)},{}),P=Object.assign(E.data,c);return new Proxy(P,{get(K,U){if(typeof U!=="string")return;if(x(U))return;if(!V(U))return z(U);return Reflect.get(K,U)}})}var o0="__vite_start_time"in globalThis,n0=typeof window!=="undefined",d7="vitest"in globalThis,Cn=lk({isServer:!o0&&!n0,server:{CI:zo.string().transform((o)=>!0).optional(),POSTGRES_USER:zo.string(),POSTGRES_PASSWORD:zo.string(),POSTGRES_DATABASE:zo.string(),POSTGRES_HOST:zo.string(),POSTGRES_PORT:zo.string().transform((o)=>Number.parseInt(o,10)),BACKEND_PORT:zo.string().transform((o)=>Number.parseInt(o,10)),RUN_WORKERS_FROM_SOURCE:zo.union([zo.literal("true"),zo.literal("false")]).optional().transform((o)=>o==="true"),FRONTEND_PORT:zo.string().transform((o)=>Number.parseInt(o,10)),FRONTEND_ORIGINS:zo.string().transform((o)=>JSON.parse(o)).pipe(zo.array(zo.string())),OPENAI_API_KEY:zo.string().optional()},clientPrefix:"VITE_",client:{VITE_BACKEND_ORIGIN:zo.string(),VITE_USE_SELF_SIGNED_CERTIFICATE:zo.union([zo.literal("true"),zo.literal("false")]).optional().transform((o)=>o==="true")},runtimeEnv:import.meta.env,emptyStringAsUndefined:!0});var dk=fy(import.meta.dirname,"../dev"),uk=Cn.VITE_USE_SELF_SIGNED_CERTIFICATE?{cert:gk(fy(dk,"./cert.pem"),"utf-8"),key:gk(fy(dk,"./key.pem"),"utf-8")}:void 0;import l0 from"path";import m0 from"os";import Q0 from"fs";var LS=new Map,yy=new Map,Ay=Symbol("OriginError"),lt={};class Xn extends Promise{constructor(o,n,t,T,S={}){let f,y;super((A,M)=>{f=A,y=M});this.tagged=Array.isArray(o.raw),this.strings=o,this.args=n,this.handler=t,this.canceller=T,this.options=S,this.state=null,this.statement=null,this.resolve=(A)=>(this.active=!1,f(A)),this.reject=(A)=>(this.active=!1,y(A)),this.active=!1,this.cancelled=null,this.executed=!1,this.signature="",this[Ay]=this.handler.debug?new Error:this.tagged&&t0(this.strings)}get origin(){return(this.handler.debug?this[Ay].stack:this.tagged&&yy.has(this.strings)?yy.get(this.strings):yy.set(this.strings,this[Ay].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 T=new Promise((S,f)=>{this.cursorFn=(y)=>{return S({value:y,done:!1}),new Promise((A)=>t=A)},this.resolve=()=>(this.active=!1,S({done:!0})),this.reject=(y)=>(this.active=!1,f(y))});return this.execute(),T},return(){return t&&t(lt),{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 t0(o){if(LS.has(o))return LS.get(o);let n=Error.stackTraceLimit;return Error.stackTraceLimit=4,LS.set(o,new Error),Error.stackTraceLimit=n,LS.get(o)}class gt extends Error{constructor(o){super(o.message);this.name=this.constructor.name,Object.assign(this,o)}}var Lo={connection:ak,postgres:sk,generic:o$,notSupported:n$};function ak(o,n,t){let{host:T,port:S}=t||n,f=Object.assign(new Error("write "+o+" "+(n.path||T+":"+S)),{code:o,errno:o,address:n.path||T},n.path?{}:{port:S});return Error.captureStackTrace(f,ak),f}function sk(o){let n=new gt(o);return Error.captureStackTrace(n,sk),n}function o$(o,n){let t=Object.assign(new Error(o+": "+n),{code:o});return Error.captureStackTrace(t,o$),t}function n$(o){let n=Object.assign(new Error(o+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:o});return Error.captureStackTrace(n,n$),n}var T0={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 bS{then(){My()}catch(){My()}finally(){My()}}class NT extends bS{constructor(o){super();this.value=cS(o)}}class cn extends bS{constructor(o,n,t){super();this.value=o,this.type=n,this.array=t}}class NS extends bS{constructor(o,n){super();this.first=o,this.rest=n}build(o,n,t,T){let S=S0.map(([f,y])=>({fn:y,i:o.search(f)})).sort((f,y)=>f.i-y.i).pop();return S.i===-1?Ry(this.first,T):S.fn(this.first,this.rest,n,t,T)}}function hS(o,n,t,T){let S=o instanceof cn?o.value:o;if(S===void 0){if(o instanceof cn?o.value=T.transform.undefined:S=o=T.transform.undefined,S===void 0)throw Lo.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||f$(o.value):o.type):(n.push(o),jS(o)))}var T$=A$(T0);function $y(o,n,t,T,S,f){for(let y=1;y<o.strings.length;y++)n+=Jy(n,t,T,S,f)+o.strings[y],t=o.args[y];return n}function Jy(o,n,t,T,S){return n instanceof NS?n.build(o,t,T,S):n instanceof Xn?ky(n,t,T,S):n instanceof NT?n.value:n&&n[0]instanceof Xn?n.reduce((f,y)=>f+" "+ky(y,t,T,S),""):hS(n,t,T,S)}function ky(o,n,t,T){return o.fragment=!0,$y(o,o.strings[0],o.args[0],n,t,T)}function S$(o,n,t,T,S){return o.map((f)=>"("+T.map((y)=>Jy("values",f[y],n,t,S)).join(",")+")").join(",")}function t$(o,n,t,T,S){let f=Array.isArray(o[0]),y=n.length?n.flat():Object.keys(f?o[0]:o);return S$(f?o:[o],t,T,y,S)}function IS(o,n,t,T,S){if(typeof o==="string"&&(o=[o].concat(n)),Array.isArray(o))return Ry(o,S);let f;return(n.length?n.flat():Object.keys(o)).map((A)=>{return f=o[A],(f instanceof Xn?ky(f,t,T,S):f instanceof NT?f.value:hS(f,t,T,S))+" as "+cS(S.transform.column.to?S.transform.column.to(A):A)}).join(",")}var S0=Object.entries({values:t$,in:(...o)=>{let n=t$(...o);return n==="()"?"(null)":n},select:IS,as:IS,returning:IS,"\\(":IS,update(o,n,t,T,S){return(n.length?n.flat():Object.keys(o)).map((f)=>cS(S.transform.column.to?S.transform.column.to(f):f)+"="+Jy("values",o[f],t,T,S))},insert(o,n,t,T,S){let f=n.length?n.flat():Object.keys(Array.isArray(o)?o[0]:o);return"("+Ry(f,S)+")values"+S$(Array.isArray(o)?o:[o],t,T,f,S)}}).map(([o,n])=>[new RegExp("((?:^|[\\s(])"+o+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),n]);function My(){throw Lo.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}var{serializers:f0,parsers:y0}=T$;function f$(o){if(Array.isArray(o))return f$(o[0]);return typeof o==="string"?1009:0}var y$=function(o){let n=A$(o||{});return{serializers:Object.assign({},f0,n.serializers),parsers:Object.assign({},y0,n.parsers)}};function A$(o){return Object.keys(o).reduce((n,t)=>{if(o[t].from&&[].concat(o[t].from).forEach((T)=>n.parsers[T]=o[t].parse),o[t].serialize)n.serializers[o[t].to]=o[t].serialize,o[t].from&&[].concat(o[t].from).forEach((T)=>n.serializers[T]=o[t].serialize);return n},{parsers:{},serializers:{}})}function Ry(o,{transform:{column:n}}){return o.map((t)=>cS(n.to?n.to(t):t)).join(",")}var cS=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},A0=/\\/g,M0=/"/g;function F0(o){return o.replace(A0,"\\\\").replace(M0,'\\"')}var M$=function o(n,t,T,S){if(Array.isArray(n)===!1)return n;if(!n.length)return"{}";let f=n[0],y=S===1020?";":",";if(Array.isArray(f)&&!f.type)return"{"+n.map((A)=>o(A,t,T,S)).join(y)+"}";return"{"+n.map((A)=>{if(A===void 0){if(A=T.transform.undefined,A===void 0)throw Lo.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return A===null?"null":'"'+F0(t?t(A.type?A.value:A):""+A)+'"'}).join(y)+"}"},Fy={i:0,char:null,str:"",quoted:!1,last:0},F$=function o(n,t,T){return Fy.i=Fy.last=0,k$(Fy,n,t,T)};function k$(o,n,t,T){let S=[],f=T===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(k$(o,n,t,T));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===f&&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},_t=(o)=>{let n=o[0].toUpperCase();for(let t=1;t<o.length;t++)n+=o[t]==="_"?o[++t].toUpperCase():o[t];return n},wt=(o)=>o.replace(/_/g,"-"),IT=(o)=>o.replace(/([A-Z])/g,"_$1").toLowerCase(),jT=(o)=>(o.slice(0,1)+o.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),bT=(o)=>o.replace(/-/g,"_");function Wy(o){return function n(t,T){return typeof t==="object"&&t!==null&&(T.type===114||T.type===3802)?Array.isArray(t)?t.map((S)=>n(S,T)):Object.entries(t).reduce((S,[f,y])=>Object.assign(S,{[o(f)]:n(y,T)}),{}):t}}Ot.column={from:Ot};Ot.value={from:Wy(Ot)};IT.column={to:IT};var Oy={...Ot};Oy.column.to=IT;_t.column={from:_t};_t.value={from:Wy(_t)};jT.column={to:jT};var _y={..._t};_y.column.to=jT;wt.column={from:wt};wt.value={from:Wy(wt)};bT.column={to:bT};var wy={...wt};wy.column.to=bT;import $$ from"net";import R0 from"tls";import hT from"crypto";import Ky from"stream";import{performance as J$}from"perf_hooks";class Kt 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 Jn=k0;function k0(o=[]){let n=o.slice(),t=0;return{get length(){return n.length-t},remove:(T)=>{let S=n.indexOf(T);return S===-1?null:(n.splice(S,1),T)},push:(T)=>(n.push(T),T),shift:()=>{let T=n[t++];if(t===n.length)t=0,n=[];else n[t-1]=void 0;return T}}}var go=Buffer.allocUnsafe(256),$0="BCcDdEFfHPpQSX".split("").reduce((o,n)=>{let t=n.charCodeAt(0);return o[n]=()=>{return go[0]=t,Wo.i=5,Wo},o},{}),Wo=Object.assign(J0,$0,{N:String.fromCharCode(0),i:0,inc(o){return Wo.i+=o,Wo},str(o){let n=Buffer.byteLength(o);return xS(n),Wo.i+=go.write(o,Wo.i,n,"utf8"),Wo},i16(o){return xS(2),go.writeUInt16BE(o,Wo.i),Wo.i+=2,Wo},i32(o,n){if(n||n===0)return go.writeUInt32BE(o,n),Wo;return xS(4),go.writeUInt32BE(o,Wo.i),Wo.i+=4,Wo},z(o){return xS(o),go.fill(0,Wo.i,Wo.i+o),Wo.i+=o,Wo},raw(o){return go=Buffer.concat([go.subarray(0,Wo.i),o]),Wo.i=go.length,Wo},end(o=1){go.writeUInt32BE(Wo.i-o,o);let n=go.subarray(0,Wo.i);return Wo.i=0,go=Buffer.allocUnsafe(256),n}}),Z=Wo;function xS(o){if(go.length-Wo.i<o){let n=go,t=n.length;go=Buffer.allocUnsafe(t+(t>>1)+o),n.copy(go)}}function J0(){return Wo.i=0,Wo}var Yy=O$,W0=1,Mt=Z().S().end(),R$=Z().H().end(),O0=Z().i32(8).i32(80877103).end(8),_0=Buffer.concat([Z().E().str(Z.N).i32(0).end(),Mt]),w0=Z().D().str("S").str(Z.N).end(),dt=()=>{},K0=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),X0={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 O$(o,n={},{onopen:t=dt,onend:T=dt,onclose:S=dt}={}){let{ssl:f,max:y,user:A,host:M,port:F,database:k,parsers:W,transform:O,onnotice:E,onnotify:Q,onparameter:z,max_pipeline:G,keep_alive:V,backoff:x,target_session_attrs:c}=o,P=Jn(),Y=W0++,K={pid:null,secret:null},U=Ey(aS,o.idle_timeout),p=Ey(aS,o.max_lifetime),b=Ey(c$,o.connect_timeout),w=null,v,j=new Kt,a=Buffer.alloc(0),oo=o.fetch_types,no={},_o={},An=Math.random().toString(36).slice(2),H=1,i=0,fo=0,Ro=0,Io=0,So=0,wo=0,Co=0,mo=null,Eo=null,vo=!1,Ko=null,Yn=null,po=null,ln=null,jo=null,Yo=null,Gn=null,Ln=null,B=null,oT=null,qo={queue:n.closed,idleTimer:U,connect($){po=$||!0,ly()},terminate:tT,execute:nT,cancel:j$,end:aS,count:0,id:Y};return n.closed&&n.closed.push(qo),qo;async function I$(){let $;try{$=o.socket?await Promise.resolve(o.socket(o)):new $$.Socket}catch(_){Gt(_);return}return $.on("error",Gt),$.on("close",gy),$.on("drain",Py),$}async function j$({pid:$,secret:_},e,Jo){try{v=Z().i32(16).i32(80877102).i32($).i32(_).end(16),await ey(),w.once("error",Jo),w.once("close",e)}catch(Vo){Jo(Vo)}}function nT($){if(vo)return ZT($,Lo.connection("CONNECTION_DESTROYED",o));if($.cancelled)return;try{return $.state=K,B?P.push($):(B=$,B.active=!0),h$($),co(b$($))&&!$.describeFirst&&!$.cursorFn&&P.length<G&&(!$.options.onexecute||$.options.onexecute(qo))}catch(_){return P.length===0&&co(Mt),In(_),!0}}function b$($){if($.parameters.length>=65534)throw Lo.generic("MAX_PARAMETERS_EXCEEDED","Max number of parameters (65534) exceeded");return $.options.simple?Z().Q().str($.statement.string+Z.N).end():$.describeFirst?Buffer.concat([py($),R$]):$.prepare?$.prepared?qT($):Buffer.concat([py($),qT($)]):N$($)}function py($){return Buffer.concat([uy($.statement.string,$.parameters,$.statement.types,$.statement.name),zJ("S",$.statement.name)])}function qT($){return Buffer.concat([GJ($.parameters,$.statement.types,$.statement.name,$.cursorName),$.cursorFn?ay("",$.cursorRows):_0])}function N$($){return Buffer.concat([uy($.statement.string,$.parameters,$.statement.types),w0,qT($)])}function h$($){let _=[],e=[],Jo=$y($,$.strings[0],$.args[0],_,e,o);!$.tagged&&$.args.forEach((Vo)=>hS(Vo,_,e,o)),$.prepare=o.prepare&&("prepare"in $.options?$.options.prepare:!0),$.string=Jo,$.signature=$.prepare&&e+Jo,$.onlyDescribe&&delete _o[$.signature],$.parameters=$.parameters||_,$.prepared=$.prepare&&$.signature in _o,$.describeFirst=$.onlyDescribe||_.length&&!$.prepared,$.statement=$.prepared?_o[$.signature]:{string:Jo,types:e,name:$.prepare?An+H++:""},typeof o.debug==="function"&&o.debug(Y,Jo,_,e)}function co($,_){if(Yo=Yo?Buffer.concat([Yo,$]):Buffer.from($),_||Yo.length>=1024)return qy(_);return Eo===null&&(Eo=setImmediate(qy)),!0}function qy($){let _=w.write(Yo,$);return Eo!==null&&clearImmediate(Eo),Yo=Eo=null,_}function c$(){In(Lo.connection("CONNECT_TIMEOUT",o,w)),w.destroy()}async function Zy(){if(co(O0),!await new Promise((_)=>w.once("data",(e)=>_(e[0]===83)))&&f==="prefer")return Yt();w.removeAllListeners(),w=R0.connect({socket:w,servername:$$.isIP(w.host)?void 0:w.host,...f==="require"||f==="allow"||f==="prefer"?{rejectUnauthorized:!1}:f==="verify-full"?{}:typeof f==="object"?f:{}}),w.on("secureConnect",Yt),w.on("error",Gt),w.on("close",gy),w.on("drain",Py)}function Py(){!B&&t(qo)}function uS($){if(Ko){if(Ko.push($),fo-=$.length,fo>=0)return}a=Ko?Buffer.concat(Ko,So-fo):a.length===0?$:Buffer.concat([a,$],a.length+$.length);while(a.length>4){if(So=a.readUInt32BE(1),So>=a.length){fo=So-a.length,Ko=[a];break}try{x$(a.subarray(0,So+1))}catch(_){B&&(B.cursorFn||B.describeFirst)&&co(Mt),In(_)}a=a.subarray(So+1),fo=0,Ko=null}}async function ey(){if(vo=!1,no={},w||(w=await I$()),!w)return;if(b.start(),o.socket)return f?Zy():Yt();if(w.on("connect",f?Zy:Yt),o.path)return w.connect(o.path);w.ssl=f,w.connect(F[Ro],M[Ro]),w.host=M[Ro],w.port=F[Ro],Ro=(Ro+1)%F.length}function ly(){setTimeout(ey,i?i+wo-J$.now():0)}function Yt(){try{_o={},oo=o.fetch_types,An=Math.random().toString(36).slice(2),H=1,p.start(),w.on("data",uS),V&&w.setKeepAlive&&w.setKeepAlive(!0,1000*V);let $=mJ();co($)}catch($){Gt($)}}function Gt($){if(qo.queue===n.connecting&&o.host[Io+1])return;In($);while(P.length)ZT(P.shift(),$)}function In($){jo&&(jo.destroy($),jo=null),B&&ZT(B,$),po&&(ZT(po,$),po=null)}function ZT($,_){"query"in _||"parameters"in _||Object.defineProperties(_,{stack:{value:_.stack+$.origin.replace(/.*\n/,"\n"),enumerable:o.debug},query:{value:$.string,enumerable:o.debug},parameters:{value:$.parameters,enumerable:o.debug},args:{value:$.args,enumerable:o.debug},types:{value:$.statement&&$.statement.types,enumerable:o.debug}}),$.reject(_)}function aS(){return ln||(!qo.reserved&&T(qo),!qo.reserved&&!po&&!B&&P.length===0?(tT(),new Promise(($)=>w&&w.readyState!=="closed"?w.once("close",$):$())):ln=new Promise(($)=>Gn=$))}function tT(){if(vo=!0,jo||B||po||P.length)Gt(Lo.connection("CONNECTION_DESTROYED",o));if(clearImmediate(Eo),w)w.removeListener("data",uS),w.removeListener("connect",Yt),w.readyState==="open"&&w.end(Z().X().end());Gn&&(Gn(),ln=Gn=null)}async function gy($){if(a=Buffer.alloc(0),fo=0,Ko=null,clearImmediate(Eo),w.removeListener("data",uS),w.removeListener("connect",Yt),U.cancel(),p.cancel(),b.cancel(),w.removeAllListeners(),w=null,po)return ly();!$&&(B||P.length)&&Gt(Lo.connection("CONNECTION_CLOSED",o,w)),i=J$.now(),$&&o.shared.retries++,wo=(typeof x==="function"?x(o.shared.retries):x)*1000,S(qo,Lo.connection("CONNECTION_CLOSED",o,w))}function x$($,_=$[0]){(_===68?i$:_===100?WJ:_===65?MJ:_===83?v$:_===90?p$:_===67?q$:_===50?dy:_===49?Z$:_===116?P$:_===84?e$:_===82?l$:_===110?oJ:_===75?nJ:_===69?yJ:_===115?FJ:_===51?kJ:_===71?$J:_===78?_J:_===72?JJ:_===99?OJ:_===73?wJ:_===86?KJ:_===118?XJ:_===87?RJ:EJ)($)}function i$($){let _=7,e,Jo,Vo,Zo=B.isRaw?new Array(B.statement.columns.length):{};for(let uo=0;uo<B.statement.columns.length;uo++)Jo=B.statement.columns[uo],e=$.readInt32BE(_),_+=4,Vo=e===-1?null:B.isRaw===!0?$.subarray(_,_+=e):Jo.parser===void 0?$.toString("utf8",_,_+=e):Jo.parser.array===!0?Jo.parser($.toString("utf8",_+1,_+=e)):Jo.parser($.toString("utf8",_,_+=e)),B.isRaw?Zo[uo]=B.isRaw===!0?Vo:O.value.from?O.value.from(Vo,Jo):Vo:Zo[Jo.name]=O.value.from?O.value.from(Vo,Jo):Vo;B.forEachFn?B.forEachFn(O.row.from?O.row.from(Zo):Zo,j):j[Co++]=O.row.from?O.row.from(Zo):Zo}function v$($){let[_,e]=$.toString("utf8",5,$.length-1).split(Z.N);if(no[_]=e,o.parameters[_]!==e)o.parameters[_]=e,z&&z(_,e)}function p$($){if(B&&B.options.simple&&B.resolve(Yn||j),B=Yn=null,j=new Kt,b.cancel(),po){if(c){if(!no.in_hot_standby||!no.default_transaction_read_only)return fJ();else if(SJ(c,no))return tT()}if(oo)return po===!0&&(po=null),tJ();po!==!0&&nT(po),o.shared.retries=Io=0,po=null;return}while(P.length&&(B=P.shift())&&(B.active=!0,B.cancelled))O$(o).cancel(B.state,B.cancelled.resolve,B.cancelled.reject);if(B)return;qo.reserved?!qo.reserved.release&&$[5]===73?ln?tT():(qo.reserved=null,t(qo)):qo.reserved():ln?tT():t(qo)}function q$($){Co=0;for(let _=$.length-1;_>0;_--){if($[_]===32&&$[_+1]<58&&j.count===null)j.count=+$.toString("utf8",_+1,$.length-1);if($[_-1]>=65){j.command=$.toString("utf8",5,_),j.state=K;break}}if(oT&&(oT(),oT=null),j.command==="BEGIN"&&y!==1&&!qo.reserved)return In(Lo.generic("UNSAFE_TRANSACTION","Only use sql.begin, sql.reserved or max: 1"));if(B.options.simple)return dy();if(B.cursorFn)j.count&&B.cursorFn(j),co(Mt);B.resolve(j)}function Z$(){B.parsing=!1}function dy(){!j.statement&&(j.statement=B.statement),j.columns=B.statement.columns}function P$($){let _=$.readUInt16BE(5);for(let e=0;e<_;++e)!B.statement.types[e]&&(B.statement.types[e]=$.readUInt32BE(7+e*4));B.prepare&&(_o[B.signature]=B.statement),B.describeFirst&&!B.onlyDescribe&&(co(qT(B)),B.describeFirst=!1)}function e$($){if(j.command)Yn=Yn||[j],Yn.push(j=new Kt),j.count=null,B.statement.columns=null;let _=$.readUInt16BE(5),e=7,Jo;B.statement.columns=Array(_);for(let Vo=0;Vo<_;++Vo){Jo=e;while($[e++]!==0);let Zo=$.readUInt32BE(e),uo=$.readUInt16BE(e+4),gn=$.readUInt32BE(e+6);B.statement.columns[Vo]={name:O.column.from?O.column.from($.toString("utf8",Jo,e-1)):$.toString("utf8",Jo,e-1),parser:W[gn],table:Zo,number:uo,type:gn},e+=18}if(j.statement=B.statement,B.onlyDescribe)return B.resolve(B.statement),co(Mt)}async function l$($,_=$.readUInt32BE(5)){(_===3?g$:_===5?d$:_===10?u$:_===11?a$:_===12?s$:_!==0?YJ:dt)($,_)}async function g$(){let $=await sS();co(Z().p().str($).z(1).end())}async function d$($){let _="md5"+await W$(Buffer.concat([Buffer.from(await W$(await sS()+A)),$.subarray(9)]));co(Z().p().str(_).z(1).end())}async function u$(){Ln=(await hT.randomBytes(18)).toString("base64"),Z().p().str("SCRAM-SHA-256"+Z.N);let $=Z.i;co(Z.inc(4).str("n,,n=*,r="+Ln).i32(Z.i-$-4,$).end())}async function a$($){let _=$.toString("utf8",9).split(",").reduce((uo,gn)=>(uo[gn[0]]=gn.slice(2),uo),{}),e=await hT.pbkdf2Sync(await sS(),Buffer.from(_.s,"base64"),parseInt(_.i),32,"sha256"),Jo=await iS(e,"Client Key"),Vo="n=*,r="+Ln+",r="+_.r+",s="+_.s+",i="+_.i+",c=biws,r="+_.r;mo=(await iS(await iS(e,"Server Key"),Vo)).toString("base64");let Zo="c=biws,r="+_.r+",p="+Y0(Jo,Buffer.from(await iS(await E0(Jo),Vo))).toString("base64");co(Z().p().str(Zo).end())}function s$($){if($.toString("utf8",9).split(Z.N,1)[0].slice(2)===mo)return;In(Lo.generic("SASL_SIGNATURE_MISMATCH","The server did not return the correct signature")),w.destroy()}function sS(){return Promise.resolve(typeof o.pass==="function"?o.pass():o.pass)}function oJ(){if(j.statement=B.statement,j.statement.columns=[],B.onlyDescribe)return B.resolve(B.statement),co(Mt)}function nJ($){K.pid=$.readUInt32BE(5),K.secret=$.readUInt32BE(9)}async function tJ(){oo=!1,(await new Xn([`
4
4
  select b.oid, b.typarray
5
5
  from pg_catalog.pg_type a
6
6
  left join pg_catalog.pg_type b on b.oid = a.typelem
7
7
  where a.typcategory = 'A'
8
8
  group by b.oid, b.typarray
9
9
  order by b.oid
10
- `],[],nT)).forEach(({oid:_,typarray:e})=>tJ(_,e))}function tJ($,_){if(!!o.parsers[_]&&!!o.serializers[_])return;let e=o.parsers[$];o.shared.typeArrayMap[$]=_,o.parsers[_]=(Jo)=>F$(Jo,e,_),o.parsers[_].array=!0,o.serializers[_]=(Jo)=>M$(Jo,o.serializers[$],o,_)}function TJ($,_){return $==="read-write"&&_.default_transaction_read_only==="on"||$==="read-only"&&_.default_transaction_read_only==="off"||$==="primary"&&_.in_hot_standby==="on"||$==="standby"&&_.in_hot_standby==="off"||$==="prefer-standby"&&_.in_hot_standby==="off"&&o.host[Io]}function SJ(){let $=new Xn([`
10
+ `],[],nT)).forEach(({oid:_,typarray:e})=>TJ(_,e))}function TJ($,_){if(!!o.parsers[_]&&!!o.serializers[_])return;let e=o.parsers[$];o.shared.typeArrayMap[$]=_,o.parsers[_]=(Jo)=>F$(Jo,e,_),o.parsers[_].array=!0,o.serializers[_]=(Jo)=>M$(Jo,o.serializers[$],o,_)}function SJ($,_){return $==="read-write"&&_.default_transaction_read_only==="on"||$==="read-only"&&_.default_transaction_read_only==="off"||$==="primary"&&_.in_hot_standby==="on"||$==="standby"&&_.in_hot_standby==="off"||$==="prefer-standby"&&_.in_hot_standby==="off"&&o.host[Io]}function fJ(){let $=new Xn([`
11
11
  show transaction_read_only;
12
12
  select pg_catalog.pg_is_in_recovery()
13
- `],[],nT,null,{simple:!0});$.resolve=([[_],[e]])=>{no.default_transaction_read_only=_.transaction_read_only,no.in_hot_standby=e.pg_is_in_recovery?"on":"off"},$.execute()}function fJ($){B&&(B.cursorFn||B.describeFirst)&&co(Mt);let _=Lo.postgres(Xy($));B&&B.retried?In(B.retried):B&&B.prepared&&w0.has(_.routine)?yJ(B,_):In(_)}function yJ($,_){delete _o[$.signature],$.retried=_,nT($)}function AJ($){if(!Q)return;let _=9;while($[_++]!==0);Q($.toString("utf8",9,_-1),$.toString("utf8",_,$.length-1))}async function MJ(){try{let $=await Promise.resolve(B.cursorFn(j));Co=0,$===lt?co(zJ(B.portal)):(j=new Kt,co(ay("",B.cursorRows)))}catch($){co(Mt),B.reject($)}}function FJ(){j.count&&B.cursorFn(j),B.resolve(j)}function kJ(){jo=new Ky.Writable({autoDestroy:!0,write($,_,e){w.write(Z().d().raw($).end(),e)},destroy($,_){_($),w.write(Z().f().str($+Z.N).end()),jo=null},final($){w.write(Z().c().end()),oT=$}}),B.resolve(jo)}function $J(){jo=new Ky.Readable({read(){w.resume()}}),B.resolve(jo)}function JJ(){jo=new Ky.Duplex({autoDestroy:!0,read(){w.resume()},write($,_,e){w.write(Z().d().raw($).end(),e)},destroy($,_){_($),w.write(Z().f().str($+Z.N).end()),jo=null},final($){w.write(Z().c().end()),oT=$}}),B.resolve(jo)}function RJ($){jo&&(jo.push($.subarray(5))||w.pause())}function WJ(){jo&&jo.push(null),jo=null}function OJ($){E?E(Xy($)):console.log(Xy($))}function _J(){}function wJ(){In(Lo.notSupported("FunctionCallResponse"))}function KJ(){In(Lo.notSupported("NegotiateProtocolVersion"))}function XJ($){console.error("Postgres.js : Unknown Message:",$[0])}function EJ($,_){console.error("Postgres.js : Unknown Auth:",_)}function YJ($,_,e="",Jo=""){let Vo,Zo;return Z().B().str(Jo+Z.N).str(e+Z.N).i16(0).i16($.length),$.forEach((uo,gn)=>{if(uo===null)return Z.i32(4294967295);Zo=_[gn],$[gn]=uo=Zo in o.serializers?o.serializers[Zo](uo):""+uo,Vo=Z.i,Z.inc(4).str(uo).i32(Z.i-Vo-4,Vo)}),Z.i16(0),Z.end()}function uy($,_,e,Jo=""){return Z().P().str(Jo+Z.N).str($+Z.N).i16(_.length),_.forEach((Vo,Zo)=>Z.i32(e[Zo]||0)),Z.end()}function GJ($,_=""){return Z().D().str($).str(_+Z.N).end()}function ay($="",_=0){return Buffer.concat([Z().E().str($+Z.N).i32(_).end(),R$])}function zJ($=""){return Buffer.concat([Z().C().str("P").str($+Z.N).end(),Z().S().end()])}function HJ(){return v||Z().inc(4).i16(3).z(2).str(Object.entries(Object.assign({user:A,database:k,client_encoding:"UTF8"},o.connection)).filter(([,$])=>$).map(([$,_])=>$+Z.N+_).join(Z.N)).z(2).end(0)}}function Xy(o){let n={},t=5;for(let T=5;T<o.length-1;T++)if(o[T]===0)n[K0[o[t]]]=o.toString("utf8",t+1,T),t=T+1;return n}function W$(o){return hT.createHash("md5").update(o).digest("hex")}function iS(o,n){return hT.createHmac("sha256",o).update(n).digest()}function X0(o){return hT.createHash("sha256").update(o).digest()}function E0(o,n){let t=Math.max(o.length,n.length),T=Buffer.allocUnsafe(t);for(let S=0;S<t;S++)T[S]=o[S]^n[S];return T}function Ey(o,n){if(n=typeof n==="function"?n():n,!n)return{cancel:dt,start:dt};let t;return{cancel(){t&&(clearTimeout(t),t=null)},start(){t&&clearTimeout(t),t=setTimeout(T,n*1000,arguments)}};function T(S){o.apply(null,S),t=null}}var _$=()=>{};function Gy(o,n){let t=new Map,T="postgresjs_"+Math.random().toString(36).slice(2),S={},f,y,A=!1,M=W.sql=o({...n,transform:{column:{},value:{},row:{}},max:1,fetch_types:!1,idle_timeout:null,max_lifetime:null,connection:{...n.connection,replication:"database"},onclose:async function(){if(A)return;y=null,S.pid=S.secret=void 0,O(await E(M,T,n.publications)),t.forEach((z)=>z.forEach(({onsubscribe:G})=>G()))},no_subscribe:!0}),F=M.end,k=M.close;return M.end=async()=>{return A=!0,y&&await new Promise((z)=>(y.once("close",z),y.end())),F()},M.close=async()=>{return y&&await new Promise((z)=>(y.once("close",z),y.end())),k()},W;async function W(z,G,V=_$,x=_$){if(z=z0(z),!f)f=E(M,T,n.publications);let c={fn:G,onsubscribe:V},P=t.has(z)?t.get(z).add(c):t.set(z,new Set([c])).get(z),Y=()=>{P.delete(c),P.size===0&&t.delete(z)};return f.then((K)=>{return O(K),V(),y&&y.on("error",x),{unsubscribe:Y,state:S,sql:M}})}function O(z){y=z.stream,S.pid=z.state.pid,S.secret=z.state.secret}async function E(z,G,V){if(!V)throw new Error("Missing publication names");let x=await z.unsafe(`CREATE_REPLICATION_SLOT ${G} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT`),[c]=x,P=await z.unsafe(`START_REPLICATION SLOT ${G} LOGICAL ${c.consistent_point} (proto_version '1', publication_names '${V}')`).writable(),Y={lsn:Buffer.concat(c.consistent_point.split("/").map((w)=>Buffer.from(("00000000"+w).slice(-8),"hex")))};return P.on("data",U),P.on("error",K),P.on("close",z.close),{stream:P,state:x.state};function K(w){console.error("Unexpected error during logical streaming - reconnecting",w)}function U(w){if(w[0]===119)G0(w.subarray(25),Y,z.options.parsers,p,n.transform);else if(w[0]===107&&w[17])Y.lsn=w.subarray(1,9),b()}function p(w,v){let j=v.relation.schema+"."+v.relation.table;Q("*",w,v),Q("*:"+j,w,v),v.relation.keys.length&&Q("*:"+j+"="+v.relation.keys.map((a)=>w[a.name]),w,v),Q(v.command,w,v),Q(v.command+":"+j,w,v),v.relation.keys.length&&Q(v.command+":"+j+"="+v.relation.keys.map((a)=>w[a.name]),w,v)}function b(){let w=Buffer.alloc(34);w[0]="r".charCodeAt(0),w.fill(Y.lsn,1),w.writeBigInt64BE(BigInt(Date.now()-Date.UTC(2000,0,1))*BigInt(1000),25),P.write(w)}}function Q(z,G,V){t.has(z)&&t.get(z).forEach(({fn:x})=>x(G,V,z))}}function Y0(o){return new Date(Date.UTC(2000,0,1)+Number(o/BigInt(1000)))}function G0(o,n,t,T,S){let f=(y,[A,M])=>(y[A.charCodeAt(0)]=M,y);Object.entries({R:(y)=>{let A=1,M=n[y.readUInt32BE(A)]={schema:y.toString("utf8",A+=4,A=y.indexOf(0,A))||"pg_catalog",table:y.toString("utf8",A+1,A=y.indexOf(0,A+1)),columns:Array(y.readUInt16BE(A+=2)),keys:[]};A+=2;let F=0,k;while(A<y.length)k=M.columns[F++]={key:y[A++],name:S.column.from?S.column.from(y.toString("utf8",A,A=y.indexOf(0,A))):y.toString("utf8",A,A=y.indexOf(0,A)),type:y.readUInt32BE(A+=1),parser:t[y.readUInt32BE(A)],atttypmod:y.readUInt32BE(A+=4)},k.key&&M.keys.push(k),A+=4},Y:()=>{},O:()=>{},B:(y)=>{n.date=Y0(y.readBigInt64BE(9)),n.lsn=y.subarray(1,9)},I:(y)=>{let A=1,M=n[y.readUInt32BE(A)],{row:F}=vS(y,M.columns,A+=7,S);T(F,{command:"insert",relation:M})},D:(y)=>{let A=1,M=n[y.readUInt32BE(A)];A+=4;let F=y[A]===75;T(F||y[A]===79?vS(y,M.columns,A+=3,S).row:null,{command:"delete",relation:M,key:F})},U:(y)=>{let A=1,M=n[y.readUInt32BE(A)];A+=4;let F=y[A]===75,k=F||y[A]===79?vS(y,M.columns,A+=3,S):null;k&&(A=k.i);let{row:W}=vS(y,M.columns,A+3,S);T(W,{command:"update",relation:M,key:F,old:k&&k.row})},T:()=>{},C:()=>{}}).reduce(f,{})[o[0]](o)}function vS(o,n,t,T){let S,f,y,A=T.raw?new Array(n.length):{};for(let M=0;M<n.length;M++)S=o[t++],f=n[M],y=S===110?null:S===117?void 0:f.parser===void 0?o.toString("utf8",t+4,t+=4+o.readUInt32BE(t)):f.parser.array===!0?f.parser(o.toString("utf8",t+5,t+=4+o.readUInt32BE(t))):f.parser(o.toString("utf8",t+4,t+=4+o.readUInt32BE(t))),T.raw?A[M]=T.raw===!0?y:T.value.from?T.value.from(y,f):y:A[f.name]=T.value.from?T.value.from(y,f):y;return{i:t,row:T.row.from?T.row.from(A):A}}function z0(o){let n=o.match(/^(\*|insert|update|delete)?:?([^.]+?\.?[^=]+)?=?(.+)?/i)||[];if(!n)throw new Error("Malformed subscribe pattern: "+o);let[,t,T,S]=n;return(t||"*")+(T?":"+(T.indexOf(".")===-1?"public."+T:T):"")+(S?"="+S:"")}import w$ from"stream";function zy(o,n,t=393216){return new Promise(async(T,S)=>{await o.begin(async(f)=>{let y;!n&&([{oid:n}]=await f`select lo_creat(-1) as oid`);let[{fd:A}]=await f`select lo_open(${n}, ${t}) as fd`,M={writable:k,readable:F,close:()=>f`select lo_close(${A})`.then(y),tell:()=>f`select lo_tell64(${A})`,read:(W)=>f`select loread(${A}, ${W}) as data`,write:(W)=>f`select lowrite(${A}, ${W})`,truncate:(W)=>f`select lo_truncate64(${A}, ${W})`,seek:(W,O=0)=>f`select lo_lseek64(${A}, ${W}, ${O})`,size:()=>f`
13
+ `],[],nT,null,{simple:!0});$.resolve=([[_],[e]])=>{no.default_transaction_read_only=_.transaction_read_only,no.in_hot_standby=e.pg_is_in_recovery?"on":"off"},$.execute()}function yJ($){B&&(B.cursorFn||B.describeFirst)&&co(Mt);let _=Lo.postgres(Xy($));B&&B.retried?In(B.retried):B&&B.prepared&&K0.has(_.routine)?AJ(B,_):In(_)}function AJ($,_){delete _o[$.signature],$.retried=_,nT($)}function MJ($){if(!Q)return;let _=9;while($[_++]!==0);Q($.toString("utf8",9,_-1),$.toString("utf8",_,$.length-1))}async function FJ(){try{let $=await Promise.resolve(B.cursorFn(j));Co=0,$===lt?co(HJ(B.portal)):(j=new Kt,co(ay("",B.cursorRows)))}catch($){co(Mt),B.reject($)}}function kJ(){j.count&&B.cursorFn(j),B.resolve(j)}function $J(){jo=new Ky.Writable({autoDestroy:!0,write($,_,e){w.write(Z().d().raw($).end(),e)},destroy($,_){_($),w.write(Z().f().str($+Z.N).end()),jo=null},final($){w.write(Z().c().end()),oT=$}}),B.resolve(jo)}function JJ(){jo=new Ky.Readable({read(){w.resume()}}),B.resolve(jo)}function RJ(){jo=new Ky.Duplex({autoDestroy:!0,read(){w.resume()},write($,_,e){w.write(Z().d().raw($).end(),e)},destroy($,_){_($),w.write(Z().f().str($+Z.N).end()),jo=null},final($){w.write(Z().c().end()),oT=$}}),B.resolve(jo)}function WJ($){jo&&(jo.push($.subarray(5))||w.pause())}function OJ(){jo&&jo.push(null),jo=null}function _J($){E?E(Xy($)):console.log(Xy($))}function wJ(){}function KJ(){In(Lo.notSupported("FunctionCallResponse"))}function XJ(){In(Lo.notSupported("NegotiateProtocolVersion"))}function EJ($){console.error("Postgres.js : Unknown Message:",$[0])}function YJ($,_){console.error("Postgres.js : Unknown Auth:",_)}function GJ($,_,e="",Jo=""){let Vo,Zo;return Z().B().str(Jo+Z.N).str(e+Z.N).i16(0).i16($.length),$.forEach((uo,gn)=>{if(uo===null)return Z.i32(4294967295);Zo=_[gn],$[gn]=uo=Zo in o.serializers?o.serializers[Zo](uo):""+uo,Vo=Z.i,Z.inc(4).str(uo).i32(Z.i-Vo-4,Vo)}),Z.i16(0),Z.end()}function uy($,_,e,Jo=""){return Z().P().str(Jo+Z.N).str($+Z.N).i16(_.length),_.forEach((Vo,Zo)=>Z.i32(e[Zo]||0)),Z.end()}function zJ($,_=""){return Z().D().str($).str(_+Z.N).end()}function ay($="",_=0){return Buffer.concat([Z().E().str($+Z.N).i32(_).end(),R$])}function HJ($=""){return Buffer.concat([Z().C().str("P").str($+Z.N).end(),Z().S().end()])}function mJ(){return v||Z().inc(4).i16(3).z(2).str(Object.entries(Object.assign({user:A,database:k,client_encoding:"UTF8"},o.connection)).filter(([,$])=>$).map(([$,_])=>$+Z.N+_).join(Z.N)).z(2).end(0)}}function Xy(o){let n={},t=5;for(let T=5;T<o.length-1;T++)if(o[T]===0)n[X0[o[t]]]=o.toString("utf8",t+1,T),t=T+1;return n}function W$(o){return hT.createHash("md5").update(o).digest("hex")}function iS(o,n){return hT.createHmac("sha256",o).update(n).digest()}function E0(o){return hT.createHash("sha256").update(o).digest()}function Y0(o,n){let t=Math.max(o.length,n.length),T=Buffer.allocUnsafe(t);for(let S=0;S<t;S++)T[S]=o[S]^n[S];return T}function Ey(o,n){if(n=typeof n==="function"?n():n,!n)return{cancel:dt,start:dt};let t;return{cancel(){t&&(clearTimeout(t),t=null)},start(){t&&clearTimeout(t),t=setTimeout(T,n*1000,arguments)}};function T(S){o.apply(null,S),t=null}}var _$=()=>{};function Gy(o,n){let t=new Map,T="postgresjs_"+Math.random().toString(36).slice(2),S={},f,y,A=!1,M=W.sql=o({...n,transform:{column:{},value:{},row:{}},max:1,fetch_types:!1,idle_timeout:null,max_lifetime:null,connection:{...n.connection,replication:"database"},onclose:async function(){if(A)return;y=null,S.pid=S.secret=void 0,O(await E(M,T,n.publications)),t.forEach((z)=>z.forEach(({onsubscribe:G})=>G()))},no_subscribe:!0}),F=M.end,k=M.close;return M.end=async()=>{return A=!0,y&&await new Promise((z)=>(y.once("close",z),y.end())),F()},M.close=async()=>{return y&&await new Promise((z)=>(y.once("close",z),y.end())),k()},W;async function W(z,G,V=_$,x=_$){if(z=H0(z),!f)f=E(M,T,n.publications);let c={fn:G,onsubscribe:V},P=t.has(z)?t.get(z).add(c):t.set(z,new Set([c])).get(z),Y=()=>{P.delete(c),P.size===0&&t.delete(z)};return f.then((K)=>{return O(K),V(),y&&y.on("error",x),{unsubscribe:Y,state:S,sql:M}})}function O(z){y=z.stream,S.pid=z.state.pid,S.secret=z.state.secret}async function E(z,G,V){if(!V)throw new Error("Missing publication names");let x=await z.unsafe(`CREATE_REPLICATION_SLOT ${G} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT`),[c]=x,P=await z.unsafe(`START_REPLICATION SLOT ${G} LOGICAL ${c.consistent_point} (proto_version '1', publication_names '${V}')`).writable(),Y={lsn:Buffer.concat(c.consistent_point.split("/").map((w)=>Buffer.from(("00000000"+w).slice(-8),"hex")))};return P.on("data",U),P.on("error",K),P.on("close",z.close),{stream:P,state:x.state};function K(w){console.error("Unexpected error during logical streaming - reconnecting",w)}function U(w){if(w[0]===119)z0(w.subarray(25),Y,z.options.parsers,p,n.transform);else if(w[0]===107&&w[17])Y.lsn=w.subarray(1,9),b()}function p(w,v){let j=v.relation.schema+"."+v.relation.table;Q("*",w,v),Q("*:"+j,w,v),v.relation.keys.length&&Q("*:"+j+"="+v.relation.keys.map((a)=>w[a.name]),w,v),Q(v.command,w,v),Q(v.command+":"+j,w,v),v.relation.keys.length&&Q(v.command+":"+j+"="+v.relation.keys.map((a)=>w[a.name]),w,v)}function b(){let w=Buffer.alloc(34);w[0]="r".charCodeAt(0),w.fill(Y.lsn,1),w.writeBigInt64BE(BigInt(Date.now()-Date.UTC(2000,0,1))*BigInt(1000),25),P.write(w)}}function Q(z,G,V){t.has(z)&&t.get(z).forEach(({fn:x})=>x(G,V,z))}}function G0(o){return new Date(Date.UTC(2000,0,1)+Number(o/BigInt(1000)))}function z0(o,n,t,T,S){let f=(y,[A,M])=>(y[A.charCodeAt(0)]=M,y);Object.entries({R:(y)=>{let A=1,M=n[y.readUInt32BE(A)]={schema:y.toString("utf8",A+=4,A=y.indexOf(0,A))||"pg_catalog",table:y.toString("utf8",A+1,A=y.indexOf(0,A+1)),columns:Array(y.readUInt16BE(A+=2)),keys:[]};A+=2;let F=0,k;while(A<y.length)k=M.columns[F++]={key:y[A++],name:S.column.from?S.column.from(y.toString("utf8",A,A=y.indexOf(0,A))):y.toString("utf8",A,A=y.indexOf(0,A)),type:y.readUInt32BE(A+=1),parser:t[y.readUInt32BE(A)],atttypmod:y.readUInt32BE(A+=4)},k.key&&M.keys.push(k),A+=4},Y:()=>{},O:()=>{},B:(y)=>{n.date=G0(y.readBigInt64BE(9)),n.lsn=y.subarray(1,9)},I:(y)=>{let A=1,M=n[y.readUInt32BE(A)],{row:F}=vS(y,M.columns,A+=7,S);T(F,{command:"insert",relation:M})},D:(y)=>{let A=1,M=n[y.readUInt32BE(A)];A+=4;let F=y[A]===75;T(F||y[A]===79?vS(y,M.columns,A+=3,S).row:null,{command:"delete",relation:M,key:F})},U:(y)=>{let A=1,M=n[y.readUInt32BE(A)];A+=4;let F=y[A]===75,k=F||y[A]===79?vS(y,M.columns,A+=3,S):null;k&&(A=k.i);let{row:W}=vS(y,M.columns,A+3,S);T(W,{command:"update",relation:M,key:F,old:k&&k.row})},T:()=>{},C:()=>{}}).reduce(f,{})[o[0]](o)}function vS(o,n,t,T){let S,f,y,A=T.raw?new Array(n.length):{};for(let M=0;M<n.length;M++)S=o[t++],f=n[M],y=S===110?null:S===117?void 0:f.parser===void 0?o.toString("utf8",t+4,t+=4+o.readUInt32BE(t)):f.parser.array===!0?f.parser(o.toString("utf8",t+5,t+=4+o.readUInt32BE(t))):f.parser(o.toString("utf8",t+4,t+=4+o.readUInt32BE(t))),T.raw?A[M]=T.raw===!0?y:T.value.from?T.value.from(y,f):y:A[f.name]=T.value.from?T.value.from(y,f):y;return{i:t,row:T.row.from?T.row.from(A):A}}function H0(o){let n=o.match(/^(\*|insert|update|delete)?:?([^.]+?\.?[^=]+)?=?(.+)?/i)||[];if(!n)throw new Error("Malformed subscribe pattern: "+o);let[,t,T,S]=n;return(t||"*")+(T?":"+(T.indexOf(".")===-1?"public."+T:T):"")+(S?"="+S:"")}import w$ from"stream";function zy(o,n,t=393216){return new Promise(async(T,S)=>{await o.begin(async(f)=>{let y;!n&&([{oid:n}]=await f`select lo_creat(-1) as oid`);let[{fd:A}]=await f`select lo_open(${n}, ${t}) as fd`,M={writable:k,readable:F,close:()=>f`select lo_close(${A})`.then(y),tell:()=>f`select lo_tell64(${A})`,read:(W)=>f`select loread(${A}, ${W}) as data`,write:(W)=>f`select lowrite(${A}, ${W})`,truncate:(W)=>f`select lo_truncate64(${A}, ${W})`,seek:(W,O=0)=>f`select lo_lseek64(${A}, ${W}, ${O})`,size:()=>f`
14
14
  select
15
15
  lo_lseek64(${A}, location, 0) as position,
16
16
  seek.size
@@ -20,10 +20,10 @@ var mJ=Object.create;var{getPrototypeOf:QJ,defineProperty:of,getOwnPropertyNames
20
20
  tell.location
21
21
  from (select lo_tell64($1) as location) tell
22
22
  ) seek
23
- `};return T(M),new Promise(async(W)=>y=W);async function F({highWaterMark:W=16384,start:O=0,end:E=1/0}={}){let Q=E-O;return O&&await M.seek(O),new w$.Readable({highWaterMark:W,async read(z){let G=z>Q?z-Q:z;Q-=z;let[{data:V}]=await M.read(G);if(this.push(V),V.length<z)this.push(null)}})}async function k({highWaterMark:W=16384,start:O=0}={}){return O&&await M.seek(O),new w$.Writable({highWaterMark:W,write(E,Q,z){M.write(E).then(()=>z(),z)}})}}).catch(S)})}Object.assign(pS,{PostgresError:gt,toPascal:_t,pascal:_y,toCamel:Ot,camel:Oy,toKebab:wt,kebab:wy,fromPascal:jT,fromCamel:IT,fromKebab:bT,BigInt:{to:20,from:[20],parse:(o)=>BigInt(o),serialize:(o)=>o.toString()}});var ut=pS;function pS(o,n){let t=Q0(o,n),T=t.no_subscribe||Gy(pS,{...t}),S=!1,f=Jn(),y=Jn(),A=Jn(),M=Jn(),F=Jn(),k=Jn(),W=Jn(),O=Jn(),E={connecting:y,reserved:A,closed:M,ended:F,open:k,busy:W,full:O},Q=[...Array(t.max)].map(()=>Yy(t,E,{onopen:_o,onend:no,onclose:An})),z=G(p);return Object.assign(z,{get parameters(){return t.parameters},largeObject:zy.bind(null,z),subscribe:T,CLOSE:lt,END:lt,PostgresError:gt,options:t,reserve:c,listen:V,begin:P,close:j,end:v}),z;function G(H){return H.debug=t.debug,Object.entries(t.types).reduce((So,[wo,Co])=>{return So[wo]=(mo)=>new cn(mo,Co.to),So},i),Object.assign(fo,{types:i,typed:i,unsafe:Ro,notify:x,array:U,json:K,file:Io}),fo;function i(So,wo){return new cn(So,wo)}function fo(So,...wo){return So&&Array.isArray(So.raw)?new Xn(So,wo,H,w):typeof So==="string"&&!wo.length?new NT(t.transform.column.to?t.transform.column.to(So):So):new NS(So,wo)}function Ro(So,wo=[],Co={}){return arguments.length===2&&!Array.isArray(wo)&&(Co=wo,wo=[]),new Xn([So],wo,H,w,{prepare:!1,...Co,simple:"simple"in Co?Co.simple:wo.length===0})}function Io(So,wo=[],Co={}){return arguments.length===2&&!Array.isArray(wo)&&(Co=wo,wo=[]),new Xn([],wo,(Eo)=>{m0.readFile(So,"utf8",(vo,Ko)=>{if(vo)return Eo.reject(vo);Eo.strings=[Ko],H(Eo)})},w,{...Co,simple:"simple"in Co?Co.simple:wo.length===0})}}async function V(H,i,fo){let Ro={fn:i,onlisten:fo},Io=V.sql||(V.sql=pS({...t,max:1,idle_timeout:null,max_lifetime:null,fetch_types:!1,onclose(){Object.entries(V.channels).forEach(([Eo,{listeners:vo}])=>{delete V.channels[Eo],Promise.all(vo.map((Ko)=>V(Eo,Ko.fn,Ko.onlisten).catch(()=>{})))})},onnotify(Eo,vo){Eo in V.channels&&V.channels[Eo].listeners.forEach((Ko)=>Ko.fn(vo))}})),So=V.channels||(V.channels={});if(H in So){So[H].listeners.push(Ro);let Eo=await So[H].result;return Ro.onlisten&&Ro.onlisten(),{state:Eo.state,unlisten:mo}}So[H]={result:Io`listen ${Io.unsafe('"'+H.replace(/"/g,'""')+'"')}`,listeners:[Ro]};let Co=await So[H].result;return Ro.onlisten&&Ro.onlisten(),{state:Co.state,unlisten:mo};async function mo(){if(H in So===!1)return;if(So[H].listeners=So[H].listeners.filter((Eo)=>Eo!==Ro),So[H].listeners.length)return;return delete So[H],Io`unlisten ${Io.unsafe('"'+H.replace(/"/g,'""')+'"')}`}}async function x(H,i){return await z`select pg_notify(${H}, ${""+i})`}async function c(){let H=Jn(),i=k.length?k.shift():await new Promise((Io)=>{f.push({reserve:Io}),M.length&&oo(M.shift())});Y(i,A),i.reserved=()=>H.length?i.execute(H.shift()):Y(i,A),i.reserved.release=!0;let fo=G(Ro);return fo.release=()=>{i.reserved=null,_o(i)},fo;function Ro(Io){i.queue===O?H.push(Io):i.execute(Io)||Y(i,O)}}async function P(H,i){!i&&(i=H,H="");let fo=Jn(),Ro=0,Io,So=null;try{return await z.unsafe("begin "+H.replace(/[^a-z ]/ig,""),[],{onexecute:Co}).execute(),await Promise.race([wo(Io,i),new Promise((mo,Eo)=>Io.onclose=Eo)])}catch(mo){throw mo}async function wo(mo,Eo,vo){let Ko=G(jo);Ko.savepoint=ln,Ko.prepare=(Yo)=>So=Yo.replace(/[^a-z0-9$-_. ]/gi);let Yn,po;vo&&await Ko`savepoint ${Ko(vo)}`;try{if(po=await new Promise((Yo,Gn)=>{let Ln=Eo(Ko);Promise.resolve(Array.isArray(Ln)?Promise.all(Ln):Ln).then(Yo,Gn)}),Yn)throw Yn}catch(Yo){throw await(vo?Ko`rollback to ${Ko(vo)}`:Ko`rollback`),Yo instanceof gt&&Yo.code==="25P02"&&Yn||Yo}if(!vo)So?await Ko`prepare transaction '${Ko.unsafe(So)}'`:await Ko`commit`;return po;function ln(Yo,Gn){if(Yo&&Array.isArray(Yo.raw))return ln((Ln)=>Ln.apply(Ln,arguments));return arguments.length===1&&(Gn=Yo,Yo=null),wo(mo,Gn,"s"+Ro+++(Yo?"_"+Yo:""))}function jo(Yo){Yo.catch((Gn)=>Yn||(Yn=Gn)),mo.queue===O?fo.push(Yo):mo.execute(Yo)||Y(mo,O)}}function Co(mo){Io=mo,Y(mo,A),mo.reserved=()=>fo.length?mo.execute(fo.shift()):Y(mo,A)}}function Y(H,i){return H.queue.remove(H),i.push(H),H.queue=i,i===k?H.idleTimer.start():H.idleTimer.cancel(),H}function K(H){return new cn(H,3802)}function U(H,i){if(!Array.isArray(H))return U(Array.from(arguments));return new cn(H,i||(H.length?jS(H)||25:0),t.shared.typeArrayMap)}function p(H){if(S)return H.reject(Lo.connection("CONNECTION_ENDED",t,t));if(k.length)return b(k.shift(),H);if(M.length)return oo(M.shift(),H);W.length?b(W.shift(),H):f.push(H)}function b(H,i){return H.execute(i)?Y(H,W):Y(H,O)}function w(H){return new Promise((i,fo)=>{H.state?H.active?Yy(t).cancel(H.state,i,fo):H.cancelled={resolve:i,reject:fo}:(f.remove(H),H.cancelled=!0,H.reject(Lo.generic("57014","canceling statement due to user request")),i())})}async function v({timeout:H=null}={}){if(S)return S;await 1;let i;return S=Promise.race([new Promise((fo)=>H!==null&&(i=setTimeout(a,H*1000,fo))),Promise.all(Q.map((fo)=>fo.end()).concat(V.sql?V.sql.end({timeout:0}):[],T.sql?T.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(i))}async function j(){await Promise.all(Q.map((H)=>H.end()))}async function a(H){await Promise.all(Q.map((i)=>i.terminate()));while(f.length)f.shift().reject(Lo.connection("CONNECTION_DESTROYED",t));H()}function oo(H,i){return Y(H,y),H.connect(i),H}function no(H){Y(H,F)}function _o(H){if(f.length===0)return Y(H,k);let i=Math.ceil(f.length/(y.length+1)),fo=!0;while(fo&&f.length&&i-- >0){let Ro=f.shift();if(Ro.reserve)return Ro.reserve(H);fo=H.execute(Ro)}fo?Y(H,W):Y(H,O)}function An(H,i){Y(H,M),H.reserved=null,H.onclose&&(H.onclose(i),H.onclose=null),t.onclose&&t.onclose(H.id),f.length&&oo(H,f.shift())}}function Q0(o,n){if(o&&o.shared)return o;let t=process.env,T=(!o||typeof o==="string"?n:o)||{},{url:S,multihost:f}=B0(o),y=[...S.searchParams].reduce((O,[E,Q])=>(O[E]=Q,O),{}),A=T.hostname||T.host||f||S.hostname||t.PGHOST||"localhost",M=T.port||S.port||t.PGPORT||5432,F=T.user||T.username||S.username||t.PGUSERNAME||t.PGUSER||C0();T.no_prepare&&(T.prepare=!1),y.sslmode&&(y.ssl=y.sslmode,delete y.sslmode),"timeout"in T&&(console.log("The timeout option is deprecated, use idle_timeout instead"),T.idle_timeout=T.timeout),y.sslrootcert==="system"&&(y.ssl="verify-full");let k=["idle_timeout","connect_timeout","max_lifetime","max_pipeline","backoff","keep_alive"],W={max:10,ssl:!1,idle_timeout:null,connect_timeout:30,max_lifetime:V0,max_pipeline:100,backoff:U0,keep_alive:60,prepare:!0,debug:!1,fetch_types:!0,publications:"alltables",target_session_attrs:null};return{host:Array.isArray(A)?A:A.split(",").map((O)=>O.split(":")[0]),port:Array.isArray(M)?M:A.split(",").map((O)=>parseInt(O.split(":")[1]||M)),path:T.path||A.indexOf("/")>-1&&A+"/.s.PGSQL."+M,database:T.database||T.db||(S.pathname||"").slice(1)||t.PGDATABASE||F,user:F,pass:T.pass||T.password||S.password||t.PGPASSWORD||"",...Object.entries(W).reduce((O,[E,Q])=>{let z=E in T?T[E]:(E in y)?y[E]==="disable"||y[E]==="false"?!1:y[E]:t["PG"+E.toUpperCase()]||Q;return O[E]=typeof z==="string"&&k.includes(E)?+z:z,O},{}),connection:{application_name:"postgres.js",...T.connection,...Object.entries(y).reduce((O,[E,Q])=>((E in W)||(O[E]=Q),O),{})},types:T.types||{},target_session_attrs:D0(T,S,t),onnotice:T.onnotice,onnotify:T.onnotify,onclose:T.onclose,onparameter:T.onparameter,socket:T.socket,transform:r0(T.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...y$(T.types)}}function D0(o,n,t){let T=o.target_session_attrs||n.searchParams.get("target_session_attrs")||t.PGTARGETSESSIONATTRS;if(!T||["read-write","read-only","primary","standby","prefer-standby"].includes(T))return T;throw new Error("target_session_attrs "+T+" is not supported")}function U0(o){return(0.5+Math.random()/2)*Math.min(3**o/100,20)}function V0(){return 60*(30+Math.random()*30)}function r0(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 B0(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 C0(){try{return H0.userInfo().username}catch(o){return process.env.USERNAME||"runner"}}class qS extends so{constructor(o,n,t,T){super();this.session=n,this.dialect=t,this.config={table:o,withList:T}}static[J]="PgDelete";config;where(o){return this.config.where=o,this}returning(o=this.config.table[L.Symbol.Columns]){return this.config.returning=_n(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)}execute=(o)=>{return Oo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(o)})};$dynamic(){return this}}class ZS{constructor(o,n,t,T){this.table=o,this.session=n,this.dialect=t,this.withList=T}static[J]="PgInsertBuilder";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 T={},S=this.table[L.Symbol.Columns];for(let f of Object.keys(t)){let y=t[f];T[f]=X(y,h)?y:new Fn(y,S[f])}return T});return new K$(this.table,n,this.session,this.dialect,this.withList)}}class K$ extends so{constructor(o,n,t,T,S){super();this.session=t,this.dialect=T,this.config={table:o,values:n,withList:S}}static[J]="PgInsert";config;returning(o=this.config.table[L.Symbol.Columns]){return this.config.returning=_n(o),this}onConflictDoNothing(o={}){if(o.target===void 0)this.config.onConflict=R`do nothing`;else{let n="";n=Array.isArray(o.target)?o.target.map((T)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(T))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(o.target));let t=o.where?R` where ${o.where}`:void 0;this.config.onConflict=R`(${R.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?R` where ${o.where}`:void 0,t=o.targetWhere?R` where ${o.targetWhere}`:void 0,T=o.setWhere?R` where ${o.setWhere}`:void 0,S=this.dialect.buildUpdateSet(this.config.table,_S(this.config.table,o.set)),f="";return f=Array.isArray(o.target)?o.target.map((y)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(y))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(o.target)),this.config.onConflict=R`(${R.raw(f)})${t} do update set ${S}${n}${T}`,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)}execute=(o)=>{return Oo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(o)})};$dynamic(){return this}}function L0(o){return(o.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((t)=>t.toLowerCase()).join("_")}function I0(o){return(o.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((t,T,S)=>{let f=S===0?T.toLowerCase():`${T[0].toUpperCase()}${T.slice(1)}`;return t+f},"")}function j0(o){return o}class Hy{static[J]="CasingCache";cache={};cachedTables={};convert;constructor(o){this.convert=o==="snake_case"?L0:o==="camelCase"?I0:j0}getColumnCasing(o){if(!o.keyAsName)return o.name;let n=o.table[L.Symbol.Schema]??"public",t=o.table[L.Symbol.OriginalName],T=`${n}.${t}.${o.name}`;if(!this.cache[T])this.cacheTable(o.table);return this.cache[T]}cacheTable(o){let n=o[L.Symbol.Schema]??"public",t=o[L.Symbol.OriginalName],T=`${n}.${t}`;if(!this.cachedTables[T]){for(let S of Object.values(o[L.Symbol.Columns])){let f=`${T}.${S.name}`;this.cache[f]=this.convert(S.name)}this.cachedTables[T]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class cT extends Sn{static[J]="PgViewBase"}class Xt{static[J]="PgDialect";casing;constructor(o){this.casing=new Hy(o?.casing)}async migrate(o,n,t){let T=typeof t==="string"?"__drizzle_migrations":t.migrationsTable??"__drizzle_migrations",S=typeof t==="string"?"drizzle":t.migrationsSchema??"drizzle",f=R`
23
+ `};return T(M),new Promise(async(W)=>y=W);async function F({highWaterMark:W=16384,start:O=0,end:E=1/0}={}){let Q=E-O;return O&&await M.seek(O),new w$.Readable({highWaterMark:W,async read(z){let G=z>Q?z-Q:z;Q-=z;let[{data:V}]=await M.read(G);if(this.push(V),V.length<z)this.push(null)}})}async function k({highWaterMark:W=16384,start:O=0}={}){return O&&await M.seek(O),new w$.Writable({highWaterMark:W,write(E,Q,z){M.write(E).then(()=>z(),z)}})}}).catch(S)})}Object.assign(pS,{PostgresError:gt,toPascal:_t,pascal:_y,toCamel:Ot,camel:Oy,toKebab:wt,kebab:wy,fromPascal:jT,fromCamel:IT,fromKebab:bT,BigInt:{to:20,from:[20],parse:(o)=>BigInt(o),serialize:(o)=>o.toString()}});var ut=pS;function pS(o,n){let t=D0(o,n),T=t.no_subscribe||Gy(pS,{...t}),S=!1,f=Jn(),y=Jn(),A=Jn(),M=Jn(),F=Jn(),k=Jn(),W=Jn(),O=Jn(),E={connecting:y,reserved:A,closed:M,ended:F,open:k,busy:W,full:O},Q=[...Array(t.max)].map(()=>Yy(t,E,{onopen:_o,onend:no,onclose:An})),z=G(p);return Object.assign(z,{get parameters(){return t.parameters},largeObject:zy.bind(null,z),subscribe:T,CLOSE:lt,END:lt,PostgresError:gt,options:t,reserve:c,listen:V,begin:P,close:j,end:v}),z;function G(H){return H.debug=t.debug,Object.entries(t.types).reduce((So,[wo,Co])=>{return So[wo]=(mo)=>new cn(mo,Co.to),So},i),Object.assign(fo,{types:i,typed:i,unsafe:Ro,notify:x,array:U,json:K,file:Io}),fo;function i(So,wo){return new cn(So,wo)}function fo(So,...wo){return So&&Array.isArray(So.raw)?new Xn(So,wo,H,w):typeof So==="string"&&!wo.length?new NT(t.transform.column.to?t.transform.column.to(So):So):new NS(So,wo)}function Ro(So,wo=[],Co={}){return arguments.length===2&&!Array.isArray(wo)&&(Co=wo,wo=[]),new Xn([So],wo,H,w,{prepare:!1,...Co,simple:"simple"in Co?Co.simple:wo.length===0})}function Io(So,wo=[],Co={}){return arguments.length===2&&!Array.isArray(wo)&&(Co=wo,wo=[]),new Xn([],wo,(Eo)=>{Q0.readFile(So,"utf8",(vo,Ko)=>{if(vo)return Eo.reject(vo);Eo.strings=[Ko],H(Eo)})},w,{...Co,simple:"simple"in Co?Co.simple:wo.length===0})}}async function V(H,i,fo){let Ro={fn:i,onlisten:fo},Io=V.sql||(V.sql=pS({...t,max:1,idle_timeout:null,max_lifetime:null,fetch_types:!1,onclose(){Object.entries(V.channels).forEach(([Eo,{listeners:vo}])=>{delete V.channels[Eo],Promise.all(vo.map((Ko)=>V(Eo,Ko.fn,Ko.onlisten).catch(()=>{})))})},onnotify(Eo,vo){Eo in V.channels&&V.channels[Eo].listeners.forEach((Ko)=>Ko.fn(vo))}})),So=V.channels||(V.channels={});if(H in So){So[H].listeners.push(Ro);let Eo=await So[H].result;return Ro.onlisten&&Ro.onlisten(),{state:Eo.state,unlisten:mo}}So[H]={result:Io`listen ${Io.unsafe('"'+H.replace(/"/g,'""')+'"')}`,listeners:[Ro]};let Co=await So[H].result;return Ro.onlisten&&Ro.onlisten(),{state:Co.state,unlisten:mo};async function mo(){if(H in So===!1)return;if(So[H].listeners=So[H].listeners.filter((Eo)=>Eo!==Ro),So[H].listeners.length)return;return delete So[H],Io`unlisten ${Io.unsafe('"'+H.replace(/"/g,'""')+'"')}`}}async function x(H,i){return await z`select pg_notify(${H}, ${""+i})`}async function c(){let H=Jn(),i=k.length?k.shift():await new Promise((Io)=>{f.push({reserve:Io}),M.length&&oo(M.shift())});Y(i,A),i.reserved=()=>H.length?i.execute(H.shift()):Y(i,A),i.reserved.release=!0;let fo=G(Ro);return fo.release=()=>{i.reserved=null,_o(i)},fo;function Ro(Io){i.queue===O?H.push(Io):i.execute(Io)||Y(i,O)}}async function P(H,i){!i&&(i=H,H="");let fo=Jn(),Ro=0,Io,So=null;try{return await z.unsafe("begin "+H.replace(/[^a-z ]/ig,""),[],{onexecute:Co}).execute(),await Promise.race([wo(Io,i),new Promise((mo,Eo)=>Io.onclose=Eo)])}catch(mo){throw mo}async function wo(mo,Eo,vo){let Ko=G(jo);Ko.savepoint=ln,Ko.prepare=(Yo)=>So=Yo.replace(/[^a-z0-9$-_. ]/gi);let Yn,po;vo&&await Ko`savepoint ${Ko(vo)}`;try{if(po=await new Promise((Yo,Gn)=>{let Ln=Eo(Ko);Promise.resolve(Array.isArray(Ln)?Promise.all(Ln):Ln).then(Yo,Gn)}),Yn)throw Yn}catch(Yo){throw await(vo?Ko`rollback to ${Ko(vo)}`:Ko`rollback`),Yo instanceof gt&&Yo.code==="25P02"&&Yn||Yo}if(!vo)So?await Ko`prepare transaction '${Ko.unsafe(So)}'`:await Ko`commit`;return po;function ln(Yo,Gn){if(Yo&&Array.isArray(Yo.raw))return ln((Ln)=>Ln.apply(Ln,arguments));return arguments.length===1&&(Gn=Yo,Yo=null),wo(mo,Gn,"s"+Ro+++(Yo?"_"+Yo:""))}function jo(Yo){Yo.catch((Gn)=>Yn||(Yn=Gn)),mo.queue===O?fo.push(Yo):mo.execute(Yo)||Y(mo,O)}}function Co(mo){Io=mo,Y(mo,A),mo.reserved=()=>fo.length?mo.execute(fo.shift()):Y(mo,A)}}function Y(H,i){return H.queue.remove(H),i.push(H),H.queue=i,i===k?H.idleTimer.start():H.idleTimer.cancel(),H}function K(H){return new cn(H,3802)}function U(H,i){if(!Array.isArray(H))return U(Array.from(arguments));return new cn(H,i||(H.length?jS(H)||25:0),t.shared.typeArrayMap)}function p(H){if(S)return H.reject(Lo.connection("CONNECTION_ENDED",t,t));if(k.length)return b(k.shift(),H);if(M.length)return oo(M.shift(),H);W.length?b(W.shift(),H):f.push(H)}function b(H,i){return H.execute(i)?Y(H,W):Y(H,O)}function w(H){return new Promise((i,fo)=>{H.state?H.active?Yy(t).cancel(H.state,i,fo):H.cancelled={resolve:i,reject:fo}:(f.remove(H),H.cancelled=!0,H.reject(Lo.generic("57014","canceling statement due to user request")),i())})}async function v({timeout:H=null}={}){if(S)return S;await 1;let i;return S=Promise.race([new Promise((fo)=>H!==null&&(i=setTimeout(a,H*1000,fo))),Promise.all(Q.map((fo)=>fo.end()).concat(V.sql?V.sql.end({timeout:0}):[],T.sql?T.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(i))}async function j(){await Promise.all(Q.map((H)=>H.end()))}async function a(H){await Promise.all(Q.map((i)=>i.terminate()));while(f.length)f.shift().reject(Lo.connection("CONNECTION_DESTROYED",t));H()}function oo(H,i){return Y(H,y),H.connect(i),H}function no(H){Y(H,F)}function _o(H){if(f.length===0)return Y(H,k);let i=Math.ceil(f.length/(y.length+1)),fo=!0;while(fo&&f.length&&i-- >0){let Ro=f.shift();if(Ro.reserve)return Ro.reserve(H);fo=H.execute(Ro)}fo?Y(H,W):Y(H,O)}function An(H,i){Y(H,M),H.reserved=null,H.onclose&&(H.onclose(i),H.onclose=null),t.onclose&&t.onclose(H.id),f.length&&oo(H,f.shift())}}function D0(o,n){if(o&&o.shared)return o;let t=process.env,T=(!o||typeof o==="string"?n:o)||{},{url:S,multihost:f}=C0(o),y=[...S.searchParams].reduce((O,[E,Q])=>(O[E]=Q,O),{}),A=T.hostname||T.host||f||S.hostname||t.PGHOST||"localhost",M=T.port||S.port||t.PGPORT||5432,F=T.user||T.username||S.username||t.PGUSERNAME||t.PGUSER||L0();T.no_prepare&&(T.prepare=!1),y.sslmode&&(y.ssl=y.sslmode,delete y.sslmode),"timeout"in T&&(console.log("The timeout option is deprecated, use idle_timeout instead"),T.idle_timeout=T.timeout),y.sslrootcert==="system"&&(y.ssl="verify-full");let k=["idle_timeout","connect_timeout","max_lifetime","max_pipeline","backoff","keep_alive"],W={max:10,ssl:!1,idle_timeout:null,connect_timeout:30,max_lifetime:r0,max_pipeline:100,backoff:V0,keep_alive:60,prepare:!0,debug:!1,fetch_types:!0,publications:"alltables",target_session_attrs:null};return{host:Array.isArray(A)?A:A.split(",").map((O)=>O.split(":")[0]),port:Array.isArray(M)?M:A.split(",").map((O)=>parseInt(O.split(":")[1]||M)),path:T.path||A.indexOf("/")>-1&&A+"/.s.PGSQL."+M,database:T.database||T.db||(S.pathname||"").slice(1)||t.PGDATABASE||F,user:F,pass:T.pass||T.password||S.password||t.PGPASSWORD||"",...Object.entries(W).reduce((O,[E,Q])=>{let z=E in T?T[E]:(E in y)?y[E]==="disable"||y[E]==="false"?!1:y[E]:t["PG"+E.toUpperCase()]||Q;return O[E]=typeof z==="string"&&k.includes(E)?+z:z,O},{}),connection:{application_name:"postgres.js",...T.connection,...Object.entries(y).reduce((O,[E,Q])=>((E in W)||(O[E]=Q),O),{})},types:T.types||{},target_session_attrs:U0(T,S,t),onnotice:T.onnotice,onnotify:T.onnotify,onclose:T.onclose,onparameter:T.onparameter,socket:T.socket,transform:B0(T.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...y$(T.types)}}function U0(o,n,t){let T=o.target_session_attrs||n.searchParams.get("target_session_attrs")||t.PGTARGETSESSIONATTRS;if(!T||["read-write","read-only","primary","standby","prefer-standby"].includes(T))return T;throw new Error("target_session_attrs "+T+" is not supported")}function V0(o){return(0.5+Math.random()/2)*Math.min(3**o/100,20)}function r0(){return 60*(30+Math.random()*30)}function B0(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 C0(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 L0(){try{return m0.userInfo().username}catch(o){return process.env.USERNAME||"runner"}}class qS extends so{constructor(o,n,t,T){super();this.session=n,this.dialect=t,this.config={table:o,withList:T}}static[J]="PgDelete";config;where(o){return this.config.where=o,this}returning(o=this.config.table[L.Symbol.Columns]){return this.config.returning=_n(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)}execute=(o)=>{return Oo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(o)})};$dynamic(){return this}}class ZS{constructor(o,n,t,T){this.table=o,this.session=n,this.dialect=t,this.withList=T}static[J]="PgInsertBuilder";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 T={},S=this.table[L.Symbol.Columns];for(let f of Object.keys(t)){let y=t[f];T[f]=X(y,h)?y:new Fn(y,S[f])}return T});return new K$(this.table,n,this.session,this.dialect,this.withList)}}class K$ extends so{constructor(o,n,t,T,S){super();this.session=t,this.dialect=T,this.config={table:o,values:n,withList:S}}static[J]="PgInsert";config;returning(o=this.config.table[L.Symbol.Columns]){return this.config.returning=_n(o),this}onConflictDoNothing(o={}){if(o.target===void 0)this.config.onConflict=R`do nothing`;else{let n="";n=Array.isArray(o.target)?o.target.map((T)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(T))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(o.target));let t=o.where?R` where ${o.where}`:void 0;this.config.onConflict=R`(${R.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?R` where ${o.where}`:void 0,t=o.targetWhere?R` where ${o.targetWhere}`:void 0,T=o.setWhere?R` where ${o.setWhere}`:void 0,S=this.dialect.buildUpdateSet(this.config.table,_S(this.config.table,o.set)),f="";return f=Array.isArray(o.target)?o.target.map((y)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(y))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(o.target)),this.config.onConflict=R`(${R.raw(f)})${t} do update set ${S}${n}${T}`,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)}execute=(o)=>{return Oo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(o)})};$dynamic(){return this}}function I0(o){return(o.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((t)=>t.toLowerCase()).join("_")}function j0(o){return(o.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((t,T,S)=>{let f=S===0?T.toLowerCase():`${T[0].toUpperCase()}${T.slice(1)}`;return t+f},"")}function b0(o){return o}class Hy{static[J]="CasingCache";cache={};cachedTables={};convert;constructor(o){this.convert=o==="snake_case"?I0:o==="camelCase"?j0:b0}getColumnCasing(o){if(!o.keyAsName)return o.name;let n=o.table[L.Symbol.Schema]??"public",t=o.table[L.Symbol.OriginalName],T=`${n}.${t}.${o.name}`;if(!this.cache[T])this.cacheTable(o.table);return this.cache[T]}cacheTable(o){let n=o[L.Symbol.Schema]??"public",t=o[L.Symbol.OriginalName],T=`${n}.${t}`;if(!this.cachedTables[T]){for(let S of Object.values(o[L.Symbol.Columns])){let f=`${T}.${S.name}`;this.cache[f]=this.convert(S.name)}this.cachedTables[T]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class cT extends Sn{static[J]="PgViewBase"}class Xt{static[J]="PgDialect";casing;constructor(o){this.casing=new Hy(o?.casing)}async migrate(o,n,t){let T=typeof t==="string"?"__drizzle_migrations":t.migrationsTable??"__drizzle_migrations",S=typeof t==="string"?"drizzle":t.migrationsSchema??"drizzle",f=R`
24
24
  CREATE TABLE IF NOT EXISTS ${R.identifier(S)}.${R.identifier(T)} (
25
25
  id SERIAL PRIMARY KEY,
26
26
  hash text NOT NULL,
27
27
  created_at bigint
28
28
  )
29
- `;await n.execute(R`CREATE SCHEMA IF NOT EXISTS ${R.identifier(S)}`),await n.execute(f);let A=(await n.all(R`select id, hash, created_at from ${R.identifier(S)}.${R.identifier(T)} order by created_at desc limit 1`))[0];await n.transaction(async(M)=>{for await(let F of o)if(!A||Number(A.created_at)<F.folderMillis){for(let k of F.sql)await M.execute(R.raw(k));await M.execute(R`insert into ${R.identifier(S)}.${R.identifier(T)} ("hash", "created_at") values(${F.hash}, ${F.folderMillis})`)}})}escapeName(o){return`"${o}"`}escapeParam(o){return`\$${o+1}`}escapeString(o){return`'${o.replace(/'/g,"''")}'`}buildWithCTE(o){if(!o?.length)return;let n=[R`with `];for(let[t,T]of o.entries())if(n.push(R`${R.identifier(T._.alias)} as (${T._.sql})`),t<o.length-1)n.push(R`, `);return n.push(R` `),R.join(n)}buildDeleteQuery({table:o,where:n,returning:t,withList:T}){let S=this.buildWithCTE(T),f=t?R` returning ${this.buildSelection(t,{isSingleTable:!0})}`:void 0,y=n?R` where ${n}`:void 0;return R`${S}delete from ${o}${y}${f}`}buildUpdateSet(o,n){let t=o[L.Symbol.Columns],T=Object.keys(t).filter((f)=>n[f]!==void 0||t[f]?.onUpdateFn!==void 0),S=T.length;return R.join(T.flatMap((f,y)=>{let A=t[f],M=n[f]??R.param(A.onUpdateFn(),A),F=R`${R.identifier(this.casing.getColumnCasing(A))} = ${M}`;if(y<S-1)return[F,R.raw(", ")];return[F]}))}buildUpdateQuery({table:o,set:n,where:t,returning:T,withList:S}){let f=this.buildWithCTE(S),y=this.buildUpdateSet(o,n),A=T?R` returning ${this.buildSelection(T,{isSingleTable:!0})}`:void 0,M=t?R` where ${t}`:void 0;return R`${f}update ${o} set ${y}${M}${A}`}buildSelection(o,{isSingleTable:n=!1}={}){let t=o.length,T=o.flatMap(({field:S},f)=>{let y=[];if(X(S,h.Aliased)&&S.isSelectionField)y.push(R.identifier(S.fieldAlias));else if(X(S,h.Aliased)||X(S,h)){let A=X(S,h.Aliased)?S.sql:S;if(n)y.push(new h(A.queryChunks.map((M)=>{if(X(M,r))return R.identifier(this.casing.getColumnCasing(M));return M})));else y.push(A);if(X(S,h.Aliased))y.push(R` as ${R.identifier(S.fieldAlias)}`)}else if(X(S,Xo))if(n)y.push(R.identifier(this.casing.getColumnCasing(S)));else y.push(S);if(f<t-1)y.push(R`, `);return y});return R.join(T)}buildSelectQuery({withList:o,fields:n,fieldsFlat:t,where:T,having:S,table:f,joins:y,orderBy:A,groupBy:M,limit:F,offset:k,lockingClause:W,distinct:O,setOperators:E}){let Q=t??_n(n);for(let oo of Q)if(X(oo.field,Xo)&&On(oo.field.table)!==(X(f,xo)?f._.alias:X(f,cT)?f[Do].name:X(f,h)?void 0:On(f))&&!((no)=>y?.some(({alias:_o})=>_o===(no[L.Symbol.IsAlias]?On(no):no[L.Symbol.BaseName])))(oo.field.table)){let no=On(oo.field.table);throw new Error(`Your "${oo.path.join("->")}" field references a column "${no}"."${oo.field.name}", but the table "${no}" is not part of the query! Did you forget to join it?`)}let z=!y||y.length===0,G=this.buildWithCTE(o),V;if(O)V=O===!0?R` distinct`:R` distinct on (${R.join(O.on,R`, `)})`;let x=this.buildSelection(Q,{isSingleTable:z}),c=(()=>{if(X(f,L)&&f[L.Symbol.OriginalName]!==f[L.Symbol.Name]){let oo=R`${R.identifier(f[L.Symbol.OriginalName])}`;if(f[L.Symbol.Schema])oo=R`${R.identifier(f[L.Symbol.Schema])}.${oo}`;return R`${oo} ${R.identifier(f[L.Symbol.Name])}`}return f})(),P=[];if(y)for(let[oo,no]of y.entries()){if(oo===0)P.push(R` `);let _o=no.table,An=no.lateral?R` lateral`:void 0;if(X(_o,wn)){let H=_o[wn.Symbol.Name],i=_o[wn.Symbol.Schema],fo=_o[wn.Symbol.OriginalName],Ro=H===fo?void 0:no.alias;P.push(R`${R.raw(no.joinType)} join${An} ${i?R`${R.identifier(i)}.`:void 0}${R.identifier(fo)}${Ro&&R` ${R.identifier(Ro)}`} on ${no.on}`)}else if(X(_o,Sn)){let H=_o[Do].name,i=_o[Do].schema,fo=_o[Do].originalName,Ro=H===fo?void 0:no.alias;P.push(R`${R.raw(no.joinType)} join${An} ${i?R`${R.identifier(i)}.`:void 0}${R.identifier(fo)}${Ro&&R` ${R.identifier(Ro)}`} on ${no.on}`)}else P.push(R`${R.raw(no.joinType)} join${An} ${_o} on ${no.on}`);if(oo<y.length-1)P.push(R` `)}let Y=R.join(P),K=T?R` where ${T}`:void 0,U=S?R` having ${S}`:void 0,p;if(A&&A.length>0)p=R` order by ${R.join(A,R`, `)}`;let b;if(M&&M.length>0)b=R` group by ${R.join(M,R`, `)}`;let w=typeof F==="object"||typeof F==="number"&&F>=0?R` limit ${F}`:void 0,v=k?R` offset ${k}`:void 0,j=R.empty();if(W){let oo=R` for ${R.raw(W.strength)}`;if(W.config.of)oo.append(R` of ${R.join(Array.isArray(W.config.of)?W.config.of:[W.config.of],R`, `)}`);if(W.config.noWait)oo.append(R` no wait`);else if(W.config.skipLocked)oo.append(R` skip locked`);j.append(oo)}let a=R`${G}select${V} ${x} from ${c}${Y}${K}${b}${U}${p}${w}${v}${j}`;if(E.length>0)return this.buildSetOperations(a,E);return a}buildSetOperations(o,n){let[t,...T]=n;if(!t)throw new Error("Cannot pass undefined values to any set operator");if(T.length===0)return this.buildSetOperationQuery({leftSelect:o,setOperator:t});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:o,setOperator:t}),T)}buildSetOperationQuery({leftSelect:o,setOperator:{type:n,isAll:t,rightSelect:T,limit:S,orderBy:f,offset:y}}){let A=R`(${o.getSQL()}) `,M=R`(${T.getSQL()})`,F;if(f&&f.length>0){let E=[];for(let Q of f)if(X(Q,r))E.push(R.identifier(Q.name));else if(X(Q,h)){for(let z=0;z<Q.queryChunks.length;z++){let G=Q.queryChunks[z];if(X(G,r))Q.queryChunks[z]=R.identifier(G.name)}E.push(R`${Q}`)}else E.push(R`${Q}`);F=R` order by ${R.join(E,R`, `)} `}let k=typeof S==="object"||typeof S==="number"&&S>=0?R` limit ${S}`:void 0,W=R.raw(`${n} ${t?"all ":""}`),O=y?R` offset ${y}`:void 0;return R`${A}${W}${M}${F}${k}${O}`}buildInsertQuery({table:o,values:n,onConflict:t,returning:T,withList:S}){let f=[],y=o[L.Symbol.Columns],A=Object.entries(y).filter(([E,Q])=>!Q.shouldDisableInsert()),M=A.map(([,E])=>R.identifier(this.casing.getColumnCasing(E)));for(let[E,Q]of n.entries()){let z=[];for(let[G,V]of A){let x=Q[G];if(x===void 0||X(x,Fn)&&x.value===void 0)if(V.defaultFn!==void 0){let c=V.defaultFn(),P=X(c,h)?c:R.param(c,V);z.push(P)}else if(!V.default&&V.onUpdateFn!==void 0){let c=V.onUpdateFn(),P=X(c,h)?c:R.param(c,V);z.push(P)}else z.push(R`default`);else z.push(x)}if(f.push(z),E<n.length-1)f.push(R`, `)}let F=this.buildWithCTE(S),k=R.join(f),W=T?R` returning ${this.buildSelection(T,{isSingleTable:!0})}`:void 0,O=t?R` on conflict ${t}`:void 0;return R`${F}insert into ${o} ${M} values ${k}${O}${W}`}buildRefreshMaterializedViewQuery({view:o,concurrently:n,withNoData:t}){let T=n?R` concurrently`:void 0,S=t?R` with no data`:void 0;return R`refresh materialized view${T} ${o}${S}`}prepareTyping(o){if(X(o,YS)||X(o,ES))return"json";else if(X(o,GS))return"decimal";else if(X(o,zS))return"time";else if(X(o,HS)||X(o,mS))return"timestamp";else if(X(o,wS)||X(o,KS))return"date";else if(X(o,QS))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:T,tableConfig:S,queryConfig:f,tableAlias:y,nestedQueryRelation:A,joinOn:M}){let F=[],k,W,O=[],E,Q=[];if(f===!0)F=Object.entries(S.columns).map(([V,x])=>({dbKey:x.name,tsKey:V,field:bn(x,y),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let G=Object.fromEntries(Object.entries(S.columns).map(([K,U])=>[K,bn(U,y)]));if(f.where){let K=typeof f.where==="function"?f.where(G,Bk()):f.where;E=K&&KT(K,y)}let V=[],x=[];if(f.columns){let K=!1;for(let[U,p]of Object.entries(f.columns)){if(p===void 0)continue;if(U in S.columns){if(!K&&p===!0)K=!0;x.push(U)}}if(x.length>0)x=K?x.filter((U)=>f.columns?.[U]===!0):Object.keys(S.columns).filter((U)=>!x.includes(U))}else x=Object.keys(S.columns);for(let K of x){let U=S.columns[K];V.push({tsKey:K,value:U})}let c=[];if(f.with)c=Object.entries(f.with).filter((K)=>!!K[1]).map(([K,U])=>({tsKey:K,queryConfig:U,relation:S.relations[K]}));let P;if(f.extras){P=typeof f.extras==="function"?f.extras(G,{sql:R}):f.extras;for(let[K,U]of Object.entries(P))V.push({tsKey:K,value:Zf(U,y)})}for(let{tsKey:K,value:U}of V)F.push({dbKey:X(U,h.Aliased)?U.fieldAlias:S.columns[K].name,tsKey:K,field:X(U,Xo)?bn(U,y):U,relationTableTsKey:void 0,isJson:!1,selection:[]});let Y=typeof f.orderBy==="function"?f.orderBy(G,Ck()):f.orderBy??[];if(!Array.isArray(Y))Y=[Y];O=Y.map((K)=>{if(X(K,Xo))return bn(K,y);return KT(K,y)}),k=f.limit,W=f.offset;for(let{tsKey:K,queryConfig:U,relation:p}of c){let b=Ik(n,t,p),w=kt(p.referencedTable),v=t[w],j=`${y}_${K}`,a=XT(...b.fields.map((_o,An)=>Ct(bn(b.references[An],j),bn(_o,y)))),oo=this.buildRelationalQueryWithoutPK({fullSchema:o,schema:n,tableNamesMap:t,table:o[v],tableConfig:n[v],queryConfig:X(p,tt)?U===!0?{limit:1}:{...U,limit:1}:U,tableAlias:j,joinOn:a,nestedQueryRelation:p}),no=R`${R.identifier(j)}.${R.identifier("data")}`.as(K);Q.push({on:R`true`,table:new xo(oo.sql,{},j),alias:j,joinType:"left",lateral:!0}),F.push({dbKey:K,tsKey:K,field:no,relationTableTsKey:v,isJson:!0,selection:oo.selection})}}if(F.length===0)throw new OS({message:`No fields selected for table "${S.tsName}" ("${y}")`});let z;if(E=XT(M,E),A){let G=R`json_build_array(${R.join(F.map(({field:c,tsKey:P,isJson:Y})=>Y?R`${R.identifier(`${y}_${P}`)}.${R.identifier("data")}`:X(c,h.Aliased)?c.sql:c),R`, `)})`;if(X(A,GT))G=R`coalesce(json_agg(${G}${O.length>0?R` order by ${R.join(O,R`, `)}`:void 0}), '[]'::json)`;let V=[{dbKey:"data",tsKey:"data",field:G.as("data"),isJson:!0,relationTableTsKey:S.tsName,selection:F}];if(k!==void 0||W!==void 0||O.length>0)z=this.buildSelectQuery({table:WS(T,y),fields:{},fieldsFlat:[{path:[],field:R.raw("*")}],where:E,limit:k,offset:W,orderBy:O,setOperators:[]}),E=void 0,k=void 0,W=void 0,O=[];else z=WS(T,y);z=this.buildSelectQuery({table:X(z,wn)?z:new xo(z,{},y),fields:{},fieldsFlat:V.map(({field:c})=>({path:[],field:X(c,Xo)?bn(c,y):c})),joins:Q,where:E,limit:k,offset:W,orderBy:O,setOperators:[]})}else z=this.buildSelectQuery({table:WS(T,y),fields:{},fieldsFlat:F.map(({field:G})=>({path:[],field:X(G,Xo)?bn(G,y):G})),joins:Q,where:E,limit:k,offset:W,orderBy:O,setOperators:[]});return{tableTsKey:S.tsName,sql:z,selection:F}}}class yn{static[J]="SelectionProxyHandler";config;constructor(o){this.config={...o}}get(o,n){if(n==="_")return{...o._,selectedFields:new Proxy(o._.selectedFields,this)};if(n===Do)return{...o[Do],selectedFields:new Proxy(o[Do].selectedFields,this)};if(typeof n==="symbol")return o[n];let T=(X(o,xo)?o._.selectedFields:X(o,Sn)?o[Do].selectedFields:o)[n];if(X(T,h.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!T.isSelectionField)return T.sql;let S=T.clone();return S.isSelectionField=!0,S}if(X(T,h)){if(this.config.sqlBehavior==="sql")return T;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(T,Xo)){if(this.config.alias)return new Proxy(T,new Bt(new Proxy(T.table,new wT(this.config.alias,this.config.replaceOriginalName??!1))));return T}if(typeof T!=="object"||T===null)return T;return new Proxy(T,new yn(this.config))}}class my{static[J]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class nn{static[J]="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}from(o){let n=!!this.fields,t;if(this.fields)t=this.fields;else if(X(o,xo))t=Object.fromEntries(Object.keys(o._.selectedFields).map((T)=>[T,o[T]]));else if(X(o,cT))t=o[Do].selectedFields;else if(X(o,h))t={};else t=jM(o);return new Qy({table:o,fields:t,isPartialSelect:n,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct})}}class X$ extends my{static[J]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;constructor({table:o,fields:n,isPartialSelect:t,session:T,dialect:S,withList:f,distinct:y}){super();this.config={withList:f,table:o,fields:{...n},distinct:y,setOperators:[]},this.isPartialSelect=t,this.session=T,this.dialect=S,this._={selectedFields:n},this.tableName=df(o),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}createJoin(o){return(n,t)=>{let T=this.tableName,S=df(n);if(typeof S==="string"&&this.config.joins?.some((f)=>f.alias===S))throw new Error(`Alias "${S}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof T==="string")this.config.fields={[T]:this.config.fields};if(typeof S==="string"&&!X(n,h)){let f=X(n,xo)?n._.selectedFields:X(n,Sn)?n[Do].selectedFields:n[L.Symbol.Columns];this.config.fields[S]=f}}if(typeof t==="function")t=t(new Proxy(this.config.fields,new yn({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(([f])=>[f,!1])),this.joinsNotNullableMap[S]=!0;break}case"inner":{this.joinsNotNullableMap[S]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([f])=>[f,!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 T=typeof t==="function"?t(b0()):t;if(!gf(this.getSelectedFields(),T.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:T}),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 yn({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=o,this}having(o){if(typeof o==="function")o=o(new Proxy(this.config.fields,new yn({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 yn({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 yn({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 xo(this.getSQL(),this.config.fields,o),new yn({alias:o,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new yn({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}}class Qy extends X${static[J]="PgSelect";_prepare(o){let{session:n,config:t,dialect:T,joinsNotNullableMap:S}=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 f=_n(t.fields),y=n.prepareQuery(T.sqlToQuery(this.getSQL()),f,o,!0);return y.joinsNotNullableMap=S,y})}prepare(o){return this._prepare(o)}execute=(o)=>{return Oo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(o)})}}IM(Qy,[so]);function at(o,n){return(t,T,...S)=>{let f=[T,...S].map((y)=>({type:o,isAll:n,rightSelect:y}));for(let y of f)if(!gf(t.getSelectedFields(),y.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(f)}}var b0=()=>({union:N0,unionAll:h0,intersect:c0,intersectAll:x0,except:i0,exceptAll:v0}),N0=at("union",!1),h0=at("union",!0),c0=at("intersect",!1),x0=at("intersect",!0),i0=at("except",!1),v0=at("except",!0);class Dy{static[J]="PgQueryBuilder";dialect;dialectConfig;constructor(o){this.dialect=X(o,Xt)?o:void 0,this.dialectConfig=X(o,Xt)?void 0:o}$with(o){let n=this;return{as(t){if(typeof t==="function")t=t(n);return new Proxy(new _T(t.getSQL(),t.getSelectedFields(),o,!0),new yn({alias:o,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}}with(...o){let n=this;function t(f){return new nn({fields:f??void 0,session:void 0,dialect:n.getDialect(),withList:o})}function T(f){return new nn({fields:f??void 0,session:void 0,dialect:n.getDialect(),distinct:!0})}function S(f,y){return new nn({fields:y??void 0,session:void 0,dialect:n.getDialect(),distinct:{on:f}})}return{select:t,selectDistinct:T,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 Xt(this.dialectConfig);return this.dialect}}class Uy extends so{constructor(o,n,t){super();this.session=n,this.dialect=t,this.config={view:o}}static[J]="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)}execute=(o)=>{return Oo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(o)})}}class PS{constructor(o,n,t,T){this.table=o,this.session=n,this.dialect=t,this.withList=T}static[J]="PgUpdateBuilder";set(o){return new E$(this.table,_S(this.table,o),this.session,this.dialect,this.withList)}}class E$ extends so{constructor(o,n,t,T,S){super();this.session=t,this.dialect=T,this.config={set:n,table:o,withList:S}}static[J]="PgUpdate";config;where(o){return this.config.where=o,this}returning(o=this.config.table[L.Symbol.Columns]){return this.config.returning=_n(o),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:o,...n}=this.dialect.sqlToQuery(this.getSQL());return n}_prepare(o){return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,o,!0)}prepare(o){return this._prepare(o)}execute=(o)=>{return this._prepare().execute(o)};$dynamic(){return this}}class xT extends h{constructor(o){super(xT.buildEmbeddedCount(o.source,o.filters).queryChunks);this.params=o,this.mapWith(Number),this.session=o.session,this.sql=xT.buildCount(o.source,o.filters)}sql;static[J]="PgCountBuilder";[Symbol.toStringTag]="PgCountBuilder";session;static buildEmbeddedCount(o,n){return R`(select count(*) from ${o}${R.raw(" where ").if(n)}${n})`}static buildCount(o,n){return R`select count(*) as count from ${o}${R.raw(" where ").if(n)}${n};`}then(o,n){return Promise.resolve(this.session.count(this.sql)).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 ry{constructor(o,n,t,T,S,f,y){this.fullSchema=o,this.schema=n,this.tableNamesMap=t,this.table=T,this.tableConfig=S,this.dialect=f,this.session=y}static[J]="PgRelationalQueryBuilder";findMany(o){return new Vy(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,o?o:{},"many")}findFirst(o){return new Vy(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,o?{...o,limit:1}:{limit:1},"first")}}class Vy extends so{constructor(o,n,t,T,S,f,y,A,M){super();this.fullSchema=o,this.schema=n,this.tableNamesMap=t,this.table=T,this.tableConfig=S,this.dialect=f,this.session=y,this.config=A,this.mode=M}static[J]="PgRelationalQuery";_prepare(o){return Oo.startActiveSpan("drizzle.prepareQuery",()=>{let{query:n,builtQuery:t}=this._toSQL();return this.session.prepareQuery(t,void 0,o,!0,(T,S)=>{let f=T.map((y)=>DS(this.schema,this.tableConfig,y,n.selection,S));if(this.mode==="first")return f[0];return f})})}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}execute(){return Oo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute()})}}class By extends so{constructor(o,n,t,T){super();this.execute=o,this.sql=n,this.query=t,this.mapBatchResult=T}static[J]="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 iT{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[T,S]of Object.entries(this._.schema))this.query[T]=new ry(t.fullSchema,this._.schema,this._.tableNamesMap,t.fullSchema[T],S,o,n)}static[J]="PgDatabase";query;$with(o){let n=this;return{as(t){if(typeof t==="function")t=t(new Dy(n.dialect));return new Proxy(new _T(t.getSQL(),t.getSelectedFields(),o,!0),new yn({alias:o,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}}$count(o,n){return new xT({source:o,filters:n,session:this.session})}with(...o){let n=this;function t(M){return new nn({fields:M??void 0,session:n.session,dialect:n.dialect,withList:o})}function T(M){return new nn({fields:M??void 0,session:n.session,dialect:n.dialect,withList:o,distinct:!0})}function S(M,F){return new nn({fields:F??void 0,session:n.session,dialect:n.dialect,withList:o,distinct:{on:M}})}function f(M){return new PS(M,n.session,n.dialect,o)}function y(M){return new ZS(M,n.session,n.dialect,o)}function A(M){return new qS(M,n.session,n.dialect,o)}return{select:t,selectDistinct:T,selectDistinctOn:S,update:f,insert:y,delete:A}}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 qS(o,this.session,this.dialect)}refreshMaterializedView(o){return new Uy(o,this.session,this.dialect)}execute(o){let n=typeof o==="string"?R.raw(o):o.getSQL(),t=this.dialect.sqlToQuery(n),T=this.session.prepareQuery(t,void 0,void 0,!1);return new By(()=>T.execute(),n,t,(S)=>T.mapResult(S,!0))}transaction(o,n){return this.session.transaction(o,n)}}class Y${constructor(o,n){this.unique=o,this.name=n}static[J]="PgIndexBuilderOn";on(...o){return new eS(o.map((n)=>{if(X(n,h))return n;n=n;let t=new OT(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 eS(o.map((n)=>{if(X(n,h))return n;n=n;let t=new OT(n.name,!!n.keyAsName,n.columnType,n.indexConfig);return n.indexConfig=n.defaultConfig,t}),this.unique,!0,this.name)}using(o,...n){return new eS(n.map((t)=>{if(X(t,h))return t;t=t;let T=new OT(t.name,!!t.keyAsName,t.columnType,t.indexConfig);return t.indexConfig=JSON.parse(JSON.stringify(t.defaultConfig)),T}),this.unique,!0,this.name,o)}}class eS{static[J]="PgIndexBuilder";config;constructor(o,n,t,T,S="btree"){this.config={name:T,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 G$(this.config,o)}}class G${static[J]="PgIndex";config;constructor(o,n){this.config={...o,table:n}}}function Cy(o){return new Y$(!0,o)}class Ly{constructor(o){this.query=o}getQuery(){return this.query}mapResult(o,n){return o}static[J]="PgPreparedQuery";joinsNotNullableMap}class Iy{constructor(o){this.dialect=o}static[J]="PgSession";execute(o){return Oo.startActiveSpan("drizzle.operation",()=>{return Oo.startActiveSpan("drizzle.prepareQuery",()=>{return this.prepareQuery(this.dialect.sqlToQuery(o),void 0,void 0,!1)}).execute()})}all(o){return this.prepareQuery(this.dialect.sqlToQuery(o),void 0,void 0,!1).all()}async count(o){let n=await this.execute(o);return Number(n[0].count)}}class jy extends iT{constructor(o,n,t,T=0){super(o,n,t);this.schema=t,this.nestedIndex=T}static[J]="PgTransaction";rollback(){throw new Pf}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 R.raw(n.join(" "))}setTransaction(o){return this.session.execute(R`set transaction ${this.getTransactionConfigSQL(o)}`)}}class z$ extends Ly{constructor(o,n,t,T,S,f,y){super({sql:n,params:t});this.client=o,this.queryString=n,this.params=t,this.logger=T,this.fields=S,this._isResponseInArrayMode=f,this.customResultMapper=y}static[J]="PostgresJsPreparedQuery";async execute(o={}){return Oo.startActiveSpan("drizzle.execute",async(n)=>{let t=qf(this.params,o);n?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(t)}),this.logger.logQuery(this.queryString,t);let{fields:T,queryString:S,client:f,joinsNotNullableMap:y,customResultMapper:A}=this;if(!T&&!A)return Oo.startActiveSpan("drizzle.driver.execute",()=>{return f.unsafe(S,t)});let M=await Oo.startActiveSpan("drizzle.driver.execute",()=>{return n?.setAttributes({"drizzle.query.text":S,"drizzle.query.params":JSON.stringify(t)}),f.unsafe(S,t).values()});return Oo.startActiveSpan("drizzle.mapResponse",()=>{return A?A(M):M.map((F)=>LM(T,F,y))})})}all(o={}){return Oo.startActiveSpan("drizzle.execute",async(n)=>{let t=qf(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 vT extends Iy{constructor(o,n,t,T={}){super(n);this.client=o,this.schema=t,this.options=T,this.logger=T.logger??new lf}static[J]="PostgresJsSession";logger;prepareQuery(o,n,t,T,S){return new z$(this.client,o.sql,o.params,this.logger,n,T,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 T=new vT(t,this.dialect,this.schema,this.options),S=new by(this.dialect,T,this.schema);if(n)await S.setTransaction(n);return o(S)})}}class by extends jy{constructor(o,n,t,T=0){super(o,n,t,T);this.session=n}static[J]="PostgresJsTransaction";transaction(o){return this.session.client.savepoint((n)=>{let t=new vT(n,this.dialect,this.schema,this.session.options),T=new by(this.dialect,t,this.schema);return o(T)})}}class H$ extends iT{static[J]="PostgresJsDatabase"}function st(o,n={}){let t=(M)=>M;for(let M of["1184","1082","1083","1114"])o.options.parsers[M]=t,o.options.serializers[M]=t;o.options.serializers["114"]=t,o.options.serializers["3802"]=t;let T=new Xt({casing:n.casing}),S;if(n.logger===!0)S=new ef;else if(n.logger!==!1)S=n.logger;let f;if(n.schema){let M=Lk(n.schema,jk);f={fullSchema:n.schema,schema:M.tables,tableNamesMap:M.tableNamesMap}}let y=new vT(o,T,f,{logger:S}),A=new H$(T,y,f);return A.$client=o,A}function lS(...o){if(typeof o[0]==="string"){let n=ut(o[0]);return st(n,o[1])}if(bM(o[0])){let{connection:n,client:t,...T}=o[0];if(t)return st(t,T);if(typeof n==="object"&&n.url!==void 0){let{url:f,...y}=n,A=ut(f,y);return st(A,T)}let S=ut(n);return st(S,T)}return st(o[0],o[1])}((o)=>{function n(t){return st({},t)}o.mock=n})(lS||(lS={}));var hy={};VJ(hy,{users:()=>Et,userChanges:()=>q0,untrackedUserColumnNames:()=>p0,twoFactorMethod:()=>U$,trackedUserColumnName:()=>D$,trackableUserColumnNames:()=>Q$,role:()=>m$,players:()=>Ny,passwordResetAttempts:()=>P0,loginHistory:()=>Z0,games:()=>gS,banishedIps:()=>pT});var m$=$S("role",["admin","user"]),Et=nt("users",{id:kn().primaryKey().defaultRandom(),username:io({length:16}).notNull(),email:io({length:254}).notNull(),hash:io({length:64}).notNull(),salt:io({length:36}).notNull(),createdAt:Dn({withTimezone:!0}).notNull().defaultNow(),createdIp:io({length:45}).notNull(),isActive:ET().notNull().default(!1),verifiedAt:Dn({withTimezone:!0}),userRole:m$().default("user")},(o)=>({usersUsernameUnique:Cy().on(o.username),usersEmailUnique:Cy().on(o.email)})),p0=["id","createdAt","createdIp","isActive","salt","verifiedAt"],Q$=["username","email","hash","userRole"],D$=$S("trackedUserColumnName",Q$),q0=nt("userChanges",{id:kn().primaryKey().defaultRandom(),userId:kn().notNull().references(()=>Et.id),changedAt:Dn({withTimezone:!0}).notNull().defaultNow(),changedIp:io({length:45}).notNull(),changedColumn:D$().notNull(),oldValue:io({length:255}),newValue:io({length:255})}),gS=nt("games",{id:kn("id").primaryKey().defaultRandom()}),Ny=nt("players",{userId:kn().notNull().references(()=>Et.id),gameId:kn().notNull().references(()=>gS.id),score:XS().notNull()},(o)=>({pk:Uk({columns:[o.userId,o.gameId]})})),Z0=nt("loginHistory",{id:kn().primaryKey().defaultRandom(),userId:kn().references(()=>Et.id),loginTime:Dn({withTimezone:!0}).notNull().defaultNow(),ipAddress:io({length:45}).notNull(),userAgent:io({length:1024}),successful:ET().notNull().default(!1)}),U$=$S("twoFactorMethod",["email","phone"]),P0=nt("passwordResetAttempts",{id:kn().primaryKey().defaultRandom(),userId:kn().notNull().references(()=>Et.id),requestedIp:io({length:45}).notNull(),requestedAt:Dn({withTimezone:!0}).notNull().defaultNow(),succeededIp:io({length:45}),succeededAt:Dn({withTimezone:!0}),verificationMethod:U$().notNull()}),pT=nt("banishedIps",{ip:io({length:45}).primaryKey(),reason:io({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 cy{options;sql;drizzle;observers=new Map;async setupTriggersAndNotifications(){await this.sql.file(e0.resolve(__dirname,"notify_update.sql"));let o=[On(Et),On(gS),On(Ny)];await this.sql`SELECT create_notify_triggers(${this.sql.array(o)})`,await this.sql.listen("table_update",(n)=>{let t=n.split(","),T=t[0],S=t[1],f=`${T}("${S}")`;if(this.observers.has(f))this.observers.get(f).next(f)})}constructor(o=!1,n={host:Cn.POSTGRES_HOST,port:Cn.POSTGRES_PORT,user:Cn.POSTGRES_USER,password:Cn.POSTGRES_PASSWORD,database:Cn.POSTGRES_DATABASE}){this.options=n,this.sql=ut(n),this.drizzle=lS(this.sql,{schema:hy,logger:o})}observe(o,n){if(!this.observers.has(o))this.observers.set(o,new s);this.observers.get(o).subscribe("SINGLETON",n)}}var dS={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"},xy=sy(dS).map(([o])=>zo.literal(Number(o))),l0=zo.union([xy[0],xy[1],...xy]),V$=zo.tuple([l0,zo.string()]);var C$=new Vf,{logger:En}=C$;En.info(" ready");var iy=B$(import.meta.dir,"..","app"),a0=new cy({logQuery(o,n){En.info("\uD83D\uDCDD query",o,n)}});u0({hostname:"0.0.0.0",port:Cn.FRONTEND_PORT??3333,...uk??void 0,async fetch(o,n){try{let t=new Date,T=new URL(o.url),S=n.requestIP(o)?.address??"??";En.info(t,S,o.method,T.pathname);let[f]=await a0.drizzle.select({banishedUntil:pT.banishedUntil}).from(pT).where(Ct(pT.ip,S)).limit(1),y=f?.banishedUntil===null,A=f?.banishedUntil&&f.banishedUntil>t;if(y||A)throw En.info(`\uD83D\uDE45 request from banned ip ${S}`),[403,S];if(T.pathname==="/")return new Response(Bun.file(B$(iy,"index.html")));if(T.pathname==="/index.html")return Response.redirect("/");let M=g0(iy,T.pathname),F=d0(M);if(!F.startsWith(iy))throw[403,"Access Denied"];if(!await r$(F).exists())return Response.redirect("/");return new Response(r$(F))}catch(t){let T=V$.safeParse(t);if(T.success){let[S,f]=T.data,A=`${dS[S]}. ${f}`;return En.info(`\u274C ${S}: ${A}`),new Response(A,{status:S})}if(t instanceof Error)En.error(t.message);else{let S=Ut(t);En.error("frontend server threw",S)}return new Response(dS[500],{status:500})}}});function vy(){En.info("\uD83D\uDEEC frontend server exiting"),process.exit(0)}process.on("SIGINT",()=>{En.info("\u2757 received SIGINT; exiting gracefully"),vy()});process.on("SIGTERM",()=>{En.info("\u2757 received SIGTERM; exiting gracefully"),vy()});process.on("exit",()=>{En.info("\u2757 received exit; exiting gracefully"),vy()});En.info(`\uD83D\uDEEB frontend server running at http://localhost:${Cn.FRONTEND_PORT}/`);C$.emit("alive");
29
+ `;await n.execute(R`CREATE SCHEMA IF NOT EXISTS ${R.identifier(S)}`),await n.execute(f);let A=(await n.all(R`select id, hash, created_at from ${R.identifier(S)}.${R.identifier(T)} order by created_at desc limit 1`))[0];await n.transaction(async(M)=>{for await(let F of o)if(!A||Number(A.created_at)<F.folderMillis){for(let k of F.sql)await M.execute(R.raw(k));await M.execute(R`insert into ${R.identifier(S)}.${R.identifier(T)} ("hash", "created_at") values(${F.hash}, ${F.folderMillis})`)}})}escapeName(o){return`"${o}"`}escapeParam(o){return`\$${o+1}`}escapeString(o){return`'${o.replace(/'/g,"''")}'`}buildWithCTE(o){if(!o?.length)return;let n=[R`with `];for(let[t,T]of o.entries())if(n.push(R`${R.identifier(T._.alias)} as (${T._.sql})`),t<o.length-1)n.push(R`, `);return n.push(R` `),R.join(n)}buildDeleteQuery({table:o,where:n,returning:t,withList:T}){let S=this.buildWithCTE(T),f=t?R` returning ${this.buildSelection(t,{isSingleTable:!0})}`:void 0,y=n?R` where ${n}`:void 0;return R`${S}delete from ${o}${y}${f}`}buildUpdateSet(o,n){let t=o[L.Symbol.Columns],T=Object.keys(t).filter((f)=>n[f]!==void 0||t[f]?.onUpdateFn!==void 0),S=T.length;return R.join(T.flatMap((f,y)=>{let A=t[f],M=n[f]??R.param(A.onUpdateFn(),A),F=R`${R.identifier(this.casing.getColumnCasing(A))} = ${M}`;if(y<S-1)return[F,R.raw(", ")];return[F]}))}buildUpdateQuery({table:o,set:n,where:t,returning:T,withList:S}){let f=this.buildWithCTE(S),y=this.buildUpdateSet(o,n),A=T?R` returning ${this.buildSelection(T,{isSingleTable:!0})}`:void 0,M=t?R` where ${t}`:void 0;return R`${f}update ${o} set ${y}${M}${A}`}buildSelection(o,{isSingleTable:n=!1}={}){let t=o.length,T=o.flatMap(({field:S},f)=>{let y=[];if(X(S,h.Aliased)&&S.isSelectionField)y.push(R.identifier(S.fieldAlias));else if(X(S,h.Aliased)||X(S,h)){let A=X(S,h.Aliased)?S.sql:S;if(n)y.push(new h(A.queryChunks.map((M)=>{if(X(M,r))return R.identifier(this.casing.getColumnCasing(M));return M})));else y.push(A);if(X(S,h.Aliased))y.push(R` as ${R.identifier(S.fieldAlias)}`)}else if(X(S,Xo))if(n)y.push(R.identifier(this.casing.getColumnCasing(S)));else y.push(S);if(f<t-1)y.push(R`, `);return y});return R.join(T)}buildSelectQuery({withList:o,fields:n,fieldsFlat:t,where:T,having:S,table:f,joins:y,orderBy:A,groupBy:M,limit:F,offset:k,lockingClause:W,distinct:O,setOperators:E}){let Q=t??_n(n);for(let oo of Q)if(X(oo.field,Xo)&&On(oo.field.table)!==(X(f,xo)?f._.alias:X(f,cT)?f[Do].name:X(f,h)?void 0:On(f))&&!((no)=>y?.some(({alias:_o})=>_o===(no[L.Symbol.IsAlias]?On(no):no[L.Symbol.BaseName])))(oo.field.table)){let no=On(oo.field.table);throw new Error(`Your "${oo.path.join("->")}" field references a column "${no}"."${oo.field.name}", but the table "${no}" is not part of the query! Did you forget to join it?`)}let z=!y||y.length===0,G=this.buildWithCTE(o),V;if(O)V=O===!0?R` distinct`:R` distinct on (${R.join(O.on,R`, `)})`;let x=this.buildSelection(Q,{isSingleTable:z}),c=(()=>{if(X(f,L)&&f[L.Symbol.OriginalName]!==f[L.Symbol.Name]){let oo=R`${R.identifier(f[L.Symbol.OriginalName])}`;if(f[L.Symbol.Schema])oo=R`${R.identifier(f[L.Symbol.Schema])}.${oo}`;return R`${oo} ${R.identifier(f[L.Symbol.Name])}`}return f})(),P=[];if(y)for(let[oo,no]of y.entries()){if(oo===0)P.push(R` `);let _o=no.table,An=no.lateral?R` lateral`:void 0;if(X(_o,wn)){let H=_o[wn.Symbol.Name],i=_o[wn.Symbol.Schema],fo=_o[wn.Symbol.OriginalName],Ro=H===fo?void 0:no.alias;P.push(R`${R.raw(no.joinType)} join${An} ${i?R`${R.identifier(i)}.`:void 0}${R.identifier(fo)}${Ro&&R` ${R.identifier(Ro)}`} on ${no.on}`)}else if(X(_o,Sn)){let H=_o[Do].name,i=_o[Do].schema,fo=_o[Do].originalName,Ro=H===fo?void 0:no.alias;P.push(R`${R.raw(no.joinType)} join${An} ${i?R`${R.identifier(i)}.`:void 0}${R.identifier(fo)}${Ro&&R` ${R.identifier(Ro)}`} on ${no.on}`)}else P.push(R`${R.raw(no.joinType)} join${An} ${_o} on ${no.on}`);if(oo<y.length-1)P.push(R` `)}let Y=R.join(P),K=T?R` where ${T}`:void 0,U=S?R` having ${S}`:void 0,p;if(A&&A.length>0)p=R` order by ${R.join(A,R`, `)}`;let b;if(M&&M.length>0)b=R` group by ${R.join(M,R`, `)}`;let w=typeof F==="object"||typeof F==="number"&&F>=0?R` limit ${F}`:void 0,v=k?R` offset ${k}`:void 0,j=R.empty();if(W){let oo=R` for ${R.raw(W.strength)}`;if(W.config.of)oo.append(R` of ${R.join(Array.isArray(W.config.of)?W.config.of:[W.config.of],R`, `)}`);if(W.config.noWait)oo.append(R` no wait`);else if(W.config.skipLocked)oo.append(R` skip locked`);j.append(oo)}let a=R`${G}select${V} ${x} from ${c}${Y}${K}${b}${U}${p}${w}${v}${j}`;if(E.length>0)return this.buildSetOperations(a,E);return a}buildSetOperations(o,n){let[t,...T]=n;if(!t)throw new Error("Cannot pass undefined values to any set operator");if(T.length===0)return this.buildSetOperationQuery({leftSelect:o,setOperator:t});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:o,setOperator:t}),T)}buildSetOperationQuery({leftSelect:o,setOperator:{type:n,isAll:t,rightSelect:T,limit:S,orderBy:f,offset:y}}){let A=R`(${o.getSQL()}) `,M=R`(${T.getSQL()})`,F;if(f&&f.length>0){let E=[];for(let Q of f)if(X(Q,r))E.push(R.identifier(Q.name));else if(X(Q,h)){for(let z=0;z<Q.queryChunks.length;z++){let G=Q.queryChunks[z];if(X(G,r))Q.queryChunks[z]=R.identifier(G.name)}E.push(R`${Q}`)}else E.push(R`${Q}`);F=R` order by ${R.join(E,R`, `)} `}let k=typeof S==="object"||typeof S==="number"&&S>=0?R` limit ${S}`:void 0,W=R.raw(`${n} ${t?"all ":""}`),O=y?R` offset ${y}`:void 0;return R`${A}${W}${M}${F}${k}${O}`}buildInsertQuery({table:o,values:n,onConflict:t,returning:T,withList:S}){let f=[],y=o[L.Symbol.Columns],A=Object.entries(y).filter(([E,Q])=>!Q.shouldDisableInsert()),M=A.map(([,E])=>R.identifier(this.casing.getColumnCasing(E)));for(let[E,Q]of n.entries()){let z=[];for(let[G,V]of A){let x=Q[G];if(x===void 0||X(x,Fn)&&x.value===void 0)if(V.defaultFn!==void 0){let c=V.defaultFn(),P=X(c,h)?c:R.param(c,V);z.push(P)}else if(!V.default&&V.onUpdateFn!==void 0){let c=V.onUpdateFn(),P=X(c,h)?c:R.param(c,V);z.push(P)}else z.push(R`default`);else z.push(x)}if(f.push(z),E<n.length-1)f.push(R`, `)}let F=this.buildWithCTE(S),k=R.join(f),W=T?R` returning ${this.buildSelection(T,{isSingleTable:!0})}`:void 0,O=t?R` on conflict ${t}`:void 0;return R`${F}insert into ${o} ${M} values ${k}${O}${W}`}buildRefreshMaterializedViewQuery({view:o,concurrently:n,withNoData:t}){let T=n?R` concurrently`:void 0,S=t?R` with no data`:void 0;return R`refresh materialized view${T} ${o}${S}`}prepareTyping(o){if(X(o,YS)||X(o,ES))return"json";else if(X(o,GS))return"decimal";else if(X(o,zS))return"time";else if(X(o,HS)||X(o,mS))return"timestamp";else if(X(o,wS)||X(o,KS))return"date";else if(X(o,QS))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:T,tableConfig:S,queryConfig:f,tableAlias:y,nestedQueryRelation:A,joinOn:M}){let F=[],k,W,O=[],E,Q=[];if(f===!0)F=Object.entries(S.columns).map(([V,x])=>({dbKey:x.name,tsKey:V,field:bn(x,y),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let G=Object.fromEntries(Object.entries(S.columns).map(([K,U])=>[K,bn(U,y)]));if(f.where){let K=typeof f.where==="function"?f.where(G,Bk()):f.where;E=K&&KT(K,y)}let V=[],x=[];if(f.columns){let K=!1;for(let[U,p]of Object.entries(f.columns)){if(p===void 0)continue;if(U in S.columns){if(!K&&p===!0)K=!0;x.push(U)}}if(x.length>0)x=K?x.filter((U)=>f.columns?.[U]===!0):Object.keys(S.columns).filter((U)=>!x.includes(U))}else x=Object.keys(S.columns);for(let K of x){let U=S.columns[K];V.push({tsKey:K,value:U})}let c=[];if(f.with)c=Object.entries(f.with).filter((K)=>!!K[1]).map(([K,U])=>({tsKey:K,queryConfig:U,relation:S.relations[K]}));let P;if(f.extras){P=typeof f.extras==="function"?f.extras(G,{sql:R}):f.extras;for(let[K,U]of Object.entries(P))V.push({tsKey:K,value:Zf(U,y)})}for(let{tsKey:K,value:U}of V)F.push({dbKey:X(U,h.Aliased)?U.fieldAlias:S.columns[K].name,tsKey:K,field:X(U,Xo)?bn(U,y):U,relationTableTsKey:void 0,isJson:!1,selection:[]});let Y=typeof f.orderBy==="function"?f.orderBy(G,Ck()):f.orderBy??[];if(!Array.isArray(Y))Y=[Y];O=Y.map((K)=>{if(X(K,Xo))return bn(K,y);return KT(K,y)}),k=f.limit,W=f.offset;for(let{tsKey:K,queryConfig:U,relation:p}of c){let b=Ik(n,t,p),w=kt(p.referencedTable),v=t[w],j=`${y}_${K}`,a=XT(...b.fields.map((_o,An)=>Ct(bn(b.references[An],j),bn(_o,y)))),oo=this.buildRelationalQueryWithoutPK({fullSchema:o,schema:n,tableNamesMap:t,table:o[v],tableConfig:n[v],queryConfig:X(p,tt)?U===!0?{limit:1}:{...U,limit:1}:U,tableAlias:j,joinOn:a,nestedQueryRelation:p}),no=R`${R.identifier(j)}.${R.identifier("data")}`.as(K);Q.push({on:R`true`,table:new xo(oo.sql,{},j),alias:j,joinType:"left",lateral:!0}),F.push({dbKey:K,tsKey:K,field:no,relationTableTsKey:v,isJson:!0,selection:oo.selection})}}if(F.length===0)throw new OS({message:`No fields selected for table "${S.tsName}" ("${y}")`});let z;if(E=XT(M,E),A){let G=R`json_build_array(${R.join(F.map(({field:c,tsKey:P,isJson:Y})=>Y?R`${R.identifier(`${y}_${P}`)}.${R.identifier("data")}`:X(c,h.Aliased)?c.sql:c),R`, `)})`;if(X(A,GT))G=R`coalesce(json_agg(${G}${O.length>0?R` order by ${R.join(O,R`, `)}`:void 0}), '[]'::json)`;let V=[{dbKey:"data",tsKey:"data",field:G.as("data"),isJson:!0,relationTableTsKey:S.tsName,selection:F}];if(k!==void 0||W!==void 0||O.length>0)z=this.buildSelectQuery({table:WS(T,y),fields:{},fieldsFlat:[{path:[],field:R.raw("*")}],where:E,limit:k,offset:W,orderBy:O,setOperators:[]}),E=void 0,k=void 0,W=void 0,O=[];else z=WS(T,y);z=this.buildSelectQuery({table:X(z,wn)?z:new xo(z,{},y),fields:{},fieldsFlat:V.map(({field:c})=>({path:[],field:X(c,Xo)?bn(c,y):c})),joins:Q,where:E,limit:k,offset:W,orderBy:O,setOperators:[]})}else z=this.buildSelectQuery({table:WS(T,y),fields:{},fieldsFlat:F.map(({field:G})=>({path:[],field:X(G,Xo)?bn(G,y):G})),joins:Q,where:E,limit:k,offset:W,orderBy:O,setOperators:[]});return{tableTsKey:S.tsName,sql:z,selection:F}}}class yn{static[J]="SelectionProxyHandler";config;constructor(o){this.config={...o}}get(o,n){if(n==="_")return{...o._,selectedFields:new Proxy(o._.selectedFields,this)};if(n===Do)return{...o[Do],selectedFields:new Proxy(o[Do].selectedFields,this)};if(typeof n==="symbol")return o[n];let T=(X(o,xo)?o._.selectedFields:X(o,Sn)?o[Do].selectedFields:o)[n];if(X(T,h.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!T.isSelectionField)return T.sql;let S=T.clone();return S.isSelectionField=!0,S}if(X(T,h)){if(this.config.sqlBehavior==="sql")return T;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(T,Xo)){if(this.config.alias)return new Proxy(T,new Bt(new Proxy(T.table,new wT(this.config.alias,this.config.replaceOriginalName??!1))));return T}if(typeof T!=="object"||T===null)return T;return new Proxy(T,new yn(this.config))}}class my{static[J]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class nn{static[J]="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}from(o){let n=!!this.fields,t;if(this.fields)t=this.fields;else if(X(o,xo))t=Object.fromEntries(Object.keys(o._.selectedFields).map((T)=>[T,o[T]]));else if(X(o,cT))t=o[Do].selectedFields;else if(X(o,h))t={};else t=jM(o);return new Qy({table:o,fields:t,isPartialSelect:n,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct})}}class X$ extends my{static[J]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;constructor({table:o,fields:n,isPartialSelect:t,session:T,dialect:S,withList:f,distinct:y}){super();this.config={withList:f,table:o,fields:{...n},distinct:y,setOperators:[]},this.isPartialSelect=t,this.session=T,this.dialect=S,this._={selectedFields:n},this.tableName=df(o),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}createJoin(o){return(n,t)=>{let T=this.tableName,S=df(n);if(typeof S==="string"&&this.config.joins?.some((f)=>f.alias===S))throw new Error(`Alias "${S}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof T==="string")this.config.fields={[T]:this.config.fields};if(typeof S==="string"&&!X(n,h)){let f=X(n,xo)?n._.selectedFields:X(n,Sn)?n[Do].selectedFields:n[L.Symbol.Columns];this.config.fields[S]=f}}if(typeof t==="function")t=t(new Proxy(this.config.fields,new yn({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(([f])=>[f,!1])),this.joinsNotNullableMap[S]=!0;break}case"inner":{this.joinsNotNullableMap[S]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([f])=>[f,!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 T=typeof t==="function"?t(N0()):t;if(!gf(this.getSelectedFields(),T.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:T}),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 yn({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=o,this}having(o){if(typeof o==="function")o=o(new Proxy(this.config.fields,new yn({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 yn({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 yn({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 xo(this.getSQL(),this.config.fields,o),new yn({alias:o,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new yn({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}}class Qy extends X${static[J]="PgSelect";_prepare(o){let{session:n,config:t,dialect:T,joinsNotNullableMap:S}=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 f=_n(t.fields),y=n.prepareQuery(T.sqlToQuery(this.getSQL()),f,o,!0);return y.joinsNotNullableMap=S,y})}prepare(o){return this._prepare(o)}execute=(o)=>{return Oo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(o)})}}IM(Qy,[so]);function at(o,n){return(t,T,...S)=>{let f=[T,...S].map((y)=>({type:o,isAll:n,rightSelect:y}));for(let y of f)if(!gf(t.getSelectedFields(),y.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(f)}}var N0=()=>({union:h0,unionAll:c0,intersect:x0,intersectAll:i0,except:v0,exceptAll:p0}),h0=at("union",!1),c0=at("union",!0),x0=at("intersect",!1),i0=at("intersect",!0),v0=at("except",!1),p0=at("except",!0);class Dy{static[J]="PgQueryBuilder";dialect;dialectConfig;constructor(o){this.dialect=X(o,Xt)?o:void 0,this.dialectConfig=X(o,Xt)?void 0:o}$with(o){let n=this;return{as(t){if(typeof t==="function")t=t(n);return new Proxy(new _T(t.getSQL(),t.getSelectedFields(),o,!0),new yn({alias:o,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}}with(...o){let n=this;function t(f){return new nn({fields:f??void 0,session:void 0,dialect:n.getDialect(),withList:o})}function T(f){return new nn({fields:f??void 0,session:void 0,dialect:n.getDialect(),distinct:!0})}function S(f,y){return new nn({fields:y??void 0,session:void 0,dialect:n.getDialect(),distinct:{on:f}})}return{select:t,selectDistinct:T,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 Xt(this.dialectConfig);return this.dialect}}class Uy extends so{constructor(o,n,t){super();this.session=n,this.dialect=t,this.config={view:o}}static[J]="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)}execute=(o)=>{return Oo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(o)})}}class PS{constructor(o,n,t,T){this.table=o,this.session=n,this.dialect=t,this.withList=T}static[J]="PgUpdateBuilder";set(o){return new E$(this.table,_S(this.table,o),this.session,this.dialect,this.withList)}}class E$ extends so{constructor(o,n,t,T,S){super();this.session=t,this.dialect=T,this.config={set:n,table:o,withList:S}}static[J]="PgUpdate";config;where(o){return this.config.where=o,this}returning(o=this.config.table[L.Symbol.Columns]){return this.config.returning=_n(o),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:o,...n}=this.dialect.sqlToQuery(this.getSQL());return n}_prepare(o){return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,o,!0)}prepare(o){return this._prepare(o)}execute=(o)=>{return this._prepare().execute(o)};$dynamic(){return this}}class xT extends h{constructor(o){super(xT.buildEmbeddedCount(o.source,o.filters).queryChunks);this.params=o,this.mapWith(Number),this.session=o.session,this.sql=xT.buildCount(o.source,o.filters)}sql;static[J]="PgCountBuilder";[Symbol.toStringTag]="PgCountBuilder";session;static buildEmbeddedCount(o,n){return R`(select count(*) from ${o}${R.raw(" where ").if(n)}${n})`}static buildCount(o,n){return R`select count(*) as count from ${o}${R.raw(" where ").if(n)}${n};`}then(o,n){return Promise.resolve(this.session.count(this.sql)).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 ry{constructor(o,n,t,T,S,f,y){this.fullSchema=o,this.schema=n,this.tableNamesMap=t,this.table=T,this.tableConfig=S,this.dialect=f,this.session=y}static[J]="PgRelationalQueryBuilder";findMany(o){return new Vy(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,o?o:{},"many")}findFirst(o){return new Vy(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,o?{...o,limit:1}:{limit:1},"first")}}class Vy extends so{constructor(o,n,t,T,S,f,y,A,M){super();this.fullSchema=o,this.schema=n,this.tableNamesMap=t,this.table=T,this.tableConfig=S,this.dialect=f,this.session=y,this.config=A,this.mode=M}static[J]="PgRelationalQuery";_prepare(o){return Oo.startActiveSpan("drizzle.prepareQuery",()=>{let{query:n,builtQuery:t}=this._toSQL();return this.session.prepareQuery(t,void 0,o,!0,(T,S)=>{let f=T.map((y)=>DS(this.schema,this.tableConfig,y,n.selection,S));if(this.mode==="first")return f[0];return f})})}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}execute(){return Oo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute()})}}class By extends so{constructor(o,n,t,T){super();this.execute=o,this.sql=n,this.query=t,this.mapBatchResult=T}static[J]="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 iT{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[T,S]of Object.entries(this._.schema))this.query[T]=new ry(t.fullSchema,this._.schema,this._.tableNamesMap,t.fullSchema[T],S,o,n)}static[J]="PgDatabase";query;$with(o){let n=this;return{as(t){if(typeof t==="function")t=t(new Dy(n.dialect));return new Proxy(new _T(t.getSQL(),t.getSelectedFields(),o,!0),new yn({alias:o,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}}$count(o,n){return new xT({source:o,filters:n,session:this.session})}with(...o){let n=this;function t(M){return new nn({fields:M??void 0,session:n.session,dialect:n.dialect,withList:o})}function T(M){return new nn({fields:M??void 0,session:n.session,dialect:n.dialect,withList:o,distinct:!0})}function S(M,F){return new nn({fields:F??void 0,session:n.session,dialect:n.dialect,withList:o,distinct:{on:M}})}function f(M){return new PS(M,n.session,n.dialect,o)}function y(M){return new ZS(M,n.session,n.dialect,o)}function A(M){return new qS(M,n.session,n.dialect,o)}return{select:t,selectDistinct:T,selectDistinctOn:S,update:f,insert:y,delete:A}}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 qS(o,this.session,this.dialect)}refreshMaterializedView(o){return new Uy(o,this.session,this.dialect)}execute(o){let n=typeof o==="string"?R.raw(o):o.getSQL(),t=this.dialect.sqlToQuery(n),T=this.session.prepareQuery(t,void 0,void 0,!1);return new By(()=>T.execute(),n,t,(S)=>T.mapResult(S,!0))}transaction(o,n){return this.session.transaction(o,n)}}class Y${constructor(o,n){this.unique=o,this.name=n}static[J]="PgIndexBuilderOn";on(...o){return new eS(o.map((n)=>{if(X(n,h))return n;n=n;let t=new OT(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 eS(o.map((n)=>{if(X(n,h))return n;n=n;let t=new OT(n.name,!!n.keyAsName,n.columnType,n.indexConfig);return n.indexConfig=n.defaultConfig,t}),this.unique,!0,this.name)}using(o,...n){return new eS(n.map((t)=>{if(X(t,h))return t;t=t;let T=new OT(t.name,!!t.keyAsName,t.columnType,t.indexConfig);return t.indexConfig=JSON.parse(JSON.stringify(t.defaultConfig)),T}),this.unique,!0,this.name,o)}}class eS{static[J]="PgIndexBuilder";config;constructor(o,n,t,T,S="btree"){this.config={name:T,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 G$(this.config,o)}}class G${static[J]="PgIndex";config;constructor(o,n){this.config={...o,table:n}}}function Cy(o){return new Y$(!0,o)}class Ly{constructor(o){this.query=o}getQuery(){return this.query}mapResult(o,n){return o}static[J]="PgPreparedQuery";joinsNotNullableMap}class Iy{constructor(o){this.dialect=o}static[J]="PgSession";execute(o){return Oo.startActiveSpan("drizzle.operation",()=>{return Oo.startActiveSpan("drizzle.prepareQuery",()=>{return this.prepareQuery(this.dialect.sqlToQuery(o),void 0,void 0,!1)}).execute()})}all(o){return this.prepareQuery(this.dialect.sqlToQuery(o),void 0,void 0,!1).all()}async count(o){let n=await this.execute(o);return Number(n[0].count)}}class jy extends iT{constructor(o,n,t,T=0){super(o,n,t);this.schema=t,this.nestedIndex=T}static[J]="PgTransaction";rollback(){throw new Pf}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 R.raw(n.join(" "))}setTransaction(o){return this.session.execute(R`set transaction ${this.getTransactionConfigSQL(o)}`)}}class z$ extends Ly{constructor(o,n,t,T,S,f,y){super({sql:n,params:t});this.client=o,this.queryString=n,this.params=t,this.logger=T,this.fields=S,this._isResponseInArrayMode=f,this.customResultMapper=y}static[J]="PostgresJsPreparedQuery";async execute(o={}){return Oo.startActiveSpan("drizzle.execute",async(n)=>{let t=qf(this.params,o);n?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(t)}),this.logger.logQuery(this.queryString,t);let{fields:T,queryString:S,client:f,joinsNotNullableMap:y,customResultMapper:A}=this;if(!T&&!A)return Oo.startActiveSpan("drizzle.driver.execute",()=>{return f.unsafe(S,t)});let M=await Oo.startActiveSpan("drizzle.driver.execute",()=>{return n?.setAttributes({"drizzle.query.text":S,"drizzle.query.params":JSON.stringify(t)}),f.unsafe(S,t).values()});return Oo.startActiveSpan("drizzle.mapResponse",()=>{return A?A(M):M.map((F)=>LM(T,F,y))})})}all(o={}){return Oo.startActiveSpan("drizzle.execute",async(n)=>{let t=qf(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 vT extends Iy{constructor(o,n,t,T={}){super(n);this.client=o,this.schema=t,this.options=T,this.logger=T.logger??new lf}static[J]="PostgresJsSession";logger;prepareQuery(o,n,t,T,S){return new z$(this.client,o.sql,o.params,this.logger,n,T,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 T=new vT(t,this.dialect,this.schema,this.options),S=new by(this.dialect,T,this.schema);if(n)await S.setTransaction(n);return o(S)})}}class by extends jy{constructor(o,n,t,T=0){super(o,n,t,T);this.session=n}static[J]="PostgresJsTransaction";transaction(o){return this.session.client.savepoint((n)=>{let t=new vT(n,this.dialect,this.schema,this.session.options),T=new by(this.dialect,t,this.schema);return o(T)})}}class H$ extends iT{static[J]="PostgresJsDatabase"}function st(o,n={}){let t=(M)=>M;for(let M of["1184","1082","1083","1114"])o.options.parsers[M]=t,o.options.serializers[M]=t;o.options.serializers["114"]=t,o.options.serializers["3802"]=t;let T=new Xt({casing:n.casing}),S;if(n.logger===!0)S=new ef;else if(n.logger!==!1)S=n.logger;let f;if(n.schema){let M=Lk(n.schema,jk);f={fullSchema:n.schema,schema:M.tables,tableNamesMap:M.tableNamesMap}}let y=new vT(o,T,f,{logger:S}),A=new H$(T,y,f);return A.$client=o,A}function lS(...o){if(typeof o[0]==="string"){let n=ut(o[0]);return st(n,o[1])}if(bM(o[0])){let{connection:n,client:t,...T}=o[0];if(t)return st(t,T);if(typeof n==="object"&&n.url!==void 0){let{url:f,...y}=n,A=ut(f,y);return st(A,T)}let S=ut(n);return st(S,T)}return st(o[0],o[1])}((o)=>{function n(t){return st({},t)}o.mock=n})(lS||(lS={}));var hy={};rJ(hy,{users:()=>Et,userChanges:()=>Z0,untrackedUserColumnNames:()=>q0,twoFactorMethod:()=>V$,trackedUserColumnName:()=>U$,trackableUserColumnNames:()=>D$,role:()=>Q$,players:()=>Ny,passwordResetAttempts:()=>e0,loginHistory:()=>P0,games:()=>gS,banishedIps:()=>pT});function m$(o){return R`lower(${o})`}var Q$=$S("role",["admin","user"]),Et=nt("users",{id:kn().primaryKey().defaultRandom(),username:io({length:16}).notNull(),email:io({length:254}).notNull(),hash:io({length:64}).notNull(),salt:io({length:36}).notNull(),createdAt:Dn({withTimezone:!0}).notNull().defaultNow(),createdIp:io({length:45}).notNull(),isActive:ET().notNull().default(!1),verifiedAt:Dn({withTimezone:!0}),userRole:Q$().default("user")},(o)=>[Cy("usernameUniqueIndex").on(m$(o.username)),Cy("emailUniqueIndex").on(m$(o.email))]),q0=["id","createdAt","createdIp","isActive","salt","verifiedAt"],D$=["username","email","hash","userRole"],U$=$S("trackedUserColumnName",D$),Z0=nt("userChanges",{id:kn().primaryKey().defaultRandom(),userId:kn().notNull().references(()=>Et.id),changedAt:Dn({withTimezone:!0}).notNull().defaultNow(),changedIp:io({length:45}).notNull(),changedColumn:U$().notNull(),oldValue:io({length:255}),newValue:io({length:255})}),gS=nt("games",{id:kn().primaryKey().defaultRandom()}),Ny=nt("players",{userId:kn().notNull().references(()=>Et.id),gameId:kn().notNull().references(()=>gS.id),score:XS().notNull()},(o)=>[Uk({name:"players_userId_gameId_pk",columns:[o.userId,o.gameId]})]),P0=nt("loginHistory",{id:kn().primaryKey().defaultRandom(),userId:kn().references(()=>Et.id),loginTime:Dn({withTimezone:!0}).notNull().defaultNow(),ipAddress:io({length:45}).notNull(),userAgent:io({length:1024}),successful:ET().notNull().default(!1)}),V$=$S("twoFactorMethod",["email","phone"]),e0=nt("passwordResetAttempts",{id:kn().primaryKey().defaultRandom(),userId:kn().notNull().references(()=>Et.id),requestedIp:io({length:45}).notNull(),requestedAt:Dn({withTimezone:!0}).notNull().defaultNow(),succeededIp:io({length:45}),succeededAt:Dn({withTimezone:!0}),verificationMethod:V$().notNull()}),pT=nt("banishedIps",{ip:io({length:45}).primaryKey(),reason:io({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 cy{options;sql;drizzle;observers=new Map;async setupTriggersAndNotifications(){await this.sql.file(l0.resolve(__dirname,"notify_update.sql"));let o=[On(Et),On(gS),On(Ny)];await this.sql`SELECT create_notify_triggers(${this.sql.array(o)})`,await this.sql.listen("table_update",(n)=>{let t=n.split(","),T=t[0],S=t[1],f=`${T}("${S}")`;if(this.observers.has(f))this.observers.get(f).next(f)})}constructor(o=!1,n={host:Cn.POSTGRES_HOST,port:Cn.POSTGRES_PORT,user:Cn.POSTGRES_USER,password:Cn.POSTGRES_PASSWORD,database:Cn.POSTGRES_DATABASE}){this.options=n,this.sql=ut(n),this.drizzle=lS(this.sql,{schema:hy,logger:o})}observe(o,n){if(!this.observers.has(o))this.observers.set(o,new s);this.observers.get(o).subscribe("SINGLETON",n)}}var dS={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"},xy=sy(dS).map(([o])=>zo.literal(Number(o))),g0=zo.union([xy[0],xy[1],...xy]),r$=zo.tuple([g0,zo.string()]);var L$=new Vf,{logger:En}=L$;En.info(" ready");var iy=C$(import.meta.dir,"..","app"),s0=new cy({logQuery(o,n){En.info("\uD83D\uDCDD query",o,n)}});a0({hostname:"0.0.0.0",port:Cn.FRONTEND_PORT??3333,...uk??void 0,async fetch(o,n){try{let t=new Date,T=new URL(o.url),S=n.requestIP(o)?.address??"??";En.info(t,S,o.method,T.pathname);let[f]=await s0.drizzle.select({banishedUntil:pT.banishedUntil}).from(pT).where(Ct(pT.ip,S)).limit(1),y=f?.banishedUntil===null,A=f?.banishedUntil&&f.banishedUntil>t;if(y||A)throw En.info(`\uD83D\uDE45 request from banned ip ${S}`),[403,S];if(T.pathname==="/")return new Response(Bun.file(C$(iy,"index.html")));if(T.pathname==="/index.html")return Response.redirect("/");let M=d0(iy,T.pathname),F=u0(M);if(!F.startsWith(iy))throw[403,"Access Denied"];if(!await B$(F).exists())return Response.redirect("/");return new Response(B$(F))}catch(t){let T=r$.safeParse(t);if(T.success){let[S,f]=T.data,A=`${dS[S]}. ${f}`;return En.info(`\u274C ${S}: ${A}`),new Response(A,{status:S})}if(t instanceof Error)En.error(t.message);else{let S=Ut(t);En.error("frontend server threw",S)}return new Response(dS[500],{status:500})}}});function vy(){En.info("\uD83D\uDEEC frontend server exiting"),process.exit(0)}process.on("SIGINT",()=>{En.info("\u2757 received SIGINT; exiting gracefully"),vy()});process.on("SIGTERM",()=>{En.info("\u2757 received SIGTERM; exiting gracefully"),vy()});process.on("exit",()=>{En.info("\u2757 received exit; exiting gracefully"),vy()});En.info(`\uD83D\uDEEB frontend server running at http://localhost:${Cn.FRONTEND_PORT}/`);L$.emit("alive");