aiecsjs 0.4.1 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +1 -1
  2. package/README_ZHTW.md +1 -1
  3. package/api.json +1 -1
  4. package/dist/chunk-7O3CM4D2.cjs +2 -0
  5. package/dist/chunk-7O3CM4D2.cjs.map +1 -0
  6. package/dist/chunk-BUFJWGRQ.js +2 -0
  7. package/dist/chunk-BUFJWGRQ.js.map +1 -0
  8. package/dist/chunk-I2SPFVXH.cjs +2 -0
  9. package/dist/chunk-I2SPFVXH.cjs.map +1 -0
  10. package/dist/{chunk-2CF2MNMH.cjs → chunk-I726BP65.cjs} +2 -2
  11. package/dist/{chunk-2CF2MNMH.cjs.map → chunk-I726BP65.cjs.map} +1 -1
  12. package/dist/chunk-LU55S4LK.js +2 -0
  13. package/dist/{chunk-ZNLOJVCV.js.map → chunk-LU55S4LK.js.map} +1 -1
  14. package/dist/chunk-QC25WDOZ.js +2 -0
  15. package/dist/chunk-QC25WDOZ.js.map +1 -0
  16. package/dist/commands.cjs +1 -1
  17. package/dist/commands.js +1 -1
  18. package/dist/index.cjs +1 -1
  19. package/dist/index.d.cts +1 -1
  20. package/dist/index.d.ts +1 -1
  21. package/dist/index.js +1 -1
  22. package/dist/observers.cjs +1 -1
  23. package/dist/observers.js +1 -1
  24. package/dist/observers.js.map +1 -1
  25. package/dist/relations.cjs +1 -1
  26. package/dist/relations.js +1 -1
  27. package/dist/serialize.cjs +1 -1
  28. package/dist/serialize.js +1 -1
  29. package/dist/worker.cjs +1 -1
  30. package/dist/worker.js +1 -1
  31. package/llms-full.txt +36 -17
  32. package/package.json +1 -1
  33. package/dist/chunk-7NNM4PGP.cjs +0 -2
  34. package/dist/chunk-7NNM4PGP.cjs.map +0 -1
  35. package/dist/chunk-AW254W5F.js +0 -2
  36. package/dist/chunk-AW254W5F.js.map +0 -1
  37. package/dist/chunk-XU3BVVCJ.cjs +0 -2
  38. package/dist/chunk-XU3BVVCJ.cjs.map +0 -1
  39. package/dist/chunk-YAHZHZNR.js +0 -2
  40. package/dist/chunk-YAHZHZNR.js.map +0 -1
  41. package/dist/chunk-ZNLOJVCV.js +0 -2
