@blac/core 2.0.0 → 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,505 +1,1895 @@
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
+
1
800
  /**
2
- * Main Blac class that manages the state management system.
3
- * Implements a singleton pattern to ensure only one instance exists.
4
- * Handles bloc lifecycle, plugin management, and instance tracking.
5
- *
6
- * Key responsibilities:
7
- * - Managing bloc instances (creation, disposal, lookup)
8
- * - Handling isolated and non-isolated blocs
9
- * - Managing plugins and lifecycle events
10
- * - Providing logging and debugging capabilities
801
+ * Metadata information about a state container instance for debugging and inspection
11
802
  */
12
- export declare class Blac {
13
- /** The singleton instance of Blac */
14
- static instance: Blac;
15
- /** Timestamp when the instance was created */
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) */
16
817
  createdAt: number;
17
- static getAllBlocs: <B extends BlocConstructor<unknown>>(blocClass: B, options?: {
18
- searchIsolated?: boolean;
19
- }) => InstanceType<B>[];
20
- static addPlugin: (plugin: BlacPlugin) => void;
21
- /** Map storing all registered bloc instances by their class name and ID */
22
- blocInstanceMap: Map<string, BlocBase<any>>;
23
- /** Map storing isolated bloc instances grouped by their constructor */
24
- isolatedBlocMap: Map<BlocConstructor<any>, BlocBase<any>[]>;
25
- pluginList: BlacPlugin[];
26
- /** Flag to control whether changes should be posted to document */
27
- postChangesToDocument: boolean;
28
- /**
29
- * Creates a new Blac instance.
30
- * @param options - Configuration options including singleton control
31
- */
32
- constructor(options?: {
33
- __unsafe_ignore_singleton?: boolean;
34
- });
35
- /** Flag to enable/disable logging */
36
- static enableLog: boolean;
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;
915
+ }
916
+
917
+ /**
918
+ * Structure of a log entry passed to output handlers
919
+ */
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 {
37
1026
  /**
38
- * Logs messages to console when logging is enabled
39
- * @param args - Arguments to log
1027
+ * Get metadata for a specific instance
40
1028
  */
41
- log: (...args: unknown[]) => void;
42
- static log: (...args: unknown[]) => void;
1029
+ getInstanceMetadata(instance: StateContainer<any>): InstanceMetadata;
43
1030
  /**
44
- * Gets the singleton instance of Blac
45
- * @returns The Blac instance
1031
+ * Get current state from a container
46
1032
  */
47
- static getInstance(): Blac;
1033
+ getState<S extends object = any>(instance: StateContainer<S>): S;
48
1034
  /**
49
- * Logs a warning message
50
- * @param message - Warning message
51
- * @param args - Additional arguments
1035
+ * Get all instances of a specific type
52
1036
  */
53
- warn: (message: string, ...args: unknown[]) => void;
54
- static warn: (message: string, ...args: unknown[]) => void;
1037
+ queryInstances<T extends StateContainer<any>>(typeClass: new (...args: any[]) => T): T[];
55
1038
  /**
56
- * Logs an error message
57
- * @param message - Error message
58
- * @param args - Additional arguments
1039
+ * Get all registered state container types
59
1040
  */
60
- error: (message: string, ...args: unknown[]) => void;
61
- static error: (message: string, ...args: unknown[]) => void;
1041
+ getAllTypes(): Array<new (...args: any[]) => StateContainer<any>>;
62
1042
  /**
63
- * Resets the Blac instance to a new one, disposing non-keepAlive blocs
64
- * from the old instance.
1043
+ * Get registry statistics
65
1044
  */
66
- resetInstance: () => void;
67
- static resetInstance: () => 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;
68
1065
  /**
69
- * Adds a plugin to the Blac instance
70
- * @param plugin - The plugin to add
1066
+ * Create a new PluginManager
1067
+ * @param registry - The StateContainerRegistry to monitor for lifecycle events
71
1068
  */
72
- addPlugin: (plugin: BlacPlugin) => void;
1069
+ constructor(registry: StateContainerRegistry);
73
1070
  /**
74
- * Dispatches a lifecycle event to all registered plugins
75
- * @param event - The lifecycle event to dispatch
76
- * @param bloc - The bloc instance involved in the event
77
- * @param params - Additional parameters for the event
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
78
1075
  */
79
- dispatchEventToPlugins: (event: BlacLifecycleEvent, bloc: BlocBase<any>, params?: unknown) => void;
1076
+ install(plugin: BlacPlugin, config?: PluginConfig): void;
80
1077
  /**
81
- * Dispatches a lifecycle event and handles related cleanup actions.
82
- * This method is responsible for:
83
- * - Logging the event
84
- * - Handling bloc disposal when needed
85
- * - Managing bloc consumer cleanup
86
- * - Forwarding the event to plugins
87
- *
88
- * @param event - The lifecycle event to dispatch
89
- * @param bloc - The bloc instance involved in the event
90
- * @param params - Additional parameters for the event
1078
+ * Uninstall a plugin by name
1079
+ * @param pluginName - The name of the plugin to uninstall
1080
+ * @throws Error if plugin is not installed
91
1081
  */
92
- dispatchEvent: (event: BlacLifecycleEvent, bloc: BlocBase<any>, params?: unknown) => void;
1082
+ uninstall(pluginName: string): void;
93
1083
  /**
94
- * Disposes of a bloc instance by removing it from the appropriate registry
95
- * @param bloc - The bloc instance to dispose
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
96
1087
  */
97
- disposeBloc: (bloc: BlocBase<any>) => void;
1088
+ getPlugin(pluginName: string): BlacPlugin | undefined;
98
1089
  /**
99
- * Creates a unique key for a bloc instance in the map based on the bloc class name and instance ID
100
- * @param blocClassName - The name of the bloc class
101
- * @param id - The instance ID
102
- * @returns A unique key string in the format "className:id"
1090
+ * Get all installed plugins
1091
+ * @returns Array of all installed plugins
103
1092
  */
104
- createBlocInstanceMapKey(blocClassName: string, id: BlocInstanceId): string;
1093
+ getAllPlugins(): BlacPlugin[];
105
1094
  /**
106
- * Unregister a bloc instance from the main registry
107
- * @param bloc - The bloc instance to unregister
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
108
1098
  */
109
- unregisterBlocInstance(bloc: BlocBase<any>): void;
1099
+ hasPlugin(pluginName: string): boolean;
110
1100
  /**
111
- * Registers a bloc instance in the main registry
112
- * @param bloc - The bloc instance to register
1101
+ * Uninstall all plugins
113
1102
  */
114
- registerBlocInstance(bloc: BlocBase<any>): void;
1103
+ clear(): void;
115
1104
  /**
116
- * Finds a registered bloc instance by its class and ID
117
- * @param blocClass - The bloc class to search for
118
- * @param id - The instance ID
119
- * @returns The found bloc instance or undefined if not found
1105
+ * Setup lifecycle hooks to notify plugins
120
1106
  */
121
- findRegisteredBlocInstance<B extends BlocConstructor<unknown>>(blocClass: B, id: BlocInstanceId): InstanceType<B> | undefined;
1107
+ private setupLifecycleHooks;
122
1108
  /**
123
- * Registers an isolated bloc instance in the isolated registry
124
- * @param bloc - The isolated bloc instance to register
1109
+ * Notify all plugins of a lifecycle event
125
1110
  */
126
- registerIsolatedBlocInstance(bloc: BlocBase<any>): void;
1111
+ private notifyPlugins;
127
1112
  /**
128
- * Unregister an isolated bloc instance from the isolated registry
129
- * @param bloc - The isolated bloc instance to unregister
1113
+ * Create plugin context with safe API access
130
1114
  */
131
- unregisterIsolatedBlocInstance(bloc: BlocBase<any>): void;
1115
+ private createPluginContext;
132
1116
  /**
133
- * Finds an isolated bloc instance by its class and ID
1117
+ * Check if plugin should be enabled based on environment
134
1118
  */
135
- findIsolatedBlocInstance<B extends BlocConstructor<unknown>>(blocClass: B, id: BlocInstanceId): InstanceType<B> | undefined;
1119
+ private shouldEnablePlugin;
136
1120
  /**
137
- * Creates a new bloc instance and registers it in the appropriate registry
138
- * @param blocClass - The bloc class to instantiate
139
- * @param id - The instance ID
140
- * @param props - Properties to pass to the bloc constructor
141
- * @param instanceRef - Optional reference string for the instance
142
- * @returns The newly created bloc instance
1121
+ * Get current environment
143
1122
  */
144
- createNewBlocInstance<B extends BlocConstructor<BlocBase<any>>>(blocClass: B, id: BlocInstanceId, options?: GetBlocOptions<InstanceType<B>>): InstanceType<B>;
145
- /**
146
- * Gets or creates a bloc instance based on the provided class and options.
147
- * If a bloc with the given ID exists, it will be returned. Otherwise, a new instance will be created.
148
- *
149
- * @param blocClass - The bloc class to get or create
150
- * @param options - Options including:
151
- * - id: The instance ID (defaults to class name if not provided)
152
- * - props: Properties to pass to the bloc constructor
153
- * - instanceRef: Optional reference string for the instance
154
- * @returns The bloc instance
155
- */
156
- getBloc: <B extends BlocConstructor<BlocBase<any>>>(blocClass: B, options?: GetBlocOptions<InstanceType<B>>) => InstanceType<B>;
157
- static getBloc: <B extends BlocConstructor<BlocBase<any>>>(blocClass: B, options?: GetBlocOptions<InstanceType<B>>) => InstanceType<B>;
158
- /**
159
- * Gets a bloc instance or throws an error if it doesn't exist
160
- * @param blocClass - The bloc class to get
161
- * @param options - Options including:
162
- * - id: The instance ID (defaults to class name if not provided)
163
- * - props: Properties to pass to the bloc constructor
164
- * - instanceRef: Optional reference string for the instance
165
- */
166
- getBlocOrThrow: <B extends BlocConstructor<unknown>>(blocClass: B, options?: {
167
- id?: BlocInstanceId;
168
- props?: InferPropsFromGeneric<B>;
169
- instanceRef?: string;
170
- }) => InstanceType<B>;
171
- static getBlocOrThrow: <B extends BlocConstructor<unknown>>(blocClass: B, options?: {
172
- id?: BlocInstanceId;
173
- props?: InferPropsFromGeneric<B> | undefined;
174
- instanceRef?: string;
175
- }) => InstanceType<B>;
176
- /**
177
- * Gets all instances of a specific bloc class
178
- * @param blocClass - The bloc class to search for
179
- * @param options - Options including:
180
- * - searchIsolated: Whether to search in isolated blocs (defaults to bloc's isolated property)
181
- * @returns Array of matching bloc instances
182
- */
183
- getAllBlocs: <B extends BlocConstructor<unknown>>(blocClass: B, options?: {
184
- searchIsolated?: boolean;
185
- }) => InstanceType<B>[];
186
- }
187
-
188
- declare type BlacAddon = {
189
- name: string;
190
- onInit?: BlacAddonInit;
191
- onEmit?: BlacAddonEmit;
192
- };
1123
+ private getCurrentEnvironment;
1124
+ }
1125
+
1126
+ /* Excluded from this release type: ProxyState */
1127
+
1128
+ export declare function register<T extends StateContainerConstructor>(BlocClass: T, isolated?: boolean): void;
193
1129
 
