@blac/core 2.0.0-rc-3 → 2.0.0-rc-4
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.
- package/dist/index.cjs.js +1 -1
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.d.ts +92 -24
- package/dist/index.es.js +312 -139
- package/dist/index.es.js.map +1 -1
- package/package.json +3 -2
- package/src/Blac.ts +226 -35
- package/src/BlocBase.ts +127 -19
package/dist/index.cjs.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var I=Object.defineProperty;var _=(d,e,t)=>e in d?I(d,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):d[e]=t;var s=(d,e,t)=>_(d,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=class o{constructor(e={}){s(this,"createdAt",Date.now());s(this,"blocInstanceMap",new Map);s(this,"isolatedBlocMap",new Map);s(this,"postChangesToDocument",!1);s(this,"log",(...e)=>{o.enableLog&&console.warn(`☢️ [Blac ${this.createdAt.toString()}]`,...e)});s(this,"warn",(e,...t)=>{o.enableLog&&console.warn(`🚨 [Blac ${String(o.instance.createdAt)}]`,e,...t)});s(this,"error",(e,...t)=>{o.enableLog&&console.error(`🚨 [Blac ${String(o.instance.createdAt)}]`,e,...t)});s(this,"resetInstance",()=>{this.log("Reset Blac instance");const e=new Map(this.blocInstanceMap),t=new Map(this.isolatedBlocMap);e.forEach(n=>{n._dispose()}),t.forEach(n=>{n.forEach(i=>{i._dispose()})}),this.blocInstanceMap.clear(),this.isolatedBlocMap.clear(),o.instance=new o({__unsafe_ignore_singleton:!0})});s(this,"disposeBloc",e=>{const t=e.constructor,n=this.createBlocInstanceMapKey(e._name,e._id);this.log(`[${e._name}:${String(e._id)}] disposeBloc called. Isolated: ${String(t.isolated)}`),t.isolated?(this.unregisterIsolatedBlocInstance(e),this.blocInstanceMap.delete(n)):this.unregisterBlocInstance(e),this.log("dispatched bloc",e)});s(this,"activateBloc",e=>{const t=e.constructor;(e.isIsolated?this.findIsolatedBlocInstance(t,e._id):this.findRegisteredBlocInstance(t,e._id))||(this.log(`[${e._name}:${String(e._id)}] activateBloc called. Isolated: ${String(e.isIsolated)}`),e.isIsolated?this.registerIsolatedBlocInstance(e):this.registerBlocInstance(e))});s(this,"getBloc",(e,t={})=>{const{id:n}=t,i=e,a=n??e.name;if(i.isolated){const l=this.findIsolatedBlocInstance(e,a);if(l)return this.log(`[${e.name}:${String(a)}] (getBloc) Found existing isolated instance.`,t),l;if(t.throwIfNotFound)throw new Error(`Isolated bloc ${e.name} not found`)}else{const l=this.findRegisteredBlocInstance(e,a);if(l)return this.log(`[${e.name}:${String(a)}] (getBloc) Found existing registered instance.`,t),l;if(t.throwIfNotFound)throw new Error(`Registered bloc ${e.name} not found`)}const r=this.createNewBlocInstance(e,a,t);return this.log(`[${e.name}:${String(a)}] (getBloc) No existing instance found. Creating new one.`,t,r),r});s(this,"getBlocOrThrow",(e,t={})=>{const n=e.isolated,i=t.id||e.name,a=n?this.findIsolatedBlocInstance(e,i):this.findRegisteredBlocInstance(e,i);if(a)return a;throw new Error(`Bloc ${e.name} not found`)});s(this,"getAllBlocs",(e,t={})=>{const n=[];if(this.blocInstanceMap.forEach(i=>{i.constructor===e&&n.push(i)}),t.searchIsolated!==!1){const i=this.isolatedBlocMap.get(e);i&&n.push(...i.map(a=>a))}return n});const{__unsafe_ignore_singleton:t=!1}=e;if(!t)return o.instance;o.instance=this}static getInstance(){return o.instance}createBlocInstanceMapKey(e,t){return`${e}:${String(t)}`}unregisterBlocInstance(e){const t=this.createBlocInstanceMapKey(e._name,e._id);this.blocInstanceMap.delete(t)}registerBlocInstance(e){const t=this.createBlocInstanceMapKey(e._name,e._id);this.blocInstanceMap.set(t,e)}findRegisteredBlocInstance(e,t){if(e.isolated)return;const i=this.createBlocInstanceMapKey(e.name,t);return this.blocInstanceMap.get(i)}registerIsolatedBlocInstance(e){const t=e.constructor,n=this.isolatedBlocMap.get(t);n?n.push(e):this.isolatedBlocMap.set(t,[e])}unregisterIsolatedBlocInstance(e){const t=e.constructor,n=this.isolatedBlocMap.get(t);if(n){const i=n.findIndex(a=>a._id===e._id);i!==-1&&n.splice(i,1),n.length===0&&this.isolatedBlocMap.delete(t)}}findIsolatedBlocInstance(e,t){if(!e.isolated)return;const i=this.isolatedBlocMap.get(e);return i?i.find(r=>r._id===t):void 0}createNewBlocInstance(e,t,n={}){const{props:i,instanceRef:a}=n,r=new e(i);return r._instanceRef=a,r.props=i||null,r._updateId(t),r.isIsolated?(this.registerIsolatedBlocInstance(r),r):(this.registerBlocInstance(r),r)}};s(o,"instance",new o),s(o,"getAllBlocs",o.instance.getAllBlocs),s(o,"enableLog",!1),s(o,"log",o.instance.log),s(o,"warn",o.instance.warn),s(o,"error",o.instance.error),s(o,"resetInstance",o.instance.resetInstance),s(o,"activateBloc",o.instance.activateBloc),s(o,"getBloc",o.instance.getBloc),s(o,"getBlocOrThrow",o.instance.getBlocOrThrow);let c=o;class p{constructor(e){s(this,"bloc");s(this,"_observers",new Set);this.bloc=e}get size(){return this._observers.size}get observers(){return this._observers}subscribe(e){return c.log("BlacObservable.subscribe: Subscribing observer.",this.bloc,e),this._observers.add(e),e.lastState||(e.lastState=e.dependencyArray?e.dependencyArray(this.bloc.state):[]),()=>{c.log("BlacObservable.subscribe: Unsubscribing observer.",this.bloc,e),this.unsubscribe(e)}}unsubscribe(e){this._observers.delete(e),this.size===0&&(c.log("BlacObservable.unsubscribe: No observers left. Disposing bloc.",this.bloc),this.bloc._dispose())}notify(e,t,n){this._observers.forEach(i=>{let a=!1;if(i.dependencyArray){const r=i.lastState||[],l=i.dependencyArray(e);for(let u=0;u<l.length;u++){const f=l[u],B=r[u]||[];for(let g=0;g<f.length;g++)if(!Object.is(f[g],B[g])){a=!0;break}}i.lastState=l}else a=!0;a&&i.fn(e,t,n)})}clear(){this._observers.forEach(e=>{this.unsubscribe(e)}),this._observers.clear()}}class h{constructor(e){s(this,"uid",crypto.randomUUID());s(this,"defaultDependencySelector");s(this,"_isolated",!1);s(this,"_observer");s(this,"_blac",c.getInstance());s(this,"_id");s(this,"_instanceRef");s(this,"_keepAlive",!1);s(this,"_createdAt",Date.now());s(this,"_state");s(this,"_oldState");s(this,"props",null);s(this,"_updateId",e=>{const t=this._id;!e||e===t||(this._id=e)});s(this,"onDispose");s(this,"_consumers",new Set);s(this,"_addConsumer",e=>{this._consumers.has(e)||(this._consumers.add(e),c.log("BlocBase._addConsumer",this,e))});s(this,"_removeConsumer",e=>{this._consumers.has(e)&&(this._consumers.delete(e),c.log("BlocBase._removeConsumer",this,e))});s(this,"lastUpdate",Date.now());s(this,"_pushState",(e,t,n)=>{this._state=e,this._observer.notify(e,t,n),this.lastUpdate=Date.now()});this._state=e,this._observer=new p(this),c.log("Bloc Created",this),this._id=this.constructor.name;const t=this.constructor;this._keepAlive=t.keepAlive,this._isolated=t.isolated}get isIsolated(){return this._isolated}get isKeepAlive(){return this._keepAlive}get state(){return this._state}get _name(){return this.constructor.name}_dispose(){var e;this._observer.clear(),(e=this.onDispose)==null||e.call(this),c.log("BlocBase._dispose",this),c.instance.disposeBloc(this)}}s(h,"isolated",!1),s(h,"keepAlive",!1);class b extends h{constructor(){super(...arguments);s(this,"eventHandlers",new Map);s(this,"add",async t=>{const n=t.constructor,i=this.eventHandlers.get(n);if(i){const a=r=>{const l=this.state;this._pushState(r,l,t)};try{await i(t,a)}catch(r){c.error(`[Bloc ${this._name}:${String(this._id)}] Error in event handler for '${n.name}':`,r,"Action:",t)}}else{const a=t.constructor.name||"UnnamedConstructor";c.warn(`[Bloc ${this._name}:${String(this._id)}] No handler registered for action type: '${a}'. Action was:`,t)}})}on(t,n){this.eventHandlers.has(t)&&c.warn(`[Bloc ${this._name}:${String(this._id)}] Handler for event '${t.name}' already registered. It will be overwritten.`),this.eventHandlers.set(t,n)}}class w extends h{emit(e){if(Object.is(e,this.state))return;const t=this.state,n=e;this._pushState(n,t)}patch(e,t=!1){if(typeof this.state!="object"||this.state===null){c.warn("Cubit.patch: was called on a cubit where the state is not an object. This is a no-op.");return}let n=!1;if(t)n=!0;else for(const i in e)if(Object.prototype.hasOwnProperty.call(e,i)){const r=this.state[i];if(!Object.is(e[i],r)){n=!0;break}}n&&this.emit({...this.state,...e})}}exports.Blac=c;exports.BlacObservable=p;exports.Bloc=b;exports.BlocBase=h;exports.Cubit=w;
|
|
1
|
+
"use strict";var w=Object.defineProperty;var y=(d,e,t)=>e in d?w(d,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):d[e]=t;var n=(d,e,t)=>y(d,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const h=class h{getInstance(){return h._instance||(h._instance=new l({__unsafe_ignore_singleton:!0})),h._instance}setInstance(e){h._instance=e}resetInstance(){const e=h._instance;h._instance=new l({__unsafe_ignore_singleton:!0});for(const t of e.keepAliveBlocs)h._instance.keepAliveBlocs.add(t),h._instance.uidRegistry.set(t.uid,t)}};n(h,"_instance");let B=h,u=new B;function m(d){u=d}const r=class r{constructor(e={}){n(this,"createdAt",Date.now());n(this,"blocInstanceMap",new Map);n(this,"isolatedBlocMap",new Map);n(this,"isolatedBlocIndex",new Map);n(this,"uidRegistry",new Map);n(this,"keepAliveBlocs",new Set);n(this,"postChangesToDocument",!1);n(this,"log",(...e)=>{r.enableLog&&console.warn(`☢️ [Blac ${this.createdAt.toString()}]`,...e)});n(this,"warn",(e,...t)=>{r.enableLog&&console.warn(`🚨 [Blac ${String(r.instance.createdAt)}]`,e,...t)});n(this,"error",(e,...t)=>{r.enableLog&&console.error(`🚨 [Blac ${String(r.instance.createdAt)}]`,e,...t)});n(this,"resetInstance",()=>{this.log("Reset Blac instance");const e=new Map(this.blocInstanceMap),t=new Map(this.isolatedBlocMap);e.forEach(s=>{s._keepAlive||s._dispose()}),t.forEach(s=>{s.forEach(i=>{i._keepAlive||i._dispose()})}),this.blocInstanceMap.clear(),this.isolatedBlocMap.clear(),this.isolatedBlocIndex.clear(),u.resetInstance()});n(this,"disposeBloc",e=>{const t=e.constructor,s=this.createBlocInstanceMapKey(e._name,e._id);this.log(`[${e._name}:${String(e._id)}] disposeBloc called. Isolated: ${String(t.isolated)}`),t.isolated?(this.unregisterIsolatedBlocInstance(e),this.blocInstanceMap.delete(s)):this.unregisterBlocInstance(e),this.log("dispatched bloc",e)});n(this,"activateBloc",e=>{const t=e.constructor;(e.isIsolated?this.findIsolatedBlocInstance(t,e._id):this.findRegisteredBlocInstance(t,e._id))||(this.log(`[${e._name}:${String(e._id)}] activateBloc called. Isolated: ${String(e.isIsolated)}`),e.isIsolated?this.registerIsolatedBlocInstance(e):this.registerBlocInstance(e))});n(this,"getBloc",(e,t={})=>{const{id:s}=t,i=e,a=s??e.name;if(i.isolated){const c=this.findIsolatedBlocInstance(e,a);if(c)return this.log(`[${e.name}:${String(a)}] (getBloc) Found existing isolated instance.`,t),c;if(t.throwIfNotFound)throw new Error(`Isolated bloc ${e.name} not found`)}else{const c=this.findRegisteredBlocInstance(e,a);if(c)return this.log(`[${e.name}:${String(a)}] (getBloc) Found existing registered instance.`,t),c;if(t.throwIfNotFound)throw new Error(`Registered bloc ${e.name} not found`)}const o=this.createNewBlocInstance(e,a,t);return this.log(`[${e.name}:${String(a)}] (getBloc) No existing instance found. Creating new one.`,t,o),o});n(this,"getBlocOrThrow",(e,t={})=>{const s=e.isolated,i=t.id||e.name,a=s?this.findIsolatedBlocInstance(e,i):this.findRegisteredBlocInstance(e,i);if(a)return a;throw new Error(`Bloc ${e.name} not found`)});n(this,"getAllBlocs",(e,t={})=>{const s=[];if(this.blocInstanceMap.forEach(i=>{i.constructor===e&&s.push(i)}),t.searchIsolated!==!1){const i=this.isolatedBlocMap.get(e);i&&s.push(...i.map(a=>a))}return s});n(this,"disposeKeepAliveBlocs",e=>{const t=[];for(const s of this.keepAliveBlocs)(!e||s.constructor===e)&&t.push(s);t.forEach(s=>s._dispose())});n(this,"disposeBlocs",e=>{const t=[];for(const s of this.blocInstanceMap.values())e(s)&&t.push(s);for(const s of this.isolatedBlocMap.values())for(const i of s)e(i)&&t.push(i);t.forEach(s=>s._dispose())});n(this,"getMemoryStats",()=>({totalBlocs:this.uidRegistry.size,registeredBlocs:this.blocInstanceMap.size,isolatedBlocs:Array.from(this.isolatedBlocMap.values()).reduce((e,t)=>e+t.length,0),keepAliveBlocs:this.keepAliveBlocs.size,isolatedBlocTypes:this.isolatedBlocMap.size}));n(this,"validateConsumers",()=>{for(const e of this.uidRegistry.values())e._consumers.size===0&&!e._keepAlive&&setTimeout(()=>{e._consumers.size===0&&!e._keepAlive&&e._dispose()},1e3)});const{__unsafe_ignore_singleton:t=!1}=e;if(!t)return r.instance;u.setInstance(this)}static get instance(){return u.getInstance()}static get getAllBlocs(){return r.instance.getAllBlocs}static get log(){return r.instance.log}static getInstance(){return u.getInstance()}static get warn(){return r.instance.warn}static get error(){return r.instance.error}createBlocInstanceMapKey(e,t){return`${e}:${String(t)}`}unregisterBlocInstance(e){const t=this.createBlocInstanceMapKey(e._name,e._id);this.blocInstanceMap.delete(t),this.uidRegistry.delete(e.uid),this.keepAliveBlocs.delete(e)}registerBlocInstance(e){const t=this.createBlocInstanceMapKey(e._name,e._id);this.blocInstanceMap.set(t,e),this.uidRegistry.set(e.uid,e),e._keepAlive&&this.keepAliveBlocs.add(e)}findRegisteredBlocInstance(e,t){if(e.isolated)return;const i=this.createBlocInstanceMapKey(e.name,t);return this.blocInstanceMap.get(i)}registerIsolatedBlocInstance(e){const t=e.constructor,s=this.isolatedBlocMap.get(t);s?s.push(e):this.isolatedBlocMap.set(t,[e]),this.isolatedBlocIndex.set(e.uid,e),this.uidRegistry.set(e.uid,e),e._keepAlive&&this.keepAliveBlocs.add(e)}unregisterIsolatedBlocInstance(e){const t=e.constructor,s=this.isolatedBlocMap.get(t);if(s){const i=s.findIndex(a=>a.uid===e.uid);i!==-1&&s.splice(i,1),s.length===0&&this.isolatedBlocMap.delete(t)}this.isolatedBlocIndex.delete(e.uid),this.uidRegistry.delete(e.uid),this.keepAliveBlocs.delete(e)}findIsolatedBlocInstance(e,t){if(!e.isolated)return;const i=this.isolatedBlocMap.get(e);return i?i.find(o=>o._id===t):void 0}findIsolatedBlocInstanceByUid(e){return this.isolatedBlocIndex.get(e)}createNewBlocInstance(e,t,s={}){const{props:i,instanceRef:a}=s,o=new e(i);return o._instanceRef=a,o.props=i||null,o._updateId(t),o._setDisposalHandler(c=>this.disposeBloc(c)),o.isIsolated?(this.registerIsolatedBlocInstance(o),o):(this.registerBlocInstance(o),o)}static get activateBloc(){return r.instance.activateBloc}static get getBloc(){return r.instance.getBloc}static get getBlocOrThrow(){return r.instance.getBlocOrThrow}static get disposeKeepAliveBlocs(){return r.instance.disposeKeepAliveBlocs}static get disposeBlocs(){return r.instance.disposeBlocs}static get getMemoryStats(){return r.instance.getMemoryStats}static get validateConsumers(){return r.instance.validateConsumers}};n(r,"enableLog",!1),n(r,"resetInstance",()=>{u.resetInstance()});let l=r;class I{constructor(e){n(this,"bloc");n(this,"_observers",new Set);this.bloc=e}get size(){return this._observers.size}get observers(){return this._observers}subscribe(e){return l.log("BlacObservable.subscribe: Subscribing observer.",this.bloc,e),this._observers.add(e),e.lastState||(e.lastState=e.dependencyArray?e.dependencyArray(this.bloc.state):[]),()=>{l.log("BlacObservable.subscribe: Unsubscribing observer.",this.bloc,e),this.unsubscribe(e)}}unsubscribe(e){this._observers.delete(e),this.size===0&&(l.log("BlacObservable.unsubscribe: No observers left. Disposing bloc.",this.bloc),this.bloc._dispose())}notify(e,t,s){this._observers.forEach(i=>{let a=!1;if(i.dependencyArray){const o=i.lastState||[],c=i.dependencyArray(e);for(let f=0;f<c.length;f++){const _=c[f],v=o[f]||[];for(let g=0;g<_.length;g++)if(!Object.is(_[g],v[g])){a=!0;break}}i.lastState=c}else a=!0;a&&i.fn(e,t,s)})}clear(){this._observers.forEach(e=>{this.unsubscribe(e)}),this._observers.clear()}}class p{constructor(e){n(this,"uid",crypto.randomUUID());n(this,"defaultDependencySelector");n(this,"_isolated",!1);n(this,"_observer");n(this,"_id");n(this,"_instanceRef");n(this,"_keepAlive",!1);n(this,"_createdAt",Date.now());n(this,"_state");n(this,"_oldState");n(this,"props",null);n(this,"_updateId",e=>{const t=this._id;!e||e===t||(this._id=e)});n(this,"onDispose");n(this,"_consumers",new Set);n(this,"_consumerRefs",new WeakSet);n(this,"_addConsumer",(e,t)=>{this._consumers.has(e)||(this._consumers.add(e),t&&this._consumerRefs.add(t))});n(this,"_removeConsumer",e=>{this._consumers.has(e)&&(this._consumers.delete(e),this._consumers.size===0&&!this._keepAlive&&this._scheduleDisposal())});n(this,"_disposalHandler");n(this,"lastUpdate",Date.now());n(this,"_batchingEnabled",!1);n(this,"_pendingUpdates",[]);n(this,"_pushState",(e,t,s)=>{if(e===void 0){console.warn("BlocBase._pushState: newState is undefined",this);return}if(s!=null){const i=typeof s;["string","object","number"].includes(i)||console.warn("BlocBase._pushState: Invalid action type",this,s)}if(this._batchingEnabled){this._pendingUpdates.push({newState:e,oldState:t,action:s});return}this._oldState=t,this._state=e,this._observer.notify(e,t,s),this.lastUpdate=Date.now()});n(this,"batch",e=>{const t=this._batchingEnabled;this._batchingEnabled=!0;try{const s=e();if(this._pendingUpdates.length>0){const i=this._pendingUpdates[this._pendingUpdates.length-1];this._oldState=this._pendingUpdates[0].oldState,this._state=i.newState,this._observer.notify(i.newState,this._oldState,i.action),this.lastUpdate=Date.now(),this._pendingUpdates=[]}return s}finally{this._batchingEnabled=t}});this._state=e,this._observer=new I(this),this._id=this.constructor.name;const t=this.constructor;this._keepAlive=typeof t.keepAlive=="boolean"?t.keepAlive:!1,this._isolated=typeof t.isolated=="boolean"?t.isolated:!1}get isIsolated(){return this._isolated}get isKeepAlive(){return this._keepAlive}get state(){return this._state}get _name(){return this.constructor.name}_dispose(){var e;this._consumers.clear(),this._observer.clear(),(e=this.onDispose)==null||e.call(this)}_setDisposalHandler(e){this._disposalHandler=e}_scheduleDisposal(){setTimeout(()=>{this._consumers.size===0&&!this._keepAlive&&(this._disposalHandler?this._disposalHandler(this):this._dispose())},0)}}n(p,"isolated",!1),n(p,"keepAlive",!1);class b extends p{constructor(){super(...arguments);n(this,"eventHandlers",new Map);n(this,"add",async t=>{const s=t.constructor,i=this.eventHandlers.get(s);if(i){const a=o=>{const c=this.state;this._pushState(o,c,t)};try{await i(t,a)}catch(o){l.error(`[Bloc ${this._name}:${String(this._id)}] Error in event handler for '${s.name}':`,o,"Action:",t)}}else{const a=t.constructor.name||"UnnamedConstructor";l.warn(`[Bloc ${this._name}:${String(this._id)}] No handler registered for action type: '${a}'. Action was:`,t)}})}on(t,s){this.eventHandlers.has(t)&&l.warn(`[Bloc ${this._name}:${String(this._id)}] Handler for event '${t.name}' already registered. It will be overwritten.`),this.eventHandlers.set(t,s)}}class A extends p{emit(e){if(Object.is(e,this.state))return;const t=this.state,s=e;this._pushState(s,t)}patch(e,t=!1){if(typeof this.state!="object"||this.state===null){l.warn("Cubit.patch: was called on a cubit where the state is not an object. This is a no-op.");return}let s=!1;if(t)s=!0;else for(const i in e)if(Object.prototype.hasOwnProperty.call(e,i)){const o=this.state[i];if(!Object.is(e[i],o)){s=!0;break}}s&&this.emit({...this.state,...e})}}exports.Blac=l;exports.BlacObservable=I;exports.Bloc=b;exports.BlocBase=p;exports.Cubit=A;exports.setBlacInstanceManager=m;
|
|
2
2
|
//# sourceMappingURL=index.cjs.js.map
|
package/dist/index.cjs.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs.js","sources":["../src/Blac.ts","../src/BlacObserver.ts","../src/BlocBase.ts","../src/Bloc.ts","../src/Cubit.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { BlocBase, BlocInstanceId } from \"./BlocBase\";\nimport {\n BlocBaseAbstract,\n BlocConstructor,\n BlocHookDependencyArrayFn,\n BlocState,\n InferPropsFromGeneric\n} from \"./types\";\n\n/**\n * Configuration options for the Blac instance\n */\nexport interface BlacConfig {\n /** Whether to expose the Blac instance globally */\n exposeBlacInstance?: boolean;\n}\n\nexport interface GetBlocOptions<B extends BlocBase<any>> {\n id?: string;\n selector?: BlocHookDependencyArrayFn<BlocState<B>>;\n props?: InferPropsFromGeneric<B>;\n onMount?: (bloc: B) => void;\n instanceRef?: string;\n throwIfNotFound?: boolean;\n}\n\n/**\n * Main Blac class that manages the state management system.\n * Implements a singleton pattern to ensure only one instance exists.\n * Handles bloc lifecycle, and instance tracking.\n * \n * Key responsibilities:\n * - Managing bloc instances (creation, disposal, lookup)\n * - Handling isolated and non-isolated blocs\n * - Providing logging and debugging capabilities\n */\nexport class Blac {\n /** The singleton instance of Blac */\n static instance: Blac = new Blac();\n /** Timestamp when the instance was created */\n createdAt = Date.now();\n static getAllBlocs = Blac.instance.getAllBlocs;\n /** Map storing all registered bloc instances by their class name and ID */\n blocInstanceMap: Map<string, BlocBase<any>> = new Map();\n /** Map storing isolated bloc instances grouped by their constructor */\n isolatedBlocMap: Map<BlocConstructor<any>, BlocBase<any>[]> = new Map();\n /** Flag to control whether changes should be posted to document */\n postChangesToDocument = false;\n\n /**\n * Creates a new Blac instance.\n * @param options - Configuration options including singleton control\n */\n constructor(options: { __unsafe_ignore_singleton?: boolean } = {}) {\n const { __unsafe_ignore_singleton = false } = options;\n if (!__unsafe_ignore_singleton) {\n return Blac.instance;\n }\n Blac.instance = this;\n }\n\n /** Flag to enable/disable logging */\n static enableLog = false;\n\n /**\n * Logs messages to console when logging is enabled\n * @param args - Arguments to log\n */\n log = (...args: unknown[]) => {\n if (Blac.enableLog) console.warn(`☢️ [Blac ${this.createdAt.toString()}]`, ...args);\n };\n static log = Blac.instance.log;\n\n /**\n * Gets the singleton instance of Blac\n * @returns The Blac instance\n */\n static getInstance(): Blac {\n return Blac.instance;\n }\n\n\n /**\n * Logs a warning message\n * @param message - Warning message\n * @param args - Additional arguments\n */\n warn = (message: string, ...args: unknown[]) => {\n if (Blac.enableLog) {\n console.warn(`🚨 [Blac ${String(Blac.instance.createdAt)}]`, message, ...args);\n }\n };\n static warn = Blac.instance.warn;\n /**\n * Logs an error message\n * @param message - Error message\n * @param args - Additional arguments\n */\n error = (message: string, ...args: unknown[]) => {\n if (Blac.enableLog) {\n console.error(`🚨 [Blac ${String(Blac.instance.createdAt)}]`, message, ...args);\n }\n };\n static error = Blac.instance.error;\n\n /**\n * Resets the Blac instance to a new one, disposing non-keepAlive blocs\n * from the old instance.\n */\n resetInstance = (): void => {\n this.log(\"Reset Blac instance\");\n\n // Dispose non-keepAlive blocs from the current instance\n const oldBlocInstanceMap = new Map(this.blocInstanceMap);\n const oldIsolatedBlocMap = new Map(this.isolatedBlocMap);\n\n oldBlocInstanceMap.forEach((bloc) => {\n bloc._dispose();\n });\n\n oldIsolatedBlocMap.forEach((blocArray) => {\n blocArray.forEach((bloc) => {\n bloc._dispose();\n });\n });\n\n this.blocInstanceMap.clear();\n this.isolatedBlocMap.clear();\n\n // Create and assign the new instance\n Blac.instance = new Blac({\n __unsafe_ignore_singleton: true,\n });\n }\n static resetInstance = Blac.instance.resetInstance;\n\n /**\n * Disposes of a bloc instance by removing it from the appropriate registry\n * @param bloc - The bloc instance to dispose\n */\n disposeBloc = (bloc: BlocBase<any>): void => {\n const base = bloc.constructor as unknown as BlocBaseAbstract;\n const key = this.createBlocInstanceMapKey(bloc._name, bloc._id);\n this.log(`[${bloc._name}:${String(bloc._id)}] disposeBloc called. Isolated: ${String(base.isolated)}`);\n\n if (base.isolated) {\n this.unregisterIsolatedBlocInstance(bloc);\n this.blocInstanceMap.delete(key);\n } else {\n this.unregisterBlocInstance(bloc);\n }\n this.log('dispatched bloc', bloc)\n };\n\n /**\n * Creates a unique key for a bloc instance in the map based on the bloc class name and instance ID\n * @param blocClassName - The name of the bloc class\n * @param id - The instance ID\n * @returns A unique key string in the format \"className:id\"\n */\n createBlocInstanceMapKey(blocClassName: string, id: BlocInstanceId): string {\n return `${blocClassName}:${String(id)}`;\n }\n\n /**\n * Unregister a bloc instance from the main registry\n * @param bloc - The bloc instance to unregister\n */\n unregisterBlocInstance(bloc: BlocBase<any>): void {\n const key = this.createBlocInstanceMapKey(bloc._name, bloc._id);\n this.blocInstanceMap.delete(key);\n }\n\n /**\n * Registers a bloc instance in the main registry\n * @param bloc - The bloc instance to register\n */\n registerBlocInstance(bloc: BlocBase<any>): void {\n const key = this.createBlocInstanceMapKey(bloc._name, bloc._id);\n this.blocInstanceMap.set(key, bloc);\n }\n\n /**\n * Finds a registered bloc instance by its class and ID\n * @param blocClass - The bloc class to search for\n * @param id - The instance ID\n * @returns The found bloc instance or undefined if not found\n */\n findRegisteredBlocInstance<B extends BlocConstructor<unknown>>(\n blocClass: B,\n id: BlocInstanceId,\n ): InstanceType<B> | undefined {\n const base = blocClass as unknown as BlocBaseAbstract;\n if (base.isolated) return undefined;\n\n const key = this.createBlocInstanceMapKey(blocClass.name, id);\n const found = this.blocInstanceMap.get(key) as InstanceType<B> | undefined;\n return found\n }\n\n /**\n * Registers an isolated bloc instance in the isolated registry\n * @param bloc - The isolated bloc instance to register\n */\n registerIsolatedBlocInstance(bloc: BlocBase<any>): void {\n const blocClass = bloc.constructor as BlocConstructor<unknown>;\n const blocs = this.isolatedBlocMap.get(blocClass);\n if (blocs) {\n blocs.push(bloc);\n } else {\n this.isolatedBlocMap.set(blocClass, [bloc]);\n }\n }\n\n /**\n * Unregister an isolated bloc instance from the isolated registry\n * @param bloc - The isolated bloc instance to unregister\n */\n unregisterIsolatedBlocInstance(bloc: BlocBase<any>): void {\n const blocClass = bloc.constructor;\n const blocs = this.isolatedBlocMap.get(blocClass as BlocConstructor<unknown>);\n if (blocs) {\n const index = blocs.findIndex((b) => b._id === bloc._id);\n if (index !== -1) {\n blocs.splice(index, 1);\n }\n\n if (blocs.length === 0) {\n this.isolatedBlocMap.delete(blocClass as BlocConstructor<unknown>);\n }\n }\n }\n\n /**\n * Finds an isolated bloc instance by its class and ID\n */\n findIsolatedBlocInstance<B extends BlocConstructor<unknown>>(\n blocClass: B,\n id: BlocInstanceId,\n ): InstanceType<B> | undefined {\n const base = blocClass as unknown as BlocBaseAbstract;\n if (!base.isolated) return undefined;\n\n const blocs = this.isolatedBlocMap.get(blocClass);\n if (!blocs) {\n return undefined;\n }\n // Fix: Find the specific bloc by ID within the isolated array\n const found = blocs.find((b) => b._id === id) as InstanceType<B> | undefined;\n return found;\n }\n\n /**\n * Creates a new bloc instance and registers it in the appropriate registry\n * @param blocClass - The bloc class to instantiate\n * @param id - The instance ID\n * @param props - Properties to pass to the bloc constructor\n * @param instanceRef - Optional reference string for the instance\n * @returns The newly created bloc instance\n */\n createNewBlocInstance<B extends BlocConstructor<BlocBase<any>>>(\n blocClass: B,\n id: BlocInstanceId,\n options: GetBlocOptions<InstanceType<B>> = {},\n ): InstanceType<B> {\n const { props, instanceRef } = options;\n const newBloc = new blocClass(props as never) as InstanceType<BlocConstructor<BlocBase<unknown>>>;\n newBloc._instanceRef = instanceRef;\n newBloc.props = props || null;\n newBloc._updateId(id);\n\n if (newBloc.isIsolated) {\n this.registerIsolatedBlocInstance(newBloc);\n return newBloc as InstanceType<B>;\n }\n\n this.registerBlocInstance(newBloc);\n return newBloc as InstanceType<B>;\n }\n\n\n activateBloc = (bloc: BlocBase<any>): void => {\n const base = bloc.constructor as unknown as BlocConstructor<BlocBase<any>>;\n const isIsolated = bloc.isIsolated;\n\n let found = isIsolated ? this.findIsolatedBlocInstance(base, bloc._id) : this.findRegisteredBlocInstance(base, bloc._id);\n if (found) {\n return;\n }\n\n this.log(`[${bloc._name}:${String(bloc._id)}] activateBloc called. Isolated: ${String(bloc.isIsolated)}`);\n if (bloc.isIsolated) {\n this.registerIsolatedBlocInstance(bloc);\n } else {\n this.registerBlocInstance(bloc);\n }\n };\n static activateBloc = Blac.instance.activateBloc;\n\n /**\n * Gets or creates a bloc instance based on the provided class and options.\n * If a bloc with the given ID exists, it will be returned. Otherwise, a new instance will be created.\n * \n * @param blocClass - The bloc class to get or create\n * @param options - Options including:\n * - id: The instance ID (defaults to class name if not provided)\n * - props: Properties to pass to the bloc constructor\n * - instanceRef: Optional reference string for the instance\n * @returns The bloc instance\n */\n getBloc = <B extends BlocConstructor<BlocBase<any>>>(\n blocClass: B,\n options: GetBlocOptions<InstanceType<B>> = {},\n ): InstanceType<B> => {\n const { id } = options;\n const base = blocClass as unknown as BlocBaseAbstract;\n const blocId = id ?? blocClass.name;\n\n\n if (base.isolated) {\n const isolatedBloc = this.findIsolatedBlocInstance<B>(blocClass, blocId)\n if (isolatedBloc) {\n this.log(`[${blocClass.name}:${String(blocId)}] (getBloc) Found existing isolated instance.`, options);\n return isolatedBloc;\n } else {\n if (options.throwIfNotFound) {\n throw new Error(`Isolated bloc ${blocClass.name} not found`);\n }\n }\n } else {\n const registeredBloc = this.findRegisteredBlocInstance(blocClass, blocId)\n if (registeredBloc) {\n this.log(`[${blocClass.name}:${String(blocId)}] (getBloc) Found existing registered instance.`, options);\n return registeredBloc\n } else {\n if (options.throwIfNotFound) {\n throw new Error(`Registered bloc ${blocClass.name} not found`);\n }\n }\n }\n\n const bloc = this.createNewBlocInstance(\n blocClass,\n blocId,\n options,\n );\n this.log(`[${blocClass.name}:${String(blocId)}] (getBloc) No existing instance found. Creating new one.`, options, bloc);\n return bloc;\n };\n static getBloc = Blac.instance.getBloc;\n\n /**\n * Gets a bloc instance or throws an error if it doesn't exist\n * @param blocClass - The bloc class to get\n * @param options - Options including:\n * - id: The instance ID (defaults to class name if not provided)\n * - props: Properties to pass to the bloc constructor\n * - instanceRef: Optional reference string for the instance\n */\n getBlocOrThrow = <B extends BlocConstructor<unknown>>(\n blocClass: B,\n options: {\n id?: BlocInstanceId;\n props?: InferPropsFromGeneric<B>;\n instanceRef?: string;\n } = {},\n ): InstanceType<B> => {\n const isIsolated = (blocClass as unknown as BlocBaseAbstract).isolated;\n const id = options.id || blocClass.name;\n\n const registered = isIsolated\n ? this.findIsolatedBlocInstance(blocClass, id)\n : this.findRegisteredBlocInstance(blocClass, id);\n\n if (registered) {\n return registered;\n }\n throw new Error(`Bloc ${blocClass.name} not found`);\n };\n static getBlocOrThrow = Blac.instance.getBlocOrThrow;\n\n /**\n * Gets all instances of a specific bloc class\n * @param blocClass - The bloc class to search for\n * @param options - Options including:\n * - searchIsolated: Whether to search in isolated blocs (defaults to bloc's isolated property)\n * @returns Array of matching bloc instances\n */\n getAllBlocs = <B extends BlocConstructor<unknown>>(\n blocClass: B,\n options: {\n searchIsolated?: boolean;\n } = {},\n ): InstanceType<B>[] => {\n const results: InstanceType<B>[] = [];\n // const blocClassName = (blocClass as any).name; // Temporarily removed for debugging\n\n // Search non-isolated blocs\n this.blocInstanceMap.forEach((blocInstance) => {\n if (blocInstance.constructor === blocClass) { // Strict constructor check\n results.push(blocInstance as InstanceType<B>);\n }\n });\n\n // Optionally search isolated blocs\n if (options.searchIsolated !== false) {\n const isolatedBlocs = this.isolatedBlocMap.get(blocClass);\n if (isolatedBlocs) {\n results.push(...isolatedBlocs.map(bloc => bloc as InstanceType<B>));\n }\n }\n\n return results;\n };\n}\n","import { Blac } from './Blac';\nimport { BlocBase } from './BlocBase';\nimport { BlocHookDependencyArrayFn } from './types';\n\n/**\n * Represents an observer that can subscribe to state changes in a Bloc\n * @template S - The type of state being observed\n */\nexport type BlacObserver<S> = {\n /** Function to be called when state changes */\n fn: (newState: S, oldState: S, action?: unknown) => void | Promise<void>;\n /** Optional function to determine if the observer should be notified of state changes */\n dependencyArray?: BlocHookDependencyArrayFn<S>;\n /** Dispose function for the observer */\n dispose?: () => void;\n /** Cached state values used for dependency comparison */\n lastState?: unknown[][];\n /** Unique identifier for the observer */\n id: string;\n};\n\n/**\n * A class that manages observers for a Bloc's state changes\n * @template S - The type of state being observed\n */\nexport class BlacObservable<S = unknown> {\n /** The Bloc instance this observable is associated with */\n bloc: BlocBase<S>;\n\n /**\n * Creates a new BlacObservable instance\n * @param bloc - The Bloc instance to observe\n */\n constructor(bloc: BlocBase<S>) {\n this.bloc = bloc;\n }\n\n private _observers = new Set<BlacObserver<S>>();\n\n /**\n * Gets the number of active observers\n * @returns The number of observers currently subscribed\n */\n get size(): number {\n return this._observers.size;\n }\n\n /**\n * Gets the set of all observers\n * @returns The Set of all BlacObserver instances\n */\n get observers() {\n return this._observers;\n }\n\n /**\n * Subscribes an observer to state changes\n * @param observer - The observer to subscribe\n * @returns A function that can be called to unsubscribe the observer\n */\n subscribe(observer: BlacObserver<S>): () => void {\n Blac.log('BlacObservable.subscribe: Subscribing observer.', this.bloc, observer);\n this._observers.add(observer);\n // Blac.instance.dispatchEvent(BlacLifecycleEvent.LISTENER_ADDED, this.bloc, { listenerId: observer.id });\n if (!observer.lastState) {\n observer.lastState = observer.dependencyArray\n ? observer.dependencyArray(this.bloc.state)\n : [];\n }\n return () => {\n Blac.log('BlacObservable.subscribe: Unsubscribing observer.', this.bloc, observer);\n this.unsubscribe(observer);\n }\n }\n\n /**\n * Unsubscribes an observer from state changes\n * @param observer - The observer to unsubscribe\n */\n unsubscribe(observer: BlacObserver<S>) {\n this._observers.delete(observer);\n // Blac.instance.dispatchEvent(BlacLifecycleEvent.LISTENER_REMOVED, this.bloc, { listenerId: observer.id });\n\n if (this.size === 0) {\n Blac.log('BlacObservable.unsubscribe: No observers left. Disposing bloc.', this.bloc);\n this.bloc._dispose();\n }\n }\n\n /**\n * Notifies all observers of a state change\n * @param newState - The new state value\n * @param oldState - The previous state value\n * @param action - Optional action that triggered the state change\n */\n notify(newState: S, oldState: S, action?: unknown) {\n this._observers.forEach((observer) => {\n let shouldUpdate = false;\n\n if (observer.dependencyArray) {\n const lastDependencyCheck = observer.lastState || [];\n const newDependencyCheck = observer.dependencyArray(newState);\n\n for (let o = 0; o < newDependencyCheck.length; o++) {\n const partNew = newDependencyCheck[o];\n const partOld = lastDependencyCheck[o] || [];\n for (let i = 0; i < partNew.length; i++) {\n if (!Object.is(partNew[i], partOld[i])) {\n shouldUpdate = true;\n break;\n }\n }\n }\n\n observer.lastState = newDependencyCheck;\n } else {\n shouldUpdate = true;\n }\n\n if (shouldUpdate) {\n void observer.fn(newState, oldState, action);\n }\n });\n }\n\n /**\n * Clears the observer set\n */\n clear() {\n this._observers.forEach((observer) => {\n this.unsubscribe(observer);\n });\n this._observers.clear();\n }\n}\n","import { Blac } from './Blac';\nimport { BlacObservable } from './BlacObserver';\nimport { BlocConstructor } from './types';\n\nexport type BlocInstanceId = string | number | undefined;\ntype DependencySelector<S> = (newState: S) => unknown[][];\n\n// Define an interface for the static properties expected on a Bloc/Cubit constructor\ninterface BlocStaticProperties {\n isolated: boolean;\n keepAlive: boolean;\n}\n\n/**\n * Base class for both Blocs and Cubits that provides core state management functionality.\n * Handles state transitions, observer notifications, lifecycle management, and addon integration.\n * \n * @abstract This class should be extended, not instantiated directly\n * @template S The type of state managed by this Bloc\n * @template P The type of props that can be passed during instance creation (optional)\n */\nexport abstract class BlocBase<\n S,\n P = unknown\n> {\n public uid = crypto.randomUUID();\n /**\n * When true, every consumer will receive its own unique instance of this Bloc.\n * Use this when state should not be shared between components.\n * @default false\n */\n static isolated = false;\n get isIsolated() {\n return this._isolated;\n }\n \n /**\n * When true, the Bloc instance persists even when there are no active consumers.\n * Useful for maintaining state between component unmount/remount cycles.\n * @default false\n */\n static keepAlive = false;\n get isKeepAlive() {\n return this._keepAlive;\n }\n \n /**\n * Defines how dependencies are selected from the state for efficient updates.\n * When provided, observers will only be notified when selected dependencies change.\n */\n defaultDependencySelector: DependencySelector<S> | undefined;\n \n /**\n * @internal\n * Indicates if this specific Bloc instance is isolated from others of the same type.\n */\n public _isolated = false;\n \n /**\n * @internal\n * Observable responsible for managing state listeners and notifying consumers.\n */\n public _observer: BlacObservable<S>;\n \n /**\n * @internal\n * Reference to the global Blac manager instance.\n */\n public _blac = Blac.getInstance();\n \n /**\n * The unique identifier for this Bloc instance.\n * Defaults to the class name, but can be customized.\n */\n public _id: BlocInstanceId;\n \n /**\n * @internal\n * Reference string used internally for tracking and debugging.\n */\n public _instanceRef?: string;\n \n /**\n * @internal\n * Indicates if this specific Bloc instance should be kept alive when no consumers are present.\n */\n public _keepAlive = false;\n \n /**\n * @readonly\n * Timestamp when this Bloc instance was created, useful for debugging and performance tracking.\n */\n public readonly _createdAt = Date.now();\n\n /**\n * @internal\n * The current state of the Bloc.\n */\n public _state: S;\n \n /**\n * @internal\n * The previous state of the Bloc, maintained for comparison and history.\n */\n public _oldState: S | undefined;\n \n /**\n * Props passed during Bloc instance creation.\n * Can be used to configure or parameterize the Bloc's behavior.\n */\n public props: P | null = null;\n\n /**\n * Creates a new BlocBase instance with the given initial state.\n * Sets up the observer, registers with the Blac manager, and initializes addons.\n * \n * @param initialState The initial state value for this Bloc\n */\n constructor(initialState: S) {\n this._state = initialState;\n this._observer = new BlacObservable(this);\n Blac.log('Bloc Created', this)\n this._id = this.constructor.name;\n\n // Use a type assertion for the constructor to access static properties safely\n const constructorWithStaticProps = this.constructor as BlocConstructor<this> & BlocStaticProperties;\n\n this._keepAlive = constructorWithStaticProps.keepAlive;\n this._isolated = constructorWithStaticProps.isolated;\n }\n\n /**\n * Returns the current state of the Bloc.\n * Use this getter to access the state in a read-only manner.\n */\n get state(): S {\n return this._state;\n }\n\n /**\n * @internal\n * Returns the name of the Bloc class for identification and debugging.\n */\n get _name() {\n return this.constructor.name;\n }\n\n /**\n * @internal\n * Updates the Bloc instance's ID to a new value.\n * Only updates if the new ID is defined and different from the current one.\n * \n * @param id The new ID to assign to this Bloc instance\n */\n _updateId = (id?: BlocInstanceId) => {\n const originalId = this._id;\n if (!id || id === originalId) return;\n this._id = id;\n };\n\n /**\n * @internal\n * Cleans up resources and removes this Bloc from the system.\n * Notifies the Blac manager and clears all observers.\n */\n _dispose() {\n this._observer.clear();\n this.onDispose?.();\n // this._blac.dispatchEvent(BlacLifecycleEvent.BLOC_DISPOSED, this);\n Blac.log('BlocBase._dispose', this);\n Blac.instance.disposeBloc(this);\n }\n\n /**\n * @internal\n * Optional function to be called when the Bloc is disposed.\n */\n onDispose?: () => void;\n\n /**\n * @internal\n * Set of consumer IDs currently listening to this Bloc's state changes.\n */\n _consumers = new Set<string>();\n\n /**\n * @internal\n * Registers a new consumer to this Bloc instance.\n * Notifies the Blac manager that a consumer has been added.\n * \n * @param consumerId The unique ID of the consumer being added\n */\n _addConsumer = (consumerId: string) => {\n if (this._consumers.has(consumerId)) return;\n this._consumers.add(consumerId);\n // this._blac.dispatchEvent(BlacLifecycleEvent.BLOC_CONSUMER_ADDED, this, { consumerId });\n Blac.log('BlocBase._addConsumer', this, consumerId);\n };\n\n /**\n * @internal\n * Unregisters a consumer from this Bloc instance.\n * Notifies the Blac manager that a consumer has been removed.\n * \n * @param consumerId The unique ID of the consumer being removed\n */\n _removeConsumer = (consumerId: string) => {\n if (!this._consumers.has(consumerId)) return;\n this._consumers.delete(consumerId);\n // this._blac.dispatchEvent(BlacLifecycleEvent.BLOC_CONSUMER_REMOVED, this, { consumerId });\n Blac.log('BlocBase._removeConsumer', this, consumerId);\n };\n\n lastUpdate = Date.now();\n\n /**\n * @internal\n * Updates the state and notifies all observers of the change.\n * \n * @param newState The new state to be set\n * @param oldState The previous state for comparison\n * @param action Optional metadata about what caused the state change\n */\n _pushState = (newState: S, oldState: S, action?: unknown): void => {\n this._state = newState;\n this._observer.notify(newState, oldState, action);\n this.lastUpdate = Date.now();\n };\n}\n","import { Blac } from './Blac';\nimport { BlocBase } from './BlocBase';\n\n// A should be the base type for all events this Bloc handles and must be an object type\n// to access action.constructor. Events are typically class instances.\n// P is for props, changed from any to unknown.\nexport abstract class Bloc<\n S, // State type\n A extends object, // Base Action/Event type, constrained to object\n P = unknown // Props type\n> extends BlocBase<S, P> {\n // Stores handlers: Map<EventConstructor (subtype of A), HandlerFunction>\n // The handler's event parameter will be correctly typed to the specific EventConstructor\n // by the 'on' method's signature.\n readonly eventHandlers: Map<\n // Key: Constructor of a specific event E (where E extends A)\n // Using 'any[]' for constructor arguments for broader compatibility.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n new (...args: any[]) => A,\n // Value: Handler function. 'event: A' is used here for the stored function type.\n // The 'on' method ensures the specific handler (event: E) is correctly typed.\n (event: A, emit: (newState: S) => void) => void | Promise<void>\n > = new Map();\n\n /**\n * Registers an event handler for a specific event type.\n * This method is typically called in the constructor of a derived Bloc class.\n * @param eventConstructor The constructor of the event to handle (e.g., LoadDataEvent).\n * @param handler A function that processes the event and can emit new states.\n * The 'event' parameter in the handler will be typed to the specific eventConstructor.\n */\n protected on<E extends A>(\n // Using 'any[]' for constructor arguments for broader compatibility.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n eventConstructor: new (...args: any[]) => E, \n handler: (event: E, emit: (newState: S) => void) => void | Promise<void>\n ): void {\n if (this.eventHandlers.has(eventConstructor)) {\n // Using Blac.warn or a similar logging mechanism from BlocBase if available,\n // otherwise console.warn. Assuming this._name and this._id are available from BlocBase.\n Blac.warn(\n `[Bloc ${this._name}:${String(this._id)}] Handler for event '${eventConstructor.name}' already registered. It will be overwritten.`\n );\n }\n // Cast the specific handler (event: E) to a more general (event: A) for storage.\n // This is safe because E extends A. When the handler is called with an 'action' of type A,\n // if it was originally registered for type E, 'action' must be an instance of E.\n this.eventHandlers.set(\n eventConstructor,\n handler as (event: A, emit: (newState: S) => void) => void | Promise<void>\n );\n }\n\n /**\n * Dispatches an action/event to the Bloc.\n * If a handler is registered for this specific event type (via 'on'), it will be invoked.\n * Asynchronous handlers are awaited.\n * @param action The action/event instance to be processed.\n */\n public add = async (action: A): Promise<void> => {\n // Using 'any[]' for constructor arguments for broader compatibility.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const eventConstructor = action.constructor as new (...args: any[]) => A;\n const handler = this.eventHandlers.get(eventConstructor);\n\n if (handler) {\n // Define the 'emit' function that handlers will use to update state.\n // It captures the current state ('this.state') right before each emission\n // to provide the correct 'previousState' to _pushState.\n const emit = (newState: S): void => {\n const previousState = this.state; // State just before this specific emission\n // The 'action' passed to _pushState is the original action that triggered the handler,\n // providing context for the state change (e.g., for logging or plugins).\n this._pushState(newState, previousState, action);\n };\n\n try {\n // Await the handler in case it's an async function (e.g., performs API calls).\n // The 'action' is passed to the handler, and due to the way 'on' is typed,\n // the 'event' parameter within the handler function will be correctly\n // typed to its specific class (e.g., LoadMyFeatureData).\n await handler(action, emit);\n } catch (error) {\n // It's good practice to handle errors occurring within event handlers.\n Blac.error(\n `[Bloc ${this._name}:${String(this._id)}] Error in event handler for '${eventConstructor.name}':`,\n error,\n \"Action:\", action\n );\n // Depending on the desired error handling strategy, you might:\n // 1. Emit a specific error state: this.emit(new MyErrorState(error));\n // 2. Re-throw the error: throw error;\n // 3. Log and ignore (as done here by default).\n // This should be decided based on application requirements.\n }\n } else {\n // action.constructor.name should be safe due to 'A extends object' and common JS practice for constructors.\n // If linting still complains, it might be overly strict for this common pattern.\n const constructorName = (action.constructor as { name?: string }).name || 'UnnamedConstructor';\n Blac.warn(\n `[Bloc ${this._name}:${String(this._id)}] No handler registered for action type: '${constructorName}'. Action was:`,\n action\n );\n // If no handler is found, the action is effectively ignored.\n // Consider if this is the desired behavior or if an error should be thrown\n // or a default handler should be invoked.\n }\n };\n}\n","import { Blac } from './Blac';\nimport { BlocBase } from './BlocBase';\n\n/**\n * A Cubit is a simpler version of a Bloc that doesn't handle events.\n * It manages state and provides methods to update it.\n * @template S - The type of state this Cubit manages\n * @template P - The type of parameters (optional, defaults to null)\n */\nexport abstract class Cubit<S, P = null> extends BlocBase<S, P> {\n /**\n * Updates the current state and notifies all observers of the change.\n * If the new state is identical to the current state (using Object.is),\n * no update will occur.\n * @param state - The new state to set\n */\n emit(state: S): void {\n if (Object.is(state, this.state)) {\n return;\n }\n\n const oldState = this.state;\n const newState = state;\n this._pushState(newState, oldState);\n }\n\n /**\n * Partially updates the current state by merging it with the provided state patch.\n * This method is only applicable when the state is an object type.\n * \n * @param statePatch - A partial state object containing only the properties to update\n * @param ignoreChangeCheck - If true, skips checking if the state has actually changed\n * @throws {TypeError} If the state is not an object type\n */\n patch(\n statePatch: S extends object ? Partial<S> : S,\n ignoreChangeCheck = false,\n ): void {\n if (typeof this.state !== 'object' || this.state === null) {\n Blac.warn(\n 'Cubit.patch: was called on a cubit where the state is not an object. This is a no-op.',\n );\n return;\n }\n\n let changes = false;\n if (!ignoreChangeCheck) {\n for (const key in statePatch) {\n if (Object.prototype.hasOwnProperty.call(statePatch, key)) {\n const s = this.state;\n const current = s[key as keyof S];\n if (!Object.is(statePatch[key as keyof S], current)) {\n changes = true;\n break;\n }\n }\n }\n } else {\n changes = true;\n }\n\n if (changes) {\n this.emit({\n ...this.state,\n ...(statePatch as Partial<S>),\n } as S);\n }\n }\n}\n"],"names":["_Blac","options","__publicField","args","message","oldBlocInstanceMap","oldIsolatedBlocMap","bloc","blocArray","base","key","blocClass","id","blocId","isolatedBloc","registeredBloc","isIsolated","registered","results","blocInstance","isolatedBlocs","__unsafe_ignore_singleton","blocClassName","blocs","index","b","props","instanceRef","newBloc","Blac","BlacObservable","observer","newState","oldState","action","shouldUpdate","lastDependencyCheck","newDependencyCheck","o","partNew","partOld","i","BlocBase","initialState","originalId","consumerId","constructorWithStaticProps","_a","Bloc","eventConstructor","handler","emit","previousState","error","constructorName","Cubit","state","statePatch","ignoreChangeCheck","changes","current"],"mappings":"oPAqCO,MAAMA,EAAN,MAAMA,CAAK,CAiBhB,YAAYC,EAAmD,GAAI,CAbnEC,EAAA,iBAAY,KAAK,IAAI,GAGrBA,EAAA,2BAAkD,KAElDA,EAAA,2BAAkE,KAElEA,EAAA,6BAAwB,IAqBxBA,EAAA,WAAM,IAAIC,IAAoB,CACxBH,EAAK,WAAW,QAAQ,KAAK,YAAY,KAAK,UAAU,SAAU,CAAA,IAAK,GAAGG,CAAI,CACpF,GAiBAD,EAAA,YAAO,CAACE,KAAoBD,IAAoB,CAC1CH,EAAK,WACC,QAAA,KAAK,YAAY,OAAOA,EAAK,SAAS,SAAS,CAAC,IAAKI,EAAS,GAAGD,CAAI,CAEjF,GAOAD,EAAA,aAAQ,CAACE,KAAo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AAoB,GACd,CACN,GAAI,OAAO,KAAK,OAAU,UAAY,KAAK,QAAU,KAAM,CACpD7B,EAAA,KACH,uFACF,EACA,MAAA,CAGF,IAAI8B,EAAU,GACd,GAAKD,EAYOC,EAAA,OAXV,WAAWjD,KAAO+C,EAChB,GAAI,OAAO,UAAU,eAAe,KAAKA,EAAY/C,CAAG,EAAG,CAEnD,MAAAkD,EADI,KAAK,MACGlD,CAAc,EAChC,GAAI,CAAC,OAAO,GAAG+C,EAAW/C,CAAc,EAAGkD,CAAO,EAAG,CACzCD,EAAA,GACV,KAAA,CACF,CAOFA,GACF,KAAK,KAAK,CACR,GAAG,KAAK,MACR,GAAIF,CAAA,CACA,CACR,CAEJ"}
|
|
1
|
+
{"version":3,"file":"index.cjs.js","sources":["../src/Blac.ts","../src/BlacObserver.ts","../src/BlocBase.ts","../src/Bloc.ts","../src/Cubit.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\n// TODO: Remove this eslint disable once any types are properly replaced\nimport { BlocBase, BlocInstanceId } from \"./BlocBase\";\nimport {\n BlocBaseAbstract,\n BlocConstructor,\n BlocHookDependencyArrayFn,\n BlocState,\n InferPropsFromGeneric\n} from \"./types\";\n\n/**\n * Configuration options for the Blac instance\n */\nexport interface BlacConfig {\n /** Whether to expose the Blac instance globally */\n exposeBlacInstance?: boolean;\n}\n\nexport interface GetBlocOptions<B extends BlocBase<unknown>> {\n id?: string;\n selector?: BlocHookDependencyArrayFn<BlocState<B>>;\n props?: InferPropsFromGeneric<B>;\n onMount?: (bloc: B) => void;\n instanceRef?: string;\n throwIfNotFound?: boolean;\n}\n\n/**\n * Interface for Blac instance management\n */\nexport interface BlacInstanceManager {\n getInstance(): Blac;\n setInstance(instance: Blac): void;\n resetInstance(): void;\n}\n\n/**\n * Default singleton implementation of BlacInstanceManager\n */\nclass SingletonBlacManager implements BlacInstanceManager {\n private static _instance: Blac;\n\n getInstance(): Blac {\n if (!SingletonBlacManager._instance) {\n SingletonBlacManager._instance = new Blac({ __unsafe_ignore_singleton: true });\n }\n return SingletonBlacManager._instance;\n }\n\n setInstance(instance: Blac): void {\n SingletonBlacManager._instance = instance;\n }\n\n resetInstance(): void {\n const oldInstance = SingletonBlacManager._instance;\n SingletonBlacManager._instance = new Blac({ __unsafe_ignore_singleton: true });\n \n // Transfer any keep-alive blocs to the new instance\n for (const bloc of oldInstance.keepAliveBlocs) {\n SingletonBlacManager._instance.keepAliveBlocs.add(bloc);\n SingletonBlacManager._instance.uidRegistry.set(bloc.uid, bloc);\n }\n }\n}\n\n/**\n * Global instance manager (can be replaced for testing or different patterns)\n */\nlet instanceManager: BlacInstanceManager = new SingletonBlacManager();\n\n/**\n * Sets a custom instance manager (useful for testing or advanced patterns)\n */\nexport function setBlacInstanceManager(manager: BlacInstanceManager): void {\n instanceManager = manager;\n}\n\n/**\n * Main Blac class that manages the state management system.\n * Can work with singleton pattern or dependency injection.\n * Handles bloc lifecycle, and instance tracking.\n * \n * Key responsibilities:\n * - Managing bloc instances (creation, disposal, lookup)\n * - Handling isolated and non-isolated blocs\n * - Providing logging and debugging capabilities\n */\nexport class Blac {\n /** @deprecated Use getInstance() instead */\n static get instance(): Blac {\n return instanceManager.getInstance();\n }\n /** Timestamp when the instance was created */\n createdAt = Date.now();\n static get getAllBlocs() {\n return Blac.instance.getAllBlocs;\n }\n /** Map storing all registered bloc instances by their class name and ID */\n blocInstanceMap: Map<string, BlocBase<unknown>> = new Map();\n /** Map storing isolated bloc instances grouped by their constructor */\n isolatedBlocMap: Map<BlocConstructor<unknown>, BlocBase<unknown>[]> = new Map();\n /** Map for O(1) lookup of isolated blocs by UID */\n private isolatedBlocIndex: Map<string, BlocBase<unknown>> = new Map();\n /** Map tracking UIDs to prevent memory leaks */\n uidRegistry: Map<string, BlocBase<unknown>> = new Map();\n /** Set of keep-alive blocs for controlled cleanup */\n keepAliveBlocs: Set<BlocBase<unknown>> = new Set();\n /** Flag to control whether changes should be posted to document */\n postChangesToDocument = false;\n\n /**\n * Creates a new Blac instance.\n * @param options - Configuration options including singleton control\n */\n constructor(options: { __unsafe_ignore_singleton?: boolean } = {}) {\n const { __unsafe_ignore_singleton = false } = options;\n if (!__unsafe_ignore_singleton) {\n return Blac.instance;\n }\n instanceManager.setInstance(this);\n }\n\n /** Flag to enable/disable logging */\n static enableLog = false;\n\n /**\n * Logs messages to console when logging is enabled\n * @param args - Arguments to log\n */\n log = (...args: unknown[]) => {\n if (Blac.enableLog) console.warn(`☢️ [Blac ${this.createdAt.toString()}]`, ...args);\n };\n static get log() { return Blac.instance.log; }\n\n /**\n * Gets the current Blac instance\n * @returns The Blac instance\n */\n static getInstance(): Blac {\n return instanceManager.getInstance();\n }\n\n\n /**\n * Logs a warning message\n * @param message - Warning message\n * @param args - Additional arguments\n */\n warn = (message: string, ...args: unknown[]) => {\n if (Blac.enableLog) {\n console.warn(`🚨 [Blac ${String(Blac.instance.createdAt)}]`, message, ...args);\n }\n };\n static get warn() { return Blac.instance.warn; }\n /**\n * Logs an error message\n * @param message - Error message\n * @param args - Additional arguments\n */\n error = (message: string, ...args: unknown[]) => {\n if (Blac.enableLog) {\n console.error(`🚨 [Blac ${String(Blac.instance.createdAt)}]`, message, ...args);\n }\n };\n static get error() { return Blac.instance.error; }\n\n /**\n * Resets the Blac instance to a new one, disposing non-keepAlive blocs\n * from the old instance.\n */\n resetInstance = (): void => {\n this.log(\"Reset Blac instance\");\n\n // Dispose non-keepAlive blocs from the current instance\n const oldBlocInstanceMap = new Map(this.blocInstanceMap);\n const oldIsolatedBlocMap = new Map(this.isolatedBlocMap);\n\n oldBlocInstanceMap.forEach((bloc) => {\n if (!bloc._keepAlive) {\n bloc._dispose();\n }\n });\n\n oldIsolatedBlocMap.forEach((blocArray) => {\n blocArray.forEach((bloc) => {\n if (!bloc._keepAlive) {\n bloc._dispose();\n }\n });\n });\n\n this.blocInstanceMap.clear();\n this.isolatedBlocMap.clear();\n this.isolatedBlocIndex.clear();\n\n // Use instance manager to reset\n instanceManager.resetInstance();\n }\n static resetInstance = (): void => {\n instanceManager.resetInstance();\n };\n\n /**\n * Disposes of a bloc instance by removing it from the appropriate registry\n * @param bloc - The bloc instance to dispose\n */\n disposeBloc = (bloc: BlocBase<unknown>): void => {\n const base = bloc.constructor as unknown as BlocBaseAbstract;\n const key = this.createBlocInstanceMapKey(bloc._name, bloc._id);\n this.log(`[${bloc._name}:${String(bloc._id)}] disposeBloc called. Isolated: ${String(base.isolated)}`);\n\n if (base.isolated) {\n this.unregisterIsolatedBlocInstance(bloc);\n this.blocInstanceMap.delete(key);\n } else {\n this.unregisterBlocInstance(bloc);\n }\n this.log('dispatched bloc', bloc)\n };\n\n /**\n * Creates a unique key for a bloc instance in the map based on the bloc class name and instance ID\n * @param blocClassName - The name of the bloc class\n * @param id - The instance ID\n * @returns A unique key string in the format \"className:id\"\n */\n createBlocInstanceMapKey(blocClassName: string, id: BlocInstanceId): string {\n return `${blocClassName}:${String(id)}`;\n }\n\n /**\n * Unregister a bloc instance from the main registry\n * @param bloc - The bloc instance to unregister\n */\n unregisterBlocInstance(bloc: BlocBase<unknown>): void {\n const key = this.createBlocInstanceMapKey(bloc._name, bloc._id);\n this.blocInstanceMap.delete(key);\n \n // Clean up UID tracking\n this.uidRegistry.delete(bloc.uid);\n \n // Remove from keep-alive set\n this.keepAliveBlocs.delete(bloc);\n }\n\n /**\n * Registers a bloc instance in the main registry\n * @param bloc - The bloc instance to register\n */\n registerBlocInstance(bloc: BlocBase<unknown>): void {\n const key = this.createBlocInstanceMapKey(bloc._name, bloc._id);\n this.blocInstanceMap.set(key, bloc);\n \n // Track UID for cleanup\n this.uidRegistry.set(bloc.uid, bloc);\n \n // Track keep-alive blocs\n if (bloc._keepAlive) {\n this.keepAliveBlocs.add(bloc);\n }\n }\n\n /**\n * Finds a registered bloc instance by its class and ID\n * @param blocClass - The bloc class to search for\n * @param id - The instance ID\n * @returns The found bloc instance or undefined if not found\n */\n findRegisteredBlocInstance<B extends BlocConstructor<unknown>>(\n blocClass: B,\n id: BlocInstanceId,\n ): InstanceType<B> | undefined {\n const base = blocClass as unknown as BlocBaseAbstract;\n if (base.isolated) return undefined;\n\n const key = this.createBlocInstanceMapKey(blocClass.name, id);\n const found = this.blocInstanceMap.get(key) as InstanceType<B> | undefined;\n return found\n }\n\n /**\n * Registers an isolated bloc instance in the isolated registry\n * @param bloc - The isolated bloc instance to register\n */\n registerIsolatedBlocInstance(bloc: BlocBase<unknown>): void {\n const blocClass = bloc.constructor as BlocConstructor<unknown>;\n const blocs = this.isolatedBlocMap.get(blocClass);\n if (blocs) {\n blocs.push(bloc);\n } else {\n this.isolatedBlocMap.set(blocClass, [bloc]);\n }\n \n // Add to isolated index for O(1) lookups\n this.isolatedBlocIndex.set(bloc.uid, bloc);\n \n // Track UID for cleanup\n this.uidRegistry.set(bloc.uid, bloc);\n \n // Track keep-alive blocs\n if (bloc._keepAlive) {\n this.keepAliveBlocs.add(bloc);\n }\n }\n\n /**\n * Unregister an isolated bloc instance from the isolated registry\n * @param bloc - The isolated bloc instance to unregister\n */\n unregisterIsolatedBlocInstance(bloc: BlocBase<unknown>): void {\n const blocClass = bloc.constructor;\n const blocs = this.isolatedBlocMap.get(blocClass as BlocConstructor<unknown>);\n if (blocs) {\n const index = blocs.findIndex((b) => b.uid === bloc.uid);\n if (index !== -1) {\n blocs.splice(index, 1);\n }\n\n if (blocs.length === 0) {\n this.isolatedBlocMap.delete(blocClass as BlocConstructor<unknown>);\n }\n }\n \n // Remove from isolated index\n this.isolatedBlocIndex.delete(bloc.uid);\n \n // Clean up UID tracking\n this.uidRegistry.delete(bloc.uid);\n \n // Remove from keep-alive set\n this.keepAliveBlocs.delete(bloc);\n }\n\n /**\n * Finds an isolated bloc instance by its class and ID (O(n) lookup)\n */\n findIsolatedBlocInstance<B extends BlocConstructor<unknown>>(\n blocClass: B,\n id: BlocInstanceId,\n ): InstanceType<B> | undefined {\n const base = blocClass as unknown as BlocBaseAbstract;\n if (!base.isolated) return undefined;\n\n const blocs = this.isolatedBlocMap.get(blocClass);\n if (!blocs) {\n return undefined;\n }\n // Find the specific bloc by ID within the isolated array\n const found = blocs.find((b) => b._id === id) as InstanceType<B> | undefined;\n return found;\n }\n\n /**\n * Finds an isolated bloc instance by UID (O(1) lookup)\n */\n findIsolatedBlocInstanceByUid<B extends BlocBase<unknown>>(\n uid: string\n ): B | undefined {\n return this.isolatedBlocIndex.get(uid) as B | undefined;\n }\n\n /**\n * Creates a new bloc instance and registers it in the appropriate registry\n * @param blocClass - The bloc class to instantiate\n * @param id - The instance ID\n * @param props - Properties to pass to the bloc constructor\n * @param instanceRef - Optional reference string for the instance\n * @returns The newly created bloc instance\n */\n createNewBlocInstance<B extends BlocConstructor<BlocBase<unknown>>>(\n blocClass: B,\n id: BlocInstanceId,\n options: GetBlocOptions<InstanceType<B>> = {},\n ): InstanceType<B> {\n const { props, instanceRef } = options;\n const newBloc = new blocClass(props as never) as InstanceType<BlocConstructor<BlocBase<unknown>>>;\n newBloc._instanceRef = instanceRef;\n newBloc.props = props || null;\n newBloc._updateId(id);\n\n // Set up disposal handler to break circular dependency\n newBloc._setDisposalHandler((bloc) => this.disposeBloc(bloc));\n\n if (newBloc.isIsolated) {\n this.registerIsolatedBlocInstance(newBloc);\n return newBloc as InstanceType<B>;\n }\n\n this.registerBlocInstance(newBloc);\n return newBloc as InstanceType<B>;\n }\n\n\n activateBloc = (bloc: BlocBase<unknown>): void => {\n const base = bloc.constructor as unknown as BlocConstructor<BlocBase<unknown>>;\n const isIsolated = bloc.isIsolated;\n\n let found = isIsolated ? this.findIsolatedBlocInstance(base, bloc._id) : this.findRegisteredBlocInstance(base, bloc._id);\n if (found) {\n return;\n }\n\n this.log(`[${bloc._name}:${String(bloc._id)}] activateBloc called. Isolated: ${String(bloc.isIsolated)}`);\n if (bloc.isIsolated) {\n this.registerIsolatedBlocInstance(bloc);\n } else {\n this.registerBlocInstance(bloc);\n }\n };\n static get activateBloc() { return Blac.instance.activateBloc; }\n\n /**\n * Gets or creates a bloc instance based on the provided class and options.\n * If a bloc with the given ID exists, it will be returned. Otherwise, a new instance will be created.\n * \n * @param blocClass - The bloc class to get or create\n * @param options - Options including:\n * - id: The instance ID (defaults to class name if not provided)\n * - props: Properties to pass to the bloc constructor\n * - instanceRef: Optional reference string for the instance\n * @returns The bloc instance\n */\n getBloc = <B extends BlocConstructor<BlocBase<unknown>>>(\n blocClass: B,\n options: GetBlocOptions<InstanceType<B>> = {},\n ): InstanceType<B> => {\n const { id } = options;\n const base = blocClass as unknown as BlocBaseAbstract;\n const blocId = id ?? blocClass.name;\n\n\n if (base.isolated) {\n const isolatedBloc = this.findIsolatedBlocInstance<B>(blocClass, blocId)\n if (isolatedBloc) {\n this.log(`[${blocClass.name}:${String(blocId)}] (getBloc) Found existing isolated instance.`, options);\n return isolatedBloc;\n } else {\n if (options.throwIfNotFound) {\n throw new Error(`Isolated bloc ${blocClass.name} not found`);\n }\n }\n } else {\n const registeredBloc = this.findRegisteredBlocInstance(blocClass, blocId)\n if (registeredBloc) {\n this.log(`[${blocClass.name}:${String(blocId)}] (getBloc) Found existing registered instance.`, options);\n return registeredBloc\n } else {\n if (options.throwIfNotFound) {\n throw new Error(`Registered bloc ${blocClass.name} not found`);\n }\n }\n }\n\n const bloc = this.createNewBlocInstance(\n blocClass,\n blocId,\n options,\n );\n this.log(`[${blocClass.name}:${String(blocId)}] (getBloc) No existing instance found. Creating new one.`, options, bloc);\n return bloc;\n };\n static get getBloc() { return Blac.instance.getBloc; }\n\n /**\n * Gets a bloc instance or throws an error if it doesn't exist\n * @param blocClass - The bloc class to get\n * @param options - Options including:\n * - id: The instance ID (defaults to class name if not provided)\n * - props: Properties to pass to the bloc constructor\n * - instanceRef: Optional reference string for the instance\n */\n getBlocOrThrow = <B extends BlocConstructor<unknown>>(\n blocClass: B,\n options: {\n id?: BlocInstanceId;\n props?: InferPropsFromGeneric<B>;\n instanceRef?: string;\n } = {},\n ): InstanceType<B> => {\n const isIsolated = (blocClass as unknown as BlocBaseAbstract).isolated;\n const id = options.id || blocClass.name;\n\n const registered = isIsolated\n ? this.findIsolatedBlocInstance(blocClass, id)\n : this.findRegisteredBlocInstance(blocClass, id);\n\n if (registered) {\n return registered;\n }\n throw new Error(`Bloc ${blocClass.name} not found`);\n };\n static get getBlocOrThrow() { return Blac.instance.getBlocOrThrow; }\n\n /**\n * Gets all instances of a specific bloc class\n * @param blocClass - The bloc class to search for\n * @param options - Options including:\n * - searchIsolated: Whether to search in isolated blocs (defaults to bloc's isolated property)\n * @returns Array of matching bloc instances\n */\n getAllBlocs = <B extends BlocConstructor<unknown>>(\n blocClass: B,\n options: {\n searchIsolated?: boolean;\n } = {},\n ): InstanceType<B>[] => {\n const results: InstanceType<B>[] = [];\n // const blocClassName = (blocClass as any).name; // Temporarily removed for debugging\n\n // Search non-isolated blocs\n this.blocInstanceMap.forEach((blocInstance) => {\n if (blocInstance.constructor === blocClass) { // Strict constructor check\n results.push(blocInstance as InstanceType<B>);\n }\n });\n\n // Optionally search isolated blocs\n if (options.searchIsolated !== false) {\n const isolatedBlocs = this.isolatedBlocMap.get(blocClass);\n if (isolatedBlocs) {\n results.push(...isolatedBlocs.map(bloc => bloc as InstanceType<B>));\n }\n }\n\n return results;\n };\n\n /**\n * Disposes all keep-alive blocs of a specific type\n * @param blocClass - The bloc class to dispose\n */\n disposeKeepAliveBlocs = <B extends BlocConstructor<unknown>>(\n blocClass?: B\n ): void => {\n const toDispose: BlocBase<unknown>[] = [];\n \n for (const bloc of this.keepAliveBlocs) {\n if (!blocClass || bloc.constructor === blocClass) {\n toDispose.push(bloc);\n }\n }\n \n toDispose.forEach(bloc => bloc._dispose());\n };\n static get disposeKeepAliveBlocs() { return Blac.instance.disposeKeepAliveBlocs; }\n\n /**\n * Disposes all blocs matching a pattern\n * @param predicate - Function to test each bloc for disposal\n */\n disposeBlocs = (predicate: (bloc: BlocBase<unknown>) => boolean): void => {\n const toDispose: BlocBase<unknown>[] = [];\n \n // Check registered blocs\n for (const bloc of this.blocInstanceMap.values()) {\n if (predicate(bloc)) {\n toDispose.push(bloc);\n }\n }\n \n // Check isolated blocs\n for (const blocs of this.isolatedBlocMap.values()) {\n for (const bloc of blocs) {\n if (predicate(bloc)) {\n toDispose.push(bloc);\n }\n }\n }\n \n toDispose.forEach(bloc => bloc._dispose());\n };\n static get disposeBlocs() { return Blac.instance.disposeBlocs; }\n\n /**\n * Gets memory usage statistics for debugging\n */\n getMemoryStats = () => {\n return {\n totalBlocs: this.uidRegistry.size,\n registeredBlocs: this.blocInstanceMap.size,\n isolatedBlocs: Array.from(this.isolatedBlocMap.values()).reduce((sum, arr) => sum + arr.length, 0),\n keepAliveBlocs: this.keepAliveBlocs.size,\n isolatedBlocTypes: this.isolatedBlocMap.size,\n };\n };\n static get getMemoryStats() { return Blac.instance.getMemoryStats; }\n\n /**\n * Validates consumer references and cleans up orphaned consumers\n */\n validateConsumers = (): void => {\n for (const bloc of this.uidRegistry.values()) {\n // This would need to be called periodically to clean up orphaned consumers\n // Implementation depends on how we want to handle consumer validation\n if (bloc._consumers.size === 0 && !bloc._keepAlive) {\n // Schedule disposal for blocs with no consumers\n setTimeout(() => {\n if (bloc._consumers.size === 0 && !bloc._keepAlive) {\n bloc._dispose();\n }\n }, 1000); // Give a grace period\n }\n }\n };\n static get validateConsumers() { return Blac.instance.validateConsumers; }\n}\n","import { Blac } from './Blac';\nimport { BlocBase } from './BlocBase';\nimport { BlocHookDependencyArrayFn } from './types';\n\n/**\n * Represents an observer that can subscribe to state changes in a Bloc\n * @template S - The type of state being observed\n */\nexport type BlacObserver<S> = {\n /** Function to be called when state changes */\n fn: (newState: S, oldState: S, action?: unknown) => void | Promise<void>;\n /** Optional function to determine if the observer should be notified of state changes */\n dependencyArray?: BlocHookDependencyArrayFn<S>;\n /** Dispose function for the observer */\n dispose?: () => void;\n /** Cached state values used for dependency comparison */\n lastState?: unknown[][];\n /** Unique identifier for the observer */\n id: string;\n};\n\n/**\n * A class that manages observers for a Bloc's state changes\n * @template S - The type of state being observed\n */\nexport class BlacObservable<S = unknown> {\n /** The Bloc instance this observable is associated with */\n bloc: BlocBase<S>;\n\n /**\n * Creates a new BlacObservable instance\n * @param bloc - The Bloc instance to observe\n */\n constructor(bloc: BlocBase<S>) {\n this.bloc = bloc;\n }\n\n private _observers = new Set<BlacObserver<S>>();\n\n /**\n * Gets the number of active observers\n * @returns The number of observers currently subscribed\n */\n get size(): number {\n return this._observers.size;\n }\n\n /**\n * Gets the set of all observers\n * @returns The Set of all BlacObserver instances\n */\n get observers() {\n return this._observers;\n }\n\n /**\n * Subscribes an observer to state changes\n * @param observer - The observer to subscribe\n * @returns A function that can be called to unsubscribe the observer\n */\n subscribe(observer: BlacObserver<S>): () => void {\n Blac.log('BlacObservable.subscribe: Subscribing observer.', this.bloc, observer);\n this._observers.add(observer);\n // Blac.instance.dispatchEvent(BlacLifecycleEvent.LISTENER_ADDED, this.bloc, { listenerId: observer.id });\n if (!observer.lastState) {\n observer.lastState = observer.dependencyArray\n ? observer.dependencyArray(this.bloc.state)\n : [];\n }\n return () => {\n Blac.log('BlacObservable.subscribe: Unsubscribing observer.', this.bloc, observer);\n this.unsubscribe(observer);\n }\n }\n\n /**\n * Unsubscribes an observer from state changes\n * @param observer - The observer to unsubscribe\n */\n unsubscribe(observer: BlacObserver<S>) {\n this._observers.delete(observer);\n // Blac.instance.dispatchEvent(BlacLifecycleEvent.LISTENER_REMOVED, this.bloc, { listenerId: observer.id });\n\n if (this.size === 0) {\n Blac.log('BlacObservable.unsubscribe: No observers left. Disposing bloc.', this.bloc);\n this.bloc._dispose();\n }\n }\n\n /**\n * Notifies all observers of a state change\n * @param newState - The new state value\n * @param oldState - The previous state value\n * @param action - Optional action that triggered the state change\n */\n notify(newState: S, oldState: S, action?: unknown) {\n this._observers.forEach((observer) => {\n let shouldUpdate = false;\n\n if (observer.dependencyArray) {\n const lastDependencyCheck = observer.lastState || [];\n const newDependencyCheck = observer.dependencyArray(newState);\n\n for (let o = 0; o < newDependencyCheck.length; o++) {\n const partNew = newDependencyCheck[o];\n const partOld = lastDependencyCheck[o] || [];\n for (let i = 0; i < partNew.length; i++) {\n if (!Object.is(partNew[i], partOld[i])) {\n shouldUpdate = true;\n break;\n }\n }\n }\n\n observer.lastState = newDependencyCheck;\n } else {\n shouldUpdate = true;\n }\n\n if (shouldUpdate) {\n void observer.fn(newState, oldState, action);\n }\n });\n }\n\n /**\n * Clears the observer set\n */\n clear() {\n this._observers.forEach((observer) => {\n this.unsubscribe(observer);\n });\n this._observers.clear();\n }\n}\n","import { BlacObservable } from './BlacObserver';\nimport { BlocConstructor } from './types';\n\nexport type BlocInstanceId = string | number | undefined;\ntype DependencySelector<S> = (newState: S) => unknown[][];\n\n// Define an interface for the static properties expected on a Bloc/Cubit constructor\ninterface BlocStaticProperties {\n isolated: boolean;\n keepAlive: boolean;\n}\n\n/**\n * Base class for both Blocs and Cubits that provides core state management functionality.\n * Handles state transitions, observer notifications, lifecycle management, and addon integration.\n * \n * @abstract This class should be extended, not instantiated directly\n * @template S The type of state managed by this Bloc\n * @template P The type of props that can be passed during instance creation (optional)\n */\nexport abstract class BlocBase<\n S,\n P = unknown\n> {\n public uid = crypto.randomUUID();\n /**\n * When true, every consumer will receive its own unique instance of this Bloc.\n * Use this when state should not be shared between components.\n * @default false\n */\n static isolated = false;\n get isIsolated() {\n return this._isolated;\n }\n \n /**\n * When true, the Bloc instance persists even when there are no active consumers.\n * Useful for maintaining state between component unmount/remount cycles.\n * @default false\n */\n static keepAlive = false;\n get isKeepAlive() {\n return this._keepAlive;\n }\n \n /**\n * Defines how dependencies are selected from the state for efficient updates.\n * When provided, observers will only be notified when selected dependencies change.\n */\n defaultDependencySelector: DependencySelector<S> | undefined;\n \n /**\n * @internal\n * Indicates if this specific Bloc instance is isolated from others of the same type.\n */\n public _isolated = false;\n \n /**\n * @internal\n * Observable responsible for managing state listeners and notifying consumers.\n */\n public _observer: BlacObservable<S>;\n \n /**\n * The unique identifier for this Bloc instance.\n * Defaults to the class name, but can be customized.\n */\n public _id: BlocInstanceId;\n \n /**\n * @internal\n * Reference string used internally for tracking and debugging.\n */\n public _instanceRef?: string;\n \n /**\n * @internal\n * Indicates if this specific Bloc instance should be kept alive when no consumers are present.\n */\n public _keepAlive = false;\n \n /**\n * @readonly\n * Timestamp when this Bloc instance was created, useful for debugging and performance tracking.\n */\n public readonly _createdAt = Date.now();\n\n /**\n * @internal\n * The current state of the Bloc.\n */\n public _state: S;\n \n /**\n * @internal\n * The previous state of the Bloc, maintained for comparison and history.\n */\n public _oldState: S | undefined;\n \n /**\n * Props passed during Bloc instance creation.\n * Can be used to configure or parameterize the Bloc's behavior.\n */\n public props: P | null = null;\n\n /**\n * Creates a new BlocBase instance with the given initial state.\n * Sets up the observer, registers with the Blac manager, and initializes addons.\n * \n * @param initialState The initial state value for this Bloc\n */\n constructor(initialState: S) {\n this._state = initialState;\n this._observer = new BlacObservable(this);\n this._id = this.constructor.name;\n\n // Access static properties safely with proper type checking\n const Constructor = this.constructor as typeof BlocBase & BlocStaticProperties;\n \n // Validate that the static properties exist and are boolean\n this._keepAlive = typeof Constructor.keepAlive === 'boolean' ? Constructor.keepAlive : false;\n this._isolated = typeof Constructor.isolated === 'boolean' ? Constructor.isolated : false;\n }\n\n /**\n * Returns the current state of the Bloc.\n * Use this getter to access the state in a read-only manner.\n */\n get state(): S {\n return this._state;\n }\n\n /**\n * @internal\n * Returns the name of the Bloc class for identification and debugging.\n */\n get _name() {\n return this.constructor.name;\n }\n\n /**\n * @internal\n * Updates the Bloc instance's ID to a new value.\n * Only updates if the new ID is defined and different from the current one.\n * \n * @param id The new ID to assign to this Bloc instance\n */\n _updateId = (id?: BlocInstanceId) => {\n const originalId = this._id;\n if (!id || id === originalId) return;\n this._id = id;\n };\n\n /**\n * @internal\n * Cleans up resources and removes this Bloc from the system.\n * Notifies the Blac manager and clears all observers.\n */\n _dispose() {\n // Clear all consumers\n this._consumers.clear();\n \n // Clear observer subscriptions\n this._observer.clear();\n \n // Call user-defined disposal hook\n this.onDispose?.();\n \n // The Blac manager will handle removal from registry\n // This method is called by Blac.disposeBloc, so we don't need to call it again\n }\n\n /**\n * @internal\n * Optional function to be called when the Bloc is disposed.\n */\n onDispose?: () => void;\n\n /**\n * @internal\n * Set of consumer IDs currently listening to this Bloc's state changes.\n */\n _consumers = new Set<string>();\n\n /**\n * @internal\n * WeakSet to track consumer references for cleanup validation\n */\n private _consumerRefs = new WeakSet<object>();\n\n /**\n * @internal\n * Registers a new consumer to this Bloc instance.\n * Notifies the Blac manager that a consumer has been added.\n * \n * @param consumerId The unique ID of the consumer being added\n * @param consumerRef Optional reference to the consumer object for cleanup validation\n */\n _addConsumer = (consumerId: string, consumerRef?: object) => {\n if (this._consumers.has(consumerId)) return;\n this._consumers.add(consumerId);\n \n if (consumerRef) {\n this._consumerRefs.add(consumerRef);\n }\n \n // this._blac.dispatchEvent(BlacLifecycleEvent.BLOC_CONSUMER_ADDED, this, { consumerId });\n };\n\n /**\n * @internal\n * Unregisters a consumer from this Bloc instance.\n * Notifies the Blac manager that a consumer has been removed.\n * \n * @param consumerId The unique ID of the consumer being removed\n */\n _removeConsumer = (consumerId: string) => {\n if (!this._consumers.has(consumerId)) return;\n this._consumers.delete(consumerId);\n // this._blac.dispatchEvent(BlacLifecycleEvent.BLOC_CONSUMER_REMOVED, this, { consumerId });\n \n // If no consumers remain and not keep-alive, schedule disposal\n if (this._consumers.size === 0 && !this._keepAlive) {\n this._scheduleDisposal();\n }\n };\n\n /**\n * @internal\n * Handler function for disposal (can be set by Blac manager)\n */\n private _disposalHandler?: (bloc: BlocBase<unknown>) => void;\n\n /**\n * @internal\n * Sets the disposal handler for this bloc\n */\n _setDisposalHandler(handler: (bloc: BlocBase<unknown>) => void) {\n this._disposalHandler = handler;\n }\n\n /**\n * @internal\n * Schedules disposal of this bloc instance if it has no consumers\n */\n private _scheduleDisposal() {\n // Use setTimeout to avoid disposal during render cycles\n setTimeout(() => {\n if (this._consumers.size === 0 && !this._keepAlive) {\n if (this._disposalHandler) {\n this._disposalHandler(this as any);\n } else {\n this._dispose();\n }\n }\n }, 0);\n }\n\n lastUpdate = Date.now();\n\n /**\n * @internal\n * Flag to indicate if batching is enabled for this bloc\n */\n private _batchingEnabled = false;\n\n /**\n * @internal\n * Pending state updates when batching is enabled\n */\n private _pendingUpdates: Array<{newState: S, oldState: S, action?: unknown}> = [];\n\n /**\n * @internal\n * Updates the state and notifies all observers of the change.\n * \n * @param newState The new state to be set\n * @param oldState The previous state for comparison\n * @param action Optional metadata about what caused the state change\n */\n _pushState = (newState: S, oldState: S, action?: unknown): void => {\n // Runtime validation for state changes\n if (newState === undefined) {\n console.warn('BlocBase._pushState: newState is undefined', this);\n return;\n }\n \n // Validate action type if provided\n if (action !== undefined && action !== null) {\n const actionType = typeof action;\n if (!(['string', 'object', 'number'].includes(actionType))) {\n console.warn('BlocBase._pushState: Invalid action type', this, action);\n }\n }\n\n // If batching is enabled, queue the update\n if (this._batchingEnabled) {\n this._pendingUpdates.push({ newState, oldState, action });\n return;\n }\n \n this._oldState = oldState;\n this._state = newState;\n this._observer.notify(newState, oldState, action);\n this.lastUpdate = Date.now();\n };\n\n /**\n * Enables batching for multiple state updates\n * @param batchFn Function to execute with batching enabled\n */\n batch = <T>(batchFn: () => T): T => {\n const wasBatching = this._batchingEnabled;\n this._batchingEnabled = true;\n \n try {\n const result = batchFn();\n \n // Process all pending updates\n if (this._pendingUpdates.length > 0) {\n const lastUpdate = this._pendingUpdates[this._pendingUpdates.length - 1];\n this._oldState = this._pendingUpdates[0].oldState;\n this._state = lastUpdate.newState;\n \n // Notify with the final state\n this._observer.notify(lastUpdate.newState, this._oldState, lastUpdate.action);\n this.lastUpdate = Date.now();\n \n this._pendingUpdates = [];\n }\n \n return result;\n } finally {\n this._batchingEnabled = wasBatching;\n }\n };\n}\n","import { Blac } from './Blac';\nimport { BlocBase } from './BlocBase';\n\n// A should be the base type for all events this Bloc handles and must be an object type\n// to access action.constructor. Events are typically class instances.\n// P is for props, changed from any to unknown.\nexport abstract class Bloc<\n S, // State type\n A extends object, // Base Action/Event type, constrained to object\n P = unknown // Props type\n> extends BlocBase<S, P> {\n // Stores handlers: Map<EventConstructor (subtype of A), HandlerFunction>\n // The handler's event parameter will be correctly typed to the specific EventConstructor\n // by the 'on' method's signature.\n readonly eventHandlers: Map<\n // Key: Constructor of a specific event E (where E extends A)\n // Using 'any[]' for constructor arguments for broader compatibility.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n new (...args: any[]) => A,\n // Value: Handler function. 'event: A' is used here for the stored function type.\n // The 'on' method ensures the specific handler (event: E) is correctly typed.\n (event: A, emit: (newState: S) => void) => void | Promise<void>\n > = new Map();\n\n /**\n * Registers an event handler for a specific event type.\n * This method is typically called in the constructor of a derived Bloc class.\n * @param eventConstructor The constructor of the event to handle (e.g., LoadDataEvent).\n * @param handler A function that processes the event and can emit new states.\n * The 'event' parameter in the handler will be typed to the specific eventConstructor.\n */\n protected on<E extends A>(\n // Using 'any[]' for constructor arguments for broader compatibility.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n eventConstructor: new (...args: any[]) => E, \n handler: (event: E, emit: (newState: S) => void) => void | Promise<void>\n ): void {\n if (this.eventHandlers.has(eventConstructor)) {\n // Using Blac.warn or a similar logging mechanism from BlocBase if available,\n // otherwise console.warn. Assuming this._name and this._id are available from BlocBase.\n Blac.warn(\n `[Bloc ${this._name}:${String(this._id)}] Handler for event '${eventConstructor.name}' already registered. It will be overwritten.`\n );\n }\n // Cast the specific handler (event: E) to a more general (event: A) for storage.\n // This is safe because E extends A. When the handler is called with an 'action' of type A,\n // if it was originally registered for type E, 'action' must be an instance of E.\n this.eventHandlers.set(\n eventConstructor,\n handler as (event: A, emit: (newState: S) => void) => void | Promise<void>\n );\n }\n\n /**\n * Dispatches an action/event to the Bloc.\n * If a handler is registered for this specific event type (via 'on'), it will be invoked.\n * Asynchronous handlers are awaited.\n * @param action The action/event instance to be processed.\n */\n public add = async (action: A): Promise<void> => {\n // Using 'any[]' for constructor arguments for broader compatibility.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const eventConstructor = action.constructor as new (...args: any[]) => A;\n const handler = this.eventHandlers.get(eventConstructor);\n\n if (handler) {\n // Define the 'emit' function that handlers will use to update state.\n // It captures the current state ('this.state') right before each emission\n // to provide the correct 'previousState' to _pushState.\n const emit = (newState: S): void => {\n const previousState = this.state; // State just before this specific emission\n // The 'action' passed to _pushState is the original action that triggered the handler,\n // providing context for the state change (e.g., for logging or plugins).\n this._pushState(newState, previousState, action);\n };\n\n try {\n // Await the handler in case it's an async function (e.g., performs API calls).\n // The 'action' is passed to the handler, and due to the way 'on' is typed,\n // the 'event' parameter within the handler function will be correctly\n // typed to its specific class (e.g., LoadMyFeatureData).\n await handler(action, emit);\n } catch (error) {\n // It's good practice to handle errors occurring within event handlers.\n Blac.error(\n `[Bloc ${this._name}:${String(this._id)}] Error in event handler for '${eventConstructor.name}':`,\n error,\n \"Action:\", action\n );\n // Depending on the desired error handling strategy, you might:\n // 1. Emit a specific error state: this.emit(new MyErrorState(error));\n // 2. Re-throw the error: throw error;\n // 3. Log and ignore (as done here by default).\n // This should be decided based on application requirements.\n }\n } else {\n // action.constructor.name should be safe due to 'A extends object' and common JS practice for constructors.\n // If linting still complains, it might be overly strict for this common pattern.\n const constructorName = (action.constructor as { name?: string }).name || 'UnnamedConstructor';\n Blac.warn(\n `[Bloc ${this._name}:${String(this._id)}] No handler registered for action type: '${constructorName}'. Action was:`,\n action\n );\n // If no handler is found, the action is effectively ignored.\n // Consider if this is the desired behavior or if an error should be thrown\n // or a default handler should be invoked.\n }\n };\n}\n","import { Blac } from './Blac';\nimport { BlocBase } from './BlocBase';\n\n/**\n * A Cubit is a simpler version of a Bloc that doesn't handle events.\n * It manages state and provides methods to update it.\n * @template S - The type of state this Cubit manages\n * @template P - The type of parameters (optional, defaults to null)\n */\nexport abstract class Cubit<S, P = null> extends BlocBase<S, P> {\n /**\n * Updates the current state and notifies all observers of the change.\n * If the new state is identical to the current state (using Object.is),\n * no update will occur.\n * @param state - The new state to set\n */\n emit(state: S): void {\n if (Object.is(state, this.state)) {\n return;\n }\n\n const oldState = this.state;\n const newState = state;\n this._pushState(newState, oldState);\n }\n\n /**\n * Partially updates the current state by merging it with the provided state patch.\n * This method is only applicable when the state is an object type.\n * \n * @param statePatch - A partial state object containing only the properties to update\n * @param ignoreChangeCheck - If true, skips checking if the state has actually changed\n * @throws {TypeError} If the state is not an object type\n */\n patch(\n statePatch: S extends object ? Partial<S> : S,\n ignoreChangeCheck = false,\n ): void {\n if (typeof this.state !== 'object' || this.state === null) {\n Blac.warn(\n 'Cubit.patch: was called on a cubit where the state is not an object. This is a no-op.',\n );\n return;\n }\n\n let changes = false;\n if (!ignoreChangeCheck) {\n for (const key in statePatch) {\n if (Object.prototype.hasOwnProperty.call(statePatch, key)) {\n const s = this.state;\n const current = s[key as keyof S];\n if (!Object.is(statePatch[key as keyof S], current)) {\n changes = true;\n break;\n }\n }\n }\n } else {\n changes = true;\n }\n\n if (changes) {\n this.emit({\n ...this.state,\n ...(statePatch as Partial<S>),\n } as S);\n }\n }\n}\n"],"names":["_SingletonBlacManager","Blac","instance","oldInstance","bloc","__publicField","SingletonBlacManager","instanceManager","setBlacInstanceManager","manager","_Blac","options","args","message","oldBlocInstanceMap","oldIsolatedBlocMap","blocArray","base","key","blocClass","id","blocId","isolatedBloc","registeredBloc","isIsolated","registered","results","blocInstance","isolatedBlocs","toDispose","predicate","blocs","sum","arr","__unsafe_ignore_singleton","blocClassName","index","b","uid","props","instanceRef","newBloc","BlacObservable","observer","newState","oldState","action","shouldUpdate","lastDependencyCheck","newDependencyCheck","o","partNew","partOld","i","BlocBase","initialState","originalId","consumerId","consumerRef","actionType","batchFn","wasBatching","result","lastUpdate","Constructor","_a","handler","Bloc","eventConstructor","emit","previousState","error","constructorName","Cubit","state","statePatch","ignoreChangeCheck","changes","current"],"mappings":"oPAwCA,MAAMA,EAAN,MAAMA,CAAoD,CAGxD,aAAoB,CAC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CACxF,EAKJ,KAAK,cAAc,IACfA,EACAF,CACJ,CAAA,CA0DR,CCnGO,MAAeO,UAA2BnB,CAAe,CAO9D,KAAKoB,EAAgB,CACnB,GAAI,OAAO,GAAGA,EAAO,KAAK,KAAK,EAC7B,OAGF,MAAM7B,EAAW,KAAK,MAChBD,EAAW8B,EACZ,KAAA,WAAW9B,EAAUC,CAAQ,CAAA,CAWpC,MACE8B,EACAC,EAAoB,GACd,CACN,GAAI,OAAO,KAAK,OAAU,UAAY,KAAK,QAAU,KAAM,CACpD3E,EAAA,KACH,uFACF,EACA,MAAA,CAGF,IAAI4E,EAAU,GACd,GAAKD,EAYOC,EAAA,OAXV,WAAW3D,KAAOyD,EAChB,GAAI,OAAO,UAAU,eAAe,KAAKA,EAAYzD,CAAG,EAAG,CAEnD,MAAA4D,EADI,KAAK,MACG5D,CAAc,EAChC,GAAI,CAAC,OAAO,GAAGyD,EAAWzD,CAAc,EAAG4D,CAAO,EAAG,CACzCD,EAAA,GACV,KAAA,CACF,CAOFA,GACF,KAAK,KAAK,CACR,GAAG,KAAK,MACR,GAAIF,CAAA,CACA,CACR,CAEJ"}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Main Blac class that manages the state management system.
|
|
3
|
-
*
|
|
3
|
+
* Can work with singleton pattern or dependency injection.
|
|
4
4
|
* Handles bloc lifecycle, and instance tracking.
|
|
5
5
|
*
|
|
6
6
|
* Key responsibilities:
|
|
@@ -9,17 +9,23 @@
|
|
|
9
9
|
* - Providing logging and debugging capabilities
|
|
10
10
|
*/
|
|
11
11
|
export declare class Blac {
|
|
12
|
-
/**
|
|
13
|
-
static instance: Blac;
|
|
12
|
+
/** @deprecated Use getInstance() instead */
|
|
13
|
+
static get instance(): Blac;
|
|
14
14
|
/** Timestamp when the instance was created */
|
|
15
15
|
createdAt: number;
|
|
16
|
-
static getAllBlocs: <B extends BlocConstructor<unknown>>(blocClass: B, options?: {
|
|
16
|
+
static get getAllBlocs(): <B extends BlocConstructor<unknown>>(blocClass: B, options?: {
|
|
17
17
|
searchIsolated?: boolean;
|
|
18
18
|
}) => InstanceType<B>[];
|
|
19
19
|
/** Map storing all registered bloc instances by their class name and ID */
|
|
20
|
-
blocInstanceMap: Map<string, BlocBase<
|
|
20
|
+
blocInstanceMap: Map<string, BlocBase<unknown>>;
|
|
21
21
|
/** Map storing isolated bloc instances grouped by their constructor */
|
|
22
|
-
isolatedBlocMap: Map<BlocConstructor<
|
|
22
|
+
isolatedBlocMap: Map<BlocConstructor<unknown>, BlocBase<unknown>[]>;
|
|
23
|
+
/** Map for O(1) lookup of isolated blocs by UID */
|
|
24
|
+
private isolatedBlocIndex;
|
|
25
|
+
/** Map tracking UIDs to prevent memory leaks */
|
|
26
|
+
uidRegistry: Map<string, BlocBase<unknown>>;
|
|
27
|
+
/** Set of keep-alive blocs for controlled cleanup */
|
|
28
|
+
keepAliveBlocs: Set<BlocBase<unknown>>;
|
|
23
29
|
/** Flag to control whether changes should be posted to document */
|
|
24
30
|
postChangesToDocument: boolean;
|
|
25
31
|
/**
|
|
@@ -36,9 +42,9 @@ export declare class Blac {
|
|
|
36
42
|
* @param args - Arguments to log
|
|
37
43
|
*/
|
|
38
44
|
log: (...args: unknown[]) => void;
|
|
39
|
-
static log: (...args: unknown[]) => void;
|
|
45
|
+
static get log(): (...args: unknown[]) => void;
|
|
40
46
|
/**
|
|
41
|
-
* Gets the
|
|
47
|
+
* Gets the current Blac instance
|
|
42
48
|
* @returns The Blac instance
|
|
43
49
|
*/
|
|
44
50
|
static getInstance(): Blac;
|
|
@@ -48,14 +54,14 @@ export declare class Blac {
|
|
|
48
54
|
* @param args - Additional arguments
|
|
49
55
|
*/
|
|
50
56
|
warn: (message: string, ...args: unknown[]) => void;
|
|
51
|
-
static warn: (message: string, ...args: unknown[]) => void;
|
|
57
|
+
static get warn(): (message: string, ...args: unknown[]) => void;
|
|
52
58
|
/**
|
|
53
59
|
* Logs an error message
|
|
54
60
|
* @param message - Error message
|
|
55
61
|
* @param args - Additional arguments
|
|
56
62
|
*/
|
|
57
63
|
error: (message: string, ...args: unknown[]) => void;
|
|
58
|
-
static error: (message: string, ...args: unknown[]) => void;
|
|
64
|
+
static get error(): (message: string, ...args: unknown[]) => void;
|
|
59
65
|
/**
|
|
60
66
|
* Resets the Blac instance to a new one, disposing non-keepAlive blocs
|
|
61
67
|
* from the old instance.
|
|
@@ -66,7 +72,7 @@ export declare class Blac {
|
|
|
66
72
|
* Disposes of a bloc instance by removing it from the appropriate registry
|
|
67
73
|
* @param bloc - The bloc instance to dispose
|
|
68
74
|
*/
|
|
69
|
-
disposeBloc: (bloc: BlocBase<
|
|
75
|
+
disposeBloc: (bloc: BlocBase<unknown>) => void;
|
|
70
76
|
/**
|
|
71
77
|
* Creates a unique key for a bloc instance in the map based on the bloc class name and instance ID
|
|
72
78
|
* @param blocClassName - The name of the bloc class
|
|
@@ -78,12 +84,12 @@ export declare class Blac {
|
|
|
78
84
|
* Unregister a bloc instance from the main registry
|
|
79
85
|
* @param bloc - The bloc instance to unregister
|
|
80
86
|
*/
|
|
81
|
-
unregisterBlocInstance(bloc: BlocBase<
|
|
87
|
+
unregisterBlocInstance(bloc: BlocBase<unknown>): void;
|
|
82
88
|
/**
|
|
83
89
|
* Registers a bloc instance in the main registry
|
|
84
90
|
* @param bloc - The bloc instance to register
|
|
85
91
|
*/
|
|
86
|
-
registerBlocInstance(bloc: BlocBase<
|
|
92
|
+
registerBlocInstance(bloc: BlocBase<unknown>): void;
|
|
87
93
|
/**
|
|
88
94
|
* Finds a registered bloc instance by its class and ID
|
|
89
95
|
* @param blocClass - The bloc class to search for
|
|
@@ -95,16 +101,20 @@ export declare class Blac {
|
|
|
95
101
|
* Registers an isolated bloc instance in the isolated registry
|
|
96
102
|
* @param bloc - The isolated bloc instance to register
|
|
97
103
|
*/
|
|
98
|
-
registerIsolatedBlocInstance(bloc: BlocBase<
|
|
104
|
+
registerIsolatedBlocInstance(bloc: BlocBase<unknown>): void;
|
|
99
105
|
/**
|
|
100
106
|
* Unregister an isolated bloc instance from the isolated registry
|
|
101
107
|
* @param bloc - The isolated bloc instance to unregister
|
|
102
108
|
*/
|
|
103
|
-
unregisterIsolatedBlocInstance(bloc: BlocBase<
|
|
109
|
+
unregisterIsolatedBlocInstance(bloc: BlocBase<unknown>): void;
|
|
104
110
|
/**
|
|
105
|
-
* Finds an isolated bloc instance by its class and ID
|
|
111
|
+
* Finds an isolated bloc instance by its class and ID (O(n) lookup)
|
|
106
112
|
*/
|
|
107
113
|
findIsolatedBlocInstance<B extends BlocConstructor<unknown>>(blocClass: B, id: BlocInstanceId): InstanceType<B> | undefined;
|
|
114
|
+
/**
|
|
115
|
+
* Finds an isolated bloc instance by UID (O(1) lookup)
|
|
116
|
+
*/
|
|
117
|
+
findIsolatedBlocInstanceByUid<B extends BlocBase<unknown>>(uid: string): B | undefined;
|
|
108
118
|
/**
|
|
109
119
|
* Creates a new bloc instance and registers it in the appropriate registry
|
|
110
120
|
* @param blocClass - The bloc class to instantiate
|
|
@@ -113,9 +123,9 @@ export declare class Blac {
|
|
|
113
123
|
* @param instanceRef - Optional reference string for the instance
|
|
114
124
|
* @returns The newly created bloc instance
|
|
115
125
|
*/
|
|
116
|
-
createNewBlocInstance<B extends BlocConstructor<BlocBase<
|
|
117
|
-
activateBloc: (bloc: BlocBase<
|
|
118
|
-
static activateBloc: (bloc: BlocBase<
|
|
126
|
+
createNewBlocInstance<B extends BlocConstructor<BlocBase<unknown>>>(blocClass: B, id: BlocInstanceId, options?: GetBlocOptions<InstanceType<B>>): InstanceType<B>;
|
|
127
|
+
activateBloc: (bloc: BlocBase<unknown>) => void;
|
|
128
|
+
static get activateBloc(): (bloc: BlocBase<unknown>) => void;
|
|
119
129
|
/**
|
|
120
130
|
* Gets or creates a bloc instance based on the provided class and options.
|
|
121
131
|
* If a bloc with the given ID exists, it will be returned. Otherwise, a new instance will be created.
|
|
@@ -127,8 +137,8 @@ export declare class Blac {
|
|
|
127
137
|
* - instanceRef: Optional reference string for the instance
|
|
128
138
|
* @returns The bloc instance
|
|
129
139
|
*/
|
|
130
|
-
getBloc: <B extends BlocConstructor<BlocBase<
|
|
131
|
-
static getBloc: <B extends BlocConstructor<BlocBase<
|
|
140
|
+
getBloc: <B extends BlocConstructor<BlocBase<unknown>>>(blocClass: B, options?: GetBlocOptions<InstanceType<B>>) => InstanceType<B>;
|
|
141
|
+
static get getBloc(): <B extends BlocConstructor<BlocBase<unknown>>>(blocClass: B, options?: GetBlocOptions<InstanceType<B>>) => InstanceType<B>;
|
|
132
142
|
/**
|
|
133
143
|
* Gets a bloc instance or throws an error if it doesn't exist
|
|
134
144
|
* @param blocClass - The bloc class to get
|
|
@@ -142,7 +152,7 @@ export declare class Blac {
|
|
|
142
152
|
props?: InferPropsFromGeneric<B>;
|
|
143
153
|
instanceRef?: string;
|
|
144
154
|
}) => InstanceType<B>;
|
|
145
|
-
static getBlocOrThrow: <B extends BlocConstructor<unknown>>(blocClass: B, options?: {
|
|
155
|
+
static get getBlocOrThrow(): <B extends BlocConstructor<unknown>>(blocClass: B, options?: {
|
|
146
156
|
id?: BlocInstanceId;
|
|
147
157
|
props?: InferPropsFromGeneric<B> | undefined;
|
|
148
158
|
instanceRef?: string;
|
|
@@ -157,6 +167,40 @@ export declare class Blac {
|
|
|
157
167
|
getAllBlocs: <B extends BlocConstructor<unknown>>(blocClass: B, options?: {
|
|
158
168
|
searchIsolated?: boolean;
|
|
159
169
|
}) => InstanceType<B>[];
|
|
170
|
+
/**
|
|
171
|
+
* Disposes all keep-alive blocs of a specific type
|
|
172
|
+
* @param blocClass - The bloc class to dispose
|
|
173
|
+
*/
|
|
174
|
+
disposeKeepAliveBlocs: <B extends BlocConstructor<unknown>>(blocClass?: B) => void;
|
|
175
|
+
static get disposeKeepAliveBlocs(): <B extends BlocConstructor<unknown>>(blocClass?: B | undefined) => void;
|
|
176
|
+
/**
|
|
177
|
+
* Disposes all blocs matching a pattern
|
|
178
|
+
* @param predicate - Function to test each bloc for disposal
|
|
179
|
+
*/
|
|
180
|
+
disposeBlocs: (predicate: (bloc: BlocBase<unknown>) => boolean) => void;
|
|
181
|
+
static get disposeBlocs(): (predicate: (bloc: BlocBase<unknown>) => boolean) => void;
|
|
182
|
+
/**
|
|
183
|
+
* Gets memory usage statistics for debugging
|
|
184
|
+
*/
|
|
185
|
+
getMemoryStats: () => {
|
|
186
|
+
totalBlocs: number;
|
|
187
|
+
registeredBlocs: number;
|
|
188
|
+
isolatedBlocs: number;
|
|
189
|
+
keepAliveBlocs: number;
|
|
190
|
+
isolatedBlocTypes: number;
|
|
191
|
+
};
|
|
192
|
+
static get getMemoryStats(): () => {
|
|
193
|
+
totalBlocs: number;
|
|
194
|
+
registeredBlocs: number;
|
|
195
|
+
isolatedBlocs: number;
|
|
196
|
+
keepAliveBlocs: number;
|
|
197
|
+
isolatedBlocTypes: number;
|
|
198
|
+
};
|
|
199
|
+
/**
|
|
200
|
+
* Validates consumer references and cleans up orphaned consumers
|
|
201
|
+
*/
|
|
202
|
+
validateConsumers: () => void;
|
|
203
|
+
static get validateConsumers(): () => void;
|
|
160
204
|
}
|
|
161
205
|
|
|
162
206
|
/**
|
|
@@ -167,6 +211,15 @@ export declare interface BlacConfig {
|
|
|
167
211
|
exposeBlacInstance?: boolean;
|
|
168
212
|
}
|
|
169
213
|
|
|
214
|
+
/**
|
|
215
|
+
* Interface for Blac instance management
|
|
216
|
+
*/
|
|
217
|
+
export declare interface BlacInstanceManager {
|
|
218
|
+
getInstance(): Blac;
|
|
219
|
+
setInstance(instance: Blac): void;
|
|
220
|
+
resetInstance(): void;
|
|
221
|
+
}
|
|
222
|
+
|
|
170
223
|
/**
|
|
171
224
|
* A class that manages observers for a Bloc's state changes
|
|
172
225
|
* @template S - The type of state being observed
|
|
@@ -283,7 +336,6 @@ export declare abstract class BlocBase<S, P = unknown> {
|
|
|
283
336
|
defaultDependencySelector: DependencySelector<S> | undefined;
|
|
284
337
|
/* Excluded from this release type: _isolated */
|
|
285
338
|
/* Excluded from this release type: _observer */
|
|
286
|
-
/* Excluded from this release type: _blac */
|
|
287
339
|
/**
|
|
288
340
|
* The unique identifier for this Bloc instance.
|
|
289
341
|
* Defaults to the class name, but can be customized.
|
|
@@ -320,10 +372,21 @@ export declare abstract class BlocBase<S, P = unknown> {
|
|
|
320
372
|
/* Excluded from this release type: _dispose */
|
|
321
373
|
/* Excluded from this release type: onDispose */
|
|
322
374
|
/* Excluded from this release type: _consumers */
|
|
375
|
+
/* Excluded from this release type: _consumerRefs */
|
|
323
376
|
/* Excluded from this release type: _addConsumer */
|
|
324
377
|
/* Excluded from this release type: _removeConsumer */
|
|
378
|
+
/* Excluded from this release type: _disposalHandler */
|
|
379
|
+
/* Excluded from this release type: _setDisposalHandler */
|
|
380
|
+
/* Excluded from this release type: _scheduleDisposal */
|
|
325
381
|
lastUpdate: number;
|
|
382
|
+
/* Excluded from this release type: _batchingEnabled */
|
|
383
|
+
/* Excluded from this release type: _pendingUpdates */
|
|
326
384
|
/* Excluded from this release type: _pushState */
|
|
385
|
+
/**
|
|
386
|
+
* Enables batching for multiple state updates
|
|
387
|
+
* @param batchFn Function to execute with batching enabled
|
|
388
|
+
*/
|
|
389
|
+
batch: <T>(batchFn: () => T) => T;
|
|
327
390
|
}
|
|
328
391
|
|
|
329
392
|
/**
|
|
@@ -390,7 +453,7 @@ export declare abstract class Cubit<S, P = null> extends BlocBase<S, P> {
|
|
|
390
453
|
|
|
391
454
|
declare type DependencySelector<S> = (newState: S) => unknown[][];
|
|
392
455
|
|
|
393
|
-
export declare interface GetBlocOptions<B extends BlocBase<
|
|
456
|
+
export declare interface GetBlocOptions<B extends BlocBase<unknown>> {
|
|
394
457
|
id?: string;
|
|
395
458
|
selector?: BlocHookDependencyArrayFn<BlocState<B>>;
|
|
396
459
|
props?: InferPropsFromGeneric<B>;
|
|
@@ -405,6 +468,11 @@ export declare interface GetBlocOptions<B extends BlocBase<any>> {
|
|
|
405
468
|
*/
|
|
406
469
|
export declare type InferPropsFromGeneric<T> = T extends Bloc<any, any, infer P> ? P : T extends Cubit<any, infer P> ? P : never;
|
|
407
470
|
|
|
471
|
+
/**
|
|
472
|
+
* Sets a custom instance manager (useful for testing or advanced patterns)
|
|
473
|
+
*/
|
|
474
|
+
export declare function setBlacInstanceManager(manager: BlacInstanceManager): void;
|
|
475
|
+
|
|
408
476
|
/**
|
|
409
477
|
* Extracts the state type from a BlocBase instance
|
|
410
478
|
* @template B - The BlocBase type to extract the state from
|