tempest.games 0.0.13 → 0.1.0
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 +12 -0
- package/app/assets/index-QvqOYuWe.js +48 -0
- package/app/index.html +1 -1
- package/bin/backend.bun.js +8 -8
- package/bin/backend.worker.game.bun.js +1 -1
- package/bin/frontend.bun.js +1 -1
- package/package.json +21 -12
- package/app/assets/index-TSjQta7U.js +0 -46
package/bin/frontend.bun.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
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
|
+
var Si=Object.create;var{getPrototypeOf:Ti,defineProperty:et,getOwnPropertyNames:ki}=Object;var bi=Object.prototype.hasOwnProperty;var Mi=(n,e,o)=>{o=n!=null?Si(Ti(n)):{};const t=e||!n||!n.__esModule?et(o,"default",{value:n,enumerable:!0}):o;for(let i of ki(n))if(!bi.call(t,i))et(t,i,{get:()=>n[i],enumerable:!0});return t};var ot=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var ti=ot((rR,Hr)=>{Hr.exports={name:"dotenv",version:"16.4.5",description:"Loads environment variables from .env file",main:"lib/main.js",types:"lib/main.d.ts",exports:{".":{types:"./lib/main.d.ts",require:"./lib/main.js",default:"./lib/main.js"},"./config":"./config.js","./config.js":"./config.js","./lib/env-options":"./lib/env-options.js","./lib/env-options.js":"./lib/env-options.js","./lib/cli-options":"./lib/cli-options.js","./lib/cli-options.js":"./lib/cli-options.js","./package.json":"./package.json"},scripts:{"dts-check":"tsc --project tests/types/tsconfig.json",lint:"standard","lint-readme":"standard-markdown",pretest:"npm run lint && npm run dts-check",test:"tap tests/*.js --100 -Rspec","test:coverage":"tap --coverage-report=lcov",prerelease:"npm test",release:"standard-version"},repository:{type:"git",url:"git://github.com/motdotla/dotenv.git"},funding:"https://dotenvx.com",keywords:["dotenv","env",".env","environment","variables","config","settings"],readmeFilename:"README.md",license:"BSD-2-Clause",devDependencies:{"@definitelytyped/dtslint":"^0.0.133","@types/node":"^18.11.3",decache:"^4.6.1",sinon:"^14.0.1",standard:"^17.0.0","standard-markdown":"^7.1.0","standard-version":"^9.5.0",tap:"^16.3.0",tar:"^6.1.11",typescript:"^4.8.4"},engines:{node:">=12"},browser:{fs:!1}}});var mi=ot((lR,jn)=>{function Er(n){const e={};let o=n.toString();o=o.replace(/\r\n?/mg,"\n");let t;while((t=Gr.exec(o))!=null){const i=t[1];let r=t[2]||"";r=r.trim();const l=r[0];if(r=r.replace(/^(['"`])([\s\S]*)\1$/mg,"$2"),l==='"')r=r.replace(/\\n/g,"\n"),r=r.replace(/\\r/g,"\r");e[i]=r}return e}function pr(n){const e=li(n),o=P.configDotenv({path:e});if(!o.parsed){const l=new Error(`MISSING_DATA: Cannot parse ${e} for an unknown reason`);throw l.code="MISSING_DATA",l}const t=ri(n).split(","),i=t.length;let r;for(let l=0;l<i;l++)try{const m=t[l].trim(),f=Ur(o,m);r=P.decrypt(f.ciphertext,f.key);break}catch(m){if(l+1>=i)throw m}return P.parse(r)}function Lr(n){console.log(`[dotenv@${Do}][INFO] ${n}`)}function Vr(n){console.log(`[dotenv@${Do}][WARN] ${n}`)}function yo(n){console.log(`[dotenv@${Do}][DEBUG] ${n}`)}function ri(n){if(n&&n.DOTENV_KEY&&n.DOTENV_KEY.length>0)return n.DOTENV_KEY;if(process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0)return process.env.DOTENV_KEY;return""}function Ur(n,e){let o;try{o=new URL(e)}catch(m){if(m.code==="ERR_INVALID_URL"){const f=new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");throw f.code="INVALID_DOTENV_KEY",f}throw m}const t=o.password;if(!t){const m=new Error("INVALID_DOTENV_KEY: Missing key part");throw m.code="INVALID_DOTENV_KEY",m}const i=o.searchParams.get("environment");if(!i){const m=new Error("INVALID_DOTENV_KEY: Missing environment part");throw m.code="INVALID_DOTENV_KEY",m}const r=`DOTENV_VAULT_${i.toUpperCase()}`,l=n.parsed[r];if(!l){const m=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${r} in your .env.vault file.`);throw m.code="NOT_FOUND_DOTENV_ENVIRONMENT",m}return{ciphertext:l,key:t}}function li(n){let e=null;if(n&&n.path&&n.path.length>0)if(Array.isArray(n.path)){for(let o of n.path)if(Uo.existsSync(o))e=o.endsWith(".vault")?o:`${o}.vault`}else e=n.path.endsWith(".vault")?n.path:`${n.path}.vault`;else e=ho.resolve(process.cwd(),".env.vault");if(Uo.existsSync(e))return e;return null}function ii(n){return n[0]==="~"?ho.join(qr.homedir(),n.slice(1)):n}function hr(n){Lr("Loading env from encrypted .env.vault");const e=P._parseVault(n);let o=process.env;if(n&&n.processEnv!=null)o=n.processEnv;return P.populate(o,e,n),{parsed:e}}function Dr(n){const e=ho.resolve(process.cwd(),".env");let o="utf8";const t=Boolean(n&&n.debug);if(n&&n.encoding)o=n.encoding;else if(t)yo("No encoding is specified. UTF-8 is used by default");let i=[e];if(n&&n.path)if(!Array.isArray(n.path))i=[ii(n.path)];else{i=[];for(let f of n.path)i.push(ii(f))}let r;const l={};for(let f of i)try{const y=P.parse(Uo.readFileSync(f,{encoding:o}));P.populate(l,y,n)}catch(y){if(t)yo(`Failed to load ${f} ${y.message}`);r=y}let m=process.env;if(n&&n.processEnv!=null)m=n.processEnv;if(P.populate(m,l,n),r)return{parsed:l,error:r};else return{parsed:l}}function Ir(n){if(ri(n).length===0)return P.configDotenv(n);const e=li(n);if(!e)return Vr(`You set DOTENV_KEY but you are missing a .env.vault file at ${e}. Did you forget to build it?`),P.configDotenv(n);return P._configVault(n)}function Nr(n,e){const o=Buffer.from(e.slice(-64),"hex");let t=Buffer.from(n,"base64");const i=t.subarray(0,12),r=t.subarray(-16);t=t.subarray(12,-16);try{const l=Qr.createDecipheriv("aes-256-gcm",o,i);return l.setAuthTag(r),`${l.update(t)}${l.final()}`}catch(l){const m=l instanceof RangeError,f=l.message==="Invalid key length",y=l.message==="Unsupported state or unable to authenticate data";if(m||f){const c=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw c.code="INVALID_DOTENV_KEY",c}else if(y){const c=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw c.code="DECRYPTION_FAILED",c}else throw l}}function vr(n,e,o={}){const t=Boolean(o&&o.debug),i=Boolean(o&&o.override);if(typeof e!=="object"){const r=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw r.code="OBJECT_REQUIRED",r}for(let r of Object.keys(e))if(Object.prototype.hasOwnProperty.call(n,r)){if(i===!0)n[r]=e[r];if(t)if(i===!0)yo(`"${r}" is already defined and WAS overwritten`);else yo(`"${r}" is already defined and was NOT overwritten`)}else n[r]=e[r]}var Uo=import.meta.require("fs"),ho=import.meta.require("path"),qr=import.meta.require("os"),Qr=import.meta.require("crypto"),Yr=ti(),Do=Yr.version,Gr=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg,P={configDotenv:Dr,_configVault:hr,_parseVault:pr,config:Ir,decrypt:Nr,parse:Er,populate:vr};lR.configDotenv=P.configDotenv;lR._configVault=P._configVault;lR._parseVault=P._parseVault;lR.config=P.config;lR.decrypt=P.decrypt;lR.parse=P.parse;lR.populate=P.populate;jn.exports=P});import{join as il,normalize as rl,resolve as ci}from"path";function Nn(n=Math.random){return n().toString(36).slice(2)}class Fe extends Promise{fate;resolve;reject;done=!1;constructor(n){let e,o;super((t,i)=>{e=t,o=i});this.resolve=e,this.reject=o,this.use(n instanceof Promise?n:new Promise(n))}pass(n,e){if(n===this.fate)this.resolve(e),this.done=!0}fail(n,e){if(n===this.fate)this.reject(e),this.done=!0}use(n){if(n instanceof Promise){const e=n;this.fate=e,e.then((o)=>{this.pass(e,o)},(o)=>{this.fail(e,o)})}else this.resolve(n),this.fate=void 0}}var tt=(n,e,o=X.STORE)=>{return Mn(o,{key:`${n.key}:JSON`,get:({get:t})=>e.toJson(t(n)),set:({set:t},i)=>{t(n,e.fromJson(i))}})};function S(n){while(n.child!==null)n=n.child;return n}function it(n){while(n.parent!==null)n=n.parent;return n}class W{Subscriber;subscribers=new Map;subscribe(n,e){return this.subscribers.set(n,e),()=>{this.unsubscribe(n)}}unsubscribe(n){this.subscribers.delete(n)}next(n){const e=this.subscribers.values();for(let o of e)o(n)}}class co extends W{state;constructor(n){super();this.state=n}next(n){this.state=n,super.next(n)}}function wn(n,e,o){const t={key:e.key,type:"atom_family"},i=n.families.get(e.key);if(i)n.logger.error("\u2757","atom_family",e.key,`Overwriting an existing ${Rn(i)} "${i.key}" in store "${n.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);const r=new W,m=Object.assign((f)=>{const y=J(f),c={key:e.key,subKey:y},T=`${e.key}(${y})`,F=S(n),u=e.default,G={key:T,default:u instanceof Function?u(f):u};if(e.effects)G.effects=e.effects(f);const Sn=ln(F,G,c);return r.next({type:"state_creation",token:Sn}),Sn},t,{subject:r,install:(f)=>wn(f,e),internalRoles:o});return n.families.set(e.key,m),n.defaults.set(e.key,e.default),t}function rt(n,e){if("mutable"in e)return ge(n,e);return wn(n,e)}function Wn(n,e,o){const t={key:e.key,type:"readonly_selector_family"},i=n.families.get(e.key);if(i)n.logger.error("\u2757","readonly_selector_family",e.key,`Overwriting an existing ${Rn(i)} "${i.key}" in store "${n.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);const r=new W,m=Object.assign((f)=>{const y=J(f),c={key:e.key,subKey:y},T=`${e.key}(${y})`,F=S(n),u=Je(F,{key:T,get:e.get(f)},c);return r.next({type:"state_creation",token:u}),u},t,{internalRoles:o,subject:r,install:(f)=>Wn(f,e),default:(f)=>{return e.get(f)({get:(...c)=>V(n,...c),find:(c,T)=>Y(n,c,T),seek:(c,T)=>L(n,c,T),json:(c)=>Z(n,c)})}});return n.families.set(e.key,m),t}function $e(n,e){if("set"in e)return Ke(n,e);return Wn(n,e)}function vn(n,e){const o=J(e),t=`${n.key}(${o})`,i=Ri[n.type],r={key:t,type:i};if(i==="molecule")Object.assign(r,{key:e,family:n});else Object.assign(r,{family:{key:n.key,subKey:o}});return Object.assign(r,{counterfeit:!0}),r}var Ri={atom_family:"atom",mutable_atom_family:"mutable_atom",selector_family:"selector",readonly_selector_family:"readonly_selector",molecule_family:"molecule"};function nn(n){const e={key:n.key,type:n.type};if("family"in n)e.family=n.family;return e}function Pn(n){return lt(X.STORE,n)}function Ln(n){return rt(X.STORE,n)}function ao(...n){if(n.length===2)return V(X.STORE,...n);return V(X.STORE,...n)}var So=(n)=>(e,o,t,i,...r)=>{console[n](`${e} ${o} "${t}" ${i}`,...r)},Ai={error:So("error"),info:So("info"),warn:So("warn")};class To{n;e;o;constructor(n,e,o=Ai){this.logLevel=n;this.filter=e;this.logger=o}error=(...n)=>{if((this.filter?.(...n)??!0)&&this.logLevel!==null)this.logger.error(...n)};info=(...n)=>{if((this.filter?.(...n)??!0)&&this.logLevel==="info")this.logger.info(...n)};warn=(...n)=>{if((this.filter?.(...n)??!0)&&this.logLevel!=="error"&&this.logLevel!==null)this.logger.warn(...n)}}function pe(n){return $e(X.STORE,n)}function we(n){return ko(n,X.STORE)}class yn{a;b;cardinality;relations=new Map;contents=new Map;isContent;makeContentKey=(n,e)=>`${n}:${e}`;warn;getRelatedKeys(n){return this.relations.get(n)}addRelation(n,e){let o=this.relations.get(n),t=this.relations.get(e);if(o)o.add(e);else o=new Set([e]),this.relations.set(n,o);if(t)t.add(n);else t=new Set([n]),this.relations.set(e,t)}deleteRelation(n,e){const o=this.relations.get(n);if(o){if(o.delete(e),o.size===0)this.relations.delete(n);const t=this.relations.get(e);if(t){if(t.delete(n),t.size===0)this.relations.delete(e)}}}replaceRelationsUnsafely(n,e){this.relations.set(n,new Set(e));for(let o of e){const t=new Set([n]);this.relations.set(o,t)}}replaceRelationsSafely(n,e){const o=this.relations.get(n);if(o)for(let t of o){const i=this.relations.get(t);if(i){if(i.size===1)this.relations.delete(t);else i.delete(n);this.contents.delete(this.makeContentKey(n,t))}}this.relations.set(n,new Set(e));for(let t of e){let i=this.relations.get(t);if(i)i.add(n);else i=new Set([n]),this.relations.set(t,i)}}getContentInternal(n){return this.contents.get(n)}setContent(n,e){this.contents.set(n,e)}deleteContent(n){this.contents.delete(n)}constructor(n,e){if(this.a=n.between[0],this.b=n.between[1],this.cardinality=n.cardinality,!e?.externalStore)this.relations=new Map(n.relations?.map(([o,t])=>[o,new Set(t)])),this.contents=new Map(n.contents);if(this.isContent=e?.isContent??null,e?.makeContentKey)this.makeContentKey=e.makeContentKey;if(e?.externalStore){const o=e.externalStore;if(this.has=(t,i)=>o.has(t,i),this.addRelation=(t,i)=>{o.addRelation(t,i)},this.deleteRelation=(t,i)=>{o.deleteRelation(t,i)},this.replaceRelationsSafely=(t,i)=>{o.replaceRelationsSafely(t,i)},this.replaceRelationsUnsafely=(t,i)=>{o.replaceRelationsUnsafely(t,i)},this.getRelatedKeys=(t)=>o.getRelatedKeys(t),o.getContent)this.getContentInternal=(t)=>{return o.getContent(t)},this.setContent=(t,i)=>{o.setContent(t,i)},this.deleteContent=(t)=>{o.deleteContent(t)};for(let[t,i]of n.relations??[])for(let r of i)this.addRelation(t,r);for(let[t,i]of n.contents??[])this.setContent(t,i)}if(e?.warn)this.warn=e.warn}toJSON(){return{between:[this.a,this.b],cardinality:this.cardinality,relations:[...this.relations.entries()].map(([n,e])=>[n,[...e]]),contents:[...this.contents.entries()]}}set(n,...e){const o=typeof e[0]==="string"?e[0]:n[this.b],t=e[1]??typeof e[0]==="string"?void 0:e[0];switch(n=typeof n==="string"?n:n[this.a],this.cardinality){case"1:1":{const i=this.getRelatedKey(n);if(i&&i!==o)this.delete(i,n)}case"1:n":{const i=this.getRelatedKey(o);if(i&&i!==n)this.delete(i,o)}}if(t){const i=this.makeContentKey(n,o);this.setContent(i,t)}return this.addRelation(n,o),this}delete(n,e){e=typeof e==="string"?e:n[this.b];const o=typeof n==="string"?n:n[this.a];if(o===void 0&&typeof e==="string"){const t=this.getRelatedKeys(e);if(t)for(let i of t)this.delete(i,e)}if(typeof o==="string"&&e===void 0){const t=this.getRelatedKeys(o);if(t)for(let i of t)this.delete(o,i)}if(typeof o==="string"&&typeof e==="string"){this.deleteRelation(o,e);const t=this.makeContentKey(o,e);this.deleteContent(t)}return this}getRelatedKey(n){const e=this.getRelatedKeys(n);if(e){if(e.size>1)this.warn?.(`${e.size} related keys were found for key "${n}": (${[...e].map((o)=>`"${o}"`).join(", ")}). Only one related key was expected.`);for(let o of e)return o}}replaceRelations(n,e,o){const t=!Array.isArray(e),i=t?Object.keys(e):e;if(o?.reckless)this.replaceRelationsUnsafely(n,i);else this.replaceRelationsSafely(n,i);if(t)for(let r of i){const l=this.makeContentKey(n,r),m=e[r];this.setContent(l,m)}return this}getContent(n,e){const o=this.makeContentKey(n,e);return this.getContentInternal(o)}getRelationEntries(n){const e=n[this.a],o=n[this.b];if(e!==void 0&&o===void 0){const t=this.getRelatedKeys(e);if(t)return[...t].map((i)=>{return[i,this.getContent(e,i)??null]})}if(e===void 0&&o!==void 0){const t=this.getRelatedKeys(o);if(t)return[...t].map((i)=>{return[i,this.getContent(i,o)??null]})}return[]}has(n,e){if(e)return this.getRelatedKeys(n)?.has(e)??!1;return this.relations.has(n)}}function d(n){return"epoch"in n.transactionMeta}function _(n){return"phase"in n.transactionMeta}var ft=(n)=>{const e=S(n);if(!_(e)){n.logger.warn("\uD83D\uDC1E","transaction","???","abortTransaction called outside of a transaction. This is probably a bug in AtomIO.");return}n.logger.info("\uD83E\uDE82","transaction",e.transactionMeta.update.key,"Aborting transaction"),e.parent.child=null};function Rn(n){return n.type.split("_").map(Fi).join(" ")}var Fi=(n)=>n[0].toUpperCase()+n.slice(1);class mn extends Error{constructor(...n){const e=n[0],o=n.length===2?n[1]:n[2];if(n.length===2)super(`${Rn(e)} ${J(e.key)} not found in store "${o.config.name}".`);else{const t=n[1];super(`${Rn(e)} "${e.key}" member ${J(t)} not found in store "${o.config.name}".`)}}}function Vn(n,e,o){return(...t)=>{const i=C(n,o);if(i)return i.run(t,e);throw new mn(n,o)}}var Le=(n)=>(e)=>n instanceof Function?n(e):n;var Xn=(n,e)=>{if(e.valueMap.has(n.key))return e.logger.info("\uD83D\uDCD6",n.type,n.key,"reading cached value"),yt(n,e);if(n.type==="selector"||n.type==="readonly_selector")return e.logger.info("\uD83E\uDDEE",n.type,n.key,"computing value"),n.get();const o=n.default instanceof Function?n.default():n.default;return e.logger.info("\uD83D\uDC81","atom",n.key,"could not find cached value; using default",o),n.default instanceof Function?n.default():n.default};var ct=(n,e)=>{if(n.operation.open){const o=performance.now();return n.logger.info("\u2757",e.type,e.key,`deferring setState at T-${o} until setState for "${n.operation.token.key}" is done`),o}n.operation={open:!0,done:new Set,prev:new Map,time:Date.now(),token:e},n.logger.info("\u2B55",e.type,e.key,`operation start in store "${n.config.name}"${!_(n)?"":` ${n.transactionMeta.phase} "${n.transactionMeta.update.key}"`}`)},at=(n)=>{if(n.operation.open)n.logger.info("\uD83D\uDD34",n.operation.token.type,n.operation.token.key,`operation done in store "${n.config.name}"`);n.operation={open:!1},n.on.operationClose.next(n.operation)},St=(n,e)=>{if(!n.operation.open)return n.logger.error("\uD83D\uDC1E","unknown",e,"isDone called outside of an operation. This is probably a bug in AtomIO."),!0;return n.operation.done.has(e)},dn=(n,e)=>{if(!n.operation.open){n.logger.error("\uD83D\uDC1E","unknown",e,"markDone called outside of an operation. This is probably a bug in AtomIO.");return}n.operation.done.add(e)};var Tt=(n,e,o)=>{switch(n.type){case"mutable_atom":o.logger.info("\uD83D\uDCE2",n.type,n.key,"is now (",e.newValue,") subscribers:",n.subject.subscribers);break;default:o.logger.info("\uD83D\uDCE2",n.type,n.key,"went (",e.oldValue,"->",e.newValue,") subscribers:",n.subject.subscribers)}n.subject.next(e)};var bo=(n,e)=>{const o=S(e),t=o.selectorAtoms.getRelatedKeys(n.key);if(o.logger.info("\uD83E\uDDF9",n.type,n.key,t?`evicting ${t.size} states downstream:`:"no downstream states",t??"to evict"),t){if(o.operation.open)o.logger.info("\uD83E\uDDF9",n.type,n.key,`[ ${[...o.operation.done].join(", ")} ] already done`);for(let i of t){if(St(o,i))continue;kt(i,o),dn(o,i)}}};function gi(n,e){if(Mt(e.newValue))return!1;if(n.includes("\uD83D\uDD0D"))return!1;return!0}var bt=(n,e,o)=>{const{key:t}=n,i=S(o);if(!_(i)||i.transactionMeta.phase!=="building"){o.logger.error("\uD83D\uDC1E","atom",t,"stowUpdate called outside of a transaction. This is probably a bug.");return}if(!gi(t,e))return;const l={type:"atom_update",key:t,...e};if(n.family)l.family=n.family;i.transactionMeta.update.updates.push(l),o.logger.info("\uD83D\uDCC1","atom",t,"stowed (",e.oldValue,"->",e.newValue,")")};var Rt=(n,e,o)=>{const t=Xn(n,o);let i=t;if(n.type==="mutable_atom"&&_(o)){const{parent:l}=o;i=Ce(n,l,o)}if(i=Le(e)(i),o.logger.info("\uD83D\uDCDD","atom",n.key,"set to",i),i=Tn(n.key,i,n.subject,o),At(n.key,o))Ft(n.key,o);dn(o,n.key),bo(n,o);const r={oldValue:t,newValue:i};if(d(o))Tt(n,r,o);else if(o.parent){if(o.on.transactionApplying.state===null)bt(n,r,o);else if(n.key.startsWith("*")){const l=n.key.slice(1),m=o.atoms.get(l);let f=o.valueMap.get(l);if(m.type==="mutable_atom"&&_(o)){const{parent:c}=o;f=Ce(m,c,o)}if(f.do(r.newValue)===null)bo(m,o)}}};var Ve=(n,e,o)=>{switch(n.type){case"atom":case"mutable_atom":Rt(n,e,o);break;case"selector":n.set(e);break}};function Ue(n,e){if(e.family){const o=n.families.get(e.family.key);if(o)return o}}function I(n,...e){let o,t,i,r;if(e.length===2){if(o=e[0],r=e[1],t=Ue(n,o)??null,t)i=o.family?D(o.family.subKey):null,o=Y(n,t,i)}else t=e[0],i=e[1],r=e[2],o=Y(n,t,i);if("counterfeit"in o){const f=n.disposalTraces.buffer.find((y)=>y?.key===o.key);n.logger.error("\u274C",o.type,o.key,`could not be set because it was not found in the store "${n.config.name}".`,f?`This state was previously disposed:\n${f.trace}`:"No previous disposal trace was found.");return}const l=ct(n,o);if(l){const f=n.on.operationClose.subscribe(`waiting to set "${o.key}" at T-${l}`,()=>{f(),n.logger.info("\uD83D\uDFE2",o.type,o.key,`resuming deferred setState from T-${l}`),I(n,o,r)});return}const m=C(o,n);Ve(m,r,n),at(n)}function he(n,e,o){const{key:t,newValue:i,oldValue:r}=e,l=n==="newValue"?i:r,m={key:t,type:"atom"};if(e.family)Object.assign(m,{family:e.family});I(o,m,l)}function Mo(n,e,o){const t=J(o);try{const i=[];let r;if(e==="root")i.push(n.molecules.get('"root"')),r="all";else if(e[0][0]===gt){r="any";const c=J(e),T=n.molecules.get(c);if(!T)throw new Error(`Molecule ${c} not found in store "${n.config.name}"`);i.push(T)}else if(o[0][0]===gt){r="all";for(let T of e){const F=J(T),u=n.molecules.get(F);if(!u)throw new Error(`Molecule ${F} not found in store "${n.config.name}"`);i.push(u)}}else{r="any";const T=J(e),F=n.molecules.get(T);if(!F)throw new Error(`Molecule ${T} not found in store "${n.config.name}"`);i.push(F)}const l=new Zn(i,o);l._dependsOn=r,n.molecules.set(t,l);for(let c of i)c.below.set(l.stringKey,l);const m={type:"molecule_creation",subType:"modern",key:l.key,provenance:e},f=S(n);if(_(f)&&f.transactionMeta.phase==="building")f.transactionMeta.update.updates.push(m);else f.on.moleculeCreationStart.next(m)}catch(i){if(i instanceof Error)n.logger.error("\u274C","molecule",t,"allocation failed:",i.message)}return o}function Oe(n,e){const o=J(e),t=n.molecules.get(o);if(!t)throw new Error(`Molecule ${o} not found in store "${n.config.name}"`);for(let y of t.joins.values())y.relations.delete(t.key),y.molecules.delete(t.stringKey);let i;if(t.above.size===1)i=t.above.values().next().value.key;else i=[...t.above.values()].map(({key:y})=>y);const r=[];for(let y of t.tokens.values()){const c=y.family;r.push([c.key,n.valueMap.get(y.key)])}for(let y of t.tokens.values())on(n,y);for(let y of t.below.values())if(y.dependsOn==="all")Oe(n,y.key);else if(y.above.delete(t.stringKey),y.above.size===0)Oe(n,y.key);t.below.clear();const l={type:"molecule_disposal",subType:"modern",key:t.key,values:r,provenance:i},m=S(n);if(_(m)&&m.transactionMeta.phase==="building")m.transactionMeta.update.updates.push(l);else m.on.moleculeDisposal.next(l);m.molecules.delete(t.stringKey);for(let y of t.above.values())y.below.delete(t.stringKey)}var hm=Symbol("provenance"),gt="T$";function Jt(n,e){const o=new W,t={type:"molecule_family",key:e.key,dependsOn:e.dependsOn??"all"},i={...t,subject:o,new:e.new};return n.moleculeFamilies.set(e.key,i),t}function An(n,e,o){const t=xn(o,e,n.key);n.tokens.set(t.key,t);const i=_(o)&&o.transactionMeta.phase==="building",r=o.moleculeInProgress===n.key;if(!i&&!r)n.subject.next({type:"state_creation",token:t});return t}class v extends Set{mode="record";subject=new W;cacheLimit=0;cache=[];cacheIdx=-1;cacheUpdateNumber=-1;constructor(n,e=0){super(n);if(n instanceof v)this.parent=n,this.cacheUpdateNumber=n.cacheUpdateNumber;if(e)this.cacheLimit=e,this.cache=new Array(e),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(n){const e=new v(n.members,n.cacheLimit);return e.cache=n.cache,e.cacheIdx=n.cacheIdx,e.cacheUpdateNumber=n.cacheUpdateNumber,e}add(n){const e=super.add(n);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`add:${J(n)}`);return e}clear(){const n=this.mode==="record"?[...this]:null;if(super.clear(),n)this.cacheUpdateNumber++,this.emit(`clear:${JSON.stringify(n)}`)}delete(n){const e=super.delete(n);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`del:${J(n)}`);return e}parent;child=null;transactionUpdates=null;transaction(n){this.mode="transaction",this.transactionUpdates=[],this.child=new v(this);const e=this.child._subscribe("transaction",(o)=>{this.transactionUpdates?.push(o)});try{if(n(this.child)){for(let t of this.transactionUpdates)this.doStep(t);this.cacheUpdateNumber++,this.emit(`tx:${this.transactionUpdates.join(";")}`)}}catch(o){throw console.error("Failed to apply transaction to SetRTX:",o),o}finally{e(),this.child=null,this.transactionUpdates=null,this.mode="record"}}_subscribe(n,e){return this.subject.subscribe(n,e)}subscribe(n,e){return this.subject.subscribe(n,(o)=>{e(`${this.cacheUpdateNumber}=${o}`)})}emit(n){this.subject.next(n)}doStep(n){const e=n.indexOf(":"),o=n.substring(0,e),t=n.substring(e+1);switch(o){case"add":this.add(JSON.parse(t));break;case"clear":this.clear();break;case"del":this.delete(JSON.parse(t));break;case"tx":for(let i of t.split(";"))this.doStep(i)}}getUpdateNumber(n){const e=n.indexOf("=");return Number(n.substring(0,e))}do(n){const e=n.indexOf("="),o=Number(n.substring(0,e)),t=o-this.cacheUpdateNumber;if(t>0){if(t===1){this.mode="playback";const r=n.substring(e+1);return this.doStep(r),this.mode="record",this.cacheUpdateNumber=o,null}return this.cacheUpdateNumber+1}if(Math.abs(t)<this.cacheLimit){const r=this.cacheIdx+t;if(this.cache[r]===n)return null;this.mode="playback";let m=!1;while(!m){this.cacheIdx%=this.cacheLimit;const y=this.cache[this.cacheIdx];if(this.cacheIdx--,!y)return"OUT_OF_RANGE";this.undo(y),m=this.cacheIdx===r-1}const f=n.substring(e+1);return this.doStep(f),this.mode="record",this.cacheUpdateNumber=o,null}return"OUT_OF_RANGE"}undoStep(n){const e=n.indexOf(":"),o=n.substring(0,e),t=n.substring(e+1);switch(o){case"add":this.delete(JSON.parse(t));break;case"del":this.add(JSON.parse(t));break;case"clear":{const i=JSON.parse(t);for(let r of i)this.add(r);break}case"tx":{const i=t.split(";");for(let r=i.length-1;r>=0;r--)this.undoStep(i[r])}}}undo(n){const e=n.indexOf("=");if(Number(n.substring(0,e))===this.cacheUpdateNumber){this.mode="playback";const t=n.substring(e+1);return this.undoStep(t),this.mode="record",this.cacheUpdateNumber--,null}return this.cacheUpdateNumber}}function U(n){return n[0].toUpperCase()+n.slice(1)}function De(n,e,o=X.STORE){return Ro(o).set(n.key,new Fo(n,e,o)),{key:n.key,type:"join",a:n.between[0],b:n.between[1],cardinality:n.cardinality}}function Ro(n){if("joins"in n&&n.joins instanceof Map)return n.joins;const e=new Map;return n.joins=e,e}function We(n,e){const o=Ro(e);let t=o.get(n.key);if(t===void 0){if(t=Ro(X.STORE).get(n.key)?.in(e),t===void 0)throw new Error(`Join "${n.key}" not found in store "${e.config.name}"`);o.set(n.key,t)}return t}function $t(n,e,o){const t=We(n,o);let i;switch(n.cardinality){case"1:1":{const r=`${n.a}KeyOf${U(n.b)}`,l=`${n.b}KeyOf${U(n.a)}`;i={get[r](){const f=t.states[r];return t.retrieve(f,e)},get[l](){const f=t.states[l];return t.retrieve(f,e)}};const m=`${n.a}EntryOf${U(n.b)}`;if(m in t.states){const f=`${n.b}EntryOf${U(n.a)}`;Object.assign(i,{get[m](){const y=t.states[m];return t.retrieve(y,e)},get[f](){const y=t.states[f];return t.retrieve(y,e)}})}break}case"1:n":{const r=`${n.a}KeyOf${U(n.b)}`,l=`${n.b}KeysOf${U(n.a)}`;i={get[r](){const f=t.states[r];return t.retrieve(f,e)},get[l](){const f=t.states[l];return t.retrieve(f,e)}};const m=`${n.a}EntryOf${U(n.b)}`;if(m in t.states){const f=`${n.b}EntriesOf${U(n.a)}`;Object.assign(i,{get[m](){const y=t.states[m];return t.retrieve(y,e)},get[f](){const y=t.states[f];return t.retrieve(y,e)}})}break}case"n:n":{const r=`${n.a}KeysOf${U(n.b)}`,l=`${n.b}KeysOf${U(n.a)}`;i={get[r](){const f=t.states[r];return t.retrieve(f,e)},get[l](){const f=t.states[l];return t.retrieve(f,e)}};const m=`${n.a}EntriesOf${U(n.b)}`;if(m in t.states){const f=`${n.b}EntriesOf${U(n.a)}`;Object.assign(i,{get[m](){const y=t.states[m];return t.retrieve(y,e)},get[f](){const y=t.states[f];return t.retrieve(y,e)}})}}}return i}function Kt(n,e){return $t(n,e,X.STORE)}function Ie(n,e,o){const t=We(n,o),i=S(o);if(_(i)){const{toolkit:r}=i.transactionMeta;t.transact(r,({relations:l})=>{e(l)})}else e(t.relations)}function Ji(n,e){return We(n,e).core.findRelatedKeysState}function wt(n){return Ji(n,X.STORE)}class Fo{options;defaultContent;toolkit;retrieve;molecules=new Map;relations;states;core;transact(n,e){const o=this.toolkit;this.toolkit=n,e(this),this.toolkit=o}store;alternates;[Symbol.dispose](){this.alternates.delete(this.store.config.name)}in(n){const e=n.config.name,o=this.alternates.get(e);if(o)return o;const t=new Fo(this.options,this.defaultContent,n);return this.alternates.set(e,t),t.alternates=this.alternates,t}constructor(n,e,o=X.STORE){this.store=o,this.options=n,this.defaultContent=e,this.alternates=new Map,this.alternates.set(o.config.name,this),this.store.miscResources.set(`join:${n.key}`,this),this.retrieve=(M,k)=>{const g=this.toolkit.seek(M,k);if(g)return g;const B=this.molecules.get(J(k));if(B){const j=C(M,o);return An(B,j,o)}if(o.config.lifespan==="immortal")throw new mn(M,k,o);return xn(o,M,k)},this.toolkit={get:(...M)=>V(o,...M),set:(...M)=>{I(o,...M)},find:this.retrieve,seek:(...M)=>L(o,...M),json:(M)=>Z(o,M),dispose:(...M)=>{on(o,...M)}};const t=n.between[0],i=n.between[1],r=ge(o,{key:`${n.key}/relatedKeys`,default:()=>new v,mutable:!0,fromJson:(M)=>v.fromJSON(M),toJson:(M)=>M.toJSON()},["join","relations"]);this.core={findRelatedKeysState:r};const l=({get:M},k)=>M(this.retrieve(r,k)),m=(M,k,g)=>{const{set:B}=M,j=this.retrieve(r,k),w=this.retrieve(r,g);B(j,(z)=>z.add(g)),B(w,(z)=>z.add(k))},f=(M,k,g)=>{const{set:B}=M,j=this.retrieve(r,k),w=this.retrieve(r,g);let z,Q;B(j,(N)=>{if(N.delete(g),N.size===0)z=`"${k}"`;return N}),B(w,(N)=>{if(N.delete(k),N.size===0)Q=`"${g}"`;return N})},y=(M,k,g)=>{const{get:B,set:j}=M,w=this.retrieve(r,k),z=B(w);for(let Q of z){if(g.includes(Q))continue;const zn=this.retrieve(r,Q);j(zn,(Kn)=>{return Kn.delete(k),Kn})}j(w,(Q)=>{return Q.transaction((N)=>{N.clear();for(let zn of g){const Kn=l(M,zn),Zo=Kn.has(k);if(this.relations.cardinality==="1:n"){const nt=[];for(let Re of Kn){if(Re===k)continue;const Ae=l(M,Re);if(Ae.delete(zn),Ae.size===0)nt.push(Re)}if(!Zo&&Kn.size>0)Kn.clear();for(let Re of nt){const Ae=[zn,Re].sort(),ai=`"${Ae[0]}:${Ae[1]}"`;this.molecules.delete(ai)}}if(!Zo)Kn.add(k);N.add(zn)}return!0}),Q})},c=(M,k,g)=>{const{set:B}=M,j=this.retrieve(r,k);B(j,(w)=>{return w.transaction((z)=>{for(let Q of g)z.add(Q);return!0}),w});for(let w of g){const z=this.retrieve(r,w);B(z,(Q)=>{return Q.add(k),Q})}return!0},T=(M,k,g)=>{const B=l(M,k);return g?B.has(g):B.size>0},F={getRelatedKeys:(M)=>l(this.toolkit,M),addRelation:(M,k)=>{m(this.toolkit,M,k)},deleteRelation:(M,k)=>{f(this.toolkit,M,k)},replaceRelationsSafely:(M,k)=>{y(this.toolkit,M,k)},replaceRelationsUnsafely:(M,k)=>{c(this.toolkit,M,k)},has:(M,k)=>T(this.toolkit,M,k)};let u,G,Sn;if(e){G=wn(o,{key:`${n.key}/content`,default:e},["join","content"]);const M={key:n.key,type:"join",a:n.between[0],b:n.between[1],cardinality:n.cardinality};Sn=Jt(o,{key:`${n.key}/content-molecules`,new:class w{Q;constructor(z,Q){this.key=Q}}});const k=({get:w},z)=>w(this.retrieve(G,z)),g=({set:w},z,Q)=>{w(this.retrieve(G,z),Q)},B=(w,z)=>{const Q=o.molecules.get(`"${z}"`);if(Q)this.toolkit.dispose(Q),this.molecules.delete(`"${z}"`)};u=Object.assign(F,{getContent:(w)=>{return k(this.toolkit,w)},setContent:(w,z)=>{g(this.toolkit,w,z)},deleteContent:(w)=>{B(this.toolkit,w)}})}else u=F;const O=new yn(n,{externalStore:u,makeContentKey:(...M)=>{const k=M.sort(),g=`${k[0]}:${k[1]}`,[B,j]=k.map((w)=>this.molecules.get(J(w)));if(o.config.lifespan==="immortal"&&B&&j){const w=S(o),z=sn(w,[B,j],Sn,g);this.molecules.set(`"${g}"`,C(z,w))}return g}}),E=()=>Wn(o,{key:`${n.key}/singleRelatedKey`,get:(M)=>({get:k})=>{const g=this.retrieve(r,M),B=k(g);for(let j of B)return j;return null}},["join","keys"]),p=()=>{return Wn(o,{key:`${n.key}/multipleRelatedKeys`,get:(M)=>({get:k})=>{const g=Ao(r,o),B=this.retrieve(g,M);return k(B).members}},["join","keys"])},q=()=>Wn(o,{key:`${n.key}/singleRelatedEntry`,get:(M)=>({get:k})=>{const g=this.retrieve(r,M),B=k(g);for(let j of B){const w=O.makeContentKey(M,j),z=this.retrieve(G,w),Q=k(z);return[j,Q]}return null}},["join","entries"]),fn=()=>Wn(o,{key:`${n.key}/multipleRelatedEntries`,get:(M)=>({get:k})=>{const g=Ao(r,o),B=this.retrieve(g,M);return k(B).members.map((w)=>{const z=O.makeContentKey(M,w),Q=this.retrieve(G,z),N=k(Q);return[w,N]})}},["join","entries"]);switch(n.cardinality){case"1:1":{const M=E(),k=`${t}KeyOf${U(i)}`,g=`${i}KeyOf${U(t)}`,B={[k]:M,[g]:M};let j;if(e){const w=q(),z=`${t}EntryOf${U(i)}`,Q=`${i}EntryOf${U(t)}`,N={[z]:w,[Q]:w};j=Object.assign(B,N)}else j=B;this.relations=O,this.states=j;break}case"1:n":{const M=E(),k=p(),g=`${t}KeyOf${U(i)}`,B=`${i}KeysOf${U(t)}`,j={[g]:M,[B]:k};let w;if(e){const z=q(),Q=fn(),N=`${t}EntryOf${U(i)}`,zn=`${i}EntriesOf${U(t)}`,Kn={[N]:z,[zn]:Q};w=Object.assign(j,Kn)}else w=j;this.relations=O,this.states=w;break}default:{const M=p(),k=`${t}KeysOf${U(i)}`,g=`${i}KeysOf${U(t)}`,B={[k]:M,[g]:M};let j;if(e){const w=fn(),z=`${t}EntriesOf${U(i)}`,Q=`${i}EntriesOf${U(t)}`,N={[z]:w,[Q]:w};j=Object.assign(B,N)}else j=B;this.relations=O,this.states=j}}}}function Ne(n){return{store:n}}function V(n,...e){let o,t,i;if(e.length===1){if(o=e[0],o.type!=="molecule"){if(t=Ue(n,o)??null,t)i=o.family?D(o.family.subKey):null,o=Y(n,t,i)}}else{t=e[0],i=e[1];let r;if(t.type==="molecule_family")r=L(n,t,i)??vn(t,i);else r=Y(n,t,i);o=r}if("counterfeit"in o&&"family"in o){t=o.type==="molecule"?C(o.family,n):n.families.get(o.family.key);const r=o.type==="molecule"?o.key:o.family.subKey,l=n.disposalTraces.buffer.find((m)=>m?.key===o.key);switch(n.logger.error("\u274C",o.type,o.key,`could not be retrieved because it was not found in the store "${n.config.name}".`,l?`This state was previously disposed:\n${l.trace}`:"No previous disposal trace was found."),t.type){case"atom_family":case"mutable_atom_family":return n.defaults.get(t.key);case"selector_family":case"readonly_selector_family":{if(n.defaults.has(t.key))return n.defaults.get(o.family.key);const m=C(t,n).default(r);return n.defaults.set(t.key,m),m}case"molecule_family":throw new mn(t,r,n)}}switch(o.type){case"atom":case"mutable_atom":case"selector":case"readonly_selector":return Xn(C(o,n),n);case"molecule":return C(o,n).instance}}class Zn{e;type="molecule";stringKey;family;_dependsOn;get dependsOn(){if(this.family)return this.family.dependsOn;return this._dependsOn}subject=new W;tokens=new Map;above=new Map;below=new Map;joins=new Map;instance;constructor(n,e,o){this.key=e;if(this.stringKey=J(e),o)this.family=o,this._dependsOn=o.dependsOn;if(n)for(let t of n)this.above.set(t.stringKey,t)}}function Ct(n){return n[0].toUpperCase()+n.slice(1)}function sn(n,e,o,t,...i){const r=it(n),l=S(n),m=J(t);l.moleculeInProgress=m;const f=Array.isArray(e)?e:[e],y=f.map((O)=>{if(O instanceof Zn)return O;const E=J(O.key),p=n.molecules.get(E);if(!p)throw new Error(`Molecule ${E} not found in store "${n.config.name}"`);return p}),c=new Zn(y,t,o);l.molecules.set(m,c);for(let O of y)O.below.set(c.stringKey,c);const T={get:(...O)=>V(S(r),...O),set:(...O)=>{I(S(r),...O)},seek:(O,E)=>L(S(r),O,E),json:(O)=>Z(S(r),O),run:(O,E=Nn())=>Vn(O,E,S(n)),make:(O,E,p,...q)=>sn(S(r),O,E,p,...q),dispose:(O)=>{on(S(r),O)},env:()=>Ne(S(r)),bond:(O,E)=>{if(O.type==="join"){const{as:p}=E,q=We(O,r);q.molecules.set(m,c),c.joins.set(O.key,q);const fn=F.subject.subscribe(`join:${O.key}-${m}`,(w)=>{if(w.type==="molecule_disposal"){if(J(w.token.key)===m)fn(),q.molecules.delete(m)}});if(p===null)return;const M=O.a===p?O.b:O.a,k=Kt(O,t),g=k[`${M}KeysOf${Ct(p)}`],B=k[`${M}EntriesOf${Ct(p)}`];let j={relatedKeys:g};if(B)j=Object.assign(j,{relatedEntries:B});return j}return An(c,C(O,r),S(r))},claim:(O,E)=>{const{exclusive:p}=E,q=S(n).molecules.get(J(O.key));if(q)if(p){for(let fn of q.above.values())fn.below.delete(q.stringKey);q.above.clear(),q.above.set(c.stringKey,c),c.below.set(q.stringKey,q)}else q.above.set(c.stringKey,c),c.below.set(q.stringKey,q)},spawn:(O,E,...p)=>sn(S(n),[c],C(O,n),E,...p)},F=C(o,n),u=F.new;c.instance=new u(T,t,...i);const G={type:"molecule",key:t,family:o},Sn={type:"molecule_creation",subType:"classic",token:G,family:o,context:f,params:i};if(d(l))F.subject.next(Sn);else if(_(l)&&l.on.transactionApplying.state===null)l.transactionMeta.update.updates.push(Sn);return l.moleculeInProgress=null,G}function go(n,e,o){switch(e){case"newValue":{Ot(n,o);break}case"oldValue":{on(o,n.token);break}}}function Jo(n,e,o){switch(e){case"newValue":{on(o,n.token);break}case"oldValue":{Ot(n,o),o.valueMap.set(n.token.key,n.value);break}}}function Ot(n,e){const{family:o}=n.token;if(o){const t=e.families.get(o.key);if(t)Y(e,t,D(o.subKey))}}function $o(n,e,o){switch(e){case"newValue":switch(n.subType){case"classic":sn(o,n.context,n.family,n.token.key,...n.params);break;case"modern":Mo(o,n.provenance,n.key);break}break;case"oldValue":switch(n.subType){case"classic":on(o,n.token);break;case"modern":Oe(o,n.key);break}break}}function Ko(n,e,o){switch(e){case"newValue":switch(n.subType){case"classic":on(o,n.token);break;case"modern":Oe(o,n.key);break}break;case"oldValue":switch(n.subType){case"classic":{const t=sn(o,n.context,n.family,n.token.key);for(let[i,r]of n.values){const l=`${i}(${J(t.key)})`,m=C(t,o),f=m.tokens.has(l),y=o.families.get(i);if(y&&!f)An(m,y,o);o.valueMap.set(l,r)}}break;case"modern":{Mo(o,n.provenance,n.key);for(let[t,i]of n.values){const r=o.families.get(t);if(r){Y(o,r,n.key);const l=`${t}(${J(n.key)})`;o.valueMap.set(l,i)}}}}break}}function ve(n,e,o){const t=n==="newValue"?e.updates:[...e.updates].reverse();for(let i of t)switch(i.type){case"atom_update":case"selector_update":he(n,i,o);break;case"state_creation":go(i,n,o);break;case"state_disposal":Jo(i,n,o);break;case"molecule_creation":$o(i,n,o);break;case"molecule_disposal":Ko(i,n,o);break;case"transaction_update":ve(n,i,o);break}}function Wt(n,e,o){if(!d(o))return;const i=o.transactionMeta.actionContinuities.getRelatedKey(n);if(i!==void 0)o.transactionMeta.epoch.set(i,e)}var xt=(n,e)=>{const o=S(e),{parent:t}=o;if(t===null||!_(o)||o.transactionMeta?.phase!=="building"){e.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=n,t.child=null,t.on.transactionApplying.next(o.transactionMeta);const{updates:i}=o.transactionMeta.update;if(e.logger.info("\uD83D\uDEC4","transaction",o.transactionMeta.update.key,`Applying transaction with ${i.length} updates:`,i),ve("newValue",o.transactionMeta.update,t),d(t))Wt(o.transactionMeta.update.key,o.transactionMeta.update.epoch,t),C({key:o.transactionMeta.update.key,type:"transaction"},e)?.subject.next(o.transactionMeta.update),e.logger.info("\uD83D\uDEEC","transaction",o.transactionMeta.update.key,"Finished applying transaction.");else if(_(t))t.transactionMeta.update.updates.push(o.transactionMeta.update);t.on.transactionApplying.next(null)};class kn extends Map{n;deleted=new Set;constructor(n){super();this.source=n}get(n){if(super.has(n))return super.get(n);if(!this.deleted.has(n)&&this.source.has(n))return this.source.get(n);return}set(n,e){return this.deleted.delete(n),super.set(n,e)}hasOwn(n){return super.has(n)}has(n){return!this.deleted.has(n)&&(super.has(n)||this.source.has(n))}delete(n){return this.deleted.add(n),super.delete(n)}}var st=(n,e,o,t)=>{const i=S(o),r={parent:i,child:null,on:i.on,loggers:i.loggers,logger:i.logger,config:i.config,atoms:new kn(i.atoms),atomsThatAreDefault:new Set(i.atomsThatAreDefault),families:new kn(i.families),operation:{open:!1},readonlySelectors:new kn(i.readonlySelectors),timelines:new kn(i.timelines),timelineTopics:new yn(i.timelineTopics.toJSON()),trackers:new Map,transactions:new kn(i.transactions),selectorAtoms:new yn(i.selectorAtoms.toJSON()),selectorGraph:new yn(i.selectorGraph.toJSON(),{makeContentKey:(...y)=>y.sort().join(":")}),selectors:new kn(i.selectors),valueMap:new kn(i.valueMap),defaults:i.defaults,disposalTraces:o.disposalTraces.copy(),molecules:new kn(i.molecules),moleculeFamilies:new kn(i.moleculeFamilies),moleculeInProgress:i.moleculeInProgress,miscResources:new kn(i.miscResources)},l=Bt(n,o),m={phase:"building",update:{type:"transaction_update",key:n,id:t,epoch:l===void 0?Number.NaN:l+1,updates:[],params:e,output:void 0},toolkit:{get:(...y)=>V(f,...y),set:(...y)=>{I(f,...y)},run:(y,c=Nn())=>Vn(y,c,f),find:(y,c)=>Y(f,y,c),seek:(y,c)=>L(f,y,c),json:(y)=>Z(f,y),make:(y,c,T,...F)=>sn(f,y,c,T,...F),dispose:(...y)=>{on(f,...y)},env:()=>Ne(f)}},f=Object.assign(r,{transactionMeta:m});return i.child=f,o.logger.info("\uD83D\uDEEB","transaction",n,"Building transaction with params:",e),f};function ko(n,e){const o={key:n.key,type:"transaction",run:(r,l)=>{const m=st(n.key,r,e,l);try{const f=S(e),{toolkit:y}=m.transactionMeta,c=n.do(y,...r);return xt(c,f),c}catch(f){throw ft(t),e.logger.warn("\uD83D\uDCA5","transaction",n.key,"caught:",f),f}},install:(r)=>ko(n,r),subject:new W},t=S(e);t.transactions.set(o.key,o);const i=nn(o);return e.on.transactionCreation.next(i),i}function Bt(n,e){const o=d(e),t=o?e.transactionMeta.actionContinuities.getRelatedKey(n):void 0;return o&&t!==void 0?e.transactionMeta.epoch.get(t):void 0}class Pe{_buffer;_index=0;constructor(n){let e;if(typeof n==="number")e=n;else e=n.length;this._buffer=Array.from({length:e})}get buffer(){return this._buffer}get index(){return this._index}add(n){this._buffer[this._index]=n,this._index=(this._index+1)%this._buffer.length}copy(){const n=new Pe([...this._buffer]);return n._index=this._index,n}}class ut{parent=null;child=null;valueMap=new Map;defaults=new Map;atoms=new Map;selectors=new Map;readonlySelectors=new Map;atomsThatAreDefault=new Set;selectorAtoms=new yn({between:["selectorKey","atomKey"],cardinality:"n:n"});selectorGraph=new yn({between:["upstreamSelectorKey","downstreamSelectorKey"],cardinality:"n:n"},{makeContentKey:(...n)=>n.sort().join(":")});trackers=new Map;families=new Map;transactions=new Map;transactionMeta={epoch:new Map,actionContinuities:new yn({between:["continuity","action"],cardinality:"1:n"})};timelines=new Map;timelineTopics=new yn({between:["timelineKey","topicKey"],cardinality:"1:n"});disposalTraces=new Pe(100);molecules=new Map;moleculeFamilies=new Map;moleculeInProgress=null;miscResources=new Map;on={atomCreation:new W,atomDisposal:new W,selectorCreation:new W,selectorDisposal:new W,timelineCreation:new W,transactionCreation:new W,transactionApplying:new co(null),operationClose:new W,moleculeCreationStart:new W,moleculeCreationDone:new W,moleculeDisposal:new W};operation={open:!1};config={name:"IMPLICIT_STORE",lifespan:"ephemeral"};loggers=[new To("warn",(n,e,o)=>!o.includes("\uD83D\uDD0D"))];logger={error:(...n)=>{for(let e of this.loggers)e.error(...n)},info:(...n)=>{for(let e of this.loggers)e.info(...n)},warn:(...n)=>{for(let e of this.loggers)e.warn(...n)}};constructor(n,e=null){if(this.config={...e?.config,...n},e!==null){if(this.valueMap=new Map(e?.valueMap),this.operation={...e?.operation},d(e))this.transactionMeta={epoch:new Map(e?.transactionMeta.epoch),actionContinuities:new yn(e?.transactionMeta.actionContinuities.toJSON())};for(let[,t]of e.families){if(t.internalRoles?.includes("mutable")||t.internalRoles?.includes("join"))continue;t.install(this)}const o=new Set;for(let[,t]of e.atoms){if(o.has(t.key))continue;if(t.install(this),t.type==="mutable_atom"){const i=Z(e,t),r=Hn(t);o.add(i.key),o.add(r.key)}}for(let[,t]of e.readonlySelectors)t.install(this);for(let[,t]of e.selectors){if(o.has(t.key))continue;t.install(this)}for(let[,t]of e.transactions)t.install(this);for(let[,t]of e.timelines)t.install(this)}}}var X={get STORE(){if(!globalThis.ATOM_IO_IMPLICIT_STORE)globalThis.ATOM_IO_IMPLICIT_STORE=new ut({name:"IMPLICIT_STORE",lifespan:"ephemeral"});return globalThis.ATOM_IO_IMPLICIT_STORE}};function C(n,e){let o,t=e;while(t!==null){switch(n.type){case"atom":case"mutable_atom":o=t.atoms.get(n.key);break;case"selector":o=t.selectors.get(n.key);break;case"readonly_selector":o=t.readonlySelectors.get(n.key);break;case"atom_family":case"mutable_atom_family":case"selector_family":case"readonly_selector_family":o=t.families.get(n.key);break;case"timeline":o=t.timelines.get(n.key);break;case"transaction":o=t.transactions.get(n.key);break;case"molecule":o=t.molecules.get(J(n.key));break;case"molecule_family":o=t.moleculeFamilies.get(n.key);break}if(o)return o;t=t.child}throw new mn(n,e)}function de(n,e){let o;o=C(n,e);const{family:t}=n;for(let l of o.joins.values())l.relations.delete(o.key),l.molecules.delete(o.stringKey);const i=[];for(let l of o.above.values())i.push(nn(l));const r=[];for(let l of o.tokens.values()){const m=l.family;r.push([m.key,e.valueMap.get(l.key)])}if(t){const l=C(t,e),m={type:"molecule_disposal",subType:"classic",token:n,family:t,context:i,values:r};if(n.family)m.family=n.family;for(let y of o.tokens.values())on(e,y);for(let y of o.below.values())if(y.dependsOn==="all")de(y,e);else if(y.above.delete(o.stringKey),y.above.size===0)de(y,e);if(o.below.clear(),_(e)&&e.transactionMeta.phase==="building")e.transactionMeta.update.updates.push(m);else l.subject.next(m);e.molecules.delete(o.stringKey)}for(let l of o.above.values())l.below.delete(o.stringKey)}function xn(n,e,o){const t=n.families.get(e.key);if(t===void 0)throw new mn(e,n);const i=t(o),r=S(n);if(i.family&&r.moleculeInProgress===null){if(d(r))switch(i.type){case"atom":case"mutable_atom":n.on.atomCreation.next(i);break;case"selector":case"readonly_selector":n.on.selectorCreation.next(i);break}else if(_(r)&&r.on.transactionApplying.state===null)r.transactionMeta.update.updates.push({type:"state_creation",token:i})}return i}function L(n,e,o){const t=J(o),i=`${e.key}(${t})`,r=S(n);let l;switch(e.type){case"atom_family":case"mutable_atom_family":l=r.atoms.get(i);break;case"selector_family":l=r.selectors.get(i);break;case"readonly_selector_family":l=r.readonlySelectors.get(i);break;case"molecule_family":l=r.molecules.get(J(o))}if(l)return nn(l);return l}function Y(n,e,o){let t=L(n,e,o);if(t)return t;const i=n.molecules.get(J(o));if(i)return An(i,e,n);if(n.config.lifespan==="immortal"){const r=vn(e,o);return n.logger.error("\u274C",r.type,r.key,`was not found in store "${n.config.name}"; returned a counterfeit token.`),r}return t=xn(n,e,o),t}function on(n,...e){let o,t;if(e.length===1)o=e[0],t=o.key;else{const r=e[0],l=e[1];o=r.type==="molecule_family"?L(n,r,l)??vn(r,l):Y(n,r,l)}try{C(o,n)}catch(r){const l=n.disposalTraces.buffer.find((m)=>m?.key===o.key);n.logger.error("\u274C",o.type,o.key,`could not be disposed because it was not found in the store "${n.config.name}".`,l?`\n This state was most recently disposed\n${l.trace}`:"No previous disposal trace was found.");return}switch(o.type){case"atom":case"mutable_atom":wo(o,n);break;case"selector":case"readonly_selector":jt(o,n);break;case"molecule":de(o,n);break}const{stack:i}=new Error;if(i){const r=i?.split("\n")?.slice(3)?.join("\n");n.disposalTraces.add({key:o.key,trace:r})}}var Ze=(n,e)=>S(e).atoms.has(n),$i=(n,e)=>S(e).selectors.has(n),Ki=(n,e)=>S(e).readonlySelectors.has(n),_t=(n,e)=>Ze(n,e)||$i(n,e)||Ki(n,e);var no=(n,e)=>{return S(e).selectorGraph.getRelationEntries({downstreamSelectorKey:n}).filter(([t,{source:i}])=>i!==n).map(([t,{source:i}])=>i).filter((t)=>_t(t,e))};var Co=(n,e,o)=>{const t=[],i=no(n,o);while(i.length>0){const r=i.shift();if(e.has(r))continue;if(e.add(r),!Ze(r,o))i.push(...no(r,o));else if(!t.includes(r))t.push(r)}return t},zt=(n,e)=>{const o=n.key,t=no(o,e),i=new Set;return t.flatMap((r)=>Ze(r,e)?r:Co(r,i,e))};var Xt=(n,e,o,t)=>{const i=S(t);if(e.type==="atom"||e.type==="mutable_atom")i.selectorAtoms.set({selectorKey:n,atomKey:e.key}),t.logger.info("\uD83D\uDD0D","selector",n,`discovers root atom "${e.key}"`);else{const r=Co(e.key,o,t);t.logger.info("\uD83D\uDD0D","selector",n,`discovers root atoms: [ ${r.map((l)=>`"${l}"`).join(", ")} ]`);for(let l of r)i.selectorAtoms=i.selectorAtoms.set({selectorKey:n,atomKey:l})}o.add(e.key)};var eo=(n,e,o)=>({get:(...t)=>{const i=S(o);let r;if(t.length===2){const[f,y]=t;switch(f.type){case"molecule_family":return V(o,f,y);default:if(o.config.lifespan==="ephemeral")r=Y(o,f,y);else{const c=L(o,f,y);if(c)r=c;else throw new mn(f,y,o)}}}else[r]=t;if(r.type==="molecule")return V(o,r);const l=C(r,o),m=Xn(l,o);return o.logger.info("\uD83D\uDD0C","selector",n,`registers dependency ( "${r.key}" =`,m,")"),i.selectorGraph.set({upstreamSelectorKey:r.key,downstreamSelectorKey:n},{source:r.key}),Xt(n,r,e,o),m},set:(...t)=>{let i,r;if(t.length===2)i=t[0],r=t[1];else{const f=t[0],y=t[1];r=t[2];const c=o.config.lifespan==="ephemeral"?Y(o,f,y):L(o,f,y);if(!c)throw new mn(f,y,o);i=c}const l=S(o),m=C(i,l);Ve(m,r,l)},find:(t,i)=>Y(o,t,i),seek:(t,i)=>L(o,t,i),json:(t)=>Z(o,t)});var Je=(n,e,o)=>{const t=S(n),i=new W,r=new Set,{get:l,find:m,seek:f,json:y}=eo(e.key,r,t),c=()=>{const G=e.get({get:l,find:m,seek:f,json:y});return Tn(e.key,G,i,S(n)),r.clear(),G},T={...e,subject:i,install:(G)=>Je(G,e,o),get:c,type:"readonly_selector",...o&&{family:o}};t.readonlySelectors.set(e.key,T);const F=c();n.logger.info("\u2728",T.type,T.key,"=",F);const u={key:e.key,type:"readonly_selector"};if(o)u.family=o;return u};var xe=(n,e,o)=>{const t=S(n),i=new W,r=new Set,l=eo(e.key,r,t),{find:m,get:f,seek:y,json:c}=l,T={find:m,get:f,seek:y,json:c},F=(E=e.get,p=S(n))=>{const q=E(T);return Tn(e.key,q,i,p),r.clear(),q},G={...e,subject:i,install:(E)=>xe(E,e,o),get:F,set:(E)=>{const p=S(n),q=F(e.get,p),fn=Le(E)(q);if(n.logger.info("\uD83D\uDCDD","selector",e.key,"set (",q,"->",fn,")"),Tn(e.key,fn,i,p),dn(p,e.key),d(p))i.next({newValue:fn,oldValue:q});e.set(l,fn)},type:"selector",...o&&{family:o}};t.selectors.set(e.key,G);const Sn=F();n.logger.info("\u2728",G.type,G.key,"=",Sn);const O={key:e.key,type:"selector"};if(o)O.family=o;return O};function Mn(n,e){if("set"in e){const i=xe(n,e,void 0);return n.on.selectorCreation.next(i),i}const t=Je(n,e,void 0);return n.on.selectorCreation.next(t),t}function jt(n,e){const o=S(e),{key:t}=n,i=C(n,o);if(!i.family)e.logger.error("\u274C","selector",t,"Standalone selectors cannot be disposed.");else{const r=o.molecules.get(i.family.subKey);if(r)r.tokens.delete(t);switch(n.type){case"selector":o.selectors.delete(t),C({key:i.family.key,type:"selector_family"},e).subject.next({type:"state_disposal",token:n});break;case"readonly_selector":o.readonlySelectors.delete(t),C({key:i.family.key,type:"readonly_selector_family"},e).subject.next({type:"state_disposal",token:n});break}if(o.valueMap.delete(t),o.selectorAtoms.delete(t),o.selectorGraph.delete(t),e.logger.info("\uD83D\uDD25",n.type,t,"deleted"),_(o)&&o.transactionMeta.phase==="building")o.transactionMeta.update.updates.push({type:"state_disposal",token:n});else e.on.selectorDisposal.next(n)}}function Ke(n,e,o){const t={key:e.key,type:"selector_family"},i=n.families.get(e.key);if(i)n.logger.error("\u2757","selector_family",e.key,`Overwriting an existing ${Rn(i)} "${i.key}" in store "${n.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);const r=new W,m=Object.assign((f)=>{const y=J(f),c={key:e.key,subKey:y},T=`${e.key}(${y})`,F=S(n),u=xe(F,{key:T,get:e.get(f),set:e.set(f)},c);return r.next({type:"state_creation",token:u}),u},t,{internalRoles:o,subject:r,install:(f)=>Ke(f,e),default:(f)=>{return e.get(f)({get:(...c)=>V(n,...c),find:(c,T)=>Y(n,c,T),seek:(c,T)=>L(n,c,T),json:(c)=>Z(n,c)})}});return n.families.set(e.key,m),t}function Ht(n,e,o=X.STORE){const t=Ke(o,{key:`${n.key}:JSON`,get:(r)=>({seek:l,get:m})=>{const f=l(n,r);if(f)return e.toJson(m(f));const y=J(r),c=o.molecules.get(y);if(c){const F=An(c,n,o);return e.toJson(m(F))}if(o.config.lifespan==="immortal")throw new Error(`No molecule found for key "${y}"`);const T=xn(o,n,r);return e.toJson(m(T))},set:(r)=>({seek:l,set:m},f)=>{const y=l(n,r);if(y)m(y,e.fromJson(f));else{const c=J(r),T=o.molecules.get(c);if(T){const F=An(T,n,o);m(F,e.fromJson(f))}else{if(o.config.lifespan==="immortal")throw new Error(`No molecule found for key "${c}"`);m(xn(o,n,r),e.fromJson(f))}}}},["mutable","json"]);return C(n,o).subject.subscribe(`store=${o.config.name}::json-selector-family`,(r)=>{if(r.token.family)L(o,t,D(r.token.family.subKey))}),t}var D=(n)=>JSON.parse(n),J=(n)=>JSON.stringify(n),lS=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];var qt=(n,e)=>{const o=S(e);if(o.operation.open)return o.operation.prev.get(n.key);return o.valueMap.get(n.key)};var Wo=(n,e)=>{const o=S(e);return zt(n,e).map((i)=>{const r=o.atoms.get(i);if(r===void 0)throw new Error(`Atom "${i}", a dependency of selector "${n.key}", not found in store "${e.config.name}".`);return r.subject.subscribe(`${n.type}:${n.key}`,(l)=>{e.logger.info("\uD83D\uDCE2",n.type,n.key,"root",i,"went",l.oldValue,"->",l.newValue);const m=qt(n,o),f=Xn(n,o);e.logger.info("\u2728",n.type,n.key,"went",m,"->",f),n.subject.next({newValue:f,oldValue:m})})})};function cn(n,e,o,t){function i(T){if(t.operation.open){const F=t.on.operationClose.subscribe(`state subscription ${o}`,()=>{F(),e(T)})}else e(T)}const r=C(n,t);t.logger.info("\uD83D\uDC40",r.type,r.key,`Adding subscription "${o}"`);const l=r.type==="selector"||r.type==="readonly_selector";let m=null,f=i;if(l)m=Wo(r,t),f=(T)=>{if(m)m.length=0,m.push(...Wo(r,t));i(T)};const y=r.subject.subscribe(o,f);return()=>{if(t.logger.info("\uD83D\uDE48",r.type,r.key,`Removing subscription "${o}"`),y(),m)for(let T of m)T()}}var Oo=(n,e,o,t)=>{const i=C(n,t);t.logger.info("\uD83D\uDC40","timeline",n.key,`Adding subscription "${o}"`);const r=i.subject.subscribe(o,e);return()=>{t.logger.info("\uD83D\uDE48","timeline",n.key,`Removing subscription "${o}" from timeline`),r()}};class qn{Update;initializeState(n,e){const o=`*${n.key}`;e.atoms.delete(o),e.valueMap.delete(o);const t=n.family?{key:`*${n.family.key}`,subKey:n.family.subKey}:void 0,i=ln(e,{key:o,default:null},t);if(e.parent?.valueMap.has(o)){const r=e.parent.valueMap.get(o);e.valueMap.set(o,r)}return i}unsubscribeFromInnerValue;unsubscribeFromState;observeCore(n,e,o){const t=`tracker:${o.config.name}:${_(o)?o.transactionMeta.update.key:"main"}:${n.key}`,i=V(o,n);this.unsubscribeFromInnerValue=i.subscribe(t,(r)=>{I(o,e,r)}),this.unsubscribeFromState=cn(n,(r)=>{if(r.newValue!==r.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=r.newValue.subscribe(t,(l)=>{I(o,e,l)})},t,o)}updateCore(n,e,o){const t=`tracker:${o.config.name}:${_(o)?o.transactionMeta.update.key:"main"}:${n.key}`;cn(e,({newValue:i,oldValue:r})=>{const l=o.timelineTopics.getRelatedKey(e.key);if(l){if(o.timelines.get(l)?.timeTraveling){const y=Oo({key:l,type:"timeline"},(c)=>{y(),I(o,n,(T)=>{if(c==="redo"&&i)T.do(i);else if(c==="undo"&&r)T.undo(r);return T})},t,o);return}}const m=o.on.operationClose.subscribe(t,()=>{m();const f=V(o,n),y=i===null?-1:f.getUpdateNumber(i),c=y-f.cacheUpdateNumber;if(i&&c===1)I(o,n,(T)=>(T.do(i),T));else o.logger.info("\u274C","mutable_atom",n.key,`could not be updated. Expected update number ${f.cacheUpdateNumber+1}, but got ${y}`)})},t,o)}mutableState;latestUpdateState;dispose;constructor(n,e){this.mutableState=n;const o=S(e);this.latestUpdateState=this.initializeState(n,o),this.observeCore(n,this.latestUpdateState,o),this.updateCore(n,this.latestUpdateState,o),o.trackers.set(n.key,this),this.dispose=()=>{this.unsubscribeFromInnerValue(),this.unsubscribeFromState(),o.trackers.delete(n.key)}}}function se(n,e,o){n.logger.info("\uD83D\uDD28","atom",e.key,`creating in store "${n.config.name}"`);const t=S(n),i=t.atoms.get(e.key);if(i&&i.type==="mutable_atom")return n.logger.error("\u274C","atom",e.key,"Tried to create atom, but it already exists in the store."),nn(i);const r=new W,l={...e,type:"mutable_atom",install:(y)=>{return y.logger.info("\uD83D\uDEE0\uFE0F","atom",e.key,`installing in store "${y.config.name}"`),se(y,e,o)},subject:r};if(o)l.family=o;const m=e.default();t.atoms.set(l.key,l),oo(e.key,n),Tn(e.key,m,r,t);const f=nn(l);if(e.effects){let y=0;const c=[];for(let T of e.effects){const F=T({setSelf:(u)=>{I(n,f,u)},onSet:(u)=>cn(f,u,`effect[${y}]`,n)});if(F)c.push(F);++y}l.cleanup=()=>{for(let T of c)T()}}if(new qn(f,n),!o)tt(f,e,n);return f}class xo{Update;latestUpdateAtoms;mutableAtoms;constructor(n,e){const o=wn(e,{key:`*${n.key}`,default:null},["mutable","updates"]);this.latestUpdateAtoms=C(o,e),this.mutableAtoms=n,this.mutableAtoms.subject.subscribe(`store=${e.config.name}::tracker-atom-family`,(t)=>{if(t.token.family){const i=D(t.token.family.subKey);L(e,this.latestUpdateAtoms,i),new qn(t.token,e)}}),this.latestUpdateAtoms.subject.subscribe(`store=${e.config.name}::tracker-atom-family`,(t)=>{if(t.token.family){const i=D(t.token.family.subKey),r=L(e,this.mutableAtoms,i);if(r)new qn(r,e)}})}}function ge(n,e,o){const t={key:e.key,type:"mutable_atom_family"},i=n.families.get(e.key);if(i)n.logger.error("\u2757","mutable_atom_family",e.key,`Overwriting an existing ${Rn(i)} "${i.key}" in store "${n.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);const r=new W,m=Object.assign((f)=>{const y=J(f),c={key:e.key,subKey:y},T=`${e.key}(${y})`,F=S(n),u={key:T,default:()=>e.default(f),toJson:e.toJson,fromJson:e.fromJson,mutable:!0};if(e.effects)u.effects=e.effects(f);const G=se(F,u,c);return r.next({type:"state_creation",token:G}),G},t,{subject:r,install:(f)=>ge(f,e),toJson:e.toJson,fromJson:e.fromJson,internalRoles:o});return n.families.set(e.key,m),Ht(m,e,n),new xo(m,n),t}var Ao=(n,e)=>{const o=S(e),t=`${n.key}:JSON`;return o.families.get(t)};var Z=(n,e)=>{if(e.family){const t=S(n),r={key:`${e.family.key}:JSON`,type:"selector_family"},l=C(r,t),m=JSON.parse(e.family.subKey);return Y(n,l,m)}return{type:"selector",key:`${e.key}:JSON`}};var Hn=(n)=>{const o={type:"atom",key:`*${n.key}`};if(n.family)o.family={key:`*${n.family.key}`,subKey:n.family.subKey};return o};function Mt(n){return typeof n==="object"&&n!==null&&"do"in n&&"undo"in n&&"subscribe"in n}function Ce(n,e,o){const t=e.valueMap.get(n.key),i=o.valueMap.get(n.key);if(t===i){if(t===void 0)return typeof n.default==="function"?n.default():n.default;e.logger.info("\uD83D\uDCC3","atom",n.key,"copying");const r=n.toJson(t),l=n.fromJson(r);return o.valueMap.set(n.key,l),new qn(n,e),l}return i}function Tn(n,e,o,t){const i=t.valueMap.get(n);if(i instanceof Fe)i.use(e);if(e instanceof Promise){const r=new Fe(e);return t.valueMap.set(n,r),r.then((l)=>{Tn(n,l,o,t),o.next({newValue:l,oldValue:r})}).catch((l)=>{t.logger.error("\uD83D\uDCA5","state",n,"rejected:",l)}),r}return t.valueMap.set(n,e),e}var yt=(n,e)=>{let o=e.valueMap.get(n.key);if(n.type==="mutable_atom"&&_(e)){const{parent:t}=e;o=Ce(n,t,e)}return o},kt=(n,e)=>{const o=e.valueMap.get(n);if(o instanceof Fe){const t=o,i=e.selectors.get(n)??e.readonlySelectors.get(n);if(i)t.use(i.get());return}if(e.operation.open)e.operation.prev.set(n,o);e.valueMap.delete(n),e.logger.info("\uD83D\uDDD1","state",n,"evicted")};var At=(n,e)=>{return S(e).atomsThatAreDefault.has(n)},oo=(n,e)=>{const o=S(e);o.atomsThatAreDefault=new Set(o.atomsThatAreDefault).add(n)},Ft=(n,e)=>{const o=S(e);o.atomsThatAreDefault=new Set(S(e).atomsThatAreDefault),o.atomsThatAreDefault.delete(n)};function ln(n,e,o){n.logger.info("\uD83D\uDD28","atom",e.key,`creating in store "${n.config.name}"`);const t=S(n),i=t.atoms.get(e.key);if(i&&i.type==="atom")return n.logger.error("\u274C","atom",e.key,"Tried to create atom, but it already exists in the store."),nn(i);const r=new W,l={...e,type:"atom",install:(y)=>{return y.logger.info("\uD83D\uDEE0\uFE0F","atom",e.key,`installing in store "${y.config.name}"`),ln(y,e,o)},subject:r};if(o)l.family=o;let m=e.default;if(e.default instanceof Function)m=e.default();t.atoms.set(l.key,l),oo(e.key,n),Tn(e.key,m,r,t);const f=nn(l);if(e.effects){let y=0;const c=[];for(let T of e.effects){const F=T({setSelf:(u)=>{I(n,f,u)},onSet:(u)=>cn(f,u,`effect[${y}]`,n)});if(F)c.push(F);++y}l.cleanup=()=>{for(let T of c)T()}}return f}function lt(n,e){if("mutable"in e){const i=se(n,e,void 0);return n.on.atomCreation.next(i),i}const t=ln(n,e,void 0);return n.on.atomCreation.next(t),t}function wo(n,e){const o=S(e),{key:t}=n,i=C(n,o);if(!i.family)e.logger.error("\u274C","atom",t,"Standalone atoms cannot be disposed.");else{i.cleanup?.();const r=e.valueMap.get(i.key);C({key:i.family.key,type:"atom_family"},e).subject.next({type:"state_disposal",token:n,value:r});const m=o.molecules.get(i.family.subKey);if(m)m.tokens.delete(t);if(o.atoms.delete(t),o.valueMap.delete(t),o.selectorAtoms.delete(t),o.atomsThatAreDefault.delete(t),e.timelineTopics.delete(t),n.type==="mutable_atom"){const f=Hn(n);wo(f,e),e.trackers.delete(t)}if(e.logger.info("\uD83D\uDD25","atom",t,"deleted"),_(o)&&o.transactionMeta.phase==="building")o.transactionMeta.update.updates.push({type:"state_disposal",token:n});else e.on.atomDisposal.next(n)}}var so=(n)=>{const e=ln(n,{key:"\uD83D\uDD0D Atom Token Index (Internal)",default:()=>{const o=new Map;for(let[t,i]of n.atoms)if(!t.includes("\uD83D\uDD0D")){const r=nn(i);if(i.family){let l=o.get(i.family.key);if(!l||!("familyMembers"in l))l={key:i.family.key,familyMembers:new Map},o.set(i.family.key,l);l.familyMembers.set(i.family.subKey,r)}else o.set(t,r)}return o},effects:[({setSelf:o})=>{n.on.atomCreation.subscribe("introspection",(t)=>{if(t.key.includes("\uD83D\uDD0D"))return;o((i)=>{if(t.family){const{key:r,subKey:l}=t.family;let m=i.get(r);if(m===void 0||!("familyMembers"in m))m={key:r,familyMembers:new Map},i.set(r,m);m.familyMembers.set(l,t)}else i.set(t.key,t);return i})}),n.on.atomDisposal.subscribe("introspection",(t)=>{o((i)=>{if(t.family){const{key:r,subKey:l}=t.family,m=i.get(r);if(m&&"familyMembers"in m){if(m.familyMembers.delete(l),m.familyMembers.size===0)i.delete(r)}}else i.delete(t.key);return i})})}]},void 0);return Mn(n,{key:"\uD83D\uDD0D Atom Token Index",get:({get:o})=>o(e)})};var Bo=(n)=>{const e=ln(n,{key:"\uD83D\uDD0D Selector Token Index (Internal)",default:()=>{const o=new Map;for(let t of[n.readonlySelectors,n.selectors])for(let[i,r]of t)if(!i.includes("\uD83D\uDD0D")){const l=nn(r);if(r.family){let m=o.get(r.family.key);if(!m||!("familyMembers"in m))m={key:r.family.key,familyMembers:new Map},o.set(r.family.key,m);m.familyMembers.set(r.family.subKey,l)}else o.set(i,l)}return o},effects:[({setSelf:o})=>{n.on.selectorCreation.subscribe("introspection",(t)=>{if(t.key.includes("\uD83D\uDD0D"))return;o((i)=>{if(t.family){const{key:r,subKey:l}=t.family;let m=i.get(r);if(m===void 0||!("familyMembers"in m))m={key:r,familyMembers:new Map},i.set(r,m);m.familyMembers.set(l,t)}else i.set(t.key,t);return i})}),n.on.selectorDisposal.subscribe("introspection",(t)=>{o((i)=>{if(t.family){const{key:r,subKey:l}=t.family,m=i.get(r);if(m&&"familyMembers"in m){if(m.familyMembers.delete(l),m.familyMembers.size===0)i.delete(r)}}else i.delete(t.key);return i})})}]},void 0);return Mn(n,{key:"\uD83D\uDD0D Selector Token Index",get:({get:o})=>o(e)})};function jo(n){if(!n)return!1;return Object.getPrototypeOf(n)===Object.prototype}class to{supported;constructor(n){this.supported=n}refine(n){for(let[e,o]of Object.entries(this.supported))try{if(o(n)===!0&&o!==Boolean)return{type:e,data:n}}catch(t){try{if(n instanceof o)return{type:e,data:n}}catch(i){}}return null}}var uo=new to({number:(n)=>typeof n==="number",string:(n)=>typeof n==="string",boolean:(n)=>typeof n==="boolean",null:(n)=>n===null}),_o=new to({object:jo,array:(n)=>Array.isArray(n)}),Ci=new to({...uo.supported,..._o.supported}),ne=(n)=>{if(n===void 0)return"undefined";const e=Ci.refine(n);if(e)return e.type;return Object.getPrototypeOf(n).constructor.name};class Qt{n;auditorCreatedAt=performance.now();statesCreatedAt=new Map;atomIndex;selectorIndex;disposed=!1;unsubscribeFromAtomCreation;unsubscribeFromAtomDisposal;unsubscribeFromSelectorCreation;unsubscribeFromSelectorDisposal;constructor(n=X.STORE){this.store=n;this.atomIndex=so(this.store),this.selectorIndex=Bo(this.store),this.unsubscribeFromAtomCreation=this.store.on.atomCreation.subscribe(`auditor-${this.auditorCreatedAt}`,({key:e})=>{this.statesCreatedAt.set(e,performance.now()-this.auditorCreatedAt)}),this.unsubscribeFromAtomDisposal=this.store.on.atomDisposal.subscribe(`auditor-${this.auditorCreatedAt}`,({key:e})=>{this.statesCreatedAt.delete(e)}),this.unsubscribeFromSelectorCreation=this.store.on.selectorCreation.subscribe(`auditor-${this.auditorCreatedAt}`,({key:e})=>{this.statesCreatedAt.set(e,performance.now()-this.auditorCreatedAt)}),this.unsubscribeFromSelectorDisposal=this.store.on.selectorDisposal.subscribe(`auditor-${this.auditorCreatedAt}`,({key:e})=>{this.statesCreatedAt.delete(e)})}static DEFAULT_LIST_RESOURCES_PARAM={atomFamilies:!0,selectorFamilies:!0};listResources(n=Qt.DEFAULT_LIST_RESOURCES_PARAM){if(this.disposed)throw new Error("This Auditor has been disposed");const e=ao(this.atomIndex),o=ao(this.selectorIndex),t=[...e.values()].filter((m)=>("familyMembers"in m)),i=[...o.values()].filter((m)=>("familyMembers"in m)),r=performance.now(),l=[];if(n.atomFamilies)for(let m of t){const f=m.familyMembers.values();for(let y of f){const T=this.statesCreatedAt.get(y.key)??this.auditorCreatedAt,F=r-T;l.push([y,F])}}if(n.selectorFamilies)for(let m of i){const f=m.familyMembers.values();for(let y of f){const T=this.statesCreatedAt.get(y.key)??this.auditorCreatedAt,F=r-T;l.push([y,F])}}return l}[Symbol.dispose](){this.unsubscribeFromAtomCreation(),this.unsubscribeFromAtomDisposal(),this.unsubscribeFromSelectorCreation(),this.unsubscribeFromSelectorDisposal(),this.disposed=!0}}var zo=(n,e)=>{const o=(t,i)=>{const l=((f,y)=>{const c=e(f,y);if(c)return c;return null})(t,i);if(l?.jobComplete??l?.pathComplete)return l;const m=Array.isArray(i)?i.map((f,y)=>[y,f]):jo(i)?Object.entries(i):[];for(let[f,y]of m){const c=o([...t,f],y);if(c?.jobComplete)return c}return{}};o([],n)};function Oi(n,e){return{summary:`${n<e?"+":"-"}${Math.abs(n-e)} (${n} \u2192 ${e})`}}function Wi(n,e){return{summary:`${n.length<e.length?"+":"-"}${Math.abs(n.length-e.length)} ("${n}" \u2192 "${e}")`}}function xi(n,e){return{summary:`${n} \u2192 ${e}`}}function Yt(n,e,o){let t="";const i=[],r=[],l=[];return zo(n,(m,f)=>{let y;for(y of m){const c=e[y];if(c===void 0)r.push([y,JSON.stringify(f)]);else{const T=o(f,c);if(T.summary!=="No Change")l.push([y,T])}}}),zo(e,(m,f)=>{let y;for(y of m)if(n[y]===void 0)i.push([y,JSON.stringify(f)])}),t=`\uFF5E${l.length} \uFF0B${i.length} \uFF0D${r.length}`,{summary:t,added:i,removed:r,changed:l}}function si(n,e,o){return Yt(n,e,o)}class Gt{leafRefinery;treeRefinery;leafDiffers;treeDiffers;constructor(n,e,o){this.leafRefinery=n,this.treeRefinery=e,this.leafDiffers={},this.treeDiffers={};for(let t of Object.keys(n.supported)){const i=o[t];this.leafDiffers[t]=i}for(let t of Object.keys(e.supported)){const i=o[t];this.treeDiffers[t]=i}}diff(n,e){if(n===e)return{summary:"No Change"};const o=this.leafRefinery.refine(n)??this.treeRefinery.refine(n),t=this.leafRefinery.refine(e)??this.treeRefinery.refine(e);if(o!==null&&t!==null){if(o.type===t.type){if(o.type in this.leafDiffers)return this.leafDiffers[o.type](o.data,t.data);if(o.type in this.treeDiffers)return this.treeDiffers[o.type](o.data,t.data,(m,f)=>this.diff(m,f))}}const i=ne(n),r=ne(e);if(i===r)return{summary:`${i} \u2192 ${r}`};return{summary:`Type change: ${i} \u2192 ${r}`}}}var Rb=new Gt(uo,_o,{number:Oi,string:Wi,boolean:xi,null:()=>({summary:"No Change"}),object:Yt,array:si});class ee{n;listeners;globalListeners;handleEvent(n,...e){for(let t of this.globalListeners)t(n,...e);const o=this.listeners.get(n);if(o)for(let t of o)t(...e)}id="no_id_retrieved";constructor(n){this.emit=n;this.listeners=new Map,this.globalListeners=new Set}on(n,e){const o=this.listeners.get(n);if(o)o.add(e);else this.listeners.set(n,new Set([e]));return this}onAny(n){return this.globalListeners.add(n),this}off(n,e){const o=this.listeners.get(n);if(o)if(e)o.delete(e);else this.listeners.delete(n);return this}offAny(n){return this.globalListeners.delete(n),this}}class Xo extends ee{n;e;o;incompleteData="";unprocessedEvents=[];incompleteLog="";unprocessedLogs=[];id="#####";handleLog(n){if(Array.isArray(n)){const[e,...o]=n;switch(e){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(n,e,o=console){super((t,...i)=>{const r=JSON.stringify([t,...i])+"\x03",l=(m)=>{if(m.code==="EPIPE")console.error("EPIPE error during write",this.process.stdin);this.process.stdin.removeListener("error",l)};return this.process.stdin.once("error",l),this.process.stdin.write(r),this});this.process=n;this.key=e;this.logger=o;if(this.process=n,this.process.stdout.on("data",(t)=>{const i=t.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 l=D(this.incompleteData);this.handleEvent(...l);while(this.unprocessedEvents.length>0){const m=this.unprocessedEvents.shift();if(m){if(this.unprocessedEvents.length===0)this.incompleteData=m;l=D(m),this.handleEvent(...l)}}this.incompleteData=""}catch(l){console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.warn(this.incompleteData),console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.error(l)}}),this.process.stderr.on("data",(t)=>{const i=t.toString();this.unprocessedLogs.push(...i.split("\x03"));const r=this.unprocessedLogs.shift();this.incompleteLog+=r??"";try{let l=D(this.incompleteLog);this.handleLog(l);while(this.unprocessedLogs.length>0)if(this.incompleteLog=this.unprocessedLogs.shift()??"",this.incompleteLog)l=D(this.incompleteLog),this.handleLog(l)}catch(l){console.error("\u274C\u274C\u274C"),console.error(this.incompleteLog),console.error(l),console.error("\u274C\u274C\u274C\uFE0F")}}),n.pid)this.id=n.pid.toString()}}class Et extends ee{in;out;id="no_id_retrieved";disposalFunctions=[];constructor(n){super((...e)=>{return this.out.next(e),this});this.id=n,this.in=new W,this.out=new W,this.in.subscribe("socket",(e)=>{this.handleEvent(...e)})}dispose(){for(let n of this.disposalFunctions)n()}}class Ho extends ee{incompleteData="";unprocessedEvents=[];relays;relayServices;process;id="#####";log(...n){this.process.stderr.write(J(n.map((e)=>e instanceof v?`{ ${e.toJSON().members.join(" | ")} }`:e))+"\x03")}logger={info:(...n)=>{this.log("i",...n)},warn:(...n)=>{this.log("w",...n)},error:(...n)=>{this.log("e",...n)}};constructor(){super((n,...e)=>{const o=JSON.stringify([n,...e]);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",(n)=>{const e=n.toString();this.unprocessedEvents.push(...e.split("\x03"));const o=this.unprocessedEvents.shift();this.incompleteData+=o??"";try{const t=D(this.incompleteData);this.logger.info("\uD83C\uDFB0","received",t),this.handleEvent(...t);while(this.unprocessedEvents.length>0){const i=this.unprocessedEvents.shift();if(i){if(this.unprocessedEvents.length===0)this.incompleteData=i;const r=D(i);this.handleEvent(...r)}}this.incompleteData=""}catch(t){if(t instanceof Error)this.logger.error("\u2757",t.message,t.cause,t.stack)}}),this.on("exit",()=>{this.logger.info("\uD83D\uDD25",this.id,'received "exit"'),process.exit(0)}),process.on("exit",(n)=>{this.logger.info("\uD83D\uDD25",this.id,`exited with code ${n}`)}),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",(n)=>{this.logger.info("\uD83D\uDC64","user",n,"joined");const e=new Et(`user:${n}`);this.relays.set(n,e),this.logger.info("\uD83D\uDD17","attaching services:",`[${[...this.relayServices.keys()].join(", ")}]`);for(let o of this.relayServices){const t=o(e);if(t)e.disposalFunctions.push(t)}this.on(`user:${n}`,(...o)=>{e.in.next(o)}),e.out.subscribe("socket",(o)=>{this.emit(...o)})}),this.on("user-leaves",(n)=>{const e=this.relays.get(n);if(this.off(`relay:${n}`),e)e.dispose(),this.relays.delete(n)}),process.stdout.write("\u2728")}relay(n){this.logger.info("\uD83D\uDD17","running relay method"),this.relayServices.push(n)}}class pt extends Map{set(n,e){if(this.has(n))return console.warn("Tried to set a key that already exists in an InvariantMap",{key:n,value:e}),this;return super.set(n,e)}clear(){throw new Error("Cannot clear an InvariantMap")}}class qo{n;type="continuity";globals=[];actions=[];perspectives=[];constructor(n){this.key=n}static existing=new pt;static create(n,e){const o=new qo(n),{type:t,globals:i,actions:r,perspectives:l}=e(o),m={type:t,key:n,globals:i,actions:r,perspectives:l};return qo.existing.set(n,m),m}add(...n){switch(n[0].type){case"atom":case"mutable_atom":this.globals.push(...n);break;case"transaction":this.actions.push(...n);break;case"atom_family":{const[o,t]=n;this.perspectives.push({type:"realtime_perspective",resourceAtoms:o,viewAtoms:t})}break}return this}}var Ib=Pn({key:"usersInRoomIndex",mutable:!0,default:()=>new v,toJson:(n)=>n.toJSON(),fromJson:(n)=>v.fromJSON(n)}),Qo=Pn({key:"roomIndex",default:()=>new v,mutable:!0,toJson:(n)=>n.toJSON(),fromJson:(n)=>v.fromJSON(n)}),Bi={enteredAtEpoch:0},Be=De({key:"usersInRooms",between:["room","user"],cardinality:"1:n"},Bi),Nb=pe({key:"usersInMyRoomView",get:(n)=>({find:e})=>{const o=wt(Be);return[e(o,n)]}});import{spawn as ui}from"child_process";var Yo=Ln({key:"roomArguments",default:["echo",["Hello World!"]]}),Lt=pe({key:"room",get:(n)=>async({get:e,find:o})=>{const t=o(Yo,n),i=e(t),[r,l]=i,m=await new Promise((f)=>{const y=ui(r,l,{env:process.env}),c=(T)=>{if(T.toString()==="\u2728")y.stdout.off("data",c),f(y)};y.stdout.on("data",c)});return new Xo(m,n)}});var yM=we({key:"createRoom",do:({get:n,set:e,find:o},t,i,r)=>{const l=r?[i,r]:[i],m=o(Yo,t);e(m,l),e(Qo,(c)=>c.add(t));const f=o(Lt,t);return n(f)}}),cM=we({key:"joinRoom",do:(n,e,o,t)=>{const i={enteredAtEpoch:t};return Ie(Be,(r)=>{r.set({room:e,user:o},i)},n.env().store),i}}),aM=we({key:"leaveRoom",do:(n,e,o)=>{Ie(Be,(t)=>{t.delete({room:e,user:o})},n.env().store)}}),SM=we({key:"destroyRoom",do:(n,e)=>{Ie(Be,(o)=>{o.delete({room:e})},n.env().store),n.set(Qo,(o)=>(o.delete(e),o))}});var bM=Ln({key:"transactionRedactor",default:{occlude:(n)=>n}}),ji=Ln({key:"unacknowledgedUpdates",default:()=>[]});var _i=Ln({key:"sockets",default:null}),gM=Pn({key:"socketsIndex",mutable:!0,default:()=>new v,toJson:(n)=>n.toJSON(),fromJson:(n)=>v.fromJSON(n)}),JM=Pn({key:"usersIndex",mutable:!0,default:()=>new v,toJson:(n)=>n.toJSON(),fromJson:(n)=>v.fromJSON(n)}),zi=De({key:"usersOfSockets",between:["user","socket"],cardinality:"1:1"});var{file:yi,serve:ll}=globalThis.Bun;function Hi(n){ht=n}function io(){return ht}function b(n,e){const o=io(),t=ro({issueData:e,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,o,o===re?void 0:re].filter((i)=>!!i)});n.common.issues.push(t)}function lo(n,e,o,t){if(o==="a"&&!t)throw new TypeError("Private accessor was defined without a getter");if(typeof e==="function"?n!==e||!t:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return o==="m"?t:o==="a"?t.call(n):t?t.value:e.get(n)}function Dt(n,e,o,t,i){if(t==="m")throw new TypeError("Private method is not writable");if(t==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e==="function"?n!==e||!i:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t==="a"?i.call(n,o):i?i.value=o:e.set(n,o),o}function x(n){if(!n)return{};const{errorMap:e,invalid_type_error:o,required_error:t,description:i}=n;if(e&&(o||t))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(e)return{errorMap:e,description:i};return{errorMap:(l,m)=>{var f,y;const{message:c}=n;if(l.code==="invalid_enum_value")return{message:c!==null&&c!==void 0?c:m.defaultError};if(typeof m.data==="undefined")return{message:(f=c!==null&&c!==void 0?c:t)!==null&&f!==void 0?f:m.defaultError};if(l.code!=="invalid_type")return{message:m.defaultError};return{message:(y=c!==null&&c!==void 0?c:o)!==null&&y!==void 0?y:m.defaultError}},description:i}}function Nt(n){let e="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";if(n.precision)e=`${e}\\.\\d{${n.precision}}`;else if(n.precision==null)e=`${e}(\\.\\d+)?`;return e}function vi(n){return new RegExp(`^${Nt(n)}\$`)}function vt(n){let e=`${It}T${Nt(n)}`;const o=[];if(o.push(n.local?"Z?":"Z"),n.offset)o.push("([+-]\\d{2}:?\\d{2})");return e=`${e}(${o.join("|")})`,new RegExp(`^${e}\$`)}function Pi(n,e){if((e==="v4"||!e)&&hi.test(n))return!0;if((e==="v6"||!e)&&Di.test(n))return!0;return!1}function di(n,e){const o=(n.toString().split(".")[1]||"").length,t=(e.toString().split(".")[1]||"").length,i=o>t?o:t,r=parseInt(n.toFixed(i).replace(".","")),l=parseInt(e.toFixed(i).replace(".",""));return r%l/Math.pow(10,i)}function oe(n){if(n instanceof h){const e={};for(let o in n.shape){const t=n.shape[o];e[o]=Jn.create(oe(t))}return new h({...n._def,shape:()=>e})}else if(n instanceof gn)return new gn({...n._def,type:oe(n.element)});else if(n instanceof Jn)return Jn.create(oe(n.unwrap()));else if(n instanceof un)return un.create(oe(n.unwrap()));else if(n instanceof On)return On.create(n.items.map((e)=>oe(e)));else return n}function Vo(n,e){const o=Qn(n),t=Qn(e);if(n===e)return{valid:!0,data:n};else if(o===R.object&&t===R.object){const i=H.objectKeys(e),r=H.objectKeys(n).filter((m)=>i.indexOf(m)!==-1),l={...n,...e};for(let m of r){const f=Vo(n[m],e[m]);if(!f.valid)return{valid:!1};l[m]=f.data}return{valid:!0,data:l}}else if(o===R.array&&t===R.array){if(n.length!==e.length)return{valid:!1};const i=[];for(let r=0;r<n.length;r++){const l=n[r],m=e[r],f=Vo(l,m);if(!f.valid)return{valid:!1};i.push(f.data)}return{valid:!0,data:i}}else if(o===R.date&&t===R.date&&+n===+e)return{valid:!0,data:n};else return{valid:!1}}function Pt(n,e){return new pn({values:n,typeName:$.ZodEnum,...x(e)})}function dt(n,e={},o){if(n)return hn.create().superRefine((t,i)=>{var r,l;if(!n(t)){const m=typeof e==="function"?e(t):typeof e==="string"?{message:e}:e,f=(l=(r=m.fatal)!==null&&r!==void 0?r:o)!==null&&l!==void 0?l:!0,y=typeof m==="string"?{message:m}:m;i.addIssue({code:"custom",...y,fatal:f})}});return hn.create()}var H;(function(n){n.assertEqual=(i)=>i;function e(i){}n.assertIs=e;function o(i){throw new Error}n.assertNever=o,n.arrayToEnum=(i)=>{const r={};for(let l of i)r[l]=l;return r},n.getValidEnumValues=(i)=>{const r=n.objectKeys(i).filter((m)=>typeof i[i[m]]!=="number"),l={};for(let m of r)l[m]=i[m];return n.objectValues(l)},n.objectValues=(i)=>{return n.objectKeys(i).map(function(r){return i[r]})},n.objectKeys=typeof Object.keys==="function"?(i)=>Object.keys(i):(i)=>{const r=[];for(let l in i)if(Object.prototype.hasOwnProperty.call(i,l))r.push(l);return r},n.find=(i,r)=>{for(let l of i)if(r(l))return l;return},n.isInteger=typeof Number.isInteger==="function"?(i)=>Number.isInteger(i):(i)=>typeof i==="number"&&isFinite(i)&&Math.floor(i)===i;function t(i,r=" | "){return i.map((l)=>typeof l==="string"?`'${l}'`:l).join(r)}n.joinValues=t,n.jsonStringifyReplacer=(i,r)=>{if(typeof r==="bigint")return r.toString();return r}})(H||(H={}));var Eo;(function(n){n.mergeShapes=(e,o)=>{return{...e,...o}}})(Eo||(Eo={}));var R=H.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Qn=(n)=>{switch(typeof n){case"undefined":return R.undefined;case"string":return R.string;case"number":return isNaN(n)?R.nan:R.number;case"boolean":return R.boolean;case"function":return R.function;case"bigint":return R.bigint;case"symbol":return R.symbol;case"object":if(Array.isArray(n))return R.array;if(n===null)return R.null;if(n.then&&typeof n.then==="function"&&n.catch&&typeof n.catch==="function")return R.promise;if(typeof Map!=="undefined"&&n instanceof Map)return R.map;if(typeof Set!=="undefined"&&n instanceof Set)return R.set;if(typeof Date!=="undefined"&&n instanceof Date)return R.date;return R.object;default:return R.unknown}},a=H.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"]),Xi=(n)=>{return JSON.stringify(n,null,2).replace(/"([^"]+)":/g,"$1:")};class an extends Error{constructor(n){super();this.issues=[],this.addIssue=(o)=>{this.issues=[...this.issues,o]},this.addIssues=(o=[])=>{this.issues=[...this.issues,...o]};const e=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,e);else this.__proto__=e;this.name="ZodError",this.issues=n}get errors(){return this.issues}format(n){const e=n||function(i){return i.message},o={_errors:[]},t=(i)=>{for(let r of i.issues)if(r.code==="invalid_union")r.unionErrors.map(t);else if(r.code==="invalid_return_type")t(r.returnTypeError);else if(r.code==="invalid_arguments")t(r.argumentsError);else if(r.path.length===0)o._errors.push(e(r));else{let l=o,m=0;while(m<r.path.length){const f=r.path[m];if(m!==r.path.length-1)l[f]=l[f]||{_errors:[]};else l[f]=l[f]||{_errors:[]},l[f]._errors.push(e(r));l=l[f],m++}}};return t(this),o}static assert(n){if(!(n instanceof an))throw new Error(`Not a ZodError: ${n}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,H.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(n=(e)=>e.message){const e={},o=[];for(let t of this.issues)if(t.path.length>0)e[t.path[0]]=e[t.path[0]]||[],e[t.path[0]].push(n(t));else o.push(n(t));return{formErrors:o,fieldErrors:e}}get formErrors(){return this.flatten()}}an.create=(n)=>{return new an(n)};var re=(n,e)=>{let o;switch(n.code){case a.invalid_type:if(n.received===R.undefined)o="Required";else o=`Expected ${n.expected}, received ${n.received}`;break;case a.invalid_literal:o=`Invalid literal value, expected ${JSON.stringify(n.expected,H.jsonStringifyReplacer)}`;break;case a.unrecognized_keys:o=`Unrecognized key(s) in object: ${H.joinValues(n.keys,", ")}`;break;case a.invalid_union:o="Invalid input";break;case a.invalid_union_discriminator:o=`Invalid discriminator value. Expected ${H.joinValues(n.options)}`;break;case a.invalid_enum_value:o=`Invalid enum value. Expected ${H.joinValues(n.options)}, received '${n.received}'`;break;case a.invalid_arguments:o="Invalid function arguments";break;case a.invalid_return_type:o="Invalid function return type";break;case a.invalid_date:o="Invalid date";break;case a.invalid_string:if(typeof n.validation==="object")if("includes"in n.validation){if(o=`Invalid input: must include "${n.validation.includes}"`,typeof n.validation.position==="number")o=`${o} at one or more positions greater than or equal to ${n.validation.position}`}else if("startsWith"in n.validation)o=`Invalid input: must start with "${n.validation.startsWith}"`;else if("endsWith"in n.validation)o=`Invalid input: must end with "${n.validation.endsWith}"`;else H.assertNever(n.validation);else if(n.validation!=="regex")o=`Invalid ${n.validation}`;else o="Invalid";break;case a.too_small:if(n.type==="array")o=`Array must contain ${n.exact?"exactly":n.inclusive?"at least":"more than"} ${n.minimum} element(s)`;else if(n.type==="string")o=`String must contain ${n.exact?"exactly":n.inclusive?"at least":"over"} ${n.minimum} character(s)`;else if(n.type==="number")o=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`;else if(n.type==="date")o=`Date must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(n.minimum))}`;else o="Invalid input";break;case a.too_big:if(n.type==="array")o=`Array must contain ${n.exact?"exactly":n.inclusive?"at most":"less than"} ${n.maximum} element(s)`;else if(n.type==="string")o=`String must contain ${n.exact?"exactly":n.inclusive?"at most":"under"} ${n.maximum} character(s)`;else if(n.type==="number")o=`Number must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`;else if(n.type==="bigint")o=`BigInt must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`;else if(n.type==="date")o=`Date must be ${n.exact?"exactly":n.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(n.maximum))}`;else o="Invalid input";break;case a.custom:o="Invalid input";break;case a.invalid_intersection_types:o="Intersection results could not be merged";break;case a.not_multiple_of:o=`Number must be a multiple of ${n.multipleOf}`;break;case a.not_finite:o="Number must be finite";break;default:o=e.defaultError,H.assertNever(n)}return{message:o}},ht=re,ro=(n)=>{const{data:e,path:o,errorMaps:t,issueData:i}=n,r=[...o,...i.path||[]],l={...i,path:r};if(i.message!==void 0)return{...i,path:r,message:i.message};let m="";const f=t.filter((y)=>!!y).slice().reverse();for(let y of f)m=y(l,{data:e,defaultError:m}).message;return{...i,path:r,message:m}},qi=[];class en{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(n,e){const o=[];for(let t of e){if(t.status==="aborted")return K;if(t.status==="dirty")n.dirty();o.push(t.value)}return{status:n.value,value:o}}static async mergeObjectAsync(n,e){const o=[];for(let t of e){const i=await t.key,r=await t.value;o.push({key:i,value:r})}return en.mergeObjectSync(n,o)}static mergeObjectSync(n,e){const o={};for(let t of e){const{key:i,value:r}=t;if(i.status==="aborted")return K;if(r.status==="aborted")return K;if(i.status==="dirty")n.dirty();if(r.status==="dirty")n.dirty();if(i.value!=="__proto__"&&(typeof r.value!=="undefined"||t.alwaysSet))o[i.value]=r.value}return{status:n.value,value:o}}}var K=Object.freeze({status:"aborted"}),te=(n)=>({status:"dirty",value:n}),tn=(n)=>({status:"valid",value:n}),po=(n)=>n.status==="aborted",Lo=(n)=>n.status==="dirty",_e=(n)=>n.status==="valid",ze=(n)=>typeof Promise!=="undefined"&&n instanceof Promise;var A;(function(n){n.errToObj=(e)=>typeof e==="string"?{message:e}:e||{},n.toString=(e)=>typeof e==="string"?e:e===null||e===void 0?void 0:e.message})(A||(A={}));var ue,je;class $n{constructor(n,e,o,t){this._cachedPath=[],this.parent=n,this.data=e,this._path=o,this._key=t}get path(){if(!this._cachedPath.length)if(this._key instanceof Array)this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var Vt=(n,e)=>{if(_e(e))return{success:!0,data:e.value};else{if(!n.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const o=new an(n.common.issues);return this._error=o,this._error}}}};class s{constructor(n){this.spa=this.safeParseAsync,this._def=n,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(n){return Qn(n.data)}_getOrReturnCtx(n,e){return e||{common:n.parent.common,data:n.data,parsedType:Qn(n.data),schemaErrorMap:this._def.errorMap,path:n.path,parent:n.parent}}_processInputParams(n){return{status:new en,ctx:{common:n.parent.common,data:n.data,parsedType:Qn(n.data),schemaErrorMap:this._def.errorMap,path:n.path,parent:n.parent}}}_parseSync(n){const e=this._parse(n);if(ze(e))throw new Error("Synchronous parse encountered promise.");return e}_parseAsync(n){const e=this._parse(n);return Promise.resolve(e)}parse(n,e){const o=this.safeParse(n,e);if(o.success)return o.data;throw o.error}safeParse(n,e){var o;const t={common:{issues:[],async:(o=e===null||e===void 0?void 0:e.async)!==null&&o!==void 0?o:!1,contextualErrorMap:e===null||e===void 0?void 0:e.errorMap},path:(e===null||e===void 0?void 0:e.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:n,parsedType:Qn(n)},i=this._parseSync({data:n,path:t.path,parent:t});return Vt(t,i)}async parseAsync(n,e){const o=await this.safeParseAsync(n,e);if(o.success)return o.data;throw o.error}async safeParseAsync(n,e){const o={common:{issues:[],contextualErrorMap:e===null||e===void 0?void 0:e.errorMap,async:!0},path:(e===null||e===void 0?void 0:e.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:n,parsedType:Qn(n)},t=this._parse({data:n,path:o.path,parent:o}),i=await(ze(t)?t:Promise.resolve(t));return Vt(o,i)}refine(n,e){const o=(t)=>{if(typeof e==="string"||typeof e==="undefined")return{message:e};else if(typeof e==="function")return e(t);else return e};return this._refinement((t,i)=>{const r=n(t),l=()=>i.addIssue({code:a.custom,...o(t)});if(typeof Promise!=="undefined"&&r instanceof Promise)return r.then((m)=>{if(!m)return l(),!1;else return!0});if(!r)return l(),!1;else return!0})}refinement(n,e){return this._refinement((o,t)=>{if(!n(o))return t.addIssue(typeof e==="function"?e(o,t):e),!1;else return!0})}_refinement(n){return new bn({schema:this,typeName:$.ZodEffects,effect:{type:"refinement",refinement:n}})}superRefine(n){return this._refinement(n)}optional(){return Jn.create(this,this._def)}nullable(){return un.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return gn.create(this,this._def)}promise(){return In.create(this,this._def)}or(n){return ye.create([this,n],this._def)}and(n){return ce.create(this,n,this._def)}transform(n){return new bn({...x(this._def),schema:this,typeName:$.ZodEffects,effect:{type:"transform",transform:n}})}default(n){const e=typeof n==="function"?n:()=>n;return new ke({...x(this._def),innerType:this,defaultValue:e,typeName:$.ZodDefault})}brand(){return new fo({typeName:$.ZodBranded,type:this,...x(this._def)})}catch(n){const e=typeof n==="function"?n:()=>n;return new be({...x(this._def),innerType:this,catchValue:e,typeName:$.ZodCatch})}describe(n){return new this.constructor({...this._def,description:n})}pipe(n){return Ge.create(this,n)}readonly(){return Me.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var Qi=/^c[^\s-]{8,}$/i,Yi=/^[0-9a-z]+$/,Gi=/^[0-9A-HJKMNP-TV-Z]{26}$/,Ei=/^[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,pi=/^[a-z0-9_-]{21}$/i,Li=/^[-+]?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)?)??$/,Vi=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Ui="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Go,hi=/^(?:(?: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])$/,Di=/^(([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})))$/,Ii=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,It="((\\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])))",Ni=new RegExp(`^${It}\$`);class Fn extends s{_parse(n){if(this._def.coerce)n.data=String(n.data);if(this._getType(n)!==R.string){const i=this._getOrReturnCtx(n);return b(i,{code:a.invalid_type,expected:R.string,received:i.parsedType}),K}const o=new en;let t=void 0;for(let i of this._def.checks)if(i.kind==="min"){if(n.data.length<i.value)t=this._getOrReturnCtx(n,t),b(t,{code:a.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),o.dirty()}else if(i.kind==="max"){if(n.data.length>i.value)t=this._getOrReturnCtx(n,t),b(t,{code:a.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),o.dirty()}else if(i.kind==="length"){const r=n.data.length>i.value,l=n.data.length<i.value;if(r||l){if(t=this._getOrReturnCtx(n,t),r)b(t,{code:a.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message});else if(l)b(t,{code:a.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message});o.dirty()}}else if(i.kind==="email"){if(!Vi.test(n.data))t=this._getOrReturnCtx(n,t),b(t,{validation:"email",code:a.invalid_string,message:i.message}),o.dirty()}else if(i.kind==="emoji"){if(!Go)Go=new RegExp(Ui,"u");if(!Go.test(n.data))t=this._getOrReturnCtx(n,t),b(t,{validation:"emoji",code:a.invalid_string,message:i.message}),o.dirty()}else if(i.kind==="uuid"){if(!Ei.test(n.data))t=this._getOrReturnCtx(n,t),b(t,{validation:"uuid",code:a.invalid_string,message:i.message}),o.dirty()}else if(i.kind==="nanoid"){if(!pi.test(n.data))t=this._getOrReturnCtx(n,t),b(t,{validation:"nanoid",code:a.invalid_string,message:i.message}),o.dirty()}else if(i.kind==="cuid"){if(!Qi.test(n.data))t=this._getOrReturnCtx(n,t),b(t,{validation:"cuid",code:a.invalid_string,message:i.message}),o.dirty()}else if(i.kind==="cuid2"){if(!Yi.test(n.data))t=this._getOrReturnCtx(n,t),b(t,{validation:"cuid2",code:a.invalid_string,message:i.message}),o.dirty()}else if(i.kind==="ulid"){if(!Gi.test(n.data))t=this._getOrReturnCtx(n,t),b(t,{validation:"ulid",code:a.invalid_string,message:i.message}),o.dirty()}else if(i.kind==="url")try{new URL(n.data)}catch(r){t=this._getOrReturnCtx(n,t),b(t,{validation:"url",code:a.invalid_string,message:i.message}),o.dirty()}else if(i.kind==="regex"){if(i.regex.lastIndex=0,!i.regex.test(n.data))t=this._getOrReturnCtx(n,t),b(t,{validation:"regex",code:a.invalid_string,message:i.message}),o.dirty()}else if(i.kind==="trim")n.data=n.data.trim();else if(i.kind==="includes"){if(!n.data.includes(i.value,i.position))t=this._getOrReturnCtx(n,t),b(t,{code:a.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),o.dirty()}else if(i.kind==="toLowerCase")n.data=n.data.toLowerCase();else if(i.kind==="toUpperCase")n.data=n.data.toUpperCase();else if(i.kind==="startsWith"){if(!n.data.startsWith(i.value))t=this._getOrReturnCtx(n,t),b(t,{code:a.invalid_string,validation:{startsWith:i.value},message:i.message}),o.dirty()}else if(i.kind==="endsWith"){if(!n.data.endsWith(i.value))t=this._getOrReturnCtx(n,t),b(t,{code:a.invalid_string,validation:{endsWith:i.value},message:i.message}),o.dirty()}else if(i.kind==="datetime"){if(!vt(i).test(n.data))t=this._getOrReturnCtx(n,t),b(t,{code:a.invalid_string,validation:"datetime",message:i.message}),o.dirty()}else if(i.kind==="date"){if(!Ni.test(n.data))t=this._getOrReturnCtx(n,t),b(t,{code:a.invalid_string,validation:"date",message:i.message}),o.dirty()}else if(i.kind==="time"){if(!vi(i).test(n.data))t=this._getOrReturnCtx(n,t),b(t,{code:a.invalid_string,validation:"time",message:i.message}),o.dirty()}else if(i.kind==="duration"){if(!Li.test(n.data))t=this._getOrReturnCtx(n,t),b(t,{validation:"duration",code:a.invalid_string,message:i.message}),o.dirty()}else if(i.kind==="ip"){if(!Pi(n.data,i.version))t=this._getOrReturnCtx(n,t),b(t,{validation:"ip",code:a.invalid_string,message:i.message}),o.dirty()}else if(i.kind==="base64"){if(!Ii.test(n.data))t=this._getOrReturnCtx(n,t),b(t,{validation:"base64",code:a.invalid_string,message:i.message}),o.dirty()}else H.assertNever(i);return{status:o.value,value:n.data}}_regex(n,e,o){return this.refinement((t)=>n.test(t),{validation:e,code:a.invalid_string,...A.errToObj(o)})}_addCheck(n){return new Fn({...this._def,checks:[...this._def.checks,n]})}email(n){return this._addCheck({kind:"email",...A.errToObj(n)})}url(n){return this._addCheck({kind:"url",...A.errToObj(n)})}emoji(n){return this._addCheck({kind:"emoji",...A.errToObj(n)})}uuid(n){return this._addCheck({kind:"uuid",...A.errToObj(n)})}nanoid(n){return this._addCheck({kind:"nanoid",...A.errToObj(n)})}cuid(n){return this._addCheck({kind:"cuid",...A.errToObj(n)})}cuid2(n){return this._addCheck({kind:"cuid2",...A.errToObj(n)})}ulid(n){return this._addCheck({kind:"ulid",...A.errToObj(n)})}base64(n){return this._addCheck({kind:"base64",...A.errToObj(n)})}ip(n){return this._addCheck({kind:"ip",...A.errToObj(n)})}datetime(n){var e,o;if(typeof n==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:n});return this._addCheck({kind:"datetime",precision:typeof(n===null||n===void 0?void 0:n.precision)==="undefined"?null:n===null||n===void 0?void 0:n.precision,offset:(e=n===null||n===void 0?void 0:n.offset)!==null&&e!==void 0?e:!1,local:(o=n===null||n===void 0?void 0:n.local)!==null&&o!==void 0?o:!1,...A.errToObj(n===null||n===void 0?void 0:n.message)})}date(n){return this._addCheck({kind:"date",message:n})}time(n){if(typeof n==="string")return this._addCheck({kind:"time",precision:null,message:n});return this._addCheck({kind:"time",precision:typeof(n===null||n===void 0?void 0:n.precision)==="undefined"?null:n===null||n===void 0?void 0:n.precision,...A.errToObj(n===null||n===void 0?void 0:n.message)})}duration(n){return this._addCheck({kind:"duration",...A.errToObj(n)})}regex(n,e){return this._addCheck({kind:"regex",regex:n,...A.errToObj(e)})}includes(n,e){return this._addCheck({kind:"includes",value:n,position:e===null||e===void 0?void 0:e.position,...A.errToObj(e===null||e===void 0?void 0:e.message)})}startsWith(n,e){return this._addCheck({kind:"startsWith",value:n,...A.errToObj(e)})}endsWith(n,e){return this._addCheck({kind:"endsWith",value:n,...A.errToObj(e)})}min(n,e){return this._addCheck({kind:"min",value:n,...A.errToObj(e)})}max(n,e){return this._addCheck({kind:"max",value:n,...A.errToObj(e)})}length(n,e){return this._addCheck({kind:"length",value:n,...A.errToObj(e)})}nonempty(n){return this.min(1,A.errToObj(n))}trim(){return new Fn({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Fn({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Fn({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((n)=>n.kind==="datetime")}get isDate(){return!!this._def.checks.find((n)=>n.kind==="date")}get isTime(){return!!this._def.checks.find((n)=>n.kind==="time")}get isDuration(){return!!this._def.checks.find((n)=>n.kind==="duration")}get isEmail(){return!!this._def.checks.find((n)=>n.kind==="email")}get isURL(){return!!this._def.checks.find((n)=>n.kind==="url")}get isEmoji(){return!!this._def.checks.find((n)=>n.kind==="emoji")}get isUUID(){return!!this._def.checks.find((n)=>n.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((n)=>n.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((n)=>n.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((n)=>n.kind==="cuid2")}get isULID(){return!!this._def.checks.find((n)=>n.kind==="ulid")}get isIP(){return!!this._def.checks.find((n)=>n.kind==="ip")}get isBase64(){return!!this._def.checks.find((n)=>n.kind==="base64")}get minLength(){let n=null;for(let e of this._def.checks)if(e.kind==="min"){if(n===null||e.value>n)n=e.value}return n}get maxLength(){let n=null;for(let e of this._def.checks)if(e.kind==="max"){if(n===null||e.value<n)n=e.value}return n}}Fn.create=(n)=>{var e;return new Fn({checks:[],typeName:$.ZodString,coerce:(e=n===null||n===void 0?void 0:n.coerce)!==null&&e!==void 0?e:!1,...x(n)})};class Gn extends s{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(n){if(this._def.coerce)n.data=Number(n.data);if(this._getType(n)!==R.number){const i=this._getOrReturnCtx(n);return b(i,{code:a.invalid_type,expected:R.number,received:i.parsedType}),K}let o=void 0;const t=new en;for(let i of this._def.checks)if(i.kind==="int"){if(!H.isInteger(n.data))o=this._getOrReturnCtx(n,o),b(o,{code:a.invalid_type,expected:"integer",received:"float",message:i.message}),t.dirty()}else if(i.kind==="min"){if(i.inclusive?n.data<i.value:n.data<=i.value)o=this._getOrReturnCtx(n,o),b(o,{code:a.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),t.dirty()}else if(i.kind==="max"){if(i.inclusive?n.data>i.value:n.data>=i.value)o=this._getOrReturnCtx(n,o),b(o,{code:a.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),t.dirty()}else if(i.kind==="multipleOf"){if(di(n.data,i.value)!==0)o=this._getOrReturnCtx(n,o),b(o,{code:a.not_multiple_of,multipleOf:i.value,message:i.message}),t.dirty()}else if(i.kind==="finite"){if(!Number.isFinite(n.data))o=this._getOrReturnCtx(n,o),b(o,{code:a.not_finite,message:i.message}),t.dirty()}else H.assertNever(i);return{status:t.value,value:n.data}}gte(n,e){return this.setLimit("min",n,!0,A.toString(e))}gt(n,e){return this.setLimit("min",n,!1,A.toString(e))}lte(n,e){return this.setLimit("max",n,!0,A.toString(e))}lt(n,e){return this.setLimit("max",n,!1,A.toString(e))}setLimit(n,e,o,t){return new Gn({...this._def,checks:[...this._def.checks,{kind:n,value:e,inclusive:o,message:A.toString(t)}]})}_addCheck(n){return new Gn({...this._def,checks:[...this._def.checks,n]})}int(n){return this._addCheck({kind:"int",message:A.toString(n)})}positive(n){return this._addCheck({kind:"min",value:0,inclusive:!1,message:A.toString(n)})}negative(n){return this._addCheck({kind:"max",value:0,inclusive:!1,message:A.toString(n)})}nonpositive(n){return this._addCheck({kind:"max",value:0,inclusive:!0,message:A.toString(n)})}nonnegative(n){return this._addCheck({kind:"min",value:0,inclusive:!0,message:A.toString(n)})}multipleOf(n,e){return this._addCheck({kind:"multipleOf",value:n,message:A.toString(e)})}finite(n){return this._addCheck({kind:"finite",message:A.toString(n)})}safe(n){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:A.toString(n)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:A.toString(n)})}get minValue(){let n=null;for(let e of this._def.checks)if(e.kind==="min"){if(n===null||e.value>n)n=e.value}return n}get maxValue(){let n=null;for(let e of this._def.checks)if(e.kind==="max"){if(n===null||e.value<n)n=e.value}return n}get isInt(){return!!this._def.checks.find((n)=>n.kind==="int"||n.kind==="multipleOf"&&H.isInteger(n.value))}get isFinite(){let n=null,e=null;for(let o of this._def.checks)if(o.kind==="finite"||o.kind==="int"||o.kind==="multipleOf")return!0;else if(o.kind==="min"){if(e===null||o.value>e)e=o.value}else if(o.kind==="max"){if(n===null||o.value<n)n=o.value}return Number.isFinite(e)&&Number.isFinite(n)}}Gn.create=(n)=>{return new Gn({checks:[],typeName:$.ZodNumber,coerce:(n===null||n===void 0?void 0:n.coerce)||!1,...x(n)})};class En extends s{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(n){if(this._def.coerce)n.data=BigInt(n.data);if(this._getType(n)!==R.bigint){const i=this._getOrReturnCtx(n);return b(i,{code:a.invalid_type,expected:R.bigint,received:i.parsedType}),K}let o=void 0;const t=new en;for(let i of this._def.checks)if(i.kind==="min"){if(i.inclusive?n.data<i.value:n.data<=i.value)o=this._getOrReturnCtx(n,o),b(o,{code:a.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),t.dirty()}else if(i.kind==="max"){if(i.inclusive?n.data>i.value:n.data>=i.value)o=this._getOrReturnCtx(n,o),b(o,{code:a.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),t.dirty()}else if(i.kind==="multipleOf"){if(n.data%i.value!==BigInt(0))o=this._getOrReturnCtx(n,o),b(o,{code:a.not_multiple_of,multipleOf:i.value,message:i.message}),t.dirty()}else H.assertNever(i);return{status:t.value,value:n.data}}gte(n,e){return this.setLimit("min",n,!0,A.toString(e))}gt(n,e){return this.setLimit("min",n,!1,A.toString(e))}lte(n,e){return this.setLimit("max",n,!0,A.toString(e))}lt(n,e){return this.setLimit("max",n,!1,A.toString(e))}setLimit(n,e,o,t){return new En({...this._def,checks:[...this._def.checks,{kind:n,value:e,inclusive:o,message:A.toString(t)}]})}_addCheck(n){return new En({...this._def,checks:[...this._def.checks,n]})}positive(n){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:A.toString(n)})}negative(n){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:A.toString(n)})}nonpositive(n){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:A.toString(n)})}nonnegative(n){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:A.toString(n)})}multipleOf(n,e){return this._addCheck({kind:"multipleOf",value:n,message:A.toString(e)})}get minValue(){let n=null;for(let e of this._def.checks)if(e.kind==="min"){if(n===null||e.value>n)n=e.value}return n}get maxValue(){let n=null;for(let e of this._def.checks)if(e.kind==="max"){if(n===null||e.value<n)n=e.value}return n}}En.create=(n)=>{var e;return new En({checks:[],typeName:$.ZodBigInt,coerce:(e=n===null||n===void 0?void 0:n.coerce)!==null&&e!==void 0?e:!1,...x(n)})};class le extends s{_parse(n){if(this._def.coerce)n.data=Boolean(n.data);if(this._getType(n)!==R.boolean){const o=this._getOrReturnCtx(n);return b(o,{code:a.invalid_type,expected:R.boolean,received:o.parsedType}),K}return tn(n.data)}}le.create=(n)=>{return new le({typeName:$.ZodBoolean,coerce:(n===null||n===void 0?void 0:n.coerce)||!1,...x(n)})};class Un extends s{_parse(n){if(this._def.coerce)n.data=new Date(n.data);if(this._getType(n)!==R.date){const i=this._getOrReturnCtx(n);return b(i,{code:a.invalid_type,expected:R.date,received:i.parsedType}),K}if(isNaN(n.data.getTime())){const i=this._getOrReturnCtx(n);return b(i,{code:a.invalid_date}),K}const o=new en;let t=void 0;for(let i of this._def.checks)if(i.kind==="min"){if(n.data.getTime()<i.value)t=this._getOrReturnCtx(n,t),b(t,{code:a.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),o.dirty()}else if(i.kind==="max"){if(n.data.getTime()>i.value)t=this._getOrReturnCtx(n,t),b(t,{code:a.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),o.dirty()}else H.assertNever(i);return{status:o.value,value:new Date(n.data.getTime())}}_addCheck(n){return new Un({...this._def,checks:[...this._def.checks,n]})}min(n,e){return this._addCheck({kind:"min",value:n.getTime(),message:A.toString(e)})}max(n,e){return this._addCheck({kind:"max",value:n.getTime(),message:A.toString(e)})}get minDate(){let n=null;for(let e of this._def.checks)if(e.kind==="min"){if(n===null||e.value>n)n=e.value}return n!=null?new Date(n):null}get maxDate(){let n=null;for(let e of this._def.checks)if(e.kind==="max"){if(n===null||e.value<n)n=e.value}return n!=null?new Date(n):null}}Un.create=(n)=>{return new Un({checks:[],coerce:(n===null||n===void 0?void 0:n.coerce)||!1,typeName:$.ZodDate,...x(n)})};class Xe extends s{_parse(n){if(this._getType(n)!==R.symbol){const o=this._getOrReturnCtx(n);return b(o,{code:a.invalid_type,expected:R.symbol,received:o.parsedType}),K}return tn(n.data)}}Xe.create=(n)=>{return new Xe({typeName:$.ZodSymbol,...x(n)})};class me extends s{_parse(n){if(this._getType(n)!==R.undefined){const o=this._getOrReturnCtx(n);return b(o,{code:a.invalid_type,expected:R.undefined,received:o.parsedType}),K}return tn(n.data)}}me.create=(n)=>{return new me({typeName:$.ZodUndefined,...x(n)})};class fe extends s{_parse(n){if(this._getType(n)!==R.null){const o=this._getOrReturnCtx(n);return b(o,{code:a.invalid_type,expected:R.null,received:o.parsedType}),K}return tn(n.data)}}fe.create=(n)=>{return new fe({typeName:$.ZodNull,...x(n)})};class hn extends s{constructor(){super(...arguments);this._any=!0}_parse(n){return tn(n.data)}}hn.create=(n)=>{return new hn({typeName:$.ZodAny,...x(n)})};class Yn extends s{constructor(){super(...arguments);this._unknown=!0}_parse(n){return tn(n.data)}}Yn.create=(n)=>{return new Yn({typeName:$.ZodUnknown,...x(n)})};class Cn extends s{_parse(n){const e=this._getOrReturnCtx(n);return b(e,{code:a.invalid_type,expected:R.never,received:e.parsedType}),K}}Cn.create=(n)=>{return new Cn({typeName:$.ZodNever,...x(n)})};class He extends s{_parse(n){if(this._getType(n)!==R.undefined){const o=this._getOrReturnCtx(n);return b(o,{code:a.invalid_type,expected:R.void,received:o.parsedType}),K}return tn(n.data)}}He.create=(n)=>{return new He({typeName:$.ZodVoid,...x(n)})};class gn extends s{_parse(n){const{ctx:e,status:o}=this._processInputParams(n),t=this._def;if(e.parsedType!==R.array)return b(e,{code:a.invalid_type,expected:R.array,received:e.parsedType}),K;if(t.exactLength!==null){const r=e.data.length>t.exactLength.value,l=e.data.length<t.exactLength.value;if(r||l)b(e,{code:r?a.too_big:a.too_small,minimum:l?t.exactLength.value:void 0,maximum:r?t.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:t.exactLength.message}),o.dirty()}if(t.minLength!==null){if(e.data.length<t.minLength.value)b(e,{code:a.too_small,minimum:t.minLength.value,type:"array",inclusive:!0,exact:!1,message:t.minLength.message}),o.dirty()}if(t.maxLength!==null){if(e.data.length>t.maxLength.value)b(e,{code:a.too_big,maximum:t.maxLength.value,type:"array",inclusive:!0,exact:!1,message:t.maxLength.message}),o.dirty()}if(e.common.async)return Promise.all([...e.data].map((r,l)=>{return t.type._parseAsync(new $n(e,r,e.path,l))})).then((r)=>{return en.mergeArray(o,r)});const i=[...e.data].map((r,l)=>{return t.type._parseSync(new $n(e,r,e.path,l))});return en.mergeArray(o,i)}get element(){return this._def.type}min(n,e){return new gn({...this._def,minLength:{value:n,message:A.toString(e)}})}max(n,e){return new gn({...this._def,maxLength:{value:n,message:A.toString(e)}})}length(n,e){return new gn({...this._def,exactLength:{value:n,message:A.toString(e)}})}nonempty(n){return this.min(1,n)}}gn.create=(n,e)=>{return new gn({type:n,minLength:null,maxLength:null,exactLength:null,typeName:$.ZodArray,...x(e)})};class h extends s{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const n=this._def.shape(),e=H.objectKeys(n);return this._cached={shape:n,keys:e}}_parse(n){if(this._getType(n)!==R.object){const f=this._getOrReturnCtx(n);return b(f,{code:a.invalid_type,expected:R.object,received:f.parsedType}),K}const{status:o,ctx:t}=this._processInputParams(n),{shape:i,keys:r}=this._getCached(),l=[];if(!(this._def.catchall instanceof Cn&&this._def.unknownKeys==="strip")){for(let f in t.data)if(!r.includes(f))l.push(f)}const m=[];for(let f of r){const y=i[f],c=t.data[f];m.push({key:{status:"valid",value:f},value:y._parse(new $n(t,c,t.path,f)),alwaysSet:f in t.data})}if(this._def.catchall instanceof Cn){const f=this._def.unknownKeys;if(f==="passthrough")for(let y of l)m.push({key:{status:"valid",value:y},value:{status:"valid",value:t.data[y]}});else if(f==="strict"){if(l.length>0)b(t,{code:a.unrecognized_keys,keys:l}),o.dirty()}else if(f==="strip");else throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const f=this._def.catchall;for(let y of l){const c=t.data[y];m.push({key:{status:"valid",value:y},value:f._parse(new $n(t,c,t.path,y)),alwaysSet:y in t.data})}}if(t.common.async)return Promise.resolve().then(async()=>{const f=[];for(let y of m){const c=await y.key,T=await y.value;f.push({key:c,value:T,alwaysSet:y.alwaysSet})}return f}).then((f)=>{return en.mergeObjectSync(o,f)});else return en.mergeObjectSync(o,m)}get shape(){return this._def.shape()}strict(n){return A.errToObj,new h({...this._def,unknownKeys:"strict",...n!==void 0?{errorMap:(e,o)=>{var t,i,r,l;const m=(r=(i=(t=this._def).errorMap)===null||i===void 0?void 0:i.call(t,e,o).message)!==null&&r!==void 0?r:o.defaultError;if(e.code==="unrecognized_keys")return{message:(l=A.errToObj(n).message)!==null&&l!==void 0?l:m};return{message:m}}}:{}})}strip(){return new h({...this._def,unknownKeys:"strip"})}passthrough(){return new h({...this._def,unknownKeys:"passthrough"})}extend(n){return new h({...this._def,shape:()=>({...this._def.shape(),...n})})}merge(n){return new h({unknownKeys:n._def.unknownKeys,catchall:n._def.catchall,shape:()=>({...this._def.shape(),...n._def.shape()}),typeName:$.ZodObject})}setKey(n,e){return this.augment({[n]:e})}catchall(n){return new h({...this._def,catchall:n})}pick(n){const e={};return H.objectKeys(n).forEach((o)=>{if(n[o]&&this.shape[o])e[o]=this.shape[o]}),new h({...this._def,shape:()=>e})}omit(n){const e={};return H.objectKeys(this.shape).forEach((o)=>{if(!n[o])e[o]=this.shape[o]}),new h({...this._def,shape:()=>e})}deepPartial(){return oe(this)}partial(n){const e={};return H.objectKeys(this.shape).forEach((o)=>{const t=this.shape[o];if(n&&!n[o])e[o]=t;else e[o]=t.optional()}),new h({...this._def,shape:()=>e})}required(n){const e={};return H.objectKeys(this.shape).forEach((o)=>{if(n&&!n[o])e[o]=this.shape[o];else{let i=this.shape[o];while(i instanceof Jn)i=i._def.innerType;e[o]=i}}),new h({...this._def,shape:()=>e})}keyof(){return Pt(H.objectKeys(this.shape))}}h.create=(n,e)=>{return new h({shape:()=>n,unknownKeys:"strip",catchall:Cn.create(),typeName:$.ZodObject,...x(e)})};h.strictCreate=(n,e)=>{return new h({shape:()=>n,unknownKeys:"strict",catchall:Cn.create(),typeName:$.ZodObject,...x(e)})};h.lazycreate=(n,e)=>{return new h({shape:n,unknownKeys:"strip",catchall:Cn.create(),typeName:$.ZodObject,...x(e)})};class ye extends s{_parse(n){const{ctx:e}=this._processInputParams(n),o=this._def.options;function t(i){for(let l of i)if(l.result.status==="valid")return l.result;for(let l of i)if(l.result.status==="dirty")return e.common.issues.push(...l.ctx.common.issues),l.result;const r=i.map((l)=>new an(l.ctx.common.issues));return b(e,{code:a.invalid_union,unionErrors:r}),K}if(e.common.async)return Promise.all(o.map(async(i)=>{const r={...e,common:{...e.common,issues:[]},parent:null};return{result:await i._parseAsync({data:e.data,path:e.path,parent:r}),ctx:r}})).then(t);else{let i=void 0;const r=[];for(let m of o){const f={...e,common:{...e.common,issues:[]},parent:null},y=m._parseSync({data:e.data,path:e.path,parent:f});if(y.status==="valid")return y;else if(y.status==="dirty"&&!i)i={result:y,ctx:f};if(f.common.issues.length)r.push(f.common.issues)}if(i)return e.common.issues.push(...i.ctx.common.issues),i.result;const l=r.map((m)=>new an(m));return b(e,{code:a.invalid_union,unionErrors:l}),K}}get options(){return this._def.options}}ye.create=(n,e)=>{return new ye({options:n,typeName:$.ZodUnion,...x(e)})};var Bn=(n)=>{if(n instanceof ae)return Bn(n.schema);else if(n instanceof bn)return Bn(n.innerType());else if(n instanceof Se)return[n.value];else if(n instanceof pn)return n.options;else if(n instanceof Te)return H.objectValues(n.enum);else if(n instanceof ke)return Bn(n._def.innerType);else if(n instanceof me)return[void 0];else if(n instanceof fe)return[null];else if(n instanceof Jn)return[void 0,...Bn(n.unwrap())];else if(n instanceof un)return[null,...Bn(n.unwrap())];else if(n instanceof fo)return Bn(n.unwrap());else if(n instanceof Me)return Bn(n.unwrap());else if(n instanceof be)return Bn(n._def.innerType);else return[]};class mo extends s{_parse(n){const{ctx:e}=this._processInputParams(n);if(e.parsedType!==R.object)return b(e,{code:a.invalid_type,expected:R.object,received:e.parsedType}),K;const o=this.discriminator,t=e.data[o],i=this.optionsMap.get(t);if(!i)return b(e,{code:a.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[o]}),K;if(e.common.async)return i._parseAsync({data:e.data,path:e.path,parent:e});else return i._parseSync({data:e.data,path:e.path,parent:e})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(n,e,o){const t=new Map;for(let i of e){const r=Bn(i.shape[n]);if(!r.length)throw new Error(`A discriminator value for key \`${n}\` could not be extracted from all schema options`);for(let l of r){if(t.has(l))throw new Error(`Discriminator property ${String(n)} has duplicate value ${String(l)}`);t.set(l,i)}}return new mo({typeName:$.ZodDiscriminatedUnion,discriminator:n,options:e,optionsMap:t,...x(o)})}}class ce extends s{_parse(n){const{status:e,ctx:o}=this._processInputParams(n),t=(i,r)=>{if(po(i)||po(r))return K;const l=Vo(i.value,r.value);if(!l.valid)return b(o,{code:a.invalid_intersection_types}),K;if(Lo(i)||Lo(r))e.dirty();return{status:e.value,value:l.data}};if(o.common.async)return Promise.all([this._def.left._parseAsync({data:o.data,path:o.path,parent:o}),this._def.right._parseAsync({data:o.data,path:o.path,parent:o})]).then(([i,r])=>t(i,r));else return t(this._def.left._parseSync({data:o.data,path:o.path,parent:o}),this._def.right._parseSync({data:o.data,path:o.path,parent:o}))}}ce.create=(n,e,o)=>{return new ce({left:n,right:e,typeName:$.ZodIntersection,...x(o)})};class On extends s{_parse(n){const{status:e,ctx:o}=this._processInputParams(n);if(o.parsedType!==R.array)return b(o,{code:a.invalid_type,expected:R.array,received:o.parsedType}),K;if(o.data.length<this._def.items.length)return b(o,{code:a.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),K;if(!this._def.rest&&o.data.length>this._def.items.length)b(o,{code:a.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),e.dirty();const i=[...o.data].map((r,l)=>{const m=this._def.items[l]||this._def.rest;if(!m)return null;return m._parse(new $n(o,r,o.path,l))}).filter((r)=>!!r);if(o.common.async)return Promise.all(i).then((r)=>{return en.mergeArray(e,r)});else return en.mergeArray(e,i)}get items(){return this._def.items}rest(n){return new On({...this._def,rest:n})}}On.create=(n,e)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new On({items:n,typeName:$.ZodTuple,rest:null,...x(e)})};class qe extends s{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(n){const{status:e,ctx:o}=this._processInputParams(n);if(o.parsedType!==R.object)return b(o,{code:a.invalid_type,expected:R.object,received:o.parsedType}),K;const t=[],i=this._def.keyType,r=this._def.valueType;for(let l in o.data)t.push({key:i._parse(new $n(o,l,o.path,l)),value:r._parse(new $n(o,o.data[l],o.path,l)),alwaysSet:l in o.data});if(o.common.async)return en.mergeObjectAsync(e,t);else return en.mergeObjectSync(e,t)}get element(){return this._def.valueType}static create(n,e,o){if(e instanceof s)return new qe({keyType:n,valueType:e,typeName:$.ZodRecord,...x(o)});return new qe({keyType:Fn.create(),valueType:n,typeName:$.ZodRecord,...x(e)})}}class Qe extends s{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(n){const{status:e,ctx:o}=this._processInputParams(n);if(o.parsedType!==R.map)return b(o,{code:a.invalid_type,expected:R.map,received:o.parsedType}),K;const t=this._def.keyType,i=this._def.valueType,r=[...o.data.entries()].map(([l,m],f)=>{return{key:t._parse(new $n(o,l,o.path,[f,"key"])),value:i._parse(new $n(o,m,o.path,[f,"value"]))}});if(o.common.async){const l=new Map;return Promise.resolve().then(async()=>{for(let m of r){const f=await m.key,y=await m.value;if(f.status==="aborted"||y.status==="aborted")return K;if(f.status==="dirty"||y.status==="dirty")e.dirty();l.set(f.value,y.value)}return{status:e.value,value:l}})}else{const l=new Map;for(let m of r){const{key:f,value:y}=m;if(f.status==="aborted"||y.status==="aborted")return K;if(f.status==="dirty"||y.status==="dirty")e.dirty();l.set(f.value,y.value)}return{status:e.value,value:l}}}}Qe.create=(n,e,o)=>{return new Qe({valueType:e,keyType:n,typeName:$.ZodMap,...x(o)})};class Dn extends s{_parse(n){const{status:e,ctx:o}=this._processInputParams(n);if(o.parsedType!==R.set)return b(o,{code:a.invalid_type,expected:R.set,received:o.parsedType}),K;const t=this._def;if(t.minSize!==null){if(o.data.size<t.minSize.value)b(o,{code:a.too_small,minimum:t.minSize.value,type:"set",inclusive:!0,exact:!1,message:t.minSize.message}),e.dirty()}if(t.maxSize!==null){if(o.data.size>t.maxSize.value)b(o,{code:a.too_big,maximum:t.maxSize.value,type:"set",inclusive:!0,exact:!1,message:t.maxSize.message}),e.dirty()}const i=this._def.valueType;function r(m){const f=new Set;for(let y of m){if(y.status==="aborted")return K;if(y.status==="dirty")e.dirty();f.add(y.value)}return{status:e.value,value:f}}const l=[...o.data.values()].map((m,f)=>i._parse(new $n(o,m,o.path,f)));if(o.common.async)return Promise.all(l).then((m)=>r(m));else return r(l)}min(n,e){return new Dn({...this._def,minSize:{value:n,message:A.toString(e)}})}max(n,e){return new Dn({...this._def,maxSize:{value:n,message:A.toString(e)}})}size(n,e){return this.min(n,e).max(n,e)}nonempty(n){return this.min(1,n)}}Dn.create=(n,e)=>{return new Dn({valueType:n,minSize:null,maxSize:null,typeName:$.ZodSet,...x(e)})};class ie extends s{constructor(){super(...arguments);this.validate=this.implement}_parse(n){const{ctx:e}=this._processInputParams(n);if(e.parsedType!==R.function)return b(e,{code:a.invalid_type,expected:R.function,received:e.parsedType}),K;function o(l,m){return ro({data:l,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,io(),re].filter((f)=>!!f),issueData:{code:a.invalid_arguments,argumentsError:m}})}function t(l,m){return ro({data:l,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,io(),re].filter((f)=>!!f),issueData:{code:a.invalid_return_type,returnTypeError:m}})}const i={errorMap:e.common.contextualErrorMap},r=e.data;if(this._def.returns instanceof In){const l=this;return tn(async function(...m){const f=new an([]),y=await l._def.args.parseAsync(m,i).catch((F)=>{throw f.addIssue(o(m,F)),f}),c=await Reflect.apply(r,this,y);return await l._def.returns._def.type.parseAsync(c,i).catch((F)=>{throw f.addIssue(t(c,F)),f})})}else{const l=this;return tn(function(...m){const f=l._def.args.safeParse(m,i);if(!f.success)throw new an([o(m,f.error)]);const y=Reflect.apply(r,this,f.data),c=l._def.returns.safeParse(y,i);if(!c.success)throw new an([t(y,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...n){return new ie({...this._def,args:On.create(n).rest(Yn.create())})}returns(n){return new ie({...this._def,returns:n})}implement(n){return this.parse(n)}strictImplement(n){return this.parse(n)}static create(n,e,o){return new ie({args:n?n:On.create([]).rest(Yn.create()),returns:e||Yn.create(),typeName:$.ZodFunction,...x(o)})}}class ae extends s{get schema(){return this._def.getter()}_parse(n){const{ctx:e}=this._processInputParams(n);return this._def.getter()._parse({data:e.data,path:e.path,parent:e})}}ae.create=(n,e)=>{return new ae({getter:n,typeName:$.ZodLazy,...x(e)})};class Se extends s{_parse(n){if(n.data!==this._def.value){const e=this._getOrReturnCtx(n);return b(e,{received:e.data,code:a.invalid_literal,expected:this._def.value}),K}return{status:"valid",value:n.data}}get value(){return this._def.value}}Se.create=(n,e)=>{return new Se({value:n,typeName:$.ZodLiteral,...x(e)})};class pn extends s{constructor(){super(...arguments);ue.set(this,void 0)}_parse(n){if(typeof n.data!=="string"){const e=this._getOrReturnCtx(n),o=this._def.values;return b(e,{expected:H.joinValues(o),received:e.parsedType,code:a.invalid_type}),K}if(!lo(this,ue,"f"))Dt(this,ue,new Set(this._def.values),"f");if(!lo(this,ue,"f").has(n.data)){const e=this._getOrReturnCtx(n),o=this._def.values;return b(e,{received:e.data,code:a.invalid_enum_value,options:o}),K}return tn(n.data)}get options(){return this._def.values}get enum(){const n={};for(let e of this._def.values)n[e]=e;return n}get Values(){const n={};for(let e of this._def.values)n[e]=e;return n}get Enum(){const n={};for(let e of this._def.values)n[e]=e;return n}extract(n,e=this._def){return pn.create(n,{...this._def,...e})}exclude(n,e=this._def){return pn.create(this.options.filter((o)=>!n.includes(o)),{...this._def,...e})}}ue=new WeakMap;pn.create=Pt;class Te extends s{constructor(){super(...arguments);je.set(this,void 0)}_parse(n){const e=H.getValidEnumValues(this._def.values),o=this._getOrReturnCtx(n);if(o.parsedType!==R.string&&o.parsedType!==R.number){const t=H.objectValues(e);return b(o,{expected:H.joinValues(t),received:o.parsedType,code:a.invalid_type}),K}if(!lo(this,je,"f"))Dt(this,je,new Set(H.getValidEnumValues(this._def.values)),"f");if(!lo(this,je,"f").has(n.data)){const t=H.objectValues(e);return b(o,{received:o.data,code:a.invalid_enum_value,options:t}),K}return tn(n.data)}get enum(){return this._def.values}}je=new WeakMap;Te.create=(n,e)=>{return new Te({values:n,typeName:$.ZodNativeEnum,...x(e)})};class In extends s{unwrap(){return this._def.type}_parse(n){const{ctx:e}=this._processInputParams(n);if(e.parsedType!==R.promise&&e.common.async===!1)return b(e,{code:a.invalid_type,expected:R.promise,received:e.parsedType}),K;const o=e.parsedType===R.promise?e.data:Promise.resolve(e.data);return tn(o.then((t)=>{return this._def.type.parseAsync(t,{path:e.path,errorMap:e.common.contextualErrorMap})}))}}In.create=(n,e)=>{return new In({type:n,typeName:$.ZodPromise,...x(e)})};class bn extends s{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===$.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(n){const{status:e,ctx:o}=this._processInputParams(n),t=this._def.effect||null,i={addIssue:(r)=>{if(b(o,r),r.fatal)e.abort();else e.dirty()},get path(){return o.path}};if(i.addIssue=i.addIssue.bind(i),t.type==="preprocess"){const r=t.transform(o.data,i);if(o.common.async)return Promise.resolve(r).then(async(l)=>{if(e.value==="aborted")return K;const m=await this._def.schema._parseAsync({data:l,path:o.path,parent:o});if(m.status==="aborted")return K;if(m.status==="dirty")return te(m.value);if(e.value==="dirty")return te(m.value);return m});else{if(e.value==="aborted")return K;const l=this._def.schema._parseSync({data:r,path:o.path,parent:o});if(l.status==="aborted")return K;if(l.status==="dirty")return te(l.value);if(e.value==="dirty")return te(l.value);return l}}if(t.type==="refinement"){const r=(l)=>{const m=t.refinement(l,i);if(o.common.async)return Promise.resolve(m);if(m instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return l};if(o.common.async===!1){const l=this._def.schema._parseSync({data:o.data,path:o.path,parent:o});if(l.status==="aborted")return K;if(l.status==="dirty")e.dirty();return r(l.value),{status:e.value,value:l.value}}else return this._def.schema._parseAsync({data:o.data,path:o.path,parent:o}).then((l)=>{if(l.status==="aborted")return K;if(l.status==="dirty")e.dirty();return r(l.value).then(()=>{return{status:e.value,value:l.value}})})}if(t.type==="transform")if(o.common.async===!1){const r=this._def.schema._parseSync({data:o.data,path:o.path,parent:o});if(!_e(r))return r;const l=t.transform(r.value,i);if(l instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:e.value,value:l}}else return this._def.schema._parseAsync({data:o.data,path:o.path,parent:o}).then((r)=>{if(!_e(r))return r;return Promise.resolve(t.transform(r.value,i)).then((l)=>({status:e.value,value:l}))});H.assertNever(t)}}bn.create=(n,e,o)=>{return new bn({schema:n,typeName:$.ZodEffects,effect:e,...x(o)})};bn.createWithPreprocess=(n,e,o)=>{return new bn({schema:e,effect:{type:"preprocess",transform:n},typeName:$.ZodEffects,...x(o)})};class Jn extends s{_parse(n){if(this._getType(n)===R.undefined)return tn(void 0);return this._def.innerType._parse(n)}unwrap(){return this._def.innerType}}Jn.create=(n,e)=>{return new Jn({innerType:n,typeName:$.ZodOptional,...x(e)})};class un extends s{_parse(n){if(this._getType(n)===R.null)return tn(null);return this._def.innerType._parse(n)}unwrap(){return this._def.innerType}}un.create=(n,e)=>{return new un({innerType:n,typeName:$.ZodNullable,...x(e)})};class ke extends s{_parse(n){const{ctx:e}=this._processInputParams(n);let o=e.data;if(e.parsedType===R.undefined)o=this._def.defaultValue();return this._def.innerType._parse({data:o,path:e.path,parent:e})}removeDefault(){return this._def.innerType}}ke.create=(n,e)=>{return new ke({innerType:n,typeName:$.ZodDefault,defaultValue:typeof e.default==="function"?e.default:()=>e.default,...x(e)})};class be extends s{_parse(n){const{ctx:e}=this._processInputParams(n),o={...e,common:{...e.common,issues:[]}},t=this._def.innerType._parse({data:o.data,path:o.path,parent:{...o}});if(ze(t))return t.then((i)=>{return{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new an(o.common.issues)},input:o.data})}});else return{status:"valid",value:t.status==="valid"?t.value:this._def.catchValue({get error(){return new an(o.common.issues)},input:o.data})}}removeCatch(){return this._def.innerType}}be.create=(n,e)=>{return new be({innerType:n,typeName:$.ZodCatch,catchValue:typeof e.catch==="function"?e.catch:()=>e.catch,...x(e)})};class Ye extends s{_parse(n){if(this._getType(n)!==R.nan){const o=this._getOrReturnCtx(n);return b(o,{code:a.invalid_type,expected:R.nan,received:o.parsedType}),K}return{status:"valid",value:n.data}}}Ye.create=(n)=>{return new Ye({typeName:$.ZodNaN,...x(n)})};var Zi=Symbol("zod_brand");class fo extends s{_parse(n){const{ctx:e}=this._processInputParams(n),o=e.data;return this._def.type._parse({data:o,path:e.path,parent:e})}unwrap(){return this._def.type}}class Ge extends s{_parse(n){const{status:e,ctx:o}=this._processInputParams(n);if(o.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:o.data,path:o.path,parent:o});if(i.status==="aborted")return K;if(i.status==="dirty")return e.dirty(),te(i.value);else return this._def.out._parseAsync({data:i.value,path:o.path,parent:o})})();else{const t=this._def.in._parseSync({data:o.data,path:o.path,parent:o});if(t.status==="aborted")return K;if(t.status==="dirty")return e.dirty(),{status:"dirty",value:t.value};else return this._def.out._parseSync({data:t.value,path:o.path,parent:o})}}static create(n,e){return new Ge({in:n,out:e,typeName:$.ZodPipeline})}}class Me extends s{_parse(n){const e=this._def.innerType._parse(n),o=(t)=>{if(_e(t))t.value=Object.freeze(t.value);return t};return ze(e)?e.then((t)=>o(t)):o(e)}unwrap(){return this._def.innerType}}Me.create=(n,e)=>{return new Me({innerType:n,typeName:$.ZodReadonly,...x(e)})};var nr={object:h.lazycreate},$;(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})($||($={}));var er=(n,e={message:`Input not instance of ${n.name}`})=>dt((o)=>o instanceof n,e),Zt=Fn.create,ni=Gn.create,or=Ye.create,tr=En.create,ei=le.create,ir=Un.create,rr=Xe.create,lr=me.create,mr=fe.create,fr=hn.create,yr=Yn.create,cr=Cn.create,ar=He.create,Sr=gn.create,Ee=h.create,Tr=h.strictCreate,kr=ye.create,br=mo.create,Mr=ce.create,Rr=On.create,Ar=qe.create,Fr=Qe.create,gr=Dn.create,Jr=ie.create,$r=ae.create,Kr=Se.create,wr=pn.create,Cr=Te.create,Or=In.create,Ut=bn.create,Wr=Jn.create,xr=un.create,sr=bn.createWithPreprocess,Br=Ge.create,ur=()=>Zt().optional(),jr=()=>ni().optional(),_r=()=>ei().optional(),zr={string:(n)=>Fn.create({...n,coerce:!0}),number:(n)=>Gn.create({...n,coerce:!0}),boolean:(n)=>le.create({...n,coerce:!0}),bigint:(n)=>En.create({...n,coerce:!0}),date:(n)=>Un.create({...n,coerce:!0})},Xr=K,rn=Object.freeze({__proto__:null,defaultErrorMap:re,setErrorMap:Hi,getErrorMap:io,makeIssue:ro,EMPTY_PATH:qi,addIssueToContext:b,ParseStatus:en,INVALID:K,DIRTY:te,OK:tn,isAborted:po,isDirty:Lo,isValid:_e,isAsync:ze,get util(){return H},get objectUtil(){return Eo},ZodParsedType:R,getParsedType:Qn,ZodType:s,datetimeRegex:vt,ZodString:Fn,ZodNumber:Gn,ZodBigInt:En,ZodBoolean:le,ZodDate:Un,ZodSymbol:Xe,ZodUndefined:me,ZodNull:fe,ZodAny:hn,ZodUnknown:Yn,ZodNever:Cn,ZodVoid:He,ZodArray:gn,ZodObject:h,ZodUnion:ye,ZodDiscriminatedUnion:mo,ZodIntersection:ce,ZodTuple:On,ZodRecord:qe,ZodMap:Qe,ZodSet:Dn,ZodFunction:ie,ZodLazy:ae,ZodLiteral:Se,ZodEnum:pn,ZodNativeEnum:Te,ZodPromise:In,ZodEffects:bn,ZodTransformer:bn,ZodOptional:Jn,ZodNullable:un,ZodDefault:ke,ZodCatch:be,ZodNaN:Ye,BRAND:Zi,ZodBranded:fo,ZodPipeline:Ge,ZodReadonly:Me,custom:dt,Schema:s,ZodSchema:s,late:nr,get ZodFirstPartyTypeKind(){return $},coerce:zr,any:fr,array:Sr,bigint:tr,boolean:ei,date:ir,discriminatedUnion:br,effect:Ut,enum:wr,function:Jr,instanceof:er,intersection:Mr,lazy:$r,literal:Kr,map:Fr,nan:or,nativeEnum:Cr,never:cr,null:mr,nullable:xr,number:ni,object:Ee,oboolean:_r,onumber:jr,optional:Wr,ostring:ur,pipeline:Br,preprocess:sr,promise:Or,record:Ar,set:gr,strictObject:Tr,string:Zt,symbol:rr,transformer:Ut,tuple:Rr,undefined:lr,union:kr,unknown:yr,void:ar,NEVER:Xr,ZodIssueCode:a,quotelessJson:Xi,ZodError:an});function oi(n){const e=n.runtimeEnvStrict??n.runtimeEnv??process.env;if(n.emptyStringAsUndefined??!1){for(let[k,g]of Object.entries(e))if(g==="")delete e[k]}if(!!n.skipValidation)return e;const i=typeof n.client==="object"?n.client:{},r=typeof n.server==="object"?n.server:{},l=typeof n.shared==="object"?n.shared:{},m=Ee(i),f=Ee(r),y=Ee(l),c=n.isServer??(typeof window==="undefined"||("Deno"in window)),T=m.merge(y),F=f.merge(y).merge(m),u=c?F.safeParse(e):T.safeParse(e),G=n.onValidationError??((k)=>{throw console.error("\u274C Invalid environment variables:",k.flatten().fieldErrors),new Error("Invalid environment variables")}),Sn=n.onInvalidAccess??((k)=>{throw new Error("\u274C Attempted to access a server-side environment variable on the client")});if(u.success===!1)return G(u.error);const O=(k)=>{if(!n.clientPrefix)return!0;return!k.startsWith(n.clientPrefix)&&!(k in y.shape)},E=(k)=>{return c||!O(k)},p=(k)=>{return k==="__esModule"||k==="$$typeof"},q=(n.extends??[]).reduce((k,g)=>{return Object.assign(k,g)},{}),fn=Object.assign(u.data,q);return new Proxy(fn,{get(k,g){if(typeof g!=="string")return;if(p(g))return;if(!E(g))return Sn(g);return Reflect.get(k,g)}})}var fi=Mi(mi(),1);fi.default.config();var Io=oi({isServer:typeof window==="undefined",server:{POSTGRES_USER:rn.string(),POSTGRES_PASSWORD:rn.string(),POSTGRES_DATABASE:rn.string(),POSTGRES_HOST:rn.string(),POSTGRES_PORT:rn.string().transform((n)=>Number.parseInt(n,10)),BACKEND_PORT:rn.string().transform((n)=>Number.parseInt(n,10)),RUN_WORKERS_FROM_SOURCE:rn.union([rn.literal("true"),rn.literal("false")]).optional().transform((n)=>n==="true"),FRONTEND_PORT:rn.string().transform((n)=>Number.parseInt(n,10)),FRONTEND_ORIGINS:rn.string().transform((n)=>D(n)).pipe(rn.array(rn.string()))},clientPrefix:"VITE_",client:{VITE_BACKEND_ORIGIN:rn.string()},runtimeEnv:process.env,emptyStringAsUndefined:!0});var No={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"};function Po(){_n.logger.info("\uD83D\uDEEC frontend server exiting"),process.exit(0)}var _n=new Ho;_n.logger.info(" ready");var vo=ci(import.meta.dir,"..","app");ll({port:Io.FRONTEND_PORT??3333,async fetch(n,e){try{const o=new URL(n.url),t=e.requestIP(n)?.address??"??";if(_n.logger.info(`[${t}]`,n.method,o.pathname),o.pathname==="/")return new Response(Bun.file(ci(vo,"index.html")));if(o.pathname==="/index.html")return Response.redirect("/");const i=il(vo,o.pathname),r=rl(i);if(!r.startsWith(vo))throw 403;if(!await yi(r).exists())throw 404;return new Response(yi(r))}catch(o){if(typeof o==="number")return new Response(No[o],{status:o});if(o instanceof Error)_n.logger.error(o.message);else{const t=ne(o);_n.logger.error("frontend server threw",t)}return new Response(No[500],{status:500})}}});process.on("SIGINT",()=>{_n.logger.info("\u2757 received SIGINT; exiting gracefully"),Po()});process.on("SIGTERM",()=>{_n.logger.info("\u2757 received SIGTERM; exiting gracefully"),Po()});process.on("exit",()=>{_n.logger.info("\u2757 received exit; exiting gracefully"),Po()});_n.logger.info(`\uD83D\uDEEB frontend server running at http://localhost:${Io.FRONTEND_PORT??3333}/`);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tempest.games",
|
|
3
|
-
"version": "0.0
|
|
3
|
+
"version": "0.1.0",
|
|
4
4
|
"publishConfig": {
|
|
5
5
|
"access": "public"
|
|
6
6
|
},
|
|
@@ -16,30 +16,37 @@
|
|
|
16
16
|
"index.html"
|
|
17
17
|
],
|
|
18
18
|
"dependencies": {
|
|
19
|
+
"@t3-oss/env-core": "0.11.1",
|
|
20
|
+
"drizzle-orm": "0.33.0",
|
|
21
|
+
"postgres": "3.4.4",
|
|
19
22
|
"react": "18.3.1",
|
|
20
23
|
"react-dom": "18.3.1",
|
|
21
24
|
"socket.io": "4.8.0",
|
|
22
25
|
"socket.io-client": "4.8.0",
|
|
23
|
-
"
|
|
26
|
+
"zod": "3.23.8",
|
|
27
|
+
"atom.io": "0.30.0"
|
|
24
28
|
},
|
|
25
29
|
"devDependencies": {
|
|
26
|
-
"@eslint/js": "9.11.
|
|
27
|
-
"@types/node": "22.
|
|
28
|
-
"@types/react": "18.3.
|
|
30
|
+
"@eslint/js": "9.11.1",
|
|
31
|
+
"@types/node": "22.7.4",
|
|
32
|
+
"@types/react": "18.3.11",
|
|
29
33
|
"@types/react-dom": "18.3.0",
|
|
30
|
-
"@vitejs/plugin-react-swc": "3.7.
|
|
34
|
+
"@vitejs/plugin-react-swc": "3.7.1",
|
|
31
35
|
"bun-types": "1.1.29",
|
|
32
36
|
"concurrently": "9.0.1",
|
|
33
37
|
"cross-env": "7.0.3",
|
|
34
|
-
"
|
|
38
|
+
"dotenv": "16.4.5",
|
|
39
|
+
"drizzle-kit": "0.24.2",
|
|
40
|
+
"eslint": "9.11.1",
|
|
35
41
|
"eslint-plugin-react-refresh": "0.4.12",
|
|
36
|
-
"globals": "15.
|
|
42
|
+
"globals": "15.10.0",
|
|
37
43
|
"rimraf": "6.0.1",
|
|
38
44
|
"tsx": "4.19.1",
|
|
39
45
|
"typescript": "5.6.2",
|
|
40
|
-
"typescript-eslint": "8.
|
|
41
|
-
"vite": "5.4.
|
|
42
|
-
"vite-tsconfig-paths": "5.0.1"
|
|
46
|
+
"typescript-eslint": "8.8.0",
|
|
47
|
+
"vite": "5.4.8",
|
|
48
|
+
"vite-tsconfig-paths": "5.0.1",
|
|
49
|
+
"vitest": "2.1.2"
|
|
43
50
|
},
|
|
44
51
|
"scripts": {
|
|
45
52
|
"dev": "concurrently \"bun:dev:*\"",
|
|
@@ -53,7 +60,9 @@
|
|
|
53
60
|
"preview": "nr build && concurrently \"bun:preview:*\"",
|
|
54
61
|
"preview:frontend": "cross-env MODE=production ./bin/frontend.bun.js",
|
|
55
62
|
"preview:backend": "cross-env MODE=production ./bin/backend.bun.js",
|
|
56
|
-
"
|
|
63
|
+
"env": "[ ! -f .env ] && cp .env.defaults .env",
|
|
64
|
+
"test": "vitest",
|
|
65
|
+
"test:once": "bun run env && vitest run",
|
|
57
66
|
"lint:biome": "biome check -- .",
|
|
58
67
|
"lint:eslint": "eslint --flag unstable_ts_config -- .",
|
|
59
68
|
"lint:types": "tsc --noEmit",
|