@blac/core 2.0.3 → 2.0.5

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.
Files changed (64) hide show
  1. package/README.md +2 -0
  2. package/dist/constants.d.ts +81 -0
  3. package/dist/core/Cubit.d.ts +24 -0
  4. package/dist/core/StateContainer.d.ts +127 -0
  5. package/dist/core/StateContainerRegistry.d.ts +189 -0
  6. package/dist/debug.d.ts +35 -0
  7. package/dist/decorators/blac.d.ts +40 -0
  8. package/dist/decorators/index.d.ts +1 -0
  9. package/dist/index.cjs +1509 -47
  10. package/dist/index.cjs.map +1 -1
  11. package/dist/index.d.cts +18 -794
  12. package/dist/index.d.ts +18 -794
  13. package/dist/index.js +1463 -10
  14. package/dist/index.js.map +1 -1
  15. package/dist/plugin/BlacPlugin.d.ts +110 -0
  16. package/dist/plugin/PluginManager.d.ts +81 -0
  17. package/dist/plugins.d.ts +25 -0
  18. package/dist/registry/acquire.d.ts +2 -0
  19. package/dist/registry/borrow.d.ts +9 -0
  20. package/dist/registry/config.d.ts +8 -0
  21. package/dist/registry/ensure.d.ts +2 -0
  22. package/dist/registry/index.d.ts +7 -0
  23. package/dist/registry/management.d.ts +4 -0
  24. package/dist/registry/queries.d.ts +5 -0
  25. package/dist/registry/release.d.ts +2 -0
  26. package/dist/tracking/index.d.ts +2 -1
  27. package/dist/tracking/resolve-dependencies.d.ts +7 -0
  28. package/dist/tracking/tracking-proxy.d.ts +0 -14
  29. package/dist/types/branded.d.ts +26 -0
  30. package/dist/types/utilities.d.ts +51 -0
  31. package/dist/utils/idGenerator.d.ts +73 -0
  32. package/dist/utils/static-props.d.ts +35 -0
  33. package/dist/watch/index.d.ts +2 -0
  34. package/dist/watch/watch.d.ts +50 -0
  35. package/dist/watch-entry.d.ts +26 -0
  36. package/package.json +6 -82
  37. package/dist/StateContainerRegistry.cjs.map +0 -1
  38. package/dist/StateContainerRegistry.js.map +0 -1
  39. package/dist/debug.cjs +0 -27
  40. package/dist/debug.cjs.map +0 -1
  41. package/dist/debug.js +0 -19
  42. package/dist/debug.js.map +0 -1
  43. package/dist/dependency-manager.cjs.map +0 -1
  44. package/dist/dependency-manager.js.map +0 -1
  45. package/dist/management.cjs.map +0 -1
  46. package/dist/management.js.map +0 -1
  47. package/dist/plugins.cjs +0 -4
  48. package/dist/plugins.js +0 -3
  49. package/dist/tracking-proxy.cjs.map +0 -1
  50. package/dist/tracking-proxy.js.map +0 -1
  51. package/dist/tracking.cjs +0 -19
  52. package/dist/tracking.d.cts +0 -9
  53. package/dist/tracking.js +0 -4
  54. package/dist/types.cjs +0 -14
  55. package/dist/types.cjs.map +0 -1
  56. package/dist/types.d.cts +0 -8
  57. package/dist/types.js +0 -13
  58. package/dist/types.js.map +0 -1
  59. package/dist/watch-entry.cjs +0 -111
  60. package/dist/watch-entry.cjs.map +0 -1
  61. package/dist/watch-entry.js +0 -107
  62. package/dist/watch-entry.js.map +0 -1
  63. package/dist/watch.cjs.map +0 -1
  64. package/dist/watch.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
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Default configuration constants for BlaC
3
+ *
4
+ * Centralized location for all magic numbers and default values.
5
+ */
6
+ /**
7
+ * Default configuration constants for BlaC
8
+ */
9
+ export declare const BLAC_DEFAULTS: {
10
+ /**
11
+ * Default instance key for shared instances
12
+ */
13
+ readonly DEFAULT_INSTANCE_KEY: "default";
14
+ /**
15
+ * Maximum getter nesting depth (prevents infinite recursion)
16
+ */
17
+ readonly MAX_GETTER_DEPTH: 10;
18
+ /**
19
+ * Default cleanup interval for subscriptions (30 seconds)
20
+ */
21
+ readonly CLEANUP_INTERVAL_MS: 30000;
22
+ /**
23
+ * Cleanup interval for weak reference stage (10 seconds)
24
+ */
25
+ readonly WEAKREF_CLEANUP_INTERVAL_MS: 10000;
26
+ /**
27
+ * Default maximum subscriptions per container
28
+ */
29
+ readonly MAX_SUBSCRIPTIONS: 1000;
30
+ /**
31
+ * Maximum subscriptions for high-performance mode
32
+ */
33
+ readonly MAX_SUBSCRIPTIONS_HIGH_PERF: 10000;
34
+ /**
35
+ * Default timeout for pipeline execution (5 seconds)
36
+ */
37
+ readonly PIPELINE_TIMEOUT_MS: 5000;
38
+ /**
39
+ * Cleanup interval for high-performance mode (5 seconds)
40
+ */
41
+ readonly CLEANUP_INTERVAL_HIGH_PERF_MS: 5000;
42
+ /**
43
+ * Maximum number of stages in a pipeline
44
+ */
45
+ readonly MAX_PIPELINE_STAGES: 30;
46
+ };
47
+ /**
48
+ * Static property names for StateContainer classes
49
+ * Used for feature flags and configuration on bloc classes
50
+ */
51
+ export declare const BLAC_STATIC_PROPS: {
52
+ /**
53
+ * Mark a bloc as isolated (each component gets its own instance)
54
+ */
55
+ readonly ISOLATED: "isolated";
56
+ /**
57
+ * Mark a bloc to never be auto-disposed (kept alive permanently)
58
+ */
59
+ readonly KEEP_ALIVE: "keepAlive";
60
+ /**
61
+ * Exclude a bloc from DevTools reporting (prevents infinite loops)
62
+ */
63
+ readonly EXCLUDE_FROM_DEVTOOLS: "__excludeFromDevTools";
64
+ };
65
+ /**
66
+ * ID generation patterns and constants
67
+ */
68
+ export declare const BLAC_ID_PATTERNS: {
69
+ /**
70
+ * Prefix for isolated instance keys
71
+ */
72
+ readonly ISOLATED_PREFIX: "isolated-";
73
+ /**
74
+ * Length of generated ID portion (9 characters from base36)
75
+ */
76
+ readonly ID_LENGTH: 9;
77
+ };
78
+ /**
79
+ * Standard error message prefix
80
+ */
81
+ export declare const BLAC_ERROR_PREFIX: "[BlaC]";
@@ -0,0 +1,24 @@
1
+ import { StateContainer } from './StateContainer';
2
+ /**
3
+ * Simple state container with direct state emission.
4
+ * Extends StateContainer with public methods for emitting and updating state.
5
+ *
6
+ * @template S - State type
7
+ */
8
+ export declare abstract class Cubit<S extends object = any> extends StateContainer<S> {
9
+ constructor(initialState: S);
10
+ /**
11
+ * Replace state with a new value and notify all listeners
12
+ * @param newState - The new state value
13
+ */
14
+ emit(newState: S): void;
15
+ /**
16
+ * Transform current state using an updater function and emit the new state
17
+ * @param updater - Function that receives current state and returns new state
18
+ */
19
+ update(updater: (current: S) => S): void;
20
+ /**
21
+ * Merge partial state changes into current state (only for object states)
22
+ */
23
+ patch: S extends object ? (partial: Partial<S>) => void : never;
24
+ }
@@ -0,0 +1,127 @@
1
+ import type { StateContainerConstructor } from '../types/utilities';
2
+ /**
3
+ * Configuration options for initializing a StateContainer instance
4
+ */
5
+ export interface StateContainerConfig {
6
+ /** Display name for the instance (defaults to class name) */
7
+ name?: string;
8
+ /** Enable debug logging for this instance */
9
+ debug?: boolean;
10
+ /** Custom instance identifier */
11
+ instanceId?: string;
12
+ }
13
+ /**
14
+ * Listener function for state changes
15
+ * @internal
16
+ */
17
+ type StateListener<S> = (state: S) => void;
18
+ /**
19
+ * System events emitted by StateContainer lifecycle
20
+ */
21
+ export type SystemEvent = 'stateChanged' | 'dispose';
22
+ /**
23
+ * Payload types for each system event
24
+ * @template S - State type
25
+ */
26
+ export interface SystemEventPayloads<S> {
27
+ /** Emitted when state changes via emit() or update() */
28
+ stateChanged: {
29
+ state: S;
30
+ previousState: S;
31
+ };
32
+ /** Emitted when the instance is disposed */
33
+ dispose: void;
34
+ }
35
+ /**
36
+ * Handler function for system events
37
+ * @internal
38
+ */
39
+ type SystemEventHandler<S, E extends SystemEvent> = (payload: SystemEventPayloads<S>[E]) => void;
40
+ /**
41
+ * Abstract base class for all state containers in BlaC.
42
+ * Provides lifecycle management, subscription handling, ref counting,
43
+ * and integration with the global registry.
44
+ *
45
+ * @template S - State type managed by this container
46
+ *
47
+ * @example
48
+ * ```ts
49
+ * class CounterBloc extends StateContainer<{ count: number }> {
50
+ * constructor() {
51
+ * super({ count: 0 });
52
+ * }
53
+ * increment() {
54
+ * this.emit({ count: this.state.count + 1 });
55
+ * }
56
+ * }
57
+ * ```
58
+ */
59
+ export declare abstract class StateContainer<S extends object = any> {
60
+ static __excludeFromDevTools: boolean;
61
+ static enableStackTrace: boolean;
62
+ private _state;
63
+ private readonly listeners;
64
+ private _disposed;
65
+ private config;
66
+ private readonly systemEventHandlers;
67
+ /** Display name for this instance */
68
+ name: string;
69
+ /** Whether debug logging is enabled */
70
+ debug: boolean;
71
+ /** Unique identifier for this instance */
72
+ instanceId: string;
73
+ /** Timestamp when this instance was created */
74
+ createdAt: number;
75
+ private _dependencies;
76
+ get dependencies(): ReadonlyMap<StateContainerConstructor, string>;
77
+ protected depend<T extends StateContainerConstructor>(Type: T, instanceKey?: string): () => InstanceType<T>;
78
+ constructor(initialState: S);
79
+ /**
80
+ * Initialize configuration for this instance.
81
+ * Called by the registry after construction.
82
+ * @param config - Configuration options
83
+ */
84
+ initConfig(config: StateContainerConfig): void;
85
+ /** Current state value */
86
+ get state(): Readonly<S>;
87
+ /** Whether this instance has been disposed */
88
+ get isDisposed(): boolean;
89
+ /**
90
+ * Subscribe to state changes
91
+ * @param listener - Function called when state changes
92
+ * @returns Unsubscribe function
93
+ */
94
+ subscribe(listener: StateListener<S>): () => void;
95
+ /**
96
+ * Dispose this instance and clean up resources.
97
+ * Clears all listeners and emits the 'dispose' system event.
98
+ */
99
+ dispose(): void;
100
+ /**
101
+ * Emit a new state value and notify all listeners.
102
+ * @param newState - The new state value
103
+ * @protected
104
+ */
105
+ protected emit(newState: S): void;
106
+ private captureStackTrace;
107
+ private formatStackLine;
108
+ private cleanFilePath;
109
+ /** Timestamp of the last state update */
110
+ lastUpdateTimestamp: number;
111
+ /**
112
+ * Update state using a transform function.
113
+ * @param updater - Function that receives current state and returns new state
114
+ * @protected
115
+ */
116
+ protected update(updater: (current: S) => S): void;
117
+ /**
118
+ * Subscribe to system lifecycle events.
119
+ * @param event - The event type to listen for
120
+ * @param handler - Handler function called when event occurs
121
+ * @returns Unsubscribe function
122
+ * @protected
123
+ */
124
+ protected onSystemEvent: <E extends SystemEvent>(event: E, handler: SystemEventHandler<S, E>) => (() => void);
125
+ private emitSystemEvent;
126
+ }
127
+ export {};
@@ -0,0 +1,189 @@
1
+ import type { StateContainer } from './StateContainer';
2
+ import { InstanceReadonlyState, StateContainerConstructor } from '../types/utilities';
3
+ /**
4
+ * Entry in the instance registry, tracking the instance and its reference count
5
+ * @template T - Instance type
6
+ */
7
+ export interface InstanceEntry<T = any> {
8
+ /** The state container instance */
9
+ instance: T;
10
+ /** Number of active references to this instance */
11
+ refCount: number;
12
+ }
13
+ /**
14
+ * Lifecycle events emitted by the registry
15
+ */
16
+ export type LifecycleEvent = 'created' | 'stateChanged' | 'disposed';
17
+ /**
18
+ * Listener function type for each lifecycle event
19
+ * @template E - The lifecycle event type
20
+ */
21
+ export type LifecycleListener<E extends LifecycleEvent> = E extends 'created' ? (container: StateContainer<any>) => void : E extends 'stateChanged' ? (container: StateContainer<any>, previousState: any, currentState: any, callstack?: string) => void : E extends 'disposed' ? (container: StateContainer<any>) => void : never;
22
+ /**
23
+ * Central registry for managing StateContainer instances.
24
+ * Handles instance lifecycle, ref counting, and lifecycle event emission.
25
+ *
26
+ * @example
27
+ * ```ts
28
+ * const registry = new StateContainerRegistry();
29
+ * const instance = registry.acquire(MyBloc); // ownership, must release
30
+ * const other = registry.ensure(OtherBloc); // no ownership, bloc-to-bloc
31
+ * registry.on('stateChanged', (container, prev, next) => {
32
+ * console.log('State changed:', prev, '->', next);
33
+ * });
34
+ * ```
35
+ */
36
+ export declare class StateContainerRegistry {
37
+ private readonly instancesByConstructor;
38
+ private readonly types;
39
+ private readonly typeConfigs;
40
+ private readonly listeners;
41
+ /**
42
+ * Register a type for lifecycle event tracking
43
+ * @param constructor - The StateContainer class constructor
44
+ */
45
+ registerType<T extends StateContainerConstructor>(constructor: T): void;
46
+ /**
47
+ * Register a StateContainer class with configuration
48
+ * @param constructor - The StateContainer class constructor
49
+ * @param isolated - Whether instances should be isolated (component-scoped)
50
+ * @throws Error if type is already registered
51
+ */
52
+ register<T extends StateContainerConstructor>(constructor: T, isolated?: boolean): void;
53
+ private ensureInstancesMap;
54
+ /**
55
+ * Get the instances Map for a specific class (public API for stats/debugging)
56
+ */
57
+ getInstancesMap<T extends StateContainerConstructor>(Type: T): Map<string, InstanceEntry>;
58
+ /**
59
+ * Acquire an instance with ref counting (ownership semantics).
60
+ * Creates a new instance if one doesn't exist, or returns existing and increments ref count.
61
+ * You must call `release()` when done to decrement the ref count.
62
+ * @param Type - The StateContainer class constructor
63
+ * @param instanceKey - Instance key (defaults to 'default')
64
+ * @param options - Acquisition options
65
+ * @param options.canCreate - Whether to create new instance if not found (default: true)
66
+ * @param options.countRef - Whether to increment ref count (default: true)
67
+ * @returns The state container instance
68
+ */
69
+ acquire<T extends StateContainerConstructor = StateContainerConstructor>(Type: T, instanceKey?: string, options?: {
70
+ canCreate?: boolean;
71
+ countRef?: boolean;
72
+ }): InstanceType<T>;
73
+ /**
74
+ * Borrow an existing instance without incrementing ref count (borrowing semantics).
75
+ * Tracks cross-bloc dependency for reactive updates.
76
+ * @param Type - The StateContainer class constructor
77
+ * @param instanceKey - Instance key (defaults to 'default')
78
+ * @returns The state container instance
79
+ * @throws Error if instance doesn't exist
80
+ */
81
+ borrow<T extends StateContainerConstructor = StateContainerConstructor>(Type: T, instanceKey?: string): InstanceType<T>;
82
+ /**
83
+ * Safely borrow an existing instance (borrowing semantics with error handling).
84
+ * Returns discriminated union for type-safe conditional access.
85
+ * @param Type - The StateContainer class constructor
86
+ * @param instanceKey - Instance key (defaults to 'default')
87
+ * @returns Discriminated union with either the instance or an error
88
+ */
89
+ borrowSafe<T extends StateContainerConstructor = StateContainerConstructor>(Type: T, instanceKey?: string): {
90
+ error: Error;
91
+ instance: null;
92
+ } | {
93
+ error: null;
94
+ instance: InstanceType<T>;
95
+ };
96
+ /**
97
+ * Ensure an instance exists without taking ownership (for bloc-to-bloc communication).
98
+ * Gets existing instance OR creates it if it doesn't exist, without incrementing ref count.
99
+ * Tracks cross-bloc dependency for reactive updates.
100
+ *
101
+ * Use this in bloc-to-bloc communication when you need to ensure an instance exists
102
+ * but don't want to claim ownership (no ref count increment).
103
+ * @param Type - The StateContainer class constructor
104
+ * @param instanceKey - Instance key (defaults to 'default')
105
+ * @returns The state container instance
106
+ */
107
+ ensure<T extends StateContainerConstructor = StateContainerConstructor>(Type: T, instanceKey?: string): InstanceType<T>;
108
+ /**
109
+ * Release a reference to an instance.
110
+ * Decrements ref count and disposes when it reaches 0 (unless keepAlive).
111
+ * @param Type - The StateContainer class constructor
112
+ * @param instanceKey - Instance key (defaults to 'default')
113
+ * @param forceDispose - Force immediate disposal regardless of ref count
114
+ */
115
+ release<T extends StateContainerConstructor>(Type: T, instanceKey?: string, forceDispose?: boolean): void;
116
+ /**
117
+ * Get all instances of a specific type.
118
+ * @param Type - The StateContainer class constructor
119
+ * @returns Array of all instances
120
+ */
121
+ getAll<T extends StateContainerConstructor>(Type: T): InstanceReadonlyState<T>[];
122
+ /**
123
+ * Safely iterate over all instances of a type.
124
+ * Skips disposed instances and catches callback errors.
125
+ * @param Type - The StateContainer class constructor
126
+ * @param callback - Function to call for each instance
127
+ */
128
+ forEach<T extends StateContainerConstructor>(Type: T, callback: (instance: InstanceReadonlyState<T>) => void): void;
129
+ /**
130
+ * Clear all instances of a specific type (disposes them).
131
+ * @param Type - The StateContainer class constructor
132
+ */
133
+ clear<T extends StateContainerConstructor>(Type: T): void;
134
+ /**
135
+ * Get reference count for an instance.
136
+ * @param Type - The StateContainer class constructor
137
+ * @param instanceKey - Instance key (defaults to 'default')
138
+ * @returns Current ref count (0 if instance doesn't exist)
139
+ */
140
+ getRefCount<T extends StateContainerConstructor>(Type: T, instanceKey?: string): number;
141
+ /**
142
+ * Check if an instance exists.
143
+ * @param Type - The StateContainer class constructor
144
+ * @param instanceKey - Instance key (defaults to 'default')
145
+ * @returns true if instance exists
146
+ */
147
+ hasInstance<T extends StateContainerConstructor>(Type: T, instanceKey?: string): boolean;
148
+ /**
149
+ * Clear all instances from all types (for testing)
150
+ *
151
+ * Iterates all registered types and clears their instances.
152
+ * Also clears type tracking to reset the registry state.
153
+ */
154
+ clearAll(): void;
155
+ /**
156
+ * Get registry statistics for debugging.
157
+ * @returns Object with registeredTypes, totalInstances, and typeBreakdown
158
+ */
159
+ getStats(): {
160
+ registeredTypes: number;
161
+ totalInstances: number;
162
+ typeBreakdown: Record<string, number>;
163
+ };
164
+ /**
165
+ * Get all registered types (for plugin system).
166
+ * @returns Array of all registered StateContainer class constructors
167
+ */
168
+ getTypes(): StateContainerConstructor[];
169
+ /**
170
+ * Subscribe to lifecycle events
171
+ * @param event - The lifecycle event to listen for
172
+ * @param listener - The listener function to call when the event occurs
173
+ * @returns Unsubscribe function
174
+ */
175
+ on<E extends LifecycleEvent>(event: E, listener: LifecycleListener<E>): () => void;
176
+ /**
177
+ * Emit lifecycle event to all listeners
178
+ * @internal - Called by StateContainer lifecycle methods
179
+ */
180
+ emit(event: LifecycleEvent, ...args: any[]): void;
181
+ }
182
+ /**
183
+ * Global default registry instance
184
+ */
185
+ export declare const globalRegistry: StateContainerRegistry;
186
+ /**
187
+ * Get the global plugin manager
188
+ */
189
+ export declare function getPluginManager(): any;
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Debug/Advanced Subpath Export
3
+ *
4
+ * Advanced registry introspection and debugging utilities.
5
+ * Import from '@blac/core/debug'
6
+ *
7
+ * These utilities are intended for debugging, testing, and advanced use cases.
8
+ * Most applications don't need these - use the main '@blac/core' exports instead.
9
+ *
10
+ * @example
11
+ * ```typescript
12
+ * import { getStats, globalRegistry, hasInstance } from '@blac/core/debug';
13
+ *
14
+ * // Get registry statistics
15
+ * const stats = getStats();
16
+ * console.log(`Total instances: ${stats.totalInstances}`);
17
+ *
18
+ * // Check if an instance exists
19
+ * if (hasInstance(UserBloc)) {
20
+ * console.log('UserBloc is registered');
21
+ * }
22
+ *
23
+ * // Iterate over all instances of a type
24
+ * forEach(UserBloc, (instance) => {
25
+ * console.log(instance.state);
26
+ * });
27
+ * ```
28
+ *
29
+ * @packageDocumentation
30
+ */
31
+ export { hasInstance, getRefCount, getAll, forEach } from './registry/queries';
32
+ export { register } from './registry/management';
33
+ export { getRegistry, setRegistry, getStats } from './registry/config';
34
+ export { globalRegistry } from './core/StateContainerRegistry';
35
+ export type { LifecycleEvent, LifecycleListener, InstanceEntry, } from './core/StateContainerRegistry';
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Configuration options for the @blac decorator.
3
+ * Only one option can be specified at a time (union type).
4
+ */
5
+ export type BlacOptions =
6
+ /** Mark bloc as isolated (each component gets its own instance) */
7
+ {
8
+ isolated: true;
9
+ }
10
+ /** Mark bloc to never be auto-disposed when ref count reaches 0 */
11
+ | {
12
+ keepAlive: true;
13
+ }
14
+ /** Exclude bloc from DevTools tracking (prevents infinite loops) */
15
+ | {
16
+ excludeFromDevTools: true;
17
+ };
18
+ /**
19
+ * Decorator to configure StateContainer classes.
20
+ *
21
+ * @example Decorator syntax (requires experimentalDecorators or TC39 decorators)
22
+ * ```ts
23
+ * @blac({ isolated: true })
24
+ * class FormBloc extends Cubit<FormState> {}
25
+ *
26
+ * @blac({ keepAlive: true })
27
+ * class AuthBloc extends Cubit<AuthState> {}
28
+ *
29
+ * @blac({ excludeFromDevTools: true })
30
+ * class InternalBloc extends Cubit<InternalState> {}
31
+ * ```
32
+ *
33
+ * @example Function syntax (no decorator support needed)
34
+ * ```ts
35
+ * const FormBloc = blac({ isolated: true })(
36
+ * class extends Cubit<FormState> {}
37
+ * );
38
+ * ```
39
+ */
40
+ export declare function blac(options: BlacOptions): <T extends new (...args: any[]) => any>(target: T, _context?: ClassDecoratorContext) => T;
@@ -0,0 +1 @@
1
+ export { blac, type BlacOptions } from './blac';