194
- declare type BlacAddonEmit = (params: {
195
- oldState: unknown;
196
- newState: unknown;
197
- cubit: BlocBase<any>;
198
- }) => void;
1130
+ export declare function release<T extends StateContainerConstructor>(BlocClass: T, instanceKey?: string, forceDispose?: boolean): void;
199
1131
 
200
- declare type BlacAddonInit = (bloc: BlocBase<any>) => void;
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 */
201
1141
 
202
1142
  /**
203
- * Configuration options for the Blac instance
1143
+ * Function that returns a snapshot of the current state
1144
+ * @template TState - The state type
204
1145
  */
205
- export declare interface BlacConfig {
206
- /** Whether to expose the Blac instance globally */
207
- exposeBlacInstance?: boolean;
208
- }
1146
+ export declare type SnapshotFunction<TState> = () => TState;
1147
+
1148
+ /* Excluded from this release type: startDependency */
1149
+
1150
+ /* Excluded from this release type: startProxy */
209
1151
 
210
1152
  /**
211
- * Enum representing different lifecycle events that can occur in the Blac system.
212
- * These events are used to track the lifecycle of blocs and their consumers.
1153
+ * Start tracking on a tracking proxy.
213
1154
  */
214
- export declare enum BlacLifecycleEvent {
215
- BLOC_DISPOSED = "BLOC_DISPOSED",
216
- BLOC_CREATED = "BLOC_CREATED",
217
- LISTENER_REMOVED = "LISTENER_REMOVED",
218
- LISTENER_ADDED = "LISTENER_ADDED",
219
- STATE_CHANGED = "STATE_CHANGED",
220
- BLOC_CONSUMER_REMOVED = "BLOC_CONSUMER_REMOVED",
221
- BLOC_CONSUMER_ADDED = "BLOC_CONSUMER_ADDED"
222
- }
1155
+ export declare function startTrackingProxy(tracker: TrackingProxyState): void;
223
1156
 
