@blac/core 2.1.1 → 2.1.2

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 (45) hide show
  1. package/dist/StateContainer-CwByTd5L.js +656 -0
  2. package/dist/StateContainer-CwByTd5L.js.map +1 -0
  3. package/dist/StateContainer-D2b10eR4.cjs +691 -0
  4. package/dist/StateContainer-D2b10eR4.cjs.map +1 -0
  5. package/dist/StateContainerRegistry-B6O6cfJd.cjs +903 -0
  6. package/dist/StateContainerRegistry-B6O6cfJd.cjs.map +1 -0
  7. package/dist/StateContainerRegistry-CrTtRX5V.js +772 -0
  8. package/dist/StateContainerRegistry-CrTtRX5V.js.map +1 -0
  9. package/dist/constants.d.cts +2 -0
  10. package/dist/constants.d.ts +2 -0
  11. package/dist/core/StateContainer.d.ts +7 -1
  12. package/dist/core/StateContainerRegistry.d.ts +2 -0
  13. package/dist/core/meta.d.ts +3 -0
  14. package/dist/core/onActivated.d.ts +10 -0
  15. package/dist/core/symbols.d.ts +5 -0
  16. package/dist/decorators/blac.d.ts +7 -0
  17. package/dist/ensure-CwtQVTam.js +46 -0
  18. package/dist/ensure-CwtQVTam.js.map +1 -0
  19. package/dist/ensure-DShrbIYY.cjs +63 -0
  20. package/dist/ensure-DShrbIYY.cjs.map +1 -0
  21. package/dist/index.cjs +27 -3
  22. package/dist/index.cjs.map +1 -1
  23. package/dist/index.d.cts +3 -2
  24. package/dist/index.d.ts +3 -2
  25. package/dist/index.js +25 -4
  26. package/dist/index.js.map +1 -1
  27. package/dist/internal.cjs +2 -2
  28. package/dist/internal.js +2 -2
  29. package/dist/plugin/BlacPlugin.d.ts +3 -1
  30. package/dist/plugin/PluginManager.d.ts +4 -4
  31. package/dist/plugins.cjs +5 -5
  32. package/dist/plugins.cjs.map +1 -1
  33. package/dist/plugins.js +5 -5
  34. package/dist/plugins.js.map +1 -1
  35. package/dist/registry/index.d.ts +1 -1
  36. package/dist/registry/management.d.ts +2 -0
  37. package/dist/testing.cjs +28 -3
  38. package/dist/testing.cjs.map +1 -1
  39. package/dist/testing.d.cts +9 -1
  40. package/dist/testing.d.ts +9 -1
  41. package/dist/testing.js +28 -4
  42. package/dist/testing.js.map +1 -1
  43. package/dist/utils/static-props.d.ts +6 -0
  44. package/dist/watch/watch.d.ts +6 -0
  45. package/package.json +2 -2
