@blac/core 2.0.3 → 2.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -0
- package/dist/StateContainerRegistry.cjs.map +1 -1
- package/dist/StateContainerRegistry.js.map +1 -1
- package/dist/index.cjs +30 -21
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +5 -5
- package/dist/index.d.ts +5 -5
- package/dist/index.js +13 -4
- package/dist/index.js.map +1 -1
- package/dist/plugins.js +1 -1
- package/dist/resolve-dependencies.cjs.map +1 -0
- package/dist/resolve-dependencies.js.map +1 -0
- package/dist/tracking/index.d.ts +2 -1
- package/dist/tracking/resolve-dependencies.d.ts +7 -0
- package/dist/tracking/tracking-proxy.d.ts +0 -14
- package/dist/tracking.cjs +17 -18
- package/dist/tracking.js +2 -3
- package/dist/watch-entry.cjs +10 -12
- package/dist/watch-entry.cjs.map +1 -1
- package/dist/watch-entry.js +1 -3
- package/dist/watch-entry.js.map +1 -1
- package/dist/watch.cjs.map +1 -1
- package/dist/watch.js.map +1 -1
- package/package.json +2 -2
- package/dist/dependency-manager.cjs.map +0 -1
- package/dist/dependency-manager.js.map +0 -1
- package/dist/tracking-proxy.cjs.map +0 -1
- package/dist/tracking-proxy.js.map +0 -1
package/README.md
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
# @blac/core
|
|
2
2
|
|
|
3
|
+
> ⚠️ **Warning:** This project is currently under active development. The API may change in future releases. Use with caution in production environments.
|
|
4
|
+
|
|
3
5
|
Core state management library implementing the BloC pattern for TypeScript applications.
|
|
4
6
|
|
|
5
7
|
## Installation
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"StateContainerRegistry.cjs","names":["BLAC_STATIC_PROPS","BLAC_ERROR_PREFIX","getGetterExecutionContext","BLAC_DEFAULTS"],"sources":["../src/plugin/PluginManager.ts","../src/utils/static-props.ts","../src/core/StateContainerRegistry.ts"],"sourcesContent":["import type { StateContainer } from '../core/StateContainer';\nimport type { StateContainerRegistry } from '../core/StateContainerRegistry';\nimport type {\n BlacPlugin,\n PluginContext,\n PluginConfig,\n InstanceMetadata,\n} from './BlacPlugin';\n\n/**\n * Internal structure for tracking installed plugins\n * @internal\n */\ninterface InstalledPlugin {\n plugin: BlacPlugin;\n config: PluginConfig;\n context: PluginContext;\n}\n\n/**\n * Manages plugin lifecycle for the BlaC state management system.\n * Plugins receive notifications about state container lifecycle events.\n *\n * @example\n * ```ts\n * const manager = createPluginManager(registry);\n * manager.install(myPlugin, { environment: 'development' });\n * ```\n */\nexport class PluginManager {\n private plugins = new Map<string, InstalledPlugin>();\n private registry: StateContainerRegistry;\n\n /**\n * Create a new PluginManager\n * @param registry - The StateContainerRegistry to monitor for lifecycle events\n */\n constructor(registry: StateContainerRegistry) {\n this.registry = registry;\n this.setupLifecycleHooks();\n }\n\n /**\n * Install a plugin with optional configuration\n * @param plugin - The plugin to install\n * @param config - Optional plugin configuration\n * @throws Error if plugin is already installed\n */\n install(plugin: BlacPlugin, config: PluginConfig = {}): void {\n const effectiveConfig: PluginConfig = {\n enabled: true,\n environment: 'all',\n ...config,\n };\n\n if (!this.shouldEnablePlugin(effectiveConfig)) {\n console.log(\n `[BlaC] Plugin \"${plugin.name}\" skipped (environment mismatch)`,\n );\n return;\n }\n\n if (this.plugins.has(plugin.name)) {\n throw new Error(`Plugin \"${plugin.name}\" is already installed`);\n }\n\n const context = this.createPluginContext();\n\n this.plugins.set(plugin.name, {\n plugin,\n config: effectiveConfig,\n context,\n });\n\n if (plugin.onInstall) {\n try {\n plugin.onInstall(context);\n } catch (error) {\n console.error(\n `[BlaC] Error installing plugin \"${plugin.name}\":`,\n error,\n );\n this.plugins.delete(plugin.name);\n throw error;\n }\n }\n\n console.log(`[BlaC] Plugin \"${plugin.name}\" v${plugin.version} installed`);\n }\n\n /**\n * Uninstall a plugin by name\n * @param pluginName - The name of the plugin to uninstall\n * @throws Error if plugin is not installed\n */\n uninstall(pluginName: string): void {\n const installed = this.plugins.get(pluginName);\n if (!installed) {\n throw new Error(`Plugin \"${pluginName}\" is not installed`);\n }\n\n if (installed.plugin.onUninstall) {\n try {\n installed.plugin.onUninstall();\n } catch (error) {\n console.error(\n `[BlaC] Error uninstalling plugin \"${pluginName}\":`,\n error,\n );\n }\n }\n\n this.plugins.delete(pluginName);\n console.log(`[BlaC] Plugin \"${pluginName}\" uninstalled`);\n }\n\n /**\n * Get an installed plugin by name\n * @param pluginName - The name of the plugin to retrieve\n * @returns The plugin instance or undefined if not found\n */\n getPlugin(pluginName: string): BlacPlugin | undefined {\n return this.plugins.get(pluginName)?.plugin;\n }\n\n /**\n * Get all installed plugins\n * @returns Array of all installed plugins\n */\n getAllPlugins(): BlacPlugin[] {\n return Array.from(this.plugins.values()).map((p) => p.plugin);\n }\n\n /**\n * Check if a plugin is installed\n * @param pluginName - The name of the plugin to check\n * @returns true if the plugin is installed\n */\n hasPlugin(pluginName: string): boolean {\n return this.plugins.has(pluginName);\n }\n\n /**\n * Uninstall all plugins\n */\n clear(): void {\n for (const name of this.plugins.keys()) {\n this.uninstall(name);\n }\n }\n\n /**\n * Setup lifecycle hooks to notify plugins\n */\n private setupLifecycleHooks(): void {\n // Instance created\n this.registry.on('created', (instance) => {\n this.notifyPlugins('onInstanceCreated', instance);\n });\n\n // State changed\n this.registry.on(\n 'stateChanged',\n (instance, previousState, currentState, callstack) => {\n this.notifyPlugins(\n 'onStateChanged',\n instance,\n previousState,\n currentState,\n callstack,\n );\n },\n );\n\n // Instance disposed\n this.registry.on('disposed', (instance) => {\n this.notifyPlugins('onInstanceDisposed', instance);\n });\n }\n\n /**\n * Notify all plugins of a lifecycle event\n */\n private notifyPlugins(hookName: keyof BlacPlugin, ...args: any[]): void {\n for (const { plugin, config, context } of this.plugins.values()) {\n if (!config.enabled) continue;\n\n const hook = plugin[hookName];\n if (typeof hook === 'function') {\n try {\n (hook as any).apply(plugin, [...args, context]);\n } catch (error) {\n console.error(\n `[BlaC] Error in plugin \"${plugin.name}\" ${hookName}:`,\n error,\n );\n }\n }\n }\n }\n\n /**\n * Create plugin context with safe API access\n */\n private createPluginContext(): PluginContext {\n return {\n getInstanceMetadata: (\n instance: StateContainer<any>,\n ): InstanceMetadata => {\n // const TypeClass = instance.constructor as any;\n\n // if (TypeClass.instances) {\n // for (const [key, entry] of TypeClass.instances) {\n // if (entry.instance === instance) {\n // break;\n // }\n // }\n // }\n\n return {\n id: instance.instanceId,\n className: instance.constructor.name,\n isDisposed: instance.isDisposed,\n name: instance.name,\n lastStateChangeTimestamp: instance.lastUpdateTimestamp,\n createdAt: instance.createdAt,\n state: instance.state,\n isIsolated: instance.instanceId.startsWith('isolated-'),\n };\n },\n\n getState: <S extends object = any>(instance: StateContainer<S>): S => {\n return instance.state;\n },\n\n queryInstances: <T extends StateContainer<any>>(\n typeClass: new (...args: any[]) => T,\n ): T[] => {\n return this.registry.getAll(typeClass as any);\n },\n\n getAllTypes: () => {\n return this.registry.getTypes();\n },\n\n getStats: () => {\n return this.registry.getStats();\n },\n };\n }\n\n /**\n * Check if plugin should be enabled based on environment\n */\n private shouldEnablePlugin(config: PluginConfig): boolean {\n if (!config.enabled) return false;\n if (config.environment === 'all') return true;\n\n const currentEnv = this.getCurrentEnvironment();\n return currentEnv === config.environment;\n }\n\n /**\n * Get current environment\n */\n private getCurrentEnvironment(): 'development' | 'production' | 'test' {\n if (typeof process !== 'undefined') {\n if (process.env.NODE_ENV === 'test') return 'test';\n if (process.env.NODE_ENV === 'production') return 'production';\n return 'development';\n }\n return 'development';\n }\n}\n\n/**\n * Create a plugin manager instance\n * @param registry - The StateContainerRegistry to monitor for lifecycle events\n * @returns A new PluginManager instance\n */\nexport function createPluginManager(\n registry: StateContainerRegistry,\n): PluginManager {\n return new PluginManager(registry);\n}\n","/**\n * Utility functions for accessing static properties on StateContainer classes\n */\n\nimport { BLAC_STATIC_PROPS } from '../constants';\nimport { StateContainerConstructor } from '../types/utilities';\n\n/**\n * Get a static property from a class constructor\n * Type-safe helper that avoids (Type as any) casts\n *\n * @param Type - The class constructor\n * @param propName - The property name to access\n * @param defaultValue - Optional default value if property is undefined\n * @returns The property value or default\n */\nexport function getStaticProp<\n V,\n T extends StateContainerConstructor = StateContainerConstructor,\n>(Type: T, propName: string, defaultValue?: V): V | undefined {\n return (Type as any)[propName] ?? defaultValue;\n}\n\n/**\n * Check if a class is marked as isolated.\n * Isolated classes create separate instances per component.\n * @param Type - The class constructor to check\n * @returns true if the class has `static isolated = true`\n */\nexport function isIsolatedClass<T extends StateContainerConstructor>(\n Type: T,\n): boolean {\n return getStaticProp<boolean>(Type, BLAC_STATIC_PROPS.ISOLATED) === true;\n}\n\n/**\n * Check if a class is marked as keepAlive.\n * KeepAlive classes are never auto-disposed when ref count reaches 0.\n * @param Type - The class constructor to check\n * @returns true if the class has `static keepAlive = true`\n */\nexport function isKeepAliveClass<T extends StateContainerConstructor>(\n Type: T,\n): boolean {\n return getStaticProp<boolean>(Type, BLAC_STATIC_PROPS.KEEP_ALIVE) === true;\n}\n\n/**\n * Check if a class should be excluded from DevTools.\n * Used to prevent infinite loops when DevTools tracks itself.\n * @param Type - The class constructor to check\n * @returns true if the class has `static __excludeFromDevTools = true`\n */\nexport function isExcludedFromDevTools<T extends StateContainerConstructor>(\n Type: T,\n): boolean {\n return (\n getStaticProp<boolean>(Type, BLAC_STATIC_PROPS.EXCLUDE_FROM_DEVTOOLS) ===\n true\n );\n}\n","import type { StateContainer, StateContainerConfig } from './StateContainer';\nimport { createPluginManager } from '../plugin/PluginManager';\nimport { getGetterExecutionContext } from '../tracking/tracking-proxy';\nimport { BLAC_DEFAULTS, BLAC_ERROR_PREFIX } from '../constants';\nimport { isIsolatedClass, isKeepAliveClass } from '../utils/static-props';\nimport {\n InstanceReadonlyState,\n StateContainerConstructor,\n} from '../types/utilities';\n\n/**\n * Internal configuration for registered types\n * @internal\n */\ninterface TypeConfig {\n isolated: boolean;\n}\n\n/**\n * Entry in the instance registry, tracking the instance and its reference count\n * @template T - Instance type\n */\nexport interface InstanceEntry<T = any> {\n /** The state container instance */\n instance: T;\n /** Number of active references to this instance */\n refCount: number;\n}\n\n/**\n * Lifecycle events emitted by the registry\n */\nexport type LifecycleEvent = 'created' | 'stateChanged' | 'disposed';\n\n/**\n * Listener function type for each lifecycle event\n * @template E - The lifecycle event type\n */\nexport type LifecycleListener<E extends LifecycleEvent> = E extends 'created'\n ? (container: StateContainer<any>) => void\n : E extends 'stateChanged'\n ? (\n container: StateContainer<any>,\n previousState: any,\n currentState: any,\n callstack?: string,\n ) => void\n : E extends 'disposed'\n ? (container: StateContainer<any>) => void\n : never;\n\n/**\n * Central registry for managing StateContainer instances.\n * Handles instance lifecycle, ref counting, and lifecycle event emission.\n *\n * @example\n * ```ts\n * const registry = new StateContainerRegistry();\n * const instance = registry.acquire(MyBloc); // ownership, must release\n * const other = registry.ensure(OtherBloc); // no ownership, bloc-to-bloc\n * registry.on('stateChanged', (container, prev, next) => {\n * console.log('State changed:', prev, '->', next);\n * });\n * ```\n */\nexport class StateContainerRegistry {\n private readonly instancesByConstructor = new WeakMap<\n StateContainerConstructor,\n Map<string, InstanceEntry>\n >();\n\n private readonly types = new Set<StateContainerConstructor>();\n\n private readonly typeConfigs = new Map<string, TypeConfig>();\n\n private readonly listeners = new Map<\n LifecycleEvent,\n Set<(...args: any[]) => void>\n >();\n\n /**\n * Register a type for lifecycle event tracking\n * @param constructor - The StateContainer class constructor\n */\n registerType<T extends StateContainerConstructor>(constructor: T): void {\n this.types.add(constructor);\n }\n\n /**\n * Register a StateContainer class with configuration\n * @param constructor - The StateContainer class constructor\n * @param isolated - Whether instances should be isolated (component-scoped)\n * @throws Error if type is already registered\n */\n register<T extends StateContainerConstructor>(\n constructor: T,\n isolated = false,\n ): void {\n const className = constructor.name;\n\n if (!isolated && isIsolatedClass(constructor)) {\n isolated = true;\n }\n\n if (this.typeConfigs.has(className)) {\n throw new Error(\n `${BLAC_ERROR_PREFIX} Type \"${className}\" is already registered`,\n );\n }\n\n this.typeConfigs.set(className, { isolated });\n this.registerType(constructor);\n }\n\n private ensureInstancesMap<T extends StateContainerConstructor>(\n Type: T,\n ): Map<string, InstanceEntry> {\n let instances = this.instancesByConstructor.get(Type);\n if (!instances) {\n instances = new Map<string, InstanceEntry>();\n this.instancesByConstructor.set(Type, instances);\n }\n return instances;\n }\n\n /**\n * Get the instances Map for a specific class (public API for stats/debugging)\n */\n getInstancesMap<T extends StateContainerConstructor>(\n Type: T,\n ): Map<string, InstanceEntry> {\n return this.instancesByConstructor.get(Type) || new Map();\n }\n\n private trackExecutionContext(instance: StateContainer<any>): void {\n // Track cross-bloc dependency if we're inside a getter execution\n const context = getGetterExecutionContext();\n if (\n context.tracker &&\n context.currentBloc &&\n context.currentBloc !== instance\n ) {\n // Add this bloc as an external dependency\n context.tracker.externalDependencies.add(instance);\n }\n }\n\n /**\n * Acquire an instance with ref counting (ownership semantics).\n * Creates a new instance if one doesn't exist, or returns existing and increments ref count.\n * You must call `release()` when done to decrement the ref count.\n * @param Type - The StateContainer class constructor\n * @param instanceKey - Instance key (defaults to 'default')\n * @param options - Acquisition options\n * @param options.canCreate - Whether to create new instance if not found (default: true)\n * @param options.countRef - Whether to increment ref count (default: true)\n * @param options.trackExecutionContext - Whether to track cross-bloc dependency (default: false)\n * @returns The state container instance\n */\n acquire<T extends StateContainerConstructor = StateContainerConstructor>(\n Type: T,\n instanceKey: string = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY,\n options: {\n canCreate?: boolean;\n countRef?: boolean;\n trackExecutionContext?: boolean;\n } = {},\n ): InstanceType<T> {\n const {\n canCreate = true,\n countRef = true,\n trackExecutionContext = false,\n } = options;\n // Check if this is an isolated type\n const registryConfig = this.typeConfigs.get(Type.name);\n const isolated = isIsolatedClass(Type) || registryConfig?.isolated === true;\n\n const config: StateContainerConfig = {\n instanceId: instanceKey,\n };\n\n if (isolated && !canCreate) {\n throw new Error(\n `${BLAC_ERROR_PREFIX} Cannot get isolated instance \"${instanceKey}\" of ${Type.name} when creation is disabled.`,\n );\n }\n\n // Isolated: always create new instance (not tracked)\n if (isolated) {\n const instance = new Type() as InstanceType<T>;\n instance.initConfig(config);\n // Register type for lifecycle coordination\n this.registerType(Type);\n if (trackExecutionContext) {\n this.trackExecutionContext(instance);\n }\n return instance;\n }\n\n // Shared: singleton pattern with ref counting\n const instances = this.ensureInstancesMap(Type);\n const entry = instances.get(instanceKey);\n\n // Increment ref count if found, only if counting is enabled or refCount is 0\n if (entry && (countRef || entry.refCount === 0)) {\n entry.refCount++;\n }\n\n if (entry) {\n if (trackExecutionContext) {\n this.trackExecutionContext(entry.instance);\n }\n return entry.instance;\n }\n\n if (!canCreate) {\n throw new Error(\n `${BLAC_ERROR_PREFIX} ${Type.name} instance \"${instanceKey}\" not found and creation is disabled.`,\n );\n }\n\n // Create new shared instance\n const instance = new Type() as InstanceType<T>;\n instance.initConfig(config);\n instances.set(instanceKey, { instance, refCount: 1 });\n\n // Register type for lifecycle coordination\n this.registerType(Type);\n\n if (trackExecutionContext) {\n this.trackExecutionContext(instance);\n }\n return instance;\n }\n\n /**\n * Borrow an existing instance without incrementing ref count (borrowing semantics).\n * Tracks cross-bloc dependency for reactive updates.\n * @param Type - The StateContainer class constructor\n * @param instanceKey - Instance key (defaults to 'default')\n * @returns The state container instance\n * @throws Error if instance doesn't exist\n */\n borrow<T extends StateContainerConstructor = StateContainerConstructor>(\n Type: T,\n instanceKey: string = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY,\n ): InstanceType<T> {\n return this.acquire(Type, instanceKey, {\n canCreate: false,\n trackExecutionContext: true,\n });\n }\n\n /**\n * Safely borrow an existing instance (borrowing semantics with error handling).\n * Returns discriminated union for type-safe conditional access.\n * @param Type - The StateContainer class constructor\n * @param instanceKey - Instance key (defaults to 'default')\n * @returns Discriminated union with either the instance or an error\n */\n borrowSafe<T extends StateContainerConstructor = StateContainerConstructor>(\n Type: T,\n instanceKey: string = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY,\n ):\n | { error: Error; instance: null }\n | { error: null; instance: InstanceType<T> } {\n try {\n const instance = this.borrow(Type, instanceKey);\n return { error: null, instance };\n } catch (error: any) {\n return { error, instance: null };\n }\n }\n\n /**\n * Ensure an instance exists without taking ownership (for bloc-to-bloc communication).\n * Gets existing instance OR creates it if it doesn't exist, without incrementing ref count.\n * Tracks cross-bloc dependency for reactive updates.\n *\n * Use this in bloc-to-bloc communication when you need to ensure an instance exists\n * but don't want to claim ownership (no ref count increment).\n * @param Type - The StateContainer class constructor\n * @param instanceKey - Instance key (defaults to 'default')\n * @returns The state container instance\n */\n ensure<T extends StateContainerConstructor = StateContainerConstructor>(\n Type: T,\n instanceKey: string = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY,\n ): InstanceType<T> {\n return this.acquire(Type, instanceKey, {\n canCreate: true,\n countRef: false,\n trackExecutionContext: true,\n });\n }\n\n /**\n * Release a reference to an instance.\n * Decrements ref count and disposes when it reaches 0 (unless keepAlive).\n * @param Type - The StateContainer class constructor\n * @param instanceKey - Instance key (defaults to 'default')\n * @param forceDispose - Force immediate disposal regardless of ref count\n */\n release<T extends StateContainerConstructor>(\n Type: T,\n instanceKey: string = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY,\n forceDispose = false,\n ): void {\n const instances = this.ensureInstancesMap(Type);\n const entry = instances.get(instanceKey);\n\n if (!entry) return;\n\n // Force dispose immediately\n if (forceDispose) {\n if (!entry.instance.isDisposed) {\n entry.instance.dispose();\n }\n instances.delete(instanceKey);\n return;\n }\n\n // Decrement ref count\n entry.refCount--;\n\n // Check static keepAlive property\n const keepAlive = isKeepAliveClass(Type);\n\n // Auto-dispose when ref count reaches 0 (unless keepAlive)\n if (entry.refCount <= 0 && !keepAlive) {\n if (!entry.instance.isDisposed) {\n entry.instance.dispose();\n }\n instances.delete(instanceKey);\n }\n }\n\n /**\n * Get all instances of a specific type.\n * @param Type - The StateContainer class constructor\n * @returns Array of all instances\n */\n getAll<T extends StateContainerConstructor>(\n Type: T,\n ): InstanceReadonlyState<T>[] {\n const instances = this.ensureInstancesMap(Type);\n const result: InstanceReadonlyState<T>[] = [];\n for (const entry of instances.values()) {\n result.push(entry.instance);\n }\n return result;\n }\n\n /**\n * Safely iterate over all instances of a type.\n * Skips disposed instances and catches callback errors.\n * @param Type - The StateContainer class constructor\n * @param callback - Function to call for each instance\n */\n forEach<T extends StateContainerConstructor>(\n Type: T,\n callback: (instance: InstanceReadonlyState<T>) => void,\n ): void {\n const instances = this.ensureInstancesMap(Type);\n for (const entry of instances.values()) {\n const instance = entry.instance;\n if (!instance.isDisposed) {\n try {\n callback(instance);\n } catch (error) {\n console.error(\n `${BLAC_ERROR_PREFIX} forEach callback error for ${Type.name}:`,\n error,\n );\n }\n }\n }\n }\n\n /**\n * Clear all instances of a specific type (disposes them).\n * @param Type - The StateContainer class constructor\n */\n clear<T extends StateContainerConstructor>(Type: T): void {\n const instances = this.ensureInstancesMap(Type);\n // Dispose all instances\n for (const entry of instances.values()) {\n if (!entry.instance.isDisposed) {\n entry.instance.dispose();\n }\n }\n // Clear the Map\n instances.clear();\n }\n\n /**\n * Get reference count for an instance.\n * @param Type - The StateContainer class constructor\n * @param instanceKey - Instance key (defaults to 'default')\n * @returns Current ref count (0 if instance doesn't exist)\n */\n getRefCount<T extends StateContainerConstructor>(\n Type: T,\n instanceKey: string = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY,\n ): number {\n const instances = this.ensureInstancesMap(Type);\n const entry = instances.get(instanceKey);\n return entry?.refCount ?? 0;\n }\n\n /**\n * Check if an instance exists.\n * @param Type - The StateContainer class constructor\n * @param instanceKey - Instance key (defaults to 'default')\n * @returns true if instance exists\n */\n hasInstance<T extends StateContainerConstructor>(\n Type: T,\n instanceKey: string = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY,\n ): boolean {\n const instances = this.ensureInstancesMap(Type);\n return instances.has(instanceKey);\n }\n\n /**\n * Clear all instances from all types (for testing)\n *\n * Iterates all registered types and clears their instances.\n * Also clears type tracking to reset the registry state.\n */\n clearAll(): void {\n // Step 1: Clear instances from each type (while we still have the types list)\n for (const Type of this.types) {\n this.clear(Type);\n }\n // Step 2: Now clear type tracking (resets registry state for tests)\n this.types.clear();\n this.typeConfigs.clear();\n }\n\n /**\n * Get registry statistics for debugging.\n * @returns Object with registeredTypes, totalInstances, and typeBreakdown\n */\n getStats(): {\n registeredTypes: number;\n totalInstances: number;\n typeBreakdown: Record<string, number>;\n } {\n const typeBreakdown: Record<string, number> = {};\n let totalInstances = 0;\n\n // Collect stats from each registered type\n for (const Type of this.types) {\n const typeName = Type.name;\n const instances = this.getInstancesMap(Type);\n const count = instances.size;\n\n typeBreakdown[typeName] = count;\n totalInstances += count;\n }\n\n return {\n registeredTypes: this.types.size,\n totalInstances,\n typeBreakdown,\n };\n }\n\n /**\n * Get all registered types (for plugin system).\n * @returns Array of all registered StateContainer class constructors\n */\n getTypes(): StateContainerConstructor[] {\n return Array.from(this.types);\n }\n\n /**\n * Subscribe to lifecycle events\n * @param event - The lifecycle event to listen for\n * @param listener - The listener function to call when the event occurs\n * @returns Unsubscribe function\n */\n on<E extends LifecycleEvent>(\n event: E,\n listener: LifecycleListener<E>,\n ): () => void {\n if (!this.listeners.has(event)) {\n this.listeners.set(event, new Set());\n }\n const instance = this.listeners.get(event);\n if (!instance) {\n throw new Error(\n `${BLAC_ERROR_PREFIX} Failed to register listener for event '${event}'`,\n );\n }\n\n instance.add(listener as (...args: any[]) => void);\n\n // Return unsubscribe function\n return () => {\n this.listeners.get(event)?.delete(listener as (...args: any[]) => void);\n };\n }\n\n /**\n * Emit lifecycle event to all listeners\n * @internal - Called by StateContainer lifecycle methods\n */\n emit(event: LifecycleEvent, ...args: any[]): void {\n const listeners = this.listeners.get(event);\n if (!listeners || listeners.size === 0) return; // Zero overhead when no listeners\n\n for (const listener of listeners) {\n try {\n listener(...args);\n } catch (error) {\n console.error(\n `${BLAC_ERROR_PREFIX} Listener error for '${event}':`,\n error,\n );\n }\n }\n }\n}\n\n/**\n * Global default registry instance\n */\nexport const globalRegistry = new StateContainerRegistry();\n\n/**\n * Global plugin manager (initialized lazily)\n */\nlet _globalPluginManager: any = null;\n\n/**\n * Get the global plugin manager\n */\nexport function getPluginManager(): any {\n if (!_globalPluginManager) {\n _globalPluginManager = createPluginManager(globalRegistry);\n }\n return _globalPluginManager;\n}\n"],"mappings":";;;;;;;;;;;;;AA6BA,IAAa,gBAAb,MAA2B;;;;;CAQzB,YAAY,UAAkC;iCAP5B,IAAI,KAA8B;AAQlD,OAAK,WAAW;AAChB,OAAK,qBAAqB;;;;;;;;CAS5B,QAAQ,QAAoB,SAAuB,EAAE,EAAQ;EAC3D,MAAM,kBAAgC;GACpC,SAAS;GACT,aAAa;GACb,GAAG;GACJ;AAED,MAAI,CAAC,KAAK,mBAAmB,gBAAgB,EAAE;AAC7C,WAAQ,IACN,kBAAkB,OAAO,KAAK,kCAC/B;AACD;;AAGF,MAAI,KAAK,QAAQ,IAAI,OAAO,KAAK,CAC/B,OAAM,IAAI,MAAM,WAAW,OAAO,KAAK,wBAAwB;EAGjE,MAAM,UAAU,KAAK,qBAAqB;AAE1C,OAAK,QAAQ,IAAI,OAAO,MAAM;GAC5B;GACA,QAAQ;GACR;GACD,CAAC;AAEF,MAAI,OAAO,UACT,KAAI;AACF,UAAO,UAAU,QAAQ;WAClB,OAAO;AACd,WAAQ,MACN,mCAAmC,OAAO,KAAK,KAC/C,MACD;AACD,QAAK,QAAQ,OAAO,OAAO,KAAK;AAChC,SAAM;;AAIV,UAAQ,IAAI,kBAAkB,OAAO,KAAK,KAAK,OAAO,QAAQ,YAAY;;;;;;;CAQ5E,UAAU,YAA0B;EAClC,MAAM,YAAY,KAAK,QAAQ,IAAI,WAAW;AAC9C,MAAI,CAAC,UACH,OAAM,IAAI,MAAM,WAAW,WAAW,oBAAoB;AAG5D,MAAI,UAAU,OAAO,YACnB,KAAI;AACF,aAAU,OAAO,aAAa;WACvB,OAAO;AACd,WAAQ,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AAM;;;;;;;;CAS/B,GACE,OACA,UACY;AACZ,MAAI,CAAC,KAAK,UAAU,IAAI,MAAM,CAC5B,MAAK,UAAU,IAAI,uBAAO,IAAI,KAAK,CAAC;EAEtC,MAAM,WAAW,KAAK,UAAU,IAAI,MAAM;AAC1C,MAAI,CAAC,SACH,OAAM,IAAI,MACR,GAAGF,yCAAkB,0CAA0C,MAAM,GACtE;AAGH,WAAS,IAAI,SAAqC;AAGlD,eAAa;AACX,QAAK,UAAU,IAAI,MAAM,EAAE,OAAO,SAAqC;;;;;;;CAQ3E,KAAK,OAAuB,GAAG,MAAmB;EAChD,MAAM,YAAY,KAAK,UAAU,IAAI,MAAM;AAC3C,MAAI,CAAC,aAAa,UAAU,SAAS,EAAG;AAExC,OAAK,MAAM,YAAY,UACrB,KAAI;AACF,YAAS,GAAG,KAAK;WACV,OAAO;AACd,WAAQ,MACN,GAAGA,yCAAkB,uBAAuB,MAAM,KAClD,MACD;;;;;;;AAST,MAAa,iBAAiB,IAAI,wBAAwB;;;;AAK1D,IAAI,uBAA4B;;;;AAKhC,SAAgB,mBAAwB;AACtC,KAAI,CAAC,qBACH,wBAAuB,oBAAoB,eAAe;AAE5D,QAAO"}
|
|
1
|
+
{"version":3,"file":"StateContainerRegistry.cjs","names":[],"sources":["../src/plugin/PluginManager.ts","../src/constants.ts","../src/utils/static-props.ts","../src/core/StateContainerRegistry.ts"],"sourcesContent":["import type { StateContainer } from '../core/StateContainer';\nimport type { StateContainerRegistry } from '../core/StateContainerRegistry';\nimport type {\n BlacPlugin,\n PluginContext,\n PluginConfig,\n InstanceMetadata,\n} from './BlacPlugin';\n\n/**\n * Internal structure for tracking installed plugins\n * @internal\n */\ninterface InstalledPlugin {\n plugin: BlacPlugin;\n config: PluginConfig;\n context: PluginContext;\n}\n\n/**\n * Manages plugin lifecycle for the BlaC state management system.\n * Plugins receive notifications about state container lifecycle events.\n *\n * @example\n * ```ts\n * const manager = createPluginManager(registry);\n * manager.install(myPlugin, { environment: 'development' });\n * ```\n */\nexport class PluginManager {\n private plugins = new Map<string, InstalledPlugin>();\n private registry: StateContainerRegistry;\n\n /**\n * Create a new PluginManager\n * @param registry - The StateContainerRegistry to monitor for lifecycle events\n */\n constructor(registry: StateContainerRegistry) {\n this.registry = registry;\n this.setupLifecycleHooks();\n }\n\n /**\n * Install a plugin with optional configuration\n * @param plugin - The plugin to install\n * @param config - Optional plugin configuration\n * @throws Error if plugin is already installed\n */\n install(plugin: BlacPlugin, config: PluginConfig = {}): void {\n const effectiveConfig: PluginConfig = {\n enabled: true,\n environment: 'all',\n ...config,\n };\n\n if (!this.shouldEnablePlugin(effectiveConfig)) {\n console.log(\n `[BlaC] Plugin \"${plugin.name}\" skipped (environment mismatch)`,\n );\n return;\n }\n\n if (this.plugins.has(plugin.name)) {\n throw new Error(`Plugin \"${plugin.name}\" is already installed`);\n }\n\n const context = this.createPluginContext();\n\n this.plugins.set(plugin.name, {\n plugin,\n config: effectiveConfig,\n context,\n });\n\n if (plugin.onInstall) {\n try {\n plugin.onInstall(context);\n } catch (error) {\n console.error(\n `[BlaC] Error installing plugin \"${plugin.name}\":`,\n error,\n );\n this.plugins.delete(plugin.name);\n throw error;\n }\n }\n\n console.log(`[BlaC] Plugin \"${plugin.name}\" v${plugin.version} installed`);\n }\n\n /**\n * Uninstall a plugin by name\n * @param pluginName - The name of the plugin to uninstall\n * @throws Error if plugin is not installed\n */\n uninstall(pluginName: string): void {\n const installed = this.plugins.get(pluginName);\n if (!installed) {\n throw new Error(`Plugin \"${pluginName}\" is not installed`);\n }\n\n if (installed.plugin.onUninstall) {\n try {\n installed.plugin.onUninstall();\n } catch (error) {\n console.error(\n `[BlaC] Error uninstalling plugin \"${pluginName}\":`,\n error,\n );\n }\n }\n\n this.plugins.delete(pluginName);\n console.log(`[BlaC] Plugin \"${pluginName}\" uninstalled`);\n }\n\n /**\n * Get an installed plugin by name\n * @param pluginName - The name of the plugin to retrieve\n * @returns The plugin instance or undefined if not found\n */\n getPlugin(pluginName: string): BlacPlugin | undefined {\n return this.plugins.get(pluginName)?.plugin;\n }\n\n /**\n * Get all installed plugins\n * @returns Array of all installed plugins\n */\n getAllPlugins(): BlacPlugin[] {\n return Array.from(this.plugins.values()).map((p) => p.plugin);\n }\n\n /**\n * Check if a plugin is installed\n * @param pluginName - The name of the plugin to check\n * @returns true if the plugin is installed\n */\n hasPlugin(pluginName: string): boolean {\n return this.plugins.has(pluginName);\n }\n\n /**\n * Uninstall all plugins\n */\n clear(): void {\n for (const name of this.plugins.keys()) {\n this.uninstall(name);\n }\n }\n\n /**\n * Setup lifecycle hooks to notify plugins\n */\n private setupLifecycleHooks(): void {\n // Instance created\n this.registry.on('created', (instance) => {\n this.notifyPlugins('onInstanceCreated', instance);\n });\n\n // State changed\n this.registry.on(\n 'stateChanged',\n (instance, previousState, currentState, callstack) => {\n this.notifyPlugins(\n 'onStateChanged',\n instance,\n previousState,\n currentState,\n callstack,\n );\n },\n );\n\n // Instance disposed\n this.registry.on('disposed', (instance) => {\n this.notifyPlugins('onInstanceDisposed', instance);\n });\n }\n\n /**\n * Notify all plugins of a lifecycle event\n */\n private notifyPlugins(hookName: keyof BlacPlugin, ...args: any[]): void {\n for (const { plugin, config, context } of this.plugins.values()) {\n if (!config.enabled) continue;\n\n const hook = plugin[hookName];\n if (typeof hook === 'function') {\n try {\n (hook as any).apply(plugin, [...args, context]);\n } catch (error) {\n console.error(\n `[BlaC] Error in plugin \"${plugin.name}\" ${hookName}:`,\n error,\n );\n }\n }\n }\n }\n\n /**\n * Create plugin context with safe API access\n */\n private createPluginContext(): PluginContext {\n return {\n getInstanceMetadata: (\n instance: StateContainer<any>,\n ): InstanceMetadata => {\n return {\n id: instance.instanceId,\n className: instance.constructor.name,\n isDisposed: instance.isDisposed,\n name: instance.name,\n lastStateChangeTimestamp: instance.lastUpdateTimestamp,\n createdAt: instance.createdAt,\n state: instance.state,\n isIsolated: instance.instanceId.startsWith('isolated-'),\n };\n },\n\n getState: <S extends object = any>(instance: StateContainer<S>): S => {\n return instance.state;\n },\n\n queryInstances: <T extends StateContainer<any>>(\n typeClass: new (...args: any[]) => T,\n ): T[] => {\n return this.registry.getAll(typeClass as any);\n },\n\n getAllTypes: () => {\n return this.registry.getTypes();\n },\n\n getStats: () => {\n return this.registry.getStats();\n },\n };\n }\n\n /**\n * Check if plugin should be enabled based on environment\n */\n private shouldEnablePlugin(config: PluginConfig): boolean {\n if (!config.enabled) return false;\n if (config.environment === 'all') return true;\n\n const currentEnv = this.getCurrentEnvironment();\n return currentEnv === config.environment;\n }\n\n /**\n * Get current environment\n */\n private getCurrentEnvironment(): 'development' | 'production' | 'test' {\n if (typeof process !== 'undefined') {\n if (process.env.NODE_ENV === 'test') return 'test';\n if (process.env.NODE_ENV === 'production') return 'production';\n return 'development';\n }\n return 'development';\n }\n}\n\n/**\n * Create a plugin manager instance\n * @param registry - The StateContainerRegistry to monitor for lifecycle events\n * @returns A new PluginManager instance\n */\nexport function createPluginManager(\n registry: StateContainerRegistry,\n): PluginManager {\n return new PluginManager(registry);\n}\n","/**\n * Default configuration constants for BlaC\n *\n * Centralized location for all magic numbers and default values.\n */\n\n/**\n * Default configuration constants for BlaC\n */\nexport const BLAC_DEFAULTS = {\n /**\n * Default instance key for shared instances\n */\n DEFAULT_INSTANCE_KEY: 'default',\n\n /**\n * Maximum getter nesting depth (prevents infinite recursion)\n */\n MAX_GETTER_DEPTH: 10,\n\n /**\n * Default cleanup interval for subscriptions (30 seconds)\n */\n CLEANUP_INTERVAL_MS: 30_000,\n\n /**\n * Cleanup interval for weak reference stage (10 seconds)\n */\n WEAKREF_CLEANUP_INTERVAL_MS: 10_000,\n\n /**\n * Default maximum subscriptions per container\n */\n MAX_SUBSCRIPTIONS: 1_000,\n\n /**\n * Maximum subscriptions for high-performance mode\n */\n MAX_SUBSCRIPTIONS_HIGH_PERF: 10_000,\n\n /**\n * Default timeout for pipeline execution (5 seconds)\n */\n PIPELINE_TIMEOUT_MS: 5_000,\n\n /**\n * Cleanup interval for high-performance mode (5 seconds)\n */\n CLEANUP_INTERVAL_HIGH_PERF_MS: 5_000,\n\n /**\n * Maximum number of stages in a pipeline\n */\n MAX_PIPELINE_STAGES: 30,\n} as const;\n\n/**\n * Static property names for StateContainer classes\n * Used for feature flags and configuration on bloc classes\n */\nexport const BLAC_STATIC_PROPS = {\n /**\n * Mark a bloc as isolated (each component gets its own instance)\n */\n ISOLATED: 'isolated',\n\n /**\n * Mark a bloc to never be auto-disposed (kept alive permanently)\n */\n KEEP_ALIVE: 'keepAlive',\n\n /**\n * Exclude a bloc from DevTools reporting (prevents infinite loops)\n */\n EXCLUDE_FROM_DEVTOOLS: '__excludeFromDevTools',\n} as const;\n\n/**\n * ID generation patterns and constants\n */\nexport const BLAC_ID_PATTERNS = {\n /**\n * Prefix for isolated instance keys\n */\n ISOLATED_PREFIX: 'isolated-',\n\n /**\n * Length of generated ID portion (9 characters from base36)\n */\n ID_LENGTH: 9,\n} as const;\n\n/**\n * Standard error message prefix\n */\nexport const BLAC_ERROR_PREFIX = '[BlaC]' as const;\n","/**\n * Utility functions for accessing static properties on StateContainer classes\n */\n\nimport { BLAC_STATIC_PROPS } from '../constants';\nimport { StateContainerConstructor } from '../types/utilities';\n\n/**\n * Get a static property from a class constructor\n * Type-safe helper that avoids (Type as any) casts\n *\n * @param Type - The class constructor\n * @param propName - The property name to access\n * @param defaultValue - Optional default value if property is undefined\n * @returns The property value or default\n */\nexport function getStaticProp<\n V,\n T extends StateContainerConstructor = StateContainerConstructor,\n>(Type: T, propName: string, defaultValue?: V): V | undefined {\n return (Type as any)[propName] ?? defaultValue;\n}\n\n/**\n * Check if a class is marked as isolated.\n * Isolated classes create separate instances per component.\n * @param Type - The class constructor to check\n * @returns true if the class has `static isolated = true`\n */\nexport function isIsolatedClass<T extends StateContainerConstructor>(\n Type: T,\n): boolean {\n return getStaticProp<boolean>(Type, BLAC_STATIC_PROPS.ISOLATED) === true;\n}\n\n/**\n * Check if a class is marked as keepAlive.\n * KeepAlive classes are never auto-disposed when ref count reaches 0.\n * @param Type - The class constructor to check\n * @returns true if the class has `static keepAlive = true`\n */\nexport function isKeepAliveClass<T extends StateContainerConstructor>(\n Type: T,\n): boolean {\n return getStaticProp<boolean>(Type, BLAC_STATIC_PROPS.KEEP_ALIVE) === true;\n}\n\n/**\n * Check if a class should be excluded from DevTools.\n * Used to prevent infinite loops when DevTools tracks itself.\n * @param Type - The class constructor to check\n * @returns true if the class has `static __excludeFromDevTools = true`\n */\nexport function isExcludedFromDevTools<T extends StateContainerConstructor>(\n Type: T,\n): boolean {\n return (\n getStaticProp<boolean>(Type, BLAC_STATIC_PROPS.EXCLUDE_FROM_DEVTOOLS) ===\n true\n );\n}\n","import type { StateContainer, StateContainerConfig } from './StateContainer';\nimport { createPluginManager } from '../plugin/PluginManager';\nimport { BLAC_DEFAULTS, BLAC_ERROR_PREFIX } from '../constants';\nimport { isIsolatedClass, isKeepAliveClass } from '../utils/static-props';\nimport {\n InstanceReadonlyState,\n StateContainerConstructor,\n} from '../types/utilities';\n\n/**\n * Internal configuration for registered types\n * @internal\n */\ninterface TypeConfig {\n isolated: boolean;\n}\n\n/**\n * Entry in the instance registry, tracking the instance and its reference count\n * @template T - Instance type\n */\nexport interface InstanceEntry<T = any> {\n /** The state container instance */\n instance: T;\n /** Number of active references to this instance */\n refCount: number;\n}\n\n/**\n * Lifecycle events emitted by the registry\n */\nexport type LifecycleEvent = 'created' | 'stateChanged' | 'disposed';\n\n/**\n * Listener function type for each lifecycle event\n * @template E - The lifecycle event type\n */\nexport type LifecycleListener<E extends LifecycleEvent> = E extends 'created'\n ? (container: StateContainer<any>) => void\n : E extends 'stateChanged'\n ? (\n container: StateContainer<any>,\n previousState: any,\n currentState: any,\n callstack?: string,\n ) => void\n : E extends 'disposed'\n ? (container: StateContainer<any>) => void\n : never;\n\n/**\n * Central registry for managing StateContainer instances.\n * Handles instance lifecycle, ref counting, and lifecycle event emission.\n *\n * @example\n * ```ts\n * const registry = new StateContainerRegistry();\n * const instance = registry.acquire(MyBloc); // ownership, must release\n * const other = registry.ensure(OtherBloc); // no ownership, bloc-to-bloc\n * registry.on('stateChanged', (container, prev, next) => {\n * console.log('State changed:', prev, '->', next);\n * });\n * ```\n */\nexport class StateContainerRegistry {\n private readonly instancesByConstructor = new WeakMap<\n StateContainerConstructor,\n Map<string, InstanceEntry>\n >();\n\n private readonly types = new Set<StateContainerConstructor>();\n\n private readonly typeConfigs = new Map<string, TypeConfig>();\n\n private readonly listeners = new Map<\n LifecycleEvent,\n Set<(...args: any[]) => void>\n >();\n\n /**\n * Register a type for lifecycle event tracking\n * @param constructor - The StateContainer class constructor\n */\n registerType<T extends StateContainerConstructor>(constructor: T): void {\n this.types.add(constructor);\n }\n\n /**\n * Register a StateContainer class with configuration\n * @param constructor - The StateContainer class constructor\n * @param isolated - Whether instances should be isolated (component-scoped)\n * @throws Error if type is already registered\n */\n register<T extends StateContainerConstructor>(\n constructor: T,\n isolated = false,\n ): void {\n const className = constructor.name;\n\n if (!isolated && isIsolatedClass(constructor)) {\n isolated = true;\n }\n\n if (this.typeConfigs.has(className)) {\n throw new Error(\n `${BLAC_ERROR_PREFIX} Type \"${className}\" is already registered`,\n );\n }\n\n this.typeConfigs.set(className, { isolated });\n this.registerType(constructor);\n }\n\n private ensureInstancesMap<T extends StateContainerConstructor>(\n Type: T,\n ): Map<string, InstanceEntry> {\n let instances = this.instancesByConstructor.get(Type);\n if (!instances) {\n instances = new Map<string, InstanceEntry>();\n this.instancesByConstructor.set(Type, instances);\n }\n return instances;\n }\n\n /**\n * Get the instances Map for a specific class (public API for stats/debugging)\n */\n getInstancesMap<T extends StateContainerConstructor>(\n Type: T,\n ): Map<string, InstanceEntry> {\n return this.instancesByConstructor.get(Type) || new Map();\n }\n\n /**\n * Acquire an instance with ref counting (ownership semantics).\n * Creates a new instance if one doesn't exist, or returns existing and increments ref count.\n * You must call `release()` when done to decrement the ref count.\n * @param Type - The StateContainer class constructor\n * @param instanceKey - Instance key (defaults to 'default')\n * @param options - Acquisition options\n * @param options.canCreate - Whether to create new instance if not found (default: true)\n * @param options.countRef - Whether to increment ref count (default: true)\n * @returns The state container instance\n */\n acquire<T extends StateContainerConstructor = StateContainerConstructor>(\n Type: T,\n instanceKey: string = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY,\n options: {\n canCreate?: boolean;\n countRef?: boolean;\n } = {},\n ): InstanceType<T> {\n const { canCreate = true, countRef = true } = options;\n // Check if this is an isolated type\n const registryConfig = this.typeConfigs.get(Type.name);\n const isolated = isIsolatedClass(Type) || registryConfig?.isolated === true;\n\n const config: StateContainerConfig = {\n instanceId: instanceKey,\n };\n\n if (isolated && !canCreate) {\n throw new Error(\n `${BLAC_ERROR_PREFIX} Cannot get isolated instance \"${instanceKey}\" of ${Type.name} when creation is disabled.`,\n );\n }\n\n // Isolated: always create new instance (not tracked)\n if (isolated) {\n const instance = new Type() as InstanceType<T>;\n instance.initConfig(config);\n // Register type for lifecycle coordination\n this.registerType(Type);\n return instance;\n }\n\n // Shared: singleton pattern with ref counting\n const instances = this.ensureInstancesMap(Type);\n let entry = instances.get(instanceKey);\n\n // Detect stale disposed entries (disposed directly, not through release)\n if (entry?.instance.isDisposed) {\n instances.delete(instanceKey);\n entry = undefined;\n }\n\n if (entry && countRef) {\n entry.refCount++;\n }\n\n if (entry) {\n return entry.instance;\n }\n\n if (!canCreate) {\n throw new Error(\n `${BLAC_ERROR_PREFIX} ${Type.name} instance \"${instanceKey}\" not found and creation is disabled.`,\n );\n }\n\n // Create new shared instance\n const instance = new Type() as InstanceType<T>;\n instance.initConfig(config);\n instances.set(instanceKey, { instance, refCount: 1 });\n\n // Register type for lifecycle coordination\n this.registerType(Type);\n\n return instance;\n }\n\n /**\n * Borrow an existing instance without incrementing ref count (borrowing semantics).\n * Tracks cross-bloc dependency for reactive updates.\n * @param Type - The StateContainer class constructor\n * @param instanceKey - Instance key (defaults to 'default')\n * @returns The state container instance\n * @throws Error if instance doesn't exist\n */\n borrow<T extends StateContainerConstructor = StateContainerConstructor>(\n Type: T,\n instanceKey: string = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY,\n ): InstanceType<T> {\n return this.acquire(Type, instanceKey, {\n canCreate: false,\n countRef: false,\n });\n }\n\n /**\n * Safely borrow an existing instance (borrowing semantics with error handling).\n * Returns discriminated union for type-safe conditional access.\n * @param Type - The StateContainer class constructor\n * @param instanceKey - Instance key (defaults to 'default')\n * @returns Discriminated union with either the instance or an error\n */\n borrowSafe<T extends StateContainerConstructor = StateContainerConstructor>(\n Type: T,\n instanceKey: string = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY,\n ):\n | { error: Error; instance: null }\n | { error: null; instance: InstanceType<T> } {\n try {\n const instance = this.borrow(Type, instanceKey);\n return { error: null, instance };\n } catch (error: any) {\n return { error, instance: null };\n }\n }\n\n /**\n * Ensure an instance exists without taking ownership (for bloc-to-bloc communication).\n * Gets existing instance OR creates it if it doesn't exist, without incrementing ref count.\n * Tracks cross-bloc dependency for reactive updates.\n *\n * Use this in bloc-to-bloc communication when you need to ensure an instance exists\n * but don't want to claim ownership (no ref count increment).\n * @param Type - The StateContainer class constructor\n * @param instanceKey - Instance key (defaults to 'default')\n * @returns The state container instance\n */\n ensure<T extends StateContainerConstructor = StateContainerConstructor>(\n Type: T,\n instanceKey: string = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY,\n ): InstanceType<T> {\n return this.acquire(Type, instanceKey, {\n canCreate: true,\n countRef: false,\n });\n }\n\n /**\n * Release a reference to an instance.\n * Decrements ref count and disposes when it reaches 0 (unless keepAlive).\n * @param Type - The StateContainer class constructor\n * @param instanceKey - Instance key (defaults to 'default')\n * @param forceDispose - Force immediate disposal regardless of ref count\n */\n release<T extends StateContainerConstructor>(\n Type: T,\n instanceKey: string = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY,\n forceDispose = false,\n ): void {\n const instances = this.ensureInstancesMap(Type);\n const entry = instances.get(instanceKey);\n\n if (!entry) return;\n\n // Force dispose immediately\n if (forceDispose) {\n if (!entry.instance.isDisposed) {\n entry.instance.dispose();\n }\n instances.delete(instanceKey);\n return;\n }\n\n // Decrement ref count\n entry.refCount--;\n\n // Check static keepAlive property\n const keepAlive = isKeepAliveClass(Type);\n\n // Auto-dispose when ref count reaches 0 (unless keepAlive)\n if (entry.refCount <= 0 && !keepAlive) {\n if (!entry.instance.isDisposed) {\n entry.instance.dispose();\n }\n instances.delete(instanceKey);\n }\n }\n\n /**\n * Get all instances of a specific type.\n * @param Type - The StateContainer class constructor\n * @returns Array of all instances\n */\n getAll<T extends StateContainerConstructor>(\n Type: T,\n ): InstanceReadonlyState<T>[] {\n const instances = this.ensureInstancesMap(Type);\n const result: InstanceReadonlyState<T>[] = [];\n for (const entry of instances.values()) {\n result.push(entry.instance);\n }\n return result;\n }\n\n /**\n * Safely iterate over all instances of a type.\n * Skips disposed instances and catches callback errors.\n * @param Type - The StateContainer class constructor\n * @param callback - Function to call for each instance\n */\n forEach<T extends StateContainerConstructor>(\n Type: T,\n callback: (instance: InstanceReadonlyState<T>) => void,\n ): void {\n const instances = this.ensureInstancesMap(Type);\n for (const entry of instances.values()) {\n const instance = entry.instance;\n if (!instance.isDisposed) {\n try {\n callback(instance);\n } catch (error) {\n console.error(\n `${BLAC_ERROR_PREFIX} forEach callback error for ${Type.name}:`,\n error,\n );\n }\n }\n }\n }\n\n /**\n * Clear all instances of a specific type (disposes them).\n * @param Type - The StateContainer class constructor\n */\n clear<T extends StateContainerConstructor>(Type: T): void {\n const instances = this.ensureInstancesMap(Type);\n // Dispose all instances\n for (const entry of instances.values()) {\n if (!entry.instance.isDisposed) {\n entry.instance.dispose();\n }\n }\n // Clear the Map\n instances.clear();\n }\n\n /**\n * Get reference count for an instance.\n * @param Type - The StateContainer class constructor\n * @param instanceKey - Instance key (defaults to 'default')\n * @returns Current ref count (0 if instance doesn't exist)\n */\n getRefCount<T extends StateContainerConstructor>(\n Type: T,\n instanceKey: string = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY,\n ): number {\n const instances = this.ensureInstancesMap(Type);\n const entry = instances.get(instanceKey);\n return entry?.refCount ?? 0;\n }\n\n /**\n * Check if an instance exists.\n * @param Type - The StateContainer class constructor\n * @param instanceKey - Instance key (defaults to 'default')\n * @returns true if instance exists\n */\n hasInstance<T extends StateContainerConstructor>(\n Type: T,\n instanceKey: string = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY,\n ): boolean {\n const instances = this.ensureInstancesMap(Type);\n return instances.has(instanceKey);\n }\n\n /**\n * Clear all instances from all types (for testing)\n *\n * Iterates all registered types and clears their instances.\n * Also clears type tracking to reset the registry state.\n */\n clearAll(): void {\n // Step 1: Clear instances from each type (while we still have the types list)\n for (const Type of this.types) {\n this.clear(Type);\n }\n // Step 2: Now clear type tracking (resets registry state for tests)\n this.types.clear();\n this.typeConfigs.clear();\n }\n\n /**\n * Get registry statistics for debugging.\n * @returns Object with registeredTypes, totalInstances, and typeBreakdown\n */\n getStats(): {\n registeredTypes: number;\n totalInstances: number;\n typeBreakdown: Record<string, number>;\n } {\n const typeBreakdown: Record<string, number> = {};\n let totalInstances = 0;\n\n // Collect stats from each registered type\n for (const Type of this.types) {\n const typeName = Type.name;\n const instances = this.getInstancesMap(Type);\n const count = instances.size;\n\n typeBreakdown[typeName] = count;\n totalInstances += count;\n }\n\n return {\n registeredTypes: this.types.size,\n totalInstances,\n typeBreakdown,\n };\n }\n\n /**\n * Get all registered types (for plugin system).\n * @returns Array of all registered StateContainer class constructors\n */\n getTypes(): StateContainerConstructor[] {\n return Array.from(this.types);\n }\n\n /**\n * Subscribe to lifecycle events\n * @param event - The lifecycle event to listen for\n * @param listener - The listener function to call when the event occurs\n * @returns Unsubscribe function\n */\n on<E extends LifecycleEvent>(\n event: E,\n listener: LifecycleListener<E>,\n ): () => void {\n if (!this.listeners.has(event)) {\n this.listeners.set(event, new Set());\n }\n const instance = this.listeners.get(event);\n if (!instance) {\n throw new Error(\n `${BLAC_ERROR_PREFIX} Failed to register listener for event '${event}'`,\n );\n }\n\n instance.add(listener as (...args: any[]) => void);\n\n // Return unsubscribe function\n return () => {\n this.listeners.get(event)?.delete(listener as (...args: any[]) => void);\n };\n }\n\n /**\n * Emit lifecycle event to all listeners\n * @internal - Called by StateContainer lifecycle methods\n */\n emit(event: LifecycleEvent, ...args: any[]): void {\n const listeners = this.listeners.get(event);\n if (!listeners || listeners.size === 0) return; // Zero overhead when no listeners\n\n for (const listener of listeners) {\n try {\n listener(...args);\n } catch (error) {\n console.error(\n `${BLAC_ERROR_PREFIX} Listener error for '${event}':`,\n error,\n );\n }\n }\n }\n}\n\n/**\n * Global default registry instance\n */\nexport const globalRegistry = new StateContainerRegistry();\n\n/**\n * Global plugin manager (initialized lazily)\n */\nlet _globalPluginManager: any = null;\n\n/**\n * Get the global plugin manager\n */\nexport function getPluginManager(): any {\n if (!_globalPluginManager) {\n _globalPluginManager = createPluginManager(globalRegistry);\n }\n return _globalPluginManager;\n}\n"],"mappings":";;;;;;;;;;;;AA6BA,IAAa,gBAAb,MAA2B;;;;;CAQzB,YAAY,UAAkC;iCAP5B,IAAI,KAA8B;AAQlD,OAAK,WAAW;AAChB,OAAK,qBAAqB;;;;;;;;CAS5B,QAAQ,QAAoB,SAAuB,EAAE,EAAQ;EAC3D,MAAM,kBAAgC;GACpC,SAAS;GACT,aAAa;GACb,GAAG;GACJ;AAED,MAAI,CAAC,KAAK,mBAAmB,gBAAgB,EAAE;AAC7C,WAAQ,IACN,kBAAkB,OAAO,KAAK,kCAC/B;AACD;;AAGF,MAAI,KAAK,QAAQ,IAAI,OAAO,KAAK,CAC/B,OAAM,IAAI,MAAM,WAAW,OAAO,KAAK,wBAAwB;EAGjE,MAAM,UAAU,KAAK,qBAAqB;AAE1C,OAAK,QAAQ,IAAI,OAAO,MAAM;GAC5B;GACA,QAAQ;GACR;GACD,CAAC;AAEF,MAAI,OAAO,UACT,KAAI;AACF,UAAO,UAAU,QAAQ;WAClB,OAAO;AACd,WAAQ,MACN,mCAAm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,OAAO;AAClB,OAAK,YAAY,OAAO;;;;;;CAO1B,WAIE;EACA,MAAM,gBAAwC,EAAE;EAChD,IAAI,iBAAiB;AAGrB,OAAK,MAAM,QAAQ,KAAK,OAAO;GAC7B,MAAM,WAAW,KAAK;GAEtB,MAAM,QADY,KAAK,gBAAgB,KAAK,CACpB;AAExB,iBAAc,YAAY;AAC1B,qBAAkB;;AAGpB,SAAO;GACL,iBAAiB,KAAK,MAAM;GAC5B;GACA;GACD;;;;;;CAOH,WAAwC;AACtC,SAAO,MAAM,KAAK,KAAK,MAAM;;;;;;;;CAS/B,GACE,OACA,UACY;AACZ,MAAI,CAAC,KAAK,UAAU,IAAI,MAAM,CAC5B,MAAK,UAAU,IAAI,uBAAO,IAAI,KAAK,CAAC;EAEtC,MAAM,WAAW,KAAK,UAAU,IAAI,MAAM;AAC1C,MAAI,CAAC,SACH,OAAM,IAAI,MACR,GAAG,kBAAkB,0CAA0C,MAAM,GACtE;AAGH,WAAS,IAAI,SAAqC;AAGlD,eAAa;AACX,QAAK,UAAU,IAAI,MAAM,EAAE,OAAO,SAAqC;;;;;;;CAQ3E,KAAK,OAAuB,GAAG,MAAmB;EAChD,MAAM,YAAY,KAAK,UAAU,IAAI,MAAM;AAC3C,MAAI,CAAC,aAAa,UAAU,SAAS,EAAG;AAExC,OAAK,MAAM,YAAY,UACrB,KAAI;AACF,YAAS,GAAG,KAAK;WACV,OAAO;AACd,WAAQ,MACN,GAAG,kBAAkB,uBAAuB,MAAM,KAClD,MACD;;;;;;;AAST,MAAa,iBAAiB,IAAI,wBAAwB;;;;AAK1D,IAAI,uBAA4B;;;;AAKhC,SAAgB,mBAAwB;AACtC,KAAI,CAAC,qBACH,wBAAuB,oBAAoB,eAAe;AAE5D,QAAO"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"StateContainerRegistry.js","names":[],"sources":["../src/plugin/PluginManager.ts","../src/utils/static-props.ts","../src/core/StateContainerRegistry.ts"],"sourcesContent":["import type { StateContainer } from '../core/StateContainer';\nimport type { StateContainerRegistry } from '../core/StateContainerRegistry';\nimport type {\n BlacPlugin,\n PluginContext,\n PluginConfig,\n InstanceMetadata,\n} from './BlacPlugin';\n\n/**\n * Internal structure for tracking installed plugins\n * @internal\n */\ninterface InstalledPlugin {\n plugin: BlacPlugin;\n config: PluginConfig;\n context: PluginContext;\n}\n\n/**\n * Manages plugin lifecycle for the BlaC state management system.\n * Plugins receive notifications about state container lifecycle events.\n *\n * @example\n * ```ts\n * const manager = createPluginManager(registry);\n * manager.install(myPlugin, { environment: 'development' });\n * ```\n */\nexport class PluginManager {\n private plugins = new Map<string, InstalledPlugin>();\n private registry: StateContainerRegistry;\n\n /**\n * Create a new PluginManager\n * @param registry - The StateContainerRegistry to monitor for lifecycle events\n */\n constructor(registry: StateContainerRegistry) {\n this.registry = registry;\n this.setupLifecycleHooks();\n }\n\n /**\n * Install a plugin with optional configuration\n * @param plugin - The plugin to install\n * @param config - Optional plugin configuration\n * @throws Error if plugin is already installed\n */\n install(plugin: BlacPlugin, config: PluginConfig = {}): void {\n const effectiveConfig: PluginConfig = {\n enabled: true,\n environment: 'all',\n ...config,\n };\n\n if (!this.shouldEnablePlugin(effectiveConfig)) {\n console.log(\n `[BlaC] Plugin \"${plugin.name}\" skipped (environment mismatch)`,\n );\n return;\n }\n\n if (this.plugins.has(plugin.name)) {\n throw new Error(`Plugin \"${plugin.name}\" is already installed`);\n }\n\n const context = this.createPluginContext();\n\n this.plugins.set(plugin.name, {\n plugin,\n config: effectiveConfig,\n context,\n });\n\n if (plugin.onInstall) {\n try {\n plugin.onInstall(context);\n } catch (error) {\n console.error(\n `[BlaC] Error installing plugin \"${plugin.name}\":`,\n error,\n );\n this.plugins.delete(plugin.name);\n throw error;\n }\n }\n\n console.log(`[BlaC] Plugin \"${plugin.name}\" v${plugin.version} installed`);\n }\n\n /**\n * Uninstall a plugin by name\n * @param pluginName - The name of the plugin to uninstall\n * @throws Error if plugin is not installed\n */\n uninstall(pluginName: string): void {\n const installed = this.plugins.get(pluginName);\n if (!installed) {\n throw new Error(`Plugin \"${pluginName}\" is not installed`);\n }\n\n if (installed.plugin.onUninstall) {\n try {\n installed.plugin.onUninstall();\n } catch (error) {\n console.error(\n `[BlaC] Error uninstalling plugin \"${pluginName}\":`,\n error,\n );\n }\n }\n\n this.plugins.delete(pluginName);\n console.log(`[BlaC] Plugin \"${pluginName}\" uninstalled`);\n }\n\n /**\n * Get an installed plugin by name\n * @param pluginName - The name of the plugin to retrieve\n * @returns The plugin instance or undefined if not found\n */\n getPlugin(pluginName: string): BlacPlugin | undefined {\n return this.plugins.get(pluginName)?.plugin;\n }\n\n /**\n * Get all installed plugins\n * @returns Array of all installed plugins\n */\n getAllPlugins(): BlacPlugin[] {\n return Array.from(this.plugins.values()).map((p) => p.plugin);\n }\n\n /**\n * Check if a plugin is installed\n * @param pluginName - The name of the plugin to check\n * @returns true if the plugin is installed\n */\n hasPlugin(pluginName: string): boolean {\n return this.plugins.has(pluginName);\n }\n\n /**\n * Uninstall all plugins\n */\n clear(): void {\n for (const name of this.plugins.keys()) {\n this.uninstall(name);\n }\n }\n\n /**\n * Setup lifecycle hooks to notify plugins\n */\n private setupLifecycleHooks(): void {\n // Instance created\n this.registry.on('created', (instance) => {\n this.notifyPlugins('onInstanceCreated', instance);\n });\n\n // State changed\n this.registry.on(\n 'stateChanged',\n (instance, previousState, currentState, callstack) => {\n this.notifyPlugins(\n 'onStateChanged',\n instance,\n previousState,\n currentState,\n callstack,\n );\n },\n );\n\n // Instance disposed\n this.registry.on('disposed', (instance) => {\n this.notifyPlugins('onInstanceDisposed', instance);\n });\n }\n\n /**\n * Notify all plugins of a lifecycle event\n */\n private notifyPlugins(hookName: keyof BlacPlugin, ...args: any[]): void {\n for (const { plugin, config, context } of this.plugins.values()) {\n if (!config.enabled) continue;\n\n const hook = plugin[hookName];\n if (typeof hook === 'function') {\n try {\n (hook as any).apply(plugin, [...args, context]);\n } catch (error) {\n console.error(\n `[BlaC] Error in plugin \"${plugin.name}\" ${hookName}:`,\n error,\n );\n }\n }\n }\n }\n\n /**\n * Create plugin context with safe API access\n */\n private createPluginContext(): PluginContext {\n return {\n getInstanceMetadata: (\n instance: StateContainer<any>,\n ): InstanceMetadata => {\n // const TypeClass = instance.constructor as any;\n\n // if (TypeClass.instances) {\n // for (const [key, entry] of TypeClass.instances) {\n // if (entry.instance === instance) {\n // break;\n // }\n // }\n // }\n\n return {\n id: instance.instanceId,\n className: instance.constructor.name,\n isDisposed: instance.isDisposed,\n name: instance.name,\n lastStateChangeTimestamp: instance.lastUpdateTimestamp,\n createdAt: instance.createdAt,\n state: instance.state,\n isIsolated: instance.instanceId.startsWith('isolated-'),\n };\n },\n\n getState: <S extends object = any>(instance: StateContainer<S>): S => {\n return instance.state;\n },\n\n queryInstances: <T extends StateContainer<any>>(\n typeClass: new (...args: any[]) => T,\n ): T[] => {\n return this.registry.getAll(typeClass as any);\n },\n\n getAllTypes: () => {\n return this.registry.getTypes();\n },\n\n getStats: () => {\n return this.registry.getStats();\n },\n };\n }\n\n /**\n * Check if plugin should be enabled based on environment\n */\n private shouldEnablePlugin(config: PluginConfig): boolean {\n if (!config.enabled) return false;\n if (config.environment === 'all') return true;\n\n const currentEnv = this.getCurrentEnvironment();\n return currentEnv === config.environment;\n }\n\n /**\n * Get current environment\n */\n private getCurrentEnvironment(): 'development' | 'production' | 'test' {\n if (typeof process !== 'undefined') {\n if (process.env.NODE_ENV === 'test') return 'test';\n if (process.env.NODE_ENV === 'production') return 'production';\n return 'development';\n }\n return 'development';\n }\n}\n\n/**\n * Create a plugin manager instance\n * @param registry - The StateContainerRegistry to monitor for lifecycle events\n * @returns A new PluginManager instance\n */\nexport function createPluginManager(\n registry: StateContainerRegistry,\n): PluginManager {\n return new PluginManager(registry);\n}\n","/**\n * Utility functions for accessing static properties on StateContainer classes\n */\n\nimport { BLAC_STATIC_PROPS } from '../constants';\nimport { StateContainerConstructor } from '../types/utilities';\n\n/**\n * Get a static property from a class constructor\n * Type-safe helper that avoids (Type as any) casts\n *\n * @param Type - The class constructor\n * @param propName - The property name to access\n * @param defaultValue - Optional default value if property is undefined\n * @returns The property value or default\n */\nexport function getStaticProp<\n V,\n T extends StateContainerConstructor = StateContainerConstructor,\n>(Type: T, propName: string, defaultValue?: V): V | undefined {\n return (Type as any)[propName] ?? defaultValue;\n}\n\n/**\n * Check if a class is marked as isolated.\n * Isolated classes create separate instances per component.\n * @param Type - The class constructor to check\n * @returns true if the class has `static isolated = true`\n */\nexport function isIsolatedClass<T extends StateContainerConstructor>(\n Type: T,\n): boolean {\n return getStaticProp<boolean>(Type, BLAC_STATIC_PROPS.ISOLATED) === true;\n}\n\n/**\n * Check if a class is marked as keepAlive.\n * KeepAlive classes are never auto-disposed when ref count reaches 0.\n * @param Type - The class constructor to check\n * @returns true if the class has `static keepAlive = true`\n */\nexport function isKeepAliveClass<T extends StateContainerConstructor>(\n Type: T,\n): boolean {\n return getStaticProp<boolean>(Type, BLAC_STATIC_PROPS.KEEP_ALIVE) === true;\n}\n\n/**\n * Check if a class should be excluded from DevTools.\n * Used to prevent infinite loops when DevTools tracks itself.\n * @param Type - The class constructor to check\n * @returns true if the class has `static __excludeFromDevTools = true`\n */\nexport function isExcludedFromDevTools<T extends StateContainerConstructor>(\n Type: T,\n): boolean {\n return (\n getStaticProp<boolean>(Type, BLAC_STATIC_PROPS.EXCLUDE_FROM_DEVTOOLS) ===\n true\n );\n}\n","import type { StateContainer, StateContainerConfig } from './StateContainer';\nimport { createPluginManager } from '../plugin/PluginManager';\nimport { getGetterExecutionContext } from '../tracking/tracking-proxy';\nimport { BLAC_DEFAULTS, BLAC_ERROR_PREFIX } from '../constants';\nimport { isIsolatedClass, isKeepAliveClass } from '../utils/static-props';\nimport {\n InstanceReadonlyState,\n StateContainerConstructor,\n} from '../types/utilities';\n\n/**\n * Internal configuration for registered types\n * @internal\n */\ninterface TypeConfig {\n isolated: boolean;\n}\n\n/**\n * Entry in the instance registry, tracking the instance and its reference count\n * @template T - Instance type\n */\nexport interface InstanceEntry<T = any> {\n /** The state container instance */\n instance: T;\n /** Number of active references to this instance */\n refCount: number;\n}\n\n/**\n * Lifecycle events emitted by the registry\n */\nexport type LifecycleEvent = 'created' | 'stateChanged' | 'disposed';\n\n/**\n * Listener function type for each lifecycle event\n * @template E - The lifecycle event type\n */\nexport type LifecycleListener<E extends LifecycleEvent> = E extends 'created'\n ? (container: StateContainer<any>) => void\n : E extends 'stateChanged'\n ? (\n container: StateContainer<any>,\n previousState: any,\n currentState: any,\n callstack?: string,\n ) => void\n : E extends 'disposed'\n ? (container: StateContainer<any>) => void\n : never;\n\n/**\n * Central registry for managing StateContainer instances.\n * Handles instance lifecycle, ref counting, and lifecycle event emission.\n *\n * @example\n * ```ts\n * const registry = new StateContainerRegistry();\n * const instance = registry.acquire(MyBloc); // ownership, must release\n * const other = registry.ensure(OtherBloc); // no ownership, bloc-to-bloc\n * registry.on('stateChanged', (container, prev, next) => {\n * console.log('State changed:', prev, '->', next);\n * });\n * ```\n */\nexport class StateContainerRegistry {\n private readonly instancesByConstructor = new WeakMap<\n StateContainerConstructor,\n Map<string, InstanceEntry>\n >();\n\n private readonly types = new Set<StateContainerConstructor>();\n\n private readonly typeConfigs = new Map<string, TypeConfig>();\n\n private readonly listeners = new Map<\n LifecycleEvent,\n Set<(...args: any[]) => void>\n >();\n\n /**\n * Register a type for lifecycle event tracking\n * @param constructor - The StateContainer class constructor\n */\n registerType<T extends StateContainerConstructor>(constructor: T): void {\n this.types.add(constructor);\n }\n\n /**\n * Register a StateContainer class with configuration\n * @param constructor - The StateContainer class constructor\n * @param isolated - Whether instances should be isolated (component-scoped)\n * @throws Error if type is already registered\n */\n register<T extends StateContainerConstructor>(\n constructor: T,\n isolated = false,\n ): void {\n const className = constructor.name;\n\n if (!isolated && isIsolatedClass(constructor)) {\n isolated = true;\n }\n\n if (this.typeConfigs.has(className)) {\n throw new Error(\n `${BLAC_ERROR_PREFIX} Type \"${className}\" is already registered`,\n );\n }\n\n this.typeConfigs.set(className, { isolated });\n this.registerType(constructor);\n }\n\n private ensureInstancesMap<T extends StateContainerConstructor>(\n Type: T,\n ): Map<string, InstanceEntry> {\n let instances = this.instancesByConstructor.get(Type);\n if (!instances) {\n instances = new Map<string, InstanceEntry>();\n this.instancesByConstructor.set(Type, instances);\n }\n return instances;\n }\n\n /**\n * Get the instances Map for a specific class (public API for stats/debugging)\n */\n getInstancesMap<T extends StateContainerConstructor>(\n Type: T,\n ): Map<string, InstanceEntry> {\n return this.instancesByConstructor.get(Type) || new Map();\n }\n\n private trackExecutionContext(instance: StateContainer<any>): void {\n // Track cross-bloc dependency if we're inside a getter execution\n const context = getGetterExecutionContext();\n if (\n context.tracker &&\n context.currentBloc &&\n context.currentBloc !== instance\n ) {\n // Add this bloc as an external dependency\n context.tracker.externalDependencies.add(instance);\n }\n }\n\n /**\n * Acquire an instance with ref counting (ownership semantics).\n * Creates a new instance if one doesn't exist, or returns existing and increments ref count.\n * You must call `release()` when done to decrement the ref count.\n * @param Type - The StateContainer class constructor\n * @param instanceKey - Instance key (defaults to 'default')\n * @param options - Acquisition options\n * @param options.canCreate - Whether to create new instance if not found (default: true)\n * @param options.countRef - Whether to increment ref count (default: true)\n * @param options.trackExecutionContext - Whether to track cross-bloc dependency (default: false)\n * @returns The state container instance\n */\n acquire<T extends StateContainerConstructor = StateContainerConstructor>(\n Type: T,\n instanceKey: string = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY,\n options: {\n canCreate?: boolean;\n countRef?: boolean;\n trackExecutionContext?: boolean;\n } = {},\n ): InstanceType<T> {\n const {\n canCreate = true,\n countRef = true,\n trackExecutionContext = false,\n } = options;\n // Check if this is an isolated type\n const registryConfig = this.typeConfigs.get(Type.name);\n const isolated = isIsolatedClass(Type) || registryConfig?.isolated === true;\n\n const config: StateContainerConfig = {\n instanceId: instanceKey,\n };\n\n if (isolated && !canCreate) {\n throw new Error(\n `${BLAC_ERROR_PREFIX} Cannot get isolated instance \"${instanceKey}\" of ${Type.name} when creation is disabled.`,\n );\n }\n\n // Isolated: always create new instance (not tracked)\n if (isolated) {\n const instance = new Type() as InstanceType<T>;\n instance.initConfig(config);\n // Register type for lifecycle coordination\n this.registerType(Type);\n if (trackExecutionContext) {\n this.trackExecutionContext(instance);\n }\n return instance;\n }\n\n // Shared: singleton pattern with ref counting\n const instances = this.ensureInstancesMap(Type);\n const entry = instances.get(instanceKey);\n\n // Increment ref count if found, only if counting is enabled or refCount is 0\n if (entry && (countRef || entry.refCount === 0)) {\n entry.refCount++;\n }\n\n if (entry) {\n if (trackExecutionContext) {\n this.trackExecutionContext(entry.instance);\n }\n return entry.instance;\n }\n\n if (!canCreate) {\n throw new Error(\n `${BLAC_ERROR_PREFIX} ${Type.name} instance \"${instanceKey}\" not found and creation is disabled.`,\n );\n }\n\n // Create new shared instance\n const instance = new Type() as InstanceType<T>;\n instance.initConfig(config);\n instances.set(instanceKey, { instance, refCount: 1 });\n\n // Register type for lifecycle coordination\n this.registerType(Type);\n\n if (trackExecutionContext) {\n this.trackExecutionContext(instance);\n }\n return instance;\n }\n\n /**\n * Borrow an existing instance without incrementing ref count (borrowing semantics).\n * Tracks cross-bloc dependency for reactive updates.\n * @param Type - The StateContainer class constructor\n * @param instanceKey - Instance key (defaults to 'default')\n * @returns The state container instance\n * @throws Error if instance doesn't exist\n */\n borrow<T extends StateContainerConstructor = StateContainerConstructor>(\n Type: T,\n instanceKey: string = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY,\n ): InstanceType<T> {\n return this.acquire(Type, instanceKey, {\n canCreate: false,\n trackExecutionContext: true,\n });\n }\n\n /**\n * Safely borrow an existing instance (borrowing semantics with error handling).\n * Returns discriminated union for type-safe conditional access.\n * @param Type - The StateContainer class constructor\n * @param instanceKey - Instance key (defaults to 'default')\n * @returns Discriminated union with either the instance or an error\n */\n borrowSafe<T extends StateContainerConstructor = StateContainerConstructor>(\n Type: T,\n instanceKey: string = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY,\n ):\n | { error: Error; instance: null }\n | { error: null; instance: InstanceType<T> } {\n try {\n const instance = this.borrow(Type, instanceKey);\n return { error: null, instance };\n } catch (error: any) {\n return { error, instance: null };\n }\n }\n\n /**\n * Ensure an instance exists without taking ownership (for bloc-to-bloc communication).\n * Gets existing instance OR creates it if it doesn't exist, without incrementing ref count.\n * Tracks cross-bloc dependency for reactive updates.\n *\n * Use this in bloc-to-bloc communication when you need to ensure an instance exists\n * but don't want to claim ownership (no ref count increment).\n * @param Type - The StateContainer class constructor\n * @param instanceKey - Instance key (defaults to 'default')\n * @returns The state container instance\n */\n ensure<T extends StateContainerConstructor = StateContainerConstructor>(\n Type: T,\n instanceKey: string = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY,\n ): InstanceType<T> {\n return this.acquire(Type, instanceKey, {\n canCreate: true,\n countRef: false,\n trackExecutionContext: true,\n });\n }\n\n /**\n * Release a reference to an instance.\n * Decrements ref count and disposes when it reaches 0 (unless keepAlive).\n * @param Type - The StateContainer class constructor\n * @param instanceKey - Instance key (defaults to 'default')\n * @param forceDispose - Force immediate disposal regardless of ref count\n */\n release<T extends StateContainerConstructor>(\n Type: T,\n instanceKey: string = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY,\n forceDispose = false,\n ): void {\n const instances = this.ensureInstancesMap(Type);\n const entry = instances.get(instanceKey);\n\n if (!entry) return;\n\n // Force dispose immediately\n if (forceDispose) {\n if (!entry.instance.isDisposed) {\n entry.instance.dispose();\n }\n instances.delete(instanceKey);\n return;\n }\n\n // Decrement ref count\n entry.refCount--;\n\n // Check static keepAlive property\n const keepAlive = isKeepAliveClass(Type);\n\n // Auto-dispose when ref count reaches 0 (unless keepAlive)\n if (entry.refCount <= 0 && !keepAlive) {\n if (!entry.instance.isDisposed) {\n entry.instance.dispose();\n }\n instances.delete(instanceKey);\n }\n }\n\n /**\n * Get all instances of a specific type.\n * @param Type - The StateContainer class constructor\n * @returns Array of all instances\n */\n getAll<T extends StateContainerConstructor>(\n Type: T,\n ): InstanceReadonlyState<T>[] {\n const instances = this.ensureInstancesMap(Type);\n const result: InstanceReadonlyState<T>[] = [];\n for (const entry of instances.values()) {\n result.push(entry.instance);\n }\n return result;\n }\n\n /**\n * Safely iterate over all instances of a type.\n * Skips disposed instances and catches callback errors.\n * @param Type - The StateContainer class constructor\n * @param callback - Function to call for each instance\n */\n forEach<T extends StateContainerConstructor>(\n Type: T,\n callback: (instance: InstanceReadonlyState<T>) => void,\n ): void {\n const instances = this.ensureInstancesMap(Type);\n for (const entry of instances.values()) {\n const instance = entry.instance;\n if (!instance.isDisposed) {\n try {\n callback(instance);\n } catch (error) {\n console.error(\n `${BLAC_ERROR_PREFIX} forEach callback error for ${Type.name}:`,\n error,\n );\n }\n }\n }\n }\n\n /**\n * Clear all instances of a specific type (disposes them).\n * @param Type - The StateContainer class constructor\n */\n clear<T extends StateContainerConstructor>(Type: T): void {\n const instances = this.ensureInstancesMap(Type);\n // Dispose all instances\n for (const entry of instances.values()) {\n if (!entry.instance.isDisposed) {\n entry.instance.dispose();\n }\n }\n // Clear the Map\n instances.clear();\n }\n\n /**\n * Get reference count for an instance.\n * @param Type - The StateContainer class constructor\n * @param instanceKey - Instance key (defaults to 'default')\n * @returns Current ref count (0 if instance doesn't exist)\n */\n getRefCount<T extends StateContainerConstructor>(\n Type: T,\n instanceKey: string = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY,\n ): number {\n const instances = this.ensureInstancesMap(Type);\n const entry = instances.get(instanceKey);\n return entry?.refCount ?? 0;\n }\n\n /**\n * Check if an instance exists.\n * @param Type - The StateContainer class constructor\n * @param instanceKey - Instance key (defaults to 'default')\n * @returns true if instance exists\n */\n hasInstance<T extends StateContainerConstructor>(\n Type: T,\n instanceKey: string = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY,\n ): boolean {\n const instances = this.ensureInstancesMap(Type);\n return instances.has(instanceKey);\n }\n\n /**\n * Clear all instances from all types (for testing)\n *\n * Iterates all registered types and clears their instances.\n * Also clears type tracking to reset the registry state.\n */\n clearAll(): void {\n // Step 1: Clear instances from each type (while we still have the types list)\n for (const Type of this.types) {\n this.clear(Type);\n }\n // Step 2: Now clear type tracking (resets registry state for tests)\n this.types.clear();\n this.typeConfigs.clear();\n }\n\n /**\n * Get registry statistics for debugging.\n * @returns Object with registeredTypes, totalInstances, and typeBreakdown\n */\n getStats(): {\n registeredTypes: number;\n totalInstances: number;\n typeBreakdown: Record<string, number>;\n } {\n const typeBreakdown: Record<string, number> = {};\n let totalInstances = 0;\n\n // Collect stats from each registered type\n for (const Type of this.types) {\n const typeName = Type.name;\n const instances = this.getInstancesMap(Type);\n const count = instances.size;\n\n typeBreakdown[typeName] = count;\n totalInstances += count;\n }\n\n return {\n registeredTypes: this.types.size,\n totalInstances,\n typeBreakdown,\n };\n }\n\n /**\n * Get all registered types (for plugin system).\n * @returns Array of all registered StateContainer class constructors\n */\n getTypes(): StateContainerConstructor[] {\n return Array.from(this.types);\n }\n\n /**\n * Subscribe to lifecycle events\n * @param event - The lifecycle event to listen for\n * @param listener - The listener function to call when the event occurs\n * @returns Unsubscribe function\n */\n on<E extends LifecycleEvent>(\n event: E,\n listener: LifecycleListener<E>,\n ): () => void {\n if (!this.listeners.has(event)) {\n this.listeners.set(event, new Set());\n }\n const instance = this.listeners.get(event);\n if (!instance) {\n throw new Error(\n `${BLAC_ERROR_PREFIX} Failed to register listener for event '${event}'`,\n );\n }\n\n instance.add(listener as (...args: any[]) => void);\n\n // Return unsubscribe function\n return () => {\n this.listeners.get(event)?.delete(listener as (...args: any[]) => void);\n };\n }\n\n /**\n * Emit lifecycle event to all listeners\n * @internal - Called by StateContainer lifecycle methods\n */\n emit(event: LifecycleEvent, ...args: any[]): void {\n const listeners = this.listeners.get(event);\n if (!listeners || listeners.size === 0) return; // Zero overhead when no listeners\n\n for (const listener of listeners) {\n try {\n listener(...args);\n } catch (error) {\n console.error(\n `${BLAC_ERROR_PREFIX} Listener error for '${event}':`,\n error,\n );\n }\n }\n }\n}\n\n/**\n * Global default registry instance\n */\nexport const globalRegistry = new StateContainerRegistry();\n\n/**\n * Global plugin manager (initialized lazily)\n */\nlet _globalPluginManager: any = null;\n\n/**\n * Get the global plugin manager\n */\nexport function getPluginManager(): any {\n if (!_globalPluginManager) {\n _globalPluginManager = createPluginManager(globalRegistry);\n }\n return _globalPluginManager;\n}\n"],"mappings":";;;;;;;;;;;;;AA6BA,IAAa,gBAAb,MAA2B;;;;;CAQzB,YAAY,UAAkC;iCAP5B,IAAI,KAA8B;AAQlD,OAAK,WAAW;AAChB,OAAK,qBAAqB;;;;;;;;CAS5B,QAAQ,QAAoB,SAAuB,EAAE,EAAQ;EAC3D,MAAM,kBAAgC;GACpC,SAAS;GACT,aAAa;GACb,GAAG;GACJ;AAED,MAAI,CAAC,KAAK,mBAAmB,gBAAgB,EAAE;AAC7C,WAAQ,IACN,kBAAkB,OAAO,KAAK,kCAC/B;AACD;;AAGF,MAAI,KAAK,QAAQ,IAAI,OAAO,KAAK,CAC/B,OAAM,IAAI,MAAM,WAAW,OAAO,KAAK,wBAAwB;EAGjE,MAAM,UAAU,KAAK,qBAAqB;AAE1C,OAAK,QAAQ,IAAI,OAAO,MAAM;GAC5B;GACA,QAAQ;GACR;GACD,CAAC;AAEF,MAAI,OAAO,UACT,KAAI;AACF,UAAO,UAAU,QAAQ;WAClB,OAAO;AACd,WAAQ,MACN,mCAAmC,OAAO,KAAK,KAC/C,MACD;AACD,QAAK,QAAQ,OAAO,OAAO,KAAK;AAChC,SAAM;;AAIV,UAAQ,IAAI,kBAAkB,OAAO,KAAK,KAAK,OAAO,QAAQ,YAAY;;;;;;;CAQ5E,UAAU,YAA0B;EAClC,MAAM,YAAY,KAAK,QAAQ,IAAI,WAAW;AAC9C,MAAI,CAAC,UACH,OAAM,IAAI,MAAM,WAAW,WAAW,oBAAoB;AAG5D,MAAI,UAAU,OAAO,YACnB,KAAI;AACF,aAAU,OAAO,aAAa;WACvB,OAAO;AACd,WAAQ,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OACA,UACY;AACZ,MAAI,CAAC,KAAK,UAAU,IAAI,MAAM,CAC5B,MAAK,UAAU,IAAI,uBAAO,IAAI,KAAK,CAAC;EAEtC,MAAM,WAAW,KAAK,UAAU,IAAI,MAAM;AAC1C,MAAI,CAAC,SACH,OAAM,IAAI,MACR,GAAG,kBAAkB,0CAA0C,MAAM,GACtE;AAGH,WAAS,IAAI,SAAqC;AAGlD,eAAa;AACX,QAAK,UAAU,IAAI,MAAM,EAAE,OAAO,SAAqC;;;;;;;CAQ3E,KAAK,OAAuB,GAAG,MAAmB;EAChD,MAAM,YAAY,KAAK,UAAU,IAAI,MAAM;AAC3C,MAAI,CAAC,aAAa,UAAU,SAAS,EAAG;AAExC,OAAK,MAAM,YAAY,UACrB,KAAI;AACF,YAAS,GAAG,KAAK;WACV,OAAO;AACd,WAAQ,MACN,GAAG,kBAAkB,uBAAuB,MAAM,KAClD,MACD;;;;;;;AAST,MAAa,iBAAiB,IAAI,wBAAwB;;;;AAK1D,IAAI,uBAA4B;;;;AAKhC,SAAgB,mBAAwB;AACtC,KAAI,CAAC,qBACH,wBAAuB,oBAAoB,eAAe;AAE5D,QAAO"}
|
|
1
|
+
{"version":3,"file":"StateContainerRegistry.js","names":[],"sources":["../src/plugin/PluginManager.ts","../src/constants.ts","../src/utils/static-props.ts","../src/core/StateContainerRegistry.ts"],"sourcesContent":["import type { StateContainer } from '../core/StateContainer';\nimport type { StateContainerRegistry } from '../core/StateContainerRegistry';\nimport type {\n BlacPlugin,\n PluginContext,\n PluginConfig,\n InstanceMetadata,\n} from './BlacPlugin';\n\n/**\n * Internal structure for tracking installed plugins\n * @internal\n */\ninterface InstalledPlugin {\n plugin: BlacPlugin;\n config: PluginConfig;\n context: PluginContext;\n}\n\n/**\n * Manages plugin lifecycle for the BlaC state management system.\n * Plugins receive notifications about state container lifecycle events.\n *\n * @example\n * ```ts\n * const manager = createPluginManager(registry);\n * manager.install(myPlugin, { environment: 'development' });\n * ```\n */\nexport class PluginManager {\n private plugins = new Map<string, InstalledPlugin>();\n private registry: StateContainerRegistry;\n\n /**\n * Create a new PluginManager\n * @param registry - The StateContainerRegistry to monitor for lifecycle events\n */\n constructor(registry: StateContainerRegistry) {\n this.registry = registry;\n this.setupLifecycleHooks();\n }\n\n /**\n * Install a plugin with optional configuration\n * @param plugin - The plugin to install\n * @param config - Optional plugin configuration\n * @throws Error if plugin is already installed\n */\n install(plugin: BlacPlugin, config: PluginConfig = {}): void {\n const effectiveConfig: PluginConfig = {\n enabled: true,\n environment: 'all',\n ...config,\n };\n\n if (!this.shouldEnablePlugin(effectiveConfig)) {\n console.log(\n `[BlaC] Plugin \"${plugin.name}\" skipped (environment mismatch)`,\n );\n return;\n }\n\n if (this.plugins.has(plugin.name)) {\n throw new Error(`Plugin \"${plugin.name}\" is already installed`);\n }\n\n const context = this.createPluginContext();\n\n this.plugins.set(plugin.name, {\n plugin,\n config: effectiveConfig,\n context,\n });\n\n if (plugin.onInstall) {\n try {\n plugin.onInstall(context);\n } catch (error) {\n console.error(\n `[BlaC] Error installing plugin \"${plugin.name}\":`,\n error,\n );\n this.plugins.delete(plugin.name);\n throw error;\n }\n }\n\n console.log(`[BlaC] Plugin \"${plugin.name}\" v${plugin.version} installed`);\n }\n\n /**\n * Uninstall a plugin by name\n * @param pluginName - The name of the plugin to uninstall\n * @throws Error if plugin is not installed\n */\n uninstall(pluginName: string): void {\n const installed = this.plugins.get(pluginName);\n if (!installed) {\n throw new Error(`Plugin \"${pluginName}\" is not installed`);\n }\n\n if (installed.plugin.onUninstall) {\n try {\n installed.plugin.onUninstall();\n } catch (error) {\n console.error(\n `[BlaC] Error uninstalling plugin \"${pluginName}\":`,\n error,\n );\n }\n }\n\n this.plugins.delete(pluginName);\n console.log(`[BlaC] Plugin \"${pluginName}\" uninstalled`);\n }\n\n /**\n * Get an installed plugin by name\n * @param pluginName - The name of the plugin to retrieve\n * @returns The plugin instance or undefined if not found\n */\n getPlugin(pluginName: string): BlacPlugin | undefined {\n return this.plugins.get(pluginName)?.plugin;\n }\n\n /**\n * Get all installed plugins\n * @returns Array of all installed plugins\n */\n getAllPlugins(): BlacPlugin[] {\n return Array.from(this.plugins.values()).map((p) => p.plugin);\n }\n\n /**\n * Check if a plugin is installed\n * @param pluginName - The name of the plugin to check\n * @returns true if the plugin is installed\n */\n hasPlugin(pluginName: string): boolean {\n return this.plugins.has(pluginName);\n }\n\n /**\n * Uninstall all plugins\n */\n clear(): void {\n for (const name of this.plugins.keys()) {\n this.uninstall(name);\n }\n }\n\n /**\n * Setup lifecycle hooks to notify plugins\n */\n private setupLifecycleHooks(): void {\n // Instance created\n this.registry.on('created', (instance) => {\n this.notifyPlugins('onInstanceCreated', instance);\n });\n\n // State changed\n this.registry.on(\n 'stateChanged',\n (instance, previousState, currentState, callstack) => {\n this.notifyPlugins(\n 'onStateChanged',\n instance,\n previousState,\n currentState,\n callstack,\n );\n },\n );\n\n // Instance disposed\n this.registry.on('disposed', (instance) => {\n this.notifyPlugins('onInstanceDisposed', instance);\n });\n }\n\n /**\n * Notify all plugins of a lifecycle event\n */\n private notifyPlugins(hookName: keyof BlacPlugin, ...args: any[]): void {\n for (const { plugin, config, context } of this.plugins.values()) {\n if (!config.enabled) continue;\n\n const hook = plugin[hookName];\n if (typeof hook === 'function') {\n try {\n (hook as any).apply(plugin, [...args, context]);\n } catch (error) {\n console.error(\n `[BlaC] Error in plugin \"${plugin.name}\" ${hookName}:`,\n error,\n );\n }\n }\n }\n }\n\n /**\n * Create plugin context with safe API access\n */\n private createPluginContext(): PluginContext {\n return {\n getInstanceMetadata: (\n instance: StateContainer<any>,\n ): InstanceMetadata => {\n return {\n id: instance.instanceId,\n className: instance.constructor.name,\n isDisposed: instance.isDisposed,\n name: instance.name,\n lastStateChangeTimestamp: instance.lastUpdateTimestamp,\n createdAt: instance.createdAt,\n state: instance.state,\n isIsolated: instance.instanceId.startsWith('isolated-'),\n };\n },\n\n getState: <S extends object = any>(instance: StateContainer<S>): S => {\n return instance.state;\n },\n\n queryInstances: <T extends StateContainer<any>>(\n typeClass: new (...args: any[]) => T,\n ): T[] => {\n return this.registry.getAll(typeClass as any);\n },\n\n getAllTypes: () => {\n return this.registry.getTypes();\n },\n\n getStats: () => {\n return this.registry.getStats();\n },\n };\n }\n\n /**\n * Check if plugin should be enabled based on environment\n */\n private shouldEnablePlugin(config: PluginConfig): boolean {\n if (!config.enabled) return false;\n if (config.environment === 'all') return true;\n\n const currentEnv = this.getCurrentEnvironment();\n return currentEnv === config.environment;\n }\n\n /**\n * Get current environment\n */\n private getCurrentEnvironment(): 'development' | 'production' | 'test' {\n if (typeof process !== 'undefined') {\n if (process.env.NODE_ENV === 'test') return 'test';\n if (process.env.NODE_ENV === 'production') return 'production';\n return 'development';\n }\n return 'development';\n }\n}\n\n/**\n * Create a plugin manager instance\n * @param registry - The StateContainerRegistry to monitor for lifecycle events\n * @returns A new PluginManager instance\n */\nexport function createPluginManager(\n registry: StateContainerRegistry,\n): PluginManager {\n return new PluginManager(registry);\n}\n","/**\n * Default configuration constants for BlaC\n *\n * Centralized location for all magic numbers and default values.\n */\n\n/**\n * Default configuration constants for BlaC\n */\nexport const BLAC_DEFAULTS = {\n /**\n * Default instance key for shared instances\n */\n DEFAULT_INSTANCE_KEY: 'default',\n\n /**\n * Maximum getter nesting depth (prevents infinite recursion)\n */\n MAX_GETTER_DEPTH: 10,\n\n /**\n * Default cleanup interval for subscriptions (30 seconds)\n */\n CLEANUP_INTERVAL_MS: 30_000,\n\n /**\n * Cleanup interval for weak reference stage (10 seconds)\n */\n WEAKREF_CLEANUP_INTERVAL_MS: 10_000,\n\n /**\n * Default maximum subscriptions per container\n */\n MAX_SUBSCRIPTIONS: 1_000,\n\n /**\n * Maximum subscriptions for high-performance mode\n */\n MAX_SUBSCRIPTIONS_HIGH_PERF: 10_000,\n\n /**\n * Default timeout for pipeline execution (5 seconds)\n */\n PIPELINE_TIMEOUT_MS: 5_000,\n\n /**\n * Cleanup interval for high-performance mode (5 seconds)\n */\n CLEANUP_INTERVAL_HIGH_PERF_MS: 5_000,\n\n /**\n * Maximum number of stages in a pipeline\n */\n MAX_PIPELINE_STAGES: 30,\n} as const;\n\n/**\n * Static property names for StateContainer classes\n * Used for feature flags and configuration on bloc classes\n */\nexport const BLAC_STATIC_PROPS = {\n /**\n * Mark a bloc as isolated (each component gets its own instance)\n */\n ISOLATED: 'isolated',\n\n /**\n * Mark a bloc to never be auto-disposed (kept alive permanently)\n */\n KEEP_ALIVE: 'keepAlive',\n\n /**\n * Exclude a bloc from DevTools reporting (prevents infinite loops)\n */\n EXCLUDE_FROM_DEVTOOLS: '__excludeFromDevTools',\n} as const;\n\n/**\n * ID generation patterns and constants\n */\nexport const BLAC_ID_PATTERNS = {\n /**\n * Prefix for isolated instance keys\n */\n ISOLATED_PREFIX: 'isolated-',\n\n /**\n * Length of generated ID portion (9 characters from base36)\n */\n ID_LENGTH: 9,\n} as const;\n\n/**\n * Standard error message prefix\n */\nexport const BLAC_ERROR_PREFIX = '[BlaC]' as const;\n","/**\n * Utility functions for accessing static properties on StateContainer classes\n */\n\nimport { BLAC_STATIC_PROPS } from '../constants';\nimport { StateContainerConstructor } from '../types/utilities';\n\n/**\n * Get a static property from a class constructor\n * Type-safe helper that avoids (Type as any) casts\n *\n * @param Type - The class constructor\n * @param propName - The property name to access\n * @param defaultValue - Optional default value if property is undefined\n * @returns The property value or default\n */\nexport function getStaticProp<\n V,\n T extends StateContainerConstructor = StateContainerConstructor,\n>(Type: T, propName: string, defaultValue?: V): V | undefined {\n return (Type as any)[propName] ?? defaultValue;\n}\n\n/**\n * Check if a class is marked as isolated.\n * Isolated classes create separate instances per component.\n * @param Type - The class constructor to check\n * @returns true if the class has `static isolated = true`\n */\nexport function isIsolatedClass<T extends StateContainerConstructor>(\n Type: T,\n): boolean {\n return getStaticProp<boolean>(Type, BLAC_STATIC_PROPS.ISOLATED) === true;\n}\n\n/**\n * Check if a class is marked as keepAlive.\n * KeepAlive classes are never auto-disposed when ref count reaches 0.\n * @param Type - The class constructor to check\n * @returns true if the class has `static keepAlive = true`\n */\nexport function isKeepAliveClass<T extends StateContainerConstructor>(\n Type: T,\n): boolean {\n return getStaticProp<boolean>(Type, BLAC_STATIC_PROPS.KEEP_ALIVE) === true;\n}\n\n/**\n * Check if a class should be excluded from DevTools.\n * Used to prevent infinite loops when DevTools tracks itself.\n * @param Type - The class constructor to check\n * @returns true if the class has `static __excludeFromDevTools = true`\n */\nexport function isExcludedFromDevTools<T extends StateContainerConstructor>(\n Type: T,\n): boolean {\n return (\n getStaticProp<boolean>(Type, BLAC_STATIC_PROPS.EXCLUDE_FROM_DEVTOOLS) ===\n true\n );\n}\n","import type { StateContainer, StateContainerConfig } from './StateContainer';\nimport { createPluginManager } from '../plugin/PluginManager';\nimport { BLAC_DEFAULTS, BLAC_ERROR_PREFIX } from '../constants';\nimport { isIsolatedClass, isKeepAliveClass } from '../utils/static-props';\nimport {\n InstanceReadonlyState,\n StateContainerConstructor,\n} from '../types/utilities';\n\n/**\n * Internal configuration for registered types\n * @internal\n */\ninterface TypeConfig {\n isolated: boolean;\n}\n\n/**\n * Entry in the instance registry, tracking the instance and its reference count\n * @template T - Instance type\n */\nexport interface InstanceEntry<T = any> {\n /** The state container instance */\n instance: T;\n /** Number of active references to this instance */\n refCount: number;\n}\n\n/**\n * Lifecycle events emitted by the registry\n */\nexport type LifecycleEvent = 'created' | 'stateChanged' | 'disposed';\n\n/**\n * Listener function type for each lifecycle event\n * @template E - The lifecycle event type\n */\nexport type LifecycleListener<E extends LifecycleEvent> = E extends 'created'\n ? (container: StateContainer<any>) => void\n : E extends 'stateChanged'\n ? (\n container: StateContainer<any>,\n previousState: any,\n currentState: any,\n callstack?: string,\n ) => void\n : E extends 'disposed'\n ? (container: StateContainer<any>) => void\n : never;\n\n/**\n * Central registry for managing StateContainer instances.\n * Handles instance lifecycle, ref counting, and lifecycle event emission.\n *\n * @example\n * ```ts\n * const registry = new StateContainerRegistry();\n * const instance = registry.acquire(MyBloc); // ownership, must release\n * const other = registry.ensure(OtherBloc); // no ownership, bloc-to-bloc\n * registry.on('stateChanged', (container, prev, next) => {\n * console.log('State changed:', prev, '->', next);\n * });\n * ```\n */\nexport class StateContainerRegistry {\n private readonly instancesByConstructor = new WeakMap<\n StateContainerConstructor,\n Map<string, InstanceEntry>\n >();\n\n private readonly types = new Set<StateContainerConstructor>();\n\n private readonly typeConfigs = new Map<string, TypeConfig>();\n\n private readonly listeners = new Map<\n LifecycleEvent,\n Set<(...args: any[]) => void>\n >();\n\n /**\n * Register a type for lifecycle event tracking\n * @param constructor - The StateContainer class constructor\n */\n registerType<T extends StateContainerConstructor>(constructor: T): void {\n this.types.add(constructor);\n }\n\n /**\n * Register a StateContainer class with configuration\n * @param constructor - The StateContainer class constructor\n * @param isolated - Whether instances should be isolated (component-scoped)\n * @throws Error if type is already registered\n */\n register<T extends StateContainerConstructor>(\n constructor: T,\n isolated = false,\n ): void {\n const className = constructor.name;\n\n if (!isolated && isIsolatedClass(constructor)) {\n isolated = true;\n }\n\n if (this.typeConfigs.has(className)) {\n throw new Error(\n `${BLAC_ERROR_PREFIX} Type \"${className}\" is already registered`,\n );\n }\n\n this.typeConfigs.set(className, { isolated });\n this.registerType(constructor);\n }\n\n private ensureInstancesMap<T extends StateContainerConstructor>(\n Type: T,\n ): Map<string, InstanceEntry> {\n let instances = this.instancesByConstructor.get(Type);\n if (!instances) {\n instances = new Map<string, InstanceEntry>();\n this.instancesByConstructor.set(Type, instances);\n }\n return instances;\n }\n\n /**\n * Get the instances Map for a specific class (public API for stats/debugging)\n */\n getInstancesMap<T extends StateContainerConstructor>(\n Type: T,\n ): Map<string, InstanceEntry> {\n return this.instancesByConstructor.get(Type) || new Map();\n }\n\n /**\n * Acquire an instance with ref counting (ownership semantics).\n * Creates a new instance if one doesn't exist, or returns existing and increments ref count.\n * You must call `release()` when done to decrement the ref count.\n * @param Type - The StateContainer class constructor\n * @param instanceKey - Instance key (defaults to 'default')\n * @param options - Acquisition options\n * @param options.canCreate - Whether to create new instance if not found (default: true)\n * @param options.countRef - Whether to increment ref count (default: true)\n * @returns The state container instance\n */\n acquire<T extends StateContainerConstructor = StateContainerConstructor>(\n Type: T,\n instanceKey: string = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY,\n options: {\n canCreate?: boolean;\n countRef?: boolean;\n } = {},\n ): InstanceType<T> {\n const { canCreate = true, countRef = true } = options;\n // Check if this is an isolated type\n const registryConfig = this.typeConfigs.get(Type.name);\n const isolated = isIsolatedClass(Type) || registryConfig?.isolated === true;\n\n const config: StateContainerConfig = {\n instanceId: instanceKey,\n };\n\n if (isolated && !canCreate) {\n throw new Error(\n `${BLAC_ERROR_PREFIX} Cannot get isolated instance \"${instanceKey}\" of ${Type.name} when creation is disabled.`,\n );\n }\n\n // Isolated: always create new instance (not tracked)\n if (isolated) {\n const instance = new Type() as InstanceType<T>;\n instance.initConfig(config);\n // Register type for lifecycle coordination\n this.registerType(Type);\n return instance;\n }\n\n // Shared: singleton pattern with ref counting\n const instances = this.ensureInstancesMap(Type);\n let entry = instances.get(instanceKey);\n\n // Detect stale disposed entries (disposed directly, not through release)\n if (entry?.instance.isDisposed) {\n instances.delete(instanceKey);\n entry = undefined;\n }\n\n if (entry && countRef) {\n entry.refCount++;\n }\n\n if (entry) {\n return entry.instance;\n }\n\n if (!canCreate) {\n throw new Error(\n `${BLAC_ERROR_PREFIX} ${Type.name} instance \"${instanceKey}\" not found and creation is disabled.`,\n );\n }\n\n // Create new shared instance\n const instance = new Type() as InstanceType<T>;\n instance.initConfig(config);\n instances.set(instanceKey, { instance, refCount: 1 });\n\n // Register type for lifecycle coordination\n this.registerType(Type);\n\n return instance;\n }\n\n /**\n * Borrow an existing instance without incrementing ref count (borrowing semantics).\n * Tracks cross-bloc dependency for reactive updates.\n * @param Type - The StateContainer class constructor\n * @param instanceKey - Instance key (defaults to 'default')\n * @returns The state container instance\n * @throws Error if instance doesn't exist\n */\n borrow<T extends StateContainerConstructor = StateContainerConstructor>(\n Type: T,\n instanceKey: string = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY,\n ): InstanceType<T> {\n return this.acquire(Type, instanceKey, {\n canCreate: false,\n countRef: false,\n });\n }\n\n /**\n * Safely borrow an existing instance (borrowing semantics with error handling).\n * Returns discriminated union for type-safe conditional access.\n * @param Type - The StateContainer class constructor\n * @param instanceKey - Instance key (defaults to 'default')\n * @returns Discriminated union with either the instance or an error\n */\n borrowSafe<T extends StateContainerConstructor = StateContainerConstructor>(\n Type: T,\n instanceKey: string = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY,\n ):\n | { error: Error; instance: null }\n | { error: null; instance: InstanceType<T> } {\n try {\n const instance = this.borrow(Type, instanceKey);\n return { error: null, instance };\n } catch (error: any) {\n return { error, instance: null };\n }\n }\n\n /**\n * Ensure an instance exists without taking ownership (for bloc-to-bloc communication).\n * Gets existing instance OR creates it if it doesn't exist, without incrementing ref count.\n * Tracks cross-bloc dependency for reactive updates.\n *\n * Use this in bloc-to-bloc communication when you need to ensure an instance exists\n * but don't want to claim ownership (no ref count increment).\n * @param Type - The StateContainer class constructor\n * @param instanceKey - Instance key (defaults to 'default')\n * @returns The state container instance\n */\n ensure<T extends StateContainerConstructor = StateContainerConstructor>(\n Type: T,\n instanceKey: string = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY,\n ): InstanceType<T> {\n return this.acquire(Type, instanceKey, {\n canCreate: true,\n countRef: false,\n });\n }\n\n /**\n * Release a reference to an instance.\n * Decrements ref count and disposes when it reaches 0 (unless keepAlive).\n * @param Type - The StateContainer class constructor\n * @param instanceKey - Instance key (defaults to 'default')\n * @param forceDispose - Force immediate disposal regardless of ref count\n */\n release<T extends StateContainerConstructor>(\n Type: T,\n instanceKey: string = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY,\n forceDispose = false,\n ): void {\n const instances = this.ensureInstancesMap(Type);\n const entry = instances.get(instanceKey);\n\n if (!entry) return;\n\n // Force dispose immediately\n if (forceDispose) {\n if (!entry.instance.isDisposed) {\n entry.instance.dispose();\n }\n instances.delete(instanceKey);\n return;\n }\n\n // Decrement ref count\n entry.refCount--;\n\n // Check static keepAlive property\n const keepAlive = isKeepAliveClass(Type);\n\n // Auto-dispose when ref count reaches 0 (unless keepAlive)\n if (entry.refCount <= 0 && !keepAlive) {\n if (!entry.instance.isDisposed) {\n entry.instance.dispose();\n }\n instances.delete(instanceKey);\n }\n }\n\n /**\n * Get all instances of a specific type.\n * @param Type - The StateContainer class constructor\n * @returns Array of all instances\n */\n getAll<T extends StateContainerConstructor>(\n Type: T,\n ): InstanceReadonlyState<T>[] {\n const instances = this.ensureInstancesMap(Type);\n const result: InstanceReadonlyState<T>[] = [];\n for (const entry of instances.values()) {\n result.push(entry.instance);\n }\n return result;\n }\n\n /**\n * Safely iterate over all instances of a type.\n * Skips disposed instances and catches callback errors.\n * @param Type - The StateContainer class constructor\n * @param callback - Function to call for each instance\n */\n forEach<T extends StateContainerConstructor>(\n Type: T,\n callback: (instance: InstanceReadonlyState<T>) => void,\n ): void {\n const instances = this.ensureInstancesMap(Type);\n for (const entry of instances.values()) {\n const instance = entry.instance;\n if (!instance.isDisposed) {\n try {\n callback(instance);\n } catch (error) {\n console.error(\n `${BLAC_ERROR_PREFIX} forEach callback error for ${Type.name}:`,\n error,\n );\n }\n }\n }\n }\n\n /**\n * Clear all instances of a specific type (disposes them).\n * @param Type - The StateContainer class constructor\n */\n clear<T extends StateContainerConstructor>(Type: T): void {\n const instances = this.ensureInstancesMap(Type);\n // Dispose all instances\n for (const entry of instances.values()) {\n if (!entry.instance.isDisposed) {\n entry.instance.dispose();\n }\n }\n // Clear the Map\n instances.clear();\n }\n\n /**\n * Get reference count for an instance.\n * @param Type - The StateContainer class constructor\n * @param instanceKey - Instance key (defaults to 'default')\n * @returns Current ref count (0 if instance doesn't exist)\n */\n getRefCount<T extends StateContainerConstructor>(\n Type: T,\n instanceKey: string = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY,\n ): number {\n const instances = this.ensureInstancesMap(Type);\n const entry = instances.get(instanceKey);\n return entry?.refCount ?? 0;\n }\n\n /**\n * Check if an instance exists.\n * @param Type - The StateContainer class constructor\n * @param instanceKey - Instance key (defaults to 'default')\n * @returns true if instance exists\n */\n hasInstance<T extends StateContainerConstructor>(\n Type: T,\n instanceKey: string = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY,\n ): boolean {\n const instances = this.ensureInstancesMap(Type);\n return instances.has(instanceKey);\n }\n\n /**\n * Clear all instances from all types (for testing)\n *\n * Iterates all registered types and clears their instances.\n * Also clears type tracking to reset the registry state.\n */\n clearAll(): void {\n // Step 1: Clear instances from each type (while we still have the types list)\n for (const Type of this.types) {\n this.clear(Type);\n }\n // Step 2: Now clear type tracking (resets registry state for tests)\n this.types.clear();\n this.typeConfigs.clear();\n }\n\n /**\n * Get registry statistics for debugging.\n * @returns Object with registeredTypes, totalInstances, and typeBreakdown\n */\n getStats(): {\n registeredTypes: number;\n totalInstances: number;\n typeBreakdown: Record<string, number>;\n } {\n const typeBreakdown: Record<string, number> = {};\n let totalInstances = 0;\n\n // Collect stats from each registered type\n for (const Type of this.types) {\n const typeName = Type.name;\n const instances = this.getInstancesMap(Type);\n const count = instances.size;\n\n typeBreakdown[typeName] = count;\n totalInstances += count;\n }\n\n return {\n registeredTypes: this.types.size,\n totalInstances,\n typeBreakdown,\n };\n }\n\n /**\n * Get all registered types (for plugin system).\n * @returns Array of all registered StateContainer class constructors\n */\n getTypes(): StateContainerConstructor[] {\n return Array.from(this.types);\n }\n\n /**\n * Subscribe to lifecycle events\n * @param event - The lifecycle event to listen for\n * @param listener - The listener function to call when the event occurs\n * @returns Unsubscribe function\n */\n on<E extends LifecycleEvent>(\n event: E,\n listener: LifecycleListener<E>,\n ): () => void {\n if (!this.listeners.has(event)) {\n this.listeners.set(event, new Set());\n }\n const instance = this.listeners.get(event);\n if (!instance) {\n throw new Error(\n `${BLAC_ERROR_PREFIX} Failed to register listener for event '${event}'`,\n );\n }\n\n instance.add(listener as (...args: any[]) => void);\n\n // Return unsubscribe function\n return () => {\n this.listeners.get(event)?.delete(listener as (...args: any[]) => void);\n };\n }\n\n /**\n * Emit lifecycle event to all listeners\n * @internal - Called by StateContainer lifecycle methods\n */\n emit(event: LifecycleEvent, ...args: any[]): void {\n const listeners = this.listeners.get(event);\n if (!listeners || listeners.size === 0) return; // Zero overhead when no listeners\n\n for (const listener of listeners) {\n try {\n listener(...args);\n } catch (error) {\n console.error(\n `${BLAC_ERROR_PREFIX} Listener error for '${event}':`,\n error,\n );\n }\n }\n }\n}\n\n/**\n * Global default registry instance\n */\nexport const globalRegistry = new StateContainerRegistry();\n\n/**\n * Global plugin manager (initialized lazily)\n */\nlet _globalPluginManager: any = null;\n\n/**\n * Get the global plugin manager\n */\nexport function getPluginManager(): any {\n if (!_globalPluginManager) {\n _globalPluginManager = createPluginManager(globalRegistry);\n }\n return _globalPluginManager;\n}\n"],"mappings":";;;;;;;;;;;AA6BA,IAAa,gBAAb,MAA2B;;;;;CAQzB,YAAY,UAAkC;iCAP5B,IAAI,KAA8B;AAQlD,OAAK,WAAW;AAChB,OAAK,qBAAqB;;;;;;;;CAS5B,QAAQ,QAAoB,SAAuB,EAAE,EAAQ;EAC3D,MAAM,kBAAgC;GACpC,SAAS;GACT,aAAa;GACb,GAAG;GACJ;AAED,MAAI,CAAC,KAAK,mBAAmB,gBAAgB,EAAE;AAC7C,WAAQ,IACN,kBAAkB,OAAO,KAAK,kCAC/B;AACD;;AAGF,MAAI,KAAK,QAAQ,IAAI,OAAO,KAAK,CAC/B,OAAM,IAAI,MAAM,WAAW,OAAO,KAAK,wBAAwB;EAGjE,MAAM,UAAU,KAAK,qBAAqB;AAE1C,OAAK,QAAQ,IAAI,OAAO,MAAM;GAC5B;GACA,QAAQ;GACR;GACD,CAAC;AAEF,MAAI,OAAO,UACT,KAAI;AACF,UAAO,UAAU,QAAQ;WAClB,OAAO;AACd,WAAQ,MACN,mCAAmC,OAAO,KAAK,KAC/C,MACD;AACD,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;;;;;CAO1B,WAIE;EACA,MAAM,gBAAwC,EAAE;EAChD,IAAI,iBAAiB;AAGrB,OAAK,MAAM,QAAQ,KAAK,OAAO;GAC7B,MAAM,WAAW,KAAK;GAEtB,MAAM,QADY,KAAK,gBAAgB,KAAK,CACpB;AAExB,iBAAc,YAAY;AAC1B,qBAAkB;;AAGpB,SAAO;GACL,iBAAiB,KAAK,MAAM;GAC5B;GACA;GACD;;;;;;CAOH,WAAwC;AACtC,SAAO,MAAM,KAAK,KAAK,MAAM;;;;;;;;CAS/B,GACE,OACA,UACY;AACZ,MAAI,CAAC,KAAK,UAAU,IAAI,MAAM,CAC5B,MAAK,UAAU,IAAI,uBAAO,IAAI,KAAK,CAAC;EAEtC,MAAM,WAAW,KAAK,UAAU,IAAI,MAAM;AAC1C,MAAI,CAAC,SACH,OAAM,IAAI,MACR,GAAG,kBAAkB,0CAA0C,MAAM,GACtE;AAGH,WAAS,IAAI,SAAqC;AAGlD,eAAa;AACX,QAAK,UAAU,IAAI,MAAM,EAAE,OAAO,SAAqC;;;;;;;CAQ3E,KAAK,OAAuB,GAAG,MAAmB;EAChD,MAAM,YAAY,KAAK,UAAU,IAAI,MAAM;AAC3C,MAAI,CAAC,aAAa,UAAU,SAAS,EAAG;AAExC,OAAK,MAAM,YAAY,UACrB,KAAI;AACF,YAAS,GAAG,KAAK;WACV,OAAO;AACd,WAAQ,MACN,GAAG,kBAAkB,uBAAuB,MAAM,KAClD,MACD;;;;;;;AAST,MAAa,iBAAiB,IAAI,wBAAwB;;;;AAK1D,IAAI,uBAA4B;;;;AAKhC,SAAgB,mBAAwB;AACtC,KAAI,CAAC,qBACH,wBAAuB,oBAAoB,eAAe;AAE5D,QAAO"}
|
package/dist/index.cjs
CHANGED
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
const require_StateContainerRegistry = require('./StateContainerRegistry.cjs');
|
|
2
|
-
const require_tracking_proxy = require('./tracking-proxy.cjs');
|
|
3
2
|
const require_management = require('./management.cjs');
|
|
4
3
|
const require_watch = require('./watch.cjs');
|
|
5
|
-
const
|
|
4
|
+
const require_resolve_dependencies = require('./resolve-dependencies.cjs');
|
|
6
5
|
require('./tracking.cjs');
|
|
7
6
|
|
|
8
7
|
//#region src/utils/idGenerator.ts
|
|
@@ -39,6 +38,7 @@ function generateIsolatedKey() {
|
|
|
39
38
|
|
|
40
39
|
//#endregion
|
|
41
40
|
//#region src/core/StateContainer.ts
|
|
41
|
+
const EMPTY_DEPS = /* @__PURE__ */ new Map();
|
|
42
42
|
/**
|
|
43
43
|
* Abstract base class for all state containers in BlaC.
|
|
44
44
|
* Provides lifecycle management, subscription handling, ref counting,
|
|
@@ -65,6 +65,14 @@ var StateContainer = class StateContainer {
|
|
|
65
65
|
static {
|
|
66
66
|
this.enableStackTrace = true;
|
|
67
67
|
}
|
|
68
|
+
get dependencies() {
|
|
69
|
+
return this._dependencies ?? EMPTY_DEPS;
|
|
70
|
+
}
|
|
71
|
+
depend(Type, instanceKey) {
|
|
72
|
+
if (!this._dependencies) this._dependencies = /* @__PURE__ */ new Map();
|
|
73
|
+
this._dependencies.set(Type, instanceKey ?? require_StateContainerRegistry.BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY);
|
|
74
|
+
return () => require_StateContainerRegistry.globalRegistry.ensure(Type, instanceKey);
|
|
75
|
+
}
|
|
68
76
|
constructor(initialState) {
|
|
69
77
|
this.listeners = /* @__PURE__ */ new Set();
|
|
70
78
|
this._disposed = false;
|
|
@@ -74,6 +82,7 @@ var StateContainer = class StateContainer {
|
|
|
74
82
|
this.debug = false;
|
|
75
83
|
this.instanceId = generateSimpleId(this.constructor.name, "main");
|
|
76
84
|
this.createdAt = Date.now();
|
|
85
|
+
this._dependencies = null;
|
|
77
86
|
this.lastUpdateTimestamp = Date.now();
|
|
78
87
|
this.onSystemEvent = (event, handler) => {
|
|
79
88
|
let handlers = this.systemEventHandlers.get(event);
|
|
@@ -298,32 +307,31 @@ function release(BlocClass, instanceKey, forceDispose = false) {
|
|
|
298
307
|
*/
|
|
299
308
|
function blac(options) {
|
|
300
309
|
return function(target, _context) {
|
|
301
|
-
if ("isolated" in options && options.isolated) target[
|
|
302
|
-
if ("keepAlive" in options && options.keepAlive) target[
|
|
303
|
-
if ("excludeFromDevTools" in options && options.excludeFromDevTools) target[
|
|
310
|
+
if ("isolated" in options && options.isolated) target[require_StateContainerRegistry.BLAC_STATIC_PROPS.ISOLATED] = true;
|
|
311
|
+
if ("keepAlive" in options && options.keepAlive) target[require_StateContainerRegistry.BLAC_STATIC_PROPS.KEEP_ALIVE] = true;
|
|
312
|
+
if ("excludeFromDevTools" in options && options.excludeFromDevTools) target[require_StateContainerRegistry.BLAC_STATIC_PROPS.EXCLUDE_FROM_DEVTOOLS] = true;
|
|
304
313
|
return target;
|
|
305
314
|
};
|
|
306
315
|
}
|
|
307
316
|
|
|
308
317
|
//#endregion
|
|
309
318
|
exports.Cubit = Cubit;
|
|
310
|
-
exports.DependencyManager =
|
|
319
|
+
exports.DependencyManager = require_resolve_dependencies.DependencyManager;
|
|
311
320
|
exports.PluginManager = require_StateContainerRegistry.PluginManager;
|
|
312
321
|
exports.StateContainer = StateContainer;
|
|
313
322
|
exports.acquire = acquire;
|
|
314
323
|
exports.blac = blac;
|
|
315
324
|
exports.borrow = borrow;
|
|
316
325
|
exports.borrowSafe = borrowSafe;
|
|
317
|
-
exports.capturePaths =
|
|
326
|
+
exports.capturePaths = require_resolve_dependencies.capturePaths;
|
|
318
327
|
exports.clear = require_management.clear;
|
|
319
|
-
exports.clearActiveTracker =
|
|
328
|
+
exports.clearActiveTracker = require_resolve_dependencies.clearActiveTracker;
|
|
320
329
|
exports.clearAll = require_management.clearAll;
|
|
321
|
-
exports.
|
|
322
|
-
exports.
|
|
323
|
-
exports.
|
|
324
|
-
exports.
|
|
325
|
-
exports.
|
|
326
|
-
exports.createGetterState = require_tracking_proxy.createGetterState;
|
|
330
|
+
exports.commitTrackedGetters = require_resolve_dependencies.commitTrackedGetters;
|
|
331
|
+
exports.createBlocProxy = require_resolve_dependencies.createBlocProxy;
|
|
332
|
+
exports.createDependencyProxy = require_resolve_dependencies.createDependencyProxy;
|
|
333
|
+
exports.createDependencyState = require_resolve_dependencies.createDependencyState;
|
|
334
|
+
exports.createGetterState = require_resolve_dependencies.createGetterState;
|
|
327
335
|
exports.ensure = require_watch.ensure;
|
|
328
336
|
exports.forEach = require_management.forEach;
|
|
329
337
|
exports.generateIsolatedKey = generateIsolatedKey;
|
|
@@ -331,16 +339,17 @@ exports.getAll = require_management.getAll;
|
|
|
331
339
|
exports.getPluginManager = require_StateContainerRegistry.getPluginManager;
|
|
332
340
|
exports.getRefCount = require_management.getRefCount;
|
|
333
341
|
exports.globalRegistry = require_StateContainerRegistry.globalRegistry;
|
|
334
|
-
exports.hasDependencyChanges =
|
|
335
|
-
exports.hasGetterChanges =
|
|
342
|
+
exports.hasDependencyChanges = require_resolve_dependencies.hasDependencyChanges;
|
|
343
|
+
exports.hasGetterChanges = require_resolve_dependencies.hasGetterChanges;
|
|
336
344
|
exports.hasInstance = require_management.hasInstance;
|
|
337
|
-
exports.hasTrackedData =
|
|
345
|
+
exports.hasTrackedData = require_resolve_dependencies.hasTrackedData;
|
|
338
346
|
exports.instance = require_watch.instance;
|
|
339
|
-
exports.invalidateRenderCache =
|
|
347
|
+
exports.invalidateRenderCache = require_resolve_dependencies.invalidateRenderCache;
|
|
340
348
|
exports.isIsolatedClass = require_StateContainerRegistry.isIsolatedClass;
|
|
341
349
|
exports.release = release;
|
|
342
|
-
exports.
|
|
343
|
-
exports.
|
|
344
|
-
exports.
|
|
350
|
+
exports.resolveDependencies = require_resolve_dependencies.resolveDependencies;
|
|
351
|
+
exports.setActiveTracker = require_resolve_dependencies.setActiveTracker;
|
|
352
|
+
exports.shallowEqual = require_resolve_dependencies.shallowEqual;
|
|
353
|
+
exports.startDependency = require_resolve_dependencies.startDependency;
|
|
345
354
|
exports.watch = require_watch.watch;
|
|
346
355
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["globalRegistry","globalRegistry","BLAC_STATIC_PROPS"],"sources":["../src/utils/idGenerator.ts","../src/core/StateContainer.ts","../src/core/Cubit.ts","../src/registry/acquire.ts","../src/registry/borrow.ts","../src/registry/release.ts","../src/decorators/blac.ts"],"sourcesContent":["/**\n * Centralized ID Generation\n *\n * Provides consistent, collision-resistant ID generation for all BlaC subsystems.\n * Uses timestamp + counter + random suffix for uniqueness.\n */\n\n// Global counter map for ID generation\nconst globalCounters = new Map<string, number>();\n\n/**\n * Creates an ID generator with isolated counter state\n *\n * @param prefix - Prefix for generated IDs\n * @returns Object with next(), nextSimple(), and reset() methods\n *\n * @example\n * ```ts\n * const generator = createIdGenerator('sub');\n * const id1 = generator.next(); // \"sub:1698765432100_1_a3k9d7f2q\"\n * const id2 = generator.next(); // \"sub:1698765432101_2_b4n8e9g3r\"\n * ```\n */\nexport function createIdGenerator(prefix: string) {\n let counter = 0;\n return {\n next: () =>\n `${prefix}:${Date.now()}_${++counter}_${Math.random().toString(36).substring(2, 11)}`,\n nextSimple: () => `${prefix}:${++counter}`,\n reset: () => {\n counter = 0;\n },\n };\n}\n\n/**\n * Generate ID with timestamp, counter, and random suffix (tree-shakeable)\n *\n * Format: `${prefix}:${timestamp}_${counter}_${random}`\n *\n * @param prefix - Prefix for the ID (e.g., 'sub', 'consumer', 'stage')\n * @returns Branded ID string\n *\n * @example\n * const id = generateId('sub');\n * // Returns: \"sub:1698765432100_1_a3k9d7f2q\"\n */\nexport function generateId(prefix: string): string {\n const counter = (globalCounters.get(prefix) ?? 0) + 1;\n globalCounters.set(prefix, counter);\n const timestamp = Date.now();\n const random = Math.random().toString(36).substring(2, 11);\n return `${prefix}:${timestamp}_${counter}_${random}`;\n}\n\n/**\n * Generate simple ID with timestamp and random (no counter tracking)\n *\n * Format: `${prefix}:${timestamp}_${random}`\n *\n * @param prefix - Prefix for the ID\n * @returns Branded ID string\n *\n * @example\n * ```ts\n * const id = generateSimpleId('CounterBloc');\n * // Returns: \"CounterBloc:1698765432100_a3k9d7f2q\"\n * ```\n */\nexport function generateSimpleId(prefix: string, affix?: string): string {\n if (affix) {\n return `${prefix}:${affix}`;\n }\n const timestamp = Date.now();\n const random = Math.random().toString(36).substring(2, 11);\n return `${prefix}:${timestamp}_${random}`;\n}\n\n/**\n * Reset all counters for testing purposes\n * @internal\n */\nexport function __resetIdCounters(): void {\n globalCounters.clear();\n}\n\n/**\n * Generate a unique isolated instance key\n * Uses base36 encoding for compact, URL-safe identifiers\n *\n * Format: \"isolated-{9-char-random-string}\"\n * Example: \"isolated-k7x2m9p4q\"\n *\n * @returns A unique isolated instance key\n */\nexport function generateIsolatedKey(): string {\n const randomPart = Math.random().toString(36).slice(2, 11);\n return `isolated-${randomPart}`;\n}\n\n/**\n * Check if a key is an isolated instance key\n * @param key - The instance key to check\n * @returns true if the key is an isolated instance key\n */\nexport function isIsolatedKey(key: string): boolean {\n return key.startsWith('isolated-');\n}\n","import { generateSimpleId } from '../utils/idGenerator';\nimport { globalRegistry } from './StateContainerRegistry';\n\n/**\n * Configuration options for initializing a StateContainer instance\n */\nexport interface StateContainerConfig {\n /** Display name for the instance (defaults to class name) */\n name?: string;\n /** Enable debug logging for this instance */\n debug?: boolean;\n /** Custom instance identifier */\n instanceId?: string;\n}\n\n/**\n * Listener function for state changes\n * @internal\n */\ntype StateListener<S> = (state: S) => void;\n\n/**\n * System events emitted by StateContainer lifecycle\n */\nexport type SystemEvent = 'stateChanged' | 'dispose';\n\n/**\n * Payload types for each system event\n * @template S - State type\n */\nexport interface SystemEventPayloads<S> {\n /** Emitted when state changes via emit() or update() */\n stateChanged: { state: S; previousState: S };\n /** Emitted when the instance is disposed */\n dispose: void;\n}\n\n/**\n * Handler function for system events\n * @internal\n */\ntype SystemEventHandler<S, E extends SystemEvent> = (\n payload: SystemEventPayloads<S>[E],\n) => void;\n\n/**\n * Abstract base class for all state containers in BlaC.\n * Provides lifecycle management, subscription handling, ref counting,\n * and integration with the global registry.\n *\n * @template S - State type managed by this container\n *\n * @example\n * ```ts\n * class CounterBloc extends StateContainer<{ count: number }> {\n * constructor() {\n * super({ count: 0 });\n * }\n * increment() {\n * this.emit({ count: this.state.count + 1 });\n * }\n * }\n * ```\n */\nexport abstract class StateContainer<S extends object = any> {\n static __excludeFromDevTools = false;\n static enableStackTrace = true;\n\n private _state: S;\n private readonly listeners = new Set<StateListener<S>>();\n private _disposed = false;\n private config: StateContainerConfig = {};\n private readonly systemEventHandlers = new Map<\n SystemEvent,\n Set<SystemEventHandler<S, any>>\n >();\n\n /** Display name for this instance */\n name: string = this.constructor.name;\n /** Whether debug logging is enabled */\n debug: boolean = false;\n /** Unique identifier for this instance */\n instanceId: string = generateSimpleId(this.constructor.name, 'main');\n /** Timestamp when this instance was created */\n createdAt: number = Date.now();\n\n constructor(initialState: S) {\n this._state = initialState;\n }\n\n /**\n * Initialize configuration for this instance.\n * Called by the registry after construction.\n * @param config - Configuration options\n */\n initConfig(config: StateContainerConfig): void {\n this.config = { ...config };\n this.name = this.config.name || this.constructor.name;\n this.debug = this.config.debug ?? false;\n this.instanceId = generateSimpleId(\n this.constructor.name,\n this.config.instanceId,\n );\n\n globalRegistry.emit('created', this);\n }\n\n /** Current state value */\n get state(): Readonly<S> {\n return this._state;\n }\n\n /** Whether this instance has been disposed */\n get isDisposed(): boolean {\n return this._disposed;\n }\n\n /**\n * Subscribe to state changes\n * @param listener - Function called when state changes\n * @returns Unsubscribe function\n */\n subscribe(listener: StateListener<S>): () => void {\n if (this._disposed) {\n throw new Error(`Cannot subscribe to disposed container ${this.name}`);\n }\n\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n /**\n * Dispose this instance and clean up resources.\n * Clears all listeners and emits the 'dispose' system event.\n */\n dispose(): void {\n if (this._disposed) return;\n\n if (this.debug) {\n console.log(`[${this.name}] Disposing...`);\n }\n\n this._disposed = true;\n\n this.emitSystemEvent('dispose', undefined as void);\n\n this.listeners.clear();\n this.systemEventHandlers.clear();\n\n globalRegistry.emit('disposed', this);\n\n if (this.debug) {\n console.log(`[${this.name}] Disposed successfully`);\n }\n }\n\n /**\n * Emit a new state value and notify all listeners.\n * @param newState - The new state value\n * @protected\n */\n protected emit(newState: S): void {\n if (this._disposed) {\n throw new Error(`Cannot emit state from disposed container ${this.name}`);\n }\n\n if (this._state === newState) return;\n\n const previousState = this._state;\n this._state = newState;\n\n this.emitSystemEvent('stateChanged', {\n state: newState,\n previousState,\n });\n\n for (const listener of this.listeners) {\n try {\n listener(newState);\n } catch (error) {\n console.error(`[${this.name}] Error in listener:`, error);\n }\n }\n\n const stackTrace = this.captureStackTrace();\n\n globalRegistry.emit(\n 'stateChanged',\n this,\n previousState,\n newState,\n stackTrace,\n );\n this.lastUpdateTimestamp = Date.now();\n }\n\n private captureStackTrace(): string {\n if (\n !StateContainer.enableStackTrace ||\n (typeof process !== 'undefined' && process.env?.NODE_ENV === 'production')\n ) {\n return '';\n }\n\n try {\n const error = new Error();\n const stack = error.stack || '';\n const lines = stack.split('\\n');\n const relevantLines = lines.slice(1);\n const formattedLines: string[] = [];\n\n for (const line of relevantLines) {\n if (!line.trim()) continue;\n\n if (\n line.includes('StateContainer.emit') ||\n line.includes('StateContainer.update') ||\n line.includes('StateContainer.captureStackTrace') ||\n line.includes('Cubit.patch')\n ) {\n continue;\n }\n\n if (\n line.includes('node_modules') ||\n line.includes('react-dom') ||\n line.includes('react_jsx') ||\n line.includes('.vite/deps') ||\n line.includes('executeDispatch') ||\n line.includes('runWithFiber') ||\n line.includes('invokeGuarded') ||\n line.includes('callCallback') ||\n line.includes('processDispatchQueue') ||\n line.includes('dispatchEvent') ||\n line.includes('batchedUpdates')\n ) {\n continue;\n }\n\n const formatted = this.formatStackLine(line);\n if (formatted) {\n formattedLines.push(formatted);\n }\n }\n\n return formattedLines.join('\\n');\n } catch {\n return '';\n }\n }\n\n private formatStackLine(line: string): string | null {\n const match = line.match(/at\\s+(.+?)\\s+\\((.+?):(\\d+):(\\d+)\\)/);\n if (!match) {\n const simpleMatch = line.match(/at\\s+(.+?):(\\d+):(\\d+)/);\n if (simpleMatch) {\n const [, url, lineNum, col] = simpleMatch;\n const cleanPath = this.cleanFilePath(url);\n return ` at ${cleanPath}:${lineNum}:${col}`;\n }\n return null;\n }\n\n const [, functionName, url, lineNum, col] = match;\n const cleanPath = this.cleanFilePath(url);\n\n return ` at ${functionName} (${cleanPath}:${lineNum}:${col})`;\n }\n\n private cleanFilePath(url: string): string {\n let path = url\n .replace(/http:\\/\\/localhost:\\d+\\/@fs/, '')\n .replace(/http:\\/\\/localhost:\\d+\\//, '')\n .replace(/\\?t=\\d+/, '')\n .replace(/\\?v=[a-f0-9]+/, '');\n\n const projectMatch = path.match(/\\/Projects\\/blac\\/(.+)/);\n if (projectMatch) {\n path = projectMatch[1];\n }\n\n const segments = path.split('/');\n if (segments.length > 3) {\n path = segments.slice(-3).join('/');\n }\n\n return path;\n }\n\n /** Timestamp of the last state update */\n lastUpdateTimestamp: number = Date.now();\n\n /**\n * Update state using a transform function.\n * @param updater - Function that receives current state and returns new state\n * @protected\n */\n protected update(updater: (current: S) => S): void {\n if (this._disposed) {\n throw new Error(\n `Cannot update state from disposed container ${this.name}`,\n );\n }\n this.emit(updater(this._state));\n }\n\n /**\n * Subscribe to system lifecycle events.\n * @param event - The event type to listen for\n * @param handler - Handler function called when event occurs\n * @returns Unsubscribe function\n * @protected\n */\n protected onSystemEvent = <E extends SystemEvent>(\n event: E,\n handler: SystemEventHandler<S, E>,\n ): (() => void) => {\n let handlers = this.systemEventHandlers.get(event);\n if (!handlers) {\n handlers = new Set();\n this.systemEventHandlers.set(event, handlers);\n }\n handlers.add(handler as SystemEventHandler<S, any>);\n\n return () => {\n handlers?.delete(handler as SystemEventHandler<S, any>);\n };\n };\n\n private emitSystemEvent<E extends SystemEvent>(\n event: E,\n payload: SystemEventPayloads<S>[E],\n ): void {\n const handlers = this.systemEventHandlers.get(event);\n if (!handlers) return;\n\n for (const handler of handlers) {\n try {\n handler(payload);\n } catch (error) {\n console.error(`[${this.name}] Error in system event handler:`, error);\n }\n }\n }\n}\n","import { StateContainer } from './StateContainer';\n\n/**\n * Simple state container with direct state emission.\n * Extends StateContainer with public methods for emitting and updating state.\n *\n * @template S - State type\n */\nexport abstract class Cubit<S extends object = any> extends StateContainer<S> {\n constructor(initialState: S) {\n super(initialState);\n }\n\n /**\n * Replace state with a new value and notify all listeners\n * @param newState - The new state value\n */\n public emit(newState: S): void {\n super['emit'](newState);\n }\n\n /**\n * Transform current state using an updater function and emit the new state\n * @param updater - Function that receives current state and returns new state\n */\n public update(updater: (current: S) => S): void {\n super['update'](updater);\n }\n\n /**\n * Merge partial state changes into current state (only for object states)\n */\n public patch = ((partial: S extends object ? Partial<S> : never): void => {\n if (typeof this.state !== 'object' || this.state === null) {\n throw new Error('patch() is only available for object state types');\n }\n this.update((current) => ({ ...current, ...partial }) as S);\n }) as S extends object ? (partial: Partial<S>) => void : never;\n}\n","import { globalRegistry } from '../core/StateContainerRegistry';\nimport type { StateContainerConstructor } from '../types/utilities';\n\nexport function acquire<T extends StateContainerConstructor>(\n BlocClass: T,\n instanceKey?: string,\n): InstanceType<T> {\n return globalRegistry.acquire(BlocClass, instanceKey, {\n canCreate: true,\n countRef: true,\n });\n}\n","import { globalRegistry } from '../core/StateContainerRegistry';\nimport type { StateContainerConstructor } from '../types/utilities';\n\nexport function borrow<T extends StateContainerConstructor>(\n BlocClass: T,\n instanceKey?: string,\n): InstanceType<T> {\n return globalRegistry.borrow(BlocClass, instanceKey);\n}\n\nexport function borrowSafe<T extends StateContainerConstructor>(\n BlocClass: T,\n instanceKey?: string,\n):\n | { error: Error; instance: null }\n | { error: null; instance: InstanceType<T> } {\n return globalRegistry.borrowSafe(BlocClass, instanceKey);\n}\n","import { globalRegistry } from '../core/StateContainerRegistry';\nimport type { StateContainerConstructor } from '../types/utilities';\n\nexport function release<T extends StateContainerConstructor>(\n BlocClass: T,\n instanceKey?: string,\n forceDispose = false,\n): void {\n globalRegistry.release(BlocClass, instanceKey, forceDispose);\n}\n","import { BLAC_STATIC_PROPS } from '../constants';\n\n/**\n * Configuration options for the @blac decorator.\n * Only one option can be specified at a time (union type).\n */\nexport type BlacOptions =\n /** Mark bloc as isolated (each component gets its own instance) */\n | { isolated: true }\n /** Mark bloc to never be auto-disposed when ref count reaches 0 */\n | { keepAlive: true }\n /** Exclude bloc from DevTools tracking (prevents infinite loops) */\n | { excludeFromDevTools: true };\n\n/**\n * Decorator to configure StateContainer classes.\n *\n * @example Decorator syntax (requires experimentalDecorators or TC39 decorators)\n * ```ts\n * @blac({ isolated: true })\n * class FormBloc extends Cubit<FormState> {}\n *\n * @blac({ keepAlive: true })\n * class AuthBloc extends Cubit<AuthState> {}\n *\n * @blac({ excludeFromDevTools: true })\n * class InternalBloc extends Cubit<InternalState> {}\n * ```\n *\n * @example Function syntax (no decorator support needed)\n * ```ts\n * const FormBloc = blac({ isolated: true })(\n * class extends Cubit<FormState> {}\n * );\n * ```\n */\nexport function blac(options: BlacOptions) {\n return function <T extends new (...args: any[]) => any>(\n target: T,\n _context?: ClassDecoratorContext,\n ): T {\n if ('isolated' in options && options.isolated) {\n (target as any)[BLAC_STATIC_PROPS.ISOLATED] = true;\n }\n if ('keepAlive' in options && options.keepAlive) {\n (target as any)[BLAC_STATIC_PROPS.KEEP_ALIVE] = true;\n }\n if ('excludeFromDevTools' in options && options.excludeFromDevTools) {\n (target as any)[BLAC_STATIC_PROPS.EXCLUDE_FROM_DEVTOOLS] = true;\n }\n return target;\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAqEA,SAAgB,iBAAiB,QAAgB,OAAwB;AACvE,KAAI,MACF,QAAO,GAAG,OAAO,GAAG;AAItB,QAAO,GAAG,OAAO,GAFC,KAAK,KAAK,CAEE,GADf,KAAK,QAAQ,CAAC,SAAS,GAAG,CAAC,UAAU,GAAG,GAAG;;;;;;;;;;;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AAQ,QAAQ;WACT,OAAO;AACd,WAAQ,MAAM,IAAI,KAAK,KAAK,mCAAmC,MAAM;;;;;;;;;;;;;AC5U7E,IAAsB,QAAtB,cAA4D,eAAkB;CAC5E,YAAY,cAAiB;AAC3B,QAAM,aAAa;iBAsBJ,YAAyD;AACxE,OAAI,OAAO,KAAK,UAAU,YAAY,KAAK,UAAU,KACnD,OAAM,IAAI,MAAM,mDAAmD;AAErE,QAAK,QAAQ,aAAa;IAAE,GAAG;IAAS,GAAG;IAAS,EAAO;;;;;;;CAnB7D,AAAO,KAAK,UAAmB;AAC7B,QAAM,QAAQ,SAAS;;;;;;CAOzB,AAAO,OAAO,SAAkC;AAC9C,QAAM,UAAU,QAAQ;;;;;;ACvB5B,SAAgB,QACd,WACA,aACiB;AACjB,QAAOA,8CAAe,QAAQ,WAAW,aAAa;EACpD,WAAW;EACX,UAAU;EACX,CAAC;;;;;ACPJ,SAAgB,OACd,WACA,aACiB;AACjB,QAAOC,8CAAe,OAAO,WAAW,YAAY;;AAGtD,SAAgB,WACd,WACA,aAG6C;AAC7C,QAAOA,8CAAe,WAAW,WAAW,YAAY;;;;;ACb1D,SAAgB,QACd,WACA,aACA,eAAe,OACT;AACN,+CAAe,QAAQ,WAAW,aAAa,aAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;AC4B9D,SAAgB,KAAK,SAAsB;AACzC,QAAO,SACL,QACA,UACG;AACH,MAAI,cAAc,WAAW,QAAQ,SACnC,CAAC,OAAeC,yCAAkB,YAAY;AAEhD,MAAI,eAAe,WAAW,QAAQ,UACpC,CAAC,OAAeA,yCAAkB,cAAc;AAElD,MAAI,yBAAyB,WAAW,QAAQ,oBAC9C,CAAC,OAAeA,yCAAkB,yBAAyB;AAE7D,SAAO"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["BLAC_DEFAULTS","globalRegistry","globalRegistry","globalRegistry","BLAC_STATIC_PROPS"],"sources":["../src/utils/idGenerator.ts","../src/core/StateContainer.ts","../src/core/Cubit.ts","../src/registry/acquire.ts","../src/registry/borrow.ts","../src/registry/release.ts","../src/decorators/blac.ts"],"sourcesContent":["/**\n * Centralized ID Generation\n *\n * Provides consistent, collision-resistant ID generation for all BlaC subsystems.\n * Uses timestamp + counter + random suffix for uniqueness.\n */\n\n// Global counter map for ID generation\nconst globalCounters = new Map<string, number>();\n\n/**\n * Creates an ID generator with isolated counter state\n *\n * @param prefix - Prefix for generated IDs\n * @returns Object with next(), nextSimple(), and reset() methods\n *\n * @example\n * ```ts\n * const generator = createIdGenerator('sub');\n * const id1 = generator.next(); // \"sub:1698765432100_1_a3k9d7f2q\"\n * const id2 = generator.next(); // \"sub:1698765432101_2_b4n8e9g3r\"\n * ```\n */\nexport function createIdGenerator(prefix: string) {\n let counter = 0;\n return {\n next: () =>\n `${prefix}:${Date.now()}_${++counter}_${Math.random().toString(36).substring(2, 11)}`,\n nextSimple: () => `${prefix}:${++counter}`,\n reset: () => {\n counter = 0;\n },\n };\n}\n\n/**\n * Generate ID with timestamp, counter, and random suffix (tree-shakeable)\n *\n * Format: `${prefix}:${timestamp}_${counter}_${random}`\n *\n * @param prefix - Prefix for the ID (e.g., 'sub', 'consumer', 'stage')\n * @returns Branded ID string\n *\n * @example\n * const id = generateId('sub');\n * // Returns: \"sub:1698765432100_1_a3k9d7f2q\"\n */\nexport function generateId(prefix: string): string {\n const counter = (globalCounters.get(prefix) ?? 0) + 1;\n globalCounters.set(prefix, counter);\n const timestamp = Date.now();\n const random = Math.random().toString(36).substring(2, 11);\n return `${prefix}:${timestamp}_${counter}_${random}`;\n}\n\n/**\n * Generate simple ID with timestamp and random (no counter tracking)\n *\n * Format: `${prefix}:${timestamp}_${random}`\n *\n * @param prefix - Prefix for the ID\n * @returns Branded ID string\n *\n * @example\n * ```ts\n * const id = generateSimpleId('CounterBloc');\n * // Returns: \"CounterBloc:1698765432100_a3k9d7f2q\"\n * ```\n */\nexport function generateSimpleId(prefix: string, affix?: string): string {\n if (affix) {\n return `${prefix}:${affix}`;\n }\n const timestamp = Date.now();\n const random = Math.random().toString(36).substring(2, 11);\n return `${prefix}:${timestamp}_${random}`;\n}\n\n/**\n * Reset all counters for testing purposes\n * @internal\n */\nexport function __resetIdCounters(): void {\n globalCounters.clear();\n}\n\n/**\n * Generate a unique isolated instance key\n * Uses base36 encoding for compact, URL-safe identifiers\n *\n * Format: \"isolated-{9-char-random-string}\"\n * Example: \"isolated-k7x2m9p4q\"\n *\n * @returns A unique isolated instance key\n */\nexport function generateIsolatedKey(): string {\n const randomPart = Math.random().toString(36).slice(2, 11);\n return `isolated-${randomPart}`;\n}\n\n/**\n * Check if a key is an isolated instance key\n * @param key - The instance key to check\n * @returns true if the key is an isolated instance key\n */\nexport function isIsolatedKey(key: string): boolean {\n return key.startsWith('isolated-');\n}\n","import { generateSimpleId } from '../utils/idGenerator';\nimport { BLAC_DEFAULTS } from '../constants';\nimport { globalRegistry } from './StateContainerRegistry';\nimport type { StateContainerConstructor } from '../types/utilities';\n\n/**\n * Configuration options for initializing a StateContainer instance\n */\nexport interface StateContainerConfig {\n /** Display name for the instance (defaults to class name) */\n name?: string;\n /** Enable debug logging for this instance */\n debug?: boolean;\n /** Custom instance identifier */\n instanceId?: string;\n}\n\n/**\n * Listener function for state changes\n * @internal\n */\ntype StateListener<S> = (state: S) => void;\n\n/**\n * System events emitted by StateContainer lifecycle\n */\nexport type SystemEvent = 'stateChanged' | 'dispose';\n\n/**\n * Payload types for each system event\n * @template S - State type\n */\nexport interface SystemEventPayloads<S> {\n /** Emitted when state changes via emit() or update() */\n stateChanged: { state: S; previousState: S };\n /** Emitted when the instance is disposed */\n dispose: void;\n}\n\n/**\n * Handler function for system events\n * @internal\n */\ntype SystemEventHandler<S, E extends SystemEvent> = (\n payload: SystemEventPayloads<S>[E],\n) => void;\n\nconst EMPTY_DEPS: ReadonlyMap<any, any> = new Map();\n\n/**\n * Abstract base class for all state containers in BlaC.\n * Provides lifecycle management, subscription handling, ref counting,\n * and integration with the global registry.\n *\n * @template S - State type managed by this container\n *\n * @example\n * ```ts\n * class CounterBloc extends StateContainer<{ count: number }> {\n * constructor() {\n * super({ count: 0 });\n * }\n * increment() {\n * this.emit({ count: this.state.count + 1 });\n * }\n * }\n * ```\n */\nexport abstract class StateContainer<S extends object = any> {\n static __excludeFromDevTools = false;\n static enableStackTrace = true;\n\n private _state: S;\n private readonly listeners = new Set<StateListener<S>>();\n private _disposed = false;\n private config: StateContainerConfig = {};\n private readonly systemEventHandlers = new Map<\n SystemEvent,\n Set<SystemEventHandler<S, any>>\n >();\n\n /** Display name for this instance */\n name: string = this.constructor.name;\n /** Whether debug logging is enabled */\n debug: boolean = false;\n /** Unique identifier for this instance */\n instanceId: string = generateSimpleId(this.constructor.name, 'main');\n /** Timestamp when this instance was created */\n createdAt: number = Date.now();\n\n private _dependencies: Map<StateContainerConstructor, string> | null = null;\n\n get dependencies(): ReadonlyMap<StateContainerConstructor, string> {\n return this._dependencies ?? EMPTY_DEPS;\n }\n\n protected depend<T extends StateContainerConstructor>(\n Type: T,\n instanceKey?: string,\n ): () => InstanceType<T> {\n if (!this._dependencies) {\n this._dependencies = new Map();\n }\n this._dependencies.set(\n Type,\n instanceKey ?? BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY,\n );\n return () => globalRegistry.ensure(Type, instanceKey);\n }\n\n constructor(initialState: S) {\n this._state = initialState;\n }\n\n /**\n * Initialize configuration for this instance.\n * Called by the registry after construction.\n * @param config - Configuration options\n */\n initConfig(config: StateContainerConfig): void {\n this.config = { ...config };\n this.name = this.config.name || this.constructor.name;\n this.debug = this.config.debug ?? false;\n this.instanceId = generateSimpleId(\n this.constructor.name,\n this.config.instanceId,\n );\n\n globalRegistry.emit('created', this);\n }\n\n /** Current state value */\n get state(): Readonly<S> {\n return this._state;\n }\n\n /** Whether this instance has been disposed */\n get isDisposed(): boolean {\n return this._disposed;\n }\n\n /**\n * Subscribe to state changes\n * @param listener - Function called when state changes\n * @returns Unsubscribe function\n */\n subscribe(listener: StateListener<S>): () => void {\n if (this._disposed) {\n throw new Error(`Cannot subscribe to disposed container ${this.name}`);\n }\n\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n /**\n * Dispose this instance and clean up resources.\n * Clears all listeners and emits the 'dispose' system event.\n */\n dispose(): void {\n if (this._disposed) return;\n\n if (this.debug) {\n console.log(`[${this.name}] Disposing...`);\n }\n\n this._disposed = true;\n\n this.emitSystemEvent('dispose', undefined as void);\n\n this.listeners.clear();\n this.systemEventHandlers.clear();\n\n globalRegistry.emit('disposed', this);\n\n if (this.debug) {\n console.log(`[${this.name}] Disposed successfully`);\n }\n }\n\n /**\n * Emit a new state value and notify all listeners.\n * @param newState - The new state value\n * @protected\n */\n protected emit(newState: S): void {\n if (this._disposed) {\n throw new Error(`Cannot emit state from disposed container ${this.name}`);\n }\n\n if (this._state === newState) return;\n\n const previousState = this._state;\n this._state = newState;\n\n this.emitSystemEvent('stateChanged', {\n state: newState,\n previousState,\n });\n\n for (const listener of this.listeners) {\n try {\n listener(newState);\n } catch (error) {\n console.error(`[${this.name}] Error in listener:`, error);\n }\n }\n\n const stackTrace = this.captureStackTrace();\n\n globalRegistry.emit(\n 'stateChanged',\n this,\n previousState,\n newState,\n stackTrace,\n );\n this.lastUpdateTimestamp = Date.now();\n }\n\n private captureStackTrace(): string {\n if (\n !StateContainer.enableStackTrace ||\n (typeof process !== 'undefined' && process.env?.NODE_ENV === 'production')\n ) {\n return '';\n }\n\n try {\n const error = new Error();\n const stack = error.stack || '';\n const lines = stack.split('\\n');\n const relevantLines = lines.slice(1);\n const formattedLines: string[] = [];\n\n for (const line of relevantLines) {\n if (!line.trim()) continue;\n\n if (\n line.includes('StateContainer.emit') ||\n line.includes('StateContainer.update') ||\n line.includes('StateContainer.captureStackTrace') ||\n line.includes('Cubit.patch')\n ) {\n continue;\n }\n\n if (\n line.includes('node_modules') ||\n line.includes('react-dom') ||\n line.includes('react_jsx') ||\n line.includes('.vite/deps') ||\n line.includes('executeDispatch') ||\n line.includes('runWithFiber') ||\n line.includes('invokeGuarded') ||\n line.includes('callCallback') ||\n line.includes('processDispatchQueue') ||\n line.includes('dispatchEvent') ||\n line.includes('batchedUpdates')\n ) {\n continue;\n }\n\n const formatted = this.formatStackLine(line);\n if (formatted) {\n formattedLines.push(formatted);\n }\n }\n\n return formattedLines.join('\\n');\n } catch {\n return '';\n }\n }\n\n private formatStackLine(line: string): string | null {\n const match = line.match(/at\\s+(.+?)\\s+\\((.+?):(\\d+):(\\d+)\\)/);\n if (!match) {\n const simpleMatch = line.match(/at\\s+(.+?):(\\d+):(\\d+)/);\n if (simpleMatch) {\n const [, url, lineNum, col] = simpleMatch;\n const cleanPath = this.cleanFilePath(url);\n return ` at ${cleanPath}:${lineNum}:${col}`;\n }\n return null;\n }\n\n const [, functionName, url, lineNum, col] = match;\n const cleanPath = this.cleanFilePath(url);\n\n return ` at ${functionName} (${cleanPath}:${lineNum}:${col})`;\n }\n\n private cleanFilePath(url: string): string {\n let path = url\n .replace(/http:\\/\\/localhost:\\d+\\/@fs/, '')\n .replace(/http:\\/\\/localhost:\\d+\\//, '')\n .replace(/\\?t=\\d+/, '')\n .replace(/\\?v=[a-f0-9]+/, '');\n\n const projectMatch = path.match(/\\/Projects\\/blac\\/(.+)/);\n if (projectMatch) {\n path = projectMatch[1];\n }\n\n const segments = path.split('/');\n if (segments.length > 3) {\n path = segments.slice(-3).join('/');\n }\n\n return path;\n }\n\n /** Timestamp of the last state update */\n lastUpdateTimestamp: number = Date.now();\n\n /**\n * Update state using a transform function.\n * @param updater - Function that receives current state and returns new state\n * @protected\n */\n protected update(updater: (current: S) => S): void {\n if (this._disposed) {\n throw new Error(\n `Cannot update state from disposed container ${this.name}`,\n );\n }\n this.emit(updater(this._state));\n }\n\n /**\n * Subscribe to system lifecycle events.\n * @param event - The event type to listen for\n * @param handler - Handler function called when event occurs\n * @returns Unsubscribe function\n * @protected\n */\n protected onSystemEvent = <E extends SystemEvent>(\n event: E,\n handler: SystemEventHandler<S, E>,\n ): (() => void) => {\n let handlers = this.systemEventHandlers.get(event);\n if (!handlers) {\n handlers = new Set();\n this.systemEventHandlers.set(event, handlers);\n }\n handlers.add(handler as SystemEventHandler<S, any>);\n\n return () => {\n handlers?.delete(handler as SystemEventHandler<S, any>);\n };\n };\n\n private emitSystemEvent<E extends SystemEvent>(\n event: E,\n payload: SystemEventPayloads<S>[E],\n ): void {\n const handlers = this.systemEventHandlers.get(event);\n if (!handlers) return;\n\n for (const handler of handlers) {\n try {\n handler(payload);\n } catch (error) {\n console.error(`[${this.name}] Error in system event handler:`, error);\n }\n }\n }\n}\n","import { StateContainer } from './StateContainer';\n\n/**\n * Simple state container with direct state emission.\n * Extends StateContainer with public methods for emitting and updating state.\n *\n * @template S - State type\n */\nexport abstract class Cubit<S extends object = any> extends StateContainer<S> {\n constructor(initialState: S) {\n super(initialState);\n }\n\n /**\n * Replace state with a new value and notify all listeners\n * @param newState - The new state value\n */\n public emit(newState: S): void {\n super['emit'](newState);\n }\n\n /**\n * Transform current state using an updater function and emit the new state\n * @param updater - Function that receives current state and returns new state\n */\n public update(updater: (current: S) => S): void {\n super['update'](updater);\n }\n\n /**\n * Merge partial state changes into current state (only for object states)\n */\n public patch = ((partial: S extends object ? Partial<S> : never): void => {\n if (typeof this.state !== 'object' || this.state === null) {\n throw new Error('patch() is only available for object state types');\n }\n this.update((current) => ({ ...current, ...partial }) as S);\n }) as S extends object ? (partial: Partial<S>) => void : never;\n}\n","import { globalRegistry } from '../core/StateContainerRegistry';\nimport type { StateContainerConstructor } from '../types/utilities';\n\nexport function acquire<T extends StateContainerConstructor>(\n BlocClass: T,\n instanceKey?: string,\n): InstanceType<T> {\n return globalRegistry.acquire(BlocClass, instanceKey, {\n canCreate: true,\n countRef: true,\n });\n}\n","import { globalRegistry } from '../core/StateContainerRegistry';\nimport type { StateContainerConstructor } from '../types/utilities';\n\nexport function borrow<T extends StateContainerConstructor>(\n BlocClass: T,\n instanceKey?: string,\n): InstanceType<T> {\n return globalRegistry.borrow(BlocClass, instanceKey);\n}\n\nexport function borrowSafe<T extends StateContainerConstructor>(\n BlocClass: T,\n instanceKey?: string,\n):\n | { error: Error; instance: null }\n | { error: null; instance: InstanceType<T> } {\n return globalRegistry.borrowSafe(BlocClass, instanceKey);\n}\n","import { globalRegistry } from '../core/StateContainerRegistry';\nimport type { StateContainerConstructor } from '../types/utilities';\n\nexport function release<T extends StateContainerConstructor>(\n BlocClass: T,\n instanceKey?: string,\n forceDispose = false,\n): void {\n globalRegistry.release(BlocClass, instanceKey, forceDispose);\n}\n","import { BLAC_STATIC_PROPS } from '../constants';\n\n/**\n * Configuration options for the @blac decorator.\n * Only one option can be specified at a time (union type).\n */\nexport type BlacOptions =\n /** Mark bloc as isolated (each component gets its own instance) */\n | { isolated: true }\n /** Mark bloc to never be auto-disposed when ref count reaches 0 */\n | { keepAlive: true }\n /** Exclude bloc from DevTools tracking (prevents infinite loops) */\n | { excludeFromDevTools: true };\n\n/**\n * Decorator to configure StateContainer classes.\n *\n * @example Decorator syntax (requires experimentalDecorators or TC39 decorators)\n * ```ts\n * @blac({ isolated: true })\n * class FormBloc extends Cubit<FormState> {}\n *\n * @blac({ keepAlive: true })\n * class AuthBloc extends Cubit<AuthState> {}\n *\n * @blac({ excludeFromDevTools: true })\n * class InternalBloc extends Cubit<InternalState> {}\n * ```\n *\n * @example Function syntax (no decorator support needed)\n * ```ts\n * const FormBloc = blac({ isolated: true })(\n * class extends Cubit<FormState> {}\n * );\n * ```\n */\nexport function blac(options: BlacOptions) {\n return function <T extends new (...args: any[]) => any>(\n target: T,\n _context?: ClassDecoratorContext,\n ): T {\n if ('isolated' in options && options.isolated) {\n (target as any)[BLAC_STATIC_PROPS.ISOLATED] = true;\n }\n if ('keepAlive' in options && options.keepAlive) {\n (target as any)[BLAC_STATIC_PROPS.KEEP_ALIVE] = true;\n }\n if ('excludeFromDevTools' in options && options.excludeFromDevTools) {\n (target as any)[BLAC_STATIC_PROPS.EXCLUDE_FROM_DEVTOOLS] =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