224
1157
  /**
225
- * A class that manages observers for a Bloc's state changes
226
- * @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
+ * ```
227
1176
  */
228
- export declare class BlacObservable<S = unknown> {
229
- /** The Bloc instance this observable is associated with */
230
- 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);
231
1197
  /**
232
- * Creates a new BlacObservable instance
233
- * @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
234
1201
  */
235
- constructor(bloc: BlocBase<S>);
236
- 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;
237
1207
  /**
238
- * Gets the number of active observers
239
- * @returns The number of observers currently subscribed
1208
+ * Subscribe to state changes
1209
+ * @param listener - Function called when state changes
1210
+ * @returns Unsubscribe function
240
1211
  */
241
- get size(): number;
1212
+ subscribe(listener: StateListener<S>): () => void;
242
1213
  /**
243
- * Gets the set of all observers
244
- * @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.
245
1216
  */
246
- get observers(): Set<BlacObserver<S>>;
1217
+ dispose(): void;
247
1218
  /**
248
- * Subscribes an observer to state changes
249
- * @param observer - The observer to subscribe
250
- * @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
251
1222
  */
252
- 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;
253
1229
  /**
254
- * Unsubscribes an observer from state changes
255
- * @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
256
1233
  */
257
- unsubscribe(observer: BlacObserver<S>): void;
1234
+ protected update(updater: (current: S) => S): void;
258
1235
  /**
259
- * Notifies all observers of a state change
260
- * @param newState - The new state value
261
- * @param oldState - The previous state value
262
- * @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
263
1241
  */
