@blac/core 2.0.18 → 2.0.20

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 (139) hide show
  1. package/dist/StateContainerRegistry-8zNFMAf7.js +1067 -0
  2. package/dist/StateContainerRegistry-8zNFMAf7.js.map +1 -0
  3. package/dist/StateContainerRegistry-Bx2ly-ba.cjs +1162 -0
  4. package/dist/StateContainerRegistry-Bx2ly-ba.cjs.map +1 -0
  5. package/dist/StateContainerRegistry-C0dCNlTF.js +1005 -0
  6. package/dist/StateContainerRegistry-C0dCNlTF.js.map +1 -0
  7. package/dist/StateContainerRegistry-CS18y4au.cjs +1163 -0
  8. package/dist/StateContainerRegistry-CS18y4au.cjs.map +1 -0
  9. package/dist/StateContainerRegistry-CchRjnjX.cjs +1094 -0
  10. package/dist/StateContainerRegistry-CchRjnjX.cjs.map +1 -0
  11. package/dist/StateContainerRegistry-D8nu7Z0T.js +1068 -0
  12. package/dist/StateContainerRegistry-D8nu7Z0T.js.map +1 -0
  13. package/dist/StateContainerRegistry-D9BIRjwv.cjs +1088 -0
  14. package/dist/StateContainerRegistry-D9BIRjwv.cjs.map +1 -0
  15. package/dist/StateContainerRegistry-DVIBTxGZ.js +999 -0
  16. package/dist/StateContainerRegistry-DVIBTxGZ.js.map +1 -0
  17. package/dist/StateContainerRegistry-Dj77cok9.js +1005 -0
  18. package/dist/StateContainerRegistry-Dj77cok9.js.map +1 -0
  19. package/dist/StateContainerRegistry-lIwo-0m3.cjs +1094 -0
  20. package/dist/StateContainerRegistry-lIwo-0m3.cjs.map +1 -0
  21. package/dist/acquire-B1LYXSGj.js +35 -0
  22. package/dist/acquire-B1LYXSGj.js.map +1 -0
  23. package/dist/acquire-BJ3xUEmh.cjs +46 -0
  24. package/dist/acquire-BJ3xUEmh.cjs.map +1 -0
  25. package/dist/acquire-BRIJVJaA.js +35 -0
  26. package/dist/acquire-BRIJVJaA.js.map +1 -0
  27. package/dist/acquire-B_p1fNEh.cjs +46 -0
  28. package/dist/acquire-B_p1fNEh.cjs.map +1 -0
  29. package/dist/acquire-BdsVZBSe.js +35 -0
  30. package/dist/acquire-BdsVZBSe.js.map +1 -0
  31. package/dist/acquire-C3nOb3XR.cjs +46 -0
  32. package/dist/acquire-C3nOb3XR.cjs.map +1 -0
  33. package/dist/acquire-C4WAS13G.cjs +46 -0
  34. package/dist/acquire-C4WAS13G.cjs.map +1 -0
  35. package/dist/acquire-C7beGI55.cjs +46 -0
  36. package/dist/acquire-C7beGI55.cjs.map +1 -0
  37. package/dist/acquire-DXEQDZGr.js +35 -0
  38. package/dist/acquire-DXEQDZGr.js.map +1 -0
  39. package/dist/acquire-Dg-uXwjF.js +35 -0
  40. package/dist/acquire-Dg-uXwjF.js.map +1 -0
  41. package/dist/config-B1l8ZGlU.cjs +32 -0
  42. package/dist/config-B1l8ZGlU.cjs.map +1 -0
  43. package/dist/config-CzcoAvBo.js +16 -0
  44. package/dist/config-CzcoAvBo.js.map +1 -0
  45. package/dist/config-D6BoWWPv.js +16 -0
  46. package/dist/config-D6BoWWPv.js.map +1 -0
  47. package/dist/config-DOO82lbZ.js +16 -0
  48. package/dist/config-DOO82lbZ.js.map +1 -0
  49. package/dist/config-DVM_ESQt.js +16 -0
  50. package/dist/config-DVM_ESQt.js.map +1 -0
  51. package/dist/config-DWUq7zEQ.cjs +32 -0
  52. package/dist/config-DWUq7zEQ.cjs.map +1 -0
  53. package/dist/config-DXI3kzmA.js +16 -0
  54. package/dist/config-DXI3kzmA.js.map +1 -0
  55. package/dist/config-cwaTn5oy.cjs +32 -0
  56. package/dist/config-cwaTn5oy.cjs.map +1 -0
  57. package/dist/config-d9_U58ef.cjs +32 -0
  58. package/dist/config-d9_U58ef.cjs.map +1 -0
  59. package/dist/config-hWTayX76.cjs +32 -0
  60. package/dist/config-hWTayX76.cjs.map +1 -0
  61. package/dist/core/StateContainer.d.ts +7 -1
  62. package/dist/core/StateContainerRegistry.d.ts +31 -3
  63. package/dist/core/symbols.d.ts +6 -0
  64. package/dist/debug.cjs +3 -3
  65. package/dist/debug.js +3 -3
  66. package/dist/ensure-B1dEDsZV.cjs +559 -0
  67. package/dist/ensure-B1dEDsZV.cjs.map +1 -0
  68. package/dist/ensure-B2DYCbbI.cjs +578 -0
  69. package/dist/ensure-B2DYCbbI.cjs.map +1 -0
  70. package/dist/ensure-B59ri8oo.js +555 -0
  71. package/dist/ensure-B59ri8oo.js.map +1 -0
  72. package/dist/ensure-BKdq5xsY.cjs +578 -0
  73. package/dist/ensure-BKdq5xsY.cjs.map +1 -0
  74. package/dist/ensure-BSJHkUNX.js +555 -0
  75. package/dist/ensure-BSJHkUNX.js.map +1 -0
  76. package/dist/ensure-Bm91o37h.js +536 -0
  77. package/dist/ensure-Bm91o37h.js.map +1 -0
  78. package/dist/ensure-CQimeD0I.cjs +559 -0
  79. package/dist/ensure-CQimeD0I.cjs.map +1 -0
  80. package/dist/ensure-DTTTd2h8.js +536 -0
  81. package/dist/ensure-DTTTd2h8.js.map +1 -0
  82. package/dist/ensure-VuiNPccZ.cjs +559 -0
  83. package/dist/ensure-VuiNPccZ.cjs.map +1 -0
  84. package/dist/ensure-vxAGa2v3.js +536 -0
  85. package/dist/ensure-vxAGa2v3.js.map +1 -0
  86. package/dist/index.cjs +7 -6
  87. package/dist/index.d.cts +3 -3
  88. package/dist/index.d.ts +3 -3
  89. package/dist/index.js +7 -7
  90. package/dist/management-AFuqQEwz.js +38 -0
  91. package/dist/management-AFuqQEwz.js.map +1 -0
  92. package/dist/management-BodVLAfJ.cjs +85 -0
  93. package/dist/management-BodVLAfJ.cjs.map +1 -0
  94. package/dist/management-C-WGcwPD.js +38 -0
  95. package/dist/management-C-WGcwPD.js.map +1 -0
  96. package/dist/management-C2wv4vGS.cjs +85 -0
  97. package/dist/management-C2wv4vGS.cjs.map +1 -0
  98. package/dist/management-D2pjr38g.js +38 -0
  99. package/dist/management-D2pjr38g.js.map +1 -0
  100. package/dist/management-D5WsZoTV.js +38 -0
  101. package/dist/management-D5WsZoTV.js.map +1 -0
  102. package/dist/management-DwO0nBzL.cjs +85 -0
  103. package/dist/management-DwO0nBzL.cjs.map +1 -0
  104. package/dist/management-P_Vi_cvw.js +38 -0
  105. package/dist/management-P_Vi_cvw.js.map +1 -0
  106. package/dist/management-QWLpbXlW.cjs +85 -0
  107. package/dist/management-QWLpbXlW.cjs.map +1 -0
  108. package/dist/management-iE4x6IQY.cjs +85 -0
  109. package/dist/management-iE4x6IQY.cjs.map +1 -0
  110. package/dist/plugin/PluginManager.d.ts +14 -1
  111. package/dist/plugins.cjs +1 -1
  112. package/dist/plugins.js +1 -1
  113. package/dist/testing.cjs +4 -4
  114. package/dist/testing.js +4 -4
  115. package/dist/utils/idGenerator.d.ts +0 -36
  116. package/dist/watch/watch.d.ts +6 -0
  117. package/dist/watch-B0pUfh-v.cjs +119 -0
  118. package/dist/watch-B0pUfh-v.cjs.map +1 -0
  119. package/dist/watch-BHfCtbn1.cjs +119 -0
  120. package/dist/watch-BHfCtbn1.cjs.map +1 -0
  121. package/dist/watch-Bx0y-Kcc.js +108 -0
  122. package/dist/watch-Bx0y-Kcc.js.map +1 -0
  123. package/dist/watch-D01MdwKy.js +108 -0
  124. package/dist/watch-D01MdwKy.js.map +1 -0
  125. package/dist/watch-DkDGmGAx.cjs +119 -0
  126. package/dist/watch-DkDGmGAx.cjs.map +1 -0
  127. package/dist/watch-DttHqefn.js +108 -0
  128. package/dist/watch-DttHqefn.js.map +1 -0
  129. package/dist/watch-DxdIZjpt.cjs +119 -0
  130. package/dist/watch-DxdIZjpt.cjs.map +1 -0
  131. package/dist/watch-DztcJuUy.cjs +119 -0
  132. package/dist/watch-DztcJuUy.cjs.map +1 -0
  133. package/dist/watch-IrR8G28N.js +108 -0
  134. package/dist/watch-IrR8G28N.js.map +1 -0
  135. package/dist/watch-entry.cjs +1 -1
  136. package/dist/watch-entry.js +1 -1
  137. package/dist/watch-hx0r92Zc.js +108 -0
  138. package/dist/watch-hx0r92Zc.js.map +1 -0
  139. package/package.json +2 -2
