@blac/core 2.0.0-rc-14 → 2.0.0-rc-16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts DELETED
@@ -1,1303 +0,0 @@
1
- /**
2
- * Adapter metadata provided to plugins
3
- */
4
- export declare interface AdapterMetadata {
5
- componentName?: string;
6
- blocInstance: BlocBase<any>;
7
- renderCount: number;
8
- trackedPaths?: string[];
9
- isUsingDependencies?: boolean;
10
- lastState?: any;
11
- lastDependencyValues?: any[];
12
- currentDependencyValues?: any[];
13
- }
14
-
15
- export declare interface AdapterOptions<B extends BlocBase<any>> {
16
- instanceId?: string;
17
- dependencies?: (bloc: B) => unknown[];
18
- staticProps?: any;
19
- onMount?: (bloc: B) => void;
20
- onUnmount?: (bloc: B) => void;
21
- }
22
-
23
- /**
24
- * Main Blac class that manages the state management system.
25
- * Can work with singleton pattern or dependency injection.
26
- * Handles bloc lifecycle, and instance tracking.
27
- *
28
- * Key responsibilities:
29
- * - Managing bloc instances (creation, disposal, lookup)
30
- * - Handling isolated and non-isolated blocs
31
- * - Providing logging and debugging capabilities
32
- */
33
- export declare class Blac {
34
- static get instance(): Blac;
35
- /** Timestamp when the instance was created */
36
- createdAt: number;
37
- private errorManager;
38
- static get getAllBlocs(): <B extends BlocConstructor<any>>(blocClass: B, options?: {
39
- searchIsolated?: boolean;
40
- }) => InstanceType<B>[];
41
- /** Private static configuration */
42
- private static _config;
43
- /** Get current configuration */
44
- static get config(): Readonly<BlacConfig>;
45
- /**
46
- * Set or update Blac configuration
47
- * @param config - Partial configuration to merge with existing config
48
- * @throws Error if configuration is invalid
49
- */
50
- static setConfig(config: Partial<BlacConfig>): void;
51
- /** Map storing all registered bloc instances by their class name and ID */
52
- blocInstanceMap: Map<string, BlocBase<unknown>>;
53
- /** Map storing isolated bloc instances grouped by their constructor */
54
- isolatedBlocMap: Map<BlocConstructor<any>, BlocBase<unknown>[]>;
55
- /** Map for O(1) lookup of isolated blocs by UID */
56
- isolatedBlocIndex: Map<string, BlocBase<unknown>>;
57
- /** Map tracking UIDs to prevent memory leaks */
58
- uidRegistry: Map<string, BlocBase<unknown>>;
59
- /** Set of keep-alive blocs for controlled cleanup */
60
- keepAliveBlocs: Set<BlocBase<unknown>>;
61
- /** Flag to control whether changes should be posted to document */
62
- postChangesToDocument: boolean;
63
- /** System plugin registry */
64
- readonly plugins: SystemPluginRegistry;
65
- /**
66
- * Creates a new Blac instance.
67
- * @param options - Configuration options including singleton control
68
- */
69
- constructor(options?: {
70
- __unsafe_ignore_singleton?: boolean;
71
- });
72
- /** Flag to enable/disable logging */
73
- static enableLog: boolean;
74
- static logLevel: 'warn' | 'log';
75
- static logSpy: ((...args: unknown[]) => void) | null;
76
- /**
77
- * Logs messages to console when logging is enabled
78
- * @param args - Arguments to log
79
- */
80
- log: (...args: unknown[]) => void;
81
- static get log(): (...args: unknown[]) => void;
82
- /**
83
- * Gets the current Blac instance
84
- * @returns The Blac instance
85
- */
86
- static getInstance(): Blac;
87
- /**
88
- * Logs a warning message
89
- * @param message - Warning message
90
- * @param args - Additional arguments
91
- */
92
- warn: (message: string, ...args: unknown[]) => void;
93
- static get warn(): (message: string, ...args: unknown[]) => void;
94
- /**
95
- * Logs an error message
96
- * @param message - Error message
97
- * @param args - Additional arguments
98
- */
99
- error: (message: string, ...args: unknown[]) => void;
100
- static get error(): (message: string, ...args: unknown[]) => void;
101
- /**
102
- * Resets the Blac instance to a new one, disposing non-keepAlive blocs
103
- * from the old instance.
104
- */
105
- resetInstance: () => void;
106
- static resetInstance: () => void;
107
- /**
108
- * Disposes of a bloc instance by removing it from the appropriate registry
109
- * @param bloc - The bloc instance to dispose
110
- */
111
- disposeBloc: (bloc: BlocBase<unknown>) => void;
112
- static get disposeBloc(): (bloc: BlocBase<unknown>) => void;
113
- /**
114
- * Creates a unique key for a bloc instance in the map based on the bloc class name and instance ID
115
- * @param blocClassName - The name of the bloc class
116
- * @param id - The instance ID
117
- * @returns A unique key string in the format "className:id"
118
- */
119
- createBlocInstanceMapKey(blocClassName: string, id: BlocInstanceId): string;
120
- /**
121
- * Unregister a bloc instance from the main registry
122
- * @param bloc - The bloc instance to unregister
123
- */
124
- unregisterBlocInstance(bloc: BlocBase<unknown>): void;
125
- /**
126
- * Registers a bloc instance in the main registry
127
- * @param bloc - The bloc instance to register
128
- */
129
- registerBlocInstance(bloc: BlocBase<unknown>): void;
130
- /**
131
- * Finds a registered bloc instance by its class and ID
132
- * @param blocClass - The bloc class to search for
133
- * @param id - The instance ID
134
- * @returns The found bloc instance or undefined if not found
135
- */
136
- findRegisteredBlocInstance<B extends BlocConstructor<any>>(blocClass: B, id: BlocInstanceId): InstanceType<B> | undefined;
137
- /**
138
- * Registers an isolated bloc instance in the isolated registry
139
- * @param bloc - The isolated bloc instance to register
140
- */
141
- registerIsolatedBlocInstance(bloc: BlocBase<unknown>): void;
142
- /**
143
- * Unregister an isolated bloc instance from the isolated registry
144
- * @param bloc - The isolated bloc instance to unregister
145
- */
146
- unregisterIsolatedBlocInstance(bloc: BlocBase<unknown>): void;
147
- /**
148
- * Finds an isolated bloc instance by its class and ID (O(n) lookup)
149
- */
150
- findIsolatedBlocInstance<B extends BlocConstructor<any>>(blocClass: B, id: BlocInstanceId): InstanceType<B> | undefined;
151
- /**
152
- * Finds an isolated bloc instance by UID (O(1) lookup)
153
- */
154
- findIsolatedBlocInstanceByUid<B extends BlocBase<unknown>>(uid: string): B | undefined;
155
- /**
156
- * Creates a new bloc instance and registers it in the appropriate registry
157
- * @param blocClass - The bloc class to instantiate
158
- * @param id - The instance ID
159
- * @param props - Properties to pass to the bloc constructor
160
- * @param instanceRef - Optional reference string for the instance
161
- * @returns The newly created bloc instance
162
- */
163
- createNewBlocInstance<B extends BlocConstructor<BlocBase<any>>>(blocClass: B, id: BlocInstanceId, options?: GetBlocOptions<InstanceType<B>>): InstanceType<B>;
164
- activateBloc: (bloc: BlocBase<unknown>) => void;
165
- static get activateBloc(): (bloc: BlocBase<unknown>) => void;
166
- /**
167
- * Gets or creates a bloc instance based on the provided class and options.
168
- * If a bloc with the given ID exists, it will be returned. Otherwise, a new instance will be created.
169
- *
170
- * @param blocClass - The bloc class to get or create
171
- * @param options - Options including:
172
- * - id: The instance ID (defaults to class name if not provided)
173
- * - props: Properties to pass to the bloc constructor
174
- * - instanceRef: Optional reference string for the instance
175
- * @returns The bloc instance
176
- */
177
- getBloc: <B extends BlocConstructor<BlocBase<any>>>(blocClass: B, options?: GetBlocOptions<InstanceType<B>>) => InstanceType<B>;
178
- static get getBloc(): <B extends BlocConstructor<BlocBase<any>>>(blocClass: B, options?: GetBlocOptions<InstanceType<B>>) => InstanceType<B>;
179
- /**
180
- * Gets all instances of a specific bloc class
181
- * @param blocClass - The bloc class to search for
182
- * @param options - Options including:
183
- * - searchIsolated: Whether to search in isolated blocs (defaults to bloc's isolated property)
184
- * @returns Array of matching bloc instances
185
- */
186
- getAllBlocs: <B extends BlocConstructor<any>>(blocClass: B, options?: {
187
- searchIsolated?: boolean;
188
- }) => InstanceType<B>[];
189
- /**
190
- * Disposes all keep-alive blocs of a specific type
191
- * @param blocClass - The bloc class to dispose
192
- */
193
- disposeKeepAliveBlocs: <B extends BlocConstructor<any>>(blocClass?: B) => void;
194
- static get disposeKeepAliveBlocs(): <B extends BlocConstructor<any>>(blocClass?: B | undefined) => void;
195
- /**
196
- * Disposes all blocs matching a pattern
197
- * @param predicate - Function to test each bloc for disposal
198
- */
199
- disposeBlocs: (predicate: (bloc: BlocBase<unknown>) => boolean) => void;
200
- static get disposeBlocs(): (predicate: (bloc: BlocBase<unknown>) => boolean) => void;
201
- /**
202
- * Gets memory usage statistics for debugging
203
- */
204
- getMemoryStats: () => {
205
- totalBlocs: number;
206
- registeredBlocs: number;
207
- isolatedBlocs: number;
208
- keepAliveBlocs: number;
209
- isolatedBlocTypes: number;
210
- };
211
- static get getMemoryStats(): () => {
212
- totalBlocs: number;
213
- registeredBlocs: number;
214
- isolatedBlocs: number;
215
- keepAliveBlocs: number;
216
- isolatedBlocTypes: number;
217
- };
218
- /**
219
- * Validates subscription references and cleans up orphaned blocs
220
- */
221
- validateConsumers: () => void;
222
- static get validateConsumers(): () => void;
223
- /**
224
- * Bootstrap the Blac instance and all plugins
225
- */
226
- bootstrap(): void;
227
- /**
228
- * Shutdown the Blac instance and all plugins
229
- */
230
- shutdown(): void;
231
- }
232
-
233
- /**
234
- * BlacAdapter orchestrates the connection between Bloc instances and React components.
235
- * It manages dependency tracking, lifecycle hooks, and proxy creation.
236
- */
237
- export declare class BlacAdapter<B extends BlocConstructor<BlocBase<any>>> {
238
- readonly id: string;
239
- readonly blocConstructor: B;
240
- readonly componentRef: {
241
- current: object;
242
- };
243
- blocInstance: InstanceType<B>;
244
- unmountTime: number;
245
- mountTime: number;
246
- private subscriptionId?;
247
- private unsubscribe?;
248
- private dependencyValues?;
249
- private isUsingDependencies;
250
- private trackedPaths;
251
- private pendingTrackedPaths;
252
- private cachedStateProxy?;
253
- private cachedBlocProxy?;
254
- private lastProxiedState?;
255
- private hasMounted;
256
- private mountCount;
257
- private lastState?;
258
- private lastDependencyValues?;
259
- private componentName?;
260
- private renderCount;
261
- private lastDependenciesFn?;
262
- options?: AdapterOptions<InstanceType<B>>;
263
- constructor(instanceProps: {
264
- componentRef: {
265
- current: object;
266
- };
267
- blocConstructor: B;
268
- }, options?: typeof BlacAdapter.options);
269
- trackAccess(consumerRef: object, type: 'state' | 'class', path: string, value?: any): void;
270
- updateBlocInstance(): InstanceType<B>;
271
- createSubscription: (options: {
272
- onChange: () => void;
273
- }) => () => void;
274
- hasDependencyValuesChanged: (oldValues: unknown[] | undefined, newValues: unknown[]) => boolean;
275
- getStateProxy: () => BlocState<InstanceType<B>>;
276
- getBlocProxy: () => InstanceType<B>;
277
- createStateProxy: <T extends object>(props: {
278
- target: T;
279
- }) => T;
280
- createClassProxy: <T extends object>(props: {
281
- target: T;
282
- }) => T;
283
- mount: () => void;
284
- unmount: () => void;
285
- resetTracking(): void;
286
- setComponentName(name: string): void;
287
- notifyRender(): void;
288
- private getAdapterMetadata;
289
- private getValueAtPath;
290
- private getStateChangedPaths;
291
- private getDeepChangedPaths;
292
- getLastRerenderReason(): any;
293
- }
294
-
295
- /**
296
- * Configuration options for the Blac instance
297
- */
298
- export declare interface BlacConfig {
299
- /**
300
- * Whether to enable proxy dependency tracking for automatic re-render optimization.
301
- * When false, state changes always cause re-renders unless dependencies are manually specified.
302
- * Default: true
303
- */
304
- proxyDependencyTracking?: boolean;
305
- }
306
-
307
- export declare class BlacError extends Error {
308
- readonly category: ErrorCategory;
309
- readonly severity: ErrorSeverity;
310
- readonly context?: BlacErrorContext | undefined;
311
- readonly cause?: unknown | undefined;
312
- constructor(message: string, category: ErrorCategory, severity: ErrorSeverity, context?: BlacErrorContext | undefined, cause?: unknown | undefined);
313
- toString(): string;
314
- }
315
-
316
- export declare type BlacErrorContext = {
317
- blocName?: string;
318
- blocId?: string;
319
- consumerId?: string;
320
- pluginName?: string;
321
- operation?: string;
322
- metadata?: Record<string, unknown>;
323
- };
324
-
325
- /**
326
- * Interface for Blac instance management
327
- */
328
- export declare interface BlacInstanceManager {
329
- getInstance(): Blac;
330
- setInstance(instance: Blac): void;
331
- resetInstance(): void;
332
- }
333
-
334
- /**
335
- * System-wide plugin that observes all blocs
336
- */
337
- export declare interface BlacPlugin extends Plugin_2 {
338
- beforeBootstrap?(): void;
339
- afterBootstrap?(): void;
340
- beforeShutdown?(): void;
341
- afterShutdown?(): void;
342
- onBlocCreated?(bloc: BlocBase<any>): void;
343
- onBlocDisposed?(bloc: BlocBase<any>): void;
344
- onStateChanged?(bloc: BlocBase<any>, previousState: any, currentState: any): void;
345
- onEventAdded?(bloc: Bloc<any, any>, event: any): void;
346
- onError?(error: Error, bloc: BlocBase<unknown>, context: ErrorContext): void;
347
- onAdapterCreated?(adapter: any, metadata: AdapterMetadata): void;
348
- onAdapterMount?(adapter: any, metadata: AdapterMetadata): void;
349
- onAdapterUnmount?(adapter: any, metadata: AdapterMetadata): void;
350
- onAdapterRender?(adapter: any, metadata: AdapterMetadata): void;
351
- onAdapterDisposed?(adapter: any, metadata: AdapterMetadata): void;
352
- }
353
-
354
- export declare abstract class Bloc<S, // State type
355
- A extends BlocEventConstraint = BlocEventConstraint> extends BlocBase<S> {
356
- readonly eventHandlers: Map<new (...args: any[]) => A, (event: A, emit: (newState: S) => void) => void | Promise<void>>;
357
- /* Excluded from this release type: _eventQueue */
358
- /* Excluded from this release type: _isProcessingEvent */
359
- /**
360
- * Registers an event handler for a specific event type.
361
- * This method is typically called in the constructor of a derived Bloc class.
362
- * @param eventConstructor The constructor of the event to handle (e.g., LoadDataEvent).
363
- * @param handler A function that processes the event and can emit new states.
364
- * The 'event' parameter in the handler will be typed to the specific eventConstructor.
365
- */
366
- protected on<E extends A>(eventConstructor: new (...args: any[]) => E, handler: (event: E, emit: (newState: S) => void) => void | Promise<void>): void;
367
- /**
368
- * Dispatches an action/event to the Bloc.
369
- * Events are queued and processed sequentially to prevent race conditions.
370
- * @param action The action/event instance to be processed.
371
- */
372
- add: (action: A) => Promise<void>;
373
- /* Excluded from this release type: _processEventQueue */
374
- /* Excluded from this release type: _processEvent */
375
- }
376
-
377
- /**
378
- * Base class for both Blocs and Cubits using unified subscription model.
379
- */
380
- export declare abstract class BlocBase<S> {
381
- uid: string;
382
- blacInstance?: Blac;
383
- static isolated: boolean;
384
- get isIsolated(): boolean;
385
- static keepAlive: boolean;
386
- get isKeepAlive(): boolean;
387
- _isolated: boolean;
388
- _id: BlocInstanceId;
389
- _instanceRef?: string;
390
- _name: string;
391
- /**
392
- * Unified subscription manager for all state notifications
393
- */
394
- _subscriptionManager: SubscriptionManager<S>;
395
- _state: S;
396
- private _lifecycleManager;
397
- private _batchingManager;
398
- _keepAlive: boolean;
399
- lastUpdate?: number;
400
- _plugins: BlocPluginRegistry<S, any>;
401
- onDispose?: () => void;
402
- /**
403
- * Creates a new BlocBase instance with unified subscription management
404
- */
405
- constructor(initialState: S);
406
- /**
407
- * Returns the current state
408
- */
409
- get state(): S;
410
- /**
411
- * Subscribe to all state changes
412
- */
413
- subscribe(callback: (state: S) => void): () => void;
414
- /**
415
- * Subscribe with a selector for optimized updates
416
- */
417
- subscribeWithSelector<T>(selector: (state: S) => T, callback: (value: T) => void, equalityFn?: (a: T, b: T) => boolean): () => void;
418
- /**
419
- * Subscribe with React component reference for automatic cleanup
420
- */
421
- subscribeComponent(componentRef: WeakRef<object>, callback: () => void): () => void;
422
- /**
423
- * Get current subscription count
424
- */
425
- get subscriptionCount(): number;
426
- /**
427
- * Track property access for a subscription
428
- */
429
- trackAccess(subscriptionId: string, path: string, value?: unknown): void;
430
- /**
431
- * Emit a new state
432
- */
433
- protected emit(newState: S, action?: unknown): void;
434
- /**
435
- * Internal state push method used by Bloc
436
- */
437
- _pushState(newState: S, oldState: S, action?: unknown): void;
438
- _batchUpdates(callback: () => void): void;
439
- /**
440
- * Add a plugin
441
- */
442
- addPlugin(plugin: BlocPlugin<S, any>): void;
443
- /**
444
- * Remove a plugin
445
- */
446
- removePlugin(plugin: BlocPlugin<S, any>): void;
447
- /**
448
- * Get all plugins
449
- */
450
- get plugins(): ReadonlyArray<BlocPlugin<S, any>>;
451
- /**
452
- * Disposal management
453
- */
454
- get isDisposed(): boolean;
455
- /**
456
- * Atomic state transition for disposal
457
- */
458
- _atomicStateTransition(expectedState: BlocLifecycleState, newState: BlocLifecycleState): StateTransitionResult;
459
- /**
460
- * Dispose the bloc and clean up resources
461
- */
462
- dispose(): Promise<void>;
463
- /**
464
- * Schedule disposal when no subscriptions remain
465
- */
466
- _scheduleDisposal(): void;
467
- /**
468
- * Set disposal handler
469
- */
470
- setDisposalHandler(handler: (bloc: BlocBase<unknown>) => void): void;
471
- /**
472
- * Check if disposal should be scheduled (called by subscription manager)
473
- */
474
- checkDisposal(): void;
475
- /**
476
- * Cancel disposal if bloc is in disposal_requested state
477
- */
478
- _cancelDisposalIfRequested(): void;
479
- }
480
-
481
- /**
482
- * Represents the abstract base types for Bloc and Cubit
483
- */
484
- export declare type BlocBaseAbstract = typeof Bloc<any, any> | typeof Cubit<any>;
485
-
486
- /**
487
- * Represents a constructor type for a Bloc that takes no parameters
488
- * @template B - The type of the Bloc instance
489
- */
490
- export declare type BlocClassNoParams<B> = new (args: never[]) => B;
491
-
492
- /**
493
- * Represents a constructor type for a Bloc that can take any parameters
494
- * @template B - The type of the Bloc instance
495
- */
496
- export declare type BlocConstructor<B> = (new (...args: any) => B) & {
497
- isolated?: boolean;
498
- keepAlive?: boolean;
499
- };
500
-
501
- export declare type BlocConstructorParams<B extends BlocConstructor<BlocBase<any>>> = ConstructorParameters<B>[0];
502
-
503
- /**
504
- * Error boundary interface for Bloc error handling
505
- */
506
- export declare interface BlocErrorBoundary<S, A extends BlocEventConstraint> {
507
- onError: (error: Error, event: A, currentState: S, bloc: {
508
- name: string;
509
- id: string;
510
- }) => void | Promise<void>;
511
- shouldRethrow?: (error: Error, event: A) => boolean;
512
- }
513
-
514
- /**
515
- * Enhanced constraint for Bloc events - must be objects with proper constructor
516
- */
517
- export declare type BlocEventConstraint = object;
518
-
519
- /**
520
- * Function type for determining dependencies that trigger re-renders
521
- * Similar to React's useEffect dependency array - if any dependency changes, a re-render is triggered
522
- * @template S The state type
523
- * @template I The bloc instance type
524
- * @param currentState The current state
525
- * @param previousState The previous state (undefined on first call)
526
- * @param instance The bloc instance
527
- * @returns Array of dependencies - if any dependency changes, a re-render is triggered
528
- */
529
- export declare type BlocHookDependencyArrayFn<S, I = any> = (currentState: S, previousState: S | undefined, instance: I) => unknown[];
530
-
531
- export declare type BlocInstanceId = string | number | undefined;
532
-
533
- /**
534
- * Manages the lifecycle state transitions for Bloc instances.
535
- * Ensures atomic state transitions to prevent race conditions during disposal.
536
- */
537
- export declare class BlocLifecycleManager {
538
- private disposalState;
539
- private disposalLock;
540
- private disposalTimer?;
541
- private disposalHandler?;
542
- get currentState(): BlocLifecycleState;
543
- get isDisposed(): boolean;
544
- /**
545
- * Atomic state transition for disposal
546
- */
547
- atomicStateTransition(expectedState: BlocLifecycleState, newState: BlocLifecycleState): StateTransitionResult;
548
- /**
549
- * Schedule disposal after a delay
550
- */
551
- scheduleDisposal(delay: number, canDispose: () => boolean, onDispose: () => void): void;
552
- /**
553
- * Cancel disposal if in disposal requested state
554
- */
555
- cancelDisposal(): boolean;
556
- /**
557
- * Set disposal handler
558
- */
559
- setDisposalHandler(handler: (bloc: unknown) => void): void;
560
- /**
561
- * Get disposal handler
562
- */
563
- getDisposalHandler(): ((bloc: unknown) => void) | undefined;
564
- /**
565
- * Clear disposal timer
566
- */
567
- clearDisposalTimer(): void;
568
- }
569
-
570
- /**
571
- * Enum representing the lifecycle states of a Bloc instance
572
- */
573
- export declare enum BlocLifecycleState {
574
- ACTIVE = "active",
575
- DISPOSAL_REQUESTED = "disposal_requested",
576
- DISPOSING = "disposing",
577
- DISPOSED = "disposed"
578
- }
579
-
580
- /**
581
- * Bloc-specific plugin that can transform behavior
582
- */
583
- export declare interface BlocPlugin<TState = any, TEvent = never> extends Plugin_2 {
584
- transformState?(previousState: TState, nextState: TState): TState;
585
- transformEvent?(event: TEvent): TEvent | null;
586
- onAttach?(bloc: BlocBase<TState>): void;
587
- onDetach?(): void;
588
- onStateChange?(previousState: TState, currentState: TState): void;
589
- onEvent?(event: TEvent): void;
590
- onError?(error: Error, context: ErrorContext): void;
591
- }
592
-
593
- /**
594
- * Registry for bloc-specific plugins
595
- */
596
- export declare class BlocPluginRegistry<TState, TEvent = never> implements PluginRegistry<BlocPlugin<TState, TEvent>> {
597
- private plugins;
598
- private executionOrder;
599
- private attached;
600
- /**
601
- * Add a bloc plugin
602
- */
603
- add(plugin: BlocPlugin<TState, TEvent>): void;
604
- /**
605
- * Remove a bloc plugin
606
- */
607
- remove(pluginName: string): boolean;
608
- /**
609
- * Get a plugin by name
610
- */
611
- get(pluginName: string): BlocPlugin<TState, TEvent> | undefined;
612
- /**
613
- * Get all plugins in execution order
614
- */
615
- getAll(): ReadonlyArray<BlocPlugin<TState, TEvent>>;
616
- /**
617
- * Clear all plugins
618
- */
619
- clear(): void;
620
- /**
621
- * Attach all plugins to a bloc
622
- */
623
- attach(bloc: any): void;
624
- /**
625
- * Transform state through all plugins
626
- */
627
- transformState(previousState: TState, nextState: TState): TState;
628
- /**
629
- * Transform event through all plugins
630
- */
631
- transformEvent(event: TEvent): TEvent | null;
632
- /**
633
- * Notify plugins of state change
634
- */
635
- notifyStateChange(previousState: TState, currentState: TState): void;
636
- /**
637
- * Notify plugins of event
638
- */
639
- notifyEvent(event: TEvent): void;
640
- /**
641
- * Notify plugins of error
642
- */
643
- notifyError(error: Error, context: ErrorContext): void;
644
- private validateCapabilities;
645
- private canReadState;
646
- private canTransformState;
647
- private canInterceptEvents;
648
- }
649
-
650
- /**
651
- * Extracts the state type from either a Bloc or Cubit
652
- * @template T - The Bloc or Cubit type to extract the state from
653
- */
654
- export declare type BlocState<T> = T extends BlocBase<infer S> ? S : never;
655
-
656
- /**
657
- * Test utilities for Blac state management
658
- */
659
- export declare class BlocTest {
660
- private static originalInstance;
661
- /**
662
- * Sets up a clean test environment
663
- */
664
- static setUp(): void;
665
- /**
666
- * Tears down the test environment and restores original state
667
- */
668
- static tearDown(): void;
669
- /**
670
- * Creates a test bloc with automatic cleanup
671
- */
672
- static createBloc<T extends BlocBase<any>>(BlocClass: new (...args: any[]) => T, ...args: any[]): T;
673
- /**
674
- * Waits for a bloc to emit a specific state
675
- */
676
- static waitForState<T extends BlocBase<S>, S>(bloc: T, predicate: (state: S) => boolean, timeout?: number): Promise<S>;
677
- /**
678
- * Expects a bloc to emit specific states in order
679
- */
680
- static expectStates<T extends BlocBase<S>, S>(bloc: T, expectedStates: S[], timeout?: number): Promise<void>;
681
- }
682
-
683
- declare interface ConsumerTracker {
684
- trackAccess: (consumerRef: object, type: 'state' | 'class', path: string, value?: any) => void;
685
- }
686
-
687
- /**
688
- * Creates a proxy for bloc instances that tracks getter access
689
- */
690
- export declare const createBlocProxy: <T extends object>(target: T, consumerRef: object, consumerTracker: ConsumerTracker) => T;
691
-
692
- /**
693
- * Creates a proxy for state objects that tracks property access
694
- */
695
- export declare const createStateProxy: <T extends object>(target: T, consumerRef: object, consumerTracker: ConsumerTracker, path?: string) => T;
696
-
697
- /**
698
- * A Cubit is a simpler version of a Bloc that doesn't handle events.
699
- * It manages state and provides methods to update it.
700
- * @template S - The type of state this Cubit manages
701
- */
702
- export declare abstract class Cubit<S> extends BlocBase<S> {
703
- /**
704
- * Updates the current state and notifies all observers of the change.
705
- * If the new state is identical to the current state (using Object.is),
706
- * no update will occur.
707
- * @param state - The new state to set
708
- */
709
- emit(state: S): void;
710
- /**
711
- * Partially updates the current state by merging it with the provided state patch.
712
- * This method is only applicable when the state is an object type.
713
- *
714
- * @param statePatch - A partial state object containing only the properties to update
715
- * @param ignoreChangeCheck - If true, skips checking if the state has actually changed
716
- * @throws {TypeError} If the state is not an object type
717
- */
718
- patch(statePatch: S extends object ? Partial<S> : S, ignoreChangeCheck?: boolean): void;
719
- }
720
-
721
- export declare const DefaultErrorStrategy: ErrorHandlingStrategy;
722
-
723
- export declare enum ErrorCategory {
724
- LIFECYCLE = "LIFECYCLE",
725
- STATE = "STATE",
726
- PLUGIN = "PLUGIN",
727
- VALIDATION = "VALIDATION",
728
- DISPOSAL = "DISPOSAL",
729
- CONSUMER = "CONSUMER"
730
- }
731
-
732
- /**
733
- * Error context provided to error handlers
734
- */
735
- export declare interface ErrorContext {
736
- readonly phase: 'initialization' | 'state-change' | 'event-processing' | 'disposal';
737
- readonly operation: string;
738
- readonly metadata?: Record<string, unknown>;
739
- }
740
-
741
- export declare type ErrorHandler = (error: BlacError) => void;
742
-
743
- export declare type ErrorHandlingStrategy = {
744
- shouldPropagate: (error: BlacError) => boolean;
745
- shouldLog: (error: BlacError) => boolean;
746
- handle: (error: BlacError) => void;
747
- };
748
-
749
- /**
750
- * Centralized error management system for BlaC framework.
751
- * Handles error processing, logging, and propagation strategies.
752
- */
753
- export declare class ErrorManager {
754
- private static instance;
755
- private handlers;
756
- private strategy;
757
- /**
758
- * Get the singleton instance of ErrorManager
759
- */
760
- static getInstance(): ErrorManager;
761
- /**
762
- * Set a custom error handling strategy
763
- */
764
- setStrategy(strategy: ErrorHandlingStrategy): void;
765
- /**
766
- * Add a custom error handler that will be called for all errors
767
- */
768
- addHandler(handler: ErrorHandler): void;
769
- /**
770
- * Remove a previously added error handler
771
- */
772
- removeHandler(handler: ErrorHandler): void;
773
- /**
774
- * Process an error through all handlers and apply the configured strategy
775
- */
776
- handle(error: BlacError): void;
777
- /**
778
- * Convenience method for wrapping operations with error handling
779
- */
780
- wrap<T>(operation: () => T, errorFactory: (error: unknown) => BlacError): T;
781
- /**
782
- * Async version of wrap
783
- */
784
- wrapAsync<T>(operation: () => Promise<T>, errorFactory: (error: unknown) => BlacError): Promise<T>;
785
- }
786
-
787
- export declare enum ErrorSeverity {
788
- FATAL = "FATAL",// System cannot continue
789
- ERROR = "ERROR",// Operation failed but system continues
790
- WARNING = "WARNING",// Potential issue but operation succeeded
791
- INFO = "INFO"
792
- }
793
-
794
- /**
795
- * Generates a deterministic instance ID from static props by extracting primitive values
796
- *
797
- * Rules:
798
- * 1. Only considers primitive types: string, number, boolean, null, undefined
799
- * 2. Ignores complex types: objects, arrays, functions, symbols
800
- * 3. Sorts keys alphabetically for deterministic output
801
- * 4. Returns undefined if no primitives found (caller should use default ID)
802
- */
803
- export declare function generateInstanceIdFromProps(props: unknown): string | undefined;
804
-
805
- /**
806
- * Cross-platform UUID v4 generator that works in all environments including React Native/Hermes
807
- * Falls back to crypto.randomUUID() when available, otherwise uses Math.random()
808
- */
809
- /**
810
- * Generates a UUID v4 string compatible with all JavaScript environments
811
- * @returns A UUID v4 string in the format xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
812
- */
813
- export declare function generateUUID(): string;
814
-
815
- export declare interface GetBlocOptions<B extends BlocBase<unknown>> {
816
- id?: string;
817
- selector?: BlocHookDependencyArrayFn<BlocState<B>>;
818
- constructorParams?: ConstructorParameters<BlocConstructor<B>>[];
819
- onMount?: (bloc: B) => void;
820
- instanceRef?: string;
821
- throwIfNotFound?: boolean;
822
- /** Force creation of a new instance for isolated blocs, bypassing instance lookup */
823
- forceNewInstance?: boolean;
824
- }
825
-
826
- /**
827
- * Standard error handling helper for BlaC
828
- *
829
- * Usage:
830
- * - For fatal errors that should propagate: handleError.fatal(...)
831
- * - For recoverable errors: handleError.error(...)
832
- * - For warnings: handleError.warn(...)
833
- */
834
- export declare const handleError: {
835
- fatal: (message: string, category: ErrorCategory, context?: BlacErrorContext, cause?: unknown) => never;
836
- error: (message: string, category: ErrorCategory, context?: BlacErrorContext, cause?: unknown) => void;
837
- warn: (message: string, category: ErrorCategory, context?: BlacErrorContext, cause?: unknown) => void;
838
- info: (message: string, category: ErrorCategory, context?: BlacErrorContext) => void;
839
- /**
840
- * Wraps a function to catch and handle errors
841
- */
842
- wrap: <T>(fn: () => T, category: ErrorCategory, context?: BlacErrorContext, severity?: ErrorSeverity) => T | undefined;
843
- /**
844
- * Wraps an async function to catch and handle errors
845
- */
846
- wrapAsync: <T>(fn: () => Promise<T>, category: ErrorCategory, context?: BlacErrorContext, severity?: ErrorSeverity) => Promise<T | undefined>;
847
- };
848
-
849
- /**
850
- * Memory leak detector for tests
851
- */
852
- export declare class MemoryLeakDetector {
853
- private initialStats;
854
- constructor();
855
- /**
856
- * Check for memory leaks and return a report
857
- */
858
- checkForLeaks(): {
859
- hasLeaks: boolean;
860
- report: string;
861
- stats: ReturnType<typeof Blac.getMemoryStats>;
862
- };
863
- }
864
-
865
- /**
866
- * Mock Bloc for testing
867
- */
868
- export declare class MockBloc<S, A extends BlocEventConstraint = BlocEventConstraint> extends Bloc<S, A> {
869
- private mockHandlers;
870
- constructor(initialState: S);
871
- /**
872
- * Mock an event handler for testing
873
- */
874
- mockEventHandler<E extends A>(eventConstructor: new (...args: any[]) => E, handler: (event: E, emit: (newState: S) => void) => void | Promise<void>): void;
875
- /**
876
- * Get the number of registered handlers
877
- */
878
- getHandlerCount(): number;
879
- /**
880
- * Check if a handler is registered for an event type
881
- */
882
- hasHandler(eventConstructor: new (...args: any[]) => A): boolean;
883
- }
884
-
885
- /**
886
- * Mock Cubit for testing
887
- */
888
- export declare class MockCubit<S> extends Cubit<S> {
889
- private stateHistory;
890
- constructor(initialState: S);
891
- /**
892
- * Override emit to track state history
893
- */
894
- emit(newState: S): void;
895
- /**
896
- * Get the history of all states
897
- */
898
- getStateHistory(): S[];
899
- /**
900
- * Clear state history
901
- */
902
- clearStateHistory(): void;
903
- }
904
-
905
- /**
906
- * Base interface for all plugins
907
- */
908
- declare interface Plugin_2 {
909
- readonly name: string;
910
- readonly version: string;
911
- readonly capabilities?: PluginCapabilities;
912
- }
913
- export { Plugin_2 as Plugin }
914
-
915
- /**
916
- * Plugin capabilities for security model
917
- */
918
- export declare interface PluginCapabilities {
919
- readonly readState: boolean;
920
- readonly transformState: boolean;
921
- readonly interceptEvents: boolean;
922
- readonly persistData: boolean;
923
- readonly accessMetadata: boolean;
924
- }
925
-
926
- /**
927
- * Plugin execution context for performance monitoring
928
- */
929
- export declare interface PluginExecutionContext {
930
- readonly pluginName: string;
931
- readonly hookName: string;
932
- readonly startTime: number;
933
- readonly blocName?: string;
934
- readonly blocId?: string;
935
- }
936
-
937
- /**
938
- * Plugin metrics for monitoring
939
- */
940
- export declare interface PluginMetrics {
941
- readonly executionTime: number;
942
- readonly executionCount: number;
943
- readonly errorCount: number;
944
- readonly lastError?: Error;
945
- readonly lastExecutionTime?: number;
946
- }
947
-
948
- /**
949
- * Plugin registry interface
950
- */
951
- export declare interface PluginRegistry<T extends Plugin_2> {
952
- add(plugin: T): void;
953
- remove(pluginName: string): boolean;
954
- get(pluginName: string): T | undefined;
955
- getAll(): ReadonlyArray<T>;
956
- clear(): void;
957
- }
958
-
959
- /**
960
- * Event fired when props are updated on a Bloc or Cubit instance.
961
- * This is primarily used internally by the framework to notify
962
- * about prop changes in React components.
963
- * @template P - The type of props being updated
964
- */
965
- export declare class PropsUpdated<P = any> {
966
- readonly props: P;
967
- constructor(props: P);
968
- }
969
-
970
- export declare const ProxyFactory: {
971
- createStateProxy: (options: {
972
- target: any;
973
- consumerRef: object;
974
- consumerTracker: ConsumerTracker;
975
- path?: string;
976
- }) => any;
977
- createClassProxy: (options: {
978
- target: any;
979
- consumerRef: object;
980
- consumerTracker: ConsumerTracker;
981
- }) => any;
982
- getProxyState: <B extends BlocBase<any>>(options: {
983
- state: any;
984
- consumerRef: object;
985
- consumerTracker: ConsumerTracker;
986
- }) => any;
987
- getProxyBlocInstance: <B extends BlocBase<any>>(options: {
988
- blocInstance: B;
989
- consumerRef: object;
990
- consumerTracker: ConsumerTracker;
991
- }) => B;
992
- getStats: () => {
993
- propertyAccesses: number;
994
- nestedProxiesCreated: number;
995
- cacheEfficiency: string;
996
- lifetime: string;
997
- proxiesPerSecond: string;
998
- stateProxiesCreated: number;
999
- classProxiesCreated: number;
1000
- cacheHits: number;
1001
- cacheMisses: number;
1002
- totalProxiesCreated: number;
1003
- };
1004
- resetStats: () => void;
1005
- };
1006
-
1007
- export declare interface RerenderInfo {
1008
- componentName: string;
1009
- blocName: string;
1010
- blocId: string;
1011
- renderCount: number;
1012
- reason: RerenderReason;
1013
- timestamp: number;
1014
- duration?: number;
1015
- stackTrace?: string;
1016
- }
1017
-
1018
- /**
1019
- * Utility class for logging component rerenders with detailed debugging information
1020
- */
1021
- export declare class RerenderLogger {
1022
- private static componentRenderCounts;
1023
- private static lastRenderTimestamps;
1024
- private static groupedLogs;
1025
- private static groupTimeouts;
1026
- /**
1027
- * Log a component rerender with detailed information
1028
- */
1029
- static logRerender(info: RerenderInfo): void;
1030
- /**
1031
- * Parse the logging configuration
1032
- */
1033
- private static parseConfig;
1034
- /**
1035
- * Log immediately without grouping
1036
- */
1037
- private static logImmediate;
1038
- /**
1039
- * Log with grouping (batch multiple rerenders)
1040
- */
1041
- private static logGrouped;
1042
- /**
1043
- * Format the log message based on level
1044
- */
1045
- private static formatMessage;
1046
- /**
1047
- * Get emoji for reason type
1048
- */
1049
- private static getReasonEmoji;
1050
- /**
1051
- * Clear all tracking data
1052
- */
1053
- static clear(): void;
1054
- /**
1055
- * Get render count for a component
1056
- */
1057
- static getRenderCount(componentName: string, blocId: string): number;
1058
- }
1059
-
1060
- export declare interface RerenderReason {
1061
- type: 'state-change' | 'dependency-change' | 'mount' | 'props-change' | 'unknown';
1062
- changedPaths?: string[];
1063
- oldValues?: Record<string, any>;
1064
- newValues?: Record<string, any>;
1065
- dependencies?: string[];
1066
- description?: string;
1067
- }
1068
-
1069
- /**
1070
- * Sets a custom instance manager (useful for testing or advanced patterns)
1071
- */
1072
- export declare function setBlacInstanceManager(manager: BlacInstanceManager): void;
1073
-
1074
- /**
1075
- * Performs a shallow equality comparison between two values.
1076
- * For objects, it checks if all top-level properties are equal using Object.is.
1077
- * @param a First value to compare
1078
- * @param b Second value to compare
1079
- * @returns true if values are shallowly equal, false otherwise
1080
- */
1081
- export declare function shallowEqual(a: any, b: any): boolean;
1082
-
1083
- export declare interface StateTransitionResult {
1084
- success: boolean;
1085
- currentState: BlocLifecycleState;
1086
- previousState: BlocLifecycleState;
1087
- }
1088
-
1089
- /**
1090
- * Unified subscription interface that replaces the dual consumer/observer system
1091
- */
1092
- export declare interface Subscription<S = unknown> {
1093
- /** Unique identifier for the subscription */
1094
- id: string;
1095
- /** Type of subscription for backward compatibility */
1096
- type: 'consumer' | 'observer';
1097
- /** Optional selector function to derive values from state */
1098
- selector?: (state: S, bloc?: BlocBase<S>) => unknown;
1099
- /** Custom equality function for selector results (defaults to Object.is) */
1100
- equalityFn?: (prev: unknown, next: unknown) => boolean;
1101
- /** Notification callback when state changes */
1102
- notify: (value: unknown, oldValue?: unknown, action?: unknown) => void;
1103
- /** Priority for notification order (higher = earlier) */
1104
- priority?: number;
1105
- /** WeakRef to the subscriber for automatic cleanup (React components) */
1106
- weakRef?: WeakRef<object>;
1107
- /** Last computed selector value for comparison */
1108
- lastValue?: unknown;
1109
- /** Tracked state path dependencies */
1110
- dependencies?: Set<string>;
1111
- /** Metadata for tracking and debugging */
1112
- metadata?: SubscriptionMetadata;
1113
- }
1114
-
1115
- /**
1116
- * Unified subscription manager that replaces the dual consumer/observer system.
1117
- * Handles all state change subscriptions with a single, consistent interface.
1118
- */
1119
- export declare class SubscriptionManager<S = unknown> {
1120
- private bloc;
1121
- private subscriptions;
1122
- private pathToSubscriptions;
1123
- private weakRefCleanupScheduled;
1124
- private totalNotifications;
1125
- constructor(bloc: BlocBase<S>);
1126
- /**
1127
- * Subscribe to state changes
1128
- */
1129
- subscribe(options: SubscriptionOptions<S>): () => void;
1130
- /**
1131
- * Unsubscribe by ID
1132
- */
1133
- unsubscribe(id: string): void;
1134
- /**
1135
- * Notify all subscriptions of state change
1136
- */
1137
- notify(newState: S, oldState: S, action?: unknown): void;
1138
- /**
1139
- * Track a path access for a subscription
1140
- */
1141
- trackAccess(subscriptionId: string, path: string, value?: unknown): void;
1142
- /**
1143
- * Get the paths that changed between two states
1144
- */
1145
- private getChangedPaths;
1146
- /**
1147
- * Check if a subscription should be notified based on changed paths
1148
- */
1149
- shouldNotifyForPaths(subscriptionId: string, changedPaths: Set<string>): boolean;
1150
- /**
1151
- * Get statistics about subscriptions
1152
- */
1153
- getStats(): SubscriptionManagerStats;
1154
- /**
1155
- * Clear all subscriptions
1156
- */
1157
- clear(): void;
1158
- /**
1159
- * Get subscription by ID
1160
- */
1161
- getSubscription(id: string): Subscription<S> | undefined;
1162
- /**
1163
- * Check if there are any active subscriptions
1164
- */
1165
- get hasSubscriptions(): boolean;
1166
- /**
1167
- * Get count of active subscriptions
1168
- */
1169
- get size(): number;
1170
- /**
1171
- * Clean up subscriptions with dead weak references
1172
- */
1173
- private cleanupDeadReferences;
1174
- /**
1175
- * Schedule weak reference cleanup for next tick
1176
- */
1177
- private scheduleWeakRefCleanup;
1178
- }
1179
-
1180
- export declare interface SubscriptionManagerStats {
1181
- /** Total number of active subscriptions */
1182
- activeSubscriptions: number;
1183
- /** Number of consumer subscriptions */
1184
- consumerCount: number;
1185
- /** Number of observer subscriptions */
1186
- observerCount: number;
1187
- /** Total notifications sent */
1188
- totalNotifications: number;
1189
- /** Number of tracked dependencies */
1190
- trackedDependencies: number;
1191
- }
1192
-
1193
- export declare interface SubscriptionMetadata {
1194
- /** Timestamp of last notification */
1195
- lastNotified?: number;
1196
- /** Whether the subscriber has rendered (React-specific) */
1197
- hasRendered?: boolean;
1198
- /** Number of times this subscription accessed state */
1199
- accessCount?: number;
1200
- /** First access timestamp */
1201
- firstAccessTime?: number;
1202
- /** Last access timestamp */
1203
- lastAccessTime?: number;
1204
- }
1205
-
1206
- export declare interface SubscriptionOptions<S> {
1207
- /** Type of subscription */
1208
- type: 'consumer' | 'observer';
1209
- /** Optional selector function */
1210
- selector?: (state: S, bloc?: BlocBase<S>) => unknown;
1211
- /** Custom equality function */
1212
- equalityFn?: (prev: unknown, next: unknown) => boolean;
1213
- /** Notification callback */
1214
- notify: (value: unknown, oldValue?: unknown, action?: unknown) => void;
1215
- /** Priority for notifications */
1216
- priority?: number;
1217
- /** WeakRef to subscriber */
1218
- weakRef?: WeakRef<object>;
1219
- }
1220
-
1221
- /**
1222
- * Registry for system-wide plugins
1223
- */
1224
- export declare class SystemPluginRegistry implements PluginRegistry<BlacPlugin> {
1225
- private plugins;
1226
- private metrics;
1227
- private executionOrder;
1228
- /**
1229
- * Add a system plugin
1230
- */
1231
- add(plugin: BlacPlugin): void;
1232
- /**
1233
- * Remove a system plugin
1234
- */
1235
- remove(pluginName: string): boolean;
1236
- /**
1237
- * Get a plugin by name
1238
- */
1239
- get(pluginName: string): BlacPlugin | undefined;
1240
- /**
1241
- * Get all plugins in execution order
1242
- */
1243
- getAll(): ReadonlyArray<BlacPlugin>;
1244
- /**
1245
- * Clear all plugins
1246
- */
1247
- clear(): void;
1248
- /**
1249
- * Execute a hook on all plugins
1250
- */
1251
- executeHook(hookName: keyof BlacPlugin, args: unknown[], errorHandler?: (error: Error, plugin: BlacPlugin) => void): void;
1252
- /**
1253
- * Bootstrap all plugins
1254
- */
1255
- bootstrap(): void;
1256
- /**
1257
- * Shutdown all plugins
1258
- */
1259
- shutdown(): void;
1260
- /**
1261
- * Notify plugins of bloc creation
1262
- */
1263
- notifyBlocCreated(bloc: BlocBase<any>): void;
1264
- /**
1265
- * Notify plugins of bloc disposal
1266
- */
1267
- notifyBlocDisposed(bloc: BlocBase<any>): void;
1268
- /**
1269
- * Notify plugins of state change
1270
- */
1271
- notifyStateChanged(bloc: BlocBase<any>, previousState: any, currentState: any): void;
1272
- /**
1273
- * Notify plugins of event addition
1274
- */
1275
- notifyEventAdded(bloc: Bloc<any, any>, event: any): void;
1276
- /**
1277
- * Notify plugins of errors
1278
- */
1279
- notifyError(error: Error, bloc: BlocBase<unknown>, context: ErrorContext): void;
1280
- /**
1281
- * Notify plugins of adapter lifecycle events
1282
- */
1283
- notifyAdapterCreated(adapter: any, metadata: AdapterMetadata): void;
1284
- notifyAdapterMount(adapter: any, metadata: AdapterMetadata): void;
1285
- notifyAdapterUnmount(adapter: any, metadata: AdapterMetadata): void;
1286
- notifyAdapterRender(adapter: any, metadata: AdapterMetadata): void;
1287
- notifyAdapterDisposed(adapter: any, metadata: AdapterMetadata): void;
1288
- /**
1289
- * Get metrics for a plugin
1290
- */
1291
- getMetrics(pluginName: string): Map<string, PluginMetrics> | undefined;
1292
- private initializeMetrics;
1293
- private recordSuccess;
1294
- private recordError;
1295
- }
1296
-
1297
- /**
1298
- * Extracts the state type from a BlocBase instance
1299
- * @template B - The BlocBase type to extract the state from
1300
- */
1301
- export declare type ValueType<B extends BlocBase<any>> = B extends BlocBase<infer U> ? U : never;
1302
-
1303
- export { }