264
- 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;
265
1244
  /**
266
- * Disposes of all observers and clears the observer set
1245
+ * Update the props for this container.
1246
+ * Emits the 'propsUpdated' system event.
1247
+ * @param newProps - The new props value
267
1248
  */
268
- dispose(): void;
1249
+ updateProps(newProps: P): void;
269
1250
  }
270
1251
 
271
1252
  /**
272
- * Represents an observer that can subscribe to state changes in a Bloc
273
- * @template S - The type of state being observed
1253
+ * Configuration options for initializing a StateContainer instance
274
1254
  */
275
- export declare type BlacObserver<S> = {
276
- /** Function to be called when state changes */
277
- fn: (newState: S, oldState: S, action?: unknown) => void | Promise<void>;
278
- /** Optional function to determine if the observer should be notified of state changes */
279
- dependencyArray?: BlocHookDependencyArrayFn<S>;
280
- /** Dispose function for the observer */
281
- dispose?: () => void;
282
- /** Cached state values used for dependency comparison */
283
- lastState?: unknown[][];
284
- /** Unique identifier for the observer */
285
- id: string;
286
- };
287
-
288
- export declare interface BlacPlugin {
289
- name: string;
290
- onEvent(event: BlacLifecycleEvent, bloc: BlocBase<any>, params?: unknown): void;
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;
291
1262
  }
292
1263
 
293
- export declare abstract class Bloc<S, // State type
294
- A extends object, // Base Action/Event type, constrained to object
295
- P = unknown> extends BlocBase<S, P> {
296
- readonly eventHandlers: Map<new (...args: any[]) => A, (event: A, emit: (newState: S) => void) => void | Promise<void>>;
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>;
1273
+ };
1274
+
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;
1294
+ /**
1295
+ * Register a type for lifecycle event tracking
1296
+ * @param constructor - The StateContainer class constructor
1297
+ */
1298
+ registerType<T extends StateContainerConstructor>(constructor: T): void;
1299
+ /**
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
1304
+ */
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>;
1340
+ /**
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
1346
+ */
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>;
1366
+ /**
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
1372
+ */
1373
+ release<T extends StateContainerConstructor>(Type: T, instanceKey?: string, forceDispose?: boolean): void;
297
1374
  /**
298
- * Registers an event handler for a specific event type.
299
- * This method is typically called in the constructor of a derived Bloc class.
300
- * @param eventConstructor The constructor of the event to handle (e.g., LoadDataEvent).
301
- * @param handler A function that processes the event and can emit new states.
302
- * The 'event' parameter in the handler will be typed to the specific eventConstructor.
1375
+ * Get all instances of a specific type.
1376
+ * @param Type - The StateContainer class constructor
1377
+ * @returns Array of all instances
303
1378
  */
