aiecsjs 0.3.0 → 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 (44) hide show
  1. package/CHANGELOG.md +27 -1
  2. package/README.md +8 -3
  3. package/README_ZHTW.md +8 -3
  4. package/api.json +2 -2
  5. package/dist/chunk-37HMYMJG.cjs +2 -0
  6. package/dist/chunk-37HMYMJG.cjs.map +1 -0
  7. package/dist/chunk-4RPFOVQC.cjs +2 -0
  8. package/dist/chunk-4RPFOVQC.cjs.map +1 -0
  9. package/dist/chunk-AGHSWLNQ.cjs +2 -0
  10. package/dist/chunk-AGHSWLNQ.cjs.map +1 -0
  11. package/dist/chunk-FDXCXNZK.js +2 -0
  12. package/dist/chunk-FDXCXNZK.js.map +1 -0
  13. package/dist/chunk-L5CMKMIP.js +2 -0
  14. package/dist/chunk-L5CMKMIP.js.map +1 -0
  15. package/dist/chunk-QOKIEF7C.js +2 -0
  16. package/dist/chunk-QOKIEF7C.js.map +1 -0
  17. package/dist/commands.cjs +1 -1
  18. package/dist/commands.cjs.map +1 -1
  19. package/dist/commands.js +1 -1
  20. package/dist/commands.js.map +1 -1
  21. package/dist/index.cjs +1 -1
  22. package/dist/index.cjs.map +1 -1
  23. package/dist/index.d.cts +1 -1
  24. package/dist/index.d.ts +1 -1
  25. package/dist/index.js +1 -1
  26. package/dist/index.js.map +1 -1
  27. package/dist/observers.cjs +1 -1
  28. package/dist/observers.cjs.map +1 -1
  29. package/dist/observers.js +1 -1
  30. package/dist/observers.js.map +1 -1
  31. package/dist/relations.cjs +1 -1
  32. package/dist/relations.cjs.map +1 -1
  33. package/dist/relations.js +1 -1
  34. package/dist/relations.js.map +1 -1
  35. package/dist/serialize.cjs +1 -1
  36. package/dist/serialize.cjs.map +1 -1
  37. package/dist/serialize.js +1 -1
  38. package/dist/serialize.js.map +1 -1
  39. package/dist/worker.cjs +1 -1
  40. package/dist/worker.cjs.map +1 -1
  41. package/dist/worker.js +1 -1
  42. package/dist/worker.js.map +1 -1
  43. package/llms-full.txt +35 -4
  44. package/package.json +6 -2
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/internal/world.ts","../src/relations.ts"],"names":["worldRegistry","getWorldState","world","state","nextRelationId","defineRelation","options","ChildOf","getOrCreateStorage","rel","storage","addRelation","source","target","data","src","tgt","next","list","inner","removeRelation","idx","getRelationTargets"],"mappings":"AAyBA,IAAMA,CAAAA,CAAgB,IAAI,GAAA,CAEnB,SAASC,CAAAA,CAAcC,CAAAA,CAA0B,CACtD,IAAMC,CAAAA,CAAQH,CAAAA,CAAc,GAAA,CAAIE,CAAAA,CAAM,EAAE,CAAA,CACxC,GAAI,CAACC,CAAAA,CAAO,MAAM,IAAI,KAAA,CAAM,CAAA,eAAA,EAAkBD,EAAM,EAAE,CAAA,wBAAA,CAA0B,CAAA,CAChF,GAAIC,CAAAA,CAAM,SAAA,CAAW,MAAM,IAAI,MAAM,CAAA,eAAA,EAAkBD,CAAAA,CAAM,EAAE,CAAA,aAAA,CAAe,CAAA,CAC9E,OAAOC,CACT,CC1BA,IAAIC,CAAAA,CAAiB,CAAA,CAEd,SAASC,EAAyBC,CAAAA,CAAgD,CAEvF,OAAO,CACL,MAAA,CAAQ,UAAA,CACR,IAAA,CAHSF,CAAAA,EAAAA,CAIT,YAAaE,CAAAA,EAAS,SAAA,EAAa,KAAA,CACnC,SAAA,CAAW,KACb,CACF,CAEO,IAAMC,EAAoBF,CAAAA,CAAe,CAAE,SAAA,CAAW,IAAK,CAAC,EAEnE,SAASG,CAAAA,CAAmBL,EAAmBM,CAAAA,CAAqC,CAClF,IAAIC,CAAAA,CAAUP,CAAAA,CAAM,eAAA,CAAgB,GAAA,CAAIM,CAAAA,CAAI,IAAI,CAAA,CAChD,OAAIC,CAAAA,GACJA,CAAAA,CAAU,CACR,GAAA,CAAAD,CAAAA,CACA,SAAA,CAAWA,EAAI,WAAA,CAAc,IAAI,UAAA,CAAWN,CAAAA,CAAM,QAAQ,C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AAK,OAAA,CAAQF,CAAG,CAAA,CACxBK,CAAAA,EAAO,CAAA,EAAGH,CAAAA,CAAK,OAAOG,CAAAA,CAAK,CAAC,CAAA,CAC5BH,CAAAA,CAAK,MAAA,GAAW,CAAA,EAAGR,CAAAA,CAAQ,QAAA,CAAS,OAAOK,CAAG,EACpD,CACF,CACA,IAAMI,CAAAA,CAAQT,CAAAA,CAAQ,IAAA,CAAK,IAAIK,CAAG,CAAA,CAC9BI,CAAAA,GACFA,CAAAA,CAAM,MAAA,CAAOH,CAAG,CAAA,CACZG,CAAAA,CAAM,OAAS,CAAA,EAAGT,CAAAA,CAAQ,IAAA,CAAK,MAAA,CAAOK,CAAG,CAAA,EAEjD,CAEO,SAASO,EACdpB,CAAAA,CACAU,CAAAA,CACAH,CAAAA,CACqB,CACrB,IAAMN,CAAAA,CAAQF,CAAAA,CAAcC,CAAK,EAC3BQ,CAAAA,CAAUP,CAAAA,CAAM,eAAA,CAAgB,GAAA,CAAIM,CAAAA,CAAI,IAAI,CAAA,CAClD,GAAI,CAACC,CAAAA,CAAS,OAAO,EAAC,CACtB,IAAMK,CAAAA,CAAOH,CAAAA,CAAoBT,CAAAA,CAAM,QAAQ,SAAA,CAC/C,GAAIO,CAAAA,CAAQ,SAAA,CAAW,CACrB,GAAIK,CAAAA,CAAML,CAAAA,CAAQ,UAAU,MAAA,CAAQ,CAClC,IAAMM,CAAAA,CAAMN,CAAAA,CAAQ,SAAA,CAAUK,CAAG,CAAA,EAAK,GACtC,OAAOC,CAAAA,EAAO,CAAA,CAAI,CAACA,CAAe,CAAA,CAAI,EACxC,CACA,OAAO,EACT,CACA,IAAME,CAAAA,CAAOR,CAAAA,CAAQ,QAAA,CAAS,IAAIK,CAAG,CAAA,CACrC,OAAKG,CAAAA,EAAa,EAEpB","file":"relations.js","sourcesContent":["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 indexMask: (1 << indexBits) - 1,\n generationMask: generationBits === 0 ? 0 : (1 << generationBits) - 1,\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 idx = eid & state.options.indexMask\n const base = idx * 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 idx = eid & state.options.indexMask\n const base = idx * 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","// aiecsjs/relations — entity-to-entity relations (experimental in 0.1).\n\nimport { registerRelationsCleanup } from './internal/entity.js'\nimport type { EntityId, Relation, RelationStorage, World, WorldState } from './internal/types.js'\nimport { getWorldState } from './internal/world.js'\n\nlet nextRelationId = 1\n\nexport function defineRelation<T = void>(options?: { exclusive?: boolean }): Relation<T> {\n const id = nextRelationId++\n return {\n __kind: 'relation',\n __id: id,\n __exclusive: options?.exclusive ?? false,\n __hasData: false,\n } as Relation<T>\n}\n\nexport const ChildOf: Relation = defineRelation({ exclusive: true })\n\nfunction getOrCreateStorage(state: WorldState, rel: Relation<any>): RelationStorage {\n let storage = state.relationStorage.get(rel.__id)\n if (storage) return storage\n storage = {\n rel,\n exclusive: rel.__exclusive ? new Int32Array(state.capacity).fill(-1) : null,\n outgoing: new Map<number, number[]>(),\n data: new Map<number, Map<number, unknown>>(),\n }\n state.relationStorage.set(rel.__id, storage)\n return storage\n}\n\nexport function addRelation<T>(\n world: World,\n source: EntityId,\n rel: Relation<T>,\n target: EntityId,\n data?: T,\n): void {\n const state = getWorldState(world)\n if (state.readOnly) throw new Error('aiecsjs: cannot mutate a read-only world')\n const storage = getOrCreateStorage(state, rel as Relation<any>)\n // Use raw idx as keys in relation storage so slot reuse invalidation is consistent\n const src = (source as number) & state.options.indexMask\n const tgt = (target as number) & state.options.indexMask\n\n if (storage.exclusive) {\n if (src >= storage.exclusive.length) {\n const next = new Int32Array(Math.max(src + 1, storage.exclusive.length * 2)).fill(-1)\n next.set(storage.exclusive)\n storage.exclusive = next\n }\n storage.exclusive[src] = tgt\n } else {\n let list = storage.outgoing.get(src)\n if (!list) {\n list = []\n storage.outgoing.set(src, list)\n }\n if (!list.includes(tgt)) list.push(tgt)\n }\n\n if (data !== undefined) {\n let inner = storage.data.get(src)\n if (!inner) {\n inner = new Map<number, unknown>()\n storage.data.set(src, inner)\n }\n inner.set(tgt, data)\n }\n}\n\nexport function removeRelation(\n world: World,\n source: EntityId,\n rel: Relation,\n target: EntityId,\n): void {\n const state = getWorldState(world)\n if (state.readOnly) throw new Error('aiecsjs: cannot mutate a read-only world')\n const storage = state.relationStorage.get(rel.__id)\n if (!storage) return\n const src = (source as number) & state.options.indexMask\n const tgt = (target as number) & state.options.indexMask\n if (storage.exclusive) {\n if (src < storage.exclusive.length && storage.exclusive[src] === tgt) {\n storage.exclusive[src] = -1\n }\n } else {\n const list = storage.outgoing.get(src)\n if (list) {\n const idx = list.indexOf(tgt)\n if (idx >= 0) list.splice(idx, 1)\n if (list.length === 0) storage.outgoing.delete(src)\n }\n }\n const inner = storage.data.get(src)\n if (inner) {\n inner.delete(tgt)\n if (inner.size === 0) storage.data.delete(src)\n }\n}\n\nexport function getRelationTargets(\n world: World,\n source: EntityId,\n rel: Relation,\n): readonly EntityId[] {\n const state = getWorldState(world)\n const storage = state.relationStorage.get(rel.__id)\n if (!storage) return []\n const src = (source as number) & state.options.indexMask\n if (storage.exclusive) {\n if (src < storage.exclusive.length) {\n const tgt = storage.exclusive[src] ?? -1\n return tgt >= 0 ? [tgt as EntityId] : []\n }\n return []\n }\n const list = storage.outgoing.get(src)\n if (!list) return []\n return list as EntityId[]\n}\n\n// Cleanup hook: when an entity is destroyed, remove all relations involving it.\nregisterRelationsCleanup((state: WorldState, eid: EntityId) => {\n const e = (eid as number) & state.options.indexMask\n for (const storage of state.relationStorage.values()) {\n if (storage.exclusive) {\n if (e < storage.exclusive.length) storage.exclusive[e] = -1\n // Also clear any references TO this entity as target\n for (let i = 0; i < storage.exclusive.length; i++) {\n if (storage.exclusive[i] === e) storage.exclusive[i] = -1\n }\n }\n storage.outgoing.delete(e)\n for (const [src, list] of storage.outgoing) {\n const idx = list.indexOf(e)\n if (idx >= 0) {\n list.splice(idx, 1)\n if (list.length === 0) storage.outgoing.delete(src)\n }\n }\n // Clear data entries involving this entity. The outer key is the source\n // eid; entries whose source IS this entity drop entirely. Entries that\n // reference this entity as a target are pruned from each inner map.\n storage.data.delete(e)\n for (const [src, inner] of storage.data) {\n inner.delete(e)\n if (inner.size === 0) storage.data.delete(src)\n }\n }\n})\n"]}
1
+ {"version":3,"sources":["../src/relations.ts"],"names":["nextRelationId","defineRelation","options","ChildOf","getOrCreateStorage","state","rel","storage","addRelation","world","source","target","data","getWorldState","src","tgt","next","list","inner","removeRelation","idx","getRelationTargets","gen","packEid","tIdx","registerRelationsCleanup","eid","e"],"mappings":"wCAMA,IAAIA,CAAAA,CAAiB,CAAA,CAEd,SAASC,CAAAA,CAAyBC,CAAAA,CAAgD,CAEvF,OAAO,CACL,MAAA,CAAQ,UAAA,CACR,IAAA,CAHSF,CAAAA,EAAAA,CAIT,WAAA,CAAaE,CAAAA,EAAS,SAAA,EAAa,KAAA,CACnC,SAAA,CAAW,KACb,CACF,CAEO,IAAMC,CAAAA,CAAoBF,CAAAA,CAAe,CAAE,SAAA,CAAW,IAAK,CAAC,EAEnE,SAASG,CAAAA,CAAmBC,CAAAA,CAAmBC,CAAAA,CAAqC,CAClF,IAAIC,CAAAA,CAAUF,CAAAA,CAAM,eAAA,CAAgB,GAAA,CAAIC,CAAAA,CAAI,IAAI,CAAA,CAChD,OAAIC,CAAAA,GACJA,CAAAA,CAAU,CACR,IAAAD,CAAAA,CACA,SAAA,CAAWA,CAAAA,CAAI,WAAA,CAAc,IAAI,UAAA,CAAWD,CAAAA,CAAM,QAAQ,CAAA,CAAE,IAAA,CAAK,EAAE,CAAA,CAAI,IAAA,CACvE,QAAA,CAAU,IAAI,GAAA,CACd,KAAM,IAAI,GACZ,CAAA,CACAA,CAAAA,CAAM,eAAA,CAAgB,GAAA,CAAIC,CAAAA,CAAI,IAAA,CAAMC,CAAO,CAAA,CACpCA,CAAAA,CACT,CAEO,SAASC,CAAAA,CACdC,CAAAA,CACAC,CAAAA,CACAJ,EACAK,CAAAA,CACAC,GAAAA,CACM,CACN,IAAMP,CAAAA,CAAQQ,CAAAA,CAAcJ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AQ,IAAA,CAAK,MAAA,CAAOO,CAAG,EAEjD,CACF,CAAC,CAAA","file":"relations.js","sourcesContent":["// aiecsjs/relations — entity-to-entity relations (experimental in 0.1).\n\nimport { packEid, registerRelationsCleanup } from './internal/entity.js'\nimport type { EntityId, Relation, RelationStorage, World, WorldState } from './internal/types.js'\nimport { getWorldState } from './internal/world.js'\n\nlet nextRelationId = 1\n\nexport function defineRelation<T = void>(options?: { exclusive?: boolean }): Relation<T> {\n const id = nextRelationId++\n return {\n __kind: 'relation',\n __id: id,\n __exclusive: options?.exclusive ?? false,\n __hasData: false,\n } as Relation<T>\n}\n\nexport const ChildOf: Relation = defineRelation({ exclusive: true })\n\nfunction getOrCreateStorage(state: WorldState, rel: Relation<any>): RelationStorage {\n let storage = state.relationStorage.get(rel.__id)\n if (storage) return storage\n storage = {\n rel,\n exclusive: rel.__exclusive ? new Int32Array(state.capacity).fill(-1) : null,\n outgoing: new Map<number, number[]>(),\n data: new Map<number, Map<number, unknown>>(),\n }\n state.relationStorage.set(rel.__id, storage)\n return storage\n}\n\nexport function addRelation<T>(\n world: World,\n source: EntityId,\n rel: Relation<T>,\n target: EntityId,\n data?: T,\n): void {\n const state = getWorldState(world)\n if (state.readOnly) throw new Error('aiecsjs: cannot mutate a read-only world')\n const storage = getOrCreateStorage(state, rel as Relation<any>)\n // Use raw idx as keys in relation storage so slot reuse invalidation is consistent\n const src = (source as number) & state.options.indexMask\n const tgt = (target as number) & state.options.indexMask\n\n if (storage.exclusive) {\n if (src >= storage.exclusive.length) {\n const next = new Int32Array(Math.max(src + 1, storage.exclusive.length * 2)).fill(-1)\n next.set(storage.exclusive)\n storage.exclusive = next\n }\n storage.exclusive[src] = tgt\n } else {\n let list = storage.outgoing.get(src)\n if (!list) {\n list = []\n storage.outgoing.set(src, list)\n }\n if (!list.includes(tgt)) list.push(tgt)\n }\n\n if (data !== undefined) {\n let inner = storage.data.get(src)\n if (!inner) {\n inner = new Map<number, unknown>()\n storage.data.set(src, inner)\n }\n inner.set(tgt, data)\n }\n}\n\nexport function removeRelation(\n world: World,\n source: EntityId,\n rel: Relation,\n target: EntityId,\n): void {\n const state = getWorldState(world)\n if (state.readOnly) throw new Error('aiecsjs: cannot mutate a read-only world')\n const storage = state.relationStorage.get(rel.__id)\n if (!storage) return\n const src = (source as number) & state.options.indexMask\n const tgt = (target as number) & state.options.indexMask\n if (storage.exclusive) {\n if (src < storage.exclusive.length && storage.exclusive[src] === tgt) {\n storage.exclusive[src] = -1\n }\n } else {\n const list = storage.outgoing.get(src)\n if (list) {\n const idx = list.indexOf(tgt)\n if (idx >= 0) list.splice(idx, 1)\n if (list.length === 0) storage.outgoing.delete(src)\n }\n }\n const inner = storage.data.get(src)\n if (inner) {\n inner.delete(tgt)\n if (inner.size === 0) storage.data.delete(src)\n }\n}\n\nexport function getRelationTargets(\n world: World,\n source: EntityId,\n rel: Relation,\n): readonly EntityId[] {\n const state = getWorldState(world)\n const storage = state.relationStorage.get(rel.__id)\n if (!storage) return []\n const src = (source as number) & state.options.indexMask\n if (storage.exclusive) {\n if (src < storage.exclusive.length) {\n const tgt = storage.exclusive[src] ?? -1\n if (tgt >= 0) {\n const gen = state.generations[tgt] ?? 0\n return [packEid(tgt, gen, state.options)]\n }\n }\n return []\n }\n const list = storage.outgoing.get(src)\n if (!list) return []\n return list.map((tIdx) => {\n const gen = state.generations[tIdx] ?? 0\n return packEid(tIdx, gen, state.options)\n })\n}\n\n// Cleanup hook: when an entity is destroyed, remove all relations involving it.\nregisterRelationsCleanup((state: WorldState, eid: EntityId) => {\n const e = (eid as number) & state.options.indexMask\n for (const storage of state.relationStorage.values()) {\n if (storage.exclusive) {\n if (e < storage.exclusive.length) storage.exclusive[e] = -1\n // Also clear any references TO this entity as target\n for (let i = 0; i < storage.exclusive.length; i++) {\n if (storage.exclusive[i] === e) storage.exclusive[i] = -1\n }\n }\n storage.outgoing.delete(e)\n for (const [src, list] of storage.outgoing) {\n const idx = list.indexOf(e)\n if (idx >= 0) {\n list.splice(idx, 1)\n if (list.length === 0) storage.outgoing.delete(src)\n }\n }\n // Clear data entries involving this entity. The outer key is the source\n // eid; entries whose source IS this entity drop entirely. Entries that\n // reference this entity as a target are pruned from each inner map.\n storage.data.delete(e)\n for (const [src, inner] of storage.data) {\n inner.delete(e)\n if (inner.size === 0) storage.data.delete(src)\n }\n }\n})\n"]}
@@ -1,2 +1,2 @@
1
- 'use strict';function j(n){return new Uint32Array(n)}function z(n,t){let o=t>>>5;n[o]=(n[o]??0)|1<<(t&31);}function T(n,t){let o=t>>>5;return ((n[o]??0)&1<<(t&31))!==0}function g(n){let t=new Uint32Array(n.length);for(let o=0;o<n.length;o++)t[o]=n[o]??0;return t}function W(n){let t=[];for(let o=0;o<n.length;o++)t.push((n[o]??0).toString(16));return t.join(",")}var x="0.3.0";var k={initialCapacity:1024,maxEntities:1e6,indexBits:24,generationBits:8},nt=256,et=1,D=new Map;function p(n){let t=D.get(n.id);if(!t)throw new Error(`aiecsjs: world ${n.id} is destroyed or unknown`);if(t.destroyed)throw new Error(`aiecsjs: world ${n.id} is destroyed`);return t}function ot(n){D.set(n.id,n);}function rt(n){let t=n??{},o=t.indexBits??k.indexBits,e=t.generationBits??k.generationBits,r=nt;if(o<1||o>24)throw new Error("aiecsjs: indexBits must be in [1, 24]");if(e<0||e>16)throw new Error("aiecsjs: generationBits must be in [0, 16]");let i=1<<o,s=Math.max(1,Math.min(t.initialCapacity??k.initialCapacity,i)),a=Math.max(s,Math.min(t.maxEntities??k.maxEntities,i));return {initialCapacity:s,maxEntities:a,indexBits:o,generationBits:e,indexMask:(1<<o)-1,generationMask:e===0?0:(1<<e)-1,maxComponents:r,maskWordCount:Math.ceil(r/32),buffer:t.buffer??null,bufferByteOffset:t.bufferByteOffset??0}}function it(n,t){return {id:0,mask:j(n),size:0,capacity:16,entities:new Uint32Array(16),entityRow:new Map,componentBits:[],edgeAdd:new Int32Array(t).fill(-1),edgeRemove:new Int32Array(t).fill(-1)}}function F(n){let t=rt(n),o=et++,e=t.generationBits>8?Uint16Array:Uint8Array,r=new e(t.initialCapacity),i={id:o,capacity:t.initialCapacity,version:x,options:t,size:0,nextFreshIndex:1,freeList:[],generations:r,destroyed:false,componentBitFor:new Map,componentInfoByBit:new Array(t.maxComponents).fill(null),componentStorageByBit:new Array(t.maxComponents).fill(null),nextComponentBit:0,entityArchetype:new Uint32Array(t.initialCapacity),entityMask:new Uint32Array(t.initialCapacity*t.maskWordCount),archetypes:[],archetypeByMaskHash:new Map,queryVersion:0,queries:[],queryMasks:new Map,queryArchetypeCache:[],queryArchetypeStamp:[],bitToQueries:new Map,reactiveBuffers:new Map,observers:[],relationStorage:new Map,sab:t.buffer,readOnly:false},s=it(t.maskWordCount,t.maxComponents);return s.id=0,i.archetypes.push(s),i.archetypeByMaskHash.set(W(s.mask),0),ot(i),st(i)}function st(n){return {id:n.id,get capacity(){return n.capacity},version:n.version}}function N(n,t){if(t<=n.capacity)return;if(t>n.options.maxEntities)throw new Error(`aiecsjs: requested capacity ${t} exceeds maxEntities ${n.options.maxEntities}`);let o=n.capacity;for(;o<t;)o=Math.min(o*2,n.options.maxEntities);at(n,o);}function at(n,t){let o=n.generations.constructor,e=new o(t);e.set(n.generations),n.generations=e;let r=new Uint32Array(t);r.set(n.entityArchetype),n.entityArchetype=r;let i=n.options.maskWordCount,s=new Uint32Array(t*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&&ct(a.soa,c.fields,t);}else a.kind==="aos"&&a.aos&&(a.aos.length=t);n.capacity=t;}function ct(n,t,o){for(let e of t){let r=n[e.name];if(!r)continue;let i=o*e.vectorLen;if(r.length>=i)continue;let s=new e.ctor(i);s.set(r),n[e.name]=s;}}function P(n,t){let o=W(t),e=n.archetypeByMaskHash.get(o);if(e!==void 0)return {archId:e,created:false};let r=n.archetypes.length,i={id:r,mask:g(t),size:0,capacity:16,entities:new Uint32Array(16),entityRow:new Map,componentBits:dt(t),edgeAdd:new Int32Array(n.options.maxComponents).fill(-1),edgeRemove:new Int32Array(n.options.maxComponents).fill(-1)};return n.archetypes.push(i),n.archetypeByMaskHash.set(o,r),n.queryVersion++,{archId:r,created:true}}function C(n,t){if(t<=n.capacity)return;let o=n.capacity;for(;o<t;)o*=2;let e=new Uint32Array(o);e.set(n.entities),n.entities=e,n.capacity=o;}function dt(n){let t=[];for(let o=0;o<n.length;o++){let e=n[o]??0;for(;e!==0;){let r=e&-e,i=(o<<5)+(31-Math.clz32(r));t.push(i),e&=e-1;}}return t}function V(n,t){let o=n.componentBitFor.get(t.id);if(o!==void 0)return o;if(n.nextComponentBit>=n.options.maxComponents)throw new Error(`aiecsjs: world reached maxComponents=${n.options.maxComponents}`);let e=n.nextComponentBit++;n.componentBitFor.set(t.id,e),n.componentInfoByBit[e]=t;let r;if(t.kind==="soa"){let i={};for(let s of t.fields)i[s.name]=new s.ctor(n.capacity*s.vectorLen);r={kind:"soa",componentId:t.id,bit:e,soa:i};}else t.kind==="aos"?r={kind:"aos",componentId:t.id,bit:e,aos:new Array(n.capacity)}:r={kind:"tag",componentId:t.id,bit:e};return n.componentStorageByBit[e]=r,e}function $(n,t){let o=n.options.maskWordCount,e=new Uint32Array(o),i=(t&n.options.indexMask)*o;for(let s=0;s<o;s++)e[s]=n.entityMask[i+s]??0;return e}function q(n,t,o){let e=n.options.maskWordCount,i=(t&n.options.indexMask)*e;for(let s=0;s<e;s++)n.entityMask[i+s]=o[s]??0;}function lt(n,t,o){return (t&o.generationMask)<<o.indexBits|n&o.indexMask}function B(n){let t=p(n);if(t.readOnly)throw new Error("aiecsjs: cannot createEntity on a read-only world (worker-attached)");let o;if(t.freeList.length>0)o=t.freeList.pop();else {if(t.nextFreshIndex>=t.options.maxEntities)throw new Error(`aiecsjs: reached maxEntities ${t.options.maxEntities}`);t.nextFreshIndex>=t.capacity&&N(t,t.nextFreshIndex+1),o=t.nextFreshIndex++;}let e=t.generations[o]??0,r=lt(o,e,t.options),i=t.archetypes[0];if(!i)throw new Error("aiecsjs: missing empty archetype");C(i,i.size+1);let s=i.size;i.entities[s]=r,i.entityRow.set(r,s),i.size++,t.entityArchetype[o]=0;let a=t.options.maskWordCount,c=o*a;for(let d=0;d<a;d++)t.entityMask[c+d]=0;return t.size++,r}function G(n,t){let o=p(n);return M(o,t)}function M(n,t){let o=t&n.options.indexMask;if(o<=0||o>=n.capacity)return false;let e=n.entityArchetype[o]??0,r=n.archetypes[e];if(!r||!r.entityRow.has(t))return false;let i=n.generations[o]??0,s=t>>>n.options.indexBits&n.options.generationMask;return i===s}var O=new Map;function J(n){let t=O.get(n.__id);if(!t)throw new Error("aiecsjs: component is not registered (call defineComponent/defineTag/defineObjectComponent)");return t}function U(n,t,o,e){let r=p(n);if(r.readOnly)throw new Error("aiecsjs: cannot mutate a read-only world");if(!M(r,t))throw new Error(`aiecsjs: addComponent on dead entity ${t}`);let i=J(o),s=V(r,i),a=$(r,t);if(T(a,s)){e!==void 0&&H(r,t,o,e);return}let c=g(a);z(c,s),pt(r,t,c),H(r,t,o,e);}function H(n,t,o,e){let r=J(o),i=n.componentBitFor.get(r.id);if(i===void 0)return;let s=n.componentStorageByBit[i];if(!s)return;let a=t&n.options.indexMask;if(r.kind==="soa"&&s.soa){if(e==null)return;let c=e;for(let d of r.fields){if(!(d.name in c))continue;let f=s.soa[d.name];if(!f)continue;let u=c[d.name];if(d.vectorLen===1)f[a]=typeof u=="boolean"?u?1:0:Number(u);else if(Array.isArray(u)||ArrayBuffer.isView(u)){let l=a*d.vectorLen,S=u;for(let m=0;m<d.vectorLen;m++)f[l+m]=Number(S[m]??0);}}}else if(r.kind==="aos"&&s.aos){let c=r.factory??(()=>({})),d=s.aos[a];if(d===void 0&&(d=c(),s.aos[a]=d),e&&typeof e=="object"){let f=e,u=d;for(let l of Object.keys(f))l==="__proto__"||l==="constructor"||l==="prototype"||(u[l]=f[l]);}}}function pt(n,t,o){let e=t&n.options.indexMask,r=n.entityArchetype[e]??0,i=n.archetypes[r];if(!i)return;let a=P(n,o).archId,c=n.archetypes[a];if(c){if(a!==r){let d=i.entityRow.get(t);if(d!==void 0){let u=i.size-1;if(d!==u){let l=i.entities[u]??0;i.entities[d]=l,i.entityRow.set(l,d);}i.entities[u]=0,i.entityRow.delete(t),i.size--;}C(c,c.size+1);let f=c.size;c.entities[f]=t,c.entityRow.set(t,f),c.size++,n.entityArchetype[e]=a;}q(n,t,o);}}function _(n){return O.get(n)}function X(){return Array.from(O.values())}var y="AIEC",Y=1;function Gt(n,t){let o=K(n);return t?.components&&(o.entities=o.entities.map(e=>({eid:e.eid,components:e.components.filter(r=>t.components.some(i=>i.__id===r.id))}))),Q(o)}function Ht(n,t){let o=Z(n,t);return bt(o)}function K(n){let t=p(n),o=[];for(let e=1;e<t.capacity;e++){let r=t.entityArchetype[e]??0;if(r===0)continue;let i=t.archetypes[r];if(!i)continue;let a=((t.generations[e]??0)&t.options.generationMask)<<t.options.indexBits|e&t.options.indexMask;if(!i.entityRow.has(a))continue;let c=t.options.maskWordCount,d=e*c,f=[];for(let u=0;u<c;u++){let l=t.entityMask[d+u]??0;for(;l!==0;){let S=l&-l,m=(u<<5)+(31-Math.clz32(S)),h=t.componentInfoByBit[m];if(h){let b=t.componentStorageByBit[m],A=null;if(h.kind==="soa"&&b?.soa){let E={};for(let w of h.fields){let I=b.soa[w.name];if(I)if(w.vectorLen===1)E[w.name]=I[e];else {let L=[],tt=e*w.vectorLen;for(let v=0;v<w.vectorLen;v++)L.push(I[tt+v]??0);E[w.name]=L;}}A=E;}else h.kind==="aos"&&b?.aos?A=b.aos[e]??null:A=true;f.push({kind:h.kind,id:h.id,data:A});}l&=l-1;}}o.push({eid:e,components:f});}return {version:t.version,capacity:t.capacity,entities:o}}function bt(n){let t=F({initialCapacity:n.capacity}),o=new Map;for(let e of n.entities){let r=B(t);o.set(e.eid,r);}for(let e of n.entities){let r=o.get(e.eid);for(let i of e.components){let s=_(i.id);if(!s)continue;let a=R(s);a&&U(t,r,a,i.data);}}return t}function R(n){if(n.kind==="soa")return {__kind:"soa",__id:n.id,__schema:n.schema??{}};if(n.kind==="aos"){let t=n.factory??(()=>({}));return {__kind:"aos",__id:n.id,__factory:t}}return {__kind:"tag",__id:n.id}}function Q(n){let t=JSON.stringify(n),o=new TextEncoder().encode(t),e=new TextEncoder().encode(x),i=12+e.length+4+o.length,s=new Uint8Array(i),a=new DataView(s.buffer),c=0;return s[c++]=y.charCodeAt(0),s[c++]=y.charCodeAt(1),s[c++]=y.charCodeAt(2),s[c++]=y.charCodeAt(3),a.setUint32(c,Y,true),c+=4,a.setUint32(c,e.length,true),c+=4,s.set(e,c),c+=e.length,a.setUint32(c,o.length,true),c+=4,s.set(o,c),s}function Z(n,t){if(n.length<12)throw new Error("aiecsjs: bytes too short to be a valid snapshot");let o=new DataView(n.buffer,n.byteOffset,n.byteLength);if(n[0]!==y.charCodeAt(0)||n[1]!==y.charCodeAt(1)||n[2]!==y.charCodeAt(2)||n[3]!==y.charCodeAt(3))throw new Error("aiecsjs: invalid magic bytes");let e=4,r=o.getUint32(e,true);e+=4;let i=t?.onUnknownVersion??"throw";if(r!==Y&&i==="throw")throw new Error(`aiecsjs: format version ${r} not supported`);let s=64*1024*1024;if(e+4>n.length)throw new Error("aiecsjs: snapshot truncated before verLen");let a=o.getUint32(e,true);if(e+=4,a>s||e+a>n.length)throw new Error(`aiecsjs: snapshot verLen=${a} out of bounds`);if(e+=a,e+4>n.length)throw new Error("aiecsjs: snapshot truncated before jsonLen");let c=o.getUint32(e,true);if(e+=4,c>s||e+c>n.length)throw new Error(`aiecsjs: snapshot jsonLen=${c} out of bounds`);let d=n.subarray(e,e+c),f=new TextDecoder().decode(d);return JSON.parse(f)}function Jt(n,t){let o={world:n,components:t?.components??X().map(e=>R(e)).filter(Boolean),lastSnapshot:null};return {capture(){let e=K(o.world),r;return o.lastSnapshot?r=At(o.lastSnapshot,e):r=e,o.lastSnapshot=e,Q(r)},apply(e,r){let i=Z(r),s=p(e);for(let a of i.entities)if(!(a.eid>=s.capacity)){if(!G(e,a.eid))for(;s.size<a.eid;)B(e);for(let c of a.components){let d=_(c.id);if(!d)continue;let f=R(d);f&&U(e,a.eid,f,c.data);}}},reset(){o.lastSnapshot=null;}}}function At(n,t){let o=new Map(n.entities.map(r=>[r.eid,r])),e=[];for(let r of t.entities){let i=o.get(r.eid);if(!i){e.push(r);continue}let s=JSON.stringify(i.components),a=JSON.stringify(r.components);s!==a&&e.push(r);}return {version:t.version,capacity:t.capacity,entities:e}}exports.createDeltaSerializer=Jt;exports.deserializeWorld=Ht;exports.fromJSON=bt;exports.serializeWorld=Gt;exports.toJSON=K;//# sourceMappingURL=serialize.cjs.map
1
+ 'use strict';var chunkAGHSWLNQ_cjs=require('./chunk-AGHSWLNQ.cjs');require('./chunk-4RPFOVQC.cjs');Object.defineProperty(exports,"createDeltaSerializer",{enumerable:true,get:function(){return chunkAGHSWLNQ_cjs.e}});Object.defineProperty(exports,"deserializeWorld",{enumerable:true,get:function(){return chunkAGHSWLNQ_cjs.b}});Object.defineProperty(exports,"fromJSON",{enumerable:true,get:function(){return chunkAGHSWLNQ_cjs.d}});Object.defineProperty(exports,"serializeWorld",{enumerable:true,get:function(){return chunkAGHSWLNQ_cjs.a}});Object.defineProperty(exports,"toJSON",{enumerable:true,get:function(){return chunkAGHSWLNQ_cjs.c}});//# sourceMappingURL=serialize.cjs.map
2
2
  //# sourceMappingURL=serialize.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/internal/bitmask.ts","../src/version.ts","../src/internal/world.ts","../src/internal/entity.ts","../src/internal/component.ts","../src/serialize.ts"],"names":["createMask","wordCount","setBit","mask","bit","w","testBit","cloneMask","src","out","i","maskHash","m","parts","VERSION","DEFAULT_OPTIONS","DEFAULT_MAX_COMPONENTS","nextWorldId","worldRegistry","getWorldState","world","state","registerWorld","resolveOptions","opts","o","indexBits","generationBits","maxComponents","maxByIndex","initialCapacity","maxEntities","createEmptyArchetype","maskWordCount","createWorld","options","resolved","id","generationCtor","generations","empty","makePublicWorld","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","packEid","idx","gen","createEntity","row","entityExists","isAliveInternal","archId","storedGen","refGen","componentInfoById","getComponentInfo","component","addComponent","initial","prevMask","writeInitial","migrateEntity","packedEid","obj","col","val","arr","factory","inst","target","srcArchId","srcArch","destArchId","destArch","lastRow","moved","newRow","getComponentByInternalId","listAllComponents","MAGIC","FORMAT_VERSION","serializeWorld","snapshot","toJSON","c","comp","packBinary","deserializeWorld","bytes","unpackBinary","fromJSON","entities","components","wi","data","baseI","eidMap","handle","getComponentHandle","json","jsonBytes","versionBytes","total","view","off","formatVersion","onUnknown","MAX_FIELD_LEN","verLen","jsonLen","createDeltaSerializer","current","delta","computeDelta","targetWorld","deltaBytes","targetState","e","prev","curr","prevByEid","changed","prevE","prevSig","currSig"],"mappings":"aAEO,SAASA,EAAWC,CAAAA,CAAgC,CACzD,OAAO,IAAI,YAAYA,CAAS,CAClC,CAEO,SAASC,EAAOC,CAAAA,CAAmBC,CAAAA,CAAmB,CAC3D,IAAMC,CAAAA,CAAID,IAAQ,CAAA,CAClBD,CAAAA,CAAKE,CAAC,CAAA,CAAA,CAAKF,EAAKE,CAAC,CAAA,EAAK,GAAM,CAAA,GAAMD,CAAAA,CAAM,IAC1C,CAOO,SAASE,CAAAA,CAAQH,CAAAA,CAAmBC,EAAsB,CAC/D,IAAMC,EAAID,CAAAA,GAAQ,CAAA,CAClB,SAASD,CAAAA,CAAKE,CAAC,CAAA,EAAK,CAAA,EAAM,IAAMD,CAAAA,CAAM,EAAA,CAAA,IAAU,CAClD,CAOO,SAASG,EAAUC,CAAAA,CAA+B,CACvD,IAAMC,CAAAA,CAAM,IAAI,WAAA,CAAYD,CAAA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QAAA,CAAU,QAAA,CAAUE,CAAQ,CAC7E","file":"serialize.cjs","sourcesContent":["// 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","export const VERSION = '0.3.0'\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 indexMask: (1 << indexBits) - 1,\n generationMask: generationBits === 0 ? 0 : (1 << generationBits) - 1,\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 idx = eid & state.options.indexMask\n const base = idx * 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 idx = eid & state.options.indexMask\n const base = idx * 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, ResolvedWorldOptions, World, WorldState } from './types.js'\nimport { ensureArchetypeCapacity, ensureCapacity, getWorldState } from './world.js'\n\n// --- Default bit layout constants (used by public getEntityIndex / getEntityGeneration / packEntity) ---\n// These use the default 24/8 split. See §4.4 limitation: callers using non-default\n// createWorld({ indexBits, generationBits }) should not rely on these functions for unpacking.\nexport const DEFAULT_INDEX_BITS = 24\nexport const DEFAULT_GENERATION_BITS = 8\nexport const DEFAULT_INDEX_MASK = (1 << DEFAULT_INDEX_BITS) - 1\nexport const DEFAULT_GENERATION_MASK = (1 << DEFAULT_GENERATION_BITS) - 1\n\n// --- Internal pack/unpack helpers (world-options-aware) ---\n\nexport function packEid(idx: number, gen: number, opts: ResolvedWorldOptions): EntityId {\n return (((gen & opts.generationMask) << opts.indexBits) | (idx & opts.indexMask)) as EntityId\n}\n\nexport function unpackIdx(eid: number, opts: ResolvedWorldOptions): number {\n return eid & opts.indexMask\n}\n\nexport function unpackGen(eid: number, opts: ResolvedWorldOptions): number {\n return (eid >>> opts.indexBits) & opts.generationMask\n}\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 idx: number\n if (state.freeList.length > 0) {\n idx = 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 idx = state.nextFreshIndex++\n }\n\n const gen = state.generations[idx] ?? 0\n const eid = packEid(idx, gen, state.options)\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[idx] = 0\n // Reset entityMask row for this idx\n const w = state.options.maskWordCount\n const base = idx * w\n for (let i = 0; i < w; i++) state.entityMask[base + i] = 0\n\n state.size++\n return eid\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 const idx = eid & state.options.indexMask\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[idx] ?? 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[idx] = 0\n const w = state.options.maskWordCount\n const base = idx * w\n for (let i = 0; i < w; i++) state.entityMask[base + i] = 0\n // Bump generation — use generationMask so non-default generationBits wraps correctly\n state.generations[idx] = ((state.generations[idx] ?? 0) + 1) & state.options.generationMask\n\n // freeList stores raw idx (not packed); createEntity packs on re-use\n state.freeList.push(idx)\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 const idx = eid & state.options.indexMask\n if (idx <= 0) return false\n if (idx >= state.capacity) return false\n const archId = state.entityArchetype[idx] ?? 0\n const arch = state.archetypes[archId]\n if (!arch) return false\n if (!arch.entityRow.has(eid)) return false\n // Generation comparison: packed eid must match stored generation\n const storedGen = state.generations[idx] ?? 0\n const refGen = (eid >>> state.options.indexBits) & state.options.generationMask\n return storedGen === refGen\n}\n\n/**\n * Extract the index portion of a packed entity ID.\n *\n * Uses the default 24-bit index layout. If you created the world with a\n * non-default `indexBits`, use `EntityRef` + `deref` instead.\n */\nexport function getEntityIndex(eid: EntityId): number {\n return (eid as number) & DEFAULT_INDEX_MASK\n}\n\n/**\n * Extract the generation portion of a packed entity ID.\n *\n * Uses the default 8-bit generation layout. If you created the world with a\n * non-default `generationBits`, use `EntityRef` + `deref` instead.\n */\nexport function getEntityGeneration(eid: EntityId): number {\n return ((eid as number) >>> DEFAULT_INDEX_BITS) & DEFAULT_GENERATION_MASK\n}\n\n/**\n * Pack an index and generation into an EntityId using the default 24/8 bit layout.\n *\n * Uses the default `indexBits=24, generationBits=8`. If you created the world\n * with non-default bit sizes, this will produce values with incorrect layout.\n * Use `EntityRef` and `deref` for portable cross-world identity matching.\n */\nexport function packEntity(index: number, generation: number): EntityId {\n return (((generation & DEFAULT_GENERATION_MASK) << DEFAULT_INDEX_BITS) |\n (index & DEFAULT_INDEX_MASK)) 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 as number, component, initial)\n return\n }\n const newMask = cloneMask(prevMask)\n setBit(newMask, bit)\n migrateEntity(state, eid as number, newMask)\n\n writeInitial(state, eid as number, 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 as number, newMask)\n\n fireRemoveObservers(state, eid, bit)\n\n const idx = (eid as number) & state.options.indexMask\n const storage = state.componentStorageByBit[bit]\n if (storage?.kind === 'soa' && storage.soa) {\n clearSoAEntity(storage.soa, info.fields, idx)\n } else if (storage?.kind === 'aos' && storage.aos) {\n storage.aos[idx] = 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') {\n const idx = (eid as number) & state.options.indexMask\n return storage.aos?.[idx]\n }\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 as number, component, value as any)\n fireSetObservers(state, eid, bit, value)\n}\n\n// --- Internals ---\n\nfunction writeInitial(\n state: WorldState,\n packedEid: 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 // Unpack to raw index for storage access\n const idx = packedEid & state.options.indexMask\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[idx] = typeof val === 'boolean' ? (val ? 1 : 0) : Number(val)\n } else if (Array.isArray(val) || ArrayBuffer.isView(val)) {\n const base = idx * 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[idx]\n if (inst === undefined) {\n inst = factory()\n storage.aos[idx] = 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) & state.options.indexMask\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, packedEid: number, newMask: Uint32Array): void {\n // Unpack to raw index for sparse-array lookups\n const idx = packedEid & state.options.indexMask\n const srcArchId = state.entityArchetype[idx] ?? 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 (arch.entities / entityRow use packed eid as key)\n const row = srcArch.entityRow.get(packedEid)\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(packedEid)\n srcArch.size--\n }\n\n // Append to dest (store packed eid)\n ensureArchetypeCapacity(destArch, destArch.size + 1)\n const newRow = destArch.size\n destArch.entities[newRow] = packedEid\n destArch.entityRow.set(packedEid, newRow)\n destArch.size++\n\n state.entityArchetype[idx] = destArchId\n }\n\n writeEntityMask(state, packedEid, 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\n/**\n * Serialize a world snapshot to a plain JSON-compatible object.\n *\n * Note: `EntityRef` is in-memory only — not preserved across serialize/deserialize.\n * Generation counters reset on world load. Stale refs from before serialization\n * will deref to null after loading the snapshot into a new world.\n */\nexport function toJSON(world: World): WorldSnapshot {\n const state = getWorldState(world)\n const entities: WorldSnapshot['entities'] = []\n // Iterate by raw slot index; snapshot stores raw idx in the `eid` field\n // (wire format unchanged — idx is used for load-side entity re-creation).\n for (let idx = 1; idx < state.capacity; idx++) {\n const archId = state.entityArchetype[idx] ?? 0\n if (archId === 0) continue // slot unused\n\n const arch = state.archetypes[archId]\n if (!arch) continue\n\n // Build the packed eid from idx + current generation to do alive check\n const gen = state.generations[idx] ?? 0\n const packedEid =\n ((gen & state.options.generationMask) << state.options.indexBits) |\n (idx & state.options.indexMask)\n if (!arch.entityRow.has(packedEid)) continue\n\n const w = state.options.maskWordCount\n const base = idx * 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[idx]\n } else {\n const arr: number[] = []\n const baseI = idx * 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[idx] ?? 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 // Wire format stores raw idx (not packed) for cross-session portability\n entities.push({ eid: idx, 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"]}
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"serialize.cjs"}
package/dist/serialize.js CHANGED
@@ -1,2 +1,2 @@
1
- function j(n){return new Uint32Array(n)}function z(n,t){let o=t>>>5;n[o]=(n[o]??0)|1<<(t&31);}function T(n,t){let o=t>>>5;return ((n[o]??0)&1<<(t&31))!==0}function g(n){let t=new Uint32Array(n.length);for(let o=0;o<n.length;o++)t[o]=n[o]??0;return t}function W(n){let t=[];for(let o=0;o<n.length;o++)t.push((n[o]??0).toString(16));return t.join(",")}var x="0.3.0";var k={initialCapacity:1024,maxEntities:1e6,indexBits:24,generationBits:8},nt=256,et=1,D=new Map;function p(n){let t=D.get(n.id);if(!t)throw new Error(`aiecsjs: world ${n.id} is destroyed or unknown`);if(t.destroyed)throw new Error(`aiecsjs: world ${n.id} is destroyed`);return t}function ot(n){D.set(n.id,n);}function rt(n){let t=n??{},o=t.indexBits??k.indexBits,e=t.generationBits??k.generationBits,r=nt;if(o<1||o>24)throw new Error("aiecsjs: indexBits must be in [1, 24]");if(e<0||e>16)throw new Error("aiecsjs: generationBits must be in [0, 16]");let i=1<<o,s=Math.max(1,Math.min(t.initialCapacity??k.initialCapacity,i)),a=Math.max(s,Math.min(t.maxEntities??k.maxEntities,i));return {initialCapacity:s,maxEntities:a,indexBits:o,generationBits:e,indexMask:(1<<o)-1,generationMask:e===0?0:(1<<e)-1,maxComponents:r,maskWordCount:Math.ceil(r/32),buffer:t.buffer??null,bufferByteOffset:t.bufferByteOffset??0}}function it(n,t){return {id:0,mask:j(n),size:0,capacity:16,entities:new Uint32Array(16),entityRow:new Map,componentBits:[],edgeAdd:new Int32Array(t).fill(-1),edgeRemove:new Int32Array(t).fill(-1)}}function F(n){let t=rt(n),o=et++,e=t.generationBits>8?Uint16Array:Uint8Array,r=new e(t.initialCapacity),i={id:o,capacity:t.initialCapacity,version:x,options:t,size:0,nextFreshIndex:1,freeList:[],generations:r,destroyed:false,componentBitFor:new Map,componentInfoByBit:new Array(t.maxComponents).fill(null),componentStorageByBit:new Array(t.maxComponents).fill(null),nextComponentBit:0,entityArchetype:new Uint32Array(t.initialCapacity),entityMask:new Uint32Array(t.initialCapacity*t.maskWordCount),archetypes:[],archetypeByMaskHash:new Map,queryVersion:0,queries:[],queryMasks:new Map,queryArchetypeCache:[],queryArchetypeStamp:[],bitToQueries:new Map,reactiveBuffers:new Map,observers:[],relationStorage:new Map,sab:t.buffer,readOnly:false},s=it(t.maskWordCount,t.maxComponents);return s.id=0,i.archetypes.push(s),i.archetypeByMaskHash.set(W(s.mask),0),ot(i),st(i)}function st(n){return {id:n.id,get capacity(){return n.capacity},version:n.version}}function N(n,t){if(t<=n.capacity)return;if(t>n.options.maxEntities)throw new Error(`aiecsjs: requested capacity ${t} exceeds maxEntities ${n.options.maxEntities}`);let o=n.capacity;for(;o<t;)o=Math.min(o*2,n.options.maxEntities);at(n,o);}function at(n,t){let o=n.generations.constructor,e=new o(t);e.set(n.generations),n.generations=e;let r=new Uint32Array(t);r.set(n.entityArchetype),n.entityArchetype=r;let i=n.options.maskWordCount,s=new Uint32Array(t*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&&ct(a.soa,c.fields,t);}else a.kind==="aos"&&a.aos&&(a.aos.length=t);n.capacity=t;}function ct(n,t,o){for(let e of t){let r=n[e.name];if(!r)continue;let i=o*e.vectorLen;if(r.length>=i)continue;let s=new e.ctor(i);s.set(r),n[e.name]=s;}}function P(n,t){let o=W(t),e=n.archetypeByMaskHash.get(o);if(e!==void 0)return {archId:e,created:false};let r=n.archetypes.length,i={id:r,mask:g(t),size:0,capacity:16,entities:new Uint32Array(16),entityRow:new Map,componentBits:dt(t),edgeAdd:new Int32Array(n.options.maxComponents).fill(-1),edgeRemove:new Int32Array(n.options.maxComponents).fill(-1)};return n.archetypes.push(i),n.archetypeByMaskHash.set(o,r),n.queryVersion++,{archId:r,created:true}}function C(n,t){if(t<=n.capacity)return;let o=n.capacity;for(;o<t;)o*=2;let e=new Uint32Array(o);e.set(n.entities),n.entities=e,n.capacity=o;}function dt(n){let t=[];for(let o=0;o<n.length;o++){let e=n[o]??0;for(;e!==0;){let r=e&-e,i=(o<<5)+(31-Math.clz32(r));t.push(i),e&=e-1;}}return t}function V(n,t){let o=n.componentBitFor.get(t.id);if(o!==void 0)return o;if(n.nextComponentBit>=n.options.maxComponents)throw new Error(`aiecsjs: world reached maxComponents=${n.options.maxComponents}`);let e=n.nextComponentBit++;n.componentBitFor.set(t.id,e),n.componentInfoByBit[e]=t;let r;if(t.kind==="soa"){let i={};for(let s of t.fields)i[s.name]=new s.ctor(n.capacity*s.vectorLen);r={kind:"soa",componentId:t.id,bit:e,soa:i};}else t.kind==="aos"?r={kind:"aos",componentId:t.id,bit:e,aos:new Array(n.capacity)}:r={kind:"tag",componentId:t.id,bit:e};return n.componentStorageByBit[e]=r,e}function $(n,t){let o=n.options.maskWordCount,e=new Uint32Array(o),i=(t&n.options.indexMask)*o;for(let s=0;s<o;s++)e[s]=n.entityMask[i+s]??0;return e}function q(n,t,o){let e=n.options.maskWordCount,i=(t&n.options.indexMask)*e;for(let s=0;s<e;s++)n.entityMask[i+s]=o[s]??0;}function lt(n,t,o){return (t&o.generationMask)<<o.indexBits|n&o.indexMask}function B(n){let t=p(n);if(t.readOnly)throw new Error("aiecsjs: cannot createEntity on a read-only world (worker-attached)");let o;if(t.freeList.length>0)o=t.freeList.pop();else {if(t.nextFreshIndex>=t.options.maxEntities)throw new Error(`aiecsjs: reached maxEntities ${t.options.maxEntities}`);t.nextFreshIndex>=t.capacity&&N(t,t.nextFreshIndex+1),o=t.nextFreshIndex++;}let e=t.generations[o]??0,r=lt(o,e,t.options),i=t.archetypes[0];if(!i)throw new Error("aiecsjs: missing empty archetype");C(i,i.size+1);let s=i.size;i.entities[s]=r,i.entityRow.set(r,s),i.size++,t.entityArchetype[o]=0;let a=t.options.maskWordCount,c=o*a;for(let d=0;d<a;d++)t.entityMask[c+d]=0;return t.size++,r}function G(n,t){let o=p(n);return M(o,t)}function M(n,t){let o=t&n.options.indexMask;if(o<=0||o>=n.capacity)return false;let e=n.entityArchetype[o]??0,r=n.archetypes[e];if(!r||!r.entityRow.has(t))return false;let i=n.generations[o]??0,s=t>>>n.options.indexBits&n.options.generationMask;return i===s}var O=new Map;function J(n){let t=O.get(n.__id);if(!t)throw new Error("aiecsjs: component is not registered (call defineComponent/defineTag/defineObjectComponent)");return t}function U(n,t,o,e){let r=p(n);if(r.readOnly)throw new Error("aiecsjs: cannot mutate a read-only world");if(!M(r,t))throw new Error(`aiecsjs: addComponent on dead entity ${t}`);let i=J(o),s=V(r,i),a=$(r,t);if(T(a,s)){e!==void 0&&H(r,t,o,e);return}let c=g(a);z(c,s),pt(r,t,c),H(r,t,o,e);}function H(n,t,o,e){let r=J(o),i=n.componentBitFor.get(r.id);if(i===void 0)return;let s=n.componentStorageByBit[i];if(!s)return;let a=t&n.options.indexMask;if(r.kind==="soa"&&s.soa){if(e==null)return;let c=e;for(let d of r.fields){if(!(d.name in c))continue;let f=s.soa[d.name];if(!f)continue;let u=c[d.name];if(d.vectorLen===1)f[a]=typeof u=="boolean"?u?1:0:Number(u);else if(Array.isArray(u)||ArrayBuffer.isView(u)){let l=a*d.vectorLen,S=u;for(let m=0;m<d.vectorLen;m++)f[l+m]=Number(S[m]??0);}}}else if(r.kind==="aos"&&s.aos){let c=r.factory??(()=>({})),d=s.aos[a];if(d===void 0&&(d=c(),s.aos[a]=d),e&&typeof e=="object"){let f=e,u=d;for(let l of Object.keys(f))l==="__proto__"||l==="constructor"||l==="prototype"||(u[l]=f[l]);}}}function pt(n,t,o){let e=t&n.options.indexMask,r=n.entityArchetype[e]??0,i=n.archetypes[r];if(!i)return;let a=P(n,o).archId,c=n.archetypes[a];if(c){if(a!==r){let d=i.entityRow.get(t);if(d!==void 0){let u=i.size-1;if(d!==u){let l=i.entities[u]??0;i.entities[d]=l,i.entityRow.set(l,d);}i.entities[u]=0,i.entityRow.delete(t),i.size--;}C(c,c.size+1);let f=c.size;c.entities[f]=t,c.entityRow.set(t,f),c.size++,n.entityArchetype[e]=a;}q(n,t,o);}}function _(n){return O.get(n)}function X(){return Array.from(O.values())}var y="AIEC",Y=1;function Gt(n,t){let o=K(n);return t?.components&&(o.entities=o.entities.map(e=>({eid:e.eid,components:e.components.filter(r=>t.components.some(i=>i.__id===r.id))}))),Q(o)}function Ht(n,t){let o=Z(n,t);return bt(o)}function K(n){let t=p(n),o=[];for(let e=1;e<t.capacity;e++){let r=t.entityArchetype[e]??0;if(r===0)continue;let i=t.archetypes[r];if(!i)continue;let a=((t.generations[e]??0)&t.options.generationMask)<<t.options.indexBits|e&t.options.indexMask;if(!i.entityRow.has(a))continue;let c=t.options.maskWordCount,d=e*c,f=[];for(let u=0;u<c;u++){let l=t.entityMask[d+u]??0;for(;l!==0;){let S=l&-l,m=(u<<5)+(31-Math.clz32(S)),h=t.componentInfoByBit[m];if(h){let b=t.componentStorageByBit[m],A=null;if(h.kind==="soa"&&b?.soa){let E={};for(let w of h.fields){let I=b.soa[w.name];if(I)if(w.vectorLen===1)E[w.name]=I[e];else {let L=[],tt=e*w.vectorLen;for(let v=0;v<w.vectorLen;v++)L.push(I[tt+v]??0);E[w.name]=L;}}A=E;}else h.kind==="aos"&&b?.aos?A=b.aos[e]??null:A=true;f.push({kind:h.kind,id:h.id,data:A});}l&=l-1;}}o.push({eid:e,components:f});}return {version:t.version,capacity:t.capacity,entities:o}}function bt(n){let t=F({initialCapacity:n.capacity}),o=new Map;for(let e of n.entities){let r=B(t);o.set(e.eid,r);}for(let e of n.entities){let r=o.get(e.eid);for(let i of e.components){let s=_(i.id);if(!s)continue;let a=R(s);a&&U(t,r,a,i.data);}}return t}function R(n){if(n.kind==="soa")return {__kind:"soa",__id:n.id,__schema:n.schema??{}};if(n.kind==="aos"){let t=n.factory??(()=>({}));return {__kind:"aos",__id:n.id,__factory:t}}return {__kind:"tag",__id:n.id}}function Q(n){let t=JSON.stringify(n),o=new TextEncoder().encode(t),e=new TextEncoder().encode(x),i=12+e.length+4+o.length,s=new Uint8Array(i),a=new DataView(s.buffer),c=0;return s[c++]=y.charCodeAt(0),s[c++]=y.charCodeAt(1),s[c++]=y.charCodeAt(2),s[c++]=y.charCodeAt(3),a.setUint32(c,Y,true),c+=4,a.setUint32(c,e.length,true),c+=4,s.set(e,c),c+=e.length,a.setUint32(c,o.length,true),c+=4,s.set(o,c),s}function Z(n,t){if(n.length<12)throw new Error("aiecsjs: bytes too short to be a valid snapshot");let o=new DataView(n.buffer,n.byteOffset,n.byteLength);if(n[0]!==y.charCodeAt(0)||n[1]!==y.charCodeAt(1)||n[2]!==y.charCodeAt(2)||n[3]!==y.charCodeAt(3))throw new Error("aiecsjs: invalid magic bytes");let e=4,r=o.getUint32(e,true);e+=4;let i=t?.onUnknownVersion??"throw";if(r!==Y&&i==="throw")throw new Error(`aiecsjs: format version ${r} not supported`);let s=64*1024*1024;if(e+4>n.length)throw new Error("aiecsjs: snapshot truncated before verLen");let a=o.getUint32(e,true);if(e+=4,a>s||e+a>n.length)throw new Error(`aiecsjs: snapshot verLen=${a} out of bounds`);if(e+=a,e+4>n.length)throw new Error("aiecsjs: snapshot truncated before jsonLen");let c=o.getUint32(e,true);if(e+=4,c>s||e+c>n.length)throw new Error(`aiecsjs: snapshot jsonLen=${c} out of bounds`);let d=n.subarray(e,e+c),f=new TextDecoder().decode(d);return JSON.parse(f)}function Jt(n,t){let o={world:n,components:t?.components??X().map(e=>R(e)).filter(Boolean),lastSnapshot:null};return {capture(){let e=K(o.world),r;return o.lastSnapshot?r=At(o.lastSnapshot,e):r=e,o.lastSnapshot=e,Q(r)},apply(e,r){let i=Z(r),s=p(e);for(let a of i.entities)if(!(a.eid>=s.capacity)){if(!G(e,a.eid))for(;s.size<a.eid;)B(e);for(let c of a.components){let d=_(c.id);if(!d)continue;let f=R(d);f&&U(e,a.eid,f,c.data);}}},reset(){o.lastSnapshot=null;}}}function At(n,t){let o=new Map(n.entities.map(r=>[r.eid,r])),e=[];for(let r of t.entities){let i=o.get(r.eid);if(!i){e.push(r);continue}let s=JSON.stringify(i.components),a=JSON.stringify(r.components);s!==a&&e.push(r);}return {version:t.version,capacity:t.capacity,entities:e}}export{Jt as createDeltaSerializer,Ht as deserializeWorld,bt as fromJSON,Gt as serializeWorld,K as toJSON};//# sourceMappingURL=serialize.js.map
1
+ export{e as createDeltaSerializer,b as deserializeWorld,d as fromJSON,a as serializeWorld,c as toJSON}from'./chunk-QOKIEF7C.js';import'./chunk-L5CMKMIP.js';//# sourceMappingURL=serialize.js.map
2
2
  //# sourceMappingURL=serialize.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/internal/bitmask.ts","../src/version.ts","../src/internal/world.ts","../src/internal/entity.ts","../src/internal/component.ts","../src/serialize.ts"],"names":["createMask","wordCount","setBit","mask","bit","w","testBit","cloneMask","src","out","i","maskHash","m","parts","VERSION","DEFAULT_OPTIONS","DEFAULT_MAX_COMPONENTS","nextWorldId","worldRegistry","getWorldState","world","state","registerWorld","resolveOptions","opts","o","indexBits","generationBits","maxComponents","maxByIndex","initialCapacity","maxEntities","createEmptyArchetype","maskWordCount","createWorld","options","resolved","id","generationCtor","generations","empty","makePublicWorld","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","packEid","idx","gen","createEntity","row","entityExists","isAliveInternal","archId","storedGen","refGen","componentInfoById","getComponentInfo","component","addComponent","initial","prevMask","writeInitial","migrateEntity","packedEid","obj","col","val","arr","factory","inst","target","srcArchId","srcArch","destArchId","destArch","lastRow","moved","newRow","getComponentByInternalId","listAllComponents","MAGIC","FORMAT_VERSION","serializeWorld","snapshot","toJSON","c","comp","packBinary","deserializeWorld","bytes","unpackBinary","fromJSON","entities","components","wi","data","baseI","eidMap","handle","getComponentHandle","json","jsonBytes","versionBytes","total","view","off","formatVersion","onUnknown","MAX_FIELD_LEN","verLen","jsonLen","createDeltaSerializer","current","delta","computeDelta","targetWorld","deltaBytes","targetState","e","prev","curr","prevByEid","changed","prevE","prevSig","currSig"],"mappings":"AAEO,SAASA,EAAWC,CAAAA,CAAgC,CACzD,OAAO,IAAI,YAAYA,CAAS,CAClC,CAEO,SAASC,EAAOC,CAAAA,CAAmBC,CAAAA,CAAmB,CAC3D,IAAMC,CAAAA,CAAID,IAAQ,CAAA,CAClBD,CAAAA,CAAKE,CAAC,CAAA,CAAA,CAAKF,EAAKE,CAAC,CAAA,EAAK,GAAM,CAAA,GAAMD,CAAAA,CAAM,IAC1C,CAOO,SAASE,CAAAA,CAAQH,CAAAA,CAAmBC,EAAsB,CAC/D,IAAMC,EAAID,CAAAA,GAAQ,CAAA,CAClB,SAASD,CAAAA,CAAKE,CAAC,CAAA,EAAK,CAAA,EAAM,IAAMD,CAAAA,CAAM,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A,EAASH,EAAQ,IAAA,CAAKJ,CAAC,EACzC,CACA,OAAO,CAAE,OAAA,CAASE,EAAK,OAAA,CAAS,QAAA,CAAUA,EAAK,QAAA,CAAU,QAAA,CAAUE,CAAQ,CAC7E","file":"serialize.js","sourcesContent":["// 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","export const VERSION = '0.3.0'\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 indexMask: (1 << indexBits) - 1,\n generationMask: generationBits === 0 ? 0 : (1 << generationBits) - 1,\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 idx = eid & state.options.indexMask\n const base = idx * 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 idx = eid & state.options.indexMask\n const base = idx * 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, ResolvedWorldOptions, World, WorldState } from './types.js'\nimport { ensureArchetypeCapacity, ensureCapacity, getWorldState } from './world.js'\n\n// --- Default bit layout constants (used by public getEntityIndex / getEntityGeneration / packEntity) ---\n// These use the default 24/8 split. See §4.4 limitation: callers using non-default\n// createWorld({ indexBits, generationBits }) should not rely on these functions for unpacking.\nexport const DEFAULT_INDEX_BITS = 24\nexport const DEFAULT_GENERATION_BITS = 8\nexport const DEFAULT_INDEX_MASK = (1 << DEFAULT_INDEX_BITS) - 1\nexport const DEFAULT_GENERATION_MASK = (1 << DEFAULT_GENERATION_BITS) - 1\n\n// --- Internal pack/unpack helpers (world-options-aware) ---\n\nexport function packEid(idx: number, gen: number, opts: ResolvedWorldOptions): EntityId {\n return (((gen & opts.generationMask) << opts.indexBits) | (idx & opts.indexMask)) as EntityId\n}\n\nexport function unpackIdx(eid: number, opts: ResolvedWorldOptions): number {\n return eid & opts.indexMask\n}\n\nexport function unpackGen(eid: number, opts: ResolvedWorldOptions): number {\n return (eid >>> opts.indexBits) & opts.generationMask\n}\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 idx: number\n if (state.freeList.length > 0) {\n idx = 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 idx = state.nextFreshIndex++\n }\n\n const gen = state.generations[idx] ?? 0\n const eid = packEid(idx, gen, state.options)\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[idx] = 0\n // Reset entityMask row for this idx\n const w = state.options.maskWordCount\n const base = idx * w\n for (let i = 0; i < w; i++) state.entityMask[base + i] = 0\n\n state.size++\n return eid\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 const idx = eid & state.options.indexMask\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[idx] ?? 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[idx] = 0\n const w = state.options.maskWordCount\n const base = idx * w\n for (let i = 0; i < w; i++) state.entityMask[base + i] = 0\n // Bump generation — use generationMask so non-default generationBits wraps correctly\n state.generations[idx] = ((state.generations[idx] ?? 0) + 1) & state.options.generationMask\n\n // freeList stores raw idx (not packed); createEntity packs on re-use\n state.freeList.push(idx)\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 const idx = eid & state.options.indexMask\n if (idx <= 0) return false\n if (idx >= state.capacity) return false\n const archId = state.entityArchetype[idx] ?? 0\n const arch = state.archetypes[archId]\n if (!arch) return false\n if (!arch.entityRow.has(eid)) return false\n // Generation comparison: packed eid must match stored generation\n const storedGen = state.generations[idx] ?? 0\n const refGen = (eid >>> state.options.indexBits) & state.options.generationMask\n return storedGen === refGen\n}\n\n/**\n * Extract the index portion of a packed entity ID.\n *\n * Uses the default 24-bit index layout. If you created the world with a\n * non-default `indexBits`, use `EntityRef` + `deref` instead.\n */\nexport function getEntityIndex(eid: EntityId): number {\n return (eid as number) & DEFAULT_INDEX_MASK\n}\n\n/**\n * Extract the generation portion of a packed entity ID.\n *\n * Uses the default 8-bit generation layout. If you created the world with a\n * non-default `generationBits`, use `EntityRef` + `deref` instead.\n */\nexport function getEntityGeneration(eid: EntityId): number {\n return ((eid as number) >>> DEFAULT_INDEX_BITS) & DEFAULT_GENERATION_MASK\n}\n\n/**\n * Pack an index and generation into an EntityId using the default 24/8 bit layout.\n *\n * Uses the default `indexBits=24, generationBits=8`. If you created the world\n * with non-default bit sizes, this will produce values with incorrect layout.\n * Use `EntityRef` and `deref` for portable cross-world identity matching.\n */\nexport function packEntity(index: number, generation: number): EntityId {\n return (((generation & DEFAULT_GENERATION_MASK) << DEFAULT_INDEX_BITS) |\n (index & DEFAULT_INDEX_MASK)) 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 as number, component, initial)\n return\n }\n const newMask = cloneMask(prevMask)\n setBit(newMask, bit)\n migrateEntity(state, eid as number, newMask)\n\n writeInitial(state, eid as number, 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 as number, newMask)\n\n fireRemoveObservers(state, eid, bit)\n\n const idx = (eid as number) & state.options.indexMask\n const storage = state.componentStorageByBit[bit]\n if (storage?.kind === 'soa' && storage.soa) {\n clearSoAEntity(storage.soa, info.fields, idx)\n } else if (storage?.kind === 'aos' && storage.aos) {\n storage.aos[idx] = 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') {\n const idx = (eid as number) & state.options.indexMask\n return storage.aos?.[idx]\n }\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 as number, component, value as any)\n fireSetObservers(state, eid, bit, value)\n}\n\n// --- Internals ---\n\nfunction writeInitial(\n state: WorldState,\n packedEid: 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 // Unpack to raw index for storage access\n const idx = packedEid & state.options.indexMask\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[idx] = typeof val === 'boolean' ? (val ? 1 : 0) : Number(val)\n } else if (Array.isArray(val) || ArrayBuffer.isView(val)) {\n const base = idx * 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[idx]\n if (inst === undefined) {\n inst = factory()\n storage.aos[idx] = 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) & state.options.indexMask\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, packedEid: number, newMask: Uint32Array): void {\n // Unpack to raw index for sparse-array lookups\n const idx = packedEid & state.options.indexMask\n const srcArchId = state.entityArchetype[idx] ?? 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 (arch.entities / entityRow use packed eid as key)\n const row = srcArch.entityRow.get(packedEid)\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(packedEid)\n srcArch.size--\n }\n\n // Append to dest (store packed eid)\n ensureArchetypeCapacity(destArch, destArch.size + 1)\n const newRow = destArch.size\n destArch.entities[newRow] = packedEid\n destArch.entityRow.set(packedEid, newRow)\n destArch.size++\n\n state.entityArchetype[idx] = destArchId\n }\n\n writeEntityMask(state, packedEid, 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\n/**\n * Serialize a world snapshot to a plain JSON-compatible object.\n *\n * Note: `EntityRef` is in-memory only — not preserved across serialize/deserialize.\n * Generation counters reset on world load. Stale refs from before serialization\n * will deref to null after loading the snapshot into a new world.\n */\nexport function toJSON(world: World): WorldSnapshot {\n const state = getWorldState(world)\n const entities: WorldSnapshot['entities'] = []\n // Iterate by raw slot index; snapshot stores raw idx in the `eid` field\n // (wire format unchanged — idx is used for load-side entity re-creation).\n for (let idx = 1; idx < state.capacity; idx++) {\n const archId = state.entityArchetype[idx] ?? 0\n if (archId === 0) continue // slot unused\n\n const arch = state.archetypes[archId]\n if (!arch) continue\n\n // Build the packed eid from idx + current generation to do alive check\n const gen = state.generations[idx] ?? 0\n const packedEid =\n ((gen & state.options.generationMask) << state.options.indexBits) |\n (idx & state.options.indexMask)\n if (!arch.entityRow.has(packedEid)) continue\n\n const w = state.options.maskWordCount\n const base = idx * 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[idx]\n } else {\n const arr: number[] = []\n const baseI = idx * 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[idx] ?? 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 // Wire format stores raw idx (not packed) for cross-session portability\n entities.push({ eid: idx, 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"]}
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"serialize.js"}
package/dist/worker.cjs CHANGED
@@ -1,2 +1,2 @@
1
- 'use strict';var b="0.3.0";function U(t){return new Uint32Array(t)}function _(t,n){let e=n>>>5;t[e]=(t[e]??0)|1<<(n&31);}function R(t,n){let e=n>>>5;return ((t[e]??0)&1<<(n&31))!==0}function k(t){let n=new Uint32Array(t.length);for(let e=0;e<t.length;e++)n[e]=t[e]??0;return n}function B(t){let n=[];for(let e=0;e<t.length;e++)n.push((t[e]??0).toString(16));return n.join(",")}var S={initialCapacity:1024,maxEntities:1e6,indexBits:24,generationBits:8},nt=256,et=1,A=new Map;function p(t){let n=A.get(t.id);if(!n)throw new Error(`aiecsjs: world ${t.id} is destroyed or unknown`);if(n.destroyed)throw new Error(`aiecsjs: world ${t.id} is destroyed`);return n}function ot(t){A.set(t.id,t);}function rt(t){A.delete(t);}function j(t){return A.has(t)}function it(t){let n=t??{},e=n.indexBits??S.indexBits,o=n.generationBits??S.generationBits,r=nt;if(e<1||e>24)throw new Error("aiecsjs: indexBits must be in [1, 24]");if(o<0||o>16)throw new Error("aiecsjs: generationBits must be in [0, 16]");let i=1<<e,s=Math.max(1,Math.min(n.initialCapacity??S.initialCapacity,i)),c=Math.max(s,Math.min(n.maxEntities??S.maxEntities,i));return {initialCapacity:s,maxEntities:c,indexBits:e,generationBits:o,indexMask:(1<<e)-1,generationMask:o===0?0:(1<<o)-1,maxComponents:r,maskWordCount:Math.ceil(r/32),buffer:n.buffer??null,bufferByteOffset:n.bufferByteOffset??0}}function st(t,n){return {id:0,mask:U(t),size:0,capacity:16,entities:new Uint32Array(16),entityRow:new Map,componentBits:[],edgeAdd:new Int32Array(n).fill(-1),edgeRemove:new Int32Array(n).fill(-1)}}function L(t){let n=it(t),e=et++,o=n.generationBits>8?Uint16Array:Uint8Array,r=new o(n.initialCapacity),i={id:e,capacity:n.initialCapacity,version:b,options:n,size:0,nextFreshIndex:1,freeList:[],generations:r,destroyed:false,componentBitFor:new Map,componentInfoByBit:new Array(n.maxComponents).fill(null),componentStorageByBit:new Array(n.maxComponents).fill(null),nextComponentBit:0,entityArchetype:new Uint32Array(n.initialCapacity),entityMask:new Uint32Array(n.initialCapacity*n.maskWordCount),archetypes:[],archetypeByMaskHash:new Map,queryVersion:0,queries:[],queryMasks:new Map,queryArchetypeCache:[],queryArchetypeStamp:[],bitToQueries:new Map,reactiveBuffers:new Map,observers:[],relationStorage:new Map,sab:n.buffer,readOnly:false},s=st(n.maskWordCount,n.maxComponents);return s.id=0,i.archetypes.push(s),i.archetypeByMaskHash.set(B(s.mask),0),ot(i),at(i)}function at(t){return {id:t.id,get capacity(){return t.capacity},version:t.version}}function T(t){let n=A.get(t.id);!n||n.destroyed||(n.destroyed=true,n.archetypes=[],n.archetypeByMaskHash.clear(),n.componentInfoByBit=[],n.componentStorageByBit=[],n.queries=[],n.queryMasks.clear(),n.queryArchetypeCache=[],n.observers=[],n.relationStorage.clear(),n.reactiveBuffers.clear(),rt(t.id));}function z(t,n){if(n<=t.capacity)return;if(n>t.options.maxEntities)throw new Error(`aiecsjs: requested capacity ${n} exceeds maxEntities ${t.options.maxEntities}`);let e=t.capacity;for(;e<n;)e=Math.min(e*2,t.options.maxEntities);ct(t,e);}function ct(t,n){let e=t.generations.constructor,o=new e(n);o.set(t.generations),t.generations=o;let r=new Uint32Array(n);r.set(t.entityArchetype),t.entityArchetype=r;let i=t.options.maskWordCount,s=new Uint32Array(n*i);s.set(t.entityMask),t.entityMask=s;for(let c of t.componentStorageByBit)if(c)if(c.kind==="soa"&&c.soa){let a=t.componentInfoByBit[c.bit];a&&dt(c.soa,a.fields,n);}else c.kind==="aos"&&c.aos&&(c.aos.length=n);t.capacity=n;}function dt(t,n,e){for(let o of n){let r=t[o.name];if(!r)continue;let i=e*o.vectorLen;if(r.length>=i)continue;let s=new o.ctor(i);s.set(r),t[o.name]=s;}}function D(t,n){let e=B(n),o=t.archetypeByMaskHash.get(e);if(o!==void 0)return {archId:o,created:false};let r=t.archetypes.length,i={id:r,mask:k(n),size:0,capacity:16,entities:new Uint32Array(16),entityRow:new Map,componentBits:ft(n),edgeAdd:new Int32Array(t.options.maxComponents).fill(-1),edgeRemove:new Int32Array(t.options.maxComponents).fill(-1)};return t.archetypes.push(i),t.archetypeByMaskHash.set(e,r),t.queryVersion++,{archId:r,created:true}}function C(t,n){if(n<=t.capacity)return;let e=t.capacity;for(;e<n;)e*=2;let o=new Uint32Array(e);o.set(t.entities),t.entities=o,t.capacity=e;}function ft(t){let n=[];for(let e=0;e<t.length;e++){let o=t[e]??0;for(;o!==0;){let r=o&-o,i=(e<<5)+(31-Math.clz32(r));n.push(i),o&=o-1;}}return n}function F(t,n){let e=t.componentBitFor.get(n.id);if(e!==void 0)return e;if(t.nextComponentBit>=t.options.maxComponents)throw new Error(`aiecsjs: world reached maxComponents=${t.options.maxComponents}`);let o=t.nextComponentBit++;t.componentBitFor.set(n.id,o),t.componentInfoByBit[o]=n;let r;if(n.kind==="soa"){let i={};for(let s of n.fields)i[s.name]=new s.ctor(t.capacity*s.vectorLen);r={kind:"soa",componentId:n.id,bit:o,soa:i};}else n.kind==="aos"?r={kind:"aos",componentId:n.id,bit:o,aos:new Array(t.capacity)}:r={kind:"tag",componentId:n.id,bit:o};return t.componentStorageByBit[o]=r,o}function N(t,n){let e=t.options.maskWordCount,o=new Uint32Array(e),i=(n&t.options.indexMask)*e;for(let s=0;s<e;s++)o[s]=t.entityMask[i+s]??0;return o}function V(t,n,e){let o=t.options.maskWordCount,i=(n&t.options.indexMask)*o;for(let s=0;s<o;s++)t.entityMask[i+s]=e[s]??0;}function pt(t,n,e){return (n&e.generationMask)<<e.indexBits|t&e.indexMask}function P(t){let n=p(t);if(n.readOnly)throw new Error("aiecsjs: cannot createEntity on a read-only world (worker-attached)");let e;if(n.freeList.length>0)e=n.freeList.pop();else {if(n.nextFreshIndex>=n.options.maxEntities)throw new Error(`aiecsjs: reached maxEntities ${n.options.maxEntities}`);n.nextFreshIndex>=n.capacity&&z(n,n.nextFreshIndex+1),e=n.nextFreshIndex++;}let o=n.generations[e]??0,r=pt(e,o,n.options),i=n.archetypes[0];if(!i)throw new Error("aiecsjs: missing empty archetype");C(i,i.size+1);let s=i.size;i.entities[s]=r,i.entityRow.set(r,s),i.size++,n.entityArchetype[e]=0;let c=n.options.maskWordCount,a=e*c;for(let d=0;d<c;d++)n.entityMask[a+d]=0;return n.size++,r}function $(t,n){let e=n&t.options.indexMask;if(e<=0||e>=t.capacity)return false;let o=t.entityArchetype[e]??0,r=t.archetypes[o];if(!r||!r.entityRow.has(n))return false;let i=t.generations[e]??0,s=n>>>t.options.indexBits&t.options.generationMask;return i===s}var G=new Map;function H(t){let n=G.get(t.__id);if(!n)throw new Error("aiecsjs: component is not registered (call defineComponent/defineTag/defineObjectComponent)");return n}function J(t,n,e,o){let r=p(t);if(r.readOnly)throw new Error("aiecsjs: cannot mutate a read-only world");if(!$(r,n))throw new Error(`aiecsjs: addComponent on dead entity ${n}`);let i=H(e),s=F(r,i),c=N(r,n);if(R(c,s)){o!==void 0&&q(r,n,e,o);return}let a=k(c);_(a,s),yt(r,n,a),q(r,n,e,o);}function q(t,n,e,o){let r=H(e),i=t.componentBitFor.get(r.id);if(i===void 0)return;let s=t.componentStorageByBit[i];if(!s)return;let c=n&t.options.indexMask;if(r.kind==="soa"&&s.soa){if(o==null)return;let a=o;for(let d of r.fields){if(!(d.name in a))continue;let l=s.soa[d.name];if(!l)continue;let f=a[d.name];if(d.vectorLen===1)l[c]=typeof f=="boolean"?f?1:0:Number(f);else if(Array.isArray(f)||ArrayBuffer.isView(f)){let u=c*d.vectorLen,W=f;for(let m=0;m<d.vectorLen;m++)l[u+m]=Number(W[m]??0);}}}else if(r.kind==="aos"&&s.aos){let a=r.factory??(()=>({})),d=s.aos[c];if(d===void 0&&(d=a(),s.aos[c]=d),o&&typeof o=="object"){let l=o,f=d;for(let u of Object.keys(l))u==="__proto__"||u==="constructor"||u==="prototype"||(f[u]=l[u]);}}}function yt(t,n,e){let o=n&t.options.indexMask,r=t.entityArchetype[o]??0,i=t.archetypes[r];if(!i)return;let c=D(t,e).archId,a=t.archetypes[c];if(a){if(c!==r){let d=i.entityRow.get(n);if(d!==void 0){let f=i.size-1;if(d!==f){let u=i.entities[f]??0;i.entities[d]=u,i.entityRow.set(u,d);}i.entities[f]=0,i.entityRow.delete(n),i.size--;}C(a,a.size+1);let l=a.size;a.entities[l]=n,a.entityRow.set(n,l),a.size++,t.entityArchetype[o]=c;}V(t,n,e);}}function X(t){return G.get(t)}var y="AIEC",Y=1;function K(t,n){let e=At(t);return kt(e)}function M(t,n){let e=St(t);return gt(e)}function At(t){let n=p(t),e=[];for(let o=1;o<n.capacity;o++){let r=n.entityArchetype[o]??0;if(r===0)continue;let i=n.archetypes[r];if(!i)continue;let c=((n.generations[o]??0)&n.options.generationMask)<<n.options.indexBits|o&n.options.indexMask;if(!i.entityRow.has(c))continue;let a=n.options.maskWordCount,d=o*a,l=[];for(let f=0;f<a;f++){let u=n.entityMask[d+f]??0;for(;u!==0;){let W=u&-u,m=(f<<5)+(31-Math.clz32(W)),h=n.componentInfoByBit[m];if(h){let g=n.componentStorageByBit[m],x=null;if(h.kind==="soa"&&g?.soa){let E={};for(let w of h.fields){let I=g.soa[w.name];if(I)if(w.vectorLen===1)E[w.name]=I[o];else {let O=[],tt=o*w.vectorLen;for(let v=0;v<w.vectorLen;v++)O.push(I[tt+v]??0);E[w.name]=O;}}x=E;}else h.kind==="aos"&&g?.aos?x=g.aos[o]??null:x=true;l.push({kind:h.kind,id:h.id,data:x});}u&=u-1;}}e.push({eid:o,components:l});}return {version:n.version,capacity:n.capacity,entities:e}}function gt(t){let n=L({initialCapacity:t.capacity}),e=new Map;for(let o of t.entities){let r=P(n);e.set(o.eid,r);}for(let o of t.entities){let r=e.get(o.eid);for(let i of o.components){let s=X(i.id);if(!s)continue;let c=xt(s);c&&J(n,r,c,i.data);}}return n}function xt(t){if(t.kind==="soa")return {__kind:"soa",__id:t.id,__schema:t.schema??{}};if(t.kind==="aos"){let n=t.factory??(()=>({}));return {__kind:"aos",__id:t.id,__factory:n}}return {__kind:"tag",__id:t.id}}function kt(t){let n=JSON.stringify(t),e=new TextEncoder().encode(n),o=new TextEncoder().encode(b),i=12+o.length+4+e.length,s=new Uint8Array(i),c=new DataView(s.buffer),a=0;return s[a++]=y.charCodeAt(0),s[a++]=y.charCodeAt(1),s[a++]=y.charCodeAt(2),s[a++]=y.charCodeAt(3),c.setUint32(a,Y,true),a+=4,c.setUint32(a,o.length,true),a+=4,s.set(o,a),a+=o.length,c.setUint32(a,e.length,true),a+=4,s.set(e,a),s}function St(t,n){if(t.length<12)throw new Error("aiecsjs: bytes too short to be a valid snapshot");let e=new DataView(t.buffer,t.byteOffset,t.byteLength);if(t[0]!==y.charCodeAt(0)||t[1]!==y.charCodeAt(1)||t[2]!==y.charCodeAt(2)||t[3]!==y.charCodeAt(3))throw new Error("aiecsjs: invalid magic bytes");let o=4,r=e.getUint32(o,true);o+=4;let i="throw";if(r!==Y&&i==="throw")throw new Error(`aiecsjs: format version ${r} not supported`);let s=64*1024*1024;if(o+4>t.length)throw new Error("aiecsjs: snapshot truncated before verLen");let c=e.getUint32(o,true);if(o+=4,c>s||o+c>t.length)throw new Error(`aiecsjs: snapshot verLen=${c} out of bounds`);if(o+=c,o+4>t.length)throw new Error("aiecsjs: snapshot truncated before jsonLen");let a=e.getUint32(o,true);if(o+=4,a>s||o+a>t.length)throw new Error(`aiecsjs: snapshot jsonLen=${a} out of bounds`);let d=t.subarray(o,o+a),l=new TextDecoder().decode(d);return JSON.parse(l)}var Z=1095320899;function on(t){let n=p(t),e=K(t);if(typeof SharedArrayBuffer>"u"){let r=new ArrayBuffer(e.byteLength);return new Uint8Array(r).set(e),{buffer:r,meta:Q(n)}}let o=new SharedArrayBuffer(e.byteLength);return new Uint8Array(o).set(e),{buffer:o,meta:Q(n)}}function rn(t){Ct(t.meta);let n=new Uint8Array(t.buffer);return M(n)}function sn(t,n){let e=new Uint8Array(t),o=M(e);if(n?.readOnly){let r=p(o);r.readOnly=true;}return o}function an(t){j(t.id)&&T(t);}function Q(t){let n=[];for(let e of t.componentInfoByBit)e&&n.push({id:e.id,kind:e.kind,schema:e.schema});return {magic:Z,formatVersion:1,aiecsjsVersion:b,indexBits:t.options.indexBits,generationBits:t.options.generationBits,maxComponents:t.options.maxComponents,maskWordCount:t.options.maskWordCount,capacity:t.capacity,componentSchemas:n}}function Ct(t){if(t.magic!==Z)throw new Error("aiecsjs: invalid snapshot meta (wrong magic)");if(t.formatVersion!==1)throw new Error(`aiecsjs: unsupported snapshot format version ${t.formatVersion}`)}exports.adoptSnapshot=rn;exports.attachWorld=sn;exports.detachWorld=an;exports.transferableSnapshot=on;//# sourceMappingURL=worker.cjs.map
1
+ 'use strict';var chunkAGHSWLNQ_cjs=require('./chunk-AGHSWLNQ.cjs'),chunk4RPFOVQC_cjs=require('./chunk-4RPFOVQC.cjs');var l=1095320899;function W(r){let e=chunk4RPFOVQC_cjs.i(r),o=chunkAGHSWLNQ_cjs.a(r);if(typeof SharedArrayBuffer>"u"){let n=new ArrayBuffer(o.byteLength);return new Uint8Array(n).set(o),{buffer:n,meta:p(e)}}let t=new SharedArrayBuffer(o.byteLength);return new Uint8Array(t).set(o),{buffer:t,meta:p(e)}}function b(r){m(r.meta);let e=new Uint8Array(r.buffer);return chunkAGHSWLNQ_cjs.b(e)}function S(r,e){let o=new Uint8Array(r),t=chunkAGHSWLNQ_cjs.b(o);if(e?.readOnly){let n=chunk4RPFOVQC_cjs.i(t);n.readOnly=true;}return t}function w(r){chunk4RPFOVQC_cjs.j(r.id)&&chunk4RPFOVQC_cjs.l(r);}function p(r){let e=[];for(let o of r.componentInfoByBit)o&&e.push({id:o.id,kind:o.kind,schema:o.schema});return {magic:l,formatVersion:1,aiecsjsVersion:chunk4RPFOVQC_cjs.a,indexBits:r.options.indexBits,generationBits:r.options.generationBits,maxComponents:r.options.maxComponents,maskWordCount:r.options.maskWordCount,capacity:r.capacity,componentSchemas:e}}function m(r){if(r.magic!==l)throw new Error("aiecsjs: invalid snapshot meta (wrong magic)");if(r.formatVersion!==1)throw new Error(`aiecsjs: unsupported snapshot format version ${r.formatVersion}`)}exports.adoptSnapshot=b;exports.attachWorld=S;exports.detachWorld=w;exports.transferableSnapshot=W;//# sourceMappingURL=worker.cjs.map
2
2
  //# sourceMappingURL=worker.cjs.map