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
package/llms-full.txt CHANGED
@@ -14,7 +14,7 @@ The short index lives at `llms.txt` (see https://llmstxt.org/).
14
14
 
15
15
  TypeScript-first archetype ECS with TypedArray SoA components, command buffers, relations, serialization, and SAB-ready snapshot transport.
16
16
 
17
- > **Status: 0.5.9 - stable 1.0-track core.** Root ECS APIs are stable; worker transport remains adapter-shaped and environment-dependent.
17
+ > **Status: 0.6.0 - stable 1.0-track core.** Root ECS APIs are stable; worker transport remains adapter-shaped and environment-dependent. 0.6.0 has breaking changes (snapshot format 2, stricter validation): see the [CHANGELOG](CHANGELOG.md).
18
18
 
19
19
  ## Install
20
20
 
@@ -29,8 +29,8 @@ import {
29
29
  createEntity,
30
30
  createWorld,
31
31
  defineComponent,
32
- forEachEntity,
33
- getComponent,
32
+ defineQuery,
33
+ forEachEntityIndexed,
34
34
  } from "aiecsjs";
35
35
  ```
36
36
 
@@ -45,15 +45,15 @@ const e = createEntity(world);
45
45
  addComponent(world, e, Position, { x: 0, y: 0 });
46
46
  addComponent(world, e, Velocity, { x: 1, y: 0 });
47
47
 
48
- forEachEntity(world, [Position, Velocity], (entity) => {
49
- const pos = getComponent(world, entity, Position);
50
- const vel = getComponent(world, entity, Velocity);
51
- pos.x += vel.x;
52
- pos.y += vel.y;
48
+ // SoA columns are TypedArrays; index them with `i`, the entity's slot index.
49
+ const movers = defineQuery([Position, Velocity]);
50
+ forEachEntityIndexed(world, movers, (entity, i, pos, vel) => {
51
+ pos.x[i] += vel.x[i];
52
+ pos.y[i] += vel.y[i];
53
53
  });
54
54
  ```
55
55
 
56
- Use `defineTag()` for marker components and `defineObjectComponent()` when you need object references instead of TypedArray storage.
56
+ Use `defineTag()` for marker components and `defineObjectComponent()` when you need object references instead of TypedArray storage. Do not index columns with the packed `entity` id: it stops matching the slot once a slot is recycled.
57
57
 
58
58
  ## Public Surface
59
59
 
@@ -67,15 +67,49 @@ Use `defineTag()` for marker components and `defineObjectComponent()` when you n
67
67
  | `aiecsjs/worker` | Transfer/adopt/attach helpers for worker snapshots. |
68
68
  | `aiecsjs/relations` | `defineRelation`, `ChildOf`, relation add/remove/read helpers. |
69
69
 
70
+ ## Snapshots
71
+
72
+ `toJSON` / `serializeWorld` write snapshot format 2: entity data plus a table of the components it uses (stable key, kind, SoA fields). Give every component you save a `key`, so a loading session can define its components in any order:
73
+
74
+ ```ts
75
+ const Position = defineComponent({ x: Types.f32, y: Types.f32 }, { key: "position" });
76
+ const Player = defineTag({ key: "player" });
77
+
78
+ const bytes = serializeWorld(world); // aiecsjs/serialize
79
+ const restored = deserializeWorld(bytes); // or fromJSON(toJSON(world))
80
+ ```
81
+
82
+ - Loading resolves every component before it creates the world: by key, or by creation-order id for keyless components. It throws `EcsError` when a component is not defined in this process (pass `onUnknownComponent: "skip"` to drop its data) or when its kind or SoA fields differ.
83
+ - 0.5.x snapshots are rejected with `EcsError` by default; `{ onUnknownVersion: "best-effort" }` loads them by id with a kind check. See [0.5.x -> 0.6.0 snapshots](docs/MIGRATION.md#05x---060-snapshots).
84
+ - Restored entities get fresh ids in snapshot order (holes in the slot range close up), so EntityIds stored inside component data are not remapped. Delta `apply()` keeps slot indices.
85
+
86
+ ## Relations
87
+
88
+ ```ts
89
+ import { ChildOf, addRelation, getRelationTargets } from "aiecsjs/relations";
90
+
91
+ addRelation(world, child, ChildOf, parent);
92
+ getRelationTargets(world, child, ChildOf); // [parent]
93
+ ```
94
+
95
+ - `addRelation` throws `EcsError` for a dead source or target, mirroring `addComponent`. Check `entityExists` first when an endpoint may be stale.
96
+ - `destroyEntity` and `resetWorld` drop every edge of the entities they remove; `removeRelation` is a no-op for dead endpoints.
97
+
98
+ ## Errors
99
+
100
+ - Misuse and invariant failures throw `EcsError` (message `aiecsjs: ...`) before any change is made: non-integer world options, dead entities, unknown components, invalid component keys, non-function callbacks (observer handlers, `forEachEntity`, `withCommandBuffer`, `pipe` systems, AoS factories) and snapshot errors.
101
+ - A world from `attachWorld(buffer, { readOnly: true })` rejects every mutator with `EcsError`: `createEntity`, `destroyEntity`, `addComponent`, `removeComponent`, `setComponent`, `resetWorld`, `addRelation`, `removeRelation` and delta `apply()`.
102
+ - `defineComponent` field-declaration errors and non-Query input to query functions throw `TypeError`. `createLoop` (`aiecsjs/loop` has no error class) throws `TypeError` / `RangeError`.
103
+
70
104
  ## Sharp Edges
71
105
 
72
106
  - Structural mutation during a query loop is allowed by the library, but app systems should prefer `withCommandBuffer()` when adding/removing/destroying entities from inside iteration.
73
107
  - Reactive query buffers are unbounded until drained. Poll and clear them every frame or event tick.
74
- - Query registration currently uses a global module cache; many worlds/components can make structural changes scan more query metadata than expected.
75
- - Exclusive relation cleanup is `O(incoming)` on destroy — a reverse index touches only the edges pointing at the destroyed entity, not the whole relation capacity.
108
+ - Queries are cached process-wide, and a structural change visits every reactive (enter/exit) source query that references the changed component, whichever world registered it.
109
+ - Exclusive relation cleanup is `O(incoming)` on destroy for the exclusive-slot reverse index, but every destroy also walks all relation `data` payload sources and all `outgoing` (non-exclusive) edge lists — cost is `O(incoming + data sources + outgoing sources)` across all relations, even for entities with no relations at all.
76
110
  - Serialization restores capacity with safety clamps, but snapshots from untrusted sources should still be treated as hostile input.
77
111
  - Worker/SAB helpers depend on the runtime environment. Feature-detect `SharedArrayBuffer` and cross-origin isolation in browsers.
78
- - `pnpm lint` currently reports many `noExplicitAny` warnings. They are not release-blocking, but they add AI-review noise.
112
+ - `pnpm lint` reports 84 `noExplicitAny` warnings, mostly casts in tests plus the public query callback types. They are not release-blocking.
79
113
 
80
114
  ## AI Context
81
115
 
@@ -98,7 +132,58 @@ MIT
98
132
 
99
133
  All notable changes to aiecsjs are summarized here. Detailed historical review notes live in Git history; this file keeps current release context compact.
100
134
 
101
- ## [Unreleased]
135
+ ## [0.6.0] - 2026-09-29
136
+
137
+ ### Breaking
138
+
139
+ - `toJSON` / `serializeWorld` / `createDeltaSerializer` / `fromJSON` / `deserializeWorld` / `adoptSnapshot` / `attachWorld`: snapshots are now format 2 with a component table, and every loader resolves each component by its stable key (by creation-order id when keyless) and throws `EcsError` for a component the process has not defined or a kind / SoA-field mismatch, because 0.5.x id-only matching silently put data into the wrong components when definition order differed; 0.5.x snapshots (no `formatVersion`, binary or worker meta format 1) are rejected with `EcsError: aiecsjs: format version 1 not supported`. Migration: give every serialized component a key (`defineComponent(schema, { key })`, `defineTag({ key })`, `defineObjectComponent(factory, { key })`), re-export existing 0.5.x snapshots with 0.6.0 or load them once with `{ onUnknownVersion: 'best-effort' }` and save again, pass `{ onUnknownComponent: 'skip' }` where dropping unknown components is intended, and add `formatVersion: 2` plus a `components` table to hand-built snapshots (see docs/MIGRATION.md).
140
+ - `addRelation`: a dead source or target now throws `EcsError` (mirroring `addComponent`), because edges are stored by slot and an edge to a dead entity was inherited by whatever entity was later recycled into that slot. Migration: check `entityExists` before `addRelation` when an endpoint may be stale.
141
+ - `createWorld`: a non-integer `initialCapacity`, `maxEntities`, `indexBits` or `generationBits` (such as `1.5`, `NaN`, `Infinity` or `'8'`) now throws `EcsError` before the range checks and clamps, because fractional and `NaN` values silently truncated typed arrays and dropped entities. Migration: pass integers for these options (for example `Math.floor(n)`).
142
+ - `resetWorld`: a read-only (worker-attached) world now throws `EcsError`, as every other mutator already did, instead of being wiped. Migration: reset a writable world instead (`adoptSnapshot`, or `attachWorld` without `readOnly`).
143
+ - `onAdd` / `onRemove` / `onSet` / `observe`, `forEachEntity` / `forEachEntityIndexed`, `withCommandBuffer`, `pipe`, `defineObjectComponent` and the relation helpers: a non-function handler, callback, system or factory, an AoS factory that returns `null` or `undefined`, or a relation argument that is not a `defineRelation` handle now throws `EcsError` at the call, instead of being accepted and failing later (for observers, after the structural change was already committed) or doing nothing. Migration: pass functions, a factory that returns a value and real relation handles; catch `EcsError` where these come from dynamic input.
144
+ - `createLoop` (`aiecsjs/loop`): a missing options object or a non-function `onUpdate` / `onRender` now throws `TypeError`, and a `fixed` that is not a finite number > 0 or a `maxSubSteps` that is not a finite number >= 1 throws `RangeError`, instead of failing in the first tick or silently stalling. Migration: pass an options object with a function `onUpdate`, and a positive finite `fixed` and a `maxSubSteps` of at least 1 when you set them.
145
+
146
+ ### Changes
147
+
148
+ - Added: stable component keys: `defineComponent(schema, { key })`, `defineTag({ key })` and `defineObjectComponent(factory, { key })`; a key must be a non-empty string (`EcsError` otherwise); defining a key again with the same kind and field layout (HMR, editor script reload) returns the existing component, and a different layout throws `EcsError`.
149
+ - Added: `DeserializeOptions.onUnknownComponent` (`'throw'` by default, or `'skip'`); `fromJSON(snapshot, options?)` takes `DeserializeOptions` (including the `components` allowlist), and `adoptSnapshot(snap, options?)` and `attachWorld(buffer, { readOnly?, ...DeserializeOptions })` pass them through.
150
+ - Added: the `EcsError` constructor accepts an optional `{ cause }`.
151
+ - Changed: every plain `Error` misuse throw (read-only guards, the dead-entity guards of `addComponent` / `setComponent`, unregistered components, the missing empty archetype guard, binary snapshot header and body errors, worker meta errors, command-buffer errors) is now `EcsError` with the same message, so callers can branch on the class; `instanceof Error` checks and message matches keep working.
152
+ - Changed: `noExplicitAny` lint warnings are down from 133 to 84 (`src` 11 to 4, tests 122 to 80), with the emitted public `.d.ts` signatures unchanged; the 4 left in `src` are the public query callback and `ComponentLike` types.
153
+ - Changed: internal refactors keep every entry inside its existing size budget: shared archetype-row and slot-placement helpers, one loop for `forEachEntity` / `forEachEntityIndexed`, one reactive-buffer drain, one mask matcher, and removal of the never-read per-archetype edge tables (two `Int32Array(256)` per archetype) and of unreachable fallback factories; the coverage `functions` threshold is raised to 100.
154
+ - Fixed: `destroyEntity` no longer recurses (or corrupts world size/freeList/exit-query state) when an onRemove/observe handler destroys, resets, or otherwise re-enters teardown for the same entity.
155
+ - Fixed: the package's `sideEffects: false` no longer lets bundlers drop `dist/index.js`'s component-lookup and mask-change registration, which broke queries (and left reactive enter/exit queries empty) for consumers who imported only chunk-owned bindings.
156
+ - Fixed: query observers (`observe(world, query, 'add'|'remove')`) now track match transitions, so queries with `none` terms fire enter/exit correctly and `'remove'` no longer fires for entities that never matched.
157
+ - Fixed: the delta serializer now replicates AoS (`defineObjectComponent`) changes; `capture()` previously aliased the live component instance and always diffed it against itself, silently dropping AoS updates.
158
+ - Fixed: `toJSON`/delta capture no longer drop component-less live entities (archetype 0) from snapshots.
159
+ - Fixed: `flush()` detaches the command-buffer queue before applying it, so a flush that throws partway through no longer replays Phase 1 and duplicates entities on retry.
160
+ - Fixed: command-buffer ops enqueued during `flush()` (e.g. from an onAdd/onRemove handler) are now processed in further rounds instead of throwing an unresolved-placeholder error or being silently dropped.
161
+ - Fixed: component-level `onRemove` handlers can now read the outgoing component's value via `getComponent` on the `removeComponent` path, matching the existing `destroyEntity` path.
162
+ - Fixed: `forEachEntity`/`forEachEntityIndexed`/`iterQuery`/`runQuery` accept a raw component array (routed through `defineQuery`) and throw a `TypeError` for other non-Query input, instead of silently iterating zero entities.
163
+ - Fixed: an in-loop `addComponent`/`removeComponent` that moves the currently visited entity into an archetype already covered by the same `forEachEntity`/`forEachEntityIndexed` pass no longer visits it twice or skips another entity.
164
+ - Fixed: `observe(world, query, 'set')` now fires only for entities that actually match the query (not merely any entity carrying a component in `query.all`), and fires for `any`-only components too.
165
+ - Fixed: `toJSON` deep-copies AoS component data instead of handing out the live instance, so `fromJSON(toJSON(w))` and a mutated snapshot no longer alias/mutate the source world.
166
+ - Fixed: the delta serializer's `capture()`/`apply()` and `deserializeWorld` now honour the documented `components` allowlist option instead of silently ignoring it.
167
+ - Fixed: component/query/world registries are now shared across duplicate ESM+CJS copies of the package (via a `globalThis` key) instead of colliding on the same auto-incrementing ids.
168
+ - Fixed: `fromJSON`/`deserializeWorld` restore `maxEntities`, `indexBits`, and `generationBits` from the snapshot instead of falling back to defaults, so a large or non-default-layout world round-trips without hitting a bogus `maxEntities` cap.
169
+ - Fixed: the fixed-timestep loop now ends a tick chain as soon as it is stopped or restarted — even from inside `onUpdate`/`onRender` — so it no longer keeps stepping, renders after `stop()`, or runs two chains concurrently.
170
+ - Fixed: reactive (enter/exit) queries are now indexed per world instead of scanning a module-level cache on every structural change, which previously registered foreign components (and could exhaust `maxComponents`) in unrelated worlds.
171
+ - Fixed: `observe()` on an `enterQuery`/`exitQuery` now registers the query directly instead of forcing registration via `runQuery`, which drained the (not-yet-registered) reactive buffer as a no-op and left the observer permanently inert.
172
+ - Fixed: `iterQuery`/`forEachEntity`/`forEachEntityIndexed` now drain their reactive buffer up front, so breaking out of the loop early or a callback throwing partway through no longer re-delivers already-seen entities on the next read.
173
+ - Fixed: the delta serializer's `apply()` rejects a non-integer `eid` instead of corrupting entity-slot allocation (a live slot pushed onto the freeList, a non-integer allocation frontier).
174
+ - Fixed: the fixed-timestep loop clamps `dtMs` to non-negative, so a first tick timestamp earlier than `start()`'s sample can no longer drive the accumulator (and `onRender`'s alpha) negative.
175
+ - Fixed: `createEntity`'s `maxEntities` guard now throws `EcsError` (matching the documented behaviour) instead of a plain `Error`.
176
+ - Fixed: `enterQuery` / `exitQuery` / `observe` now check their query argument like `runQuery`: a raw component array works, and other non-Query input throws the documented `TypeError` instead of an internal `TypeError` (`enterQuery` / `exitQuery` also cached a broken reactive query that later calls returned silently).
177
+ - Fixed: `addComponent` builds a new AoS instance before it moves the entity to its new archetype, so a factory that throws leaves the entity unchanged instead of half-added (moved, but never announced to observers or reactive queries).
178
+ - Fixed: a missing world handle, component handle, snapshot, worker meta or delta byte array now throws `EcsError` instead of a bare `TypeError` from property access.
179
+ - Fixed: `deserializeWorld` applied the `components` allowlist to the snapshot's source-process component ids; `fromJSON` / `deserializeWorld` now apply it to the resolved local components.
180
+ - Fixed: package.json `exports` now nest `types` under `import` and `require` for every subpath, with `require.types` pointing at the `.d.cts` file, so CommonJS consumers on `node16`/`nodenext` module resolution get the CommonJS declarations; `verify-exports` walks nested conditions.
181
+ - Docs: relation-destroy cost is documented as `O(incoming + data sources + outgoing sources)` (was understated as `O(incoming)` alone).
182
+ - Docs: `deref`/`aliveRef` are documented as "never throws for a live world" (was an unqualified "never throws") — both throw `EcsError` once the world has been disposed.
183
+ - Docs: the README / README_ZHTW Quick Start no longer corrupts the world: it did `pos.x += vel.x` on the column objects returned by `getComponent`, which replaced the `Position.x` column with a string; it now indexes the columns with `forEachEntityIndexed`'s `i` over a `defineQuery` query (the TypeScript signature does not accept a raw array).
184
+ - Docs: README / README_ZHTW gain Snapshots, Relations and Errors sections; STABILITY gains a Behavioral Contract section (the ai*js re-entrancy clause for observer dispatch, argument validation, read-only mutators, relation liveness, snapshot format 2); `docs/MIGRATION.md` / `MIGRATION_ZHTW.md` gain "0.5.x -> 0.6.0 snapshots".
185
+ - Docs: README / STABILITY no longer describe reactive-query tracking as a module-level cache scan; it is a per-component index.
186
+ - Docs: `api.json` is updated for 0.6.0 signatures and throws, documents that the `defineObjectComponent` factory runs once per entity on first add (not once at definition), and lists `DeserializeOptions.components`.
102
187
 
103
188
  ## [0.5.9] - 2026-06-29
104
189
 
@@ -144,25 +229,36 @@ aiecsjs keeps the root ECS surface stable and treats subpaths as explicit public
144
229
  | `aiecsjs/loop` | Stable utility | Loop helper only; scheduler policy remains app-owned. |
145
230
  | `aiecsjs/commands` | Stable utility | Command buffers for deferred structural mutations. |
146
231
  | `aiecsjs/observers` | Stable utility | Add/remove/set observer helpers. |
147
- | `aiecsjs/serialize` | Stable utility | Binary and JSON snapshots with capacity clamps. |
232
+ | `aiecsjs/serialize` | Stable utility | Binary and JSON snapshots with capacity clamps; format 2; keyed components; mismatch rejected. |
148
233
  | `aiecsjs/worker` | Experimental adapter | Environment-dependent SAB/transfer helpers. |
149
- | `aiecsjs/relations` | Stable | Relations and `ChildOf`; destroy cleanup cost remains documented. |
234
+ | `aiecsjs/relations` | Stable | Relations and `ChildOf`; `addRelation` throws `EcsError` for a dead source or target, mirroring `addComponent`; destroy cleanup cost remains documented. |
150
235
  | `aiecsjs/internal/*` | Private | No compatibility guarantee. |
151
236
 
237
+ ## Behavioral Contract
238
+
239
+ - Re-entrancy (ai*js rule for pure fan-out emitters): observer dispatch (`onAdd`, `onRemove`, `onSet`, `observe`) is synchronous and depth-first. A structural change made inside a handler, with its own notifications, runs to completion before the outer dispatch resumes; the outer dispatch keeps iterating its pre-taken snapshot and skips observers removed meanwhile; nested dispatch is never rejected or queued. aiecsjs has no `once` observers.
240
+ - Structural changes are applied at once, never queued. A handler that destroys the entity being destroyed, or removes the component being removed, makes the nested call a no-op and the outer call finishes. `flush()` on a buffer that is already flushing returns immediately; ops queued during a flush run in later rounds of that flush, in queue order.
241
+ - Misuse throws `EcsError` (message `aiecsjs: <subject> must be <constraint>` or `aiecsjs: <operation> on dead entity <eid>`) before any change is made: a non-integer `initialCapacity` / `maxEntities` / `indexBits` / `generationBits`; an empty, non-string or duplicate component `key`; a non-function observer handler, `forEachEntity` / `forEachEntityIndexed` / `withCommandBuffer` callback, `pipe` system or AoS factory; an AoS factory that returns `null` / `undefined`; a value that is not a relation handle; a missing world or component handle.
242
+ - `defineComponent` field-declaration errors and non-Query input to the query functions throw `TypeError`. `aiecsjs/loop` exports no error class: `createLoop` throws `TypeError` for a missing options object or a non-function `onUpdate` / `onRender` and `RangeError` for a `fixed` that is not a finite number > 0 or a `maxSubSteps` that is not a finite number >= 1.
243
+ - A read-only world (`attachWorld(buffer, { readOnly: true })`) rejects every mutator with `EcsError`: `createEntity`, `destroyEntity`, `addComponent`, `removeComponent`, `setComponent`, `resetWorld`, `addRelation`, `removeRelation` and delta `apply()`.
244
+ - `addRelation` throws `EcsError` for a dead source or target; `removeRelation` is lenient. `destroyEntity` and `resetWorld` drop the edges of the entities they remove, so relation storage never holds an edge for a dead entity.
245
+ - Snapshots are format 2: `toJSON`, `serializeWorld` and delta `capture()` write `formatVersion: 2` and a table of every referenced component (`id`, `key`, `kind`, SoA `fields`). `fromJSON`, `deserializeWorld`, delta `apply()`, `adoptSnapshot` and `attachWorld` resolve every component (by `key`, by `id` when keyless) before they create or write anything. An undefined component throws `EcsError` unless `onUnknownComponent: 'skip'`; a kind or SoA-field mismatch always throws. A snapshot of another format version (every 0.5.x snapshot) throws unless `onUnknownVersion: 'best-effort'`, which resolves by `id` with a kind check only.
246
+
152
247
  ## Behavioral Boundaries
153
248
 
154
249
  - Entity ids are generational numeric ids. Use refs (`refOf`, `deref`, `aliveRef`) when storing ids across time.
155
250
  - Query iteration is synchronous and direct. Use command buffers for structural changes inside systems.
156
251
  - Reactive query buffers must be drained by the caller.
157
252
  - Serialization accepts trusted snapshots; hostile input is bounded but not a sandbox.
253
+ - `fromJSON` / `deserializeWorld` re-create entities in snapshot order with fresh ids; EntityIds stored inside component data are not remapped.
158
254
  - No build-mode-gated runtime validation policy is promised.
159
255
  - Worker support depends on `SharedArrayBuffer`, transfer support, and browser isolation policy.
160
256
 
161
257
  ## Current Caveats
162
258
 
163
- - Reactive query registration scans a module-level query cache on structural changes.
164
- - Exclusive relation cleanup touches only the incoming edges (`O(incoming)`) when an entity is destroyed, via a reverse index — no full relation-capacity scan.
165
- - Lint has many `noExplicitAny` warnings pending cleanup.
259
+ - Queries are cached process-wide, and reactive (enter/exit) source queries are indexed process-wide by component: a structural change visits every such source that references the changed component, whichever world registered it.
260
+ - Exclusive relation cleanup avoids a full relation-capacity scan (via a reverse index it touches only `O(incoming)` exclusive edges), but it still walks every relation's `data` payload sources and `outgoing` (non-exclusive) edge lists on every destroy: `O(incoming + data sources + outgoing sources)` across all relations, even for entities with no relations.
261
+ - Lint reports `noExplicitAny` warnings, mostly test casts plus the public query callback types (typed per arity only in a future design).
166
262
 
167
263
  ---
168
264
 
package/llms.txt CHANGED
@@ -7,4 +7,5 @@ Archetype ECS with TypedArray SoA components, command buffers, relations, snapsh
7
7
  - Current backlog: REVIEW.md
8
8
  - Machine-readable API: api.json
9
9
  - Changelog: CHANGELOG.md
10
+ - Migration and upgrade notes: docs/MIGRATION.md
10
11
  - Full generated context: llms-full.txt
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aiecsjs",
3
- "version": "0.5.9",
3
+ "version": "0.6.0",
4
4
  "description": "TypeScript-first archetype ECS with TypedArray SoA, SAB-ready snapshot transport, and AI-readable docs.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -8,39 +8,74 @@
8
8
  "types": "./dist/index.d.ts",
9
9
  "exports": {
10
10
  ".": {
11
- "types": "./dist/index.d.ts",
12
- "import": "./dist/index.js",
13
- "require": "./dist/index.cjs"
11
+ "import": {
12
+ "types": "./dist/index.d.ts",
13
+ "default": "./dist/index.js"
14
+ },
15
+ "require": {
16
+ "types": "./dist/index.d.cts",
17
+ "default": "./dist/index.cjs"
18
+ }
14
19
  },
15
20
  "./loop": {
16
- "types": "./dist/loop.d.ts",
17
- "import": "./dist/loop.js",
18
- "require": "./dist/loop.cjs"
21
+ "import": {
22
+ "types": "./dist/loop.d.ts",
23
+ "default": "./dist/loop.js"
24
+ },
25
+ "require": {
26
+ "types": "./dist/loop.d.cts",
27
+ "default": "./dist/loop.cjs"
28
+ }
19
29
  },
20
30
  "./commands": {
21
- "types": "./dist/commands.d.ts",
22
- "import": "./dist/commands.js",
23
- "require": "./dist/commands.cjs"
31
+ "import": {
32
+ "types": "./dist/commands.d.ts",
33
+ "default": "./dist/commands.js"
34
+ },
35
+ "require": {
36
+ "types": "./dist/commands.d.cts",
37
+ "default": "./dist/commands.cjs"
38
+ }
24
39
  },
25
40
  "./observers": {
26
- "types": "./dist/observers.d.ts",
27
- "import": "./dist/observers.js",
28
- "require": "./dist/observers.cjs"
41
+ "import": {
42
+ "types": "./dist/observers.d.ts",
43
+ "default": "./dist/observers.js"
44
+ },
45
+ "require": {
46
+ "types": "./dist/observers.d.cts",
47
+ "default": "./dist/observers.cjs"
48
+ }
29
49
  },
30
50
  "./serialize": {
31
- "types": "./dist/serialize.d.ts",
32
- "import": "./dist/serialize.js",
33
- "require": "./dist/serialize.cjs"
51
+ "import": {
52
+ "types": "./dist/serialize.d.ts",
53
+ "default": "./dist/serialize.js"
54
+ },
55
+ "require": {
56
+ "types": "./dist/serialize.d.cts",
57
+ "default": "./dist/serialize.cjs"
58
+ }
34
59
  },
35
60
  "./worker": {
36
- "types": "./dist/worker.d.ts",
37
- "import": "./dist/worker.js",
38
- "require": "./dist/worker.cjs"
61
+ "import": {
62
+ "types": "./dist/worker.d.ts",
63
+ "default": "./dist/worker.js"
64
+ },
65
+ "require": {
66
+ "types": "./dist/worker.d.cts",
67
+ "default": "./dist/worker.cjs"
68
+ }
39
69
  },
40
70
  "./relations": {
41
- "types": "./dist/relations.d.ts",
42
- "import": "./dist/relations.js",
43
- "require": "./dist/relations.cjs"
71
+ "import": {
72
+ "types": "./dist/relations.d.ts",
73
+ "default": "./dist/relations.js"
74
+ },
75
+ "require": {
76
+ "types": "./dist/relations.d.cts",
77
+ "default": "./dist/relations.cjs"
78
+ }
44
79
  },
45
80
  "./package.json": "./package.json"
46
81
  },
@@ -1,2 +0,0 @@
1
- 'use strict';var chunkQ2XLL6YG_cjs=require('./chunk-Q2XLL6YG.cjs');var p="AIEC",b=1;function Q(n,o){let e=B(n);return o?.components&&(e.entities=e.entities.map(t=>({eid:t.eid,components:t.components.filter(i=>o.components.some(c=>c.__id===i.id))}))),D(e)}function Z(n,o){let e=x(n,o);return T(e)}function B(n){let o=chunkQ2XLL6YG_cjs.j(n),e=[];for(let t=1;t<o.capacity;t++){let i=o.entityArchetype[t]??0;if(i===0)continue;let c=o.archetypes[i];if(!c)continue;let r=o.generations[t]??0,a=chunkQ2XLL6YG_cjs.s(t,r,o.options);if(!c.entityRow.has(a))continue;let s=o.options.maskWordCount,f=t*s,l=[];for(let d=0;d<s;d++){let m=o.entityMask[f+d]??0;for(;m!==0;){let M=m&-m,_=(d<<5)+(31-Math.clz32(M)),h=o.componentInfoByBit[_];if(h){let S=o.componentStorageByBit[_],w=null;if(h.kind==="soa"&&S?.soa){let y={};for(let u of h.fields){let g=S.soa[u.name];if(g)if(u.vectorLen===1)y[u.name]=g[t];else {let v=[],N=t*u.vectorLen;for(let C=0;C<u.vectorLen;C++)v.push(g[N+C]??0);y[u.name]=v;}}w=y;}else h.kind==="aos"&&S?.aos?w=S.aos[t]??null:w=true;l.push({kind:h.kind,id:h.id,data:w});}m&=m-1;}}e.push({eid:t,components:l});}return {version:o.version,capacity:o.capacity,entities:e}}var R=1024;function J(n,o){let e=Math.max(R,o+1);return typeof n!="number"||!Number.isFinite(n)||n<=0?e:Math.min(Math.floor(n),e)}function T(n){let o=J(n.capacity,n.entities.length),e=chunkQ2XLL6YG_cjs.l({initialCapacity:o}),t=new Map;for(let i of n.entities){let c=chunkQ2XLL6YG_cjs.v(e);t.set(i.eid,c);}for(let i of n.entities){let c=t.get(i.eid);for(let r of i.components){let a=chunkQ2XLL6YG_cjs.R(r.id);if(!a)continue;let s=A(a);s&&chunkQ2XLL6YG_cjs.K(e,c,s,r.data);}}return e}function A(n){if(n.kind==="soa")return {__kind:"soa",__id:n.id,__schema:n.schema??{}};if(n.kind==="aos"){let o=n.factory??(()=>({}));return {__kind:"aos",__id:n.id,__factory:o}}return {__kind:"tag",__id:n.id}}function D(n){let o=JSON.stringify(n),e=new TextEncoder().encode(o),t=new TextEncoder().encode(chunkQ2XLL6YG_cjs.a),c=12+t.length+4+e.length,r=new Uint8Array(c),a=new DataView(r.buffer),s=0;return r[s++]=p.charCodeAt(0),r[s++]=p.charCodeAt(1),r[s++]=p.charCodeAt(2),r[s++]=p.charCodeAt(3),a.setUint32(s,b,true),s+=4,a.setUint32(s,t.length,true),s+=4,r.set(t,s),s+=t.length,a.setUint32(s,e.length,true),s+=4,r.set(e,s),r}function x(n,o){if(n.length<12)throw new Error("aiecsjs: bytes too short to be a valid snapshot");let e=new DataView(n.buffer,n.byteOffset,n.byteLength);if(n[0]!==p.charCodeAt(0)||n[1]!==p.charCodeAt(1)||n[2]!==p.charCodeAt(2)||n[3]!==p.charCodeAt(3))throw new Error("aiecsjs: invalid magic bytes");let t=4,i=e.getUint32(t,true);t+=4;let c=o?.onUnknownVersion??"throw";if(i!==b&&c==="throw")throw new Error(`aiecsjs: format version ${i} not supported`);let r=64*1024*1024;if(t+4>n.length)throw new Error("aiecsjs: snapshot truncated before verLen");let a=e.getUint32(t,true);if(t+=4,a>r||t+a>n.length)throw new Error(`aiecsjs: snapshot verLen=${a} out of bounds`);if(t+=a,t+4>n.length)throw new Error("aiecsjs: snapshot truncated before jsonLen");let s=e.getUint32(t,true);if(t+=4,s>r||t+s>n.length)throw new Error(`aiecsjs: snapshot jsonLen=${s} out of bounds`);let f=n.subarray(t,t+s),l=new TextDecoder().decode(f);try{return JSON.parse(l)}catch(d){throw new Error("aiecsjs: snapshot body is not valid JSON",{cause:d})}}function tt(n,o){let e={world:n,components:o?.components??chunkQ2XLL6YG_cjs.S().map(t=>A(t)).filter(Boolean),lastSnapshot:null};return {capture(){let t=B(e.world),i;return e.lastSnapshot?i=V(e.lastSnapshot,t):i=t,e.lastSnapshot=t,D(i)},apply(t,i){let c=x(i),r=chunkQ2XLL6YG_cjs.j(t);for(let a of c.entities){if(a.eid<=0||a.eid>=r.options.maxEntities)continue;let s=chunkQ2XLL6YG_cjs.w(r,a.eid);for(let f of a.components){let l=chunkQ2XLL6YG_cjs.R(f.id);if(!l)continue;let d=A(l);d&&chunkQ2XLL6YG_cjs.K(t,s,d,f.data);}}},reset(){e.lastSnapshot=null;}}}function V(n,o){let e=new Map(n.entities.map(i=>[i.eid,i])),t=[];for(let i of o.entities){let c=e.get(i.eid);if(!c){t.push(i);continue}let r=JSON.stringify(c.components),a=JSON.stringify(i.components);r!==a&&t.push(i);}return {version:o.version,capacity:o.capacity,entities:t}}exports.a=Q;exports.b=Z;exports.c=B;exports.d=T;exports.e=tt;//# sourceMappingURL=chunk-JDV5JZP2.cjs.map
2
- //# sourceMappingURL=chunk-JDV5JZP2.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/serialize.ts"],"names":["MAGIC","FORMAT_VERSION","serializeWorld","world","options","snapshot","toJSON","e","c","comp","packBinary","deserializeWorld","bytes","unpackBinary","fromJSON","state","getWorldState","entities","idx","archId","arch","gen","packedEid","packEid","w","base","components","wi","word","lsb","bit","info","storage","data","obj","f","col","arr","baseI","i","RESTORE_CAPACITY_FLOOR","clampRestoreCapacity","rawCapacity","entityCount","needed","initialCapacity","createWorld","eidMap","eid","createEntity","getComponentByInternalId","handle","getComponentHandle","addComponent","factory","json","jsonBytes","versionBytes","VERSION","total","out","view","off","formatVersion","onUnknown","MAX_FIELD_LEN","verLen","jsonLen","cause","createDeltaSerializer","listAllComponents","current","delta","computeDelta","targetWorld","deltaBytes","targetState","ensureEntityA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AAC,EACzC,CACA,OAAO,CAAE,OAAA,CAASwE,CAAAA,CAAK,OAAA,CAAS,QAAA,CAAUA,CAAAA,CAAK,QAAA,CAAU,QAAA,CAAUE,CAAQ,CAC7E","file":"chunk-JDV5JZP2.cjs","sourcesContent":["// aiecsjs/serialize — binary, JSON, and delta serializers.\n\nimport { testBit } from './internal/bitmask.js'\nimport {\n addComponent,\n defineComponent,\n defineObjectComponent,\n defineTag,\n getComponentByInternalId,\n getComponentInfo,\n listAllComponents,\n} from './internal/component.js'\nimport { createEntity, destroyEntity, ensureEntityAtSlot, packEid } from './internal/entity.js'\nimport type {\n ComponentInfo,\n ComponentInit,\n ComponentLike,\n DeltaSerializer,\n DeserializeOptions,\n EntityId,\n SerializeOptions,\n World,\n WorldSnapshot,\n} from './internal/types.js'\nimport { createWorld, getWorldState } from './internal/world.js'\nimport { VERSION } from './version.js'\n\nconst MAGIC = 'AIEC'\nconst FORMAT_VERSION = 1\n\nexport function serializeWorld(world: World, options?: SerializeOptions): Uint8Array {\n const snapshot = toJSON(world)\n if (options?.components) {\n snapshot.entities = snapshot.entities.map((e) => ({\n eid: e.eid,\n components: e.components.filter((c) =>\n options.components!.some((comp) => comp.__id === c.id),\n ),\n }))\n }\n return packBinary(snapshot)\n}\n\nexport function deserializeWorld(bytes: Uint8Array, options?: DeserializeOptions): World {\n const snapshot = unpackBinary(bytes, options)\n return fromJSON(snapshot)\n}\n\n/**\n * Serialize a world snapshot to a plain JSON-compatible object.\n *\n * Note: `EntityRef` is in-memory only — not preserved across serialize/deserialize.\n * Generation counters reset on world load. Stale refs from before serialization\n * will deref to null after loading the snapshot into a new world.\n */\nexport function toJSON(world: World): WorldSnapshot {\n const state = getWorldState(world)\n const entities: WorldSnapshot['entities'] = []\n // Iterate by raw slot index; snapshot stores raw idx in the `eid` field\n // (wire format unchanged — idx is used for load-side entity re-creation).\n for (let idx = 1; idx < state.capacity; idx++) {\n const archId = state.entityArchetype[idx] ?? 0\n if (archId === 0) continue // slot unused\n\n const arch = state.archetypes[archId]\n if (!arch) continue\n\n // Build the packed eid from idx + current generation to do alive check\n const gen = state.generations[idx] ?? 0\n const packedEid = packEid(idx, gen, state.options)\n if (!arch.entityRow.has(packedEid)) continue\n\n const w = state.options.maskWordCount\n const base = idx * w\n const components: WorldSnapshot['entities'][0]['components'] = []\n for (let wi = 0; wi < w; wi++) {\n let word = state.entityMask[base + wi] ?? 0\n while (word !== 0) {\n const lsb = word & -word\n const bit = (wi << 5) + (31 - Math.clz32(lsb))\n const info = state.componentInfoByBit[bit]\n if (info) {\n const storage = state.componentStorageByBit[bit]\n let data: unknown = null\n if (info.kind === 'soa' && storage?.soa) {\n const obj: Record<string, unknown> = {}\n for (const f of info.fields) {\n const col = storage.soa[f.name]\n if (!col) continue\n if (f.vectorLen === 1) {\n obj[f.name] = col[idx]\n } else {\n const arr: number[] = []\n const baseI = idx * f.vectorLen\n for (let i = 0; i < f.vectorLen; i++) arr.push(col[baseI + i] ?? 0)\n obj[f.name] = arr\n }\n }\n data = obj\n } else if (info.kind === 'aos' && storage?.aos) {\n data = storage.aos[idx] ?? null\n } else {\n data = true\n }\n components.push({ kind: info.kind, id: info.id, data })\n }\n word &= word - 1\n }\n }\n // Wire format stores raw idx (not packed) for cross-session portability\n entities.push({ eid: idx, components })\n }\n return {\n version: state.version,\n capacity: state.capacity,\n entities,\n }\n}\n\n// Default initial-capacity floor for a restored world (matches createWorld's\n// own default). Keeps the common round-trip from needlessly shrinking while\n// staying a trivial allocation (~36 KB of index arrays at 1024 slots).\nconst RESTORE_CAPACITY_FLOOR = 1024\n\n// SECURITY (ECS-S-01): the snapshot `capacity` field is attacker-controlled on\n// any untrusted-load path (localStorage, network — both documented flows for the\n// stable deserializeWorld). createWorld only clamps to 1<<indexBits (16,777,216),\n// so an inflated value forces a near-600 MB TypedArray allocation from a tiny\n// payload — a browser-tab OOM DoS. Clamp the *starting* capacity to the real\n// entity count (fromJSON re-creates entities via createEntity, which grows the\n// world on demand, so a tight initial hint never loses data). A garbage/missing\n// value falls back to the count too.\nfunction clampRestoreCapacity(rawCapacity: unknown, entityCount: number): number {\n const needed = Math.max(RESTORE_CAPACITY_FLOOR, entityCount + 1)\n if (typeof rawCapacity !== 'number' || !Number.isFinite(rawCapacity) || rawCapacity <= 0) {\n return needed\n }\n return Math.min(Math.floor(rawCapacity), needed)\n}\n\nexport function fromJSON(snapshot: WorldSnapshot): World {\n const initialCapacity = clampRestoreCapacity(snapshot.capacity, snapshot.entities.length)\n const world = createWorld({ initialCapacity })\n const eidMap = new Map<number, EntityId>()\n for (const e of snapshot.entities) {\n const eid = createEntity(world)\n eidMap.set(e.eid, eid)\n }\n for (const e of snapshot.entities) {\n const eid = eidMap.get(e.eid)!\n for (const comp of e.components) {\n const info = getComponentByInternalId(comp.id)\n if (!info) {\n // Component missing — silently skip; future version may throw based on options\n continue\n }\n const handle = getComponentHandle(info)\n if (handle) {\n addComponent(world, eid, handle, comp.data as ComponentInit<ComponentLike>)\n }\n }\n }\n return world\n}\n\n// Reconstruct a component handle from its ComponentInfo. Since defineComponent\n// returns plain handles { __kind, __id, __schema }, we can synthesize them.\nfunction getComponentHandle(info: ComponentInfo): ComponentLike | null {\n if (info.kind === 'soa') {\n return { __kind: 'soa', __id: info.id, __schema: info.schema ?? {} } as ComponentLike\n }\n if (info.kind === 'aos') {\n const factory = info.factory ?? (() => ({}))\n return { __kind: 'aos', __id: info.id, __factory: factory } as ComponentLike\n }\n return { __kind: 'tag', __id: info.id } as ComponentLike\n}\n\n// --- Binary packing (wrapped JSON for 0.1) ---\n\nfunction packBinary(snapshot: WorldSnapshot): Uint8Array {\n const json = JSON.stringify(snapshot)\n const jsonBytes = new TextEncoder().encode(json)\n const versionBytes = new TextEncoder().encode(VERSION)\n const headerSize = 4 + 4 + 4 + versionBytes.length + 4\n const total = headerSize + jsonBytes.length\n const out = new Uint8Array(total)\n const view = new DataView(out.buffer)\n let off = 0\n out[off++] = MAGIC.charCodeAt(0)\n out[off++] = MAGIC.charCodeAt(1)\n out[off++] = MAGIC.charCodeAt(2)\n out[off++] = MAGIC.charCodeAt(3)\n view.setUint32(off, FORMAT_VERSION, true)\n off += 4\n view.setUint32(off, versionBytes.length, true)\n off += 4\n out.set(versionBytes, off)\n off += versionBytes.length\n view.setUint32(off, jsonBytes.length, true)\n off += 4\n out.set(jsonBytes, off)\n return out\n}\n\nfunction unpackBinary(bytes: Uint8Array, options?: DeserializeOptions): WorldSnapshot {\n if (bytes.length < 12) throw new Error('aiecsjs: bytes too short to be a valid snapshot')\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)\n if (\n bytes[0] !== MAGIC.charCodeAt(0) ||\n bytes[1] !== MAGIC.charCodeAt(1) ||\n bytes[2] !== MAGIC.charCodeAt(2) ||\n bytes[3] !== MAGIC.charCodeAt(3)\n ) {\n throw new Error('aiecsjs: invalid magic bytes')\n }\n let off = 4\n const formatVersion = view.getUint32(off, true)\n off += 4\n const onUnknown = options?.onUnknownVersion ?? 'throw'\n if (formatVersion !== FORMAT_VERSION && onUnknown === 'throw') {\n throw new Error(`aiecsjs: format version ${formatVersion} not supported`)\n }\n\n // SECURITY: explicit bounds checks on every length field. DataView itself\n // throws on out-of-range reads, but an attacker who controls the bytes can\n // still craft a `verLen` that skips past data of their choosing — we make\n // each step's invariant explicit and impose a sane cap to short-circuit\n // pathological payloads early.\n const MAX_FIELD_LEN = 64 * 1024 * 1024 // 64 MiB\n if (off + 4 > bytes.length) {\n throw new Error('aiecsjs: snapshot truncated before verLen')\n }\n const verLen = view.getUint32(off, true)\n off += 4\n if (verLen > MAX_FIELD_LEN || off + verLen > bytes.length) {\n throw new Error(`aiecsjs: snapshot verLen=${verLen} out of bounds`)\n }\n off += verLen // skip the aiecsjs version string\n\n if (off + 4 > bytes.length) {\n throw new Error('aiecsjs: snapshot truncated before jsonLen')\n }\n const jsonLen = view.getUint32(off, true)\n off += 4\n if (jsonLen > MAX_FIELD_LEN || off + jsonLen > bytes.length) {\n throw new Error(`aiecsjs: snapshot jsonLen=${jsonLen} out of bounds`)\n }\n const jsonBytes = bytes.subarray(off, off + jsonLen)\n const json = new TextDecoder().decode(jsonBytes)\n // Wrap the parse so a malformed body (e.g. a truncated/garbled payload reached\n // under onUnknownVersion:'best-effort') surfaces a namespaced `aiecsjs:` error\n // instead of leaking a raw SyntaxError — consistent with the rest of the module.\n // Bounds checks above already guarantee `json` covers exactly the declared body.\n try {\n return JSON.parse(json) as WorldSnapshot\n } catch (cause) {\n throw new Error('aiecsjs: snapshot body is not valid JSON', { cause })\n }\n}\n\n// --- Delta serializer ---\n\ninterface DeltaState {\n world: World\n components: ComponentLike[]\n lastSnapshot: WorldSnapshot | null\n}\n\nexport function createDeltaSerializer(world: World, options?: SerializeOptions): DeltaSerializer {\n const state: DeltaState = {\n world,\n components:\n options?.components ??\n listAllComponents()\n .map((i) => getComponentHandle(i)!)\n .filter(Boolean),\n lastSnapshot: null,\n }\n return {\n capture(): Uint8Array {\n const current = toJSON(state.world)\n let delta: WorldSnapshot\n if (!state.lastSnapshot) {\n delta = current\n } else {\n // Compute simple delta: entities with changed components\n delta = computeDelta(state.lastSnapshot, current)\n }\n state.lastSnapshot = current\n return packBinary(delta)\n },\n apply(targetWorld: World, deltaBytes: Uint8Array): void {\n const snapshot = unpackBinary(deltaBytes)\n // Materialise each snapshot entity at the SAME slot index the source used\n // (the wire stores raw slot indices in `eid`). ensureEntityAtSlot reuses a\n // live slot, reclaims a freed one, or advances the frontier — so apply() is\n // sound on a non-pristine / independently-churned replica (it uses the\n // slot's CURRENT generation, never gen=0) and never spawns phantom padding\n // entities for holes in the source's slot range.\n //\n // CAVEAT: deltas carry added/changed entities only (see computeDelta) —\n // entity REMOVALS are not represented, so a replica is not pruned when the\n // source destroys an entity, and a component removed on the source is not\n // removed on the replica. apply() is additive/updating.\n const targetState = getWorldState(targetWorld)\n for (const e of snapshot.entities) {\n if (e.eid <= 0 || e.eid >= targetState.options.maxEntities) continue\n const eid = ensureEntityAtSlot(targetState, e.eid)\n for (const comp of e.components) {\n const info = getComponentByInternalId(comp.id)\n if (!info) continue\n const handle = getComponentHandle(info)\n if (handle)\n addComponent(targetWorld, eid, handle, comp.data as ComponentInit<ComponentLike>)\n }\n }\n },\n reset(): void {\n state.lastSnapshot = null\n },\n }\n}\n\nfunction computeDelta(prev: WorldSnapshot, curr: WorldSnapshot): WorldSnapshot {\n const prevByEid = new Map(prev.entities.map((e) => [e.eid, e]))\n const changed: WorldSnapshot['entities'] = []\n for (const e of curr.entities) {\n const prevE = prevByEid.get(e.eid)\n if (!prevE) {\n changed.push(e)\n continue\n }\n const prevSig = JSON.stringify(prevE.components)\n const currSig = JSON.stringify(e.components)\n if (prevSig !== currSig) changed.push(e)\n }\n return { version: curr.version, capacity: curr.capacity, entities: changed }\n}\n"]}
@@ -1,2 +0,0 @@
1
- var F="0.5.9";function T(t){return new Uint32Array(t)}function z(t,n){let e=n>>>5;t[e]=(t[e]??0)|1<<(n&31);}function E(t,n){let e=n>>>5;t[e]=(t[e]??0)&~(1<<(n&31));}function A(t,n){let e=n>>>5;return ((t[e]??0)&1<<(n&31))!==0}function b(t){let n=new Uint32Array(t.length);for(let e=0;e<t.length;e++)n[e]=t[e]??0;return n}function W(t){let n=[];for(let e=0;e<t.length;e++)n.push((t[e]??0).toString(16));return n.join(",")}function xn(t){for(let n=0;n<t.length;n++)if((t[n]??0)!==0)return false;return true}function gn(t,n,e,o,r,i){let s=!r;for(let a=0;a<i;a++){let c=t[a]??0,f=n[a]??0,d=e[a]??0,u=o[a]??0;if((c&f)!==f||(c&u)!==0)return false;!s&&(c&d)!==0&&(s=true);}return s}function kn(t){let n=[];for(let e=0;e<t.length;e++){let o=t[e]??0;for(;o!==0;){let r=(e<<5)+D(o);n.push(r),o&=o-1;}}return n}function B(t,n,e,o){for(let r=0;r<e;r++){let i=t[n+r]??0;for(;i!==0;){let s=(r<<5)+D(i);o(s),i&=i-1;}}}function Cn(t,n,e,o,r,i,s){let a=!s;for(let c=0;c<e;c++){let f=t[n+c]??0,d=o[c]??0,u=r[c]??0,l=i[c]??0;if((f&d)!==d||(f&l)!==0)return false;!a&&(f&u)!==0&&(a=true);}return a}function D(t){return 31-Math.clz32(t&-t)}var p=class extends Error{constructor(n){super(n),this.name="EcsError";}};var S={initialCapacity:1024,maxEntities:1e6,indexBits:24,generationBits:8},nn=256,tn=1,w=new Map;function y(t){let n=w.get(t.id);if(!n)throw new p(`aiecsjs: world ${t.id} is destroyed or unknown`);if(n.destroyed)throw new p(`aiecsjs: world ${t.id} is destroyed`);return n}function en(t){w.set(t.id,t);}function on(t){w.delete(t);}function Mn(t){return w.has(t)}function rn(t){let n=t??{},e=n.indexBits??S.indexBits,o=n.generationBits??S.generationBits,r=nn;if(e<1||e>24)throw new p("aiecsjs: indexBits must be in [1, 24]");if(o<0||o>16)throw new p("aiecsjs: generationBits must be in [0, 16]");if(e+o>32)throw new p(`aiecsjs: indexBits (${e}) + generationBits (${o}) must be <= 32`);let i=1<<e,s=Math.max(1,Math.min(n.initialCapacity??S.initialCapacity,i)),a=Math.max(s,Math.min(n.maxEntities??S.maxEntities,i));return {initialCapacity:s,maxEntities:a,indexBits:e,generationBits:o,indexMask:(1<<e)-1,generationMask:o===0?0:(1<<o)-1,maxComponents:r,maskWordCount:Math.ceil(r/32),buffer:n.buffer??null,bufferByteOffset:n.bufferByteOffset??0}}function sn(t,n){return {id:0,mask:T(t),size:0,capacity:16,entities:new Uint32Array(16),entityRow:new Map,componentBits:[],edgeAdd:new Int32Array(n).fill(-1),edgeRemove:new Int32Array(n).fill(-1)}}function Un(t){let n=rn(t),e=tn++,o=n.generationBits>8?Uint16Array:Uint8Array,r=new o(n.initialCapacity),i={id:e,capacity:n.initialCapacity,version:F,options:n,size:0,nextFreshIndex:1,freeList:[],generations:r,destroyed:false,componentBitFor:new Map,componentInfoByBit:new Array(n.maxComponents).fill(null),componentStorageByBit:new Array(n.maxComponents).fill(null),nextComponentBit:0,entityArchetype:new Uint32Array(n.initialCapacity),entityMask:new Uint32Array(n.initialCapacity*n.maskWordCount),archetypes:[],archetypeByMaskHash:new Map,queryVersion:0,queries:[],queryMasks:new Map,queryArchetypeCache:[],queryArchetypeStamp:[],bitToQueries:new Map,reactiveBuffers:new Map,observers:[],relationStorage:new Map,sab:n.buffer,readOnly:false},s=sn(n.maskWordCount,n.maxComponents);return s.id=0,i.archetypes.push(s),i.archetypeByMaskHash.set(W(s.mask),0),en(i),an(i)}function an(t){return {id:t.id,get capacity(){return t.capacity},version:t.version}}function On(t){let n=w.get(t.id);!n||n.destroyed||(n.destroyed=true,n.archetypes=[],n.archetypeByMaskHash.clear(),n.componentInfoByBit=[],n.componentStorageByBit=[],n.queries=[],n.queryMasks.clear(),n.queryArchetypeCache=[],n.observers=[],n.relationStorage.clear(),n.reactiveBuffers.clear(),n.entityMask=new Uint32Array(0),n.entityArchetype=new Uint32Array(0),n.generations=new Uint8Array(0),n.freeList=[],n.componentBitFor.clear(),n.bitToQueries.clear(),n.queryArchetypeStamp=[],n.sab=null,on(t.id));}function Rn(t){let n=y(t);n.size=0,n.nextFreshIndex=1,n.freeList=[],n.generations.fill(0),n.entityArchetype.fill(0),n.entityMask.fill(0);for(let e of n.archetypes)e.size=0,e.entityRow.clear();for(let e of n.componentStorageByBit)if(e)if(e.kind==="soa"&&e.soa)for(let o of Object.keys(e.soa))e.soa[o]?.fill(0);else e.kind==="aos"&&e.aos&&e.aos.fill(void 0);n.relationStorage.clear(),n.queryVersion++;for(let e of n.reactiveBuffers.values())e.entered.length=0,e.exited.length=0;}function _n(t){return y(t).size}function Ln(t){return y(t).capacity}function M(t,n){if(n<=t.capacity)return;if(n>t.options.maxEntities)throw new p(`aiecsjs: requested capacity ${n} exceeds maxEntities ${t.options.maxEntities}`);let e=t.capacity;for(;e<n;)e=Math.min(e*2,t.options.maxEntities);cn(t,e);}function cn(t,n){let e=t.generations.constructor,o=new e(n);o.set(t.generations),t.generations=o;let r=new Uint32Array(n);r.set(t.entityArchetype),t.entityArchetype=r;let i=t.options.maskWordCount,s=new Uint32Array(n*i);s.set(t.entityMask),t.entityMask=s;for(let a of t.componentStorageByBit)if(a)if(a.kind==="soa"&&a.soa){let c=t.componentInfoByBit[a.bit];c&&fn(a.soa,c.fields,n);}else a.kind==="aos"&&a.aos&&(a.aos.length=n);t.capacity=n;}function fn(t,n,e){for(let o of n){let r=t[o.name];if(!r)continue;let i=e*o.vectorLen;if(r.length>=i)continue;let s=new o.ctor(i);s.set(r),t[o.name]=s;}}function N(t,n){let e=W(n),o=t.archetypeByMaskHash.get(e);if(o!==void 0)return {archId:o,created:false};let r=t.archetypes.length,i={id:r,mask:b(n),size:0,capacity:16,entities:new Uint32Array(16),entityRow:new Map,componentBits:dn(n),edgeAdd:new Int32Array(t.options.maxComponents).fill(-1),edgeRemove:new Int32Array(t.options.maxComponents).fill(-1)};return t.archetypes.push(i),t.archetypeByMaskHash.set(e,r),t.queryVersion++,{archId:r,created:true}}function k(t,n){if(n<=t.capacity)return;let e=t.capacity;for(;e<n;)e*=2;let o=new Uint32Array(e);o.set(t.entities),t.entities=o,t.capacity=e;}function dn(t){let n=[];for(let e=0;e<t.length;e++){let o=t[e]??0;for(;o!==0;){let r=o&-o,i=(e<<5)+(31-Math.clz32(r));n.push(i),o&=o-1;}}return n}function P(t,n){let e=t.componentBitFor.get(n.id);if(e!==void 0)return e;if(t.nextComponentBit>=t.options.maxComponents)throw new p(`aiecsjs: world reached maxComponents=${t.options.maxComponents}`);let o=t.nextComponentBit++;t.componentBitFor.set(n.id,o),t.componentInfoByBit[o]=n;let r;if(n.kind==="soa"){let i={};for(let s of n.fields)i[s.name]=new s.ctor(t.capacity*s.vectorLen);r={kind:"soa",componentId:n.id,bit:o,soa:i};}else n.kind==="aos"?r={kind:"aos",componentId:n.id,bit:o,aos:new Array(t.capacity)}:r={kind:"tag",componentId:n.id,bit:o};return t.componentStorageByBit[o]=r,o}function h(t,n){let e=t.options.maskWordCount,o=new Uint32Array(e),i=(n&t.options.indexMask)*e;for(let s=0;s<e;s++)o[s]=t.entityMask[i+s]??0;return o}function q(t,n,e){let o=t.options.maskWordCount,i=(n&t.options.indexMask)*o;for(let s=0;s<o;s++)t.entityMask[i+s]=e[s]??0;}function C(t,n){return t.componentBitFor.get(n.id)}function jn(t){if(!t||typeof t!="object")return false;let n=t;return typeof n.id!="number"||typeof n.version!="string"?false:w.has(n.id)}var O=1,un={i8:Int8Array,u8:Uint8Array,i16:Int16Array,u16:Uint16Array,i32:Int32Array,u32:Uint32Array,f32:Float32Array,f64:Float64Array,eid:Uint32Array,bool:Uint8Array},x=new Map;function Nn(t){let n=[];for(let[i,s]of Object.entries(t)){let a,c=1;if(typeof s=="string")a=s;else if(Array.isArray(s)){let[d,u]=s;a=d,c=u;}else throw new TypeError(`aiecsjs: invalid field declaration for "${i}"`);let f=un[a];if(!f)throw new TypeError(`aiecsjs: unknown field type "${a}" for field "${i}"`);n.push({name:i,type:a,vectorLen:c,ctor:f,bytesPerElement:f.BYTES_PER_ELEMENT});}let e=O++,o={id:e,kind:"soa",schema:t,fields:n,factory:null};return x.set(e,o),{__kind:"soa",__id:e,__schema:t}}function Pn(){let t=O++,n={id:t,kind:"tag",schema:null,fields:[],factory:null};return x.set(t,n),{__kind:"tag",__id:t}}function qn(t){let n=O++,e=t??(()=>({})),o={id:n,kind:"aos",schema:null,fields:[],factory:e};return x.set(n,o),{__kind:"aos",__id:n,__factory:e}}function g(t){let n=x.get(t.__id);if(!n)throw new Error("aiecsjs: component is not registered (call defineComponent/defineTag/defineObjectComponent)");return n}function $(t,n,e,o){let r=y(t);if(r.readOnly)throw new Error("aiecsjs: cannot mutate a read-only world");if(!m(r,n))throw new Error(`aiecsjs: addComponent on dead entity ${n}`);let i=g(e),s=P(r,i),a=h(r,n);if(A(a,s)){o!==void 0&&U(r,n,e,o);return}let c=b(a);z(c,s),V(r,n,c),U(r,n,e,o),ln(r,n,s),R(r,n,s,a,c);}function $n(t,n,e){let o=y(t);if(o.readOnly)throw new Error("aiecsjs: cannot mutate a read-only world");if(!m(o,n))return;let r=g(e),i=C(o,r);if(i===void 0)return;let s=h(o,n);if(!A(s,i))return;let a=b(s);E(a,i),V(o,n,a),yn(o,n,i);let c=n&o.options.indexMask,f=o.componentStorageByBit[i];f?.kind==="soa"&&f.soa?G(f.soa,r.fields,c):f?.kind==="aos"&&f.aos&&(f.aos[c]=void 0),R(o,n,i,s,a);}function Gn(t,n,e){let o=y(t);if(!m(o,n))return false;let r=g(e),i=C(o,r);if(i===void 0)return false;let s=h(o,n);return A(s,i)}function Hn(t,n,e){let o=y(t);if(!m(o,n))return;let r=g(e),i=C(o,r);if(i===void 0)return;let s=h(o,n);if(!A(s,i))return;let a=o.componentStorageByBit[i];if(a){if(a.kind==="soa")return a.soa;if(a.kind==="aos"){let c=n&o.options.indexMask;return a.aos?.[c]}return true}}function Vn(t,n,e,o){let r=y(t);if(r.readOnly)throw new Error("aiecsjs: cannot mutate a read-only world");if(!m(r,n))throw new Error(`aiecsjs: setComponent on dead entity ${n}`);let i=g(e),s=C(r,i);if(s===void 0){$(t,n,e,o);return}let a=h(r,n);if(!A(a,s)){$(t,n,e,o);return}U(r,n,e,o),pn(r,n,s,o);}function U(t,n,e,o){let r=g(e),i=t.componentBitFor.get(r.id);if(i===void 0)return;let s=t.componentStorageByBit[i];if(!s)return;let a=n&t.options.indexMask;if(r.kind==="soa"&&s.soa){if(o==null)return;let c=o;for(let f of r.fields){if(!(f.name in c))continue;let d=s.soa[f.name];if(!d)continue;let u=c[f.name];if(f.vectorLen===1)d[a]=typeof u=="boolean"?u?1:0:Number(u);else if(Array.isArray(u)||ArrayBuffer.isView(u)){let l=a*f.vectorLen,J=u;for(let I=0;I<f.vectorLen;I++)d[l+I]=Number(J[I]??0);}}}else if(r.kind==="aos"&&s.aos){let c=r.factory??(()=>({})),f=s.aos[a];if(f===void 0&&(f=c(),s.aos[a]=f),o&&typeof o=="object"){let d=o,u=f;for(let l of Object.keys(d))l==="__proto__"||l==="constructor"||l==="prototype"||(u[l]=d[l]);}}}function G(t,n,e){for(let o of n){let r=t[o.name];if(r)if(o.vectorLen===1)r[e]=0;else {let i=e*o.vectorLen;for(let s=0;s<o.vectorLen;s++)r[i+s]=0;}}}function H(t,n){let e=t.options.maskWordCount,o=n&t.options.indexMask,r=o*e;B(t.entityMask,r,e,i=>{let s=t.componentStorageByBit[i],a=t.componentInfoByBit[i];s?.kind==="soa"&&s.soa&&a?G(s.soa,a.fields,o):s?.kind==="aos"&&s.aos&&(s.aos[o]=void 0);});}function V(t,n,e){let o=n&t.options.indexMask,r=t.entityArchetype[o]??0,i=t.archetypes[r];if(!i)return;let a=N(t,e).archId,c=t.archetypes[a];if(c){if(a!==r){let f=i.entityRow.get(n);if(f!==void 0){let u=i.size-1;if(f!==u){let l=i.entities[u]??0;i.entities[f]=l,i.entityRow.set(l,f);}i.entities[u]=0,i.entityRow.delete(n),i.size--;}k(c,c.size+1);let d=c.size;c.entities[d]=n,c.entityRow.set(n,d),c.size++,t.entityArchetype[o]=a;}q(t,n,e);}}var v={fireAdd:()=>{},fireRemove:()=>{},fireSet:()=>{}},X=()=>{};function Xn(t){X=t;}function R(t,n,e,o,r){X(t,n,e,o,r);}function Y(t,n,e){let o=t.options.maskWordCount,r=b(e),i=b(e);B(e,0,o,s=>{E(i,s),R(t,n,s,r,i),E(r,s);});}function Yn(t){v=t;}function ln(t,n,e){v.fireAdd(t,n,e);}function yn(t,n,e){v.fireRemove(t,n,e);}function pn(t,n,e,o){v.fireSet(t,n,e,o);}function Kn(t){return x.get(t)}function Qn(){return Array.from(x.values())}var j=24,mn=8,K=(1<<j)-1,Q=(1<<mn)-1;function Z(t,n,e){return ((n&e.generationMask)<<e.indexBits|t&e.indexMask)>>>0}function tt(t,n){return t&n.indexMask}function et(t,n){return t>>>n.indexBits&n.generationMask}function ot(t){let n=y(t);if(n.readOnly)throw new Error("aiecsjs: cannot createEntity on a read-only world (worker-attached)");let e;if(n.freeList.length>0)e=n.freeList.pop();else {if(n.nextFreshIndex>=n.options.maxEntities)throw new Error(`aiecsjs: reached maxEntities ${n.options.maxEntities}`);n.nextFreshIndex>=n.capacity&&M(n,n.nextFreshIndex+1),e=n.nextFreshIndex++;}let o=n.generations[e]??0,r=Z(e,o,n.options),i=n.archetypes[0];if(!i)throw new Error("aiecsjs: missing empty archetype");k(i,i.size+1);let s=i.size;i.entities[s]=r,i.entityRow.set(r,s),i.size++,n.entityArchetype[e]=0;let a=n.options.maskWordCount,c=e*a;for(let f=0;f<a;f++)n.entityMask[c+f]=0;return n.size++,r}function rt(t,n){if(t.readOnly)throw new Error("aiecsjs: cannot create entities on a read-only world (worker-attached)");if(n<=0||n>=t.options.maxEntities)throw new Error(`aiecsjs: slot index ${n} out of range`);n>=t.capacity&&M(t,n+1);let e=t.generations[n]??0,o=Z(n,e,t.options);if(m(t,o))return o;if(n>=t.nextFreshIndex){for(let c=t.nextFreshIndex;c<n;c++)t.freeList.push(c);t.nextFreshIndex=n+1;}else {let c=t.freeList.lastIndexOf(n);if(c!==-1){let f=t.freeList.length-1;t.freeList[c]=t.freeList[f],t.freeList.pop();}}let r=t.archetypes[0];if(!r)throw new Error("aiecsjs: missing empty archetype");k(r,r.size+1);let i=r.size;r.entities[i]=o,r.entityRow.set(o,i),r.size++,t.entityArchetype[n]=0;let s=t.options.maskWordCount,a=n*s;for(let c=0;c<s;c++)t.entityMask[a+c]=0;return t.size++,o}function it(t,n){let e=y(t);if(e.readOnly)throw new Error("aiecsjs: cannot destroyEntity on a read-only world");if(!m(e,n))return;let o=n&e.options.indexMask,r=h(e,n),{dispatchDestroyObservers:i}=bn();i(e,n),An(e,n),H(e,n);let s=e.entityArchetype[o]??0,a=e.archetypes[s];if(a){let d=a.entityRow.get(n);if(d!==void 0){let u=a.size-1;if(d!==u){let l=a.entities[u]??0;a.entities[d]=l,a.entityRow.set(l,d);}a.entities[u]=0,a.entityRow.delete(n),a.size--;}}Y(e,n,r),e.entityArchetype[o]=0;let c=e.options.maskWordCount,f=o*c;for(let d=0;d<c;d++)e.entityMask[f+d]=0;e.generations[o]=(e.generations[o]??0)+1&e.options.generationMask,e.freeList.push(o),e.size--;}function hn(t,n){let e=y(t);return m(e,n)}function m(t,n){let e=n&t.options.indexMask;if(e<=0||e>=t.capacity)return false;let o=t.entityArchetype[e]??0,r=t.archetypes[o];if(!r||!r.entityRow.has(n))return false;let i=t.generations[e]??0,s=n>>>t.options.indexBits&t.options.generationMask;return i===s}function st(t){return t&K}function at(t){return t>>>j&Q}function ct(t,n){return ((n&Q)<<j|t&K)>>>0}function ft(t,n){return typeof n!="number"?false:hn(t,n)}var _=null;function dt(t){_=t;}function bn(){return _||{dispatchDestroyObservers:()=>{}}}var L=null;function ut(t){L=t;}function An(t,n){L&&L(t,n);}export{st as A,at as B,ct as C,ft as D,dt as E,ut as F,Nn as G,Pn as H,qn as I,g as J,$ as K,$n as L,Gn as M,Hn as N,Vn as O,Xn as P,Yn as Q,Kn as R,Qn as S,F as a,T as b,z as c,xn as d,gn as e,kn as f,B as g,Cn as h,p as i,y as j,Mn as k,Un as l,On as m,Rn as n,_n as o,Ln as p,P as q,jn as r,Z as s,tt as t,et as u,ot as v,rt as w,it as x,hn as y,m as z};//# sourceMappingURL=chunk-OBMQME2P.js.map
2
- //# sourceMappingURL=chunk-OBMQME2P.js.map