@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.cjs ADDED
@@ -0,0 +1,2993 @@
1
+
2
+ //#region src/utils/idGenerator.ts
3
+ /**
4
+ * Centralized ID Generation
5
+ *
6
+ * Provides consistent, collision-resistant ID generation for all BlaC subsystems.
7
+ * Uses timestamp + counter + random suffix for uniqueness.
8
+ */
9
+ const globalCounters = /* @__PURE__ */ new Map();
10
+ /**
11
+ * Creates an ID generator with isolated counter state
12
+ *
13
+ * @param prefix - Prefix for generated IDs
14
+ * @returns Object with next(), nextSimple(), and reset() methods
15
+ *
16
+ * @example
17
+ * ```ts
18
+ * const generator = createIdGenerator('sub');
19
+ * const id1 = generator.next(); // "sub:1698765432100_1_a3k9d7f2q"
20
+ * const id2 = generator.next(); // "sub:1698765432101_2_b4n8e9g3r"
21
+ * ```
22
+ */
23
+ function createIdGenerator(prefix) {
24
+ let counter = 0;
25
+ return {
26
+ next: () => `${prefix}:${Date.now()}_${++counter}_${Math.random().toString(36).substring(2, 11)}`,
27
+ nextSimple: () => `${prefix}:${++counter}`,
28
+ reset: () => {
29
+ counter = 0;
30
+ }
31
+ };
32
+ }
33
+ /**
34
+ * Generate ID with timestamp, counter, and random suffix (tree-shakeable)
35
+ *
36
+ * Format: `${prefix}:${timestamp}_${counter}_${random}`
37
+ *
38
+ * @param prefix - Prefix for the ID (e.g., 'sub', 'consumer', 'stage')
39
+ * @returns Branded ID string
40
+ *
41
+ * @example
42
+ * const id = generateId('sub');
43
+ * // Returns: "sub:1698765432100_1_a3k9d7f2q"
44
+ */
45
+ function generateId(prefix) {
46
+ const counter = (globalCounters.get(prefix) ?? 0) + 1;
47
+ globalCounters.set(prefix, counter);
48
+ return `${prefix}:${Date.now()}_${counter}_${Math.random().toString(36).substring(2, 11)}`;
49
+ }
50
+ /**
51
+ * Generate simple ID with timestamp and random (no counter tracking)
52
+ *
53
+ * Format: `${prefix}:${timestamp}_${random}`
54
+ *
55
+ * @param prefix - Prefix for the ID
56
+ * @returns Branded ID string
57
+ *
58
+ * @example
59
+ * ```ts
60
+ * const id = generateSimpleId('CounterBloc');
61
+ * // Returns: "CounterBloc:1698765432100_a3k9d7f2q"
62
+ * ```
63
+ */
64
+ function generateSimpleId(prefix, affix) {
65
+ if (affix) return `${prefix}:${affix}`;
66
+ return `${prefix}:${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;
67
+ }
68
+ /**
69
+ * Reset all counters for testing purposes
70
+ * @internal
71
+ */
72
+ function __resetIdCounters() {
73
+ globalCounters.clear();
74
+ }
75
+ /**
76
+ * Generate a unique isolated instance key
77
+ * Uses base36 encoding for compact, URL-safe identifiers
78
+ *
79
+ * Format: "isolated-{9-char-random-string}"
80
+ * Example: "isolated-k7x2m9p4q"
81
+ *
82
+ * @returns A unique isolated instance key
83
+ */
84
+ function generateIsolatedKey() {
85
+ return `isolated-${Math.random().toString(36).slice(2, 11)}`;
86
+ }
87
+ /**
88
+ * Check if a key is an isolated instance key
89
+ * @param key - The instance key to check
90
+ * @returns true if the key is an isolated instance key
91
+ */
92
+ function isIsolatedKey(key) {
93
+ return key.startsWith("isolated-");
94
+ }
95
+
96
+ //#endregion
97
+ //#region src/plugin/PluginManager.ts
98
+ /**
99
+ * Manages plugin lifecycle for the BlaC state management system.
100
+ * Plugins receive notifications about state container lifecycle events.
101
+ *
102
+ * @example
103
+ * ```ts
104
+ * const manager = createPluginManager(registry);
105
+ * manager.install(myPlugin, { environment: 'development' });
106
+ * ```
107
+ */
108
+ var PluginManager = class {
109
+ /**
110
+ * Create a new PluginManager
111
+ * @param registry - The StateContainerRegistry to monitor for lifecycle events
112
+ */
113
+ constructor(registry) {
114
+ this.plugins = /* @__PURE__ */ new Map();
115
+ this.registry = registry;
116
+ this.setupLifecycleHooks();
117
+ }
118
+ /**
119
+ * Install a plugin with optional configuration
120
+ * @param plugin - The plugin to install
121
+ * @param config - Optional plugin configuration
122
+ * @throws Error if plugin is already installed
123
+ */
124
+ install(plugin, config = {}) {
125
+ const effectiveConfig = {
126
+ enabled: true,
127
+ environment: "all",
128
+ ...config
129
+ };
130
+ if (!this.shouldEnablePlugin(effectiveConfig)) {
131
+ console.log(`[BlaC] Plugin "${plugin.name}" skipped (environment mismatch)`);
132
+ return;
133
+ }
134
+ if (this.plugins.has(plugin.name)) throw new Error(`Plugin "${plugin.name}" is already installed`);
135
+ const context = this.createPluginContext();
136
+ this.plugins.set(plugin.name, {
137
+ plugin,
138
+ config: effectiveConfig,
139
+ context
140
+ });
141
+ if (plugin.onInstall) try {
142
+ plugin.onInstall(context);
143
+ } catch (error$1) {
144
+ console.error(`[BlaC] Error installing plugin "${plugin.name}":`, error$1);
145
+ this.plugins.delete(plugin.name);
146
+ throw error$1;
147
+ }
148
+ console.log(`[BlaC] Plugin "${plugin.name}" v${plugin.version} installed`);
149
+ }
150
+ /**
151
+ * Uninstall a plugin by name
152
+ * @param pluginName - The name of the plugin to uninstall
153
+ * @throws Error if plugin is not installed
154
+ */
155
+ uninstall(pluginName) {
156
+ const installed = this.plugins.get(pluginName);
157
+ if (!installed) throw new Error(`Plugin "${pluginName}" is not installed`);
158
+ if (installed.plugin.onUninstall) try {
159
+ installed.plugin.onUninstall();
160
+ } catch (error$1) {
161
+ console.error(`[BlaC] Error uninstalling plugin "${pluginName}":`, error$1);
162
+ }
163
+ this.plugins.delete(pluginName);
164
+ console.log(`[BlaC] Plugin "${pluginName}" uninstalled`);
165
+ }
166
+ /**
167
+ * Get an installed plugin by name
168
+ * @param pluginName - The name of the plugin to retrieve
169
+ * @returns The plugin instance or undefined if not found
170
+ */
171
+ getPlugin(pluginName) {
172
+ return this.plugins.get(pluginName)?.plugin;
173
+ }
174
+ /**
175
+ * Get all installed plugins
176
+ * @returns Array of all installed plugins
177
+ */
178
+ getAllPlugins() {
179
+ return Array.from(this.plugins.values()).map((p) => p.plugin);
180
+ }
181
+ /**
182
+ * Check if a plugin is installed
183
+ * @param pluginName - The name of the plugin to check
184
+ * @returns true if the plugin is installed
185
+ */
186
+ hasPlugin(pluginName) {
187
+ return this.plugins.has(pluginName);
188
+ }
189
+ /**
190
+ * Uninstall all plugins
191
+ */
192
+ clear() {
193
+ for (const name of this.plugins.keys()) this.uninstall(name);
194
+ }
195
+ /**
196
+ * Setup lifecycle hooks to notify plugins
197
+ */
198
+ setupLifecycleHooks() {
199
+ this.registry.on("created", (instance$1) => {
200
+ this.notifyPlugins("onInstanceCreated", instance$1);
201
+ });
202
+ this.registry.on("stateChanged", (instance$1, previousState, currentState, callstack) => {
203
+ this.notifyPlugins("onStateChanged", instance$1, previousState, currentState, callstack);
204
+ });
205
+ this.registry.on("eventAdded", (vertex, event) => {
206
+ this.notifyPlugins("onEventAdded", vertex, event);
207
+ });
208
+ this.registry.on("disposed", (instance$1) => {
209
+ this.notifyPlugins("onInstanceDisposed", instance$1);
210
+ });
211
+ }
212
+ /**
213
+ * Notify all plugins of a lifecycle event
214
+ */
215
+ notifyPlugins(hookName, ...args) {
216
+ for (const { plugin, config, context } of this.plugins.values()) {
217
+ if (!config.enabled) continue;
218
+ const hook = plugin[hookName];
219
+ if (typeof hook === "function") try {
220
+ hook.apply(plugin, [...args, context]);
221
+ } catch (error$1) {
222
+ console.error(`[BlaC] Error in plugin "${plugin.name}" ${hookName}:`, error$1);
223
+ }
224
+ }
225
+ }
226
+ /**
227
+ * Create plugin context with safe API access
228
+ */
229
+ createPluginContext() {
230
+ return {
231
+ getInstanceMetadata: (instance$1) => {
232
+ return {
233
+ id: instance$1.instanceId,
234
+ className: instance$1.constructor.name,
235
+ isDisposed: instance$1.isDisposed,
236
+ name: instance$1.name,
237
+ lastStateChangeTimestamp: instance$1.lastUpdateTimestamp,
238
+ createdAt: instance$1.createdAt,
239
+ state: instance$1.state,
240
+ isIsolated: instance$1.instanceId.startsWith("isolated-")
241
+ };
242
+ },
243
+ getState: (instance$1) => {
244
+ return instance$1.state;
245
+ },
246
+ queryInstances: (typeClass) => {
247
+ return this.registry.getAll(typeClass);
248
+ },
249
+ getAllTypes: () => {
250
+ return this.registry.getTypes();
251
+ },
252
+ getStats: () => {
253
+ return this.registry.getStats();
254
+ }
255
+ };
256
+ }
257
+ /**
258
+ * Check if plugin should be enabled based on environment
259
+ */
260
+ shouldEnablePlugin(config) {
261
+ if (!config.enabled) return false;
262
+ if (config.environment === "all") return true;
263
+ return this.getCurrentEnvironment() === config.environment;
264
+ }
265
+ /**
266
+ * Get current environment
267
+ */
268
+ getCurrentEnvironment() {
269
+ if (typeof process !== "undefined") {
270
+ if (process.env.NODE_ENV === "test") return "test";
271
+ if (process.env.NODE_ENV === "production") return "production";
272
+ return "development";
273
+ }
274
+ return "development";
275
+ }
276
+ };
277
+ /**
278
+ * Create a plugin manager instance
279
+ * @param registry - The StateContainerRegistry to monitor for lifecycle events
280
+ * @returns A new PluginManager instance
281
+ */
282
+ function createPluginManager(registry) {
283
+ return new PluginManager(registry);
284
+ }
285
+
286
+ //#endregion
287
+ //#region src/constants.ts
288
+ /**
289
+ * Default configuration constants for BlaC
290
+ *
291
+ * Centralized location for all magic numbers and default values.
292
+ */
293
+ /**
294
+ * Default configuration constants for BlaC
295
+ */
296
+ const BLAC_DEFAULTS = {
297
+ DEFAULT_INSTANCE_KEY: "default",
298
+ MAX_GETTER_DEPTH: 10,
299
+ CLEANUP_INTERVAL_MS: 3e4,
300
+ WEAKREF_CLEANUP_INTERVAL_MS: 1e4,
301
+ MAX_SUBSCRIPTIONS: 1e3,
302
+ MAX_SUBSCRIPTIONS_HIGH_PERF: 1e4,
303
+ PIPELINE_TIMEOUT_MS: 5e3,
304
+ CLEANUP_INTERVAL_HIGH_PERF_MS: 5e3,
305
+ MAX_PIPELINE_STAGES: 30
306
+ };
307
+ /**
308
+ * Static property names for StateContainer classes
309
+ * Used for feature flags and configuration on bloc classes
310
+ */
311
+ const BLAC_STATIC_PROPS = {
312
+ ISOLATED: "isolated",
313
+ KEEP_ALIVE: "keepAlive",
314
+ EXCLUDE_FROM_DEVTOOLS: "__excludeFromDevTools"
315
+ };
316
+ /**
317
+ * ID generation patterns and constants
318
+ */
319
+ const BLAC_ID_PATTERNS = {
320
+ ISOLATED_PREFIX: "isolated-",
321
+ ID_LENGTH: 9
322
+ };
323
+ /**
324
+ * Standard error message prefix
325
+ */
326
+ const BLAC_ERROR_PREFIX = "[BlaC]";
327
+
328
+ //#endregion
329
+ //#region src/tracking/getter-tracker.ts
330
+ const descriptorCache = /* @__PURE__ */ new WeakMap();
331
+ const blocProxyCache = /* @__PURE__ */ new WeakMap();
332
+ const activeTrackerMap = /* @__PURE__ */ new WeakMap();
333
+ const getterExecutionContext = {
334
+ tracker: null,
335
+ currentBloc: null,
336
+ depth: 0,
337
+ visitedBlocs: /* @__PURE__ */ new Set()
338
+ };
339
+ const MAX_GETTER_DEPTH$1 = BLAC_DEFAULTS.MAX_GETTER_DEPTH;
340
+ /**
341
+ * @internal
342
+ */
343
+ function getGetterExecutionContext() {
344
+ return getterExecutionContext;
345
+ }
346
+ /**
347
+ * @internal
348
+ */
349
+ function getDescriptor(obj, prop) {
350
+ const constructor = obj.constructor;
351
+ let constructorCache = descriptorCache.get(constructor);
352
+ if (constructorCache?.has(prop)) return constructorCache.get(prop);
353
+ let current = obj;
354
+ let descriptor;
355
+ while (current && current !== Object.prototype) {
356
+ descriptor = Object.getOwnPropertyDescriptor(current, prop);
357
+ if (descriptor) break;
358
+ current = Object.getPrototypeOf(current);
359
+ }
360
+ if (!constructorCache) {
361
+ constructorCache = /* @__PURE__ */ new Map();
362
+ descriptorCache.set(constructor, constructorCache);
363
+ }
364
+ constructorCache.set(prop, descriptor);
365
+ return descriptor;
366
+ }
367
+ /**
368
+ * @internal
369
+ */
370
+ function isGetter(obj, prop) {
371
+ return getDescriptor(obj, prop)?.get !== void 0;
372
+ }
373
+ /**
374
+ * @internal
375
+ */
376
+ function createGetterState() {
377
+ return {
378
+ trackedValues: /* @__PURE__ */ new Map(),
379
+ currentlyAccessing: /* @__PURE__ */ new Set(),
380
+ trackedGetters: /* @__PURE__ */ new Set(),
381
+ isTracking: false,
382
+ renderCache: /* @__PURE__ */ new Map(),
383
+ cacheValid: false,
384
+ externalDependencies: /* @__PURE__ */ new Set()
385
+ };
386
+ }
387
+ /**
388
+ * @internal
389
+ */
390
+ function setActiveTracker(bloc, tracker) {
391
+ activeTrackerMap.set(bloc, tracker);
392
+ }
393
+ /**
394
+ * @internal
395
+ */
396
+ function clearActiveTracker(bloc) {
397
+ activeTrackerMap.delete(bloc);
398
+ }
399
+ /**
400
+ * @internal
401
+ */
402
+ function getActiveTracker(bloc) {
403
+ return activeTrackerMap.get(bloc);
404
+ }
405
+ /**
406
+ * @internal
407
+ */
408
+ function commitTrackedGetters(tracker) {
409
+ if (tracker.currentlyAccessing.size > 0) tracker.trackedGetters = new Set(tracker.currentlyAccessing);
410
+ tracker.currentlyAccessing.clear();
411
+ }
412
+ /**
413
+ * @internal
414
+ */
415
+ function createBlocProxy(bloc) {
416
+ const cached = blocProxyCache.get(bloc);
417
+ if (cached) return cached;
418
+ const proxy = new Proxy(bloc, { get(target, prop, receiver) {
419
+ const tracker = activeTrackerMap.get(target);
420
+ if (tracker?.isTracking && isGetter(target, prop)) {
421
+ tracker.currentlyAccessing.add(prop);
422
+ if (tracker.cacheValid && tracker.renderCache.has(prop)) {
423
+ const cachedValue = tracker.renderCache.get(prop);
424
+ tracker.trackedValues.set(prop, cachedValue);
425
+ return cachedValue;
426
+ }
427
+ if (getterExecutionContext.depth >= MAX_GETTER_DEPTH$1) {
428
+ console.warn(`${BLAC_ERROR_PREFIX} Maximum getter depth (${MAX_GETTER_DEPTH$1}) exceeded. Possible circular dependency in getter "${String(prop)}" on ${target.constructor.name}. Returning undefined to prevent stack overflow.`);
429
+ return;
430
+ }
431
+ if (getterExecutionContext.visitedBlocs.has(target)) {
432
+ console.warn(`${BLAC_ERROR_PREFIX} Circular dependency detected: getter "${String(prop)}" on ${target.constructor.name} is calling back into itself. Returning undefined to prevent infinite recursion.`);
433
+ return;
434
+ }
435
+ const prevContext = {
436
+ tracker: getterExecutionContext.tracker,
437
+ currentBloc: getterExecutionContext.currentBloc,
438
+ depth: getterExecutionContext.depth,
439
+ visitedBlocs: new Set(getterExecutionContext.visitedBlocs)
440
+ };
441
+ getterExecutionContext.tracker = tracker;
442
+ getterExecutionContext.currentBloc = target;
443
+ getterExecutionContext.depth++;
444
+ getterExecutionContext.visitedBlocs.add(target);
445
+ try {
446
+ const value = getDescriptor(target, prop).get.call(target);
447
+ tracker.trackedValues.set(prop, value);
448
+ return value;
449
+ } catch (error$1) {
450
+ tracker.currentlyAccessing.delete(prop);
451
+ throw error$1;
452
+ } finally {
453
+ getterExecutionContext.tracker = prevContext.tracker;
454
+ getterExecutionContext.currentBloc = prevContext.currentBloc;
455
+ getterExecutionContext.depth = prevContext.depth;
456
+ getterExecutionContext.visitedBlocs = prevContext.visitedBlocs;
457
+ }
458
+ }
459
+ return Reflect.get(target, prop, receiver);
460
+ } });
461
+ blocProxyCache.set(bloc, proxy);
462
+ return proxy;
463
+ }
464
+ /**
465
+ * @internal
466
+ */
467
+ function hasGetterChanges(bloc, tracker) {
468
+ if (!tracker || tracker.trackedGetters.size === 0) return false;
469
+ tracker.renderCache.clear();
470
+ let hasAnyChange = false;
471
+ for (const prop of tracker.trackedGetters) try {
472
+ const descriptor = getDescriptor(bloc, prop);
473
+ if (!descriptor?.get) continue;
474
+ const newValue = descriptor.get.call(bloc);
475
+ const oldValue = tracker.trackedValues.get(prop);
476
+ tracker.renderCache.set(prop, newValue);
477
+ tracker.trackedValues.set(prop, newValue);
478
+ if (!Object.is(newValue, oldValue)) hasAnyChange = true;
479
+ } catch (error$1) {
480
+ console.warn(`${BLAC_ERROR_PREFIX} Getter "${String(prop)}" threw error during change detection. Stopping tracking for this getter.`, error$1);
481
+ tracker.trackedGetters.delete(prop);
482
+ tracker.trackedValues.delete(prop);
483
+ tracker.cacheValid = false;
484
+ return true;
485
+ }
486
+ tracker.cacheValid = true;
487
+ return hasAnyChange;
488
+ }
489
+ /**
490
+ * @internal
491
+ */
492
+ function invalidateRenderCache(tracker) {
493
+ tracker.cacheValid = false;
494
+ }
495
+ /**
496
+ * @internal
497
+ */
498
+ function clearExternalDependencies(tracker) {
499
+ tracker.externalDependencies.clear();
500
+ }
501
+ /**
502
+ * @internal
503
+ */
504
+ function resetGetterState(tracker) {
505
+ tracker.trackedValues.clear();
506
+ tracker.currentlyAccessing.clear();
507
+ tracker.trackedGetters.clear();
508
+ tracker.renderCache.clear();
509
+ tracker.cacheValid = false;
510
+ tracker.isTracking = false;
511
+ tracker.externalDependencies.clear();
512
+ }
513
+
514
+ //#endregion
515
+ //#region src/core/markers.ts
516
+ /**
517
+ * Marker symbols for identifying container types.
518
+ * These are in a separate file to avoid circular dependencies.
519
+ * @internal
520
+ */
521
+ /**
522
+ * Marker symbol to identify stateless containers at the type level.
523
+ * Used by React hooks to prevent `useBloc` from accepting stateless containers.
524
+ */
525
+ const STATELESS_MARKER = Symbol("STATELESS_CONTAINER");
526
+
527
+ //#endregion
528
+ //#region src/utils/static-props.ts
529
+ /**
530
+ * Utility functions for accessing static properties on StateContainer classes
531
+ */
532
+ /**
533
+ * Get a static property from a class constructor
534
+ * Type-safe helper that avoids (Type as any) casts
535
+ *
536
+ * @param Type - The class constructor
537
+ * @param propName - The property name to access
538
+ * @param defaultValue - Optional default value if property is undefined
539
+ * @returns The property value or default
540
+ */
541
+ function getStaticProp(Type, propName, defaultValue) {
542
+ return Type[propName] ?? defaultValue;
543
+ }
544
+ /**
545
+ * Check if a class is marked as isolated.
546
+ * Isolated classes create separate instances per component.
547
+ * @param Type - The class constructor to check
548
+ * @returns true if the class has `static isolated = true`
549
+ */
550
+ function isIsolatedClass(Type) {
551
+ return getStaticProp(Type, BLAC_STATIC_PROPS.ISOLATED) === true;
552
+ }
553
+ /**
554
+ * Check if a class is marked as keepAlive.
555
+ * KeepAlive classes are never auto-disposed when ref count reaches 0.
556
+ * @param Type - The class constructor to check
557
+ * @returns true if the class has `static keepAlive = true`
558
+ */
559
+ function isKeepAliveClass(Type) {
560
+ return getStaticProp(Type, BLAC_STATIC_PROPS.KEEP_ALIVE) === true;
561
+ }
562
+ /**
563
+ * Check if a class should be excluded from DevTools.
564
+ * Used to prevent infinite loops when DevTools tracks itself.
565
+ * @param Type - The class constructor to check
566
+ * @returns true if the class has `static __excludeFromDevTools = true`
567
+ */
568
+ function isExcludedFromDevTools(Type) {
569
+ return getStaticProp(Type, BLAC_STATIC_PROPS.EXCLUDE_FROM_DEVTOOLS) === true;
570
+ }
571
+ /**
572
+ * Check if a class is a stateless container (StatelessCubit or StatelessVertex).
573
+ * Stateless containers don't have state, emit, update, or subscribe methods.
574
+ * @param Type - The class constructor to check
575
+ * @returns true if the class is a stateless container
576
+ */
577
+ function isStatelessClass(Type) {
578
+ return Type[STATELESS_MARKER] === true;
579
+ }
580
+
581
+ //#endregion
582
+ //#region src/core/StateContainerRegistry.ts
583
+ /**
584
+ * Central registry for managing StateContainer instances.
585
+ * Handles instance lifecycle, ref counting, and lifecycle event emission.
586
+ *
587
+ * @example
588
+ * ```ts
589
+ * const registry = new StateContainerRegistry();
590
+ * const instance = registry.acquire(MyBloc); // ownership, must release
591
+ * const other = registry.ensure(OtherBloc); // no ownership, bloc-to-bloc
592
+ * registry.on('stateChanged', (container, prev, next) => {
593
+ * console.log('State changed:', prev, '->', next);
594
+ * });
595
+ * ```
596
+ */
597
+ var StateContainerRegistry = class {
598
+ constructor() {
599
+ this.instancesByConstructor = /* @__PURE__ */ new WeakMap();
600
+ this.types = /* @__PURE__ */ new Set();
601
+ this.typeConfigs = /* @__PURE__ */ new Map();
602
+ this.listeners = /* @__PURE__ */ new Map();
603
+ }
604
+ /**
605
+ * Register a type for lifecycle event tracking
606
+ * @param constructor - The StateContainer class constructor
607
+ */
608
+ registerType(constructor) {
609
+ this.types.add(constructor);
610
+ }
611
+ /**
612
+ * Register a StateContainer class with configuration
613
+ * @param constructor - The StateContainer class constructor
614
+ * @param isolated - Whether instances should be isolated (component-scoped)
615
+ * @throws Error if type is already registered
616
+ */
617
+ register(constructor, isolated = false) {
618
+ const className = constructor.name;
619
+ if (!isolated && isIsolatedClass(constructor)) isolated = true;
620
+ if (this.typeConfigs.has(className)) throw new Error(`${BLAC_ERROR_PREFIX} Type "${className}" is already registered`);
621
+ this.typeConfigs.set(className, { isolated });
622
+ this.registerType(constructor);
623
+ }
624
+ ensureInstancesMap(Type) {
625
+ let instances = this.instancesByConstructor.get(Type);
626
+ if (!instances) {
627
+ instances = /* @__PURE__ */ new Map();
628
+ this.instancesByConstructor.set(Type, instances);
629
+ }
630
+ return instances;
631
+ }
632
+ /**
633
+ * Get the instances Map for a specific class (public API for stats/debugging)
634
+ */
635
+ getInstancesMap(Type) {
636
+ return this.instancesByConstructor.get(Type) || /* @__PURE__ */ new Map();
637
+ }
638
+ trackExecutionContext(instance$1) {
639
+ const context = getGetterExecutionContext();
640
+ if (context.tracker && context.currentBloc && context.currentBloc !== instance$1) context.tracker.externalDependencies.add(instance$1);
641
+ }
642
+ /**
643
+ * Acquire an instance with ref counting (ownership semantics).
644
+ * Creates a new instance if one doesn't exist, or returns existing and increments ref count.
645
+ * You must call `release()` when done to decrement the ref count.
646
+ * @param Type - The StateContainer class constructor
647
+ * @param instanceKey - Instance key (defaults to 'default')
648
+ * @param options - Acquisition options
649
+ * @param options.canCreate - Whether to create new instance if not found (default: true)
650
+ * @param options.countRef - Whether to increment ref count (default: true)
651
+ * @param options.props - Props to pass to constructor if creating new instance
652
+ * @param options.trackExecutionContext - Whether to track cross-bloc dependency (default: false)
653
+ * @returns The state container instance
654
+ */
655
+ acquire(Type, instanceKey = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY, options = {}) {
656
+ const { canCreate = true, countRef = true, props, trackExecutionContext = false } = options;
657
+ const registryConfig = this.typeConfigs.get(Type.name);
658
+ const isolated = isIsolatedClass(Type) || registryConfig?.isolated === true;
659
+ const config = { instanceId: instanceKey };
660
+ if (isolated && !canCreate) throw new Error(`${BLAC_ERROR_PREFIX} Cannot get isolated instance "${instanceKey}" of ${Type.name} when creation is disabled.`);
661
+ if (isolated) {
662
+ const instance$2 = new Type(props);
663
+ instance$2.initConfig(config);
664
+ this.registerType(Type);
665
+ if (trackExecutionContext) this.trackExecutionContext(instance$2);
666
+ return instance$2;
667
+ }
668
+ const instances = this.ensureInstancesMap(Type);
669
+ const entry = instances.get(instanceKey);
670
+ if (entry && (countRef || entry.refCount === 0)) entry.refCount++;
671
+ if (entry) {
672
+ if (trackExecutionContext) this.trackExecutionContext(entry.instance);
673
+ return entry.instance;
674
+ }
675
+ if (!canCreate) throw new Error(`${BLAC_ERROR_PREFIX} ${Type.name} instance "${instanceKey}" not found and creation is disabled.`);
676
+ const instance$1 = new Type(props);
677
+ instance$1.initConfig(config);
678
+ instances.set(instanceKey, {
679
+ instance: instance$1,
680
+ refCount: 1
681
+ });
682
+ this.registerType(Type);
683
+ if (trackExecutionContext) this.trackExecutionContext(instance$1);
684
+ return instance$1;
685
+ }
686
+ /**
687
+ * Borrow an existing instance without incrementing ref count (borrowing semantics).
688
+ * Tracks cross-bloc dependency for reactive updates.
689
+ * @param Type - The StateContainer class constructor
690
+ * @param instanceKey - Instance key (defaults to 'default')
691
+ * @returns The state container instance
692
+ * @throws Error if instance doesn't exist
693
+ */
694
+ borrow(Type, instanceKey = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY) {
695
+ return this.acquire(Type, instanceKey, {
696
+ canCreate: false,
697
+ trackExecutionContext: true
698
+ });
699
+ }
700
+ /**
701
+ * Safely borrow an existing instance (borrowing semantics with error handling).
702
+ * Returns discriminated union for type-safe conditional access.
703
+ * @param Type - The StateContainer class constructor
704
+ * @param instanceKey - Instance key (defaults to 'default')
705
+ * @returns Discriminated union with either the instance or an error
706
+ */
707
+ borrowSafe(Type, instanceKey = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY) {
708
+ try {
709
+ return {
710
+ error: null,
711
+ instance: this.borrow(Type, instanceKey)
712
+ };
713
+ } catch (error$1) {
714
+ return {
715
+ error: error$1,
716
+ instance: null
717
+ };
718
+ }
719
+ }
720
+ /**
721
+ * Ensure an instance exists without taking ownership (for bloc-to-bloc communication).
722
+ * Gets existing instance OR creates it if it doesn't exist, without incrementing ref count.
723
+ * Tracks cross-bloc dependency for reactive updates.
724
+ *
725
+ * Use this in bloc-to-bloc communication when you need to ensure an instance exists
726
+ * but don't want to claim ownership (no ref count increment).
727
+ * @param Type - The StateContainer class constructor
728
+ * @param instanceKey - Instance key (defaults to 'default')
729
+ * @returns The state container instance
730
+ */
731
+ ensure(Type, instanceKey = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY) {
732
+ return this.acquire(Type, instanceKey, {
733
+ canCreate: true,
734
+ countRef: false,
735
+ trackExecutionContext: true
736
+ });
737
+ }
738
+ /**
739
+ * Release a reference to an instance.
740
+ * Decrements ref count and disposes when it reaches 0 (unless keepAlive).
741
+ * @param Type - The StateContainer class constructor
742
+ * @param instanceKey - Instance key (defaults to 'default')
743
+ * @param forceDispose - Force immediate disposal regardless of ref count
744
+ */
745
+ release(Type, instanceKey = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY, forceDispose = false) {
746
+ const instances = this.ensureInstancesMap(Type);
747
+ const entry = instances.get(instanceKey);
748
+ if (!entry) return;
749
+ if (forceDispose) {
750
+ if (!entry.instance.isDisposed) entry.instance.dispose();
751
+ instances.delete(instanceKey);
752
+ return;
753
+ }
754
+ entry.refCount--;
755
+ const keepAlive = isKeepAliveClass(Type);
756
+ if (entry.refCount <= 0 && !keepAlive) {
757
+ if (!entry.instance.isDisposed) entry.instance.dispose();
758
+ instances.delete(instanceKey);
759
+ }
760
+ }
761
+ /**
762
+ * Get all instances of a specific type.
763
+ * @param Type - The StateContainer class constructor
764
+ * @returns Array of all instances
765
+ */
766
+ getAll(Type) {
767
+ const instances = this.ensureInstancesMap(Type);
768
+ const result = [];
769
+ for (const entry of instances.values()) result.push(entry.instance);
770
+ return result;
771
+ }
772
+ /**
773
+ * Safely iterate over all instances of a type.
774
+ * Skips disposed instances and catches callback errors.
775
+ * @param Type - The StateContainer class constructor
776
+ * @param callback - Function to call for each instance
777
+ */
778
+ forEach(Type, callback) {
779
+ const instances = this.ensureInstancesMap(Type);
780
+ for (const entry of instances.values()) {
781
+ const instance$1 = entry.instance;
782
+ if (!instance$1.isDisposed) try {
783
+ callback(instance$1);
784
+ } catch (error$1) {
785
+ console.error(`${BLAC_ERROR_PREFIX} forEach callback error for ${Type.name}:`, error$1);
786
+ }
787
+ }
788
+ }
789
+ /**
790
+ * Clear all instances of a specific type (disposes them).
791
+ * @param Type - The StateContainer class constructor
792
+ */
793
+ clear(Type) {
794
+ const instances = this.ensureInstancesMap(Type);
795
+ for (const entry of instances.values()) if (!entry.instance.isDisposed) entry.instance.dispose();
796
+ instances.clear();
797
+ }
798
+ /**
799
+ * Get reference count for an instance.
800
+ * @param Type - The StateContainer class constructor
801
+ * @param instanceKey - Instance key (defaults to 'default')
802
+ * @returns Current ref count (0 if instance doesn't exist)
803
+ */
804
+ getRefCount(Type, instanceKey = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY) {
805
+ return this.ensureInstancesMap(Type).get(instanceKey)?.refCount ?? 0;
806
+ }
807
+ /**
808
+ * Check if an instance exists.
809
+ * @param Type - The StateContainer class constructor
810
+ * @param instanceKey - Instance key (defaults to 'default')
811
+ * @returns true if instance exists
812
+ */
813
+ hasInstance(Type, instanceKey = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY) {
814
+ return this.ensureInstancesMap(Type).has(instanceKey);
815
+ }
816
+ /**
817
+ * Clear all instances from all types (for testing)
818
+ *
819
+ * Iterates all registered types and clears their instances.
820
+ * Also clears type tracking to reset the registry state.
821
+ */
822
+ clearAll() {
823
+ for (const Type of this.types) this.clear(Type);
824
+ this.types.clear();
825
+ this.typeConfigs.clear();
826
+ }
827
+ /**
828
+ * Get registry statistics for debugging.
829
+ * @returns Object with registeredTypes, totalInstances, and typeBreakdown
830
+ */
831
+ getStats() {
832
+ const typeBreakdown = {};
833
+ let totalInstances = 0;
834
+ for (const Type of this.types) {
835
+ const typeName = Type.name;
836
+ const count = this.getInstancesMap(Type).size;
837
+ typeBreakdown[typeName] = count;
838
+ totalInstances += count;
839
+ }
840
+ return {
841
+ registeredTypes: this.types.size,
842
+ totalInstances,
843
+ typeBreakdown
844
+ };
845
+ }
846
+ /**
847
+ * Get all registered types (for plugin system).
848
+ * @returns Array of all registered StateContainer class constructors
849
+ */
850
+ getTypes() {
851
+ return Array.from(this.types);
852
+ }
853
+ /**
854
+ * Subscribe to lifecycle events
855
+ * @param event - The lifecycle event to listen for
856
+ * @param listener - The listener function to call when the event occurs
857
+ * @returns Unsubscribe function
858
+ */
859
+ on(event, listener) {
860
+ if (!this.listeners.has(event)) this.listeners.set(event, /* @__PURE__ */ new Set());
861
+ const instance$1 = this.listeners.get(event);
862
+ if (!instance$1) throw new Error(`${BLAC_ERROR_PREFIX} Failed to register listener for event '${event}'`);
863
+ instance$1.add(listener);
864
+ return () => {
865
+ this.listeners.get(event)?.delete(listener);
866
+ };
867
+ }
868
+ /**
869
+ * Emit lifecycle event to all listeners
870
+ * @internal - Called by StateContainer/Vertex lifecycle methods
871
+ */
872
+ emit(event, ...args) {
873
+ const listeners = this.listeners.get(event);
874
+ if (!listeners || listeners.size === 0) return;
875
+ for (const listener of listeners) try {
876
+ listener(...args);
877
+ } catch (error$1) {
878
+ console.error(`${BLAC_ERROR_PREFIX} Listener error for '${event}':`, error$1);
879
+ }
880
+ }
881
+ };
882
+ /**
883
+ * Global default registry instance
884
+ */
885
+ const globalRegistry = new StateContainerRegistry();
886
+ /**
887
+ * Global plugin manager (initialized lazily)
888
+ */
889
+ let _globalPluginManager = null;
890
+ /**
891
+ * Get the global plugin manager
892
+ */
893
+ function getPluginManager() {
894
+ if (!_globalPluginManager) _globalPluginManager = createPluginManager(globalRegistry);
895
+ return _globalPluginManager;
896
+ }
897
+
898
+ //#endregion
899
+ //#region src/core/StateContainer.ts
900
+ /**
901
+ * Abstract base class for all state containers in BlaC.
902
+ * Provides lifecycle management, subscription handling, ref counting,
903
+ * and integration with the global registry.
904
+ *
905
+ * @template S - State type managed by this container
906
+ * @template P - Props type passed to the container (optional)
907
+ *
908
+ * @example
909
+ * ```ts
910
+ * class CounterBloc extends StateContainer<{ count: number }> {
911
+ * constructor() {
912
+ * super({ count: 0 });
913
+ * }
914
+ * increment() {
915
+ * this.emit({ count: this.state.count + 1 });
916
+ * }
917
+ * }
918
+ * ```
919
+ */
920
+ var StateContainer = class StateContainer {
921
+ static {
922
+ this.__excludeFromDevTools = false;
923
+ }
924
+ static {
925
+ this.enableStackTrace = true;
926
+ }
927
+ /** Current props value passed to this container */
928
+ get props() {
929
+ return this._props;
930
+ }
931
+ constructor(initialState) {
932
+ this.listeners = /* @__PURE__ */ new Set();
933
+ this._disposed = false;
934
+ this.config = {};
935
+ this._props = void 0;
936
+ this.systemEventHandlers = /* @__PURE__ */ new Map();
937
+ this.name = this.constructor.name;
938
+ this.debug = false;
939
+ this.instanceId = generateSimpleId(this.constructor.name, "main");
940
+ this.createdAt = Date.now();
941
+ this.lastUpdateTimestamp = Date.now();
942
+ this.onSystemEvent = (event, handler) => {
943
+ let handlers = this.systemEventHandlers.get(event);
944
+ if (!handlers) {
945
+ handlers = /* @__PURE__ */ new Set();
946
+ this.systemEventHandlers.set(event, handlers);
947
+ }
948
+ handlers.add(handler);
949
+ return () => {
950
+ handlers?.delete(handler);
951
+ };
952
+ };
953
+ this._state = initialState;
954
+ }
955
+ /**
956
+ * Initialize configuration for this instance.
957
+ * Called by the registry after construction.
958
+ * @param config - Configuration options
959
+ */
960
+ initConfig(config) {
961
+ this.config = { ...config };
962
+ this.name = this.config.name || this.constructor.name;
963
+ this.debug = this.config.debug ?? false;
964
+ this.instanceId = generateSimpleId(this.constructor.name, this.config.instanceId);
965
+ globalRegistry.emit("created", this);
966
+ }
967
+ /** Current state value */
968
+ get state() {
969
+ return this._state;
970
+ }
971
+ /** Whether this instance has been disposed */
972
+ get isDisposed() {
973
+ return this._disposed;
974
+ }
975
+ /**
976
+ * Subscribe to state changes
977
+ * @param listener - Function called when state changes
978
+ * @returns Unsubscribe function
979
+ */
980
+ subscribe(listener) {
981
+ if (this._disposed) throw new Error(`Cannot subscribe to disposed container ${this.name}`);
982
+ this.listeners.add(listener);
983
+ return () => this.listeners.delete(listener);
984
+ }
985
+ /**
986
+ * Dispose this instance and clean up resources.
987
+ * Clears all listeners and emits the 'dispose' system event.
988
+ */
989
+ dispose() {
990
+ if (this._disposed) return;
991
+ if (this.debug) console.log(`[${this.name}] Disposing...`);
992
+ this._disposed = true;
993
+ this.emitSystemEvent("dispose", void 0);
994
+ this.listeners.clear();
995
+ this.systemEventHandlers.clear();
996
+ globalRegistry.emit("disposed", this);
997
+ if (this.debug) console.log(`[${this.name}] Disposed successfully`);
998
+ }
999
+ /**
1000
+ * Emit a new state value and notify all listeners.
1001
+ * @param newState - The new state value
1002
+ * @protected
1003
+ */
1004
+ emit(newState) {
1005
+ if (this._disposed) throw new Error(`Cannot emit state from disposed container ${this.name}`);
1006
+ if (this._state === newState) return;
1007
+ const previousState = this._state;
1008
+ this._state = newState;
1009
+ this.emitSystemEvent("stateChanged", {
1010
+ state: newState,
1011
+ previousState
1012
+ });
1013
+ for (const listener of this.listeners) try {
1014
+ listener(newState);
1015
+ } catch (error$1) {
1016
+ console.error(`[${this.name}] Error in listener:`, error$1);
1017
+ }
1018
+ const stackTrace = this.captureStackTrace();
1019
+ globalRegistry.emit("stateChanged", this, previousState, newState, stackTrace);
1020
+ this.lastUpdateTimestamp = Date.now();
1021
+ }
1022
+ captureStackTrace() {
1023
+ if (!StateContainer.enableStackTrace || typeof process !== "undefined" && process.env?.NODE_ENV === "production") return "";
1024
+ try {
1025
+ const relevantLines = ((/* @__PURE__ */ new Error()).stack || "").split("\n").slice(1);
1026
+ const formattedLines = [];
1027
+ for (const line of relevantLines) {
1028
+ if (!line.trim()) continue;
1029
+ if (line.includes("StateContainer.emit") || line.includes("StateContainer.update") || line.includes("StateContainer.captureStackTrace") || line.includes("Cubit.patch") || line.includes("Vertex.")) continue;
1030
+ if (line.includes("node_modules") || line.includes("react-dom") || line.includes("react_jsx") || line.includes(".vite/deps") || line.includes("executeDispatch") || line.includes("runWithFiber") || line.includes("invokeGuarded") || line.includes("callCallback") || line.includes("processDispatchQueue") || line.includes("dispatchEvent") || line.includes("batchedUpdates")) continue;
1031
+ const formatted = this.formatStackLine(line);
1032
+ if (formatted) formattedLines.push(formatted);
1033
+ }
1034
+ return formattedLines.join("\n");
1035
+ } catch {
1036
+ return "";
1037
+ }
1038
+ }
1039
+ formatStackLine(line) {
1040
+ const match = line.match(/at\s+(.+?)\s+\((.+?):(\d+):(\d+)\)/);
1041
+ if (!match) {
1042
+ const simpleMatch = line.match(/at\s+(.+?):(\d+):(\d+)/);
1043
+ if (simpleMatch) {
1044
+ const [, url$1, lineNum$1, col$1] = simpleMatch;
1045
+ return ` at ${this.cleanFilePath(url$1)}:${lineNum$1}:${col$1}`;
1046
+ }
1047
+ return null;
1048
+ }
1049
+ const [, functionName, url, lineNum, col] = match;
1050
+ return ` at ${functionName} (${this.cleanFilePath(url)}:${lineNum}:${col})`;
1051
+ }
1052
+ cleanFilePath(url) {
1053
+ let path = url.replace(/http:\/\/localhost:\d+\/@fs/, "").replace(/http:\/\/localhost:\d+\//, "").replace(/\?t=\d+/, "").replace(/\?v=[a-f0-9]+/, "");
1054
+ const projectMatch = path.match(/\/Projects\/blac\/(.+)/);
1055
+ if (projectMatch) path = projectMatch[1];
1056
+ const segments = path.split("/");
1057
+ if (segments.length > 3) path = segments.slice(-3).join("/");
1058
+ return path;
1059
+ }
1060
+ /**
1061
+ * Update state using a transform function.
1062
+ * @param updater - Function that receives current state and returns new state
1063
+ * @protected
1064
+ */
1065
+ update(updater) {
1066
+ if (this._disposed) throw new Error(`Cannot update state from disposed container ${this.name}`);
1067
+ this.emit(updater(this._state));
1068
+ }
1069
+ emitSystemEvent(event, payload) {
1070
+ const handlers = this.systemEventHandlers.get(event);
1071
+ if (!handlers) return;
1072
+ for (const handler of handlers) try {
1073
+ handler(payload);
1074
+ } catch (error$1) {
1075
+ console.error(`[${this.name}] Error in system event handler:`, error$1);
1076
+ }
1077
+ }
1078
+ /**
1079
+ * Update the props for this container.
1080
+ * Emits the 'propsUpdated' system event.
1081
+ * @param newProps - The new props value
1082
+ */
1083
+ updateProps(newProps) {
1084
+ if (this._disposed) throw new Error(`Cannot update props on disposed container ${this.name}`);
1085
+ const previousProps = this._props;
1086
+ this._props = newProps;
1087
+ this.emitSystemEvent("propsUpdated", {
1088
+ props: newProps,
1089
+ previousProps
1090
+ });
1091
+ if (this.debug) console.log(`[${this.name}] Props updated:`, {
1092
+ newProps,
1093
+ previousProps
1094
+ });
1095
+ }
1096
+ };
1097
+
1098
+ //#endregion
1099
+ //#region src/core/Cubit.ts
1100
+ /**
1101
+ * Simple state container with direct state emission.
1102
+ * Extends StateContainer with public methods for emitting and updating state.
1103
+ *
1104
+ * @template S - State type
1105
+ * @template P - Props type (optional)
1106
+ */
1107
+ var Cubit = class extends StateContainer {
1108
+ constructor(initialState) {
1109
+ super(initialState);
1110
+ this.patch = ((partial) => {
1111
+ if (typeof this.state !== "object" || this.state === null) throw new Error("patch() is only available for object state types");
1112
+ this.update((current) => ({
1113
+ ...current,
1114
+ ...partial
1115
+ }));
1116
+ });
1117
+ }
1118
+ /**
1119
+ * Replace state with a new value and notify all listeners
1120
+ * @param newState - The new state value
1121
+ */
1122
+ emit(newState) {
1123
+ super["emit"](newState);
1124
+ }
1125
+ /**
1126
+ * Transform current state using an updater function and emit the new state
1127
+ * @param updater - Function that receives current state and returns new state
1128
+ */
1129
+ update(updater) {
1130
+ super["update"](updater);
1131
+ }
1132
+ };
1133
+
1134
+ //#endregion
1135
+ //#region src/core/Vertex.ts
1136
+ /**
1137
+ * Event-driven state container using discriminated union events.
1138
+ * Extends StateContainer with event-based state transitions and
1139
+ * compile-time exhaustive checking for event handlers.
1140
+ *
1141
+ * @template S - State type (must be an object)
1142
+ * @template E - Event union type (discriminated by 'type' property)
1143
+ * @template P - Props type (optional)
1144
+ *
1145
+ * @example
1146
+ * ```typescript
1147
+ * type CounterEvent =
1148
+ * | { type: 'increment'; amount: number }
1149
+ * | { type: 'decrement' }
1150
+ * | { type: 'reset' };
1151
+ *
1152
+ * class CounterVertex extends Vertex<{ count: number }, CounterEvent> {
1153
+ * constructor() {
1154
+ * super({ count: 0 });
1155
+ * this.createHandlers({
1156
+ * increment: (event, emit) => {
1157
+ * emit({ count: this.state.count + event.amount });
1158
+ * },
1159
+ * decrement: (_, emit) => {
1160
+ * emit({ count: this.state.count - 1 });
1161
+ * },
1162
+ * reset: (_, emit) => {
1163
+ * emit({ count: 0 });
1164
+ * },
1165
+ * });
1166
+ * }
1167
+ *
1168
+ * increment = (amount = 1) => this.add({ type: 'increment', amount });
1169
+ * }
1170
+ * ```
1171
+ */
1172
+ var Vertex = class extends StateContainer {
1173
+ constructor(initialState) {
1174
+ super(initialState);
1175
+ this.handlers = /* @__PURE__ */ new Map();
1176
+ this.isProcessing = false;
1177
+ this.eventQueue = [];
1178
+ this.add = (event) => {
1179
+ const enrichedEvent = this.enrichEvent(event);
1180
+ globalRegistry.emit("eventAdded", this, enrichedEvent);
1181
+ this.processEvent(enrichedEvent);
1182
+ };
1183
+ }
1184
+ /**
1185
+ * Register all event handlers with exhaustive type checking.
1186
+ * TypeScript will error if any event type from the union is missing.
1187
+ *
1188
+ * @param handlers - Map of event type to handler function
1189
+ */
1190
+ createHandlers(handlers) {
1191
+ for (const [eventType, handler] of Object.entries(handlers)) this.handlers.set(eventType, handler);
1192
+ }
1193
+ /** @internal */
1194
+ enrichEvent(event) {
1195
+ return {
1196
+ ...event,
1197
+ timestamp: Date.now()
1198
+ };
1199
+ }
1200
+ /** @internal */
1201
+ processEvent(event) {
1202
+ if (this.isProcessing) {
1203
+ this.eventQueue.push(event);
1204
+ return;
1205
+ }
1206
+ this.isProcessing = true;
1207
+ try {
1208
+ this.handleEvent(event);
1209
+ while (this.eventQueue.length > 0) {
1210
+ const nextEvent = this.eventQueue.shift();
1211
+ this.handleEvent(nextEvent);
1212
+ }
1213
+ } finally {
1214
+ this.isProcessing = false;
1215
+ }
1216
+ }
1217
+ /** @internal */
1218
+ handleEvent(event) {
1219
+ const handler = this.handlers.get(event.type);
1220
+ if (!handler) {
1221
+ if (this.debug) console.warn(`No handler registered for event type: ${event.type}`);
1222
+ return;
1223
+ }
1224
+ const emitFn = (state) => {
1225
+ this.emit(state);
1226
+ };
1227
+ try {
1228
+ handler(event, emitFn);
1229
+ } catch (error$1) {
1230
+ if (this.debug) console.error(`Error handling event ${event.type}:`, error$1);
1231
+ this.onEventError(event, error$1);
1232
+ }
1233
+ }
1234
+ /**
1235
+ * Called when an error occurs during event processing.
1236
+ * Override to implement custom error handling.
1237
+ *
1238
+ * @param _event - The event that caused the error
1239
+ * @param _error - The error that occurred
1240
+ */
1241
+ onEventError(_event, _error) {}
1242
+ };
1243
+
1244
+ //#endregion
1245
+ //#region src/core/StatelessCubit.ts
1246
+ /**
1247
+ * A Cubit without state management capabilities.
1248
+ * Use this for action-only containers that don't need to manage or emit state.
1249
+ *
1250
+ * StatelessCubit:
1251
+ * - Has no `emit()`, `update()`, or `patch()` methods
1252
+ * - Has no accessible `state` property
1253
+ * - Cannot be subscribed to (throws error)
1254
+ * - Is rejected by `useBloc` hook (use `useBlocActions` instead)
1255
+ *
1256
+ * @template P - Props type (optional)
1257
+ *
1258
+ * @example
1259
+ * ```typescript
1260
+ * class AnalyticsService extends StatelessCubit {
1261
+ * trackPageView(page: string) {
1262
+ * analytics.track('page_view', { page });
1263
+ * }
1264
+ *
1265
+ * trackClick(element: string) {
1266
+ * analytics.track('click', { element });
1267
+ * }
1268
+ * }
1269
+ *
1270
+ * // In React component:
1271
+ * const analytics = useBlocActions(AnalyticsService);
1272
+ * analytics.trackPageView('/home');
1273
+ * ```
1274
+ */
1275
+ var StatelessCubit = class extends Cubit {
1276
+ static {
1277
+ this[STATELESS_MARKER] = true;
1278
+ }
1279
+ constructor() {
1280
+ super({});
1281
+ this.patch = (_partial) => {
1282
+ throw new Error(`${this.name} is a StatelessCubit and does not support patch(). Use a regular Cubit if you need state management.`);
1283
+ };
1284
+ }
1285
+ /**
1286
+ * State is not available on StatelessCubit.
1287
+ * @throws Always throws an error when accessed.
1288
+ */
1289
+ get state() {
1290
+ throw new Error(`${this.name} is a StatelessCubit and does not have state. Use a regular Cubit if you need state management.`);
1291
+ }
1292
+ /**
1293
+ * Subscriptions are not available on StatelessCubit.
1294
+ * @throws Always throws an error when called.
1295
+ */
1296
+ subscribe(_listener) {
1297
+ throw new Error(`${this.name} is a StatelessCubit and does not support subscriptions. Use useBlocActions() instead of useBloc() in React.`);
1298
+ }
1299
+ /**
1300
+ * emit() is not available on StatelessCubit.
1301
+ * TypeScript will show an error if you try to call this method.
1302
+ */
1303
+ emit(_newState) {
1304
+ throw new Error(`${this.name} is a StatelessCubit and does not support emit(). Use a regular Cubit if you need state management.`);
1305
+ }
1306
+ /**
1307
+ * update() is not available on StatelessCubit.
1308
+ * TypeScript will show an error if you try to call this method.
1309
+ */
1310
+ update(_updater) {
1311
+ throw new Error(`${this.name} is a StatelessCubit and does not support update(). Use a regular Cubit if you need state management.`);
1312
+ }
1313
+ };
1314
+
1315
+ //#endregion
1316
+ //#region src/core/StatelessVertex.ts
1317
+ /**
1318
+ * An event-driven container without state management capabilities.
1319
+ * Use this for event processing that only produces side effects (logging, analytics, etc).
1320
+ *
1321
+ * StatelessVertex:
1322
+ * - Processes events via `add()` method
1323
+ * - Handlers receive only the event (no `emit` function)
1324
+ * - Has no accessible `state` property
1325
+ * - Cannot be subscribed to (throws error)
1326
+ * - Is rejected by `useBloc` hook (use `useBlocActions` instead)
1327
+ *
1328
+ * @template E - Event union type (discriminated by 'type' property)
1329
+ * @template P - Props type (optional)
1330
+ *
1331
+ * @example
1332
+ * ```typescript
1333
+ * type LogEvent =
1334
+ * | { type: 'info'; message: string }
1335
+ * | { type: 'error'; message: string; error: Error }
1336
+ * | { type: 'warn'; message: string };
1337
+ *
1338
+ * class LoggingVertex extends StatelessVertex<LogEvent> {
1339
+ * constructor() {
1340
+ * super();
1341
+ * this.createHandlers({
1342
+ * info: (event) => console.log('[INFO]', event.message),
1343
+ * error: (event) => console.error('[ERROR]', event.message, event.error),
1344
+ * warn: (event) => console.warn('[WARN]', event.message),
1345
+ * });
1346
+ * }
1347
+ *
1348
+ * info = (message: string) => this.add({ type: 'info', message });
1349
+ * error = (message: string, error: Error) => this.add({ type: 'error', message, error });
1350
+ * warn = (message: string) => this.add({ type: 'warn', message });
1351
+ * }
1352
+ *
1353
+ * // In React component:
1354
+ * const logger = useBlocActions(LoggingVertex);
1355
+ * logger.info('Page loaded');
1356
+ * ```
1357
+ */
1358
+ var StatelessVertex = class extends StateContainer {
1359
+ static {
1360
+ this[STATELESS_MARKER] = true;
1361
+ }
1362
+ constructor() {
1363
+ super({});
1364
+ this.handlers = /* @__PURE__ */ new Map();
1365
+ this.isProcessing = false;
1366
+ this.eventQueue = [];
1367
+ this.add = (event) => {
1368
+ const enrichedEvent = this.enrichEvent(event);
1369
+ globalRegistry.emit("eventAdded", this, enrichedEvent);
1370
+ this.processEvent(enrichedEvent);
1371
+ };
1372
+ }
1373
+ /**
1374
+ * State is not available on StatelessVertex.
1375
+ * @throws Always throws an error when accessed.
1376
+ */
1377
+ get state() {
1378
+ throw new Error(`${this.name} is a StatelessVertex and does not have state. Use a regular Vertex if you need state management.`);
1379
+ }
1380
+ /**
1381
+ * Subscriptions are not available on StatelessVertex.
1382
+ * @throws Always throws an error when called.
1383
+ */
1384
+ subscribe(_listener) {
1385
+ throw new Error(`${this.name} is a StatelessVertex and does not support subscriptions. Use useBlocActions() instead of useBloc() in React.`);
1386
+ }
1387
+ /**
1388
+ * Register all event handlers with exhaustive type checking.
1389
+ * TypeScript will error if any event type from the union is missing.
1390
+ *
1391
+ * Unlike regular Vertex, handlers do NOT receive an emit function
1392
+ * since StatelessVertex cannot emit state.
1393
+ *
1394
+ * @param handlers - Map of event type to handler function
1395
+ */
1396
+ createHandlers(handlers) {
1397
+ for (const [eventType, handler] of Object.entries(handlers)) this.handlers.set(eventType, handler);
1398
+ }
1399
+ /** @internal */
1400
+ enrichEvent(event) {
1401
+ return {
1402
+ ...event,
1403
+ timestamp: Date.now()
1404
+ };
1405
+ }
1406
+ /** @internal */
1407
+ processEvent(event) {
1408
+ if (this.isProcessing) {
1409
+ this.eventQueue.push(event);
1410
+ return;
1411
+ }
1412
+ this.isProcessing = true;
1413
+ try {
1414
+ this.handleEvent(event);
1415
+ while (this.eventQueue.length > 0) {
1416
+ const nextEvent = this.eventQueue.shift();
1417
+ this.handleEvent(nextEvent);
1418
+ }
1419
+ } finally {
1420
+ this.isProcessing = false;
1421
+ }
1422
+ }
1423
+ /** @internal */
1424
+ handleEvent(event) {
1425
+ const handler = this.handlers.get(event.type);
1426
+ if (!handler) {
1427
+ if (this.debug) console.warn(`No handler registered for event type: ${event.type}`);
1428
+ return;
1429
+ }
1430
+ try {
1431
+ handler(event);
1432
+ } catch (error$1) {
1433
+ if (this.debug) console.error(`Error handling event ${event.type}:`, error$1);
1434
+ this.onEventError(event, error$1);
1435
+ }
1436
+ }
1437
+ /**
1438
+ * Called when an error occurs during event processing.
1439
+ * Override to implement custom error handling.
1440
+ *
1441
+ * @param _event - The event that caused the error
1442
+ * @param _error - The error that occurred
1443
+ */
1444
+ onEventError(_event, _error) {}
1445
+ /**
1446
+ * emit() is not available on StatelessVertex.
1447
+ * @internal
1448
+ */
1449
+ emit(_newState) {
1450
+ throw new Error(`${this.name} is a StatelessVertex and does not support emit(). Use a regular Vertex if you need state management.`);
1451
+ }
1452
+ /**
1453
+ * update() is not available on StatelessVertex.
1454
+ * @internal
1455
+ */
1456
+ update(_updater) {
1457
+ throw new Error(`${this.name} is a StatelessVertex and does not support update(). Use a regular Vertex if you need state management.`);
1458
+ }
1459
+ };
1460
+
1461
+ //#endregion
1462
+ //#region src/plugin/BlacPlugin.ts
1463
+ /**
1464
+ * Type guard to check if a plugin has a required onInstall hook
1465
+ * @param plugin - The plugin to check
1466
+ * @returns true if the plugin implements BlacPluginWithInit
1467
+ */
1468
+ function hasInitHook(plugin) {
1469
+ return typeof plugin.onInstall === "function";
1470
+ }
1471
+
1472
+ //#endregion
1473
+ //#region src/tracking/proxy-tracker.ts
1474
+ /**
1475
+ * Functional proxy tracker for automatic dependency tracking
1476
+ *
1477
+ * This module provides a functional approach to proxy-based dependency tracking.
1478
+ * Unlike the class-based ProxyTracker, this uses a state object pattern that's
1479
+ * easier to integrate with functional programming patterns and framework hooks.
1480
+ *
1481
+ * @internal
1482
+ */
1483
+ /**
1484
+ * Check if a value can be proxied
1485
+ *
1486
+ * Returns true for plain objects and arrays only.
1487
+ * Excludes built-in objects like Date, Map, Set, etc.
1488
+ *
1489
+ * @internal
1490
+ */
1491
+ function isProxyable(value) {
1492
+ if (typeof value !== "object" || value === null) return false;
1493
+ const proto = Object.getPrototypeOf(value);
1494
+ return proto === Object.prototype || proto === Array.prototype;
1495
+ }
1496
+ /**
1497
+ * Create a new proxy tracker state
1498
+ *
1499
+ * @example
1500
+ * const state = createProxyTrackerState<MyState>();
1501
+ * startProxyTracking(state);
1502
+ * const proxy = createProxyForTarget(state, myObject);
1503
+ * // ... use proxy ...
1504
+ * const paths = stopProxyTracking(state);
1505
+ *
1506
+ * @internal
1507
+ */
1508
+ function createProxyState() {
1509
+ return {
1510
+ trackedPaths: /* @__PURE__ */ new Set(),
1511
+ isTracking: false,
1512
+ proxyCache: /* @__PURE__ */ new WeakMap(),
1513
+ boundFunctionsCache: null,
1514
+ lastProxiedState: null,
1515
+ lastProxy: null,
1516
+ maxDepth: 10
1517
+ };
1518
+ }
1519
+ /**
1520
+ * Start tracking property accesses
1521
+ *
1522
+ * Clears previous tracked paths and enables tracking mode.
1523
+ *
1524
+ * @internal
1525
+ */
1526
+ function startProxy(state) {
1527
+ state.isTracking = true;
1528
+ state.trackedPaths.clear();
1529
+ }
1530
+ /**
1531
+ * Stop tracking and return the tracked paths
1532
+ *
1533
+ * Returns a new Set containing all tracked paths.
1534
+ *
1535
+ * @internal
1536
+ */
1537
+ function stopProxy(state) {
1538
+ state.isTracking = false;
1539
+ return new Set(state.trackedPaths);
1540
+ }
1541
+ /**
1542
+ * Create a proxy for an array with property access tracking
1543
+ *
1544
+ * Tracks:
1545
+ * - Array element access (arr[0])
1546
+ * - Length access (arr.length)
1547
+ * - Array method calls (arr.map, arr.filter, etc.)
1548
+ *
1549
+ * @internal
1550
+ */
1551
+ function createArrayProxy(state, target, path, depth = 0) {
1552
+ const proxy = new Proxy(target, { get: (arr, prop) => {
1553
+ if (typeof prop === "symbol") return Reflect.get(arr, prop);
1554
+ const value = Reflect.get(arr, prop);
1555
+ if (typeof value === "function") {
1556
+ if (!state.boundFunctionsCache) state.boundFunctionsCache = /* @__PURE__ */ new WeakMap();
1557
+ const cached = state.boundFunctionsCache.get(value);
1558
+ if (cached) return cached;
1559
+ const bound = value.bind(arr);
1560
+ state.boundFunctionsCache.set(value, bound);
1561
+ return bound;
1562
+ }
1563
+ if (prop === "length") {
1564
+ if (state.isTracking) {
1565
+ const fullPath$1 = path ? `${path}.length` : "length";
1566
+ state.trackedPaths.add(fullPath$1);
1567
+ }
1568
+ return value;
1569
+ }
1570
+ let fullPath;
1571
+ if (typeof prop === "string") {
1572
+ const index = Number(prop);
1573
+ if (!isNaN(index) && index >= 0) fullPath = path ? `${path}[${index}]` : `[${index}]`;
1574
+ else fullPath = path ? `${path}.${prop}` : prop;
1575
+ } else return value;
1576
+ if (isProxyable(value)) return createInternal(state, value, fullPath, depth + 1);
1577
+ if (state.isTracking) state.trackedPaths.add(fullPath);
1578
+ return value;
1579
+ } });
1580
+ state.proxyCache.set(target, proxy);
1581
+ return proxy;
1582
+ }
1583
+ /**
1584
+ * Create a proxy for an object with property access tracking
1585
+ *
1586
+ * This is the core proxy creation function that recursively creates proxies
1587
+ * for nested objects and arrays.
1588
+ *
1589
+ * Tracks:
1590
+ * - Property access (obj.prop)
1591
+ * - Nested property access (obj.nested.prop)
1592
+ * - 'in' operator usage ('prop' in obj)
1593
+ * - Object.keys, Object.entries, etc.
1594
+ *
1595
+ * @internal
1596
+ */
1597
+ function createInternal(state, target, path = "", depth = 0) {
1598
+ if (!state.isTracking || !isProxyable(target)) return target;
1599
+ if (depth >= state.maxDepth) return target;
1600
+ if (state.proxyCache.has(target)) return state.proxyCache.get(target);
1601
+ if (Array.isArray(target)) return createArrayProxy(state, target, path, depth);
1602
+ const proxy = new Proxy(target, {
1603
+ get: (obj, prop) => {
1604
+ if (typeof prop === "symbol") return Reflect.get(obj, prop);
1605
+ const value = Reflect.get(obj, prop);
1606
+ if (typeof value === "function") {
1607
+ if (!state.boundFunctionsCache) state.boundFunctionsCache = /* @__PURE__ */ new WeakMap();
1608
+ const cached = state.boundFunctionsCache.get(value);
1609
+ if (cached) return cached;
1610
+ const bound = value.bind(obj);
1611
+ state.boundFunctionsCache.set(value, bound);
1612
+ return bound;
1613
+ }
1614
+ const fullPath = path ? `${path}.${String(prop)}` : String(prop);
1615
+ if (typeof prop === "string" && state.isTracking) {
1616
+ if (!prop.startsWith("_") && !prop.startsWith("$$")) state.trackedPaths.add(fullPath);
1617
+ }
1618
+ if (isProxyable(value)) return createInternal(state, value, fullPath, depth + 1);
1619
+ return value;
1620
+ },
1621
+ has: (obj, prop) => {
1622
+ if (typeof prop === "string" && state.isTracking) {
1623
+ const fullPath = path ? `${path}.${prop}` : prop;
1624
+ state.trackedPaths.add(fullPath);
1625
+ }
1626
+ return Reflect.has(obj, prop);
1627
+ },
1628
+ ownKeys: (obj) => {
1629
+ if (state.isTracking && path) state.trackedPaths.add(path);
1630
+ return Reflect.ownKeys(obj);
1631
+ }
1632
+ });
1633
+ state.proxyCache.set(target, proxy);
1634
+ return proxy;
1635
+ }
1636
+ /**
1637
+ * Create a proxy for a target with caching
1638
+ *
1639
+ * If the target hasn't changed since the last call, returns the cached proxy.
1640
+ * Otherwise, creates a new proxy and caches it.
1641
+ *
1642
+ * This is the main entry point for creating tracked proxies.
1643
+ *
1644
+ * @internal
1645
+ */
1646
+ function createForTarget(state, target) {
1647
+ if (state.lastProxiedState === target && state.lastProxy) return state.lastProxy;
1648
+ state.proxyCache = /* @__PURE__ */ new WeakMap();
1649
+ state.boundFunctionsCache = null;
1650
+ const proxy = createInternal(state, target, "", 0);
1651
+ state.lastProxiedState = target;
1652
+ state.lastProxy = proxy;
1653
+ return proxy;
1654
+ }
1655
+
1656
+ //#endregion
1657
+ //#region src/tracking/path-utils.ts
1658
+ /**
1659
+ * Path utilities for dependency tracking
1660
+ *
1661
+ * Provides utilities for parsing property paths and extracting values
1662
+ * from nested objects using path strings.
1663
+ *
1664
+ * @internal
1665
+ */
1666
+ /**
1667
+ * Parse a property path string into an array of segments
1668
+ *
1669
+ * @internal
1670
+ *
1671
+ * Handles both dot notation (a.b.c) and bracket notation (a[0].b)
1672
+ *
1673
+ * @example
1674
+ * ```ts
1675
+ * parsePath('user.name') // ['user', 'name']
1676
+ * parsePath('items[0].name') // ['items', '0', 'name']
1677
+ * parsePath('data.users[2].address.city') // ['data', 'users', '2', 'address', 'city']
1678
+ * ```
1679
+ */
1680
+ function parsePath(path) {
1681
+ const segments = [];
1682
+ let current = "";
1683
+ let i = 0;
1684
+ while (i < path.length) {
1685
+ const char = path[i];
1686
+ if (char === ".") {
1687
+ if (current) segments.push(current);
1688
+ current = "";
1689
+ } else if (char === "[") {
1690
+ if (current) segments.push(current);
1691
+ current = "";
1692
+ i++;
1693
+ while (i < path.length && path[i] !== "]") current += path[i++];
1694
+ if (current) segments.push(current);
1695
+ current = "";
1696
+ } else current += char;
1697
+ i++;
1698
+ }
1699
+ if (current) segments.push(current);
1700
+ return segments;
1701
+ }
1702
+ /**
1703
+ * Get a value from an object using a path of segments
1704
+ *
1705
+ * @example
1706
+ * ```ts
1707
+ * const obj = { user: { name: 'Alice', age: 30 } }
1708
+ * getValueAtPath(obj, ['user', 'name']) // 'Alice'
1709
+ * getValueAtPath(obj, ['user', 'age']) // 30
1710
+ * getValueAtPath(obj, ['user', 'missing']) // undefined
1711
+ * ```
1712
+ *
1713
+ * @internal
1714
+ */
1715
+ function getValueAtPath(obj, segments) {
1716
+ if (obj == null) return void 0;
1717
+ let current = obj;
1718
+ for (let i = 0; i < segments.length; i++) {
1719
+ current = current[segments[i]];
1720
+ if (current == null) return void 0;
1721
+ }
1722
+ return current;
1723
+ }
1724
+ /**
1725
+ * Shallow equality comparison for arrays
1726
+ *
1727
+ * Compares two arrays element-by-element using Object.is
1728
+ *
1729
+ * @example
1730
+ * ```ts
1731
+ * shallowEqual([1, 2, 3], [1, 2, 3]) // true
1732
+ * shallowEqual([1, 2, 3], [1, 2, 4]) // false
1733
+ * shallowEqual([1, 2], [1, 2, 3]) // false
1734
+ * ```
1735
+ *
1736
+ * @internal
1737
+ */
1738
+ function shallowEqual(arr1, arr2) {
1739
+ if (arr1.length !== arr2.length) return false;
1740
+ for (let i = 0; i < arr1.length; i++) if (!Object.is(arr1[i], arr2[i])) return false;
1741
+ return true;
1742
+ }
1743
+
1744
+ //#endregion
1745
+ //#region src/tracking/dependency-tracker.ts
1746
+ function isChildPath(child, parent) {
1747
+ if (child === parent) return false;
1748
+ return child.startsWith(parent + ".") || child.startsWith(parent + "[");
1749
+ }
1750
+ /**
1751
+ * Extract the parent array path from an array child path
1752
+ * Examples:
1753
+ * 'messages.length' -> 'messages'
1754
+ * 'messages[0]' -> 'messages'
1755
+ * 'messages[0].text' -> 'messages'
1756
+ * 'data.items[0]' -> 'data.items'
1757
+ */
1758
+ function getArrayParentPath(path) {
1759
+ if (path.endsWith(".length")) return path.slice(0, -7);
1760
+ const arrayIndexMatch = path.match(/^(.+?)\[\d+\]/);
1761
+ if (arrayIndexMatch) return arrayIndexMatch[1];
1762
+ return null;
1763
+ }
1764
+ /**
1765
+ * @internal
1766
+ */
1767
+ function optimizeTrackedPaths(paths) {
1768
+ if (paths.size === 0) return /* @__PURE__ */ new Set();
1769
+ if (paths.size === 1) return new Set(paths);
1770
+ const sortedPaths = Array.from(paths).sort((a, b) => b.length - a.length);
1771
+ const optimized = /* @__PURE__ */ new Set();
1772
+ for (const path of sortedPaths) {
1773
+ let hasMoreSpecificChild = false;
1774
+ for (const optimizedPath of optimized) if (isChildPath(optimizedPath, path)) {
1775
+ hasMoreSpecificChild = true;
1776
+ break;
1777
+ }
1778
+ if (!hasMoreSpecificChild) optimized.add(path);
1779
+ }
1780
+ const arrayParents = /* @__PURE__ */ new Set();
1781
+ for (const path of optimized) {
1782
+ const arrayParent = getArrayParentPath(path);
1783
+ if (arrayParent) arrayParents.add(arrayParent);
1784
+ }
1785
+ for (const arrayParent of arrayParents) optimized.add(arrayParent);
1786
+ return optimized;
1787
+ }
1788
+ /**
1789
+ * @internal
1790
+ */
1791
+ function createDependencyState() {
1792
+ return {
1793
+ proxyState: createProxyState(),
1794
+ previousRenderPaths: /* @__PURE__ */ new Set(),
1795
+ currentRenderPaths: /* @__PURE__ */ new Set(),
1796
+ pathCache: /* @__PURE__ */ new Map(),
1797
+ lastCheckedState: null,
1798
+ lastCheckedValues: /* @__PURE__ */ new Map()
1799
+ };
1800
+ }
1801
+ /**
1802
+ * @internal
1803
+ */
1804
+ function startDependency(tracker) {
1805
+ startProxy(tracker.proxyState);
1806
+ }
1807
+ /**
1808
+ * @internal
1809
+ */
1810
+ function createDependencyProxy(tracker, state) {
1811
+ return createForTarget(tracker.proxyState, state);
1812
+ }
1813
+ /**
1814
+ * @internal
1815
+ */
1816
+ function capturePaths(tracker, state) {
1817
+ tracker.previousRenderPaths = tracker.currentRenderPaths;
1818
+ tracker.currentRenderPaths = optimizeTrackedPaths(stopProxy(tracker.proxyState));
1819
+ if (tracker.previousRenderPaths.size === 0 && tracker.currentRenderPaths.size === 0) return;
1820
+ const trackedPathsUnion = new Set(tracker.previousRenderPaths);
1821
+ for (const path of tracker.currentRenderPaths) trackedPathsUnion.add(path);
1822
+ const canReuseCache = tracker.lastCheckedState === state;
1823
+ for (const path of trackedPathsUnion) if (!tracker.pathCache.has(path)) {
1824
+ const segments = parsePath(path);
1825
+ const value = canReuseCache && tracker.lastCheckedValues.has(path) ? tracker.lastCheckedValues.get(path) : getValueAtPath(state, segments);
1826
+ tracker.pathCache.set(path, {
1827
+ segments,
1828
+ value
1829
+ });
1830
+ } else {
1831
+ const info$1 = tracker.pathCache.get(path);
1832
+ info$1.value = canReuseCache && tracker.lastCheckedValues.has(path) ? tracker.lastCheckedValues.get(path) : getValueAtPath(state, info$1.segments);
1833
+ }
1834
+ tracker.lastCheckedValues.clear();
1835
+ }
1836
+ /**
1837
+ * @internal
1838
+ */
1839
+ function hasDependencyChanges(tracker, state) {
1840
+ if (tracker.pathCache.size === 0) return true;
1841
+ tracker.lastCheckedValues.clear();
1842
+ for (const [path, info$1] of tracker.pathCache.entries()) {
1843
+ const currentValue = getValueAtPath(state, info$1.segments);
1844
+ tracker.lastCheckedValues.set(path, currentValue);
1845
+ if (!Object.is(currentValue, info$1.value)) {
1846
+ tracker.lastCheckedState = state;
1847
+ return true;
1848
+ }
1849
+ }
1850
+ tracker.lastCheckedState = state;
1851
+ return false;
1852
+ }
1853
+ /**
1854
+ * @internal
1855
+ */
1856
+ function hasTrackedData(tracker) {
1857
+ return tracker.proxyState.trackedPaths.size > 0 || tracker.pathCache.size > 0 || tracker.previousRenderPaths.size > 0;
1858
+ }
1859
+
1860
+ //#endregion
1861
+ //#region src/tracking/tracking-proxy.ts
1862
+ /**
1863
+ * Create a new tracking proxy state.
1864
+ */
1865
+ function createState() {
1866
+ return {
1867
+ dependencyState: createDependencyState(),
1868
+ getterState: createGetterState(),
1869
+ dependencies: /* @__PURE__ */ new Set(),
1870
+ isTracking: false
1871
+ };
1872
+ }
1873
+ /**
1874
+ * Start tracking on a tracking proxy.
1875
+ */
1876
+ function startTracking(tracker) {
1877
+ tracker.isTracking = true;
1878
+ tracker.dependencies.clear();
1879
+ tracker.getterState.isTracking = true;
1880
+ tracker.getterState.externalDependencies.clear();
1881
+ startDependency(tracker.dependencyState);
1882
+ }
1883
+ /**
1884
+ * Stop tracking and collect all dependencies.
1885
+ */
1886
+ function stopTracking(tracker, bloc) {
1887
+ tracker.isTracking = false;
1888
+ tracker.getterState.isTracking = false;
1889
+ capturePaths(tracker.dependencyState, bloc.state);
1890
+ commitTrackedGetters(tracker.getterState);
1891
+ const allDeps = new Set(tracker.dependencies);
1892
+ for (const dep of tracker.getterState.externalDependencies) allDeps.add(dep);
1893
+ tracker.getterState.externalDependencies.clear();
1894
+ return allDeps;
1895
+ }
1896
+ /**
1897
+ * Check if tracked state or getters have changed.
1898
+ */
1899
+ function hasChanges(tracker, bloc) {
1900
+ invalidateRenderCache(tracker.getterState);
1901
+ const stateChanged = hasDependencyChanges(tracker.dependencyState, bloc.state);
1902
+ const getterChanged = hasGetterChanges(bloc, tracker.getterState);
1903
+ return stateChanged || getterChanged;
1904
+ }
1905
+ const MAX_GETTER_DEPTH = BLAC_DEFAULTS.MAX_GETTER_DEPTH;
1906
+ /**
1907
+ * Create a tracking proxy for a bloc instance.
1908
+ * Tracks both state property access and getter access.
1909
+ */
1910
+ function createTrackingProxy(bloc, tracker) {
1911
+ tracker.dependencies.add(bloc);
1912
+ const stateProxyCache = /* @__PURE__ */ new WeakMap();
1913
+ return new Proxy(bloc, { get(target, prop, receiver) {
1914
+ if (prop === "state") {
1915
+ if (!tracker.isTracking) return target.state;
1916
+ const rawState = target.state;
1917
+ if (rawState === null || typeof rawState !== "object") return rawState;
1918
+ if (stateProxyCache.has(rawState)) return stateProxyCache.get(rawState);
1919
+ const stateProxy = createDependencyProxy(tracker.dependencyState, rawState);
1920
+ stateProxyCache.set(rawState, stateProxy);
1921
+ return stateProxy;
1922
+ }
1923
+ if (typeof prop === "symbol") return Reflect.get(target, prop, receiver);
1924
+ const value = Reflect.get(target, prop, receiver);
1925
+ if (typeof value === "function") return value.bind(target);
1926
+ if (tracker.isTracking && isGetter(target, prop)) {
1927
+ tracker.getterState.currentlyAccessing.add(prop);
1928
+ if (tracker.getterState.cacheValid && tracker.getterState.renderCache.has(prop)) {
1929
+ const cachedValue = tracker.getterState.renderCache.get(prop);
1930
+ tracker.getterState.trackedValues.set(prop, cachedValue);
1931
+ return cachedValue;
1932
+ }
1933
+ const context = getGetterExecutionContext();
1934
+ if (context.depth >= MAX_GETTER_DEPTH) {
1935
+ console.warn(`${BLAC_ERROR_PREFIX} Maximum getter depth (${MAX_GETTER_DEPTH}) exceeded. Possible circular dependency in getter "${String(prop)}" on ${target.constructor.name}.`);
1936
+ return;
1937
+ }
1938
+ if (context.visitedBlocs.has(target)) {
1939
+ console.warn(`${BLAC_ERROR_PREFIX} Circular dependency detected: getter "${String(prop)}" on ${target.constructor.name}.`);
1940
+ return;
1941
+ }
1942
+ const prevContext = {
1943
+ tracker: context.tracker,
1944
+ currentBloc: context.currentBloc,
1945
+ depth: context.depth,
1946
+ visitedBlocs: new Set(context.visitedBlocs)
1947
+ };
1948
+ context.tracker = tracker.getterState;
1949
+ context.currentBloc = target;
1950
+ context.depth++;
1951
+ context.visitedBlocs.add(target);
1952
+ try {
1953
+ const getterValue = getDescriptor(target, prop).get.call(target);
1954
+ tracker.getterState.trackedValues.set(prop, getterValue);
1955
+ return getterValue;
1956
+ } catch (error$1) {
1957
+ tracker.getterState.currentlyAccessing.delete(prop);
1958
+ throw error$1;
1959
+ } finally {
1960
+ context.tracker = prevContext.tracker;
1961
+ context.currentBloc = prevContext.currentBloc;
1962
+ context.depth = prevContext.depth;
1963
+ context.visitedBlocs = prevContext.visitedBlocs;
1964
+ }
1965
+ }
1966
+ return value;
1967
+ } });
1968
+ }
1969
+
1970
+ //#endregion
1971
+ //#region src/tracking/dependency-manager.ts
1972
+ /**
1973
+ * Manages subscriptions to state container dependencies.
1974
+ * Provides efficient sync mechanism to add/remove subscriptions
1975
+ * as dependencies change between callback invocations.
1976
+ */
1977
+ var DependencyManager = class {
1978
+ constructor() {
1979
+ this.subscriptions = /* @__PURE__ */ new Map();
1980
+ this.currentDeps = /* @__PURE__ */ new Set();
1981
+ }
1982
+ /**
1983
+ * Sync subscriptions with a new set of dependencies.
1984
+ * Adds subscriptions for new deps, removes subscriptions for stale deps.
1985
+ *
1986
+ * @param newDeps - The new set of dependencies to subscribe to
1987
+ * @param onChange - Callback to invoke when any dependency changes
1988
+ * @param exclude - Optional instance to exclude from subscriptions (e.g., primary bloc)
1989
+ * @returns true if the dependency set changed, false if unchanged
1990
+ */
1991
+ sync(newDeps, onChange, exclude) {
1992
+ const filteredNewDeps = /* @__PURE__ */ new Set();
1993
+ for (const dep of newDeps) if (dep !== exclude && !dep.isDisposed) filteredNewDeps.add(dep);
1994
+ if (this.areSetsEqual(this.currentDeps, filteredNewDeps)) return false;
1995
+ for (const dep of this.currentDeps) if (!filteredNewDeps.has(dep)) {
1996
+ const unsub = this.subscriptions.get(dep);
1997
+ if (unsub) {
1998
+ unsub();
1999
+ this.subscriptions.delete(dep);
2000
+ }
2001
+ }
2002
+ for (const dep of filteredNewDeps) if (!this.currentDeps.has(dep) && !this.subscriptions.has(dep)) {
2003
+ const unsub = dep.subscribe(onChange);
2004
+ this.subscriptions.set(dep, unsub);
2005
+ }
2006
+ this.currentDeps = filteredNewDeps;
2007
+ return true;
2008
+ }
2009
+ /**
2010
+ * Add a single dependency subscription.
2011
+ */
2012
+ add(dep, onChange) {
2013
+ if (this.subscriptions.has(dep) || dep.isDisposed) return;
2014
+ const unsub = dep.subscribe(onChange);
2015
+ this.subscriptions.set(dep, unsub);
2016
+ this.currentDeps.add(dep);
2017
+ }
2018
+ /**
2019
+ * Check if a dependency is currently subscribed.
2020
+ */
2021
+ has(dep) {
2022
+ return this.currentDeps.has(dep);
2023
+ }
2024
+ /**
2025
+ * Get the current set of dependencies.
2026
+ */
2027
+ getDependencies() {
2028
+ return new Set(this.currentDeps);
2029
+ }
2030
+ /**
2031
+ * Clean up all active subscriptions.
2032
+ */
2033
+ cleanup() {
2034
+ for (const unsub of this.subscriptions.values()) unsub();
2035
+ this.subscriptions.clear();
2036
+ this.currentDeps.clear();
2037
+ }
2038
+ areSetsEqual(a, b) {
2039
+ if (a.size !== b.size) return false;
2040
+ for (const item of a) if (!b.has(item)) return false;
2041
+ return true;
2042
+ }
2043
+ };
2044
+
2045
+ //#endregion
2046
+ //#region src/tracking/tracked.ts
2047
+ /**
2048
+ * Run a callback while tracking all bloc dependencies accessed.
2049
+ * Returns both the result and the set of discovered dependencies.
2050
+ *
2051
+ * @example
2052
+ * ```ts
2053
+ * const { result, dependencies } = tracked(() => {
2054
+ * const user = ensure(UserBloc);
2055
+ * return user.fullName; // getter that may access other blocs
2056
+ * });
2057
+ * // dependencies contains UserBloc + any blocs accessed in fullName getter
2058
+ * ```
2059
+ */
2060
+ function tracked(callback, options) {
2061
+ const tracker = createState();
2062
+ startTracking(tracker);
2063
+ let result;
2064
+ try {
2065
+ result = callback();
2066
+ } finally {
2067
+ stopTracking(tracker, { state: null });
2068
+ }
2069
+ const dependencies = new Set(tracker.dependencies);
2070
+ for (const dep of tracker.getterState.externalDependencies) dependencies.add(dep);
2071
+ if (options?.exclude) dependencies.delete(options.exclude);
2072
+ return {
2073
+ result,
2074
+ dependencies
2075
+ };
2076
+ }
2077
+ /**
2078
+ * Context for running tracked callbacks with bloc proxies.
2079
+ * Provides methods to create proxies and check for changes.
2080
+ */
2081
+ var TrackedContext = class {
2082
+ constructor() {
2083
+ this.proxiedBlocs = /* @__PURE__ */ new WeakMap();
2084
+ this.primaryBlocs = /* @__PURE__ */ new Set();
2085
+ this.tracker = createState();
2086
+ }
2087
+ /**
2088
+ * Get a tracking proxy for a bloc instance.
2089
+ * The proxy will track state and getter accesses.
2090
+ */
2091
+ proxy(bloc) {
2092
+ const cached = this.proxiedBlocs.get(bloc);
2093
+ if (cached) return cached;
2094
+ const proxied = createTrackingProxy(bloc, this.tracker);
2095
+ this.proxiedBlocs.set(bloc, proxied);
2096
+ this.primaryBlocs.add(bloc);
2097
+ return proxied;
2098
+ }
2099
+ /**
2100
+ * Start tracking for a new callback execution.
2101
+ */
2102
+ start() {
2103
+ startTracking(this.tracker);
2104
+ }
2105
+ /**
2106
+ * Stop tracking and get discovered dependencies.
2107
+ * Excludes primary blocs (those explicitly proxied via proxy()).
2108
+ */
2109
+ stop() {
2110
+ const allDeps = /* @__PURE__ */ new Set();
2111
+ for (const bloc of this.primaryBlocs) {
2112
+ const deps = stopTracking(this.tracker, bloc);
2113
+ for (const dep of deps) if (!this.primaryBlocs.has(dep)) allDeps.add(dep);
2114
+ }
2115
+ for (const dep of this.tracker.getterState.externalDependencies) if (!this.primaryBlocs.has(dep)) allDeps.add(dep);
2116
+ return allDeps;
2117
+ }
2118
+ /**
2119
+ * Check if any tracked state or getters have changed.
2120
+ */
2121
+ changed() {
2122
+ for (const bloc of this.primaryBlocs) if (hasChanges(this.tracker, bloc)) return true;
2123
+ return false;
2124
+ }
2125
+ /**
2126
+ * Get all primary blocs (those explicitly proxied).
2127
+ */
2128
+ getPrimaryBlocs() {
2129
+ return new Set(this.primaryBlocs);
2130
+ }
2131
+ /**
2132
+ * Reset the context for reuse.
2133
+ */
2134
+ reset() {
2135
+ this.tracker = createState();
2136
+ this.proxiedBlocs = /* @__PURE__ */ new WeakMap();
2137
+ this.primaryBlocs.clear();
2138
+ }
2139
+ };
2140
+ /**
2141
+ * Create a new tracked context for manual control over tracking.
2142
+ */
2143
+ function createTrackedContext() {
2144
+ return new TrackedContext();
2145
+ }
2146
+
2147
+ //#endregion
2148
+ //#region src/adapter/framework-adapter.ts
2149
+ /**
2150
+ * Manages subscriptions to external bloc dependencies for getter tracking.
2151
+ * When a getter accesses another bloc's state, this manager ensures
2152
+ * re-renders occur when those external dependencies change.
2153
+ *
2154
+ * @deprecated Use DependencyManager from tracking module instead.
2155
+ * This class is kept for backward compatibility.
2156
+ */
2157
+ var ExternalDepsManager = class {
2158
+ constructor() {
2159
+ this.manager = new DependencyManager();
2160
+ }
2161
+ /**
2162
+ * Update subscriptions to external bloc dependencies.
2163
+ * Creates subscriptions to blocs accessed via getters.
2164
+ * @param getterTracker - The getter tracker state with external dependencies
2165
+ * @param rawInstance - The primary bloc instance (excluded from subscriptions)
2166
+ * @param onGetterChange - Callback to invoke when external dependency changes
2167
+ * @returns true if subscriptions were updated, false if unchanged
2168
+ */
2169
+ updateSubscriptions(getterState, rawInstance, onGetterChange) {
2170
+ if (!getterState?.externalDependencies) return false;
2171
+ const currentDeps = getterState.externalDependencies;
2172
+ const onExternalChange = () => {
2173
+ invalidateRenderCache(getterState);
2174
+ if (hasGetterChanges(rawInstance, getterState)) onGetterChange();
2175
+ };
2176
+ const changed = this.manager.sync(currentDeps, onExternalChange, rawInstance);
2177
+ clearExternalDependencies(getterState);
2178
+ return changed;
2179
+ }
2180
+ /**
2181
+ * Clean up all active subscriptions
2182
+ */
2183
+ cleanup() {
2184
+ this.manager.cleanup();
2185
+ }
2186
+ };
2187
+ /**
2188
+ * Create a subscribe function for auto-tracking mode.
2189
+ * Only triggers callback when tracked properties change.
2190
+ * @param instance - The state container instance
2191
+ * @param adapterState - The adapter state for tracking
2192
+ * @returns Subscribe function for use with useSyncExternalStore
2193
+ */
2194
+ function autoTrackSubscribe(instance$1, adapterState) {
2195
+ return (callback) => {
2196
+ return instance$1.subscribe(() => {
2197
+ const depState = adapterState.dependencyState || (adapterState.dependencyState = createDependencyState());
2198
+ const hasStateDeps = depState.pathCache && depState.pathCache.size > 0;
2199
+ const hasGetterDeps = adapterState.getterState && adapterState.getterState.trackedGetters.size > 0;
2200
+ const isPrimitiveState = instance$1.state !== null && typeof instance$1.state !== "object" && typeof instance$1.state !== "function";
2201
+ if (!hasStateDeps && !hasGetterDeps && !isPrimitiveState) return;
2202
+ let stateChanged = hasDependencyChanges(depState, instance$1.state);
2203
+ if (!hasStateDeps && hasGetterDeps) stateChanged = false;
2204
+ if (stateChanged) {
2205
+ callback();
2206
+ return;
2207
+ }
2208
+ if (hasGetterChanges(instance$1, adapterState.getterState)) callback();
2209
+ });
2210
+ };
2211
+ }
2212
+ /**
2213
+ * Create a subscribe function for manual dependency tracking mode.
2214
+ * Only triggers callback when dependencies array changes.
2215
+ * @param instance - The state container instance
2216
+ * @param adapterState - The adapter state for caching
2217
+ * @param config - Configuration with dependencies function
2218
+ * @returns Subscribe function for use with useSyncExternalStore
2219
+ */
2220
+ function manualDepsSubscribe(instance$1, adapterState, config) {
2221
+ return (callback) => {
2222
+ return instance$1.subscribe(() => {
2223
+ const newDeps = config.dependencies(instance$1.state, instance$1);
2224
+ if (!adapterState.manualDepsCache || !shallowEqual(adapterState.manualDepsCache, newDeps)) {
2225
+ adapterState.manualDepsCache = newDeps;
2226
+ callback();
2227
+ }
2228
+ });
2229
+ };
2230
+ }
2231
+ /**
2232
+ * Create a subscribe function for no-tracking mode.
2233
+ * Triggers callback on every state change.
2234
+ * @param instance - The state container instance
2235
+ * @returns Subscribe function for use with useSyncExternalStore
2236
+ */
2237
+ function noTrackSubscribe(instance$1) {
2238
+ return (callback) => instance$1.subscribe(callback);
2239
+ }
2240
+ /**
2241
+ * Create a snapshot function for auto-tracking mode.
2242
+ * Returns a proxied state that tracks property access.
2243
+ * @param instance - The state container instance
2244
+ * @param adapterState - The adapter state for tracking
2245
+ * @returns Snapshot function for use with useSyncExternalStore
2246
+ */
2247
+ function autoTrackSnapshot(instance$1, adapterState) {
2248
+ return () => {
2249
+ const depState = adapterState.dependencyState || (adapterState.dependencyState = createDependencyState());
2250
+ if (hasTrackedData(depState)) capturePaths(depState, instance$1.state);
2251
+ if (adapterState.getterState) {
2252
+ invalidateRenderCache(adapterState.getterState);
2253
+ commitTrackedGetters(adapterState.getterState);
2254
+ adapterState.getterState.isTracking = true;
2255
+ setActiveTracker(instance$1, adapterState.getterState);
2256
+ }
2257
+ startDependency(depState);
2258
+ return createDependencyProxy(depState, instance$1.state);
2259
+ };
2260
+ }
2261
+ /**
2262
+ * Create a snapshot function for manual dependency tracking mode.
2263
+ * Caches dependencies for comparison on next render.
2264
+ * @param instance - The state container instance
2265
+ * @param adapterState - The adapter state for caching
2266
+ * @param config - Configuration with dependencies function
2267
+ * @returns Snapshot function for use with useSyncExternalStore
2268
+ */
2269
+ function manualDepsSnapshot(instance$1, adapterState, config) {
2270
+ return () => {
2271
+ adapterState.manualDepsCache = config.dependencies(instance$1.state, instance$1);
2272
+ return instance$1.state;
2273
+ };
2274
+ }
2275
+ /**
2276
+ * Create a snapshot function for no-tracking mode.
2277
+ * Returns the raw state directly.
2278
+ * @param instance - The state container instance
2279
+ * @returns Snapshot function for use with useSyncExternalStore
2280
+ */
2281
+ function noTrackSnapshot(instance$1) {
2282
+ return () => instance$1.state;
2283
+ }
2284
+ /**
2285
+ * Initialize adapter state for auto-tracking mode.
2286
+ * Creates getter tracker and proxied bloc instance.
2287
+ * @param instance - The state container instance
2288
+ * @returns Initialized adapter state
2289
+ */
2290
+ function autoTrackInit(instance$1) {
2291
+ return {
2292
+ dependencyState: null,
2293
+ manualDepsCache: null,
2294
+ getterState: createGetterState(),
2295
+ proxiedBloc: createBlocProxy(instance$1)
2296
+ };
2297
+ }
2298
+ /**
2299
+ * Initialize adapter state for manual dependency tracking mode.
2300
+ * No proxy is created; bloc is used directly.
2301
+ * @param instance - The state container instance
2302
+ * @returns Initialized adapter state
2303
+ */
2304
+ function manualDepsInit(instance$1) {
2305
+ return {
2306
+ dependencyState: null,
2307
+ manualDepsCache: null,
2308
+ getterState: null,
2309
+ proxiedBloc: instance$1
2310
+ };
2311
+ }
2312
+ /**
2313
+ * Initialize adapter state for no-tracking mode.
2314
+ * No tracking or proxy is created.
2315
+ * @param instance - The state container instance
2316
+ * @returns Initialized adapter state
2317
+ */
2318
+ function noTrackInit(instance$1) {
2319
+ return {
2320
+ dependencyState: null,
2321
+ manualDepsCache: null,
2322
+ getterState: null,
2323
+ proxiedBloc: instance$1
2324
+ };
2325
+ }
2326
+ /**
2327
+ * Disable getter tracking after render phase completes.
2328
+ * Clears the active tracker to prevent tracking outside of render.
2329
+ * @param adapterState - The adapter state
2330
+ * @param rawInstance - The raw bloc instance
2331
+ */
2332
+ function disableGetterTracking(adapterState, rawInstance) {
2333
+ if (adapterState.getterState) {
2334
+ adapterState.getterState.isTracking = false;
2335
+ clearActiveTracker(rawInstance);
2336
+ }
2337
+ }
2338
+
2339
+ //#endregion
2340
+ //#region src/logging/Logger.ts
2341
+ /**
2342
+ * Log severity levels (lower number = higher severity)
2343
+ */
2344
+ let LogLevel = /* @__PURE__ */ function(LogLevel$1) {
2345
+ /** Critical errors that may cause application failure */
2346
+ LogLevel$1[LogLevel$1["ERROR"] = 0] = "ERROR";
2347
+ /** Warning conditions that should be addressed */
2348
+ LogLevel$1[LogLevel$1["WARN"] = 1] = "WARN";
2349
+ /** Informational messages about application state */
2350
+ LogLevel$1[LogLevel$1["INFO"] = 2] = "INFO";
2351
+ /** Detailed debugging information */
2352
+ LogLevel$1[LogLevel$1["DEBUG"] = 3] = "DEBUG";
2353
+ return LogLevel$1;
2354
+ }({});
2355
+ /**
2356
+ * Creates a logger instance with given configuration
2357
+ *
2358
+ * @param config - Logger configuration
2359
+ * @returns Logger instance with debug, info, warn, error, and configure methods
2360
+ *
2361
+ * @example
2362
+ * ```ts
2363
+ * const logger = createLogger({
2364
+ * enabled: true,
2365
+ * level: LogLevel.DEBUG,
2366
+ * output: (entry) => console.log(JSON.stringify(entry))
2367
+ * });
2368
+ * logger.debug('MyComponent', 'Rendering', { props: { foo: 'bar' } });
2369
+ * ```
2370
+ */
2371
+ function createLogger(config) {
2372
+ const shouldLog = (level) => {
2373
+ return config.enabled && config.level >= level;
2374
+ };
2375
+ const log = (level, context, message, data) => {
2376
+ try {
2377
+ const entry = {
2378
+ level,
2379
+ context,
2380
+ message,
2381
+ timestamp: Date.now(),
2382
+ ...data !== void 0 && { data: serialize(data) }
2383
+ };
2384
+ config.output(entry);
2385
+ } catch (e) {
2386
+ console.error("[BlacLogger] Error logging:", e);
2387
+ }
2388
+ };
2389
+ const serialize = (data) => {
2390
+ try {
2391
+ return JSON.parse(JSON.stringify(data));
2392
+ } catch {
2393
+ return String(data);
2394
+ }
2395
+ };
2396
+ return {
2397
+ debug: (context, message, data) => {
2398
+ if (shouldLog(LogLevel.DEBUG)) log("DEBUG", context, message, data);
2399
+ },
2400
+ info: (context, message, data) => {
2401
+ if (shouldLog(LogLevel.INFO)) log("INFO", context, message, data);
2402
+ },
2403
+ warn: (context, message, data) => {
2404
+ if (shouldLog(LogLevel.WARN)) log("WARN", context, message, data);
2405
+ },
2406
+ error: (context, message, data) => {
2407
+ if (shouldLog(LogLevel.ERROR)) log("ERROR", context, message, data);
2408
+ },
2409
+ configure: (opts) => {
2410
+ Object.assign(config, opts);
2411
+ }
2412
+ };
2413
+ }
2414
+ let currentConfig = {
2415
+ enabled: false,
2416
+ level: LogLevel.INFO,
2417
+ output: (entry) => console.log(JSON.stringify(entry))
2418
+ };
2419
+ let defaultLogger = createLogger(currentConfig);
2420
+ /**
2421
+ * Log a debug message (tree-shakeable export)
2422
+ * @param context - Context identifier (module or component name)
2423
+ * @param message - Log message
2424
+ * @param data - Optional structured data
2425
+ */
2426
+ const debug = (context, message, data) => defaultLogger.debug(context, message, data);
2427
+ /**
2428
+ * Log an info message (tree-shakeable export)
2429
+ * @param context - Context identifier (module or component name)
2430
+ * @param message - Log message
2431
+ * @param data - Optional structured data
2432
+ */
2433
+ const info = (context, message, data) => defaultLogger.info(context, message, data);
2434
+ /**
2435
+ * Log a warning message (tree-shakeable export)
2436
+ * @param context - Context identifier (module or component name)
2437
+ * @param message - Log message
2438
+ * @param data - Optional structured data
2439
+ */
2440
+ const warn = (context, message, data) => defaultLogger.warn(context, message, data);
2441
+ /**
2442
+ * Log an error message (tree-shakeable export)
2443
+ * @param context - Context identifier (module or component name)
2444
+ * @param message - Log message
2445
+ * @param data - Optional structured data
2446
+ */
2447
+ const error = (context, message, data) => defaultLogger.error(context, message, data);
2448
+ /**
2449
+ * Configuration function that recreates the default logger
2450
+ *
2451
+ * @param opts - Partial logger configuration
2452
+ *
2453
+ * @example
2454
+ * ```ts
2455
+ * configureLogger({ enabled: true, level: LogLevel.DEBUG });
2456
+ * ```
2457
+ */
2458
+ function configureLogger(opts) {
2459
+ currentConfig = {
2460
+ ...currentConfig,
2461
+ ...opts
2462
+ };
2463
+ defaultLogger = createLogger(currentConfig);
2464
+ }
2465
+
2466
+ //#endregion
2467
+ //#region src/config.ts
2468
+ const defaultConfig = {
2469
+ devMode: process.env.NODE_ENV !== "production",
2470
+ logger: {
2471
+ enabled: false,
2472
+ level: LogLevel.INFO
2473
+ }
2474
+ };
2475
+ let globalConfig = { ...defaultConfig };
2476
+ /**
2477
+ * Configure global defaults for @blac/core.
2478
+ *
2479
+ * @example
2480
+ * ```ts
2481
+ * import { configureBlac, LogLevel } from '@blac/core';
2482
+ *
2483
+ * configureBlac({
2484
+ * devMode: true,
2485
+ * logger: {
2486
+ * enabled: true,
2487
+ * level: LogLevel.DEBUG
2488
+ * }
2489
+ * });
2490
+ * ```
2491
+ *
2492
+ * @param config - Partial configuration to merge with defaults
2493
+ */
2494
+ function configureBlac(config) {
2495
+ globalConfig = {
2496
+ ...globalConfig,
2497
+ ...config,
2498
+ logger: {
2499
+ ...globalConfig.logger,
2500
+ ...config.logger
2501
+ }
2502
+ };
2503
+ if (config.logger) configureLogger(config.logger);
2504
+ }
2505
+ /**
2506
+ * Get the current global configuration.
2507
+ * @internal
2508
+ */
2509
+ function getBlacConfig() {
2510
+ return globalConfig;
2511
+ }
2512
+ /**
2513
+ * Check if development mode is enabled.
2514
+ */
2515
+ function isDevMode() {
2516
+ return globalConfig.devMode;
2517
+ }
2518
+ /**
2519
+ * Reset configuration to defaults (useful for testing).
2520
+ * @internal
2521
+ */
2522
+ function resetBlacConfig() {
2523
+ globalConfig = { ...defaultConfig };
2524
+ configureLogger(defaultConfig.logger);
2525
+ }
2526
+
2527
+ //#endregion
2528
+ //#region src/decorators/blac.ts
2529
+ /**
2530
+ * Decorator to configure StateContainer classes.
2531
+ *
2532
+ * @example Decorator syntax (requires experimentalDecorators or TC39 decorators)
2533
+ * ```ts
2534
+ * @blac({ isolated: true })
2535
+ * class FormBloc extends Cubit<FormState> {}
2536
+ *
2537
+ * @blac({ keepAlive: true })
2538
+ * class AuthBloc extends Cubit<AuthState> {}
2539
+ *
2540
+ * @blac({ excludeFromDevTools: true })
2541
+ * class InternalBloc extends Cubit<InternalState> {}
2542
+ * ```
2543
+ *
2544
+ * @example Function syntax (no decorator support needed)
2545
+ * ```ts
2546
+ * const FormBloc = blac({ isolated: true })(
2547
+ * class extends Cubit<FormState> {}
2548
+ * );
2549
+ * ```
2550
+ */
2551
+ function blac(options) {
2552
+ return function(target, _context) {
2553
+ if ("isolated" in options && options.isolated) target[BLAC_STATIC_PROPS.ISOLATED] = true;
2554
+ if ("keepAlive" in options && options.keepAlive) target[BLAC_STATIC_PROPS.KEEP_ALIVE] = true;
2555
+ if ("excludeFromDevTools" in options && options.excludeFromDevTools) target[BLAC_STATIC_PROPS.EXCLUDE_FROM_DEVTOOLS] = true;
2556
+ return target;
2557
+ };
2558
+ }
2559
+
2560
+ //#endregion
2561
+ //#region src/registry/acquire.ts
2562
+ function acquire(BlocClass, instanceKey, options) {
2563
+ return globalRegistry.acquire(BlocClass, instanceKey, {
2564
+ canCreate: true,
2565
+ countRef: true,
2566
+ props: options?.props
2567
+ });
2568
+ }
2569
+
2570
+ //#endregion
2571
+ //#region src/registry/borrow.ts
2572
+ function borrow(BlocClass, instanceKey) {
2573
+ return globalRegistry.borrow(BlocClass, instanceKey);
2574
+ }
2575
+ function borrowSafe(BlocClass, instanceKey) {
2576
+ return globalRegistry.borrowSafe(BlocClass, instanceKey);
2577
+ }
2578
+
2579
+ //#endregion
2580
+ //#region src/registry/ensure.ts
2581
+ function ensure(BlocClass, instanceKey) {
2582
+ return globalRegistry.ensure(BlocClass, instanceKey);
2583
+ }
2584
+
2585
+ //#endregion
2586
+ //#region src/registry/release.ts
2587
+ function release(BlocClass, instanceKey, forceDispose = false) {
2588
+ globalRegistry.release(BlocClass, instanceKey, forceDispose);
2589
+ }
2590
+
2591
+ //#endregion
2592
+ //#region src/registry/queries.ts
2593
+ function hasInstance(BlocClass, instanceKey) {
2594
+ return globalRegistry.hasInstance(BlocClass, instanceKey);
2595
+ }
2596
+ function getRefCount(BlocClass, instanceKey) {
2597
+ return globalRegistry.getRefCount(BlocClass, instanceKey);
2598
+ }
2599
+ function getAll(BlocClass) {
2600
+ return globalRegistry.getAll(BlocClass);
2601
+ }
2602
+ function forEach(BlocClass, callback) {
2603
+ globalRegistry.forEach(BlocClass, callback);
2604
+ }
2605
+
2606
+ //#endregion
2607
+ //#region src/registry/management.ts
2608
+ function clear(BlocClass) {
2609
+ globalRegistry.clear(BlocClass);
2610
+ }
2611
+ function clearAll() {
2612
+ globalRegistry.clearAll();
2613
+ }
2614
+ function register(BlocClass, isolated = false) {
2615
+ globalRegistry.register(BlocClass, isolated);
2616
+ }
2617
+
2618
+ //#endregion
2619
+ //#region src/registry/config.ts
2620
+ let _registry = globalRegistry;
2621
+ function getRegistry() {
2622
+ return _registry;
2623
+ }
2624
+ function setRegistry(registry) {
2625
+ _registry.clearAll();
2626
+ _registry = registry;
2627
+ }
2628
+ function getStats() {
2629
+ return _registry.getStats();
2630
+ }
2631
+
2632
+ //#endregion
2633
+ //#region src/waitUntil/errors.ts
2634
+ var WaitUntilTimeoutError = class extends Error {
2635
+ constructor(timeout) {
2636
+ super(`waitUntil timed out after ${timeout}ms`);
2637
+ this.name = "WaitUntilTimeoutError";
2638
+ }
2639
+ };
2640
+ var WaitUntilAbortedError = class extends Error {
2641
+ constructor() {
2642
+ super("waitUntil was aborted");
2643
+ this.name = "WaitUntilAbortedError";
2644
+ }
2645
+ };
2646
+ var WaitUntilDisposedError = class extends Error {
2647
+ constructor(blocName) {
2648
+ super(`waitUntil failed: ${blocName} was disposed while waiting`);
2649
+ this.name = "WaitUntilDisposedError";
2650
+ }
2651
+ };
2652
+
2653
+ //#endregion
2654
+ //#region src/waitUntil/waitUntil.ts
2655
+ function waitUntil(BlocClass, selectorOrPredicate, predicateOrOptions, maybeOptions) {
2656
+ if (typeof predicateOrOptions !== "function") return waitUntilSimple(BlocClass, selectorOrPredicate, predicateOrOptions);
2657
+ else return waitUntilSelector(BlocClass, selectorOrPredicate, predicateOrOptions, maybeOptions);
2658
+ }
2659
+ function waitUntilSimple(BlocClass, predicate, options) {
2660
+ const { instanceId = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY, timeout, signal } = options ?? {};
2661
+ return new Promise((resolve, reject) => {
2662
+ if (signal?.aborted) {
2663
+ reject(new WaitUntilAbortedError());
2664
+ return;
2665
+ }
2666
+ const bloc = ensure(BlocClass, instanceId);
2667
+ if (bloc.isDisposed) {
2668
+ reject(new WaitUntilDisposedError(BlocClass.name));
2669
+ return;
2670
+ }
2671
+ const tracker = createState();
2672
+ const proxiedBloc = createTrackingProxy(bloc, tracker);
2673
+ const externalDepsManager = new DependencyManager();
2674
+ const runPredicate = () => {
2675
+ startTracking(tracker);
2676
+ try {
2677
+ return predicate(proxiedBloc);
2678
+ } finally {
2679
+ const deps = stopTracking(tracker, bloc);
2680
+ for (const dep of tracker.getterState.externalDependencies) deps.add(dep);
2681
+ deps.delete(bloc);
2682
+ externalDepsManager.sync(deps, checkCondition, bloc);
2683
+ }
2684
+ };
2685
+ if (runPredicate()) {
2686
+ resolve(bloc);
2687
+ return;
2688
+ }
2689
+ let unsubscribe = null;
2690
+ let unsubscribeDispose = null;
2691
+ let timeoutId = null;
2692
+ let abortHandler = null;
2693
+ const cleanup = () => {
2694
+ unsubscribe?.();
2695
+ unsubscribeDispose?.();
2696
+ externalDepsManager.cleanup();
2697
+ if (timeoutId) clearTimeout(timeoutId);
2698
+ if (abortHandler && signal) signal.removeEventListener("abort", abortHandler);
2699
+ };
2700
+ function checkCondition() {
2701
+ try {
2702
+ if (runPredicate()) {
2703
+ cleanup();
2704
+ resolve(bloc);
2705
+ }
2706
+ } catch (error$1) {
2707
+ cleanup();
2708
+ reject(error$1);
2709
+ }
2710
+ }
2711
+ unsubscribe = bloc.subscribe(checkCondition);
2712
+ unsubscribeDispose = getRegistry().on("disposed", (instance$1) => {
2713
+ if (instance$1 === bloc) {
2714
+ cleanup();
2715
+ reject(new WaitUntilDisposedError(BlocClass.name));
2716
+ }
2717
+ });
2718
+ if (timeout !== void 0) timeoutId = setTimeout(() => {
2719
+ cleanup();
2720
+ reject(new WaitUntilTimeoutError(timeout));
2721
+ }, timeout);
2722
+ if (signal) {
2723
+ abortHandler = () => {
2724
+ cleanup();
2725
+ reject(new WaitUntilAbortedError());
2726
+ };
2727
+ signal.addEventListener("abort", abortHandler);
2728
+ }
2729
+ });
2730
+ }
2731
+ function waitUntilSelector(BlocClass, selector, predicate, options) {
2732
+ const { instanceId = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY, timeout, signal } = options ?? {};
2733
+ return new Promise((resolve, reject) => {
2734
+ if (signal?.aborted) {
2735
+ reject(new WaitUntilAbortedError());
2736
+ return;
2737
+ }
2738
+ const bloc = ensure(BlocClass, instanceId);
2739
+ if (bloc.isDisposed) {
2740
+ reject(new WaitUntilDisposedError(BlocClass.name));
2741
+ return;
2742
+ }
2743
+ const tracker = createState();
2744
+ const proxiedBloc = createTrackingProxy(bloc, tracker);
2745
+ const externalDepsManager = new DependencyManager();
2746
+ const runSelector = () => {
2747
+ startTracking(tracker);
2748
+ try {
2749
+ const value = selector(proxiedBloc);
2750
+ return {
2751
+ value,
2752
+ matches: predicate(value)
2753
+ };
2754
+ } finally {
2755
+ const deps = stopTracking(tracker, bloc);
2756
+ for (const dep of tracker.getterState.externalDependencies) deps.add(dep);
2757
+ deps.delete(bloc);
2758
+ externalDepsManager.sync(deps, checkCondition, bloc);
2759
+ }
2760
+ };
2761
+ const initial = runSelector();
2762
+ if (initial.matches) {
2763
+ resolve(initial.value);
2764
+ return;
2765
+ }
2766
+ let unsubscribe = null;
2767
+ let unsubscribeDispose = null;
2768
+ let timeoutId = null;
2769
+ let abortHandler = null;
2770
+ const cleanup = () => {
2771
+ unsubscribe?.();
2772
+ unsubscribeDispose?.();
2773
+ externalDepsManager.cleanup();
2774
+ if (timeoutId) clearTimeout(timeoutId);
2775
+ if (abortHandler && signal) signal.removeEventListener("abort", abortHandler);
2776
+ };
2777
+ function checkCondition() {
2778
+ try {
2779
+ const result = runSelector();
2780
+ if (result.matches) {
2781
+ cleanup();
2782
+ resolve(result.value);
2783
+ }
2784
+ } catch (error$1) {
2785
+ cleanup();
2786
+ reject(error$1);
2787
+ }
2788
+ }
2789
+ unsubscribe = bloc.subscribe(checkCondition);
2790
+ unsubscribeDispose = getRegistry().on("disposed", (instance$1) => {
2791
+ if (instance$1 === bloc) {
2792
+ cleanup();
2793
+ reject(new WaitUntilDisposedError(BlocClass.name));
2794
+ }
2795
+ });
2796
+ if (timeout !== void 0) timeoutId = setTimeout(() => {
2797
+ cleanup();
2798
+ reject(new WaitUntilTimeoutError(timeout));
2799
+ }, timeout);
2800
+ if (signal) {
2801
+ abortHandler = () => {
2802
+ cleanup();
2803
+ reject(new WaitUntilAbortedError());
2804
+ };
2805
+ signal.addEventListener("abort", abortHandler);
2806
+ }
2807
+ });
2808
+ }
2809
+
2810
+ //#endregion
2811
+ //#region src/watch/watch.ts
2812
+ const STOP = Symbol("watch.STOP");
2813
+ const BLOC_REF_MARKER = Symbol("BlocRef");
2814
+ /**
2815
+ * Create a reference to a specific bloc instance.
2816
+ *
2817
+ * @example
2818
+ * ```ts
2819
+ * watch(instance(UserBloc, 'user-123'), (userBloc) => {
2820
+ * console.log(userBloc.state.name);
2821
+ * });
2822
+ * ```
2823
+ */
2824
+ function instance(BlocClass, instanceId) {
2825
+ return {
2826
+ [BLOC_REF_MARKER]: true,
2827
+ blocClass: BlocClass,
2828
+ instanceId
2829
+ };
2830
+ }
2831
+ function isBlocRef(input) {
2832
+ return typeof input === "object" && input !== null && BLOC_REF_MARKER in input;
2833
+ }
2834
+ function resolveBloc(input) {
2835
+ if (isBlocRef(input)) return ensure(input.blocClass, input.instanceId);
2836
+ return ensure(input, BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY);
2837
+ }
2838
+ function isArray(input) {
2839
+ return Array.isArray(input);
2840
+ }
2841
+ function watchImpl(blocsOrBloc, callback) {
2842
+ const isSingle = !isArray(blocsOrBloc);
2843
+ const instances = (isSingle ? [blocsOrBloc] : blocsOrBloc).map(resolveBloc);
2844
+ const tracker = createState();
2845
+ const proxiedInstances = instances.map((inst) => createTrackingProxy(inst, tracker));
2846
+ const externalDepsManager = new DependencyManager();
2847
+ let disposed = false;
2848
+ const primarySubscriptions = [];
2849
+ const cleanup = () => {
2850
+ if (disposed) return;
2851
+ disposed = true;
2852
+ primarySubscriptions.forEach((unsub) => unsub());
2853
+ externalDepsManager.cleanup();
2854
+ };
2855
+ const runCallback = () => {
2856
+ if (disposed) return;
2857
+ startTracking(tracker);
2858
+ let result;
2859
+ try {
2860
+ result = callback(isSingle ? proxiedInstances[0] : proxiedInstances);
2861
+ } finally {
2862
+ const externalDeps = /* @__PURE__ */ new Set();
2863
+ for (const inst of instances) {
2864
+ const deps = stopTracking(tracker, inst);
2865
+ for (const dep of deps) externalDeps.add(dep);
2866
+ }
2867
+ for (const dep of tracker.getterState.externalDependencies) externalDeps.add(dep);
2868
+ for (const inst of instances) externalDeps.delete(inst);
2869
+ externalDepsManager.sync(externalDeps, runCallback);
2870
+ }
2871
+ if (result === STOP) cleanup();
2872
+ };
2873
+ const onChange = () => {
2874
+ if (disposed) return;
2875
+ runCallback();
2876
+ };
2877
+ for (const inst of instances) primarySubscriptions.push(inst.subscribe(onChange));
2878
+ runCallback();
2879
+ return cleanup;
2880
+ }
2881
+ const watch = Object.assign(watchImpl, { STOP });
2882
+
2883
+ //#endregion
2884
+ exports.BLAC_DEFAULTS = BLAC_DEFAULTS;
2885
+ exports.BLAC_ERROR_PREFIX = BLAC_ERROR_PREFIX;
2886
+ exports.BLAC_ID_PATTERNS = BLAC_ID_PATTERNS;
2887
+ exports.BLAC_STATIC_PROPS = BLAC_STATIC_PROPS;
2888
+ exports.Cubit = Cubit;
2889
+ exports.DependencyManager = DependencyManager;
2890
+ exports.ExternalDepsManager = ExternalDepsManager;
2891
+ exports.LogLevel = LogLevel;
2892
+ exports.PluginManager = PluginManager;
2893
+ exports.STATELESS_MARKER = STATELESS_MARKER;
2894
+ exports.StateContainer = StateContainer;
2895
+ exports.StateContainerRegistry = StateContainerRegistry;
2896
+ exports.StatelessCubit = StatelessCubit;
2897
+ exports.StatelessVertex = StatelessVertex;
2898
+ exports.TrackedContext = TrackedContext;
2899
+ exports.Vertex = Vertex;
2900
+ exports.WaitUntilAbortedError = WaitUntilAbortedError;
2901
+ exports.WaitUntilDisposedError = WaitUntilDisposedError;
2902
+ exports.WaitUntilTimeoutError = WaitUntilTimeoutError;
2903
+ exports.__resetIdCounters = __resetIdCounters;
2904
+ exports.acquire = acquire;
2905
+ exports.autoTrackInit = autoTrackInit;
2906
+ exports.autoTrackSnapshot = autoTrackSnapshot;
2907
+ exports.autoTrackSubscribe = autoTrackSubscribe;
2908
+ exports.blac = blac;
2909
+ exports.borrow = borrow;
2910
+ exports.borrowSafe = borrowSafe;
2911
+ exports.capturePaths = capturePaths;
2912
+ exports.clear = clear;
2913
+ exports.clearActiveTracker = clearActiveTracker;
2914
+ exports.clearAll = clearAll;
2915
+ exports.clearExternalDependencies = clearExternalDependencies;
2916
+ exports.commitTrackedGetters = commitTrackedGetters;
2917
+ exports.configureBlac = configureBlac;
2918
+ exports.configureLogger = configureLogger;
2919
+ exports.createArrayProxy = createArrayProxy;
2920
+ exports.createBlocProxy = createBlocProxy;
2921
+ exports.createDependencyProxy = createDependencyProxy;
2922
+ exports.createDependencyState = createDependencyState;
2923
+ exports.createForTarget = createForTarget;
2924
+ exports.createGetterState = createGetterState;
2925
+ exports.createIdGenerator = createIdGenerator;
2926
+ exports.createInternal = createInternal;
2927
+ exports.createLogger = createLogger;
2928
+ exports.createPluginManager = createPluginManager;
2929
+ exports.createProxyState = createProxyState;
2930
+ exports.createTrackedContext = createTrackedContext;
2931
+ exports.createTrackingProxy = createTrackingProxy;
2932
+ exports.createTrackingProxyState = createState;
2933
+ exports.debug = debug;
2934
+ exports.disableGetterTracking = disableGetterTracking;
2935
+ exports.ensure = ensure;
2936
+ exports.error = error;
2937
+ exports.forEach = forEach;
2938
+ exports.generateId = generateId;
2939
+ exports.generateIsolatedKey = generateIsolatedKey;
2940
+ exports.generateSimpleId = generateSimpleId;
2941
+ exports.getActiveTracker = getActiveTracker;
2942
+ exports.getAll = getAll;
2943
+ exports.getBlacConfig = getBlacConfig;
2944
+ exports.getDescriptor = getDescriptor;
2945
+ exports.getGetterExecutionContext = getGetterExecutionContext;
2946
+ exports.getPluginManager = getPluginManager;
2947
+ exports.getRefCount = getRefCount;
2948
+ exports.getRegistry = getRegistry;
2949
+ exports.getStaticProp = getStaticProp;
2950
+ exports.getStats = getStats;
2951
+ exports.getValueAtPath = getValueAtPath;
2952
+ exports.globalRegistry = globalRegistry;
2953
+ exports.hasDependencyChanges = hasDependencyChanges;
2954
+ exports.hasGetterChanges = hasGetterChanges;
2955
+ exports.hasInitHook = hasInitHook;
2956
+ exports.hasInstance = hasInstance;
2957
+ exports.hasTrackedData = hasTrackedData;
2958
+ exports.hasTrackingProxyChanges = hasChanges;
2959
+ exports.info = info;
2960
+ exports.instance = instance;
2961
+ exports.invalidateRenderCache = invalidateRenderCache;
2962
+ exports.isDevMode = isDevMode;
2963
+ exports.isExcludedFromDevTools = isExcludedFromDevTools;
2964
+ exports.isGetter = isGetter;
2965
+ exports.isIsolatedClass = isIsolatedClass;
2966
+ exports.isIsolatedKey = isIsolatedKey;
2967
+ exports.isKeepAliveClass = isKeepAliveClass;
2968
+ exports.isProxyable = isProxyable;
2969
+ exports.isStatelessClass = isStatelessClass;
2970
+ exports.manualDepsInit = manualDepsInit;
2971
+ exports.manualDepsSnapshot = manualDepsSnapshot;
2972
+ exports.manualDepsSubscribe = manualDepsSubscribe;
2973
+ exports.noTrackInit = noTrackInit;
2974
+ exports.noTrackSnapshot = noTrackSnapshot;
2975
+ exports.noTrackSubscribe = noTrackSubscribe;
2976
+ exports.parsePath = parsePath;
2977
+ exports.register = register;
2978
+ exports.release = release;
2979
+ exports.resetBlacConfig = resetBlacConfig;
2980
+ exports.resetGetterState = resetGetterState;
2981
+ exports.setActiveTracker = setActiveTracker;
2982
+ exports.setRegistry = setRegistry;
2983
+ exports.shallowEqual = shallowEqual;
2984
+ exports.startDependency = startDependency;
2985
+ exports.startProxy = startProxy;
2986
+ exports.startTrackingProxy = startTracking;
2987
+ exports.stopProxy = stopProxy;
2988
+ exports.stopTrackingProxy = stopTracking;
2989
+ exports.tracked = tracked;
2990
+ exports.waitUntil = waitUntil;
2991
+ exports.warn = warn;
2992
+ exports.watch = watch;
2993
+ //# sourceMappingURL=index.cjs.map