@blac/core 2.0.12 → 2.0.13

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 (180) hide show
  1. package/dist/Cubit-BBKF3PIg.js +248 -0
  2. package/dist/Cubit-BBKF3PIg.js.map +1 -0
  3. package/dist/Cubit-BOxMvpfc.js +250 -0
  4. package/dist/Cubit-BOxMvpfc.js.map +1 -0
  5. package/dist/Cubit-BogJXkLm.js +243 -0
  6. package/dist/Cubit-BogJXkLm.js.map +1 -0
  7. package/dist/Cubit-COfHT1Bm.cjs +280 -0
  8. package/dist/Cubit-COfHT1Bm.cjs.map +1 -0
  9. package/dist/Cubit-CXxh9iol.js +260 -0
  10. package/dist/Cubit-CXxh9iol.js.map +1 -0
  11. package/dist/Cubit-CYOWfzQt.cjs +274 -0
  12. package/dist/Cubit-CYOWfzQt.cjs.map +1 -0
  13. package/dist/Cubit-CcKgMEBO.js +257 -0
  14. package/dist/Cubit-CcKgMEBO.js.map +1 -0
  15. package/dist/Cubit-CfT6Y1jl.js +298 -0
  16. package/dist/Cubit-CfT6Y1jl.js.map +1 -0
  17. package/dist/Cubit-DKEY9WYq.cjs +260 -0
  18. package/dist/Cubit-DKEY9WYq.cjs.map +1 -0
  19. package/dist/Cubit-DrqG3SP3.cjs +321 -0
  20. package/dist/Cubit-DrqG3SP3.cjs.map +1 -0
  21. package/dist/Cubit-DsDkCo42.cjs +271 -0
  22. package/dist/Cubit-DsDkCo42.cjs.map +1 -0
  23. package/dist/Cubit-DwRw1E9D.cjs +267 -0
  24. package/dist/Cubit-DwRw1E9D.cjs.map +1 -0
  25. package/dist/Cubit-NRhvdDQ6.js +257 -0
  26. package/dist/Cubit-NRhvdDQ6.js.map +1 -0
  27. package/dist/Cubit-jz922NKf.cjs +277 -0
  28. package/dist/Cubit-jz922NKf.cjs.map +1 -0
  29. package/dist/StateContainerRegistry-BAcxouCu.js +655 -0
  30. package/dist/StateContainerRegistry-BAcxouCu.js.map +1 -0
  31. package/dist/StateContainerRegistry-BK57H92E.js +676 -0
  32. package/dist/StateContainerRegistry-BK57H92E.js.map +1 -0
  33. package/dist/StateContainerRegistry-BglEhqdA.js +646 -0
  34. package/dist/StateContainerRegistry-BglEhqdA.js.map +1 -0
  35. package/dist/StateContainerRegistry-BpO5t-0i.js +620 -0
  36. package/dist/StateContainerRegistry-BpO5t-0i.js.map +1 -0
  37. package/dist/StateContainerRegistry-CDH9mnQS.cjs +661 -0
  38. package/dist/StateContainerRegistry-CDH9mnQS.cjs.map +1 -0
  39. package/dist/StateContainerRegistry-CTOXUf75.cjs +687 -0
  40. package/dist/StateContainerRegistry-CTOXUf75.cjs.map +1 -0
  41. package/dist/StateContainerRegistry-CX2CBOmv.cjs +735 -0
  42. package/dist/StateContainerRegistry-CX2CBOmv.cjs.map +1 -0
  43. package/dist/StateContainerRegistry-Ci0ajc5g.js +652 -0
  44. package/dist/StateContainerRegistry-Ci0ajc5g.js.map +1 -0
  45. package/dist/StateContainerRegistry-D1lVJFGL.cjs +693 -0
  46. package/dist/StateContainerRegistry-D1lVJFGL.cjs.map +1 -0
  47. package/dist/StateContainerRegistry-Upsrlg9G.cjs +696 -0
  48. package/dist/StateContainerRegistry-Upsrlg9G.cjs.map +1 -0
  49. package/dist/config-B3NIwDQv.cjs +32 -0
  50. package/dist/config-B3NIwDQv.cjs.map +1 -0
  51. package/dist/config-BKGHop0V.js +16 -0
  52. package/dist/config-BKGHop0V.js.map +1 -0
  53. package/dist/config-BR0Xy-Tn.cjs +32 -0
  54. package/dist/config-BR0Xy-Tn.cjs.map +1 -0
  55. package/dist/config-CQH9fTY-.cjs +32 -0
  56. package/dist/config-CQH9fTY-.cjs.map +1 -0
  57. package/dist/config-Cwj8-C1J.js +16 -0
  58. package/dist/config-Cwj8-C1J.js.map +1 -0
  59. package/dist/config-DEcslxan.cjs +32 -0
  60. package/dist/config-DEcslxan.cjs.map +1 -0
  61. package/dist/config-De9oQ6Ki.js +16 -0
  62. package/dist/config-De9oQ6Ki.js.map +1 -0
  63. package/dist/config-H6FAqbW4.cjs +32 -0
  64. package/dist/config-H6FAqbW4.cjs.map +1 -0
  65. package/dist/config-Yp645dGK.js +16 -0
  66. package/dist/config-Yp645dGK.js.map +1 -0
  67. package/dist/config-ispAzOZV.js +16 -0
  68. package/dist/config-ispAzOZV.js.map +1 -0
  69. package/dist/constants.d.cts +5 -28
  70. package/dist/constants.d.ts +5 -28
  71. package/dist/core/Cubit.d.ts +0 -1
  72. package/dist/core/StateContainer.d.ts +4 -7
  73. package/dist/core/StateContainerRegistry.d.ts +18 -3
  74. package/dist/core/symbols.d.ts +0 -1
  75. package/dist/debug.cjs +3 -3
  76. package/dist/debug.js +3 -3
  77. package/dist/ensure-C3eIRs6e.cjs +14 -0
  78. package/dist/ensure-C3eIRs6e.cjs.map +1 -0
  79. package/dist/ensure-CN6unBOe.cjs +14 -0
  80. package/dist/ensure-CN6unBOe.cjs.map +1 -0
  81. package/dist/ensure-CWKzeno7.js +9 -0
  82. package/dist/ensure-CWKzeno7.js.map +1 -0
  83. package/dist/ensure-DGEtPU9A.cjs +14 -0
  84. package/dist/ensure-DGEtPU9A.cjs.map +1 -0
  85. package/dist/ensure-DME-_T0j.cjs +14 -0
  86. package/dist/ensure-DME-_T0j.cjs.map +1 -0
  87. package/dist/ensure-DWd0GCYB.js +9 -0
  88. package/dist/ensure-DWd0GCYB.js.map +1 -0
  89. package/dist/ensure-Dr7I78Ku.cjs +14 -0
  90. package/dist/ensure-Dr7I78Ku.cjs.map +1 -0
  91. package/dist/ensure-SLVdGd5b.js +9 -0
  92. package/dist/ensure-SLVdGd5b.js.map +1 -0
  93. package/dist/ensure-l2-H7S5W.js +9 -0
  94. package/dist/ensure-l2-H7S5W.js.map +1 -0
  95. package/dist/ensure-nCxg7MCN.js +9 -0
  96. package/dist/ensure-nCxg7MCN.js.map +1 -0
  97. package/dist/index.cjs +9 -7
  98. package/dist/index.d.cts +2 -1
  99. package/dist/index.d.ts +2 -1
  100. package/dist/index.js +7 -7
  101. package/dist/management-B46QwA9Y.js +32 -0
  102. package/dist/management-B46QwA9Y.js.map +1 -0
  103. package/dist/management-BCKTEZ8Q.js +32 -0
  104. package/dist/management-BCKTEZ8Q.js.map +1 -0
  105. package/dist/management-BnedF5ZD.cjs +79 -0
  106. package/dist/management-BnedF5ZD.cjs.map +1 -0
  107. package/dist/management-CK-GL3wY.js +32 -0
  108. package/dist/management-CK-GL3wY.js.map +1 -0
  109. package/dist/management-DL0Uzsoz.js +32 -0
  110. package/dist/management-DL0Uzsoz.js.map +1 -0
  111. package/dist/management-DMZ8qpwr.cjs +79 -0
  112. package/dist/management-DMZ8qpwr.cjs.map +1 -0
  113. package/dist/management-DYLNyj9p.cjs +79 -0
  114. package/dist/management-DYLNyj9p.cjs.map +1 -0
  115. package/dist/management-DjBU1gtb.cjs +79 -0
  116. package/dist/management-DjBU1gtb.cjs.map +1 -0
  117. package/dist/management-DwCozsY8.js +32 -0
  118. package/dist/management-DwCozsY8.js.map +1 -0
  119. package/dist/management-ry_KteFK.cjs +79 -0
  120. package/dist/management-ry_KteFK.cjs.map +1 -0
  121. package/dist/plugin/BlacPlugin.d.ts +1 -105
  122. package/dist/plugin/PluginManager.d.ts +2 -0
  123. package/dist/plugins.cjs +1 -1
  124. package/dist/plugins.js +1 -1
  125. package/dist/resolve-dependencies-B2QggQAi.js +646 -0
  126. package/dist/resolve-dependencies-B2QggQAi.js.map +1 -0
  127. package/dist/resolve-dependencies-B6JDXvpr.js +654 -0
  128. package/dist/resolve-dependencies-B6JDXvpr.js.map +1 -0
  129. package/dist/resolve-dependencies-BNeayhbQ.cjs +779 -0
  130. package/dist/resolve-dependencies-BNeayhbQ.cjs.map +1 -0
  131. package/dist/resolve-dependencies-BWEMpuDy.js +646 -0
  132. package/dist/resolve-dependencies-BWEMpuDy.js.map +1 -0
  133. package/dist/resolve-dependencies-By26rT_i.js +654 -0
  134. package/dist/resolve-dependencies-By26rT_i.js.map +1 -0
  135. package/dist/resolve-dependencies-C9Kf7AzY.cjs +774 -0
  136. package/dist/resolve-dependencies-C9Kf7AzY.cjs.map +1 -0
  137. package/dist/resolve-dependencies-ClSsP0DJ.cjs +771 -0
  138. package/dist/resolve-dependencies-ClSsP0DJ.cjs.map +1 -0
  139. package/dist/resolve-dependencies-DMlqYJR2.js +649 -0
  140. package/dist/resolve-dependencies-DMlqYJR2.js.map +1 -0
  141. package/dist/resolve-dependencies-Dd8T6TLt.cjs +774 -0
  142. package/dist/resolve-dependencies-Dd8T6TLt.cjs.map +1 -0
  143. package/dist/resolve-dependencies-Dfdp_DZd.cjs +779 -0
  144. package/dist/resolve-dependencies-Dfdp_DZd.cjs.map +1 -0
  145. package/dist/resolve-dependencies-KSpTt4jy.cjs +771 -0
  146. package/dist/resolve-dependencies-KSpTt4jy.cjs.map +1 -0
  147. package/dist/resolve-dependencies-Nvjp4CwS.js +649 -0
  148. package/dist/resolve-dependencies-Nvjp4CwS.js.map +1 -0
  149. package/dist/testing.cjs +4 -4
  150. package/dist/testing.js +4 -4
  151. package/dist/tracked-BTbFkFeM.js +192 -0
  152. package/dist/tracked-BTbFkFeM.js.map +1 -0
  153. package/dist/tracked-BhQtzUhZ.js +192 -0
  154. package/dist/tracked-BhQtzUhZ.js.map +1 -0
  155. package/dist/tracked-C52awNV9.js +177 -0
  156. package/dist/tracked-C52awNV9.js.map +1 -0
  157. package/dist/tracked-CGzduF2m.js +192 -0
  158. package/dist/tracked-CGzduF2m.js.map +1 -0
  159. package/dist/tracked-CK_-ixtX.cjs +206 -0
  160. package/dist/tracked-CK_-ixtX.cjs.map +1 -0
  161. package/dist/tracked-CLlvURln.js +192 -0
  162. package/dist/tracked-CLlvURln.js.map +1 -0
  163. package/dist/tracked-CgHWmuGC.cjs +221 -0
  164. package/dist/tracked-CgHWmuGC.cjs.map +1 -0
  165. package/dist/tracked-D3Xjm1H1.cjs +221 -0
  166. package/dist/tracked-D3Xjm1H1.cjs.map +1 -0
  167. package/dist/tracked-DN3h3Rp1.js +177 -0
  168. package/dist/tracked-DN3h3Rp1.js.map +1 -0
  169. package/dist/tracked-DUkp4zve.cjs +206 -0
  170. package/dist/tracked-DUkp4zve.cjs.map +1 -0
  171. package/dist/tracked-O2lv-kJV.cjs +221 -0
  172. package/dist/tracked-O2lv-kJV.cjs.map +1 -0
  173. package/dist/tracked-njU-_pVa.cjs +221 -0
  174. package/dist/tracked-njU-_pVa.cjs.map +1 -0
  175. package/dist/tracking.cjs +1 -1
  176. package/dist/tracking.js +1 -1
  177. package/dist/utils/static-props.d.ts +9 -0
  178. package/dist/watch-entry.cjs +1 -1
  179. package/dist/watch-entry.js +1 -1
  180. package/package.json +1 -1
