coaction 2.1.0 → 3.0.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,58 +1,54 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- //#region \0rolldown/runtime.js
3
- var __create = Object.create;
4
- var __defProp = Object.defineProperty;
5
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
- var __getOwnPropNames = Object.getOwnPropertyNames;
7
- var __getProtoOf = Object.getPrototypeOf;
8
- var __hasOwnProp = Object.prototype.hasOwnProperty;
9
- var __copyProps = (to, from, except, desc) => {
10
- if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
- key = keys[i];
12
- if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
13
- get: ((k) => from[k]).bind(null, key),
14
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
15
- });
16
- }
17
- return to;
18
- };
19
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
20
- value: mod,
21
- enumerable: true
22
- }) : target, mod));
23
- //#endregion
24
- let mutative = require("mutative");
25
2
  let data_transport = require("data-transport");
26
3
  let alien_signals = require("alien-signals");
27
- let alien_signals_system = require("alien-signals/system");
28
- alien_signals_system = __toESM(alien_signals_system);
29
- //#region packages/core/src/global.ts
30
- const getGlobal = () => {
31
- let _global;
32
- if (typeof window !== "undefined") _global = window;
33
- else if (typeof global !== "undefined") _global = global;
34
- else if (typeof self !== "undefined") _global = self;
35
- else _global = {};
36
- return _global;
4
+ let mutative = require("mutative");
5
+ //#region packages/core/src/lifecycle.ts
6
+ const reportLifecycleError = (error) => {
7
+ if (process.env.NODE_ENV === "development") console.error(error);
37
8
  };
38
- //#endregion
39
- //#region packages/core/src/constant.ts
40
- const WorkerType = getGlobal().SharedWorkerGlobalScope ? "SharedWorkerInternal" : globalThis.WorkerGlobalScope ? "WebWorkerInternal" : null;
41
- const bindSymbol = Symbol("bind");
42
- //#endregion
43
- //#region packages/core/src/wrapStore.ts
44
- /**
45
- * Convert a store object into Coaction's callable store shape.
46
- *
47
- * @remarks
48
- * Framework bindings use this to attach selector-aware readers while
49
- * preserving the underlying store API on the returned function object. Most
50
- * applications should call {@link create} instead of using `wrapStore()`
51
- * directly.
52
- */
53
- const wrapStore = (store, getState = () => store.getState()) => {
54
- const { name, ..._store } = store;
55
- return Object.assign({ [name]: (...args) => getState(...args) }[name], _store);
9
+ const tryDestroyStore = (store) => {
10
+ try {
11
+ store.destroy?.();
12
+ } catch (error) {
13
+ reportLifecycleError(error);
14
+ }
15
+ };
16
+ const failStoreSetup = (store, error) => {
17
+ tryDestroyStore(store);
18
+ throw error;
19
+ };
20
+ const failTransportInitialization = (transport, error) => {
21
+ try {
22
+ transport?.dispose?.();
23
+ } catch (disposeError) {
24
+ reportLifecycleError(disposeError);
25
+ }
26
+ throw error;
27
+ };
28
+ const readyStores = /* @__PURE__ */ new WeakSet();
29
+ const readyCallbacks = /* @__PURE__ */ new WeakMap();
30
+ const onStoreReady = (store, callback) => {
31
+ if (readyStores.has(store)) {
32
+ callback();
33
+ return () => void 0;
34
+ }
35
+ let callbacks = readyCallbacks.get(store);
36
+ if (!callbacks) {
37
+ callbacks = /* @__PURE__ */ new Set();
38
+ readyCallbacks.set(store, callbacks);
39
+ }
40
+ callbacks.add(callback);
41
+ return () => {
42
+ callbacks?.delete(callback);
43
+ };
44
+ };
45
+ const markStoreReady = (store) => {
46
+ readyStores.add(store);
47
+ const callbacks = readyCallbacks.get(store);
48
+ if (!callbacks) return;
49
+ readyCallbacks.delete(store);
50
+ callbacks.forEach((callback) => callback());
51
+ callbacks.clear();
56
52
  };
57
53
  //#endregion
58
54
  //#region packages/core/src/utils.ts
@@ -96,95 +92,6 @@ const sanitizeCheckedPatches = (patches, source) => {
96
92
  assertSafePatches(patches, source);
97
93
  return sanitizePatches(patches) ?? [];
98
94
  };
99
- const createRootReplacementPatches = (currentState, nextState) => {
100
- const patches = [];
101
- const inversePatches = [];
102
- const nextKeys = new Set(getOwnEnumerableKeys(nextState));
103
- for (const key of getOwnEnumerableKeys(currentState)) {
104
- if (typeof key === "string" && isUnsafeKey(key)) continue;
105
- if (nextKeys.has(key)) continue;
106
- patches.push({
107
- op: "remove",
108
- path: [key]
109
- });
110
- inversePatches.push({
111
- op: "add",
112
- path: [key],
113
- value: currentState[key]
114
- });
115
- }
116
- for (const key of nextKeys) {
117
- if (typeof key === "string" && isUnsafeKey(key)) continue;
118
- if (!Object.prototype.hasOwnProperty.call(currentState, key)) {
119
- patches.push({
120
- op: "add",
121
- path: [key],
122
- value: nextState[key]
123
- });
124
- inversePatches.push({
125
- op: "remove",
126
- path: [key]
127
- });
128
- continue;
129
- }
130
- if (Object.is(currentState[key], nextState[key])) continue;
131
- patches.push({
132
- op: "replace",
133
- path: [key],
134
- value: nextState[key]
135
- });
136
- inversePatches.push({
137
- op: "replace",
138
- path: [key],
139
- value: currentState[key]
140
- });
141
- }
142
- return {
143
- patches,
144
- inversePatches
145
- };
146
- };
147
- const createRootStateFromPatches = (currentState, patches) => {
148
- const nextState = sanitizeReplacementState(currentState);
149
- const seen = /* @__PURE__ */ new WeakMap();
150
- for (const patch of patches) {
151
- if (!Array.isArray(patch.path) || patch.path.length !== 1 || ![
152
- "add",
153
- "remove",
154
- "replace"
155
- ].includes(patch.op)) return;
156
- const key = patch.path[0];
157
- if (patch.op === "remove") {
158
- delete nextState[key];
159
- continue;
160
- }
161
- nextState[key] = sanitizeReplacementState(patch.value, seen);
162
- }
163
- return nextState;
164
- };
165
- const applyRootReplacementWithPatches = (store, nextState, options = {}) => {
166
- const { patches, inversePatches } = createRootReplacementPatches(store.getPureState(), nextState);
167
- const finalPatches = store.patch ? store.patch({
168
- patches,
169
- inversePatches
170
- }) : {
171
- patches,
172
- inversePatches
173
- };
174
- const safePatches = sanitizeCheckedPatches(finalPatches.patches, "store.patch()");
175
- const safeInversePatches = sanitizeCheckedPatches(finalPatches.inversePatches, "store.patch() inverse patches");
176
- if (safePatches.length) {
177
- const applyExactReplacement = options.applyExactReplacement;
178
- const exactReplacementState = applyExactReplacement ? createRootStateFromPatches(store.getPureState(), safePatches) : void 0;
179
- if (applyExactReplacement && exactReplacementState) applyExactReplacement(exactReplacementState);
180
- else store.apply(store.getPureState(), safePatches);
181
- }
182
- return [
183
- store.getPureState(),
184
- safePatches,
185
- safeInversePatches
186
- ];
187
- };
188
95
  const setOwnEnumerable = (target, key, value) => {
189
96
  if (typeof key === "string" && isUnsafeKey(key)) return;
190
97
  target[key] = value;
@@ -245,7 +152,7 @@ const assertKnownStateShape = (source, rootState, schema, isSliceStore, options
245
152
  for (const sliceKey of getOwnEnumerableKeys(slice)) assertKnownSchemaKey(knownSliceKeys, sliceKey, [key]);
246
153
  }
247
154
  };
248
- const isArrayIndexKey$2 = (key) => {
155
+ const isArrayIndexKey = (key) => {
249
156
  if (typeof key !== "string") return false;
250
157
  const index = Number(key);
251
158
  return Number.isInteger(index) && index >= 0 && index < 2 ** 32 - 1 && String(index) === key;
@@ -254,20 +161,6 @@ const assignOwnEnumerable = (target, source, seen = /* @__PURE__ */ new WeakMap(
254
161
  if (!seen.has(source)) seen.set(source, target);
255
162
  for (const key of getOwnEnumerableKeys(source)) setOwnEnumerable(target, key, sanitizeReplacementState(source[key], seen));
256
163
  };
257
- const replaceOwnEnumerable = (target, source) => {
258
- const seen = /* @__PURE__ */ new WeakMap();
259
- seen.set(source, target);
260
- const nextKeys = /* @__PURE__ */ new Set();
261
- for (const key of getOwnEnumerableKeys(source)) {
262
- if (typeof key === "string" && isUnsafeKey(key)) continue;
263
- if (typeof source[key] === "function") continue;
264
- nextKeys.add(key);
265
- }
266
- for (const key of getOwnEnumerableKeys(target)) if (!nextKeys.has(key)) delete target[key];
267
- nextKeys.forEach((key) => {
268
- setOwnEnumerable(target, key, sanitizeReplacementState(source[key], seen));
269
- });
270
- };
271
164
  const cloneOwnEnumerable = (source) => {
272
165
  const target = {};
273
166
  assignOwnEnumerable(target, source);
@@ -283,7 +176,7 @@ const sanitizeReplacementState = (source, seen = /* @__PURE__ */ new WeakMap())
283
176
  seen.set(source, target);
284
177
  for (let index = 0; index < source.length; index += 1) if (Object.prototype.hasOwnProperty.call(source, index)) target[index] = sanitizeReplacementState(source[index], seen);
285
178
  for (const key of getOwnEnumerableKeys(source)) {
286
- if (isArrayIndexKey$2(key) || typeof key === "string" && isUnsafeKey(key)) continue;
179
+ if (isArrayIndexKey(key) || typeof key === "string" && isUnsafeKey(key)) continue;
287
180
  const value = source[key];
288
181
  if (typeof value === "function") continue;
289
182
  setOwnEnumerable(target, key, sanitizeReplacementState(value, seen));
@@ -312,7 +205,7 @@ const sanitizeInitialStateValue = (source, seen = /* @__PURE__ */ new WeakMap())
312
205
  seen.set(source, target);
313
206
  for (let index = 0; index < source.length; index += 1) if (Object.prototype.hasOwnProperty.call(source, index)) target[index] = sanitizeInitialStateValue(source[index], seen);
314
207
  for (const key of getOwnEnumerableKeys(source)) {
315
- if (isArrayIndexKey$2(key) || typeof key === "string" && isUnsafeKey(key)) continue;
208
+ if (isArrayIndexKey(key) || typeof key === "string" && isUnsafeKey(key)) continue;
316
209
  setOwnEnumerable(target, key, sanitizeInitialStateValue(source[key], seen));
317
210
  }
318
211
  return target;
@@ -357,320 +250,628 @@ const uuid = () => {
357
250
  });
358
251
  };
359
252
  //#endregion
360
- //#region packages/core/src/sharedState.ts
361
- const formatPropertyPath = (path) => path.length ? path.map((key) => String(key)).join(".") : "<root>";
362
- const isPlainObject = (value) => {
363
- const prototype = Object.getPrototypeOf(value);
364
- return prototype === Object.prototype || prototype === null;
365
- };
366
- const isArrayIndexKey$1 = (key, length) => {
367
- if (key === "") return false;
368
- const index = Number(key);
369
- return Number.isInteger(index) && index >= 0 && index < length && String(index) === key;
370
- };
371
- const findSymbolKeyViolation = (value, path = [], seen = /* @__PURE__ */ new WeakSet()) => {
372
- if (typeof value !== "object" || value === null) return;
373
- if (seen.has(value)) return;
374
- seen.add(value);
375
- const descriptors = Object.getOwnPropertyDescriptors(value);
376
- for (const key of getOwnEnumerableKeys(value)) {
377
- const nextPath = [...path, key];
378
- if (typeof key === "symbol") return {
379
- type: "symbol-key",
380
- path: nextPath
381
- };
382
- const descriptor = descriptors[key];
383
- if (descriptor && Object.prototype.hasOwnProperty.call(descriptor, "value")) {
384
- const violation = findSymbolKeyViolation(descriptor.value, nextPath, seen);
385
- if (violation) return violation;
386
- }
253
+ //#region packages/core/src/computed.ts
254
+ const isObjectLike = (value) => typeof value === "object" && value !== null;
255
+ const runComputedRead = (internal, read) => {
256
+ internal.computedReadDepth = (internal.computedReadDepth ?? 0) + 1;
257
+ try {
258
+ return read();
259
+ } finally {
260
+ internal.computedReadDepth -= 1;
387
261
  }
388
262
  };
389
- const findJsonViolation = (value, path = [], ancestors = /* @__PURE__ */ new WeakSet()) => {
390
- switch (typeof value) {
391
- case "symbol": return {
392
- type: "symbol-value",
393
- path
394
- };
395
- case "bigint": return {
396
- type: "bigint",
397
- path
398
- };
399
- case "undefined": return {
400
- type: "undefined",
401
- path
402
- };
403
- case "function": return {
404
- type: "function",
405
- path
263
+ var Computed = class {
264
+ deps;
265
+ fn;
266
+ constructor(deps, fn) {
267
+ this.deps = deps;
268
+ this.fn = fn;
269
+ }
270
+ createGetter({ internal }) {
271
+ const memoByReceiver = /* @__PURE__ */ new WeakMap();
272
+ const lastArgs = /* @__PURE__ */ new WeakMap();
273
+ const lastResult = /* @__PURE__ */ new WeakMap();
274
+ const fallbackReceiver = {};
275
+ const evaluate = (receiver) => {
276
+ const args = this.deps(internal.module);
277
+ if (!lastArgs.has(receiver) || !areShallowEqualWithArray(lastArgs.get(receiver), args)) lastResult.set(receiver, this.fn.apply(receiver, args));
278
+ lastArgs.set(receiver, args);
279
+ return lastResult.get(receiver);
406
280
  };
407
- case "number": return Number.isFinite(value) ? void 0 : {
408
- type: "non-finite-number",
409
- path
281
+ return function() {
282
+ const receiver = typeof this === "object" && this !== null ? this : fallbackReceiver;
283
+ if (internal.isBatching) return evaluate(receiver);
284
+ let accessor = memoByReceiver.get(receiver);
285
+ if (!accessor) {
286
+ accessor = (0, alien_signals.computed)(() => runComputedRead(internal, () => evaluate(receiver)));
287
+ memoByReceiver.set(receiver, accessor);
288
+ }
289
+ return accessor();
410
290
  };
411
- default: break;
412
291
  }
413
- if (typeof value !== "object" || value === null) return;
414
- if (ancestors.has(value)) return {
415
- type: "circular-reference",
416
- path
417
- };
418
- if (Array.isArray(value)) {
419
- ancestors.add(value);
420
- for (let index = 0; index < value.length; index += 1) if (!Object.prototype.hasOwnProperty.call(value, index)) return {
421
- type: "array-hole",
422
- path: [...path, index]
423
- };
424
- for (const key of getOwnEnumerableKeys(value)) {
425
- const nextPath = [...path, key];
426
- if (typeof key === "symbol") return {
427
- type: "symbol-key",
428
- path: nextPath
429
- };
430
- if (!isArrayIndexKey$1(key, value.length)) return {
431
- type: "array-property",
432
- path: nextPath
433
- };
434
- const violation = findJsonViolation(value[Number(key)], nextPath, ancestors);
435
- if (violation) return violation;
292
+ };
293
+ const createCachedGetter = (internal, getter) => {
294
+ const accessors = /* @__PURE__ */ new WeakMap();
295
+ const fallbackReceiver = {};
296
+ return function() {
297
+ const receiver = typeof this === "object" && this !== null ? this : fallbackReceiver;
298
+ if (internal.isBatching) return getter.call(receiver);
299
+ let accessor = accessors.get(receiver);
300
+ if (!accessor) {
301
+ accessor = (0, alien_signals.computed)(() => runComputedRead(internal, () => getter.call(receiver)));
302
+ accessors.set(receiver, accessor);
436
303
  }
437
- ancestors.delete(value);
438
- return;
439
- }
440
- if (!isPlainObject(value)) return {
441
- type: "non-plain-object",
442
- path
304
+ return accessor();
443
305
  };
444
- if (typeof value.toJSON === "function") return {
445
- type: "to-json",
446
- path
306
+ };
307
+ const createTrackedStateReader = (internal, read, initialValue) => {
308
+ const slotSignal = (0, alien_signals.signal)(initialValue);
309
+ const slotVersionSignal = (0, alien_signals.signal)(0);
310
+ let slotVersion = 0;
311
+ (internal.signalSlots ??= /* @__PURE__ */ new Set()).add({ refresh: () => {
312
+ const nextValue = read();
313
+ slotSignal(nextValue);
314
+ if (internal.mutableInstance && isObjectLike(nextValue)) {
315
+ slotVersion += 1;
316
+ slotVersionSignal(slotVersion);
317
+ }
318
+ } });
319
+ return () => {
320
+ const currentValue = slotSignal();
321
+ if (internal.mutableInstance && isObjectLike(currentValue)) slotVersionSignal();
322
+ return read();
447
323
  };
448
- ancestors.add(value);
449
- for (const key of getOwnEnumerableKeys(value)) {
450
- const nextPath = [...path, key];
451
- if (typeof key === "symbol") return {
452
- type: "symbol-key",
453
- path: nextPath
454
- };
455
- const child = value[key];
456
- const violation = findJsonViolation(child, nextPath, ancestors);
457
- if (violation) return violation;
458
- }
459
- ancestors.delete(value);
460
- };
461
- const getViolationLabel = (violation) => {
462
- switch (violation.type) {
463
- case "bigint": return "BigInt-valued state";
464
- case "undefined": return "Undefined-valued state";
465
- case "function": return "Function-valued state";
466
- case "non-finite-number": return "NaN or infinite number state";
467
- case "non-plain-object": return "Non-plain object state";
468
- case "circular-reference": return "Circular state reference";
469
- case "array-hole": return "Sparse array state";
470
- case "array-property": return "Non-index array property state";
471
- case "to-json": return "Custom toJSON state";
472
- default: return;
324
+ };
325
+ const refreshSignalSlots = (internal) => {
326
+ if (!internal.signalSlots?.size) return;
327
+ (0, alien_signals.startBatch)();
328
+ try {
329
+ internal.signalSlots.forEach((slot) => slot.refresh());
330
+ } finally {
331
+ (0, alien_signals.endBatch)();
473
332
  }
474
333
  };
475
- const validateSharedActionPaths = (state) => {
476
- const violation = findSymbolKeyViolation(state);
477
- if (!violation) return;
478
- throw new Error(`Symbol-keyed state is not supported in shared store mode because transport synchronization uses JSON and string action paths. Found symbol key at ${formatPropertyPath(violation.path)}.`);
334
+ //#endregion
335
+ //#region packages/core/src/sharedState.ts
336
+ const formatPath = (path) => path.length ? path.map((key) => String(key)).join(".") : "<root>";
337
+ const unsupported = (label, path) => {
338
+ throw new TypeError(`${label} is not supported in shared store mode because transport synchronization uses JSON. Found unsupported value at ${formatPath(path)}.`);
479
339
  };
480
- const validateSharedStateSerializable = (state) => {
481
- const violation = findJsonViolation(state);
482
- if (!violation) return;
483
- if (violation.type === "symbol-key") throw new Error(`Symbol-keyed state is not supported in shared store mode because transport synchronization uses JSON and string action paths. Found symbol key at ${formatPropertyPath(violation.path)}.`);
484
- if (violation.type === "symbol-value") throw new Error(`Symbol-valued state is not supported in shared store mode because transport synchronization uses JSON. Found symbol value at ${formatPropertyPath(violation.path)}.`);
485
- throw new Error(`${getViolationLabel(violation)} is not supported in shared store mode because transport synchronization uses JSON. Found unsupported value at ${formatPropertyPath(violation.path)}.`);
340
+ const getDescriptors = (value, path) => {
341
+ try {
342
+ return Object.getOwnPropertyDescriptors(value);
343
+ } catch {
344
+ return unsupported("Uninspectable state", path);
345
+ }
486
346
  };
487
- //#endregion
488
- //#region packages/core/src/asyncClientStore.ts
489
- const parseFullSyncState$1 = (state) => {
490
- const parsed = JSON.parse(state);
491
- if (typeof parsed !== "object" || parsed === null) throw new Error("Invalid fullSync payload");
492
- return sanitizeReplacementState(parsed);
347
+ const getPrototype = (value, path) => {
348
+ try {
349
+ return Object.getPrototypeOf(value);
350
+ } catch {
351
+ return unsupported("Uninspectable state prototype", path);
352
+ }
493
353
  };
494
- const clientApplyErrorMessage = "apply() cannot be called in the client store. Client stores are mirrors; use a store method to update the main store instead.";
495
- const createAsyncClientStore = (createStore, asyncStoreClientOption) => {
496
- const { store: asyncClientStore, internal } = createStore({ share: "client" });
497
- let isApplyingClientState = false;
498
- const previousAssertMutationAllowed = internal.assertMutationAllowed;
499
- internal.assertMutationAllowed = (operation) => {
500
- if (operation === "apply" && !isApplyingClientState) throw new Error(clientApplyErrorMessage);
501
- previousAssertMutationAllowed?.(operation);
502
- };
503
- const baseApply = asyncClientStore.apply.bind(asyncClientStore);
504
- asyncClientStore.apply = (state, patches) => {
505
- if (!isApplyingClientState) throw new Error(clientApplyErrorMessage);
506
- return baseApply(state, patches);
507
- };
508
- internal.applyClientState = (...args) => {
509
- isApplyingClientState = true;
354
+ const assertNoInheritedToJson = (prototype, path) => {
355
+ let current = prototype;
356
+ while (current) {
357
+ let descriptor;
510
358
  try {
511
- baseApply(...args);
512
- } finally {
513
- isApplyingClientState = false;
359
+ descriptor = Object.getOwnPropertyDescriptor(current, "toJSON");
360
+ } catch {
361
+ unsupported("Uninspectable inherited toJSON state", path);
514
362
  }
515
- };
516
- const isSharedWorker = typeof SharedWorker !== "undefined" && asyncStoreClientOption.worker instanceof SharedWorker;
517
- const transport = asyncStoreClientOption.worker ? (0, data_transport.createTransport)(isSharedWorker ? "SharedWorkerClient" : "WebWorkerClient", {
518
- worker: asyncStoreClientOption.worker,
519
- prefix: asyncClientStore.name
520
- }) : asyncStoreClientOption.clientTransport;
521
- if (!transport) throw new Error("transport is required");
522
- asyncClientStore.transport = transport;
523
- let syncingPromise = null;
524
- let awaitingReconnectSync = false;
525
- let reconnectSequenceBaseline = null;
526
- const fullSync = async (allowLowerSequence = false) => {
527
- if (!syncingPromise) syncingPromise = (async () => {
528
- const latest = await transport.emit("fullSync");
529
- if (typeof latest !== "object" || latest === null || typeof latest.sequence !== "number" || typeof latest.state !== "string") throw new Error("Invalid fullSync payload");
530
- const canApplyLowerSequence = allowLowerSequence && awaitingReconnectSync && reconnectSequenceBaseline !== null && reconnectSequenceBaseline === internal.sequence;
531
- if (latest.sequence < internal.sequence && !canApplyLowerSequence) return;
532
- internal.applyClientState(parseFullSyncState$1(latest.state));
533
- internal.sequence = latest.sequence;
534
- awaitingReconnectSync = false;
535
- reconnectSequenceBaseline = null;
536
- })().finally(() => {
537
- syncingPromise = null;
538
- });
539
- return syncingPromise;
540
- };
541
- if (typeof transport.onConnect !== "function") throw new Error("transport.onConnect is required");
542
- transport.onConnect?.(() => {
543
- awaitingReconnectSync = true;
544
- reconnectSequenceBaseline = internal.sequence;
545
- fullSync(true).catch((error) => {
546
- if (process.env.NODE_ENV === "development") console.error(error);
547
- });
363
+ if (descriptor) {
364
+ if (!Object.prototype.hasOwnProperty.call(descriptor, "value") || typeof descriptor.value === "function") unsupported("Inherited toJSON state", path);
365
+ return;
366
+ }
367
+ current = getPrototype(current, path);
368
+ }
369
+ };
370
+ const isArrayIndex = (key, length) => {
371
+ const index = Number(key);
372
+ return key !== "" && Number.isSafeInteger(index) && index >= 0 && index < length && String(index) === key;
373
+ };
374
+ const pushDataProperty = (work, descriptor, key, path, actionRoot = false) => {
375
+ const nextPath = [...path, key];
376
+ if (!descriptor) return unsupported("Sparse array state", nextPath);
377
+ if (!descriptor.enumerable) return unsupported("Non-enumerable data state", nextPath);
378
+ if (!Object.prototype.hasOwnProperty.call(descriptor, "value")) return unsupported("Accessor-backed state", nextPath);
379
+ work.push({
380
+ actionRoot,
381
+ path: nextPath,
382
+ value: descriptor.value
548
383
  });
549
- transport.listen("update", async (options) => {
550
- let shouldFullSync = false;
551
- let allowLowerSequence = false;
552
- try {
553
- if (typeof options.sequence !== "number") shouldFullSync = true;
554
- else if (options.sequence <= internal.sequence) if (awaitingReconnectSync) {
555
- shouldFullSync = true;
556
- allowLowerSequence = true;
557
- } else if (options.sequence === 0 && internal.sequence > 0) {
558
- awaitingReconnectSync = true;
559
- reconnectSequenceBaseline = internal.sequence;
560
- shouldFullSync = true;
561
- allowLowerSequence = true;
562
- } else return;
563
- else if (options.sequence === internal.sequence + 1) {
564
- assertSafePatches(options.patches, "client transport update");
565
- internal.applyClientState(void 0, options.patches);
566
- internal.sequence = options.sequence;
567
- awaitingReconnectSync = false;
568
- reconnectSequenceBaseline = null;
569
- return;
570
- } else {
571
- shouldFullSync = true;
572
- allowLowerSequence = awaitingReconnectSync;
384
+ };
385
+ const assertSharedJsonWork = (work, isSliceStore = false) => {
386
+ const seen = /* @__PURE__ */ new WeakSet();
387
+ while (work.length) {
388
+ const { actionRoot = false, path, value } = work.pop();
389
+ if (value === null) continue;
390
+ switch (typeof value) {
391
+ case "string":
392
+ case "boolean": continue;
393
+ case "number":
394
+ if (!Number.isFinite(value)) unsupported("NaN or infinite number state", path);
395
+ if (Object.is(value, -0)) unsupported("Negative zero state", path);
396
+ continue;
397
+ case "bigint": unsupported("BigInt-valued state", path);
398
+ case "undefined": unsupported("Undefined-valued state", path);
399
+ case "function": unsupported("Function-valued state", path);
400
+ case "symbol": throw new TypeError(`Symbol-valued state is not supported in shared store mode because transport synchronization uses JSON. Found symbol value at ${formatPath(path)}.`);
401
+ default: break;
402
+ }
403
+ const object = value;
404
+ if (seen.has(object)) unsupported("Repeated state reference", path);
405
+ seen.add(object);
406
+ const descriptors = getDescriptors(object, path);
407
+ if (Array.isArray(object)) {
408
+ const prototype = getPrototype(object, path);
409
+ if (prototype !== Array.prototype) unsupported("Non-plain array state", path);
410
+ assertNoInheritedToJson(prototype, path);
411
+ const length = descriptors.length?.value;
412
+ if (!Number.isSafeInteger(length) || length < 0) unsupported("Invalid array state", path);
413
+ for (const key of Reflect.ownKeys(descriptors)) {
414
+ if (key === "length") continue;
415
+ if (typeof key === "symbol") throw new TypeError(`Symbol-keyed state is not supported in shared store mode because transport synchronization uses JSON and string action paths. Found symbol key at ${formatPath([...path, key])}.`);
416
+ if (!isArrayIndex(key, length)) unsupported("Non-index array property state", [...path, key]);
573
417
  }
574
- if (shouldFullSync) await fullSync(allowLowerSequence);
575
- } catch (error) {
576
- if (!shouldFullSync) try {
577
- await fullSync(awaitingReconnectSync);
578
- } catch (syncError) {
579
- if (process.env.NODE_ENV === "development") console.error(syncError);
418
+ for (let index = 0; index < length; index += 1) pushDataProperty(work, descriptors[index], index, path);
419
+ continue;
420
+ }
421
+ const prototype = getPrototype(object, path);
422
+ if (prototype !== Object.prototype && prototype !== null) unsupported("Non-plain object state", path);
423
+ assertNoInheritedToJson(prototype, path);
424
+ for (const key of Reflect.ownKeys(descriptors)) {
425
+ if (typeof key === "symbol") throw new TypeError(`Symbol-keyed state is not supported in shared store mode because transport synchronization uses JSON and string action paths. Found symbol key at ${formatPath([...path, key])}.`);
426
+ if (isUnsafeKey(key)) unsupported("Unsafe-keyed state", [...path, key]);
427
+ const descriptor = descriptors[key];
428
+ if (actionRoot && descriptor) {
429
+ const isDataProperty = Object.prototype.hasOwnProperty.call(descriptor, "value");
430
+ if (isDataProperty && typeof descriptor.value === "function") continue;
431
+ if (actionRoot === "initial" && (!isDataProperty || descriptor.value instanceof Computed)) continue;
580
432
  }
581
- if (process.env.NODE_ENV === "development") console.error(error);
433
+ pushDataProperty(work, descriptor, key, path, isSliceStore && path.length === 0 ? "initial" : false);
582
434
  }
583
- });
584
- return wrapStore(asyncClientStore, () => asyncClientStore.getState());
435
+ }
585
436
  };
586
- const emit = (store, internal, patches) => {
587
- const safePatches = sanitizePatches(patches, {
588
- source: "transport emit",
589
- warnOnDropped: true
590
- });
591
- if (store.transport && safePatches?.length) {
592
- validateSharedStateSerializable(internal.rootState);
593
- internal.sequence += 1;
594
- store.transport.emit({
595
- name: "update",
596
- respond: false
597
- }, {
598
- patches: safePatches,
599
- sequence: internal.sequence
600
- });
437
+ const assertSharedJsonValue = (root) => {
438
+ assertSharedJsonWork([{
439
+ path: [],
440
+ value: root
441
+ }]);
442
+ };
443
+ const validateSharedInitialState = (root, isSliceStore = false) => {
444
+ assertSharedJsonWork([{
445
+ actionRoot: isSliceStore ? false : "initial",
446
+ path: [],
447
+ value: root
448
+ }], isSliceStore);
449
+ };
450
+ const validateSharedReplacementSource = (root) => {
451
+ if (typeof root !== "object" || root === null || Array.isArray(root)) unsupported("Non-record replacement state", []);
452
+ assertSharedJsonWork([{
453
+ actionRoot: "replacement",
454
+ path: [],
455
+ value: root
456
+ }]);
457
+ };
458
+ const encodeSharedJson = (value) => {
459
+ assertSharedJsonValue(value);
460
+ const encoded = JSON.stringify(value);
461
+ if (typeof encoded !== "string") throw new TypeError("Shared transport value could not be encoded as JSON.");
462
+ return encoded;
463
+ };
464
+ const decodeSharedJson = (encoded) => {
465
+ if (typeof encoded !== "string") throw new TypeError("Shared transport payload must be a JSON string.");
466
+ let value;
467
+ try {
468
+ value = JSON.parse(encoded);
469
+ } catch {
470
+ throw new TypeError("Shared transport payload is not valid JSON.");
601
471
  }
472
+ assertSharedJsonValue(value);
473
+ return value;
602
474
  };
603
- const handleDraft = (store, internal) => {
604
- internal.rootState = internal.backupState;
605
- const [nextState, patches, inversePatches] = internal.finalizeDraft();
606
- if (store.share === "main") validateSharedStateSerializable(nextState);
607
- const safePatches = sanitizeCheckedPatches((store.patch ? store.patch({
608
- patches,
609
- inversePatches
610
- }) : {
611
- patches,
612
- inversePatches
613
- }).patches, "store.patch()");
614
- if (safePatches.length) {
615
- store.apply(internal.rootState, safePatches);
616
- emit(store, internal, safePatches);
475
+ const validateSharedActionPaths = (state, isSliceStore = false) => {
476
+ const actions = /* @__PURE__ */ new Set();
477
+ const work = [{
478
+ actionRoot: !isSliceStore,
479
+ path: [],
480
+ value: state
481
+ }];
482
+ const seen = /* @__PURE__ */ new WeakSet();
483
+ while (work.length) {
484
+ const { actionRoot, path, value } = work.pop();
485
+ if (typeof value !== "object" || value === null || seen.has(value)) continue;
486
+ seen.add(value);
487
+ const descriptors = getDescriptors(value, path);
488
+ for (const key of Reflect.ownKeys(descriptors)) {
489
+ if (typeof key === "symbol") throw new TypeError(`Symbol-keyed state is not supported in shared store mode because transport synchronization uses JSON and string action paths. Found symbol key at ${formatPath([...path, key])}.`);
490
+ const descriptor = descriptors[key];
491
+ if (descriptor && Object.prototype.hasOwnProperty.call(descriptor, "value")) {
492
+ const nextPath = [...path, key];
493
+ if (actionRoot && typeof descriptor.value === "function") {
494
+ actions.add(JSON.stringify(nextPath));
495
+ continue;
496
+ }
497
+ work.push({
498
+ actionRoot: isSliceStore && path.length === 0,
499
+ path: nextPath,
500
+ value: descriptor.value
501
+ });
502
+ }
503
+ }
617
504
  }
505
+ return actions;
618
506
  };
619
- //#endregion
620
- //#region packages/core/src/getInitialState.ts
621
- const isObject = (value) => typeof value === "object" && value !== null;
622
- const isStateFactory = (value) => typeof value === "function";
623
- const hasGetState = (value) => (typeof value === "object" || typeof value === "function") && value !== null && typeof value.getState === "function";
624
- const hasBindState = (value) => isObject(value) && !!value[bindSymbol];
625
- const formatInvalidStateMessage = (type, stateOrFn, key) => `Invalid state ${type} encountered in makeState: ${typeof key !== "undefined" ? `for key ${String(key)}, ` : ""}${typeof stateOrFn}`;
626
- const getInitialState = (store, createState, internal) => {
627
- const makeState = (stateOrFn, key) => {
628
- let state;
629
- if (isStateFactory(stateOrFn)) state = stateOrFn(store.setState, store.getState, store);
630
- else if (isObject(stateOrFn)) state = stateOrFn;
631
- else {
632
- if (process.env.NODE_ENV !== "production") throw new Error(formatInvalidStateMessage("value", stateOrFn, key));
633
- return {};
507
+ const validateSharedStateSerializable = assertSharedJsonValue;
508
+ const hasOwn = (value, key) => Object.prototype.hasOwnProperty.call(value, key);
509
+ const asRecord = (value, message) => {
510
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new TypeError(message);
511
+ return value;
512
+ };
513
+ const decodeMessage = (encoded, type) => {
514
+ const message = asRecord(decodeSharedJson(encoded), "Invalid transport message");
515
+ if (message.v !== 1 || message.type !== type) throw new TypeError("Invalid transport message");
516
+ return message;
517
+ };
518
+ const readEpoch = (message) => {
519
+ if (typeof message.epoch !== "string" || message.epoch.length === 0) throw new TypeError("Invalid transport epoch");
520
+ return message.epoch;
521
+ };
522
+ const readSequence = (message) => {
523
+ if (typeof message.sequence !== "number" || !Number.isSafeInteger(message.sequence) || message.sequence < 0) throw new TypeError("Invalid transport sequence");
524
+ return message.sequence;
525
+ };
526
+ const readAction = (value) => {
527
+ if (!Array.isArray(value) || value.length === 0 || value.some((key) => typeof key !== "string" || isUnsafePathSegment(key))) throw new TypeError("Invalid transport action");
528
+ return [...value];
529
+ };
530
+ const readPath = (value, { allowUnsafe = false } = {}) => {
531
+ if (!Array.isArray(value) || value.length === 0) throw new TypeError("Invalid transport patch path");
532
+ const path = [];
533
+ for (const segment of value) {
534
+ if (typeof segment !== "string" && (typeof segment !== "number" || !Number.isSafeInteger(segment) || segment < 0) || !allowUnsafe && isUnsafePathSegment(segment)) throw new TypeError("Invalid transport patch path");
535
+ path.push(segment);
536
+ }
537
+ return path;
538
+ };
539
+ const readPatches = (value, options = {}) => {
540
+ if (!Array.isArray(value)) throw new TypeError("Invalid transport patches");
541
+ return value.map((candidate) => {
542
+ const patch = asRecord(candidate, "Invalid transport patch");
543
+ const path = readPath(patch.path, { allowUnsafe: options.allowUnsafePaths });
544
+ if (patch.op === "remove") {
545
+ if (hasOwn(patch, "value")) throw new TypeError("Invalid remove patch");
546
+ return {
547
+ op: "remove",
548
+ path
549
+ };
634
550
  }
635
- if (hasGetState(state)) state = state.getState();
636
- else if (typeof state === "function") state = state();
637
- if (hasBindState(state)) {
638
- if (store.isSliceStore) throw new Error("Third-party state binding does not support Slices mode. Please inject a whole store instead.");
639
- const binder = state[bindSymbol];
640
- const rawState = binder.bind(state);
641
- binder.handleStore(store, rawState, state, internal, key);
642
- delete state[bindSymbol];
643
- return rawState;
551
+ if (patch.op !== "add" && patch.op !== "replace" || !hasOwn(patch, "value")) throw new TypeError("Invalid transport patch");
552
+ return {
553
+ op: patch.op,
554
+ path,
555
+ value: patch.value
556
+ };
557
+ });
558
+ };
559
+ const validateUpdatePatches = (patches) => {
560
+ assertSharedJsonValue(patches);
561
+ readPatches(patches, { allowUnsafePaths: true });
562
+ };
563
+ const encodeExecuteRequest = (action, args) => encodeSharedJson({
564
+ action: readAction([...action]),
565
+ args,
566
+ type: "execute",
567
+ v: 1
568
+ });
569
+ const decodeExecuteRequest = (encoded) => {
570
+ const message = decodeMessage(encoded, "execute");
571
+ if (!Array.isArray(message.args)) throw new TypeError("Invalid transport arguments");
572
+ return {
573
+ action: readAction(message.action),
574
+ args: [...message.args]
575
+ };
576
+ };
577
+ const encodeExecuteResponse = (response) => encodeSharedJson({
578
+ ...response,
579
+ type: "execute-result",
580
+ v: 1
581
+ });
582
+ const decodeExecuteResponse = (encoded) => {
583
+ const message = decodeMessage(encoded, "execute-result");
584
+ const base = {
585
+ epoch: readEpoch(message),
586
+ sequence: readSequence(message)
587
+ };
588
+ if (message.ok === true) return hasOwn(message, "value") ? {
589
+ ...base,
590
+ ok: true,
591
+ value: message.value
592
+ } : {
593
+ ...base,
594
+ ok: true
595
+ };
596
+ if (message.ok !== false || typeof message.error !== "string" || message.error.length === 0) throw new TypeError("Invalid execute response");
597
+ return {
598
+ ...base,
599
+ error: message.error,
600
+ ok: false
601
+ };
602
+ };
603
+ const encodeFullSyncRequest = () => encodeSharedJson({
604
+ type: "full-sync",
605
+ v: 1
606
+ });
607
+ const decodeFullSyncRequest = (encoded) => {
608
+ decodeMessage(encoded, "full-sync");
609
+ };
610
+ const encodeFullSyncResponse = (response) => encodeSharedJson({
611
+ ...response,
612
+ type: "full-sync-result",
613
+ v: 1
614
+ });
615
+ const decodeFullSyncResponse = (encoded) => {
616
+ const message = decodeMessage(encoded, "full-sync-result");
617
+ return {
618
+ epoch: readEpoch(message),
619
+ sequence: readSequence(message),
620
+ state: asRecord(message.state, "Invalid fullSync state")
621
+ };
622
+ };
623
+ const encodeUpdateMessage = (epoch, sequence, patches) => {
624
+ return encodeSharedJson({
625
+ epoch,
626
+ patches: readPatches(patches.map((patch) => patch.op === "remove" ? {
627
+ op: patch.op,
628
+ path: patch.path
629
+ } : {
630
+ op: patch.op,
631
+ path: patch.path,
632
+ value: patch.value
633
+ })),
634
+ sequence,
635
+ type: "update",
636
+ v: 1
637
+ });
638
+ };
639
+ const decodeUpdateMessage = (encoded) => {
640
+ const message = decodeMessage(encoded, "update");
641
+ return {
642
+ epoch: readEpoch(message),
643
+ patches: readPatches(message.patches),
644
+ sequence: readSequence(message)
645
+ };
646
+ };
647
+ //#endregion
648
+ //#region packages/core/src/wrapStore.ts
649
+ /**
650
+ * Convert a store object into Coaction's callable store shape.
651
+ *
652
+ * @remarks
653
+ * Framework bindings use this to attach selector-aware readers while
654
+ * preserving the underlying store API on the returned function object. Most
655
+ * applications should use a public `create` entry instead of calling
656
+ * `wrapStore()` directly. Framework authors import this helper from
657
+ * `coaction/local` or `coaction/adapter`.
658
+ */
659
+ const wrapStore = (store, getState = () => store.getState()) => {
660
+ const { name, ..._store } = store;
661
+ return Object.assign({ [name]: (...args) => getState(...args) }[name], _store);
662
+ };
663
+ //#endregion
664
+ //#region packages/core/src/asyncClientStore.ts
665
+ const clientApplyErrorMessage = "apply() cannot be called in the client store. Client stores are mirrors; use a store method to update the main store instead.";
666
+ const createAsyncClientStore = (createStore, options) => {
667
+ let createdStore;
668
+ try {
669
+ createdStore = createStore({ share: "client" });
670
+ } catch (error) {
671
+ return failTransportInitialization(options.clientTransport, error);
672
+ }
673
+ const { store, internal } = createdStore;
674
+ let canApplyClientState = false;
675
+ const previousAssertMutationAllowed = internal.assertMutationAllowed;
676
+ internal.assertMutationAllowed = (operation) => {
677
+ if (operation === "apply") {
678
+ if (!canApplyClientState) throw new Error(clientApplyErrorMessage);
679
+ canApplyClientState = false;
644
680
  }
645
- if (!isObject(state)) {
646
- if (process.env.NODE_ENV !== "production") throw new Error(formatInvalidStateMessage("result", state, key));
647
- return {};
681
+ previousAssertMutationAllowed?.(operation);
682
+ };
683
+ const baseApply = store.apply.bind(store);
684
+ store.apply = () => {
685
+ throw new Error(clientApplyErrorMessage);
686
+ };
687
+ internal.applyClientState = (...args) => {
688
+ canApplyClientState = true;
689
+ try {
690
+ baseApply(...args);
691
+ } finally {
692
+ canApplyClientState = false;
648
693
  }
649
- return state;
650
694
  };
651
- if (!store.isSliceStore) return makeState(createState);
652
- return getOwnEnumerableKeys(createState).reduce((stateTree, key) => {
653
- if (typeof key === "string" && isUnsafeKey(key)) return stateTree;
654
- setOwnEnumerable(stateTree, key, makeState(createState[key], key));
655
- return stateTree;
656
- }, {});
695
+ const isSharedWorker = typeof SharedWorker !== "undefined" && options.worker instanceof SharedWorker;
696
+ let transport;
697
+ try {
698
+ transport = options.worker ? (0, data_transport.createTransport)(isSharedWorker ? "SharedWorkerClient" : "WebWorkerClient", {
699
+ worker: options.worker,
700
+ prefix: store.name
701
+ }) : options.clientTransport;
702
+ } catch (error) {
703
+ return failStoreSetup(store, error);
704
+ }
705
+ if (!transport) return failStoreSetup(store, /* @__PURE__ */ new Error("transport is required"));
706
+ try {
707
+ store.transport = transport;
708
+ if (typeof transport.onConnect !== "function") throw new Error("transport.onConnect is required");
709
+ } catch (error) {
710
+ return failStoreSetup(store, error);
711
+ }
712
+ const destroyedMarker = Symbol("destroyed client transport");
713
+ let resolveDestroyed;
714
+ const destroyedSignal = new Promise((resolve) => {
715
+ resolveDestroyed = () => resolve(destroyedMarker);
716
+ });
717
+ const disposers = /* @__PURE__ */ new Set();
718
+ let destroyed = false;
719
+ let connectGeneration = 0;
720
+ let connectSync = null;
721
+ let syncTail = Promise.resolve();
722
+ const registerDisposer = (value) => {
723
+ if (typeof value === "function") disposers.add(value);
724
+ };
725
+ const cleanup = () => {
726
+ if (destroyed) return;
727
+ destroyed = true;
728
+ connectGeneration += 1;
729
+ resolveDestroyed();
730
+ const callbacks = [...disposers];
731
+ disposers.clear();
732
+ for (const dispose of callbacks) try {
733
+ dispose();
734
+ } catch (error) {
735
+ reportLifecycleError(error);
736
+ }
737
+ };
738
+ const awaitActive = async (value) => {
739
+ const result = await Promise.race([Promise.resolve(value), destroyedSignal]);
740
+ if (result === destroyedMarker) throw new Error("Client transport was destroyed");
741
+ return result;
742
+ };
743
+ internal.awaitClientTransport = awaitActive;
744
+ const applyFullSync = (state, epoch, sequence) => {
745
+ const previousEpoch = internal.transportEpoch;
746
+ const previousSequence = internal.sequence;
747
+ internal.transportEpoch = epoch;
748
+ internal.sequence = sequence;
749
+ try {
750
+ internal.applyClientState(state);
751
+ } catch (error) {
752
+ internal.transportEpoch = previousEpoch;
753
+ internal.sequence = previousSequence;
754
+ throw error;
755
+ }
756
+ };
757
+ const fullSync = (expectedEpoch, minimumSequence = 0, generation = connectGeneration) => {
758
+ const execute = async () => {
759
+ if (destroyed || generation !== connectGeneration) return;
760
+ const encoded = await awaitActive(transport.emit("fullSync", encodeFullSyncRequest()));
761
+ if (destroyed || generation !== connectGeneration) return;
762
+ const snapshot = decodeFullSyncResponse(encoded);
763
+ if (expectedEpoch && snapshot.epoch !== expectedEpoch) throw new Error("Mismatched fullSync epoch");
764
+ if (snapshot.sequence < minimumSequence) throw new Error("Stale fullSync sequence");
765
+ if (snapshot.epoch === internal.transportEpoch && snapshot.sequence < internal.sequence) return;
766
+ applyFullSync(snapshot.state, snapshot.epoch, snapshot.sequence);
767
+ };
768
+ const run = syncTail.then(execute, execute);
769
+ syncTail = run.then(() => void 0, () => void 0);
770
+ return run;
771
+ };
772
+ internal.syncClientState = (expectedEpoch, minimumSequence) => fullSync(expectedEpoch, minimumSequence);
773
+ const applyUpdate = (update) => {
774
+ const previousEpoch = internal.transportEpoch;
775
+ const previousSequence = internal.sequence;
776
+ internal.transportEpoch = update.epoch;
777
+ internal.sequence = update.sequence;
778
+ try {
779
+ internal.applyClientState(void 0, update.patches);
780
+ } catch (error) {
781
+ internal.transportEpoch = previousEpoch;
782
+ internal.sequence = previousSequence;
783
+ throw error;
784
+ }
785
+ };
786
+ const handleUpdate = async (encoded) => {
787
+ if (destroyed) return;
788
+ const generation = connectGeneration;
789
+ const update = decodeUpdateMessage(encoded);
790
+ if (connectSync) await connectSync;
791
+ if (destroyed || generation !== connectGeneration) return;
792
+ if (update.epoch !== internal.transportEpoch) await fullSync(update.epoch, 0, generation);
793
+ if (destroyed || generation !== connectGeneration) return;
794
+ if (update.epoch !== internal.transportEpoch) throw new Error("Mismatched update epoch");
795
+ if (update.sequence <= internal.sequence) return;
796
+ if (update.sequence === internal.sequence + 1) {
797
+ applyUpdate(update);
798
+ return;
799
+ }
800
+ await fullSync(update.epoch, update.sequence, generation);
801
+ };
802
+ internal.destroyCallbacks?.add(cleanup);
803
+ try {
804
+ registerDisposer(transport.listen("update", async (encoded) => {
805
+ try {
806
+ await handleUpdate(encoded);
807
+ } catch (error) {
808
+ if (!destroyed) {
809
+ try {
810
+ await fullSync();
811
+ } catch (syncError) {
812
+ reportLifecycleError(syncError);
813
+ }
814
+ reportLifecycleError(error);
815
+ }
816
+ }
817
+ }));
818
+ registerDisposer(transport.onConnect(() => {
819
+ const pending = fullSync(void 0, 0, ++connectGeneration).finally(() => {
820
+ if (connectSync === pending) connectSync = null;
821
+ });
822
+ connectSync = pending;
823
+ pending.catch(reportLifecycleError);
824
+ return pending;
825
+ }));
826
+ markStoreReady(store);
827
+ internal.assertAlive?.("store initialization");
828
+ } catch (error) {
829
+ return failStoreSetup(store, error);
830
+ }
831
+ return wrapStore(store, () => store.getState());
657
832
  };
658
- //#endregion
659
- //#region packages/core/src/getRawStateClientAction.ts
660
- const transportErrorMarker$1 = "__coactionTransportError__";
661
- const parseFullSyncState = (state) => {
662
- const parsed = JSON.parse(state);
663
- if (typeof parsed !== "object" || parsed === null) throw new Error("Invalid fullSync payload");
664
- return sanitizeReplacementState(parsed);
833
+ const emit = (store, internal, patches) => {
834
+ if (!store.transport || !patches?.length || !internal.transportEpoch) return;
835
+ const sequence = internal.sequence + 1;
836
+ const encoded = encodeUpdateMessage(internal.transportEpoch, sequence, patches);
837
+ internal.sequence = sequence;
838
+ try {
839
+ const pending = store.transport.emit({
840
+ name: "update",
841
+ respond: false
842
+ }, encoded);
843
+ Promise.resolve(pending).catch(reportLifecycleError);
844
+ } catch (error) {
845
+ reportLifecycleError(error);
846
+ }
665
847
  };
666
- const isTransportErrorEnvelope = (value) => {
667
- if (typeof value !== "object" || value === null) return false;
668
- return value[transportErrorMarker$1] === true && typeof value.message === "string";
848
+ //#endregion
849
+ //#region packages/core/src/global.ts
850
+ const getGlobal = () => {
851
+ let _global;
852
+ if (typeof window !== "undefined") _global = window;
853
+ else if (typeof global !== "undefined") _global = global;
854
+ else if (typeof self !== "undefined") _global = self;
855
+ else _global = {};
856
+ return _global;
669
857
  };
670
- const isLegacyTransportErrorEnvelope = (value) => {
671
- if (typeof value !== "object" || value === null) return false;
672
- const candidate = value;
673
- return typeof candidate.$$Error === "string" && candidate.$$Error.length > 0 && Object.keys(candidate).length === 1;
858
+ //#endregion
859
+ //#region packages/core/src/constant.ts
860
+ const WorkerType = getGlobal().SharedWorkerGlobalScope ? "SharedWorkerInternal" : globalThis.WorkerGlobalScope ? "WebWorkerInternal" : null;
861
+ const bindSymbol = Symbol("bind");
862
+ //#endregion
863
+ //#region packages/core/src/getRawStateClientAction.ts
864
+ /**
865
+ * The authority changed while a remote action was in flight, so its side-effect
866
+ * outcome cannot be determined safely from the current client mirror.
867
+ */
868
+ var ActionAuthorityChangedError = class extends Error {
869
+ code = "COACTION_ACTION_AUTHORITY_CHANGED";
870
+ outcome = "unknown";
871
+ constructor(action) {
872
+ super(`The authority changed while action '${action}' was in flight. The action may have completed on the previous authority; retry only if it is idempotent.`);
873
+ this.name = "ActionAuthorityChangedError";
874
+ }
674
875
  };
675
876
  const createClientAction = ({ clientExecuteSyncTimeoutMs, internal, key, store, sliceKey }) => {
676
877
  return (...args) => {
@@ -712,58 +913,237 @@ const createClientAction = ({ clientExecuteSyncTimeoutMs, internal, key, store,
712
913
  }
713
914
  };
714
915
  if (typeof sliceKey === "symbol") throw new Error("Symbol-keyed slice actions are not supported in client store mode.");
715
- const keys = typeof sliceKey !== "undefined" ? [String(sliceKey), key] : [key];
716
- return traceAction(() => store.transport.emit("execute", keys, args).then(async (response) => {
717
- const result = Array.isArray(response) ? response[0] : response;
718
- const sequence = Array.isArray(response) ? typeof response[1] === "number" ? response[1] : internal.sequence : internal.sequence;
719
- if (internal.sequence < sequence) {
720
- if (process.env.NODE_ENV === "development") console.warn(`The sequence of the action is not consistent.`, sequence, internal.sequence);
721
- await new Promise((resolve, reject) => {
722
- let settled = false;
723
- let unsubscribe = () => {};
724
- const timeoutRef = {};
725
- const cleanup = () => {
726
- unsubscribe();
727
- if (typeof timeoutRef.current !== "undefined") clearTimeout(timeoutRef.current);
728
- };
729
- const finishResolve = () => {
730
- if (settled) return;
731
- settled = true;
732
- cleanup();
733
- resolve();
734
- };
735
- const finishReject = (error) => {
736
- if (settled) return;
737
- settled = true;
738
- cleanup();
739
- reject(error);
740
- };
741
- unsubscribe = store.subscribe(() => {
742
- if (internal.sequence >= sequence) finishResolve();
743
- });
744
- timeoutRef.current = setTimeout(() => {
745
- store.transport.emit("fullSync").then((latest) => {
746
- if (typeof latest !== "object" || latest === null) throw new Error("Invalid fullSync payload");
747
- const next = latest;
748
- if (typeof next.state !== "string" || typeof next.sequence !== "number") throw new Error("Invalid fullSync payload");
749
- if (next.sequence >= sequence) {
750
- (internal.applyClientState ?? store.apply.bind(store))(parseFullSyncState(next.state));
751
- internal.sequence = next.sequence;
752
- finishResolve();
753
- return;
754
- }
755
- finishReject(/* @__PURE__ */ new Error(`Stale fullSync sequence: expected >= ${sequence}, got ${next.sequence}`));
756
- }).catch((error) => {
757
- finishReject(error);
916
+ const encoded = encodeExecuteRequest(typeof sliceKey === "undefined" ? [key] : [String(sliceKey), key], args);
917
+ const requestEpoch = internal.transportEpoch;
918
+ return traceAction(() => {
919
+ const emitted = store.transport.emit("execute", encoded);
920
+ return (internal.awaitClientTransport ? internal.awaitClientTransport(emitted) : emitted).then(async (payload) => {
921
+ const response = decodeExecuteResponse(payload);
922
+ internal.assertAlive?.(`action ${key}`);
923
+ const syncClientState = internal.syncClientState;
924
+ if (!syncClientState) throw new Error("Client fullSync is not available");
925
+ if (internal.transportEpoch !== requestEpoch && response.epoch !== internal.transportEpoch) throw new ActionAuthorityChangedError(key);
926
+ if (response.epoch !== internal.transportEpoch) {
927
+ await syncClientState(response.epoch, response.sequence);
928
+ internal.assertAlive?.(`action ${key}`);
929
+ } else if (response.sequence > internal.sequence) {
930
+ await new Promise((resolve, reject) => {
931
+ let settled = false;
932
+ let unsubscribe = () => {};
933
+ let timeout;
934
+ const cancel = () => finish(/* @__PURE__ */ new Error("Client transport was destroyed"));
935
+ const finish = (error) => {
936
+ if (settled) return;
937
+ settled = true;
938
+ unsubscribe();
939
+ internal.destroyCallbacks?.delete(cancel);
940
+ if (timeout) clearTimeout(timeout);
941
+ if (typeof error === "undefined") resolve();
942
+ else reject(error);
943
+ };
944
+ unsubscribe = store.subscribe(() => {
945
+ if (internal.transportEpoch === response.epoch && internal.sequence >= response.sequence) finish();
758
946
  });
759
- }, clientExecuteSyncTimeoutMs);
947
+ internal.destroyCallbacks?.add(cancel);
948
+ timeout = setTimeout(() => {
949
+ syncClientState(response.epoch, response.sequence).then(() => finish(), (error) => finish(error));
950
+ }, clientExecuteSyncTimeoutMs);
951
+ if (internal.transportEpoch === response.epoch && internal.sequence >= response.sequence) finish();
952
+ });
953
+ internal.assertAlive?.(`action ${key}`);
954
+ }
955
+ if (!response.ok) throw new Error(response.error);
956
+ return response.value;
957
+ });
958
+ });
959
+ };
960
+ };
961
+ //#endregion
962
+ //#region packages/core/src/handleMainTransport.ts
963
+ const publicErrorMessages = /* @__PURE__ */ new Set([
964
+ "Remote action is not allowed",
965
+ "The function is not found",
966
+ "Transport request is not authorized",
967
+ "Transport request was cancelled after store destroy"
968
+ ]);
969
+ const getErrorMessage = async (error, request, policy) => {
970
+ if (error instanceof Error && publicErrorMessages.has(error.message)) return error.message;
971
+ if (request && policy?.mapError) try {
972
+ const message = await policy.mapError(error, request);
973
+ if (typeof message === "string" && message) return message;
974
+ } catch (mapError) {
975
+ if (process.env.NODE_ENV === "development") console.error(mapError);
976
+ }
977
+ return "Remote action failed";
978
+ };
979
+ const handleMainTransport = (store, internal, storeTransport, workerType, checkEnablePatches, policy) => {
980
+ const transport = storeTransport ?? (workerType === "SharedWorkerInternal" || workerType === "WebWorkerInternal" ? (0, data_transport.createTransport)(workerType, { prefix: store.name }) : void 0);
981
+ if (!transport) return;
982
+ if (checkEnablePatches) throw new Error("enablePatches: true is required for the transport");
983
+ const epoch = uuid();
984
+ internal.transportEpoch = epoch;
985
+ let destroyed = false;
986
+ const disposers = /* @__PURE__ */ new Set();
987
+ const registerDisposer = (value) => {
988
+ if (typeof value === "function") disposers.add(value);
989
+ };
990
+ const cleanup = () => {
991
+ if (destroyed) return;
992
+ destroyed = true;
993
+ const callbacks = [...disposers];
994
+ disposers.clear();
995
+ for (const dispose of callbacks) try {
996
+ dispose();
997
+ } catch (error) {
998
+ if (process.env.NODE_ENV === "development") console.error(error);
999
+ }
1000
+ };
1001
+ const assertActive = () => {
1002
+ if (destroyed) throw new Error("Transport request was cancelled after store destroy");
1003
+ };
1004
+ store.transport = transport;
1005
+ internal.emitPatches = (patches) => emit(store, internal, patches);
1006
+ internal.destroyCallbacks?.add(cleanup);
1007
+ try {
1008
+ registerDisposer(transport.listen("execute", async (encoded) => {
1009
+ let policyRequest;
1010
+ try {
1011
+ assertActive();
1012
+ const request = decodeExecuteRequest(encoded);
1013
+ if (!internal.sharedActionPaths?.has(JSON.stringify(request.action))) throw new Error("Remote action is not allowed");
1014
+ if (policy?.allowedActions && !policy.allowedActions.some((allowed) => allowed.length === request.action.length && allowed.every((key, index) => key === request.action[index]))) throw new Error("Remote action is not allowed");
1015
+ policyRequest = {
1016
+ ...request,
1017
+ type: "execute"
1018
+ };
1019
+ if (policy?.authorize && await policy.authorize(policyRequest) !== true) throw new Error("Transport request is not authorized");
1020
+ assertActive();
1021
+ let action = store.getState();
1022
+ let receiver;
1023
+ for (const key of request.action) {
1024
+ if (isUnsafePathSegment(key) || typeof action !== "object" && typeof action !== "function" || action === null || !Object.prototype.hasOwnProperty.call(action, key)) throw new Error("The function is not found");
1025
+ receiver = action;
1026
+ action = action[key];
1027
+ }
1028
+ if (typeof action !== "function") throw new Error("The function is not found");
1029
+ const value = await Reflect.apply(action, receiver, request.args);
1030
+ assertActive();
1031
+ return encodeExecuteResponse({
1032
+ epoch,
1033
+ ok: true,
1034
+ sequence: internal.sequence,
1035
+ ...typeof value === "undefined" ? {} : { value }
1036
+ });
1037
+ } catch (error) {
1038
+ if (process.env.NODE_ENV === "development") console.error(error);
1039
+ return encodeExecuteResponse({
1040
+ epoch,
1041
+ error: await getErrorMessage(error, policyRequest, policy),
1042
+ ok: false,
1043
+ sequence: internal.sequence
760
1044
  });
761
1045
  }
762
- if (isTransportErrorEnvelope(result)) throw new Error(result.message);
763
- if (isLegacyTransportErrorEnvelope(result)) throw new Error(result.$$Error);
764
- return result;
765
1046
  }));
1047
+ registerDisposer(transport.listen("fullSync", async (encoded) => {
1048
+ assertActive();
1049
+ decodeFullSyncRequest(encoded);
1050
+ if (policy?.authorize && await policy.authorize({ type: "fullSync" }) !== true) throw new Error("Transport request is not authorized");
1051
+ assertActive();
1052
+ const state = internal.getTransportState?.() ?? internal.rootState;
1053
+ validateSharedStateSerializable(state);
1054
+ if (typeof state !== "object" || state === null || Array.isArray(state)) throw new TypeError("Shared store state must be a JSON object");
1055
+ return encodeFullSyncResponse({
1056
+ epoch,
1057
+ sequence: internal.sequence,
1058
+ state
1059
+ });
1060
+ }));
1061
+ } catch (error) {
1062
+ internal.destroyCallbacks?.delete(cleanup);
1063
+ cleanup();
1064
+ store.transport = void 0;
1065
+ try {
1066
+ transport.dispose?.();
1067
+ } catch (disposeError) {
1068
+ if (process.env.NODE_ENV === "development") console.error(disposeError);
1069
+ }
1070
+ throw error;
1071
+ }
1072
+ };
1073
+ //#endregion
1074
+ //#region packages/core/src/applyMiddlewares.ts
1075
+ const isStoreLike = (value) => {
1076
+ if (!value || typeof value !== "object") return false;
1077
+ const candidate = value;
1078
+ return typeof candidate.setState === "function" && typeof candidate.getState === "function" && typeof candidate.subscribe === "function" && typeof candidate.destroy === "function" && typeof candidate.apply === "function" && typeof candidate.getPureState === "function";
1079
+ };
1080
+ const applyMiddlewares = (store, middlewares) => {
1081
+ return middlewares.reduce((store, middleware, index) => {
1082
+ if (process.env.NODE_ENV === "development") {
1083
+ if (typeof middleware !== "function") throw new Error(`middlewares[${index}] should be a function`);
1084
+ }
1085
+ const nextStore = middleware(store);
1086
+ if (process.env.NODE_ENV === "development") {
1087
+ if (!isStoreLike(nextStore)) throw new Error(`middlewares[${index}] should return a store-like object`);
1088
+ }
1089
+ return nextStore;
1090
+ }, store);
1091
+ };
1092
+ //#endregion
1093
+ //#region packages/core/src/getInitialState.ts
1094
+ const isObject = (value) => typeof value === "object" && value !== null;
1095
+ const isStateFactory = (value) => typeof value === "function";
1096
+ const hasGetState = (value) => (typeof value === "object" || typeof value === "function") && value !== null && typeof value.getState === "function";
1097
+ const hasBindState = (value) => isObject(value) && !!value[bindSymbol];
1098
+ const formatInvalidStateMessage = (type, stateOrFn, key) => `Invalid state ${type} encountered in makeState: ${typeof key !== "undefined" ? `for key ${String(key)}, ` : ""}${typeof stateOrFn}`;
1099
+ const getInitialState = (store, createState, internal) => {
1100
+ const makeState = (stateOrFn, key) => {
1101
+ let state;
1102
+ if (isStateFactory(stateOrFn)) state = stateOrFn(store.setState, store.getState, store);
1103
+ else if (isObject(stateOrFn)) state = stateOrFn;
1104
+ else {
1105
+ if (process.env.NODE_ENV !== "production") throw new Error(formatInvalidStateMessage("value", stateOrFn, key));
1106
+ return {};
1107
+ }
1108
+ if (hasGetState(state)) state = state.getState();
1109
+ else if (typeof state === "function") state = state();
1110
+ if (hasBindState(state)) {
1111
+ if (store.isSliceStore) throw new Error("Third-party state binding does not support Slices mode. Please inject a whole store instead.");
1112
+ const binder = state[bindSymbol];
1113
+ const rawState = binder.bind(state);
1114
+ binder.handleStore(store, rawState, state, internal, key);
1115
+ delete state[bindSymbol];
1116
+ return rawState;
1117
+ }
1118
+ if (!isObject(state)) {
1119
+ if (process.env.NODE_ENV !== "production") throw new Error(formatInvalidStateMessage("result", state, key));
1120
+ return {};
1121
+ }
1122
+ return state;
766
1123
  };
1124
+ if (!store.isSliceStore) return makeState(createState);
1125
+ return getOwnEnumerableKeys(createState).reduce((stateTree, key) => {
1126
+ if (typeof key === "string" && isUnsafeKey(key)) return stateTree;
1127
+ setOwnEnumerable(stateTree, key, makeState(createState[key], key));
1128
+ return stateTree;
1129
+ }, {});
1130
+ };
1131
+ //#endregion
1132
+ //#region packages/core/src/handleDraft.ts
1133
+ const handleDraft = (store, internal) => {
1134
+ internal.rootState = internal.backupState;
1135
+ const [, patches, inversePatches] = internal.finalizeDraft();
1136
+ const safePatches = sanitizeCheckedPatches((store.patch ? store.patch({
1137
+ patches,
1138
+ inversePatches
1139
+ }) : {
1140
+ patches,
1141
+ inversePatches
1142
+ }).patches, "store.patch()");
1143
+ if (safePatches.length) {
1144
+ store.apply(internal.rootState, safePatches);
1145
+ internal.emitPatches?.(safePatches);
1146
+ }
767
1147
  };
768
1148
  //#endregion
769
1149
  //#region packages/core/src/getRawStateLocalAction.ts
@@ -852,77 +1232,63 @@ const createLocalAction = ({ fn, internal, key, options, store, sliceKey }) => {
852
1232
  };
853
1233
  };
854
1234
  //#endregion
855
- //#region packages/core/src/computed.ts
856
- const isObjectLike = (value) => typeof value === "object" && value !== null;
857
- var Computed = class {
858
- deps;
859
- fn;
860
- constructor(deps, fn) {
861
- this.deps = deps;
862
- this.fn = fn;
863
- }
864
- createGetter({ internal }) {
865
- const memoByReceiver = /* @__PURE__ */ new WeakMap();
866
- const lastArgs = /* @__PURE__ */ new WeakMap();
867
- const lastResult = /* @__PURE__ */ new WeakMap();
868
- const fallbackReceiver = {};
869
- const evaluate = (receiver) => {
870
- const args = this.deps(internal.module);
871
- if (!lastArgs.has(receiver) || !areShallowEqualWithArray(lastArgs.get(receiver), args)) lastResult.set(receiver, this.fn.apply(receiver, args));
872
- lastArgs.set(receiver, args);
873
- return lastResult.get(receiver);
874
- };
875
- return function() {
876
- const receiver = typeof this === "object" && this !== null ? this : fallbackReceiver;
877
- if (internal.isBatching) return evaluate(receiver);
878
- let accessor = memoByReceiver.get(receiver);
879
- if (!accessor) {
880
- accessor = (0, alien_signals.computed)(() => evaluate(receiver));
881
- memoByReceiver.set(receiver, accessor);
882
- }
883
- return accessor();
884
- };
885
- }
886
- };
887
- const createCachedGetter = (internal, getter) => {
888
- const accessors = /* @__PURE__ */ new WeakMap();
889
- const fallbackReceiver = {};
890
- return function() {
891
- const receiver = typeof this === "object" && this !== null ? this : fallbackReceiver;
892
- if (internal.isBatching) return getter.call(receiver);
893
- let accessor = accessors.get(receiver);
894
- if (!accessor) {
895
- accessor = (0, alien_signals.computed)(() => getter.call(receiver));
896
- accessors.set(receiver, accessor);
897
- }
898
- return accessor();
899
- };
900
- };
901
- const createTrackedStateReader = (internal, read, initialValue) => {
902
- const slotSignal = (0, alien_signals.signal)(initialValue);
903
- const slotVersionSignal = (0, alien_signals.signal)(0);
904
- let slotVersion = 0;
905
- (internal.signalSlots ??= /* @__PURE__ */ new Set()).add({ refresh: () => {
906
- const nextValue = read();
907
- slotSignal(nextValue);
908
- if (internal.mutableInstance && isObjectLike(nextValue)) {
909
- slotVersion += 1;
910
- slotVersionSignal(slotVersion);
1235
+ //#region packages/core/src/immutableState.ts
1236
+ const isImmutableStateObject = (value) => {
1237
+ if (typeof value !== "object" || value === null) return false;
1238
+ if (Array.isArray(value)) return true;
1239
+ const prototype = Object.getPrototypeOf(value);
1240
+ return prototype === Object.prototype || prototype === null;
1241
+ };
1242
+ const getImmutableStateSnapshot = (value, cache) => {
1243
+ if (!isImmutableStateObject(value)) return value;
1244
+ const cached = cache.get(value);
1245
+ if (cached) return cached;
1246
+ const isArray = Array.isArray(value);
1247
+ const snapshot = isArray ? new Array(value.length) : Object.create(Object.getPrototypeOf(value));
1248
+ cache.set(value, snapshot);
1249
+ for (const key of Reflect.ownKeys(value)) {
1250
+ if (isArray && key === "length") continue;
1251
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
1252
+ if (Object.prototype.hasOwnProperty.call(descriptor, "value")) descriptor.value = getImmutableStateSnapshot(descriptor.value, cache);
1253
+ Object.defineProperty(snapshot, key, descriptor);
1254
+ }
1255
+ return Object.freeze(snapshot);
1256
+ };
1257
+ const createImmutableSnapshotPatches = (patches, cache) => patches.map((patch) => Object.prototype.hasOwnProperty.call(patch, "value") ? {
1258
+ ...patch,
1259
+ value: getImmutableStateSnapshot(patch.value, cache)
1260
+ } : patch);
1261
+ const finalizeImmutableStateSnapshot = (state, snapshot, patches, cache, sources) => {
1262
+ const mapPair = (value, snapshotValue) => {
1263
+ if (isImmutableStateObject(value) && isImmutableStateObject(snapshotValue)) {
1264
+ cache.set(value, snapshotValue);
1265
+ sources?.set(snapshotValue, value);
911
1266
  }
912
- } });
913
- return () => {
914
- const currentValue = slotSignal();
915
- if (internal.mutableInstance && isObjectLike(currentValue)) slotVersionSignal();
916
- return read();
917
1267
  };
1268
+ mapPair(state, snapshot);
1269
+ for (const patch of patches) {
1270
+ let value = state;
1271
+ let snapshotValue = snapshot;
1272
+ const ancestors = [];
1273
+ if (isImmutableStateObject(snapshotValue)) ancestors.push(snapshotValue);
1274
+ for (const key of patch.path) {
1275
+ if (!isImmutableStateObject(value) || !isImmutableStateObject(snapshotValue)) break;
1276
+ value = value[key];
1277
+ snapshotValue = snapshotValue[key];
1278
+ mapPair(value, snapshotValue);
1279
+ if (isImmutableStateObject(snapshotValue)) ancestors.push(snapshotValue);
1280
+ }
1281
+ for (let index = ancestors.length - 1; index >= 0; index -= 1) if (!Object.isFrozen(ancestors[index])) Object.freeze(ancestors[index]);
1282
+ }
918
1283
  };
919
- const refreshSignalSlots = (internal) => {
920
- if (!internal.signalSlots?.size) return;
921
- (0, alien_signals.startBatch)();
922
- try {
923
- internal.signalSlots.forEach((slot) => slot.refresh());
924
- } finally {
925
- (0, alien_signals.endBatch)();
1284
+ const indexImmutableStateSnapshot = (state, snapshot, sources, seen = /* @__PURE__ */ new WeakSet()) => {
1285
+ if (!isImmutableStateObject(state) || !isImmutableStateObject(snapshot) || seen.has(snapshot)) return;
1286
+ seen.add(snapshot);
1287
+ sources.set(snapshot, state);
1288
+ for (const key of Reflect.ownKeys(state)) {
1289
+ const stateDescriptor = Object.getOwnPropertyDescriptor(state, key);
1290
+ const snapshotDescriptor = Object.getOwnPropertyDescriptor(snapshot, key);
1291
+ if (stateDescriptor && snapshotDescriptor && Object.prototype.hasOwnProperty.call(stateDescriptor, "value") && Object.prototype.hasOwnProperty.call(snapshotDescriptor, "value")) indexImmutableStateSnapshot(stateDescriptor.value, snapshotDescriptor.value, sources, seen);
926
1292
  }
927
1293
  };
928
1294
  //#endregion
@@ -932,12 +1298,6 @@ const assertImmutableStateMutationAllowed = (internal) => {
932
1298
  throw new Error("Direct state mutation is not allowed in immutable Coaction stores. Wrap mutations in set(() => { ... }).");
933
1299
  };
934
1300
  const readonlyProxyCache = /* @__PURE__ */ new WeakMap();
935
- const isReadonlyProxyable = (value) => {
936
- if (typeof value !== "object" || value === null) return false;
937
- if (Array.isArray(value)) return true;
938
- const prototype = Object.getPrototypeOf(value);
939
- return prototype === Object.prototype || prototype === null;
940
- };
941
1301
  const getReadonlyProxyCache = (internal) => {
942
1302
  let cache = readonlyProxyCache.get(internal);
943
1303
  if (!cache) {
@@ -954,7 +1314,12 @@ const getPublicStateObject = (internal, value, sliceKey) => {
954
1314
  if (rootState[sliceKey] === value) return module[sliceKey];
955
1315
  };
956
1316
  const toReadonlyStateValue = (internal, value, sliceKey) => {
957
- if (internal.mutableInstance || internal.isBatching || !isReadonlyProxyable(value)) return value;
1317
+ if (internal.mutableInstance || internal.isBatching || !isImmutableStateObject(value)) return value;
1318
+ if (internal.computedReadDepth) {
1319
+ const cache = internal.computedSnapshotCache ??= /* @__PURE__ */ new WeakMap();
1320
+ if (isImmutableStateObject(internal.rootState) && !cache.has(internal.rootState)) getImmutableStateSnapshot(internal.rootState, cache);
1321
+ return getImmutableStateSnapshot(value, cache);
1322
+ }
958
1323
  const publicValue = getPublicStateObject(internal, value, sliceKey);
959
1324
  if (publicValue) return publicValue;
960
1325
  const cache = getReadonlyProxyCache(internal);
@@ -984,6 +1349,18 @@ const toReadonlyStateValue = (internal, value, sliceKey) => {
984
1349
  cache.set(value, proxy);
985
1350
  return proxy;
986
1351
  };
1352
+ const toPublicComputedValue = (internal, value, sliceKey) => {
1353
+ if (!isImmutableStateObject(value)) return value;
1354
+ const rootSnapshot = internal.computedSnapshotCache?.get(internal.rootState);
1355
+ const sources = internal.computedSnapshotSources ??= /* @__PURE__ */ new WeakMap();
1356
+ let source = sources.get(value);
1357
+ if (!source && Object.isFrozen(value) && rootSnapshot) {
1358
+ indexImmutableStateSnapshot(internal.rootState, rootSnapshot, sources);
1359
+ source = sources.get(value);
1360
+ }
1361
+ if (source) internal.computedIdentityRequired = true;
1362
+ return source ? toReadonlyStateValue(internal, source, sliceKey) : value;
1363
+ };
987
1364
  const prepareStateDescriptor = ({ descriptor, initialStateSeen, internal, key, rawState, sliceKey }) => {
988
1365
  const isComputed = descriptor.value instanceof Computed;
989
1366
  const readStateValue = () => typeof sliceKey !== "undefined" ? internal.rootState[sliceKey][key] : internal.rootState[key];
@@ -1004,7 +1381,10 @@ const prepareStateDescriptor = ({ descriptor, initialStateSeen, internal, key, r
1004
1381
  });
1005
1382
  if (isComputed) {
1006
1383
  if (internal.mutableInstance) throw new Error("Computed is not supported with mutable instance");
1007
- descriptor.get = descriptor.value.createGetter({ internal });
1384
+ const getComputed = descriptor.value.createGetter({ internal });
1385
+ descriptor.get = function() {
1386
+ return toPublicComputedValue(internal, getComputed.call(this), sliceKey);
1387
+ };
1008
1388
  } else if (typeof sliceKey !== "undefined") {
1009
1389
  const read = createTrackedStateReader(internal, readStateValue, initialValue);
1010
1390
  descriptor.get = () => toReadonlyStateValue(internal, read(), sliceKey);
@@ -1023,9 +1403,12 @@ const prepareStateDescriptor = ({ descriptor, initialStateSeen, internal, key, r
1023
1403
  delete descriptor.value;
1024
1404
  delete descriptor.writable;
1025
1405
  };
1026
- const prepareAccessorDescriptor = ({ descriptor, internal }) => {
1406
+ const prepareAccessorDescriptor = ({ descriptor, internal, sliceKey }) => {
1027
1407
  if (internal.mutableInstance || typeof descriptor.get !== "function") return;
1028
- descriptor.get = createCachedGetter(internal, descriptor.get);
1408
+ const getComputed = createCachedGetter(internal, descriptor.get);
1409
+ descriptor.get = function() {
1410
+ return toPublicComputedValue(internal, getComputed.call(this), sliceKey);
1411
+ };
1029
1412
  };
1030
1413
  //#endregion
1031
1414
  //#region packages/core/src/getRawState.ts
@@ -1040,7 +1423,7 @@ const getClientExecuteSyncTimeoutMs = (options) => {
1040
1423
  if (!Number.isFinite(timeout) || timeout < 0) throw new Error("executeSyncTimeoutMs must be a finite number greater than or equal to 0");
1041
1424
  return timeout;
1042
1425
  };
1043
- const getRawState = (store, internal, initialState, options) => {
1426
+ const getRawState = (store, internal, initialState, options, createClientAction) => {
1044
1427
  const clientExecuteSyncTimeoutMs = getClientExecuteSyncTimeoutMs(options);
1045
1428
  const rawState = {};
1046
1429
  const handle = (_rawState, _initialState, sliceKey) => {
@@ -1059,7 +1442,8 @@ const getRawState = (store, internal, initialState, options) => {
1059
1442
  if (!Object.prototype.hasOwnProperty.call(descriptor, "value")) {
1060
1443
  prepareAccessorDescriptor({
1061
1444
  descriptor,
1062
- internal
1445
+ internal,
1446
+ sliceKey
1063
1447
  });
1064
1448
  return;
1065
1449
  }
@@ -1077,6 +1461,7 @@ const getRawState = (store, internal, initialState, options) => {
1077
1461
  }
1078
1462
  if (store.share === "client") {
1079
1463
  if (typeof key !== "string") return;
1464
+ if (!createClientAction) throw new Error("Client action runtime is not configured");
1080
1465
  descriptor.value = createClientAction({
1081
1466
  clientExecuteSyncTimeoutMs,
1082
1467
  internal,
@@ -1111,8 +1496,11 @@ const getRawState = (store, internal, initialState, options) => {
1111
1496
  //#endregion
1112
1497
  //#region packages/core/src/handleState.ts
1113
1498
  const handleState = (store, internal, options) => {
1499
+ let defaultResultValidated = false;
1114
1500
  const defaultUpdater = (next) => {
1501
+ defaultResultValidated = false;
1115
1502
  const merge = (_next = next) => {
1503
+ if (_next !== next) internal.validateState?.(_next);
1116
1504
  assertKnownStateShape(_next, internal.rootState, internal.stateSchema, store.isSliceStore);
1117
1505
  mergeObject(internal.rootState, _next, store.isSliceStore);
1118
1506
  };
@@ -1129,9 +1517,11 @@ const handleState = (store, internal, options) => {
1129
1517
  internal.actMutable(() => {
1130
1518
  fn.apply(null);
1131
1519
  });
1520
+ defaultResultValidated = true;
1132
1521
  return [];
1133
1522
  }
1134
1523
  fn.apply(null);
1524
+ defaultResultValidated = true;
1135
1525
  return [];
1136
1526
  }
1137
1527
  internal.backupState = internal.rootState;
@@ -1143,22 +1533,27 @@ const handleState = (store, internal, options) => {
1143
1533
  return fn.apply(null);
1144
1534
  }, { enablePatches: true });
1145
1535
  assertKnownStateShape(result[0], internal.backupState, internal.stateSchema, store.isSliceStore, { requireSliceRoots: true });
1146
- if (store.share === "main") validateSharedStateSerializable(result[0]);
1536
+ internal.validateState?.(internal.getTransportState?.() ?? result[0]);
1147
1537
  patches = result[1];
1148
1538
  inversePatches = result[2];
1149
1539
  } finally {
1150
1540
  internal.rootState = internal.backupState;
1151
1541
  }
1152
- const finalPatches = store.patch ? store.patch({
1542
+ const patch = store.patch;
1543
+ const finalPatches = patch ? patch({
1153
1544
  patches,
1154
1545
  inversePatches
1155
1546
  }) : {
1156
1547
  patches,
1157
1548
  inversePatches
1158
1549
  };
1550
+ if (!patch) internal.validatePatches?.(finalPatches.patches);
1159
1551
  const safePatches = sanitizeCheckedPatches(finalPatches.patches, "store.patch()");
1160
1552
  const safeInversePatches = sanitizeCheckedPatches(finalPatches.inversePatches, "store.patch() inverse patches");
1161
- if (safePatches.length) store.apply(internal.rootState, safePatches);
1553
+ if (safePatches.length) {
1554
+ defaultResultValidated = internal.applyValidatedPatches?.(internal.rootState, safePatches, !patch) ?? false;
1555
+ if (!internal.applyValidatedPatches) store.apply(internal.rootState, safePatches);
1556
+ } else defaultResultValidated = true;
1162
1557
  return [
1163
1558
  internal.rootState,
1164
1559
  safePatches,
@@ -1171,12 +1566,19 @@ const handleState = (store, internal, options) => {
1171
1566
  if (store.share === "client") throw new Error(`setState() cannot be called in the client store. To update the state, please trigger a store method with setState() instead.`);
1172
1567
  if (internal.isBatching) throw new Error("setState cannot be called within the updater");
1173
1568
  if (next === null) return [];
1174
- if (typeof next === "object") assertKnownStateShape(next, internal.rootState, internal.stateSchema, store.isSliceStore);
1569
+ if (typeof next === "object") {
1570
+ internal.validateState?.(next);
1571
+ assertKnownStateShape(next, internal.rootState, internal.stateSchema, store.isSliceStore);
1572
+ }
1175
1573
  internal.isBatching = true;
1176
1574
  if (!store.share && !options.enablePatches && !internal.mutableInstance && updater === defaultUpdater) try {
1177
1575
  if (typeof next === "function") try {
1178
1576
  internal.backupState = internal.rootState;
1179
- const nextState = (0, mutative.create)(internal.rootState, (draft) => {
1577
+ const snapshotCache = internal.computedSnapshotCache;
1578
+ const snapshotSources = internal.computedIdentityRequired ? internal.computedSnapshotSources : void 0;
1579
+ const snapshot = snapshotCache?.get(internal.rootState);
1580
+ const updateSnapshot = Boolean(snapshot && snapshotCache);
1581
+ const produced = (0, mutative.create)(internal.rootState, (draft) => {
1180
1582
  internal.rootState = draft;
1181
1583
  const returnValue = next(internal.module);
1182
1584
  if (returnValue instanceof Promise) {
@@ -1187,8 +1589,13 @@ const handleState = (store, internal, options) => {
1187
1589
  assertKnownStateShape(returnValue, internal.rootState, internal.stateSchema, store.isSliceStore);
1188
1590
  mergeObject(internal.rootState, returnValue, store.isSliceStore);
1189
1591
  }
1190
- });
1592
+ }, { enablePatches: updateSnapshot });
1593
+ const nextState = updateSnapshot ? produced[0] : produced;
1191
1594
  assertKnownStateShape(nextState, internal.backupState, internal.stateSchema, store.isSliceStore, { requireSliceRoots: true });
1595
+ if (updateSnapshot) {
1596
+ const patches = produced[1];
1597
+ finalizeImmutableStateSnapshot(nextState, (0, mutative.apply)(snapshot, createImmutableSnapshotPatches(patches, snapshotCache)), patches, snapshotCache, snapshotSources);
1598
+ }
1192
1599
  internal.rootState = nextState;
1193
1600
  } catch (error) {
1194
1601
  internal.rootState = internal.backupState;
@@ -1226,7 +1633,7 @@ const handleState = (store, internal, options) => {
1226
1633
  if (isDrafted) handleDraft(store, internal);
1227
1634
  result = updater(next);
1228
1635
  if (internal.mutableInstance) assertKnownStateShape(internal.rootState, internal.backupState ?? internal.rootState, internal.stateSchema, store.isSliceStore, { requireSliceRoots: true });
1229
- if (store.share === "main") validateSharedStateSerializable(internal.rootState);
1636
+ if (!(updater === defaultUpdater && defaultResultValidated)) internal.validateState?.(internal.getTransportState?.() ?? internal.rootState);
1230
1637
  if (isDrafted) {
1231
1638
  internal.backupState = internal.rootState;
1232
1639
  const [draft, finalize] = (0, mutative.create)(internal.rootState, { enablePatches: true });
@@ -1236,12 +1643,16 @@ const handleState = (store, internal, options) => {
1236
1643
  } finally {
1237
1644
  internal.isBatching = false;
1238
1645
  }
1239
- if (result?.length) result = [
1240
- result[0],
1241
- sanitizeCheckedPatches(result[1], "setState updater result"),
1242
- sanitizeCheckedPatches(result[2], "setState updater inverse result")
1243
- ];
1244
- emit(store, internal, result?.[1]);
1646
+ const trustedDefaultResult = updater === defaultUpdater && defaultResultValidated;
1647
+ if (result?.length && !trustedDefaultResult) {
1648
+ internal.validatePatches?.(result[1]);
1649
+ result = [
1650
+ result[0],
1651
+ sanitizeCheckedPatches(result[1], "setState updater result"),
1652
+ sanitizeCheckedPatches(result[2], "setState updater inverse result")
1653
+ ];
1654
+ }
1655
+ if (result?.[1]) internal.emitPatches?.(result[1]);
1245
1656
  return result;
1246
1657
  };
1247
1658
  const getState = (deps, selector) => deps && selector ? new Computed(deps, selector) : internal.module;
@@ -1251,95 +1662,183 @@ const handleState = (store, internal, options) => {
1251
1662
  };
1252
1663
  };
1253
1664
  //#endregion
1254
- //#region packages/core/src/applyMiddlewares.ts
1255
- const isStoreLike = (value) => {
1256
- if (!value || typeof value !== "object") return false;
1257
- const candidate = value;
1258
- return typeof candidate.setState === "function" && typeof candidate.getState === "function" && typeof candidate.subscribe === "function" && typeof candidate.destroy === "function" && typeof candidate.apply === "function" && typeof candidate.getPureState === "function";
1259
- };
1260
- const applyMiddlewares = (store, middlewares) => {
1261
- return middlewares.reduce((store, middleware, index) => {
1262
- if (process.env.NODE_ENV === "development") {
1263
- if (typeof middleware !== "function") throw new Error(`middlewares[${index}] should be a function`);
1264
- }
1265
- const nextStore = middleware(store);
1266
- if (process.env.NODE_ENV === "development") {
1267
- if (!isStoreLike(nextStore)) throw new Error(`middlewares[${index}] should return a store-like object`);
1268
- }
1269
- return nextStore;
1270
- }, store);
1271
- };
1272
- //#endregion
1273
- //#region packages/core/src/handleMainTransport.ts
1274
- const getErrorMessage = (error) => {
1275
- if (error instanceof Error) return error.message;
1276
- return String(error);
1665
+ //#region packages/core/src/storeFactory.ts
1666
+ const namespaceMap = /* @__PURE__ */ new Map();
1667
+ let hasWarnedAmbiguousFunctionMap = false;
1668
+ const warnAmbiguousFunctionMap = () => {
1669
+ if (hasWarnedAmbiguousFunctionMap || process.env.NODE_ENV === "production" || process.env.NODE_ENV === "test") return;
1670
+ hasWarnedAmbiguousFunctionMap = true;
1671
+ console.warn([
1672
+ `sliceMode: 'auto' inferred slices from an object of functions.`,
1673
+ `This shape is ambiguous with a single store that only contains methods.`,
1674
+ `Use create({ ping() {} }, { sliceMode: 'single' }) for a plain method store,`,
1675
+ `or create({ counter: (set) => ({ count: 0 }) }, { sliceMode: 'slices' }) for slices.`
1676
+ ].join(" "));
1277
1677
  };
1278
- const transportErrorMarker = "__coactionTransportError__";
1279
- const handleMainTransport = (store, internal, storeTransport, workerType, checkEnablePatches) => {
1280
- const transport = storeTransport ?? (workerType === "SharedWorkerInternal" || workerType === "WebWorkerInternal" ? (0, data_transport.createTransport)(workerType, { prefix: store.name }) : void 0);
1281
- if (!transport) return;
1282
- if (typeof transport.onConnect !== "function") throw new Error("transport.onConnect is required");
1283
- if (checkEnablePatches) throw new Error(`enablePatches: true is required for the transport`);
1284
- transport.listen("execute", async (keys, args) => {
1285
- let base = store.getState();
1286
- try {
1287
- for (const key of keys) {
1288
- if (isUnsafePathSegment(key) || typeof base !== "object" && typeof base !== "function" || base === null || !Object.prototype.hasOwnProperty.call(base, key)) throw new Error("The function is not found");
1289
- const obj = base;
1290
- base = base[key];
1291
- if (typeof base === "function") base = base.bind(obj);
1678
+ const createStore = (createState, options, runtime = {}) => {
1679
+ const { share, validatePatches, validateReplacementSource, validateState } = runtime;
1680
+ const store = {};
1681
+ const internal = {
1682
+ sequence: 0,
1683
+ isBatching: false,
1684
+ listeners: /* @__PURE__ */ new Set(),
1685
+ destroyCallbacks: /* @__PURE__ */ new Set(),
1686
+ validatePatches,
1687
+ validateReplacementSource,
1688
+ validateState
1689
+ };
1690
+ internal.notifyStateChange = () => {
1691
+ refreshSignalSlots(internal);
1692
+ internal.listeners.forEach((listener) => listener());
1693
+ };
1694
+ const name = options.name ?? "default";
1695
+ const shouldTrackName = share === "main" && process.env.NODE_ENV !== "test";
1696
+ const releaseStoreName = () => {
1697
+ if (shouldTrackName) namespaceMap.delete(name);
1698
+ };
1699
+ if (shouldTrackName) {
1700
+ if (namespaceMap.get(name)) throw new Error(`Store name '${name}' is not unique.`);
1701
+ namespaceMap.set(name, true);
1702
+ }
1703
+ try {
1704
+ const { setState, getState } = handleState(store, internal, options);
1705
+ const subscribe = (listener) => {
1706
+ internal.assertAlive?.("subscribe");
1707
+ internal.listeners.add(listener);
1708
+ return () => internal.listeners.delete(listener);
1709
+ };
1710
+ let isDestroyed = false;
1711
+ internal.assertAlive = (operation) => {
1712
+ if (isDestroyed) throw new Error(`${operation} cannot be called after store.destroy().`);
1713
+ };
1714
+ const destroy = () => {
1715
+ if (isDestroyed) return;
1716
+ isDestroyed = true;
1717
+ let firstError;
1718
+ const callbacks = [...internal.destroyCallbacks ?? []];
1719
+ internal.destroyCallbacks?.clear();
1720
+ for (const callback of callbacks) try {
1721
+ callback();
1722
+ } catch (error) {
1723
+ firstError ??= error;
1292
1724
  }
1293
- if (typeof base !== "function") throw new Error("The function is not found");
1294
- return [await base(...args), internal.sequence];
1295
- } catch (error) {
1296
- if (process.env.NODE_ENV === "development") console.error(error);
1297
- return [{
1298
- [transportErrorMarker]: true,
1299
- message: getErrorMessage(error)
1300
- }, internal.sequence];
1725
+ internal.listeners.clear();
1726
+ try {
1727
+ store.transport?.dispose();
1728
+ } catch (error) {
1729
+ firstError ??= error;
1730
+ } finally {
1731
+ releaseStoreName();
1732
+ }
1733
+ if (firstError) throw firstError;
1734
+ };
1735
+ const applyState = (state, patches, prepared = false, skipFinalValidation = false) => {
1736
+ internal.assertAlive?.("apply");
1737
+ internal.assertMutationAllowed?.("apply");
1738
+ if (patches && !prepared) validatePatches?.(patches);
1739
+ if (!prepared) assertSafePatches(patches, "store.apply()");
1740
+ const safePatches = prepared ? patches : sanitizePatches(patches);
1741
+ const baseState = state === internal.module ? internal.rootState : state;
1742
+ if (baseState !== internal.rootState) validateReplacementSource?.(baseState);
1743
+ const appliedState = safePatches ? (0, mutative.apply)(baseState, safePatches) : baseState;
1744
+ const nextState = prepared ? appliedState : sanitizeReplacementState(appliedState);
1745
+ if (!skipFinalValidation) {
1746
+ assertKnownStateShape(nextState, internal.rootState, internal.stateSchema, store.isSliceStore, { requireSliceRoots: true });
1747
+ validateState?.(internal.getTransportState?.() ?? nextState);
1748
+ }
1749
+ internal.rootState = nextState;
1750
+ refreshSignalSlots(internal);
1751
+ if (internal.updateImmutable) internal.updateImmutable(internal.rootState);
1752
+ else internal.listeners.forEach((listener) => listener());
1753
+ };
1754
+ const apply = (state = internal.rootState, patches) => applyState(state, patches);
1755
+ internal.applyValidatedPatches = (state, patches, skipFinalValidation) => {
1756
+ if (store.apply !== apply) {
1757
+ store.apply(state, patches);
1758
+ return false;
1759
+ }
1760
+ applyState(state, patches, true, skipFinalValidation);
1761
+ return true;
1762
+ };
1763
+ const getPureState = () => internal.rootState;
1764
+ const isFunctionMapObject = () => {
1765
+ if (typeof createState !== "object" || createState === null) return false;
1766
+ const values = getOwnEnumerableKeys(createState).map((key) => createState[key]);
1767
+ return values.length > 0 && values.every((value) => typeof value === "function");
1768
+ };
1769
+ const getIsSliceStore = () => {
1770
+ const sliceMode = options.sliceMode ?? "auto";
1771
+ if (sliceMode === "single") return false;
1772
+ if (sliceMode === "slices") {
1773
+ if (!isFunctionMapObject()) throw new Error(`sliceMode: 'slices' requires createState to be an object of slice functions.`);
1774
+ return true;
1775
+ }
1776
+ if (isFunctionMapObject()) {
1777
+ warnAmbiguousFunctionMap();
1778
+ return true;
1779
+ }
1780
+ return false;
1781
+ };
1782
+ const isSliceStore = getIsSliceStore();
1783
+ Object.assign(store, {
1784
+ name,
1785
+ share: share ?? false,
1786
+ setState,
1787
+ getState,
1788
+ subscribe,
1789
+ destroy,
1790
+ apply,
1791
+ isSliceStore,
1792
+ getPureState
1793
+ });
1794
+ const middlewareStore = applyMiddlewares(store, options.middlewares ?? []);
1795
+ if (middlewareStore !== store) Object.assign(store, middlewareStore);
1796
+ internal.assertAlive?.("store initialization");
1797
+ if (validatePatches && store.patch) {
1798
+ const patch = store.patch.bind(store);
1799
+ store.patch = (options) => {
1800
+ const result = patch(options);
1801
+ validatePatches(result.patches);
1802
+ return result;
1803
+ };
1301
1804
  }
1302
- });
1303
- transport.listen("fullSync", async () => {
1304
- validateSharedStateSerializable(internal.rootState);
1805
+ const initialState = getInitialState(store, createState, internal);
1806
+ internal.assertAlive?.("store initialization");
1807
+ internal.sharedActionPaths = runtime.collectActionPaths?.(initialState, store.isSliceStore);
1808
+ if (!internal.getTransportState) runtime.validateInitialState?.(initialState, store.isSliceStore);
1809
+ store.getInitialState = () => initialState;
1810
+ internal.rootState = getRawState(store, internal, initialState, options, runtime.clientAction);
1811
+ if (validatePatches && store.apply !== apply) {
1812
+ const applyWithAdapter = store.apply.bind(store);
1813
+ store.apply = (state, patches) => {
1814
+ internal.assertAlive?.("apply");
1815
+ internal.assertMutationAllowed?.("apply");
1816
+ if (typeof state !== "undefined" && state !== internal.rootState && state !== internal.module) validateReplacementSource?.(state);
1817
+ if (patches) {
1818
+ validatePatches(patches);
1819
+ assertSafePatches(patches, "store.apply()");
1820
+ }
1821
+ applyWithAdapter(state, patches);
1822
+ };
1823
+ }
1824
+ internal.stateSchema = createStateSchema(internal.rootState, store.isSliceStore);
1825
+ validateState?.(internal.getTransportState?.() ?? internal.rootState);
1305
1826
  return {
1306
- state: JSON.stringify(internal.rootState),
1307
- sequence: internal.sequence
1827
+ store,
1828
+ internal
1308
1829
  };
1309
- });
1310
- store.transport = transport;
1311
- };
1312
- //#endregion
1313
- //#region packages/core/src/lifecycle.ts
1314
- const readyStores = /* @__PURE__ */ new WeakSet();
1315
- const readyCallbacks = /* @__PURE__ */ new WeakMap();
1316
- const onStoreReady = (store, callback) => {
1317
- if (readyStores.has(store)) {
1318
- callback();
1319
- return () => void 0;
1320
- }
1321
- let callbacks = readyCallbacks.get(store);
1322
- if (!callbacks) {
1323
- callbacks = /* @__PURE__ */ new Set();
1324
- readyCallbacks.set(store, callbacks);
1830
+ } catch (error) {
1831
+ try {
1832
+ store.destroy?.();
1833
+ } catch (destroyError) {
1834
+ if (process.env.NODE_ENV === "development") console.error(destroyError);
1835
+ }
1836
+ releaseStoreName();
1837
+ throw error;
1325
1838
  }
1326
- callbacks.add(callback);
1327
- return () => {
1328
- callbacks?.delete(callback);
1329
- };
1330
- };
1331
- const markStoreReady = (store) => {
1332
- readyStores.add(store);
1333
- const callbacks = readyCallbacks.get(store);
1334
- if (!callbacks) return;
1335
- readyCallbacks.delete(store);
1336
- callbacks.forEach((callback) => callback());
1337
- callbacks.clear();
1338
1839
  };
1339
1840
  //#endregion
1340
1841
  //#region packages/core/src/create.ts
1341
- const namespaceMap = /* @__PURE__ */ new Map();
1342
- let hasWarnedAmbiguousFunctionMap = false;
1343
1842
  const isMainWorkerType = (workerType) => workerType === "SharedWorkerInternal" || workerType === "WebWorkerInternal";
1344
1843
  const isClientWorkerType = (workerType) => workerType === "SharedWorkerClient" || workerType === "WebWorkerClient";
1345
1844
  const validateCreateModeOptions = (options) => {
@@ -1353,430 +1852,55 @@ const validateCreateModeOptions = (options) => {
1353
1852
  if (isMainWorkerType(explicitWorkerType) && (clientTransport || worker)) throw new Error("main workerType cannot be combined with client transport settings.");
1354
1853
  if (isClientWorkerType(explicitWorkerType) && storeTransport) throw new Error("client workerType cannot be combined with transport.");
1355
1854
  };
1356
- const warnAmbiguousFunctionMap = () => {
1357
- if (hasWarnedAmbiguousFunctionMap || process.env.NODE_ENV === "production" || process.env.NODE_ENV === "test") return;
1358
- hasWarnedAmbiguousFunctionMap = true;
1359
- console.warn([
1360
- `sliceMode: 'auto' inferred slices from an object of functions.`,
1361
- `This shape is ambiguous with a single store that only contains methods.`,
1362
- `Use create({ ping() {} }, { sliceMode: 'single' }) for a plain method store,`,
1363
- `or create({ counter: (set) => ({ count: 0 }) }, { sliceMode: 'slices' }) for slices.`
1364
- ].join(" "));
1365
- };
1366
1855
  /**
1367
1856
  * Create a local store, the main side of a shared store, or a client mirror of
1368
1857
  * a shared store.
1369
1858
  *
1370
1859
  * @remarks
1371
- * - Pass a {@link Slice} function for a single store.
1372
- * - Pass an object of slice factories for a slices store.
1373
- * - When an object input only contains functions, prefer explicit `sliceMode`
1374
- * to avoid ambiguous inference.
1375
- * - When `clientTransport` or `worker` is provided, returned store methods
1376
- * become promise-returning methods because execution happens on the main
1377
- * shared store.
1378
- * - New semantics should prefer explicit helpers or variants over adding more
1379
- * ambiguous `create()` input forms.
1860
+ * Prefer the static `coaction/local` entry when transport support is not
1861
+ * required. It excludes the JSON protocol and reconnect runtime from the
1862
+ * consumer dependency graph.
1380
1863
  */
1381
1864
  const create = (createState, options = {}) => {
1382
1865
  const checkEnablePatches = Object.hasOwnProperty.call(options, "enablePatches") && !options.enablePatches;
1383
1866
  validateCreateModeOptions(options);
1384
1867
  const workerType = options.workerType ?? WorkerType;
1385
1868
  const storeTransport = options.transport;
1386
- const share = workerType === "WebWorkerInternal" || workerType === "SharedWorkerInternal" || storeTransport ? "main" : void 0;
1387
- const createStore = ({ share }) => {
1388
- const store = {};
1389
- const internal = {
1390
- sequence: 0,
1391
- isBatching: false,
1392
- listeners: /* @__PURE__ */ new Set()
1393
- };
1394
- internal.notifyStateChange = () => {
1395
- refreshSignalSlots(internal);
1396
- internal.listeners.forEach((listener) => listener());
1397
- };
1398
- const name = options.name ?? "default";
1399
- const shouldTrackName = share === "main" && process.env.NODE_ENV !== "test";
1400
- const releaseStoreName = () => {
1401
- if (shouldTrackName) namespaceMap.delete(name);
1402
- };
1403
- if (shouldTrackName) {
1404
- if (namespaceMap.get(name)) throw new Error(`Store name '${name}' is not unique.`);
1405
- namespaceMap.set(name, true);
1406
- }
1407
- try {
1408
- const { setState, getState } = handleState(store, internal, options);
1409
- const subscribe = (listener) => {
1410
- internal.assertAlive?.("subscribe");
1411
- internal.listeners.add(listener);
1412
- return () => internal.listeners.delete(listener);
1413
- };
1414
- let isDestroyed = false;
1415
- internal.assertAlive = (operation) => {
1416
- if (isDestroyed) throw new Error(`${operation} cannot be called after store.destroy().`);
1417
- };
1418
- const destroy = () => {
1419
- if (isDestroyed) return;
1420
- isDestroyed = true;
1421
- internal.listeners.clear();
1422
- store.transport?.dispose();
1423
- releaseStoreName();
1424
- };
1425
- const apply = (state = internal.rootState, patches) => {
1426
- internal.assertAlive?.("apply");
1427
- internal.assertMutationAllowed?.("apply");
1428
- assertSafePatches(patches, "store.apply()");
1429
- const safePatches = sanitizePatches(patches);
1430
- const baseState = state === internal.module ? internal.rootState : state;
1431
- const nextState = sanitizeReplacementState(safePatches ? (0, mutative.apply)(baseState, safePatches) : baseState);
1432
- assertKnownStateShape(nextState, internal.rootState, internal.stateSchema, store.isSliceStore, { requireSliceRoots: true });
1433
- if (store.share === "main") validateSharedStateSerializable(nextState);
1434
- internal.rootState = nextState;
1435
- refreshSignalSlots(internal);
1436
- if (internal.updateImmutable) internal.updateImmutable(internal.rootState);
1437
- else internal.listeners.forEach((listener) => listener());
1438
- };
1439
- const getPureState = () => internal.rootState;
1440
- const isFunctionMapObject = () => {
1441
- if (typeof createState === "object" && createState !== null) {
1442
- const values = getOwnEnumerableKeys(createState).map((key) => createState[key]);
1443
- return values.length > 0 && values.every((value) => typeof value === "function");
1444
- }
1445
- return false;
1446
- };
1447
- const getIsSliceStore = () => {
1448
- const sliceMode = options.sliceMode ?? "auto";
1449
- if (sliceMode === "single") return false;
1450
- if (sliceMode === "slices") {
1451
- if (!isFunctionMapObject()) throw new Error(`sliceMode: 'slices' requires createState to be an object of slice functions.`);
1452
- return true;
1453
- }
1454
- if (isFunctionMapObject()) {
1455
- warnAmbiguousFunctionMap();
1456
- return true;
1457
- }
1458
- return false;
1459
- };
1460
- const isSliceStore = getIsSliceStore();
1461
- Object.assign(store, {
1462
- name,
1463
- share: share ?? false,
1464
- setState,
1465
- getState,
1466
- subscribe,
1467
- destroy,
1468
- apply,
1469
- isSliceStore,
1470
- getPureState
1471
- });
1472
- const middlewareStore = applyMiddlewares(store, options.middlewares ?? []);
1473
- if (middlewareStore !== store) Object.assign(store, middlewareStore);
1474
- const initialState = getInitialState(store, createState, internal);
1475
- if (share) validateSharedActionPaths(initialState);
1476
- store.getInitialState = () => initialState;
1477
- internal.rootState = getRawState(store, internal, initialState, options);
1478
- internal.stateSchema = createStateSchema(internal.rootState, store.isSliceStore);
1479
- if (share) validateSharedStateSerializable(internal.rootState);
1480
- markStoreReady(store);
1481
- return {
1482
- store,
1483
- internal
1484
- };
1485
- } catch (error) {
1486
- releaseStoreName();
1487
- throw error;
1488
- }
1489
- };
1490
- if (options.clientTransport || options.worker || options.workerType === "WebWorkerClient" || options.workerType === "SharedWorkerClient") {
1491
- if (checkEnablePatches) throw new Error(`enablePatches: true is required for the async store`);
1492
- return wrapStore(createAsyncClientStore(createStore, options));
1493
- }
1494
- const { store, internal } = createStore({ share });
1495
- handleMainTransport(store, internal, storeTransport, workerType, checkEnablePatches);
1496
- return wrapStore(store);
1497
- };
1498
- //#endregion
1499
- //#region packages/core/src/binder.ts
1500
- const createExternalStoreAdapter = ({ handleState, handleStore }) => ((state) => {
1501
- const { copyState, key, bind } = handleState(state);
1502
- const value = typeof key !== "undefined" ? copyState[key] : copyState;
1503
- Object.defineProperty(value, bindSymbol, {
1504
- configurable: true,
1505
- enumerable: typeof key !== "undefined",
1506
- value: {
1507
- handleStore,
1508
- bind
1509
- }
1869
+ const share = isMainWorkerType(workerType) || storeTransport ? "main" : void 0;
1870
+ const buildStore = ({ share }) => createStore(createState, options, {
1871
+ share,
1872
+ clientAction: share === "client" ? createClientAction : void 0,
1873
+ collectActionPaths: share === "main" ? validateSharedActionPaths : void 0,
1874
+ validateInitialState: share ? validateSharedInitialState : void 0,
1875
+ validatePatches: share === "main" ? validateUpdatePatches : void 0,
1876
+ validateReplacementSource: share ? validateSharedReplacementSource : void 0,
1877
+ validateState: share ? validateSharedStateSerializable : void 0
1510
1878
  });
1511
- return copyState;
1512
- });
1513
- /**
1514
- * Build an adapter helper for bridging an external store implementation into
1515
- * Coaction.
1516
- *
1517
- * @remarks
1518
- * Official bindings use this to integrate stores such as Redux, Jotai, Pinia,
1519
- * Zustand, MobX, and Valtio. Binder-backed integrations are whole-store
1520
- * adapters; they are not compatible with Coaction slices mode.
1521
- */
1522
- function createBinder({ handleState, handleStore }) {
1523
- return createExternalStoreAdapter({
1524
- handleState,
1525
- handleStore
1526
- });
1527
- }
1528
- /**
1529
- * Define a whole-store adapter for integrating an external state runtime with
1530
- * Coaction.
1531
- *
1532
- * @remarks
1533
- * This is the stable 2.x name for adapter authors. `createBinder()` remains as
1534
- * a compatibility alias for existing official and community integrations.
1535
- */
1536
- function defineExternalStoreAdapter(options) {
1537
- return createExternalStoreAdapter(options);
1538
- }
1539
- //#endregion
1540
- //#region packages/core/src/reactiveTracker.ts
1541
- const ReactiveFlags = alien_signals_system.ReactiveFlags;
1542
- const unwatch = (node) => {
1543
- if (!(node.flags & ReactiveFlags.Mutable)) {
1544
- node.depsTail = void 0;
1545
- node.flags = 0;
1546
- purgeDeps(node);
1547
- const sub = node.subs;
1548
- if (sub !== void 0) unlink(sub);
1549
- return;
1550
- }
1551
- if (node.depsTail !== void 0) {
1552
- node.depsTail = void 0;
1553
- node.flags = ReactiveFlags.Mutable | ReactiveFlags.Dirty;
1554
- purgeDeps(node);
1879
+ if (options.clientTransport || options.worker || isClientWorkerType(options.workerType)) {
1880
+ if (checkEnablePatches) throw new Error("enablePatches: true is required for the async store");
1881
+ return wrapStore(createAsyncClientStore(buildStore, options));
1555
1882
  }
1556
- };
1557
- const unlink = (link, sub = link.sub) => {
1558
- const dep = link.dep;
1559
- const prevDep = link.prevDep;
1560
- const nextDep = link.nextDep;
1561
- const nextSub = link.nextSub;
1562
- const prevSub = link.prevSub;
1563
- if (nextDep !== void 0) nextDep.prevDep = prevDep;
1564
- else sub.depsTail = prevDep;
1565
- if (prevDep !== void 0) prevDep.nextDep = nextDep;
1566
- else sub.deps = nextDep;
1567
- if (nextSub !== void 0) nextSub.prevSub = prevSub;
1568
- else dep.subsTail = prevSub;
1569
- if (prevSub !== void 0) prevSub.nextSub = nextSub;
1570
- else if ((dep.subs = nextSub) === void 0) unwatch(dep);
1571
- return nextDep;
1572
- };
1573
- const purgeDeps = (sub) => {
1574
- const depsTail = sub.depsTail;
1575
- let dep = depsTail !== void 0 ? depsTail.nextDep : sub.deps;
1576
- while (dep !== void 0) dep = unlink(dep, sub);
1577
- };
1578
- const createReactiveTracker = () => {
1579
- let version = 0;
1580
- let disposed = false;
1581
- const listeners = /* @__PURE__ */ new Set();
1582
- const node = {
1583
- deps: void 0,
1584
- depsTail: void 0,
1585
- subs: void 0,
1586
- subsTail: void 0,
1587
- flags: ReactiveFlags.Watching,
1588
- fn: () => {
1589
- if (disposed) return;
1590
- version += 1;
1591
- listeners.forEach((listener) => listener());
1592
- }
1593
- };
1594
- const dispose = () => {
1595
- if (disposed) return;
1596
- disposed = true;
1597
- listeners.clear();
1598
- node.depsTail = void 0;
1599
- purgeDeps(node);
1600
- node.flags = 0;
1601
- };
1602
- return {
1603
- getSnapshot: () => version,
1604
- subscribe(listener) {
1605
- if (disposed) return () => void 0;
1606
- listeners.add(listener);
1607
- return () => {
1608
- listeners.delete(listener);
1609
- };
1610
- },
1611
- track(fn) {
1612
- if (disposed) return fn();
1613
- node.depsTail = void 0;
1614
- node.flags = ReactiveFlags.Watching | ReactiveFlags.RecursedCheck;
1615
- const prevSub = (0, alien_signals.setActiveSub)(node);
1616
- try {
1617
- return fn();
1618
- } finally {
1619
- (0, alien_signals.setActiveSub)(prevSub);
1620
- node.flags &= ~ReactiveFlags.RecursedCheck;
1621
- purgeDeps(node);
1622
- }
1623
- },
1624
- dispose
1625
- };
1626
- };
1627
- //#endregion
1628
- //#region packages/core/src/replaceExternalStoreState.ts
1629
- const replaceExternalStoreState = (store, internal, source, { syncImmutable = true } = {}) => {
1630
- const [, patches, inversePatches] = (0, mutative.create)(internal.rootState, (draft) => {
1631
- replaceOwnEnumerable(draft, source);
1632
- }, { enablePatches: true });
1633
- const safePatches = sanitizeCheckedPatches((store.patch ? store.patch({
1634
- patches,
1635
- inversePatches
1636
- }) : {
1637
- patches,
1638
- inversePatches
1639
- }).patches, "store.patch()");
1640
- if (!safePatches.length) return;
1641
- const updateImmutable = internal.updateImmutable;
1642
- if (!syncImmutable) internal.updateImmutable = void 0;
1883
+ if (share === "main" && checkEnablePatches) throw new Error("enablePatches: true is required for the transport");
1884
+ let builtStore;
1643
1885
  try {
1644
- store.apply(internal.rootState, safePatches);
1645
- } finally {
1646
- internal.updateImmutable = updateImmutable;
1647
- }
1648
- emit(store, internal, safePatches);
1649
- };
1650
- //#endregion
1651
- //#region packages/core/src/externalMutableAdapterUtils.ts
1652
- const getMutableAdapterOwnEnumerableKeys = (value) => Reflect.ownKeys(value).filter((key) => Object.prototype.propertyIsEnumerable.call(value, key));
1653
- const isMutableAdapterUnsafeKey = (key) => typeof key === "string" && isUnsafeKey(key);
1654
- const isArrayIndexKey = (key) => {
1655
- if (typeof key !== "string") return false;
1656
- const index = Number(key);
1657
- return Number.isInteger(index) && index >= 0 && index < 2 ** 32 - 1 && String(index) === key;
1658
- };
1659
- const isObjectRecord = (value) => Object.prototype.toString.call(value) === "[object Object]";
1660
- const assertCanSetMutableAdapterPublicStateKey = (publicState, key) => {
1661
- if (Object.prototype.hasOwnProperty.call(publicState, key)) return;
1662
- if (Object.isExtensible(publicState)) return;
1663
- throw new StateSchemaError(`Unknown state key '${String(key)}' cannot be added after store initialization. Coaction state schema is fixed.`);
1664
- };
1665
- const ensureMutableAdapterRawDescriptor = (rawState, mutableState, publicState, key) => {
1666
- if (rawState === mutableState) return;
1667
- const rawDescriptor = Object.getOwnPropertyDescriptor(rawState, key);
1668
- if (rawDescriptor?.get && rawDescriptor.set) return;
1669
- const publicDescriptor = Object.getOwnPropertyDescriptor(publicState, key);
1670
- if (!publicDescriptor || rawDescriptor?.configurable === false) return;
1671
- Object.defineProperty(rawState, key, {
1672
- get: () => mutableState[key],
1673
- set: (value) => {
1674
- mutableState[key] = value;
1675
- },
1676
- configurable: true,
1677
- enumerable: publicDescriptor.enumerable
1678
- });
1679
- };
1680
- const replaceMutableAdapterState = (rawState, mutableState, publicState, source) => {
1681
- const nextKeys = /* @__PURE__ */ new Set();
1682
- for (const key of getMutableAdapterOwnEnumerableKeys(source)) {
1683
- if (isMutableAdapterUnsafeKey(key)) continue;
1684
- if (typeof source[key] === "function") continue;
1685
- nextKeys.add(key);
1886
+ builtStore = buildStore({ share });
1887
+ } catch (error) {
1888
+ return failTransportInitialization(storeTransport, error);
1686
1889
  }
1687
- nextKeys.forEach((key) => {
1688
- assertCanSetMutableAdapterPublicStateKey(publicState, key);
1689
- });
1690
- for (const key of getMutableAdapterOwnEnumerableKeys(rawState)) {
1691
- if (isMutableAdapterUnsafeKey(key)) {
1692
- delete rawState[key];
1693
- delete mutableState[key];
1694
- continue;
1695
- }
1696
- if (typeof rawState[key] === "function") continue;
1697
- if (!nextKeys.has(key)) {
1698
- delete rawState[key];
1699
- delete mutableState[key];
1700
- }
1701
- }
1702
- const rawSeen = /* @__PURE__ */ new WeakMap();
1703
- const mutableSeen = /* @__PURE__ */ new WeakMap();
1704
- const publicSeen = /* @__PURE__ */ new WeakMap();
1705
- rawSeen.set(source, rawState);
1706
- mutableSeen.set(source, mutableState);
1707
- publicSeen.set(source, publicState);
1708
- nextKeys.forEach((key) => {
1709
- ensureMutableAdapterRawDescriptor(rawState, mutableState, publicState, key);
1710
- rawState[key] = sanitizeReplacementState(source[key], rawSeen);
1711
- mutableState[key] = sanitizeReplacementState(source[key], mutableSeen);
1712
- publicState[key] = sanitizeReplacementState(source[key], publicSeen);
1713
- });
1714
- };
1715
- const applyMutableAdapterPatches = (baseState, patches, rawState, mutableState, publicState) => {
1716
- assertSafePatches(patches, "mutable adapter apply()");
1717
- replaceMutableAdapterState(rawState, mutableState, publicState, (0, mutative.apply)(toMutableAdapterSnapshot(baseState === publicState ? rawState : baseState), patches));
1718
- };
1719
- const toMutableAdapterSnapshot = (value, visited = /* @__PURE__ */ new WeakMap()) => {
1720
- if (Array.isArray(value)) {
1721
- if (visited.has(value)) return visited.get(value);
1722
- const next = [];
1723
- next.length = value.length;
1724
- visited.set(value, next);
1725
- for (let index = 0; index < value.length; index += 1) if (Object.prototype.hasOwnProperty.call(value, index)) next[index] = toMutableAdapterSnapshot(value[index], visited);
1726
- const source = value;
1727
- const target = next;
1728
- for (const key of getMutableAdapterOwnEnumerableKeys(value)) {
1729
- if (isArrayIndexKey(key) || isMutableAdapterUnsafeKey(key)) continue;
1730
- const child = source[key];
1731
- if (typeof child !== "function") target[key] = toMutableAdapterSnapshot(child, visited);
1732
- }
1733
- return next;
1734
- }
1735
- if (typeof value === "object" && value !== null) {
1736
- if (!isObjectRecord(value)) return value;
1737
- if (visited.has(value)) return visited.get(value);
1738
- const next = {};
1739
- visited.set(value, next);
1740
- for (const key of getMutableAdapterOwnEnumerableKeys(value)) {
1741
- if (isMutableAdapterUnsafeKey(key)) continue;
1742
- const child = value[key];
1743
- if (typeof child !== "function") next[key] = toMutableAdapterSnapshot(child, visited);
1744
- }
1745
- return next;
1746
- }
1747
- return value;
1748
- };
1749
- const snapshotMutableAdapterPureState = (store) => toMutableAdapterSnapshot(store.getPureState());
1750
- const isEqualMutableAdapterSnapshot = (left, right, visited = /* @__PURE__ */ new WeakMap()) => {
1751
- if (Object.is(left, right)) return true;
1752
- if (typeof left !== "object" || left === null || typeof right !== "object" || right === null) return false;
1753
- const leftIsArray = Array.isArray(left);
1754
- const rightIsArray = Array.isArray(right);
1755
- if (leftIsArray || rightIsArray) {
1756
- if (!leftIsArray || !rightIsArray || left.length !== right.length) return false;
1757
- } else if (!isObjectRecord(left) || !isObjectRecord(right)) return false;
1758
- let seenTargets = visited.get(left);
1759
- if (!seenTargets) {
1760
- seenTargets = /* @__PURE__ */ new WeakSet();
1761
- visited.set(left, seenTargets);
1762
- } else if (seenTargets.has(right)) return true;
1763
- seenTargets.add(right);
1764
- const leftRecord = left;
1765
- const rightRecord = right;
1766
- const leftKeys = getMutableAdapterOwnEnumerableKeys(left);
1767
- const rightKeys = getMutableAdapterOwnEnumerableKeys(right);
1768
- if (leftKeys.length !== rightKeys.length) return false;
1769
- for (const key of leftKeys) {
1770
- if (!Object.prototype.hasOwnProperty.call(rightRecord, key)) return false;
1771
- if (!isEqualMutableAdapterSnapshot(leftRecord[key], rightRecord[key], visited)) return false;
1890
+ const { store, internal } = builtStore;
1891
+ try {
1892
+ handleMainTransport(store, internal, storeTransport, workerType, checkEnablePatches, options.transportPolicy);
1893
+ markStoreReady(store);
1894
+ internal.assertAlive?.("store initialization");
1895
+ } catch (error) {
1896
+ return failStoreSetup(store, error);
1772
1897
  }
1773
- return true;
1898
+ return wrapStore(store);
1774
1899
  };
1775
1900
  //#endregion
1901
+ exports.ActionAuthorityChangedError = ActionAuthorityChangedError;
1776
1902
  exports.StateSchemaError = StateSchemaError;
1777
1903
  exports.UnsafePatchPathError = UnsafePatchPathError;
1778
- exports.applyMutableAdapterPatches = applyMutableAdapterPatches;
1779
- exports.applyRootReplacementWithPatches = applyRootReplacementWithPatches;
1780
1904
  exports.assertSafePatches = assertSafePatches;
1781
1905
  Object.defineProperty(exports, "computed", {
1782
1906
  enumerable: true,
@@ -1785,10 +1909,6 @@ Object.defineProperty(exports, "computed", {
1785
1909
  }
1786
1910
  });
1787
1911
  exports.create = create;
1788
- exports.createBinder = createBinder;
1789
- exports.createReactiveTracker = createReactiveTracker;
1790
- exports.createRootReplacementPatches = createRootReplacementPatches;
1791
- exports.defineExternalStoreAdapter = defineExternalStoreAdapter;
1792
1912
  Object.defineProperty(exports, "effect", {
1793
1913
  enumerable: true,
1794
1914
  get: function() {
@@ -1807,7 +1927,6 @@ Object.defineProperty(exports, "endBatch", {
1807
1927
  return alien_signals.endBatch;
1808
1928
  }
1809
1929
  });
1810
- exports.getMutableAdapterOwnEnumerableKeys = getMutableAdapterOwnEnumerableKeys;
1811
1930
  Object.defineProperty(exports, "isComputed", {
1812
1931
  enumerable: true,
1813
1932
  get: function() {
@@ -1826,8 +1945,6 @@ Object.defineProperty(exports, "isEffectScope", {
1826
1945
  return alien_signals.isEffectScope;
1827
1946
  }
1828
1947
  });
1829
- exports.isEqualMutableAdapterSnapshot = isEqualMutableAdapterSnapshot;
1830
- exports.isMutableAdapterUnsafeKey = isMutableAdapterUnsafeKey;
1831
1948
  Object.defineProperty(exports, "isSignal", {
1832
1949
  enumerable: true,
1833
1950
  get: function() {
@@ -1836,9 +1953,6 @@ Object.defineProperty(exports, "isSignal", {
1836
1953
  });
1837
1954
  exports.isStateSchemaError = isStateSchemaError;
1838
1955
  exports.onStoreReady = onStoreReady;
1839
- exports.replaceExternalStoreState = replaceExternalStoreState;
1840
- exports.replaceMutableAdapterState = replaceMutableAdapterState;
1841
- exports.replaceOwnEnumerable = replaceOwnEnumerable;
1842
1956
  exports.sanitizeInitialStateValue = sanitizeInitialStateValue;
1843
1957
  exports.sanitizePatches = sanitizePatches;
1844
1958
  exports.sanitizeReplacementState = sanitizeReplacementState;
@@ -1848,18 +1962,15 @@ Object.defineProperty(exports, "signal", {
1848
1962
  return alien_signals.signal;
1849
1963
  }
1850
1964
  });
1851
- exports.snapshotMutableAdapterPureState = snapshotMutableAdapterPureState;
1852
1965
  Object.defineProperty(exports, "startBatch", {
1853
1966
  enumerable: true,
1854
1967
  get: function() {
1855
1968
  return alien_signals.startBatch;
1856
1969
  }
1857
1970
  });
1858
- exports.toMutableAdapterSnapshot = toMutableAdapterSnapshot;
1859
1971
  Object.defineProperty(exports, "trigger", {
1860
1972
  enumerable: true,
1861
1973
  get: function() {
1862
1974
  return alien_signals.trigger;
1863
1975
  }
1864
1976
  });
1865
- exports.wrapStore = wrapStore;