304
- protected on<E extends A>(eventConstructor: new (...args: any[]) => E, handler: (event: E, emit: (newState: S) => void) => void | Promise<void>): void;
1379
+ getAll<T extends StateContainerConstructor>(Type: T): InstanceReadonlyState<T>[];
305
1380
  /**
306
- * Dispatches an action/event to the Bloc.
307
- * If a handler is registered for this specific event type (via 'on'), it will be invoked.
308
- * Asynchronous handlers are awaited.
309
- * @param action The action/event instance to be processed.
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
310
1385
  */
311
- add: (action: A) => Promise<void>;
1386
+ forEach<T extends StateContainerConstructor>(Type: T, callback: (instance: InstanceReadonlyState<T>) => void): void;
1387
+ /**
1388
+ * Clear all instances of a specific type (disposes them).
1389
+ * @param Type - The StateContainer class constructor
1390
+ */
1391
+ clear<T extends StateContainerConstructor>(Type: T): void;
1392
+ /**
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)
1397
+ */
1398
+ getRefCount<T extends StateContainerConstructor>(Type: T, instanceKey?: string): number;
1399
+ /**
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)
1408
+ *
1409
+ * Iterates all registered types and clears their instances.
1410
+ * Also clears type tracking to reset the registry state.
1411
+ */
1412
+ clearAll(): void;
1413
+ /**
1414
+ * Get registry statistics for debugging.
1415
+ * @returns Object with registeredTypes, totalInstances, and typeBreakdown
1416
+ */
1417
+ getStats(): {
1418
+ registeredTypes: number;
1419
+ totalInstances: number;
1420
+ typeBreakdown: Record<string, number>;
1421
+ };
1422
+ /**
1423
+ * Get all registered types (for plugin system).
1424
+ * @returns Array of all registered StateContainer class constructors
1425
+ */
1426
+ getTypes(): StateContainerConstructor[];
1427
+ /**
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
1432
+ */
1433
+ on<E extends LifecycleEvent>(event: E, listener: LifecycleListener<E>): () => void;
1434
+ /* Excluded from this release type: emit */
312
1435
  }
313
1436
 
314
1437
  /**
315
- * Base class for both Blocs and Cubits that provides core state management functionality.
316
- * Handles state transitions, observer notifications, lifecycle management, and addon integration.
1438
+ * Constrain a type to only accept stateful containers (not StatelessCubit/StatelessVertex).
1439
+ * Use this to reject stateless containers at the type level.
1440
+ */
1441
+ export declare type StatefulContainerOnly<T extends StateContainerConstructor> = IsStatelessContainer<T> extends true ? never : T;
1442
+
1443
+ /**
1444
+ * Marker symbol to identify stateless containers at the type level.
1445
+ * Used by React hooks to prevent `useBloc` from accepting stateless containers.
1446
+ */
1447
+ export declare const STATELESS_MARKER: unique symbol;
1448
+
1449
+ /**
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
+ * }
317
1467
  *
318
- * @abstract This class should be extended, not instantiated directly
319
- * @template S The type of state managed by this Bloc
320
- * @template P The type of props that can be passed during instance creation (optional)
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
+ * ```
321
1477
  */
