tempest.games 0.0.13 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +29 -0
- package/app/DelveSystem-Regular.otf +0 -0
- package/app/Sudo-Code.otf +0 -0
- package/app/Theia0.2.300-300.otf +0 -0
- package/app/Theia0.2.400-400.otf +0 -0
- package/app/Theia0.2.500-500.otf +0 -0
- package/app/Uruz/Brahmin-0r.otf +0 -0
- package/app/Uruz/Brahmin-1r.otf +0 -0
- package/app/Uruz/Brahmin-2r.otf +0 -0
- package/app/Uruz/Brahmin-3r.otf +0 -0
- package/app/Uruz/Brahmin-4r.otf +0 -0
- package/app/Uruz/Brahmin-5r.otf +0 -0
- package/app/Uruz/Brahmin-6r.otf +0 -0
- package/app/Uruz/Brahmin-7r.otf +0 -0
- package/app/Uruz/Uruz-4c.otf +0 -0
- package/app/Uruz/Uruz-4cc.otf +0 -0
- package/app/Uruz/Uruz-4r.otf +0 -0
- package/app/Uruz/Uruz-5c.otf +0 -0
- package/app/Uruz/Uruz-5r.otf +0 -0
- package/app/Uruz/Uruz-6c.otf +0 -0
- package/app/Uruz/Uruz-6r.otf +0 -0
- package/app/Uruz/Uruz-7r.otf +0 -0
- package/app/assets/index-CTvfPidG.css +1 -0
- package/app/assets/index-CpJSDdLN.js +46 -0
- package/app/icons.ai +1543 -5
- package/app/index.html +2 -2
- package/app/kablooey.gif +0 -0
- package/app/love_yanone.ttf +0 -0
- package/app/react.svg +1 -0
- package/bin/backend.bun.js +36 -8
- package/bin/backend.worker.game.bun.js +1 -1
- package/bin/frontend.bun.js +27 -1
- package/package.json +35 -19
- package/app/assets/index-BLiTugnk.css +0 -1
- package/app/assets/index-TSjQta7U.js +0 -46
- package/app/vite.svg +0 -1
package/bin/frontend.bun.js
CHANGED
|
@@ -1,3 +1,29 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
import{join as go,normalize as xo,resolve as io}from"path";function pe(e=Math.random){return e().toString(36).slice(2)}class ge extends Promise{fate;resolve;reject;done=!1;constructor(e){let t,o;super((n,i)=>{t=n,o=i});this.resolve=t,this.reject=o,this.use(e instanceof Promise?e:new Promise(e))}pass(e,t){if(e===this.fate)this.resolve(t),this.done=!0}fail(e,t){if(e===this.fate)this.reject(t),this.done=!0}use(e){if(e instanceof Promise){const t=e;this.fate=t,t.then((o)=>{this.pass(t,o)},(o)=>{this.fail(t,o)})}else this.resolve(e),this.fate=void 0}}function y(e){while(e.child!==null)e=e.child;return e}function xt(e){while(e.parent!==null)e=e.parent;return e}function ue(e,t){const o=S(t),n=`${e.key}(${o})`,i=ao[e.type],r={key:n,type:i};if(i==="molecule")Object.assign(r,{key:t,family:e});else Object.assign(r,{family:{key:e.key,subKey:o}});return Object.assign(r,{counterfeit:!0}),r}var ao={atom_family:"atom",mutable_atom_family:"mutable_atom",selector_family:"selector",readonly_selector_family:"readonly_selector",molecule_family:"molecule"};function U(e){const t={key:e.key,type:e.type};if("family"in e)t.family=e.family;return t}function Te(e){return Ft(K.STORE,e)}function me(e){return At(K.STORE,e)}var Ue=(e)=>(t,o,n,i,...r)=>{console[e](`${t} ${o} "${n}" ${i}`,...r)},lo={error:Ue("error"),info:Ue("info"),warn:Ue("warn")};class Ye{e;t;o;constructor(e,t,o=lo){this.logLevel=e;this.filter=t;this.logger=o}error=(...e)=>{if((this.filter?.(...e)??!0)&&this.logLevel!==null)this.logger.error(...e)};info=(...e)=>{if((this.filter?.(...e)??!0)&&this.logLevel==="info")this.logger.info(...e)};warn=(...e)=>{if((this.filter?.(...e)??!0)&&this.logLevel!=="error"&&this.logLevel!==null)this.logger.warn(...e)}}function $e(e){return Le(K.STORE,e)}function Ae(e){return qe(e,K.STORE)}class X{a;b;cardinality;relations=new Map;contents=new Map;isContent;makeContentKey=(e,t)=>`${e}:${t}`;warn;getRelatedKeys(e){return this.relations.get(e)}addRelation(e,t){let o=this.relations.get(e),n=this.relations.get(t);if(o)o.add(t);else o=new Set([t]),this.relations.set(e,o);if(n)n.add(e);else n=new Set([e]),this.relations.set(t,n)}deleteRelation(e,t){const o=this.relations.get(e);if(o){if(o.delete(t),o.size===0)this.relations.delete(e);const n=this.relations.get(t);if(n){if(n.delete(e),n.size===0)this.relations.delete(t)}}}replaceRelationsUnsafely(e,t){this.relations.set(e,new Set(t));for(let o of t){const n=new Set([e]);this.relations.set(o,n)}}replaceRelationsSafely(e,t){const o=this.relations.get(e);if(o)for(let n of o){const i=this.relations.get(n);if(i){if(i.size===1)this.relations.delete(n);else i.delete(e);this.contents.delete(this.makeContentKey(e,n))}}this.relations.set(e,new Set(t));for(let n of t){let i=this.relations.get(n);if(i)i.add(e);else i=new Set([e]),this.relations.set(n,i)}}getContentInternal(e){return this.contents.get(e)}setContent(e,t){this.contents.set(e,t)}deleteContent(e){this.contents.delete(e)}constructor(e,t){if(this.a=e.between[0],this.b=e.between[1],this.cardinality=e.cardinality,!t?.externalStore)this.relations=new Map(e.relations?.map(([o,n])=>[o,new Set(n)])),this.contents=new Map(e.contents);if(this.isContent=t?.isContent??null,t?.makeContentKey)this.makeContentKey=t.makeContentKey;if(t?.externalStore){const o=t.externalStore;if(this.has=(n,i)=>o.has(n,i),this.addRelation=(n,i)=>{o.addRelation(n,i)},this.deleteRelation=(n,i)=>{o.deleteRelation(n,i)},this.replaceRelationsSafely=(n,i)=>{o.replaceRelationsSafely(n,i)},this.replaceRelationsUnsafely=(n,i)=>{o.replaceRelationsUnsafely(n,i)},this.getRelatedKeys=(n)=>o.getRelatedKeys(n),o.getContent)this.getContentInternal=(n)=>{return o.getContent(n)},this.setContent=(n,i)=>{o.setContent(n,i)},this.deleteContent=(n)=>{o.deleteContent(n)};for(let[n,i]of e.relations??[])for(let r of i)this.addRelation(n,r);for(let[n,i]of e.contents??[])this.setContent(n,i)}if(t?.warn)this.warn=t.warn}toJSON(){return{between:[this.a,this.b],cardinality:this.cardinality,relations:[...this.relations.entries()].map(([e,t])=>[e,[...t]]),contents:[...this.contents.entries()]}}set(e,...t){const o=typeof t[0]==="string"?t[0]:e[this.b],n=t[1]??typeof t[0]==="string"?void 0:t[0];switch(e=typeof e==="string"?e:e[this.a],this.cardinality){case"1:1":{const i=this.getRelatedKey(e);if(i&&i!==o)this.delete(i,e)}case"1:n":{const i=this.getRelatedKey(o);if(i&&i!==e)this.delete(i,o)}}if(n){const i=this.makeContentKey(e,o);this.setContent(i,n)}return this.addRelation(e,o),this}delete(e,t){t=typeof t==="string"?t:e[this.b];const o=typeof e==="string"?e:e[this.a];if(o===void 0&&typeof t==="string"){const n=this.getRelatedKeys(t);if(n)for(let i of n)this.delete(i,t)}if(typeof o==="string"&&t===void 0){const n=this.getRelatedKeys(o);if(n)for(let i of n)this.delete(o,i)}if(typeof o==="string"&&typeof t==="string"){this.deleteRelation(o,t);const n=this.makeContentKey(o,t);this.deleteContent(n)}return this}getRelatedKey(e){const t=this.getRelatedKeys(e);if(t){if(t.size>1)this.warn?.(`${t.size} related keys were found for key "${e}": (${[...t].map((o)=>`"${o}"`).join(", ")}). Only one related key was expected.`);for(let o of t)return o}}replaceRelations(e,t,o){const n=!Array.isArray(t),i=n?Object.keys(t):t;if(o?.reckless)this.replaceRelationsUnsafely(e,i);else this.replaceRelationsSafely(e,i);if(n)for(let r of i){const a=this.makeContentKey(e,r),s=t[r];this.setContent(a,s)}return this}getContent(e,t){const o=this.makeContentKey(e,t);return this.getContentInternal(o)}getRelationEntries(e){const t=e[this.a],o=e[this.b];if(t!==void 0&&o===void 0){const n=this.getRelatedKeys(t);if(n)return[...n].map((i)=>{return[i,this.getContent(t,i)??null]})}if(t===void 0&&o!==void 0){const n=this.getRelatedKeys(o);if(n)return[...n].map((i)=>{return[i,this.getContent(i,o)??null]})}return[]}has(e,t){if(t)return this.getRelatedKeys(e)?.has(t)??!1;return this.relations.has(e)}}class b{Subscriber;subscribers=new Map;subscribe(e,t){return this.subscribers.set(e,t),()=>{this.unsubscribe(e)}}unsubscribe(e){this.subscribers.delete(e)}next(e){const t=this.subscribers.values();for(let o of t)o(e)}}class Qe extends b{state;constructor(e){super();this.state=e}next(e){this.state=e,super.next(e)}}function P(e){return"epoch"in e.transactionMeta}function R(e){return"phase"in e.transactionMeta}var Mt=(e)=>{const t=y(e);if(!R(t)){e.logger.warn("\uD83D\uDC1E","transaction","???","abortTransaction called outside of a transaction. This is probably a bug in AtomIO.");return}e.logger.info("\uD83E\uDE82","transaction",t.transactionMeta.update.key,"Aborting transaction"),t.parent.child=null};function Q(e){return e.type.split("_").map(so).join(" ")}var so=(e)=>e[0].toUpperCase()+e.slice(1);class N extends Error{constructor(...e){const t=e[0],o=e.length===2?e[1]:e[2];if(e.length===2)super(`${Q(t)} ${S(t.key)} not found in store "${o.config.name}".`);else{const n=e[1];super(`${Q(t)} "${t.key}" member ${S(n)} not found in store "${o.config.name}".`)}}}function ye(e,t,o){return(...n)=>{const i=d(e,o);if(i)return i.run(n,t);throw new N(e,o)}}var Oe=(e)=>(t)=>e instanceof Function?e(t):e;var ie=(e,t)=>{if(t.valueMap.has(e.key))return t.logger.info("\uD83D\uDCD6",e.type,e.key,"reading cached value"),Rt(e,t);if(e.type==="selector"||e.type==="readonly_selector")return t.logger.info("\uD83E\uDDEE",e.type,e.key,"computing value"),e.get();const o=e.default instanceof Function?e.default():e.default;return t.logger.info("\uD83D\uDC81","atom",e.key,"could not find cached value; using default",o),e.default instanceof Function?e.default():e.default};var Ct=(e,t)=>{if(e.operation.open){const o=performance.now();return e.logger.info("\u2757",t.type,t.key,`deferring setState at T-${o} until setState for "${e.operation.token.key}" is done`),o}e.operation={open:!0,done:new Set,prev:new Map,time:Date.now(),token:t},e.logger.info("\u2B55",t.type,t.key,`operation start in store "${e.config.name}"${!R(e)?"":` ${e.transactionMeta.phase} "${e.transactionMeta.update.key}"`}`)},Kt=(e)=>{if(e.operation.open)e.logger.info("\uD83D\uDD34",e.operation.token.type,e.operation.token.key,`operation done in store "${e.config.name}"`);e.operation={open:!1},e.on.operationClose.next(e.operation)},Jt=(e,t)=>{if(!e.operation.open)return e.logger.error("\uD83D\uDC1E","unknown",t,"isDone called outside of an operation. This is probably a bug in AtomIO."),!0;return e.operation.done.has(t)},de=(e,t)=>{if(!e.operation.open){e.logger.error("\uD83D\uDC1E","unknown",t,"markDone called outside of an operation. This is probably a bug in AtomIO.");return}e.operation.done.add(t)};var wt=(e,t,o)=>{switch(e.type){case"mutable_atom":o.logger.info("\uD83D\uDCE2",e.type,e.key,"is now (",t.newValue,") subscribers:",e.subject.subscribers);break;default:o.logger.info("\uD83D\uDCE2",e.type,e.key,"went (",t.oldValue,"->",t.newValue,") subscribers:",e.subject.subscribers)}e.subject.next(t)};var Ze=(e,t)=>{const o=y(t),n=o.selectorAtoms.getRelatedKeys(e.key);if(o.logger.info("\uD83E\uDDF9",e.type,e.key,n?`evicting ${n.size} states downstream:`:"no downstream states",n??"to evict"),n){if(o.operation.open)o.logger.info("\uD83E\uDDF9",e.type,e.key,`[ ${[...o.operation.done].join(", ")} ] already done`);for(let i of n){if(Jt(o,i))continue;ht(i,o),de(o,i)}}};function co(e,t){if(Ot(t.newValue))return!1;if(e.includes("\uD83D\uDD0D"))return!1;return!0}var $t=(e,t,o)=>{const{key:n}=e,i=y(o);if(!R(i)||i.transactionMeta.phase!=="building"){o.logger.error("\uD83D\uDC1E","atom",n,"stowUpdate called outside of a transaction. This is probably a bug.");return}if(!co(n,t))return;const a={type:"atom_update",key:n,...t};if(e.family)a.family=e.family;i.transactionMeta.update.updates.push(a),o.logger.info("\uD83D\uDCC1","atom",n,"stowed (",t.oldValue,"->",t.newValue,")")};var vt=(e,t,o)=>{const n=ie(e,o);let i=n;if(e.type==="mutable_atom"&&R(o)){const{parent:a}=o;i=Fe(e,a,o)}if(i=Oe(t)(i),o.logger.info("\uD83D\uDCDD","atom",e.key,"set to",i),i=Y(e.key,i,e.subject,o),It(e.key,o))Wt(e.key,o);de(o,e.key),Ze(e,o);const r={oldValue:n,newValue:i};if(P(o))wt(e,r,o);else if(o.parent){if(o.on.transactionApplying.state===null)$t(e,r,o);else if(e.key.startsWith("*")){const a=e.key.slice(1),s=o.atoms.get(a);let l=o.valueMap.get(a);if(s.type==="mutable_atom"&&R(o)){const{parent:m}=o;l=Fe(s,m,o)}if(l.do(r.newValue)===null)Ze(s,o)}}};var ve=(e,t,o)=>{switch(e.type){case"atom":case"mutable_atom":vt(e,t,o);break;case"selector":e.set(t);break}};function re(e,t,o){const n={key:t.key,type:"atom_family"},i=e.families.get(t.key);if(i)e.logger.error("\u2757","atom_family",t.key,`Overwriting an existing ${Q(i)} "${i.key}" in store "${e.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);const r=new b,s=Object.assign((l)=>{const c=S(l),m={key:t.key,subKey:c},u=`${t.key}(${c})`,F=y(e),C=t.default,v={key:u,default:C instanceof Function?C(l):C};if(t.effects)v.effects=t.effects(l);const G=ae(F,v,m);return r.next({type:"state_creation",token:G}),G},n,{subject:r,install:(l)=>re(l,t),internalRoles:o});return e.families.set(t.key,s),e.defaults.set(t.key,t.default),n}function At(e,t){if("mutable"in t)return Me(e,t);return re(e,t)}function Ie(e,t){if(t.family){const o=e.families.get(t.family.key);if(o)return o}}function _(e,...t){let o,n,i;if(t.length===1){if(o=t[0],o.type!=="molecule"){if(n=Ie(e,o)??null,n)i=o.family?E(o.family.subKey):null,o=h(e,n,i)}}else{n=t[0],i=t[1];let r;if(n.type==="molecule_family")r=$(e,n,i)??ue(n,i);else r=h(e,n,i);o=r}if("counterfeit"in o&&"family"in o){n=o.type==="molecule"?d(o.family,e):e.families.get(o.family.key);const r=o.type==="molecule"?o.key:o.family.subKey,a=e.disposalTraces.buffer.find((s)=>s?.key===o.key);switch(e.logger.error("\u274C",o.type,o.key,`could not be retrieved because it was not found in the store "${e.config.name}".`,a?`This state was previously disposed:\n${a.trace}`:"No previous disposal trace was found."),n.type){case"atom_family":case"mutable_atom_family":return e.defaults.get(n.key);case"selector_family":case"readonly_selector_family":{if(e.defaults.has(n.key))return e.defaults.get(o.family.key);const s=d(n,e).default(r);return e.defaults.set(n.key,s),s}case"molecule_family":throw new N(n,r,e)}}switch(o.type){case"atom":case"mutable_atom":case"selector":case"readonly_selector":return ie(d(o,e),e);case"molecule":return d(o,e).instance}}var We=(e,t)=>y(t).atoms.has(e),mo=(e,t)=>y(t).selectors.has(e),yo=(e,t)=>y(t).readonlySelectors.has(e),_t=(e,t)=>We(e,t)||mo(e,t)||yo(e,t);var _e=(e,t)=>{return y(t).selectorGraph.getRelationEntries({downstreamSelectorKey:e}).filter(([n,{source:i}])=>i!==e).map(([n,{source:i}])=>i).filter((n)=>_t(n,t))};var Ge=(e,t,o)=>{const n=[],i=_e(e,o);while(i.length>0){const r=i.shift();if(t.has(r))continue;if(t.add(r),!We(r,o))i.push(..._e(r,o));else if(!n.includes(r))n.push(r)}return n},jt=(e,t)=>{const o=e.key,n=_e(o,t),i=new Set;return n.flatMap((r)=>We(r,t)?r:Ge(r,i,t))};var Bt=(e,t,o,n)=>{const i=y(n);if(t.type==="atom"||t.type==="mutable_atom")i.selectorAtoms.set({selectorKey:e,atomKey:t.key}),n.logger.info("\uD83D\uDD0D","selector",e,`discovers root atom "${t.key}"`);else{const r=Ge(t.key,o,n);n.logger.info("\uD83D\uDD0D","selector",e,`discovers root atoms: [ ${r.map((a)=>`"${a}"`).join(", ")} ]`);for(let a of r)i.selectorAtoms=i.selectorAtoms.set({selectorKey:e,atomKey:a})}o.add(t.key)};var je=(e,t,o)=>({get:(...n)=>{const i=y(o);let r;if(n.length===2){const[l,c]=n;switch(l.type){case"molecule_family":return _(o,l,c);default:if(o.config.lifespan==="ephemeral")r=h(o,l,c);else{const m=$(o,l,c);if(m)r=m;else throw new N(l,c,o)}}}else[r]=n;if(r.type==="molecule")return _(o,r);const a=d(r,o),s=ie(a,o);return o.logger.info("\uD83D\uDD0C","selector",e,`registers dependency ( "${r.key}" =`,s,")"),i.selectorGraph.set({upstreamSelectorKey:r.key,downstreamSelectorKey:e},{source:r.key}),Bt(e,r,t,o),s},set:(...n)=>{let i,r;if(n.length===2)i=n[0],r=n[1];else{const l=n[0],c=n[1];r=n[2];const m=o.config.lifespan==="ephemeral"?h(o,l,c):$(o,l,c);if(!m)throw new N(l,c,o);i=m}const a=y(o),s=d(i,a);ve(s,r,a)},find:(n,i)=>h(o,n,i),seek:(n,i)=>$(o,n,i),json:(n)=>V(o,n)});var Re=(e,t,o)=>{const n=y(e),i=new b,r=new Set,{get:a,find:s,seek:l,json:c}=je(t.key,r,n),m=()=>{const v=t.get({get:a,find:s,seek:l,json:c});return Y(t.key,v,i,y(e)),r.clear(),v},u={...t,subject:i,install:(v)=>Re(v,t,o),get:m,type:"readonly_selector",...o&&{family:o}};n.readonlySelectors.set(t.key,u);const F=m();e.logger.info("\u2728",u.type,u.key,"=",F);const C={key:t.key,type:"readonly_selector"};if(o)C.family=o;return C};var Ce=(e,t,o)=>{const n=y(e),i=new b,r=new Set,a=je(t.key,r,n),{find:s,get:l,seek:c,json:m}=a,u={find:s,get:l,seek:c,json:m},F=(I=t.get,W=y(e))=>{const w=I(u);return Y(t.key,w,i,W),r.clear(),w},v={...t,subject:i,install:(I)=>Ce(I,t,o),get:F,set:(I)=>{const W=y(e),w=F(t.get,W),q=Oe(I)(w);if(e.logger.info("\uD83D\uDCDD","selector",t.key,"set (",w,"->",q,")"),Y(t.key,q,i,W),de(W,t.key),P(W))i.next({newValue:q,oldValue:w});t.set(a,q)},type:"selector",...o&&{family:o}};n.selectors.set(t.key,v);const G=F();e.logger.info("\u2728",v.type,v.key,"=",G);const k={key:t.key,type:"selector"};if(o)k.family=o;return k};function xe(e,t){if("set"in t){const i=Ce(e,t,void 0);return e.on.selectorCreation.next(i),i}const n=Re(e,t,void 0);return e.on.selectorCreation.next(n),n}function Et(e,t){const o=y(t),{key:n}=e,i=d(e,o);if(!i.family)t.logger.error("\u274C","selector",n,"Standalone selectors cannot be disposed.");else{const r=o.molecules.get(i.family.subKey);if(r)r.tokens.delete(n);switch(e.type){case"selector":o.selectors.delete(n),d({key:i.family.key,type:"selector_family"},t).subject.next({type:"state_disposal",token:e});break;case"readonly_selector":o.readonlySelectors.delete(n),d({key:i.family.key,type:"readonly_selector_family"},t).subject.next({type:"state_disposal",token:e});break}if(o.valueMap.delete(n),o.selectorAtoms.delete(n),o.selectorGraph.delete(n),t.logger.info("\uD83D\uDD25",e.type,n,"deleted"),R(o)&&o.transactionMeta.phase==="building")o.transactionMeta.update.updates.push({type:"state_disposal",token:e});else t.on.selectorDisposal.next(e)}}function le(e,t,o){const n={key:t.key,type:"readonly_selector_family"},i=e.families.get(t.key);if(i)e.logger.error("\u2757","readonly_selector_family",t.key,`Overwriting an existing ${Q(i)} "${i.key}" in store "${e.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);const r=new b,s=Object.assign((l)=>{const c=S(l),m={key:t.key,subKey:c},u=`${t.key}(${c})`,F=y(e),C=Re(F,{key:u,get:t.get(l)},m);return r.next({type:"state_creation",token:C}),C},n,{internalRoles:o,subject:r,install:(l)=>le(l,t),default:(l)=>{return t.get(l)({get:(...m)=>_(e,...m),find:(m,u)=>h(e,m,u),seek:(m,u)=>$(e,m,u),json:(m)=>V(e,m)})}});return e.families.set(t.key,s),n}function Ke(e,t,o){const n={key:t.key,type:"selector_family"},i=e.families.get(t.key);if(i)e.logger.error("\u2757","selector_family",t.key,`Overwriting an existing ${Q(i)} "${i.key}" in store "${e.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);const r=new b,s=Object.assign((l)=>{const c=S(l),m={key:t.key,subKey:c},u=`${t.key}(${c})`,F=y(e),C=Ce(F,{key:u,get:t.get(l),set:t.set(l)},m);return r.next({type:"state_creation",token:C}),C},n,{internalRoles:o,subject:r,install:(l)=>Ke(l,t),default:(l)=>{return t.get(l)({get:(...m)=>_(e,...m),find:(m,u)=>h(e,m,u),seek:(m,u)=>$(e,m,u),json:(m)=>V(e,m)})}});return e.families.set(t.key,s),n}function Le(e,t){if("set"in t)return Ke(e,t);return le(e,t)}function Be(e,t){let o;o=d(e,t);const{family:n}=e;for(let a of o.joins.values())a.relations.delete(o.key),a.molecules.delete(o.stringKey);const i=[];for(let a of o.above.values())i.push(U(a));const r=[];for(let a of o.tokens.values()){const s=a.family;r.push([s.key,t.valueMap.get(a.key)])}if(n){const a=d(n,t),s={type:"molecule_disposal",token:e,family:n,context:i,values:r};if(e.family)s.family=e.family;for(let c of o.tokens.values())D(t,c);for(let c of o.below.values())if(c.family?.dependsOn==="all")Be(c,t);else if(c.above.delete(o.stringKey),c.above.size===0)Be(c,t);if(o.below.clear(),R(t)&&t.transactionMeta.phase==="building")t.transactionMeta.update.updates.push(s);else a.subject.next(s);t.molecules.delete(o.stringKey)}for(let a of o.above.values())a.below.delete(o.stringKey)}function zt(e,t){const o=new b,n={type:"molecule_family",key:t.key,dependsOn:t.dependsOn??"all"},i={...n,subject:o,new:t.new};return e.moleculeFamilies.set(t.key,i),n}function Z(e,t,o){const n=te(o,t,e.key);e.tokens.set(n.key,n);const i=R(o)&&o.transactionMeta.phase==="building",r=o.moleculeInProgress===e.key;if(!i&&!r)e.subject.next({type:"state_creation",token:n});return n}class z extends Set{mode="record";subject=new b;cacheLimit=0;cache=[];cacheIdx=-1;cacheUpdateNumber=-1;constructor(e,t=0){super(e);if(e instanceof z)this.parent=e,this.cacheUpdateNumber=e.cacheUpdateNumber;if(t)this.cacheLimit=t,this.cache=new Array(t),this.subscribe("auto cache",(o)=>{this.cacheIdx++,this.cacheIdx%=this.cacheLimit,this.cache[this.cacheIdx]=o})}toJSON(){return{members:[...this],cache:this.cache,cacheLimit:this.cacheLimit,cacheIdx:this.cacheIdx,cacheUpdateNumber:this.cacheUpdateNumber}}static fromJSON(e){const t=new z(e.members,e.cacheLimit);return t.cache=e.cache,t.cacheIdx=e.cacheIdx,t.cacheUpdateNumber=e.cacheUpdateNumber,t}add(e){const t=super.add(e);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`add:${S(e)}`);return t}clear(){const e=this.mode==="record"?[...this]:null;if(super.clear(),e)this.cacheUpdateNumber++,this.emit(`clear:${JSON.stringify(e)}`)}delete(e){const t=super.delete(e);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`del:${S(e)}`);return t}parent;child=null;transactionUpdates=null;transaction(e){this.mode="transaction",this.transactionUpdates=[],this.child=new z(this);const t=this.child._subscribe("transaction",(o)=>{this.transactionUpdates?.push(o)});try{if(e(this.child)){for(let n of this.transactionUpdates)this.doStep(n);this.cacheUpdateNumber++,this.emit(`tx:${this.transactionUpdates.join(";")}`)}}catch(o){throw console.error("Failed to apply transaction to SetRTX:",o),o}finally{t(),this.child=null,this.transactionUpdates=null,this.mode="record"}}_subscribe(e,t){return this.subject.subscribe(e,t)}subscribe(e,t){return this.subject.subscribe(e,(o)=>{t(`${this.cacheUpdateNumber}=${o}`)})}emit(e){this.subject.next(e)}doStep(e){const t=e.indexOf(":"),o=e.substring(0,t),n=e.substring(t+1);switch(o){case"add":this.add(JSON.parse(n));break;case"clear":this.clear();break;case"del":this.delete(JSON.parse(n));break;case"tx":for(let i of n.split(";"))this.doStep(i)}}getUpdateNumber(e){const t=e.indexOf("=");return Number(e.substring(0,t))}do(e){const t=e.indexOf("="),o=Number(e.substring(0,t)),n=o-this.cacheUpdateNumber;if(n>0){if(n===1){this.mode="playback";const r=e.substring(t+1);return this.doStep(r),this.mode="record",this.cacheUpdateNumber=o,null}return this.cacheUpdateNumber+1}if(Math.abs(n)<this.cacheLimit){const r=this.cacheIdx+n;if(this.cache[r]===e)return null;this.mode="playback";let s=!1;while(!s){this.cacheIdx%=this.cacheLimit;const c=this.cache[this.cacheIdx];if(this.cacheIdx--,!c)return"OUT_OF_RANGE";this.undo(c),s=this.cacheIdx===r-1}const l=e.substring(t+1);return this.doStep(l),this.mode="record",this.cacheUpdateNumber=o,null}return"OUT_OF_RANGE"}undoStep(e){const t=e.indexOf(":"),o=e.substring(0,t),n=e.substring(t+1);switch(o){case"add":this.delete(JSON.parse(n));break;case"del":this.add(JSON.parse(n));break;case"clear":{const i=JSON.parse(n);for(let r of i)this.add(r);break}case"tx":{const i=n.split(";");for(let r=i.length-1;r>=0;r--)this.undoStep(i[r])}}}undo(e){const t=e.indexOf("=");if(Number(e.substring(0,t))===this.cacheUpdateNumber){this.mode="playback";const n=e.substring(t+1);return this.undoStep(n),this.mode="record",this.cacheUpdateNumber--,null}return this.cacheUpdateNumber}}function O(e){return e[0].toUpperCase()+e.slice(1)}function Ee(e,t,o=K.STORE){return et(o).set(e.key,new ot(e,t,o)),{key:e.key,type:"join",a:e.between[0],b:e.between[1],cardinality:e.cardinality}}function et(e){if("joins"in e&&e.joins instanceof Map)return e.joins;const t=new Map;return e.joins=t,t}function Je(e,t){const o=et(t);let n=o.get(e.key);if(n===void 0){if(n=et(K.STORE).get(e.key)?.in(t),n===void 0)throw new Error(`Join "${e.key}" not found in store "${t.config.name}"`);o.set(e.key,n)}return n}function Pt(e,t,o){const n=Je(e,o);let i;switch(e.cardinality){case"1:1":{const r=`${e.a}KeyOf${O(e.b)}`,a=`${e.b}KeyOf${O(e.a)}`;i={get[r](){const l=n.states[r];return n.retrieve(l,t)},get[a](){const l=n.states[a];return n.retrieve(l,t)}};const s=`${e.a}EntryOf${O(e.b)}`;if(s in n.states){const l=`${e.b}EntryOf${O(e.a)}`;Object.assign(i,{get[s](){const c=n.states[s];return n.retrieve(c,t)},get[l](){const c=n.states[l];return n.retrieve(c,t)}})}break}case"1:n":{const r=`${e.a}KeyOf${O(e.b)}`,a=`${e.b}KeysOf${O(e.a)}`;i={get[r](){const l=n.states[r];return n.retrieve(l,t)},get[a](){const l=n.states[a];return n.retrieve(l,t)}};const s=`${e.a}EntryOf${O(e.b)}`;if(s in n.states){const l=`${e.b}EntriesOf${O(e.a)}`;Object.assign(i,{get[s](){const c=n.states[s];return n.retrieve(c,t)},get[l](){const c=n.states[l];return n.retrieve(c,t)}})}break}case"n:n":{const r=`${e.a}KeysOf${O(e.b)}`,a=`${e.b}KeysOf${O(e.a)}`;i={get[r](){const l=n.states[r];return n.retrieve(l,t)},get[a](){const l=n.states[a];return n.retrieve(l,t)}};const s=`${e.a}EntriesOf${O(e.b)}`;if(s in n.states){const l=`${e.b}EntriesOf${O(e.a)}`;Object.assign(i,{get[s](){const c=n.states[s];return n.retrieve(c,t)},get[l](){const c=n.states[l];return n.retrieve(c,t)}})}}}return i}function Vt(e,t){return Pt(e,t,K.STORE)}function ze(e,t,o){const n=Je(e,o),i=y(o);if(R(i)){const{toolkit:r}=i.transactionMeta;n.transact(r,({relations:a})=>{t(a)})}else t(n.relations)}function fo(e,t){return Je(e,t).core.findRelatedKeysState}function Nt(e){return fo(e,K.STORE)}class ot{options;defaultContent;toolkit;retrieve;molecules=new Map;relations;states;core;transact(e,t){const o=this.toolkit;this.toolkit=e,t(this),this.toolkit=o}store;alternates;[Symbol.dispose](){this.alternates.delete(this.store.config.name)}in(e){const t=e.config.name,o=this.alternates.get(t);if(o)return o;const n=new ot(this.options,this.defaultContent,e);return this.alternates.set(t,n),n.alternates=this.alternates,n}constructor(e,t,o=K.STORE){this.store=o,this.options=e,this.defaultContent=t,this.alternates=new Map,this.alternates.set(o.config.name,this),this.store.miscResources.set(`join:${e.key}`,this),this.retrieve=(f,p)=>{const g=this.toolkit.seek(f,p);if(g)return g;const x=this.molecules.get(S(p));if(x){const A=d(f,o);return Z(x,A,o)}if(o.config.lifespan==="immortal")throw new N(f,p,o);return te(o,f,p)},this.toolkit={get:(...f)=>_(o,...f),set:(...f)=>{j(o,...f)},find:this.retrieve,seek:(...f)=>$(o,...f),json:(f)=>V(o,f),dispose:(...f)=>{D(o,...f)}};const n=e.between[0],i=e.between[1],r=Me(o,{key:`${e.key}/relatedKeys`,default:()=>new z,mutable:!0,fromJson:(f)=>z.fromJSON(f),toJson:(f)=>f.toJSON()},["join","relations"]);this.core={findRelatedKeysState:r};const a=({get:f},p)=>f(this.retrieve(r,p)),s=(f,p,g)=>{const{set:x}=f,A=this.retrieve(r,p),T=this.retrieve(r,g);x(A,(M)=>M.add(g)),x(T,(M)=>M.add(p))},l=(f,p,g)=>{const{set:x}=f,A=this.retrieve(r,p),T=this.retrieve(r,g);let M,J;x(A,(B)=>{if(B.delete(g),B.size===0)M=`"${p}"`;return B}),x(T,(B)=>{if(B.delete(p),B.size===0)J=`"${g}"`;return B})},c=(f,p,g)=>{const{get:x,set:A}=f,T=this.retrieve(r,p),M=x(T);for(let J of M){if(g.includes(J))continue;const ne=this.retrieve(r,J);A(ne,(ee)=>{return ee.delete(p),ee})}A(T,(J)=>{return J.transaction((B)=>{B.clear();for(let ne of g){const ee=a(f,ne),bt=ee.has(p);if(this.relations.cardinality==="1:n"){const gt=[];for(let ke of ee){if(ke===p)continue;const be=a(f,ke);if(be.delete(ne),be.size===0)gt.push(ke)}if(!bt&&ee.size>0)ee.clear();for(let ke of gt){const be=[ne,ke].sort(),ro=`"${be[0]}:${be[1]}"`;this.molecules.delete(ro)}}if(!bt)ee.add(p);B.add(ne)}return!0}),J})},m=(f,p,g)=>{const{set:x}=f,A=this.retrieve(r,p);x(A,(T)=>{return T.transaction((M)=>{for(let J of g)M.add(J);return!0}),T});for(let T of g){const M=this.retrieve(r,T);x(M,(J)=>{return J.add(p),J})}return!0},u=(f,p,g)=>{const x=a(f,p);return g?x.has(g):x.size>0},F={getRelatedKeys:(f)=>a(this.toolkit,f),addRelation:(f,p)=>{s(this.toolkit,f,p)},deleteRelation:(f,p)=>{l(this.toolkit,f,p)},replaceRelationsSafely:(f,p)=>{c(this.toolkit,f,p)},replaceRelationsUnsafely:(f,p)=>{m(this.toolkit,f,p)},has:(f,p)=>u(this.toolkit,f,p)};let C,v,G;if(t){v=re(o,{key:`${e.key}/content`,default:t},["join","content"]);const f={key:e.key,type:"join",a:e.between[0],b:e.between[1],cardinality:e.cardinality};G=zt(o,{key:`${e.key}/content-molecules`,new:class T{J;constructor(M,J){this.key=J}}});const p=({get:T},M)=>T(this.retrieve(v,M)),g=({set:T},M,J)=>{T(this.retrieve(v,M),J)},x=(T,M)=>{const J=o.molecules.get(`"${M}"`);if(J)this.toolkit.dispose(J),this.molecules.delete(`"${M}"`)};C=Object.assign(F,{getContent:(T)=>{return p(this.toolkit,T)},setContent:(T,M)=>{g(this.toolkit,T,M)},deleteContent:(T)=>{x(this.toolkit,T)}})}else C=F;const k=new X(e,{externalStore:C,makeContentKey:(...f)=>{const p=f.sort(),g=`${p[0]}:${p[1]}`,[x,A]=p.map((T)=>this.molecules.get(S(T)));if(o.config.lifespan==="immortal"&&x&&A){const T=y(o),M=oe(T,[x,A],G,g);this.molecules.set(`"${g}"`,d(M,T))}return g}}),I=()=>le(o,{key:`${e.key}/singleRelatedKey`,get:(f)=>({get:p})=>{const g=this.retrieve(r,f),x=p(g);for(let A of x)return A;return null}},["join","keys"]),W=()=>{return le(o,{key:`${e.key}/multipleRelatedKeys`,get:(f)=>({get:p})=>{const g=tt(r,o),x=this.retrieve(g,f);return p(x).members}},["join","keys"])},w=()=>le(o,{key:`${e.key}/singleRelatedEntry`,get:(f)=>({get:p})=>{const g=this.retrieve(r,f),x=p(g);for(let A of x){const T=k.makeContentKey(f,A),M=this.retrieve(v,T),J=p(M);return[A,J]}return null}},["join","entries"]),q=()=>le(o,{key:`${e.key}/multipleRelatedEntries`,get:(f)=>({get:p})=>{const g=tt(r,o),x=this.retrieve(g,f);return p(x).members.map((T)=>{const M=k.makeContentKey(f,T),J=this.retrieve(v,M),B=p(J);return[T,B]})}},["join","entries"]);switch(e.cardinality){case"1:1":{const f=I(),p=`${n}KeyOf${O(i)}`,g=`${i}KeyOf${O(n)}`,x={[p]:f,[g]:f};let A;if(t){const T=w(),M=`${n}EntryOf${O(i)}`,J=`${i}EntryOf${O(n)}`,B={[M]:T,[J]:T};A=Object.assign(x,B)}else A=x;this.relations=k,this.states=A;break}case"1:n":{const f=I(),p=W(),g=`${n}KeyOf${O(i)}`,x=`${i}KeysOf${O(n)}`,A={[g]:f,[x]:p};let T;if(t){const M=w(),J=q(),B=`${n}EntryOf${O(i)}`,ne=`${i}EntriesOf${O(n)}`,ee={[B]:M,[ne]:J};T=Object.assign(A,ee)}else T=A;this.relations=k,this.states=T;break}default:{const f=W(),p=`${n}KeysOf${O(i)}`,g=`${i}KeysOf${O(n)}`,x={[p]:f,[g]:f};let A;if(t){const T=q(),M=`${n}EntriesOf${O(i)}`,J=`${i}EntriesOf${O(n)}`,B={[M]:T,[J]:T};A=Object.assign(x,B)}else A=x;this.relations=k,this.states=A}}}}function Pe(e){return{store:e}}class Ve{t;type="molecule";stringKey;family;subject=new b;tokens=new Map;above=new Map;below=new Map;joins=new Map;instance;constructor(e,t,o){this.key=t;if(this.stringKey=S(t),o)this.family=o;if(e)if(Array.isArray(e))for(let n of e)this.above.set(n.stringKey,n);else this.above.set(e.stringKey,e)}}function Xt(e){return e[0].toUpperCase()+e.slice(1)}function oe(e,t,o,n,...i){const r=xt(e),a=y(e),s=S(n);a.moleculeInProgress=s;const l=Array.isArray(t)?t:[t],c=l.map((k)=>{if(k instanceof Ve)return k;const I=S(k.key),W=e.molecules.get(I);if(!W)throw new Error(`Molecule ${I} not found in store "${e.config.name}"`);return W}),m=new Ve(c,n,o);a.molecules.set(s,m);for(let k of c)k.below.set(m.stringKey,m);const u={get:(...k)=>_(y(r),...k),set:(...k)=>{j(y(r),...k)},seek:(k,I)=>$(y(r),k,I),json:(k)=>V(y(r),k),run:(k,I=pe())=>ye(k,I,y(e)),make:(k,I,W,...w)=>oe(y(r),k,I,W,...w),dispose:(k)=>{D(y(r),k)},env:()=>Pe(y(r)),bond:(k,I)=>{if(k.type==="join"){const{as:W}=I,w=Je(k,r);w.molecules.set(s,m),m.joins.set(k.key,w);const q=F.subject.subscribe(`join:${k.key}-${s}`,(T)=>{if(T.type==="molecule_disposal"&&S(T.token.key)===s)q(),w.molecules.delete(s)});if(W===null)return;const f=k.a===W?k.b:k.a,p=Vt(k,n),g=p[`${f}KeysOf${Xt(W)}`],x=p[`${f}EntriesOf${Xt(W)}`];let A={relatedKeys:g};if(x)A=Object.assign(A,{relatedEntries:x});return A}return Z(m,d(k,r),y(r))},claim:(k,I)=>{const{exclusive:W}=I,w=y(e).molecules.get(S(k.key));if(w)if(W){for(let q of w.above.values())q.below.delete(w.stringKey);w.above.clear(),w.above.set(m.stringKey,m),m.below.set(w.stringKey,w)}else w.above.set(m.stringKey,m),m.below.set(w.stringKey,w)},spawn:(k,I,...W)=>oe(y(e),[m],d(k,e),I,...W)},F=d(o,e),C=F.new;m.instance=new C(u,n,...i);const v={type:"molecule",key:n,family:o},G={type:"molecule_creation",token:v,family:o,context:l,params:i};if(P(a))F.subject.next(G);else if(R(a)&&a.on.transactionApplying.state===null)a.transactionMeta.update.updates.push(G);return a.moleculeInProgress=null,v}function te(e,t,o){const n=e.families.get(t.key);if(n===void 0)throw new N(t,e);const i=n(o),r=y(e);if(i.family&&r.moleculeInProgress===null){if(P(r))switch(i.type){case"atom":case"mutable_atom":e.on.atomCreation.next(i);break;case"selector":case"readonly_selector":e.on.selectorCreation.next(i);break}else if(R(r)&&r.on.transactionApplying.state===null)r.transactionMeta.update.updates.push({type:"state_creation",token:i})}return i}function $(e,t,o){const n=S(o),i=`${t.key}(${n})`,r=y(e);let a;switch(t.type){case"atom_family":case"mutable_atom_family":a=r.atoms.get(i);break;case"selector_family":a=r.selectors.get(i);break;case"readonly_selector_family":a=r.readonlySelectors.get(i);break;case"molecule_family":a=r.molecules.get(S(o))}if(a)return U(a);return a}function h(e,t,o){let n=$(e,t,o);if(n)return n;const i=e.molecules.get(S(o));if(i)return Z(i,t,e);if(e.config.lifespan==="immortal"){const r=ue(t,o);return e.logger.error("\u274C",r.type,r.key,`was not found in store "${e.config.name}"; returned a counterfeit token.`),r}return n=te(e,t,o),n}function D(e,...t){let o,n;if(t.length===1)o=t[0],n=o.key;else{const r=t[0],a=t[1];o=r.type==="molecule_family"?$(e,r,a)??ue(r,a):h(e,r,a)}try{d(o,e)}catch(r){const a=e.disposalTraces.buffer.find((s)=>s?.key===o.key);e.logger.error("\u274C",o.type,o.key,`could not be disposed because it was not found in the store "${e.config.name}".`,a?`\n This state was most recently disposed\n${a.trace}`:"No previous disposal trace was found.");return}switch(o.type){case"atom":case"mutable_atom":nt(o,e);break;case"selector":case"readonly_selector":Et(o,e);break;case"molecule":Be(o,e);break}const{stack:i}=new Error;if(i){const r=i?.split("\n")?.slice(3)?.join("\n");e.disposalTraces.add({key:o.key,trace:r})}}function j(e,...t){let o,n,i,r;if(t.length===2){if(o=t[0],r=t[1],n=Ie(e,o)??null,n)i=o.family?E(o.family.subKey):null,o=h(e,n,i)}else n=t[0],i=t[1],r=t[2],o=h(e,n,i);if("counterfeit"in o){const l=e.disposalTraces.buffer.find((c)=>c?.key===o.key);e.logger.error("\u274C",o.type,o.key,`could not be set because it was not found in the store "${e.config.name}".`,l?`This state was previously disposed:\n${l.trace}`:"No previous disposal trace was found.");return}const a=Ct(e,o);if(a){const l=e.on.operationClose.subscribe(`waiting to set "${o.key}" at T-${a}`,()=>{l(),e.logger.info("\uD83D\uDFE2",o.type,o.key,`resuming deferred setState from T-${a}`),j(e,o,r)});return}const s=d(o,e);ve(s,r,e),Kt(e)}function Ne(e,t,o){const{key:n,newValue:i,oldValue:r}=t,a=e==="newValue"?i:r,s={key:n,type:"atom"};if(t.family)Object.assign(s,{family:t.family});j(o,s,a)}function it(e,t,o){switch(t){case"newValue":{Dt(e,o);break}case"oldValue":{D(o,e.token);break}}}function rt(e,t,o){switch(t){case"newValue":{D(o,e.token);break}case"oldValue":{Dt(e,o),o.valueMap.set(e.token.key,e.value);break}}}function Dt(e,t){const{family:o}=e.token;if(o){const n=t.families.get(o.key);if(n)h(t,n,E(o.subKey))}}function at(e,t,o){switch(t){case"newValue":oe(o,e.context,e.family,e.token.key,...e.params);break;case"oldValue":D(o,e.token);break}}function lt(e,t,o){switch(t){case"newValue":D(o,e.token);break;case"oldValue":{const n=oe(o,e.context,e.family,e.token.key);for(let[i,r]of e.values){const a=`${i}(${S(n.key)})`,s=d(n,o),l=s.tokens.has(a),c=o.families.get(i);if(c&&!l)Z(s,c,o);o.valueMap.set(a,r)}}break}}function Xe(e,t,o){const n=e==="newValue"?t.updates:[...t.updates].reverse();for(let i of n)switch(i.type){case"atom_update":case"selector_update":Ne(e,i,o);break;case"state_creation":it(i,e,o);break;case"state_disposal":rt(i,e,o);break;case"molecule_creation":at(i,e,o);break;case"molecule_disposal":lt(i,e,o);break;case"transaction_update":Xe(e,i,o);break}}function Ht(e,t,o){if(!P(o))return;const i=o.transactionMeta.actionContinuities.getRelatedKey(e);if(i!==void 0)o.transactionMeta.epoch.set(i,t)}var Ut=(e,t)=>{const o=y(t),{parent:n}=o;if(n===null||!R(o)||o.transactionMeta?.phase!=="building"){t.logger.warn("\uD83D\uDC1E","transaction","???","applyTransaction called outside of a transaction. This is probably a bug in AtomIO.");return}o.transactionMeta.phase="applying",o.transactionMeta.update.output=e,n.child=null,n.on.transactionApplying.next(o.transactionMeta);const{updates:i}=o.transactionMeta.update;if(t.logger.info("\uD83D\uDEC4","transaction",o.transactionMeta.update.key,`Applying transaction with ${i.length} updates:`,i),Xe("newValue",o.transactionMeta.update,n),P(n))Ht(o.transactionMeta.update.key,o.transactionMeta.update.epoch,n),d({key:o.transactionMeta.update.key,type:"transaction"},t)?.subject.next(o.transactionMeta.update),t.logger.info("\uD83D\uDEEC","transaction",o.transactionMeta.update.key,"Finished applying transaction.");else if(R(n))n.transactionMeta.update.updates.push(o.transactionMeta.update);n.on.transactionApplying.next(null)};class L extends Map{e;deleted=new Set;constructor(e){super();this.source=e}get(e){if(super.has(e))return super.get(e);if(!this.deleted.has(e)&&this.source.has(e))return this.source.get(e);return}set(e,t){return this.deleted.delete(e),super.set(e,t)}hasOwn(e){return super.has(e)}has(e){return!this.deleted.has(e)&&(super.has(e)||this.source.has(e))}delete(e){return this.deleted.add(e),super.delete(e)}}var Yt=(e,t,o,n)=>{const i=y(o),r={parent:i,child:null,on:i.on,loggers:i.loggers,logger:i.logger,config:i.config,atoms:new L(i.atoms),atomsThatAreDefault:new Set(i.atomsThatAreDefault),families:new L(i.families),operation:{open:!1},readonlySelectors:new L(i.readonlySelectors),timelines:new L(i.timelines),timelineTopics:new X(i.timelineTopics.toJSON()),trackers:new Map,transactions:new L(i.transactions),selectorAtoms:new X(i.selectorAtoms.toJSON()),selectorGraph:new X(i.selectorGraph.toJSON(),{makeContentKey:(...c)=>c.sort().join(":")}),selectors:new L(i.selectors),valueMap:new L(i.valueMap),defaults:i.defaults,disposalTraces:o.disposalTraces.copy(),molecules:new L(i.molecules),moleculeFamilies:new L(i.moleculeFamilies),moleculeInProgress:i.moleculeInProgress,miscResources:new L(i.miscResources)},a=Lt(e,o),s={phase:"building",update:{type:"transaction_update",key:e,id:n,epoch:a===void 0?Number.NaN:a+1,updates:[],params:t,output:void 0},toolkit:{get:(...c)=>_(l,...c),set:(...c)=>{j(l,...c)},run:(c,m=pe())=>ye(c,m,l),find:(c,m)=>h(l,c,m),seek:(c,m)=>$(l,c,m),json:(c)=>V(l,c),make:(c,m,u,...F)=>oe(l,c,m,u,...F),dispose:(...c)=>{D(l,...c)},env:()=>Pe(l)}},l=Object.assign(r,{transactionMeta:s});return i.child=l,o.logger.info("\uD83D\uDEEB","transaction",e,"Building transaction with params:",t),l};function qe(e,t){const o={key:e.key,type:"transaction",run:(r,a)=>{const s=Yt(e.key,r,t,a);try{const l=y(t),{toolkit:c}=s.transactionMeta,m=e.do(c,...r);return Ut(m,l),m}catch(l){throw Mt(n),t.logger.warn("\uD83D\uDCA5","transaction",e.key,"caught:",l),l}},install:(r)=>qe(e,r),subject:new b},n=y(t);n.transactions.set(o.key,o);const i=U(o);return t.on.transactionCreation.next(i),i}function Lt(e,t){const o=P(t),n=o?t.transactionMeta.actionContinuities.getRelatedKey(e):void 0;return o&&n!==void 0?t.transactionMeta.epoch.get(n):void 0}class De{_buffer;_index=0;constructor(e){let t;if(typeof e==="number")t=e;else t=e.length;this._buffer=Array.from({length:t})}get buffer(){return this._buffer}get index(){return this._index}add(e){this._buffer[this._index]=e,this._index=(this._index+1)%this._buffer.length}copy(){const e=new De([...this._buffer]);return e._index=this._index,e}}class qt{parent=null;child=null;valueMap=new Map;defaults=new Map;atoms=new Map;selectors=new Map;readonlySelectors=new Map;atomsThatAreDefault=new Set;selectorAtoms=new X({between:["selectorKey","atomKey"],cardinality:"n:n"});selectorGraph=new X({between:["upstreamSelectorKey","downstreamSelectorKey"],cardinality:"n:n"},{makeContentKey:(...e)=>e.sort().join(":")});trackers=new Map;families=new Map;transactions=new Map;transactionMeta={epoch:new Map,actionContinuities:new X({between:["continuity","action"],cardinality:"1:n"})};timelines=new Map;timelineTopics=new X({between:["timelineKey","topicKey"],cardinality:"1:n"});disposalTraces=new De(100);molecules=new Map;moleculeFamilies=new Map;moleculeInProgress=null;miscResources=new Map;on={atomCreation:new b,atomDisposal:new b,selectorCreation:new b,selectorDisposal:new b,timelineCreation:new b,transactionCreation:new b,transactionApplying:new Qe(null),operationClose:new b,moleculeCreationStart:new b,moleculeCreationDone:new b,moleculeDisposal:new b};operation={open:!1};config={name:"IMPLICIT_STORE",lifespan:"ephemeral"};loggers=[new Ye("warn",(e,t,o)=>!o.includes("\uD83D\uDD0D"))];logger={error:(...e)=>{for(let t of this.loggers)t.error(...e)},info:(...e)=>{for(let t of this.loggers)t.info(...e)},warn:(...e)=>{for(let t of this.loggers)t.warn(...e)}};constructor(e,t=null){if(this.config={...t?.config,...e},t!==null){if(this.valueMap=new Map(t?.valueMap),this.operation={...t?.operation},P(t))this.transactionMeta={epoch:new Map(t?.transactionMeta.epoch),actionContinuities:new X(t?.transactionMeta.actionContinuities.toJSON())};for(let[,n]of t.families){if(n.internalRoles?.includes("mutable")||n.internalRoles?.includes("join"))continue;n.install(this)}const o=new Set;for(let[,n]of t.atoms){if(o.has(n.key))continue;if(n.install(this),n.type==="mutable_atom"){const i=V(t,n),r=se(n);o.add(i.key),o.add(r.key)}}for(let[,n]of t.readonlySelectors)n.install(this);for(let[,n]of t.selectors){if(o.has(n.key))continue;n.install(this)}for(let[,n]of t.transactions)n.install(this);for(let[,n]of t.timelines)n.install(this)}}}var K={get STORE(){if(!globalThis.ATOM_IO_IMPLICIT_STORE)globalThis.ATOM_IO_IMPLICIT_STORE=new qt({name:"IMPLICIT_STORE",lifespan:"ephemeral"});return globalThis.ATOM_IO_IMPLICIT_STORE}};function d(e,t){let o,n=t;while(n!==null){switch(e.type){case"atom":case"mutable_atom":o=n.atoms.get(e.key);break;case"selector":o=n.selectors.get(e.key);break;case"readonly_selector":o=n.readonlySelectors.get(e.key);break;case"atom_family":case"mutable_atom_family":case"selector_family":case"readonly_selector_family":o=n.families.get(e.key);break;case"timeline":o=n.timelines.get(e.key);break;case"transaction":o=n.transactions.get(e.key);break;case"molecule":o=n.molecules.get(S(e.key));break;case"molecule_family":o=n.moleculeFamilies.get(e.key);break}if(o)return o;n=n.child}throw new N(e,t)}var Qt=(e,t)=>{const o=y(t);if(o.operation.open)return o.operation.prev.get(e.key);return o.valueMap.get(e.key)};var ct=(e,t)=>{const o=y(t);return jt(e,t).map((i)=>{const r=o.atoms.get(i);if(r===void 0)throw new Error(`Atom "${i}", a dependency of selector "${e.key}", not found in store "${t.config.name}".`);return r.subject.subscribe(`${e.type}:${e.key}`,(a)=>{t.logger.info("\uD83D\uDCE2",e.type,e.key,"root",i,"went",a.oldValue,"->",a.newValue);const s=Qt(e,o),l=ie(e,o);t.logger.info("\u2728",e.type,e.key,"went",s,"->",l),e.subject.next({newValue:l,oldValue:s})})})};function H(e,t,o,n){function i(u){if(n.operation.open){const F=n.on.operationClose.subscribe(`state subscription ${o}`,()=>{F(),t(u)})}else t(u)}const r=d(e,n);n.logger.info("\uD83D\uDC40",r.type,r.key,`Adding subscription "${o}"`);const a=r.type==="selector"||r.type==="readonly_selector";let s=null,l=i;if(a)s=ct(r,n),l=(u)=>{if(s)s.length=0,s.push(...ct(r,n));i(u)};const c=r.subject.subscribe(o,l);return()=>{if(n.logger.info("\uD83D\uDE48",r.type,r.key,`Removing subscription "${o}"`),c(),s)for(let u of s)u()}}var st=(e,t,o,n)=>{const i=d(e,n);n.logger.info("\uD83D\uDC40","timeline",e.key,`Adding subscription "${o}"`);const r=i.subject.subscribe(o,t);return()=>{n.logger.info("\uD83D\uDE48","timeline",e.key,`Removing subscription "${o}" from timeline`),r()}};class ce{Update;initializeState(e,t){const o=`*${e.key}`;t.atoms.delete(o),t.valueMap.delete(o);const n=e.family?{key:`*${e.family.key}`,subKey:e.family.subKey}:void 0,i=ae(t,{key:o,default:null},n);if(t.parent?.valueMap.has(o)){const r=t.parent.valueMap.get(o);t.valueMap.set(o,r)}return i}unsubscribeFromInnerValue;unsubscribeFromState;observeCore(e,t,o){const n=`tracker:${o.config.name}:${R(o)?o.transactionMeta.update.key:"main"}:${e.key}`,i=_(o,e);this.unsubscribeFromInnerValue=i.subscribe(n,(r)=>{j(o,t,r)}),this.unsubscribeFromState=H(e,(r)=>{if(r.newValue!==r.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=r.newValue.subscribe(n,(a)=>{j(o,t,a)})},n,o)}updateCore(e,t,o){const n=`tracker:${o.config.name}:${R(o)?o.transactionMeta.update.key:"main"}:${e.key}`;H(t,({newValue:i,oldValue:r})=>{const a=o.timelineTopics.getRelatedKey(t.key);if(a){if(o.timelines.get(a)?.timeTraveling){const c=st({key:a,type:"timeline"},(m)=>{c(),j(o,e,(u)=>{if(m==="redo"&&i)u.do(i);else if(m==="undo"&&r)u.undo(r);return u})},n,o);return}}const s=o.on.operationClose.subscribe(n,()=>{s();const l=_(o,e),c=i===null?-1:l.getUpdateNumber(i),m=c-l.cacheUpdateNumber;if(i&&m===1)j(o,e,(u)=>(u.do(i),u));else o.logger.info("\u274C","mutable_atom",e.key,`could not be updated. Expected update number ${l.cacheUpdateNumber+1}, but got ${c}`)})},n,o)}mutableState;latestUpdateState;dispose;constructor(e,t){this.mutableState=e;const o=y(t);this.latestUpdateState=this.initializeState(e,o),this.observeCore(e,this.latestUpdateState,o),this.updateCore(e,this.latestUpdateState,o),o.trackers.set(e.key,this),this.dispose=()=>{this.unsubscribeFromInnerValue(),this.unsubscribeFromState(),o.trackers.delete(e.key)}}}function we(e,t,o){e.logger.info("\uD83D\uDD28","atom",t.key,`creating in store "${e.config.name}"`);const n=y(e),i=n.atoms.get(t.key);if(i&&i.type==="mutable_atom")return e.logger.error("\u274C","atom",t.key,"Tried to create atom, but it already exists in the store."),U(i);const r=new b,a={...t,type:"mutable_atom",install:(c)=>{return c.logger.info("\uD83D\uDEE0\uFE0F","atom",t.key,`installing in store "${c.config.name}"`),we(c,t,o)},subject:r};if(o)a.family=o;const s=t.default();n.atoms.set(a.key,a),He(t.key,e),Y(t.key,s,r,n);const l=U(a);if(t.effects){let c=0;const m=[];for(let u of t.effects){const F=u({setSelf:(C)=>{j(e,l,C)},onSet:(C)=>H(l,C,`effect[${c}]`,e)});if(F)m.push(F);++c}a.cleanup=()=>{for(let u of m)u()}}if(new ce(l,e),!o)Zt(l,t,e);return l}class mt{Update;latestUpdateAtoms;mutableAtoms;constructor(e,t){const o=re(t,{key:`*${e.key}`,default:null},["mutable","updates"]);this.latestUpdateAtoms=d(o,t),this.mutableAtoms=e,this.mutableAtoms.subject.subscribe(`store=${t.config.name}::tracker-atom-family`,(n)=>{if(n.token.family){const i=E(n.token.family.subKey);$(t,this.latestUpdateAtoms,i),new ce(n.token,t)}}),this.latestUpdateAtoms.subject.subscribe(`store=${t.config.name}::tracker-atom-family`,(n)=>{if(n.token.family){const i=E(n.token.family.subKey),r=$(t,this.mutableAtoms,i);if(r)new ce(r,t)}})}}function Me(e,t,o){const n={key:t.key,type:"mutable_atom_family"},i=e.families.get(t.key);if(i)e.logger.error("\u2757","mutable_atom_family",t.key,`Overwriting an existing ${Q(i)} "${i.key}" in store "${e.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);const r=new b,s=Object.assign((l)=>{const c=S(l),m={key:t.key,subKey:c},u=`${t.key}(${c})`,F=y(e),C={key:u,default:()=>t.default(l),toJson:t.toJson,fromJson:t.fromJson,mutable:!0};if(t.effects)C.effects=t.effects(l);const v=we(F,C,m);return r.next({type:"state_creation",token:v}),v},n,{subject:r,install:(l)=>Me(l,t),toJson:t.toJson,fromJson:t.fromJson,internalRoles:o});return e.families.set(t.key,s),Gt(s,t,e),new mt(s,e),n}var tt=(e,t)=>{const o=y(t),n=`${e.key}:JSON`;return o.families.get(n)};var V=(e,t)=>{if(t.family){const n=y(e),r={key:`${t.family.key}:JSON`,type:"selector_family"},a=d(r,n),s=JSON.parse(t.family.subKey);return h(e,a,s)}return{type:"selector",key:`${t.key}:JSON`}};var se=(e)=>{const o={type:"atom",key:`*${e.key}`};if(e.family)o.family={key:`*${e.family.key}`,subKey:e.family.subKey};return o};function Ot(e){return typeof e==="object"&&e!==null&&"do"in e&&"undo"in e&&"subscribe"in e}function Fe(e,t,o){const n=t.valueMap.get(e.key),i=o.valueMap.get(e.key);if(n===i){if(n===void 0)return typeof e.default==="function"?e.default():e.default;t.logger.info("\uD83D\uDCC3","atom",e.key,"copying");const r=e.toJson(n),a=e.fromJson(r);return o.valueMap.set(e.key,a),new ce(e,t),a}return i}function Y(e,t,o,n){const i=n.valueMap.get(e);if(i instanceof ge)i.use(t);if(t instanceof Promise){const r=new ge(t);return n.valueMap.set(e,r),r.then((a)=>{Y(e,a,o,n),o.next({newValue:a,oldValue:r})}).catch((a)=>{n.logger.error("\uD83D\uDCA5","state",e,"rejected:",a)}),r}return n.valueMap.set(e,t),t}var Rt=(e,t)=>{let o=t.valueMap.get(e.key);if(e.type==="mutable_atom"&&R(t)){const{parent:n}=t;o=Fe(e,n,t)}return o},ht=(e,t)=>{const o=t.valueMap.get(e);if(o instanceof ge){const n=o,i=t.selectors.get(e)??t.readonlySelectors.get(e);if(i)n.use(i.get());return}if(t.operation.open)t.operation.prev.set(e,o);t.valueMap.delete(e),t.logger.info("\uD83D\uDDD1","state",e,"evicted")};var It=(e,t)=>{return y(t).atomsThatAreDefault.has(e)},He=(e,t)=>{const o=y(t);o.atomsThatAreDefault=new Set(o.atomsThatAreDefault).add(e)},Wt=(e,t)=>{const o=y(t);o.atomsThatAreDefault=new Set(y(t).atomsThatAreDefault),o.atomsThatAreDefault.delete(e)};function ae(e,t,o){e.logger.info("\uD83D\uDD28","atom",t.key,`creating in store "${e.config.name}"`);const n=y(e),i=n.atoms.get(t.key);if(i&&i.type==="atom")return e.logger.error("\u274C","atom",t.key,"Tried to create atom, but it already exists in the store."),U(i);const r=new b,a={...t,type:"atom",install:(c)=>{return c.logger.info("\uD83D\uDEE0\uFE0F","atom",t.key,`installing in store "${c.config.name}"`),ae(c,t,o)},subject:r};if(o)a.family=o;let s=t.default;if(t.default instanceof Function)s=t.default();n.atoms.set(a.key,a),He(t.key,e),Y(t.key,s,r,n);const l=U(a);if(t.effects){let c=0;const m=[];for(let u of t.effects){const F=u({setSelf:(C)=>{j(e,l,C)},onSet:(C)=>H(l,C,`effect[${c}]`,e)});if(F)m.push(F);++c}a.cleanup=()=>{for(let u of m)u()}}return l}function Ft(e,t){if("mutable"in t){const i=we(e,t,void 0);return e.on.atomCreation.next(i),i}const n=ae(e,t,void 0);return e.on.atomCreation.next(n),n}function nt(e,t){const o=y(t),{key:n}=e,i=d(e,o);if(!i.family)t.logger.error("\u274C","atom",n,"Standalone atoms cannot be disposed.");else{i.cleanup?.();const r=t.valueMap.get(i.key);d({key:i.family.key,type:"atom_family"},t).subject.next({type:"state_disposal",token:e,value:r});const s=o.molecules.get(i.family.subKey);if(s)s.tokens.delete(n);if(o.atoms.delete(n),o.valueMap.delete(n),o.selectorAtoms.delete(n),o.atomsThatAreDefault.delete(n),o.timelineTopics.delete(n),e.type==="mutable_atom"){const l=se(e);nt(l,t),t.trackers.delete(n)}if(t.logger.info("\uD83D\uDD25","atom",n,"deleted"),R(o)&&o.transactionMeta.phase==="building")o.transactionMeta.update.updates.push({type:"state_disposal",token:e});else t.on.atomDisposal.next(e)}}var Zt=(e,t,o=K.STORE)=>{return xe(o,{key:`${e.key}:JSON`,get:({get:n})=>t.toJson(n(e)),set:({set:n},i)=>{n(e,t.fromJson(i))}})};function Gt(e,t,o=K.STORE){const n=Ke(o,{key:`${e.key}:JSON`,get:(r)=>({seek:a,get:s})=>{const l=a(e,r);if(l)return t.toJson(s(l));const c=S(r),m=o.molecules.get(c);if(m){const F=Z(m,e,o);return t.toJson(s(F))}if(o.config.lifespan==="immortal")throw new Error(`No molecule found for key "${c}"`);const u=te(o,e,r);return t.toJson(s(u))},set:(r)=>({seek:a,set:s},l)=>{const c=a(e,r);if(c)s(c,t.fromJson(l));else{const m=S(r),u=o.molecules.get(m);if(u){const F=Z(u,e,o);s(F,t.fromJson(l))}else{if(o.config.lifespan==="immortal")throw new Error(`No molecule found for key "${m}"`);s(te(o,e,r),t.fromJson(l))}}}},["mutable","json"]);return d(e,o).subject.subscribe(`store=${o.config.name}::json-selector-family`,(r)=>{if(r.token.family)$(o,n,E(r.token.family.subKey))}),n}var E=(e)=>JSON.parse(e),S=(e)=>JSON.stringify(e),Pm=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];class Se{e;listeners;globalListeners;handleEvent(e,...t){for(let n of this.globalListeners)n(e,...t);const o=this.listeners.get(e);if(o)for(let n of o)n(...t)}id="no_id_retrieved";constructor(e){this.emit=e;this.listeners=new Map,this.globalListeners=new Set}on(e,t){const o=this.listeners.get(e);if(o)o.add(t);else this.listeners.set(e,new Set([t]));return this}onAny(e){return this.globalListeners.add(e),this}off(e,t){const o=this.listeners.get(e);if(o)if(t)o.delete(t);else this.listeners.delete(e);return this}offAny(e){return this.globalListeners.delete(e),this}}class yt extends Se{e;t;o;incompleteData="";unprocessedEvents=[];incompleteLog="";unprocessedLogs=[];id="#####";handleLog(e){if(Array.isArray(e)){const[t,...o]=e;switch(t){case"i":this.logger.info(this.id,this.key,...o);break;case"w":this.logger.warn(this.id,this.key,...o);break;case"e":this.logger.error(this.id,this.key,...o);break}}}constructor(e,t,o=console){super((n,...i)=>{const r=JSON.stringify([n,...i])+"\x03",a=(s)=>{if(s.code==="EPIPE")console.error("EPIPE error during write",this.process.stdin);this.process.stdin.removeListener("error",a)};return this.process.stdin.once("error",a),this.process.stdin.write(r),this});this.process=e;this.key=t;this.logger=o;if(this.process=e,this.process.stdout.on("data",(n)=>{const i=n.toString();if(i==="\u2728")return;this.unprocessedEvents.push(...i.split("\x03"));const r=this.unprocessedEvents.shift();this.incompleteData+=r??"";try{if(this.incompleteData.startsWith("error"))console.log("\u2757",this.incompleteData);let a=E(this.incompleteData);this.handleEvent(...a);while(this.unprocessedEvents.length>0){const s=this.unprocessedEvents.shift();if(s){if(this.unprocessedEvents.length===0)this.incompleteData=s;a=E(s),this.handleEvent(...a)}}this.incompleteData=""}catch(a){console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.warn(this.incompleteData),console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.error(a)}}),this.process.stderr.on("data",(n)=>{const i=n.toString();this.unprocessedLogs.push(...i.split("\x03"));const r=this.unprocessedLogs.shift();this.incompleteLog+=r??"";try{let a=E(this.incompleteLog);this.handleLog(a);while(this.unprocessedLogs.length>0)if(this.incompleteLog=this.unprocessedLogs.shift()??"",this.incompleteLog)a=E(this.incompleteLog),this.handleLog(a)}catch(a){console.error("\u274C\u274C\u274C"),console.error(this.incompleteLog),console.error(a),console.error("\u274C\u274C\u274C\uFE0F")}}),e.pid)this.id=e.pid.toString()}}class eo extends Se{in;out;id="no_id_retrieved";disposalFunctions=[];constructor(e){super((...t)=>{return this.out.next(t),this});this.id=e,this.in=new b,this.out=new b,this.in.subscribe("socket",(t)=>{this.handleEvent(...t)})}dispose(){for(let e of this.disposalFunctions)e()}}class ft extends Se{incompleteData="";unprocessedEvents=[];relays;relayServices;process;id="#####";log(...e){this.process.stderr.write(S(e.map((t)=>t instanceof z?`{ ${t.toJSON().members.join(" | ")} }`:t))+"\x03")}logger={info:(...e)=>{this.log("i",...e)},warn:(...e)=>{this.log("w",...e)},error:(...e)=>{this.log("e",...e)}};constructor(){super((e,...t)=>{const o=JSON.stringify([e,...t]);return this.process.stdout.write(o+"\x03"),this});if(this.process=process,this.process.stdin.resume(),this.relays=new Map,this.relayServices=[],this.process.stdin.on("data",(e)=>{const t=e.toString();this.unprocessedEvents.push(...t.split("\x03"));const o=this.unprocessedEvents.shift();this.incompleteData+=o??"";try{const n=E(this.incompleteData);this.logger.info("\uD83C\uDFB0","received",n),this.handleEvent(...n);while(this.unprocessedEvents.length>0){const i=this.unprocessedEvents.shift();if(i){if(this.unprocessedEvents.length===0)this.incompleteData=i;const r=E(i);this.handleEvent(...r)}}this.incompleteData=""}catch(n){if(n instanceof Error)this.logger.error("\u2757",n.message,n.cause,n.stack)}}),this.on("exit",()=>{this.logger.info("\uD83D\uDD25",this.id,'received "exit"'),process.exit(0)}),process.on("exit",(e)=>{this.logger.info("\uD83D\uDD25",this.id,`exited with code ${e}`)}),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",(e)=>{this.logger.info("\uD83D\uDC64","user",e,"joined");const t=new eo(`user:${e}`);this.relays.set(e,t),this.logger.info("\uD83D\uDD17","attaching services:",`[${[...this.relayServices.keys()].join(", ")}]`);for(let o of this.relayServices){const n=o(t);if(n)t.disposalFunctions.push(n)}this.on(`user:${e}`,(...o)=>{t.in.next(o)}),t.out.subscribe("socket",(o)=>{this.emit(...o)})}),this.on("user-leaves",(e)=>{const t=this.relays.get(e);if(this.off(`relay:${e}`),t)t.dispose(),this.relays.delete(e)}),process.stdout.write("\u2728")}relay(e){this.logger.info("\uD83D\uDD17","running relay method"),this.relayServices.push(e)}}class to extends Map{set(e,t){if(this.has(e))return console.warn("Tried to set a key that already exists in an InvariantMap",{key:e,value:t}),this;return super.set(e,t)}clear(){throw new Error("Cannot clear an InvariantMap")}}class pt{e;type="continuity";globals=[];actions=[];perspectives=[];constructor(e){this.key=e}static existing=new to;static create(e,t){const o=new pt(e),{type:n,globals:i,actions:r,perspectives:a}=t(o),s={type:n,key:e,globals:i,actions:r,perspectives:a};return pt.existing.set(e,s),s}add(...e){switch(e[0].type){case"atom":case"mutable_atom":this.globals.push(...e);break;case"transaction":this.actions.push(...e);break;case"atom_family":{const[o,n]=e;this.perspectives.push({type:"realtime_perspective",resourceAtoms:o,viewAtoms:n})}break}return this}}var Ty=Te({key:"usersInRoomIndex",mutable:!0,default:()=>new z,toJson:(e)=>e.toJSON(),fromJson:(e)=>z.fromJSON(e)}),ut=Te({key:"roomIndex",default:()=>new z,mutable:!0,toJson:(e)=>e.toJSON(),fromJson:(e)=>z.fromJSON(e)}),uo={enteredAtEpoch:0},he=Ee({key:"usersInRooms",between:["room","user"],cardinality:"1:n"},uo),dy=$e({key:"usersInMyRoomView",get:(e)=>({find:t})=>{const o=Nt(he);return[t(o,e)]}});import{spawn as To}from"child_process";var Tt=me({key:"roomArguments",default:["echo",["Hello World!"]]}),oo=$e({key:"room",get:(e)=>async({get:t,find:o})=>{const n=o(Tt,e),i=t(n),[r,a]=i,s=await new Promise((l)=>{const c=To(r,a,{env:process.env}),m=(u)=>{if(u.toString()==="\u2728")c.stdout.off("data",m),l(c)};c.stdout.on("data",m)});return new yt(s,e)}});var hy=Ae({key:"createRoom",do:({get:e,set:t,find:o},n,i,r)=>{const a=r?[i,r]:[i],s=o(Tt,n);t(s,a),t(ut,(m)=>m.add(n));const l=o(oo,n);return e(l)}}),$y=Ae({key:"joinRoom",do:(e,t,o,n)=>{const i={enteredAtEpoch:n};return ze(he,(r)=>{r.set({room:t,user:o},i)},e.env().store),i}}),Oy=Ae({key:"leaveRoom",do:(e,t,o)=>{ze(he,(n)=>{n.delete({room:t,user:o})},e.env().store)}}),vy=Ae({key:"destroyRoom",do:(e,t)=>{ze(he,(o)=>{o.delete({room:t})},e.env().store),e.set(ut,(o)=>(o.delete(t),o))}});var _y=me({key:"transactionRedactor",default:{occlude:(e)=>e}}),So=me({key:"unacknowledgedUpdates",default:()=>[]});var ko=me({key:"sockets",default:null}),Py=Te({key:"socketsIndex",mutable:!0,default:()=>new z,toJson:(e)=>e.toJSON(),fromJson:(e)=>z.fromJSON(e)}),Vy=Te({key:"usersIndex",mutable:!0,default:()=>new z,toJson:(e)=>e.toJSON(),fromJson:(e)=>z.fromJSON(e)}),bo=Ee({key:"usersOfSockets",between:["user","socket"],cardinality:"1:1"});var{file:no,serve:Ao}=globalThis.Bun;var{MODE:Mf,FRONTEND_PORT:dt,BACKEND_PORT:Rf}=process.env;function kt(){fe.logger.info("\uD83D\uDEEC frontend server exiting"),process.exit(0)}var fe=new ft;fe.logger.info(" ready");var St=io(import.meta.dir,"..","app");Ao({port:dt??3333,async fetch(e,t){const o=new URL(e.url),n=t.requestIP(e)?.address??"??";if(fe.logger.info(`[${n}]`,e.method,o.pathname),o.pathname==="/")return new Response(Bun.file(io(St,"index.html")));if(o.pathname==="/index.html")return Response.redirect("/");const i=go(St,o.pathname),r=xo(i);if(!r.startsWith(St))return new Response("403: Forbidden",{status:403});return await no(r).exists()?new Response(no(r)):new Response("404: Not Found",{status:404})}});process.on("SIGINT",()=>{fe.logger.info("\u2757 received SIGINT; exiting gracefully"),kt()});process.on("SIGTERM",()=>{fe.logger.info("\u2757 received SIGTERM; exiting gracefully"),kt()});process.on("exit",()=>{fe.logger.info("\u2757 received exit; exiting gracefully"),kt()});fe.logger.info(`\uD83D\uDEEB frontend server running at http://localhost:${dt??3333}/`);
|
|
3
|
+
import{join as Y0,normalize as E0,resolve as FJ}from"path";function zt(o=Math.random){return o().toString(36).slice(2)}class oS extends Promise{fate;resolve;reject;done=!1;constructor(o){let n,t;super((S,f)=>{n=S,t=f});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){const 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 iM(o){return Object.entries(o)}var vM=(o,n,t=ko.STORE)=>{return En(t,{key:`${o.key}:JSON`,get:({get:S})=>n.toJson(S(o)),set:({set:S},f)=>{S(o,n.fromJson(f))}})};function m(o){while(o.child!==null)o=o.child;return o}function qM(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){const n=this.subscribers.values();for(let t of n)t(o)}}class lf extends s{state;constructor(o){super();this.state=o}next(o){this.state=o,super.next(o)}}function jn(o,n,t){const S={key:n.key,type:"atom_family"},f=o.families.get(n.key);if(f)o.logger.error("\u2757","atom_family",n.key,`Overwriting an existing ${zn(f)} "${f.key}" in store "${o.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);const T=new s,F=Object.assign((k)=>{const A=l(k),$={key:n.key,subKey:A},O=`${n.key}(${A})`,w=m(o),z=n.default,r={key:O,default:z instanceof Function?z(k):z};if(n.effects)r.effects=n.effects(k);const H=nn(w,r,$);return T.next({type:"state_creation",token:H}),H},S,{subject:T,install:(k)=>jn(k,n),internalRoles:t});return o.families.set(n.key,F),o.defaults.set(n.key,n.default),S}function pM(o,n){if("mutable"in n)return nS(o,n);return jn(o,n)}function hn(o,n,t){const S={key:n.key,type:"readonly_selector_family"},f=o.families.get(n.key);if(f)o.logger.error("\u2757","readonly_selector_family",n.key,`Overwriting an existing ${zn(f)} "${f.key}" in store "${o.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);const T=new s,F=Object.assign((k)=>{const A=l(k),$={key:n.key,subKey:A},O=`${n.key}(${A})`,w=m(o),z=tS(w,{key:O,get:n.get(k)},$);return T.next({type:"state_creation",token:z}),z},S,{internalRoles:t,subject:T,install:(k)=>hn(k,n),default:(k)=>{return n.get(k)({get:(...$)=>zo(o,...$),find:($,O)=>Ro(o,$,O),seek:($,O)=>Eo(o,$,O),json:($)=>ho(o,$)})}});return o.families.set(n.key,F),S}function SS(o,n){if("set"in n)return fS(o,n);return hn(o,n)}function Gt(o,n){const t=l(n),S=`${o.key}(${t})`,f=oy[o.type],T={key:S,type:f};if(f==="molecule")Object.assign(T,{key:n,family:o});else Object.assign(T,{family:{key:o.key,subKey:t}});return Object.assign(T,{counterfeit:!0}),T}var oy={atom_family:"atom",mutable_atom_family:"mutable_atom",selector_family:"selector",readonly_selector_family:"readonly_selector",molecule_family:"molecule"};function Po(o){const n={key:o.key,type:o.type};if("family"in o)n.family=o.family;return n}function Ht(o){return ZM(ko.STORE,o)}function kt(o){return pM(ko.STORE,o)}function ef(...o){if(o.length===2)return zo(ko.STORE,...o);return zo(ko.STORE,...o)}var df=(o)=>(n,t,S,f,...T)=>{console[o](`${n} ${t} "${S}" ${f}`,...T)},ny={error:df("error"),info:df("info"),warn:df("warn")};class uf{o;n;t;constructor(o,n,t=ny){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 vS(o){return SS(ko.STORE,o)}function TS(o){return af(o,ko.STORE)}class Fn{a;b;cardinality;relations=new Map;contents=new Map;isContent;makeContentKey=(o,n)=>`${o}:${n}`;warn;getRelatedKeys(o){return this.relations.get(o)}addRelation(o,n){let t=this.relations.get(o),S=this.relations.get(n);if(t)t.add(n);else t=new Set([n]),this.relations.set(o,t);if(S)S.add(o);else S=new Set([o]),this.relations.set(n,S)}deleteRelation(o,n){const t=this.relations.get(o);if(t){if(t.delete(n),t.size===0)this.relations.delete(o);const S=this.relations.get(n);if(S){if(S.delete(o),S.size===0)this.relations.delete(n)}}}replaceRelationsUnsafely(o,n){this.relations.set(o,new Set(n));for(let t of n){const S=new Set([o]);this.relations.set(t,S)}}replaceRelationsSafely(o,n){const t=this.relations.get(o);if(t)for(let S of t){const f=this.relations.get(S);if(f){if(f.size===1)this.relations.delete(S);else f.delete(o);this.contents.delete(this.makeContentKey(o,S))}}this.relations.set(o,new Set(n));for(let S of n){let f=this.relations.get(S);if(f)f.add(o);else f=new Set([o]),this.relations.set(S,f)}}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,S])=>[t,new Set(S)])),this.contents=new Map(o.contents);if(this.isContent=n?.isContent??null,n?.makeContentKey)this.makeContentKey=n.makeContentKey;if(n?.externalStore){const t=n.externalStore;if(this.has=(S,f)=>t.has(S,f),this.addRelation=(S,f)=>{t.addRelation(S,f)},this.deleteRelation=(S,f)=>{t.deleteRelation(S,f)},this.replaceRelationsSafely=(S,f)=>{t.replaceRelationsSafely(S,f)},this.replaceRelationsUnsafely=(S,f)=>{t.replaceRelationsUnsafely(S,f)},this.getRelatedKeys=(S)=>t.getRelatedKeys(S),t.getContent)this.getContentInternal=(S)=>{return t.getContent(S)},this.setContent=(S,f)=>{t.setContent(S,f)},this.deleteContent=(S)=>{t.deleteContent(S)};for(let[S,f]of o.relations??[])for(let T of f)this.addRelation(S,T);for(let[S,f]of o.contents??[])this.setContent(S,f)}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){const t=typeof n[0]==="string"?n[0]:o[this.b],S=n[1]??typeof n[0]==="string"?void 0:n[0];switch(o=typeof o==="string"?o:o[this.a],this.cardinality){case"1:1":{const f=this.getRelatedKey(o);if(f&&f!==t)this.delete(f,o)}case"1:n":{const f=this.getRelatedKey(t);if(f&&f!==o)this.delete(f,t)}}if(S){const f=this.makeContentKey(o,t);this.setContent(f,S)}return this.addRelation(o,t),this}delete(o,n){n=typeof n==="string"?n:o[this.b];const t=typeof o==="string"?o:o[this.a];if(t===void 0&&typeof n==="string"){const S=this.getRelatedKeys(n);if(S)for(let f of S)this.delete(f,n)}if(typeof t==="string"&&n===void 0){const S=this.getRelatedKeys(t);if(S)for(let f of S)this.delete(t,f)}if(typeof t==="string"&&typeof n==="string"){this.deleteRelation(t,n);const S=this.makeContentKey(t,n);this.deleteContent(S)}return this}getRelatedKey(o){const 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.`);for(let t of n)return t}}replaceRelations(o,n,t){const S=!Array.isArray(n),f=S?Object.keys(n):n;if(t?.reckless)this.replaceRelationsUnsafely(o,f);else this.replaceRelationsSafely(o,f);if(S)for(let T of f){const M=this.makeContentKey(o,T),F=n[T];this.setContent(M,F)}return this}getContent(o,n){const t=this.makeContentKey(o,n);return this.getContentInternal(t)}getRelationEntries(o){const n=o[this.a],t=o[this.b];if(n!==void 0&&t===void 0){const S=this.getRelatedKeys(n);if(S)return[...S].map((f)=>{return[f,this.getContent(n,f)??null]})}if(n===void 0&&t!==void 0){const S=this.getRelatedKeys(t);if(S)return[...S].map((f)=>{return[f,this.getContent(f,t)??null]})}return[]}has(o,n){if(n)return this.getRelatedKeys(o)?.has(n)??!1;return this.relations.has(o)}}function bo(o){return"epoch"in o.transactionMeta}function Fo(o){return"phase"in o.transactionMeta}var gM=(o)=>{const n=m(o);if(!Fo(n)){o.logger.warn("\uD83D\uDC1E","transaction","???","abortTransaction called outside of a transaction. This is probably a bug in AtomIO.");return}o.logger.info("\uD83E\uDE82","transaction",n.transactionMeta.update.key,"Aborting transaction"),n.parent.child=null};function zn(o){return o.type.split("_").map(ty).join(" ")}var ty=(o)=>o[0].toUpperCase()+o.slice(1);class tn extends Error{constructor(...o){const 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{const S=o[1];super(`${zn(n)} "${n.key}" member ${l(S)} not found in store "${t.config.name}".`)}}}function At(o,n,t){return(...S)=>{const f=u(o,t);if(f)return f.run(S,n);throw new tn(o,t)}}var qS=(o)=>(n)=>o instanceof Function?o(n):o;var en=(o,n)=>{if(n.valueMap.has(o.key))return n.logger.info("\uD83D\uDCD6",o.type,o.key,"reading cached value"),lM(o,n);if(o.type==="selector"||o.type==="readonly_selector")return n.logger.info("\uD83E\uDDEE",o.type,o.key,"computing value"),o.get();const 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 eM=(o,n)=>{if(o.operation.open){const t=performance.now();return o.logger.info("\u2757",n.type,n.key,`deferring setState at T-${t} until setState for "${o.operation.token.key}" is done`),t}o.operation={open:!0,done:new Set,prev:new Map,time:Date.now(),token:n},o.logger.info("\u2B55",n.type,n.key,`operation start in store "${o.config.name}"${!Fo(o)?"":` ${o.transactionMeta.phase} "${o.transactionMeta.update.key}"`}`)},dM=(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)},uM=(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)},mt=(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 aM=(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 sf=(o,n)=>{const t=m(n),S=t.selectorAtoms.getRelatedKeys(o.key);if(t.logger.info("\uD83E\uDDF9",o.type,o.key,S?`evicting ${S.size} states downstream:`:"no downstream states",S??"to evict"),S){if(t.operation.open)t.logger.info("\uD83E\uDDF9",o.type,o.key,`[ ${[...t.operation.done].join(", ")} ] already done`);for(let f of S){if(uM(t,f))continue;sM(f,t),mt(t,f)}}};function Sy(o,n){if(nF(n.newValue))return!1;if(o.includes("\uD83D\uDD0D"))return!1;return!0}var oF=(o,n,t)=>{const{key:S}=o,f=m(t);if(!Fo(f)||f.transactionMeta.phase!=="building"){t.logger.error("\uD83D\uDC1E","atom",S,"stowUpdate called outside of a transaction. This is probably a bug.");return}if(!Sy(S,n))return;const M={type:"atom_update",key:S,...n};if(o.family)M.family=o.family;f.transactionMeta.update.updates.push(M),t.logger.info("\uD83D\uDCC1","atom",S,"stowed (",n.oldValue,"->",n.newValue,")")};var tF=(o,n,t)=>{const S=en(o,t);let f=S;if(o.type==="mutable_atom"&&Fo(t)){const{parent:M}=t;f=MS(o,M,t)}if(f=qS(n)(f),t.logger.info("\uD83D\uDCDD","atom",o.key,"set to",f),f=Rn(o.key,f,o.subject,t),SF(o.key,t))fF(o.key,t);mt(t,o.key),sf(o,t);const T={oldValue:S,newValue:f};if(bo(t))aM(o,T,t);else if(t.parent){if(t.on.transactionApplying.state===null)oF(o,T,t);else if(o.key.startsWith("*")){const M=o.key.slice(1),F=t.atoms.get(M);let k=t.valueMap.get(M);if(F.type==="mutable_atom"&&Fo(t)){const{parent:$}=t;k=MS(F,$,t)}if(k.do(T.newValue)===null)sf(F,t)}}};var pS=(o,n,t)=>{switch(o.type){case"atom":case"mutable_atom":tF(o,n,t);break;case"selector":o.set(n);break}};function ZS(o,n){if(n.family){const t=o.families.get(n.family.key);if(t)return t}}function ro(o,...n){let t,S,f,T;if(n.length===2){if(t=n[0],T=n[1],S=ZS(o,t)??null,S)f=t.family?Uo(t.family.subKey):null,t=Ro(o,S,f)}else S=n[0],f=n[1],T=n[2],t=Ro(o,S,f);if("counterfeit"in t){const k=o.disposalTraces.buffer.find((A)=>A?.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}".`,k?`This state was previously disposed:\n${k.trace}`:"No previous disposal trace was found.");return}const M=eM(o,t);if(M){const k=o.on.operationClose.subscribe(`waiting to set "${t.key}" at T-${M}`,()=>{k(),o.logger.info("\uD83D\uDFE2",t.type,t.key,`resuming deferred setState from T-${M}`),ro(o,t,T)});return}const F=u(t,o);pS(F,T,o),dM(o)}function PS(o,n,t){const{key:S,newValue:f,oldValue:T}=n,M=o==="newValue"?f:T,F={key:S,type:"atom"};if(n.family)Object.assign(F,{family:n.family});ro(t,F,M)}function oT(o,n,t){const S=l(t);try{const f=[];let T;if(n==="root")f.push(o.molecules.get('"root"')),T="all";else if(n[0][0]===TF){T="any";const $=l(n),O=o.molecules.get($);if(!O)throw new Error(`Molecule ${$} not found in store "${o.config.name}"`);f.push(O)}else if(t[0][0]===TF){T="all";for(let O of n){const w=l(O),z=o.molecules.get(w);if(!z)throw new Error(`Molecule ${w} not found in store "${o.config.name}"`);f.push(z)}}else{T="any";const O=l(n),w=o.molecules.get(O);if(!w)throw new Error(`Molecule ${O} not found in store "${o.config.name}"`);f.push(w)}const M=new Qt(f,t);M._dependsOn=T,o.molecules.set(S,M);for(let $ of f)$.below.set(M.stringKey,M);const F={type:"molecule_creation",subType:"modern",key:M.key,provenance:n},k=m(o);if(Fo(k)&&k.transactionMeta.phase==="building")k.transactionMeta.update.updates.push(F);else k.on.moleculeCreationStart.next(F)}catch(f){if(f instanceof Error)o.logger.error("\u274C","molecule",S,"allocation failed:",f.message)}return t}function FS(o,n){const t=l(n),S=o.molecules.get(t);if(!S)throw new Error(`Molecule ${t} not found in store "${o.config.name}"`);for(let A of S.joins.values())A.relations.delete(S.key),A.molecules.delete(S.stringKey);let f;if(S.above.size===1)f=S.above.values().next().value.key;else f=[...S.above.values()].map(({key:A})=>A);const T=[];for(let A of S.tokens.values()){const $=A.family;T.push([$.key,o.valueMap.get(A.key)])}for(let A of S.tokens.values())uo(o,A);for(let A of S.below.values())if(A.dependsOn==="all")FS(o,A.key);else if(A.above.delete(S.stringKey),A.above.size===0)FS(o,A.key);S.below.clear();const M={type:"molecule_disposal",subType:"modern",key:S.key,values:T,provenance:f},F=m(o);if(Fo(F)&&F.transactionMeta.phase==="building")F.transactionMeta.update.updates.push(M);else F.on.moleculeDisposal.next(M);F.molecules.delete(S.stringKey);for(let A of S.above.values())A.below.delete(S.stringKey)}var kW=Symbol("provenance"),TF="T$";function MF(o,n){const t=new s,S={type:"molecule_family",key:n.key,dependsOn:n.dependsOn??"all"},f={...S,subject:t,new:n.new};return o.moleculeFamilies.set(n.key,f),S}function Gn(o,n,t){const S=xn(t,n,o.key);o.tokens.set(S.key,S);const f=Fo(t)&&t.transactionMeta.phase==="building",T=t.moleculeInProgress===o.key;if(!f&&!T)o.subject.next({type:"state_creation",token:S});return S}class co extends Set{mode="record";subject=new s;cacheLimit=0;cache=[];cacheIdx=-1;cacheUpdateNumber=-1;constructor(o,n=0){super(o);if(o instanceof co)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){const n=new co(o.members,o.cacheLimit);return n.cache=o.cache,n.cacheIdx=o.cacheIdx,n.cacheUpdateNumber=o.cacheUpdateNumber,n}add(o){const n=super.add(o);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`add:${l(o)}`);return n}clear(){const o=this.mode==="record"?[...this]:null;if(super.clear(),o)this.cacheUpdateNumber++,this.emit(`clear:${JSON.stringify(o)}`)}delete(o){const 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 co(this);const n=this.child._subscribe("transaction",(t)=>{this.transactionUpdates?.push(t)});try{if(o(this.child)){for(let S of this.transactionUpdates)this.doStep(S);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){const n=o.indexOf(":"),t=o.substring(0,n),S=o.substring(n+1);switch(t){case"add":this.add(JSON.parse(S));break;case"clear":this.clear();break;case"del":this.delete(JSON.parse(S));break;case"tx":for(let f of S.split(";"))this.doStep(f)}}getUpdateNumber(o){const n=o.indexOf("=");return Number(o.substring(0,n))}do(o){const n=o.indexOf("="),t=Number(o.substring(0,n)),S=t-this.cacheUpdateNumber;if(S>0){if(S===1){this.mode="playback";const T=o.substring(n+1);return this.doStep(T),this.mode="record",this.cacheUpdateNumber=t,null}return this.cacheUpdateNumber+1}if(Math.abs(S)<this.cacheLimit){const T=this.cacheIdx+S;if(this.cache[T]===o)return null;this.mode="playback";let F=!1;while(!F){this.cacheIdx%=this.cacheLimit;const A=this.cache[this.cacheIdx];if(this.cacheIdx--,!A)return"OUT_OF_RANGE";this.undo(A),F=this.cacheIdx===T-1}const k=o.substring(n+1);return this.doStep(k),this.mode="record",this.cacheUpdateNumber=t,null}return"OUT_OF_RANGE"}undoStep(o){const n=o.indexOf(":"),t=o.substring(0,n),S=o.substring(n+1);switch(t){case"add":this.delete(JSON.parse(S));break;case"del":this.add(JSON.parse(S));break;case"clear":{const f=JSON.parse(S);for(let T of f)this.add(T);break}case"tx":{const f=S.split(";");for(let T=f.length-1;T>=0;T--)this.undoStep(f[T])}}}undo(o){const n=o.indexOf("=");if(Number(o.substring(0,n))===this.cacheUpdateNumber){this.mode="playback";const S=o.substring(n+1);return this.undoStep(S),this.mode="record",this.cacheUpdateNumber--,null}return this.cacheUpdateNumber}}function Go(o){return o[0].toUpperCase()+o.slice(1)}function gS(o,n,t=ko.STORE){return nT(t).set(o.key,new ST(o,n,t)),{key:o.key,type:"join",a:o.between[0],b:o.between[1],cardinality:o.cardinality}}function nT(o){if("joins"in o&&o.joins instanceof Map)return o.joins;const n=new Map;return o.joins=n,n}function kS(o,n){const t=nT(n);let S=t.get(o.key);if(S===void 0){if(S=nT(ko.STORE).get(o.key)?.in(n),S===void 0)throw new Error(`Join "${o.key}" not found in store "${n.config.name}"`);t.set(o.key,S)}return S}function FF(o,n,t){const S=kS(o,t);let f;switch(o.cardinality){case"1:1":{const T=`${o.a}KeyOf${Go(o.b)}`,M=`${o.b}KeyOf${Go(o.a)}`;f={get[T](){const k=S.states[T];return S.retrieve(k,n)},get[M](){const k=S.states[M];return S.retrieve(k,n)}};const F=`${o.a}EntryOf${Go(o.b)}`;if(F in S.states){const k=`${o.b}EntryOf${Go(o.a)}`;Object.assign(f,{get[F](){const A=S.states[F];return S.retrieve(A,n)},get[k](){const A=S.states[k];return S.retrieve(A,n)}})}break}case"1:n":{const T=`${o.a}KeyOf${Go(o.b)}`,M=`${o.b}KeysOf${Go(o.a)}`;f={get[T](){const k=S.states[T];return S.retrieve(k,n)},get[M](){const k=S.states[M];return S.retrieve(k,n)}};const F=`${o.a}EntryOf${Go(o.b)}`;if(F in S.states){const k=`${o.b}EntriesOf${Go(o.a)}`;Object.assign(f,{get[F](){const A=S.states[F];return S.retrieve(A,n)},get[k](){const A=S.states[k];return S.retrieve(A,n)}})}break}case"n:n":{const T=`${o.a}KeysOf${Go(o.b)}`,M=`${o.b}KeysOf${Go(o.a)}`;f={get[T](){const k=S.states[T];return S.retrieve(k,n)},get[M](){const k=S.states[M];return S.retrieve(k,n)}};const F=`${o.a}EntriesOf${Go(o.b)}`;if(F in S.states){const k=`${o.b}EntriesOf${Go(o.a)}`;Object.assign(f,{get[F](){const A=S.states[F];return S.retrieve(A,n)},get[k](){const A=S.states[k];return S.retrieve(A,n)}})}}}return f}function kF(o,n){return FF(o,n,ko.STORE)}function lS(o,n,t){const S=kS(o,t),f=m(t);if(Fo(f)){const{toolkit:T}=f.transactionMeta;S.transact(T,({relations:M})=>{n(M)})}else n(S.relations)}function fy(o,n){return kS(o,n).core.findRelatedKeysState}function AF(o){return fy(o,ko.STORE)}class ST{options;defaultContent;toolkit;retrieve;molecules=new Map;relations;states;core;transact(o,n){const t=this.toolkit;this.toolkit=o,n(this),this.toolkit=t}store;alternates;[Symbol.dispose](){this.alternates.delete(this.store.config.name)}in(o){const n=o.config.name,t=this.alternates.get(n);if(t)return t;const S=new ST(this.options,this.defaultContent,o);return this.alternates.set(n,S),S.alternates=this.alternates,S}constructor(o,n,t=ko.STORE){this.store=t,this.options=o,this.defaultContent=n,this.alternates=new Map,this.alternates.set(t.config.name,this),this.store.miscResources.set(`join:${o.key}`,this),this.retrieve=(Y,K)=>{const Q=this.toolkit.seek(Y,K);if(Q)return Q;const i=this.molecules.get(l(K));if(i){const g=u(Y,t);return Gn(i,g,t)}if(t.config.lifespan==="immortal")throw new tn(Y,K,t);return xn(t,Y,K)},this.toolkit={get:(...Y)=>zo(t,...Y),set:(...Y)=>{ro(t,...Y)},find:this.retrieve,seek:(...Y)=>Eo(t,...Y),json:(Y)=>ho(t,Y),dispose:(...Y)=>{uo(t,...Y)}};const S=o.between[0],f=o.between[1],T=nS(t,{key:`${o.key}/relatedKeys`,default:()=>new co,mutable:!0,fromJson:(Y)=>co.fromJSON(Y),toJson:(Y)=>Y.toJSON()},["join","relations"]);this.core={findRelatedKeysState:T};const M=({get:Y},K)=>Y(this.retrieve(T,K)),F=(Y,K,Q)=>{const{set:i}=Y,g=this.retrieve(T,K),_=this.retrieve(T,Q);i(g,(h)=>h.add(Q)),i(_,(h)=>h.add(K))},k=(Y,K,Q)=>{const{set:i}=Y,g=this.retrieve(T,K),_=this.retrieve(T,Q);let h,C;i(g,(a)=>{if(a.delete(Q),a.size===0)h=`"${K}"`;return a}),i(_,(a)=>{if(a.delete(K),a.size===0)C=`"${Q}"`;return a})},A=(Y,K,Q)=>{const{get:i,set:g}=Y,_=this.retrieve(T,K),h=i(_);for(let C of h){if(Q.includes(C))continue;const So=this.retrieve(T,C);g(So,(to)=>{return to.delete(K),to})}g(_,(C)=>{return C.transaction((a)=>{a.clear();for(let So of Q){const to=M(Y,So),Wo=to.has(K);if(this.relations.cardinality==="1:n"){const Mn=[];for(let E of to){if(E===K)continue;const x=M(Y,E);if(x.delete(So),x.size===0)Mn.push(E)}if(!Wo&&to.size>0)to.clear();for(let E of Mn){const x=[So,E].sort(),To=`"${x[0]}:${x[1]}"`;this.molecules.delete(To)}}if(!Wo)to.add(K);a.add(So)}return!0}),C})},$=(Y,K,Q)=>{const{set:i}=Y,g=this.retrieve(T,K);i(g,(_)=>{return _.transaction((h)=>{for(let C of Q)h.add(C);return!0}),_});for(let _ of Q){const h=this.retrieve(T,_);i(h,(C)=>{return C.add(K),C})}return!0},O=(Y,K,Q)=>{const i=M(Y,K);return Q?i.has(Q):i.size>0},w={getRelatedKeys:(Y)=>M(this.toolkit,Y),addRelation:(Y,K)=>{F(this.toolkit,Y,K)},deleteRelation:(Y,K)=>{k(this.toolkit,Y,K)},replaceRelationsSafely:(Y,K)=>{A(this.toolkit,Y,K)},replaceRelationsUnsafely:(Y,K)=>{$(this.toolkit,Y,K)},has:(Y,K)=>O(this.toolkit,Y,K)};let z,r,H;if(n){r=jn(t,{key:`${o.key}/content`,default:n},["join","content"]);const Y={key:o.key,type:"join",a:o.between[0],b:o.between[1],cardinality:o.cardinality};H=MF(t,{key:`${o.key}/content-molecules`,new:class _{C;constructor(h,C){this.key=C}}});const K=({get:_},h)=>_(this.retrieve(r,h)),Q=({set:_},h,C)=>{_(this.retrieve(r,h),C)},i=(_,h)=>{const C=t.molecules.get(`"${h}"`);if(C)this.toolkit.dispose(C),this.molecules.delete(`"${h}"`)};z=Object.assign(w,{getContent:(_)=>{return K(this.toolkit,_)},setContent:(_,h)=>{Q(this.toolkit,_,h)},deleteContent:(_)=>{i(this.toolkit,_)}})}else z=w;const D=new Fn(o,{externalStore:z,makeContentKey:(...Y)=>{const K=Y.sort(),Q=`${K[0]}:${K[1]}`,[i,g]=K.map((_)=>this.molecules.get(l(_)));if(t.config.lifespan==="immortal"&&i&&g){const _=m(t),h=vn(_,[i,g],H,Q);this.molecules.set(`"${Q}"`,u(h,_))}return Q}}),I=()=>hn(t,{key:`${o.key}/singleRelatedKey`,get:(Y)=>({get:K})=>{const Q=this.retrieve(T,Y),i=K(Q);for(let g of i)return g;return null}},["join","keys"]),v=()=>{return hn(t,{key:`${o.key}/multipleRelatedKeys`,get:(Y)=>({get:K})=>{const Q=tT(T,t),i=this.retrieve(Q,Y);return K(i).members}},["join","keys"])},N=()=>hn(t,{key:`${o.key}/singleRelatedEntry`,get:(Y)=>({get:K})=>{const Q=this.retrieve(T,Y),i=K(Q);for(let g of i){const _=D.makeContentKey(Y,g),h=this.retrieve(r,_),C=K(h);return[g,C]}return null}},["join","entries"]),P=()=>hn(t,{key:`${o.key}/multipleRelatedEntries`,get:(Y)=>({get:K})=>{const Q=tT(T,t),i=this.retrieve(Q,Y);return K(i).members.map((_)=>{const h=D.makeContentKey(Y,_),C=this.retrieve(r,h),a=K(C);return[_,a]})}},["join","entries"]);switch(o.cardinality){case"1:1":{const Y=I(),K=`${S}KeyOf${Go(f)}`,Q=`${f}KeyOf${Go(S)}`,i={[K]:Y,[Q]:Y};let g;if(n){const _=N(),h=`${S}EntryOf${Go(f)}`,C=`${f}EntryOf${Go(S)}`,a={[h]:_,[C]:_};g=Object.assign(i,a)}else g=i;this.relations=D,this.states=g;break}case"1:n":{const Y=I(),K=v(),Q=`${S}KeyOf${Go(f)}`,i=`${f}KeysOf${Go(S)}`,g={[Q]:Y,[i]:K};let _;if(n){const h=N(),C=P(),a=`${S}EntryOf${Go(f)}`,So=`${f}EntriesOf${Go(S)}`,to={[a]:h,[So]:C};_=Object.assign(g,to)}else _=g;this.relations=D,this.states=_;break}default:{const Y=v(),K=`${S}KeysOf${Go(f)}`,Q=`${f}KeysOf${Go(S)}`,i={[K]:Y,[Q]:Y};let g;if(n){const _=P(),h=`${S}EntriesOf${Go(f)}`,C=`${f}EntriesOf${Go(S)}`,a={[h]:_,[C]:_};g=Object.assign(i,a)}else g=i;this.relations=D,this.states=g}}}}function eS(o){return{store:o}}function zo(o,...n){let t,S,f;if(n.length===1){if(t=n[0],t.type!=="molecule"){if(S=ZS(o,t)??null,S)f=t.family?Uo(t.family.subKey):null,t=Ro(o,S,f)}}else{S=n[0],f=n[1];let T;if(S.type==="molecule_family")T=Eo(o,S,f)??Gt(S,f);else T=Ro(o,S,f);t=T}if("counterfeit"in t&&"family"in t){S=t.type==="molecule"?u(t.family,o):o.families.get(t.family.key);const T=t.type==="molecule"?t.key:t.family.subKey,M=o.disposalTraces.buffer.find((F)=>F?.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}".`,M?`This state was previously disposed:\n${M.trace}`:"No previous disposal trace was found."),S.type){case"atom_family":case"mutable_atom_family":return o.defaults.get(S.key);case"selector_family":case"readonly_selector_family":{if(o.defaults.has(S.key))return o.defaults.get(t.family.key);const F=u(S,o).default(T);return o.defaults.set(S.key,F),F}case"molecule_family":throw new tn(S,T,o)}}switch(t.type){case"atom":case"mutable_atom":case"selector":case"readonly_selector":return en(u(t,o),o);case"molecule":return u(t,o).instance}}class Qt{n;type="molecule";stringKey;family;_dependsOn;get dependsOn(){if(this.family)return this.family.dependsOn;return this._dependsOn}subject=new s;tokens=new Map;above=new Map;below=new Map;joins=new Map;instance;constructor(o,n,t){this.key=n;if(this.stringKey=l(n),t)this.family=t,this._dependsOn=t.dependsOn;if(o)for(let S of o)this.above.set(S.stringKey,S)}}function $F(o){return o[0].toUpperCase()+o.slice(1)}function vn(o,n,t,S,...f){const T=qM(o),M=m(o),F=l(S);M.moleculeInProgress=F;const k=Array.isArray(n)?n:[n],A=k.map((D)=>{if(D instanceof Qt)return D;const I=l(D.key),v=o.molecules.get(I);if(!v)throw new Error(`Molecule ${I} not found in store "${o.config.name}"`);return v}),$=new Qt(A,S,t);M.molecules.set(F,$);for(let D of A)D.below.set($.stringKey,$);const O={get:(...D)=>zo(m(T),...D),set:(...D)=>{ro(m(T),...D)},seek:(D,I)=>Eo(m(T),D,I),json:(D)=>ho(m(T),D),run:(D,I=zt())=>At(D,I,m(o)),make:(D,I,v,...N)=>vn(m(T),D,I,v,...N),dispose:(D)=>{uo(m(T),D)},env:()=>eS(m(T)),bond:(D,I)=>{if(D.type==="join"){const{as:v}=I,N=kS(D,T);N.molecules.set(F,$),$.joins.set(D.key,N);const P=w.subject.subscribe(`join:${D.key}-${F}`,(_)=>{if(_.type==="molecule_disposal"){if(l(_.token.key)===F)P(),N.molecules.delete(F)}});if(v===null)return;const Y=D.a===v?D.b:D.a,K=kF(D,S),Q=K[`${Y}KeysOf${$F(v)}`],i=K[`${Y}EntriesOf${$F(v)}`];let g={relatedKeys:Q};if(i)g=Object.assign(g,{relatedEntries:i});return g}return Gn($,u(D,T),m(T))},claim:(D,I)=>{const{exclusive:v}=I,N=m(o).molecules.get(l(D.key));if(N)if(v){for(let P of N.above.values())P.below.delete(N.stringKey);N.above.clear(),N.above.set($.stringKey,$),$.below.set(N.stringKey,N)}else N.above.set($.stringKey,$),$.below.set(N.stringKey,N)},spawn:(D,I,...v)=>vn(m(o),[$],u(D,o),I,...v)},w=u(t,o),z=w.new;$.instance=new z(O,S,...f);const r={type:"molecule",key:S,family:t},H={type:"molecule_creation",subType:"classic",token:r,family:t,context:k,params:f};if(bo(M))w.subject.next(H);else if(Fo(M)&&M.on.transactionApplying.state===null)M.transactionMeta.update.updates.push(H);return M.moleculeInProgress=null,r}function fT(o,n,t){switch(n){case"newValue":{JF(o,t);break}case"oldValue":{uo(t,o.token);break}}}function TT(o,n,t){switch(n){case"newValue":{uo(t,o.token);break}case"oldValue":{JF(o,t),t.valueMap.set(o.token.key,o.value);break}}}function JF(o,n){const{family:t}=o.token;if(t){const S=n.families.get(t.key);if(S)Ro(n,S,Uo(t.subKey))}}function MT(o,n,t){switch(n){case"newValue":switch(o.subType){case"classic":vn(t,o.context,o.family,o.token.key,...o.params);break;case"modern":oT(t,o.provenance,o.key);break}break;case"oldValue":switch(o.subType){case"classic":uo(t,o.token);break;case"modern":FS(t,o.key);break}break}}function FT(o,n,t){switch(n){case"newValue":switch(o.subType){case"classic":uo(t,o.token);break;case"modern":FS(t,o.key);break}break;case"oldValue":switch(o.subType){case"classic":{const S=vn(t,o.context,o.family,o.token.key);for(let[f,T]of o.values){const M=`${f}(${l(S.key)})`,F=u(S,t),k=F.tokens.has(M),A=t.families.get(f);if(A&&!k)Gn(F,A,t);t.valueMap.set(M,T)}}break;case"modern":{oT(t,o.provenance,o.key);for(let[S,f]of o.values){const T=t.families.get(S);if(T){Ro(t,T,o.key);const M=`${S}(${l(o.key)})`;t.valueMap.set(M,f)}}}}break}}function dS(o,n,t){const S=o==="newValue"?n.updates:[...n.updates].reverse();for(let f of S)switch(f.type){case"atom_update":case"selector_update":PS(o,f,t);break;case"state_creation":fT(f,o,t);break;case"state_disposal":TT(f,o,t);break;case"molecule_creation":MT(f,o,t);break;case"molecule_disposal":FT(f,o,t);break;case"transaction_update":dS(o,f,t);break}}function yF(o,n,t){if(!bo(t))return;const f=t.transactionMeta.actionContinuities.getRelatedKey(o);if(f!==void 0)t.transactionMeta.epoch.set(f,n)}var RF=(o,n)=>{const t=m(n),{parent:S}=t;if(S===null||!Fo(t)||t.transactionMeta?.phase!=="building"){n.logger.warn("\uD83D\uDC1E","transaction","???","applyTransaction called outside of a transaction. This is probably a bug in AtomIO.");return}t.transactionMeta.phase="applying",t.transactionMeta.update.output=o,S.child=null,S.on.transactionApplying.next(t.transactionMeta);const{updates:f}=t.transactionMeta.update;if(n.logger.info("\uD83D\uDEC4","transaction",t.transactionMeta.update.key,`Applying transaction with ${f.length} updates:`,f),dS("newValue",t.transactionMeta.update,S),bo(S))yF(t.transactionMeta.update.key,t.transactionMeta.update.epoch,S),u({key:t.transactionMeta.update.key,type:"transaction"},n)?.subject.next(t.transactionMeta.update),n.logger.info("\uD83D\uDEEC","transaction",t.transactionMeta.update.key,"Finished applying transaction.");else if(Fo(S))S.transactionMeta.update.updates.push(t.transactionMeta.update);S.on.transactionApplying.next(null)};class On extends Map{o;deleted=new Set;constructor(o){super();this.source=o}get(o){if(super.has(o))return super.get(o);if(!this.deleted.has(o)&&this.source.has(o))return this.source.get(o);return}set(o,n){return this.deleted.delete(o),super.set(o,n)}hasOwn(o){return super.has(o)}has(o){return!this.deleted.has(o)&&(super.has(o)||this.source.has(o))}delete(o){return this.deleted.add(o),super.delete(o)}}var OF=(o,n,t,S)=>{const f=m(t),T={parent:f,child:null,on:f.on,loggers:f.loggers,logger:f.logger,config:f.config,atoms:new On(f.atoms),atomsThatAreDefault:new Set(f.atomsThatAreDefault),families:new On(f.families),operation:{open:!1},readonlySelectors:new On(f.readonlySelectors),timelines:new On(f.timelines),timelineTopics:new Fn(f.timelineTopics.toJSON()),trackers:new Map,transactions:new On(f.transactions),selectorAtoms:new Fn(f.selectorAtoms.toJSON()),selectorGraph:new Fn(f.selectorGraph.toJSON(),{makeContentKey:(...A)=>A.sort().join(":")}),selectors:new On(f.selectors),valueMap:new On(f.valueMap),defaults:f.defaults,disposalTraces:t.disposalTraces.copy(),molecules:new On(f.molecules),moleculeFamilies:new On(f.moleculeFamilies),moleculeInProgress:f.moleculeInProgress,miscResources:new On(f.miscResources)},M=WF(o,t),F={phase:"building",update:{type:"transaction_update",key:o,id:S,epoch:M===void 0?Number.NaN:M+1,updates:[],params:n,output:void 0},toolkit:{get:(...A)=>zo(k,...A),set:(...A)=>{ro(k,...A)},run:(A,$=zt())=>At(A,$,k),find:(A,$)=>Ro(k,A,$),seek:(A,$)=>Eo(k,A,$),json:(A)=>ho(k,A),make:(A,$,O,...w)=>vn(k,A,$,O,...w),dispose:(...A)=>{uo(k,...A)},env:()=>eS(k)}},k=Object.assign(T,{transactionMeta:F});return f.child=k,t.logger.info("\uD83D\uDEEB","transaction",o,"Building transaction with params:",n),k};function af(o,n){const t={key:o.key,type:"transaction",run:(T,M)=>{const F=OF(o.key,T,n,M);try{const k=m(n),{toolkit:A}=F.transactionMeta,$=o.do(A,...T);return RF($,k),$}catch(k){throw gM(S),n.logger.warn("\uD83D\uDCA5","transaction",o.key,"caught:",k),k}},install:(T)=>af(o,T),subject:new s},S=m(n);S.transactions.set(t.key,t);const f=Po(t);return n.on.transactionCreation.next(f),f}function WF(o,n){const t=bo(n),S=t?n.transactionMeta.actionContinuities.getRelatedKey(o):void 0;return t&&S!==void 0?n.transactionMeta.epoch.get(S):void 0}class uS{_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(){const o=new uS([...this._buffer]);return o._index=this._index,o}}class _F{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 uS(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 lf(null),operationClose:new s,moleculeCreationStart:new s,moleculeCreationDone:new s,moleculeDisposal:new s};operation={open:!1};config={name:"IMPLICIT_STORE",lifespan:"ephemeral"};loggers=[new uf("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[,S]of n.families){if(S.internalRoles?.includes("mutable")||S.internalRoles?.includes("join"))continue;S.install(this)}const t=new Set;for(let[,S]of n.atoms){if(t.has(S.key))continue;if(S.install(this),S.type==="mutable_atom"){const f=ho(n,S),T=dn(S);t.add(f.key),t.add(T.key)}}for(let[,S]of n.readonlySelectors)S.install(this);for(let[,S]of n.selectors){if(t.has(S.key))continue;S.install(this)}for(let[,S]of n.transactions)S.install(this);for(let[,S]of n.timelines)S.install(this)}}}var ko={get STORE(){if(!globalThis.ATOM_IO_IMPLICIT_STORE)globalThis.ATOM_IO_IMPLICIT_STORE=new _F({name:"IMPLICIT_STORE",lifespan:"ephemeral"});return globalThis.ATOM_IO_IMPLICIT_STORE}};function u(o,n){let t,S=n;while(S!==null){switch(o.type){case"atom":case"mutable_atom":t=S.atoms.get(o.key);break;case"selector":t=S.selectors.get(o.key);break;case"readonly_selector":t=S.readonlySelectors.get(o.key);break;case"atom_family":case"mutable_atom_family":case"selector_family":case"readonly_selector_family":t=S.families.get(o.key);break;case"timeline":t=S.timelines.get(o.key);break;case"transaction":t=S.transactions.get(o.key);break;case"molecule":t=S.molecules.get(l(o.key));break;case"molecule_family":t=S.moleculeFamilies.get(o.key);break}if(t)return t;S=S.child}throw new tn(o,n)}function aS(o,n){let t;t=u(o,n);const{family:S}=o;for(let M of t.joins.values())M.relations.delete(t.key),M.molecules.delete(t.stringKey);const f=[];for(let M of t.above.values())f.push(Po(M));const T=[];for(let M of t.tokens.values()){const F=M.family;T.push([F.key,n.valueMap.get(M.key)])}if(S){const M=u(S,n),F={type:"molecule_disposal",subType:"classic",token:o,family:S,context:f,values:T};if(o.family)F.family=o.family;for(let A of t.tokens.values())uo(n,A);for(let A of t.below.values())if(A.dependsOn==="all")aS(A,n);else if(A.above.delete(t.stringKey),A.above.size===0)aS(A,n);if(t.below.clear(),Fo(n)&&n.transactionMeta.phase==="building")n.transactionMeta.update.updates.push(F);else M.subject.next(F);n.molecules.delete(t.stringKey)}for(let M of t.above.values())M.below.delete(t.stringKey)}function xn(o,n,t){const S=o.families.get(n.key);if(S===void 0)throw new tn(n,o);const f=S(t),T=m(o);if(f.family&&T.moleculeInProgress===null){if(bo(T))switch(f.type){case"atom":case"mutable_atom":o.on.atomCreation.next(f);break;case"selector":case"readonly_selector":o.on.selectorCreation.next(f);break}else if(Fo(T)&&T.on.transactionApplying.state===null)T.transactionMeta.update.updates.push({type:"state_creation",token:f})}return f}function Eo(o,n,t){const S=l(t),f=`${n.key}(${S})`,T=m(o);let M;switch(n.type){case"atom_family":case"mutable_atom_family":M=T.atoms.get(f);break;case"selector_family":M=T.selectors.get(f);break;case"readonly_selector_family":M=T.readonlySelectors.get(f);break;case"molecule_family":M=T.molecules.get(l(t))}if(M)return Po(M);return M}function Ro(o,n,t){let S=Eo(o,n,t);if(S)return S;const f=o.molecules.get(l(t));if(f)return Gn(f,n,o);if(o.config.lifespan==="immortal"){const T=Gt(n,t);return o.logger.error("\u274C",T.type,T.key,`was not found in store "${o.config.name}"; returned a counterfeit token.`),T}return S=xn(o,n,t),S}function uo(o,...n){let t,S;if(n.length===1)t=n[0],S=t.key;else{const T=n[0],M=n[1];t=T.type==="molecule_family"?Eo(o,T,M)??Gt(T,M):Ro(o,T,M)}try{u(t,o)}catch(T){const M=o.disposalTraces.buffer.find((F)=>F?.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}".`,M?`\n This state was most recently disposed\n${M.trace}`:"No previous disposal trace was found.");return}switch(t.type){case"atom":case"mutable_atom":kT(t,o);break;case"selector":case"readonly_selector":wF(t,o);break;case"molecule":aS(t,o);break}const{stack:f}=new Error;if(f){const T=f?.split("\n")?.slice(3)?.join("\n");o.disposalTraces.add({key:t.key,trace:T})}}var sS=(o,n)=>m(n).atoms.has(o),Ty=(o,n)=>m(n).selectors.has(o),My=(o,n)=>m(n).readonlySelectors.has(o),KF=(o,n)=>sS(o,n)||Ty(o,n)||My(o,n);var of=(o,n)=>{return m(n).selectorGraph.getRelationEntries({downstreamSelectorKey:o}).filter(([S,{source:f}])=>f!==o).map(([S,{source:f}])=>f).filter((S)=>KF(S,n))};var AT=(o,n,t)=>{const S=[],f=of(o,t);while(f.length>0){const T=f.shift();if(n.has(T))continue;if(n.add(T),!sS(T,t))f.push(...of(T,t));else if(!S.includes(T))S.push(T)}return S},XF=(o,n)=>{const t=o.key,S=of(t,n),f=new Set;return S.flatMap((T)=>sS(T,n)?T:AT(T,f,n))};var YF=(o,n,t,S)=>{const f=m(S);if(n.type==="atom"||n.type==="mutable_atom")f.selectorAtoms.set({selectorKey:o,atomKey:n.key}),S.logger.info("\uD83D\uDD0D","selector",o,`discovers root atom "${n.key}"`);else{const T=AT(n.key,t,S);S.logger.info("\uD83D\uDD0D","selector",o,`discovers root atoms: [ ${T.map((M)=>`"${M}"`).join(", ")} ]`);for(let M of T)f.selectorAtoms=f.selectorAtoms.set({selectorKey:o,atomKey:M})}t.add(n.key)};var nf=(o,n,t)=>({get:(...S)=>{const f=m(t);let T;if(S.length===2){const[k,A]=S;switch(k.type){case"molecule_family":return zo(t,k,A);default:if(t.config.lifespan==="ephemeral")T=Ro(t,k,A);else{const $=Eo(t,k,A);if($)T=$;else throw new tn(k,A,t)}}}else[T]=S;if(T.type==="molecule")return zo(t,T);const M=u(T,t),F=en(M,t);return t.logger.info("\uD83D\uDD0C","selector",o,`registers dependency ( "${T.key}" =`,F,")"),f.selectorGraph.set({upstreamSelectorKey:T.key,downstreamSelectorKey:o},{source:T.key}),YF(o,T,n,t),F},set:(...S)=>{let f,T;if(S.length===2)f=S[0],T=S[1];else{const k=S[0],A=S[1];T=S[2];const $=t.config.lifespan==="ephemeral"?Ro(t,k,A):Eo(t,k,A);if(!$)throw new tn(k,A,t);f=$}const M=m(t),F=u(f,M);pS(F,T,M)},find:(S,f)=>Ro(t,S,f),seek:(S,f)=>Eo(t,S,f),json:(S)=>ho(t,S)});var tS=(o,n,t)=>{const S=m(o),f=new s,T=new Set,{get:M,find:F,seek:k,json:A}=nf(n.key,T,S),$=()=>{const r=n.get({get:M,find:F,seek:k,json:A});return Rn(n.key,r,f,m(o)),T.clear(),r},O={...n,subject:f,install:(r)=>tS(r,n,t),get:$,type:"readonly_selector",...t&&{family:t}};S.readonlySelectors.set(n.key,O);const w=$();o.logger.info("\u2728",O.type,O.key,"=",w);const z={key:n.key,type:"readonly_selector"};if(t)z.family=t;return z};var AS=(o,n,t)=>{const S=m(o),f=new s,T=new Set,M=nf(n.key,T,S),{find:F,get:k,seek:A,json:$}=M,O={find:F,get:k,seek:A,json:$},w=(I=n.get,v=m(o))=>{const N=I(O);return Rn(n.key,N,f,v),T.clear(),N},r={...n,subject:f,install:(I)=>AS(I,n,t),get:w,set:(I)=>{const v=m(o),N=w(n.get,v),P=qS(I)(N);if(o.logger.info("\uD83D\uDCDD","selector",n.key,"set (",N,"->",P,")"),Rn(n.key,P,f,v),mt(v,n.key),bo(v))f.next({newValue:P,oldValue:N});n.set(M,P)},type:"selector",...t&&{family:t}};S.selectors.set(n.key,r);const H=w();o.logger.info("\u2728",r.type,r.key,"=",H);const D={key:n.key,type:"selector"};if(t)D.family=t;return D};function En(o,n){if("set"in n){const f=AS(o,n,void 0);return o.on.selectorCreation.next(f),f}const S=tS(o,n,void 0);return o.on.selectorCreation.next(S),S}function wF(o,n){const t=m(n),{key:S}=o,f=u(o,t);if(!f.family)n.logger.error("\u274C","selector",S,"Standalone selectors cannot be disposed.");else{const T=t.molecules.get(f.family.subKey);if(T)T.tokens.delete(S);switch(o.type){case"selector":t.selectors.delete(S),u({key:f.family.key,type:"selector_family"},n).subject.next({type:"state_disposal",token:o});break;case"readonly_selector":t.readonlySelectors.delete(S),u({key:f.family.key,type:"readonly_selector_family"},n).subject.next({type:"state_disposal",token:o});break}if(t.valueMap.delete(S),t.selectorAtoms.delete(S),t.selectorGraph.delete(S),n.logger.info("\uD83D\uDD25",o.type,S,"deleted"),Fo(t)&&t.transactionMeta.phase==="building")t.transactionMeta.update.updates.push({type:"state_disposal",token:o});else n.on.selectorDisposal.next(o)}}function fS(o,n,t){const S={key:n.key,type:"selector_family"},f=o.families.get(n.key);if(f)o.logger.error("\u2757","selector_family",n.key,`Overwriting an existing ${zn(f)} "${f.key}" in store "${o.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);const T=new s,F=Object.assign((k)=>{const A=l(k),$={key:n.key,subKey:A},O=`${n.key}(${A})`,w=m(o),z=AS(w,{key:O,get:n.get(k),set:n.set(k)},$);return T.next({type:"state_creation",token:z}),z},S,{internalRoles:t,subject:T,install:(k)=>fS(k,n),default:(k)=>{return n.get(k)({get:(...$)=>zo(o,...$),find:($,O)=>Ro(o,$,O),seek:($,O)=>Eo(o,$,O),json:($)=>ho(o,$)})}});return o.families.set(n.key,F),S}function EF(o,n,t=ko.STORE){const S=fS(t,{key:`${o.key}:JSON`,get:(T)=>({seek:M,get:F})=>{const k=M(o,T);if(k)return n.toJson(F(k));const A=l(T),$=t.molecules.get(A);if($){const w=Gn($,o,t);return n.toJson(F(w))}if(t.config.lifespan==="immortal")throw new Error(`No molecule found for key "${A}"`);const O=xn(t,o,T);return n.toJson(F(O))},set:(T)=>({seek:M,set:F},k)=>{const A=M(o,T);if(A)F(A,n.fromJson(k));else{const $=l(T),O=t.molecules.get($);if(O){const w=Gn(O,o,t);F(w,n.fromJson(k))}else{if(t.config.lifespan==="immortal")throw new Error(`No molecule found for key "${$}"`);F(xn(t,o,T),n.fromJson(k))}}}},["mutable","json"]);return u(o,t).subject.subscribe(`store=${t.config.name}::json-selector-family`,(T)=>{if(T.token.family)Eo(t,S,Uo(T.token.family.subKey))}),S}var Uo=(o)=>JSON.parse(o),l=(o)=>JSON.stringify(o),EK=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];var zF=(o,n)=>{const t=m(n);if(t.operation.open)return t.operation.prev.get(o.key);return t.valueMap.get(o.key)};var JT=(o,n)=>{const t=m(n);return XF(o,n).map((f)=>{const T=t.atoms.get(f);if(T===void 0)throw new Error(`Atom "${f}", a dependency of selector "${o.key}", not found in store "${n.config.name}".`);return T.subject.subscribe(`${o.type}:${o.key}`,(M)=>{n.logger.info("\uD83D\uDCE2",o.type,o.key,"root",f,"went",M.oldValue,"->",M.newValue);const F=zF(o,t),k=en(o,t);n.logger.info("\u2728",o.type,o.key,"went",F,"->",k),o.subject.next({newValue:k,oldValue:F})})})};function kn(o,n,t,S){function f(O){if(S.operation.open){const w=S.on.operationClose.subscribe(`state subscription ${t}`,()=>{w(),n(O)})}else n(O)}const T=u(o,S);S.logger.info("\uD83D\uDC40",T.type,T.key,`Adding subscription "${t}"`);const M=T.type==="selector"||T.type==="readonly_selector";let F=null,k=f;if(M)F=JT(T,S),k=(O)=>{if(F)F.length=0,F.push(...JT(T,S));f(O)};const A=T.subject.subscribe(t,k);return()=>{if(S.logger.info("\uD83D\uDE48",T.type,T.key,`Removing subscription "${t}"`),A(),F)for(let O of F)O()}}var $T=(o,n,t,S)=>{const f=u(o,S);S.logger.info("\uD83D\uDC40","timeline",o.key,`Adding subscription "${t}"`);const T=f.subject.subscribe(t,n);return()=>{S.logger.info("\uD83D\uDE48","timeline",o.key,`Removing subscription "${t}" from timeline`),T()}};class un{Update;initializeState(o,n){const t=`*${o.key}`;n.atoms.delete(t),n.valueMap.delete(t);const S=o.family?{key:`*${o.family.key}`,subKey:o.family.subKey}:void 0,f=nn(n,{key:t,default:null},S);if(n.parent?.valueMap.has(t)){const T=n.parent.valueMap.get(t);n.valueMap.set(t,T)}return f}unsubscribeFromInnerValue;unsubscribeFromState;observeCore(o,n,t){const S=`tracker:${t.config.name}:${Fo(t)?t.transactionMeta.update.key:"main"}:${o.key}`,f=zo(t,o);this.unsubscribeFromInnerValue=f.subscribe(S,(T)=>{ro(t,n,T)}),this.unsubscribeFromState=kn(o,(T)=>{if(T.newValue!==T.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=T.newValue.subscribe(S,(M)=>{ro(t,n,M)})},S,t)}updateCore(o,n,t){const S=`tracker:${t.config.name}:${Fo(t)?t.transactionMeta.update.key:"main"}:${o.key}`;kn(n,({newValue:f,oldValue:T})=>{const M=t.timelineTopics.getRelatedKey(n.key);if(M){if(t.timelines.get(M)?.timeTraveling){const A=$T({key:M,type:"timeline"},($)=>{A(),ro(t,o,(O)=>{if($==="redo"&&f)O.do(f);else if($==="undo"&&T)O.undo(T);return O})},S,t);return}}const F=t.on.operationClose.subscribe(S,()=>{F();const k=zo(t,o),A=f===null?-1:k.getUpdateNumber(f),$=A-k.cacheUpdateNumber;if(f&&$===1)ro(t,o,(O)=>(O.do(f),O));else t.logger.info("\u274C","mutable_atom",o.key,`could not be updated. Expected update number ${k.cacheUpdateNumber+1}, but got ${A}`)})},S,t)}mutableState;latestUpdateState;dispose;constructor(o,n){this.mutableState=o;const t=m(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 $S(o,n,t){o.logger.info("\uD83D\uDD28","atom",n.key,`creating in store "${o.config.name}"`);const S=m(o),f=S.atoms.get(n.key);if(f&&f.type==="mutable_atom")return o.logger.error("\u274C","atom",n.key,"Tried to create atom, but it already exists in the store."),Po(f);const T=new s,M={...n,type:"mutable_atom",install:(A)=>{return A.logger.info("\uD83D\uDEE0\uFE0F","atom",n.key,`installing in store "${A.config.name}"`),$S(A,n,t)},subject:T};if(t)M.family=t;const F=n.default();S.atoms.set(M.key,M),tf(n.key,o),Rn(n.key,F,T,S);const k=Po(M);if(n.effects){let A=0;const $=[];for(let O of n.effects){const w=O({setSelf:(z)=>{ro(o,k,z)},onSet:(z)=>kn(k,z,`effect[${A}]`,o)});if(w)$.push(w);++A}M.cleanup=()=>{for(let O of $)O()}}if(new un(k,o),!t)vM(k,n,o);return k}class yT{Update;latestUpdateAtoms;mutableAtoms;constructor(o,n){const t=jn(n,{key:`*${o.key}`,default:null},["mutable","updates"]);this.latestUpdateAtoms=u(t,n),this.mutableAtoms=o,this.mutableAtoms.subject.subscribe(`store=${n.config.name}::tracker-atom-family`,(S)=>{if(S.token.family){const f=Uo(S.token.family.subKey);Eo(n,this.latestUpdateAtoms,f),new un(S.token,n)}}),this.latestUpdateAtoms.subject.subscribe(`store=${n.config.name}::tracker-atom-family`,(S)=>{if(S.token.family){const f=Uo(S.token.family.subKey),T=Eo(n,this.mutableAtoms,f);if(T)new un(T,n)}})}}function nS(o,n,t){const S={key:n.key,type:"mutable_atom_family"},f=o.families.get(n.key);if(f)o.logger.error("\u2757","mutable_atom_family",n.key,`Overwriting an existing ${zn(f)} "${f.key}" in store "${o.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);const T=new s,F=Object.assign((k)=>{const A=l(k),$={key:n.key,subKey:A},O=`${n.key}(${A})`,w=m(o),z={key:O,default:()=>n.default(k),toJson:n.toJson,fromJson:n.fromJson,mutable:!0};if(n.effects)z.effects=n.effects(k);const r=$S(w,z,$);return T.next({type:"state_creation",token:r}),r},S,{subject:T,install:(k)=>nS(k,n),toJson:n.toJson,fromJson:n.fromJson,internalRoles:t});return o.families.set(n.key,F),EF(F,n,o),new yT(F,o),S}var tT=(o,n)=>{const t=m(n),S=`${o.key}:JSON`;return t.families.get(S)};var ho=(o,n)=>{if(n.family){const S=m(o),T={key:`${n.family.key}:JSON`,type:"selector_family"},M=u(T,S),F=JSON.parse(n.family.subKey);return Ro(o,M,F)}return{type:"selector",key:`${n.key}:JSON`}};var dn=(o)=>{const t={type:"atom",key:`*${o.key}`};if(o.family)t.family={key:`*${o.family.key}`,subKey:o.family.subKey};return t};function nF(o){return typeof o==="object"&&o!==null&&"do"in o&&"undo"in o&&"subscribe"in o}function MS(o,n,t){const S=n.valueMap.get(o.key),f=t.valueMap.get(o.key);if(S===f){if(S===void 0)return typeof o.default==="function"?o.default():o.default;n.logger.info("\uD83D\uDCC3","atom",o.key,"copying");const T=o.toJson(S),M=o.fromJson(T);return t.valueMap.set(o.key,M),new un(o,n),M}return f}function Rn(o,n,t,S){const f=S.valueMap.get(o);if(f instanceof oS)f.use(n);if(n instanceof Promise){const T=new oS(n);return S.valueMap.set(o,T),T.then((M)=>{Rn(o,M,t,S),t.next({newValue:M,oldValue:T})}).catch((M)=>{S.logger.error("\uD83D\uDCA5","state",o,"rejected:",M)}),T}return S.valueMap.set(o,n),n}var lM=(o,n)=>{let t=n.valueMap.get(o.key);if(o.type==="mutable_atom"&&Fo(n)){const{parent:S}=n;t=MS(o,S,n)}return t},sM=(o,n)=>{const t=n.valueMap.get(o);if(t instanceof oS){const S=t,f=n.selectors.get(o)??n.readonlySelectors.get(o);if(f)S.use(f.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 SF=(o,n)=>{return m(n).atomsThatAreDefault.has(o)},tf=(o,n)=>{const t=m(n);t.atomsThatAreDefault=new Set(t.atomsThatAreDefault).add(o)},fF=(o,n)=>{const t=m(n);t.atomsThatAreDefault=new Set(m(n).atomsThatAreDefault),t.atomsThatAreDefault.delete(o)};function nn(o,n,t){o.logger.info("\uD83D\uDD28","atom",n.key,`creating in store "${o.config.name}"`);const S=m(o),f=S.atoms.get(n.key);if(f&&f.type==="atom")return o.logger.error("\u274C","atom",n.key,"Tried to create atom, but it already exists in the store."),Po(f);const T=new s,M={...n,type:"atom",install:(A)=>{return A.logger.info("\uD83D\uDEE0\uFE0F","atom",n.key,`installing in store "${A.config.name}"`),nn(A,n,t)},subject:T};if(t)M.family=t;let F=n.default;if(n.default instanceof Function)F=n.default();S.atoms.set(M.key,M),tf(n.key,o),Rn(n.key,F,T,S);const k=Po(M);if(n.effects){let A=0;const $=[];for(let O of n.effects){const w=O({setSelf:(z)=>{ro(o,k,z)},onSet:(z)=>kn(k,z,`effect[${A}]`,o)});if(w)$.push(w);++A}M.cleanup=()=>{for(let O of $)O()}}return k}function ZM(o,n){if("mutable"in n){const f=$S(o,n,void 0);return o.on.atomCreation.next(f),f}const S=nn(o,n,void 0);return o.on.atomCreation.next(S),S}function kT(o,n){const t=m(n),{key:S}=o,f=u(o,t);if(!f.family)n.logger.error("\u274C","atom",S,"Standalone atoms cannot be disposed.");else{f.cleanup?.();const T=n.valueMap.get(f.key);u({key:f.family.key,type:"atom_family"},n).subject.next({type:"state_disposal",token:o,value:T});const F=t.molecules.get(f.family.subKey);if(F)F.tokens.delete(S);if(t.atoms.delete(S),t.valueMap.delete(S),t.selectorAtoms.delete(S),t.atomsThatAreDefault.delete(S),n.timelineTopics.delete(S),o.type==="mutable_atom"){const k=dn(o);kT(k,n),n.trackers.delete(S)}if(n.logger.info("\uD83D\uDD25","atom",S,"deleted"),Fo(t)&&t.transactionMeta.phase==="building")t.transactionMeta.update.updates.push({type:"state_disposal",token:o});else n.on.atomDisposal.next(o)}}var RT=(o)=>{const n=nn(o,{key:"\uD83D\uDD0D Atom Token Index (Internal)",default:()=>{const t=new Map;for(let[S,f]of o.atoms)if(!S.includes("\uD83D\uDD0D")){const T=Po(f);if(f.family){let M=t.get(f.family.key);if(!M||!("familyMembers"in M))M={key:f.family.key,familyMembers:new Map},t.set(f.family.key,M);M.familyMembers.set(f.family.subKey,T)}else t.set(S,T)}return t},effects:[({setSelf:t})=>{o.on.atomCreation.subscribe("introspection",(S)=>{if(S.key.includes("\uD83D\uDD0D"))return;t((f)=>{if(S.family){const{key:T,subKey:M}=S.family;let F=f.get(T);if(F===void 0||!("familyMembers"in F))F={key:T,familyMembers:new Map},f.set(T,F);F.familyMembers.set(M,S)}else f.set(S.key,S);return f})}),o.on.atomDisposal.subscribe("introspection",(S)=>{t((f)=>{if(S.family){const{key:T,subKey:M}=S.family,F=f.get(T);if(F&&"familyMembers"in F){if(F.familyMembers.delete(M),F.familyMembers.size===0)f.delete(T)}}else f.delete(S.key);return f})})}]},void 0);return En(o,{key:"\uD83D\uDD0D Atom Token Index",get:({get:t})=>t(n)})};var OT=(o)=>{const n=nn(o,{key:"\uD83D\uDD0D Selector Token Index (Internal)",default:()=>{const t=new Map;for(let S of[o.readonlySelectors,o.selectors])for(let[f,T]of S)if(!f.includes("\uD83D\uDD0D")){const M=Po(T);if(T.family){let F=t.get(T.family.key);if(!F||!("familyMembers"in F))F={key:T.family.key,familyMembers:new Map},t.set(T.family.key,F);F.familyMembers.set(T.family.subKey,M)}else t.set(f,M)}return t},effects:[({setSelf:t})=>{o.on.selectorCreation.subscribe("introspection",(S)=>{if(S.key.includes("\uD83D\uDD0D"))return;t((f)=>{if(S.family){const{key:T,subKey:M}=S.family;let F=f.get(T);if(F===void 0||!("familyMembers"in F))F={key:T,familyMembers:new Map},f.set(T,F);F.familyMembers.set(M,S)}else f.set(S.key,S);return f})}),o.on.selectorDisposal.subscribe("introspection",(S)=>{t((f)=>{if(S.family){const{key:T,subKey:M}=S.family,F=f.get(T);if(F&&"familyMembers"in F){if(F.familyMembers.delete(M),F.familyMembers.size===0)f.delete(T)}}else f.delete(S.key);return f})})}]},void 0);return En(o,{key:"\uD83D\uDD0D Selector Token Index",get:({get:t})=>t(n)})};function _T(o){if(!o)return!1;return Object.getPrototypeOf(o)===Object.prototype}class Sf{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(S){try{if(o instanceof t)return{type:n,data:o}}catch(f){}}return null}}var WT=new Sf({number:(o)=>typeof o==="number",string:(o)=>typeof o==="string",boolean:(o)=>typeof o==="boolean",null:(o)=>o===null}),wT=new Sf({object:_T,array:(o)=>Array.isArray(o)}),ky=new Sf({...WT.supported,...wT.supported}),Dt=(o)=>{if(o===void 0)return"undefined";const n=ky.refine(o);if(n)return n.type;return Object.getPrototypeOf(o).constructor.name};class GF{o;auditorCreatedAt=performance.now();statesCreatedAt=new Map;atomIndex;selectorIndex;disposed=!1;unsubscribeFromAtomCreation;unsubscribeFromAtomDisposal;unsubscribeFromSelectorCreation;unsubscribeFromSelectorDisposal;constructor(o=ko.STORE){this.store=o;this.atomIndex=RT(this.store),this.selectorIndex=OT(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=GF.DEFAULT_LIST_RESOURCES_PARAM){if(this.disposed)throw new Error("This Auditor has been disposed");const n=ef(this.atomIndex),t=ef(this.selectorIndex),S=[...n.values()].filter((F)=>("familyMembers"in F)),f=[...t.values()].filter((F)=>("familyMembers"in F)),T=performance.now(),M=[];if(o.atomFamilies)for(let F of S){const k=F.familyMembers.values();for(let A of k){const O=this.statesCreatedAt.get(A.key)??this.auditorCreatedAt,w=T-O;M.push([A,w])}}if(o.selectorFamilies)for(let F of f){const k=F.familyMembers.values();for(let A of k){const O=this.statesCreatedAt.get(A.key)??this.auditorCreatedAt,w=T-O;M.push([A,w])}}return M}[Symbol.dispose](){this.unsubscribeFromAtomCreation(),this.unsubscribeFromAtomDisposal(),this.unsubscribeFromSelectorCreation(),this.unsubscribeFromSelectorDisposal(),this.disposed=!0}}var KT=(o,n)=>{const t=(S,f)=>{const M=((k,A)=>{const $=n(k,A);if($)return $;return null})(S,f);if(M?.jobComplete??M?.pathComplete)return M;const F=Array.isArray(f)?f.map((k,A)=>[A,k]):_T(f)?Object.entries(f):[];for(let[k,A]of F){const $=t([...S,k],A);if($?.jobComplete)return $}return{}};t([],o)};function Ay(o,n){return{summary:`${o<n?"+":"-"}${Math.abs(o-n)} (${o} \u2192 ${n})`}}function $y(o,n){return{summary:`${o.length<n.length?"+":"-"}${Math.abs(o.length-n.length)} ("${o}" \u2192 "${n}")`}}function Jy(o,n){return{summary:`${o} \u2192 ${n}`}}function HF(o,n,t){let S="";const f=[],T=[],M=[];return KT(o,(F,k)=>{let A;for(A of F){const $=n[A];if($===void 0)T.push([A,JSON.stringify(k)]);else{const O=t(k,$);if(O.summary!=="No Change")M.push([A,O])}}}),KT(n,(F,k)=>{let A;for(A of F)if(o[A]===void 0)f.push([A,JSON.stringify(k)])}),S=`\uFF5E${M.length} \uFF0B${f.length} \uFF0D${T.length}`,{summary:S,added:f,removed:T,changed:M}}function yy(o,n,t){return HF(o,n,t)}class mF{leafRefinery;treeRefinery;leafDiffers;treeDiffers;constructor(o,n,t){this.leafRefinery=o,this.treeRefinery=n,this.leafDiffers={},this.treeDiffers={};for(let S of Object.keys(o.supported)){const f=t[S];this.leafDiffers[S]=f}for(let S of Object.keys(n.supported)){const f=t[S];this.treeDiffers[S]=f}}diff(o,n){if(o===n)return{summary:"No Change"};const t=this.leafRefinery.refine(o)??this.treeRefinery.refine(o),S=this.leafRefinery.refine(n)??this.treeRefinery.refine(n);if(t!==null&&S!==null){if(t.type===S.type){if(t.type in this.leafDiffers)return this.leafDiffers[t.type](t.data,S.data);if(t.type in this.treeDiffers)return this.treeDiffers[t.type](t.data,S.data,(F,k)=>this.diff(F,k))}}const f=Dt(o),T=Dt(n);if(f===T)return{summary:`${f} \u2192 ${T}`};return{summary:`Type change: ${f} \u2192 ${T}`}}}var LX=new mF(WT,wT,{number:Ay,string:$y,boolean:Jy,null:()=>({summary:"No Change"}),object:HF,array:yy});class Ut{o;listeners;globalListeners;handleEvent(o,...n){for(let S of this.globalListeners)S(o,...n);const t=this.listeners.get(o);if(t)for(let S of t)S(...n)}id="no_id_retrieved";constructor(o){this.emit=o;this.listeners=new Map,this.globalListeners=new Set}on(o,n){const 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){const 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 XT extends Ut{o;n;t;incompleteData="";unprocessedEvents=[];incompleteLog="";unprocessedLogs=[];id="#####";handleLog(o){if(Array.isArray(o)){const[n,...t]=o;switch(n){case"i":this.logger.info(this.id,this.key,...t);break;case"w":this.logger.warn(this.id,this.key,...t);break;case"e":this.logger.error(this.id,this.key,...t);break}}}constructor(o,n,t=console){super((S,...f)=>{const T=JSON.stringify([S,...f])+"\x03",M=(F)=>{if(F.code==="EPIPE")console.error("EPIPE error during write",this.process.stdin);this.process.stdin.removeListener("error",M)};return this.process.stdin.once("error",M),this.process.stdin.write(T),this});this.process=o;this.key=n;this.logger=t;if(this.process=o,this.process.stdout.on("data",(S)=>{const f=S.toString();if(f==="\u2728")return;this.unprocessedEvents.push(...f.split("\x03"));const T=this.unprocessedEvents.shift();this.incompleteData+=T??"";try{if(this.incompleteData.startsWith("error"))console.log("\u2757",this.incompleteData);let M=Uo(this.incompleteData);this.handleEvent(...M);while(this.unprocessedEvents.length>0){const F=this.unprocessedEvents.shift();if(F){if(this.unprocessedEvents.length===0)this.incompleteData=F;M=Uo(F),this.handleEvent(...M)}}this.incompleteData=""}catch(M){console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.warn(this.incompleteData),console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.error(M)}}),this.process.stderr.on("data",(S)=>{const f=S.toString();this.unprocessedLogs.push(...f.split("\x03"));const T=this.unprocessedLogs.shift();this.incompleteLog+=T??"";try{let M=Uo(this.incompleteLog);this.handleLog(M);while(this.unprocessedLogs.length>0)if(this.incompleteLog=this.unprocessedLogs.shift()??"",this.incompleteLog)M=Uo(this.incompleteLog),this.handleLog(M)}catch(M){console.error("\u274C\u274C\u274C"),console.error(this.incompleteLog),console.error(M),console.error("\u274C\u274C\u274C\uFE0F")}}),o.pid)this.id=o.pid.toString()}}class QF extends Ut{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 YT extends Ut{incompleteData="";unprocessedEvents=[];relays;relayServices;process;id="#####";log(...o){this.process.stderr.write(l(o.map((n)=>n instanceof co?`{ ${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)=>{const 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)=>{const n=o.toString();this.unprocessedEvents.push(...n.split("\x03"));const t=this.unprocessedEvents.shift();this.incompleteData+=t??"";try{const S=Uo(this.incompleteData);this.logger.info("\uD83C\uDFB0","received",S),this.handleEvent(...S);while(this.unprocessedEvents.length>0){const f=this.unprocessedEvents.shift();if(f){if(this.unprocessedEvents.length===0)this.incompleteData=f;const T=Uo(f);this.handleEvent(...T)}}this.incompleteData=""}catch(S){if(S instanceof Error)this.logger.error("\u2757",S.message,S.cause,S.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");const n=new QF(`user:${o}`);this.relays.set(o,n),this.logger.info("\uD83D\uDD17","attaching services:",`[${[...this.relayServices.keys()].join(", ")}]`);for(let t of this.relayServices){const S=t(n);if(S)n.disposalFunctions.push(S)}this.on(`user:${o}`,(...t)=>{n.in.next(t)}),n.out.subscribe("socket",(t)=>{this.emit(...t)})}),this.on("user-leaves",(o)=>{const n=this.relays.get(o);if(this.off(`relay:${o}`),n)n.dispose(),this.relays.delete(o)}),process.stdout.write("\u2728")}relay(o){this.logger.info("\uD83D\uDD17","running relay method"),this.relayServices.push(o)}}class DF 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 ET{o;type="continuity";globals=[];actions=[];perspectives=[];constructor(o){this.key=o}static existing=new DF;static create(o,n){const t=new ET(o),{type:S,globals:f,actions:T,perspectives:M}=n(t),F={type:S,key:o,globals:f,actions:T,perspectives:M};return ET.existing.set(o,F),F}add(...o){switch(o[0].type){case"atom":case"mutable_atom":this.globals.push(...o);break;case"transaction":this.actions.push(...o);break;case"atom_family":{const[t,S]=o;this.perspectives.push({type:"realtime_perspective",resourceAtoms:t,viewAtoms:S})}break}return this}}var A8=Ht({key:"usersInRoomIndex",mutable:!0,default:()=>new co,toJson:(o)=>o.toJSON(),fromJson:(o)=>co.fromJSON(o)}),zT=Ht({key:"roomIndex",default:()=>new co,mutable:!0,toJson:(o)=>o.toJSON(),fromJson:(o)=>co.fromJSON(o)}),Ry={enteredAtEpoch:0},JS=gS({key:"usersInRooms",between:["room","user"],cardinality:"1:n"},Ry),$8=vS({key:"usersInMyRoomView",get:(o)=>({find:n})=>{const t=AF(JS);return[n(t,o)]}});import{spawn as Oy}from"child_process";var GT=kt({key:"roomArguments",default:["echo",["Hello World!"]]}),UF=vS({key:"room",get:(o)=>async({get:n,find:t})=>{const S=t(GT,o),f=n(S),[T,M]=f,F=await new Promise((k)=>{const A=Oy(T,M,{env:process.env}),$=(O)=>{if(O.toString()==="\u2728")A.stdout.off("data",$),k(A)};A.stdout.on("data",$)});return new XT(F,o)}});var H8=TS({key:"createRoom",do:({get:o,set:n,find:t},S,f,T)=>{const M=T?[f,T]:[f],F=t(GT,S);n(F,M),n(zT,($)=>$.add(S));const k=t(UF,S);return o(k)}}),m8=TS({key:"joinRoom",do:(o,n,t,S)=>{const f={enteredAtEpoch:S};return lS(JS,(T)=>{T.set({room:n,user:t},f)},o.env().store),f}}),Q8=TS({key:"leaveRoom",do:(o,n,t)=>{lS(JS,(S)=>{S.delete({room:n,user:t})},o.env().store)}}),D8=TS({key:"destroyRoom",do:(o,n)=>{lS(JS,(t)=>{t.delete({room:n})},o.env().store),o.set(zT,(t)=>(t.delete(n),t))}});var r8=kt({key:"transactionRedactor",default:{occlude:(o)=>o}}),Wy=kt({key:"unacknowledgedUpdates",default:()=>[]});var _y=kt({key:"sockets",default:null}),c8=Ht({key:"socketsIndex",mutable:!0,default:()=>new co,toJson:(o)=>o.toJSON(),fromJson:(o)=>co.fromJSON(o)}),B8=Ht({key:"usersIndex",mutable:!0,default:()=>new co,toJson:(o)=>o.toJSON(),fromJson:(o)=>co.fromJSON(o)}),wy=gS({key:"usersOfSockets",between:["user","socket"],cardinality:"1:1"});var{file:MJ,serve:z0}=globalThis.Bun;function X(o,n){if(!o||typeof o!=="object")return!1;if(o instanceof n)return!0;if(!Object.prototype.hasOwnProperty.call(n,y))throw new Error(`Class "${n.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let t=o.constructor;if(t)while(t){if(y in t&&t[y]===n[y])return!0;t=Object.getPrototypeOf(t)}return!1}var y=Symbol.for("drizzle:entityKind"),w5=Symbol.for("drizzle:hasOwnEntityKind");class Ko{constructor(o,n){this.table=o,this.config=n,this.name=n.name,this.keyAsName=n.keyAsName,this.notNull=n.notNull,this.default=n.default,this.defaultFn=n.defaultFn,this.onUpdateFn=n.onUpdateFn,this.hasDefault=n.hasDefault,this.primary=n.primaryKey,this.isUnique=n.isUnique,this.uniqueName=n.uniqueName,this.uniqueType=n.uniqueType,this.dataType=n.dataType,this.columnType=n.columnType,this.generated=n.generated,this.generatedIdentity=n.generatedIdentity}static[y]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue(o){return o}mapToDriverValue(o){return o}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}class HT{static[y]="ColumnBuilder";config;constructor(o,n,t){this.config={name:o,keyAsName:o==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:n,columnType:t,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(o){return this.config.default=o,this.config.hasDefault=!0,this}$defaultFn(o){return this.config.defaultFn=o,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(o){return this.config.onUpdateFn=o,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(o){if(this.config.name!=="")return;this.config.name=o}}var Hn=Symbol.for("drizzle:Name");class mT{static[y]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(o,n){if(this.reference=()=>{const{name:t,columns:S,foreignColumns:f}=o();return{name:t,columns:S,foreignTable:f[0].table,foreignColumns:f}},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 VF(o,this)}}class VF{constructor(o,n){this.table=o,this.reference=n.reference,this.onUpdate=n._onUpdate,this.onDelete=n._onDelete}static[y]="PgForeignKey";reference;onUpdate;onDelete;getName(){const{name:o,columns:n,foreignColumns:t}=this.reference(),S=n.map((M)=>M.name),f=t.map((M)=>M.name),T=[this.table[Hn],...S,t[0].table[Hn],...f];return o??`${T.join("_")}_fk`}}function ff(o,...n){return o(...n)}function rF(o,n){return`${o[Hn]}_${n.join("_")}_unique`}function CF(o,n,t){for(let S=n;S<o.length;S++){const f=o[S];if(f==="\\"){S++;continue}if(f==='"')return[o.slice(n,S).replace(/\\/g,""),S+1];if(t)continue;if(f===","||f==="}")return[o.slice(n,S).replace(/\\/g,""),S]}return[o.slice(n).replace(/\\/g,""),o.length]}function LF(o,n=0){const t=[];let S=n,f=!1;while(S<o.length){const T=o[S];if(T===","){if(f||S===n)t.push("");f=!0,S++;continue}if(f=!1,T==="\\"){S+=2;continue}if(T==='"'){const[k,A]=CF(o,S+1,!0);t.push(k),S=A;continue}if(T==="}")return[t,S+1];if(T==="{"){const[k,A]=LF(o,S+1);t.push(k),S=A;continue}const[M,F]=CF(o,S,!1);t.push(M),S=F}return[t,S]}function IF(o){const[n]=LF(o,1);return n}function QT(o){return`{${o.map((n)=>{if(Array.isArray(n))return QT(n);if(typeof n==="string")return`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`;return`${n}`}).join(",")}}`}class B extends HT{foreignKeyConfigs=[];static[y]="PgColumnBuilder";array(o){return new cF(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:S})=>{return ff((f,T)=>{const M=new mT(()=>{const F=f();return{columns:[o],foreignColumns:[F]}});if(T.onUpdate)M.onUpdate(T.onUpdate);if(T.onDelete)M.onDelete(T.onDelete);return M.build(n)},t,S)})}buildExtraConfigColumn(o){return new jF(o,this.config)}}class U extends Ko{constructor(o,n){if(!n.uniqueName)n.uniqueName=rF(o,[n.name]);super(o,n);this.table=o}static[y]="PgColumn"}class jF extends U{static[y]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op(o){return this.indexConfig.opClass=o,this}}class yS{static[y]="IndexedColumn";constructor(o,n,t,S){this.name=o,this.keyAsName=n,this.type=t,this.indexConfig=S}name;keyAsName;type;indexConfig}class cF extends B{static[y]="PgArrayBuilder";constructor(o,n,t){super(o,"array","PgArray");this.config.baseBuilder=n,this.config.size=t}build(o){const n=this.config.baseBuilder.build(o);return new DT(o,this.config,n)}}class DT extends U{constructor(o,n,t,S){super(o,n);this.baseColumn=t,this.range=S,this.size=n.size}size;static[y]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(o){if(typeof o==="string")o=IF(o);return o.map((n)=>this.baseColumn.mapFromDriverValue(n))}mapToDriverValue(o,n=!1){const t=o.map((S)=>S===null?null:X(this.baseColumn,DT)?this.baseColumn.mapToDriverValue(S,!0):this.baseColumn.mapToDriverValue(S));if(n)return t;return QT(t)}}function BF(o){return!!o&&typeof o==="function"&&UT in o&&o[UT]===!0}function Tf(o,n){return Ky(o,n,void 0)}function Ky(o,n,t){const S=Object.assign((f)=>new bF(f??"",S),{enumName:o,enumValues:n,schema:t,[UT]:!0});return S}var UT=Symbol.for("drizzle:isPgEnum");class bF extends B{static[y]="PgEnumColumnBuilder";constructor(o,n){super(o,"string","PgEnumColumn");this.config.enum=n}build(o){return new NF(o,this.config)}}class NF extends U{static[y]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(o,n){super(o,n);this.enum=n.enum}getSQLType(){return this.enum.enumName}}class xo{static[y]="Subquery";constructor(o,n,t,S=!1){this._={brand:"Subquery",sql:o,selectedFields:n,alias:t,isWith:S}}}class RS extends xo{static[y]="WithSubquery"}var hF="0.34.1";var VT,rT,Oo={startActiveSpan(o,n){if(!VT)return n();if(!rT)rT=VT.trace.getTracer("drizzle-orm",hF);return ff((t,S)=>S.startActiveSpan(o,(f)=>{try{return n(f)}catch(T){throw f.setStatus({code:t.SpanStatusCode.ERROR,message:T instanceof Error?T.message:"Unknown error"}),T}finally{f.end()}}),VT,rT)}};var mo=Symbol.for("drizzle:ViewBaseConfig");function Wn(o){return o[Hn]}function $t(o){return`${o[Mf]??"public"}.${o[Hn]}`}var Mf=Symbol.for("drizzle:Schema"),xF=Symbol.for("drizzle:Columns"),iF=Symbol.for("drizzle:ExtraConfigColumns"),CT=Symbol.for("drizzle:OriginalName"),LT=Symbol.for("drizzle:BaseName"),vF=Symbol.for("drizzle:IsAlias"),qF=Symbol.for("drizzle:ExtraConfigBuilder"),Xy=Symbol.for("drizzle:IsDrizzleTable");class j{static[y]="Table";static Symbol={Name:Hn,Schema:Mf,OriginalName:CT,Columns:xF,ExtraConfigColumns:iF,BaseName:LT,IsAlias:vF,ExtraConfigBuilder:qF};[Hn];[CT];[Mf];[xF];[iF];[LT];[vF]=!1;[Xy]=!0;[qF]=void 0;constructor(o,n,t){this[Hn]=this[CT]=o,this[Mf]=n,this[LT]=t}}function IT(o){return o!==null&&o!==void 0&&typeof o.getSQL==="function"}function Yy(o){const 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}function pF(o){return typeof o==="object"&&o!==null&&"mapToDriverValue"in o&&typeof o.mapToDriverValue==="function"}function R(o,...n){const t=[];if(n.length>0||o.length>0&&o[0]!=="")t.push(new Bo(o[0]));for(let[S,f]of n.entries())t.push(f,new Bo(o[S+1]));return new b(t)}function jT(o,n){return o.map((t)=>{if(X(t,an)){if(!(t.name in n))throw new Error(`No value for placeholder "${t.name}" was provided`);return n[t.name]}if(X(t,An)&&X(t.value,an)){if(!(t.value.name in n))throw new Error(`No value for placeholder "${t.value.name}" was provided`);return t.encoder.mapToDriverValue(n[t.value.name])}return t})}class Bo{static[y]="StringChunk";value;constructor(o){this.value=Array.isArray(o)?o:[o]}getSQL(){return new b([this])}}class b{constructor(o){this.queryChunks=o}static[y]="SQL";decoder=ZF;shouldInlineParams=!1;append(o){return this.queryChunks.push(...o.queryChunks),this}toQuery(o){return Oo.startActiveSpan("drizzle.buildSQL",(n)=>{const 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){const t=Object.assign({},n,{inlineParams:n.inlineParams||this.shouldInlineParams,paramStartIndex:n.paramStartIndex||{value:0}}),{casing:S,escapeName:f,escapeParam:T,prepareTyping:M,inlineParams:F,paramStartIndex:k}=t;return Yy(o.map((A)=>{if(X(A,Bo))return{sql:A.value.join(""),params:[]};if(X(A,Ff))return{sql:f(A.value),params:[]};if(A===void 0)return{sql:"",params:[]};if(Array.isArray(A)){const $=[new Bo("(")];for(let[O,w]of A.entries())if($.push(w),O<A.length-1)$.push(new Bo(", "));return $.push(new Bo(")")),this.buildQueryFromSourceParams($,t)}if(X(A,b))return this.buildQueryFromSourceParams(A.queryChunks,{...t,inlineParams:F||A.shouldInlineParams});if(X(A,j)){const $=A[j.Symbol.Schema],O=A[j.Symbol.Name];return{sql:$===void 0?f(O):f($)+"."+f(O),params:[]}}if(X(A,Ko)){const $=S.getColumnCasing(A);if(n.invokeSource==="indexes")return{sql:f($),params:[]};return{sql:f(A.table[j.Symbol.Name])+"."+f($),params:[]}}if(X(A,Sn)){const $=A[mo].schema,O=A[mo].name;return{sql:$===void 0?f(O):f($)+"."+f(O),params:[]}}if(X(A,An)){if(X(A.value,an))return{sql:T(k.value++,A),params:[A],typings:["none"]};const $=A.value===null?null:A.encoder.mapToDriverValue(A.value);if(X($,b))return this.buildQueryFromSourceParams([$],t);if(F)return{sql:this.mapInlineParam($,t),params:[]};let O=["none"];if(M)O=[M(A.encoder)];return{sql:T(k.value++,$),params:[$],typings:O}}if(X(A,an))return{sql:T(k.value++,A),params:[A],typings:["none"]};if(X(A,b.Aliased)&&A.fieldAlias!==void 0)return{sql:f(A.fieldAlias),params:[]};if(X(A,xo)){if(A._.isWith)return{sql:f(A._.alias),params:[]};return this.buildQueryFromSourceParams([new Bo("("),A._.sql,new Bo(") "),new Ff(A._.alias)],t)}if(BF(A)){if(A.schema)return{sql:f(A.schema)+"."+f(A.enumName),params:[]};return{sql:f(A.enumName),params:[]}}if(IT(A)){if(A.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([A.getSQL()],t);return this.buildQueryFromSourceParams([new Bo("("),A.getSQL(),new Bo(")")],t)}if(F)return{sql:this.mapInlineParam(A,t),params:[]};return{sql:T(k.value++,A),params:[A],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"){const 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 b.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 Ff{constructor(o){this.value=o}static[y]="Name";brand;getSQL(){return new b([this])}}var ZF={mapFromDriverValue:(o)=>o},PF={mapToDriverValue:(o)=>o},TY={...ZF,...PF};class An{constructor(o,n=PF){this.value=o,this.encoder=n}static[y]="Param";brand;getSQL(){return new b([this])}}((o)=>{function n(){return new b([])}o.empty=n;function t(k){return new b(k)}o.fromList=t;function S(k){return new b([new Bo(k)])}o.raw=S;function f(k,A){const $=[];for(let[O,w]of k.entries()){if(O>0&&A!==void 0)$.push(A);$.push(w)}return new b($)}o.join=f;function T(k){return new Ff(k)}o.identifier=T;function M(k){return new an(k)}o.placeholder=M;function F(k,A){return new An(k,A)}o.param=F})(R||(R={}));((o)=>{class n{constructor(t,S){this.sql=t,this.fieldAlias=S}static[y]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new n(this.sql,this.fieldAlias)}}o.Aliased=n})(b||(b={}));class an{constructor(o){this.name=o}static[y]="Placeholder";getSQL(){return new b([this])}}class Sn{static[y]="View";[mo];constructor({name:o,schema:n,selectedFields:t,query:S}){this[mo]={name:o,originalName:o,schema:n,selectedFields:t,query:S,isExisting:!S,isAlias:!1}}getSQL(){return new b([this])}}Ko.prototype.getSQL=function(){return new b([this])};j.prototype.getSQL=function(){return new b([this])};xo.prototype.getSQL=function(){return new b([this])};function kf(o,n){return new Proxy(o,new OS(n,!1))}function cn(o,n){return new Proxy(o,new Vt(new Proxy(o.table,new OS(n,!1))))}function cT(o,n){return new b.Aliased(WS(o.sql,n),o.fieldAlias)}function WS(o,n){return R.join(o.queryChunks.map((t)=>{if(X(t,Ko))return cn(t,n);if(X(t,b))return WS(t,n);if(X(t,b.Aliased))return cT(t,n);return t}))}class Vt{constructor(o){this.table=o}static[y]="ColumnAliasProxyHandler";get(o,n){if(n==="table")return this.table;return o[n]}}class OS{constructor(o,n){this.alias=o,this.replaceOriginalName=n}static[y]="TableAliasProxyHandler";get(o,n){if(n===j.Symbol.IsAlias)return!0;if(n===j.Symbol.Name)return this.alias;if(this.replaceOriginalName&&n===j.Symbol.OriginalName)return this.alias;if(n===mo)return{...o[mo],name:this.alias,isAlias:!0};if(n===j.Symbol.Columns){const S=o[j.Symbol.Columns];if(!S)return S;const f={};return Object.keys(S).map((T)=>{f[T]=new Proxy(S[T],new Vt(new Proxy(o,this)))}),f}const t=o[n];if(X(t,Ko))return new Proxy(t,new Vt(new Proxy(o,this)));return t}}class Af extends Error{static[y]="DrizzleError";constructor({message:o,cause:n}){super(o);this.name="DrizzleError",this.cause=n}}class BT extends Af{static[y]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}function fn(o,n){if(pF(n)&&!IT(o)&&!X(o,An)&&!X(o,an)&&!X(o,Ko)&&!X(o,j)&&!X(o,Sn))return new An(o,n);return o}function _S(...o){const n=o.filter((t)=>t!==void 0);if(n.length===0)return;if(n.length===1)return new b(n);return new b([new Bo("("),R.join(n,new Bo(" and ")),new Bo(")")])}function lF(...o){const n=o.filter((t)=>t!==void 0);if(n.length===0)return;if(n.length===1)return new b(n);return new b([new Bo("("),R.join(n,new Bo(" or ")),new Bo(")")])}function eF(o){return R`not ${o}`}function ok(o,n){if(Array.isArray(n)){if(n.length===0)return R`false`;return R`${o} in ${n.map((t)=>fn(t,o))}`}return R`${o} in ${fn(n,o)}`}function nk(o,n){if(Array.isArray(n)){if(n.length===0)return R`true`;return R`${o} not in ${n.map((t)=>fn(t,o))}`}return R`${o} not in ${fn(n,o)}`}function tk(o){return R`${o} is null`}function Sk(o){return R`${o} is not null`}function fk(o){return R`exists ${o}`}function Tk(o){return R`not exists ${o}`}function Mk(o,n,t){return R`${o} between ${fn(n,o)} and ${fn(t,o)}`}function Fk(o,n,t){return R`${o} not between ${fn(n,o)} and ${fn(t,o)}`}function kk(o,n){return R`${o} like ${n}`}function Ak(o,n){return R`${o} not like ${n}`}function $k(o,n){return R`${o} ilike ${n}`}function Jk(o,n){return R`${o} not ilike ${n}`}var rt=(o,n)=>{return R`${o} = ${fn(n,o)}`},gF=(o,n)=>{return R`${o} <> ${fn(n,o)}`},dF=(o,n)=>{return R`${o} > ${fn(n,o)}`},uF=(o,n)=>{return R`${o} >= ${fn(n,o)}`},aF=(o,n)=>{return R`${o} < ${fn(n,o)}`},sF=(o,n)=>{return R`${o} <= ${fn(n,o)}`};function yk(o){return R`${o} asc`}function Rk(o){return R`${o} desc`}class Ok{static[y]="ConsoleLogWriter";write(o){console.log(o)}}class bT{static[y]="DefaultLogger";writer;constructor(o){this.writer=o?.writer??new Ok}logQuery(o,n){const t=n.map((f)=>{try{return JSON.stringify(f)}catch{return String(f)}}),S=t.length?` -- params: [${t.join(", ")}]`:"";this.writer.write(`Query: ${o}${S}`)}}class NT{static[y]="NoopLogger";logQuery(){}}class ao{static[y]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(o){return this.then(void 0,o)}finally(o){return this.then((n)=>{return o?.(),n},(n)=>{throw o?.(),n})}then(o,n){return this.execute().then(o,n)}}function Wk(o,n,t){const S={},f=o.reduce((T,{path:M,field:F},k)=>{let A;if(X(F,Ko))A=F;else if(X(F,b))A=F.decoder;else A=F.sql.decoder;let $=T;for(let[O,w]of M.entries())if(O<M.length-1){if(!(w in $))$[w]={};$=$[w]}else{const z=n[k],r=$[w]=z===null?null:A.mapFromDriverValue(z);if(t&&X(F,Ko)&&M.length===2){const H=M[0];if(!(H in S))S[H]=r===null?Wn(F.table):!1;else if(typeof S[H]==="string"&&S[H]!==Wn(F.table))S[H]=!1}}return T},{});if(t&&Object.keys(S).length>0){for(let[T,M]of Object.entries(S))if(typeof M==="string"&&!t[M])f[T]=null}return f}function _n(o,n){return Object.entries(o).reduce((t,[S,f])=>{if(typeof S!=="string")return t;const T=n?[...n,S]:[S];if(X(f,Ko)||X(f,b)||X(f,b.Aliased))t.push({path:T,field:f});else if(X(f,j))t.push(..._n(f[j.Symbol.Columns],T));else t.push(..._n(f,T));return t},[])}function hT(o,n){const t=Object.keys(o),S=Object.keys(n);if(t.length!==S.length)return!1;for(let[f,T]of t.entries())if(T!==S[f])return!1;return!0}function $f(o,n){const t=Object.entries(n).filter(([,S])=>S!==void 0).map(([S,f])=>{if(X(f,b))return[S,f];else return[S,new An(f,o[j.Symbol.Columns][S])]});if(t.length===0)throw new Error("No values to set");return Object.fromEntries(t)}function _k(o,n){for(let t of n)for(let S of Object.getOwnPropertyNames(t.prototype)){if(S==="constructor")continue;Object.defineProperty(o.prototype,S,Object.getOwnPropertyDescriptor(t.prototype,S)||Object.create(null))}}function wk(o){return o[j.Symbol.Columns]}function xT(o){return X(o,xo)?o._.alias:X(o,Sn)?o[mo].name:X(o,b)?void 0:o[j.Symbol.IsAlias]?o[j.Symbol.Name]:o[j.Symbol.BaseName]}function Mo(o,n){return{name:typeof o==="string"&&o.length>0?o:"",config:typeof o==="object"?o:n}}class sn extends B{static[y]="PgIntColumnBaseBuilder";generatedAlwaysAsIdentity(o){if(o){const{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){const{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}}function zk(o,n){const{name:t,config:S}=Mo(o,n);if(S.mode==="number")return new Kk(t);return new Yk(t)}class Kk extends sn{static[y]="PgBigInt53Builder";constructor(o){super(o,"number","PgBigInt53")}build(o){return new Xk(o,this.config)}}class Xk extends U{static[y]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(o){if(typeof o==="number")return o;return Number(o)}}class Yk extends sn{static[y]="PgBigInt64Builder";constructor(o){super(o,"bigint","PgBigInt64")}build(o){return new Ek(o,this.config)}}class Ek extends U{static[y]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(o){return BigInt(o)}}function Dk(o,n){const{name:t,config:S}=Mo(o,n);if(S.mode==="number")return new Gk(t);return new mk(t)}class Gk extends B{static[y]="PgBigSerial53Builder";constructor(o){super(o,"number","PgBigSerial53");this.config.hasDefault=!0,this.config.notNull=!0}build(o){return new Hk(o,this.config)}}class Hk extends U{static[y]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(o){if(typeof o==="number")return o;return Number(o)}}class mk extends B{static[y]="PgBigSerial64Builder";constructor(o){super(o,"bigint","PgBigSerial64");this.config.hasDefault=!0}build(o){return new Qk(o,this.config)}}class Qk extends U{static[y]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(o){return BigInt(o)}}function wS(o){return new Uk(o??"")}class Uk extends B{static[y]="PgBooleanBuilder";constructor(o){super(o,"boolean","PgBoolean")}build(o){return new Vk(o,this.config)}}class Vk extends U{static[y]="PgBoolean";getSQLType(){return"boolean"}}function Lk(o,n={}){const{name:t,config:S}=Mo(o,n);return new rk(t,S)}class rk extends B{static[y]="PgCharBuilder";constructor(o,n){super(o,"string","PgChar");this.config.length=n.length,this.config.enumValues=n.enum}build(o){return new Ck(o,this.config)}}class Ck extends U{static[y]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}}function ck(o){return new Ik(o??"")}class Ik extends B{static[y]="PgCidrBuilder";constructor(o){super(o,"string","PgCidr")}build(o){return new jk(o,this.config)}}class jk extends U{static[y]="PgCidr";getSQLType(){return"cidr"}}function Nk(o){return(n,t)=>{const{name:S,config:f}=Mo(n,t);return new Bk(S,f,o)}}class Bk extends B{static[y]="PgCustomColumnBuilder";constructor(o,n,t){super(o,"custom","PgCustomColumn");this.config.fieldConfig=n,this.config.customTypeParams=t}build(o){return new bk(o,this.config)}}class bk extends U{static[y]="PgCustomColumn";sqlName;mapTo;mapFrom;constructor(o,n){super(o,n);this.sqlName=n.customTypeParams.dataType(n.fieldConfig),this.mapTo=n.customTypeParams.toDriver,this.mapFrom=n.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(o){return typeof this.mapFrom==="function"?this.mapFrom(o):o}mapToDriverValue(o){return typeof this.mapTo==="function"?this.mapTo(o):o}}class qn extends B{static[y]="PgDateColumnBaseBuilder";defaultNow(){return this.default(R`now()`)}}function ik(o,n){const{name:t,config:S}=Mo(o,n);if(S?.mode==="date")return new hk(t);return new xk(t)}class hk extends qn{static[y]="PgDateBuilder";constructor(o){super(o,"date","PgDate")}build(o){return new Jf(o,this.config)}}class Jf extends U{static[y]="PgDate";getSQLType(){return"date"}mapFromDriverValue(o){return new Date(o)}mapToDriverValue(o){return o.toISOString()}}class xk extends qn{static[y]="PgDateStringBuilder";constructor(o){super(o,"string","PgDateString")}build(o){return new yf(o,this.config)}}class yf extends U{static[y]="PgDateString";getSQLType(){return"date"}}function pk(o){return new vk(o??"")}class vk extends B{static[y]="PgDoublePrecisionBuilder";constructor(o){super(o,"number","PgDoublePrecision")}build(o){return new qk(o,this.config)}}class qk extends U{static[y]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(o){if(typeof o==="string")return Number.parseFloat(o);return o}}function gk(o){return new Zk(o??"")}class Zk extends B{static[y]="PgInetBuilder";constructor(o){super(o,"string","PgInet")}build(o){return new Pk(o,this.config)}}class Pk extends U{static[y]="PgInet";getSQLType(){return"inet"}}function Rf(o){return new lk(o??"")}class lk extends sn{static[y]="PgIntegerBuilder";constructor(o){super(o,"number","PgInteger")}build(o){return new ek(o,this.config)}}class ek extends U{static[y]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(o){if(typeof o==="string")return Number.parseInt(o);return o}}function ak(o,n={}){const{name:t,config:S}=Mo(o,n);return new dk(t,S)}class dk extends B{static[y]="PgIntervalBuilder";constructor(o,n){super(o,"string","PgInterval");this.config.intervalConfig=n}build(o){return new uk(o,this.config)}}class uk extends U{static[y]="PgInterval";fields=this.config.intervalConfig.fields;precision=this.config.intervalConfig.precision;getSQLType(){const o=this.fields?` ${this.fields}`:"",n=this.precision?`(${this.precision})`:"";return`interval${o}${n}`}}function oA(o){return new sk(o??"")}class sk extends B{static[y]="PgJsonBuilder";constructor(o){super(o,"json","PgJson")}build(o){return new Of(o,this.config)}}class Of extends U{static[y]="PgJson";constructor(o,n){super(o,n)}getSQLType(){return"json"}mapToDriverValue(o){return JSON.stringify(o)}mapFromDriverValue(o){if(typeof o==="string")try{return JSON.parse(o)}catch{return o}return o}}function tA(o){return new nA(o??"")}class nA extends B{static[y]="PgJsonbBuilder";constructor(o){super(o,"json","PgJsonb")}build(o){return new Wf(o,this.config)}}class Wf extends U{static[y]="PgJsonb";constructor(o,n){super(o,n)}getSQLType(){return"jsonb"}mapToDriverValue(o){return JSON.stringify(o)}mapFromDriverValue(o){if(typeof o==="string")try{return JSON.parse(o)}catch{return o}return o}}function FA(o,n){const{name:t,config:S}=Mo(o,n);if(!S?.mode||S.mode==="tuple")return new SA(t);return new TA(t)}class SA extends B{static[y]="PgLineBuilder";constructor(o){super(o,"array","PgLine")}build(o){return new fA(o,this.config)}}class fA extends U{static[y]="PgLine";getSQLType(){return"line"}mapFromDriverValue(o){const[n,t,S]=o.slice(1,-1).split(",");return[Number.parseFloat(n),Number.parseFloat(t),Number.parseFloat(S)]}mapToDriverValue(o){return`{${o[0]},${o[1]},${o[2]}}`}}class TA extends B{static[y]="PgLineABCBuilder";constructor(o){super(o,"json","PgLineABC")}build(o){return new MA(o,this.config)}}class MA extends U{static[y]="PgLineABC";getSQLType(){return"line"}mapFromDriverValue(o){const[n,t,S]=o.slice(1,-1).split(",");return{a:Number.parseFloat(n),b:Number.parseFloat(t),c:Number.parseFloat(S)}}mapToDriverValue(o){return`{${o.a},${o.b},${o.c}}`}}function $A(o){return new kA(o??"")}class kA extends B{static[y]="PgMacaddrBuilder";constructor(o){super(o,"string","PgMacaddr")}build(o){return new AA(o,this.config)}}class AA extends U{static[y]="PgMacaddr";getSQLType(){return"macaddr"}}function RA(o){return new JA(o??"")}class JA extends B{static[y]="PgMacaddr8Builder";constructor(o){super(o,"string","PgMacaddr8")}build(o){return new yA(o,this.config)}}class yA extends U{static[y]="PgMacaddr8";getSQLType(){return"macaddr8"}}function WA(o,n){const{name:t,config:S}=Mo(o,n);return new OA(t,S?.precision,S?.scale)}class OA extends B{static[y]="PgNumericBuilder";constructor(o,n,t){super(o,"string","PgNumeric");this.config.precision=n,this.config.scale=t}build(o){return new _f(o,this.config)}}class _f extends U{static[y]="PgNumeric";precision;scale;constructor(o,n){super(o,n);this.precision=n.precision,this.scale=n.scale}getSQLType(){if(this.precision!==void 0&&this.scale!==void 0)return`numeric(${this.precision}, ${this.scale})`;else if(this.precision===void 0)return"numeric";else return`numeric(${this.precision})`}}function YA(o,n){const{name:t,config:S}=Mo(o,n);if(!S?.mode||S.mode==="tuple")return new _A(t);return new KA(t)}class _A extends B{static[y]="PgPointTupleBuilder";constructor(o){super(o,"array","PgPointTuple")}build(o){return new wA(o,this.config)}}class wA extends U{static[y]="PgPointTuple";getSQLType(){return"point"}mapFromDriverValue(o){if(typeof o==="string"){const[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 KA extends B{static[y]="PgPointObjectBuilder";constructor(o){super(o,"json","PgPointObject")}build(o){return new XA(o,this.config)}}class XA extends U{static[y]="PgPointObject";getSQLType(){return"point"}mapFromDriverValue(o){if(typeof o==="string"){const[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 Ey(o){const 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 EA(o,n){const t=new ArrayBuffer(8),S=new DataView(t);for(let f=0;f<8;f++)S.setUint8(f,o[n+f]);return S.getFloat64(0,!0)}function iT(o){const n=Ey(o);let t=0;const S=n[t];t+=1;const f=new DataView(n.buffer),T=f.getUint32(t,S===1);t+=4;let M;if(T&536870912)M=f.getUint32(t,S===1),t+=4;if((T&65535)===1){const F=EA(n,t);t+=8;const k=EA(n,t);return t+=8,[F,k]}throw new Error("Unsupported geometry type")}function QA(o,n){const{name:t,config:S}=Mo(o,n);if(!S?.mode||S.mode==="tuple")return new zA(t);return new HA(t)}class zA extends B{static[y]="PgGeometryBuilder";constructor(o){super(o,"array","PgGeometry")}build(o){return new GA(o,this.config)}}class GA extends U{static[y]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(o){return iT(o)}mapToDriverValue(o){return`point(${o[0]} ${o[1]})`}}class HA extends B{static[y]="PgGeometryObjectBuilder";constructor(o){super(o,"json","PgGeometryObject")}build(o){return new mA(o,this.config)}}class mA extends U{static[y]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(o){const n=iT(o);return{x:n[0],y:n[1]}}mapToDriverValue(o){return`point(${o.x} ${o.y})`}}function VA(o){return new DA(o??"")}class DA extends B{static[y]="PgRealBuilder";constructor(o,n){super(o,"number","PgReal");this.config.length=n}build(o){return new UA(o,this.config)}}class UA extends U{static[y]="PgReal";constructor(o,n){super(o,n)}getSQLType(){return"real"}mapFromDriverValue=(o)=>{if(typeof o==="string")return Number.parseFloat(o);return o}}function LA(o){return new rA(o??"")}class rA extends B{static[y]="PgSerialBuilder";constructor(o){super(o,"number","PgSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(o){return new CA(o,this.config)}}class CA extends U{static[y]="PgSerial";getSQLType(){return"serial"}}function cA(o){return new IA(o??"")}class IA extends sn{static[y]="PgSmallIntBuilder";constructor(o){super(o,"number","PgSmallInt")}build(o){return new jA(o,this.config)}}class jA extends U{static[y]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=(o)=>{if(typeof o==="string")return Number(o);return o}}function NA(o){return new BA(o??"")}class BA extends B{static[y]="PgSmallSerialBuilder";constructor(o){super(o,"number","PgSmallSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(o){return new bA(o,this.config)}}class bA extends U{static[y]="PgSmallSerial";getSQLType(){return"smallserial"}}function iA(o,n={}){const{name:t,config:S}=Mo(o,n);return new hA(t,S)}class hA extends B{static[y]="PgTextBuilder";constructor(o,n){super(o,"string","PgText");this.config.enumValues=n.enum}build(o){return new xA(o,this.config)}}class xA extends U{static[y]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function qA(o,n={}){const{name:t,config:S}=Mo(o,n);return new vA(t,S.withTimezone??!1,S.precision)}class vA extends qn{constructor(o,n,t){super(o,"string","PgTime");this.withTimezone=n,this.precision=t,this.config.withTimezone=n,this.config.precision=t}static[y]="PgTimeBuilder";build(o){return new wf(o,this.config)}}class wf extends U{static[y]="PgTime";withTimezone;precision;constructor(o,n){super(o,n);this.withTimezone=n.withTimezone,this.precision=n.precision}getSQLType(){return`time${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function mn(o,n={}){const{name:t,config:S}=Mo(o,n);if(S?.mode==="string")return new ZA(t,S.withTimezone??!1,S.precision);return new pA(t,S?.withTimezone??!1,S?.precision)}class pA extends qn{static[y]="PgTimestampBuilder";constructor(o,n,t){super(o,"date","PgTimestamp");this.config.withTimezone=n,this.config.precision=t}build(o){return new Kf(o,this.config)}}class Kf extends U{static[y]="PgTimestamp";withTimezone;precision;constructor(o,n){super(o,n);this.withTimezone=n.withTimezone,this.precision=n.precision}getSQLType(){return`timestamp${this.precision===void 0?"":` (${this.precision})`}${this.withTimezone?" with time zone":""}`}mapFromDriverValue=(o)=>{return new Date(this.withTimezone?o:o+"+0000")};mapToDriverValue=(o)=>{return o.toISOString()}}class ZA extends qn{static[y]="PgTimestampStringBuilder";constructor(o,n,t){super(o,"string","PgTimestampString");this.config.withTimezone=n,this.config.precision=t}build(o){return new Xf(o,this.config)}}class Xf extends U{static[y]="PgTimestampString";withTimezone;precision;constructor(o,n){super(o,n);this.withTimezone=n.withTimezone,this.precision=n.precision}getSQLType(){return`timestamp${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function $n(o){return new PA(o??"")}class PA extends B{static[y]="PgUUIDBuilder";constructor(o){super(o,"string","PgUUID")}defaultRandom(){return this.default(R`gen_random_uuid()`)}build(o){return new Yf(o,this.config)}}class Yf extends U{static[y]="PgUUID";getSQLType(){return"uuid"}}function io(o,n={}){const{name:t,config:S}=Mo(o,n);return new gA(t,S)}class gA extends B{static[y]="PgVarcharBuilder";constructor(o,n){super(o,"string","PgVarchar");this.config.length=n.length,this.config.enumValues=n.enum}build(o){return new lA(o,this.config)}}class lA extends U{static[y]="PgVarchar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"varchar":`varchar(${this.length})`}}function uA(o,n){const{name:t,config:S}=Mo(o,n);return new eA(t,S)}class eA extends B{static[y]="PgBinaryVectorBuilder";constructor(o,n){super(o,"string","PgBinaryVector");this.config.dimensions=n.dimensions}build(o){return new dA(o,this.config)}}class dA extends U{static[y]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}}function o$(o,n){const{name:t,config:S}=Mo(o,n);return new aA(t,S)}class aA extends B{static[y]="PgHalfVectorBuilder";constructor(o,n){super(o,"array","PgHalfVector");this.config.dimensions=n.dimensions}build(o){return new sA(o,this.config)}}class sA extends U{static[y]="PgHalfVector";dimensions=this.config.dimensions;getSQLType(){return`halfvec(${this.dimensions})`}mapToDriverValue(o){return JSON.stringify(o)}mapFromDriverValue(o){return o.slice(1,-1).split(",").map((n)=>Number.parseFloat(n))}}function S$(o,n){const{name:t,config:S}=Mo(o,n);return new n$(t,S)}class n$ extends B{static[y]="PgSparseVectorBuilder";constructor(o,n){super(o,"string","PgSparseVector");this.config.dimensions=n.dimensions}build(o){return new t$(o,this.config)}}class t$ extends U{static[y]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function M$(o,n){const{name:t,config:S}=Mo(o,n);return new f$(t,S)}class f$ extends B{static[y]="PgVectorBuilder";constructor(o,n){super(o,"array","PgVector");this.config.dimensions=n.dimensions}build(o){return new T$(o,this.config)}}class T$ extends U{static[y]="PgVector";dimensions=this.config.dimensions;getSQLType(){return`vector(${this.dimensions})`}mapToDriverValue(o){return JSON.stringify(o)}mapFromDriverValue(o){return o.slice(1,-1).split(",").map((n)=>Number.parseFloat(n))}}function F$(){return{bigint:zk,bigserial:Dk,boolean:wS,char:Lk,cidr:ck,customType:Nk,date:ik,doublePrecision:pk,inet:gk,integer:Rf,interval:ak,json:oA,jsonb:tA,line:FA,macaddr:$A,macaddr8:RA,numeric:WA,point:YA,geometry:QA,real:VA,serial:LA,smallint:cA,smallserial:NA,text:iA,time:qA,timestamp:mn,uuid:$n,varchar:io,bit:uA,halfvec:o$,sparsevec:S$,vector:M$}}function zy(o,n,t,S,f=o){const T=new Qn(o,S,f),M=typeof n==="function"?n(F$()):n,F=Object.fromEntries(Object.entries(M).map(([$,O])=>{const w=O;w.setName($);const z=w.build(T);return T[vT].push(...w.buildForeignKeys(z,T)),[$,z]})),k=Object.fromEntries(Object.entries(M).map(([$,O])=>{const w=O;w.setName($);const z=w.buildExtraConfigColumn(T);return[$,z]})),A=Object.assign(T,F);if(A[j.Symbol.Columns]=F,A[j.Symbol.ExtraConfigColumns]=k,t)A[Qn.Symbol.ExtraConfigBuilder]=t;return A}var vT=Symbol.for("drizzle:PgInlineForeignKeys");class Qn extends j{static[y]="PgTable";static Symbol=Object.assign({},j.Symbol,{InlineForeignKeys:vT});[vT]=[];[j.Symbol.ExtraConfigBuilder]=void 0}var ot=(o,n,t)=>{return zy(o,n,t,void 0)};function k$(...o){if(o[0].columns)return new KS(o[0].columns,o[0].name);return new KS(o)}class KS{static[y]="PgPrimaryKeyBuilder";columns;name;constructor(o,n){this.columns=o,this.name=n}build(o){return new A$(o,this.columns,this.name)}}class A${constructor(o,n,t){this.table=o,this.columns=n,this.name=t}static[y]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[Qn.Symbol.Name]}_${this.columns.map((o)=>o.name).join("_")}_pk`}}function J$(){return{and:_S,between:Mk,eq:rt,exists:fk,gt:dF,gte:uF,ilike:$k,inArray:ok,isNull:tk,isNotNull:Sk,like:kk,lt:aF,lte:sF,ne:gF,not:eF,notBetween:Fk,notExists:Tk,notLike:Ak,notIlike:Jk,notInArray:nk,or:lF,sql:R}}function y$(){return{sql:R,asc:yk,desc:Rk}}function R$(o,n){if(Object.keys(o).length===1&&"default"in o&&!X(o.default,j))o=o.default;const t={},S={},f={};for(let[T,M]of Object.entries(o))if(X(M,j)){const F=$t(M),k=S[F];t[F]=T,f[T]={tsName:T,dbName:M[j.Symbol.Name],schema:M[j.Symbol.Schema],columns:M[j.Symbol.Columns],relations:k?.relations??{},primaryKey:k?.primaryKey??[]};for(let $ of Object.values(M[j.Symbol.Columns]))if($.primary)f[T].primaryKey.push($);const A=M[j.Symbol.ExtraConfigBuilder]?.(M[j.Symbol.ExtraConfigColumns]);if(A){for(let $ of Object.values(A))if(X($,KS))f[T].primaryKey.push(...$.columns)}}else if(X(M,$$)){const F=$t(M.table),k=t[F],A=M.config(n(M.table));let $;for(let[O,w]of Object.entries(A))if(k){const z=f[k];if(z.relations[O]=w,$)z.primaryKey.push(...$)}else{if(!(F in S))S[F]={relations:{},primaryKey:$};S[F].relations[O]=w}}return{tables:f,tableNamesMap:t}}function Gy(o){return function n(t,S){return new nt(o,t,S,S?.fields.reduce((f,T)=>f&&T.notNull,!0)??!1)}}function Hy(o){return function n(t,S){return new XS(o,t,S)}}function O$(o,n,t){if(X(t,nt)&&t.config)return{fields:t.config.fields,references:t.config.references};const S=n[$t(t.referencedTable)];if(!S)throw new Error(`Table "${t.referencedTable[j.Symbol.Name]}" not found in schema`);const f=o[S];if(!f)throw new Error(`Table "${S}" not found in schema`);const T=t.sourceTable,M=n[$t(T)];if(!M)throw new Error(`Table "${T[j.Symbol.Name]}" not found in schema`);const F=[];for(let k of Object.values(f.relations))if(t.relationName&&t!==k&&k.relationName===t.relationName||!t.relationName&&k.referencedTable===t.sourceTable)F.push(k);if(F.length>1)throw t.relationName?new Error(`There are multiple relations with name "${t.relationName}" in table "${S}"`):new Error(`There are multiple relations between "${S}" and "${t.sourceTable[j.Symbol.Name]}". Please specify relation name`);if(F[0]&&X(F[0],nt)&&F[0].config)return{fields:F[0].config.references,references:F[0].config.fields};throw new Error(`There is not enough information to infer relation "${M}.${t.fieldName}"`)}function W$(o){return{one:Gy(o),many:Hy(o)}}function Ef(o,n,t,S,f=(T)=>T){const T={};for(let[M,F]of S.entries())if(F.isJson){const k=n.relations[F.tsKey],A=t[M],$=typeof A==="string"?JSON.parse(A):A;T[F.tsKey]=X(k,nt)?$&&Ef(o,o[F.relationTableTsKey],$,F.selection,f):$.map((O)=>Ef(o,o[F.relationTableTsKey],O,F.selection,f))}else{const k=f(t[M]),A=F.field;let $;if(X(A,Ko))$=A;else if(X(A,b))$=A.decoder;else $=A.sql.decoder;T[F.tsKey]=k===null?null:$.mapFromDriverValue(k)}return T}class qT{constructor(o,n,t){this.sourceTable=o,this.referencedTable=n,this.relationName=t,this.referencedTableName=n[j.Symbol.Name]}static[y]="Relation";referencedTableName;fieldName}class $${constructor(o,n){this.table=o,this.config=n}static[y]="Relations"}class nt extends qT{constructor(o,n,t,S){super(o,n,t?.relationName);this.config=t,this.isNullable=S}static[y]="One";withFieldName(o){const n=new nt(this.sourceTable,this.referencedTable,this.config,this.isNullable);return n.fieldName=o,n}}class XS extends qT{constructor(o,n,t){super(o,n,t?.relationName);this.config=t}static[y]="Many";withFieldName(o){const n=new XS(this.sourceTable,this.referencedTable,this.config);return n.fieldName=o,n}}import K0 from"path";class zf extends ao{constructor(o,n,t,S){super();this.session=n,this.dialect=t,this.config={table:o,withList:S}}static[y]="PgDelete";config;where(o){return this.config.where=o,this}returning(o=this.config.table[j.Symbol.Columns]){return this.config.returning=_n(o),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){const{typings:o,...n}=this.dialect.sqlToQuery(this.getSQL());return n}_prepare(o){return Oo.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,o,!0)})}prepare(o){return this._prepare(o)}execute=(o)=>{return Oo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(o)})};$dynamic(){return this}}class Gf{constructor(o,n,t,S){this.table=o,this.session=n,this.dialect=t,this.withList=S}static[y]="PgInsertBuilder";values(o){if(o=Array.isArray(o)?o:[o],o.length===0)throw new Error("values() must be called with at least one value");const n=o.map((t)=>{const S={},f=this.table[j.Symbol.Columns];for(let T of Object.keys(t)){const M=t[T];S[T]=X(M,b)?M:new An(M,f[T])}return S});return new _$(this.table,n,this.session,this.dialect,this.withList)}}class _$ extends ao{constructor(o,n,t,S,f){super();this.session=t,this.dialect=S,this.config={table:o,values:n,withList:f}}static[y]="PgInsert";config;returning(o=this.config.table[j.Symbol.Columns]){return this.config.returning=_n(o),this}onConflictDoNothing(o={}){if(o.target===void 0)this.config.onConflict=R`do nothing`;else{let n="";n=Array.isArray(o.target)?o.target.map((S)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(S))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(o.target));const 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.');const n=o.where?R` where ${o.where}`:void 0,t=o.targetWhere?R` where ${o.targetWhere}`:void 0,S=o.setWhere?R` where ${o.setWhere}`:void 0,f=this.dialect.buildUpdateSet(this.config.table,$f(this.config.table,o.set));let T="";return T=Array.isArray(o.target)?o.target.map((M)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(M))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(o.target)),this.config.onConflict=R`(${R.raw(T)})${t} do update set ${f}${n}${S}`,this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){const{typings:o,...n}=this.dialect.sqlToQuery(this.getSQL());return n}_prepare(o){return Oo.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,o,!0)})}prepare(o){return this._prepare(o)}execute=(o)=>{return Oo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(o)})};$dynamic(){return this}}function my(o){return(o.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((t)=>t.toLowerCase()).join("_")}function Qy(o){return(o.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((t,S,f)=>{const T=f===0?S.toLowerCase():`${S[0].toUpperCase()}${S.slice(1)}`;return t+T},"")}function Dy(o){return o}class pT{static[y]="CasingCache";cache={};cachedTables={};convert;constructor(o){this.convert=o==="snake_case"?my:o==="camelCase"?Qy:Dy}getColumnCasing(o){if(!o.keyAsName)return o.name;const n=o.table[j.Symbol.Schema]??"public",t=o.table[j.Symbol.OriginalName],S=`${n}.${t}.${o.name}`;if(!this.cache[S])this.cacheTable(o.table);return this.cache[S]}cacheTable(o){const n=o[j.Symbol.Schema]??"public",t=o[j.Symbol.OriginalName],S=`${n}.${t}`;if(!this.cachedTables[S]){for(let f of Object.values(o[j.Symbol.Columns])){const T=`${S}.${f.name}`;this.cache[T]=this.convert(f.name)}this.cachedTables[S]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class YS extends Sn{static[y]="PgViewBase"}class Jt{static[y]="PgDialect";casing;constructor(o){this.casing=new pT(o?.casing)}async migrate(o,n,t){const S=typeof t==="string"?"__drizzle_migrations":t.migrationsTable??"__drizzle_migrations",f=typeof t==="string"?"drizzle":t.migrationsSchema??"drizzle",T=R`
|
|
4
|
+
CREATE TABLE IF NOT EXISTS ${R.identifier(f)}.${R.identifier(S)} (
|
|
5
|
+
id SERIAL PRIMARY KEY,
|
|
6
|
+
hash text NOT NULL,
|
|
7
|
+
created_at bigint
|
|
8
|
+
)
|
|
9
|
+
`;await n.execute(R`CREATE SCHEMA IF NOT EXISTS ${R.identifier(f)}`),await n.execute(T);const F=(await n.all(R`select id, hash, created_at from ${R.identifier(f)}.${R.identifier(S)} order by created_at desc limit 1`))[0];await n.transaction(async(k)=>{for await(let A of o)if(!F||Number(F.created_at)<A.folderMillis){for(let $ of A.sql)await k.execute(R.raw($));await k.execute(R`insert into ${R.identifier(f)}.${R.identifier(S)} ("hash", "created_at") values(${A.hash}, ${A.folderMillis})`)}})}escapeName(o){return`"${o}"`}escapeParam(o){return`\$${o+1}`}escapeString(o){return`'${o.replace(/'/g,"''")}'`}buildWithCTE(o){if(!o?.length)return;const n=[R`with `];for(let[t,S]of o.entries())if(n.push(R`${R.identifier(S._.alias)} as (${S._.sql})`),t<o.length-1)n.push(R`, `);return n.push(R` `),R.join(n)}buildDeleteQuery({table:o,where:n,returning:t,withList:S}){const f=this.buildWithCTE(S),T=t?R` returning ${this.buildSelection(t,{isSingleTable:!0})}`:void 0,M=n?R` where ${n}`:void 0;return R`${f}delete from ${o}${M}${T}`}buildUpdateSet(o,n){const t=o[j.Symbol.Columns],S=Object.keys(t).filter((T)=>n[T]!==void 0||t[T]?.onUpdateFn!==void 0),f=S.length;return R.join(S.flatMap((T,M)=>{const F=t[T],k=n[T]??R.param(F.onUpdateFn(),F),A=R`${R.identifier(this.casing.getColumnCasing(F))} = ${k}`;if(M<f-1)return[A,R.raw(", ")];return[A]}))}buildUpdateQuery({table:o,set:n,where:t,returning:S,withList:f}){const T=this.buildWithCTE(f),M=this.buildUpdateSet(o,n),F=S?R` returning ${this.buildSelection(S,{isSingleTable:!0})}`:void 0,k=t?R` where ${t}`:void 0;return R`${T}update ${o} set ${M}${k}${F}`}buildSelection(o,{isSingleTable:n=!1}={}){const t=o.length,S=o.flatMap(({field:f},T)=>{const M=[];if(X(f,b.Aliased)&&f.isSelectionField)M.push(R.identifier(f.fieldAlias));else if(X(f,b.Aliased)||X(f,b)){const F=X(f,b.Aliased)?f.sql:f;if(n)M.push(new b(F.queryChunks.map((k)=>{if(X(k,U))return R.identifier(this.casing.getColumnCasing(k));return k})));else M.push(F);if(X(f,b.Aliased))M.push(R` as ${R.identifier(f.fieldAlias)}`)}else if(X(f,Ko))if(n)M.push(R.identifier(this.casing.getColumnCasing(f)));else M.push(f);if(T<t-1)M.push(R`, `);return M});return R.join(S)}buildSelectQuery({withList:o,fields:n,fieldsFlat:t,where:S,having:f,table:T,joins:M,orderBy:F,groupBy:k,limit:A,offset:$,lockingClause:O,distinct:w,setOperators:z}){const r=t??_n(n);for(let So of r)if(X(So.field,Ko)&&Wn(So.field.table)!==(X(T,xo)?T._.alias:X(T,YS)?T[mo].name:X(T,b)?void 0:Wn(T))&&!((to)=>M?.some(({alias:Wo})=>Wo===(to[j.Symbol.IsAlias]?Wn(to):to[j.Symbol.BaseName])))(So.field.table)){const to=Wn(So.field.table);throw new Error(`Your "${So.path.join("->")}" field references a column "${to}"."${So.field.name}", but the table "${to}" is not part of the query! Did you forget to join it?`)}const H=!M||M.length===0,D=this.buildWithCTE(o);let I;if(w)I=w===!0?R` distinct`:R` distinct on (${R.join(w.on,R`, `)})`;const v=this.buildSelection(r,{isSingleTable:H}),N=(()=>{if(X(T,j)&&T[j.Symbol.OriginalName]!==T[j.Symbol.Name]){let So=R`${R.identifier(T[j.Symbol.OriginalName])}`;if(T[j.Symbol.Schema])So=R`${R.identifier(T[j.Symbol.Schema])}.${So}`;return R`${So} ${R.identifier(T[j.Symbol.Name])}`}return T})(),P=[];if(M)for(let[So,to]of M.entries()){if(So===0)P.push(R` `);const Wo=to.table,Mn=to.lateral?R` lateral`:void 0;if(X(Wo,Qn)){const E=Wo[Qn.Symbol.Name],x=Wo[Qn.Symbol.Schema],To=Wo[Qn.Symbol.OriginalName],Jo=E===To?void 0:to.alias;P.push(R`${R.raw(to.joinType)} join${Mn} ${x?R`${R.identifier(x)}.`:void 0}${R.identifier(To)}${Jo&&R` ${R.identifier(Jo)}`} on ${to.on}`)}else if(X(Wo,Sn)){const E=Wo[mo].name,x=Wo[mo].schema,To=Wo[mo].originalName,Jo=E===To?void 0:to.alias;P.push(R`${R.raw(to.joinType)} join${Mn} ${x?R`${R.identifier(x)}.`:void 0}${R.identifier(To)}${Jo&&R` ${R.identifier(Jo)}`} on ${to.on}`)}else P.push(R`${R.raw(to.joinType)} join${Mn} ${Wo} on ${to.on}`);if(So<M.length-1)P.push(R` `)}const Y=R.join(P),K=S?R` where ${S}`:void 0,Q=f?R` having ${f}`:void 0;let i;if(F&&F.length>0)i=R` order by ${R.join(F,R`, `)}`;let g;if(k&&k.length>0)g=R` group by ${R.join(k,R`, `)}`;const _=typeof A==="object"||typeof A==="number"&&A>=0?R` limit ${A}`:void 0,h=$?R` offset ${$}`:void 0,C=R.empty();if(O){const So=R` for ${R.raw(O.strength)}`;if(O.config.of)So.append(R` of ${R.join(Array.isArray(O.config.of)?O.config.of:[O.config.of],R`, `)}`);if(O.config.noWait)So.append(R` no wait`);else if(O.config.skipLocked)So.append(R` skip locked`);C.append(So)}const a=R`${D}select${I} ${v} from ${N}${Y}${K}${g}${Q}${i}${_}${h}${C}`;if(z.length>0)return this.buildSetOperations(a,z);return a}buildSetOperations(o,n){const[t,...S]=n;if(!t)throw new Error("Cannot pass undefined values to any set operator");if(S.length===0)return this.buildSetOperationQuery({leftSelect:o,setOperator:t});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:o,setOperator:t}),S)}buildSetOperationQuery({leftSelect:o,setOperator:{type:n,isAll:t,rightSelect:S,limit:f,orderBy:T,offset:M}}){const F=R`(${o.getSQL()}) `,k=R`(${S.getSQL()})`;let A;if(T&&T.length>0){const z=[];for(let r of T)if(X(r,U))z.push(R.identifier(r.name));else if(X(r,b)){for(let H=0;H<r.queryChunks.length;H++){const D=r.queryChunks[H];if(X(D,U))r.queryChunks[H]=R.identifier(D.name)}z.push(R`${r}`)}else z.push(R`${r}`);A=R` order by ${R.join(z,R`, `)} `}const $=typeof f==="object"||typeof f==="number"&&f>=0?R` limit ${f}`:void 0,O=R.raw(`${n} ${t?"all ":""}`),w=M?R` offset ${M}`:void 0;return R`${F}${O}${k}${A}${$}${w}`}buildInsertQuery({table:o,values:n,onConflict:t,returning:S,withList:f}){const T=[],M=o[j.Symbol.Columns],F=Object.entries(M).filter(([z,r])=>!r.shouldDisableInsert()),k=F.map(([,z])=>R.identifier(this.casing.getColumnCasing(z)));for(let[z,r]of n.entries()){const H=[];for(let[D,I]of F){const v=r[D];if(v===void 0||X(v,An)&&v.value===void 0)if(I.defaultFn!==void 0){const N=I.defaultFn(),P=X(N,b)?N:R.param(N,I);H.push(P)}else if(!I.default&&I.onUpdateFn!==void 0){const N=I.onUpdateFn(),P=X(N,b)?N:R.param(N,I);H.push(P)}else H.push(R`default`);else H.push(v)}if(T.push(H),z<n.length-1)T.push(R`, `)}const A=this.buildWithCTE(f),$=R.join(T),O=S?R` returning ${this.buildSelection(S,{isSingleTable:!0})}`:void 0,w=t?R` on conflict ${t}`:void 0;return R`${A}insert into ${o} ${k} values ${$}${w}${O}`}buildRefreshMaterializedViewQuery({view:o,concurrently:n,withNoData:t}){const S=n?R` concurrently`:void 0,f=t?R` with no data`:void 0;return R`refresh materialized view${S} ${o}${f}`}prepareTyping(o){if(X(o,Wf)||X(o,Of))return"json";else if(X(o,_f))return"decimal";else if(X(o,wf))return"time";else if(X(o,Kf)||X(o,Xf))return"timestamp";else if(X(o,Jf)||X(o,yf))return"date";else if(X(o,Yf))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:S,tableConfig:f,queryConfig:T,tableAlias:M,nestedQueryRelation:F,joinOn:k}){let A=[],$,O,w=[],z;const r=[];if(T===!0)A=Object.entries(f.columns).map(([I,v])=>({dbKey:v.name,tsKey:I,field:cn(v,M),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{const D=Object.fromEntries(Object.entries(f.columns).map(([K,Q])=>[K,cn(Q,M)]));if(T.where){const K=typeof T.where==="function"?T.where(D,J$()):T.where;z=K&&WS(K,M)}const I=[];let v=[];if(T.columns){let K=!1;for(let[Q,i]of Object.entries(T.columns)){if(i===void 0)continue;if(Q in f.columns){if(!K&&i===!0)K=!0;v.push(Q)}}if(v.length>0)v=K?v.filter((Q)=>T.columns?.[Q]===!0):Object.keys(f.columns).filter((Q)=>!v.includes(Q))}else v=Object.keys(f.columns);for(let K of v){const Q=f.columns[K];I.push({tsKey:K,value:Q})}let N=[];if(T.with)N=Object.entries(T.with).filter((K)=>!!K[1]).map(([K,Q])=>({tsKey:K,queryConfig:Q,relation:f.relations[K]}));let P;if(T.extras){P=typeof T.extras==="function"?T.extras(D,{sql:R}):T.extras;for(let[K,Q]of Object.entries(P))I.push({tsKey:K,value:cT(Q,M)})}for(let{tsKey:K,value:Q}of I)A.push({dbKey:X(Q,b.Aliased)?Q.fieldAlias:f.columns[K].name,tsKey:K,field:X(Q,Ko)?cn(Q,M):Q,relationTableTsKey:void 0,isJson:!1,selection:[]});let Y=typeof T.orderBy==="function"?T.orderBy(D,y$()):T.orderBy??[];if(!Array.isArray(Y))Y=[Y];w=Y.map((K)=>{if(X(K,Ko))return cn(K,M);return WS(K,M)}),$=T.limit,O=T.offset;for(let{tsKey:K,queryConfig:Q,relation:i}of N){const g=O$(n,t,i),_=$t(i.referencedTable),h=t[_],C=`${M}_${K}`,a=_S(...g.fields.map((Wo,Mn)=>rt(cn(g.references[Mn],C),cn(Wo,M)))),So=this.buildRelationalQueryWithoutPK({fullSchema:o,schema:n,tableNamesMap:t,table:o[h],tableConfig:n[h],queryConfig:X(i,nt)?Q===!0?{limit:1}:{...Q,limit:1}:Q,tableAlias:C,joinOn:a,nestedQueryRelation:i}),to=R`${R.identifier(C)}.${R.identifier("data")}`.as(K);r.push({on:R`true`,table:new xo(So.sql,{},C),alias:C,joinType:"left",lateral:!0}),A.push({dbKey:K,tsKey:K,field:to,relationTableTsKey:h,isJson:!0,selection:So.selection})}}if(A.length===0)throw new Af({message:`No fields selected for table "${f.tsName}" ("${M}")`});let H;if(z=_S(k,z),F){let D=R`json_build_array(${R.join(A.map(({field:N,tsKey:P,isJson:Y})=>Y?R`${R.identifier(`${M}_${P}`)}.${R.identifier("data")}`:X(N,b.Aliased)?N.sql:N),R`, `)})`;if(X(F,XS))D=R`coalesce(json_agg(${D}${w.length>0?R` order by ${R.join(w,R`, `)}`:void 0}), '[]'::json)`;const I=[{dbKey:"data",tsKey:"data",field:D.as("data"),isJson:!0,relationTableTsKey:f.tsName,selection:A}];if($!==void 0||O!==void 0||w.length>0)H=this.buildSelectQuery({table:kf(S,M),fields:{},fieldsFlat:[{path:[],field:R.raw("*")}],where:z,limit:$,offset:O,orderBy:w,setOperators:[]}),z=void 0,$=void 0,O=void 0,w=[];else H=kf(S,M);H=this.buildSelectQuery({table:X(H,Qn)?H:new xo(H,{},M),fields:{},fieldsFlat:I.map(({field:N})=>({path:[],field:X(N,Ko)?cn(N,M):N})),joins:r,where:z,limit:$,offset:O,orderBy:w,setOperators:[]})}else H=this.buildSelectQuery({table:kf(S,M),fields:{},fieldsFlat:A.map(({field:D})=>({path:[],field:X(D,Ko)?cn(D,M):D})),joins:r,where:z,limit:$,offset:O,orderBy:w,setOperators:[]});return{tableTsKey:f.tsName,sql:H,selection:A}}}class Tn{static[y]="SelectionProxyHandler";config;constructor(o){this.config={...o}}get(o,n){if(n==="_")return{...o._,selectedFields:new Proxy(o._.selectedFields,this)};if(n===mo)return{...o[mo],selectedFields:new Proxy(o[mo].selectedFields,this)};if(typeof n==="symbol")return o[n];const S=(X(o,xo)?o._.selectedFields:X(o,Sn)?o[mo].selectedFields:o)[n];if(X(S,b.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!S.isSelectionField)return S.sql;const f=S.clone();return f.isSelectionField=!0,f}if(X(S,b)){if(this.config.sqlBehavior==="sql")return S;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(S,Ko)){if(this.config.alias)return new Proxy(S,new Vt(new Proxy(S.table,new OS(this.config.alias,this.config.replaceOriginalName??!1))));return S}if(typeof S!=="object"||S===null)return S;return new Proxy(S,new Tn(this.config))}}class ZT{static[y]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}function Ct(o,n){return(t,S,...f)=>{const T=[S,...f].map((M)=>({type:o,isAll:n,rightSelect:M}));for(let M of T)if(!hT(t.getSelectedFields(),M.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(T)}}class so{static[y]="PgSelectBuilder";fields;session;dialect;withList=[];distinct;constructor(o){if(this.fields=o.fields,this.session=o.session,this.dialect=o.dialect,o.withList)this.withList=o.withList;this.distinct=o.distinct}from(o){const n=!!this.fields;let t;if(this.fields)t=this.fields;else if(X(o,xo))t=Object.fromEntries(Object.keys(o._.selectedFields).map((S)=>[S,o[S]]));else if(X(o,YS))t=o[mo].selectedFields;else if(X(o,b))t={};else t=wk(o);return new PT({table:o,fields:t,isPartialSelect:n,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct})}}class w$ extends ZT{static[y]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;constructor({table:o,fields:n,isPartialSelect:t,session:S,dialect:f,withList:T,distinct:M}){super();this.config={withList:T,table:o,fields:{...n},distinct:M,setOperators:[]},this.isPartialSelect=t,this.session=S,this.dialect=f,this._={selectedFields:n},this.tableName=xT(o),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}createJoin(o){return(n,t)=>{const S=this.tableName,f=xT(n);if(typeof f==="string"&&this.config.joins?.some((T)=>T.alias===f))throw new Error(`Alias "${f}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof S==="string")this.config.fields={[S]:this.config.fields};if(typeof f==="string"&&!X(n,b)){const T=X(n,xo)?n._.selectedFields:X(n,Sn)?n[mo].selectedFields:n[j.Symbol.Columns];this.config.fields[f]=T}}if(typeof t==="function")t=t(new Proxy(this.config.fields,new Tn({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:t,table:n,joinType:o,alias:f}),typeof f==="string")switch(o){case"left":{this.joinsNotNullableMap[f]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([T])=>[T,!1])),this.joinsNotNullableMap[f]=!0;break}case"inner":{this.joinsNotNullableMap[f]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([T])=>[T,!1])),this.joinsNotNullableMap[f]=!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)=>{const S=typeof t==="function"?t(Uy()):t;if(!hT(this.getSelectedFields(),S.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:S}),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 Tn({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=o,this}having(o){if(typeof o==="function")o=o(new Proxy(this.config.fields,new Tn({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=o,this}groupBy(...o){if(typeof o[0]==="function"){const n=o[0](new Proxy(this.config.fields,new Tn({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"){const n=o[0](new Proxy(this.config.fields,new Tn({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{const 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(){const{typings:o,...n}=this.dialect.sqlToQuery(this.getSQL());return n}as(o){return new Proxy(new xo(this.getSQL(),this.config.fields,o),new Tn({alias:o,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new Tn({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}}class PT extends w${static[y]="PgSelect";_prepare(o){const{session:n,config:t,dialect:S,joinsNotNullableMap:f}=this;if(!n)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");return Oo.startActiveSpan("drizzle.prepareQuery",()=>{const T=_n(t.fields),M=n.prepareQuery(S.sqlToQuery(this.getSQL()),T,o,!0);return M.joinsNotNullableMap=f,M})}prepare(o){return this._prepare(o)}execute=(o)=>{return Oo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(o)})}}_k(PT,[ao]);var Uy=()=>({union:Vy,unionAll:ry,intersect:Cy,intersectAll:Ly,except:Iy,exceptAll:jy}),Vy=Ct("union",!1),ry=Ct("union",!0),Cy=Ct("intersect",!1),Ly=Ct("intersect",!0),Iy=Ct("except",!1),jy=Ct("except",!0);class gT{static[y]="PgQueryBuilder";dialect;dialectConfig;constructor(o){this.dialect=X(o,Jt)?o:void 0,this.dialectConfig=X(o,Jt)?void 0:o}$with(o){const n=this;return{as(t){if(typeof t==="function")t=t(n);return new Proxy(new RS(t.getSQL(),t.getSelectedFields(),o,!0),new Tn({alias:o,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}}with(...o){const n=this;function t(T){return new so({fields:T??void 0,session:void 0,dialect:n.getDialect(),withList:o})}function S(T){return new so({fields:T??void 0,session:void 0,dialect:n.getDialect(),distinct:!0})}function f(T,M){return new so({fields:M??void 0,session:void 0,dialect:n.getDialect(),distinct:{on:T}})}return{select:t,selectDistinct:S,selectDistinctOn:f}}select(o){return new so({fields:o??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(o){return new so({fields:o??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(o,n){return new so({fields:n??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:o}})}getDialect(){if(!this.dialect)this.dialect=new Jt(this.dialectConfig);return this.dialect}}class lT extends ao{constructor(o,n,t){super();this.session=n,this.dialect=t,this.config={view:o}}static[y]="PgRefreshMaterializedView";config;concurrently(){if(this.config.withNoData!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.concurrently=!0,this}withNoData(){if(this.config.concurrently!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.withNoData=!0,this}getSQL(){return this.dialect.buildRefreshMaterializedViewQuery(this.config)}toSQL(){const{typings:o,...n}=this.dialect.sqlToQuery(this.getSQL());return n}_prepare(o){return Oo.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),void 0,o,!0)})}prepare(o){return this._prepare(o)}execute=(o)=>{return Oo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(o)})}}class Hf{constructor(o,n,t,S){this.table=o,this.session=n,this.dialect=t,this.withList=S}static[y]="PgUpdateBuilder";set(o){return new K$(this.table,$f(this.table,o),this.session,this.dialect,this.withList)}}class K$ extends ao{constructor(o,n,t,S,f){super();this.session=t,this.dialect=S,this.config={set:n,table:o,withList:f}}static[y]="PgUpdate";config;where(o){return this.config.where=o,this}returning(o=this.config.table[j.Symbol.Columns]){return this.config.returning=_n(o),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){const{typings:o,...n}=this.dialect.sqlToQuery(this.getSQL());return n}_prepare(o){return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,o,!0)}prepare(o){return this._prepare(o)}execute=(o)=>{return this._prepare().execute(o)};$dynamic(){return this}}class ES extends b{constructor(o){super(ES.buildEmbeddedCount(o.source,o.filters).queryChunks);this.params=o,this.mapWith(Number),this.session=o.session,this.sql=ES.buildCount(o.source,o.filters)}sql;static[y]="PgCountBuilder";[Symbol.toStringTag]="PgCountBuilder";session;static buildEmbeddedCount(o,n){return R`(select count(*) from ${o}${R.raw(" where ").if(n)}${n})`}static buildCount(o,n){return R`select count(*) as count from ${o}${R.raw(" where ").if(n)}${n};`}then(o,n){return Promise.resolve(this.session.count(this.sql)).then(o,n)}catch(o){return this.then(void 0,o)}finally(o){return this.then((n)=>{return o?.(),n},(n)=>{throw o?.(),n})}}class dT{constructor(o,n,t,S,f,T,M){this.fullSchema=o,this.schema=n,this.tableNamesMap=t,this.table=S,this.tableConfig=f,this.dialect=T,this.session=M}static[y]="PgRelationalQueryBuilder";findMany(o){return new eT(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,o?o:{},"many")}findFirst(o){return new eT(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,o?{...o,limit:1}:{limit:1},"first")}}class eT extends ao{constructor(o,n,t,S,f,T,M,F,k){super();this.fullSchema=o,this.schema=n,this.tableNamesMap=t,this.table=S,this.tableConfig=f,this.dialect=T,this.session=M,this.config=F,this.mode=k}static[y]="PgRelationalQuery";_prepare(o){return Oo.startActiveSpan("drizzle.prepareQuery",()=>{const{query:n,builtQuery:t}=this._toSQL();return this.session.prepareQuery(t,void 0,o,!0,(S,f)=>{const T=S.map((M)=>Ef(this.schema,this.tableConfig,M,n.selection,f));if(this.mode==="first")return T[0];return T})})}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(){const o=this._getQuery(),n=this.dialect.sqlToQuery(o.sql);return{query:o,builtQuery:n}}toSQL(){return this._toSQL().builtQuery}execute(){return Oo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute()})}}class uT extends ao{constructor(o,n,t,S){super();this.execute=o,this.sql=n,this.query=t,this.mapBatchResult=S}static[y]="PgRaw";getSQL(){return this.sql}getQuery(){return this.query}mapResult(o,n){return n?this.mapBatchResult(o):o}_prepare(){return this}isResponseInArrayMode(){return!1}}class zS{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[S,f]of Object.entries(this._.schema))this.query[S]=new dT(t.fullSchema,this._.schema,this._.tableNamesMap,t.fullSchema[S],f,o,n)}static[y]="PgDatabase";query;$with(o){const n=this;return{as(t){if(typeof t==="function")t=t(new gT(n.dialect));return new Proxy(new RS(t.getSQL(),t.getSelectedFields(),o,!0),new Tn({alias:o,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}}$count(o,n){return new ES({source:o,filters:n,session:this.session})}with(...o){const n=this;function t(k){return new so({fields:k??void 0,session:n.session,dialect:n.dialect,withList:o})}function S(k){return new so({fields:k??void 0,session:n.session,dialect:n.dialect,withList:o,distinct:!0})}function f(k,A){return new so({fields:A??void 0,session:n.session,dialect:n.dialect,withList:o,distinct:{on:k}})}function T(k){return new Hf(k,n.session,n.dialect,o)}function M(k){return new Gf(k,n.session,n.dialect,o)}function F(k){return new zf(k,n.session,n.dialect,o)}return{select:t,selectDistinct:S,selectDistinctOn:f,update:T,insert:M,delete:F}}select(o){return new so({fields:o??void 0,session:this.session,dialect:this.dialect})}selectDistinct(o){return new so({fields:o??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(o,n){return new so({fields:n??void 0,session:this.session,dialect:this.dialect,distinct:{on:o}})}update(o){return new Hf(o,this.session,this.dialect)}insert(o){return new Gf(o,this.session,this.dialect)}delete(o){return new zf(o,this.session,this.dialect)}refreshMaterializedView(o){return new lT(o,this.session,this.dialect)}execute(o){const n=typeof o==="string"?R.raw(o):o.getSQL(),t=this.dialect.sqlToQuery(n),S=this.session.prepareQuery(t,void 0,void 0,!1);return new uT(()=>S.execute(),n,t,(f)=>S.mapResult(f,!0))}transaction(o,n){return this.session.transaction(o,n)}}function aT(o){return new X$(!0,o)}class X${constructor(o,n){this.unique=o,this.name=n}static[y]="PgIndexBuilderOn";on(...o){return new mf(o.map((n)=>{if(X(n,b))return n;n=n;const t=new yS(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 mf(o.map((n)=>{if(X(n,b))return n;n=n;const t=new yS(n.name,!!n.keyAsName,n.columnType,n.indexConfig);return n.indexConfig=n.defaultConfig,t}),this.unique,!0,this.name)}using(o,...n){return new mf(n.map((t)=>{if(X(t,b))return t;t=t;const S=new yS(t.name,!!t.keyAsName,t.columnType,t.indexConfig);return t.indexConfig=JSON.parse(JSON.stringify(t.defaultConfig)),S}),this.unique,!0,this.name,o)}}class mf{static[y]="PgIndexBuilder";config;constructor(o,n,t,S,f="btree"){this.config={name:S,columns:o,unique:n,only:t,method:f}}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 Y$(this.config,o)}}class Y${static[y]="PgIndex";config;constructor(o,n){this.config={...o,table:n}}}class sT{constructor(o){this.query=o}getQuery(){return this.query}mapResult(o,n){return o}static[y]="PgPreparedQuery";joinsNotNullableMap}class oM{constructor(o){this.dialect=o}static[y]="PgSession";execute(o){return Oo.startActiveSpan("drizzle.operation",()=>{return Oo.startActiveSpan("drizzle.prepareQuery",()=>{return this.prepareQuery(this.dialect.sqlToQuery(o),void 0,void 0,!1)}).execute()})}all(o){return this.prepareQuery(this.dialect.sqlToQuery(o),void 0,void 0,!1).all()}async count(o){const n=await this.execute(o);return Number(n[0].count)}}class nM extends zS{constructor(o,n,t,S=0){super(o,n,t);this.schema=t,this.nestedIndex=S}static[y]="PgTransaction";rollback(){throw new BT}getTransactionConfigSQL(o){const 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 E$ extends sT{constructor(o,n,t,S,f,T,M){super({sql:n,params:t});this.client=o,this.queryString=n,this.params=t,this.logger=S,this.fields=f,this._isResponseInArrayMode=T,this.customResultMapper=M}static[y]="PostgresJsPreparedQuery";async execute(o={}){return Oo.startActiveSpan("drizzle.execute",async(n)=>{const t=jT(this.params,o);n?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(t)}),this.logger.logQuery(this.queryString,t);const{fields:S,queryString:f,client:T,joinsNotNullableMap:M,customResultMapper:F}=this;if(!S&&!F)return Oo.startActiveSpan("drizzle.driver.execute",()=>{return T.unsafe(f,t)});const k=await Oo.startActiveSpan("drizzle.driver.execute",()=>{return n?.setAttributes({"drizzle.query.text":f,"drizzle.query.params":JSON.stringify(t)}),T.unsafe(f,t).values()});return Oo.startActiveSpan("drizzle.mapResponse",()=>{return F?F(k):k.map((A)=>Wk(S,A,M))})})}all(o={}){return Oo.startActiveSpan("drizzle.execute",async(n)=>{const t=jT(this.params,o);return n?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(t)}),this.logger.logQuery(this.queryString,t),Oo.startActiveSpan("drizzle.driver.execute",()=>{return n?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(t)}),this.client.unsafe(this.queryString,t)})})}isResponseInArrayMode(){return this._isResponseInArrayMode}}class GS extends oM{constructor(o,n,t,S={}){super(n);this.client=o,this.schema=t,this.options=S,this.logger=S.logger??new NT}static[y]="PostgresJsSession";logger;prepareQuery(o,n,t,S,f){return new E$(this.client,o.sql,o.params,this.logger,n,S,f)}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)=>{const S=new GS(t,this.dialect,this.schema,this.options),f=new tM(this.dialect,S,this.schema);if(n)await f.setTransaction(n);return o(f)})}}class tM extends nM{constructor(o,n,t,S=0){super(o,n,t,S);this.session=n}static[y]="PostgresJsTransaction";transaction(o){return this.session.client.savepoint((n)=>{const t=new GS(n,this.dialect,this.schema,this.session.options),S=new tM(this.dialect,t,this.schema);return o(S)})}}function G$(o,n={}){const t=(k)=>k;for(let k of["1184","1082","1083","1114"])o.options.parsers[k]=t,o.options.serializers[k]=t;o.options.serializers["114"]=t,o.options.serializers["3802"]=t;const S=new Jt({casing:n.casing});let f;if(n.logger===!0)f=new bT;else if(n.logger!==!1)f=n.logger;let T;if(n.schema){const k=R$(n.schema,W$);T={fullSchema:n.schema,schema:k.tables,tableNamesMap:k.tableNamesMap}}const M=new GS(o,S,T,{logger:f}),F=new z$(S,M,T);return F.$client=o,F}class z$ extends zS{static[y]="PostgresJsDatabase"}import fR from"os";import TR from"fs";function cy(o){if(Qf.has(o))return Qf.get(o);const n=Error.stackTraceLimit;return Error.stackTraceLimit=4,Qf.set(o,new Error),Error.stackTraceLimit=n,Qf.get(o)}var Qf=new Map,SM=new Map,fM=Symbol("OriginError"),Lt={};class wn extends Promise{constructor(o,n,t,S,f={}){let T,M;super((F,k)=>{T=F,M=k});this.tagged=Array.isArray(o.raw),this.strings=o,this.args=n,this.handler=t,this.canceller=S,this.options=f,this.state=null,this.statement=null,this.resolve=(F)=>(this.active=!1,T(F)),this.reject=(F)=>(this.active=!1,M(F)),this.active=!1,this.cancelled=null,this.executed=!1,this.signature="",this[fM]=this.handler.debug?new Error:this.tagged&&cy(this.strings)}get origin(){return(this.handler.debug?this[fM].stack:this.tagged&&SM.has(this.strings)?SM.get(this.strings):SM.set(this.strings,this[fM].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();const S=new Promise((f,T)=>{this.cursorFn=(M)=>{return f({value:M,done:!1}),new Promise((F)=>t=F)},this.resolve=()=>(this.active=!1,f({done:!0})),this.reject=(M)=>(this.active=!1,T(M))});return this.execute(),S},return(){return t&&t(Lt),{done:!0}}})}}describe(){return this.options.simple=!1,this.onlyDescribe=this.options.prepare=!0,this}stream(){throw new Error(".stream has been renamed to .forEach")}forEach(o){return this.forEachFn=o,this.handle(),this}raw(){return this.isRaw=!0,this}values(){return this.isRaw="values",this}async handle(){!this.executed&&(this.executed=!0)&&await 1&&this.handler(this)}execute(){return this.handle(),this}then(){return this.handle(),super.then.apply(this,arguments)}catch(){return this.handle(),super.catch.apply(this,arguments)}finally(){return this.handle(),super.finally.apply(this,arguments)}}function H$(o,n,t){const{host:S,port:f}=t||n,T=Object.assign(new Error("write "+o+" "+(n.path||S+":"+f)),{code:o,errno:o,address:n.path||S},n.path?{}:{port:f});return Error.captureStackTrace(T,H$),T}function m$(o){const n=new It(o);return Error.captureStackTrace(n,m$),n}function Q$(o,n){const t=Object.assign(new Error(o+": "+n),{code:o});return Error.captureStackTrace(t,Q$),t}function D$(o){const n=Object.assign(new Error(o+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:o});return Error.captureStackTrace(n,D$),n}class It extends Error{constructor(o){super(o.message);this.name=this.constructor.name,Object.assign(this,o)}}var Co={connection:H$,postgres:m$,generic:Q$,notSupported:D$};function Cf(o,n,t,S){let f=o instanceof Bn?o.value:o;if(f===void 0){if(o instanceof Bn?o.value=S.transform.undefined:f=o=S.transform.undefined,f===void 0)throw Co.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return"$"+t.push(o instanceof Bn?(n.push(o.value),o.array?o.array[o.type||Uf(o.value)]||o.type||C$(o.value):o.type):(n.push(o),Uf(o)))}function kM(o,n,t,S,f,T){for(let M=1;M<o.strings.length;M++)n+=AM(n,t,S,f,T)+o.strings[M],t=o.args[M];return n}function AM(o,n,t,S,f){return n instanceof rf?n.build(o,t,S,f):n instanceof wn?FM(n,t,S,f):n instanceof DS?n.value:n&&n[0]instanceof wn?n.reduce((T,M)=>T+" "+FM(M,t,S,f),""):Cf(n,t,S,f)}function FM(o,n,t,S){return o.fragment=!0,kM(o,o.strings[0],o.args[0],n,t,S)}function r$(o,n,t,S,f){return o.map((T)=>"("+S.map((M)=>AM("values",T[M],n,t,f)).join(",")+")").join(",")}function U$(o,n,t,S,f){const T=Array.isArray(o[0]),M=n.length?n.flat():Object.keys(T?o[0]:o);return r$(T?o:[o],t,S,M,f)}function Df(o,n,t,S,f){if(typeof o==="string"&&(o=[o].concat(n)),Array.isArray(o))return $M(o,f);let T;return(n.length?n.flat():Object.keys(o)).map((F)=>{return T=o[F],(T instanceof wn?FM(T,t,S,f):T instanceof DS?T.value:Cf(T,t,S,f))+" as "+Lf(f.transform.column.to?f.transform.column.to(F):F)}).join(",")}function TM(){throw Co.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}function C$(o){if(Array.isArray(o))return C$(o[0]);return typeof o==="string"?1009:0}function I$(o){return Object.keys(o).reduce((n,t)=>{if(o[t].from&&[].concat(o[t].from).forEach((S)=>n.parsers[S]=o[t].parse),o[t].serialize)n.serializers[o[t].to]=o[t].serialize,o[t].from&&[].concat(o[t].from).forEach((S)=>n.serializers[S]=o[t].serialize);return n},{parsers:{},serializers:{}})}function $M(o,{transform:{column:n}}){return o.map((t)=>Lf(n.to?n.to(t):t)).join(",")}function vy(o){return o.replace(xy,"\\\\").replace(iy,'\\"')}function B$(o,n,t,S){const f=[],T=S===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==='"')f.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,f.push(B$(o,n,t,S));else if(o.char==="}"){o.quoted=!1,o.last<o.i&&f.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===T&&o.p!=="}"&&o.p!=='"')f.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&&f.push(t?t(n.slice(o.last,o.i+1)):n.slice(o.last,o.i+1)),f}function JM(o){return function n(t,S){return typeof t==="object"&&t!==null&&(S.type===114||S.type===3802)?Array.isArray(t)?t.map((f)=>n(f,S)):Object.entries(t).reduce((f,[T,M])=>Object.assign(f,{[o(T)]:n(M,S)}),{}):t}}var By={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 Vf{then(){TM()}catch(){TM()}finally(){TM()}}class DS extends Vf{constructor(o){super();this.value=Lf(o)}}class Bn extends Vf{constructor(o,n,t){super();this.value=o,this.type=n,this.array=t}}class rf extends Vf{constructor(o,n){super();this.first=o,this.rest=n}build(o,n,t,S){const f=by.map(([T,M])=>({fn:M,i:o.search(T)})).sort((T,M)=>T.i-M.i).pop();return f.i===-1?$M(this.first,S):f.fn(this.first,this.rest,n,t,S)}}var V$=I$(By),by=Object.entries({values:U$,in:(...o)=>{const n=U$(...o);return n==="()"?"(null)":n},select:Df,as:Df,returning:Df,"\\(":Df,update(o,n,t,S,f){return(n.length?n.flat():Object.keys(o)).map((T)=>Lf(f.transform.column.to?f.transform.column.to(T):T)+"="+AM("values",o[T],t,S,f))},insert(o,n,t,S,f){const T=n.length?n.flat():Object.keys(Array.isArray(o)?o[0]:o);return"("+$M(T,f)+")values"+r$(Array.isArray(o)?o:[o],t,S,T,f)}}).map(([o,n])=>[new RegExp("((?:^|[\\s(])"+o+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),n]),Ny=V$.serializers,hy=V$.parsers;var L$=function(o){const n=I$(o||{});return{serializers:Object.assign({},Ny,n.serializers),parsers:Object.assign({},hy,n.parsers)}},Lf=function o(n){return'"'+n.replace(/"/g,'""').replace(/\./g,'"."')+'"'},Uf=function o(n){return n instanceof Bn?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},xy=/\\/g,iy=/"/g,j$=function o(n,t,S,f){if(Array.isArray(n)===!1)return n;if(!n.length)return"{}";const T=n[0],M=f===1020?";":",";if(Array.isArray(T)&&!T.type)return"{"+n.map((F)=>o(F,t,S,f)).join(M)+"}";return"{"+n.map((F)=>{if(F===void 0){if(F=S.transform.undefined,F===void 0)throw Co.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return F===null?"null":'"'+vy(t?t(F.type?F.value:F):""+F)+'"'}).join(M)+"}"},MM={i:0,char:null,str:"",quoted:!1,last:0},c$=function o(n,t,S){return MM.i=MM.last=0,B$(MM,n,t,S)},yt=(o)=>{let n=o[0];for(let t=1;t<o.length;t++)n+=o[t]==="_"?o[++t].toUpperCase():o[t];return n},Rt=(o)=>{let n=o[0].toUpperCase();for(let t=1;t<o.length;t++)n+=o[t]==="_"?o[++t].toUpperCase():o[t];return n},Ot=(o)=>o.replace(/_/g,"-"),HS=(o)=>o.replace(/([A-Z])/g,"_$1").toLowerCase(),mS=(o)=>(o.slice(0,1)+o.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),QS=(o)=>o.replace(/-/g,"_");yt.column={from:yt};yt.value={from:JM(yt)};HS.column={to:HS};var yM={...yt};yM.column.to=HS;Rt.column={from:Rt};Rt.value={from:JM(Rt)};mS.column={to:mS};var RM={...Rt};RM.column.to=mS;Ot.column={from:Ot};Ot.value={from:JM(Ot)};QS.column={to:QS};var OM={...Ot};OM.column.to=QS;import b$ from"net";import Py from"tls";import US from"crypto";import WM from"stream";import{performance as N$}from"perf_hooks";class Wt 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}}function qy(o=[]){let n=o.slice(),t=0;return{get length(){return n.length-t},remove:(S)=>{const f=n.indexOf(S);return f===-1?null:(n.splice(f,1),S)},push:(S)=>(n.push(S),S),shift:()=>{const S=n[t++];if(t===n.length)t=0,n=[];else n[t-1]=void 0;return S}}}var Jn=qy;function If(o){if(go.length-yo.i<o){const n=go,t=n.length;go=Buffer.allocUnsafe(t+(t>>1)+o),n.copy(go)}}function Zy(){return yo.i=0,yo}var go=Buffer.allocUnsafe(256),py="BCcDdEFfHPpQSX".split("").reduce((o,n)=>{const t=n.charCodeAt(0);return o[n]=()=>{return go[0]=t,yo.i=5,yo},o},{}),yo=Object.assign(Zy,py,{N:String.fromCharCode(0),i:0,inc(o){return yo.i+=o,yo},str(o){const n=Buffer.byteLength(o);return If(n),yo.i+=go.write(o,yo.i,n,"utf8"),yo},i16(o){return If(2),go.writeUInt16BE(o,yo.i),yo.i+=2,yo},i32(o,n){if(n||n===0)return go.writeUInt32BE(o,n),yo;return If(4),go.writeUInt32BE(o,yo.i),yo.i+=4,yo},z(o){return If(o),go.fill(0,yo.i,yo.i+o),yo.i+=o,yo},raw(o){return go=Buffer.concat([go.subarray(0,yo.i),o]),yo.i=go.length,yo},end(o=1){go.writeUInt32BE(yo.i-o,o);const n=go.subarray(0,yo.i);return yo.i=0,go=Buffer.allocUnsafe(256),n}}),p=yo;function i$(o,n={},{onopen:t=jt,onend:S=jt,onclose:f=jt}={}){const{ssl:T,max:M,user:F,host:k,port:A,database:$,parsers:O,transform:w,onnotice:z,onnotify:r,onparameter:H,max_pipeline:D,keep_alive:I,backoff:v,target_session_attrs:N}=o,P=Jn(),Y=gy++,K={pid:null,secret:null},Q=wM(Pf,o.idle_timeout),i=wM(Pf,o.max_lifetime),g=wM(RJ,o.connect_timeout);let _=null,h,C=new Wt,a=Buffer.alloc(0),So=o.fetch_types,to={},Wo={},Mn=Math.random().toString(36).slice(2),E=1,x=0,To=0,Jo=0,Io=0,fo=0,_o=0,Vo=0,Ho=null,Xo=null,vo=!1,wo=null,Xn=null,qo=null,gn=null,jo=null,Yo=null,Yn=null,Ln=null,V=null,ut=null;const po={queue:n.closed,idleTimer:Q,connect(J){qo=J||!0,BM()},terminate:st,execute:at,cancel:AJ,end:Pf,count:0,id:Y};return n.closed&&n.closed.push(po),po;async function kJ(){let J;try{J=o.socket?await Promise.resolve(o.socket(o)):new b$.Socket}catch(W){Et(W);return}return J.on("error",Et),J.on("close",bM),J.on("drain",jM),J}async function AJ({pid:J,secret:W},Z,$o){try{h=p().i32(16).i32(80877102).i32(J).i32(W).end(16),await cM(),_.once("error",$o),_.once("close",Z)}catch(Do){$o(Do)}}function at(J){if(vo)return iS(J,Co.connection("CONNECTION_DESTROYED",o));if(J.cancelled)return;try{return J.state=K,V?P.push(J):(V=J,V.active=!0),yJ(J),No($J(J))&&!J.describeFirst&&!J.cursorFn&&P.length<D&&(!J.options.onexecute||J.options.onexecute(po))}catch(W){return P.length===0&&No(tt),In(W),!0}}function $J(J){if(J.parameters.length>=65534)throw Co.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([CM(J),h$]):J.prepare?J.prepared?xS(J):Buffer.concat([CM(J),xS(J)]):JJ(J)}function CM(J){return Buffer.concat([hM(J.statement.string,J.parameters,J.statement.types,J.statement.name),uJ("S",J.statement.name)])}function xS(J){return Buffer.concat([dJ(J.parameters,J.statement.types,J.statement.name,J.cursorName),J.cursorFn?xM("",J.cursorRows):ey])}function JJ(J){return Buffer.concat([hM(J.statement.string,J.parameters,J.statement.types),dy,xS(J)])}function yJ(J){const W=[],Z=[],$o=kM(J,J.strings[0],J.args[0],W,Z,o);!J.tagged&&J.args.forEach((Do)=>Cf(Do,W,Z,o)),J.prepare=o.prepare&&("prepare"in J.options?J.options.prepare:!0),J.string=$o,J.signature=J.prepare&&Z+$o,J.onlyDescribe&&delete Wo[J.signature],J.parameters=J.parameters||W,J.prepared=J.prepare&&J.signature in Wo,J.describeFirst=J.onlyDescribe||W.length&&!J.prepared,J.statement=J.prepared?Wo[J.signature]:{string:$o,types:Z,name:J.prepare?Mn+E++:""},typeof o.debug==="function"&&o.debug(Y,$o,W,Z)}function No(J,W){if(Yo=Yo?Buffer.concat([Yo,J]):Buffer.from(J),W||Yo.length>=1024)return LM(W);return Xo===null&&(Xo=setImmediate(LM)),!0}function LM(J){const W=_.write(Yo,J);return Xo!==null&&clearImmediate(Xo),Yo=Xo=null,W}function RJ(){In(Co.connection("CONNECT_TIMEOUT",o,_)),_.destroy()}async function IM(){if(No(ly),!await new Promise((W)=>_.once("data",(Z)=>W(Z[0]===83)))&&T==="prefer")return Yt();_.removeAllListeners(),_=Py.connect({socket:_,servername:b$.isIP(_.host)?void 0:_.host,...T==="require"||T==="allow"||T==="prefer"?{rejectUnauthorized:!1}:T==="verify-full"?{}:typeof T==="object"?T:{}}),_.on("secureConnect",Yt),_.on("error",Et),_.on("close",bM),_.on("drain",jM)}function jM(){!V&&t(po)}function Zf(J){if(wo){if(wo.push(J),To-=J.length,To>=0)return}a=wo?Buffer.concat(wo,fo-To):a.length===0?J:Buffer.concat([a,J],a.length+J.length);while(a.length>4){if(fo=a.readUInt32BE(1),fo>=a.length){To=fo-a.length,wo=[a];break}try{OJ(a.subarray(0,fo+1))}catch(W){V&&(V.cursorFn||V.describeFirst)&&No(tt),In(W)}a=a.subarray(fo+1),To=0,wo=null}}async function cM(){if(vo=!1,to={},_||(_=await kJ()),!_)return;if(g.start(),o.socket)return T?IM():Yt();if(_.on("connect",T?IM:Yt),o.path)return _.connect(o.path);_.ssl=T,_.connect(A[Jo],k[Jo]),_.host=k[Jo],_.port=A[Jo],Jo=(Jo+1)%A.length}function BM(){setTimeout(cM,x?x+_o-N$.now():0)}function Yt(){try{Wo={},So=o.fetch_types,Mn=Math.random().toString(36).slice(2),E=1,i.start(),_.on("data",Zf),I&&_.setKeepAlive&&_.setKeepAlive(!0,1000*I);const J=sJ();No(J)}catch(J){Et(J)}}function Et(J){if(po.queue===n.connecting&&o.host[Io+1])return;In(J);while(P.length)iS(P.shift(),J)}function In(J){jo&&(jo.destroy(J),jo=null),V&&iS(V,J),qo&&(iS(qo,J),qo=null)}function iS(J,W){Object.defineProperties(W,{stack:{value:W.stack+J.origin.replace(/.*\n/,"\n"),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(W)}function Pf(){return gn||(!po.reserved&&S(po),!po.reserved&&!qo&&!V&&P.length===0?(st(),new Promise((J)=>_&&_.readyState!=="closed"?_.once("close",J):J())):gn=new Promise((J)=>Yn=J))}function st(){if(vo=!0,jo||V||qo||P.length)Et(Co.connection("CONNECTION_DESTROYED",o));if(clearImmediate(Xo),_)_.removeListener("data",Zf),_.removeListener("connect",Yt),_.readyState==="open"&&_.end(p().X().end());Yn&&(Yn(),gn=Yn=null)}async function bM(J){if(a=Buffer.alloc(0),To=0,wo=null,clearImmediate(Xo),_.removeListener("data",Zf),_.removeListener("connect",Yt),Q.cancel(),i.cancel(),g.cancel(),_.removeAllListeners(),_=null,qo)return BM();!J&&(V||P.length)&&Et(Co.connection("CONNECTION_CLOSED",o,_)),x=N$.now(),J&&o.shared.retries++,_o=(typeof v==="function"?v(o.shared.retries):v)*1000,f(po,Co.connection("CONNECTION_CLOSED",o,_))}function OJ(J,W=J[0]){(W===68?WJ:W===100?vJ:W===65?BJ:W===83?_J:W===90?wJ:W===67?KJ:W===50?NM:W===49?XJ:W===116?YJ:W===84?EJ:W===82?zJ:W===110?UJ:W===75?VJ:W===69?jJ:W===115?bJ:W===51?NJ:W===71?hJ:W===78?pJ:W===72?xJ:W===99?qJ:W===73?ZJ:W===86?PJ:W===118?gJ:W===87?iJ:lJ)(J)}function WJ(J){let W=7,Z,$o,Do;const Zo=V.isRaw?new Array(V.statement.columns.length):{};for(let eo=0;eo<V.statement.columns.length;eo++)$o=V.statement.columns[eo],Z=J.readInt32BE(W),W+=4,Do=Z===-1?null:V.isRaw===!0?J.subarray(W,W+=Z):$o.parser===void 0?J.toString("utf8",W,W+=Z):$o.parser.array===!0?$o.parser(J.toString("utf8",W+1,W+=Z)):$o.parser(J.toString("utf8",W,W+=Z)),V.isRaw?Zo[eo]=V.isRaw===!0?Do:w.value.from?w.value.from(Do,$o):Do:Zo[$o.name]=w.value.from?w.value.from(Do,$o):Do;V.forEachFn?V.forEachFn(w.row.from?w.row.from(Zo):Zo,C):C[Vo++]=w.row.from?w.row.from(Zo):Zo}function _J(J){const[W,Z]=J.toString("utf8",5,J.length-1).split(p.N);if(to[W]=Z,o.parameters[W]!==Z)o.parameters[W]=Z,H&&H(W,Z)}function wJ(J){if(V&&V.options.simple&&V.resolve(Xn||C),V=Xn=null,C=new Wt,g.cancel(),qo){if(N){if(!to.in_hot_standby||!to.default_transaction_read_only)return IJ();else if(LJ(N,to))return st()}if(So)return qo===!0&&(qo=null),rJ();qo!==!0&&at(qo),o.shared.retries=Io=0,qo=null;return}while(P.length&&(V=P.shift())&&(V.active=!0,V.cancelled))i$(o).cancel(V.state,V.cancelled.resolve,V.cancelled.reject);if(V)return;po.reserved?!po.reserved.release&&J[5]===73?gn?st():(po.reserved=null,t(po)):po.reserved():gn?st():t(po)}function KJ(J){Vo=0;for(let W=J.length-1;W>0;W--){if(J[W]===32&&J[W+1]<58&&C.count===null)C.count=+J.toString("utf8",W+1,J.length-1);if(J[W-1]>=65){C.command=J.toString("utf8",5,W),C.state=K;break}}if(ut&&(ut(),ut=null),C.command==="BEGIN"&&M!==1&&!po.reserved)return In(Co.generic("UNSAFE_TRANSACTION","Only use sql.begin, sql.reserved or max: 1"));if(V.options.simple)return NM();if(V.cursorFn)C.count&&V.cursorFn(C),No(tt);V.resolve(C)}function XJ(){V.parsing=!1}function NM(){!C.statement&&(C.statement=V.statement),C.columns=V.statement.columns}function YJ(J){const W=J.readUInt16BE(5);for(let Z=0;Z<W;++Z)!V.statement.types[Z]&&(V.statement.types[Z]=J.readUInt32BE(7+Z*4));V.prepare&&(Wo[V.signature]=V.statement),V.describeFirst&&!V.onlyDescribe&&(No(xS(V)),V.describeFirst=!1)}function EJ(J){if(C.command)Xn=Xn||[C],Xn.push(C=new Wt),C.count=null,V.statement.columns=null;const W=J.readUInt16BE(5);let Z=7,$o;V.statement.columns=Array(W);for(let Do=0;Do<W;++Do){$o=Z;while(J[Z++]!==0);const Zo=J.readUInt32BE(Z),eo=J.readUInt16BE(Z+4),ln=J.readUInt32BE(Z+6);V.statement.columns[Do]={name:w.column.from?w.column.from(J.toString("utf8",$o,Z-1)):J.toString("utf8",$o,Z-1),parser:O[ln],table:Zo,number:eo,type:ln},Z+=18}if(C.statement=V.statement,V.onlyDescribe)return V.resolve(V.statement),No(tt)}async function zJ(J,W=J.readUInt32BE(5)){(W===3?GJ:W===5?HJ:W===10?mJ:W===11?QJ:W===12?DJ:W!==0?eJ:jt)(J,W)}async function GJ(){const J=await gf();No(p().p().str(J).z(1).end())}async function HJ(J){const W="md5"+await x$(Buffer.concat([Buffer.from(await x$(await gf()+F)),J.subarray(9)]));No(p().p().str(W).z(1).end())}async function mJ(){Ln=(await US.randomBytes(18)).toString("base64"),p().p().str("SCRAM-SHA-256"+p.N);const J=p.i;No(p.inc(4).str("n,,n=*,r="+Ln).i32(p.i-J-4,J).end())}async function QJ(J){const W=J.toString("utf8",9).split(",").reduce((eo,ln)=>(eo[ln[0]]=ln.slice(2),eo),{}),Z=await US.pbkdf2Sync(await gf(),Buffer.from(W.s,"base64"),parseInt(W.i),32,"sha256"),$o=await jf(Z,"Client Key"),Do="n=*,r="+Ln+",r="+W.r+",s="+W.s+",i="+W.i+",c=biws,r="+W.r;Ho=(await jf(await jf(Z,"Server Key"),Do)).toString("base64");const Zo="c=biws,r="+W.r+",p="+oR($o,Buffer.from(await jf(await sy($o),Do))).toString("base64");No(p().p().str(Zo).end())}function DJ(J){if(J.toString("utf8",9).split(p.N,1)[0].slice(2)===Ho)return;In(Co.generic("SASL_SIGNATURE_MISMATCH","The server did not return the correct signature")),_.destroy()}function gf(){return Promise.resolve(typeof o.pass==="function"?o.pass():o.pass)}function UJ(){if(C.statement=V.statement,C.statement.columns=[],V.onlyDescribe)return V.resolve(V.statement),No(tt)}function VJ(J){K.pid=J.readUInt32BE(5),K.secret=J.readUInt32BE(9)}async function rJ(){So=!1,(await new wn([`
|
|
10
|
+
select b.oid, b.typarray
|
|
11
|
+
from pg_catalog.pg_type a
|
|
12
|
+
left join pg_catalog.pg_type b on b.oid = a.typelem
|
|
13
|
+
where a.typcategory = 'A'
|
|
14
|
+
group by b.oid, b.typarray
|
|
15
|
+
order by b.oid
|
|
16
|
+
`],[],at)).forEach(({oid:W,typarray:Z})=>CJ(W,Z))}function CJ(J,W){if(!!o.parsers[W]&&!!o.serializers[W])return;const Z=o.parsers[J];o.shared.typeArrayMap[J]=W,o.parsers[W]=($o)=>c$($o,Z,W),o.parsers[W].array=!0,o.serializers[W]=($o)=>j$($o,o.serializers[J],o,W)}function LJ(J,W){return J==="read-write"&&W.default_transaction_read_only==="on"||J==="read-only"&&W.default_transaction_read_only==="off"||J==="primary"&&W.in_hot_standby==="on"||J==="standby"&&W.in_hot_standby==="off"||J==="prefer-standby"&&W.in_hot_standby==="off"&&o.host[Io]}function IJ(){const J=new wn([`
|
|
17
|
+
show transaction_read_only;
|
|
18
|
+
select pg_catalog.pg_is_in_recovery()
|
|
19
|
+
`],[],at,null,{simple:!0});J.resolve=([[W],[Z]])=>{to.default_transaction_read_only=W.transaction_read_only,to.in_hot_standby=Z.pg_is_in_recovery?"on":"off"},J.execute()}function jJ(J){V&&(V.cursorFn||V.describeFirst)&&No(tt);const W=Co.postgres(_M(J));V&&V.retried?In(V.retried):V&&V.prepared&&uy.has(W.routine)?cJ(V,W):In(W)}function cJ(J,W){delete Wo[J.signature],J.retried=W,at(J)}function BJ(J){if(!r)return;let W=9;while(J[W++]!==0);r(J.toString("utf8",9,W-1),J.toString("utf8",W,J.length-1))}async function bJ(){try{const J=await Promise.resolve(V.cursorFn(C));Vo=0,J===Lt?No(aJ(V.portal)):(C=new Wt,No(xM("",V.cursorRows)))}catch(J){No(tt),V.reject(J)}}function NJ(){C.count&&V.cursorFn(C),V.resolve(C)}function hJ(){jo=new WM.Writable({autoDestroy:!0,write(J,W,Z){_.write(p().d().raw(J).end(),Z)},destroy(J,W){W(J),_.write(p().f().str(J+p.N).end()),jo=null},final(J){_.write(p().c().end()),ut=J}}),V.resolve(jo)}function xJ(){jo=new WM.Readable({read(){_.resume()}}),V.resolve(jo)}function iJ(){jo=new WM.Duplex({autoDestroy:!0,read(){_.resume()},write(J,W,Z){_.write(p().d().raw(J).end(),Z)},destroy(J,W){W(J),_.write(p().f().str(J+p.N).end()),jo=null},final(J){_.write(p().c().end()),ut=J}}),V.resolve(jo)}function vJ(J){jo&&(jo.push(J.subarray(5))||_.pause())}function qJ(){jo&&jo.push(null),jo=null}function pJ(J){z?z(_M(J)):console.log(_M(J))}function ZJ(){}function PJ(){In(Co.notSupported("FunctionCallResponse"))}function gJ(){In(Co.notSupported("NegotiateProtocolVersion"))}function lJ(J){console.error("Postgres.js : Unknown Message:",J[0])}function eJ(J,W){console.error("Postgres.js : Unknown Auth:",W)}function dJ(J,W,Z="",$o=""){let Do,Zo;return p().B().str($o+p.N).str(Z+p.N).i16(0).i16(J.length),J.forEach((eo,ln)=>{if(eo===null)return p.i32(4294967295);Zo=W[ln],J[ln]=eo=Zo in o.serializers?o.serializers[Zo](eo):""+eo,Do=p.i,p.inc(4).str(eo).i32(p.i-Do-4,Do)}),p.i16(0),p.end()}function hM(J,W,Z,$o=""){return p().P().str($o+p.N).str(J+p.N).i16(W.length),W.forEach((Do,Zo)=>p.i32(Z[Zo]||0)),p.end()}function uJ(J,W=""){return p().D().str(J).str(W+p.N).end()}function xM(J="",W=0){return Buffer.concat([p().E().str(J+p.N).i32(W).end(),h$])}function aJ(J=""){return Buffer.concat([p().C().str("P").str(J+p.N).end(),p().S().end()])}function sJ(){return h||p().inc(4).i16(3).z(2).str(Object.entries(Object.assign({user:F,database:$,client_encoding:"UTF8"},o.connection)).filter(([,J])=>J).map(([J,W])=>J+p.N+W).join(p.N)).z(2).end(0)}}function _M(o){const n={};let t=5;for(let S=5;S<o.length-1;S++)if(o[S]===0)n[ay[o[t]]]=o.toString("utf8",t+1,S),t=S+1;return n}function x$(o){return US.createHash("md5").update(o).digest("hex")}function jf(o,n){return US.createHmac("sha256",o).update(n).digest()}function sy(o){return US.createHash("sha256").update(o).digest()}function oR(o,n){const t=Math.max(o.length,n.length),S=Buffer.allocUnsafe(t);for(let f=0;f<t;f++)S[f]=o[f]^n[f];return S}function wM(o,n){if(n=typeof n==="function"?n():n,!n)return{cancel:jt,start:jt};let t;return{cancel(){t&&(clearTimeout(t),t=null)},start(){t&&clearTimeout(t),t=setTimeout(S,n*1000,arguments)}};function S(f){o.apply(null,f),t=null}}var KM=i$,gy=1,tt=p().S().end(),h$=p().H().end(),ly=p().i32(8).i32(80877103).end(8),ey=Buffer.concat([p().E().str(p.N).i32(0).end(),tt]),dy=p().D().str("S").str(p.N).end(),jt=()=>{},uy=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),ay={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 nR(o){return new Date(Date.UTC(2000,0,1)+Number(o/BigInt(1000)))}function tR(o,n,t,S,f){const T=(M,[F,k])=>(M[F.charCodeAt(0)]=k,M);Object.entries({R:(M)=>{let F=1;const k=n[M.readUInt32BE(F)]={schema:M.toString("utf8",F+=4,F=M.indexOf(0,F))||"pg_catalog",table:M.toString("utf8",F+1,F=M.indexOf(0,F+1)),columns:Array(M.readUInt16BE(F+=2)),keys:[]};F+=2;let A=0,$;while(F<M.length)$=k.columns[A++]={key:M[F++],name:f.column.from?f.column.from(M.toString("utf8",F,F=M.indexOf(0,F))):M.toString("utf8",F,F=M.indexOf(0,F)),type:M.readUInt32BE(F+=1),parser:t[M.readUInt32BE(F)],atttypmod:M.readUInt32BE(F+=4)},$.key&&k.keys.push($),F+=4},Y:()=>{},O:()=>{},B:(M)=>{n.date=nR(M.readBigInt64BE(9)),n.lsn=M.subarray(1,9)},I:(M)=>{let F=1;const k=n[M.readUInt32BE(F)],{row:A}=cf(M,k.columns,F+=7,f);S(A,{command:"insert",relation:k})},D:(M)=>{let F=1;const k=n[M.readUInt32BE(F)];F+=4;const A=M[F]===75;S(A||M[F]===79?cf(M,k.columns,F+=3,f).row:null,{command:"delete",relation:k,key:A})},U:(M)=>{let F=1;const k=n[M.readUInt32BE(F)];F+=4;const A=M[F]===75,$=A||M[F]===79?cf(M,k.columns,F+=3,f):null;$&&(F=$.i);const{row:O}=cf(M,k.columns,F+3,f);S(O,{command:"update",relation:k,key:A,old:$&&$.row})},T:()=>{},C:()=>{}}).reduce(T,{})[o[0]](o)}function cf(o,n,t,S){let f,T,M;const F=S.raw?new Array(n.length):{};for(let k=0;k<n.length;k++)f=o[t++],T=n[k],M=f===110?null:f===117?void 0:T.parser===void 0?o.toString("utf8",t+4,t+=4+o.readUInt32BE(t)):T.parser.array===!0?T.parser(o.toString("utf8",t+5,t+=4+o.readUInt32BE(t))):T.parser(o.toString("utf8",t+4,t+=4+o.readUInt32BE(t))),S.raw?F[k]=S.raw===!0?M:S.value.from?S.value.from(M,T):M:F[T.name]=S.value.from?S.value.from(M,T):M;return{i:t,row:S.row.from?S.row.from(F):F}}function SR(o){const n=o.match(/^(\*|insert|update|delete)?:?([^.]+?\.?[^=]+)?=?(.+)?/i)||[];if(!n)throw new Error("Malformed subscribe pattern: "+o);const[,t,S,f]=n;return(t||"*")+(S?":"+(S.indexOf(".")===-1?"public."+S:S):"")+(f?"="+f:"")}var v$=()=>{};function XM(o,n){const t=new Map,S="postgresjs_"+Math.random().toString(36).slice(2),f={};let T,M,F=!1;const k=O.sql=o({...n,transform:{column:{},value:{},row:{}},max:1,fetch_types:!1,idle_timeout:null,max_lifetime:null,connection:{...n.connection,replication:"database"},onclose:async function(){if(F)return;M=null,f.pid=f.secret=void 0,w(await z(k,S,n.publications)),t.forEach((H)=>H.forEach(({onsubscribe:D})=>D()))},no_subscribe:!0}),A=k.end,$=k.close;return k.end=async()=>{return F=!0,M&&await new Promise((H)=>(M.once("close",H),M.end())),A()},k.close=async()=>{return M&&await new Promise((H)=>(M.once("close",H),M.end())),$()},O;async function O(H,D,I=v$,v=v$){if(H=SR(H),!T)T=z(k,S,n.publications);const N={fn:D,onsubscribe:I},P=t.has(H)?t.get(H).add(N):t.set(H,new Set([N])).get(H),Y=()=>{P.delete(N),P.size===0&&t.delete(H)};return T.then((K)=>{return w(K),I(),M&&M.on("error",v),{unsubscribe:Y,state:f,sql:k}})}function w(H){M=H.stream,f.pid=H.state.pid,f.secret=H.state.secret}async function z(H,D,I){if(!I)throw new Error("Missing publication names");const v=await H.unsafe(`CREATE_REPLICATION_SLOT ${D} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT`),[N]=v,P=await H.unsafe(`START_REPLICATION SLOT ${D} LOGICAL ${N.consistent_point} (proto_version '1', publication_names '${I}')`).writable(),Y={lsn:Buffer.concat(N.consistent_point.split("/").map((_)=>Buffer.from(("00000000"+_).slice(-8),"hex")))};return P.on("data",Q),P.on("error",K),P.on("close",H.close),{stream:P,state:v.state};function K(_){console.error("Unexpected error during logical streaming - reconnecting",_)}function Q(_){if(_[0]===119)tR(_.subarray(25),Y,H.options.parsers,i,n.transform);else if(_[0]===107&&_[17])Y.lsn=_.subarray(1,9),g()}function i(_,h){const C=h.relation.schema+"."+h.relation.table;r("*",_,h),r("*:"+C,_,h),h.relation.keys.length&&r("*:"+C+"="+h.relation.keys.map((a)=>_[a.name]),_,h),r(h.command,_,h),r(h.command+":"+C,_,h),h.relation.keys.length&&r(h.command+":"+C+"="+h.relation.keys.map((a)=>_[a.name]),_,h)}function g(){const _=Buffer.alloc(34);_[0]="r".charCodeAt(0),_.fill(Y.lsn,1),_.writeBigInt64BE(BigInt(Date.now()-Date.UTC(2000,0,1))*BigInt(1000),25),P.write(_)}}function r(H,D,I){t.has(H)&&t.get(H).forEach(({fn:v})=>v(D,I,H))}}import q$ from"stream";function YM(o,n,t=393216){return new Promise(async(S,f)=>{await o.begin(async(T)=>{let M;!n&&([{oid:n}]=await T`select lo_creat(-1) as oid`);const[{fd:F}]=await T`select lo_open(${n}, ${t}) as fd`,k={writable:$,readable:A,close:()=>T`select lo_close(${F})`.then(M),tell:()=>T`select lo_tell64(${F})`,read:(O)=>T`select loread(${F}, ${O}) as data`,write:(O)=>T`select lowrite(${F}, ${O})`,truncate:(O)=>T`select lo_truncate64(${F}, ${O})`,seek:(O,w=0)=>T`select lo_lseek64(${F}, ${O}, ${w})`,size:()=>T`
|
|
20
|
+
select
|
|
21
|
+
lo_lseek64(${F}, location, 0) as position,
|
|
22
|
+
seek.size
|
|
23
|
+
from (
|
|
24
|
+
select
|
|
25
|
+
lo_lseek64($1, 0, 2) as size,
|
|
26
|
+
tell.location
|
|
27
|
+
from (select lo_tell64($1) as location) tell
|
|
28
|
+
) seek
|
|
29
|
+
`};return S(k),new Promise(async(O)=>M=O);async function A({highWaterMark:O=16384,start:w=0,end:z=1/0}={}){let r=z-w;return w&&await k.seek(w),new q$.Readable({highWaterMark:O,async read(H){const D=H>r?H-r:H;r-=H;const[{data:I}]=await k.read(D);if(this.push(I),I.length<H)this.push(null)}})}async function $({highWaterMark:O=16384,start:w=0}={}){return w&&await k.seek(w),new q$.Writable({highWaterMark:O,write(z,r,H){k.write(z).then(()=>H(),H)}})}}).catch(f)})}function Bf(o,n){const t=MR(o,n),S=t.no_subscribe||XM(Bf,{...t});let f=!1;const T=Jn(),M=Jn(),F=Jn(),k=Jn(),A=Jn(),$=Jn(),O=Jn(),w=Jn(),z={connecting:M,reserved:F,closed:k,ended:A,open:$,busy:O,full:w},r=[...Array(t.max)].map(()=>KM(t,z,{onopen:Wo,onend:to,onclose:Mn})),H=D(i);return Object.assign(H,{get parameters(){return t.parameters},largeObject:YM.bind(null,H),subscribe:S,CLOSE:Lt,END:Lt,PostgresError:It,options:t,reserve:N,listen:I,begin:P,close:C,end:h}),H;function D(E){return E.debug=t.debug,Object.entries(t.types).reduce((fo,[_o,Vo])=>{return fo[_o]=(Ho)=>new Bn(Ho,Vo.to),fo},x),Object.assign(To,{types:x,typed:x,unsafe:Jo,notify:v,array:Q,json:K,file:Io}),To;function x(fo,_o){return new Bn(fo,_o)}function To(fo,..._o){return fo&&Array.isArray(fo.raw)?new wn(fo,_o,E,_):typeof fo==="string"&&!_o.length?new DS(t.transform.column.to?t.transform.column.to(fo):fo):new rf(fo,_o)}function Jo(fo,_o=[],Vo={}){return arguments.length===2&&!Array.isArray(_o)&&(Vo=_o,_o=[]),new wn([fo],_o,E,_,{prepare:!1,...Vo,simple:"simple"in Vo?Vo.simple:_o.length===0})}function Io(fo,_o=[],Vo={}){return arguments.length===2&&!Array.isArray(_o)&&(Vo=_o,_o=[]),new wn([],_o,(Xo)=>{TR.readFile(fo,"utf8",(vo,wo)=>{if(vo)return Xo.reject(vo);Xo.strings=[wo],E(Xo)})},_,{...Vo,simple:"simple"in Vo?Vo.simple:_o.length===0})}}async function I(E,x,To){const Jo={fn:x,onlisten:To},Io=I.sql||(I.sql=Bf({...t,max:1,idle_timeout:null,max_lifetime:null,fetch_types:!1,onclose(){Object.entries(I.channels).forEach(([Xo,{listeners:vo}])=>{delete I.channels[Xo],Promise.all(vo.map((wo)=>I(Xo,wo.fn,wo.onlisten).catch(()=>{})))})},onnotify(Xo,vo){Xo in I.channels&&I.channels[Xo].listeners.forEach((wo)=>wo.fn(vo))}})),fo=I.channels||(I.channels={});if(E in fo){fo[E].listeners.push(Jo);const Xo=await fo[E].result;return Jo.onlisten&&Jo.onlisten(),{state:Xo.state,unlisten:Ho}}fo[E]={result:Io`listen ${Io.unsafe('"'+E.replace(/"/g,'""')+'"')}`,listeners:[Jo]};const Vo=await fo[E].result;return Jo.onlisten&&Jo.onlisten(),{state:Vo.state,unlisten:Ho};async function Ho(){if(E in fo===!1)return;if(fo[E].listeners=fo[E].listeners.filter((Xo)=>Xo!==Jo),fo[E].listeners.length)return;return delete fo[E],Io`unlisten ${Io.unsafe('"'+E.replace(/"/g,'""')+'"')}`}}async function v(E,x){return await H`select pg_notify(${E}, ${""+x})`}async function N(){const E=Jn(),x=$.length?$.shift():await new Promise((Io)=>{T.push({reserve:Io}),k.length&&So(k.shift())});Y(x,F),x.reserved=()=>E.length?x.execute(E.shift()):Y(x,F),x.reserved.release=!0;const To=D(Jo);return To.release=()=>{x.reserved=null,Wo(x)},To;function Jo(Io){x.queue===w?E.push(Io):x.execute(Io)||Y(x,w)}}async function P(E,x){!x&&(x=E,E="");const To=Jn();let Jo=0,Io,fo=null;try{return await H.unsafe("begin "+E.replace(/[^a-z ]/ig,""),[],{onexecute:Vo}).execute(),await Promise.race([_o(Io,x),new Promise((Ho,Xo)=>Io.onclose=Xo)])}catch(Ho){throw Ho}async function _o(Ho,Xo,vo){const wo=D(jo);wo.savepoint=gn,wo.prepare=(Yo)=>fo=Yo.replace(/[^a-z0-9$-_. ]/gi);let Xn,qo;vo&&await wo`savepoint ${wo(vo)}`;try{if(qo=await new Promise((Yo,Yn)=>{const Ln=Xo(wo);Promise.resolve(Array.isArray(Ln)?Promise.all(Ln):Ln).then(Yo,Yn)}),Xn)throw Xn}catch(Yo){throw await(vo?wo`rollback to ${wo(vo)}`:wo`rollback`),Yo instanceof It&&Yo.code==="25P02"&&Xn||Yo}if(!vo)fo?await wo`prepare transaction '${wo.unsafe(fo)}'`:await wo`commit`;return qo;function gn(Yo,Yn){if(Yo&&Array.isArray(Yo.raw))return gn((Ln)=>Ln.apply(Ln,arguments));return arguments.length===1&&(Yn=Yo,Yo=null),_o(Ho,Yn,"s"+Jo+++(Yo?"_"+Yo:""))}function jo(Yo){Yo.catch((Yn)=>Xn||(Xn=Yn)),Ho.queue===w?To.push(Yo):Ho.execute(Yo)||Y(Ho,w)}}function Vo(Ho){Io=Ho,Y(Ho,F),Ho.reserved=()=>To.length?Ho.execute(To.shift()):Y(Ho,F)}}function Y(E,x){return E.queue.remove(E),x.push(E),E.queue=x,x===$?E.idleTimer.start():E.idleTimer.cancel(),E}function K(E){return new Bn(E,3802)}function Q(E,x){if(!Array.isArray(E))return Q(Array.from(arguments));return new Bn(E,x||(E.length?Uf(E)||25:0),t.shared.typeArrayMap)}function i(E){if(f)return E.reject(Co.connection("CONNECTION_ENDED",t,t));if($.length)return g($.shift(),E);if(k.length)return So(k.shift(),E);O.length?g(O.shift(),E):T.push(E)}function g(E,x){return E.execute(x)?Y(E,O):Y(E,w)}function _(E){return new Promise((x,To)=>{E.state?E.active?KM(t).cancel(E.state,x,To):E.cancelled={resolve:x,reject:To}:(T.remove(E),E.cancelled=!0,E.reject(Co.generic("57014","canceling statement due to user request")),x())})}async function h({timeout:E=null}={}){if(f)return f;await 1;let x;return f=Promise.race([new Promise((To)=>E!==null&&(x=setTimeout(a,E*1000,To))),Promise.all(r.map((To)=>To.end()).concat(I.sql?I.sql.end({timeout:0}):[],S.sql?S.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(x))}async function C(){await Promise.all(r.map((E)=>E.end()))}async function a(E){await Promise.all(r.map((x)=>x.terminate()));while(T.length)T.shift().reject(Co.connection("CONNECTION_DESTROYED",t));E()}function So(E,x){return Y(E,M),E.connect(x),E}function to(E){Y(E,A)}function Wo(E){if(T.length===0)return Y(E,$);let x=Math.ceil(T.length/(M.length+1)),To=!0;while(To&&T.length&&x-- >0){const Jo=T.shift();if(Jo.reserve)return Jo.reserve(E);To=E.execute(Jo)}To?Y(E,O):Y(E,w)}function Mn(E,x){Y(E,k),E.reserved=null,E.onclose&&(E.onclose(x),E.onclose=null),t.onclose&&t.onclose(E.id),T.length&&So(E,T.shift())}}function MR(o,n){if(o&&o.shared)return o;const t=process.env,S=(!o||typeof o==="string"?n:o)||{},{url:f,multihost:T}=JR(o),M=[...f.searchParams].reduce((w,[z,r])=>(w[z]=r,w),{}),F=S.hostname||S.host||T||f.hostname||t.PGHOST||"localhost",k=S.port||f.port||t.PGPORT||5432,A=S.user||S.username||f.username||t.PGUSERNAME||t.PGUSER||yR();S.no_prepare&&(S.prepare=!1),M.sslmode&&(M.ssl=M.sslmode,delete M.sslmode),"timeout"in S&&(console.log("The timeout option is deprecated, use idle_timeout instead"),S.idle_timeout=S.timeout),M.sslrootcert==="system"&&(M.ssl="verify-full");const $=["idle_timeout","connect_timeout","max_lifetime","max_pipeline","backoff","keep_alive"],O={max:10,ssl:!1,idle_timeout:null,connect_timeout:30,max_lifetime:AR,max_pipeline:100,backoff:kR,keep_alive:60,prepare:!0,debug:!1,fetch_types:!0,publications:"alltables",target_session_attrs:null};return{host:Array.isArray(F)?F:F.split(",").map((w)=>w.split(":")[0]),port:Array.isArray(k)?k:F.split(",").map((w)=>parseInt(w.split(":")[1]||k)),path:S.path||F.indexOf("/")>-1&&F+"/.s.PGSQL."+k,database:S.database||S.db||(f.pathname||"").slice(1)||t.PGDATABASE||A,user:A,pass:S.pass||S.password||f.password||t.PGPASSWORD||"",...Object.entries(O).reduce((w,[z,r])=>{const H=z in S?S[z]:(z in M)?M[z]==="disable"||M[z]==="false"?!1:M[z]:t["PG"+z.toUpperCase()]||r;return w[z]=typeof H==="string"&&$.includes(z)?+H:H,w},{}),connection:{application_name:"postgres.js",...S.connection,...Object.entries(M).reduce((w,[z,r])=>((z in O)||(w[z]=r),w),{})},types:S.types||{},target_session_attrs:FR(S,f,t),onnotice:S.onnotice,onnotify:S.onnotify,onclose:S.onclose,onparameter:S.onparameter,socket:S.socket,transform:$R(S.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...L$(S.types)}}function FR(o,n,t){const S=o.target_session_attrs||n.searchParams.get("target_session_attrs")||t.PGTARGETSESSIONATTRS;if(!S||["read-write","read-only","primary","standby","prefer-standby"].includes(S))return S;throw new Error("target_session_attrs "+S+" is not supported")}function kR(o){return(0.5+Math.random()/2)*Math.min(3**o/100,20)}function AR(){return 60*(30+Math.random()*30)}function $R(o){return{undefined:o.undefined,column:{from:typeof o.column==="function"?o.column:o.column&&o.column.from,to:o.column&&o.column.to},value:{from:typeof o.value==="function"?o.value:o.value&&o.value.from,to:o.value&&o.value.to},row:{from:typeof o.row==="function"?o.row:o.row&&o.row.from,to:o.row&&o.row.to}}}function JR(o){if(!o||typeof o!=="string")return{url:{searchParams:new Map}};let n=o;n=n.slice(n.indexOf("://")+3).split(/[?/]/)[0],n=decodeURIComponent(n.slice(n.indexOf("@")+1));const t=new URL(o.replace(n,n.split(",")[0]));return{url:{username:decodeURIComponent(t.username),password:decodeURIComponent(t.password),host:t.host,hostname:t.hostname,port:t.port,pathname:t.pathname,searchParams:t.searchParams},multihost:n.indexOf(",")>-1&&n}}function yR(){try{return fR.userInfo().username}catch(o){return process.env.USERNAME||process.env.USER||process.env.LOGNAME}}Object.assign(Bf,{PostgresError:It,toPascal:Rt,pascal:RM,toCamel:yt,camel:yM,toKebab:Ot,kebab:OM,fromPascal:mS,fromCamel:HS,fromKebab:QS,BigInt:{to:20,from:[20],parse:(o)=>BigInt(o),serialize:(o)=>o.toString()}});var p$=Bf;function OR(o){g$=o}function bf(){return g$}function L(o,n){const t=bf(),S=Nf({issueData:n,data:o.data,path:o.path,errorMaps:[o.common.contextualErrorMap,o.schemaErrorMap,t,t===Nt?void 0:Nt].filter((f)=>!!f)});o.common.issues.push(S)}function hf(o,n,t,S){if(t==="a"&&!S)throw new TypeError("Private accessor was defined without a getter");if(typeof n==="function"?o!==n||!S:!n.has(o))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?S:t==="a"?S.call(o):S?S.value:n.get(o)}function l$(o,n,t,S,f){if(S==="m")throw new TypeError("Private method is not writable");if(S==="a"&&!f)throw new TypeError("Private accessor was defined without a setter");if(typeof n==="function"?o!==n||!f:!n.has(o))throw new TypeError("Cannot write private member to an object whose class did not declare it");return S==="a"?f.call(o,t):f?f.value=t:n.set(o,t),t}function oo(o){if(!o)return{};const{errorMap:n,invalid_type_error:t,required_error:S,description:f}=o;if(n&&(t||S))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(n)return{errorMap:n,description:f};return{errorMap:(M,F)=>{var k,A;const{message:$}=o;if(M.code==="invalid_enum_value")return{message:$!==null&&$!==void 0?$:F.defaultError};if(typeof F.data==="undefined")return{message:(k=$!==null&&$!==void 0?$:S)!==null&&k!==void 0?k:F.defaultError};if(M.code!=="invalid_type")return{message:F.defaultError};return{message:(A=$!==null&&$!==void 0?$:t)!==null&&A!==void 0?A:F.defaultError}},description:f}}function d$(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 UR(o){return new RegExp(`^${d$(o)}\$`)}function u$(o){let n=`${e$}T${d$(o)}`;const 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 VR(o,n){if((n==="v4"||!n)&&HR.test(o))return!0;if((n==="v6"||!n)&&mR.test(o))return!0;return!1}function rR(o,n){const t=(o.toString().split(".")[1]||"").length,S=(n.toString().split(".")[1]||"").length,f=t>S?t:S,T=parseInt(o.toFixed(f).replace(".","")),M=parseInt(n.toFixed(f).replace(".",""));return T%M/Math.pow(10,f)}function ct(o){if(o instanceof Qo){const n={};for(let t in o.shape){const S=o.shape[t];n[t]=Vn.create(ct(S))}return new Qo({...o._def,shape:()=>n})}else if(o instanceof Un)return new Un({...o._def,type:ct(o.element)});else if(o instanceof Vn)return Vn.create(ct(o.unwrap()));else if(o instanceof Zn)return Zn.create(ct(o.unwrap()));else if(o instanceof Nn)return Nn.create(o.items.map((n)=>ct(n)));else return o}function mM(o,n){const t=St(o),S=St(n);if(o===n)return{valid:!0,data:o};else if(t===c.object&&S===c.object){const f=Ao.objectKeys(n),T=Ao.objectKeys(o).filter((F)=>f.indexOf(F)!==-1),M={...o,...n};for(let F of T){const k=mM(o[F],n[F]);if(!k.valid)return{valid:!1};M[F]=k.data}return{valid:!0,data:M}}else if(t===c.array&&S===c.array){if(o.length!==n.length)return{valid:!1};const f=[];for(let T=0;T<o.length;T++){const M=o[T],F=n[T],k=mM(M,F);if(!k.valid)return{valid:!1};f.push(k.data)}return{valid:!0,data:f}}else if(t===c.date&&S===c.date&&+o===+n)return{valid:!0,data:o};else return{valid:!1}}function a$(o,n){return new Ft({values:o,typeName:e.ZodEnum,...oo(n)})}function s$(o,n={},t){if(o)return wt.create().superRefine((S,f)=>{var T,M;if(!o(S)){const F=typeof n==="function"?n(S):typeof n==="string"?{message:n}:n,k=(M=(T=F.fatal)!==null&&T!==void 0?T:t)!==null&&M!==void 0?M:!0,A=typeof F==="string"?{message:F}:F;f.addIssue({code:"custom",...A,fatal:k})}});return wt.create()}var Ao;(function(o){o.assertEqual=(f)=>f;function n(f){}o.assertIs=n;function t(f){throw new Error}o.assertNever=t,o.arrayToEnum=(f)=>{const T={};for(let M of f)T[M]=M;return T},o.getValidEnumValues=(f)=>{const T=o.objectKeys(f).filter((F)=>typeof f[f[F]]!=="number"),M={};for(let F of T)M[F]=f[F];return o.objectValues(M)},o.objectValues=(f)=>{return o.objectKeys(f).map(function(T){return f[T]})},o.objectKeys=typeof Object.keys==="function"?(f)=>Object.keys(f):(f)=>{const T=[];for(let M in f)if(Object.prototype.hasOwnProperty.call(f,M))T.push(M);return T},o.find=(f,T)=>{for(let M of f)if(T(M))return M;return},o.isInteger=typeof Number.isInteger==="function"?(f)=>Number.isInteger(f):(f)=>typeof f==="number"&&isFinite(f)&&Math.floor(f)===f;function S(f,T=" | "){return f.map((M)=>typeof M==="string"?`'${M}'`:M).join(T)}o.joinValues=S,o.jsonStringifyReplacer=(f,T)=>{if(typeof T==="bigint")return T.toString();return T}})(Ao||(Ao={}));var zM;(function(o){o.mergeShapes=(n,t)=>{return{...n,...t}}})(zM||(zM={}));var c=Ao.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),St=(o)=>{switch(typeof o){case"undefined":return c.undefined;case"string":return c.string;case"number":return isNaN(o)?c.nan:c.number;case"boolean":return c.boolean;case"function":return c.function;case"bigint":return c.bigint;case"symbol":return c.symbol;case"object":if(Array.isArray(o))return c.array;if(o===null)return c.null;if(o.then&&typeof o.then==="function"&&o.catch&&typeof o.catch==="function")return c.promise;if(typeof Map!=="undefined"&&o instanceof Map)return c.map;if(typeof Set!=="undefined"&&o instanceof Set)return c.set;if(typeof Date!=="undefined"&&o instanceof Date)return c.date;return c.object;default:return c.unknown}},G=Ao.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),RR=(o)=>{return JSON.stringify(o,null,2).replace(/"([^"]+)":/g,"$1:")};class yn extends Error{constructor(o){super();this.issues=[],this.addIssue=(t)=>{this.issues=[...this.issues,t]},this.addIssues=(t=[])=>{this.issues=[...this.issues,...t]};const n=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,n);else this.__proto__=n;this.name="ZodError",this.issues=o}get errors(){return this.issues}format(o){const n=o||function(f){return f.message},t={_errors:[]},S=(f)=>{for(let T of f.issues)if(T.code==="invalid_union")T.unionErrors.map(S);else if(T.code==="invalid_return_type")S(T.returnTypeError);else if(T.code==="invalid_arguments")S(T.argumentsError);else if(T.path.length===0)t._errors.push(n(T));else{let M=t,F=0;while(F<T.path.length){const k=T.path[F];if(F!==T.path.length-1)M[k]=M[k]||{_errors:[]};else M[k]=M[k]||{_errors:[]},M[k]._errors.push(n(T));M=M[k],F++}}};return S(this),t}static assert(o){if(!(o instanceof yn))throw new Error(`Not a ZodError: ${o}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Ao.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(o=(n)=>n.message){const n={},t=[];for(let S of this.issues)if(S.path.length>0)n[S.path[0]]=n[S.path[0]]||[],n[S.path[0]].push(o(S));else t.push(o(S));return{formErrors:t,fieldErrors:n}}get formErrors(){return this.flatten()}}yn.create=(o)=>{return new yn(o)};var Nt=(o,n)=>{let t;switch(o.code){case G.invalid_type:if(o.received===c.undefined)t="Required";else t=`Expected ${o.expected}, received ${o.received}`;break;case G.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(o.expected,Ao.jsonStringifyReplacer)}`;break;case G.unrecognized_keys:t=`Unrecognized key(s) in object: ${Ao.joinValues(o.keys,", ")}`;break;case G.invalid_union:t="Invalid input";break;case G.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${Ao.joinValues(o.options)}`;break;case G.invalid_enum_value:t=`Invalid enum value. Expected ${Ao.joinValues(o.options)}, received '${o.received}'`;break;case G.invalid_arguments:t="Invalid function arguments";break;case G.invalid_return_type:t="Invalid function return type";break;case G.invalid_date:t="Invalid date";break;case G.invalid_string:if(typeof o.validation==="object")if("includes"in o.validation){if(t=`Invalid input: must include "${o.validation.includes}"`,typeof o.validation.position==="number")t=`${t} at one or more positions greater than or equal to ${o.validation.position}`}else if("startsWith"in o.validation)t=`Invalid input: must start with "${o.validation.startsWith}"`;else if("endsWith"in o.validation)t=`Invalid input: must end with "${o.validation.endsWith}"`;else Ao.assertNever(o.validation);else if(o.validation!=="regex")t=`Invalid ${o.validation}`;else t="Invalid";break;case G.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 G.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 G.custom:t="Invalid input";break;case G.invalid_intersection_types:t="Intersection results could not be merged";break;case G.not_multiple_of:t=`Number must be a multiple of ${o.multipleOf}`;break;case G.not_finite:t="Number must be finite";break;default:t=n.defaultError,Ao.assertNever(o)}return{message:t}},g$=Nt,Nf=(o)=>{const{data:n,path:t,errorMaps:S,issueData:f}=o,T=[...t,...f.path||[]],M={...f,path:T};if(f.message!==void 0)return{...f,path:T,message:f.message};let F="";const k=S.filter((A)=>!!A).slice().reverse();for(let A of k)F=A(M,{data:n,defaultError:F}).message;return{...f,path:T,message:F}},WR=[];class lo{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(o,n){const t=[];for(let S of n){if(S.status==="aborted")return d;if(S.status==="dirty")o.dirty();t.push(S.value)}return{status:o.value,value:t}}static async mergeObjectAsync(o,n){const t=[];for(let S of n){const f=await S.key,T=await S.value;t.push({key:f,value:T})}return lo.mergeObjectSync(o,t)}static mergeObjectSync(o,n){const t={};for(let S of n){const{key:f,value:T}=S;if(f.status==="aborted")return d;if(T.status==="aborted")return d;if(f.status==="dirty")o.dirty();if(T.status==="dirty")o.dirty();if(f.value!=="__proto__"&&(typeof T.value!=="undefined"||S.alwaysSet))t[f.value]=T.value}return{status:o.value,value:t}}}var d=Object.freeze({status:"aborted"}),Bt=(o)=>({status:"dirty",value:o}),on=(o)=>({status:"valid",value:o}),GM=(o)=>o.status==="aborted",HM=(o)=>o.status==="dirty",CS=(o)=>o.status==="valid",LS=(o)=>typeof Promise!=="undefined"&&o instanceof Promise;var q;(function(o){o.errToObj=(n)=>typeof n==="string"?{message:n}:n||{},o.toString=(n)=>typeof n==="string"?n:n===null||n===void 0?void 0:n.message})(q||(q={}));var VS,rS;class rn{constructor(o,n,t,S){this._cachedPath=[],this.parent=o,this.data=n,this._path=t,this._key=S}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 Z$=(o,n)=>{if(CS(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;const t=new yn(o.common.issues);return this._error=t,this._error}}}};class no{constructor(o){this.spa=this.safeParseAsync,this._def=o,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(o){return St(o.data)}_getOrReturnCtx(o,n){return n||{common:o.parent.common,data:o.data,parsedType:St(o.data),schemaErrorMap:this._def.errorMap,path:o.path,parent:o.parent}}_processInputParams(o){return{status:new lo,ctx:{common:o.parent.common,data:o.data,parsedType:St(o.data),schemaErrorMap:this._def.errorMap,path:o.path,parent:o.parent}}}_parseSync(o){const n=this._parse(o);if(LS(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(o){const n=this._parse(o);return Promise.resolve(n)}parse(o,n){const t=this.safeParse(o,n);if(t.success)return t.data;throw t.error}safeParse(o,n){var t;const S={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:St(o)},f=this._parseSync({data:o,path:S.path,parent:S});return Z$(S,f)}async parseAsync(o,n){const t=await this.safeParseAsync(o,n);if(t.success)return t.data;throw t.error}async safeParseAsync(o,n){const 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:St(o)},S=this._parse({data:o,path:t.path,parent:t}),f=await(LS(S)?S:Promise.resolve(S));return Z$(t,f)}refine(o,n){const t=(S)=>{if(typeof n==="string"||typeof n==="undefined")return{message:n};else if(typeof n==="function")return n(S);else return n};return this._refinement((S,f)=>{const T=o(S),M=()=>f.addIssue({code:G.custom,...t(S)});if(typeof Promise!=="undefined"&&T instanceof Promise)return T.then((F)=>{if(!F)return M(),!1;else return!0});if(!T)return M(),!1;else return!0})}refinement(o,n){return this._refinement((t,S)=>{if(!o(t))return S.addIssue(typeof n==="function"?n(t,S):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)}optional(){return Vn.create(this,this._def)}nullable(){return Zn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Un.create(this,this._def)}promise(){return Xt.create(this,this._def)}or(o){return vt.create([this,o],this._def)}and(o){return qt.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){const n=typeof o==="function"?o:()=>o;return new gt({...oo(this._def),innerType:this,defaultValue:n,typeName:e.ZodDefault})}brand(){return new vf({typeName:e.ZodBranded,type:this,...oo(this._def)})}catch(o){const 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 NS.create(this,o)}readonly(){return et.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var _R=/^c[^\s-]{8,}$/i,wR=/^[0-9a-z]+$/,KR=/^[0-9A-HJKMNP-TV-Z]{26}$/,XR=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,YR=/^[a-z0-9_-]{21}$/i,ER=/^[-+]?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)?)??$/,zR=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,GR="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",EM,HR=/^(?:(?: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])$/,mR=/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,QR=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,e$="((\\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])))",DR=new RegExp(`^${e$}\$`);class Dn extends no{_parse(o){if(this._def.coerce)o.data=String(o.data);if(this._getType(o)!==c.string){const f=this._getOrReturnCtx(o);return L(f,{code:G.invalid_type,expected:c.string,received:f.parsedType}),d}const t=new lo;let S=void 0;for(let f of this._def.checks)if(f.kind==="min"){if(o.data.length<f.value)S=this._getOrReturnCtx(o,S),L(S,{code:G.too_small,minimum:f.value,type:"string",inclusive:!0,exact:!1,message:f.message}),t.dirty()}else if(f.kind==="max"){if(o.data.length>f.value)S=this._getOrReturnCtx(o,S),L(S,{code:G.too_big,maximum:f.value,type:"string",inclusive:!0,exact:!1,message:f.message}),t.dirty()}else if(f.kind==="length"){const T=o.data.length>f.value,M=o.data.length<f.value;if(T||M){if(S=this._getOrReturnCtx(o,S),T)L(S,{code:G.too_big,maximum:f.value,type:"string",inclusive:!0,exact:!0,message:f.message});else if(M)L(S,{code:G.too_small,minimum:f.value,type:"string",inclusive:!0,exact:!0,message:f.message});t.dirty()}}else if(f.kind==="email"){if(!zR.test(o.data))S=this._getOrReturnCtx(o,S),L(S,{validation:"email",code:G.invalid_string,message:f.message}),t.dirty()}else if(f.kind==="emoji"){if(!EM)EM=new RegExp(GR,"u");if(!EM.test(o.data))S=this._getOrReturnCtx(o,S),L(S,{validation:"emoji",code:G.invalid_string,message:f.message}),t.dirty()}else if(f.kind==="uuid"){if(!XR.test(o.data))S=this._getOrReturnCtx(o,S),L(S,{validation:"uuid",code:G.invalid_string,message:f.message}),t.dirty()}else if(f.kind==="nanoid"){if(!YR.test(o.data))S=this._getOrReturnCtx(o,S),L(S,{validation:"nanoid",code:G.invalid_string,message:f.message}),t.dirty()}else if(f.kind==="cuid"){if(!_R.test(o.data))S=this._getOrReturnCtx(o,S),L(S,{validation:"cuid",code:G.invalid_string,message:f.message}),t.dirty()}else if(f.kind==="cuid2"){if(!wR.test(o.data))S=this._getOrReturnCtx(o,S),L(S,{validation:"cuid2",code:G.invalid_string,message:f.message}),t.dirty()}else if(f.kind==="ulid"){if(!KR.test(o.data))S=this._getOrReturnCtx(o,S),L(S,{validation:"ulid",code:G.invalid_string,message:f.message}),t.dirty()}else if(f.kind==="url")try{new URL(o.data)}catch(T){S=this._getOrReturnCtx(o,S),L(S,{validation:"url",code:G.invalid_string,message:f.message}),t.dirty()}else if(f.kind==="regex"){if(f.regex.lastIndex=0,!f.regex.test(o.data))S=this._getOrReturnCtx(o,S),L(S,{validation:"regex",code:G.invalid_string,message:f.message}),t.dirty()}else if(f.kind==="trim")o.data=o.data.trim();else if(f.kind==="includes"){if(!o.data.includes(f.value,f.position))S=this._getOrReturnCtx(o,S),L(S,{code:G.invalid_string,validation:{includes:f.value,position:f.position},message:f.message}),t.dirty()}else if(f.kind==="toLowerCase")o.data=o.data.toLowerCase();else if(f.kind==="toUpperCase")o.data=o.data.toUpperCase();else if(f.kind==="startsWith"){if(!o.data.startsWith(f.value))S=this._getOrReturnCtx(o,S),L(S,{code:G.invalid_string,validation:{startsWith:f.value},message:f.message}),t.dirty()}else if(f.kind==="endsWith"){if(!o.data.endsWith(f.value))S=this._getOrReturnCtx(o,S),L(S,{code:G.invalid_string,validation:{endsWith:f.value},message:f.message}),t.dirty()}else if(f.kind==="datetime"){if(!u$(f).test(o.data))S=this._getOrReturnCtx(o,S),L(S,{code:G.invalid_string,validation:"datetime",message:f.message}),t.dirty()}else if(f.kind==="date"){if(!DR.test(o.data))S=this._getOrReturnCtx(o,S),L(S,{code:G.invalid_string,validation:"date",message:f.message}),t.dirty()}else if(f.kind==="time"){if(!UR(f).test(o.data))S=this._getOrReturnCtx(o,S),L(S,{code:G.invalid_string,validation:"time",message:f.message}),t.dirty()}else if(f.kind==="duration"){if(!ER.test(o.data))S=this._getOrReturnCtx(o,S),L(S,{validation:"duration",code:G.invalid_string,message:f.message}),t.dirty()}else if(f.kind==="ip"){if(!VR(o.data,f.version))S=this._getOrReturnCtx(o,S),L(S,{validation:"ip",code:G.invalid_string,message:f.message}),t.dirty()}else if(f.kind==="base64"){if(!QR.test(o.data))S=this._getOrReturnCtx(o,S),L(S,{validation:"base64",code:G.invalid_string,message:f.message}),t.dirty()}else Ao.assertNever(f);return{status:t.value,value:o.data}}_regex(o,n,t){return this.refinement((S)=>o.test(S),{validation:n,code:G.invalid_string,...q.errToObj(t)})}_addCheck(o){return new Dn({...this._def,checks:[...this._def.checks,o]})}email(o){return this._addCheck({kind:"email",...q.errToObj(o)})}url(o){return this._addCheck({kind:"url",...q.errToObj(o)})}emoji(o){return this._addCheck({kind:"emoji",...q.errToObj(o)})}uuid(o){return this._addCheck({kind:"uuid",...q.errToObj(o)})}nanoid(o){return this._addCheck({kind:"nanoid",...q.errToObj(o)})}cuid(o){return this._addCheck({kind:"cuid",...q.errToObj(o)})}cuid2(o){return this._addCheck({kind:"cuid2",...q.errToObj(o)})}ulid(o){return this._addCheck({kind:"ulid",...q.errToObj(o)})}base64(o){return this._addCheck({kind:"base64",...q.errToObj(o)})}ip(o){return this._addCheck({kind:"ip",...q.errToObj(o)})}datetime(o){var n,t;if(typeof o==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:o});return this._addCheck({kind:"datetime",precision:typeof(o===null||o===void 0?void 0:o.precision)==="undefined"?null:o===null||o===void 0?void 0:o.precision,offset:(n=o===null||o===void 0?void 0:o.offset)!==null&&n!==void 0?n:!1,local:(t=o===null||o===void 0?void 0:o.local)!==null&&t!==void 0?t:!1,...q.errToObj(o===null||o===void 0?void 0:o.message)})}date(o){return this._addCheck({kind:"date",message:o})}time(o){if(typeof o==="string")return this._addCheck({kind:"time",precision:null,message:o});return this._addCheck({kind:"time",precision:typeof(o===null||o===void 0?void 0:o.precision)==="undefined"?null:o===null||o===void 0?void 0:o.precision,...q.errToObj(o===null||o===void 0?void 0:o.message)})}duration(o){return this._addCheck({kind:"duration",...q.errToObj(o)})}regex(o,n){return this._addCheck({kind:"regex",regex:o,...q.errToObj(n)})}includes(o,n){return this._addCheck({kind:"includes",value:o,position:n===null||n===void 0?void 0:n.position,...q.errToObj(n===null||n===void 0?void 0:n.message)})}startsWith(o,n){return this._addCheck({kind:"startsWith",value:o,...q.errToObj(n)})}endsWith(o,n){return this._addCheck({kind:"endsWith",value:o,...q.errToObj(n)})}min(o,n){return this._addCheck({kind:"min",value:o,...q.errToObj(n)})}max(o,n){return this._addCheck({kind:"max",value:o,...q.errToObj(n)})}length(o,n){return this._addCheck({kind:"length",value:o,...q.errToObj(n)})}nonempty(o){return this.min(1,q.errToObj(o))}trim(){return new 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 isBase64(){return!!this._def.checks.find((o)=>o.kind==="base64")}get minLength(){let o=null;for(let n of this._def.checks)if(n.kind==="min"){if(o===null||n.value>o)o=n.value}return o}get maxLength(){let o=null;for(let n of this._def.checks)if(n.kind==="max"){if(o===null||n.value<o)o=n.value}return o}}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)})};class Tt 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)!==c.number){const f=this._getOrReturnCtx(o);return L(f,{code:G.invalid_type,expected:c.number,received:f.parsedType}),d}let t=void 0;const S=new lo;for(let f of this._def.checks)if(f.kind==="int"){if(!Ao.isInteger(o.data))t=this._getOrReturnCtx(o,t),L(t,{code:G.invalid_type,expected:"integer",received:"float",message:f.message}),S.dirty()}else if(f.kind==="min"){if(f.inclusive?o.data<f.value:o.data<=f.value)t=this._getOrReturnCtx(o,t),L(t,{code:G.too_small,minimum:f.value,type:"number",inclusive:f.inclusive,exact:!1,message:f.message}),S.dirty()}else if(f.kind==="max"){if(f.inclusive?o.data>f.value:o.data>=f.value)t=this._getOrReturnCtx(o,t),L(t,{code:G.too_big,maximum:f.value,type:"number",inclusive:f.inclusive,exact:!1,message:f.message}),S.dirty()}else if(f.kind==="multipleOf"){if(rR(o.data,f.value)!==0)t=this._getOrReturnCtx(o,t),L(t,{code:G.not_multiple_of,multipleOf:f.value,message:f.message}),S.dirty()}else if(f.kind==="finite"){if(!Number.isFinite(o.data))t=this._getOrReturnCtx(o,t),L(t,{code:G.not_finite,message:f.message}),S.dirty()}else Ao.assertNever(f);return{status:S.value,value:o.data}}gte(o,n){return this.setLimit("min",o,!0,q.toString(n))}gt(o,n){return this.setLimit("min",o,!1,q.toString(n))}lte(o,n){return this.setLimit("max",o,!0,q.toString(n))}lt(o,n){return this.setLimit("max",o,!1,q.toString(n))}setLimit(o,n,t,S){return new Tt({...this._def,checks:[...this._def.checks,{kind:o,value:n,inclusive:t,message:q.toString(S)}]})}_addCheck(o){return new Tt({...this._def,checks:[...this._def.checks,o]})}int(o){return this._addCheck({kind:"int",message:q.toString(o)})}positive(o){return this._addCheck({kind:"min",value:0,inclusive:!1,message:q.toString(o)})}negative(o){return this._addCheck({kind:"max",value:0,inclusive:!1,message:q.toString(o)})}nonpositive(o){return this._addCheck({kind:"max",value:0,inclusive:!0,message:q.toString(o)})}nonnegative(o){return this._addCheck({kind:"min",value:0,inclusive:!0,message:q.toString(o)})}multipleOf(o,n){return this._addCheck({kind:"multipleOf",value:o,message:q.toString(n)})}finite(o){return this._addCheck({kind:"finite",message:q.toString(o)})}safe(o){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:q.toString(o)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:q.toString(o)})}get minValue(){let o=null;for(let n of this._def.checks)if(n.kind==="min"){if(o===null||n.value>o)o=n.value}return o}get maxValue(){let o=null;for(let n of this._def.checks)if(n.kind==="max"){if(o===null||n.value<o)o=n.value}return o}get isInt(){return!!this._def.checks.find((o)=>o.kind==="int"||o.kind==="multipleOf"&&Ao.isInteger(o.value))}get isFinite(){let o=null,n=null;for(let t of this._def.checks)if(t.kind==="finite"||t.kind==="int"||t.kind==="multipleOf")return!0;else if(t.kind==="min"){if(n===null||t.value>n)n=t.value}else if(t.kind==="max"){if(o===null||t.value<o)o=t.value}return Number.isFinite(n)&&Number.isFinite(o)}}Tt.create=(o)=>{return new Tt({checks:[],typeName:e.ZodNumber,coerce:(o===null||o===void 0?void 0:o.coerce)||!1,...oo(o)})};class Mt extends no{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(o){if(this._def.coerce)o.data=BigInt(o.data);if(this._getType(o)!==c.bigint){const f=this._getOrReturnCtx(o);return L(f,{code:G.invalid_type,expected:c.bigint,received:f.parsedType}),d}let t=void 0;const S=new lo;for(let f of this._def.checks)if(f.kind==="min"){if(f.inclusive?o.data<f.value:o.data<=f.value)t=this._getOrReturnCtx(o,t),L(t,{code:G.too_small,type:"bigint",minimum:f.value,inclusive:f.inclusive,message:f.message}),S.dirty()}else if(f.kind==="max"){if(f.inclusive?o.data>f.value:o.data>=f.value)t=this._getOrReturnCtx(o,t),L(t,{code:G.too_big,type:"bigint",maximum:f.value,inclusive:f.inclusive,message:f.message}),S.dirty()}else if(f.kind==="multipleOf"){if(o.data%f.value!==BigInt(0))t=this._getOrReturnCtx(o,t),L(t,{code:G.not_multiple_of,multipleOf:f.value,message:f.message}),S.dirty()}else Ao.assertNever(f);return{status:S.value,value:o.data}}gte(o,n){return this.setLimit("min",o,!0,q.toString(n))}gt(o,n){return this.setLimit("min",o,!1,q.toString(n))}lte(o,n){return this.setLimit("max",o,!0,q.toString(n))}lt(o,n){return this.setLimit("max",o,!1,q.toString(n))}setLimit(o,n,t,S){return new Mt({...this._def,checks:[...this._def.checks,{kind:o,value:n,inclusive:t,message:q.toString(S)}]})}_addCheck(o){return new Mt({...this._def,checks:[...this._def.checks,o]})}positive(o){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:q.toString(o)})}negative(o){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:q.toString(o)})}nonpositive(o){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:q.toString(o)})}nonnegative(o){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:q.toString(o)})}multipleOf(o,n){return this._addCheck({kind:"multipleOf",value:o,message:q.toString(n)})}get minValue(){let o=null;for(let n of this._def.checks)if(n.kind==="min"){if(o===null||n.value>o)o=n.value}return o}get maxValue(){let o=null;for(let n of this._def.checks)if(n.kind==="max"){if(o===null||n.value<o)o=n.value}return o}}Mt.create=(o)=>{var n;return new Mt({checks:[],typeName:e.ZodBigInt,coerce:(n=o===null||o===void 0?void 0:o.coerce)!==null&&n!==void 0?n:!1,...oo(o)})};class ht extends no{_parse(o){if(this._def.coerce)o.data=Boolean(o.data);if(this._getType(o)!==c.boolean){const t=this._getOrReturnCtx(o);return L(t,{code:G.invalid_type,expected:c.boolean,received:t.parsedType}),d}return on(o.data)}}ht.create=(o)=>{return new ht({typeName:e.ZodBoolean,coerce:(o===null||o===void 0?void 0:o.coerce)||!1,...oo(o)})};class _t extends no{_parse(o){if(this._def.coerce)o.data=new Date(o.data);if(this._getType(o)!==c.date){const f=this._getOrReturnCtx(o);return L(f,{code:G.invalid_type,expected:c.date,received:f.parsedType}),d}if(isNaN(o.data.getTime())){const f=this._getOrReturnCtx(o);return L(f,{code:G.invalid_date}),d}const t=new lo;let S=void 0;for(let f of this._def.checks)if(f.kind==="min"){if(o.data.getTime()<f.value)S=this._getOrReturnCtx(o,S),L(S,{code:G.too_small,message:f.message,inclusive:!0,exact:!1,minimum:f.value,type:"date"}),t.dirty()}else if(f.kind==="max"){if(o.data.getTime()>f.value)S=this._getOrReturnCtx(o,S),L(S,{code:G.too_big,message:f.message,inclusive:!0,exact:!1,maximum:f.value,type:"date"}),t.dirty()}else Ao.assertNever(f);return{status:t.value,value:new Date(o.data.getTime())}}_addCheck(o){return new _t({...this._def,checks:[...this._def.checks,o]})}min(o,n){return this._addCheck({kind:"min",value:o.getTime(),message:q.toString(n)})}max(o,n){return this._addCheck({kind:"max",value:o.getTime(),message:q.toString(n)})}get minDate(){let o=null;for(let n of this._def.checks)if(n.kind==="min"){if(o===null||n.value>o)o=n.value}return o!=null?new Date(o):null}get maxDate(){let o=null;for(let n of this._def.checks)if(n.kind==="max"){if(o===null||n.value<o)o=n.value}return o!=null?new Date(o):null}}_t.create=(o)=>{return new _t({checks:[],coerce:(o===null||o===void 0?void 0:o.coerce)||!1,typeName:e.ZodDate,...oo(o)})};class IS extends no{_parse(o){if(this._getType(o)!==c.symbol){const t=this._getOrReturnCtx(o);return L(t,{code:G.invalid_type,expected:c.symbol,received:t.parsedType}),d}return on(o.data)}}IS.create=(o)=>{return new IS({typeName:e.ZodSymbol,...oo(o)})};class xt extends no{_parse(o){if(this._getType(o)!==c.undefined){const t=this._getOrReturnCtx(o);return L(t,{code:G.invalid_type,expected:c.undefined,received:t.parsedType}),d}return on(o.data)}}xt.create=(o)=>{return new xt({typeName:e.ZodUndefined,...oo(o)})};class it extends no{_parse(o){if(this._getType(o)!==c.null){const t=this._getOrReturnCtx(o);return L(t,{code:G.invalid_type,expected:c.null,received:t.parsedType}),d}return on(o.data)}}it.create=(o)=>{return new it({typeName:e.ZodNull,...oo(o)})};class wt extends no{constructor(){super(...arguments);this._any=!0}_parse(o){return on(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 on(o.data)}}ft.create=(o)=>{return new ft({typeName:e.ZodUnknown,...oo(o)})};class bn extends no{_parse(o){const n=this._getOrReturnCtx(o);return L(n,{code:G.invalid_type,expected:c.never,received:n.parsedType}),d}}bn.create=(o)=>{return new bn({typeName:e.ZodNever,...oo(o)})};class jS extends no{_parse(o){if(this._getType(o)!==c.undefined){const t=this._getOrReturnCtx(o);return L(t,{code:G.invalid_type,expected:c.void,received:t.parsedType}),d}return on(o.data)}}jS.create=(o)=>{return new jS({typeName:e.ZodVoid,...oo(o)})};class Un extends no{_parse(o){const{ctx:n,status:t}=this._processInputParams(o),S=this._def;if(n.parsedType!==c.array)return L(n,{code:G.invalid_type,expected:c.array,received:n.parsedType}),d;if(S.exactLength!==null){const T=n.data.length>S.exactLength.value,M=n.data.length<S.exactLength.value;if(T||M)L(n,{code:T?G.too_big:G.too_small,minimum:M?S.exactLength.value:void 0,maximum:T?S.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:S.exactLength.message}),t.dirty()}if(S.minLength!==null){if(n.data.length<S.minLength.value)L(n,{code:G.too_small,minimum:S.minLength.value,type:"array",inclusive:!0,exact:!1,message:S.minLength.message}),t.dirty()}if(S.maxLength!==null){if(n.data.length>S.maxLength.value)L(n,{code:G.too_big,maximum:S.maxLength.value,type:"array",inclusive:!0,exact:!1,message:S.maxLength.message}),t.dirty()}if(n.common.async)return Promise.all([...n.data].map((T,M)=>{return S.type._parseAsync(new rn(n,T,n.path,M))})).then((T)=>{return lo.mergeArray(t,T)});const f=[...n.data].map((T,M)=>{return S.type._parseSync(new rn(n,T,n.path,M))});return lo.mergeArray(t,f)}get element(){return this._def.type}min(o,n){return new Un({...this._def,minLength:{value:o,message:q.toString(n)}})}max(o,n){return new Un({...this._def,maxLength:{value:o,message:q.toString(n)}})}length(o,n){return new Un({...this._def,exactLength:{value:o,message:q.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)})};class Qo extends no{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const o=this._def.shape(),n=Ao.objectKeys(o);return this._cached={shape:o,keys:n}}_parse(o){if(this._getType(o)!==c.object){const k=this._getOrReturnCtx(o);return L(k,{code:G.invalid_type,expected:c.object,received:k.parsedType}),d}const{status:t,ctx:S}=this._processInputParams(o),{shape:f,keys:T}=this._getCached(),M=[];if(!(this._def.catchall instanceof bn&&this._def.unknownKeys==="strip")){for(let k in S.data)if(!T.includes(k))M.push(k)}const F=[];for(let k of T){const A=f[k],$=S.data[k];F.push({key:{status:"valid",value:k},value:A._parse(new rn(S,$,S.path,k)),alwaysSet:k in S.data})}if(this._def.catchall instanceof bn){const k=this._def.unknownKeys;if(k==="passthrough")for(let A of M)F.push({key:{status:"valid",value:A},value:{status:"valid",value:S.data[A]}});else if(k==="strict"){if(M.length>0)L(S,{code:G.unrecognized_keys,keys:M}),t.dirty()}else if(k==="strip");else throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const k=this._def.catchall;for(let A of M){const $=S.data[A];F.push({key:{status:"valid",value:A},value:k._parse(new rn(S,$,S.path,A)),alwaysSet:A in S.data})}}if(S.common.async)return Promise.resolve().then(async()=>{const k=[];for(let A of F){const $=await A.key,O=await A.value;k.push({key:$,value:O,alwaysSet:A.alwaysSet})}return k}).then((k)=>{return lo.mergeObjectSync(t,k)});else return lo.mergeObjectSync(t,F)}get shape(){return this._def.shape()}strict(o){return q.errToObj,new Qo({...this._def,unknownKeys:"strict",...o!==void 0?{errorMap:(n,t)=>{var S,f,T,M;const F=(T=(f=(S=this._def).errorMap)===null||f===void 0?void 0:f.call(S,n,t).message)!==null&&T!==void 0?T:t.defaultError;if(n.code==="unrecognized_keys")return{message:(M=q.errToObj(o).message)!==null&&M!==void 0?M:F};return{message:F}}}:{}})}strip(){return new Qo({...this._def,unknownKeys:"strip"})}passthrough(){return new Qo({...this._def,unknownKeys:"passthrough"})}extend(o){return new Qo({...this._def,shape:()=>({...this._def.shape(),...o})})}merge(o){return new Qo({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 Qo({...this._def,catchall:o})}pick(o){const n={};return Ao.objectKeys(o).forEach((t)=>{if(o[t]&&this.shape[t])n[t]=this.shape[t]}),new Qo({...this._def,shape:()=>n})}omit(o){const n={};return Ao.objectKeys(this.shape).forEach((t)=>{if(!o[t])n[t]=this.shape[t]}),new Qo({...this._def,shape:()=>n})}deepPartial(){return ct(this)}partial(o){const n={};return Ao.objectKeys(this.shape).forEach((t)=>{const S=this.shape[t];if(o&&!o[t])n[t]=S;else n[t]=S.optional()}),new Qo({...this._def,shape:()=>n})}required(o){const n={};return Ao.objectKeys(this.shape).forEach((t)=>{if(o&&!o[t])n[t]=this.shape[t];else{let f=this.shape[t];while(f instanceof Vn)f=f._def.innerType;n[t]=f}}),new Qo({...this._def,shape:()=>n})}keyof(){return a$(Ao.objectKeys(this.shape))}}Qo.create=(o,n)=>{return new Qo({shape:()=>o,unknownKeys:"strip",catchall:bn.create(),typeName:e.ZodObject,...oo(n)})};Qo.strictCreate=(o,n)=>{return new Qo({shape:()=>o,unknownKeys:"strict",catchall:bn.create(),typeName:e.ZodObject,...oo(n)})};Qo.lazycreate=(o,n)=>{return new Qo({shape:o,unknownKeys:"strip",catchall:bn.create(),typeName:e.ZodObject,...oo(n)})};class vt extends no{_parse(o){const{ctx:n}=this._processInputParams(o),t=this._def.options;function S(f){for(let M of f)if(M.result.status==="valid")return M.result;for(let M of f)if(M.result.status==="dirty")return n.common.issues.push(...M.ctx.common.issues),M.result;const T=f.map((M)=>new yn(M.ctx.common.issues));return L(n,{code:G.invalid_union,unionErrors:T}),d}if(n.common.async)return Promise.all(t.map(async(f)=>{const T={...n,common:{...n.common,issues:[]},parent:null};return{result:await f._parseAsync({data:n.data,path:n.path,parent:T}),ctx:T}})).then(S);else{let f=void 0;const T=[];for(let F of t){const k={...n,common:{...n.common,issues:[]},parent:null},A=F._parseSync({data:n.data,path:n.path,parent:k});if(A.status==="valid")return A;else if(A.status==="dirty"&&!f)f={result:A,ctx:k};if(k.common.issues.length)T.push(k.common.issues)}if(f)return n.common.issues.push(...f.ctx.common.issues),f.result;const M=T.map((F)=>new yn(F));return L(n,{code:G.invalid_union,unionErrors:M}),d}}get options(){return this._def.options}}vt.create=(o,n)=>{return new vt({options:o,typeName:e.ZodUnion,...oo(n)})};var pn=(o)=>{if(o instanceof pt)return pn(o.schema);else if(o instanceof Kn)return pn(o.innerType());else if(o instanceof Zt)return[o.value];else if(o instanceof Ft)return o.options;else if(o instanceof Pt)return Ao.objectValues(o.enum);else if(o instanceof gt)return pn(o._def.innerType);else if(o instanceof xt)return[void 0];else if(o instanceof it)return[null];else if(o instanceof Vn)return[void 0,...pn(o.unwrap())];else if(o instanceof Zn)return[null,...pn(o.unwrap())];else if(o instanceof vf)return pn(o.unwrap());else if(o instanceof et)return pn(o.unwrap());else if(o instanceof lt)return pn(o._def.innerType);else return[]};class xf extends no{_parse(o){const{ctx:n}=this._processInputParams(o);if(n.parsedType!==c.object)return L(n,{code:G.invalid_type,expected:c.object,received:n.parsedType}),d;const t=this.discriminator,S=n.data[t],f=this.optionsMap.get(S);if(!f)return L(n,{code:G.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[t]}),d;if(n.common.async)return f._parseAsync({data:n.data,path:n.path,parent:n});else return f._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){const S=new Map;for(let f of n){const T=pn(f.shape[o]);if(!T.length)throw new Error(`A discriminator value for key \`${o}\` could not be extracted from all schema options`);for(let M of T){if(S.has(M))throw new Error(`Discriminator property ${String(o)} has duplicate value ${String(M)}`);S.set(M,f)}}return new xf({typeName:e.ZodDiscriminatedUnion,discriminator:o,options:n,optionsMap:S,...oo(t)})}}class qt extends no{_parse(o){const{status:n,ctx:t}=this._processInputParams(o),S=(f,T)=>{if(GM(f)||GM(T))return d;const M=mM(f.value,T.value);if(!M.valid)return L(t,{code:G.invalid_intersection_types}),d;if(HM(f)||HM(T))n.dirty();return{status:n.value,value:M.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(([f,T])=>S(f,T));else return S(this._def.left._parseSync({data:t.data,path:t.path,parent:t}),this._def.right._parseSync({data:t.data,path:t.path,parent:t}))}}qt.create=(o,n,t)=>{return new qt({left:o,right:n,typeName:e.ZodIntersection,...oo(t)})};class Nn extends no{_parse(o){const{status:n,ctx:t}=this._processInputParams(o);if(t.parsedType!==c.array)return L(t,{code:G.invalid_type,expected:c.array,received:t.parsedType}),d;if(t.data.length<this._def.items.length)return L(t,{code:G.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),d;if(!this._def.rest&&t.data.length>this._def.items.length)L(t,{code:G.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty();const f=[...t.data].map((T,M)=>{const F=this._def.items[M]||this._def.rest;if(!F)return null;return F._parse(new rn(t,T,t.path,M))}).filter((T)=>!!T);if(t.common.async)return Promise.all(f).then((T)=>{return lo.mergeArray(n,T)});else return lo.mergeArray(n,f)}get items(){return this._def.items}rest(o){return new Nn({...this._def,rest:o})}}Nn.create=(o,n)=>{if(!Array.isArray(o))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Nn({items:o,typeName:e.ZodTuple,rest:null,...oo(n)})};class cS extends no{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(o){const{status:n,ctx:t}=this._processInputParams(o);if(t.parsedType!==c.object)return L(t,{code:G.invalid_type,expected:c.object,received:t.parsedType}),d;const S=[],f=this._def.keyType,T=this._def.valueType;for(let M in t.data)S.push({key:f._parse(new rn(t,M,t.path,M)),value:T._parse(new rn(t,t.data[M],t.path,M)),alwaysSet:M in t.data});if(t.common.async)return lo.mergeObjectAsync(n,S);else return lo.mergeObjectSync(n,S)}get element(){return this._def.valueType}static create(o,n,t){if(n instanceof no)return new cS({keyType:o,valueType:n,typeName:e.ZodRecord,...oo(t)});return new cS({keyType:Dn.create(),valueType:o,typeName:e.ZodRecord,...oo(n)})}}class BS extends no{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(o){const{status:n,ctx:t}=this._processInputParams(o);if(t.parsedType!==c.map)return L(t,{code:G.invalid_type,expected:c.map,received:t.parsedType}),d;const S=this._def.keyType,f=this._def.valueType,T=[...t.data.entries()].map(([M,F],k)=>{return{key:S._parse(new rn(t,M,t.path,[k,"key"])),value:f._parse(new rn(t,F,t.path,[k,"value"]))}});if(t.common.async){const M=new Map;return Promise.resolve().then(async()=>{for(let F of T){const k=await F.key,A=await F.value;if(k.status==="aborted"||A.status==="aborted")return d;if(k.status==="dirty"||A.status==="dirty")n.dirty();M.set(k.value,A.value)}return{status:n.value,value:M}})}else{const M=new Map;for(let F of T){const{key:k,value:A}=F;if(k.status==="aborted"||A.status==="aborted")return d;if(k.status==="dirty"||A.status==="dirty")n.dirty();M.set(k.value,A.value)}return{status:n.value,value:M}}}}BS.create=(o,n,t)=>{return new BS({valueType:n,keyType:o,typeName:e.ZodMap,...oo(t)})};class Kt extends no{_parse(o){const{status:n,ctx:t}=this._processInputParams(o);if(t.parsedType!==c.set)return L(t,{code:G.invalid_type,expected:c.set,received:t.parsedType}),d;const S=this._def;if(S.minSize!==null){if(t.data.size<S.minSize.value)L(t,{code:G.too_small,minimum:S.minSize.value,type:"set",inclusive:!0,exact:!1,message:S.minSize.message}),n.dirty()}if(S.maxSize!==null){if(t.data.size>S.maxSize.value)L(t,{code:G.too_big,maximum:S.maxSize.value,type:"set",inclusive:!0,exact:!1,message:S.maxSize.message}),n.dirty()}const f=this._def.valueType;function T(F){const k=new Set;for(let A of F){if(A.status==="aborted")return d;if(A.status==="dirty")n.dirty();k.add(A.value)}return{status:n.value,value:k}}const M=[...t.data.values()].map((F,k)=>f._parse(new rn(t,F,t.path,k)));if(t.common.async)return Promise.all(M).then((F)=>T(F));else return T(M)}min(o,n){return new Kt({...this._def,minSize:{value:o,message:q.toString(n)}})}max(o,n){return new Kt({...this._def,maxSize:{value:o,message:q.toString(n)}})}size(o,n){return this.min(o,n).max(o,n)}nonempty(o){return this.min(1,o)}}Kt.create=(o,n)=>{return new Kt({valueType:o,minSize:null,maxSize:null,typeName:e.ZodSet,...oo(n)})};class bt extends no{constructor(){super(...arguments);this.validate=this.implement}_parse(o){const{ctx:n}=this._processInputParams(o);if(n.parsedType!==c.function)return L(n,{code:G.invalid_type,expected:c.function,received:n.parsedType}),d;function t(M,F){return Nf({data:M,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,bf(),Nt].filter((k)=>!!k),issueData:{code:G.invalid_arguments,argumentsError:F}})}function S(M,F){return Nf({data:M,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,bf(),Nt].filter((k)=>!!k),issueData:{code:G.invalid_return_type,returnTypeError:F}})}const f={errorMap:n.common.contextualErrorMap},T=n.data;if(this._def.returns instanceof Xt){const M=this;return on(async function(...F){const k=new yn([]),A=await M._def.args.parseAsync(F,f).catch((w)=>{throw k.addIssue(t(F,w)),k}),$=await Reflect.apply(T,this,A);return await M._def.returns._def.type.parseAsync($,f).catch((w)=>{throw k.addIssue(S($,w)),k})})}else{const M=this;return on(function(...F){const k=M._def.args.safeParse(F,f);if(!k.success)throw new yn([t(F,k.error)]);const A=Reflect.apply(T,this,k.data),$=M._def.returns.safeParse(A,f);if(!$.success)throw new yn([S(A,$.error)]);return $.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...o){return new bt({...this._def,args:Nn.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:Nn.create([]).rest(ft.create()),returns:n||ft.create(),typeName:e.ZodFunction,...oo(t)})}}class pt extends no{get schema(){return this._def.getter()}_parse(o){const{ctx:n}=this._processInputParams(o);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}pt.create=(o,n)=>{return new pt({getter:o,typeName:e.ZodLazy,...oo(n)})};class Zt extends no{_parse(o){if(o.data!==this._def.value){const n=this._getOrReturnCtx(o);return L(n,{received:n.data,code:G.invalid_literal,expected:this._def.value}),d}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)})};class Ft extends no{constructor(){super(...arguments);VS.set(this,void 0)}_parse(o){if(typeof o.data!=="string"){const n=this._getOrReturnCtx(o),t=this._def.values;return L(n,{expected:Ao.joinValues(t),received:n.parsedType,code:G.invalid_type}),d}if(!hf(this,VS,"f"))l$(this,VS,new Set(this._def.values),"f");if(!hf(this,VS,"f").has(o.data)){const n=this._getOrReturnCtx(o),t=this._def.values;return L(n,{received:n.data,code:G.invalid_enum_value,options:t}),d}return on(o.data)}get options(){return this._def.values}get enum(){const o={};for(let n of this._def.values)o[n]=n;return o}get Values(){const o={};for(let n of this._def.values)o[n]=n;return o}get Enum(){const o={};for(let n of this._def.values)o[n]=n;return o}extract(o,n=this._def){return Ft.create(o,{...this._def,...n})}exclude(o,n=this._def){return Ft.create(this.options.filter((t)=>!o.includes(t)),{...this._def,...n})}}VS=new WeakMap;Ft.create=a$;class Pt extends no{constructor(){super(...arguments);rS.set(this,void 0)}_parse(o){const n=Ao.getValidEnumValues(this._def.values),t=this._getOrReturnCtx(o);if(t.parsedType!==c.string&&t.parsedType!==c.number){const S=Ao.objectValues(n);return L(t,{expected:Ao.joinValues(S),received:t.parsedType,code:G.invalid_type}),d}if(!hf(this,rS,"f"))l$(this,rS,new Set(Ao.getValidEnumValues(this._def.values)),"f");if(!hf(this,rS,"f").has(o.data)){const S=Ao.objectValues(n);return L(t,{received:t.data,code:G.invalid_enum_value,options:S}),d}return on(o.data)}get enum(){return this._def.values}}rS=new WeakMap;Pt.create=(o,n)=>{return new Pt({values:o,typeName:e.ZodNativeEnum,...oo(n)})};class Xt extends no{unwrap(){return this._def.type}_parse(o){const{ctx:n}=this._processInputParams(o);if(n.parsedType!==c.promise&&n.common.async===!1)return L(n,{code:G.invalid_type,expected:c.promise,received:n.parsedType}),d;const t=n.parsedType===c.promise?n.data:Promise.resolve(n.data);return on(t.then((S)=>{return this._def.type.parseAsync(S,{path:n.path,errorMap:n.common.contextualErrorMap})}))}}Xt.create=(o,n)=>{return new Xt({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){const{status:n,ctx:t}=this._processInputParams(o),S=this._def.effect||null,f={addIssue:(T)=>{if(L(t,T),T.fatal)n.abort();else n.dirty()},get path(){return t.path}};if(f.addIssue=f.addIssue.bind(f),S.type==="preprocess"){const T=S.transform(t.data,f);if(t.common.async)return Promise.resolve(T).then(async(M)=>{if(n.value==="aborted")return d;const F=await this._def.schema._parseAsync({data:M,path:t.path,parent:t});if(F.status==="aborted")return d;if(F.status==="dirty")return Bt(F.value);if(n.value==="dirty")return Bt(F.value);return F});else{if(n.value==="aborted")return d;const M=this._def.schema._parseSync({data:T,path:t.path,parent:t});if(M.status==="aborted")return d;if(M.status==="dirty")return Bt(M.value);if(n.value==="dirty")return Bt(M.value);return M}}if(S.type==="refinement"){const T=(M)=>{const F=S.refinement(M,f);if(t.common.async)return Promise.resolve(F);if(F instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return M};if(t.common.async===!1){const M=this._def.schema._parseSync({data:t.data,path:t.path,parent:t});if(M.status==="aborted")return d;if(M.status==="dirty")n.dirty();return T(M.value),{status:n.value,value:M.value}}else return this._def.schema._parseAsync({data:t.data,path:t.path,parent:t}).then((M)=>{if(M.status==="aborted")return d;if(M.status==="dirty")n.dirty();return T(M.value).then(()=>{return{status:n.value,value:M.value}})})}if(S.type==="transform")if(t.common.async===!1){const T=this._def.schema._parseSync({data:t.data,path:t.path,parent:t});if(!CS(T))return T;const M=S.transform(T.value,f);if(M instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:M}}else return this._def.schema._parseAsync({data:t.data,path:t.path,parent:t}).then((T)=>{if(!CS(T))return T;return Promise.resolve(S.transform(T.value,f)).then((M)=>({status:n.value,value:M}))});Ao.assertNever(S)}}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)===c.undefined)return on(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 Zn extends no{_parse(o){if(this._getType(o)===c.null)return on(null);return this._def.innerType._parse(o)}unwrap(){return this._def.innerType}}Zn.create=(o,n)=>{return new Zn({innerType:o,typeName:e.ZodNullable,...oo(n)})};class gt extends no{_parse(o){const{ctx:n}=this._processInputParams(o);let t=n.data;if(n.parsedType===c.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){const{ctx:n}=this._processInputParams(o),t={...n,common:{...n.common,issues:[]}},S=this._def.innerType._parse({data:t.data,path:t.path,parent:{...t}});if(LS(S))return S.then((f)=>{return{status:"valid",value:f.status==="valid"?f.value:this._def.catchValue({get error(){return new yn(t.common.issues)},input:t.data})}});else return{status:"valid",value:S.status==="valid"?S.value:this._def.catchValue({get error(){return new yn(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 bS extends no{_parse(o){if(this._getType(o)!==c.nan){const t=this._getOrReturnCtx(o);return L(t,{code:G.invalid_type,expected:c.nan,received:t.parsedType}),d}return{status:"valid",value:o.data}}}bS.create=(o)=>{return new bS({typeName:e.ZodNaN,...oo(o)})};var CR=Symbol("zod_brand");class vf extends no{_parse(o){const{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 NS extends no{_parse(o){const{status:n,ctx:t}=this._processInputParams(o);if(t.common.async)return(async()=>{const f=await this._def.in._parseAsync({data:t.data,path:t.path,parent:t});if(f.status==="aborted")return d;if(f.status==="dirty")return n.dirty(),Bt(f.value);else return this._def.out._parseAsync({data:f.value,path:t.path,parent:t})})();else{const S=this._def.in._parseSync({data:t.data,path:t.path,parent:t});if(S.status==="aborted")return d;if(S.status==="dirty")return n.dirty(),{status:"dirty",value:S.value};else return this._def.out._parseSync({data:S.value,path:t.path,parent:t})}}static create(o,n){return new NS({in:o,out:n,typeName:e.ZodPipeline})}}class et extends no{_parse(o){const n=this._def.innerType._parse(o),t=(S)=>{if(CS(S))S.value=Object.freeze(S.value);return S};return LS(n)?n.then((S)=>t(S)):t(n)}unwrap(){return this._def.innerType}}et.create=(o,n)=>{return new et({innerType:o,typeName:e.ZodReadonly,...oo(n)})};var LR={object:Qo.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 IR=(o,n={message:`Input not instance of ${o.name}`})=>s$((t)=>t instanceof o,n),oJ=Dn.create,nJ=Tt.create,jR=bS.create,cR=Mt.create,tJ=ht.create,BR=_t.create,bR=IS.create,NR=xt.create,hR=it.create,xR=wt.create,iR=ft.create,vR=bn.create,qR=jS.create,pR=Un.create,hS=Qo.create,ZR=Qo.strictCreate,PR=vt.create,gR=xf.create,lR=qt.create,eR=Nn.create,dR=cS.create,uR=BS.create,aR=Kt.create,sR=bt.create,o0=pt.create,n0=Zt.create,t0=Ft.create,S0=Pt.create,f0=Xt.create,P$=Kn.create,T0=Vn.create,M0=Zn.create,F0=Kn.createWithPreprocess,k0=NS.create,A0=()=>oJ().optional(),$0=()=>nJ().optional(),J0=()=>tJ().optional(),y0={string:(o)=>Dn.create({...o,coerce:!0}),number:(o)=>Tt.create({...o,coerce:!0}),boolean:(o)=>ht.create({...o,coerce:!0}),bigint:(o)=>Mt.create({...o,coerce:!0}),date:(o)=>_t.create({...o,coerce:!0})},R0=d,Lo=Object.freeze({__proto__:null,defaultErrorMap:Nt,setErrorMap:OR,getErrorMap:bf,makeIssue:Nf,EMPTY_PATH:WR,addIssueToContext:L,ParseStatus:lo,INVALID:d,DIRTY:Bt,OK:on,isAborted:GM,isDirty:HM,isValid:CS,isAsync:LS,get util(){return Ao},get objectUtil(){return zM},ZodParsedType:c,getParsedType:St,ZodType:no,datetimeRegex:u$,ZodString:Dn,ZodNumber:Tt,ZodBigInt:Mt,ZodBoolean:ht,ZodDate:_t,ZodSymbol:IS,ZodUndefined:xt,ZodNull:it,ZodAny:wt,ZodUnknown:ft,ZodNever:bn,ZodVoid:jS,ZodArray:Un,ZodObject:Qo,ZodUnion:vt,ZodDiscriminatedUnion:xf,ZodIntersection:qt,ZodTuple:Nn,ZodRecord:cS,ZodMap:BS,ZodSet:Kt,ZodFunction:bt,ZodLazy:pt,ZodLiteral:Zt,ZodEnum:Ft,ZodNativeEnum:Pt,ZodPromise:Xt,ZodEffects:Kn,ZodTransformer:Kn,ZodOptional:Vn,ZodNullable:Zn,ZodDefault:gt,ZodCatch:lt,ZodNaN:bS,BRAND:CR,ZodBranded:vf,ZodPipeline:NS,ZodReadonly:et,custom:s$,Schema:no,ZodSchema:no,late:LR,get ZodFirstPartyTypeKind(){return e},coerce:y0,any:xR,array:pR,bigint:cR,boolean:tJ,date:BR,discriminatedUnion:gR,effect:P$,enum:t0,function:sR,instanceof:IR,intersection:lR,lazy:o0,literal:n0,map:uR,nan:jR,nativeEnum:S0,never:vR,null:hR,nullable:M0,number:nJ,object:hS,oboolean:J0,onumber:$0,optional:T0,ostring:A0,pipeline:k0,preprocess:F0,promise:f0,record:dR,set:aR,strictObject:ZR,string:oJ,symbol:bR,transformer:P$,tuple:eR,undefined:NR,union:PR,unknown:iR,void:qR,NEVER:R0,ZodIssueCode:G,quotelessJson:RR,ZodError:yn});function SJ(o){const 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;const f=typeof o.client==="object"?o.client:{},T=typeof o.server==="object"?o.server:{},M=typeof o.shared==="object"?o.shared:{},F=hS(f),k=hS(T),A=hS(M),$=o.isServer??(typeof window==="undefined"||("Deno"in window)),O=F.merge(A),w=k.merge(A).merge(F),z=$?w.safeParse(n):O.safeParse(n),r=o.onValidationError??((K)=>{throw console.error("\u274C Invalid environment variables:",K.flatten().fieldErrors),new Error("Invalid environment variables")}),H=o.onInvalidAccess??((K)=>{throw new Error("\u274C Attempted to access a server-side environment variable on the client")});if(z.success===!1)return r(z.error);const D=(K)=>{if(!o.clientPrefix)return!0;return!K.startsWith(o.clientPrefix)&&!(K in A.shape)},I=(K)=>{return $||!D(K)},v=(K)=>{return K==="__esModule"||K==="$$typeof"},N=(o.extends??[]).reduce((K,Q)=>{return Object.assign(K,Q)},{}),P=Object.assign(z.data,N);return new Proxy(P,{get(K,Q){if(typeof Q!=="string")return;if(v(Q))return;if(!I(Q))return H(Q);return Reflect.get(K,Q)}})}var Pn=SJ({isServer:typeof window==="undefined",server:{POSTGRES_USER:Lo.string(),POSTGRES_PASSWORD:Lo.string(),POSTGRES_DATABASE:Lo.string(),POSTGRES_HOST:Lo.string(),POSTGRES_PORT:Lo.string().transform((o)=>Number.parseInt(o,10)),BACKEND_PORT:Lo.string().transform((o)=>Number.parseInt(o,10)),RUN_WORKERS_FROM_SOURCE:Lo.union([Lo.literal("true"),Lo.literal("false")]).optional().transform((o)=>o==="true"),FRONTEND_PORT:Lo.string().transform((o)=>Number.parseInt(o,10)),FRONTEND_ORIGINS:Lo.string().transform((o)=>Uo(o)).pipe(Lo.array(Lo.string()))},clientPrefix:"VITE_",client:{VITE_BACKEND_ORIGIN:Lo.string()},runtimeEnv:import.meta.env,emptyStringAsUndefined:!0});var O0=Tf("role",["admin","user"]),dt=ot("users",{id:$n().primaryKey().defaultRandom(),username:io({length:16}).notNull(),email:io({length:254}).notNull(),hash:io({length:64}).notNull(),salt:io({length:36}).notNull(),createdAt:mn({withTimezone:!0}).notNull().defaultNow(),createdIp:io({length:45}).notNull(),isActive:wS().notNull().default(!1),verifiedAt:mn({withTimezone:!0}),userRole:O0().default("user")},(o)=>({usersUsernameUnique:aT().on(o.username),usersEmailUnique:aT().on(o.email)}));var W0=["username","email","hash","userRole"],_0=Tf("trackedUserColumnName",W0),Z9=ot("userChanges",{id:$n().primaryKey().defaultRandom(),userId:$n().notNull().references(()=>dt.id),changedAt:mn({withTimezone:!0}).notNull().defaultNow(),changedIp:io({length:45}).notNull(),changedColumn:_0().notNull(),oldValue:io({length:255}),newValue:io({length:255})}),QM=ot("games",{id:$n("id").primaryKey().defaultRandom()}),fJ=ot("players",{userId:$n().notNull().references(()=>dt.id),gameId:$n().notNull().references(()=>QM.id),score:Rf().notNull()},(o)=>({pk:k$({columns:[o.userId,o.gameId]})})),P9=ot("loginHistory",{id:$n().primaryKey().defaultRandom(),userId:$n().references(()=>dt.id),loginTime:mn({withTimezone:!0}).notNull().defaultNow(),ipAddress:io({length:45}).notNull(),userAgent:io({length:1024}),successful:wS().notNull().default(!1)}),w0=Tf("twoFactorMethod",["email","phone"]),g9=ot("passwordResetAttempts",{id:$n().primaryKey().defaultRandom(),userId:$n().notNull().references(()=>dt.id),requestedIp:io({length:45}).notNull(),requestedAt:mn({withTimezone:!0}).notNull().defaultNow(),succeededIp:io({length:45}),succeededAt:mn({withTimezone:!0}),verificationMethod:w0().notNull()}),qf=ot("banishedIps",{ip:io({length:45}).primaryKey(),reason:io({length:2048}).notNull(),banishedAt:mn({withTimezone:!0}).notNull().defaultNow(),banishedUntil:mn({withTimezone:!0})});var __dirname="/home/runner/work/wayforge/wayforge/apps/tempest.games/src/database";class DM{options;sql;drizzle;observers=new Map;async setupTriggersAndNotifications(){await this.sql.file(K0.resolve(__dirname,"notify_update.sql"));const o=[Wn(dt),Wn(QM),Wn(fJ)];await this.sql`SELECT create_notify_triggers(${this.sql.array(o)})`,await this.sql.listen("table_update",(n)=>{const t=n.split(","),S=t[0],f=t[1],T=`${S}("${f}")`;if(this.observers.has(T))this.observers.get(T).next(T)})}constructor(o={host:Pn.POSTGRES_HOST,port:Pn.POSTGRES_PORT,user:Pn.POSTGRES_USER,password:Pn.POSTGRES_PASSWORD,database:Pn.POSTGRES_DATABASE}){this.options=o,this.sql=p$(o),this.drizzle=G$(this.sql)}observe(o,n){if(!this.observers.has(o))this.observers.set(o,new s);this.observers.get(o).subscribe("SINGLETON",n)}}var pf={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"},UM=iM(pf).map(([o])=>Lo.literal(Number(o))),X0=Lo.union([UM[0],UM[1],...UM]),TJ=Lo.tuple([X0,Lo.string()]);function rM(){Cn.logger.info("\uD83D\uDEEC frontend server exiting"),process.exit(0)}var Cn=new YT;Cn.logger.info(" ready");var VM=FJ(import.meta.dir,"..","app"),G0=new DM;z0({port:Pn.FRONTEND_PORT??3333,async fetch(o,n){try{const t=new Date,S=new URL(o.url),f=n.requestIP(o)?.address??"??";Cn.logger.info(t,f,o.method,S.pathname);const[T]=await G0.drizzle.select({banishedUntil:qf.banishedUntil}).from(qf).where(rt(qf.ip,f)).limit(1),M=T?.banishedUntil===null,F=T?.banishedUntil&&T.banishedUntil>t;if(M||F)throw Cn.logger.info(`\uD83D\uDE45 request from banned ip ${f}`),[403,f];if(S.pathname==="/")return new Response(Bun.file(FJ(VM,"index.html")));if(S.pathname==="/index.html")return Response.redirect("/");const k=Y0(VM,S.pathname),A=E0(k);if(!A.startsWith(VM))throw[403,"Access Denied"];if(!await MJ(A).exists())return Response.redirect("/");return new Response(MJ(A))}catch(t){const S=TJ.safeParse(t);if(S.success){const[f,T]=S.data,F=`${pf[f]}. ${T}`;return Cn.logger.info(`\u274C ${f}: ${F}`),new Response(F,{status:f})}if(t instanceof Error)Cn.logger.error(t.message);else{const f=Dt(t);Cn.logger.error("frontend server threw",f)}return new Response(pf[500],{status:500})}}});process.on("SIGINT",()=>{Cn.logger.info("\u2757 received SIGINT; exiting gracefully"),rM()});process.on("SIGTERM",()=>{Cn.logger.info("\u2757 received SIGTERM; exiting gracefully"),rM()});process.on("exit",()=>{Cn.logger.info("\u2757 received exit; exiting gracefully"),rM()});Cn.logger.info(`\uD83D\uDEEB frontend server running at http://localhost:${Pn.FRONTEND_PORT??3333}/`);
|