@blac/core 2.0.20 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/dist/StateContainerRegistry-C75QpeaO.cjs +1260 -0
  2. package/dist/StateContainerRegistry-C75QpeaO.cjs.map +1 -0
  3. package/dist/StateContainerRegistry-DL5Ai7wh.js +1153 -0
  4. package/dist/StateContainerRegistry-DL5Ai7wh.js.map +1 -0
  5. package/dist/StateContainerRegistry-DWOzx7Gd.js +1154 -0
  6. package/dist/StateContainerRegistry-DWOzx7Gd.js.map +1 -0
  7. package/dist/StateContainerRegistry-G81GcCRm.cjs +1261 -0
  8. package/dist/StateContainerRegistry-G81GcCRm.cjs.map +1 -0
  9. package/dist/acquire-CE0uq0Dx.cjs +46 -0
  10. package/dist/acquire-CE0uq0Dx.cjs.map +1 -0
  11. package/dist/acquire-CU0u8BMn.js +35 -0
  12. package/dist/acquire-CU0u8BMn.js.map +1 -0
  13. package/dist/acquire-CkgLJ8WL.cjs +46 -0
  14. package/dist/acquire-CkgLJ8WL.cjs.map +1 -0
  15. package/dist/acquire-DTvfYJ0y.js +35 -0
  16. package/dist/acquire-DTvfYJ0y.js.map +1 -0
  17. package/dist/config-C1T6Jw7n.cjs +32 -0
  18. package/dist/config-C1T6Jw7n.cjs.map +1 -0
  19. package/dist/config-D2A8ZYRM.js +16 -0
  20. package/dist/config-D2A8ZYRM.js.map +1 -0
  21. package/dist/config-D34BkraU.cjs +32 -0
  22. package/dist/config-D34BkraU.cjs.map +1 -0
  23. package/dist/config-ZVy_yFZ3.js +16 -0
  24. package/dist/config-ZVy_yFZ3.js.map +1 -0
  25. package/dist/config.d.cts +7 -3
  26. package/dist/config.d.ts +7 -3
  27. package/dist/constants.d.cts +2 -13
  28. package/dist/constants.d.ts +2 -13
  29. package/dist/core/StateContainer.d.ts +21 -0
  30. package/dist/core/StateContainerRegistry.d.ts +48 -5
  31. package/dist/debug.cjs +3 -3
  32. package/dist/debug.js +3 -3
  33. package/dist/decorators/blac.d.ts +2 -0
  34. package/dist/ensure-11-asM1e.js +677 -0
  35. package/dist/ensure-11-asM1e.js.map +1 -0
  36. package/dist/ensure-BEeY5Ab7.js +673 -0
  37. package/dist/ensure-BEeY5Ab7.js.map +1 -0
  38. package/dist/ensure-D3WWWwMo.cjs +714 -0
  39. package/dist/ensure-D3WWWwMo.cjs.map +1 -0
  40. package/dist/ensure-r1C_7K6_.cjs +718 -0
  41. package/dist/ensure-r1C_7K6_.cjs.map +1 -0
  42. package/dist/events.d.cts +42 -0
  43. package/dist/events.d.ts +42 -0
  44. package/dist/index.cjs +60 -6
  45. package/dist/index.cjs.map +1 -1
  46. package/dist/index.d.cts +4 -3
  47. package/dist/index.d.ts +4 -3
  48. package/dist/index.js +56 -8
  49. package/dist/index.js.map +1 -1
  50. package/dist/management-8x1OVMi6.js +38 -0
  51. package/dist/management-8x1OVMi6.js.map +1 -0
  52. package/dist/management-BZgsi29F.js +38 -0
  53. package/dist/management-BZgsi29F.js.map +1 -0
  54. package/dist/management-Dg2SxUb6.cjs +85 -0
  55. package/dist/management-Dg2SxUb6.cjs.map +1 -0
  56. package/dist/management-hkY13log.cjs +85 -0
  57. package/dist/management-hkY13log.cjs.map +1 -0
  58. package/dist/plugins.cjs +1 -1
  59. package/dist/plugins.js +1 -1
  60. package/dist/registry/index.d.ts +1 -1
  61. package/dist/registry/release.d.ts +17 -1
  62. package/dist/testing.cjs +4 -4
  63. package/dist/testing.js +4 -4
  64. package/dist/utils/static-props.d.ts +5 -0
  65. package/dist/utils/structural-key.d.ts +11 -1
  66. package/dist/watch/index.d.ts +1 -0
  67. package/dist/watch/observe.d.ts +13 -0
  68. package/dist/watch-BDiwCPmb.js +108 -0
  69. package/dist/watch-BDiwCPmb.js.map +1 -0
  70. package/dist/watch-BW7gYiDf.js +108 -0
  71. package/dist/watch-BW7gYiDf.js.map +1 -0
  72. package/dist/watch-aoNLQAXp.cjs +119 -0
  73. package/dist/watch-aoNLQAXp.cjs.map +1 -0
  74. package/dist/watch-entry.cjs +1 -1
  75. package/dist/watch-entry.js +1 -1
  76. package/dist/watch-lEco5Tbl.cjs +119 -0
  77. package/dist/watch-lEco5Tbl.cjs.map +1 -0
  78. package/package.json +3 -3
