aiecsjs 0.5.9 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/README.md +46 -12
  2. package/README_ZHTW.md +46 -12
  3. package/api.json +171 -48
  4. package/dist/chunk-27JX7WHY.js +2 -0
  5. package/dist/chunk-27JX7WHY.js.map +1 -0
  6. package/dist/chunk-GJ6U2TIU.js +2 -0
  7. package/dist/chunk-GJ6U2TIU.js.map +1 -0
  8. package/dist/chunk-LNZZ4WWC.js +2 -0
  9. package/dist/chunk-LNZZ4WWC.js.map +1 -0
  10. package/dist/chunk-MVBFYRHY.cjs +2 -0
  11. package/dist/chunk-MVBFYRHY.cjs.map +1 -0
  12. package/dist/chunk-NPNWRCB5.cjs +2 -0
  13. package/dist/chunk-NPNWRCB5.cjs.map +1 -0
  14. package/dist/chunk-O4UVAWFU.cjs +2 -0
  15. package/dist/chunk-O4UVAWFU.cjs.map +1 -0
  16. package/dist/commands.cjs +1 -1
  17. package/dist/commands.cjs.map +1 -1
  18. package/dist/commands.d.cts +1 -1
  19. package/dist/commands.d.ts +1 -1
  20. package/dist/commands.js +1 -1
  21. package/dist/commands.js.map +1 -1
  22. package/dist/index.cjs +1 -1
  23. package/dist/index.cjs.map +1 -1
  24. package/dist/index.d.cts +79 -13
  25. package/dist/index.d.ts +79 -13
  26. package/dist/index.js +1 -1
  27. package/dist/index.js.map +1 -1
  28. package/dist/loop.cjs +1 -1
  29. package/dist/loop.cjs.map +1 -1
  30. package/dist/loop.d.cts +12 -0
  31. package/dist/loop.d.ts +12 -0
  32. package/dist/loop.js +1 -1
  33. package/dist/loop.js.map +1 -1
  34. package/dist/observers.cjs +1 -1
  35. package/dist/observers.cjs.map +1 -1
  36. package/dist/observers.d.cts +7 -1
  37. package/dist/observers.d.ts +7 -1
  38. package/dist/observers.js +1 -1
  39. package/dist/observers.js.map +1 -1
  40. package/dist/relations.cjs +1 -1
  41. package/dist/relations.cjs.map +1 -1
  42. package/dist/relations.d.cts +18 -9
  43. package/dist/relations.d.ts +18 -9
  44. package/dist/relations.js +1 -1
  45. package/dist/relations.js.map +1 -1
  46. package/dist/serialize.cjs +1 -1
  47. package/dist/serialize.d.cts +30 -5
  48. package/dist/serialize.d.ts +30 -5
  49. package/dist/serialize.js +1 -1
  50. package/dist/{types-BeVLA7xG.d.cts → types-C6TkQ7HW.d.cts} +33 -0
  51. package/dist/{types-BeVLA7xG.d.ts → types-C6TkQ7HW.d.ts} +33 -0
  52. package/dist/worker.cjs +1 -1
  53. package/dist/worker.cjs.map +1 -1
  54. package/dist/worker.d.cts +10 -3
  55. package/dist/worker.d.ts +10 -3
  56. package/dist/worker.js +1 -1
  57. package/dist/worker.js.map +1 -1
  58. package/llms-full.txt +114 -18
  59. package/llms.txt +1 -0
  60. package/package.json +57 -22
  61. package/dist/chunk-JDV5JZP2.cjs +0 -2
  62. package/dist/chunk-JDV5JZP2.cjs.map +0 -1
  63. package/dist/chunk-OBMQME2P.js +0 -2
  64. package/dist/chunk-OBMQME2P.js.map +0 -1
  65. package/dist/chunk-Q2XLL6YG.cjs +0 -2
  66. package/dist/chunk-Q2XLL6YG.cjs.map +0 -1
  67. package/dist/chunk-USHKPJQG.cjs +0 -2
  68. package/dist/chunk-USHKPJQG.cjs.map +0 -1
  69. package/dist/chunk-XKN3ULCC.js +0 -2
  70. package/dist/chunk-XKN3ULCC.js.map +0 -1
  71. package/dist/chunk-ZZBNE7C5.js +0 -2
  72. package/dist/chunk-ZZBNE7C5.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/version.ts","../src/internal/bitmask.ts","../src/internal/errors.ts","../src/internal/registry.ts","../src/internal/world.ts","../src/internal/component.ts","../src/internal/entity.ts"],"names":["VERSION","createMask","wordCount","setBit","mask","bit","w","clearBit","testBit","cloneMask","src","out","i","maskHash","m","parts","forEachSetBit","base","words","fn","wi","word","ctz32","matchesEntityMask","entityMask","withMask","anyMask","noneMask","anyHasBits","anyHit","wm","am","nm","v","EcsError","message","options","g","IDS_KEY","ids","SHARED_KEY","shared","DEFAULT_OPTIONS","DEFAULT_MAX_COMPONENTS","worldRegistry","getWorldState","world","id","state","getWritableState","registerWorld","unregisterWorld","isWorldRegistered","resolveOptions","opts","o","name","indexBits","generationBits","maxComponents","maxByIndex","initialCapacity","maxEntities","createWorld","resolved","generationCtor","generations","findOrCreateArchetype","makePublicWorld","destroyWorld","resetWorld","arch","storage","k","buf","getWorldSize","getWorldCapacity","ensureCapacity","needed","newCap","growEntityArrays","genCtor","newGen","newArch","newMask","newStamp","info","growSoAColumns","soa","fields","f","old","newLen","next","key","existing","addRow","eid","removeRow","row","last","moved","getOrRegisterComponentBit","readEntityMask","writeEntityMask","tryGetComponentBit","isWorld","x","obj","TYPE_CTOR","componentInfoById","componentInfoByKey","registerComponent","kind","schema","factory","prev","defineComponent","decl","type","vectorLen","t","len","ctor","defineTag","defineObjectComponent","fac","getComponentInfo","component","addComponent","initial","isAliveInternal","idx","prevMask","writeInitial","aosInstance","migrateEntity","notifyMaskChange","removeComponent","clearSoAEntity","hasComponent","getComponent","setComponent","value","col","val","arr","inst","target","aos","clearAllEntityStorages","packedEid","srcArchId","srcArch","destArchId","destArch","registerMaskChangeDispatch","dispatchDestroyMaskChange","before","after","registerObserverDispatch","api","getComponentByInternalId","DEFAULT_INDEX_BITS","DEFAULT_GENERATION_BITS","DEFAULT_INDEX_MASK","DEFAULT_GENERATION_MASK","packEid","gen","unpackIdx","unpackGen","createEntity","placeEntity","ensureEntityAtSlot","s","pos","destroyEntity","owned","cleanupRelationsOnDestroy","entityExists","archId","storedGen","refGen","getEntityIndex","getEntityGeneration","packEntity","index","generation","isEntity","registerObserversAPI","registerRelationsCleanup"],"mappings":"aAAO,IAAMA,CAAAA,CAAU,QCEhB,SAASC,CAAAA,CAAWC,EAAgC,CACzD,OAAO,IAAI,WAAA,CAAYA,CAAS,CAClC,CAEO,SAASC,CAAAA,CAAOC,CAAAA,C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K,SAAA,CAAU,GAAA,CAAI0B,CAAG,CAAA,CAAG,OAAO,MAAA,CAErC,IAAMoF,CAAAA,CAAYrI,CAAAA,CAAM,WAAA,CAAYoF,CAAG,GAAK,CAAA,CACtCkD,CAAAA,CAAUrF,CAAAA,GAAQjD,CAAAA,CAAM,OAAA,CAAQ,SAAA,CAAaA,EAAM,OAAA,CAAQ,cAAA,CACjE,OAAOqI,CAAAA,GAAcC,CACvB,CAQO,SAASC,EAAAA,CAAetF,CAAAA,CAAuB,CACpD,OAAQA,CAAAA,CAAiBoE,CAC3B,CAQO,SAASmB,EAAAA,CAAoBvF,CAAAA,CAAuB,CACzD,OAASA,IAAmBkE,CAAAA,CAAsBG,CACpD,CASO,SAASmB,EAAAA,CAAWC,CAAAA,CAAeC,EAA8B,CAEtE,OAAA,CAAA,CAAWA,EAAarB,CAAAA,GAA4BH,CAAAA,CACjDuB,EAAQrB,CAAAA,IACT,CACJ,CAEO,SAASuB,EAAAA,CAAS9I,CAAAA,CAAc6D,EAA2B,CAChE,OAAI,OAAOA,CAAAA,EAAM,QAAA,CAAiB,KAAA,CAC3BwE,GAAarI,CAAAA,CAAO6D,CAAa,CAC1C,CAOO,SAASkF,EAAAA,CAAqB5B,EAAyB,CAC5DxH,CAAAA,CAAO,KAAA,CAAM,gBAAA,CAAmBwH,EAClC,CAEO,SAAS6B,EAAAA,CAAyB3K,CAAAA,CAAsD,CAC7FsB,CAAAA,CAAO,KAAA,CAAM,gBAAA,CAAmBtB,EAClC,CACA,SAAS+J,EAAAA,CAA0BlI,CAAAA,CAAmBiD,CAAAA,CAAqB,CACzExD,EAAO,KAAA,CAAM,gBAAA,GAAmBO,CAAAA,CAAOiD,CAAG,EAC5C","file":"chunk-NPNWRCB5.cjs","sourcesContent":["export const VERSION = '0.6.0'\n","// Multi-word Uint32 bitmask helpers.\n\nexport function createMask(wordCount: number): Uint32Array {\n return new Uint32Array(wordCount)\n}\n\nexport function setBit(mask: Uint32Array, bit: number): void {\n const w = bit >>> 5\n mask[w] = (mask[w] ?? 0) | (1 << (bit & 31))\n}\n\nexport function clearBit(mask: Uint32Array, bit: number): void {\n const w = bit >>> 5\n mask[w] = (mask[w] ?? 0) & ~(1 << (bit & 31))\n}\n\nexport function testBit(mask: Uint32Array, bit: number): boolean {\n const w = bit >>> 5\n return ((mask[w] ?? 0) & (1 << (bit & 31))) !== 0\n}\n\nexport function copyMask(dst: Uint32Array, src: Uint32Array): void {\n const n = src.length\n for (let i = 0; i < n; i++) dst[i] = src[i] ?? 0\n}\n\nexport function cloneMask(src: Uint32Array): Uint32Array {\n const out = new Uint32Array(src.length)\n for (let i = 0; i < src.length; i++) out[i] = src[i] ?? 0\n return out\n}\n\nexport function maskEquals(a: Uint32Array, b: Uint32Array): boolean {\n const n = a.length\n if (b.length !== n) return false\n for (let i = 0; i < n; i++) if ((a[i] ?? 0) !== (b[i] ?? 0)) return false\n return true\n}\n\nexport function maskHash(m: Uint32Array): string {\n // Stable string key for Map lookups. Hex-joined.\n const parts: string[] = []\n for (let i = 0; i < m.length; i++) {\n parts.push((m[i] ?? 0).toString(16))\n }\n return parts.join(',')\n}\n\nexport function isMaskZero(m: Uint32Array): boolean {\n for (let i = 0; i < m.length; i++) if ((m[i] ?? 0) !== 0) return false\n return true\n}\n\nexport function unionMask(a: Uint32Array, b: Uint32Array): Uint32Array {\n const out = new Uint32Array(a.length)\n for (let i = 0; i < a.length; i++) out[i] = (a[i] ?? 0) | (b[i] ?? 0)\n return out\n}\n\nexport function listBits(mask: Uint32Array): number[] {\n const out: number[] = []\n forEachSetBit(mask, 0, mask.length, (bit) => out.push(bit))\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/**\n * Match a query against a mask stored at word offset `base` of `entityMask`\n * (base 0 for a standalone archetype / entity mask). Reading directly from the\n * parent array avoids a temporary Uint32Array on every observer dispatch.\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 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","// aiecsjs/internal/errors — named error types for the core.\n\n/**\n * Thrown by aiecsjs for invariant violations and misuse, with an\n * `aiecsjs: `-prefixed message:\n *\n * - world: bad or non-integer world options, a destroyed/unknown/missing world,\n * exhausted component slots, capacity overflow, `maxEntities` reached;\n * - read-only (worker-attached) worlds: every mutator — `createEntity`,\n * `destroyEntity`, `addComponent`/`removeComponent`/`setComponent`,\n * `resetWorld`, `addRelation`/`removeRelation`, delta `apply()`;\n * - entities/components: `addComponent`/`setComponent` on a dead entity, an\n * unregistered component (or query component id), an invalid or duplicate\n * component `key`, a non-function or nullish-returning AoS factory;\n * - relations: `addRelation` on a dead source or target, a value that is not a\n * relation handle;\n * - callbacks: a non-function observer handler, `forEachEntity` /\n * `forEachEntityIndexed` / `withCommandBuffer` callback or `pipe` system;\n * - command buffers: an unknown buffer or an unresolved placeholder;\n * - snapshots (`aiecsjs/serialize`, `aiecsjs/worker`): malformed binary\n * headers or bodies, invalid worker meta, an unsupported format version, an\n * unknown component or a component kind/field mismatch.\n *\n * `defineComponent` field-declaration errors and non-Query input to the query\n * functions throw `TypeError` instead; `aiecsjs/loop` throws `TypeError` /\n * `RangeError` (it exports no error class).\n *\n * Catch this to distinguish an aiecsjs-originated failure from an unrelated\n * runtime error, instead of string-matching on the message. Mirrors the\n * {@link EntityNotAliveError} class style.\n *\n * @example\n * try {\n * createWorld({ indexBits: 99 })\n * } catch (err) {\n * if (err instanceof EcsError) {\n * // an aiecsjs invariant was violated\n * }\n * }\n */\nexport class EcsError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message, options)\n this.name = 'EcsError'\n }\n}\n","import { VERSION } from '../version.js'\nimport type { MaskChangeFn, ObserversDispatchAPI } from './component.js'\nimport type { ObserversAPI } from './entity.js'\nimport type { ComponentInfo, EntityId, QueryInternal, Relation, WorldState } from './types.js'\n\n// Process-wide registries, kept on globalThis rather than in module scope.\n//\n// The package ships separate ESM and CJS builds (and apps can end up with\n// duplicated bundles), so several copies of this code can be loaded into one\n// process. With module-level registries every copy started its counters at 1:\n// a component defined through one copy silently resolved to a DIFFERENT\n// component in another (same id), and world / query ids collided the same way.\n//\n// - `ids` — version-agnostic id counters shared by every copy of any\n// version, so ids never collide across copies. A handle a copy's own\n// registry does not know then fails loudly instead of aliasing.\n// - `shared` — the registries and cross-module dispatch hooks, keyed by the\n// exact VERSION (their shapes are internal and may change between\n// releases), so copies of the same release interoperate fully.\n\ninterface IdCounters {\n component: number\n query: number\n world: number\n relation: number\n}\n\ninterface SharedRegistry {\n componentInfoById: Map<number, ComponentInfo>\n // stable component key (defineComponent/defineTag/defineObjectComponent\n // `options.key`) → component\n componentInfoByKey: Map<string, ComponentInfo>\n queryCache: Map<string, QueryInternal>\n // source query id → its enter/exit variants\n reactiveBySource: Map<number, QueryInternal[]>\n // component id → source queries (with a reactive variant) that reference it\n reactiveSourcesByComponent: Map<number, QueryInternal[]>\n worlds: Map<number, WorldState>\n childOf: Relation | null\n hooks: {\n observerDispatch: ObserversDispatchAPI | null\n maskChange: MaskChangeFn | null\n destroyObservers: ObserversAPI | null\n relationsCleanup: ((state: WorldState, eid: EntityId) => void) | null\n }\n}\n\nconst g = globalThis as unknown as Record<symbol, unknown>\n\nconst IDS_KEY = Symbol.for('aiecsjs.ids')\ng[IDS_KEY] ??= { component: 1, query: 1, world: 1, relation: 1 } satisfies IdCounters\nexport const ids = g[IDS_KEY] as IdCounters\n\nconst SHARED_KEY = Symbol.for(`aiecsjs.registry@${VERSION}`)\ng[SHARED_KEY] ??= {\n componentInfoById: new Map(),\n componentInfoByKey: new Map(),\n queryCache: new Map(),\n reactiveBySource: new Map(),\n reactiveSourcesByComponent: new Map(),\n worlds: new Map(),\n childOf: null,\n hooks: {\n observerDispatch: null,\n maskChange: null,\n destroyObservers: null,\n relationsCleanup: null,\n },\n} satisfies SharedRegistry\nexport const shared = g[SHARED_KEY] as SharedRegistry\n","import { VERSION } from '../version.js'\nimport { cloneMask, createMask, maskHash } from './bitmask.js'\nimport { EcsError } from './errors.js'\nimport { ids, shared } from './registry.js'\nimport type {\n ArchetypeState,\n ComponentInfo,\n FieldInfo,\n ResolvedWorldOptions,\n SoAColumns,\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\n// Shared across every loaded copy of the package (see registry.ts).\nconst worldRegistry = shared.worlds\n\n// destroyWorld unregisters a world in the same call that marks it destroyed,\n// so a registered state is always live. `world?.id` keeps a missing handle on\n// the EcsError path instead of leaking a TypeError.\nexport function getWorldState(world: World): WorldState {\n const id = world?.id\n const state = worldRegistry.get(id)\n if (!state) throw new EcsError(`aiecsjs: world ${id} is destroyed or unknown`)\n return state\n}\n\n// getWorldState for a mutator: rejects a read-only (worker-attached) world.\nexport function getWritableState(world: World): WorldState {\n const state = getWorldState(world)\n if (state.readOnly) throw new EcsError('aiecsjs: cannot mutate a read-only world')\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 // Integer check first: a fractional / NaN / non-number value would otherwise\n // slip through the range checks below and silently truncate typed arrays.\n for (const name of Object.keys(DEFAULT_OPTIONS) as (keyof typeof DEFAULT_OPTIONS)[]) {\n const v = o[name]\n if (v !== undefined && !Number.isInteger(v)) {\n throw new EcsError(`aiecsjs: ${name} must be an integer`)\n }\n }\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 EcsError('aiecsjs: indexBits must be in [1, 24]')\n }\n if (generationBits < 0 || generationBits > 16) {\n throw new EcsError('aiecsjs: generationBits must be in [0, 16]')\n }\n if (indexBits + generationBits > 32) {\n throw new EcsError(\n `aiecsjs: indexBits (${indexBits}) + generationBits (${generationBits}) must be <= 32`,\n )\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\n/**\n * Create an ECS world. `initialCapacity`, `maxEntities`, `indexBits` and\n * `generationBits` must be integers when given (`EcsError` otherwise); they are\n * then range-checked (`indexBits` 1–24, `generationBits` 0–16, sum <= 32) and\n * clamped (`initialCapacity` to [1, 2^indexBits], `maxEntities` to\n * [initialCapacity, 2^indexBits]).\n */\nexport function createWorld(options?: WorldOptions): World {\n const resolved = resolveOptions(options)\n const id = ids.world++\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 destroying: new Set<number>(),\n removing: new Set<number>(),\n visitStamp: new Uint32Array(0),\n visitEpoch: 0,\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 findOrCreateArchetype(state, createMask(resolved.maskWordCount))\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. Post-dispose ops already throw via\n // getWorldState (state.destroyed), so releasing internal state can't regress\n // live behaviour; the capacity getter closure in makePublicWorld is the only\n // thing pinning `state`, so we must drop the big per-entity arrays here or\n // they survive as long as the (typically retained) public world handle.\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 // Release the remaining large per-entity arrays / indices that the original\n // \"clear large buffers\" pass left allocated (these dominate memory for big\n // worlds). Swap to length-0 instances rather than mutating in place.\n state.entityMask = new Uint32Array(0)\n state.entityArchetype = new Uint32Array(0)\n state.visitStamp = new Uint32Array(0)\n state.generations = new Uint8Array(0)\n state.freeList = []\n state.destroying.clear()\n state.componentBitFor.clear()\n state.bitToQueries.clear()\n state.queryArchetypeStamp = []\n state.sab = null\n unregisterWorld(state.id)\n}\n\n/**\n * Wipe every entity, its component data and relation edges while keeping the\n * world's capacity and registered components (e.g. for hot module reload).\n * Throws `EcsError` on a read-only (worker-attached) world, like every other\n * mutator.\n */\nexport function resetWorld(world: World): void {\n const state = getWritableState(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 // Abort any destroyEntity in flight (a teardown handler called resetWorld):\n // the outer call sees its eid gone from this set and skips its own teardown.\n state.destroying.clear()\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 // Clear relation edges, exactly as destroyWorld does. relationStorage is keyed\n // by raw slot index; resetWorld restarts nextFreshIndex=1 and zeroes generations,\n // so recycled slots would otherwise inherit the prior occupant's relation edges\n // and data (C5). Storage is recreated lazily on the next addRelation.\n state.relationStorage.clear()\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 EcsError(\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 = state.generations.constructor as new (len: number) => Uint8Array | Uint16Array\n const newGen = new genCtor(newCap)\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 // visit stamps (allocated lazily by the first forEachEntity pass); copied so\n // a pass that grows the world mid-loop keeps its stamps\n if (state.visitStamp.length > 0) {\n const newStamp = new Uint32Array(newCap)\n newStamp.set(state.visitStamp)\n state.visitStamp = newStamp\n }\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: SoAColumns, 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 }\n state.archetypes.push(arch)\n state.archetypeByMaskHash.set(key, id)\n state.queryVersion++\n return { archId: id, created: true }\n}\n\n// Append `eid` as the last row of `arch`, doubling its row storage when full.\nexport function addRow(arch: ArchetypeState, eid: number): void {\n if (arch.size === arch.capacity) {\n arch.capacity *= 2\n const next = new Uint32Array(arch.capacity)\n next.set(arch.entities)\n arch.entities = next\n }\n arch.entities[arch.size] = eid\n arch.entityRow.set(eid, arch.size++)\n}\n\n// Swap-pop `eid`'s row out of `arch`: the last row moves into the freed one\n// and the vacated tail slot is zeroed. No-op when `eid` has no row here.\nexport function removeRow(arch: ArchetypeState, eid: number): void {\n const row = arch.entityRow.get(eid)\n if (row === undefined) return\n const last = --arch.size\n const moved = arch.entities[last] ?? 0\n arch.entities[row] = moved\n arch.entityRow.set(moved, row)\n arch.entities[last] = 0\n arch.entityRow.delete(eid)\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 EcsError(`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: SoAColumns = {}\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 { clearBit, cloneMask, forEachSetBit, setBit, testBit } from './bitmask.js'\nimport { isAliveInternal } from './entity.js'\nimport { EcsError } from './errors.js'\nimport { ids, shared } from './registry.js'\nimport type {\n AoSComponent,\n ComponentInfo,\n ComponentInit,\n ComponentLike,\n EntityId,\n FieldInfo,\n SoAColumns,\n SoAComponent,\n SoAFieldDecl,\n SoAFieldType,\n SoASchema,\n TagComponent,\n TypedArrayConstructor,\n World,\n WorldComponentStorage,\n WorldState,\n} from './types.js'\nimport {\n addRow,\n findOrCreateArchetype,\n getOrRegisterComponentBit,\n getWorldState,\n getWritableState,\n readEntityMask,\n removeRow,\n tryGetComponentBit,\n writeEntityMask,\n} from './world.js'\n\n// --- Component factories ---\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\n// Shared across every loaded copy of the package (see registry.ts).\nconst componentInfoById = shared.componentInfoById\nconst componentInfoByKey = shared.componentInfoByKey\n\n// Register a component definition under a fresh id and, when `options.key` is\n// given, under that stable serialization key. The key is validated before the\n// id counter or either registry is touched.\nfunction registerComponent(\n options: { key?: string } | undefined,\n kind: ComponentInfo['kind'],\n schema: SoASchema | null = null,\n fields: FieldInfo[] = [],\n factory: (() => unknown) | null = null,\n): number {\n const key = options?.key\n if (key !== undefined) {\n if (typeof key !== 'string' || key === '') {\n throw new EcsError('aiecsjs: component key must be a non-empty string')\n }\n // Re-running a definition (HMR, editor script reload) with the same kind\n // and field layout returns the existing component; the newest AoS factory\n // wins. A different layout under the same key is a real collision.\n const prev = componentInfoByKey.get(key)\n if (prev) {\n if (\n prev.kind !== kind ||\n prev.fields.length !== fields.length ||\n prev.fields.some(\n (f, i) =>\n f.name !== fields[i]!.name ||\n f.type !== fields[i]!.type ||\n f.vectorLen !== fields[i]!.vectorLen,\n )\n ) {\n throw new EcsError(\n `aiecsjs: component key \"${key}\" is already defined with a different layout`,\n )\n }\n if (factory) prev.factory = factory\n return prev.id\n }\n }\n const id = ids.component++\n const info: ComponentInfo = { id, key: key ?? null, kind, schema, fields, factory }\n componentInfoById.set(id, info)\n if (key !== undefined) componentInfoByKey.set(key, info)\n return id\n}\n\n/**\n * Declare a Structure-of-Arrays component.\n *\n * `options.key` gives the component a stable identity for snapshots: loaders\n * match snapshot data to components by key (by creation-order id when keyless),\n * so a keyed component survives a different definition order in the loading\n * process. The key must be a non-empty string. Defining the same key again with\n * the same kind and field layout (a module re-run by HMR or an editor reload)\n * returns the existing component; a different layout throws `EcsError`.\n */\nexport function defineComponent<S extends SoASchema>(\n schema: S,\n options?: { key?: string },\n): SoAComponent<S> {\n const fields: FieldInfo[] = []\n for (const [name, decl] of Object.entries(schema) as [string, SoAFieldDecl][]) {\n let type: SoAFieldType\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({ name, type, vectorLen, ctor })\n }\n return {\n __kind: 'soa',\n __id: registerComponent(options, 'soa', schema, fields),\n __schema: schema,\n }\n}\n\n/** Declare a zero-byte tag component. `options.key`: see {@link defineComponent}. */\nexport function defineTag(options?: { key?: string }): TagComponent {\n return { __kind: 'tag', __id: registerComponent(options, 'tag') }\n}\n\n/**\n * Declare an Array-of-Structures component (one JS object per entity).\n * `options.key`: see {@link defineComponent}.\n */\nexport function defineObjectComponent<T>(\n factory?: () => T,\n options?: { key?: string },\n): AoSComponent<T> {\n if (factory !== undefined && typeof factory !== 'function') {\n throw new EcsError('aiecsjs: factory must be a function')\n }\n const fac = factory ?? (() => ({}) as T)\n return {\n __kind: 'aos',\n __id: registerComponent(options, 'aos', null, [], fac),\n __factory: fac,\n }\n}\n\nexport function getComponentInfo(component: ComponentLike): ComponentInfo {\n const info = componentInfoById.get(component?.__id)\n if (!info)\n throw new EcsError(\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 = getWritableState(world)\n if (!isAliveInternal(state, eid)) {\n throw new EcsError(`aiecsjs: addComponent on dead entity ${eid}`)\n }\n const info = getComponentInfo(component)\n const bit = getOrRegisterComponentBit(state, info)\n\n const idx = (eid as number) & state.options.indexMask\n const prevMask = readEntityMask(state, eid)\n if (testBit(prevMask, bit)) {\n if (initial !== undefined) writeInitial(state, idx, info, bit, initial)\n return\n }\n const newMask = cloneMask(prevMask)\n setBit(newMask, bit)\n // Build the AoS instance before the structural change, so a factory that\n // throws or returns nothing leaves the entity untouched.\n if (info.kind === 'aos') aosInstance(state, idx, info, bit)\n migrateEntity(state, eid as number, newMask)\n\n writeInitial(state, idx, info, bit, initial)\n\n shared.hooks.observerDispatch?.fireAdd(state, eid, bit, prevMask, newMask)\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 = getWritableState(world)\n if (!isAliveInternal(state, eid)) return\n const info = getComponentInfo(component)\n const bit = tryGetComponentBit(state, info)\n if (bit === undefined) return\n if (!testBit(readEntityMask(state, eid), bit)) return\n\n // Component-level onRemove fires BEFORE the mask write, while the component\n // is still attached, so handlers can read the outgoing value with\n // getComponent — the same guarantee destroyEntity gives. The `removing` key\n // makes a nested removeComponent of this same component a no-op (the outer\n // call finishes the removal) instead of re-firing onRemove forever.\n const key = ((eid as number) & state.options.indexMask) * state.options.maxComponents + bit\n if (state.removing.has(key)) return\n state.removing.add(key)\n try {\n shared.hooks.observerDispatch?.fireRemove(state, eid, bit)\n } finally {\n state.removing.delete(key)\n }\n // A handler may have destroyed the entity (destroy already tore the\n // component down) or otherwise dropped the component.\n if (!isAliveInternal(state, eid)) return\n const prevMask = readEntityMask(state, eid)\n if (!testBit(prevMask, bit)) return\n\n // Write the new mask BEFORE firing query observers so they see the\n // post-removal state (and thus correctly detect \"entity left this query\").\n const newMask = cloneMask(prevMask)\n clearBit(newMask, bit)\n migrateEntity(state, eid as number, newMask)\n\n shared.hooks.observerDispatch?.fireRemoveQuery(state, eid, prevMask, newMask)\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 = getWritableState(world)\n if (!isAliveInternal(state, eid))\n throw new EcsError(`aiecsjs: setComponent on dead entity ${eid}`)\n const info = getComponentInfo(component)\n const bit = tryGetComponentBit(state, info)\n if (bit === undefined || !testBit(readEntityMask(state, eid), bit)) {\n // Adding via set\n addComponent(world, eid, component, value as ComponentInit<C>)\n return\n }\n writeInitial(state, (eid as number) & state.options.indexMask, info, bit, value)\n shared.hooks.observerDispatch?.fireSet(state, eid, bit, value)\n}\n\n// --- Internals ---\n\n// Write `initial` into the component storage of slot `idx` (`bit` is the\n// component's registered bit in this world).\nfunction writeInitial(\n state: WorldState,\n idx: number,\n info: ComponentInfo,\n bit: number,\n initial: unknown,\n): void {\n const storage = state.componentStorageByBit[bit]\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') {\n const inst = aosInstance(state, idx, info, bit)\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\n// The AoS instance at slot `idx`, created by the component's factory on first\n// use. A nullish factory result is rejected: the slot would read as absent\n// and a later write of initial data would crash.\nfunction aosInstance(state: WorldState, idx: number, info: ComponentInfo, bit: number): unknown {\n const aos = state.componentStorageByBit[bit]!.aos!\n if (aos[idx] === undefined) {\n // defineObjectComponent always stores a factory for an AoS component.\n const inst = info.factory!()\n if (inst == null) throw new EcsError('aiecsjs: factory result must not be null or undefined')\n aos[idx] = inst\n }\n return aos[idx]\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, append to dest (rows are keyed by packed eid)\n removeRow(srcArch, packedEid)\n addRow(destArch, packedEid)\n state.entityArchetype[idx] = destArchId\n }\n\n writeEntityMask(state, packedEid, newMask)\n}\n\n// --- Observer dispatch (lazy-bound) ---\n\nexport interface ObserversDispatchAPI {\n fireAdd(state: WorldState, eid: EntityId, bit: number, prev: Uint32Array, next: Uint32Array): void\n fireRemove(state: WorldState, eid: EntityId, bit: number): void\n fireRemoveQuery(state: WorldState, eid: EntityId, prev: Uint32Array, next: Uint32Array): void\n fireSet(state: WorldState, eid: EntityId, bit: number, value: unknown): void\n}\nexport type MaskChangeFn = (\n state: WorldState,\n eid: EntityId,\n bit: number,\n prev: Uint32Array,\n next: Uint32Array,\n) => void\nexport function registerMaskChangeDispatch(fn: MaskChangeFn): void {\n shared.hooks.maskChange = fn\n}\nfunction notifyMaskChange(\n state: WorldState,\n eid: number,\n bit: number,\n prev: Uint32Array,\n next: Uint32Array,\n): void {\n shared.hooks.maskChange?.(state, eid as EntityId, bit, prev, next)\n}\n\n// Fire the reactive enter/exit mask-change notification for an entity being\n// destroyed. destroyEntity clears the entity's mask wholesale rather than\n// removing components one-by-one, so it never reaches removeComponent's\n// `notifyMaskChange` call — leaving exitQuery buffers empty on destroy while a\n// component-by-component teardown would have populated them (asymmetric with\n// observe(q,'remove')). We replay the removals here.\n//\n// CORRECTNESS: transition ONE bit at a time through evolving masks, exactly as a\n// sequence of removeComponent() calls would. Passing a single (prevMask, empty)\n// pair once per set bit double-counts — a query matching on several of the\n// entity's components would see wasMatch=true,isMatch=false on every bit and push\n// the same exit N times. Clearing bits incrementally flips wasMatch=false after\n// the first component that breaks each query's match, so every query records\n// exactly one exit.\n//\n// SNAPSHOT DISCIPLINE: `prevMask` is a private copy captured after destroy's\n// teardown handlers ran (their own add/removeComponent calls already recorded\n// those transitions). We iterate that snapshot and mutate only our own clones.\nexport function dispatchDestroyMaskChange(\n state: WorldState,\n eid: EntityId,\n prevMask: Uint32Array,\n): void {\n const w = state.options.maskWordCount\n const before = cloneMask(prevMask) // current bit still set\n const after = cloneMask(prevMask) // current bit cleared\n forEachSetBit(prevMask, 0, w, (bit) => {\n clearBit(after, bit)\n notifyMaskChange(state, eid as number, bit, before, after)\n clearBit(before, bit)\n })\n}\nexport function registerObserverDispatch(api: ObserversDispatchAPI): void {\n shared.hooks.observerDispatch = api\n}\n\n// --- Helper for serialize/worker ---\n\nexport function getComponentByInternalId(id: number): ComponentInfo | undefined {\n return componentInfoById.get(id)\n}\n\nexport function _resetComponentRegistry_FOR_TESTS_ONLY(): void {\n componentInfoById.clear()\n componentInfoByKey.clear()\n ids.component = 1\n}\n","import { clearAllEntityStorages, dispatchDestroyMaskChange } from './component.js'\nimport { EcsError } from './errors.js'\nimport { shared } from './registry.js'\nimport type { EntityId, ResolvedWorldOptions, World, WorldState } from './types.js'\nimport { addRow, ensureCapacity, getWorldState, readEntityMask, removeRow } 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 // `>>> 0` normalises to unsigned: for generation ≥ 128 (default 8-bit gen) the\n // signed `<<`/`|` would yield a negative number that diverges from the unsigned\n // value stored in `arch.entities` (Uint32Array), breaking entityRow lookups for\n // query-iterated high-generation entities. Keep EntityId a non-negative int32.\n return ((((gen & opts.generationMask) << opts.indexBits) | (idx & opts.indexMask)) >>>\n 0) 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 EcsError('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 EcsError(`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 return placeEntity(state, idx)\n}\n\n// Make the free slot `idx` a live, component-less entity in the empty\n// archetype (0) at the slot's current generation; returns its packed id.\nfunction placeEntity(state: WorldState, idx: number): EntityId {\n const eid = packEid(idx, state.generations[idx] ?? 0, state.options)\n const arch = state.archetypes[0]\n if (!arch) throw new EcsError('aiecsjs: missing empty archetype')\n addRow(arch, eid)\n state.entityArchetype[idx] = 0\n state.entityMask.fill(\n 0,\n idx * state.options.maskWordCount,\n (idx + 1) * state.options.maskWordCount,\n )\n state.size++\n return eid\n}\n\n// Ensure a LIVE entity occupies slot `idx`, returning its packed EntityId.\n// Used by delta apply() to materialise a replica entity at the SAME slot the\n// source used (the wire stores raw slot indices), so a source eid keeps\n// addressing the replica by slot. Mirrors createEntity's placement but targets\n// a specific slot:\n// - slot already live -> reuse it (return its current packed id)\n// - slot in the freeList -> reclaim it\n// - slot beyond the frontier -> advance nextFreshIndex, pushing the skipped\n// slots onto the freeList so they remain\n// allocatable (mirrors holes in the source)\n// The slot's CURRENT generation is used (never gen=0), so a replica whose\n// generation has advanced is handled without a dead-entity throw.\nexport function ensureEntityAtSlot(state: WorldState, idx: number): EntityId {\n if (state.readOnly) {\n throw new EcsError('aiecsjs: cannot create entities on a read-only world (worker-attached)')\n }\n if (idx <= 0 || idx >= state.options.maxEntities) {\n /* v8 ignore next — defensive: apply() pre-guards the eid range */\n throw new EcsError(`aiecsjs: slot index ${idx} out of range`)\n }\n if (idx >= state.capacity) ensureCapacity(state, idx + 1)\n\n const gen = state.generations[idx] ?? 0\n const eid = packEid(idx, gen, state.options)\n if (isAliveInternal(state, eid)) return eid // already live — reuse\n\n // Reclaim the free slot.\n if (idx >= state.nextFreshIndex) {\n // Free the slots we skip over so they can still be allocated later.\n for (let s = state.nextFreshIndex; s < idx; s++) state.freeList.push(s)\n state.nextFreshIndex = idx + 1\n } else {\n // Below the frontier, so the slot must be in the freeList — remove it.\n const pos = state.freeList.lastIndexOf(idx)\n if (pos !== -1) {\n const last = state.freeList.length - 1\n state.freeList[pos] = state.freeList[last]!\n state.freeList.pop()\n }\n }\n\n return placeEntity(state, idx)\n}\n\nexport function destroyEntity(world: World, eid: EntityId): void {\n const state = getWorldState(world)\n if (state.readOnly) {\n throw new EcsError('aiecsjs: cannot destroyEntity on a read-only world')\n }\n if (!isAliveInternal(state, eid)) return\n // Reentrancy guard: a teardown handler (onRemove / observe / relation cleanup)\n // that destroys this same entity again is a no-op. Without it the nested call\n // runs a full teardown and the outer call then finishes anyway, pushing the\n // slot onto the freeList twice and double-decrementing size.\n if (state.destroying.has(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 state.destroying.add(eid)\n let owned: boolean\n try {\n shared.hooks.destroyObservers?.dispatchDestroyObservers(state, eid)\n\n // Clean up relations referring to this entity\n cleanupRelationsOnDestroy(state, eid)\n } finally {\n // resetWorld / destroyWorld clear the set, so a missing entry means a\n // handler already wiped this entity's slot.\n owned = state.destroying.delete(eid)\n }\n if (!owned || state.destroyed || !isAliveInternal(state, eid)) return\n\n // Read the mask AFTER teardown handlers ran: component changes they made on\n // this entity (removeComponent / addComponent) already recorded their own\n // reactive enter/exit, so the exit notification below must start from the\n // live mask or those components would be reported twice.\n const prevMask = readEntityMask(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 (isAliveInternal above proved it exists)\n removeRow(state.archetypes[state.entityArchetype[idx] ?? 0]!, eid)\n\n // Notify the REACTIVE enter/exit surface that the entity is leaving every\n // query it was matching. destroyEntity clears the mask wholesale rather than\n // routing through removeComponent, so without this exitQuery buffers stay\n // empty on destroy (asymmetric with observe(q,'remove')). We pass the\n // post-teardown snapshot; the helper computes post-state = empty mask\n // (component absent).\n dispatchDestroyMaskChange(state, eid, prevMask)\n\n // Wipe state\n state.entityArchetype[idx] = 0\n state.entityMask.fill(\n 0,\n idx * state.options.maskWordCount,\n (idx + 1) * state.options.maskWordCount,\n )\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 // `>>> 0` normalises to unsigned — see packEid. Keeps EntityId a non-negative int32.\n return ((((generation & DEFAULT_GENERATION_MASK) << DEFAULT_INDEX_BITS) |\n (index & DEFAULT_INDEX_MASK)) >>>\n 0) 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\nexport interface ObserversAPI {\n dispatchDestroyObservers(state: WorldState, eid: EntityId): void\n}\nexport function registerObserversAPI(api: ObserversAPI): void {\n shared.hooks.destroyObservers = api\n}\n\nexport function registerRelationsCleanup(fn: (state: WorldState, eid: EntityId) => void): void {\n shared.hooks.relationsCleanup = fn\n}\nfunction cleanupRelationsOnDestroy(state: WorldState, eid: EntityId): void {\n shared.hooks.relationsCleanup?.(state, eid)\n}\n"]}