322
- export declare abstract class BlocBase<S, P = unknown> {
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;
323
1486
  /**
324
- * When true, every consumer will receive its own unique instance of this Bloc.
325
- * Use this when state should not be shared between components.
326
- * @default false
1487
+ * Subscriptions are not available on StatelessCubit.
1488
+ * @throws Always throws an error when called.
327
1489
  */
328
- static isolated: boolean;
329
- get isIsolated(): boolean;
1490
+ subscribe(_listener: (state: EmptyState) => void): never;
330
1491
  /**
331
- * When true, the Bloc instance persists even when there are no active consumers.
332
- * Useful for maintaining state between component unmount/remount cycles.
333
- * @default false
1492
+ * emit() is not available on StatelessCubit.
1493
+ * TypeScript will show an error if you try to call this method.
334
1494
  */
335
- static keepAlive: boolean;
336
- get isKeepAlive(): boolean;
1495
+ emit(_newState: never): never;
337
1496
  /**
338
- * Defines how dependencies are selected from the state for efficient updates.
339
- * When provided, observers will only be notified when selected dependencies change.
1497
+ * update() is not available on StatelessCubit.
1498
+ * TypeScript will show an error if you try to call this method.
340
1499
  */
341
- defaultDependencySelector: DependencySelector<S> | undefined;
342
- /* Excluded from this release type: _addons */
343
- /* Excluded from this release type: _isolated */
344
- /* Excluded from this release type: _observer */
345
- /* Excluded from this release type: _blac */
1500
+ update(_updater: never): never;
346
1501
  /**
347
- * The unique identifier for this Bloc instance.
348
- * Defaults to the class name, but can be customized.
1502
+ * patch() is not available on StatelessCubit.
1503
+ * @throws Error always - StatelessCubit does not support state changes
349
1504
  */
350
- _id: BlocInstanceId;
351
- /* Excluded from this release type: _instanceRef */
352
- /* Excluded from this release type: _keepAlive */
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;
1513
+
1514
+ /**
1515
+ * Map of event types to their handlers for StatelessVertex.
1516
+ * Enforces exhaustive handling of all event types in the union.
1517
+ */
1518
+ export declare type StatelessEventHandlerMap<E extends DiscriminatedEvent> = {
1519
+ [K in E['type']]: StatelessEventHandler<Extract<E, {
1520
+ type: K;
1521
+ }>>;
1522
+ };
1523
+
1524
+ /**
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
+ * ```
1564
+ */
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();
353
1571
  /**
354
- * @readonly
355
- * Timestamp when this Bloc instance was created, useful for debugging and performance tracking.
1572
+ * State is not available on StatelessVertex.
1573
+ * @throws Always throws an error when accessed.
356
1574
  */
357
- readonly _createdAt: number;
358
- /* Excluded from this release type: _state */
359
- /* Excluded from this release type: _oldState */
1575
+ get state(): never;
360
1576
  /**
361
- * Props passed during Bloc instance creation.
362
- * Can be used to configure or parameterize the Bloc's behavior.
1577
+ * Subscriptions are not available on StatelessVertex.
1578
+ * @throws Always throws an error when called.
363
1579
  */
364
- props: P | null;
1580
+ subscribe(_listener: (state: EmptyState_2) => void): never;
365
1581
  /**
366
- * Creates a new BlocBase instance with the given initial state.
367
- * Sets up the observer, registers with the Blac manager, and initializes addons.
1582
+ * Register all event handlers with exhaustive type checking.
1583
+ * TypeScript will error if any event type from the union is missing.
368
1584
  *
369
- * @param initialState The initial state value for this Bloc
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
370
1589
  */
371
- constructor(initialState: S);
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 */
372
1602
  /**
373
- * Returns the current state of the Bloc.
374
- * Use this getter to access the state in a read-only manner.
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
375
1608
  */
376
- get state(): S;
377
- /* Excluded from this release type: _name */
378
- /* Excluded from this release type: _updateId */
379
- /* Excluded from this release type: _dispose */
380
- /* Excluded from this release type: onDispose */
381
- /* Excluded from this release type: _consumers */
382
- /* Excluded from this release type: _addConsumer */
383
- /* Excluded from this release type: _removeConsumer */
384
- /* Excluded from this release type: _connectAddons */
385
- lastUpdate: number;
386
- /* Excluded from this release type: _pushState */
1609
+ protected onEventError(_event: EventWithMetadata<E>, _error: Error): void;
1610
+ /* Excluded from this release type: emit */
1611
+ /* Excluded from this release type: update */
387
1612
  }
388
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
+
389
1622
  /**
390
- * Represents the abstract base types for Bloc and Cubit
1623
+ * Stop tracking and collect all dependencies.
391
1624
  */
392
- export declare type BlocBaseAbstract = typeof Bloc<any, any, any> | typeof Cubit<any, any>;
1625
+ export declare function stopTrackingProxy(tracker: TrackingProxyState, bloc: StateContainerInstance): Set<StateContainerInstance>;
393
1626
 
394
1627
  /**
395
- * Represents a constructor type for a Bloc that takes no parameters
396
- * @template B - The type of the Bloc instance
1628
+ * Function that subscribes to state changes and returns an unsubscribe function
397
1629
  */