@@ -0,0 +1,691 @@
1
+ const require_StateContainerRegistry = require("./StateContainerRegistry-B6O6cfJd.cjs");
2
+ let _dirtytalk_structural = require("@dirtytalk/structural");
3
+ //#region src/utils/idGenerator.ts
4
+ /**
5
+ * Build an instance id: `${prefix}:${affix}` when an affix is given (the
6
+ * registry passes the instance key), otherwise `${prefix}:${timestamp}_${random}`.
7
+ *
8
+ * Ids are not unique: same-named classes share an id for the same affix, and
9
+ * the lazy `$blac.id` of an unregistered instance is always `${prefix}:main`.
10
+ *
11
+ * @example
12
+ * ```ts
13
+ * generateSimpleId('CounterBloc', 'default'); // "CounterBloc:default"
14
+ * generateSimpleId('CounterBloc'); // "CounterBloc:1698765432100_a3k9d7f2q"
15
+ * ```
16
+ */
17
+ function generateSimpleId(prefix, affix) {
18
+ if (affix) return `${prefix}:${affix}`;
19
+ return `${prefix}:${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;
20
+ }
21
+ //#endregion
22
+ //#region src/registry/config.ts
23
+ let _registry = require_StateContainerRegistry.globalRegistry;
24
+ /**
25
+ * The registry every plain helper (`acquire`, `ensure`, `watch`, …) uses.
26
+ * `RegistryProvider` from `@blac/react` does not change it; components use
27
+ * `useRegistry()` for the provider's registry.
28
+ * @public
29
+ */
30
+ function getRegistry() {
31
+ return _registry;
32
+ }
33
+ /**
34
+ * @public
35
+ */
36
+ function setRegistry(registry) {
37
+ _registry = registry;
38
+ }
39
+ /**
40
+ * @public
41
+ */
42
+ function getStats() {
43
+ return _registry.getStats();
44
+ }
45
+ //#endregion
46
+ //#region src/core/meta.ts
47
+ /**
48
+ * `$blac` meta namespace for `StateContainer`.
49
+ *
50
+ * `BlacMeta` and `BlacHydration` are classes whose accessors live on the
51
+ * prototype and read the container through one `#private` back-reference, so
52
+ * a container allocates a single small object here instead of a literal with
53
+ * seven closures. Members are therefore not own-enumerable: `Object.keys` and
54
+ * `JSON.stringify` see an empty object. Read the fields by name.
55
+ */
56
+ /**
57
+ * Non-enumerable brand carried on every `$blac` object. Used by the clobber
58
+ * guard in `StateContainer` to detect a subclass class-field shadowing the
59
+ * base's own `$blac` property, and by the meta tests. Intentionally NOT
60
+ * re-exported from the package barrel.
61
+ */
62
+ const META_BRAND = Symbol("blac.meta");
63
+ const EMPTY_DEPS = /* @__PURE__ */ new Map();
64
+ /**
65
+ * Hydration sub-surface of {@link BlacMeta}. Exposes the container's
66
+ * hydration state machine — the `begin`/`apply`/`finish`/`fail`/`wait`
67
+ * methods and the `status`/`error`/`isHydrated`/`changedWhileHydrating`
68
+ * getters — namespaced under `$blac`.
69
+ */
70
+ var BlacHydration = class {
71
+ #c;
72
+ /** @internal */
73
+ constructor(container) {
74
+ this.#c = container;
75
+ Object.freeze(this);
76
+ }
77
+ get status() {
78
+ return this.#c._hydrationStatus;
79
+ }
80
+ get error() {
81
+ return this.#c._hydrationError;
82
+ }
83
+ get isHydrated() {
84
+ return this.#c._hydrationStatus === "hydrated";
85
+ }
86
+ get changedWhileHydrating() {
87
+ return this.#c._changedWhileHydrating;
88
+ }
89
+ begin() {
90
+ this.#c._beginHydration();
91
+ }
92
+ apply(next) {
93
+ return this.#c._applyHydratedState(next);
94
+ }
95
+ finish() {
96
+ this.#c._finishHydration();
97
+ }
98
+ fail(error) {
99
+ this.#c._failHydration(error);
100
+ }
101
+ wait() {
102
+ return this.#c._waitForHydration();
103
+ }
104
+ };
105
+ /**
106
+ * The reserved `$blac` instance member on every `StateContainer`. Gathers the
107
+ * container's identity/lifecycle/hydration surface (`name`, `id`, `debug`,
108
+ * `createdAt`, `disposed`, `dependencies`, and the hydration methods) under one
109
+ * namespace, keeping the generic names free for userland blocs.
110
+ *
111
+ * Allocated once per container and frozen. Every accessor reads the
112
+ * container's current `_`-private fields live — values are never snapshotted.
113
+ */
114
+ var BlacMeta = class {
115
+ #c;
116
+ #hydration;
117
+ /** @internal Called from the `StateContainer` field initializer. */
118
+ constructor(container) {
119
+ this.#c = container;
120
+ Object.freeze(this);
121
+ }
122
+ get name() {
123
+ return this.#c._name;
124
+ }
125
+ get id() {
126
+ const c = this.#c;
127
+ return c._instanceId ??= generateSimpleId(require_StateContainerRegistry.getBlacName(c.constructor), "main");
128
+ }
129
+ get debug() {
130
+ return this.#c._debug;
131
+ }
132
+ get createdAt() {
133
+ return this.#c._createdAt;
134
+ }
135
+ get disposed() {
136
+ return this.#c._disposed;
137
+ }
138
+ /** The registry that owns this container (the global one for a bare `new`). */
139
+ get registry() {
140
+ return this.#c._registry;
141
+ }
142
+ get dependencies() {
143
+ return this.#c._dependencies ?? EMPTY_DEPS;
144
+ }
145
+ /** Built on first access; identity-stable afterwards. */
146
+ get hydration() {
147
+ return this.#hydration ??= new BlacHydration(this.#c);
148
+ }
149
+ };
150
+ Object.defineProperty(BlacMeta.prototype, META_BRAND, {
151
+ value: true,
152
+ enumerable: false,
153
+ writable: false,
154
+ configurable: false
155
+ });
156
+ //#endregion
157
+ //#region src/core/StateContainer.ts
158
+ /**
159
+ * Brand symbol carried (non-enumerable) on every handle returned by
160
+ * `depend()`. Framework adapters (`@blac/react`) use this to detect handles
161
+ * inside a tracked-proxy and swap in a session-bound wrapper.
162
+ *
163
+ * @internal — exported from `@blac/core/internal` for `@blac/react`.
164
+ */
165
+ const DEP_BRAND = Symbol("blac.depHandle");
166
+ const EMPTY_RECORD = Object.freeze({});
167
+ let deactivatedReason;
168
+ let stateChangeCount = 0;
169
+ /** @internal */
170
+ function getStateChangeCount() {
171
+ return stateChangeCount;
172
+ }
173
+ /**
174
+ * Shallow per-key `Object.is` comparison of two plain records. Keys are
175
+ * considered: a key present in one but not the other (regardless of value)
176
+ * makes the records unequal. Used to detect real deps changes.
177
+ */
178
+ function shallowEqualRecord(a, b) {
179
+ if (a === b) return true;
180
+ const aKeys = Object.keys(a);
181
+ if (aKeys.length !== Object.keys(b).length) return false;
182
+ for (const key of aKeys) {
183
+ if (!(key in b)) return false;
184
+ if (!Object.is(a[key], b[key])) return false;
185
+ }
186
+ return true;
187
+ }
188
+ /**
189
+ * BlaC's lifecycle/identity/dependency layer on top of `StructuralContainer`
190
+ * (which provides `state`, `emit`/`patch`/`update`, and `channel`).
191
+ * StateContainer adds identity/lifecycle/hydration (`$blac: BlacMeta`),
192
+ * cross-bloc deps (`depend()`), per-consumer deps slices, and registry
193
+ * integration. Subscribe via `onSystemEvent(...)` for coarse lifecycle
194
+ * events or `this.channel.subscribe(...)` for path-scoped ones.
195
+ */
196
+ var StateContainer = class extends _dirtytalk_structural.StructuralContainer {
197
+ static {
198
+ this.__excludeFromDevTools = false;
199
+ }
200
+ get deps() {
201
+ return this._deps;
202
+ }
203
+ /**
204
+ * @internal Apply one owner's (consumer's) deps slice. Shallow-merges the
205
+ * slice, reconciles keys the owner dropped since its last apply (other
206
+ * owners' keys untouched), dev-warns on cross-owner key collisions, then
207
+ * recomputes the merged view and fires onDepsChanged if it changed.
208
+ *
209
+ * Idempotent: re-applying an identical slice for the same owner is a no-op.
210
+ */
211
+ [require_StateContainerRegistry.APPLY_DEPS](ownerId, slice) {
212
+ if (this._disposed) return;
213
+ const owners = this._depsByOwner ??= /* @__PURE__ */ new Map();
214
+ const prevSlice = owners.get(ownerId);
215
+ if (prevSlice && shallowEqualRecord(prevSlice, slice)) return;
216
+ if (require_StateContainerRegistry.IS_DEV) for (const key of Object.keys(slice)) for (const [otherOwner, otherSlice] of owners) {
217
+ if (otherOwner === ownerId) continue;
218
+ if (key in otherSlice && otherSlice[key] !== slice[key]) console.warn(`[${this._name}] multiple owners writing dep \`${String(key)}\`; last write wins`);
219
+ }
220
+ owners.set(ownerId, { ...slice });
221
+ this.reconcileDeps();
222
+ }
223
+ /**
224
+ * @internal Withdraw an owner's entire deps slice (consumer unmounted).
225
+ */
226
+ [require_StateContainerRegistry.REMOVE_DEPS_OWNER](ownerId) {
227
+ if (this._disposed) return;
228
+ if (!this._depsByOwner?.delete(ownerId)) return;
229
+ this.reconcileDeps();
230
+ }
231
+ /**
232
+ * @internal Subscribe to this instance's own disposal. Delegates to the
233
+ * per-instance `'dispose'` system event — used by `watch()` in place of
234
+ * filtering the global registry `'disposed'` event.
235
+ */
236
+ [require_StateContainerRegistry.ON_DISPOSE](handler) {
237
+ return this.onSystemEvent("dispose", handler);
238
+ }
239
+ /**
240
+ * @internal Run `handler` on every activation, and now if already active.
241
+ * Backs `onActivated()`.
242
+ */
243
+ [require_StateContainerRegistry.ON_ACTIVATED](handler) {
244
+ if (this._disposed) return () => {};
245
+ (this._activationHandlers ??= /* @__PURE__ */ new Set()).add(handler);
246
+ if (this._activation) handler(this._activation.signal);
247
+ return () => {
248
+ this._activationHandlers?.delete(handler);
249
+ };
250
+ }
251
+ /**
252
+ * @internal Drive the 0↔1 ownership transition. Idempotent: repeated calls
253
+ * with the same value are no-ops, so the registry can call it from every
254
+ * acquire/release without tracking edges itself.
255
+ *
256
+ * Returns which real transition (if any) just happened, so the registry can
257
+ * emit the matching `activated`/`deactivated` plugin event without exposing
258
+ * `_activation` itself — `'none'` for an idempotent no-op call.
259
+ */
260
+ [require_StateContainerRegistry.SET_ACTIVE](active) {
261
+ if (this._disposed) return "none";
262
+ if (active === (this._activation !== null)) return "none";
263
+ if (active) {
264
+ this._activation = new AbortController();
265
+ const { signal } = this._activation;
266
+ this.onActivate(signal);
267
+ if (this._activationHandlers) for (const handler of [...this._activationHandlers]) try {
268
+ handler(signal);
269
+ } catch (error) {
270
+ console.error(`[${this._name}] Error in onActivated handler:`, error);
271
+ }
272
+ return {
273
+ kind: "activated",
274
+ signal: this._activation.signal
275
+ };
276
+ }
277
+ this._abortActivation();
278
+ this.onDeactivate();
279
+ return "deactivated";
280
+ }
281
+ _abortActivation() {
282
+ this._activation?.abort(deactivatedReason ??= new DOMException("The bloc was deactivated", "AbortError"));
283
+ this._activation = null;
284
+ }
285
+ reconcileDeps() {
286
+ const prev = this._deps;
287
+ const next = {};
288
+ if (this._depsByOwner) for (const slice of this._depsByOwner.values()) Object.assign(next, slice);
289
+ for (const key of Object.keys(prev)) if (!(key in next)) next[key] = void 0;
290
+ if (shallowEqualRecord(prev, next)) return;
291
+ this._deps = next;
292
+ this.onDepsChanged(next, prev);
293
+ this._registry.emit("depsChanged", this, prev, next);
294
+ }
295
+ onDepsChanged(_next, _prev) {}
296
+ get state() {
297
+ return this._stateOverride ?? super.state;
298
+ }
299
+ /**
300
+ * @internal Run `fn` (with `this` = this instance, so a prototype getter can
301
+ * be passed directly) while `state` reports `tracked` and dep handles read
302
+ * off `this` route through `onDepHandle`. Restored in `finally`, and
303
+ * nestable — getters reading other getters stay in tracked context.
304
+ *
305
+ * The dep hook lives here rather than in the adapter's proxy because getters
306
+ * now run with `this` = the real instance (so ES `#private` works), which
307
+ * means a `this.someDep` read never passes through the proxy's trap.
308
+ */
309
+ [require_StateContainerRegistry.WITH_TRACKED_STATE](tracked, fn, onDepHandle) {
310
+ const prevState = this._stateOverride;
311
+ const prevHook = this._depHandleHook;
312
+ this._stateOverride = tracked;
313
+ this._depHandleHook = onDepHandle;
314
+ try {
315
+ return fn.call(this);
316
+ } finally {
317
+ this._stateOverride = prevState;
318
+ this._depHandleHook = prevHook;
319
+ }
320
+ }
321
+ get args() {
322
+ return this._config.args;
323
+ }
324
+ /**
325
+ * Declare a cross-bloc dependency. Returns a branded handle with two
326
+ * accessors — the dep instance is resolved against the registry on each call,
327
+ * which keeps the surface immune to dep-instance churn:
328
+ *
329
+ * - `handle.track(options?)` — reactive read. Returns `[state, instance]`.
330
+ * Inside a getter reached through the React proxy this subscribes the
331
+ * reading component to the dep's changes (base impl: live, no subscription).
332
+ * - `handle.untracked(options?)` — returns the live instance with no tracking,
333
+ * for imperative method calls and one-off reads.
334
+ *
335
+ * `defaultArgs` resolves the dep instance when an accessor is called without
336
+ * its own `args`; per-call `options.args` overrides it and can derive from
337
+ * current state. This does NOT auto-resubscribe outside the React proxy;
338
+ * non-React consumers needing updates should subscribe explicitly.
339
+ */
340
+ depend(Type, defaultArgs) {
341
+ if (!this._dependencies) this._dependencies = /* @__PURE__ */ new Map();
342
+ this._dependencies.set(Type, this._registry.resolveKey(Type, void 0, defaultArgs));
343
+ const resolve = (args) => {
344
+ const effectiveArgs = args ?? defaultArgs;
345
+ const key = this._registry.resolveKey(Type, void 0, effectiveArgs);
346
+ if (this._disposed && require_StateContainerRegistry.IS_DEV) console.warn(`[blac] ${this._name}: dependency accessed after dispose. Guard with \`if (this.$blac.disposed) return\` after each \`await\`.`);
347
+ return this._registry.acquire(Type, key, {
348
+ canCreate: true,
349
+ countRef: false,
350
+ args: effectiveArgs,
351
+ dependent: this._disposed ? void 0 : this,
352
+ sweepIfUnowned: this._disposed
353
+ });
354
+ };
355
+ const handle = {
356
+ track: (options) => {
357
+ const wrapped = this._depHandleHook?.(handle);
358
+ if (wrapped !== void 0 && wrapped !== handle) return wrapped.track(options);
359
+ const instance = resolve(options?.args);
360
+ return [instance.state, instance];
361
+ },
362
+ untracked: (options) => resolve(options?.args)
363
+ };
364
+ Object.defineProperty(handle, DEP_BRAND, {
365
+ value: {
366
+ Type,
367
+ defaultArgs
368
+ },
369
+ enumerable: false,
370
+ writable: false,
371
+ configurable: false
372
+ });
373
+ return handle;
374
+ }
375
+ constructor(initialState, options) {
376
+ super(initialState, options);
377
+ this._depsByOwner = null;
378
+ this._deps = EMPTY_RECORD;
379
+ this._disposed = false;
380
+ this._hydrationStatus = "idle";
381
+ this._changedWhileHydrating = false;
382
+ this._hydrationPromise = null;
383
+ this._hydrationPromiseSettled = false;
384
+ this._config = EMPTY_RECORD;
385
+ this._initCalled = false;
386
+ this._activation = null;
387
+ this._activationHandlers = null;
388
+ this._emitWindowStart = 0;
389
+ this._emitCount = 0;
390
+ this._emitRateWarned = false;
391
+ this._systemEventHandlers = null;
392
+ this._dependencies = null;
393
+ this._pendingChange = null;
394
+ this._bridgeUnsub = null;
395
+ this._registry = getRegistry();
396
+ this._equalityFn = require_StateContainerRegistry.getClassEquality(this.constructor) ?? require_StateContainerRegistry.getBlacConfig().equality;
397
+ this._name = require_StateContainerRegistry.getBlacName(this.constructor);
398
+ this._debug = false;
399
+ this._createdAt = Date.now();
400
+ this.$blac = new BlacMeta(this);
401
+ }
402
+ /**
403
+ * Called once after construction with the args passed at acquire time, before the first
404
+ * state snapshot is read by any consumer. Override to seed args-derived state (via
405
+ * this.emit(...)) or kick off loads.
406
+ */
407
+ init(_args) {}
408
+ /**
409
+ * Called when this instance goes from unowned to owned (first ref or first
410
+ * `depend()` dependent). Override to start work that should only run while
411
+ * something is actually using the instance — fetches, timers, listeners.
412
+ *
413
+ * `signal` aborts on the matching `onDeactivate` and on dispose, so
414
+ * async work started here can be cancelled without extra bookkeeping.
415
+ *
416
+ * Runs before the first `useBlocDeps` slice is applied, so `this.deps` is
417
+ * empty on first activation — use `onDepsChanged` for deps-driven work.
418
+ */
419
+ onActivate(_signal) {}
420
+ /**
421
+ * Called when this instance goes from owned back to unowned while surviving
422
+ * in the registry (i.e. `keepAlive`). A disposed instance does NOT get this
423
+ * callback — `dispose()` is the teardown path for that case.
424
+ */
425
+ onDeactivate() {}
426
+ /**
427
+ * @internal Framework-only configuration entry point (registry + testing
428
+ * helpers). Writes the `_`-private identity fields directly, emits the
429
+ * registry `created` event, and runs `init()` once. See `INIT_CONFIG`.
430
+ */
431
+ [require_StateContainerRegistry.INIT_CONFIG](config) {
432
+ this._config = { ...config };
433
+ const className = require_StateContainerRegistry.getBlacName(this.constructor);
434
+ this._name = this._config.name || className;
435
+ this._debug = this._config.debug ?? false;
436
+ this._instanceId = generateSimpleId(className, this._config.instanceId);
437
+ this._registry = this._config.registry ?? this._registry;
438
+ if (!this._initCalled) {
439
+ this._initCalled = true;
440
+ this.init(this._config.args);
441
+ }
442
+ this._registry.emit("created", this);
443
+ if (require_StateContainerRegistry.IS_DEV) {
444
+ if (!this.$blac?.[META_BRAND]) console.warn(`[blac] ${this.constructor.name} appears to declare its own \`$blac\` member, which shadows the reserved meta namespace. \`$blac\` is reserved by StateContainer — remove the subclass field.`);
445
+ }
446
+ }
447
+ dispose() {
448
+ if (this._disposed) return;
449
+ if (this._debug) console.log(`[${this._name}] Disposing...`);
450
+ if (this._depsByOwner) {
451
+ this._depsByOwner.clear();
452
+ this.reconcileDeps();
453
+ }
454
+ this._disposed = true;
455
+ if (this._hydrationStatus === "hydrating") this._failHydration(/* @__PURE__ */ new Error(`Hydration cancelled because ${this._name} was disposed`));
456
+ this.emitSystemEvent("dispose", void 0);
457
+ this._bridgeUnsub?.();
458
+ this._bridgeUnsub = null;
459
+ this._abortActivation();
460
+ this._systemEventHandlers = null;
461
+ this._activationHandlers = null;
462
+ this._pendingChange = null;
463
+ this._registry.emit("disposed", this);
464
+ super.dispose();
465
+ if (this._debug) console.log(`[${this._name}] Disposed successfully`);
466
+ }
467
+ emit(next) {
468
+ this.applyState(next, "default");
469
+ }
470
+ /** @see emit for the StateContainer concerns layered onto `super.patch`. */
471
+ patch(partial) {
472
+ if (this._disposed) {
473
+ this._warnDisposedMutation("patch");
474
+ return;
475
+ }
476
+ const prev = super.state;
477
+ super.patch(partial);
478
+ const next = super.state;
479
+ if (Object.is(prev, next)) return;
480
+ this._recordChange(prev, next, "default");
481
+ }
482
+ applyState(next, source) {
483
+ if (this._disposed) {
484
+ this._warnDisposedMutation("emit");
485
+ return;
486
+ }
487
+ const prev = super.state;
488
+ if (prev === next) return;
489
+ if (this._equalityFn(prev, next)) return;
490
+ this._recordChange(prev, next, source);
491
+ super.emit(next);
492
+ }
493
+ /** Bookkeeping shared by every real state change (`emit`, `patch`, hydration). */
494
+ _recordChange(prev, next, source) {
495
+ stateChangeCount++;
496
+ if (require_StateContainerRegistry.IS_DEV && !this._emitRateWarned) this._checkEmitRate();
497
+ if (this._hydrationStatus === "hydrating" && source !== "hydration") this._changedWhileHydrating = true;
498
+ if (this._bridgeUnsub !== null) if (this._pendingChange) this._pendingChange.next = next;
499
+ else this._pendingChange = {
500
+ prev,
501
+ next
502
+ };
503
+ this._registry.notifyStateChanged(this, prev, next);
504
+ }
505
+ /**
506
+ * Called by the channel-bridge subscriber on each flush. Drains the
507
+ * pending change (if any) into the 'stateChanged' system event.
508
+ * No pending change == flush from a no-op patch == skip.
509
+ */
510
+ _drainPending() {
511
+ const pending = this._pendingChange;
512
+ if (!pending) return;
513
+ this._pendingChange = null;
514
+ this.emitSystemEvent("stateChanged", {
515
+ state: pending.next,
516
+ previousState: pending.prev
517
+ });
518
+ }
519
+ _beginHydration() {
520
+ if (this._disposed) throw new Error(`Cannot begin hydration for disposed container ${this._name}`);
521
+ this._changedWhileHydrating = false;
522
+ this._hydrationError = void 0;
523
+ this._hydrationPromise = null;
524
+ this._resolveHydrationPromise = void 0;
525
+ this._rejectHydrationPromise = void 0;
526
+ this._hydrationPromiseSettled = false;
527
+ this.ensureHydrationPromise();
528
+ this.setHydrationStatus("hydrating");
529
+ }
530
+ _warnDisposedMutation(op) {
531
+ if (require_StateContainerRegistry.IS_DEV) console.warn(`[blac] ${this._name}: ${op}() after dispose ignored. This usually means an async method resolved after the last consumer unmounted. Guard with \`if (this.$blac.disposed) return\` after each \`await\`, or abort the work from \`onSystemEvent('dispose', ...)\`.`);
532
+ }
533
+ _applyHydratedState(next) {
534
+ if (this._disposed) return false;
535
+ if (this._hydrationStatus !== "hydrating" || this._changedWhileHydrating) {
536
+ if (require_StateContainerRegistry.IS_DEV && this._changedWhileHydrating) console.warn(`[blac] ${this._name}: persisted state discarded because the container emitted while hydrating.`);
537
+ return false;
538
+ }
539
+ this.applyState(next, "hydration");
540
+ return true;
541
+ }
542
+ _finishHydration() {
543
+ if (this._hydrationStatus !== "hydrating") {
544
+ if (this._hydrationStatus === "hydrated") return;
545
+ if (this._hydrationStatus === "error") this.ensureHydrationPromise();
546
+ }
547
+ this.setHydrationStatus("hydrated");
548
+ this.resolveHydration();
549
+ }
550
+ _failHydration(error) {
551
+ const err = error instanceof Error ? error : /* @__PURE__ */ new Error(`Hydration failed: ${String(error)}`);
552
+ this._hydrationError = err;
553
+ this.setHydrationStatus("error", err);
554
+ this.rejectHydration(err);
555
+ }
556
+ _waitForHydration() {
557
+ if (this._hydrationStatus === "idle" || this._hydrationStatus === "hydrated") return Promise.resolve();
558
+ if (this._hydrationStatus === "error") return Promise.reject(this._hydrationError ?? /* @__PURE__ */ new Error(`Hydration failed for container ${this._name}`));
559
+ return this.ensureHydrationPromise();
560
+ }
561
+ setHydrationStatus(status, error) {
562
+ const previousStatus = this._hydrationStatus;
563
+ this._hydrationStatus = status;
564
+ this._hydrationError = error;
565
+ this.emitSystemEvent("hydrationChanged", {
566
+ status,
567
+ previousStatus,
568
+ error,
569
+ changedWhileHydrating: this._changedWhileHydrating
570
+ });
571
+ this._registry.emit("hydrationChanged", this, status, previousStatus);
572
+ }
573
+ ensureHydrationPromise() {
574
+ if (!this._hydrationPromise || this._hydrationPromiseSettled) {
575
+ this._hydrationPromiseSettled = false;
576
+ this._hydrationPromise = new Promise((resolve, reject) => {
577
+ this._resolveHydrationPromise = () => {
578
+ if (this._hydrationPromiseSettled) return;
579
+ this._hydrationPromiseSettled = true;
580
+ resolve();
581
+ };
582
+ this._rejectHydrationPromise = (error) => {
583
+ if (this._hydrationPromiseSettled) return;
584
+ this._hydrationPromiseSettled = true;
585
+ reject(error);
586
+ };
587
+ });
588
+ this._hydrationPromise.catch(() => {});
589
+ }
590
+ return this._hydrationPromise;
591
+ }
592
+ resolveHydration() {
593
+ this._resolveHydrationPromise?.();
594
+ }
595
+ rejectHydration(error) {
596
+ this.ensureHydrationPromise();
597
+ this._rejectHydrationPromise?.(error);
598
+ }
599
+ onSystemEvent(event, handler) {
600
+ if (this._disposed) return () => {};
601
+ const all = this._systemEventHandlers ??= /* @__PURE__ */ new Map();
602
+ let handlers = all.get(event);
603
+ if (!handlers) {
604
+ handlers = /* @__PURE__ */ new Set();
605
+ all.set(event, handlers);
606
+ }
607
+ handlers.add(handler);
608
+ if (event === "stateChanged" && this._bridgeUnsub === null) this._bridgeUnsub = this.channel.subscribe(() => _dirtytalk_structural.ALL_PATHS, () => this._drainPending());
609
+ return () => {
610
+ handlers?.delete(handler);
611
+ if (event === "stateChanged" && handlers?.size === 0) {
612
+ this._bridgeUnsub?.();
613
+ this._bridgeUnsub = null;
614
+ this._pendingChange = null;
615
+ }
616
+ };
617
+ }
618
+ emitSystemEvent(event, payload) {
619
+ const handlers = this._systemEventHandlers?.get(event);
620
+ if (!handlers) return;
621
+ let remaining = handlers.size;
622
+ for (const handler of handlers) {
623
+ if (remaining-- === 0) break;
624
+ try {
625
+ handler(payload);
626
+ } catch (error) {
627
+ console.error(`[${this._name}] Error in system event handler:`, error);
628
+ }
629
+ }
630
+ }
631
+ /**
632
+ * Dev-only soft circuit breaker. Counts real state changes in a rolling 1s
633
+ * window and warns once if the rate exceeds `maxEmitsPerSecond` — the
634
+ * signature of a runaway loop (RAF/animation or emit-on-every-commit) pushing
635
+ * high-frequency data through state, which freezes subscribers/plugins.
636
+ */
637
+ _checkEmitRate() {
638
+ const limit = require_StateContainerRegistry.getBlacConfig().maxEmitsPerSecond;
639
+ if (!(limit > 0) || !Number.isFinite(limit)) return;
640
+ const now = Date.now();
641
+ if (now - this._emitWindowStart >= 1e3) {
642
+ this._emitWindowStart = now;
643
+ this._emitCount = 1;
644
+ return;
645
+ }
646
+ this._emitCount++;
647
+ if (this._emitCount > limit) {
648
+ this._emitRateWarned = true;
649
+ console.warn(`[${this._name}] emitted more than ${limit} state changes in under a second. This is usually a runaway loop pushing high-frequency data through state (e.g. \`emit\`/\`patch\` inside a requestAnimationFrame loop, or an effect that emits on every render). It can freeze the app by saturating subscribers and plugins (logging/devtools). Keep high-frequency work imperative and emit only coarse/throttled state, or raise \`configureBlac({ maxEmitsPerSecond })\`. (This warning fires once.)`);
650
+ }
651
+ }
652
+ };
653
+ //#endregion
654
+ Object.defineProperty(exports, "DEP_BRAND", {
655
+ enumerable: true,
656
+ get: function() {
657
+ return DEP_BRAND;
658
+ }
659
+ });
660
+ Object.defineProperty(exports, "StateContainer", {
661
+ enumerable: true,
662
+ get: function() {
663
+ return StateContainer;
664
+ }
665
+ });
666
+ Object.defineProperty(exports, "getRegistry", {
667
+ enumerable: true,
668
+ get: function() {
669
+ return getRegistry;
670
+ }
671
+ });
672
+ Object.defineProperty(exports, "getStateChangeCount", {
673
+ enumerable: true,
674
+ get: function() {
675
+ return getStateChangeCount;
676
+ }
677
+ });
678
+ Object.defineProperty(exports, "getStats", {
679
+ enumerable: true,
680
+ get: function() {
681
+ return getStats;
682
+ }
683
+ });
684
+ Object.defineProperty(exports, "setRegistry", {
685
+ enumerable: true,
686
+ get: function() {
687
+ return setRegistry;
688
+ }
689
+ });
690
+
691
+ //# sourceMappingURL=StateContainer-D2b10eR4.cjs.map