tempest.games 0.1.22 → 0.1.24

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,12 +1,12 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- var Qk=Object.create;var{getPrototypeOf:Dk,defineProperty:yf,getOwnPropertyNames:Uk}=Object;var Vk=Object.prototype.hasOwnProperty;var AW=(o,n,T)=>{T=o!=null?Qk(Dk(o)):{};let t=n||!o||!o.__esModule?yf(T,"default",{value:o,enumerable:!0}):T;for(let S of Uk(o))if(!Vk.call(t,S))yf(t,S,{get:()=>o[S],enumerable:!0});return t};var MW=(o,n)=>()=>(n||o((n={exports:{}}).exports,n),n.exports);var Bk=(o,n)=>{for(var T in n)yf(o,T,{get:n[T],enumerable:!0,configurable:!0,set:(t)=>n[T]=()=>t})};import{join as tW,normalize as SW,resolve as IJ}from"path";function mT(o=Math.random){return o().toString(36).slice(2)}class ft 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 tA(o){return Object.entries(o)}var SA=(o,n,T=to.STORE)=>{return Gn(T,{key:`${o.key}:JSON`,get:({get:t})=>n.toJson(t(o)),set:({set:t},S)=>{t(o,n.fromJson(S))}})};function U(o){while(o.child!==null)o=o.child;return o}function fA(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 Af 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 ${zn(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),$={key:n.key,subKey:F},W=`${n.key}(${F})`,O=U(o),G=n.default,D={key:W,default:G instanceof Function?G(M):G};if(n.effects)D.effects=n.effects(M);let z=fn(O,D,$);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 yA(o,n){if("mutable"in n)return yt(o,n);return jn(o,n)}function cn(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 ${zn(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),$={key:n.key,subKey:F},W=`${n.key}(${F})`,O=U(o),G=At(O,{key:W,get:n.get(M)},$);return f.next({type:"state_creation",token:G}),G},t,{internalRoles:T,subject:f,install:(M)=>cn(M,n),default:(M)=>{return n.get(M)({get:(...$)=>fo(o,...$),find:($,W)=>Ao(o,$,W),seek:($,W)=>Eo(o,$,W),json:($)=>Vo(o,$)})}});return o.families.set(n.key,A),t}function Mt(o,n){if("set"in n)return Ft(o,n);return cn(o,n)}var Ck={atom_family:"atom",mutable_atom_family:"mutable_atom",selector_family:"selector",readonly_selector_family:"readonly_selector",molecule_family:"molecule"};function QT(o,n){let T=l(n),t=`${o.key}(${T})`,S=Ck[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 go(o){let n={key:o.key,type:o.type};if("family"in o)n.family=o.family;return n}var cW=Symbol("provenance");function Mf(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(Lk)){f="any";let $=l(n),W=o.molecules.get($);if(!W)throw new Error(`Molecule ${$} 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),G=o.molecules.get(O);if(!G)throw new Error(`Molecule ${O} not found in store "${o.config.name}"`);S.push(G)}}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 DT(S,T);y._dependsOn=f,o.molecules.set(t,y);for(let $ of S)$.below.set(y.stringKey,y);let A={type:"molecule_creation",subType:"modern",key:y.key,provenance:n},M=U(o);if(yo(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 $t(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 $=F.family;f.push([$.key,o.valueMap.get(F.key)])}for(let F of t.tokens.values())so(o,F);for(let F of t.below.values())if(F.dependsOn==="all")$t(o,F.key);else if(F.above.delete(t.stringKey),F.above.size===0)$t(o,F.key);t.below.clear();let y={type:"molecule_disposal",subType:"modern",key:t.key,values:f,provenance:S},A=U(o);if(yo(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 Lk="T$";function UT(o){return AA(to.STORE,o)}function $T(o){return yA(to.STORE,o)}function Ff(...o){if(o.length===2)return fo(to.STORE,...o);return fo(to.STORE,...o)}var $f=(o)=>(n,T,t,S,...f)=>{console[o](`${n} ${T} "${t}" ${S}`,...f)},Ik={error:$f("error"),info:$f("info"),warn:$f("warn")};class Jf{logLevel;filter;logger;constructor(o,n,T=Ik){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 et(o){return Mt(to.STORE,o)}function Jt(o){return kf(o,to.STORE)}class Fn{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 yo(o){return"phase"in o.transactionMeta}var FA=(o)=>{let n=U(o);if(!yo(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 jk=(o)=>o[0].toUpperCase()+o.slice(1);function zn(o){return o.type.split("_").map(jk).join(" ")}class yn extends Error{constructor(...o){let n=o[0],T=o.length===2?o[1]:o[2];if(o.length===2)super(`${zn(n)} ${l(n.key)} not found in store "${T.config.name}".`);else{let t=o[1];super(`${zn(n)} "${n.key}" member ${l(t)} not found in store "${T.config.name}".`)}}}function an(o,n,T){return(...t)=>{let S=d(o,T);if(S)return S.run(t,n);throw new yn(o,T)}}var dt=(o)=>(n)=>o instanceof Function?o(n):o;var sn=(o,n)=>{if(n.valueMap.has(o.key))return n.logger.info("\uD83D\uDCD6",o.type,o.key,"reading cached value"),$A(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 JA=(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}"${!yo(o)?"":` ${o.transactionMeta.phase} "${o.transactionMeta.update.key}"`}`)},kA=(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)},RA=(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)},VT=(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 WA=(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 Rf=(o,n)=>{let T=U(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(RA(T,S))continue;OA(S,T),VT(T,S)}}};function rk(o,n){if(wA(n.newValue))return!1;if(o.includes("\uD83D\uDD0D"))return!1;return!0}var _A=(o,n,T)=>{let{key:t}=o,S=U(T);if(!yo(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(!rk(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 KA=(o,n,T)=>{let t=sn(o,T),S=t;if(o.type==="mutable_atom"&&yo(T)){let{parent:y}=T;S=kt(o,y,T)}if(S=dt(n)(S),T.logger.info("\uD83D\uDCDD","atom",o.key,"set to",S),S=Wn(o.key,S,o.subject,T),XA(o.key,T))EA(o.key,T);VT(T,o.key),Rf(o,T);let f={oldValue:t,newValue:S};if(Bo(T))WA(o,f,T);else if(T.parent){if(T.on.transactionApplying.state===null)_A(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"&&yo(T)){let{parent:$}=T;M=kt(A,$,T)}if(M.do(f.newValue)===null)Rf(A,T)}}};var ut=(o,n,T)=>{switch(o.type){case"atom":case"mutable_atom":KA(o,n,T);break;case"selector":o.set(n);break}};function at(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=at(o,T)??null,t)S=T.family?ro(T.family.subKey):null,T=Ao(o,t,S)}else t=n[0],S=n[1],f=n[2],T=Ao(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:
3
+ var Qk=Object.create;var{getPrototypeOf:Dk,defineProperty:yf,getOwnPropertyNames:Uk}=Object;var Vk=Object.prototype.hasOwnProperty;var AW=(o,n,T)=>{T=o!=null?Qk(Dk(o)):{};let t=n||!o||!o.__esModule?yf(T,"default",{value:o,enumerable:!0}):T;for(let S of Uk(o))if(!Vk.call(t,S))yf(t,S,{get:()=>o[S],enumerable:!0});return t};var MW=(o,n)=>()=>(n||o((n={exports:{}}).exports,n),n.exports);var Bk=(o,n)=>{for(var T in n)yf(o,T,{get:n[T],enumerable:!0,configurable:!0,set:(t)=>n[T]=()=>t})};import{join as tW,normalize as SW,resolve as IJ}from"path";function mT(o=Math.random){return o().toString(36).slice(2)}class ft 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 kW(o){return Object.fromEntries(o)}function tA(o){return Object.entries(o)}var SA=(o,n,T=to.STORE)=>{return Gn(T,{key:`${o.key}:JSON`,get:({get:t})=>n.toJson(t(o)),set:({set:t},S)=>{t(o,n.fromJson(S))}})};function U(o){while(o.child!==null)o=o.child;return o}function fA(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 Af 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 ${zn(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),$={key:n.key,subKey:F},W=`${n.key}(${F})`,O=U(o),G=n.default,D={key:W,default:G instanceof Function?G(M):G};if(n.effects)D.effects=n.effects(M);let z=fn(O,D,$);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 yA(o,n){if("mutable"in n)return yt(o,n);return jn(o,n)}function cn(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 ${zn(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),$={key:n.key,subKey:F},W=`${n.key}(${F})`,O=U(o),G=At(O,{key:W,get:n.get(M)},$);return f.next({type:"state_creation",token:G}),G},t,{internalRoles:T,subject:f,install:(M)=>cn(M,n),default:(M)=>{return n.get(M)({get:(...$)=>fo(o,...$),find:($,W)=>Ao(o,$,W),seek:($,W)=>Eo(o,$,W),json:($)=>Vo(o,$)})}});return o.families.set(n.key,A),t}function Mt(o,n){if("set"in n)return Ft(o,n);return cn(o,n)}var Ck={atom_family:"atom",mutable_atom_family:"mutable_atom",selector_family:"selector",readonly_selector_family:"readonly_selector",molecule_family:"molecule"};function QT(o,n){let T=l(n),t=`${o.key}(${T})`,S=Ck[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 go(o){let n={key:o.key,type:o.type};if("family"in o)n.family=o.family;return n}var vW=Symbol("provenance");function Mf(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(Lk)){f="any";let $=l(n),W=o.molecules.get($);if(!W)throw new Error(`Molecule ${$} 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),G=o.molecules.get(O);if(!G)throw new Error(`Molecule ${O} not found in store "${o.config.name}"`);S.push(G)}}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 DT(S,T);y._dependsOn=f,o.molecules.set(t,y);for(let $ of S)$.below.set(y.stringKey,y);let A={type:"molecule_creation",subType:"modern",key:y.key,provenance:n},M=U(o);if(yo(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 $t(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 $=F.family;f.push([$.key,o.valueMap.get(F.key)])}for(let F of t.tokens.values())so(o,F);for(let F of t.below.values())if(F.dependsOn==="all")$t(o,F.key);else if(F.above.delete(t.stringKey),F.above.size===0)$t(o,F.key);t.below.clear();let y={type:"molecule_disposal",subType:"modern",key:t.key,values:f,provenance:S},A=U(o);if(yo(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 Lk="T$";function UT(o){return AA(to.STORE,o)}function $T(o){return yA(to.STORE,o)}function Ff(...o){if(o.length===2)return fo(to.STORE,...o);return fo(to.STORE,...o)}var $f=(o)=>(n,T,t,S,...f)=>{console[o](`${n} ${T} "${t}" ${S}`,...f)},Ik={error:$f("error"),info:$f("info"),warn:$f("warn")};class Jf{logLevel;filter;logger;constructor(o,n,T=Ik){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 et(o){return Mt(to.STORE,o)}function Jt(o){return kf(o,to.STORE)}class Fn{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 yo(o){return"phase"in o.transactionMeta}var FA=(o)=>{let n=U(o);if(!yo(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 jk=(o)=>o[0].toUpperCase()+o.slice(1);function zn(o){return o.type.split("_").map(jk).join(" ")}class yn extends Error{constructor(...o){let n=o[0],T=o.length===2?o[1]:o[2];if(o.length===2)super(`${zn(n)} ${l(n.key)} not found in store "${T.config.name}".`);else{let t=o[1];super(`${zn(n)} "${n.key}" member ${l(t)} not found in store "${T.config.name}".`)}}}function an(o,n,T){return(...t)=>{let S=d(o,T);if(S)return S.run(t,n);throw new yn(o,T)}}var dt=(o)=>(n)=>o instanceof Function?o(n):o;var sn=(o,n)=>{if(n.valueMap.has(o.key))return n.logger.info("\uD83D\uDCD6",o.type,o.key,"reading cached value"),$A(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 JA=(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}"${!yo(o)?"":` ${o.transactionMeta.phase} "${o.transactionMeta.update.key}"`}`)},kA=(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)},RA=(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)},VT=(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 WA=(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 Rf=(o,n)=>{let T=U(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(RA(T,S))continue;OA(S,T),VT(T,S)}}};function rk(o,n){if(wA(n.newValue))return!1;if(o.includes("\uD83D\uDD0D"))return!1;return!0}var _A=(o,n,T)=>{let{key:t}=o,S=U(T);if(!yo(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(!rk(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 KA=(o,n,T)=>{let t=sn(o,T),S=t;if(o.type==="mutable_atom"&&yo(T)){let{parent:y}=T;S=kt(o,y,T)}if(S=dt(n)(S),T.logger.info("\uD83D\uDCDD","atom",o.key,"set to",S),S=Wn(o.key,S,o.subject,T),XA(o.key,T))EA(o.key,T);VT(T,o.key),Rf(o,T);let f={oldValue:t,newValue:S};if(Bo(T))WA(o,f,T);else if(T.parent){if(T.on.transactionApplying.state===null)_A(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"&&yo(T)){let{parent:$}=T;M=kt(A,$,T)}if(M.do(f.newValue)===null)Rf(A,T)}}};var ut=(o,n,T)=>{switch(o.type){case"atom":case"mutable_atom":KA(o,n,T);break;case"selector":o.set(n);break}};function at(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=at(o,T)??null,t)S=T.family?ro(T.family.subKey):null,T=Ao(o,t,S)}else t=n[0],S=n[1],f=n[2],T=Ao(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:
4
4
  ${M.trace}`:"No previous disposal trace was found.");return}let y=JA(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);ut(A,f,o),kA(o)}function st(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 YA(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 Hn(o,n,T){let t=vn(T,n,o.key);o.tokens.set(t.key,t);let S=yo(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 _f{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 _f(this.options,this.defaultContent,o);return this.alternates.set(n,t),t.alternates=this.alternates,t}constructor(o,n,T=to.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=(E,K)=>{let Q=this.toolkit.seek(E,K);if(Q)return Q;let x=this.store.molecules.get(l(K));if(x){let h=d(E,T);return Hn(x,h,T)}if(T.config.lifespan==="immortal")throw new yn(E,K,T);return vn(T,E,K)},this.toolkit={get:(...E)=>fo(T,...E),set:(...E)=>{Qo(T,...E)},find:this.retrieve,seek:(...E)=>Eo(T,...E),json:(E)=>Vo(T,E),dispose:(...E)=>{so(T,...E)}};let t=o.between[0],S=o.between[1],f=yt(T,{key:`${o.key}/relatedKeys`,default:()=>new No,mutable:!0,fromJson:(E)=>No.fromJSON(E),toJson:(E)=>E.toJSON()},["join","relations"]);this.core={findRelatedKeysState:f};let y=({get:E},K)=>E(this.retrieve(f,K)),A=(E,K,Q)=>{let{set:x}=E,h=this.retrieve(f,K),w=this.retrieve(f,Q);x(h,(v)=>v.add(Q)),x(w,(v)=>v.add(K))},M=(E,K,Q)=>{let{set:x}=E,h=this.retrieve(f,K),w=this.retrieve(f,Q),v,N;x(h,(q)=>{if(q.delete(Q),q.size===0)v=`"${K}"`;return q}),x(w,(q)=>{if(q.delete(K),q.size===0)N=`"${Q}"`;return q})},F=(E,K,Q)=>{let{get:x,set:h}=E,w=this.retrieve(f,K),v=x(w);for(let N of v){if(Q.includes(N))continue;let Jo=this.retrieve(f,N);h(Jo,(Oo)=>{return Oo.delete(K),Oo})}h(w,(N)=>{return N.transaction((q)=>{q.clear();for(let Jo of Q){let Oo=y(E,Jo),Sn=Oo.has(K);if(this.relations.cardinality==="1:n"){let xn=[];for(let H of Oo){if(H===K)continue;let Z=y(E,H);if(Z.delete(Jo),Z.size===0)xn.push(H)}if(!Sn&&Oo.size>0)Oo.clear();for(let H of xn){let Z=[Jo,H].sort(),Fo=`"${Z[0]}:${Z[1]}"`;this.molecules.delete(Fo)}}if(!Sn)Oo.add(K);q.add(Jo)}return!0}),N})},$=(E,K,Q)=>{let{set:x}=E,h=this.retrieve(f,K);x(h,(w)=>{return w.transaction((v)=>{for(let N of Q)v.add(N);return!0}),w});for(let w of Q){let v=this.retrieve(f,w);x(v,(N)=>{return N.add(K),N})}return!0},W=(E,K,Q)=>{let x=y(E,K);return Q?x.has(Q):x.size>0},O={getRelatedKeys:(E)=>y(this.toolkit,E),addRelation:(E,K)=>{A(this.toolkit,E,K)},deleteRelation:(E,K)=>{M(this.toolkit,E,K)},replaceRelationsSafely:(E,K)=>{F(this.toolkit,E,K)},replaceRelationsUnsafely:(E,K)=>{$(this.toolkit,E,K)},has:(E,K)=>W(this.toolkit,E,K)},G,D,z;if(n){D=jn(T,{key:`${o.key}/content`,default:n},["join","content"]),z=YA(T,{key:`${o.key}/content-molecules`,new:class h{key;constructor(w,v){this.key=v}}});let E=({get:h},w)=>h(this.retrieve(D,w)),K=({set:h},w,v)=>{h(this.retrieve(D,w),v)},Q=(h,w)=>{let v=T.molecules.get(`"${w}"`);if(v)this.toolkit.dispose(v),this.molecules.delete(`"${w}"`)};G=Object.assign(O,{getContent:(h)=>{return E(this.toolkit,h)},setContent:(h,w)=>{K(this.toolkit,h,w)},deleteContent:(h)=>{Q(this.toolkit,h)}})}else G=O;let Y=new Fn(o,{externalStore:G,isAType:o.isAType,isBType:o.isBType,makeContentKey:(...E)=>{let K=E.sort(),Q=`${K[0]}:${K[1]}`,[x,h]=K.map((w)=>this.molecules.get(l(w)));if(T.config.lifespan==="immortal"&&x&&h){let w=U(T),v=pn(w,[x,h],z,Q);this.molecules.set(`"${Q}"`,d(v,w))}return Q}}),B=()=>cn(T,{key:`${o.key}/singleRelatedKey`,get:(E)=>({get:K})=>{let Q=this.retrieve(f,E),x=K(Q);for(let h of x)return h;return null}},["join","keys"]),p=()=>{return cn(T,{key:`${o.key}/multipleRelatedKeys`,get:(E)=>({get:K})=>{let Q=Of(f,T),x=this.retrieve(Q,E);return K(x).members}},["join","keys"])},c=()=>cn(T,{key:`${o.key}/singleRelatedEntry`,get:(E)=>({get:K})=>{let Q=this.retrieve(f,E),x=K(Q);for(let h of x){let w=Y.isAType?.(E)?E:void 0,v=w===void 0?E:void 0;w??=h,v??=h;let N=Y.makeContentKey(w,v),q=this.retrieve(D,N),Jo=K(q);return[h,Jo]}return null}},["join","entries"]),a=()=>cn(T,{key:`${o.key}/multipleRelatedEntries`,get:(E)=>({get:K})=>{let Q=Of(f,T),x=this.retrieve(Q,E);return K(x).members.map((w)=>{let v=Y.isAType?.(E)?E:void 0,N=v===void 0?E:void 0;v??=w,N??=w;let q=Y.makeContentKey(v,N),Jo=this.retrieve(D,q),Oo=K(Jo);return[w,Oo]})}},["join","entries"]);switch(o.cardinality){case"1:1":{let E=B(),K=`${t}KeyOf${Ho(S)}`,Q=`${S}KeyOf${Ho(t)}`,x={[K]:E,[Q]:E},h;if(n){let w=c(),v=`${t}EntryOf${Ho(S)}`,N=`${S}EntryOf${Ho(t)}`,q={[v]:w,[N]:w};h=Object.assign(x,q)}else h=x;this.relations=Y,this.states=h;break}case"1:n":{let E=B(),K=p(),Q=`${t}KeyOf${Ho(S)}`,x=`${S}KeysOf${Ho(t)}`,h={[Q]:E,[x]:K},w;if(n){let v=c(),N=a(),q=`${t}EntryOf${Ho(S)}`,Jo=`${S}EntriesOf${Ho(t)}`,Oo={[q]:v,[Jo]:N};w=Object.assign(h,Oo)}else w=h;this.relations=Y,this.states=w;break}default:{let E=p(),K=`${t}KeysOf${Ho(S)}`,Q=`${S}KeysOf${Ho(t)}`,x={[K]:E,[Q]:E},h;if(n){let w=a(),v=`${t}EntriesOf${Ho(S)}`,N=`${S}EntriesOf${Ho(t)}`,q={[v]:w,[N]:w};h=Object.assign(x,q)}else h=x;this.relations=Y,this.states=h}}}}function oS(o,n,T=to.STORE){return Wf(T).set(o.key,new _f(o,n,T)),{key:o.key,type:"join",a:o.between[0],b:o.between[1],cardinality:o.cardinality}}function Wf(o){if("joins"in o&&o.joins instanceof Map)return o.joins;let n=new Map;return o.joins=n,n}function Rt(o,n){let T=Wf(n),t=T.get(o.key);if(t===void 0){if(t=Wf(to.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 nS(o,n,T){let t=Rt(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 GA(o,n){return nS(o,n,to.STORE)}function TS(o,n,T){let t=Rt(o,T),S=U(T);if(yo(S)){let{toolkit:f}=S.transactionMeta;t.transact(f,({relations:y})=>{n(y)})}else n(t.relations)}function Nk(o,n){return Rt(o,n).core.findRelatedKeysState}function zA(o){return Nk(o,to.STORE)}function tS(o){return{store:o}}function fo(o,...n){let T,t,S;if(n.length===1){if(T=n[0],T.type!=="molecule"){if(t=at(o,T)??null,t)S=T.family?ro(T.family.subKey):null,T=Ao(o,t,S)}}else{t=n[0],S=n[1];let f;if(t.type==="molecule_family")f=Eo(o,t,S)??QT(t,S);else f=Ao(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:
5
5
  ${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 yn(t,f,o)}}switch(T.type){case"atom":case"mutable_atom":case"selector":case"readonly_selector":return sn(d(T,o),o);case"molecule":return d(T,o).instance}}class DT{key;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 HA(o){return o[0].toUpperCase()+o.slice(1)}function pn(o,n,T,t,...S){let f=fA(o),y=U(o),A=l(t);y.moleculeInProgress=A;let M=Array.isArray(n)?n:[n],F=M.map((Y)=>{if(Y instanceof DT)return Y;let B=l(Y.key),p=o.molecules.get(B);if(!p)throw new Error(`Molecule ${B} not found in store "${o.config.name}"`);return p}),$=new DT(F,t,T);y.molecules.set(A,$);for(let Y of F)Y.below.set($.stringKey,$);let W={get:(...Y)=>fo(U(f),...Y),set:(...Y)=>{Qo(U(f),...Y)},seek:(Y,B)=>Eo(U(f),Y,B),json:(Y)=>Vo(U(f),Y),run:(Y,B=mT())=>an(Y,B,U(o)),make:(Y,B,p,...c)=>pn(U(f),Y,B,p,...c),dispose:(Y)=>{so(U(f),Y)},env:()=>tS(U(f)),bond:(Y,B)=>{if(Y.type==="join"){let{as:p}=B,c=Rt(Y,f);c.molecules.set(A,$),$.joins.set(Y.key,c);let a=O.subject.subscribe(`join:${Y.key}-${A}`,(w)=>{if(w.type==="molecule_disposal"){if(l(w.token.key)===A)a(),c.molecules.delete(A)}});if(p===null)return;let E=Y.a===p?Y.b:Y.a,K=GA(Y,t),Q=K[`${E}KeysOf${HA(p)}`],x=K[`${E}EntriesOf${HA(p)}`],h={relatedKeys:Q};if(x)h=Object.assign(h,{relatedEntries:x});return h}return Hn($,d(Y,f),U(f))},claim:(Y,B)=>{let{exclusive:p}=B,c=U(o).molecules.get(l(Y.key));if(c)if(p){for(let a of c.above.values())a.below.delete(c.stringKey);c.above.clear(),c.above.set($.stringKey,$),$.below.set(c.stringKey,c)}else c.above.set($.stringKey,$),$.below.set(c.stringKey,c)},spawn:(Y,B,...p)=>pn(U(o),[$],d(Y,o),B,...p)},O=d(T,o),G=O.new;$.instance=new G(W,t,...S);let D={type:"molecule",key:t,family:T},z={type:"molecule_creation",subType:"classic",token:D,family:T,context:M,params:S};if(Bo(y))O.subject.next(z);else if(yo(y)&&y.on.transactionApplying.state===null)y.transactionMeta.update.updates.push(z);return y.moleculeInProgress=null,D}function wf(o,n,T){switch(n){case"newValue":{mA(o,T);break}case"oldValue":{so(T,o.token);break}}}function Kf(o,n,T){switch(n){case"newValue":{so(T,o.token);break}case"oldValue":{mA(o,T),T.valueMap.set(o.token.key,o.value);break}}}function mA(o,n){let{family:T}=o.token;if(T){let t=n.families.get(T.key);if(t)Ao(n,t,ro(T.subKey))}}function Xf(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":Mf(T,o.provenance,o.key);break}break;case"oldValue":switch(o.subType){case"classic":so(T,o.token);break;case"modern":$t(T,o.key);break}break}}function Ef(o,n,T){switch(n){case"newValue":switch(o.subType){case"classic":so(T,o.token);break;case"modern":$t(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)Hn(A,F,T);T.valueMap.set(y,f)}}break;case"modern":{Mf(T,o.provenance,o.key);for(let[t,S]of o.values){let f=T.families.get(t);if(f){Ao(T,f,o.key);let y=`${t}(${l(o.key)})`;T.valueMap.set(y,S)}}}}break}}function SS(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":st(o,S,T);break;case"state_creation":wf(S,o,T);break;case"state_disposal":Kf(S,o,T);break;case"molecule_creation":Xf(S,o,T);break;case"molecule_disposal":Ef(S,o,T);break;case"transaction_update":SS(o,S,T);break}}function QA(o,n,T){if(Bo(T)&&o)T.transactionMeta.epoch.set(o,n)}function DA(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 UA=(o,n)=>{let T=U(n),{parent:t}=T;if(t===null||!yo(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),SS("newValue",T.transactionMeta.update,t),Bo(t))DA(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(yo(t))t.transactionMeta.update.updates.push(T.transactionMeta.update);t.on.transactionApplying.next(null)};function VA(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 On extends Map{source;deleted=new Set;constructor(o){super();this.source=o}get(o){if(super.has(o))return super.get(o);if(!this.deleted.has(o)&&this.source.has(o))return this.source.get(o);return}set(o,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 BA=(o,n,T,t)=>{let S=U(T),f={parent:S,child:null,on:S.on,loggers:S.loggers,logger:S.logger,config:S.config,atoms:new On(S.atoms),atomsThatAreDefault:new Set(S.atomsThatAreDefault),families:new On(S.families),operation:{open:!1},readonlySelectors:new On(S.readonlySelectors),timelines:new On(S.timelines),timelineTopics:new Fn(S.timelineTopics.toJSON()),trackers:new Map,transactions:new On(S.transactions),selectorAtoms:new Fn(S.selectorAtoms.toJSON()),selectorGraph:new Fn(S.selectorGraph.toJSON(),{makeContentKey:(...F)=>F.sort().join(":")}),selectors:new On(S.selectors),valueMap:new On(S.valueMap),defaults:S.defaults,disposalTraces:T.disposalTraces.copy(),molecules:new On(S.molecules),moleculeFamilies:new On(S.moleculeFamilies),moleculeInProgress:S.moleculeInProgress,miscResources:new On(S.miscResources)},y=CA(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)=>fo(M,...F),set:(...F)=>{Qo(M,...F)},run:(F,$=mT())=>an(F,$,M),find:(F,$)=>Ao(M,F,$),seek:(F,$)=>Eo(M,F,$),json:(F)=>Vo(M,F),make:(F,$,W,...O)=>pn(M,F,$,W,...O),dispose:(...F)=>{so(M,...F)},env:()=>tS(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 kf(o,n){let T={key:o.key,type:"transaction",run:(f,y)=>{let A=BA(o.key,f,n,y);try{let M=U(n),{toolkit:F}=A.transactionMeta,$=o.do(F,...f);return UA($,M),$}catch(M){throw FA(t),n.logger.warn("\uD83D\uDCA5","transaction",o.key,"caught:",M),M}},install:(f)=>kf(o,f),subject:new s},t=U(n);t.transactions.set(T.key,T);let S=go(T);return n.on.transactionCreation.next(S),S}function CA(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 fS{_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 fS([...this._buffer]);return o._index=this._index,o}}class LA{parent=null;child=null;valueMap=new Map;defaults=new Map;atoms=new Map;selectors=new Map;readonlySelectors=new Map;atomsThatAreDefault=new Set;selectorAtoms=new Fn({between:["selectorKey","atomKey"],cardinality:"n:n"});selectorGraph=new Fn({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 Fn({between:["continuity","action"],cardinality:"1:n"})};timelines=new Map;timelineTopics=new Fn({between:["timelineKey","topicKey"],cardinality:"1:n"});disposalTraces=new fS(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 Af(null),operationClose:new s,moleculeCreationStart:new s,moleculeCreationDone:new s,moleculeDisposal:new s};operation={open:!1};config={name:"IMPLICIT_STORE",lifespan:"ephemeral"};loggers=[new Jf("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 Fn(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=Vo(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 to={get STORE(){if(!globalThis.ATOM_IO_IMPLICIT_STORE)globalThis.ATOM_IO_IMPLICIT_STORE=new LA({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 yn(o,n)}function yS(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(go(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())so(n,F);for(let F of T.below.values())if(F.dependsOn==="all")yS(F,n);else if(F.above.delete(T.stringKey),F.above.size===0)yS(F,n);if(T.below.clear(),yo(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 yn(n,o);let S=t(T),f=U(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(yo(f)&&f.on.transactionApplying.state===null)f.transactionMeta.update.updates.push({type:"state_creation",token:S})}return S}function Eo(o,n,T){let t=l(T),S=`${n.key}(${t})`,f=U(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 go(y);return y}function Ao(o,n,T){let t=Eo(o,n,T);if(t)return t;let S=o.molecules.get(l(T));if(S)return Hn(S,n,o);if(o.config.lifespan==="immortal"){let f=QT(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 so(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"?Eo(o,f,y)??QT(f,y):Ao(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?`
6
6
  This state was most recently disposed
7
7
  ${y.trace}`:"No previous disposal trace was found.");return}switch(T.type){case"atom":case"mutable_atom":Yf(T,o);break;case"selector":case"readonly_selector":IA(T,o);break;case"molecule":yS(T,o);break}let{stack:S}=new Error;if(S){let f=S?.split(`
8
8
  `)?.slice(3)?.join(`
9
- `);o.disposalTraces.add({key:T.key,trace:f})}}var AS=(o,n)=>U(n).atoms.has(o),bk=(o,n)=>U(n).selectors.has(o),hk=(o,n)=>U(n).readonlySelectors.has(o),jA=(o,n)=>AS(o,n)||bk(o,n)||hk(o,n);var MS=(o,n)=>{return U(n).selectorGraph.getRelationEntries({downstreamSelectorKey:o}).filter(([t,{source:S}])=>S!==o).map(([t,{source:S}])=>S).filter((t)=>jA(t,n))};var Gf=(o,n,T)=>{let t=[],S=MS(o,T);while(S.length>0){let f=S.shift();if(n.has(f))continue;if(n.add(f),!AS(f,T))S.push(...MS(f,T));else if(!t.includes(f))t.push(f)}return t},rA=(o,n)=>{let T=o.key,t=MS(T,n),S=new Set;return t.flatMap((f)=>AS(f,n)?f:Gf(f,S,n))};var NA=(o,n,T,t)=>{let S=U(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=Gf(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 FS=(o,n,T)=>({get:(...t)=>{let S=U(T),f;if(t.length===2){let[M,F]=t;switch(M.type){case"molecule_family":return fo(T,M,F);default:if(T.config.lifespan==="ephemeral")f=Ao(T,M,F);else{let $=Eo(T,M,F);if($)f=$;else throw new yn(M,F,T)}}}else[f]=t;if(f.type==="molecule")return fo(T,f);let y=d(f,T),A=sn(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}),NA(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 $=T.config.lifespan==="ephemeral"?Ao(T,M,F):Eo(T,M,F);if(!$)throw new yn(M,F,T);S=$}let y=U(T),A=d(S,y);ut(A,f,y)},find:(t,S)=>Ao(T,t,S),seek:(t,S)=>Eo(T,t,S),json:(t)=>Vo(T,t)});var At=(o,n,T)=>{let t=U(o),S=new s,f=new Set,{get:y,find:A,seek:M,json:F}=FS(n.key,f,t),$=()=>{let D=n.get({get:y,find:A,seek:M,json:F});return Wn(n.key,D,S,U(o)),f.clear(),D},W={...n,subject:S,install:(D)=>At(D,n,T),get:$,type:"readonly_selector",...T&&{family:T}};t.readonlySelectors.set(n.key,W);let O=$();o.logger.info("\u2728",W.type,W.key,"=",O);let G={key:n.key,type:"readonly_selector"};if(T)G.family=T;return G};var Wt=(o,n,T)=>{let t=U(o),S=new s,f=new Set,y=FS(n.key,f,t),{find:A,get:M,seek:F,json:$}=y,W={find:A,get:M,seek:F,json:$},O=(B=n.get,p=U(o))=>{let c=B(W);return Wn(n.key,c,S,p),f.clear(),c},D={...n,subject:S,install:(B)=>Wt(B,n,T),get:O,set:(B)=>{let p=U(o),c=O(n.get,p),a=dt(B)(c);if(o.logger.info("\uD83D\uDCDD","selector",n.key,"set (",c,"->",a,")"),Wn(n.key,a,S,p),VT(p,n.key),Bo(p))S.next({newValue:a,oldValue:c});n.set(y,a)},type:"selector",...T&&{family:T}};t.selectors.set(n.key,D);let z=O();o.logger.info("\u2728",D.type,D.key,"=",z);let Y={key:n.key,type:"selector"};if(T)Y.family=T;return Y};function Gn(o,n){if("set"in n){let S=Wt(o,n,void 0);return o.on.selectorCreation.next(S),S}let t=At(o,n,void 0);return o.on.selectorCreation.next(t),t}function IA(o,n){let T=U(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"),yo(T)&&T.transactionMeta.phase==="building")T.transactionMeta.update.updates.push({type:"state_disposal",token:o});else n.on.selectorDisposal.next(o)}}function Ft(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 ${zn(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),$={key:n.key,subKey:F},W=`${n.key}(${F})`,O=U(o),G=Wt(O,{key:W,get:n.get(M),set:n.set(M)},$);return f.next({type:"state_creation",token:G}),G},t,{internalRoles:T,subject:f,install:(M)=>Ft(M,n),default:(M)=>{return n.get(M)({get:(...$)=>fo(o,...$),find:($,W)=>Ao(o,$,W),seek:($,W)=>Eo(o,$,W),json:($)=>Vo(o,$)})}});return o.families.set(n.key,A),t}function bA(o,n,T=to.STORE){let t=Ft(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),$=T.molecules.get(F);if($){let O=Hn($,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 $=l(f),W=T.molecules.get($);if(W){let O=Hn(W,o,T);A(O,n.fromJson(M))}else{if(T.config.lifespan==="immortal")throw new Error(`No molecule found for key "${$}"`);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)Eo(T,t,ro(f.token.family.subKey))}),t}var ro=(o)=>JSON.parse(o),l=(o)=>JSON.stringify(o),A4=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];var hA=(o,n)=>{let T=U(n);if(T.operation.open)return T.operation.prev.get(o.key);return T.valueMap.get(o.key)};var mf=(o,n)=>{let T=U(n);return rA(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=hA(o,T),M=sn(o,T);n.logger.info("\u2728",o.type,o.key,"went",A,"->",M),o.subject.next({newValue:M,oldValue:A})})})};function lo(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=mf(f,t),M=(W)=>{if(A)A.length=0,A.push(...mf(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 zf=(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 Hf=(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 oT{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=fn(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}:${yo(T)?T.transactionMeta.update.key:"main"}:${o.key}`,S=fo(T,o);this.unsubscribeFromInnerValue=S.subscribe(t,(f)=>{Qo(T,n,f)}),this.unsubscribeFromState=lo(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}:${yo(T)?T.transactionMeta.update.key:"main"}:${o.key}`;lo(n,({newValue:S,oldValue:f})=>{let y=T.timelineTopics.getRelatedKey(n.key);if(y){if(T.timelines.get(y)?.timeTraveling){let F=zf({key:y,type:"timeline"},($)=>{F(),Qo(T,o,(W)=>{if($==="redo"&&S)W.do(S);else if($==="undo"&&f)W.undo(f);return W})},t,T);return}}let A=T.on.operationClose.subscribe(t,()=>{A();let M=fo(T,o),F=S===null?-1:M.getUpdateNumber(S),$=F-M.cacheUpdateNumber;if(S&&$===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=U(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 Ot(o,n,T){o.logger.info("\uD83D\uDD28","atom",n.key,`creating in store "${o.config.name}"`);let t=U(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."),go(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}"`),Ot(F,n,T)},subject:f};if(T)y.family=T;let A=n.default();t.atoms.set(y.key,y),$S(n.key,o),Wn(n.key,A,f,t);let M=go(y);if(n.effects){let F=0,$=[];for(let W of n.effects){let O=W({setSelf:(G)=>{Qo(o,M,G)},onSet:(G)=>lo(M,G,`effect[${F}]`,o)});if(O)$.push(O);++F}y.cleanup=()=>{for(let W of $)W()}}if(new oT(M,o),!T)SA(M,n,o);return M}class Qf{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=ro(t.token.family.subKey);Eo(n,this.latestUpdateAtoms,S),new oT(t.token,n)}}),this.latestUpdateAtoms.subject.subscribe(`store=${n.config.name}::tracker-atom-family`,(t)=>{if(t.token.family){let S=ro(t.token.family.subKey),f=Eo(n,this.mutableAtoms,S);if(f)new oT(f,n)}})}}function yt(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 ${zn(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),$={key:n.key,subKey:F},W=`${n.key}(${F})`,O=U(o),G={key:W,default:()=>n.default(M),toJson:n.toJson,fromJson:n.fromJson,mutable:!0};if(n.effects)G.effects=n.effects(M);let D=Ot(O,G,$);return f.next({type:"state_creation",token:D}),D},t,{subject:f,install:(M)=>yt(M,n),toJson:n.toJson,fromJson:n.fromJson,internalRoles:T});return o.families.set(n.key,A),bA(A,n,o),new Qf(A,o),t}var Of=(o,n)=>{let T=U(n),t=`${o.key}:JSON`;return T.families.get(t)};var Vo=(o,n)=>{if(n.family){let t=U(o),f={key:`${n.family.key}:JSON`,type:"selector_family"},y=d(f,t),A=JSON.parse(n.family.subKey);return Ao(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 wA(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 oT(o,n),y}return S}function Wn(o,n,T,t){let S=t.valueMap.get(o);if(S instanceof ft)S.use(n);if(n instanceof Promise){let f=new ft(n);return t.valueMap.set(o,f),f.then((y)=>{Wn(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 $A=(o,n)=>{let T=n.valueMap.get(o.key);if(o.type==="mutable_atom"&&yo(n)){let{parent:t}=n;T=kt(o,t,n)}return T},OA=(o,n)=>{let T=n.valueMap.get(o);if(T instanceof ft){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 XA=(o,n)=>{return U(n).atomsThatAreDefault.has(o)},$S=(o,n)=>{let T=U(n);T.atomsThatAreDefault=new Set(T.atomsThatAreDefault).add(o)},EA=(o,n)=>{let T=U(n);T.atomsThatAreDefault=new Set(U(n).atomsThatAreDefault),T.atomsThatAreDefault.delete(o)};function fn(o,n,T){o.logger.info("\uD83D\uDD28","atom",n.key,`creating in store "${o.config.name}"`);let t=U(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."),go(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}"`),fn(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),$S(n.key,o),Wn(n.key,A,f,t);let M=go(y);if(n.effects){let F=0,$=[];for(let W of n.effects){let O=W({setSelf:(G)=>{Qo(o,M,G)},onSet:(G)=>lo(M,G,`effect[${F}]`,o)});if(O)$.push(O);++F}y.cleanup=()=>{for(let W of $)W()}}return M}function AA(o,n){if("mutable"in n){let S=Ot(o,n,void 0);return o.on.atomCreation.next(S),S}let t=fn(o,n,void 0);return o.on.atomCreation.next(t),t}function Yf(o,n){let T=U(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);Yf(M,n),n.trackers.delete(t)}if(n.logger.info("\uD83D\uDD25","atom",t,"deleted"),yo(T)&&T.transactionMeta.phase==="building")T.transactionMeta.update.updates.push({type:"state_disposal",token:o});else n.on.atomDisposal.next(o)}}var Df=(o)=>{let n=fn(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=go(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 Gn(o,{key:"\uD83D\uDD0D Atom Token Index",get:({get:T})=>T(n)})};var Uf=(o)=>{let n=fn(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=go(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 Gn(o,{key:"\uD83D\uDD0D Selector Token Index",get:({get:T})=>T(n)})};class JS{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 Vf=new JS({number:(o)=>typeof o==="number",string:(o)=>typeof o==="string",boolean:(o)=>typeof o==="boolean",null:(o)=>o===null});function Bf(o){if(!o)return!1;return Object.getPrototypeOf(o)===Object.prototype}var Cf=new JS({object:Bf,array:(o)=>Array.isArray(o)}),xk=new JS({...Vf.supported,...Cf.supported}),BT=(o)=>{if(o===void 0)return"undefined";let n=xk.refine(o);if(n)return n.type;return Object.getPrototypeOf(o).constructor.name};class xA{store;auditorCreatedAt=performance.now();statesCreatedAt=new Map;atomIndex;selectorIndex;disposed=!1;unsubscribeFromAtomCreation;unsubscribeFromAtomDisposal;unsubscribeFromSelectorCreation;unsubscribeFromSelectorDisposal;constructor(o=to.STORE){this.store=o;this.atomIndex=Df(this.store),this.selectorIndex=Uf(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=xA.DEFAULT_LIST_RESOURCES_PARAM){if(this.disposed)throw new Error("This Auditor has been disposed");let n=Ff(this.atomIndex),T=Ff(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 Lf=(o,n)=>{let T=(t,S)=>{let y=((M,F)=>{let $=n(M,F);if($)return $;return null})(t,S);if(y?.jobComplete??y?.pathComplete)return y;let A=Array.isArray(S)?S.map((M,F)=>[F,M]):Bf(S)?Object.entries(S):[];for(let[M,F]of A){let $=T([...t,M],F);if($?.jobComplete)return $}return{}};T([],o)};function ck(o,n){return{summary:`${o<n?"+":"-"}${Math.abs(o-n)} (${o} \u2192 ${n})`}}function vk(o,n){return{summary:`${o.length<n.length?"+":"-"}${Math.abs(o.length-n.length)} ("${o}" \u2192 "${n}")`}}function ik(o,n){return{summary:`${o} \u2192 ${n}`}}function cA(o,n,T){let t="",S=[],f=[],y=[];return Lf(o,(A,M)=>{let F;for(F of A){let $=n[F];if($===void 0)f.push([F,JSON.stringify(M)]);else{let W=T(M,$);if(W.summary!=="No Change")y.push([F,W])}}}),Lf(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 pk(o,n,T){return cA(o,n,T)}class vA{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=BT(o),f=BT(n);if(S===f)return{summary:`${S} \u2192 ${f}`};return{summary:`Type change: ${S} \u2192 ${f}`}}}var K8=new vA(Vf,Cf,{number:ck,string:vk,boolean:ik,null:()=>({summary:"No Change"}),object:cA,array:pk});class iA 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 kS{key;type="continuity";globals=[];actions=[];perspectives=[];constructor(o){this.key=o}static existing=new iA;static create(o,n){let T=new kS(o),{type:t,globals:S,actions:f,perspectives:y}=n(T),A={type:t,key:o,globals:S,actions:f,perspectives:y};return kS.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 D8(o){let{key:n,config:T}=o,t=kS.create(n,T),{actions:S}=t;for(let f of S)VA(n,f.key,to.STORE);return QA(n,-1,to.STORE),t}var L8=UT({key:"usersInRoomIndex",mutable:!0,default:()=>new No,toJson:(o)=>o.toJSON(),fromJson:(o)=>No.fromJSON(o)}),If=UT({key:"roomIndex",default:()=>new No,mutable:!0,toJson:(o)=>o.toJSON(),fromJson:(o)=>No.fromJSON(o)}),qk={enteredAtEpoch:0},_t=oS({key:"usersInRooms",between:["room","user"],cardinality:"1:n",isAType:(o)=>typeof o==="string",isBType:(o)=>typeof o==="string"},qk),I8=et({key:"usersInMyRoomView",get:(o)=>({find:n})=>{let T=zA(_t);return[n(T,o)]}});import{spawn as Zk}from"child_process";class CT{emit;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 jf extends CT{incompleteData="";unprocessedEvents=[];incompleteLog="";unprocessedLogs=[];id="#####";process;key;logger;handleLog(o){if(Array.isArray(o)){let[n,...T]=o;switch(n){case"i":this.logger.info(...T);break;case"w":this.logger.warn(...T);break;case"e":this.logger.error(...T);break}}}constructor(o,n,T){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});if(this.process=o,this.key=n,this.logger=T??{info:(...t)=>{console.info(this.id,this.key,...t)},warn:(...t)=>{console.warn(this.id,this.key,...t)},error:(...t)=>{console.error(this.id,this.key,...t)}},this.process.stdout.on("data",(t)=>{let S=t.toString();if(S==="ALIVE")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=ro(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=ro(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=ro(this.incompleteLog);this.handleLog(y);while(this.unprocessedLogs.length>0)if(this.incompleteLog=this.unprocessedLogs.shift()??"",this.incompleteLog)y=ro(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 pA extends CT{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 rf extends CT{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=ro(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=ro(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 pA(`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("ALIVE")}relay(o){this.logger.info("\uD83D\uDD17","running relay method"),this.relayServices.push(o)}}var Nf=$T({key:"roomArguments",default:["echo",["Hello World!"]]}),qA=et({key:"room",get:(o)=>async({get:n,find:T})=>{let t=T(Nf,o),S=n(t),[f,y]=S,A=await new Promise((M)=>{let F=Zk(f,y,{env:process.env}),$=(W)=>{if(W.toString()==="ALIVE")F.stdout.off("data",$),M(F)};F.stdout.on("data",$)});return new jf(A,o)}});var AE=Jt({key:"createRoom",do:({get:o,set:n,find:T},t,S,f)=>{let y=f?[S,f]:[S],A=T(Nf,t);n(A,y),n(If,($)=>$.add(t));let M=T(qA,t);return o(M)}}),ME=Jt({key:"joinRoom",do:(o,n,T,t)=>{let S={enteredAtEpoch:t};return TS(_t,(f)=>{f.set({room:n,user:T},S)},o.env().store),S}}),FE=Jt({key:"leaveRoom",do:(o,n,T)=>{TS(_t,(t)=>{t.delete({room:n,user:T})},o.env().store)}}),$E=Jt({key:"destroyRoom",do:(o,n)=>{TS(_t,(T)=>{T.delete({room:n})},o.env().store),o.set(If,(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 RE=$T({key:"redactor",default:{occlude:(o)=>o}}),LT=$T({key:"unacknowledgedUpdates",default:()=>[]});var ZA=$T({key:"sockets",default:null}),KE=UT({key:"socketsIndex",mutable:!0,default:()=>new No,toJson:(o)=>o.toJSON(),fromJson:(o)=>No.fromJSON(o)}),XE=UT({key:"usersIndex",mutable:!0,default:()=>new No,toJson:(o)=>o.toJSON(),fromJson:(o)=>No.fromJSON(o)}),hf=oS({key:"usersOfSockets",between:["user","socket"],cardinality:"1:1",isAType:(o)=>o.startsWith("user::"),isBType:(o)=>o.startsWith("socket::")});function PA(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"?Vo(o,M):M,$=fo(o,F);y.push(F,$)}for(let M of n.perspectives){let{viewAtoms:F,resourceAtoms:$}=M,W=Ao(o,F,T),O=fo(o,W);o.logger.info("\uD83D\uDC41","atom",$.key,`${T} can see`,{viewAtoms:F,resourceAtoms:$,userView:O});for(let G of O){let D=G.type==="mutable_atom"?Vo(o,G):G,z=fo(o,D);y.push(D,z)}}let A=Bo(o)?o.transactionMeta.epoch.get(S)??null:null;t?.emit(`continuity-init:${S}`,A,y)}}function gA(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`,$=`${M}:end`;performance.mark(F);try{an({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($);let W=performance.measure(M,F,$);o?.logger.info("\uD83D\uDE80","transaction",y,A,T,W.duration)}}function lA(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,LT,T,(M)=>{return M.shift(),o.logger.info("\uD83D\uDC4D","continuity",S,`${T} unacknowledged update queue now has`,M.length,"items"),M})}}function eA(o,n,T,t){let S=n.key,f=[];for(let y of n.actions){let A=Hf(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:G}=O,D=Ao(o,G,T);return fo(o,D).map((Y)=>{return Y.type==="mutable_atom"?"*"+Y.key:Y.key})})),$=bf(F,M.updates),W={...M,updates:$};Qo(o,LT,T,(O)=>{if(W)O.push(W),O.sort((G,D)=>G.epoch-D.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 dA(o,n,T,t){let S=n.key,f=[];for(let y of n.perspectives){let{viewAtoms:A}=y,M=Ao(o,A,T),F=lo(M,({oldValue:$,newValue:W})=>{let O=$.map((Y)=>Y.key),G=W.map((Y)=>Y.key),D=$.filter((Y)=>!G.includes(Y.key)),z=W.filter((Y)=>!O.includes(Y.key)).flatMap((Y)=>{let B=Y.type==="mutable_atom"?Vo(o,Y):Y,p=fo(o,B);return[B,p]});if(o.logger.info("\uD83D\uDC41","atom",y.resourceAtoms.key,`${T} has a new perspective`,{oldKeys:O,newKeys:G,revealed:z,concealed:D}),z.length>0)t?.emit(`reveal:${S}`,z);if(D.length>0)t?.emit(`conceal:${S}`,D)},`sync-continuity:${S}:${T}:perspective:${y.resourceAtoms.key}`,o);f.push(F)}return f}function eE({socket:o,store:n=to.STORE}){return function T(t){let S=o,f=t.key,y=nS(hf,`socket::${S.id}`,n).userKeyOfSocket,A=fo(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=nS(hf,A,n).socketKeyOfUser,F=lo(M,({newValue:B})=>{if(n.logger.info("\uD83D\uDC4B","continuity",f,`seeing ${A} on new socket ${B}`),B===null){n.logger.warn("\u274C","continuity",f,`User (${A}) is not connected to a socket, waiting for them to reappear.`);return}let p=Ao(n,ZA,B);S=fo(n,p);for(let a of $)S?.emit(`tx-new:${f}`,a)},`sync-continuity:${f}:${A}`,n),$=fo(n,LT,A),W=[],O=dA(n,t,A,S),G=eA(n,t,A,S);W.push(...O,...G);let D=PA(n,t,A,o);S.off(`get:${f}`,D),S.on(`get:${f}`,D);let z=gA(n,t,A);S.off(`tx-run:${f}`,z),S.on(`tx-run:${f}`,z);let Y=lA(n,t,A,$);return S?.on(`ack:${f}`,Y),()=>{for(let B of W)B();S?.off(`ack:${f}`,Y),S?.off(`get:${f}`,D),S?.off(`tx-run:${f}`,z)}}}var{file:LJ,serve:fW}=globalThis.Bun;var k=Symbol.for("drizzle:entityKind"),Y5=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,k))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(k in T&&T[k]===n[k])return!0;T=Object.getPrototypeOf(T)}return!1}class Ro{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[k]="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 xf{static[k]="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 mn=Symbol.for("drizzle:Name");class cf{static[k]="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 uA(o,this)}}class uA{constructor(o,n){this.table=o,this.reference=n.reference,this.onUpdate=n._onUpdate,this.onDelete=n._onDelete}static[k]="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[mn],...t,T[0].table[mn],...S];return o??`${f.join("_")}_fk`}}function RS(o,...n){return o(...n)}function aA(o,n){return`${o[mn]}_${n.join("_")}_unique`}function sA(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 oM(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]=sA(o,t+1,!0);T.push(M),t=F;continue}if(f==="}")return[T,t+1];if(f==="{"){let[M,F]=oM(o,t+1);T.push(M),t=F;continue}let[y,A]=sA(o,t,!1);T.push(y),t=A}return[T,t]}function nM(o){let[n]=oM(o,1);return n}function vf(o){return`{${o.map((n)=>{if(Array.isArray(n))return vf(n);if(typeof n==="string")return`"${n.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${n}`}).join(",")}}`}class b extends xf{foreignKeyConfigs=[];static[k]="PgColumnBuilder";array(o){return new tM(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 RS((S,f)=>{let y=new cf(()=>{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 TM(o,this.config)}}class V extends Ro{constructor(o,n){if(!n.uniqueName)n.uniqueName=aA(o,[n.name]);super(o,n);this.table=o}static[k]="PgColumn"}class TM extends V{static[k]="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 wt{static[k]="IndexedColumn";constructor(o,n,T,t){this.name=o,this.keyAsName=n,this.type=T,this.indexConfig=t}name;keyAsName;type;indexConfig}class tM extends b{static[k]="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 pf(o,this.config,n)}}class pf extends V{constructor(o,n,T,t){super(o,n);this.baseColumn=T,this.range=t,this.size=n.size}size;static[k]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(o){if(typeof o==="string")o=nM(o);return o.map((n)=>this.baseColumn.mapFromDriverValue(n))}mapToDriverValue(o,n=!1){let T=o.map((t)=>t===null?null:X(this.baseColumn,pf)?this.baseColumn.mapToDriverValue(t,!0):this.baseColumn.mapToDriverValue(t));if(n)return T;return vf(T)}}var qf=Symbol.for("drizzle:isPgEnum");function SM(o){return!!o&&typeof o==="function"&&qf in o&&o[qf]===!0}class fM extends b{static[k]="PgEnumColumnBuilder";constructor(o,n){super(o,"string","PgEnumColumn");this.config.enum=n}build(o){return new yM(o,this.config)}}class yM extends V{static[k]="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 WS(o,n){return Pk(o,n,void 0)}function Pk(o,n,T){let t=Object.assign((S)=>new fM(S??"",t),{enumName:o,enumValues:n,schema:T,[qf]:!0});return t}class bo{static[k]="Subquery";constructor(o,n,T,t=!1){this._={brand:"Subquery",sql:o,selectedFields:n,alias:T,isWith:t}}}class Kt extends bo{static[k]="WithSubquery"}var AM="0.38.3";var Zf,Pf,Wo={startActiveSpan(o,n){if(!Zf)return n();if(!Pf)Pf=Zf.trace.getTracer("drizzle-orm",AM);return RS((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()}}),Zf,Pf)}};var Yo=Symbol.for("drizzle:ViewBaseConfig");var OS=Symbol.for("drizzle:Schema"),_S=Symbol.for("drizzle:Columns"),MM=Symbol.for("drizzle:ExtraConfigColumns"),gf=Symbol.for("drizzle:OriginalName"),lf=Symbol.for("drizzle:BaseName"),wS=Symbol.for("drizzle:IsAlias"),FM=Symbol.for("drizzle:ExtraConfigBuilder"),gk=Symbol.for("drizzle:IsDrizzleTable");class I{static[k]="Table";static Symbol={Name:mn,Schema:OS,OriginalName:gf,Columns:_S,ExtraConfigColumns:MM,BaseName:lf,IsAlias:wS,ExtraConfigBuilder:FM};[mn];[gf];[OS];[_S];[MM];[lf];[wS]=!1;[gk]=!0;[FM]=void 0;constructor(o,n,T){this[mn]=this[gf]=o,this[OS]=n,this[lf]=T}}function _n(o){return o[mn]}function JT(o){return`${o[OS]??"public"}.${o[mn]}`}function ef(o){return o!==null&&o!==void 0&&typeof o.getSQL==="function"}function lk(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[k]="StringChunk";value;constructor(o){this.value=Array.isArray(o)?o:[o]}getSQL(){return new j([this])}}class j{constructor(o){this.queryChunks=o}static[k]="SQL";decoder=JM;shouldInlineParams=!1;append(o){return this.queryChunks.push(...o.queryChunks),this}toQuery(o){return Wo.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 lk(o.map((F)=>{if(X(F,ho))return{sql:F.value.join(""),params:[]};if(X(F,KS))return{sql:S(F.value),params:[]};if(F===void 0)return{sql:"",params:[]};if(Array.isArray(F)){let $=[new ho("(")];for(let[W,O]of F.entries())if($.push(O),W<F.length-1)$.push(new ho(", "));return $.push(new ho(")")),this.buildQueryFromSourceParams($,T)}if(X(F,j))return this.buildQueryFromSourceParams(F.queryChunks,{...T,inlineParams:A||F.shouldInlineParams});if(X(F,I)){let $=F[I.Symbol.Schema],W=F[I.Symbol.Name];return{sql:$===void 0?S(W):S($)+"."+S(W),params:[]}}if(X(F,Ro)){let $=t.getColumnCasing(F);if(n.invokeSource==="indexes")return{sql:S($),params:[]};let W=F.table[I.Symbol.Schema];return{sql:F.table[wS]||W===void 0?S(F.table[I.Symbol.Name])+"."+S($):S(W)+"."+S(F.table[I.Symbol.Name])+"."+S($),params:[]}}if(X(F,An)){let $=F[Yo].schema,W=F[Yo].name;return{sql:$===void 0?S(W):S($)+"."+S(W),params:[]}}if(X(F,$n)){if(X(F.value,nT))return{sql:f(M.value++,F),params:[F],typings:["none"]};let $=F.value===null?null:F.encoder.mapToDriverValue(F.value);if(X($,j))return this.buildQueryFromSourceParams([$],T);if(A)return{sql:this.mapInlineParam($,T),params:[]};let W=["none"];if(y)W=[y(F.encoder)];return{sql:f(M.value++,$),params:[$],typings:W}}if(X(F,nT))return{sql:f(M.value++,F),params:[F],typings:["none"]};if(X(F,j.Aliased)&&F.fieldAlias!==void 0)return{sql:S(F.fieldAlias),params:[]};if(X(F,bo)){if(F._.isWith)return{sql:S(F._.alias),params:[]};return this.buildQueryFromSourceParams([new ho("("),F._.sql,new ho(") "),new KS(F._.alias)],T)}if(SM(F)){if(F.schema)return{sql:S(F.schema)+"."+S(F.enumName),params:[]};return{sql:S(F.enumName),params:[]}}if(ef(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 j.Aliased(this,o)}mapWith(o){return this.decoder=typeof o==="function"?{mapFromDriverValue:o}:o,this}inlineParams(){return this.shouldInlineParams=!0,this}if(o){return o?this:void 0}}class KS{constructor(o){this.value=o}static[k]="Name";brand;getSQL(){return new j([this])}}function $M(o){return typeof o==="object"&&o!==null&&"mapToDriverValue"in o&&typeof o.mapToDriverValue==="function"}var JM={mapFromDriverValue:(o)=>o},kM={mapToDriverValue:(o)=>o},FY={...JM,...kM};class $n{constructor(o,n=kM){this.value=o,this.encoder=n}static[k]="Param";brand;getSQL(){return new j([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 j(T)}((o)=>{function n(){return new j([])}o.empty=n;function T(M){return new j(M)}o.fromList=T;function t(M){return new j([new ho(M)])}o.raw=t;function S(M,F){let $=[];for(let[W,O]of M.entries()){if(W>0&&F!==void 0)$.push(F);$.push(O)}return new j($)}o.join=S;function f(M){return new KS(M)}o.identifier=f;function y(M){return new nT(M)}o.placeholder=y;function A(M,F){return new $n(M,F)}o.param=A})(R||(R={}));((o)=>{class n{constructor(T,t){this.sql=T,this.fieldAlias=t}static[k]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new n(this.sql,this.fieldAlias)}}o.Aliased=n})(j||(j={}));class nT{constructor(o){this.name=o}static[k]="Placeholder";getSQL(){return new j([this])}}function df(o,n){return o.map((T)=>{if(X(T,nT)){if(!(T.name in n))throw new Error(`No value for placeholder "${T.name}" was provided`);return n[T.name]}if(X(T,$n)&&X(T.value,nT)){if(!(T.value.name in n))throw new Error(`No value for placeholder "${T.value.name}" was provided`);return T.encoder.mapToDriverValue(n[T.value.name])}return T})}var ek=Symbol.for("drizzle:IsDrizzleView");class An{static[k]="View";[Yo];[ek]=!0;constructor({name:o,schema:n,selectedFields:T,query:t}){this[Yo]={name:o,originalName:o,schema:n,selectedFields:T,query:t,isExisting:!t,isAlias:!1}}getSQL(){return new j([this])}}Ro.prototype.getSQL=function(){return new j([this])};I.prototype.getSQL=function(){return new j([this])};bo.prototype.getSQL=function(){return new j([this])};class IT{constructor(o){this.table=o}static[k]="ColumnAliasProxyHandler";get(o,n){if(n==="table")return this.table;return o[n]}}class Xt{constructor(o,n){this.alias=o,this.replaceOriginalName=n}static[k]="TableAliasProxyHandler";get(o,n){if(n===I.Symbol.IsAlias)return!0;if(n===I.Symbol.Name)return this.alias;if(this.replaceOriginalName&&n===I.Symbol.OriginalName)return this.alias;if(n===Yo)return{...o[Yo],name:this.alias,isAlias:!0};if(n===I.Symbol.Columns){let t=o[I.Symbol.Columns];if(!t)return t;let S={};return Object.keys(t).map((f)=>{S[f]=new Proxy(t[f],new IT(new Proxy(o,this)))}),S}let T=o[n];if(X(T,Ro))return new Proxy(T,new IT(new Proxy(o,this)));return T}}function XS(o,n){return new Proxy(o,new Xt(n,!1))}function rn(o,n){return new Proxy(o,new IT(new Proxy(o.table,new Xt(n,!1))))}function uf(o,n){return new j.Aliased(Et(o.sql,n),o.fieldAlias)}function Et(o,n){return R.join(o.queryChunks.map((T)=>{if(X(T,Ro))return rn(T,n);if(X(T,j))return Et(T,n);if(X(T,j.Aliased))return uf(T,n);return T}))}class ES extends Error{static[k]="DrizzleError";constructor({message:o,cause:n}){super(o);this.name="DrizzleError",this.cause=n}}class af extends ES{static[k]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}function Mn(o,n){if($M(n)&&!ef(o)&&!X(o,$n)&&!X(o,nT)&&!X(o,Ro)&&!X(o,I)&&!X(o,An))return new $n(o,n);return o}var jT=(o,n)=>{return R`${o} = ${Mn(n,o)}`},RM=(o,n)=>{return R`${o} <> ${Mn(n,o)}`};function Yt(...o){let n=o.filter((T)=>T!==void 0);if(n.length===0)return;if(n.length===1)return new j(n);return new j([new ho("("),R.join(n,new ho(" and ")),new ho(")")])}function WM(...o){let n=o.filter((T)=>T!==void 0);if(n.length===0)return;if(n.length===1)return new j(n);return new j([new ho("("),R.join(n,new ho(" or ")),new ho(")")])}function OM(o){return R`not ${o}`}var _M=(o,n)=>{return R`${o} > ${Mn(n,o)}`},wM=(o,n)=>{return R`${o} >= ${Mn(n,o)}`},KM=(o,n)=>{return R`${o} < ${Mn(n,o)}`},XM=(o,n)=>{return R`${o} <= ${Mn(n,o)}`};function EM(o,n){if(Array.isArray(n)){if(n.length===0)return R`false`;return R`${o} in ${n.map((T)=>Mn(T,o))}`}return R`${o} in ${Mn(n,o)}`}function YM(o,n){if(Array.isArray(n)){if(n.length===0)return R`true`;return R`${o} not in ${n.map((T)=>Mn(T,o))}`}return R`${o} not in ${Mn(n,o)}`}function GM(o){return R`${o} is null`}function zM(o){return R`${o} is not null`}function HM(o){return R`exists ${o}`}function mM(o){return R`not exists ${o}`}function QM(o,n,T){return R`${o} between ${Mn(n,o)} and ${Mn(T,o)}`}function DM(o,n,T){return R`${o} not between ${Mn(n,o)} and ${Mn(T,o)}`}function UM(o,n){return R`${o} like ${n}`}function VM(o,n){return R`${o} not like ${n}`}function BM(o,n){return R`${o} ilike ${n}`}function CM(o,n){return R`${o} not ilike ${n}`}function LM(o){return R`${o} asc`}function IM(o){return R`${o} desc`}class jM{static[k]="ConsoleLogWriter";write(o){console.log(o)}}class sf{static[k]="DefaultLogger";writer;constructor(o){this.writer=o?.writer??new jM}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 oy{static[k]="NoopLogger";logQuery(){}}class on{static[k]="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 rM(o,n,T){let t={},S=o.reduce((f,{path:y,field:A},M)=>{let F;if(X(A,Ro))F=A;else if(X(A,j))F=A.decoder;else F=A.sql.decoder;let $=f;for(let[W,O]of y.entries())if(W<y.length-1){if(!(O in $))$[O]={};$=$[O]}else{let G=n[M],D=$[O]=G===null?null:F.mapFromDriverValue(G);if(T&&X(A,Ro)&&y.length===2){let z=y[0];if(!(z in t))t[z]=D===null?_n(A.table):!1;else if(typeof t[z]==="string"&&t[z]!==_n(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 wn(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,Ro)||X(S,j)||X(S,j.Aliased))T.push({path:f,field:S});else if(X(S,I))T.push(...wn(S[I.Symbol.Columns],f));else T.push(...wn(S,f));return T},[])}function Gt(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 YS(o,n){let T=Object.entries(n).filter(([,t])=>t!==void 0).map(([t,S])=>{if(X(S,j)||X(S,Ro))return[t,S];else return[t,new $n(S,o[I.Symbol.Columns][t])]});if(T.length===0)throw new Error("No values to set");return Object.fromEntries(T)}function NM(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 bM(o){return o[I.Symbol.Columns]}function Zn(o){return X(o,bo)?o._.alias:X(o,An)?o[Yo].name:X(o,j)?void 0:o[I.Symbol.IsAlias]?o[I.Symbol.Name]:o[I.Symbol.BaseName]}function So(o,n){return{name:typeof o==="string"&&o.length>0?o:"",config:typeof o==="object"?o:n}}function hM(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 TT extends b{static[k]="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 xM extends TT{static[k]="PgBigInt53Builder";constructor(o){super(o,"number","PgBigInt53")}build(o){return new cM(o,this.config)}}class cM extends V{static[k]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(o){if(typeof o==="number")return o;return Number(o)}}class vM extends TT{static[k]="PgBigInt64Builder";constructor(o){super(o,"bigint","PgBigInt64")}build(o){return new iM(o,this.config)}}class iM extends V{static[k]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(o){return BigInt(o)}}function pM(o,n){let{name:T,config:t}=So(o,n);if(t.mode==="number")return new xM(T);return new vM(T)}class qM extends b{static[k]="PgBigSerial53Builder";constructor(o){super(o,"number","PgBigSerial53");this.config.hasDefault=!0,this.config.notNull=!0}build(o){return new ZM(o,this.config)}}class ZM extends V{static[k]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(o){if(typeof o==="number")return o;return Number(o)}}class PM extends b{static[k]="PgBigSerial64Builder";constructor(o){super(o,"bigint","PgBigSerial64");this.config.hasDefault=!0}build(o){return new gM(o,this.config)}}class gM extends V{static[k]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(o){return BigInt(o)}}function lM(o,n){let{name:T,config:t}=So(o,n);if(t.mode==="number")return new qM(T);return new PM(T)}class eM extends b{static[k]="PgBooleanBuilder";constructor(o){super(o,"boolean","PgBoolean")}build(o){return new dM(o,this.config)}}class dM extends V{static[k]="PgBoolean";getSQLType(){return"boolean"}}function zt(o){return new eM(o??"")}class uM extends b{static[k]="PgCharBuilder";constructor(o,n){super(o,"string","PgChar");this.config.length=n.length,this.config.enumValues=n.enum}build(o){return new aM(o,this.config)}}class aM extends V{static[k]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}}function sM(o,n={}){let{name:T,config:t}=So(o,n);return new uM(T,t)}class oF extends b{static[k]="PgCidrBuilder";constructor(o){super(o,"string","PgCidr")}build(o){return new nF(o,this.config)}}class nF extends V{static[k]="PgCidr";getSQLType(){return"cidr"}}function TF(o){return new oF(o??"")}class tF extends b{static[k]="PgCustomColumnBuilder";constructor(o,n,T){super(o,"custom","PgCustomColumn");this.config.fieldConfig=n,this.config.customTypeParams=T}build(o){return new SF(o,this.config)}}class SF extends V{static[k]="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 fF(o){return(n,T)=>{let{name:t,config:S}=So(n,T);return new tF(t,S,o)}}class Pn extends b{static[k]="PgDateColumnBaseBuilder";defaultNow(){return this.default(R`now()`)}}class yF extends Pn{static[k]="PgDateBuilder";constructor(o){super(o,"date","PgDate")}build(o){return new GS(o,this.config)}}class GS extends V{static[k]="PgDate";getSQLType(){return"date"}mapFromDriverValue(o){return new Date(o)}mapToDriverValue(o){return o.toISOString()}}class AF extends Pn{static[k]="PgDateStringBuilder";constructor(o){super(o,"string","PgDateString")}build(o){return new zS(o,this.config)}}class zS extends V{static[k]="PgDateString";getSQLType(){return"date"}}function MF(o,n){let{name:T,config:t}=So(o,n);if(t?.mode==="date")return new yF(T);return new AF(T)}class FF extends b{static[k]="PgDoublePrecisionBuilder";constructor(o){super(o,"number","PgDoublePrecision")}build(o){return new $F(o,this.config)}}class $F extends V{static[k]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(o){if(typeof o==="string")return Number.parseFloat(o);return o}}function JF(o){return new FF(o??"")}class kF extends b{static[k]="PgInetBuilder";constructor(o){super(o,"string","PgInet")}build(o){return new RF(o,this.config)}}class RF extends V{static[k]="PgInet";getSQLType(){return"inet"}}function WF(o){return new kF(o??"")}class OF extends TT{static[k]="PgIntegerBuilder";constructor(o){super(o,"number","PgInteger")}build(o){return new _F(o,this.config)}}class _F extends V{static[k]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(o){if(typeof o==="string")return Number.parseInt(o);return o}}function HS(o){return new OF(o??"")}class wF extends b{static[k]="PgIntervalBuilder";constructor(o,n){super(o,"string","PgInterval");this.config.intervalConfig=n}build(o){return new KF(o,this.config)}}class KF extends V{static[k]="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 XF(o,n={}){let{name:T,config:t}=So(o,n);return new wF(T,t)}class EF extends b{static[k]="PgJsonBuilder";constructor(o){super(o,"json","PgJson")}build(o){return new mS(o,this.config)}}class mS extends V{static[k]="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 YF(o){return new EF(o??"")}class GF extends b{static[k]="PgJsonbBuilder";constructor(o){super(o,"json","PgJsonb")}build(o){return new QS(o,this.config)}}class QS extends V{static[k]="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 zF(o){return new GF(o??"")}class HF extends b{static[k]="PgLineBuilder";constructor(o){super(o,"array","PgLine")}build(o){return new mF(o,this.config)}}class mF extends V{static[k]="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 QF extends b{static[k]="PgLineABCBuilder";constructor(o){super(o,"json","PgLineABC")}build(o){return new DF(o,this.config)}}class DF extends V{static[k]="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 UF(o,n){let{name:T,config:t}=So(o,n);if(!t?.mode||t.mode==="tuple")return new HF(T);return new QF(T)}class VF extends b{static[k]="PgMacaddrBuilder";constructor(o){super(o,"string","PgMacaddr")}build(o){return new BF(o,this.config)}}class BF extends V{static[k]="PgMacaddr";getSQLType(){return"macaddr"}}function CF(o){return new VF(o??"")}class LF extends b{static[k]="PgMacaddr8Builder";constructor(o){super(o,"string","PgMacaddr8")}build(o){return new IF(o,this.config)}}class IF extends V{static[k]="PgMacaddr8";getSQLType(){return"macaddr8"}}function jF(o){return new LF(o??"")}class rF extends b{static[k]="PgNumericBuilder";constructor(o,n,T){super(o,"string","PgNumeric");this.config.precision=n,this.config.scale=T}build(o){return new DS(o,this.config)}}class DS extends V{static[k]="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 NF(o,n){let{name:T,config:t}=So(o,n);return new rF(T,t?.precision,t?.scale)}class bF extends b{static[k]="PgPointTupleBuilder";constructor(o){super(o,"array","PgPointTuple")}build(o){return new hF(o,this.config)}}class hF extends V{static[k]="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 xF extends b{static[k]="PgPointObjectBuilder";constructor(o){super(o,"json","PgPointObject")}build(o){return new cF(o,this.config)}}class cF extends V{static[k]="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 vF(o,n){let{name:T,config:t}=So(o,n);if(!t?.mode||t.mode==="tuple")return new bF(T);return new xF(T)}function dk(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 iF(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 ny(o){let n=dk(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=iF(n,T);T+=8;let M=iF(n,T);return T+=8,[A,M]}throw new Error("Unsupported geometry type")}class pF extends b{static[k]="PgGeometryBuilder";constructor(o){super(o,"array","PgGeometry")}build(o){return new qF(o,this.config)}}class qF extends V{static[k]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(o){return ny(o)}mapToDriverValue(o){return`point(${o[0]} ${o[1]})`}}class ZF extends b{static[k]="PgGeometryObjectBuilder";constructor(o){super(o,"json","PgGeometryObject")}build(o){return new PF(o,this.config)}}class PF extends V{static[k]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(o){let n=ny(o);return{x:n[0],y:n[1]}}mapToDriverValue(o){return`point(${o.x} ${o.y})`}}function gF(o,n){let{name:T,config:t}=So(o,n);if(!t?.mode||t.mode==="tuple")return new pF(T);return new ZF(T)}class lF extends b{static[k]="PgRealBuilder";constructor(o,n){super(o,"number","PgReal");this.config.length=n}build(o){return new eF(o,this.config)}}class eF extends V{static[k]="PgReal";constructor(o,n){super(o,n)}getSQLType(){return"real"}mapFromDriverValue=(o)=>{if(typeof o==="string")return Number.parseFloat(o);return o}}function dF(o){return new lF(o??"")}class uF extends b{static[k]="PgSerialBuilder";constructor(o){super(o,"number","PgSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(o){return new aF(o,this.config)}}class aF extends V{static[k]="PgSerial";getSQLType(){return"serial"}}function sF(o){return new uF(o??"")}class o$ extends TT{static[k]="PgSmallIntBuilder";constructor(o){super(o,"number","PgSmallInt")}build(o){return new n$(o,this.config)}}class n$ extends V{static[k]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=(o)=>{if(typeof o==="string")return Number(o);return o}}function T$(o){return new o$(o??"")}class t$ extends b{static[k]="PgSmallSerialBuilder";constructor(o){super(o,"number","PgSmallSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(o){return new S$(o,this.config)}}class S$ extends V{static[k]="PgSmallSerial";getSQLType(){return"smallserial"}}function f$(o){return new t$(o??"")}class y$ extends b{static[k]="PgTextBuilder";constructor(o,n){super(o,"string","PgText");this.config.enumValues=n.enum}build(o){return new A$(o,this.config)}}class A$ extends V{static[k]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function M$(o,n={}){let{name:T,config:t}=So(o,n);return new y$(T,t)}class F$ extends Pn{constructor(o,n,T){super(o,"string","PgTime");this.withTimezone=n,this.precision=T,this.config.withTimezone=n,this.config.precision=T}static[k]="PgTimeBuilder";build(o){return new US(o,this.config)}}class US extends V{static[k]="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 $$(o,n={}){let{name:T,config:t}=So(o,n);return new F$(T,t.withTimezone??!1,t.precision)}class J$ extends Pn{static[k]="PgTimestampBuilder";constructor(o,n,T){super(o,"date","PgTimestamp");this.config.withTimezone=n,this.config.precision=T}build(o){return new VS(o,this.config)}}class VS extends V{static[k]="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 k$ extends Pn{static[k]="PgTimestampStringBuilder";constructor(o,n,T){super(o,"string","PgTimestampString");this.config.withTimezone=n,this.config.precision=T}build(o){return new BS(o,this.config)}}class BS extends V{static[k]="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 Qn(o,n={}){let{name:T,config:t}=So(o,n);if(t?.mode==="string")return new k$(T,t.withTimezone??!1,t.precision);return new J$(T,t?.withTimezone??!1,t?.precision)}class R$ extends b{static[k]="PgUUIDBuilder";constructor(o){super(o,"string","PgUUID")}defaultRandom(){return this.default(R`gen_random_uuid()`)}build(o){return new CS(o,this.config)}}class CS extends V{static[k]="PgUUID";getSQLType(){return"uuid"}}function Jn(o){return new R$(o??"")}class W$ extends b{static[k]="PgVarcharBuilder";constructor(o,n){super(o,"string","PgVarchar");this.config.length=n.length,this.config.enumValues=n.enum}build(o){return new O$(o,this.config)}}class O$ extends V{static[k]="PgVarchar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"varchar":`varchar(${this.length})`}}function co(o,n={}){let{name:T,config:t}=So(o,n);return new W$(T,t)}class _$ extends b{static[k]="PgBinaryVectorBuilder";constructor(o,n){super(o,"string","PgBinaryVector");this.config.dimensions=n.dimensions}build(o){return new w$(o,this.config)}}class w$ extends V{static[k]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}}function K$(o,n){let{name:T,config:t}=So(o,n);return new _$(T,t)}class X$ extends b{static[k]="PgHalfVectorBuilder";constructor(o,n){super(o,"array","PgHalfVector");this.config.dimensions=n.dimensions}build(o){return new E$(o,this.config)}}class E$ extends V{static[k]="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 Y$(o,n){let{name:T,config:t}=So(o,n);return new X$(T,t)}class G$ extends b{static[k]="PgSparseVectorBuilder";constructor(o,n){super(o,"string","PgSparseVector");this.config.dimensions=n.dimensions}build(o){return new z$(o,this.config)}}class z$ extends V{static[k]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function H$(o,n){let{name:T,config:t}=So(o,n);return new G$(T,t)}class m$ extends b{static[k]="PgVectorBuilder";constructor(o,n){super(o,"array","PgVector");this.config.dimensions=n.dimensions}build(o){return new Q$(o,this.config)}}class Q$ extends V{static[k]="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 D$(o,n){let{name:T,config:t}=So(o,n);return new m$(T,t)}function U$(){return{bigint:pM,bigserial:lM,boolean:zt,char:sM,cidr:TF,customType:fF,date:MF,doublePrecision:JF,inet:WF,integer:HS,interval:XF,json:YF,jsonb:zF,line:UF,macaddr:CF,macaddr8:jF,numeric:NF,point:vF,geometry:gF,real:dF,serial:sF,smallint:T$,smallserial:f$,text:M$,time:$$,timestamp:Qn,uuid:Jn,varchar:co,bit:K$,halfvec:Y$,sparsevec:H$,vector:D$}}var Ty=Symbol.for("drizzle:PgInlineForeignKeys"),V$=Symbol.for("drizzle:EnableRLS");class vo extends I{static[k]="PgTable";static Symbol=Object.assign({},I.Symbol,{InlineForeignKeys:Ty,EnableRLS:V$});[Ty]=[];[V$]=!1;[I.Symbol.ExtraConfigBuilder]=void 0}function uk(o,n,T,t,S=o){let f=new vo(o,t,S),y=typeof n==="function"?n(U$()):n,A=Object.fromEntries(Object.entries(y).map(([$,W])=>{let O=W;O.setName($);let G=O.build(f);return f[Ty].push(...O.buildForeignKeys(G,f)),[$,G]})),M=Object.fromEntries(Object.entries(y).map(([$,W])=>{let O=W;O.setName($);let G=O.buildExtraConfigColumn(f);return[$,G]})),F=Object.assign(f,A);if(F[I.Symbol.Columns]=A,F[I.Symbol.ExtraConfigColumns]=M,T)F[vo.Symbol.ExtraConfigBuilder]=T;return Object.assign(F,{enableRLS:()=>{return F[vo.Symbol.EnableRLS]=!0,F}})}var tT=(o,n,T)=>{return uk(o,n,T,void 0)};function B$(...o){if(o[0].columns)return new Ht(o[0].columns,o[0].name);return new Ht(o)}class Ht{static[k]="PgPrimaryKeyBuilder";columns;name;constructor(o,n){this.columns=o,this.name=n}build(o){return new C$(o,this.columns,this.name)}}class C${constructor(o,n,T){this.table=o,this.columns=n,this.name=T}static[k]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[vo.Symbol.Name]}_${this.columns.map((o)=>o.name).join("_")}_pk`}}class ty{constructor(o,n,T){this.sourceTable=o,this.referencedTable=n,this.relationName=T,this.referencedTableName=n[I.Symbol.Name]}static[k]="Relation";referencedTableName;fieldName}class L${constructor(o,n){this.table=o,this.config=n}static[k]="Relations"}class ST extends ty{constructor(o,n,T,t){super(o,n,T?.relationName);this.config=T,this.isNullable=t}static[k]="One";withFieldName(o){let n=new ST(this.sourceTable,this.referencedTable,this.config,this.isNullable);return n.fieldName=o,n}}class mt extends ty{constructor(o,n,T){super(o,n,T?.relationName);this.config=T}static[k]="Many";withFieldName(o){let n=new mt(this.sourceTable,this.referencedTable,this.config);return n.fieldName=o,n}}function I$(){return{and:Yt,between:QM,eq:jT,exists:HM,gt:_M,gte:wM,ilike:BM,inArray:EM,isNull:GM,isNotNull:zM,like:UM,lt:KM,lte:XM,ne:RM,not:OM,notBetween:DM,notExists:mM,notLike:VM,notIlike:CM,notInArray:YM,or:WM,sql:R}}function j$(){return{sql:R,asc:LM,desc:IM}}function r$(o,n){if(Object.keys(o).length===1&&"default"in o&&!X(o.default,I))o=o.default;let T={},t={},S={};for(let[f,y]of Object.entries(o))if(X(y,I)){let A=JT(y),M=t[A];T[A]=f,S[f]={tsName:f,dbName:y[I.Symbol.Name],schema:y[I.Symbol.Schema],columns:y[I.Symbol.Columns],relations:M?.relations??{},primaryKey:M?.primaryKey??[]};for(let $ of Object.values(y[I.Symbol.Columns]))if($.primary)S[f].primaryKey.push($);let F=y[I.Symbol.ExtraConfigBuilder]?.(y[I.Symbol.ExtraConfigColumns]);if(F){for(let $ of Object.values(F))if(X($,Ht))S[f].primaryKey.push(...$.columns)}}else if(X(y,L$)){let A=JT(y.table),M=T[A],F=y.config(n(y.table)),$;for(let[W,O]of Object.entries(F))if(M){let G=S[M];if(G.relations[W]=O,$)G.primaryKey.push(...$)}else{if(!(A in t))t[A]={relations:{},primaryKey:$};t[A].relations[W]=O}}return{tables:S,tableNamesMap:T}}function ak(o){return function n(T,t){return new ST(o,T,t,t?.fields.reduce((S,f)=>S&&f.notNull,!0)??!1)}}function sk(o){return function n(T,t){return new mt(o,T,t)}}function N$(o,n,T){if(X(T,ST)&&T.config)return{fields:T.config.fields,references:T.config.references};let t=n[JT(T.referencedTable)];if(!t)throw new Error(`Table "${T.referencedTable[I.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[JT(f)];if(!y)throw new Error(`Table "${f[I.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[I.Symbol.Name]}". Please specify relation name`);if(A[0]&&X(A[0],ST)&&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 b$(o){return{one:ak(o),many:sk(o)}}function LS(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],$=typeof F==="string"?JSON.parse(F):F;f[A.tsKey]=X(M,ST)?$&&LS(o,o[A.relationTableTsKey],$,A.selection,S):$.map((W)=>LS(o,o[A.relationTableTsKey],W,A.selection,S))}else{let M=S(T[y]),F=A.field,$;if(X(F,Ro))$=F;else if(X(F,j))$=F.decoder;else $=F.sql.decoder;f[A.tsKey]=M===null?null:$.mapFromDriverValue(M)}return f}import{readFileSync as u$}from"fs";import{resolve as Fy}from"path";var Mo;(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}})(Mo||(Mo={}));var fy;(function(o){o.mergeShapes=(n,T)=>{return{...n,...T}}})(fy||(fy={}));var r=Mo.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ln=(o)=>{switch(typeof o){case"undefined":return r.undefined;case"string":return r.string;case"number":return isNaN(o)?r.nan:r.number;case"boolean":return r.boolean;case"function":return r.function;case"bigint":return r.bigint;case"symbol":return r.symbol;case"object":if(Array.isArray(o))return r.array;if(o===null)return r.null;if(o.then&&typeof o.then==="function"&&o.catch&&typeof o.catch==="function")return r.promise;if(typeof Map!=="undefined"&&o instanceof Map)return r.map;if(typeof Set!=="undefined"&&o instanceof Set)return r.set;if(typeof Date!=="undefined"&&o instanceof Date)return r.date;return r.object;default:return r.unknown}},m=Mo.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"]),oR=(o)=>{return JSON.stringify(o,null,2).replace(/"([^"]+)":/g,"$1:")};class kn extends Error{get errors(){return this.issues}constructor(o){super();this.issues=[],this.addIssue=(T)=>{this.issues=[...this.issues,T]},this.addIssues=(T=[])=>{this.issues=[...this.issues,...T]};let n=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,n);else this.__proto__=n;this.name="ZodError",this.issues=o}format(o){let n=o||function(S){return S.message},T={_errors:[]},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 kn))throw new Error(`Not a ZodError: ${o}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Mo.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()}}kn.create=(o)=>{return new kn(o)};var hT=(o,n)=>{let T;switch(o.code){case m.invalid_type:if(o.received===r.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,Mo.jsonStringifyReplacer)}`;break;case m.unrecognized_keys:T=`Unrecognized key(s) in object: ${Mo.joinValues(o.keys,", ")}`;break;case m.invalid_union:T="Invalid input";break;case m.invalid_union_discriminator:T=`Invalid discriminator value. Expected ${Mo.joinValues(o.options)}`;break;case m.invalid_enum_value:T=`Invalid enum value. Expected ${Mo.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 Mo.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,Mo.assertNever(o)}return{message:T}},c$=hT;function nR(o){c$=o}function IS(){return c$}var jS=(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}},TR=[];function L(o,n){let T=IS(),t=jS({issueData:n,data:o.data,path:o.path,errorMaps:[o.common.contextualErrorMap,o.schemaErrorMap,T,T===hT?void 0:hT].filter((S)=>!!S)});o.common.issues.push(t)}class eo{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 eo.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"}),NT=(o)=>({status:"dirty",value:o}),nn=(o)=>({status:"valid",value:o}),yy=(o)=>o.status==="aborted",Ay=(o)=>o.status==="dirty",kT=(o)=>o.status==="valid",Ut=(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 v$(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 i;(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})(i||(i={}));var Qt,Dt;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 h$=(o,n)=>{if(kT(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 kn(o.common.issues);return this._error=T,this._error}}}};function oo(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:$}=o;if(y.code==="invalid_enum_value")return{message:$!==null&&$!==void 0?$:A.defaultError};if(typeof A.data==="undefined")return{message:(M=$!==null&&$!==void 0?$:t)!==null&&M!==void 0?M:A.defaultError};if(y.code!=="invalid_type")return{message:A.defaultError};return{message:(F=$!==null&&$!==void 0?$:T)!==null&&F!==void 0?F:A.defaultError}},description:S}}class no{get description(){return this._def.description}_getType(o){return ln(o.data)}_getOrReturnCtx(o,n){return n||{common:o.parent.common,data:o.data,parsedType:ln(o.data),schemaErrorMap:this._def.errorMap,path:o.path,parent:o.parent}}_processInputParams(o){return{status:new eo,ctx:{common:o.parent.common,data:o.data,parsedType:ln(o.data),schemaErrorMap:this._def.errorMap,path:o.path,parent:o.parent}}}_parseSync(o){let n=this._parse(o);if(Ut(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:ln(o)},S=this._parseSync({data:o,path:t.path,parent:t});return h$(t,S)}"~validate"(o){var n,T;let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:o,parsedType:ln(o)};if(!this["~standard"].async)try{let S=this._parseSync({data:o,path:[],parent:t});return kT(S)?{value:S.value}:{issues:t.common.issues}}catch(S){if((T=(n=S===null||S===void 0?void 0:S.message)===null||n===void 0?void 0:n.toLowerCase())===null||T===void 0?void 0:T.includes("encountered"))this["~standard"].async=!0;t.common={issues:[],async:!0}}return this._parseAsync({data:o,path:[],parent:t}).then((S)=>kT(S)?{value:S.value}:{issues:t.common.issues})}async parseAsync(o,n){let T=await this.safeParseAsync(o,n);if(T.success)return T.data;throw T.error}async safeParseAsync(o,n){let T={common:{issues:[],contextualErrorMap:n===null||n===void 0?void 0:n.errorMap,async:!0},path:(n===null||n===void 0?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:o,parsedType:ln(o)},t=this._parse({data:o,path:T.path,parent:T}),S=await(Ut(t)?t:Promise.resolve(t));return h$(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:e.ZodEffects,effect:{type:"refinement",refinement:o}})}superRefine(o){return this._refinement(o)}constructor(o){this.spa=this.safeParseAsync,this._def=o,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:(n)=>this["~validate"](n)}}optional(){return Vn.create(this,this._def)}nullable(){return en.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Un.create(this)}promise(){return _T.create(this,this._def)}or(o){return iT.create([this,o],this._def)}and(o){return pT.create(this,o,this._def)}transform(o){return new Kn({...oo(this._def),schema:this,typeName:e.ZodEffects,effect:{type:"transform",transform:o}})}default(o){let n=typeof o==="function"?o:()=>o;return new gT({...oo(this._def),innerType:this,defaultValue:n,typeName:e.ZodDefault})}brand(){return new bS({typeName:e.ZodBranded,type:this,...oo(this._def)})}catch(o){let n=typeof o==="function"?o:()=>o;return new lT({...oo(this._def),innerType:this,catchValue:n,typeName:e.ZodCatch})}describe(o){return new this.constructor({...this._def,description:o})}pipe(o){return jt.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,SR=/^[0-9a-z]+$/,fR=/^[0-9A-HJKMNP-TV-Z]{26}$/i,yR=/^[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,AR=/^[a-z0-9_-]{21}$/i,MR=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,FR=/^[-+]?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)?)??$/,$R=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,JR="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Sy,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])$/,RR=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,WR=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,OR=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,_R=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,wR=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,i$="((\\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])))",KR=new RegExp(`^${i$}$`);function p$(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 XR(o){return new RegExp(`^${p$(o)}$`)}function q$(o){let n=`${i$}T${p$(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 ER(o,n){if((n==="v4"||!n)&&kR.test(o))return!0;if((n==="v6"||!n)&&WR.test(o))return!0;return!1}function YR(o,n){if(!MR.test(o))return!1;try{let[T]=o.split("."),t=T.replace(/-/g,"+").replace(/_/g,"/").padEnd(T.length+(4-T.length%4)%4,"="),S=JSON.parse(atob(t));if(typeof S!=="object"||S===null)return!1;if(!S.typ||!S.alg)return!1;if(n&&S.alg!==n)return!1;return!0}catch(T){return!1}}function GR(o,n){if((n==="v4"||!n)&&RR.test(o))return!0;if((n==="v6"||!n)&&OR.test(o))return!0;return!1}class Dn extends no{_parse(o){if(this._def.coerce)o.data=String(o.data);if(this._getType(o)!==r.string){let S=this._getOrReturnCtx(o);return L(S,{code:m.invalid_type,expected:r.string,received:S.parsedType}),u}let T=new eo,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),L(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),L(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)L(t,{code:m.too_big,maximum:S.value,type:"string",inclusive:!0,exact:!0,message:S.message});else if(y)L(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(!$R.test(o.data))t=this._getOrReturnCtx(o,t),L(t,{validation:"email",code:m.invalid_string,message:S.message}),T.dirty()}else if(S.kind==="emoji"){if(!Sy)Sy=new RegExp(JR,"u");if(!Sy.test(o.data))t=this._getOrReturnCtx(o,t),L(t,{validation:"emoji",code:m.invalid_string,message:S.message}),T.dirty()}else if(S.kind==="uuid"){if(!yR.test(o.data))t=this._getOrReturnCtx(o,t),L(t,{validation:"uuid",code:m.invalid_string,message:S.message}),T.dirty()}else if(S.kind==="nanoid"){if(!AR.test(o.data))t=this._getOrReturnCtx(o,t),L(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),L(t,{validation:"cuid",code:m.invalid_string,message:S.message}),T.dirty()}else if(S.kind==="cuid2"){if(!SR.test(o.data))t=this._getOrReturnCtx(o,t),L(t,{validation:"cuid2",code:m.invalid_string,message:S.message}),T.dirty()}else if(S.kind==="ulid"){if(!fR.test(o.data))t=this._getOrReturnCtx(o,t),L(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),L(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),L(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),L(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),L(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),L(t,{code:m.invalid_string,validation:{endsWith:S.value},message:S.message}),T.dirty()}else if(S.kind==="datetime"){if(!q$(S).test(o.data))t=this._getOrReturnCtx(o,t),L(t,{code:m.invalid_string,validation:"datetime",message:S.message}),T.dirty()}else if(S.kind==="date"){if(!KR.test(o.data))t=this._getOrReturnCtx(o,t),L(t,{code:m.invalid_string,validation:"date",message:S.message}),T.dirty()}else if(S.kind==="time"){if(!XR(S).test(o.data))t=this._getOrReturnCtx(o,t),L(t,{code:m.invalid_string,validation:"time",message:S.message}),T.dirty()}else if(S.kind==="duration"){if(!FR.test(o.data))t=this._getOrReturnCtx(o,t),L(t,{validation:"duration",code:m.invalid_string,message:S.message}),T.dirty()}else if(S.kind==="ip"){if(!ER(o.data,S.version))t=this._getOrReturnCtx(o,t),L(t,{validation:"ip",code:m.invalid_string,message:S.message}),T.dirty()}else if(S.kind==="jwt"){if(!YR(o.data,S.alg))t=this._getOrReturnCtx(o,t),L(t,{validation:"jwt",code:m.invalid_string,message:S.message}),T.dirty()}else if(S.kind==="cidr"){if(!GR(o.data,S.version))t=this._getOrReturnCtx(o,t),L(t,{validation:"cidr",code:m.invalid_string,message:S.message}),T.dirty()}else if(S.kind==="base64"){if(!_R.test(o.data))t=this._getOrReturnCtx(o,t),L(t,{validation:"base64",code:m.invalid_string,message:S.message}),T.dirty()}else if(S.kind==="base64url"){if(!wR.test(o.data))t=this._getOrReturnCtx(o,t),L(t,{validation:"base64url",code:m.invalid_string,message:S.message}),T.dirty()}else Mo.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,...i.errToObj(T)})}_addCheck(o){return new Dn({...this._def,checks:[...this._def.checks,o]})}email(o){return this._addCheck({kind:"email",...i.errToObj(o)})}url(o){return this._addCheck({kind:"url",...i.errToObj(o)})}emoji(o){return this._addCheck({kind:"emoji",...i.errToObj(o)})}uuid(o){return this._addCheck({kind:"uuid",...i.errToObj(o)})}nanoid(o){return this._addCheck({kind:"nanoid",...i.errToObj(o)})}cuid(o){return this._addCheck({kind:"cuid",...i.errToObj(o)})}cuid2(o){return this._addCheck({kind:"cuid2",...i.errToObj(o)})}ulid(o){return this._addCheck({kind:"ulid",...i.errToObj(o)})}base64(o){return this._addCheck({kind:"base64",...i.errToObj(o)})}base64url(o){return this._addCheck({kind:"base64url",...i.errToObj(o)})}jwt(o){return this._addCheck({kind:"jwt",...i.errToObj(o)})}ip(o){return this._addCheck({kind:"ip",...i.errToObj(o)})}cidr(o){return this._addCheck({kind:"cidr",...i.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,...i.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,...i.errToObj(o===null||o===void 0?void 0:o.message)})}duration(o){return this._addCheck({kind:"duration",...i.errToObj(o)})}regex(o,n){return this._addCheck({kind:"regex",regex:o,...i.errToObj(n)})}includes(o,n){return this._addCheck({kind:"includes",value:o,position:n===null||n===void 0?void 0:n.position,...i.errToObj(n===null||n===void 0?void 0:n.message)})}startsWith(o,n){return this._addCheck({kind:"startsWith",value:o,...i.errToObj(n)})}endsWith(o,n){return this._addCheck({kind:"endsWith",value:o,...i.errToObj(n)})}min(o,n){return this._addCheck({kind:"min",value:o,...i.errToObj(n)})}max(o,n){return this._addCheck({kind:"max",value:o,...i.errToObj(n)})}length(o,n){return this._addCheck({kind:"length",value:o,...i.errToObj(n)})}nonempty(o){return this.min(1,i.errToObj(o))}trim(){return new Dn({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Dn({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Dn({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((o)=>o.kind==="datetime")}get isDate(){return!!this._def.checks.find((o)=>o.kind==="date")}get isTime(){return!!this._def.checks.find((o)=>o.kind==="time")}get isDuration(){return!!this._def.checks.find((o)=>o.kind==="duration")}get isEmail(){return!!this._def.checks.find((o)=>o.kind==="email")}get isURL(){return!!this._def.checks.find((o)=>o.kind==="url")}get isEmoji(){return!!this._def.checks.find((o)=>o.kind==="emoji")}get isUUID(){return!!this._def.checks.find((o)=>o.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((o)=>o.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((o)=>o.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((o)=>o.kind==="cuid2")}get isULID(){return!!this._def.checks.find((o)=>o.kind==="ulid")}get isIP(){return!!this._def.checks.find((o)=>o.kind==="ip")}get isCIDR(){return!!this._def.checks.find((o)=>o.kind==="cidr")}get isBase64(){return!!this._def.checks.find((o)=>o.kind==="base64")}get isBase64url(){return!!this._def.checks.find((o)=>o.kind==="base64url")}get minLength(){let o=null;for(let n of this._def.checks)if(n.kind==="min"){if(o===null||n.value>o)o=n.value}return o}get maxLength(){let o=null;for(let n of this._def.checks)if(n.kind==="max"){if(o===null||n.value<o)o=n.value}return o}}Dn.create=(o)=>{var n;return new Dn({checks:[],typeName:e.ZodString,coerce:(n=o===null||o===void 0?void 0:o.coerce)!==null&&n!==void 0?n:!1,...oo(o)})};function zR(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 yT extends no{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)!==r.number){let S=this._getOrReturnCtx(o);return L(S,{code:m.invalid_type,expected:r.number,received:S.parsedType}),u}let T=void 0,t=new eo;for(let S of this._def.checks)if(S.kind==="int"){if(!Mo.isInteger(o.data))T=this._getOrReturnCtx(o,T),L(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),L(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),L(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(zR(o.data,S.value)!==0)T=this._getOrReturnCtx(o,T),L(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),L(T,{code:m.not_finite,message:S.message}),t.dirty()}else Mo.assertNever(S);return{status:t.value,value:o.data}}gte(o,n){return this.setLimit("min",o,!0,i.toString(n))}gt(o,n){return this.setLimit("min",o,!1,i.toString(n))}lte(o,n){return this.setLimit("max",o,!0,i.toString(n))}lt(o,n){return this.setLimit("max",o,!1,i.toString(n))}setLimit(o,n,T,t){return new yT({...this._def,checks:[...this._def.checks,{kind:o,value:n,inclusive:T,message:i.toString(t)}]})}_addCheck(o){return new yT({...this._def,checks:[...this._def.checks,o]})}int(o){return this._addCheck({kind:"int",message:i.toString(o)})}positive(o){return this._addCheck({kind:"min",value:0,inclusive:!1,message:i.toString(o)})}negative(o){return this._addCheck({kind:"max",value:0,inclusive:!1,message:i.toString(o)})}nonpositive(o){return this._addCheck({kind:"max",value:0,inclusive:!0,message:i.toString(o)})}nonnegative(o){return this._addCheck({kind:"min",value:0,inclusive:!0,message:i.toString(o)})}multipleOf(o,n){return this._addCheck({kind:"multipleOf",value:o,message:i.toString(n)})}finite(o){return this._addCheck({kind:"finite",message:i.toString(o)})}safe(o){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:i.toString(o)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:i.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"&&Mo.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)}}yT.create=(o)=>{return new yT({checks:[],typeName:e.ZodNumber,coerce:(o===null||o===void 0?void 0:o.coerce)||!1,...oo(o)})};class AT extends no{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(o){if(this._def.coerce)try{o.data=BigInt(o.data)}catch(S){return this._getInvalidInput(o)}if(this._getType(o)!==r.bigint)return this._getInvalidInput(o);let T=void 0,t=new eo;for(let S of this._def.checks)if(S.kind==="min"){if(S.inclusive?o.data<S.value:o.data<=S.value)T=this._getOrReturnCtx(o,T),L(T,{code: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),L(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),L(T,{code:m.not_multiple_of,multipleOf:S.value,message:S.message}),t.dirty()}else Mo.assertNever(S);return{status:t.value,value:o.data}}_getInvalidInput(o){let n=this._getOrReturnCtx(o);return L(n,{code:m.invalid_type,expected:r.bigint,received:n.parsedType}),u}gte(o,n){return this.setLimit("min",o,!0,i.toString(n))}gt(o,n){return this.setLimit("min",o,!1,i.toString(n))}lte(o,n){return this.setLimit("max",o,!0,i.toString(n))}lt(o,n){return this.setLimit("max",o,!1,i.toString(n))}setLimit(o,n,T,t){return new AT({...this._def,checks:[...this._def.checks,{kind:o,value:n,inclusive:T,message:i.toString(t)}]})}_addCheck(o){return new AT({...this._def,checks:[...this._def.checks,o]})}positive(o){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:i.toString(o)})}negative(o){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:i.toString(o)})}nonpositive(o){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:i.toString(o)})}nonnegative(o){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:i.toString(o)})}multipleOf(o,n){return this._addCheck({kind:"multipleOf",value:o,message:i.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}}AT.create=(o)=>{var n;return new AT({checks:[],typeName:e.ZodBigInt,coerce:(n=o===null||o===void 0?void 0:o.coerce)!==null&&n!==void 0?n:!1,...oo(o)})};class xT extends no{_parse(o){if(this._def.coerce)o.data=Boolean(o.data);if(this._getType(o)!==r.boolean){let T=this._getOrReturnCtx(o);return L(T,{code:m.invalid_type,expected:r.boolean,received:T.parsedType}),u}return nn(o.data)}}xT.create=(o)=>{return new xT({typeName:e.ZodBoolean,coerce:(o===null||o===void 0?void 0:o.coerce)||!1,...oo(o)})};class RT extends no{_parse(o){if(this._def.coerce)o.data=new Date(o.data);if(this._getType(o)!==r.date){let S=this._getOrReturnCtx(o);return L(S,{code:m.invalid_type,expected:r.date,received:S.parsedType}),u}if(isNaN(o.data.getTime())){let S=this._getOrReturnCtx(o);return L(S,{code:m.invalid_date}),u}let T=new eo,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),L(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),L(t,{code:m.too_big,message:S.message,inclusive:!0,exact:!1,maximum:S.value,type:"date"}),T.dirty()}else Mo.assertNever(S);return{status:T.value,value:new Date(o.data.getTime())}}_addCheck(o){return new RT({...this._def,checks:[...this._def.checks,o]})}min(o,n){return this._addCheck({kind:"min",value:o.getTime(),message:i.toString(n)})}max(o,n){return this._addCheck({kind:"max",value:o.getTime(),message:i.toString(n)})}get minDate(){let o=null;for(let n of this._def.checks)if(n.kind==="min"){if(o===null||n.value>o)o=n.value}return o!=null?new Date(o):null}get maxDate(){let o=null;for(let n of this._def.checks)if(n.kind==="max"){if(o===null||n.value<o)o=n.value}return o!=null?new Date(o):null}}RT.create=(o)=>{return new RT({checks:[],coerce:(o===null||o===void 0?void 0:o.coerce)||!1,typeName:e.ZodDate,...oo(o)})};class Vt extends no{_parse(o){if(this._getType(o)!==r.symbol){let T=this._getOrReturnCtx(o);return L(T,{code:m.invalid_type,expected:r.symbol,received:T.parsedType}),u}return nn(o.data)}}Vt.create=(o)=>{return new Vt({typeName:e.ZodSymbol,...oo(o)})};class cT extends no{_parse(o){if(this._getType(o)!==r.undefined){let T=this._getOrReturnCtx(o);return L(T,{code:m.invalid_type,expected:r.undefined,received:T.parsedType}),u}return nn(o.data)}}cT.create=(o)=>{return new cT({typeName:e.ZodUndefined,...oo(o)})};class vT extends no{_parse(o){if(this._getType(o)!==r.null){let T=this._getOrReturnCtx(o);return L(T,{code:m.invalid_type,expected:r.null,received:T.parsedType}),u}return nn(o.data)}}vT.create=(o)=>{return new vT({typeName:e.ZodNull,...oo(o)})};class WT extends no{constructor(){super(...arguments);this._any=!0}_parse(o){return nn(o.data)}}WT.create=(o)=>{return new WT({typeName:e.ZodAny,...oo(o)})};class fT extends no{constructor(){super(...arguments);this._unknown=!0}_parse(o){return nn(o.data)}}fT.create=(o)=>{return new fT({typeName:e.ZodUnknown,...oo(o)})};class Nn extends no{_parse(o){let n=this._getOrReturnCtx(o);return L(n,{code:m.invalid_type,expected:r.never,received:n.parsedType}),u}}Nn.create=(o)=>{return new Nn({typeName:e.ZodNever,...oo(o)})};class Bt extends no{_parse(o){if(this._getType(o)!==r.undefined){let T=this._getOrReturnCtx(o);return L(T,{code:m.invalid_type,expected:r.void,received:T.parsedType}),u}return nn(o.data)}}Bt.create=(o)=>{return new Bt({typeName:e.ZodVoid,...oo(o)})};class Un extends no{_parse(o){let{ctx:n,status:T}=this._processInputParams(o),t=this._def;if(n.parsedType!==r.array)return L(n,{code:m.invalid_type,expected:r.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)L(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)L(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)L(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 eo.mergeArray(T,f)});let S=[...n.data].map((f,y)=>{return t.type._parseSync(new Bn(n,f,n.path,y))});return eo.mergeArray(T,S)}get element(){return this._def.type}min(o,n){return new Un({...this._def,minLength:{value:o,message:i.toString(n)}})}max(o,n){return new Un({...this._def,maxLength:{value:o,message:i.toString(n)}})}length(o,n){return new Un({...this._def,exactLength:{value:o,message:i.toString(n)}})}nonempty(o){return this.min(1,o)}}Un.create=(o,n)=>{return new Un({type:o,minLength:null,maxLength:null,exactLength:null,typeName:e.ZodArray,...oo(n)})};function rT(o){if(o instanceof Do){let n={};for(let T in o.shape){let t=o.shape[T];n[T]=Vn.create(rT(t))}return new Do({...o._def,shape:()=>n})}else if(o instanceof Un)return new Un({...o._def,type:rT(o.element)});else if(o instanceof Vn)return Vn.create(rT(o.unwrap()));else if(o instanceof en)return en.create(rT(o.unwrap()));else if(o instanceof bn)return bn.create(o.items.map((n)=>rT(n)));else return o}class Do extends no{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=Mo.objectKeys(o);return this._cached={shape:o,keys:n}}_parse(o){if(this._getType(o)!==r.object){let M=this._getOrReturnCtx(o);return L(M,{code:m.invalid_type,expected:r.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],$=t.data[M];A.push({key:{status:"valid",value:M},value:F._parse(new Bn(t,$,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)L(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 $=t.data[F];A.push({key:{status:"valid",value:F},value:M._parse(new Bn(t,$,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 $=await F.key,W=await F.value;M.push({key:$,value:W,alwaysSet:F.alwaysSet})}return M}).then((M)=>{return eo.mergeObjectSync(T,M)});else return eo.mergeObjectSync(T,A)}get shape(){return this._def.shape()}strict(o){return i.errToObj,new Do({...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=i.errToObj(o).message)!==null&&y!==void 0?y:A};return{message:A}}}:{}})}strip(){return new Do({...this._def,unknownKeys:"strip"})}passthrough(){return new Do({...this._def,unknownKeys:"passthrough"})}extend(o){return new Do({...this._def,shape:()=>({...this._def.shape(),...o})})}merge(o){return new Do({unknownKeys:o._def.unknownKeys,catchall:o._def.catchall,shape:()=>({...this._def.shape(),...o._def.shape()}),typeName:e.ZodObject})}setKey(o,n){return this.augment({[o]:n})}catchall(o){return new Do({...this._def,catchall:o})}pick(o){let n={};return Mo.objectKeys(o).forEach((T)=>{if(o[T]&&this.shape[T])n[T]=this.shape[T]}),new Do({...this._def,shape:()=>n})}omit(o){let n={};return Mo.objectKeys(this.shape).forEach((T)=>{if(!o[T])n[T]=this.shape[T]}),new Do({...this._def,shape:()=>n})}deepPartial(){return rT(this)}partial(o){let n={};return Mo.objectKeys(this.shape).forEach((T)=>{let t=this.shape[T];if(o&&!o[T])n[T]=t;else n[T]=t.optional()}),new Do({...this._def,shape:()=>n})}required(o){let n={};return Mo.objectKeys(this.shape).forEach((T)=>{if(o&&!o[T])n[T]=this.shape[T];else{let S=this.shape[T];while(S instanceof Vn)S=S._def.innerType;n[T]=S}}),new Do({...this._def,shape:()=>n})}keyof(){return Z$(Mo.objectKeys(this.shape))}}Do.create=(o,n)=>{return new Do({shape:()=>o,unknownKeys:"strip",catchall:Nn.create(),typeName:e.ZodObject,...oo(n)})};Do.strictCreate=(o,n)=>{return new Do({shape:()=>o,unknownKeys:"strict",catchall:Nn.create(),typeName:e.ZodObject,...oo(n)})};Do.lazycreate=(o,n)=>{return new Do({shape:o,unknownKeys:"strip",catchall:Nn.create(),typeName:e.ZodObject,...oo(n)})};class iT extends no{_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 kn(y.ctx.common.issues));return L(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 kn(A));return L(n,{code:m.invalid_union,unionErrors:y}),u}}get options(){return this._def.options}}iT.create=(o,n)=>{return new iT({options:o,typeName:e.ZodUnion,...oo(n)})};var gn=(o)=>{if(o instanceof qT)return gn(o.schema);else if(o instanceof Kn)return gn(o.innerType());else if(o instanceof ZT)return[o.value];else if(o instanceof MT)return o.options;else if(o instanceof PT)return Mo.objectValues(o.enum);else if(o instanceof gT)return gn(o._def.innerType);else if(o instanceof cT)return[void 0];else if(o instanceof vT)return[null];else if(o instanceof Vn)return[void 0,...gn(o.unwrap())];else if(o instanceof en)return[null,...gn(o.unwrap())];else if(o instanceof bS)return gn(o.unwrap());else if(o instanceof eT)return gn(o.unwrap());else if(o instanceof lT)return gn(o._def.innerType);else return[]};class NS extends no{_parse(o){let{ctx:n}=this._processInputParams(o);if(n.parsedType!==r.object)return L(n,{code:m.invalid_type,expected:r.object,received:n.parsedType}),u;let T=this.discriminator,t=n.data[T],S=this.optionsMap.get(t);if(!S)return L(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=gn(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 NS({typeName:e.ZodDiscriminatedUnion,discriminator:o,options:n,optionsMap:t,...oo(T)})}}function My(o,n){let T=ln(o),t=ln(n);if(o===n)return{valid:!0,data:o};else if(T===r.object&&t===r.object){let S=Mo.objectKeys(n),f=Mo.objectKeys(o).filter((A)=>S.indexOf(A)!==-1),y={...o,...n};for(let A of f){let M=My(o[A],n[A]);if(!M.valid)return{valid:!1};y[A]=M.data}return{valid:!0,data:y}}else if(T===r.array&&t===r.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=My(y,A);if(!M.valid)return{valid:!1};S.push(M.data)}return{valid:!0,data:S}}else if(T===r.date&&t===r.date&&+o===+n)return{valid:!0,data:o};else return{valid:!1}}class pT extends no{_parse(o){let{status:n,ctx:T}=this._processInputParams(o),t=(S,f)=>{if(yy(S)||yy(f))return u;let y=My(S.value,f.value);if(!y.valid)return L(T,{code:m.invalid_intersection_types}),u;if(Ay(S)||Ay(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}))}}pT.create=(o,n,T)=>{return new pT({left:o,right:n,typeName:e.ZodIntersection,...oo(T)})};class bn extends no{_parse(o){let{status:n,ctx:T}=this._processInputParams(o);if(T.parsedType!==r.array)return L(T,{code:m.invalid_type,expected:r.array,received:T.parsedType}),u;if(T.data.length<this._def.items.length)return L(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)L(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 eo.mergeArray(n,f)});else return eo.mergeArray(n,S)}get items(){return this._def.items}rest(o){return new bn({...this._def,rest:o})}}bn.create=(o,n)=>{if(!Array.isArray(o))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new bn({items:o,typeName:e.ZodTuple,rest:null,...oo(n)})};class Ct extends no{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!==r.object)return L(T,{code:m.invalid_type,expected:r.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 eo.mergeObjectAsync(n,t);else return eo.mergeObjectSync(n,t)}get element(){return this._def.valueType}static create(o,n,T){if(n instanceof no)return new Ct({keyType:o,valueType:n,typeName:e.ZodRecord,...oo(T)});return new Ct({keyType:Dn.create(),valueType:o,typeName:e.ZodRecord,...oo(n)})}}class Lt extends no{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!==r.map)return L(T,{code:m.invalid_type,expected:r.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}}}}Lt.create=(o,n,T)=>{return new Lt({valueType:n,keyType:o,typeName:e.ZodMap,...oo(T)})};class OT extends no{_parse(o){let{status:n,ctx:T}=this._processInputParams(o);if(T.parsedType!==r.set)return L(T,{code:m.invalid_type,expected:r.set,received:T.parsedType}),u;let t=this._def;if(t.minSize!==null){if(T.data.size<t.minSize.value)L(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)L(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 OT({...this._def,minSize:{value:o,message:i.toString(n)}})}max(o,n){return new OT({...this._def,maxSize:{value:o,message:i.toString(n)}})}size(o,n){return this.min(o,n).max(o,n)}nonempty(o){return this.min(1,o)}}OT.create=(o,n)=>{return new OT({valueType:o,minSize:null,maxSize:null,typeName:e.ZodSet,...oo(n)})};class bT extends no{constructor(){super(...arguments);this.validate=this.implement}_parse(o){let{ctx:n}=this._processInputParams(o);if(n.parsedType!==r.function)return L(n,{code:m.invalid_type,expected:r.function,received:n.parsedType}),u;function T(y,A){return jS({data:y,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,IS(),hT].filter((M)=>!!M),issueData:{code:m.invalid_arguments,argumentsError:A}})}function t(y,A){return jS({data:y,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,IS(),hT].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 _T){let y=this;return nn(async function(...A){let M=new kn([]),F=await y._def.args.parseAsync(A,S).catch((O)=>{throw M.addIssue(T(A,O)),M}),$=await Reflect.apply(f,this,F);return await y._def.returns._def.type.parseAsync($,S).catch((O)=>{throw M.addIssue(t($,O)),M})})}else{let y=this;return nn(function(...A){let M=y._def.args.safeParse(A,S);if(!M.success)throw new kn([T(A,M.error)]);let F=Reflect.apply(f,this,M.data),$=y._def.returns.safeParse(F,S);if(!$.success)throw new kn([t(F,$.error)]);return $.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...o){return new bT({...this._def,args:bn.create(o).rest(fT.create())})}returns(o){return new bT({...this._def,returns:o})}implement(o){return this.parse(o)}strictImplement(o){return this.parse(o)}static create(o,n,T){return new bT({args:o?o:bn.create([]).rest(fT.create()),returns:n||fT.create(),typeName:e.ZodFunction,...oo(T)})}}class qT extends no{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})}}qT.create=(o,n)=>{return new qT({getter:o,typeName:e.ZodLazy,...oo(n)})};class ZT extends no{_parse(o){if(o.data!==this._def.value){let n=this._getOrReturnCtx(o);return L(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}}ZT.create=(o,n)=>{return new ZT({value:o,typeName:e.ZodLiteral,...oo(n)})};function Z$(o,n){return new MT({values:o,typeName:e.ZodEnum,...oo(n)})}class MT extends no{constructor(){super(...arguments);Qt.set(this,void 0)}_parse(o){if(typeof o.data!=="string"){let n=this._getOrReturnCtx(o),T=this._def.values;return L(n,{expected:Mo.joinValues(T),received:n.parsedType,code:m.invalid_type}),u}if(!rS(this,Qt,"f"))v$(this,Qt,new Set(this._def.values),"f");if(!rS(this,Qt,"f").has(o.data)){let n=this._getOrReturnCtx(o),T=this._def.values;return L(n,{received:n.data,code:m.invalid_enum_value,options:T}),u}return nn(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 MT.create(o,{...this._def,...n})}exclude(o,n=this._def){return MT.create(this.options.filter((T)=>!o.includes(T)),{...this._def,...n})}}Qt=new WeakMap;MT.create=Z$;class PT extends no{constructor(){super(...arguments);Dt.set(this,void 0)}_parse(o){let n=Mo.getValidEnumValues(this._def.values),T=this._getOrReturnCtx(o);if(T.parsedType!==r.string&&T.parsedType!==r.number){let t=Mo.objectValues(n);return L(T,{expected:Mo.joinValues(t),received:T.parsedType,code:m.invalid_type}),u}if(!rS(this,Dt,"f"))v$(this,Dt,new Set(Mo.getValidEnumValues(this._def.values)),"f");if(!rS(this,Dt,"f").has(o.data)){let t=Mo.objectValues(n);return L(T,{received:T.data,code:m.invalid_enum_value,options:t}),u}return nn(o.data)}get enum(){return this._def.values}}Dt=new WeakMap;PT.create=(o,n)=>{return new PT({values:o,typeName:e.ZodNativeEnum,...oo(n)})};class _T extends no{unwrap(){return this._def.type}_parse(o){let{ctx:n}=this._processInputParams(o);if(n.parsedType!==r.promise&&n.common.async===!1)return L(n,{code:m.invalid_type,expected:r.promise,received:n.parsedType}),u;let T=n.parsedType===r.promise?n.data:Promise.resolve(n.data);return nn(T.then((t)=>{return this._def.type.parseAsync(t,{path:n.path,errorMap:n.common.contextualErrorMap})}))}}_T.create=(o,n)=>{return new _T({type:o,typeName:e.ZodPromise,...oo(n)})};class Kn extends no{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===e.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(L(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 NT(A.value);if(n.value==="dirty")return NT(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 NT(y.value);if(n.value==="dirty")return NT(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(!kT(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(!kT(f))return f;return Promise.resolve(t.transform(f.value,S)).then((y)=>({status:n.value,value:y}))});Mo.assertNever(t)}}Kn.create=(o,n,T)=>{return new Kn({schema:o,typeName:e.ZodEffects,effect:n,...oo(T)})};Kn.createWithPreprocess=(o,n,T)=>{return new Kn({schema:n,effect:{type:"preprocess",transform:o},typeName:e.ZodEffects,...oo(T)})};class Vn extends no{_parse(o){if(this._getType(o)===r.undefined)return nn(void 0);return this._def.innerType._parse(o)}unwrap(){return this._def.innerType}}Vn.create=(o,n)=>{return new Vn({innerType:o,typeName:e.ZodOptional,...oo(n)})};class en extends no{_parse(o){if(this._getType(o)===r.null)return nn(null);return this._def.innerType._parse(o)}unwrap(){return this._def.innerType}}en.create=(o,n)=>{return new en({innerType:o,typeName:e.ZodNullable,...oo(n)})};class gT extends no{_parse(o){let{ctx:n}=this._processInputParams(o),T=n.data;if(n.parsedType===r.undefined)T=this._def.defaultValue();return this._def.innerType._parse({data:T,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}gT.create=(o,n)=>{return new gT({innerType:o,typeName:e.ZodDefault,defaultValue:typeof n.default==="function"?n.default:()=>n.default,...oo(n)})};class lT extends no{_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(Ut(t))return t.then((S)=>{return{status:"valid",value:S.status==="valid"?S.value:this._def.catchValue({get error(){return new kn(T.common.issues)},input:T.data})}});else return{status:"valid",value:t.status==="valid"?t.value:this._def.catchValue({get error(){return new kn(T.common.issues)},input:T.data})}}removeCatch(){return this._def.innerType}}lT.create=(o,n)=>{return new lT({innerType:o,typeName:e.ZodCatch,catchValue:typeof n.catch==="function"?n.catch:()=>n.catch,...oo(n)})};class It extends no{_parse(o){if(this._getType(o)!==r.nan){let T=this._getOrReturnCtx(o);return L(T,{code:m.invalid_type,expected:r.nan,received:T.parsedType}),u}return{status:"valid",value:o.data}}}It.create=(o)=>{return new It({typeName:e.ZodNaN,...oo(o)})};var HR=Symbol("zod_brand");class bS extends no{_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 jt extends no{_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(),NT(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 jt({in:o,out:n,typeName:e.ZodPipeline})}}class eT extends no{_parse(o){let n=this._def.innerType._parse(o),T=(t)=>{if(kT(t))t.value=Object.freeze(t.value);return t};return Ut(n)?n.then((t)=>T(t)):T(n)}unwrap(){return this._def.innerType}}eT.create=(o,n)=>{return new eT({innerType:o,typeName:e.ZodReadonly,...oo(n)})};function P$(o,n={},T){if(o)return WT.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 WT.create()}var mR={object:Do.lazycreate},e;(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"})(e||(e={}));var QR=(o,n={message:`Input not instance of ${o.name}`})=>P$((T)=>T instanceof o,n),g$=Dn.create,l$=yT.create,DR=It.create,UR=AT.create,e$=xT.create,VR=RT.create,BR=Vt.create,CR=cT.create,LR=vT.create,IR=WT.create,jR=fT.create,rR=Nn.create,NR=Bt.create,bR=Un.create,rt=Do.create,hR=Do.strictCreate,xR=iT.create,cR=NS.create,vR=pT.create,iR=bn.create,pR=Ct.create,qR=Lt.create,ZR=OT.create,PR=bT.create,gR=qT.create,lR=ZT.create,eR=MT.create,dR=PT.create,uR=_T.create,x$=Kn.create,aR=Vn.create,sR=en.create,o0=Kn.createWithPreprocess,n0=jt.create,T0=()=>g$().optional(),t0=()=>l$().optional(),S0=()=>e$().optional(),f0={string:(o)=>Dn.create({...o,coerce:!0}),number:(o)=>yT.create({...o,coerce:!0}),boolean:(o)=>xT.create({...o,coerce:!0}),bigint:(o)=>AT.create({...o,coerce:!0}),date:(o)=>RT.create({...o,coerce:!0})},y0=u,Go=Object.freeze({__proto__:null,defaultErrorMap:hT,setErrorMap:nR,getErrorMap:IS,makeIssue:jS,EMPTY_PATH:TR,addIssueToContext:L,ParseStatus:eo,INVALID:u,DIRTY:NT,OK:nn,isAborted:yy,isDirty:Ay,isValid:kT,isAsync:Ut,get util(){return Mo},get objectUtil(){return fy},ZodParsedType:r,getParsedType:ln,ZodType:no,datetimeRegex:q$,ZodString:Dn,ZodNumber:yT,ZodBigInt:AT,ZodBoolean:xT,ZodDate:RT,ZodSymbol:Vt,ZodUndefined:cT,ZodNull:vT,ZodAny:WT,ZodUnknown:fT,ZodNever:Nn,ZodVoid:Bt,ZodArray:Un,ZodObject:Do,ZodUnion:iT,ZodDiscriminatedUnion:NS,ZodIntersection:pT,ZodTuple:bn,ZodRecord:Ct,ZodMap:Lt,ZodSet:OT,ZodFunction:bT,ZodLazy:qT,ZodLiteral:ZT,ZodEnum:MT,ZodNativeEnum:PT,ZodPromise:_T,ZodEffects:Kn,ZodTransformer:Kn,ZodOptional:Vn,ZodNullable:en,ZodDefault:gT,ZodCatch:lT,ZodNaN:It,BRAND:HR,ZodBranded:bS,ZodPipeline:jt,ZodReadonly:eT,custom:P$,Schema:no,ZodSchema:no,late:mR,get ZodFirstPartyTypeKind(){return e},coerce:f0,any:IR,array:bR,bigint:UR,boolean:e$,date:VR,discriminatedUnion:cR,effect:x$,enum:eR,function:PR,instanceof:QR,intersection:vR,lazy:gR,literal:lR,map:qR,nan:DR,nativeEnum:dR,never:rR,null:LR,nullable:sR,number:l$,object:rt,oboolean:S0,onumber:t0,optional:aR,ostring:T0,pipeline:n0,preprocess:o0,promise:uR,record:pR,set:ZR,strictObject:hR,string:g$,symbol:BR,transformer:x$,tuple:iR,undefined:CR,union:xR,unknown:jR,void:NR,NEVER:y0,ZodIssueCode:m,quotelessJson:oR,ZodError:kn});function d$(o){let n=o.runtimeEnvStrict??o.runtimeEnv??process.env;if(o.emptyStringAsUndefined??!1){for(let[K,Q]of Object.entries(n))if(Q==="")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=rt(S),M=rt(f),F=rt(y),$=o.isServer??(typeof window==="undefined"||("Deno"in window)),W=A.merge(F),O=M.merge(F).merge(A),G=$?O.safeParse(n):W.safeParse(n),D=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(G.success===!1)return D(G.error);let Y=(K)=>{if(!o.clientPrefix)return!0;return!K.startsWith(o.clientPrefix)&&!(K in F.shape)},B=(K)=>{return $||!Y(K)},p=(K)=>{return K==="__esModule"||K==="$$typeof"},c=(o.extends??[]).reduce((K,Q)=>{return Object.assign(K,Q)},{}),a=Object.assign(G.data,c);return new Proxy(a,{get(K,Q){if(typeof Q!=="string")return;if(p(Q))return;if(!B(Q))return z(Q);return Reflect.get(K,Q)}})}var A0="__vite_start_time"in globalThis,M0=typeof window!=="undefined",t9="vitest"in globalThis,Cn=d$({isServer:!A0&&!M0,server:{CI:Go.string().transform((o)=>!0).optional(),POSTGRES_USER:Go.string(),POSTGRES_PASSWORD:Go.string(),POSTGRES_DATABASE:Go.string(),POSTGRES_HOST:Go.string(),POSTGRES_PORT:Go.string().transform((o)=>Number.parseInt(o,10)),BACKEND_PORT:Go.string().transform((o)=>Number.parseInt(o,10)),RUN_WORKERS_FROM_SOURCE:Go.union([Go.literal("true"),Go.literal("false")]).optional().transform((o)=>o==="true"),FRONTEND_PORT:Go.string().transform((o)=>Number.parseInt(o,10)),FRONTEND_ORIGINS:Go.string().transform((o)=>JSON.parse(o)).pipe(Go.array(Go.string())),OPENAI_API_KEY:Go.string().optional()},clientPrefix:"VITE_",client:{VITE_BACKEND_ORIGIN:Go.string(),VITE_USE_SELF_SIGNED_CERTIFICATE:Go.union([Go.literal("true"),Go.literal("false")]).optional().transform((o)=>o==="true")},runtimeEnv:import.meta.env,emptyStringAsUndefined:!0});var a$=Fy(import.meta.dirname,"../dev"),s$=Cn.VITE_USE_SELF_SIGNED_CERTIFICATE?{cert:u$(Fy(a$,"./cert.pem"),"utf-8"),key:u$(Fy(a$,"./key.pem"),"utf-8")}:void 0;import nW from"path";import L0 from"os";import I0 from"fs";var hS=new Map,$y=new Map,Jy=Symbol("OriginError"),dT={};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[Jy]=this.handler.debug?new Error:this.tagged&&F0(this.strings)}get origin(){return(this.handler.debug?this[Jy].stack:this.tagged&&$y.has(this.strings)?$y.get(this.strings):$y.set(this.strings,this[Jy].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(dT),{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 F0(o){if(hS.has(o))return hS.get(o);let n=Error.stackTraceLimit;return Error.stackTraceLimit=4,hS.set(o,new Error),Error.stackTraceLimit=n,hS.get(o)}class uT extends Error{constructor(o){super(o.message);this.name=this.constructor.name,Object.assign(this,o)}}var Lo={connection:oJ,postgres:nJ,generic:TJ,notSupported:tJ};function oJ(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,oJ),f}function nJ(o){let n=new uT(o);return Error.captureStackTrace(n,nJ),n}function TJ(o,n){let T=Object.assign(new Error(o+": "+n),{code:o});return Error.captureStackTrace(T,TJ),T}function tJ(o){let n=Object.assign(new Error(o+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:o});return Error.captureStackTrace(n,tJ),n}var $0={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 vS{then(){ky()}catch(){ky()}finally(){ky()}}class xt extends vS{constructor(o){super();this.value=qS(o)}}class hn extends vS{constructor(o,n,T){super();this.value=o,this.type=n,this.array=T}}class iS extends vS{constructor(o,n){super();this.first=o,this.rest=n}build(o,n,T,t){let S=J0.map(([f,y])=>({fn:y,i:o.search(f)})).sort((f,y)=>f.i-y.i).pop();return S.i===-1?wy(this.first,t):S.fn(this.first,this.rest,n,T,t)}}function pS(o,n,T,t){let S=o instanceof hn?o.value:o;if(S===void 0){if(o instanceof hn?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 hn?(n.push(o.value),o.array?o.array[o.type||cS(o.value)]||o.type||AJ(o.value):o.type):(n.push(o),cS(o)))}var fJ=FJ($0);function Oy(o,n,T,t,S,f){for(let y=1;y<o.strings.length;y++)n+=_y(n,T,t,S,f)+o.strings[y],T=o.args[y];return n}function _y(o,n,T,t,S){return n instanceof iS?n.build(o,T,t,S):n instanceof Xn?Wy(n,T,t,S):n instanceof xt?n.value:n&&n[0]instanceof Xn?n.reduce((f,y)=>f+" "+Wy(y,T,t,S),""):pS(n,T,t,S)}function Wy(o,n,T,t){return o.fragment=!0,Oy(o,o.strings[0],o.args[0],n,T,t)}function yJ(o,n,T,t,S){return o.map((f)=>"("+t.map((y)=>_y("values",f[y],n,T,S)).join(",")+")").join(",")}function SJ(o,n,T,t,S){let f=Array.isArray(o[0]),y=n.length?n.flat():Object.keys(f?o[0]:o);return yJ(f?o:[o],T,t,y,S)}function xS(o,n,T,t,S){if(typeof o==="string"&&(o=[o].concat(n)),Array.isArray(o))return wy(o,S);let f;return(n.length?n.flat():Object.keys(o)).map((A)=>{return f=o[A],(f instanceof Xn?Wy(f,T,t,S):f instanceof xt?f.value:pS(f,T,t,S))+" as "+qS(S.transform.column.to?S.transform.column.to(A):A)}).join(",")}var J0=Object.entries({values:SJ,in:(...o)=>{let n=SJ(...o);return n==="()"?"(null)":n},select:xS,as:xS,returning:xS,"\\(":xS,update(o,n,T,t,S){return(n.length?n.flat():Object.keys(o)).map((f)=>qS(S.transform.column.to?S.transform.column.to(f):f)+"="+_y("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"("+wy(f,S)+")values"+yJ(Array.isArray(o)?o:[o],T,t,f,S)}}).map(([o,n])=>[new RegExp("((?:^|[\\s(])"+o+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),n]);function ky(){throw Lo.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}var{serializers:k0,parsers:R0}=fJ;function AJ(o){if(Array.isArray(o))return AJ(o[0]);return typeof o==="string"?1009:0}var MJ=function(o){let n=FJ(o||{});return{serializers:Object.assign({},k0,n.serializers),parsers:Object.assign({},R0,n.parsers)}};function FJ(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 wy(o,{transform:{column:n}}){return o.map((T)=>qS(n.to?n.to(T):T)).join(",")}var qS=function o(n){return'"'+n.replace(/"/g,'""').replace(/\./g,'"."')+'"'},cS=function o(n){return n instanceof hn?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},W0=/\\/g,O0=/"/g;function _0(o){return o.replace(W0,"\\\\").replace(O0,"\\\"")}var $J=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":'"'+_0(T?T(A.type?A.value:A):""+A)+'"'}).join(y)+"}"},Ry={i:0,char:null,str:"",quoted:!1,last:0},JJ=function o(n,T,t){return Ry.i=Ry.last=0,kJ(Ry,n,T,t)};function kJ(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(kJ(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 wT=(o)=>{let n=o[0];for(let T=1;T<o.length;T++)n+=o[T]==="_"?o[++T].toUpperCase():o[T];return n},KT=(o)=>{let n=o[0].toUpperCase();for(let T=1;T<o.length;T++)n+=o[T]==="_"?o[++T].toUpperCase():o[T];return n},XT=(o)=>o.replace(/_/g,"-"),Nt=(o)=>o.replace(/([A-Z])/g,"_$1").toLowerCase(),bt=(o)=>(o.slice(0,1)+o.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),ht=(o)=>o.replace(/-/g,"_");function Ky(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}}wT.column={from:wT};wT.value={from:Ky(wT)};Nt.column={to:Nt};var Xy={...wT};Xy.column.to=Nt;KT.column={from:KT};KT.value={from:Ky(KT)};bt.column={to:bt};var Ey={...KT};Ey.column.to=bt;XT.column={from:XT};XT.value={from:Ky(XT)};ht.column={to:ht};var Yy={...XT};Yy.column.to=ht;import RJ from"net";import E0 from"tls";import ct from"crypto";import Gy from"stream";import{performance as WJ}from"perf_hooks";class ET 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 Rn=w0;function w0(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 uo=Buffer.allocUnsafe(256),K0="BCcDdEFfHPpQSX".split("").reduce((o,n)=>{let T=n.charCodeAt(0);return o[n]=()=>{return uo[0]=T,ko.i=5,ko},o},{}),ko=Object.assign(X0,K0,{N:String.fromCharCode(0),i:0,inc(o){return ko.i+=o,ko},str(o){let n=Buffer.byteLength(o);return ZS(n),ko.i+=uo.write(o,ko.i,n,"utf8"),ko},i16(o){return ZS(2),uo.writeUInt16BE(o,ko.i),ko.i+=2,ko},i32(o,n){if(n||n===0)return uo.writeUInt32BE(o,n),ko;return ZS(4),uo.writeUInt32BE(o,ko.i),ko.i+=4,ko},z(o){return ZS(o),uo.fill(0,ko.i,ko.i+o),ko.i+=o,ko},raw(o){return uo=Buffer.concat([uo.subarray(0,ko.i),o]),ko.i=uo.length,ko},end(o=1){uo.writeUInt32BE(ko.i-o,o);let n=uo.subarray(0,ko.i);return ko.i=0,uo=Buffer.allocUnsafe(256),n}}),P=ko;function ZS(o){if(uo.length-ko.i<o){let n=uo,T=n.length;uo=Buffer.allocUnsafe(T+(T>>1)+o),n.copy(uo)}}function X0(){return ko.i=0,ko}var my=wJ,Y0=1,FT=P().S().end(),OJ=P().H().end(),G0=P().i32(8).i32(80877103).end(8),z0=Buffer.concat([P().E().str(P.N).i32(0).end(),FT]),H0=P().D().str("S").str(P.N).end(),aT=()=>{},m0=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),Q0={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 wJ(o,n={},{onopen:T=aT,onend:t=aT,onclose:S=aT}={}){let{ssl:f,max:y,user:A,host:M,port:F,database:$,parsers:W,transform:O,onnotice:G,onnotify:D,onparameter:z,max_pipeline:Y,keep_alive:B,backoff:p,target_session_attrs:c}=o,a=Rn(),E=Y0++,K={pid:null,secret:null},Q=Hy(Sf,o.idle_timeout),x=Hy(Sf,o.max_lifetime),h=Hy(xJ,o.connect_timeout),w=null,v,N=new ET,q=Buffer.alloc(0),Jo=o.fetch_types,Oo={},Sn={},xn=Math.random().toString(36).slice(2),H=1,Z=0,Fo=0,zo=0,Io=0,To=0,_o=0,Co=0,mo=null,Ko=null,po=!1,wo=null,En=null,qo=null,dn=null,jo=null,Xo=null,Yn=null,Ln=null,C=null,Tt=null,Zo={queue:n.closed,idleTimer:Q,connect(J){qo=J||!0,ay()},terminate:St,execute:tt,cancel:rJ,end:Sf,count:0,id:E};return n.closed&&n.closed.push(Zo),Zo;async function jJ(){let J;try{J=o.socket?await Promise.resolve(o.socket(o)):new RJ.Socket}catch(_){HT(_);return}return J.on("error",HT),J.on("close",sy),J.on("drain",dy),J}async function rJ({pid:J,secret:_},g,$o){try{v=P().i32(16).i32(80877102).i32(J).i32(_).end(16),await uy(),w.once("error",$o),w.once("close",g)}catch(Uo){$o(Uo)}}function tt(J){if(po)return lt(J,Lo.connection("CONNECTION_DESTROYED",o));if(J.cancelled)return;try{return J.state=K,C?a.push(J):(C=J,C.active=!0),hJ(J),xo(NJ(J))&&!J.describeFirst&&!J.cursorFn&&a.length<Y&&(!J.options.onexecute||J.options.onexecute(Zo))}catch(_){return a.length===0&&xo(FT),In(_),!0}}function NJ(J){if(J.parameters.length>=65534)throw Lo.generic("MAX_PARAMETERS_EXCEEDED","Max number of parameters (65534) exceeded");return J.options.simple?P().Q().str(J.statement.string+P.N).end():J.describeFirst?Buffer.concat([gy(J),OJ]):J.prepare?J.prepared?gt(J):Buffer.concat([gy(J),gt(J)]):bJ(J)}function gy(J){return Buffer.concat([nA(J.statement.string,J.parameters,J.statement.types,J.statement.name),zk("S",J.statement.name)])}function gt(J){return Buffer.concat([Gk(J.parameters,J.statement.types,J.statement.name,J.cursorName),J.cursorFn?TA("",J.cursorRows):z0])}function bJ(J){return Buffer.concat([nA(J.statement.string,J.parameters,J.statement.types),H0,gt(J)])}function hJ(J){let _=[],g=[],$o=Oy(J,J.strings[0],J.args[0],_,g,o);!J.tagged&&J.args.forEach((Uo)=>pS(Uo,_,g,o)),J.prepare=o.prepare&&("prepare"in J.options?J.options.prepare:!0),J.string=$o,J.signature=J.prepare&&g+$o,J.onlyDescribe&&delete Sn[J.signature],J.parameters=J.parameters||_,J.prepared=J.prepare&&J.signature in Sn,J.describeFirst=J.onlyDescribe||_.length&&!J.prepared,J.statement=J.prepared?Sn[J.signature]:{string:$o,types:g,name:J.prepare?xn+H++:""},typeof o.debug==="function"&&o.debug(E,$o,_,g)}function xo(J,_){if(Xo=Xo?Buffer.concat([Xo,J]):Buffer.from(J),_||Xo.length>=1024)return ly(_);return Ko===null&&(Ko=setImmediate(ly)),!0}function ly(J){let _=w.write(Xo,J);return Ko!==null&&clearImmediate(Ko),Xo=Ko=null,_}function xJ(){In(Lo.connection("CONNECT_TIMEOUT",o,w)),w.destroy()}async function ey(){if(xo(G0),!await new Promise((_)=>w.once("data",(g)=>_(g[0]===83)))&&f==="prefer")return zT();w.removeAllListeners(),w=E0.connect({socket:w,servername:RJ.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",zT),w.on("error",HT),w.on("close",sy),w.on("drain",dy)}function dy(){!C&&T(Zo)}function tf(J){if(wo){if(wo.push(J),Fo-=J.length,Fo>=0)return}q=wo?Buffer.concat(wo,To-Fo):q.length===0?J:Buffer.concat([q,J],q.length+J.length);while(q.length>4){if(To=q.readUInt32BE(1),To>=q.length){Fo=To-q.length,wo=[q];break}try{cJ(q.subarray(0,To+1))}catch(_){C&&(C.cursorFn||C.describeFirst)&&xo(FT),In(_)}q=q.subarray(To+1),Fo=0,wo=null}}async function uy(){if(po=!1,Oo={},w||(w=await jJ()),!w)return;if(h.start(),o.socket)return f?ey():zT();if(w.on("connect",f?ey:zT),o.path)return w.connect(o.path);w.ssl=f,w.connect(F[zo],M[zo]),w.host=M[zo],w.port=F[zo],zo=(zo+1)%F.length}function ay(){setTimeout(uy,Z?Z+_o-WJ.now():0)}function zT(){try{Sn={},Jo=o.fetch_types,xn=Math.random().toString(36).slice(2),H=1,x.start(),w.on("data",tf),B&&w.setKeepAlive&&w.setKeepAlive(!0,1000*B);let J=mk();xo(J)}catch(J){HT(J)}}function HT(J){if(Zo.queue===n.connecting&&o.host[Io+1])return;In(J);while(a.length)lt(a.shift(),J)}function In(J){jo&&(jo.destroy(J),jo=null),C&&lt(C,J),qo&&(lt(qo,J),qo=null)}function lt(J,_){"query"in _||"parameters"in _||Object.defineProperties(_,{stack:{value:_.stack+J.origin.replace(/.*\n/,`
9
+ `);o.disposalTraces.add({key:T.key,trace:f})}}var AS=(o,n)=>U(n).atoms.has(o),bk=(o,n)=>U(n).selectors.has(o),hk=(o,n)=>U(n).readonlySelectors.has(o),jA=(o,n)=>AS(o,n)||bk(o,n)||hk(o,n);var MS=(o,n)=>{return U(n).selectorGraph.getRelationEntries({downstreamSelectorKey:o}).filter(([t,{source:S}])=>S!==o).map(([t,{source:S}])=>S).filter((t)=>jA(t,n))};var Gf=(o,n,T)=>{let t=[],S=MS(o,T);while(S.length>0){let f=S.shift();if(n.has(f))continue;if(n.add(f),!AS(f,T))S.push(...MS(f,T));else if(!t.includes(f))t.push(f)}return t},rA=(o,n)=>{let T=o.key,t=MS(T,n),S=new Set;return t.flatMap((f)=>AS(f,n)?f:Gf(f,S,n))};var NA=(o,n,T,t)=>{let S=U(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=Gf(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 FS=(o,n,T)=>({get:(...t)=>{let S=U(T),f;if(t.length===2){let[M,F]=t;switch(M.type){case"molecule_family":return fo(T,M,F);default:if(T.config.lifespan==="ephemeral")f=Ao(T,M,F);else{let $=Eo(T,M,F);if($)f=$;else throw new yn(M,F,T)}}}else[f]=t;if(f.type==="molecule")return fo(T,f);let y=d(f,T),A=sn(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}),NA(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 $=T.config.lifespan==="ephemeral"?Ao(T,M,F):Eo(T,M,F);if(!$)throw new yn(M,F,T);S=$}let y=U(T),A=d(S,y);ut(A,f,y)},find:(t,S)=>Ao(T,t,S),seek:(t,S)=>Eo(T,t,S),json:(t)=>Vo(T,t)});var At=(o,n,T)=>{let t=U(o),S=new s,f=new Set,{get:y,find:A,seek:M,json:F}=FS(n.key,f,t),$=()=>{let D=n.get({get:y,find:A,seek:M,json:F});return Wn(n.key,D,S,U(o)),f.clear(),D},W={...n,subject:S,install:(D)=>At(D,n,T),get:$,type:"readonly_selector",...T&&{family:T}};t.readonlySelectors.set(n.key,W);let O=$();o.logger.info("\u2728",W.type,W.key,"=",O);let G={key:n.key,type:"readonly_selector"};if(T)G.family=T;return G};var Wt=(o,n,T)=>{let t=U(o),S=new s,f=new Set,y=FS(n.key,f,t),{find:A,get:M,seek:F,json:$}=y,W={find:A,get:M,seek:F,json:$},O=(B=n.get,p=U(o))=>{let c=B(W);return Wn(n.key,c,S,p),f.clear(),c},D={...n,subject:S,install:(B)=>Wt(B,n,T),get:O,set:(B)=>{let p=U(o),c=O(n.get,p),a=dt(B)(c);if(o.logger.info("\uD83D\uDCDD","selector",n.key,"set (",c,"->",a,")"),Wn(n.key,a,S,p),VT(p,n.key),Bo(p))S.next({newValue:a,oldValue:c});n.set(y,a)},type:"selector",...T&&{family:T}};t.selectors.set(n.key,D);let z=O();o.logger.info("\u2728",D.type,D.key,"=",z);let Y={key:n.key,type:"selector"};if(T)Y.family=T;return Y};function Gn(o,n){if("set"in n){let S=Wt(o,n,void 0);return o.on.selectorCreation.next(S),S}let t=At(o,n,void 0);return o.on.selectorCreation.next(t),t}function IA(o,n){let T=U(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"),yo(T)&&T.transactionMeta.phase==="building")T.transactionMeta.update.updates.push({type:"state_disposal",token:o});else n.on.selectorDisposal.next(o)}}function Ft(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 ${zn(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),$={key:n.key,subKey:F},W=`${n.key}(${F})`,O=U(o),G=Wt(O,{key:W,get:n.get(M),set:n.set(M)},$);return f.next({type:"state_creation",token:G}),G},t,{internalRoles:T,subject:f,install:(M)=>Ft(M,n),default:(M)=>{return n.get(M)({get:(...$)=>fo(o,...$),find:($,W)=>Ao(o,$,W),seek:($,W)=>Eo(o,$,W),json:($)=>Vo(o,$)})}});return o.families.set(n.key,A),t}function bA(o,n,T=to.STORE){let t=Ft(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),$=T.molecules.get(F);if($){let O=Hn($,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 $=l(f),W=T.molecules.get($);if(W){let O=Hn(W,o,T);A(O,n.fromJson(M))}else{if(T.config.lifespan==="immortal")throw new Error(`No molecule found for key "${$}"`);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)Eo(T,t,ro(f.token.family.subKey))}),t}var ro=(o)=>JSON.parse(o),l=(o)=>JSON.stringify(o),M4=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];var hA=(o,n)=>{let T=U(n);if(T.operation.open)return T.operation.prev.get(o.key);return T.valueMap.get(o.key)};var mf=(o,n)=>{let T=U(n);return rA(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=hA(o,T),M=sn(o,T);n.logger.info("\u2728",o.type,o.key,"went",A,"->",M),o.subject.next({newValue:M,oldValue:A})})})};function lo(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=mf(f,t),M=(W)=>{if(A)A.length=0,A.push(...mf(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 zf=(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 Hf=(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 oT{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=fn(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}:${yo(T)?T.transactionMeta.update.key:"main"}:${o.key}`,S=fo(T,o);this.unsubscribeFromInnerValue=S.subscribe(t,(f)=>{Qo(T,n,f)}),this.unsubscribeFromState=lo(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}:${yo(T)?T.transactionMeta.update.key:"main"}:${o.key}`;lo(n,({newValue:S,oldValue:f})=>{let y=T.timelineTopics.getRelatedKey(n.key);if(y){if(T.timelines.get(y)?.timeTraveling){let F=zf({key:y,type:"timeline"},($)=>{F(),Qo(T,o,(W)=>{if($==="redo"&&S)W.do(S);else if($==="undo"&&f)W.undo(f);return W})},t,T);return}}let A=T.on.operationClose.subscribe(t,()=>{A();let M=fo(T,o),F=S===null?-1:M.getUpdateNumber(S),$=F-M.cacheUpdateNumber;if(S&&$===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=U(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 Ot(o,n,T){o.logger.info("\uD83D\uDD28","atom",n.key,`creating in store "${o.config.name}"`);let t=U(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."),go(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}"`),Ot(F,n,T)},subject:f};if(T)y.family=T;let A=n.default();t.atoms.set(y.key,y),$S(n.key,o),Wn(n.key,A,f,t);let M=go(y);if(n.effects){let F=0,$=[];for(let W of n.effects){let O=W({setSelf:(G)=>{Qo(o,M,G)},onSet:(G)=>lo(M,G,`effect[${F}]`,o)});if(O)$.push(O);++F}y.cleanup=()=>{for(let W of $)W()}}if(new oT(M,o),!T)SA(M,n,o);return M}class Qf{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=ro(t.token.family.subKey);Eo(n,this.latestUpdateAtoms,S),new oT(t.token,n)}}),this.latestUpdateAtoms.subject.subscribe(`store=${n.config.name}::tracker-atom-family`,(t)=>{if(t.token.family){let S=ro(t.token.family.subKey),f=Eo(n,this.mutableAtoms,S);if(f)new oT(f,n)}})}}function yt(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 ${zn(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),$={key:n.key,subKey:F},W=`${n.key}(${F})`,O=U(o),G={key:W,default:()=>n.default(M),toJson:n.toJson,fromJson:n.fromJson,mutable:!0};if(n.effects)G.effects=n.effects(M);let D=Ot(O,G,$);return f.next({type:"state_creation",token:D}),D},t,{subject:f,install:(M)=>yt(M,n),toJson:n.toJson,fromJson:n.fromJson,internalRoles:T});return o.families.set(n.key,A),bA(A,n,o),new Qf(A,o),t}var Of=(o,n)=>{let T=U(n),t=`${o.key}:JSON`;return T.families.get(t)};var Vo=(o,n)=>{if(n.family){let t=U(o),f={key:`${n.family.key}:JSON`,type:"selector_family"},y=d(f,t),A=JSON.parse(n.family.subKey);return Ao(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 wA(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 oT(o,n),y}return S}function Wn(o,n,T,t){let S=t.valueMap.get(o);if(S instanceof ft)S.use(n);if(n instanceof Promise){let f=new ft(n);return t.valueMap.set(o,f),f.then((y)=>{Wn(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 $A=(o,n)=>{let T=n.valueMap.get(o.key);if(o.type==="mutable_atom"&&yo(n)){let{parent:t}=n;T=kt(o,t,n)}return T},OA=(o,n)=>{let T=n.valueMap.get(o);if(T instanceof ft){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 XA=(o,n)=>{return U(n).atomsThatAreDefault.has(o)},$S=(o,n)=>{let T=U(n);T.atomsThatAreDefault=new Set(T.atomsThatAreDefault).add(o)},EA=(o,n)=>{let T=U(n);T.atomsThatAreDefault=new Set(U(n).atomsThatAreDefault),T.atomsThatAreDefault.delete(o)};function fn(o,n,T){o.logger.info("\uD83D\uDD28","atom",n.key,`creating in store "${o.config.name}"`);let t=U(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."),go(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}"`),fn(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),$S(n.key,o),Wn(n.key,A,f,t);let M=go(y);if(n.effects){let F=0,$=[];for(let W of n.effects){let O=W({setSelf:(G)=>{Qo(o,M,G)},onSet:(G)=>lo(M,G,`effect[${F}]`,o)});if(O)$.push(O);++F}y.cleanup=()=>{for(let W of $)W()}}return M}function AA(o,n){if("mutable"in n){let S=Ot(o,n,void 0);return o.on.atomCreation.next(S),S}let t=fn(o,n,void 0);return o.on.atomCreation.next(t),t}function Yf(o,n){let T=U(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);Yf(M,n),n.trackers.delete(t)}if(n.logger.info("\uD83D\uDD25","atom",t,"deleted"),yo(T)&&T.transactionMeta.phase==="building")T.transactionMeta.update.updates.push({type:"state_disposal",token:o});else n.on.atomDisposal.next(o)}}var Df=(o)=>{let n=fn(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=go(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 Gn(o,{key:"\uD83D\uDD0D Atom Token Index",get:({get:T})=>T(n)})};var Uf=(o)=>{let n=fn(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=go(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 Gn(o,{key:"\uD83D\uDD0D Selector Token Index",get:({get:T})=>T(n)})};class JS{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 Vf=new JS({number:(o)=>typeof o==="number",string:(o)=>typeof o==="string",boolean:(o)=>typeof o==="boolean",null:(o)=>o===null});function Bf(o){if(!o)return!1;return Object.getPrototypeOf(o)===Object.prototype}var Cf=new JS({object:Bf,array:(o)=>Array.isArray(o)}),xk=new JS({...Vf.supported,...Cf.supported}),BT=(o)=>{if(o===void 0)return"undefined";let n=xk.refine(o);if(n)return n.type;return Object.getPrototypeOf(o).constructor.name};class xA{store;auditorCreatedAt=performance.now();statesCreatedAt=new Map;atomIndex;selectorIndex;disposed=!1;unsubscribeFromAtomCreation;unsubscribeFromAtomDisposal;unsubscribeFromSelectorCreation;unsubscribeFromSelectorDisposal;constructor(o=to.STORE){this.store=o;this.atomIndex=Df(this.store),this.selectorIndex=Uf(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=xA.DEFAULT_LIST_RESOURCES_PARAM){if(this.disposed)throw new Error("This Auditor has been disposed");let n=Ff(this.atomIndex),T=Ff(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 Lf=(o,n)=>{let T=(t,S)=>{let y=((M,F)=>{let $=n(M,F);if($)return $;return null})(t,S);if(y?.jobComplete??y?.pathComplete)return y;let A=Array.isArray(S)?S.map((M,F)=>[F,M]):Bf(S)?Object.entries(S):[];for(let[M,F]of A){let $=T([...t,M],F);if($?.jobComplete)return $}return{}};T([],o)};function ck(o,n){return{summary:`${o<n?"+":"-"}${Math.abs(o-n)} (${o} \u2192 ${n})`}}function vk(o,n){return{summary:`${o.length<n.length?"+":"-"}${Math.abs(o.length-n.length)} ("${o}" \u2192 "${n}")`}}function ik(o,n){return{summary:`${o} \u2192 ${n}`}}function cA(o,n,T){let t="",S=[],f=[],y=[];return Lf(o,(A,M)=>{let F;for(F of A){let $=n[F];if($===void 0)f.push([F,JSON.stringify(M)]);else{let W=T(M,$);if(W.summary!=="No Change")y.push([F,W])}}}),Lf(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 pk(o,n,T){return cA(o,n,T)}class vA{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=BT(o),f=BT(n);if(S===f)return{summary:`${S} \u2192 ${f}`};return{summary:`Type change: ${S} \u2192 ${f}`}}}var X8=new vA(Vf,Cf,{number:ck,string:vk,boolean:ik,null:()=>({summary:"No Change"}),object:cA,array:pk});class iA 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 kS{key;type="continuity";globals=[];actions=[];perspectives=[];constructor(o){this.key=o}static existing=new iA;static create(o,n){let T=new kS(o),{type:t,globals:S,actions:f,perspectives:y}=n(T),A={type:t,key:o,globals:S,actions:f,perspectives:y};return kS.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 U8(o){let{key:n,config:T}=o,t=kS.create(n,T),{actions:S}=t;for(let f of S)VA(n,f.key,to.STORE);return QA(n,-1,to.STORE),t}var I8=UT({key:"usersInRoomIndex",mutable:!0,default:()=>new No,toJson:(o)=>o.toJSON(),fromJson:(o)=>No.fromJSON(o)}),If=UT({key:"roomIndex",default:()=>new No,mutable:!0,toJson:(o)=>o.toJSON(),fromJson:(o)=>No.fromJSON(o)}),qk={enteredAtEpoch:0},_t=oS({key:"usersInRooms",between:["room","user"],cardinality:"1:n",isAType:(o)=>typeof o==="string",isBType:(o)=>typeof o==="string"},qk),j8=et({key:"usersInMyRoomView",get:(o)=>({find:n})=>{let T=zA(_t);return[n(T,o)]}});import{spawn as Zk}from"child_process";class CT{emit;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 jf extends CT{incompleteData="";unprocessedEvents=[];incompleteLog="";unprocessedLogs=[];id="#####";process;key;logger;handleLog(o){if(Array.isArray(o)){let[n,...T]=o;switch(n){case"i":this.logger.info(...T);break;case"w":this.logger.warn(...T);break;case"e":this.logger.error(...T);break}}}constructor(o,n,T){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});if(this.process=o,this.key=n,this.logger=T??{info:(...t)=>{console.info(this.id,this.key,...t)},warn:(...t)=>{console.warn(this.id,this.key,...t)},error:(...t)=>{console.error(this.id,this.key,...t)}},this.process.stdout.on("data",(t)=>{let S=t.toString();if(S==="ALIVE")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=ro(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=ro(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=ro(this.incompleteLog);this.handleLog(y);while(this.unprocessedLogs.length>0)if(this.incompleteLog=this.unprocessedLogs.shift()??"",this.incompleteLog)y=ro(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 pA extends CT{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 rf extends CT{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=ro(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=ro(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 pA(`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("ALIVE")}relay(o){this.logger.info("\uD83D\uDD17","running relay method"),this.relayServices.push(o)}}var Nf=$T({key:"roomArguments",default:["echo",["Hello World!"]]}),qA=et({key:"room",get:(o)=>async({get:n,find:T})=>{let t=T(Nf,o),S=n(t),[f,y]=S,A=await new Promise((M)=>{let F=Zk(f,y,{env:process.env}),$=(W)=>{if(W.toString()==="ALIVE")F.stdout.off("data",$),M(F)};F.stdout.on("data",$)});return new jf(A,o)}});var ME=Jt({key:"createRoom",do:({get:o,set:n,find:T},t,S,f)=>{let y=f?[S,f]:[S],A=T(Nf,t);n(A,y),n(If,($)=>$.add(t));let M=T(qA,t);return o(M)}}),FE=Jt({key:"joinRoom",do:(o,n,T,t)=>{let S={enteredAtEpoch:t};return TS(_t,(f)=>{f.set({room:n,user:T},S)},o.env().store),S}}),$E=Jt({key:"leaveRoom",do:(o,n,T)=>{TS(_t,(t)=>{t.delete({room:n,user:T})},o.env().store)}}),JE=Jt({key:"destroyRoom",do:(o,n)=>{TS(_t,(T)=>{T.delete({room:n})},o.env().store),o.set(If,(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 WE=$T({key:"redactor",default:{occlude:(o)=>o}}),LT=$T({key:"unacknowledgedUpdates",default:()=>[]});var ZA=$T({key:"sockets",default:null}),XE=UT({key:"socketsIndex",mutable:!0,default:()=>new No,toJson:(o)=>o.toJSON(),fromJson:(o)=>No.fromJSON(o)}),EE=UT({key:"usersIndex",mutable:!0,default:()=>new No,toJson:(o)=>o.toJSON(),fromJson:(o)=>No.fromJSON(o)}),hf=oS({key:"usersOfSockets",between:["user","socket"],cardinality:"1:1",isAType:(o)=>o.startsWith("user::"),isBType:(o)=>o.startsWith("socket::")});function PA(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"?Vo(o,M):M,$=fo(o,F);y.push(F,$)}for(let M of n.perspectives){let{viewAtoms:F,resourceAtoms:$}=M,W=Ao(o,F,T),O=fo(o,W);o.logger.info("\uD83D\uDC41","atom",$.key,`${T} can see`,{viewAtoms:F,resourceAtoms:$,userView:O});for(let G of O){let D=G.type==="mutable_atom"?Vo(o,G):G,z=fo(o,D);y.push(D,z)}}let A=Bo(o)?o.transactionMeta.epoch.get(S)??null:null;t?.emit(`continuity-init:${S}`,A,y)}}function gA(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`,$=`${M}:end`;performance.mark(F);try{an({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($);let W=performance.measure(M,F,$);o?.logger.info("\uD83D\uDE80","transaction",y,A,T,W.duration)}}function lA(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,LT,T,(M)=>{return M.shift(),o.logger.info("\uD83D\uDC4D","continuity",S,`${T} unacknowledged update queue now has`,M.length,"items"),M})}}function eA(o,n,T,t){let S=n.key,f=[];for(let y of n.actions){let A=Hf(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:G}=O,D=Ao(o,G,T);return fo(o,D).map((Y)=>{return Y.type==="mutable_atom"?"*"+Y.key:Y.key})})),$=bf(F,M.updates),W={...M,updates:$};Qo(o,LT,T,(O)=>{if(W)O.push(W),O.sort((G,D)=>G.epoch-D.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 dA(o,n,T,t){let S=n.key,f=[];for(let y of n.perspectives){let{viewAtoms:A}=y,M=Ao(o,A,T),F=lo(M,({oldValue:$,newValue:W})=>{let O=$.map((Y)=>Y.key),G=W.map((Y)=>Y.key),D=$.filter((Y)=>!G.includes(Y.key)),z=W.filter((Y)=>!O.includes(Y.key)).flatMap((Y)=>{let B=Y.type==="mutable_atom"?Vo(o,Y):Y,p=fo(o,B);return[B,p]});if(o.logger.info("\uD83D\uDC41","atom",y.resourceAtoms.key,`${T} has a new perspective`,{oldKeys:O,newKeys:G,revealed:z,concealed:D}),z.length>0)t?.emit(`reveal:${S}`,z);if(D.length>0)t?.emit(`conceal:${S}`,D)},`sync-continuity:${S}:${T}:perspective:${y.resourceAtoms.key}`,o);f.push(F)}return f}function dE({socket:o,store:n=to.STORE}){return function T(t){let S=o,f=t.key,y=nS(hf,`socket::${S.id}`,n).userKeyOfSocket,A=fo(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=nS(hf,A,n).socketKeyOfUser,F=lo(M,({newValue:B})=>{if(n.logger.info("\uD83D\uDC4B","continuity",f,`seeing ${A} on new socket ${B}`),B===null){n.logger.warn("\u274C","continuity",f,`User (${A}) is not connected to a socket, waiting for them to reappear.`);return}let p=Ao(n,ZA,B);S=fo(n,p);for(let a of $)S?.emit(`tx-new:${f}`,a)},`sync-continuity:${f}:${A}`,n),$=fo(n,LT,A),W=[],O=dA(n,t,A,S),G=eA(n,t,A,S);W.push(...O,...G);let D=PA(n,t,A,o);S.off(`get:${f}`,D),S.on(`get:${f}`,D);let z=gA(n,t,A);S.off(`tx-run:${f}`,z),S.on(`tx-run:${f}`,z);let Y=lA(n,t,A,$);return S?.on(`ack:${f}`,Y),()=>{for(let B of W)B();S?.off(`ack:${f}`,Y),S?.off(`get:${f}`,D),S?.off(`tx-run:${f}`,z)}}}var{file:LJ,serve:fW}=globalThis.Bun;var k=Symbol.for("drizzle:entityKind"),G5=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,k))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(k in T&&T[k]===n[k])return!0;T=Object.getPrototypeOf(T)}return!1}class Ro{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[k]="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 xf{static[k]="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 mn=Symbol.for("drizzle:Name");class cf{static[k]="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 uA(o,this)}}class uA{constructor(o,n){this.table=o,this.reference=n.reference,this.onUpdate=n._onUpdate,this.onDelete=n._onDelete}static[k]="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[mn],...t,T[0].table[mn],...S];return o??`${f.join("_")}_fk`}}function RS(o,...n){return o(...n)}function aA(o,n){return`${o[mn]}_${n.join("_")}_unique`}function sA(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 oM(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]=sA(o,t+1,!0);T.push(M),t=F;continue}if(f==="}")return[T,t+1];if(f==="{"){let[M,F]=oM(o,t+1);T.push(M),t=F;continue}let[y,A]=sA(o,t,!1);T.push(y),t=A}return[T,t]}function nM(o){let[n]=oM(o,1);return n}function vf(o){return`{${o.map((n)=>{if(Array.isArray(n))return vf(n);if(typeof n==="string")return`"${n.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${n}`}).join(",")}}`}class b extends xf{foreignKeyConfigs=[];static[k]="PgColumnBuilder";array(o){return new tM(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 RS((S,f)=>{let y=new cf(()=>{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 TM(o,this.config)}}class V extends Ro{constructor(o,n){if(!n.uniqueName)n.uniqueName=aA(o,[n.name]);super(o,n);this.table=o}static[k]="PgColumn"}class TM extends V{static[k]="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 wt{static[k]="IndexedColumn";constructor(o,n,T,t){this.name=o,this.keyAsName=n,this.type=T,this.indexConfig=t}name;keyAsName;type;indexConfig}class tM extends b{static[k]="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 pf(o,this.config,n)}}class pf extends V{constructor(o,n,T,t){super(o,n);this.baseColumn=T,this.range=t,this.size=n.size}size;static[k]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(o){if(typeof o==="string")o=nM(o);return o.map((n)=>this.baseColumn.mapFromDriverValue(n))}mapToDriverValue(o,n=!1){let T=o.map((t)=>t===null?null:X(this.baseColumn,pf)?this.baseColumn.mapToDriverValue(t,!0):this.baseColumn.mapToDriverValue(t));if(n)return T;return vf(T)}}var qf=Symbol.for("drizzle:isPgEnum");function SM(o){return!!o&&typeof o==="function"&&qf in o&&o[qf]===!0}class fM extends b{static[k]="PgEnumColumnBuilder";constructor(o,n){super(o,"string","PgEnumColumn");this.config.enum=n}build(o){return new yM(o,this.config)}}class yM extends V{static[k]="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 WS(o,n){return Pk(o,n,void 0)}function Pk(o,n,T){let t=Object.assign((S)=>new fM(S??"",t),{enumName:o,enumValues:n,schema:T,[qf]:!0});return t}class bo{static[k]="Subquery";constructor(o,n,T,t=!1){this._={brand:"Subquery",sql:o,selectedFields:n,alias:T,isWith:t}}}class Kt extends bo{static[k]="WithSubquery"}var AM="0.38.3";var Zf,Pf,Wo={startActiveSpan(o,n){if(!Zf)return n();if(!Pf)Pf=Zf.trace.getTracer("drizzle-orm",AM);return RS((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()}}),Zf,Pf)}};var Yo=Symbol.for("drizzle:ViewBaseConfig");var OS=Symbol.for("drizzle:Schema"),_S=Symbol.for("drizzle:Columns"),MM=Symbol.for("drizzle:ExtraConfigColumns"),gf=Symbol.for("drizzle:OriginalName"),lf=Symbol.for("drizzle:BaseName"),wS=Symbol.for("drizzle:IsAlias"),FM=Symbol.for("drizzle:ExtraConfigBuilder"),gk=Symbol.for("drizzle:IsDrizzleTable");class I{static[k]="Table";static Symbol={Name:mn,Schema:OS,OriginalName:gf,Columns:_S,ExtraConfigColumns:MM,BaseName:lf,IsAlias:wS,ExtraConfigBuilder:FM};[mn];[gf];[OS];[_S];[MM];[lf];[wS]=!1;[gk]=!0;[FM]=void 0;constructor(o,n,T){this[mn]=this[gf]=o,this[OS]=n,this[lf]=T}}function _n(o){return o[mn]}function JT(o){return`${o[OS]??"public"}.${o[mn]}`}function ef(o){return o!==null&&o!==void 0&&typeof o.getSQL==="function"}function lk(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[k]="StringChunk";value;constructor(o){this.value=Array.isArray(o)?o:[o]}getSQL(){return new j([this])}}class j{constructor(o){this.queryChunks=o}static[k]="SQL";decoder=JM;shouldInlineParams=!1;append(o){return this.queryChunks.push(...o.queryChunks),this}toQuery(o){return Wo.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 lk(o.map((F)=>{if(X(F,ho))return{sql:F.value.join(""),params:[]};if(X(F,KS))return{sql:S(F.value),params:[]};if(F===void 0)return{sql:"",params:[]};if(Array.isArray(F)){let $=[new ho("(")];for(let[W,O]of F.entries())if($.push(O),W<F.length-1)$.push(new ho(", "));return $.push(new ho(")")),this.buildQueryFromSourceParams($,T)}if(X(F,j))return this.buildQueryFromSourceParams(F.queryChunks,{...T,inlineParams:A||F.shouldInlineParams});if(X(F,I)){let $=F[I.Symbol.Schema],W=F[I.Symbol.Name];return{sql:$===void 0?S(W):S($)+"."+S(W),params:[]}}if(X(F,Ro)){let $=t.getColumnCasing(F);if(n.invokeSource==="indexes")return{sql:S($),params:[]};let W=F.table[I.Symbol.Schema];return{sql:F.table[wS]||W===void 0?S(F.table[I.Symbol.Name])+"."+S($):S(W)+"."+S(F.table[I.Symbol.Name])+"."+S($),params:[]}}if(X(F,An)){let $=F[Yo].schema,W=F[Yo].name;return{sql:$===void 0?S(W):S($)+"."+S(W),params:[]}}if(X(F,$n)){if(X(F.value,nT))return{sql:f(M.value++,F),params:[F],typings:["none"]};let $=F.value===null?null:F.encoder.mapToDriverValue(F.value);if(X($,j))return this.buildQueryFromSourceParams([$],T);if(A)return{sql:this.mapInlineParam($,T),params:[]};let W=["none"];if(y)W=[y(F.encoder)];return{sql:f(M.value++,$),params:[$],typings:W}}if(X(F,nT))return{sql:f(M.value++,F),params:[F],typings:["none"]};if(X(F,j.Aliased)&&F.fieldAlias!==void 0)return{sql:S(F.fieldAlias),params:[]};if(X(F,bo)){if(F._.isWith)return{sql:S(F._.alias),params:[]};return this.buildQueryFromSourceParams([new ho("("),F._.sql,new ho(") "),new KS(F._.alias)],T)}if(SM(F)){if(F.schema)return{sql:S(F.schema)+"."+S(F.enumName),params:[]};return{sql:S(F.enumName),params:[]}}if(ef(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 j.Aliased(this,o)}mapWith(o){return this.decoder=typeof o==="function"?{mapFromDriverValue:o}:o,this}inlineParams(){return this.shouldInlineParams=!0,this}if(o){return o?this:void 0}}class KS{constructor(o){this.value=o}static[k]="Name";brand;getSQL(){return new j([this])}}function $M(o){return typeof o==="object"&&o!==null&&"mapToDriverValue"in o&&typeof o.mapToDriverValue==="function"}var JM={mapFromDriverValue:(o)=>o},kM={mapToDriverValue:(o)=>o},$Y={...JM,...kM};class $n{constructor(o,n=kM){this.value=o,this.encoder=n}static[k]="Param";brand;getSQL(){return new j([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 j(T)}((o)=>{function n(){return new j([])}o.empty=n;function T(M){return new j(M)}o.fromList=T;function t(M){return new j([new ho(M)])}o.raw=t;function S(M,F){let $=[];for(let[W,O]of M.entries()){if(W>0&&F!==void 0)$.push(F);$.push(O)}return new j($)}o.join=S;function f(M){return new KS(M)}o.identifier=f;function y(M){return new nT(M)}o.placeholder=y;function A(M,F){return new $n(M,F)}o.param=A})(R||(R={}));((o)=>{class n{constructor(T,t){this.sql=T,this.fieldAlias=t}static[k]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new n(this.sql,this.fieldAlias)}}o.Aliased=n})(j||(j={}));class nT{constructor(o){this.name=o}static[k]="Placeholder";getSQL(){return new j([this])}}function df(o,n){return o.map((T)=>{if(X(T,nT)){if(!(T.name in n))throw new Error(`No value for placeholder "${T.name}" was provided`);return n[T.name]}if(X(T,$n)&&X(T.value,nT)){if(!(T.value.name in n))throw new Error(`No value for placeholder "${T.value.name}" was provided`);return T.encoder.mapToDriverValue(n[T.value.name])}return T})}var ek=Symbol.for("drizzle:IsDrizzleView");class An{static[k]="View";[Yo];[ek]=!0;constructor({name:o,schema:n,selectedFields:T,query:t}){this[Yo]={name:o,originalName:o,schema:n,selectedFields:T,query:t,isExisting:!t,isAlias:!1}}getSQL(){return new j([this])}}Ro.prototype.getSQL=function(){return new j([this])};I.prototype.getSQL=function(){return new j([this])};bo.prototype.getSQL=function(){return new j([this])};class IT{constructor(o){this.table=o}static[k]="ColumnAliasProxyHandler";get(o,n){if(n==="table")return this.table;return o[n]}}class Xt{constructor(o,n){this.alias=o,this.replaceOriginalName=n}static[k]="TableAliasProxyHandler";get(o,n){if(n===I.Symbol.IsAlias)return!0;if(n===I.Symbol.Name)return this.alias;if(this.replaceOriginalName&&n===I.Symbol.OriginalName)return this.alias;if(n===Yo)return{...o[Yo],name:this.alias,isAlias:!0};if(n===I.Symbol.Columns){let t=o[I.Symbol.Columns];if(!t)return t;let S={};return Object.keys(t).map((f)=>{S[f]=new Proxy(t[f],new IT(new Proxy(o,this)))}),S}let T=o[n];if(X(T,Ro))return new Proxy(T,new IT(new Proxy(o,this)));return T}}function XS(o,n){return new Proxy(o,new Xt(n,!1))}function rn(o,n){return new Proxy(o,new IT(new Proxy(o.table,new Xt(n,!1))))}function uf(o,n){return new j.Aliased(Et(o.sql,n),o.fieldAlias)}function Et(o,n){return R.join(o.queryChunks.map((T)=>{if(X(T,Ro))return rn(T,n);if(X(T,j))return Et(T,n);if(X(T,j.Aliased))return uf(T,n);return T}))}class ES extends Error{static[k]="DrizzleError";constructor({message:o,cause:n}){super(o);this.name="DrizzleError",this.cause=n}}class af extends ES{static[k]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}function Mn(o,n){if($M(n)&&!ef(o)&&!X(o,$n)&&!X(o,nT)&&!X(o,Ro)&&!X(o,I)&&!X(o,An))return new $n(o,n);return o}var jT=(o,n)=>{return R`${o} = ${Mn(n,o)}`},RM=(o,n)=>{return R`${o} <> ${Mn(n,o)}`};function Yt(...o){let n=o.filter((T)=>T!==void 0);if(n.length===0)return;if(n.length===1)return new j(n);return new j([new ho("("),R.join(n,new ho(" and ")),new ho(")")])}function WM(...o){let n=o.filter((T)=>T!==void 0);if(n.length===0)return;if(n.length===1)return new j(n);return new j([new ho("("),R.join(n,new ho(" or ")),new ho(")")])}function OM(o){return R`not ${o}`}var _M=(o,n)=>{return R`${o} > ${Mn(n,o)}`},wM=(o,n)=>{return R`${o} >= ${Mn(n,o)}`},KM=(o,n)=>{return R`${o} < ${Mn(n,o)}`},XM=(o,n)=>{return R`${o} <= ${Mn(n,o)}`};function EM(o,n){if(Array.isArray(n)){if(n.length===0)return R`false`;return R`${o} in ${n.map((T)=>Mn(T,o))}`}return R`${o} in ${Mn(n,o)}`}function YM(o,n){if(Array.isArray(n)){if(n.length===0)return R`true`;return R`${o} not in ${n.map((T)=>Mn(T,o))}`}return R`${o} not in ${Mn(n,o)}`}function GM(o){return R`${o} is null`}function zM(o){return R`${o} is not null`}function HM(o){return R`exists ${o}`}function mM(o){return R`not exists ${o}`}function QM(o,n,T){return R`${o} between ${Mn(n,o)} and ${Mn(T,o)}`}function DM(o,n,T){return R`${o} not between ${Mn(n,o)} and ${Mn(T,o)}`}function UM(o,n){return R`${o} like ${n}`}function VM(o,n){return R`${o} not like ${n}`}function BM(o,n){return R`${o} ilike ${n}`}function CM(o,n){return R`${o} not ilike ${n}`}function LM(o){return R`${o} asc`}function IM(o){return R`${o} desc`}class jM{static[k]="ConsoleLogWriter";write(o){console.log(o)}}class sf{static[k]="DefaultLogger";writer;constructor(o){this.writer=o?.writer??new jM}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 oy{static[k]="NoopLogger";logQuery(){}}class on{static[k]="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 rM(o,n,T){let t={},S=o.reduce((f,{path:y,field:A},M)=>{let F;if(X(A,Ro))F=A;else if(X(A,j))F=A.decoder;else F=A.sql.decoder;let $=f;for(let[W,O]of y.entries())if(W<y.length-1){if(!(O in $))$[O]={};$=$[O]}else{let G=n[M],D=$[O]=G===null?null:F.mapFromDriverValue(G);if(T&&X(A,Ro)&&y.length===2){let z=y[0];if(!(z in t))t[z]=D===null?_n(A.table):!1;else if(typeof t[z]==="string"&&t[z]!==_n(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 wn(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,Ro)||X(S,j)||X(S,j.Aliased))T.push({path:f,field:S});else if(X(S,I))T.push(...wn(S[I.Symbol.Columns],f));else T.push(...wn(S,f));return T},[])}function Gt(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 YS(o,n){let T=Object.entries(n).filter(([,t])=>t!==void 0).map(([t,S])=>{if(X(S,j)||X(S,Ro))return[t,S];else return[t,new $n(S,o[I.Symbol.Columns][t])]});if(T.length===0)throw new Error("No values to set");return Object.fromEntries(T)}function NM(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 bM(o){return o[I.Symbol.Columns]}function Zn(o){return X(o,bo)?o._.alias:X(o,An)?o[Yo].name:X(o,j)?void 0:o[I.Symbol.IsAlias]?o[I.Symbol.Name]:o[I.Symbol.BaseName]}function So(o,n){return{name:typeof o==="string"&&o.length>0?o:"",config:typeof o==="object"?o:n}}function hM(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 TT extends b{static[k]="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 xM extends TT{static[k]="PgBigInt53Builder";constructor(o){super(o,"number","PgBigInt53")}build(o){return new cM(o,this.config)}}class cM extends V{static[k]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(o){if(typeof o==="number")return o;return Number(o)}}class vM extends TT{static[k]="PgBigInt64Builder";constructor(o){super(o,"bigint","PgBigInt64")}build(o){return new iM(o,this.config)}}class iM extends V{static[k]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(o){return BigInt(o)}}function pM(o,n){let{name:T,config:t}=So(o,n);if(t.mode==="number")return new xM(T);return new vM(T)}class qM extends b{static[k]="PgBigSerial53Builder";constructor(o){super(o,"number","PgBigSerial53");this.config.hasDefault=!0,this.config.notNull=!0}build(o){return new ZM(o,this.config)}}class ZM extends V{static[k]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(o){if(typeof o==="number")return o;return Number(o)}}class PM extends b{static[k]="PgBigSerial64Builder";constructor(o){super(o,"bigint","PgBigSerial64");this.config.hasDefault=!0}build(o){return new gM(o,this.config)}}class gM extends V{static[k]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(o){return BigInt(o)}}function lM(o,n){let{name:T,config:t}=So(o,n);if(t.mode==="number")return new qM(T);return new PM(T)}class eM extends b{static[k]="PgBooleanBuilder";constructor(o){super(o,"boolean","PgBoolean")}build(o){return new dM(o,this.config)}}class dM extends V{static[k]="PgBoolean";getSQLType(){return"boolean"}}function zt(o){return new eM(o??"")}class uM extends b{static[k]="PgCharBuilder";constructor(o,n){super(o,"string","PgChar");this.config.length=n.length,this.config.enumValues=n.enum}build(o){return new aM(o,this.config)}}class aM extends V{static[k]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}}function sM(o,n={}){let{name:T,config:t}=So(o,n);return new uM(T,t)}class oF extends b{static[k]="PgCidrBuilder";constructor(o){super(o,"string","PgCidr")}build(o){return new nF(o,this.config)}}class nF extends V{static[k]="PgCidr";getSQLType(){return"cidr"}}function TF(o){return new oF(o??"")}class tF extends b{static[k]="PgCustomColumnBuilder";constructor(o,n,T){super(o,"custom","PgCustomColumn");this.config.fieldConfig=n,this.config.customTypeParams=T}build(o){return new SF(o,this.config)}}class SF extends V{static[k]="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 fF(o){return(n,T)=>{let{name:t,config:S}=So(n,T);return new tF(t,S,o)}}class Pn extends b{static[k]="PgDateColumnBaseBuilder";defaultNow(){return this.default(R`now()`)}}class yF extends Pn{static[k]="PgDateBuilder";constructor(o){super(o,"date","PgDate")}build(o){return new GS(o,this.config)}}class GS extends V{static[k]="PgDate";getSQLType(){return"date"}mapFromDriverValue(o){return new Date(o)}mapToDriverValue(o){return o.toISOString()}}class AF extends Pn{static[k]="PgDateStringBuilder";constructor(o){super(o,"string","PgDateString")}build(o){return new zS(o,this.config)}}class zS extends V{static[k]="PgDateString";getSQLType(){return"date"}}function MF(o,n){let{name:T,config:t}=So(o,n);if(t?.mode==="date")return new yF(T);return new AF(T)}class FF extends b{static[k]="PgDoublePrecisionBuilder";constructor(o){super(o,"number","PgDoublePrecision")}build(o){return new $F(o,this.config)}}class $F extends V{static[k]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(o){if(typeof o==="string")return Number.parseFloat(o);return o}}function JF(o){return new FF(o??"")}class kF extends b{static[k]="PgInetBuilder";constructor(o){super(o,"string","PgInet")}build(o){return new RF(o,this.config)}}class RF extends V{static[k]="PgInet";getSQLType(){return"inet"}}function WF(o){return new kF(o??"")}class OF extends TT{static[k]="PgIntegerBuilder";constructor(o){super(o,"number","PgInteger")}build(o){return new _F(o,this.config)}}class _F extends V{static[k]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(o){if(typeof o==="string")return Number.parseInt(o);return o}}function HS(o){return new OF(o??"")}class wF extends b{static[k]="PgIntervalBuilder";constructor(o,n){super(o,"string","PgInterval");this.config.intervalConfig=n}build(o){return new KF(o,this.config)}}class KF extends V{static[k]="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 XF(o,n={}){let{name:T,config:t}=So(o,n);return new wF(T,t)}class EF extends b{static[k]="PgJsonBuilder";constructor(o){super(o,"json","PgJson")}build(o){return new mS(o,this.config)}}class mS extends V{static[k]="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 YF(o){return new EF(o??"")}class GF extends b{static[k]="PgJsonbBuilder";constructor(o){super(o,"json","PgJsonb")}build(o){return new QS(o,this.config)}}class QS extends V{static[k]="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 zF(o){return new GF(o??"")}class HF extends b{static[k]="PgLineBuilder";constructor(o){super(o,"array","PgLine")}build(o){return new mF(o,this.config)}}class mF extends V{static[k]="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 QF extends b{static[k]="PgLineABCBuilder";constructor(o){super(o,"json","PgLineABC")}build(o){return new DF(o,this.config)}}class DF extends V{static[k]="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 UF(o,n){let{name:T,config:t}=So(o,n);if(!t?.mode||t.mode==="tuple")return new HF(T);return new QF(T)}class VF extends b{static[k]="PgMacaddrBuilder";constructor(o){super(o,"string","PgMacaddr")}build(o){return new BF(o,this.config)}}class BF extends V{static[k]="PgMacaddr";getSQLType(){return"macaddr"}}function CF(o){return new VF(o??"")}class LF extends b{static[k]="PgMacaddr8Builder";constructor(o){super(o,"string","PgMacaddr8")}build(o){return new IF(o,this.config)}}class IF extends V{static[k]="PgMacaddr8";getSQLType(){return"macaddr8"}}function jF(o){return new LF(o??"")}class rF extends b{static[k]="PgNumericBuilder";constructor(o,n,T){super(o,"string","PgNumeric");this.config.precision=n,this.config.scale=T}build(o){return new DS(o,this.config)}}class DS extends V{static[k]="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 NF(o,n){let{name:T,config:t}=So(o,n);return new rF(T,t?.precision,t?.scale)}class bF extends b{static[k]="PgPointTupleBuilder";constructor(o){super(o,"array","PgPointTuple")}build(o){return new hF(o,this.config)}}class hF extends V{static[k]="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 xF extends b{static[k]="PgPointObjectBuilder";constructor(o){super(o,"json","PgPointObject")}build(o){return new cF(o,this.config)}}class cF extends V{static[k]="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 vF(o,n){let{name:T,config:t}=So(o,n);if(!t?.mode||t.mode==="tuple")return new bF(T);return new xF(T)}function dk(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 iF(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 ny(o){let n=dk(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=iF(n,T);T+=8;let M=iF(n,T);return T+=8,[A,M]}throw new Error("Unsupported geometry type")}class pF extends b{static[k]="PgGeometryBuilder";constructor(o){super(o,"array","PgGeometry")}build(o){return new qF(o,this.config)}}class qF extends V{static[k]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(o){return ny(o)}mapToDriverValue(o){return`point(${o[0]} ${o[1]})`}}class ZF extends b{static[k]="PgGeometryObjectBuilder";constructor(o){super(o,"json","PgGeometryObject")}build(o){return new PF(o,this.config)}}class PF extends V{static[k]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(o){let n=ny(o);return{x:n[0],y:n[1]}}mapToDriverValue(o){return`point(${o.x} ${o.y})`}}function gF(o,n){let{name:T,config:t}=So(o,n);if(!t?.mode||t.mode==="tuple")return new pF(T);return new ZF(T)}class lF extends b{static[k]="PgRealBuilder";constructor(o,n){super(o,"number","PgReal");this.config.length=n}build(o){return new eF(o,this.config)}}class eF extends V{static[k]="PgReal";constructor(o,n){super(o,n)}getSQLType(){return"real"}mapFromDriverValue=(o)=>{if(typeof o==="string")return Number.parseFloat(o);return o}}function dF(o){return new lF(o??"")}class uF extends b{static[k]="PgSerialBuilder";constructor(o){super(o,"number","PgSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(o){return new aF(o,this.config)}}class aF extends V{static[k]="PgSerial";getSQLType(){return"serial"}}function sF(o){return new uF(o??"")}class o$ extends TT{static[k]="PgSmallIntBuilder";constructor(o){super(o,"number","PgSmallInt")}build(o){return new n$(o,this.config)}}class n$ extends V{static[k]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=(o)=>{if(typeof o==="string")return Number(o);return o}}function T$(o){return new o$(o??"")}class t$ extends b{static[k]="PgSmallSerialBuilder";constructor(o){super(o,"number","PgSmallSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(o){return new S$(o,this.config)}}class S$ extends V{static[k]="PgSmallSerial";getSQLType(){return"smallserial"}}function f$(o){return new t$(o??"")}class y$ extends b{static[k]="PgTextBuilder";constructor(o,n){super(o,"string","PgText");this.config.enumValues=n.enum}build(o){return new A$(o,this.config)}}class A$ extends V{static[k]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function M$(o,n={}){let{name:T,config:t}=So(o,n);return new y$(T,t)}class F$ extends Pn{constructor(o,n,T){super(o,"string","PgTime");this.withTimezone=n,this.precision=T,this.config.withTimezone=n,this.config.precision=T}static[k]="PgTimeBuilder";build(o){return new US(o,this.config)}}class US extends V{static[k]="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 $$(o,n={}){let{name:T,config:t}=So(o,n);return new F$(T,t.withTimezone??!1,t.precision)}class J$ extends Pn{static[k]="PgTimestampBuilder";constructor(o,n,T){super(o,"date","PgTimestamp");this.config.withTimezone=n,this.config.precision=T}build(o){return new VS(o,this.config)}}class VS extends V{static[k]="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 k$ extends Pn{static[k]="PgTimestampStringBuilder";constructor(o,n,T){super(o,"string","PgTimestampString");this.config.withTimezone=n,this.config.precision=T}build(o){return new BS(o,this.config)}}class BS extends V{static[k]="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 Qn(o,n={}){let{name:T,config:t}=So(o,n);if(t?.mode==="string")return new k$(T,t.withTimezone??!1,t.precision);return new J$(T,t?.withTimezone??!1,t?.precision)}class R$ extends b{static[k]="PgUUIDBuilder";constructor(o){super(o,"string","PgUUID")}defaultRandom(){return this.default(R`gen_random_uuid()`)}build(o){return new CS(o,this.config)}}class CS extends V{static[k]="PgUUID";getSQLType(){return"uuid"}}function Jn(o){return new R$(o??"")}class W$ extends b{static[k]="PgVarcharBuilder";constructor(o,n){super(o,"string","PgVarchar");this.config.length=n.length,this.config.enumValues=n.enum}build(o){return new O$(o,this.config)}}class O$ extends V{static[k]="PgVarchar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"varchar":`varchar(${this.length})`}}function co(o,n={}){let{name:T,config:t}=So(o,n);return new W$(T,t)}class _$ extends b{static[k]="PgBinaryVectorBuilder";constructor(o,n){super(o,"string","PgBinaryVector");this.config.dimensions=n.dimensions}build(o){return new w$(o,this.config)}}class w$ extends V{static[k]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}}function K$(o,n){let{name:T,config:t}=So(o,n);return new _$(T,t)}class X$ extends b{static[k]="PgHalfVectorBuilder";constructor(o,n){super(o,"array","PgHalfVector");this.config.dimensions=n.dimensions}build(o){return new E$(o,this.config)}}class E$ extends V{static[k]="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 Y$(o,n){let{name:T,config:t}=So(o,n);return new X$(T,t)}class G$ extends b{static[k]="PgSparseVectorBuilder";constructor(o,n){super(o,"string","PgSparseVector");this.config.dimensions=n.dimensions}build(o){return new z$(o,this.config)}}class z$ extends V{static[k]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function H$(o,n){let{name:T,config:t}=So(o,n);return new G$(T,t)}class m$ extends b{static[k]="PgVectorBuilder";constructor(o,n){super(o,"array","PgVector");this.config.dimensions=n.dimensions}build(o){return new Q$(o,this.config)}}class Q$ extends V{static[k]="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 D$(o,n){let{name:T,config:t}=So(o,n);return new m$(T,t)}function U$(){return{bigint:pM,bigserial:lM,boolean:zt,char:sM,cidr:TF,customType:fF,date:MF,doublePrecision:JF,inet:WF,integer:HS,interval:XF,json:YF,jsonb:zF,line:UF,macaddr:CF,macaddr8:jF,numeric:NF,point:vF,geometry:gF,real:dF,serial:sF,smallint:T$,smallserial:f$,text:M$,time:$$,timestamp:Qn,uuid:Jn,varchar:co,bit:K$,halfvec:Y$,sparsevec:H$,vector:D$}}var Ty=Symbol.for("drizzle:PgInlineForeignKeys"),V$=Symbol.for("drizzle:EnableRLS");class vo extends I{static[k]="PgTable";static Symbol=Object.assign({},I.Symbol,{InlineForeignKeys:Ty,EnableRLS:V$});[Ty]=[];[V$]=!1;[I.Symbol.ExtraConfigBuilder]=void 0}function uk(o,n,T,t,S=o){let f=new vo(o,t,S),y=typeof n==="function"?n(U$()):n,A=Object.fromEntries(Object.entries(y).map(([$,W])=>{let O=W;O.setName($);let G=O.build(f);return f[Ty].push(...O.buildForeignKeys(G,f)),[$,G]})),M=Object.fromEntries(Object.entries(y).map(([$,W])=>{let O=W;O.setName($);let G=O.buildExtraConfigColumn(f);return[$,G]})),F=Object.assign(f,A);if(F[I.Symbol.Columns]=A,F[I.Symbol.ExtraConfigColumns]=M,T)F[vo.Symbol.ExtraConfigBuilder]=T;return Object.assign(F,{enableRLS:()=>{return F[vo.Symbol.EnableRLS]=!0,F}})}var tT=(o,n,T)=>{return uk(o,n,T,void 0)};function B$(...o){if(o[0].columns)return new Ht(o[0].columns,o[0].name);return new Ht(o)}class Ht{static[k]="PgPrimaryKeyBuilder";columns;name;constructor(o,n){this.columns=o,this.name=n}build(o){return new C$(o,this.columns,this.name)}}class C${constructor(o,n,T){this.table=o,this.columns=n,this.name=T}static[k]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[vo.Symbol.Name]}_${this.columns.map((o)=>o.name).join("_")}_pk`}}class ty{constructor(o,n,T){this.sourceTable=o,this.referencedTable=n,this.relationName=T,this.referencedTableName=n[I.Symbol.Name]}static[k]="Relation";referencedTableName;fieldName}class L${constructor(o,n){this.table=o,this.config=n}static[k]="Relations"}class ST extends ty{constructor(o,n,T,t){super(o,n,T?.relationName);this.config=T,this.isNullable=t}static[k]="One";withFieldName(o){let n=new ST(this.sourceTable,this.referencedTable,this.config,this.isNullable);return n.fieldName=o,n}}class mt extends ty{constructor(o,n,T){super(o,n,T?.relationName);this.config=T}static[k]="Many";withFieldName(o){let n=new mt(this.sourceTable,this.referencedTable,this.config);return n.fieldName=o,n}}function I$(){return{and:Yt,between:QM,eq:jT,exists:HM,gt:_M,gte:wM,ilike:BM,inArray:EM,isNull:GM,isNotNull:zM,like:UM,lt:KM,lte:XM,ne:RM,not:OM,notBetween:DM,notExists:mM,notLike:VM,notIlike:CM,notInArray:YM,or:WM,sql:R}}function j$(){return{sql:R,asc:LM,desc:IM}}function r$(o,n){if(Object.keys(o).length===1&&"default"in o&&!X(o.default,I))o=o.default;let T={},t={},S={};for(let[f,y]of Object.entries(o))if(X(y,I)){let A=JT(y),M=t[A];T[A]=f,S[f]={tsName:f,dbName:y[I.Symbol.Name],schema:y[I.Symbol.Schema],columns:y[I.Symbol.Columns],relations:M?.relations??{},primaryKey:M?.primaryKey??[]};for(let $ of Object.values(y[I.Symbol.Columns]))if($.primary)S[f].primaryKey.push($);let F=y[I.Symbol.ExtraConfigBuilder]?.(y[I.Symbol.ExtraConfigColumns]);if(F){for(let $ of Object.values(F))if(X($,Ht))S[f].primaryKey.push(...$.columns)}}else if(X(y,L$)){let A=JT(y.table),M=T[A],F=y.config(n(y.table)),$;for(let[W,O]of Object.entries(F))if(M){let G=S[M];if(G.relations[W]=O,$)G.primaryKey.push(...$)}else{if(!(A in t))t[A]={relations:{},primaryKey:$};t[A].relations[W]=O}}return{tables:S,tableNamesMap:T}}function ak(o){return function n(T,t){return new ST(o,T,t,t?.fields.reduce((S,f)=>S&&f.notNull,!0)??!1)}}function sk(o){return function n(T,t){return new mt(o,T,t)}}function N$(o,n,T){if(X(T,ST)&&T.config)return{fields:T.config.fields,references:T.config.references};let t=n[JT(T.referencedTable)];if(!t)throw new Error(`Table "${T.referencedTable[I.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[JT(f)];if(!y)throw new Error(`Table "${f[I.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[I.Symbol.Name]}". Please specify relation name`);if(A[0]&&X(A[0],ST)&&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 b$(o){return{one:ak(o),many:sk(o)}}function LS(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],$=typeof F==="string"?JSON.parse(F):F;f[A.tsKey]=X(M,ST)?$&&LS(o,o[A.relationTableTsKey],$,A.selection,S):$.map((W)=>LS(o,o[A.relationTableTsKey],W,A.selection,S))}else{let M=S(T[y]),F=A.field,$;if(X(F,Ro))$=F;else if(X(F,j))$=F.decoder;else $=F.sql.decoder;f[A.tsKey]=M===null?null:$.mapFromDriverValue(M)}return f}import{readFileSync as u$}from"fs";import{resolve as Fy}from"path";var Mo;(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}})(Mo||(Mo={}));var fy;(function(o){o.mergeShapes=(n,T)=>{return{...n,...T}}})(fy||(fy={}));var r=Mo.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ln=(o)=>{switch(typeof o){case"undefined":return r.undefined;case"string":return r.string;case"number":return isNaN(o)?r.nan:r.number;case"boolean":return r.boolean;case"function":return r.function;case"bigint":return r.bigint;case"symbol":return r.symbol;case"object":if(Array.isArray(o))return r.array;if(o===null)return r.null;if(o.then&&typeof o.then==="function"&&o.catch&&typeof o.catch==="function")return r.promise;if(typeof Map!=="undefined"&&o instanceof Map)return r.map;if(typeof Set!=="undefined"&&o instanceof Set)return r.set;if(typeof Date!=="undefined"&&o instanceof Date)return r.date;return r.object;default:return r.unknown}},m=Mo.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"]),oR=(o)=>{return JSON.stringify(o,null,2).replace(/"([^"]+)":/g,"$1:")};class kn extends Error{get errors(){return this.issues}constructor(o){super();this.issues=[],this.addIssue=(T)=>{this.issues=[...this.issues,T]},this.addIssues=(T=[])=>{this.issues=[...this.issues,...T]};let n=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,n);else this.__proto__=n;this.name="ZodError",this.issues=o}format(o){let n=o||function(S){return S.message},T={_errors:[]},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 kn))throw new Error(`Not a ZodError: ${o}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Mo.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()}}kn.create=(o)=>{return new kn(o)};var hT=(o,n)=>{let T;switch(o.code){case m.invalid_type:if(o.received===r.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,Mo.jsonStringifyReplacer)}`;break;case m.unrecognized_keys:T=`Unrecognized key(s) in object: ${Mo.joinValues(o.keys,", ")}`;break;case m.invalid_union:T="Invalid input";break;case m.invalid_union_discriminator:T=`Invalid discriminator value. Expected ${Mo.joinValues(o.options)}`;break;case m.invalid_enum_value:T=`Invalid enum value. Expected ${Mo.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 Mo.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,Mo.assertNever(o)}return{message:T}},c$=hT;function nR(o){c$=o}function IS(){return c$}var jS=(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}},TR=[];function L(o,n){let T=IS(),t=jS({issueData:n,data:o.data,path:o.path,errorMaps:[o.common.contextualErrorMap,o.schemaErrorMap,T,T===hT?void 0:hT].filter((S)=>!!S)});o.common.issues.push(t)}class eo{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 eo.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"}),NT=(o)=>({status:"dirty",value:o}),nn=(o)=>({status:"valid",value:o}),yy=(o)=>o.status==="aborted",Ay=(o)=>o.status==="dirty",kT=(o)=>o.status==="valid",Ut=(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 v$(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 i;(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})(i||(i={}));var Qt,Dt;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 h$=(o,n)=>{if(kT(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 kn(o.common.issues);return this._error=T,this._error}}}};function oo(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:$}=o;if(y.code==="invalid_enum_value")return{message:$!==null&&$!==void 0?$:A.defaultError};if(typeof A.data==="undefined")return{message:(M=$!==null&&$!==void 0?$:t)!==null&&M!==void 0?M:A.defaultError};if(y.code!=="invalid_type")return{message:A.defaultError};return{message:(F=$!==null&&$!==void 0?$:T)!==null&&F!==void 0?F:A.defaultError}},description:S}}class no{get description(){return this._def.description}_getType(o){return ln(o.data)}_getOrReturnCtx(o,n){return n||{common:o.parent.common,data:o.data,parsedType:ln(o.data),schemaErrorMap:this._def.errorMap,path:o.path,parent:o.parent}}_processInputParams(o){return{status:new eo,ctx:{common:o.parent.common,data:o.data,parsedType:ln(o.data),schemaErrorMap:this._def.errorMap,path:o.path,parent:o.parent}}}_parseSync(o){let n=this._parse(o);if(Ut(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:ln(o)},S=this._parseSync({data:o,path:t.path,parent:t});return h$(t,S)}"~validate"(o){var n,T;let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:o,parsedType:ln(o)};if(!this["~standard"].async)try{let S=this._parseSync({data:o,path:[],parent:t});return kT(S)?{value:S.value}:{issues:t.common.issues}}catch(S){if((T=(n=S===null||S===void 0?void 0:S.message)===null||n===void 0?void 0:n.toLowerCase())===null||T===void 0?void 0:T.includes("encountered"))this["~standard"].async=!0;t.common={issues:[],async:!0}}return this._parseAsync({data:o,path:[],parent:t}).then((S)=>kT(S)?{value:S.value}:{issues:t.common.issues})}async parseAsync(o,n){let T=await this.safeParseAsync(o,n);if(T.success)return T.data;throw T.error}async safeParseAsync(o,n){let T={common:{issues:[],contextualErrorMap:n===null||n===void 0?void 0:n.errorMap,async:!0},path:(n===null||n===void 0?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:o,parsedType:ln(o)},t=this._parse({data:o,path:T.path,parent:T}),S=await(Ut(t)?t:Promise.resolve(t));return h$(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:e.ZodEffects,effect:{type:"refinement",refinement:o}})}superRefine(o){return this._refinement(o)}constructor(o){this.spa=this.safeParseAsync,this._def=o,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:(n)=>this["~validate"](n)}}optional(){return Vn.create(this,this._def)}nullable(){return en.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Un.create(this)}promise(){return _T.create(this,this._def)}or(o){return iT.create([this,o],this._def)}and(o){return pT.create(this,o,this._def)}transform(o){return new Kn({...oo(this._def),schema:this,typeName:e.ZodEffects,effect:{type:"transform",transform:o}})}default(o){let n=typeof o==="function"?o:()=>o;return new gT({...oo(this._def),innerType:this,defaultValue:n,typeName:e.ZodDefault})}brand(){return new bS({typeName:e.ZodBranded,type:this,...oo(this._def)})}catch(o){let n=typeof o==="function"?o:()=>o;return new lT({...oo(this._def),innerType:this,catchValue:n,typeName:e.ZodCatch})}describe(o){return new this.constructor({...this._def,description:o})}pipe(o){return jt.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,SR=/^[0-9a-z]+$/,fR=/^[0-9A-HJKMNP-TV-Z]{26}$/i,yR=/^[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,AR=/^[a-z0-9_-]{21}$/i,MR=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,FR=/^[-+]?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)?)??$/,$R=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,JR="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Sy,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])$/,RR=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,WR=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,OR=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,_R=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,wR=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,i$="((\\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])))",KR=new RegExp(`^${i$}$`);function p$(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 XR(o){return new RegExp(`^${p$(o)}$`)}function q$(o){let n=`${i$}T${p$(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 ER(o,n){if((n==="v4"||!n)&&kR.test(o))return!0;if((n==="v6"||!n)&&WR.test(o))return!0;return!1}function YR(o,n){if(!MR.test(o))return!1;try{let[T]=o.split("."),t=T.replace(/-/g,"+").replace(/_/g,"/").padEnd(T.length+(4-T.length%4)%4,"="),S=JSON.parse(atob(t));if(typeof S!=="object"||S===null)return!1;if(!S.typ||!S.alg)return!1;if(n&&S.alg!==n)return!1;return!0}catch(T){return!1}}function GR(o,n){if((n==="v4"||!n)&&RR.test(o))return!0;if((n==="v6"||!n)&&OR.test(o))return!0;return!1}class Dn extends no{_parse(o){if(this._def.coerce)o.data=String(o.data);if(this._getType(o)!==r.string){let S=this._getOrReturnCtx(o);return L(S,{code:m.invalid_type,expected:r.string,received:S.parsedType}),u}let T=new eo,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),L(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),L(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)L(t,{code:m.too_big,maximum:S.value,type:"string",inclusive:!0,exact:!0,message:S.message});else if(y)L(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(!$R.test(o.data))t=this._getOrReturnCtx(o,t),L(t,{validation:"email",code:m.invalid_string,message:S.message}),T.dirty()}else if(S.kind==="emoji"){if(!Sy)Sy=new RegExp(JR,"u");if(!Sy.test(o.data))t=this._getOrReturnCtx(o,t),L(t,{validation:"emoji",code:m.invalid_string,message:S.message}),T.dirty()}else if(S.kind==="uuid"){if(!yR.test(o.data))t=this._getOrReturnCtx(o,t),L(t,{validation:"uuid",code:m.invalid_string,message:S.message}),T.dirty()}else if(S.kind==="nanoid"){if(!AR.test(o.data))t=this._getOrReturnCtx(o,t),L(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),L(t,{validation:"cuid",code:m.invalid_string,message:S.message}),T.dirty()}else if(S.kind==="cuid2"){if(!SR.test(o.data))t=this._getOrReturnCtx(o,t),L(t,{validation:"cuid2",code:m.invalid_string,message:S.message}),T.dirty()}else if(S.kind==="ulid"){if(!fR.test(o.data))t=this._getOrReturnCtx(o,t),L(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),L(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),L(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),L(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),L(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),L(t,{code:m.invalid_string,validation:{endsWith:S.value},message:S.message}),T.dirty()}else if(S.kind==="datetime"){if(!q$(S).test(o.data))t=this._getOrReturnCtx(o,t),L(t,{code:m.invalid_string,validation:"datetime",message:S.message}),T.dirty()}else if(S.kind==="date"){if(!KR.test(o.data))t=this._getOrReturnCtx(o,t),L(t,{code:m.invalid_string,validation:"date",message:S.message}),T.dirty()}else if(S.kind==="time"){if(!XR(S).test(o.data))t=this._getOrReturnCtx(o,t),L(t,{code:m.invalid_string,validation:"time",message:S.message}),T.dirty()}else if(S.kind==="duration"){if(!FR.test(o.data))t=this._getOrReturnCtx(o,t),L(t,{validation:"duration",code:m.invalid_string,message:S.message}),T.dirty()}else if(S.kind==="ip"){if(!ER(o.data,S.version))t=this._getOrReturnCtx(o,t),L(t,{validation:"ip",code:m.invalid_string,message:S.message}),T.dirty()}else if(S.kind==="jwt"){if(!YR(o.data,S.alg))t=this._getOrReturnCtx(o,t),L(t,{validation:"jwt",code:m.invalid_string,message:S.message}),T.dirty()}else if(S.kind==="cidr"){if(!GR(o.data,S.version))t=this._getOrReturnCtx(o,t),L(t,{validation:"cidr",code:m.invalid_string,message:S.message}),T.dirty()}else if(S.kind==="base64"){if(!_R.test(o.data))t=this._getOrReturnCtx(o,t),L(t,{validation:"base64",code:m.invalid_string,message:S.message}),T.dirty()}else if(S.kind==="base64url"){if(!wR.test(o.data))t=this._getOrReturnCtx(o,t),L(t,{validation:"base64url",code:m.invalid_string,message:S.message}),T.dirty()}else Mo.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,...i.errToObj(T)})}_addCheck(o){return new Dn({...this._def,checks:[...this._def.checks,o]})}email(o){return this._addCheck({kind:"email",...i.errToObj(o)})}url(o){return this._addCheck({kind:"url",...i.errToObj(o)})}emoji(o){return this._addCheck({kind:"emoji",...i.errToObj(o)})}uuid(o){return this._addCheck({kind:"uuid",...i.errToObj(o)})}nanoid(o){return this._addCheck({kind:"nanoid",...i.errToObj(o)})}cuid(o){return this._addCheck({kind:"cuid",...i.errToObj(o)})}cuid2(o){return this._addCheck({kind:"cuid2",...i.errToObj(o)})}ulid(o){return this._addCheck({kind:"ulid",...i.errToObj(o)})}base64(o){return this._addCheck({kind:"base64",...i.errToObj(o)})}base64url(o){return this._addCheck({kind:"base64url",...i.errToObj(o)})}jwt(o){return this._addCheck({kind:"jwt",...i.errToObj(o)})}ip(o){return this._addCheck({kind:"ip",...i.errToObj(o)})}cidr(o){return this._addCheck({kind:"cidr",...i.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,...i.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,...i.errToObj(o===null||o===void 0?void 0:o.message)})}duration(o){return this._addCheck({kind:"duration",...i.errToObj(o)})}regex(o,n){return this._addCheck({kind:"regex",regex:o,...i.errToObj(n)})}includes(o,n){return this._addCheck({kind:"includes",value:o,position:n===null||n===void 0?void 0:n.position,...i.errToObj(n===null||n===void 0?void 0:n.message)})}startsWith(o,n){return this._addCheck({kind:"startsWith",value:o,...i.errToObj(n)})}endsWith(o,n){return this._addCheck({kind:"endsWith",value:o,...i.errToObj(n)})}min(o,n){return this._addCheck({kind:"min",value:o,...i.errToObj(n)})}max(o,n){return this._addCheck({kind:"max",value:o,...i.errToObj(n)})}length(o,n){return this._addCheck({kind:"length",value:o,...i.errToObj(n)})}nonempty(o){return this.min(1,i.errToObj(o))}trim(){return new Dn({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Dn({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Dn({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((o)=>o.kind==="datetime")}get isDate(){return!!this._def.checks.find((o)=>o.kind==="date")}get isTime(){return!!this._def.checks.find((o)=>o.kind==="time")}get isDuration(){return!!this._def.checks.find((o)=>o.kind==="duration")}get isEmail(){return!!this._def.checks.find((o)=>o.kind==="email")}get isURL(){return!!this._def.checks.find((o)=>o.kind==="url")}get isEmoji(){return!!this._def.checks.find((o)=>o.kind==="emoji")}get isUUID(){return!!this._def.checks.find((o)=>o.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((o)=>o.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((o)=>o.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((o)=>o.kind==="cuid2")}get isULID(){return!!this._def.checks.find((o)=>o.kind==="ulid")}get isIP(){return!!this._def.checks.find((o)=>o.kind==="ip")}get isCIDR(){return!!this._def.checks.find((o)=>o.kind==="cidr")}get isBase64(){return!!this._def.checks.find((o)=>o.kind==="base64")}get isBase64url(){return!!this._def.checks.find((o)=>o.kind==="base64url")}get minLength(){let o=null;for(let n of this._def.checks)if(n.kind==="min"){if(o===null||n.value>o)o=n.value}return o}get maxLength(){let o=null;for(let n of this._def.checks)if(n.kind==="max"){if(o===null||n.value<o)o=n.value}return o}}Dn.create=(o)=>{var n;return new Dn({checks:[],typeName:e.ZodString,coerce:(n=o===null||o===void 0?void 0:o.coerce)!==null&&n!==void 0?n:!1,...oo(o)})};function zR(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 yT extends no{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)!==r.number){let S=this._getOrReturnCtx(o);return L(S,{code:m.invalid_type,expected:r.number,received:S.parsedType}),u}let T=void 0,t=new eo;for(let S of this._def.checks)if(S.kind==="int"){if(!Mo.isInteger(o.data))T=this._getOrReturnCtx(o,T),L(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),L(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),L(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(zR(o.data,S.value)!==0)T=this._getOrReturnCtx(o,T),L(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),L(T,{code:m.not_finite,message:S.message}),t.dirty()}else Mo.assertNever(S);return{status:t.value,value:o.data}}gte(o,n){return this.setLimit("min",o,!0,i.toString(n))}gt(o,n){return this.setLimit("min",o,!1,i.toString(n))}lte(o,n){return this.setLimit("max",o,!0,i.toString(n))}lt(o,n){return this.setLimit("max",o,!1,i.toString(n))}setLimit(o,n,T,t){return new yT({...this._def,checks:[...this._def.checks,{kind:o,value:n,inclusive:T,message:i.toString(t)}]})}_addCheck(o){return new yT({...this._def,checks:[...this._def.checks,o]})}int(o){return this._addCheck({kind:"int",message:i.toString(o)})}positive(o){return this._addCheck({kind:"min",value:0,inclusive:!1,message:i.toString(o)})}negative(o){return this._addCheck({kind:"max",value:0,inclusive:!1,message:i.toString(o)})}nonpositive(o){return this._addCheck({kind:"max",value:0,inclusive:!0,message:i.toString(o)})}nonnegative(o){return this._addCheck({kind:"min",value:0,inclusive:!0,message:i.toString(o)})}multipleOf(o,n){return this._addCheck({kind:"multipleOf",value:o,message:i.toString(n)})}finite(o){return this._addCheck({kind:"finite",message:i.toString(o)})}safe(o){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:i.toString(o)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:i.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"&&Mo.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)}}yT.create=(o)=>{return new yT({checks:[],typeName:e.ZodNumber,coerce:(o===null||o===void 0?void 0:o.coerce)||!1,...oo(o)})};class AT extends no{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(o){if(this._def.coerce)try{o.data=BigInt(o.data)}catch(S){return this._getInvalidInput(o)}if(this._getType(o)!==r.bigint)return this._getInvalidInput(o);let T=void 0,t=new eo;for(let S of this._def.checks)if(S.kind==="min"){if(S.inclusive?o.data<S.value:o.data<=S.value)T=this._getOrReturnCtx(o,T),L(T,{code: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),L(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),L(T,{code:m.not_multiple_of,multipleOf:S.value,message:S.message}),t.dirty()}else Mo.assertNever(S);return{status:t.value,value:o.data}}_getInvalidInput(o){let n=this._getOrReturnCtx(o);return L(n,{code:m.invalid_type,expected:r.bigint,received:n.parsedType}),u}gte(o,n){return this.setLimit("min",o,!0,i.toString(n))}gt(o,n){return this.setLimit("min",o,!1,i.toString(n))}lte(o,n){return this.setLimit("max",o,!0,i.toString(n))}lt(o,n){return this.setLimit("max",o,!1,i.toString(n))}setLimit(o,n,T,t){return new AT({...this._def,checks:[...this._def.checks,{kind:o,value:n,inclusive:T,message:i.toString(t)}]})}_addCheck(o){return new AT({...this._def,checks:[...this._def.checks,o]})}positive(o){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:i.toString(o)})}negative(o){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:i.toString(o)})}nonpositive(o){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:i.toString(o)})}nonnegative(o){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:i.toString(o)})}multipleOf(o,n){return this._addCheck({kind:"multipleOf",value:o,message:i.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}}AT.create=(o)=>{var n;return new AT({checks:[],typeName:e.ZodBigInt,coerce:(n=o===null||o===void 0?void 0:o.coerce)!==null&&n!==void 0?n:!1,...oo(o)})};class xT extends no{_parse(o){if(this._def.coerce)o.data=Boolean(o.data);if(this._getType(o)!==r.boolean){let T=this._getOrReturnCtx(o);return L(T,{code:m.invalid_type,expected:r.boolean,received:T.parsedType}),u}return nn(o.data)}}xT.create=(o)=>{return new xT({typeName:e.ZodBoolean,coerce:(o===null||o===void 0?void 0:o.coerce)||!1,...oo(o)})};class RT extends no{_parse(o){if(this._def.coerce)o.data=new Date(o.data);if(this._getType(o)!==r.date){let S=this._getOrReturnCtx(o);return L(S,{code:m.invalid_type,expected:r.date,received:S.parsedType}),u}if(isNaN(o.data.getTime())){let S=this._getOrReturnCtx(o);return L(S,{code:m.invalid_date}),u}let T=new eo,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),L(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),L(t,{code:m.too_big,message:S.message,inclusive:!0,exact:!1,maximum:S.value,type:"date"}),T.dirty()}else Mo.assertNever(S);return{status:T.value,value:new Date(o.data.getTime())}}_addCheck(o){return new RT({...this._def,checks:[...this._def.checks,o]})}min(o,n){return this._addCheck({kind:"min",value:o.getTime(),message:i.toString(n)})}max(o,n){return this._addCheck({kind:"max",value:o.getTime(),message:i.toString(n)})}get minDate(){let o=null;for(let n of this._def.checks)if(n.kind==="min"){if(o===null||n.value>o)o=n.value}return o!=null?new Date(o):null}get maxDate(){let o=null;for(let n of this._def.checks)if(n.kind==="max"){if(o===null||n.value<o)o=n.value}return o!=null?new Date(o):null}}RT.create=(o)=>{return new RT({checks:[],coerce:(o===null||o===void 0?void 0:o.coerce)||!1,typeName:e.ZodDate,...oo(o)})};class Vt extends no{_parse(o){if(this._getType(o)!==r.symbol){let T=this._getOrReturnCtx(o);return L(T,{code:m.invalid_type,expected:r.symbol,received:T.parsedType}),u}return nn(o.data)}}Vt.create=(o)=>{return new Vt({typeName:e.ZodSymbol,...oo(o)})};class cT extends no{_parse(o){if(this._getType(o)!==r.undefined){let T=this._getOrReturnCtx(o);return L(T,{code:m.invalid_type,expected:r.undefined,received:T.parsedType}),u}return nn(o.data)}}cT.create=(o)=>{return new cT({typeName:e.ZodUndefined,...oo(o)})};class vT extends no{_parse(o){if(this._getType(o)!==r.null){let T=this._getOrReturnCtx(o);return L(T,{code:m.invalid_type,expected:r.null,received:T.parsedType}),u}return nn(o.data)}}vT.create=(o)=>{return new vT({typeName:e.ZodNull,...oo(o)})};class WT extends no{constructor(){super(...arguments);this._any=!0}_parse(o){return nn(o.data)}}WT.create=(o)=>{return new WT({typeName:e.ZodAny,...oo(o)})};class fT extends no{constructor(){super(...arguments);this._unknown=!0}_parse(o){return nn(o.data)}}fT.create=(o)=>{return new fT({typeName:e.ZodUnknown,...oo(o)})};class Nn extends no{_parse(o){let n=this._getOrReturnCtx(o);return L(n,{code:m.invalid_type,expected:r.never,received:n.parsedType}),u}}Nn.create=(o)=>{return new Nn({typeName:e.ZodNever,...oo(o)})};class Bt extends no{_parse(o){if(this._getType(o)!==r.undefined){let T=this._getOrReturnCtx(o);return L(T,{code:m.invalid_type,expected:r.void,received:T.parsedType}),u}return nn(o.data)}}Bt.create=(o)=>{return new Bt({typeName:e.ZodVoid,...oo(o)})};class Un extends no{_parse(o){let{ctx:n,status:T}=this._processInputParams(o),t=this._def;if(n.parsedType!==r.array)return L(n,{code:m.invalid_type,expected:r.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)L(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)L(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)L(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 eo.mergeArray(T,f)});let S=[...n.data].map((f,y)=>{return t.type._parseSync(new Bn(n,f,n.path,y))});return eo.mergeArray(T,S)}get element(){return this._def.type}min(o,n){return new Un({...this._def,minLength:{value:o,message:i.toString(n)}})}max(o,n){return new Un({...this._def,maxLength:{value:o,message:i.toString(n)}})}length(o,n){return new Un({...this._def,exactLength:{value:o,message:i.toString(n)}})}nonempty(o){return this.min(1,o)}}Un.create=(o,n)=>{return new Un({type:o,minLength:null,maxLength:null,exactLength:null,typeName:e.ZodArray,...oo(n)})};function rT(o){if(o instanceof Do){let n={};for(let T in o.shape){let t=o.shape[T];n[T]=Vn.create(rT(t))}return new Do({...o._def,shape:()=>n})}else if(o instanceof Un)return new Un({...o._def,type:rT(o.element)});else if(o instanceof Vn)return Vn.create(rT(o.unwrap()));else if(o instanceof en)return en.create(rT(o.unwrap()));else if(o instanceof bn)return bn.create(o.items.map((n)=>rT(n)));else return o}class Do extends no{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=Mo.objectKeys(o);return this._cached={shape:o,keys:n}}_parse(o){if(this._getType(o)!==r.object){let M=this._getOrReturnCtx(o);return L(M,{code:m.invalid_type,expected:r.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],$=t.data[M];A.push({key:{status:"valid",value:M},value:F._parse(new Bn(t,$,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)L(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 $=t.data[F];A.push({key:{status:"valid",value:F},value:M._parse(new Bn(t,$,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 $=await F.key,W=await F.value;M.push({key:$,value:W,alwaysSet:F.alwaysSet})}return M}).then((M)=>{return eo.mergeObjectSync(T,M)});else return eo.mergeObjectSync(T,A)}get shape(){return this._def.shape()}strict(o){return i.errToObj,new Do({...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=i.errToObj(o).message)!==null&&y!==void 0?y:A};return{message:A}}}:{}})}strip(){return new Do({...this._def,unknownKeys:"strip"})}passthrough(){return new Do({...this._def,unknownKeys:"passthrough"})}extend(o){return new Do({...this._def,shape:()=>({...this._def.shape(),...o})})}merge(o){return new Do({unknownKeys:o._def.unknownKeys,catchall:o._def.catchall,shape:()=>({...this._def.shape(),...o._def.shape()}),typeName:e.ZodObject})}setKey(o,n){return this.augment({[o]:n})}catchall(o){return new Do({...this._def,catchall:o})}pick(o){let n={};return Mo.objectKeys(o).forEach((T)=>{if(o[T]&&this.shape[T])n[T]=this.shape[T]}),new Do({...this._def,shape:()=>n})}omit(o){let n={};return Mo.objectKeys(this.shape).forEach((T)=>{if(!o[T])n[T]=this.shape[T]}),new Do({...this._def,shape:()=>n})}deepPartial(){return rT(this)}partial(o){let n={};return Mo.objectKeys(this.shape).forEach((T)=>{let t=this.shape[T];if(o&&!o[T])n[T]=t;else n[T]=t.optional()}),new Do({...this._def,shape:()=>n})}required(o){let n={};return Mo.objectKeys(this.shape).forEach((T)=>{if(o&&!o[T])n[T]=this.shape[T];else{let S=this.shape[T];while(S instanceof Vn)S=S._def.innerType;n[T]=S}}),new Do({...this._def,shape:()=>n})}keyof(){return Z$(Mo.objectKeys(this.shape))}}Do.create=(o,n)=>{return new Do({shape:()=>o,unknownKeys:"strip",catchall:Nn.create(),typeName:e.ZodObject,...oo(n)})};Do.strictCreate=(o,n)=>{return new Do({shape:()=>o,unknownKeys:"strict",catchall:Nn.create(),typeName:e.ZodObject,...oo(n)})};Do.lazycreate=(o,n)=>{return new Do({shape:o,unknownKeys:"strip",catchall:Nn.create(),typeName:e.ZodObject,...oo(n)})};class iT extends no{_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 kn(y.ctx.common.issues));return L(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 kn(A));return L(n,{code:m.invalid_union,unionErrors:y}),u}}get options(){return this._def.options}}iT.create=(o,n)=>{return new iT({options:o,typeName:e.ZodUnion,...oo(n)})};var gn=(o)=>{if(o instanceof qT)return gn(o.schema);else if(o instanceof Kn)return gn(o.innerType());else if(o instanceof ZT)return[o.value];else if(o instanceof MT)return o.options;else if(o instanceof PT)return Mo.objectValues(o.enum);else if(o instanceof gT)return gn(o._def.innerType);else if(o instanceof cT)return[void 0];else if(o instanceof vT)return[null];else if(o instanceof Vn)return[void 0,...gn(o.unwrap())];else if(o instanceof en)return[null,...gn(o.unwrap())];else if(o instanceof bS)return gn(o.unwrap());else if(o instanceof eT)return gn(o.unwrap());else if(o instanceof lT)return gn(o._def.innerType);else return[]};class NS extends no{_parse(o){let{ctx:n}=this._processInputParams(o);if(n.parsedType!==r.object)return L(n,{code:m.invalid_type,expected:r.object,received:n.parsedType}),u;let T=this.discriminator,t=n.data[T],S=this.optionsMap.get(t);if(!S)return L(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=gn(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 NS({typeName:e.ZodDiscriminatedUnion,discriminator:o,options:n,optionsMap:t,...oo(T)})}}function My(o,n){let T=ln(o),t=ln(n);if(o===n)return{valid:!0,data:o};else if(T===r.object&&t===r.object){let S=Mo.objectKeys(n),f=Mo.objectKeys(o).filter((A)=>S.indexOf(A)!==-1),y={...o,...n};for(let A of f){let M=My(o[A],n[A]);if(!M.valid)return{valid:!1};y[A]=M.data}return{valid:!0,data:y}}else if(T===r.array&&t===r.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=My(y,A);if(!M.valid)return{valid:!1};S.push(M.data)}return{valid:!0,data:S}}else if(T===r.date&&t===r.date&&+o===+n)return{valid:!0,data:o};else return{valid:!1}}class pT extends no{_parse(o){let{status:n,ctx:T}=this._processInputParams(o),t=(S,f)=>{if(yy(S)||yy(f))return u;let y=My(S.value,f.value);if(!y.valid)return L(T,{code:m.invalid_intersection_types}),u;if(Ay(S)||Ay(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}))}}pT.create=(o,n,T)=>{return new pT({left:o,right:n,typeName:e.ZodIntersection,...oo(T)})};class bn extends no{_parse(o){let{status:n,ctx:T}=this._processInputParams(o);if(T.parsedType!==r.array)return L(T,{code:m.invalid_type,expected:r.array,received:T.parsedType}),u;if(T.data.length<this._def.items.length)return L(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)L(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 eo.mergeArray(n,f)});else return eo.mergeArray(n,S)}get items(){return this._def.items}rest(o){return new bn({...this._def,rest:o})}}bn.create=(o,n)=>{if(!Array.isArray(o))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new bn({items:o,typeName:e.ZodTuple,rest:null,...oo(n)})};class Ct extends no{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!==r.object)return L(T,{code:m.invalid_type,expected:r.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 eo.mergeObjectAsync(n,t);else return eo.mergeObjectSync(n,t)}get element(){return this._def.valueType}static create(o,n,T){if(n instanceof no)return new Ct({keyType:o,valueType:n,typeName:e.ZodRecord,...oo(T)});return new Ct({keyType:Dn.create(),valueType:o,typeName:e.ZodRecord,...oo(n)})}}class Lt extends no{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!==r.map)return L(T,{code:m.invalid_type,expected:r.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}}}}Lt.create=(o,n,T)=>{return new Lt({valueType:n,keyType:o,typeName:e.ZodMap,...oo(T)})};class OT extends no{_parse(o){let{status:n,ctx:T}=this._processInputParams(o);if(T.parsedType!==r.set)return L(T,{code:m.invalid_type,expected:r.set,received:T.parsedType}),u;let t=this._def;if(t.minSize!==null){if(T.data.size<t.minSize.value)L(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)L(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 OT({...this._def,minSize:{value:o,message:i.toString(n)}})}max(o,n){return new OT({...this._def,maxSize:{value:o,message:i.toString(n)}})}size(o,n){return this.min(o,n).max(o,n)}nonempty(o){return this.min(1,o)}}OT.create=(o,n)=>{return new OT({valueType:o,minSize:null,maxSize:null,typeName:e.ZodSet,...oo(n)})};class bT extends no{constructor(){super(...arguments);this.validate=this.implement}_parse(o){let{ctx:n}=this._processInputParams(o);if(n.parsedType!==r.function)return L(n,{code:m.invalid_type,expected:r.function,received:n.parsedType}),u;function T(y,A){return jS({data:y,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,IS(),hT].filter((M)=>!!M),issueData:{code:m.invalid_arguments,argumentsError:A}})}function t(y,A){return jS({data:y,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,IS(),hT].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 _T){let y=this;return nn(async function(...A){let M=new kn([]),F=await y._def.args.parseAsync(A,S).catch((O)=>{throw M.addIssue(T(A,O)),M}),$=await Reflect.apply(f,this,F);return await y._def.returns._def.type.parseAsync($,S).catch((O)=>{throw M.addIssue(t($,O)),M})})}else{let y=this;return nn(function(...A){let M=y._def.args.safeParse(A,S);if(!M.success)throw new kn([T(A,M.error)]);let F=Reflect.apply(f,this,M.data),$=y._def.returns.safeParse(F,S);if(!$.success)throw new kn([t(F,$.error)]);return $.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...o){return new bT({...this._def,args:bn.create(o).rest(fT.create())})}returns(o){return new bT({...this._def,returns:o})}implement(o){return this.parse(o)}strictImplement(o){return this.parse(o)}static create(o,n,T){return new bT({args:o?o:bn.create([]).rest(fT.create()),returns:n||fT.create(),typeName:e.ZodFunction,...oo(T)})}}class qT extends no{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})}}qT.create=(o,n)=>{return new qT({getter:o,typeName:e.ZodLazy,...oo(n)})};class ZT extends no{_parse(o){if(o.data!==this._def.value){let n=this._getOrReturnCtx(o);return L(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}}ZT.create=(o,n)=>{return new ZT({value:o,typeName:e.ZodLiteral,...oo(n)})};function Z$(o,n){return new MT({values:o,typeName:e.ZodEnum,...oo(n)})}class MT extends no{constructor(){super(...arguments);Qt.set(this,void 0)}_parse(o){if(typeof o.data!=="string"){let n=this._getOrReturnCtx(o),T=this._def.values;return L(n,{expected:Mo.joinValues(T),received:n.parsedType,code:m.invalid_type}),u}if(!rS(this,Qt,"f"))v$(this,Qt,new Set(this._def.values),"f");if(!rS(this,Qt,"f").has(o.data)){let n=this._getOrReturnCtx(o),T=this._def.values;return L(n,{received:n.data,code:m.invalid_enum_value,options:T}),u}return nn(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 MT.create(o,{...this._def,...n})}exclude(o,n=this._def){return MT.create(this.options.filter((T)=>!o.includes(T)),{...this._def,...n})}}Qt=new WeakMap;MT.create=Z$;class PT extends no{constructor(){super(...arguments);Dt.set(this,void 0)}_parse(o){let n=Mo.getValidEnumValues(this._def.values),T=this._getOrReturnCtx(o);if(T.parsedType!==r.string&&T.parsedType!==r.number){let t=Mo.objectValues(n);return L(T,{expected:Mo.joinValues(t),received:T.parsedType,code:m.invalid_type}),u}if(!rS(this,Dt,"f"))v$(this,Dt,new Set(Mo.getValidEnumValues(this._def.values)),"f");if(!rS(this,Dt,"f").has(o.data)){let t=Mo.objectValues(n);return L(T,{received:T.data,code:m.invalid_enum_value,options:t}),u}return nn(o.data)}get enum(){return this._def.values}}Dt=new WeakMap;PT.create=(o,n)=>{return new PT({values:o,typeName:e.ZodNativeEnum,...oo(n)})};class _T extends no{unwrap(){return this._def.type}_parse(o){let{ctx:n}=this._processInputParams(o);if(n.parsedType!==r.promise&&n.common.async===!1)return L(n,{code:m.invalid_type,expected:r.promise,received:n.parsedType}),u;let T=n.parsedType===r.promise?n.data:Promise.resolve(n.data);return nn(T.then((t)=>{return this._def.type.parseAsync(t,{path:n.path,errorMap:n.common.contextualErrorMap})}))}}_T.create=(o,n)=>{return new _T({type:o,typeName:e.ZodPromise,...oo(n)})};class Kn extends no{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===e.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(L(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 NT(A.value);if(n.value==="dirty")return NT(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 NT(y.value);if(n.value==="dirty")return NT(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(!kT(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(!kT(f))return f;return Promise.resolve(t.transform(f.value,S)).then((y)=>({status:n.value,value:y}))});Mo.assertNever(t)}}Kn.create=(o,n,T)=>{return new Kn({schema:o,typeName:e.ZodEffects,effect:n,...oo(T)})};Kn.createWithPreprocess=(o,n,T)=>{return new Kn({schema:n,effect:{type:"preprocess",transform:o},typeName:e.ZodEffects,...oo(T)})};class Vn extends no{_parse(o){if(this._getType(o)===r.undefined)return nn(void 0);return this._def.innerType._parse(o)}unwrap(){return this._def.innerType}}Vn.create=(o,n)=>{return new Vn({innerType:o,typeName:e.ZodOptional,...oo(n)})};class en extends no{_parse(o){if(this._getType(o)===r.null)return nn(null);return this._def.innerType._parse(o)}unwrap(){return this._def.innerType}}en.create=(o,n)=>{return new en({innerType:o,typeName:e.ZodNullable,...oo(n)})};class gT extends no{_parse(o){let{ctx:n}=this._processInputParams(o),T=n.data;if(n.parsedType===r.undefined)T=this._def.defaultValue();return this._def.innerType._parse({data:T,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}gT.create=(o,n)=>{return new gT({innerType:o,typeName:e.ZodDefault,defaultValue:typeof n.default==="function"?n.default:()=>n.default,...oo(n)})};class lT extends no{_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(Ut(t))return t.then((S)=>{return{status:"valid",value:S.status==="valid"?S.value:this._def.catchValue({get error(){return new kn(T.common.issues)},input:T.data})}});else return{status:"valid",value:t.status==="valid"?t.value:this._def.catchValue({get error(){return new kn(T.common.issues)},input:T.data})}}removeCatch(){return this._def.innerType}}lT.create=(o,n)=>{return new lT({innerType:o,typeName:e.ZodCatch,catchValue:typeof n.catch==="function"?n.catch:()=>n.catch,...oo(n)})};class It extends no{_parse(o){if(this._getType(o)!==r.nan){let T=this._getOrReturnCtx(o);return L(T,{code:m.invalid_type,expected:r.nan,received:T.parsedType}),u}return{status:"valid",value:o.data}}}It.create=(o)=>{return new It({typeName:e.ZodNaN,...oo(o)})};var HR=Symbol("zod_brand");class bS extends no{_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 jt extends no{_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(),NT(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 jt({in:o,out:n,typeName:e.ZodPipeline})}}class eT extends no{_parse(o){let n=this._def.innerType._parse(o),T=(t)=>{if(kT(t))t.value=Object.freeze(t.value);return t};return Ut(n)?n.then((t)=>T(t)):T(n)}unwrap(){return this._def.innerType}}eT.create=(o,n)=>{return new eT({innerType:o,typeName:e.ZodReadonly,...oo(n)})};function P$(o,n={},T){if(o)return WT.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 WT.create()}var mR={object:Do.lazycreate},e;(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"})(e||(e={}));var QR=(o,n={message:`Input not instance of ${o.name}`})=>P$((T)=>T instanceof o,n),g$=Dn.create,l$=yT.create,DR=It.create,UR=AT.create,e$=xT.create,VR=RT.create,BR=Vt.create,CR=cT.create,LR=vT.create,IR=WT.create,jR=fT.create,rR=Nn.create,NR=Bt.create,bR=Un.create,rt=Do.create,hR=Do.strictCreate,xR=iT.create,cR=NS.create,vR=pT.create,iR=bn.create,pR=Ct.create,qR=Lt.create,ZR=OT.create,PR=bT.create,gR=qT.create,lR=ZT.create,eR=MT.create,dR=PT.create,uR=_T.create,x$=Kn.create,aR=Vn.create,sR=en.create,o0=Kn.createWithPreprocess,n0=jt.create,T0=()=>g$().optional(),t0=()=>l$().optional(),S0=()=>e$().optional(),f0={string:(o)=>Dn.create({...o,coerce:!0}),number:(o)=>yT.create({...o,coerce:!0}),boolean:(o)=>xT.create({...o,coerce:!0}),bigint:(o)=>AT.create({...o,coerce:!0}),date:(o)=>RT.create({...o,coerce:!0})},y0=u,Go=Object.freeze({__proto__:null,defaultErrorMap:hT,setErrorMap:nR,getErrorMap:IS,makeIssue:jS,EMPTY_PATH:TR,addIssueToContext:L,ParseStatus:eo,INVALID:u,DIRTY:NT,OK:nn,isAborted:yy,isDirty:Ay,isValid:kT,isAsync:Ut,get util(){return Mo},get objectUtil(){return fy},ZodParsedType:r,getParsedType:ln,ZodType:no,datetimeRegex:q$,ZodString:Dn,ZodNumber:yT,ZodBigInt:AT,ZodBoolean:xT,ZodDate:RT,ZodSymbol:Vt,ZodUndefined:cT,ZodNull:vT,ZodAny:WT,ZodUnknown:fT,ZodNever:Nn,ZodVoid:Bt,ZodArray:Un,ZodObject:Do,ZodUnion:iT,ZodDiscriminatedUnion:NS,ZodIntersection:pT,ZodTuple:bn,ZodRecord:Ct,ZodMap:Lt,ZodSet:OT,ZodFunction:bT,ZodLazy:qT,ZodLiteral:ZT,ZodEnum:MT,ZodNativeEnum:PT,ZodPromise:_T,ZodEffects:Kn,ZodTransformer:Kn,ZodOptional:Vn,ZodNullable:en,ZodDefault:gT,ZodCatch:lT,ZodNaN:It,BRAND:HR,ZodBranded:bS,ZodPipeline:jt,ZodReadonly:eT,custom:P$,Schema:no,ZodSchema:no,late:mR,get ZodFirstPartyTypeKind(){return e},coerce:f0,any:IR,array:bR,bigint:UR,boolean:e$,date:VR,discriminatedUnion:cR,effect:x$,enum:eR,function:PR,instanceof:QR,intersection:vR,lazy:gR,literal:lR,map:qR,nan:DR,nativeEnum:dR,never:rR,null:LR,nullable:sR,number:l$,object:rt,oboolean:S0,onumber:t0,optional:aR,ostring:T0,pipeline:n0,preprocess:o0,promise:uR,record:pR,set:ZR,strictObject:hR,string:g$,symbol:BR,transformer:x$,tuple:iR,undefined:CR,union:xR,unknown:jR,void:NR,NEVER:y0,ZodIssueCode:m,quotelessJson:oR,ZodError:kn});function d$(o){let n=o.runtimeEnvStrict??o.runtimeEnv??process.env;if(o.emptyStringAsUndefined??!1){for(let[K,Q]of Object.entries(n))if(Q==="")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=rt(S),M=rt(f),F=rt(y),$=o.isServer??(typeof window==="undefined"||("Deno"in window)),W=A.merge(F),O=M.merge(F).merge(A),G=$?O.safeParse(n):W.safeParse(n),D=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(G.success===!1)return D(G.error);let Y=(K)=>{if(!o.clientPrefix)return!0;return!K.startsWith(o.clientPrefix)&&!(K in F.shape)},B=(K)=>{return $||!Y(K)},p=(K)=>{return K==="__esModule"||K==="$$typeof"},c=(o.extends??[]).reduce((K,Q)=>{return Object.assign(K,Q)},{}),a=Object.assign(G.data,c);return new Proxy(a,{get(K,Q){if(typeof Q!=="string")return;if(p(Q))return;if(!B(Q))return z(Q);return Reflect.get(K,Q)}})}var A0="__vite_start_time"in globalThis,M0=typeof window!=="undefined",S9="vitest"in globalThis,Cn=d$({isServer:!A0&&!M0,server:{CI:Go.string().transform((o)=>!0).optional(),POSTGRES_USER:Go.string(),POSTGRES_PASSWORD:Go.string(),POSTGRES_DATABASE:Go.string(),POSTGRES_HOST:Go.string(),POSTGRES_PORT:Go.string().transform((o)=>Number.parseInt(o,10)),BACKEND_PORT:Go.string().transform((o)=>Number.parseInt(o,10)),RUN_WORKERS_FROM_SOURCE:Go.union([Go.literal("true"),Go.literal("false")]).optional().transform((o)=>o==="true"),FRONTEND_PORT:Go.string().transform((o)=>Number.parseInt(o,10)),FRONTEND_ORIGINS:Go.string().transform((o)=>JSON.parse(o)).pipe(Go.array(Go.string())),OPENAI_API_KEY:Go.string().optional()},clientPrefix:"VITE_",client:{VITE_BACKEND_ORIGIN:Go.string(),VITE_USE_SELF_SIGNED_CERTIFICATE:Go.union([Go.literal("true"),Go.literal("false")]).optional().transform((o)=>o==="true")},runtimeEnv:import.meta.env,emptyStringAsUndefined:!0});var a$=Fy(import.meta.dirname,"../dev"),s$=Cn.VITE_USE_SELF_SIGNED_CERTIFICATE?{cert:u$(Fy(a$,"./cert.pem"),"utf-8"),key:u$(Fy(a$,"./key.pem"),"utf-8")}:void 0;import nW from"path";import L0 from"os";import I0 from"fs";var hS=new Map,$y=new Map,Jy=Symbol("OriginError"),dT={};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[Jy]=this.handler.debug?new Error:this.tagged&&F0(this.strings)}get origin(){return(this.handler.debug?this[Jy].stack:this.tagged&&$y.has(this.strings)?$y.get(this.strings):$y.set(this.strings,this[Jy].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(dT),{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 F0(o){if(hS.has(o))return hS.get(o);let n=Error.stackTraceLimit;return Error.stackTraceLimit=4,hS.set(o,new Error),Error.stackTraceLimit=n,hS.get(o)}class uT extends Error{constructor(o){super(o.message);this.name=this.constructor.name,Object.assign(this,o)}}var Lo={connection:oJ,postgres:nJ,generic:TJ,notSupported:tJ};function oJ(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,oJ),f}function nJ(o){let n=new uT(o);return Error.captureStackTrace(n,nJ),n}function TJ(o,n){let T=Object.assign(new Error(o+": "+n),{code:o});return Error.captureStackTrace(T,TJ),T}function tJ(o){let n=Object.assign(new Error(o+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:o});return Error.captureStackTrace(n,tJ),n}var $0={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 vS{then(){ky()}catch(){ky()}finally(){ky()}}class xt extends vS{constructor(o){super();this.value=qS(o)}}class hn extends vS{constructor(o,n,T){super();this.value=o,this.type=n,this.array=T}}class iS extends vS{constructor(o,n){super();this.first=o,this.rest=n}build(o,n,T,t){let S=J0.map(([f,y])=>({fn:y,i:o.search(f)})).sort((f,y)=>f.i-y.i).pop();return S.i===-1?wy(this.first,t):S.fn(this.first,this.rest,n,T,t)}}function pS(o,n,T,t){let S=o instanceof hn?o.value:o;if(S===void 0){if(o instanceof hn?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 hn?(n.push(o.value),o.array?o.array[o.type||cS(o.value)]||o.type||AJ(o.value):o.type):(n.push(o),cS(o)))}var fJ=FJ($0);function Oy(o,n,T,t,S,f){for(let y=1;y<o.strings.length;y++)n+=_y(n,T,t,S,f)+o.strings[y],T=o.args[y];return n}function _y(o,n,T,t,S){return n instanceof iS?n.build(o,T,t,S):n instanceof Xn?Wy(n,T,t,S):n instanceof xt?n.value:n&&n[0]instanceof Xn?n.reduce((f,y)=>f+" "+Wy(y,T,t,S),""):pS(n,T,t,S)}function Wy(o,n,T,t){return o.fragment=!0,Oy(o,o.strings[0],o.args[0],n,T,t)}function yJ(o,n,T,t,S){return o.map((f)=>"("+t.map((y)=>_y("values",f[y],n,T,S)).join(",")+")").join(",")}function SJ(o,n,T,t,S){let f=Array.isArray(o[0]),y=n.length?n.flat():Object.keys(f?o[0]:o);return yJ(f?o:[o],T,t,y,S)}function xS(o,n,T,t,S){if(typeof o==="string"&&(o=[o].concat(n)),Array.isArray(o))return wy(o,S);let f;return(n.length?n.flat():Object.keys(o)).map((A)=>{return f=o[A],(f instanceof Xn?Wy(f,T,t,S):f instanceof xt?f.value:pS(f,T,t,S))+" as "+qS(S.transform.column.to?S.transform.column.to(A):A)}).join(",")}var J0=Object.entries({values:SJ,in:(...o)=>{let n=SJ(...o);return n==="()"?"(null)":n},select:xS,as:xS,returning:xS,"\\(":xS,update(o,n,T,t,S){return(n.length?n.flat():Object.keys(o)).map((f)=>qS(S.transform.column.to?S.transform.column.to(f):f)+"="+_y("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"("+wy(f,S)+")values"+yJ(Array.isArray(o)?o:[o],T,t,f,S)}}).map(([o,n])=>[new RegExp("((?:^|[\\s(])"+o+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),n]);function ky(){throw Lo.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}var{serializers:k0,parsers:R0}=fJ;function AJ(o){if(Array.isArray(o))return AJ(o[0]);return typeof o==="string"?1009:0}var MJ=function(o){let n=FJ(o||{});return{serializers:Object.assign({},k0,n.serializers),parsers:Object.assign({},R0,n.parsers)}};function FJ(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 wy(o,{transform:{column:n}}){return o.map((T)=>qS(n.to?n.to(T):T)).join(",")}var qS=function o(n){return'"'+n.replace(/"/g,'""').replace(/\./g,'"."')+'"'},cS=function o(n){return n instanceof hn?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},W0=/\\/g,O0=/"/g;function _0(o){return o.replace(W0,"\\\\").replace(O0,"\\\"")}var $J=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":'"'+_0(T?T(A.type?A.value:A):""+A)+'"'}).join(y)+"}"},Ry={i:0,char:null,str:"",quoted:!1,last:0},JJ=function o(n,T,t){return Ry.i=Ry.last=0,kJ(Ry,n,T,t)};function kJ(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(kJ(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 wT=(o)=>{let n=o[0];for(let T=1;T<o.length;T++)n+=o[T]==="_"?o[++T].toUpperCase():o[T];return n},KT=(o)=>{let n=o[0].toUpperCase();for(let T=1;T<o.length;T++)n+=o[T]==="_"?o[++T].toUpperCase():o[T];return n},XT=(o)=>o.replace(/_/g,"-"),Nt=(o)=>o.replace(/([A-Z])/g,"_$1").toLowerCase(),bt=(o)=>(o.slice(0,1)+o.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),ht=(o)=>o.replace(/-/g,"_");function Ky(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}}wT.column={from:wT};wT.value={from:Ky(wT)};Nt.column={to:Nt};var Xy={...wT};Xy.column.to=Nt;KT.column={from:KT};KT.value={from:Ky(KT)};bt.column={to:bt};var Ey={...KT};Ey.column.to=bt;XT.column={from:XT};XT.value={from:Ky(XT)};ht.column={to:ht};var Yy={...XT};Yy.column.to=ht;import RJ from"net";import E0 from"tls";import ct from"crypto";import Gy from"stream";import{performance as WJ}from"perf_hooks";class ET 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 Rn=w0;function w0(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 uo=Buffer.allocUnsafe(256),K0="BCcDdEFfHPpQSX".split("").reduce((o,n)=>{let T=n.charCodeAt(0);return o[n]=()=>{return uo[0]=T,ko.i=5,ko},o},{}),ko=Object.assign(X0,K0,{N:String.fromCharCode(0),i:0,inc(o){return ko.i+=o,ko},str(o){let n=Buffer.byteLength(o);return ZS(n),ko.i+=uo.write(o,ko.i,n,"utf8"),ko},i16(o){return ZS(2),uo.writeUInt16BE(o,ko.i),ko.i+=2,ko},i32(o,n){if(n||n===0)return uo.writeUInt32BE(o,n),ko;return ZS(4),uo.writeUInt32BE(o,ko.i),ko.i+=4,ko},z(o){return ZS(o),uo.fill(0,ko.i,ko.i+o),ko.i+=o,ko},raw(o){return uo=Buffer.concat([uo.subarray(0,ko.i),o]),ko.i=uo.length,ko},end(o=1){uo.writeUInt32BE(ko.i-o,o);let n=uo.subarray(0,ko.i);return ko.i=0,uo=Buffer.allocUnsafe(256),n}}),P=ko;function ZS(o){if(uo.length-ko.i<o){let n=uo,T=n.length;uo=Buffer.allocUnsafe(T+(T>>1)+o),n.copy(uo)}}function X0(){return ko.i=0,ko}var my=wJ,Y0=1,FT=P().S().end(),OJ=P().H().end(),G0=P().i32(8).i32(80877103).end(8),z0=Buffer.concat([P().E().str(P.N).i32(0).end(),FT]),H0=P().D().str("S").str(P.N).end(),aT=()=>{},m0=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),Q0={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 wJ(o,n={},{onopen:T=aT,onend:t=aT,onclose:S=aT}={}){let{ssl:f,max:y,user:A,host:M,port:F,database:$,parsers:W,transform:O,onnotice:G,onnotify:D,onparameter:z,max_pipeline:Y,keep_alive:B,backoff:p,target_session_attrs:c}=o,a=Rn(),E=Y0++,K={pid:null,secret:null},Q=Hy(Sf,o.idle_timeout),x=Hy(Sf,o.max_lifetime),h=Hy(xJ,o.connect_timeout),w=null,v,N=new ET,q=Buffer.alloc(0),Jo=o.fetch_types,Oo={},Sn={},xn=Math.random().toString(36).slice(2),H=1,Z=0,Fo=0,zo=0,Io=0,To=0,_o=0,Co=0,mo=null,Ko=null,po=!1,wo=null,En=null,qo=null,dn=null,jo=null,Xo=null,Yn=null,Ln=null,C=null,Tt=null,Zo={queue:n.closed,idleTimer:Q,connect(J){qo=J||!0,ay()},terminate:St,execute:tt,cancel:rJ,end:Sf,count:0,id:E};return n.closed&&n.closed.push(Zo),Zo;async function jJ(){let J;try{J=o.socket?await Promise.resolve(o.socket(o)):new RJ.Socket}catch(_){HT(_);return}return J.on("error",HT),J.on("close",sy),J.on("drain",dy),J}async function rJ({pid:J,secret:_},g,$o){try{v=P().i32(16).i32(80877102).i32(J).i32(_).end(16),await uy(),w.once("error",$o),w.once("close",g)}catch(Uo){$o(Uo)}}function tt(J){if(po)return lt(J,Lo.connection("CONNECTION_DESTROYED",o));if(J.cancelled)return;try{return J.state=K,C?a.push(J):(C=J,C.active=!0),hJ(J),xo(NJ(J))&&!J.describeFirst&&!J.cursorFn&&a.length<Y&&(!J.options.onexecute||J.options.onexecute(Zo))}catch(_){return a.length===0&&xo(FT),In(_),!0}}function NJ(J){if(J.parameters.length>=65534)throw Lo.generic("MAX_PARAMETERS_EXCEEDED","Max number of parameters (65534) exceeded");return J.options.simple?P().Q().str(J.statement.string+P.N).end():J.describeFirst?Buffer.concat([gy(J),OJ]):J.prepare?J.prepared?gt(J):Buffer.concat([gy(J),gt(J)]):bJ(J)}function gy(J){return Buffer.concat([nA(J.statement.string,J.parameters,J.statement.types,J.statement.name),zk("S",J.statement.name)])}function gt(J){return Buffer.concat([Gk(J.parameters,J.statement.types,J.statement.name,J.cursorName),J.cursorFn?TA("",J.cursorRows):z0])}function bJ(J){return Buffer.concat([nA(J.statement.string,J.parameters,J.statement.types),H0,gt(J)])}function hJ(J){let _=[],g=[],$o=Oy(J,J.strings[0],J.args[0],_,g,o);!J.tagged&&J.args.forEach((Uo)=>pS(Uo,_,g,o)),J.prepare=o.prepare&&("prepare"in J.options?J.options.prepare:!0),J.string=$o,J.signature=J.prepare&&g+$o,J.onlyDescribe&&delete Sn[J.signature],J.parameters=J.parameters||_,J.prepared=J.prepare&&J.signature in Sn,J.describeFirst=J.onlyDescribe||_.length&&!J.prepared,J.statement=J.prepared?Sn[J.signature]:{string:$o,types:g,name:J.prepare?xn+H++:""},typeof o.debug==="function"&&o.debug(E,$o,_,g)}function xo(J,_){if(Xo=Xo?Buffer.concat([Xo,J]):Buffer.from(J),_||Xo.length>=1024)return ly(_);return Ko===null&&(Ko=setImmediate(ly)),!0}function ly(J){let _=w.write(Xo,J);return Ko!==null&&clearImmediate(Ko),Xo=Ko=null,_}function xJ(){In(Lo.connection("CONNECT_TIMEOUT",o,w)),w.destroy()}async function ey(){if(xo(G0),!await new Promise((_)=>w.once("data",(g)=>_(g[0]===83)))&&f==="prefer")return zT();w.removeAllListeners(),w=E0.connect({socket:w,servername:RJ.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",zT),w.on("error",HT),w.on("close",sy),w.on("drain",dy)}function dy(){!C&&T(Zo)}function tf(J){if(wo){if(wo.push(J),Fo-=J.length,Fo>=0)return}q=wo?Buffer.concat(wo,To-Fo):q.length===0?J:Buffer.concat([q,J],q.length+J.length);while(q.length>4){if(To=q.readUInt32BE(1),To>=q.length){Fo=To-q.length,wo=[q];break}try{cJ(q.subarray(0,To+1))}catch(_){C&&(C.cursorFn||C.describeFirst)&&xo(FT),In(_)}q=q.subarray(To+1),Fo=0,wo=null}}async function uy(){if(po=!1,Oo={},w||(w=await jJ()),!w)return;if(h.start(),o.socket)return f?ey():zT();if(w.on("connect",f?ey:zT),o.path)return w.connect(o.path);w.ssl=f,w.connect(F[zo],M[zo]),w.host=M[zo],w.port=F[zo],zo=(zo+1)%F.length}function ay(){setTimeout(uy,Z?Z+_o-WJ.now():0)}function zT(){try{Sn={},Jo=o.fetch_types,xn=Math.random().toString(36).slice(2),H=1,x.start(),w.on("data",tf),B&&w.setKeepAlive&&w.setKeepAlive(!0,1000*B);let J=mk();xo(J)}catch(J){HT(J)}}function HT(J){if(Zo.queue===n.connecting&&o.host[Io+1])return;In(J);while(a.length)lt(a.shift(),J)}function In(J){jo&&(jo.destroy(J),jo=null),C&&lt(C,J),qo&&(lt(qo,J),qo=null)}function lt(J,_){"query"in _||"parameters"in _||Object.defineProperties(_,{stack:{value:_.stack+J.origin.replace(/.*\n/,`
10
10
  `),enumerable:o.debug},query:{value:J.string,enumerable:o.debug},parameters:{value:J.parameters,enumerable:o.debug},args:{value:J.args,enumerable:o.debug},types:{value:J.statement&&J.statement.types,enumerable:o.debug}}),J.reject(_)}function Sf(){return dn||(!Zo.reserved&&t(Zo),!Zo.reserved&&!qo&&!C&&a.length===0?(St(),new Promise((J)=>w&&w.readyState!=="closed"?w.once("close",J):J())):dn=new Promise((J)=>Yn=J))}function St(){if(po=!0,jo||C||qo||a.length)HT(Lo.connection("CONNECTION_DESTROYED",o));if(clearImmediate(Ko),w)w.removeListener("data",tf),w.removeListener("connect",zT),w.readyState==="open"&&w.end(P().X().end());Yn&&(Yn(),dn=Yn=null)}async function sy(J){if(q=Buffer.alloc(0),Fo=0,wo=null,clearImmediate(Ko),w.removeListener("data",tf),w.removeListener("connect",zT),Q.cancel(),x.cancel(),h.cancel(),w.removeAllListeners(),w=null,qo)return ay();!J&&(C||a.length)&&HT(Lo.connection("CONNECTION_CLOSED",o,w)),Z=WJ.now(),J&&o.shared.retries++,_o=(typeof p==="function"?p(o.shared.retries):p)*1000,S(Zo,Lo.connection("CONNECTION_CLOSED",o,w))}function cJ(J,_=J[0]){(_===68?vJ:_===100?Wk:_===65?Mk:_===83?iJ:_===90?pJ:_===67?qJ:_===50?oA:_===49?ZJ:_===116?PJ:_===84?gJ:_===82?lJ:_===110?ok:_===75?nk:_===69?yk:_===115?Fk:_===51?$k:_===71?Jk:_===78?_k:_===72?kk:_===99?Ok:_===73?wk:_===86?Kk:_===118?Xk:_===87?Rk:Ek)(J)}function vJ(J){let _=7,g,$o,Uo,Po=C.isRaw?new Array(C.statement.columns.length):{};for(let ao=0;ao<C.statement.columns.length;ao++)$o=C.statement.columns[ao],g=J.readInt32BE(_),_+=4,Uo=g===-1?null:C.isRaw===!0?J.subarray(_,_+=g):$o.parser===void 0?J.toString("utf8",_,_+=g):$o.parser.array===!0?$o.parser(J.toString("utf8",_+1,_+=g)):$o.parser(J.toString("utf8",_,_+=g)),C.isRaw?Po[ao]=C.isRaw===!0?Uo:O.value.from?O.value.from(Uo,$o):Uo:Po[$o.name]=O.value.from?O.value.from(Uo,$o):Uo;C.forEachFn?C.forEachFn(O.row.from?O.row.from(Po):Po,N):N[Co++]=O.row.from?O.row.from(Po):Po}function iJ(J){let[_,g]=J.toString("utf8",5,J.length-1).split(P.N);if(Oo[_]=g,o.parameters[_]!==g)o.parameters[_]=g,z&&z(_,g)}function pJ(J){if(C&&C.options.simple&&C.resolve(En||N),C=En=null,N=new ET,h.cancel(),qo){if(c){if(!Oo.in_hot_standby||!Oo.default_transaction_read_only)return fk();else if(Sk(c,Oo))return St()}if(Jo)return qo===!0&&(qo=null),Tk();qo!==!0&&tt(qo),o.shared.retries=Io=0,qo=null;return}while(a.length&&(C=a.shift())&&(C.active=!0,C.cancelled))wJ(o).cancel(C.state,C.cancelled.resolve,C.cancelled.reject);if(C)return;Zo.reserved?!Zo.reserved.release&&J[5]===73?dn?St():(Zo.reserved=null,T(Zo)):Zo.reserved():dn?St():T(Zo)}function qJ(J){Co=0;for(let _=J.length-1;_>0;_--){if(J[_]===32&&J[_+1]<58&&N.count===null)N.count=+J.toString("utf8",_+1,J.length-1);if(J[_-1]>=65){N.command=J.toString("utf8",5,_),N.state=K;break}}if(Tt&&(Tt(),Tt=null),N.command==="BEGIN"&&y!==1&&!Zo.reserved)return In(Lo.generic("UNSAFE_TRANSACTION","Only use sql.begin, sql.reserved or max: 1"));if(C.options.simple)return oA();if(C.cursorFn)N.count&&C.cursorFn(N),xo(FT);C.resolve(N)}function ZJ(){C.parsing=!1}function oA(){!N.statement&&(N.statement=C.statement),N.columns=C.statement.columns}function PJ(J){let _=J.readUInt16BE(5);for(let g=0;g<_;++g)!C.statement.types[g]&&(C.statement.types[g]=J.readUInt32BE(7+g*4));C.prepare&&(Sn[C.signature]=C.statement),C.describeFirst&&!C.onlyDescribe&&(xo(gt(C)),C.describeFirst=!1)}function gJ(J){if(N.command)En=En||[N],En.push(N=new ET),N.count=null,C.statement.columns=null;let _=J.readUInt16BE(5),g=7,$o;C.statement.columns=Array(_);for(let Uo=0;Uo<_;++Uo){$o=g;while(J[g++]!==0);let Po=J.readUInt32BE(g),ao=J.readUInt16BE(g+4),un=J.readUInt32BE(g+6);C.statement.columns[Uo]={name:O.column.from?O.column.from(J.toString("utf8",$o,g-1)):J.toString("utf8",$o,g-1),parser:W[un],table:Po,number:ao,type:un},g+=18}if(N.statement=C.statement,C.onlyDescribe)return C.resolve(C.statement),xo(FT)}async function lJ(J,_=J.readUInt32BE(5)){(_===3?eJ:_===5?dJ:_===10?uJ:_===11?aJ:_===12?sJ:_!==0?Yk:aT)(J,_)}async function eJ(){let J=await ff();xo(P().p().str(J).z(1).end())}async function dJ(J){let _="md5"+await _J(Buffer.concat([Buffer.from(await _J(await ff()+A)),J.subarray(9)]));xo(P().p().str(_).z(1).end())}async function uJ(){Ln=(await ct.randomBytes(18)).toString("base64"),P().p().str("SCRAM-SHA-256"+P.N);let J=P.i;xo(P.inc(4).str("n,,n=*,r="+Ln).i32(P.i-J-4,J).end())}async function aJ(J){let _=J.toString("utf8",9).split(",").reduce((ao,un)=>(ao[un[0]]=un.slice(2),ao),{}),g=await ct.pbkdf2Sync(await ff(),Buffer.from(_.s,"base64"),parseInt(_.i),32,"sha256"),$o=await PS(g,"Client Key"),Uo="n=*,r="+Ln+",r="+_.r+",s="+_.s+",i="+_.i+",c=biws,r="+_.r;mo=(await PS(await PS(g,"Server Key"),Uo)).toString("base64");let Po="c=biws,r="+_.r+",p="+U0($o,Buffer.from(await PS(await D0($o),Uo))).toString("base64");xo(P().p().str(Po).end())}function sJ(J){if(J.toString("utf8",9).split(P.N,1)[0].slice(2)===mo)return;In(Lo.generic("SASL_SIGNATURE_MISMATCH","The server did not return the correct signature")),w.destroy()}function ff(){return Promise.resolve(typeof o.pass==="function"?o.pass():o.pass)}function ok(){if(N.statement=C.statement,N.statement.columns=[],C.onlyDescribe)return C.resolve(C.statement),xo(FT)}function nk(J){K.pid=J.readUInt32BE(5),K.secret=J.readUInt32BE(9)}async function Tk(){Jo=!1,(await new Xn([`
11
11
  select b.oid, b.typarray
12
12
  from pg_catalog.pg_type a
@@ -33,4 +33,4 @@ ${y.trace}`:"No previous disposal trace was found.");return}switch(T.type){case"
33
33
  hash text NOT NULL,
34
34
  created_at bigint
35
35
  )
36
- `;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 $ of F.sql)await M.execute(R.raw($));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[I.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,from:f,joins:y}){let A=this.buildWithCTE(S),M=o[vo.Symbol.Name],F=o[vo.Symbol.Schema],$=o[vo.Symbol.OriginalName],W=M===$?void 0:M,O=R`${F?R`${R.identifier(F)}.`:void 0}${R.identifier($)}${W&&R` ${R.identifier(W)}`}`,G=this.buildUpdateSet(o,n),D=f&&R.join([R.raw(" from "),this.buildFromTable(f)]),z=this.buildJoins(y),Y=t?R` returning ${this.buildSelection(t,{isSingleTable:!f})}`:void 0,B=T?R` where ${T}`:void 0;return R`${A}update ${O} set ${G}${D}${z}${B}${Y}`}buildSelection(o,{isSingleTable:n=!1}={}){let T=o.length,t=o.flatMap(({field:S},f)=>{let y=[];if(X(S,j.Aliased)&&S.isSelectionField)y.push(R.identifier(S.fieldAlias));else if(X(S,j.Aliased)||X(S,j)){let A=X(S,j.Aliased)?S.sql:S;if(n)y.push(new j(A.queryChunks.map((M)=>{if(X(M,V))return R.identifier(this.casing.getColumnCasing(M));return M})));else y.push(A);if(X(S,j.Aliased))y.push(R` as ${R.identifier(S.fieldAlias)}`)}else if(X(S,Ro))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)}buildJoins(o){if(!o||o.length===0)return;let n=[];for(let[T,t]of o.entries()){if(T===0)n.push(R` `);let S=t.table,f=t.lateral?R` lateral`:void 0;if(X(S,vo)){let y=S[vo.Symbol.Name],A=S[vo.Symbol.Schema],M=S[vo.Symbol.OriginalName],F=y===M?void 0:t.alias;n.push(R`${R.raw(t.joinType)} join${f} ${A?R`${R.identifier(A)}.`:void 0}${R.identifier(M)}${F&&R` ${R.identifier(F)}`} on ${t.on}`)}else if(X(S,An)){let y=S[Yo].name,A=S[Yo].schema,M=S[Yo].originalName,F=y===M?void 0:t.alias;n.push(R`${R.raw(t.joinType)} join${f} ${A?R`${R.identifier(A)}.`:void 0}${R.identifier(M)}${F&&R` ${R.identifier(F)}`} on ${t.on}`)}else n.push(R`${R.raw(t.joinType)} join${f} ${S} on ${t.on}`);if(T<o.length-1)n.push(R` `)}return R.join(n)}buildFromTable(o){if(X(o,I)&&o[I.Symbol.OriginalName]!==o[I.Symbol.Name]){let n=R`${R.identifier(o[I.Symbol.OriginalName])}`;if(o[I.Symbol.Schema])n=R`${R.identifier(o[I.Symbol.Schema])}.${n}`;return R`${n} ${R.identifier(o[I.Symbol.Name])}`}return o}buildSelectQuery({withList:o,fields:n,fieldsFlat:T,where:t,having:S,table:f,joins:y,orderBy:A,groupBy:M,limit:F,offset:$,lockingClause:W,distinct:O,setOperators:G}){let D=T??wn(n);for(let q of D)if(X(q.field,Ro)&&_n(q.field.table)!==(X(f,bo)?f._.alias:X(f,vt)?f[Yo].name:X(f,j)?void 0:_n(f))&&!((Jo)=>y?.some(({alias:Oo})=>Oo===(Jo[I.Symbol.IsAlias]?_n(Jo):Jo[I.Symbol.BaseName])))(q.field.table)){let Jo=_n(q.field.table);throw new Error(`Your "${q.path.join("->")}" field references a column "${Jo}"."${q.field.name}", but the table "${Jo}" is not part of the query! Did you forget to join it?`)}let z=!y||y.length===0,Y=this.buildWithCTE(o),B;if(O)B=O===!0?R` distinct`:R` distinct on (${R.join(O.on,R`, `)})`;let p=this.buildSelection(D,{isSingleTable:z}),c=this.buildFromTable(f),a=this.buildJoins(y),E=t?R` where ${t}`:void 0,K=S?R` having ${S}`:void 0,Q;if(A&&A.length>0)Q=R` order by ${R.join(A,R`, `)}`;let x;if(M&&M.length>0)x=R` group by ${R.join(M,R`, `)}`;let h=typeof F==="object"||typeof F==="number"&&F>=0?R` limit ${F}`:void 0,w=$?R` offset ${$}`:void 0,v=R.empty();if(W){let q=R` for ${R.raw(W.strength)}`;if(W.config.of)q.append(R` of ${R.join(Array.isArray(W.config.of)?W.config.of:[W.config.of],R`, `)}`);if(W.config.noWait)q.append(R` no wait`);else if(W.config.skipLocked)q.append(R` skip locked`);v.append(q)}let N=R`${Y}select${B} ${p} from ${c}${a}${E}${x}${K}${Q}${h}${w}${v}`;if(G.length>0)return this.buildSetOperations(N,G);return N}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 G=[];for(let D of f)if(X(D,V))G.push(R.identifier(D.name));else if(X(D,j)){for(let z=0;z<D.queryChunks.length;z++){let Y=D.queryChunks[z];if(X(Y,V))D.queryChunks[z]=R.identifier(Y.name)}G.push(R`${D}`)}else G.push(R`${D}`);F=R` order by ${R.join(G,R`, `)} `}let $=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}${$}${O}`}buildInsertQuery({table:o,values:n,onConflict:T,returning:t,withList:S,select:f,overridingSystemValue_:y}){let A=[],M=o[I.Symbol.Columns],F=Object.entries(M).filter(([Y,B])=>!B.shouldDisableInsert()),$=F.map(([,Y])=>R.identifier(this.casing.getColumnCasing(Y)));if(f){let Y=n;if(X(Y,j))A.push(Y);else A.push(Y.getSQL())}else{let Y=n;A.push(R.raw("values "));for(let[B,p]of Y.entries()){let c=[];for(let[a,E]of F){let K=p[a];if(K===void 0||X(K,$n)&&K.value===void 0)if(E.defaultFn!==void 0){let Q=E.defaultFn(),x=X(Q,j)?Q:R.param(Q,E);c.push(x)}else if(!E.default&&E.onUpdateFn!==void 0){let Q=E.onUpdateFn(),x=X(Q,j)?Q:R.param(Q,E);c.push(x)}else c.push(R`default`);else c.push(K)}if(A.push(c),B<Y.length-1)A.push(R`, `)}}let W=this.buildWithCTE(S),O=R.join(A),G=t?R` returning ${this.buildSelection(t,{isSingleTable:!0})}`:void 0,D=T?R` on conflict ${T}`:void 0,z=y===!0?R`overriding system value `:void 0;return R`${W}insert into ${o} ${$} ${z}${O}${D}${G}`}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,QS)||X(o,mS))return"json";else if(X(o,DS))return"decimal";else if(X(o,US))return"time";else if(X(o,VS)||X(o,BS))return"timestamp";else if(X(o,GS)||X(o,zS))return"date";else if(X(o,CS))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=[],$,W,O=[],G,D=[];if(f===!0)F=Object.entries(S.columns).map(([B,p])=>({dbKey:p.name,tsKey:B,field:rn(p,y),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let Y=Object.fromEntries(Object.entries(S.columns).map(([K,Q])=>[K,rn(Q,y)]));if(f.where){let K=typeof f.where==="function"?f.where(Y,I$()):f.where;G=K&&Et(K,y)}let B=[],p=[];if(f.columns){let K=!1;for(let[Q,x]of Object.entries(f.columns)){if(x===void 0)continue;if(Q in S.columns){if(!K&&x===!0)K=!0;p.push(Q)}}if(p.length>0)p=K?p.filter((Q)=>f.columns?.[Q]===!0):Object.keys(S.columns).filter((Q)=>!p.includes(Q))}else p=Object.keys(S.columns);for(let K of p){let Q=S.columns[K];B.push({tsKey:K,value:Q})}let c=[];if(f.with)c=Object.entries(f.with).filter((K)=>!!K[1]).map(([K,Q])=>({tsKey:K,queryConfig:Q,relation:S.relations[K]}));let a;if(f.extras){a=typeof f.extras==="function"?f.extras(Y,{sql:R}):f.extras;for(let[K,Q]of Object.entries(a))B.push({tsKey:K,value:uf(Q,y)})}for(let{tsKey:K,value:Q}of B)F.push({dbKey:X(Q,j.Aliased)?Q.fieldAlias:S.columns[K].name,tsKey:K,field:X(Q,Ro)?rn(Q,y):Q,relationTableTsKey:void 0,isJson:!1,selection:[]});let E=typeof f.orderBy==="function"?f.orderBy(Y,j$()):f.orderBy??[];if(!Array.isArray(E))E=[E];O=E.map((K)=>{if(X(K,Ro))return rn(K,y);return Et(K,y)}),$=f.limit,W=f.offset;for(let{tsKey:K,queryConfig:Q,relation:x}of c){let h=N$(n,T,x),w=JT(x.referencedTable),v=T[w],N=`${y}_${K}`,q=Yt(...h.fields.map((Sn,xn)=>jT(rn(h.references[xn],N),rn(Sn,y)))),Jo=this.buildRelationalQueryWithoutPK({fullSchema:o,schema:n,tableNamesMap:T,table:o[v],tableConfig:n[v],queryConfig:X(x,ST)?Q===!0?{limit:1}:{...Q,limit:1}:Q,tableAlias:N,joinOn:q,nestedQueryRelation:x}),Oo=R`${R.identifier(N)}.${R.identifier("data")}`.as(K);D.push({on:R`true`,table:new bo(Jo.sql,{},N),alias:N,joinType:"left",lateral:!0}),F.push({dbKey:K,tsKey:K,field:Oo,relationTableTsKey:v,isJson:!0,selection:Jo.selection})}}if(F.length===0)throw new ES({message:`No fields selected for table "${S.tsName}" ("${y}")`});let z;if(G=Yt(M,G),A){let Y=R`json_build_array(${R.join(F.map(({field:c,tsKey:a,isJson:E})=>E?R`${R.identifier(`${y}_${a}`)}.${R.identifier("data")}`:X(c,j.Aliased)?c.sql:c),R`, `)})`;if(X(A,mt))Y=R`coalesce(json_agg(${Y}${O.length>0?R` order by ${R.join(O,R`, `)}`:void 0}), '[]'::json)`;let B=[{dbKey:"data",tsKey:"data",field:Y.as("data"),isJson:!0,relationTableTsKey:S.tsName,selection:F}];if($!==void 0||W!==void 0||O.length>0)z=this.buildSelectQuery({table:XS(t,y),fields:{},fieldsFlat:[{path:[],field:R.raw("*")}],where:G,limit:$,offset:W,orderBy:O,setOperators:[]}),G=void 0,$=void 0,W=void 0,O=[];else z=XS(t,y);z=this.buildSelectQuery({table:X(z,vo)?z:new bo(z,{},y),fields:{},fieldsFlat:B.map(({field:c})=>({path:[],field:X(c,Ro)?rn(c,y):c})),joins:D,where:G,limit:$,offset:W,orderBy:O,setOperators:[]})}else z=this.buildSelectQuery({table:XS(t,y),fields:{},fieldsFlat:F.map(({field:Y})=>({path:[],field:X(Y,Ro)?rn(Y,y):Y})),joins:D,where:G,limit:$,offset:W,orderBy:O,setOperators:[]});return{tableTsKey:S.tsName,sql:z,selection:F}}}class io{static[k]="SelectionProxyHandler";config;constructor(o){this.config={...o}}get(o,n){if(n==="_")return{...o._,selectedFields:new Proxy(o._.selectedFields,this)};if(n===Yo)return{...o[Yo],selectedFields:new Proxy(o[Yo].selectedFields,this)};if(typeof n==="symbol")return o[n];let t=(X(o,bo)?o._.selectedFields:X(o,An)?o[Yo].selectedFields:o)[n];if(X(t,j.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!t.isSelectionField)return t.sql;let S=t.clone();return S.isSelectionField=!0,S}if(X(t,j)){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,Ro)){if(this.config.alias)return new Proxy(t,new IT(new Proxy(t.table,new Xt(this.config.alias,this.config.replaceOriginalName??!1))));return t}if(typeof t!=="object"||t===null)return t;return new Proxy(t,new io(this.config))}}class Vy{static[k]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class Tn{static[k]="PgSelectBuilder";fields;session;dialect;withList=[];distinct;constructor(o){if(this.fields=o.fields,this.session=o.session,this.dialect=o.dialect,o.withList)this.withList=o.withList;this.distinct=o.distinct}authToken;setToken(o){return this.authToken=o,this}from(o){let n=!!this.fields,T;if(this.fields)T=this.fields;else if(X(o,bo))T=Object.fromEntries(Object.keys(o._.selectedFields).map((t)=>[t,o[t]]));else if(X(o,vt))T=o[Yo].selectedFields;else if(X(o,j))T={};else T=bM(o);return new By({table:o,fields:T,isPartialSelect:n,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}}class EJ extends Vy{static[k]="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=Zn(o),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}createJoin(o){return(n,T)=>{let t=this.tableName,S=Zn(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,j)){let f=X(n,bo)?n._.selectedFields:X(n,An)?n[Yo].selectedFields:n[I.Symbol.Columns];this.config.fields[S]=f}}if(typeof T==="function")T=T(new Proxy(this.config.fields,new io({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(q0()):T;if(!Gt(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 io({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=o,this}having(o){if(typeof o==="function")o=o(new Proxy(this.config.fields,new io({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 io({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 io({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 bo(this.getSQL(),this.config.fields,o),new io({alias:o,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new io({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}}class By extends EJ{static[k]="PgSelect";_prepare(o){let{session:n,config:T,dialect:t,joinsNotNullableMap:S,authToken:f}=this;if(!n)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");return Wo.startActiveSpan("drizzle.prepareQuery",()=>{let y=wn(T.fields),A=n.prepareQuery(t.sqlToQuery(this.getSQL()),y,o,!0);return A.joinsNotNullableMap=S,A.setToken(f)})}prepare(o){return this._prepare(o)}authToken;setToken(o){return this.authToken=o,this}execute=(o)=>{return Wo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(o,this.authToken)})}}NM(By,[on]);function ot(o,n){return(T,t,...S)=>{let f=[t,...S].map((y)=>({type:o,isAll:n,rightSelect:y}));for(let y of f)if(!Gt(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 q0=()=>({union:Z0,unionAll:P0,intersect:g0,intersectAll:l0,except:e0,exceptAll:d0}),Z0=ot("union",!1),P0=ot("union",!0),g0=ot("intersect",!1),l0=ot("intersect",!0),e0=ot("except",!1),d0=ot("except",!0);class it{static[k]="PgQueryBuilder";dialect;dialectConfig;constructor(o){this.dialect=X(o,YT)?o:void 0,this.dialectConfig=X(o,YT)?void 0:o}$with(o){let n=this;return{as(T){if(typeof T==="function")T=T(n);return new Proxy(new Kt(T.getSQL(),T.getSelectedFields(),o,!0),new io({alias:o,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}}with(...o){let n=this;function T(f){return new Tn({fields:f??void 0,session:void 0,dialect:n.getDialect(),withList:o})}function t(f){return new Tn({fields:f??void 0,session:void 0,dialect:n.getDialect(),distinct:!0})}function S(f,y){return new Tn({fields:y??void 0,session:void 0,dialect:n.getDialect(),distinct:{on:f}})}return{select:T,selectDistinct:t,selectDistinctOn:S}}select(o){return new Tn({fields:o??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(o){return new Tn({fields:o??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(o,n){return new Tn({fields:n??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:o}})}getDialect(){if(!this.dialect)this.dialect=new YT(this.dialectConfig);return this.dialect}}class dS{constructor(o,n,T,t,S){this.table=o,this.session=n,this.dialect=T,this.withList=t,this.overridingSystemValue_=S}static[k]="PgInsertBuilder";authToken;setToken(o){return this.authToken=o,this}overridingSystemValue(){return this.overridingSystemValue_=!0,this}values(o){if(o=Array.isArray(o)?o:[o],o.length===0)throw new Error("values() must be called with at least one value");let n=o.map((T)=>{let t={},S=this.table[I.Symbol.Columns];for(let f of Object.keys(T)){let y=T[f];t[f]=X(y,j)?y:new $n(y,S[f])}return t});return new Cy(this.table,n,this.session,this.dialect,this.withList,!1,this.overridingSystemValue_).setToken(this.authToken)}select(o){let n=typeof o==="function"?o(new it):o;if(!X(n,j)&&!Gt(this.table[_S],n._.selectedFields))throw new Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");return new Cy(this.table,n,this.session,this.dialect,this.withList,!0)}}class Cy extends on{constructor(o,n,T,t,S,f,y){super();this.session=T,this.dialect=t,this.config={table:o,values:n,withList:S,select:f,overridingSystemValue_:y}}static[k]="PgInsert";config;returning(o=this.config.table[I.Symbol.Columns]){return this.config.returning=wn(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,YS(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 Wo.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,o,!0)})}prepare(o){return this._prepare(o)}authToken;setToken(o){return this.authToken=o,this}execute=(o)=>{return Wo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(o,this.authToken)})};$dynamic(){return this}}class Ly extends on{constructor(o,n,T){super();this.session=n,this.dialect=T,this.config={view:o}}static[k]="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 Wo.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),void 0,o,!0)})}prepare(o){return this._prepare(o)}authToken;setToken(o){return this.authToken=o,this}execute=(o)=>{return Wo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(o,this.authToken)})}}class uS{constructor(o,n,T,t){this.table=o,this.session=n,this.dialect=T,this.withList=t}static[k]="PgUpdateBuilder";authToken;setToken(o){return this.authToken=o,this}set(o){return new YJ(this.table,YS(this.table,o),this.session,this.dialect,this.withList).setToken(this.authToken)}}class YJ extends on{constructor(o,n,T,t,S){super();this.session=T,this.dialect=t,this.config={set:n,table:o,withList:S,joins:[]},this.tableName=Zn(o),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}static[k]="PgUpdate";config;tableName;joinsNotNullableMap;from(o){let n=Zn(o);if(typeof n==="string")this.joinsNotNullableMap[n]=!0;return this.config.from=o,this}getTableLikeFields(o){if(X(o,vo))return o[I.Symbol.Columns];else if(X(o,bo))return o._.selectedFields;return o[Yo].selectedFields}createJoin(o){return(n,T)=>{let t=Zn(n);if(typeof t==="string"&&this.config.joins.some((S)=>S.alias===t))throw new Error(`Alias "${t}" is already used in this query`);if(typeof T==="function"){let S=this.config.from&&!X(this.config.from,j)?this.getTableLikeFields(this.config.from):void 0;T=T(new Proxy(this.config.table[I.Symbol.Columns],new io({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),S&&new Proxy(S,new io({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}if(this.config.joins.push({on:T,table:n,joinType:o,alias:t}),typeof t==="string")switch(o){case"left":{this.joinsNotNullableMap[t]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([S])=>[S,!1])),this.joinsNotNullableMap[t]=!0;break}case"inner":{this.joinsNotNullableMap[t]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([S])=>[S,!1])),this.joinsNotNullableMap[t]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(o){return this.config.where=o,this}returning(o){if(!o){if(o=Object.assign({},this.config.table[I.Symbol.Columns]),this.config.from){let n=Zn(this.config.from);if(typeof n==="string"&&this.config.from&&!X(this.config.from,j)){let T=this.getTableLikeFields(this.config.from);o[n]=T}for(let T of this.config.joins){let t=Zn(T.table);if(typeof t==="string"&&!X(T.table,j)){let S=this.getTableLikeFields(T.table);o[t]=S}}}}return this.config.returning=wn(o),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:o,...n}=this.dialect.sqlToQuery(this.getSQL());return n}_prepare(o){let n=this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,o,!0);return n.joinsNotNullableMap=this.joinsNotNullableMap,n}prepare(o){return this._prepare(o)}authToken;setToken(o){return this.authToken=o,this}execute=(o)=>{return this._prepare().execute(o,this.authToken)};$dynamic(){return this}}class pt extends j{constructor(o){super(pt.buildEmbeddedCount(o.source,o.filters).queryChunks);this.params=o,this.mapWith(Number),this.session=o.session,this.sql=pt.buildCount(o.source,o.filters)}sql;token;static[k]="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};`}setToken(o){return this.token=o,this}then(o,n){return Promise.resolve(this.session.count(this.sql,this.token)).then(o,n)}catch(o){return this.then(void 0,o)}finally(o){return this.then((n)=>{return o?.(),n},(n)=>{throw o?.(),n})}}class jy{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[k]="PgRelationalQueryBuilder";findMany(o){return new Iy(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,o?o:{},"many")}findFirst(o){return new Iy(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,o?{...o,limit:1}:{limit:1},"first")}}class Iy extends on{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[k]="PgRelationalQuery";_prepare(o){return Wo.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)=>LS(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}authToken;setToken(o){return this.authToken=o,this}execute(){return Wo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(void 0,this.authToken)})}}class ry extends on{constructor(o,n,T,t){super();this.execute=o,this.sql=n,this.query=T,this.mapBatchResult=t}static[k]="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 qt{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 jy(T.fullSchema,this._.schema,this._.tableNamesMap,T.fullSchema[t],S,o,n)}static[k]="PgDatabase";query;$with(o){let n=this;return{as(T){if(typeof T==="function")T=T(new it(n.dialect));return new Proxy(new Kt(T.getSQL(),T.getSelectedFields(),o,!0),new io({alias:o,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}}$count(o,n){return new pt({source:o,filters:n,session:this.session})}with(...o){let n=this;function T(M){return new Tn({fields:M??void 0,session:n.session,dialect:n.dialect,withList:o})}function t(M){return new Tn({fields:M??void 0,session:n.session,dialect:n.dialect,withList:o,distinct:!0})}function S(M,F){return new Tn({fields:F??void 0,session:n.session,dialect:n.dialect,withList:o,distinct:{on:M}})}function f(M){return new uS(M,n.session,n.dialect,o)}function y(M){return new dS(M,n.session,n.dialect,o)}function A(M){return new eS(M,n.session,n.dialect,o)}return{select:T,selectDistinct:t,selectDistinctOn:S,update:f,insert:y,delete:A}}select(o){return new Tn({fields:o??void 0,session:this.session,dialect:this.dialect})}selectDistinct(o){return new Tn({fields:o??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(o,n){return new Tn({fields:n??void 0,session:this.session,dialect:this.dialect,distinct:{on:o}})}update(o){return new uS(o,this.session,this.dialect)}insert(o){return new dS(o,this.session,this.dialect)}delete(o){return new eS(o,this.session,this.dialect)}refreshMaterializedView(o){return new Ly(o,this.session,this.dialect)}authToken;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 ry(()=>t.execute(void 0,this.authToken),n,T,(S)=>t.mapResult(S,!0))}transaction(o,n){return this.session.transaction(o,n)}}class GJ{constructor(o,n){this.unique=o,this.name=n}static[k]="PgIndexBuilderOn";on(...o){return new aS(o.map((n)=>{if(X(n,j))return n;n=n;let T=new wt(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 aS(o.map((n)=>{if(X(n,j))return n;n=n;let T=new wt(n.name,!!n.keyAsName,n.columnType,n.indexConfig);return n.indexConfig=n.defaultConfig,T}),this.unique,!0,this.name)}using(o,...n){return new aS(n.map((T)=>{if(X(T,j))return T;T=T;let t=new wt(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 aS{static[k]="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 zJ(this.config,o)}}class zJ{static[k]="PgIndex";config;constructor(o,n){this.config={...o,table:n}}}function Ny(o){return new GJ(!0,o)}class by{constructor(o){this.query=o}authToken;getQuery(){return this.query}mapResult(o,n){return o}setToken(o){return this.authToken=o,this}static[k]="PgPreparedQuery";joinsNotNullableMap}class hy{constructor(o){this.dialect=o}static[k]="PgSession";execute(o,n){return Wo.startActiveSpan("drizzle.operation",()=>{return Wo.startActiveSpan("drizzle.prepareQuery",()=>{return this.prepareQuery(this.dialect.sqlToQuery(o),void 0,void 0,!1)}).setToken(n).execute(void 0,n)})}all(o){return this.prepareQuery(this.dialect.sqlToQuery(o),void 0,void 0,!1).all()}async count(o,n){let T=await this.execute(o,n);return Number(T[0].count)}}class xy extends qt{constructor(o,n,T,t=0){super(o,n,T);this.schema=T,this.nestedIndex=t}static[k]="PgTransaction";rollback(){throw new af}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 HJ extends by{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[k]="PostgresJsPreparedQuery";async execute(o={}){return Wo.startActiveSpan("drizzle.execute",async(n)=>{let T=df(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 Wo.startActiveSpan("drizzle.driver.execute",()=>{return f.unsafe(S,T)});let M=await Wo.startActiveSpan("drizzle.driver.execute",()=>{return n?.setAttributes({"drizzle.query.text":S,"drizzle.query.params":JSON.stringify(T)}),f.unsafe(S,T).values()});return Wo.startActiveSpan("drizzle.mapResponse",()=>{return A?A(M):M.map((F)=>rM(t,F,y))})})}all(o={}){return Wo.startActiveSpan("drizzle.execute",async(n)=>{let T=df(this.params,o);return n?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(T)}),this.logger.logQuery(this.queryString,T),Wo.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 Zt extends hy{constructor(o,n,T,t={}){super(n);this.client=o,this.schema=T,this.options=t,this.logger=t.logger??new oy}static[k]="PostgresJsSession";logger;prepareQuery(o,n,T,t,S){return new HJ(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 Zt(T,this.dialect,this.schema,this.options),S=new cy(this.dialect,t,this.schema);if(n)await S.setTransaction(n);return o(S)})}}class cy extends xy{constructor(o,n,T,t=0){super(o,n,T,t);this.session=n}static[k]="PostgresJsTransaction";transaction(o){return this.session.client.savepoint((n)=>{let T=new Zt(n,this.dialect,this.schema,this.session.options),t=new cy(this.dialect,T,this.schema);return o(t)})}}class mJ extends qt{static[k]="PostgresJsDatabase"}function nt(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 YT({casing:n.casing}),S;if(n.logger===!0)S=new sf;else if(n.logger!==!1)S=n.logger;let f;if(n.schema){let M=r$(n.schema,b$);f={fullSchema:n.schema,schema:M.tables,tableNamesMap:M.tableNamesMap}}let y=new Zt(o,t,f,{logger:S}),A=new mJ(t,y,f);return A.$client=o,A}function sS(...o){if(typeof o[0]==="string"){let n=sT(o[0]);return nt(n,o[1])}if(hM(o[0])){let{connection:n,client:T,...t}=o[0];if(T)return nt(T,t);if(typeof n==="object"&&n.url!==void 0){let{url:f,...y}=n,A=sT(f,y);return nt(A,t)}let S=sT(n);return nt(S,t)}return nt(o[0],o[1])}((o)=>{function n(T){return nt({options:{parsers:{},serializers:{}}},T)}o.mock=n})(sS||(sS={}));var iy={};Bk(iy,{users:()=>GT,userChanges:()=>a0,untrackedUserColumnNames:()=>u0,twoFactorMethod:()=>BJ,trackedUserColumnName:()=>VJ,trackableUserColumnNames:()=>UJ,role:()=>DJ,players:()=>vy,passwordResetAttempts:()=>oW,loginHistory:()=>s0,games:()=>of,banishedIps:()=>Pt});function QJ(o){return R`lower(${o})`}var DJ=WS("role",["admin","user"]),GT=tT("users",{id:Jn().primaryKey().defaultRandom(),username:co({length:16}).notNull(),email:co({length:254}).notNull(),hash:co({length:64}).notNull(),salt:co({length:36}).notNull(),createdAt:Qn({withTimezone:!0}).notNull().defaultNow(),createdIp:co({length:45}).notNull(),isActive:zt().notNull().default(!1),verifiedAt:Qn({withTimezone:!0}),userRole:DJ().default("user")},(o)=>[Ny("usernameUniqueIndex").on(QJ(o.username)),Ny("emailUniqueIndex").on(QJ(o.email))]),u0=["id","createdAt","createdIp","isActive","salt","verifiedAt"],UJ=["username","email","hash","userRole"],VJ=WS("trackedUserColumnName",UJ),a0=tT("userChanges",{id:Jn().primaryKey().defaultRandom(),userId:Jn().notNull().references(()=>GT.id),changedAt:Qn({withTimezone:!0}).notNull().defaultNow(),changedIp:co({length:45}).notNull(),changedColumn:VJ().notNull(),oldValue:co({length:255}),newValue:co({length:255})}),of=tT("games",{id:Jn().primaryKey().defaultRandom()}),vy=tT("players",{userId:Jn().notNull().references(()=>GT.id),gameId:Jn().notNull().references(()=>of.id),score:HS().notNull()},(o)=>[B$({name:"players_userId_gameId_pk",columns:[o.userId,o.gameId]})]),s0=tT("loginHistory",{id:Jn().primaryKey().defaultRandom(),userId:Jn().references(()=>GT.id),loginTime:Qn({withTimezone:!0}).notNull().defaultNow(),ipAddress:co({length:45}).notNull(),userAgent:co({length:1024}),successful:zt().notNull().default(!1)}),BJ=WS("twoFactorMethod",["email","phone"]),oW=tT("passwordResetAttempts",{id:Jn().primaryKey().defaultRandom(),userId:Jn().notNull().references(()=>GT.id),requestedIp:co({length:45}).notNull(),requestedAt:Qn({withTimezone:!0}).notNull().defaultNow(),succeededIp:co({length:45}),succeededAt:Qn({withTimezone:!0}),verificationMethod:BJ().notNull()}),Pt=tT("banishedIps",{ip:co({length:45}).primaryKey(),reason:co({length:2048}).notNull(),banishedAt:Qn({withTimezone:!0}).notNull().defaultNow(),banishedUntil:Qn({withTimezone:!0})});var __dirname="/home/runner/work/wayforge/wayforge/apps/tempest.games/src/database";class py{options;sql;drizzle;observers=new Map;async setupTriggersAndNotifications(){await this.sql.file(nW.resolve(__dirname,"notify_update.sql"));let o=[_n(GT),_n(of),_n(vy)];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=sT(n),this.drizzle=sS(this.sql,{schema:iy,logger:o})}observe(o,n){if(!this.observers.has(o))this.observers.set(o,new s);this.observers.get(o).subscribe("SINGLETON",n)}}var nf={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"},qy=tA(nf).map(([o])=>Go.literal(Number(o))),TW=Go.union([qy[0],qy[1],...qy]),CJ=Go.tuple([TW,Go.string()]);var Py=new rf,{logger:tn}=Py;Object.assign(console,tn,{log:tn.info});tn.info(" ready");var Zy=IJ(import.meta.dir,"..","app"),yW=new py({logQuery(o,n){tn.info("\uD83D\uDCDD query",o,n)}});fW({hostname:"0.0.0.0",port:Cn.FRONTEND_PORT??3333,...s$??void 0,async fetch(o,n){try{let T=new Date,t=new URL(o.url),S=n.requestIP(o)?.address??"??";tn.info(T,S,o.method,t.pathname);let[f]=await yW.drizzle.select({banishedUntil:Pt.banishedUntil}).from(Pt).where(jT(Pt.ip,S)).limit(1),y=f?.banishedUntil===null,A=f?.banishedUntil&&f.banishedUntil>T;if(y||A)throw tn.info(`\uD83D\uDE45 request from banned ip ${S}`),[403,S];if(t.pathname==="/")return new Response(Bun.file(IJ(Zy,"index.html")));if(t.pathname==="/index.html")return Response.redirect("/");let M=tW(Zy,t.pathname),F=SW(M);if(!F.startsWith(Zy))throw[403,"Access Denied"];if(!await LJ(F).exists())return Response.redirect("/");return new Response(LJ(F))}catch(T){let t=CJ.safeParse(T);if(t.success){let[S,f]=t.data,A=`${nf[S]}. ${f}`;return tn.info(`\u274C ${S}: ${A}`),new Response(A,{status:S})}if(T instanceof Error)tn.error(T.message);else{let S=BT(T);tn.error("frontend server threw",S)}return new Response(nf[500],{status:500})}}});function Tf(){tn.info("\uD83D\uDEEC frontend server exiting"),process.exit(0)}process.on("SIGINT",()=>{tn.info("\u2757 received SIGINT; exiting gracefully"),Tf()});process.on("SIGTERM",()=>{tn.info("\u2757 received SIGTERM; exiting gracefully"),Tf()});process.on("exit",()=>{tn.info("\u2757 received exit; exiting gracefully"),Tf()});Py.on("timeToStop",()=>{tn.info('\u2757 backend server received signal "timeToStop"; exiting gracefully'),Tf()});tn.info(`\uD83D\uDEEB frontend server running at http://localhost:${Cn.FRONTEND_PORT}/`);Py.emit("alive");
36
+ `;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 $ of F.sql)await M.execute(R.raw($));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[I.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,from:f,joins:y}){let A=this.buildWithCTE(S),M=o[vo.Symbol.Name],F=o[vo.Symbol.Schema],$=o[vo.Symbol.OriginalName],W=M===$?void 0:M,O=R`${F?R`${R.identifier(F)}.`:void 0}${R.identifier($)}${W&&R` ${R.identifier(W)}`}`,G=this.buildUpdateSet(o,n),D=f&&R.join([R.raw(" from "),this.buildFromTable(f)]),z=this.buildJoins(y),Y=t?R` returning ${this.buildSelection(t,{isSingleTable:!f})}`:void 0,B=T?R` where ${T}`:void 0;return R`${A}update ${O} set ${G}${D}${z}${B}${Y}`}buildSelection(o,{isSingleTable:n=!1}={}){let T=o.length,t=o.flatMap(({field:S},f)=>{let y=[];if(X(S,j.Aliased)&&S.isSelectionField)y.push(R.identifier(S.fieldAlias));else if(X(S,j.Aliased)||X(S,j)){let A=X(S,j.Aliased)?S.sql:S;if(n)y.push(new j(A.queryChunks.map((M)=>{if(X(M,V))return R.identifier(this.casing.getColumnCasing(M));return M})));else y.push(A);if(X(S,j.Aliased))y.push(R` as ${R.identifier(S.fieldAlias)}`)}else if(X(S,Ro))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)}buildJoins(o){if(!o||o.length===0)return;let n=[];for(let[T,t]of o.entries()){if(T===0)n.push(R` `);let S=t.table,f=t.lateral?R` lateral`:void 0;if(X(S,vo)){let y=S[vo.Symbol.Name],A=S[vo.Symbol.Schema],M=S[vo.Symbol.OriginalName],F=y===M?void 0:t.alias;n.push(R`${R.raw(t.joinType)} join${f} ${A?R`${R.identifier(A)}.`:void 0}${R.identifier(M)}${F&&R` ${R.identifier(F)}`} on ${t.on}`)}else if(X(S,An)){let y=S[Yo].name,A=S[Yo].schema,M=S[Yo].originalName,F=y===M?void 0:t.alias;n.push(R`${R.raw(t.joinType)} join${f} ${A?R`${R.identifier(A)}.`:void 0}${R.identifier(M)}${F&&R` ${R.identifier(F)}`} on ${t.on}`)}else n.push(R`${R.raw(t.joinType)} join${f} ${S} on ${t.on}`);if(T<o.length-1)n.push(R` `)}return R.join(n)}buildFromTable(o){if(X(o,I)&&o[I.Symbol.OriginalName]!==o[I.Symbol.Name]){let n=R`${R.identifier(o[I.Symbol.OriginalName])}`;if(o[I.Symbol.Schema])n=R`${R.identifier(o[I.Symbol.Schema])}.${n}`;return R`${n} ${R.identifier(o[I.Symbol.Name])}`}return o}buildSelectQuery({withList:o,fields:n,fieldsFlat:T,where:t,having:S,table:f,joins:y,orderBy:A,groupBy:M,limit:F,offset:$,lockingClause:W,distinct:O,setOperators:G}){let D=T??wn(n);for(let q of D)if(X(q.field,Ro)&&_n(q.field.table)!==(X(f,bo)?f._.alias:X(f,vt)?f[Yo].name:X(f,j)?void 0:_n(f))&&!((Jo)=>y?.some(({alias:Oo})=>Oo===(Jo[I.Symbol.IsAlias]?_n(Jo):Jo[I.Symbol.BaseName])))(q.field.table)){let Jo=_n(q.field.table);throw new Error(`Your "${q.path.join("->")}" field references a column "${Jo}"."${q.field.name}", but the table "${Jo}" is not part of the query! Did you forget to join it?`)}let z=!y||y.length===0,Y=this.buildWithCTE(o),B;if(O)B=O===!0?R` distinct`:R` distinct on (${R.join(O.on,R`, `)})`;let p=this.buildSelection(D,{isSingleTable:z}),c=this.buildFromTable(f),a=this.buildJoins(y),E=t?R` where ${t}`:void 0,K=S?R` having ${S}`:void 0,Q;if(A&&A.length>0)Q=R` order by ${R.join(A,R`, `)}`;let x;if(M&&M.length>0)x=R` group by ${R.join(M,R`, `)}`;let h=typeof F==="object"||typeof F==="number"&&F>=0?R` limit ${F}`:void 0,w=$?R` offset ${$}`:void 0,v=R.empty();if(W){let q=R` for ${R.raw(W.strength)}`;if(W.config.of)q.append(R` of ${R.join(Array.isArray(W.config.of)?W.config.of:[W.config.of],R`, `)}`);if(W.config.noWait)q.append(R` no wait`);else if(W.config.skipLocked)q.append(R` skip locked`);v.append(q)}let N=R`${Y}select${B} ${p} from ${c}${a}${E}${x}${K}${Q}${h}${w}${v}`;if(G.length>0)return this.buildSetOperations(N,G);return N}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 G=[];for(let D of f)if(X(D,V))G.push(R.identifier(D.name));else if(X(D,j)){for(let z=0;z<D.queryChunks.length;z++){let Y=D.queryChunks[z];if(X(Y,V))D.queryChunks[z]=R.identifier(Y.name)}G.push(R`${D}`)}else G.push(R`${D}`);F=R` order by ${R.join(G,R`, `)} `}let $=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}${$}${O}`}buildInsertQuery({table:o,values:n,onConflict:T,returning:t,withList:S,select:f,overridingSystemValue_:y}){let A=[],M=o[I.Symbol.Columns],F=Object.entries(M).filter(([Y,B])=>!B.shouldDisableInsert()),$=F.map(([,Y])=>R.identifier(this.casing.getColumnCasing(Y)));if(f){let Y=n;if(X(Y,j))A.push(Y);else A.push(Y.getSQL())}else{let Y=n;A.push(R.raw("values "));for(let[B,p]of Y.entries()){let c=[];for(let[a,E]of F){let K=p[a];if(K===void 0||X(K,$n)&&K.value===void 0)if(E.defaultFn!==void 0){let Q=E.defaultFn(),x=X(Q,j)?Q:R.param(Q,E);c.push(x)}else if(!E.default&&E.onUpdateFn!==void 0){let Q=E.onUpdateFn(),x=X(Q,j)?Q:R.param(Q,E);c.push(x)}else c.push(R`default`);else c.push(K)}if(A.push(c),B<Y.length-1)A.push(R`, `)}}let W=this.buildWithCTE(S),O=R.join(A),G=t?R` returning ${this.buildSelection(t,{isSingleTable:!0})}`:void 0,D=T?R` on conflict ${T}`:void 0,z=y===!0?R`overriding system value `:void 0;return R`${W}insert into ${o} ${$} ${z}${O}${D}${G}`}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,QS)||X(o,mS))return"json";else if(X(o,DS))return"decimal";else if(X(o,US))return"time";else if(X(o,VS)||X(o,BS))return"timestamp";else if(X(o,GS)||X(o,zS))return"date";else if(X(o,CS))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=[],$,W,O=[],G,D=[];if(f===!0)F=Object.entries(S.columns).map(([B,p])=>({dbKey:p.name,tsKey:B,field:rn(p,y),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let Y=Object.fromEntries(Object.entries(S.columns).map(([K,Q])=>[K,rn(Q,y)]));if(f.where){let K=typeof f.where==="function"?f.where(Y,I$()):f.where;G=K&&Et(K,y)}let B=[],p=[];if(f.columns){let K=!1;for(let[Q,x]of Object.entries(f.columns)){if(x===void 0)continue;if(Q in S.columns){if(!K&&x===!0)K=!0;p.push(Q)}}if(p.length>0)p=K?p.filter((Q)=>f.columns?.[Q]===!0):Object.keys(S.columns).filter((Q)=>!p.includes(Q))}else p=Object.keys(S.columns);for(let K of p){let Q=S.columns[K];B.push({tsKey:K,value:Q})}let c=[];if(f.with)c=Object.entries(f.with).filter((K)=>!!K[1]).map(([K,Q])=>({tsKey:K,queryConfig:Q,relation:S.relations[K]}));let a;if(f.extras){a=typeof f.extras==="function"?f.extras(Y,{sql:R}):f.extras;for(let[K,Q]of Object.entries(a))B.push({tsKey:K,value:uf(Q,y)})}for(let{tsKey:K,value:Q}of B)F.push({dbKey:X(Q,j.Aliased)?Q.fieldAlias:S.columns[K].name,tsKey:K,field:X(Q,Ro)?rn(Q,y):Q,relationTableTsKey:void 0,isJson:!1,selection:[]});let E=typeof f.orderBy==="function"?f.orderBy(Y,j$()):f.orderBy??[];if(!Array.isArray(E))E=[E];O=E.map((K)=>{if(X(K,Ro))return rn(K,y);return Et(K,y)}),$=f.limit,W=f.offset;for(let{tsKey:K,queryConfig:Q,relation:x}of c){let h=N$(n,T,x),w=JT(x.referencedTable),v=T[w],N=`${y}_${K}`,q=Yt(...h.fields.map((Sn,xn)=>jT(rn(h.references[xn],N),rn(Sn,y)))),Jo=this.buildRelationalQueryWithoutPK({fullSchema:o,schema:n,tableNamesMap:T,table:o[v],tableConfig:n[v],queryConfig:X(x,ST)?Q===!0?{limit:1}:{...Q,limit:1}:Q,tableAlias:N,joinOn:q,nestedQueryRelation:x}),Oo=R`${R.identifier(N)}.${R.identifier("data")}`.as(K);D.push({on:R`true`,table:new bo(Jo.sql,{},N),alias:N,joinType:"left",lateral:!0}),F.push({dbKey:K,tsKey:K,field:Oo,relationTableTsKey:v,isJson:!0,selection:Jo.selection})}}if(F.length===0)throw new ES({message:`No fields selected for table "${S.tsName}" ("${y}")`});let z;if(G=Yt(M,G),A){let Y=R`json_build_array(${R.join(F.map(({field:c,tsKey:a,isJson:E})=>E?R`${R.identifier(`${y}_${a}`)}.${R.identifier("data")}`:X(c,j.Aliased)?c.sql:c),R`, `)})`;if(X(A,mt))Y=R`coalesce(json_agg(${Y}${O.length>0?R` order by ${R.join(O,R`, `)}`:void 0}), '[]'::json)`;let B=[{dbKey:"data",tsKey:"data",field:Y.as("data"),isJson:!0,relationTableTsKey:S.tsName,selection:F}];if($!==void 0||W!==void 0||O.length>0)z=this.buildSelectQuery({table:XS(t,y),fields:{},fieldsFlat:[{path:[],field:R.raw("*")}],where:G,limit:$,offset:W,orderBy:O,setOperators:[]}),G=void 0,$=void 0,W=void 0,O=[];else z=XS(t,y);z=this.buildSelectQuery({table:X(z,vo)?z:new bo(z,{},y),fields:{},fieldsFlat:B.map(({field:c})=>({path:[],field:X(c,Ro)?rn(c,y):c})),joins:D,where:G,limit:$,offset:W,orderBy:O,setOperators:[]})}else z=this.buildSelectQuery({table:XS(t,y),fields:{},fieldsFlat:F.map(({field:Y})=>({path:[],field:X(Y,Ro)?rn(Y,y):Y})),joins:D,where:G,limit:$,offset:W,orderBy:O,setOperators:[]});return{tableTsKey:S.tsName,sql:z,selection:F}}}class io{static[k]="SelectionProxyHandler";config;constructor(o){this.config={...o}}get(o,n){if(n==="_")return{...o._,selectedFields:new Proxy(o._.selectedFields,this)};if(n===Yo)return{...o[Yo],selectedFields:new Proxy(o[Yo].selectedFields,this)};if(typeof n==="symbol")return o[n];let t=(X(o,bo)?o._.selectedFields:X(o,An)?o[Yo].selectedFields:o)[n];if(X(t,j.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!t.isSelectionField)return t.sql;let S=t.clone();return S.isSelectionField=!0,S}if(X(t,j)){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,Ro)){if(this.config.alias)return new Proxy(t,new IT(new Proxy(t.table,new Xt(this.config.alias,this.config.replaceOriginalName??!1))));return t}if(typeof t!=="object"||t===null)return t;return new Proxy(t,new io(this.config))}}class Vy{static[k]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class Tn{static[k]="PgSelectBuilder";fields;session;dialect;withList=[];distinct;constructor(o){if(this.fields=o.fields,this.session=o.session,this.dialect=o.dialect,o.withList)this.withList=o.withList;this.distinct=o.distinct}authToken;setToken(o){return this.authToken=o,this}from(o){let n=!!this.fields,T;if(this.fields)T=this.fields;else if(X(o,bo))T=Object.fromEntries(Object.keys(o._.selectedFields).map((t)=>[t,o[t]]));else if(X(o,vt))T=o[Yo].selectedFields;else if(X(o,j))T={};else T=bM(o);return new By({table:o,fields:T,isPartialSelect:n,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}}class EJ extends Vy{static[k]="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=Zn(o),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}createJoin(o){return(n,T)=>{let t=this.tableName,S=Zn(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,j)){let f=X(n,bo)?n._.selectedFields:X(n,An)?n[Yo].selectedFields:n[I.Symbol.Columns];this.config.fields[S]=f}}if(typeof T==="function")T=T(new Proxy(this.config.fields,new io({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(q0()):T;if(!Gt(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 io({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=o,this}having(o){if(typeof o==="function")o=o(new Proxy(this.config.fields,new io({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 io({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 io({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 bo(this.getSQL(),this.config.fields,o),new io({alias:o,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new io({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}}class By extends EJ{static[k]="PgSelect";_prepare(o){let{session:n,config:T,dialect:t,joinsNotNullableMap:S,authToken:f}=this;if(!n)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");return Wo.startActiveSpan("drizzle.prepareQuery",()=>{let y=wn(T.fields),A=n.prepareQuery(t.sqlToQuery(this.getSQL()),y,o,!0);return A.joinsNotNullableMap=S,A.setToken(f)})}prepare(o){return this._prepare(o)}authToken;setToken(o){return this.authToken=o,this}execute=(o)=>{return Wo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(o,this.authToken)})}}NM(By,[on]);function ot(o,n){return(T,t,...S)=>{let f=[t,...S].map((y)=>({type:o,isAll:n,rightSelect:y}));for(let y of f)if(!Gt(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 q0=()=>({union:Z0,unionAll:P0,intersect:g0,intersectAll:l0,except:e0,exceptAll:d0}),Z0=ot("union",!1),P0=ot("union",!0),g0=ot("intersect",!1),l0=ot("intersect",!0),e0=ot("except",!1),d0=ot("except",!0);class it{static[k]="PgQueryBuilder";dialect;dialectConfig;constructor(o){this.dialect=X(o,YT)?o:void 0,this.dialectConfig=X(o,YT)?void 0:o}$with(o){let n=this;return{as(T){if(typeof T==="function")T=T(n);return new Proxy(new Kt(T.getSQL(),T.getSelectedFields(),o,!0),new io({alias:o,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}}with(...o){let n=this;function T(f){return new Tn({fields:f??void 0,session:void 0,dialect:n.getDialect(),withList:o})}function t(f){return new Tn({fields:f??void 0,session:void 0,dialect:n.getDialect(),distinct:!0})}function S(f,y){return new Tn({fields:y??void 0,session:void 0,dialect:n.getDialect(),distinct:{on:f}})}return{select:T,selectDistinct:t,selectDistinctOn:S}}select(o){return new Tn({fields:o??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(o){return new Tn({fields:o??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(o,n){return new Tn({fields:n??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:o}})}getDialect(){if(!this.dialect)this.dialect=new YT(this.dialectConfig);return this.dialect}}class dS{constructor(o,n,T,t,S){this.table=o,this.session=n,this.dialect=T,this.withList=t,this.overridingSystemValue_=S}static[k]="PgInsertBuilder";authToken;setToken(o){return this.authToken=o,this}overridingSystemValue(){return this.overridingSystemValue_=!0,this}values(o){if(o=Array.isArray(o)?o:[o],o.length===0)throw new Error("values() must be called with at least one value");let n=o.map((T)=>{let t={},S=this.table[I.Symbol.Columns];for(let f of Object.keys(T)){let y=T[f];t[f]=X(y,j)?y:new $n(y,S[f])}return t});return new Cy(this.table,n,this.session,this.dialect,this.withList,!1,this.overridingSystemValue_).setToken(this.authToken)}select(o){let n=typeof o==="function"?o(new it):o;if(!X(n,j)&&!Gt(this.table[_S],n._.selectedFields))throw new Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");return new Cy(this.table,n,this.session,this.dialect,this.withList,!0)}}class Cy extends on{constructor(o,n,T,t,S,f,y){super();this.session=T,this.dialect=t,this.config={table:o,values:n,withList:S,select:f,overridingSystemValue_:y}}static[k]="PgInsert";config;returning(o=this.config.table[I.Symbol.Columns]){return this.config.returning=wn(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,YS(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 Wo.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,o,!0)})}prepare(o){return this._prepare(o)}authToken;setToken(o){return this.authToken=o,this}execute=(o)=>{return Wo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(o,this.authToken)})};$dynamic(){return this}}class Ly extends on{constructor(o,n,T){super();this.session=n,this.dialect=T,this.config={view:o}}static[k]="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 Wo.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),void 0,o,!0)})}prepare(o){return this._prepare(o)}authToken;setToken(o){return this.authToken=o,this}execute=(o)=>{return Wo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(o,this.authToken)})}}class uS{constructor(o,n,T,t){this.table=o,this.session=n,this.dialect=T,this.withList=t}static[k]="PgUpdateBuilder";authToken;setToken(o){return this.authToken=o,this}set(o){return new YJ(this.table,YS(this.table,o),this.session,this.dialect,this.withList).setToken(this.authToken)}}class YJ extends on{constructor(o,n,T,t,S){super();this.session=T,this.dialect=t,this.config={set:n,table:o,withList:S,joins:[]},this.tableName=Zn(o),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}static[k]="PgUpdate";config;tableName;joinsNotNullableMap;from(o){let n=Zn(o);if(typeof n==="string")this.joinsNotNullableMap[n]=!0;return this.config.from=o,this}getTableLikeFields(o){if(X(o,vo))return o[I.Symbol.Columns];else if(X(o,bo))return o._.selectedFields;return o[Yo].selectedFields}createJoin(o){return(n,T)=>{let t=Zn(n);if(typeof t==="string"&&this.config.joins.some((S)=>S.alias===t))throw new Error(`Alias "${t}" is already used in this query`);if(typeof T==="function"){let S=this.config.from&&!X(this.config.from,j)?this.getTableLikeFields(this.config.from):void 0;T=T(new Proxy(this.config.table[I.Symbol.Columns],new io({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),S&&new Proxy(S,new io({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}if(this.config.joins.push({on:T,table:n,joinType:o,alias:t}),typeof t==="string")switch(o){case"left":{this.joinsNotNullableMap[t]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([S])=>[S,!1])),this.joinsNotNullableMap[t]=!0;break}case"inner":{this.joinsNotNullableMap[t]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([S])=>[S,!1])),this.joinsNotNullableMap[t]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(o){return this.config.where=o,this}returning(o){if(!o){if(o=Object.assign({},this.config.table[I.Symbol.Columns]),this.config.from){let n=Zn(this.config.from);if(typeof n==="string"&&this.config.from&&!X(this.config.from,j)){let T=this.getTableLikeFields(this.config.from);o[n]=T}for(let T of this.config.joins){let t=Zn(T.table);if(typeof t==="string"&&!X(T.table,j)){let S=this.getTableLikeFields(T.table);o[t]=S}}}}return this.config.returning=wn(o),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:o,...n}=this.dialect.sqlToQuery(this.getSQL());return n}_prepare(o){let n=this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,o,!0);return n.joinsNotNullableMap=this.joinsNotNullableMap,n}prepare(o){return this._prepare(o)}authToken;setToken(o){return this.authToken=o,this}execute=(o)=>{return this._prepare().execute(o,this.authToken)};$dynamic(){return this}}class pt extends j{constructor(o){super(pt.buildEmbeddedCount(o.source,o.filters).queryChunks);this.params=o,this.mapWith(Number),this.session=o.session,this.sql=pt.buildCount(o.source,o.filters)}sql;token;static[k]="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};`}setToken(o){return this.token=o,this}then(o,n){return Promise.resolve(this.session.count(this.sql,this.token)).then(o,n)}catch(o){return this.then(void 0,o)}finally(o){return this.then((n)=>{return o?.(),n},(n)=>{throw o?.(),n})}}class jy{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[k]="PgRelationalQueryBuilder";findMany(o){return new Iy(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,o?o:{},"many")}findFirst(o){return new Iy(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,o?{...o,limit:1}:{limit:1},"first")}}class Iy extends on{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[k]="PgRelationalQuery";_prepare(o){return Wo.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)=>LS(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}authToken;setToken(o){return this.authToken=o,this}execute(){return Wo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(void 0,this.authToken)})}}class ry extends on{constructor(o,n,T,t){super();this.execute=o,this.sql=n,this.query=T,this.mapBatchResult=t}static[k]="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 qt{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 jy(T.fullSchema,this._.schema,this._.tableNamesMap,T.fullSchema[t],S,o,n)}static[k]="PgDatabase";query;$with(o){let n=this;return{as(T){if(typeof T==="function")T=T(new it(n.dialect));return new Proxy(new Kt(T.getSQL(),T.getSelectedFields(),o,!0),new io({alias:o,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}}$count(o,n){return new pt({source:o,filters:n,session:this.session})}with(...o){let n=this;function T(M){return new Tn({fields:M??void 0,session:n.session,dialect:n.dialect,withList:o})}function t(M){return new Tn({fields:M??void 0,session:n.session,dialect:n.dialect,withList:o,distinct:!0})}function S(M,F){return new Tn({fields:F??void 0,session:n.session,dialect:n.dialect,withList:o,distinct:{on:M}})}function f(M){return new uS(M,n.session,n.dialect,o)}function y(M){return new dS(M,n.session,n.dialect,o)}function A(M){return new eS(M,n.session,n.dialect,o)}return{select:T,selectDistinct:t,selectDistinctOn:S,update:f,insert:y,delete:A}}select(o){return new Tn({fields:o??void 0,session:this.session,dialect:this.dialect})}selectDistinct(o){return new Tn({fields:o??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(o,n){return new Tn({fields:n??void 0,session:this.session,dialect:this.dialect,distinct:{on:o}})}update(o){return new uS(o,this.session,this.dialect)}insert(o){return new dS(o,this.session,this.dialect)}delete(o){return new eS(o,this.session,this.dialect)}refreshMaterializedView(o){return new Ly(o,this.session,this.dialect)}authToken;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 ry(()=>t.execute(void 0,this.authToken),n,T,(S)=>t.mapResult(S,!0))}transaction(o,n){return this.session.transaction(o,n)}}class GJ{constructor(o,n){this.unique=o,this.name=n}static[k]="PgIndexBuilderOn";on(...o){return new aS(o.map((n)=>{if(X(n,j))return n;n=n;let T=new wt(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 aS(o.map((n)=>{if(X(n,j))return n;n=n;let T=new wt(n.name,!!n.keyAsName,n.columnType,n.indexConfig);return n.indexConfig=n.defaultConfig,T}),this.unique,!0,this.name)}using(o,...n){return new aS(n.map((T)=>{if(X(T,j))return T;T=T;let t=new wt(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 aS{static[k]="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 zJ(this.config,o)}}class zJ{static[k]="PgIndex";config;constructor(o,n){this.config={...o,table:n}}}function Ny(o){return new GJ(!0,o)}class by{constructor(o){this.query=o}authToken;getQuery(){return this.query}mapResult(o,n){return o}setToken(o){return this.authToken=o,this}static[k]="PgPreparedQuery";joinsNotNullableMap}class hy{constructor(o){this.dialect=o}static[k]="PgSession";execute(o,n){return Wo.startActiveSpan("drizzle.operation",()=>{return Wo.startActiveSpan("drizzle.prepareQuery",()=>{return this.prepareQuery(this.dialect.sqlToQuery(o),void 0,void 0,!1)}).setToken(n).execute(void 0,n)})}all(o){return this.prepareQuery(this.dialect.sqlToQuery(o),void 0,void 0,!1).all()}async count(o,n){let T=await this.execute(o,n);return Number(T[0].count)}}class xy extends qt{constructor(o,n,T,t=0){super(o,n,T);this.schema=T,this.nestedIndex=t}static[k]="PgTransaction";rollback(){throw new af}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 HJ extends by{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[k]="PostgresJsPreparedQuery";async execute(o={}){return Wo.startActiveSpan("drizzle.execute",async(n)=>{let T=df(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 Wo.startActiveSpan("drizzle.driver.execute",()=>{return f.unsafe(S,T)});let M=await Wo.startActiveSpan("drizzle.driver.execute",()=>{return n?.setAttributes({"drizzle.query.text":S,"drizzle.query.params":JSON.stringify(T)}),f.unsafe(S,T).values()});return Wo.startActiveSpan("drizzle.mapResponse",()=>{return A?A(M):M.map((F)=>rM(t,F,y))})})}all(o={}){return Wo.startActiveSpan("drizzle.execute",async(n)=>{let T=df(this.params,o);return n?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(T)}),this.logger.logQuery(this.queryString,T),Wo.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 Zt extends hy{constructor(o,n,T,t={}){super(n);this.client=o,this.schema=T,this.options=t,this.logger=t.logger??new oy}static[k]="PostgresJsSession";logger;prepareQuery(o,n,T,t,S){return new HJ(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 Zt(T,this.dialect,this.schema,this.options),S=new cy(this.dialect,t,this.schema);if(n)await S.setTransaction(n);return o(S)})}}class cy extends xy{constructor(o,n,T,t=0){super(o,n,T,t);this.session=n}static[k]="PostgresJsTransaction";transaction(o){return this.session.client.savepoint((n)=>{let T=new Zt(n,this.dialect,this.schema,this.session.options),t=new cy(this.dialect,T,this.schema);return o(t)})}}class mJ extends qt{static[k]="PostgresJsDatabase"}function nt(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 YT({casing:n.casing}),S;if(n.logger===!0)S=new sf;else if(n.logger!==!1)S=n.logger;let f;if(n.schema){let M=r$(n.schema,b$);f={fullSchema:n.schema,schema:M.tables,tableNamesMap:M.tableNamesMap}}let y=new Zt(o,t,f,{logger:S}),A=new mJ(t,y,f);return A.$client=o,A}function sS(...o){if(typeof o[0]==="string"){let n=sT(o[0]);return nt(n,o[1])}if(hM(o[0])){let{connection:n,client:T,...t}=o[0];if(T)return nt(T,t);if(typeof n==="object"&&n.url!==void 0){let{url:f,...y}=n,A=sT(f,y);return nt(A,t)}let S=sT(n);return nt(S,t)}return nt(o[0],o[1])}((o)=>{function n(T){return nt({options:{parsers:{},serializers:{}}},T)}o.mock=n})(sS||(sS={}));var iy={};Bk(iy,{users:()=>GT,userChanges:()=>a0,untrackedUserColumnNames:()=>u0,twoFactorMethod:()=>BJ,trackedUserColumnName:()=>VJ,trackableUserColumnNames:()=>UJ,role:()=>DJ,players:()=>vy,passwordResetAttempts:()=>oW,loginHistory:()=>s0,games:()=>of,banishedIps:()=>Pt});function QJ(o){return R`lower(${o})`}var DJ=WS("role",["admin","user"]),GT=tT("users",{id:Jn().primaryKey().defaultRandom(),username:co({length:16}).notNull(),email:co({length:254}).notNull(),hash:co({length:64}).notNull(),salt:co({length:36}).notNull(),createdAt:Qn({withTimezone:!0}).notNull().defaultNow(),createdIp:co({length:45}).notNull(),isActive:zt().notNull().default(!1),verifiedAt:Qn({withTimezone:!0}),userRole:DJ().default("user")},(o)=>[Ny("usernameUniqueIndex").on(QJ(o.username)),Ny("emailUniqueIndex").on(QJ(o.email))]),u0=["id","createdAt","createdIp","isActive","salt","verifiedAt"],UJ=["username","email","hash","userRole"],VJ=WS("trackedUserColumnName",UJ),a0=tT("userChanges",{id:Jn().primaryKey().defaultRandom(),userId:Jn().notNull().references(()=>GT.id),changedAt:Qn({withTimezone:!0}).notNull().defaultNow(),changedIp:co({length:45}).notNull(),changedColumn:VJ().notNull(),oldValue:co({length:255}),newValue:co({length:255})}),of=tT("games",{id:Jn().primaryKey().defaultRandom()}),vy=tT("players",{userId:Jn().notNull().references(()=>GT.id),gameId:Jn().notNull().references(()=>of.id),score:HS().notNull()},(o)=>[B$({name:"players_userId_gameId_pk",columns:[o.userId,o.gameId]})]),s0=tT("loginHistory",{id:Jn().primaryKey().defaultRandom(),userId:Jn().references(()=>GT.id),loginTime:Qn({withTimezone:!0}).notNull().defaultNow(),ipAddress:co({length:45}).notNull(),userAgent:co({length:1024}),successful:zt().notNull().default(!1)}),BJ=WS("twoFactorMethod",["email","phone"]),oW=tT("passwordResetAttempts",{id:Jn().primaryKey().defaultRandom(),userId:Jn().notNull().references(()=>GT.id),requestedIp:co({length:45}).notNull(),requestedAt:Qn({withTimezone:!0}).notNull().defaultNow(),succeededIp:co({length:45}),succeededAt:Qn({withTimezone:!0}),verificationMethod:BJ().notNull()}),Pt=tT("banishedIps",{ip:co({length:45}).primaryKey(),reason:co({length:2048}).notNull(),banishedAt:Qn({withTimezone:!0}).notNull().defaultNow(),banishedUntil:Qn({withTimezone:!0})});var __dirname="/home/runner/work/wayforge/wayforge/apps/tempest.games/src/database";class py{options;sql;drizzle;observers=new Map;async setupTriggersAndNotifications(){await this.sql.file(nW.resolve(__dirname,"notify_update.sql"));let o=[_n(GT),_n(of),_n(vy)];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=sT(n),this.drizzle=sS(this.sql,{schema:iy,logger:o})}observe(o,n){if(!this.observers.has(o))this.observers.set(o,new s);this.observers.get(o).subscribe("SINGLETON",n)}}var nf={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"},qy=tA(nf).map(([o])=>Go.literal(Number(o))),TW=Go.union([qy[0],qy[1],...qy]),CJ=Go.tuple([TW,Go.string()]);var Py=new rf,{logger:tn}=Py;Object.assign(console,tn,{log:tn.info});tn.info("ready");var Zy=IJ(import.meta.dir,"..","app"),yW=new py({logQuery(o,n){tn.info("\uD83D\uDCDD query",o,n)}});fW({hostname:"0.0.0.0",port:Cn.FRONTEND_PORT??3333,...s$??void 0,async fetch(o,n){try{let T=new Date,t=new URL(o.url),S=n.requestIP(o)?.address??"??";tn.info(T,S,o.method,t.pathname);let[f]=await yW.drizzle.select({banishedUntil:Pt.banishedUntil}).from(Pt).where(jT(Pt.ip,S)).limit(1),y=f?.banishedUntil===null,A=f?.banishedUntil&&f.banishedUntil>T;if(y||A)throw tn.info(`\uD83D\uDE45 request from banned ip ${S}`),[403,S];if(t.pathname==="/")return new Response(Bun.file(IJ(Zy,"index.html")));if(t.pathname==="/index.html")return Response.redirect("/");let M=tW(Zy,t.pathname),F=SW(M);if(!F.startsWith(Zy))throw[403,"Access Denied"];if(!await LJ(F).exists())return Response.redirect("/");return new Response(LJ(F))}catch(T){let t=CJ.safeParse(T);if(t.success){let[S,f]=t.data,A=`${nf[S]}. ${f}`;return tn.info(`\u274C ${S}: ${A}`),new Response(A,{status:S})}if(T instanceof Error)tn.error(T.message);else{let S=BT(T);tn.error("frontend server threw",S)}return new Response(nf[500],{status:500})}}});function Tf(){tn.info("\uD83D\uDEEC frontend server exiting"),process.exit(0)}process.on("SIGINT",()=>{tn.info("\u2757 received SIGINT; exiting gracefully"),Tf()});process.on("SIGTERM",()=>{tn.info("\u2757 received SIGTERM; exiting gracefully"),Tf()});process.on("exit",()=>{tn.info("\u2757 received exit; exiting gracefully"),Tf()});Py.on("timeToStop",()=>{tn.info('\u2757 backend server received signal "timeToStop"; exiting gracefully'),Tf()});tn.info(`\uD83D\uDEEB frontend server running at http://localhost:${Cn.FRONTEND_PORT}/`);Py.emit("alive");