@@ -0,0 +1,1088 @@
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: 1e3,
23
+ maxRefsPerInstance: 1e3,
24
+ maxEmitsPerSecond: 100
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
+ if (plugin.onInstall) try {
124
+ plugin.onInstall(installContext);
125
+ } catch (error) {
126
+ console.error(`[BlaC] Error installing plugin "${plugin.name}":`, error);
127
+ this.plugins.delete(plugin.name);
128
+ throw error;
129
+ }
130
+ console.log(`[BlaC] Plugin "${plugin.name}" v${plugin.version} installed`);
131
+ }
132
+ /**
133
+ * Uninstall a plugin by name
134
+ * @param pluginName - The name of the plugin to uninstall
135
+ * @throws Error if plugin is not installed
136
+ */
137
+ uninstall(pluginName) {
138
+ const installed = this.plugins.get(pluginName);
139
+ if (!installed) throw new Error(`Plugin "${pluginName}" is not installed`);
140
+ if (installed.plugin.onUninstall) try {
141
+ installed.plugin.onUninstall();
142
+ } catch (error) {
143
+ console.error(`[BlaC] Error uninstalling plugin "${pluginName}":`, error);
144
+ }
145
+ this.plugins.delete(pluginName);
146
+ console.log(`[BlaC] Plugin "${pluginName}" uninstalled`);
147
+ }
148
+ /**
149
+ * Get an installed plugin by name
150
+ * @param pluginName - The name of the plugin to retrieve
151
+ * @returns The plugin instance or undefined if not found
152
+ */
153
+ getPlugin(pluginName) {
154
+ return this.plugins.get(pluginName)?.plugin;
155
+ }
156
+ /**
157
+ * Get all installed plugins
158
+ * @returns Array of all installed plugins
159
+ */
160
+ getAllPlugins() {
161
+ return Array.from(this.plugins.values()).map((p) => p.plugin);
162
+ }
163
+ /**
164
+ * Check if a plugin is installed
165
+ * @param pluginName - The name of the plugin to check
166
+ * @returns true if the plugin is installed
167
+ */
168
+ hasPlugin(pluginName) {
169
+ return this.plugins.has(pluginName);
170
+ }
171
+ /**
172
+ * Uninstall all plugins
173
+ */
174
+ clear() {
175
+ for (const name of this.plugins.keys()) this.uninstall(name);
176
+ }
177
+ destroy() {
178
+ this.clear();
179
+ for (const unsub of this.lifecycleUnsubscribers) unsub();
180
+ this.lifecycleUnsubscribers = [];
181
+ }
182
+ /**
183
+ * Wire registry lifecycle events into plugin dispatch.
184
+ *
185
+ * `onStateChange` is NOT wired through `registry.on('stateChanged', …)` —
186
+ * that event lacks the `PathSet` payload. Instead, on each `created` we
187
+ * subscribe to the container's channel directly so we get
188
+ * `(paths)` and capture `(prev, next)` via the per-container snapshot.
189
+ */
190
+ setupLifecycleHooks() {
191
+ this.lifecycleUnsubscribers = [
192
+ this.registry.on("created", (instance) => {
193
+ this.attachStateBridge(instance);
194
+ this.notifyPlugins("onCreated", instance);
195
+ }),
196
+ this.registry.on("disposed", (instance) => {
197
+ this.notifyPlugins("onDestroyed", instance);
198
+ this.detachStateBridge(instance);
199
+ }),
200
+ this.registry.on("refAcquired", (instance, refId) => {
201
+ this.notifyPlugins("onRefAcquired", instance, refId);
202
+ }),
203
+ this.registry.on("refReleased", (instance, refId) => {
204
+ this.notifyPlugins("onRefReleased", instance, refId);
205
+ }),
206
+ this.registry.on("depsChanged", (instance, previousDeps, currentDeps) => {
207
+ this.notifyPlugins("onDepsChanged", instance, previousDeps, currentDeps);
208
+ }),
209
+ this.registry.on("hydrationChanged", (instance, status, previousStatus) => {
210
+ this.notifyPlugins("onHydrationChange", instance, status, previousStatus);
211
+ })
212
+ ];
213
+ }
214
+ /**
215
+ * Subscribe to the container's channel with `ALL_PATHS` interest, so we
216
+ * fire on every flush. Capture `prev` from the snapshot taken on the
217
+ * previous flush (or at create-time for the first flush) and pass the
218
+ * channel's `paths` argument straight through to plugins.
219
+ *
220
+ * Per-container bookkeeping is stored in a `WeakMap` keyed by the
221
+ * container itself, so a disposed/GC'd container drops cleanly.
222
+ */
223
+ attachStateBridge(container) {
224
+ if (this.containerBridges.has(container)) return;
225
+ const bridge = {
226
+ unsub: () => {},
227
+ prevState: container.state
228
+ };
229
+ this.containerBridges.set(container, bridge);
230
+ bridge.unsub = container.channel.subscribe(() => _dirtytalk_structural.ALL_PATHS, (paths) => this.dispatchStateChange(container, paths));
231
+ }
232
+ detachStateBridge(container) {
233
+ const bridge = this.containerBridges.get(container);
234
+ if (!bridge) return;
235
+ bridge.unsub();
236
+ this.containerBridges.delete(container);
237
+ }
238
+ /**
239
+ * Channel-flush callback. Snapshots `next`, hands `(prev, next, paths)`
240
+ * to every enabled plugin's `onStateChange`, then updates `prevState`
241
+ * for the next flush.
242
+ *
243
+ * Note: `prev` is captured once and reused across plugins — every
244
+ * plugin sees the same `prev`/`next`/`paths` regardless of dispatch
245
+ * order, matching the "snapshot prev once per flush" invariant.
246
+ */
247
+ dispatchStateChange(container, paths) {
248
+ const bridge = this.containerBridges.get(container);
249
+ if (!bridge) return;
250
+ const prev = bridge.prevState;
251
+ const next = container.state;
252
+ bridge.prevState = next;
253
+ for (const { plugin, config } of this.plugins.values()) {
254
+ if (!config.enabled) continue;
255
+ const hook = plugin.onStateChange;
256
+ if (typeof hook !== "function") continue;
257
+ try {
258
+ hook.call(plugin, this.buildContext(container), prev, next, paths);
259
+ } catch (error) {
260
+ console.error(`[BlaC] Error in plugin "${plugin.name}" onStateChange:`, error);
261
+ }
262
+ }
263
+ }
264
+ /**
265
+ * Notify all plugins of a lifecycle event.
266
+ *
267
+ * Builds a fresh `PluginContext` per dispatch (instance becomes
268
+ * `ctx.container`), so plugins can reach the focal bloc through
269
+ * `ctx.container`.
270
+ */
271
+ notifyPlugins(hookName, instance, ...extraArgs) {
272
+ for (const { plugin, config } of this.plugins.values()) {
273
+ if (!config.enabled) continue;
274
+ const hook = plugin[hookName];
275
+ if (typeof hook !== "function") continue;
276
+ try {
277
+ hook.call(plugin, this.buildContext(instance), ...extraArgs);
278
+ } catch (error) {
279
+ console.error(`[BlaC] Error in plugin "${plugin.name}" ${hookName}:`, error);
280
+ }
281
+ }
282
+ }
283
+ /**
284
+ * Build a `PluginContext` for a given focal container. The context is
285
+ * cheap to build — its methods close over `this.registry` directly —
286
+ * so we create one per dispatch rather than caching per container.
287
+ * This sidesteps the lifetime question of "when do we evict a cached
288
+ * context?" and keeps `paths`-vs-`container` lifetimes cleanly
289
+ * separated.
290
+ */
291
+ buildContext(container) {
292
+ const registry = this.registry;
293
+ return {
294
+ container,
295
+ getInstanceMetadata: (instance) => {
296
+ return {
297
+ id: instance.$blac.id,
298
+ className: instance.constructor.name,
299
+ isDisposed: instance.$blac.disposed,
300
+ name: instance.$blac.name,
301
+ createdAt: instance.$blac.createdAt,
302
+ state: instance.state,
303
+ hydrationStatus: instance.$blac.hydration.status,
304
+ isHydrated: instance.$blac.hydration.isHydrated,
305
+ hydrationError: instance.$blac.hydration.error,
306
+ changedWhileHydrating: instance.$blac.hydration.changedWhileHydrating,
307
+ args: instance.args
308
+ };
309
+ },
310
+ getState: (instance) => {
311
+ return instance.state;
312
+ },
313
+ getHydrationStatus: (instance) => {
314
+ return instance.$blac.hydration.status;
315
+ },
316
+ startHydration: (instance) => {
317
+ instance.$blac.hydration.begin();
318
+ },
319
+ applyHydratedState: (instance, state) => {
320
+ return instance.$blac.hydration.apply(state);
321
+ },
322
+ finishHydration: (instance) => {
323
+ instance.$blac.hydration.finish();
324
+ },
325
+ failHydration: (instance, error) => {
326
+ instance.$blac.hydration.fail(error);
327
+ },
328
+ waitForHydration: (instance) => {
329
+ return instance.$blac.hydration.wait();
330
+ },
331
+ queryInstances: (typeClass) => {
332
+ return registry.getAll(typeClass);
333
+ },
334
+ getAllTypes: () => {
335
+ return registry.getTypes();
336
+ },
337
+ getStats: () => {
338
+ return registry.getStats();
339
+ },
340
+ getRefIds: (instanceId) => {
341
+ for (const Type of registry.getTypes()) {
342
+ const map = registry.getInstancesMap(Type);
343
+ for (const [, entry] of map) if (entry.instance.$blac.id === instanceId) return Array.from(entry.refs.keys());
344
+ }
345
+ return [];
346
+ }
347
+ };
348
+ }
349
+ /**
350
+ * Check if plugin should be enabled based on environment
351
+ */
352
+ shouldEnablePlugin(config) {
353
+ if (!config.enabled) return false;
354
+ if (config.environment === "all") return true;
355
+ return this.getCurrentEnvironment() === config.environment;
356
+ }
357
+ /**
358
+ * Get current environment
359
+ */
360
+ getCurrentEnvironment() {
361
+ if (typeof process !== "undefined") {
362
+ if (process.env.NODE_ENV === "test") return "test";
363
+ if (process.env.NODE_ENV === "production") return "production";
364
+ return "development";
365
+ }
366
+ return "development";
367
+ }
368
+ };
369
+ /**
370
+ * Create a plugin manager instance
371
+ * @param registry - The StateContainerRegistry to monitor for lifecycle events
372
+ * @returns A new PluginManager instance
373
+ */
374
+ function createPluginManager(registry) {
375
+ return new PluginManager(registry);
376
+ }
377
+ //#endregion
378
+ //#region src/constants.ts
379
+ /**
380
+ * Default configuration constants for BlaC
381
+ *
382
+ * Centralized location for all magic numbers and default values.
383
+ */
384
+ /**
385
+ * Default configuration constants for BlaC
386
+ */
387
+ const BLAC_DEFAULTS = {
388
+ /**
389
+ * Default instance key for shared instances
390
+ */
391
+ DEFAULT_INSTANCE_KEY: "default",
392
+ /**
393
+ * Maximum getter nesting depth (prevents infinite recursion)
394
+ */
395
+ MAX_GETTER_DEPTH: 10
396
+ };
397
+ /**
398
+ * Static property names for StateContainer classes
399
+ * Used for feature flags and configuration on bloc classes
400
+ */
401
+ const BLAC_STATIC_PROPS = {
402
+ /**
403
+ * Mark a bloc to never be auto-disposed (kept alive permanently)
404
+ */
405
+ KEEP_ALIVE: "keepAlive",
406
+ /**
407
+ * Exclude a bloc from DevTools reporting (prevents infinite loops)
408
+ */
409
+ EXCLUDE_FROM_DEVTOOLS: "__excludeFromDevTools",
410
+ /**
411
+ * Per-class equality function used to short-circuit `emit`/`patch` when the
412
+ * new state is structurally equal to the previous state. Falls back to the
413
+ * global `configureBlac({ equality })` value when unset.
414
+ */
415
+ EQUALITY: "__equality",
416
+ /**
417
+ * Per-class key function: `static key = (args) => string`.
418
+ * When set, the registry calls `Type.key(args)` to derive the instance key
419
+ * instead of using a structural hash of `args`. Allows blocs to ignore
420
+ * non-identity fields (e.g., `readonly` flags) while still keying by id.
421
+ */
422
+ KEY: "key"
423
+ };
424
+ /**
425
+ * Standard error message prefix
426
+ */
427
+ const BLAC_ERROR_PREFIX = "[BlaC]";
428
+ //#endregion
429
+ //#region src/utils/static-props.ts
430
+ /**
431
+ * Utility functions for accessing static properties on StateContainer classes
432
+ */
433
+ /**
434
+ * Get a static property from a class constructor
435
+ * Type-safe helper that avoids (Type as any) casts
436
+ *
437
+ * @param Type - The class constructor
438
+ * @param propName - The property name to access
439
+ * @param defaultValue - Optional default value if property is undefined
440
+ * @returns The property value or default
441
+ */
442
+ function getStaticProp(Type, propName, defaultValue) {
443
+ return Type[propName] ?? defaultValue;
444
+ }
445
+ /**
446
+ * Check if a class is marked as keepAlive.
447
+ * KeepAlive classes are never auto-disposed when ref count reaches 0.
448
+ * @param Type - The class constructor to check
449
+ * @returns true if the class has `static keepAlive = true`
450
+ */
451
+ function isKeepAliveClass(Type) {
452
+ return getStaticProp(Type, BLAC_STATIC_PROPS.KEEP_ALIVE) === true;
453
+ }
454
+ /**
455
+ * Check if a class should be excluded from DevTools.
456
+ * Used to prevent infinite loops when DevTools tracks itself.
457
+ * @param Type - The class constructor to check
458
+ * @returns true if the class has `static __excludeFromDevTools = true`
459
+ */
460
+ function isExcludedFromDevTools(Type) {
461
+ return getStaticProp(Type, BLAC_STATIC_PROPS.EXCLUDE_FROM_DEVTOOLS) === true;
462
+ }
463
+ /**
464
+ * Get the per-class equality function set via `@blac({ equality })`, if any.
465
+ * @param Type - The class constructor to check
466
+ * @returns the equality function or `undefined`
467
+ */
468
+ function getClassEquality(Type) {
469
+ const fn = getStaticProp(Type, BLAC_STATIC_PROPS.EQUALITY);
470
+ return typeof fn === "function" ? fn : void 0;
471
+ }
472
+ /**
473
+ * Get the per-class key function set via `@blac({ key })` or `static key = …`, if any.
474
+ * Used by the registry to derive a stable instance key from `args`.
475
+ * @param Type - The class constructor to check
476
+ * @returns the key function or `undefined`
477
+ */
478
+ function getClassKey(Type) {
479
+ const fn = getStaticProp(Type, BLAC_STATIC_PROPS.KEY, void 0);
480
+ return typeof fn === "function" ? fn : void 0;
481
+ }
482
+ //#endregion
483
+ //#region src/utils/structural-key.ts
484
+ /**
485
+ * Deterministic, order-independent hash of serializable args.
486
+ * Sorts object keys so {a,b} === {b,a}.
487
+ * Throws (dev) if it encounters a function or non-plain object — those belong in `deps`.
488
+ */
489
+ const DEFAULT_STRUCTURAL_KEY = "default";
490
+ /**
491
+ * Produce a stable string key for serializable args.
492
+ * - `undefined` / `void` args → `'default'` sentinel (no-args blocs stay on the default key).
493
+ * - Object keys are sorted for order-independence.
494
+ * - Arrays keep their insertion order.
495
+ * - Functions throw — they must be passed via `deps`, not `args`.
496
+ */
497
+ function structuralKey(args) {
498
+ if (args === void 0 || args === null) return DEFAULT_STRUCTURAL_KEY;
499
+ return JSON.stringify(args, function(_k, v) {
500
+ if (typeof v === "function") throw new Error("[blac] args must be serializable; put refs/callbacks in `deps`");
501
+ if (v && typeof v === "object" && !Array.isArray(v)) return Object.keys(v).sort().reduce((o, k) => {
502
+ o[k] = v[k];
503
+ return o;
504
+ }, {});
505
+ return v;
506
+ });
507
+ }
508
+ //#endregion
509
+ //#region src/core/symbols.ts
510
+ /**
511
+ * @internal Apply one owner's (consumer's) deps slice to an instance.
512
+ * Called by framework adapters (e.g. @blac/react useBloc) — not public API.
513
+ */
514
+ const APPLY_DEPS = Symbol("blac.applyDeps");
515
+ /**
516
+ * @internal Withdraw one owner's entire deps slice (consumer unmounted).
517
+ * Called by framework adapters — not public API.
518
+ */
519
+ const REMOVE_DEPS_OWNER = Symbol("blac.removeDepsOwner");
520
+ /**
521
+ * @internal Symbol-keyed configuration entry point on `StateContainer`.
522
+ * Writes the instance's identity fields (`_name`/`_debug`/`_instanceId`),
523
+ * resolves per-class equality, emits the registry `created` event, and runs
524
+ * `init()` once.
525
+ *
526
+ * Framework-only — the registry (`StateContainerRegistry.ensure`) and testing
527
+ * helpers are the sole callers, mirroring the `APPLY_DEPS` precedent.
528
+ */
529
+ const INIT_CONFIG = Symbol("blac.initConfig");
530
+ //#endregion
531
+ //#region src/core/StateContainerRegistry.ts
532
+ /**
533
+ * Central registry for managing StateContainer instances.
534
+ * Handles instance lifecycle, named ref tracking, and lifecycle event emission.
535
+ *
536
+ * @example
537
+ * ```ts
538
+ * const registry = new StateContainerRegistry();
539
+ * const instance = registry.acquire(MyBloc); // ownership, must release
540
+ * const other = registry.ensure(OtherBloc); // no ownership, bloc-to-bloc
541
+ * registry.on('stateChanged', (container, prev, next) => {
542
+ * console.log('State changed:', prev, '->', next);
543
+ * });
544
+ * ```
545
+ */
546
+ var StateContainerRegistry = class {
547
+ constructor() {
548
+ this.instancesByConstructor = /* @__PURE__ */ new WeakMap();
549
+ this.types = /* @__PURE__ */ new Set();
550
+ this.registeredTypeNames = /* @__PURE__ */ new Set();
551
+ this.listeners = /* @__PURE__ */ new Map();
552
+ this._stateChangedListenerCount = 0;
553
+ this._pendingStateChanges = null;
554
+ this._autoRefIdCounter = 0;
555
+ }
556
+ get hasStateChangedListeners() {
557
+ return this._stateChangedListenerCount > 0;
558
+ }
559
+ /**
560
+ * Register a type for lifecycle event tracking
561
+ * @param constructor - The StateContainer class constructor
562
+ */
563
+ registerType(constructor) {
564
+ this.types.add(constructor);
565
+ }
566
+ /**
567
+ * Register a StateContainer class with configuration
568
+ * @param constructor - The StateContainer class constructor
569
+ * @throws Error if type is already registered
570
+ */
571
+ register(constructor) {
572
+ const className = constructor.name;
573
+ if (this.registeredTypeNames.has(className)) throw new Error(`${BLAC_ERROR_PREFIX} Type "${className}" is already registered`);
574
+ this.registeredTypeNames.add(className);
575
+ this.registerType(constructor);
576
+ }
577
+ ensureInstancesMap(Type) {
578
+ let instances = this.instancesByConstructor.get(Type);
579
+ if (!instances) {
580
+ instances = /* @__PURE__ */ new Map();
581
+ this.instancesByConstructor.set(Type, instances);
582
+ }
583
+ return instances;
584
+ }
585
+ /**
586
+ * Get the instances Map for a specific class (public API for stats/debugging)
587
+ */
588
+ getInstancesMap(Type) {
589
+ return this.instancesByConstructor.get(Type) || /* @__PURE__ */ new Map();
590
+ }
591
+ /**
592
+ * Directly insert an instance entry into the registry without going through
593
+ * acquire/release. Creates the internal WeakMap bucket for the constructor if
594
+ * it does not exist yet. Replaces any existing entry for the same key.
595
+ *
596
+ * The provided instance is NOT configured or disposed here — callers are
597
+ * responsible for any initConfig / dispose calls. Intended for testing
598
+ * helpers that create stubs outside the normal acquisition path.
599
+ *
600
+ * @internal Used by testing helpers only.
601
+ */
602
+ insertInstance(Type, instanceKey, instance, refs = /* @__PURE__ */ new Map()) {
603
+ const instances = this.ensureInstancesMap(Type);
604
+ const existingEntry = instances.get(instanceKey);
605
+ if (existingEntry && existingEntry.instance !== instance && !existingEntry.instance.$blac.disposed) existingEntry.instance.dispose();
606
+ instances.set(instanceKey, {
607
+ instance,
608
+ refs
609
+ });
610
+ }
611
+ /**
612
+ * Resolve the storage key for an instance. This is the single source of truth
613
+ * for keying — `acquire` and `release` MUST agree, otherwise a ref taken under
614
+ * an args-derived key is never dropped (instance leaks).
615
+ *
616
+ * Resolution order (explicit beats derived):
617
+ * explicit key > `static key(args)` > structural hash of args > default sentinel.
618
+ *
619
+ * @param Type - The StateContainer class constructor
620
+ * @param instanceKey - Explicit key, or undefined to derive from args
621
+ * @param args - Construction args used for structural/`static key` derivation
622
+ */
623
+ resolveKey(Type, instanceKey, args) {
624
+ if (instanceKey !== void 0) return instanceKey;
625
+ const keyFn = getClassKey(Type);
626
+ if (keyFn) return keyFn(args);
627
+ if (args !== void 0) return structuralKey(args);
628
+ return DEFAULT_STRUCTURAL_KEY;
629
+ }
630
+ /**
631
+ * Circuit breaker for runaway instance creation. Throws when a single
632
+ * constructor would exceed `maxInstancesPerType` live instances — almost
633
+ * always an unstable instance key (e.g. a new object/array passed as `args`
634
+ * every render, or a missing `static key`) leaking an instance per render.
635
+ */
636
+ assertInstanceLimit(Type, currentCount) {
637
+ const limit = getBlacConfig().maxInstancesPerType;
638
+ 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 })\`.`);
639
+ }
640
+ /**
641
+ * Circuit breaker for runaway reference growth. Throws when one instance
642
+ * accumulates more than `maxRefsPerInstance` distinct live refs — almost
643
+ * always consumer cleanup (e.g. `useBloc`'s unmount `release`) never firing.
644
+ */
645
+ assertRefLimit(Type, resolvedKey, refCount) {
646
+ const limit = getBlacConfig().maxRefsPerInstance;
647
+ 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 })\`.`);
648
+ }
649
+ /**
650
+ * Acquire an instance with ref tracking (ownership semantics).
651
+ * Creates a new instance if one doesn't exist, or returns existing and adds a ref.
652
+ * You must call `release()` with the same refId when done.
653
+ *
654
+ * @internal Internal key tier. Public callers use the args-based `acquire`
655
+ * wrapper; `useBloc` and `watch` address a pre-resolved key here.
656
+ * @param Type - The StateContainer class constructor
657
+ * @param instanceKey - Pre-resolved instance key (defaults to 'default')
658
+ * @param options - Acquisition options
659
+ * @param options.canCreate - Whether to create new instance if not found (default: true)
660
+ * @param options.countRef - Whether to add a reference (default: true)
661
+ * @param options.refId - Named reference ID for debugging; auto-generated if omitted
662
+ * @returns The state container instance
663
+ */
664
+ acquire(Type, instanceKey, options = {}) {
665
+ const { canCreate = true, countRef = true } = options;
666
+ const args = options.args;
667
+ const resolvedKey = this.resolveKey(Type, instanceKey, args);
668
+ const config = {
669
+ instanceId: resolvedKey,
670
+ args
671
+ };
672
+ const instances = this.ensureInstancesMap(Type);
673
+ let entry = instances.get(resolvedKey);
674
+ if (entry?.instance.$blac.disposed) {
675
+ instances.delete(resolvedKey);
676
+ entry = void 0;
677
+ }
678
+ if (entry) {
679
+ if (process.env.NODE_ENV !== "production" && args !== void 0 && entry.args !== void 0) {
680
+ const incomingKey = structuralKey(args);
681
+ const storedKey = structuralKey(entry.args);
682
+ 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.`);
683
+ }
684
+ if (countRef) {
685
+ const refId = options.refId ?? `_auto_${this._autoRefIdCounter++}`;
686
+ entry.refs.set(refId, (entry.refs.get(refId) ?? 0) + 1);
687
+ this.assertRefLimit(Type, resolvedKey, entry.refs.size);
688
+ this.emit("refAcquired", entry.instance, refId);
689
+ }
690
+ return entry.instance;
691
+ }
692
+ if (!canCreate) throw new Error(`${BLAC_ERROR_PREFIX} ${Type.name} instance "${resolvedKey}" not found and creation is disabled.`);
693
+ this.assertInstanceLimit(Type, instances.size);
694
+ const instance = new Type();
695
+ instance[INIT_CONFIG](config);
696
+ const initialRefs = /* @__PURE__ */ new Map();
697
+ let initialRefId;
698
+ if (countRef) {
699
+ initialRefId = options.refId ?? `_auto_${this._autoRefIdCounter++}`;
700
+ initialRefs.set(initialRefId, 1);
701
+ }
702
+ instances.set(resolvedKey, {
703
+ instance,
704
+ refs: initialRefs,
705
+ args
706
+ });
707
+ this.registerType(Type);
708
+ if (initialRefId) this.emit("refAcquired", instance, initialRefId);
709
+ return instance;
710
+ }
711
+ /**
712
+ * Borrow an existing instance without adding a ref (borrowing semantics).
713
+ * Tracks cross-bloc dependency for reactive updates.
714
+ *
715
+ * @internal Internal key tier; public callers use the args-based `borrow`.
716
+ * @param Type - The StateContainer class constructor
717
+ * @param instanceKey - Pre-resolved instance key (defaults to 'default')
718
+ * @returns The state container instance
719
+ * @throws Error if instance doesn't exist
720
+ */
721
+ borrow(Type, instanceKey = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY) {
722
+ return this.acquire(Type, instanceKey, {
723
+ canCreate: false,
724
+ countRef: false
725
+ });
726
+ }
727
+ /**
728
+ * Safely borrow an existing instance (borrowing semantics with error handling).
729
+ * Returns discriminated union for type-safe conditional access.
730
+ *
731
+ * @internal Internal key tier; public callers use the args-based `borrowSafe`.
732
+ * @param Type - The StateContainer class constructor
733
+ * @param instanceKey - Pre-resolved instance key (defaults to 'default')
734
+ * @returns Discriminated union with either the instance or an error
735
+ */
736
+ borrowSafe(Type, instanceKey = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY) {
737
+ try {
738
+ return {
739
+ error: null,
740
+ instance: this.borrow(Type, instanceKey)
741
+ };
742
+ } catch (error) {
743
+ return {
744
+ error,
745
+ instance: null
746
+ };
747
+ }
748
+ }
749
+ /**
750
+ * Ensure an instance exists without taking ownership (for bloc-to-bloc communication).
751
+ * Gets existing instance OR creates it if it doesn't exist, without adding a ref.
752
+ * Tracks cross-bloc dependency for reactive updates.
753
+ *
754
+ * Use this in bloc-to-bloc communication when you need to ensure an instance exists
755
+ * but don't want to claim ownership (no ref added).
756
+ *
757
+ * @internal Internal key tier; public callers use the args-based `ensure`.
758
+ * @param Type - The StateContainer class constructor
759
+ * @param instanceKey - Pre-resolved instance key, or undefined to derive from `args`
760
+ * (`static key(args)` / structural hash), matching `acquire`.
761
+ * @param args - Construction args; used for keying when no explicit key is given
762
+ * @returns The state container instance
763
+ */
764
+ ensure(Type, instanceKey, args) {
765
+ return this.acquire(Type, instanceKey, {
766
+ canCreate: true,
767
+ countRef: false,
768
+ args
769
+ });
770
+ }
771
+ /**
772
+ * Release a reference to an instance.
773
+ * Removes the ref and disposes when refs is empty (unless keepAlive).
774
+ * Releasing an already-removed refId is a no-op (idempotent).
775
+ *
776
+ * @internal Internal key tier; public callers use the args-based `release`.
777
+ * @param Type - The StateContainer class constructor
778
+ * @param instanceKey - Pre-resolved instance key (defaults to 'default')
779
+ * @param forceDispose - Force immediate disposal regardless of refs
780
+ * @param refId - The specific ref to remove; removes one arbitrary ref if omitted
781
+ */
782
+ release(Type, instanceKey = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY, forceDispose = false, refId) {
783
+ const instances = this.ensureInstancesMap(Type);
784
+ const entry = instances.get(instanceKey);
785
+ if (!entry) return;
786
+ if (forceDispose) {
787
+ if (!entry.instance.$blac.disposed) entry.instance.dispose();
788
+ instances.delete(instanceKey);
789
+ return;
790
+ }
791
+ let releasedRefId;
792
+ if (refId !== void 0) {
793
+ const count = entry.refs.get(refId) ?? 0;
794
+ if (count <= 1) entry.refs.delete(refId);
795
+ else entry.refs.set(refId, count - 1);
796
+ releasedRefId = refId;
797
+ } else {
798
+ const firstKey = entry.refs.keys().next().value;
799
+ if (firstKey !== void 0) {
800
+ const count = entry.refs.get(firstKey) ?? 0;
801
+ if (count <= 1) entry.refs.delete(firstKey);
802
+ else entry.refs.set(firstKey, count - 1);
803
+ releasedRefId = firstKey;
804
+ }
805
+ }
806
+ if (releasedRefId) this.emit("refReleased", entry.instance, releasedRefId);
807
+ const keepAlive = isKeepAliveClass(Type);
808
+ if (entry.refs.size === 0 && !keepAlive) {
809
+ const deps = entry.instance.$blac.dependencies;
810
+ if (!entry.instance.$blac.disposed) entry.instance.dispose();
811
+ instances.delete(instanceKey);
812
+ for (const [DepType, depKey] of deps) {
813
+ const depInstances = this.ensureInstancesMap(DepType);
814
+ const depEntry = depInstances.get(depKey);
815
+ if (depEntry && depEntry.refs.size === 0 && !isKeepAliveClass(DepType) && !depEntry.instance.$blac.disposed) {
816
+ depEntry.instance.dispose();
817
+ depInstances.delete(depKey);
818
+ }
819
+ }
820
+ }
821
+ }
822
+ /**
823
+ * Get all instances of a specific type.
824
+ * @param Type - The StateContainer class constructor
825
+ * @returns Array of all instances
826
+ */
827
+ getAll(Type) {
828
+ const instances = this.ensureInstancesMap(Type);
829
+ const result = [];
830
+ for (const entry of instances.values()) result.push(entry.instance);
831
+ return result;
832
+ }
833
+ /**
834
+ * Safely iterate over all instances of a type.
835
+ * Skips disposed instances and catches callback errors.
836
+ * @param Type - The StateContainer class constructor
837
+ * @param callback - Function to call for each instance
838
+ */
839
+ forEach(Type, callback) {
840
+ const instances = this.ensureInstancesMap(Type);
841
+ for (const entry of instances.values()) {
842
+ const instance = entry.instance;
843
+ if (!instance.$blac.disposed) try {
844
+ callback(instance);
845
+ } catch (error) {
846
+ console.error(`${BLAC_ERROR_PREFIX} forEach callback error for ${Type.name}:`, error);
847
+ }
848
+ }
849
+ }
850
+ /**
851
+ * Clear all instances of a specific type (disposes them).
852
+ * @param Type - The StateContainer class constructor
853
+ */
854
+ clear(Type) {
855
+ const instances = this.ensureInstancesMap(Type);
856
+ for (const entry of instances.values()) if (!entry.instance.$blac.disposed) entry.instance.dispose();
857
+ instances.clear();
858
+ }
859
+ /**
860
+ * Get reference count for an instance (number of active refs).
861
+ *
862
+ * @internal Internal key tier; public callers use the args-based `getRefCount`.
863
+ * @param Type - The StateContainer class constructor
864
+ * @param instanceKey - Pre-resolved instance key (defaults to 'default')
865
+ * @returns Current ref count (0 if instance doesn't exist)
866
+ */
867
+ getRefCount(Type, instanceKey = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY) {
868
+ return this.ensureInstancesMap(Type).get(instanceKey)?.refs.size ?? 0;
869
+ }
870
+ /**
871
+ * Get all active reference IDs for an instance.
872
+ *
873
+ * @internal Internal key tier; public callers use the args-based `getRefIds`.
874
+ * @param Type - The StateContainer class constructor
875
+ * @param instanceKey - Pre-resolved instance key (defaults to 'default')
876
+ * @returns Array of ref ID strings (empty if instance doesn't exist)
877
+ */
878
+ getRefIds(Type, instanceKey = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY) {
879
+ const instances = this.instancesByConstructor.get(Type);
880
+ if (!instances) return [];
881
+ const entry = instances.get(instanceKey);
882
+ return entry ? Array.from(entry.refs.keys()) : [];
883
+ }
884
+ /**
885
+ * Check if an instance exists.
886
+ *
887
+ * @internal Internal key tier; public callers use the args-based `hasInstance`.
888
+ * @param Type - The StateContainer class constructor
889
+ * @param instanceKey - Pre-resolved instance key (defaults to 'default')
890
+ * @returns true if instance exists
891
+ */
892
+ hasInstance(Type, instanceKey = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY) {
893
+ return this.ensureInstancesMap(Type).has(instanceKey);
894
+ }
895
+ /**
896
+ * Clear all instances from all types (for testing)
897
+ *
898
+ * Iterates all registered types and clears their instances.
899
+ * Also clears type tracking to reset the registry state.
900
+ */
901
+ clearAll() {
902
+ for (const Type of this.types) this.clear(Type);
903
+ this.types.clear();
904
+ this.registeredTypeNames.clear();
905
+ }
906
+ /**
907
+ * Get registry statistics for debugging.
908
+ * @returns Object with registeredTypes, totalInstances, and typeBreakdown
909
+ */
910
+ getStats() {
911
+ const typeBreakdown = {};
912
+ let totalInstances = 0;
913
+ for (const Type of this.types) {
914
+ const typeName = Type.name;
915
+ const count = this.getInstancesMap(Type).size;
916
+ typeBreakdown[typeName] = count;
917
+ totalInstances += count;
918
+ }
919
+ return {
920
+ registeredTypes: this.types.size,
921
+ totalInstances,
922
+ typeBreakdown
923
+ };
924
+ }
925
+ /**
926
+ * Get all registered types (for plugin system).
927
+ * @returns Array of all registered StateContainer class constructors
928
+ */
929
+ getTypes() {
930
+ return Array.from(this.types);
931
+ }
932
+ /**
933
+ * Subscribe to lifecycle events
934
+ * @param event - The lifecycle event to listen for
935
+ * @param listener - The listener function to call when the event occurs
936
+ * @returns Unsubscribe function
937
+ */
938
+ on(event, listener) {
939
+ if (!this.listeners.has(event)) this.listeners.set(event, /* @__PURE__ */ new Set());
940
+ const instance = this.listeners.get(event);
941
+ if (!instance) throw new Error(`${BLAC_ERROR_PREFIX} Failed to register listener for event '${event}'`);
942
+ instance.add(listener);
943
+ if (event === "stateChanged") this._stateChangedListenerCount++;
944
+ return () => {
945
+ if (this.listeners.get(event)?.delete(listener) && event === "stateChanged") this._stateChangedListenerCount--;
946
+ };
947
+ }
948
+ emit(event, ...args) {
949
+ const listeners = this.listeners.get(event);
950
+ if (!listeners || listeners.size === 0) return;
951
+ for (const listener of listeners) try {
952
+ listener(...args);
953
+ } catch (error) {
954
+ console.error(`${BLAC_ERROR_PREFIX} Listener error for '${event}':`, error);
955
+ }
956
+ }
957
+ /**
958
+ * Schedule a deferred stateChanged notification via microtask.
959
+ * Skips entirely when no stateChanged listeners are registered.
960
+ * @internal - Called by StateContainer.applyState
961
+ */
962
+ notifyStateChanged(container, previousState, newState) {
963
+ if (this._stateChangedListenerCount === 0) return;
964
+ if (!this._pendingStateChanges) {
965
+ this._pendingStateChanges = [];
966
+ queueMicrotask(() => this.flushStateChanged());
967
+ }
968
+ this._pendingStateChanges.push([
969
+ container,
970
+ previousState,
971
+ newState
972
+ ]);
973
+ }
974
+ flushStateChanged() {
975
+ const pending = this._pendingStateChanges;
976
+ this._pendingStateChanges = null;
977
+ if (!pending) return;
978
+ for (const [container, prev, next] of pending) this.emit("stateChanged", container, prev, next);
979
+ }
980
+ };
981
+ /**
982
+ * Global default registry instance
983
+ */
984
+ const globalRegistry = new StateContainerRegistry();
985
+ /**
986
+ * Global plugin manager (initialized lazily)
987
+ */
988
+ let _globalPluginManager = null;
989
+ /**
990
+ * Get the global plugin manager
991
+ */
992
+ function getPluginManager() {
993
+ if (!_globalPluginManager) _globalPluginManager = createPluginManager(globalRegistry);
994
+ return _globalPluginManager;
995
+ }
996
+ //#endregion
997
+ Object.defineProperty(exports, "APPLY_DEPS", {
998
+ enumerable: true,
999
+ get: function() {
1000
+ return APPLY_DEPS;
1001
+ }
1002
+ });
1003
+ Object.defineProperty(exports, "BLAC_STATIC_PROPS", {
1004
+ enumerable: true,
1005
+ get: function() {
1006
+ return BLAC_STATIC_PROPS;
1007
+ }
1008
+ });
1009
+ Object.defineProperty(exports, "INIT_CONFIG", {
1010
+ enumerable: true,
1011
+ get: function() {
1012
+ return INIT_CONFIG;
1013
+ }
1014
+ });
1015
+ Object.defineProperty(exports, "PluginManager", {
1016
+ enumerable: true,
1017
+ get: function() {
1018
+ return PluginManager;
1019
+ }
1020
+ });
1021
+ Object.defineProperty(exports, "REMOVE_DEPS_OWNER", {
1022
+ enumerable: true,
1023
+ get: function() {
1024
+ return REMOVE_DEPS_OWNER;
1025
+ }
1026
+ });
1027
+ Object.defineProperty(exports, "StateContainerRegistry", {
1028
+ enumerable: true,
1029
+ get: function() {
1030
+ return StateContainerRegistry;
1031
+ }
1032
+ });
1033
+ Object.defineProperty(exports, "configureBlac", {
1034
+ enumerable: true,
1035
+ get: function() {
1036
+ return configureBlac;
1037
+ }
1038
+ });
1039
+ Object.defineProperty(exports, "getBlacConfig", {
1040
+ enumerable: true,
1041
+ get: function() {
1042
+ return getBlacConfig;
1043
+ }
1044
+ });
1045
+ Object.defineProperty(exports, "getClassEquality", {
1046
+ enumerable: true,
1047
+ get: function() {
1048
+ return getClassEquality;
1049
+ }
1050
+ });
1051
+ Object.defineProperty(exports, "getPluginManager", {
1052
+ enumerable: true,
1053
+ get: function() {
1054
+ return getPluginManager;
1055
+ }
1056
+ });
1057
+ Object.defineProperty(exports, "globalRegistry", {
1058
+ enumerable: true,
1059
+ get: function() {
1060
+ return globalRegistry;
1061
+ }
1062
+ });
1063
+ Object.defineProperty(exports, "isExcludedFromDevTools", {
1064
+ enumerable: true,
1065
+ get: function() {
1066
+ return isExcludedFromDevTools;
1067
+ }
1068
+ });
1069
+ Object.defineProperty(exports, "isKeepAliveClass", {
1070
+ enumerable: true,
1071
+ get: function() {
1072
+ return isKeepAliveClass;
1073
+ }
1074
+ });
1075
+ Object.defineProperty(exports, "resetBlacConfig", {
1076
+ enumerable: true,
1077
+ get: function() {
1078
+ return resetBlacConfig;
1079
+ }
1080
+ });
1081
+ Object.defineProperty(exports, "shallowEqualState", {
1082
+ enumerable: true,
1083
+ get: function() {
1084
+ return shallowEqualState;
1085
+ }
1086
+ });
1087
+
1088
+ //# sourceMappingURL=StateContainerRegistry-D9BIRjwv.cjs.map