@@ -0,0 +1,1260 @@
1
+ let _dirtytalk_structural = require("@dirtytalk/structural");
2
+ //#region src/config.ts
3
+ /**
4
+ * Default equality: shallow per-key `Object.is` comparison.
5
+ * Falls through to `false` for primitives/null so reference-only state still
6
+ * behaves correctly.
7
+ */
8
+ const shallowEqualState = (prev, next) => {
9
+ if (Object.is(prev, next)) return true;
10
+ if (typeof prev !== "object" || prev === null) return false;
11
+ if (typeof next !== "object" || next === null) return false;
12
+ const prevKeys = Object.keys(prev);
13
+ if (prevKeys.length !== Object.keys(next).length) return false;
14
+ for (let i = 0; i < prevKeys.length; i++) {
15
+ const key = prevKeys[i];
16
+ if (!Object.is(prev[key], next[key])) return false;
17
+ }
18
+ return true;
19
+ };
20
+ const defaultConfig = {
21
+ equality: shallowEqualState,
22
+ maxInstancesPerType: 1e5,
23
+ maxRefsPerInstance: 1e5,
24
+ maxEmitsPerSecond: 1e3
25
+ };
26
+ let globalConfig = { ...defaultConfig };
27
+ /**
28
+ * Configure global defaults for @blac/core.
29
+ *
30
+ * @example
31
+ * ```ts
32
+ * import { configureBlac, shallowEqualState } from '@blac/core';
33
+ *
34
+ * // Swap in a deep-equality check for all blocs
35
+ * configureBlac({ equality: myDeepEqual });
36
+ * ```
37
+ */
38
+ function configureBlac(config) {
39
+ globalConfig = {
40
+ ...globalConfig,
41
+ ...config
42
+ };
43
+ }
44
+ /**
45
+ * Get the current global configuration.
46
+ * @internal
47
+ */
48
+ function getBlacConfig() {
49
+ return globalConfig;
50
+ }
51
+ /**
52
+ * Reset configuration to defaults (useful for testing).
53
+ * @internal
54
+ */
55
+ function resetBlacConfig() {
56
+ globalConfig = { ...defaultConfig };
57
+ }
58
+ //#endregion
59
+ //#region src/plugin/PluginManager.ts
60
+ /**
61
+ * Manages plugin lifecycle for the BlaC state management system.
62
+ *
63
+ * The manager hooks into two surfaces:
64
+ *
65
+ * 1. **Registry lifecycle events** (`created`, `disposed`, `refAcquired`,
66
+ * `refReleased`, `depsChanged`) — synchronous, fired by the registry.
67
+ *
68
+ * 2. **Per-container channel flushes** — microtask-coalesced. For each
69
+ * container, the manager subscribes once at create-time with
70
+ * `ALL_PATHS` interest and stashes `prevState`. On every flush it
71
+ * captures the new state + the changed `PathSet` and dispatches
72
+ * `onStateChange(ctx, prev, next, paths)` to every enabled plugin.
73
+ *
74
+ * The `ALL_PATHS` subscription cost: plugins counted as a consumer with
75
+ * `ALL_PATHS` interest will defeat the single-consumer-skip optimization
76
+ * in `StructuralContainer`. This is the intended trade-off — devtools /
77
+ * persist plugins genuinely want every change, and stateful plugins
78
+ * (logging) can decode `paths` via `container.interner.lookup(id)` to log
79
+ * only relevant fields. Plugins that want low overhead should remain
80
+ * uninstalled or environment-gated.
81
+ *
82
+ * @example
83
+ * ```ts
84
+ * const manager = createPluginManager(registry);
85
+ * manager.install(myPlugin, { environment: 'development' });
86
+ * ```
87
+ */
88
+ var PluginManager = class {
89
+ /**
90
+ * Create a new PluginManager
91
+ * @param registry - The StateContainerRegistry to monitor for lifecycle events
92
+ */
93
+ constructor(registry) {
94
+ this.plugins = /* @__PURE__ */ new Map();
95
+ this.lifecycleUnsubscribers = [];
96
+ this.containerBridges = /* @__PURE__ */ new WeakMap();
97
+ this.registry = registry;
98
+ this.setupLifecycleHooks();
99
+ }
100
+ /**
101
+ * Install a plugin with optional configuration
102
+ * @param plugin - The plugin to install
103
+ * @param config - Optional plugin configuration
104
+ * @throws Error if plugin is already installed
105
+ */
106
+ install(plugin, config = {}) {
107
+ const effectiveConfig = {
108
+ enabled: true,
109
+ environment: "all",
110
+ ...config
111
+ };
112
+ if (!this.shouldEnablePlugin(effectiveConfig)) {
113
+ console.log(`[BlaC] Plugin "${plugin.name}" skipped (environment mismatch)`);
114
+ return;
115
+ }
116
+ if (this.plugins.has(plugin.name)) throw new Error(`Plugin "${plugin.name}" is already installed`);
117
+ const installContext = this.buildContext(void 0);
118
+ this.plugins.set(plugin.name, {
119
+ plugin,
120
+ config: effectiveConfig,
121
+ installContext
122
+ });
123
+ this.backfillPlugin(this.plugins.get(plugin.name));
124
+ if (plugin.onInstall) try {
125
+ plugin.onInstall(installContext);
126
+ } catch (error) {
127
+ console.error(`[BlaC] Error installing plugin "${plugin.name}":`, error);
128
+ this.plugins.delete(plugin.name);
129
+ throw error;
130
+ }
131
+ console.log(`[BlaC] Plugin "${plugin.name}" v${plugin.version} installed`);
132
+ }
133
+ /**
134
+ * Uninstall a plugin by name
135
+ * @param pluginName - The name of the plugin to uninstall
136
+ * @throws Error if plugin is not installed
137
+ */
138
+ uninstall(pluginName) {
139
+ const installed = this.plugins.get(pluginName);
140
+ if (!installed) throw new Error(`Plugin "${pluginName}" is not installed`);
141
+ if (installed.plugin.onUninstall) try {
142
+ installed.plugin.onUninstall();
143
+ } catch (error) {
144
+ console.error(`[BlaC] Error uninstalling plugin "${pluginName}":`, error);
145
+ }
146
+ this.plugins.delete(pluginName);
147
+ console.log(`[BlaC] Plugin "${pluginName}" uninstalled`);
148
+ }
149
+ /**
150
+ * Get an installed plugin by name
151
+ * @param pluginName - The name of the plugin to retrieve
152
+ * @returns The plugin instance or undefined if not found
153
+ */
154
+ getPlugin(pluginName) {
155
+ return this.plugins.get(pluginName)?.plugin;
156
+ }
157
+ /**
158
+ * Get all installed plugins
159
+ * @returns Array of all installed plugins
160
+ */
161
+ getAllPlugins() {
162
+ return Array.from(this.plugins.values()).map((p) => p.plugin);
163
+ }
164
+ /**
165
+ * Check if a plugin is installed
166
+ * @param pluginName - The name of the plugin to check
167
+ * @returns true if the plugin is installed
168
+ */
169
+ hasPlugin(pluginName) {
170
+ return this.plugins.has(pluginName);
171
+ }
172
+ /**
173
+ * Uninstall all plugins
174
+ */
175
+ clear() {
176
+ for (const name of this.plugins.keys()) this.uninstall(name);
177
+ }
178
+ destroy() {
179
+ this.clear();
180
+ for (const unsub of this.lifecycleUnsubscribers) unsub();
181
+ this.lifecycleUnsubscribers = [];
182
+ }
183
+ /**
184
+ * Wire registry lifecycle events into plugin dispatch.
185
+ *
186
+ * `onStateChange` is NOT wired through `registry.on('stateChanged', …)` —
187
+ * that event lacks the `PathSet` payload. Instead, on each `created` we
188
+ * subscribe to the container's channel directly so we get
189
+ * `(paths)` and capture `(prev, next)` via the per-container snapshot.
190
+ */
191
+ setupLifecycleHooks() {
192
+ this.lifecycleUnsubscribers = [
193
+ this.registry.on("created", (instance) => {
194
+ this.attachStateBridge(instance);
195
+ this.notifyPlugins("onCreated", instance);
196
+ }),
197
+ this.registry.on("disposed", (instance) => {
198
+ this.notifyPlugins("onDestroyed", instance);
199
+ this.detachStateBridge(instance);
200
+ }),
201
+ this.registry.on("refAcquired", (instance, refId) => {
202
+ this.notifyPlugins("onRefAcquired", instance, refId);
203
+ }),
204
+ this.registry.on("refReleased", (instance, refId) => {
205
+ this.notifyPlugins("onRefReleased", instance, refId);
206
+ }),
207
+ this.registry.on("depsChanged", (instance, previousDeps, currentDeps) => {
208
+ this.notifyPlugins("onDepsChanged", instance, previousDeps, currentDeps);
209
+ }),
210
+ this.registry.on("hydrationChanged", (instance, status, previousStatus) => {
211
+ this.notifyPlugins("onHydrationChange", instance, status, previousStatus);
212
+ })
213
+ ];
214
+ }
215
+ /**
216
+ * Subscribe to the container's channel with `ALL_PATHS` interest, so we
217
+ * fire on every flush. Capture `prev` from the snapshot taken on the
218
+ * previous flush (or at create-time for the first flush) and pass the
219
+ * channel's `paths` argument straight through to plugins.
220
+ *
221
+ * Per-container bookkeeping is stored in a `WeakMap` keyed by the
222
+ * container itself, so a disposed/GC'd container drops cleanly.
223
+ */
224
+ attachStateBridge(container) {
225
+ if (this.containerBridges.has(container)) return;
226
+ const bridge = {
227
+ unsub: () => {},
228
+ prevState: container.state
229
+ };
230
+ this.containerBridges.set(container, bridge);
231
+ bridge.unsub = container.channel.subscribe(() => _dirtytalk_structural.ALL_PATHS, (paths) => this.dispatchStateChange(container, paths));
232
+ }
233
+ detachStateBridge(container) {
234
+ const bridge = this.containerBridges.get(container);
235
+ if (!bridge) return;
236
+ bridge.unsub();
237
+ this.containerBridges.delete(container);
238
+ }
239
+ /**
240
+ * Backfill a newly-installed plugin with the app's existing instances.
241
+ *
242
+ * Iterates every registered `Type` and its live instances (`getAll`
243
+ * already skips disposed), attaching the state bridge (idempotent — see
244
+ * `attachStateBridge`) and, if the plugin implements `onCreated`, invoking
245
+ * it directly for each instance. Scoped to this single plugin only — the
246
+ * broadcast `notifyPlugins` would re-notify *every* plugin of *every*
247
+ * instance, which is wrong here.
248
+ */
249
+ backfillPlugin(installed) {
250
+ const { plugin } = installed;
251
+ for (const Type of this.registry.getTypes()) for (const instance of this.registry.getAll(Type)) {
252
+ const container = instance;
253
+ this.attachStateBridge(container);
254
+ if (!plugin.onCreated) continue;
255
+ try {
256
+ plugin.onCreated(this.buildContext(container));
257
+ } catch (error) {
258
+ console.error(`[BlaC] Error in plugin "${plugin.name}" onCreated (backfill):`, error);
259
+ }
260
+ }
261
+ }
262
+ /**
263
+ * Channel-flush callback. Snapshots `next`, hands `(prev, next, paths)`
264
+ * to every enabled plugin's `onStateChange`, then updates `prevState`
265
+ * for the next flush.
266
+ *
267
+ * Note: `prev` is captured once and reused across plugins — every
268
+ * plugin sees the same `prev`/`next`/`paths` regardless of dispatch
269
+ * order, matching the "snapshot prev once per flush" invariant.
270
+ */
271
+ dispatchStateChange(container, paths) {
272
+ const bridge = this.containerBridges.get(container);
273
+ if (!bridge) return;
274
+ const prev = bridge.prevState;
275
+ const next = container.state;
276
+ bridge.prevState = next;
277
+ let ctx;
278
+ for (const { plugin, config } of this.plugins.values()) {
279
+ if (!config.enabled) continue;
280
+ const hook = plugin.onStateChange;
281
+ if (typeof hook !== "function") continue;
282
+ try {
283
+ ctx ??= this.buildContext(container);
284
+ hook.call(plugin, ctx, prev, next, paths);
285
+ } catch (error) {
286
+ console.error(`[BlaC] Error in plugin "${plugin.name}" onStateChange:`, error);
287
+ }
288
+ }
289
+ }
290
+ /**
291
+ * Notify all plugins of a lifecycle event.
292
+ *
293
+ * Builds a fresh `PluginContext` per dispatch (instance becomes
294
+ * `ctx.container`), so plugins can reach the focal bloc through
295
+ * `ctx.container`. The context is built lazily on the first matching
296
+ * hook and reused for every other plugin in this dispatch — zero
297
+ * builds if no enabled plugin implements `hookName`.
298
+ */
299
+ notifyPlugins(hookName, instance, ...extraArgs) {
300
+ let ctx;
301
+ for (const { plugin, config } of this.plugins.values()) {
302
+ if (!config.enabled) continue;
303
+ const hook = plugin[hookName];
304
+ if (typeof hook !== "function") continue;
305
+ try {
306
+ ctx ??= this.buildContext(instance);
307
+ hook.call(plugin, ctx, ...extraArgs);
308
+ } catch (error) {
309
+ console.error(`[BlaC] Error in plugin "${plugin.name}" ${hookName}:`, error);
310
+ }
311
+ }
312
+ }
313
+ /**
314
+ * Build a `PluginContext` for a given focal container. The context is
315
+ * cheap to build — its methods close over `this.registry` directly —
316
+ * so we create one per dispatch rather than caching per container.
317
+ * This sidesteps the lifetime question of "when do we evict a cached
318
+ * context?" and keeps `paths`-vs-`container` lifetimes cleanly
319
+ * separated.
320
+ */
321
+ buildContext(container) {
322
+ const registry = this.registry;
323
+ return {
324
+ container,
325
+ getInstanceMetadata: (instance) => {
326
+ return {
327
+ id: instance.$blac.id,
328
+ className: instance.constructor.name,
329
+ isDisposed: instance.$blac.disposed,
330
+ name: instance.$blac.name,
331
+ createdAt: instance.$blac.createdAt,
332
+ state: instance.state,
333
+ hydrationStatus: instance.$blac.hydration.status,
334
+ isHydrated: instance.$blac.hydration.isHydrated,
335
+ hydrationError: instance.$blac.hydration.error,
336
+ changedWhileHydrating: instance.$blac.hydration.changedWhileHydrating,
337
+ args: instance.args
338
+ };
339
+ },
340
+ getState: (instance) => {
341
+ return instance.state;
342
+ },
343
+ getHydrationStatus: (instance) => {
344
+ return instance.$blac.hydration.status;
345
+ },
346
+ startHydration: (instance) => {
347
+ instance.$blac.hydration.begin();
348
+ },
349
+ applyHydratedState: (instance, state) => {
350
+ return instance.$blac.hydration.apply(state);
351
+ },
352
+ finishHydration: (instance) => {
353
+ instance.$blac.hydration.finish();
354
+ },
355
+ failHydration: (instance, error) => {
356
+ instance.$blac.hydration.fail(error);
357
+ },
358
+ waitForHydration: (instance) => {
359
+ return instance.$blac.hydration.wait();
360
+ },
361
+ queryInstances: (typeClass) => {
362
+ return registry.getAll(typeClass);
363
+ },
364
+ getAllTypes: () => {
365
+ return registry.getTypes();
366
+ },
367
+ getStats: () => {
368
+ return registry.getStats();
369
+ },
370
+ getRefIds: (instanceId) => {
371
+ const entry = registry.findEntryById(instanceId);
372
+ return entry ? Array.from(entry.refs.keys()) : [];
373
+ }
374
+ };
375
+ }
376
+ /**
377
+ * Check if plugin should be enabled based on environment
378
+ */
379
+ shouldEnablePlugin(config) {
380
+ if (!config.enabled) return false;
381
+ if (config.environment === "all") return true;
382
+ return this.getCurrentEnvironment() === config.environment;
383
+ }
384
+ /**
385
+ * Get current environment
386
+ */
387
+ getCurrentEnvironment() {
388
+ if (typeof process !== "undefined") {
389
+ if (process.env.NODE_ENV === "test") return "test";
390
+ if (process.env.NODE_ENV === "production") return "production";
391
+ return "development";
392
+ }
393
+ return "development";
394
+ }
395
+ };
396
+ /**
397
+ * Create a plugin manager instance
398
+ * @param registry - The StateContainerRegistry to monitor for lifecycle events
399
+ * @returns A new PluginManager instance
400
+ */
401
+ function createPluginManager(registry) {
402
+ return new PluginManager(registry);
403
+ }
404
+ //#endregion
405
+ //#region src/constants.ts
406
+ /**
407
+ * Default configuration constants for BlaC
408
+ *
409
+ * Centralized location for all magic numbers and default values.
410
+ */
411
+ /**
412
+ * Default configuration constants for BlaC
413
+ */
414
+ const BLAC_DEFAULTS = {
415
+ /**
416
+ * Default instance key for shared instances
417
+ */
418
+ DEFAULT_INSTANCE_KEY: "default" };
419
+ /**
420
+ * Static property names for StateContainer classes
421
+ * Used for feature flags and configuration on bloc classes
422
+ */
423
+ const BLAC_STATIC_PROPS = {
424
+ /**
425
+ * Mark a bloc to never be auto-disposed (kept alive permanently)
426
+ */
427
+ KEEP_ALIVE: "keepAlive",
428
+ /**
429
+ * Exclude a bloc from DevTools reporting (prevents infinite loops)
430
+ */
431
+ EXCLUDE_FROM_DEVTOOLS: "__excludeFromDevTools",
432
+ /**
433
+ * Per-class equality function used to short-circuit `emit`/`patch` when the
434
+ * new state is structurally equal to the previous state. Falls back to the
435
+ * global `configureBlac({ equality })` value when unset.
436
+ */
437
+ EQUALITY: "__equality",
438
+ /**
439
+ * Per-class key function: `static key = (args) => string`.
440
+ * When set, the registry calls `Type.key(args)` to derive the instance key
441
+ * instead of using a structural hash of `args`. Allows blocs to ignore
442
+ * non-identity fields (e.g., `readonly` flags) while still keying by id.
443
+ */
444
+ KEY: "key",
445
+ /** Mark a bloc as always per-mount: `static isolated = true`. */
446
+ ISOLATED: "isolated"
447
+ };
448
+ /**
449
+ * Standard error message prefix
450
+ */
451
+ const BLAC_ERROR_PREFIX = "[BlaC]";
452
+ //#endregion
453
+ //#region src/utils/static-props.ts
454
+ /**
455
+ * Utility functions for accessing static properties on StateContainer classes
456
+ */
457
+ /**
458
+ * Get a static property from a class constructor
459
+ * Type-safe helper that avoids (Type as any) casts
460
+ *
461
+ * @param Type - The class constructor
462
+ * @param propName - The property name to access
463
+ * @param defaultValue - Optional default value if property is undefined
464
+ * @returns The property value or default
465
+ */
466
+ function getStaticProp(Type, propName, defaultValue) {
467
+ return Type[propName] ?? defaultValue;
468
+ }
469
+ /**
470
+ * Check if a class is marked as keepAlive.
471
+ * KeepAlive classes are never auto-disposed when ref count reaches 0.
472
+ * @param Type - The class constructor to check
473
+ * @returns true if the class has `static keepAlive = true`
474
+ */
475
+ function isKeepAliveClass(Type) {
476
+ return getStaticProp(Type, BLAC_STATIC_PROPS.KEEP_ALIVE) === true;
477
+ }
478
+ /**
479
+ * Check if a class should be excluded from DevTools.
480
+ * Used to prevent infinite loops when DevTools tracks itself.
481
+ * @param Type - The class constructor to check
482
+ * @returns true if the class has `static __excludeFromDevTools = true`
483
+ */
484
+ function isExcludedFromDevTools(Type) {
485
+ return getStaticProp(Type, BLAC_STATIC_PROPS.EXCLUDE_FROM_DEVTOOLS) === true;
486
+ }
487
+ /**
488
+ * Get the per-class equality function set via `@blac({ equality })`, if any.
489
+ * @param Type - The class constructor to check
490
+ * @returns the equality function or `undefined`
491
+ */
492
+ function getClassEquality(Type) {
493
+ const fn = getStaticProp(Type, BLAC_STATIC_PROPS.EQUALITY);
494
+ return typeof fn === "function" ? fn : void 0;
495
+ }
496
+ /**
497
+ * Get the per-class key function set via `@blac({ key })` or `static key = …`, if any.
498
+ * Used by the registry to derive a stable instance key from `args`.
499
+ * @param Type - The class constructor to check
500
+ * @returns the key function or `undefined`
501
+ */
502
+ function getClassKey(Type) {
503
+ const fn = getStaticProp(Type, BLAC_STATIC_PROPS.KEY, void 0);
504
+ return typeof fn === "function" ? fn : void 0;
505
+ }
506
+ /**
507
+ * Check if a class is marked as always-per-mount.
508
+ * @returns true if the class has `static isolated = true`
509
+ */
510
+ function isIsolatedClass(Type) {
511
+ return getStaticProp(Type, BLAC_STATIC_PROPS.ISOLATED) === true;
512
+ }
513
+ //#endregion
514
+ //#region src/utils/structural-key.ts
515
+ /**
516
+ * Deterministic, order-independent hash of serializable args.
517
+ * Sorts object keys so {a,b} === {b,a}.
518
+ *
519
+ * - Functions throw a friendly `[blac]` error — they must be passed via `deps`.
520
+ * - `Date` (and anything else with a `toJSON`) serializes via that `toJSON`
521
+ * (e.g. as an ISO string), since `JSON.stringify` calls it before the
522
+ * replacer ever sees the value — there's no cheap way to guard against
523
+ * non-plain objects here.
524
+ * - `BigInt` and circular args throw `JSON.stringify`'s own raw `TypeError`,
525
+ * not the friendly `[blac]` message.
526
+ * - `undefined` values inside objects are preserved via a reserved sentinel
527
+ * (rather than being dropped, which is `JSON.stringify`'s default and would
528
+ * let structurally different args collide on the same key).
529
+ */
530
+ const DEFAULT_STRUCTURAL_KEY = "default";
531
+ /** Reserved sentinel standing in for `undefined` values inside args objects. */
532
+ const UNDEFINED_SENTINEL = "\0undefined";
533
+ /**
534
+ * Produce a stable string key for serializable args.
535
+ * - `undefined` / `void` args → `'default'` sentinel (no-args blocs stay on the default key).
536
+ * - Object keys are sorted for order-independence.
537
+ * - Arrays keep their insertion order.
538
+ * - Functions throw — they must be passed via `deps`, not `args`.
539
+ */
540
+ function structuralKey(args) {
541
+ if (args === void 0 || args === null) return DEFAULT_STRUCTURAL_KEY;
542
+ return JSON.stringify(args, function(_k, v) {
543
+ if (typeof v === "function") throw new Error("[blac] args must be serializable; put refs/callbacks in `deps`");
544
+ if (v === void 0) return UNDEFINED_SENTINEL;
545
+ if (v && typeof v === "object" && !Array.isArray(v)) return Object.keys(v).sort().reduce((o, k) => {
546
+ o[k] = v[k];
547
+ return o;
548
+ }, {});
549
+ return v;
550
+ });
551
+ }
552
+ //#endregion
553
+ //#region src/core/symbols.ts
554
+ /**
555
+ * @internal Apply one owner's (consumer's) deps slice to an instance.
556
+ * Called by framework adapters (e.g. @blac/react useBloc) — not public API.
557
+ */
558
+ const APPLY_DEPS = Symbol("blac.applyDeps");
559
+ /**
560
+ * @internal Withdraw one owner's entire deps slice (consumer unmounted).
561
+ * Called by framework adapters — not public API.
562
+ */
563
+ const REMOVE_DEPS_OWNER = Symbol("blac.removeDepsOwner");
564
+ /**
565
+ * @internal Subscribe to this specific instance's own disposal, bypassing
566
+ * the global registry `'disposed'` event. Called by `watch()` — not public
567
+ * API.
568
+ */
569
+ const ON_DISPOSE = Symbol("blac.onDispose");
570
+ /**
571
+ * @internal Symbol-keyed configuration entry point on `StateContainer`.
572
+ * Writes the instance's identity fields (`_name`/`_debug`/`_instanceId`),
573
+ * resolves per-class equality, emits the registry `created` event, and runs
574
+ * `init()` once.
575
+ *
576
+ * Framework-only — the registry (`StateContainerRegistry.ensure`) and testing
577
+ * helpers are the sole callers, mirroring the `APPLY_DEPS` precedent.
578
+ */
579
+ const INIT_CONFIG = Symbol("blac.initConfig");
580
+ //#endregion
581
+ //#region src/core/StateContainerRegistry.ts
582
+ /**
583
+ * Central registry for managing StateContainer instances.
584
+ * Handles instance lifecycle, named ref tracking, and lifecycle event emission.
585
+ *
586
+ * @example
587
+ * ```ts
588
+ * const registry = new StateContainerRegistry();
589
+ * const instance = registry.acquire(MyBloc); // ownership, must release
590
+ * const other = registry.ensure(OtherBloc); // no ownership, bloc-to-bloc
591
+ * registry.on('stateChanged', (container, prev, next) => {
592
+ * console.log('State changed:', prev, '->', next);
593
+ * });
594
+ * ```
595
+ */
596
+ var StateContainerRegistry = class {
597
+ get hasStateChangedListeners() {
598
+ return this._stateChangedListenerCount > 0;
599
+ }
600
+ constructor() {
601
+ this.instancesByConstructor = /* @__PURE__ */ new WeakMap();
602
+ this._keyByInstance = /* @__PURE__ */ new WeakMap();
603
+ this._byId = /* @__PURE__ */ new Map();
604
+ this.types = /* @__PURE__ */ new Set();
605
+ this._registeredTypes = /* @__PURE__ */ new WeakSet();
606
+ this.listeners = /* @__PURE__ */ new Map();
607
+ this._stateChangedListenerCount = 0;
608
+ this._pendingStateChanges = null;
609
+ this._autoRefIdCounter = 0;
610
+ this.on("disposed", (container) => this._handleDisposed(container));
611
+ }
612
+ /**
613
+ * Registry-internal reaction to any instance's `disposed` lifecycle event.
614
+ * Prunes its Map entry, if this registry was tracking it (i.e. it was
615
+ * `acquire()`/`ensure()`'d, not a bare `new`), and always releases its
616
+ * dependent edges on whatever it `depend()`'d on.
617
+ */
618
+ _handleDisposed(container) {
619
+ const Type = container.constructor;
620
+ this._pruneEntry(Type, container);
621
+ const depEdges = container._depEdges;
622
+ if (depEdges) for (const [DepType, keys] of depEdges) for (const key of keys) this._releaseDependent(DepType, key, container);
623
+ }
624
+ /**
625
+ * Remove the Map entry for `container`, if this registry is tracking it.
626
+ * O(1): looks up the entry's key via `_keyByInstance` instead of scanning
627
+ * every entry for identity. Keeps an identity guard so a recreated entry
628
+ * under the same key (a fresh instance under a reused/derived key) is
629
+ * never deleted by a stale container's disposal.
630
+ * @returns true if an entry was found and removed
631
+ */
632
+ _pruneEntry(Type, container) {
633
+ const instances = this.instancesByConstructor.get(Type);
634
+ if (!instances) return false;
635
+ const key = this._keyByInstance.get(container);
636
+ if (key === void 0) return false;
637
+ const entry = instances.get(key);
638
+ if (!entry || entry.instance !== container) return false;
639
+ instances.delete(key);
640
+ this._forgetEntry(entry);
641
+ this._maybeDropType(Type, instances);
642
+ return true;
643
+ }
644
+ /**
645
+ * Single removal point for the `_byId` index (P6). Every path that drops
646
+ * an `InstanceEntry` from the registry MUST route through this so the
647
+ * index can never leak a stale id -> entry mapping.
648
+ */
649
+ _forgetEntry(entry) {
650
+ if (entry.id !== void 0) this._byId.delete(entry.id);
651
+ }
652
+ /**
653
+ * O(1) entry lookup by `$blac.id`, used by `PluginContext.getRefIds`
654
+ * instead of a nested scan over every type x every instance.
655
+ */
656
+ findEntryById(id) {
657
+ return this._byId.get(id);
658
+ }
659
+ /**
660
+ * Storage key `container` is CURRENTLY indexed under, or `undefined` if this
661
+ * registry never tracked it (bare `new`) or no longer does (disposed/pruned,
662
+ * or its key was taken over by a newer instance). Lets callers that hold only
663
+ * an instance address it without knowing the `args` it was acquired with.
664
+ */
665
+ keyOf(container) {
666
+ const key = this._keyByInstance.get(container);
667
+ if (key === void 0) return void 0;
668
+ return (this.instancesByConstructor.get(container.constructor)?.get(key))?.instance === container ? key : void 0;
669
+ }
670
+ /**
671
+ * Drop `Type` from `types` once its instances map is empty, so constructors
672
+ * (and anything keyed on them, e.g. a per-class PathInterner) aren't held
673
+ * alive forever. Deliberate consequence: `getStats()`/`getTypes()` no
674
+ * longer list types with zero live instances.
675
+ */
676
+ _maybeDropType(Type, instances) {
677
+ if (instances.size === 0) this.types.delete(Type);
678
+ }
679
+ /**
680
+ * Drop `dependent`'s edge on the `Type`/`key` entry (a `depend()`-resolved
681
+ * instance). When that leaves the entry with no dependents AND no public
682
+ * refs AND it isn't keepAlive, dispose it — this recurses into the same
683
+ * `disposed` listener, so dep-of-dep chains unwind naturally.
684
+ */
685
+ _releaseDependent(Type, key, dependent) {
686
+ const entry = this.instancesByConstructor.get(Type)?.get(key);
687
+ if (!entry) return;
688
+ entry.dependents?.delete(dependent);
689
+ if ((!entry.dependents || entry.dependents.size === 0) && entry.refs.size === 0 && !isKeepAliveClass(Type) && !entry.instance.$blac.disposed) entry.instance.dispose();
690
+ }
691
+ /**
692
+ * Register a type for lifecycle event tracking
693
+ * @param constructor - The StateContainer class constructor
694
+ */
695
+ registerType(constructor) {
696
+ this.types.add(constructor);
697
+ }
698
+ /**
699
+ * Register a StateContainer class with configuration
700
+ * @param constructor - The StateContainer class constructor
701
+ * @throws Error if type is already registered
702
+ */
703
+ register(constructor) {
704
+ const className = constructor.name;
705
+ if (this._registeredTypes.has(constructor)) throw new Error(`${BLAC_ERROR_PREFIX} Type "${className}" is already registered`);
706
+ this._registeredTypes.add(constructor);
707
+ this.registerType(constructor);
708
+ }
709
+ ensureInstancesMap(Type) {
710
+ let instances = this.instancesByConstructor.get(Type);
711
+ if (!instances) {
712
+ instances = /* @__PURE__ */ new Map();
713
+ this.instancesByConstructor.set(Type, instances);
714
+ }
715
+ return instances;
716
+ }
717
+ /**
718
+ * Get the instances Map for a specific class (public API for stats/debugging)
719
+ */
720
+ getInstancesMap(Type) {
721
+ return this.instancesByConstructor.get(Type) || /* @__PURE__ */ new Map();
722
+ }
723
+ /**
724
+ * Directly insert an instance entry into the registry without going through
725
+ * acquire/release. Creates the internal WeakMap bucket for the constructor if
726
+ * it does not exist yet. Replaces any existing entry for the same key.
727
+ *
728
+ * The provided instance is NOT configured or disposed here — callers are
729
+ * responsible for any initConfig / dispose calls. Intended for testing
730
+ * helpers that create stubs outside the normal acquisition path.
731
+ *
732
+ * @internal Used by testing helpers only.
733
+ */
734
+ insertInstance(Type, instanceKey, instance, refs = /* @__PURE__ */ new Map()) {
735
+ const instances = this.ensureInstancesMap(Type);
736
+ const existingEntry = instances.get(instanceKey);
737
+ if (existingEntry && existingEntry.instance !== instance) {
738
+ if (!existingEntry.instance.$blac.disposed) existingEntry.instance.dispose();
739
+ this._forgetEntry(existingEntry);
740
+ }
741
+ const entry = {
742
+ instance,
743
+ refs
744
+ };
745
+ instances.set(instanceKey, entry);
746
+ this._keyByInstance.set(instance, instanceKey);
747
+ entry.id = instance.$blac.id;
748
+ this._byId.set(entry.id, entry);
749
+ }
750
+ /**
751
+ * Resolve the storage key for an instance. This is the single source of truth
752
+ * for keying — `acquire` and `release` MUST agree, otherwise a ref taken under
753
+ * an args-derived key is never dropped (instance leaks).
754
+ *
755
+ * Resolution order (explicit beats derived):
756
+ * explicit key > `static key(args)` > structural hash of args > default sentinel.
757
+ *
758
+ * @param Type - The StateContainer class constructor
759
+ * @param instanceKey - Explicit key, or undefined to derive from args
760
+ * @param args - Construction args used for structural/`static key` derivation
761
+ */
762
+ resolveKey(Type, instanceKey, args) {
763
+ if (instanceKey !== void 0) return instanceKey;
764
+ const keyFn = getClassKey(Type);
765
+ if (keyFn) return keyFn(args);
766
+ if (args !== void 0) return structuralKey(args);
767
+ return DEFAULT_STRUCTURAL_KEY;
768
+ }
769
+ /**
770
+ * Circuit breaker for runaway instance creation. Throws when a single
771
+ * constructor would exceed `maxInstancesPerType` live instances — almost
772
+ * always an unstable instance key (e.g. a new object/array passed as `args`
773
+ * every render, or a missing `static key`) leaking an instance per render.
774
+ */
775
+ assertInstanceLimit(Type, currentCount) {
776
+ const limit = getBlacConfig().maxInstancesPerType;
777
+ if (limit > 0 && currentCount >= limit) throw new Error(`${BLAC_ERROR_PREFIX} ${Type.name} exceeded the maximum of ${limit} live instances. This usually means the instance key is unstable — e.g. \`args\` that change identity every render, or a missing \`static key\` — so a new instance is created and never disposed (memory leak). Stabilize the key, add a \`static key(args)\`, or raise \`configureBlac({ maxInstancesPerType })\`.`);
778
+ }
779
+ /**
780
+ * Circuit breaker for runaway reference growth. Throws when one instance
781
+ * accumulates more than `maxRefsPerInstance` distinct live refs — almost
782
+ * always consumer cleanup (e.g. `useBloc`'s unmount `release`) never firing.
783
+ */
784
+ assertRefLimit(Type, resolvedKey, refCount) {
785
+ const limit = getBlacConfig().maxRefsPerInstance;
786
+ if (limit > 0 && refCount > limit) throw new Error(`${BLAC_ERROR_PREFIX} ${Type.name} instance "${resolvedKey}" exceeded the maximum of ${limit} live references. This usually means references are acquired without a matching release (e.g. a consumer that never unmounts/cleans up), leaking refs that keep the instance alive forever. Ensure every acquire is paired with a release, or raise \`configureBlac({ maxRefsPerInstance })\`.`);
787
+ }
788
+ /**
789
+ * Acquire an instance with ref tracking (ownership semantics).
790
+ * Creates a new instance if one doesn't exist, or returns existing and adds a ref.
791
+ * You must call `release()` with the same refId when done.
792
+ *
793
+ * @internal Internal key tier. Public callers use the args-based `acquire`
794
+ * wrapper; `useBloc` and `watch` address a pre-resolved key here.
795
+ * @param Type - The StateContainer class constructor
796
+ * @param instanceKey - Pre-resolved instance key (defaults to 'default')
797
+ * @param options - Acquisition options
798
+ * @param options.canCreate - Whether to create new instance if not found (default: true)
799
+ * @param options.countRef - Whether to add a reference (default: true)
800
+ * @param options.refId - Named reference ID for debugging; auto-generated if omitted
801
+ * @param options.dependent - The `depend()`-owner resolving this instance, if any;
802
+ * recorded so its dependent edge can be released on the owner's disposal.
803
+ * @returns The state container instance
804
+ */
805
+ acquire(Type, instanceKey, options = {}) {
806
+ const { canCreate = true, countRef = true } = options;
807
+ const args = options.args;
808
+ const resolvedKey = this.resolveKey(Type, instanceKey, args);
809
+ const config = {
810
+ instanceId: resolvedKey,
811
+ args
812
+ };
813
+ const instances = this.ensureInstancesMap(Type);
814
+ let entry = instances.get(resolvedKey);
815
+ if (entry?.instance.$blac.disposed) {
816
+ instances.delete(resolvedKey);
817
+ entry = void 0;
818
+ }
819
+ if (entry) {
820
+ if (process.env.NODE_ENV !== "production" && args !== void 0 && entry.args !== void 0) {
821
+ const incomingKey = structuralKey(args);
822
+ const storedKey = entry.argsKey ??= structuralKey(entry.args);
823
+ if (incomingKey !== storedKey) console.warn(`${BLAC_ERROR_PREFIX} ${Type.name} instance key "${resolvedKey}" was acquired with different args. Existing args: ${storedKey}, new args: ${incomingKey}. The existing instance will be reused. If distinct args should produce distinct instances, either remove the explicit instanceKey or provide a \`static key\` function that reflects the difference.`);
824
+ }
825
+ if (countRef) {
826
+ const refId = options.refId ?? `_auto_${this._autoRefIdCounter++}`;
827
+ entry.refs.set(refId, (entry.refs.get(refId) ?? 0) + 1);
828
+ this.assertRefLimit(Type, resolvedKey, entry.refs.size);
829
+ this.emit("refAcquired", entry.instance, refId);
830
+ }
831
+ if (options.dependent) (entry.dependents ??= /* @__PURE__ */ new Set()).add(options.dependent);
832
+ return entry.instance;
833
+ }
834
+ if (!canCreate) throw new Error(`${BLAC_ERROR_PREFIX} ${Type.name} instance "${resolvedKey}" not found and creation is disabled.`);
835
+ this.assertInstanceLimit(Type, instances.size);
836
+ const instance = new Type();
837
+ const initialRefs = /* @__PURE__ */ new Map();
838
+ let initialRefId;
839
+ if (countRef) {
840
+ initialRefId = options.refId ?? `_auto_${this._autoRefIdCounter++}`;
841
+ initialRefs.set(initialRefId, 1);
842
+ }
843
+ const newEntry = {
844
+ instance,
845
+ refs: initialRefs,
846
+ args
847
+ };
848
+ if (options.dependent) (newEntry.dependents ??= /* @__PURE__ */ new Set()).add(options.dependent);
849
+ instances.set(resolvedKey, newEntry);
850
+ this.registerType(Type);
851
+ this._keyByInstance.set(instance, resolvedKey);
852
+ try {
853
+ instance[INIT_CONFIG](config);
854
+ } catch (error) {
855
+ instances.delete(resolvedKey);
856
+ throw error;
857
+ }
858
+ newEntry.id = instance.$blac.id;
859
+ this._byId.set(newEntry.id, newEntry);
860
+ if (initialRefId) this.emit("refAcquired", instance, initialRefId);
861
+ return instance;
862
+ }
863
+ /**
864
+ * Borrow an existing instance without adding a ref (borrowing semantics).
865
+ * Tracks cross-bloc dependency for reactive updates.
866
+ *
867
+ * @internal Internal key tier; public callers use the args-based `borrow`.
868
+ * @param Type - The StateContainer class constructor
869
+ * @param instanceKey - Pre-resolved instance key (defaults to 'default')
870
+ * @returns The state container instance
871
+ * @throws Error if instance doesn't exist
872
+ */
873
+ borrow(Type, instanceKey = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY) {
874
+ return this.acquire(Type, instanceKey, {
875
+ canCreate: false,
876
+ countRef: false
877
+ });
878
+ }
879
+ /**
880
+ * Safely borrow an existing instance (borrowing semantics with error handling).
881
+ * Returns discriminated union for type-safe conditional access.
882
+ *
883
+ * @internal Internal key tier; public callers use the args-based `borrowSafe`.
884
+ * @param Type - The StateContainer class constructor
885
+ * @param instanceKey - Pre-resolved instance key (defaults to 'default')
886
+ * @returns Discriminated union with either the instance or an error
887
+ */
888
+ borrowSafe(Type, instanceKey = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY) {
889
+ try {
890
+ return {
891
+ error: null,
892
+ instance: this.borrow(Type, instanceKey)
893
+ };
894
+ } catch (error) {
895
+ return {
896
+ error,
897
+ instance: null
898
+ };
899
+ }
900
+ }
901
+ /**
902
+ * Ensure an instance exists without taking ownership (for bloc-to-bloc communication).
903
+ * Gets existing instance OR creates it if it doesn't exist, without adding a ref.
904
+ * Tracks cross-bloc dependency for reactive updates.
905
+ *
906
+ * Use this in bloc-to-bloc communication when you need to ensure an instance exists
907
+ * but don't want to claim ownership (no ref added).
908
+ *
909
+ * @internal Internal key tier; public callers use the args-based `ensure`.
910
+ * @param Type - The StateContainer class constructor
911
+ * @param instanceKey - Pre-resolved instance key, or undefined to derive from `args`
912
+ * (`static key(args)` / structural hash), matching `acquire`.
913
+ * @param args - Construction args; used for keying when no explicit key is given
914
+ * @returns The state container instance
915
+ */
916
+ ensure(Type, instanceKey, args) {
917
+ return this.acquire(Type, instanceKey, {
918
+ canCreate: true,
919
+ countRef: false,
920
+ args
921
+ });
922
+ }
923
+ /**
924
+ * Release a reference to an instance.
925
+ * Removes the ref and disposes when refs is empty (unless keepAlive).
926
+ * Releasing an already-removed refId is a no-op (idempotent).
927
+ *
928
+ * @internal Internal key tier; public callers use the args-based `release`.
929
+ * @param Type - The StateContainer class constructor
930
+ * @param instanceKey - Pre-resolved instance key (defaults to 'default')
931
+ * @param forceDispose - Force immediate disposal regardless of refs
932
+ * @param refId - The specific ref to remove; removes one arbitrary ref if omitted
933
+ */
934
+ release(Type, instanceKey = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY, forceDispose = false, refId) {
935
+ const instances = this.instancesByConstructor.get(Type);
936
+ const entry = instances?.get(instanceKey);
937
+ if (!instances || !entry) return;
938
+ if (forceDispose) {
939
+ if (!entry.instance.$blac.disposed) entry.instance.dispose();
940
+ instances.delete(instanceKey);
941
+ this._forgetEntry(entry);
942
+ this._maybeDropType(Type, instances);
943
+ return;
944
+ }
945
+ let releasedRefId;
946
+ if (refId !== void 0) {
947
+ const count = entry.refs.get(refId) ?? 0;
948
+ if (count <= 1) entry.refs.delete(refId);
949
+ else entry.refs.set(refId, count - 1);
950
+ releasedRefId = refId;
951
+ } else {
952
+ const firstKey = entry.refs.keys().next().value;
953
+ if (firstKey !== void 0) {
954
+ const count = entry.refs.get(firstKey) ?? 0;
955
+ if (count <= 1) entry.refs.delete(firstKey);
956
+ else entry.refs.set(firstKey, count - 1);
957
+ releasedRefId = firstKey;
958
+ }
959
+ }
960
+ if (releasedRefId) this.emit("refReleased", entry.instance, releasedRefId);
961
+ const keepAlive = isKeepAliveClass(Type);
962
+ if (entry.refs.size === 0 && !keepAlive) {
963
+ if (!entry.instance.$blac.disposed) entry.instance.dispose();
964
+ instances.delete(instanceKey);
965
+ this._forgetEntry(entry);
966
+ this._maybeDropType(Type, instances);
967
+ }
968
+ }
969
+ /**
970
+ * Get all instances of a specific type.
971
+ * @param Type - The StateContainer class constructor
972
+ * @returns Array of all instances
973
+ */
974
+ getAll(Type) {
975
+ const instances = this.instancesByConstructor.get(Type);
976
+ const result = [];
977
+ if (!instances) return result;
978
+ for (const entry of instances.values()) if (!entry.instance.$blac.disposed) result.push(entry.instance);
979
+ return result;
980
+ }
981
+ /**
982
+ * Safely iterate over all instances of a type.
983
+ * Skips disposed instances and catches callback errors.
984
+ * @param Type - The StateContainer class constructor
985
+ * @param callback - Function to call for each instance
986
+ */
987
+ forEach(Type, callback) {
988
+ const instances = this.instancesByConstructor.get(Type);
989
+ if (!instances) return;
990
+ for (const entry of instances.values()) {
991
+ const instance = entry.instance;
992
+ if (!instance.$blac.disposed) try {
993
+ callback(instance);
994
+ } catch (error) {
995
+ console.error(`${BLAC_ERROR_PREFIX} forEach callback error for ${Type.name}:`, error);
996
+ }
997
+ }
998
+ }
999
+ /**
1000
+ * Clear all instances of a specific type (disposes them).
1001
+ * @param Type - The StateContainer class constructor
1002
+ */
1003
+ clear(Type) {
1004
+ const instances = this.instancesByConstructor.get(Type);
1005
+ if (!instances) return;
1006
+ for (const entry of instances.values()) {
1007
+ if (!entry.instance.$blac.disposed) entry.instance.dispose();
1008
+ this._forgetEntry(entry);
1009
+ }
1010
+ instances.clear();
1011
+ this._maybeDropType(Type, instances);
1012
+ }
1013
+ /**
1014
+ * Get reference count for an instance (number of active refs).
1015
+ *
1016
+ * @internal Internal key tier; public callers use the args-based `getRefCount`.
1017
+ * @param Type - The StateContainer class constructor
1018
+ * @param instanceKey - Pre-resolved instance key (defaults to 'default')
1019
+ * @returns Current ref count (0 if instance doesn't exist)
1020
+ */
1021
+ getRefCount(Type, instanceKey = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY) {
1022
+ return (this.instancesByConstructor.get(Type)?.get(instanceKey))?.refs.size ?? 0;
1023
+ }
1024
+ /**
1025
+ * Get all active reference IDs for an instance.
1026
+ *
1027
+ * @internal Internal key tier; public callers use the args-based `getRefIds`.
1028
+ * @param Type - The StateContainer class constructor
1029
+ * @param instanceKey - Pre-resolved instance key (defaults to 'default')
1030
+ * @returns Array of ref ID strings (empty if instance doesn't exist)
1031
+ */
1032
+ getRefIds(Type, instanceKey = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY) {
1033
+ const instances = this.instancesByConstructor.get(Type);
1034
+ if (!instances) return [];
1035
+ const entry = instances.get(instanceKey);
1036
+ return entry ? Array.from(entry.refs.keys()) : [];
1037
+ }
1038
+ /**
1039
+ * Check if an instance exists.
1040
+ *
1041
+ * @internal Internal key tier; public callers use the args-based `hasInstance`.
1042
+ * @param Type - The StateContainer class constructor
1043
+ * @param instanceKey - Pre-resolved instance key (defaults to 'default')
1044
+ * @returns true if instance exists
1045
+ */
1046
+ hasInstance(Type, instanceKey = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY) {
1047
+ return this.instancesByConstructor.get(Type)?.has(instanceKey) ?? false;
1048
+ }
1049
+ /**
1050
+ * Clear all instances from all types (for testing)
1051
+ *
1052
+ * Iterates all registered types and clears their instances.
1053
+ * Also clears type tracking to reset the registry state.
1054
+ */
1055
+ clearAll() {
1056
+ for (const Type of this.types) this.clear(Type);
1057
+ this.types.clear();
1058
+ this._registeredTypes = /* @__PURE__ */ new WeakSet();
1059
+ }
1060
+ /**
1061
+ * Get registry statistics for debugging.
1062
+ * @returns Object with registeredTypes, totalInstances, and typeBreakdown
1063
+ */
1064
+ getStats() {
1065
+ const typeBreakdown = {};
1066
+ let totalInstances = 0;
1067
+ for (const Type of this.types) {
1068
+ const typeName = Type.name;
1069
+ const count = this.getInstancesMap(Type).size;
1070
+ typeBreakdown[typeName] = count;
1071
+ totalInstances += count;
1072
+ }
1073
+ return {
1074
+ registeredTypes: this.types.size,
1075
+ totalInstances,
1076
+ typeBreakdown
1077
+ };
1078
+ }
1079
+ /**
1080
+ * Get all registered types (for plugin system).
1081
+ * @returns Array of all registered StateContainer class constructors
1082
+ */
1083
+ getTypes() {
1084
+ return Array.from(this.types);
1085
+ }
1086
+ /**
1087
+ * Subscribe to lifecycle events
1088
+ * @param event - The lifecycle event to listen for
1089
+ * @param listener - The listener function to call when the event occurs
1090
+ * @returns Unsubscribe function
1091
+ */
1092
+ on(event, listener) {
1093
+ if (!this.listeners.has(event)) this.listeners.set(event, /* @__PURE__ */ new Set());
1094
+ const instance = this.listeners.get(event);
1095
+ if (!instance) throw new Error(`${BLAC_ERROR_PREFIX} Failed to register listener for event '${event}'`);
1096
+ instance.add(listener);
1097
+ if (event === "stateChanged") this._stateChangedListenerCount++;
1098
+ return () => {
1099
+ if (this.listeners.get(event)?.delete(listener) && event === "stateChanged") this._stateChangedListenerCount--;
1100
+ };
1101
+ }
1102
+ emit(event, ...args) {
1103
+ const listeners = this.listeners.get(event);
1104
+ if (!listeners || listeners.size === 0) return;
1105
+ for (const listener of listeners) try {
1106
+ listener(...args);
1107
+ } catch (error) {
1108
+ console.error(`${BLAC_ERROR_PREFIX} Listener error for '${event}':`, error);
1109
+ }
1110
+ }
1111
+ /**
1112
+ * Schedule a deferred stateChanged notification via microtask.
1113
+ * Skips entirely when no stateChanged listeners are registered.
1114
+ * @internal - Called by StateContainer.applyState
1115
+ */
1116
+ notifyStateChanged(container, previousState, newState) {
1117
+ if (this._stateChangedListenerCount === 0) return;
1118
+ if (!this._pendingStateChanges) {
1119
+ this._pendingStateChanges = [];
1120
+ queueMicrotask(() => this.flushStateChanged());
1121
+ }
1122
+ this._pendingStateChanges.push([
1123
+ container,
1124
+ previousState,
1125
+ newState
1126
+ ]);
1127
+ }
1128
+ flushStateChanged() {
1129
+ const pending = this._pendingStateChanges;
1130
+ this._pendingStateChanges = null;
1131
+ if (!pending) return;
1132
+ for (const [container, prev, next] of pending) this.emit("stateChanged", container, prev, next);
1133
+ }
1134
+ };
1135
+ /**
1136
+ * Global default registry instance
1137
+ */
1138
+ const globalRegistry = new StateContainerRegistry();
1139
+ /**
1140
+ * Global plugin manager (initialized lazily)
1141
+ */
1142
+ let _globalPluginManager = null;
1143
+ /**
1144
+ * Get the global plugin manager
1145
+ */
1146
+ function getPluginManager() {
1147
+ if (!_globalPluginManager) _globalPluginManager = createPluginManager(globalRegistry);
1148
+ return _globalPluginManager;
1149
+ }
1150
+ //#endregion
1151
+ Object.defineProperty(exports, "APPLY_DEPS", {
1152
+ enumerable: true,
1153
+ get: function() {
1154
+ return APPLY_DEPS;
1155
+ }
1156
+ });
1157
+ Object.defineProperty(exports, "BLAC_ERROR_PREFIX", {
1158
+ enumerable: true,
1159
+ get: function() {
1160
+ return BLAC_ERROR_PREFIX;
1161
+ }
1162
+ });
1163
+ Object.defineProperty(exports, "BLAC_STATIC_PROPS", {
1164
+ enumerable: true,
1165
+ get: function() {
1166
+ return BLAC_STATIC_PROPS;
1167
+ }
1168
+ });
1169
+ Object.defineProperty(exports, "INIT_CONFIG", {
1170
+ enumerable: true,
1171
+ get: function() {
1172
+ return INIT_CONFIG;
1173
+ }
1174
+ });
1175
+ Object.defineProperty(exports, "ON_DISPOSE", {
1176
+ enumerable: true,
1177
+ get: function() {
1178
+ return ON_DISPOSE;
1179
+ }
1180
+ });
1181
+ Object.defineProperty(exports, "PluginManager", {
1182
+ enumerable: true,
1183
+ get: function() {
1184
+ return PluginManager;
1185
+ }
1186
+ });
1187
+ Object.defineProperty(exports, "REMOVE_DEPS_OWNER", {
1188
+ enumerable: true,
1189
+ get: function() {
1190
+ return REMOVE_DEPS_OWNER;
1191
+ }
1192
+ });
1193
+ Object.defineProperty(exports, "StateContainerRegistry", {
1194
+ enumerable: true,
1195
+ get: function() {
1196
+ return StateContainerRegistry;
1197
+ }
1198
+ });
1199
+ Object.defineProperty(exports, "configureBlac", {
1200
+ enumerable: true,
1201
+ get: function() {
1202
+ return configureBlac;
1203
+ }
1204
+ });
1205
+ Object.defineProperty(exports, "getBlacConfig", {
1206
+ enumerable: true,
1207
+ get: function() {
1208
+ return getBlacConfig;
1209
+ }
1210
+ });
1211
+ Object.defineProperty(exports, "getClassEquality", {
1212
+ enumerable: true,
1213
+ get: function() {
1214
+ return getClassEquality;
1215
+ }
1216
+ });
1217
+ Object.defineProperty(exports, "getPluginManager", {
1218
+ enumerable: true,
1219
+ get: function() {
1220
+ return getPluginManager;
1221
+ }
1222
+ });
1223
+ Object.defineProperty(exports, "globalRegistry", {
1224
+ enumerable: true,
1225
+ get: function() {
1226
+ return globalRegistry;
1227
+ }
1228
+ });
1229
+ Object.defineProperty(exports, "isExcludedFromDevTools", {
1230
+ enumerable: true,
1231
+ get: function() {
1232
+ return isExcludedFromDevTools;
1233
+ }
1234
+ });
1235
+ Object.defineProperty(exports, "isIsolatedClass", {
1236
+ enumerable: true,
1237
+ get: function() {
1238
+ return isIsolatedClass;
1239
+ }
1240
+ });
1241
+ Object.defineProperty(exports, "isKeepAliveClass", {
1242
+ enumerable: true,
1243
+ get: function() {
1244
+ return isKeepAliveClass;
1245
+ }
1246
+ });
1247
+ Object.defineProperty(exports, "resetBlacConfig", {
1248
+ enumerable: true,
1249
+ get: function() {
1250
+ return resetBlacConfig;
1251
+ }
1252
+ });
1253
+ Object.defineProperty(exports, "shallowEqualState", {
1254
+ enumerable: true,
1255
+ get: function() {
1256
+ return shallowEqualState;
1257
+ }
1258
+ });
1259
+
1260
+ //# sourceMappingURL=StateContainerRegistry-C75QpeaO.cjs.map