aiecsjs 0.2.1 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/CHANGELOG.md +90 -2
  2. package/README.md +8 -3
  3. package/README_ZHTW.md +8 -3
  4. package/STABILITY.md +10 -4
  5. package/STABILITY_ZHTW.md +10 -3
  6. package/api.json +568 -100
  7. package/dist/chunk-37HMYMJG.cjs +2 -0
  8. package/dist/chunk-37HMYMJG.cjs.map +1 -0
  9. package/dist/chunk-4RPFOVQC.cjs +2 -0
  10. package/dist/chunk-4RPFOVQC.cjs.map +1 -0
  11. package/dist/chunk-AGHSWLNQ.cjs +2 -0
  12. package/dist/chunk-AGHSWLNQ.cjs.map +1 -0
  13. package/dist/chunk-FDXCXNZK.js +2 -0
  14. package/dist/chunk-FDXCXNZK.js.map +1 -0
  15. package/dist/chunk-L5CMKMIP.js +2 -0
  16. package/dist/chunk-L5CMKMIP.js.map +1 -0
  17. package/dist/chunk-QOKIEF7C.js +2 -0
  18. package/dist/chunk-QOKIEF7C.js.map +1 -0
  19. package/dist/commands.cjs +1 -1
  20. package/dist/commands.cjs.map +1 -1
  21. package/dist/commands.js +1 -1
  22. package/dist/commands.js.map +1 -1
  23. package/dist/index.cjs +1 -1
  24. package/dist/index.cjs.map +1 -1
  25. package/dist/index.d.cts +87 -4
  26. package/dist/index.d.ts +87 -4
  27. package/dist/index.js +1 -1
  28. package/dist/index.js.map +1 -1
  29. package/dist/observers.cjs +1 -1
  30. package/dist/observers.cjs.map +1 -1
  31. package/dist/observers.d.cts +16 -3
  32. package/dist/observers.d.ts +16 -3
  33. package/dist/observers.js +1 -1
  34. package/dist/observers.js.map +1 -1
  35. package/dist/relations.cjs +1 -1
  36. package/dist/relations.cjs.map +1 -1
  37. package/dist/relations.js +1 -1
  38. package/dist/relations.js.map +1 -1
  39. package/dist/serialize.cjs +1 -1
  40. package/dist/serialize.cjs.map +1 -1
  41. package/dist/serialize.d.cts +7 -0
  42. package/dist/serialize.d.ts +7 -0
  43. package/dist/serialize.js +1 -1
  44. package/dist/serialize.js.map +1 -1
  45. package/dist/worker.cjs +1 -1
  46. package/dist/worker.cjs.map +1 -1
  47. package/dist/worker.js +1 -1
  48. package/dist/worker.js.map +1 -1
  49. package/llms-full.txt +108 -9
  50. package/package.json +6 -2
package/dist/index.d.cts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { o as WorldOptions, W as World, E as EntityId, c as ComponentLike, b as ComponentInit, k as SoASchema, h as SoAComponent, A as AoSComponent, T as TagComponent, f as QueryDescriptor, Q as Query, a as Archetype, l as System } from './types-BGEeHad-.cjs';
2
2
  export { d as ComponentView, g as SoAColumns, i as SoAFieldDecl, j as SoAFieldType, n as Types } from './types-BGEeHad-.cjs';
3
3
 
4
- declare const VERSION = "0.2.1";
4
+ declare const VERSION = "0.3.1";
5
5
 
6
6
  declare function createWorld(options?: WorldOptions): World;
7
7
  declare function destroyWorld(world: World): void;
@@ -13,9 +13,28 @@ declare function isWorld(x: unknown): x is World;
13
13
  declare function createEntity(world: World): EntityId;
14
14
  declare function destroyEntity(world: World, eid: EntityId): void;
15
15
  declare function entityExists(world: World, eid: EntityId): boolean;
16
+ /**
17
+ * Extract the index portion of a packed entity ID.
18
+ *
19
+ * Uses the default 24-bit index layout. If you created the world with a
20
+ * non-default `indexBits`, use `EntityRef` + `deref` instead.
21
+ */
16
22
  declare function getEntityIndex(eid: EntityId): number;
17
- declare function getEntityGeneration(_eid: EntityId): number;
18
- declare function packEntity(index: number, _generation: number): EntityId;
23
+ /**
24
+ * Extract the generation portion of a packed entity ID.
25
+ *
26
+ * Uses the default 8-bit generation layout. If you created the world with a
27
+ * non-default `generationBits`, use `EntityRef` + `deref` instead.
28
+ */
29
+ declare function getEntityGeneration(eid: EntityId): number;
30
+ /**
31
+ * Pack an index and generation into an EntityId using the default 24/8 bit layout.
32
+ *
33
+ * Uses the default `indexBits=24, generationBits=8`. If you created the world
34
+ * with non-default bit sizes, this will produce values with incorrect layout.
35
+ * Use `EntityRef` and `deref` for portable cross-world identity matching.
36
+ */
37
+ declare function packEntity(index: number, generation: number): EntityId;
19
38
  declare function isEntity(world: World, x: unknown): x is EntityId;
20
39
 
21
40
  declare function defineComponent<S extends SoASchema>(schema: S): SoAComponent<S>;
