@blac/core 2.0.0-rc-11 → 2.0.0-rc-14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs.js +2 -2
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.d.ts +739 -260
- package/dist/index.es.js +1924 -1237
- package/dist/index.es.js.map +1 -1
- package/package.json +6 -7
- package/src/Blac.ts +82 -69
- package/src/Bloc.ts +45 -3
- package/src/BlocBase.ts +263 -454
- package/src/Cubit.ts +1 -16
- package/src/__tests__/Blac.config.test.ts +10 -17
- package/src/__tests__/Bloc.event.test.ts +27 -52
- package/src/__tests__/BlocBase.subscription.test.ts +349 -0
- package/src/__tests__/Cubit.test.ts +39 -50
- package/src/__tests__/memory-leaks.test.ts +383 -0
- package/src/__tests__/plugins.test.ts +464 -0
- package/src/adapter/BlacAdapter.ts +347 -207
- package/src/adapter/ProxyFactory.ts +196 -255
- package/src/adapter/__tests__/BlacAdapter.test.ts +71 -77
- package/src/adapter/__tests__/ProxyFactory.test.ts +1 -1
- package/src/adapter/index.ts +0 -1
- package/src/errors/BlacError.ts +69 -0
- package/src/errors/ErrorManager.ts +101 -0
- package/src/errors/handleError.ts +114 -0
- package/src/errors/index.ts +13 -0
- package/src/events.ts +7 -1
- package/src/index.ts +10 -1
- package/src/lifecycle/BlocLifecycle.ts +156 -0
- package/src/lifecycle/index.ts +1 -0
- package/src/plugins/BlocPluginRegistry.ts +240 -0
- package/src/plugins/SystemPluginRegistry.ts +242 -0
- package/src/plugins/__tests__/BlocPluginRegistry.test.ts +450 -0
- package/src/plugins/__tests__/SystemPluginRegistry.test.ts +404 -0
- package/src/plugins/index.ts +8 -0
- package/src/plugins/types.ts +129 -0
- package/src/subscription/README.md +132 -0
- package/src/subscription/SubscriptionManager.ts +395 -0
- package/src/subscription/__tests__/SubscriptionManager.test.ts +355 -0
- package/src/subscription/index.ts +2 -0
- package/src/subscription/types.ts +90 -0
- package/src/testing.ts +31 -37
- package/src/types.ts +4 -21
- package/src/utils/BatchingManager.ts +59 -0
- package/src/utils/RerenderLogger.ts +265 -0
- package/src/utils/__tests__/generateInstanceId.test.ts +104 -0
- package/src/utils/__tests__/shallowEqual.test.ts +171 -0
- package/src/utils/__tests__/uuid.test.ts +144 -0
- package/src/utils/generateInstanceId.ts +54 -0
- package/src/utils/shallowEqual.ts +1 -1
- package/README.md +0 -329
- package/src/BlacObserver.ts +0 -186
- package/src/__tests__/BlocBase.lifecycle.test.ts +0 -441
- package/src/__tests__/props.test.ts +0 -256
- package/src/adapter/ConsumerTracker.ts +0 -241
- package/src/adapter/__tests__/ConsumerTracker.test.ts +0 -562
package/dist/index.es.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.es.js","sources":["../src/BlacObserver.ts","../src/utils/uuid.ts","../src/BlocBase.ts","../src/Blac.ts","../src/Bloc.ts","../src/Cubit.ts","../src/events.ts","../src/utils/shallowEqual.ts","../src/testing.ts","../src/adapter/ConsumerTracker.ts","../src/adapter/ProxyFactory.ts","../src/adapter/BlacAdapter.ts"],"sourcesContent":["import { Blac } from './Blac';\nimport { BlocLifecycleState } from './BlocBase';\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 // Check if bloc is disposed or in disposal process\n const disposalState = (this.bloc as any)._disposalState;\n if (\n disposalState === BlocLifecycleState.DISPOSED ||\n disposalState === BlocLifecycleState.DISPOSING\n ) {\n Blac.log(\n 'BlacObservable.subscribe: Cannot subscribe to disposed/disposing bloc.',\n this.bloc,\n observer,\n );\n return () => {}; // Return no-op unsubscribe\n }\n\n Blac.log(\n 'BlacObservable.subscribe: Subscribing observer.',\n this.bloc,\n observer,\n );\n this._observers.add(observer);\n\n // If we're in DISPOSAL_REQUESTED state, cancel the disposal since we have a new observer\n if (disposalState === BlocLifecycleState.DISPOSAL_REQUESTED) {\n Blac.log(\n 'BlacObservable.subscribe: Cancelling disposal due to new subscription.',\n this.bloc,\n );\n // Transition back to active state\n (this.bloc as any)._atomicStateTransition(\n BlocLifecycleState.DISPOSAL_REQUESTED,\n BlocLifecycleState.ACTIVE,\n );\n }\n\n // Don't initialize lastState here - let it remain undefined for first-time detection\n return () => {\n Blac.log(\n 'BlacObservable.subscribe: Unsubscribing observer.',\n this.bloc,\n observer,\n );\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 // Check if bloc should be disposed when both observers and consumers are gone\n if (\n this.bloc._consumers.size === 0 &&\n !this.bloc._keepAlive &&\n (this.bloc as any)._disposalState === BlocLifecycleState.ACTIVE\n ) {\n Blac.log(\n `[${this.bloc._name}:${this.bloc._id}] No observers or consumers left. Scheduling disposal.`,\n );\n (this.bloc as any)._scheduleDisposal();\n }\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(\n newState,\n oldState,\n this.bloc,\n );\n\n // If this is the first time (no lastState), trigger initial render\n if (!lastDependencyCheck) {\n shouldUpdate = true;\n } else {\n // Compare dependency arrays\n if (lastDependencyCheck.length !== newDependencyCheck.length) {\n shouldUpdate = true;\n } else {\n // Compare each dependency value using Object.is (same as React)\n for (let i = 0; i < newDependencyCheck.length; i++) {\n if (!Object.is(lastDependencyCheck[i], newDependencyCheck[i])) {\n shouldUpdate = true;\n break;\n }\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}\n","import { BlacObservable } from './BlacObserver';\nimport { generateUUID } from './utils/uuid';\n\nexport type BlocInstanceId = string | number | undefined;\ntype DependencySelector<S> = (\n currentState: S,\n previousState: S | undefined,\n instance: any,\n) => unknown[];\n\n/**\n * Enum representing the lifecycle states of a Bloc instance\n * Used for atomic state transitions to prevent race conditions\n */\nexport enum BlocLifecycleState {\n ACTIVE = 'active',\n DISPOSAL_REQUESTED = 'disposal_requested',\n DISPOSING = 'disposing',\n DISPOSED = 'disposed',\n}\n\n/**\n * Result of an atomic state transition operation\n */\nexport interface StateTransitionResult {\n success: boolean;\n currentState: BlocLifecycleState;\n previousState: BlocLifecycleState;\n}\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<S, P = unknown> {\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 * Atomic disposal state to prevent race conditions\n */\n private _disposalState: BlocLifecycleState = BlocLifecycleState.ACTIVE;\n\n /**\n * @internal\n * Timestamp when disposal was requested (for React Strict Mode grace period)\n */\n private _disposalRequestTime: number = 0;\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<{\n newState: S;\n oldState: S;\n action?: unknown;\n }> = [];\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 (\n this._consumers.size === 0 &&\n !this._keepAlive &&\n this._disposalState === BlocLifecycleState.ACTIVE\n ) {\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 &\n BlocStaticProperties;\n\n // Validate that the static properties exist and are boolean\n this._keepAlive =\n typeof Constructor.keepAlive === 'boolean'\n ? Constructor.keepAlive\n : false;\n this._isolated =\n 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 * Returns the state even during transitional lifecycle states for React compatibility.\n */\n get state(): S {\n // Allow state access during all states except DISPOSED for React compatibility\n if (this._disposalState === BlocLifecycleState.DISPOSED) {\n // Return the last known state for disposed blocs to prevent crashes\n return this._state;\n }\n return this._state;\n }\n\n /**\n * Returns whether this Bloc instance has been disposed.\n * @returns true if the bloc is in DISPOSED state\n */\n get isDisposed(): boolean {\n return this._disposalState === BlocLifecycleState.DISPOSED;\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 * Performs atomic state transition using compare-and-swap semantics\n * @param expectedState The expected current state\n * @param newState The desired new state\n * @returns Result indicating success/failure and state information\n */\n _atomicStateTransition(\n expectedState: BlocLifecycleState,\n newState: BlocLifecycleState,\n ): StateTransitionResult {\n if (this._disposalState === expectedState) {\n const previousState = this._disposalState;\n this._disposalState = newState;\n\n // Log state transition for debugging\n if ((globalThis as any).Blac?.enableLog) {\n (globalThis as any).Blac?.log(\n `[${this._name}:${this._id}] State transition: ${previousState} -> ${newState} (SUCCESS)`,\n );\n }\n\n return {\n success: true,\n currentState: newState,\n previousState,\n };\n }\n\n // Log failed transition attempt\n if ((globalThis as any).Blac?.enableLog) {\n (globalThis as any).Blac?.log(\n `[${this._name}:${this._id}] State transition failed: expected ${expectedState}, current ${this._disposalState}`,\n );\n }\n\n return {\n success: false,\n currentState: this._disposalState,\n previousState: expectedState,\n };\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(): boolean {\n // Step 1: Attempt atomic transition to DISPOSING state from either ACTIVE or DISPOSAL_REQUESTED\n let transitionResult = this._atomicStateTransition(\n BlocLifecycleState.ACTIVE,\n BlocLifecycleState.DISPOSING,\n );\n\n // If that failed, try from DISPOSAL_REQUESTED state\n if (!transitionResult.success) {\n transitionResult = this._atomicStateTransition(\n BlocLifecycleState.DISPOSAL_REQUESTED,\n BlocLifecycleState.DISPOSING,\n );\n }\n\n if (!transitionResult.success) {\n // Already disposing or disposed - idempotent operation\n return false;\n }\n\n try {\n // Step 2: Perform cleanup operations\n this._consumers.clear();\n this._consumerRefs.clear();\n this._observer.clear();\n\n // Call user-defined disposal hook\n this.onDispose?.();\n\n // Step 3: Final state transition to DISPOSED\n const finalResult = this._atomicStateTransition(\n BlocLifecycleState.DISPOSING,\n BlocLifecycleState.DISPOSED,\n );\n\n return finalResult.success;\n } catch (error) {\n // Recovery: Reset state on cleanup failure\n this._disposalState = BlocLifecycleState.ACTIVE;\n throw error;\n }\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): boolean => {\n // Atomic state validation - only allow consumer addition in ACTIVE state\n if (this._disposalState !== BlocLifecycleState.ACTIVE) {\n return false; // Clear failure indication\n }\n\n // Prevent duplicate consumers\n if (this._consumers.has(consumerId)) return true;\n\n // Safe consumer addition\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 // @ts-ignore - Blac is available globally\n (globalThis as any).Blac?.log(\n `[${this._name}:${this._id}] Consumer added. Total consumers: ${this._consumers.size}`,\n );\n\n // this._blac.dispatchEvent(BlacLifecycleEvent.BLOC_CONSUMER_ADDED, this, { consumerId });\n return true;\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 // @ts-ignore - Blac is available globally\n (globalThis as any).Blac?.log(\n `[${this._name}:${this._id}] Consumer removed. Remaining consumers: ${this._consumers.size}, keepAlive: ${this._keepAlive}`,\n );\n\n // If no consumers remain and not keep-alive, schedule disposal\n if (\n this._consumers.size === 0 &&\n !this._keepAlive &&\n this._disposalState === BlocLifecycleState.ACTIVE\n ) {\n // @ts-ignore - Blac is available globally\n (globalThis as any).Blac?.log(\n `[${this._name}:${this._id}] No consumers left and not keep-alive. Scheduling disposal.`,\n );\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 * Uses atomic state transitions to prevent race conditions\n */\n private _scheduleDisposal(): void {\n // Step 1: Atomic transition to DISPOSAL_REQUESTED\n const requestResult = this._atomicStateTransition(\n BlocLifecycleState.ACTIVE,\n BlocLifecycleState.DISPOSAL_REQUESTED,\n );\n\n if (!requestResult.success) {\n // Already requested, disposing, or disposed\n return;\n }\n\n // Step 2: Verify disposal conditions under atomic protection\n const shouldDispose = this._consumers.size === 0 && !this._keepAlive;\n\n if (!shouldDispose) {\n // Conditions no longer met, revert to active\n this._atomicStateTransition(\n BlocLifecycleState.DISPOSAL_REQUESTED,\n BlocLifecycleState.ACTIVE,\n );\n return;\n }\n\n // Record disposal request time for tracking\n this._disposalRequestTime = Date.now();\n\n // Step 3: Defer disposal until after current execution completes\n // This allows React Strict Mode's immediate remount to cancel disposal\n queueMicrotask(() => {\n // Re-verify disposal conditions - React Strict Mode remount may have cancelled this\n const stillShouldDispose =\n this._consumers.size === 0 &&\n !this._keepAlive &&\n this._observer.size === 0 &&\n (this as any)._disposalState === BlocLifecycleState.DISPOSAL_REQUESTED;\n\n if (stillShouldDispose) {\n // No cancellation occurred, proceed with disposal\n if (this._disposalHandler) {\n this._disposalHandler(this as any);\n } else {\n this._dispose();\n }\n } else {\n // Disposal was cancelled (React Strict Mode remount), revert to active\n this._atomicStateTransition(\n BlocLifecycleState.DISPOSAL_REQUESTED,\n BlocLifecycleState.ACTIVE,\n );\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 return;\n }\n\n // Validate action type if provided\n if (\n action !== undefined &&\n typeof action !== 'object' &&\n typeof action !== 'function'\n ) {\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 =\n this._pendingUpdates[this._pendingUpdates.length - 1];\n this._observer.notify(\n finalUpdate.newState,\n finalUpdate.oldState,\n finalUpdate.action,\n );\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 { BlocBase, BlocInstanceId, BlocLifecycleState } 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 * Whether to enable proxy dependency tracking for automatic re-render optimization.\n * When false, state changes always cause re-renders unless dependencies are manually specified.\n * Default: true\n */\n proxyDependencyTracking?: 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 /** Force creation of a new instance for isolated blocs, bypassing instance lookup */\n forceNewInstance?: 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({\n __unsafe_ignore_singleton: true,\n });\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({\n __unsafe_ignore_singleton: true,\n });\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 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\n /** Private static configuration */\n private static _config: BlacConfig = {\n exposeBlacInstance: false,\n proxyDependencyTracking: true,\n };\n\n /** Get current configuration */\n static get config(): Readonly<BlacConfig> {\n return { ...this._config };\n }\n\n /**\n * Set or update Blac configuration\n * @param config - Partial configuration to merge with existing config\n * @throws Error if configuration is invalid\n */\n static setConfig(config: Partial<BlacConfig>): void {\n // Validate config\n if (config.proxyDependencyTracking !== undefined &&\n typeof config.proxyDependencyTracking !== 'boolean') {\n throw new Error('BlacConfig.proxyDependencyTracking must be a boolean');\n }\n\n if (config.exposeBlacInstance !== undefined &&\n typeof config.exposeBlacInstance !== 'boolean') {\n throw new Error('BlacConfig.exposeBlacInstance must be a boolean');\n }\n\n // Merge with existing config\n this._config = {\n ...this._config,\n ...config,\n };\n\n // Log config update if logging is enabled\n if (this.enableLog) {\n this.instance.log('Blac config updated:', this._config);\n }\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 // Using BlocConstructor<BlocBase<unknown>> would break type inference when storing\n // different bloc types in the same map. The 'any' allows proper polymorphic storage\n // while maintaining type safety at usage sites through the BlocConstructor constraint.\n isolatedBlocMap: Map<BlocConstructor<any>, BlocBase<unknown>[]> = new Map();\n /** Map for O(1) lookup of isolated blocs by UID */\n 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 static logLevel: 'warn' | 'log' = 'warn';\n static logSpy: ((...args: unknown[]) => void) | null = null;\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.logSpy) {\n Blac.logSpy(args);\n }\n if (Blac.enableLog && Blac.logLevel === 'warn') {\n // Logging disabled - console.warn removed\n }\n if (Blac.enableLog && Blac.logLevel === 'log') {\n // Logging disabled - console.log removed\n }\n };\n static get log() {\n return Blac.instance.log;\n }\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 * 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 // Logging disabled - console.warn removed\n }\n };\n static get warn() {\n return Blac.instance.warn;\n }\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 // Logging disabled - console.error removed\n }\n };\n static get error() {\n return Blac.instance.error;\n }\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 // TODO: Type assertion for private property access (see explanation above)\n if (\n !bloc._keepAlive &&\n (bloc as any)._disposalState === BlocLifecycleState.ACTIVE\n ) {\n this.disposeBloc(bloc);\n }\n });\n\n oldIsolatedBlocMap.forEach((blocArray) => {\n blocArray.forEach((bloc) => {\n // TODO: Type assertion for private property access (see explanation above)\n if (\n !bloc._keepAlive &&\n (bloc as any)._disposalState === BlocLifecycleState.ACTIVE\n ) {\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 // TODO: Type assertion needed to access private _disposalState property from external class.\n // This is safe because we know BlocBase has this property, but TypeScript can't verify\n // private property access across class boundaries. Alternative would be to make\n // _disposalState protected, but that would expose internal implementation details.\n const currentState = (bloc as any)._disposalState;\n const validStatesForDisposal = [\n BlocLifecycleState.ACTIVE,\n BlocLifecycleState.DISPOSAL_REQUESTED,\n ];\n\n if (!validStatesForDisposal.includes(currentState)) {\n this.log(\n `[${bloc._name}:${String(bloc._id)}] disposeBloc called on bloc in invalid state: ${currentState}`,\n );\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(\n `[${bloc._name}:${String(bloc._id)}] disposeBloc called. Isolated: ${String(base.isolated)}`,\n );\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() {\n return Blac.instance.disposeBloc;\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<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\n | InstanceType<B>\n | 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 activateBloc = (bloc: BlocBase<unknown>): void => {\n // Don't activate disposed blocs\n if ((bloc as any)._disposalState !== BlocLifecycleState.ACTIVE) {\n this.log(\n `[${bloc._name}:${String(bloc._id)}] activateBloc called on disposed bloc. Ignoring.`,\n );\n return;\n }\n\n const base = bloc.constructor as unknown as BlocConstructor<BlocBase<any>>;\n const isIsolated = bloc.isIsolated;\n\n let found = isIsolated\n ? this.findIsolatedBlocInstance(base, bloc._id)\n : this.findRegisteredBlocInstance(base, bloc._id);\n if (found) {\n return;\n }\n\n this.log(\n `[${bloc._name}:${String(bloc._id)}] activateBloc called. Isolated: ${String(bloc.isIsolated)}`,\n );\n if (bloc.isIsolated) {\n this.registerIsolatedBlocInstance(bloc);\n } else {\n this.registerBlocInstance(bloc);\n }\n };\n static get activateBloc() {\n return Blac.instance.activateBloc;\n }\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, forceNewInstance } = options;\n const base = blocClass as unknown as BlocBaseAbstract;\n const blocId = id ?? blocClass.name;\n this.log(`[${blocClass.name}:${String(blocId)}] (getBloc) Called:`, {\n options,\n base,\n });\n\n // Skip instance lookup if forceNewInstance is true for isolated blocs\n if (!forceNewInstance) {\n if (base.isolated) {\n const isolatedBloc = this.findIsolatedBlocInstance<B>(\n blocClass,\n options.instanceRef ?? blocId,\n );\n if (isolatedBloc) {\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(\n blocClass,\n blocId,\n );\n if (registeredBloc) {\n return registeredBloc;\n } else {\n if (options.throwIfNotFound) {\n throw new Error(`Registered bloc ${blocClass.name} not found`);\n }\n }\n }\n }\n\n const bloc = this.createNewBlocInstance(blocClass, blocId, options);\n this.log(\n `[${blocClass.name}:${String(blocId)}] (getBloc) No existing instance found. Creating new one.`,\n options,\n bloc,\n );\n\n if (!bloc) {\n throw new Error(\n `[getBloc] Failed to create bloc instance for ${blocClass.name}. This should never happen.`,\n );\n }\n\n return bloc;\n };\n static get getBloc() {\n return Blac.instance.getBloc;\n }\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() {\n return Blac.instance.getBlocOrThrow;\n }\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) {\n // 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() {\n return Blac.instance.disposeKeepAliveBlocs;\n }\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() {\n return Blac.instance.disposeBlocs;\n }\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(\n (sum, arr) => sum + arr.length,\n 0,\n ),\n keepAliveBlocs: this.keepAliveBlocs.size,\n isolatedBlocTypes: this.isolatedBlocMap.size,\n };\n };\n static get getMemoryStats() {\n return Blac.instance.getMemoryStats;\n }\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 // TODO: Type assertion for private property access (see explanation above)\n if (\n bloc._consumers.size === 0 &&\n !bloc._keepAlive &&\n (bloc as any)._disposalState === BlocLifecycleState.ACTIVE\n ) {\n // Schedule disposal for blocs with no consumers\n setTimeout(() => {\n // Double-check conditions before disposal\n // TODO: Type assertion for private property access (see explanation above)\n if (\n bloc._consumers.size === 0 &&\n !bloc._keepAlive &&\n (bloc as any)._disposalState === BlocLifecycleState.ACTIVE\n ) {\n this.disposeBloc(bloc);\n }\n }, 1000); // Give a grace period\n }\n }\n };\n static get validateConsumers() {\n return Blac.instance.validateConsumers;\n }\n}\n","import { Blac } from './Blac';\nimport { BlocBase } from './BlocBase';\nimport { BlocEventConstraint } from './types';\n\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 readonly eventHandlers: Map<\n new (...args: any[]) => A,\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 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 Blac.warn(\n `[Bloc ${this._name}:${String(this._id)}] Handler for event '${eventConstructor.name}' already registered. It will be overwritten.`,\n );\n }\n this.eventHandlers.set(\n eventConstructor,\n handler as (\n event: A,\n emit: (newState: S) => void,\n ) => 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 this._eventQueue.push(action);\n\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 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 const eventConstructor = action.constructor as new (...args: any[]) => A;\n const handler = this.eventHandlers.get(eventConstructor);\n\n if (handler) {\n const emit = (newState: S): void => {\n const previousState = this.state; // State just before this specific emission\n this._pushState(newState, previousState, action);\n };\n\n try {\n await handler(action, emit);\n } catch (error) {\n const constructorName =\n (action.constructor as { name?: string }).name ||\n '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:',\n errorContext,\n );\n\n if (error instanceof Error && error.name === 'CriticalError') {\n throw error;\n }\n }\n } else {\n const constructorName =\n (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:',\n Array.from(this.eventHandlers.keys()).map((k) => k.name),\n 'Action was:',\n 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 * @internal\n * Protected method for useBloc to call\n */\n protected _updateProps(props: P): void {\n const oldProps = this.props;\n this.props = props;\n this.onPropsChanged?.(oldProps as P | undefined, props);\n }\n \n /**\n * Optional override for props handling\n */\n protected onPropsChanged?(oldProps: P | undefined, newProps: P): void;\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","export class PropsUpdated<P = any> {\n constructor(public readonly props: P) {}\n}","/**\n * Performs a shallow equality comparison between two values.\n * For objects, it checks if all top-level properties are equal using Object.is.\n * @param a First value to compare\n * @param b Second value to compare\n * @returns true if values are shallowly equal, false otherwise\n */\nexport function shallowEqual(a: any, b: any): boolean {\n if (Object.is(a, b)) {\n return true;\n }\n\n if (\n typeof a !== 'object' ||\n a === null ||\n typeof b !== 'object' ||\n b === null\n ) {\n return false;\n }\n\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n\n if (keysA.length !== keysB.length) {\n return false;\n }\n\n for (let i = 0; i < keysA.length; i++) {\n const key = keysA[i];\n if (\n !Object.prototype.hasOwnProperty.call(b, key) ||\n !Object.is(a[key], b[key])\n ) {\n return false;\n }\n }\n\n return true;\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(\n new Error(\n `Timeout waiting for state matching predicate after ${timeout}ms`,\n ),\n );\n }, timeout);\n\n const unsubscribe = bloc._observer.subscribe({\n id: `test-waiter-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,\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(\n new Error(\n `Timeout waiting for states. Expected: ${JSON.stringify(expectedStates)}, ` +\n `Received: ${JSON.stringify(receivedStates)}`,\n ),\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(\n new Error(\n `State mismatch at index ${i}. Expected: ${JSON.stringify(expected)}, ` +\n `Received: ${JSON.stringify(received)}`,\n ),\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<\n S,\n A extends BlocEventConstraint = BlocEventConstraint,\n> extends Bloc<S, A> {\n private mockHandlers = new Map<\n string,\n (event: A, emit: (newState: S) => void) => void | Promise<void>\n >();\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 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}\n","export interface DependencyArray {\n statePaths: string[];\n classPaths: string[];\n}\n\nexport interface TrackedValue {\n value: any;\n lastAccessTime: number;\n}\n\nexport interface ConsumerInfo {\n id: string;\n lastNotified: number;\n hasRendered: boolean;\n // Dependency tracking\n stateAccesses: Set<string>;\n classAccesses: Set<string>;\n stateValues: Map<string, TrackedValue>;\n classValues: Map<string, TrackedValue>;\n accessCount: number;\n lastAccessTime: number;\n firstAccessTime: number;\n}\n\n/**\n * ConsumerTracker manages both consumer registration and dependency tracking.\n * It uses a WeakMap for automatic garbage collection when consumers are no longer referenced.\n */\nexport class ConsumerTracker {\n private consumers = new WeakMap<object, ConsumerInfo>();\n private registrationCount = 0;\n private activeConsumers = 0;\n\n register(consumerRef: object, consumerId: string): void {\n this.registrationCount++;\n\n const existingConsumer = this.consumers.get(consumerRef);\n if (!existingConsumer) {\n this.activeConsumers++;\n }\n\n this.consumers.set(consumerRef, {\n id: consumerId,\n lastNotified: Date.now(),\n hasRendered: false,\n stateAccesses: new Set(),\n classAccesses: new Set(),\n stateValues: new Map(),\n classValues: new Map(),\n accessCount: 0,\n lastAccessTime: 0,\n firstAccessTime: 0,\n });\n }\n\n unregister(consumerRef: object): void {\n if (consumerRef) {\n const consumerInfo = this.consumers.get(consumerRef);\n if (consumerInfo) {\n this.consumers.delete(consumerRef);\n this.activeConsumers = Math.max(0, this.activeConsumers - 1);\n }\n }\n }\n\n trackAccess(\n consumerRef: object,\n type: 'state' | 'class',\n path: string,\n value?: any,\n ): void {\n const consumerInfo = this.consumers.get(consumerRef);\n if (!consumerInfo) return;\n\n const now = Date.now();\n\n if (!consumerInfo.firstAccessTime) {\n consumerInfo.firstAccessTime = now;\n }\n\n consumerInfo.accessCount++;\n consumerInfo.lastAccessTime = now;\n\n if (type === 'state') {\n consumerInfo.stateAccesses.add(path);\n if (value !== undefined) {\n consumerInfo.stateValues.set(path, { value, lastAccessTime: now });\n }\n } else {\n consumerInfo.classAccesses.add(path);\n if (value !== undefined) {\n consumerInfo.classValues.set(path, { value, lastAccessTime: now });\n }\n }\n }\n\n resetTracking(consumerRef: object): void {\n const consumerInfo = this.consumers.get(consumerRef);\n if (!consumerInfo) return;\n\n consumerInfo.stateAccesses.clear();\n consumerInfo.classAccesses.clear();\n consumerInfo.stateValues.clear();\n consumerInfo.classValues.clear();\n consumerInfo.accessCount = 0;\n consumerInfo.firstAccessTime = 0;\n }\n\n getDependencies(consumerRef: object): DependencyArray | null {\n const consumerInfo = this.consumers.get(consumerRef);\n if (!consumerInfo) return null;\n\n return {\n statePaths: Array.from(consumerInfo.stateAccesses),\n classPaths: Array.from(consumerInfo.classAccesses),\n };\n }\n\n hasValuesChanged(\n consumerRef: object,\n newState: any,\n newBlocInstance: any,\n ): boolean {\n const consumerInfo = this.consumers.get(consumerRef);\n if (!consumerInfo) return true;\n\n let hasChanged = false;\n const now = Date.now();\n\n // If we haven't tracked any values yet, consider it changed to establish baseline\n if (\n consumerInfo.stateValues.size === 0 &&\n consumerInfo.classValues.size === 0 &&\n (consumerInfo.stateAccesses.size > 0 ||\n consumerInfo.classAccesses.size > 0)\n ) {\n return true;\n }\n\n // Check state values\n for (const [path, trackedValue] of consumerInfo.stateValues) {\n try {\n const currentValue = this.getValueAtPath(newState, path);\n if (currentValue !== trackedValue.value) {\n consumerInfo.stateValues.set(path, {\n value: currentValue,\n lastAccessTime: now,\n });\n hasChanged = true;\n }\n } catch (error) {\n hasChanged = true;\n }\n }\n\n // Check class getter values\n for (const [path, trackedValue] of consumerInfo.classValues) {\n try {\n const currentValue = this.getValueAtPath(newBlocInstance, path);\n if (currentValue !== trackedValue.value) {\n consumerInfo.classValues.set(path, {\n value: currentValue,\n lastAccessTime: now,\n });\n hasChanged = true;\n }\n } catch (error) {\n hasChanged = true;\n }\n }\n\n return hasChanged;\n }\n\n shouldNotifyConsumer(\n consumerRef: object,\n changedPaths: Set<string>,\n ): boolean {\n const consumerInfo = this.consumers.get(consumerRef);\n if (!consumerInfo) return false;\n\n // Check if any changed paths match tracked dependencies\n for (const changedPath of changedPaths) {\n if (consumerInfo.stateAccesses.has(changedPath)) return true;\n if (consumerInfo.classAccesses.has(changedPath)) return true;\n\n // Check for nested path changes\n for (const trackedPath of consumerInfo.stateAccesses) {\n if (\n changedPath.startsWith(trackedPath + '.') ||\n trackedPath.startsWith(changedPath + '.')\n ) {\n return true;\n }\n }\n }\n\n return false;\n }\n\n updateLastNotified(consumerRef: object): void {\n const consumerInfo = this.consumers.get(consumerRef);\n if (consumerInfo) {\n consumerInfo.lastNotified = Date.now();\n }\n }\n\n getConsumerInfo(consumerRef: object): ConsumerInfo | undefined {\n return this.consumers.get(consumerRef);\n }\n\n setHasRendered(consumerRef: object, hasRendered: boolean): void {\n const consumerInfo = this.consumers.get(consumerRef);\n if (consumerInfo) {\n consumerInfo.hasRendered = hasRendered;\n }\n }\n\n hasConsumer(consumerRef: object): boolean {\n return this.consumers.has(consumerRef);\n }\n\n getStats() {\n return {\n totalRegistrations: this.registrationCount,\n activeConsumers: this.activeConsumers,\n };\n }\n\n private getValueAtPath(obj: any, path: string): any {\n const parts = path.split('.');\n let current = obj;\n\n for (const part of parts) {\n if (current == null) return undefined;\n current = current[part];\n }\n\n return current;\n }\n}\n","import { BlocBase } from '../BlocBase';\nimport { BlocState } from '../types';\n\ninterface ConsumerTracker {\n trackAccess: (\n consumerRef: object,\n type: 'state' | 'class',\n path: string,\n value?: any,\n ) => void;\n}\n\n// Cache for proxies to ensure consistent object identity\nconst proxyCache = new WeakMap<object, WeakMap<object, any>>();\n\n// Statistics tracking\nlet proxyStats = {\n stateProxiesCreated: 0,\n classProxiesCreated: 0,\n cacheHits: 0,\n cacheMisses: 0,\n propertyAccesses: 0,\n nestedProxiesCreated: 0,\n totalProxiesCreated: 0,\n createdAt: Date.now(),\n};\n\nexport class ProxyFactory {\n static createStateProxy<T extends object>(options: {\n target: T;\n consumerRef: object;\n consumerTracker: ConsumerTracker;\n path?: string;\n }): T {\n const { target, consumerRef, consumerTracker, path = '' } = options;\n\n if (!consumerRef || !consumerTracker) {\n return target;\n }\n\n if (typeof target !== 'object' || target === null) {\n return target;\n }\n\n // Check cache to ensure consistent proxy identity\n let refCache = proxyCache.get(target);\n if (!refCache) {\n refCache = new WeakMap();\n proxyCache.set(target, refCache);\n }\n\n const existingProxy = refCache.get(consumerRef);\n if (existingProxy) {\n proxyStats.cacheHits++;\n return existingProxy;\n }\n\n proxyStats.cacheMisses++;\n\n const handler: ProxyHandler<T> = {\n get(obj: T, prop: string | symbol): any {\n // Handle symbols and special properties\n if (typeof prop === 'symbol' || prop === 'constructor') {\n return Reflect.get(obj, prop);\n }\n\n const fullPath = path ? `${path}.${prop}` : prop;\n proxyStats.propertyAccesses++;\n\n const value = Reflect.get(obj, prop);\n const valueType = typeof value;\n const isObject = value && valueType === 'object' && value !== null;\n\n // Track the access with value (only for primitives at root level)\n const trackValue = !isObject ? value : undefined;\n consumerTracker.trackAccess(consumerRef, 'state', fullPath, trackValue);\n\n // Recursively proxy nested objects and arrays\n if (value && typeof value === 'object' && value !== null) {\n // Support arrays, plain objects, and other object types\n const isPlainObject =\n Object.getPrototypeOf(value) === Object.prototype;\n const isArray = Array.isArray(value);\n\n if (isPlainObject || isArray) {\n proxyStats.nestedProxiesCreated++;\n return ProxyFactory.createStateProxy({\n target: value,\n consumerRef,\n consumerTracker,\n path: fullPath,\n });\n }\n }\n\n return value;\n },\n\n has(obj: T, prop: string | symbol): boolean {\n return prop in obj;\n },\n\n ownKeys(obj: T): (string | symbol)[] {\n return Reflect.ownKeys(obj);\n },\n\n getOwnPropertyDescriptor(\n obj: T,\n prop: string | symbol,\n ): PropertyDescriptor | undefined {\n return Reflect.getOwnPropertyDescriptor(obj, prop);\n },\n\n set(): boolean {\n // State should not be mutated directly. Use emit() or patch() methods.\n return false;\n },\n\n deleteProperty(): boolean {\n // State properties should not be deleted directly.\n return false;\n },\n };\n\n const proxy = new Proxy(target, handler);\n refCache.set(consumerRef, proxy);\n\n proxyStats.stateProxiesCreated++;\n proxyStats.totalProxiesCreated++;\n\n return proxy;\n }\n\n static createClassProxy<T extends object>(options: {\n target: T;\n consumerRef: object;\n consumerTracker: ConsumerTracker;\n }): T {\n const { target, consumerRef, consumerTracker } = options;\n\n if (!consumerRef || !consumerTracker) {\n return target;\n }\n\n // Check cache for class proxies\n let refCache = proxyCache.get(target);\n if (!refCache) {\n refCache = new WeakMap();\n proxyCache.set(target, refCache);\n }\n\n const existingProxy = refCache.get(consumerRef);\n if (existingProxy) {\n proxyStats.cacheHits++;\n return existingProxy;\n }\n\n proxyStats.cacheMisses++;\n\n const handler: ProxyHandler<T> = {\n get(obj: T, prop: string | symbol): any {\n const value = Reflect.get(obj, prop);\n // Check for getter on the prototype chain with safety limits\n let isGetter = false;\n let currentObj: any = obj;\n const visitedPrototypes = new WeakSet();\n const MAX_PROTOTYPE_DEPTH = 10; // Reasonable depth limit\n let depth = 0;\n\n while (currentObj && !isGetter && depth < MAX_PROTOTYPE_DEPTH) {\n // Check for circular references\n if (visitedPrototypes.has(currentObj)) {\n break;\n }\n visitedPrototypes.add(currentObj);\n\n try {\n const descriptor = Object.getOwnPropertyDescriptor(\n currentObj,\n prop,\n );\n if (descriptor && descriptor.get) {\n isGetter = true;\n break;\n }\n currentObj = Object.getPrototypeOf(currentObj);\n depth++;\n } catch (error) {\n break;\n }\n }\n\n if (!isGetter) {\n // bind methods to the object if they are functions\n /*\n if (typeof value === 'function') {\n proxyStats.propertyAccesses++;\n console.log(\n `🏭 [ProxyFactory] 🔧 Method accessed: ${String(prop)}`,\n );\n console.log(`🏭 [ProxyFactory] Binding method to object instance`);\n return value.bind(obj);\n }\n */\n\n // Return the value directly if it's not a getter or method\n return value;\n }\n\n // For getters, track access and value\n proxyStats.propertyAccesses++;\n\n // Track the getter value if it's a primitive\n const getterValue = value;\n const isGetterValuePrimitive =\n getterValue !== null && typeof getterValue !== 'object';\n const trackValue = isGetterValuePrimitive ? getterValue : undefined;\n\n // Track access with value for primitives\n consumerTracker.trackAccess(\n consumerRef,\n 'class',\n String(prop),\n trackValue,\n );\n return value;\n },\n\n has(obj: T, prop: string | symbol): boolean {\n return prop in obj;\n },\n\n ownKeys(obj: T): (string | symbol)[] {\n return Reflect.ownKeys(obj);\n },\n\n getOwnPropertyDescriptor(\n obj: T,\n prop: string | symbol,\n ): PropertyDescriptor | undefined {\n return Reflect.getOwnPropertyDescriptor(obj, prop);\n },\n };\n\n const proxy = new Proxy(target, handler);\n refCache.set(consumerRef, proxy);\n\n proxyStats.classProxiesCreated++;\n proxyStats.totalProxiesCreated++;\n\n return proxy;\n }\n\n static getProxyState<B extends BlocBase<any>>(options: {\n state: BlocState<B>;\n consumerRef: object;\n consumerTracker: ConsumerTracker;\n }): BlocState<B> {\n return ProxyFactory.createStateProxy({\n target: options.state,\n consumerRef: options.consumerRef,\n consumerTracker: options.consumerTracker,\n });\n }\n\n static getProxyBlocInstance<B extends BlocBase<any>>(options: {\n blocInstance: B;\n consumerRef: object;\n consumerTracker: ConsumerTracker;\n }): B {\n return ProxyFactory.createClassProxy({\n target: options.blocInstance,\n consumerRef: options.consumerRef,\n consumerTracker: options.consumerTracker,\n });\n }\n\n static getStats() {\n const lifetime = Date.now() - proxyStats.createdAt;\n return {\n ...proxyStats,\n totalProxies:\n proxyStats.stateProxiesCreated + proxyStats.classProxiesCreated,\n cacheEfficiency:\n proxyStats.cacheHits + proxyStats.cacheMisses > 0\n ? `${((proxyStats.cacheHits / (proxyStats.cacheHits + proxyStats.cacheMisses)) * 100).toFixed(1)}%`\n : 'N/A',\n lifetime: `${lifetime}ms`,\n proxiesPerSecond:\n lifetime > 0\n ? (proxyStats.totalProxiesCreated / (lifetime / 1000)).toFixed(2)\n : 'N/A',\n };\n }\n\n static resetStats() {\n proxyStats = {\n stateProxiesCreated: 0,\n classProxiesCreated: 0,\n cacheHits: 0,\n cacheMisses: 0,\n propertyAccesses: 0,\n nestedProxiesCreated: 0,\n totalProxiesCreated: 0,\n createdAt: Date.now(),\n };\n }\n}\n","import { Blac } from '../Blac';\nimport { BlocBase, BlocLifecycleState } from '../BlocBase';\nimport { BlocConstructor, BlocState, InferPropsFromGeneric } from '../types';\nimport { PropsUpdated } from '../events';\nimport { generateUUID } from '../utils/uuid';\nimport { shallowEqual } from '../utils/shallowEqual';\nimport { ConsumerTracker, DependencyArray } from './ConsumerTracker';\nimport { ProxyFactory } from './ProxyFactory';\n\nexport interface AdapterOptions<B extends BlocBase<any>> {\n id?: string;\n dependencies?: (bloc: B) => unknown[];\n props?: any;\n onMount?: (bloc: B) => void;\n onUnmount?: (bloc: B) => void;\n}\n\n/**\n * BlacAdapter orchestrates the connection between Bloc instances and React components.\n * It manages dependency tracking, lifecycle hooks, and proxy creation.\n */\nexport class BlacAdapter<B extends BlocConstructor<BlocBase<any>>> {\n public readonly id = `consumer-${generateUUID()}`;\n public readonly blocConstructor: B;\n public readonly componentRef: { current: object } = { current: {} };\n public blocInstance: InstanceType<B>;\n\n // Core components\n private consumerTracker: ConsumerTracker;\n\n // Props ownership tracking\n private static propsOwners = new WeakMap<BlocBase<any>, string>();\n private lastProps?: any;\n\n unmountTime: number = 0;\n mountTime: number = 0;\n\n // Dependency tracking\n private dependencyValues?: unknown[];\n private isUsingDependencies: boolean = false;\n\n // Lifecycle state\n private hasMounted = false;\n private mountCount = 0;\n\n options?: AdapterOptions<InstanceType<B>>;\n\n constructor(\n instanceProps: { componentRef: { current: object }; blocConstructor: B },\n options?: typeof this.options,\n ) {\n this.options = options;\n this.blocConstructor = instanceProps.blocConstructor;\n this.componentRef = instanceProps.componentRef;\n this.isUsingDependencies = !!options?.dependencies;\n\n // Initialize consumer tracker\n this.consumerTracker = new ConsumerTracker();\n\n // Initialize bloc instance and register consumer\n this.blocInstance = this.updateBlocInstance();\n this.consumerTracker.register(instanceProps.componentRef.current, this.id);\n\n // Initialize dependency values if using dependencies\n if (this.isUsingDependencies && options?.dependencies) {\n this.dependencyValues = options.dependencies(this.blocInstance);\n }\n\n // Handle initial props if provided\n if (options?.props !== undefined) {\n this.updateProps(options.props);\n }\n }\n\n trackAccess(\n consumerRef: object,\n type: 'state' | 'class',\n path: string,\n value?: any,\n ): void {\n this.consumerTracker.trackAccess(consumerRef, type, path, value);\n }\n\n getConsumerDependencies(consumerRef: object): DependencyArray | null {\n return this.consumerTracker.getDependencies(consumerRef);\n }\n\n shouldNotifyConsumer(\n consumerRef: object,\n changedPaths: Set<string>,\n ): boolean {\n const consumerInfo = this.consumerTracker.getConsumerInfo(consumerRef);\n if (!consumerInfo) {\n return true; // If consumer not registered yet, notify by default\n }\n\n // First render - always notify to establish baseline\n if (!consumerInfo.hasRendered) {\n return true;\n }\n\n // Use built-in method from ConsumerTracker\n return this.consumerTracker.shouldNotifyConsumer(consumerRef, changedPaths);\n }\n\n updateLastNotified(consumerRef: object): void {\n this.consumerTracker.updateLastNotified(consumerRef);\n this.consumerTracker.setHasRendered(consumerRef, true);\n }\n\n resetConsumerTracking(): void {\n this.consumerTracker.resetTracking(this.componentRef.current);\n }\n\n createStateProxy = <T extends object>(props: { target: T }): T => {\n return ProxyFactory.createStateProxy({\n target: props.target,\n consumerRef: this.componentRef.current,\n consumerTracker: this as any,\n });\n };\n\n createClassProxy = <T extends object>(props: { target: T }): T => {\n return ProxyFactory.createClassProxy({\n target: props.target,\n consumerRef: this.componentRef.current,\n consumerTracker: this as any,\n });\n };\n\n updateBlocInstance(): InstanceType<B> {\n this.blocInstance = Blac.instance.getBloc<B>(this.blocConstructor, {\n props: this.options?.props,\n id: this.options?.id,\n instanceRef: this.id,\n });\n return this.blocInstance;\n }\n\n createSubscription = (options: { onChange: () => void }) => {\n const unsubscribe = this.blocInstance._observer.subscribe({\n id: this.id,\n fn: (\n newState: BlocState<InstanceType<B>>,\n oldState: BlocState<InstanceType<B>>,\n ) => {\n // Case 1: Manual dependencies provided\n if (this.isUsingDependencies && this.options?.dependencies) {\n const newValues = this.options.dependencies(this.blocInstance);\n const hasChanged = this.hasDependencyValuesChanged(\n this.dependencyValues,\n newValues,\n );\n\n if (!hasChanged) {\n return; // Don't trigger re-render\n }\n\n this.dependencyValues = newValues;\n } \n // Case 2: Proxy tracking disabled globally (and no manual dependencies)\n else if (!Blac.config.proxyDependencyTracking) {\n // Always trigger re-render when proxy tracking is disabled\n options.onChange();\n return;\n } \n // Case 3: Proxy tracking enabled (default behavior)\n else {\n // Check if any tracked values have changed (proxy-based tracking)\n const consumerInfo = this.consumerTracker.getConsumerInfo(\n this.componentRef.current,\n );\n if (consumerInfo && consumerInfo.hasRendered) {\n // Only check dependencies if component has rendered at least once\n const hasChanged = this.consumerTracker.hasValuesChanged(\n this.componentRef.current,\n newState,\n this.blocInstance,\n );\n\n if (!hasChanged) {\n return; // Don't trigger re-render\n }\n }\n }\n\n options.onChange();\n },\n });\n\n return unsubscribe;\n };\n\n mount = (): void => {\n // Re-run dependencies on mount to ensure fresh values\n if (this.isUsingDependencies && this.options?.dependencies) {\n this.dependencyValues = this.options.dependencies(this.blocInstance);\n }\n\n // Lifecycle management\n this.mountCount++;\n this.blocInstance._addConsumer(this.id, this.componentRef.current);\n\n // Call onMount callback if provided and not already called\n if (!this.hasMounted) {\n this.hasMounted = true;\n this.mountTime = Date.now();\n\n if (this.options?.onMount) {\n try {\n this.options.onMount(this.blocInstance);\n } catch (error) {\n throw error;\n }\n }\n }\n };\n\n unmount = (): void => {\n this.unmountTime = Date.now();\n this.consumerTracker.unregister(this.componentRef.current);\n this.blocInstance._removeConsumer(this.id);\n\n // Clear ownership if we own this bloc\n if (BlacAdapter.propsOwners.get(this.blocInstance) === this.id) {\n BlacAdapter.propsOwners.delete(this.blocInstance);\n }\n\n // Call onUnmount callback\n if (this.options?.onUnmount) {\n try {\n this.options.onUnmount(this.blocInstance);\n } catch (error) {\n // Don't re-throw on unmount to allow cleanup to continue\n }\n }\n };\n\n getProxyState = (\n state: BlocState<InstanceType<B>>,\n ): BlocState<InstanceType<B>> => {\n // Return raw state if proxy tracking is disabled globally or using manual dependencies\n if (this.isUsingDependencies || !Blac.config.proxyDependencyTracking) {\n return state;\n }\n\n return ProxyFactory.getProxyState({\n state,\n consumerRef: this.componentRef.current,\n consumerTracker: this as any,\n });\n };\n\n getProxyBlocInstance = (): InstanceType<B> => {\n // Return raw instance if proxy tracking is disabled globally or using manual dependencies\n if (this.isUsingDependencies || !Blac.config.proxyDependencyTracking) {\n return this.blocInstance;\n }\n\n return ProxyFactory.getProxyBlocInstance({\n blocInstance: this.blocInstance,\n consumerRef: this.componentRef.current,\n consumerTracker: this as any,\n });\n };\n\n // Expose calledOnMount for backward compatibility\n get calledOnMount(): boolean {\n return this.hasMounted;\n }\n\n updateProps(props: any): void {\n const bloc = this.blocInstance;\n \n // Check ownership\n if (!BlacAdapter.propsOwners.has(bloc)) {\n // First adapter with props becomes the owner\n BlacAdapter.propsOwners.set(bloc, this.id);\n }\n \n if (BlacAdapter.propsOwners.get(bloc) !== this.id) {\n Blac.warn(\n `[BlacAdapter] Attempted to set props on ${bloc.constructor.name} from non-owner adapter`\n );\n return;\n }\n \n // Disposal safety\n if ((bloc as any)._disposalState === BlocLifecycleState.DISPOSED ||\n (bloc as any)._disposalState === BlocLifecycleState.DISPOSING) {\n return;\n }\n \n // Check if props have changed\n if (shallowEqual(this.lastProps, props)) {\n return;\n }\n \n // Update props based on bloc type\n if ('add' in bloc && typeof bloc.add === 'function') {\n // Bloc: dispatch PropsUpdated event\n (bloc as any).add(new PropsUpdated(props));\n } else if ('_updateProps' in bloc && typeof (bloc as any)._updateProps === 'function') {\n // Cubit: direct props update\n (bloc as any)._updateProps(props);\n }\n \n this.lastProps = props;\n }\n\n private hasDependencyValuesChanged(\n prev: unknown[] | undefined,\n next: unknown[],\n ): boolean {\n if (!prev) return true; // First run, always trigger\n if (prev.length !== next.length) return true;\n\n // Use Object.is for comparison (handles NaN, +0/-0 correctly)\n for (let i = 0; i < prev.length; i++) {\n if (!Object.is(prev[i], next[i])) {\n return true;\n }\n }\n\n return false;\n }\n}\n"],"names":["BlacObservable","bloc","__publicField","observer","disposalState","BlocLifecycleState","Blac","newState","oldState","action","shouldUpdate","lastDependencyCheck","newDependencyCheck","i","generateUUID","r","BlocBase","initialState","deadConsumers","consumerId","weakRef","id","originalId","consumerRef","_a","_b","batchFn","result","finalUpdate","Constructor","expectedState","_c","_d","previousState","transitionResult","error","handler","_SingletonBlacManager","instance","oldInstance","SingletonBlacManager","instanceManager","setBlacInstanceManager","manager","_Blac","options","args","message","oldBlocInstanceMap","oldIsolatedBlocMap","blocArray","currentState","base","key","blocClass","forceNewInstance","blocId","isolatedBloc","registeredBloc","isIsolated","registered","results","blocInstance","isolatedBlocs","toDispose","predicate","blocs","sum","arr","__unsafe_ignore_singleton","config","blocClassName","wasRemoved","index","b","wasInIndex","uid","props","instanceRef","newBloc","Bloc","eventConstructor","emit","constructorName","errorContext","k","Cubit","oldProps","state","statePatch","ignoreChangeCheck","changes","current","PropsUpdated","shallowEqual","a","keysA","keysB","BlocTest","BlocClass","timeout","resolve","reject","timeoutId","unsubscribe","expectedStates","receivedStates","expected","received","MockBloc","MockCubit","MemoryLeakDetector","currentStats","hasLeaks","report","ConsumerTracker","type","path","value","consumerInfo","now","newBlocInstance","hasChanged","trackedValue","currentValue","changedPaths","changedPath","trackedPath","hasRendered","obj","parts","part","proxyCache","proxyStats","ProxyFactory","target","consumerTracker","refCache","existingProxy","prop","fullPath","trackValue","isPlainObject","isArray","proxy","isGetter","currentObj","visitedPrototypes","MAX_PROTOTYPE_DEPTH","depth","descriptor","getterValue","lifetime","_BlacAdapter","instanceProps","newValues","prev","next","BlacAdapter"],"mappings":";;;AA0BO,MAAMA,EAA4B;AAAA;AAAA;AAAA;AAAA;AAAA,EAQvC,YAAYC,GAAmB;AAN/B;AAAA,IAAAC,EAAA;AAUQ,IAAAA,EAAA,wCAAiB,IAAqB;AAH5C,SAA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AA;AAGxC,aAAShJ,IAAI,GAAGA,IAAI+I,EAAK,QAAQ/I;AAC3B,UAAA,CAAC,OAAO,GAAG+I,EAAK/I,CAAC,GAAGgJ,EAAKhJ,CAAC,CAAC;AACtB,eAAA;AAIJ,WAAA;AAAA,EAAA;AAEX;AAAA;AAvSEX,EAVWuJ,GAUI,eAAc,oBAAI,QAA+B;AAV3D,IAAMK,IAANL;"}
|
|
1
|
+
{"version":3,"file":"index.es.js","sources":["../src/lifecycle/BlocLifecycle.ts","../src/plugins/SystemPluginRegistry.ts","../src/errors/BlacError.ts","../src/errors/ErrorManager.ts","../src/Blac.ts","../src/utils/uuid.ts","../src/errors/handleError.ts","../src/plugins/BlocPluginRegistry.ts","../src/subscription/SubscriptionManager.ts","../src/utils/BatchingManager.ts","../src/BlocBase.ts","../src/Bloc.ts","../src/Cubit.ts","../src/events.ts","../src/utils/shallowEqual.ts","../src/utils/generateInstanceId.ts","../src/utils/RerenderLogger.ts","../src/testing.ts","../src/adapter/ProxyFactory.ts","../src/adapter/BlacAdapter.ts"],"sourcesContent":["/**\n * Enum representing the lifecycle states of a Bloc instance\n */\nexport enum BlocLifecycleState {\n ACTIVE = 'active',\n DISPOSAL_REQUESTED = 'disposal_requested',\n DISPOSING = 'disposing',\n DISPOSED = 'disposed',\n}\n\nexport interface StateTransitionResult {\n success: boolean;\n currentState: BlocLifecycleState;\n previousState: BlocLifecycleState;\n}\n\n/**\n * Manages the lifecycle state transitions for Bloc instances.\n * Ensures atomic state transitions to prevent race conditions during disposal.\n */\nexport class BlocLifecycleManager {\n private disposalState = BlocLifecycleState.ACTIVE;\n private disposalLock = false;\n private disposalTimer?: NodeJS.Timeout | number;\n private disposalHandler?: (bloc: unknown) => void;\n\n get currentState(): BlocLifecycleState {\n return this.disposalState;\n }\n\n get isDisposed(): boolean {\n return this.disposalState === BlocLifecycleState.DISPOSED;\n }\n\n /**\n * Atomic state transition for disposal\n */\n atomicStateTransition(\n expectedState: BlocLifecycleState,\n newState: BlocLifecycleState,\n ): StateTransitionResult {\n if (this.disposalLock) {\n return {\n success: false,\n currentState: this.disposalState,\n previousState: this.disposalState,\n };\n }\n\n this.disposalLock = true;\n try {\n if (this.disposalState !== expectedState) {\n return {\n success: false,\n currentState: this.disposalState,\n previousState: this.disposalState,\n };\n }\n\n const previousState = this.disposalState;\n this.disposalState = newState;\n\n return {\n success: true,\n currentState: newState,\n previousState,\n };\n } finally {\n this.disposalLock = false;\n }\n }\n\n /**\n * Schedule disposal after a delay\n */\n scheduleDisposal(\n delay: number,\n canDispose: () => boolean,\n onDispose: () => void,\n ): void {\n // Cancel any existing disposal timer\n if (this.disposalTimer) {\n clearTimeout(this.disposalTimer as NodeJS.Timeout);\n this.disposalTimer = undefined;\n }\n\n const transitionResult = this.atomicStateTransition(\n BlocLifecycleState.ACTIVE,\n BlocLifecycleState.DISPOSAL_REQUESTED,\n );\n\n if (!transitionResult.success) {\n return;\n }\n\n this.disposalTimer = setTimeout(() => {\n if (\n canDispose() &&\n this.disposalState === BlocLifecycleState.DISPOSAL_REQUESTED\n ) {\n onDispose();\n } else {\n this.atomicStateTransition(\n BlocLifecycleState.DISPOSAL_REQUESTED,\n BlocLifecycleState.ACTIVE,\n );\n }\n }, delay);\n }\n\n /**\n * Cancel disposal if in disposal requested state\n */\n cancelDisposal(): boolean {\n if (this.disposalState === BlocLifecycleState.DISPOSAL_REQUESTED) {\n // Cancel disposal timer\n if (this.disposalTimer) {\n clearTimeout(this.disposalTimer as NodeJS.Timeout);\n this.disposalTimer = undefined;\n }\n\n // Transition back to active state\n const result = this.atomicStateTransition(\n BlocLifecycleState.DISPOSAL_REQUESTED,\n BlocLifecycleState.ACTIVE,\n );\n\n return result.success;\n }\n return false;\n }\n\n /**\n * Set disposal handler\n */\n setDisposalHandler(handler: (bloc: unknown) => void): void {\n this.disposalHandler = handler;\n }\n\n /**\n * Get disposal handler\n */\n getDisposalHandler(): ((bloc: unknown) => void) | undefined {\n return this.disposalHandler;\n }\n\n /**\n * Clear disposal timer\n */\n clearDisposalTimer(): void {\n if (this.disposalTimer) {\n clearTimeout(this.disposalTimer as NodeJS.Timeout);\n this.disposalTimer = undefined;\n }\n }\n}\n","import {\n BlacPlugin,\n PluginRegistry,\n PluginMetrics,\n ErrorContext,\n AdapterMetadata,\n} from './types';\nimport { BlocBase } from '../BlocBase';\nimport { Bloc } from '../Bloc';\n\n/**\n * Registry for system-wide plugins\n */\nexport class SystemPluginRegistry implements PluginRegistry<BlacPlugin> {\n private plugins = new Map<string, BlacPlugin>();\n private metrics = new Map<string, Map<string, PluginMetrics>>();\n private executionOrder: string[] = [];\n\n /**\n * Add a system plugin\n */\n add(plugin: BlacPlugin): void {\n if (this.plugins.has(plugin.name)) {\n throw new Error(`Plugin '${plugin.name}' is already registered`);\n }\n\n this.plugins.set(plugin.name, plugin);\n this.executionOrder.push(plugin.name);\n this.initializeMetrics(plugin.name);\n }\n\n /**\n * Remove a system plugin\n */\n remove(pluginName: string): boolean {\n const plugin = this.plugins.get(pluginName);\n if (!plugin) return false;\n\n this.plugins.delete(pluginName);\n this.metrics.delete(pluginName);\n this.executionOrder = this.executionOrder.filter(\n (name) => name !== pluginName,\n );\n\n return true;\n }\n\n /**\n * Get a plugin by name\n */\n get(pluginName: string): BlacPlugin | undefined {\n return this.plugins.get(pluginName);\n }\n\n /**\n * Get all plugins in execution order\n */\n getAll(): ReadonlyArray<BlacPlugin> {\n return this.executionOrder.map((name) => this.plugins.get(name)!);\n }\n\n /**\n * Clear all plugins\n */\n clear(): void {\n this.plugins.clear();\n this.metrics.clear();\n this.executionOrder = [];\n }\n\n /**\n * Execute a hook on all plugins\n */\n executeHook(\n hookName: keyof BlacPlugin,\n args: unknown[],\n errorHandler?: (error: Error, plugin: BlacPlugin) => void,\n ): void {\n for (const pluginName of this.executionOrder) {\n const plugin = this.plugins.get(pluginName)!;\n const hook = plugin[hookName] as Function | undefined;\n\n if (typeof hook !== 'function') continue;\n\n const startTime = performance.now();\n\n try {\n hook.apply(plugin, args);\n this.recordSuccess(pluginName, hookName as string, startTime);\n } catch (error) {\n this.recordError(pluginName, hookName as string, error as Error);\n\n if (errorHandler) {\n errorHandler(error as Error, plugin);\n } else {\n // Default: log and continue\n console.error(\n `Plugin '${pluginName}' error in hook '${hookName as string}':`,\n error,\n );\n }\n }\n }\n }\n\n /**\n * Bootstrap all plugins\n */\n bootstrap(): void {\n this.executeHook('beforeBootstrap', []);\n this.executeHook('afterBootstrap', []);\n }\n\n /**\n * Shutdown all plugins\n */\n shutdown(): void {\n this.executeHook('beforeShutdown', []);\n this.executeHook('afterShutdown', []);\n }\n\n /**\n * Notify plugins of bloc creation\n */\n notifyBlocCreated(bloc: BlocBase<any>): void {\n this.executeHook('onBlocCreated', [bloc]);\n }\n\n /**\n * Notify plugins of bloc disposal\n */\n notifyBlocDisposed(bloc: BlocBase<any>): void {\n this.executeHook('onBlocDisposed', [bloc]);\n }\n\n /**\n * Notify plugins of state change\n */\n notifyStateChanged(\n bloc: BlocBase<any>,\n previousState: any,\n currentState: any,\n ): void {\n this.executeHook('onStateChanged', [bloc, previousState, currentState]);\n }\n\n /**\n * Notify plugins of event addition\n */\n notifyEventAdded(bloc: Bloc<any, any>, event: any): void {\n this.executeHook('onEventAdded', [bloc, event]);\n }\n\n /**\n * Notify plugins of errors\n */\n notifyError(\n error: Error,\n bloc: BlocBase<unknown>,\n context: ErrorContext,\n ): void {\n this.executeHook('onError', [error, bloc, context], (hookError, plugin) => {\n // Double fault protection - if error handler fails, just log\n console.error(`Plugin '${plugin.name}' error handler failed:`, hookError);\n });\n }\n\n /**\n * Notify plugins of adapter lifecycle events\n */\n notifyAdapterCreated(adapter: any, metadata: AdapterMetadata): void {\n this.executeHook('onAdapterCreated', [adapter, metadata]);\n }\n\n notifyAdapterMount(adapter: any, metadata: AdapterMetadata): void {\n this.executeHook('onAdapterMount', [adapter, metadata]);\n }\n\n notifyAdapterUnmount(adapter: any, metadata: AdapterMetadata): void {\n this.executeHook('onAdapterUnmount', [adapter, metadata]);\n }\n\n notifyAdapterRender(adapter: any, metadata: AdapterMetadata): void {\n this.executeHook('onAdapterRender', [adapter, metadata]);\n }\n\n notifyAdapterDisposed(adapter: any, metadata: AdapterMetadata): void {\n this.executeHook('onAdapterDisposed', [adapter, metadata]);\n }\n\n /**\n * Get metrics for a plugin\n */\n getMetrics(pluginName: string): Map<string, PluginMetrics> | undefined {\n return this.metrics.get(pluginName);\n }\n\n private initializeMetrics(pluginName: string): void {\n this.metrics.set(pluginName, new Map());\n }\n\n private recordSuccess(\n pluginName: string,\n hookName: string,\n startTime: number,\n ): void {\n const pluginMetrics = this.metrics.get(pluginName)!;\n const hookMetrics = pluginMetrics.get(hookName) || {\n executionTime: 0,\n executionCount: 0,\n errorCount: 0,\n };\n\n const executionTime = performance.now() - startTime;\n\n pluginMetrics.set(hookName, {\n ...hookMetrics,\n executionTime: hookMetrics.executionTime + executionTime,\n executionCount: hookMetrics.executionCount + 1,\n lastExecutionTime: executionTime,\n });\n }\n\n private recordError(\n pluginName: string,\n hookName: string,\n error: Error,\n ): void {\n const pluginMetrics = this.metrics.get(pluginName)!;\n const hookMetrics = pluginMetrics.get(hookName) || {\n executionTime: 0,\n executionCount: 0,\n errorCount: 0,\n };\n\n pluginMetrics.set(hookName, {\n ...hookMetrics,\n errorCount: hookMetrics.errorCount + 1,\n lastError: error,\n });\n }\n}\n","export enum ErrorCategory {\n LIFECYCLE = 'LIFECYCLE',\n STATE = 'STATE',\n PLUGIN = 'PLUGIN',\n VALIDATION = 'VALIDATION',\n DISPOSAL = 'DISPOSAL',\n CONSUMER = 'CONSUMER',\n}\n\nexport enum ErrorSeverity {\n FATAL = 'FATAL', // System cannot continue\n ERROR = 'ERROR', // Operation failed but system continues\n WARNING = 'WARNING', // Potential issue but operation succeeded\n INFO = 'INFO', // Informational, not an error\n}\n\nexport type BlacErrorContext = {\n blocName?: string;\n blocId?: string;\n consumerId?: string;\n pluginName?: string;\n operation?: string;\n metadata?: Record<string, unknown>;\n};\n\nexport class BlacError extends Error {\n constructor(\n message: string,\n public readonly category: ErrorCategory,\n public readonly severity: ErrorSeverity,\n public readonly context?: BlacErrorContext,\n public readonly cause?: unknown,\n ) {\n super(message);\n this.name = 'BlacError';\n\n // Ensure proper prototype chain\n Object.setPrototypeOf(this, BlacError.prototype);\n }\n\n toString(): string {\n const contextStr = this.context\n ? ` [${Object.entries(this.context)\n .filter(([_, v]) => v !== undefined)\n .map(([k, v]) => `${k}: ${v}`)\n .join(', ')}]`\n : '';\n\n return `${this.name} [${this.severity}/${this.category}]: ${this.message}${contextStr}`;\n }\n}\n\nexport type ErrorHandler = (error: BlacError) => void;\n\nexport type ErrorHandlingStrategy = {\n shouldPropagate: (error: BlacError) => boolean;\n shouldLog: (error: BlacError) => boolean;\n handle: (error: BlacError) => void;\n};\n\nexport const DefaultErrorStrategy: ErrorHandlingStrategy = {\n shouldPropagate: (error) => error.severity === ErrorSeverity.FATAL,\n shouldLog: (error) => error.severity !== ErrorSeverity.INFO,\n handle: (error) => {\n if (DefaultErrorStrategy.shouldLog(error)) {\n console.error(error.toString(), error.cause);\n }\n },\n};\n","import {\n BlacError,\n ErrorHandler,\n ErrorHandlingStrategy,\n DefaultErrorStrategy,\n} from './BlacError';\n\n/**\n * Centralized error management system for BlaC framework.\n * Handles error processing, logging, and propagation strategies.\n */\nexport class ErrorManager {\n private static instance: ErrorManager;\n private handlers: Set<ErrorHandler> = new Set();\n private strategy: ErrorHandlingStrategy = DefaultErrorStrategy;\n\n /**\n * Get the singleton instance of ErrorManager\n */\n static getInstance(): ErrorManager {\n if (!ErrorManager.instance) {\n ErrorManager.instance = new ErrorManager();\n }\n return ErrorManager.instance;\n }\n\n /**\n * Set a custom error handling strategy\n */\n setStrategy(strategy: ErrorHandlingStrategy): void {\n this.strategy = strategy;\n }\n\n /**\n * Add a custom error handler that will be called for all errors\n */\n addHandler(handler: ErrorHandler): void {\n this.handlers.add(handler);\n }\n\n /**\n * Remove a previously added error handler\n */\n removeHandler(handler: ErrorHandler): void {\n this.handlers.delete(handler);\n }\n\n /**\n * Process an error through all handlers and apply the configured strategy\n */\n handle(error: BlacError): void {\n // Always notify handlers first\n this.handlers.forEach((handler) => {\n try {\n handler(error);\n } catch (handlerError) {\n // Prevent handler errors from breaking error handling\n console.error('Error in error handler:', handlerError);\n }\n });\n\n // Apply strategy\n this.strategy.handle(error);\n\n // Propagate if needed\n if (this.strategy.shouldPropagate(error)) {\n throw error;\n }\n }\n\n /**\n * Convenience method for wrapping operations with error handling\n */\n wrap<T>(operation: () => T, errorFactory: (error: unknown) => BlacError): T {\n try {\n return operation();\n } catch (error) {\n const blacError = errorFactory(error);\n this.handle(blacError);\n // Will only reach here if strategy says not to propagate\n return undefined as T;\n }\n }\n\n /**\n * Async version of wrap\n */\n async wrapAsync<T>(\n operation: () => Promise<T>,\n errorFactory: (error: unknown) => BlacError,\n ): Promise<T> {\n try {\n return await operation();\n } catch (error) {\n const blacError = errorFactory(error);\n this.handle(blacError);\n // Will only reach here if strategy says not to propagate\n return undefined as T;\n }\n }\n}\n","import { BlocBase, BlocInstanceId } from './BlocBase';\nimport { BlocLifecycleState } from './lifecycle/BlocLifecycle';\nimport {\n BlocBaseAbstract,\n BlocConstructor,\n BlocHookDependencyArrayFn,\n BlocState,\n} from './types';\nimport { SystemPluginRegistry } from './plugins/SystemPluginRegistry';\nimport { BlacError, ErrorCategory, ErrorSeverity } from './errors/BlacError';\nimport { ErrorManager } from './errors/ErrorManager';\n\n/**\n * Configuration options for the Blac instance\n */\nexport interface BlacConfig {\n /**\n * Whether to enable proxy dependency tracking for automatic re-render optimization.\n * When false, state changes always cause re-renders unless dependencies are manually specified.\n * Default: true\n */\n proxyDependencyTracking?: boolean;\n}\n\nexport interface GetBlocOptions<B extends BlocBase<unknown>> {\n id?: string;\n selector?: BlocHookDependencyArrayFn<BlocState<B>>;\n constructorParams?: ConstructorParameters<BlocConstructor<B>>[];\n onMount?: (bloc: B) => void;\n instanceRef?: string;\n throwIfNotFound?: boolean;\n /** Force creation of a new instance for isolated blocs, bypassing instance lookup */\n forceNewInstance?: 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({\n __unsafe_ignore_singleton: true,\n });\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({\n __unsafe_ignore_singleton: true,\n });\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 static get instance(): Blac {\n return instanceManager.getInstance();\n }\n /** Timestamp when the instance was created */\n createdAt = Date.now();\n private errorManager = ErrorManager.getInstance();\n static get getAllBlocs() {\n return Blac.instance.getAllBlocs;\n }\n\n /** Private static configuration */\n private static _config: BlacConfig = {\n proxyDependencyTracking: true,\n };\n\n /** Get current configuration */\n static get config(): Readonly<BlacConfig> {\n return { ...this._config };\n }\n\n /**\n * Set or update Blac configuration\n * @param config - Partial configuration to merge with existing config\n * @throws Error if configuration is invalid\n */\n static setConfig(config: Partial<BlacConfig>): void {\n // Validate config\n if (\n config.proxyDependencyTracking !== undefined &&\n typeof config.proxyDependencyTracking !== 'boolean'\n ) {\n const error = new BlacError(\n 'BlacConfig.proxyDependencyTracking must be a boolean',\n ErrorCategory.VALIDATION,\n ErrorSeverity.FATAL,\n );\n this.instance.errorManager.handle(error);\n }\n\n // Merge with existing config\n this._config = {\n ...this._config,\n ...config,\n };\n\n // Log config update if logging is enabled\n if (this.enableLog) {\n this.instance.log('Blac config updated:', this._config);\n }\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 // Using BlocConstructor<BlocBase<unknown>> would break type inference when storing\n // different bloc types in the same map. The 'any' allows proper polymorphic storage\n // while maintaining type safety at usage sites through the BlocConstructor constraint.\n isolatedBlocMap: Map<BlocConstructor<any>, BlocBase<unknown>[]> = new Map();\n /** Map for O(1) lookup of isolated blocs by UID */\n 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 /** System plugin registry */\n readonly plugins = new SystemPluginRegistry();\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 // Bootstrap plugins on creation\n this.plugins.bootstrap();\n }\n\n /** Flag to enable/disable logging */\n static enableLog = false;\n static logLevel: 'warn' | 'log' = 'warn';\n static logSpy: ((...args: unknown[]) => void) | null = null;\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.logSpy) {\n Blac.logSpy(args);\n }\n if (Blac.enableLog && Blac.logLevel === 'warn') {\n // Logging disabled - console.warn removed\n }\n if (Blac.enableLog && Blac.logLevel === 'log') {\n // Logging disabled - console.log removed\n }\n };\n static get log() {\n return Blac.instance.log;\n }\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 * Logs a warning message\n * @param message - Warning message\n * @param args - Additional arguments\n */\n warn = (message: string, ...args: unknown[]) => {\n console.warn(message, ...args);\n };\n static get warn() {\n return Blac.instance.warn;\n }\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(message, ...args);\n }\n };\n static get error() {\n return Blac.instance.error;\n }\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 // TODO: Type assertion for private property access (see explanation above)\n if (\n !bloc._keepAlive &&\n (bloc as any)._disposalState === BlocLifecycleState.ACTIVE\n ) {\n this.disposeBloc(bloc);\n }\n });\n\n oldIsolatedBlocMap.forEach((blocArray) => {\n blocArray.forEach((bloc) => {\n // TODO: Type assertion for private property access (see explanation above)\n if (\n !bloc._keepAlive &&\n (bloc as any)._disposalState === BlocLifecycleState.ACTIVE\n ) {\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 // TODO: Type assertion needed to access private _disposalState property from external class.\n // This is safe because we know BlocBase has this property, but TypeScript can't verify\n // private property access across class boundaries. Alternative would be to make\n // _disposalState protected, but that would expose internal implementation details.\n const currentState = (bloc as any)._disposalState;\n const validStatesForDisposal = [\n BlocLifecycleState.ACTIVE,\n BlocLifecycleState.DISPOSAL_REQUESTED,\n ];\n\n if (!validStatesForDisposal.includes(currentState)) {\n this.log(\n `[${bloc._name}:${String(bloc._id)}] disposeBloc called on bloc in invalid state: ${currentState}`,\n );\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(\n `[${bloc._name}:${String(bloc._id)}] disposeBloc called. Isolated: ${String(base.isolated)}`,\n );\n\n // First dispose the bloc to prevent further operations\n bloc.dispose();\n\n // Notify plugins of bloc disposal\n this.plugins.notifyBlocDisposed(bloc);\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() {\n return Blac.instance.disposeBloc;\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<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\n // Don't return disposed blocs\n if (found && (found as any).isDisposed) {\n return undefined;\n }\n\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 && !(b as any).isDisposed) as\n | InstanceType<B>\n | 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 { constructorParams, instanceRef } = options;\n const newBloc = new blocClass(constructorParams) as InstanceType<B>;\n newBloc.blacInstance = this;\n newBloc._instanceRef = instanceRef;\n newBloc._id = 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 } else {\n this.registerBlocInstance(newBloc);\n }\n\n // Plugins are activated in constructor\n\n // Notify system plugins of bloc creation\n this.plugins.notifyBlocCreated(newBloc);\n\n return newBloc;\n }\n\n activateBloc = (bloc: BlocBase<unknown>): void => {\n // Don't activate disposed blocs\n if ((bloc as any)._disposalState !== BlocLifecycleState.ACTIVE) {\n this.log(\n `[${bloc._name}:${String(bloc._id)}] activateBloc called on disposed bloc. Ignoring.`,\n );\n return;\n }\n\n const base = bloc.constructor as unknown as BlocConstructor<BlocBase<any>>;\n const isIsolated = bloc.isIsolated;\n\n let found = isIsolated\n ? this.findIsolatedBlocInstance(base, bloc._id)\n : this.findRegisteredBlocInstance(base, bloc._id);\n if (found) {\n return;\n }\n\n this.log(\n `[${bloc._name}:${String(bloc._id)}] activateBloc called. Isolated: ${String(bloc.isIsolated)}`,\n );\n if (bloc.isIsolated) {\n this.registerIsolatedBlocInstance(bloc);\n } else {\n this.registerBlocInstance(bloc);\n }\n };\n static get activateBloc() {\n return Blac.instance.activateBloc;\n }\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, forceNewInstance } = options;\n const base = blocClass as unknown as BlocBaseAbstract;\n const blocId = id ?? blocClass.name;\n this.log(`[${blocClass.name}:${String(blocId)}] (getBloc) Called:`, {\n options,\n base,\n });\n\n // Skip instance lookup if forceNewInstance is true for isolated blocs\n if (!forceNewInstance) {\n if (base.isolated) {\n const isolatedBloc = this.findIsolatedBlocInstance<B>(\n blocClass,\n options.instanceRef ?? blocId,\n );\n if (isolatedBloc) {\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(\n blocClass,\n blocId,\n );\n if (registeredBloc) {\n return registeredBloc;\n } else {\n if (options.throwIfNotFound) {\n throw new Error(`Registered bloc ${blocClass.name} not found`);\n }\n }\n }\n }\n\n const bloc = this.createNewBlocInstance(blocClass, blocId, options);\n this.log(\n `[${blocClass.name}:${String(blocId)}] (getBloc) No existing instance found. Creating new one.`,\n options,\n bloc,\n );\n\n if (!bloc) {\n throw new Error(\n `[getBloc] Failed to create bloc instance for ${blocClass.name}. This should never happen.`,\n );\n }\n\n return bloc;\n };\n static get getBloc() {\n return Blac.instance.getBloc;\n }\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\n // Search non-isolated blocs\n this.blocInstanceMap.forEach((blocInstance) => {\n if (blocInstance.constructor === blocClass) {\n // 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() {\n return Blac.instance.disposeKeepAliveBlocs;\n }\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() {\n return Blac.instance.disposeBlocs;\n }\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(\n (sum, arr) => sum + arr.length,\n 0,\n ),\n keepAliveBlocs: this.keepAliveBlocs.size,\n isolatedBlocTypes: this.isolatedBlocMap.size,\n };\n };\n static get getMemoryStats() {\n return Blac.instance.getMemoryStats;\n }\n\n /**\n * Validates subscription references and cleans up orphaned blocs\n */\n validateConsumers = (): void => {\n for (const bloc of this.uidRegistry.values()) {\n // Check if bloc should be disposed after validation\n // TODO: Type assertion for private property access (see explanation above)\n if (\n bloc.subscriptionCount === 0 &&\n !bloc._keepAlive &&\n (bloc as any)._disposalState === BlocLifecycleState.ACTIVE\n ) {\n // Schedule disposal for blocs with no subscriptions\n setTimeout(() => {\n // Double-check conditions before disposal\n // TODO: Type assertion for private property access (see explanation above)\n if (\n bloc.subscriptionCount === 0 &&\n !bloc._keepAlive &&\n (bloc as any)._disposalState === BlocLifecycleState.ACTIVE\n ) {\n this.disposeBloc(bloc);\n }\n }, 1000); // Give a grace period\n }\n }\n };\n static get validateConsumers() {\n return Blac.instance.validateConsumers;\n }\n\n /**\n * Bootstrap the Blac instance and all plugins\n */\n bootstrap(): void {\n this.plugins.bootstrap();\n }\n\n /**\n * Shutdown the Blac instance and all plugins\n */\n shutdown(): void {\n this.plugins.shutdown();\n\n // Dispose all non-keepAlive blocs\n for (const bloc of this.blocInstanceMap.values()) {\n if (!bloc._keepAlive) {\n this.disposeBloc(bloc);\n }\n }\n\n for (const blocs of this.isolatedBlocMap.values()) {\n for (const bloc of blocs) {\n if (!bloc._keepAlive) {\n this.disposeBloc(bloc);\n }\n }\n }\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}\n","import {\n BlacError,\n ErrorCategory,\n ErrorSeverity,\n BlacErrorContext,\n} from './BlacError';\nimport { ErrorManager } from './ErrorManager';\n\n/**\n * Standard error handling helper for BlaC\n *\n * Usage:\n * - For fatal errors that should propagate: handleError.fatal(...)\n * - For recoverable errors: handleError.error(...)\n * - For warnings: handleError.warn(...)\n */\nexport const handleError = {\n fatal: (\n message: string,\n category: ErrorCategory,\n context?: BlacErrorContext,\n cause?: unknown,\n ): never => {\n const error = new BlacError(\n message,\n category,\n ErrorSeverity.FATAL,\n context,\n cause,\n );\n ErrorManager.getInstance().handle(error);\n // This will always throw due to FATAL severity\n throw error;\n },\n\n error: (\n message: string,\n category: ErrorCategory,\n context?: BlacErrorContext,\n cause?: unknown,\n ): void => {\n const error = new BlacError(\n message,\n category,\n ErrorSeverity.ERROR,\n context,\n cause,\n );\n ErrorManager.getInstance().handle(error);\n },\n\n warn: (\n message: string,\n category: ErrorCategory,\n context?: BlacErrorContext,\n cause?: unknown,\n ): void => {\n const error = new BlacError(\n message,\n category,\n ErrorSeverity.WARNING,\n context,\n cause,\n );\n ErrorManager.getInstance().handle(error);\n },\n\n info: (\n message: string,\n category: ErrorCategory,\n context?: BlacErrorContext,\n ): void => {\n const error = new BlacError(message, category, ErrorSeverity.INFO, context);\n ErrorManager.getInstance().handle(error);\n },\n\n /**\n * Wraps a function to catch and handle errors\n */\n wrap: <T>(\n fn: () => T,\n category: ErrorCategory,\n context?: BlacErrorContext,\n severity: ErrorSeverity = ErrorSeverity.ERROR,\n ): T | undefined => {\n try {\n return fn();\n } catch (cause) {\n const message = cause instanceof Error ? cause.message : String(cause);\n const error = new BlacError(message, category, severity, context, cause);\n ErrorManager.getInstance().handle(error);\n return undefined;\n }\n },\n\n /**\n * Wraps an async function to catch and handle errors\n */\n wrapAsync: async <T>(\n fn: () => Promise<T>,\n category: ErrorCategory,\n context?: BlacErrorContext,\n severity: ErrorSeverity = ErrorSeverity.ERROR,\n ): Promise<T | undefined> => {\n try {\n return await fn();\n } catch (cause) {\n const message = cause instanceof Error ? cause.message : String(cause);\n const error = new BlacError(message, category, severity, context, cause);\n ErrorManager.getInstance().handle(error);\n return undefined;\n }\n },\n};\n","import { BlocPlugin, PluginRegistry, ErrorContext } from './types';\nimport { handleError } from '../errors/handleError';\nimport { ErrorCategory } from '../errors/BlacError';\n\n/**\n * Registry for bloc-specific plugins\n */\nexport class BlocPluginRegistry<TState, TEvent = never>\n implements PluginRegistry<BlocPlugin<TState, TEvent>>\n{\n private plugins = new Map<string, BlocPlugin<TState, TEvent>>();\n private executionOrder: string[] = [];\n private attached = false;\n\n /**\n * Add a bloc plugin\n */\n add(plugin: BlocPlugin<TState, TEvent>): void {\n if (this.plugins.has(plugin.name)) {\n throw new Error(`Plugin '${plugin.name}' is already registered`);\n }\n\n // Validate capabilities\n if (plugin.capabilities) {\n this.validateCapabilities(plugin);\n }\n\n this.plugins.set(plugin.name, plugin);\n this.executionOrder.push(plugin.name);\n }\n\n /**\n * Remove a bloc plugin\n */\n remove(pluginName: string): boolean {\n const plugin = this.plugins.get(pluginName);\n if (!plugin) return false;\n\n // Call onDetach if attached\n if (this.attached && plugin.onDetach) {\n handleError.wrap(() => plugin.onDetach!(), ErrorCategory.PLUGIN, {\n pluginName,\n operation: 'onDetach',\n });\n }\n\n this.plugins.delete(pluginName);\n this.executionOrder = this.executionOrder.filter(\n (name) => name !== pluginName,\n );\n\n return true;\n }\n\n /**\n * Get a plugin by name\n */\n get(pluginName: string): BlocPlugin<TState, TEvent> | undefined {\n return this.plugins.get(pluginName);\n }\n\n /**\n * Get all plugins in execution order\n */\n getAll(): ReadonlyArray<BlocPlugin<TState, TEvent>> {\n return this.executionOrder.map((name) => this.plugins.get(name)!);\n }\n\n /**\n * Clear all plugins\n */\n clear(): void {\n // Detach all plugins first\n if (this.attached) {\n for (const plugin of this.getAll()) {\n if (plugin.onDetach) {\n handleError.wrap(() => plugin.onDetach!(), ErrorCategory.PLUGIN, {\n pluginName: plugin.name,\n operation: 'onDetach',\n });\n }\n }\n }\n\n this.plugins.clear();\n this.executionOrder = [];\n this.attached = false;\n }\n\n /**\n * Attach all plugins to a bloc\n */\n attach(bloc: any): void {\n if (this.attached) {\n throw new Error('Plugins are already attached');\n }\n\n for (const plugin of this.getAll()) {\n if (plugin.onAttach) {\n try {\n plugin.onAttach(bloc);\n } catch (error) {\n console.error(`Plugin '${plugin.name}' error in onAttach:`, error);\n // Remove failing plugin\n this.remove(plugin.name);\n }\n }\n }\n\n this.attached = true;\n }\n\n /**\n * Transform state through all plugins\n */\n transformState(previousState: TState, nextState: TState): TState {\n let transformedState = nextState;\n\n for (const plugin of this.getAll()) {\n if (plugin.transformState && this.canTransformState(plugin)) {\n try {\n transformedState = plugin.transformState(\n previousState,\n transformedState,\n );\n } catch (error) {\n console.error(\n `Plugin '${plugin.name}' error in transformState:`,\n error,\n );\n // Continue with untransformed state\n }\n }\n }\n\n return transformedState;\n }\n\n /**\n * Transform event through all plugins\n */\n transformEvent(event: TEvent): TEvent | null {\n let transformedEvent: TEvent | null = event;\n\n for (const plugin of this.getAll()) {\n if (transformedEvent === null) break;\n\n if (plugin.transformEvent && this.canInterceptEvents(plugin)) {\n try {\n transformedEvent = plugin.transformEvent(transformedEvent);\n } catch (error) {\n console.error(\n `Plugin '${plugin.name}' error in transformEvent:`,\n error,\n );\n // Continue with untransformed event\n }\n }\n }\n\n return transformedEvent;\n }\n\n /**\n * Notify plugins of state change\n */\n notifyStateChange(previousState: TState, currentState: TState): void {\n for (const plugin of this.getAll()) {\n if (plugin.onStateChange && this.canReadState(plugin)) {\n try {\n plugin.onStateChange(previousState, currentState);\n } catch (error) {\n console.error(\n `Plugin '${plugin.name}' error in onStateChange:`,\n error,\n );\n }\n }\n }\n }\n\n /**\n * Notify plugins of event\n */\n notifyEvent(event: TEvent): void {\n for (const plugin of this.getAll()) {\n if (plugin.onEvent && this.canReadState(plugin)) {\n try {\n plugin.onEvent(event);\n } catch (error) {\n console.error(`Plugin '${plugin.name}' error in onEvent:`, error);\n }\n }\n }\n }\n\n /**\n * Notify plugins of error\n */\n notifyError(error: Error, context: ErrorContext): void {\n for (const plugin of this.getAll()) {\n if (plugin.onError) {\n try {\n plugin.onError(error, context);\n } catch (hookError) {\n console.error(`Plugin '${plugin.name}' error in onError:`, hookError);\n }\n }\n }\n }\n\n private validateCapabilities(plugin: BlocPlugin<TState, TEvent>): void {\n const caps = plugin.capabilities!;\n\n // Validate logical constraints\n if (caps.transformState && !caps.readState) {\n throw new Error(\n `Plugin '${plugin.name}': transformState requires readState capability`,\n );\n }\n\n if (caps.interceptEvents && !caps.readState) {\n throw new Error(\n `Plugin '${plugin.name}': interceptEvents requires readState capability`,\n );\n }\n }\n\n private canReadState(plugin: BlocPlugin<TState, TEvent>): boolean {\n return !plugin.capabilities || plugin.capabilities.readState !== false;\n }\n\n private canTransformState(plugin: BlocPlugin<TState, TEvent>): boolean {\n return !plugin.capabilities || plugin.capabilities.transformState === true;\n }\n\n private canInterceptEvents(plugin: BlocPlugin<TState, TEvent>): boolean {\n return !plugin.capabilities || plugin.capabilities.interceptEvents === true;\n }\n}\n","import { BlocBase } from '../BlocBase';\nimport { Blac } from '../Blac';\nimport { generateUUID } from '../utils/uuid';\nimport {\n Subscription,\n SubscriptionOptions,\n SubscriptionManagerStats,\n} from './types';\n\n/**\n * Unified subscription manager that replaces the dual consumer/observer system.\n * Handles all state change subscriptions with a single, consistent interface.\n */\nexport class SubscriptionManager<S = unknown> {\n private subscriptions = new Map<string, Subscription<S>>();\n private pathToSubscriptions = new Map<string, Set<string>>();\n private weakRefCleanupScheduled = false;\n private totalNotifications = 0;\n\n constructor(private bloc: BlocBase<S>) {}\n\n /**\n * Subscribe to state changes\n */\n subscribe(options: SubscriptionOptions<S>): () => void {\n const id = `${options.type}-${generateUUID()}`;\n\n const subscription: Subscription<S> = {\n id,\n type: options.type,\n selector: options.selector,\n equalityFn: options.equalityFn || Object.is,\n notify: options.notify,\n priority: options.priority ?? 0,\n weakRef: options.weakRef,\n dependencies: new Set(),\n metadata: {\n lastNotified: Date.now(),\n hasRendered: false,\n accessCount: 0,\n firstAccessTime: Date.now(),\n },\n };\n\n // Initialize selector value if provided\n if (subscription.selector) {\n try {\n subscription.lastValue = subscription.selector(\n this.bloc.state,\n this.bloc,\n );\n } catch (error) {\n Blac.error(`SubscriptionManager: Error in selector for ${id}:`, error);\n }\n }\n\n this.subscriptions.set(id, subscription);\n\n Blac.log(\n `[${this.bloc._name}:${this.bloc._id}] Subscription added: ${id}. Total: ${this.subscriptions.size}`,\n );\n\n // Cancel disposal if bloc is in disposal_requested state\n (this.bloc as any)._cancelDisposalIfRequested();\n\n // Return unsubscribe function\n return () => this.unsubscribe(id);\n }\n\n /**\n * Unsubscribe by ID\n */\n unsubscribe(id: string): void {\n const subscription = this.subscriptions.get(id);\n if (!subscription) return;\n\n // Remove from path dependencies\n if (subscription.dependencies) {\n for (const path of subscription.dependencies) {\n const subs = this.pathToSubscriptions.get(path);\n if (subs) {\n subs.delete(id);\n if (subs.size === 0) {\n this.pathToSubscriptions.delete(path);\n }\n }\n }\n }\n\n this.subscriptions.delete(id);\n\n Blac.log(\n `[${this.bloc._name}:${this.bloc._id}] Subscription removed: ${id}. Remaining: ${this.subscriptions.size}`,\n );\n\n // Check if bloc should be disposed\n this.bloc.checkDisposal();\n }\n\n /**\n * Notify all subscriptions of state change\n */\n notify(newState: S, oldState: S, action?: unknown): void {\n // Clean up dead weak references if needed\n this.cleanupDeadReferences();\n\n // Sort subscriptions by priority (descending)\n const sortedSubscriptions = Array.from(this.subscriptions.values()).sort(\n (a, b) => (b.priority ?? 0) - (a.priority ?? 0),\n );\n\n for (const subscription of sortedSubscriptions) {\n // Check if WeakRef is still alive\n if (subscription.weakRef && !subscription.weakRef.deref()) {\n this.scheduleWeakRefCleanup();\n continue;\n }\n\n let shouldNotify = false;\n let newValue: unknown;\n let oldValue: unknown;\n\n if (subscription.selector) {\n // Use selector to determine if notification is needed\n try {\n newValue = subscription.selector(newState, this.bloc);\n oldValue = subscription.lastValue;\n\n const equalityFn = subscription.equalityFn || Object.is;\n shouldNotify = !equalityFn(oldValue, newValue);\n\n if (shouldNotify) {\n subscription.lastValue = newValue;\n }\n } catch (error) {\n Blac.error(\n `SubscriptionManager: Error in selector for ${subscription.id}:`,\n error,\n );\n continue;\n }\n } else {\n // No selector - check if tracked dependencies changed\n if (subscription.dependencies && subscription.dependencies.size > 0) {\n // Check which paths changed between old and new state\n const changedPaths = this.getChangedPaths(oldState, newState);\n shouldNotify = this.shouldNotifyForPaths(\n subscription.id,\n changedPaths,\n );\n if ((Blac.config as any).logLevel === 'debug') {\n Blac.log(\n `[SubscriptionManager] Subscription ${subscription.id} dependencies:`,\n Array.from(subscription.dependencies),\n );\n Blac.log(\n `[SubscriptionManager] Changed paths:`,\n Array.from(changedPaths),\n );\n Blac.log(`[SubscriptionManager] Should notify:`, shouldNotify);\n }\n } else {\n // No tracked dependencies, always notify\n shouldNotify = true;\n }\n newValue = newState;\n oldValue = oldState;\n }\n\n if (shouldNotify) {\n try {\n subscription.notify(newValue, oldValue, action);\n this.totalNotifications++;\n\n if (subscription.metadata) {\n subscription.metadata.lastNotified = Date.now();\n subscription.metadata.hasRendered = true;\n }\n } catch (error) {\n Blac.error(\n `SubscriptionManager: Error in notify for ${subscription.id}:`,\n error,\n );\n }\n }\n }\n }\n\n /**\n * Track a path access for a subscription\n */\n trackAccess(subscriptionId: string, path: string, value?: unknown): void {\n const subscription = this.subscriptions.get(subscriptionId);\n if (!subscription) return;\n\n // Update dependencies\n if (!subscription.dependencies) {\n subscription.dependencies = new Set();\n }\n subscription.dependencies.add(path);\n\n // Update path-to-subscription mapping\n let subs = this.pathToSubscriptions.get(path);\n if (!subs) {\n subs = new Set();\n this.pathToSubscriptions.set(path, subs);\n }\n subs.add(subscriptionId);\n\n // Update metadata\n if (subscription.metadata) {\n subscription.metadata.accessCount =\n (subscription.metadata.accessCount || 0) + 1;\n subscription.metadata.lastAccessTime = Date.now();\n }\n }\n\n /**\n * Get the paths that changed between two states\n */\n private getChangedPaths(\n oldState: any,\n newState: any,\n path = '',\n ): Set<string> {\n const changedPaths = new Set<string>();\n\n if (oldState === newState) return changedPaths;\n\n // Handle primitives\n if (\n typeof oldState !== 'object' ||\n typeof newState !== 'object' ||\n oldState === null ||\n newState === null\n ) {\n if (path) changedPaths.add(path);\n return changedPaths;\n }\n\n // Get all keys from both objects\n const allKeys = new Set([\n ...Object.keys(oldState),\n ...Object.keys(newState),\n ]);\n\n for (const key of allKeys) {\n const fullPath = path ? `${path}.${key}` : key;\n const oldValue = oldState[key];\n const newValue = newState[key];\n\n if (oldValue !== newValue) {\n changedPaths.add(fullPath);\n\n // For nested objects, get all nested changed paths\n if (\n typeof oldValue === 'object' &&\n typeof newValue === 'object' &&\n oldValue !== null &&\n newValue !== null\n ) {\n const nestedChanges = this.getChangedPaths(\n oldValue,\n newValue,\n fullPath,\n );\n nestedChanges.forEach((p) => changedPaths.add(p));\n }\n }\n }\n\n return changedPaths;\n }\n\n /**\n * Check if a subscription should be notified based on changed paths\n */\n shouldNotifyForPaths(\n subscriptionId: string,\n changedPaths: Set<string>,\n ): boolean {\n const subscription = this.subscriptions.get(subscriptionId);\n if (!subscription || !subscription.dependencies) return true;\n\n // Check if any tracked dependencies match changed paths\n for (const trackedPath of subscription.dependencies) {\n // Handle class getter dependencies (_class.propertyName)\n if (trackedPath.startsWith('_class.')) {\n // For class getters, we need to notify on any state change\n // since we can't determine which state properties the getter depends on\n // This is conservative but ensures correctness\n if (changedPaths.size > 0) {\n return true;\n }\n continue;\n }\n\n // Check direct path matches\n if (changedPaths.has(trackedPath)) return true;\n\n // Check nested paths\n for (const changedPath of changedPaths) {\n if (\n changedPath.startsWith(trackedPath + '.') ||\n trackedPath.startsWith(changedPath + '.')\n ) {\n return true;\n }\n }\n }\n\n return false;\n }\n\n /**\n * Get statistics about subscriptions\n */\n getStats(): SubscriptionManagerStats {\n let consumerCount = 0;\n let observerCount = 0;\n\n for (const sub of this.subscriptions.values()) {\n if (sub.type === 'consumer') consumerCount++;\n else observerCount++;\n }\n\n return {\n activeSubscriptions: this.subscriptions.size,\n consumerCount,\n observerCount,\n totalNotifications: this.totalNotifications,\n trackedDependencies: this.pathToSubscriptions.size,\n };\n }\n\n /**\n * Clear all subscriptions\n */\n clear(): void {\n this.subscriptions.clear();\n this.pathToSubscriptions.clear();\n }\n\n /**\n * Get subscription by ID\n */\n getSubscription(id: string): Subscription<S> | undefined {\n return this.subscriptions.get(id);\n }\n\n /**\n * Check if there are any active subscriptions\n */\n get hasSubscriptions(): boolean {\n return this.subscriptions.size > 0;\n }\n\n /**\n * Get count of active subscriptions\n */\n get size(): number {\n return this.subscriptions.size;\n }\n\n /**\n * Clean up subscriptions with dead weak references\n */\n private cleanupDeadReferences(): void {\n if (!this.weakRefCleanupScheduled) return;\n\n const deadIds: string[] = [];\n\n for (const [id, subscription] of this.subscriptions) {\n if (subscription.weakRef && !subscription.weakRef.deref()) {\n deadIds.push(id);\n }\n }\n\n for (const id of deadIds) {\n this.unsubscribe(id);\n }\n\n this.weakRefCleanupScheduled = false;\n }\n\n /**\n * Schedule weak reference cleanup for next tick\n */\n private scheduleWeakRefCleanup(): void {\n if (this.weakRefCleanupScheduled) return;\n\n this.weakRefCleanupScheduled = true;\n queueMicrotask(() => this.cleanupDeadReferences());\n }\n}\n","/**\n * Manages batching of state updates to optimize performance\n */\nexport class BatchingManager<S> {\n private pendingUpdates: Array<{\n newState: S;\n oldState: S;\n action?: unknown;\n }> = [];\n private isBatching = false;\n\n /**\n * Execute a callback with batched updates\n */\n batchUpdates(\n callback: () => void,\n onFlush: (finalUpdate: {\n newState: S;\n oldState: S;\n action?: unknown;\n }) => void,\n ): void {\n if (this.isBatching) {\n callback();\n return;\n }\n\n this.isBatching = true;\n this.pendingUpdates = [];\n\n try {\n callback();\n\n if (this.pendingUpdates.length > 0) {\n const finalUpdate = this.pendingUpdates[this.pendingUpdates.length - 1];\n onFlush(finalUpdate);\n }\n } finally {\n this.isBatching = false;\n this.pendingUpdates = [];\n }\n }\n\n /**\n * Add an update to the batch\n */\n addUpdate(update: { newState: S; oldState: S; action?: unknown }): void {\n if (this.isBatching) {\n this.pendingUpdates.push(update);\n }\n }\n\n /**\n * Check if currently batching\n */\n get isCurrentlyBatching(): boolean {\n return this.isBatching;\n }\n}\n","import { generateUUID } from './utils/uuid';\nimport { BlocPlugin } from './plugins/types';\nimport { BlocPluginRegistry } from './plugins/BlocPluginRegistry';\nimport { SubscriptionManager } from './subscription/SubscriptionManager';\nimport {\n BlocLifecycleManager,\n BlocLifecycleState,\n StateTransitionResult,\n} from './lifecycle/BlocLifecycle';\nimport { BatchingManager } from './utils/BatchingManager';\nimport type { Blac } from './Blac';\n\nexport type BlocInstanceId = string | number | undefined;\n\ninterface BlocStaticProperties {\n isolated: boolean;\n keepAlive: boolean;\n plugins?: BlocPlugin<any, any>[];\n}\n\n/**\n * Base class for both Blocs and Cubits using unified subscription model.\n */\nexport abstract class BlocBase<S> {\n public uid = generateUUID();\n blacInstance?: Blac;\n\n static isolated = false;\n get isIsolated() {\n return this._isolated;\n }\n\n static keepAlive = false;\n get isKeepAlive() {\n return this._keepAlive;\n }\n\n public _isolated = false;\n public _id: BlocInstanceId;\n public _instanceRef?: string;\n public _name: string;\n\n /**\n * Unified subscription manager for all state notifications\n */\n public _subscriptionManager: SubscriptionManager<S>;\n\n _state: S;\n private _lifecycleManager = new BlocLifecycleManager();\n private _batchingManager = new BatchingManager<S>();\n _keepAlive = false;\n public lastUpdate?: number;\n\n _plugins = new BlocPluginRegistry<S, any>();\n\n onDispose?: () => void;\n\n /**\n * Creates a new BlocBase instance with unified subscription management\n */\n constructor(initialState: S) {\n this._state = initialState;\n this._id = this.constructor.name;\n this._name = this.constructor.name;\n\n // Initialize unified subscription system\n this._subscriptionManager = new SubscriptionManager(this as any);\n\n // Access static properties\n const Constructor = this.constructor as typeof BlocBase &\n BlocStaticProperties;\n\n this._keepAlive =\n typeof Constructor.keepAlive === 'boolean'\n ? Constructor.keepAlive\n : false;\n this._isolated =\n typeof Constructor.isolated === 'boolean' ? Constructor.isolated : false;\n\n // Initialize plugin registry\n this._plugins = new BlocPluginRegistry<S, any>();\n\n // Register static plugins\n if (Constructor.plugins && Array.isArray(Constructor.plugins)) {\n for (const plugin of Constructor.plugins) {\n this._plugins.add(plugin);\n }\n }\n\n // Attach all plugins\n this._plugins.attach(this);\n }\n\n /**\n * Returns the current state\n */\n get state(): S {\n if (this._lifecycleManager.isDisposed) {\n return this._state; // Return last known state for disposed blocs\n }\n return this._state;\n }\n\n /**\n * Subscribe to all state changes\n */\n subscribe(callback: (state: S) => void): () => void {\n return this._subscriptionManager.subscribe({\n type: 'observer',\n notify: (state) => callback(state as S),\n });\n }\n\n /**\n * Subscribe with a selector for optimized updates\n */\n subscribeWithSelector<T>(\n selector: (state: S) => T,\n callback: (value: T) => void,\n equalityFn?: (a: T, b: T) => boolean,\n ): () => void {\n return this._subscriptionManager.subscribe({\n type: 'consumer',\n selector: selector as any,\n equalityFn: equalityFn as any,\n notify: (value) => callback(value as T),\n });\n }\n\n /**\n * Subscribe with React component reference for automatic cleanup\n */\n subscribeComponent(\n componentRef: WeakRef<object>,\n callback: () => void,\n ): () => void {\n return this._subscriptionManager.subscribe({\n type: 'consumer',\n weakRef: componentRef,\n notify: callback,\n });\n }\n\n /**\n * Get current subscription count\n */\n get subscriptionCount(): number {\n return this._subscriptionManager.size;\n }\n\n /**\n * Track property access for a subscription\n */\n trackAccess(subscriptionId: string, path: string, value?: unknown): void {\n this._subscriptionManager.trackAccess(subscriptionId, path, value);\n }\n\n /**\n * Emit a new state\n */\n protected emit(newState: S, action?: unknown): void {\n this._pushState(newState, this._state, action);\n }\n\n /**\n * Internal state push method used by Bloc\n */\n _pushState(newState: S, oldState: S, action?: unknown): void {\n // Validate state emission conditions\n if (this._lifecycleManager.currentState !== BlocLifecycleState.ACTIVE) {\n this.blacInstance?.error(\n `[${this._name}:${this._id}] Attempted state update on ${this._lifecycleManager.currentState} bloc. Update ignored.`,\n );\n return;\n }\n\n if (newState === undefined) {\n return; // Silent failure for undefined states\n }\n\n this._state = newState;\n\n // Apply plugins\n const transformedState = this._plugins.transformState(\n oldState,\n newState,\n ) as S;\n this._state = transformedState;\n\n // Notify plugins of state change\n this._plugins.notifyStateChange(oldState, transformedState);\n\n // Notify system plugins of state change\n this.blacInstance?.plugins.notifyStateChanged(\n this as any,\n oldState,\n transformedState,\n );\n\n // Handle batching\n if (this._batchingManager.isCurrentlyBatching) {\n this._batchingManager.addUpdate({\n newState: transformedState,\n oldState,\n action,\n });\n return;\n }\n\n // Notify all subscriptions\n this._subscriptionManager.notify(transformedState, oldState, action);\n this.lastUpdate = Date.now();\n }\n\n _batchUpdates(callback: () => void): void {\n this._batchingManager.batchUpdates(callback, (finalUpdate) => {\n this._subscriptionManager.notify(\n finalUpdate.newState,\n finalUpdate.oldState,\n finalUpdate.action,\n );\n });\n }\n\n /**\n * Add a plugin\n */\n addPlugin(plugin: BlocPlugin<S, any>): void {\n this._plugins.add(plugin);\n\n // If plugins are already attached (bloc is active), attach the new plugin\n if ((this._plugins as any).attached && plugin.onAttach) {\n try {\n plugin.onAttach(this);\n } catch (error) {\n console.error(`Plugin '${plugin.name}' error in onAttach:`, error);\n }\n }\n }\n\n /**\n * Remove a plugin\n */\n removePlugin(plugin: BlocPlugin<S, any>): void {\n this._plugins.remove(plugin.name);\n }\n\n /**\n * Get all plugins\n */\n get plugins(): ReadonlyArray<BlocPlugin<S, any>> {\n return this._plugins.getAll();\n }\n\n /**\n * Disposal management\n */\n get isDisposed(): boolean {\n return this._lifecycleManager.isDisposed;\n }\n\n /**\n * Atomic state transition for disposal\n */\n _atomicStateTransition(\n expectedState: BlocLifecycleState,\n newState: BlocLifecycleState,\n ): StateTransitionResult {\n return this._lifecycleManager.atomicStateTransition(\n expectedState,\n newState,\n );\n }\n\n /**\n * Dispose the bloc and clean up resources\n */\n async dispose(): Promise<void> {\n const transitionResult = this._lifecycleManager.atomicStateTransition(\n BlocLifecycleState.ACTIVE,\n BlocLifecycleState.DISPOSING,\n );\n\n if (!transitionResult.success) {\n if (\n this._lifecycleManager.currentState ===\n BlocLifecycleState.DISPOSAL_REQUESTED\n ) {\n this._lifecycleManager.atomicStateTransition(\n BlocLifecycleState.DISPOSAL_REQUESTED,\n BlocLifecycleState.DISPOSING,\n );\n } else {\n return;\n }\n }\n\n try {\n // Clear subscriptions\n this._subscriptionManager.clear();\n\n // Call disposal hook\n if (this.onDispose) {\n this.onDispose();\n }\n\n // Notify plugins of disposal\n for (const plugin of this._plugins.getAll()) {\n try {\n if ('onDispose' in plugin && typeof plugin.onDispose === 'function') {\n plugin.onDispose(this as any);\n }\n } catch (error) {\n console.error('Plugin disposal error:', error);\n }\n }\n\n // Call disposal handler\n const handler = this._lifecycleManager.getDisposalHandler();\n if (handler) {\n handler(this as any);\n }\n } finally {\n this._lifecycleManager.atomicStateTransition(\n BlocLifecycleState.DISPOSING,\n BlocLifecycleState.DISPOSED,\n );\n }\n }\n\n /**\n * Schedule disposal when no subscriptions remain\n */\n _scheduleDisposal(): void {\n const shouldDispose =\n this._subscriptionManager.size === 0 && !this._keepAlive;\n\n if (!shouldDispose) {\n return;\n }\n\n this._lifecycleManager.scheduleDisposal(\n 16,\n () => this._subscriptionManager.size === 0 && !this._keepAlive,\n () => this.dispose(),\n );\n }\n\n /**\n * Set disposal handler\n */\n setDisposalHandler(handler: (bloc: BlocBase<unknown>) => void): void {\n this._lifecycleManager.setDisposalHandler(\n handler as (bloc: unknown) => void,\n );\n }\n\n /**\n * Check if disposal should be scheduled (called by subscription manager)\n */\n checkDisposal(): void {\n if (\n this._subscriptionManager.size === 0 &&\n !this._keepAlive &&\n this._lifecycleManager.currentState === BlocLifecycleState.ACTIVE\n ) {\n this._scheduleDisposal();\n }\n }\n\n /**\n * Cancel disposal if bloc is in disposal_requested state\n */\n _cancelDisposalIfRequested(): void {\n this.blacInstance?.log(\n `[${this._name}:${this._id}] _cancelDisposalIfRequested called. Current state: ${this._lifecycleManager.currentState}`,\n );\n\n const success = this._lifecycleManager.cancelDisposal();\n\n if (success) {\n this.blacInstance?.log(\n `[${this._name}:${this._id}] Disposal cancelled - new subscription added`,\n );\n } else if (\n this._lifecycleManager.currentState ===\n BlocLifecycleState.DISPOSAL_REQUESTED\n ) {\n this.blacInstance?.warn(\n `[${this._name}:${this._id}] Failed to cancel disposal. Current state: ${this._lifecycleManager.currentState}`,\n );\n } else if (this._lifecycleManager.isDisposed) {\n this.blacInstance?.error(\n `[${this._name}:${this._id}] Cannot cancel disposal - bloc is already disposed`,\n );\n }\n }\n}\n","import { Blac } from './Blac';\nimport { BlocBase } from './BlocBase';\nimport { BlocEventConstraint } from './types';\n\nexport abstract class Bloc<\n S, // State type\n A extends BlocEventConstraint = BlocEventConstraint, // Base Action/Event type with proper constraints\n> extends BlocBase<S> {\n readonly eventHandlers: Map<\n new (...args: any[]) => A,\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 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 Blac.warn(\n `[Bloc ${this._name}:${String(this._id)}] Handler for event '${eventConstructor.name}' already registered. It will be overwritten.`,\n );\n }\n this.eventHandlers.set(\n eventConstructor,\n handler as (\n event: A,\n emit: (newState: S) => void,\n ) => 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 // Transform event through plugins\n let transformedAction: A | null = action;\n try {\n transformedAction = (this._plugins as any).transformEvent(action);\n } catch (error) {\n console.error('Error transforming event:', error);\n // Continue with original event if transformation fails\n }\n\n // If event was cancelled by plugin, don't process it\n if (transformedAction === null) {\n return;\n }\n\n // Notify bloc plugins of event\n try {\n (this._plugins as any).notifyEvent(transformedAction);\n } catch (error) {\n console.error('Error notifying plugins of event:', error);\n }\n\n // Notify system plugins of event\n Blac.instance.plugins.notifyEventAdded(this as any, transformedAction);\n\n this._eventQueue.push(transformedAction);\n\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 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 const eventConstructor = action.constructor as new (...args: any[]) => A;\n const handler = this.eventHandlers.get(eventConstructor);\n\n if (handler) {\n const emit = (newState: S): void => {\n const previousState = this.state; // State just before this specific emission\n this._pushState(newState, previousState, action);\n };\n\n try {\n await handler(action, emit);\n } catch (error) {\n const constructorName =\n (action.constructor as { name?: string }).name ||\n '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:',\n errorContext,\n );\n\n // Notify plugins of the error\n if (error instanceof Error) {\n try {\n this._plugins.notifyError(error, {\n phase: 'event-processing',\n operation: 'handler',\n metadata: { event: action },\n });\n\n Blac.instance.plugins.notifyError(error, this as any, {\n phase: 'event-processing',\n operation: 'handler',\n metadata: { event: action },\n });\n } catch (pluginError) {\n console.error('Error notifying plugins:', pluginError);\n }\n }\n\n if (error instanceof Error && error.name === 'CriticalError') {\n throw error;\n }\n }\n } else {\n const constructorName =\n (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:',\n Array.from(this.eventHandlers.keys()).map((k) => k.name),\n 'Action was:',\n 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 */\nexport abstract class Cubit<S> extends BlocBase<S> {\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","/**\n * Event fired when props are updated on a Bloc or Cubit instance.\n * This is primarily used internally by the framework to notify\n * about prop changes in React components.\n * @template P - The type of props being updated\n */\nexport class PropsUpdated<P = any> {\n constructor(public readonly props: P) {}\n}\n","/**\n * Performs a shallow equality comparison between two values.\n * For objects, it checks if all top-level properties are equal using Object.is.\n * @param a First value to compare\n * @param b Second value to compare\n * @returns true if values are shallowly equal, false otherwise\n */\nexport function shallowEqual(a: any, b: any): boolean {\n if (Object.is(a, b)) {\n return true;\n }\n\n if (\n typeof a !== 'object' ||\n a === null ||\n typeof b !== 'object' ||\n b === null\n ) {\n return false;\n }\n\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n\n if (keysA.length !== keysB.length) {\n return false;\n }\n\n for (let i = 0; i < keysA.length; i++) {\n const key = keysA[i];\n if (\n !Object.prototype.hasOwnProperty.call(b, key) ||\n !Object.is(a[key], b[key])\n ) {\n return false;\n }\n }\n\n return true;\n}\n","/**\n * Generates a deterministic instance ID from static props by extracting primitive values\n *\n * Rules:\n * 1. Only considers primitive types: string, number, boolean, null, undefined\n * 2. Ignores complex types: objects, arrays, functions, symbols\n * 3. Sorts keys alphabetically for deterministic output\n * 4. Returns undefined if no primitives found (caller should use default ID)\n */\nexport function generateInstanceIdFromProps(\n props: unknown,\n): string | undefined {\n if (!props || typeof props !== 'object') {\n return undefined;\n }\n\n const primitives: Array<[string, unknown]> = [];\n\n // Extract primitive values\n for (const [key, value] of Object.entries(props)) {\n const type = typeof value;\n if (\n type === 'string' ||\n type === 'number' ||\n type === 'boolean' ||\n value === null ||\n value === undefined\n ) {\n primitives.push([key, value]);\n }\n }\n\n // No primitives found\n if (primitives.length === 0) {\n return undefined;\n }\n\n // Sort by key for deterministic output\n primitives.sort(([a], [b]) => a.localeCompare(b));\n\n // Create instance ID\n const parts: string[] = [];\n for (const [key, value] of primitives) {\n if (value === null) {\n parts.push(`${key}:null`);\n } else if (value === undefined) {\n parts.push(`${key}:undefined`);\n } else {\n parts.push(`${key}:${String(value)}`);\n }\n }\n\n return parts.join('|');\n}\n","import { Blac } from '../Blac';\nimport { BlocBase } from '../BlocBase';\n\nexport interface RerenderInfo {\n componentName: string;\n blocName: string;\n blocId: string;\n renderCount: number;\n reason: RerenderReason;\n timestamp: number;\n duration?: number;\n stackTrace?: string;\n}\n\nexport interface RerenderReason {\n type:\n | 'state-change'\n | 'dependency-change'\n | 'mount'\n | 'props-change'\n | 'unknown';\n changedPaths?: string[];\n oldValues?: Record<string, any>;\n newValues?: Record<string, any>;\n dependencies?: string[];\n description?: string;\n}\n\n/**\n * Utility class for logging component rerenders with detailed debugging information\n */\nexport class RerenderLogger {\n private static componentRenderCounts = new Map<string, number>();\n private static lastRenderTimestamps = new Map<string, number>();\n private static groupedLogs = new Map<string, RerenderInfo[]>();\n private static groupTimeouts = new Map<string, NodeJS.Timeout>();\n\n /**\n * Log a component rerender with detailed information\n */\n static logRerender(info: RerenderInfo): void {\n // RerenderLogger is now controlled by the RenderLoggingPlugin\n // This method is called by the plugin which already handles configuration\n const config = (Blac as any)._config?.rerenderLogging;\n if (!config) return;\n\n // Parse config\n const loggingConfig = this.parseConfig(config);\n if (!loggingConfig.enabled) return;\n\n // Apply filter if provided\n if (\n loggingConfig.filter &&\n !loggingConfig.filter({\n componentName: info.componentName,\n blocName: info.blocName,\n })\n ) {\n return;\n }\n\n // Track render count\n const key = `${info.componentName}-${info.blocId}`;\n const currentCount = this.componentRenderCounts.get(key) || 0;\n this.componentRenderCounts.set(key, currentCount + 1);\n info.renderCount = currentCount + 1;\n\n // Calculate duration if possible\n const lastTimestamp = this.lastRenderTimestamps.get(key);\n if (lastTimestamp) {\n info.duration = info.timestamp - lastTimestamp;\n }\n this.lastRenderTimestamps.set(key, info.timestamp);\n\n // Add stack trace if requested\n if (loggingConfig.includeStackTrace && loggingConfig.level === 'detailed') {\n info.stackTrace = new Error().stack;\n }\n\n // Handle grouping\n if (loggingConfig.groupRerenders) {\n this.logGrouped(info, loggingConfig);\n } else {\n this.logImmediate(info, loggingConfig);\n }\n }\n\n /**\n * Parse the logging configuration\n */\n private static parseConfig(config: any) {\n if (config === true) {\n return { enabled: true, level: 'normal' as const };\n }\n if (typeof config === 'string') {\n return {\n enabled: true,\n level:\n config === 'minimal' ? ('minimal' as const) : ('detailed' as const),\n };\n }\n return {\n enabled: config.enabled,\n level: config.level || ('normal' as const),\n filter: config.filter,\n includeStackTrace: config.includeStackTrace,\n groupRerenders: config.groupRerenders,\n };\n }\n\n /**\n * Log immediately without grouping\n */\n private static logImmediate(\n info: RerenderInfo,\n config: ReturnType<typeof RerenderLogger.parseConfig>,\n ): void {\n const message = this.formatMessage(info, config.level!);\n\n if (config.level === 'detailed') {\n console.group(message.header);\n if (message.details) console.log(message.details);\n if (message.values) console.table(message.values);\n if (info.stackTrace) console.log('Stack trace:', info.stackTrace);\n console.groupEnd();\n } else {\n console.log(message.header, message.details || '');\n }\n }\n\n /**\n * Log with grouping (batch multiple rerenders)\n */\n private static logGrouped(\n info: RerenderInfo,\n config: ReturnType<typeof RerenderLogger.parseConfig>,\n ): void {\n const groupKey = `${info.componentName}-${info.blocId}`;\n\n // Clear existing timeout\n const existingTimeout = this.groupTimeouts.get(groupKey);\n if (existingTimeout) {\n clearTimeout(existingTimeout);\n }\n\n // Add to group\n const group = this.groupedLogs.get(groupKey) || [];\n group.push(info);\n this.groupedLogs.set(groupKey, group);\n\n // Set new timeout\n const timeout = setTimeout(() => {\n const logs = this.groupedLogs.get(groupKey) || [];\n this.groupedLogs.delete(groupKey);\n this.groupTimeouts.delete(groupKey);\n\n if (logs.length === 1) {\n this.logImmediate(logs[0], config);\n } else {\n console.group(\n `🔄 ${info.componentName} rendered ${logs.length} times (${info.blocName})`,\n );\n logs.forEach((log, index) => {\n const message = this.formatMessage(log, config.level!);\n console.log(` ${index + 1}. ${message.details || message.header}`);\n });\n console.groupEnd();\n }\n }, 50); // 50ms debounce\n\n this.groupTimeouts.set(groupKey, timeout);\n }\n\n /**\n * Format the log message based on level\n */\n private static formatMessage(\n info: RerenderInfo,\n level: 'minimal' | 'normal' | 'detailed',\n ) {\n const emoji = this.getReasonEmoji(info.reason.type);\n\n if (level === 'minimal') {\n return {\n header: `${emoji} ${info.componentName} #${info.renderCount}`,\n details: null,\n values: null,\n };\n }\n\n const header = `${emoji} ${info.componentName} rerender #${info.renderCount} (${info.blocName})`;\n\n let details = `Reason: ${info.reason.description || info.reason.type}`;\n\n if (info.duration !== undefined) {\n details += ` | Time since last: ${info.duration}ms`;\n }\n\n if (\n level === 'normal' &&\n info.reason.changedPaths &&\n info.reason.changedPaths.length > 0\n ) {\n details += ` | Changed: ${info.reason.changedPaths.join(', ')}`;\n }\n\n let values: Record<string, { old: any; new: any }> | null = null;\n if (\n level === 'detailed' &&\n info.reason.changedPaths &&\n info.reason.changedPaths.length > 0\n ) {\n values = {};\n info.reason.changedPaths.forEach((path) => {\n values![path] = {\n old: info.reason.oldValues?.[path],\n new: info.reason.newValues?.[path],\n };\n });\n\n // If we have values to show in detailed mode, ensure they're not empty\n if (Object.keys(values).length === 0) {\n values = null;\n }\n }\n\n return { header, details, values };\n }\n\n /**\n * Get emoji for reason type\n */\n private static getReasonEmoji(type: RerenderReason['type']): string {\n switch (type) {\n case 'state-change':\n return '📊';\n case 'dependency-change':\n return '🔗';\n case 'mount':\n return '🚀';\n case 'props-change':\n return '📦';\n default:\n return '🔄';\n }\n }\n\n /**\n * Clear all tracking data\n */\n static clear(): void {\n this.componentRenderCounts.clear();\n this.lastRenderTimestamps.clear();\n this.groupedLogs.clear();\n this.groupTimeouts.forEach((timeout) => clearTimeout(timeout));\n this.groupTimeouts.clear();\n }\n\n /**\n * Get render count for a component\n */\n static getRenderCount(componentName: string, blocId: string): number {\n return this.componentRenderCounts.get(`${componentName}-${blocId}`) || 0;\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(\n new Error(\n `Timeout waiting for state matching predicate after ${timeout}ms`,\n ),\n );\n }, timeout);\n\n const unsubscribe = bloc.subscribe((newState: S) => {\n if (predicate(newState)) {\n clearTimeout(timeoutId);\n unsubscribe();\n resolve(newState);\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(\n new Error(\n `Timeout waiting for states. Expected: ${JSON.stringify(expectedStates)}, ` +\n `Received: ${JSON.stringify(receivedStates)}`,\n ),\n );\n }, timeout);\n\n const unsubscribe = bloc.subscribe((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(\n new Error(\n `State mismatch at index ${i}. Expected: ${JSON.stringify(expected)}, ` +\n `Received: ${JSON.stringify(received)}`,\n ),\n );\n return;\n }\n }\n\n resolve();\n }\n });\n });\n }\n}\n\n/**\n * Mock Bloc for testing\n */\nexport class MockBloc<\n S,\n A extends BlocEventConstraint = BlocEventConstraint,\n> extends Bloc<S, A> {\n private mockHandlers = new Map<\n string,\n (event: A, emit: (newState: S) => void) => void | Promise<void>\n >();\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 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}\n","import { BlocBase } from '../BlocBase';\n\ninterface ConsumerTracker {\n trackAccess: (\n consumerRef: object,\n type: 'state' | 'class',\n path: string,\n value?: any,\n ) => void;\n}\n\n// Minimal cache for backward compatibility\nconst proxyCache = new WeakMap<object, WeakMap<object, any>>();\n\n// Minimal stats for backward compatibility\nconst stats = {\n stateProxiesCreated: 0,\n classProxiesCreated: 0,\n cacheHits: 0,\n cacheMisses: 0,\n totalProxiesCreated: 0,\n};\n\n/**\n * Creates a proxy for state objects that tracks property access\n */\nexport const createStateProxy = <T extends object>(\n target: T,\n consumerRef: object,\n consumerTracker: ConsumerTracker,\n path = '',\n): T => {\n if (\n !consumerRef ||\n !consumerTracker ||\n typeof target !== 'object' ||\n target === null\n ) {\n return target;\n }\n\n // Check cache for backward compatibility with tests\n if (!path) {\n // Only cache root objects\n let refCache = proxyCache.get(target);\n if (!refCache) {\n refCache = new WeakMap();\n proxyCache.set(target, refCache);\n }\n\n const cached = refCache.get(consumerRef);\n if (cached) {\n stats.cacheHits++;\n return cached;\n }\n stats.cacheMisses++;\n }\n\n const proxy = new Proxy(target, {\n get(obj: T, prop: string | symbol): any {\n // Handle symbols and special properties\n if (typeof prop === 'symbol' || prop === 'constructor') {\n return Reflect.get(obj, prop);\n }\n\n const fullPath = path ? `${path}.${prop}` : prop;\n const value = Reflect.get(obj, prop);\n const isObject = value && typeof value === 'object';\n\n // Track access with value for primitives\n consumerTracker.trackAccess(\n consumerRef,\n 'state',\n fullPath,\n isObject ? undefined : value,\n );\n\n // Recursively proxy nested objects and arrays\n if (\n isObject &&\n (Array.isArray(value) ||\n Object.getPrototypeOf(value) === Object.prototype)\n ) {\n return createStateProxy(value, consumerRef, consumerTracker, fullPath);\n }\n\n return value;\n },\n\n set: () => false, // State should be immutable\n deleteProperty: () => false, // State properties should not be deleted\n });\n\n // Cache root proxies\n if (!path) {\n const refCache = proxyCache.get(target)!;\n refCache.set(consumerRef, proxy);\n stats.stateProxiesCreated++;\n stats.totalProxiesCreated++;\n }\n\n return proxy;\n};\n\n/**\n * Creates a proxy for bloc instances that tracks getter access\n */\nexport const createBlocProxy = <T extends object>(\n target: T,\n consumerRef: object,\n consumerTracker: ConsumerTracker,\n): T => {\n if (!consumerRef || !consumerTracker) {\n return target;\n }\n\n // Check cache\n let refCache = proxyCache.get(target);\n if (!refCache) {\n refCache = new WeakMap();\n proxyCache.set(target, refCache);\n }\n\n const cached = refCache.get(consumerRef);\n if (cached) {\n stats.cacheHits++;\n return cached;\n }\n stats.cacheMisses++;\n\n const proxy = new Proxy(target, {\n get(obj: T, prop: string | symbol): any {\n const value = Reflect.get(obj, prop);\n\n // Only track getters, not methods or regular properties\n const descriptor = findPropertyDescriptor(obj, prop);\n if (descriptor?.get) {\n // Track getter access with value for primitives\n const isPrimitive = value !== null && typeof value !== 'object';\n consumerTracker.trackAccess(\n consumerRef,\n 'class',\n String(prop),\n isPrimitive ? value : undefined,\n );\n }\n\n return value;\n },\n });\n\n // Cache proxy\n refCache.set(consumerRef, proxy);\n stats.classProxiesCreated++;\n stats.totalProxiesCreated++;\n\n return proxy;\n};\n\n/**\n * Helper to find property descriptor in prototype chain\n */\nconst findPropertyDescriptor = (\n obj: any,\n prop: string | symbol,\n maxDepth = 10,\n): PropertyDescriptor | undefined => {\n let current = obj;\n let depth = 0;\n\n while (current && depth < maxDepth) {\n const descriptor = Object.getOwnPropertyDescriptor(current, prop);\n if (descriptor) return descriptor;\n\n current = Object.getPrototypeOf(current);\n depth++;\n }\n\n return undefined;\n};\n\n// Export compatibility functions for easier migration\nexport const ProxyFactory = {\n createStateProxy: (options: {\n target: any;\n consumerRef: object;\n consumerTracker: ConsumerTracker;\n path?: string;\n }) =>\n createStateProxy(\n options.target,\n options.consumerRef,\n options.consumerTracker,\n options.path,\n ),\n\n createClassProxy: (options: {\n target: any;\n consumerRef: object;\n consumerTracker: ConsumerTracker;\n }) =>\n createBlocProxy(\n options.target,\n options.consumerRef,\n options.consumerTracker,\n ),\n\n getProxyState: <B extends BlocBase<any>>(options: {\n state: any;\n consumerRef: object;\n consumerTracker: ConsumerTracker;\n }) =>\n createStateProxy(\n options.state,\n options.consumerRef,\n options.consumerTracker,\n ),\n\n getProxyBlocInstance: <B extends BlocBase<any>>(options: {\n blocInstance: B;\n consumerRef: object;\n consumerTracker: ConsumerTracker;\n }) =>\n createBlocProxy(\n options.blocInstance,\n options.consumerRef,\n options.consumerTracker,\n ),\n\n // Compatibility functions that return expected structure\n getStats: () => ({\n ...stats,\n propertyAccesses: 0,\n nestedProxiesCreated: 0,\n cacheEfficiency:\n stats.cacheHits + stats.cacheMisses > 0\n ? `${((stats.cacheHits / (stats.cacheHits + stats.cacheMisses)) * 100).toFixed(1)}%`\n : 'N/A',\n lifetime: '0ms',\n proxiesPerSecond: 'N/A',\n }),\n resetStats: () => {\n stats.stateProxiesCreated = 0;\n stats.classProxiesCreated = 0;\n stats.cacheHits = 0;\n stats.cacheMisses = 0;\n stats.totalProxiesCreated = 0;\n },\n};\n","import { Blac } from '../Blac';\nimport { BlocBase } from '../BlocBase';\nimport { BlocConstructor, BlocState } from '../types';\nimport { generateUUID } from '../utils/uuid';\nimport { generateInstanceIdFromProps } from '../utils/generateInstanceId';\nimport { ProxyFactory } from './ProxyFactory';\n\nexport interface AdapterOptions<B extends BlocBase<any>> {\n instanceId?: string;\n dependencies?: (bloc: B) => unknown[];\n staticProps?: any;\n onMount?: (bloc: B) => void;\n onUnmount?: (bloc: B) => void;\n}\n\n/**\n * BlacAdapter orchestrates the connection between Bloc instances and React components.\n * It manages dependency tracking, lifecycle hooks, and proxy creation.\n */\nexport class BlacAdapter<B extends BlocConstructor<BlocBase<any>>> {\n public readonly id = `adapter-${generateUUID()}`;\n public readonly blocConstructor: B;\n public readonly componentRef: { current: object } = { current: {} };\n public blocInstance!: InstanceType<B>;\n\n unmountTime: number = 0;\n mountTime: number = 0;\n\n // Subscription management\n private subscriptionId?: string;\n private unsubscribe?: () => void;\n\n // Dependency tracking\n private dependencyValues?: unknown[];\n private isUsingDependencies: boolean = false;\n private trackedPaths = new Set<string>();\n private pendingTrackedPaths = new Set<string>(); // Paths tracked before subscription exists\n\n // Proxy caching\n private cachedStateProxy?: BlocState<InstanceType<B>>;\n private cachedBlocProxy?: InstanceType<B>;\n private lastProxiedState?: BlocState<InstanceType<B>>;\n\n // Lifecycle state\n private hasMounted = false;\n private mountCount = 0;\n\n // Rerender tracking\n private lastState?: BlocState<InstanceType<B>>;\n private lastDependencyValues?: unknown[];\n private componentName?: string;\n private renderCount = 0;\n private lastDependenciesFn?: (bloc: InstanceType<B>) => unknown[];\n\n options?: AdapterOptions<InstanceType<B>>;\n\n constructor(\n instanceProps: { componentRef: { current: object }; blocConstructor: B },\n options?: typeof this.options,\n ) {\n this.options = options;\n this.blocConstructor = instanceProps.blocConstructor;\n this.componentRef = instanceProps.componentRef;\n this.isUsingDependencies = !!options?.dependencies;\n\n // Initialize bloc instance\n this.updateBlocInstance();\n\n // Initialize dependency values if using dependencies\n if (this.isUsingDependencies && options?.dependencies) {\n this.dependencyValues = options.dependencies(this.blocInstance);\n }\n\n // Notify plugins\n const metadata = this.getAdapterMetadata();\n Blac.getInstance().plugins.notifyAdapterCreated(this, metadata);\n }\n\n trackAccess(\n consumerRef: object,\n type: 'state' | 'class',\n path: string,\n value?: any,\n ): void {\n const fullPath = type === 'class' ? `_class.${path}` : path;\n this.trackedPaths.add(fullPath);\n\n if (this.subscriptionId) {\n this.blocInstance.trackAccess(this.subscriptionId, fullPath, value);\n } else {\n // No subscription ID yet - store for later\n this.pendingTrackedPaths.add(fullPath);\n if ((Blac.config as any).logLevel === 'debug') {\n Blac.log(`[BlacAdapter] trackAccess storing pending path: ${path}`);\n }\n }\n }\n\n updateBlocInstance(): InstanceType<B> {\n // Determine the instance ID\n let instanceId = this.options?.instanceId;\n\n // If no explicit instanceId provided but staticProps exist, generate from them\n if (!instanceId && this.options?.staticProps) {\n const generatedId = generateInstanceIdFromProps(this.options.staticProps);\n if (generatedId) {\n instanceId = generatedId;\n }\n }\n\n this.blocInstance = Blac.instance.getBloc<B>(this.blocConstructor, {\n constructorParams: this.options?.staticProps,\n id: instanceId,\n instanceRef: this.id,\n });\n return this.blocInstance;\n }\n\n createSubscription = (options: { onChange: () => void }) => {\n // If using manual dependencies, create a selector-based subscription\n if (this.isUsingDependencies && this.options?.dependencies) {\n this.unsubscribe = this.blocInstance.subscribeWithSelector(\n (_state) => this.options!.dependencies!(this.blocInstance),\n (newValues) => {\n const hasChanged = this.hasDependencyValuesChanged(\n this.dependencyValues,\n newValues as unknown[],\n );\n\n if (hasChanged) {\n this.dependencyValues = newValues as unknown[];\n options.onChange();\n }\n },\n );\n } else {\n // Create a component subscription with weak reference\n const weakRef = new WeakRef(this.componentRef.current);\n this.unsubscribe = this.blocInstance.subscribeComponent(\n weakRef,\n options.onChange,\n );\n\n // Get the subscription ID for tracking\n const subscriptions = (this.blocInstance._subscriptionManager as any)\n .subscriptions as Map<string, any>;\n this.subscriptionId = Array.from(subscriptions.keys()).pop();\n\n // Apply any pending tracked paths\n if (this.subscriptionId && this.pendingTrackedPaths.size > 0) {\n for (const path of this.pendingTrackedPaths) {\n this.blocInstance.trackAccess(this.subscriptionId, path);\n }\n this.pendingTrackedPaths.clear();\n }\n }\n\n // Don't call onChange initially - let React handle the initial render\n\n return () => {\n if (this.unsubscribe) {\n this.unsubscribe();\n this.unsubscribe = undefined;\n this.subscriptionId = undefined;\n }\n };\n };\n\n hasDependencyValuesChanged = (\n oldValues: unknown[] | undefined,\n newValues: unknown[],\n ): boolean => {\n if (!oldValues) return true;\n if (oldValues.length !== newValues.length) return true;\n\n for (let i = 0; i < oldValues.length; i++) {\n if (!Object.is(oldValues[i], newValues[i])) {\n return true;\n }\n }\n\n return false;\n };\n\n getStateProxy = (): BlocState<InstanceType<B>> => {\n // If using manual dependencies or proxy tracking is disabled, return raw state\n if (this.isUsingDependencies || !Blac.config.proxyDependencyTracking) {\n return this.blocInstance.state;\n }\n\n // Return cached proxy if state hasn't changed\n const currentState = this.blocInstance.state;\n if (this.cachedStateProxy && this.lastProxiedState === currentState) {\n return this.cachedStateProxy;\n }\n\n // Create new proxy for new state\n this.lastProxiedState = currentState;\n this.cachedStateProxy = this.createStateProxy({ target: currentState });\n return this.cachedStateProxy!;\n };\n\n getBlocProxy = (): InstanceType<B> => {\n // If using manual dependencies or proxy tracking is disabled, return raw bloc\n if (this.isUsingDependencies || !Blac.config.proxyDependencyTracking) {\n return this.blocInstance;\n }\n\n // Return cached proxy if bloc instance hasn't changed\n if (this.cachedBlocProxy) {\n return this.cachedBlocProxy;\n }\n\n // Create and cache proxy\n this.cachedBlocProxy = this.createClassProxy({ target: this.blocInstance });\n return this.cachedBlocProxy;\n };\n\n createStateProxy = <T extends object>(props: { target: T }): T => {\n return ProxyFactory.createStateProxy({\n target: props.target,\n consumerRef: this.componentRef.current,\n consumerTracker: this as any,\n });\n };\n\n createClassProxy = <T extends object>(props: { target: T }): T => {\n return ProxyFactory.createClassProxy({\n target: props.target,\n consumerRef: this.componentRef.current,\n consumerTracker: this as any,\n });\n };\n\n // Lifecycle methods\n mount = () => {\n this.hasMounted = true;\n this.mountCount++;\n this.mountTime = Date.now();\n\n // Call onMount hook\n if (this.options?.onMount) {\n this.options.onMount(this.blocInstance);\n }\n\n // Refresh dependencies if using manual tracking\n if (this.isUsingDependencies && this.options?.dependencies) {\n this.dependencyValues = this.options.dependencies(this.blocInstance);\n }\n\n // Notify plugins\n const metadata = this.getAdapterMetadata();\n Blac.getInstance().plugins.notifyAdapterMount(this, metadata);\n };\n\n unmount = () => {\n this.unmountTime = Date.now();\n\n // Cancel subscription\n if (this.unsubscribe) {\n this.unsubscribe();\n this.unsubscribe = undefined;\n this.subscriptionId = undefined;\n }\n\n // Call onUnmount hook\n if (this.options?.onUnmount) {\n try {\n this.options.onUnmount(this.blocInstance);\n } catch (error) {\n console.error('Error in onUnmount hook:', error);\n }\n }\n\n // Notify plugins\n const metadata = this.getAdapterMetadata();\n Blac.getInstance().plugins.notifyAdapterUnmount(this, metadata);\n };\n\n // Reset tracking for next render\n resetTracking(): void {\n // Clear tracked paths from previous render\n this.trackedPaths.clear();\n this.pendingTrackedPaths.clear();\n\n // Clear subscription dependencies to track only current render\n if (this.subscriptionId) {\n const subscription = (\n this.blocInstance._subscriptionManager as any\n ).subscriptions.get(this.subscriptionId);\n if (subscription && subscription.dependencies) {\n // Clear old dependencies - we'll track new ones in this render\n subscription.dependencies.clear();\n }\n }\n }\n\n // Set component name for rerender logging\n setComponentName(name: string): void {\n this.componentName = name;\n }\n\n // Notify plugins about render\n notifyRender(): void {\n this.renderCount++;\n\n // Update dependency values if using manual tracking\n if (this.isUsingDependencies && this.options?.dependencies) {\n this.lastDependencyValues = this.dependencyValues;\n this.dependencyValues = this.options.dependencies(this.blocInstance);\n }\n\n const metadata = this.getAdapterMetadata();\n Blac.getInstance().plugins.notifyAdapterRender(this, metadata);\n }\n\n // Get adapter metadata for plugins\n private getAdapterMetadata(): any {\n return {\n componentName: this.componentName,\n blocInstance: this.blocInstance,\n renderCount: this.renderCount,\n trackedPaths: Array.from(this.trackedPaths),\n isUsingDependencies: this.isUsingDependencies,\n lastState: this.lastState,\n lastDependencyValues: this.lastDependencyValues,\n currentDependencyValues: this.dependencyValues,\n };\n }\n\n // Get value at a dot-notated path\n private getValueAtPath(obj: any, path: string): any {\n const parts = path.split('.');\n let current = obj;\n\n for (const part of parts) {\n if (current == null) return undefined;\n current = current[part];\n }\n\n return current;\n }\n\n // Get paths that changed between states\n private getStateChangedPaths(oldState: any, newState: any): string[] {\n const changedPaths: string[] = [];\n\n // Only check tracked paths if we have any\n if (this.trackedPaths.size > 0) {\n for (const path of this.trackedPaths) {\n // Skip class property paths\n if (path.startsWith('_class.')) continue;\n\n const oldValue = this.getValueAtPath(oldState, path);\n const newValue = this.getValueAtPath(newState, path);\n\n if (!Object.is(oldValue, newValue)) {\n changedPaths.push(path);\n }\n }\n } else {\n // No tracked paths - do deep comparison to find what changed\n if (oldState !== newState) {\n const deepChanges = this.getDeepChangedPaths(oldState, newState);\n if (deepChanges.length > 0) {\n return deepChanges;\n }\n changedPaths.push('(entire state)');\n }\n }\n\n return changedPaths;\n }\n\n // Deep comparison to find all changed paths\n private getDeepChangedPaths(\n oldObj: any,\n newObj: any,\n basePath: string = '',\n ): string[] {\n const changes: string[] = [];\n\n // Handle null/undefined\n if (oldObj === newObj) return changes;\n if (oldObj == null || newObj == null) {\n changes.push(basePath || '(root)');\n return changes;\n }\n\n // Handle primitives\n if (typeof oldObj !== 'object' || typeof newObj !== 'object') {\n if (oldObj !== newObj) {\n changes.push(basePath || '(root)');\n }\n return changes;\n }\n\n // Handle arrays\n if (Array.isArray(oldObj) || Array.isArray(newObj)) {\n if (\n !Array.isArray(oldObj) ||\n !Array.isArray(newObj) ||\n oldObj.length !== newObj.length\n ) {\n changes.push(basePath || '(root)');\n return changes;\n }\n // Compare array elements\n for (let i = 0; i < oldObj.length; i++) {\n const elementPath = basePath ? `${basePath}[${i}]` : `[${i}]`;\n changes.push(\n ...this.getDeepChangedPaths(oldObj[i], newObj[i], elementPath),\n );\n }\n return changes;\n }\n\n // Handle objects\n const allKeys = new Set([...Object.keys(oldObj), ...Object.keys(newObj)]);\n for (const key of allKeys) {\n const keyPath = basePath ? `${basePath}.${key}` : key;\n\n if (!(key in oldObj)) {\n changes.push(`${keyPath} (added)`);\n } else if (!(key in newObj)) {\n changes.push(`${keyPath} (removed)`);\n } else {\n const oldVal = oldObj[key];\n const newVal = newObj[key];\n\n // Use Object.is for comparison\n if (!Object.is(oldVal, newVal)) {\n // For primitives and different object references, record the change\n if (\n typeof oldVal !== 'object' ||\n typeof newVal !== 'object' ||\n oldVal === null ||\n newVal === null\n ) {\n changes.push(keyPath);\n } else {\n // For objects/arrays, recurse deeper\n const deeperChanges = this.getDeepChangedPaths(\n oldVal,\n newVal,\n keyPath,\n );\n if (deeperChanges.length > 0) {\n changes.push(...deeperChanges);\n } else {\n // Objects are different references but have same content\n changes.push(keyPath);\n }\n }\n }\n }\n }\n\n return changes;\n }\n\n // Get last rerender reason\n getLastRerenderReason(): any {\n // This method is deprecated - render reason is now handled by the RenderLoggingPlugin\n return undefined;\n }\n}\n"],"names":["BlocLifecycleState","BlocLifecycleManager","expectedState","newState","previousState","delay","canDispose","onDispose","handler","SystemPluginRegistry","plugin","pluginName","name","hookName","args","errorHandler","hook","startTime","error","bloc","currentState","event","context","hookError","adapter","metadata","pluginMetrics","hookMetrics","executionTime","ErrorCategory","ErrorSeverity","BlacError","message","category","severity","cause","contextStr","_","v","k","DefaultErrorStrategy","ErrorManager","strategy","handlerError","operation","errorFactory","blacError","SingletonBlacManager","Blac","instance","oldInstance","instanceManager","setBlacInstanceManager","manager","config","options","__unsafe_ignore_singleton","oldBlocInstanceMap","oldIsolatedBlocMap","blocArray","base","key","blocClassName","id","blocClass","found","blocs","wasRemoved","index","b","wasInIndex","uid","constructorParams","instanceRef","newBloc","forceNewInstance","blocId","isolatedBloc","registeredBloc","results","blocInstance","isolatedBlocs","toDispose","predicate","sum","arr","generateUUID","c","r","handleError","fn","BlocPluginRegistry","nextState","transformedState","transformedEvent","caps","SubscriptionManager","subscription","path","subs","oldState","action","sortedSubscriptions","a","shouldNotify","newValue","oldValue","changedPaths","subscriptionId","value","allKeys","fullPath","p","trackedPath","changedPath","consumerCount","observerCount","sub","deadIds","BatchingManager","callback","onFlush","finalUpdate","update","BlocBase","initialState","Constructor","state","selector","equalityFn","componentRef","Bloc","eventConstructor","transformedAction","emit","constructorName","errorContext","pluginError","Cubit","statePatch","ignoreChangeCheck","changes","current","PropsUpdated","props","shallowEqual","keysA","keysB","generateInstanceIdFromProps","primitives","type","parts","RerenderLogger","info","loggingConfig","currentCount","lastTimestamp","groupKey","existingTimeout","group","timeout","logs","log","level","emoji","header","details","values","componentName","BlocTest","BlocClass","resolve","reject","timeoutId","unsubscribe","expectedStates","receivedStates","i","expected","received","MockBloc","MockCubit","MemoryLeakDetector","currentStats","hasLeaks","report","proxyCache","stats","createStateProxy","target","consumerRef","consumerTracker","refCache","cached","proxy","obj","prop","isObject","createBlocProxy","findPropertyDescriptor","isPrimitive","maxDepth","depth","descriptor","ProxyFactory","BlacAdapter","instanceProps","instanceId","generatedId","_state","newValues","weakRef","subscriptions","oldValues","part","deepChanges","oldObj","newObj","basePath","elementPath","keyPath","oldVal","newVal","deeperChanges"],"mappings":"AAGY,IAAAA,sBAAAA,OACVA,EAAA,SAAS,UACTA,EAAA,qBAAqB,sBACrBA,EAAA,YAAY,aACZA,EAAA,WAAW,YAJDA,IAAAA,KAAA,CAAA,CAAA;AAiBL,MAAMC,EAAqB;AAAA,EACxB,gBAAgB;AAAA,EAChB,eAAe;AAAA,EACf;AAAA,EACA;AAAA,EAER,IAAI,eAAmC;AACrC,WAAO,KAAK;AAAA,EAAA;AAAA,EAGd,IAAI,aAAsB;AACxB,WAAO,KAAK,kBAAkB;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMhC,sBACEC,GACAC,GACuB;AACvB,QAAI,KAAK;AACA,aAAA;AAAA,QACL,SAAS;AAAA,QACT,cAAc,KAAK;AAAA,QACnB,eAAe,KAAK;AAAA,MACtB;AAGF,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