398
- export declare type BlocClassNoParams<B> = new (args: never[]) => B;
1630
+ export declare type SubscribeFunction = (callback: SubscriptionCallback) => () => void;
399
1631
 
400
1632
  /**
401
- * Represents a constructor type for a Bloc that can take any parameters
402
- * @template B - The type of the Bloc instance
1633
+ * Callback function invoked when subscribed state changes
403
1634
  */
404
- export declare type BlocConstructor<B> = new (...args: any) => B;
1635
+ export declare type SubscriptionCallback = () => void;
405
1636
 
406
1637
  /**
407
- * Extracts the constructor parameters type from a BlocBase
408
- * @template B - The BlocBase type to extract the constructor parameters from
1638
+ * System events emitted by StateContainer lifecycle
409
1639
  */
410
- export declare type BlocConstructorParameters<B extends BlocBase<any>> = BlocConstructor<B> extends new (...args: infer P) => B ? P : never;
1640
+ export declare type SystemEvent = 'propsUpdated' | 'stateChanged' | 'dispose';
1641
+
1642
+ /* Excluded from this release type: SystemEventHandler */
411
1643
 
412
1644
  /**
413
- * Represents a function type for determining hook dependencies based on state changes
414
- * @template B - The BlocGeneric type
1645
+ * Payload types for each system event
1646
+ * @template S - State type
1647
+ * @template P - Props type
415
1648
  */
416
- export declare type BlocHookDependencyArrayFn<S> = (newState: S, oldState: S) => unknown[][];
417
-
418
- export declare type BlocInstanceId = string | number | undefined;
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;
1662
+ }
419
1663
 
420
1664
  /**
421
- * Extracts the state type from either a Bloc or Cubit
422
- * @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
+ * ```
423
1676
  */
424
- export declare type BlocState<T> = T extends BlocBase<infer S> ? S : never;
1677
+ export declare function tracked<T>(callback: () => T, options?: TrackedOptions): TrackedResult<T>;
425
1678
 
426
1679
  /**
427
- * A Cubit is a simpler version of a Bloc that doesn't handle events.
428
- * It manages state and provides methods to update it.
429
- * @template S - The type of state this Cubit manages
430
- * @template P - The type of parameters (optional, defaults to null)
1680
+ * Context for running tracked callbacks with bloc proxies.
1681
+ * Provides methods to create proxies and check for changes.
431
1682
  */