@@ -37,6 +56,70 @@ declare function forEachEntity(world: World, query: Query, fn: (eid: EntityId, .
37
56
 
38
57
  declare function pipe<W extends World = World, Ctx = unknown>(...systems: System<W, Ctx>[]): System<W, Ctx>;
39
58
 
59
+ /**
60
+ * ABA-safe entity reference.
61
+ *
62
+ * Holds the packed EntityId and the id of the world that issued it.
63
+ * Use `deref(world, ref)` to validate and retrieve the live entity id.
64
+ *
65
+ * The phantom type `T` allows callers to distinguish reference kinds at the
66
+ * type system level — e.g. `EntityRef<'bullet'>` vs `EntityRef<'player'>` —
67
+ * without any runtime overhead.
68
+ *
69
+ * @example
70
+ * const ref = refOf<'bullet'>(world, e)
71
+ * // later, in a system:
72
+ * const live = deref(world, ref)
73
+ * if (live !== null) {
74
+ * // entity is still alive with the same generation
75
+ * }
76
+ */
77
+ interface EntityRef<T = unknown> {
78
+ readonly id: EntityId;
79
+ readonly worldId: number;
80
+ readonly __phantom?: T;
81
+ }
82
+ /**
83
+ * Thrown by `refOf` when the entity is not alive.
84
+ * `deref` and `aliveRef` never throw — they return null/false.
85
+ */
86
+ declare class EntityNotAliveError extends Error {
87
+ readonly eid: number;
88
+ constructor(eid: number);
89
+ }
90
+ /**
91
+ * Create an ABA-safe reference to a live entity.
92
+ *
93
+ * @throws {EntityNotAliveError} if the entity is not alive (dead, never created, or eid === 0).
94
+ *
95
+ * The returned object is frozen. `id` is the packed EntityId; `worldId` is
96
+ * the world's numeric id used by `deref` to reject cross-world lookups.
97
+ *
98
+ * The function may be called on the hot path — each call returns a new object
99
+ * but performs no allocation beyond that.
100
+ */
101
+ declare function refOf<T = unknown>(world: World, entity: EntityId): EntityRef<T>;
102
+ /**
103
+ * Resolve a ref to its live EntityId, or return null if stale.
104
+ *
105
+ * Returns null when any of the following hold:
106
+ * 1. `ref.worldId !== state.id` — cross-world ref
107
+ * 2. `getEntityIndex(ref.id) >= state.capacity` — index out-of-bounds
108
+ * 3. `getEntityIndex(ref.id) === 0` — sentinel slot
109
+ * 4. entity is not in any archetype's entityRow (slot released)
110
+ * 5. generation mismatch → ABA: old ref points at recycled slot
111
+ *
112
+ * Never throws.
113
+ */
114
+ declare function deref<T = unknown>(world: World, ref: EntityRef<T>): EntityId | null;
115
+ /**
116
+ * Boolean guard form of `deref`. Equivalent to `deref(world, ref) !== null`.
117
+ * Use in guard clauses when you do not need the resolved EntityId.
118
+ *
119
+ * Never throws.
120
+ */
121
+ declare function aliveRef<T = unknown>(world: World, ref: EntityRef<T>): boolean;
122
+
40
123
  declare const IS_SAB_SUPPORTED: boolean;
41
124
 
42
- export { AoSComponent, Archetype, ComponentInit, ComponentLike, EntityId, IS_SAB_SUPPORTED, Query, QueryDescriptor, SoAComponent, SoASchema, System, TagComponent, VERSION, World, WorldOptions, addComponent, createEntity, createWorld, defineComponent, defineObjectComponent, defineQuery, defineTag, destroyEntity, destroyWorld, destroyWorld as disposeWorld, enterQuery, entityExists, exitQuery, forEachEntity, getComponent, getEntityGeneration, getEntityIndex, getWorldCapacity, getWorldSize, hasComponent, isEntity, isWorld, iterQuery, packEntity, pipe, queryArchetypes, removeComponent, resetWorld, runQuery, setComponent };
125
+ export { AoSComponent, Archetype, ComponentInit, ComponentLike, EntityId, EntityNotAliveError, type EntityRef, IS_SAB_SUPPORTED, Query, QueryDescriptor, SoAComponent, SoASchema, System, TagComponent, VERSION, World, WorldOptions, addComponent, aliveRef, createEntity, createWorld, defineComponent, defineObjectComponent, defineQuery, defineTag, deref, destroyEntity, destroyWorld, destroyWorld as disposeWorld, enterQuery, entityExists, exitQuery, forEachEntity, getComponent, getEntityGeneration, getEntityIndex, getWorldCapacity, getWorldSize, hasComponent, isEntity, isWorld, iterQuery, packEntity, pipe, queryArchetypes, refOf, removeComponent, resetWorld, runQuery, setComponent };
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { o as WorldOptions, W as World, E as EntityId, c as ComponentLike, b as ComponentInit, k as SoASchema, h as SoAComponent, A as AoSComponent, T as TagComponent, f as QueryDescriptor, Q as Query, a as Archetype, l as System } from './types-BGEeHad-.js';
2
2
  export { d as ComponentView, g as SoAColumns, i as SoAFieldDecl, j as SoAFieldType, n as Types } from './types-BGEeHad-.js';
3
3
 
4
- declare const VERSION = "0.2.1";
4
+ declare const VERSION = "0.3.1";
5
5
 
6
6
  declare function createWorld(options?: WorldOptions): World;
7
7
  declare function destroyWorld(world: World): void;
@@ -13,9 +13,28 @@ declare function isWorld(x: unknown): x is World;
13
13
  declare function createEntity(world: World): EntityId;
14
14
  declare function destroyEntity(world: World, eid: EntityId): void;
15
15
  declare function entityExists(world: World, eid: EntityId): boolean;
16
+ /**
17
+ * Extract the index portion of a packed entity ID.
18
+ *
19
+ * Uses the default 24-bit index layout. If you created the world with a
20
+ * non-default `indexBits`, use `EntityRef` + `deref` instead.
21
+ */
16
22
  declare function getEntityIndex(eid: EntityId): number;
17
- declare function getEntityGeneration(_eid: EntityId): number;
18
- declare function packEntity(index: number, _generation: number): EntityId;
23
+ /**
24
+ * Extract the generation portion of a packed entity ID.
25
+ *
26
+ * Uses the default 8-bit generation layout. If you created the world with a
27
+ * non-default `generationBits`, use `EntityRef` + `deref` instead.
28
+ */
29
+ declare function getEntityGeneration(eid: EntityId): number;
30
+ /**
31
+ * Pack an index and generation into an EntityId using the default 24/8 bit layout.
32
+ *
33
+ * Uses the default `indexBits=24, generationBits=8`. If you created the world
34
+ * with non-default bit sizes, this will produce values with incorrect layout.
35
+ * Use `EntityRef` and `deref` for portable cross-world identity matching.
36
+ */
37
+ declare function packEntity(index: number, generation: number): EntityId;
19
38
  declare function isEntity(world: World, x: unknown): x is EntityId;
20
39
 
21
40
  declare function defineComponent<S extends SoASchema>(schema: S): SoAComponent<S>;
@@ -37,6 +56,70 @@ declare function forEachEntity(world: World, query: Query, fn: (eid: EntityId, .
37
56
 
38
57
  declare function pipe<W extends World = World, Ctx = unknown>(...systems: System<W, Ctx>[]): System<W, Ctx>;
39
58
 
59
+ /**
60
+ * ABA-safe entity reference.
61
+ *
62
+ * Holds the packed EntityId and the id of the world that issued it.
63
+ * Use `deref(world, ref)` to validate and retrieve the live entity id.
64
+ *
65
+ * The phantom type `T` allows callers to distinguish reference kinds at the
66
+ * type system level — e.g. `EntityRef<'bullet'>` vs `EntityRef<'player'>` —
67
+ * without any runtime overhead.
68
+ *
69
+ * @example
70
+ * const ref = refOf<'bullet'>(world, e)
71
+ * // later, in a system:
72
+ * const live = deref(world, ref)
73
+ * if (live !== null) {
74
+ * // entity is still alive with the same generation
75
+ * }
76
+ */
77
+ interface EntityRef<T = unknown> {
78
+ readonly id: EntityId;
79
+ readonly worldId: number;
80
+ readonly __phantom?: T;
81
+ }
82
+ /**
83
+ * Thrown by `refOf` when the entity is not alive.
84
+ * `deref` and `aliveRef` never throw — they return null/false.
85
+ */
86
+ declare class EntityNotAliveError extends Error {
87
+ readonly eid: number;
88
+ constructor(eid: number);
89
+ }
90
+ /**
91
+ * Create an ABA-safe reference to a live entity.
92
+ *
93
+ * @throws {EntityNotAliveError} if the entity is not alive (dead, never created, or eid === 0).
94
+ *
95
+ * The returned object is frozen. `id` is the packed EntityId; `worldId` is
96
+ * the world's numeric id used by `deref` to reject cross-world lookups.
97
+ *
98
+ * The function may be called on the hot path — each call returns a new object
99
+ * but performs no allocation beyond that.
100
+ */
101
+ declare function refOf<T = unknown>(world: World, entity: EntityId): EntityRef<T>;
102
+ /**
103
+ * Resolve a ref to its live EntityId, or return null if stale.
104
+ *
105
+ * Returns null when any of the following hold:
106
+ * 1. `ref.worldId !== state.id` — cross-world ref
107
+ * 2. `getEntityIndex(ref.id) >= state.capacity` — index out-of-bounds
108
+ * 3. `getEntityIndex(ref.id) === 0` — sentinel slot
109
+ * 4. entity is not in any archetype's entityRow (slot released)
110
+ * 5. generation mismatch → ABA: old ref points at recycled slot
111
+ *
112
+ * Never throws.
113
+ */
114
+ declare function deref<T = unknown>(world: World, ref: EntityRef<T>): EntityId | null;
115
+ /**
116
+ * Boolean guard form of `deref`. Equivalent to `deref(world, ref) !== null`.
117
+ * Use in guard clauses when you do not need the resolved EntityId.
118
+ *
119
+ * Never throws.
120
+ */
121
+ declare function aliveRef<T = unknown>(world: World, ref: EntityRef<T>): boolean;
122
+
40
123
  declare const IS_SAB_SUPPORTED: boolean;
41
124
 
42
- export { AoSComponent, Archetype, ComponentInit, ComponentLike, EntityId, IS_SAB_SUPPORTED, Query, QueryDescriptor, SoAComponent, SoASchema, System, TagComponent, VERSION, World, WorldOptions, addComponent, createEntity, createWorld, defineComponent, defineObjectComponent, defineQuery, defineTag, destroyEntity, destroyWorld, destroyWorld as disposeWorld, enterQuery, entityExists, exitQuery, forEachEntity, getComponent, getEntityGeneration, getEntityIndex, getWorldCapacity, getWorldSize, hasComponent, isEntity, isWorld, iterQuery, packEntity, pipe, queryArchetypes, removeComponent, resetWorld, runQuery, setComponent };
125
+ export { AoSComponent, Archetype, ComponentInit, ComponentLike, EntityId, EntityNotAliveError, type EntityRef, IS_SAB_SUPPORTED, Query, QueryDescriptor, SoAComponent, SoASchema, System, TagComponent, VERSION, World, WorldOptions, addComponent, aliveRef, createEntity, createWorld, defineComponent, defineObjectComponent, defineQuery, defineTag, deref, destroyEntity, destroyWorld, destroyWorld as disposeWorld, enterQuery, entityExists, exitQuery, forEachEntity, getComponent, getEntityGeneration, getEntityIndex, getWorldCapacity, getWorldSize, hasComponent, isEntity, isWorld, iterQuery, packEntity, pipe, queryArchetypes, refOf, removeComponent, resetWorld, runQuery, setComponent };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- var U="0.2.1";function b(n){return new Uint32Array(n)}function h(n,e){let t=e>>>5;n[t]=(n[t]??0)|1<<(e&31);}function D(n,e){let t=e>>>5;n[t]=(n[t]??0)&~(1<<(e&31));}function C(n,e){let t=e>>>5;return ((n[t]??0)&1<<(e&31))!==0}function g(n){let e=new Uint32Array(n.length);for(let t=0;t<n.length;t++)e[t]=n[t]??0;return e}function O(n){let e=[];for(let t=0;t<n.length;t++)e.push((n[t]??0).toString(16));return e.join(",")}function q(n){for(let e=0;e<n.length;e++)if((n[e]??0)!==0)return false;return true}function E(n,e,t,r,o,i){let s=!o;for(let a=0;a<i;a++){let c=n[a]??0,u=e[a]??0,d=t[a]??0,y=r[a]??0;if((c&u)!==u||(c&y)!==0)return false;!s&&(c&d)!==0&&(s=true);}return s}function W(n){let e=[];for(let t=0;t<n.length;t++){let r=n[t]??0;for(;r!==0;){let o=(t<<5)+P(r);e.push(o),r&=r-1;}}return e}function V(n,e,t,r){for(let o=0;o<t;o++){let i=n[e+o]??0;for(;i!==0;){let s=(o<<5)+P(i);r(s),i&=i-1;}}}function P(n){return 31-Math.clz32(n&-n)}var B={initialCapacity:1024,maxEntities:1e6,indexBits:24,generationBits:8},ye=256,fe=1,k=new Map;function f(n){let e=k.get(n.id);if(!e)throw new Error(`aiecsjs: world ${n.id} is destroyed or unknown`);if(e.destroyed)throw new Error(`aiecsjs: world ${n.id} is destroyed`);return e}function pe(n){k.set(n.id,n);}function le(n){k.delete(n);}function me(n){let e=n??{},t=e.indexBits??B.indexBits,r=e.generationBits??B.generationBits,o=ye;if(t<1||t>24)throw new Error("aiecsjs: indexBits must be in [1, 24]");if(r<0||r>16)throw new Error("aiecsjs: generationBits must be in [0, 16]");let i=1<<t,s=Math.max(1,Math.min(e.initialCapacity??B.initialCapacity,i)),a=Math.max(s,Math.min(e.maxEntities??B.maxEntities,i));return {initialCapacity:s,maxEntities:a,indexBits:t,generationBits:r,maxComponents:o,maskWordCount:Math.ceil(o/32),buffer:e.buffer??null,bufferByteOffset:e.bufferByteOffset??0}}function be(n,e){return {id:0,mask:b(n),size:0,capacity:16,entities:new Uint32Array(16),entityRow:new Map,componentBits:[],edgeAdd:new Int32Array(e).fill(-1),edgeRemove:new Int32Array(e).fill(-1)}}function he(n){let e=me(n),t=fe++,r=e.generationBits>8?Uint16Array:Uint8Array,o=new r(e.initialCapacity),i={id:t,capacity:e.initialCapacity,version:U,options:e,size:0,nextFreshIndex:1,freeList:[],generations:o,destroyed:false,componentBitFor:new Map,componentInfoByBit:new Array(e.maxComponents).fill(null),componentStorageByBit:new Array(e.maxComponents).fill(null),nextComponentBit:0,entityArchetype:new Uint32Array(e.initialCapacity),entityMask:new Uint32Array(e.initialCapacity*e.maskWordCount),archetypes:[],archetypeByMaskHash:new Map,queryVersion:0,queries:[],queryMasks:new Map,queryArchetypeCache:[],queryArchetypeStamp:[],bitToQueries:new Map,reactiveBuffers:new Map,observers:[],relationStorage:new Map,sab:e.buffer,readOnly:false},s=be(e.maskWordCount,e.maxComponents);return s.id=0,i.archetypes.push(s),i.archetypeByMaskHash.set(O(s.mask),0),pe(i),Ce(i)}function Ce(n){return {id:n.id,get capacity(){return n.capacity},version:n.version}}function $(n){let e=k.get(n.id);!e||e.destroyed||(e.destroyed=true,e.archetypes=[],e.archetypeByMaskHash.clear(),e.componentInfoByBit=[],e.componentStorageByBit=[],e.queries=[],e.queryMasks.clear(),e.queryArchetypeCache=[],e.observers=[],e.relationStorage.clear(),e.reactiveBuffers.clear(),le(n.id));}function Ae(n){let e=f(n);e.size=0,e.nextFreshIndex=1,e.freeList=[],e.generations.fill(0),e.entityArchetype.fill(0),e.entityMask.fill(0);for(let t of e.archetypes)t.size=0,t.entityRow.clear();for(let t of e.componentStorageByBit)if(t)if(t.kind==="soa"&&t.soa)for(let r of Object.keys(t.soa))t.soa[r]?.fill(0);else t.kind==="aos"&&t.aos&&t.aos.fill(void 0);e.queryVersion++;for(let t of e.reactiveBuffers.values())t.entered.length=0,t.exited.length=0;}function xe(n){return f(n).size}function ge(n){return f(n).capacity}function H(n,e){if(e<=n.capacity)return;if(e>n.options.maxEntities)throw new Error(`aiecsjs: requested capacity ${e} exceeds maxEntities ${n.options.maxEntities}`);let t=n.capacity;for(;t<e;)t=Math.min(t*2,n.options.maxEntities);ke(n,t);}function ke(n,e){let t=n.generations.constructor,r=new t(e);r.set(n.generations),n.generations=r;let o=new Uint32Array(e);o.set(n.entityArchetype),n.entityArchetype=o;let i=n.options.maskWordCount,s=new Uint32Array(e*i);s.set(n.entityMask),n.entityMask=s;for(let a of n.componentStorageByBit)if(a)if(a.kind==="soa"&&a.soa){let c=n.componentInfoByBit[a.bit];c&&Ie(a.soa,c.fields,e);}else a.kind==="aos"&&a.aos&&(a.aos.length=e);n.capacity=e;}function Ie(n,e,t){for(let r of e){let o=n[r.name];if(!o)continue;let i=t*r.vectorLen;if(o.length>=i)continue;let s=new r.ctor(i);s.set(o),n[r.name]=s;}}function K(n,e){let t=O(e),r=n.archetypeByMaskHash.get(t);if(r!==void 0)return {archId:r,created:false};let o=n.archetypes.length,i={id:o,mask:g(e),size:0,capacity:16,entities:new Uint32Array(16),entityRow:new Map,componentBits:we(e),edgeAdd:new Int32Array(n.options.maxComponents).fill(-1),edgeRemove:new Int32Array(n.options.maxComponents).fill(-1)};return n.archetypes.push(i),n.archetypeByMaskHash.set(t,o),n.queryVersion++,{archId:o,created:true}}function M(n,e){if(e<=n.capacity)return;let t=n.capacity;for(;t<e;)t*=2;let r=new Uint32Array(t);r.set(n.entities),n.entities=r,n.capacity=t;}function we(n){let e=[];for(let t=0;t<n.length;t++){let r=n[t]??0;for(;r!==0;){let o=r&-r,i=(t<<5)+(31-Math.clz32(o));e.push(i),r&=r-1;}}return e}function A(n,e){let t=n.componentBitFor.get(e.id);if(t!==void 0)return t;if(n.nextComponentBit>=n.options.maxComponents)throw new Error(`aiecsjs: world reached maxComponents=${n.options.maxComponents}`);let r=n.nextComponentBit++;n.componentBitFor.set(e.id,r),n.componentInfoByBit[r]=e;let o;if(e.kind==="soa"){let i={};for(let s of e.fields)i[s.name]=new s.ctor(n.capacity*s.vectorLen);o={kind:"soa",componentId:e.id,bit:r,soa:i};}else e.kind==="aos"?o={kind:"aos",componentId:e.id,bit:r,aos:new Array(n.capacity)}:o={kind:"tag",componentId:e.id,bit:r};return n.componentStorageByBit[r]=o,r}function x(n,e){let t=n.options.maskWordCount,r=new Uint32Array(t),o=e*t;for(let i=0;i<t;i++)r[i]=n.entityMask[o+i]??0;return r}function N(n,e,t){let r=n.options.maskWordCount,o=e*r;for(let i=0;i<r;i++)n.entityMask[o+i]=t[i]??0;}function I(n,e){return n.componentBitFor.get(e.id)}function ve(n){if(!n||typeof n!="object")return false;let e=n;return typeof e.id!="number"||typeof e.version!="string"?false:k.has(e.id)}function Se(n){let e=f(n);if(e.readOnly)throw new Error("aiecsjs: cannot createEntity on a read-only world (worker-attached)");let t;if(e.freeList.length>0)t=e.freeList.pop();else {if(e.nextFreshIndex>=e.options.maxEntities)throw new Error(`aiecsjs: reached maxEntities ${e.options.maxEntities}`);e.nextFreshIndex>=e.capacity&&H(e,e.nextFreshIndex+1),t=e.nextFreshIndex++;}let r=e.archetypes[0];if(!r)throw new Error("aiecsjs: missing empty archetype");M(r,r.size+1);let o=r.size;r.entities[o]=t,r.entityRow.set(t,o),r.size++,e.entityArchetype[t]=0;let i=e.options.maskWordCount,s=t*i;for(let a=0;a<i;a++)e.entityMask[s+a]=0;return e.size++,t}function Ee(n,e){let t=f(n);if(t.readOnly)throw new Error("aiecsjs: cannot destroyEntity on a read-only world");if(!p(t,e))return;X(t,e);let o=t.entityArchetype[e]??0,i=t.archetypes[o];if(i){let u=i.entityRow.get(e);if(u!==void 0){let d=i.size-1;if(u!==d){let y=i.entities[d]??0;i.entities[u]=y,i.entityRow.set(y,u);}i.entities[d]=0,i.entityRow.delete(e),i.size--;}}t.entityArchetype[e]=0;let s=t.options.maskWordCount,a=e*s;for(let u=0;u<s;u++)t.entityMask[a+u]=0;let c=e;t.generations[c]=(t.generations[c]??0)+1&65535,t.freeList.push(e),t.size--;}function Z(n,e){let t=f(n);return p(t,e)}function p(n,e){if(e<=0||e>=n.capacity)return false;let t=n.entityArchetype[e]??0,r=n.archetypes[t];return r?r.entityRow.has(e):false}function We(n){return n}function Be(n){return 0}function Me(n,e){return n}function _e(n,e){return typeof e!="number"?false:Z(n,e)}var T=1,Qe={i8:Int8Array,u8:Uint8Array,i16:Int16Array,u16:Uint16Array,i32:Int32Array,u32:Uint32Array,f32:Float32Array,f64:Float64Array,eid:Uint32Array,bool:Uint8Array},w=new Map;function Re(n){let e=[];for(let[i,s]of Object.entries(n)){let a,c=1;if(typeof s=="string")a=s;else if(Array.isArray(s)){let[d,y]=s;a=d,c=y;}else throw new TypeError(`aiecsjs: invalid field declaration for "${i}"`);let u=Qe[a];if(!u)throw new TypeError(`aiecsjs: unknown field type "${a}" for field "${i}"`);e.push({name:i,type:a,vectorLen:c,ctor:u,bytesPerElement:u.BYTES_PER_ELEMENT});}let t=T++,r={id:t,kind:"soa",schema:n,fields:e,factory:null};return w.set(t,r),{__kind:"soa",__id:t,__schema:n}}function Te(){let n=T++,e={id:n,kind:"tag",schema:null,fields:[],factory:null};return w.set(n,e),{__kind:"tag",__id:n}}function Le(n){let e=T++,t=n??(()=>({})),r={id:e,kind:"aos",schema:null,fields:[],factory:t};return w.set(e,r),{__kind:"aos",__id:e,__factory:t}}function l(n){let e=w.get(n.__id);if(!e)throw new Error("aiecsjs: component is not registered (call defineComponent/defineTag/defineObjectComponent)");return e}function Q(n,e,t,r){let o=f(n);if(o.readOnly)throw new Error("aiecsjs: cannot mutate a read-only world");if(!p(o,e))throw new Error(`aiecsjs: addComponent on dead entity ${e}`);let i=l(t),s=A(o,i),a=x(o,e);if(C(a,s)){r!==void 0&&R(o,e,t,r);return}let c=g(a);h(c,s),ee(o,e,c),R(o,e,t,r),re(o,e,s,a,c);}function je(n,e,t){let r=f(n);if(r.readOnly)throw new Error("aiecsjs: cannot mutate a read-only world");if(!p(r,e))return;let o=l(t),i=I(r,o);if(i===void 0)return;let s=x(r,e);if(!C(s,i))return;let a=g(s);D(a,i),ee(r,e,a);let c=r.componentStorageByBit[i];c?.kind==="soa"&&c.soa?J(c.soa,o.fields,e):c?.kind==="aos"&&c.aos&&(c.aos[e]=void 0),re(r,e,i,s,a);}function Fe(n,e,t){let r=f(n);if(!p(r,e))return false;let o=l(t),i=I(r,o);if(i===void 0)return false;let s=x(r,e);return C(s,i)}function ze(n,e,t){let r=f(n);if(!p(r,e))return;let o=l(t),i=I(r,o);if(i===void 0)return;let s=x(r,e);if(!C(s,i))return;let a=r.componentStorageByBit[i];if(a)return a.kind==="soa"?a.soa:a.kind==="aos"?a.aos?.[e]:true}function De(n,e,t,r){let o=f(n);if(o.readOnly)throw new Error("aiecsjs: cannot mutate a read-only world");if(!p(o,e))throw new Error(`aiecsjs: setComponent on dead entity ${e}`);let i=l(t),s=I(o,i);if(s===void 0){Q(n,e,t,r);return}let a=x(o,e);if(!C(a,s)){Q(n,e,t,r);return}R(o,e,t,r);}function R(n,e,t,r){let o=l(t),i=n.componentBitFor.get(o.id);if(i===void 0)return;let s=n.componentStorageByBit[i];if(s){if(o.kind==="soa"&&s.soa){if(r==null)return;let a=r;for(let c of o.fields){if(!(c.name in a))continue;let u=s.soa[c.name];if(!u)continue;let d=a[c.name];if(c.vectorLen===1)u[e]=typeof d=="boolean"?d?1:0:Number(d);else if(Array.isArray(d)||ArrayBuffer.isView(d)){let y=e*c.vectorLen,de=d;for(let S=0;S<c.vectorLen;S++)u[y+S]=Number(de[S]??0);}}}else if(o.kind==="aos"&&s.aos){let a=o.factory??(()=>({})),c=s.aos[e];if(c===void 0&&(c=a(),s.aos[e]=c),r&&typeof r=="object"){let u=r,d=c;for(let y of Object.keys(u))y==="__proto__"||y==="constructor"||y==="prototype"||(d[y]=u[y]);}}}}function J(n,e,t){for(let r of e){let o=n[r.name];if(o)if(r.vectorLen===1)o[t]=0;else {let i=t*r.vectorLen;for(let s=0;s<r.vectorLen;s++)o[i+s]=0;}}}function X(n,e){let t=n.options.maskWordCount,r=e,o=r*t;V(n.entityMask,o,t,i=>{let s=n.componentStorageByBit[i],a=n.componentInfoByBit[i];s?.kind==="soa"&&s.soa&&a?J(s.soa,a.fields,r):s?.kind==="aos"&&s.aos&&(s.aos[r]=void 0);});}function ee(n,e,t){let r=n.entityArchetype[e]??0,o=n.archetypes[r];if(!o)return;let s=K(n,t).archId,a=n.archetypes[s];if(a){if(s!==r){let c=o.entityRow.get(e);if(c!==void 0){let d=o.size-1;if(c!==d){let y=o.entities[d]??0;o.entities[c]=y,o.entityRow.set(y,c);}o.entities[d]=0,o.entityRow.delete(e),o.size--;}M(a,a.size+1);let u=a.size;a.entities[u]=e,a.entityRow.set(e,u),a.size++,n.entityArchetype[e]=s;}N(n,e,t);}}var ne=()=>{};function te(n){ne=n;}function re(n,e,t,r,o){ne(n,e,t,r,o);}function oe(n){return w.get(n)}var z=1,m=new Map;function $e(n){let e=(n.all??[]).map(o=>o.__id).sort((o,i)=>o-i).join("-"),t=(n.any??[]).map(o=>o.__id).sort((o,i)=>o-i).join("-"),r=(n.none??[]).map(o=>o.__id).sort((o,i)=>o-i).join("-");return `A${e}|Y${t}|N${r}`}function He(n){let e=Array.isArray(n)?{all:n}:n;for(let i of [...e.all??[],...e.any??[],...e.none??[]])if(!i||typeof i!="object"||typeof i.__id!="number")throw new TypeError("aiecsjs: defineQuery received a non-component value");let t=$e(e),r=m.get(t);if(r)return r;let o={id:z++,mask:[],all:(e.all??[]).map(i=>i.__id),any:(e.any??[]).map(i=>i.__id),none:(e.none??[]).map(i=>i.__id),columnViewCache:[...e.all??[],...e.any??[]],reactiveKind:"normal",sourceQueryId:-1,sourceQuery:null};return m.set(t,o),o}function Ke(n){let e=n,t=`enter:${e.id}`,r=m.get(t);if(r)return r;let o={id:z++,mask:[],all:e.all,any:e.any,none:e.none,columnViewCache:e.columnViewCache,reactiveKind:"enter",sourceQueryId:e.id,sourceQuery:e};return m.set(t,o),o}function Ne(n){let e=n,t=`exit:${e.id}`,r=m.get(t);if(r)return r;let o={id:z++,mask:[],all:e.all,any:e.any,none:e.none,columnViewCache:e.columnViewCache,reactiveKind:"exit",sourceQueryId:e.id,sourceQuery:e};return m.set(t,o),o}function v(n,e){if(n.queries[e.id]===e&&n.queryMasks.has(e.id))return;let t=n.options.maskWordCount,r=b(t),o=b(t),i=b(t);for(let c of e.all){let u=j(c),d=A(n,u);h(r,d);}for(let c of e.any){let u=j(c),d=A(n,u);h(o,d);}for(let c of e.none){let u=j(c),d=A(n,u);h(i,d);}let s={withMask:r,anyMask:o,noneMask:i,anyHasBits:!q(o)};n.queryMasks.set(e.id,s),n.queries[e.id]=e,n.queryArchetypeCache[e.id]=null,n.queryArchetypeStamp[e.id]=-1;let a=[...W(r),...W(o),...W(i)];for(let c of a){let u=n.bitToQueries.get(c);u||(u=new Set,n.bitToQueries.set(c,u)),u.add(e.id);}e.reactiveKind!=="normal"&&(n.reactiveBuffers.has(e.id)||n.reactiveBuffers.set(e.id,{entered:[],exited:[]}),e.sourceQuery&&v(n,e.sourceQuery));}function _(n,e){if(v(n,e),n.queryArchetypeCache[e.id]&&n.queryArchetypeStamp[e.id]===n.queryVersion)return n.queryArchetypeCache[e.id];let t=n.queryMasks.get(e.id),r=n.options.maskWordCount,o=[];for(let i=0;i<n.archetypes.length;i++){let s=n.archetypes[i];E(s.mask,t.withMask,t.anyMask,t.noneMask,t.anyHasBits,r)&&o.push(i);}return n.queryArchetypeCache[e.id]=o,n.queryArchetypeStamp[e.id]=n.queryVersion,o}function Ge(n,e){let t=f(n),o=_(t,e),i=[];for(let s of o){let a=t.archetypes[s];i.push({id:a.id,mask:Array.from(a.mask),size:a.size});}return i}function Ye(n,e){let t=f(n),r=e,o=[];if(r.reactiveKind==="enter"){let s=t.reactiveBuffers.get(r.id);if(s){for(let a of s.entered)o.push(a);s.entered.length=0;}return o}if(r.reactiveKind==="exit"){let s=t.reactiveBuffers.get(r.id);if(s){for(let a of s.exited)o.push(a);s.exited.length=0;}return o}let i=_(t,r);for(let s of i){let a=t.archetypes[s];for(let c=0;c<a.size;c++)o.push(a.entities[c]);}return o}function*Ze(n,e){let t=f(n),r=e;if(r.reactiveKind!=="normal"){let i=t.reactiveBuffers.get(r.id);if(!i)return;let s=r.reactiveKind==="enter"?i.entered:i.exited;for(let a of s)yield a;s.length=0;return}let o=_(t,r);for(let i of o){let s=t.archetypes[i];for(let a=0;a<s.size;a++)yield s.entities[a];}}function Xe(n,e,t){let r=f(n),o=e;if(o.reactiveKind!=="normal"){let a=r.reactiveBuffers.get(o.id);if(!a)return;let c=o.reactiveKind==="enter"?a.entered:a.exited;if(c.length===0)return;let u=se(r,o);for(let d=0;d<c.length;d++){let y=c[d];ie(t,y,u);}c.length=0;return}v(r,o);let i=_(r,o),s=se(r,o);for(let a of i){let c=r.archetypes[a],u=c.entities,d=c.size;for(let y=0;y<d;y++)ie(t,u[y],s);}}function ie(n,e,t){switch(t.length){case 0:n(e);break;case 1:n(e,t[0]);break;case 2:n(e,t[0],t[1]);break;case 3:n(e,t[0],t[1],t[2]);break;case 4:n(e,t[0],t[1],t[2],t[3]);break;case 5:n(e,t[0],t[1],t[2],t[3],t[4]);break;default:n(e,...t);}}function se(n,e){let t=[];for(let r of e.columnViewCache){let o=l(r),i=n.componentBitFor.get(o.id);if(i===void 0){t.push(void 0);continue}let s=n.componentStorageByBit[i];if(!s){t.push(void 0);continue}s.kind==="soa"?t.push(s.soa):s.kind==="aos"?t.push(s.aos):t.push(true);}return t}function ce(n,e,t,r,o){for(let a of m.values())a.reactiveKind!=="normal"&&a.sourceQuery&&n.queries[a.sourceQuery.id]!==a.sourceQuery&&v(n,a.sourceQuery);let i=n.bitToQueries.get(t);if(!i)return;let s=n.options.maskWordCount;for(let a of i){let c=n.queries[a];if(!c||c.reactiveKind!=="normal")continue;let u=n.queryMasks.get(a);if(!u)continue;let d=E(r,u.withMask,u.anyMask,u.noneMask,u.anyHasBits,s),y=E(o,u.withMask,u.anyMask,u.noneMask,u.anyHasBits,s);!d&&y?ae(n,a,"enter",e):d&&!y&&ae(n,a,"exit",e);}}function ae(n,e,t,r){for(let o of m.values()){if(o.sourceQueryId!==e||o.reactiveKind!==t)continue;v(n,o);let i=Je(n,o.id);t==="enter"?i.entered.push(r):i.exited.push(r);}}function Je(n,e){let t=n.reactiveBuffers.get(e);return t||(t={entered:[],exited:[]},n.reactiveBuffers.set(e,t)),t}function j(n){let e=en(n);if(!e)throw new Error(`aiecsjs: component id ${n} not registered`);return e}var F=null;function ue(n){F=n;}function en(n){return F?F(n):void 0}var nn={i8:"i8",u8:"u8",i16:"i16",u16:"u16",i32:"i32",u32:"u32",f32:"f32",f64:"f64",eid:"eid",bool:"bool"};function tn(...n){return n.length===0?e=>e:n.length===1?n[0]:(e,t)=>{let r=e;for(let o of n)r=o(r,t);return r}}ue(n=>oe(n));te((n,e,t,r,o)=>{ce(n,e,t,r,o);});var Wn=typeof SharedArrayBuffer<"u";export{Wn as IS_SAB_SUPPORTED,nn as Types,U as VERSION,Q as addComponent,Se as createEntity,he as createWorld,Re as defineComponent,Le as defineObjectComponent,He as defineQuery,Te as defineTag,Ee as destroyEntity,$ as destroyWorld,$ as disposeWorld,Ke as enterQuery,Z as entityExists,Ne as exitQuery,Xe as forEachEntity,ze as getComponent,Be as getEntityGeneration,We as getEntityIndex,ge as getWorldCapacity,xe as getWorldSize,Fe as hasComponent,_e as isEntity,ve as isWorld,Ze as iterQuery,Me as packEntity,tn as pipe,Ge as queryArchetypes,je as removeComponent,Ae as resetWorld,Ye as runQuery,De as setComponent};//# sourceMappingURL=index.js.map
1
+ import {i as i$1,h}from'./chunk-FDXCXNZK.js';export{a as defineQuery,b as enterQuery,c as exitQuery,g as forEachEntity,f as iterQuery,d as queryArchetypes,e as runQuery}from'./chunk-FDXCXNZK.js';import {P,N,i as i$2,x,s,t}from'./chunk-L5CMKMIP.js';export{a as VERSION,I as addComponent,u as createEntity,k as createWorld,E as defineComponent,G as defineObjectComponent,F as defineTag,v as destroyEntity,l as destroyWorld,l as disposeWorld,w as entityExists,L as getComponent,z as getEntityGeneration,y as getEntityIndex,o as getWorldCapacity,n as getWorldSize,K as hasComponent,B as isEntity,q as isWorld,A as packEntity,J as removeComponent,m as resetWorld,M as setComponent}from'./chunk-L5CMKMIP.js';var K={i8:"i8",u8:"u8",i16:"i16",u16:"u16",i32:"i32",u32:"u32",f32:"f32",f64:"f64",eid:"eid",bool:"bool"};function $(...n){return n.length===0?e=>e:n.length===1?n[0]:(e,r)=>{let t=e;for(let o of n)t=o(t,r);return t}}var i=class extends Error{eid;constructor(e){super(`aiecsjs: entity ${e} is not alive`),this.name="EntityNotAliveError",this.eid=e;}};function J(n,e){let r=i$2(n);if(!x(r,e))throw new i(e);return Object.freeze({id:e,worldId:r.id})}function b(n,e){let r=i$2(n);if(e.worldId!==r.id)return null;let t$1=e.id,o=s(t$1,r.options);if(o<=0||o>=r.capacity)return null;let x=r.entityArchetype[o]??0,d=r.archetypes[x];if(!d||!d.entityRow.has(e.id))return null;let C=r.generations[o]??0,A=t(t$1,r.options);return C!==A?null:e.id}function X(n,e){return b(n,e)!==null}i$1(n=>P(n));N((n,e,r,t,o)=>{h(n,e,r,t,o);});var ae=typeof SharedArrayBuffer<"u";export{i as EntityNotAliveError,ae as IS_SAB_SUPPORTED,K as Types,X as aliveRef,b as deref,$ as pipe,J as refOf};//# sourceMappingURL=index.js.map
2
2
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/version.ts","../src/internal/bitmask.ts","../src/internal/world.ts","../src/internal/entity.ts","../src/internal/component.ts","../src/internal/query.ts","../src/internal/types.ts","../src/internal/pipe.ts","../src/index.ts"],"names":["VERSION","createMask","wordCount","setBit","mask","bit","w","clearBit","testBit","cloneMask","src","out","i","maskHash","m","parts","isMaskZero","matches","withMask","anyMask","noneMask","anyHasBits","words","anyHit","wm","am","nm","listBits","word","ctz32","forEachSetBit","base","fn","wi","v","DEFAULT_OPTIONS","DEFAULT_MAX_COMPONENTS","nextWorldId","worldRegistry","getWorldState","world","state","registerWorld","unregisterWorld","id","resolveOptions","opts","o","indexBits","generationBits","maxComponents","maxByIndex","initialCapacity","maxEntities","createEmptyArchetype","maskWordCount","createWorld","options","resolved","generationCtor","generations","empty","makePublicWorld","destroyWorld","resetWorld","arch","storage","k","buf","getWorldSize","getWorldCapacity","ensureCapacity","needed","newCap","growEntityArrays","genCtor","newGen","newArch","newMask","info","growSoAColumns","soa","fields","f","old","newLen","next","findOrCreateArchetype","key","existing","collectBits","ensureArchetypeCapacity","bits","lsb","getOrRegisterComponentBit","readEntityMask","eid","writeEntityMask","tryGetComponentBit","isWorld","x","obj","createEntity","row","destroyEntity","isAliveInternal","clearAllEntityStorages","archId","lastRow","moved","idx","entityExists","getEntityIndex","getEntityGeneration","_eid","packEntity","index","_generation","isEntity","nextComponentId","TYPE_CTOR","componentInfoById","defineComponent","schema","name","decl","type","vectorLen","t","len","ctor","defineTag","defineObjectComponent","factory","fac","getComponentInfo","component","addComponent","initial","prevMask","writeInitial","migrateEntity","notifyMaskChange","removeComponent","clearSoAEntity","hasComponent","getComponent","setComponent","value","col","val","arr","inst","target","srcArchId","srcArch","destArchId","destArch","newRow","_maskChange","registerMaskChangeDispatch","prev","getComponentByInternalId","nextQueryId","moduleQueryCache","descKey","d","all","c","a","b","any","none","defineQuery","arg","desc","cached","q","enterQuery","query","reactive","exitQuery","ensureQueryRegistered","ww","compId","getComponentInfoById","bundle","involvedBits","s","getQueryArchetypes","list","queryArchetypes","ids","runQuery","e","archIds","r","iterQuery","forEachEntity","cols","buildColumnViews","callWithCols","ents","n","comp","recordEntityMaskChange","changedBit","nextMask","involved","qid","wasMatch","isMatch","pushReactive","queryId","kind","ensureReactiveBuffer","componentId","lazyGetComponentInfo","_getComponentInfoFn","registerComponentLookup","Types","pipe","systems","ctx","IS_SAB_SUPPORTED"],"mappings":"AAAO,IAAMA,CAAAA,CAAU,QCEhB,SAASC,CAAAA,CAAWC,CAAAA,CAAgC,CACzD,OAAO,IAAI,WAAA,CAAYA,CAAS,CAClC,CAEO,SAASC,CAAAA,C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AIkC,CAAAA,CACR,IAAA,IAAWoJ,KAAKkC,CAAAA,CAASxN,CAAAA,CAAIsL,CAAAA,CAAEtL,CAAAA,CAAGyN,CAAG,CAAA,CACrC,OAAOzN,CACT,CACF,CCGAqN,EAAAA,CAAyB/K,CAAAA,EAAOsH,EAAAA,CAAyBtH,CAAE,CAAC,CAAA,CAG5DoH,EAAAA,CAA2B,CAACvH,CAAAA,CAAOuD,CAAAA,CAAK3F,CAAAA,CAAK4J,CAAAA,CAAM3E,CAAAA,GAAS,CAC1DuH,EAAAA,CAAuBpK,CAAAA,CAAOuD,EAAK3F,CAAAA,CAAK4J,CAAAA,CAAM3E,CAAI,EACpD,CAAC,CAAA,CAoFM,IAAM0I,EAAAA,CAA4B,OAAO,iBAAA,CAAsB","file":"index.js","sourcesContent":["export const VERSION = '0.2.1'\n","// Multi-word Uint32 bitmask helpers.\n\nexport function createMask(wordCount: number): Uint32Array {\n return new Uint32Array(wordCount)\n}\n\nexport function setBit(mask: Uint32Array, bit: number): void {\n const w = bit >>> 5\n mask[w] = (mask[w] ?? 0) | (1 << (bit & 31))\n}\n\nexport function clearBit(mask: Uint32Array, bit: number): void {\n const w = bit >>> 5\n mask[w] = (mask[w] ?? 0) & ~(1 << (bit & 31))\n}\n\nexport function testBit(mask: Uint32Array, bit: number): boolean {\n const w = bit >>> 5\n return ((mask[w] ?? 0) & (1 << (bit & 31))) !== 0\n}\n\nexport function copyMask(dst: Uint32Array, src: Uint32Array): void {\n const n = src.length\n for (let i = 0; i < n; i++) dst[i] = src[i] ?? 0\n}\n\nexport function cloneMask(src: Uint32Array): Uint32Array {\n const out = new Uint32Array(src.length)\n for (let i = 0; i < src.length; i++) out[i] = src[i] ?? 0\n return out\n}\n\nexport function maskEquals(a: Uint32Array, b: Uint32Array): boolean {\n const n = a.length\n if (b.length !== n) return false\n for (let i = 0; i < n; i++) if ((a[i] ?? 0) !== (b[i] ?? 0)) return false\n return true\n}\n\nexport function maskHash(m: Uint32Array): string {\n // Stable string key for Map lookups. Hex-joined.\n const parts: string[] = []\n for (let i = 0; i < m.length; i++) {\n parts.push((m[i] ?? 0).toString(16))\n }\n return parts.join(',')\n}\n\nexport function isMaskZero(m: Uint32Array): boolean {\n for (let i = 0; i < m.length; i++) if ((m[i] ?? 0) !== 0) return false\n return true\n}\n\nexport function unionMask(a: Uint32Array, b: Uint32Array): Uint32Array {\n const out = new Uint32Array(a.length)\n for (let i = 0; i < a.length; i++) out[i] = (a[i] ?? 0) | (b[i] ?? 0)\n return out\n}\n\n/**\n * Test whether an archetype's mask matches a query.\n * - withMask: all of these bits must be present\n * - anyMask: if anyHasBits, at least one of these bits must be present\n * - noneMask: none of these bits may be present\n */\nexport function matches(\n mask: Uint32Array,\n withMask: Uint32Array,\n anyMask: Uint32Array,\n noneMask: Uint32Array,\n anyHasBits: boolean,\n words: number,\n): boolean {\n let anyHit = !anyHasBits\n for (let w = 0; w < words; w++) {\n const m = mask[w] ?? 0\n const wm = withMask[w] ?? 0\n const am = anyMask[w] ?? 0\n const nm = noneMask[w] ?? 0\n if ((m & wm) !== wm) return false\n if ((m & nm) !== 0) return false\n if (!anyHit && (m & am) !== 0) anyHit = true\n }\n return anyHit\n}\n\nexport function listBits(mask: Uint32Array): number[] {\n const out: number[] = []\n for (let w = 0; w < mask.length; w++) {\n let word = mask[w] ?? 0\n while (word !== 0) {\n const bit = (w << 5) + ctz32(word)\n out.push(bit)\n word &= word - 1\n }\n }\n return out\n}\n\n// Iterate set bits in a slice of a larger Uint32Array starting at `base`.\n// Shared by destroy paths and storage cleanup so the bit-extraction maths\n// lives in exactly one place.\nexport function forEachSetBit(\n mask: Uint32Array,\n base: number,\n words: number,\n fn: (bit: number) => void,\n): void {\n for (let wi = 0; wi < words; wi++) {\n let word = mask[base + wi] ?? 0\n while (word !== 0) {\n const bit = (wi << 5) + ctz32(word)\n fn(bit)\n word &= word - 1\n }\n }\n}\n\n// Match a query against an entity's mask stored as a slice inside a larger\n// Uint32Array. Reading directly from the parent array avoids the temporary\n// Uint32Array allocation on every observer dispatch.\nexport function matchesEntityMask(\n entityMask: Uint32Array,\n base: number,\n words: number,\n withMask: Uint32Array,\n anyMask: Uint32Array,\n noneMask: Uint32Array,\n anyHasBits: boolean,\n): boolean {\n let anyHit = !anyHasBits\n for (let i = 0; i < words; i++) {\n const m = entityMask[base + i] ?? 0\n const wm = withMask[i] ?? 0\n const am = anyMask[i] ?? 0\n const nm = noneMask[i] ?? 0\n if ((m & wm) !== wm) return false\n if ((m & nm) !== 0) return false\n if (!anyHit && (m & am) !== 0) anyHit = true\n }\n return anyHit\n}\n\nfunction ctz32(v: number): number {\n // Count trailing zeros in a 32-bit integer (assumes v !== 0)\n return 31 - Math.clz32(v & -v)\n}\n","import { VERSION } from '../version.js'\nimport { cloneMask, copyMask, createMask, maskHash } from './bitmask.js'\nimport type {\n ArchetypeState,\n ComponentInfo,\n FieldInfo,\n ResolvedWorldOptions,\n World,\n WorldComponentStorage,\n WorldOptions,\n WorldState,\n} from './types.js'\n\nexport const WORLD_BRAND = Symbol.for('aiecsjs.world')\n\nconst DEFAULT_OPTIONS: Required<Omit<WorldOptions, 'buffer' | 'bufferByteOffset'>> = {\n initialCapacity: 1024,\n maxEntities: 1_000_000,\n indexBits: 24,\n generationBits: 8,\n}\n\nconst DEFAULT_MAX_COMPONENTS = 256\n\nlet nextWorldId = 1\nconst worldRegistry = new Map<number, WorldState>()\n\nexport function getWorldState(world: World): WorldState {\n const state = worldRegistry.get(world.id)\n if (!state) throw new Error(`aiecsjs: world ${world.id} is destroyed or unknown`)\n if (state.destroyed) throw new Error(`aiecsjs: world ${world.id} is destroyed`)\n return state\n}\n\nexport function registerWorld(state: WorldState): void {\n worldRegistry.set(state.id, state)\n}\n\nexport function unregisterWorld(id: number): void {\n worldRegistry.delete(id)\n}\n\nexport function isWorldRegistered(id: number): boolean {\n return worldRegistry.has(id)\n}\n\nfunction resolveOptions(opts: WorldOptions | undefined): ResolvedWorldOptions {\n const o = opts ?? {}\n const indexBits = o.indexBits ?? DEFAULT_OPTIONS.indexBits\n const generationBits = o.generationBits ?? DEFAULT_OPTIONS.generationBits\n const maxComponents = DEFAULT_MAX_COMPONENTS\n if (indexBits < 1 || indexBits > 24) {\n throw new Error('aiecsjs: indexBits must be in [1, 24]')\n }\n if (generationBits < 0 || generationBits > 16) {\n throw new Error('aiecsjs: generationBits must be in [0, 16]')\n }\n const maxByIndex = 1 << indexBits\n const initialCapacity = Math.max(\n 1,\n Math.min(o.initialCapacity ?? DEFAULT_OPTIONS.initialCapacity, maxByIndex),\n )\n const maxEntities = Math.max(\n initialCapacity,\n Math.min(o.maxEntities ?? DEFAULT_OPTIONS.maxEntities, maxByIndex),\n )\n return {\n initialCapacity,\n maxEntities,\n indexBits,\n generationBits,\n maxComponents,\n maskWordCount: Math.ceil(maxComponents / 32),\n buffer: o.buffer ?? null,\n bufferByteOffset: o.bufferByteOffset ?? 0,\n }\n}\n\nexport function createEmptyArchetype(maskWordCount: number, maxComponents: number): ArchetypeState {\n return {\n id: 0,\n mask: createMask(maskWordCount),\n size: 0,\n capacity: 16,\n entities: new Uint32Array(16),\n entityRow: new Map<number, number>(),\n componentBits: [],\n edgeAdd: new Int32Array(maxComponents).fill(-1),\n edgeRemove: new Int32Array(maxComponents).fill(-1),\n }\n}\n\nexport function createWorld(options?: WorldOptions): World {\n const resolved = resolveOptions(options)\n const id = nextWorldId++\n\n const generationCtor = resolved.generationBits > 8 ? Uint16Array : Uint8Array\n const generations = new generationCtor(resolved.initialCapacity)\n\n const state: WorldState = {\n id,\n capacity: resolved.initialCapacity,\n version: VERSION,\n options: resolved,\n size: 0,\n nextFreshIndex: 1, // 0 reserved\n freeList: [],\n generations,\n destroyed: false,\n componentBitFor: new Map<number, number>(),\n componentInfoByBit: new Array(resolved.maxComponents).fill(null),\n componentStorageByBit: new Array(resolved.maxComponents).fill(null),\n nextComponentBit: 0,\n entityArchetype: new Uint32Array(resolved.initialCapacity),\n entityMask: new Uint32Array(resolved.initialCapacity * resolved.maskWordCount),\n archetypes: [],\n archetypeByMaskHash: new Map<string, number>(),\n queryVersion: 0,\n queries: [],\n queryMasks: new Map(),\n queryArchetypeCache: [],\n queryArchetypeStamp: [],\n bitToQueries: new Map<number, Set<number>>(),\n reactiveBuffers: new Map(),\n observers: [],\n relationStorage: new Map(),\n sab: resolved.buffer,\n readOnly: false,\n }\n\n // Seed archetype 0 (the empty mask)\n const empty = createEmptyArchetype(resolved.maskWordCount, resolved.maxComponents)\n empty.id = 0\n state.archetypes.push(empty)\n state.archetypeByMaskHash.set(maskHash(empty.mask), 0)\n\n registerWorld(state)\n return makePublicWorld(state)\n}\n\nexport function makePublicWorld(state: WorldState): World {\n return {\n id: state.id,\n get capacity() {\n return state.capacity\n },\n version: state.version,\n } as World\n}\n\nexport function destroyWorld(world: World): void {\n const state = worldRegistry.get(world.id)\n if (!state || state.destroyed) return\n state.destroyed = true\n // Clear large buffers to help GC\n state.archetypes = []\n state.archetypeByMaskHash.clear()\n state.componentInfoByBit = []\n state.componentStorageByBit = []\n state.queries = []\n state.queryMasks.clear()\n state.queryArchetypeCache = []\n state.observers = []\n state.relationStorage.clear()\n state.reactiveBuffers.clear()\n unregisterWorld(world.id)\n}\n\nexport function resetWorld(world: World): void {\n const state = getWorldState(world)\n // Keep capacity and registered components; clear entities and per-entity state.\n state.size = 0\n state.nextFreshIndex = 1\n state.freeList = []\n state.generations.fill(0)\n state.entityArchetype.fill(0)\n state.entityMask.fill(0)\n // Wipe archetype memberships but keep archetype graph for stability.\n for (const arch of state.archetypes) {\n arch.size = 0\n arch.entityRow.clear()\n }\n // Clear SoA columns and AoS instances; storage allocation is preserved.\n for (const storage of state.componentStorageByBit) {\n if (!storage) continue\n if (storage.kind === 'soa' && storage.soa) {\n for (const k of Object.keys(storage.soa)) {\n storage.soa[k]?.fill(0)\n }\n } else if (storage.kind === 'aos' && storage.aos) {\n storage.aos.fill(undefined as unknown as never)\n }\n }\n state.queryVersion++\n for (const buf of state.reactiveBuffers.values()) {\n buf.entered.length = 0\n buf.exited.length = 0\n }\n}\n\nexport function getWorldSize(world: World): number {\n return getWorldState(world).size\n}\n\nexport function getWorldCapacity(world: World): number {\n return getWorldState(world).capacity\n}\n\n// --- Capacity growth ---\n\nexport function ensureCapacity(state: WorldState, needed: number): void {\n if (needed <= state.capacity) return\n if (needed > state.options.maxEntities) {\n throw new Error(\n `aiecsjs: requested capacity ${needed} exceeds maxEntities ${state.options.maxEntities}`,\n )\n }\n let newCap = state.capacity\n while (newCap < needed) newCap = Math.min(newCap * 2, state.options.maxEntities)\n growEntityArrays(state, newCap)\n}\n\nfunction growEntityArrays(state: WorldState, newCap: number): void {\n // generations\n const genCtor: any = state.generations.constructor\n const newGen = new genCtor(newCap) as Uint8Array | Uint16Array\n ;(newGen as Uint8Array).set(state.generations as Uint8Array)\n state.generations = newGen\n\n // entityArchetype\n const newArch = new Uint32Array(newCap)\n newArch.set(state.entityArchetype)\n state.entityArchetype = newArch\n\n // entityMask\n const wordCount = state.options.maskWordCount\n const newMask = new Uint32Array(newCap * wordCount)\n newMask.set(state.entityMask)\n state.entityMask = newMask\n\n // Component storages (SoA columns + AoS arrays)\n for (const storage of state.componentStorageByBit) {\n if (!storage) continue\n if (storage.kind === 'soa' && storage.soa) {\n const info = state.componentInfoByBit[storage.bit]\n if (info) growSoAColumns(storage.soa, info.fields, newCap)\n } else if (storage.kind === 'aos' && storage.aos) {\n storage.aos.length = newCap\n }\n }\n\n state.capacity = newCap\n}\n\nfunction growSoAColumns(soa: Record<string, any>, fields: FieldInfo[], newCap: number): void {\n for (const f of fields) {\n const old = soa[f.name]\n if (!old) continue\n const newLen = newCap * f.vectorLen\n if (old.length >= newLen) continue\n const next = new f.ctor(newLen)\n next.set(old)\n soa[f.name] = next\n }\n}\n\n// --- Archetype management ---\n\nexport function findOrCreateArchetype(\n state: WorldState,\n mask: Uint32Array,\n): { archId: number; created: boolean } {\n const key = maskHash(mask)\n const existing = state.archetypeByMaskHash.get(key)\n if (existing !== undefined) return { archId: existing, created: false }\n\n const id = state.archetypes.length\n const arch: ArchetypeState = {\n id,\n mask: cloneMask(mask),\n size: 0,\n capacity: 16,\n entities: new Uint32Array(16),\n entityRow: new Map<number, number>(),\n componentBits: collectBits(mask),\n edgeAdd: new Int32Array(state.options.maxComponents).fill(-1),\n edgeRemove: new Int32Array(state.options.maxComponents).fill(-1),\n }\n state.archetypes.push(arch)\n state.archetypeByMaskHash.set(key, id)\n state.queryVersion++\n return { archId: id, created: true }\n}\n\nexport function ensureArchetypeCapacity(arch: ArchetypeState, needed: number): void {\n if (needed <= arch.capacity) return\n let newCap = arch.capacity\n while (newCap < needed) newCap *= 2\n const next = new Uint32Array(newCap)\n next.set(arch.entities)\n arch.entities = next\n arch.capacity = newCap\n}\n\nfunction collectBits(mask: Uint32Array): number[] {\n const bits: number[] = []\n for (let w = 0; w < mask.length; w++) {\n let word = mask[w] ?? 0\n while (word !== 0) {\n const lsb = word & -word\n const bit = (w << 5) + (31 - Math.clz32(lsb))\n bits.push(bit)\n word &= word - 1\n }\n }\n return bits\n}\n\n// --- Component registration in a world ---\n\nexport function getOrRegisterComponentBit(state: WorldState, info: ComponentInfo): number {\n const existing = state.componentBitFor.get(info.id)\n if (existing !== undefined) return existing\n\n if (state.nextComponentBit >= state.options.maxComponents) {\n throw new Error(`aiecsjs: world reached maxComponents=${state.options.maxComponents}`)\n }\n const bit = state.nextComponentBit++\n state.componentBitFor.set(info.id, bit)\n state.componentInfoByBit[bit] = info\n\n // Create storage\n let storage: WorldComponentStorage\n if (info.kind === 'soa') {\n const soa: Record<string, any> = {}\n for (const f of info.fields) {\n soa[f.name] = new f.ctor(state.capacity * f.vectorLen)\n }\n storage = { kind: 'soa', componentId: info.id, bit, soa }\n } else if (info.kind === 'aos') {\n storage = { kind: 'aos', componentId: info.id, bit, aos: new Array(state.capacity) }\n } else {\n storage = { kind: 'tag', componentId: info.id, bit }\n }\n state.componentStorageByBit[bit] = storage\n return bit\n}\n\n// Read a bitmask out of state.entityMask[] into a fresh Uint32Array.\nexport function readEntityMask(state: WorldState, eid: number): Uint32Array {\n const w = state.options.maskWordCount\n const out = new Uint32Array(w)\n const base = eid * w\n for (let i = 0; i < w; i++) out[i] = state.entityMask[base + i] ?? 0\n return out\n}\n\nexport function writeEntityMask(state: WorldState, eid: number, mask: Uint32Array): void {\n const w = state.options.maskWordCount\n const base = eid * w\n for (let i = 0; i < w; i++) state.entityMask[base + i] = mask[i] ?? 0\n}\n\n// Get the bit of a component within a world without registering.\nexport function tryGetComponentBit(state: WorldState, info: ComponentInfo): number | undefined {\n return state.componentBitFor.get(info.id)\n}\n\nexport function isWorld(x: unknown): x is World {\n if (!x || typeof x !== 'object') return false\n const obj = x as { id?: unknown; version?: unknown }\n if (typeof obj.id !== 'number') return false\n if (typeof obj.version !== 'string') return false\n return worldRegistry.has(obj.id)\n}\n","import { clearAllEntityStorages } from './component.js'\nimport type { EntityId, World, WorldState } from './types.js'\nimport { ensureArchetypeCapacity, ensureCapacity, getWorldState } from './world.js'\n\nexport function createEntity(world: World): EntityId {\n const state = getWorldState(world)\n if (state.readOnly) {\n throw new Error('aiecsjs: cannot createEntity on a read-only world (worker-attached)')\n }\n\n let eid: number\n if (state.freeList.length > 0) {\n eid = state.freeList.pop()!\n } else {\n if (state.nextFreshIndex >= state.options.maxEntities) {\n throw new Error(`aiecsjs: reached maxEntities ${state.options.maxEntities}`)\n }\n if (state.nextFreshIndex >= state.capacity) {\n ensureCapacity(state, state.nextFreshIndex + 1)\n }\n eid = state.nextFreshIndex++\n }\n\n // Move into the empty archetype (0)\n const arch = state.archetypes[0]\n if (!arch) throw new Error('aiecsjs: missing empty archetype')\n ensureArchetypeCapacity(arch, arch.size + 1)\n const row = arch.size\n arch.entities[row] = eid\n arch.entityRow.set(eid, row)\n arch.size++\n\n state.entityArchetype[eid] = 0\n // Reset entityMask row for this eid\n const w = state.options.maskWordCount\n const base = eid * w\n for (let i = 0; i < w; i++) state.entityMask[base + i] = 0\n\n state.size++\n return eid as EntityId\n}\n\nexport function destroyEntity(world: World, eid: EntityId): void {\n const state = getWorldState(world)\n if (state.readOnly) {\n throw new Error('aiecsjs: cannot destroyEntity on a read-only world')\n }\n if (!isAliveInternal(state, eid)) return\n\n // Fire onRemove for every component the entity has, plus reactive exit\n // (Late-bound to avoid circular imports — done via observers module.)\n const { dispatchDestroyObservers } = lazyObservers()\n dispatchDestroyObservers(state, eid)\n\n // Clean up relations referring to this entity\n cleanupRelationsOnDestroy(state, eid)\n\n // Zero the SoA columns / undefine the AoS slots the entity owned, before\n // the mask is cleared. Without this, destroyed entities leave stale data\n // visible to snapshots and serialisation.\n clearAllEntityStorages(state, eid)\n\n // Swap-pop from its archetype\n const archId = state.entityArchetype[eid] ?? 0\n const arch = state.archetypes[archId]\n if (arch) {\n const row = arch.entityRow.get(eid)\n if (row !== undefined) {\n const lastRow = arch.size - 1\n if (row !== lastRow) {\n const moved = arch.entities[lastRow] ?? 0\n arch.entities[row] = moved\n arch.entityRow.set(moved, row)\n }\n arch.entities[lastRow] = 0\n arch.entityRow.delete(eid)\n arch.size--\n }\n }\n\n // Wipe state\n state.entityArchetype[eid] = 0\n const w = state.options.maskWordCount\n const base = eid * w\n for (let i = 0; i < w; i++) state.entityMask[base + i] = 0\n // bump generation (Uint8Array wraps to 8 bits naturally; Uint16Array to 16)\n const idx = eid as number\n state.generations[idx] = ((state.generations[idx] ?? 0) + 1) & 0xffff\n\n state.freeList.push(eid)\n state.size--\n}\n\nexport function entityExists(world: World, eid: EntityId): boolean {\n const state = getWorldState(world)\n return isAliveInternal(state, eid)\n}\n\nexport function isAliveInternal(state: WorldState, eid: number): boolean {\n if (eid <= 0) return false\n if (eid >= state.capacity) return false\n // An entity is alive iff it is in some archetype (its row map points somewhere).\n const archId = state.entityArchetype[eid] ?? 0\n const arch = state.archetypes[archId]\n if (!arch) return false\n return arch.entityRow.has(eid)\n}\n\nexport function getEntityIndex(eid: EntityId): number {\n return eid as number\n}\n\nexport function getEntityGeneration(_eid: EntityId): number {\n // Unversioned in 0.1: generation not encoded in EntityId.\n return 0\n}\n\nexport function packEntity(index: number, _generation: number): EntityId {\n // Identity in 0.1.\n return index as EntityId\n}\n\nexport function isEntity(world: World, x: unknown): x is EntityId {\n if (typeof x !== 'number') return false\n return entityExists(world, x as EntityId)\n}\n\n// --- Lazy loaders to break import cycles ---\n\ninterface ObserversAPI {\n dispatchDestroyObservers(state: WorldState, eid: EntityId): void\n}\nlet _observersAPI: ObserversAPI | null = null\nexport function registerObserversAPI(api: ObserversAPI): void {\n _observersAPI = api\n}\nfunction lazyObservers(): ObserversAPI {\n if (!_observersAPI) {\n return { dispatchDestroyObservers: () => {} }\n }\n return _observersAPI\n}\n\nlet _relationsCleanup: ((state: WorldState, eid: EntityId) => void) | null = null\nexport function registerRelationsCleanup(fn: (state: WorldState, eid: EntityId) => void): void {\n _relationsCleanup = fn\n}\nfunction cleanupRelationsOnDestroy(state: WorldState, eid: EntityId): void {\n if (_relationsCleanup) _relationsCleanup(state, eid)\n}\n","import { clearBit, cloneMask, forEachSetBit, setBit, testBit } from './bitmask.js'\nimport { isAliveInternal } from './entity.js'\nimport type {\n AoSComponent,\n ComponentInfo,\n ComponentInit,\n ComponentLike,\n EntityId,\n FieldInfo,\n SoAColumns,\n SoAComponent,\n SoASchema,\n TagComponent,\n TypedArrayConstructor,\n World,\n WorldComponentStorage,\n WorldState,\n} from './types.js'\nimport {\n ensureArchetypeCapacity,\n findOrCreateArchetype,\n getOrRegisterComponentBit,\n getWorldState,\n readEntityMask,\n tryGetComponentBit,\n writeEntityMask,\n} from './world.js'\n\n// --- Component factories ---\n\nlet nextComponentId = 1\n\nconst TYPE_CTOR: Record<string, TypedArrayConstructor> = {\n i8: Int8Array,\n u8: Uint8Array,\n i16: Int16Array,\n u16: Uint16Array,\n i32: Int32Array,\n u32: Uint32Array,\n f32: Float32Array,\n f64: Float64Array,\n eid: Uint32Array,\n bool: Uint8Array,\n}\n\nconst componentInfoById = new Map<number, ComponentInfo>()\n\nexport function defineComponent<S extends SoASchema>(schema: S): SoAComponent<S> {\n const fields: FieldInfo[] = []\n for (const [name, decl] of Object.entries(schema)) {\n let type: keyof typeof TYPE_CTOR\n let vectorLen = 1\n if (typeof decl === 'string') {\n type = decl\n } else if (Array.isArray(decl)) {\n const [t, len] = decl\n type = t\n vectorLen = len\n } else {\n throw new TypeError(`aiecsjs: invalid field declaration for \"${name}\"`)\n }\n const ctor = TYPE_CTOR[type]\n if (!ctor) throw new TypeError(`aiecsjs: unknown field type \"${type}\" for field \"${name}\"`)\n fields.push({\n name,\n type: type as any,\n vectorLen,\n ctor,\n bytesPerElement: (ctor as any).BYTES_PER_ELEMENT,\n })\n }\n const id = nextComponentId++\n const info: ComponentInfo = { id, kind: 'soa', schema, fields, factory: null }\n componentInfoById.set(id, info)\n const handle: SoAComponent<S> = {\n __kind: 'soa',\n __id: id,\n __schema: schema,\n }\n return handle\n}\n\nexport function defineTag(): TagComponent {\n const id = nextComponentId++\n const info: ComponentInfo = { id, kind: 'tag', schema: null, fields: [], factory: null }\n componentInfoById.set(id, info)\n return { __kind: 'tag', __id: id }\n}\n\nexport function defineObjectComponent<T>(factory?: () => T): AoSComponent<T> {\n const id = nextComponentId++\n const fac = factory ?? (() => ({}) as T)\n const info: ComponentInfo = { id, kind: 'aos', schema: null, fields: [], factory: fac as any }\n componentInfoById.set(id, info)\n return { __kind: 'aos', __id: id, __factory: fac }\n}\n\nexport function getComponentInfo(component: ComponentLike): ComponentInfo {\n const info = componentInfoById.get(component.__id)\n if (!info)\n throw new Error(\n 'aiecsjs: component is not registered (call defineComponent/defineTag/defineObjectComponent)',\n )\n return info\n}\n\n// --- Component ops on entities ---\n\nexport function addComponent<C extends ComponentLike>(\n world: World,\n eid: EntityId,\n component: C,\n initial?: ComponentInit<C>,\n): void {\n const state = getWorldState(world)\n if (state.readOnly) throw new Error('aiecsjs: cannot mutate a read-only world')\n if (!isAliveInternal(state, eid)) {\n throw new Error(`aiecsjs: addComponent on dead entity ${eid}`)\n }\n const info = getComponentInfo(component)\n const bit = getOrRegisterComponentBit(state, info)\n\n const prevMask = readEntityMask(state, eid)\n if (testBit(prevMask, bit)) {\n if (initial !== undefined) writeInitial(state, eid, component, initial)\n return\n }\n const newMask = cloneMask(prevMask)\n setBit(newMask, bit)\n migrateEntity(state, eid, newMask)\n\n writeInitial(state, eid, component, initial)\n\n fireAddObservers(state, eid, bit)\n notifyMaskChange(state, eid, bit, prevMask, newMask)\n}\n\nexport function removeComponent<C extends ComponentLike>(\n world: World,\n eid: EntityId,\n component: C,\n): void {\n const state = getWorldState(world)\n if (state.readOnly) throw new Error('aiecsjs: cannot mutate a read-only world')\n if (!isAliveInternal(state, eid)) return\n const info = getComponentInfo(component)\n const bit = tryGetComponentBit(state, info)\n if (bit === undefined) return\n const prevMask = readEntityMask(state, eid)\n if (!testBit(prevMask, bit)) return\n\n // Write the new mask BEFORE firing observers so query-targeted observers\n // reading `state.entityMask` see the post-removal state (and thus correctly\n // detect \"entity left this query\"). Without this reorder, a query that\n // requires the removed component would still match during dispatch and the\n // remove observer would never fire. Component-targeted observers receive the\n // bit directly and don't depend on mask timing. addComponent already follows\n // this \"mutate then fire\" order; keeping removeComponent consistent.\n const newMask = cloneMask(prevMask)\n clearBit(newMask, bit)\n migrateEntity(state, eid, newMask)\n\n fireRemoveObservers(state, eid, bit)\n\n const storage = state.componentStorageByBit[bit]\n if (storage?.kind === 'soa' && storage.soa) {\n clearSoAEntity(storage.soa, info.fields, eid)\n } else if (storage?.kind === 'aos' && storage.aos) {\n storage.aos[eid] = undefined\n }\n\n notifyMaskChange(state, eid, bit, prevMask, newMask)\n}\n\nexport function hasComponent<C extends ComponentLike>(\n world: World,\n eid: EntityId,\n component: C,\n): boolean {\n const state = getWorldState(world)\n if (!isAliveInternal(state, eid)) return false\n const info = getComponentInfo(component)\n const bit = tryGetComponentBit(state, info)\n if (bit === undefined) return false\n const mask = readEntityMask(state, eid)\n return testBit(mask, bit)\n}\n\nexport function getComponent<C extends ComponentLike>(\n world: World,\n eid: EntityId,\n component: C,\n): unknown {\n const state = getWorldState(world)\n if (!isAliveInternal(state, eid)) return undefined\n const info = getComponentInfo(component)\n const bit = tryGetComponentBit(state, info)\n if (bit === undefined) return undefined\n const mask = readEntityMask(state, eid)\n if (!testBit(mask, bit)) return undefined\n const storage = state.componentStorageByBit[bit]\n if (!storage) return undefined\n if (storage.kind === 'soa') return storage.soa\n if (storage.kind === 'aos') return storage.aos?.[eid]\n return true // tag\n}\n\nexport function setComponent<C extends ComponentLike, V>(\n world: World,\n eid: EntityId,\n component: C,\n value: V,\n): void {\n const state = getWorldState(world)\n if (state.readOnly) throw new Error('aiecsjs: cannot mutate a read-only world')\n if (!isAliveInternal(state, eid)) throw new Error(`aiecsjs: setComponent on dead entity ${eid}`)\n const info = getComponentInfo(component)\n const bit = tryGetComponentBit(state, info)\n if (bit === undefined) {\n // Adding via set\n addComponent(world, eid, component, value as any)\n return\n }\n const mask = readEntityMask(state, eid)\n if (!testBit(mask, bit)) {\n addComponent(world, eid, component, value as any)\n return\n }\n writeInitial(state, eid, component, value as any)\n fireSetObservers(state, eid, bit, value)\n}\n\n// --- Internals ---\n\nfunction writeInitial(\n state: WorldState,\n eid: number,\n component: ComponentLike,\n initial: unknown,\n): void {\n const info = getComponentInfo(component)\n const bit = state.componentBitFor.get(info.id)\n if (bit === undefined) return\n const storage = state.componentStorageByBit[bit]\n if (!storage) return\n if (info.kind === 'soa' && storage.soa) {\n if (initial == null) return\n const obj = initial as Record<string, unknown>\n for (const f of info.fields) {\n if (!(f.name in obj)) continue\n const col = storage.soa[f.name]\n if (!col) continue\n const val = obj[f.name]\n if (f.vectorLen === 1) {\n col[eid] = typeof val === 'boolean' ? (val ? 1 : 0) : Number(val)\n } else if (Array.isArray(val) || ArrayBuffer.isView(val)) {\n const base = eid * f.vectorLen\n const arr = val as ArrayLike<number>\n for (let i = 0; i < f.vectorLen; i++) col[base + i] = Number(arr[i] ?? 0)\n }\n }\n } else if (info.kind === 'aos' && storage.aos) {\n const factory = info.factory ?? (() => ({}))\n let inst = storage.aos[eid]\n if (inst === undefined) {\n inst = factory()\n storage.aos[eid] = inst\n }\n if (initial && typeof initial === 'object') {\n // SECURITY: do NOT use `Object.assign(inst, initial)` here. When `initial`\n // comes from `JSON.parse(untrustedBytes)` — e.g. via `fromJSON`,\n // `deserializeWorld`, or app code piping a bridge payload — the parsed\n // object can carry an OWN `__proto__` property, and `Object.assign` uses\n // [[Set]] semantics which would trigger the proto setter and clobber the\n // instance's prototype chain. Explicit own-key copy with a deny-list\n // closes the prototype-pollution path.\n const src = initial as Record<string, unknown>\n const target = inst as Record<string, unknown>\n for (const key of Object.keys(src)) {\n if (key === '__proto__' || key === 'constructor' || key === 'prototype') continue\n target[key] = src[key]\n }\n }\n }\n // tag: nothing\n}\n\nfunction clearSoAEntity(soa: SoAColumns, fields: FieldInfo[], eid: number): void {\n for (const f of fields) {\n const col = soa[f.name]\n if (!col) continue\n if (f.vectorLen === 1) {\n col[eid] = 0\n } else {\n const base = eid * f.vectorLen\n for (let i = 0; i < f.vectorLen; i++) col[base + i] = 0\n }\n }\n}\n\n// Clear every component-storage slot that the entity currently owns.\n// Walks the entity's mask; for each set bit, zeroes the SoA columns or\n// undefines the AoS slot at the entity index. Tag storages are bit-only.\n// Caller (e.g. destroyEntity) is expected to clear the mask separately.\nexport function clearAllEntityStorages(state: WorldState, eid: EntityId): void {\n const wordCount = state.options.maskWordCount\n const idx = eid as number\n const base = idx * wordCount\n forEachSetBit(state.entityMask, base, wordCount, (bit) => {\n const storage = state.componentStorageByBit[bit]\n const info = state.componentInfoByBit[bit]\n if (storage?.kind === 'soa' && storage.soa && info) {\n clearSoAEntity(storage.soa, info.fields, idx)\n } else if (storage?.kind === 'aos' && storage.aos) {\n storage.aos[idx] = undefined\n }\n })\n}\n\nfunction migrateEntity(state: WorldState, eid: number, newMask: Uint32Array): void {\n const srcArchId = state.entityArchetype[eid] ?? 0\n const srcArch = state.archetypes[srcArchId]\n if (!srcArch) return\n\n const found = findOrCreateArchetype(state, newMask)\n const destArchId = found.archId\n const destArch = state.archetypes[destArchId]\n if (!destArch) return\n\n if (destArchId !== srcArchId) {\n // Swap-pop from src\n const row = srcArch.entityRow.get(eid)\n if (row !== undefined) {\n const lastRow = srcArch.size - 1\n if (row !== lastRow) {\n const moved = srcArch.entities[lastRow] ?? 0\n srcArch.entities[row] = moved\n srcArch.entityRow.set(moved, row)\n }\n srcArch.entities[lastRow] = 0\n srcArch.entityRow.delete(eid)\n srcArch.size--\n }\n\n // Append to dest\n ensureArchetypeCapacity(destArch, destArch.size + 1)\n const newRow = destArch.size\n destArch.entities[newRow] = eid\n destArch.entityRow.set(eid, newRow)\n destArch.size++\n\n state.entityArchetype[eid] = destArchId\n }\n\n writeEntityMask(state, eid, newMask)\n}\n\n// --- Observer dispatch (lazy-bound) ---\n\ninterface ObserversDispatchAPI {\n fireAdd(state: WorldState, eid: EntityId, bit: number): void\n fireRemove(state: WorldState, eid: EntityId, bit: number): void\n fireSet(state: WorldState, eid: EntityId, bit: number, value: unknown): void\n}\nlet _dispatch: ObserversDispatchAPI = {\n fireAdd: () => {},\n fireRemove: () => {},\n fireSet: () => {},\n}\n\ntype MaskChangeFn = (\n state: WorldState,\n eid: EntityId,\n bit: number,\n prev: Uint32Array,\n next: Uint32Array,\n) => void\nlet _maskChange: MaskChangeFn = () => {}\nexport function registerMaskChangeDispatch(fn: MaskChangeFn): void {\n _maskChange = fn\n}\nfunction notifyMaskChange(\n state: WorldState,\n eid: number,\n bit: number,\n prev: Uint32Array,\n next: Uint32Array,\n): void {\n _maskChange(state, eid as EntityId, bit, prev, next)\n}\nexport function registerObserverDispatch(api: ObserversDispatchAPI): void {\n _dispatch = api\n}\nfunction fireAddObservers(state: WorldState, eid: number, bit: number): void {\n _dispatch.fireAdd(state, eid as EntityId, bit)\n}\nfunction fireRemoveObservers(state: WorldState, eid: number, bit: number): void {\n _dispatch.fireRemove(state, eid as EntityId, bit)\n}\nfunction fireSetObservers(state: WorldState, eid: number, bit: number, value: unknown): void {\n _dispatch.fireSet(state, eid as EntityId, bit, value)\n}\n\n// --- Helper for serialize/worker ---\n\nexport function getComponentByInternalId(id: number): ComponentInfo | undefined {\n return componentInfoById.get(id)\n}\n\nexport function listAllComponents(): ComponentInfo[] {\n return Array.from(componentInfoById.values())\n}\n\nexport function _resetComponentRegistry_FOR_TESTS_ONLY(): void {\n componentInfoById.clear()\n nextComponentId = 1\n}\n","import { createMask, isMaskZero, listBits, matches, setBit } from './bitmask.js'\nimport { getComponentInfo } from './component.js'\nimport type {\n Archetype,\n ComponentInfo,\n ComponentLike,\n EntityId,\n Query,\n QueryDescriptor,\n QueryInternal,\n QueryMaskBundle,\n ReactiveBuffer,\n World,\n WorldState,\n} from './types.js'\nimport {\n getOrRegisterComponentBit,\n getWorldState,\n readEntityMask,\n tryGetComponentBit,\n} from './world.js'\n\nlet nextQueryId = 1\nconst moduleQueryCache = new Map<string, QueryInternal>()\n\nfunction descKey(d: QueryDescriptor): string {\n const all = (d.all ?? [])\n .map((c) => c.__id)\n .sort((a, b) => a - b)\n .join('-')\n const any = (d.any ?? [])\n .map((c) => c.__id)\n .sort((a, b) => a - b)\n .join('-')\n const none = (d.none ?? [])\n .map((c) => c.__id)\n .sort((a, b) => a - b)\n .join('-')\n return `A${all}|Y${any}|N${none}`\n}\n\nexport function defineQuery(arg: ComponentLike[] | QueryDescriptor): Query {\n const desc: QueryDescriptor = Array.isArray(arg) ? { all: arg } : arg\n\n // Validate all members are components\n for (const c of [...(desc.all ?? []), ...(desc.any ?? []), ...(desc.none ?? [])]) {\n if (!c || typeof c !== 'object' || typeof (c as any).__id !== 'number') {\n throw new TypeError('aiecsjs: defineQuery received a non-component value')\n }\n }\n\n const key = descKey(desc)\n const cached = moduleQueryCache.get(key)\n if (cached) return cached\n\n const q: QueryInternal = {\n id: nextQueryId++,\n mask: [],\n all: (desc.all ?? []).map((c) => c.__id),\n any: (desc.any ?? []).map((c) => c.__id),\n none: (desc.none ?? []).map((c) => c.__id),\n columnViewCache: [...(desc.all ?? []), ...(desc.any ?? [])],\n reactiveKind: 'normal',\n sourceQueryId: -1,\n sourceQuery: null,\n }\n moduleQueryCache.set(key, q)\n return q\n}\n\nexport function enterQuery(query: Query): Query {\n const q = query as QueryInternal\n const key = `enter:${q.id}`\n const cached = moduleQueryCache.get(key)\n if (cached) return cached\n const reactive: QueryInternal = {\n id: nextQueryId++,\n mask: [],\n all: q.all,\n any: q.any,\n none: q.none,\n columnViewCache: q.columnViewCache,\n reactiveKind: 'enter',\n sourceQueryId: q.id,\n sourceQuery: q,\n }\n moduleQueryCache.set(key, reactive)\n return reactive\n}\n\nexport function exitQuery(query: Query): Query {\n const q = query as QueryInternal\n const key = `exit:${q.id}`\n const cached = moduleQueryCache.get(key)\n if (cached) return cached\n const reactive: QueryInternal = {\n id: nextQueryId++,\n mask: [],\n all: q.all,\n any: q.any,\n none: q.none,\n columnViewCache: q.columnViewCache,\n reactiveKind: 'exit',\n sourceQueryId: q.id,\n sourceQuery: q,\n }\n moduleQueryCache.set(key, reactive)\n return reactive\n}\n\n// --- Per-world query setup ---\n\nfunction ensureQueryRegistered(state: WorldState, q: QueryInternal): void {\n if (state.queries[q.id] === q && state.queryMasks.has(q.id)) return\n\n // Build per-world bitmasks (this may register new bits)\n const ww = state.options.maskWordCount\n const withMask = createMask(ww)\n const anyMask = createMask(ww)\n const noneMask = createMask(ww)\n for (const compId of q.all) {\n const info = getComponentInfoById(compId)\n const bit = getOrRegisterComponentBit(state, info)\n setBit(withMask, bit)\n }\n for (const compId of q.any) {\n const info = getComponentInfoById(compId)\n const bit = getOrRegisterComponentBit(state, info)\n setBit(anyMask, bit)\n }\n for (const compId of q.none) {\n const info = getComponentInfoById(compId)\n const bit = getOrRegisterComponentBit(state, info)\n setBit(noneMask, bit)\n }\n\n const bundle: QueryMaskBundle = {\n withMask,\n anyMask,\n noneMask,\n anyHasBits: !isMaskZero(anyMask),\n }\n state.queryMasks.set(q.id, bundle)\n\n state.queries[q.id] = q\n state.queryArchetypeCache[q.id] = null\n state.queryArchetypeStamp[q.id] = -1\n\n // Build bit → queries index for fast reactive lookup\n const involvedBits: number[] = [\n ...listBits(withMask),\n ...listBits(anyMask),\n ...listBits(noneMask),\n ]\n for (const b of involvedBits) {\n let s = state.bitToQueries.get(b)\n if (!s) {\n s = new Set<number>()\n state.bitToQueries.set(b, s)\n }\n s.add(q.id)\n }\n\n // Initialize reactive buffer for enter/exit queries\n if (q.reactiveKind !== 'normal') {\n if (!state.reactiveBuffers.has(q.id)) {\n state.reactiveBuffers.set(q.id, { entered: [], exited: [] })\n }\n // Also register the source query so recordEntityMaskChange will see it\n if (q.sourceQuery) ensureQueryRegistered(state, q.sourceQuery)\n }\n}\n\nfunction getQueryArchetypes(state: WorldState, q: QueryInternal): number[] {\n ensureQueryRegistered(state, q)\n if (state.queryArchetypeCache[q.id] && state.queryArchetypeStamp[q.id] === state.queryVersion) {\n return state.queryArchetypeCache[q.id]!\n }\n const bundle = state.queryMasks.get(q.id)!\n const words = state.options.maskWordCount\n const list: number[] = []\n for (let i = 0; i < state.archetypes.length; i++) {\n const arch = state.archetypes[i]!\n if (\n matches(arch.mask, bundle.withMask, bundle.anyMask, bundle.noneMask, bundle.anyHasBits, words)\n ) {\n list.push(i)\n }\n }\n state.queryArchetypeCache[q.id] = list\n state.queryArchetypeStamp[q.id] = state.queryVersion\n return list\n}\n\nexport function queryArchetypes(world: World, query: Query): readonly Archetype[] {\n const state = getWorldState(world)\n const q = query as QueryInternal\n const ids = getQueryArchetypes(state, q)\n const out: Archetype[] = []\n for (const id of ids) {\n const arch = state.archetypes[id]!\n out.push({ id: arch.id, mask: Array.from(arch.mask), size: arch.size })\n }\n return out\n}\n\nexport function runQuery(world: World, query: Query): readonly EntityId[] {\n const state = getWorldState(world)\n const q = query as QueryInternal\n const out: EntityId[] = []\n if (q.reactiveKind === 'enter') {\n const buf = state.reactiveBuffers.get(q.id)\n if (buf) {\n for (const e of buf.entered) out.push(e as EntityId)\n buf.entered.length = 0\n }\n return out\n }\n if (q.reactiveKind === 'exit') {\n const buf = state.reactiveBuffers.get(q.id)\n if (buf) {\n for (const e of buf.exited) out.push(e as EntityId)\n buf.exited.length = 0\n }\n return out\n }\n const archIds = getQueryArchetypes(state, q)\n for (const id of archIds) {\n const arch = state.archetypes[id]!\n for (let r = 0; r < arch.size; r++) {\n out.push(arch.entities[r] as EntityId)\n }\n }\n return out\n}\n\nexport function* iterQuery(world: World, query: Query): IterableIterator<EntityId> {\n const state = getWorldState(world)\n const q = query as QueryInternal\n if (q.reactiveKind !== 'normal') {\n const buf = state.reactiveBuffers.get(q.id)\n if (!buf) return\n const src = q.reactiveKind === 'enter' ? buf.entered : buf.exited\n for (const e of src) yield e as EntityId\n src.length = 0\n return\n }\n const archIds = getQueryArchetypes(state, q)\n for (const id of archIds) {\n const arch = state.archetypes[id]!\n for (let r = 0; r < arch.size; r++) {\n yield arch.entities[r] as EntityId\n }\n }\n}\n\nexport function forEachEntity(\n world: World,\n query: Query,\n fn: (eid: EntityId, ...cols: any[]) => void,\n): void {\n const state = getWorldState(world)\n const q = query as QueryInternal\n\n if (q.reactiveKind !== 'normal') {\n const buf = state.reactiveBuffers.get(q.id)\n if (!buf) return\n const src = q.reactiveKind === 'enter' ? buf.entered : buf.exited\n if (src.length === 0) return\n const cols = buildColumnViews(state, q)\n for (let i = 0; i < src.length; i++) {\n const e = src[i] as EntityId\n callWithCols(fn, e, cols)\n }\n src.length = 0\n return\n }\n\n ensureQueryRegistered(state, q)\n const archIds = getQueryArchetypes(state, q)\n const cols = buildColumnViews(state, q)\n for (const id of archIds) {\n const arch = state.archetypes[id]!\n const ents = arch.entities\n const n = arch.size\n for (let r = 0; r < n; r++) {\n callWithCols(fn, ents[r] as EntityId, cols)\n }\n }\n}\n\nfunction callWithCols(\n fn: (eid: EntityId, ...cols: any[]) => void,\n eid: EntityId,\n cols: any[],\n): void {\n // Specialise for low arities to avoid spread allocation.\n switch (cols.length) {\n case 0:\n fn(eid)\n break\n case 1:\n fn(eid, cols[0])\n break\n case 2:\n fn(eid, cols[0], cols[1])\n break\n case 3:\n fn(eid, cols[0], cols[1], cols[2])\n break\n case 4:\n fn(eid, cols[0], cols[1], cols[2], cols[3])\n break\n case 5:\n fn(eid, cols[0], cols[1], cols[2], cols[3], cols[4])\n break\n default:\n fn(eid, ...cols)\n }\n}\n\nfunction buildColumnViews(state: WorldState, q: QueryInternal): any[] {\n const out: any[] = []\n for (const comp of q.columnViewCache) {\n const info = getComponentInfo(comp)\n const bit = state.componentBitFor.get(info.id)\n if (bit === undefined) {\n out.push(undefined)\n continue\n }\n const storage = state.componentStorageByBit[bit]\n if (!storage) {\n out.push(undefined)\n continue\n }\n if (storage.kind === 'soa') out.push(storage.soa)\n else if (storage.kind === 'aos') out.push(storage.aos)\n else out.push(true) // tag\n }\n return out\n}\n\n// --- Reactive query updates (called from migration code) ---\n\nexport function recordEntityMaskChange(\n state: WorldState,\n eid: EntityId,\n changedBit: number,\n prevMask: Uint32Array,\n nextMask: Uint32Array,\n): void {\n // Lazy-register any reactive queries (and their sources) so we can correctly\n // determine match transitions even if the user only ever called enterQuery/exitQuery.\n for (const q of moduleQueryCache.values()) {\n if (q.reactiveKind === 'normal') continue\n if (q.sourceQuery && state.queries[q.sourceQuery.id] !== q.sourceQuery) {\n ensureQueryRegistered(state, q.sourceQuery)\n }\n }\n\n const involved = state.bitToQueries.get(changedBit)\n if (!involved) return\n const words = state.options.maskWordCount\n for (const qid of involved) {\n const q = state.queries[qid]\n if (!q) continue\n if (q.reactiveKind !== 'normal') continue\n const bundle = state.queryMasks.get(qid)\n if (!bundle) continue\n const wasMatch = matches(\n prevMask,\n bundle.withMask,\n bundle.anyMask,\n bundle.noneMask,\n bundle.anyHasBits,\n words,\n )\n const isMatch = matches(\n nextMask,\n bundle.withMask,\n bundle.anyMask,\n bundle.noneMask,\n bundle.anyHasBits,\n words,\n )\n if (!wasMatch && isMatch) {\n pushReactive(state, qid, 'enter', eid)\n } else if (wasMatch && !isMatch) {\n pushReactive(state, qid, 'exit', eid)\n }\n }\n}\n\nfunction pushReactive(\n state: WorldState,\n queryId: number,\n kind: 'enter' | 'exit',\n eid: EntityId,\n): void {\n // Walk the module cache (not just state.queries) so reactive variants that\n // haven't been registered with this world yet still receive events.\n for (const r of moduleQueryCache.values()) {\n if (r.sourceQueryId !== queryId) continue\n if (r.reactiveKind !== kind) continue\n // Lazily register the reactive query in this world so subsequent reads can find it\n ensureQueryRegistered(state, r)\n const buf = ensureReactiveBuffer(state, r.id)\n if (kind === 'enter') buf.entered.push(eid as number)\n else buf.exited.push(eid as number)\n }\n}\n\nfunction ensureReactiveBuffer(state: WorldState, qid: number): ReactiveBuffer {\n let buf = state.reactiveBuffers.get(qid)\n if (!buf) {\n buf = { entered: [], exited: [] }\n state.reactiveBuffers.set(qid, buf)\n }\n return buf\n}\n\n// --- Helpers ---\n\nfunction getComponentInfoById(componentId: number): ComponentInfo {\n // We need access to the component registry's lookup by id. Re-import dynamically to avoid cycles.\n const info = lazyGetComponentInfo(componentId)\n if (!info) throw new Error(`aiecsjs: component id ${componentId} not registered`)\n return info\n}\n\nlet _getComponentInfoFn: ((id: number) => ComponentInfo | undefined) | null = null\nexport function registerComponentLookup(fn: (id: number) => ComponentInfo | undefined): void {\n _getComponentInfoFn = fn\n}\nfunction lazyGetComponentInfo(id: number): ComponentInfo | undefined {\n return _getComponentInfoFn ? _getComponentInfoFn(id) : undefined\n}\n\nexport function _resetQueryRegistry_FOR_TESTS_ONLY(): void {\n moduleQueryCache.clear()\n nextQueryId = 1\n}\n","// Shared type definitions for aiecsjs internals.\n// Public-facing types are re-exported from src/index.ts.\n\nexport type EntityId = number & { readonly __brand: 'EntityId' }\n\nexport const Types = {\n i8: 'i8',\n u8: 'u8',\n i16: 'i16',\n u16: 'u16',\n i32: 'i32',\n u32: 'u32',\n f32: 'f32',\n f64: 'f64',\n eid: 'eid',\n bool: 'bool',\n} as const\n\nexport type SoAFieldType =\n | 'i8'\n | 'u8'\n | 'i16'\n | 'u16'\n | 'i32'\n | 'u32'\n | 'f32'\n | 'f64'\n | 'eid'\n | 'bool'\n\nexport type SoAFieldDecl = SoAFieldType | readonly [SoAFieldType, number]\nexport type SoASchema = Readonly<Record<string, SoAFieldDecl>>\n\nexport interface SoAComponent<S extends SoASchema = SoASchema> {\n readonly __kind: 'soa'\n readonly __id: number\n readonly __schema: S\n}\n\nexport interface AoSComponent<T = unknown> {\n readonly __kind: 'aos'\n readonly __id: number\n readonly __factory: () => T\n}\n\nexport interface TagComponent {\n readonly __kind: 'tag'\n readonly __id: number\n}\n\nexport type ComponentLike = SoAComponent<any> | AoSComponent<any> | TagComponent\n\nexport type ColumnArray =\n | Int8Array\n | Uint8Array\n | Int16Array\n | Uint16Array\n | Int32Array\n | Uint32Array\n | Float32Array\n | Float64Array\n\nexport interface SoAColumns {\n [field: string]: ColumnArray\n}\n\nexport type ComponentView<C extends ComponentLike> = C extends SoAComponent<infer _S>\n ? SoAColumns\n : C extends AoSComponent<infer T>\n ? T | undefined\n : C extends TagComponent\n ? boolean\n : never\n\nexport type ComponentInit<C extends ComponentLike> = C extends SoAComponent<infer _S>\n ? Record<string, unknown>\n : C extends AoSComponent<infer T>\n ? Partial<T>\n : undefined\n\nexport interface QueryDescriptor {\n all?: ComponentLike[]\n any?: ComponentLike[]\n none?: ComponentLike[]\n}\n\nexport interface Query {\n readonly id: number\n readonly mask: ReadonlyArray<number>\n}\n\nexport interface Archetype {\n readonly id: number\n readonly mask: ReadonlyArray<number>\n readonly size: number\n}\n\nexport interface WorldOptions {\n initialCapacity?: number\n maxEntities?: number\n indexBits?: number\n generationBits?: number\n buffer?: SharedArrayBuffer\n bufferByteOffset?: number\n}\n\nexport interface World {\n readonly id: number\n readonly capacity: number\n readonly version: string\n}\n\nexport type System<W extends World = World, Ctx = unknown> = (world: W, ctx: Ctx) => W\n\n// --- Internal-only types ---\n\nexport interface ResolvedWorldOptions {\n initialCapacity: number\n maxEntities: number\n indexBits: number\n generationBits: number\n maxComponents: number\n maskWordCount: number\n buffer: SharedArrayBuffer | null\n bufferByteOffset: number\n}\n\nexport interface FieldInfo {\n name: string\n type: SoAFieldType\n vectorLen: number // 1 for scalar\n ctor: TypedArrayConstructor\n bytesPerElement: number\n}\n\nexport type TypedArrayConstructor =\n | Int8ArrayConstructor\n | Uint8ArrayConstructor\n | Int16ArrayConstructor\n | Uint16ArrayConstructor\n | Int32ArrayConstructor\n | Uint32ArrayConstructor\n | Float32ArrayConstructor\n | Float64ArrayConstructor\n\nexport interface ComponentInfo {\n id: number\n kind: 'soa' | 'aos' | 'tag'\n schema: SoASchema | null\n fields: FieldInfo[]\n factory: (() => unknown) | null\n}\n\nexport interface WorldComponentStorage {\n // For each component bit in this world: storage backed by a column map (SoA), object array (AoS), or null (tag)\n kind: 'soa' | 'aos' | 'tag'\n componentId: number\n bit: number\n // SoA: field name → TypedArray of size `worldCapacity`\n soa?: SoAColumns\n // AoS: per-entity object array, sparse, indexed by eid; undefined for unowned\n aos?: (unknown | undefined)[]\n}\n\nexport interface ArchetypeState {\n id: number\n mask: Uint32Array\n size: number\n capacity: number\n entities: Uint32Array // packed eids in row order\n entityRow: Map<number, number> // eid → row (small archetype-local lookup)\n componentBits: number[] // sorted\n edgeAdd: Int32Array // [bit] → archetype id; -1 unknown\n edgeRemove: Int32Array // [bit] → archetype id; -1 unknown\n}\n\nexport interface QueryInternal extends Query {\n id: number\n all: number[]\n any: number[]\n none: number[]\n // Cache of column references per matched archetype (per query-call)\n columnViewCache: ComponentLike[] // the requested components in their declared order\n reactiveKind: 'normal' | 'enter' | 'exit'\n sourceQueryId: number // -1 for normal\n sourceQuery: QueryInternal | null // back-ref for reactive registration\n}\n\n// Per-world resolved bitmasks for a query. Component bits are assigned per\n// world, so the masks must live in WorldState — keeping them on the shared\n// QueryInternal would silently cross-contaminate worlds whose component\n// registration order differs.\nexport interface QueryMaskBundle {\n withMask: Uint32Array\n anyMask: Uint32Array\n noneMask: Uint32Array\n anyHasBits: boolean\n}\n\nexport interface ReactiveBuffer {\n entered: number[]\n exited: number[]\n}\n\nexport type ObserverEvent = 'add' | 'remove' | 'set'\n\nexport interface ObserverEntry {\n event: ObserverEvent\n componentBit: number // -1 means \"any component\" (used by query observe)\n queryId: number // -1 means component-only\n handler: (eid: EntityId, value?: unknown) => void\n}\n\nexport interface CommandBufferState {\n worldId: number\n ops: CommandOp[]\n nextPlaceholder: number\n flushing: boolean\n}\n\nexport type CommandOp =\n | { kind: 'create'; placeholder: number }\n | { kind: 'add'; eid: EntityId; component: ComponentLike; initial?: unknown }\n | { kind: 'remove'; eid: EntityId; component: ComponentLike }\n | { kind: 'destroy'; eid: EntityId }\n\nexport interface CommandBuffer {\n add<C extends ComponentLike>(eid: EntityId, component: C, initial?: ComponentInit<C>): void\n remove<C extends ComponentLike>(eid: EntityId, component: C): void\n destroy(eid: EntityId): void\n create(): EntityId\n}\n\nexport interface WorldMeta {\n magic: number\n formatVersion: number\n aiecsjsVersion: string\n indexBits: number\n generationBits: number\n maxComponents: number\n maskWordCount: number\n capacity: number\n componentSchemas: Array<{ id: number; kind: 'soa' | 'aos' | 'tag'; schema: SoASchema | null }>\n}\n\nexport interface TransferableSnapshot {\n buffer: SharedArrayBuffer\n meta: WorldMeta\n}\n\nexport interface SerializeOptions {\n components?: ComponentLike[]\n}\n\nexport interface DeserializeOptions {\n components?: ComponentLike[]\n onUnknownVersion?: 'throw' | 'best-effort'\n}\n\nexport interface WorldSnapshot {\n version: string\n capacity: number\n entities: Array<{\n eid: number\n components: Array<{\n kind: 'soa' | 'aos' | 'tag'\n id: number\n data: unknown\n }>\n }>\n}\n\nexport interface DeltaSerializer {\n capture(): Uint8Array\n apply(world: World, delta: Uint8Array): void\n reset(): void\n}\n\nexport interface Relation<T = void> {\n readonly __kind: 'relation'\n readonly __id: number\n readonly __exclusive: boolean\n readonly __hasData: boolean\n}\n\nexport interface RelationStorage {\n rel: Relation<any>\n exclusive: Int32Array | null // [srcEid] → tgtEid; -1 means none\n outgoing: Map<number, number[]> // srcEid → tgtEid[]\n data: Map<number, Map<number, unknown>> // srcEid → (tgtEid → data); nested to stay correct across capacity growth\n}\n\nexport interface WorldState {\n // --- public view ---\n readonly id: number\n capacity: number\n readonly version: string\n\n // --- options ---\n options: ResolvedWorldOptions\n\n // --- entity allocation ---\n size: number // alive count\n nextFreshIndex: number // never-used index\n freeList: number[] // recycled indices\n generations: Uint8Array | Uint16Array // [eid] → version\n destroyed: boolean\n\n // --- component registry (per-world) ---\n componentBitFor: Map<number, number> // global component id → bit pos in this world\n componentInfoByBit: (ComponentInfo | null)[] // bit pos → ComponentInfo\n componentStorageByBit: (WorldComponentStorage | null)[]\n nextComponentBit: number\n\n // --- sparse entity state ---\n entityArchetype: Uint32Array // [eid] → archetype id (0 = unattached)\n // entityMask flattened: word w of mask of eid is at entityMask[eid * maskWordCount + w]\n entityMask: Uint32Array\n\n // --- archetype registry ---\n archetypes: ArchetypeState[]\n archetypeByMaskHash: Map<string, number>\n queryVersion: number\n\n // --- query cache ---\n queries: QueryInternal[] // by id\n queryMasks: Map<number, QueryMaskBundle> // queryId → per-world resolved bitmasks\n queryArchetypeCache: (number[] | null)[]\n queryArchetypeStamp: number[]\n bitToQueries: Map<number, Set<number>> // bit → queryIds that mention this bit\n\n // --- reactive query state ---\n reactiveBuffers: Map<number, ReactiveBuffer> // queryId → { entered, exited }\n\n // --- observers ---\n observers: ObserverEntry[]\n\n // --- relations ---\n relationStorage: Map<number, RelationStorage> // relation id → storage\n\n // --- worker / SAB ---\n sab: SharedArrayBuffer | null\n readOnly: boolean\n}\n","import type { System, World } from './types.js'\n\nexport function pipe<W extends World = World, Ctx = unknown>(\n ...systems: System<W, Ctx>[]\n): System<W, Ctx> {\n if (systems.length === 0) return (w: W) => w\n if (systems.length === 1) return systems[0]!\n return (world: W, ctx: Ctx) => {\n let w = world\n for (const s of systems) w = s(w, ctx)\n return w\n }\n}\n","// aiecsjs — public root entry.\n// Re-exports the core API and wires up the lazy cross-module references.\n\nexport { VERSION } from './version.js'\n\nimport {\n getComponentByInternalId,\n registerMaskChangeDispatch,\n registerObserverDispatch,\n} from './internal/component.js'\nimport { registerObserversAPI, registerRelationsCleanup } from './internal/entity.js'\nimport { recordEntityMaskChange, registerComponentLookup } from './internal/query.js'\nimport type { EntityId, WorldState } from './internal/types.js'\n\n// Wire query → component lookup\nregisterComponentLookup((id) => getComponentByInternalId(id))\n\n// Wire component mask-change → query reactive update\nregisterMaskChangeDispatch((state, eid, bit, prev, next) => {\n recordEntityMaskChange(state, eid, bit, prev, next)\n})\n\n// Observer dispatch is registered lazily by observers.ts on first import.\n// Relations cleanup is registered lazily by relations.ts on first import.\n\n// --- Type re-exports ---\nexport type {\n EntityId,\n World,\n WorldOptions,\n System,\n SoAComponent,\n AoSComponent,\n TagComponent,\n ComponentLike,\n ComponentInit,\n ComponentView,\n SoAColumns,\n SoASchema,\n SoAFieldType,\n SoAFieldDecl,\n Query,\n QueryDescriptor,\n Archetype,\n} from './internal/types.js'\n\n// --- World ---\nexport {\n createWorld,\n destroyWorld,\n resetWorld,\n getWorldSize,\n getWorldCapacity,\n isWorld,\n} from './internal/world.js'\n\n// `disposeWorld` is the new preferred name (added 0.2.0). It is the same\n// function as `destroyWorld`, exported under a name that aligns with the ai*js\n// ecosystem `dispose()` convention (aifsmjs Runtime, aibridgejs Bridge).\n//\n// `destroyWorld` is the original 0.1.x export. It is now deprecated as of 0.2.0\n// and is scheduled for removal in 1.0. New code should import `disposeWorld`.\nexport { destroyWorld as disposeWorld } from './internal/world.js'\n\n// --- Entity ---\nexport {\n createEntity,\n destroyEntity,\n entityExists,\n getEntityIndex,\n getEntityGeneration,\n packEntity,\n isEntity,\n} from './internal/entity.js'\n\n// --- Component ---\nexport {\n defineComponent,\n defineTag,\n defineObjectComponent,\n addComponent,\n removeComponent,\n hasComponent,\n getComponent,\n setComponent,\n} from './internal/component.js'\n\nexport { Types } from './internal/types.js'\n\n// --- Query ---\nexport {\n defineQuery,\n runQuery,\n iterQuery,\n forEachEntity,\n enterQuery,\n exitQuery,\n queryArchetypes,\n} from './internal/query.js'\n\n// --- System ---\nexport { pipe } from './internal/pipe.js'\n\n// --- Utility ---\nexport const IS_SAB_SUPPORTED: boolean = typeof SharedArrayBuffer !== 'undefined'\n"]}
1
+ {"version":3,"sources":["../src/internal/types.ts","../src/internal/pipe.ts","../src/ref.ts","../src/index.ts"],"names":["Types","pipe","systems","w","world","ctx","s","EntityNotAliveError","eid","refOf","entity","state","getWorldState","isAliveInternal","deref","ref","idx","unpackIdx","archId","arch","storedGen","refGen","unpackGen","aliveRef","registerComponentLookup","id","getComponentByInternalId","registerMaskChangeDispatch","bit","prev","next","recordEntityMaskChange","IS_SAB_SUPPORTED"],"mappings":"8rBAKO,IAAMA,CAAAA,CAAQ,CACnB,EAAA,CAAI,IAAA,CACJ,EAAA,CAAI,KACJ,GAAA,CAAK,KAAA,CACL,GAAA,CAAK,KAAA,CACL,GAAA,CAAK,KAAA,CACL,IAAK,KAAA,CACL,GAAA,CAAK,KAAA,CACL,GAAA,CAAK,KAAA,CACL,GAAA,CAAK,KAAA,CACL,IAAA,CAAM,MACR,ECdO,SAASC,CAAAA,CAAAA,GACXC,CAAAA,CACa,CAChB,OAAIA,CAAAA,CAAQ,MAAA,GAAW,CAAA,CAAWC,CAAAA,EAASA,CAAAA,CACvCD,CAAAA,CAAQ,SAAW,CAAA,CAAUA,CAAAA,CAAQ,CAAC,CAAA,CACnC,CAACE,CAAAA,CAAUC,IAAa,CAC7B,IAAIF,CAAAA,CAAIC,CAAAA,CACR,IAAA,IAAWE,CAAAA,IAAKJ,CAAAA,CAASC,CAAAA,CAAIG,CAAAA,CAAEH,CAAAA,CAAGE,CAAG,CAAA,CACrC,OAAOF,CACT,CACF,CC8BO,IAAMI,CAAAA,CAAN,cAAkC,KAAM,CACpC,IACT,WAAA,CAAYC,CAAAA,CAAa,CACvB,KAAA,CAAM,CAAA,gBAAA,EAAmBA,CAAG,eAAe,CAA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CAAAA,CAAI,EACb,CAQO,SAASQ,CAAAA,CAAsBnB,CAAAA,CAAcW,CAAAA,CAA4B,CAC9E,OAAOD,CAAAA,CAAMV,CAAAA,CAAOW,CAAG,CAAA,GAAM,IAC/B,CCtGAS,GAAAA,CAAyBC,CAAAA,EAAOC,CAAAA,CAAyBD,CAAE,CAAC,CAAA,CAG5DE,CAAAA,CAA2B,CAAChB,CAAAA,CAAOH,CAAAA,CAAKoB,CAAAA,CAAKC,CAAAA,CAAMC,CAAAA,GAAS,CAC1DC,CAAAA,CAAuBpB,CAAAA,CAAOH,CAAAA,CAAKoB,CAAAA,CAAKC,CAAAA,CAAMC,CAAI,EACpD,CAAC,CAAA,CAoFM,IAAME,EAAAA,CAA4B,OAAO,iBAAA,CAAsB","file":"index.js","sourcesContent":["// Shared type definitions for aiecsjs internals.\n// Public-facing types are re-exported from src/index.ts.\n\nexport type EntityId = number & { readonly __brand: 'EntityId' }\n\nexport const Types = {\n i8: 'i8',\n u8: 'u8',\n i16: 'i16',\n u16: 'u16',\n i32: 'i32',\n u32: 'u32',\n f32: 'f32',\n f64: 'f64',\n eid: 'eid',\n bool: 'bool',\n} as const\n\nexport type SoAFieldType =\n | 'i8'\n | 'u8'\n | 'i16'\n | 'u16'\n | 'i32'\n | 'u32'\n | 'f32'\n | 'f64'\n | 'eid'\n | 'bool'\n\nexport type SoAFieldDecl = SoAFieldType | readonly [SoAFieldType, number]\nexport type SoASchema = Readonly<Record<string, SoAFieldDecl>>\n\nexport interface SoAComponent<S extends SoASchema = SoASchema> {\n readonly __kind: 'soa'\n readonly __id: number\n readonly __schema: S\n}\n\nexport interface AoSComponent<T = unknown> {\n readonly __kind: 'aos'\n readonly __id: number\n readonly __factory: () => T\n}\n\nexport interface TagComponent {\n readonly __kind: 'tag'\n readonly __id: number\n}\n\nexport type ComponentLike = SoAComponent<any> | AoSComponent<any> | TagComponent\n\nexport type ColumnArray =\n | Int8Array\n | Uint8Array\n | Int16Array\n | Uint16Array\n | Int32Array\n | Uint32Array\n | Float32Array\n | Float64Array\n\nexport interface SoAColumns {\n [field: string]: ColumnArray\n}\n\nexport type ComponentView<C extends ComponentLike> = C extends SoAComponent<infer _S>\n ? SoAColumns\n : C extends AoSComponent<infer T>\n ? T | undefined\n : C extends TagComponent\n ? boolean\n : never\n\nexport type ComponentInit<C extends ComponentLike> = C extends SoAComponent<infer _S>\n ? Record<string, unknown>\n : C extends AoSComponent<infer T>\n ? Partial<T>\n : undefined\n\nexport interface QueryDescriptor {\n all?: ComponentLike[]\n any?: ComponentLike[]\n none?: ComponentLike[]\n}\n\nexport interface Query {\n readonly id: number\n readonly mask: ReadonlyArray<number>\n}\n\nexport interface Archetype {\n readonly id: number\n readonly mask: ReadonlyArray<number>\n readonly size: number\n}\n\nexport interface WorldOptions {\n initialCapacity?: number\n maxEntities?: number\n indexBits?: number\n generationBits?: number\n buffer?: SharedArrayBuffer\n bufferByteOffset?: number\n}\n\nexport interface World {\n readonly id: number\n readonly capacity: number\n readonly version: string\n}\n\nexport type System<W extends World = World, Ctx = unknown> = (world: W, ctx: Ctx) => W\n\n// --- Internal-only types ---\n\nexport interface ResolvedWorldOptions {\n initialCapacity: number\n maxEntities: number\n indexBits: number\n generationBits: number\n indexMask: number\n generationMask: number\n maxComponents: number\n maskWordCount: number\n buffer: SharedArrayBuffer | null\n bufferByteOffset: number\n}\n\nexport interface FieldInfo {\n name: string\n type: SoAFieldType\n vectorLen: number // 1 for scalar\n ctor: TypedArrayConstructor\n bytesPerElement: number\n}\n\nexport type TypedArrayConstructor =\n | Int8ArrayConstructor\n | Uint8ArrayConstructor\n | Int16ArrayConstructor\n | Uint16ArrayConstructor\n | Int32ArrayConstructor\n | Uint32ArrayConstructor\n | Float32ArrayConstructor\n | Float64ArrayConstructor\n\nexport interface ComponentInfo {\n id: number\n kind: 'soa' | 'aos' | 'tag'\n schema: SoASchema | null\n fields: FieldInfo[]\n factory: (() => unknown) | null\n}\n\nexport interface WorldComponentStorage {\n // For each component bit in this world: storage backed by a column map (SoA), object array (AoS), or null (tag)\n kind: 'soa' | 'aos' | 'tag'\n componentId: number\n bit: number\n // SoA: field name → TypedArray of size `worldCapacity`\n soa?: SoAColumns\n // AoS: per-entity object array, sparse, indexed by eid; undefined for unowned\n aos?: (unknown | undefined)[]\n}\n\nexport interface ArchetypeState {\n id: number\n mask: Uint32Array\n size: number\n capacity: number\n entities: Uint32Array // packed eids in row order\n entityRow: Map<number, number> // eid → row (small archetype-local lookup)\n componentBits: number[] // sorted\n edgeAdd: Int32Array // [bit] → archetype id; -1 unknown\n edgeRemove: Int32Array // [bit] → archetype id; -1 unknown\n}\n\nexport interface QueryInternal extends Query {\n id: number\n all: number[]\n any: number[]\n none: number[]\n // Cache of column references per matched archetype (per query-call)\n columnViewCache: ComponentLike[] // the requested components in their declared order\n reactiveKind: 'normal' | 'enter' | 'exit'\n sourceQueryId: number // -1 for normal\n sourceQuery: QueryInternal | null // back-ref for reactive registration\n}\n\n// Per-world resolved bitmasks for a query. Component bits are assigned per\n// world, so the masks must live in WorldState — keeping them on the shared\n// QueryInternal would silently cross-contaminate worlds whose component\n// registration order differs.\nexport interface QueryMaskBundle {\n withMask: Uint32Array\n anyMask: Uint32Array\n noneMask: Uint32Array\n anyHasBits: boolean\n}\n\nexport interface ReactiveBuffer {\n entered: number[]\n exited: number[]\n}\n\nexport type ObserverEvent = 'add' | 'remove' | 'set'\n\nexport interface ObserverEntry {\n event: ObserverEvent\n componentBit: number // -1 means \"any component\" (used by query observe)\n queryId: number // -1 means component-only\n handler: (eid: EntityId, value?: unknown) => void\n}\n\nexport interface CommandBufferState {\n worldId: number\n ops: CommandOp[]\n nextPlaceholder: number\n flushing: boolean\n}\n\nexport type CommandOp =\n | { kind: 'create'; placeholder: number }\n | { kind: 'add'; eid: EntityId; component: ComponentLike; initial?: unknown }\n | { kind: 'remove'; eid: EntityId; component: ComponentLike }\n | { kind: 'destroy'; eid: EntityId }\n\nexport interface CommandBuffer {\n add<C extends ComponentLike>(eid: EntityId, component: C, initial?: ComponentInit<C>): void\n remove<C extends ComponentLike>(eid: EntityId, component: C): void\n destroy(eid: EntityId): void\n create(): EntityId\n}\n\nexport interface WorldMeta {\n magic: number\n formatVersion: number\n aiecsjsVersion: string\n indexBits: number\n generationBits: number\n maxComponents: number\n maskWordCount: number\n capacity: number\n componentSchemas: Array<{ id: number; kind: 'soa' | 'aos' | 'tag'; schema: SoASchema | null }>\n}\n\nexport interface TransferableSnapshot {\n buffer: SharedArrayBuffer\n meta: WorldMeta\n}\n\nexport interface SerializeOptions {\n components?: ComponentLike[]\n}\n\nexport interface DeserializeOptions {\n components?: ComponentLike[]\n onUnknownVersion?: 'throw' | 'best-effort'\n}\n\nexport interface WorldSnapshot {\n version: string\n capacity: number\n entities: Array<{\n eid: number\n components: Array<{\n kind: 'soa' | 'aos' | 'tag'\n id: number\n data: unknown\n }>\n }>\n}\n\nexport interface DeltaSerializer {\n capture(): Uint8Array\n apply(world: World, delta: Uint8Array): void\n reset(): void\n}\n\nexport interface Relation<T = void> {\n readonly __kind: 'relation'\n readonly __id: number\n readonly __exclusive: boolean\n readonly __hasData: boolean\n}\n\nexport interface RelationStorage {\n rel: Relation<any>\n exclusive: Int32Array | null // [srcEid] → tgtEid; -1 means none\n outgoing: Map<number, number[]> // srcEid → tgtEid[]\n data: Map<number, Map<number, unknown>> // srcEid → (tgtEid → data); nested to stay correct across capacity growth\n}\n\nexport interface WorldState {\n // --- public view ---\n readonly id: number\n capacity: number\n readonly version: string\n\n // --- options ---\n options: ResolvedWorldOptions\n\n // --- entity allocation ---\n size: number // alive count\n nextFreshIndex: number // never-used index\n freeList: number[] // recycled indices\n generations: Uint8Array | Uint16Array // [eid] → version\n destroyed: boolean\n\n // --- component registry (per-world) ---\n componentBitFor: Map<number, number> // global component id → bit pos in this world\n componentInfoByBit: (ComponentInfo | null)[] // bit pos → ComponentInfo\n componentStorageByBit: (WorldComponentStorage | null)[]\n nextComponentBit: number\n\n // --- sparse entity state ---\n entityArchetype: Uint32Array // [eid] → archetype id (0 = unattached)\n // entityMask flattened: word w of mask of eid is at entityMask[eid * maskWordCount + w]\n entityMask: Uint32Array\n\n // --- archetype registry ---\n archetypes: ArchetypeState[]\n archetypeByMaskHash: Map<string, number>\n queryVersion: number\n\n // --- query cache ---\n queries: QueryInternal[] // by id\n queryMasks: Map<number, QueryMaskBundle> // queryId → per-world resolved bitmasks\n queryArchetypeCache: (number[] | null)[]\n queryArchetypeStamp: number[]\n bitToQueries: Map<number, Set<number>> // bit → queryIds that mention this bit\n\n // --- reactive query state ---\n reactiveBuffers: Map<number, ReactiveBuffer> // queryId → { entered, exited }\n\n // --- observers ---\n observers: ObserverEntry[]\n\n // --- relations ---\n relationStorage: Map<number, RelationStorage> // relation id → storage\n\n // --- worker / SAB ---\n sab: SharedArrayBuffer | null\n readOnly: boolean\n}\n","import type { System, World } from './types.js'\n\nexport function pipe<W extends World = World, Ctx = unknown>(\n ...systems: System<W, Ctx>[]\n): System<W, Ctx> {\n if (systems.length === 0) return (w: W) => w\n if (systems.length === 1) return systems[0]!\n return (world: W, ctx: Ctx) => {\n let w = world\n for (const s of systems) w = s(w, ctx)\n return w\n }\n}\n","// aiecsjs/ref — ABA-safe entity references.\n//\n// EntityRef<T> wraps a packed EntityId with a world identity check so that\n// stale references (pointing at a recycled slot with a different generation)\n// safely return null rather than silently accessing the wrong entity.\n//\n// EntityRef is in-memory only. Do not pass across worker boundaries or persist\n// to disk. The packed id field has meaning only within the world that issued it.\n// Generation counters reset on resetWorld / deserializeWorld / adoptSnapshot.\n\nimport { isAliveInternal, unpackGen, unpackIdx } from './internal/entity.js'\nimport type { EntityId, World } from './internal/types.js'\nimport { getWorldState } from './internal/world.js'\n\n/**\n * ABA-safe entity reference.\n *\n * Holds the packed EntityId and the id of the world that issued it.\n * Use `deref(world, ref)` to validate and retrieve the live entity id.\n *\n * The phantom type `T` allows callers to distinguish reference kinds at the\n * type system level — e.g. `EntityRef<'bullet'>` vs `EntityRef<'player'>` —\n * without any runtime overhead.\n *\n * @example\n * const ref = refOf<'bullet'>(world, e)\n * // later, in a system:\n * const live = deref(world, ref)\n * if (live !== null) {\n * // entity is still alive with the same generation\n * }\n */\nexport interface EntityRef<T = unknown> {\n readonly id: EntityId // packed value (index + generation)\n readonly worldId: number // world.id — guards against cross-world deref\n readonly __phantom?: T // phantom type tag; zero runtime size\n}\n\n/**\n * Thrown by `refOf` when the entity is not alive.\n * `deref` and `aliveRef` never throw — they return null/false.\n */\nexport class EntityNotAliveError extends Error {\n readonly eid: number\n constructor(eid: number) {\n super(`aiecsjs: entity ${eid} is not alive`)\n this.name = 'EntityNotAliveError'\n this.eid = eid\n }\n}\n\n/**\n * Create an ABA-safe reference to a live entity.\n *\n * @throws {EntityNotAliveError} if the entity is not alive (dead, never created, or eid === 0).\n *\n * The returned object is frozen. `id` is the packed EntityId; `worldId` is\n * the world's numeric id used by `deref` to reject cross-world lookups.\n *\n * The function may be called on the hot path — each call returns a new object\n * but performs no allocation beyond that.\n */\nexport function refOf<T = unknown>(world: World, entity: EntityId): EntityRef<T> {\n const state = getWorldState(world)\n if (!isAliveInternal(state, entity as number)) {\n throw new EntityNotAliveError(entity as number)\n }\n return Object.freeze({ id: entity, worldId: state.id }) as EntityRef<T>\n}\n\n/**\n * Resolve a ref to its live EntityId, or return null if stale.\n *\n * Returns null when any of the following hold:\n * 1. `ref.worldId !== state.id` — cross-world ref\n * 2. `getEntityIndex(ref.id) >= state.capacity` — index out-of-bounds\n * 3. `getEntityIndex(ref.id) === 0` — sentinel slot\n * 4. entity is not in any archetype's entityRow (slot released)\n * 5. generation mismatch → ABA: old ref points at recycled slot\n *\n * Never throws.\n */\nexport function deref<T = unknown>(world: World, ref: EntityRef<T>): EntityId | null {\n const state = getWorldState(world)\n\n // Cross-world guard\n if (ref.worldId !== state.id) return null\n\n const eid = ref.id as number\n const idx = unpackIdx(eid, state.options)\n\n // Sentinel and OOB guards\n if (idx <= 0) return null\n if (idx >= state.capacity) return null\n\n // Archetype membership check\n const archId = state.entityArchetype[idx] ?? 0\n const arch = state.archetypes[archId]\n if (!arch) return null\n if (!arch.entityRow.has(ref.id)) return null\n\n // Generation match — the core ABA protection\n const storedGen = state.generations[idx] ?? 0\n const refGen = unpackGen(eid, state.options)\n if (storedGen !== refGen) return null\n\n return ref.id\n}\n\n/**\n * Boolean guard form of `deref`. Equivalent to `deref(world, ref) !== null`.\n * Use in guard clauses when you do not need the resolved EntityId.\n *\n * Never throws.\n */\nexport function aliveRef<T = unknown>(world: World, ref: EntityRef<T>): boolean {\n return deref(world, ref) !== null\n}\n","// aiecsjs — public root entry.\n// Re-exports the core API and wires up the lazy cross-module references.\n\nexport { VERSION } from './version.js'\n\nimport {\n getComponentByInternalId,\n registerMaskChangeDispatch,\n registerObserverDispatch,\n} from './internal/component.js'\nimport { registerObserversAPI, registerRelationsCleanup } from './internal/entity.js'\nimport { recordEntityMaskChange, registerComponentLookup } from './internal/query.js'\nimport type { EntityId, WorldState } from './internal/types.js'\n\n// Wire query → component lookup\nregisterComponentLookup((id) => getComponentByInternalId(id))\n\n// Wire component mask-change → query reactive update\nregisterMaskChangeDispatch((state, eid, bit, prev, next) => {\n recordEntityMaskChange(state, eid, bit, prev, next)\n})\n\n// Observer dispatch is registered lazily by observers.ts on first import.\n// Relations cleanup is registered lazily by relations.ts on first import.\n\n// --- Type re-exports ---\nexport type {\n EntityId,\n World,\n WorldOptions,\n System,\n SoAComponent,\n AoSComponent,\n TagComponent,\n ComponentLike,\n ComponentInit,\n ComponentView,\n SoAColumns,\n SoASchema,\n SoAFieldType,\n SoAFieldDecl,\n Query,\n QueryDescriptor,\n Archetype,\n} from './internal/types.js'\n\n// --- World ---\nexport {\n createWorld,\n destroyWorld,\n resetWorld,\n getWorldSize,\n getWorldCapacity,\n isWorld,\n} from './internal/world.js'\n\n// `disposeWorld` is the new preferred name (added 0.2.0). It is the same\n// function as `destroyWorld`, exported under a name that aligns with the ai*js\n// ecosystem `dispose()` convention (aifsmjs Runtime, aibridgejs Bridge).\n//\n// `destroyWorld` is the original 0.1.x export. It is now deprecated as of 0.2.0\n// and is scheduled for removal in 1.0. New code should import `disposeWorld`.\nexport { destroyWorld as disposeWorld } from './internal/world.js'\n\n// --- Entity ---\nexport {\n createEntity,\n destroyEntity,\n entityExists,\n getEntityIndex,\n getEntityGeneration,\n packEntity,\n isEntity,\n} from './internal/entity.js'\n\n// --- Component ---\nexport {\n defineComponent,\n defineTag,\n defineObjectComponent,\n addComponent,\n removeComponent,\n hasComponent,\n getComponent,\n setComponent,\n} from './internal/component.js'\n\nexport { Types } from './internal/types.js'\n\n// --- Query ---\nexport {\n defineQuery,\n runQuery,\n iterQuery,\n forEachEntity,\n enterQuery,\n exitQuery,\n queryArchetypes,\n} from './internal/query.js'\n\n// --- System ---\nexport { pipe } from './internal/pipe.js'\n\n// --- Utility ---\nexport const IS_SAB_SUPPORTED: boolean = typeof SharedArrayBuffer !== 'undefined'\n\n// --- EntityRef (ABA-safe references) ---\nexport type { EntityRef } from './ref.js'\nexport { refOf, deref, aliveRef, EntityNotAliveError } from './ref.js'\n"]}