ecspresso 0.4.3 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -8,6 +8,11 @@ export default class EventBus<EventTypes> {
8
8
  * Subscribe to an event once
9
9
  */
10
10
  once<E extends keyof EventTypes>(eventType: E, callback: (data: EventTypes[E]) => void): () => void;
11
+ /**
12
+ * Unsubscribe a specific callback from an event by reference
13
+ * @returns true if the callback was found and removed, false otherwise
14
+ */
15
+ unsubscribe<E extends keyof EventTypes>(eventType: E, callback: (data: EventTypes[E]) => void): boolean;
11
16
  /**
12
17
  * Internal method to add an event handler
13
18
  */
@@ -0,0 +1,122 @@
1
+ import type { HierarchyEntry, HierarchyIteratorOptions } from "./types";
2
+ /**
3
+ * Manages parent-child relationships between entities.
4
+ * Handles hierarchy storage, validation, and traversal operations.
5
+ */
6
+ export default class HierarchyManager {
7
+ /** childId -> parentId */
8
+ private parentMap;
9
+ /** parentId -> ordered childIds */
10
+ private childrenMap;
11
+ /**
12
+ * Set the parent of an entity.
13
+ * @param childId The entity to set as a child
14
+ * @param parentId The entity to set as the parent
15
+ * @throws Error if this would create a circular reference or self-parenting
16
+ */
17
+ setParent(childId: number, parentId: number): this;
18
+ /**
19
+ * Remove the parent relationship for an entity (orphan it).
20
+ * @param childId The entity to orphan
21
+ * @returns true if a parent was removed, false if entity had no parent
22
+ */
23
+ removeParent(childId: number): boolean;
24
+ /**
25
+ * Get the parent of an entity.
26
+ * @param entityId The entity to get the parent of
27
+ * @returns The parent entity ID, or null if no parent
28
+ */
29
+ getParent(entityId: number): number | null;
30
+ /**
31
+ * Get all children of an entity in insertion order.
32
+ * @param parentId The parent entity
33
+ * @returns Readonly array of child entity IDs
34
+ */
35
+ getChildren(parentId: number): readonly number[];
36
+ /**
37
+ * Get a child at a specific index.
38
+ * @param parentId The parent entity
39
+ * @param index The index of the child
40
+ * @returns The child entity ID, or null if index is out of bounds
41
+ */
42
+ getChildAt(parentId: number, index: number): number | null;
43
+ /**
44
+ * Get the index of a child within its parent's children list.
45
+ * @param parentId The parent entity
46
+ * @param childId The child entity to find
47
+ * @returns The index of the child, or -1 if not found
48
+ */
49
+ getChildIndex(parentId: number, childId: number): number;
50
+ /**
51
+ * Remove an entity from the hierarchy (called when entity is destroyed).
52
+ * Orphans any children and removes from parent's children list.
53
+ * @param entityId The entity being removed
54
+ * @returns Information about the removal (oldParent and orphanedChildren)
55
+ */
56
+ removeEntity(entityId: number): {
57
+ oldParent: number | null;
58
+ orphanedChildren: number[];
59
+ };
60
+ /**
61
+ * Get all ancestors of an entity in order [parent, grandparent, ...].
62
+ * @param entityId The entity to get ancestors of
63
+ * @returns Readonly array of ancestor entity IDs
64
+ */
65
+ getAncestors(entityId: number): readonly number[];
66
+ /**
67
+ * Get all descendants of an entity in depth-first order.
68
+ * @param entityId The entity to get descendants of
69
+ * @returns Readonly array of descendant entity IDs
70
+ */
71
+ getDescendants(entityId: number): readonly number[];
72
+ /**
73
+ * Get the root ancestor of an entity (topmost parent), or self if no parent.
74
+ * @param entityId The entity to get the root of
75
+ * @returns The root entity ID
76
+ */
77
+ getRoot(entityId: number): number;
78
+ /**
79
+ * Get siblings of an entity (other children of the same parent).
80
+ * @param entityId The entity to get siblings of
81
+ * @returns Readonly array of sibling entity IDs
82
+ */
83
+ getSiblings(entityId: number): readonly number[];
84
+ /**
85
+ * Check if an entity is a descendant of another entity.
86
+ * @param entityId The potential descendant
87
+ * @param ancestorId The potential ancestor
88
+ * @returns true if entityId is a descendant of ancestorId
89
+ */
90
+ isDescendantOf(entityId: number, ancestorId: number): boolean;
91
+ /**
92
+ * Check if an entity is an ancestor of another entity.
93
+ * @param entityId The potential ancestor
94
+ * @param descendantId The potential descendant
95
+ * @returns true if entityId is an ancestor of descendantId
96
+ */
97
+ isAncestorOf(entityId: number, descendantId: number): boolean;
98
+ /**
99
+ * Get all root entities (entities that have children but no parent).
100
+ * @returns Readonly array of root entity IDs
101
+ */
102
+ getRootEntities(): readonly number[];
103
+ /**
104
+ * Check if setting a parent would create a cycle.
105
+ * A cycle would occur if the prospective parent is a descendant of the child.
106
+ */
107
+ private wouldCreateCycle;
108
+ /**
109
+ * Traverse the hierarchy in parent-first (breadth-first) order.
110
+ * Parents are guaranteed to be visited before their children.
111
+ * @param callback Function called for each entity with (entityId, parentId, depth)
112
+ * @param options Optional traversal options (roots to filter to specific subtrees)
113
+ */
114
+ forEachInHierarchy(callback: (entityId: number, parentId: number | null, depth: number) => void, options?: HierarchyIteratorOptions): void;
115
+ /**
116
+ * Generator-based hierarchy traversal in parent-first (breadth-first) order.
117
+ * Supports early termination via break.
118
+ * @param options Optional traversal options (roots to filter to specific subtrees)
119
+ * @yields HierarchyEntry for each entity in parent-first order
120
+ */
121
+ hierarchyIterator(options?: HierarchyIteratorOptions): Generator<HierarchyEntry, void, unknown>;
122
+ }
package/dist/index.d.ts CHANGED
@@ -2,13 +2,19 @@ import ECSpresso from './ecspresso';
2
2
  import { SystemBuilder } from './system-builder';
3
3
  import Bundle, { mergeBundles } from './bundle';
4
4
  export * from './types';
5
+ export * from './asset-types';
6
+ export * from './screen-types';
7
+ export type { ReactiveQueryDefinition } from './reactive-query-manager';
5
8
  export { default as EntityManager } from './entity-manager';
6
9
  export { default as EventBus } from './event-bus';
10
+ export { default as HierarchyManager } from './hierarchy-manager';
7
11
  /**
8
12
  * @internal ResourceManager is exported for testing purposes only.
9
13
  * Use ECSpresso resource methods instead: getResource(), addResource(), removeResource(), updateResource(), hasResource()
10
14
  */
11
15
  export { default as ResourceManager } from './resource-manager';
16
+ export { default as AssetManager, createAssetConfigurator } from './asset-manager';
17
+ export { default as ScreenManager, createScreenConfigurator } from './screen-manager';
12
18
  export { SystemBuilder };
13
19
  export { Bundle, mergeBundles };
14
20
  export default ECSpresso;
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- class F{nextId=1;entities=new Map;componentIndices=new Map;addedCallbacks=new Map;removedCallbacks=new Map;createEntity(){let j=this.nextId++,G={id:j,components:{}};return this.entities.set(j,G),G}addComponent(j,G,H){let J=typeof j==="number"?this.entities.get(j):j;if(!J){let Y=typeof j==="number"?j:j.id;throw Error(`Cannot add component '${String(G)}': Entity with ID ${Y} does not exist`)}if(J.components[G]=H,!this.componentIndices.has(G))this.componentIndices.set(G,new Set);this.componentIndices.get(G)?.add(J.id);let X=this.addedCallbacks.get(G);if(X)for(let Y of X)Y(H,J);return this}addComponents(j,G){let H=typeof j==="number"?this.entities.get(j):j;if(!H){let J=typeof j==="number"?j:j.id;throw Error(`Cannot add components: Entity with ID ${J} does not exist`)}for(let J in G)this.addComponent(H,J,G[J]);return this}removeComponent(j,G){let H=typeof j==="number"?this.entities.get(j):j;if(!H){let Y=typeof j==="number"?j:j.id;throw Error(`Cannot remove component '${String(G)}': Entity with ID ${Y} does not exist`)}let J=H.components[G];delete H.components[G];let X=this.removedCallbacks.get(G);if(X&&J!==void 0)for(let Y of X)Y(J,H);return this.componentIndices.get(G)?.delete(H.id),this}getComponent(j,G){let H=this.entities.get(j);if(!H)throw Error(`Cannot get component '${String(G)}': Entity with ID ${j} does not exist`);return H.components[G]||null}getEntitiesWithQuery(j=[],G=[]){if(j.length===0){if(G.length===0)return Array.from(this.entities.values());return Array.from(this.entities.values()).filter((Z)=>{return G.every((_)=>!(_ in Z.components))})}let H=j.reduce((Z,_)=>{let $=this.componentIndices.get(_)?.size??0,w=this.componentIndices.get(Z)?.size??1/0;return $<w?_:Z},j[0]),J=this.componentIndices.get(H);if(!J||J.size===0)return[];let X=[],Y=G.length>0;for(let Z of J){let _=this.entities.get(Z);if(_&&j.every(($)=>($ in _.components))&&(!Y||G.every(($)=>!($ in _.components))))X.push(_)}return X}removeEntity(j){let G=typeof j==="number"?this.entities.get(j):j;if(!G)return!1;for(let H of Object.keys(G.components)){let J=G.components[H];if(J!==void 0){let X=this.removedCallbacks.get(H);if(X)for(let Y of X)Y(J,G)}this.componentIndices.get(H)?.delete(G.id)}return this.entities.delete(G.id)}getEntity(j){return this.entities.get(j)}onComponentAdded(j,G){if(!this.addedCallbacks.has(j))this.addedCallbacks.set(j,new Set);return this.addedCallbacks.get(j).add(G),this}onComponentRemoved(j,G){if(!this.removedCallbacks.has(j))this.removedCallbacks.set(j,new Set);return this.removedCallbacks.get(j).add(G),this}}class P{handlers=new Map;subscribe(j,G){return this.addHandler(j,G,!1)}once(j,G){return this.addHandler(j,G,!0)}addHandler(j,G,H){if(!this.handlers.has(j))this.handlers.set(j,[]);let J={callback:G,once:H};return this.handlers.get(j).push(J),()=>{let X=this.handlers.get(j);if(X){let Y=X.indexOf(J);if(Y!==-1)X.splice(Y,1)}}}publish(j,G){let H=this.handlers.get(j);if(!H)return;let J=[...H],X=[];for(let Y of J)if(Y.callback(G),Y.once)X.push(Y);if(X.length>0)for(let Y of X){let Z=H.indexOf(Y);if(Z!==-1)H.splice(Z,1)}}clear(){this.handlers.clear()}clearEvent(j){this.handlers.delete(j)}}class U{resources=new Map;resourceFactories=new Map;initializedResourceKeys=new Set;add(j,G){if(this._isFactoryFunction(G))this.resourceFactories.set(j,G);else this.resources.set(j,G),this.initializedResourceKeys.add(j);return this}_isFactoryFunction(j){if(typeof j!=="function")return!1;let G=j.toString();if(G.startsWith("class "))return!1;if(G.includes("[native code]"))return!1;if(j.prototype){let H=Object.getOwnPropertyNames(j.prototype);if(H.length>1||H.length===1&&H[0]!=="constructor")return!1}if(j.name&&j.name[0]===j.name[0].toUpperCase()&&j.name.length>1){if(G.includes("this.")||G.includes("new "))return!1}return!0}get(j,G){let H=this.resources.get(j);if(H!==void 0)return H;let J=this.resourceFactories.get(j);if(J===void 0)throw Error(`Resource ${String(j)} not found`);let X=J(G);if(!(X instanceof Promise))this.resources.set(j,X),this.initializedResourceKeys.add(j);return X}has(j){return this.resources.has(j)||this.resourceFactories.has(j)}remove(j){let G=this.resources.delete(j),H=this.resourceFactories.delete(j);if(this.initializedResourceKeys.has(j))this.initializedResourceKeys.delete(j);return G||H}getKeys(){let j=new Set([...this.resources.keys(),...this.resourceFactories.keys()]);return Array.from(j)}needsInitialization(j){return this.resourceFactories.has(j)&&!this.initializedResourceKeys.has(j)}getPendingInitializationKeys(){return Array.from(this.resourceFactories.keys()).filter((j)=>!this.initializedResourceKeys.has(j))}async initializeResource(j,G){if(!this.resourceFactories.has(j)||this.initializedResourceKeys.has(j))return;let J=await this.resourceFactories.get(j)(G);this.resources.set(j,J),this.initializedResourceKeys.add(j),this.resourceFactories.delete(j)}async initializeResources(j,...G){if(G.length===0){let H=this.getPendingInitializationKeys();await Promise.all(H.map((J)=>this.initializeResource(J,j)));return}await Promise.all(G.map((H)=>this.initializeResource(H,j)))}}class M{_label;_ecspresso;_bundle;queries={};processFunction;detachFunction;initializeFunction;eventHandlers;_priority=0;_isRegistered=!1;constructor(j,G=null,H=null){this._label=j;this._ecspresso=G;this._bundle=H}get label(){return this._label}get bundle(){return this._bundle}get ecspresso(){return this._ecspresso}_autoRegister(){if(this._isRegistered||!this._ecspresso)return;let j=this._buildSystemObject();Q(j,this._ecspresso),this._isRegistered=!0}_buildSystemObject(){return this._createSystemObject()}_createSystemObject(){let j={label:this._label,entityQueries:this.queries,priority:this._priority};if(this.processFunction)j.process=this.processFunction;if(this.detachFunction)j.onDetach=this.detachFunction;if(this.initializeFunction)j.onInitialize=this.initializeFunction;if(this.eventHandlers)j.eventHandlers=this.eventHandlers;return j}setPriority(j){return this._priority=j,this}addQuery(j,G){let H=this;return H.queries={...this.queries,[j]:G},H}setProcess(j){return this.processFunction=j,this}registerAndContinue(){if(!this._ecspresso)throw Error(`Cannot register system '${this._label}': SystemBuilder is not attached to an ECSpresso instance. Use Bundle.addSystem() or ECSpresso.addSystem() instead.`);return this._autoRegister(),this._ecspresso}and(){if(this._ecspresso)return this._autoRegister(),this._ecspresso;if(this._bundle)return this._bundle;throw Error(`Cannot use and() on system '${this._label}': not attached to ECSpresso or Bundle.`)}setOnDetach(j){return this.detachFunction=j,this}setOnInitialize(j){return this.initializeFunction=j,this}setEventHandlers(j){return this.eventHandlers=j,this}build(j){let G=this._createSystemObject();if(this._ecspresso)Q(G,this._ecspresso);if(j)Q(G,j);return this}}function Q(j,G){G._registerSystem(j)}function W(j,G){return new M(j,G)}function g(j,G){return new M(j,null,G)}var K="0.4.3";var z={};class A{static VERSION=K;_entityManager;_eventBus;_resourceManager;_systems=[];_sortedSystems=[];_installedBundles=new Set;constructor(){this._entityManager=new F,this._eventBus=new P,this._resourceManager=new U,this._sortedSystems=[]}static create(){return new V}addSystem(j){return W(j,this)}update(j){for(let G of this._sortedSystems){if(!G.process)continue;let H={},J=!1,X=!1;if(G.entityQueries)for(let Y in G.entityQueries){X=!0;let Z=G.entityQueries[Y];if(Z){if(H[Y]=this._entityManager.getEntitiesWithQuery(Z.with,Z.without||[]),H[Y].length)J=!0}}if(J)G.process(H,j,this);else if(!X)G.process(z,j,this)}}async initialize(){await this.initializeResources();for(let j of this._systems)await j.onInitialize?.(this)}async initializeResources(...j){await this._resourceManager.initializeResources(this,...j)}_sortSystems(){this._sortedSystems=[...this._systems].sort((j,G)=>{let H=j.priority??0;return(G.priority??0)-H})}updateSystemPriority(j,G){let H=this._systems.find((J)=>J.label===j);if(!H)return!1;return H.priority=G,this._sortSystems(),!0}removeSystem(j){let G=this._systems.findIndex((J)=>J.label===j);if(G===-1)return!1;let H=this._systems[G];if(!H)return!1;if(H.onDetach)H.onDetach(this);return this._systems.splice(G,1),this._sortSystems(),!0}_registerSystem(j){if(this._systems.push(j),this._sortSystems(),!j.eventHandlers)return;for(let G in j.eventHandlers){let H=j.eventHandlers[G]?.handler;if(H)this._eventBus.subscribe(G,(J)=>{H(J,this)})}}hasResource(j){return this._resourceManager.has(j)}getResource(j){let G=this._resourceManager.get(j,this);if(!G)throw Error(`Resource '${String(j)}' not found. Available resources: [${this.getResourceKeys().map((H)=>String(H)).join(", ")}]`);return G}addResource(j,G){return this._resourceManager.add(j,G),this}removeResource(j){return this._resourceManager.remove(j)}updateResource(j,G){let H=this.getResource(j),J=G(H);return this._resourceManager.add(j,J),this}getResourceKeys(){return this._resourceManager.getKeys()}resourceNeedsInitialization(j){return this._resourceManager.needsInitialization(j)}hasComponent(j,G){return this._entityManager.getComponent(j,G)!==null}spawn(j){let G=this._entityManager.createEntity();return this._entityManager.addComponents(G,j),G}getEntitiesWithQuery(j,G=[]){return this._entityManager.getEntitiesWithQuery(j,G)}get installedBundles(){return Array.from(this._installedBundles)}get entityManager(){return this._entityManager}get eventBus(){return this._eventBus}_installBundle(j){if(this._installedBundles.has(j.id))return this;this._installedBundles.add(j.id),j.registerSystemsWithEcspresso(this);let G=j.getResources();for(let[H,J]of G.entries())this._resourceManager.add(H,J);return this}}class V{ecspresso;constructor(){this.ecspresso=new A}withBundle(j){return this.ecspresso._installBundle(j),this}build(){return this.ecspresso}}function f(){return`bundle_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,9)}`}class D{_systems=[];_resources=new Map;_id;constructor(j){this._id=j||f()}get id(){return this._id}set id(j){this._id=j}addSystem(j){if(typeof j==="string"){let G=g(j,this);return this._systems.push(G),G}else return this._systems.push(j),j}addResource(j,G){return this._resources.set(j,G),this}getSystems(){return this._systems.map((j)=>j.build())}registerSystemsWithEcspresso(j){for(let G of this._systems)G.build(j)}getResources(){return new Map(this._resources)}getResource(j){return this._resources.get(j)}getSystemBuilders(){return[...this._systems]}hasResource(j){return this._resources.has(j)}}function E(j,...G){if(G.length===0)return new D(j);let H=new D(j);for(let J of G){for(let X of J.getSystemBuilders())H.addSystem(X);for(let[X,Y]of J.getResources().entries())H.addResource(X,Y)}return H}function p(j){return j}var a=A;export{E as mergeBundles,a as default,p as createQueryDefinition,M as SystemBuilder,U as ResourceManager,P as EventBus,F as EntityManager,D as Bundle};
1
+ var h=Object.create;var{getPrototypeOf:k,defineProperty:T,getOwnPropertyNames:g}=Object;var I=Object.prototype.hasOwnProperty;var s=(j,J,X)=>{X=j!=null?h(k(j)):{};let Y=J||!j||!j.__esModule?T(X,"default",{value:j,enumerable:!0}):X;for(let Z of g(j))if(!I.call(Y,Z))T(Y,Z,{get:()=>j[Z],enumerable:!0});return Y};var y=((j)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(j,{get:(J,X)=>(typeof require<"u"?require:J)[X]}):j)(function(j){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+j+'" is not supported')});class W{parentMap=new Map;childrenMap=new Map;setParent(j,J){if(j===J)throw Error(`Cannot set entity ${j} as its own parent`);if(this.wouldCreateCycle(j,J))throw Error("Cannot set parent: would create circular reference");let X=this.parentMap.get(j);if(X!==void 0){let Z=this.childrenMap.get(X);if(Z){let _=Z.indexOf(j);if(_!==-1)Z.splice(_,1)}}this.parentMap.set(j,J);let Y=this.childrenMap.get(J);if(Y)Y.push(j);else this.childrenMap.set(J,[j]);return this}removeParent(j){let J=this.parentMap.get(j);if(J===void 0)return!1;let X=this.childrenMap.get(J);if(X){let Y=X.indexOf(j);if(Y!==-1)X.splice(Y,1)}return this.parentMap.delete(j),!0}getParent(j){return this.parentMap.get(j)??null}getChildren(j){let J=this.childrenMap.get(j);return J?[...J]:[]}getChildAt(j,J){if(J<0)return null;let X=this.childrenMap.get(j);if(!X||J>=X.length)return null;return X[J]??null}getChildIndex(j,J){let X=this.childrenMap.get(j);if(!X)return-1;return X.indexOf(J)}removeEntity(j){let J=this.parentMap.get(j)??null;if(J!==null){let Z=this.childrenMap.get(J);if(Z){let _=Z.indexOf(j);if(_!==-1)Z.splice(_,1)}}this.parentMap.delete(j);let X=this.childrenMap.get(j)??[],Y=[...X];for(let Z of X)this.parentMap.delete(Z);return this.childrenMap.delete(j),{oldParent:J,orphanedChildren:Y}}getAncestors(j){let J=[],X=this.parentMap.get(j);while(X!==void 0)J.push(X),X=this.parentMap.get(X);return J}getDescendants(j){let J=[],X=[...this.childrenMap.get(j)??[]];while(X.length>0){let Y=X.shift();if(Y===void 0)continue;J.push(Y);let Z=this.childrenMap.get(Y);if(Z)X.unshift(...Z)}return J}getRoot(j){let J=j,X=this.parentMap.get(J);while(X!==void 0)J=X,X=this.parentMap.get(J);return J}getSiblings(j){let J=this.parentMap.get(j);if(J===void 0)return[];let X=this.childrenMap.get(J);if(!X)return[];return X.filter((Y)=>Y!==j)}isDescendantOf(j,J){if(j===J)return!1;let X=this.parentMap.get(j);while(X!==void 0){if(X===J)return!0;X=this.parentMap.get(X)}return!1}isAncestorOf(j,J){return this.isDescendantOf(J,j)}getRootEntities(){let j=[];for(let J of this.childrenMap.keys())if(!this.parentMap.has(J))j.push(J);return j}wouldCreateCycle(j,J){let X=J;while(X!==void 0){if(X===j)return!0;X=this.parentMap.get(X)}return!1}forEachInHierarchy(j,J){let X=J?.roots??this.getRootEntities(),Y=[];for(let Z of X)Y.push({entityId:Z,parentId:null,depth:0});while(Y.length>0){let Z=Y.shift();if(!Z)break;j(Z.entityId,Z.parentId,Z.depth);let _=this.childrenMap.get(Z.entityId);if(_)for(let F of _)Y.push({entityId:F,parentId:Z.entityId,depth:Z.depth+1})}}*hierarchyIterator(j){let J=j?.roots??this.getRootEntities(),X=[];for(let Y of J)X.push({entityId:Y,parentId:null,depth:0});while(X.length>0){let Y=X.shift();if(!Y)break;yield Y;let Z=this.childrenMap.get(Y.entityId);if(Z)for(let _ of Z)X.push({entityId:_,parentId:Y.entityId,depth:Y.depth+1})}}}class Q{nextId=1;entities=new Map;componentIndices=new Map;addedCallbacks=new Map;removedCallbacks=new Map;hierarchyManager=new W;createEntity(){let j=this.nextId++,J={id:j,components:{}};return this.entities.set(j,J),J}addComponent(j,J,X){let Y=typeof j==="number"?this.entities.get(j):j;if(!Y){let _=typeof j==="number"?j:j.id;throw Error(`Cannot add component '${String(J)}': Entity with ID ${_} does not exist`)}if(Y.components[J]=X,!this.componentIndices.has(J))this.componentIndices.set(J,new Set);this.componentIndices.get(J)?.add(Y.id);let Z=this.addedCallbacks.get(J);if(Z)for(let _ of[...Z])_(X,Y);return this}addComponents(j,J){let X=typeof j==="number"?this.entities.get(j):j;if(!X){let Y=typeof j==="number"?j:j.id;throw Error(`Cannot add components: Entity with ID ${Y} does not exist`)}for(let Y in J)this.addComponent(X,Y,J[Y]);return this}removeComponent(j,J){let X=typeof j==="number"?this.entities.get(j):j;if(!X){let _=typeof j==="number"?j:j.id;throw Error(`Cannot remove component '${String(J)}': Entity with ID ${_} does not exist`)}let Y=X.components[J];delete X.components[J];let Z=this.removedCallbacks.get(J);if(Z&&Y!==void 0)for(let _ of[...Z])_(Y,X);return this.componentIndices.get(J)?.delete(X.id),this}getComponent(j,J){let X=this.entities.get(j);if(!X)throw Error(`Cannot get component '${String(J)}': Entity with ID ${j} does not exist`);return X.components[J]||null}getEntitiesWithQuery(j=[],J=[]){if(j.length===0){if(J.length===0)return Array.from(this.entities.values());return Array.from(this.entities.values()).filter((F)=>{return J.every(($)=>!($ in F.components))})}let X=j.reduce((F,$)=>{let G=this.componentIndices.get($)?.size??0,U=this.componentIndices.get(F)?.size??1/0;return G<U?$:F},j[0]),Y=this.componentIndices.get(X);if(!Y||Y.size===0)return[];let Z=[],_=J.length>0;for(let F of Y){let $=this.entities.get(F);if($&&j.every((G)=>(G in $.components))&&(!_||J.every((G)=>!(G in $.components))))Z.push($)}return Z}removeEntity(j,J){let X=typeof j==="number"?this.entities.get(j):j;if(!X)return!1;if(J?.cascade??!0){let Z=this.hierarchyManager.getDescendants(X.id);for(let _ of[...Z].reverse())this.removeEntityInternal(_)}return this.removeEntityInternal(X.id)}removeEntityInternal(j){let J=this.entities.get(j);if(!J)return!1;this.hierarchyManager.removeEntity(j);for(let X of Object.keys(J.components)){let Y=J.components[X];if(Y!==void 0){let Z=this.removedCallbacks.get(X);if(Z)for(let _ of[...Z])_(Y,J)}this.componentIndices.get(X)?.delete(J.id)}return this.entities.delete(J.id)}getEntity(j){return this.entities.get(j)}onComponentAdded(j,J){if(!this.addedCallbacks.has(j))this.addedCallbacks.set(j,new Set);return this.addedCallbacks.get(j).add(J),()=>{this.addedCallbacks.get(j)?.delete(J)}}onComponentRemoved(j,J){if(!this.removedCallbacks.has(j))this.removedCallbacks.set(j,new Set);return this.removedCallbacks.get(j).add(J),()=>{this.removedCallbacks.get(j)?.delete(J)}}spawnChild(j,J){let X=this.createEntity();return this.addComponents(X,J),this.setParent(X.id,j),X}setParent(j,J){return this.hierarchyManager.setParent(j,J),this}removeParent(j){return this.hierarchyManager.removeParent(j)}getParent(j){return this.hierarchyManager.getParent(j)}getChildren(j){return this.hierarchyManager.getChildren(j)}getChildAt(j,J){return this.hierarchyManager.getChildAt(j,J)}getChildIndex(j,J){return this.hierarchyManager.getChildIndex(j,J)}getAncestors(j){return this.hierarchyManager.getAncestors(j)}getDescendants(j){return this.hierarchyManager.getDescendants(j)}getRoot(j){return this.hierarchyManager.getRoot(j)}getSiblings(j){return this.hierarchyManager.getSiblings(j)}isDescendantOf(j,J){return this.hierarchyManager.isDescendantOf(j,J)}isAncestorOf(j,J){return this.hierarchyManager.isAncestorOf(j,J)}getRootEntities(){return this.hierarchyManager.getRootEntities()}forEachInHierarchy(j,J){this.hierarchyManager.forEachInHierarchy(j,J)}hierarchyIterator(j){return this.hierarchyManager.hierarchyIterator(j)}}class L{handlers=new Map;subscribe(j,J){return this.addHandler(j,J,!1)}once(j,J){return this.addHandler(j,J,!0)}unsubscribe(j,J){let X=this.handlers.get(j);if(!X)return!1;let Y=X.findIndex((Z)=>Z.callback===J);if(Y===-1)return!1;return X.splice(Y,1),!0}addHandler(j,J,X){if(!this.handlers.has(j))this.handlers.set(j,[]);let Y={callback:J,once:X};return this.handlers.get(j).push(Y),()=>{let Z=this.handlers.get(j);if(Z){let _=Z.indexOf(Y);if(_!==-1)Z.splice(_,1)}}}publish(j,J){let X=this.handlers.get(j);if(!X)return;let Y=[...X],Z=[];for(let _ of Y)if(_.callback(J),_.once)Z.push(_);if(Z.length>0)for(let _ of Z){let F=X.indexOf(_);if(F!==-1)X.splice(F,1)}}clear(){this.handlers.clear()}clearEvent(j){this.handlers.delete(j)}}function p(j){return typeof j==="object"&&j!==null&&"factory"in j&&typeof j.factory==="function"}function C(j,J){let X=[],Y=new Set,Z=new Set;function _(F,$=[]){if(Y.has(F))return;if(Z.has(F))throw Error(`Circular resource dependency: ${[...$,F].join(" -> ")}`);Z.add(F);for(let G of J(F))if(j.includes(G))_(G,[...$,F]);Z.delete(F),Y.add(F),X.push(F)}for(let F of j)_(F);return X}class z{resources=new Map;resourceFactories=new Map;resourceDependencies=new Map;resourceDisposers=new Map;initializedResourceKeys=new Set;add(j,J){if(p(J)){if(this.resourceFactories.set(j,J.factory),this.resourceDependencies.set(j,J.dependsOn??[]),J.onDispose)this.resourceDisposers.set(j,J.onDispose)}else if(this._isFactoryFunction(J))this.resourceFactories.set(j,J),this.resourceDependencies.set(j,[]);else this.resources.set(j,J),this.initializedResourceKeys.add(j),this.resourceDependencies.set(j,[]);return this}_isFactoryFunction(j){if(typeof j!=="function")return!1;let J=j.toString();if(J.startsWith("class "))return!1;if(J.includes("[native code]"))return!1;if(j.prototype){let X=Object.getOwnPropertyNames(j.prototype);if(X.length>1||X.length===1&&X[0]!=="constructor")return!1}if(j.name&&j.name[0]===j.name[0].toUpperCase()&&j.name.length>1){if(J.includes("this.")||J.includes("new "))return!1}return!0}get(j,J){let X=this.resources.get(j);if(X!==void 0)return X;let Y=this.resourceFactories.get(j);if(Y===void 0)throw Error(`Resource ${String(j)} not found`);let Z=Y(J);if(!(Z instanceof Promise))this.resources.set(j,Z),this.initializedResourceKeys.add(j);return Z}has(j){return this.resources.has(j)||this.resourceFactories.has(j)}remove(j){let J=this.resources.delete(j),X=this.resourceFactories.delete(j);return this.resourceDependencies.delete(j),this.resourceDisposers.delete(j),this.initializedResourceKeys.delete(j),J||X}getKeys(){let j=new Set([...this.resources.keys(),...this.resourceFactories.keys()]);return Array.from(j)}needsInitialization(j){return this.resourceFactories.has(j)&&!this.initializedResourceKeys.has(j)}getPendingInitializationKeys(){return Array.from(this.resourceFactories.keys()).filter((j)=>!this.initializedResourceKeys.has(j))}async initializeResource(j,J){if(!this.resourceFactories.has(j)||this.initializedResourceKeys.has(j))return;let Y=await this.resourceFactories.get(j)(J);this.resources.set(j,Y),this.initializedResourceKeys.add(j),this.resourceFactories.delete(j)}async initializeResources(j,...J){let X=J.length===0?this.getPendingInitializationKeys():J.map((Z)=>Z);if(X.length===0)return;let Y=C(X,(Z)=>this.resourceDependencies.get(Z)??[]);for(let Z of Y)await this.initializeResource(Z,j)}getDependencies(j){return this.resourceDependencies.get(j)??[]}async disposeResource(j,J){let X=j;if(!this.resources.has(X)&&!this.resourceFactories.has(X))return!1;if(this.initializedResourceKeys.has(X)){let Y=this.resourceDisposers.get(X),Z=this.resources.get(X);if(Y&&Z!==void 0)await Y(Z,J)}return this.resources.delete(X),this.resourceFactories.delete(X),this.resourceDependencies.delete(X),this.resourceDisposers.delete(X),this.initializedResourceKeys.delete(X),!0}async disposeResources(j){let J=Array.from(this.initializedResourceKeys);if(J.length===0)return;let X=C(J,(Y)=>this.resourceDependencies.get(Y)??[]).reverse();for(let Y of X)await this.disposeResource(Y,j)}}class E{assets=new Map;groups=new Map;eventBus=null;setEventBus(j){this.eventBus=j}register(j,J){if(this.assets.set(j,{definition:J,status:"pending"}),J.group){let X=this.groups.get(J.group)??new Set;X.add(j),this.groups.set(J.group,X)}}async loadEagerAssets(){let j=[];for(let[J,X]of this.assets)if(X.definition.eager&&X.status==="pending")j.push(J);await Promise.all(j.map((J)=>this.loadAsset(J)))}async loadAsset(j){let J=j,X=this.assets.get(J);if(!X)throw Error(`Asset '${J}' not found`);if(X.status==="loaded"&&X.value!==void 0)return X.value;if(X.status==="loading"&&X.loadPromise)return X.loadPromise;if(X.status==="failed")X.status="pending";X.status="loading",X.loadPromise=X.definition.loader();try{let Y=await X.loadPromise;return X.value=Y,X.status="loaded",X.loadPromise=void 0,this.eventBus?.publish("assetLoaded",{key:J}),this.checkGroupProgress(X.definition.group),Y}catch(Y){let Z=Y instanceof Error?Y:Error(String(Y));throw X.status="failed",X.error=Z,X.loadPromise=void 0,this.eventBus?.publish("assetFailed",{key:J,error:Z}),Z}}async loadAssetGroup(j){let J=this.groups.get(j);if(!J||J.size===0)throw Error(`Asset group '${j}' not found or empty`);await Promise.all(Array.from(J).map((X)=>this.loadAsset(X)))}get(j){let J=j,X=this.assets.get(J);if(!X)throw Error(`Asset '${J}' not found`);if(X.status!=="loaded"||X.value===void 0)throw Error(`Asset '${J}' is not loaded (status: ${X.status})`);return X.value}getOrUndefined(j){let J=j,X=this.assets.get(J);if(!X||X.status!=="loaded")return;return X.value}getHandle(j){let J=j,X=this.assets.get(J);if(!X)throw Error(`Asset '${J}' not found`);let Y=this;return{get status(){return X.status},get isLoaded(){return X.status==="loaded"},get(){return Y.get(j)},getOrUndefined(){return Y.getOrUndefined(j)}}}getStatus(j){let J=j,X=this.assets.get(J);if(!X)throw Error(`Asset '${J}' not found`);return X.status}isLoaded(j){let J=j;return this.assets.get(J)?.status==="loaded"}isGroupLoaded(j){let J=this.groups.get(j);if(!J||J.size===0)return!1;for(let X of J){let Y=this.assets.get(X);if(!Y||Y.status!=="loaded")return!1}return!0}getGroupProgress(j){let J=this.groups.get(j);if(!J||J.size===0)return 0;let X=0;for(let Y of J)if(this.assets.get(Y)?.status==="loaded")X++;return X/J.size}getGroupProgressDetails(j){let J=this.groups.get(j);if(!J||J.size===0)return{loaded:0,total:0,progress:0};let X=0;for(let Z of J)if(this.assets.get(Z)?.status==="loaded")X++;let Y=J.size;return{loaded:X,total:Y,progress:X/Y}}checkGroupProgress(j){if(!j||!this.eventBus)return;let J=this.getGroupProgressDetails(j);if(this.eventBus.publish("assetGroupProgress",{group:j,...J}),J.loaded===J.total)this.eventBus.publish("assetGroupLoaded",{group:j})}createResource(){let j=this;return{getStatus(J){return j.getStatus(J)},isLoaded(J){return j.isLoaded(J)},isGroupLoaded(J){return j.isGroupLoaded(J)},getGroupProgress(J){return j.getGroupProgress(J)},get(J){return j.get(J)},getOrUndefined(J){return j.getOrUndefined(J)},getHandle(J){return j.getHandle(J)}}}getKeys(){return Array.from(this.assets.keys())}getGroupNames(){return Array.from(this.groups.keys())}getGroupKeys(j){let J=this.groups.get(j);return J?Array.from(J):[]}}class q{manager;constructor(j){this.manager=j}add(j,J){return this.manager.register(j,{loader:J,eager:!0}),this}addWithConfig(j,J){return this.manager.register(j,J),this}addGroup(j,J){for(let[X,Y]of Object.entries(J))this.manager.register(X,{loader:Y,eager:!1,group:j});return this}getManager(){return this.manager}}function K(j){return new q(j??new E)}class w{screens=new Map;currentScreen=null;screenStack=[];eventBus=null;assetManager=null;ecs=null;setDependencies(j,J,X){this.eventBus=j,this.assetManager=J,this.ecs=X}register(j,J){this.screens.set(j,{definition:J})}async setScreen(j,J){let X=j,Y=this.screens.get(X);if(!Y)throw Error(`Screen '${X}' not found`);await this.verifyRequiredAssets(Y.definition);while(this.screenStack.length>0){let _=this.screenStack.pop();if(_)await this.exitScreen(_.name)}if(this.currentScreen)await this.exitScreen(this.currentScreen.name);let Z=Y.definition.initialState(J);this.currentScreen={name:j,config:J,state:Z},await Y.definition.onEnter?.(J,this.ecs),this.eventBus?.publish("screenEnter",{screen:X,config:J})}async pushScreen(j,J){let X=j,Y=this.screens.get(X);if(!Y)throw Error(`Screen '${X}' not found`);if(await this.verifyRequiredAssets(Y.definition),this.currentScreen)this.screenStack.push(this.currentScreen);let Z=Y.definition.initialState(J);this.currentScreen={name:j,config:J,state:Z},await Y.definition.onEnter?.(J,this.ecs),this.eventBus?.publish("screenPush",{screen:X,config:J})}async popScreen(){if(this.screenStack.length===0)throw Error("Cannot pop screen: stack is empty");if(this.currentScreen){let j=this.currentScreen.name;await this.exitScreen(j),this.eventBus?.publish("screenPop",{screen:j})}this.currentScreen=this.screenStack.pop()??null}async exitScreen(j){let J=this.screens.get(j);if(J?.definition.onExit)await J.definition.onExit(this.ecs);this.eventBus?.publish("screenExit",{screen:j})}async verifyRequiredAssets(j){if(!this.assetManager)return;if(j.requiredAssets){for(let J of j.requiredAssets)if(!this.assetManager.isLoaded(J))await this.assetManager.loadAsset(J)}if(j.requiredAssetGroups){for(let J of j.requiredAssetGroups)if(!this.assetManager.isGroupLoaded(J))await this.assetManager.loadAssetGroup(J)}}getCurrentScreen(){return this.currentScreen?.name??null}getConfig(){if(!this.currentScreen)throw Error("No current screen");return this.currentScreen.config}getConfigOrNull(){return this.currentScreen?.config??null}getState(){if(!this.currentScreen)throw Error("No current screen");return this.currentScreen.state}getStateOrNull(){return this.currentScreen?.state??null}updateState(j){if(!this.currentScreen)throw Error("No current screen");let J=typeof j==="function"?j(this.currentScreen.state):j;this.currentScreen.state={...this.currentScreen.state,...J}}getStackDepth(){return this.screenStack.length}isOverlay(){return this.screenStack.length>0}isActive(j){if(this.currentScreen?.name===j)return!0;return this.screenStack.some((J)=>J.name===j)}isCurrent(j){return this.currentScreen?.name===j}createResource(){let j=this;return{get current(){return j.getCurrentScreen()},get config(){return j.getConfigOrNull()},get state(){return j.getStateOrNull()},set state(J){if(j.currentScreen)j.currentScreen.state=J},get stack(){return j.screenStack},get isOverlay(){return j.isOverlay()},get stackDepth(){return j.getStackDepth()},isActive(J){return j.isActive(J)},isCurrent(J){return j.isCurrent(J)}}}getScreenNames(){return Array.from(this.screens.keys())}hasScreen(j){return this.screens.has(j)}}class S{manager;constructor(j){this.manager=j}add(j,J){return this.manager.register(j,J),this}getManager(){return this.manager}}function R(j){return new S(j??new w)}class M{queries=new Map;entityManager;constructor(j){this.entityManager=j}addQuery(j,J){let X={definition:J,matchingEntities:new Set};this.queries.set(j,X);let Y=this.entityManager.getEntitiesWithQuery(J.with,J.without??[]);for(let Z of Y)X.matchingEntities.add(Z.id),J.onEnter?.(Z)}removeQuery(j){return this.queries.delete(j)}entityMatchesQuery(j,J){for(let X of J.with)if(!(X in j.components))return!1;if(J.without){for(let X of J.without)if(X in j.components)return!1}return!0}onComponentAdded(j,J){for(let[X,Y]of this.queries){let Z=Y.matchingEntities.has(j.id),_=this.entityMatchesQuery(j,Y.definition);if(!Z&&_)Y.matchingEntities.add(j.id),Y.definition.onEnter?.(j);else if(Z&&!_)Y.matchingEntities.delete(j.id),Y.definition.onExit?.(j.id)}}onComponentRemoved(j,J){for(let[X,Y]of this.queries){let Z=Y.matchingEntities.has(j.id),_=this.entityMatchesQuery(j,Y.definition);if(Z&&!_)Y.matchingEntities.delete(j.id),Y.definition.onExit?.(j.id);else if(!Z&&_)Y.matchingEntities.add(j.id),Y.definition.onEnter?.(j)}}onEntityRemoved(j){for(let[J,X]of this.queries)if(X.matchingEntities.has(j))X.matchingEntities.delete(j),X.definition.onExit?.(j)}recheckEntity(j){for(let[J,X]of this.queries){let Y=X.matchingEntities.has(j.id),Z=this.entityMatchesQuery(j,X.definition);if(!Y&&Z)X.matchingEntities.add(j.id),X.definition.onEnter?.(j);else if(Y&&!Z)X.matchingEntities.delete(j.id),X.definition.onExit?.(j.id)}}}class B{_label;_ecspresso;_bundle;queries={};processFunction;detachFunction;initializeFunction;eventHandlers;_priority=0;_isRegistered=!1;_groups=[];_inScreens;_excludeScreens;_requiredAssets;constructor(j,J=null,X=null){this._label=j;this._ecspresso=J;this._bundle=X}get label(){return this._label}get bundle(){return this._bundle}get ecspresso(){return this._ecspresso}_autoRegister(){if(this._isRegistered||!this._ecspresso)return;let j=this._buildSystemObject();x(j,this._ecspresso),this._isRegistered=!0}_buildSystemObject(){return this._createSystemObject()}_createSystemObject(){let j={label:this._label,entityQueries:this.queries,priority:this._priority};if(this.processFunction)j.process=this.processFunction;if(this.detachFunction)j.onDetach=this.detachFunction;if(this.initializeFunction)j.onInitialize=this.initializeFunction;if(this.eventHandlers)j.eventHandlers=this.eventHandlers;if(this._groups.length>0)j.groups=[...this._groups];if(this._inScreens)j.inScreens=this._inScreens;if(this._excludeScreens)j.excludeScreens=this._excludeScreens;if(this._requiredAssets)j.requiredAssets=this._requiredAssets;return j}setPriority(j){return this._priority=j,this}inGroup(j){if(!this._groups.includes(j))this._groups.push(j);return this}inScreens(j){return this._inScreens=[...j],this}excludeScreens(j){return this._excludeScreens=[...j],this}requiresAssets(j){return this._requiredAssets=[...j],this}addQuery(j,J){let X=this;return X.queries={...this.queries,[j]:J},X}setProcess(j){return this.processFunction=j,this}registerAndContinue(){if(!this._ecspresso)throw Error(`Cannot register system '${this._label}': SystemBuilder is not attached to an ECSpresso instance. Use Bundle.addSystem() or ECSpresso.addSystem() instead.`);return this._autoRegister(),this._ecspresso}and(){if(this._ecspresso)return this._autoRegister(),this._ecspresso;if(this._bundle)return this._bundle;throw Error(`Cannot use and() on system '${this._label}': not attached to ECSpresso or Bundle.`)}setOnDetach(j){return this.detachFunction=j,this}setOnInitialize(j){return this.initializeFunction=j,this}setEventHandlers(j){return this.eventHandlers=j,this}build(j){let J=this._createSystemObject();if(this._ecspresso)x(J,this._ecspresso);if(j)x(J,j);return this}}function x(j,J){J._registerSystem(j)}function v(j,J){return new B(j,J)}function O(j,J){return new B(j,null,J)}var f="0.6.0";var m={};class D{static VERSION=f;_entityManager;_eventBus;_resourceManager;_systems=[];_sortedSystems=[];_installedBundles=new Set;_disabledGroups=new Set;_assetManager=null;_screenManager=null;_reactiveQueryManager;_postUpdateHooks=[];constructor(){this._entityManager=new Q,this._eventBus=new L,this._resourceManager=new z,this._reactiveQueryManager=new M(this._entityManager),this._sortedSystems=[],this._setupReactiveQueryHooks()}_setupReactiveQueryHooks(){let j=0,J=new Set,X=()=>{for(let $ of J){let G=this._entityManager.getEntity($);if(G)this._reactiveQueryManager.recheckEntity(G)}J.clear()},Y=this._entityManager.addComponent.bind(this._entityManager);this._entityManager.addComponent=($,G,U)=>{let H=Y($,G,U),V=typeof $==="number"?$:$.id;if(j>0)J.add(V);else{let A=this._entityManager.getEntity(V);if(A)this._reactiveQueryManager.onComponentAdded(A,G)}return H};let Z=this._entityManager.addComponents.bind(this._entityManager);this._entityManager.addComponents=($,G)=>{j++;let U=Z($,G);if(j--,j===0)X();return U};let _=this._entityManager.removeComponent.bind(this._entityManager);this._entityManager.removeComponent=($,G)=>{let U=typeof $==="number"?$:$.id,H=this._entityManager.getEntity(U),V=_($,G);if(H)this._reactiveQueryManager.onComponentRemoved(H,G);return V};let F=this._entityManager.removeEntity.bind(this._entityManager);this._entityManager.removeEntity=($,G)=>{let U=typeof $==="number"?$:$.id;if(this._entityManager.getEntity(U)){if(G?.cascade??!0){let A=this._entityManager.getDescendants(U);for(let b of A)this._reactiveQueryManager.onEntityRemoved(b)}this._reactiveQueryManager.onEntityRemoved(U)}return F($,G)}}static create(){return new N}addSystem(j){return v(j,this)}update(j){let J=this._screenManager?.getCurrentScreen()??null;for(let X of this._sortedSystems){if(!X.process)continue;if(X.groups?.length){let F=!1;for(let $ of X.groups)if(this._disabledGroups.has($)){F=!0;break}if(F)continue}if(X.inScreens?.length){if(J===null||!X.inScreens.includes(J))continue}if(X.excludeScreens?.length){if(J!==null&&X.excludeScreens.includes(J))continue}if(X.requiredAssets?.length&&this._assetManager){let F=!0;for(let $ of X.requiredAssets)if(!this._assetManager.isLoaded($)){F=!1;break}if(!F)continue}let Y={},Z=!1,_=!1;if(X.entityQueries)for(let F in X.entityQueries){_=!0;let $=X.entityQueries[F];if($){if(Y[F]=this._entityManager.getEntitiesWithQuery($.with,$.without||[]),Y[F].length)Z=!0}}if(Z)X.process(Y,j,this);else if(!_)X.process(m,j,this)}for(let X of this._postUpdateHooks)X(this,j)}async initialize(){if(await this.initializeResources(),this._assetManager)this._assetManager.setEventBus(this._eventBus),await this._assetManager.loadEagerAssets(),this._resourceManager.add("$assets",this._assetManager.createResource());if(this._screenManager)this._screenManager.setDependencies(this._eventBus,this._assetManager,this),this._resourceManager.add("$screen",this._screenManager.createResource());for(let j of this._systems)await j.onInitialize?.(this)}async initializeResources(...j){await this._resourceManager.initializeResources(this,...j)}_sortSystems(){this._sortedSystems=[...this._systems].sort((j,J)=>{let X=j.priority??0;return(J.priority??0)-X})}updateSystemPriority(j,J){let X=this._systems.find((Y)=>Y.label===j);if(!X)return!1;return X.priority=J,this._sortSystems(),!0}disableSystemGroup(j){this._disabledGroups.add(j)}enableSystemGroup(j){this._disabledGroups.delete(j)}isSystemGroupEnabled(j){return!this._disabledGroups.has(j)}getSystemsInGroup(j){return this._systems.filter((J)=>J.groups?.includes(j)).map((J)=>J.label)}removeSystem(j){let J=this._systems.findIndex((Y)=>Y.label===j);if(J===-1)return!1;let X=this._systems[J];if(!X)return!1;if(X.onDetach)X.onDetach(this);return this._systems.splice(J,1),this._sortSystems(),!0}_registerSystem(j){if(this._systems.push(j),this._sortSystems(),!j.eventHandlers)return;for(let J in j.eventHandlers){let X=j.eventHandlers[J]?.handler;if(X)this._eventBus.subscribe(J,(Y)=>{X(Y,this)})}}hasResource(j){return this._resourceManager.has(j)}getResource(j){let J=this._resourceManager.get(j,this);if(!J)throw Error(`Resource '${String(j)}' not found. Available resources: [${this.getResourceKeys().map((X)=>String(X)).join(", ")}]`);return J}addResource(j,J){return this._resourceManager.add(j,J),this}removeResource(j){return this._resourceManager.remove(j)}async disposeResource(j){return this._resourceManager.disposeResource(j,this)}async disposeResources(){return this._resourceManager.disposeResources(this)}updateResource(j,J){let X=this.getResource(j),Y=J(X);return this._resourceManager.add(j,Y),this}getResourceKeys(){return this._resourceManager.getKeys()}resourceNeedsInitialization(j){return this._resourceManager.needsInitialization(j)}hasComponent(j,J){return this._entityManager.getComponent(j,J)!==null}spawn(j){let J=this._entityManager.createEntity();return this._entityManager.addComponents(J,j),J}getEntitiesWithQuery(j,J=[]){return this._entityManager.getEntitiesWithQuery(j,J)}removeEntity(j,J){return this._entityManager.removeEntity(j,J)}spawnChild(j,J){let X=this._entityManager.spawnChild(j,J);return this._emitHierarchyChanged(X.id,null,j),X}setParent(j,J){let X=this._entityManager.getParent(j);return this._entityManager.setParent(j,J),this._emitHierarchyChanged(j,X,J),this}removeParent(j){let J=this._entityManager.getParent(j),X=this._entityManager.removeParent(j);if(X)this._emitHierarchyChanged(j,J,null);return X}getParent(j){return this._entityManager.getParent(j)}getChildren(j){return this._entityManager.getChildren(j)}getChildAt(j,J){return this._entityManager.getChildAt(j,J)}getChildIndex(j,J){return this._entityManager.getChildIndex(j,J)}getAncestors(j){return this._entityManager.getAncestors(j)}getDescendants(j){return this._entityManager.getDescendants(j)}getRoot(j){return this._entityManager.getRoot(j)}getSiblings(j){return this._entityManager.getSiblings(j)}isDescendantOf(j,J){return this._entityManager.isDescendantOf(j,J)}isAncestorOf(j,J){return this._entityManager.isAncestorOf(j,J)}getRootEntities(){return this._entityManager.getRootEntities()}forEachInHierarchy(j,J){this._entityManager.forEachInHierarchy(j,J)}hierarchyIterator(j){return this._entityManager.hierarchyIterator(j)}_emitHierarchyChanged(j,J,X){this._eventBus.publish("hierarchyChanged",{entityId:j,oldParent:J,newParent:X})}get installedBundles(){return Array.from(this._installedBundles)}get entityManager(){return this._entityManager}get eventBus(){return this._eventBus}onComponentAdded(j,J){return this._entityManager.onComponentAdded(j,J)}onComponentRemoved(j,J){return this._entityManager.onComponentRemoved(j,J)}addReactiveQuery(j,J){this._reactiveQueryManager.addQuery(j,J)}removeReactiveQuery(j){return this._reactiveQueryManager.removeQuery(j)}on(j,J){return this._eventBus.subscribe(j,J)}off(j,J){return this._eventBus.unsubscribe(j,J)}onPostUpdate(j){return this._postUpdateHooks.push(j),()=>{let J=this._postUpdateHooks.indexOf(j);if(J!==-1)this._postUpdateHooks.splice(J,1)}}getAsset(j){if(!this._assetManager)throw Error("Asset manager not configured. Use withAssets() in builder.");return this._assetManager.get(j)}getAssetOrUndefined(j){return this._assetManager?.getOrUndefined(j)}getAssetHandle(j){if(!this._assetManager)throw Error("Asset manager not configured. Use withAssets() in builder.");return this._assetManager.getHandle(j)}isAssetLoaded(j){return this._assetManager?.isLoaded(j)??!1}async loadAsset(j){if(!this._assetManager)throw Error("Asset manager not configured. Use withAssets() in builder.");return this._assetManager.loadAsset(j)}async loadAssetGroup(j){if(!this._assetManager)throw Error("Asset manager not configured. Use withAssets() in builder.");return this._assetManager.loadAssetGroup(j)}isAssetGroupLoaded(j){return this._assetManager?.isGroupLoaded(j)??!1}getAssetGroupProgress(j){return this._assetManager?.getGroupProgress(j)??0}async setScreen(j,J){if(!this._screenManager)throw Error("Screen manager not configured. Use withScreens() in builder.");return this._screenManager.setScreen(j,J)}async pushScreen(j,J){if(!this._screenManager)throw Error("Screen manager not configured. Use withScreens() in builder.");return this._screenManager.pushScreen(j,J)}async popScreen(){if(!this._screenManager)throw Error("Screen manager not configured. Use withScreens() in builder.");return this._screenManager.popScreen()}getCurrentScreen(){return this._screenManager?.getCurrentScreen()??null}getScreenConfig(){if(!this._screenManager)throw Error("Screen manager not configured. Use withScreens() in builder.");return this._screenManager.getConfig()}getScreenConfigOrNull(){return this._screenManager?.getConfigOrNull()??null}getScreenState(){if(!this._screenManager)throw Error("Screen manager not configured. Use withScreens() in builder.");return this._screenManager.getState()}getScreenStateOrNull(){return this._screenManager?.getStateOrNull()??null}updateScreenState(j){if(!this._screenManager)throw Error("Screen manager not configured. Use withScreens() in builder.");this._screenManager.updateState(j)}isCurrentScreen(j){return this._screenManager?.isCurrent(j)??!1}isScreenActive(j){return this._screenManager?.isActive(j)??!1}getScreenStackDepth(){return this._screenManager?.getStackDepth()??0}_setAssetManager(j){this._assetManager=j}_setScreenManager(j){this._screenManager=j}_installBundle(j){if(this._installedBundles.has(j.id))return this;this._installedBundles.add(j.id),j.registerSystemsWithEcspresso(this);let J=j.getResources();for(let[X,Y]of J.entries())this._resourceManager.add(X,Y);if(this._assetManager){let X=j.getAssets();for(let[Y,Z]of X.entries())this._assetManager.register(Y,Z)}if(this._screenManager){let X=j.getScreens();for(let[Y,Z]of X.entries())this._screenManager.register(Y,Z)}return this}}class N{ecspresso;assetConfigurator=null;screenConfigurator=null;pendingResources=[];constructor(){this.ecspresso=new D}withBundle(j){return this.ecspresso._installBundle(j),this}withResource(j,J){return this.pendingResources.push({key:j,value:J}),this}withAssets(j){let J=K();return j(J),this.assetConfigurator=J,this}withScreens(j){let J=R();return j(J),this.screenConfigurator=J,this}build(){for(let{key:j,value:J}of this.pendingResources)this.ecspresso.addResource(j,J);if(this.assetConfigurator)this.ecspresso._setAssetManager(this.assetConfigurator.getManager());if(this.screenConfigurator)this.ecspresso._setScreenManager(this.screenConfigurator.getManager());return this.ecspresso}}function c(){return`bundle_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,9)}`}class P{_systems=[];_resources=new Map;_assets=new Map;_assetGroups=new Map;_screens=new Map;_id;constructor(j){this._id=j||c()}get id(){return this._id}set id(j){this._id=j}addSystem(j){if(typeof j==="string"){let J=O(j,this);return this._systems.push(J),J}else return this._systems.push(j),j}addResource(j,J){return this._resources.set(j,J),this}addAsset(j,J,X){return this._assets.set(j,{loader:J,eager:X?.eager??!0,group:X?.group}),this}addAssetGroup(j,J){let X=new Map;for(let[Y,Z]of Object.entries(J))X.set(Y,Z),this._assets.set(Y,{loader:Z,eager:!1,group:j});return this._assetGroups.set(j,X),this}addScreen(j,J){return this._screens.set(j,J),this}getAssets(){return new Map(this._assets)}getScreens(){return new Map(this._screens)}_setResource(j,J){this._resources.set(j,J)}_setAsset(j,J){this._assets.set(j,J)}_setScreen(j,J){this._screens.set(j,J)}getSystems(){return this._systems.map((j)=>j.build())}registerSystemsWithEcspresso(j){for(let J of this._systems)J.build(j)}getResources(){return new Map(this._resources)}getResource(j){return this._resources.get(j)}getSystemBuilders(){return[...this._systems]}hasResource(j){return this._resources.has(j)}}function l(j,...J){if(J.length===0)return new P(j);let X=new P(j);for(let Y of J){for(let Z of Y.getSystemBuilders())X.addSystem(Z);for(let[Z,_]of Y.getResources().entries())X._setResource(Z,_);for(let[Z,_]of Y.getAssets().entries())X._setAsset(Z,_);for(let[Z,_]of Y.getScreens().entries())X._setScreen(Z,_)}return X}function Ej(j){return j}var bj=D;export{l as mergeBundles,bj as default,R as createScreenConfigurator,Ej as createQueryDefinition,K as createAssetConfigurator,B as SystemBuilder,w as ScreenManager,z as ResourceManager,W as HierarchyManager,L as EventBus,Q as EntityManager,P as Bundle,E as AssetManager};
2
2
 
3
- //# debugId=179E5389134FBDFC64756E2164756E21
3
+ //# debugId=00D10EC49F41135764756E2164756E21
4
4
  //# sourceMappingURL=index.js.map