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.
- package/CHANGELOG.md +90 -2
- package/README.md +8 -3
- package/README_ZHTW.md +8 -3
- package/STABILITY.md +10 -4
- package/STABILITY_ZHTW.md +10 -3
- package/api.json +568 -100
- package/dist/chunk-37HMYMJG.cjs +2 -0
- package/dist/chunk-37HMYMJG.cjs.map +1 -0
- package/dist/chunk-4RPFOVQC.cjs +2 -0
- package/dist/chunk-4RPFOVQC.cjs.map +1 -0
- package/dist/chunk-AGHSWLNQ.cjs +2 -0
- package/dist/chunk-AGHSWLNQ.cjs.map +1 -0
- package/dist/chunk-FDXCXNZK.js +2 -0
- package/dist/chunk-FDXCXNZK.js.map +1 -0
- package/dist/chunk-L5CMKMIP.js +2 -0
- package/dist/chunk-L5CMKMIP.js.map +1 -0
- package/dist/chunk-QOKIEF7C.js +2 -0
- package/dist/chunk-QOKIEF7C.js.map +1 -0
- package/dist/commands.cjs +1 -1
- package/dist/commands.cjs.map +1 -1
- package/dist/commands.js +1 -1
- package/dist/commands.js.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +87 -4
- package/dist/index.d.ts +87 -4
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/observers.cjs +1 -1
- package/dist/observers.cjs.map +1 -1
- package/dist/observers.d.cts +16 -3
- package/dist/observers.d.ts +16 -3
- package/dist/observers.js +1 -1
- package/dist/observers.js.map +1 -1
- package/dist/relations.cjs +1 -1
- package/dist/relations.cjs.map +1 -1
- package/dist/relations.js +1 -1
- package/dist/relations.js.map +1 -1
- package/dist/serialize.cjs +1 -1
- package/dist/serialize.cjs.map +1 -1
- package/dist/serialize.d.cts +7 -0
- package/dist/serialize.d.ts +7 -0
- package/dist/serialize.js +1 -1
- package/dist/serialize.js.map +1 -1
- package/dist/worker.cjs +1 -1
- package/dist/worker.cjs.map +1 -1
- package/dist/worker.js +1 -1
- package/dist/worker.js.map +1 -1
- package/llms-full.txt +108 -9
- package/package.json +6 -2
package/dist/worker.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/serialize.ts","../src/worker.ts"],"names":["VERSION","createMask","wordCount","setBit","mask","bit","w","testBit","cloneMask","src","out","i","maskHash","m","parts","DEFAULT_OPTIONS","DEFAULT_MAX_COMPONENTS","nextWorldId","worldRegistry","getWorldState","world","state","registerWorld","unregisterWorld","id","isWorldRegistered","resolveOptions","opts","o","indexBits","generationBits","maxComponents","maxByIndex","initialCapacity","maxEntities","createEmptyArchetype","maskWordCount","createWorld","options","resolved","generationCtor","generations","empty","makePublicWorld","destroyWorld","ensureCapacity","needed","newCap","growEntityArrays","genCtor","newGen","newArch","newMask","storage","info","growSoAColumns","soa","fields","f","old","newLen","next","findOrCreateArchetype","key","existing","arch","collectBits","ensureArchetypeCapacity","bits","word","lsb","getOrRegisterComponentBit","readEntityMask","eid","base","writeEntityMask","createEntity","row","entityExists","isAliveInternal","archId","componentInfoById","getComponentInfo","component","addComponent","initial","prevMask","writeInitial","migrateEntity","obj","col","val","arr","factory","inst","target","srcArchId","srcArch","destArchId","destArch","lastRow","moved","newRow","getComponentByInternalId","MAGIC","FORMAT_VERSION","serializeWorld","snapshot","toJSON","packBinary","deserializeWorld","bytes","unpackBinary","fromJSON","entities","components","wi","data","baseI","eidMap","e","comp","handle","getComponentHandle","json","jsonBytes","versionBytes","total","view","off","formatVersion","onUnknown","MAX_FIELD_LEN","verLen","jsonLen","transferableSnapshot","ab","buildMeta","sab","adoptSnapshot","snap","validateMeta","attachWorld","buffer","detachWorld","componentSchemas","meta"],"mappings":"AAAO,IAAMA,EAAU,OAAA,CCEhB,SAASC,CAAAA,CAAWC,CAAAA,CAAgC,CACzD,OAAO,IAAI,WAAA,C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CAAAA,CAAM,EAAE,GAC5BwB,CAAAA,CAAaxB,CAAK,EAEtB,CAEA,SAASqH,CAAAA,CAAUpH,CAAAA,CAA8B,CAC/C,IAAM4H,EAAkD,EAAC,CACzD,IAAA,IAAW3F,CAAAA,IAAQjC,EAAM,kBAAA,CAClBiC,CAAAA,EACL2F,EAAiB,IAAA,CAAK,CAAE,GAAI3F,CAAAA,CAAK,EAAA,CAAI,IAAA,CAAMA,CAAAA,CAAK,KAAM,MAAA,CAAQA,CAAAA,CAAK,MAAO,CAAC,CAAA,CAE7E,OAAO,CACL,KAAA,CAAOkD,CAAAA,CACP,aAAA,CAAe,EACf,cAAA,CAAgBxG,CAAAA,CAChB,UAAWqB,CAAAA,CAAM,OAAA,CAAQ,UACzB,cAAA,CAAgBA,CAAAA,CAAM,OAAA,CAAQ,cAAA,CAC9B,cAAeA,CAAAA,CAAM,OAAA,CAAQ,aAAA,CAC7B,aAAA,CAAeA,EAAM,OAAA,CAAQ,aAAA,CAC7B,QAAA,CAAUA,CAAAA,CAAM,SAChB,gBAAA,CAAA4H,CACF,CACF,CAEA,SAASJ,GAAaK,CAAAA,CAAuB,CAC3C,GAAIA,CAAAA,CAAK,QAAU1C,CAAAA,CACjB,MAAM,IAAI,KAAA,CAAM,8CAA8C,EAEhE,GAAI0C,CAAAA,CAAK,aAAA,GAAkB,CAAA,CACzB,MAAM,IAAI,KAAA,CAAM,gDAAgDA,CAAAA,CAAK,aAAa,EAAE,CAExF","file":"worker.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","// aiecsjs/serialize — binary, JSON, and delta serializers.\n\nimport { testBit } from './internal/bitmask.js'\nimport {\n addComponent,\n defineComponent,\n defineObjectComponent,\n defineTag,\n getComponentByInternalId,\n getComponentInfo,\n listAllComponents,\n} from './internal/component.js'\nimport { createEntity, destroyEntity, entityExists } from './internal/entity.js'\nimport type {\n ComponentInfo,\n ComponentLike,\n DeltaSerializer,\n DeserializeOptions,\n EntityId,\n SerializeOptions,\n World,\n WorldSnapshot,\n} from './internal/types.js'\nimport { createWorld, getWorldState } from './internal/world.js'\nimport { VERSION } from './version.js'\n\nconst MAGIC = 'AIEC'\nconst FORMAT_VERSION = 1\n\nexport function serializeWorld(world: World, options?: SerializeOptions): Uint8Array {\n const snapshot = toJSON(world)\n if (options?.components) {\n snapshot.entities = snapshot.entities.map((e) => ({\n eid: e.eid,\n components: e.components.filter((c) =>\n options.components!.some((comp) => comp.__id === c.id),\n ),\n }))\n }\n return packBinary(snapshot)\n}\n\nexport function deserializeWorld(bytes: Uint8Array, options?: DeserializeOptions): World {\n const snapshot = unpackBinary(bytes, options)\n return fromJSON(snapshot)\n}\n\nexport function toJSON(world: World): WorldSnapshot {\n const state = getWorldState(world)\n const entities: WorldSnapshot['entities'] = []\n for (let eid = 1; eid < state.capacity; eid++) {\n if (!entityExists(world, eid as EntityId)) continue\n const archId = state.entityArchetype[eid] ?? 0\n if (archId === 0) continue // unattached (shouldn't happen for alive)\n\n const w = state.options.maskWordCount\n const base = eid * w\n const components: WorldSnapshot['entities'][0]['components'] = []\n for (let wi = 0; wi < w; wi++) {\n let word = state.entityMask[base + wi] ?? 0\n while (word !== 0) {\n const lsb = word & -word\n const bit = (wi << 5) + (31 - Math.clz32(lsb))\n const info = state.componentInfoByBit[bit]\n if (info) {\n const storage = state.componentStorageByBit[bit]\n let data: unknown = null\n if (info.kind === 'soa' && storage?.soa) {\n const obj: Record<string, unknown> = {}\n for (const f of info.fields) {\n const col = storage.soa[f.name]\n if (!col) continue\n if (f.vectorLen === 1) {\n obj[f.name] = col[eid]\n } else {\n const arr: number[] = []\n const baseI = eid * f.vectorLen\n for (let i = 0; i < f.vectorLen; i++) arr.push(col[baseI + i] ?? 0)\n obj[f.name] = arr\n }\n }\n data = obj\n } else if (info.kind === 'aos' && storage?.aos) {\n data = storage.aos[eid] ?? null\n } else {\n data = true\n }\n components.push({ kind: info.kind, id: info.id, data })\n }\n word &= word - 1\n }\n }\n entities.push({ eid, components })\n }\n return {\n version: state.version,\n capacity: state.capacity,\n entities,\n }\n}\n\nexport function fromJSON(snapshot: WorldSnapshot): World {\n const world = createWorld({ initialCapacity: snapshot.capacity })\n const eidMap = new Map<number, EntityId>()\n for (const e of snapshot.entities) {\n const eid = createEntity(world)\n eidMap.set(e.eid, eid)\n }\n for (const e of snapshot.entities) {\n const eid = eidMap.get(e.eid)!\n for (const comp of e.components) {\n const info = getComponentByInternalId(comp.id)\n if (!info) {\n // Component missing — silently skip; future version may throw based on options\n continue\n }\n const handle = getComponentHandle(info)\n if (handle) {\n addComponent(world, eid, handle, comp.data as any)\n }\n }\n }\n return world\n}\n\n// Reconstruct a component handle from its ComponentInfo. Since defineComponent\n// returns plain handles { __kind, __id, __schema }, we can synthesize them.\nfunction getComponentHandle(info: ComponentInfo): ComponentLike | null {\n if (info.kind === 'soa') {\n return { __kind: 'soa', __id: info.id, __schema: info.schema ?? {} } as ComponentLike\n }\n if (info.kind === 'aos') {\n const factory = info.factory ?? (() => ({}))\n return { __kind: 'aos', __id: info.id, __factory: factory } as ComponentLike\n }\n return { __kind: 'tag', __id: info.id } as ComponentLike\n}\n\n// --- Binary packing (wrapped JSON for 0.1) ---\n\nfunction packBinary(snapshot: WorldSnapshot): Uint8Array {\n const json = JSON.stringify(snapshot)\n const jsonBytes = new TextEncoder().encode(json)\n const versionBytes = new TextEncoder().encode(VERSION)\n const headerSize = 4 + 4 + 4 + versionBytes.length + 4\n const total = headerSize + jsonBytes.length\n const out = new Uint8Array(total)\n const view = new DataView(out.buffer)\n let off = 0\n out[off++] = MAGIC.charCodeAt(0)\n out[off++] = MAGIC.charCodeAt(1)\n out[off++] = MAGIC.charCodeAt(2)\n out[off++] = MAGIC.charCodeAt(3)\n view.setUint32(off, FORMAT_VERSION, true)\n off += 4\n view.setUint32(off, versionBytes.length, true)\n off += 4\n out.set(versionBytes, off)\n off += versionBytes.length\n view.setUint32(off, jsonBytes.length, true)\n off += 4\n out.set(jsonBytes, off)\n return out\n}\n\nfunction unpackBinary(bytes: Uint8Array, options?: DeserializeOptions): WorldSnapshot {\n if (bytes.length < 12) throw new Error('aiecsjs: bytes too short to be a valid snapshot')\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)\n if (\n bytes[0] !== MAGIC.charCodeAt(0) ||\n bytes[1] !== MAGIC.charCodeAt(1) ||\n bytes[2] !== MAGIC.charCodeAt(2) ||\n bytes[3] !== MAGIC.charCodeAt(3)\n ) {\n throw new Error('aiecsjs: invalid magic bytes')\n }\n let off = 4\n const formatVersion = view.getUint32(off, true)\n off += 4\n const onUnknown = options?.onUnknownVersion ?? 'throw'\n if (formatVersion !== FORMAT_VERSION && onUnknown === 'throw') {\n throw new Error(`aiecsjs: format version ${formatVersion} not supported`)\n }\n\n // SECURITY: explicit bounds checks on every length field. DataView itself\n // throws on out-of-range reads, but an attacker who controls the bytes can\n // still craft a `verLen` that skips past data of their choosing — we make\n // each step's invariant explicit and impose a sane cap to short-circuit\n // pathological payloads early.\n const MAX_FIELD_LEN = 64 * 1024 * 1024 // 64 MiB\n if (off + 4 > bytes.length) {\n throw new Error('aiecsjs: snapshot truncated before verLen')\n }\n const verLen = view.getUint32(off, true)\n off += 4\n if (verLen > MAX_FIELD_LEN || off + verLen > bytes.length) {\n throw new Error(`aiecsjs: snapshot verLen=${verLen} out of bounds`)\n }\n off += verLen // skip the aiecsjs version string\n\n if (off + 4 > bytes.length) {\n throw new Error('aiecsjs: snapshot truncated before jsonLen')\n }\n const jsonLen = view.getUint32(off, true)\n off += 4\n if (jsonLen > MAX_FIELD_LEN || off + jsonLen > bytes.length) {\n throw new Error(`aiecsjs: snapshot jsonLen=${jsonLen} out of bounds`)\n }\n const jsonBytes = bytes.subarray(off, off + jsonLen)\n const json = new TextDecoder().decode(jsonBytes)\n return JSON.parse(json) as WorldSnapshot\n}\n\n// --- Delta serializer ---\n\ninterface DeltaState {\n world: World\n components: ComponentLike[]\n lastSnapshot: WorldSnapshot | null\n}\n\nexport function createDeltaSerializer(world: World, options?: SerializeOptions): DeltaSerializer {\n const state: DeltaState = {\n world,\n components:\n options?.components ??\n listAllComponents()\n .map((i) => getComponentHandle(i)!)\n .filter(Boolean),\n lastSnapshot: null,\n }\n return {\n capture(): Uint8Array {\n const current = toJSON(state.world)\n let delta: WorldSnapshot\n if (!state.lastSnapshot) {\n delta = current\n } else {\n // Compute simple delta: entities with changed components\n delta = computeDelta(state.lastSnapshot, current)\n }\n state.lastSnapshot = current\n return packBinary(delta)\n },\n apply(targetWorld: World, deltaBytes: Uint8Array): void {\n const snapshot = unpackBinary(deltaBytes)\n // Apply: ensure entities exist, then add/update their components\n const targetState = getWorldState(targetWorld)\n for (const e of snapshot.entities) {\n if (e.eid >= targetState.capacity) continue\n if (!entityExists(targetWorld, e.eid as EntityId)) {\n // Create the entity. For simplicity, we just spawn until we have enough.\n while (targetState.size < e.eid) {\n createEntity(targetWorld)\n }\n }\n for (const comp of e.components) {\n const info = getComponentByInternalId(comp.id)\n if (!info) continue\n const handle = getComponentHandle(info)\n if (handle) addComponent(targetWorld, e.eid as EntityId, handle, comp.data as any)\n }\n }\n },\n reset(): void {\n state.lastSnapshot = null\n },\n }\n}\n\nfunction computeDelta(prev: WorldSnapshot, curr: WorldSnapshot): WorldSnapshot {\n const prevByEid = new Map(prev.entities.map((e) => [e.eid, e]))\n const changed: WorldSnapshot['entities'] = []\n for (const e of curr.entities) {\n const prevE = prevByEid.get(e.eid)\n if (!prevE) {\n changed.push(e)\n continue\n }\n const prevSig = JSON.stringify(prevE.components)\n const currSig = JSON.stringify(e.components)\n if (prevSig !== currSig) changed.push(e)\n }\n return { version: curr.version, capacity: curr.capacity, entities: changed }\n}\n","// aiecsjs/worker — SharedArrayBuffer helpers (experimental, snapshot-copy in 0.1).\n//\n// Note: 0.1 implements SAB as a transferable snapshot pattern rather than true\n// shared-memory aliasing. The world is serialized into the SAB, and the worker\n// reconstructs a fresh world from those bytes via adoptSnapshot/attachWorld.\n// True shared-column memory is on the 0.2 roadmap. The API matches the\n// documented contract and survives postMessage cleanly.\n\nimport type { TransferableSnapshot, World, WorldMeta, WorldState } from './internal/types.js'\nimport { destroyWorld, getWorldState, isWorldRegistered } from './internal/world.js'\nimport { deserializeWorld, serializeWorld } from './serialize.js'\nimport { VERSION } from './version.js'\n\nconst MAGIC = 0x41494543 // 'AIEC' little-endian as uint32\n\nexport function transferableSnapshot(world: World): TransferableSnapshot {\n const state = getWorldState(world)\n const bytes = serializeWorld(world)\n\n if (typeof SharedArrayBuffer === 'undefined') {\n // Fallback: ArrayBuffer wrapped to look like a SAB at runtime\n const ab = new ArrayBuffer(bytes.byteLength)\n new Uint8Array(ab).set(bytes)\n return {\n buffer: ab as unknown as SharedArrayBuffer,\n meta: buildMeta(state),\n }\n }\n\n const sab = new SharedArrayBuffer(bytes.byteLength)\n new Uint8Array(sab).set(bytes)\n return { buffer: sab, meta: buildMeta(state) }\n}\n\n/**\n * Adopt a snapshot previously produced by `transferableSnapshot`.\n *\n * SECURITY: same trust expectation as `attachWorld` — the sender of the\n * `TransferableSnapshot` (typically a Web Worker) must be trusted. The\n * function runs `validateMeta` and `deserializeWorld`, which enforce magic\n * + format version + length bounds on the binary header; but the inner\n * JSON payload, once decoded, is fed to `addComponent` and reaches AoS\n * components. For untrusted senders, use `aibridgejs` + `toJSON(world)` at\n * the application boundary instead.\n */\nexport function adoptSnapshot(snap: TransferableSnapshot): World {\n validateMeta(snap.meta)\n const bytes = new Uint8Array(snap.buffer)\n return deserializeWorld(bytes)\n}\n\n/**\n * Adopt a SharedArrayBuffer-backed snapshot produced by `transferableSnapshot`.\n *\n * SECURITY: the SAB sender must be trusted. `attachWorld` performs the same\n * magic + version + length-bounds checks as `deserializeWorld`, but the JSON\n * payload itself is deserialised into AoS components via `addComponent`. If\n * the sender is untrusted (e.g. a third-party Web Worker that you do not\n * audit), prefer the higher-level `aibridgejs` channel + `toJSON(world)`\n * pattern, which lets you validate the shape at the application boundary\n * before constructing entities.\n */\nexport function attachWorld(buffer: SharedArrayBuffer, options?: { readOnly?: boolean }): World {\n const bytes = new Uint8Array(buffer)\n const world = deserializeWorld(bytes)\n if (options?.readOnly) {\n const state = getWorldState(world)\n state.readOnly = true\n }\n return world\n}\n\nexport function detachWorld(world: World): void {\n if (isWorldRegistered(world.id)) {\n destroyWorld(world)\n }\n}\n\nfunction buildMeta(state: WorldState): WorldMeta {\n const componentSchemas: WorldMeta['componentSchemas'] = []\n for (const info of state.componentInfoByBit) {\n if (!info) continue\n componentSchemas.push({ id: info.id, kind: info.kind, schema: info.schema })\n }\n return {\n magic: MAGIC,\n formatVersion: 1,\n aiecsjsVersion: VERSION,\n indexBits: state.options.indexBits,\n generationBits: state.options.generationBits,\n maxComponents: state.options.maxComponents,\n maskWordCount: state.options.maskWordCount,\n capacity: state.capacity,\n componentSchemas,\n }\n}\n\nfunction validateMeta(meta: WorldMeta): void {\n if (meta.magic !== MAGIC) {\n throw new Error('aiecsjs: invalid snapshot meta (wrong magic)')\n }\n if (meta.formatVersion !== 1) {\n throw new Error(`aiecsjs: unsupported snapshot format version ${meta.formatVersion}`)\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/worker.ts"],"names":["MAGIC","transferableSnapshot","world","state","getWorldState","bytes","serializeWorld","ab","buildMeta","sab","adoptSnapshot","snap","validateMeta","deserializeWorld","attachWorld","buffer","options","detachWorld","isWorldRegistered","destroyWorld","componentSchemas","info","VERSION","meta"],"mappings":"qGAkBA,IAAMA,CAAAA,CAAQ,WAEP,SAASC,CAAAA,CAAqBC,EAAoC,CACvE,IAAMC,CAAAA,CAAQC,CAAAA,CAAcF,CAAK,CAAA,CAC3BG,EAAQC,CAAAA,CAAeJ,CAAK,EAElC,GAAI,OAAO,kBAAsB,GAAA,CAAa,CAE5C,IAAMK,CAAAA,CAAK,IAAI,WAAA,CAAYF,EAAM,UAAU,CAAA,CAC3C,WAAI,UAAA,CAAWE,CAAE,EAAE,GAAA,CAAIF,CAAK,CAAA,CACrB,CACL,MAAA,CAAQE,CAAAA,CACR,KAAMC,CAAAA,CAAUL,CAAK,CACvB,CACF,CAEA,IAAMM,EAAM,IAAI,iBAAA,CAAkBJ,CAAAA,CAAM,UAAU,CAAA,CAClD,OAAA,IAAI,WAAWI,CAAG,CAAA,CAAE,IAAIJ,CAAK,CAAA,CACtB,CAAE,MAAA,CAAQI,CAAAA,CAAK,IAAA,CAAMD,CAAAA,CAAUL,C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AA,CAAAiB,CACF,CACF,CAEA,SAASR,CAAAA,CAAaW,EAAuB,CAC3C,GAAIA,EAAK,KAAA,GAAUvB,CAAAA,CACjB,MAAM,IAAI,KAAA,CAAM,8CAA8C,EAEhE,GAAIuB,CAAAA,CAAK,aAAA,GAAkB,CAAA,CACzB,MAAM,IAAI,MAAM,CAAA,6CAAA,EAAgDA,CAAAA,CAAK,aAAa,CAAA,CAAE,CAExF","file":"worker.js","sourcesContent":["// aiecsjs/worker — SharedArrayBuffer helpers (experimental, snapshot-copy).\n//\n// Note: 0.x implements SAB as a transferable snapshot pattern rather than true\n// shared-memory aliasing. The world is serialized into the SAB, and the worker\n// reconstructs a fresh world from those bytes via adoptSnapshot/attachWorld.\n// True shared-column memory is targeted for a future stable release.\n// The API matches the documented contract and survives postMessage cleanly.\n//\n// EntityRef is in-memory only — not preserved across worker boundaries.\n// Generation counters reset on adoptSnapshot/attachWorld. Pass `EntityRef.id`\n// (the packed EntityId) across the worker boundary only if you understand that\n// the generation portion will be stale after a round-trip snapshot.\n\nimport type { TransferableSnapshot, World, WorldMeta, WorldState } from './internal/types.js'\nimport { destroyWorld, getWorldState, isWorldRegistered } from './internal/world.js'\nimport { deserializeWorld, serializeWorld } from './serialize.js'\nimport { VERSION } from './version.js'\n\nconst MAGIC = 0x41494543 // 'AIEC' little-endian as uint32\n\nexport function transferableSnapshot(world: World): TransferableSnapshot {\n const state = getWorldState(world)\n const bytes = serializeWorld(world)\n\n if (typeof SharedArrayBuffer === 'undefined') {\n // Fallback: ArrayBuffer wrapped to look like a SAB at runtime\n const ab = new ArrayBuffer(bytes.byteLength)\n new Uint8Array(ab).set(bytes)\n return {\n buffer: ab as unknown as SharedArrayBuffer,\n meta: buildMeta(state),\n }\n }\n\n const sab = new SharedArrayBuffer(bytes.byteLength)\n new Uint8Array(sab).set(bytes)\n return { buffer: sab, meta: buildMeta(state) }\n}\n\n/**\n * Adopt a snapshot previously produced by `transferableSnapshot`.\n *\n * SECURITY: same trust expectation as `attachWorld` — the sender of the\n * `TransferableSnapshot` (typically a Web Worker) must be trusted. The\n * function runs `validateMeta` and `deserializeWorld`, which enforce magic\n * + format version + length bounds on the binary header; but the inner\n * JSON payload, once decoded, is fed to `addComponent` and reaches AoS\n * components. For untrusted senders, use `aibridgejs` + `toJSON(world)` at\n * the application boundary instead.\n */\nexport function adoptSnapshot(snap: TransferableSnapshot): World {\n validateMeta(snap.meta)\n const bytes = new Uint8Array(snap.buffer)\n return deserializeWorld(bytes)\n}\n\n/**\n * Adopt a SharedArrayBuffer-backed snapshot produced by `transferableSnapshot`.\n *\n * SECURITY: the SAB sender must be trusted. `attachWorld` performs the same\n * magic + version + length-bounds checks as `deserializeWorld`, but the JSON\n * payload itself is deserialised into AoS components via `addComponent`. If\n * the sender is untrusted (e.g. a third-party Web Worker that you do not\n * audit), prefer the higher-level `aibridgejs` channel + `toJSON(world)`\n * pattern, which lets you validate the shape at the application boundary\n * before constructing entities.\n */\nexport function attachWorld(buffer: SharedArrayBuffer, options?: { readOnly?: boolean }): World {\n const bytes = new Uint8Array(buffer)\n const world = deserializeWorld(bytes)\n if (options?.readOnly) {\n const state = getWorldState(world)\n state.readOnly = true\n }\n return world\n}\n\nexport function detachWorld(world: World): void {\n if (isWorldRegistered(world.id)) {\n destroyWorld(world)\n }\n}\n\nfunction buildMeta(state: WorldState): WorldMeta {\n const componentSchemas: WorldMeta['componentSchemas'] = []\n for (const info of state.componentInfoByBit) {\n if (!info) continue\n componentSchemas.push({ id: info.id, kind: info.kind, schema: info.schema })\n }\n return {\n magic: MAGIC,\n formatVersion: 1,\n aiecsjsVersion: VERSION,\n indexBits: state.options.indexBits,\n generationBits: state.options.generationBits,\n maxComponents: state.options.maxComponents,\n maskWordCount: state.options.maskWordCount,\n capacity: state.capacity,\n componentSchemas,\n }\n}\n\nfunction validateMeta(meta: WorldMeta): void {\n if (meta.magic !== MAGIC) {\n throw new Error('aiecsjs: invalid snapshot meta (wrong magic)')\n }\n if (meta.formatVersion !== 1) {\n throw new Error(`aiecsjs: unsupported snapshot format version ${meta.formatVersion}`)\n }\n}\n"]}
|
package/llms-full.txt
CHANGED
|
@@ -22,7 +22,7 @@ The short index lives at `llms.txt` (see https://llmstxt.org/).
|
|
|
22
22
|
|
|
23
23
|
Part of the [ai\*js micro-runtime ecosystem](https://github.com/yshengliao) — see also [aifsmjs](https://github.com/yshengliao/aifsmjs) (FSM) and [aibridgejs](https://github.com/yshengliao/aibridgejs) (cross-context RPC).
|
|
24
24
|
|
|
25
|
-
aiecsjs uses **archetype tables with TypedArray columns** and **bitmask queries** — the same architecture that powers piecs and wolf-ecs at the top of public benchmarks. Its API is **functional and tree-shakable**, composed with `pipe()`. Components support both Structure-of-Arrays (SoA) and Array-of-Structures (AoS) layouts.
|
|
25
|
+
aiecsjs uses **archetype tables with TypedArray columns** and **bitmask queries** — the same architecture that powers piecs and wolf-ecs at the top of public benchmarks. Its API is **functional and tree-shakable**, composed with `pipe()`. Components support both Structure-of-Arrays (SoA) and Array-of-Structures (AoS) layouts. Since 0.3, `EntityId` packs index + generation into a single 32-bit number; the ABA-safe `EntityRef` API shipped in 0.3.0.
|
|
26
26
|
|
|
27
27
|
```ts
|
|
28
28
|
import { createWorld, createEntity, defineComponent, defineQuery, pipe, forEachEntity, Types } from 'aiecsjs'
|
|
@@ -392,8 +392,13 @@ type WorldOptions = {
|
|
|
392
392
|
| `destroyEntity` | `(world: World, eid: EntityId) => void` | stable |
|
|
393
393
|
| `entityExists` | `(world: World, eid: EntityId) => boolean` | stable |
|
|
394
394
|
| `getEntityIndex` | `(eid: EntityId) => number` | stable |
|
|
395
|
-
| `getEntityGeneration` | `(eid: EntityId) => number` |
|
|
396
|
-
| `packEntity` | `(index: number, generation: number) => EntityId` |
|
|
395
|
+
| `getEntityGeneration` | `(eid: EntityId) => number` | stable (since 0.3.0) — returns the 8-bit generation field; uses default 24/8 layout |
|
|
396
|
+
| `packEntity` | `(index: number, generation: number) => EntityId` | stable (since 0.3.0) — packs index + generation using default 24/8 layout |
|
|
397
|
+
| `refOf` | `<T>(world: World, eid: EntityId) => EntityRef<T>` | stable (since 0.3.0) — creates ABA-safe ref; throws `EntityNotAliveError` if entity is dead |
|
|
398
|
+
| `deref` | `<T>(world: World, ref: EntityRef<T>) => EntityId \| null` | stable (since 0.3.0) — returns live `EntityId` or `null` if stale/cross-world; never throws |
|
|
399
|
+
| `aliveRef` | `<T>(world: World, ref: EntityRef<T>) => boolean` | stable (since 0.3.0) — boolean guard form of `deref`; never throws |
|
|
400
|
+
| `EntityRef` | `interface EntityRef<T> { id: EntityId; worldId: number }` | stable (since 0.3.0) — opaque ABA-safe reference; in-memory only |
|
|
401
|
+
| `EntityNotAliveError` | `class EntityNotAliveError extends Error { eid: number }` | stable (since 0.3.0) — thrown by `refOf` when entity is not alive |
|
|
397
402
|
|
|
398
403
|
### Component — `aiecsjs`
|
|
399
404
|
|
|
@@ -934,14 +939,102 @@ All notable changes to `aiecsjs` are recorded in this file.
|
|
|
934
939
|
|
|
935
940
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
936
941
|
|
|
942
|
+
## [0.3.1] - 2026-05-29
|
|
943
|
+
|
|
944
|
+
### Fixed
|
|
945
|
+
|
|
946
|
+
- **Packed EntityId signed-overflow for generation ≥ 128**: `createEntity` returned a negative number diverging from the unsigned value stored in archetype row arrays (`Uint32Array`), so query iteration (`runQuery`/`iterQuery`/`forEachEntity`) yielded an eid that failed `entityRow` lookups; `refOf`/`entityExists`/`deref` on a query-iterated high-generation entity misbehaved (`refOf` threw on a live entity). `packEid`/`packEntity` now normalise with `>>> 0`. No public-bundle behaviour change beyond the corrected eid representation (EntityId is opaque + in-memory-only).
|
|
947
|
+
- **`toJSON` silently dropped high-generation entities** (gen ≥ 128 with default 8-bit generation): `toJSON` contained its own inline pack expression that produced a signed (negative) result, diverging from the unsigned key stored in `arch.entityRow`. The affected entity passed the archetype check but failed `entityRow.has()`, so it was omitted from every snapshot and `serializeWorld` call. Fixed by replacing the inline expression with the canonical `packEid` (which applies `>>> 0`). SPOT principle: one pack source of truth.
|
|
948
|
+
- **Cross-subpath registry isolation** (`tsup splitting: false` → `splitting: true`): each compiled entry point (`dist/index.js`, `dist/serialize.js`, etc.) previously bundled its own private copy of `internal/world.ts`, including the module-scope `worldRegistry`. A world created via the core subpath was invisible to `serializeWorld`/`getRelationTargets`/`transferableSnapshot` imported from their respective subpaths, causing `world N is destroyed or unknown` at runtime. With `splitting: true`, esbuild extracts a shared chunk used by all entries; ESM and CJS are both verified by the new `scripts/check-dist-subpaths.mjs` smoke script.
|
|
949
|
+
- **`getRelationTargets` returned raw index as `EntityId`** (gen always 0): `addRelation` stores the target as a raw slot index (`& indexMask`). The previous return path cast this raw index directly to `EntityId`, which is equivalent to a packed id with generation 0. For any target that had been recycled (gen > 0), callers received a stale id that failed `entityExists`, `entityRow` lookups, and component access. Fixed by re-packing each raw index against the current generation via `packEid` before returning.
|
|
950
|
+
- **`resolveOptions` did not validate `indexBits + generationBits ≤ 32`**: the individual range checks (`indexBits ∈ [1, 24]`, `generationBits ∈ [0, 16]`) allowed combinations such as `indexBits=24, generationBits=16` (40 bits), where `gen << 24` silently overflowed and high-generation bits were lost. A sum check is now enforced with a clear error message. The `[Unreleased]` example corrected accordingly (`indexBits: 16, generationBits: 16` = 32 bits).
|
|
951
|
+
|
|
952
|
+
### Known Limitations
|
|
953
|
+
|
|
954
|
+
- **`createDeltaSerializer.apply` with a recycled target world**: `apply` uses the raw entity index from the delta snapshot as the `EntityId` directly. When the target world has already recycled any of those slots (generation > 0), component operations silently act on the wrong packed id. This is a known limitation of the experimental delta API; the common usage (delta → a fresh gen-0 render-mirror world) is unaffected. A proper raw-index-to-packed-id mapping is planned for 0.4. Avoid `apply` against a world that has previously destroyed entities.
|
|
955
|
+
|
|
956
|
+
### Documentation
|
|
957
|
+
|
|
958
|
+
- README / README_ZHTW updated to reflect the shipped 0.3.0 `EntityRef` API: the previous README still described EntityRef as "targeted for 0.3+" and `getEntityGeneration`/`packEntity` as experimental. Both files now correctly state EntityId has been packed since 0.3, and `EntityRef` / `refOf` / `deref` / `aliveRef` / `EntityNotAliveError` are all stable since 0.3.0. API table entries for these symbols added.
|
|
959
|
+
|
|
960
|
+
### Build & Tooling
|
|
961
|
+
|
|
962
|
+
- Coverage gate: `@vitest/coverage-v8` installed and wired into `prepublishOnly` (replaces `npm run test`) and CI. Thresholds: statements 95 / branches 80 / functions 97 / lines 98 — the achievable bar on pristine source. The branch figure honours the `?? 0` / `noUncheckedIndexedAccess` idiom on TypedArray reads (nullish-fallback branches unreachable by design); thresholds are raised only by adding tests, never by stripping defensive guards or scattering `/* v8 ignore */`.
|
|
963
|
+
- `fast-check` property tests (`tests/properties.test.ts`): pack/unpack round-trip invariant (asserts `e >= 0` to guard the P0 regression) and ABA-deref always-null invariant.
|
|
964
|
+
- Dispose three-cycle tests, error-path tests, and observer handler-throw behaviour documented in `tests/world.test.ts` / `tests/observers.test.ts`.
|
|
965
|
+
- `scripts/check-dist-subpaths.mjs` (`npm run verify:dist`): post-build smoke test that imports `createWorld`+`createEntity` from the core subpath and calls `serializeWorld`, `addRelation`/`getRelationTargets`, and `transferableSnapshot` from their respective subpaths for both ESM (`dist/*.js`) and CJS (`dist/*.cjs`). Wired into `prepublishOnly` (after `build`) and CI.
|
|
966
|
+
|
|
937
967
|
## [Unreleased]
|
|
938
968
|
|
|
939
|
-
### Planned for 0.
|
|
969
|
+
### Planned for 0.4+
|
|
940
970
|
|
|
941
|
-
- Implement ABA-safe `EntityRef` and graduate `getEntityGeneration` / `packEntity` from experimental → stable.
|
|
942
971
|
- Add `pipeAsync` for async system composition.
|
|
943
972
|
- Doc-test harness so README code blocks are mechanically verified.
|
|
944
973
|
- Promote `aiecsjs/relations` and `aiecsjs/worker` (true SAB-shared columns) to `stable`.
|
|
974
|
+
- Document the 8-bit generation wrap caveat in [STABILITY.md](./STABILITY.md): with the
|
|
975
|
+
default `generationBits=8`, a single slot recycled 256 times wraps back to its
|
|
976
|
+
starting generation, briefly re-opening the ABA window. Safe for v0.5 shmup
|
|
977
|
+
workloads (~5000 frame to wrap a single slot at 60 fps × ~1k destroys); high-churn
|
|
978
|
+
pools should set `createWorld({ indexBits: 16, generationBits: 16 })` (16 + 16 = 32 bits;
|
|
979
|
+
65 536 entities × 65 536 generations). See test
|
|
980
|
+
[tests/ref.test.ts](./tests/ref.test.ts) `generation wrap` describe block.
|
|
981
|
+
|
|
982
|
+
## [0.3.0] - 2026-05-29
|
|
983
|
+
|
|
984
|
+
### Added (API)
|
|
985
|
+
|
|
986
|
+
- **`EntityRef<T>`** — ABA-safe entity reference. `refOf(world, eid)` builds one;
|
|
987
|
+
`deref(world, ref)` returns the entity id when still alive (generation match)
|
|
988
|
+
or `null` otherwise; `aliveRef(world, ref)` is the boolean guard form. Phantom
|
|
989
|
+
type `T` lets callers distinguish ref kinds (e.g. `EntityRef<'bullet'>`) without
|
|
990
|
+
runtime cost. Refs are in-memory only — not serializable across worker / disk.
|
|
991
|
+
- **`EntityNotAliveError`** — thrown by `refOf` when the entity is dead or invalid.
|
|
992
|
+
`deref` / `aliveRef` never throw.
|
|
993
|
+
|
|
994
|
+
### Changed
|
|
995
|
+
|
|
996
|
+
- **`EntityId` now packs index + generation** into a single 32-bit number
|
|
997
|
+
`(generation << indexBits) | index` (default `indexBits=24, generationBits=8`).
|
|
998
|
+
`EntityId` remains opaque per STABILITY contract; the layout is implementation
|
|
999
|
+
detail. **Migration note**: do not compare `EntityId` numbers directly
|
|
1000
|
+
(`eid === 42` will break across slot recycles); use
|
|
1001
|
+
`getEntityIndex(eid)` for index comparison or `refOf(world, eid).id` for
|
|
1002
|
+
identity matching that survives slot reuse.
|
|
1003
|
+
- **`getEntityGeneration` / `packEntity` graduate to `stable`** (were `experimental`
|
|
1004
|
+
since 0.2.0). Both now return real values. These functions use default 24/8 bit
|
|
1005
|
+
layout; for non-default `createWorld({ indexBits, generationBits })`, use
|
|
1006
|
+
`EntityRef` and `deref` instead of manual unpacking.
|
|
1007
|
+
|
|
1008
|
+
### Fixed
|
|
1009
|
+
|
|
1010
|
+
- **ABA bug on entity slot recycle**: previously `entityExists` and `isAliveInternal`
|
|
1011
|
+
only checked archetype membership; a stale `EntityId` pointing at a recycled slot
|
|
1012
|
+
would silently report alive. With packed generation + `deref` generation match,
|
|
1013
|
+
stale refs now correctly invalidate.
|
|
1014
|
+
- **`destroyEntity` generation wrap mask aligned with `options.generationBits`**
|
|
1015
|
+
(was hard-coded `& 0xffff`). The mask now correctly uses
|
|
1016
|
+
`state.options.generationMask`, fixing inconsistency for non-default
|
|
1017
|
+
`generationBits` values.
|
|
1018
|
+
|
|
1019
|
+
### Documentation
|
|
1020
|
+
|
|
1021
|
+
- `onSet` JSDoc clarifies that `addComponent` does NOT trigger `onSet`, and
|
|
1022
|
+
direct writes to column views returned by `getComponent` (e.g. `col.x[idx] = 5`)
|
|
1023
|
+
also do NOT trigger `onSet`. Only `setComponent` on an already-present
|
|
1024
|
+
component fires the callback. Anti-pattern example included.
|
|
1025
|
+
|
|
1026
|
+
### Compatibility
|
|
1027
|
+
|
|
1028
|
+
- `EntityId` layout change is **not** breaking at the type system level (opaque
|
|
1029
|
+
branded number), but consumers who relied on `eid === N` direct comparison
|
|
1030
|
+
will need to migrate (see Migration note above).
|
|
1031
|
+
- All existing `stable` exports unchanged.
|
|
1032
|
+
- `aiecsjs/worker` snapshot wire format unchanged (still uses raw indices).
|
|
1033
|
+
- `aiecsjs/serialize` wire format unchanged.
|
|
1034
|
+
|
|
1035
|
+
### Build & tooling
|
|
1036
|
+
|
|
1037
|
+
- `VERSION` constant bumped to `0.3.0`.
|
|
945
1038
|
|
|
946
1039
|
## [0.2.1] - 2026-05-28
|
|
947
1040
|
|
|
@@ -1154,8 +1247,13 @@ The **root** entry (`aiecsjs`) is the stable core: world, entity, component, que
|
|
|
1154
1247
|
| `destroyEntity` | stable | 0.1.0 | |
|
|
1155
1248
|
| `entityExists` | stable | 0.1.0 | |
|
|
1156
1249
|
| `getEntityIndex` | stable | 0.1.0 | |
|
|
1157
|
-
| `getEntityGeneration` |
|
|
1158
|
-
| `packEntity` |
|
|
1250
|
+
| `getEntityGeneration` | stable | 0.3.0 | Returns real generation value packed into EntityId (default 24-bit index, 8-bit generation). For non-default `createWorld({ indexBits, generationBits })`, use `EntityRef` + `deref` instead. |
|
|
1251
|
+
| `packEntity` | stable | 0.3.0 | Packs index + generation into an EntityId using default 24/8 bit layout. For non-default bit sizes, use `EntityRef` + `deref` instead. |
|
|
1252
|
+
| `refOf` | stable | 0.3.0 | Throws `EntityNotAliveError` for dead entity. |
|
|
1253
|
+
| `deref` | stable | 0.3.0 | Returns null for stale / cross-world refs; never throws. |
|
|
1254
|
+
| `aliveRef` | stable | 0.3.0 | Boolean guard form of `deref`; never throws. |
|
|
1255
|
+
| `EntityRef` (type) | stable | 0.3.0 | In-memory only; not serializable. |
|
|
1256
|
+
| `EntityNotAliveError` | stable | 0.3.0 | Thrown only by `refOf`. |
|
|
1159
1257
|
| `defineComponent` | stable | 0.1.0 | |
|
|
1160
1258
|
| `defineTag` | stable | 0.1.0 | |
|
|
1161
1259
|
| `defineObjectComponent` | stable | 0.1.0 | AoS components are main-thread only; not SAB-shareable. |
|
|
@@ -1250,8 +1348,9 @@ Everything under this prefix is **internal**. It exists for the implementation's
|
|
|
1250
1348
|
|---|---|---|
|
|
1251
1349
|
| 0.1.x | Core surface (world, entity, component, query, system, loop, commands, observers, serialize) | Initial publish; all marked experimental at the package level but per-export stable where listed. |
|
|
1252
1350
|
| 0.2.0 | Safety + alignment | Prototype-pollution hardening, observer `{ signal? }`, `disposeWorld` alias, `getEntityGeneration` / `packEntity` re-labelled experimental, `verify:llms` gate. See [CHANGELOG.md](./CHANGELOG.md#020---2026-05-28). |
|
|
1253
|
-
| 0.3
|
|
1254
|
-
| 0.
|
|
1351
|
+
| 0.3.x | EntityRef + generation packing | ABA-safe; `getEntityGeneration` / `packEntity` → stable. |
|
|
1352
|
+
| 0.4+ | Relations stabilisation + true SAB worker | `aiecsjs/relations` and `aiecsjs/worker` → stable. |
|
|
1353
|
+
| 0.6+ | Multi-World snapshot diff transport (placeholder) | experimental — design TBD. |
|
|
1255
1354
|
| 1.0.0 | API freeze | All `stable` exports frozen for 1.x. |
|
|
1256
1355
|
|
|
1257
1356
|
## How to check stability at runtime
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "aiecsjs",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.1",
|
|
4
4
|
"description": "TypeScript-first archetype ECS with TypedArray SoA, SAB-ready snapshot transport, and AI-readable docs.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.cjs",
|
|
@@ -84,14 +84,18 @@
|
|
|
84
84
|
"lint": "biome check src tests",
|
|
85
85
|
"format": "biome format --write src tests",
|
|
86
86
|
"verify:exports": "node scripts/verify-exports.mjs",
|
|
87
|
+
"verify:dist": "node scripts/check-dist-subpaths.mjs",
|
|
87
88
|
"build:llms": "node scripts/build-llms-full.mjs",
|
|
88
89
|
"verify:llms": "node scripts/build-llms-full.mjs --check",
|
|
89
90
|
"size": "size-limit",
|
|
90
|
-
"
|
|
91
|
+
"coverage": "vitest run --coverage",
|
|
92
|
+
"prepublishOnly": "npm run typecheck && npm run lint && npm run coverage && npm run build && npm run verify:dist && npm run verify:exports && npm run verify:llms && npm run size"
|
|
91
93
|
},
|
|
92
94
|
"devDependencies": {
|
|
93
95
|
"@biomejs/biome": "^1.9.4",
|
|
94
96
|
"@size-limit/file": "^12.1.0",
|
|
97
|
+
"@vitest/coverage-v8": "^4.1.7",
|
|
98
|
+
"fast-check": "^4.8.0",
|
|
95
99
|
"size-limit": "^12.1.0",
|
|
96
100
|
"tsup": "^8.0.0",
|
|
97
101
|
"typescript": "^5.5.0",
|