@oxog/state 1.2.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,25 +1,4 @@
1
- import { useRef, useSyncExternalStore, useDebugValue, useEffect, useCallback } from 'react';
2
-
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __esm = (fn, res) => function __init() {
8
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
9
- };
10
- var __export = (target, all) => {
11
- for (var name in all)
12
- __defProp(target, name, { get: all[name], enumerable: true });
13
- };
14
- var __copyProps = (to, from, except, desc) => {
15
- if (from && typeof from === "object" || typeof from === "function") {
16
- for (let key of __getOwnPropNames(from))
17
- if (!__hasOwnProp.call(to, key) && key !== except)
18
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
19
- }
20
- return to;
21
- };
22
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
1
+ import { useRef, useCallback, useSyncExternalStore, useDebugValue, useEffect } from 'react';
23
2
 
24
3
  // src/utils/deep-clone.ts
25
4
  function deepClone(value, seen) {
@@ -48,7 +27,7 @@ function deepClone(value, seen) {
48
27
  const cloned = {};
49
28
  seen.set(value, cloned);
50
29
  for (const key in value) {
51
- if (Object.prototype.hasOwnProperty.call(value, key)) {
30
+ if (key !== "__proto__" && Object.prototype.hasOwnProperty.call(value, key)) {
52
31
  cloned[key] = deepClone(value[key], seen);
53
32
  }
54
33
  }
@@ -56,10 +35,6 @@ function deepClone(value, seen) {
56
35
  }
57
36
  return value;
58
37
  }
59
- var init_deep_clone = __esm({
60
- "src/utils/deep-clone.ts"() {
61
- }
62
- });
63
38
 
64
39
  // src/utils/deep-equal.ts
65
40
  function deepEqual(a, b) {
@@ -96,10 +71,6 @@ function deepEqual(a, b) {
96
71
  }
97
72
  return true;
98
73
  }
99
- var init_deep_equal = __esm({
100
- "src/utils/deep-equal.ts"() {
101
- }
102
- });
103
74
 
104
75
  // src/utils/shallow-equal.ts
105
76
  function shallowEqual(a, b) {
@@ -121,10 +92,6 @@ function shallowEqual(a, b) {
121
92
  }
122
93
  return true;
123
94
  }
124
- var init_shallow_equal = __esm({
125
- "src/utils/shallow-equal.ts"() {
126
- }
127
- });
128
95
 
129
96
  // src/utils/deep-merge.ts
130
97
  function deepMerge(target, source) {
@@ -136,14 +103,14 @@ function deepMerge(target, source) {
136
103
  }
137
104
  const output = deepClone(target);
138
105
  for (const key in source) {
139
- if (Object.prototype.hasOwnProperty.call(source, key)) {
106
+ if (key !== "__proto__" && Object.prototype.hasOwnProperty.call(source, key)) {
140
107
  const sourceValue = source[key];
141
108
  const targetValue = output[key];
142
109
  if (sourceValue instanceof Date) {
143
110
  output[key] = new Date(sourceValue.getTime());
144
111
  continue;
145
112
  }
146
- if (sourceValue !== null && typeof sourceValue === "object" && !Array.isArray(sourceValue) && !(sourceValue instanceof Date) && targetValue !== null && typeof targetValue === "object" && !Array.isArray(targetValue) && !(targetValue instanceof Date)) {
113
+ if (Object.prototype.hasOwnProperty.call(output, key) && sourceValue !== null && typeof sourceValue === "object" && !Array.isArray(sourceValue) && !(sourceValue instanceof Date) && targetValue !== null && typeof targetValue === "object" && !Array.isArray(targetValue) && !(targetValue instanceof Date)) {
147
114
  output[key] = deepMerge(targetValue, sourceValue);
148
115
  } else {
149
116
  output[key] = cloneValue(sourceValue);
@@ -165,7 +132,7 @@ function cloneValue(value) {
165
132
  if (value.constructor === Object) {
166
133
  const cloned = {};
167
134
  for (const key in value) {
168
- if (Object.prototype.hasOwnProperty.call(value, key)) {
135
+ if (key !== "__proto__" && Object.prototype.hasOwnProperty.call(value, key)) {
169
136
  cloned[key] = cloneValue(value[key]);
170
137
  }
171
138
  }
@@ -173,20 +140,11 @@ function cloneValue(value) {
173
140
  }
174
141
  return value;
175
142
  }
176
- var init_deep_merge = __esm({
177
- "src/utils/deep-merge.ts"() {
178
- init_deep_clone();
179
- }
180
- });
181
143
 
182
144
  // src/utils/is-function.ts
183
145
  function isFunction(value) {
184
146
  return typeof value === "function";
185
147
  }
186
- var init_is_function = __esm({
187
- "src/utils/is-function.ts"() {
188
- }
189
- });
190
148
 
191
149
  // src/utils/pick.ts
192
150
  function pick(obj, keys) {
@@ -198,10 +156,6 @@ function pick(obj, keys) {
198
156
  }
199
157
  return result;
200
158
  }
201
- var init_pick = __esm({
202
- "src/utils/pick.ts"() {
203
- }
204
- });
205
159
 
206
160
  // src/utils/omit.ts
207
161
  function omit(obj, keys) {
@@ -211,251 +165,227 @@ function omit(obj, keys) {
211
165
  }
212
166
  return result;
213
167
  }
214
- var init_omit = __esm({
215
- "src/utils/omit.ts"() {
216
- }
217
- });
218
168
 
219
169
  // src/utils/identity.ts
220
170
  function identity(value) {
221
171
  return value;
222
172
  }
223
- var init_identity = __esm({
224
- "src/utils/identity.ts"() {
225
- }
226
- });
227
-
228
- // src/utils/index.ts
229
- var init_utils = __esm({
230
- "src/utils/index.ts"() {
231
- init_deep_clone();
232
- init_deep_equal();
233
- init_shallow_equal();
234
- init_deep_merge();
235
- init_is_function();
236
- init_pick();
237
- init_omit();
238
- init_identity();
239
- }
240
- });
241
173
 
242
174
  // src/kernel.ts
243
- function createKernel(config) {
244
- return new Kernel(config);
245
- }
246
- var EventBus, Kernel;
247
- var init_kernel = __esm({
248
- "src/kernel.ts"() {
249
- EventBus = class {
250
- listeners = /* @__PURE__ */ new Map();
251
- /**
252
- * Subscribe to an event.
253
- *
254
- * @param event - Event name
255
- * @param handler - Event handler
256
- * @returns Unsubscribe function
257
- */
258
- on(event, handler) {
259
- if (!this.listeners.has(event)) {
260
- this.listeners.set(event, /* @__PURE__ */ new Set());
261
- }
262
- this.listeners.get(event).add(handler);
263
- return () => {
264
- this.listeners.get(event)?.delete(handler);
265
- };
266
- }
267
- /**
268
- * Emit an event to all subscribers.
269
- *
270
- * @param event - Event name
271
- * @param data - Event data
272
- */
273
- emit(event, data) {
274
- const handlers = this.listeners.get(event);
275
- if (handlers) {
276
- for (const handler of handlers) {
277
- try {
278
- handler(data);
279
- } catch (error) {
280
- console.error(`Error in ${event} handler:`, error);
281
- }
282
- }
283
- }
284
- }
285
- /** Clear all listeners. */
286
- destroy() {
287
- this.listeners.clear();
288
- }
175
+ var EventBus = class {
176
+ listeners = /* @__PURE__ */ new Map();
177
+ /**
178
+ * Subscribe to an event.
179
+ *
180
+ * @param event - Event name
181
+ * @param handler - Event handler
182
+ * @returns Unsubscribe function
183
+ */
184
+ on(event, handler) {
185
+ if (!this.listeners.has(event)) {
186
+ this.listeners.set(event, /* @__PURE__ */ new Set());
187
+ }
188
+ this.listeners.get(event).add(handler);
189
+ return () => {
190
+ this.listeners.get(event)?.delete(handler);
289
191
  };
290
- Kernel = class {
291
- plugins = /* @__PURE__ */ new Map();
292
- eventBus = new EventBus();
293
- config;
294
- errorHandlers = /* @__PURE__ */ new Set();
295
- initializing = false;
296
- constructor(config) {
297
- this.config = config || {};
298
- }
299
- /**
300
- * Register a plugin.
301
- *
302
- * @param plugin - The plugin to register
303
- * @param options - Plugin options
304
- * @param store - The store instance
305
- * @throws {Error} If plugin already registered or dependencies missing
306
- */
307
- register(plugin, options, store) {
308
- if (!plugin.name || !plugin.version || typeof plugin.install !== "function") {
309
- throw new Error("Invalid plugin: must have name, version, and install function");
310
- }
311
- if (this.plugins.has(plugin.name)) {
312
- throw new Error(`Plugin '${plugin.name}' is already registered`);
313
- }
314
- if (plugin.dependencies) {
315
- for (const dep of plugin.dependencies) {
316
- if (!this.plugins.has(dep)) {
317
- throw new Error(
318
- `Plugin '${plugin.name}' requires '${dep}' to be registered first`
319
- );
320
- }
321
- }
322
- }
323
- const instance = {
324
- plugin,
325
- options
326
- };
192
+ }
193
+ /**
194
+ * Emit an event to all subscribers.
195
+ *
196
+ * @param event - Event name
197
+ * @param data - Event data
198
+ */
199
+ emit(event, data) {
200
+ const handlers = this.listeners.get(event);
201
+ if (handlers) {
202
+ for (const handler of handlers) {
327
203
  try {
328
- plugin.install(store, options);
204
+ handler(data);
329
205
  } catch (error) {
330
- throw new Error(`Failed to install plugin '${plugin.name}': ${error}`);
331
- }
332
- this.plugins.set(plugin.name, instance);
333
- if (!this.initializing && plugin.onInit) {
334
- this.runOnInit(plugin, store);
206
+ console.error(`Error in ${event} handler:`, error);
335
207
  }
336
208
  }
337
- /**
338
- * Initialize all plugins.
339
- *
340
- * @param store - The store instance
341
- */
342
- async initializeAll(store) {
343
- this.initializing = true;
344
- const plugins = Array.from(this.plugins.values());
345
- for (const { plugin } of plugins) {
346
- if (plugin.onInit) {
347
- await this.runOnInit(plugin, store);
348
- }
209
+ }
210
+ }
211
+ /** Clear all listeners. */
212
+ destroy() {
213
+ this.listeners.clear();
214
+ }
215
+ };
216
+ var Kernel = class {
217
+ plugins = /* @__PURE__ */ new Map();
218
+ eventBus = new EventBus();
219
+ config;
220
+ errorHandlers = /* @__PURE__ */ new Set();
221
+ initializing = false;
222
+ constructor(config) {
223
+ this.config = config || {};
224
+ }
225
+ /**
226
+ * Register a plugin.
227
+ *
228
+ * @param plugin - The plugin to register
229
+ * @param options - Plugin options
230
+ * @param store - The store instance
231
+ * @throws {Error} If plugin already registered or dependencies missing
232
+ */
233
+ register(plugin, options, store) {
234
+ if (!plugin.name || !plugin.version || typeof plugin.install !== "function") {
235
+ throw new Error("Invalid plugin: must have name, version, and install function");
236
+ }
237
+ if (this.plugins.has(plugin.name)) {
238
+ throw new Error(`Plugin '${plugin.name}' is already registered`);
239
+ }
240
+ if (plugin.dependencies) {
241
+ for (const dep of plugin.dependencies) {
242
+ if (!this.plugins.has(dep)) {
243
+ throw new Error(
244
+ `Plugin '${plugin.name}' requires '${dep}' to be registered first`
245
+ );
349
246
  }
350
- this.initializing = false;
351
247
  }
352
- /**
353
- * Run plugin's onInit safely.
354
- */
355
- async runOnInit(plugin, store) {
248
+ }
249
+ const instance = {
250
+ plugin,
251
+ options
252
+ };
253
+ try {
254
+ plugin.install(store, options);
255
+ } catch (error) {
256
+ throw new Error(`Failed to install plugin '${plugin.name}': ${error}`);
257
+ }
258
+ this.plugins.set(plugin.name, instance);
259
+ if (!this.initializing && plugin.onInit) {
260
+ this.runOnInit(plugin, store);
261
+ }
262
+ }
263
+ /**
264
+ * Initialize all plugins.
265
+ *
266
+ * @param store - The store instance
267
+ */
268
+ async initializeAll(store) {
269
+ this.initializing = true;
270
+ const plugins = Array.from(this.plugins.values());
271
+ for (const { plugin } of plugins) {
272
+ if (plugin.onInit) {
273
+ await this.runOnInit(plugin, store);
274
+ }
275
+ }
276
+ this.initializing = false;
277
+ }
278
+ /**
279
+ * Run plugin's onInit safely.
280
+ */
281
+ async runOnInit(plugin, store) {
282
+ try {
283
+ await plugin.onInit(store);
284
+ } catch (error) {
285
+ console.error(`Error in ${plugin.name} onInit:`, error);
286
+ }
287
+ }
288
+ /**
289
+ * Unregister a plugin.
290
+ *
291
+ * @param name - Plugin name
292
+ */
293
+ async unregister(name) {
294
+ const instance = this.plugins.get(name);
295
+ if (!instance) {
296
+ return;
297
+ }
298
+ if (instance.plugin.onDestroy) {
299
+ try {
300
+ await instance.plugin.onDestroy();
301
+ } catch (error) {
302
+ console.error(`Error in ${name} onDestroy:`, error);
303
+ }
304
+ }
305
+ this.plugins.delete(name);
306
+ }
307
+ /**
308
+ * Emit a state change event.
309
+ *
310
+ * @param state - New state
311
+ * @param prevState - Previous state
312
+ */
313
+ emitStateChange(state, prevState) {
314
+ this.eventBus.emit("stateChange", { state, prevState });
315
+ for (const { plugin } of this.plugins.values()) {
316
+ if (plugin.onStateChange) {
356
317
  try {
357
- await plugin.onInit(store);
318
+ plugin.onStateChange(state, prevState);
358
319
  } catch (error) {
359
- console.error(`Error in ${plugin.name} onInit:`, error);
360
- }
361
- }
362
- /**
363
- * Unregister a plugin.
364
- *
365
- * @param name - Plugin name
366
- */
367
- async unregister(name) {
368
- const instance = this.plugins.get(name);
369
- if (!instance) {
370
- return;
371
- }
372
- if (instance.plugin.onDestroy) {
373
- try {
374
- await instance.plugin.onDestroy();
375
- } catch (error) {
376
- console.error(`Error in ${name} onDestroy:`, error);
377
- }
378
- }
379
- this.plugins.delete(name);
380
- }
381
- /**
382
- * Emit a state change event.
383
- *
384
- * @param state - New state
385
- * @param prevState - Previous state
386
- */
387
- emitStateChange(state, prevState) {
388
- this.eventBus.emit("stateChange", { state, prevState });
389
- for (const { plugin } of this.plugins.values()) {
390
- if (plugin.onStateChange) {
391
- try {
392
- plugin.onStateChange(state, prevState);
393
- } catch (error) {
394
- console.error(`Error in ${plugin.name} onStateChange:`, error);
395
- }
396
- }
320
+ console.error(`Error in ${plugin.name} onStateChange:`, error);
397
321
  }
398
322
  }
399
- /**
400
- * Emit an error event.
401
- *
402
- * @param error - The error
403
- */
404
- emitError(error) {
405
- this.eventBus.emit("error", error);
406
- for (const { plugin } of this.plugins.values()) {
407
- if (plugin.onError) {
408
- try {
409
- plugin.onError(error);
410
- } catch (err) {
411
- console.error(`Error in ${plugin.name} onError:`, err);
412
- }
413
- }
414
- }
415
- for (const handler of this.errorHandlers) {
416
- try {
417
- handler(error);
418
- } catch (err) {
419
- console.error("Error in error handler:", err);
420
- }
323
+ }
324
+ }
325
+ /**
326
+ * Emit an error event.
327
+ *
328
+ * @param error - The error
329
+ */
330
+ emitError(error) {
331
+ this.eventBus.emit("error", error);
332
+ for (const { plugin } of this.plugins.values()) {
333
+ if (plugin.onError) {
334
+ try {
335
+ plugin.onError(error);
336
+ } catch (err) {
337
+ console.error(`Error in ${plugin.name} onError:`, err);
421
338
  }
422
339
  }
423
- /**
424
- * Add an error handler.
425
- *
426
- * @param handler - Error handler function
427
- * @returns Unsubscribe function
428
- */
429
- onError(handler) {
430
- this.errorHandlers.add(handler);
431
- return () => {
432
- this.errorHandlers.delete(handler);
433
- };
434
- }
435
- /**
436
- * Subscribe to an event.
437
- *
438
- * @param event - Event name
439
- * @param handler - Event handler
440
- * @returns Unsubscribe function
441
- */
442
- on(event, handler) {
443
- return this.eventBus.on(event, handler);
444
- }
445
- /** Destroy the kernel and cleanup. */
446
- async destroy() {
447
- const pluginNames = Array.from(this.plugins.keys());
448
- for (const name of pluginNames) {
449
- await this.unregister(name);
450
- }
451
- this.eventBus.destroy();
452
- this.errorHandlers.clear();
340
+ }
341
+ for (const handler of this.errorHandlers) {
342
+ try {
343
+ handler(error);
344
+ } catch (err) {
345
+ console.error("Error in error handler:", err);
453
346
  }
347
+ }
348
+ }
349
+ /**
350
+ * Add an error handler.
351
+ *
352
+ * @param handler - Error handler function
353
+ * @returns Unsubscribe function
354
+ */
355
+ onError(handler) {
356
+ this.errorHandlers.add(handler);
357
+ return () => {
358
+ this.errorHandlers.delete(handler);
454
359
  };
455
360
  }
456
- });
361
+ /**
362
+ * Subscribe to an event.
363
+ *
364
+ * @param event - Event name
365
+ * @param handler - Event handler
366
+ * @returns Unsubscribe function
367
+ */
368
+ on(event, handler) {
369
+ return this.eventBus.on(event, handler);
370
+ }
371
+ /** Destroy the kernel and cleanup. */
372
+ async destroy() {
373
+ const pluginNames = Array.from(this.plugins.keys());
374
+ for (const name of pluginNames) {
375
+ await this.unregister(name);
376
+ }
377
+ this.eventBus.destroy();
378
+ this.errorHandlers.clear();
379
+ }
380
+ };
381
+ function createKernel(config) {
382
+ return new Kernel(config);
383
+ }
457
384
 
458
385
  // src/batch-context.ts
386
+ var batchDepth = 0;
387
+ var batchStores = /* @__PURE__ */ new Set();
388
+ var batchManagedStores = /* @__PURE__ */ new Set();
459
389
  function isBatching() {
460
390
  return batchDepth > 0;
461
391
  }
@@ -484,125 +414,418 @@ function addManagedStore(store) {
484
414
  function isStoreManaged(store) {
485
415
  return batchManagedStores.has(store);
486
416
  }
487
- var batchDepth, batchStores, batchManagedStores, sharedBatchContext;
488
- var init_batch_context = __esm({
489
- "src/batch-context.ts"() {
490
- batchDepth = 0;
491
- batchStores = /* @__PURE__ */ new Set();
492
- batchManagedStores = /* @__PURE__ */ new Set();
493
- sharedBatchContext = {
494
- get depth() {
495
- return batchDepth;
496
- },
497
- get stores() {
498
- return batchStores;
499
- },
500
- get managedStores() {
501
- return batchManagedStores;
502
- },
503
- isBatching,
504
- batch(store, fn) {
505
- const wasAlreadyBatching = isStoreManaged(store);
506
- incrementBatchDepth();
507
- addBatchStore(store);
508
- if (!wasAlreadyBatching && "beginBatch" in store) {
509
- store.beginBatch();
510
- addManagedStore(store);
511
- }
512
- try {
513
- const result = fn();
514
- decrementBatchDepth();
515
- if (getBatchDepth() === 0) {
516
- for (const s of getBatchManagedStores()) {
517
- if ("flushNotifications" in s) {
518
- s.flushNotifications();
519
- }
520
- if ("endBatch" in s) {
521
- s.endBatch();
522
- }
523
- }
524
- clearBatchStores();
417
+ var sharedBatchContext = {
418
+ get depth() {
419
+ return batchDepth;
420
+ },
421
+ get stores() {
422
+ return batchStores;
423
+ },
424
+ get managedStores() {
425
+ return batchManagedStores;
426
+ },
427
+ isBatching,
428
+ batch(store, fn) {
429
+ const wasAlreadyBatching = isStoreManaged(store);
430
+ incrementBatchDepth();
431
+ addBatchStore(store);
432
+ if (!wasAlreadyBatching && "beginBatch" in store) {
433
+ store.beginBatch();
434
+ addManagedStore(store);
435
+ }
436
+ try {
437
+ const result = fn();
438
+ decrementBatchDepth();
439
+ if (getBatchDepth() === 0) {
440
+ for (const s of getBatchManagedStores()) {
441
+ if ("flushNotifications" in s) {
442
+ s.flushNotifications();
525
443
  }
526
- return result;
527
- } catch (error) {
528
- decrementBatchDepth();
529
- if (getBatchDepth() === 0) {
530
- for (const s of getBatchManagedStores()) {
531
- if ("endBatch" in s) {
532
- s.endBatch();
533
- }
534
- }
535
- clearBatchStores();
444
+ if ("endBatch" in s) {
445
+ s.endBatch();
536
446
  }
537
- throw error;
538
447
  }
448
+ clearBatchStores();
539
449
  }
540
- };
450
+ return result;
451
+ } catch (error) {
452
+ decrementBatchDepth();
453
+ if (getBatchDepth() === 0) {
454
+ for (const s of getBatchManagedStores()) {
455
+ if ("endBatch" in s) {
456
+ s.endBatch();
457
+ }
458
+ }
459
+ clearBatchStores();
460
+ }
461
+ throw error;
462
+ }
541
463
  }
542
- });
464
+ };
543
465
 
544
466
  // src/types.ts
545
- var StoreErrorCode, StoreError;
546
- var init_types = __esm({
547
- "src/types.ts"() {
548
- StoreErrorCode = /* @__PURE__ */ ((StoreErrorCode2) => {
549
- StoreErrorCode2["STORE_DESTROYED"] = "STORE_DESTROYED";
550
- StoreErrorCode2["PLUGIN_EXISTS"] = "PLUGIN_EXISTS";
551
- StoreErrorCode2["PLUGIN_DEPENDENCY_MISSING"] = "PLUGIN_DEPENDENCY_MISSING";
552
- StoreErrorCode2["INVALID_STATE_UPDATE"] = "INVALID_STATE_UPDATE";
553
- StoreErrorCode2["ACTION_ERROR"] = "ACTION_ERROR";
554
- return StoreErrorCode2;
555
- })(StoreErrorCode || {});
556
- StoreError = class extends Error {
557
- constructor(code, message) {
558
- super(message);
559
- this.code = code;
560
- this.name = "StoreError";
467
+ var StoreErrorCode = /* @__PURE__ */ ((StoreErrorCode2) => {
468
+ StoreErrorCode2["STORE_DESTROYED"] = "STORE_DESTROYED";
469
+ StoreErrorCode2["PLUGIN_EXISTS"] = "PLUGIN_EXISTS";
470
+ StoreErrorCode2["PLUGIN_DEPENDENCY_MISSING"] = "PLUGIN_DEPENDENCY_MISSING";
471
+ StoreErrorCode2["INVALID_STATE_UPDATE"] = "INVALID_STATE_UPDATE";
472
+ StoreErrorCode2["ACTION_ERROR"] = "ACTION_ERROR";
473
+ return StoreErrorCode2;
474
+ })(StoreErrorCode || {});
475
+ var StoreError = class extends Error {
476
+ constructor(code, message) {
477
+ super(message);
478
+ this.code = code;
479
+ this.name = "StoreError";
480
+ }
481
+ };
482
+
483
+ // src/batch.ts
484
+ function batch(fn) {
485
+ incrementBatchDepth();
486
+ try {
487
+ const result = fn();
488
+ decrementBatchDepth();
489
+ if (getBatchDepth() === 0) {
490
+ const storesArray = Array.from(getBatchManagedStores());
491
+ for (const s of storesArray) {
492
+ if ("flushNotifications" in s) {
493
+ s.flushNotifications();
494
+ }
561
495
  }
562
- };
496
+ clearBatchStores();
497
+ }
498
+ return result;
499
+ } catch (error) {
500
+ decrementBatchDepth();
501
+ const storesArray = Array.from(getBatchManagedStores());
502
+ for (const s of storesArray) {
503
+ if ("flushNotifications" in s) {
504
+ s.flushNotifications();
505
+ }
506
+ }
507
+ clearBatchStores();
508
+ throw error;
563
509
  }
564
- });
510
+ }
565
511
 
566
512
  // src/store.ts
567
- var store_exports = {};
568
- __export(store_exports, {
569
- StoreError: () => StoreError,
570
- StoreErrorCode: () => StoreErrorCode,
571
- StoreImpl: () => StoreImpl,
572
- batch: () => batch,
573
- createStore: () => createStore
574
- });
575
- function createStore(initialState, actions) {
576
- const kernel = createKernel({ name: "store" });
577
- const state = { ...initialState };
578
- const extractedActions = {};
579
- for (const key in state) {
580
- if (isFunction(state[key]) && key.startsWith("$")) {
581
- extractedActions[key.substring(1)] = state[key];
582
- delete state[key];
513
+ var StoreImpl = class {
514
+ state;
515
+ initialState;
516
+ listeners = /* @__PURE__ */ new Set();
517
+ selectorSubscriptions = /* @__PURE__ */ new Set();
518
+ kernel;
519
+ destroyed = false;
520
+ batchDepth = 0;
521
+ pendingNotify = false;
522
+ queuedState = null;
523
+ queuedPrevState = null;
524
+ actions = {};
525
+ /** Incremented on every state change. */
526
+ version = 0;
527
+ /** True while listeners are being notified. */
528
+ notifying = false;
529
+ /** Notifications raised by listeners while notifying; delivered in order. */
530
+ notifyQueue = [];
531
+ constructor(initialState, kernel) {
532
+ this.state = deepClone(initialState);
533
+ this.initialState = deepClone(initialState);
534
+ this.kernel = kernel;
535
+ this.kernel.onError((error) => {
536
+ console.error("Store error:", error);
537
+ });
538
+ }
539
+ /** Get current state snapshot. */
540
+ getState() {
541
+ this.checkNotDestroyed();
542
+ return this.state;
543
+ }
544
+ /** Update state with partial object or function. */
545
+ setState(partial) {
546
+ this.checkNotDestroyed();
547
+ const prevState = this.state;
548
+ const update = typeof partial === "function" ? partial(this.state) : partial;
549
+ if (update === null || update === void 0) {
550
+ return;
551
+ }
552
+ this.state = { ...this.state, ...withoutProtoKey(update) };
553
+ this.notifyOrQueue(this.state, prevState);
554
+ }
555
+ /** Deep merge state. */
556
+ merge(partial) {
557
+ this.checkNotDestroyed();
558
+ const prevState = this.state;
559
+ this.state = deepMerge(this.state, partial);
560
+ this.notifyOrQueue(this.state, prevState);
561
+ }
562
+ /** Reset to initial state. */
563
+ reset() {
564
+ this.checkNotDestroyed();
565
+ const prevState = this.state;
566
+ this.state = deepClone(this.initialState);
567
+ this.notifyOrQueue(this.state, prevState);
568
+ }
569
+ subscribe(arg1, arg2, arg3) {
570
+ this.checkNotDestroyed();
571
+ if (arg2 === void 0 && typeof arg1 === "function") {
572
+ const subscription2 = { listener: arg1, since: this.version };
573
+ this.listeners.add(subscription2);
574
+ return () => {
575
+ this.listeners.delete(subscription2);
576
+ };
583
577
  }
578
+ const subscription = {
579
+ selector: arg1,
580
+ listener: arg2,
581
+ equalityFn: arg3 || shallowEqual,
582
+ value: arg1(this.state)
583
+ };
584
+ this.selectorSubscriptions.add(subscription);
585
+ return () => {
586
+ this.selectorSubscriptions.delete(subscription);
587
+ };
584
588
  }
585
- const allActions = { ...extractedActions, ...actions };
586
- const builder = new StoreBuilderImpl(state, kernel);
587
- if (allActions) {
588
- for (const [name, fn] of Object.entries(allActions)) {
589
- builder.addAction(name, fn);
589
+ /** Register a plugin. */
590
+ use(plugin, options) {
591
+ this.checkNotDestroyed();
592
+ this.kernel.register(plugin, options, this);
593
+ return this;
594
+ }
595
+ /** Destroy store and cleanup. */
596
+ destroy() {
597
+ if (this.destroyed) {
598
+ return;
599
+ }
600
+ this.destroyed = true;
601
+ this.kernel.destroy().catch((error) => {
602
+ console.error("Error destroying store plugins:", error);
603
+ });
604
+ this.listeners.clear();
605
+ this.selectorSubscriptions.clear();
606
+ this.notifyQueue = [];
607
+ this.actions = {};
608
+ }
609
+ /** Add an action (for fluent builder pattern). */
610
+ addAction(name, fn) {
611
+ this.actions[name] = fn;
612
+ return this;
613
+ }
614
+ /**
615
+ * Expose a bound action on the state object (and on the initial state, so
616
+ * `reset()` keeps it). Construction-time only: no notification is sent.
617
+ */
618
+ exposeAction(name, fn) {
619
+ if (name === "__proto__") return;
620
+ this.state = { ...this.state, [name]: fn };
621
+ this.initialState = { ...this.initialState, [name]: fn };
622
+ }
623
+ /** Get all actions. */
624
+ getActions() {
625
+ return this.actions;
626
+ }
627
+ /** Check if store is destroyed. */
628
+ checkNotDestroyed() {
629
+ if (this.destroyed) {
630
+ throw new Error("Cannot use destroyed store");
631
+ }
632
+ }
633
+ /** Notify listeners or queue if batching. */
634
+ notifyOrQueue(state, prevState) {
635
+ this.version++;
636
+ const inGlobalBatch = sharedBatchContext.isBatching();
637
+ if (inGlobalBatch) {
638
+ const managedStores = sharedBatchContext.managedStores;
639
+ if (!managedStores.has(this)) {
640
+ managedStores.add(this);
641
+ }
642
+ }
643
+ if (this.batchDepth > 0 || inGlobalBatch) {
644
+ this.queuedState = state;
645
+ if (!this.pendingNotify) {
646
+ this.queuedPrevState = prevState;
647
+ }
648
+ this.pendingNotify = true;
649
+ } else {
650
+ this.notify(state, prevState);
651
+ }
652
+ }
653
+ /**
654
+ * Notify all listeners.
655
+ *
656
+ * Re-entrant updates (a listener calling setState) are queued and delivered
657
+ * after the current pass, so every listener sees changes in order and ends
658
+ * on the latest state.
659
+ */
660
+ notify(state, prevState) {
661
+ this.notifyQueue.push({ state, prevState, version: this.version });
662
+ if (this.notifying) {
663
+ return;
664
+ }
665
+ this.notifying = true;
666
+ try {
667
+ let next;
668
+ while ((next = this.notifyQueue.shift()) !== void 0) {
669
+ this.deliver(next);
670
+ }
671
+ } finally {
672
+ this.notifying = false;
673
+ this.notifyQueue = [];
674
+ }
675
+ }
676
+ /** Deliver one notification to plugins and listeners. */
677
+ deliver({ state, prevState, version }) {
678
+ this.kernel.emitStateChange(state, prevState);
679
+ for (const subscription of Array.from(this.listeners)) {
680
+ if (!this.listeners.has(subscription) || subscription.since >= version) {
681
+ continue;
682
+ }
683
+ try {
684
+ subscription.listener(state, prevState);
685
+ } catch (error) {
686
+ this.kernel.emitError(error);
687
+ }
688
+ }
689
+ for (const subscription of Array.from(this.selectorSubscriptions)) {
690
+ if (!this.selectorSubscriptions.has(subscription)) {
691
+ continue;
692
+ }
693
+ try {
694
+ const newValue = subscription.selector(state);
695
+ if (subscription.equalityFn(newValue, subscription.value)) {
696
+ continue;
697
+ }
698
+ const prevValue = subscription.value;
699
+ subscription.value = newValue;
700
+ subscription.listener(newValue, prevValue);
701
+ } catch (error) {
702
+ this.kernel.emitError(error);
703
+ }
704
+ }
705
+ }
706
+ /** Flush pending notifications (end of batch). */
707
+ flushNotifications() {
708
+ if (this.pendingNotify) {
709
+ const state = this.queuedState;
710
+ const prevState = this.queuedPrevState;
711
+ this.pendingNotify = false;
712
+ this.queuedState = null;
713
+ this.queuedPrevState = null;
714
+ if (!this.destroyed) {
715
+ this.notify(state, prevState);
716
+ }
717
+ }
718
+ }
719
+ /** Start batching. */
720
+ beginBatch() {
721
+ this.batchDepth++;
722
+ }
723
+ /** End batching. */
724
+ endBatch() {
725
+ this.batchDepth--;
726
+ if (this.batchDepth === 0) {
727
+ this.flushNotifications();
728
+ }
729
+ }
730
+ };
731
+ function withoutProtoKey(update) {
732
+ if (update !== null && typeof update === "object" && Object.prototype.hasOwnProperty.call(update, "__proto__")) {
733
+ const copy = {};
734
+ for (const key of Object.keys(update)) {
735
+ if (key !== "__proto__") copy[key] = update[key];
736
+ }
737
+ return copy;
738
+ }
739
+ return update;
740
+ }
741
+ var StoreBuilderImpl = class {
742
+ store;
743
+ constructor(initialState, kernel) {
744
+ this.store = new StoreImpl(initialState, kernel);
745
+ }
746
+ getState() {
747
+ return this.store.getState();
748
+ }
749
+ setState(partial) {
750
+ this.store.setState(partial);
751
+ }
752
+ merge(partial) {
753
+ this.store.merge(partial);
754
+ }
755
+ reset() {
756
+ this.store.reset();
757
+ }
758
+ subscribe(arg1, arg2, arg3) {
759
+ if (arg2 === void 0) {
760
+ return this.store.subscribe(arg1);
761
+ } else {
762
+ return this.store.subscribe(arg1, arg2, arg3);
590
763
  }
591
764
  }
592
- const actionList = builder.getActions();
593
- for (const [name, fn] of Object.entries(actionList)) {
594
- builder[name] = (...args) => {
595
- const currentState = builder.getState();
596
- const result = fn(currentState, ...args);
765
+ use(plugin, options) {
766
+ this.store.use(plugin, options);
767
+ return this;
768
+ }
769
+ destroy() {
770
+ this.store.destroy();
771
+ }
772
+ action(name, fn) {
773
+ this.store.addAction(name, fn);
774
+ const bound = (...args) => {
775
+ const result = fn(this.getState(), ...args);
597
776
  if (result instanceof Promise) {
598
777
  return result.then((partial) => {
599
- builder.setState(partial);
778
+ this.setState(partial);
600
779
  return partial;
601
780
  });
602
781
  }
603
- builder.setState(result);
782
+ this.setState(result);
604
783
  return result;
605
784
  };
785
+ Object.defineProperty(bound, "name", { value: name, configurable: true });
786
+ this[name] = bound;
787
+ this.store.exposeAction(name, bound);
788
+ return this;
789
+ }
790
+ /** Add action (internal use). */
791
+ addAction(name, fn) {
792
+ this.store.addAction(name, fn);
793
+ return this;
794
+ }
795
+ /** Get actions (internal use). */
796
+ getActions() {
797
+ return this.store.getActions();
798
+ }
799
+ /** Start batching. */
800
+ beginBatch() {
801
+ this.store.beginBatch();
802
+ }
803
+ /** End batching. */
804
+ endBatch() {
805
+ this.store.endBatch();
806
+ }
807
+ /** Flush pending notifications. */
808
+ flushNotifications() {
809
+ this.store.flushNotifications();
810
+ }
811
+ };
812
+ function createStore(initialState, actions) {
813
+ const kernel = createKernel({ name: "store" });
814
+ const state = {};
815
+ const extractedActions = {};
816
+ for (const key of Object.keys(initialState)) {
817
+ const value = initialState[key];
818
+ if (key === "__proto__") continue;
819
+ if (isFunction(value) && key.startsWith("$")) {
820
+ extractedActions[key.substring(1)] = value;
821
+ } else {
822
+ state[key] = value;
823
+ }
824
+ }
825
+ const allActions = { ...extractedActions, ...actions };
826
+ const builder = new StoreBuilderImpl(state, kernel);
827
+ for (const [name, fn] of Object.entries(allActions)) {
828
+ builder.action(name, fn);
606
829
  }
607
830
  kernel.initializeAll(builder).catch((error) => {
608
831
  console.error("Error initializing plugins:", error);
@@ -635,321 +858,55 @@ function createStore(initialState, actions) {
635
858
  }
636
859
  });
637
860
  }
638
- function batch(fn) {
639
- return fn();
640
- }
641
- var StoreImpl, StoreBuilderImpl;
642
- var init_store = __esm({
643
- "src/store.ts"() {
644
- init_utils();
645
- init_kernel();
646
- init_batch_context();
647
- init_types();
648
- StoreImpl = class {
649
- state;
650
- initialState;
651
- listeners = /* @__PURE__ */ new Set();
652
- selectorSubscriptions = /* @__PURE__ */ new Map();
653
- kernel;
654
- destroyed = false;
655
- batchDepth = 0;
656
- pendingNotify = false;
657
- queuedState = null;
658
- queuedPrevState = null;
659
- actions = {};
660
- constructor(initialState, kernel) {
661
- this.state = deepClone(initialState);
662
- this.initialState = deepClone(initialState);
663
- this.kernel = kernel;
664
- this.kernel.onError((error) => {
665
- console.error("Store error:", error);
666
- });
667
- }
668
- /** Get current state snapshot. */
669
- getState() {
670
- this.checkNotDestroyed();
671
- return this.state;
672
- }
673
- /** Update state with partial object or function. */
674
- setState(partial) {
675
- this.checkNotDestroyed();
676
- const prevState = this.state;
677
- const update = typeof partial === "function" ? partial(this.state) : partial;
678
- this.state = { ...this.state, ...update };
679
- this.notifyOrQueue(this.state, prevState);
680
- }
681
- /** Deep merge state. */
682
- merge(partial) {
683
- this.checkNotDestroyed();
684
- const prevState = this.state;
685
- this.state = deepMerge(this.state, partial);
686
- this.notifyOrQueue(this.state, prevState);
687
- }
688
- /** Reset to initial state. */
689
- reset() {
690
- this.checkNotDestroyed();
691
- const prevState = this.state;
692
- this.state = deepClone(this.initialState);
693
- this.notifyOrQueue(this.state, prevState);
694
- }
695
- subscribe(arg1, arg2, arg3) {
696
- this.checkNotDestroyed();
697
- if (arg2 === void 0 && typeof arg1 === "function") {
698
- const listener2 = arg1;
699
- this.listeners.add(listener2);
700
- return () => {
701
- this.listeners.delete(listener2);
702
- };
703
- }
704
- const selector2 = arg1;
705
- const listener = arg2;
706
- const equalityFn = arg3 || shallowEqual;
707
- let subscription = this.selectorSubscriptions.get(selector2);
708
- if (!subscription) {
709
- const initialValue = selector2(this.state);
710
- subscription = {
711
- value: initialValue,
712
- listeners: /* @__PURE__ */ new Set(),
713
- selector: selector2,
714
- equalityFn
715
- };
716
- this.selectorSubscriptions.set(selector2, subscription);
717
- }
718
- subscription.listeners.add(listener);
719
- return () => {
720
- const sub = this.selectorSubscriptions.get(selector2);
721
- if (sub) {
722
- sub.listeners.delete(listener);
723
- if (sub.listeners.size === 0) {
724
- this.selectorSubscriptions.delete(selector2);
725
- }
726
- }
727
- };
728
- }
729
- /** Register a plugin. */
730
- use(plugin, options) {
731
- this.checkNotDestroyed();
732
- this.kernel.register(plugin, options, this);
733
- return this;
734
- }
735
- /** Destroy store and cleanup. */
736
- destroy() {
737
- if (this.destroyed) {
738
- return;
739
- }
740
- this.destroyed = true;
741
- this.kernel.destroy();
742
- this.listeners.clear();
743
- this.selectorSubscriptions.clear();
744
- this.actions = {};
745
- }
746
- /** Add an action (for fluent builder pattern). */
747
- addAction(name, fn) {
748
- this.actions[name] = fn;
749
- return this;
750
- }
751
- /** Get all actions. */
752
- getActions() {
753
- return this.actions;
754
- }
755
- /** Check if store is destroyed. */
756
- checkNotDestroyed() {
757
- if (this.destroyed) {
758
- throw new Error("Cannot use destroyed store");
759
- }
760
- }
761
- /** Notify listeners or queue if batching. */
762
- notifyOrQueue(state, prevState) {
763
- const inGlobalBatch = sharedBatchContext.isBatching();
764
- if (inGlobalBatch) {
765
- const managedStores = sharedBatchContext.managedStores;
766
- if (!managedStores.has(this)) {
767
- managedStores.add(this);
768
- }
769
- }
770
- if (this.batchDepth > 0 || inGlobalBatch) {
771
- this.queuedState = state;
772
- if (!this.pendingNotify) {
773
- this.queuedPrevState = prevState;
774
- }
775
- this.pendingNotify = true;
776
- } else {
777
- this.notify(state, prevState);
778
- }
779
- }
780
- /** Notify all listeners. */
781
- notify(state, prevState) {
782
- this.kernel.emitStateChange(state, prevState);
783
- for (const listener of this.listeners) {
784
- try {
785
- listener(state, prevState);
786
- } catch (error) {
787
- this.kernel.emitError(error);
788
- }
789
- }
790
- for (const subscription of this.selectorSubscriptions.values()) {
791
- const newValue = subscription.selector(state);
792
- if (!subscription.equalityFn(newValue, subscription.value)) {
793
- const prevValue = subscription.value;
794
- subscription.value = newValue;
795
- for (const listener of subscription.listeners) {
796
- try {
797
- listener(newValue, prevValue);
798
- } catch (error) {
799
- this.kernel.emitError(error);
800
- }
801
- }
802
- }
803
- }
804
- }
805
- /** Flush pending notifications (end of batch). */
806
- flushNotifications() {
807
- if (this.pendingNotify) {
808
- this.notify(this.queuedState, this.queuedPrevState);
809
- this.pendingNotify = false;
810
- this.queuedState = null;
811
- this.queuedPrevState = null;
812
- }
813
- }
814
- /** Start batching. */
815
- beginBatch() {
816
- this.batchDepth++;
817
- }
818
- /** End batching. */
819
- endBatch() {
820
- this.batchDepth--;
821
- if (this.batchDepth === 0) {
822
- this.flushNotifications();
823
- }
824
- }
825
- };
826
- StoreBuilderImpl = class {
827
- store;
828
- constructor(initialState, kernel) {
829
- this.store = new StoreImpl(initialState, kernel);
830
- }
831
- getState() {
832
- return this.store.getState();
833
- }
834
- setState(partial) {
835
- this.store.setState(partial);
836
- }
837
- merge(partial) {
838
- this.store.merge(partial);
839
- }
840
- reset() {
841
- this.store.reset();
842
- }
843
- subscribe(arg1, arg2, arg3) {
844
- if (arg2 === void 0) {
845
- return this.store.subscribe(arg1);
846
- } else {
847
- return this.store.subscribe(arg1, arg2, arg3);
848
- }
849
- }
850
- use(plugin, options) {
851
- this.store.use(plugin, options);
852
- return this;
853
- }
854
- destroy() {
855
- this.store.destroy();
856
- }
857
- action(name, fn) {
858
- this.store.addAction(name, fn);
859
- this[name] = (...args) => {
860
- const currentState = this.getState();
861
- const result = fn(currentState, ...args);
862
- if (result instanceof Promise) {
863
- return result.then((partial) => {
864
- this.setState(partial);
865
- return partial;
866
- });
867
- }
868
- this.setState(result);
869
- return result;
870
- };
871
- return this;
872
- }
873
- /** Add action (internal use). */
874
- addAction(name, fn) {
875
- this.store.addAction(name, fn);
876
- return this;
877
- }
878
- /** Get actions (internal use). */
879
- getActions() {
880
- return this.store.getActions();
881
- }
882
- /** Start batching. */
883
- beginBatch() {
884
- this.store.beginBatch();
885
- }
886
- /** End batching. */
887
- endBatch() {
888
- this.store.endBatch();
889
- }
890
- /** Flush pending notifications. */
891
- flushNotifications() {
892
- this.store.flushNotifications();
893
- }
894
- };
895
- }
896
- });
897
-
898
- // src/index.ts
899
- init_store();
900
-
901
- // src/react.ts
902
- init_identity();
903
- init_shallow_equal();
904
- init_store();
905
861
  function useStore(store, selector2 = identity, equalityFn = shallowEqual) {
906
862
  const selectorRef = useRef(selector2);
907
863
  const equalityFnRef = useRef(equalityFn);
908
- const storeRef = useRef(store);
909
- if (selectorRef.current !== selector2) {
910
- selectorRef.current = selector2;
911
- }
912
- if (equalityFnRef.current !== equalityFn) {
913
- equalityFnRef.current = equalityFn;
914
- }
915
- if (storeRef.current !== store) {
916
- storeRef.current = store;
917
- }
918
- const getSnapshot = () => {
919
- const state = storeRef.current.getState();
920
- return selectorRef.current(state);
921
- };
922
- const getServerSnapshot = getSnapshot;
923
- const subscribe = (callback) => {
924
- const unsubscribe = storeRef.current.subscribe(
925
- (state) => selectorRef.current(state),
926
- (value, prevValue) => {
927
- if (!equalityFnRef.current(value, prevValue)) {
928
- callback();
929
- }
930
- },
931
- equalityFnRef.current
932
- );
933
- return unsubscribe;
934
- };
935
- const selectedState = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
864
+ selectorRef.current = selector2;
865
+ equalityFnRef.current = equalityFn;
866
+ const cacheRef = useRef(null);
867
+ const getSnapshot = useCallback(() => {
868
+ const state = store.getState();
869
+ const currentSelector = selectorRef.current;
870
+ const cache = cacheRef.current;
871
+ if (cache && cache.store === store && cache.state === state && cache.selector === currentSelector) {
872
+ return cache.selected;
873
+ }
874
+ const next = currentSelector(state);
875
+ if (cache && cache.store === store && equalityFnRef.current(cache.selected, next)) {
876
+ cacheRef.current = { store, state, selector: currentSelector, selected: cache.selected };
877
+ return cache.selected;
878
+ }
879
+ cacheRef.current = { store, state, selector: currentSelector, selected: next };
880
+ return next;
881
+ }, [store]);
882
+ const subscribe = useCallback((callback) => store.subscribe(() => callback()), [store]);
883
+ const selectedState = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
936
884
  useDebugValue(selectedState);
937
885
  return selectedState;
938
886
  }
939
887
  function useCreateStore(initialState) {
940
888
  const storeRef = useRef();
889
+ const pendingDestroyRef = useRef(null);
941
890
  if (storeRef.current === void 0) {
942
891
  storeRef.current = createStore(initialState);
943
892
  }
893
+ const store = storeRef.current;
944
894
  useEffect(() => {
895
+ pendingDestroyRef.current = null;
945
896
  return () => {
946
- if (storeRef.current) {
947
- storeRef.current.destroy();
948
- storeRef.current = void 0;
949
- }
897
+ const token = {};
898
+ pendingDestroyRef.current = token;
899
+ queueMicrotask(() => {
900
+ if (pendingDestroyRef.current === token) {
901
+ store.destroy();
902
+ if (storeRef.current === store) {
903
+ storeRef.current = void 0;
904
+ }
905
+ }
906
+ });
950
907
  };
951
- }, []);
952
- return storeRef.current;
908
+ }, [store]);
909
+ return store;
953
910
  }
954
911
  function useAction(store, actionName) {
955
912
  const storeRef = useRef(store);
@@ -1009,51 +966,49 @@ function useStoreActions(store, ...actionNames) {
1009
966
  return result;
1010
967
  }
1011
968
  function useStoreSelector(store, selectors) {
1012
- const selectorsRef = useRef(selectors);
1013
- const keysRef = useRef(Object.keys(selectors));
1014
969
  const prevResultRef = useRef(null);
1015
- if (selectorsRef.current !== selectors) {
1016
- selectorsRef.current = selectors;
1017
- keysRef.current = Object.keys(selectors);
1018
- }
1019
970
  const combinedSelector = useCallback((state) => {
1020
- const keys = keysRef.current;
1021
- const currentSelectors = selectorsRef.current;
971
+ const keys = Object.keys(selectors);
1022
972
  const result = {};
1023
973
  for (const key of keys) {
1024
- const selector2 = currentSelectors[key];
974
+ const selector2 = selectors[key];
1025
975
  if (selector2) {
1026
976
  result[key] = selector2(state);
1027
977
  }
1028
978
  }
1029
- if (prevResultRef.current !== null) {
979
+ const prev = prevResultRef.current;
980
+ if (prev !== null && Object.keys(prev).length === keys.length) {
1030
981
  let isEqual = true;
1031
982
  for (const key of keys) {
1032
- if (!shallowEqual(prevResultRef.current[key], result[key])) {
983
+ if (!(key in prev) || !shallowEqual(prev[key], result[key])) {
1033
984
  isEqual = false;
1034
985
  break;
1035
986
  }
1036
987
  }
1037
988
  if (isEqual) {
1038
- return prevResultRef.current;
989
+ return prev;
1039
990
  }
1040
991
  }
1041
992
  prevResultRef.current = result;
1042
993
  return result;
1043
- }, []);
994
+ }, [selectors]);
1044
995
  return useStore(store, combinedSelector);
1045
996
  }
1046
997
  function useTransientSubscribe(store, selector2, callback, equalityFn = shallowEqual) {
1047
998
  const callbackRef = useRef(callback);
999
+ const selectorRef = useRef(selector2);
1000
+ const equalityFnRef = useRef(equalityFn);
1048
1001
  callbackRef.current = callback;
1002
+ selectorRef.current = selector2;
1003
+ equalityFnRef.current = equalityFn;
1049
1004
  useEffect(() => {
1050
1005
  const unsubscribe = store.subscribe(
1051
- selector2,
1006
+ (state) => selectorRef.current(state),
1052
1007
  (value, prevValue) => callbackRef.current(value, prevValue),
1053
- equalityFn
1008
+ (a, b) => equalityFnRef.current(a, b)
1054
1009
  );
1055
1010
  return unsubscribe;
1056
- }, [store, selector2, equalityFn]);
1011
+ }, [store]);
1057
1012
  }
1058
1013
  function useSetState(store) {
1059
1014
  const storeRef = useRef(store);
@@ -1067,7 +1022,6 @@ function useSetState(store) {
1067
1022
  }
1068
1023
 
1069
1024
  // src/subscribe.ts
1070
- init_utils();
1071
1025
  function createDebounced(fn, delay2) {
1072
1026
  let timeoutId = null;
1073
1027
  const debounced = ((...args) => {
@@ -1212,28 +1166,34 @@ function subscribeToMany(store, selectors, listener, options = {}) {
1212
1166
  }
1213
1167
  function subscribeOnce(store, selector2, listener, options = {}) {
1214
1168
  let unsubscribe = null;
1169
+ let fired = false;
1215
1170
  const onceListener = (value, prevValue) => {
1171
+ if (fired) return;
1172
+ fired = true;
1216
1173
  listener(value, prevValue);
1217
1174
  if (unsubscribe) {
1218
1175
  unsubscribe();
1219
1176
  }
1220
1177
  };
1221
1178
  unsubscribe = subscribeWithOptions(store, selector2, onceListener, options);
1179
+ if (fired) {
1180
+ unsubscribe();
1181
+ }
1222
1182
  return unsubscribe;
1223
1183
  }
1224
1184
 
1225
1185
  // src/computed.ts
1226
- init_utils();
1227
1186
  function computed(store, selector2, options = {}) {
1228
1187
  const { equals = shallowEqual, lazy = false, cacheSize = 1 } = options;
1229
1188
  const cache = [];
1230
1189
  let currentValue;
1190
+ let notifiedValue;
1191
+ let computedFrom;
1231
1192
  let isInitialized = false;
1232
1193
  let isDestroyed = false;
1233
1194
  const listeners = /* @__PURE__ */ new Set();
1234
1195
  let unsubscribe = null;
1235
- const compute = () => {
1236
- const state = store.getState();
1196
+ const compute = (state) => {
1237
1197
  for (const entry of cache) {
1238
1198
  if (entry.input === state || shallowEqual(entry.input, state)) {
1239
1199
  return entry.output;
@@ -1246,23 +1206,36 @@ function computed(store, selector2, options = {}) {
1246
1206
  }
1247
1207
  return newValue;
1248
1208
  };
1209
+ const refresh = () => {
1210
+ const state = store.getState();
1211
+ if (isInitialized && state === computedFrom) return;
1212
+ const newValue = compute(state);
1213
+ if (!isInitialized || !equals(newValue, currentValue)) {
1214
+ currentValue = newValue;
1215
+ }
1216
+ computedFrom = state;
1217
+ };
1218
+ const emit = () => {
1219
+ const prevValue = notifiedValue;
1220
+ const value = currentValue;
1221
+ if (equals(value, prevValue)) return;
1222
+ notifiedValue = value;
1223
+ for (const listener of Array.from(listeners)) {
1224
+ try {
1225
+ listener(value, prevValue);
1226
+ } catch (error) {
1227
+ console.error("Computed listener error:", error);
1228
+ }
1229
+ }
1230
+ };
1249
1231
  const initialize = () => {
1250
1232
  if (isInitialized || isDestroyed) return;
1233
+ refresh();
1251
1234
  isInitialized = true;
1252
- currentValue = compute();
1253
- unsubscribe = store.subscribe((state, prevState) => {
1254
- const prevValue = currentValue;
1255
- const newValue = compute();
1256
- if (!equals(newValue, prevValue)) {
1257
- currentValue = newValue;
1258
- for (const listener of listeners) {
1259
- try {
1260
- listener(newValue, prevValue);
1261
- } catch (error) {
1262
- console.error("Computed listener error:", error);
1263
- }
1264
- }
1265
- }
1235
+ notifiedValue = currentValue;
1236
+ unsubscribe = store.subscribe(() => {
1237
+ refresh();
1238
+ emit();
1266
1239
  });
1267
1240
  };
1268
1241
  if (!lazy) {
@@ -1274,6 +1247,8 @@ function computed(store, selector2, options = {}) {
1274
1247
  }
1275
1248
  if (!isInitialized) {
1276
1249
  initialize();
1250
+ } else {
1251
+ refresh();
1277
1252
  }
1278
1253
  return currentValue;
1279
1254
  };
@@ -1281,17 +1256,13 @@ function computed(store, selector2, options = {}) {
1281
1256
  if (isDestroyed) return;
1282
1257
  cache.length = 0;
1283
1258
  if (isInitialized) {
1284
- const prevValue = currentValue;
1285
- currentValue = compute();
1286
- if (!equals(currentValue, prevValue)) {
1287
- for (const listener of listeners) {
1288
- try {
1289
- listener(currentValue, prevValue);
1290
- } catch (error) {
1291
- console.error("Computed listener error:", error);
1292
- }
1293
- }
1259
+ const state = store.getState();
1260
+ const newValue = compute(state);
1261
+ computedFrom = state;
1262
+ if (!equals(newValue, currentValue)) {
1263
+ currentValue = newValue;
1294
1264
  }
1265
+ emit();
1295
1266
  }
1296
1267
  };
1297
1268
  const subscribe = (listener) => {
@@ -1319,6 +1290,8 @@ function computed(store, selector2, options = {}) {
1319
1290
  listeners.clear();
1320
1291
  cache.length = 0;
1321
1292
  currentValue = void 0;
1293
+ notifiedValue = void 0;
1294
+ computedFrom = void 0;
1322
1295
  };
1323
1296
  const computedFn = get;
1324
1297
  computedFn.get = get;
@@ -1339,25 +1312,33 @@ function combineComputed(computeds, combiner, options = {}) {
1339
1312
  const values = computeds.map((c) => c());
1340
1313
  return combiner(values);
1341
1314
  };
1315
+ let notifiedValue;
1316
+ const refresh = () => {
1317
+ const newValue = compute();
1318
+ if (!equals(newValue, currentValue)) {
1319
+ currentValue = newValue;
1320
+ cache.unshift(newValue);
1321
+ while (cache.length > cacheSize) {
1322
+ cache.pop();
1323
+ }
1324
+ }
1325
+ };
1342
1326
  currentValue = compute();
1343
1327
  cache.push(currentValue);
1328
+ notifiedValue = currentValue;
1344
1329
  for (const computed2 of computeds) {
1345
1330
  const unsub = computed2.subscribe(() => {
1346
1331
  if (isDestroyed) return;
1347
- const prevValue = currentValue;
1348
- const newValue = compute();
1349
- if (!equals(newValue, prevValue)) {
1350
- currentValue = newValue;
1351
- cache.unshift(newValue);
1352
- while (cache.length > cacheSize) {
1353
- cache.pop();
1354
- }
1355
- for (const listener of listeners) {
1356
- try {
1357
- listener(newValue, prevValue);
1358
- } catch (error) {
1359
- console.error("Combined computed listener error:", error);
1360
- }
1332
+ refresh();
1333
+ const prevValue = notifiedValue;
1334
+ const value = currentValue;
1335
+ if (equals(value, prevValue)) return;
1336
+ notifiedValue = value;
1337
+ for (const listener of Array.from(listeners)) {
1338
+ try {
1339
+ listener(value, prevValue);
1340
+ } catch (error) {
1341
+ console.error("Combined computed listener error:", error);
1361
1342
  }
1362
1343
  }
1363
1344
  });
@@ -1367,6 +1348,7 @@ function combineComputed(computeds, combiner, options = {}) {
1367
1348
  if (isDestroyed) {
1368
1349
  throw new Error("Cannot access destroyed computed value");
1369
1350
  }
1351
+ refresh();
1370
1352
  return currentValue;
1371
1353
  };
1372
1354
  const invalidate = () => {
@@ -1418,7 +1400,15 @@ function memoizeSelector(selector2, equals = shallowEqual) {
1418
1400
  }
1419
1401
 
1420
1402
  // src/slices.ts
1421
- init_store();
1403
+ var sliceRegistry = /* @__PURE__ */ new WeakMap();
1404
+ function registerSlice(store, name, data) {
1405
+ let slices = sliceRegistry.get(store);
1406
+ if (!slices) {
1407
+ slices = /* @__PURE__ */ new Map();
1408
+ sliceRegistry.set(store, slices);
1409
+ }
1410
+ slices.set(name, data);
1411
+ }
1422
1412
  function createSlice(name, creator) {
1423
1413
  return { name, creator };
1424
1414
  }
@@ -1452,15 +1442,19 @@ function combineSlices(...slices) {
1452
1442
  destroy: () => {
1453
1443
  }
1454
1444
  };
1445
+ const sliceData = /* @__PURE__ */ new Map();
1455
1446
  for (const slice of slices) {
1456
1447
  const sliceResult = slice.creator(set, get, placeholderStore);
1448
+ const data = {};
1457
1449
  for (const [key, value] of Object.entries(sliceResult)) {
1458
1450
  if (typeof value === "function") {
1459
1451
  actions[key] = value;
1460
1452
  } else {
1461
1453
  initialState[key] = value;
1454
+ data[key] = value;
1462
1455
  }
1463
1456
  }
1457
+ sliceData.set(slice.name, data);
1464
1458
  }
1465
1459
  tempStore = createStore(initialState);
1466
1460
  for (const slice of slices) {
@@ -1481,6 +1475,9 @@ function combineSlices(...slices) {
1481
1475
  }
1482
1476
  }
1483
1477
  }
1478
+ for (const [name, data] of sliceData) {
1479
+ registerSlice(tempStore, name, data);
1480
+ }
1484
1481
  const store = tempStore;
1485
1482
  for (const [name, action] of Object.entries(actions)) {
1486
1483
  store[name] = action;
@@ -1488,7 +1485,7 @@ function combineSlices(...slices) {
1488
1485
  return store;
1489
1486
  }
1490
1487
  function createNamespacedSlice(namespace, creator) {
1491
- return createSlice(namespace, (set, get, store) => {
1488
+ return createSlice(namespace, (set, get) => {
1492
1489
  const namespacedSet = (partial) => {
1493
1490
  const current = get()[namespace] || {};
1494
1491
  const update = typeof partial === "function" ? partial(current) : partial;
@@ -1525,13 +1522,16 @@ function extendStore(store, ...slices) {
1525
1522
  const get = () => store.getState();
1526
1523
  for (const slice of slices) {
1527
1524
  const sliceResult = slice.creator(set, get, store);
1525
+ const data = {};
1528
1526
  for (const [key, value] of Object.entries(sliceResult)) {
1529
1527
  if (typeof value === "function") {
1530
1528
  actions[key] = value;
1531
1529
  } else {
1532
1530
  store.setState({ [key]: value });
1531
+ data[key] = value;
1533
1532
  }
1534
1533
  }
1534
+ registerSlice(store, slice.name, data);
1535
1535
  }
1536
1536
  const extendedStore = store;
1537
1537
  for (const [name, action] of Object.entries(actions)) {
@@ -1540,8 +1540,24 @@ function extendStore(store, ...slices) {
1540
1540
  return extendedStore;
1541
1541
  }
1542
1542
  function resetSlices(store, ...sliceNames) {
1543
- console.warn("resetSlices: Use store.reset() to reset all state");
1544
- store.reset();
1543
+ const slices = sliceRegistry.get(store);
1544
+ if (!slices) {
1545
+ console.warn("resetSlices: store was not created with combineSlices/extendStore; resetting all state");
1546
+ store.reset();
1547
+ return;
1548
+ }
1549
+ const update = {};
1550
+ for (const name of sliceNames) {
1551
+ const data = slices.get(name);
1552
+ if (!data) {
1553
+ console.warn(`resetSlices: unknown slice '${name}'`);
1554
+ continue;
1555
+ }
1556
+ Object.assign(update, data);
1557
+ }
1558
+ if (Object.keys(update).length > 0) {
1559
+ store.setState(deepClone(update));
1560
+ }
1545
1561
  }
1546
1562
 
1547
1563
  // src/federation.ts
@@ -1684,6 +1700,15 @@ function createFederation(stores, options = {}) {
1684
1700
  getStore(storeName) {
1685
1701
  return stores[storeName];
1686
1702
  },
1703
+ subscribeStore(storeName, listener) {
1704
+ const store = stores[storeName];
1705
+ if (!store) {
1706
+ throw new Error(`Unknown store '${String(storeName)}' in federation '${name}'`);
1707
+ }
1708
+ const unsubscribe = store.subscribe(listener);
1709
+ unsubscribers.push(unsubscribe);
1710
+ return unsubscribe;
1711
+ },
1687
1712
  destroy() {
1688
1713
  log("Destroying federation");
1689
1714
  for (const unsubscribe of unsubscribers) {
@@ -1750,7 +1775,6 @@ function waitForFederated(federation, predicate, timeout) {
1750
1775
  }
1751
1776
 
1752
1777
  // src/plugins/persist.ts
1753
- init_utils();
1754
1778
  var defaultStorage = {
1755
1779
  getItem: (key) => {
1756
1780
  if (typeof window === "undefined") return null;
@@ -1762,10 +1786,7 @@ var defaultStorage = {
1762
1786
  },
1763
1787
  setItem: (key, value) => {
1764
1788
  if (typeof window === "undefined") return;
1765
- try {
1766
- window.localStorage.setItem(key, value);
1767
- } catch {
1768
- }
1789
+ window.localStorage.setItem(key, value);
1769
1790
  },
1770
1791
  /* c8 ignore next 3 */
1771
1792
  removeItem: () => {
@@ -1782,10 +1803,7 @@ var sessionStorage = {
1782
1803
  },
1783
1804
  setItem: (key, value) => {
1784
1805
  if (typeof window === "undefined") return;
1785
- try {
1786
- window.sessionStorage.setItem(key, value);
1787
- } catch {
1788
- }
1806
+ window.sessionStorage.setItem(key, value);
1789
1807
  },
1790
1808
  removeItem: (key) => {
1791
1809
  if (typeof window === "undefined") return;
@@ -1940,7 +1958,9 @@ function getDevtools() {
1940
1958
  function devtools(options = {}) {
1941
1959
  const { name = "OxogState Store", enabled = true, maxAge = 50 } = options;
1942
1960
  let connection = null;
1943
- let history2 = [];
1961
+ let unsubscribeStore = null;
1962
+ let unsubscribeDevtools = null;
1963
+ let states = [];
1944
1964
  return {
1945
1965
  name: "devtools",
1946
1966
  version: "1.0.0",
@@ -1950,55 +1970,79 @@ function devtools(options = {}) {
1950
1970
  }
1951
1971
  const extension = getDevtools();
1952
1972
  if (!extension) return;
1953
- connection = extension.connect({ name });
1954
- connection.init(store.getState());
1955
- store.subscribe((state, prevState) => {
1956
- if (!connection) return;
1957
- history2.push({ state, action: "UPDATE" });
1958
- if (history2.length > maxAge) {
1959
- history2.shift();
1973
+ const conn = extension.connect({ name });
1974
+ connection = conn;
1975
+ conn.init(store.getState());
1976
+ states = [store.getState()];
1977
+ let applyingFromDevtools = false;
1978
+ const apply = (fn) => {
1979
+ applyingFromDevtools = true;
1980
+ try {
1981
+ fn();
1982
+ } finally {
1983
+ applyingFromDevtools = false;
1984
+ }
1985
+ };
1986
+ unsubscribeStore = store.subscribe((state, prevState) => {
1987
+ if (!connection || applyingFromDevtools) return;
1988
+ states.push(state);
1989
+ if (states.length > maxAge + 1) {
1990
+ states.shift();
1960
1991
  }
1961
1992
  connection.send({ type: "UPDATE", prev: prevState }, state);
1962
1993
  });
1963
- connection.subscribe((message) => {
1964
- if (message.type === "DISPATCH" && message.payload) {
1965
- switch (message.payload.type) {
1966
- case "JUMP_TO_STATE":
1967
- case "JUMP_TO_ACTION": {
1968
- const index = message.payload.type === "JUMP_TO_ACTION" ? history2.findIndex((h) => h.action === message.payload.action) : message.payload.index;
1969
- if (index >= 0 && index < history2.length) {
1970
- const entry = history2[index];
1971
- if (entry) {
1972
- store.setState(entry.state);
1973
- }
1974
- }
1975
- break;
1976
- }
1977
- case "COMMIT": {
1978
- connection.init(store.getState());
1979
- history2 = [];
1980
- break;
1981
- }
1982
- case "ROLLBACK": {
1983
- if (history2.length > 1) {
1984
- const previous = history2[history2.length - 2];
1985
- if (previous) {
1986
- store.setState(previous.state);
1987
- }
1988
- }
1989
- break;
1994
+ const parseState = (message) => {
1995
+ if (typeof message.state !== "string") return void 0;
1996
+ try {
1997
+ return JSON.parse(message.state);
1998
+ } catch {
1999
+ return void 0;
2000
+ }
2001
+ };
2002
+ const unsubscribe = conn.subscribe((message) => {
2003
+ if (message?.type !== "DISPATCH" || !message.payload) return;
2004
+ switch (message.payload.type) {
2005
+ case "JUMP_TO_STATE":
2006
+ case "JUMP_TO_ACTION": {
2007
+ const target = parseState(message) ?? states[message.payload.index];
2008
+ if (target !== void 0) {
2009
+ apply(() => store.setState(target));
1990
2010
  }
1991
- case "RESET": {
1992
- store.reset();
1993
- break;
2011
+ break;
2012
+ }
2013
+ case "COMMIT": {
2014
+ conn.init(store.getState());
2015
+ states = [store.getState()];
2016
+ break;
2017
+ }
2018
+ case "ROLLBACK": {
2019
+ const target = parseState(message) ?? states[0];
2020
+ if (target !== void 0) {
2021
+ apply(() => store.setState(target));
1994
2022
  }
2023
+ conn.init(store.getState());
2024
+ states = [store.getState()];
2025
+ break;
2026
+ }
2027
+ case "RESET": {
2028
+ apply(() => store.reset());
2029
+ conn.init(store.getState());
2030
+ states = [store.getState()];
2031
+ break;
1995
2032
  }
1996
2033
  }
1997
2034
  });
2035
+ if (typeof unsubscribe === "function") {
2036
+ unsubscribeDevtools = unsubscribe;
2037
+ }
1998
2038
  },
1999
2039
  onDestroy() {
2040
+ unsubscribeStore?.();
2041
+ unsubscribeStore = null;
2042
+ unsubscribeDevtools?.();
2043
+ unsubscribeDevtools = null;
2000
2044
  connection = null;
2001
- history2 = [];
2045
+ states = [];
2002
2046
  }
2003
2047
  };
2004
2048
  }
@@ -2008,6 +2052,7 @@ function history(options = {}) {
2008
2052
  const { limit = 50, keys } = options;
2009
2053
  let historyState = null;
2010
2054
  let isInternalUpdate = false;
2055
+ let internalState = null;
2011
2056
  return {
2012
2057
  name: "history",
2013
2058
  version: "1.0.0",
@@ -2019,6 +2064,11 @@ function history(options = {}) {
2019
2064
  };
2020
2065
  store.subscribe((state) => {
2021
2066
  if (!historyState || isInternalUpdate) return;
2067
+ if (internalState !== null && state === internalState) {
2068
+ internalState = null;
2069
+ return;
2070
+ }
2071
+ internalState = null;
2022
2072
  const previousPresent = historyState.present;
2023
2073
  const newPresent = state;
2024
2074
  let hasChanged = true;
@@ -2043,8 +2093,12 @@ function history(options = {}) {
2043
2093
  historyState.future.push(historyState.present);
2044
2094
  historyState.present = previous;
2045
2095
  isInternalUpdate = true;
2046
- store.setState(previous);
2047
- isInternalUpdate = false;
2096
+ try {
2097
+ store.setState(previous);
2098
+ internalState = store.getState();
2099
+ } finally {
2100
+ isInternalUpdate = false;
2101
+ }
2048
2102
  };
2049
2103
  store.redo = () => {
2050
2104
  if (!historyState || historyState.future.length === 0) return;
@@ -2052,8 +2106,12 @@ function history(options = {}) {
2052
2106
  historyState.past.push(historyState.present);
2053
2107
  historyState.present = next;
2054
2108
  isInternalUpdate = true;
2055
- store.setState(next);
2056
- isInternalUpdate = false;
2109
+ try {
2110
+ store.setState(next);
2111
+ internalState = store.getState();
2112
+ } finally {
2113
+ isInternalUpdate = false;
2114
+ }
2057
2115
  };
2058
2116
  store.clearHistory = () => {
2059
2117
  if (!historyState) return;
@@ -2081,7 +2139,16 @@ function sync(options = {}) {
2081
2139
  const { channel = "oxog-state" } = options;
2082
2140
  let broadcastChannel = null;
2083
2141
  let currentStore = null;
2084
- let isLocalUpdate = false;
2142
+ let unsubscribe = null;
2143
+ let applyingRemote = false;
2144
+ const broadcast = (state, errorMessage) => {
2145
+ if (!broadcastChannel) return;
2146
+ try {
2147
+ broadcastChannel.postMessage(toMessage(state));
2148
+ } catch (error) {
2149
+ console.error(errorMessage, error);
2150
+ }
2151
+ };
2085
2152
  return {
2086
2153
  name: "sync",
2087
2154
  version: "1.0.0",
@@ -2093,28 +2160,34 @@ function sync(options = {}) {
2093
2160
  }
2094
2161
  broadcastChannel = new BroadcastChannel(channel);
2095
2162
  broadcastChannel.onmessage = (event) => {
2096
- if (!isLocalUpdate) {
2097
- try {
2098
- store.setState(event.data);
2099
- } catch (error) {
2100
- console.error("Error applying sync state:", error);
2101
- }
2163
+ if (!currentStore) return;
2164
+ applyingRemote = true;
2165
+ try {
2166
+ currentStore.setState(event.data);
2167
+ } catch (error) {
2168
+ console.error("Error applying sync state:", error);
2169
+ } finally {
2170
+ applyingRemote = false;
2102
2171
  }
2103
2172
  };
2173
+ unsubscribe = store.subscribe((state) => {
2174
+ if (!applyingRemote) {
2175
+ broadcast(state, "Error broadcasting state:");
2176
+ }
2177
+ });
2104
2178
  },
2105
2179
  onInit() {
2106
- if (broadcastChannel && currentStore) {
2107
- isLocalUpdate = true;
2108
- try {
2109
- broadcastChannel.postMessage(currentStore.getState());
2110
- } catch (error) {
2111
- console.error("Error broadcasting initial state:", error);
2112
- }
2113
- isLocalUpdate = false;
2180
+ if (currentStore) {
2181
+ broadcast(currentStore.getState(), "Error broadcasting initial state:");
2114
2182
  }
2115
2183
  },
2116
2184
  onDestroy() {
2185
+ if (unsubscribe) {
2186
+ unsubscribe();
2187
+ unsubscribe = null;
2188
+ }
2117
2189
  if (broadcastChannel) {
2190
+ broadcastChannel.onmessage = null;
2118
2191
  broadcastChannel.close();
2119
2192
  broadcastChannel = null;
2120
2193
  }
@@ -2122,82 +2195,166 @@ function sync(options = {}) {
2122
2195
  }
2123
2196
  };
2124
2197
  }
2198
+ function toMessage(state) {
2199
+ if (state === null || typeof state !== "object") return state;
2200
+ const data = {};
2201
+ for (const key of Object.keys(state)) {
2202
+ const value = state[key];
2203
+ if (typeof value !== "function") {
2204
+ data[key] = value;
2205
+ }
2206
+ }
2207
+ return data;
2208
+ }
2125
2209
  function triggerSync(store, channel = "oxog-state") {
2126
2210
  if (typeof BroadcastChannel === "undefined") {
2127
2211
  console.warn("BroadcastChannel is not supported in this environment");
2128
2212
  return;
2129
2213
  }
2130
2214
  const broadcastChannel = new BroadcastChannel(channel);
2131
- broadcastChannel.postMessage(store.getState());
2215
+ broadcastChannel.postMessage(toMessage(store.getState()));
2132
2216
  broadcastChannel.close();
2133
2217
  }
2134
2218
 
2135
2219
  // src/plugins/immer.ts
2136
- function createProxy(base, copies) {
2137
- return new Proxy(base || {}, {
2138
- get(target, key) {
2139
- const value = target[key];
2140
- if (value !== null && typeof value === "object" && !Array.isArray(value)) {
2141
- if (copies.has(value)) {
2142
- return createProxy(copies.get(value), copies);
2143
- }
2144
- return createProxy(value, copies);
2145
- }
2146
- return value;
2220
+ var DRAFT_STATE = /* @__PURE__ */ Symbol("oxog-state.draft");
2221
+ function isDraftable(value) {
2222
+ if (value === null || typeof value !== "object") return false;
2223
+ if (Array.isArray(value)) return true;
2224
+ const proto = Object.getPrototypeOf(value);
2225
+ return proto === Object.prototype || proto === null;
2226
+ }
2227
+ function getDraftState(value) {
2228
+ if (value === null || typeof value !== "object") return void 0;
2229
+ return value[DRAFT_STATE];
2230
+ }
2231
+ function latest(state) {
2232
+ return state.copy ?? state.base;
2233
+ }
2234
+ function hasOwn(target, key) {
2235
+ return Object.prototype.hasOwnProperty.call(target, key);
2236
+ }
2237
+ function shallowCopy(base) {
2238
+ if (Array.isArray(base)) return base.slice();
2239
+ return Object.getPrototypeOf(base) === null ? Object.assign(/* @__PURE__ */ Object.create(null), base) : { ...base };
2240
+ }
2241
+ function markChanged(state) {
2242
+ if (state.copy === null) {
2243
+ state.copy = shallowCopy(state.base);
2244
+ if (state.parent) markChanged(state.parent);
2245
+ }
2246
+ }
2247
+ function createDraft(base, parent) {
2248
+ const state = {
2249
+ base,
2250
+ copy: null,
2251
+ parent,
2252
+ children: /* @__PURE__ */ new Map(),
2253
+ proxy: null,
2254
+ finalized: false,
2255
+ result: void 0
2256
+ };
2257
+ const target = Array.isArray(base) ? [] : {};
2258
+ state.proxy = new Proxy(target, {
2259
+ get(_target, prop) {
2260
+ if (prop === DRAFT_STATE) return state;
2261
+ const source = latest(state);
2262
+ const value = Reflect.get(source, prop, state.proxy);
2263
+ if (!hasOwn(source, prop) || !isDraftable(value)) return value;
2264
+ if (value !== state.base[prop]) return value;
2265
+ let child = state.children.get(prop);
2266
+ if (!child) {
2267
+ child = createDraft(value, state);
2268
+ state.children.set(prop, child);
2269
+ }
2270
+ return child.proxy;
2147
2271
  },
2148
- set(target, key, value) {
2149
- if (!copies.has(target)) {
2150
- copies.set(target, { ...target });
2151
- }
2152
- const copy = copies.get(target);
2153
- copy[key] = value;
2272
+ set(_target, prop, value) {
2273
+ if (prop === "__proto__") return true;
2274
+ const source = latest(state);
2275
+ if (hasOwn(source, prop) && Object.is(source[prop], value)) return true;
2276
+ markChanged(state);
2277
+ state.copy[prop] = value;
2278
+ state.children.delete(prop);
2154
2279
  return true;
2155
2280
  },
2156
- deleteProperty(target, key) {
2157
- if (!copies.has(target)) {
2158
- copies.set(target, { ...target });
2159
- }
2160
- const copy = copies.get(target);
2161
- delete copy[key];
2281
+ deleteProperty(_target, prop) {
2282
+ if (!hasOwn(latest(state), prop)) return true;
2283
+ markChanged(state);
2284
+ delete state.copy[prop];
2285
+ state.children.delete(prop);
2286
+ return true;
2287
+ },
2288
+ has(_target, prop) {
2289
+ return prop in latest(state);
2290
+ },
2291
+ ownKeys() {
2292
+ return Reflect.ownKeys(latest(state));
2293
+ },
2294
+ getOwnPropertyDescriptor(_target, prop) {
2295
+ const source = latest(state);
2296
+ const descriptor = Reflect.getOwnPropertyDescriptor(source, prop);
2297
+ if (!descriptor) return void 0;
2298
+ if (Array.isArray(source) && prop === "length") return descriptor;
2299
+ return { ...descriptor, configurable: true };
2300
+ },
2301
+ defineProperty(_target, prop, descriptor) {
2302
+ markChanged(state);
2303
+ Object.defineProperty(state.copy, prop, { ...descriptor, configurable: true });
2162
2304
  return true;
2305
+ },
2306
+ getPrototypeOf() {
2307
+ return Object.getPrototypeOf(state.base);
2308
+ },
2309
+ setPrototypeOf() {
2310
+ return false;
2163
2311
  }
2164
2312
  });
2313
+ return state;
2314
+ }
2315
+ function finalizeValue(value, seen) {
2316
+ const draft = getDraftState(value);
2317
+ if (draft) return finalizeDraft(draft, seen);
2318
+ if (!isDraftable(value) || seen.has(value)) return value;
2319
+ seen.add(value);
2320
+ for (const key of Object.keys(value)) {
2321
+ const item = value[key];
2322
+ const finalized = finalizeValue(item, seen);
2323
+ if (finalized !== item) value[key] = finalized;
2324
+ }
2325
+ return value;
2165
2326
  }
2166
- function finalize(base, copies) {
2167
- if (!copies.has(base)) {
2168
- return deepClone2(base);
2327
+ function finalizeDraft(state, seen) {
2328
+ if (state.finalized) return state.result;
2329
+ state.finalized = true;
2330
+ if (state.copy === null) {
2331
+ state.result = state.base;
2332
+ return state.result;
2169
2333
  }
2170
- const copy = copies.get(base);
2171
- for (const key in copy) {
2172
- if (Object.prototype.hasOwnProperty.call(copy, key)) {
2173
- const value = copy[key];
2174
- if (value !== null && typeof value === "object" && !Array.isArray(value)) {
2175
- copy[key] = finalize(value, copies);
2176
- }
2334
+ const copy = state.copy;
2335
+ state.result = copy;
2336
+ for (const key of Object.keys(copy)) {
2337
+ const value = copy[key];
2338
+ const child = state.children.get(key);
2339
+ if (child && value === child.base) {
2340
+ copy[key] = finalizeDraft(child, seen);
2341
+ } else if (value !== state.base[key]) {
2342
+ copy[key] = finalizeValue(value, seen);
2177
2343
  }
2178
2344
  }
2179
2345
  return copy;
2180
2346
  }
2181
- function deepClone2(value) {
2182
- if (value === null || typeof value !== "object") {
2183
- return value;
2184
- }
2185
- if (Array.isArray(value)) {
2186
- return value.map((v) => deepClone2(v));
2347
+ function produce(base, recipe) {
2348
+ if (!isDraftable(base)) {
2349
+ const result2 = recipe(base);
2350
+ return result2 === void 0 ? base : result2;
2187
2351
  }
2188
- const cloned = {};
2189
- for (const key in value) {
2190
- if (Object.prototype.hasOwnProperty.call(value, key)) {
2191
- cloned[key] = deepClone2(value[key]);
2192
- }
2352
+ const root = createDraft(base, null);
2353
+ const result = recipe(root.proxy);
2354
+ if (result !== null && typeof result === "object" && result !== root.proxy) {
2355
+ return finalizeValue(result, /* @__PURE__ */ new Set());
2193
2356
  }
2194
- return cloned;
2195
- }
2196
- function produce(base, recipe) {
2197
- const copies = /* @__PURE__ */ new Map();
2198
- const draft = createProxy(base, copies);
2199
- recipe(draft);
2200
- return finalize(base, copies);
2357
+ return finalizeDraft(root, /* @__PURE__ */ new Set());
2201
2358
  }
2202
2359
  function immer() {
2203
2360
  return {
@@ -2207,8 +2364,10 @@ function immer() {
2207
2364
  const originalSetState = store.setState.bind(store);
2208
2365
  store.setState = (update) => {
2209
2366
  if (typeof update === "function") {
2210
- const newState = produce(store.getState(), update);
2211
- originalSetState(newState);
2367
+ const current = store.getState();
2368
+ const next = produce(current, update);
2369
+ if (next === current) return;
2370
+ originalSetState(next);
2212
2371
  } else {
2213
2372
  originalSetState(update);
2214
2373
  }
@@ -2225,28 +2384,43 @@ function selector(options) {
2225
2384
  version: "1.0.0",
2226
2385
  install(store) {
2227
2386
  const originalGetState = store.getState.bind(store);
2228
- const cache = /* @__PURE__ */ new Map();
2229
- const computedState = new Proxy({}, {
2230
- get(_, prop) {
2231
- const selectorFn = selectors[prop];
2232
- if (selectorFn) {
2233
- const currentState = originalGetState();
2234
- const cacheKey = prop;
2235
- const cached = cache.get(cacheKey);
2236
- if (cached && cached.state === currentState) {
2237
- return cached.value;
2387
+ let lastState;
2388
+ let lastSnapshot;
2389
+ const createSnapshot = (state) => {
2390
+ if (state === null || typeof state !== "object") return state;
2391
+ const cache = /* @__PURE__ */ new Map();
2392
+ return new Proxy(state, {
2393
+ get(target, prop, receiver) {
2394
+ const selectorFn = Object.prototype.hasOwnProperty.call(selectors, prop) ? selectors[prop] : void 0;
2395
+ if (selectorFn) {
2396
+ if (!cache.has(prop)) {
2397
+ cache.set(prop, selectorFn(state));
2398
+ }
2399
+ return cache.get(prop);
2238
2400
  }
2239
- const value = selectorFn(currentState);
2240
- cache.set(cacheKey, { value, state: currentState });
2241
- return value;
2401
+ return Reflect.get(target, prop, receiver);
2402
+ },
2403
+ getOwnPropertyDescriptor(target, prop) {
2404
+ const descriptor = Reflect.getOwnPropertyDescriptor(target, prop);
2405
+ const selectorFn = Object.prototype.hasOwnProperty.call(selectors, prop) ? selectors[prop] : void 0;
2406
+ if (descriptor && selectorFn && "value" in descriptor && descriptor.configurable) {
2407
+ if (!cache.has(prop)) {
2408
+ cache.set(prop, selectorFn(state));
2409
+ }
2410
+ return { ...descriptor, value: cache.get(prop) };
2411
+ }
2412
+ return descriptor;
2242
2413
  }
2243
- return originalGetState()[prop];
2414
+ });
2415
+ };
2416
+ store.getState = () => {
2417
+ const state = originalGetState();
2418
+ if (state !== lastState || lastSnapshot === void 0) {
2419
+ lastState = state;
2420
+ lastSnapshot = createSnapshot(state);
2244
2421
  }
2245
- });
2246
- store.getState = () => computedState;
2247
- store.subscribe(() => {
2248
- cache.clear();
2249
- });
2422
+ return lastSnapshot;
2423
+ };
2250
2424
  }
2251
2425
  };
2252
2426
  }
@@ -2408,7 +2582,6 @@ function createLogger(defaultOptions = {}) {
2408
2582
  }
2409
2583
 
2410
2584
  // src/plugins/effects.ts
2411
- init_utils();
2412
2585
  function createDebounced3(fn, delay2) {
2413
2586
  let timeoutId = null;
2414
2587
  const debounced = ((...args) => {
@@ -2430,12 +2603,20 @@ function createDebounced3(fn, delay2) {
2430
2603
  }
2431
2604
  function effects(options) {
2432
2605
  const { effects: effectDefs, onError } = options;
2606
+ let destroyAll = null;
2433
2607
  return {
2434
2608
  name: "effects",
2435
2609
  version: "1.0.0",
2436
2610
  install(store) {
2437
2611
  const cleanups = [];
2438
- const effectCleanups = /* @__PURE__ */ new Map();
2612
+ let destroyed = false;
2613
+ const report = (error, name) => {
2614
+ if (onError) {
2615
+ onError(error, name);
2616
+ } else {
2617
+ console.error(`Effect error${name ? ` in '${name}'` : ""}:`, error);
2618
+ }
2619
+ };
2439
2620
  for (let i = 0; i < effectDefs.length; i++) {
2440
2621
  const def = effectDefs[i];
2441
2622
  if (!def) continue;
@@ -2447,85 +2628,101 @@ function effects(options) {
2447
2628
  debounce,
2448
2629
  name
2449
2630
  } = def;
2450
- let isActive = true;
2451
- let prevValue = selector2(store.getState());
2452
- const createUtils = () => ({
2453
- getState: () => store.getState(),
2454
- setState: (partial) => store.setState(partial),
2455
- isActive: () => isActive,
2456
- cancel: () => {
2457
- isActive = false;
2458
- },
2459
- onlyIfActive: (fn) => {
2460
- if (isActive) {
2461
- return fn();
2462
- }
2463
- return void 0;
2631
+ let currentRun = null;
2632
+ let currentCleanup = null;
2633
+ const runCleanup = (cleanup) => {
2634
+ if (!cleanup) return;
2635
+ try {
2636
+ cleanup();
2637
+ } catch (error) {
2638
+ report(error, name);
2464
2639
  }
2465
- });
2640
+ };
2641
+ const deactivate = (run) => {
2642
+ if (run && run.active) {
2643
+ run.active = false;
2644
+ run.controller.abort();
2645
+ }
2646
+ };
2466
2647
  const runEffect = async (value, prev) => {
2467
- const prevCleanup = effectCleanups.get(i);
2468
- if (prevCleanup) {
2469
- try {
2470
- prevCleanup();
2471
- } catch (e) {
2648
+ if (destroyed) return;
2649
+ deactivate(currentRun);
2650
+ const previousCleanup = currentCleanup;
2651
+ currentCleanup = null;
2652
+ runCleanup(previousCleanup);
2653
+ const run = { active: true, controller: new AbortController() };
2654
+ currentRun = run;
2655
+ const utils = {
2656
+ getState: () => store.getState(),
2657
+ setState: (partial) => {
2658
+ if (run.active) store.setState(partial);
2659
+ },
2660
+ isActive: () => run.active,
2661
+ cancel: () => deactivate(run),
2662
+ onlyIfActive: (fn) => run.active ? fn() : void 0,
2663
+ signal: run.controller.signal
2664
+ };
2665
+ const settle = (result) => {
2666
+ if (typeof result !== "function") return;
2667
+ if (run.active) {
2668
+ currentCleanup = result;
2669
+ } else {
2670
+ runCleanup(result);
2472
2671
  }
2473
- effectCleanups.delete(i);
2474
- }
2475
- isActive = true;
2672
+ };
2673
+ const fail = (error) => {
2674
+ if (!(run.controller.signal.aborted && error?.name === "AbortError")) {
2675
+ report(error, name);
2676
+ }
2677
+ };
2476
2678
  try {
2477
- const result = effect(value, prev, createUtils());
2679
+ const result = effect(value, prev, utils);
2478
2680
  if (result instanceof Promise) {
2479
- const cleanup = await result;
2480
- if (cleanup && isActive) {
2481
- effectCleanups.set(i, cleanup);
2681
+ try {
2682
+ settle(await result);
2683
+ } catch (error) {
2684
+ fail(error);
2482
2685
  }
2483
- } else if (result) {
2484
- effectCleanups.set(i, result);
2485
- }
2486
- } catch (error) {
2487
- if (onError) {
2488
- onError(error, name);
2489
2686
  } else {
2490
- console.error(`Effect error${name ? ` in '${name}'` : ""}:`, error);
2687
+ settle(result);
2491
2688
  }
2689
+ } catch (error) {
2690
+ fail(error);
2492
2691
  }
2493
2692
  };
2494
- const effectFn = debounce && debounce > 0 ? createDebounced3(runEffect, debounce) : runEffect;
2693
+ const debounced = debounce && debounce > 0 ? createDebounced3(runEffect, debounce) : null;
2694
+ const effectFn = debounced ?? runEffect;
2495
2695
  if (fireImmediately) {
2496
- effectFn(prevValue, prevValue);
2696
+ const initial = selector2(store.getState());
2697
+ void effectFn(initial, initial);
2497
2698
  }
2498
2699
  const unsubscribe = store.subscribe(
2499
2700
  selector2,
2500
2701
  (value, prev) => {
2501
- if (!equalityFn(value, prev)) {
2502
- prevValue = value;
2503
- effectFn(value, prev);
2504
- }
2702
+ void effectFn(value, prev);
2505
2703
  },
2506
2704
  equalityFn
2507
2705
  );
2508
2706
  cleanups.push(() => {
2509
2707
  unsubscribe();
2510
- isActive = false;
2511
- if ("cancel" in effectFn) {
2512
- effectFn.cancel();
2513
- }
2514
- const cleanup = effectCleanups.get(i);
2515
- if (cleanup) {
2516
- try {
2517
- cleanup();
2518
- } catch {
2519
- }
2520
- }
2708
+ debounced?.cancel();
2709
+ deactivate(currentRun);
2710
+ const cleanup = currentCleanup;
2711
+ currentCleanup = null;
2712
+ runCleanup(cleanup);
2521
2713
  });
2522
2714
  }
2523
- store.__effectsCleanup = () => {
2715
+ destroyAll = () => {
2716
+ if (destroyed) return;
2717
+ destroyed = true;
2524
2718
  for (const cleanup of cleanups) {
2525
2719
  cleanup();
2526
2720
  }
2527
- effectCleanups.clear();
2528
2721
  };
2722
+ store.__effectsCleanup = destroyAll;
2723
+ },
2724
+ onDestroy() {
2725
+ destroyAll?.();
2529
2726
  }
2530
2727
  };
2531
2728
  }
@@ -2731,12 +2928,7 @@ function createAsyncValidator(validator) {
2731
2928
  };
2732
2929
  }
2733
2930
 
2734
- // src/index.ts
2735
- init_utils();
2736
-
2737
2931
  // src/testing.ts
2738
- init_store();
2739
- init_utils();
2740
2932
  function createMockStorage() {
2741
2933
  const storage = /* @__PURE__ */ new Map();
2742
2934
  return {
@@ -2951,7 +3143,7 @@ function toMiddlewareApi(store) {
2951
3143
  destroy: () => store.destroy()
2952
3144
  };
2953
3145
  }
2954
- function middlewareCompat(middleware, options) {
3146
+ function middlewareCompat(middleware, _options) {
2955
3147
  return {
2956
3148
  name: "middleware-compat",
2957
3149
  version: "1.0.0",
@@ -2984,7 +3176,6 @@ function middlewareCompat(middleware, options) {
2984
3176
  };
2985
3177
  }
2986
3178
  function createWithMiddleware(creator) {
2987
- const { createStore: createStore2 } = (init_store(), __toCommonJS(store_exports));
2988
3179
  let currentState = null;
2989
3180
  let storeRef = null;
2990
3181
  const set = (partial, replace) => {
@@ -3022,7 +3213,7 @@ function createWithMiddleware(creator) {
3022
3213
  }
3023
3214
  };
3024
3215
  currentState = creator(set, get, placeholderApi);
3025
- storeRef = createStore2(currentState);
3216
+ storeRef = createStore(currentState);
3026
3217
  const api = {
3027
3218
  setState: (partial, replace) => {
3028
3219
  if (typeof partial === "function") {