@@ -0,0 +1,2 @@
1
+ 'use strict';var chunkNPNWRCB5_cjs=require('./chunk-NPNWRCB5.cjs');var h=chunkNPNWRCB5_cjs.h.queryCache,w=chunkNPNWRCB5_cjs.h.reactiveBySource,S=chunkNPNWRCB5_cjs.h.reactiveSourcesByComponent;function z(e){let n=t=>(t??[]).map(r=>r.__id).sort((r,o)=>r-o).join("-");return `A${n(e.all)}|Y${n(e.any)}|N${n(e.none)}`}function D(e){let n=Array.isArray(e)?{all:e}:e;for(let i of [...n.all??[],...n.any??[],...n.none??[]])if(!i||typeof i!="object"||typeof i.__id!="number")throw new TypeError("aiecsjs: defineQuery received a non-component value");let t=z(n),r=h.get(t);if(r)return r;let o={id:chunkNPNWRCB5_cjs.g.query++,mask:[],all:(n.all??[]).map(i=>i.__id),any:(n.any??[]).map(i=>i.__id),none:(n.none??[]).map(i=>i.__id),columnViewCache:[...n.all??[],...n.any??[]],reactiveKind:"normal",sourceQueryId:-1,sourceQuery:null};return h.set(t,o),o}function te(e){return L(e,"enter")}function re(e){return L(e,"exit")}function L(e,n){let t=p(e),r=`${n}:${t.id}`,o=h.get(r);if(o)return o;let i={id:chunkNPNWRCB5_cjs.g.query++,mask:[],all:t.all,any:t.any,none:t.none,columnViewCache:t.columnViewCache,reactiveKind:n,sourceQueryId:t.id,sourceQuery:t};return h.set(r,i),U(t,i),i}function U(e,n){let t=w.get(e.id);if(t){t.push(n);return}w.set(e.id,[n]);for(let r of new Set([...e.all,...e.any,...e.none])){let o=S.get(r);o?o.push(e):S.set(r,[e]);}}function p(e){if(Array.isArray(e))return D(e);let n=e,t=n?.reactiveKind;if(t!=="normal"&&t!=="enter"&&t!=="exit")throw new TypeError("aiecsjs: expected a Query");return n}function v(e,n){if(e.queries[n.id]===n&&e.queryMasks.has(n.id))return;let t=[],r=i=>{let c=chunkNPNWRCB5_cjs.b(e.options.maskWordCount);for(let s of i){let u=chunkNPNWRCB5_cjs.q(e,P(s));chunkNPNWRCB5_cjs.c(c,u),t.push(u);}return c},o={withMask:r(n.all),anyMask:r(n.any),noneMask:r(n.none),anyHasBits:n.any.length>0};e.queryMasks.set(n.id,o),e.queries[n.id]=n,e.queryArchetypeCache[n.id]=null,e.queryArchetypeStamp[n.id]=-1;for(let i of t){let c=e.bitToQueries.get(i);c||(c=new Set,e.bitToQueries.set(i,c)),c.add(n.id);}n.reactiveKind!=="normal"&&(e.reactiveBuffers.has(n.id)||e.reactiveBuffers.set(n.id,{entered:[],exited:[]}),n.sourceQuery&&v(e,n.sourceQuery));}function Q(e,n){if(v(e,n),e.queryArchetypeCache[n.id]&&e.queryArchetypeStamp[n.id]===e.queryVersion)return e.queryArchetypeCache[n.id];let t=e.queryMasks.get(n.id),r=[];for(let o=0;o<e.archetypes.length;o++)B(e,t,e.archetypes[o].mask)&&r.push(o);return e.queryArchetypeCache[n.id]=r,e.queryArchetypeStamp[n.id]=e.queryVersion,r}function oe(e,n){let t=chunkNPNWRCB5_cjs.i(e),r=p(n),o=Q(t,r),i=[];for(let c of o){let s=t.archetypes[c];i.push({id:s.id,mask:Array.from(s.mask),size:s.size});}return i}function C(e,n){let t=e.reactiveBuffers.get(n.id);return t?(n.reactiveKind==="enter"?t.entered:t.exited).splice(0):[]}function ie(e,n){let t=chunkNPNWRCB5_cjs.i(e),r=p(n);if(r.reactiveKind!=="normal")return C(t,r);let o=[],i=Q(t,r);for(let c of i){let s=t.archetypes[c];for(let u=0;u<s.size;u++)o.push(s.entities[u]);}return o}function*ce(e,n){let t=chunkNPNWRCB5_cjs.i(e),r=p(n);if(r.reactiveKind!=="normal"){yield*C(t,r);return}let o=Q(t,r);for(let i of o){let c=t.archetypes[i];for(let s=0;s<c.size;s++)yield c.entities[s];}}function ue(e,n,t){$(e,n,t,false);}function se(e,n,t){$(e,n,t,true);}function $(e,n,t,r){let o=chunkNPNWRCB5_cjs.i(e),i=p(n);if(typeof t!="function")throw new chunkNPNWRCB5_cjs.f("aiecsjs: fn must be a function");let c=o.options.indexMask;if(i.reactiveKind!=="normal"){let d=C(o,i);if(d.length===0)return;let f=V(o,i,r);for(let a of d)j(t,a,a&c,f,r);return}let s=Q(o,i),u=V(o,i,r),y=F(o);for(let d of s){let f=o.archetypes[d];for(let a=0;a<f.size;a++){let I=f.entities[a],k=I&c;o.visitStamp[k]!==y&&(o.visitStamp[k]=y,j(t,I,k,u,r),O(o,f.entities[a],I)&&a--);}}}function F(e){return (e.visitStamp.length<e.capacity||e.visitEpoch===4294967295)&&(e.visitStamp=new Uint32Array(e.capacity),e.visitEpoch=0),++e.visitEpoch}function O(e,n,t){return n!==t&&chunkNPNWRCB5_cjs.z(e,t)}function V(e,n,t){let r=q(e,n);return t&&r.unshift(0),r}function j(e,n,t,r,o){switch(o&&(r[0]=t),r.length){case 0:e(n);break;case 1:e(n,r[0]);break;case 2:e(n,r[0],r[1]);break;case 3:e(n,r[0],r[1],r[2]);break;case 4:e(n,r[0],r[1],r[2],r[3]);break;case 5:e(n,r[0],r[1],r[2],r[3],r[4]);break;case 6:e(n,r[0],r[1],r[2],r[3],r[4],r[5]);break;default:e(n,...r);}}function q(e,n){let t=[];for(let r of n.columnViewCache){let o=chunkNPNWRCB5_cjs.J(r),i=e.componentBitFor.get(o.id);if(i===void 0){t.push(void 0);continue}let c=e.componentStorageByBit[i];if(!c){t.push(void 0);continue}c.kind==="soa"?t.push(c.soa):c.kind==="aos"?t.push(c.aos):t.push(true);}return t}function H(e,n,t,r,o){let i=e.componentInfoByBit[t]?.id,c=i===void 0?void 0:S.get(i);if(c)for(let u of c)e.queries[u.id]!==u&&N(e,u)&&v(e,u);let s=e.bitToQueries.get(t);if(s)for(let u of s){let y=e.queries[u];if(!y||y.reactiveKind!=="normal")continue;let d=e.queryMasks.get(u);if(!d)continue;let f=B(e,d,r),a=B(e,d,o);!f&&a?T(e,u,"enter",n):f&&!a&&T(e,u,"exit",n);}}function T(e,n,t,r){let o=w.get(n);if(o)for(let i of o){if(i.reactiveKind!==t)continue;v(e,i);let c=Y(e,i.id);t==="enter"?c.entered.push(r):c.exited.push(r);}}function N(e,n){for(let t of n.all)if(!e.componentBitFor.has(t))return false;if(n.any.length===0)return true;for(let t of n.any)if(e.componentBitFor.has(t))return true;return false}function Y(e,n){let t=e.reactiveBuffers.get(n);return t||(t={entered:[],exited:[]},e.reactiveBuffers.set(n,t)),t}function B(e,n,t){let r=e.options.maskWordCount;return chunkNPNWRCB5_cjs.e(t,0,r,n.withMask,n.anyMask,n.noneMask,n.anyHasBits)}function P(e){let n=chunkNPNWRCB5_cjs.R(e);if(!n)throw new chunkNPNWRCB5_cjs.f(`aiecsjs: component id ${e} not registered`);return n}chunkNPNWRCB5_cjs.P(H);exports.a=D;exports.b=te;exports.c=re;exports.d=p;exports.e=v;exports.f=oe;exports.g=ie;exports.h=ce;exports.i=ue;exports.j=se;//# sourceMappingURL=chunk-O4UVAWFU.cjs.map
2
+ //# sourceMappingURL=chunk-O4UVAWFU.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/internal/query.ts"],"names":["moduleQueryCache","shared","reactiveBySource","reactiveSourcesByComponent","descKey","d","idList","cs","c","a","b","defineQuery","arg","desc","key","cached","q","ids","enterQuery","query","reactiveVariant","exitQuery","kind","asQueryInternal","reactive","indexReactive","source","variants","id","list","ensureQueryRegistered","state","involvedBits","maskOf","compIds","mask","createMask","bit","getOrRegisterComponentBit","getComponentInfoById","setBit","bundle","s","getQueryArchetypes","i","bundleMatches","queryArchetypes","world","getWorldState","out","arch","drainReactive","buf","runQuery","archIds","r","iterQuery","forEachEntity","fn","eachEntity","forEachEntityIndexed","indexed","EcsError","indexMask","src","args","columnArgs","e","callWithArgs","stamp","beginVisitPass","idx","revisitRow","current","isAliveInternal","cols","buildColumnViews","eid","comp","info","getComponentInfo","storage","recordEntityMaskChange","changedBit","prevMask","nextMask","changedId","sources","canMatchIn","involved","qid","wasMatch","isMatch","pushReactive","queryId","ensureReactiveBuffer","words","matchesEntityMask","componentId","getComponentByInternalId","registerMaskChangeDispatch"],"mappings":"mEAyBA,IAAMA,EAAmBC,mBAAAA,CAAO,UAAA,CAC1BC,EAAmBD,mBAAAA,CAAO,gBAAA,CAC1BE,EAA6BF,mBAAAA,CAAO,0BAAA,CAE1C,SAASG,CAAAA,CAAQC,CAAAA,CAA4B,CAC3C,IAAMC,CAAAA,CAAUC,IACbA,CAAAA,EAAM,IACJ,GAAA,CAAKC,CAAAA,EAAMA,EAAE,IAAI,CAAA,CACjB,KAAK,CAACC,CAAAA,CAAGC,IAAMD,CAAAA,CAAIC,CAAC,EACpB,IAAA,CAAK,GAAG,EACb,OAAO,CAAA,CAAA,EAAIJ,EAAOD,CAAAA,CAAE,GAAG,CAAC,CAAA,EAAA,EAAKC,CAAAA,CAAOD,EAAE,GAAG,CAAC,KAAKC,CAAAA,CAAOD,CAAAA,CAAE,IAAI,CAAC,CAAA,CAC/D,CAEO,SAASM,CAAAA,CAAYC,EAA+C,CACzE,IAAMC,EAAwB,KAAA,CAAM,OAAA,CAAQD,CAAG,CAAA,CAAI,CAAE,IAAKA,CAAI,CAAA,CAAIA,EAGlE,IAAA,IAAWJ,CAAAA,IAAK,CAAC,GAAIK,CAAAA,CAAK,KAAO,EAAC,CAAI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E,CAAAA,CAAM,QAAQ,aAAA,CAC5B,OAAOkE,oBAAkB9D,CAAAA,CAAM,CAAA,CAAG6D,EAAOtF,CAAAA,CAAE,QAAA,CAAUA,EAAE,OAAA,CAASA,CAAAA,CAAE,SAAUA,CAAAA,CAAE,UAAU,CAC1F,CAEA,SAAS6B,EAAqB2D,CAAAA,CAAoC,CAChE,IAAMnB,CAAAA,CAAOoB,mBAAAA,CAAyBD,CAAW,CAAA,CACjD,GAAI,CAACnB,CAAAA,CAAM,MAAM,IAAIjB,mBAAAA,CAAS,CAAA,sBAAA,EAAyBoC,CAAW,CAAA,eAAA,CAAiB,CAAA,CACnF,OAAOnB,CACT,CAOAqB,oBAA2BlB,CAAsB,CAAA","file":"chunk-O4UVAWFU.cjs","sourcesContent":["import { createMask, matchesEntityMask, setBit } from './bitmask.js'\nimport {\n getComponentByInternalId,\n getComponentInfo,\n registerMaskChangeDispatch,\n} from './component.js'\nimport { isAliveInternal } from './entity.js'\nimport { EcsError } from './errors.js'\nimport { ids, shared } from './registry.js'\nimport type {\n Archetype,\n ComponentInfo,\n ComponentLike,\n EntityId,\n Query,\n QueryDescriptor,\n QueryInternal,\n QueryMaskBundle,\n ReactiveBuffer,\n World,\n WorldState,\n} from './types.js'\nimport { getOrRegisterComponentBit, getWorldState } from './world.js'\n\n// Shared across every loaded copy of the package (see registry.ts).\nconst moduleQueryCache = shared.queryCache\nconst reactiveBySource = shared.reactiveBySource\nconst reactiveSourcesByComponent = shared.reactiveSourcesByComponent\n\nfunction descKey(d: QueryDescriptor): string {\n const idList = (cs: ComponentLike[] | undefined) =>\n (cs ?? [])\n .map((c) => c.__id)\n .sort((a, b) => a - b)\n .join('-')\n return `A${idList(d.all)}|Y${idList(d.any)}|N${idList(d.none)}`\n}\n\nexport function defineQuery(arg: ComponentLike[] | QueryDescriptor): Query {\n const desc: QueryDescriptor = Array.isArray(arg) ? { all: arg } : arg\n\n // Validate all members are components\n for (const c of [...(desc.all ?? []), ...(desc.any ?? []), ...(desc.none ?? [])]) {\n if (!c || typeof c !== 'object' || typeof (c as { __id?: unknown }).__id !== 'number') {\n throw new TypeError('aiecsjs: defineQuery received a non-component value')\n }\n }\n\n const key = descKey(desc)\n const cached = moduleQueryCache.get(key)\n if (cached) return cached\n\n const q: QueryInternal = {\n id: ids.query++,\n mask: [],\n all: (desc.all ?? []).map((c) => c.__id),\n any: (desc.any ?? []).map((c) => c.__id),\n none: (desc.none ?? []).map((c) => c.__id),\n columnViewCache: [...(desc.all ?? []), ...(desc.any ?? [])],\n reactiveKind: 'normal',\n sourceQueryId: -1,\n sourceQuery: null,\n }\n moduleQueryCache.set(key, q)\n return q\n}\n\n/**\n * Reactive \"entered\" view of `query`: each read drains the entities that began\n * matching since the last read (via `runQuery` / `iterQuery` / `forEachEntity`).\n *\n * **MUST-DRAIN CONTRACT (unbounded buffer).** The enter buffer has **no cap**.\n * Every structural change that makes an entity newly match pushes one id; the\n * buffer only shrinks when you read the reactive view. A view that is created\n * but never read — e.g. a disabled system, or reading only the {@link exitQuery}\n * twin — accumulates one number per event **forever**, an unbounded memory leak\n * at churn rates (e.g. ~1k spawns/frame). Read every enter view you create, once\n * per frame. Dropping ids silently would corrupt enter/exit symmetry, so capping\n * is intentionally not done — draining is the caller's responsibility.\n */\nexport function enterQuery(query: Query): Query {\n return reactiveVariant(query, 'enter')\n}\n\n/**\n * Reactive \"exited\" view of `query`: each read drains the entities that stopped\n * matching since the last read (via `runQuery` / `iterQuery` / `forEachEntity`).\n *\n * **MUST-DRAIN CONTRACT (unbounded buffer).** The exit buffer has **no cap** —\n * same discipline as {@link enterQuery}. An unread exit view accumulates one id\n * per matching structural change (including every `destroyEntity` of a matching\n * entity) without bound. Read every exit view you create, once per frame. Capping\n * is intentionally not done because dropping ids would break enter/exit symmetry.\n */\nexport function exitQuery(query: Query): Query {\n return reactiveVariant(query, 'exit')\n}\n\n// The cached enter/exit variant of `query`. The source goes through\n// asQueryInternal first, so a raw component array works and any other\n// non-Query throws before anything is cached.\nfunction reactiveVariant(query: Query, kind: 'enter' | 'exit'): QueryInternal {\n const q = asQueryInternal(query)\n const key = `${kind}:${q.id}`\n const cached = moduleQueryCache.get(key)\n if (cached) return cached\n const reactive: QueryInternal = {\n id: ids.query++,\n mask: [],\n all: q.all,\n any: q.any,\n none: q.none,\n columnViewCache: q.columnViewCache,\n reactiveKind: kind,\n sourceQueryId: q.id,\n sourceQuery: q,\n }\n moduleQueryCache.set(key, reactive)\n indexReactive(q, reactive)\n return reactive\n}\n\n// Index a new enter/exit variant so structural changes find it without\n// scanning the module query cache: by its source query (pushReactive) and, on\n// the source's first variant, by every component the source references\n// (recordEntityMaskChange).\nfunction indexReactive(source: QueryInternal, reactive: QueryInternal): void {\n const variants = reactiveBySource.get(source.id)\n if (variants) {\n variants.push(reactive)\n return\n }\n reactiveBySource.set(source.id, [reactive])\n for (const id of new Set([...source.all, ...source.any, ...source.none])) {\n const list = reactiveSourcesByComponent.get(id)\n if (list) list.push(source)\n else reactiveSourcesByComponent.set(id, [source])\n }\n}\n\n// Normalise the query argument of every query-taking entry point. A raw\n// component array (`forEachEntity(world, [A, B], fn)`) is routed through\n// defineQuery; anything else that is not a Query throws instead of silently\n// iterating nothing (the reactive branch would look up an undefined buffer).\nexport function asQueryInternal(query: Query): QueryInternal {\n if (Array.isArray(query)) return defineQuery(query as ComponentLike[]) as QueryInternal\n const q = query as QueryInternal\n const kind = q?.reactiveKind\n if (kind !== 'normal' && kind !== 'enter' && kind !== 'exit') {\n throw new TypeError('aiecsjs: expected a Query')\n }\n return q\n}\n\n// --- Per-world query setup ---\n\nexport function ensureQueryRegistered(state: WorldState, q: QueryInternal): void {\n if (state.queries[q.id] === q && state.queryMasks.has(q.id)) return\n\n // Build per-world bitmasks (this may register new bits)\n const involvedBits: number[] = []\n const maskOf = (compIds: number[]): Uint32Array => {\n const mask = createMask(state.options.maskWordCount)\n for (const id of compIds) {\n const bit = getOrRegisterComponentBit(state, getComponentInfoById(id))\n setBit(mask, bit)\n involvedBits.push(bit)\n }\n return mask\n }\n\n const bundle: QueryMaskBundle = {\n withMask: maskOf(q.all),\n anyMask: maskOf(q.any),\n noneMask: maskOf(q.none),\n anyHasBits: q.any.length > 0,\n }\n state.queryMasks.set(q.id, bundle)\n\n state.queries[q.id] = q\n state.queryArchetypeCache[q.id] = null\n state.queryArchetypeStamp[q.id] = -1\n\n // Build bit → queries index for fast reactive lookup\n for (const b of involvedBits) {\n let s = state.bitToQueries.get(b)\n if (!s) {\n s = new Set<number>()\n state.bitToQueries.set(b, s)\n }\n s.add(q.id)\n }\n\n // Initialize reactive buffer for enter/exit queries\n if (q.reactiveKind !== 'normal') {\n if (!state.reactiveBuffers.has(q.id)) {\n state.reactiveBuffers.set(q.id, { entered: [], exited: [] })\n }\n // Also register the source query so recordEntityMaskChange will see it\n if (q.sourceQuery) ensureQueryRegistered(state, q.sourceQuery)\n }\n}\n\nfunction getQueryArchetypes(state: WorldState, q: QueryInternal): number[] {\n ensureQueryRegistered(state, q)\n if (state.queryArchetypeCache[q.id] && state.queryArchetypeStamp[q.id] === state.queryVersion) {\n return state.queryArchetypeCache[q.id]!\n }\n const bundle = state.queryMasks.get(q.id)!\n const list: number[] = []\n for (let i = 0; i < state.archetypes.length; i++) {\n if (bundleMatches(state, bundle, state.archetypes[i]!.mask)) list.push(i)\n }\n state.queryArchetypeCache[q.id] = list\n state.queryArchetypeStamp[q.id] = state.queryVersion\n return list\n}\n\nexport function queryArchetypes(world: World, query: Query): readonly Archetype[] {\n const state = getWorldState(world)\n const q = asQueryInternal(query)\n const ids = getQueryArchetypes(state, q)\n const out: Archetype[] = []\n for (const id of ids) {\n const arch = state.archetypes[id]!\n out.push({ id: arch.id, mask: Array.from(arch.mask), size: arch.size })\n }\n return out\n}\n\n// Drain a reactive (enter/exit) query's buffer. splice(0) empties the live\n// buffer in place and returns the removed entries, so the buffer is drained\n// exactly once up front — a caller that breaks out early, or a callback that\n// throws partway through, never sees those entities re-delivered.\nfunction drainReactive(state: WorldState, q: QueryInternal): EntityId[] {\n const buf = state.reactiveBuffers.get(q.id)\n if (!buf) return []\n return (q.reactiveKind === 'enter' ? buf.entered : buf.exited).splice(0) as EntityId[]\n}\n\nexport function runQuery(world: World, query: Query): readonly EntityId[] {\n const state = getWorldState(world)\n const q = asQueryInternal(query)\n if (q.reactiveKind !== 'normal') return drainReactive(state, q)\n const out: EntityId[] = []\n const archIds = getQueryArchetypes(state, q)\n for (const id of archIds) {\n const arch = state.archetypes[id]!\n for (let r = 0; r < arch.size; r++) {\n out.push(arch.entities[r] as EntityId)\n }\n }\n return out\n}\n\nexport function* iterQuery(world: World, query: Query): IterableIterator<EntityId> {\n const state = getWorldState(world)\n const q = asQueryInternal(query)\n if (q.reactiveKind !== 'normal') {\n yield* drainReactive(state, q)\n return\n }\n const archIds = getQueryArchetypes(state, q)\n for (const id of archIds) {\n const arch = state.archetypes[id]!\n for (let r = 0; r < arch.size; r++) {\n yield arch.entities[r] as EntityId\n }\n }\n}\n\n/**\n * Iterate every entity matching `query`, invoking `fn(e, ...cols)` once per row\n * with the packed {@link EntityId} and the query's SoA column views.\n *\n * **Caution — `e` is a packed EntityId, not a column subscript.** It carries the\n * generation in its high bits, so indexing a column view with it directly\n * (`pos.x[e]`) reads out of bounds once a slot has been recycled. Use `e` only\n * for identity operations (`destroyEntity` / `hasComponent` / `refOf`). To index\n * columns safely, prefer {@link forEachEntityIndexed} — which yields the masked\n * slot index `i` alongside `e` — or mask it yourself with {@link getEntityIndex}.\n *\n * @see {@link forEachEntityIndexed} — same iteration plus the safe column index `i`.\n * @see {@link getEntityIndex} — mask a packed EntityId to its raw slot index.\n */\nexport function forEachEntity(\n world: World,\n query: Query,\n fn: (eid: EntityId, ...cols: any[]) => void,\n): void {\n eachEntity(world, query, fn, false)\n}\n\n/**\n * Like {@link forEachEntity}, but yields the masked column index `i` alongside\n * the packed `EntityId`. The callback signature is `(e, i, ...cols)`:\n *\n * - `e` — the packed EntityId (carries the generation in its high bits). Use\n * it for in-loop `destroyEntity` / `hasComponent` / `refOf`, exactly as with\n * `forEachEntity`.\n * - `i` — `e & indexMask`, the raw slot index. This is the **correct subscript**\n * for SoA column views (`pos.x[i]`), and stays correct after a slot is\n * recycled — where indexing with the packed `e` would read out of bounds.\n * - `...cols` — the same column views `forEachEntity` passes.\n *\n * This closes the packed-EntityId footgun (A1): callers no longer need to call\n * `getEntityIndex(e)` (or hand-mask) themselves to index columns safely.\n */\nexport function forEachEntityIndexed(\n world: World,\n query: Query,\n fn: (e: EntityId, i: number, ...cols: any[]) => void,\n): void {\n eachEntity(world, query, fn as (eid: EntityId, ...args: unknown[]) => void, true)\n}\n\n// Shared body of forEachEntity / forEachEntityIndexed. The indexed form keeps\n// a slot for `i` at the front of the column-view argument list and rewrites it\n// per entity, so both forms share one loop and one zero-allocation call path.\nfunction eachEntity(\n world: World,\n query: Query,\n fn: (eid: EntityId, ...args: unknown[]) => void,\n indexed: boolean,\n): void {\n const state = getWorldState(world)\n const q = asQueryInternal(query)\n // Checked before a reactive buffer is drained, so misuse loses no entities.\n if (typeof fn !== 'function') throw new EcsError('aiecsjs: fn must be a function')\n const indexMask = state.options.indexMask\n\n if (q.reactiveKind !== 'normal') {\n const src = drainReactive(state, q)\n if (src.length === 0) return\n const args = columnArgs(state, q, indexed)\n for (const e of src) callWithArgs(fn, e, e & indexMask, args, indexed)\n return\n }\n\n const archIds = getQueryArchetypes(state, q)\n const args = columnArgs(state, q, indexed)\n const stamp = beginVisitPass(state)\n for (const id of archIds) {\n const arch = state.archetypes[id]!\n // Re-read `arch.size` AND `arch.entities` each iteration (do NOT cache either):\n // - `arch.size`: an in-loop `destroyEntity` swap-pops the visited row, shrinks\n // `arch.size`, and zeroes the freed tail slot. A cached bound would keep\n // walking into those zeroed tail rows and hand back the sentinel eid 0\n // (ECS-B-01). The swapped-in survivor is intentionally skipped this pass.\n // - `arch.entities`: an in-loop create (createEntity / addComponent landing in\n // this archetype) can grow it past capacity, so addRow swaps in a NEW,\n // larger Uint32Array. A cached reference would still point at the OLD\n // shorter array, so its tail rows read `undefined` (C4) — the sentinel\n // leaking across the public callback boundary again (and, for the indexed\n // form, `undefined & indexMask === 0`, a bogus i=0 payload).\n // Both are scalar property reads — no per-iteration allocation, so the\n // zero-allocation hot-path contract holds. Mirrors runQuery / iterQuery.\n // In-loop add/removeComponent moves (see revisitRow) are handled so every\n // matching live entity is visited exactly once per pass.\n for (let r = 0; r < arch.size; r++) {\n const e = arch.entities[r] as EntityId\n const idx = e & indexMask\n if (state.visitStamp[idx] === stamp) continue\n state.visitStamp[idx] = stamp\n callWithArgs(fn, e, idx, args, indexed)\n if (revisitRow(state, arch.entities[r], e)) r--\n }\n }\n}\n\n// Stamp one forEachEntity pass. visitStamp[idx] === stamp marks an entity the\n// pass already visited, so one that an in-loop add/removeComponent moves into\n// an archetype later in the pass is not visited twice. A nested pass takes a\n// fresh stamp; the outer pass then merely loses that dedup for the entities\n// the inner pass touched. No per-pass allocation after the first.\nfunction beginVisitPass(state: WorldState): number {\n // First pass in this world, or the stamp counter is about to wrap: start\n // from a zeroed array.\n if (state.visitStamp.length < state.capacity || state.visitEpoch === 0xffffffff) {\n state.visitStamp = new Uint32Array(state.capacity)\n state.visitEpoch = 0\n }\n return ++state.visitEpoch\n}\n\n// After the callback for `e` at row r: if an in-loop add/removeComponent moved\n// the still-live `e` out of this archetype, the swap-pop put an unvisited\n// entity into row r — revisit it. After an in-loop destroyEntity the\n// swapped-in survivor is still deferred to the next pass (ECS-B-01).\nfunction revisitRow(state: WorldState, current: number | undefined, e: EntityId): boolean {\n return current !== e && isAliveInternal(state, e)\n}\n\n// The per-call argument list after `eid`: the column views, preceded by a\n// slot for the column index `i` in the indexed form.\nfunction columnArgs(state: WorldState, q: QueryInternal, indexed: boolean): unknown[] {\n const cols = buildColumnViews(state, q)\n if (indexed) cols.unshift(0)\n return cols\n}\n\nfunction callWithArgs(\n fn: (eid: EntityId, ...args: unknown[]) => void,\n eid: EntityId,\n i: number,\n args: unknown[],\n indexed: boolean,\n): void {\n if (indexed) args[0] = i\n // Specialise for low arities to avoid spread allocation.\n switch (args.length) {\n case 0:\n fn(eid)\n break\n case 1:\n fn(eid, args[0])\n break\n case 2:\n fn(eid, args[0], args[1])\n break\n case 3:\n fn(eid, args[0], args[1], args[2])\n break\n case 4:\n fn(eid, args[0], args[1], args[2], args[3])\n break\n case 5:\n fn(eid, args[0], args[1], args[2], args[3], args[4])\n break\n case 6:\n fn(eid, args[0], args[1], args[2], args[3], args[4], args[5])\n break\n default:\n fn(eid, ...args)\n }\n}\n\nfunction buildColumnViews(state: WorldState, q: QueryInternal): unknown[] {\n const out: unknown[] = []\n for (const comp of q.columnViewCache) {\n const info = getComponentInfo(comp)\n const bit = state.componentBitFor.get(info.id)\n if (bit === undefined) {\n out.push(undefined)\n continue\n }\n const storage = state.componentStorageByBit[bit]\n if (!storage) {\n out.push(undefined)\n continue\n }\n if (storage.kind === 'soa') out.push(storage.soa)\n else if (storage.kind === 'aos') out.push(storage.aos)\n else out.push(true) // tag\n }\n return out\n}\n\n// --- Reactive query updates (called from migration code) ---\n\nexport function recordEntityMaskChange(\n state: WorldState,\n eid: EntityId,\n changedBit: number,\n prevMask: Uint32Array,\n nextMask: Uint32Array,\n): void {\n // Lazy-register the sources of reactive queries that reference the changed\n // component, so match transitions are tracked even if the user only ever\n // called enterQuery/exitQuery. Only sources that can match in this world\n // are registered: one whose `all` (or entire `any`) components this world\n // has never registered cannot match any of its entities, and registering it\n // would allocate storage (and burn component bits) for foreign components.\n // It is picked up by a later change once those components exist here.\n const changedId = state.componentInfoByBit[changedBit]?.id\n const sources = changedId === undefined ? undefined : reactiveSourcesByComponent.get(changedId)\n if (sources) {\n for (const src of sources) {\n if (state.queries[src.id] === src) continue\n if (canMatchIn(state, src)) ensureQueryRegistered(state, src)\n }\n }\n\n const involved = state.bitToQueries.get(changedBit)\n if (!involved) return\n for (const qid of involved) {\n const q = state.queries[qid]\n if (!q) continue\n if (q.reactiveKind !== 'normal') continue\n const bundle = state.queryMasks.get(qid)\n if (!bundle) continue\n const wasMatch = bundleMatches(state, bundle, prevMask)\n const isMatch = bundleMatches(state, bundle, nextMask)\n if (!wasMatch && isMatch) {\n pushReactive(state, qid, 'enter', eid)\n } else if (wasMatch && !isMatch) {\n pushReactive(state, qid, 'exit', eid)\n }\n }\n}\n\nfunction pushReactive(\n state: WorldState,\n queryId: number,\n kind: 'enter' | 'exit',\n eid: EntityId,\n): void {\n // Use the module-wide variant index (not just state.queries) so reactive\n // variants that haven't been registered with this world yet still receive events.\n const variants = reactiveBySource.get(queryId)\n if (!variants) return\n for (const r of variants) {\n if (r.reactiveKind !== kind) continue\n // Lazily register the reactive query in this world so subsequent reads can find it\n ensureQueryRegistered(state, r)\n const buf = ensureReactiveBuffer(state, r.id)\n if (kind === 'enter') buf.entered.push(eid as number)\n else buf.exited.push(eid as number)\n }\n}\n\n// Whether any entity of this world could match `q` given the components the\n// world has registered: every `all` component, and at least one `any`\n// component when `any` is non-empty. (`none` components need not exist.)\nfunction canMatchIn(state: WorldState, q: QueryInternal): boolean {\n for (const id of q.all) if (!state.componentBitFor.has(id)) return false\n if (q.any.length === 0) return true\n for (const id of q.any) if (state.componentBitFor.has(id)) return true\n return false\n}\n\nfunction ensureReactiveBuffer(state: WorldState, qid: number): ReactiveBuffer {\n let buf = state.reactiveBuffers.get(qid)\n if (!buf) {\n buf = { entered: [], exited: [] }\n state.reactiveBuffers.set(qid, buf)\n }\n return buf\n}\n\n// --- Helpers ---\n\n// Whether a whole-entity (or archetype) mask satisfies a query's masks.\nfunction bundleMatches(state: WorldState, b: QueryMaskBundle, mask: Uint32Array): boolean {\n const words = state.options.maskWordCount\n return matchesEntityMask(mask, 0, words, b.withMask, b.anyMask, b.noneMask, b.anyHasBits)\n}\n\nfunction getComponentInfoById(componentId: number): ComponentInfo {\n const info = getComponentByInternalId(componentId)\n if (!info) throw new EcsError(`aiecsjs: component id ${componentId} not registered`)\n return info\n}\n\n// Wire component mask-change → query reactive update. This lives here rather\n// than in index.ts: the package declares `sideEffects: false`, so a bundler may\n// drop index.js when a consumer imports only re-exported names. Every reactive\n// query is created through this module, so registering here guarantees the\n// hook is live whenever a reactive buffer can exist.\nregisterMaskChangeDispatch(recordEntityMaskChange)\n\nexport function _resetQueryRegistry_FOR_TESTS_ONLY(): void {\n moduleQueryCache.clear()\n reactiveBySource.clear()\n reactiveSourcesByComponent.clear()\n ids.query = 1\n}\n"]}
package/dist/commands.cjs CHANGED
@@ -1,2 +1,2 @@
1
- 'use strict';var chunkQ2XLL6YG_cjs=require('./chunk-Q2XLL6YG.cjs');function l(e){let n={worldId:chunkQ2XLL6YG_cjs.j(e).id,ops:[],nextPlaceholder:-1,flushing:false};return h(n)}function C(e){let o=y(e);if(!o.flushing){o.flushing=true;try{let n=k(o.worldId),r=new Map;for(let t of o.ops)t.kind==="create"&&r.set(t.placeholder,chunkQ2XLL6YG_cjs.v(n));let d=t=>{let i=t;if(i<0){let f=r.get(i);if(f===void 0)throw new Error(`aiecsjs: unresolved placeholder ${i}`);return f}return t};for(let t of o.ops)t.kind==="add"?chunkQ2XLL6YG_cjs.K(n,d(t.eid),t.component,t.initial):t.kind==="remove"&&chunkQ2XLL6YG_cjs.L(n,d(t.eid),t.component);for(let t of o.ops)t.kind==="destroy"&&chunkQ2XLL6YG_cjs.x(n,d(t.eid));o.ops.length=0,o.nextPlaceholder=-1;}finally{o.flushing=false;}}}function b(e,o){let n=l(e),r=o(n);return C(n),r}var p=new WeakMap;function h(e){let o={add(n,r,d){e.ops.push({kind:"add",eid:n,component:r,initial:d});},remove(n,r){e.ops.push({kind:"remove",eid:n,component:r});},destroy(n){e.ops.push({kind:"destroy",eid:n});},create(){let n=e.nextPlaceholder--;return e.ops.push({kind:"create",placeholder:n}),n}};return p.set(o,e),o}function y(e){let o=p.get(e);if(!o)throw new Error("aiecsjs: unknown CommandBuffer");return o}function k(e){let o=B(e);return {id:o.id,capacity:o.capacity,version:o.version}}function B(e){return chunkQ2XLL6YG_cjs.j({id:e,capacity:0,version:"0.0.0"})}exports.createCommandBuffer=l;exports.flush=C;exports.withCommandBuffer=b;//# sourceMappingURL=commands.cjs.map
1
+ 'use strict';var chunkNPNWRCB5_cjs=require('./chunk-NPNWRCB5.cjs');function h(t){let o={worldId:chunkNPNWRCB5_cjs.i(t).id,ops:[],nextPlaceholder:-1,flushing:false};return y(o)}function C(t){let e=B(t);if(!e.flushing){e.flushing=true;try{let o={id:e.worldId};chunkNPNWRCB5_cjs.i(o);let r=new Map,d=f=>{let n=f;if(n<0){let m=r.get(n);if(m===void 0)throw new chunkNPNWRCB5_cjs.f(`aiecsjs: unresolved placeholder ${n}`);return m}return f};for(;e.ops.length>0;){let f=e.ops;e.ops=[];for(let n of f)n.kind==="create"&&r.set(n.placeholder,chunkNPNWRCB5_cjs.v(o));for(let n of f)n.kind==="add"?chunkNPNWRCB5_cjs.K(o,d(n.eid),n.component,n.initial):n.kind==="remove"&&chunkNPNWRCB5_cjs.L(o,d(n.eid),n.component);for(let n of f)n.kind==="destroy"&&chunkNPNWRCB5_cjs.x(o,d(n.eid));}}finally{e.ops.length===0&&(e.nextPlaceholder=-1),e.flushing=false;}}}function I(t,e){if(typeof e!="function")throw new chunkNPNWRCB5_cjs.f("aiecsjs: fn must be a function");let o=h(t),r=e(o);return C(o),r}var l=new WeakMap;function y(t){let e={add(o,r,d){t.ops.push({kind:"add",eid:o,component:r,initial:d});},remove(o,r){t.ops.push({kind:"remove",eid:o,component:r});},destroy(o){t.ops.push({kind:"destroy",eid:o});},create(){let o=t.nextPlaceholder--;return t.ops.push({kind:"create",placeholder:o}),o}};return l.set(e,t),e}function B(t){let e=l.get(t);if(!e)throw new chunkNPNWRCB5_cjs.f("aiecsjs: unknown CommandBuffer");return e}exports.createCommandBuffer=h;exports.flush=C;exports.withCommandBuffer=I;//# sourceMappingURL=commands.cjs.map
2
2
  //# sourceMappingURL=commands.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/commands.ts"],"names":["createCommandBuffer","world","buf","getWorldState","makeApi","flush","cb","state","stateOf","lookupWorld","placeholders","op","createEntity","resolve","eid","num","real","addComponent","removeComponent","destroyEntity","withCommandBuffer","fn","result","cbStateMap","api","component","initial","ph","s","worldId","lookupState"],"mappings":"mEAeO,SAASA,EAAoBC,CAAAA,CAA6B,CAE/D,IAAMC,CAAAA,CAA0B,CAC9B,OAAA,CAFYC,mBAAAA,CAAcF,CAAK,CAAA,CAEhB,GACf,GAAA,CAAK,EAAC,CACN,eAAA,CAAiB,GACjB,QAAA,CAAU,KACZ,CAAA,CACA,OAAOG,EAAQF,CAAG,CACpB,CAEO,SAASG,EAAMC,CAAAA,CAAyB,CAC7C,IAAMC,CAAAA,CAAQC,EAAQF,CAAE,CAAA,CACxB,GAAI,CAAAC,CAAAA,CAAM,SACV,CAAAA,CAAAA,CAAM,QAAA,CAAW,IAAA,CACjB,GAAI,CACF,IAAMN,CAAAA,CAAQQ,CAAAA,CAAYF,EAAM,OAAO,CAAA,CAGjCG,CAAAA,CAAe,IAAI,IACzB,IAAA,IAAWC,CAAAA,IAAMJ,CAAAA,CAAM,GAAA,CACjBI,EAAG,IAAA,GAAS,QAAA,EACdD,CAAAA,CAAa,GAAA,CAAIC,EAAG,WAAA,CAAaC,mBAAAA,CAAaX,CAAK,CAAC,EAIxD,IAAMY,CAAAA,CAAWC,CAAAA,EAA4B,CAC3C,IAAMC,CAAAA,CAAMD,CAAAA,CACZ,GAAIC,CAAAA,CAAM,CAAA,CAAG,CACX,IAAMC,CAAAA,CAAON,CAAAA,CAAa,GAAA,CAAIK,CAAG,CAAA,CACjC,GAAIC,CAAAA,GAAS,KAAA,CAAA,CAAW,MAAM,IAAI,KAAA,CAAM,CAAA,gCAAA,EAAmCD,CAAG,EAAE,CAAA,CAChF,OAAOC,CACT,CACA,OAAOF,CACT,CAAA,CAGA,IAAA,IAAWH,CAAAA,IAAMJ,EAAM,GAAA,CACjBI,CAAAA,CAAG,IAAA,GAAS,KAAA,CACdM,oBACEhB,CAAA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,IAAI,IAAA,CAAK,CAAE,IAAA,CAAM,SAAA,CAAW,IAAAO,CAAI,CAAC,EACzC,CAAA,CACA,MAAA,EAAS,CACP,IAAMa,CAAAA,CAAKpB,CAAAA,CAAM,eAAA,EAAA,CACjB,OAAAA,CAAAA,CAAM,GAAA,CAAI,IAAA,CAAK,CAAE,KAAM,QAAA,CAAU,WAAA,CAAaoB,CAAG,CAAC,EAC3CA,CACT,CACF,CAAA,CACA,OAAAJ,EAAW,GAAA,CAAIC,CAAAA,CAAKjB,CAAK,CAAA,CAClBiB,CACT,CAEA,SAAShB,CAAAA,CAAQF,CAAAA,CAAuC,CACtD,IAAMsB,CAAAA,CAAIL,CAAAA,CAAW,GAAA,CAAIjB,CAAE,CAAA,CAC3B,GAAI,CAACsB,CAAAA,CAAG,MAAM,IAAI,KAAA,CAAM,gCAAgC,CAAA,CACxD,OAAOA,CACT,CAGA,SAASnB,CAAAA,CAAYoB,CAAAA,CAAwB,CAG3C,IAAMtB,CAAAA,CAAQuB,CAAAA,CAAYD,CAAO,EACjC,OAAO,CAAE,GAAItB,CAAAA,CAAM,EAAA,CAAI,SAAUA,CAAAA,CAAM,QAAA,CAAU,OAAA,CAASA,CAAAA,CAAM,OAAQ,CAC1E,CAEA,SAASuB,CAAAA,CAAYD,EAA2D,CAG9E,OAAO1B,mBAAAA,CAAc,CAAE,GAAI0B,CAAAA,CAAS,QAAA,CAAU,EAAG,OAAA,CAAS,OAAQ,CAAU,CAC9E","file":"commands.cjs","sourcesContent":["// aiecsjs/commands — deferred structural mutations during iteration.\n\nimport { addComponent, removeComponent } from './internal/component.js'\nimport { createEntity, destroyEntity } from './internal/entity.js'\nimport type {\n CommandBuffer,\n CommandBufferState,\n CommandOp,\n ComponentInit,\n ComponentLike,\n EntityId,\n World,\n} from './internal/types.js'\nimport { getWorldState } from './internal/world.js'\n\nexport function createCommandBuffer(world: World): CommandBuffer {\n const state = getWorldState(world)\n const buf: CommandBufferState = {\n worldId: state.id,\n ops: [],\n nextPlaceholder: -1,\n flushing: false,\n }\n return makeApi(buf)\n}\n\nexport function flush(cb: CommandBuffer): void {\n const state = stateOf(cb)\n if (state.flushing) return\n state.flushing = true\n try {\n const world = lookupWorld(state.worldId)\n\n // Phase 1: resolve placeholders by creating real entities first\n const placeholders = new Map<number, EntityId>()\n for (const op of state.ops) {\n if (op.kind === 'create') {\n placeholders.set(op.placeholder, createEntity(world))\n }\n }\n\n const resolve = (eid: EntityId): EntityId => {\n const num = eid as number\n if (num < 0) {\n const real = placeholders.get(num)\n if (real === undefined) throw new Error(`aiecsjs: unresolved placeholder ${num}`)\n return real\n }\n return eid\n }\n\n // Phase 2: add/remove in queue order\n for (const op of state.ops) {\n if (op.kind === 'add') {\n addComponent(\n world,\n resolve(op.eid),\n op.component,\n op.initial as ComponentInit<ComponentLike>,\n )\n } else if (op.kind === 'remove') {\n removeComponent(world, resolve(op.eid), op.component)\n }\n }\n\n // Phase 3: destroy last\n for (const op of state.ops) {\n if (op.kind === 'destroy') {\n destroyEntity(world, resolve(op.eid))\n }\n }\n\n state.ops.length = 0\n state.nextPlaceholder = -1\n } finally {\n state.flushing = false\n }\n}\n\nexport function withCommandBuffer<R>(world: World, fn: (cb: CommandBuffer) => R): R {\n const cb = createCommandBuffer(world)\n const result = fn(cb)\n flush(cb)\n return result\n}\n\n// --- Internals ---\n\nconst cbStateMap = new WeakMap<object, CommandBufferState>()\n\nfunction makeApi(state: CommandBufferState): CommandBuffer {\n const api: CommandBuffer = {\n add(eid, component, initial) {\n state.ops.push({ kind: 'add', eid, component, initial })\n },\n remove(eid, component) {\n state.ops.push({ kind: 'remove', eid, component })\n },\n destroy(eid) {\n state.ops.push({ kind: 'destroy', eid })\n },\n create() {\n const ph = state.nextPlaceholder--\n state.ops.push({ kind: 'create', placeholder: ph })\n return ph as EntityId\n },\n }\n cbStateMap.set(api, state)\n return api\n}\n\nfunction stateOf(cb: CommandBuffer): CommandBufferState {\n const s = cbStateMap.get(cb)\n if (!s) throw new Error('aiecsjs: unknown CommandBuffer')\n return s\n}\n\n// Look up a public World from its state id. We need a registry — re-import lazily.\nfunction lookupWorld(worldId: number): World {\n // The world registry is in internal/world.ts. We need to construct a public reference.\n // Since destroy clears state, we look up afresh by id via the worldRegistry.\n const state = lookupState(worldId)\n return { id: state.id, capacity: state.capacity, version: state.version } as World\n}\n\nfunction lookupState(worldId: number): import('./internal/types.js').WorldState {\n // Access worldRegistry indirectly via getWorldState requires a World object.\n // Use a small workaround: construct a minimal World-like and call getWorldState.\n return getWorldState({ id: worldId, capacity: 0, version: '0.0.0' } as World)\n}\n"]}