@@ -0,0 +1,676 @@
1
+ //#region src/constants.ts
2
+ /**
3
+ * Default configuration constants for BlaC
4
+ *
5
+ * Centralized location for all magic numbers and default values.
6
+ */
7
+ /**
8
+ * Default configuration constants for BlaC
9
+ */
10
+ const BLAC_DEFAULTS = {
11
+ DEFAULT_INSTANCE_KEY: "default",
12
+ MAX_GETTER_DEPTH: 10
13
+ };
14
+ /**
15
+ * Static property names for StateContainer classes
16
+ * Used for feature flags and configuration on bloc classes
17
+ */
18
+ const BLAC_STATIC_PROPS = {
19
+ KEEP_ALIVE: "keepAlive",
20
+ EXCLUDE_FROM_DEVTOOLS: "__excludeFromDevTools",
21
+ ISOLATED: "isolated"
22
+ };
23
+ /**
24
+ * Standard error message prefix
25
+ */
26
+ const BLAC_ERROR_PREFIX = "[BlaC]";
27
+ //#endregion
28
+ //#region src/plugin/PluginManager.ts
29
+ /**
30
+ * Manages plugin lifecycle for the BlaC state management system.
31
+ * Plugins receive notifications about state container lifecycle events.
32
+ *
33
+ * @example
34
+ * ```ts
35
+ * const manager = createPluginManager(registry);
36
+ * manager.install(myPlugin, { environment: 'development' });
37
+ * ```
38
+ */
39
+ var PluginManager = class {
40
+ /**
41
+ * Create a new PluginManager
42
+ * @param registry - The StateContainerRegistry to monitor for lifecycle events
43
+ */
44
+ constructor(registry) {
45
+ this.plugins = /* @__PURE__ */ new Map();
46
+ this.lifecycleUnsubscribers = [];
47
+ this.registry = registry;
48
+ this.setupLifecycleHooks();
49
+ }
50
+ /**
51
+ * Install a plugin with optional configuration
52
+ * @param plugin - The plugin to install
53
+ * @param config - Optional plugin configuration
54
+ * @throws Error if plugin is already installed
55
+ */
56
+ install(plugin, config = {}) {
57
+ const effectiveConfig = {
58
+ enabled: true,
59
+ environment: "all",
60
+ ...config
61
+ };
62
+ if (!this.shouldEnablePlugin(effectiveConfig)) {
63
+ console.log(`[BlaC] Plugin "${plugin.name}" skipped (environment mismatch)`);
64
+ return;
65
+ }
66
+ if (this.plugins.has(plugin.name)) throw new Error(`Plugin "${plugin.name}" is already installed`);
67
+ const context = this.createPluginContext();
68
+ this.plugins.set(plugin.name, {
69
+ plugin,
70
+ config: effectiveConfig,
71
+ context
72
+ });
73
+ if (plugin.onInstall) try {
74
+ plugin.onInstall(context);
75
+ } catch (error) {
76
+ console.error(`[BlaC] Error installing plugin "${plugin.name}":`, error);
77
+ this.plugins.delete(plugin.name);
78
+ throw error;
79
+ }
80
+ console.log(`[BlaC] Plugin "${plugin.name}" v${plugin.version} installed`);
81
+ }
82
+ /**
83
+ * Uninstall a plugin by name
84
+ * @param pluginName - The name of the plugin to uninstall
85
+ * @throws Error if plugin is not installed
86
+ */
87
+ uninstall(pluginName) {
88
+ const installed = this.plugins.get(pluginName);
89
+ if (!installed) throw new Error(`Plugin "${pluginName}" is not installed`);
90
+ if (installed.plugin.onUninstall) try {
91
+ installed.plugin.onUninstall();
92
+ } catch (error) {
93
+ console.error(`[BlaC] Error uninstalling plugin "${pluginName}":`, error);
94
+ }
95
+ this.plugins.delete(pluginName);
96
+ console.log(`[BlaC] Plugin "${pluginName}" uninstalled`);
97
+ }
98
+ /**
99
+ * Get an installed plugin by name
100
+ * @param pluginName - The name of the plugin to retrieve
101
+ * @returns The plugin instance or undefined if not found
102
+ */
103
+ getPlugin(pluginName) {
104
+ return this.plugins.get(pluginName)?.plugin;
105
+ }
106
+ /**
107
+ * Get all installed plugins
108
+ * @returns Array of all installed plugins
109
+ */
110
+ getAllPlugins() {
111
+ return Array.from(this.plugins.values()).map((p) => p.plugin);
112
+ }
113
+ /**
114
+ * Check if a plugin is installed
115
+ * @param pluginName - The name of the plugin to check
116
+ * @returns true if the plugin is installed
117
+ */
118
+ hasPlugin(pluginName) {
119
+ return this.plugins.has(pluginName);
120
+ }
121
+ /**
122
+ * Uninstall all plugins
123
+ */
124
+ clear() {
125
+ for (const name of this.plugins.keys()) this.uninstall(name);
126
+ }
127
+ destroy() {
128
+ this.clear();
129
+ for (const unsub of this.lifecycleUnsubscribers) unsub();
130
+ this.lifecycleUnsubscribers = [];
131
+ }
132
+ /**
133
+ * Setup lifecycle hooks to notify plugins
134
+ */
135
+ setupLifecycleHooks() {
136
+ this.lifecycleUnsubscribers = [
137
+ this.registry.on("created", (instance) => {
138
+ this.notifyPlugins("onInstanceCreated", instance);
139
+ }),
140
+ this.registry.on("stateChanged", (instance, previousState, currentState) => {
141
+ this.notifyPlugins("onStateChanged", instance, previousState, currentState);
142
+ }),
143
+ this.registry.on("disposed", (instance) => {
144
+ this.notifyPlugins("onInstanceDisposed", instance);
145
+ }),
146
+ this.registry.on("refAcquired", (instance, refId) => {
147
+ this.notifyPlugins("onRefAcquired", instance, refId);
148
+ }),
149
+ this.registry.on("refReleased", (instance, refId) => {
150
+ this.notifyPlugins("onRefReleased", instance, refId);
151
+ })
152
+ ];
153
+ }
154
+ /**
155
+ * Notify all plugins of a lifecycle event
156
+ */
157
+ notifyPlugins(hookName, ...args) {
158
+ for (const { plugin, config, context } of this.plugins.values()) {
159
+ if (!config.enabled) continue;
160
+ const hook = plugin[hookName];
161
+ if (typeof hook === "function") try {
162
+ hook.apply(plugin, [...args, context]);
163
+ } catch (error) {
164
+ console.error(`[BlaC] Error in plugin "${plugin.name}" ${hookName}:`, error);
165
+ }
166
+ }
167
+ }
168
+ /**
169
+ * Create plugin context with safe API access
170
+ */
171
+ createPluginContext() {
172
+ return {
173
+ getInstanceMetadata: (instance) => {
174
+ return {
175
+ id: instance.instanceId,
176
+ className: instance.constructor.name,
177
+ isDisposed: instance.isDisposed,
178
+ name: instance.name,
179
+ createdAt: instance.createdAt,
180
+ state: instance.state,
181
+ hydrationStatus: instance.hydrationStatus,
182
+ isHydrated: instance.isHydrated,
183
+ hydrationError: instance.hydrationError,
184
+ changedWhileHydrating: instance.changedWhileHydrating
185
+ };
186
+ },
187
+ getState: (instance) => {
188
+ return instance.state;
189
+ },
190
+ getHydrationStatus: (instance) => {
191
+ return instance.hydrationStatus;
192
+ },
193
+ startHydration: (instance) => {
194
+ instance.beginHydration();
195
+ },
196
+ applyHydratedState: (instance, state) => {
197
+ return instance.applyHydratedState(state);
198
+ },
199
+ finishHydration: (instance) => {
200
+ instance.finishHydration();
201
+ },
202
+ failHydration: (instance, error) => {
203
+ instance.failHydration(error);
204
+ },
205
+ waitForHydration: (instance) => {
206
+ return instance.waitForHydration();
207
+ },
208
+ queryInstances: (typeClass) => {
209
+ return this.registry.getAll(typeClass);
210
+ },
211
+ getAllTypes: () => {
212
+ return this.registry.getTypes();
213
+ },
214
+ getStats: () => {
215
+ return this.registry.getStats();
216
+ },
217
+ getRefIds: (instanceId) => {
218
+ for (const Type of this.registry.getTypes()) {
219
+ const map = this.registry.getInstancesMap(Type);
220
+ for (const [, entry] of map) if (entry.instance.instanceId === instanceId) return Array.from(entry.refs.keys());
221
+ }
222
+ return [];
223
+ }
224
+ };
225
+ }
226
+ /**
227
+ * Check if plugin should be enabled based on environment
228
+ */
229
+ shouldEnablePlugin(config) {
230
+ if (!config.enabled) return false;
231
+ if (config.environment === "all") return true;
232
+ return this.getCurrentEnvironment() === config.environment;
233
+ }
234
+ /**
235
+ * Get current environment
236
+ */
237
+ getCurrentEnvironment() {
238
+ if (typeof process !== "undefined") {
239
+ if (process.env.NODE_ENV === "test") return "test";
240
+ if (process.env.NODE_ENV === "production") return "production";
241
+ return "development";
242
+ }
243
+ return "development";
244
+ }
245
+ };
246
+ /**
247
+ * Create a plugin manager instance
248
+ * @param registry - The StateContainerRegistry to monitor for lifecycle events
249
+ * @returns A new PluginManager instance
250
+ */
251
+ function createPluginManager(registry) {
252
+ return new PluginManager(registry);
253
+ }
254
+ //#endregion
255
+ //#region src/utils/static-props.ts
256
+ /**
257
+ * Utility functions for accessing static properties on StateContainer classes
258
+ */
259
+ /**
260
+ * Get a static property from a class constructor
261
+ * Type-safe helper that avoids (Type as any) casts
262
+ *
263
+ * @param Type - The class constructor
264
+ * @param propName - The property name to access
265
+ * @param defaultValue - Optional default value if property is undefined
266
+ * @returns The property value or default
267
+ */
268
+ function getStaticProp(Type, propName, defaultValue) {
269
+ return Type[propName] ?? defaultValue;
270
+ }
271
+ /**
272
+ * Check if a class is marked as keepAlive.
273
+ * KeepAlive classes are never auto-disposed when ref count reaches 0.
274
+ * @param Type - The class constructor to check
275
+ * @returns true if the class has `static keepAlive = true`
276
+ */
277
+ function isKeepAliveClass(Type) {
278
+ return getStaticProp(Type, BLAC_STATIC_PROPS.KEEP_ALIVE) === true;
279
+ }
280
+ /**
281
+ * Check if a class should be excluded from DevTools.
282
+ * Used to prevent infinite loops when DevTools tracks itself.
283
+ * @param Type - The class constructor to check
284
+ * @returns true if the class has `static __excludeFromDevTools = true`
285
+ */
286
+ function isExcludedFromDevTools(Type) {
287
+ return getStaticProp(Type, BLAC_STATIC_PROPS.EXCLUDE_FROM_DEVTOOLS) === true;
288
+ }
289
+ /**
290
+ * Check if a class is marked as isolated.
291
+ * Isolated classes get a fresh, per-mount instance from `useBloc`
292
+ * (auto-keyed via React's `useId()`), instead of sharing the default
293
+ * instance with sibling call sites.
294
+ * @param Type - The class constructor to check
295
+ * @returns true if the class has `static isolated = true`
296
+ */
297
+ function isIsolatedClass(Type) {
298
+ return getStaticProp(Type, BLAC_STATIC_PROPS.ISOLATED) === true;
299
+ }
300
+ //#endregion
301
+ //#region src/core/StateContainerRegistry.ts
302
+ /**
303
+ * Central registry for managing StateContainer instances.
304
+ * Handles instance lifecycle, named ref tracking, and lifecycle event emission.
305
+ *
306
+ * @example
307
+ * ```ts
308
+ * const registry = new StateContainerRegistry();
309
+ * const instance = registry.acquire(MyBloc); // ownership, must release
310
+ * const other = registry.ensure(OtherBloc); // no ownership, bloc-to-bloc
311
+ * registry.on('stateChanged', (container, prev, next) => {
312
+ * console.log('State changed:', prev, '->', next);
313
+ * });
314
+ * ```
315
+ */
316
+ var StateContainerRegistry = class {
317
+ constructor() {
318
+ this.instancesByConstructor = /* @__PURE__ */ new WeakMap();
319
+ this.types = /* @__PURE__ */ new Set();
320
+ this.registeredTypeNames = /* @__PURE__ */ new Set();
321
+ this.listeners = /* @__PURE__ */ new Map();
322
+ this._stateChangedListenerCount = 0;
323
+ this._pendingStateChanges = null;
324
+ this._autoRefIdCounter = 0;
325
+ }
326
+ get hasStateChangedListeners() {
327
+ return this._stateChangedListenerCount > 0;
328
+ }
329
+ /**
330
+ * Register a type for lifecycle event tracking
331
+ * @param constructor - The StateContainer class constructor
332
+ */
333
+ registerType(constructor) {
334
+ this.types.add(constructor);
335
+ }
336
+ /**
337
+ * Register a StateContainer class with configuration
338
+ * @param constructor - The StateContainer class constructor
339
+ * @throws Error if type is already registered
340
+ */
341
+ register(constructor) {
342
+ const className = constructor.name;
343
+ if (this.registeredTypeNames.has(className)) throw new Error(`${BLAC_ERROR_PREFIX} Type "${className}" is already registered`);
344
+ this.registeredTypeNames.add(className);
345
+ this.registerType(constructor);
346
+ }
347
+ ensureInstancesMap(Type) {
348
+ let instances = this.instancesByConstructor.get(Type);
349
+ if (!instances) {
350
+ instances = /* @__PURE__ */ new Map();
351
+ this.instancesByConstructor.set(Type, instances);
352
+ }
353
+ return instances;
354
+ }
355
+ /**
356
+ * Get the instances Map for a specific class (public API for stats/debugging)
357
+ */
358
+ getInstancesMap(Type) {
359
+ return this.instancesByConstructor.get(Type) || /* @__PURE__ */ new Map();
360
+ }
361
+ /**
362
+ * Acquire an instance with ref tracking (ownership semantics).
363
+ * Creates a new instance if one doesn't exist, or returns existing and adds a ref.
364
+ * You must call `release()` with the same refId when done.
365
+ * @param Type - The StateContainer class constructor
366
+ * @param instanceKey - Instance key (defaults to 'default')
367
+ * @param options - Acquisition options
368
+ * @param options.canCreate - Whether to create new instance if not found (default: true)
369
+ * @param options.countRef - Whether to add a reference (default: true)
370
+ * @param options.refId - Named reference ID for debugging; auto-generated if omitted
371
+ * @returns The state container instance
372
+ */
373
+ acquire(Type, instanceKey = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY, options = {}) {
374
+ const { canCreate = true, countRef = true } = options;
375
+ const config = { instanceId: instanceKey };
376
+ const instances = this.ensureInstancesMap(Type);
377
+ let entry = instances.get(instanceKey);
378
+ if (entry?.instance.isDisposed) {
379
+ instances.delete(instanceKey);
380
+ entry = void 0;
381
+ }
382
+ if (entry && countRef) {
383
+ const refId = options.refId ?? `_auto_${this._autoRefIdCounter++}`;
384
+ entry.refs.set(refId, (entry.refs.get(refId) ?? 0) + 1);
385
+ this.emit("refAcquired", entry.instance, refId);
386
+ }
387
+ if (entry) return entry.instance;
388
+ if (!canCreate) throw new Error(`${BLAC_ERROR_PREFIX} ${Type.name} instance "${instanceKey}" not found and creation is disabled.`);
389
+ const instance = new Type();
390
+ instance.initConfig(config);
391
+ const initialRefs = /* @__PURE__ */ new Map();
392
+ let initialRefId;
393
+ if (countRef) {
394
+ initialRefId = options.refId ?? `_auto_${this._autoRefIdCounter++}`;
395
+ initialRefs.set(initialRefId, 1);
396
+ }
397
+ instances.set(instanceKey, {
398
+ instance,
399
+ refs: initialRefs
400
+ });
401
+ this.registerType(Type);
402
+ if (initialRefId) this.emit("refAcquired", instance, initialRefId);
403
+ return instance;
404
+ }
405
+ /**
406
+ * Borrow an existing instance without adding a ref (borrowing semantics).
407
+ * Tracks cross-bloc dependency for reactive updates.
408
+ * @param Type - The StateContainer class constructor
409
+ * @param instanceKey - Instance key (defaults to 'default')
410
+ * @returns The state container instance
411
+ * @throws Error if instance doesn't exist
412
+ */
413
+ borrow(Type, instanceKey = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY) {
414
+ return this.acquire(Type, instanceKey, {
415
+ canCreate: false,
416
+ countRef: false
417
+ });
418
+ }
419
+ /**
420
+ * Safely borrow an existing instance (borrowing semantics with error handling).
421
+ * Returns discriminated union for type-safe conditional access.
422
+ * @param Type - The StateContainer class constructor
423
+ * @param instanceKey - Instance key (defaults to 'default')
424
+ * @returns Discriminated union with either the instance or an error
425
+ */
426
+ borrowSafe(Type, instanceKey = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY) {
427
+ try {
428
+ return {
429
+ error: null,
430
+ instance: this.borrow(Type, instanceKey)
431
+ };
432
+ } catch (error) {
433
+ return {
434
+ error,
435
+ instance: null
436
+ };
437
+ }
438
+ }
439
+ /**
440
+ * Ensure an instance exists without taking ownership (for bloc-to-bloc communication).
441
+ * Gets existing instance OR creates it if it doesn't exist, without adding a ref.
442
+ * Tracks cross-bloc dependency for reactive updates.
443
+ *
444
+ * Use this in bloc-to-bloc communication when you need to ensure an instance exists
445
+ * but don't want to claim ownership (no ref added).
446
+ * @param Type - The StateContainer class constructor
447
+ * @param instanceKey - Instance key (defaults to 'default')
448
+ * @returns The state container instance
449
+ */
450
+ ensure(Type, instanceKey = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY) {
451
+ return this.acquire(Type, instanceKey, {
452
+ canCreate: true,
453
+ countRef: false
454
+ });
455
+ }
456
+ /**
457
+ * Release a reference to an instance.
458
+ * Removes the ref and disposes when refs is empty (unless keepAlive).
459
+ * Releasing an already-removed refId is a no-op (idempotent).
460
+ * @param Type - The StateContainer class constructor
461
+ * @param instanceKey - Instance key (defaults to 'default')
462
+ * @param forceDispose - Force immediate disposal regardless of refs
463
+ * @param refId - The specific ref to remove; removes one arbitrary ref if omitted
464
+ */
465
+ release(Type, instanceKey = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY, forceDispose = false, refId) {
466
+ const instances = this.ensureInstancesMap(Type);
467
+ const entry = instances.get(instanceKey);
468
+ if (!entry) return;
469
+ if (forceDispose) {
470
+ if (!entry.instance.isDisposed) entry.instance.dispose();
471
+ instances.delete(instanceKey);
472
+ return;
473
+ }
474
+ let releasedRefId;
475
+ if (refId !== void 0) {
476
+ const count = entry.refs.get(refId) ?? 0;
477
+ if (count <= 1) entry.refs.delete(refId);
478
+ else entry.refs.set(refId, count - 1);
479
+ releasedRefId = refId;
480
+ } else {
481
+ const firstKey = entry.refs.keys().next().value;
482
+ if (firstKey !== void 0) {
483
+ const count = entry.refs.get(firstKey) ?? 0;
484
+ if (count <= 1) entry.refs.delete(firstKey);
485
+ else entry.refs.set(firstKey, count - 1);
486
+ releasedRefId = firstKey;
487
+ }
488
+ }
489
+ if (releasedRefId) this.emit("refReleased", entry.instance, releasedRefId);
490
+ const keepAlive = isKeepAliveClass(Type);
491
+ if (entry.refs.size === 0 && !keepAlive) {
492
+ const deps = entry.instance.dependencies;
493
+ if (!entry.instance.isDisposed) entry.instance.dispose();
494
+ instances.delete(instanceKey);
495
+ for (const [DepType, depKey] of deps) {
496
+ const depInstances = this.ensureInstancesMap(DepType);
497
+ const depEntry = depInstances.get(depKey);
498
+ if (depEntry && depEntry.refs.size === 0 && !isKeepAliveClass(DepType) && !depEntry.instance.isDisposed) {
499
+ depEntry.instance.dispose();
500
+ depInstances.delete(depKey);
501
+ }
502
+ }
503
+ }
504
+ }
505
+ /**
506
+ * Get all instances of a specific type.
507
+ * @param Type - The StateContainer class constructor
508
+ * @returns Array of all instances
509
+ */
510
+ getAll(Type) {
511
+ const instances = this.ensureInstancesMap(Type);
512
+ const result = [];
513
+ for (const entry of instances.values()) result.push(entry.instance);
514
+ return result;
515
+ }
516
+ /**
517
+ * Safely iterate over all instances of a type.
518
+ * Skips disposed instances and catches callback errors.
519
+ * @param Type - The StateContainer class constructor
520
+ * @param callback - Function to call for each instance
521
+ */
522
+ forEach(Type, callback) {
523
+ const instances = this.ensureInstancesMap(Type);
524
+ for (const entry of instances.values()) {
525
+ const instance = entry.instance;
526
+ if (!instance.isDisposed) try {
527
+ callback(instance);
528
+ } catch (error) {
529
+ console.error(`${BLAC_ERROR_PREFIX} forEach callback error for ${Type.name}:`, error);
530
+ }
531
+ }
532
+ }
533
+ /**
534
+ * Clear all instances of a specific type (disposes them).
535
+ * @param Type - The StateContainer class constructor
536
+ */
537
+ clear(Type) {
538
+ const instances = this.ensureInstancesMap(Type);
539
+ for (const entry of instances.values()) if (!entry.instance.isDisposed) entry.instance.dispose();
540
+ instances.clear();
541
+ }
542
+ /**
543
+ * Get reference count for an instance (number of active refs).
544
+ * @param Type - The StateContainer class constructor
545
+ * @param instanceKey - Instance key (defaults to 'default')
546
+ * @returns Current ref count (0 if instance doesn't exist)
547
+ */
548
+ getRefCount(Type, instanceKey = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY) {
549
+ return this.ensureInstancesMap(Type).get(instanceKey)?.refs.size ?? 0;
550
+ }
551
+ /**
552
+ * Get all active reference IDs for an instance.
553
+ * @param Type - The StateContainer class constructor
554
+ * @param instanceKey - Instance key (defaults to 'default')
555
+ * @returns Array of ref ID strings (empty if instance doesn't exist)
556
+ */
557
+ getRefIds(Type, instanceKey = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY) {
558
+ const instances = this.instancesByConstructor.get(Type);
559
+ if (!instances) return [];
560
+ const entry = instances.get(instanceKey);
561
+ return entry ? Array.from(entry.refs.keys()) : [];
562
+ }
563
+ /**
564
+ * Check if an instance exists.
565
+ * @param Type - The StateContainer class constructor
566
+ * @param instanceKey - Instance key (defaults to 'default')
567
+ * @returns true if instance exists
568
+ */
569
+ hasInstance(Type, instanceKey = BLAC_DEFAULTS.DEFAULT_INSTANCE_KEY) {
570
+ return this.ensureInstancesMap(Type).has(instanceKey);
571
+ }
572
+ /**
573
+ * Clear all instances from all types (for testing)
574
+ *
575
+ * Iterates all registered types and clears their instances.
576
+ * Also clears type tracking to reset the registry state.
577
+ */
578
+ clearAll() {
579
+ for (const Type of this.types) this.clear(Type);
580
+ this.types.clear();
581
+ this.registeredTypeNames.clear();
582
+ }
583
+ /**
584
+ * Get registry statistics for debugging.
585
+ * @returns Object with registeredTypes, totalInstances, and typeBreakdown
586
+ */
587
+ getStats() {
588
+ const typeBreakdown = {};
589
+ let totalInstances = 0;
590
+ for (const Type of this.types) {
591
+ const typeName = Type.name;
592
+ const count = this.getInstancesMap(Type).size;
593
+ typeBreakdown[typeName] = count;
594
+ totalInstances += count;
595
+ }
596
+ return {
597
+ registeredTypes: this.types.size,
598
+ totalInstances,
599
+ typeBreakdown
600
+ };
601
+ }
602
+ /**
603
+ * Get all registered types (for plugin system).
604
+ * @returns Array of all registered StateContainer class constructors
605
+ */
606
+ getTypes() {
607
+ return Array.from(this.types);
608
+ }
609
+ /**
610
+ * Subscribe to lifecycle events
611
+ * @param event - The lifecycle event to listen for
612
+ * @param listener - The listener function to call when the event occurs
613
+ * @returns Unsubscribe function
614
+ */
615
+ on(event, listener) {
616
+ if (!this.listeners.has(event)) this.listeners.set(event, /* @__PURE__ */ new Set());
617
+ const instance = this.listeners.get(event);
618
+ if (!instance) throw new Error(`${BLAC_ERROR_PREFIX} Failed to register listener for event '${event}'`);
619
+ instance.add(listener);
620
+ if (event === "stateChanged") this._stateChangedListenerCount++;
621
+ return () => {
622
+ if (this.listeners.get(event)?.delete(listener) && event === "stateChanged") this._stateChangedListenerCount--;
623
+ };
624
+ }
625
+ emit(event, ...args) {
626
+ const listeners = this.listeners.get(event);
627
+ if (!listeners || listeners.size === 0) return;
628
+ for (const listener of listeners) try {
629
+ listener(...args);
630
+ } catch (error) {
631
+ console.error(`${BLAC_ERROR_PREFIX} Listener error for '${event}':`, error);
632
+ }
633
+ }
634
+ /**
635
+ * Schedule a deferred stateChanged notification via microtask.
636
+ * Skips entirely when no stateChanged listeners are registered.
637
+ * @internal - Called by StateContainer.applyState
638
+ */
639
+ notifyStateChanged(container, previousState, newState) {
640
+ if (this._stateChangedListenerCount === 0) return;
641
+ if (!this._pendingStateChanges) {
642
+ this._pendingStateChanges = [];
643
+ queueMicrotask(() => this.flushStateChanged());
644
+ }
645
+ this._pendingStateChanges.push([
646
+ container,
647
+ previousState,
648
+ newState
649
+ ]);
650
+ }
651
+ flushStateChanged() {
652
+ const pending = this._pendingStateChanges;
653
+ this._pendingStateChanges = null;
654
+ if (!pending) return;
655
+ for (const [container, prev, next] of pending) this.emit("stateChanged", container, prev, next);
656
+ }
657
+ };
658
+ /**
659
+ * Global default registry instance
660
+ */
661
+ const globalRegistry = new StateContainerRegistry();
662
+ /**
663
+ * Global plugin manager (initialized lazily)
664
+ */
665
+ let _globalPluginManager = null;
666
+ /**
667
+ * Get the global plugin manager
668
+ */
669
+ function getPluginManager() {
670
+ if (!_globalPluginManager) _globalPluginManager = createPluginManager(globalRegistry);
671
+ return _globalPluginManager;
672
+ }
673
+ //#endregion
674
+ export { isIsolatedClass as a, BLAC_DEFAULTS as c, isExcludedFromDevTools as i, BLAC_ERROR_PREFIX as l, getPluginManager as n, isKeepAliveClass as o, globalRegistry as r, PluginManager as s, StateContainerRegistry as t, BLAC_STATIC_PROPS as u };
675
+
676
+ //# sourceMappingURL=StateContainerRegistry-BK57H92E.js.map