@lite-fsm/entities 0.1.0-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/PERFORMANCE.md +537 -0
- package/README.md +395 -0
- package/dist/index.cjs +1 -0
- package/dist/index.d.cts +8 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +1 -0
- package/dist/internal.d.cts +5 -0
- package/dist/internal.d.ts +5 -0
- package/dist/machine-extension.d.cts +153 -0
- package/dist/machine-extension.d.ts +153 -0
- package/dist/plugin.d.cts +32 -0
- package/dist/plugin.d.ts +32 -0
- package/dist/react/index.d.cts +11 -0
- package/dist/react/index.d.ts +11 -0
- package/dist/react.cjs +1 -0
- package/dist/react.js +1 -0
- package/dist/runtime/access.d.cts +72 -0
- package/dist/runtime/access.d.ts +72 -0
- package/dist/runtime/columns.d.cts +11 -0
- package/dist/runtime/columns.d.ts +11 -0
- package/dist/runtime/compile.d.cts +68 -0
- package/dist/runtime/compile.d.ts +68 -0
- package/dist/runtime/effects.d.cts +26 -0
- package/dist/runtime/effects.d.ts +26 -0
- package/dist/runtime/lifecycle.d.cts +10 -0
- package/dist/runtime/lifecycle.d.ts +10 -0
- package/dist/runtime/mutation-snapshot.d.cts +41 -0
- package/dist/runtime/mutation-snapshot.d.ts +41 -0
- package/dist/runtime/react.d.cts +29 -0
- package/dist/runtime/react.d.ts +29 -0
- package/dist/runtime/reactions.d.cts +15 -0
- package/dist/runtime/reactions.d.ts +15 -0
- package/dist/runtime/reduce-batch.d.cts +6 -0
- package/dist/runtime/reduce-batch.d.ts +6 -0
- package/dist/runtime/reduce-despawn.d.cts +7 -0
- package/dist/runtime/reduce-despawn.d.ts +7 -0
- package/dist/runtime/reduce-post-process.d.cts +35 -0
- package/dist/runtime/reduce-post-process.d.ts +35 -0
- package/dist/runtime/reduce-shared.d.cts +34 -0
- package/dist/runtime/reduce-shared.d.ts +34 -0
- package/dist/runtime/reduce-spawn.d.cts +5 -0
- package/dist/runtime/reduce-spawn.d.ts +5 -0
- package/dist/runtime/reduce-transitions.d.cts +11 -0
- package/dist/runtime/reduce-transitions.d.ts +11 -0
- package/dist/runtime/reduce.d.cts +5 -0
- package/dist/runtime/reduce.d.ts +5 -0
- package/dist/runtime/routing.d.cts +11 -0
- package/dist/runtime/routing.d.ts +11 -0
- package/dist/runtime/runtime-index.d.cts +23 -0
- package/dist/runtime/runtime-index.d.ts +23 -0
- package/dist/runtime/snapshot-export.d.cts +12 -0
- package/dist/runtime/snapshot-export.d.ts +12 -0
- package/dist/runtime/snapshot-import.d.cts +5 -0
- package/dist/runtime/snapshot-import.d.ts +5 -0
- package/dist/runtime/snapshot-types.d.cts +56 -0
- package/dist/runtime/snapshot-types.d.ts +56 -0
- package/dist/runtime/snapshot.d.cts +15 -0
- package/dist/runtime/snapshot.d.ts +15 -0
- package/dist/runtime/spawn-commit.d.cts +10 -0
- package/dist/runtime/spawn-commit.d.ts +10 -0
- package/dist/runtime/state.d.cts +15 -0
- package/dist/runtime/state.d.ts +15 -0
- package/dist/runtime/storage.d.cts +19 -0
- package/dist/runtime/storage.d.ts +19 -0
- package/dist/runtime/store-types.d.cts +81 -0
- package/dist/runtime/store-types.d.ts +81 -0
- package/dist/runtime/transaction.d.cts +104 -0
- package/dist/runtime/transaction.d.ts +104 -0
- package/dist/runtime/transitionTrace.d.cts +19 -0
- package/dist/runtime/transitionTrace.d.ts +19 -0
- package/dist/schema.d.cts +90 -0
- package/dist/schema.d.ts +90 -0
- package/dist/spawn.d.cts +56 -0
- package/dist/spawn.d.ts +56 -0
- package/package.json +90 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{definePlugin as $a,LiteFsmError as ho}from"@lite-fsm/core";import{LiteFsmError as Ie}from"@lite-fsm/core";import{LiteFsmError as Ro}from"@lite-fsm/core";var m=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),I=t=>t!==null&&typeof t=="object"&&!Array.isArray(t)&&Object.getPrototypeOf(t)===Object.prototype,Y=()=>globalThis.process?.env?.NODE_ENV!=="production",g=t=>new Ro("LITE_FSM_INVALID_STORAGE_RUNTIME",`[lite-fsm/entities] ${t}.`);var O="ENTITY_SPAWNED",L="ENTITY_DESPAWNED",Co=new Set([O,L]),Ae=t=>Object.prototype.toString.call(t)==="[object Object]",pt=(t,e)=>new Ie("LITE_FSM_INVALID_STORAGE_CONFIG",`[lite-fsm/entities] machine '${t}' has invalid storage: "entity" config: ${e}.`),Lt=t=>Co.has(t),lt=t=>{if(Lt(t))throw new Ie("LITE_FSM_INVALID_STORAGE_RUNTIME",`[lite-fsm/entities] public dispatch of internal entity lifecycle event '${t}' is not allowed.`)},ve=(t,e)=>{if(!Ae(e))throw pt(t,"config must be a plain object");if(!m(e,"__INIT"))throw pt(t,"config.__INIT must be a transition map");let n=e.__INIT;if(!Ae(n))throw pt(t,"config.__INIT must be a transition map");for(let o of Object.keys(n))if(o!==O)throw pt(t,`custom event edge '${o}' from __INIT is not allowed; use '${O}'`)};import{defineStorageRuntime as Ba,LiteFsmError as he}from"@lite-fsm/core";import{LiteFsmError as xo}from"@lite-fsm/core";var ft=Symbol.for("lite-fsm.entities.schema-descriptor"),Nt=Symbol.for("lite-fsm.entities.resource-descriptor"),Ao=new Set(["count","capacity","ids","indexById","alive","generation","freeList","stateCode","version","columns","presence","rowVersion","indices","states"]),Io=new Set(["acceptedScratch","acceptStateBucketsByEventCode","entityId","entitiesByGroupTag","groupTagByIndex","groupTagPosition","has","metadata","pendingPrevStateCodeSync","pendingPrevStateCodeSyncMark","pendingPrevStateCodeSyncToken","prevStateCode","publicSlice","reducerSelf","resources","resourceViews","routingScratchVersion","state","stateBuckets","statePosition","templateKey"]),vo=t=>Ao.has(t),et=(t,e)=>{let n=e&&m(e,"default")?{[ft]:!0,kind:t,default:e.default}:{[ft]:!0,kind:t};return Object.freeze(n)},To=t=>et("f32",t),bo=t=>et("i16",t),ko=t=>et("i32",t),Bo=t=>et("u8",t),Po=t=>et("string",t),Mo=t=>Object.freeze({[ft]:!0,kind:"optional",inner:t});function Do(t,e){let n=e===void 0?{[Nt]:!0,kind:"resource",factory:t,exposed:!1}:{[Nt]:!0,kind:"resource",factory:t,expose:e,exposed:!0};return Object.freeze(n)}var Oo=t=>I(t)&&Reflect.get(t,ft)===!0,St=t=>I(t)&&Reflect.get(t,Nt)===!0,_o=t=>t.kind==="f32"||t.kind==="i16"||t.kind==="i32"||t.kind==="u8"||t.kind==="string",v=(t,e,n)=>new xo("LITE_FSM_INVALID_STORAGE_CONFIG",`[lite-fsm/entities] machine '${t}' has invalid ${e}: ${n}.`),Te=t=>Array.isArray(t)?"arrays are not supported in entity schemas":t instanceof Map?"Map is not supported in entity schemas":t instanceof Set?"Set is not supported in entity schemas":Object.getPrototypeOf(t)!==Object.prototype?"custom prototype objects are not supported in entity schemas":"unknown descriptor shape",$o=(t,e,n)=>{for(let o of Object.keys(n))if(o!=="kind"&&o!=="default"&&o!=="inner")throw v(t,e,`unknown descriptor property '${o}'`)},Lo=(t,e,n)=>{for(let o of Object.keys(n))if(o!=="kind"&&o!=="factory"&&o!=="expose"&&o!=="exposed")throw v(t,e,`unknown descriptor property '${o}'`)},No=(t,e,n,o)=>{if(!m(n,"default"))return;if(!o)throw v(t,e,"default values are not allowed in spawnSchema");let r=n.default;if(n.kind==="string"?typeof r!="string":typeof r!="number")throw v(t,e,"default value does not match descriptor kind")},be=(t,e,n,o,r)=>{if(St(n)){if(o)throw v(t,e,"resource(...) is not allowed in spawnSchema");Lo(t,e,n);return}if(!Oo(n))throw n!==null&&typeof n=="object"?v(t,e,Te(n)):v(t,e,"schema field must be a descriptor");if($o(t,e,n),n.kind==="optional"){if(!o)throw v(t,e,"optional(...) is not allowed in initialContext");be(t,`${e}.inner`,n.inner,!1,r);return}if(!_o(n))throw v(t,e,"unknown descriptor kind");No(t,e,n,r)},Vt=(t,e,n)=>{if(!I(n))throw n!==null&&typeof n=="object"?v(t,e,Te(n)):v(t,e,"schema must be a plain object");let o=e==="spawnSchema",r=e==="initialContext";for(let[i,a]of Object.entries(n)){let s=St(a);if(vo(i)||e==="initialContext"&&s&&Io.has(i))throw v(t,`${e}.${i}`,"field name is reserved");be(t,`${e}.${i}`,a,o,r)}};import{LiteFsmError as mt}from"@lite-fsm/core";var Vo=t=>new mt("LITE_FSM_INVALID_STORAGE_RUNTIME",`[lite-fsm/entities] unknown entity actor template '${t}'.`),Be=(t,e)=>{let n=t.actorStores[e];if(n)return n;throw Vo(e)},ke=(t,e,n,o)=>new mt("LITE_FSM_INVALID_STORAGE_RUNTIME",`[lite-fsm/entities] scoped entities().get('${e}') failed for source actor '${t.sourceActor}' while handling '${t.eventType}' on entity '${n}': ${o}.`),Pe=(t,e)=>t.entityStore.alive[e.entity]===1&&t.entityStore.generation[e.entity]===e.generation,jo=(t,e,n,o)=>{if(Y())for(let r of e.entries){if(!Pe(t,r))throw ke(e,n,r.id,"captured entity scope is stale");if(o.presence[r.entity]!==1)throw ke(e,n,r.id,"requested actor row is missing")}},Me=(t,e)=>{for(let n of Object.keys(e.columns))Object.defineProperty(t,n,{enumerable:!0,configurable:!0,writable:!1,value:e.columns[n]})},De=(t,e)=>{for(let[n,o]of Object.entries(e.resourceViews))Object.defineProperty(t,n,{enumerable:!0,configurable:!0,writable:!1,value:o})},Oe=new WeakMap,q=t=>{let e=Oe.get(t);e&&(Me(e,t),De(e,t))},Fo=(t,e)=>{let n=Be(t,e),o={get count(){return n.count},get version(){return n.version},has(r){return n.presence[r]===1},state(r){if(n.presence[r]===1){let i=n.stateCode[r];return n.metadata.publicStates[i]}}};return Me(o,n),De(o,n),Oe.set(n,o),o},_e=t=>{let e=new Map,n=o=>{let r=e.get(o);if(r)return r;let i=Fo(t,o);return e.set(o,i),i};return{get(o){return n(o)},maybe(o){return n(o)}}},$e=(t,e)=>new mt("LITE_FSM_INVALID_STORAGE_RUNTIME",`[lite-fsm/entities] entity index ${e} is outside current entity ${t} scope.`),Et=(t,e)=>new mt("LITE_FSM_INVALID_STORAGE_RUNTIME",`[lite-fsm/entities] entity index ${t} is stale in current entity reaction scope: ${e}.`),jt=(t,e)=>{t.presence=e.presence,t.stateCode=e.stateCode,t.prevStateCode=e.prevStateCode,t.rowVersion=e.rowVersion;for(let[n,o]of Object.entries(e.columns))t[n]=o;for(let[n,o]of Object.entries(e.resources))t[n]=o},wt=(t,e)=>{let n={indices:e.indices,states:t.metadata.stateCodeByName,has:e.has,entityId:e.entityId};return jt(n,t),n},Le=(t,e,n)=>{let o,r=()=>{if(o)return o;let i=new Map;for(let a of n.entries)i.set(a.entity,a);return o=i,i};return wt(e,{indices:n.indices,has(i){let a=r().get(i);return a?Pe(t,a)&&e.presence[i]===1:!1},entityId(i){let a=r().get(i);if(a)return a.id;throw $e(n.scopeName,i)}})},Ne=(t,e,n)=>{let o=a=>n.lifetime.token===n.token&&n.markers[a]===n.token,r=a=>t.entityStore.generation[a]===n.generation[a],i=a=>{let s=t.entityStore.ids[a];return s!==void 0&&s.length>0};return wt(e,{indices:n.indices,has(a){return o(a)&&r(a)&&t.entityStore.alive[a]===1&&e.presence[a]===1&&i(a)},entityId(a){if(!o(a))throw $e("reaction",a);if(!r(a))throw Et(a,"generation changed");if(t.entityStore.alive[a]!==1)throw Et(a,"entity is not live");if(e.presence[a]!==1)throw Et(a,"actor row is missing");let s=t.entityStore.ids[a];if(s!==void 0&&s.length>0)return s;throw Et(a,"entity id is missing")}})},Ve=t=>t.access,je=(t,e)=>{let n=t.access;return{get(o){let r=Be(t,o),i=n.get(o);return jo(t,e,o,r),i},maybe(o){return n.maybe(o)}}};import{LiteFsmError as Ko}from"@lite-fsm/core";var Fe=Symbol.for("lite-fsm.entities.spawn-event"),Ke=Symbol.for("lite-fsm.entities.spawn-descriptor"),N=t=>new Ko("LITE_FSM_INVALID_OPTIONS",`[lite-fsm/entities] invalid entity spawn config: ${t}.`),Uo=t=>I(t)&&Reflect.get(t,Fe)===!0,Ue=(t,e)=>{if(Lt(e))throw N(`${t} cannot use internal lifecycle event '${e}'`)};function Ft(t){if(!I(t))throw N("spawnEvents must be a plain object");for(let[e,n]of Object.entries(t))if(Ue("spawnEvents",e),!Uo(n))throw N(`spawnEvents.${e} must be created by spawnEvent()`)}function Ge(t,e){if(!I(e))throw N("recipes must be a plain object");let n=Object.keys(t),o=new Set(n);for(let r of Object.keys(e)){if(Ue("recipes",r),!o.has(r))throw N(`unknown recipe key '${r}'`);if(typeof e[r]!="function")throw N(`recipe '${r}' must be a function`)}for(let r of n)if(!m(e,r))throw N(`missing recipe for spawn event '${r}'`)}var Go=()=>Object.freeze({[Fe]:!0}),Ho=t=>(Ft(t),Object.freeze({...t})),Yo=(t,e)=>n=>(Ft(e),Ge(e,n),Object.freeze({[Ke]:!0,spawnEvents:e,recipes:n})),qo=t=>I(t)&&Reflect.get(t,Ke)===!0;function He(t){if(!qo(t))throw N("entitiesPlugin({ spawn }) expects a value returned by defineEntitySpawn(...)");Ft(t.spawnEvents),Ge(t.spawnEvents,t.recipes)}var Ye=(t,e)=>m(t.recipes,e),qe=(t,e)=>{let n=t.recipes[e.type];return n(e.payload)};var Wo="@lite-fsm/core/transition-trace",V=t=>{let e=t.runtime.get(Wo);if(!e||typeof e!="object")return;let n=e;if(!(typeof n.depth!="number"||typeof n.now!="function"||typeof n.record!="function"||typeof n.count!="function"||typeof n.finish!="function"))return n},h=(t,e,n)=>{!t||n===void 0||t.record(e,n)},G=(t,e,n)=>{t&&t.count(e,n)},x=(t,e,n)=>{if(!t)return n();let o=t.now();try{return n()}finally{t.record(e,o)}},W=(t,e,n)=>x(V(t),e,n);var tn="@lite-fsm/entities/transaction",en=Symbol.for("@lite-fsm/entities/despawn-options"),Kt="LITE_FSM_ENTITY_DESPAWN",zo=new Uint8Array,We=new WeakMap,ze=16,Je=16,A=t=>g(`invalid entity spawn: ${t}`),Jo=t=>{if(!(t===null||typeof t!="object"))return t[en]},Ut=t=>({[en]:t}),Qo=(t,e)=>{let n=t.runtime.entityStore.indexById[e];return n===void 0?!1:nt(t,n)},Xo=(t,e)=>{let n=t.runtime.entityStore;if(!(n.alive[e.entity]!==1||n.generation[e.entity]!==e.generation))return nt(t,e.entity);if(Y())throw g(`stale entity effect scope cannot despawn entity '${e.id}' at index ${e.entity}`);return!1},Zo=(t,e,n)=>{let o=Jo(e);if(!o)return;let r=0;if(o.mode==="ids"){G(n,"entities.prepare.explicitDespawn.ids",o.ids.length);for(let i of o.ids)Qo(t,i)&&(r+=1);G(n,"entities.prepare.explicitDespawn.scheduled",r);return}G(n,"entities.prepare.explicitDespawn.scopeEntries",o.entries.length);for(let i of o.entries)Xo(t,i)&&(r+=1);G(n,"entities.prepare.explicitDespawn.scheduled",r)},M=t=>{let e=We.get(t);if(e)return e;let n={despawnScheduled:zo,despawnScheduledMarks:[],despawnRowHintMarksByStoreId:[],despawnRowHintBucketStateCodeByStoreId:[],despawnRowHintMarks:[],cleanupScratchPool:[],cleanupScratchPoolCursor:0,reactionIndexPool:[],reactionIndexPoolCursor:0};return We.set(t,n),n},tr=t=>{for(let e of t.despawnScheduledMarks)t.despawnScheduled[e]=0;t.despawnScheduledMarks.length=0},nn=t=>{for(let e of t.despawnRowHintMarks)t.despawnRowHintMarksByStoreId[e.storeId][e.entity]=0;t.despawnRowHintMarks.length=0},er=t=>{for(let e=0;e<t.reactionIndexPoolCursor;e+=1)t.reactionIndexPool[e].length=0;t.reactionIndexPoolCursor=0},nr=()=>({entities:[],removalBatchesByStoreId:[],removalTouchedStoreIds:[],lifecycleBatchesByStoreId:[],lifecycleTouchedStoreIds:[]}),Gt=t=>{for(let e of t.removalTouchedStoreIds){let n=t.removalBatchesByStoreId[e];n&&(n.rows.length=0,n.bucketStateCodes.length=0,n.bucketStateCodesActive=!1)}t.removalTouchedStoreIds.length=0;for(let e of t.lifecycleTouchedStoreIds){let n=t.lifecycleBatchesByStoreId[e];n&&(n.indices.length=0)}t.lifecycleTouchedStoreIds.length=0,t.entities.length=0},or=t=>{if(t.cleanupScratchPoolCursor===0)for(let e of t.cleanupScratchPool)Gt(e)},on=(t,e)=>{let n=M(e);tr(n),nn(n),or(n),er(n);let o={runtime:e,stagedSpawns:[],scheduledDespawns:[],despawnScheduled:n.despawnScheduled,despawnRowHints:[],terminalRows:[],effectBatches:[],reactionBatches:[]};t.runtime.set(tn,o);let r=V(t);return x(r,"entities.prepare.explicitDespawn",()=>Zo(o,t.options,r)),o},j=t=>t.runtime.get(tn),Qe=(t,e)=>{if(typeof e=="string"&&e.length>0)return e;throw A(`${t} must be a non-empty string`)},Xe=t=>t===void 0?"undefined":t===null?"null":typeof t,Ze=(t,e,n)=>{if(e==="string"){if(typeof n=="string")return;throw A(`${t} must be a string, got ${Xe(n)}`)}if(!(typeof n=="number"&&Number.isFinite(n)))throw A(`${t} must be a finite number, got ${Xe(n)}`)},rr=(t,e,n)=>{if(e.kind!=="optional"){Ze(t,String(e.kind),n);return}if(n!==null){if(n===void 0)throw A(`${t} is required and cannot be undefined`);Ze(t,String(e.inner.kind),n)}},ir=(t,e,n)=>{if(!I(n))throw A(`actor '${t}' payload must be a plain object`);for(let o in n)if(m(n,o)&&!m(e,o))throw A(`actor '${t}' payload has unknown key '${o}'`);for(let o in e){if(!m(e,o))continue;if(!m(n,o))throw A(`actor '${t}' payload is missing required key '${o}'`);let r=e[o];rr(`actor '${t}' payload.${o}`,r,n[o])}return n},ar=t=>{if(Array.isArray(t))return t;if(I(t))return[t];throw A("recipe must return an EntitySpawnSpec or an array of EntitySpawnSpec")},sr=(t,e,n)=>{if(!I(e))throw A("EntitySpawnSpec must be a plain object");let o=Qe("EntitySpawnSpec.id",e.id),r=Qe("EntitySpawnSpec.groupTag",e.groupTag),i=t.entityStore.indexById[o];if(i!==void 0&&t.entityStore.alive[i]===1)throw A(`duplicate entity id '${o}'`);if(n.has(o))throw A(`duplicate entity id '${o}' in one recipe result`);if(n.add(o),!I(e.actors))throw A(`EntitySpawnSpec '${o}' actors must be a plain object`);let a=[];for(let s in e.actors){if(!m(e.actors,s))continue;let c=e.actors[s],d=t.actorStores[s];if(!d)throw A(`unknown entity actor template '${s}'`);a.push({templateKey:s,payload:ir(s,d.metadata.spawnSchema,c)})}if(a.length===0)throw A(`EntitySpawnSpec '${o}' must contain at least one actor`);return{id:o,groupTag:r,actors:a}},rn=(t,e)=>{let n=V(t),o=n?.now();try{if(t.skipDelivery||!Ye(e,t.action.type))return;let r=j(t);if(!r)throw A("entity transaction slot was not prepared before spawn staging");let i=x(n,"entities.spawn.stage.recipe",()=>qe(e,t.action)),a=x(n,"entities.spawn.stage.normalize",()=>ar(i));if(a.length===0){r.stagedSpawns=[];return}r.stagedSpawns=x(n,"entities.spawn.stage.validate",()=>{let s=new Set;return a.map(c=>sr(r.runtime,c,s))})}finally{h(n,"entities.spawn.stage",o)}},an=t=>{let e=j(t);return e?e.stagedSpawns:[]},cr=(t,e)=>{let n=t.despawnScheduled.length;if(n>=e)return;let o=Math.max(e,t.runtime.entityStore.capacity,ze),r=Math.max(n,ze);for(;r<o;)r*=2;let i=new Uint8Array(r);i.set(t.despawnScheduled),M(t.runtime).despawnScheduled=i,t.despawnScheduled=i},nt=(t,e)=>t.runtime.entityStore.alive[e]!==1||(cr(t,e+1),t.despawnScheduled[e]===1)?!1:(t.despawnScheduled[e]=1,t.scheduledDespawns.push(e),M(t.runtime).despawnScheduledMarks.push(e),!0),dr=(t,e,n,o)=>{let r=t.despawnRowHintMarksByStoreId[e],i=t.despawnRowHintBucketStateCodeByStoreId[e];if(r&&i&&r.length>=n&&i.length>=n)return;let a=Math.min(r?.length??0,i?.length??0),s=Math.max(n,o,Je),c=Math.max(a,Je);for(;c<s;)c*=2;let d=new Uint8Array(c);r&&d.set(r),t.despawnRowHintMarksByStoreId[e]=d;let y=new Int16Array(c);i&&y.set(i),t.despawnRowHintBucketStateCodeByStoreId[e]=y},Ht=(t,e,n,o)=>{let r=M(t.runtime);dr(r,e.storeId,n+1,e.capacity);let i=r.despawnRowHintMarksByStoreId[e.storeId];if(i[n]===1)return!1;i[n]=1,r.despawnRowHintBucketStateCodeByStoreId[e.storeId][n]=o;let a={storeId:e.storeId,entity:n,bucketStateCode:o};return t.despawnRowHints.push(a),r.despawnRowHintMarks.push(a),!0},sn=(t,e,n)=>{let o=M(t.runtime),r=o.despawnRowHintMarksByStoreId[e];if(!(!r||r[n]!==1))return o.despawnRowHintBucketStateCodeByStoreId[e][n]},cn=t=>{nn(M(t.runtime)),t.despawnRowHints=[]},dn=t=>{let e=t.scheduledDespawns;t.scheduledDespawns=[];for(let n of e)t.despawnScheduled[n]=0;return M(t.runtime).despawnScheduledMarks.length=0,e},Yt=t=>{let e=M(t.runtime),n=e.cleanupScratchPoolCursor,o=e.cleanupScratchPool[n]??nr();return e.cleanupScratchPool[n]=o,e.cleanupScratchPoolCursor+=1,Gt(o),o},qt=(t,e)=>{Gt(e);let n=M(t.runtime),o=n.cleanupScratchPoolCursor-1;o>=0&&n.cleanupScratchPool[o]===e&&(n.cleanupScratchPoolCursor=o)},yn=(t,e,n,o)=>{let r=t.removalBatchesByStoreId[e.storeId];r||(r={store:e,rows:[],bucketStateCodes:[],bucketStateCodesActive:!1},t.removalBatchesByStoreId[e.storeId]=r),r.rows.length===0&&t.removalTouchedStoreIds.push(e.storeId),(o!==void 0||r.bucketStateCodesActive)&&(r.bucketStateCodesActive||(r.bucketStateCodes.length=r.rows.length,r.bucketStateCodesActive=!0),r.bucketStateCodes.push(o)),r.rows.push(n)},un=(t,e,n)=>{let o=t.lifecycleBatchesByStoreId[e.storeId];o||(o={store:e,indices:[]},t.lifecycleBatchesByStoreId[e.storeId]=o),o.indices.length===0&&t.lifecycleTouchedStoreIds.push(e.storeId),o.indices.push(n)},pn=(t,e,n,o,r)=>{if(!t||o.length===0||!e.metadata.effectsByStateCode[n])return;let i=t.runtime.entityStore;t.effectBatches.push({store:e,stateCode:n,indices:o,capturedEntries:r,storeVersion:e.version,entityStoreVersion:i.version})},yr=(t,e)=>{let n=M(t.runtime),o=n.reactionIndexPoolCursor,r=n.reactionIndexPool[o]??[];n.reactionIndexPool[o]=r,n.reactionIndexPoolCursor+=1,r.length=e.length;for(let i=0;i<e.length;i+=1)r[i]=e[i];return r},Wt=(t,e,n,o,r={})=>{if(!t||n===void 0||o.length===0||!e.metadata.reactionsByEventCode[n])return;let i=r.ownership??"owned";return{store:e,eventCode:n,ownership:i,indices:i==="borrowed"?o:yr(t,o)}},ln=(t,e,n,o,r)=>{if(!t)return;let i=Wt(t,e,n,o,r);i&&t.reactionBatches.push(i)};var gt=(t,e)=>({...t,meta:{...t.meta??{},...e}}),Rt=(t,e)=>{if(typeof e=="string")return[e];if(!Array.isArray(e)||e.some(n=>typeof n!="string"))throw g(`${t} target must be a string or an array of strings`);return e},ur=t=>{let e=new Set,n=[];for(let o of t)e.has(o)||(e.add(o),n.push(o));return n},ht=t=>t.length===1?t[0]:t,pr=(t,e)=>{let n=t.entityStore.indexById[e];return n!==void 0&&t.entityStore.alive[n]===1},fn=(t,e)=>ur(Rt("entity",e)).filter(n=>pr(t,n)),lr=t=>g(`stale entity effect scope cannot despawn entity '${t.id}' at index ${t.entity}`),fr=(t,e)=>{let n=[],o=t.entityStore.alive,r=t.entityStore.generation;for(let i of e){if(o[i.entity]===1&&r[i.entity]===i.generation){n.push(i);continue}if(Y())throw lr(i)}return n},Sr=(t,e,n)=>{let o=(r=>e.transition(r));return o.unscoped=r=>e.transition(r,{routingMode:"unscoped"}),o.actor=(r,i)=>e.transition(gt(i,{actorId:ht(Rt("actor",r))})),o.group=(r,i)=>e.transition(gt(i,{groupId:ht(Rt("group",r))})),o.tag=(r,i)=>e.transition(gt(i,{groupTag:ht(Rt("tag",r))})),o.entity=(r,i)=>{let a=fn(t,r);return a.length===0?i:e.transition(gt(i,{entityId:ht(a)}))},o.despawn=r=>{if(typeof r=="string"||Array.isArray(r)&&r.every(i=>typeof i=="string")){let i=fn(t,r);if(i.length===0)return;e.transition({type:Kt},Ut({mode:"ids",ids:i}));return}if(Array.isArray(r)&&r.every(i=>typeof i=="number")){if(r!==n.indices)throw g("transition.despawn(EntityIndex[]) only accepts self.indices from current entity effect scope");let i=fr(t,n.scope.entries);if(i.length===0)return;e.transition({type:Kt},Ut({mode:"scope",entries:i}));return}throw g("transition.despawn(...) expects an entity id, entity id array or self.indices")},o},Er=()=>{throw g('condition() is not supported in storage: "entity" effects')},mr=(t,e,n)=>n.capturedEntries!==void 0&&n.storeVersion===e.version&&n.entityStoreVersion===t.entityStore.version,wr=(t,e)=>({storeKey:t.store.templateKey,stateCode:t.stateCode,indices:t.indices,scope:{sourceActor:t.store.templateKey,eventType:e,entries:t.capturedEntries}}),gr=(t,e,n)=>{let o=e.store,r=e.stateCode,i=e.indices,a=o.presence,s=o.stateCode,c=t.entityStore.alive,d=t.entityStore.ids,y=t.entityStore.generation,u=[],p,w=()=>{if(p)return p;p=[];for(let E=0;E<u.length;E+=1)p.push(u[E].entity);return p};for(let E=0;E<i.length;E+=1){let l=i[E];if(a[l]!==1||s[l]!==r||c[l]!==1){w();continue}let f=d[l];if(f===void 0||f.length===0){w();continue}u.push({entity:l,generation:y[l],id:f}),p?.push(l)}if(u.length!==0)return{storeKey:o.templateKey,stateCode:r,indices:p??i,scope:{sourceActor:o.templateKey,eventType:n,entries:u}}},Sn=(t,e)=>{let n=j(e.dispatch);if(!n||n.effectBatches.length===0)return[];let o=e.action.type,r=[];for(let i of n.effectBatches){if(!i.store.metadata.effectsByStateCode[i.stateCode])continue;if(mr(t,i.store,i)){r.push(wr(i,o));continue}let a=gr(t,i,o);a&&r.push(a)}return r},En=(t,e,n)=>{let o=t.actorStores[e.storeKey],r=o?.metadata.effectsByStateCode[e.stateCode];if(!o||!r)return;let i=je(t,e.scope),a=Object.create(n.manager.getDependencies());a.action=n.action,a.self=Le(t,o,{scopeName:"effect",indices:e.indices,entries:e.scope.entries}),a.entities=()=>i,a.transition=Sr(t,n.manager,e),a.condition=Er;try{let s=r(a);s instanceof Promise&&s.catch(c=>{n.dispatch.reportError(c)})}catch(s){n.dispatch.reportError(s)}};import{LiteFsmError as hr}from"@lite-fsm/core";var Ct="__INIT",R=-1,ot=-2,rt=-3,it=-4,F=-32768,xt=-32767,Rr=new Set(["__INIT","__RESOLVED","__REJECTED","__CANCELLED","*"]),Cr=new Set(["__INIT","__RESOLVED","__REJECTED","__CANCELLED"]),xr={__RESOLVED:ot,__REJECTED:rt,__CANCELLED:it},Ar={[ot]:"__RESOLVED",[rt]:"__REJECTED",[it]:"__CANCELLED"},B=(t,e)=>new hr("LITE_FSM_INVALID_STORAGE_CONFIG",`[lite-fsm/entities] machine '${t}' has invalid storage: "entity" config: ${e}.`),Ir=t=>{let e=Object.create(null),n=Object.create(null);for(let[o,r]of Object.entries(t)){if(St(r)){n[o]=r;continue}e[o]=r}return{initialContext:e,resourceSchema:n}},vr=(t,e)=>e===Ct?R:t.stateCodeByName[e],Tr=(t,e)=>e===Ct?R:xr[e]??t.stateCodeByName[e],mn=t=>t+1,P=t=>t===ot||t===rt||t===it,At=t=>{for(let e=0;e<t.length;e+=1)if(t[e]===1)return!0;return!1},br=t=>{let e=[],n=new Set;for(let o of Object.values(t))if(o)for(let r of Object.keys(o))n.has(r)||(n.add(r),e.push(r));return e},kr=(t,e)=>{if(e===void 0)return[];if(typeof e=="string")return[e];if(Array.isArray(e)&&e.every(n=>typeof n=="string"))return e;throw B(t,"despawnOn must be a state name or a readonly array of state names")},Br=(t,e,n,o)=>{let r=new Uint8Array(Object.keys(n).length);for(let i of kr(t,o)){if(Cr.has(i))throw B(t,`despawnOn cannot reference special state '${i}'`);if(!m(e,i))throw B(t,`despawnOn references unknown state '${i}'`);let a=n[i];if(a===void 0)throw B(t,`despawnOn references non-public state '${i}'`);r[a]=1}return r},Pr=(t,e,n)=>{let o=Array.from({length:Object.keys(e).length});if(n===void 0)return o;if(n===null||typeof n!="object"||Array.isArray(n))throw B(t,"effects must be a plain object keyed by public state names");for(let[r,i]of Object.entries(n)){if(r==="*")throw B(t,'wildcard "*" effects are not supported for storage: "entity"');if(!m(e,r))throw B(t,`effects references unknown public state '${r}'`);if(typeof i!="function")throw B(t,`effect for state '${r}' must be a function`);o[e[r]]=i}return o},Mr=(t,e,n)=>{let o=Object.create(null);if(n===void 0)return o;if(n===null||typeof n!="object"||Array.isArray(n))throw B(t,"reactions must be a plain object keyed by event names");let r=new Set(e);for(let[i,a]of Object.entries(n)){if(!r.has(i))throw B(t,`reactions references event '${i}' that is not accepted by config`);if(typeof a!="function")throw B(t,`reaction for event '${i}' must be a function`);o[i]=a}return o},zt=(t,e)=>{let n=e.config,o=Object.keys(n).filter(s=>!Rr.has(s)),r=Object.fromEntries(o.map((s,c)=>[s,c])),i=br(n),a=Ir(e.initialContext);return{templateKey:t,config:n,initialContext:a.initialContext,resourceSchema:a.resourceSchema,spawnSchema:e.spawnSchema,publicStates:o,stateCodeByName:r,eventTypes:i,eventAcceptMask:new Uint8Array(0),transitionTable:new Int16Array(0),transitionTargetByCell:Object.create(null),acceptStateCodesByEventCode:[],stateSlotCount:o.length+1,despawnStateMask:Br(t,n,r,e.despawnOn),despawnLifecycleStateMask:new Uint8Array(o.length+1),effectsByStateCode:Pr(t,r,e.effects),reactionsByEventType:Mr(t,i,e.reactions),reactionsByEventCode:[],reducePlansByEventCode:[],...typeof e.reducer=="function"?{reducer:e.reducer}:{}}},Dr=(t,e,n)=>{let o=new Uint8Array(t.stateSlotCount),r=e[L];if(r===void 0||!t.reducer&&!m(t.reactionsByEventType,L))return o;let i=r*t.stateSlotCount;for(let a=0;a<t.stateSlotCount;a+=1)n[i+a]!==F&&(o[a]=1);return o},Or=(t,e,n,o,r,i)=>{let a=!0,s=!1,c=!1,d=!1,y=e*t.stateSlotCount;for(let u of o){let p=n[y+mn(u)];p!==u&&(a=!1,s=!0),p>=0&&p!==u&&t.effectsByStateCode[p]&&(c=!0),P(p)&&(d=!0)}return{eventCode:e,acceptStateCodes:o,allDefaultTransitionsIdentity:a,hasNonIdentityDefaultTransition:s,mayEnterEffectState:c,hasDespawnOnStates:i,hasReaction:r,mayEnterTerminalState:d,requiresReducerCall:t.reducer!==void 0}},_r=(t,e,n,o,r)=>{let i=At(t.despawnStateMask),a=[];for(let s=0;s<e;s+=1)a[s]=Or(t,s,n,o[s],r[s]!==void 0,i);return a},$r=(t,e,n)=>{let o=new Uint8Array(n),r=new Int16Array(n*t.stateSlotCount);r.fill(F);let i=Object.create(null),a=Array.from({length:n},()=>[]),s=Array.from({length:n});for(let[c,d]of Object.entries(t.config)){if(!d)continue;let y=vr(t,c);if(y!==void 0)for(let[u,p]of Object.entries(d)){let w=e[u];if(w===void 0)continue;let E=p??c,l=Tr(t,E),f=w*t.stateSlotCount+mn(y);if(o[w]=1,a[w].push(y),l===void 0){r[f]=xt,i[f]=E;continue}r[f]=l}}for(let[c,d]of Object.entries(t.reactionsByEventType)){let y=e[c];y!==void 0&&(s[y]=d)}return{...t,eventAcceptMask:o,transitionTable:r,transitionTargetByCell:i,acceptStateCodesByEventCode:a,despawnLifecycleStateMask:Dr(t,e,r),reactionsByEventCode:s,reducePlansByEventCode:_r(t,n,r,a,s)}},wn=t=>{let e=Object.create(null),n=[];for(let r of t)for(let i of r.eventTypes)m(e,i)||(e[i]=n.length,n.push(i));let o=Object.create(null);for(let r of t)o[r.templateKey]=$r(r,e,n.length);return{eventCodeByType:e,eventTypesByCode:n,metadataByKey:o}},z=(t,e)=>e===R?Ct:e<R?Ar[e]:t.publicStates[e];var It=(t,e,n,o,r)=>{let i=Wt(t,n,o,r,{ownership:"owned"});i&&e.push(i)};import{LiteFsmError as jr}from"@lite-fsm/core";var gn={f32:()=>new Float32Array(0),i16:()=>new Int16Array(0),i32:()=>new Int32Array(0),u8:()=>new Uint8Array(0),string:()=>[]},hn=t=>gn[t.kind](),Rn=(t,e,n)=>{if(t.length>=n)return t;if(e.kind==="string"){let i=t.slice();i.length=n;for(let a=t.length;a<n;a+=1)i[a]="";return i}let o=gn[e.kind](),r=new o.constructor(n);return r.set(t),r},Jt=(t,e,n=0)=>{if(t.length>=e)return t;let o=new Int16Array(e);return o.fill(n),o.set(t),o},Qt=(t,e,n=0)=>{if(t.length>=e)return t;let o=new Int32Array(e);return o.fill(n),o.set(t),o},Xt=(t,e)=>{if(t.length>=e)return t;let n=new Uint8Array(e);return n.set(t),n},vt=(t,e)=>{if(t.length>=e)return t;let n=new Uint32Array(e);return n.set(t),n},at=t=>t.default!==void 0?t.default:t.kind==="string"?"":0;var Zt=t=>t.map(()=>[]),Cn=t=>({storage:"entity",version:t.version,count:t.count,capacity:t.capacity}),_=t=>{t.publicSlice=Cn(t)},Tt=t=>{t.pendingPrevStateCodeSync.length=0,t.pendingPrevStateCodeSyncToken+=1,t.pendingPrevStateCodeSyncToken>=4294967295&&(t.pendingPrevStateCodeSyncMark.fill(0),t.pendingPrevStateCodeSyncToken=1)},te=(t,e)=>{for(let n=0;n<e.length;n+=1)bt(t,e[n])},bt=(t,e)=>{let n=t.pendingPrevStateCodeSyncMark,o=t.pendingPrevStateCodeSyncToken;n[e]!==o&&(n[e]=o,t.pendingPrevStateCodeSync.push(e))},ee=t=>{let e=t.pendingPrevStateCodeSync,n=t.pendingPrevStateCodeSyncMark,o=t.pendingPrevStateCodeSyncToken,r=t.presence;for(let i=0;i<r.length;i+=1)r[i]!==1||n[i]===o||(n[i]=o,e.push(i))},ne=t=>{let e=t.pendingPrevStateCodeSync;if(e.length===0)return;let n=t.presence,o=t.prevStateCode,r=t.stateCode;for(let i=0;i<e.length;i+=1){let a=e[i];n[a]===1&&(o[a]=r[a])}Tt(t)},st=t=>{t.acceptStateBucketsByEventCode=t.metadata.acceptStateCodesByEventCode.map(e=>e.flatMap(n=>n>=0?[t.stateBuckets[n]]:[]))},kt=(t,e,n)=>{let o=t.entitiesByGroupTag[n]??[];o.length===0&&(t.entitiesByGroupTag[n]=o),t.groupTagPosition[e]=o.length,o.push(e)},Lr=(t,e)=>{let n=t.groupTagByIndex[e],o=t.entitiesByGroupTag[n],r=t.groupTagPosition[e];if(!o||r<0)return;let i=o.pop();i!==void 0&&i!==e&&(o[r]=i,t.groupTagPosition[i]=r),o.length===0&&delete t.entitiesByGroupTag[n],t.groupTagPosition[e]=-1},xn=(t,e,n,o)=>{let r=t.actorRowsByEntity[n]??[];r.length===0&&(t.actorRowsByEntity[n]=r);let i=t.actorRowsByGroupTag[o]??[];i.length===0&&(t.actorRowsByGroupTag[o]=i);let a={store:e,entity:n,groupTag:o,entityRowsPosition:r.length,groupRowsPosition:i.length};r.push(a),i.push(a)},An=(t,e,n,o)=>{if(!t||n<0||t[n]!==e)return!1;let r=t.pop();return r!==void 0&&r!==e&&(t[n]=r,o(r,n)),!0},Nr=(t,e)=>{let n=t.actorRowsByEntity[e.entity];An(n,e,e.entityRowsPosition,(o,r)=>{o.entityRowsPosition=r}),e.entityRowsPosition=-1},In=(t,e)=>{let n=t.actorRowsByGroupTag[e.groupTag];An(n,e,e.groupRowsPosition,(o,r)=>{o.groupRowsPosition=r}),e.groupRowsPosition=-1,n&&n.length===0&&delete t.actorRowsByGroupTag[e.groupTag]},Vr=(t,e)=>{Nr(t,e),In(t,e)},vn=(t,e,n)=>{if(n<0)return;let o=t.stateBuckets[n],r=t.statePosition[e];if(!o||r<0)return;let i=o.pop();i!==void 0&&i!==e&&(o[r]=i,t.statePosition[i]=r),t.statePosition[e]=-1},Tn=(t,e,n)=>{if(n<0)return;let o=t.stateBuckets[n];o&&(t.statePosition[e]=o.length,o.push(e))},oe=(t,e,n,o)=>{n!==o&&(vn(t,e,n),Tn(t,e,o))},re=(t,e,n,o)=>{if(e===n||e<0||n<0)return!1;let r=t.stateBuckets[e],i=t.stateBuckets[n];return r!==o||!i||i.length!==0?!1:(t.stateBuckets[e]=i,t.stateBuckets[n]=r,st(t),!0)},ie=(t,e,n,o,r="row")=>{let i=0;for(let a=0;a<n.length;a+=1){let s=n[a],c=s.entity;s.store!==e||e.presence[c]!==1||(vn(e,c,o?.[a]??e.stateCode[c]),r==="fullEntity"?(s.entityRowsPosition=-1,In(t,s)):Vr(t,s),e.presence[c]=0,e.stateCode[c]=R,e.prevStateCode[c]=R,e.rowVersion[c]=0,i+=1)}return i===0?0:(e.count-=i,e.version+=1,_(e),i)},Bt=(t,e)=>{let n=t.entityStore,o=0;for(let r of e){if(n.alive[r]!==1)continue;let i=n.ids[r];Lr(n,r),delete n.indexById[i],n.ids[r]="",n.alive[r]=0,n.groupTagByIndex[r]="",n.freeList.push(r),t.actorRowsByEntity[r]=[],o+=1}return o===0?0:(n.count-=o,n.version+=1,o)},ae=(t,e)=>{let n=t.actorStores[e.key];if(!n)throw new Error(`[lite-fsm/entities] missing actor store for entity template '${e.key}'.`);return n.publicSlice=Cn(n),n.publicSlice},J=(t,e)=>{let n=e;for(let o of Object.values(t.actorStores))n[o.templateKey]!==o.publicSlice&&(n===e&&(n={...e}),n[o.templateKey]=o.publicSlice);return n},se=t=>{let e=t.entityStore;e.indexById=Object.create(null),e.entitiesByGroupTag=Object.create(null),e.groupTagPosition=new Int32Array(e.capacity),e.groupTagPosition.fill(-1),e.count=0,t.actorRowsByEntity=Array.from({length:e.capacity},()=>[]),t.actorRowsByGroupTag=Object.create(null),t.routingScratchVersion=0;for(let n of Object.values(t.actorStores))n.count=0,n.stateBuckets=Zt(n.metadata.publicStates),n.statePosition=new Int32Array(n.capacity),n.statePosition.fill(-1),n.acceptedScratch=[],n.routingScratchVersion=0,st(n);for(let n=0;n<e.capacity;n+=1){if(e.alive[n]!==1)continue;let o=n;e.indexById[e.ids[n]]=o,kt(e,o,e.groupTagByIndex[n]),e.count+=1}for(let n of Object.values(t.actorStores)){for(let o=0;o<n.capacity;o+=1){if(n.presence[o]!==1)continue;let r=o;Tn(n,r,n.stateCode[o]),xn(t,n,r,e.groupTagByIndex[o]),n.count+=1}_(n)}};var ce=new WeakMap,bn=(t,e,n)=>new jr("LITE_FSM_INVALID_STORAGE_CONFIG",`[lite-fsm/entities] machine '${t}' resource '${e}' ${n}.`),kn=t=>t instanceof Promise,Fr=(t,e)=>wt(e,{indices:[],has(n){return e.presence[n]===1},entityId(n){let o=t.ids[n];if(o!==void 0)return o;throw g(`unknown entity index ${n}`)}}),ct=t=>{jt(t.reducerSelf,t)},Bn=(t,e)=>(t.reducerSelf.indices=e,t.reducerSelf),Kr=t=>{let e=Object.create(null),n=Object.create(null);for(let[o,r]of Object.entries(t.resourceSchema)){let i=r.factory();if(kn(i))throw bn(t.templateKey,o,"factory returned a Promise; resource factories are sync-only");if(e[o]=i,!r.exposed)continue;let a=r.expose,s=a(i);if(kn(s))throw bn(t.templateKey,o,"expose returned a Promise; resource expose functions are sync-only");n[o]=s}return{resources:e,resourceViews:n}},Ur=()=>({count:0,capacity:0,ids:[],indexById:Object.create(null),alive:new Uint8Array(0),generation:new Uint32Array(0),groupTagByIndex:[],entitiesByGroupTag:Object.create(null),groupTagPosition:new Int32Array(0),freeList:[],version:0}),Gr=(t,e,n)=>{let o=Object.fromEntries(Object.entries(t.initialContext).map(([a,s])=>[a,hn(s)])),r=Kr(t),i={storeId:n,templateKey:t.templateKey,metadata:t,capacity:0,count:0,version:0,presence:new Uint8Array(0),stateCode:new Int16Array(0),prevStateCode:new Int16Array(0),rowVersion:new Uint32Array(0),stateBuckets:Zt(t.publicStates),statePosition:new Int32Array(0),acceptedScratch:[],defaultTransitionSourceStateScratch:[],pendingPrevStateCodeSync:[],pendingPrevStateCodeSyncMark:new Uint32Array(0),pendingPrevStateCodeSyncToken:1,routingScratchVersion:0,acceptStateBucketsByEventCode:[],columns:o,resources:r.resources,resourceViews:r.resourceViews,reducerSelf:void 0,publicSlice:{storage:"entity",version:0,count:0,capacity:0}};return i.reducerSelf=Fr(e,i),i.acceptStateBucketsByEventCode=t.acceptStateCodesByEventCode.map(a=>a.flatMap(s=>s>=0?[i.stateBuckets[s]]:[])),_(i),i},Pn=(t,e)=>{let n=wn(t.map(r=>r.data)),o={entityStore:Ur(),actorStores:Object.create(null),actorStoresById:[],eventCodeByType:n.eventCodeByType,eventTypesByCode:n.eventTypesByCode,templatesByEventCode:n.eventTypesByCode.map(()=>[]),actorRowsByEntity:[],actorRowsByGroupTag:Object.create(null),routingScratchVersion:0,access:void 0};for(let r=0;r<t.length;r+=1){let i=t[r],a=n.metadataByKey[i.key],s=Gr(a,o.entityStore,r);o.actorStores[i.key]=s,o.actorStoresById[r]=s;for(let c=0;c<a.eventAcceptMask.length;c+=1)a.eventAcceptMask[c]===1&&o.templatesByEventCode[c].push(s)}return o.access=_e(o),ce.set(e,o),ce.set(o.access,o),o},Mn=t=>{let e=ce.get(t);if(!e)throw new Error("[lite-fsm/entities] entity runtime state is not initialized for this manager.");return e},D=t=>t,Dn=(t,e)=>{t.capacity>=e||(t.capacity=e,t.alive=Xt(t.alive,e),t.generation=vt(t.generation,e),t.groupTagPosition=Qt(t.groupTagPosition,e,-1))},On=(t,e)=>{if(!(t.capacity>=e)){t.capacity=e,t.presence=Xt(t.presence,e),t.stateCode=Jt(t.stateCode,e,R),t.prevStateCode=Jt(t.prevStateCode,e,R),t.rowVersion=vt(t.rowVersion,e),t.statePosition=Qt(t.statePosition,e,-1),t.pendingPrevStateCodeSyncMark=vt(t.pendingPrevStateCodeSyncMark,e);for(let[n,o]of Object.entries(t.metadata.initialContext))t.columns[n]=Rn(t.columns[n],o,e);ct(t),q(t)}};var de=(t,e,n)=>{if(!(n===R||t.metadata.publicStates[n]!==void 0||P(n)))throw g(`actor '${t.templateKey}' reducer wrote invalid stateCode ${n} for entity ${e}`)},Hr=t=>{for(let e of t.metadata.effectsByStateCode)if(e)return!0;return!1},_n=(t,e,n)=>{let o=t.metadata.reducer!==void 0;return{scheduleDespawnOn:(n.scheduleDespawnOn??!0)&&At(t.metadata.despawnStateMask),scheduleEffects:(n.scheduleEffects??!0)&&(e?.mayEnterEffectState===!0||o&&Hr(t)),collectReactionSurvivors:n.scheduleReactions===!0&&e?.hasReaction===!0&&(n.scheduleDespawnOn??!0)&&At(t.metadata.despawnStateMask),scheduleTerminal:(n.scheduleTerminal??!0)&&(e?.mayEnterTerminalState===!0||o)}},Yr=(t,e,n,o,r)=>{let i=t??new Map,a={entity:o,generation:e.generation[o],id:e.ids[o]},s=i.get(n);return s?(s.indices!==r&&s.indices.push(o),s.entries.push(a),i):(i.set(n,{indices:i.size===0?r:[o],entries:[a]}),i)},$n=t=>{if(t.indices.length===t.entries.length)return t.indices;let e=new Array(t.entries.length);for(let n=0;n<t.entries.length;n+=1)e[n]=t.entries[n].entity;return e},qr=(t,e,n,o,r)=>{let i=e.stateCode,a=e.rowVersion,s,c=!1;for(let d=0;d<n.length;d+=1){let y=n[d],u=i[y];a[y]+=1,u!==r&&(de(e,y,u),s||(s=[]),s.push(y),o.scheduleTerminal&&P(u)&&(c=!0,t&&t.terminalRows.push({store:e,entity:y})))}return{dirtyRows:s,dirtyRowsPreviousStateCode:s?r:void 0,dirtyRowsPreviousStateCodes:void 0,bulkStateTransition:void 0,enteredByState:void 0,cleanupRemovesAcceptedRows:c,despawnOnRemovesAcceptedRows:!1,acceptedRowsHaveFinalRemoval:!1,reactionSurvivorRows:void 0}},Wr=(t,e,n,o,r,i)=>{let a=e.stateCode,s=e.rowVersion,c=e.metadata.despawnStateMask,d,y=!1,u=!1,p=!1;for(let w=0;w<n.length;w+=1){let E=n[w],l=a[E];if(l===r){s[E]+=1;continue}if(l!==i&&de(e,E,l),s[E]+=1,l>=0&&c[l]===1&&(y=!0,u=!0,t&&nt(t,E),!Ln(e,l))){p=!0,t&&Ht(t,e,E,r);continue}d||(d=[]),d.push(E),o.scheduleTerminal&&P(l)&&(y=!0,t&&t.terminalRows.push({store:e,entity:E}))}return{dirtyRows:d,dirtyRowsPreviousStateCode:d?r:void 0,dirtyRowsPreviousStateCodes:void 0,bulkStateTransition:void 0,enteredByState:void 0,cleanupRemovesAcceptedRows:y,despawnOnRemovesAcceptedRows:u,acceptedRowsHaveFinalRemoval:p,reactionSurvivorRows:void 0}},zr=(t,e)=>{for(let n of t.acceptStateCodes)if(n===e)return!0;return!1},Jr=(t,e,n,o,r,i)=>{if(o?.hasNonIdentityDefaultTransition&&!(r===void 0||i===void 0)&&r!==i&&!(r<0||i<0)&&zr(o,r)&&t.stateBuckets[r]===e&&t.stateBuckets[i]?.length===0&&!(n.scheduleDespawnOn&&t.metadata.despawnStateMask[i]===1))return{indices:e,previousStateCode:r,stateCode:i}},Qr=(t,e)=>{let n=t.runtime.entityStore,o=new Array(e.length);for(let r=0;r<e.length;r+=1){let i=e[r];o[r]={entity:i,generation:n.generation[i],id:n.ids[i]}}return{indices:e,entries:o}},Ln=(t,e)=>{let n=e+1;return n>=0&&t.metadata.despawnLifecycleStateMask[n]===1},Xr=(t,e,n,o,r)=>n!==void 0?n:o===void 0?r[t]:o[e],Zr=(t,e,n,o,r,i,a)=>{let s=Jr(e,n,o,r,i,a);if(!s)return;let c=e.stateCode;for(let u=0;u<n.length;u+=1)if(c[n[u]]!==s.stateCode)return;let d=e.rowVersion;for(let u=0;u<n.length;u+=1){let p=n[u];d[p]+=1,bt(e,p)}let y;return o.scheduleEffects&&t&&e.metadata.effectsByStateCode[s.stateCode]&&(y=new Map,y.set(s.stateCode,Qr(t,n))),{dirtyRows:void 0,dirtyRowsPreviousStateCode:void 0,dirtyRowsPreviousStateCodes:void 0,bulkStateTransition:s,enteredByState:y,cleanupRemovesAcceptedRows:!1,despawnOnRemovesAcceptedRows:!1,acceptedRowsHaveFinalRemoval:!1,reactionSurvivorRows:void 0}},Nn=(t,e,n,o,r,i,a,s)=>{let c=Zr(t,e,n,o,r,i,a);if(c)return c;if(i!==void 0&&!o.scheduleDespawnOn&&!o.scheduleEffects)return qr(t,e,n,o,i);if(i!==void 0&&o.scheduleDespawnOn&&!o.scheduleEffects&&!o.collectReactionSurvivors&&(i<0||e.metadata.despawnStateMask[i]!==1))return Wr(t,e,n,o,i,a);let d,y,u,p=!1,w=!1,E=!1,l,f=i!==void 0,U=e.stateCode,$=e.prevStateCode,Z=e.rowVersion,tt=e.metadata.despawnStateMask,Ot=e.metadata.effectsByStateCode;for(let C=0;C<n.length;C+=1){let b=n[C],k=U[b],_t=Xr(b,C,i,s,$),Ce=k!==_t;(Ce||!f)&&!(i!==void 0&&(k===i||k===a))&&de(e,b,k),Z[b]+=1;let xe=!1;if(o.scheduleDespawnOn&&k>=0&&tt[k]===1){if(p=!0,w=!0,xe=!0,o.collectReactionSurvivors&&!l){l=[];for(let $t=0;$t<C;$t+=1)l.push(n[$t])}if(t&&nt(t,b),!Ln(e,k)){E=!0,t&&Ht(t,e,b,_t);continue}}else l?.push(b);if(Ce){if(d||(d=[],i===void 0&&(y=[])),d.push(b),y?.push(_t),o.scheduleTerminal&&P(k)){p=!0,t&&t.terminalRows.push({store:e,entity:b});continue}o.scheduleEffects&&t&&!xe&&k>=0&&Ot[k]&&(u=Yr(u,t.runtime.entityStore,k,b,d))}}return{dirtyRows:d,dirtyRowsPreviousStateCode:d?i:void 0,dirtyRowsPreviousStateCodes:y,bulkStateTransition:void 0,enteredByState:u,cleanupRemovesAcceptedRows:p,despawnOnRemovesAcceptedRows:w,acceptedRowsHaveFinalRemoval:E,reactionSurvivorRows:l}};var Vn=(t,e,n,o)=>{if(n===void 0)return{accepted:!1,nextState:void 0,sourceStateCode:F};let r=t.stateCode[e],i=r+1;if(i<0||i>=t.metadata.stateSlotCount)throw g(`actor '${t.templateKey}' has invalid stateCode ${r} for entity ${e}`);let a=n*t.metadata.stateSlotCount+i,s=t.metadata.transitionTable[a];if(s===F)return{accepted:!1,nextState:void 0,sourceStateCode:r};if(s===xt)throw g(`actor '${t.templateKey}' transition '${o}' targets unknown state '${t.metadata.transitionTargetByCell[a]}'`);return t.prevStateCode[e]=r,t.stateCode[e]=s,{accepted:!0,nextState:z(t.metadata,s),sourceStateCode:r}},jn=t=>{if(t.accepted)return t.indices;let e=t.store.acceptedScratch;e.length=0;for(let n=0;n<t.indices.length;n+=1){let o=t.indices[n];Vn(t.store,o,t.eventCode,t.action.type).accepted&&e.push(o)}return e},ti=(t,e)=>{if(!t.accepted||t.eventCode===void 0)return;let n=t.store.metadata.reducePlansByEventCode[t.eventCode];if(n){for(let o of n.acceptStateCodes)if(o>=0&&t.store.stateBuckets[o]===e)return o}},ei=(t,e)=>{let n=ti(t,e);if(n===void 0)return;let o=t.store,i=t.eventCode*o.metadata.stateSlotCount+n+1,a=o.metadata.transitionTable[i];if(a===F)return;if(a===xt)throw g(`actor '${o.templateKey}' transition '${t.action.type}' targets unknown state '${o.metadata.transitionTargetByCell[i]}'`);if(a===n)return ne(o),{firstNextState:z(o.metadata,n),previousStateCodeForAccepted:n,knownValidStateCodeForAccepted:n};let s=o.prevStateCode,c=o.stateCode;for(let d=0;d<e.length;d+=1){let y=e[d];if(c[y]!==n)throw g(`actor '${o.templateKey}' has invalid stateCode ${c[y]} for entity ${y}`);s[y]=n,c[y]=a}return{firstNextState:z(o.metadata,a),previousStateCodeForAccepted:n,knownValidStateCodeForAccepted:a}},Fn=(t,e)=>{let n=ei(t,e);if(n!==void 0)return n;let o;if(!t.accepted){let i=t.store.stateCode,a=t.store.prevStateCode,s=t.store.defaultTransitionSourceStateScratch;s.length=e.length;for(let c=0;c<e.length;c+=1){let d=e[c];s[c]=a[d],o??(o=z(t.store.metadata,i[d]))}return{firstNextState:o,previousStateCodeForAccepted:void 0,sourceStateCodesByAccepted:s}}let r=t.store.defaultTransitionSourceStateScratch;r.length=e.length;for(let i=0;i<e.length;i+=1){let a=e[i],s=Vn(t.store,a,t.eventCode,t.action.type);r[i]=s.sourceStateCode,o??(o=s.nextState)}return{firstNextState:o,previousStateCodeForAccepted:void 0,sourceStateCodesByAccepted:r}};var ni=t=>{t.version+=1,_(t)},Kn=(t,e,n,o)=>{let r=t.prevStateCode,i=t.stateCode;for(let a=e.length-1;a>=0;a-=1){let s=e[a],c=n;c===void 0&&o!==void 0&&(c=o[a]),c===void 0&&(c=r[s]),oe(t,s,c,i[s])}},oi=(t,e,n)=>{if(!(!t||!n))for(let[o,r]of n)pn(t,e,o,$n(r),r.entries)},Un=(t,e,n)=>{let o=t.acceptStateBucketsByEventCode[e];return o!==void 0&&o.length===1&&o[0]===n},ri=(t,e,n)=>!n.allowBorrowedReactionBatch||t?.allDefaultTransitionsIdentity!==!0||e.dirtyRows&&e.dirtyRows.length>0||e.cleanupRemovesAcceptedRows?"owned":"borrowed",ii=(t,e)=>e.despawnOnRemovesAcceptedRows?e.reactionSurvivorRows??[]:t,ai=(t,e)=>e?n=>{let o=n-e.firstEntity;if(o>=0&&o<e.indices.length&&e.indices[o]===n)return e.payloads[o];let r=e.positionsByEntity?.[n];if(r!==void 0&&e.indices[r]===n)return e.payloads[r];throw g(`payloadFor(entity) for actor '${t.templateKey}' only accepts EntityIndex values from current spawn scope`)}:()=>{throw g(`payloadFor(entity) is only available while reducing ${O}`)},si=t=>{if(t.eventCode!==void 0)return t.store.metadata.reducePlansByEventCode[t.eventCode]},Q=(t,e,n,o={})=>{let r=o.traceBatchPrefix??"entities.reduce.publicBatch",i=o.tracePublicBatch||o.traceBatchPrefix?o.trace:void 0,a=i?.now();try{let s=[],c,d,y,u,p=i?.now();try{if(s=jn(e),s.length===0)return!1;let C=Fn(e,s);c=C.firstNextState,d=C.previousStateCodeForAccepted,y=C.sourceStateCodesByAccepted,u=C.knownValidStateCodeForAccepted}finally{h(i,`${r}.defaultTransitions`,p)}let w=e.store.metadata.reducer,E=i?.now();try{if(w){let C=c;if(w({state:C,context:{}},e.action,{nextState:C,config:e.store.metadata.config,self:Bn(e.store,s),entities:()=>t.access,payloadFor:ai(e.store,e.payloadScope)})instanceof Promise)throw g(`reducer for actor '${e.store.templateKey}' and event '${e.action.type}' returned a Promise; entity reducers are sync-only`)}}finally{h(i,`${r}.userReducer`,E)}let l=si(e),f,U=i?.now();try{f=Nn(n,e.store,s,_n(e.store,l,o),l,d,u,y)}finally{h(i,`${r}.postProcess`,U)}let $=i?.now();try{ni(e.store)}finally{h(i,`${r}.markTouched`,$)}let Z=i?.now();try{oi(n,e.store,f.enteredByState)}finally{h(i,`${r}.scheduleEffects`,Z)}let tt=i?.now();try{if(o.scheduleReactions&&e.eventCode!==void 0){let C=ii(s,f);C.length>0&&ln(n,e.store,e.eventCode,C,{ownership:ri(l,f,o)})}}finally{h(i,`${r}.scheduleReactions`,tt)}let Ot=i?.now();try{f.bulkStateTransition&&(re(e.store,f.bulkStateTransition.previousStateCode,f.bulkStateTransition.stateCode,f.bulkStateTransition.indices)||Kn(e.store,f.bulkStateTransition.indices,f.bulkStateTransition.previousStateCode)),f.dirtyRows&&(Kn(e.store,f.dirtyRows,f.dirtyRowsPreviousStateCode,f.dirtyRowsPreviousStateCodes),te(e.store,f.dirtyRows))}finally{h(i,`${r}.updateStateBuckets`,Ot)}return o.onAccepted?.(s),!0}finally{h(i,`${r}.total`,a)}};var Gn=new WeakMap,ci=()=>({markers:new Uint32Array(0),generation:new Uint32Array(0),compactIndices:[],lifetime:{token:0},token:0}),di=t=>{let e=Gn.get(t);if(e)return e;let n=ci();return Gn.set(t,n),n},yi=(t,e)=>{if(t.markers.length>=e)return;let n=new Uint32Array(e);n.set(t.markers),t.markers=n;let o=new Uint32Array(e);o.set(t.generation),t.generation=o},ui=t=>(t.token+=1,t.token>=4294967295&&(t.markers.fill(0),t.generation.fill(0),t.token=1),t.token),pi=(t,e,n)=>{if(e.presence[n]!==1||t.entityStore.alive[n]!==1)return!1;let o=t.entityStore.ids[n];return o!==void 0&&o.length>0},ye=t=>{t.lifetime.token=0,t.compactIndices.length=0},li=(t,e,n,o)=>{let r=di(t);ye(r),yi(r,Math.max(t.entityStore.generation.length,e.presence.length));let i=ui(r),a;if(o==="borrowed")for(let c=0;c<n.length;c+=1){let d=n[c];r.markers[d]=i,r.generation[d]=t.entityStore.generation[d]}else for(let c=0;c<n.length;c+=1){let d=n[c];if(!pi(t,e,d)){if(!a){a=r.compactIndices,a.length=0;for(let y=0;y<c;y+=1)a.push(n[y])}continue}r.markers[d]=i,r.generation[d]=t.entityStore.generation[d],a?.push(d)}let s=a??n;if(s.length===0){ye(r);return}return r.lifetime.token=i,{scratch:r,scope:{indices:s,markers:r.markers,generation:r.generation,lifetime:r.lifetime,token:i}}},fi=(t,e,n,o)=>{let r=Ve(t),i=Object.create(o.manager.getDependencies());return i.action=o.action,i.self=Ne(t,e,n),i.entities=()=>r,i.transition=void 0,i.condition=void 0,i},Si=(t,e)=>g(`reaction for actor '${t.templateKey}' and event '${e}' returned a Promise; entity reactions are sync-only`),Hn=(t,e,n,o,r="entities.reactions")=>{let i=e.store.metadata.reactionsByEventCode[e.eventCode];if(!i)return;let a=o?.now(),s=li(t,e.store,e.indices,e.ownership);if(h(o,`${r}.captureScope`,a),!s)return;let c=o?.now(),d=fi(t,e.store,s.scope,n);h(o,`${r}.createDeps`,c);let y=o?.now();try{i(d)instanceof Promise&&n.dispatch.reportError(Si(e.store,n.action.type))}catch(u){n.dispatch.reportError(u)}finally{h(o,`${r}.user`,y),ye(s.scratch)}},Pt=(t,e,n,o,r)=>{for(let i of e)Hn(t,i,n,o,r)},Yn=(t,e)=>{let n=j(e.dispatch);if(!n||n.reactionBatches.length===0)return;let o=V(e.dispatch);for(let r of n.reactionBatches)Hn(t,r,e,o)};var qn={type:L},T=(t,e,n,o)=>{G(t,`entities.cleanup.${e}.${n}`,o)},Ei=t=>{if(!t)return 0;let e=0;for(let n of t.lifecycleTouchedStoreIds)e+=t.lifecycleBatchesByStoreId[n]?.indices.length??0;return e},mi=(t,e)=>{let n=t.stateCode[e]+1;return n>=0&&t.metadata.despawnLifecycleStateMask[n]===1},Wn=(t,e,n)=>{let o=t?sn(t,n.store.storeId,n.entity):void 0;yn(e,n.store,n,o)},wi=(t,e,n,o)=>{let r=t.eventCodeByType[L];for(let i of n){if(t.entityStore.alive[i]!==1)continue;o.entities.push(i);let a=t.actorRowsByEntity[i];if(a)for(let s of a){let{store:c}=s;c.presence[i]===1&&(Wn(e,o,s),r!==void 0&&mi(c,i)&&un(o,c,i))}}},gi=(t,e,n)=>{let o=t.actorRowsByEntity[n];if(o){for(let r of o)if(r.store===e)return r}},zn=(t,e,n="row")=>{let o=0;for(let r of e.removalTouchedStoreIds){let i=e.removalBatchesByStoreId[r];if(!i)continue;let a=ie(t,i.store,i.rows,i.bucketStateCodesActive?i.bucketStateCodes:void 0,n);o+=a}return o},hi=(t,e)=>{let n=0;for(let o=0;o<e.length;o+=1){let r=e[o],i=t.actorRowsByEntity[r];i&&i.length>0||(e[n]=r,n+=1)}return e.length=n,Bt(t,e)},Ri=(t,e,n,o)=>{if(e.terminalRows.length===0)return T(n,o,"terminalRows",0),!1;let r=Yt(e);try{let i=n?.now();try{let y=e.terminalRows;e.terminalRows=[],T(n,o,"terminalRows",y.length);for(let u of y){if(!P(u.store.stateCode[u.entity]))continue;let p=gi(t,u.store,u.entity);p&&(Wn(void 0,r,p),r.entities.push(u.entity))}}finally{h(n,`entities.cleanup.${o}.collectPlan`,i)}let a=!1,s=0,c=n?.now();try{s=zn(t,r)}finally{T(n,o,"removedActorRows",s),h(n,`entities.cleanup.${o}.removeActorRows`,c)}a=s>0;let d=n?.now();try{let y=hi(t,r.entities);T(n,o,"removedEntityRecords",y),a=y>0||a}finally{h(n,`entities.cleanup.${o}.removeEntityRecords`,d)}return a}finally{qt(e,r)}},ue=(t,e,n,o,r)=>{if(!e)return!1;let i=!1,a=dn(e);T(r,o,"scheduledDespawns",a.length);let s;try{let d=r?.now();try{a.length>0&&(s=Yt(e),wi(t,e,a,s))}finally{h(r,`entities.cleanup.${o}.collectPlan`,d)}if(T(r,o,"despawnedEntities",s?.entities.length??0),T(r,o,"touchedTemplates",s?.removalTouchedStoreIds.length??0),T(r,o,"lifecycleBatches",s?.lifecycleTouchedStoreIds.length??0),T(r,o,"lifecycleRows",Ei(s)),T(r,o,"removalBatches",s?.removalTouchedStoreIds.length??0),s){let y=t.eventCodeByType[L],u=[],p=r?.now();try{for(let U of s.lifecycleTouchedStoreIds){let $=s.lifecycleBatchesByStoreId[U];if(!$)continue;let Z=Q(t,{store:$.store,indices:$.indices,action:qn,eventCode:y,accepted:!0},e,{scheduleDespawnOn:!1,scheduleEffects:!1,scheduleReactions:!1,scheduleTerminal:!1,onAccepted(tt){It(e,u,$.store,y,tt)}});i=i||Z}Pt(t,u,{action:qn,manager:n.manager,dispatch:n.dispatch})}finally{h(r,`entities.cleanup.${o}.lifecycle`,p)}let w=0,E=r?.now();try{w=zn(t,s,"fullEntity")}finally{T(r,o,"removedActorRows",w),h(r,`entities.cleanup.${o}.removeActorRows`,E)}let l=0,f=r?.now();try{l=Bt(t,s.entities)}finally{T(r,o,"removedEntityRecords",l),h(r,`entities.cleanup.${o}.removeEntityRecords`,f)}w>0&&(i=!0),l>0&&(i=!0)}}finally{cn(e),s&&qt(e,s)}let c=Ri(t,e,r,o);return i=i||c,i};var Ci=t=>t,xi=t=>Object.entries(t.metadata.initialContext).map(([e,n])=>({name:e,value:at(n)})),Ai=(t,e)=>{let n=t.get(e.templateKey);if(n)return n;let o={store:e,defaultEntries:xi(e),requiredCapacity:e.capacity,addedRows:0};return t.set(e.templateKey,o),o},Ii=(t,e)=>{let n=t.get(e.templateKey);if(n)return n;let o={store:e,indices:[],payloads:[]};return t.set(e.templateKey,o),o},vi=(t,e)=>{let n=t[0],o=!0;for(let i=1;i<t.length;i+=1)if(t[i]!==n+i){o=!1;break}if(o)return{indices:t,payloads:e,firstEntity:n};let r=Object.create(null);for(let i=0;i<t.length;i+=1)r[t[i]]=i;return{indices:t,payloads:e,firstEntity:n,positionsByEntity:r}},Ti=t=>t.map(e=>({store:e.store,indices:e.indices,payloadScope:vi(e.indices,e.payloads)})),bi=(t,e)=>{let n=t.entityStore,o=n.freeList.length,r=Math.min(o,e.length),i=new Array(e.length),a=new Map,s=new Map,c=n.capacity;for(let d=0;d<e.length;d+=1){let y=d<o?n.freeList[o-1-d]:Ci(n.ids.length+(d-o));i[d]=y,c=Math.max(c,y+1);let u=e[d];for(let p of u.actors){let w=t.actorStores[p.templateKey],E=Ai(a,w);E.requiredCapacity=Math.max(E.requiredCapacity,y+1),E.addedRows+=1;let l=Ii(s,w);l.indices.push(y),l.payloads.push(p.payload)}}return{assignedEntities:i,batches:[...s.values()],actorPlans:a,requiredEntityCapacity:c,usedFreeListCount:r}},ki=(t,e)=>{e.requiredEntityCapacity>t.entityStore.capacity&&Dn(t.entityStore,e.requiredEntityCapacity);for(let n of e.actorPlans.values())n.requiredCapacity>n.store.capacity&&On(n.store,n.requiredCapacity)},Bi=(t,e,n)=>{for(let o=0;o<n.length;o+=1){let r=n[o];t.columns[r.name][e]=r.value}},Pi=(t,e,n,o)=>{let r=t.actorRowsByEntity[n]??[];r.length===0&&(t.actorRowsByEntity[n]=r);let i=t.actorRowsByGroupTag[o]??[];i.length===0&&(t.actorRowsByGroupTag[o]=i);let a={store:e,entity:n,groupTag:o,entityRowsPosition:r.length,groupRowsPosition:i.length};r.push(a),i.push(a)},Mi=(t,e,n)=>{let o=t.entityStore;n.usedFreeListCount>0&&(o.freeList.length-=n.usedFreeListCount);for(let r=0;r<e.length;r+=1){let i=e[r],a=n.assignedEntities[r];o.ids[a]=i.id,o.indexById[i.id]=a,o.alive[a]=1,o.generation[a]+=1,o.groupTagByIndex[a]=i.groupTag,kt(o,a,i.groupTag)}e.length!==0&&(o.count+=e.length,o.version+=1)},Di=(t,e,n)=>{for(let o=0;o<e.length;o+=1){let r=e[o],i=n.assignedEntities[o];for(let a of r.actors){let s=n.actorPlans.get(a.templateKey),c=s.store;c.presence[i]=1,c.stateCode[i]=R,c.prevStateCode[i]=R,c.rowVersion[i]=0,Bi(c,i,s.defaultEntries),Pi(t,c,i,r.groupTag)}}for(let o of n.actorPlans.values())o.store.count+=o.addedRows,o.store.version+=1,_(o.store)},Jn=(t,e)=>{let n=bi(t,e);return ki(t,n),Mi(t,e,n),Di(t,e,n),Ti(n.batches)};var Qn={type:O},Xn=(t,e,n,o,r)=>{if(e.length===0)return!1;let i=x(r,"entities.reduce.spawnLifecycle.applyStagedSpawns",()=>Jn(t,e)),a=[];return x(r,"entities.reduce.spawnLifecycle.reduceBatches",()=>{for(let s of i)Q(t,{store:s.store,indices:s.indices,action:Qn,eventCode:t.eventCodeByType[O],payloadScope:s.payloadScope},n,{scheduleReactions:!1,trace:r,traceBatchPrefix:"entities.reduce.spawnLifecycle.batch",onAccepted(c){It(n,a,s.store,t.eventCodeByType[O],c)}})}),x(r,"entities.reduce.spawnLifecycle.reactions",()=>{Pt(t,a,{action:Qn,manager:o.manager,dispatch:o.dispatch},r,"entities.reduce.spawnLifecycle.reactions")}),!0};var Oi=t=>Object.assign(Object.create(null),t),_i=t=>Object.assign(Object.create(null),Object.fromEntries(Object.entries(t).map(([e,n])=>[e,n.slice()]))),$i=t=>t.map(e=>e.slice()),Zn=(t,e)=>{let n=e.get(t);if(n)return n;let o={...t};return e.set(t,o),o},Li=(t,e)=>t.map(n=>n.map(o=>Zn(o,e))),Ni=(t,e)=>Object.assign(Object.create(null),Object.fromEntries(Object.entries(t).map(([n,o])=>[n,o.map(r=>Zn(r,e))]))),Vi=t=>(Array.isArray(t),t.slice()),ji=t=>Object.fromEntries(Object.entries(t).map(([e,n])=>[e,Vi(n)])),Fi=t=>({count:t.count,capacity:t.capacity,ids:t.ids.slice(),indexById:Oi(t.indexById),alive:t.alive.slice(),generation:t.generation.slice(),groupTagByIndex:t.groupTagByIndex.slice(),entitiesByGroupTag:_i(t.entitiesByGroupTag),groupTagPosition:t.groupTagPosition.slice(),freeList:t.freeList.slice(),version:t.version}),Ki=t=>({capacity:t.capacity,count:t.count,version:t.version,presence:t.presence.slice(),stateCode:t.stateCode.slice(),prevStateCode:t.prevStateCode.slice(),rowVersion:t.rowVersion.slice(),stateBuckets:$i(t.stateBuckets),statePosition:t.statePosition.slice(),acceptedScratch:t.acceptedScratch.slice(),pendingPrevStateCodeSync:t.pendingPrevStateCodeSync.slice(),pendingPrevStateCodeSyncMark:t.pendingPrevStateCodeSyncMark.slice(),pendingPrevStateCodeSyncToken:t.pendingPrevStateCodeSyncToken,columns:ji(t.columns),publicSlice:t.publicSlice}),to=t=>{let e=new Map;return{entityStore:Fi(t.entityStore),actorStores:Object.fromEntries(Object.entries(t.actorStores).map(([n,o])=>[n,Ki(o)])),actorRowsByEntity:Li(t.actorRowsByEntity,e),actorRowsByGroupTag:Ni(t.actorRowsByGroupTag,e)}},Ui=(t,e)=>{t.count=e.count,t.capacity=e.capacity,t.ids=e.ids,t.indexById=e.indexById,t.alive=e.alive,t.generation=e.generation,t.groupTagByIndex=e.groupTagByIndex,t.entitiesByGroupTag=e.entitiesByGroupTag,t.groupTagPosition=e.groupTagPosition,t.freeList=e.freeList,t.version=e.version},Gi=(t,e)=>{t.capacity=e.capacity,t.count=e.count,t.version=e.version,t.presence=e.presence,t.stateCode=e.stateCode,t.prevStateCode=e.prevStateCode,t.rowVersion=e.rowVersion,t.stateBuckets=e.stateBuckets,t.statePosition=e.statePosition,t.acceptedScratch=e.acceptedScratch,t.pendingPrevStateCodeSync=e.pendingPrevStateCodeSync,t.pendingPrevStateCodeSyncMark=e.pendingPrevStateCodeSyncMark,t.pendingPrevStateCodeSyncToken=e.pendingPrevStateCodeSyncToken,st(t),t.columns=e.columns,ct(t),q(t),t.publicSlice=e.publicSlice},eo=(t,e)=>{Ui(t.entityStore,e.entityStore);for(let[n,o]of Object.entries(e.actorStores))Gi(t.actorStores[n],o);t.actorRowsByEntity=e.actorRowsByEntity,t.actorRowsByGroupTag=e.actorRowsByGroupTag};var Hi=(t,e,n)=>{let o=n+1;return o<0||o>=t.stateSlotCount?-1:e*t.stateSlotCount+o},Yi=(t,e,n)=>{let o=t.stateCode[e],r=Hi(t.metadata,n,o);if(r<0)throw g(`actor '${t.templateKey}' has invalid stateCode ${o} for entity ${e}`);return t.metadata.transitionTable[r]!==F},qi=(t,e,n,o)=>t.entityStore.alive[o]!==1||e.presence[o]!==1?!1:Yi(e,o,n),Wi=(t,e)=>{let n=t.acceptStateBucketsByEventCode[e];if(!n||n.length===0)return;if(n.length===1)return n[0].length===0?void 0:n[0];let o,r=t.acceptedScratch;r.length=0;for(let i of n)if(i.length!==0){if(!o){o=i;continue}if(r.length===0)for(let a=0;a<o.length;a+=1)r.push(o[a]);for(let a=0;a<i.length;a+=1)r.push(i[a])}return r.length>0?r:o},no=t=>(t.routingScratchVersion+=1,t.routingScratchVersion),oo=(t,e,n,o,r)=>{let{store:i,entity:a}=o;qi(t,i,e,a)&&(i.routingScratchVersion!==n&&(i.routingScratchVersion=n,i.acceptedScratch.length=0),i.acceptedScratch.length===0&&r.push({store:i,indices:i.acceptedScratch,accepted:!0}),i.acceptedScratch.push(a))},zi=(t,e,n)=>{let o=[],r=no(t);for(let i of n){let a=t.entityStore.indexById[i];if(a===void 0)continue;let s=t.actorRowsByEntity[a];if(s)for(let c=0;c<s.length;c+=1)oo(t,e,r,s[c],o)}return o},Ji=(t,e,n)=>{let o=[],r=no(t);for(let i of n){let a=t.actorRowsByGroupTag[i];if(a)for(let s=0;s<a.length;s+=1)oo(t,e,r,a[s],o)}return o},ro=(t,e,n)=>{if(n.scope==="plugin"&&n.key==="entityId")return zi(t,e,n.targetSet);if(n.scope==="tag")return Ji(t,e,n.targetSet);if(n.scope!=="unscoped")return[];let o=t.templatesByEventCode[e];if(!o||o.length===0)return[];let r=[];for(let i of o){let a=Wi(i,e);!a||a.length===0||r.push({store:i,indices:a,accepted:!0})}return r};var io=(t,e)=>{let n=V(e.dispatch),o=an(e.dispatch),r=j(e.dispatch),i=o.length>0?to(t):void 0,a=t.eventCodeByType[e.action.type];return x(n,"entities.reduce.total",()=>{try{let s=x(n,"entities.reduce.spawnLifecycle",()=>Xn(t,o,r,e,n)),c=x(n,"entities.reduce.spawnCleanup",()=>ue(t,r,e,"spawn",n)),d=s||c;if(a===void 0)return d?void 0:{type:"skip"};let y=x(n,"entities.reduce.collectPublicBatches",()=>ro(t,a,e.dispatch.route));for(let p of y)Q(t,{store:p.store,indices:p.indices,action:e.action,eventCode:a,accepted:p.accepted},r,{allowBorrowedReactionBatch:e.dispatch.route.scope==="unscoped"&&Un(p.store,a,p.indices),scheduleReactions:!0,trace:n,tracePublicBatch:!0})&&(d=!0);let u=x(n,"entities.reduce.publicCleanup",()=>ue(t,r,e,"public",n));return d=d||u,d?void 0:{type:"skip"}}catch(s){throw i&&eo(t,i),s}})};import{LiteFsmError as Ca}from"@lite-fsm/core";import{LiteFsmError as Qi}from"@lite-fsm/core";var Xi=t=>t!==null&&typeof t=="object"&&!Array.isArray(t),S=t=>new Qi("LITE_FSM_INVALID_HYDRATION_ENVELOPE",`[lite-fsm/entities] hydrate: invalid snapshot.storage.entity: ${t}.`),H=(t,e)=>{if(Xi(e))return e;throw S(`${t} must be an object`)},X=(t,e)=>{if(Array.isArray(e))return e;throw S(`${t} must be an array`)},dt=(t,e,n)=>{if(e.length!==n)throw S(`${t} length ${e.length} does not match capacity ${n}`)},le=(t,e)=>{if(typeof e=="number"&&Number.isInteger(e))return e;throw S(`${t} must be an integer`)},K=(t,e)=>{let n=le(t,e);if(n>=0)return n;throw S(`${t} must be a non-negative integer`)},yt=(t,e)=>{if(e<=4294967295)return e;throw S(`${t} must fit Uint32`)},co=(t,e,n)=>{let o=X(t,e);dt(t,o,n);let r=new Uint32Array(n);for(let i=0;i<n;i+=1)r[i]=yt(`${t}[${i}]`,K(`${t}[${i}]`,o[i]));return r},yo=(t,e,n)=>{let o=X(t,e);dt(t,o,n);let r=new Uint8Array(n);for(let i=0;i<n;i+=1){let a=le(`${t}[${i}]`,o[i]);if(a!==0&&a!==1)throw S(`${t}[${i}] must be 0 or 1`);r[i]=a}return r},ao=(t,e,n)=>{let o=X(t,e);dt(t,o,n);let r=new Int16Array(n);for(let i=0;i<n;i+=1){let a=le(`${t}[${i}]`,o[i]);if(a<-32768||a>32767)throw S(`${t}[${i}] must fit Int16`);r[i]=a}return r},pe=(t,e,n)=>{let o=X(t,e);return dt(t,o,n),o.map((r,i)=>{if(typeof r=="string")return r;throw S(`${t}[${i}] must be a string`)})},Zi=(t,e)=>{let n=X("entityStore.freeList",t),o=new Set,r=[];for(let i=0;i<n.length;i+=1){let a=K(`entityStore.freeList[${i}]`,n[i]);if(a>=e.length)throw S(`entityStore.freeList[${i}] is out of range`);if(e[a]===1)throw S(`entityStore.freeList[${i}] points to a live entity`);if(o.has(a))throw S(`entityStore.freeList contains duplicate entity index ${a}`);o.add(a),r.push(a)}for(let i=0;i<e.length;i+=1)if(e[i]===0&&!o.has(i))throw S(`entityStore.freeList is missing dead entity index ${i}`);return r},ta=t=>{let e=[];for(let n=0;n<t.length;n+=1)t[n]===0&&e.push(n);return e},ea=(t,e,n,o)=>{let r=new Set,i=0;for(let a=0;a<n.length;a+=1){if(n[a]!==1)continue;let s=e[a],c=o[a];if(s.length===0)throw S(`entityStore.ids[${a}] must be non-empty for a live entity`);if(c.length===0)throw S(`entityStore.groupTagByIndex[${a}] must be non-empty for a live entity`);if(r.has(s))throw S(`entityStore.ids contains duplicate live id '${s}'`);r.add(s),i+=1}if(t!==i)throw S(`entityStore.count ${t} does not match live entity count ${i}`)},na=(t,e)=>yt("entityStore.version",Math.max(t,e)+1),oa=(t,e)=>{let n=H("entityStore",t.entityStore),o=K("entityStore.capacity",n.capacity),r=K("entityStore.count",n.count);if(r>o)throw S("entityStore.count cannot exceed capacity");let i=pe("entityStore.ids",n.ids,o),a=yo("entityStore.alive",n.alive,o),s=pe("entityStore.groupTagByIndex",n.groupTagByIndex,o),c=m(n,"generation")&&n.generation!==void 0,d=c?co("entityStore.generation",n.generation,o):new Uint32Array(o),y=c?Zi(n.freeList,a):ta(a),u=na(e.version,yt("entityStore.version",K("entityStore.version",n.version)));return ea(r,i,a,s),{count:r,capacity:o,ids:i,alive:a,generation:d,groupTagByIndex:s,freeList:y,version:u}},ra=t=>t.kind,Mt=t=>Object.fromEntries(Object.entries(t.metadata.initialContext).map(([e,n])=>[e,ra(n)])),fe=(t,e,n)=>{let o=[...e].sort(),r=[...n].sort();if(o.length!==r.length)throw S(`${t} keys do not match current entity schema`);for(let i=0;i<o.length;i+=1)if(o[i]!==r[i])throw S(`${t} keys do not match current entity schema`)},ia=(t,e)=>{let n=H(`actors.${t.templateKey}.schema`,e.schema),o=pe(`actors.${t.templateKey}.schema.states`,n.states,t.metadata.publicStates.length);for(let a=0;a<o.length;a+=1)if(o[a]!==t.metadata.publicStates[a])throw S(`actors.${t.templateKey}.schema.states do not match current entity schema`);let r=H(`actors.${t.templateKey}.schema.columns`,n.columns),i=Mt(t);fe(`actors.${t.templateKey}.schema.columns`,Object.keys(r),Object.keys(i));for(let[a,s]of Object.entries(i))if(r[a]!==s)throw S(`actors.${t.templateKey}.schema.columns.${a} does not match current entity schema`)},aa=(t,e)=>e===R||e===ot||e===rt||e===it||e>=0&&e<t.metadata.publicStates.length,so=(t,e,n)=>{for(let o=0;o<n.length;o+=1)if(!aa(t,n[o]))throw S(`actors.${t.templateKey}.${e}[${o}] has unknown stateCode ${n[o]}`)},sa=(t,e,n)=>{for(let o=0;o<e.length;o+=1)if(!(e[o]!==1||!P(n[o])))throw S(`actors.${t.templateKey}.stateCode[${o}] cannot be a terminal stateCode for a present row`)},ca=(t,e,n)=>{if(typeof n!="number"||!Number.isFinite(n))throw S(`${t} must be a finite number`);if(e==="f32")return n;if(!Number.isInteger(n))throw S(`${t} must be an integer`);if(e==="i16"&&(n<-32768||n>32767))throw S(`${t} must fit Int16`);if(e==="i32"&&(n<-2147483648||n>2147483647))throw S(`${t} must fit Int32`);if(e==="u8"&&(n<0||n>255))throw S(`${t} must fit Uint8`);return n},da=(t,e)=>t==="f32"?Float32Array.from(e):t==="i16"?Int16Array.from(e):t==="i32"?Int32Array.from(e):Uint8Array.from(e),ya=(t,e,n,o)=>{let r=X(t,n);return dt(t,r,o),e==="string"?r.map((i,a)=>{if(typeof i=="string")return i;throw S(`${t}[${a}] must be a string`)}):da(e,r.map((i,a)=>ca(`${t}[${a}]`,e,i)))},ua=(t,e,n)=>{let o=0;for(let r=0;r<n.length;r+=1)if(n[r]===1){if(e.alive[r]!==1)throw S(`actors.${t.templateKey}.presence[${r}] points to a missing entity`);o+=1}return o},pa=(t,e,n)=>{let o=Math.max(t,e);if(n)for(let r=0;r<n.length;r+=1)n[r]>o&&(o=n[r]);return yt("actor.version",o+1)},la=(t,e,n)=>{let o=H(`actors.${t.templateKey}`,e);ia(t,o);let r=K(`actors.${t.templateKey}.capacity`,o.capacity);if(r>n.capacity)throw S(`actors.${t.templateKey}.capacity cannot exceed entityStore.capacity`);let i=K(`actors.${t.templateKey}.count`,o.count);if(i>r)throw S(`actors.${t.templateKey}.count cannot exceed capacity`);let a=yo(`actors.${t.templateKey}.presence`,o.presence,r),s=ua(t,n,a);if(i!==s)throw S(`actors.${t.templateKey}.count ${i} does not match present row count ${s}`);let c=ao(`actors.${t.templateKey}.stateCode`,o.stateCode,r),d=ao(`actors.${t.templateKey}.prevStateCode`,o.prevStateCode,r);so(t,"stateCode",c),so(t,"prevStateCode",d),sa(t,a,c);let y=m(o,"rowVersion")&&o.rowVersion!==void 0?co(`actors.${t.templateKey}.rowVersion`,o.rowVersion,r):void 0,u=pa(t.version,yt(`actors.${t.templateKey}.version`,K(`actors.${t.templateKey}.version`,o.version)),y),p=new Uint32Array(r);for(let f=0;f<r;f+=1)a[f]===1&&(p[f]=u);let w=H(`actors.${t.templateKey}.columns`,o.columns),E=Mt(t);fe(`actors.${t.templateKey}.columns`,Object.keys(w),Object.keys(E));let l=Object.create(null);for(let[f,U]of Object.entries(E))l[f]=ya(`actors.${t.templateKey}.columns.${f}`,U,w[f],r);return{capacity:r,count:i,version:u,presence:a,stateCode:c,prevStateCode:d,rowVersion:p,columns:l}},fa=t=>{let e=new Uint8Array(t.entityStore.capacity);for(let n of Object.values(t.actorStores))for(let o=0;o<n.capacity;o+=1)n.presence[o]===1&&(e[o]=1);for(let n=0;n<t.entityStore.capacity;n+=1)if(t.entityStore.alive[n]===1&&e[n]!==1)throw S(`entity '${t.entityStore.ids[n]}' has no actor rows`)},Se=(t,e)=>{let n=H("storage.entity",e);if(n.formatVersion!==1)throw S("formatVersion must be 1");let o=oa(n,t.entityStore),r=H("actors",n.actors),i=Object.keys(t.actorStores);fe("actors",Object.keys(r),i);let a=Object.create(null);for(let c of i)a[c]=la(t.actorStores[c],r[c],o);let s={entityStore:o,actorStores:a};return fa(s),s},Dt=(t,e)=>Se(t,e);var uo=(t,e)=>Array.from({length:e},(n,o)=>t[o]??""),Sa=t=>({count:t.count,capacity:t.capacity,ids:uo(t.ids,t.capacity),alive:Array.from(t.alive),generation:Array.from(t.generation),groupTagByIndex:uo(t.groupTagByIndex,t.capacity),freeList:t.freeList.slice(),version:t.version}),Ea=(t,e,n,o)=>Array.from({length:e},(i,a)=>n[a]!==1?o:t[a]??o),ma=t=>{let e=Mt(t);return{schema:{states:t.metadata.publicStates.slice(),columns:e},count:t.count,capacity:t.capacity,version:t.version,presence:Array.from(t.presence),stateCode:Array.from(t.stateCode),prevStateCode:Array.from(t.prevStateCode),rowVersion:Array.from(t.rowVersion),columns:Object.fromEntries(Object.entries(t.columns).map(([n,o])=>[n,Ea(o,t.capacity,t.presence,at(t.metadata.initialContext[n]))]))}},Ee=(t,e)=>{let o=e.options?.machines??Object.keys(t.actorStores),r=Object.create(null);for(let i of o)r[i]=t.actorStores[i].publicSlice;return{machines:r,snapshot:{formatVersion:1,entityStore:Sa(t.entityStore),actors:Object.fromEntries(Object.entries(t.actorStores).map(([i,a])=>[i,ma(a)]))}}};var wa=(t,e)=>{let n=e;for(let[o,r]of Object.entries(t)){let i={storage:"entity",version:r.version,count:r.count,capacity:r.capacity};n===e&&(n={...e}),n[o]=i}return n},ga=(t,e)=>{t.count=e.count,t.capacity=e.capacity,t.ids=e.ids,t.indexById=Object.create(null),t.alive=e.alive,t.generation=e.generation,t.groupTagByIndex=e.groupTagByIndex,t.entitiesByGroupTag=Object.create(null),t.groupTagPosition=new Int32Array(e.capacity),t.groupTagPosition.fill(-1),t.freeList=e.freeList,t.version=e.version},ha=(t,e)=>{t.capacity=e.capacity,t.count=e.count,t.version=e.version,t.presence=e.presence,t.stateCode=e.stateCode,t.prevStateCode=e.prevStateCode,t.rowVersion=e.rowVersion,t.pendingPrevStateCodeSync=[],t.pendingPrevStateCodeSyncMark=new Uint32Array(e.capacity),t.pendingPrevStateCodeSyncToken=1,Tt(t),ee(t),t.columns=e.columns,ct(t),q(t)},Ra=(t,e)=>{ga(t.entityStore,e.entityStore);for(let[n,o]of Object.entries(e.actorStores))ha(t.actorStores[n],o);se(t)},po=(t,e)=>{if(e.snapshot===void 0){let r=J(t,e.baseState);return{nextState:r,changed:r!==e.baseState}}let n=Se(t,e.snapshot),o=e.mode==="preview"?wa(n.actorStores,e.baseState):(Ra(t,n),J(t,e.baseState));return{nextState:o,changed:e.mode!=="preview"||o!==e.baseState}};var lo=Object.freeze([]),me=()=>({rows:new Map,lists:new Map}),ge=t=>new Ca("LITE_FSM_INVALID_STORAGE_RUNTIME",`[lite-fsm/entities/react] ${t}.`),we=(t,e)=>{let n=t.actorStores[e];if(n)return n;throw ge(`unknown entity actor template '${e}'`)},fo=t=>{let e=t?.groupTag;if(e!==void 0){if(typeof e=="string")return e;throw ge("EntityListOptions.groupTag must be a string")}},So=t=>{let e=Object.create(null);for(let n=0;n<t.alive.length;n+=1)t.alive[n]===1&&(e[t.ids[n]]=n);return e},xa=(t,e)=>`${t}\0${e}`,Aa=(t,e)=>e===void 0?t:`${t}\0${e}`,Ia=(t,e)=>{if(t.length!==e.length)return!1;for(let n=0;n<t.length;n+=1)if(t[n]!==e[n])return!1;return!0},va=(t,e)=>t[e],Ta=(t,e,n)=>{let o={};for(let r of Object.keys(t.metadata.initialContext))o[r]=va(e.columns[r],n);return o},ba=(t,e,n)=>{let o=t.metadata.publicStates[e.stateCode[n]];if(o!==void 0)return o;throw ge(`actor '${t.templateKey}' row for entity '${n}' has no public state snapshot`)},ka=(t,e,n,o)=>{if(we(t,n),o==null)return;let r=e.indexById[o];if(r===void 0)return;let i=e.actorStores[n];if(i.presence[r]!==1)return;let a=e.entityStore.generation[r],s=i.rowVersion[r],c=xa(n,o),d=e.cache.rows.get(c);if(d?.entity===r&&d.generation===a&&d.rowVersion===s)return d.snapshot;let y=we(t,n),u={entityId:o,groupTag:e.entityStore.groupTagByIndex[r],state:ba(y,i,r),context:Ta(y,i,r)};return e.cache.rows.set(c,{entity:r,generation:a,rowVersion:s,snapshot:u}),u},Eo=(t,e,n,o)=>{we(t,n);let r=e.actorStores[n];if(r.count===0)return lo;let i=[];for(let c=0;c<r.presence.length;c+=1)r.presence[c]===1&&(o!==void 0&&e.entityStore.groupTagByIndex[c]!==o||i.push(e.entityStore.ids[c]));if(i.length===0)return lo;let a=Aa(n,o),s=e.cache.lists.get(a);return s&&Ia(s.ids,i)?s.ids:(e.cache.lists.set(a,{ids:i}),i)},mo=t=>{let e=me(),n=new WeakMap,o=i=>{if(i!==null&&(typeof i=="object"||typeof i=="function")){let s=n.get(i);if(s)return s;let c=Dt(t,i),d={imported:c,indexById:So(c.entityStore),cache:me()};return n.set(i,d),d}let a=Dt(t,i);return{imported:a,indexById:So(a.entityStore),cache:me()}},r=i=>{if(i.mode==="commit")return{entityStore:t.entityStore,actorStores:t.actorStores,indexById:t.entityStore.indexById,cache:e};let a=o(i.snapshot);return{entityStore:a.imported.entityStore,actorStores:a.imported.actorStores,indexById:a.indexById,cache:a.cache}};return{readRow(i,a,s){return ka(t,r(s),i,a)},readCount(i,a,s){let c=fo(a);return Eo(t,r(s),i,c).length},readList(i,a,s){let c=fo(a);return Eo(t,r(s),i,c)}}};var Re="entity",ut=(t,e)=>new he("LITE_FSM_INVALID_STORAGE_CONFIG",`[lite-fsm/entities] machine '${t}' has invalid storage: "entity" config: ${e}.`),Pa=t=>new he("LITE_FSM_INVALID_STORAGE_CONFIG",`[lite-fsm/entities] machine '${t}' uses despawnOn, but despawnOn is only supported with storage: "entity".`),Ma=t=>new he("LITE_FSM_INVALID_STORAGE_CONFIG",`[lite-fsm/entities] machine '${t}' uses reactions, but reactions are only supported with storage: "entity".`),Da=t=>{for(let[e,n]of Object.entries(t)){if(n===null||typeof n!="object")continue;let o=n;if(!(!m(o,"despawnOn")||o.despawnOn===void 0)&&o.storage!==Re)throw Pa(e)}},Oa=t=>{for(let[e,n]of Object.entries(t)){if(n===null||typeof n!="object")continue;let o=n;if(!(!m(o,"reactions")||o.reactions===void 0)&&o.storage!==Re)throw Ma(e)}},_a=(t,e)=>{if(!m(e,"initialState")||e.initialState===void 0)throw ut(t,'missing required field "initialState"');if(e.initialState!=="__INIT")throw ut(t,'initialState must be "__INIT"');if(!m(e,"initialContext")||e.initialContext===void 0)throw ut(t,'missing required field "initialContext"');if(!m(e,"spawnSchema")||e.spawnSchema===void 0)throw ut(t,'missing required field "spawnSchema"');if(m(e,"groupTag")&&e.groupTag!==void 0)throw ut(t,"groupTag is defined by EntitySpawnSpec, not by actor template");Vt(t,"initialContext",e.initialContext),Vt(t,"spawnSchema",e.spawnSchema),ve(t,e.config)},wo=(t,e)=>{let n=Pn(t,e);return n.react=mo(n),n},go=Ba().create({kind:Re,routeMetaKeys:["entityId"],reduceScope:"bucket",validateTemplate({key:t,machine:e}){_a(t,e)},compileTemplate({key:t,machine:e}){return{data:zt(t,e)}},createRuntimeState({templates:t,manager:e}){let n=e.config;return n===null||typeof n!="object"||(Da(n),Oa(n)),wo(t,e)},createPublicInitialState({template:t,state:e}){return ae(D(e),t)},prepareAction({action:t,dispatch:e,state:n}){W(e,"entities.prepare.transaction",()=>{lt(t.type),on(e,D(n))})},reduceBucket(t){return io(D(t.state),t)},commit({state:t,dispatch:e}){W(e,"entities.commit.restorePublicSlices",()=>{e.nextState=J(D(t),e.nextState)})},effects:{resolveInvocations(t){return W(t.dispatch,"entities.effects.resolve",()=>Sn(D(t.state),t))},invoke(t){W(t.dispatch,"entities.effects.invoke",()=>{En(D(t.state),t.invocation,t)})}},reactions:{run(t){W(t.dispatch,"entities.reactions.total",()=>{Yn(D(t.state),t)})}},snapshot:{dehydrate(t){return Ee(D(t.state),t)},hydrate(t){return po(D(t.state),t)}}});var La="@lite-fsm/entities",Na=t=>{if(typeof t=="string"||Array.isArray(t)&&t.every(e=>typeof e=="string"))return t;throw new ho("LITE_FSM_INVALID_ROUTE_RESOLVER_RESULT","[lite-fsm/entities] routeMeta.entityId must be a string or an array of strings.")},Va=t=>$a().create({name:La,storage:[go],routeMeta:{entityId:Na},hooks:{beforeReduce(e){let{action:n}=e;lt(n.type),t&&rn(e,t)}},manager:{entities(e){let n=Mn(e).access;return()=>n}}}),ja=t=>{if(t!==void 0){if(t!==null&&typeof t=="object"&&"spawn"in t){let e=t.spawn;return He(e),e}throw new ho("LITE_FSM_INVALID_OPTIONS","[lite-fsm/entities] entitiesPlugin options must be { spawn } with a defineEntitySpawn(...) descriptor.")}};function Fa(t){let e=ja(t);return Va(e)}export{Yo as defineEntitySpawn,Ho as defineSpawnEvents,Fa as entitiesPlugin,To as f32,bo as i16,ko as i32,Mo as optional,Do as resource,Go as spawnEvent,Po as string,Bo as u8};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { LiteFsmError } from "@lite-fsm/core";
|
|
2
|
+
export declare const hasOwn: (value: object, key: PropertyKey) => boolean;
|
|
3
|
+
export declare const isPlainObject: (value: unknown) => value is Record<string, unknown>;
|
|
4
|
+
export declare const isDev: () => boolean;
|
|
5
|
+
export declare const runtimeError: (reason: string) => LiteFsmError;
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { LiteFsmError } from "@lite-fsm/core";
|
|
2
|
+
export declare const hasOwn: (value: object, key: PropertyKey) => boolean;
|
|
3
|
+
export declare const isPlainObject: (value: unknown) => value is Record<string, unknown>;
|
|
4
|
+
export declare const isDev: () => boolean;
|
|
5
|
+
export declare const runtimeError: (reason: string) => LiteFsmError;
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import type { ActorPublicState, AnyEvent, ManagerAction, MachineStore, ReadonlyManagerAction, StorageDependentField, StorageDependentTypeLambda } from "@lite-fsm/core";
|
|
2
|
+
import type { EntityContextSchema, EntitySchemaColumns, EntitySchemaResourceOwners, EntitySchemaValue, EntitySpawnPayload, EntitySpawnSchema } from "./schema";
|
|
3
|
+
import type { EntityIndex } from "./plugin";
|
|
4
|
+
import type { LiteFsmEntityLifecycleEvents } from "./runtime/lifecycle";
|
|
5
|
+
import type { EntityAccess, ReadonlyEntityColumn } from "./runtime/access";
|
|
6
|
+
export declare const entityStateMetadata: unique symbol;
|
|
7
|
+
type Prettify<Value> = {
|
|
8
|
+
[Key in keyof Value]: Value[Key];
|
|
9
|
+
} & {};
|
|
10
|
+
export type EntityMachineInput<ContextSchema extends EntityContextSchema = EntityContextSchema, SpawnSchema extends EntitySpawnSchema = EntitySpawnSchema, Config extends object = object, AppDeps = unknown> = {
|
|
11
|
+
readonly storage: "entity";
|
|
12
|
+
readonly config: Config;
|
|
13
|
+
readonly initialState: "__INIT";
|
|
14
|
+
readonly initialContext: ContextSchema;
|
|
15
|
+
readonly spawnSchema: SpawnSchema;
|
|
16
|
+
readonly despawnOn?: ActorPublicState<Config> | readonly ActorPublicState<Config>[];
|
|
17
|
+
readonly reactions?: EntityReactions<ContextSchema, AppDeps, Config>;
|
|
18
|
+
};
|
|
19
|
+
export type EntityMachineExtension<ContextSchema extends EntityContextSchema = EntityContextSchema, SpawnSchema extends EntitySpawnSchema = EntitySpawnSchema, Config extends object = object, AppDeps = unknown> = AppDeps extends unknown ? {
|
|
20
|
+
readonly storage: "entity";
|
|
21
|
+
readonly internalEvents: LiteFsmEntityLifecycleEvents;
|
|
22
|
+
readonly input: EntityMachineInput<ContextSchema, SpawnSchema, Config, AppDeps>;
|
|
23
|
+
readonly reducerContext: StorageDependentField<EntityReducerContextLambda<AppDeps>>;
|
|
24
|
+
readonly effectDeps: StorageDependentField<EntityEffectDepsLambda>;
|
|
25
|
+
readonly reactionDeps: StorageDependentField<EntityReactionDepsLambda<AppDeps>>;
|
|
26
|
+
readonly resultMetadata: <Input extends EntityMachineInput<ContextSchema, SpawnSchema, Config>>(input: Input) => {
|
|
27
|
+
readonly entityContextSchema: Input["initialContext"];
|
|
28
|
+
readonly entitySpawnSchema: Input["spawnSchema"];
|
|
29
|
+
};
|
|
30
|
+
readonly publicState: <Input extends EntityMachineInput<ContextSchema, SpawnSchema, Config>>(input: Input) => EntityMachinePublicState<{
|
|
31
|
+
readonly entityContextSchema: Input["initialContext"];
|
|
32
|
+
readonly entitySpawnSchema: Input["spawnSchema"];
|
|
33
|
+
}>;
|
|
34
|
+
} : never;
|
|
35
|
+
export type EntityMachineStateMetadata<ContextSchema extends EntityContextSchema, SpawnSchema extends EntitySpawnSchema> = {
|
|
36
|
+
readonly entityContextSchema: ContextSchema;
|
|
37
|
+
readonly entitySpawnSchema: SpawnSchema;
|
|
38
|
+
};
|
|
39
|
+
export type EntityMachinePublicState<Metadata> = {
|
|
40
|
+
readonly storage: "entity";
|
|
41
|
+
readonly version: number;
|
|
42
|
+
readonly count: number;
|
|
43
|
+
readonly capacity: number;
|
|
44
|
+
readonly [entityStateMetadata]?: Metadata;
|
|
45
|
+
};
|
|
46
|
+
type EntityReducerColumns<ContextSchema extends EntityContextSchema> = {
|
|
47
|
+
readonly [Field in keyof EntitySchemaColumns<ContextSchema>]: EntitySchemaColumns<ContextSchema>[Field] extends readonly string[] ? string[] : EntitySchemaColumns<ContextSchema>[Field];
|
|
48
|
+
};
|
|
49
|
+
type EntityEffectColumns<ContextSchema extends EntityContextSchema> = {
|
|
50
|
+
readonly [Field in keyof EntitySchemaValue<ContextSchema>]: ReadonlyEntityColumn<EntitySchemaValue<ContextSchema>[Field]>;
|
|
51
|
+
};
|
|
52
|
+
type AnyEntityMachineStore = Record<string, {
|
|
53
|
+
readonly storage: "entity";
|
|
54
|
+
readonly initialState: "__INIT";
|
|
55
|
+
readonly config: object;
|
|
56
|
+
readonly initialContext: EntityContextSchema;
|
|
57
|
+
readonly spawnSchema: EntitySpawnSchema;
|
|
58
|
+
}>;
|
|
59
|
+
type EntityReducerEntityAccess<AppDeps> = AppDeps extends {
|
|
60
|
+
readonly entities: () => EntityAccess<infer AppMachines extends MachineStore>;
|
|
61
|
+
} ? EntityAccess<AppMachines> : EntityAccess<AnyEntityMachineStore>;
|
|
62
|
+
export type EntityReducerStates<Config extends object> = {
|
|
63
|
+
readonly [State in ActorPublicState<Config>]: number;
|
|
64
|
+
};
|
|
65
|
+
export type EntityReducerSelf<ContextSchema extends EntityContextSchema, Config extends object = object> = Prettify<{
|
|
66
|
+
readonly indices: readonly EntityIndex[];
|
|
67
|
+
readonly states: EntityReducerStates<Config>;
|
|
68
|
+
readonly presence: Uint8Array;
|
|
69
|
+
readonly stateCode: Int16Array;
|
|
70
|
+
readonly prevStateCode: Int16Array;
|
|
71
|
+
readonly rowVersion: Uint32Array;
|
|
72
|
+
has(entity: EntityIndex): boolean;
|
|
73
|
+
entityId(entity: EntityIndex): string;
|
|
74
|
+
} & EntityReducerColumns<ContextSchema> & EntitySchemaResourceOwners<ContextSchema>>;
|
|
75
|
+
/**
|
|
76
|
+
* `self` в entity effects действует только в рамках текущего transition.
|
|
77
|
+
* Resource поля являются mutable owner objects текущего template; не сохраняй
|
|
78
|
+
* `self` или resource references для использования после async boundary.
|
|
79
|
+
*/
|
|
80
|
+
export type EntityEffectSelf<ContextSchema extends EntityContextSchema, Config extends object = object> = Prettify<{
|
|
81
|
+
readonly indices: readonly EntityIndex[];
|
|
82
|
+
readonly states: EntityReducerStates<Config>;
|
|
83
|
+
readonly presence: ReadonlyEntityColumn<number>;
|
|
84
|
+
readonly stateCode: ReadonlyEntityColumn<number>;
|
|
85
|
+
readonly prevStateCode: ReadonlyEntityColumn<number>;
|
|
86
|
+
readonly rowVersion: ReadonlyEntityColumn<number>;
|
|
87
|
+
has(entity: EntityIndex): boolean;
|
|
88
|
+
entityId(entity: EntityIndex): string;
|
|
89
|
+
} & EntityEffectColumns<ContextSchema> & EntitySchemaResourceOwners<ContextSchema>>;
|
|
90
|
+
type EntityPlainAction<Events extends AnyEvent> = Events & {
|
|
91
|
+
readonly meta?: never;
|
|
92
|
+
};
|
|
93
|
+
export type EntityEffectTransition<Events extends AnyEvent = AnyEvent> = {
|
|
94
|
+
entity(entityId: string | readonly string[], action: EntityPlainAction<Events>): ManagerAction<Events>;
|
|
95
|
+
actor(actorId: string | readonly string[], action: EntityPlainAction<Events>): ManagerAction<Events>;
|
|
96
|
+
group(groupId: string | readonly string[], action: EntityPlainAction<Events>): ManagerAction<Events>;
|
|
97
|
+
tag(groupTag: string | readonly string[], action: EntityPlainAction<Events>): ManagerAction<Events>;
|
|
98
|
+
unscoped(action: EntityPlainAction<Events>): ManagerAction<Events>;
|
|
99
|
+
despawn(entity: string | readonly string[] | readonly EntityIndex[]): void;
|
|
100
|
+
};
|
|
101
|
+
export type EntityEffectDeps<ContextSchema extends EntityContextSchema, Config extends object = object> = {
|
|
102
|
+
readonly self: EntityEffectSelf<ContextSchema, Config>;
|
|
103
|
+
readonly transition: EntityEffectTransition;
|
|
104
|
+
};
|
|
105
|
+
/**
|
|
106
|
+
* `self` в entity reactions имеет тот же transition-scope contract, что и
|
|
107
|
+
* effects: owner resources доступны как mutable objects только до async boundary.
|
|
108
|
+
*/
|
|
109
|
+
export type EntityReactionSelf<ContextSchema extends EntityContextSchema, Config extends object = object> = EntityEffectSelf<ContextSchema, Config>;
|
|
110
|
+
type EntityReactionRuntimeDeps<ContextSchema extends EntityContextSchema, Config extends object> = {
|
|
111
|
+
readonly action: ReadonlyManagerAction<AnyEvent>;
|
|
112
|
+
readonly self: EntityReactionSelf<ContextSchema, Config>;
|
|
113
|
+
};
|
|
114
|
+
type EntityReactionUserDeps<AppDeps> = AppDeps extends object ? Omit<AppDeps, "action" | "condition" | "self" | "transition"> : {};
|
|
115
|
+
export type EntityReactionDeps<ContextSchema extends EntityContextSchema, AppDeps = unknown, Config extends object = object> = EntityReactionUserDeps<AppDeps> & EntityReactionRuntimeDeps<ContextSchema, Config>;
|
|
116
|
+
export type EntityReaction<ContextSchema extends EntityContextSchema, AppDeps = unknown, Config extends object = object> = (deps: EntityReactionDeps<ContextSchema, AppDeps, Config>) => unknown;
|
|
117
|
+
export type EntityReactions<ContextSchema extends EntityContextSchema, AppDeps = unknown, Config extends object = object> = {
|
|
118
|
+
readonly [eventType: string]: EntityReaction<ContextSchema, AppDeps, Config> | undefined;
|
|
119
|
+
};
|
|
120
|
+
export type EntityReducerContext<ContextSchema extends EntityContextSchema, SpawnSchema extends EntitySpawnSchema, Config extends object = object, AppDeps = unknown> = {
|
|
121
|
+
readonly self: EntityReducerSelf<ContextSchema, Config>;
|
|
122
|
+
readonly entities: () => EntityReducerEntityAccess<AppDeps>;
|
|
123
|
+
payloadFor(entity: EntityIndex): EntitySpawnPayload<SpawnSchema>;
|
|
124
|
+
};
|
|
125
|
+
type EntityReducerContextForInput<Input, AppDeps> = Input extends {
|
|
126
|
+
readonly initialContext: infer ContextSchema extends EntityContextSchema;
|
|
127
|
+
readonly spawnSchema: infer SpawnSchema extends EntitySpawnSchema;
|
|
128
|
+
readonly config: infer Config extends object;
|
|
129
|
+
} ? EntityReducerContext<ContextSchema, SpawnSchema, Config, AppDeps> : never;
|
|
130
|
+
interface EntityReducerContextLambda<AppDeps> extends StorageDependentTypeLambda {
|
|
131
|
+
readonly type: this extends {
|
|
132
|
+
readonly input: infer Input;
|
|
133
|
+
} ? EntityReducerContextForInput<Input, AppDeps> : never;
|
|
134
|
+
}
|
|
135
|
+
type EntityEffectDepsForInput<Input> = Input extends {
|
|
136
|
+
readonly initialContext: infer ContextSchema extends EntityContextSchema;
|
|
137
|
+
readonly config: infer Config extends object;
|
|
138
|
+
} ? EntityEffectDeps<ContextSchema, Config> : never;
|
|
139
|
+
interface EntityEffectDepsLambda extends StorageDependentTypeLambda {
|
|
140
|
+
readonly type: this extends {
|
|
141
|
+
readonly input: infer Input;
|
|
142
|
+
} ? EntityEffectDepsForInput<Input> : never;
|
|
143
|
+
}
|
|
144
|
+
type EntityReactionDepsForInput<Input, AppDeps> = Input extends {
|
|
145
|
+
readonly initialContext: infer ContextSchema extends EntityContextSchema;
|
|
146
|
+
readonly config: infer Config extends object;
|
|
147
|
+
} ? EntityReactionDeps<ContextSchema, AppDeps, Config> : never;
|
|
148
|
+
interface EntityReactionDepsLambda<AppDeps> extends StorageDependentTypeLambda {
|
|
149
|
+
readonly type: this extends {
|
|
150
|
+
readonly input: infer Input;
|
|
151
|
+
} ? EntityReactionDepsForInput<Input, AppDeps> : never;
|
|
152
|
+
}
|
|
153
|
+
export {};
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import type { ActorPublicState, AnyEvent, ManagerAction, MachineStore, ReadonlyManagerAction, StorageDependentField, StorageDependentTypeLambda } from "@lite-fsm/core";
|
|
2
|
+
import type { EntityContextSchema, EntitySchemaColumns, EntitySchemaResourceOwners, EntitySchemaValue, EntitySpawnPayload, EntitySpawnSchema } from "./schema";
|
|
3
|
+
import type { EntityIndex } from "./plugin";
|
|
4
|
+
import type { LiteFsmEntityLifecycleEvents } from "./runtime/lifecycle";
|
|
5
|
+
import type { EntityAccess, ReadonlyEntityColumn } from "./runtime/access";
|
|
6
|
+
export declare const entityStateMetadata: unique symbol;
|
|
7
|
+
type Prettify<Value> = {
|
|
8
|
+
[Key in keyof Value]: Value[Key];
|
|
9
|
+
} & {};
|
|
10
|
+
export type EntityMachineInput<ContextSchema extends EntityContextSchema = EntityContextSchema, SpawnSchema extends EntitySpawnSchema = EntitySpawnSchema, Config extends object = object, AppDeps = unknown> = {
|
|
11
|
+
readonly storage: "entity";
|
|
12
|
+
readonly config: Config;
|
|
13
|
+
readonly initialState: "__INIT";
|
|
14
|
+
readonly initialContext: ContextSchema;
|
|
15
|
+
readonly spawnSchema: SpawnSchema;
|
|
16
|
+
readonly despawnOn?: ActorPublicState<Config> | readonly ActorPublicState<Config>[];
|
|
17
|
+
readonly reactions?: EntityReactions<ContextSchema, AppDeps, Config>;
|
|
18
|
+
};
|
|
19
|
+
export type EntityMachineExtension<ContextSchema extends EntityContextSchema = EntityContextSchema, SpawnSchema extends EntitySpawnSchema = EntitySpawnSchema, Config extends object = object, AppDeps = unknown> = AppDeps extends unknown ? {
|
|
20
|
+
readonly storage: "entity";
|
|
21
|
+
readonly internalEvents: LiteFsmEntityLifecycleEvents;
|
|
22
|
+
readonly input: EntityMachineInput<ContextSchema, SpawnSchema, Config, AppDeps>;
|
|
23
|
+
readonly reducerContext: StorageDependentField<EntityReducerContextLambda<AppDeps>>;
|
|
24
|
+
readonly effectDeps: StorageDependentField<EntityEffectDepsLambda>;
|
|
25
|
+
readonly reactionDeps: StorageDependentField<EntityReactionDepsLambda<AppDeps>>;
|
|
26
|
+
readonly resultMetadata: <Input extends EntityMachineInput<ContextSchema, SpawnSchema, Config>>(input: Input) => {
|
|
27
|
+
readonly entityContextSchema: Input["initialContext"];
|
|
28
|
+
readonly entitySpawnSchema: Input["spawnSchema"];
|
|
29
|
+
};
|
|
30
|
+
readonly publicState: <Input extends EntityMachineInput<ContextSchema, SpawnSchema, Config>>(input: Input) => EntityMachinePublicState<{
|
|
31
|
+
readonly entityContextSchema: Input["initialContext"];
|
|
32
|
+
readonly entitySpawnSchema: Input["spawnSchema"];
|
|
33
|
+
}>;
|
|
34
|
+
} : never;
|
|
35
|
+
export type EntityMachineStateMetadata<ContextSchema extends EntityContextSchema, SpawnSchema extends EntitySpawnSchema> = {
|
|
36
|
+
readonly entityContextSchema: ContextSchema;
|
|
37
|
+
readonly entitySpawnSchema: SpawnSchema;
|
|
38
|
+
};
|
|
39
|
+
export type EntityMachinePublicState<Metadata> = {
|
|
40
|
+
readonly storage: "entity";
|
|
41
|
+
readonly version: number;
|
|
42
|
+
readonly count: number;
|
|
43
|
+
readonly capacity: number;
|
|
44
|
+
readonly [entityStateMetadata]?: Metadata;
|
|
45
|
+
};
|
|
46
|
+
type EntityReducerColumns<ContextSchema extends EntityContextSchema> = {
|
|
47
|
+
readonly [Field in keyof EntitySchemaColumns<ContextSchema>]: EntitySchemaColumns<ContextSchema>[Field] extends readonly string[] ? string[] : EntitySchemaColumns<ContextSchema>[Field];
|
|
48
|
+
};
|
|
49
|
+
type EntityEffectColumns<ContextSchema extends EntityContextSchema> = {
|
|
50
|
+
readonly [Field in keyof EntitySchemaValue<ContextSchema>]: ReadonlyEntityColumn<EntitySchemaValue<ContextSchema>[Field]>;
|
|
51
|
+
};
|
|
52
|
+
type AnyEntityMachineStore = Record<string, {
|
|
53
|
+
readonly storage: "entity";
|
|
54
|
+
readonly initialState: "__INIT";
|
|
55
|
+
readonly config: object;
|
|
56
|
+
readonly initialContext: EntityContextSchema;
|
|
57
|
+
readonly spawnSchema: EntitySpawnSchema;
|
|
58
|
+
}>;
|
|
59
|
+
type EntityReducerEntityAccess<AppDeps> = AppDeps extends {
|
|
60
|
+
readonly entities: () => EntityAccess<infer AppMachines extends MachineStore>;
|
|
61
|
+
} ? EntityAccess<AppMachines> : EntityAccess<AnyEntityMachineStore>;
|
|
62
|
+
export type EntityReducerStates<Config extends object> = {
|
|
63
|
+
readonly [State in ActorPublicState<Config>]: number;
|
|
64
|
+
};
|
|
65
|
+
export type EntityReducerSelf<ContextSchema extends EntityContextSchema, Config extends object = object> = Prettify<{
|
|
66
|
+
readonly indices: readonly EntityIndex[];
|
|
67
|
+
readonly states: EntityReducerStates<Config>;
|
|
68
|
+
readonly presence: Uint8Array;
|
|
69
|
+
readonly stateCode: Int16Array;
|
|
70
|
+
readonly prevStateCode: Int16Array;
|
|
71
|
+
readonly rowVersion: Uint32Array;
|
|
72
|
+
has(entity: EntityIndex): boolean;
|
|
73
|
+
entityId(entity: EntityIndex): string;
|
|
74
|
+
} & EntityReducerColumns<ContextSchema> & EntitySchemaResourceOwners<ContextSchema>>;
|
|
75
|
+
/**
|
|
76
|
+
* `self` в entity effects действует только в рамках текущего transition.
|
|
77
|
+
* Resource поля являются mutable owner objects текущего template; не сохраняй
|
|
78
|
+
* `self` или resource references для использования после async boundary.
|
|
79
|
+
*/
|
|
80
|
+
export type EntityEffectSelf<ContextSchema extends EntityContextSchema, Config extends object = object> = Prettify<{
|
|
81
|
+
readonly indices: readonly EntityIndex[];
|
|
82
|
+
readonly states: EntityReducerStates<Config>;
|
|
83
|
+
readonly presence: ReadonlyEntityColumn<number>;
|
|
84
|
+
readonly stateCode: ReadonlyEntityColumn<number>;
|
|
85
|
+
readonly prevStateCode: ReadonlyEntityColumn<number>;
|
|
86
|
+
readonly rowVersion: ReadonlyEntityColumn<number>;
|
|
87
|
+
has(entity: EntityIndex): boolean;
|
|
88
|
+
entityId(entity: EntityIndex): string;
|
|
89
|
+
} & EntityEffectColumns<ContextSchema> & EntitySchemaResourceOwners<ContextSchema>>;
|
|
90
|
+
type EntityPlainAction<Events extends AnyEvent> = Events & {
|
|
91
|
+
readonly meta?: never;
|
|
92
|
+
};
|
|
93
|
+
export type EntityEffectTransition<Events extends AnyEvent = AnyEvent> = {
|
|
94
|
+
entity(entityId: string | readonly string[], action: EntityPlainAction<Events>): ManagerAction<Events>;
|
|
95
|
+
actor(actorId: string | readonly string[], action: EntityPlainAction<Events>): ManagerAction<Events>;
|
|
96
|
+
group(groupId: string | readonly string[], action: EntityPlainAction<Events>): ManagerAction<Events>;
|
|
97
|
+
tag(groupTag: string | readonly string[], action: EntityPlainAction<Events>): ManagerAction<Events>;
|
|
98
|
+
unscoped(action: EntityPlainAction<Events>): ManagerAction<Events>;
|
|
99
|
+
despawn(entity: string | readonly string[] | readonly EntityIndex[]): void;
|
|
100
|
+
};
|
|
101
|
+
export type EntityEffectDeps<ContextSchema extends EntityContextSchema, Config extends object = object> = {
|
|
102
|
+
readonly self: EntityEffectSelf<ContextSchema, Config>;
|
|
103
|
+
readonly transition: EntityEffectTransition;
|
|
104
|
+
};
|
|
105
|
+
/**
|
|
106
|
+
* `self` в entity reactions имеет тот же transition-scope contract, что и
|
|
107
|
+
* effects: owner resources доступны как mutable objects только до async boundary.
|
|
108
|
+
*/
|
|
109
|
+
export type EntityReactionSelf<ContextSchema extends EntityContextSchema, Config extends object = object> = EntityEffectSelf<ContextSchema, Config>;
|
|
110
|
+
type EntityReactionRuntimeDeps<ContextSchema extends EntityContextSchema, Config extends object> = {
|
|
111
|
+
readonly action: ReadonlyManagerAction<AnyEvent>;
|
|
112
|
+
readonly self: EntityReactionSelf<ContextSchema, Config>;
|
|
113
|
+
};
|
|
114
|
+
type EntityReactionUserDeps<AppDeps> = AppDeps extends object ? Omit<AppDeps, "action" | "condition" | "self" | "transition"> : {};
|
|
115
|
+
export type EntityReactionDeps<ContextSchema extends EntityContextSchema, AppDeps = unknown, Config extends object = object> = EntityReactionUserDeps<AppDeps> & EntityReactionRuntimeDeps<ContextSchema, Config>;
|
|
116
|
+
export type EntityReaction<ContextSchema extends EntityContextSchema, AppDeps = unknown, Config extends object = object> = (deps: EntityReactionDeps<ContextSchema, AppDeps, Config>) => unknown;
|
|
117
|
+
export type EntityReactions<ContextSchema extends EntityContextSchema, AppDeps = unknown, Config extends object = object> = {
|
|
118
|
+
readonly [eventType: string]: EntityReaction<ContextSchema, AppDeps, Config> | undefined;
|
|
119
|
+
};
|
|
120
|
+
export type EntityReducerContext<ContextSchema extends EntityContextSchema, SpawnSchema extends EntitySpawnSchema, Config extends object = object, AppDeps = unknown> = {
|
|
121
|
+
readonly self: EntityReducerSelf<ContextSchema, Config>;
|
|
122
|
+
readonly entities: () => EntityReducerEntityAccess<AppDeps>;
|
|
123
|
+
payloadFor(entity: EntityIndex): EntitySpawnPayload<SpawnSchema>;
|
|
124
|
+
};
|
|
125
|
+
type EntityReducerContextForInput<Input, AppDeps> = Input extends {
|
|
126
|
+
readonly initialContext: infer ContextSchema extends EntityContextSchema;
|
|
127
|
+
readonly spawnSchema: infer SpawnSchema extends EntitySpawnSchema;
|
|
128
|
+
readonly config: infer Config extends object;
|
|
129
|
+
} ? EntityReducerContext<ContextSchema, SpawnSchema, Config, AppDeps> : never;
|
|
130
|
+
interface EntityReducerContextLambda<AppDeps> extends StorageDependentTypeLambda {
|
|
131
|
+
readonly type: this extends {
|
|
132
|
+
readonly input: infer Input;
|
|
133
|
+
} ? EntityReducerContextForInput<Input, AppDeps> : never;
|
|
134
|
+
}
|
|
135
|
+
type EntityEffectDepsForInput<Input> = Input extends {
|
|
136
|
+
readonly initialContext: infer ContextSchema extends EntityContextSchema;
|
|
137
|
+
readonly config: infer Config extends object;
|
|
138
|
+
} ? EntityEffectDeps<ContextSchema, Config> : never;
|
|
139
|
+
interface EntityEffectDepsLambda extends StorageDependentTypeLambda {
|
|
140
|
+
readonly type: this extends {
|
|
141
|
+
readonly input: infer Input;
|
|
142
|
+
} ? EntityEffectDepsForInput<Input> : never;
|
|
143
|
+
}
|
|
144
|
+
type EntityReactionDepsForInput<Input, AppDeps> = Input extends {
|
|
145
|
+
readonly initialContext: infer ContextSchema extends EntityContextSchema;
|
|
146
|
+
readonly config: infer Config extends object;
|
|
147
|
+
} ? EntityReactionDeps<ContextSchema, AppDeps, Config> : never;
|
|
148
|
+
interface EntityReactionDepsLambda<AppDeps> extends StorageDependentTypeLambda {
|
|
149
|
+
readonly type: this extends {
|
|
150
|
+
readonly input: infer Input;
|
|
151
|
+
} ? EntityReactionDepsForInput<Input, AppDeps> : never;
|
|
152
|
+
}
|
|
153
|
+
export {};
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { AnyEvent, LiteFsmPlugin, MachineStore, ManagerExtensionFactory, ManagerExtensionType, ManagerExtensionTypeLambda, ManagerRuntimeContext } from "@lite-fsm/core";
|
|
2
|
+
import type { EntityAccess } from "./runtime/access";
|
|
3
|
+
import { type EntityStorageDefinition, type EntityStorageRouteMeta } from "./runtime/storage";
|
|
4
|
+
import { type AnyEntitySpawnDescriptor, type EntitySpawnPluginEvents } from "./spawn";
|
|
5
|
+
declare const entityIndexBrand: unique symbol;
|
|
6
|
+
export type EntityId = string;
|
|
7
|
+
export type EntityIndex = number & {
|
|
8
|
+
readonly [entityIndexBrand]: "EntityIndex";
|
|
9
|
+
};
|
|
10
|
+
type EntityPluginOptions<Spawn extends AnyEntitySpawnDescriptor> = {
|
|
11
|
+
readonly spawn: Spawn;
|
|
12
|
+
};
|
|
13
|
+
interface EntityAccessManagerExtension extends ManagerExtensionTypeLambda {
|
|
14
|
+
readonly type: this extends {
|
|
15
|
+
readonly context: ManagerRuntimeContext<infer _Events, infer AppMachines extends MachineStore>;
|
|
16
|
+
} ? () => EntityAccess<AppMachines> : never;
|
|
17
|
+
}
|
|
18
|
+
type EntityManagerDefinition = {
|
|
19
|
+
readonly entities: ManagerExtensionFactory & ManagerExtensionType<EntityAccessManagerExtension>;
|
|
20
|
+
};
|
|
21
|
+
type EntityRouteMetaResolvers = {
|
|
22
|
+
readonly entityId: (value: EntityStorageRouteMeta["entityId"]) => EntityStorageRouteMeta["entityId"];
|
|
23
|
+
};
|
|
24
|
+
export type EntitiesPlugin<AppDeps = unknown, PluginEvents extends AnyEvent = never> = LiteFsmPlugin<"@lite-fsm/entities", PluginEvents, {
|
|
25
|
+
readonly name: "@lite-fsm/entities";
|
|
26
|
+
readonly storage: readonly [EntityStorageDefinition<AppDeps>];
|
|
27
|
+
readonly routeMeta?: EntityRouteMetaResolvers;
|
|
28
|
+
readonly manager: EntityManagerDefinition;
|
|
29
|
+
}>;
|
|
30
|
+
export declare function entitiesPlugin(): EntitiesPlugin<unknown, never>;
|
|
31
|
+
export declare function entitiesPlugin<const Spawn extends AnyEntitySpawnDescriptor>(options: EntityPluginOptions<Spawn>): EntitiesPlugin<unknown, EntitySpawnPluginEvents<Spawn>>;
|
|
32
|
+
export {};
|
package/dist/plugin.d.ts
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { AnyEvent, LiteFsmPlugin, MachineStore, ManagerExtensionFactory, ManagerExtensionType, ManagerExtensionTypeLambda, ManagerRuntimeContext } from "@lite-fsm/core";
|
|
2
|
+
import type { EntityAccess } from "./runtime/access";
|
|
3
|
+
import { type EntityStorageDefinition, type EntityStorageRouteMeta } from "./runtime/storage";
|
|
4
|
+
import { type AnyEntitySpawnDescriptor, type EntitySpawnPluginEvents } from "./spawn";
|
|
5
|
+
declare const entityIndexBrand: unique symbol;
|
|
6
|
+
export type EntityId = string;
|
|
7
|
+
export type EntityIndex = number & {
|
|
8
|
+
readonly [entityIndexBrand]: "EntityIndex";
|
|
9
|
+
};
|
|
10
|
+
type EntityPluginOptions<Spawn extends AnyEntitySpawnDescriptor> = {
|
|
11
|
+
readonly spawn: Spawn;
|
|
12
|
+
};
|
|
13
|
+
interface EntityAccessManagerExtension extends ManagerExtensionTypeLambda {
|
|
14
|
+
readonly type: this extends {
|
|
15
|
+
readonly context: ManagerRuntimeContext<infer _Events, infer AppMachines extends MachineStore>;
|
|
16
|
+
} ? () => EntityAccess<AppMachines> : never;
|
|
17
|
+
}
|
|
18
|
+
type EntityManagerDefinition = {
|
|
19
|
+
readonly entities: ManagerExtensionFactory & ManagerExtensionType<EntityAccessManagerExtension>;
|
|
20
|
+
};
|
|
21
|
+
type EntityRouteMetaResolvers = {
|
|
22
|
+
readonly entityId: (value: EntityStorageRouteMeta["entityId"]) => EntityStorageRouteMeta["entityId"];
|
|
23
|
+
};
|
|
24
|
+
export type EntitiesPlugin<AppDeps = unknown, PluginEvents extends AnyEvent = never> = LiteFsmPlugin<"@lite-fsm/entities", PluginEvents, {
|
|
25
|
+
readonly name: "@lite-fsm/entities";
|
|
26
|
+
readonly storage: readonly [EntityStorageDefinition<AppDeps>];
|
|
27
|
+
readonly routeMeta?: EntityRouteMetaResolvers;
|
|
28
|
+
readonly manager: EntityManagerDefinition;
|
|
29
|
+
}>;
|
|
30
|
+
export declare function entitiesPlugin(): EntitiesPlugin<unknown, never>;
|
|
31
|
+
export declare function entitiesPlugin<const Spawn extends AnyEntitySpawnDescriptor>(options: EntityPluginOptions<Spawn>): EntitiesPlugin<unknown, EntitySpawnPluginEvents<Spawn>>;
|
|
32
|
+
export {};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { MachineStore } from "@lite-fsm/core";
|
|
2
|
+
import type { EntityId } from "../plugin";
|
|
3
|
+
import type { EntityActorKey, EntityContextFor, EntityStateFor } from "../runtime/access";
|
|
4
|
+
import type { EntityListOptions, EntityRowSnapshot } from "../runtime/react";
|
|
5
|
+
export type { EntityListOptions, EntityRowSnapshot, TypedUseEntityCountHook, TypedUseEntityListHook, TypedUseEntitySnapshotHook, } from "../runtime/react";
|
|
6
|
+
export declare function useEntitySnapshot<AppMachines extends MachineStore = MachineStore, Key extends EntityActorKey<AppMachines> = EntityActorKey<AppMachines>>(templateKey: Key, entityId: EntityId | null | undefined): EntityRowSnapshot<EntityContextFor<AppMachines, Key>, EntityStateFor<AppMachines, Key>> | undefined;
|
|
7
|
+
export declare function useEntitySnapshot(templateKey: string, entityId: EntityId | null | undefined): EntityRowSnapshot<Record<string, unknown>, string> | undefined;
|
|
8
|
+
export declare function useEntityCount<AppMachines extends MachineStore = MachineStore, Key extends EntityActorKey<AppMachines> = EntityActorKey<AppMachines>>(templateKey: Key, options?: EntityListOptions): number;
|
|
9
|
+
export declare function useEntityCount(templateKey: string, options?: EntityListOptions): number;
|
|
10
|
+
export declare function useEntityList<AppMachines extends MachineStore = MachineStore, Key extends EntityActorKey<AppMachines> = EntityActorKey<AppMachines>>(templateKey: Key, options?: EntityListOptions): readonly EntityId[];
|
|
11
|
+
export declare function useEntityList(templateKey: string, options?: EntityListOptions): readonly EntityId[];
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { MachineStore } from "@lite-fsm/core";
|
|
2
|
+
import type { EntityId } from "../plugin";
|
|
3
|
+
import type { EntityActorKey, EntityContextFor, EntityStateFor } from "../runtime/access";
|
|
4
|
+
import type { EntityListOptions, EntityRowSnapshot } from "../runtime/react";
|
|
5
|
+
export type { EntityListOptions, EntityRowSnapshot, TypedUseEntityCountHook, TypedUseEntityListHook, TypedUseEntitySnapshotHook, } from "../runtime/react";
|
|
6
|
+
export declare function useEntitySnapshot<AppMachines extends MachineStore = MachineStore, Key extends EntityActorKey<AppMachines> = EntityActorKey<AppMachines>>(templateKey: Key, entityId: EntityId | null | undefined): EntityRowSnapshot<EntityContextFor<AppMachines, Key>, EntityStateFor<AppMachines, Key>> | undefined;
|
|
7
|
+
export declare function useEntitySnapshot(templateKey: string, entityId: EntityId | null | undefined): EntityRowSnapshot<Record<string, unknown>, string> | undefined;
|
|
8
|
+
export declare function useEntityCount<AppMachines extends MachineStore = MachineStore, Key extends EntityActorKey<AppMachines> = EntityActorKey<AppMachines>>(templateKey: Key, options?: EntityListOptions): number;
|
|
9
|
+
export declare function useEntityCount(templateKey: string, options?: EntityListOptions): number;
|
|
10
|
+
export declare function useEntityList<AppMachines extends MachineStore = MachineStore, Key extends EntityActorKey<AppMachines> = EntityActorKey<AppMachines>>(templateKey: Key, options?: EntityListOptions): readonly EntityId[];
|
|
11
|
+
export declare function useEntityList(templateKey: string, options?: EntityListOptions): readonly EntityId[];
|
package/dist/react.cjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";"use client";var v=Object.create;var y=Object.defineProperty;var f=Object.getOwnPropertyDescriptor;var g=Object.getOwnPropertyNames;var h=Object.getPrototypeOf,C=Object.prototype.hasOwnProperty;var R=(n,t)=>{for(var r in t)y(n,r,{get:t[r],enumerable:!0})},E=(n,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let e of g(t))!C.call(n,e)&&e!==r&&y(n,e,{get:()=>t[e],enumerable:!(o=f(t,e))||o.enumerable});return n};var A=(n,t,r)=>(r=n!=null?v(h(n)):{},E(t||!n||!n.__esModule?y(r,"default",{value:n,enumerable:!0}):r,n)),M=n=>E(y({},"__esModule",{value:!0}),n);var O={};R(O,{useEntityCount:()=>I,useEntityList:()=>B,useEntitySnapshot:()=>k});module.exports=M(O);var i=A(require("react"),1),s=require("@lite-fsm/react");var P=require("@lite-fsm/core");var x=new WeakMap;var w=n=>{let t=x.get(n);if(!t)throw new Error("[lite-fsm/entities] entity runtime state is not initialized for this manager.");return t};var d="entity",b={mode:"commit"},T=()=>()=>{},p=(n,t)=>n?{mode:"preview",snapshot:t}:b,S=(n,t,r,o)=>n?{mode:"preview",snapshot:t}:p(r,o),l=n=>{let t=n.entities;if(!t)throw new Error("[lite-fsm/entities/react] hooks require a manager configured with entitiesPlugin().");let r=w(t());if(r.react)return r.react;throw new Error("[lite-fsm/entities/react] entity runtime does not expose React subscription/preview capability.")},m=n=>t=>n.onTransition(()=>t());function k(n,t){let r=(0,s.useManager)(),o=l(r),e=(0,s.useStorageHydrationPreview)(d),a=i.default.useMemo(()=>t==null?T:m(r),[t,r]),c=i.default.useCallback(()=>o.readRow(n,t,p(e.hasPreview,e.preview)),[t,e.hasPreview,e.preview,o,n]),u=i.default.useCallback(()=>o.readRow(n,t,S(e.hasServerPreview,e.serverPreview,e.hasPreview,e.preview)),[t,e.hasPreview,e.hasServerPreview,e.preview,e.serverPreview,o,n]);return i.default.useSyncExternalStore(a,c,u)}function I(n,t){let r=(0,s.useManager)(),o=l(r),e=(0,s.useStorageHydrationPreview)(d),a=i.default.useMemo(()=>m(r),[r]),c=i.default.useCallback(()=>o.readCount(n,t,p(e.hasPreview,e.preview)),[t,e.hasPreview,e.preview,o,n]),u=i.default.useCallback(()=>o.readCount(n,t,S(e.hasServerPreview,e.serverPreview,e.hasPreview,e.preview)),[t,e.hasPreview,e.hasServerPreview,e.preview,e.serverPreview,o,n]);return i.default.useSyncExternalStore(a,c,u)}function B(n,t){let r=(0,s.useManager)(),o=l(r),e=(0,s.useStorageHydrationPreview)(d),a=i.default.useMemo(()=>m(r),[r]),c=i.default.useCallback(()=>o.readList(n,t,p(e.hasPreview,e.preview)),[t,e.hasPreview,e.preview,o,n]),u=i.default.useCallback(()=>o.readList(n,t,S(e.hasServerPreview,e.serverPreview,e.hasPreview,e.preview)),[t,e.hasPreview,e.hasServerPreview,e.preview,e.serverPreview,o,n]);return i.default.useSyncExternalStore(a,c,u)}0&&(module.exports={useEntityCount,useEntityList,useEntitySnapshot});
|
package/dist/react.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use client";import i from"react";import{useManager as y,useStorageHydrationPreview as p}from"@lite-fsm/react";import{LiteFsmError as h}from"@lite-fsm/core";var w=new WeakMap;var E=n=>{let t=w.get(n);if(!t)throw new Error("[lite-fsm/entities] entity runtime state is not initialized for this manager.");return t};var d="entity",v={mode:"commit"},f=()=>()=>{},u=(n,t)=>n?{mode:"preview",snapshot:t}:v,S=(n,t,r,o)=>n?{mode:"preview",snapshot:t}:u(r,o),l=n=>{let t=n.entities;if(!t)throw new Error("[lite-fsm/entities/react] hooks require a manager configured with entitiesPlugin().");let r=E(t());if(r.react)return r.react;throw new Error("[lite-fsm/entities/react] entity runtime does not expose React subscription/preview capability.")},m=n=>t=>n.onTransition(()=>t());function P(n,t){let r=y(),o=l(r),e=p(d),s=i.useMemo(()=>t==null?f:m(r),[t,r]),a=i.useCallback(()=>o.readRow(n,t,u(e.hasPreview,e.preview)),[t,e.hasPreview,e.preview,o,n]),c=i.useCallback(()=>o.readRow(n,t,S(e.hasServerPreview,e.serverPreview,e.hasPreview,e.preview)),[t,e.hasPreview,e.hasServerPreview,e.preview,e.serverPreview,o,n]);return i.useSyncExternalStore(s,a,c)}function x(n,t){let r=y(),o=l(r),e=p(d),s=i.useMemo(()=>m(r),[r]),a=i.useCallback(()=>o.readCount(n,t,u(e.hasPreview,e.preview)),[t,e.hasPreview,e.preview,o,n]),c=i.useCallback(()=>o.readCount(n,t,S(e.hasServerPreview,e.serverPreview,e.hasPreview,e.preview)),[t,e.hasPreview,e.hasServerPreview,e.preview,e.serverPreview,o,n]);return i.useSyncExternalStore(s,a,c)}function b(n,t){let r=y(),o=l(r),e=p(d),s=i.useMemo(()=>m(r),[r]),a=i.useCallback(()=>o.readList(n,t,u(e.hasPreview,e.preview)),[t,e.hasPreview,e.preview,o,n]),c=i.useCallback(()=>o.readList(n,t,S(e.hasServerPreview,e.serverPreview,e.hasPreview,e.preview)),[t,e.hasPreview,e.hasServerPreview,e.preview,e.serverPreview,o,n]);return i.useSyncExternalStore(s,a,c)}export{x as useEntityCount,b as useEntityList,P as useEntitySnapshot};
|