@@ -1,2 +1,2 @@
1
- 'use strict';var chunk7NNM4PGP_cjs=require('./chunk-7NNM4PGP.cjs');var C=1,f=new Map;function _(n){let e=(n.all??[]).map(r=>r.__id).sort((r,o)=>r-o).join("-"),t=(n.any??[]).map(r=>r.__id).sort((r,o)=>r-o).join("-"),i=(n.none??[]).map(r=>r.__id).sort((r,o)=>r-o).join("-");return `A${e}|Y${t}|N${i}`}function q(n){let e=Array.isArray(n)?{all:n}:n;for(let o of [...e.all??[],...e.any??[],...e.none??[]])if(!o||typeof o!="object"||typeof o.__id!="number")throw new TypeError("aiecsjs: defineQuery received a non-component value");let t=_(e),i=f.get(t);if(i)return i;let r={id:C++,mask:[],all:(e.all??[]).map(o=>o.__id),any:(e.any??[]).map(o=>o.__id),none:(e.none??[]).map(o=>o.__id),columnViewCache:[...e.all??[],...e.any??[]],reactiveKind:"normal",sourceQueryId:-1,sourceQuery:null};return f.set(t,r),r}function z(n){let e=n,t=`enter:${e.id}`,i=f.get(t);if(i)return i;let r={id:C++,mask:[],all:e.all,any:e.any,none:e.none,columnViewCache:e.columnViewCache,reactiveKind:"enter",sourceQueryId:e.id,sourceQuery:e};return f.set(t,r),r}function T(n){let e=n,t=`exit:${e.id}`,i=f.get(t);if(i)return i;let r={id:C++,mask:[],all:e.all,any:e.any,none:e.none,columnViewCache:e.columnViewCache,reactiveKind:"exit",sourceQueryId:e.id,sourceQuery:e};return f.set(t,r),r}function p(n,e){if(n.queries[e.id]===e&&n.queryMasks.has(e.id))return;let t=n.options.maskWordCount,i=chunk7NNM4PGP_cjs.b(t),r=chunk7NNM4PGP_cjs.b(t),o=chunk7NNM4PGP_cjs.b(t);for(let a of e.all){let u=b(a),d=chunk7NNM4PGP_cjs.p(n,u);chunk7NNM4PGP_cjs.c(i,d);}for(let a of e.any){let u=b(a),d=chunk7NNM4PGP_cjs.p(n,u);chunk7NNM4PGP_cjs.c(r,d);}for(let a of e.none){let u=b(a),d=chunk7NNM4PGP_cjs.p(n,u);chunk7NNM4PGP_cjs.c(o,d);}let c={withMask:i,anyMask:r,noneMask:o,anyHasBits:!chunk7NNM4PGP_cjs.d(r)};n.queryMasks.set(e.id,c),n.queries[e.id]=e,n.queryArchetypeCache[e.id]=null,n.queryArchetypeStamp[e.id]=-1;let s=[...chunk7NNM4PGP_cjs.f(i),...chunk7NNM4PGP_cjs.f(r),...chunk7NNM4PGP_cjs.f(o)];for(let a of s){let u=n.bitToQueries.get(a);u||(u=new Set,n.bitToQueries.set(a,u)),u.add(e.id);}e.reactiveKind!=="normal"&&(n.reactiveBuffers.has(e.id)||n.reactiveBuffers.set(e.id,{entered:[],exited:[]}),e.sourceQuery&&p(n,e.sourceQuery));}function v(n,e){if(p(n,e),n.queryArchetypeCache[e.id]&&n.queryArchetypeStamp[e.id]===n.queryVersion)return n.queryArchetypeCache[e.id];let t=n.queryMasks.get(e.id),i=n.options.maskWordCount,r=[];for(let o=0;o<n.archetypes.length;o++){let c=n.archetypes[o];chunk7NNM4PGP_cjs.e(c.mask,t.withMask,t.anyMask,t.noneMask,t.anyHasBits,i)&&r.push(o);}return n.queryArchetypeCache[e.id]=r,n.queryArchetypeStamp[e.id]=n.queryVersion,r}function $(n,e){let t=chunk7NNM4PGP_cjs.i(n),r=v(t,e),o=[];for(let c of r){let s=t.archetypes[c];o.push({id:s.id,mask:Array.from(s.mask),size:s.size});}return o}function D(n,e){let t=chunk7NNM4PGP_cjs.i(n),i=e,r=[];if(i.reactiveKind==="enter"){let c=t.reactiveBuffers.get(i.id);if(c){for(let s of c.entered)r.push(s);c.entered.length=0;}return r}if(i.reactiveKind==="exit"){let c=t.reactiveBuffers.get(i.id);if(c){for(let s of c.exited)r.push(s);c.exited.length=0;}return r}let o=v(t,i);for(let c of o){let s=t.archetypes[c];for(let a=0;a<s.size;a++)r.push(s.entities[a]);}return r}function*H(n,e){let t=chunk7NNM4PGP_cjs.i(n),i=e;if(i.reactiveKind!=="normal"){let o=t.reactiveBuffers.get(i.id);if(!o)return;let c=i.reactiveKind==="enter"?o.entered:o.exited;for(let s of c)yield s;c.length=0;return}let r=v(t,i);for(let o of r){let c=t.archetypes[o];for(let s=0;s<c.size;s++)yield c.entities[s];}}function L(n,e,t){let i=chunk7NNM4PGP_cjs.i(n),r=e;if(r.reactiveKind!=="normal"){let s=i.reactiveBuffers.get(r.id);if(!s)return;let a=r.reactiveKind==="enter"?s.entered:s.exited;if(a.length===0)return;let u=w(i,r);for(let d=0;d<a.length;d++){let y=a[d];x(t,y,u);}a.length=0;return}p(i,r);let o=v(i,r),c=w(i,r);for(let s of o){let a=i.archetypes[s],u=a.entities,d=a.size;for(let y=0;y<d;y++)x(t,u[y],c);}}function x(n,e,t){switch(t.length){case 0:n(e);break;case 1:n(e,t[0]);break;case 2:n(e,t[0],t[1]);break;case 3:n(e,t[0],t[1],t[2]);break;case 4:n(e,t[0],t[1],t[2],t[3]);break;case 5:n(e,t[0],t[1],t[2],t[3],t[4]);break;default:n(e,...t);}}function w(n,e){let t=[];for(let i of e.columnViewCache){let r=chunk7NNM4PGP_cjs.H(i),o=n.componentBitFor.get(r.id);if(o===void 0){t.push(void 0);continue}let c=n.componentStorageByBit[o];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 F(n,e,t,i,r){for(let s of f.values())s.reactiveKind!=="normal"&&s.sourceQuery&&n.queries[s.sourceQuery.id]!==s.sourceQuery&&p(n,s.sourceQuery);let o=n.bitToQueries.get(t);if(!o)return;let c=n.options.maskWordCount;for(let s of o){let a=n.queries[s];if(!a||a.reactiveKind!=="normal")continue;let u=n.queryMasks.get(s);if(!u)continue;let d=chunk7NNM4PGP_cjs.e(i,u.withMask,u.anyMask,u.noneMask,u.anyHasBits,c),y=chunk7NNM4PGP_cjs.e(r,u.withMask,u.anyMask,u.noneMask,u.anyHasBits,c);!d&&y?E(n,s,"enter",e):d&&!y&&E(n,s,"exit",e);}}function E(n,e,t,i){for(let r of f.values()){if(r.sourceQueryId!==e||r.reactiveKind!==t)continue;p(n,r);let o=A(n,r.id);t==="enter"?o.entered.push(i):o.exited.push(i);}}function A(n,e){let t=n.reactiveBuffers.get(e);return t||(t={entered:[],exited:[]},n.reactiveBuffers.set(e,t)),t}function b(n){let e=W(n);if(!e)throw new Error(`aiecsjs: component id ${n} not registered`);return e}var g=null;function O(n){g=n;}function W(n){return g?g(n):void 0}exports.a=q;exports.b=z;exports.c=T;exports.d=$;exports.e=D;exports.f=H;exports.g=L;exports.h=F;exports.i=O;//# sourceMappingURL=chunk-2CF2MNMH.cjs.map
2
- //# sourceMappingURL=chunk-2CF2MNMH.cjs.map
1
+ 'use strict';var chunk7O3CM4D2_cjs=require('./chunk-7O3CM4D2.cjs');var C=1,f=new Map;function _(n){let e=(n.all??[]).map(r=>r.__id).sort((r,o)=>r-o).join("-"),t=(n.any??[]).map(r=>r.__id).sort((r,o)=>r-o).join("-"),i=(n.none??[]).map(r=>r.__id).sort((r,o)=>r-o).join("-");return `A${e}|Y${t}|N${i}`}function q(n){let e=Array.isArray(n)?{all:n}:n;for(let o of [...e.all??[],...e.any??[],...e.none??[]])if(!o||typeof o!="object"||typeof o.__id!="number")throw new TypeError("aiecsjs: defineQuery received a non-component value");let t=_(e),i=f.get(t);if(i)return i;let r={id:C++,mask:[],all:(e.all??[]).map(o=>o.__id),any:(e.any??[]).map(o=>o.__id),none:(e.none??[]).map(o=>o.__id),columnViewCache:[...e.all??[],...e.any??[]],reactiveKind:"normal",sourceQueryId:-1,sourceQuery:null};return f.set(t,r),r}function z(n){let e=n,t=`enter:${e.id}`,i=f.get(t);if(i)return i;let r={id:C++,mask:[],all:e.all,any:e.any,none:e.none,columnViewCache:e.columnViewCache,reactiveKind:"enter",sourceQueryId:e.id,sourceQuery:e};return f.set(t,r),r}function T(n){let e=n,t=`exit:${e.id}`,i=f.get(t);if(i)return i;let r={id:C++,mask:[],all:e.all,any:e.any,none:e.none,columnViewCache:e.columnViewCache,reactiveKind:"exit",sourceQueryId:e.id,sourceQuery:e};return f.set(t,r),r}function p(n,e){if(n.queries[e.id]===e&&n.queryMasks.has(e.id))return;let t=n.options.maskWordCount,i=chunk7O3CM4D2_cjs.b(t),r=chunk7O3CM4D2_cjs.b(t),o=chunk7O3CM4D2_cjs.b(t);for(let a of e.all){let u=b(a),d=chunk7O3CM4D2_cjs.p(n,u);chunk7O3CM4D2_cjs.c(i,d);}for(let a of e.any){let u=b(a),d=chunk7O3CM4D2_cjs.p(n,u);chunk7O3CM4D2_cjs.c(r,d);}for(let a of e.none){let u=b(a),d=chunk7O3CM4D2_cjs.p(n,u);chunk7O3CM4D2_cjs.c(o,d);}let c={withMask:i,anyMask:r,noneMask:o,anyHasBits:!chunk7O3CM4D2_cjs.d(r)};n.queryMasks.set(e.id,c),n.queries[e.id]=e,n.queryArchetypeCache[e.id]=null,n.queryArchetypeStamp[e.id]=-1;let s=[...chunk7O3CM4D2_cjs.f(i),...chunk7O3CM4D2_cjs.f(r),...chunk7O3CM4D2_cjs.f(o)];for(let a of s){let u=n.bitToQueries.get(a);u||(u=new Set,n.bitToQueries.set(a,u)),u.add(e.id);}e.reactiveKind!=="normal"&&(n.reactiveBuffers.has(e.id)||n.reactiveBuffers.set(e.id,{entered:[],exited:[]}),e.sourceQuery&&p(n,e.sourceQuery));}function v(n,e){if(p(n,e),n.queryArchetypeCache[e.id]&&n.queryArchetypeStamp[e.id]===n.queryVersion)return n.queryArchetypeCache[e.id];let t=n.queryMasks.get(e.id),i=n.options.maskWordCount,r=[];for(let o=0;o<n.archetypes.length;o++){let c=n.archetypes[o];chunk7O3CM4D2_cjs.e(c.mask,t.withMask,t.anyMask,t.noneMask,t.anyHasBits,i)&&r.push(o);}return n.queryArchetypeCache[e.id]=r,n.queryArchetypeStamp[e.id]=n.queryVersion,r}function $(n,e){let t=chunk7O3CM4D2_cjs.i(n),r=v(t,e),o=[];for(let c of r){let s=t.archetypes[c];o.push({id:s.id,mask:Array.from(s.mask),size:s.size});}return o}function D(n,e){let t=chunk7O3CM4D2_cjs.i(n),i=e,r=[];if(i.reactiveKind==="enter"){let c=t.reactiveBuffers.get(i.id);if(c){for(let s of c.entered)r.push(s);c.entered.length=0;}return r}if(i.reactiveKind==="exit"){let c=t.reactiveBuffers.get(i.id);if(c){for(let s of c.exited)r.push(s);c.exited.length=0;}return r}let o=v(t,i);for(let c of o){let s=t.archetypes[c];for(let a=0;a<s.size;a++)r.push(s.entities[a]);}return r}function*H(n,e){let t=chunk7O3CM4D2_cjs.i(n),i=e;if(i.reactiveKind!=="normal"){let o=t.reactiveBuffers.get(i.id);if(!o)return;let c=i.reactiveKind==="enter"?o.entered:o.exited;for(let s of c)yield s;c.length=0;return}let r=v(t,i);for(let o of r){let c=t.archetypes[o];for(let s=0;s<c.size;s++)yield c.entities[s];}}function L(n,e,t){let i=chunk7O3CM4D2_cjs.i(n),r=e;if(r.reactiveKind!=="normal"){let s=i.reactiveBuffers.get(r.id);if(!s)return;let a=r.reactiveKind==="enter"?s.entered:s.exited;if(a.length===0)return;let u=w(i,r);for(let d=0;d<a.length;d++){let y=a[d];x(t,y,u);}a.length=0;return}p(i,r);let o=v(i,r),c=w(i,r);for(let s of o){let a=i.archetypes[s],u=a.entities,d=a.size;for(let y=0;y<d;y++)x(t,u[y],c);}}function x(n,e,t){switch(t.length){case 0:n(e);break;case 1:n(e,t[0]);break;case 2:n(e,t[0],t[1]);break;case 3:n(e,t[0],t[1],t[2]);break;case 4:n(e,t[0],t[1],t[2],t[3]);break;case 5:n(e,t[0],t[1],t[2],t[3],t[4]);break;default:n(e,...t);}}function w(n,e){let t=[];for(let i of e.columnViewCache){let r=chunk7O3CM4D2_cjs.I(i),o=n.componentBitFor.get(r.id);if(o===void 0){t.push(void 0);continue}let c=n.componentStorageByBit[o];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 F(n,e,t,i,r){for(let s of f.values())s.reactiveKind!=="normal"&&s.sourceQuery&&n.queries[s.sourceQuery.id]!==s.sourceQuery&&p(n,s.sourceQuery);let o=n.bitToQueries.get(t);if(!o)return;let c=n.options.maskWordCount;for(let s of o){let a=n.queries[s];if(!a||a.reactiveKind!=="normal")continue;let u=n.queryMasks.get(s);if(!u)continue;let d=chunk7O3CM4D2_cjs.e(i,u.withMask,u.anyMask,u.noneMask,u.anyHasBits,c),y=chunk7O3CM4D2_cjs.e(r,u.withMask,u.anyMask,u.noneMask,u.anyHasBits,c);!d&&y?E(n,s,"enter",e):d&&!y&&E(n,s,"exit",e);}}function E(n,e,t,i){for(let r of f.values()){if(r.sourceQueryId!==e||r.reactiveKind!==t)continue;p(n,r);let o=A(n,r.id);t==="enter"?o.entered.push(i):o.exited.push(i);}}function A(n,e){let t=n.reactiveBuffers.get(e);return t||(t={entered:[],exited:[]},n.reactiveBuffers.set(e,t)),t}function b(n){let e=W(n);if(!e)throw new Error(`aiecsjs: component id ${n} not registered`);return e}var g=null;function O(n){g=n;}function W(n){return g?g(n):void 0}exports.a=q;exports.b=z;exports.c=T;exports.d=$;exports.e=D;exports.f=H;exports.g=L;exports.h=F;exports.i=O;//# sourceMappingURL=chunk-I726BP65.cjs.map
2
+ //# sourceMappingURL=chunk-I726BP65.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/internal/query.ts"],"names":["nextQueryId","moduleQueryCache","descKey","d","all","c","a","b","any","none","defineQuery","arg","desc","key","cached","q","enterQuery","query","reactive","exitQuery","ensureQueryRegistered","state","ww","withMask","createMask","anyMask","noneMask","compId","info","getComponentInfoById","bit","getOrRegisterComponentBit","setBit","bundle","isMaskZero","involvedBits","listBits","s","getQueryArchetypes","words","list","i","arch","matches","queryArchetypes","world","getWorldState","ids","out","id","runQuery","buf","e","archIds","r","iterQuery","src","forEachEntity","fn","cols","buildColumnViews","callWithCols","ents","n","eid","comp","getComponentInfo","storage","recordEntityMaskChange","changedBit","prevMask","nextMask","involved","qid","wasMatch","isMatch","pushReactive","queryId","kind","ensureReactiveBuffer","componentId","lazyGetComponentInfo","_getComponentInfoFn","registerComponentLookup"],"mappings":"mEAsBA,IAAIA,EAAc,CAAA,CACZC,CAAAA,CAAmB,IAAI,GAAA,CAE7B,SAASC,CAAAA,CAAQC,CAAAA,CAA4B,CAC3C,IAAMC,GAAOD,CAAAA,CAAE,GAAA,EAAO,EAAC,EACpB,GAAA,CAAKE,GAAMA,CAAAA,CAAE,IAAI,CAAA,CACjB,IAAA,CAAK,CAACC,CAAAA,CAAGC,CAAAA,GAAMD,EAAIC,CAAC,CAAA,CACpB,KAAK,GAAG,CAAA,CACLC,CAAAA,CAAAA,CAAOL,CAAAA,CAAE,KAAO,EAAC,EACpB,IAAKE,CAAAA,EAAMA,CAAAA,CAAE,IAAI,CAAA,CACjB,IAAA,CAAK,CAACC,CAAAA,CAAGC,IAAMD,CAAAA,CAAIC,CAAC,EACpB,IAAA,CAAK,GAAG,EACLE,CAAAA,CAAAA,CAAQN,CAAAA,CAAE,IAAA,EAAQ,IACrB,GAAA,CAAKE,CAAAA,EAAMA,EAAE,IAAI,CAAA,CACjB,KAAK,CAACC,CAAAA,CAAGC,CAAAA,GAAMD,CAAAA,CAAIC,CAAC,CAAA,CACpB,IAAA,CAAK,GAAG,CAAA,CACX,OAAO,IAAIH,CAAG,CAAA,EAAA,EAAKI,CAAG,CAAA,EAAA,EAAKC,CAAI,CAAA,CACjC,CAEO,SAASC,CAAAA,CAAYC,CAAAA,CAA+C,CACzE,IAAMC,CAAAA,CAAwB,KAAA,CAAM,OAAA,CAAQD,CAAG,CAAA,CAAI,CAAE,IAAKA,CAAI,CAAA,CAAIA,EAGlE,IAAA,IAAWN,CAAAA,IAAK,CAAC,GAAIO,EAAK,GAAA,EAAO,GAAK,GAAIA,CAAAA,CAAK,KAAO,E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A,CAAgB,GAAA,CAAIoD,CAAG,CAAA,CACvC,OAAKtB,IACHA,CAAAA,CAAM,CAAE,QAAS,EAAC,CAAG,MAAA,CAAQ,EAAG,CAAA,CAChC9B,CAAAA,CAAM,gBAAgB,GAAA,CAAIoD,CAAAA,CAAKtB,CAAG,CAAA,CAAA,CAE7BA,CACT,CAIA,SAAStB,EAAqBmD,CAAAA,CAAoC,CAEhE,IAAMpD,CAAAA,CAAOqD,CAAAA,CAAqBD,CAAW,CAAA,CAC7C,GAAI,CAACpD,CAAAA,CAAM,MAAM,IAAI,KAAA,CAAM,yBAAyBoD,CAAW,CAAA,eAAA,CAAiB,EAChF,OAAOpD,CACT,CAEA,IAAIsD,EAA0E,IAAA,CACvE,SAASC,EAAwBzB,CAAAA,CAAqD,CAC3FwB,EAAsBxB,EACxB,CACA,SAASuB,CAAAA,CAAqBhC,EAAuC,CACnE,OAAOiC,EAAsBA,CAAAA,CAAoBjC,CAAE,EAAI,MACzD","file":"chunk-2CF2MNMH.cjs","sourcesContent":["import { createMask, isMaskZero, listBits, matches, setBit } from './bitmask.js'\nimport { getComponentInfo } from './component.js'\nimport type {\n Archetype,\n ComponentInfo,\n ComponentLike,\n EntityId,\n Query,\n QueryDescriptor,\n QueryInternal,\n QueryMaskBundle,\n ReactiveBuffer,\n World,\n WorldState,\n} from './types.js'\nimport {\n getOrRegisterComponentBit,\n getWorldState,\n readEntityMask,\n tryGetComponentBit,\n} from './world.js'\n\nlet nextQueryId = 1\nconst moduleQueryCache = new Map<string, QueryInternal>()\n\nfunction descKey(d: QueryDescriptor): string {\n const all = (d.all ?? [])\n .map((c) => c.__id)\n .sort((a, b) => a - b)\n .join('-')\n const any = (d.any ?? [])\n .map((c) => c.__id)\n .sort((a, b) => a - b)\n .join('-')\n const none = (d.none ?? [])\n .map((c) => c.__id)\n .sort((a, b) => a - b)\n .join('-')\n return `A${all}|Y${any}|N${none}`\n}\n\nexport function defineQuery(arg: ComponentLike[] | QueryDescriptor): Query {\n const desc: QueryDescriptor = Array.isArray(arg) ? { all: arg } : arg\n\n // Validate all members are components\n for (const c of [...(desc.all ?? []), ...(desc.any ?? []), ...(desc.none ?? [])]) {\n if (!c || typeof c !== 'object' || typeof (c as any).__id !== 'number') {\n throw new TypeError('aiecsjs: defineQuery received a non-component value')\n }\n }\n\n const key = descKey(desc)\n const cached = moduleQueryCache.get(key)\n if (cached) return cached\n\n const q: QueryInternal = {\n id: nextQueryId++,\n mask: [],\n all: (desc.all ?? []).map((c) => c.__id),\n any: (desc.any ?? []).map((c) => c.__id),\n none: (desc.none ?? []).map((c) => c.__id),\n columnViewCache: [...(desc.all ?? []), ...(desc.any ?? [])],\n reactiveKind: 'normal',\n sourceQueryId: -1,\n sourceQuery: null,\n }\n moduleQueryCache.set(key, q)\n return q\n}\n\nexport function enterQuery(query: Query): Query {\n const q = query as QueryInternal\n const key = `enter:${q.id}`\n const cached = moduleQueryCache.get(key)\n if (cached) return cached\n const reactive: QueryInternal = {\n id: nextQueryId++,\n mask: [],\n all: q.all,\n any: q.any,\n none: q.none,\n columnViewCache: q.columnViewCache,\n reactiveKind: 'enter',\n sourceQueryId: q.id,\n sourceQuery: q,\n }\n moduleQueryCache.set(key, reactive)\n return reactive\n}\n\nexport function exitQuery(query: Query): Query {\n const q = query as QueryInternal\n const key = `exit:${q.id}`\n const cached = moduleQueryCache.get(key)\n if (cached) return cached\n const reactive: QueryInternal = {\n id: nextQueryId++,\n mask: [],\n all: q.all,\n any: q.any,\n none: q.none,\n columnViewCache: q.columnViewCache,\n reactiveKind: 'exit',\n sourceQueryId: q.id,\n sourceQuery: q,\n }\n moduleQueryCache.set(key, reactive)\n return reactive\n}\n\n// --- Per-world query setup ---\n\nfunction ensureQueryRegistered(state: WorldState, q: QueryInternal): void {\n if (state.queries[q.id] === q && state.queryMasks.has(q.id)) return\n\n // Build per-world bitmasks (this may register new bits)\n const ww = state.options.maskWordCount\n const withMask = createMask(ww)\n const anyMask = createMask(ww)\n const noneMask = createMask(ww)\n for (const compId of q.all) {\n const info = getComponentInfoById(compId)\n const bit = getOrRegisterComponentBit(state, info)\n setBit(withMask, bit)\n }\n for (const compId of q.any) {\n const info = getComponentInfoById(compId)\n const bit = getOrRegisterComponentBit(state, info)\n setBit(anyMask, bit)\n }\n for (const compId of q.none) {\n const info = getComponentInfoById(compId)\n const bit = getOrRegisterComponentBit(state, info)\n setBit(noneMask, bit)\n }\n\n const bundle: QueryMaskBundle = {\n withMask,\n anyMask,\n noneMask,\n anyHasBits: !isMaskZero(anyMask),\n }\n state.queryMasks.set(q.id, bundle)\n\n state.queries[q.id] = q\n state.queryArchetypeCache[q.id] = null\n state.queryArchetypeStamp[q.id] = -1\n\n // Build bit → queries index for fast reactive lookup\n const involvedBits: number[] = [\n ...listBits(withMask),\n ...listBits(anyMask),\n ...listBits(noneMask),\n ]\n for (const b of involvedBits) {\n let s = state.bitToQueries.get(b)\n if (!s) {\n s = new Set<number>()\n state.bitToQueries.set(b, s)\n }\n s.add(q.id)\n }\n\n // Initialize reactive buffer for enter/exit queries\n if (q.reactiveKind !== 'normal') {\n if (!state.reactiveBuffers.has(q.id)) {\n state.reactiveBuffers.set(q.id, { entered: [], exited: [] })\n }\n // Also register the source query so recordEntityMaskChange will see it\n if (q.sourceQuery) ensureQueryRegistered(state, q.sourceQuery)\n }\n}\n\nfunction getQueryArchetypes(state: WorldState, q: QueryInternal): number[] {\n ensureQueryRegistered(state, q)\n if (state.queryArchetypeCache[q.id] && state.queryArchetypeStamp[q.id] === state.queryVersion) {\n return state.queryArchetypeCache[q.id]!\n }\n const bundle = state.queryMasks.get(q.id)!\n const words = state.options.maskWordCount\n const list: number[] = []\n for (let i = 0; i < state.archetypes.length; i++) {\n const arch = state.archetypes[i]!\n if (\n matches(arch.mask, bundle.withMask, bundle.anyMask, bundle.noneMask, bundle.anyHasBits, words)\n ) {\n list.push(i)\n }\n }\n state.queryArchetypeCache[q.id] = list\n state.queryArchetypeStamp[q.id] = state.queryVersion\n return list\n}\n\nexport function queryArchetypes(world: World, query: Query): readonly Archetype[] {\n const state = getWorldState(world)\n const q = query as QueryInternal\n const ids = getQueryArchetypes(state, q)\n const out: Archetype[] = []\n for (const id of ids) {\n const arch = state.archetypes[id]!\n out.push({ id: arch.id, mask: Array.from(arch.mask), size: arch.size })\n }\n return out\n}\n\nexport function runQuery(world: World, query: Query): readonly EntityId[] {\n const state = getWorldState(world)\n const q = query as QueryInternal\n const out: EntityId[] = []\n if (q.reactiveKind === 'enter') {\n const buf = state.reactiveBuffers.get(q.id)\n if (buf) {\n for (const e of buf.entered) out.push(e as EntityId)\n buf.entered.length = 0\n }\n return out\n }\n if (q.reactiveKind === 'exit') {\n const buf = state.reactiveBuffers.get(q.id)\n if (buf) {\n for (const e of buf.exited) out.push(e as EntityId)\n buf.exited.length = 0\n }\n return out\n }\n const archIds = getQueryArchetypes(state, q)\n for (const id of archIds) {\n const arch = state.archetypes[id]!\n for (let r = 0; r < arch.size; r++) {\n out.push(arch.entities[r] as EntityId)\n }\n }\n return out\n}\n\nexport function* iterQuery(world: World, query: Query): IterableIterator<EntityId> {\n const state = getWorldState(world)\n const q = query as QueryInternal\n if (q.reactiveKind !== 'normal') {\n const buf = state.reactiveBuffers.get(q.id)\n if (!buf) return\n const src = q.reactiveKind === 'enter' ? buf.entered : buf.exited\n for (const e of src) yield e as EntityId\n src.length = 0\n return\n }\n const archIds = getQueryArchetypes(state, q)\n for (const id of archIds) {\n const arch = state.archetypes[id]!\n for (let r = 0; r < arch.size; r++) {\n yield arch.entities[r] as EntityId\n }\n }\n}\n\nexport function forEachEntity(\n world: World,\n query: Query,\n fn: (eid: EntityId, ...cols: any[]) => void,\n): void {\n const state = getWorldState(world)\n const q = query as QueryInternal\n\n if (q.reactiveKind !== 'normal') {\n const buf = state.reactiveBuffers.get(q.id)\n if (!buf) return\n const src = q.reactiveKind === 'enter' ? buf.entered : buf.exited\n if (src.length === 0) return\n const cols = buildColumnViews(state, q)\n for (let i = 0; i < src.length; i++) {\n const e = src[i] as EntityId\n callWithCols(fn, e, cols)\n }\n src.length = 0\n return\n }\n\n ensureQueryRegistered(state, q)\n const archIds = getQueryArchetypes(state, q)\n const cols = buildColumnViews(state, q)\n for (const id of archIds) {\n const arch = state.archetypes[id]!\n const ents = arch.entities\n const n = arch.size\n for (let r = 0; r < n; r++) {\n callWithCols(fn, ents[r] as EntityId, cols)\n }\n }\n}\n\nfunction callWithCols(\n fn: (eid: EntityId, ...cols: any[]) => void,\n eid: EntityId,\n cols: any[],\n): void {\n // Specialise for low arities to avoid spread allocation.\n switch (cols.length) {\n case 0:\n fn(eid)\n break\n case 1:\n fn(eid, cols[0])\n break\n case 2:\n fn(eid, cols[0], cols[1])\n break\n case 3:\n fn(eid, cols[0], cols[1], cols[2])\n break\n case 4:\n fn(eid, cols[0], cols[1], cols[2], cols[3])\n break\n case 5:\n fn(eid, cols[0], cols[1], cols[2], cols[3], cols[4])\n break\n default:\n fn(eid, ...cols)\n }\n}\n\nfunction buildColumnViews(state: WorldState, q: QueryInternal): any[] {\n const out: any[] = []\n for (const comp of q.columnViewCache) {\n const info = getComponentInfo(comp)\n const bit = state.componentBitFor.get(info.id)\n if (bit === undefined) {\n out.push(undefined)\n continue\n }\n const storage = state.componentStorageByBit[bit]\n if (!storage) {\n out.push(undefined)\n continue\n }\n if (storage.kind === 'soa') out.push(storage.soa)\n else if (storage.kind === 'aos') out.push(storage.aos)\n else out.push(true) // tag\n }\n return out\n}\n\n// --- Reactive query updates (called from migration code) ---\n\nexport function recordEntityMaskChange(\n state: WorldState,\n eid: EntityId,\n changedBit: number,\n prevMask: Uint32Array,\n nextMask: Uint32Array,\n): void {\n // Lazy-register any reactive queries (and their sources) so we can correctly\n // determine match transitions even if the user only ever called enterQuery/exitQuery.\n for (const q of moduleQueryCache.values()) {\n if (q.reactiveKind === 'normal') continue\n if (q.sourceQuery && state.queries[q.sourceQuery.id] !== q.sourceQuery) {\n ensureQueryRegistered(state, q.sourceQuery)\n }\n }\n\n const involved = state.bitToQueries.get(changedBit)\n if (!involved) return\n const words = state.options.maskWordCount\n for (const qid of involved) {\n const q = state.queries[qid]\n if (!q) continue\n if (q.reactiveKind !== 'normal') continue\n const bundle = state.queryMasks.get(qid)\n if (!bundle) continue\n const wasMatch = matches(\n prevMask,\n bundle.withMask,\n bundle.anyMask,\n bundle.noneMask,\n bundle.anyHasBits,\n words,\n )\n const isMatch = matches(\n nextMask,\n bundle.withMask,\n bundle.anyMask,\n bundle.noneMask,\n bundle.anyHasBits,\n words,\n )\n if (!wasMatch && isMatch) {\n pushReactive(state, qid, 'enter', eid)\n } else if (wasMatch && !isMatch) {\n pushReactive(state, qid, 'exit', eid)\n }\n }\n}\n\nfunction pushReactive(\n state: WorldState,\n queryId: number,\n kind: 'enter' | 'exit',\n eid: EntityId,\n): void {\n // Walk the module cache (not just state.queries) so reactive variants that\n // haven't been registered with this world yet still receive events.\n for (const r of moduleQueryCache.values()) {\n if (r.sourceQueryId !== queryId) continue\n if (r.reactiveKind !== kind) continue\n // Lazily register the reactive query in this world so subsequent reads can find it\n ensureQueryRegistered(state, r)\n const buf = ensureReactiveBuffer(state, r.id)\n if (kind === 'enter') buf.entered.push(eid as number)\n else buf.exited.push(eid as number)\n }\n}\n\nfunction ensureReactiveBuffer(state: WorldState, qid: number): ReactiveBuffer {\n let buf = state.reactiveBuffers.get(qid)\n if (!buf) {\n buf = { entered: [], exited: [] }\n state.reactiveBuffers.set(qid, buf)\n }\n return buf\n}\n\n// --- Helpers ---\n\nfunction getComponentInfoById(componentId: number): ComponentInfo {\n // We need access to the component registry's lookup by id. Re-import dynamically to avoid cycles.\n const info = lazyGetComponentInfo(componentId)\n if (!info) throw new Error(`aiecsjs: component id ${componentId} not registered`)\n return info\n}\n\nlet _getComponentInfoFn: ((id: number) => ComponentInfo | undefined) | null = null\nexport function registerComponentLookup(fn: (id: number) => ComponentInfo | undefined): void {\n _getComponentInfoFn = fn\n}\nfunction lazyGetComponentInfo(id: number): ComponentInfo | undefined {\n return _getComponentInfoFn ? _getComponentInfoFn(id) : undefined\n}\n\nexport function _resetQueryRegistry_FOR_TESTS_ONLY(): void {\n moduleQueryCache.clear()\n nextQueryId = 1\n}\n"]}
1
+ {"version":3,"sources":["../src/internal/query.ts"],"names":["nextQueryId","moduleQueryCache","descKey","d","all","c","a","b","any","none","defineQuery","arg","desc","key","cached","q","enterQuery","query","reactive","exitQuery","ensureQueryRegistered","state","ww","withMask","createMask","anyMask","noneMask","compId","info","getComponentInfoById","bit","getOrRegisterComponentBit","setBit","bundle","isMaskZero","involvedBits","listBits","s","getQueryArchetypes","words","list","i","arch","matches","queryArchetypes","world","getWorldState","ids","out","id","runQuery","buf","e","archIds","r","iterQuery","src","forEachEntity","fn","cols","buildColumnViews","callWithCols","ents","n","eid","comp","getComponentInfo","storage","recordEntityMaskChange","changedBit","prevMask","nextMask","involved","qid","wasMatch","isMatch","pushReactive","queryId","kind","ensureReactiveBuffer","componentId","lazyGetComponentInfo","_getComponentInfoFn","registerComponentLookup"],"mappings":"mEAsBA,IAAIA,EAAc,CAAA,CACZC,CAAAA,CAAmB,IAAI,GAAA,CAE7B,SAASC,CAAAA,CAAQC,CAAAA,CAA4B,CAC3C,IAAMC,GAAOD,CAAAA,CAAE,GAAA,EAAO,EAAC,EACpB,GAAA,CAAKE,GAAMA,CAAAA,CAAE,IAAI,CAAA,CACjB,IAAA,CAAK,CAACC,CAAAA,CAAGC,CAAAA,GAAMD,EAAIC,CAAC,CAAA,CACpB,KAAK,GAAG,CAAA,CACLC,CAAAA,CAAAA,CAAOL,CAAAA,CAAE,KAAO,EAAC,EACpB,IAAKE,CAAAA,EAAMA,CAAAA,CAAE,IAAI,CAAA,CACjB,IAAA,CAAK,CAACC,CAAAA,CAAGC,IAAMD,CAAAA,CAAIC,CAAC,EACpB,IAAA,CAAK,GAAG,EACLE,CAAAA,CAAAA,CAAQN,CAAAA,CAAE,IAAA,EAAQ,IACrB,GAAA,CAAKE,CAAAA,EAAMA,EAAE,IAAI,CAAA,CACjB,K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CAAE,gBAAkB4E,CAAAA,EACpB,CAAA,CAAE,eAAiBC,CAAAA,CAAM,SAE7B1D,CAAAA,CAAsBC,CAAAA,CAAO,CAAC,CAAA,CAC9B,IAAM8B,EAAM4B,CAAAA,CAAqB1D,CAAAA,CAAO,EAAE,EAAE,CAAA,CACxCyD,CAAAA,GAAS,OAAA,CAAS3B,EAAI,OAAA,CAAQ,IAAA,CAAKa,CAAa,CAAA,CAC/Cb,CAAAA,CAAI,OAAO,IAAA,CAAKa,CAAa,EACpC,CACF,CAEA,SAASe,CAAAA,CAAqB1D,EAAmBoD,CAAAA,CAA6B,CAC5E,IAAItB,CAAAA,CAAM9B,CAAAA,CAAM,eAAA,CAAgB,GAAA,CAAIoD,CAAG,CAAA,CACvC,OAAKtB,IACHA,CAAAA,CAAM,CAAE,QAAS,EAAC,CAAG,MAAA,CAAQ,EAAG,CAAA,CAChC9B,CAAAA,CAAM,gBAAgB,GAAA,CAAIoD,CAAAA,CAAKtB,CAAG,CAAA,CAAA,CAE7BA,CACT,CAIA,SAAStB,EAAqBmD,CAAAA,CAAoC,CAEhE,IAAMpD,CAAAA,CAAOqD,CAAAA,CAAqBD,CAAW,CAAA,CAC7C,GAAI,CAACpD,CAAAA,CAAM,MAAM,IAAI,KAAA,CAAM,yBAAyBoD,CAAW,CAAA,eAAA,CAAiB,EAChF,OAAOpD,CACT,CAEA,IAAIsD,EAA0E,IAAA,CACvE,SAASC,EAAwBzB,CAAAA,CAAqD,CAC3FwB,EAAsBxB,EACxB,CACA,SAASuB,CAAAA,CAAqBhC,EAAuC,CACnE,OAAOiC,EAAsBA,CAAAA,CAAoBjC,CAAE,EAAI,MACzD","file":"chunk-I726BP65.cjs","sourcesContent":["import { createMask, isMaskZero, listBits, matches, setBit } from './bitmask.js'\nimport { getComponentInfo } from './component.js'\nimport type {\n Archetype,\n ComponentInfo,\n ComponentLike,\n EntityId,\n Query,\n QueryDescriptor,\n QueryInternal,\n QueryMaskBundle,\n ReactiveBuffer,\n World,\n WorldState,\n} from './types.js'\nimport {\n getOrRegisterComponentBit,\n getWorldState,\n readEntityMask,\n tryGetComponentBit,\n} from './world.js'\n\nlet nextQueryId = 1\nconst moduleQueryCache = new Map<string, QueryInternal>()\n\nfunction descKey(d: QueryDescriptor): string {\n const all = (d.all ?? [])\n .map((c) => c.__id)\n .sort((a, b) => a - b)\n .join('-')\n const any = (d.any ?? [])\n .map((c) => c.__id)\n .sort((a, b) => a - b)\n .join('-')\n const none = (d.none ?? [])\n .map((c) => c.__id)\n .sort((a, b) => a - b)\n .join('-')\n return `A${all}|Y${any}|N${none}`\n}\n\nexport function defineQuery(arg: ComponentLike[] | QueryDescriptor): Query {\n const desc: QueryDescriptor = Array.isArray(arg) ? { all: arg } : arg\n\n // Validate all members are components\n for (const c of [...(desc.all ?? []), ...(desc.any ?? []), ...(desc.none ?? [])]) {\n if (!c || typeof c !== 'object' || typeof (c as any).__id !== 'number') {\n throw new TypeError('aiecsjs: defineQuery received a non-component value')\n }\n }\n\n const key = descKey(desc)\n const cached = moduleQueryCache.get(key)\n if (cached) return cached\n\n const q: QueryInternal = {\n id: nextQueryId++,\n mask: [],\n all: (desc.all ?? []).map((c) => c.__id),\n any: (desc.any ?? []).map((c) => c.__id),\n none: (desc.none ?? []).map((c) => c.__id),\n columnViewCache: [...(desc.all ?? []), ...(desc.any ?? [])],\n reactiveKind: 'normal',\n sourceQueryId: -1,\n sourceQuery: null,\n }\n moduleQueryCache.set(key, q)\n return q\n}\n\nexport function enterQuery(query: Query): Query {\n const q = query as QueryInternal\n const key = `enter:${q.id}`\n const cached = moduleQueryCache.get(key)\n if (cached) return cached\n const reactive: QueryInternal = {\n id: nextQueryId++,\n mask: [],\n all: q.all,\n any: q.any,\n none: q.none,\n columnViewCache: q.columnViewCache,\n reactiveKind: 'enter',\n sourceQueryId: q.id,\n sourceQuery: q,\n }\n moduleQueryCache.set(key, reactive)\n return reactive\n}\n\nexport function exitQuery(query: Query): Query {\n const q = query as QueryInternal\n const key = `exit:${q.id}`\n const cached = moduleQueryCache.get(key)\n if (cached) return cached\n const reactive: QueryInternal = {\n id: nextQueryId++,\n mask: [],\n all: q.all,\n any: q.any,\n none: q.none,\n columnViewCache: q.columnViewCache,\n reactiveKind: 'exit',\n sourceQueryId: q.id,\n sourceQuery: q,\n }\n moduleQueryCache.set(key, reactive)\n return reactive\n}\n\n// --- Per-world query setup ---\n\nfunction ensureQueryRegistered(state: WorldState, q: QueryInternal): void {\n if (state.queries[q.id] === q && state.queryMasks.has(q.id)) return\n\n // Build per-world bitmasks (this may register new bits)\n const ww = state.options.maskWordCount\n const withMask = createMask(ww)\n const anyMask = createMask(ww)\n const noneMask = createMask(ww)\n for (const compId of q.all) {\n const info = getComponentInfoById(compId)\n const bit = getOrRegisterComponentBit(state, info)\n setBit(withMask, bit)\n }\n for (const compId of q.any) {\n const info = getComponentInfoById(compId)\n const bit = getOrRegisterComponentBit(state, info)\n setBit(anyMask, bit)\n }\n for (const compId of q.none) {\n const info = getComponentInfoById(compId)\n const bit = getOrRegisterComponentBit(state, info)\n setBit(noneMask, bit)\n }\n\n const bundle: QueryMaskBundle = {\n withMask,\n anyMask,\n noneMask,\n anyHasBits: !isMaskZero(anyMask),\n }\n state.queryMasks.set(q.id, bundle)\n\n state.queries[q.id] = q\n state.queryArchetypeCache[q.id] = null\n state.queryArchetypeStamp[q.id] = -1\n\n // Build bit → queries index for fast reactive lookup\n const involvedBits: number[] = [\n ...listBits(withMask),\n ...listBits(anyMask),\n ...listBits(noneMask),\n ]\n for (const b of involvedBits) {\n let s = state.bitToQueries.get(b)\n if (!s) {\n s = new Set<number>()\n state.bitToQueries.set(b, s)\n }\n s.add(q.id)\n }\n\n // Initialize reactive buffer for enter/exit queries\n if (q.reactiveKind !== 'normal') {\n if (!state.reactiveBuffers.has(q.id)) {\n state.reactiveBuffers.set(q.id, { entered: [], exited: [] })\n }\n // Also register the source query so recordEntityMaskChange will see it\n if (q.sourceQuery) ensureQueryRegistered(state, q.sourceQuery)\n }\n}\n\nfunction getQueryArchetypes(state: WorldState, q: QueryInternal): number[] {\n ensureQueryRegistered(state, q)\n if (state.queryArchetypeCache[q.id] && state.queryArchetypeStamp[q.id] === state.queryVersion) {\n return state.queryArchetypeCache[q.id]!\n }\n const bundle = state.queryMasks.get(q.id)!\n const words = state.options.maskWordCount\n const list: number[] = []\n for (let i = 0; i < state.archetypes.length; i++) {\n const arch = state.archetypes[i]!\n if (\n matches(arch.mask, bundle.withMask, bundle.anyMask, bundle.noneMask, bundle.anyHasBits, words)\n ) {\n list.push(i)\n }\n }\n state.queryArchetypeCache[q.id] = list\n state.queryArchetypeStamp[q.id] = state.queryVersion\n return list\n}\n\nexport function queryArchetypes(world: World, query: Query): readonly Archetype[] {\n const state = getWorldState(world)\n const q = query as QueryInternal\n const ids = getQueryArchetypes(state, q)\n const out: Archetype[] = []\n for (const id of ids) {\n const arch = state.archetypes[id]!\n out.push({ id: arch.id, mask: Array.from(arch.mask), size: arch.size })\n }\n return out\n}\n\nexport function runQuery(world: World, query: Query): readonly EntityId[] {\n const state = getWorldState(world)\n const q = query as QueryInternal\n const out: EntityId[] = []\n if (q.reactiveKind === 'enter') {\n const buf = state.reactiveBuffers.get(q.id)\n if (buf) {\n for (const e of buf.entered) out.push(e as EntityId)\n buf.entered.length = 0\n }\n return out\n }\n if (q.reactiveKind === 'exit') {\n const buf = state.reactiveBuffers.get(q.id)\n if (buf) {\n for (const e of buf.exited) out.push(e as EntityId)\n buf.exited.length = 0\n }\n return out\n }\n const archIds = getQueryArchetypes(state, q)\n for (const id of archIds) {\n const arch = state.archetypes[id]!\n for (let r = 0; r < arch.size; r++) {\n out.push(arch.entities[r] as EntityId)\n }\n }\n return out\n}\n\nexport function* iterQuery(world: World, query: Query): IterableIterator<EntityId> {\n const state = getWorldState(world)\n const q = query as QueryInternal\n if (q.reactiveKind !== 'normal') {\n const buf = state.reactiveBuffers.get(q.id)\n if (!buf) return\n const src = q.reactiveKind === 'enter' ? buf.entered : buf.exited\n for (const e of src) yield e as EntityId\n src.length = 0\n return\n }\n const archIds = getQueryArchetypes(state, q)\n for (const id of archIds) {\n const arch = state.archetypes[id]!\n for (let r = 0; r < arch.size; r++) {\n yield arch.entities[r] as EntityId\n }\n }\n}\n\nexport function forEachEntity(\n world: World,\n query: Query,\n fn: (eid: EntityId, ...cols: any[]) => void,\n): void {\n const state = getWorldState(world)\n const q = query as QueryInternal\n\n if (q.reactiveKind !== 'normal') {\n const buf = state.reactiveBuffers.get(q.id)\n if (!buf) return\n const src = q.reactiveKind === 'enter' ? buf.entered : buf.exited\n if (src.length === 0) return\n const cols = buildColumnViews(state, q)\n for (let i = 0; i < src.length; i++) {\n const e = src[i] as EntityId\n callWithCols(fn, e, cols)\n }\n src.length = 0\n return\n }\n\n ensureQueryRegistered(state, q)\n const archIds = getQueryArchetypes(state, q)\n const cols = buildColumnViews(state, q)\n for (const id of archIds) {\n const arch = state.archetypes[id]!\n const ents = arch.entities\n const n = arch.size\n for (let r = 0; r < n; r++) {\n callWithCols(fn, ents[r] as EntityId, cols)\n }\n }\n}\n\nfunction callWithCols(\n fn: (eid: EntityId, ...cols: any[]) => void,\n eid: EntityId,\n cols: any[],\n): void {\n // Specialise for low arities to avoid spread allocation.\n switch (cols.length) {\n case 0:\n fn(eid)\n break\n case 1:\n fn(eid, cols[0])\n break\n case 2:\n fn(eid, cols[0], cols[1])\n break\n case 3:\n fn(eid, cols[0], cols[1], cols[2])\n break\n case 4:\n fn(eid, cols[0], cols[1], cols[2], cols[3])\n break\n case 5:\n fn(eid, cols[0], cols[1], cols[2], cols[3], cols[4])\n break\n default:\n fn(eid, ...cols)\n }\n}\n\nfunction buildColumnViews(state: WorldState, q: QueryInternal): any[] {\n const out: any[] = []\n for (const comp of q.columnViewCache) {\n const info = getComponentInfo(comp)\n const bit = state.componentBitFor.get(info.id)\n if (bit === undefined) {\n out.push(undefined)\n continue\n }\n const storage = state.componentStorageByBit[bit]\n if (!storage) {\n out.push(undefined)\n continue\n }\n if (storage.kind === 'soa') out.push(storage.soa)\n else if (storage.kind === 'aos') out.push(storage.aos)\n else out.push(true) // tag\n }\n return out\n}\n\n// --- Reactive query updates (called from migration code) ---\n\nexport function recordEntityMaskChange(\n state: WorldState,\n eid: EntityId,\n changedBit: number,\n prevMask: Uint32Array,\n nextMask: Uint32Array,\n): void {\n // Lazy-register any reactive queries (and their sources) so we can correctly\n // determine match transitions even if the user only ever called enterQuery/exitQuery.\n for (const q of moduleQueryCache.values()) {\n if (q.reactiveKind === 'normal') continue\n if (q.sourceQuery && state.queries[q.sourceQuery.id] !== q.sourceQuery) {\n ensureQueryRegistered(state, q.sourceQuery)\n }\n }\n\n const involved = state.bitToQueries.get(changedBit)\n if (!involved) return\n const words = state.options.maskWordCount\n for (const qid of involved) {\n const q = state.queries[qid]\n if (!q) continue\n if (q.reactiveKind !== 'normal') continue\n const bundle = state.queryMasks.get(qid)\n if (!bundle) continue\n const wasMatch = matches(\n prevMask,\n bundle.withMask,\n bundle.anyMask,\n bundle.noneMask,\n bundle.anyHasBits,\n words,\n )\n const isMatch = matches(\n nextMask,\n bundle.withMask,\n bundle.anyMask,\n bundle.noneMask,\n bundle.anyHasBits,\n words,\n )\n if (!wasMatch && isMatch) {\n pushReactive(state, qid, 'enter', eid)\n } else if (wasMatch && !isMatch) {\n pushReactive(state, qid, 'exit', eid)\n }\n }\n}\n\nfunction pushReactive(\n state: WorldState,\n queryId: number,\n kind: 'enter' | 'exit',\n eid: EntityId,\n): void {\n // Walk the module cache (not just state.queries) so reactive variants that\n // haven't been registered with this world yet still receive events.\n for (const r of moduleQueryCache.values()) {\n if (r.sourceQueryId !== queryId) continue\n if (r.reactiveKind !== kind) continue\n // Lazily register the reactive query in this world so subsequent reads can find it\n ensureQueryRegistered(state, r)\n const buf = ensureReactiveBuffer(state, r.id)\n if (kind === 'enter') buf.entered.push(eid as number)\n else buf.exited.push(eid as number)\n }\n}\n\nfunction ensureReactiveBuffer(state: WorldState, qid: number): ReactiveBuffer {\n let buf = state.reactiveBuffers.get(qid)\n if (!buf) {\n buf = { entered: [], exited: [] }\n state.reactiveBuffers.set(qid, buf)\n }\n return buf\n}\n\n// --- Helpers ---\n\nfunction getComponentInfoById(componentId: number): ComponentInfo {\n // We need access to the component registry's lookup by id. Re-import dynamically to avoid cycles.\n const info = lazyGetComponentInfo(componentId)\n if (!info) throw new Error(`aiecsjs: component id ${componentId} not registered`)\n return info\n}\n\nlet _getComponentInfoFn: ((id: number) => ComponentInfo | undefined) | null = null\nexport function registerComponentLookup(fn: (id: number) => ComponentInfo | undefined): void {\n _getComponentInfoFn = fn\n}\nfunction lazyGetComponentInfo(id: number): ComponentInfo | undefined {\n return _getComponentInfoFn ? _getComponentInfoFn(id) : undefined\n}\n\nexport function _resetQueryRegistry_FOR_TESTS_ONLY(): void {\n moduleQueryCache.clear()\n nextQueryId = 1\n}\n"]}
@@ -0,0 +1,2 @@
1
+ import {i,I,e,b as b$1,p as p$1,c,d,f as f$1}from'./chunk-BUFJWGRQ.js';var C=1,f=new Map;function _(n){let e=(n.all??[]).map(r=>r.__id).sort((r,o)=>r-o).join("-"),t=(n.any??[]).map(r=>r.__id).sort((r,o)=>r-o).join("-"),i=(n.none??[]).map(r=>r.__id).sort((r,o)=>r-o).join("-");return `A${e}|Y${t}|N${i}`}function q(n){let e=Array.isArray(n)?{all:n}:n;for(let o of [...e.all??[],...e.any??[],...e.none??[]])if(!o||typeof o!="object"||typeof o.__id!="number")throw new TypeError("aiecsjs: defineQuery received a non-component value");let t=_(e),i=f.get(t);if(i)return i;let r={id:C++,mask:[],all:(e.all??[]).map(o=>o.__id),any:(e.any??[]).map(o=>o.__id),none:(e.none??[]).map(o=>o.__id),columnViewCache:[...e.all??[],...e.any??[]],reactiveKind:"normal",sourceQueryId:-1,sourceQuery:null};return f.set(t,r),r}function z(n){let e=n,t=`enter:${e.id}`,i=f.get(t);if(i)return i;let r={id:C++,mask:[],all:e.all,any:e.any,none:e.none,columnViewCache:e.columnViewCache,reactiveKind:"enter",sourceQueryId:e.id,sourceQuery:e};return f.set(t,r),r}function T(n){let e=n,t=`exit:${e.id}`,i=f.get(t);if(i)return i;let r={id:C++,mask:[],all:e.all,any:e.any,none:e.none,columnViewCache:e.columnViewCache,reactiveKind:"exit",sourceQueryId:e.id,sourceQuery:e};return f.set(t,r),r}function p(n,e){if(n.queries[e.id]===e&&n.queryMasks.has(e.id))return;let t=n.options.maskWordCount,i=b$1(t),r=b$1(t),o=b$1(t);for(let a of e.all){let u=b(a),d=p$1(n,u);c(i,d);}for(let a of e.any){let u=b(a),d=p$1(n,u);c(r,d);}for(let a of e.none){let u=b(a),d=p$1(n,u);c(o,d);}let c$1={withMask:i,anyMask:r,noneMask:o,anyHasBits:!d(r)};n.queryMasks.set(e.id,c$1),n.queries[e.id]=e,n.queryArchetypeCache[e.id]=null,n.queryArchetypeStamp[e.id]=-1;let s=[...f$1(i),...f$1(r),...f$1(o)];for(let a of s){let u=n.bitToQueries.get(a);u||(u=new Set,n.bitToQueries.set(a,u)),u.add(e.id);}e.reactiveKind!=="normal"&&(n.reactiveBuffers.has(e.id)||n.reactiveBuffers.set(e.id,{entered:[],exited:[]}),e.sourceQuery&&p(n,e.sourceQuery));}function v(n,e$1){if(p(n,e$1),n.queryArchetypeCache[e$1.id]&&n.queryArchetypeStamp[e$1.id]===n.queryVersion)return n.queryArchetypeCache[e$1.id];let t=n.queryMasks.get(e$1.id),i=n.options.maskWordCount,r=[];for(let o=0;o<n.archetypes.length;o++){let c=n.archetypes[o];e(c.mask,t.withMask,t.anyMask,t.noneMask,t.anyHasBits,i)&&r.push(o);}return n.queryArchetypeCache[e$1.id]=r,n.queryArchetypeStamp[e$1.id]=n.queryVersion,r}function $(n,e){let t=i(n),r=v(t,e),o=[];for(let c of r){let s=t.archetypes[c];o.push({id:s.id,mask:Array.from(s.mask),size:s.size});}return o}function D(n,e){let t=i(n),i$1=e,r=[];if(i$1.reactiveKind==="enter"){let c=t.reactiveBuffers.get(i$1.id);if(c){for(let s of c.entered)r.push(s);c.entered.length=0;}return r}if(i$1.reactiveKind==="exit"){let c=t.reactiveBuffers.get(i$1.id);if(c){for(let s of c.exited)r.push(s);c.exited.length=0;}return r}let o=v(t,i$1);for(let c of o){let s=t.archetypes[c];for(let a=0;a<s.size;a++)r.push(s.entities[a]);}return r}function*H(n,e){let t=i(n),i$1=e;if(i$1.reactiveKind!=="normal"){let o=t.reactiveBuffers.get(i$1.id);if(!o)return;let c=i$1.reactiveKind==="enter"?o.entered:o.exited;for(let s of c)yield s;c.length=0;return}let r=v(t,i$1);for(let o of r){let c=t.archetypes[o];for(let s=0;s<c.size;s++)yield c.entities[s];}}function L(n,e,t){let i$1=i(n),r=e;if(r.reactiveKind!=="normal"){let s=i$1.reactiveBuffers.get(r.id);if(!s)return;let a=r.reactiveKind==="enter"?s.entered:s.exited;if(a.length===0)return;let u=w(i$1,r);for(let d=0;d<a.length;d++){let y=a[d];x(t,y,u);}a.length=0;return}p(i$1,r);let o=v(i$1,r),c=w(i$1,r);for(let s of o){let a=i$1.archetypes[s],u=a.entities,d=a.size;for(let y=0;y<d;y++)x(t,u[y],c);}}function x(n,e,t){switch(t.length){case 0:n(e);break;case 1:n(e,t[0]);break;case 2:n(e,t[0],t[1]);break;case 3:n(e,t[0],t[1],t[2]);break;case 4:n(e,t[0],t[1],t[2],t[3]);break;case 5:n(e,t[0],t[1],t[2],t[3],t[4]);break;default:n(e,...t);}}function w(n,e){let t=[];for(let i of e.columnViewCache){let r=I(i),o=n.componentBitFor.get(r.id);if(o===void 0){t.push(void 0);continue}let c=n.componentStorageByBit[o];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 F(n,e$1,t,i,r){for(let s of f.values())s.reactiveKind!=="normal"&&s.sourceQuery&&n.queries[s.sourceQuery.id]!==s.sourceQuery&&p(n,s.sourceQuery);let o=n.bitToQueries.get(t);if(!o)return;let c=n.options.maskWordCount;for(let s of o){let a=n.queries[s];if(!a||a.reactiveKind!=="normal")continue;let u=n.queryMasks.get(s);if(!u)continue;let d=e(i,u.withMask,u.anyMask,u.noneMask,u.anyHasBits,c),y=e(r,u.withMask,u.anyMask,u.noneMask,u.anyHasBits,c);!d&&y?E(n,s,"enter",e$1):d&&!y&&E(n,s,"exit",e$1);}}function E(n,e,t,i){for(let r of f.values()){if(r.sourceQueryId!==e||r.reactiveKind!==t)continue;p(n,r);let o=A(n,r.id);t==="enter"?o.entered.push(i):o.exited.push(i);}}function A(n,e){let t=n.reactiveBuffers.get(e);return t||(t={entered:[],exited:[]},n.reactiveBuffers.set(e,t)),t}function b(n){let e=W(n);if(!e)throw new Error(`aiecsjs: component id ${n} not registered`);return e}var g=null;function O(n){g=n;}function W(n){return g?g(n):void 0}export{q as a,z as b,T as c,$ as d,D as e,H as f,L as g,F as h,O as i};//# sourceMappingURL=chunk-LU55S4LK.js.map
2
+ //# sourceMappingURL=chunk-LU55S4LK.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/internal/query.ts"],"names":["nextQueryId","moduleQueryCache","descKey","d","all","c","a","b","any","none","defineQuery","arg","desc","key","cached","q","enterQuery","query","reactive","exitQuery","ensureQueryRegistered","state","ww","withMask","createMask","anyMask","noneMask","compId","info","getComponentInfoById","bit","getOrRegisterComponentBit","setBit","bundle","isMaskZero","involvedBits","listBits","s","getQueryArchetypes","words","list","i","arch","matches","queryArchetypes","world","getWorldState","ids","out","id","runQuery","buf","e","archIds","r","iterQuery","src","forEachEntity","fn","cols","buildColumnViews","callWithCols","ents","n","eid","comp","getComponentInfo","storage","recordEntityMaskChange","changedBit","prevMask","nextMask","involved","qid","wasMatch","isMatch","pushReactive","queryId","kind","ensureReactiveBuffer","componentId","lazyGetComponentInfo","_getComponentInfoFn","registerComponentLookup"],"mappings":"8EAsBA,IAAIA,EAAc,CAAA,CACZC,CAAAA,CAAmB,IAAI,GAAA,CAE7B,SAASC,CAAAA,CAAQC,CAAAA,CAA4B,CAC3C,IAAMC,GAAOD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AAM,IAAI,KAAA,CAAM,yBAAyBoD,CAAW,CAAA,eAAA,CAAiB,EAChF,OAAOpD,CACT,CAEA,IAAIsD,EAA0E,IAAA,CACvE,SAASC,EAAwBzB,CAAAA,CAAqD,CAC3FwB,EAAsBxB,EACxB,CACA,SAASuB,CAAAA,CAAqBhC,EAAuC,CACnE,OAAOiC,EAAsBA,CAAAA,CAAoBjC,CAAE,EAAI,MACzD","file":"chunk-ZNLOJVCV.js","sourcesContent":["import { createMask, isMaskZero, listBits, matches, setBit } from './bitmask.js'\nimport { getComponentInfo } from './component.js'\nimport type {\n Archetype,\n ComponentInfo,\n ComponentLike,\n EntityId,\n Query,\n QueryDescriptor,\n QueryInternal,\n QueryMaskBundle,\n ReactiveBuffer,\n World,\n WorldState,\n} from './types.js'\nimport {\n getOrRegisterComponentBit,\n getWorldState,\n readEntityMask,\n tryGetComponentBit,\n} from './world.js'\n\nlet nextQueryId = 1\nconst moduleQueryCache = new Map<string, QueryInternal>()\n\nfunction descKey(d: QueryDescriptor): string {\n const all = (d.all ?? [])\n .map((c) => c.__id)\n .sort((a, b) => a - b)\n .join('-')\n const any = (d.any ?? [])\n .map((c) => c.__id)\n .sort((a, b) => a - b)\n .join('-')\n const none = (d.none ?? [])\n .map((c) => c.__id)\n .sort((a, b) => a - b)\n .join('-')\n return `A${all}|Y${any}|N${none}`\n}\n\nexport function defineQuery(arg: ComponentLike[] | QueryDescriptor): Query {\n const desc: QueryDescriptor = Array.isArray(arg) ? { all: arg } : arg\n\n // Validate all members are components\n for (const c of [...(desc.all ?? []), ...(desc.any ?? []), ...(desc.none ?? [])]) {\n if (!c || typeof c !== 'object' || typeof (c as any).__id !== 'number') {\n throw new TypeError('aiecsjs: defineQuery received a non-component value')\n }\n }\n\n const key = descKey(desc)\n const cached = moduleQueryCache.get(key)\n if (cached) return cached\n\n const q: QueryInternal = {\n id: nextQueryId++,\n mask: [],\n all: (desc.all ?? []).map((c) => c.__id),\n any: (desc.any ?? []).map((c) => c.__id),\n none: (desc.none ?? []).map((c) => c.__id),\n columnViewCache: [...(desc.all ?? []), ...(desc.any ?? [])],\n reactiveKind: 'normal',\n sourceQueryId: -1,\n sourceQuery: null,\n }\n moduleQueryCache.set(key, q)\n return q\n}\n\nexport function enterQuery(query: Query): Query {\n const q = query as QueryInternal\n const key = `enter:${q.id}`\n const cached = moduleQueryCache.get(key)\n if (cached) return cached\n const reactive: QueryInternal = {\n id: nextQueryId++,\n mask: [],\n all: q.all,\n any: q.any,\n none: q.none,\n columnViewCache: q.columnViewCache,\n reactiveKind: 'enter',\n sourceQueryId: q.id,\n sourceQuery: q,\n }\n moduleQueryCache.set(key, reactive)\n return reactive\n}\n\nexport function exitQuery(query: Query): Query {\n const q = query as QueryInternal\n const key = `exit:${q.id}`\n const cached = moduleQueryCache.get(key)\n if (cached) return cached\n const reactive: QueryInternal = {\n id: nextQueryId++,\n mask: [],\n all: q.all,\n any: q.any,\n none: q.none,\n columnViewCache: q.columnViewCache,\n reactiveKind: 'exit',\n sourceQueryId: q.id,\n sourceQuery: q,\n }\n moduleQueryCache.set(key, reactive)\n return reactive\n}\n\n// --- Per-world query setup ---\n\nfunction ensureQueryRegistered(state: WorldState, q: QueryInternal): void {\n if (state.queries[q.id] === q && state.queryMasks.has(q.id)) return\n\n // Build per-world bitmasks (this may register new bits)\n const ww = state.options.maskWordCount\n const withMask = createMask(ww)\n const anyMask = createMask(ww)\n const noneMask = createMask(ww)\n for (const compId of q.all) {\n const info = getComponentInfoById(compId)\n const bit = getOrRegisterComponentBit(state, info)\n setBit(withMask, bit)\n }\n for (const compId of q.any) {\n const info = getComponentInfoById(compId)\n const bit = getOrRegisterComponentBit(state, info)\n setBit(anyMask, bit)\n }\n for (const compId of q.none) {\n const info = getComponentInfoById(compId)\n const bit = getOrRegisterComponentBit(state, info)\n setBit(noneMask, bit)\n }\n\n const bundle: QueryMaskBundle = {\n withMask,\n anyMask,\n noneMask,\n anyHasBits: !isMaskZero(anyMask),\n }\n state.queryMasks.set(q.id, bundle)\n\n state.queries[q.id] = q\n state.queryArchetypeCache[q.id] = null\n state.queryArchetypeStamp[q.id] = -1\n\n // Build bit → queries index for fast reactive lookup\n const involvedBits: number[] = [\n ...listBits(withMask),\n ...listBits(anyMask),\n ...listBits(noneMask),\n ]\n for (const b of involvedBits) {\n let s = state.bitToQueries.get(b)\n if (!s) {\n s = new Set<number>()\n state.bitToQueries.set(b, s)\n }\n s.add(q.id)\n }\n\n // Initialize reactive buffer for enter/exit queries\n if (q.reactiveKind !== 'normal') {\n if (!state.reactiveBuffers.has(q.id)) {\n state.reactiveBuffers.set(q.id, { entered: [], exited: [] })\n }\n // Also register the source query so recordEntityMaskChange will see it\n if (q.sourceQuery) ensureQueryRegistered(state, q.sourceQuery)\n }\n}\n\nfunction getQueryArchetypes(state: WorldState, q: QueryInternal): number[] {\n ensureQueryRegistered(state, q)\n if (state.queryArchetypeCache[q.id] && state.queryArchetypeStamp[q.id] === state.queryVersion) {\n return state.queryArchetypeCache[q.id]!\n }\n const bundle = state.queryMasks.get(q.id)!\n const words = state.options.maskWordCount\n const list: number[] = []\n for (let i = 0; i < state.archetypes.length; i++) {\n const arch = state.archetypes[i]!\n if (\n matches(arch.mask, bundle.withMask, bundle.anyMask, bundle.noneMask, bundle.anyHasBits, words)\n ) {\n list.push(i)\n }\n }\n state.queryArchetypeCache[q.id] = list\n state.queryArchetypeStamp[q.id] = state.queryVersion\n return list\n}\n\nexport function queryArchetypes(world: World, query: Query): readonly Archetype[] {\n const state = getWorldState(world)\n const q = query as QueryInternal\n const ids = getQueryArchetypes(state, q)\n const out: Archetype[] = []\n for (const id of ids) {\n const arch = state.archetypes[id]!\n out.push({ id: arch.id, mask: Array.from(arch.mask), size: arch.size })\n }\n return out\n}\n\nexport function runQuery(world: World, query: Query): readonly EntityId[] {\n const state = getWorldState(world)\n const q = query as QueryInternal\n const out: EntityId[] = []\n if (q.reactiveKind === 'enter') {\n const buf = state.reactiveBuffers.get(q.id)\n if (buf) {\n for (const e of buf.entered) out.push(e as EntityId)\n buf.entered.length = 0\n }\n return out\n }\n if (q.reactiveKind === 'exit') {\n const buf = state.reactiveBuffers.get(q.id)\n if (buf) {\n for (const e of buf.exited) out.push(e as EntityId)\n buf.exited.length = 0\n }\n return out\n }\n const archIds = getQueryArchetypes(state, q)\n for (const id of archIds) {\n const arch = state.archetypes[id]!\n for (let r = 0; r < arch.size; r++) {\n out.push(arch.entities[r] as EntityId)\n }\n }\n return out\n}\n\nexport function* iterQuery(world: World, query: Query): IterableIterator<EntityId> {\n const state = getWorldState(world)\n const q = query as QueryInternal\n if (q.reactiveKind !== 'normal') {\n const buf = state.reactiveBuffers.get(q.id)\n if (!buf) return\n const src = q.reactiveKind === 'enter' ? buf.entered : buf.exited\n for (const e of src) yield e as EntityId\n src.length = 0\n return\n }\n const archIds = getQueryArchetypes(state, q)\n for (const id of archIds) {\n const arch = state.archetypes[id]!\n for (let r = 0; r < arch.size; r++) {\n yield arch.entities[r] as EntityId\n }\n }\n}\n\nexport function forEachEntity(\n world: World,\n query: Query,\n fn: (eid: EntityId, ...cols: any[]) => void,\n): void {\n const state = getWorldState(world)\n const q = query as QueryInternal\n\n if (q.reactiveKind !== 'normal') {\n const buf = state.reactiveBuffers.get(q.id)\n if (!buf) return\n const src = q.reactiveKind === 'enter' ? buf.entered : buf.exited\n if (src.length === 0) return\n const cols = buildColumnViews(state, q)\n for (let i = 0; i < src.length; i++) {\n const e = src[i] as EntityId\n callWithCols(fn, e, cols)\n }\n src.length = 0\n return\n }\n\n ensureQueryRegistered(state, q)\n const archIds = getQueryArchetypes(state, q)\n const cols = buildColumnViews(state, q)\n for (const id of archIds) {\n const arch = state.archetypes[id]!\n const ents = arch.entities\n const n = arch.size\n for (let r = 0; r < n; r++) {\n callWithCols(fn, ents[r] as EntityId, cols)\n }\n }\n}\n\nfunction callWithCols(\n fn: (eid: EntityId, ...cols: any[]) => void,\n eid: EntityId,\n cols: any[],\n): void {\n // Specialise for low arities to avoid spread allocation.\n switch (cols.length) {\n case 0:\n fn(eid)\n break\n case 1:\n fn(eid, cols[0])\n break\n case 2:\n fn(eid, cols[0], cols[1])\n break\n case 3:\n fn(eid, cols[0], cols[1], cols[2])\n break\n case 4:\n fn(eid, cols[0], cols[1], cols[2], cols[3])\n break\n case 5:\n fn(eid, cols[0], cols[1], cols[2], cols[3], cols[4])\n break\n default:\n fn(eid, ...cols)\n }\n}\n\nfunction buildColumnViews(state: WorldState, q: QueryInternal): any[] {\n const out: any[] = []\n for (const comp of q.columnViewCache) {\n const info = getComponentInfo(comp)\n const bit = state.componentBitFor.get(info.id)\n if (bit === undefined) {\n out.push(undefined)\n continue\n }\n const storage = state.componentStorageByBit[bit]\n if (!storage) {\n out.push(undefined)\n continue\n }\n if (storage.kind === 'soa') out.push(storage.soa)\n else if (storage.kind === 'aos') out.push(storage.aos)\n else out.push(true) // tag\n }\n return out\n}\n\n// --- Reactive query updates (called from migration code) ---\n\nexport function recordEntityMaskChange(\n state: WorldState,\n eid: EntityId,\n changedBit: number,\n prevMask: Uint32Array,\n nextMask: Uint32Array,\n): void {\n // Lazy-register any reactive queries (and their sources) so we can correctly\n // determine match transitions even if the user only ever called enterQuery/exitQuery.\n for (const q of moduleQueryCache.values()) {\n if (q.reactiveKind === 'normal') continue\n if (q.sourceQuery && state.queries[q.sourceQuery.id] !== q.sourceQuery) {\n ensureQueryRegistered(state, q.sourceQuery)\n }\n }\n\n const involved = state.bitToQueries.get(changedBit)\n if (!involved) return\n const words = state.options.maskWordCount\n for (const qid of involved) {\n const q = state.queries[qid]\n if (!q) continue\n if (q.reactiveKind !== 'normal') continue\n const bundle = state.queryMasks.get(qid)\n if (!bundle) continue\n const wasMatch = matches(\n prevMask,\n bundle.withMask,\n bundle.anyMask,\n bundle.noneMask,\n bundle.anyHasBits,\n words,\n )\n const isMatch = matches(\n nextMask,\n bundle.withMask,\n bundle.anyMask,\n bundle.noneMask,\n bundle.anyHasBits,\n words,\n )\n if (!wasMatch && isMatch) {\n pushReactive(state, qid, 'enter', eid)\n } else if (wasMatch && !isMatch) {\n pushReactive(state, qid, 'exit', eid)\n }\n }\n}\n\nfunction pushReactive(\n state: WorldState,\n queryId: number,\n kind: 'enter' | 'exit',\n eid: EntityId,\n): void {\n // Walk the module cache (not just state.queries) so reactive variants that\n // haven't been registered with this world yet still receive events.\n for (const r of moduleQueryCache.values()) {\n if (r.sourceQueryId !== queryId) continue\n if (r.reactiveKind !== kind) continue\n // Lazily register the reactive query in this world so subsequent reads can find it\n ensureQueryRegistered(state, r)\n const buf = ensureReactiveBuffer(state, r.id)\n if (kind === 'enter') buf.entered.push(eid as number)\n else buf.exited.push(eid as number)\n }\n}\n\nfunction ensureReactiveBuffer(state: WorldState, qid: number): ReactiveBuffer {\n let buf = state.reactiveBuffers.get(qid)\n if (!buf) {\n buf = { entered: [], exited: [] }\n state.reactiveBuffers.set(qid, buf)\n }\n return buf\n}\n\n// --- Helpers ---\n\nfunction getComponentInfoById(componentId: number): ComponentInfo {\n // We need access to the component registry's lookup by id. Re-import dynamically to avoid cycles.\n const info = lazyGetComponentInfo(componentId)\n if (!info) throw new Error(`aiecsjs: component id ${componentId} not registered`)\n return info\n}\n\nlet _getComponentInfoFn: ((id: number) => ComponentInfo | undefined) | null = null\nexport function registerComponentLookup(fn: (id: number) => ComponentInfo | undefined): void {\n _getComponentInfoFn = fn\n}\nfunction lazyGetComponentInfo(id: number): ComponentInfo | undefined {\n return _getComponentInfoFn ? _getComponentInfoFn(id) : undefined\n}\n\nexport function _resetQueryRegistry_FOR_TESTS_ONLY(): void {\n moduleQueryCache.clear()\n nextQueryId = 1\n}\n"]}
1
+ {"version":3,"sources":["../src/internal/query.ts"],"names":["nextQueryId","moduleQueryCache","descKey","d","all","c","a","b","any","none","defineQuery","arg","desc","key","cached","q","enterQuery","query","reactive","exitQuery","ensureQueryRegistered","state","ww","withMask","createMask","anyMask","noneMask","compId","info","getComponentInfoById","bit","getOrRegisterComponentBit","setBit","bundle","isMaskZero","involvedBits","listBits","s","getQueryArchetypes","words","list","i","arch","matches","queryArchetypes","world","getWorldState","ids","out","id","runQuery","buf","e","archIds","r","iterQuery","src","forEachEntity","fn","cols","buildColumnViews","callWithCols","ents","n","eid","comp","getComponentInfo","storage","recordEntityMaskChange","changedBit","prevMask","nextMask","involved","qid","wasMatch","isMatch","pushReactive","queryId","kind","ensureReactiveBuffer","componentId","lazyGetComponentInfo","_getComponentInfoFn","registerComponentLookup"],"mappings":"uEAsBA,IAAIA,EAAc,CAAA,CACZC,CAAAA,CAAmB,IAAI,GAAA,CAE7B,SAASC,CAAAA,CAAQC,CAAAA,CAA4B,CAC3C,IAAMC,GAAOD,CAAAA,CAAE,GAAA,EAAO,EAAC,EACpB,GAAA,CAAKE,GAAMA,CAAAA,CAAE,IAAI,CAAA,CACjB,IAAA,CAAK,CAACC,CAAAA,CAAGC,CAAAA,GAAMD,EAAIC,CAAC,CAAA,CACpB,KAAK,GAAG,CAAA,CACLC,CAAAA,CAAAA,CAAOL,CAAAA,CAAE,KAAO,EAAC,EACpB,IAAKE,CAAAA,EAAMA,CAAAA,CAAE,IAAI,CAAA,CACjB,IAAA,CAAK,CAACC,CAAAA,CAAGC,IAAMD,CAAAA,CAAIC,CAAC,EACpB,IAAA,CAAK,GAAG,EACLE,CAAAA,CAAAA,CAAQN,CAAAA,CAAE,IAAA,EAAQ,IACrB,GAAA,CAAKE,CAAAA,EAAMA,EAAE,IAAI,CAAA,CACjB,KAAK,CAACC,CAAAA,CAAGC,CAAAA,GAAMD,CAAAA,CAAIC,CAAC,CAAA,CACpB,IAAA,CAAK,GAAG,CAAA,CACX,OAAO,IAAIH,CAAG,CAAA,EAAA,EAAKI,CAAG,CAAA,EAAA,EAAKC,CAAI,CAAA,CACjC,CAEO,SAASC,CAAAA,CAAYC,CAAAA,CAA+C,CACzE,IAAMC,CAAAA,CAAwB,KAAA,CAAM,OAAA,CAAQD,CAAG,CAAA,CAAI,CAAE,IAAKA,CAAI,CAAA,CAAIA,EAGlE,IAAA,IA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AA,CAA6B,CAC5E,IAAItB,CAAAA,CAAM9B,CAAAA,CAAM,eAAA,CAAgB,GAAA,CAAIoD,CAAG,CAAA,CACvC,OAAKtB,IACHA,CAAAA,CAAM,CAAE,QAAS,EAAC,CAAG,MAAA,CAAQ,EAAG,CAAA,CAChC9B,CAAAA,CAAM,gBAAgB,GAAA,CAAIoD,CAAAA,CAAKtB,CAAG,CAAA,CAAA,CAE7BA,CACT,CAIA,SAAStB,EAAqBmD,CAAAA,CAAoC,CAEhE,IAAMpD,CAAAA,CAAOqD,CAAAA,CAAqBD,CAAW,CAAA,CAC7C,GAAI,CAACpD,CAAAA,CAAM,MAAM,IAAI,KAAA,CAAM,yBAAyBoD,CAAW,CAAA,eAAA,CAAiB,EAChF,OAAOpD,CACT,CAEA,IAAIsD,EAA0E,IAAA,CACvE,SAASC,EAAwBzB,CAAAA,CAAqD,CAC3FwB,EAAsBxB,EACxB,CACA,SAASuB,CAAAA,CAAqBhC,EAAuC,CACnE,OAAOiC,EAAsBA,CAAAA,CAAoBjC,CAAE,EAAI,MACzD","file":"chunk-LU55S4LK.js","sourcesContent":["import { createMask, isMaskZero, listBits, matches, setBit } from './bitmask.js'\nimport { getComponentInfo } from './component.js'\nimport type {\n Archetype,\n ComponentInfo,\n ComponentLike,\n EntityId,\n Query,\n QueryDescriptor,\n QueryInternal,\n QueryMaskBundle,\n ReactiveBuffer,\n World,\n WorldState,\n} from './types.js'\nimport {\n getOrRegisterComponentBit,\n getWorldState,\n readEntityMask,\n tryGetComponentBit,\n} from './world.js'\n\nlet nextQueryId = 1\nconst moduleQueryCache = new Map<string, QueryInternal>()\n\nfunction descKey(d: QueryDescriptor): string {\n const all = (d.all ?? [])\n .map((c) => c.__id)\n .sort((a, b) => a - b)\n .join('-')\n const any = (d.any ?? [])\n .map((c) => c.__id)\n .sort((a, b) => a - b)\n .join('-')\n const none = (d.none ?? [])\n .map((c) => c.__id)\n .sort((a, b) => a - b)\n .join('-')\n return `A${all}|Y${any}|N${none}`\n}\n\nexport function defineQuery(arg: ComponentLike[] | QueryDescriptor): Query {\n const desc: QueryDescriptor = Array.isArray(arg) ? { all: arg } : arg\n\n // Validate all members are components\n for (const c of [...(desc.all ?? []), ...(desc.any ?? []), ...(desc.none ?? [])]) {\n if (!c || typeof c !== 'object' || typeof (c as any).__id !== 'number') {\n throw new TypeError('aiecsjs: defineQuery received a non-component value')\n }\n }\n\n const key = descKey(desc)\n const cached = moduleQueryCache.get(key)\n if (cached) return cached\n\n const q: QueryInternal = {\n id: nextQueryId++,\n mask: [],\n all: (desc.all ?? []).map((c) => c.__id),\n any: (desc.any ?? []).map((c) => c.__id),\n none: (desc.none ?? []).map((c) => c.__id),\n columnViewCache: [...(desc.all ?? []), ...(desc.any ?? [])],\n reactiveKind: 'normal',\n sourceQueryId: -1,\n sourceQuery: null,\n }\n moduleQueryCache.set(key, q)\n return q\n}\n\nexport function enterQuery(query: Query): Query {\n const q = query as QueryInternal\n const key = `enter:${q.id}`\n const cached = moduleQueryCache.get(key)\n if (cached) return cached\n const reactive: QueryInternal = {\n id: nextQueryId++,\n mask: [],\n all: q.all,\n any: q.any,\n none: q.none,\n columnViewCache: q.columnViewCache,\n reactiveKind: 'enter',\n sourceQueryId: q.id,\n sourceQuery: q,\n }\n moduleQueryCache.set(key, reactive)\n return reactive\n}\n\nexport function exitQuery(query: Query): Query {\n const q = query as QueryInternal\n const key = `exit:${q.id}`\n const cached = moduleQueryCache.get(key)\n if (cached) return cached\n const reactive: QueryInternal = {\n id: nextQueryId++,\n mask: [],\n all: q.all,\n any: q.any,\n none: q.none,\n columnViewCache: q.columnViewCache,\n reactiveKind: 'exit',\n sourceQueryId: q.id,\n sourceQuery: q,\n }\n moduleQueryCache.set(key, reactive)\n return reactive\n}\n\n// --- Per-world query setup ---\n\nfunction ensureQueryRegistered(state: WorldState, q: QueryInternal): void {\n if (state.queries[q.id] === q && state.queryMasks.has(q.id)) return\n\n // Build per-world bitmasks (this may register new bits)\n const ww = state.options.maskWordCount\n const withMask = createMask(ww)\n const anyMask = createMask(ww)\n const noneMask = createMask(ww)\n for (const compId of q.all) {\n const info = getComponentInfoById(compId)\n const bit = getOrRegisterComponentBit(state, info)\n setBit(withMask, bit)\n }\n for (const compId of q.any) {\n const info = getComponentInfoById(compId)\n const bit = getOrRegisterComponentBit(state, info)\n setBit(anyMask, bit)\n }\n for (const compId of q.none) {\n const info = getComponentInfoById(compId)\n const bit = getOrRegisterComponentBit(state, info)\n setBit(noneMask, bit)\n }\n\n const bundle: QueryMaskBundle = {\n withMask,\n anyMask,\n noneMask,\n anyHasBits: !isMaskZero(anyMask),\n }\n state.queryMasks.set(q.id, bundle)\n\n state.queries[q.id] = q\n state.queryArchetypeCache[q.id] = null\n state.queryArchetypeStamp[q.id] = -1\n\n // Build bit → queries index for fast reactive lookup\n const involvedBits: number[] = [\n ...listBits(withMask),\n ...listBits(anyMask),\n ...listBits(noneMask),\n ]\n for (const b of involvedBits) {\n let s = state.bitToQueries.get(b)\n if (!s) {\n s = new Set<number>()\n state.bitToQueries.set(b, s)\n }\n s.add(q.id)\n }\n\n // Initialize reactive buffer for enter/exit queries\n if (q.reactiveKind !== 'normal') {\n if (!state.reactiveBuffers.has(q.id)) {\n state.reactiveBuffers.set(q.id, { entered: [], exited: [] })\n }\n // Also register the source query so recordEntityMaskChange will see it\n if (q.sourceQuery) ensureQueryRegistered(state, q.sourceQuery)\n }\n}\n\nfunction getQueryArchetypes(state: WorldState, q: QueryInternal): number[] {\n ensureQueryRegistered(state, q)\n if (state.queryArchetypeCache[q.id] && state.queryArchetypeStamp[q.id] === state.queryVersion) {\n return state.queryArchetypeCache[q.id]!\n }\n const bundle = state.queryMasks.get(q.id)!\n const words = state.options.maskWordCount\n const list: number[] = []\n for (let i = 0; i < state.archetypes.length; i++) {\n const arch = state.archetypes[i]!\n if (\n matches(arch.mask, bundle.withMask, bundle.anyMask, bundle.noneMask, bundle.anyHasBits, words)\n ) {\n list.push(i)\n }\n }\n state.queryArchetypeCache[q.id] = list\n state.queryArchetypeStamp[q.id] = state.queryVersion\n return list\n}\n\nexport function queryArchetypes(world: World, query: Query): readonly Archetype[] {\n const state = getWorldState(world)\n const q = query as QueryInternal\n const ids = getQueryArchetypes(state, q)\n const out: Archetype[] = []\n for (const id of ids) {\n const arch = state.archetypes[id]!\n out.push({ id: arch.id, mask: Array.from(arch.mask), size: arch.size })\n }\n return out\n}\n\nexport function runQuery(world: World, query: Query): readonly EntityId[] {\n const state = getWorldState(world)\n const q = query as QueryInternal\n const out: EntityId[] = []\n if (q.reactiveKind === 'enter') {\n const buf = state.reactiveBuffers.get(q.id)\n if (buf) {\n for (const e of buf.entered) out.push(e as EntityId)\n buf.entered.length = 0\n }\n return out\n }\n if (q.reactiveKind === 'exit') {\n const buf = state.reactiveBuffers.get(q.id)\n if (buf) {\n for (const e of buf.exited) out.push(e as EntityId)\n buf.exited.length = 0\n }\n return out\n }\n const archIds = getQueryArchetypes(state, q)\n for (const id of archIds) {\n const arch = state.archetypes[id]!\n for (let r = 0; r < arch.size; r++) {\n out.push(arch.entities[r] as EntityId)\n }\n }\n return out\n}\n\nexport function* iterQuery(world: World, query: Query): IterableIterator<EntityId> {\n const state = getWorldState(world)\n const q = query as QueryInternal\n if (q.reactiveKind !== 'normal') {\n const buf = state.reactiveBuffers.get(q.id)\n if (!buf) return\n const src = q.reactiveKind === 'enter' ? buf.entered : buf.exited\n for (const e of src) yield e as EntityId\n src.length = 0\n return\n }\n const archIds = getQueryArchetypes(state, q)\n for (const id of archIds) {\n const arch = state.archetypes[id]!\n for (let r = 0; r < arch.size; r++) {\n yield arch.entities[r] as EntityId\n }\n }\n}\n\nexport function forEachEntity(\n world: World,\n query: Query,\n fn: (eid: EntityId, ...cols: any[]) => void,\n): void {\n const state = getWorldState(world)\n const q = query as QueryInternal\n\n if (q.reactiveKind !== 'normal') {\n const buf = state.reactiveBuffers.get(q.id)\n if (!buf) return\n const src = q.reactiveKind === 'enter' ? buf.entered : buf.exited\n if (src.length === 0) return\n const cols = buildColumnViews(state, q)\n for (let i = 0; i < src.length; i++) {\n const e = src[i] as EntityId\n callWithCols(fn, e, cols)\n }\n src.length = 0\n return\n }\n\n ensureQueryRegistered(state, q)\n const archIds = getQueryArchetypes(state, q)\n const cols = buildColumnViews(state, q)\n for (const id of archIds) {\n const arch = state.archetypes[id]!\n const ents = arch.entities\n const n = arch.size\n for (let r = 0; r < n; r++) {\n callWithCols(fn, ents[r] as EntityId, cols)\n }\n }\n}\n\nfunction callWithCols(\n fn: (eid: EntityId, ...cols: any[]) => void,\n eid: EntityId,\n cols: any[],\n): void {\n // Specialise for low arities to avoid spread allocation.\n switch (cols.length) {\n case 0:\n fn(eid)\n break\n case 1:\n fn(eid, cols[0])\n break\n case 2:\n fn(eid, cols[0], cols[1])\n break\n case 3:\n fn(eid, cols[0], cols[1], cols[2])\n break\n case 4:\n fn(eid, cols[0], cols[1], cols[2], cols[3])\n break\n case 5:\n fn(eid, cols[0], cols[1], cols[2], cols[3], cols[4])\n break\n default:\n fn(eid, ...cols)\n }\n}\n\nfunction buildColumnViews(state: WorldState, q: QueryInternal): any[] {\n const out: any[] = []\n for (const comp of q.columnViewCache) {\n const info = getComponentInfo(comp)\n const bit = state.componentBitFor.get(info.id)\n if (bit === undefined) {\n out.push(undefined)\n continue\n }\n const storage = state.componentStorageByBit[bit]\n if (!storage) {\n out.push(undefined)\n continue\n }\n if (storage.kind === 'soa') out.push(storage.soa)\n else if (storage.kind === 'aos') out.push(storage.aos)\n else out.push(true) // tag\n }\n return out\n}\n\n// --- Reactive query updates (called from migration code) ---\n\nexport function recordEntityMaskChange(\n state: WorldState,\n eid: EntityId,\n changedBit: number,\n prevMask: Uint32Array,\n nextMask: Uint32Array,\n): void {\n // Lazy-register any reactive queries (and their sources) so we can correctly\n // determine match transitions even if the user only ever called enterQuery/exitQuery.\n for (const q of moduleQueryCache.values()) {\n if (q.reactiveKind === 'normal') continue\n if (q.sourceQuery && state.queries[q.sourceQuery.id] !== q.sourceQuery) {\n ensureQueryRegistered(state, q.sourceQuery)\n }\n }\n\n const involved = state.bitToQueries.get(changedBit)\n if (!involved) return\n const words = state.options.maskWordCount\n for (const qid of involved) {\n const q = state.queries[qid]\n if (!q) continue\n if (q.reactiveKind !== 'normal') continue\n const bundle = state.queryMasks.get(qid)\n if (!bundle) continue\n const wasMatch = matches(\n prevMask,\n bundle.withMask,\n bundle.anyMask,\n bundle.noneMask,\n bundle.anyHasBits,\n words,\n )\n const isMatch = matches(\n nextMask,\n bundle.withMask,\n bundle.anyMask,\n bundle.noneMask,\n bundle.anyHasBits,\n words,\n )\n if (!wasMatch && isMatch) {\n pushReactive(state, qid, 'enter', eid)\n } else if (wasMatch && !isMatch) {\n pushReactive(state, qid, 'exit', eid)\n }\n }\n}\n\nfunction pushReactive(\n state: WorldState,\n queryId: number,\n kind: 'enter' | 'exit',\n eid: EntityId,\n): void {\n // Walk the module cache (not just state.queries) so reactive variants that\n // haven't been registered with this world yet still receive events.\n for (const r of moduleQueryCache.values()) {\n if (r.sourceQueryId !== queryId) continue\n if (r.reactiveKind !== kind) continue\n // Lazily register the reactive query in this world so subsequent reads can find it\n ensureQueryRegistered(state, r)\n const buf = ensureReactiveBuffer(state, r.id)\n if (kind === 'enter') buf.entered.push(eid as number)\n else buf.exited.push(eid as number)\n }\n}\n\nfunction ensureReactiveBuffer(state: WorldState, qid: number): ReactiveBuffer {\n let buf = state.reactiveBuffers.get(qid)\n if (!buf) {\n buf = { entered: [], exited: [] }\n state.reactiveBuffers.set(qid, buf)\n }\n return buf\n}\n\n// --- Helpers ---\n\nfunction getComponentInfoById(componentId: number): ComponentInfo {\n // We need access to the component registry's lookup by id. Re-import dynamically to avoid cycles.\n const info = lazyGetComponentInfo(componentId)\n if (!info) throw new Error(`aiecsjs: component id ${componentId} not registered`)\n return info\n}\n\nlet _getComponentInfoFn: ((id: number) => ComponentInfo | undefined) | null = null\nexport function registerComponentLookup(fn: (id: number) => ComponentInfo | undefined): void {\n _getComponentInfoFn = fn\n}\nfunction lazyGetComponentInfo(id: number): ComponentInfo | undefined {\n return _getComponentInfoFn ? _getComponentInfoFn(id) : undefined\n}\n\nexport function _resetQueryRegistry_FOR_TESTS_ONLY(): void {\n moduleQueryCache.clear()\n nextQueryId = 1\n}\n"]}
@@ -0,0 +1,2 @@
1
+ import {i,r,k,u,Q as Q$1,J as J$1,a,R,v as v$1}from'./chunk-BUFJWGRQ.js';var p="AIEC",B=1;function P(n,o){let e=D(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))}))),x(e)}function Q(n,o){let e=N(n,o);return J(e)}function D(n){let o=i(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$1=o.generations[t]??0,a=r(t,r$1,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 b=m&-m,A=(d<<5)+(31-Math.clz32(b)),h=o.componentInfoByBit[A];if(h){let S=o.componentStorageByBit[A],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 _=[],M=t*u.vectorLen;for(let C=0;C<u.vectorLen;C++)_.push(g[M+C]??0);y[u.name]=_;}}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}}function J(n){let o=k({initialCapacity:n.capacity}),e=new Map;for(let t of n.entities){let i=u(o);e.set(t.eid,i);}for(let t of n.entities){let i=e.get(t.eid);for(let c of t.components){let r=Q$1(c.id);if(!r)continue;let a=v(r);a&&J$1(o,i,a,c.data);}}return o}function v(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 x(n){let o=JSON.stringify(n),e=new TextEncoder().encode(o),t=new TextEncoder().encode(a),c=12+t.length+4+e.length,r=new Uint8Array(c),a$1=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$1.setUint32(s,B,true),s+=4,a$1.setUint32(s,t.length,true),s+=4,r.set(t,s),s+=t.length,a$1.setUint32(s,e.length,true),s+=4,r.set(e,s),r}function N(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 Y(n,o){let e={world:n,components:o?.components??R().map(t=>v(t)).filter(Boolean),lastSnapshot:null};return {capture(){let t=D(e.world),i;return e.lastSnapshot?i=V(e.lastSnapshot,t):i=t,e.lastSnapshot=t,x(i)},apply(t,i$1){let c=N(i$1),r=i(t);for(let a of c.entities){if(a.eid<=0||a.eid>=r.options.maxEntities)continue;let s=v$1(r,a.eid);for(let f of a.components){let l=Q$1(f.id);if(!l)continue;let d=v(l);d&&J$1(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}}export{P as a,Q as b,D as c,J as d,Y as e};//# sourceMappingURL=chunk-QC25WDOZ.js.map
2
+ //# sourceMappingURL=chunk-QC25WDOZ.js.map
@@ -0,0 +1 @@
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","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","ensureEntityAtSlot","prev","curr","prevByEid","changed","prevE","prevSig","currSig"],"mappings":"yEA0BA,IAAMA,CAAAA,CAAQ,MAAA,CACRC,CAAAA,CAAiB,CAAA,CAEhB,SAASC,CAAAA,CAAeC,CAAAA,CAAcC,CAAAA,CAAwC,CACnF,IAAMC,CAAAA,CAAWC,CAAAA,CAAOH,CAAK,EAC7B,OAAIC,CAAAA,EAAS,UAAA,GACXC,CAAAA,CAAS,QAAA,CAAWA,CAAAA,CAAS,QAAA,CAAS,GAAA,CAAKE,CAAAA,GAAO,CAChD,GAAA,CAAKA,CAAAA,CAAE,GAAA,CACP,UAAA,CAAYA,EAAE,UAAA,CA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UvE,CAAAA,CAAE,UAAU,CAAA,CACvCsE,CAAAA,GAAYC,CAAAA,EAASH,CAAAA,CAAQ,IAAA,CAAKpE,CAAC,EACzC,CACA,OAAO,CAAE,OAAA,CAASkE,CAAAA,CAAK,OAAA,CAAS,QAAA,CAAUA,CAAAA,CAAK,QAAA,CAAU,QAAA,CAAUE,CAAQ,CAC7E","file":"chunk-QC25WDOZ.js","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 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\nexport function fromJSON(snapshot: WorldSnapshot): World {\n const world = createWorld({ initialCapacity: snapshot.capacity })\n const eidMap = new Map<number, EntityId>()\n for (const e of snapshot.entities) {\n const eid = createEntity(world)\n eidMap.set(e.eid, eid)\n }\n for (const e of snapshot.entities) {\n const eid = eidMap.get(e.eid)!\n for (const comp of e.components) {\n const info = getComponentByInternalId(comp.id)\n if (!info) {\n // Component missing — silently skip; future version may throw based on options\n continue\n }\n const handle = getComponentHandle(info)\n if (handle) {\n addComponent(world, eid, handle, comp.data as any)\n }\n }\n }\n return world\n}\n\n// Reconstruct a component handle from its ComponentInfo. Since defineComponent\n// returns plain handles { __kind, __id, __schema }, we can synthesize them.\nfunction getComponentHandle(info: ComponentInfo): ComponentLike | null {\n if (info.kind === 'soa') {\n return { __kind: 'soa', __id: info.id, __schema: info.schema ?? {} } as ComponentLike\n }\n if (info.kind === 'aos') {\n const factory = info.factory ?? (() => ({}))\n return { __kind: 'aos', __id: info.id, __factory: factory } as ComponentLike\n }\n return { __kind: 'tag', __id: info.id } as ComponentLike\n}\n\n// --- Binary packing (wrapped JSON for 0.1) ---\n\nfunction packBinary(snapshot: WorldSnapshot): Uint8Array {\n const json = JSON.stringify(snapshot)\n const jsonBytes = new TextEncoder().encode(json)\n const versionBytes = new TextEncoder().encode(VERSION)\n const headerSize = 4 + 4 + 4 + versionBytes.length + 4\n const total = headerSize + jsonBytes.length\n const out = new Uint8Array(total)\n const view = new DataView(out.buffer)\n let off = 0\n out[off++] = MAGIC.charCodeAt(0)\n out[off++] = MAGIC.charCodeAt(1)\n out[off++] = MAGIC.charCodeAt(2)\n out[off++] = MAGIC.charCodeAt(3)\n view.setUint32(off, FORMAT_VERSION, true)\n off += 4\n view.setUint32(off, versionBytes.length, true)\n off += 4\n out.set(versionBytes, off)\n off += versionBytes.length\n view.setUint32(off, jsonBytes.length, true)\n off += 4\n out.set(jsonBytes, off)\n return out\n}\n\nfunction unpackBinary(bytes: Uint8Array, options?: DeserializeOptions): WorldSnapshot {\n if (bytes.length < 12) throw new Error('aiecsjs: bytes too short to be a valid snapshot')\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)\n if (\n bytes[0] !== MAGIC.charCodeAt(0) ||\n bytes[1] !== MAGIC.charCodeAt(1) ||\n bytes[2] !== MAGIC.charCodeAt(2) ||\n bytes[3] !== MAGIC.charCodeAt(3)\n ) {\n throw new Error('aiecsjs: invalid magic bytes')\n }\n let off = 4\n const formatVersion = view.getUint32(off, true)\n off += 4\n const onUnknown = options?.onUnknownVersion ?? 'throw'\n if (formatVersion !== FORMAT_VERSION && onUnknown === 'throw') {\n throw new Error(`aiecsjs: format version ${formatVersion} not supported`)\n }\n\n // SECURITY: explicit bounds checks on every length field. DataView itself\n // throws on out-of-range reads, but an attacker who controls the bytes can\n // still craft a `verLen` that skips past data of their choosing — we make\n // each step's invariant explicit and impose a sane cap to short-circuit\n // pathological payloads early.\n const MAX_FIELD_LEN = 64 * 1024 * 1024 // 64 MiB\n if (off + 4 > bytes.length) {\n throw new Error('aiecsjs: snapshot truncated before verLen')\n }\n const verLen = view.getUint32(off, true)\n off += 4\n if (verLen > MAX_FIELD_LEN || off + verLen > bytes.length) {\n throw new Error(`aiecsjs: snapshot verLen=${verLen} out of bounds`)\n }\n off += verLen // skip the aiecsjs version string\n\n if (off + 4 > bytes.length) {\n throw new Error('aiecsjs: snapshot truncated before jsonLen')\n }\n const jsonLen = view.getUint32(off, true)\n off += 4\n if (jsonLen > MAX_FIELD_LEN || off + jsonLen > bytes.length) {\n throw new Error(`aiecsjs: snapshot jsonLen=${jsonLen} out of bounds`)\n }\n const jsonBytes = bytes.subarray(off, off + jsonLen)\n const json = new TextDecoder().decode(jsonBytes)\n // 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) addComponent(targetWorld, eid, handle, comp.data as any)\n }\n }\n },\n reset(): void {\n state.lastSnapshot = null\n },\n }\n}\n\nfunction computeDelta(prev: WorldSnapshot, curr: WorldSnapshot): WorldSnapshot {\n const prevByEid = new Map(prev.entities.map((e) => [e.eid, e]))\n const changed: WorldSnapshot['entities'] = []\n for (const e of curr.entities) {\n const prevE = prevByEid.get(e.eid)\n if (!prevE) {\n changed.push(e)\n continue\n }\n const prevSig = JSON.stringify(prevE.components)\n const currSig = JSON.stringify(e.components)\n if (prevSig !== currSig) changed.push(e)\n }\n return { version: curr.version, capacity: curr.capacity, entities: changed }\n}\n"]}
package/dist/commands.cjs CHANGED
@@ -1,2 +1,2 @@
1
- 'use strict';var chunk7NNM4PGP_cjs=require('./chunk-7NNM4PGP.cjs');function l(n){let e={worldId:chunk7NNM4PGP_cjs.i(n).id,ops:[],nextPlaceholder:-1,flushing:false};return h(e)}function C(n){let o=y(n);if(!o.flushing){o.flushing=true;try{let e=B(o.worldId),r=new Map;for(let t of o.ops)t.kind==="create"&&r.set(t.placeholder,chunk7NNM4PGP_cjs.u(e));let d=t=>{let a=t;if(a<0){let f=r.get(a);if(f===void 0)throw new Error(`aiecsjs: unresolved placeholder ${a}`);return f}return t};for(let t of o.ops)t.kind==="add"?chunk7NNM4PGP_cjs.I(e,d(t.eid),t.component,t.initial):t.kind==="remove"&&chunk7NNM4PGP_cjs.J(e,d(t.eid),t.component);for(let t of o.ops)t.kind==="destroy"&&chunk7NNM4PGP_cjs.v(e,d(t.eid));o.ops.length=0,o.nextPlaceholder=-1;}finally{o.flushing=false;}}}function W(n,o){let e=l(n),r=o(e);return C(e),r}var p=new WeakMap;function h(n){let o={add(e,r,d){n.ops.push({kind:"add",eid:e,component:r,initial:d});},remove(e,r){n.ops.push({kind:"remove",eid:e,component:r});},destroy(e){n.ops.push({kind:"destroy",eid:e});},create(){let e=n.nextPlaceholder--;return n.ops.push({kind:"create",placeholder:e}),e}};return p.set(o,n),o}function y(n){let o=p.get(n);if(!o)throw new Error("aiecsjs: unknown CommandBuffer");return o}function B(n){let o=k(n);return {id:o.id,capacity:o.capacity,version:o.version}}function k(n){return chunk7NNM4PGP_cjs.i({id:n,capacity:0,version:"0.0.0"})}exports.createCommandBuffer=l;exports.flush=C;exports.withCommandBuffer=W;//# sourceMappingURL=commands.cjs.map
1
+ 'use strict';var chunk7O3CM4D2_cjs=require('./chunk-7O3CM4D2.cjs');function l(n){let e={worldId:chunk7O3CM4D2_cjs.i(n).id,ops:[],nextPlaceholder:-1,flushing:false};return h(e)}function C(n){let o=y(n);if(!o.flushing){o.flushing=true;try{let e=B(o.worldId),r=new Map;for(let t of o.ops)t.kind==="create"&&r.set(t.placeholder,chunk7O3CM4D2_cjs.u(e));let d=t=>{let a=t;if(a<0){let f=r.get(a);if(f===void 0)throw new Error(`aiecsjs: unresolved placeholder ${a}`);return f}return t};for(let t of o.ops)t.kind==="add"?chunk7O3CM4D2_cjs.J(e,d(t.eid),t.component,t.initial):t.kind==="remove"&&chunk7O3CM4D2_cjs.K(e,d(t.eid),t.component);for(let t of o.ops)t.kind==="destroy"&&chunk7O3CM4D2_cjs.w(e,d(t.eid));o.ops.length=0,o.nextPlaceholder=-1;}finally{o.flushing=false;}}}function W(n,o){let e=l(n),r=o(e);return C(e),r}var p=new WeakMap;function h(n){let o={add(e,r,d){n.ops.push({kind:"add",eid:e,component:r,initial:d});},remove(e,r){n.ops.push({kind:"remove",eid:e,component:r});},destroy(e){n.ops.push({kind:"destroy",eid:e});},create(){let e=n.nextPlaceholder--;return n.ops.push({kind:"create",placeholder:e}),e}};return p.set(o,n),o}function y(n){let o=p.get(n);if(!o)throw new Error("aiecsjs: unknown CommandBuffer");return o}function B(n){let o=k(n);return {id:o.id,capacity:o.capacity,version:o.version}}function k(n){return chunk7O3CM4D2_cjs.i({id:n,capacity:0,version:"0.0.0"})}exports.createCommandBuffer=l;exports.flush=C;exports.withCommandBuffer=W;//# sourceMappingURL=commands.cjs.map
2
2
  //# sourceMappingURL=commands.cjs.map
package/dist/commands.js CHANGED
@@ -1,2 +1,2 @@
1
- import {i,u,I,J,v}from'./chunk-YAHZHZNR.js';function l(n){let e={worldId:i(n).id,ops:[],nextPlaceholder:-1,flushing:false};return h(e)}function C(n){let o=y(n);if(!o.flushing){o.flushing=true;try{let e=B(o.worldId),r=new Map;for(let t of o.ops)t.kind==="create"&&r.set(t.placeholder,u(e));let d=t=>{let a=t;if(a<0){let f=r.get(a);if(f===void 0)throw new Error(`aiecsjs: unresolved placeholder ${a}`);return f}return t};for(let t of o.ops)t.kind==="add"?I(e,d(t.eid),t.component,t.initial):t.kind==="remove"&&J(e,d(t.eid),t.component);for(let t of o.ops)t.kind==="destroy"&&v(e,d(t.eid));o.ops.length=0,o.nextPlaceholder=-1;}finally{o.flushing=false;}}}function W(n,o){let e=l(n),r=o(e);return C(e),r}var p=new WeakMap;function h(n){let o={add(e,r,d){n.ops.push({kind:"add",eid:e,component:r,initial:d});},remove(e,r){n.ops.push({kind:"remove",eid:e,component:r});},destroy(e){n.ops.push({kind:"destroy",eid:e});},create(){let e=n.nextPlaceholder--;return n.ops.push({kind:"create",placeholder:e}),e}};return p.set(o,n),o}function y(n){let o=p.get(n);if(!o)throw new Error("aiecsjs: unknown CommandBuffer");return o}function B(n){let o=k(n);return {id:o.id,capacity:o.capacity,version:o.version}}function k(n){return i({id:n,capacity:0,version:"0.0.0"})}export{l as createCommandBuffer,C as flush,W as withCommandBuffer};//# sourceMappingURL=commands.js.map
1
+ import {i,u,J,K,w}from'./chunk-BUFJWGRQ.js';function l(n){let e={worldId:i(n).id,ops:[],nextPlaceholder:-1,flushing:false};return h(e)}function C(n){let o=y(n);if(!o.flushing){o.flushing=true;try{let e=B(o.worldId),r=new Map;for(let t of o.ops)t.kind==="create"&&r.set(t.placeholder,u(e));let d=t=>{let a=t;if(a<0){let f=r.get(a);if(f===void 0)throw new Error(`aiecsjs: unresolved placeholder ${a}`);return f}return t};for(let t of o.ops)t.kind==="add"?J(e,d(t.eid),t.component,t.initial):t.kind==="remove"&&K(e,d(t.eid),t.component);for(let t of o.ops)t.kind==="destroy"&&w(e,d(t.eid));o.ops.length=0,o.nextPlaceholder=-1;}finally{o.flushing=false;}}}function W(n,o){let e=l(n),r=o(e);return C(e),r}var p=new WeakMap;function h(n){let o={add(e,r,d){n.ops.push({kind:"add",eid:e,component:r,initial:d});},remove(e,r){n.ops.push({kind:"remove",eid:e,component:r});},destroy(e){n.ops.push({kind:"destroy",eid:e});},create(){let e=n.nextPlaceholder--;return n.ops.push({kind:"create",placeholder:e}),e}};return p.set(o,n),o}function y(n){let o=p.get(n);if(!o)throw new Error("aiecsjs: unknown CommandBuffer");return o}function B(n){let o=k(n);return {id:o.id,capacity:o.capacity,version:o.version}}function k(n){return i({id:n,capacity:0,version:"0.0.0"})}export{l as createCommandBuffer,C as flush,W as withCommandBuffer};//# sourceMappingURL=commands.js.map
2
2
  //# sourceMappingURL=commands.js.map
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- 'use strict';var chunk2CF2MNMH_cjs=require('./chunk-2CF2MNMH.cjs'),chunk7NNM4PGP_cjs=require('./chunk-7NNM4PGP.cjs');var K={i8:"i8",u8:"u8",i16:"i16",u16:"u16",i32:"i32",u32:"u32",f32:"f32",f64:"f64",eid:"eid",bool:"bool"};function $(...n){return n.length===0?e=>e:n.length===1?n[0]:(e,r)=>{let t=e;for(let o of n)t=o(t,r);return t}}var i=class extends Error{eid;constructor(e){super(`aiecsjs: entity ${e} is not alive`),this.name="EntityNotAliveError",this.eid=e;}};function J(n,e){let r=chunk7NNM4PGP_cjs.i(n);if(!chunk7NNM4PGP_cjs.x(r,e))throw new i(e);return Object.freeze({id:e,worldId:r.id})}function b(n,e){let r=chunk7NNM4PGP_cjs.i(n);if(e.worldId!==r.id)return null;let t=e.id,o=chunk7NNM4PGP_cjs.s(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=chunk7NNM4PGP_cjs.t(t,r.options);return C!==A?null:e.id}function X(n,e){return b(n,e)!==null}chunk2CF2MNMH_cjs.i(n=>chunk7NNM4PGP_cjs.P(n));chunk7NNM4PGP_cjs.N((n,e,r,t,o)=>{chunk2CF2MNMH_cjs.h(n,e,r,t,o);});var ae=typeof SharedArrayBuffer<"u";Object.defineProperty(exports,"defineQuery",{enumerable:true,get:function(){return chunk2CF2MNMH_cjs.a}});Object.defineProperty(exports,"enterQuery",{enumerable:true,get:function(){return chunk2CF2MNMH_cjs.b}});Object.defineProperty(exports,"exitQuery",{enumerable:true,get:function(){return chunk2CF2MNMH_cjs.c}});Object.defineProperty(exports,"forEachEntity",{enumerable:true,get:function(){return chunk2CF2MNMH_cjs.g}});Object.defineProperty(exports,"iterQuery",{enumerable:true,get:function(){return chunk2CF2MNMH_cjs.f}});Object.defineProperty(exports,"queryArchetypes",{enumerable:true,get:function(){return chunk2CF2MNMH_cjs.d}});Object.defineProperty(exports,"runQuery",{enumerable:true,get:function(){return chunk2CF2MNMH_cjs.e}});Object.defineProperty(exports,"VERSION",{enumerable:true,get:function(){return chunk7NNM4PGP_cjs.a}});Object.defineProperty(exports,"addComponent",{enumerable:true,get:function(){return chunk7NNM4PGP_cjs.I}});Object.defineProperty(exports,"createEntity",{enumerable:true,get:function(){return chunk7NNM4PGP_cjs.u}});Object.defineProperty(exports,"createWorld",{enumerable:true,get:function(){return chunk7NNM4PGP_cjs.k}});Object.defineProperty(exports,"defineComponent",{enumerable:true,get:function(){return chunk7NNM4PGP_cjs.E}});Object.defineProperty(exports,"defineObjectComponent",{enumerable:true,get:function(){return chunk7NNM4PGP_cjs.G}});Object.defineProperty(exports,"defineTag",{enumerable:true,get:function(){return chunk7NNM4PGP_cjs.F}});Object.defineProperty(exports,"destroyEntity",{enumerable:true,get:function(){return chunk7NNM4PGP_cjs.v}});Object.defineProperty(exports,"destroyWorld",{enumerable:true,get:function(){return chunk7NNM4PGP_cjs.l}});Object.defineProperty(exports,"disposeWorld",{enumerable:true,get:function(){return chunk7NNM4PGP_cjs.l}});Object.defineProperty(exports,"entityExists",{enumerable:true,get:function(){return chunk7NNM4PGP_cjs.w}});Object.defineProperty(exports,"getComponent",{enumerable:true,get:function(){return chunk7NNM4PGP_cjs.L}});Object.defineProperty(exports,"getEntityGeneration",{enumerable:true,get:function(){return chunk7NNM4PGP_cjs.z}});Object.defineProperty(exports,"getEntityIndex",{enumerable:true,get:function(){return chunk7NNM4PGP_cjs.y}});Object.defineProperty(exports,"getWorldCapacity",{enumerable:true,get:function(){return chunk7NNM4PGP_cjs.o}});Object.defineProperty(exports,"getWorldSize",{enumerable:true,get:function(){return chunk7NNM4PGP_cjs.n}});Object.defineProperty(exports,"hasComponent",{enumerable:true,get:function(){return chunk7NNM4PGP_cjs.K}});Object.defineProperty(exports,"isEntity",{enumerable:true,get:function(){return chunk7NNM4PGP_cjs.B}});Object.defineProperty(exports,"isWorld",{enumerable:true,get:function(){return chunk7NNM4PGP_cjs.q}});Object.defineProperty(exports,"packEntity",{enumerable:true,get:function(){return chunk7NNM4PGP_cjs.A}});Object.defineProperty(exports,"removeComponent",{enumerable:true,get:function(){return chunk7NNM4PGP_cjs.J}});Object.defineProperty(exports,"resetWorld",{enumerable:true,get:function(){return chunk7NNM4PGP_cjs.m}});Object.defineProperty(exports,"setComponent",{enumerable:true,get:function(){return chunk7NNM4PGP_cjs.M}});exports.EntityNotAliveError=i;exports.IS_SAB_SUPPORTED=ae;exports.Types=K;exports.aliveRef=X;exports.deref=b;exports.pipe=$;exports.refOf=J;//# sourceMappingURL=index.cjs.map
1
+ 'use strict';var chunkI726BP65_cjs=require('./chunk-I726BP65.cjs'),chunk7O3CM4D2_cjs=require('./chunk-7O3CM4D2.cjs');var K={i8:"i8",u8:"u8",i16:"i16",u16:"u16",i32:"i32",u32:"u32",f32:"f32",f64:"f64",eid:"eid",bool:"bool"};function $(...n){return n.length===0?e=>e:n.length===1?n[0]:(e,r)=>{let t=e;for(let o of n)t=o(t,r);return t}}var i=class extends Error{eid;constructor(e){super(`aiecsjs: entity ${e} is not alive`),this.name="EntityNotAliveError",this.eid=e;}};function J(n,e){let r=chunk7O3CM4D2_cjs.i(n);if(!chunk7O3CM4D2_cjs.y(r,e))throw new i(e);return Object.freeze({id:e,worldId:r.id})}function b(n,e){let r=chunk7O3CM4D2_cjs.i(n);if(e.worldId!==r.id)return null;let t=e.id,o=chunk7O3CM4D2_cjs.s(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=chunk7O3CM4D2_cjs.t(t,r.options);return C!==A?null:e.id}function X(n,e){return b(n,e)!==null}chunkI726BP65_cjs.i(n=>chunk7O3CM4D2_cjs.Q(n));chunk7O3CM4D2_cjs.O((n,e,r,t,o)=>{chunkI726BP65_cjs.h(n,e,r,t,o);});var ae=typeof SharedArrayBuffer<"u";Object.defineProperty(exports,"defineQuery",{enumerable:true,get:function(){return chunkI726BP65_cjs.a}});Object.defineProperty(exports,"enterQuery",{enumerable:true,get:function(){return chunkI726BP65_cjs.b}});Object.defineProperty(exports,"exitQuery",{enumerable:true,get:function(){return chunkI726BP65_cjs.c}});Object.defineProperty(exports,"forEachEntity",{enumerable:true,get:function(){return chunkI726BP65_cjs.g}});Object.defineProperty(exports,"iterQuery",{enumerable:true,get:function(){return chunkI726BP65_cjs.f}});Object.defineProperty(exports,"queryArchetypes",{enumerable:true,get:function(){return chunkI726BP65_cjs.d}});Object.defineProperty(exports,"runQuery",{enumerable:true,get:function(){return chunkI726BP65_cjs.e}});Object.defineProperty(exports,"VERSION",{enumerable:true,get:function(){return chunk7O3CM4D2_cjs.a}});Object.defineProperty(exports,"addComponent",{enumerable:true,get:function(){return chunk7O3CM4D2_cjs.J}});Object.defineProperty(exports,"createEntity",{enumerable:true,get:function(){return chunk7O3CM4D2_cjs.u}});Object.defineProperty(exports,"createWorld",{enumerable:true,get:function(){return chunk7O3CM4D2_cjs.k}});Object.defineProperty(exports,"defineComponent",{enumerable:true,get:function(){return chunk7O3CM4D2_cjs.F}});Object.defineProperty(exports,"defineObjectComponent",{enumerable:true,get:function(){return chunk7O3CM4D2_cjs.H}});Object.defineProperty(exports,"defineTag",{enumerable:true,get:function(){return chunk7O3CM4D2_cjs.G}});Object.defineProperty(exports,"destroyEntity",{enumerable:true,get:function(){return chunk7O3CM4D2_cjs.w}});Object.defineProperty(exports,"destroyWorld",{enumerable:true,get:function(){return chunk7O3CM4D2_cjs.l}});Object.defineProperty(exports,"disposeWorld",{enumerable:true,get:function(){return chunk7O3CM4D2_cjs.l}});Object.defineProperty(exports,"entityExists",{enumerable:true,get:function(){return chunk7O3CM4D2_cjs.x}});Object.defineProperty(exports,"getComponent",{enumerable:true,get:function(){return chunk7O3CM4D2_cjs.M}});Object.defineProperty(exports,"getEntityGeneration",{enumerable:true,get:function(){return chunk7O3CM4D2_cjs.A}});Object.defineProperty(exports,"getEntityIndex",{enumerable:true,get:function(){return chunk7O3CM4D2_cjs.z}});Object.defineProperty(exports,"getWorldCapacity",{enumerable:true,get:function(){return chunk7O3CM4D2_cjs.o}});Object.defineProperty(exports,"getWorldSize",{enumerable:true,get:function(){return chunk7O3CM4D2_cjs.n}});Object.defineProperty(exports,"hasComponent",{enumerable:true,get:function(){return chunk7O3CM4D2_cjs.L}});Object.defineProperty(exports,"isEntity",{enumerable:true,get:function(){return chunk7O3CM4D2_cjs.C}});Object.defineProperty(exports,"isWorld",{enumerable:true,get:function(){return chunk7O3CM4D2_cjs.q}});Object.defineProperty(exports,"packEntity",{enumerable:true,get:function(){return chunk7O3CM4D2_cjs.B}});Object.defineProperty(exports,"removeComponent",{enumerable:true,get:function(){return chunk7O3CM4D2_cjs.K}});Object.defineProperty(exports,"resetWorld",{enumerable:true,get:function(){return chunk7O3CM4D2_cjs.m}});Object.defineProperty(exports,"setComponent",{enumerable:true,get:function(){return chunk7O3CM4D2_cjs.N}});exports.EntityNotAliveError=i;exports.IS_SAB_SUPPORTED=ae;exports.Types=K;exports.aliveRef=X;exports.deref=b;exports.pipe=$;exports.refOf=J;//# sourceMappingURL=index.cjs.map
2
2
  //# sourceMappingURL=index.cjs.map
package/dist/index.d.cts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { o as WorldOptions, W as World, E as EntityId, c as ComponentLike, b as ComponentInit, k as SoASchema, h as SoAComponent, A as AoSComponent, T as TagComponent, f as QueryDescriptor, Q as Query, a as Archetype, l as System } from './types-BGEeHad-.cjs';
2
2
  export { d as ComponentView, g as SoAColumns, i as SoAFieldDecl, j as SoAFieldType, n as Types } from './types-BGEeHad-.cjs';
3
3
 
4
- declare const VERSION = "0.4.1";
4
+ declare const VERSION = "0.5.1";
5
5
 
6
6
  declare function createWorld(options?: WorldOptions): World;
7
7
  declare function destroyWorld(world: World): void;
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { o as WorldOptions, W as World, E as EntityId, c as ComponentLike, b as ComponentInit, k as SoASchema, h as SoAComponent, A as AoSComponent, T as TagComponent, f as QueryDescriptor, Q as Query, a as Archetype, l as System } from './types-BGEeHad-.js';
2
2
  export { d as ComponentView, g as SoAColumns, i as SoAFieldDecl, j as SoAFieldType, n as Types } from './types-BGEeHad-.js';
3
3
 
4
- declare const VERSION = "0.4.1";
4
+ declare const VERSION = "0.5.1";
5
5
 
6
6
  declare function createWorld(options?: WorldOptions): World;
7
7
  declare function destroyWorld(world: World): void;
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import {i as i$1,h}from'./chunk-ZNLOJVCV.js';export{a as defineQuery,b as enterQuery,c as exitQuery,g as forEachEntity,f as iterQuery,d as queryArchetypes,e as runQuery}from'./chunk-ZNLOJVCV.js';import {P,N,i as i$2,x,s,t}from'./chunk-YAHZHZNR.js';export{a as VERSION,I as addComponent,u as createEntity,k as createWorld,E as defineComponent,G as defineObjectComponent,F as defineTag,v as destroyEntity,l as destroyWorld,l as disposeWorld,w as entityExists,L as getComponent,z as getEntityGeneration,y as getEntityIndex,o as getWorldCapacity,n as getWorldSize,K as hasComponent,B as isEntity,q as isWorld,A as packEntity,J as removeComponent,m as resetWorld,M as setComponent}from'./chunk-YAHZHZNR.js';var K={i8:"i8",u8:"u8",i16:"i16",u16:"u16",i32:"i32",u32:"u32",f32:"f32",f64:"f64",eid:"eid",bool:"bool"};function $(...n){return n.length===0?e=>e:n.length===1?n[0]:(e,r)=>{let t=e;for(let o of n)t=o(t,r);return t}}var i=class extends Error{eid;constructor(e){super(`aiecsjs: entity ${e} is not alive`),this.name="EntityNotAliveError",this.eid=e;}};function J(n,e){let r=i$2(n);if(!x(r,e))throw new i(e);return Object.freeze({id:e,worldId:r.id})}function b(n,e){let r=i$2(n);if(e.worldId!==r.id)return null;let t$1=e.id,o=s(t$1,r.options);if(o<=0||o>=r.capacity)return null;let x=r.entityArchetype[o]??0,d=r.archetypes[x];if(!d||!d.entityRow.has(e.id))return null;let C=r.generations[o]??0,A=t(t$1,r.options);return C!==A?null:e.id}function X(n,e){return b(n,e)!==null}i$1(n=>P(n));N((n,e,r,t,o)=>{h(n,e,r,t,o);});var ae=typeof SharedArrayBuffer<"u";export{i as EntityNotAliveError,ae as IS_SAB_SUPPORTED,K as Types,X as aliveRef,b as deref,$ as pipe,J as refOf};//# sourceMappingURL=index.js.map
1
+ import {i as i$1,h}from'./chunk-LU55S4LK.js';export{a as defineQuery,b as enterQuery,c as exitQuery,g as forEachEntity,f as iterQuery,d as queryArchetypes,e as runQuery}from'./chunk-LU55S4LK.js';import {Q,O,i as i$2,y,s,t}from'./chunk-BUFJWGRQ.js';export{a as VERSION,J as addComponent,u as createEntity,k as createWorld,F as defineComponent,H as defineObjectComponent,G as defineTag,w as destroyEntity,l as destroyWorld,l as disposeWorld,x as entityExists,M as getComponent,A as getEntityGeneration,z as getEntityIndex,o as getWorldCapacity,n as getWorldSize,L as hasComponent,C as isEntity,q as isWorld,B as packEntity,K as removeComponent,m as resetWorld,N as setComponent}from'./chunk-BUFJWGRQ.js';var K={i8:"i8",u8:"u8",i16:"i16",u16:"u16",i32:"i32",u32:"u32",f32:"f32",f64:"f64",eid:"eid",bool:"bool"};function $(...n){return n.length===0?e=>e:n.length===1?n[0]:(e,r)=>{let t=e;for(let o of n)t=o(t,r);return t}}var i=class extends Error{eid;constructor(e){super(`aiecsjs: entity ${e} is not alive`),this.name="EntityNotAliveError",this.eid=e;}};function J(n,e){let r=i$2(n);if(!y(r,e))throw new i(e);return Object.freeze({id:e,worldId:r.id})}function b(n,e){let r=i$2(n);if(e.worldId!==r.id)return null;let t$1=e.id,o=s(t$1,r.options);if(o<=0||o>=r.capacity)return null;let x=r.entityArchetype[o]??0,d=r.archetypes[x];if(!d||!d.entityRow.has(e.id))return null;let C=r.generations[o]??0,A=t(t$1,r.options);return C!==A?null:e.id}function X(n,e){return b(n,e)!==null}i$1(n=>Q(n));O((n,e,r,t,o)=>{h(n,e,r,t,o);});var ae=typeof SharedArrayBuffer<"u";export{i as EntityNotAliveError,ae as IS_SAB_SUPPORTED,K as Types,X as aliveRef,b as deref,$ as pipe,J as refOf};//# sourceMappingURL=index.js.map
2
2
  //# sourceMappingURL=index.js.map
@@ -1,2 +1,2 @@
1
- 'use strict';var chunk2CF2MNMH_cjs=require('./chunk-2CF2MNMH.cjs'),chunk7NNM4PGP_cjs=require('./chunk-7NNM4PGP.cjs');function f(n,e){if(!e)return n;if(e.aborted)return n(),()=>{};let o=()=>{n();};e.addEventListener("abort",o,{once:true});let t=false;return ()=>{t||(t=true,e.removeEventListener("abort",o),n());}}function w(n,e,o,t){return f(b(n,e,"add",o),t?.signal)}function x(n,e,o,t){return f(b(n,e,"remove",o),t?.signal)}function C(n,e,o,t){return f(b(n,e,"set",o),t?.signal)}function L(n,e,o,t,r){let s=chunk7NNM4PGP_cjs.i(n);chunk2CF2MNMH_cjs.e(n,e);let i={event:o,componentBit:-1,queryId:e.id,handler:t};return s.observers.push(i),f(()=>{let d=s.observers.indexOf(i);d>=0&&s.observers.splice(d,1);},r?.signal)}function b(n,e,o,t){let r=chunk7NNM4PGP_cjs.i(n),s=chunk7NNM4PGP_cjs.H(e),i=r.componentBitFor.get(s.id);i===void 0&&(i=chunk7NNM4PGP_cjs.p(r,s));let u={event:o,componentBit:i,queryId:-1,handler:t};return r.observers.push(u),()=>{let d=r.observers.indexOf(u);d>=0&&r.observers.splice(d,1);}}function E(n,e,o){let t=Array.from(n.observers);for(let r of t)r.event==="add"&&r.componentBit===o&&n.observers.includes(r)&&r.handler(e);O(n,e,"add");}function M(n,e,o){let t=Array.from(n.observers);for(let r of t)r.event==="remove"&&r.componentBit===o&&n.observers.includes(r)&&r.handler(e);O(n,e,"remove");}function g(n,e,o,t){let r=Array.from(n.observers);for(let s of r)s.event==="set"&&n.observers.includes(s)&&(s.componentBit===o||s.queryId!==-1&&n.queries[s.queryId]?.all.includes(n.componentInfoByBit[o]?.id??-1))&&s.handler(e,t);}function O(n,e,o,t,r){let s=n.options.maskWordCount,i=(e&n.options.indexMask)*s,u=Array.from(n.observers);for(let d of u){if(d.event!==o||d.queryId===-1||!n.observers.includes(d))continue;let c=n.queryMasks.get(d.queryId);if(!c)continue;let l=chunk7NNM4PGP_cjs.h(n.entityMask,i,s,c.withMask,c.anyMask,c.noneMask,c.anyHasBits);o==="add"&&l&&d.handler(e),o==="remove"&&!l&&d.handler(e);}}chunk7NNM4PGP_cjs.O({fireAdd:E,fireRemove:M,fireSet:g});chunk7NNM4PGP_cjs.C({dispatchDestroyObservers(n,e){let o=n.options.maskWordCount,t=(e&n.options.indexMask)*o,r=new Uint32Array(o);for(let i=0;i<o;i++)r[i]=n.entityMask[t+i]??0;chunk7NNM4PGP_cjs.g(r,0,o,i=>{let u=Array.from(n.observers);for(let d of u)d.event==="remove"&&d.componentBit===i&&n.observers.includes(d)&&d.handler(e);});let s=Array.from(n.observers);for(let i of s){if(i.event!=="remove"||i.queryId===-1||!n.observers.includes(i))continue;let u=n.queryMasks.get(i.queryId);if(!u)continue;chunk7NNM4PGP_cjs.h(r,0,o,u.withMask,u.anyMask,u.noneMask,u.anyHasBits)&&i.handler(e);}}});exports.observe=L;exports.onAdd=w;exports.onRemove=x;exports.onSet=C;//# sourceMappingURL=observers.cjs.map
1
+ 'use strict';var chunkI726BP65_cjs=require('./chunk-I726BP65.cjs'),chunk7O3CM4D2_cjs=require('./chunk-7O3CM4D2.cjs');function f(n,e){if(!e)return n;if(e.aborted)return n(),()=>{};let o=()=>{n();};e.addEventListener("abort",o,{once:true});let t=false;return ()=>{t||(t=true,e.removeEventListener("abort",o),n());}}function w(n,e,o,t){return f(b(n,e,"add",o),t?.signal)}function x(n,e,o,t){return f(b(n,e,"remove",o),t?.signal)}function C(n,e,o,t){return f(b(n,e,"set",o),t?.signal)}function L(n,e,o,t,r){let s=chunk7O3CM4D2_cjs.i(n);chunkI726BP65_cjs.e(n,e);let i={event:o,componentBit:-1,queryId:e.id,handler:t};return s.observers.push(i),f(()=>{let d=s.observers.indexOf(i);d>=0&&s.observers.splice(d,1);},r?.signal)}function b(n,e,o,t){let r=chunk7O3CM4D2_cjs.i(n),s=chunk7O3CM4D2_cjs.I(e),i=r.componentBitFor.get(s.id);i===void 0&&(i=chunk7O3CM4D2_cjs.p(r,s));let u={event:o,componentBit:i,queryId:-1,handler:t};return r.observers.push(u),()=>{let d=r.observers.indexOf(u);d>=0&&r.observers.splice(d,1);}}function E(n,e,o){let t=Array.from(n.observers);for(let r of t)r.event==="add"&&r.componentBit===o&&n.observers.includes(r)&&r.handler(e);O(n,e,"add");}function M(n,e,o){let t=Array.from(n.observers);for(let r of t)r.event==="remove"&&r.componentBit===o&&n.observers.includes(r)&&r.handler(e);O(n,e,"remove");}function g(n,e,o,t){let r=Array.from(n.observers);for(let s of r)s.event==="set"&&n.observers.includes(s)&&(s.componentBit===o||s.queryId!==-1&&n.queries[s.queryId]?.all.includes(n.componentInfoByBit[o]?.id??-1))&&s.handler(e,t);}function O(n,e,o,t,r){let s=n.options.maskWordCount,i=(e&n.options.indexMask)*s,u=Array.from(n.observers);for(let d of u){if(d.event!==o||d.queryId===-1||!n.observers.includes(d))continue;let c=n.queryMasks.get(d.queryId);if(!c)continue;let l=chunk7O3CM4D2_cjs.h(n.entityMask,i,s,c.withMask,c.anyMask,c.noneMask,c.anyHasBits);o==="add"&&l&&d.handler(e),o==="remove"&&!l&&d.handler(e);}}chunk7O3CM4D2_cjs.P({fireAdd:E,fireRemove:M,fireSet:g});chunk7O3CM4D2_cjs.D({dispatchDestroyObservers(n,e){let o=n.options.maskWordCount,t=(e&n.options.indexMask)*o,r=new Uint32Array(o);for(let i=0;i<o;i++)r[i]=n.entityMask[t+i]??0;chunk7O3CM4D2_cjs.g(r,0,o,i=>{let u=Array.from(n.observers);for(let d of u)d.event==="remove"&&d.componentBit===i&&n.observers.includes(d)&&d.handler(e);});let s=Array.from(n.observers);for(let i of s){if(i.event!=="remove"||i.queryId===-1||!n.observers.includes(i))continue;let u=n.queryMasks.get(i.queryId);if(!u)continue;chunk7O3CM4D2_cjs.h(r,0,o,u.withMask,u.anyMask,u.noneMask,u.anyHasBits)&&i.handler(e);}}});exports.observe=L;exports.onAdd=w;exports.onRemove=x;exports.onSet=C;//# sourceMappingURL=observers.cjs.map
2
2
  //# sourceMappingURL=observers.cjs.map
package/dist/observers.js CHANGED
@@ -1,2 +1,2 @@
1
- import {e}from'./chunk-ZNLOJVCV.js';import {O as O$1,C as C$1,g as g$1,h,i,H,p}from'./chunk-YAHZHZNR.js';function f(n,e){if(!e)return n;if(e.aborted)return n(),()=>{};let o=()=>{n();};e.addEventListener("abort",o,{once:true});let t=false;return ()=>{t||(t=true,e.removeEventListener("abort",o),n());}}function w(n,e,o,t){return f(b(n,e,"add",o),t?.signal)}function x(n,e,o,t){return f(b(n,e,"remove",o),t?.signal)}function C(n,e,o,t){return f(b(n,e,"set",o),t?.signal)}function L(n,e$1,o,t,r){let s=i(n);e(n,e$1);let i$1={event:o,componentBit:-1,queryId:e$1.id,handler:t};return s.observers.push(i$1),f(()=>{let d=s.observers.indexOf(i$1);d>=0&&s.observers.splice(d,1);},r?.signal)}function b(n,e,o,t){let r=i(n),s=H(e),i$1=r.componentBitFor.get(s.id);i$1===void 0&&(i$1=p(r,s));let u={event:o,componentBit:i$1,queryId:-1,handler:t};return r.observers.push(u),()=>{let d=r.observers.indexOf(u);d>=0&&r.observers.splice(d,1);}}function E(n,e,o){let t=Array.from(n.observers);for(let r of t)r.event==="add"&&r.componentBit===o&&n.observers.includes(r)&&r.handler(e);O(n,e,"add");}function M(n,e,o){let t=Array.from(n.observers);for(let r of t)r.event==="remove"&&r.componentBit===o&&n.observers.includes(r)&&r.handler(e);O(n,e,"remove");}function g(n,e,o,t){let r=Array.from(n.observers);for(let s of r)s.event==="set"&&n.observers.includes(s)&&(s.componentBit===o||s.queryId!==-1&&n.queries[s.queryId]?.all.includes(n.componentInfoByBit[o]?.id??-1))&&s.handler(e,t);}function O(n,e,o,t,r){let s=n.options.maskWordCount,i=(e&n.options.indexMask)*s,u=Array.from(n.observers);for(let d of u){if(d.event!==o||d.queryId===-1||!n.observers.includes(d))continue;let c=n.queryMasks.get(d.queryId);if(!c)continue;let l=h(n.entityMask,i,s,c.withMask,c.anyMask,c.noneMask,c.anyHasBits);o==="add"&&l&&d.handler(e),o==="remove"&&!l&&d.handler(e);}}O$1({fireAdd:E,fireRemove:M,fireSet:g});C$1({dispatchDestroyObservers(n,e){let o=n.options.maskWordCount,t=(e&n.options.indexMask)*o,r=new Uint32Array(o);for(let i=0;i<o;i++)r[i]=n.entityMask[t+i]??0;g$1(r,0,o,i=>{let u=Array.from(n.observers);for(let d of u)d.event==="remove"&&d.componentBit===i&&n.observers.includes(d)&&d.handler(e);});let s=Array.from(n.observers);for(let i of s){if(i.event!=="remove"||i.queryId===-1||!n.observers.includes(i))continue;let u=n.queryMasks.get(i.queryId);if(!u)continue;h(r,0,o,u.withMask,u.anyMask,u.noneMask,u.anyHasBits)&&i.handler(e);}}});export{L as observe,w as onAdd,x as onRemove,C as onSet};//# sourceMappingURL=observers.js.map
1
+ import {e}from'./chunk-LU55S4LK.js';import {P,D,g as g$1,h,i,I,p}from'./chunk-BUFJWGRQ.js';function f(n,e){if(!e)return n;if(e.aborted)return n(),()=>{};let o=()=>{n();};e.addEventListener("abort",o,{once:true});let t=false;return ()=>{t||(t=true,e.removeEventListener("abort",o),n());}}function w(n,e,o,t){return f(b(n,e,"add",o),t?.signal)}function x(n,e,o,t){return f(b(n,e,"remove",o),t?.signal)}function C(n,e,o,t){return f(b(n,e,"set",o),t?.signal)}function L(n,e$1,o,t,r){let s=i(n);e(n,e$1);let i$1={event:o,componentBit:-1,queryId:e$1.id,handler:t};return s.observers.push(i$1),f(()=>{let d=s.observers.indexOf(i$1);d>=0&&s.observers.splice(d,1);},r?.signal)}function b(n,e,o,t){let r=i(n),s=I(e),i$1=r.componentBitFor.get(s.id);i$1===void 0&&(i$1=p(r,s));let u={event:o,componentBit:i$1,queryId:-1,handler:t};return r.observers.push(u),()=>{let d=r.observers.indexOf(u);d>=0&&r.observers.splice(d,1);}}function E(n,e,o){let t=Array.from(n.observers);for(let r of t)r.event==="add"&&r.componentBit===o&&n.observers.includes(r)&&r.handler(e);O(n,e,"add");}function M(n,e,o){let t=Array.from(n.observers);for(let r of t)r.event==="remove"&&r.componentBit===o&&n.observers.includes(r)&&r.handler(e);O(n,e,"remove");}function g(n,e,o,t){let r=Array.from(n.observers);for(let s of r)s.event==="set"&&n.observers.includes(s)&&(s.componentBit===o||s.queryId!==-1&&n.queries[s.queryId]?.all.includes(n.componentInfoByBit[o]?.id??-1))&&s.handler(e,t);}function O(n,e,o,t,r){let s=n.options.maskWordCount,i=(e&n.options.indexMask)*s,u=Array.from(n.observers);for(let d of u){if(d.event!==o||d.queryId===-1||!n.observers.includes(d))continue;let c=n.queryMasks.get(d.queryId);if(!c)continue;let l=h(n.entityMask,i,s,c.withMask,c.anyMask,c.noneMask,c.anyHasBits);o==="add"&&l&&d.handler(e),o==="remove"&&!l&&d.handler(e);}}P({fireAdd:E,fireRemove:M,fireSet:g});D({dispatchDestroyObservers(n,e){let o=n.options.maskWordCount,t=(e&n.options.indexMask)*o,r=new Uint32Array(o);for(let i=0;i<o;i++)r[i]=n.entityMask[t+i]??0;g$1(r,0,o,i=>{let u=Array.from(n.observers);for(let d of u)d.event==="remove"&&d.componentBit===i&&n.observers.includes(d)&&d.handler(e);});let s=Array.from(n.observers);for(let i of s){if(i.event!=="remove"||i.queryId===-1||!n.observers.includes(i))continue;let u=n.queryMasks.get(i.queryId);if(!u)continue;h(r,0,o,u.withMask,u.anyMask,u.noneMask,u.anyHasBits)&&i.handler(e);}}});export{L as observe,w as onAdd,x as onRemove,C as onSet};//# sourceMappingURL=observers.js.map
2
2
  //# sourceMappingURL=observers.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/observers.ts"],"names":["bindAbortSignal","unsubscribe","signal","onAbort","detached","onAdd","world","component","handler","opts","registerComponentObserver","onRemove","onSet","observe","query","event","state","getWorldState","runQuery","entry","idx","info","getComponentInfo","bit","getOrRegisterComponentBit","fireAdd","eid","snapshot","obs","dispatchQueryObservers","fireRemove","fireSet","value","_prev","_current","w","base","bundle","isMatch","matchesEntityMask","registerObserverDispatch","registerObserversAPI","preMask","forEachSetBit","querySnapshot"],"mappings":"yGA0BA,SAASA,CAAAA,CAAgBC,CAAAA,CAAyBC,CAAAA,CAA6C,CAC7F,GAAI,CAACA,CAAAA,CAAQ,OAAOD,CAAAA,CACpB,GAAIC,CAAAA,CAAO,OAAA,CACT,OAAAD,GAAY,CACL,IAAM,CAAC,CAAA,CAEhB,IAAME,CAAAA,CAAU,IAAY,CAC1BF,IACF,CAAA,CACAC,CAAAA,CAAO,gBAAA,CAAiB,QAASC,CAAAA,CAAS,CAAE,IAAA,CAAM,IAAK,CAAC,CAAA,CACxD,IAAIC,CAAAA,CAAW,KAAA,CACf,OAAO,IAAM,CACPA,CAAAA,GACJA,EAAW,IAAA,CACXF,CAAAA,CAAO,mBAAA,CAAoB,OAAA,CAASC,CAAO,CAAA,CAC3CF,CAAAA,EAAY,EACd,CACF,CAEO,SAASI,CAAAA,CACdC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACY,CACZ,OAAOT,CAAAA,CAAgBU,CAAAA,CAA0BJ,CAAAA,CAAOC,CAAAA,CAAW,MAAOC,CAAO,CAAA,CAAGC,CAAAA,EAAM,MAAM,CAClG,CAEO,SAASE,CAAAA,CACdL,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACY,CACZ,OAAOT,CAAAA,CACLU,CAAAA,CAA0BJ,CAAAA,CAAOC,CAAAA,CAAW,QAAA,CAAUC,CAAO,CAAA,CAC7DC,CAAAA,EAAM,MACR,CACF,CAyBO,SAASG,CAA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CAAAA,CAAI,QAAU,QAAA,EACdA,CAAAA,CAAI,OAAA,GAAY,EAAA,EAChB,CAACZ,CAAAA,CAAM,SAAA,CAAU,QAAA,CAASY,CAAG,CAAA,CAAG,SACpC,IAAMS,CAAAA,CAASrB,EAAM,UAAA,CAAW,GAAA,CAAIY,CAAAA,CAAI,OAAO,CAAA,CAC/C,GAAI,CAACS,CAAAA,CAAQ,SACIE,CAAAA,CACfG,CAAAA,CACA,CAAA,CACAP,CAAAA,CACAE,CAAAA,CAAO,QAAA,CACPA,CAAAA,CAAO,OAAA,CACPA,EAAO,QAAA,CACPA,CAAAA,CAAO,UACT,CAAA,EACcT,EAAI,OAAA,CAAQF,CAAG,EAC/B,CACF,CACF,CAAC,CAAA","file":"observers.js","sourcesContent":["// aiecsjs/observers — observe component add/remove/set events.\n\nimport { forEachSetBit, matchesEntityMask } from './internal/bitmask.js'\nimport { getComponentInfo, registerObserverDispatch } from './internal/component.js'\nimport { registerObserversAPI } from './internal/entity.js'\nimport { runQuery } from './internal/query.js'\nimport type {\n ComponentLike,\n EntityId,\n ObserverEntry,\n ObserverEvent,\n Query,\n QueryInternal,\n World,\n WorldState,\n} from './internal/types.js'\nimport { getOrRegisterComponentBit, getWorldState } from './internal/world.js'\n\n/**\n * Options accepted by every observer registration. `signal` aborts the\n * subscription when fired; the returned unsubscribe is still safe to call.\n */\nexport interface ObserverOptions {\n signal?: AbortSignal\n}\n\nfunction bindAbortSignal(unsubscribe: () => void, signal: AbortSignal | undefined): () => void {\n if (!signal) return unsubscribe\n if (signal.aborted) {\n unsubscribe()\n return () => {}\n }\n const onAbort = (): void => {\n unsubscribe()\n }\n signal.addEventListener('abort', onAbort, { once: true })\n let detached = false\n return () => {\n if (detached) return\n detached = true\n signal.removeEventListener('abort', onAbort)\n unsubscribe()\n }\n}\n\nexport function onAdd(\n world: World,\n component: ComponentLike,\n handler: (eid: EntityId) => void,\n opts?: ObserverOptions,\n): () => void {\n return bindAbortSignal(registerComponentObserver(world, component, 'add', handler), opts?.signal)\n}\n\nexport function onRemove(\n world: World,\n component: ComponentLike,\n handler: (eid: EntityId) => void,\n opts?: ObserverOptions,\n): () => void {\n return bindAbortSignal(\n registerComponentObserver(world, component, 'remove', handler),\n opts?.signal,\n )\n}\n\n/**\n * Low-level mutation hook. Fires after `setComponent(world, eid, comp, value)`\n * when the component is already present on the entity.\n *\n * Does NOT fire for:\n * - `addComponent` (use `onAdd` for that path; `addComponent + setComponent`\n * fires `onAdd` then `onSet`)\n * - Direct writes to a column view returned by `getComponent`. The column\n * array is the raw `TypedArray` / object — mutations bypass observer\n * dispatch.\n *\n * @example\n * // ❌ Anti-pattern: no `onSet` callback fires.\n * const col = getComponent(world, eid, Position) // raw column object\n * col.x[getEntityIndex(eid)] = 5\n *\n * // ✅ Correct: triggers `onSet`.\n * setComponent(world, eid, Position, { x: 5 })\n *\n * This is NOT a reactive value-predicate query — see `enterQuery` /\n * `exitQuery` for structural change tracking, and validate value predicates\n * in app code if you need them.\n */\nexport function onSet<C extends ComponentLike>(\n world: World,\n component: C,\n handler: (eid: EntityId, value: unknown) => void,\n opts?: ObserverOptions,\n): () => void {\n return bindAbortSignal(registerComponentObserver(world, component, 'set', handler), opts?.signal)\n}\n\nexport function observe(\n world: World,\n query: Query,\n event: ObserverEvent,\n handler: (eid: EntityId) => void,\n opts?: ObserverOptions,\n): () => void {\n const state = getWorldState(world)\n // Force registration of the query into this world so dispatch can find it.\n runQuery(world, query)\n const entry: ObserverEntry = {\n event,\n componentBit: -1,\n queryId: (query as QueryInternal).id,\n handler: handler as (eid: EntityId, value?: unknown) => void,\n }\n state.observers.push(entry)\n const unsubscribe = (): void => {\n const idx = state.observers.indexOf(entry)\n if (idx >= 0) state.observers.splice(idx, 1)\n }\n return bindAbortSignal(unsubscribe, opts?.signal)\n}\n\nfunction registerComponentObserver(\n world: World,\n component: ComponentLike,\n event: ObserverEvent,\n handler: (eid: EntityId, value?: unknown) => void,\n): () => void {\n const state = getWorldState(world)\n const info = getComponentInfo(component)\n let bit = state.componentBitFor.get(info.id)\n if (bit === undefined) {\n bit = getOrRegisterComponentBit(state, info)\n }\n const entry: ObserverEntry = { event, componentBit: bit, queryId: -1, handler }\n state.observers.push(entry)\n return () => {\n const idx = state.observers.indexOf(entry)\n if (idx >= 0) state.observers.splice(idx, 1)\n }\n}\n\n// --- Dispatch impls (wired into component.ts) ---\n//\n// CORRECTNESS: every dispatch loop snapshots `state.observers` via `Array.from`\n// before iterating. A handler may call its returned unsubscribe (which splices\n// `state.observers`), and mutating the backing array while iterating with a\n// for-of would skip the next sibling observer. The snapshot pins the visit\n// list; already-removed entries are filtered via `state.observers.includes`\n// so an in-flight unsubscribe also skips subsequent fires of the same dispatch.\n\nfunction fireAdd(state: WorldState, eid: EntityId, bit: number): void {\n const snapshot = Array.from(state.observers)\n for (const obs of snapshot) {\n if (obs.event !== 'add') continue\n if (obs.componentBit !== bit) continue\n if (!state.observers.includes(obs)) continue\n obs.handler(eid)\n }\n // Query-targeted observers: check if the entity's mask now matches the query\n // (uses the post-mutation mask, which the caller already wrote)\n dispatchQueryObservers(state, eid, 'add', /*prev*/ null, /*current*/ true)\n}\n\nfunction fireRemove(state: WorldState, eid: EntityId, bit: number): void {\n const snapshot = Array.from(state.observers)\n for (const obs of snapshot) {\n if (obs.event !== 'remove') continue\n if (obs.componentBit !== bit) continue\n if (!state.observers.includes(obs)) continue\n obs.handler(eid)\n }\n dispatchQueryObservers(state, eid, 'remove', /*prev*/ true, /*current*/ null)\n}\n\nfunction fireSet(state: WorldState, eid: EntityId, bit: number, value: unknown): void {\n const snapshot = Array.from(state.observers)\n for (const obs of snapshot) {\n if (obs.event !== 'set') continue\n if (!state.observers.includes(obs)) continue\n if (obs.componentBit === bit) obs.handler(eid, value)\n else if (obs.queryId !== -1) {\n const q = state.queries[obs.queryId]\n if (q?.all.includes(state.componentInfoByBit[bit]?.id ?? -1)) {\n obs.handler(eid, value)\n }\n }\n }\n}\n\n// Helper: when a component changes, walk query observers to see if their query\n// match status changed. Reads state.entityMask in place; no per-call allocation.\nfunction dispatchQueryObservers(\n state: WorldState,\n eid: EntityId,\n event: 'add' | 'remove',\n _prev: unknown,\n _current: unknown,\n): void {\n const w = state.options.maskWordCount\n const base = ((eid as number) & state.options.indexMask) * w\n const snapshot = Array.from(state.observers)\n for (const obs of snapshot) {\n if (obs.event !== event) continue\n if (obs.queryId === -1) continue\n if (!state.observers.includes(obs)) continue\n const bundle = state.queryMasks.get(obs.queryId)\n if (!bundle) continue\n const isMatch = matchesEntityMask(\n state.entityMask,\n base,\n w,\n bundle.withMask,\n bundle.anyMask,\n bundle.noneMask,\n bundle.anyHasBits,\n )\n // For 'add' event, fire if newly matched. For 'remove', fire if newly unmatched.\n // We approximate \"newly\" by always firing on event when match status agrees;\n // duplicates are acceptable for 0.1 query observers.\n if (event === 'add' && isMatch) obs.handler(eid)\n if (event === 'remove' && !isMatch) obs.handler(eid)\n }\n}\n\n// Wire the dispatch into component.ts\nregisterObserverDispatch({ fireAdd, fireRemove, fireSet })\n\n// Register destroy hook so onRemove fires for every component on destroy\n// AND so query-targeted observers see the entity exit any matched query.\nregisterObserversAPI({\n dispatchDestroyObservers(state: WorldState, eid: EntityId): void {\n const w = state.options.maskWordCount\n const base = ((eid as number) & state.options.indexMask) * w\n\n // Snapshot the pre-destroy mask so Phase 2's `wasMatch` is computed\n // against the state at destroy entry — Phase 1 handlers might reentrant-\n // mutate `state.entityMask` (e.g. by calling removeComponent on a\n // sibling), and we still want query observers to fire for queries the\n // entity was matching *before* the destroy began.\n const preMask = new Uint32Array(w)\n for (let i = 0; i < w; i++) preMask[i] = state.entityMask[base + i] ?? 0\n\n // Phase 1: component-level remove for every bit set at destroy entry.\n forEachSetBit(preMask, 0, w, (bit) => {\n const snapshot = Array.from(state.observers)\n for (const obs of snapshot) {\n if (obs.event !== 'remove') continue\n if (obs.componentBit !== bit) continue\n if (!state.observers.includes(obs)) continue\n obs.handler(eid)\n }\n })\n\n // Phase 2: query-level remove for any query that was matching this entity.\n // Read the pre-destroy mask snapshot (not live state.entityMask) so this\n // phase is decoupled from Phase 1 reentrant mutations.\n const querySnapshot = Array.from(state.observers)\n for (const obs of querySnapshot) {\n if (obs.event !== 'remove') continue\n if (obs.queryId === -1) continue\n if (!state.observers.includes(obs)) continue\n const bundle = state.queryMasks.get(obs.queryId)\n if (!bundle) continue\n const wasMatch = matchesEntityMask(\n preMask,\n 0,\n w,\n bundle.withMask,\n bundle.anyMask,\n bundle.noneMask,\n bundle.anyHasBits,\n )\n if (wasMatch) obs.handler(eid)\n }\n },\n})\n"]}
1
+ {"version":3,"sources":["../src/observers.ts"],"names":["bindAbortSignal","unsubscribe","signal","onAbort","detached","onAdd","world","component","handler","opts","registerComponentObserver","onRemove","onSet","observe","query","event","state","getWorldState","runQuery","entry","idx","info","getComponentInfo","bit","getOrRegisterComponentBit","fireAdd","eid","snapshot","obs","dispatchQueryObservers","fireRemove","fireSet","value","_prev","_current","w","base","bundle","isMatch","matchesEntityMask","registerObserverDispatch","registerObserversAPI","preMask","forEachSetBit","querySnapshot"],"mappings":"2FA0BA,SAASA,CAAAA,CAAgBC,CAAAA,CAAyBC,CAAAA,CAA6C,CAC7F,GAAI,CAACA,CAAAA,CAAQ,OAAOD,CAAAA,CACpB,GAAIC,CAAAA,CAAO,OAAA,CACT,OAAAD,GAAY,CACL,IAAM,CAAC,CAAA,CAEhB,IAAME,CAAAA,CAAU,IAAY,CAC1BF,IACF,CAAA,CACAC,CAAAA,CAAO,gBAAA,CAAiB,QAASC,CAAAA,CAAS,CAAE,IAAA,CAAM,IAAK,CAAC,CAAA,CACxD,IAAIC,CAAAA,CAAW,KAAA,CACf,OAAO,IAAM,CACPA,CAAAA,GACJA,EAAW,IAAA,CACXF,CAAAA,CAAO,mBAAA,CAAoB,OAAA,CAASC,CAAO,CAAA,CAC3CF,CAAAA,EAAY,EACd,CACF,CAEO,SAASI,CAAAA,CACdC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,C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3C,IAAA,IAAWY,KAAOD,CAAAA,CACZC,CAAAA,CAAI,KAAA,GAAU,QAAA,EACdA,CAAAA,CAAI,YAAA,GAAiBL,CAAAA,EACpBP,CAAAA,CAAM,UAAU,QAAA,CAASY,CAAG,CAAA,EACjCA,CAAAA,CAAI,OAAA,CAAQF,CAAG,EAEnB,CAAC,EAKD,IAAMkB,CAAAA,CAAgB,KAAA,CAAM,IAAA,CAAK5B,CAAAA,CAAM,SAAS,CAAA,CAChD,IAAA,IAAWY,KAAOgB,CAAAA,CAAe,CAG/B,GAFIhB,CAAAA,CAAI,QAAU,QAAA,EACdA,CAAAA,CAAI,OAAA,GAAY,EAAA,EAChB,CAACZ,CAAAA,CAAM,SAAA,CAAU,QAAA,CAASY,CAAG,CAAA,CAAG,SACpC,IAAMS,CAAAA,CAASrB,EAAM,UAAA,CAAW,GAAA,CAAIY,CAAAA,CAAI,OAAO,CAAA,CAC/C,GAAI,CAACS,CAAAA,CAAQ,SACIE,CAAAA,CACfG,CAAAA,CACA,CAAA,CACAP,CAAAA,CACAE,CAAAA,CAAO,QAAA,CACPA,CAAAA,CAAO,OAAA,CACPA,EAAO,QAAA,CACPA,CAAAA,CAAO,UACT,CAAA,EACcT,EAAI,OAAA,CAAQF,CAAG,EAC/B,CACF,CACF,CAAC,CAAA","file":"observers.js","sourcesContent":["// aiecsjs/observers — observe component add/remove/set events.\n\nimport { forEachSetBit, matchesEntityMask } from './internal/bitmask.js'\nimport { getComponentInfo, registerObserverDispatch } from './internal/component.js'\nimport { registerObserversAPI } from './internal/entity.js'\nimport { runQuery } from './internal/query.js'\nimport type {\n ComponentLike,\n EntityId,\n ObserverEntry,\n ObserverEvent,\n Query,\n QueryInternal,\n World,\n WorldState,\n} from './internal/types.js'\nimport { getOrRegisterComponentBit, getWorldState } from './internal/world.js'\n\n/**\n * Options accepted by every observer registration. `signal` aborts the\n * subscription when fired; the returned unsubscribe is still safe to call.\n */\nexport interface ObserverOptions {\n signal?: AbortSignal\n}\n\nfunction bindAbortSignal(unsubscribe: () => void, signal: AbortSignal | undefined): () => void {\n if (!signal) return unsubscribe\n if (signal.aborted) {\n unsubscribe()\n return () => {}\n }\n const onAbort = (): void => {\n unsubscribe()\n }\n signal.addEventListener('abort', onAbort, { once: true })\n let detached = false\n return () => {\n if (detached) return\n detached = true\n signal.removeEventListener('abort', onAbort)\n unsubscribe()\n }\n}\n\nexport function onAdd(\n world: World,\n component: ComponentLike,\n handler: (eid: EntityId) => void,\n opts?: ObserverOptions,\n): () => void {\n return bindAbortSignal(registerComponentObserver(world, component, 'add', handler), opts?.signal)\n}\n\nexport function onRemove(\n world: World,\n component: ComponentLike,\n handler: (eid: EntityId) => void,\n opts?: ObserverOptions,\n): () => void {\n return bindAbortSignal(\n registerComponentObserver(world, component, 'remove', handler),\n opts?.signal,\n )\n}\n\n/**\n * Low-level mutation hook. Fires after `setComponent(world, eid, comp, value)`\n * when the component is already present on the entity.\n *\n * Does NOT fire for:\n * - `addComponent` (use `onAdd` for that path; `addComponent + setComponent`\n * fires `onAdd` then `onSet`)\n * - Direct writes to a column view returned by `getComponent`. The column\n * array is the raw `TypedArray` / object — mutations bypass observer\n * dispatch.\n *\n * @example\n * // ❌ Anti-pattern: no `onSet` callback fires.\n * const col = getComponent(world, eid, Position) // raw column object\n * col.x[getEntityIndex(eid)] = 5\n *\n * // ✅ Correct: triggers `onSet`.\n * setComponent(world, eid, Position, { x: 5 })\n *\n * This is NOT a reactive value-predicate query — see `enterQuery` /\n * `exitQuery` for structural change tracking, and validate value predicates\n * in app code if you need them.\n */\nexport function onSet<C extends ComponentLike>(\n world: World,\n component: C,\n handler: (eid: EntityId, value: unknown) => void,\n opts?: ObserverOptions,\n): () => void {\n return bindAbortSignal(registerComponentObserver(world, component, 'set', handler), opts?.signal)\n}\n\nexport function observe(\n world: World,\n query: Query,\n event: ObserverEvent,\n handler: (eid: EntityId) => void,\n opts?: ObserverOptions,\n): () => void {\n const state = getWorldState(world)\n // Force registration of the query into this world so dispatch can find it.\n runQuery(world, query)\n const entry: ObserverEntry = {\n event,\n componentBit: -1,\n queryId: (query as QueryInternal).id,\n handler: handler as (eid: EntityId, value?: unknown) => void,\n }\n state.observers.push(entry)\n const unsubscribe = (): void => {\n const idx = state.observers.indexOf(entry)\n if (idx >= 0) state.observers.splice(idx, 1)\n }\n return bindAbortSignal(unsubscribe, opts?.signal)\n}\n\nfunction registerComponentObserver(\n world: World,\n component: ComponentLike,\n event: ObserverEvent,\n handler: (eid: EntityId, value?: unknown) => void,\n): () => void {\n const state = getWorldState(world)\n const info = getComponentInfo(component)\n let bit = state.componentBitFor.get(info.id)\n if (bit === undefined) {\n bit = getOrRegisterComponentBit(state, info)\n }\n const entry: ObserverEntry = { event, componentBit: bit, queryId: -1, handler }\n state.observers.push(entry)\n return () => {\n const idx = state.observers.indexOf(entry)\n if (idx >= 0) state.observers.splice(idx, 1)\n }\n}\n\n// --- Dispatch impls (wired into component.ts) ---\n//\n// CORRECTNESS: every dispatch loop snapshots `state.observers` via `Array.from`\n// before iterating. A handler may call its returned unsubscribe (which splices\n// `state.observers`), and mutating the backing array while iterating with a\n// for-of would skip the next sibling observer. The snapshot pins the visit\n// list; already-removed entries are filtered via `state.observers.includes`\n// so an in-flight unsubscribe also skips subsequent fires of the same dispatch.\n\nfunction fireAdd(state: WorldState, eid: EntityId, bit: number): void {\n const snapshot = Array.from(state.observers)\n for (const obs of snapshot) {\n if (obs.event !== 'add') continue\n if (obs.componentBit !== bit) continue\n if (!state.observers.includes(obs)) continue\n obs.handler(eid)\n }\n // Query-targeted observers: check if the entity's mask now matches the query\n // (uses the post-mutation mask, which the caller already wrote)\n dispatchQueryObservers(state, eid, 'add', /*prev*/ null, /*current*/ true)\n}\n\nfunction fireRemove(state: WorldState, eid: EntityId, bit: number): void {\n const snapshot = Array.from(state.observers)\n for (const obs of snapshot) {\n if (obs.event !== 'remove') continue\n if (obs.componentBit !== bit) continue\n if (!state.observers.includes(obs)) continue\n obs.handler(eid)\n }\n dispatchQueryObservers(state, eid, 'remove', /*prev*/ true, /*current*/ null)\n}\n\nfunction fireSet(state: WorldState, eid: EntityId, bit: number, value: unknown): void {\n const snapshot = Array.from(state.observers)\n for (const obs of snapshot) {\n if (obs.event !== 'set') continue\n if (!state.observers.includes(obs)) continue\n if (obs.componentBit === bit) obs.handler(eid, value)\n else if (obs.queryId !== -1) {\n const q = state.queries[obs.queryId]\n if (q?.all.includes(state.componentInfoByBit[bit]?.id ?? -1)) {\n obs.handler(eid, value)\n }\n }\n }\n}\n\n// Helper: when a component changes, walk query observers to see if their query\n// match status changed. Reads state.entityMask in place; no per-call allocation.\nfunction dispatchQueryObservers(\n state: WorldState,\n eid: EntityId,\n event: 'add' | 'remove',\n _prev: unknown,\n _current: unknown,\n): void {\n const w = state.options.maskWordCount\n const base = ((eid as number) & state.options.indexMask) * w\n const snapshot = Array.from(state.observers)\n for (const obs of snapshot) {\n if (obs.event !== event) continue\n if (obs.queryId === -1) continue\n if (!state.observers.includes(obs)) continue\n const bundle = state.queryMasks.get(obs.queryId)\n if (!bundle) continue\n const isMatch = matchesEntityMask(\n state.entityMask,\n base,\n w,\n bundle.withMask,\n bundle.anyMask,\n bundle.noneMask,\n bundle.anyHasBits,\n )\n // For 'add' event, fire if newly matched. For 'remove', fire if newly unmatched.\n // We approximate \"newly\" by always firing on event when match status agrees;\n // duplicates are acceptable for 0.1 query observers.\n if (event === 'add' && isMatch) obs.handler(eid)\n if (event === 'remove' && !isMatch) obs.handler(eid)\n }\n}\n\n// Wire the dispatch into component.ts\nregisterObserverDispatch({ fireAdd, fireRemove, fireSet })\n\n// Register destroy hook so onRemove fires for every component on destroy\n// AND so query-targeted observers see the entity exit any matched query.\nregisterObserversAPI({\n dispatchDestroyObservers(state: WorldState, eid: EntityId): void {\n const w = state.options.maskWordCount\n const base = ((eid as number) & state.options.indexMask) * w\n\n // Snapshot the pre-destroy mask so Phase 2's `wasMatch` is computed\n // against the state at destroy entry — Phase 1 handlers might reentrant-\n // mutate `state.entityMask` (e.g. by calling removeComponent on a\n // sibling), and we still want query observers to fire for queries the\n // entity was matching *before* the destroy began.\n const preMask = new Uint32Array(w)\n for (let i = 0; i < w; i++) preMask[i] = state.entityMask[base + i] ?? 0\n\n // Phase 1: component-level remove for every bit set at destroy entry.\n forEachSetBit(preMask, 0, w, (bit) => {\n const snapshot = Array.from(state.observers)\n for (const obs of snapshot) {\n if (obs.event !== 'remove') continue\n if (obs.componentBit !== bit) continue\n if (!state.observers.includes(obs)) continue\n obs.handler(eid)\n }\n })\n\n // Phase 2: query-level remove for any query that was matching this entity.\n // Read the pre-destroy mask snapshot (not live state.entityMask) so this\n // phase is decoupled from Phase 1 reentrant mutations.\n const querySnapshot = Array.from(state.observers)\n for (const obs of querySnapshot) {\n if (obs.event !== 'remove') continue\n if (obs.queryId === -1) continue\n if (!state.observers.includes(obs)) continue\n const bundle = state.queryMasks.get(obs.queryId)\n if (!bundle) continue\n const wasMatch = matchesEntityMask(\n preMask,\n 0,\n w,\n bundle.withMask,\n bundle.anyMask,\n bundle.noneMask,\n bundle.anyHasBits,\n )\n if (wasMatch) obs.handler(eid)\n }\n },\n})\n"]}