432
- export declare abstract class Cubit<S, P = null> extends BlocBase<S, P> {
1683
+ export declare class TrackedContext {
1684
+ private tracker;
1685
+ private proxiedBlocs;
1686
+ private primaryBlocs;
1687
+ constructor();
433
1688
  /**
434
- * Updates the current state and notifies all observers of the change.
435
- * If the new state is identical to the current state (using Object.is),
436
- * no update will occur.
437
- * @param state - The new state to set
1689
+ * Get a tracking proxy for a bloc instance.
1690
+ * The proxy will track state and getter accesses.
438
1691
  */
439
- emit(state: S): void;
1692
+ proxy<T extends StateContainerInstance>(bloc: T): T;
440
1693
  /**
441
- * Partially updates the current state by merging it with the provided state patch.
442
- * This method is only applicable when the state is an object type.
443
- *
444
- * @param statePatch - A partial state object containing only the properties to update
445
- * @param ignoreChangeCheck - If true, skips checking if the state has actually changed
446
- * @throws {TypeError} If the state is not an object type
1694
+ * Start tracking for a new callback execution.
1695
+ */
1696
+ start(): void;
1697
+ /**
1698
+ * Stop tracking and get discovered dependencies.
1699
+ * Excludes primary blocs (those explicitly proxied via proxy()).
1700
+ */
1701
+ stop(): Set<StateContainerInstance>;
1702
+ /**
1703
+ * Check if any tracked state or getters have changed.
1704
+ */
1705
+ changed(): boolean;
1706
+ /**
1707
+ * Get all primary blocs (those explicitly proxied).
1708
+ */
1709
+ getPrimaryBlocs(): Set<StateContainerInstance>;
1710
+ /**
1711
+ * Reset the context for reuse.
447
1712
  */
448
- patch(statePatch: S extends object ? Partial<S> : S, ignoreChangeCheck?: boolean): void;
1713
+ reset(): void;
449
1714
  }
450
1715
 
451
- declare type DependencySelector<S> = (newState: S, oldState?: S) => unknown[][];
1716
+ /**
1717
+ * Options for the tracked() function.
1718
+ */
1719
+ export declare interface TrackedOptions {
1720
+ exclude?: StateContainerInstance;
1721
+ }
452
1722
 
453
- export declare interface GetBlocOptions<B extends BlocBase<any>> {
454
- id?: string;
455
- dependencySelector?: BlocHookDependencyArrayFn<BlocState<B>>;
456
- props?: InferPropsFromGeneric<B>;
457
- onMount?: (bloc: B) => void;
458
- instanceRef?: string;
1723
+ /**
1724
+ * Result of running a tracked callback.
1725
+ */
1726
+ export declare interface TrackedResult<T> {
1727
+ result: T;
1728
+ dependencies: Set<StateContainerInstance>;
459
1729
  }
460
1730
 
461
1731
  /**
462
- * Extracts the props type from either a Bloc or Cubit
463
- * @template T - The Bloc or Cubit type to extract the props from
1732
+ * State for tracking both state property access and getter access.
464
1733
  */
465
- export declare type InferPropsFromGeneric<T> = T extends Bloc<any, any, infer P> ? P : T extends Cubit<any, infer P> ? P : never;
1734
+ export declare interface TrackingProxyState {
1735
+ dependencyState: DependencyState<any>;
1736
+ getterState: GetterState;
1737
+ dependencies: Set<StateContainerInstance>;
1738
+ isTracking: boolean;
1739
+ }
466
1740
 
467
1741
  /**
468
- * Persist addon
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
+ * }
469
1772
  *
470
- * @param options
471
- * @returns BlacAddon
1773
+ * increment = (amount = 1) => this.add({ type: 'increment', amount });
1774
+ * }
1775
+ * ```
472
1776
  */
473
- export declare function Persist(options?: {
474
- /**
475
- * @default 'blac'
476
- */
477
- keyPrefix?: string;
478
- /**
479
- * @default the bloc's id
480
- */
481
- keyName?: string;
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 */
1781
+ constructor(initialState: S);
482
1782
  /**
483
- * Used when the value is not found in storage
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
484
1787
  */
485
- defaultValue?: unknown;
1788
+ protected createHandlers(handlers: EventHandlerMap<E, S>): void;
486
1789
  /**
487
- * @default 'localStorage'
488
- * @see StorageType
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)
489
1795
  */
490
- storageType?: StorageType;
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 */
491
1800
  /**
492
- * @default false
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
493
1806
  */
494
- onError?: (e: unknown) => void;
495
- }): BlacAddon;
1807
+ protected onEventError(_event: EventWithMetadata<E>, _error: Error): void;
1808
+ }
1809
+
1810
+ /* Excluded from this release type: VertexEventHandler */
1811
+
1812
+ /**
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
+ * ```
1825
+ */
1826
+ export declare function waitUntil<T extends StateContainerConstructor>(BlocClass: T, predicate: (bloc: InstanceType<T>) => boolean, options?: WaitUntilOptions): Promise<InstanceType<T>>;
1827
+
1828
+ /**
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
+ * ```
1849
+ */
1850
+ export declare function waitUntil<T extends StateContainerConstructor, TSelected>(BlocClass: T, selector: (bloc: InstanceType<T>) => TSelected, predicate: (selected: TSelected) => boolean, options?: WaitUntilOptions): Promise<TSelected>;
496
1851
 
497
- declare type StorageType = 'localStorage' | 'sessionStorage';
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
+ }
1869
+
1870
+ /**
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
1875
+ */
1876
+ export declare const warn: (context: string, message: string, data?: any) => void;
1877
+
1878
+ export declare const watch: WatchFn;
1879
+
1880
+ /**
1881
+ * Combined watch function type.
1882
+ */
1883
+ export declare interface WatchFn extends WatchSingleFn {
1884
+ <T extends readonly BlocInput[]>(blocs: T, callback: (blocs: ExtractInstances<T>) => void | StopSymbol): () => void;
1885
+ }
498
1886
 
499
1887
  /**
500
- * Extracts the state type from a BlocBase instance
501
- * @template B - The BlocBase type to extract the state from
1888
+ * Watch function signature for single bloc.
502
1889
  */
503
- 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
+ }
504
1894
 
505
1895
  export { }