1
+ {"version":3,"sources":["../src/commands.ts"],"names":["createCommandBuffer","world","buf","getWorldState","makeApi","flush","cb","state","stateOf","placeholders","resolve","eid","num","real","EcsError","ops","op","createEntity","addComponent","removeComponent","destroyEntity","withCommandBuffer","fn","result","cbStateMap","api","component","initial","ph","s"],"mappings":"mEAgBO,SAASA,CAAAA,CAAoBC,CAAAA,CAA6B,CAE/D,IAAMC,EAA0B,CAC9B,OAAA,CAFYC,mBAAAA,CAAcF,CAAK,EAEhB,EAAA,CACf,GAAA,CAAK,EAAC,CACN,gBAAiB,EAAA,CACjB,QAAA,CAAU,KACZ,CAAA,CACA,OAAOG,CAAAA,CAAQF,CAAG,CACpB,CAQO,SAASG,CAAAA,CAAMC,CAAAA,CAAyB,CAC7C,IAAMC,EAAQC,CAAAA,CAAQF,CAAE,CAAA,CACxB,GAAI,CAAAC,CAAAA,CAAM,QAAA,CACV,CAAAA,CAAAA,CAAM,SAAW,IAAA,CACjB,GAAI,CAGF,IAAMN,EAAQ,CAAE,EAAA,CAAIM,CAAAA,CAAM,OAAQ,EAClCJ,mBAAAA,CAAcF,CAAK,CAAA,CAGnB,IAAMQ,EAAe,IAAI,GAAA,CAEnBC,CAAAA,CAAWC,CAAAA,EAA4B,CAC3C,IAAMC,CAAAA,CAAMD,CAAAA,CACZ,GAAIC,EAAM,CAAA,CAAG,CACX,IAAMC,CAAAA,CAAOJ,EAAa,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cjs","sourcesContent":["// aiecsjs/commands — deferred structural mutations during iteration.\n\nimport { addComponent, removeComponent } from './internal/component.js'\nimport { createEntity, destroyEntity } from './internal/entity.js'\nimport { EcsError } from './internal/errors.js'\nimport type {\n CommandBuffer,\n CommandBufferState,\n CommandOp,\n ComponentInit,\n ComponentLike,\n EntityId,\n World,\n} from './internal/types.js'\nimport { getWorldState } from './internal/world.js'\n\nexport function createCommandBuffer(world: World): CommandBuffer {\n const state = getWorldState(world)\n const buf: CommandBufferState = {\n worldId: state.id,\n ops: [],\n nextPlaceholder: -1,\n flushing: false,\n }\n return makeApi(buf)\n}\n\n// Applies the queued ops, then empties the queue. Each round detaches the\n// queue before any op runs, so if an op throws midway the ops already applied\n// stay applied and the rest are dropped — a retried flush never replays Phase 1\n// (duplicate entities) or the already-applied prefix. Ops queued on this buffer\n// while a round runs (e.g. from onAdd / onRemove handlers) form the next round\n// of the same flush, so their creates are resolved before their add/remove.\nexport function flush(cb: CommandBuffer): void {\n const state = stateOf(cb)\n if (state.flushing) return\n state.flushing = true\n try {\n // Every op resolves the world by id; resolving it up front makes a flush\n // on a disposed world throw EcsError even when the queue is empty.\n const world = { id: state.worldId } as World\n getWorldState(world)\n // Flush-wide: placeholders keep counting down across rounds, so an id\n // minted mid-flush never collides with one from an earlier round.\n const placeholders = new Map<number, EntityId>()\n\n const resolve = (eid: EntityId): EntityId => {\n const num = eid as number\n if (num < 0) {\n const real = placeholders.get(num)\n if (real === undefined) throw new EcsError(`aiecsjs: unresolved placeholder ${num}`)\n return real\n }\n return eid\n }\n\n while (state.ops.length > 0) {\n const ops = state.ops\n state.ops = []\n\n // Phase 1: resolve placeholders by creating real entities first\n for (const op of ops) {\n if (op.kind === 'create') {\n placeholders.set(op.placeholder, createEntity(world))\n }\n }\n\n // Phase 2: add/remove in queue order\n for (const op of ops) {\n if (op.kind === 'add') {\n addComponent(\n world,\n resolve(op.eid),\n op.component,\n op.initial as ComponentInit<ComponentLike>,\n )\n } else if (op.kind === 'remove') {\n removeComponent(world, resolve(op.eid), op.component)\n }\n }\n\n // Phase 3: destroy last\n for (const op of ops) {\n if (op.kind === 'destroy') {\n destroyEntity(world, resolve(op.eid))\n }\n }\n }\n } finally {\n // Ops a handler queued in a round that then threw stay queued; keep the\n // counter running so the next create cannot reuse their placeholder ids.\n if (state.ops.length === 0) state.nextPlaceholder = -1\n state.flushing = false\n }\n}\n\nexport function withCommandBuffer<R>(world: World, fn: (cb: CommandBuffer) => R): R {\n if (typeof fn !== 'function') throw new EcsError('aiecsjs: fn must be a function')\n const cb = createCommandBuffer(world)\n const result = fn(cb)\n flush(cb)\n return result\n}\n\n// --- Internals ---\n\nconst cbStateMap = new WeakMap<object, CommandBufferState>()\n\nfunction makeApi(state: CommandBufferState): CommandBuffer {\n const api: CommandBuffer = {\n add(eid, component, initial) {\n state.ops.push({ kind: 'add', eid, component, initial })\n },\n remove(eid, component) {\n state.ops.push({ kind: 'remove', eid, component })\n },\n destroy(eid) {\n state.ops.push({ kind: 'destroy', eid })\n },\n create() {\n const ph = state.nextPlaceholder--\n state.ops.push({ kind: 'create', placeholder: ph })\n return ph as EntityId\n },\n }\n cbStateMap.set(api, state)\n return api\n}\n\nfunction stateOf(cb: CommandBuffer): CommandBufferState {\n const s = cbStateMap.get(cb)\n if (!s) throw new EcsError('aiecsjs: unknown CommandBuffer')\n return s\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { W as World, C as CommandBuffer } from './types-BeVLA7xG.cjs';
1
+ import { W as World, C as CommandBuffer } from './types-C6TkQ7HW.cjs';
2
2
 
3
3
  declare function createCommandBuffer(world: World): CommandBuffer;
4
4
  declare function flush(cb: CommandBuffer): void;
@@ -1,4 +1,4 @@
1
- import { W as World, C as CommandBuffer } from './types-BeVLA7xG.js';
1
+ import { W as World, C as CommandBuffer } from './types-C6TkQ7HW.js';
2
2
 
3
3
  declare function createCommandBuffer(world: World): CommandBuffer;
4
4
  declare function flush(cb: CommandBuffer): void;
package/dist/commands.js CHANGED
@@ -1,2 +1,2 @@
1
- import {j,v,K,L,x}from'./chunk-OBMQME2P.js';function l(e){let n={worldId:j(e).id,ops:[],nextPlaceholder:-1,flushing:false};return h(n)}function C(e){let o=y(e);if(!o.flushing){o.flushing=true;try{let n=k(o.worldId),r=new Map;for(let t of o.ops)t.kind==="create"&&r.set(t.placeholder,v(n));let d=t=>{let i=t;if(i<0){let f=r.get(i);if(f===void 0)throw new Error(`aiecsjs: unresolved placeholder ${i}`);return f}return t};for(let t of o.ops)t.kind==="add"?K(n,d(t.eid),t.component,t.initial):t.kind==="remove"&&L(n,d(t.eid),t.component);for(let t of o.ops)t.kind==="destroy"&&x(n,d(t.eid));o.ops.length=0,o.nextPlaceholder=-1;}finally{o.flushing=false;}}}function b(e,o){let n=l(e),r=o(n);return C(n),r}var p=new WeakMap;function h(e){let o={add(n,r,d){e.ops.push({kind:"add",eid:n,component:r,initial:d});},remove(n,r){e.ops.push({kind:"remove",eid:n,component:r});},destroy(n){e.ops.push({kind:"destroy",eid:n});},create(){let n=e.nextPlaceholder--;return e.ops.push({kind:"create",placeholder:n}),n}};return p.set(o,e),o}function y(e){let o=p.get(e);if(!o)throw new Error("aiecsjs: unknown CommandBuffer");return o}function k(e){let o=B(e);return {id:o.id,capacity:o.capacity,version:o.version}}function B(e){return j({id:e,capacity:0,version:"0.0.0"})}export{l as createCommandBuffer,C as flush,b as withCommandBuffer};//# sourceMappingURL=commands.js.map
1
+ import {i,f,v,K,L,x}from'./chunk-27JX7WHY.js';function h(t){let o={worldId:i(t).id,ops:[],nextPlaceholder:-1,flushing:false};return y(o)}function C(t){let e=B(t);if(!e.flushing){e.flushing=true;try{let o={id:e.worldId};i(o);let r=new Map,d=f$1=>{let n=f$1;if(n<0){let m=r.get(n);if(m===void 0)throw new f(`aiecsjs: unresolved placeholder ${n}`);return m}return f$1};for(;e.ops.length>0;){let f=e.ops;e.ops=[];for(let n of f)n.kind==="create"&&r.set(n.placeholder,v(o));for(let n of f)n.kind==="add"?K(o,d(n.eid),n.component,n.initial):n.kind==="remove"&&L(o,d(n.eid),n.component);for(let n of f)n.kind==="destroy"&&x(o,d(n.eid));}}finally{e.ops.length===0&&(e.nextPlaceholder=-1),e.flushing=false;}}}function I(t,e){if(typeof e!="function")throw new f("aiecsjs: fn must be a function");let o=h(t),r=e(o);return C(o),r}var l=new WeakMap;function y(t){let e={add(o,r,d){t.ops.push({kind:"add",eid:o,component:r,initial:d});},remove(o,r){t.ops.push({kind:"remove",eid:o,component:r});},destroy(o){t.ops.push({kind:"destroy",eid:o});},create(){let o=t.nextPlaceholder--;return t.ops.push({kind:"create",placeholder:o}),o}};return l.set(e,t),e}function B(t){let e=l.get(t);if(!e)throw new f("aiecsjs: unknown CommandBuffer");return e}export{h as createCommandBuffer,C as flush,I as withCommandBuffer};//# sourceMappingURL=commands.js.map
2
2
  //# sourceMappingURL=commands.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/commands.ts"],"names":["createCommandBuffer","world","buf","getWorldState","makeApi","flush","cb","state","stateOf","lookupWorld","placeholders","op","createEntity","resolve","eid","num","real","addComponent","removeComponent","destroyEntity","withCommandBuffer","fn","result","cbStateMap","api","component","initial","ph","s","worldId","lookupState"],"mappings":"4CAeO,SAASA,EAAoBC,CAAAA,CAA6B,CAE/D,IAAMC,CAAAA,CAA0B,CAC9B,OAAA,CAFYC,CAAAA,CAAcF,CAAK,CAAA,CAEhB,GACf,GAAA,CAAK,EAAC,CACN,eAAA,CAAiB,GACjB,QAAA,CAAU,KACZ,CAAA,CACA,OAAOG,EAAQF,CAAG,CACpB,CAEO,SAASG,EAAMC,CAAAA,CAAyB,CAC7C,IAAMC,CAAAA,CAAQC,EAAQF,CAAE,CAAA,CACxB,GAAI,CAAAC,CAAAA,CAAM,SACV,CAAAA,CAAAA,CAAM,QAAA,CAAW,IAAA,CACjB,GAAI,CACF,IAAMN,CAAAA,CAAQQ,CAAAA,CAAYF,EAAM,OAAO,CAAA,CAGjCG,CAAAA,CAAe,IAAI,IACzB,I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,EACjC,OAAO,CAAE,GAAItB,CAAAA,CAAM,EAAA,CAAI,SAAUA,CAAAA,CAAM,QAAA,CAAU,OAAA,CAASA,CAAAA,CAAM,OAAQ,CAC1E,CAEA,SAASuB,CAAAA,CAAYD,EAA2D,CAG9E,OAAO1B,CAAAA,CAAc,CAAE,GAAI0B,CAAAA,CAAS,QAAA,CAAU,EAAG,OAAA,CAAS,OAAQ,CAAU,CAC9E","file":"commands.js","sourcesContent":["// aiecsjs/commands — deferred structural mutations during iteration.\n\nimport { addComponent, removeComponent } from './internal/component.js'\nimport { createEntity, destroyEntity } from './internal/entity.js'\nimport type {\n CommandBuffer,\n CommandBufferState,\n CommandOp,\n ComponentInit,\n ComponentLike,\n EntityId,\n World,\n} from './internal/types.js'\nimport { getWorldState } from './internal/world.js'\n\nexport function createCommandBuffer(world: World): CommandBuffer {\n const state = getWorldState(world)\n const buf: CommandBufferState = {\n worldId: state.id,\n ops: [],\n nextPlaceholder: -1,\n flushing: false,\n }\n return makeApi(buf)\n}\n\nexport function flush(cb: CommandBuffer): void {\n const state = stateOf(cb)\n if (state.flushing) return\n state.flushing = true\n try {\n const world = lookupWorld(state.worldId)\n\n // Phase 1: resolve placeholders by creating real entities first\n const placeholders = new Map<number, EntityId>()\n for (const op of state.ops) {\n if (op.kind === 'create') {\n placeholders.set(op.placeholder, createEntity(world))\n }\n }\n\n const resolve = (eid: EntityId): EntityId => {\n const num = eid as number\n if (num < 0) {\n const real = placeholders.get(num)\n if (real === undefined) throw new Error(`aiecsjs: unresolved placeholder ${num}`)\n return real\n }\n return eid\n }\n\n // Phase 2: add/remove in queue order\n for (const op of state.ops) {\n if (op.kind === 'add') {\n addComponent(\n world,\n resolve(op.eid),\n op.component,\n op.initial as ComponentInit<ComponentLike>,\n )\n } else if (op.kind === 'remove') {\n removeComponent(world, resolve(op.eid), op.component)\n }\n }\n\n // Phase 3: destroy last\n for (const op of state.ops) {\n if (op.kind === 'destroy') {\n destroyEntity(world, resolve(op.eid))\n }\n }\n\n state.ops.length = 0\n state.nextPlaceholder = -1\n } finally {\n state.flushing = false\n }\n}\n\nexport function withCommandBuffer<R>(world: World, fn: (cb: CommandBuffer) => R): R {\n const cb = createCommandBuffer(world)\n const result = fn(cb)\n flush(cb)\n return result\n}\n\n// --- Internals ---\n\nconst cbStateMap = new WeakMap<object, CommandBufferState>()\n\nfunction makeApi(state: CommandBufferState): CommandBuffer {\n const api: CommandBuffer = {\n add(eid, component, initial) {\n state.ops.push({ kind: 'add', eid, component, initial })\n },\n remove(eid, component) {\n state.ops.push({ kind: 'remove', eid, component })\n },\n destroy(eid) {\n state.ops.push({ kind: 'destroy', eid })\n },\n create() {\n const ph = state.nextPlaceholder--\n state.ops.push({ kind: 'create', placeholder: ph })\n return ph as EntityId\n },\n }\n cbStateMap.set(api, state)\n return api\n}\n\nfunction stateOf(cb: CommandBuffer): CommandBufferState {\n const s = cbStateMap.get(cb)\n if (!s) throw new Error('aiecsjs: unknown CommandBuffer')\n return s\n}\n\n// Look up a public World from its state id. We need a registry — re-import lazily.\nfunction lookupWorld(worldId: number): World {\n // The world registry is in internal/world.ts. We need to construct a public reference.\n // Since destroy clears state, we look up afresh by id via the worldRegistry.\n const state = lookupState(worldId)\n return { id: state.id, capacity: state.capacity, version: state.version } as World\n}\n\nfunction lookupState(worldId: number): import('./internal/types.js').WorldState {\n // Access worldRegistry indirectly via getWorldState requires a World object.\n // Use a small workaround: construct a minimal World-like and call getWorldState.\n return getWorldState({ id: worldId, capacity: 0, version: '0.0.0' } as World)\n}\n"]}
1
+ {"version":3,"sources":["../src/commands.ts"],"names":["createCommandBuffer","world","buf","getWorldState","makeApi","flush","cb","state","stateOf","placeholders","resolve","eid","num","real","EcsError","ops","op","createEntity","addComponent","removeComponent","destroyEntity","withCommandBuffer","fn","result","cbStateMap","api","component","initial","ph","s"],"mappings":"8CAgBO,SAASA,CAAAA,CAAoBC,CAAAA,CAA6B,CAE/D,IAAMC,EAA0B,CAC9B,OAAA,CAFYC,CAAAA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,CAAM,GAAA,CAAI,KAAK,CAAE,IAAA,CAAM,SAAA,CAAW,GAAA,CAAAI,CAAI,CAAC,EACzC,CAAA,CACA,MAAA,EAAS,CACP,IAAMiB,CAAAA,CAAKrB,CAAAA,CAAM,eAAA,EAAA,CACjB,OAAAA,CAAAA,CAAM,GAAA,CAAI,IAAA,CAAK,CAAE,KAAM,QAAA,CAAU,WAAA,CAAaqB,CAAG,CAAC,EAC3CA,CACT,CACF,CAAA,CACA,OAAAJ,EAAW,GAAA,CAAIC,CAAAA,CAAKlB,CAAK,CAAA,CAClBkB,CACT,CAEA,SAASjB,CAAAA,CAAQF,CAAAA,CAAuC,CACtD,IAAMuB,CAAAA,CAAIL,CAAAA,CAAW,GAAA,CAAIlB,CAAE,CAAA,CAC3B,GAAI,CAACuB,CAAAA,CAAG,MAAM,IAAIf,CAAAA,CAAS,gCAAgC,CAAA,CAC3D,OAAOe,CACT","file":"commands.js","sourcesContent":["// aiecsjs/commands — deferred structural mutations during iteration.\n\nimport { addComponent, removeComponent } from './internal/component.js'\nimport { createEntity, destroyEntity } from './internal/entity.js'\nimport { EcsError } from './internal/errors.js'\nimport type {\n CommandBuffer,\n CommandBufferState,\n CommandOp,\n ComponentInit,\n ComponentLike,\n EntityId,\n World,\n} from './internal/types.js'\nimport { getWorldState } from './internal/world.js'\n\nexport function createCommandBuffer(world: World): CommandBuffer {\n const state = getWorldState(world)\n const buf: CommandBufferState = {\n worldId: state.id,\n ops: [],\n nextPlaceholder: -1,\n flushing: false,\n }\n return makeApi(buf)\n}\n\n// Applies the queued ops, then empties the queue. Each round detaches the\n// queue before any op runs, so if an op throws midway the ops already applied\n// stay applied and the rest are dropped — a retried flush never replays Phase 1\n// (duplicate entities) or the already-applied prefix. Ops queued on this buffer\n// while a round runs (e.g. from onAdd / onRemove handlers) form the next round\n// of the same flush, so their creates are resolved before their add/remove.\nexport function flush(cb: CommandBuffer): void {\n const state = stateOf(cb)\n if (state.flushing) return\n state.flushing = true\n try {\n // Every op resolves the world by id; resolving it up front makes a flush\n // on a disposed world throw EcsError even when the queue is empty.\n const world = { id: state.worldId } as World\n getWorldState(world)\n // Flush-wide: placeholders keep counting down across rounds, so an id\n // minted mid-flush never collides with one from an earlier round.\n const placeholders = new Map<number, EntityId>()\n\n const resolve = (eid: EntityId): EntityId => {\n const num = eid as number\n if (num < 0) {\n const real = placeholders.get(num)\n if (real === undefined) throw new EcsError(`aiecsjs: unresolved placeholder ${num}`)\n return real\n }\n return eid\n }\n\n while (state.ops.length > 0) {\n const ops = state.ops\n state.ops = []\n\n // Phase 1: resolve placeholders by creating real entities first\n for (const op of ops) {\n if (op.kind === 'create') {\n placeholders.set(op.placeholder, createEntity(world))\n }\n }\n\n // Phase 2: add/remove in queue order\n for (const op of ops) {\n if (op.kind === 'add') {\n addComponent(\n world,\n resolve(op.eid),\n op.component,\n op.initial as ComponentInit<ComponentLike>,\n )\n } else if (op.kind === 'remove') {\n removeComponent(world, resolve(op.eid), op.component)\n }\n }\n\n // Phase 3: destroy last\n for (const op of ops) {\n if (op.kind === 'destroy') {\n destroyEntity(world, resolve(op.eid))\n }\n }\n }\n } finally {\n // Ops a handler queued in a round that then threw stay queued; keep the\n // counter running so the next create cannot reuse their placeholder ids.\n if (state.ops.length === 0) state.nextPlaceholder = -1\n state.flushing = false\n }\n}\n\nexport function withCommandBuffer<R>(world: World, fn: (cb: CommandBuffer) => R): R {\n if (typeof fn !== 'function') throw new EcsError('aiecsjs: fn must be a function')\n const cb = createCommandBuffer(world)\n const result = fn(cb)\n flush(cb)\n return result\n}\n\n// --- Internals ---\n\nconst cbStateMap = new WeakMap<object, CommandBufferState>()\n\nfunction makeApi(state: CommandBufferState): CommandBuffer {\n const api: CommandBuffer = {\n add(eid, component, initial) {\n state.ops.push({ kind: 'add', eid, component, initial })\n },\n remove(eid, component) {\n state.ops.push({ kind: 'remove', eid, component })\n },\n destroy(eid) {\n state.ops.push({ kind: 'destroy', eid })\n },\n create() {\n const ph = state.nextPlaceholder--\n state.ops.push({ kind: 'create', placeholder: ph })\n return ph as EntityId\n },\n }\n cbStateMap.set(api, state)\n return api\n}\n\nfunction stateOf(cb: CommandBuffer): CommandBufferState {\n const s = cbStateMap.get(cb)\n if (!s) throw new EcsError('aiecsjs: unknown CommandBuffer')\n return s\n}\n"]}
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- 'use strict';var chunkUSHKPJQG_cjs=require('./chunk-USHKPJQG.cjs'),chunkQ2XLL6YG_cjs=require('./chunk-Q2XLL6YG.cjs');var J={i8:"i8",u8:"u8",i16:"i16",u16:"u16",i32:"i32",u32:"u32",f32:"f32",f64:"f64",eid:"eid",bool:"bool"};function X(...n){return n.length===0?e=>e:n.length===1?n[0]:(e,r)=>{let t=e;for(let o of n)t=o(t,r);return t}}var i=class extends Error{eid;constructor(e){super(`aiecsjs: entity ${e} is not alive`),this.name="EntityNotAliveError",this.eid=e;}};function Y(n,e){let r=chunkQ2XLL6YG_cjs.j(n);if(!chunkQ2XLL6YG_cjs.z(r,e))throw new i(e);return Object.freeze({id:e,worldId:r.id})}function b(n,e){let r=chunkQ2XLL6YG_cjs.j(n);if(e.worldId!==r.id)return null;let t=e.id,o=chunkQ2XLL6YG_cjs.t(t,r.options);if(o<=0||o>=r.capacity)return null;let x=r.entityArchetype[o]??0,d=r.archetypes[x];if(!d||!d.entityRow.has(e.id))return null;let C=r.generations[o]??0,A=chunkQ2XLL6YG_cjs.u(t,r.options);return C!==A?null:e.id}function Z(n,e){return b(n,e)!==null}chunkUSHKPJQG_cjs.j(n=>chunkQ2XLL6YG_cjs.R(n));chunkQ2XLL6YG_cjs.P((n,e,r,t,o)=>{chunkUSHKPJQG_cjs.i(n,e,r,t,o);});var me=typeof SharedArrayBuffer<"u";Object.defineProperty(exports,"defineQuery",{enumerable:true,get:function(){return chunkUSHKPJQG_cjs.a}});Object.defineProperty(exports,"enterQuery",{enumerable:true,get:function(){return chunkUSHKPJQG_cjs.b}});Object.defineProperty(exports,"exitQuery",{enumerable:true,get:function(){return chunkUSHKPJQG_cjs.c}});Object.defineProperty(exports,"forEachEntity",{enumerable:true,get:function(){return chunkUSHKPJQG_cjs.g}});Object.defineProperty(exports,"forEachEntityIndexed",{enumerable:true,get:function(){return chunkUSHKPJQG_cjs.h}});Object.defineProperty(exports,"iterQuery",{enumerable:true,get:function(){return chunkUSHKPJQG_cjs.f}});Object.defineProperty(exports,"queryArchetypes",{enumerable:true,get:function(){return chunkUSHKPJQG_cjs.d}});Object.defineProperty(exports,"runQuery",{enumerable:true,get:function(){return chunkUSHKPJQG_cjs.e}});Object.defineProperty(exports,"EcsError",{enumerable:true,get:function(){return chunkQ2XLL6YG_cjs.i}});Object.defineProperty(exports,"VERSION",{enumerable:true,get:function(){return chunkQ2XLL6YG_cjs.a}});Object.defineProperty(exports,"addComponent",{enumerable:true,get:function(){return chunkQ2XLL6YG_cjs.K}});Object.defineProperty(exports,"createEntity",{enumerable:true,get:function(){return chunkQ2XLL6YG_cjs.v}});Object.defineProperty(exports,"createWorld",{enumerable:true,get:function(){return chunkQ2XLL6YG_cjs.l}});Object.defineProperty(exports,"defineComponent",{enumerable:true,get:function(){return chunkQ2XLL6YG_cjs.G}});Object.defineProperty(exports,"defineObjectComponent",{enumerable:true,get:function(){return chunkQ2XLL6YG_cjs.I}});Object.defineProperty(exports,"defineTag",{enumerable:true,get:function(){return chunkQ2XLL6YG_cjs.H}});Object.defineProperty(exports,"destroyEntity",{enumerable:true,get:function(){return chunkQ2XLL6YG_cjs.x}});Object.defineProperty(exports,"destroyWorld",{enumerable:true,get:function(){return chunkQ2XLL6YG_cjs.m}});Object.defineProperty(exports,"disposeWorld",{enumerable:true,get:function(){return chunkQ2XLL6YG_cjs.m}});Object.defineProperty(exports,"entityExists",{enumerable:true,get:function(){return chunkQ2XLL6YG_cjs.y}});Object.defineProperty(exports,"getComponent",{enumerable:true,get:function(){return chunkQ2XLL6YG_cjs.N}});Object.defineProperty(exports,"getEntityGeneration",{enumerable:true,get:function(){return chunkQ2XLL6YG_cjs.B}});Object.defineProperty(exports,"getEntityIndex",{enumerable:true,get:function(){return chunkQ2XLL6YG_cjs.A}});Object.defineProperty(exports,"getWorldCapacity",{enumerable:true,get:function(){return chunkQ2XLL6YG_cjs.p}});Object.defineProperty(exports,"getWorldSize",{enumerable:true,get:function(){return chunkQ2XLL6YG_cjs.o}});Object.defineProperty(exports,"hasComponent",{enumerable:true,get:function(){return chunkQ2XLL6YG_cjs.M}});Object.defineProperty(exports,"isEntity",{enumerable:true,get:function(){return chunkQ2XLL6YG_cjs.D}});Object.defineProperty(exports,"isWorld",{enumerable:true,get:function(){return chunkQ2XLL6YG_cjs.r}});Object.defineProperty(exports,"packEntity",{enumerable:true,get:function(){return chunkQ2XLL6YG_cjs.C}});Object.defineProperty(exports,"removeComponent",{enumerable:true,get:function(){return chunkQ2XLL6YG_cjs.L}});Object.defineProperty(exports,"resetWorld",{enumerable:true,get:function(){return chunkQ2XLL6YG_cjs.n}});Object.defineProperty(exports,"setComponent",{enumerable:true,get:function(){return chunkQ2XLL6YG_cjs.O}});exports.EntityNotAliveError=i;exports.IS_SAB_SUPPORTED=me;exports.Types=J;exports.aliveRef=Z;exports.deref=b;exports.pipe=X;exports.refOf=Y;//# sourceMappingURL=index.cjs.map
1
+ 'use strict';var chunkO4UVAWFU_cjs=require('./chunk-O4UVAWFU.cjs'),chunkNPNWRCB5_cjs=require('./chunk-NPNWRCB5.cjs');var H={i8:"i8",u8:"u8",i16:"i16",u16:"u16",i32:"i32",u32:"u32",f32:"f32",f64:"f64",eid:"eid",bool:"bool"};function N(...n){for(let e of n)if(typeof e!="function")throw new chunkNPNWRCB5_cjs.f("aiecsjs: every system must be a function");return n.length===0?e=>e:n.length===1?n[0]:(e,r)=>{let t=e;for(let o of n)t=o(t,r);return t}}var i=class extends Error{eid;constructor(e){super(`aiecsjs: entity ${e} is not alive`),this.name="EntityNotAliveError",this.eid=e;}};function K(n,e){let r=chunkNPNWRCB5_cjs.i(n);if(!chunkNPNWRCB5_cjs.z(r,e))throw new i(e);return Object.freeze({id:e,worldId:r.id})}function l(n,e){let r=chunkNPNWRCB5_cjs.i(n);if(e.worldId!==r.id)return null;let t=e.id,o=chunkNPNWRCB5_cjs.t(t,r.options);if(o<=0||o>=r.capacity)return null;let c=r.entityArchetype[o]??0,u=r.archetypes[c];if(!u||!u.entityRow.has(e.id))return null;let f=r.generations[o]??0,b=chunkNPNWRCB5_cjs.u(t,r.options);return f!==b?null:e.id}function $(n,e){return l(n,e)!==null}var re=typeof SharedArrayBuffer<"u";Object.defineProperty(exports,"defineQuery",{enumerable:true,get:function(){return chunkO4UVAWFU_cjs.a}});Object.defineProperty(exports,"enterQuery",{enumerable:true,get:function(){return chunkO4UVAWFU_cjs.b}});Object.defineProperty(exports,"exitQuery",{enumerable:true,get:function(){return chunkO4UVAWFU_cjs.c}});Object.defineProperty(exports,"forEachEntity",{enumerable:true,get:function(){return chunkO4UVAWFU_cjs.i}});Object.defineProperty(exports,"forEachEntityIndexed",{enumerable:true,get:function(){return chunkO4UVAWFU_cjs.j}});Object.defineProperty(exports,"iterQuery",{enumerable:true,get:function(){return chunkO4UVAWFU_cjs.h}});Object.defineProperty(exports,"queryArchetypes",{enumerable:true,get:function(){return chunkO4UVAWFU_cjs.f}});Object.defineProperty(exports,"runQuery",{enumerable:true,get:function(){return chunkO4UVAWFU_cjs.g}});Object.defineProperty(exports,"EcsError",{enumerable:true,get:function(){return chunkNPNWRCB5_cjs.f}});Object.defineProperty(exports,"VERSION",{enumerable:true,get:function(){return chunkNPNWRCB5_cjs.a}});Object.defineProperty(exports,"addComponent",{enumerable:true,get:function(){return chunkNPNWRCB5_cjs.K}});Object.defineProperty(exports,"createEntity",{enumerable:true,get:function(){return chunkNPNWRCB5_cjs.v}});Object.defineProperty(exports,"createWorld",{enumerable:true,get:function(){return chunkNPNWRCB5_cjs.l}});Object.defineProperty(exports,"defineComponent",{enumerable:true,get:function(){return chunkNPNWRCB5_cjs.G}});Object.defineProperty(exports,"defineObjectComponent",{enumerable:true,get:function(){return chunkNPNWRCB5_cjs.I}});Object.defineProperty(exports,"defineTag",{enumerable:true,get:function(){return chunkNPNWRCB5_cjs.H}});Object.defineProperty(exports,"destroyEntity",{enumerable:true,get:function(){return chunkNPNWRCB5_cjs.x}});Object.defineProperty(exports,"destroyWorld",{enumerable:true,get:function(){return chunkNPNWRCB5_cjs.m}});Object.defineProperty(exports,"disposeWorld",{enumerable:true,get:function(){return chunkNPNWRCB5_cjs.m}});Object.defineProperty(exports,"entityExists",{enumerable:true,get:function(){return chunkNPNWRCB5_cjs.y}});Object.defineProperty(exports,"getComponent",{enumerable:true,get:function(){return chunkNPNWRCB5_cjs.N}});Object.defineProperty(exports,"getEntityGeneration",{enumerable:true,get:function(){return chunkNPNWRCB5_cjs.B}});Object.defineProperty(exports,"getEntityIndex",{enumerable:true,get:function(){return chunkNPNWRCB5_cjs.A}});Object.defineProperty(exports,"getWorldCapacity",{enumerable:true,get:function(){return chunkNPNWRCB5_cjs.p}});Object.defineProperty(exports,"getWorldSize",{enumerable:true,get:function(){return chunkNPNWRCB5_cjs.o}});Object.defineProperty(exports,"hasComponent",{enumerable:true,get:function(){return chunkNPNWRCB5_cjs.M}});Object.defineProperty(exports,"isEntity",{enumerable:true,get:function(){return chunkNPNWRCB5_cjs.D}});Object.defineProperty(exports,"isWorld",{enumerable:true,get:function(){return chunkNPNWRCB5_cjs.r}});Object.defineProperty(exports,"packEntity",{enumerable:true,get:function(){return chunkNPNWRCB5_cjs.C}});Object.defineProperty(exports,"removeComponent",{enumerable:true,get:function(){return chunkNPNWRCB5_cjs.L}});Object.defineProperty(exports,"resetWorld",{enumerable:true,get:function(){return chunkNPNWRCB5_cjs.n}});Object.defineProperty(exports,"setComponent",{enumerable:true,get:function(){return chunkNPNWRCB5_cjs.O}});exports.EntityNotAliveError=i;exports.IS_SAB_SUPPORTED=re;exports.Types=H;exports.aliveRef=$;exports.deref=l;exports.pipe=N;exports.refOf=K;//# sourceMappingURL=index.cjs.map
2
2
  //# sourceMappingURL=index.cjs.map