@blac/core 2.0.0-rc-4 → 2.0.0-rc-6

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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.es.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":";;;AAwCA,MAAMA,IAAN,MAAMA,EAAoD;AAAA,EAGxD,cAAoB;AACd,WAACA,EAAqB,cACxBA,EAAqB,YAAY,IAAIC,EAAK,EAAE,2BAA2B,IAAM,IAExED,EAAqB;AAAA,EAAA;AAAA,EAG9B,YAAYE,GAAsB;AAChC,IAAAF,EAAqB,YAAYE;AAAA,EAAA;AAAA,EAGnC,gBAAsB;AACpB,UAAMC,IAAcH,EAAqB;AACzC,IAAAA,EAAqB,YAAY,IAAIC,EAAK,EAAE,2BAA2B,IAAM;AAGlE,eAAAG,KAAQD,EAAY;AACR,MAAAH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O,MAAAC,IAAA;AAAA;AAXV,iBAAW3D,KAAOyD;AAChB,YAAI,OAAO,UAAU,eAAe,KAAKA,GAAYzD,CAAG,GAAG;AAEnD,gBAAA4D,IADI,KAAK,MACG5D,CAAc;AAChC,cAAI,CAAC,OAAO,GAAGyD,EAAWzD,CAAc,GAAG4D,CAAO,GAAG;AACzC,YAAAD,IAAA;AACV;AAAA,UAAA;AAAA,QACF;AAON,IAAIA,KACF,KAAK,KAAK;AAAA,MACR,GAAG,KAAK;AAAA,MACR,GAAIF;AAAA,IAAA,CACA;AAAA,EACR;AAEJ;"}
1
+ {"version":3,"file":"index.es.js","sources":["../src/Blac.ts","../src/BlacObserver.ts","../src/utils/uuid.ts","../src/BlocBase.ts","../src/Bloc.ts","../src/Cubit.ts","../src/testing.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 if (oldInstance) {\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/**\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<any>, 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 // Create snapshots to avoid concurrent modification issues\n const oldBlocInstanceMap = new Map(this.blocInstanceMap);\n const oldIsolatedBlocMap = new Map(this.isolatedBlocMap);\n\n // Dispose non-keepAlive blocs from the current instance\n // Use disposeBloc method to ensure proper cleanup\n oldBlocInstanceMap.forEach((bloc) => {\n if (!bloc._keepAlive && (bloc as any)._disposalState === 'active') {\n this.disposeBloc(bloc);\n }\n });\n\n oldIsolatedBlocMap.forEach((blocArray) => {\n blocArray.forEach((bloc) => {\n if (!bloc._keepAlive && (bloc as any)._disposalState === 'active') {\n this.disposeBloc(bloc);\n }\n });\n });\n\n // Clear registries (keep-alive blocs will be re-added by instance manager)\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 // Check if bloc is already disposed to prevent double disposal\n if ((bloc as any)._disposalState !== 'active') {\n this.log(`[${bloc._name}:${String(bloc._id)}] disposeBloc called on already disposed bloc`);\n return;\n }\n\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 // First dispose the bloc to prevent further operations\n bloc._dispose();\n \n // Then clean up from registries\n if (base.isolated) {\n this.unregisterIsolatedBlocInstance(bloc);\n this.blocInstanceMap.delete(key);\n } else {\n this.unregisterBlocInstance(bloc);\n }\n \n this.log('dispatched bloc', bloc)\n };\n static get disposeBloc() { return Blac.instance.disposeBloc; }\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<any>>(\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<any>;\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<any>);\n \n // Ensure both data structures are synchronized\n let wasRemoved = false;\n \n if (blocs) {\n const index = blocs.findIndex((b) => b.uid === bloc.uid);\n if (index !== -1) {\n blocs.splice(index, 1);\n wasRemoved = true;\n }\n\n if (blocs.length === 0) {\n this.isolatedBlocMap.delete(blocClass as BlocConstructor<any>);\n }\n }\n \n // Always try to remove from isolated index, even if not found in map\n const wasInIndex = 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 // Log inconsistency for debugging\n if (wasRemoved !== wasInIndex) {\n this.warn(\n `[Blac] Inconsistent state detected during isolated bloc cleanup for ${bloc._name}:${bloc.uid}. ` +\n `Map removal: ${wasRemoved}, Index removal: ${wasInIndex}`\n );\n }\n }\n\n /**\n * Finds an isolated bloc instance by its class and ID (O(n) lookup)\n */\n findIsolatedBlocInstance<B extends BlocConstructor<any>>(\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<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<B>;\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;\n }\n\n this.registerBlocInstance(newBloc);\n return newBloc;\n }\n\n\n activateBloc = (bloc: BlocBase<unknown>): 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 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<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 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<any>>(\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<any>>(\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<any>>(\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 // Validate consumers using the bloc's own validation method\n bloc._validateConsumers();\n \n // Check if bloc should be disposed after validation\n if (bloc._consumers.size === 0 && !bloc._keepAlive && (bloc as any)._disposalState === 'active') {\n // Schedule disposal for blocs with no consumers\n setTimeout(() => {\n // Double-check conditions before disposal\n if (bloc._consumers.size === 0 && !bloc._keepAlive && (bloc as any)._disposalState === 'active') {\n this.disposeBloc(bloc);\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 // Don't initialize lastState here - let it remain undefined for first-time detection\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.', this.bloc);\n // The bloc will handle its own disposal through consumer management\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 // If this is the first time (no lastState), always update\n if (!lastDependencyCheck) {\n shouldUpdate = true;\n } else {\n // Compare dependency arrays for changes\n if (lastDependencyCheck.length !== newDependencyCheck.length) {\n shouldUpdate = true;\n } else {\n // Compare each part of the dependency arrays\n for (let o = 0; o < newDependencyCheck.length; o++) {\n const partNew = newDependencyCheck[o];\n const partOld = lastDependencyCheck[o] || [];\n \n // If the part lengths are different, definitely update\n if (partNew.length !== partOld.length) {\n shouldUpdate = true;\n break;\n }\n \n // Compare each value in the parts\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 if (shouldUpdate) 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 // Just clear the observers without calling unsubscribe to avoid circular disposal\n this._observers.clear();\n }\n}\n","/**\n * Cross-platform UUID v4 generator that works in all environments including React Native/Hermes\n * Falls back to crypto.randomUUID() when available, otherwise uses Math.random()\n */\n\n/**\n * Generates a UUID v4 string compatible with all JavaScript environments\n * @returns A UUID v4 string in the format xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\n */\nexport function generateUUID(): string {\n // Try to use crypto.randomUUID() if available (Node.js 16+, modern browsers)\n if (typeof crypto !== 'undefined' && crypto.randomUUID) {\n return crypto.randomUUID();\n }\n\n // Fallback implementation for React Native/Hermes and older environments\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {\n const r = Math.random() * 16 | 0;\n const v = c === 'x' ? r : (r & 0x3 | 0x8);\n return v.toString(16);\n });\n}","import { BlacObservable } from './BlacObserver';\nimport { generateUUID } from './utils/uuid';\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 = generateUUID();\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 * Disposal state to prevent race conditions\n */\n private _disposalState: 'active' | 'disposing' | 'disposed' = 'active';\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 * @internal\n * Flag to prevent batching race conditions\n */\n private _batchingLock = false;\n\n /**\n * @internal\n * Pending batched updates\n */\n private _pendingUpdates: Array<{newState: S, oldState: S, action?: unknown}> = [];\n\n /**\n * @internal\n * Map of consumer IDs to their WeakRef objects for proper cleanup\n */\n private _consumerRefs = new Map<string, WeakRef<object>>();\n\n /**\n * @internal\n * Validates that all consumer references are still alive\n * Removes dead consumers automatically\n */\n _validateConsumers = (): void => {\n const deadConsumers: string[] = [];\n \n for (const [consumerId, weakRef] of this._consumerRefs) {\n if (weakRef.deref() === undefined) {\n deadConsumers.push(consumerId);\n }\n }\n \n // Clean up dead consumers\n for (const consumerId of deadConsumers) {\n this._consumers.delete(consumerId);\n this._consumerRefs.delete(consumerId);\n }\n \n // Schedule disposal if no live consumers remain\n if (this._consumers.size === 0 && !this._keepAlive && this._disposalState === 'active') {\n this._scheduleDisposal();\n }\n };\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 // Prevent re-entrant disposal using atomic state change\n if (this._disposalState !== 'active') {\n return;\n }\n this._disposalState = 'disposing';\n \n // Clear all consumers and their references\n this._consumers.clear();\n this._consumerRefs.clear();\n \n // Clear observer subscriptions\n this._observer.clear();\n \n // Call user-defined disposal hook\n this.onDispose?.();\n \n // Mark as fully disposed\n this._disposalState = 'disposed';\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 * 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 // Prevent adding consumers to disposed blocs\n if (this._disposalState !== 'active') {\n return;\n }\n \n if (this._consumers.has(consumerId)) return;\n this._consumers.add(consumerId);\n \n // Store WeakRef for proper memory management\n if (consumerRef) {\n this._consumerRefs.set(consumerId, new WeakRef(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 \n this._consumers.delete(consumerId);\n this._consumerRefs.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 && this._disposalState === 'active') {\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 // Prevent multiple disposal attempts\n if (this._disposalState !== 'active') {\n return;\n }\n \n // Double-check conditions before disposal\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 }\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 * 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 // Validate newState\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 && typeof action !== 'object' && typeof action !== 'function') {\n console.warn('BlocBase._pushState: Invalid action type', this, action);\n return;\n }\n\n if (this._batchingEnabled) {\n // When batching, just accumulate the updates\n this._pendingUpdates.push({ newState, oldState, action });\n \n // Update internal state for consistency\n this._oldState = oldState;\n this._state = newState;\n return;\n }\n\n // Normal state update flow\n this._oldState = oldState;\n this._state = newState;\n \n // Notify observers of the state change\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 // Prevent batching race conditions\n if (this._batchingLock) {\n // If already batching, just execute the function without nesting batches\n return batchFn();\n }\n \n this._batchingLock = true;\n this._batchingEnabled = true;\n this._pendingUpdates = [];\n\n try {\n const result = batchFn();\n \n // Process all batched updates\n if (this._pendingUpdates.length > 0) {\n // Only notify once with the final state\n const finalUpdate = this._pendingUpdates[this._pendingUpdates.length - 1];\n this._observer.notify(finalUpdate.newState, finalUpdate.oldState, finalUpdate.action);\n this.lastUpdate = Date.now();\n }\n \n return result;\n } finally {\n this._batchingEnabled = false;\n this._batchingLock = false;\n this._pendingUpdates = [];\n }\n };\n}\n","import { Blac } from './Blac';\nimport { BlocBase } from './BlocBase';\nimport { BlocEventConstraint } from './types';\n\n// A should be the base type for all events this Bloc handles and must extend BlocEventConstraint\n// to access action.constructor and ensure proper event structure.\n// P is for props, changed from any to unknown.\nexport abstract class Bloc<\n S, // State type\n A extends BlocEventConstraint = BlocEventConstraint, // Base Action/Event type with proper constraints\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 * @internal\n * Event queue to ensure sequential processing of async events\n */\n private _eventQueue: A[] = [];\n \n /**\n * @internal\n * Flag indicating if an event is currently being processed\n */\n private _isProcessingEvent = false;\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 * Events are queued and processed sequentially to prevent race conditions.\n * @param action The action/event instance to be processed.\n */\n public add = async (action: A): Promise<void> => {\n // Add event to queue\n this._eventQueue.push(action);\n \n // If not already processing, start processing the queue\n if (!this._isProcessingEvent) {\n await this._processEventQueue();\n }\n };\n\n /**\n * @internal\n * Processes events from the queue sequentially\n */\n private async _processEventQueue(): Promise<void> {\n // Prevent concurrent processing\n if (this._isProcessingEvent) {\n return;\n }\n \n this._isProcessingEvent = true;\n \n try {\n while (this._eventQueue.length > 0) {\n const action = this._eventQueue.shift()!;\n await this._processEvent(action);\n }\n } finally {\n this._isProcessingEvent = false;\n }\n }\n\n /**\n * @internal\n * Processes a single event\n */\n private async _processEvent(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 // Enhanced error handling with better context\n const constructorName = (action.constructor as { name?: string }).name || 'UnnamedConstructor';\n const errorContext = {\n blocName: this._name,\n blocId: String(this._id),\n eventType: constructorName,\n currentState: this.state,\n action: action,\n timestamp: new Date().toISOString()\n };\n \n Blac.error(\n `[Bloc ${this._name}:${String(this._id)}] Error in event handler for '${constructorName}':`,\n error,\n \"Context:\", errorContext\n );\n \n // TODO: Consider implementing error boundary pattern\n // For now, we log and continue, but applications may want to:\n // 1. Emit an error state\n // 2. Re-throw the error \n // 3. Call an error handler callback\n \n // Optional: Re-throw for critical errors (can be configured)\n if (error instanceof Error && error.name === 'CriticalError') {\n throw error;\n }\n }\n } else {\n // Enhanced warning with more context\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}'.`,\n \"Registered handlers:\", Array.from(this.eventHandlers.keys()).map(k => k.name),\n \"Action was:\", action\n );\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","import { Blac } from './Blac';\nimport { Bloc } from './Bloc';\nimport { BlocBase } from './BlocBase';\nimport { Cubit } from './Cubit';\nimport { BlocEventConstraint } from './types';\n\n/**\n * Test utilities for Blac state management\n */\nexport class BlocTest {\n private static originalInstance: Blac;\n \n /**\n * Sets up a clean test environment\n */\n static setUp(): void {\n this.originalInstance = Blac.instance;\n Blac.resetInstance();\n Blac.enableLog = false; // Disable logging in tests by default\n }\n \n /**\n * Tears down the test environment and restores original state\n */\n static tearDown(): void {\n Blac.resetInstance();\n // Note: Cannot restore original instance due to singleton pattern\n // Tests should use setUp/tearDown properly to manage state\n }\n \n /**\n * Creates a test bloc with automatic cleanup\n */\n static createBloc<T extends BlocBase<any>>(\n BlocClass: new (...args: any[]) => T,\n ...args: any[]\n ): T {\n const bloc = new BlocClass(...args);\n Blac.activateBloc(bloc);\n return bloc;\n }\n \n /**\n * Waits for a bloc to emit a specific state\n */\n static async waitForState<T extends BlocBase<S>, S>(\n bloc: T,\n predicate: (state: S) => boolean,\n timeout = 5000\n ): Promise<S> {\n return new Promise<S>((resolve, reject) => {\n const timeoutId = setTimeout(() => {\n reject(new Error(`Timeout waiting for state matching predicate after ${timeout}ms`));\n }, timeout);\n \n const unsubscribe = bloc._observer.subscribe({\n id: `test-waiter-${crypto.randomUUID()}`,\n fn: (newState: S) => {\n if (predicate(newState)) {\n clearTimeout(timeoutId);\n unsubscribe();\n resolve(newState);\n }\n }\n });\n \n // Check current state immediately\n if (predicate(bloc.state)) {\n clearTimeout(timeoutId);\n unsubscribe();\n resolve(bloc.state);\n }\n });\n }\n \n /**\n * Expects a bloc to emit specific states in order\n */\n static async expectStates<T extends BlocBase<S>, S>(\n bloc: T,\n expectedStates: S[],\n timeout = 5000\n ): Promise<void> {\n const receivedStates: S[] = [];\n \n return new Promise<void>((resolve, reject) => {\n const timeoutId = setTimeout(() => {\n reject(new Error(\n `Timeout waiting for states. Expected: ${JSON.stringify(expectedStates)}, ` +\n `Received: ${JSON.stringify(receivedStates)}`\n ));\n }, timeout);\n \n const unsubscribe = bloc._observer.subscribe({\n id: `test-expecter-${crypto.randomUUID()}`,\n fn: (newState: S) => {\n receivedStates.push(newState);\n \n // Check if we have all expected states\n if (receivedStates.length === expectedStates.length) {\n clearTimeout(timeoutId);\n unsubscribe();\n \n // Verify all states match using deep equality\n for (let i = 0; i < expectedStates.length; i++) {\n const expected = expectedStates[i];\n const received = receivedStates[i];\n \n // Use JSON comparison for deep equality\n if (JSON.stringify(expected) !== JSON.stringify(received)) {\n reject(new Error(\n `State mismatch at index ${i}. Expected: ${JSON.stringify(expected)}, ` +\n `Received: ${JSON.stringify(received)}`\n ));\n return;\n }\n }\n \n resolve();\n }\n }\n });\n });\n }\n}\n\n/**\n * Mock Bloc for testing\n */\nexport class MockBloc<S, A extends BlocEventConstraint = BlocEventConstraint> extends Bloc<S, A> {\n private mockHandlers = new Map<string, (event: A, emit: (newState: S) => void) => void | Promise<void>>();\n \n constructor(initialState: S) {\n super(initialState);\n }\n \n /**\n * Mock an event handler for testing\n */\n mockEventHandler<E extends A>(\n eventConstructor: new (...args: any[]) => E,\n handler: (event: E, emit: (newState: S) => void) => void | Promise<void>\n ): void {\n // Use the on method to register the mock handler\n this.on(eventConstructor, handler);\n }\n \n /**\n * Get the number of registered handlers\n */\n getHandlerCount(): number {\n return this.eventHandlers.size;\n }\n \n /**\n * Check if a handler is registered for an event type\n */\n hasHandler(eventConstructor: new (...args: any[]) => A): boolean {\n return this.eventHandlers.has(eventConstructor);\n }\n}\n\n/**\n * Mock Cubit for testing\n */\nexport class MockCubit<S> extends Cubit<S> {\n private stateHistory: S[] = [];\n \n constructor(initialState: S) {\n super(initialState);\n this.stateHistory.push(initialState);\n }\n \n /**\n * Override emit to track state history\n */\n emit(newState: S): void {\n this.stateHistory.push(newState);\n super.emit(newState);\n }\n \n /**\n * Get the history of all states\n */\n getStateHistory(): S[] {\n return [...this.stateHistory];\n }\n \n /**\n * Clear state history\n */\n clearStateHistory(): void {\n this.stateHistory = [this.state];\n }\n}\n\n/**\n * Memory leak detector for tests\n */\nexport class MemoryLeakDetector {\n private initialStats: ReturnType<typeof Blac.getMemoryStats>;\n \n constructor() {\n this.initialStats = Blac.getMemoryStats();\n }\n \n /**\n * Check for memory leaks and return a report\n */\n checkForLeaks(): {\n hasLeaks: boolean;\n report: string;\n stats: ReturnType<typeof Blac.getMemoryStats>;\n } {\n const currentStats = Blac.getMemoryStats();\n const hasLeaks = (\n currentStats.registeredBlocs > this.initialStats.registeredBlocs ||\n currentStats.isolatedBlocs > this.initialStats.isolatedBlocs ||\n currentStats.keepAliveBlocs > this.initialStats.keepAliveBlocs\n );\n \n const report = `\nMemory Leak Detection Report:\n- Initial registered blocs: ${this.initialStats.registeredBlocs}\n- Current registered blocs: ${currentStats.registeredBlocs}\n- Initial isolated blocs: ${this.initialStats.isolatedBlocs} \n- Current isolated blocs: ${currentStats.isolatedBlocs}\n- Initial keep-alive blocs: ${this.initialStats.keepAliveBlocs}\n- Current keep-alive blocs: ${currentStats.keepAliveBlocs}\n- Potential leaks detected: ${hasLeaks ? 'YES' : 'NO'}\n `.trim();\n \n return {\n hasLeaks,\n report,\n stats: currentStats\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","wasRemoved","index","b","wasInIndex","uid","props","instanceRef","newBloc","BlacObservable","observer","newState","oldState","action","shouldUpdate","lastDependencyCheck","newDependencyCheck","o","partNew","partOld","i","generateUUID","c","r","BlocBase","initialState","deadConsumers","consumerId","weakRef","originalId","consumerRef","batchFn","result","finalUpdate","Constructor","_a","handler","Bloc","eventConstructor","emit","previousState","error","constructorName","errorContext","k","Cubit","state","statePatch","ignoreChangeCheck","changes","current","BlocTest","BlocClass","timeout","resolve","reject","timeoutId","unsubscribe","expectedStates","receivedStates","expected","received","MockBloc","MockCubit","MemoryLeakDetector","currentStats","hasLeaks","report"],"mappings":";;;AAwCA,MAAMA,IAAN,MAAMA,EAAoD;AAAA,EAGxD,cAAoB;AACd,WAACA,EAAqB,cACxBA,EAAqB,YAAY,IAAIC,EAAK,EAAE,2BAA2B,IAAM,IAExED,EAAqB;AAAA,EAAA;AAAA,EAG9B,YAAYE,GAAsB;AAChC,IAAAF,EAAqB,YAAYE;AAAA,EAAA;AAAA,EAGnC,gBAAsB;AACpB,UAAMC,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Ac;AAAA,8BAC3BC,IAAW,QAAQ,IAAI;AAAA,MAC/C,KAAK;AAEA,WAAA;AAAA,MACL,UAAAA;AAAA,MACA,QAAAC;AAAA,MACA,OAAOF;AAAA,IACT;AAAA,EAAA;AAEJ;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blac/core",
3
- "version": "2.0.0-rc-4",
3
+ "version": "2.0.0-rc-6",
4
4
  "license": "MIT",
5
5
  "author": "Brendan Mullins <jsnanigans@gmail.com>",
6
6
  "main": "dist/index.cjs.js",
package/src/Blac.ts CHANGED
@@ -2,11 +2,11 @@
2
2
  // TODO: Remove this eslint disable once any types are properly replaced
3
3
  import { BlocBase, BlocInstanceId } from "./BlocBase";
4
4
  import {
5
- BlocBaseAbstract,
6
- BlocConstructor,
7
- BlocHookDependencyArrayFn,
8
- BlocState,
9
- InferPropsFromGeneric
5
+ BlocBaseAbstract,
6
+ BlocConstructor,
7
+ BlocHookDependencyArrayFn,
8
+ BlocState,
9
+ InferPropsFromGeneric
10
10
  } from "./types";
11
11
 
12
12
  /**
@@ -57,9 +57,11 @@ class SingletonBlacManager implements BlacInstanceManager {
57
57
  SingletonBlacManager._instance = new Blac({ __unsafe_ignore_singleton: true });
58
58
 
59
59
  // Transfer any keep-alive blocs to the new instance
60
- for (const bloc of oldInstance.keepAliveBlocs) {
61
- SingletonBlacManager._instance.keepAliveBlocs.add(bloc);
62
- SingletonBlacManager._instance.uidRegistry.set(bloc.uid, bloc);
60
+ if (oldInstance) {
61
+ for (const bloc of oldInstance.keepAliveBlocs) {
62
+ SingletonBlacManager._instance.keepAliveBlocs.add(bloc);
63
+ SingletonBlacManager._instance.uidRegistry.set(bloc.uid, bloc);
64
+ }
63
65
  }
64
66
  }
65
67
  }
@@ -99,7 +101,7 @@ export class Blac {
99
101
  /** Map storing all registered bloc instances by their class name and ID */
100
102
  blocInstanceMap: Map<string, BlocBase<unknown>> = new Map();
101
103
  /** Map storing isolated bloc instances grouped by their constructor */
102
- isolatedBlocMap: Map<BlocConstructor<unknown>, BlocBase<unknown>[]> = new Map();
104
+ isolatedBlocMap: Map<BlocConstructor<any>, BlocBase<unknown>[]> = new Map();
103
105
  /** Map for O(1) lookup of isolated blocs by UID */
104
106
  private isolatedBlocIndex: Map<string, BlocBase<unknown>> = new Map();
105
107
  /** Map tracking UIDs to prevent memory leaks */
@@ -172,24 +174,27 @@ export class Blac {
172
174
  resetInstance = (): void => {
173
175
  this.log("Reset Blac instance");
174
176
 
175
- // Dispose non-keepAlive blocs from the current instance
177
+ // Create snapshots to avoid concurrent modification issues
176
178
  const oldBlocInstanceMap = new Map(this.blocInstanceMap);
177
179
  const oldIsolatedBlocMap = new Map(this.isolatedBlocMap);
178
180
 
181
+ // Dispose non-keepAlive blocs from the current instance
182
+ // Use disposeBloc method to ensure proper cleanup
179
183
  oldBlocInstanceMap.forEach((bloc) => {
180
- if (!bloc._keepAlive) {
181
- bloc._dispose();
184
+ if (!bloc._keepAlive && (bloc as any)._disposalState === 'active') {
185
+ this.disposeBloc(bloc);
182
186
  }
183
187
  });
184
188
 
185
189
  oldIsolatedBlocMap.forEach((blocArray) => {
186
190
  blocArray.forEach((bloc) => {
187
- if (!bloc._keepAlive) {
188
- bloc._dispose();
191
+ if (!bloc._keepAlive && (bloc as any)._disposalState === 'active') {
192
+ this.disposeBloc(bloc);
189
193
  }
190
194
  });
191
195
  });
192
196
 
197
+ // Clear registries (keep-alive blocs will be re-added by instance manager)
193
198
  this.blocInstanceMap.clear();
194
199
  this.isolatedBlocMap.clear();
195
200
  this.isolatedBlocIndex.clear();
@@ -206,18 +211,30 @@ export class Blac {
206
211
  * @param bloc - The bloc instance to dispose
207
212
  */
208
213
  disposeBloc = (bloc: BlocBase<unknown>): void => {
214
+ // Check if bloc is already disposed to prevent double disposal
215
+ if ((bloc as any)._disposalState !== 'active') {
216
+ this.log(`[${bloc._name}:${String(bloc._id)}] disposeBloc called on already disposed bloc`);
217
+ return;
218
+ }
219
+
209
220
  const base = bloc.constructor as unknown as BlocBaseAbstract;
210
221
  const key = this.createBlocInstanceMapKey(bloc._name, bloc._id);
211
222
  this.log(`[${bloc._name}:${String(bloc._id)}] disposeBloc called. Isolated: ${String(base.isolated)}`);
212
223
 
224
+ // First dispose the bloc to prevent further operations
225
+ bloc._dispose();
226
+
227
+ // Then clean up from registries
213
228
  if (base.isolated) {
214
229
  this.unregisterIsolatedBlocInstance(bloc);
215
230
  this.blocInstanceMap.delete(key);
216
231
  } else {
217
232
  this.unregisterBlocInstance(bloc);
218
233
  }
234
+
219
235
  this.log('dispatched bloc', bloc)
220
236
  };
237
+ static get disposeBloc() { return Blac.instance.disposeBloc; }
221
238
 
222
239
  /**
223
240
  * Creates a unique key for a bloc instance in the map based on the bloc class name and instance ID
@@ -267,7 +284,7 @@ export class Blac {
267
284
  * @param id - The instance ID
268
285
  * @returns The found bloc instance or undefined if not found
269
286
  */
270
- findRegisteredBlocInstance<B extends BlocConstructor<unknown>>(
287
+ findRegisteredBlocInstance<B extends BlocConstructor<any>>(
271
288
  blocClass: B,
272
289
  id: BlocInstanceId,
273
290
  ): InstanceType<B> | undefined {
@@ -284,7 +301,7 @@ export class Blac {
284
301
  * @param bloc - The isolated bloc instance to register
285
302
  */
286
303
  registerIsolatedBlocInstance(bloc: BlocBase<unknown>): void {
287
- const blocClass = bloc.constructor as BlocConstructor<unknown>;
304
+ const blocClass = bloc.constructor as BlocConstructor<any>;
288
305
  const blocs = this.isolatedBlocMap.get(blocClass);
289
306
  if (blocs) {
290
307
  blocs.push(bloc);
@@ -310,32 +327,45 @@ export class Blac {
310
327
  */
311
328
  unregisterIsolatedBlocInstance(bloc: BlocBase<unknown>): void {
312
329
  const blocClass = bloc.constructor;
313
- const blocs = this.isolatedBlocMap.get(blocClass as BlocConstructor<unknown>);
330
+ const blocs = this.isolatedBlocMap.get(blocClass as BlocConstructor<any>);
331
+
332
+ // Ensure both data structures are synchronized
333
+ let wasRemoved = false;
334
+
314
335
  if (blocs) {
315
336
  const index = blocs.findIndex((b) => b.uid === bloc.uid);
316
337
  if (index !== -1) {
317
338
  blocs.splice(index, 1);
339
+ wasRemoved = true;
318
340
  }
319
341
 
320
342
  if (blocs.length === 0) {
321
- this.isolatedBlocMap.delete(blocClass as BlocConstructor<unknown>);
343
+ this.isolatedBlocMap.delete(blocClass as BlocConstructor<any>);
322
344
  }
323
345
  }
324
346
 
325
- // Remove from isolated index
326
- this.isolatedBlocIndex.delete(bloc.uid);
347
+ // Always try to remove from isolated index, even if not found in map
348
+ const wasInIndex = this.isolatedBlocIndex.delete(bloc.uid);
327
349
 
328
350
  // Clean up UID tracking
329
351
  this.uidRegistry.delete(bloc.uid);
330
352
 
331
353
  // Remove from keep-alive set
332
354
  this.keepAliveBlocs.delete(bloc);
355
+
356
+ // Log inconsistency for debugging
357
+ if (wasRemoved !== wasInIndex) {
358
+ this.warn(
359
+ `[Blac] Inconsistent state detected during isolated bloc cleanup for ${bloc._name}:${bloc.uid}. ` +
360
+ `Map removal: ${wasRemoved}, Index removal: ${wasInIndex}`
361
+ );
362
+ }
333
363
  }
334
364
 
335
365
  /**
336
366
  * Finds an isolated bloc instance by its class and ID (O(n) lookup)
337
367
  */
338
- findIsolatedBlocInstance<B extends BlocConstructor<unknown>>(
368
+ findIsolatedBlocInstance<B extends BlocConstructor<any>>(
339
369
  blocClass: B,
340
370
  id: BlocInstanceId,
341
371
  ): InstanceType<B> | undefined {
@@ -368,13 +398,13 @@ export class Blac {
368
398
  * @param instanceRef - Optional reference string for the instance
369
399
  * @returns The newly created bloc instance
370
400
  */
371
- createNewBlocInstance<B extends BlocConstructor<BlocBase<unknown>>>(
401
+ createNewBlocInstance<B extends BlocConstructor<BlocBase<any>>>(
372
402
  blocClass: B,
373
403
  id: BlocInstanceId,
374
404
  options: GetBlocOptions<InstanceType<B>> = {},
375
405
  ): InstanceType<B> {
376
406
  const { props, instanceRef } = options;
377
- const newBloc = new blocClass(props as never) as InstanceType<BlocConstructor<BlocBase<unknown>>>;
407
+ const newBloc = new blocClass(props as never) as InstanceType<B>;
378
408
  newBloc._instanceRef = instanceRef;
379
409
  newBloc.props = props || null;
380
410
  newBloc._updateId(id);
@@ -384,16 +414,16 @@ export class Blac {
384
414
 
385
415
  if (newBloc.isIsolated) {
386
416
  this.registerIsolatedBlocInstance(newBloc);
387
- return newBloc as InstanceType<B>;
417
+ return newBloc;
388
418
  }
389
419
 
390
420
  this.registerBlocInstance(newBloc);
391
- return newBloc as InstanceType<B>;
421
+ return newBloc;
392
422
  }
393
423
 
394
424
 
395
425
  activateBloc = (bloc: BlocBase<unknown>): void => {
396
- const base = bloc.constructor as unknown as BlocConstructor<BlocBase<unknown>>;
426
+ const base = bloc.constructor as unknown as BlocConstructor<BlocBase<any>>;
397
427
  const isIsolated = bloc.isIsolated;
398
428
 
399
429
  let found = isIsolated ? this.findIsolatedBlocInstance(base, bloc._id) : this.findRegisteredBlocInstance(base, bloc._id);
@@ -421,7 +451,7 @@ export class Blac {
421
451
  * - instanceRef: Optional reference string for the instance
422
452
  * @returns The bloc instance
423
453
  */
424
- getBloc = <B extends BlocConstructor<BlocBase<unknown>>>(
454
+ getBloc = <B extends BlocConstructor<BlocBase<any>>>(
425
455
  blocClass: B,
426
456
  options: GetBlocOptions<InstanceType<B>> = {},
427
457
  ): InstanceType<B> => {
@@ -470,7 +500,7 @@ export class Blac {
470
500
  * - props: Properties to pass to the bloc constructor
471
501
  * - instanceRef: Optional reference string for the instance
472
502
  */
473
- getBlocOrThrow = <B extends BlocConstructor<unknown>>(
503
+ getBlocOrThrow = <B extends BlocConstructor<any>>(
474
504
  blocClass: B,
475
505
  options: {
476
506
  id?: BlocInstanceId;
@@ -499,7 +529,7 @@ export class Blac {
499
529
  * - searchIsolated: Whether to search in isolated blocs (defaults to bloc's isolated property)
500
530
  * @returns Array of matching bloc instances
501
531
  */
502
- getAllBlocs = <B extends BlocConstructor<unknown>>(
532
+ getAllBlocs = <B extends BlocConstructor<any>>(
503
533
  blocClass: B,
504
534
  options: {
505
535
  searchIsolated?: boolean;
@@ -530,7 +560,7 @@ export class Blac {
530
560
  * Disposes all keep-alive blocs of a specific type
531
561
  * @param blocClass - The bloc class to dispose
532
562
  */
533
- disposeKeepAliveBlocs = <B extends BlocConstructor<unknown>>(
563
+ disposeKeepAliveBlocs = <B extends BlocConstructor<any>>(
534
564
  blocClass?: B
535
565
  ): void => {
536
566
  const toDispose: BlocBase<unknown>[] = [];
@@ -591,13 +621,16 @@ export class Blac {
591
621
  */
592
622
  validateConsumers = (): void => {
593
623
  for (const bloc of this.uidRegistry.values()) {
594
- // This would need to be called periodically to clean up orphaned consumers
595
- // Implementation depends on how we want to handle consumer validation
596
- if (bloc._consumers.size === 0 && !bloc._keepAlive) {
624
+ // Validate consumers using the bloc's own validation method
625
+ bloc._validateConsumers();
626
+
627
+ // Check if bloc should be disposed after validation
628
+ if (bloc._consumers.size === 0 && !bloc._keepAlive && (bloc as any)._disposalState === 'active') {
597
629
  // Schedule disposal for blocs with no consumers
598
630
  setTimeout(() => {
599
- if (bloc._consumers.size === 0 && !bloc._keepAlive) {
600
- bloc._dispose();
631
+ // Double-check conditions before disposal
632
+ if (bloc._consumers.size === 0 && !bloc._keepAlive && (bloc as any)._disposalState === 'active') {
633
+ this.disposeBloc(bloc);
601
634
  }
602
635
  }, 1000); // Give a grace period
603
636
  }