@blac/core 2.0.0-rn-12 → 2.0.1

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 CHANGED
@@ -1,824 +1,1895 @@
1
- export declare interface AdapterOptions<B extends BlocBase<any>> {
2
- id?: string;
3
- dependencies?: (bloc: B) => unknown[];
4
- props?: any;
5
- onMount?: (bloc: B) => void;
6
- onUnmount?: (bloc: B) => void;
1
+ /* Excluded from this release type: __resetIdCounters */
2
+
3
+ export declare function acquire<T extends StateContainerConstructor>(BlocClass: T, instanceKey?: string, options?: AcquireOptions<T>): InstanceType<T>;
4
+
5
+ export declare interface AcquireOptions<T extends StateContainerConstructor> {
6
+ props?: ExtractProps<T>;
7
+ }
8
+
9
+ /**
10
+ * Internal state for framework adapters, holding tracking and caching data.
11
+ * @template TBloc - The state container type
12
+ */
13
+ export declare interface AdapterState<TBloc extends StateContainerConstructor> {
14
+ /** Dependency tracker for state property access tracking */
15
+ dependencyState: DependencyState<ExtractState<TBloc>> | null;
16
+ /** Cached manual dependencies for comparison */
17
+ manualDepsCache: unknown[] | null;
18
+ /** Getter state for computed property tracking */
19
+ getterState: GetterState | null;
20
+ /** Proxied bloc instance for auto-tracking */
21
+ proxiedBloc: InstanceState<TBloc> | null;
22
+ }
23
+
24
+ /**
25
+ * Initialize adapter state for auto-tracking mode.
26
+ * Creates getter tracker and proxied bloc instance.
27
+ * @param instance - The state container instance
28
+ * @returns Initialized adapter state
29
+ */
30
+ export declare function autoTrackInit<TBloc extends StateContainerConstructor>(instance: InstanceState<TBloc>): AdapterState<TBloc>;
31
+
32
+ /**
33
+ * Create a snapshot function for auto-tracking mode.
34
+ * Returns a proxied state that tracks property access.
35
+ * @param instance - The state container instance
36
+ * @param adapterState - The adapter state for tracking
37
+ * @returns Snapshot function for use with useSyncExternalStore
38
+ */
39
+ export declare function autoTrackSnapshot<TBloc extends StateContainerConstructor>(instance: InstanceReadonlyState<TBloc>, adapterState: AdapterState<TBloc>): SnapshotFunction<ExtractState<TBloc>>;
40
+
41
+ /**
42
+ * Create a subscribe function for auto-tracking mode.
43
+ * Only triggers callback when tracked properties change.
44
+ * @param instance - The state container instance
45
+ * @param adapterState - The adapter state for tracking
46
+ * @returns Subscribe function for use with useSyncExternalStore
47
+ */
48
+ export declare function autoTrackSubscribe<TBloc extends StateContainerConstructor>(instance: InstanceReadonlyState<TBloc>, adapterState: AdapterState<TBloc>): SubscribeFunction;
49
+
50
+ /**
51
+ * Decorator to configure StateContainer classes.
52
+ *
53
+ * @example Decorator syntax (requires experimentalDecorators or TC39 decorators)
54
+ * ```ts
55
+ * @blac({ isolated: true })
56
+ * class FormBloc extends Cubit<FormState> {}
57
+ *
58
+ * @blac({ keepAlive: true })
59
+ * class AuthBloc extends Cubit<AuthState> {}
60
+ *
61
+ * @blac({ excludeFromDevTools: true })
62
+ * class InternalBloc extends Cubit<InternalState> {}
63
+ * ```
64
+ *
65
+ * @example Function syntax (no decorator support needed)
66
+ * ```ts
67
+ * const FormBloc = blac({ isolated: true })(
68
+ * class extends Cubit<FormState> {}
69
+ * );
70
+ * ```
71
+ */
72
+ export declare function blac(options: BlacOptions): <T extends new (...args: any[]) => any>(target: T, _context?: ClassDecoratorContext) => T;
73
+
74
+ /**
75
+ * Default configuration constants for BlaC
76
+ */
77
+ export declare const BLAC_DEFAULTS: {
78
+ /**
79
+ * Default instance key for shared instances
80
+ */
81
+ readonly DEFAULT_INSTANCE_KEY: "default";
82
+ /**
83
+ * Maximum getter nesting depth (prevents infinite recursion)
84
+ */
85
+ readonly MAX_GETTER_DEPTH: 10;
86
+ /**
87
+ * Default cleanup interval for subscriptions (30 seconds)
88
+ */
89
+ readonly CLEANUP_INTERVAL_MS: 30000;
90
+ /**
91
+ * Cleanup interval for weak reference stage (10 seconds)
92
+ */
93
+ readonly WEAKREF_CLEANUP_INTERVAL_MS: 10000;
94
+ /**
95
+ * Default maximum subscriptions per container
96
+ */
97
+ readonly MAX_SUBSCRIPTIONS: 1000;
98
+ /**
99
+ * Maximum subscriptions for high-performance mode
100
+ */
101
+ readonly MAX_SUBSCRIPTIONS_HIGH_PERF: 10000;
102
+ /**
103
+ * Default timeout for pipeline execution (5 seconds)
104
+ */
105
+ readonly PIPELINE_TIMEOUT_MS: 5000;
106
+ /**
107
+ * Cleanup interval for high-performance mode (5 seconds)
108
+ */
109
+ readonly CLEANUP_INTERVAL_HIGH_PERF_MS: 5000;
110
+ /**
111
+ * Maximum number of stages in a pipeline
112
+ */
113
+ readonly MAX_PIPELINE_STAGES: 30;
114
+ };
115
+
116
+ /**
117
+ * Standard error message prefix
118
+ */
119
+ export declare const BLAC_ERROR_PREFIX: "[BlaC]";
120
+
121
+ /**
122
+ * ID generation patterns and constants
123
+ */
124
+ export declare const BLAC_ID_PATTERNS: {
125
+ /**
126
+ * Prefix for isolated instance keys
127
+ */
128
+ readonly ISOLATED_PREFIX: "isolated-";
129
+ /**
130
+ * Length of generated ID portion (9 characters from base36)
131
+ */
132
+ readonly ID_LENGTH: 9;
133
+ };
134
+
135
+ /**
136
+ * Static property names for StateContainer classes
137
+ * Used for feature flags and configuration on bloc classes
138
+ */
139
+ export declare const BLAC_STATIC_PROPS: {
140
+ /**
141
+ * Mark a bloc as isolated (each component gets its own instance)
142
+ */
143
+ readonly ISOLATED: "isolated";
144
+ /**
145
+ * Mark a bloc to never be auto-disposed (kept alive permanently)
146
+ */
147
+ readonly KEEP_ALIVE: "keepAlive";
148
+ /**
149
+ * Exclude a bloc from DevTools reporting (prevents infinite loops)
150
+ */
151
+ readonly EXCLUDE_FROM_DEVTOOLS: "__excludeFromDevTools";
152
+ };
153
+
154
+ /**
155
+ * Global configuration for @blac/core
156
+ */
157
+ export declare interface BlacConfig {
158
+ /** Enable development mode (enables additional warnings and checks) */
159
+ devMode: boolean;
160
+ /** Logger configuration */
161
+ logger: Partial<LogConfig>;
162
+ }
163
+
164
+ /**
165
+ * Configuration options for the @blac decorator.
166
+ * Only one option can be specified at a time (union type).
167
+ */
168
+ export declare type BlacOptions =
169
+ /** Mark bloc as isolated (each component gets its own instance) */
170
+ {
171
+ isolated: true;
172
+ }
173
+ /** Mark bloc to never be auto-disposed when ref count reaches 0 */
174
+ | {
175
+ keepAlive: true;
176
+ }
177
+ /** Exclude bloc from DevTools tracking (prevents infinite loops) */
178
+ | {
179
+ excludeFromDevTools: true;
180
+ };
181
+
182
+ /**
183
+ * Interface for plugins that extend BlaC functionality
184
+ */
185
+ export declare interface BlacPlugin {
186
+ /** Unique plugin identifier */
187
+ readonly name: string;
188
+ /** Plugin version identifier */
189
+ readonly version: string;
190
+ /**
191
+ * Called when the plugin is installed (optional)
192
+ */
193
+ onInstall?(context: PluginContext): void;
194
+ /**
195
+ * Called when the plugin is uninstalled
196
+ */
197
+ onUninstall?(): void;
198
+ /**
199
+ * Called when a state container instance is created
200
+ */
201
+ onInstanceCreated?(instance: StateContainer<any>, context: PluginContext): void;
202
+ /**
203
+ * Called when state changes in a container instance
204
+ */
205
+ onStateChanged?<S extends object = any>(instance: StateContainer<S>, previousState: S, currentState: S, callstack: string | undefined, context: PluginContext): void;
206
+ /**
207
+ * Called when an event is added to a Vertex instance
208
+ */
209
+ onEventAdded?<E extends DiscriminatedEvent>(vertex: Vertex<any, E>, event: EventWithMetadata<E>, context: PluginContext): void;
210
+ /**
211
+ * Called when a state container instance is disposed
212
+ */
213
+ onInstanceDisposed?(instance: StateContainer<any>, context: PluginContext): void;
214
+ }
215
+
216
+ /**
217
+ * Plugin interface variant that requires mandatory onInstall hook
218
+ */
219
+ export declare interface BlacPluginWithInit extends BlacPlugin {
220
+ /**
221
+ * Required initialization hook called when plugin is installed
222
+ */
223
+ onInstall(context: PluginContext): void;
224
+ }
225
+
226
+ declare const BLOC_REF_MARKER: unique symbol;
227
+
228
+ /**
229
+ * Constructor type for StateContainer classes with static registry methods.
230
+ * Used for type-safe hook parameters.
231
+ * @template TBloc - The StateContainer instance type
232
+ */
233
+ export declare type BlocConstructor<S extends object = any, T extends new (...args: any[]) => StateContainer<S, any> = new (...args: any[]) => StateContainer<S, any>> = (new (...args: any[]) => InstanceType<T>) & {
234
+ acquire(instanceKey?: string, ...args: any[]): InstanceType<T>;
235
+ borrow(instanceKey?: string, ...args: any[]): InstanceType<T> | null;
236
+ borrowSafe(instanceKey?: string, ...args: any[]): {
237
+ error: Error;
238
+ instance: null;
239
+ } | {
240
+ error: null;
241
+ instance: InstanceType<T>;
242
+ };
243
+ ensure(instanceKey?: string): InstanceType<T>;
244
+ release(instanceKey?: string): void;
245
+ isolated?: boolean;
246
+ keepAlive?: boolean;
247
+ };
248
+
249
+ declare type BlocInput = StateContainerConstructor | BlocRef<StateContainerConstructor>;
250
+
251
+ /**
252
+ * Extract instance type from an abstract class constructor
253
+ * @template T - The abstract class constructor type
254
+ */
255
+ export declare type BlocInstanceType<T extends abstract new (...args: any) => any> = T extends abstract new (...args: any) => infer R ? R : any;
256
+
257
+ /**
258
+ * Reference to a specific bloc instance by class and instance ID.
259
+ */
260
+ export declare interface BlocRef<T extends StateContainerConstructor> {
261
+ [BLOC_REF_MARKER]: true;
262
+ blocClass: T;
263
+ instanceId: string;
264
+ }
265
+
266
+ export declare function borrow<T extends StateContainerConstructor>(BlocClass: T, instanceKey?: string): InstanceType<T>;
267
+
268
+ export declare function borrowSafe<T extends StateContainerConstructor>(BlocClass: T, instanceKey?: string): {
269
+ error: Error;
270
+ instance: null;
271
+ } | {
272
+ error: null;
273
+ instance: InstanceType<T>;
274
+ };
275
+
276
+ /**
277
+ * Utility type for creating branded/nominal types.
278
+ * Prevents accidental type confusion between similar primitive types.
279
+ * @template T - The base type
280
+ * @template B - The brand identifier
281
+ */
282
+ export declare type Brand<T, B> = T & {
283
+ [brand]: B;
284
+ };
285
+
286
+ declare const brand: unique symbol;
287
+
288
+ /**
289
+ * Branded string type for type-safe IDs.
290
+ * @template B - The brand identifier
291
+ */
292
+ export declare type BrandedId<B> = Brand<string, B>;
293
+
294
+ /* Excluded from this release type: capturePaths */
295
+
296
+ export declare function clear<T extends StateContainerConstructor>(BlocClass: T): void;
297
+
298
+ /* Excluded from this release type: clearActiveTracker */
299
+
300
+ export declare function clearAll(): void;
301
+
302
+ /* Excluded from this release type: clearExternalDependencies */
303
+
304
+ /* Excluded from this release type: commitTrackedGetters */
305
+
306
+ /**
307
+ * Configure global defaults for @blac/core.
308
+ *
309
+ * @example
310
+ * ```ts
311
+ * import { configureBlac, LogLevel } from '@blac/core';
312
+ *
313
+ * configureBlac({
314
+ * devMode: true,
315
+ * logger: {
316
+ * enabled: true,
317
+ * level: LogLevel.DEBUG
318
+ * }
319
+ * });
320
+ * ```
321
+ *
322
+ * @param config - Partial configuration to merge with defaults
323
+ */
324
+ export declare function configureBlac(config: Partial<BlacConfig>): void;
325
+
326
+ /**
327
+ * Configuration function that recreates the default logger
328
+ *
329
+ * @param opts - Partial logger configuration
330
+ *
331
+ * @example
332
+ * ```ts
333
+ * configureLogger({ enabled: true, level: LogLevel.DEBUG });
334
+ * ```
335
+ */
336
+ export declare function configureLogger(opts: Partial<LogConfig>): void;
337
+
338
+ /* Excluded from this release type: createArrayProxy */
339
+
340
+ /* Excluded from this release type: createBlocProxy */
341
+
342
+ /* Excluded from this release type: createDependencyProxy */
343
+
344
+ /* Excluded from this release type: createDependencyState */
345
+
346
+ /* Excluded from this release type: createForTarget */
347
+
348
+ /* Excluded from this release type: createGetterState */
349
+
350
+ /**
351
+ * Centralized ID Generation
352
+ *
353
+ * Provides consistent, collision-resistant ID generation for all BlaC subsystems.
354
+ * Uses timestamp + counter + random suffix for uniqueness.
355
+ */
356
+ /**
357
+ * Creates an ID generator with isolated counter state
358
+ *
359
+ * @param prefix - Prefix for generated IDs
360
+ * @returns Object with next(), nextSimple(), and reset() methods
361
+ *
362
+ * @example
363
+ * ```ts
364
+ * const generator = createIdGenerator('sub');
365
+ * const id1 = generator.next(); // "sub:1698765432100_1_a3k9d7f2q"
366
+ * const id2 = generator.next(); // "sub:1698765432101_2_b4n8e9g3r"
367
+ * ```
368
+ */
369
+ export declare function createIdGenerator(prefix: string): {
370
+ next: () => string;
371
+ nextSimple: () => string;
372
+ reset: () => void;
373
+ };
374
+
375
+ /* Excluded from this release type: createInternal */
376
+
377
+ /**
378
+ * Creates a logger instance with given configuration
379
+ *
380
+ * @param config - Logger configuration
381
+ * @returns Logger instance with debug, info, warn, error, and configure methods
382
+ *
383
+ * @example
384
+ * ```ts
385
+ * const logger = createLogger({
386
+ * enabled: true,
387
+ * level: LogLevel.DEBUG,
388
+ * output: (entry) => console.log(JSON.stringify(entry))
389
+ * });
390
+ * logger.debug('MyComponent', 'Rendering', { props: { foo: 'bar' } });
391
+ * ```
392
+ */
393
+ export declare function createLogger(config: LogConfig): {
394
+ debug: (context: string, message: string, data?: any) => void;
395
+ info: (context: string, message: string, data?: any) => void;
396
+ warn: (context: string, message: string, data?: any) => void;
397
+ error: (context: string, message: string, data?: any) => void;
398
+ configure: (opts: Partial<LogConfig>) => void;
399
+ };
400
+
401
+ /**
402
+ * Create a plugin manager instance
403
+ * @param registry - The StateContainerRegistry to monitor for lifecycle events
404
+ * @returns A new PluginManager instance
405
+ */
406
+ export declare function createPluginManager(registry: StateContainerRegistry): PluginManager;
407
+
408
+ /* Excluded from this release type: createProxyState */
409
+
410
+ /**
411
+ * Create a new tracked context for manual control over tracking.
412
+ */
413
+ export declare function createTrackedContext(): TrackedContext;
414
+
415
+ /**
416
+ * Create a tracking proxy for a bloc instance.
417
+ * Tracks both state property access and getter access.
418
+ */
419
+ export declare function createTrackingProxy<T extends StateContainerInstance>(bloc: T, tracker: TrackingProxyState): T;
420
+
421
+ /**
422
+ * Create a new tracking proxy state.
423
+ */
424
+ export declare function createTrackingProxyState(): TrackingProxyState;
425
+
426
+ /**
427
+ * Simple state container with direct state emission.
428
+ * Extends StateContainer with public methods for emitting and updating state.
429
+ *
430
+ * @template S - State type
431
+ * @template P - Props type (optional)
432
+ */
433
+ export declare abstract class Cubit<S extends object = any, P = undefined> extends StateContainer<S, P> {
434
+ constructor(initialState: S);
435
+ /**
436
+ * Replace state with a new value and notify all listeners
437
+ * @param newState - The new state value
438
+ */
439
+ emit(newState: S): void;
440
+ /**
441
+ * Transform current state using an updater function and emit the new state
442
+ * @param updater - Function that receives current state and returns new state
443
+ */
444
+ update(updater: (current: S) => S): void;
445
+ /**
446
+ * Merge partial state changes into current state (only for object states)
447
+ */
448
+ patch: S extends object ? (partial: Partial<S>) => void : never;
449
+ }
450
+
451
+ /**
452
+ * Log a debug message (tree-shakeable export)
453
+ * @param context - Context identifier (module or component name)
454
+ * @param message - Log message
455
+ * @param data - Optional structured data
456
+ */
457
+ export declare const debug: (context: string, message: string, data?: any) => void;
458
+
459
+ /**
460
+ * Manages subscriptions to state container dependencies.
461
+ * Provides efficient sync mechanism to add/remove subscriptions
462
+ * as dependencies change between callback invocations.
463
+ */
464
+ export declare class DependencyManager {
465
+ private subscriptions;
466
+ private currentDeps;
467
+ /**
468
+ * Sync subscriptions with a new set of dependencies.
469
+ * Adds subscriptions for new deps, removes subscriptions for stale deps.
470
+ *
471
+ * @param newDeps - The new set of dependencies to subscribe to
472
+ * @param onChange - Callback to invoke when any dependency changes
473
+ * @param exclude - Optional instance to exclude from subscriptions (e.g., primary bloc)
474
+ * @returns true if the dependency set changed, false if unchanged
475
+ */
476
+ sync(newDeps: Set<StateContainerInstance>, onChange: () => void, exclude?: StateContainerInstance): boolean;
477
+ /**
478
+ * Add a single dependency subscription.
479
+ */
480
+ add(dep: StateContainerInstance, onChange: () => void): void;
481
+ /**
482
+ * Check if a dependency is currently subscribed.
483
+ */
484
+ has(dep: StateContainerInstance): boolean;
485
+ /**
486
+ * Get the current set of dependencies.
487
+ */
488
+ getDependencies(): Set<StateContainerInstance>;
489
+ /**
490
+ * Clean up all active subscriptions.
491
+ */
492
+ cleanup(): void;
493
+ private areSetsEqual;
494
+ }
495
+
496
+ /* Excluded from this release type: DependencyState */
497
+
498
+ /**
499
+ * Disable getter tracking after render phase completes.
500
+ * Clears the active tracker to prevent tracking outside of render.
501
+ * @param adapterState - The adapter state
502
+ * @param rawInstance - The raw bloc instance
503
+ */
504
+ export declare function disableGetterTracking<TBloc extends StateContainerConstructor>(adapterState: AdapterState<TBloc>, rawInstance: InstanceState<TBloc>): void;
505
+
506
+ /**
507
+ * Base type for discriminated union events.
508
+ * All events must have a `type` property as the discriminator.
509
+ *
510
+ * @example
511
+ * ```typescript
512
+ * type MyEvent =
513
+ * | { type: 'increment'; amount: number }
514
+ * | { type: 'decrement' };
515
+ * ```
516
+ */
517
+ export declare interface DiscriminatedEvent {
518
+ readonly type: string;
519
+ }
520
+
521
+ /* Excluded from this release type: EmptyState */
522
+
523
+ /* Excluded from this release type: EmptyState_2 */
524
+
525
+ export declare function ensure<T extends StateContainerConstructor>(BlocClass: T, instanceKey?: string): InstanceType<T>;
526
+
527
+ /**
528
+ * Log an error message (tree-shakeable export)
529
+ * @param context - Context identifier (module or component name)
530
+ * @param message - Log message
531
+ * @param data - Optional structured data
532
+ */
533
+ export declare const error: (context: string, message: string, data?: any) => void;
534
+
535
+ /**
536
+ * Map of event handlers requiring exhaustive coverage.
537
+ * TypeScript enforces that every event type in the union has a handler.
538
+ *
539
+ * @template E - The discriminated event union type
540
+ * @template S - The state type
541
+ *
542
+ * @example
543
+ * ```typescript
544
+ * type CounterEvent =
545
+ * | { type: 'increment'; amount: number }
546
+ * | { type: 'reset' };
547
+ *
548
+ * // All event types must be handled:
549
+ * const handlers: EventHandlerMap<CounterEvent, { count: number }> = {
550
+ * increment: (event, emit) => emit({ count: event.amount }),
551
+ * reset: (_, emit) => emit({ count: 0 }),
552
+ * };
553
+ * ```
554
+ */
555
+ export declare type EventHandlerMap<E extends DiscriminatedEvent, S extends object> = {
556
+ [K in EventType<E>]: VertexEventHandler<ExtractEvent<E, K>, S>;
557
+ };
558
+
559
+ /* Excluded from this release type: EventMetadata */
560
+
561
+ /**
562
+ * Extract the `type` literal union from a discriminated event union.
563
+ *
564
+ * @template E - The discriminated event union type
565
+ *
566
+ * @example
567
+ * ```typescript
568
+ * type MyEvent = { type: 'a' } | { type: 'b' };
569
+ * type Types = EventType<MyEvent>; // 'a' | 'b'
570
+ * ```
571
+ */
572
+ export declare type EventType<E extends DiscriminatedEvent> = E['type'];
573
+
574
+ /* Excluded from this release type: EventWithMetadata */
575
+
576
+ /**
577
+ * Manages subscriptions to external bloc dependencies for getter tracking.
578
+ * When a getter accesses another bloc's state, this manager ensures
579
+ * re-renders occur when those external dependencies change.
580
+ *
581
+ * @deprecated Use DependencyManager from tracking module instead.
582
+ * This class is kept for backward compatibility.
583
+ */
584
+ export declare class ExternalDepsManager {
585
+ private manager;
586
+ /**
587
+ * Update subscriptions to external bloc dependencies.
588
+ * Creates subscriptions to blocs accessed via getters.
589
+ * @param getterTracker - The getter tracker state with external dependencies
590
+ * @param rawInstance - The primary bloc instance (excluded from subscriptions)
591
+ * @param onGetterChange - Callback to invoke when external dependency changes
592
+ * @returns true if subscriptions were updated, false if unchanged
593
+ */
594
+ updateSubscriptions(getterState: GetterState | null, rawInstance: StateContainerInstance, onGetterChange: () => void): boolean;
595
+ /**
596
+ * Clean up all active subscriptions
597
+ */
598
+ cleanup(): void;
599
+ }
600
+
601
+ /**
602
+ * Extract constructor argument types from a class
603
+ * @template T - The class type
604
+ */
605
+ export declare type ExtractConstructorArgs<T> = T extends new (...args: infer P) => any ? P : never[];
606
+
607
+ /**
608
+ * Extract a specific event variant from a union by its type.
609
+ *
610
+ * @template E - The discriminated event union type
611
+ * @template T - The type literal to extract
612
+ *
613
+ * @example
614
+ * ```typescript
615
+ * type MyEvent = { type: 'a'; value: number } | { type: 'b' };
616
+ * type EventA = ExtractEvent<MyEvent, 'a'>; // { type: 'a'; value: number }
617
+ * ```
618
+ */
619
+ export declare type ExtractEvent<E extends DiscriminatedEvent, T extends EventType<E>> = Extract<E, {
620
+ type: T;
621
+ }>;
622
+
623
+ declare type ExtractInstance<T> = T extends BlocRef<infer C> ? InstanceType<C> : T extends StateContainerConstructor ? InstanceType<T> : never;
624
+
625
+ declare type ExtractInstances<T extends readonly BlocInput[]> = {
626
+ [K in keyof T]: ExtractInstance<T[K]>;
627
+ };
628
+
629
+ /**
630
+ * Extract the props type from a StateContainer
631
+ * @template T - The StateContainer type
632
+ */
633
+ export declare type ExtractProps<T> = T extends StateContainerConstructor<any, infer P> ? P : undefined;
634
+
635
+ /**
636
+ * Extract the state type from a StateContainer
637
+ * @template T - The StateContainer type
638
+ */
639
+ export declare type ExtractState<T> = T extends StateContainerConstructor<infer S, any> ? Readonly<S> : never;
640
+
641
+ /**
642
+ * Constrain a type to extract state only from stateful containers.
643
+ * Returns `never` for stateless containers.
644
+ */
645
+ export declare type ExtractStatefulState<T extends StateContainerConstructor> = IsStatelessContainer<T> extends true ? never : ExtractState<T>;
646
+
647
+ export declare type ExtractStateMutable<T> = T extends StateContainerConstructor<infer S, any> ? S : never;
648
+
649
+ export declare function forEach<T extends StateContainerConstructor>(BlocClass: T, callback: (instance: InstanceReadonlyState<T>) => void): void;
650
+
651
+ /**
652
+ * Generate ID with timestamp, counter, and random suffix (tree-shakeable)
653
+ *
654
+ * Format: `${prefix}:${timestamp}_${counter}_${random}`
655
+ *
656
+ * @param prefix - Prefix for the ID (e.g., 'sub', 'consumer', 'stage')
657
+ * @returns Branded ID string
658
+ *
659
+ * @example
660
+ * const id = generateId('sub');
661
+ * // Returns: "sub:1698765432100_1_a3k9d7f2q"
662
+ */
663
+ export declare function generateId(prefix: string): string;
664
+
665
+ /**
666
+ * Generate a unique isolated instance key
667
+ * Uses base36 encoding for compact, URL-safe identifiers
668
+ *
669
+ * Format: "isolated-{9-char-random-string}"
670
+ * Example: "isolated-k7x2m9p4q"
671
+ *
672
+ * @returns A unique isolated instance key
673
+ */
674
+ export declare function generateIsolatedKey(): string;
675
+
676
+ /**
677
+ * Generate simple ID with timestamp and random (no counter tracking)
678
+ *
679
+ * Format: `${prefix}:${timestamp}_${random}`
680
+ *
681
+ * @param prefix - Prefix for the ID
682
+ * @returns Branded ID string
683
+ *
684
+ * @example
685
+ * ```ts
686
+ * const id = generateSimpleId('CounterBloc');
687
+ * // Returns: "CounterBloc:1698765432100_a3k9d7f2q"
688
+ * ```
689
+ */
690
+ export declare function generateSimpleId(prefix: string, affix?: string): string;
691
+
692
+ /* Excluded from this release type: getActiveTracker */
693
+
694
+ export declare function getAll<T extends StateContainerConstructor>(BlocClass: T): InstanceReadonlyState<T>[];
695
+
696
+ /* Excluded from this release type: getBlacConfig */
697
+
698
+ /* Excluded from this release type: getDescriptor */
699
+
700
+ /* Excluded from this release type: getGetterExecutionContext */
701
+
702
+ /**
703
+ * Get the global plugin manager
704
+ */
705
+ export declare function getPluginManager(): any;
706
+
707
+ export declare function getRefCount<T extends StateContainerConstructor>(BlocClass: T, instanceKey?: string): number;
708
+
709
+ export declare function getRegistry(): StateContainerRegistry;
710
+
711
+ /**
712
+ * Get a static property from a class constructor
713
+ * Type-safe helper that avoids (Type as any) casts
714
+ *
715
+ * @param Type - The class constructor
716
+ * @param propName - The property name to access
717
+ * @param defaultValue - Optional default value if property is undefined
718
+ * @returns The property value or default
719
+ */
720
+ export declare function getStaticProp<V, T extends StateContainerConstructor = StateContainerConstructor>(Type: T, propName: string, defaultValue?: V): V | undefined;
721
+
722
+ export declare function getStats(): {
723
+ registeredTypes: number;
724
+ totalInstances: number;
725
+ typeBreakdown: Record<string, number>;
726
+ };
727
+
728
+ declare interface GetterExecutionContext {
729
+ tracker: GetterState | null;
730
+ currentBloc: StateContainerInstance | null;
731
+ depth: number;
732
+ visitedBlocs: Set<StateContainerInstance>;
733
+ }
734
+
735
+ /* Excluded from this release type: GetterState */
736
+
737
+ /* Excluded from this release type: getValueAtPath */
738
+
739
+ /**
740
+ * Global default registry instance
741
+ */
742
+ export declare const globalRegistry: StateContainerRegistry;
743
+
744
+ /* Excluded from this release type: hasDependencyChanges */
745
+
746
+ /* Excluded from this release type: hasGetterChanges */
747
+
748
+ /**
749
+ * Type guard to check if a plugin has a required onInstall hook
750
+ * @param plugin - The plugin to check
751
+ * @returns true if the plugin implements BlacPluginWithInit
752
+ */
753
+ export declare function hasInitHook(plugin: BlacPlugin): plugin is BlacPluginWithInit;
754
+
755
+ export declare function hasInstance<T extends StateContainerConstructor>(BlocClass: T, instanceKey?: string): boolean;
756
+
757
+ /* Excluded from this release type: hasTrackedData */
758
+
759
+ /**
760
+ * Check if tracked state or getters have changed.
761
+ */
762
+ export declare function hasTrackingProxyChanges(tracker: TrackingProxyState, bloc: StateContainerInstance): boolean;
763
+
764
+ /**
765
+ * Log an info message (tree-shakeable export)
766
+ * @param context - Context identifier (module or component name)
767
+ * @param message - Log message
768
+ * @param data - Optional structured data
769
+ */
770
+ export declare const info: (context: string, message: string, data?: any) => void;
771
+
772
+ /**
773
+ * Create a reference to a specific bloc instance.
774
+ *
775
+ * @example
776
+ * ```ts
777
+ * watch(instance(UserBloc, 'user-123'), (userBloc) => {
778
+ * console.log(userBloc.state.name);
779
+ * });
780
+ * ```
781
+ */
782
+ export declare function instance<T extends StateContainerConstructor>(BlocClass: T, instanceId: string): BlocRef<T>;
783
+
784
+ /**
785
+ * Entry in the instance registry, tracking the instance and its reference count
786
+ * @template T - Instance type
787
+ */
788
+ export declare interface InstanceEntry<T = any> {
789
+ /** The state container instance */
790
+ instance: T;
791
+ /** Number of active references to this instance */
792
+ refCount: number;
793
+ }
794
+
795
+ /**
796
+ * Branded string type for state container instance IDs
797
+ */
798
+ export declare type InstanceId = Brand<string, 'InstanceId'>;
799
+
800
+ /**
801
+ * Metadata information about a state container instance for debugging and inspection
802
+ */
803
+ export declare interface InstanceMetadata {
804
+ /** Unique instance identifier */
805
+ id: string;
806
+ /** Name of the state container class */
807
+ className: string;
808
+ /** Whether the instance has been disposed */
809
+ isDisposed: boolean;
810
+ /** Display name for the instance */
811
+ name: string;
812
+ /** When state last changed (milliseconds) */
813
+ lastStateChangeTimestamp: number;
814
+ /** Current state value */
815
+ state: any;
816
+ /** Timestamp when instance was created (milliseconds) */
817
+ createdAt: number;
818
+ /** Whether this is an isolated (component-scoped) instance */
819
+ isIsolated: boolean;
820
+ /** Stack trace from when instance was created (for debugging) */
821
+ callstack?: string;
822
+ /** Previous state value */
823
+ previousState?: any;
824
+ /** Current state value */
825
+ currentState?: any;
826
+ }
827
+
828
+ export declare type InstanceReadonlyState<T extends StateContainerConstructor = any> = Omit<InstanceType<T>, 'state'> & {
829
+ state: ExtractState<T>;
830
+ };
831
+
832
+ export declare type InstanceState<T extends StateContainerConstructor = any> = Omit<InstanceType<T>, 'state'> & {
833
+ state: ExtractStateMutable<T>;
834
+ };
835
+
836
+ /* Excluded from this release type: invalidateRenderCache */
837
+
838
+ /**
839
+ * Check if development mode is enabled.
840
+ */
841
+ export declare function isDevMode(): boolean;
842
+
843
+ /**
844
+ * Check if a class should be excluded from DevTools.
845
+ * Used to prevent infinite loops when DevTools tracks itself.
846
+ * @param Type - The class constructor to check
847
+ * @returns true if the class has `static __excludeFromDevTools = true`
848
+ */
849
+ export declare function isExcludedFromDevTools<T extends StateContainerConstructor>(Type: T): boolean;
850
+
851
+ /* Excluded from this release type: isGetter */
852
+
853
+ /**
854
+ * Check if a class is marked as isolated.
855
+ * Isolated classes create separate instances per component.
856
+ * @param Type - The class constructor to check
857
+ * @returns true if the class has `static isolated = true`
858
+ */
859
+ export declare function isIsolatedClass<T extends StateContainerConstructor>(Type: T): boolean;
860
+
861
+ /**
862
+ * Check if a key is an isolated instance key
863
+ * @param key - The instance key to check
864
+ * @returns true if the key is an isolated instance key
865
+ */
866
+ export declare function isIsolatedKey(key: string): boolean;
867
+
868
+ /**
869
+ * Check if a class is marked as keepAlive.
870
+ * KeepAlive classes are never auto-disposed when ref count reaches 0.
871
+ * @param Type - The class constructor to check
872
+ * @returns true if the class has `static keepAlive = true`
873
+ */
874
+ export declare function isKeepAliveClass<T extends StateContainerConstructor>(Type: T): boolean;
875
+
876
+ /* Excluded from this release type: isProxyable */
877
+
878
+ /**
879
+ * Check if a class is a stateless container (StatelessCubit or StatelessVertex).
880
+ * Stateless containers don't have state, emit, update, or subscribe methods.
881
+ * @param Type - The class constructor to check
882
+ * @returns true if the class is a stateless container
883
+ */
884
+ export declare function isStatelessClass<T extends StateContainerConstructor>(Type: T): boolean;
885
+
886
+ /**
887
+ * Check if a StateContainer constructor is a stateless container.
888
+ * Returns true for StatelessCubit and StatelessVertex classes.
889
+ */
890
+ export declare type IsStatelessContainer<T> = T extends {
891
+ readonly [STATELESS_MARKER]: true;
892
+ } ? true : false;
893
+
894
+ /**
895
+ * Lifecycle events emitted by the registry
896
+ */
897
+ export declare type LifecycleEvent = 'created' | 'stateChanged' | 'eventAdded' | 'disposed';
898
+
899
+ /**
900
+ * Listener function type for each lifecycle event
901
+ * @template E - The lifecycle event type
902
+ */
903
+ export declare 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 'eventAdded' ? (container: Vertex<any, any>, event: any) => void : E extends 'disposed' ? (container: StateContainer<any>) => void : never;
904
+
905
+ /**
906
+ * Configuration for the logger
907
+ */
908
+ export declare interface LogConfig {
909
+ /** Whether logging is enabled */
910
+ enabled: boolean;
911
+ /** Minimum log level to output */
912
+ level: LogLevel;
913
+ /** Function called to output log entries */
914
+ output: (entry: LogEntry) => void;
7
915
  }
8
916
 
9
917
  /**
10
- * Main Blac class that manages the state management system.
11
- * Can work with singleton pattern or dependency injection.
12
- * Handles bloc lifecycle, and instance tracking.
13
- *
14
- * Key responsibilities:
15
- * - Managing bloc instances (creation, disposal, lookup)
16
- * - Handling isolated and non-isolated blocs
17
- * - Providing logging and debugging capabilities
918
+ * Structure of a log entry passed to output handlers
18
919
  */
19
- export declare class Blac {
20
- static get instance(): Blac;
21
- /** Timestamp when the instance was created */
22
- createdAt: number;
23
- static get getAllBlocs(): <B extends BlocConstructor<any>>(blocClass: B, options?: {
24
- searchIsolated?: boolean;
25
- }) => InstanceType<B>[];
26
- /** Private static configuration */
27
- private static _config;
28
- /** Get current configuration */
29
- static get config(): Readonly<BlacConfig>;
30
- /**
31
- * Set or update Blac configuration
32
- * @param config - Partial configuration to merge with existing config
33
- * @throws Error if configuration is invalid
34
- */
35
- static setConfig(config: Partial<BlacConfig>): void;
36
- /** Map storing all registered bloc instances by their class name and ID */
37
- blocInstanceMap: Map<string, BlocBase<unknown>>;
38
- /** Map storing isolated bloc instances grouped by their constructor */
39
- isolatedBlocMap: Map<BlocConstructor<any>, BlocBase<unknown>[]>;
40
- /** Map for O(1) lookup of isolated blocs by UID */
41
- isolatedBlocIndex: Map<string, BlocBase<unknown>>;
42
- /** Map tracking UIDs to prevent memory leaks */
43
- uidRegistry: Map<string, BlocBase<unknown>>;
44
- /** Set of keep-alive blocs for controlled cleanup */
45
- keepAliveBlocs: Set<BlocBase<unknown>>;
46
- /** Flag to control whether changes should be posted to document */
47
- postChangesToDocument: boolean;
920
+ export declare interface LogEntry {
921
+ /** Log level as string (DEBUG, INFO, WARN, ERROR) */
922
+ level: string;
923
+ /** Context identifier (typically component or module name) */
924
+ context: string;
925
+ /** Log message */
926
+ message: string;
927
+ /** Optional structured data */
928
+ data?: any;
929
+ /** Unix timestamp in milliseconds */
930
+ timestamp: number;
931
+ }
932
+
933
+ /**
934
+ * Log severity levels (lower number = higher severity)
935
+ */
936
+ export declare enum LogLevel {
937
+ /** Critical errors that may cause application failure */
938
+ ERROR = 0,
939
+ /** Warning conditions that should be addressed */
940
+ WARN = 1,
941
+ /** Informational messages about application state */
942
+ INFO = 2,
943
+ /** Detailed debugging information */
944
+ DEBUG = 3
945
+ }
946
+
947
+ /**
948
+ * Configuration for manual dependency tracking mode
949
+ * @template TBloc - The state container type
950
+ */
951
+ export declare interface ManualDepsConfig<TBloc extends StateContainerConstructor> {
952
+ /** Function that returns dependency array from state and bloc */
953
+ dependencies: (state: ExtractState<TBloc>, bloc: InstanceState<TBloc>) => any[];
954
+ }
955
+
956
+ /**
957
+ * Initialize adapter state for manual dependency tracking mode.
958
+ * No proxy is created; bloc is used directly.
959
+ * @param instance - The state container instance
960
+ * @returns Initialized adapter state
961
+ */
962
+ export declare function manualDepsInit<TBloc extends StateContainerConstructor>(instance: InstanceState<TBloc>): AdapterState<TBloc>;
963
+
964
+ /**
965
+ * Create a snapshot function for manual dependency tracking mode.
966
+ * Caches dependencies for comparison on next render.
967
+ * @param instance - The state container instance
968
+ * @param adapterState - The adapter state for caching
969
+ * @param config - Configuration with dependencies function
970
+ * @returns Snapshot function for use with useSyncExternalStore
971
+ */
972
+ export declare function manualDepsSnapshot<TBloc extends StateContainerConstructor>(instance: InstanceState<TBloc>, adapterState: AdapterState<TBloc>, config: ManualDepsConfig<TBloc>): SnapshotFunction<ExtractState<TBloc>>;
973
+
974
+ /**
975
+ * Create a subscribe function for manual dependency tracking mode.
976
+ * Only triggers callback when dependencies array changes.
977
+ * @param instance - The state container instance
978
+ * @param adapterState - The adapter state for caching
979
+ * @param config - Configuration with dependencies function
980
+ * @returns Subscribe function for use with useSyncExternalStore
981
+ */
982
+ export declare function manualDepsSubscribe<TBloc extends StateContainerConstructor>(instance: InstanceState<TBloc>, adapterState: AdapterState<TBloc>, config: ManualDepsConfig<TBloc>): SubscribeFunction;
983
+
984
+ /**
985
+ * Initialize adapter state for no-tracking mode.
986
+ * No tracking or proxy is created.
987
+ * @param instance - The state container instance
988
+ * @returns Initialized adapter state
989
+ */
990
+ export declare function noTrackInit<TBloc extends StateContainerConstructor>(instance: InstanceState<TBloc>): AdapterState<TBloc>;
991
+
992
+ /**
993
+ * Create a snapshot function for no-tracking mode.
994
+ * Returns the raw state directly.
995
+ * @param instance - The state container instance
996
+ * @returns Snapshot function for use with useSyncExternalStore
997
+ */
998
+ export declare function noTrackSnapshot<TBloc extends StateContainerConstructor>(instance: InstanceReadonlyState<TBloc>): SnapshotFunction<ExtractState<TBloc>>;
999
+
1000
+ /**
1001
+ * Create a subscribe function for no-tracking mode.
1002
+ * Triggers callback on every state change.
1003
+ * @param instance - The state container instance
1004
+ * @returns Subscribe function for use with useSyncExternalStore
1005
+ */
1006
+ export declare function noTrackSubscribe<TBloc extends StateContainerInstance>(instance: TBloc): SubscribeFunction;
1007
+
1008
+ /* Excluded from this release type: parsePath */
1009
+
1010
+ /* Excluded from this release type: PathInfo */
1011
+
1012
+ /**
1013
+ * Configuration options for plugin installation
1014
+ */
1015
+ export declare interface PluginConfig {
1016
+ /** Enable or disable the plugin */
1017
+ enabled?: boolean;
1018
+ /** Environments where plugin runs */
1019
+ environment?: 'development' | 'production' | 'test' | 'all';
1020
+ }
1021
+
1022
+ /**
1023
+ * Safe context API provided to plugins for accessing registry data
1024
+ */
1025
+ export declare interface PluginContext {
48
1026
  /**
49
- * Creates a new Blac instance.
50
- * @param options - Configuration options including singleton control
1027
+ * Get metadata for a specific instance
51
1028
  */
52
- constructor(options?: {
53
- __unsafe_ignore_singleton?: boolean;
54
- });
55
- /** Flag to enable/disable logging */
56
- static enableLog: boolean;
57
- static logLevel: 'warn' | 'log';
58
- static logSpy: ((...args: unknown[]) => void) | null;
1029
+ getInstanceMetadata(instance: StateContainer<any>): InstanceMetadata;
59
1030
  /**
60
- * Logs messages to console when logging is enabled
61
- * @param args - Arguments to log
1031
+ * Get current state from a container
62
1032
  */
63
- log: (...args: unknown[]) => void;
64
- static get log(): (...args: unknown[]) => void;
1033
+ getState<S extends object = any>(instance: StateContainer<S>): S;
65
1034
  /**
66
- * Gets the current Blac instance
67
- * @returns The Blac instance
1035
+ * Get all instances of a specific type
68
1036
  */
69
- static getInstance(): Blac;
1037
+ queryInstances<T extends StateContainer<any>>(typeClass: new (...args: any[]) => T): T[];
70
1038
  /**
71
- * Logs a warning message
72
- * @param message - Warning message
73
- * @param args - Additional arguments
1039
+ * Get all registered state container types
74
1040
  */
75
- warn: (message: string, ...args: unknown[]) => void;
76
- static get warn(): (message: string, ...args: unknown[]) => void;
1041
+ getAllTypes(): Array<new (...args: any[]) => StateContainer<any>>;
77
1042
  /**
78
- * Logs an error message
79
- * @param message - Error message
80
- * @param args - Additional arguments
1043
+ * Get registry statistics
81
1044
  */
82
- error: (message: string, ...args: unknown[]) => void;
83
- static get error(): (message: string, ...args: unknown[]) => void;
1045
+ getStats(): {
1046
+ registeredTypes: number;
1047
+ totalInstances: number;
1048
+ typeBreakdown: Record<string, number>;
1049
+ };
1050
+ }
1051
+
1052
+ /**
1053
+ * Manages plugin lifecycle for the BlaC state management system.
1054
+ * Plugins receive notifications about state container lifecycle events.
1055
+ *
1056
+ * @example
1057
+ * ```ts
1058
+ * const manager = createPluginManager(registry);
1059
+ * manager.install(myPlugin, { environment: 'development' });
1060
+ * ```
1061
+ */
1062
+ export declare class PluginManager {
1063
+ private plugins;
1064
+ private registry;
84
1065
  /**
85
- * Resets the Blac instance to a new one, disposing non-keepAlive blocs
86
- * from the old instance.
1066
+ * Create a new PluginManager
1067
+ * @param registry - The StateContainerRegistry to monitor for lifecycle events
87
1068
  */
88
- resetInstance: () => void;
89
- static resetInstance: () => void;
1069
+ constructor(registry: StateContainerRegistry);
90
1070
  /**
91
- * Disposes of a bloc instance by removing it from the appropriate registry
92
- * @param bloc - The bloc instance to dispose
1071
+ * Install a plugin with optional configuration
1072
+ * @param plugin - The plugin to install
1073
+ * @param config - Optional plugin configuration
1074
+ * @throws Error if plugin is already installed
93
1075
  */
94
- disposeBloc: (bloc: BlocBase<unknown>) => void;
95
- static get disposeBloc(): (bloc: BlocBase<unknown>) => void;
1076
+ install(plugin: BlacPlugin, config?: PluginConfig): void;
96
1077
  /**
97
- * Creates a unique key for a bloc instance in the map based on the bloc class name and instance ID
98
- * @param blocClassName - The name of the bloc class
99
- * @param id - The instance ID
100
- * @returns A unique key string in the format "className:id"
1078
+ * Uninstall a plugin by name
1079
+ * @param pluginName - The name of the plugin to uninstall
1080
+ * @throws Error if plugin is not installed
101
1081
  */
102
- createBlocInstanceMapKey(blocClassName: string, id: BlocInstanceId): string;
1082
+ uninstall(pluginName: string): void;
103
1083
  /**
104
- * Unregister a bloc instance from the main registry
105
- * @param bloc - The bloc instance to unregister
1084
+ * Get an installed plugin by name
1085
+ * @param pluginName - The name of the plugin to retrieve
1086
+ * @returns The plugin instance or undefined if not found
106
1087
  */
107
- unregisterBlocInstance(bloc: BlocBase<unknown>): void;
1088
+ getPlugin(pluginName: string): BlacPlugin | undefined;
108
1089
  /**
109
- * Registers a bloc instance in the main registry
110
- * @param bloc - The bloc instance to register
1090
+ * Get all installed plugins
1091
+ * @returns Array of all installed plugins
111
1092
  */
112
- registerBlocInstance(bloc: BlocBase<unknown>): void;
1093
+ getAllPlugins(): BlacPlugin[];
113
1094
  /**
114
- * Finds a registered bloc instance by its class and ID
115
- * @param blocClass - The bloc class to search for
116
- * @param id - The instance ID
117
- * @returns The found bloc instance or undefined if not found
1095
+ * Check if a plugin is installed
1096
+ * @param pluginName - The name of the plugin to check
1097
+ * @returns true if the plugin is installed
118
1098
  */
119
- findRegisteredBlocInstance<B extends BlocConstructor<any>>(blocClass: B, id: BlocInstanceId): InstanceType<B> | undefined;
1099
+ hasPlugin(pluginName: string): boolean;
120
1100
  /**
121
- * Registers an isolated bloc instance in the isolated registry
122
- * @param bloc - The isolated bloc instance to register
1101
+ * Uninstall all plugins
123
1102
  */
124
- registerIsolatedBlocInstance(bloc: BlocBase<unknown>): void;
1103
+ clear(): void;
125
1104
  /**
126
- * Unregister an isolated bloc instance from the isolated registry
127
- * @param bloc - The isolated bloc instance to unregister
1105
+ * Setup lifecycle hooks to notify plugins
128
1106
  */
129
- unregisterIsolatedBlocInstance(bloc: BlocBase<unknown>): void;
1107
+ private setupLifecycleHooks;
130
1108
  /**
131
- * Finds an isolated bloc instance by its class and ID (O(n) lookup)
1109
+ * Notify all plugins of a lifecycle event
132
1110
  */
133
- findIsolatedBlocInstance<B extends BlocConstructor<any>>(blocClass: B, id: BlocInstanceId): InstanceType<B> | undefined;
1111
+ private notifyPlugins;
134
1112
  /**
135
- * Finds an isolated bloc instance by UID (O(1) lookup)
1113
+ * Create plugin context with safe API access
136
1114
  */
137
- findIsolatedBlocInstanceByUid<B extends BlocBase<unknown>>(uid: string): B | undefined;
1115
+ private createPluginContext;
138
1116
  /**
139
- * Creates a new bloc instance and registers it in the appropriate registry
140
- * @param blocClass - The bloc class to instantiate
141
- * @param id - The instance ID
142
- * @param props - Properties to pass to the bloc constructor
143
- * @param instanceRef - Optional reference string for the instance
144
- * @returns The newly created bloc instance
1117
+ * Check if plugin should be enabled based on environment
145
1118
  */
146
- createNewBlocInstance<B extends BlocConstructor<BlocBase<any>>>(blocClass: B, id: BlocInstanceId, options?: GetBlocOptions<InstanceType<B>>): InstanceType<B>;
147
- activateBloc: (bloc: BlocBase<unknown>) => void;
148
- static get activateBloc(): (bloc: BlocBase<unknown>) => void;
149
- /**
150
- * Gets or creates a bloc instance based on the provided class and options.
151
- * If a bloc with the given ID exists, it will be returned. Otherwise, a new instance will be created.
152
- *
153
- * @param blocClass - The bloc class to get or create
154
- * @param options - Options including:
155
- * - id: The instance ID (defaults to class name if not provided)
156
- * - props: Properties to pass to the bloc constructor
157
- * - instanceRef: Optional reference string for the instance
158
- * @returns The bloc instance
159
- */
160
- getBloc: <B extends BlocConstructor<BlocBase<any>>>(blocClass: B, options?: GetBlocOptions<InstanceType<B>>) => InstanceType<B>;
161
- static get getBloc(): <B extends BlocConstructor<BlocBase<any>>>(blocClass: B, options?: GetBlocOptions<InstanceType<B>>) => InstanceType<B>;
162
- /**
163
- * Gets a bloc instance or throws an error if it doesn't exist
164
- * @param blocClass - The bloc class to get
165
- * @param options - Options including:
166
- * - id: The instance ID (defaults to class name if not provided)
167
- * - props: Properties to pass to the bloc constructor
168
- * - instanceRef: Optional reference string for the instance
169
- */
170
- getBlocOrThrow: <B extends BlocConstructor<any>>(blocClass: B, options?: {
171
- id?: BlocInstanceId;
172
- props?: InferPropsFromGeneric<B>;
173
- instanceRef?: string;
174
- }) => InstanceType<B>;
175
- static get getBlocOrThrow(): <B extends BlocConstructor<any>>(blocClass: B, options?: {
176
- id?: BlocInstanceId;
177
- props?: InferPropsFromGeneric<B> | undefined;
178
- instanceRef?: string;
179
- }) => InstanceType<B>;
180
- /**
181
- * Gets all instances of a specific bloc class
182
- * @param blocClass - The bloc class to search for
183
- * @param options - Options including:
184
- * - searchIsolated: Whether to search in isolated blocs (defaults to bloc's isolated property)
185
- * @returns Array of matching bloc instances
186
- */
187
- getAllBlocs: <B extends BlocConstructor<any>>(blocClass: B, options?: {
188
- searchIsolated?: boolean;
189
- }) => InstanceType<B>[];
190
- /**
191
- * Disposes all keep-alive blocs of a specific type
192
- * @param blocClass - The bloc class to dispose
193
- */
194
- disposeKeepAliveBlocs: <B extends BlocConstructor<any>>(blocClass?: B) => void;
195
- static get disposeKeepAliveBlocs(): <B extends BlocConstructor<any>>(blocClass?: B | undefined) => void;
196
- /**
197
- * Disposes all blocs matching a pattern
198
- * @param predicate - Function to test each bloc for disposal
199
- */
200
- disposeBlocs: (predicate: (bloc: BlocBase<unknown>) => boolean) => void;
201
- static get disposeBlocs(): (predicate: (bloc: BlocBase<unknown>) => boolean) => void;
202
- /**
203
- * Gets memory usage statistics for debugging
204
- */
205
- getMemoryStats: () => {
206
- totalBlocs: number;
207
- registeredBlocs: number;
208
- isolatedBlocs: number;
209
- keepAliveBlocs: number;
210
- isolatedBlocTypes: number;
211
- };
212
- static get getMemoryStats(): () => {
213
- totalBlocs: number;
214
- registeredBlocs: number;
215
- isolatedBlocs: number;
216
- keepAliveBlocs: number;
217
- isolatedBlocTypes: number;
218
- };
1119
+ private shouldEnablePlugin;
219
1120
  /**
220
- * Validates consumer references and cleans up orphaned consumers
1121
+ * Get current environment
221
1122
  */
222
- validateConsumers: () => void;
223
- static get validateConsumers(): () => void;
1123
+ private getCurrentEnvironment;
224
1124
  }
225
1125
 
1126
+ /* Excluded from this release type: ProxyState */
1127
+
1128
+ export declare function register<T extends StateContainerConstructor>(BlocClass: T, isolated?: boolean): void;
1129
+
1130
+ export declare function release<T extends StateContainerConstructor>(BlocClass: T, instanceKey?: string, forceDispose?: boolean): void;
1131
+
1132
+ /* Excluded from this release type: resetBlacConfig */
1133
+
1134
+ /* Excluded from this release type: resetGetterState */
1135
+
1136
+ /* Excluded from this release type: setActiveTracker */
1137
+
1138
+ export declare function setRegistry(registry: StateContainerRegistry): void;
1139
+
1140
+ /* Excluded from this release type: shallowEqual */
1141
+
226
1142
  /**
227
- * BlacAdapter orchestrates the connection between Bloc instances and React components.
228
- * It manages dependency tracking, lifecycle hooks, and proxy creation.
229
- */
230
- export declare class BlacAdapter<B extends BlocConstructor<BlocBase<any>>> {
231
- readonly id: string;
232
- readonly blocConstructor: B;
233
- readonly componentRef: {
234
- current: object;
235
- };
236
- blocInstance: InstanceType<B>;
237
- private consumerTracker;
238
- private static propsOwners;
239
- private lastProps?;
240
- unmountTime: number;
241
- mountTime: number;
242
- private dependencyValues?;
243
- private isUsingDependencies;
244
- private hasMounted;
245
- private mountCount;
246
- options?: AdapterOptions<InstanceType<B>>;
247
- constructor(instanceProps: {
248
- componentRef: {
249
- current: object;
250
- };
251
- blocConstructor: B;
252
- }, options?: typeof BlacAdapter.options);
253
- trackAccess(consumerRef: object, type: 'state' | 'class', path: string, value?: any): void;
254
- getConsumerDependencies(consumerRef: object): DependencyArray | null;
255
- shouldNotifyConsumer(consumerRef: object, changedPaths: Set<string>): boolean;
256
- updateLastNotified(consumerRef: object): void;
257
- resetConsumerTracking(): void;
258
- createStateProxy: <T extends object>(props: {
259
- target: T;
260
- }) => T;
261
- createClassProxy: <T extends object>(props: {
262
- target: T;
263
- }) => T;
264
- updateBlocInstance(): InstanceType<B>;
265
- createSubscription: (options: {
266
- onChange: () => void;
267
- }) => () => void;
268
- mount: () => void;
269
- unmount: () => void;
270
- getProxyState: (state: BlocState<InstanceType<B>>) => BlocState<InstanceType<B>>;
271
- getProxyBlocInstance: () => InstanceType<B>;
272
- get calledOnMount(): boolean;
273
- updateProps(props: any): void;
274
- private hasDependencyValuesChanged;
275
- }
276
-
277
- /**
278
- * Configuration options for the Blac instance
1143
+ * Function that returns a snapshot of the current state
1144
+ * @template TState - The state type
279
1145
  */
280
- export declare interface BlacConfig {
281
- /** Whether to expose the Blac instance globally */
282
- exposeBlacInstance?: boolean;
283
- /**
284
- * Whether to enable proxy dependency tracking for automatic re-render optimization.
285
- * When false, state changes always cause re-renders unless dependencies are manually specified.
286
- * Default: true
287
- */
288
- proxyDependencyTracking?: boolean;
289
- }
1146
+ export declare type SnapshotFunction<TState> = () => TState;
1147
+
1148
+ /* Excluded from this release type: startDependency */
1149
+
1150
+ /* Excluded from this release type: startProxy */
290
1151
 
291
1152
  /**
292
- * Interface for Blac instance management
1153
+ * Start tracking on a tracking proxy.
293
1154
  */
294
- export declare interface BlacInstanceManager {
295
- getInstance(): Blac;
296
- setInstance(instance: Blac): void;
297
- resetInstance(): void;
298
- }
1155
+ export declare function startTrackingProxy(tracker: TrackingProxyState): void;
299
1156
 
300
1157
  /**
301
- * A class that manages observers for a Bloc's state changes
302
- * @template S - The type of state being observed
1158
+ * Abstract base class for all state containers in BlaC.
1159
+ * Provides lifecycle management, subscription handling, ref counting,
1160
+ * and integration with the global registry.
1161
+ *
1162
+ * @template S - State type managed by this container
1163
+ * @template P - Props type passed to the container (optional)
1164
+ *
1165
+ * @example
1166
+ * ```ts
1167
+ * class CounterBloc extends StateContainer<{ count: number }> {
1168
+ * constructor() {
1169
+ * super({ count: 0 });
1170
+ * }
1171
+ * increment() {
1172
+ * this.emit({ count: this.state.count + 1 });
1173
+ * }
1174
+ * }
1175
+ * ```
303
1176
  */
304
- export declare class BlacObservable<S = unknown> {
305
- /** The Bloc instance this observable is associated with */
306
- bloc: BlocBase<S>;
1177
+ export declare abstract class StateContainer<S extends object = any, P = any> {
1178
+ static __excludeFromDevTools: boolean;
1179
+ static enableStackTrace: boolean;
1180
+ private _state;
1181
+ private readonly listeners;
1182
+ private _disposed;
1183
+ private config;
1184
+ private _props;
1185
+ private readonly systemEventHandlers;
1186
+ /** Display name for this instance */
1187
+ name: string;
1188
+ /** Whether debug logging is enabled */
1189
+ debug: boolean;
1190
+ /** Unique identifier for this instance */
1191
+ instanceId: string;
1192
+ /** Timestamp when this instance was created */
1193
+ createdAt: number;
1194
+ /** Current props value passed to this container */
1195
+ get props(): P | undefined;
1196
+ constructor(initialState: S);
307
1197
  /**
308
- * Creates a new BlacObservable instance
309
- * @param bloc - The Bloc instance to observe
1198
+ * Initialize configuration for this instance.
1199
+ * Called by the registry after construction.
1200
+ * @param config - Configuration options
310
1201
  */
311
- constructor(bloc: BlocBase<S>);
312
- private _observers;
1202
+ initConfig(config: StateContainerConfig): void;
1203
+ /** Current state value */
1204
+ get state(): Readonly<S>;
1205
+ /** Whether this instance has been disposed */
1206
+ get isDisposed(): boolean;
313
1207
  /**
314
- * Gets the number of active observers
315
- * @returns The number of observers currently subscribed
1208
+ * Subscribe to state changes
1209
+ * @param listener - Function called when state changes
1210
+ * @returns Unsubscribe function
316
1211
  */
317
- get size(): number;
1212
+ subscribe(listener: StateListener<S>): () => void;
318
1213
  /**
319
- * Gets the set of all observers
320
- * @returns The Set of all BlacObserver instances
1214
+ * Dispose this instance and clean up resources.
1215
+ * Clears all listeners and emits the 'dispose' system event.
321
1216
  */
322
- get observers(): Set<BlacObserver<S>>;
1217
+ dispose(): void;
323
1218
  /**
324
- * Subscribes an observer to state changes
325
- * @param observer - The observer to subscribe
326
- * @returns A function that can be called to unsubscribe the observer
1219
+ * Emit a new state value and notify all listeners.
1220
+ * @param newState - The new state value
1221
+ * @protected
327
1222
  */
328
- subscribe(observer: BlacObserver<S>): () => void;
1223
+ protected emit(newState: S): void;
1224
+ private captureStackTrace;
1225
+ private formatStackLine;
1226
+ private cleanFilePath;
1227
+ /** Timestamp of the last state update */
1228
+ lastUpdateTimestamp: number;
329
1229
  /**
330
- * Unsubscribes an observer from state changes
331
- * @param observer - The observer to unsubscribe
1230
+ * Update state using a transform function.
1231
+ * @param updater - Function that receives current state and returns new state
1232
+ * @protected
332
1233
  */
333
- unsubscribe(observer: BlacObserver<S>): void;
1234
+ protected update(updater: (current: S) => S): void;
334
1235
  /**
335
- * Notifies all observers of a state change
336
- * @param newState - The new state value
337
- * @param oldState - The previous state value
338
- * @param action - Optional action that triggered the state change
1236
+ * Subscribe to system lifecycle events.
1237
+ * @param event - The event type to listen for
1238
+ * @param handler - Handler function called when event occurs
1239
+ * @returns Unsubscribe function
1240
+ * @protected
339
1241
  */
340
- notify(newState: S, oldState: S, action?: unknown): void;
1242
+ protected onSystemEvent: <E extends SystemEvent>(event: E, handler: SystemEventHandler<S, P, E>) => (() => void);
1243
+ private emitSystemEvent;
341
1244
  /**
342
- * Clears the observer set
1245
+ * Update the props for this container.
1246
+ * Emits the 'propsUpdated' system event.
1247
+ * @param newProps - The new props value
343
1248
  */
344
- clear(): void;
1249
+ updateProps(newProps: P): void;
345
1250
  }
346
1251
 
347
1252
  /**
348
- * Represents an observer that can subscribe to state changes in a Bloc
349
- * @template S - The type of state being observed
1253
+ * Configuration options for initializing a StateContainer instance
350
1254
  */
351
- export declare type BlacObserver<S> = {
352
- /** Function to be called when state changes */
353
- fn: (newState: S, oldState: S, action?: unknown) => void | Promise<void>;
354
- /** Optional function to determine if the observer should be notified of state changes */
355
- dependencyArray?: BlocHookDependencyArrayFn<S>;
356
- /** Dispose function for the observer */
357
- dispose?: () => void;
358
- /** Cached state values used for dependency comparison */
359
- lastState?: unknown[];
360
- /** Unique identifier for the observer */
361
- id: string;
1255
+ export declare interface StateContainerConfig {
1256
+ /** Display name for the instance (defaults to class name) */
1257
+ name?: string;
1258
+ /** Enable debug logging for this instance */
1259
+ debug?: boolean;
1260
+ /** Custom instance identifier */
1261
+ instanceId?: string;
1262
+ }
1263
+
1264
+ /**
1265
+ * Constructor type for StateContainer classes
1266
+ * @template S - State type managed by the container
1267
+ * @template P - Props type passed to the container
1268
+ */
1269
+ export declare type StateContainerConstructor<S extends object = any, P = any> = new (...args: any[]) => StateContainer<S, P>;
1270
+
1271
+ export declare type StateContainerInstance<S extends object = any, P = any> = Omit<StateContainer<S, P>, 'state'> & {
1272
+ state: Readonly<S>;
362
1273
  };
363
1274
 
364
- export declare abstract class Bloc<S, // State type
365
- A extends BlocEventConstraint = BlocEventConstraint, // Base Action/Event type with proper constraints
366
- P = unknown> extends BlocBase<S, P> {
367
- readonly eventHandlers: Map<new (...args: any[]) => A, (event: A, emit: (newState: S) => void) => void | Promise<void>>;
368
- /* Excluded from this release type: _eventQueue */
369
- /* Excluded from this release type: _isProcessingEvent */
1275
+ /**
1276
+ * Central registry for managing StateContainer instances.
1277
+ * Handles instance lifecycle, ref counting, and lifecycle event emission.
1278
+ *
1279
+ * @example
1280
+ * ```ts
1281
+ * const registry = new StateContainerRegistry();
1282
+ * const instance = registry.acquire(MyBloc); // ownership, must release
1283
+ * const other = registry.ensure(OtherBloc); // no ownership, bloc-to-bloc
1284
+ * registry.on('stateChanged', (container, prev, next) => {
1285
+ * console.log('State changed:', prev, '->', next);
1286
+ * });
1287
+ * ```
1288
+ */
1289
+ export declare class StateContainerRegistry {
1290
+ private readonly instancesByConstructor;
1291
+ private readonly types;
1292
+ private readonly typeConfigs;
1293
+ private readonly listeners;
370
1294
  /**
371
- * Registers an event handler for a specific event type.
372
- * This method is typically called in the constructor of a derived Bloc class.
373
- * @param eventConstructor The constructor of the event to handle (e.g., LoadDataEvent).
374
- * @param handler A function that processes the event and can emit new states.
375
- * The 'event' parameter in the handler will be typed to the specific eventConstructor.
1295
+ * Register a type for lifecycle event tracking
1296
+ * @param constructor - The StateContainer class constructor
376
1297
  */
377
- protected on<E extends A>(eventConstructor: new (...args: any[]) => E, handler: (event: E, emit: (newState: S) => void) => void | Promise<void>): void;
1298
+ registerType<T extends StateContainerConstructor>(constructor: T): void;
378
1299
  /**
379
- * Dispatches an action/event to the Bloc.
380
- * Events are queued and processed sequentially to prevent race conditions.
381
- * @param action The action/event instance to be processed.
1300
+ * Register a StateContainer class with configuration
1301
+ * @param constructor - The StateContainer class constructor
1302
+ * @param isolated - Whether instances should be isolated (component-scoped)
1303
+ * @throws Error if type is already registered
382
1304
  */
383
- add: (action: A) => Promise<void>;
384
- /* Excluded from this release type: _processEventQueue */
385
- /* Excluded from this release type: _processEvent */
386
- }
387
-
388
- /**
389
- * Base class for both Blocs and Cubits that provides core state management functionality.
390
- * Handles state transitions, observer notifications, lifecycle management, and addon integration.
391
- *
392
- * @abstract This class should be extended, not instantiated directly
393
- * @template S The type of state managed by this Bloc
394
- * @template P The type of props that can be passed during instance creation (optional)
395
- */
396
- export declare abstract class BlocBase<S, P = unknown> {
397
- uid: string;
1305
+ register<T extends StateContainerConstructor>(constructor: T, isolated?: boolean): void;
1306
+ private ensureInstancesMap;
1307
+ /**
1308
+ * Get the instances Map for a specific class (public API for stats/debugging)
1309
+ */
1310
+ getInstancesMap<T extends StateContainerConstructor>(Type: T): Map<string, InstanceEntry>;
1311
+ private trackExecutionContext;
1312
+ /**
1313
+ * Acquire an instance with ref counting (ownership semantics).
1314
+ * Creates a new instance if one doesn't exist, or returns existing and increments ref count.
1315
+ * You must call `release()` when done to decrement the ref count.
1316
+ * @param Type - The StateContainer class constructor
1317
+ * @param instanceKey - Instance key (defaults to 'default')
1318
+ * @param options - Acquisition options
1319
+ * @param options.canCreate - Whether to create new instance if not found (default: true)
1320
+ * @param options.countRef - Whether to increment ref count (default: true)
1321
+ * @param options.props - Props to pass to constructor if creating new instance
1322
+ * @param options.trackExecutionContext - Whether to track cross-bloc dependency (default: false)
1323
+ * @returns The state container instance
1324
+ */
1325
+ acquire<T extends StateContainerConstructor = StateContainerConstructor>(Type: T, instanceKey?: string, options?: {
1326
+ canCreate?: boolean;
1327
+ countRef?: boolean;
1328
+ props?: ExtractProps<T>;
1329
+ trackExecutionContext?: boolean;
1330
+ }): InstanceType<T>;
1331
+ /**
1332
+ * Borrow an existing instance without incrementing ref count (borrowing semantics).
1333
+ * Tracks cross-bloc dependency for reactive updates.
1334
+ * @param Type - The StateContainer class constructor
1335
+ * @param instanceKey - Instance key (defaults to 'default')
1336
+ * @returns The state container instance
1337
+ * @throws Error if instance doesn't exist
1338
+ */
1339
+ borrow<T extends StateContainerConstructor = StateContainerConstructor>(Type: T, instanceKey?: string): InstanceType<T>;
398
1340
  /**
399
- * When true, every consumer will receive its own unique instance of this Bloc.
400
- * Use this when state should not be shared between components.
401
- * @default false
1341
+ * Safely borrow an existing instance (borrowing semantics with error handling).
1342
+ * Returns discriminated union for type-safe conditional access.
1343
+ * @param Type - The StateContainer class constructor
1344
+ * @param instanceKey - Instance key (defaults to 'default')
1345
+ * @returns Discriminated union with either the instance or an error
402
1346
  */
403
- static isolated: boolean;
404
- get isIsolated(): boolean;
1347
+ borrowSafe<T extends StateContainerConstructor = StateContainerConstructor>(Type: T, instanceKey?: string): {
1348
+ error: Error;
1349
+ instance: null;
1350
+ } | {
1351
+ error: null;
1352
+ instance: InstanceType<T>;
1353
+ };
1354
+ /**
1355
+ * Ensure an instance exists without taking ownership (for bloc-to-bloc communication).
1356
+ * Gets existing instance OR creates it if it doesn't exist, without incrementing ref count.
1357
+ * Tracks cross-bloc dependency for reactive updates.
1358
+ *
1359
+ * Use this in bloc-to-bloc communication when you need to ensure an instance exists
1360
+ * but don't want to claim ownership (no ref count increment).
1361
+ * @param Type - The StateContainer class constructor
1362
+ * @param instanceKey - Instance key (defaults to 'default')
1363
+ * @returns The state container instance
1364
+ */
1365
+ ensure<T extends StateContainerConstructor = StateContainerConstructor>(Type: T, instanceKey?: string): InstanceType<T>;
405
1366
  /**
406
- * When true, the Bloc instance persists even when there are no active consumers.
407
- * Useful for maintaining state between component unmount/remount cycles.
408
- * @default false
1367
+ * Release a reference to an instance.
1368
+ * Decrements ref count and disposes when it reaches 0 (unless keepAlive).
1369
+ * @param Type - The StateContainer class constructor
1370
+ * @param instanceKey - Instance key (defaults to 'default')
1371
+ * @param forceDispose - Force immediate disposal regardless of ref count
409
1372
  */
410
- static keepAlive: boolean;
411
- get isKeepAlive(): boolean;
1373
+ release<T extends StateContainerConstructor>(Type: T, instanceKey?: string, forceDispose?: boolean): void;
412
1374
  /**
413
- * Defines how dependencies are selected from the state for efficient updates.
414
- * When provided, observers will only be notified when selected dependencies change.
1375
+ * Get all instances of a specific type.
1376
+ * @param Type - The StateContainer class constructor
1377
+ * @returns Array of all instances
415
1378
  */
416
- defaultDependencySelector: DependencySelector<S> | undefined;
417
- /* Excluded from this release type: _isolated */
418
- /* Excluded from this release type: _observer */
1379
+ getAll<T extends StateContainerConstructor>(Type: T): InstanceReadonlyState<T>[];
419
1380
  /**
420
- * The unique identifier for this Bloc instance.
421
- * Defaults to the class name, but can be customized.
1381
+ * Safely iterate over all instances of a type.
1382
+ * Skips disposed instances and catches callback errors.
1383
+ * @param Type - The StateContainer class constructor
1384
+ * @param callback - Function to call for each instance
422
1385
  */
423
- _id: BlocInstanceId;
424
- /* Excluded from this release type: _instanceRef */
425
- /* Excluded from this release type: _keepAlive */
1386
+ forEach<T extends StateContainerConstructor>(Type: T, callback: (instance: InstanceReadonlyState<T>) => void): void;
426
1387
  /**
427
- * @readonly
428
- * Timestamp when this Bloc instance was created, useful for debugging and performance tracking.
1388
+ * Clear all instances of a specific type (disposes them).
1389
+ * @param Type - The StateContainer class constructor
429
1390
  */
430
- readonly _createdAt: number;
431
- /* Excluded from this release type: _disposalState */
432
- /* Excluded from this release type: _disposalRequestTime */
433
- /* Excluded from this release type: _state */
434
- /* Excluded from this release type: _oldState */
1391
+ clear<T extends StateContainerConstructor>(Type: T): void;
435
1392
  /**
436
- * Props passed during Bloc instance creation.
437
- * Can be used to configure or parameterize the Bloc's behavior.
1393
+ * Get reference count for an instance.
1394
+ * @param Type - The StateContainer class constructor
1395
+ * @param instanceKey - Instance key (defaults to 'default')
1396
+ * @returns Current ref count (0 if instance doesn't exist)
438
1397
  */
439
- props: P | null;
440
- /* Excluded from this release type: _batchingLock */
441
- /* Excluded from this release type: _pendingUpdates */
442
- /* Excluded from this release type: _consumerRefs */
443
- /* Excluded from this release type: _validateConsumers */
1398
+ getRefCount<T extends StateContainerConstructor>(Type: T, instanceKey?: string): number;
444
1399
  /**
445
- * Creates a new BlocBase instance with the given initial state.
446
- * Sets up the observer, registers with the Blac manager, and initializes addons.
1400
+ * Check if an instance exists.
1401
+ * @param Type - The StateContainer class constructor
1402
+ * @param instanceKey - Instance key (defaults to 'default')
1403
+ * @returns true if instance exists
1404
+ */
1405
+ hasInstance<T extends StateContainerConstructor>(Type: T, instanceKey?: string): boolean;
1406
+ /**
1407
+ * Clear all instances from all types (for testing)
447
1408
  *
448
- * @param initialState The initial state value for this Bloc
1409
+ * Iterates all registered types and clears their instances.
1410
+ * Also clears type tracking to reset the registry state.
449
1411
  */
450
- constructor(initialState: S);
1412
+ clearAll(): void;
451
1413
  /**
452
- * Returns the current state of the Bloc.
453
- * Use this getter to access the state in a read-only manner.
454
- * Returns the state even during transitional lifecycle states for React compatibility.
1414
+ * Get registry statistics for debugging.
1415
+ * @returns Object with registeredTypes, totalInstances, and typeBreakdown
455
1416
  */
456
- get state(): S;
1417
+ getStats(): {
1418
+ registeredTypes: number;
1419
+ totalInstances: number;
1420
+ typeBreakdown: Record<string, number>;
1421
+ };
457
1422
  /**
458
- * Returns whether this Bloc instance has been disposed.
459
- * @returns true if the bloc is in DISPOSED state
1423
+ * Get all registered types (for plugin system).
1424
+ * @returns Array of all registered StateContainer class constructors
460
1425
  */
461
- get isDisposed(): boolean;
462
- /* Excluded from this release type: _name */
463
- /* Excluded from this release type: _updateId */
464
- /* Excluded from this release type: _atomicStateTransition */
465
- /* Excluded from this release type: _dispose */
466
- /* Excluded from this release type: onDispose */
467
- /* Excluded from this release type: _consumers */
468
- /* Excluded from this release type: _addConsumer */
469
- /* Excluded from this release type: _removeConsumer */
470
- /* Excluded from this release type: _disposalHandler */
471
- /* Excluded from this release type: _setDisposalHandler */
472
- /* Excluded from this release type: _scheduleDisposal */
473
- lastUpdate: number;
474
- /* Excluded from this release type: _batchingEnabled */
475
- /* Excluded from this release type: _pushState */
1426
+ getTypes(): StateContainerConstructor[];
476
1427
  /**
477
- * Enables batching for multiple state updates
478
- * @param batchFn Function to execute with batching enabled
1428
+ * Subscribe to lifecycle events
1429
+ * @param event - The lifecycle event to listen for
1430
+ * @param listener - The listener function to call when the event occurs
1431
+ * @returns Unsubscribe function
479
1432
  */
480
- batch: <T>(batchFn: () => T) => T;
1433
+ on<E extends LifecycleEvent>(event: E, listener: LifecycleListener<E>): () => void;
1434
+ /* Excluded from this release type: emit */
481
1435
  }
482
1436
 
483
1437
  /**
484
- * Represents the abstract base types for Bloc and Cubit
1438
+ * Constrain a type to only accept stateful containers (not StatelessCubit/StatelessVertex).
1439
+ * Use this to reject stateless containers at the type level.
485
1440
  */
486
- export declare type BlocBaseAbstract = typeof Bloc<any, any, any> | typeof Cubit<any, any>;
1441
+ export declare type StatefulContainerOnly<T extends StateContainerConstructor> = IsStatelessContainer<T> extends true ? never : T;
487
1442
 
488
1443
  /**
489
- * Represents a constructor type for a Bloc that takes no parameters
490
- * @template B - The type of the Bloc instance
1444
+ * Marker symbol to identify stateless containers at the type level.
1445
+ * Used by React hooks to prevent `useBloc` from accepting stateless containers.
491
1446
  */
492
- export declare type BlocClassNoParams<B> = new (args: never[]) => B;
1447
+ export declare const STATELESS_MARKER: unique symbol;
493
1448
 
494
1449
  /**
495
- * Represents a constructor type for a Bloc that can take any parameters
496
- * @template B - The type of the Bloc instance
1450
+ * A Cubit without state management capabilities.
1451
+ * Use this for action-only containers that don't need to manage or emit state.
1452
+ *
1453
+ * StatelessCubit:
1454
+ * - Has no `emit()`, `update()`, or `patch()` methods
1455
+ * - Has no accessible `state` property
1456
+ * - Cannot be subscribed to (throws error)
1457
+ * - Is rejected by `useBloc` hook (use `useBlocActions` instead)
1458
+ *
1459
+ * @template P - Props type (optional)
1460
+ *
1461
+ * @example
1462
+ * ```typescript
1463
+ * class AnalyticsService extends StatelessCubit {
1464
+ * trackPageView(page: string) {
1465
+ * analytics.track('page_view', { page });
1466
+ * }
1467
+ *
1468
+ * trackClick(element: string) {
1469
+ * analytics.track('click', { element });
1470
+ * }
1471
+ * }
1472
+ *
1473
+ * // In React component:
1474
+ * const analytics = useBlocActions(AnalyticsService);
1475
+ * analytics.trackPageView('/home');
1476
+ * ```
497
1477
  */
498
- export declare type BlocConstructor<B> = (new (...args: any) => B) & {
499
- isolated?: boolean;
500
- keepAlive?: boolean;
501
- };
1478
+ export declare abstract class StatelessCubit<P = undefined> extends Cubit<EmptyState, P> {
1479
+ /* Excluded from this release type: [STATELESS_MARKER] */
1480
+ constructor();
1481
+ /**
1482
+ * State is not available on StatelessCubit.
1483
+ * @throws Always throws an error when accessed.
1484
+ */
1485
+ get state(): never;
1486
+ /**
1487
+ * Subscriptions are not available on StatelessCubit.
1488
+ * @throws Always throws an error when called.
1489
+ */
1490
+ subscribe(_listener: (state: EmptyState) => void): never;
1491
+ /**
1492
+ * emit() is not available on StatelessCubit.
1493
+ * TypeScript will show an error if you try to call this method.
1494
+ */
1495
+ emit(_newState: never): never;
1496
+ /**
1497
+ * update() is not available on StatelessCubit.
1498
+ * TypeScript will show an error if you try to call this method.
1499
+ */
1500
+ update(_updater: never): never;
1501
+ /**
1502
+ * patch() is not available on StatelessCubit.
1503
+ * @throws Error always - StatelessCubit does not support state changes
1504
+ */
1505
+ patch: (_partial: Partial<EmptyState>) => void;
1506
+ }
1507
+
1508
+ /**
1509
+ * Event handler for StatelessVertex that receives only the event (no emit function).
1510
+ * Use for side-effect-only event processing.
1511
+ */
1512
+ export declare type StatelessEventHandler<E extends DiscriminatedEvent> = (event: EventWithMetadata<E>) => void;
502
1513
 
503
1514
  /**
504
- * Extracts the constructor parameters type from a BlocBase
505
- * @template B - The BlocBase type to extract the constructor parameters from
1515
+ * Map of event types to their handlers for StatelessVertex.
1516
+ * Enforces exhaustive handling of all event types in the union.
506
1517
  */
507
- export declare type BlocConstructorParameters<B extends BlocBase<any>> = BlocConstructor<B> extends new (...args: infer P) => B ? P : never;
1518
+ export declare type StatelessEventHandlerMap<E extends DiscriminatedEvent> = {
1519
+ [K in E['type']]: StatelessEventHandler<Extract<E, {
1520
+ type: K;
1521
+ }>>;
1522
+ };
508
1523
 
509
1524
  /**
510
- * Error boundary interface for Bloc error handling
1525
+ * An event-driven container without state management capabilities.
1526
+ * Use this for event processing that only produces side effects (logging, analytics, etc).
1527
+ *
1528
+ * StatelessVertex:
1529
+ * - Processes events via `add()` method
1530
+ * - Handlers receive only the event (no `emit` function)
1531
+ * - Has no accessible `state` property
1532
+ * - Cannot be subscribed to (throws error)
1533
+ * - Is rejected by `useBloc` hook (use `useBlocActions` instead)
1534
+ *
1535
+ * @template E - Event union type (discriminated by 'type' property)
1536
+ * @template P - Props type (optional)
1537
+ *
1538
+ * @example
1539
+ * ```typescript
1540
+ * type LogEvent =
1541
+ * | { type: 'info'; message: string }
1542
+ * | { type: 'error'; message: string; error: Error }
1543
+ * | { type: 'warn'; message: string };
1544
+ *
1545
+ * class LoggingVertex extends StatelessVertex<LogEvent> {
1546
+ * constructor() {
1547
+ * super();
1548
+ * this.createHandlers({
1549
+ * info: (event) => console.log('[INFO]', event.message),
1550
+ * error: (event) => console.error('[ERROR]', event.message, event.error),
1551
+ * warn: (event) => console.warn('[WARN]', event.message),
1552
+ * });
1553
+ * }
1554
+ *
1555
+ * info = (message: string) => this.add({ type: 'info', message });
1556
+ * error = (message: string, error: Error) => this.add({ type: 'error', message, error });
1557
+ * warn = (message: string) => this.add({ type: 'warn', message });
1558
+ * }
1559
+ *
1560
+ * // In React component:
1561
+ * const logger = useBlocActions(LoggingVertex);
1562
+ * logger.info('Page loaded');
1563
+ * ```
511
1564
  */
512
- export declare interface BlocErrorBoundary<S, A extends BlocEventConstraint> {
513
- onError: (error: Error, event: A, currentState: S, bloc: {
514
- name: string;
515
- id: string;
516
- }) => void | Promise<void>;
517
- shouldRethrow?: (error: Error, event: A) => boolean;
1565
+ export declare abstract class StatelessVertex<E extends DiscriminatedEvent = DiscriminatedEvent, P = undefined> extends StateContainer<EmptyState_2, P> {
1566
+ /* Excluded from this release type: [STATELESS_MARKER] */
1567
+ /* Excluded from this release type: handlers */
1568
+ /* Excluded from this release type: isProcessing */
1569
+ /* Excluded from this release type: eventQueue */
1570
+ constructor();
1571
+ /**
1572
+ * State is not available on StatelessVertex.
1573
+ * @throws Always throws an error when accessed.
1574
+ */
1575
+ get state(): never;
1576
+ /**
1577
+ * Subscriptions are not available on StatelessVertex.
1578
+ * @throws Always throws an error when called.
1579
+ */
1580
+ subscribe(_listener: (state: EmptyState_2) => void): never;
1581
+ /**
1582
+ * Register all event handlers with exhaustive type checking.
1583
+ * TypeScript will error if any event type from the union is missing.
1584
+ *
1585
+ * Unlike regular Vertex, handlers do NOT receive an emit function
1586
+ * since StatelessVertex cannot emit state.
1587
+ *
1588
+ * @param handlers - Map of event type to handler function
1589
+ */
1590
+ protected createHandlers(handlers: StatelessEventHandlerMap<E>): void;
1591
+ /**
1592
+ * Dispatch an event for processing.
1593
+ * Events are processed synchronously; if called during processing,
1594
+ * the event is queued and processed after the current event completes.
1595
+ *
1596
+ * @param event - The event to process (must match the event union type)
1597
+ */
1598
+ add: (event: E) => void;
1599
+ /* Excluded from this release type: enrichEvent */
1600
+ /* Excluded from this release type: processEvent */
1601
+ /* Excluded from this release type: handleEvent */
1602
+ /**
1603
+ * Called when an error occurs during event processing.
1604
+ * Override to implement custom error handling.
1605
+ *
1606
+ * @param _event - The event that caused the error
1607
+ * @param _error - The error that occurred
1608
+ */
1609
+ protected onEventError(_event: EventWithMetadata<E>, _error: Error): void;
1610
+ /* Excluded from this release type: emit */
1611
+ /* Excluded from this release type: update */
518
1612
  }
519
1613
 
1614
+ /* Excluded from this release type: StateListener */
1615
+
1616
+ declare const STOP: unique symbol;
1617
+
1618
+ /* Excluded from this release type: stopProxy */
1619
+
1620
+ declare type StopSymbol = typeof STOP;
1621
+
1622
+ /**
1623
+ * Stop tracking and collect all dependencies.
1624
+ */
1625
+ export declare function stopTrackingProxy(tracker: TrackingProxyState, bloc: StateContainerInstance): Set<StateContainerInstance>;
1626
+
1627
+ /**
1628
+ * Function that subscribes to state changes and returns an unsubscribe function
1629
+ */
1630
+ export declare type SubscribeFunction = (callback: SubscriptionCallback) => () => void;
1631
+
520
1632
  /**
521
- * Enhanced constraint for Bloc events - must be objects with proper constructor
1633
+ * Callback function invoked when subscribed state changes
522
1634
  */
523
- export declare type BlocEventConstraint = object;
1635
+ export declare type SubscriptionCallback = () => void;
524
1636
 
525
1637
  /**
526
- * Function type for determining dependencies that trigger re-renders
527
- * Similar to React's useEffect dependency array - if any dependency changes, a re-render is triggered
528
- * @template S The state type
529
- * @template I The bloc instance type
530
- * @param currentState The current state
531
- * @param previousState The previous state (undefined on first call)
532
- * @param instance The bloc instance
533
- * @returns Array of dependencies - if any dependency changes, a re-render is triggered
1638
+ * System events emitted by StateContainer lifecycle
534
1639
  */
535
- export declare type BlocHookDependencyArrayFn<S, I = any> = (currentState: S, previousState: S | undefined, instance: I) => unknown[];
1640
+ export declare type SystemEvent = 'propsUpdated' | 'stateChanged' | 'dispose';
536
1641
 
537
- export declare type BlocInstanceId = string | number | undefined;
1642
+ /* Excluded from this release type: SystemEventHandler */
538
1643
 
539
1644
  /**
540
- * Enum representing the lifecycle states of a Bloc instance
541
- * Used for atomic state transitions to prevent race conditions
1645
+ * Payload types for each system event
1646
+ * @template S - State type
1647
+ * @template P - Props type
542
1648
  */
543
- export declare enum BlocLifecycleState {
544
- ACTIVE = "active",
545
- DISPOSAL_REQUESTED = "disposal_requested",
546
- DISPOSING = "disposing",
547
- DISPOSED = "disposed"
1649
+ export declare interface SystemEventPayloads<S, P> {
1650
+ /** Emitted when props are updated via updateProps() */
1651
+ propsUpdated: {
1652
+ props: P;
1653
+ previousProps: P | undefined;
1654
+ };
1655
+ /** Emitted when state changes via emit() or update() */
1656
+ stateChanged: {
1657
+ state: S;
1658
+ previousState: S;
1659
+ };
1660
+ /** Emitted when the instance is disposed */
1661
+ dispose: void;
548
1662
  }
549
1663
 
550
1664
  /**
551
- * Extracts the state type from either a Bloc or Cubit
552
- * @template T - The Bloc or Cubit type to extract the state from
1665
+ * Run a callback while tracking all bloc dependencies accessed.
1666
+ * Returns both the result and the set of discovered dependencies.
1667
+ *
1668
+ * @example
1669
+ * ```ts
1670
+ * const { result, dependencies } = tracked(() => {
1671
+ * const user = ensure(UserBloc);
1672
+ * return user.fullName; // getter that may access other blocs
1673
+ * });
1674
+ * // dependencies contains UserBloc + any blocs accessed in fullName getter
1675
+ * ```
553
1676
  */
554
- export declare type BlocState<T> = T extends BlocBase<infer S> ? S : never;
1677
+ export declare function tracked<T>(callback: () => T, options?: TrackedOptions): TrackedResult<T>;
555
1678
 
556
1679
  /**
557
- * Test utilities for Blac state management
1680
+ * Context for running tracked callbacks with bloc proxies.
1681
+ * Provides methods to create proxies and check for changes.
558
1682
  */
559
- export declare class BlocTest {
560
- private static originalInstance;
561
- /**
562
- * Sets up a clean test environment
563
- */
564
- static setUp(): void;
565
- /**
566
- * Tears down the test environment and restores original state
567
- */
568
- static tearDown(): void;
1683
+ export declare class TrackedContext {
1684
+ private tracker;
1685
+ private proxiedBlocs;
1686
+ private primaryBlocs;
1687
+ constructor();
569
1688
  /**
570
- * Creates a test bloc with automatic cleanup
1689
+ * Get a tracking proxy for a bloc instance.
1690
+ * The proxy will track state and getter accesses.
571
1691
  */
572
- static createBloc<T extends BlocBase<any>>(BlocClass: new (...args: any[]) => T, ...args: any[]): T;
1692
+ proxy<T extends StateContainerInstance>(bloc: T): T;
573
1693
  /**
574
- * Waits for a bloc to emit a specific state
1694
+ * Start tracking for a new callback execution.
575
1695
  */
576
- static waitForState<T extends BlocBase<S>, S>(bloc: T, predicate: (state: S) => boolean, timeout?: number): Promise<S>;
1696
+ start(): void;
577
1697
  /**
578
- * Expects a bloc to emit specific states in order
1698
+ * Stop tracking and get discovered dependencies.
1699
+ * Excludes primary blocs (those explicitly proxied via proxy()).
579
1700
  */
580
- static expectStates<T extends BlocBase<S>, S>(bloc: T, expectedStates: S[], timeout?: number): Promise<void>;
581
- }
582
-
583
- export declare interface ConsumerInfo {
584
- id: string;
585
- lastNotified: number;
586
- hasRendered: boolean;
587
- stateAccesses: Set<string>;
588
- classAccesses: Set<string>;
589
- stateValues: Map<string, TrackedValue>;
590
- classValues: Map<string, TrackedValue>;
591
- accessCount: number;
592
- lastAccessTime: number;
593
- firstAccessTime: number;
594
- }
595
-
596
- /**
597
- * ConsumerTracker manages both consumer registration and dependency tracking.
598
- * It uses a WeakMap for automatic garbage collection when consumers are no longer referenced.
599
- */
600
- export declare class ConsumerTracker {
601
- private consumers;
602
- private registrationCount;
603
- private activeConsumers;
604
- register(consumerRef: object, consumerId: string): void;
605
- unregister(consumerRef: object): void;
606
- trackAccess(consumerRef: object, type: 'state' | 'class', path: string, value?: any): void;
607
- resetTracking(consumerRef: object): void;
608
- getDependencies(consumerRef: object): DependencyArray | null;
609
- hasValuesChanged(consumerRef: object, newState: any, newBlocInstance: any): boolean;
610
- shouldNotifyConsumer(consumerRef: object, changedPaths: Set<string>): boolean;
611
- updateLastNotified(consumerRef: object): void;
612
- getConsumerInfo(consumerRef: object): ConsumerInfo | undefined;
613
- setHasRendered(consumerRef: object, hasRendered: boolean): void;
614
- hasConsumer(consumerRef: object): boolean;
615
- getStats(): {
616
- totalRegistrations: number;
617
- activeConsumers: number;
618
- };
619
- private getValueAtPath;
620
- }
621
-
622
- declare interface ConsumerTracker_2 {
623
- trackAccess: (consumerRef: object, type: 'state' | 'class', path: string, value?: any) => void;
624
- }
625
-
626
- /**
627
- * A Cubit is a simpler version of a Bloc that doesn't handle events.
628
- * It manages state and provides methods to update it.
629
- * @template S - The type of state this Cubit manages
630
- * @template P - The type of parameters (optional, defaults to null)
631
- */
632
- export declare abstract class Cubit<S, P = null> extends BlocBase<S, P> {
633
- /* Excluded from this release type: _updateProps */
1701
+ stop(): Set<StateContainerInstance>;
634
1702
  /**
635
- * Optional override for props handling
1703
+ * Check if any tracked state or getters have changed.
636
1704
  */
637
- protected onPropsChanged?(oldProps: P | undefined, newProps: P): void;
1705
+ changed(): boolean;
638
1706
  /**
639
- * Updates the current state and notifies all observers of the change.
640
- * If the new state is identical to the current state (using Object.is),
641
- * no update will occur.
642
- * @param state - The new state to set
1707
+ * Get all primary blocs (those explicitly proxied).
643
1708
  */
644
- emit(state: S): void;
1709
+ getPrimaryBlocs(): Set<StateContainerInstance>;
645
1710
  /**
646
- * Partially updates the current state by merging it with the provided state patch.
647
- * This method is only applicable when the state is an object type.
648
- *
649
- * @param statePatch - A partial state object containing only the properties to update
650
- * @param ignoreChangeCheck - If true, skips checking if the state has actually changed
651
- * @throws {TypeError} If the state is not an object type
1711
+ * Reset the context for reuse.
652
1712
  */
653
- patch(statePatch: S extends object ? Partial<S> : S, ignoreChangeCheck?: boolean): void;
654
- }
655
-
656
- export declare interface DependencyArray {
657
- statePaths: string[];
658
- classPaths: string[];
1713
+ reset(): void;
659
1714
  }
660
1715
 
661
- declare type DependencySelector<S> = (currentState: S, previousState: S | undefined, instance: any) => unknown[];
662
-
663
1716
  /**
664
- * Cross-platform UUID v4 generator that works in all environments including React Native/Hermes
665
- * Falls back to crypto.randomUUID() when available, otherwise uses Math.random()
1717
+ * Options for the tracked() function.
666
1718
  */
667
- /**
668
- * Generates a UUID v4 string compatible with all JavaScript environments
669
- * @returns A UUID v4 string in the format xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
670
- */
671
- export declare function generateUUID(): string;
672
-
673
- export declare interface GetBlocOptions<B extends BlocBase<unknown>> {
674
- id?: string;
675
- selector?: BlocHookDependencyArrayFn<BlocState<B>>;
676
- props?: InferPropsFromGeneric<B>;
677
- onMount?: (bloc: B) => void;
678
- instanceRef?: string;
679
- throwIfNotFound?: boolean;
680
- /** Force creation of a new instance for isolated blocs, bypassing instance lookup */
681
- forceNewInstance?: boolean;
1719
+ export declare interface TrackedOptions {
1720
+ exclude?: StateContainerInstance;
682
1721
  }
683
1722
 
684
1723
  /**
685
- * Extracts the props type from either a Bloc or Cubit
686
- * @template T - The Bloc or Cubit type to extract the props from
1724
+ * Result of running a tracked callback.
687
1725
  */
688
- export declare type InferPropsFromGeneric<T> = T extends Bloc<any, any, infer P> ? P : T extends Cubit<any, infer P> ? P : never;
1726
+ export declare interface TrackedResult<T> {
1727
+ result: T;
1728
+ dependencies: Set<StateContainerInstance>;
1729
+ }
689
1730
 
690
1731
  /**
691
- * Memory leak detector for tests
1732
+ * State for tracking both state property access and getter access.
692
1733
  */
693
- export declare class MemoryLeakDetector {
694
- private initialStats;
695
- constructor();
696
- /**
697
- * Check for memory leaks and return a report
698
- */
699
- checkForLeaks(): {
700
- hasLeaks: boolean;
701
- report: string;
702
- stats: ReturnType<typeof Blac.getMemoryStats>;
703
- };
1734
+ export declare interface TrackingProxyState {
1735
+ dependencyState: DependencyState<any>;
1736
+ getterState: GetterState;
1737
+ dependencies: Set<StateContainerInstance>;
1738
+ isTracking: boolean;
704
1739
  }
705
1740
 
706
1741
  /**
707
- * Mock Bloc for testing
1742
+ * Event-driven state container using discriminated union events.
1743
+ * Extends StateContainer with event-based state transitions and
1744
+ * compile-time exhaustive checking for event handlers.
1745
+ *
1746
+ * @template S - State type (must be an object)
1747
+ * @template E - Event union type (discriminated by 'type' property)
1748
+ * @template P - Props type (optional)
1749
+ *
1750
+ * @example
1751
+ * ```typescript
1752
+ * type CounterEvent =
1753
+ * | { type: 'increment'; amount: number }
1754
+ * | { type: 'decrement' }
1755
+ * | { type: 'reset' };
1756
+ *
1757
+ * class CounterVertex extends Vertex<{ count: number }, CounterEvent> {
1758
+ * constructor() {
1759
+ * super({ count: 0 });
1760
+ * this.createHandlers({
1761
+ * increment: (event, emit) => {
1762
+ * emit({ count: this.state.count + event.amount });
1763
+ * },
1764
+ * decrement: (_, emit) => {
1765
+ * emit({ count: this.state.count - 1 });
1766
+ * },
1767
+ * reset: (_, emit) => {
1768
+ * emit({ count: 0 });
1769
+ * },
1770
+ * });
1771
+ * }
1772
+ *
1773
+ * increment = (amount = 1) => this.add({ type: 'increment', amount });
1774
+ * }
1775
+ * ```
708
1776
  */
709
- export declare class MockBloc<S, A extends BlocEventConstraint = BlocEventConstraint> extends Bloc<S, A> {
710
- private mockHandlers;
1777
+ export declare abstract class Vertex<S extends object = object, E extends DiscriminatedEvent = DiscriminatedEvent, P = undefined> extends StateContainer<S, P> {
1778
+ /* Excluded from this release type: handlers */
1779
+ /* Excluded from this release type: isProcessing */
1780
+ /* Excluded from this release type: eventQueue */
711
1781
  constructor(initialState: S);
712
1782
  /**
713
- * Mock an event handler for testing
1783
+ * Register all event handlers with exhaustive type checking.
1784
+ * TypeScript will error if any event type from the union is missing.
1785
+ *
1786
+ * @param handlers - Map of event type to handler function
714
1787
  */
715
- mockEventHandler<E extends A>(eventConstructor: new (...args: any[]) => E, handler: (event: E, emit: (newState: S) => void) => void | Promise<void>): void;
1788
+ protected createHandlers(handlers: EventHandlerMap<E, S>): void;
716
1789
  /**
717
- * Get the number of registered handlers
1790
+ * Dispatch an event for processing.
1791
+ * Events are processed synchronously; if called during processing,
1792
+ * the event is queued and processed after the current event completes.
1793
+ *
1794
+ * @param event - The event to process (must match the event union type)
718
1795
  */
719
- getHandlerCount(): number;
1796
+ add: (event: E) => void;
1797
+ /* Excluded from this release type: enrichEvent */
1798
+ /* Excluded from this release type: processEvent */
1799
+ /* Excluded from this release type: handleEvent */
720
1800
  /**
721
- * Check if a handler is registered for an event type
1801
+ * Called when an error occurs during event processing.
1802
+ * Override to implement custom error handling.
1803
+ *
1804
+ * @param _event - The event that caused the error
1805
+ * @param _error - The error that occurred
722
1806
  */
723
- hasHandler(eventConstructor: new (...args: any[]) => A): boolean;
1807
+ protected onEventError(_event: EventWithMetadata<E>, _error: Error): void;
724
1808
  }
725
1809
 
1810
+ /* Excluded from this release type: VertexEventHandler */
1811
+
726
1812
  /**
727
- * Mock Cubit for testing
1813
+ * Wait until a condition is met on a bloc instance.
1814
+ * Returns the bloc instance when the predicate returns true.
1815
+ * Automatically tracks dependencies accessed in the predicate.
1816
+ *
1817
+ * @example
1818
+ * ```ts
1819
+ * // Wait for bloc state to be ready
1820
+ * const userBloc = await waitUntil(UserBloc, (bloc) => bloc.state.isAuthenticated);
1821
+ *
1822
+ * // Wait using a getter
1823
+ * const userBloc = await waitUntil(UserBloc, (bloc) => bloc.isReady);
1824
+ * ```
728
1825
  */
729
- export declare class MockCubit<S> extends Cubit<S> {
730
- private stateHistory;
731
- constructor(initialState: S);
732
- /**
733
- * Override emit to track state history
734
- */
735
- emit(newState: S): void;
736
- /**
737
- * Get the history of all states
738
- */
739
- getStateHistory(): S[];
740
- /**
741
- * Clear state history
742
- */
743
- clearStateHistory(): void;
744
- }
745
-
746
- export declare class PropsUpdated<P = any> {
747
- readonly props: P;
748
- constructor(props: P);
749
- }
750
-
751
- export declare class ProxyFactory {
752
- static createStateProxy<T extends object>(options: {
753
- target: T;
754
- consumerRef: object;
755
- consumerTracker: ConsumerTracker_2;
756
- path?: string;
757
- }): T;
758
- static createClassProxy<T extends object>(options: {
759
- target: T;
760
- consumerRef: object;
761
- consumerTracker: ConsumerTracker_2;
762
- }): T;
763
- static getProxyState<B extends BlocBase<any>>(options: {
764
- state: BlocState<B>;
765
- consumerRef: object;
766
- consumerTracker: ConsumerTracker_2;
767
- }): BlocState<B>;
768
- static getProxyBlocInstance<B extends BlocBase<any>>(options: {
769
- blocInstance: B;
770
- consumerRef: object;
771
- consumerTracker: ConsumerTracker_2;
772
- }): B;
773
- static getStats(): {
774
- totalProxies: number;
775
- cacheEfficiency: string;
776
- lifetime: string;
777
- proxiesPerSecond: string;
778
- stateProxiesCreated: number;
779
- classProxiesCreated: number;
780
- cacheHits: number;
781
- cacheMisses: number;
782
- propertyAccesses: number;
783
- nestedProxiesCreated: number;
784
- totalProxiesCreated: number;
785
- createdAt: number;
786
- };
787
- static resetStats(): void;
788
- }
1826
+ export declare function waitUntil<T extends StateContainerConstructor>(BlocClass: T, predicate: (bloc: InstanceType<T>) => boolean, options?: WaitUntilOptions): Promise<InstanceType<T>>;
789
1827
 
790
1828
  /**
791
- * Sets a custom instance manager (useful for testing or advanced patterns)
1829
+ * Wait until a condition is met on a selected value from a bloc.
1830
+ * Returns the selected value when the predicate returns true.
1831
+ * Automatically tracks dependencies accessed in selector and predicate.
1832
+ *
1833
+ * @example
1834
+ * ```ts
1835
+ * // Wait for layout to be set and get it directly
1836
+ * const layout = await waitUntil(
1837
+ * LayoutBloc,
1838
+ * (bloc) => bloc.state.currentLayout,
1839
+ * (layout) => layout !== null
1840
+ * );
1841
+ *
1842
+ * // Using a getter as selector
1843
+ * const user = await waitUntil(
1844
+ * UserBloc,
1845
+ * (bloc) => bloc.currentUser,
1846
+ * (user) => user !== null
1847
+ * );
1848
+ * ```
792
1849
  */
793
- export declare function setBlacInstanceManager(manager: BlacInstanceManager): void;
1850
+ export declare function waitUntil<T extends StateContainerConstructor, TSelected>(BlocClass: T, selector: (bloc: InstanceType<T>) => TSelected, predicate: (selected: TSelected) => boolean, options?: WaitUntilOptions): Promise<TSelected>;
1851
+
1852
+ export declare class WaitUntilAbortedError extends Error {
1853
+ constructor();
1854
+ }
1855
+
1856
+ export declare class WaitUntilDisposedError extends Error {
1857
+ constructor(blocName: string);
1858
+ }
1859
+
1860
+ export declare interface WaitUntilOptions {
1861
+ instanceId?: string;
1862
+ timeout?: number;
1863
+ signal?: AbortSignal;
1864
+ }
1865
+
1866
+ export declare class WaitUntilTimeoutError extends Error {
1867
+ constructor(timeout: number);
1868
+ }
794
1869
 
795
1870
  /**
796
- * Performs a shallow equality comparison between two values.
797
- * For objects, it checks if all top-level properties are equal using Object.is.
798
- * @param a First value to compare
799
- * @param b Second value to compare
800
- * @returns true if values are shallowly equal, false otherwise
1871
+ * Log a warning message (tree-shakeable export)
1872
+ * @param context - Context identifier (module or component name)
1873
+ * @param message - Log message
1874
+ * @param data - Optional structured data
801
1875
  */
802
- export declare function shallowEqual(a: any, b: any): boolean;
1876
+ export declare const warn: (context: string, message: string, data?: any) => void;
1877
+
1878
+ export declare const watch: WatchFn;
803
1879
 
804
1880
  /**
805
- * Result of an atomic state transition operation
1881
+ * Combined watch function type.
806
1882
  */
807
- export declare interface StateTransitionResult {
808
- success: boolean;
809
- currentState: BlocLifecycleState;
810
- previousState: BlocLifecycleState;
811
- }
812
-
813
- export declare interface TrackedValue {
814
- value: any;
815
- lastAccessTime: number;
1883
+ export declare interface WatchFn extends WatchSingleFn {
1884
+ <T extends readonly BlocInput[]>(blocs: T, callback: (blocs: ExtractInstances<T>) => void | StopSymbol): () => void;
816
1885
  }
817
1886
 
818
1887
  /**
819
- * Extracts the state type from a BlocBase instance
820
- * @template B - The BlocBase type to extract the state from
1888
+ * Watch function signature for single bloc.
821
1889
  */
822
- export declare type ValueType<B extends BlocBase<any>> = B extends BlocBase<infer U> ? U : never;
1890
+ declare interface WatchSingleFn {
1891
+ <T extends StateContainerConstructor>(bloc: T | BlocRef<T>, callback: (bloc: InstanceType<T>) => void | StopSymbol): () => void;
1892
+ STOP: StopSymbol;
1893
+ }
823
1894
 
824
1895
  export { }