tempest.games 0.0.4 → 0.0.6

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 CHANGED
@@ -1,5 +1,17 @@
1
1
  # tempest.games
2
2
 
3
+ ## 0.0.6
4
+
5
+ ### Patch Changes
6
+
7
+ - f36d18f: 🐛 Use ParentSocket for logging.
8
+
9
+ ## 0.0.5
10
+
11
+ ### Patch Changes
12
+
13
+ - 8cf0e94: ♻️ Bun
14
+
3
15
  ## 0.0.4
4
16
 
5
17
  ### Patch Changes
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env bun
2
+ // @bun
3
+ function fe(e=Math.random){return e().toString(36).slice(2)}class be 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 kt(e){while(e.parent!==null)e=e.parent;return e}function pe(e,t){const o=S(t),n=`${e.key}(${o})`,i=oo[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 oo={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 ue(e){return gt(K.STORE,e)}function me(e){return bt(K.STORE,e)}var Ue=(e)=>(t,o,n,i,...r)=>{console[e](`${t} ${o} "${n}" ${i}`,...r)},no={error:Ue("error"),info:Ue("info"),warn:Ue("warn")};class qe{e;t;o;constructor(e,t,o=no){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 Ye(K.STORE,e)}function xe(e){return Le(e,K.STORE)}class X{a;b;cardinality;relations=new Map;contents=new Map;isContent;makeContentKey=(e,t)=>`${e}:${t}`;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)}}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)console.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 xt=(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(io).join(" ")}var io=(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"),At(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 Ft=(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}"`}`)},Mt=(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)},Rt=(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)},Te=(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 Ct=(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(Rt(o,i))continue;Kt(i,o),Te(o,i)}}};function ro(e,t){if(wt(t.newValue))return!1;if(e.includes("\uD83D\uDD0D"))return!1;return!0}var Jt=(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(!ro(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 ht=(e,t,o)=>{const n=ie(e,o);let i=n;if(e.type==="mutable_atom"&&R(o)){const{parent:a}=o;i=Ae(e,a,o)}if(i=Oe(t)(i),o.logger.info("\uD83D\uDCDD","atom",e.key,"set to",i),i=q(e.key,i,e.subject,o),$t(e.key,o))Ot(e.key,o);Te(o,e.key),Ze(e,o);const r={oldValue:n,newValue:i};if(P(o))Ct(e,r,o);else if(o.parent){if(o.on.transactionApplying.state===null)Jt(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=Ae(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":ht(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 bt(e,t){if("mutable"in t)return Fe(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)??pe(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),ao=(e,t)=>y(t).selectors.has(e),lo=(e,t)=>y(t).readonlySelectors.has(e),vt=(e,t)=>We(e,t)||ao(e,t)||lo(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)=>vt(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},It=(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 Wt=(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}),Wt(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 Me=(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 q(t.key,v,i,y(e)),r.clear(),v},u={...t,subject:i,install:(v)=>Me(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 Re=(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 q(t.key,w,i,W),r.clear(),w},v={...t,subject:i,install:(I)=>Re(I,t,o),get:F,set:(I)=>{const W=y(e),w=F(t.get,W),L=Oe(I)(w);if(e.logger.info("\uD83D\uDCDD","selector",t.key,"set (",w,"->",L,")"),q(t.key,L,i,W),Te(W,t.key),P(W))i.next({newValue:L,oldValue:w});t.set(a,L)},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 ge(e,t){if("set"in t){const i=Re(e,t,void 0);return e.on.selectorCreation.next(i),i}const n=Me(e,t,void 0);return e.on.selectorCreation.next(n),n}function _t(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=Me(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 Ce(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=Re(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)=>Ce(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 Ye(e,t){if("set"in t)return Ce(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 jt(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 Ke(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 Bt(e,t,o){const n=Ke(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 Et(e,t){return Bt(e,t,K.STORE)}function ze(e,t,o){const n=Ke(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 so(e,t){return Ke(e,t).core.findRelatedKeysState}function zt(e){return so(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=Fe(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),dt=ee.has(p);if(this.relations.cardinality==="1:n"){const St=[];for(let Se of ee){if(Se===p)continue;const ke=a(f,Se);if(ke.delete(ne),ke.size===0)St.push(Se)}if(!dt&&ee.size>0)ee.clear();for(let Se of St){const ke=[ne,Se].sort(),to=`"${ke[0]}:${ke[1]}"`;this.molecules.delete(to)}}if(!dt)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=jt(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"]),L=()=>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=L(),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=L(),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 Pt(e){return e[0].toUpperCase()+e.slice(1)}function oe(e,t,o,n,...i){const r=kt(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=fe())=>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=Ke(k,r);w.molecules.set(s,m),m.joins.set(k.key,w);const L=F.subject.subscribe(`join:${k.key}-${s}`,(T)=>{if(T.type==="molecule_disposal"&&S(T.token.key)===s)L(),w.molecules.delete(s)});if(W===null)return;const f=k.a===W?k.b:k.a,p=Et(k,n),g=p[`${f}KeysOf${Pt(W)}`],x=p[`${f}EntriesOf${Pt(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 L of w.above.values())L.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=pe(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)??pe(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":_t(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=Ft(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),Mt(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":{Vt(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":{Vt(e,o),o.valueMap.set(e.token.key,e.value);break}}}function Vt(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 Nt(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 Xt=(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))Nt(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 Y 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 Dt=(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 Y(i.atoms),atomsThatAreDefault:new Set(i.atomsThatAreDefault),families:new Y(i.families),operation:{open:!1},readonlySelectors:new Y(i.readonlySelectors),timelines:new Y(i.timelines),timelineTopics:new X(i.timelineTopics.toJSON()),trackers:new Map,transactions:new Y(i.transactions),selectorAtoms:new X(i.selectorAtoms.toJSON()),selectorGraph:new X(i.selectorGraph.toJSON(),{makeContentKey:(...c)=>c.sort().join(":")}),selectors:new Y(i.selectors),valueMap:new Y(i.valueMap),defaults:i.defaults,disposalTraces:o.disposalTraces.copy(),molecules:new Y(i.molecules),moleculeFamilies:new Y(i.moleculeFamilies),moleculeInProgress:i.moleculeInProgress,miscResources:new Y(i.miscResources)},a=Ht(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=fe())=>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 Le(e,t){const o={key:e.key,type:"transaction",run:(r,a)=>{const s=Dt(e.key,r,t,a);try{const l=y(t),{toolkit:c}=s.transactionMeta,m=e.do(c,...r);return Xt(m,l),m}catch(l){throw xt(n),t.logger.warn("\uD83D\uDCA5","transaction",e.key,"caught:",l),l}},install:(r)=>Le(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 Ht(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 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 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 qe("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 Ut({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 It(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 Je(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}"`),Je(c,t,o)},subject:r};if(o)a.family=o;const s=t.default();n.atoms.set(a.key,a),He(t.key,e),q(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)Yt(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 Fe(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=Je(F,C,m);return r.next({type:"state_creation",token:v}),v},n,{subject:r,install:(l)=>Fe(l,t),toJson:t.toJson,fromJson:t.fromJson,internalRoles:o});return e.families.set(t.key,s),Lt(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 wt(e){return typeof e==="object"&&e!==null&&"do"in e&&"undo"in e&&"subscribe"in e}function Ae(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 q(e,t,o,n){const i=n.valueMap.get(e);if(i instanceof be)i.use(t);if(t instanceof Promise){const r=new be(t);return n.valueMap.set(e,r),r.then((a)=>{q(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 At=(e,t)=>{let o=t.valueMap.get(e.key);if(e.type==="mutable_atom"&&R(t)){const{parent:n}=t;o=Ae(e,n,t)}return o},Kt=(e,t)=>{const o=t.valueMap.get(e);if(o instanceof be){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 $t=(e,t)=>{return y(t).atomsThatAreDefault.has(e)},He=(e,t)=>{const o=y(t);o.atomsThatAreDefault=new Set(o.atomsThatAreDefault).add(e)},Ot=(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),q(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 gt(e,t){if("mutable"in t){const i=Je(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 Yt=(e,t,o=K.STORE)=>{return ge(o,{key:`${e.key}:JSON`,get:({get:n})=>t.toJson(n(e)),set:({set:n},i)=>{n(e,t.fromJson(i))}})};function Lt(e,t,o=K.STORE){const n=Ce(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),zm=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];class de{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 we extends de{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 Qt extends de{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 yt extends de{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 Qt(`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 Zt 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 ft{e;type="continuity";globals=[];actions=[];perspectives=[];constructor(e){this.key=e}static existing=new Zt;static create(e,t){const o=new ft(e),{type:n,globals:i,actions:r,perspectives:a}=t(o),s={type:n,key:e,globals:i,actions:r,perspectives:a};return ft.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 uy=ue({key:"usersInRoomIndex",mutable:!0,default:()=>new z,toJson:(e)=>e.toJSON(),fromJson:(e)=>z.fromJSON(e)}),pt=ue({key:"roomIndex",default:()=>new z,mutable:!0,toJson:(e)=>e.toJSON(),fromJson:(e)=>z.fromJSON(e)}),mo={enteredAtEpoch:0},he=Ee({key:"usersInRooms",between:["room","user"],cardinality:"1:n"},mo),Ty=$e({key:"usersInMyRoomView",get:(e)=>({find:t})=>{const o=zt(he);return[t(o,e)]}});import{spawn as yo}from"child_process";var ut=me({key:"roomArguments",default:["echo",["Hello World!"]]}),Gt=$e({key:"room",get:(e)=>async({get:t,find:o})=>{const n=o(ut,e),i=t(n),[r,a]=i,s=await new Promise((l)=>{const c=yo(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 we(s,e)}});var wy=xe({key:"createRoom",do:({get:e,set:t,find:o},n,i,r)=>{const a=r?[i,r]:[i],s=o(ut,n);t(s,a),t(pt,(m)=>m.add(n));const l=o(Gt,n);return e(l)}}),hy=xe({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}}),$y=xe({key:"leaveRoom",do:(e,t,o)=>{ze(he,(n)=>{n.delete({room:t,user:o})},e.env().store)}}),Oy=xe({key:"destroyRoom",do:(e,t)=>{ze(he,(o)=>{o.delete({room:t})},e.env().store),e.set(pt,(o)=>(o.delete(t),o))}});var Wy=me({key:"transactionRedactor",default:{occlude:(e)=>e}}),fo=me({key:"unacknowledgedUpdates",default:()=>[]});var po=me({key:"sockets",default:null}),zy=ue({key:"socketsIndex",mutable:!0,default:()=>new z,toJson:(e)=>e.toJSON(),fromJson:(e)=>z.fromJSON(e)}),Py=ue({key:"usersIndex",mutable:!0,default:()=>new z,toJson:(e)=>e.toJSON(),fromJson:(e)=>z.fromJSON(e)}),uo=Ee({key:"usersOfSockets",between:["user","socket"],cardinality:"1:1"});import{spawn as To}from"child_process";import{resolve as So}from"path";function eo(e,t){const n=process.env.MODE==="development"?"ts":"js",i=t.endsWith(".bun")?"bun":"node",a=[So(import.meta.dir,`${t}.${n}`)];if(i==="node"&&n==="ts")a.push("--experimental-strip-types");const s=To(i,a);return new we(s,t,e.logger)}var Tt=new yt,ko=eo(Tt,"backend.worker.game.bun");process.on("exit",()=>{ko.process.kill(),Tt.logger.info("\uD83D\uDEEC backend server exiting")});Tt.logger.info("\uD83D\uDEEB backend server ready");
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- function fe(e=Math.random){return e().toString(36).slice(2)}class be 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 St(e){while(e.parent!==null)e=e.parent;return e}function pe(e,t){const o=S(t),n=`${e.key}(${o})`,i=to[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 to={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 ue(e){return bt(K.STORE,e)}function me(e){return kt(K.STORE,e)}var He=(e)=>(t,o,n,i,...r)=>{console[e](`${t} ${o} "${n}" ${i}`,...r)},oo={error:He("error"),info:He("info"),warn:He("warn")};class Ue{e;t;o;constructor(e,t,o=oo){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 he(e){return qe(K.STORE,e)}function xe(e){return Ye(e,K.STORE)}class X{a;b;cardinality;relations=new Map;contents=new Map;isContent;makeContentKey=(e,t)=>`${e}:${t}`;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)}}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)console.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 Le 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 gt=(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(no).join(" ")}var no=(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 $e=(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"),xt(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 At=(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}"`}`)},Ft=(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)},Mt=(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)},Te=(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 Rt=(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 Qe=(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(Mt(o,i))continue;Ct(i,o),Te(o,i)}}};function io(e,t){if(Jt(t.newValue))return!1;if(e.includes("\uD83D\uDD0D"))return!1;return!0}var Kt=(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(!io(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 wt=(e,t,o)=>{const n=ie(e,o);let i=n;if(e.type==="mutable_atom"&&R(o)){const{parent:a}=o;i=Ae(e,a,o)}if(i=$e(t)(i),o.logger.info("\uD83D\uDCDD","atom",e.key,"set to",i),i=q(e.key,i,e.subject,o),ht(e.key,o))$t(e.key,o);Te(o,e.key),Qe(e,o);const r={oldValue:n,newValue:i};if(P(o))Rt(e,r,o);else if(o.parent){if(o.on.transactionApplying.state===null)Kt(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=Ae(s,m,o)}if(l.do(r.newValue)===null)Qe(s,o)}}};var Oe=(e,t,o)=>{switch(e.type){case"atom":case"mutable_atom":wt(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 kt(e,t){if("mutable"in t)return Fe(e,t);return re(e,t)}function ve(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=ve(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)??pe(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 Ie=(e,t)=>y(t).atoms.has(e),ro=(e,t)=>y(t).selectors.has(e),ao=(e,t)=>y(t).readonlySelectors.has(e),Ot=(e,t)=>Ie(e,t)||ro(e,t)||ao(e,t);var We=(e,t)=>{return y(t).selectorGraph.getRelationEntries({downstreamSelectorKey:e}).filter(([n,{source:i}])=>i!==e).map(([n,{source:i}])=>i).filter((n)=>Ot(n,t))};var Ze=(e,t,o)=>{const n=[],i=We(e,o);while(i.length>0){const r=i.shift();if(t.has(r))continue;if(t.add(r),!Ie(r,o))i.push(...We(r,o));else if(!n.includes(r))n.push(r)}return n},vt=(e,t)=>{const o=e.key,n=We(o,t),i=new Set;return n.flatMap((r)=>Ie(r,t)?r:Ze(r,i,t))};var It=(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=Ze(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 _e=(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}),It(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);Oe(s,r,a)},find:(n,i)=>h(o,n,i),seek:(n,i)=>$(o,n,i),json:(n)=>V(o,n)});var Me=(e,t,o)=>{const n=y(e),i=new b,r=new Set,{get:a,find:s,seek:l,json:c}=_e(t.key,r,n),m=()=>{const v=t.get({get:a,find:s,seek:l,json:c});return q(t.key,v,i,y(e)),r.clear(),v},u={...t,subject:i,install:(v)=>Me(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 Re=(e,t,o)=>{const n=y(e),i=new b,r=new Set,a=_e(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 q(t.key,w,i,W),r.clear(),w},v={...t,subject:i,install:(I)=>Re(I,t,o),get:F,set:(I)=>{const W=y(e),w=F(t.get,W),L=$e(I)(w);if(e.logger.info("\uD83D\uDCDD","selector",t.key,"set (",w,"->",L,")"),q(t.key,L,i,W),Te(W,t.key),P(W))i.next({newValue:L,oldValue:w});t.set(a,L)},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 ge(e,t){if("set"in t){const i=Re(e,t,void 0);return e.on.selectorCreation.next(i),i}const n=Me(e,t,void 0);return e.on.selectorCreation.next(n),n}function Wt(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=Me(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 Ce(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=Re(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)=>Ce(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 qe(e,t){if("set"in t)return Ce(e,t);return le(e,t)}function je(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")je(c,t);else if(c.above.delete(o.stringKey),c.above.size===0)je(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 _t(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 Be(e,t,o=K.STORE){return Ge(o).set(e.key,new tt(e,t,o)),{key:e.key,type:"join",a:e.between[0],b:e.between[1],cardinality:e.cardinality}}function Ge(e){if("joins"in e&&e.joins instanceof Map)return e.joins;const t=new Map;return e.joins=t,t}function Ke(e,t){const o=Ge(t);let n=o.get(e.key);if(n===void 0){if(n=Ge(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 jt(e,t,o){const n=Ke(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 Bt(e,t){return jt(e,t,K.STORE)}function Ee(e,t,o){const n=Ke(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 lo(e,t){return Ke(e,t).core.findRelatedKeysState}function Et(e){return lo(e,K.STORE)}class tt{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 tt(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=Fe(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),Tt=ee.has(p);if(this.relations.cardinality==="1:n"){const dt=[];for(let Se of ee){if(Se===p)continue;const ke=a(f,Se);if(ke.delete(ne),ke.size===0)dt.push(Se)}if(!Tt&&ee.size>0)ee.clear();for(let Se of dt){const ke=[ne,Se].sort(),eo=`"${ke[0]}:${ke[1]}"`;this.molecules.delete(eo)}}if(!Tt)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=_t(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=et(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"]),L=()=>le(o,{key:`${e.key}/multipleRelatedEntries`,get:(f)=>({get:p})=>{const g=et(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=L(),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=L(),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 ze(e){return{store:e}}class Pe{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 zt(e){return e[0].toUpperCase()+e.slice(1)}function oe(e,t,o,n,...i){const r=St(e),a=y(e),s=S(n);a.moleculeInProgress=s;const l=Array.isArray(t)?t:[t],c=l.map((k)=>{if(k instanceof Pe)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 Pe(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=fe())=>ye(k,I,y(e)),make:(k,I,W,...w)=>oe(y(r),k,I,W,...w),dispose:(k)=>{D(y(r),k)},env:()=>ze(y(r)),bond:(k,I)=>{if(k.type==="join"){const{as:W}=I,w=Ke(k,r);w.molecules.set(s,m),m.joins.set(k.key,w);const L=F.subject.subscribe(`join:${k.key}-${s}`,(T)=>{if(T.type==="molecule_disposal"&&S(T.token.key)===s)L(),w.molecules.delete(s)});if(W===null)return;const f=k.a===W?k.b:k.a,p=Bt(k,n),g=p[`${f}KeysOf${zt(W)}`],x=p[`${f}EntriesOf${zt(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 L of w.above.values())L.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=pe(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)??pe(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":ot(o,e);break;case"selector":case"readonly_selector":Wt(o,e);break;case"molecule":je(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=ve(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=At(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);Oe(s,r,e),Ft(e)}function Ve(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 nt(e,t,o){switch(t){case"newValue":{Pt(e,o);break}case"oldValue":{D(o,e.token);break}}}function it(e,t,o){switch(t){case"newValue":{D(o,e.token);break}case"oldValue":{Pt(e,o),o.valueMap.set(e.token.key,e.value);break}}}function Pt(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 rt(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 at(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 Ne(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":Ve(e,i,o);break;case"state_creation":nt(i,e,o);break;case"state_disposal":it(i,e,o);break;case"molecule_creation":rt(i,e,o);break;case"molecule_disposal":at(i,e,o);break;case"transaction_update":Ne(e,i,o);break}}function Vt(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 Nt=(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),Ne("newValue",o.transactionMeta.update,n),P(n))Vt(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 Y 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 Xt=(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 Y(i.atoms),atomsThatAreDefault:new Set(i.atomsThatAreDefault),families:new Y(i.families),operation:{open:!1},readonlySelectors:new Y(i.readonlySelectors),timelines:new Y(i.timelines),timelineTopics:new X(i.timelineTopics.toJSON()),trackers:new Map,transactions:new Y(i.transactions),selectorAtoms:new X(i.selectorAtoms.toJSON()),selectorGraph:new X(i.selectorGraph.toJSON(),{makeContentKey:(...c)=>c.sort().join(":")}),selectors:new Y(i.selectors),valueMap:new Y(i.valueMap),defaults:i.defaults,disposalTraces:o.disposalTraces.copy(),molecules:new Y(i.molecules),moleculeFamilies:new Y(i.moleculeFamilies),moleculeInProgress:i.moleculeInProgress,miscResources:new Y(i.miscResources)},a=Dt(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=fe())=>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:()=>ze(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 Ye(e,t){const o={key:e.key,type:"transaction",run:(r,a)=>{const s=Xt(e.key,r,t,a);try{const l=y(t),{toolkit:c}=s.transactionMeta,m=e.do(c,...r);return Nt(m,l),m}catch(l){throw gt(n),t.logger.warn("\uD83D\uDCA5","transaction",e.key,"caught:",l),l}},install:(r)=>Ye(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 Dt(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 Xe{_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 Xe([...this._buffer]);return e._index=this._index,e}}class Ht{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 Xe(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 Le(null),operationClose:new b,moleculeCreationStart:new b,moleculeCreationDone:new b,moleculeDisposal:new b};operation={open:!1};config={name:"IMPLICIT_STORE",lifespan:"ephemeral"};loggers=[new Ue("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 Ht({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 Ut=(e,t)=>{const o=y(t);if(o.operation.open)return o.operation.prev.get(e.key);return o.valueMap.get(e.key)};var st=(e,t)=>{const o=y(t);return vt(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=Ut(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=st(r,n),l=(u)=>{if(s)s.length=0,s.push(...st(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 lt=(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=lt({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 Je(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}"`),Je(c,t,o)},subject:r};if(o)a.family=o;const s=t.default();n.atoms.set(a.key,a),De(t.key,e),q(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)qt(l,t,e);return l}class ct{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 Fe(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=Je(F,C,m);return r.next({type:"state_creation",token:v}),v},n,{subject:r,install:(l)=>Fe(l,t),toJson:t.toJson,fromJson:t.fromJson,internalRoles:o});return e.families.set(t.key,s),Yt(s,t,e),new ct(s,e),n}var et=(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 Jt(e){return typeof e==="object"&&e!==null&&"do"in e&&"undo"in e&&"subscribe"in e}function Ae(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 q(e,t,o,n){const i=n.valueMap.get(e);if(i instanceof be)i.use(t);if(t instanceof Promise){const r=new be(t);return n.valueMap.set(e,r),r.then((a)=>{q(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 xt=(e,t)=>{let o=t.valueMap.get(e.key);if(e.type==="mutable_atom"&&R(t)){const{parent:n}=t;o=Ae(e,n,t)}return o},Ct=(e,t)=>{const o=t.valueMap.get(e);if(o instanceof be){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 ht=(e,t)=>{return y(t).atomsThatAreDefault.has(e)},De=(e,t)=>{const o=y(t);o.atomsThatAreDefault=new Set(o.atomsThatAreDefault).add(e)},$t=(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),De(t.key,e),q(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 bt(e,t){if("mutable"in t){const i=Je(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 ot(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);ot(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 qt=(e,t,o=K.STORE)=>{return ge(o,{key:`${e.key}:JSON`,get:({get:n})=>t.toJson(n(e)),set:({set:n},i)=>{n(e,t.fromJson(i))}})};function Yt(e,t,o=K.STORE){const n=Ce(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),_m=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];class de{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 mt extends de{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 Lt extends de{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 yt extends de{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 Lt(`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 Qt 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 ft{e;type="continuity";globals=[];actions=[];perspectives=[];constructor(e){this.key=e}static existing=new Qt;static create(e,t){const o=new ft(e),{type:n,globals:i,actions:r,perspectives:a}=t(o),s={type:n,key:e,globals:i,actions:r,perspectives:a};return ft.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 my=ue({key:"usersInRoomIndex",mutable:!0,default:()=>new z,toJson:(e)=>e.toJSON(),fromJson:(e)=>z.fromJSON(e)}),pt=ue({key:"roomIndex",default:()=>new z,mutable:!0,toJson:(e)=>e.toJSON(),fromJson:(e)=>z.fromJSON(e)}),co={enteredAtEpoch:0},we=Be({key:"usersInRooms",between:["room","user"],cardinality:"1:n"},co),yy=he({key:"usersInMyRoomView",get:(e)=>({find:t})=>{const o=Et(we);return[t(o,e)]}});import{spawn as mo}from"child_process";var ut=me({key:"roomArguments",default:["echo",["Hello World!"]]}),Zt=he({key:"room",get:(e)=>async({get:t,find:o})=>{const n=o(ut,e),i=t(n),[r,a]=i,s=await new Promise((l)=>{const c=mo(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 mt(s,e)}});var Ry=xe({key:"createRoom",do:({get:e,set:t,find:o},n,i,r)=>{const a=r?[i,r]:[i],s=o(ut,n);t(s,a),t(pt,(m)=>m.add(n));const l=o(Zt,n);return e(l)}}),Cy=xe({key:"joinRoom",do:(e,t,o,n)=>{const i={enteredAtEpoch:n};return Ee(we,(r)=>{r.set({room:t,user:o},i)},e.env().store),i}}),Ky=xe({key:"leaveRoom",do:(e,t,o)=>{Ee(we,(n)=>{n.delete({room:t,user:o})},e.env().store)}}),Jy=xe({key:"destroyRoom",do:(e,t)=>{Ee(we,(o)=>{o.delete({room:t})},e.env().store),e.set(pt,(o)=>(o.delete(t),o))}});var $y=me({key:"transactionRedactor",default:{occlude:(e)=>e}}),yo=me({key:"unacknowledgedUpdates",default:()=>[]});var fo=me({key:"sockets",default:null}),_y=ue({key:"socketsIndex",mutable:!0,default:()=>new z,toJson:(e)=>e.toJSON(),fromJson:(e)=>z.fromJSON(e)}),jy=ue({key:"usersIndex",mutable:!0,default:()=>new z,toJson:(e)=>e.toJSON(),fromJson:(e)=>z.fromJSON(e)}),po=Be({key:"usersOfSockets",between:["user","socket"],cardinality:"1:1"});var Gt=new yt;Gt.logger.info("\uD83D\uDE80","hello from game worker");process.on("exit",()=>{Gt.logger.info("\uD83D\uDE80","goodbye from game worker")});
3
+ function fe(e=Math.random){return e().toString(36).slice(2)}class be 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 St(e){while(e.parent!==null)e=e.parent;return e}function pe(e,t){const o=S(t),n=`${e.key}(${o})`,i=to[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 to={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 ue(e){return bt(K.STORE,e)}function me(e){return kt(K.STORE,e)}var He=(e)=>(t,o,n,i,...r)=>{console[e](`${t} ${o} "${n}" ${i}`,...r)},oo={error:He("error"),info:He("info"),warn:He("warn")};class Ue{e;t;o;constructor(e,t,o=oo){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 he(e){return qe(K.STORE,e)}function xe(e){return Ye(e,K.STORE)}class X{a;b;cardinality;relations=new Map;contents=new Map;isContent;makeContentKey=(e,t)=>`${e}:${t}`;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)}}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)console.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 Le 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 gt=(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(no).join(" ")}var no=(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 $e=(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"),xt(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 At=(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}"`}`)},Ft=(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)},Mt=(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)},Te=(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 Rt=(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 Qe=(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(Mt(o,i))continue;Ct(i,o),Te(o,i)}}};function io(e,t){if(Jt(t.newValue))return!1;if(e.includes("\uD83D\uDD0D"))return!1;return!0}var Kt=(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(!io(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 wt=(e,t,o)=>{const n=ie(e,o);let i=n;if(e.type==="mutable_atom"&&R(o)){const{parent:a}=o;i=Ae(e,a,o)}if(i=$e(t)(i),o.logger.info("\uD83D\uDCDD","atom",e.key,"set to",i),i=q(e.key,i,e.subject,o),ht(e.key,o))$t(e.key,o);Te(o,e.key),Qe(e,o);const r={oldValue:n,newValue:i};if(P(o))Rt(e,r,o);else if(o.parent){if(o.on.transactionApplying.state===null)Kt(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=Ae(s,m,o)}if(l.do(r.newValue)===null)Qe(s,o)}}};var Oe=(e,t,o)=>{switch(e.type){case"atom":case"mutable_atom":wt(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 kt(e,t){if("mutable"in t)return Fe(e,t);return re(e,t)}function ve(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=ve(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)??pe(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 Ie=(e,t)=>y(t).atoms.has(e),ro=(e,t)=>y(t).selectors.has(e),ao=(e,t)=>y(t).readonlySelectors.has(e),Ot=(e,t)=>Ie(e,t)||ro(e,t)||ao(e,t);var We=(e,t)=>{return y(t).selectorGraph.getRelationEntries({downstreamSelectorKey:e}).filter(([n,{source:i}])=>i!==e).map(([n,{source:i}])=>i).filter((n)=>Ot(n,t))};var Ze=(e,t,o)=>{const n=[],i=We(e,o);while(i.length>0){const r=i.shift();if(t.has(r))continue;if(t.add(r),!Ie(r,o))i.push(...We(r,o));else if(!n.includes(r))n.push(r)}return n},vt=(e,t)=>{const o=e.key,n=We(o,t),i=new Set;return n.flatMap((r)=>Ie(r,t)?r:Ze(r,i,t))};var It=(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=Ze(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 _e=(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}),It(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);Oe(s,r,a)},find:(n,i)=>h(o,n,i),seek:(n,i)=>$(o,n,i),json:(n)=>V(o,n)});var Me=(e,t,o)=>{const n=y(e),i=new b,r=new Set,{get:a,find:s,seek:l,json:c}=_e(t.key,r,n),m=()=>{const v=t.get({get:a,find:s,seek:l,json:c});return q(t.key,v,i,y(e)),r.clear(),v},u={...t,subject:i,install:(v)=>Me(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 Re=(e,t,o)=>{const n=y(e),i=new b,r=new Set,a=_e(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 q(t.key,w,i,W),r.clear(),w},v={...t,subject:i,install:(I)=>Re(I,t,o),get:F,set:(I)=>{const W=y(e),w=F(t.get,W),L=$e(I)(w);if(e.logger.info("\uD83D\uDCDD","selector",t.key,"set (",w,"->",L,")"),q(t.key,L,i,W),Te(W,t.key),P(W))i.next({newValue:L,oldValue:w});t.set(a,L)},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 ge(e,t){if("set"in t){const i=Re(e,t,void 0);return e.on.selectorCreation.next(i),i}const n=Me(e,t,void 0);return e.on.selectorCreation.next(n),n}function Wt(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=Me(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 Ce(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=Re(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)=>Ce(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 qe(e,t){if("set"in t)return Ce(e,t);return le(e,t)}function je(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")je(c,t);else if(c.above.delete(o.stringKey),c.above.size===0)je(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 _t(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 Be(e,t,o=K.STORE){return Ge(o).set(e.key,new tt(e,t,o)),{key:e.key,type:"join",a:e.between[0],b:e.between[1],cardinality:e.cardinality}}function Ge(e){if("joins"in e&&e.joins instanceof Map)return e.joins;const t=new Map;return e.joins=t,t}function Ke(e,t){const o=Ge(t);let n=o.get(e.key);if(n===void 0){if(n=Ge(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 jt(e,t,o){const n=Ke(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 Bt(e,t){return jt(e,t,K.STORE)}function Ee(e,t,o){const n=Ke(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 lo(e,t){return Ke(e,t).core.findRelatedKeysState}function Et(e){return lo(e,K.STORE)}class tt{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 tt(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=Fe(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),Tt=ee.has(p);if(this.relations.cardinality==="1:n"){const dt=[];for(let Se of ee){if(Se===p)continue;const ke=a(f,Se);if(ke.delete(ne),ke.size===0)dt.push(Se)}if(!Tt&&ee.size>0)ee.clear();for(let Se of dt){const ke=[ne,Se].sort(),eo=`"${ke[0]}:${ke[1]}"`;this.molecules.delete(eo)}}if(!Tt)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=_t(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=et(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"]),L=()=>le(o,{key:`${e.key}/multipleRelatedEntries`,get:(f)=>({get:p})=>{const g=et(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=L(),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=L(),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 ze(e){return{store:e}}class Pe{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 zt(e){return e[0].toUpperCase()+e.slice(1)}function oe(e,t,o,n,...i){const r=St(e),a=y(e),s=S(n);a.moleculeInProgress=s;const l=Array.isArray(t)?t:[t],c=l.map((k)=>{if(k instanceof Pe)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 Pe(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=fe())=>ye(k,I,y(e)),make:(k,I,W,...w)=>oe(y(r),k,I,W,...w),dispose:(k)=>{D(y(r),k)},env:()=>ze(y(r)),bond:(k,I)=>{if(k.type==="join"){const{as:W}=I,w=Ke(k,r);w.molecules.set(s,m),m.joins.set(k.key,w);const L=F.subject.subscribe(`join:${k.key}-${s}`,(T)=>{if(T.type==="molecule_disposal"&&S(T.token.key)===s)L(),w.molecules.delete(s)});if(W===null)return;const f=k.a===W?k.b:k.a,p=Bt(k,n),g=p[`${f}KeysOf${zt(W)}`],x=p[`${f}EntriesOf${zt(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 L of w.above.values())L.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=pe(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)??pe(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":ot(o,e);break;case"selector":case"readonly_selector":Wt(o,e);break;case"molecule":je(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=ve(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=At(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);Oe(s,r,e),Ft(e)}function Ve(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 nt(e,t,o){switch(t){case"newValue":{Pt(e,o);break}case"oldValue":{D(o,e.token);break}}}function it(e,t,o){switch(t){case"newValue":{D(o,e.token);break}case"oldValue":{Pt(e,o),o.valueMap.set(e.token.key,e.value);break}}}function Pt(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 rt(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 at(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 Ne(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":Ve(e,i,o);break;case"state_creation":nt(i,e,o);break;case"state_disposal":it(i,e,o);break;case"molecule_creation":rt(i,e,o);break;case"molecule_disposal":at(i,e,o);break;case"transaction_update":Ne(e,i,o);break}}function Vt(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 Nt=(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),Ne("newValue",o.transactionMeta.update,n),P(n))Vt(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 Y 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 Xt=(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 Y(i.atoms),atomsThatAreDefault:new Set(i.atomsThatAreDefault),families:new Y(i.families),operation:{open:!1},readonlySelectors:new Y(i.readonlySelectors),timelines:new Y(i.timelines),timelineTopics:new X(i.timelineTopics.toJSON()),trackers:new Map,transactions:new Y(i.transactions),selectorAtoms:new X(i.selectorAtoms.toJSON()),selectorGraph:new X(i.selectorGraph.toJSON(),{makeContentKey:(...c)=>c.sort().join(":")}),selectors:new Y(i.selectors),valueMap:new Y(i.valueMap),defaults:i.defaults,disposalTraces:o.disposalTraces.copy(),molecules:new Y(i.molecules),moleculeFamilies:new Y(i.moleculeFamilies),moleculeInProgress:i.moleculeInProgress,miscResources:new Y(i.miscResources)},a=Dt(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=fe())=>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:()=>ze(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 Ye(e,t){const o={key:e.key,type:"transaction",run:(r,a)=>{const s=Xt(e.key,r,t,a);try{const l=y(t),{toolkit:c}=s.transactionMeta,m=e.do(c,...r);return Nt(m,l),m}catch(l){throw gt(n),t.logger.warn("\uD83D\uDCA5","transaction",e.key,"caught:",l),l}},install:(r)=>Ye(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 Dt(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 Xe{_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 Xe([...this._buffer]);return e._index=this._index,e}}class Ht{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 Xe(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 Le(null),operationClose:new b,moleculeCreationStart:new b,moleculeCreationDone:new b,moleculeDisposal:new b};operation={open:!1};config={name:"IMPLICIT_STORE",lifespan:"ephemeral"};loggers=[new Ue("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 Ht({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 Ut=(e,t)=>{const o=y(t);if(o.operation.open)return o.operation.prev.get(e.key);return o.valueMap.get(e.key)};var st=(e,t)=>{const o=y(t);return vt(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=Ut(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=st(r,n),l=(u)=>{if(s)s.length=0,s.push(...st(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 lt=(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=lt({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 Je(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}"`),Je(c,t,o)},subject:r};if(o)a.family=o;const s=t.default();n.atoms.set(a.key,a),De(t.key,e),q(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)qt(l,t,e);return l}class ct{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 Fe(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=Je(F,C,m);return r.next({type:"state_creation",token:v}),v},n,{subject:r,install:(l)=>Fe(l,t),toJson:t.toJson,fromJson:t.fromJson,internalRoles:o});return e.families.set(t.key,s),Yt(s,t,e),new ct(s,e),n}var et=(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 Jt(e){return typeof e==="object"&&e!==null&&"do"in e&&"undo"in e&&"subscribe"in e}function Ae(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 q(e,t,o,n){const i=n.valueMap.get(e);if(i instanceof be)i.use(t);if(t instanceof Promise){const r=new be(t);return n.valueMap.set(e,r),r.then((a)=>{q(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 xt=(e,t)=>{let o=t.valueMap.get(e.key);if(e.type==="mutable_atom"&&R(t)){const{parent:n}=t;o=Ae(e,n,t)}return o},Ct=(e,t)=>{const o=t.valueMap.get(e);if(o instanceof be){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 ht=(e,t)=>{return y(t).atomsThatAreDefault.has(e)},De=(e,t)=>{const o=y(t);o.atomsThatAreDefault=new Set(o.atomsThatAreDefault).add(e)},$t=(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),De(t.key,e),q(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 bt(e,t){if("mutable"in t){const i=Je(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 ot(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);ot(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 qt=(e,t,o=K.STORE)=>{return ge(o,{key:`${e.key}:JSON`,get:({get:n})=>t.toJson(n(e)),set:({set:n},i)=>{n(e,t.fromJson(i))}})};function Yt(e,t,o=K.STORE){const n=Ce(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),_m=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];class de{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 mt extends de{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 Lt extends de{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 yt extends de{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 Lt(`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 Qt 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 ft{e;type="continuity";globals=[];actions=[];perspectives=[];constructor(e){this.key=e}static existing=new Qt;static create(e,t){const o=new ft(e),{type:n,globals:i,actions:r,perspectives:a}=t(o),s={type:n,key:e,globals:i,actions:r,perspectives:a};return ft.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 my=ue({key:"usersInRoomIndex",mutable:!0,default:()=>new z,toJson:(e)=>e.toJSON(),fromJson:(e)=>z.fromJSON(e)}),pt=ue({key:"roomIndex",default:()=>new z,mutable:!0,toJson:(e)=>e.toJSON(),fromJson:(e)=>z.fromJSON(e)}),co={enteredAtEpoch:0},we=Be({key:"usersInRooms",between:["room","user"],cardinality:"1:n"},co),yy=he({key:"usersInMyRoomView",get:(e)=>({find:t})=>{const o=Et(we);return[t(o,e)]}});import{spawn as mo}from"child_process";var ut=me({key:"roomArguments",default:["echo",["Hello World!"]]}),Zt=he({key:"room",get:(e)=>async({get:t,find:o})=>{const n=o(ut,e),i=t(n),[r,a]=i,s=await new Promise((l)=>{const c=mo(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 mt(s,e)}});var Ry=xe({key:"createRoom",do:({get:e,set:t,find:o},n,i,r)=>{const a=r?[i,r]:[i],s=o(ut,n);t(s,a),t(pt,(m)=>m.add(n));const l=o(Zt,n);return e(l)}}),Cy=xe({key:"joinRoom",do:(e,t,o,n)=>{const i={enteredAtEpoch:n};return Ee(we,(r)=>{r.set({room:t,user:o},i)},e.env().store),i}}),Ky=xe({key:"leaveRoom",do:(e,t,o)=>{Ee(we,(n)=>{n.delete({room:t,user:o})},e.env().store)}}),Jy=xe({key:"destroyRoom",do:(e,t)=>{Ee(we,(o)=>{o.delete({room:t})},e.env().store),e.set(pt,(o)=>(o.delete(t),o))}});var $y=me({key:"transactionRedactor",default:{occlude:(e)=>e}}),yo=me({key:"unacknowledgedUpdates",default:()=>[]});var fo=me({key:"sockets",default:null}),_y=ue({key:"socketsIndex",mutable:!0,default:()=>new z,toJson:(e)=>e.toJSON(),fromJson:(e)=>z.fromJSON(e)}),jy=ue({key:"usersIndex",mutable:!0,default:()=>new z,toJson:(e)=>e.toJSON(),fromJson:(e)=>z.fromJSON(e)}),po=Be({key:"usersOfSockets",between:["user","socket"],cardinality:"1:1"});var Gt=new yt;process.on("exit",()=>{Gt.logger.info("\uD83D\uDEEC game worker exiting")});Gt.logger.info("\uD83D\uDEEB game worker ready");
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{join as G,normalize as H,resolve as A}from"path";var{file:y,serve:I}=globalThis.Bun;var k=A(import.meta.dir,"..","app");I({port:process.env.PORT??8080,static:{"/":new Response(await Bun.file(A(k,"index.html")).bytes(),{headers:{"Content-Type":"text/html"}})},async fetch(c,B){const x=new URL(c.url),C=B.requestIP(c)?.address??"??";console.log(`[${C}]`,c.method,x.pathname);const F=G(k,x.pathname),g=H(F);if(!g.startsWith(k))return new Response("403: Forbidden",{status:403});return await y(g).exists()?new Response(y(g)):new Response("404: Not Found",{status:404})}});console.log(`Server running at http://localhost:${process.env.PORT??8080}/`);
2
+ import{join as ko,normalize as bo,resolve as oo}from"path";function fe(e=Math.random){return e().toString(36).slice(2)}class be 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 bt(e){while(e.parent!==null)e=e.parent;return e}function pe(e,t){const o=S(t),n=`${e.key}(${o})`,i=io[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 io={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 ue(e){return xt(K.STORE,e)}function me(e){return gt(K.STORE,e)}var Ue=(e)=>(t,o,n,i,...r)=>{console[e](`${t} ${o} "${n}" ${i}`,...r)},ro={error:Ue("error"),info:Ue("info"),warn:Ue("warn")};class Ye{e;t;o;constructor(e,t,o=ro){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 he(e){return Le(K.STORE,e)}function xe(e){return qe(e,K.STORE)}class X{a;b;cardinality;relations=new Map;contents=new Map;isContent;makeContentKey=(e,t)=>`${e}:${t}`;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)}}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)console.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 At=(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(ao).join(" ")}var ao=(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 $e=(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"),Ft(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 Mt=(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}"`}`)},Rt=(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)},Ct=(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)},Te=(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 Kt=(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(Ct(o,i))continue;Jt(i,o),Te(o,i)}}};function lo(e,t){if(ht(t.newValue))return!1;if(e.includes("\uD83D\uDD0D"))return!1;return!0}var wt=(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(!lo(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 $t=(e,t,o)=>{const n=ie(e,o);let i=n;if(e.type==="mutable_atom"&&R(o)){const{parent:a}=o;i=Ae(e,a,o)}if(i=$e(t)(i),o.logger.info("\uD83D\uDCDD","atom",e.key,"set to",i),i=Y(e.key,i,e.subject,o),Ot(e.key,o))vt(e.key,o);Te(o,e.key),Ze(e,o);const r={oldValue:n,newValue:i};if(P(o))Kt(e,r,o);else if(o.parent){if(o.on.transactionApplying.state===null)wt(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=Ae(s,m,o)}if(l.do(r.newValue)===null)Ze(s,o)}}};var Oe=(e,t,o)=>{switch(e.type){case"atom":case"mutable_atom":$t(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 gt(e,t){if("mutable"in t)return Fe(e,t);return re(e,t)}function ve(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=ve(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)??pe(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 Ie=(e,t)=>y(t).atoms.has(e),so=(e,t)=>y(t).selectors.has(e),co=(e,t)=>y(t).readonlySelectors.has(e),It=(e,t)=>Ie(e,t)||so(e,t)||co(e,t);var We=(e,t)=>{return y(t).selectorGraph.getRelationEntries({downstreamSelectorKey:e}).filter(([n,{source:i}])=>i!==e).map(([n,{source:i}])=>i).filter((n)=>It(n,t))};var Ge=(e,t,o)=>{const n=[],i=We(e,o);while(i.length>0){const r=i.shift();if(t.has(r))continue;if(t.add(r),!Ie(r,o))i.push(...We(r,o));else if(!n.includes(r))n.push(r)}return n},Wt=(e,t)=>{const o=e.key,n=We(o,t),i=new Set;return n.flatMap((r)=>Ie(r,t)?r:Ge(r,i,t))};var _t=(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 _e=(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}),_t(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);Oe(s,r,a)},find:(n,i)=>h(o,n,i),seek:(n,i)=>$(o,n,i),json:(n)=>V(o,n)});var Me=(e,t,o)=>{const n=y(e),i=new b,r=new Set,{get:a,find:s,seek:l,json:c}=_e(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)=>Me(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 Re=(e,t,o)=>{const n=y(e),i=new b,r=new Set,a=_e(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)=>Re(I,t,o),get:F,set:(I)=>{const W=y(e),w=F(t.get,W),q=$e(I)(w);if(e.logger.info("\uD83D\uDCDD","selector",t.key,"set (",w,"->",q,")"),Y(t.key,q,i,W),Te(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 ge(e,t){if("set"in t){const i=Re(e,t,void 0);return e.on.selectorCreation.next(i),i}const n=Me(e,t,void 0);return e.on.selectorCreation.next(n),n}function jt(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=Me(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 Ce(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=Re(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)=>Ce(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 Ce(e,t);return le(e,t)}function je(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())H(t,c);for(let c of o.below.values())if(c.family?.dependsOn==="all")je(c,t);else if(c.above.delete(o.stringKey),c.above.size===0)je(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 Bt(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 Be(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 Ke(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 Et(e,t,o){const n=Ke(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 zt(e,t){return Et(e,t,K.STORE)}function Ee(e,t,o){const n=Ke(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 mo(e,t){return Ke(e,t).core.findRelatedKeysState}function Pt(e){return mo(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)=>{H(o,...f)}};const n=e.between[0],i=e.between[1],r=Fe(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),St=ee.has(p);if(this.relations.cardinality==="1:n"){const kt=[];for(let Se of ee){if(Se===p)continue;const ke=a(f,Se);if(ke.delete(ne),ke.size===0)kt.push(Se)}if(!St&&ee.size>0)ee.clear();for(let Se of kt){const ke=[ne,Se].sort(),no=`"${ke[0]}:${ke[1]}"`;this.molecules.delete(no)}}if(!St)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=Bt(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 ze(e){return{store:e}}class Pe{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 Vt(e){return e[0].toUpperCase()+e.slice(1)}function oe(e,t,o,n,...i){const r=bt(e),a=y(e),s=S(n);a.moleculeInProgress=s;const l=Array.isArray(t)?t:[t],c=l.map((k)=>{if(k instanceof Pe)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 Pe(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=fe())=>ye(k,I,y(e)),make:(k,I,W,...w)=>oe(y(r),k,I,W,...w),dispose:(k)=>{H(y(r),k)},env:()=>ze(y(r)),bond:(k,I)=>{if(k.type==="join"){const{as:W}=I,w=Ke(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=zt(k,n),g=p[`${f}KeysOf${Vt(W)}`],x=p[`${f}EntriesOf${Vt(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=pe(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 H(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)??pe(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":jt(o,e);break;case"molecule":je(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=ve(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=Mt(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);Oe(s,r,e),Rt(e)}function Ve(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":{Nt(e,o);break}case"oldValue":{H(o,e.token);break}}}function rt(e,t,o){switch(t){case"newValue":{H(o,e.token);break}case"oldValue":{Nt(e,o),o.valueMap.set(e.token.key,e.value);break}}}function Nt(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":H(o,e.token);break}}function lt(e,t,o){switch(t){case"newValue":H(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 Ne(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":Ve(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":Ne(e,i,o);break}}function Xt(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 Ht=(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),Ne("newValue",o.transactionMeta.update,n),P(n))Xt(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 Dt=(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=Ut(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=fe())=>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)=>{H(l,...c)},env:()=>ze(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=Dt(e.key,r,t,a);try{const l=y(t),{toolkit:c}=s.transactionMeta,m=e.do(c,...r);return Ht(m,l),m}catch(l){throw At(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 Ut(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 Xe{_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 Xe([...this._buffer]);return e._index=this._index,e}}class Yt{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 Xe(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 Yt({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 Lt=(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 Wt(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=Lt(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 D(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=D(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}`;D(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 Je(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}"`),Je(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)=>D(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)qt(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 Fe(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=Je(F,C,m);return r.next({type:"state_creation",token:v}),v},n,{subject:r,install:(l)=>Fe(l,t),toJson:t.toJson,fromJson:t.fromJson,internalRoles:o});return e.families.set(t.key,s),Qt(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 ht(e){return typeof e==="object"&&e!==null&&"do"in e&&"undo"in e&&"subscribe"in e}function Ae(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 be)i.use(t);if(t instanceof Promise){const r=new be(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 Ft=(e,t)=>{let o=t.valueMap.get(e.key);if(e.type==="mutable_atom"&&R(t)){const{parent:n}=t;o=Ae(e,n,t)}return o},Jt=(e,t)=>{const o=t.valueMap.get(e);if(o instanceof be){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 Ot=(e,t)=>{return y(t).atomsThatAreDefault.has(e)},He=(e,t)=>{const o=y(t);o.atomsThatAreDefault=new Set(o.atomsThatAreDefault).add(e)},vt=(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)=>D(l,C,`effect[${c}]`,e)});if(F)m.push(F);++c}a.cleanup=()=>{for(let u of m)u()}}return l}function xt(e,t){if("mutable"in t){const i=Je(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 qt=(e,t,o=K.STORE)=>{return ge(o,{key:`${e.key}:JSON`,get:({get:n})=>t.toJson(n(e)),set:({set:n},i)=>{n(e,t.fromJson(i))}})};function Qt(e,t,o=K.STORE){const n=Ce(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),Vm=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];class de{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 de{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 Zt extends de{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 de{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 Zt(`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 Gt 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 Gt;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 dy=ue({key:"usersInRoomIndex",mutable:!0,default:()=>new z,toJson:(e)=>e.toJSON(),fromJson:(e)=>z.fromJSON(e)}),ut=ue({key:"roomIndex",default:()=>new z,mutable:!0,toJson:(e)=>e.toJSON(),fromJson:(e)=>z.fromJSON(e)}),fo={enteredAtEpoch:0},we=Be({key:"usersInRooms",between:["room","user"],cardinality:"1:n"},fo),Sy=he({key:"usersInMyRoomView",get:(e)=>({find:t})=>{const o=Pt(we);return[t(o,e)]}});import{spawn as po}from"child_process";var Tt=me({key:"roomArguments",default:["echo",["Hello World!"]]}),eo=he({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=po(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 $y=xe({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(eo,n);return e(l)}}),Oy=xe({key:"joinRoom",do:(e,t,o,n)=>{const i={enteredAtEpoch:n};return Ee(we,(r)=>{r.set({room:t,user:o},i)},e.env().store),i}}),vy=xe({key:"leaveRoom",do:(e,t,o)=>{Ee(we,(n)=>{n.delete({room:t,user:o})},e.env().store)}}),Iy=xe({key:"destroyRoom",do:(e,t)=>{Ee(we,(o)=>{o.delete({room:t})},e.env().store),e.set(ut,(o)=>(o.delete(t),o))}});var jy=me({key:"transactionRedactor",default:{occlude:(e)=>e}}),uo=me({key:"unacknowledgedUpdates",default:()=>[]});var To=me({key:"sockets",default:null}),Vy=ue({key:"socketsIndex",mutable:!0,default:()=>new z,toJson:(e)=>e.toJSON(),fromJson:(e)=>z.fromJSON(e)}),Ny=ue({key:"usersIndex",mutable:!0,default:()=>new z,toJson:(e)=>e.toJSON(),fromJson:(e)=>z.fromJSON(e)}),So=Be({key:"usersOfSockets",between:["user","socket"],cardinality:"1:1"});var{file:to,serve:go}=globalThis.Bun;var De=new ft;De.logger.info(" ready");var dt=oo(import.meta.dir,"..","app");go({port:process.env.PORT??8080,static:{"/":new Response(await Bun.file(oo(dt,"index.html")).bytes(),{headers:{"Content-Type":"text/html"}})},async fetch(e,t){const o=new URL(e.url),n=t.requestIP(e)?.address??"??";De.logger.info(`[${n}]`,e.method,o.pathname);const i=ko(dt,o.pathname),r=bo(i);if(!r.startsWith(dt))return new Response("403: Forbidden",{status:403});return await to(r).exists()?new Response(to(r)):new Response("404: Not Found",{status:404})}});process.on("exit",()=>{De.logger.info("\uD83D\uDEEC frontend server exiting")});De.logger.info(`\uD83D\uDEEB frontend server running at http://localhost:${process.env.FRONTEND_PORT??3333}/`);
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "tempest.games",
3
- "version": "0.0.4",
3
+ "version": "0.0.6",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
7
7
  "type": "module",
8
8
  "bin": {
9
9
  "frontend": "./bin/frontend.bun.js",
10
- "backend": "./bin/backend.node.js"
10
+ "backend": "./bin/backend.bun.js"
11
11
  },
12
12
  "files": [
13
13
  "app",
@@ -24,7 +24,7 @@
24
24
  "@eslint/js": "9.10.0",
25
25
  "@types/bun": "1.1.9",
26
26
  "@types/node": "22.5.5",
27
- "@types/react": "18.3.6",
27
+ "@types/react": "18.3.7",
28
28
  "@types/react-dom": "18.3.0",
29
29
  "@vitejs/plugin-react-swc": "3.7.0",
30
30
  "concurrently": "9.0.1",
@@ -41,15 +41,15 @@
41
41
  "scripts": {
42
42
  "dev": "concurrently \"bun:dev:*\"",
43
43
  "dev:vite": "vite --port 3333",
44
- "dev:backend": "cross-env MODE=development PORT=4444 tsx --watch ./src/backend.node.ts",
44
+ "dev:backend": "cross-env MODE=development PORT=4444 bun --hot ./src/backend.bun.ts",
45
45
  "build": "rimraf ./bin && concurrently \"bun:build:*\"",
46
46
  "build:vite": "vite build --outDir ./app",
47
47
  "build:frontend": "bun build ./src/frontend.bun.ts --outdir ./bin --bundle --minify --target bun",
48
- "build:backend": "bun build ./src/backend.node.ts --outdir ./bin --bundle --minify --target node",
48
+ "build:backend": "bun build ./src/backend.bun.ts --outdir ./bin --bundle --minify --target bun",
49
49
  "build:backend:game": "bun build ./src/backend.worker.game.bun.ts --outdir ./bin --bundle --minify --target bun",
50
50
  "preview": "concurrently \"bun:preview:*\"",
51
51
  "preview:frontend": "bun ./bin/frontend.bun.js",
52
- "preview:backend": "bun ./bin/backend.node.js",
52
+ "preview:backend": "bun ./bin/backend.bun.js",
53
53
  "test": "echo no tests yet",
54
54
  "lint:biome": "biome check -- .",
55
55
  "lint:eslint": "eslint --flag unstable_ts_config -- .",
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env node
2
- import{spawn as fo}from"node:child_process";import{resolve as po}from"node:path";function fe(e=Math.random){return e().toString(36).slice(2)}class ke 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 dt(e){while(e.parent!==null)e=e.parent;return e}function pe(e,t){const o=k(t),n=`${e.key}(${o})`,i=Gt[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 Gt={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 ue(e){return kt(K.STORE,e)}function me(e){return St(K.STORE,e)}var Ue=(e)=>(t,o,n,i,...r)=>{console[e](`${t} ${o} "${n}" ${i}`,...r)},eo={error:Ue("error"),info:Ue("info"),warn:Ue("warn")};class qe{e;t;o;constructor(e,t,o=eo){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 he(e){return Ye(K.STORE,e)}function ge(e){return Le(e,K.STORE)}class X{a;b;cardinality;relations=new Map;contents=new Map;isContent;makeContentKey=(e,t)=>`${e}:${t}`;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)}}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)console.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 x{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 x{state;constructor(e){super();this.state=e}next(e){this.state=e,super.next(e)}}function E(e){return"epoch"in e.transactionMeta}function R(e){return"phase"in e.transactionMeta}var bt=(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(to).join(" ")}var to=(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)} ${k(t.key)} not found in store "${o.config.name}".`);else{const n=e[1];super(`${Q(t)} "${t.key}" member ${k(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 $e=(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"),gt(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 xt=(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}"`}`)},At=(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)},Ft=(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)},Te=(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 Mt=(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(Ft(o,i))continue;Rt(i,o),Te(o,i)}}};function oo(e,t){if(Kt(t.newValue))return!1;if(e.includes("\uD83D\uDD0D"))return!1;return!0}var Ct=(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(!oo(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 Jt=(e,t,o)=>{const n=ie(e,o);let i=n;if(e.type==="mutable_atom"&&R(o)){const{parent:a}=o;i=xe(e,a,o)}if(i=$e(t)(i),o.logger.info("\uD83D\uDCDD","atom",e.key,"set to",i),i=q(e.key,i,e.subject,o),wt(e.key,o))ht(e.key,o);Te(o,e.key),Ze(e,o);const r={oldValue:n,newValue:i};if(E(o))Mt(e,r,o);else if(o.parent){if(o.on.transactionApplying.state===null)Ct(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=xe(s,m,o)}if(l.do(r.newValue)===null)Ze(s,o)}}};var Oe=(e,t,o)=>{switch(e.type){case"atom":case"mutable_atom":Jt(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 x,s=Object.assign((l)=>{const c=k(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 St(e,t){if("mutable"in t)return Ae(e,t);return re(e,t)}function ve(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=ve(e,o)??null,n)i=o.family?P(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)??pe(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 Ie=(e,t)=>y(t).atoms.has(e),no=(e,t)=>y(t).selectors.has(e),io=(e,t)=>y(t).readonlySelectors.has(e),$t=(e,t)=>Ie(e,t)||no(e,t)||io(e,t);var We=(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=We(e,o);while(i.length>0){const r=i.shift();if(t.has(r))continue;if(t.add(r),!Ie(r,o))i.push(...We(r,o));else if(!n.includes(r))n.push(r)}return n},Ot=(e,t)=>{const o=e.key,n=We(o,t),i=new Set;return n.flatMap((r)=>Ie(r,t)?r:Ge(r,i,t))};var vt=(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 _e=(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}),vt(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);Oe(s,r,a)},find:(n,i)=>h(o,n,i),seek:(n,i)=>$(o,n,i),json:(n)=>V(o,n)});var Fe=(e,t,o)=>{const n=y(e),i=new x,r=new Set,{get:a,find:s,seek:l,json:c}=_e(t.key,r,n),m=()=>{const v=t.get({get:a,find:s,seek:l,json:c});return q(t.key,v,i,y(e)),r.clear(),v},u={...t,subject:i,install:(v)=>Fe(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 Me=(e,t,o)=>{const n=y(e),i=new x,r=new Set,a=_e(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 q(t.key,w,i,W),r.clear(),w},v={...t,subject:i,install:(I)=>Me(I,t,o),get:F,set:(I)=>{const W=y(e),w=F(t.get,W),L=$e(I)(w);if(e.logger.info("\uD83D\uDCDD","selector",t.key,"set (",w,"->",L,")"),q(t.key,L,i,W),Te(W,t.key),E(W))i.next({newValue:L,oldValue:w});t.set(a,L)},type:"selector",...o&&{family:o}};n.selectors.set(t.key,v);const G=F();e.logger.info("\u2728",v.type,v.key,"=",G);const S={key:t.key,type:"selector"};if(o)S.family=o;return S};function be(e,t){if("set"in t){const i=Me(e,t,void 0);return e.on.selectorCreation.next(i),i}const n=Fe(e,t,void 0);return e.on.selectorCreation.next(n),n}function It(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 x,s=Object.assign((l)=>{const c=k(l),m={key:t.key,subKey:c},u=`${t.key}(${c})`,F=y(e),C=Fe(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 Re(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 x,s=Object.assign((l)=>{const c=k(l),m={key:t.key,subKey:c},u=`${t.key}(${c})`,F=y(e),C=Me(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)=>Re(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 Ye(e,t){if("set"in t)return Re(e,t);return le(e,t)}function je(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")je(c,t);else if(c.above.delete(o.stringKey),c.above.size===0)je(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 Wt(e,t){const o=new x,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 x;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:${k(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:${k(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 Be(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 Ce(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 _t(e,t,o){const n=Ce(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 jt(e,t){return _t(e,t,K.STORE)}function Ee(e,t,o){const n=Ce(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 ro(e,t){return Ce(e,t).core.findRelatedKeysState}function Bt(e){return ro(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 b=this.toolkit.seek(f,p);if(b)return b;const g=this.molecules.get(k(p));if(g){const A=d(f,o);return Z(g,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=Ae(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,b)=>{const{set:g}=f,A=this.retrieve(r,p),T=this.retrieve(r,b);g(A,(M)=>M.add(b)),g(T,(M)=>M.add(p))},l=(f,p,b)=>{const{set:g}=f,A=this.retrieve(r,p),T=this.retrieve(r,b);let M,J;g(A,(B)=>{if(B.delete(b),B.size===0)M=`"${p}"`;return B}),g(T,(B)=>{if(B.delete(p),B.size===0)J=`"${b}"`;return B})},c=(f,p,b)=>{const{get:g,set:A}=f,T=this.retrieve(r,p),M=g(T);for(let J of M){if(b.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 b){const ee=a(f,ne),ut=ee.has(p);if(this.relations.cardinality==="1:n"){const Tt=[];for(let de of ee){if(de===p)continue;const Se=a(f,de);if(Se.delete(ne),Se.size===0)Tt.push(de)}if(!ut&&ee.size>0)ee.clear();for(let de of Tt){const Se=[ne,de].sort(),Zt=`"${Se[0]}:${Se[1]}"`;this.molecules.delete(Zt)}}if(!ut)ee.add(p);B.add(ne)}return!0}),J})},m=(f,p,b)=>{const{set:g}=f,A=this.retrieve(r,p);g(A,(T)=>{return T.transaction((M)=>{for(let J of b)M.add(J);return!0}),T});for(let T of b){const M=this.retrieve(r,T);g(M,(J)=>{return J.add(p),J})}return!0},u=(f,p,b)=>{const g=a(f,p);return b?g.has(b):g.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=Wt(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)),b=({set:T},M,J)=>{T(this.retrieve(v,M),J)},g=(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)=>{b(this.toolkit,T,M)},deleteContent:(T)=>{g(this.toolkit,T)}})}else C=F;const S=new X(e,{externalStore:C,makeContentKey:(...f)=>{const p=f.sort(),b=`${p[0]}:${p[1]}`,[g,A]=p.map((T)=>this.molecules.get(k(T)));if(o.config.lifespan==="immortal"&&g&&A){const T=y(o),M=oe(T,[g,A],G,b);this.molecules.set(`"${b}"`,d(M,T))}return b}}),I=()=>le(o,{key:`${e.key}/singleRelatedKey`,get:(f)=>({get:p})=>{const b=this.retrieve(r,f),g=p(b);for(let A of g)return A;return null}},["join","keys"]),W=()=>{return le(o,{key:`${e.key}/multipleRelatedKeys`,get:(f)=>({get:p})=>{const b=tt(r,o),g=this.retrieve(b,f);return p(g).members}},["join","keys"])},w=()=>le(o,{key:`${e.key}/singleRelatedEntry`,get:(f)=>({get:p})=>{const b=this.retrieve(r,f),g=p(b);for(let A of g){const T=S.makeContentKey(f,A),M=this.retrieve(v,T),J=p(M);return[A,J]}return null}},["join","entries"]),L=()=>le(o,{key:`${e.key}/multipleRelatedEntries`,get:(f)=>({get:p})=>{const b=tt(r,o),g=this.retrieve(b,f);return p(g).members.map((T)=>{const M=S.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)}`,b=`${i}KeyOf${O(n)}`,g={[p]:f,[b]: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(g,B)}else A=g;this.relations=S,this.states=A;break}case"1:n":{const f=I(),p=W(),b=`${n}KeyOf${O(i)}`,g=`${i}KeysOf${O(n)}`,A={[b]:f,[g]:p};let T;if(t){const M=w(),J=L(),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=S,this.states=T;break}default:{const f=W(),p=`${n}KeysOf${O(i)}`,b=`${i}KeysOf${O(n)}`,g={[p]:f,[b]:f};let A;if(t){const T=L(),M=`${n}EntriesOf${O(i)}`,J=`${i}EntriesOf${O(n)}`,B={[M]:T,[J]:T};A=Object.assign(g,B)}else A=g;this.relations=S,this.states=A}}}}function ze(e){return{store:e}}class Pe{t;type="molecule";stringKey;family;subject=new x;tokens=new Map;above=new Map;below=new Map;joins=new Map;instance;constructor(e,t,o){this.key=t;if(this.stringKey=k(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 Et(e){return e[0].toUpperCase()+e.slice(1)}function oe(e,t,o,n,...i){const r=dt(e),a=y(e),s=k(n);a.moleculeInProgress=s;const l=Array.isArray(t)?t:[t],c=l.map((S)=>{if(S instanceof Pe)return S;const I=k(S.key),W=e.molecules.get(I);if(!W)throw new Error(`Molecule ${I} not found in store "${e.config.name}"`);return W}),m=new Pe(c,n,o);a.molecules.set(s,m);for(let S of c)S.below.set(m.stringKey,m);const u={get:(...S)=>_(y(r),...S),set:(...S)=>{j(y(r),...S)},seek:(S,I)=>$(y(r),S,I),json:(S)=>V(y(r),S),run:(S,I=fe())=>ye(S,I,y(e)),make:(S,I,W,...w)=>oe(y(r),S,I,W,...w),dispose:(S)=>{D(y(r),S)},env:()=>ze(y(r)),bond:(S,I)=>{if(S.type==="join"){const{as:W}=I,w=Ce(S,r);w.molecules.set(s,m),m.joins.set(S.key,w);const L=F.subject.subscribe(`join:${S.key}-${s}`,(T)=>{if(T.type==="molecule_disposal"&&k(T.token.key)===s)L(),w.molecules.delete(s)});if(W===null)return;const f=S.a===W?S.b:S.a,p=jt(S,n),b=p[`${f}KeysOf${Et(W)}`],g=p[`${f}EntriesOf${Et(W)}`];let A={relatedKeys:b};if(g)A=Object.assign(A,{relatedEntries:g});return A}return Z(m,d(S,r),y(r))},claim:(S,I)=>{const{exclusive:W}=I,w=y(e).molecules.get(k(S.key));if(w)if(W){for(let L of w.above.values())L.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:(S,I,...W)=>oe(y(e),[m],d(S,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(E(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(E(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=k(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(k(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(k(o));if(i)return Z(i,t,e);if(e.config.lifespan==="immortal"){const r=pe(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)??pe(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":It(o,e);break;case"molecule":je(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=ve(e,o)??null,n)i=o.family?P(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=xt(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);Oe(s,r,e),At(e)}function Ve(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":{zt(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":{zt(e,o),o.valueMap.set(e.token.key,e.value);break}}}function zt(e,t){const{family:o}=e.token;if(o){const n=t.families.get(o.key);if(n)h(t,n,P(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}(${k(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 Ne(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":Ve(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":Ne(e,i,o);break}}function Pt(e,t,o){if(!E(o))return;const i=o.transactionMeta.actionContinuities.getRelatedKey(e);if(i!==void 0)o.transactionMeta.epoch.set(i,t)}var Vt=(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),Ne("newValue",o.transactionMeta.update,n),E(n))Pt(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 Y 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 Nt=(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 Y(i.atoms),atomsThatAreDefault:new Set(i.atomsThatAreDefault),families:new Y(i.families),operation:{open:!1},readonlySelectors:new Y(i.readonlySelectors),timelines:new Y(i.timelines),timelineTopics:new X(i.timelineTopics.toJSON()),trackers:new Map,transactions:new Y(i.transactions),selectorAtoms:new X(i.selectorAtoms.toJSON()),selectorGraph:new X(i.selectorGraph.toJSON(),{makeContentKey:(...c)=>c.sort().join(":")}),selectors:new Y(i.selectors),valueMap:new Y(i.valueMap),defaults:i.defaults,disposalTraces:o.disposalTraces.copy(),molecules:new Y(i.molecules),moleculeFamilies:new Y(i.moleculeFamilies),moleculeInProgress:i.moleculeInProgress,miscResources:new Y(i.miscResources)},a=Xt(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=fe())=>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:()=>ze(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 Le(e,t){const o={key:e.key,type:"transaction",run:(r,a)=>{const s=Nt(e.key,r,t,a);try{const l=y(t),{toolkit:c}=s.transactionMeta,m=e.do(c,...r);return Vt(m,l),m}catch(l){throw bt(n),t.logger.warn("\uD83D\uDCA5","transaction",e.key,"caught:",l),l}},install:(r)=>Le(e,r),subject:new x},n=y(t);n.transactions.set(o.key,o);const i=U(o);return t.on.transactionCreation.next(i),i}function Xt(e,t){const o=E(t),n=o?t.transactionMeta.actionContinuities.getRelatedKey(e):void 0;return o&&n!==void 0?t.transactionMeta.epoch.get(n):void 0}class Xe{_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 Xe([...this._buffer]);return e._index=this._index,e}}class Dt{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 Xe(100);molecules=new Map;moleculeFamilies=new Map;moleculeInProgress=null;miscResources=new Map;on={atomCreation:new x,atomDisposal:new x,selectorCreation:new x,selectorDisposal:new x,timelineCreation:new x,transactionCreation:new x,transactionApplying:new Qe(null),operationClose:new x,moleculeCreationStart:new x,moleculeCreationDone:new x,moleculeDisposal:new x};operation={open:!1};config={name:"IMPLICIT_STORE",lifespan:"ephemeral"};loggers=[new qe("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},E(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 Dt({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(k(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 Ht=(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 Ot(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=Ht(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 Ke(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 x,a={...t,type:"mutable_atom",install:(c)=>{return c.logger.info("\uD83D\uDEE0\uFE0F","atom",t.key,`installing in store "${c.config.name}"`),Ke(c,t,o)},subject:r};if(o)a.family=o;const s=t.default();n.atoms.set(a.key,a),De(t.key,e),q(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)Ut(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=P(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=P(n.token.family.subKey),r=$(t,this.mutableAtoms,i);if(r)new ce(r,t)}})}}function Ae(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 x,s=Object.assign((l)=>{const c=k(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=Ke(F,C,m);return r.next({type:"state_creation",token:v}),v},n,{subject:r,install:(l)=>Ae(l,t),toJson:t.toJson,fromJson:t.fromJson,internalRoles:o});return e.families.set(t.key,s),qt(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 Kt(e){return typeof e==="object"&&e!==null&&"do"in e&&"undo"in e&&"subscribe"in e}function xe(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 q(e,t,o,n){const i=n.valueMap.get(e);if(i instanceof ke)i.use(t);if(t instanceof Promise){const r=new ke(t);return n.valueMap.set(e,r),r.then((a)=>{q(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 gt=(e,t)=>{let o=t.valueMap.get(e.key);if(e.type==="mutable_atom"&&R(t)){const{parent:n}=t;o=xe(e,n,t)}return o},Rt=(e,t)=>{const o=t.valueMap.get(e);if(o instanceof ke){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 wt=(e,t)=>{return y(t).atomsThatAreDefault.has(e)},De=(e,t)=>{const o=y(t);o.atomsThatAreDefault=new Set(o.atomsThatAreDefault).add(e)},ht=(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 x,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),De(t.key,e),q(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 kt(e,t){if("mutable"in t){const i=Ke(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 Ut=(e,t,o=K.STORE)=>{return be(o,{key:`${e.key}:JSON`,get:({get:n})=>t.toJson(n(e)),set:({set:n},i)=>{n(e,t.fromJson(i))}})};function qt(e,t,o=K.STORE){const n=Re(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=k(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=k(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,P(r.token.family.subKey))}),n}var P=(e)=>JSON.parse(e),k=(e)=>JSON.stringify(e),jm=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];class He{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 Je extends He{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=P(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=P(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=P(this.incompleteLog);this.handleLog(a);while(this.unprocessedLogs.length>0)if(this.incompleteLog=this.unprocessedLogs.shift()??"",this.incompleteLog)a=P(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 Yt 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 yt{e;type="continuity";globals=[];actions=[];perspectives=[];constructor(e){this.key=e}static existing=new Yt;static create(e,t){const o=new yt(e),{type:n,globals:i,actions:r,perspectives:a}=t(o),s={type:n,key:e,globals:i,actions:r,perspectives:a};return yt.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 yy=ue({key:"usersInRoomIndex",mutable:!0,default:()=>new z,toJson:(e)=>e.toJSON(),fromJson:(e)=>z.fromJSON(e)}),ft=ue({key:"roomIndex",default:()=>new z,mutable:!0,toJson:(e)=>e.toJSON(),fromJson:(e)=>z.fromJSON(e)}),lo={enteredAtEpoch:0},we=Be({key:"usersInRooms",between:["room","user"],cardinality:"1:n"},lo),fy=he({key:"usersInMyRoomView",get:(e)=>({find:t})=>{const o=Bt(we);return[t(o,e)]}});import{spawn as so}from"node:child_process";var pt=me({key:"roomArguments",default:["echo",["Hello World!"]]}),Lt=he({key:"room",get:(e)=>async({get:t,find:o})=>{const n=o(pt,e),i=t(n),[r,a]=i,s=await new Promise((l)=>{const c=so(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 Je(s,e)}});var Cy=ge({key:"createRoom",do:({get:e,set:t,find:o},n,i,r)=>{const a=r?[i,r]:[i],s=o(pt,n);t(s,a),t(ft,(m)=>m.add(n));const l=o(Lt,n);return e(l)}}),Ky=ge({key:"joinRoom",do:(e,t,o,n)=>{const i={enteredAtEpoch:n};return Ee(we,(r)=>{r.set({room:t,user:o},i)},e.env().store),i}}),Jy=ge({key:"leaveRoom",do:(e,t,o)=>{Ee(we,(n)=>{n.delete({room:t,user:o})},e.env().store)}}),wy=ge({key:"destroyRoom",do:(e,t)=>{Ee(we,(o)=>{o.delete({room:t})},e.env().store),e.set(ft,(o)=>(o.delete(t),o))}});var Oy=me({key:"transactionRedactor",default:{occlude:(e)=>e}}),co=me({key:"unacknowledgedUpdates",default:()=>[]});var mo=me({key:"sockets",default:null}),jy=ue({key:"socketsIndex",mutable:!0,default:()=>new z,toJson:(e)=>e.toJSON(),fromJson:(e)=>z.fromJSON(e)}),By=ue({key:"usersIndex",mutable:!0,default:()=>new z,toJson:(e)=>e.toJSON(),fromJson:(e)=>z.fromJSON(e)}),yo=Be({key:"usersOfSockets",between:["user","socket"],cardinality:"1:1"});function Qt(e){const o=process.env.MODE==="development"?"ts":"js",n=e.endsWith(".bun")?"bun":"node",r=[po(import.meta.dir,`${e}.${o}`)];if(n==="node"&&o==="ts")r.push("--experimental-strip-types");const a=fo(n,r);return new Je(a,e,console)}console.log("hello world");var uo=Qt("backend.worker.game.bun");process.on("exit",()=>uo.process.kill());