atom.io 0.14.0 → 0.14.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. package/data/dist/index.cjs +1473 -52
  2. package/data/dist/index.cjs.map +1 -1
  3. package/data/dist/index.d.cts +315 -16
  4. package/data/dist/index.js +10 -267
  5. package/data/dist/index.js.map +1 -1
  6. package/data/package.json +5 -5
  7. package/data/src/join.ts +3 -3
  8. package/dist/chunk-5VJ77LZE.js +176 -0
  9. package/dist/chunk-5VJ77LZE.js.map +1 -0
  10. package/dist/chunk-CK7GNCU5.js +309 -0
  11. package/dist/chunk-CK7GNCU5.js.map +1 -0
  12. package/dist/chunk-KW7RA7IM.js +67 -0
  13. package/dist/chunk-KW7RA7IM.js.map +1 -0
  14. package/dist/chunk-LFXB7Y6M.js +68 -0
  15. package/dist/chunk-LFXB7Y6M.js.map +1 -0
  16. package/dist/chunk-NYCVSXQB.js +181 -0
  17. package/dist/chunk-NYCVSXQB.js.map +1 -0
  18. package/dist/chunk-TE3ZSTQ6.js +2516 -0
  19. package/dist/chunk-TE3ZSTQ6.js.map +1 -0
  20. package/dist/index.cjs +2244 -55
  21. package/dist/index.cjs.map +1 -1
  22. package/dist/index.d.cts +268 -21
  23. package/dist/index.js +1 -152
  24. package/dist/index.js.map +1 -1
  25. package/dist/metafile-cjs.json +1 -1
  26. package/internal/dist/index.cjs +208 -79
  27. package/internal/dist/index.cjs.map +1 -1
  28. package/internal/dist/index.d.cts +226 -27
  29. package/internal/dist/index.js +1 -2240
  30. package/internal/dist/index.js.map +1 -1
  31. package/internal/package.json +5 -5
  32. package/introspection/dist/index.cjs +1618 -46
  33. package/introspection/dist/index.cjs.map +1 -1
  34. package/introspection/dist/index.d.cts +374 -4
  35. package/introspection/dist/index.js +2 -316
  36. package/introspection/dist/index.js.map +1 -1
  37. package/introspection/package.json +5 -5
  38. package/json/dist/index.cjs +1560 -8
  39. package/json/dist/index.cjs.map +1 -1
  40. package/json/dist/index.d.cts +371 -7
  41. package/json/dist/index.js +1 -76
  42. package/json/dist/index.js.map +1 -1
  43. package/json/package.json +5 -5
  44. package/package.json +5 -4
  45. package/react/dist/index.cjs +1604 -14
  46. package/react/dist/index.cjs.map +1 -1
  47. package/react/dist/index.d.cts +375 -4
  48. package/react/dist/index.js +2 -68
  49. package/react/dist/index.js.map +1 -1
  50. package/react/package.json +5 -5
  51. package/react-devtools/dist/index.cjs +2268 -198
  52. package/react-devtools/dist/index.cjs.map +1 -1
  53. package/react-devtools/dist/index.css +2 -2
  54. package/react-devtools/dist/index.d.cts +148 -24
  55. package/react-devtools/dist/index.js +57 -297
  56. package/react-devtools/dist/index.js.map +1 -1
  57. package/react-devtools/package.json +5 -5
  58. package/realtime-client/dist/index.cjs +1585 -35
  59. package/realtime-client/dist/index.cjs.map +1 -1
  60. package/realtime-client/dist/index.d.cts +382 -12
  61. package/realtime-client/dist/index.js +2 -165
  62. package/realtime-client/dist/index.js.map +1 -1
  63. package/realtime-client/package.json +5 -5
  64. package/realtime-react/dist/index.cjs +1782 -35
  65. package/realtime-react/dist/index.cjs.map +1 -1
  66. package/realtime-react/dist/index.d.cts +49 -9
  67. package/realtime-react/dist/index.js +4 -66
  68. package/realtime-react/dist/index.js.map +1 -1
  69. package/realtime-react/package.json +5 -5
  70. package/realtime-server/dist/index.cjs +1604 -58
  71. package/realtime-server/dist/index.cjs.map +1 -1
  72. package/realtime-server/dist/index.d.cts +391 -11
  73. package/realtime-server/dist/index.js +27 -21
  74. package/realtime-server/dist/index.js.map +1 -1
  75. package/realtime-server/package.json +6 -6
  76. package/realtime-testing/dist/index.cjs +2352 -16
  77. package/realtime-testing/dist/index.cjs.map +1 -1
  78. package/realtime-testing/dist/index.d.cts +486 -3
  79. package/realtime-testing/dist/index.js +10 -31
  80. package/realtime-testing/dist/index.js.map +1 -1
  81. package/realtime-testing/package.json +5 -5
  82. package/transceivers/set-rtx/dist/index.cjs +31 -10
  83. package/transceivers/set-rtx/dist/index.cjs.map +1 -1
  84. package/transceivers/set-rtx/dist/index.d.cts +29 -3
  85. package/transceivers/set-rtx/dist/index.js +2 -3
  86. package/transceivers/set-rtx/dist/index.js.map +1 -1
  87. package/transceivers/set-rtx/package.json +6 -6
  88. package/data/dist/index.d.ts +0 -158
  89. package/data/dist/metafile-cjs.json +0 -1
  90. package/data/dist/metafile-esm.json +0 -1
  91. package/dist/index.d.ts +0 -243
  92. package/dist/metafile-esm.json +0 -1
  93. package/internal/dist/index.d.ts +0 -421
  94. package/internal/dist/metafile-cjs.json +0 -1
  95. package/internal/dist/metafile-esm.json +0 -1
  96. package/introspection/dist/index.d.ts +0 -24
  97. package/introspection/dist/metafile-cjs.json +0 -1
  98. package/introspection/dist/metafile-esm.json +0 -1
  99. package/json/dist/index.d.ts +0 -51
  100. package/json/dist/metafile-cjs.json +0 -1
  101. package/json/dist/metafile-esm.json +0 -1
  102. package/react/dist/index.d.ts +0 -23
  103. package/react/dist/metafile-cjs.json +0 -1
  104. package/react/dist/metafile-esm.json +0 -1
  105. package/react-devtools/dist/index.d.ts +0 -341
  106. package/react-devtools/dist/metafile-cjs.json +0 -1
  107. package/react-devtools/dist/metafile-esm.json +0 -1
  108. package/realtime-client/dist/index.d.ts +0 -22
  109. package/realtime-client/dist/metafile-cjs.json +0 -1
  110. package/realtime-client/dist/metafile-esm.json +0 -1
  111. package/realtime-react/dist/index.d.ts +0 -27
  112. package/realtime-react/dist/metafile-cjs.json +0 -1
  113. package/realtime-react/dist/metafile-esm.json +0 -1
  114. package/realtime-server/dist/index.d.ts +0 -25
  115. package/realtime-server/dist/metafile-cjs.json +0 -1
  116. package/realtime-server/dist/metafile-esm.json +0 -1
  117. package/realtime-testing/dist/index.d.ts +0 -49
  118. package/realtime-testing/dist/metafile-cjs.json +0 -1
  119. package/realtime-testing/dist/metafile-esm.json +0 -1
  120. package/transceivers/set-rtx/dist/index.d.ts +0 -40
  121. package/transceivers/set-rtx/dist/metafile-cjs.json +0 -1
  122. package/transceivers/set-rtx/dist/metafile-esm.json +0 -1
@@ -2,14 +2,11 @@
2
2
 
3
3
  var http = require('http');
4
4
  var react = require('@testing-library/react');
5
- var AtomIO = require('atom.io');
6
- var Internal = require('atom.io/internal');
7
- var AR = require('atom.io/react');
8
- var RTC = require('atom.io/realtime-react');
5
+ var React2 = require('react');
6
+ var jsxRuntime = require('react/jsx-runtime');
7
+ var socket_ioClient = require('socket.io-client');
9
8
  var Happy = require('happy-dom');
10
9
  var SocketIO = require('socket.io');
11
- var socket_ioClient = require('socket.io-client');
12
- var jsxRuntime = require('react/jsx-runtime');
13
10
 
14
11
  function _interopNamespace(e) {
15
12
  if (e && e.__esModule) return e;
@@ -30,10 +27,7 @@ function _interopNamespace(e) {
30
27
  }
31
28
 
32
29
  var http__namespace = /*#__PURE__*/_interopNamespace(http);
33
- var AtomIO__namespace = /*#__PURE__*/_interopNamespace(AtomIO);
34
- var Internal__namespace = /*#__PURE__*/_interopNamespace(Internal);
35
- var AR__namespace = /*#__PURE__*/_interopNamespace(AR);
36
- var RTC__namespace = /*#__PURE__*/_interopNamespace(RTC);
30
+ var React2__namespace = /*#__PURE__*/_interopNamespace(React2);
37
31
  var Happy__namespace = /*#__PURE__*/_interopNamespace(Happy);
38
32
  var SocketIO__namespace = /*#__PURE__*/_interopNamespace(SocketIO);
39
33
 
@@ -57,7 +51,2349 @@ var __spreadValues = (a, b) => {
57
51
  };
58
52
  var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
59
53
 
60
- // ../../anvl/src/object/entries.ts
54
+ // internal/src/future.ts
55
+ var Future = class extends Promise {
56
+ constructor(executor) {
57
+ super((resolve, reject) => {
58
+ const pass = (value) => this.isCanceled ? reject(`canceled`) : resolve(value);
59
+ const fail = (reason) => this.isCanceled ? reject(`canceled`) : reject(reason);
60
+ if (typeof executor === `function`) {
61
+ executor(pass, fail);
62
+ } else {
63
+ executor.then(pass, fail);
64
+ }
65
+ });
66
+ this.isCanceled = false;
67
+ }
68
+ cancel() {
69
+ this.isCanceled = true;
70
+ }
71
+ };
72
+
73
+ // internal/src/lineage.ts
74
+ function newest(scion) {
75
+ while (scion.child !== null) {
76
+ scion = scion.child;
77
+ }
78
+ return scion;
79
+ }
80
+
81
+ // internal/src/caching.ts
82
+ function cacheValue(key, value, subject, store) {
83
+ const target = newest(store);
84
+ const currentValue = target.valueMap.get(key);
85
+ if (currentValue instanceof Future) {
86
+ currentValue.cancel();
87
+ }
88
+ if (value instanceof Promise) {
89
+ const future = new Future(value);
90
+ newest(store).valueMap.set(key, future);
91
+ future.then((resolved) => {
92
+ if (future.isCanceled) {
93
+ return;
94
+ }
95
+ cacheValue(key, resolved, subject, store);
96
+ subject.next({ newValue: resolved, oldValue: future });
97
+ }).catch((thrown) => {
98
+ if (thrown !== `canceled`) {
99
+ store.logger.error(`\u{1F4A5}`, `state`, key, `rejected:`, thrown);
100
+ }
101
+ });
102
+ return future;
103
+ }
104
+ target.valueMap.set(key, value);
105
+ return value;
106
+ }
107
+ var readCachedValue = (key, store) => {
108
+ return newest(store).valueMap.get(key);
109
+ };
110
+ var isValueCached = (key, store) => {
111
+ return newest(store).valueMap.has(key);
112
+ };
113
+ var evictCachedValue = (key, store) => {
114
+ const core = newest(store);
115
+ const currentValue = core.valueMap.get(key);
116
+ if (currentValue instanceof Future) {
117
+ currentValue.cancel();
118
+ }
119
+ if (core.operation.open) {
120
+ core.operation.prev.set(key, currentValue);
121
+ }
122
+ core.valueMap.delete(key);
123
+ store.logger.info(`\u{1F5D1}`, `state`, key, `evicted`);
124
+ };
125
+
126
+ // ../anvl/src/json/index.ts
127
+ var parseJson = (str) => JSON.parse(str);
128
+ var stringifyJson = (json) => JSON.stringify(json);
129
+
130
+ // json/src/select-json.ts
131
+ var selectJson = (atom2, transform, store = IMPLICIT.STORE) => {
132
+ return createSelector(
133
+ {
134
+ key: `${atom2.key}:JSON`,
135
+ get: ({ get }) => transform.toJson(get(atom2)),
136
+ set: ({ set }, newValue) => set(atom2, transform.fromJson(newValue))
137
+ },
138
+ void 0,
139
+ store
140
+ );
141
+ };
142
+
143
+ // json/src/select-json-family.ts
144
+ var selectJsonFamily = (atomFamily, transform, store = IMPLICIT.STORE) => {
145
+ const jsonFamily = createSelectorFamily(
146
+ {
147
+ key: `${atomFamily.key}:JSON`,
148
+ get: (key) => ({ get }) => transform.toJson(get(atomFamily(key))),
149
+ set: (key) => ({ set }, newValue) => set(atomFamily(key), transform.fromJson(newValue))
150
+ },
151
+ store
152
+ );
153
+ atomFamily.subject.subscribe(
154
+ `store=${store.config.name}::json-selector-family`,
155
+ (token) => {
156
+ if (token.family) {
157
+ jsonFamily(parseJson(token.family.subKey));
158
+ }
159
+ }
160
+ );
161
+ return jsonFamily;
162
+ };
163
+
164
+ // internal/src/read-or-compute-value.ts
165
+ var readOrComputeValue = (state, store) => {
166
+ if (isValueCached(state.key, store)) {
167
+ store.logger.info(`\u{1F4D6}`, state.type, state.key, `reading cached value`);
168
+ return readCachedValue(state.key, store);
169
+ }
170
+ if (state.type !== `atom`) {
171
+ store.logger.info(`\u{1F9EE}`, state.type, state.key, `computing value`);
172
+ return state.get();
173
+ }
174
+ const fallback = state.default instanceof Function ? state.default() : state.default;
175
+ store.logger.info(
176
+ `\u{1F481}`,
177
+ `atom`,
178
+ state.key,
179
+ `could not find cached value; using default`,
180
+ fallback
181
+ );
182
+ return state.default instanceof Function ? state.default() : state.default;
183
+ };
184
+
185
+ // internal/src/operation.ts
186
+ var openOperation = (token, store) => {
187
+ const target = newest(store);
188
+ if (target.operation.open) {
189
+ store.logger.error(
190
+ `\u274C`,
191
+ token.type,
192
+ token.key,
193
+ `failed to setState during a setState for "${target.operation.token.key}"`
194
+ );
195
+ return `rejection`;
196
+ }
197
+ target.operation = {
198
+ open: true,
199
+ done: /* @__PURE__ */ new Set(),
200
+ prev: /* @__PURE__ */ new Map(),
201
+ time: Date.now(),
202
+ token
203
+ };
204
+ store.logger.info(
205
+ `\u2B55`,
206
+ token.type,
207
+ token.key,
208
+ `operation start in store "${store.config.name}"${target.transactionMeta === null ? `` : ` ${target.transactionMeta.phase} "${target.transactionMeta.update.key}"`}`
209
+ );
210
+ };
211
+ var closeOperation = (store) => {
212
+ const target = newest(store);
213
+ if (target.operation.open) {
214
+ store.logger.info(
215
+ `\u{1F534}`,
216
+ target.operation.token.type,
217
+ target.operation.token.key,
218
+ `operation done in store "${store.config.name}"`
219
+ );
220
+ }
221
+ target.operation = { open: false };
222
+ store.subject.operationStatus.next(target.operation);
223
+ };
224
+ var isDone = (key, store) => {
225
+ const target = newest(store);
226
+ if (!target.operation.open) {
227
+ store.logger.warn(
228
+ `\u{1F41E}`,
229
+ `unknown`,
230
+ key,
231
+ `isDone called outside of an operation. This is probably a bug.`
232
+ );
233
+ return true;
234
+ }
235
+ return target.operation.done.has(key);
236
+ };
237
+ var markDone = (key, store) => {
238
+ const target = newest(store);
239
+ if (!target.operation.open) {
240
+ store.logger.warn(
241
+ `\u{1F41E}`,
242
+ `unknown`,
243
+ key,
244
+ `markDone called outside of an operation. This is probably a bug.`
245
+ );
246
+ return;
247
+ }
248
+ target.operation.done.add(key);
249
+ };
250
+
251
+ // internal/src/set-state/become.ts
252
+ var become = (nextVersionOfThing) => (originalThing) => nextVersionOfThing instanceof Function ? nextVersionOfThing(
253
+ originalThing instanceof Function ? originalThing() : originalThing
254
+ ) : nextVersionOfThing;
255
+
256
+ // internal/src/subject.ts
257
+ var Subject = class {
258
+ constructor() {
259
+ this.subscribers = /* @__PURE__ */ new Map();
260
+ }
261
+ subscribe(key, subscriber) {
262
+ this.subscribers.set(key, subscriber);
263
+ const unsubscribe = () => this.unsubscribe(key);
264
+ return unsubscribe;
265
+ }
266
+ unsubscribe(key) {
267
+ this.subscribers.delete(key);
268
+ }
269
+ next(value) {
270
+ for (const subscriber of this.subscribers.values()) {
271
+ subscriber(value);
272
+ }
273
+ }
274
+ };
275
+ var StatefulSubject = class extends Subject {
276
+ constructor(initialState) {
277
+ super();
278
+ this.state = initialState;
279
+ }
280
+ next(value) {
281
+ this.state = value;
282
+ super.next(value);
283
+ }
284
+ };
285
+
286
+ // internal/src/set-state/copy-mutable-if-needed.ts
287
+ function copyMutableIfNeeded(atom2, transform, origin, target) {
288
+ const originValue = origin.valueMap.get(atom2.key);
289
+ const targetValue = target.valueMap.get(atom2.key);
290
+ if (originValue === targetValue) {
291
+ origin.logger.info(`\u{1F4C3}`, `atom`, `${atom2.key}`, `copying`);
292
+ const jsonValue = transform.toJson(originValue);
293
+ const copiedValue = transform.fromJson(jsonValue);
294
+ target.valueMap.set(atom2.key, copiedValue);
295
+ new Tracker(atom2, origin);
296
+ return copiedValue;
297
+ }
298
+ return targetValue;
299
+ }
300
+
301
+ // internal/src/set-state/copy-mutable-in-transaction.ts
302
+ function copyMutableIfWithinTransaction(oldValue, atom2, store) {
303
+ const target = newest(store);
304
+ const parent = target.parent;
305
+ if (parent !== null) {
306
+ if (`toJson` in atom2 && `fromJson` in atom2) {
307
+ const copiedValue = copyMutableIfNeeded(atom2, atom2, parent, target);
308
+ return copiedValue;
309
+ }
310
+ if (`family` in atom2) {
311
+ const family = parent.families.get(atom2.family.key);
312
+ if (family && family.type === `atom_family`) {
313
+ const result = copyMutableFamilyMemberWithinTransaction(
314
+ atom2,
315
+ family,
316
+ parent,
317
+ target
318
+ );
319
+ if (result) {
320
+ return result;
321
+ }
322
+ }
323
+ }
324
+ }
325
+ return oldValue;
326
+ }
327
+ function copyMutableFamilyMemberWithinTransaction(atom2, family, origin, target) {
328
+ if (`toJson` in family && `fromJson` in family) {
329
+ const copyCreated = copyMutableIfNeeded(atom2, family, origin, target);
330
+ return copyCreated;
331
+ }
332
+ return null;
333
+ }
334
+
335
+ // internal/src/set-state/emit-update.ts
336
+ var emitUpdate = (state, update, store) => {
337
+ store.logger.info(
338
+ `\u{1F4E2}`,
339
+ state.type,
340
+ state.key,
341
+ `went (`,
342
+ update.oldValue,
343
+ `->`,
344
+ update.newValue,
345
+ `) subscribers:`,
346
+ state.subject.subscribers
347
+ );
348
+ state.subject.next(update);
349
+ };
350
+
351
+ // internal/src/set-state/evict-downstream.ts
352
+ var evictDownStream = (atom2, store) => {
353
+ const target = newest(store);
354
+ const downstreamKeys = target.selectorAtoms.getRelatedKeys(atom2.key);
355
+ store.logger.info(
356
+ `\u{1F9F9}`,
357
+ atom2.type,
358
+ atom2.key,
359
+ downstreamKeys ? `evicting ${downstreamKeys.size} states downstream:` : `no downstream states`,
360
+ downstreamKeys != null ? downstreamKeys : `to evict`
361
+ );
362
+ if (downstreamKeys) {
363
+ if (target.operation.open) {
364
+ store.logger.info(
365
+ `\u{1F9F9}`,
366
+ atom2.type,
367
+ atom2.key,
368
+ `[ ${[...target.operation.done].join(`, `)} ] already done`
369
+ );
370
+ }
371
+ for (const key of downstreamKeys) {
372
+ if (isDone(key, store)) {
373
+ continue;
374
+ }
375
+ evictCachedValue(key, store);
376
+ markDone(key, store);
377
+ }
378
+ }
379
+ };
380
+
381
+ // internal/src/set-state/stow-update.ts
382
+ function shouldUpdateBeStowed(key, update) {
383
+ if (isTransceiver(update.newValue)) {
384
+ return false;
385
+ }
386
+ if (key.includes(`\u{1F441}\u200D\u{1F5E8}`)) {
387
+ return false;
388
+ }
389
+ return true;
390
+ }
391
+ var stowUpdate = (state, update, store) => {
392
+ const { key } = state;
393
+ const target = newest(store);
394
+ if (target.transactionMeta === null || target.transactionMeta.phase !== `building`) {
395
+ store.logger.error(
396
+ `\u{1F41E}`,
397
+ `atom`,
398
+ key,
399
+ `stowUpdate called outside of a transaction. This is probably a bug.`
400
+ );
401
+ return;
402
+ }
403
+ const shouldStow = shouldUpdateBeStowed(key, update);
404
+ if (!shouldStow) {
405
+ return;
406
+ }
407
+ const atomUpdate = __spreadValues({ key }, update);
408
+ if (state.family) {
409
+ atomUpdate.family = state.family;
410
+ }
411
+ target.transactionMeta.update.updates.push(atomUpdate);
412
+ store.logger.info(
413
+ `\u{1F4C1}`,
414
+ `atom`,
415
+ key,
416
+ `stowed (`,
417
+ update.oldValue,
418
+ `->`,
419
+ update.newValue,
420
+ `)`
421
+ );
422
+ };
423
+
424
+ // internal/src/set-state/set-atom.ts
425
+ var setAtom = (atom2, next, store) => {
426
+ const target = newest(store);
427
+ const oldValue = readOrComputeValue(atom2, store);
428
+ let newValue = copyMutableIfWithinTransaction(oldValue, atom2, store);
429
+ newValue = become(next)(newValue);
430
+ store.logger.info(`\u{1F4DD}`, `atom`, atom2.key, `set to`, newValue);
431
+ newValue = cacheValue(atom2.key, newValue, atom2.subject, store);
432
+ if (isAtomDefault(atom2.key, store)) {
433
+ markAtomAsNotDefault(atom2.key, store);
434
+ }
435
+ markDone(atom2.key, store);
436
+ evictDownStream(atom2, store);
437
+ const update = { oldValue, newValue };
438
+ if (target.transactionMeta === null || target.transactionMeta.phase === `applying`) {
439
+ emitUpdate(atom2, update, store);
440
+ } else {
441
+ stowUpdate(atom2, update, store);
442
+ }
443
+ };
444
+
445
+ // internal/src/set-state/set-atom-or-selector.ts
446
+ var setAtomOrSelector = (state, value, store) => {
447
+ if (state.type === `selector`) {
448
+ state.set(value);
449
+ } else {
450
+ setAtom(state, value, store);
451
+ }
452
+ };
453
+
454
+ // internal/src/store/deposit.ts
455
+ function deposit(state) {
456
+ const token = {
457
+ key: state.key,
458
+ type: state.type
459
+ };
460
+ if (`family` in state) {
461
+ token.family = state.family;
462
+ }
463
+ return token;
464
+ }
465
+
466
+ // ../rel8/junction/src/junction.ts
467
+ var Junction = class {
468
+ constructor(data, config) {
469
+ this.relations = /* @__PURE__ */ new Map();
470
+ this.contents = /* @__PURE__ */ new Map();
471
+ this.makeContentKey = (a, b) => `${a}:${b}`;
472
+ var _a, _b, _c, _d;
473
+ this.a = data.between[0];
474
+ this.b = data.between[1];
475
+ this.cardinality = data.cardinality;
476
+ if (!(config == null ? void 0 : config.externalStore)) {
477
+ this.relations = new Map((_a = data.relations) == null ? void 0 : _a.map(([a, b]) => [a, new Set(b)]));
478
+ this.contents = new Map(data.contents);
479
+ }
480
+ this.isContent = (_b = config == null ? void 0 : config.isContent) != null ? _b : null;
481
+ if (config == null ? void 0 : config.makeContentKey) {
482
+ this.makeContentKey = config.makeContentKey;
483
+ }
484
+ if (config == null ? void 0 : config.externalStore) {
485
+ const externalStore = config.externalStore;
486
+ this.has = (a, b) => externalStore.has(a, b);
487
+ this.addRelation = (a, b) => {
488
+ externalStore.addRelation(a, b);
489
+ };
490
+ this.deleteRelation = (a, b) => {
491
+ externalStore.deleteRelation(a, b);
492
+ };
493
+ this.replaceRelationsSafely = (a, bs) => {
494
+ externalStore.replaceRelationsSafely(a, bs);
495
+ };
496
+ this.replaceRelationsUnsafely = (a, bs) => {
497
+ externalStore.replaceRelationsUnsafely(a, bs);
498
+ };
499
+ this.getRelatedKeys = (key) => externalStore.getRelatedKeys(key);
500
+ if (externalStore.getContent) {
501
+ this.getContentInternal = (contentKey) => {
502
+ return externalStore.getContent(contentKey);
503
+ };
504
+ this.setContent = (contentKey, content) => {
505
+ externalStore.setContent(contentKey, content);
506
+ };
507
+ this.deleteContent = (contentKey) => {
508
+ externalStore.deleteContent(contentKey);
509
+ };
510
+ }
511
+ for (const [x, ys] of (_c = data.relations) != null ? _c : []) {
512
+ for (const y of ys)
513
+ this.addRelation(x, y);
514
+ }
515
+ for (const [contentKey, content] of (_d = data.contents) != null ? _d : []) {
516
+ this.setContent(contentKey, content);
517
+ }
518
+ }
519
+ }
520
+ getRelatedKeys(key) {
521
+ return this.relations.get(key);
522
+ }
523
+ addRelation(a, b) {
524
+ let aRelations = this.relations.get(a);
525
+ let bRelations = this.relations.get(b);
526
+ if (aRelations) {
527
+ aRelations.add(b);
528
+ } else {
529
+ aRelations = /* @__PURE__ */ new Set([b]);
530
+ this.relations.set(a, aRelations);
531
+ }
532
+ if (bRelations) {
533
+ bRelations.add(a);
534
+ } else {
535
+ bRelations = /* @__PURE__ */ new Set([a]);
536
+ this.relations.set(b, bRelations);
537
+ }
538
+ }
539
+ deleteRelation(a, b) {
540
+ const aRelations = this.relations.get(a);
541
+ if (aRelations) {
542
+ aRelations.delete(b);
543
+ if (aRelations.size === 0) {
544
+ this.relations.delete(a);
545
+ }
546
+ const bRelations = this.relations.get(b);
547
+ if (bRelations) {
548
+ bRelations.delete(a);
549
+ if (bRelations.size === 0) {
550
+ this.relations.delete(b);
551
+ }
552
+ }
553
+ }
554
+ }
555
+ replaceRelationsUnsafely(a, bs) {
556
+ this.relations.set(a, new Set(bs));
557
+ for (const b of bs) {
558
+ const bRelations = /* @__PURE__ */ new Set([a]);
559
+ this.relations.set(b, bRelations);
560
+ }
561
+ }
562
+ replaceRelationsSafely(a, bs) {
563
+ const aRelationsPrev = this.relations.get(a);
564
+ if (aRelationsPrev) {
565
+ for (const b of aRelationsPrev) {
566
+ const bRelations = this.relations.get(b);
567
+ if (bRelations) {
568
+ if (bRelations.size === 1) {
569
+ this.relations.delete(b);
570
+ } else {
571
+ bRelations.delete(a);
572
+ }
573
+ this.contents.delete(this.makeContentKey(a, b));
574
+ }
575
+ }
576
+ }
577
+ this.relations.set(a, new Set(bs));
578
+ for (const b of bs) {
579
+ let bRelations = this.relations.get(b);
580
+ if (bRelations) {
581
+ bRelations.add(a);
582
+ } else {
583
+ bRelations = /* @__PURE__ */ new Set([a]);
584
+ this.relations.set(b, bRelations);
585
+ }
586
+ }
587
+ }
588
+ getContentInternal(contentKey) {
589
+ return this.contents.get(contentKey);
590
+ }
591
+ setContent(contentKey, content) {
592
+ this.contents.set(contentKey, content);
593
+ }
594
+ deleteContent(contentKey) {
595
+ this.contents.delete(contentKey);
596
+ }
597
+ toJSON() {
598
+ return {
599
+ between: [this.a, this.b],
600
+ cardinality: this.cardinality,
601
+ relations: [...this.relations.entries()].map(([a, b]) => [a, [...b]]),
602
+ contents: [...this.contents.entries()]
603
+ };
604
+ }
605
+ set(a, ...rest) {
606
+ var _a;
607
+ const b = typeof rest[0] === `string` ? rest[0] : a[this.b];
608
+ const content = ((_a = rest[1]) != null ? _a : typeof rest[0] === `string`) ? void 0 : rest[0];
609
+ a = typeof a === `string` ? a : a[this.a];
610
+ switch (this.cardinality) {
611
+ case `1:1`: {
612
+ const bPrev = this.getRelatedKey(a);
613
+ if (bPrev && bPrev !== b)
614
+ this.delete(bPrev, a);
615
+ }
616
+ case `1:n`: {
617
+ const aPrev = this.getRelatedKey(b);
618
+ if (aPrev && aPrev !== a)
619
+ this.delete(aPrev, b);
620
+ }
621
+ }
622
+ if (content) {
623
+ const contentKey = this.makeContentKey(a, b);
624
+ this.setContent(contentKey, content);
625
+ }
626
+ this.addRelation(a, b);
627
+ return this;
628
+ }
629
+ delete(x, b) {
630
+ b = typeof b === `string` ? b : x[this.b];
631
+ const a = typeof x === `string` ? x : x[this.a];
632
+ if (a === void 0 && typeof b === `string`) {
633
+ const bRelations = this.getRelatedKeys(b);
634
+ if (bRelations) {
635
+ for (const a2 of bRelations) {
636
+ this.delete(a2, b);
637
+ }
638
+ }
639
+ }
640
+ if (typeof a === `string` && b === void 0) {
641
+ const aRelations = this.getRelatedKeys(a);
642
+ if (aRelations) {
643
+ for (const b2 of aRelations) {
644
+ this.delete(a, b2);
645
+ }
646
+ }
647
+ }
648
+ if (typeof a === `string` && typeof b === `string`) {
649
+ this.deleteRelation(a, b);
650
+ const contentKey = this.makeContentKey(a, b);
651
+ this.deleteContent(contentKey);
652
+ }
653
+ return this;
654
+ }
655
+ getRelatedKey(key) {
656
+ const relations = this.getRelatedKeys(key);
657
+ if (relations) {
658
+ if (relations.size > 1) {
659
+ console.warn(
660
+ `${relations.size} related keys were found for key "${key}": (${[
661
+ ...relations
662
+ ].map((k) => `"${k}"`).join(`, `)}). Only one related key was expected.`
663
+ );
664
+ }
665
+ for (const relation of relations) {
666
+ return relation;
667
+ }
668
+ }
669
+ }
670
+ replaceRelations(a, relations, config) {
671
+ const hasContent = !Array.isArray(relations);
672
+ const bs = hasContent ? Object.keys(relations) : relations;
673
+ if (config == null ? void 0 : config.reckless) {
674
+ this.replaceRelationsUnsafely(a, bs);
675
+ } else {
676
+ this.replaceRelationsSafely(a, bs);
677
+ }
678
+ if (hasContent) {
679
+ for (const b of bs) {
680
+ const contentKey = this.makeContentKey(a, b);
681
+ const content = relations[b];
682
+ this.setContent(contentKey, content);
683
+ }
684
+ }
685
+ return this;
686
+ }
687
+ getContent(a, b) {
688
+ const contentKey = this.makeContentKey(a, b);
689
+ return this.getContentInternal(contentKey);
690
+ }
691
+ getRelationEntries(input) {
692
+ const a = input[this.a];
693
+ const b = input[this.b];
694
+ if (a !== void 0 && b === void 0) {
695
+ const aRelations = this.getRelatedKeys(a);
696
+ if (aRelations) {
697
+ return [...aRelations].map((b2) => {
698
+ var _a;
699
+ return [b2, (_a = this.getContent(a, b2)) != null ? _a : null];
700
+ });
701
+ }
702
+ }
703
+ if (a === void 0 && b !== void 0) {
704
+ const bRelations = this.getRelatedKeys(b);
705
+ if (bRelations) {
706
+ return [...bRelations].map((a2) => {
707
+ var _a;
708
+ return [a2, (_a = this.getContent(a2, b)) != null ? _a : null];
709
+ });
710
+ }
711
+ }
712
+ return [];
713
+ }
714
+ has(a, b) {
715
+ var _a;
716
+ if (b) {
717
+ const setA = this.getRelatedKeys(a);
718
+ return (_a = setA == null ? void 0 : setA.has(b)) != null ? _a : false;
719
+ }
720
+ return this.relations.has(a);
721
+ }
722
+ };
723
+
724
+ // internal/src/store/store.ts
725
+ var Store = class {
726
+ constructor(name, store = null) {
727
+ this.parent = null;
728
+ this.child = null;
729
+ this.valueMap = /* @__PURE__ */ new Map();
730
+ this.atoms = /* @__PURE__ */ new Map();
731
+ this.selectors = /* @__PURE__ */ new Map();
732
+ this.readonlySelectors = /* @__PURE__ */ new Map();
733
+ this.trackers = /* @__PURE__ */ new Map();
734
+ this.families = /* @__PURE__ */ new Map();
735
+ this.timelines = /* @__PURE__ */ new Map();
736
+ this.transactions = /* @__PURE__ */ new Map();
737
+ this.atomsThatAreDefault = /* @__PURE__ */ new Set();
738
+ this.timelineAtoms = new Junction({
739
+ between: [`timelineKey`, `atomKey`],
740
+ cardinality: `1:n`
741
+ });
742
+ this.selectorAtoms = new Junction({
743
+ between: [`selectorKey`, `atomKey`],
744
+ cardinality: `n:n`
745
+ });
746
+ this.selectorGraph = new Junction(
747
+ {
748
+ between: [`upstreamSelectorKey`, `downstreamSelectorKey`],
749
+ cardinality: `n:n`
750
+ },
751
+ {
752
+ makeContentKey: (...keys) => keys.sort().join(`:`)
753
+ }
754
+ );
755
+ this.subject = {
756
+ atomCreation: new Subject(),
757
+ selectorCreation: new Subject(),
758
+ transactionCreation: new Subject(),
759
+ timelineCreation: new Subject(),
760
+ transactionApplying: new StatefulSubject(null),
761
+ operationStatus: new Subject()
762
+ };
763
+ this.operation = { open: false };
764
+ this.transactionMeta = null;
765
+ this.config = {
766
+ name: `IMPLICIT_STORE`
767
+ };
768
+ this.loggers = [
769
+ new AtomIOLogger(`warn`, (_, __, key) => !key.includes(`\u{1F441}\u200D\u{1F5E8}`))
770
+ ];
771
+ this.logger = {
772
+ error: (...messages) => {
773
+ for (const logger of this.loggers)
774
+ logger.error(...messages);
775
+ },
776
+ info: (...messages) => {
777
+ for (const logger of this.loggers)
778
+ logger.info(...messages);
779
+ },
780
+ warn: (...messages) => {
781
+ for (const logger of this.loggers)
782
+ logger.warn(...messages);
783
+ }
784
+ };
785
+ if (store !== null) {
786
+ this.valueMap = new Map(store == null ? void 0 : store.valueMap);
787
+ this.operation = __spreadValues({}, store == null ? void 0 : store.operation);
788
+ this.transactionMeta = (store == null ? void 0 : store.transactionMeta) ? __spreadValues({}, store == null ? void 0 : store.transactionMeta) : null;
789
+ this.config = __spreadProps(__spreadValues({}, store == null ? void 0 : store.config), {
790
+ name
791
+ });
792
+ for (const [, atom2] of store.atoms) {
793
+ atom2.install(this);
794
+ }
795
+ for (const [, selector2] of store.readonlySelectors) {
796
+ selector2.install(this);
797
+ }
798
+ for (const [, selector2] of store.selectors) {
799
+ selector2.install(this);
800
+ }
801
+ for (const [, tx] of store.transactions) {
802
+ tx.install(this);
803
+ }
804
+ for (const [, timeline] of store.timelines) {
805
+ timeline.install(this);
806
+ }
807
+ }
808
+ }
809
+ };
810
+ var IMPLICIT = {
811
+ STORE_INTERNAL: void 0,
812
+ get STORE() {
813
+ var _a;
814
+ return (_a = this.STORE_INTERNAL) != null ? _a : this.STORE_INTERNAL = new Store(`IMPLICIT_STORE`);
815
+ }
816
+ };
817
+ var clearStore = (store) => {
818
+ const { config } = store;
819
+ Object.assign(store, new Store(config.name));
820
+ store.config = config;
821
+ };
822
+
823
+ // internal/src/store/withdraw.ts
824
+ function withdraw(token, store) {
825
+ var _a, _b, _c, _d;
826
+ const target = newest(store);
827
+ const state = (_d = (_c = (_b = (_a = target.atoms.get(token.key)) != null ? _a : target.selectors.get(token.key)) != null ? _b : target.readonlySelectors.get(token.key)) != null ? _c : target.transactions.get(token.key)) != null ? _d : target.timelines.get(token.key);
828
+ if (state) {
829
+ return state;
830
+ }
831
+ return void 0;
832
+ }
833
+
834
+ // internal/src/store/withdraw-new-family-member.ts
835
+ function withdrawNewFamilyMember(token, store) {
836
+ if (token.family) {
837
+ store.logger.info(
838
+ `\u{1F46A}`,
839
+ token.type,
840
+ token.key,
841
+ `creating new family member in store "${store.config.name}"`
842
+ );
843
+ const target = newest(store);
844
+ const family = target.families.get(token.family.key);
845
+ if (family) {
846
+ const jsonSubKey = JSON.parse(token.family.subKey);
847
+ family(jsonSubKey);
848
+ const state = withdraw(token, store);
849
+ return state;
850
+ }
851
+ }
852
+ return void 0;
853
+ }
854
+
855
+ // internal/src/keys.ts
856
+ var isAtomKey = (key, store) => newest(store).atoms.has(key);
857
+ var isSelectorKey = (key, store) => newest(store).selectors.has(key);
858
+ var isReadonlySelectorKey = (key, store) => newest(store).readonlySelectors.has(key);
859
+ var isStateKey = (key, store) => isAtomKey(key, store) || isSelectorKey(key, store) || isReadonlySelectorKey(key, store);
860
+
861
+ // internal/src/selector/get-selector-dependency-keys.ts
862
+ var getSelectorDependencyKeys = (key, store) => {
863
+ const sources = newest(store).selectorGraph.getRelationEntries({ downstreamSelectorKey: key }).filter(([_, { source }]) => source !== key).map(([_, { source }]) => source).filter((source) => isStateKey(source, store));
864
+ return sources;
865
+ };
866
+
867
+ // internal/src/selector/trace-selector-atoms.ts
868
+ var traceSelectorAtoms = (selectorKey, directDependencyKey, store) => {
869
+ const rootKeys = [];
870
+ const indirectDependencyKeys = getSelectorDependencyKeys(
871
+ directDependencyKey,
872
+ store
873
+ );
874
+ let depth = 0;
875
+ while (indirectDependencyKeys.length > 0) {
876
+ const indirectDependencyKey = indirectDependencyKeys.shift();
877
+ ++depth;
878
+ if (depth > 99999) {
879
+ throw new Error(
880
+ `Maximum selector dependency depth exceeded (> 99999) in selector "${selectorKey}". This is likely due to a circular dependency.`
881
+ );
882
+ }
883
+ if (!isAtomKey(indirectDependencyKey, store)) {
884
+ indirectDependencyKeys.push(
885
+ ...getSelectorDependencyKeys(indirectDependencyKey, store)
886
+ );
887
+ } else if (!rootKeys.includes(indirectDependencyKey)) {
888
+ rootKeys.push(indirectDependencyKey);
889
+ }
890
+ }
891
+ return rootKeys;
892
+ };
893
+ var traceAllSelectorAtoms = (selectorKey, store) => {
894
+ const directDependencyKeys = getSelectorDependencyKeys(selectorKey, store);
895
+ return directDependencyKeys.flatMap(
896
+ (depKey) => isAtomKey(depKey, store) ? depKey : traceSelectorAtoms(selectorKey, depKey, store)
897
+ );
898
+ };
899
+
900
+ // internal/src/selector/update-selector-atoms.ts
901
+ var updateSelectorAtoms = (selectorKey, dependency, store) => {
902
+ const target = newest(store);
903
+ if (dependency.type === `atom`) {
904
+ target.selectorAtoms.set({
905
+ selectorKey,
906
+ atomKey: dependency.key
907
+ });
908
+ store.logger.info(
909
+ `\u{1F50D}`,
910
+ `selector`,
911
+ selectorKey,
912
+ `discovers root atom "${dependency.key}"`
913
+ );
914
+ } else {
915
+ const rootKeys = traceSelectorAtoms(selectorKey, dependency.key, store);
916
+ store.logger.info(
917
+ `\u{1F50D}`,
918
+ `selector`,
919
+ selectorKey,
920
+ `discovers root atoms: [ ${rootKeys.map((key) => `"${key}"`).join(`, `)} ]`
921
+ );
922
+ for (const atomKey of rootKeys) {
923
+ target.selectorAtoms = target.selectorAtoms.set({
924
+ selectorKey,
925
+ atomKey
926
+ });
927
+ }
928
+ }
929
+ };
930
+
931
+ // internal/src/selector/register-selector.ts
932
+ var registerSelector = (selectorKey, store) => ({
933
+ get: (dependency) => {
934
+ const target = newest(store);
935
+ const alreadyRegistered = target.selectorGraph.getRelationEntries({ downstreamSelectorKey: selectorKey }).some(([_, { source }]) => source === dependency.key);
936
+ const dependencyState = withdraw(dependency, store);
937
+ if (dependencyState === void 0) {
938
+ throw new Error(
939
+ `State "${dependency.key}" not found in this store. Did you forget to initialize with the "atom" or "selector" function?`
940
+ );
941
+ }
942
+ const dependencyValue = readOrComputeValue(dependencyState, store);
943
+ store.logger.info(
944
+ `\u{1F50C}`,
945
+ `selector`,
946
+ selectorKey,
947
+ `registers dependency ( "${dependency.key}" =`,
948
+ dependencyValue,
949
+ `)`
950
+ );
951
+ if (!alreadyRegistered) {
952
+ target.selectorGraph.set(
953
+ {
954
+ upstreamSelectorKey: dependency.key,
955
+ downstreamSelectorKey: selectorKey
956
+ },
957
+ {
958
+ source: dependency.key
959
+ }
960
+ );
961
+ }
962
+ updateSelectorAtoms(selectorKey, dependency, store);
963
+ return dependencyValue;
964
+ },
965
+ set: (stateToken, newValue) => {
966
+ const state = withdraw(stateToken, store);
967
+ if (state === void 0) {
968
+ throw new Error(
969
+ `State "${stateToken.key}" not found in this store. Did you forget to initialize with the "atom" or "selector" function?`
970
+ );
971
+ }
972
+ setAtomOrSelector(state, newValue, store);
973
+ }
974
+ });
975
+
976
+ // internal/src/selector/create-read-write-selector.ts
977
+ var createReadWriteSelector = (options, family, store) => {
978
+ const target = newest(store);
979
+ const subject = new Subject();
980
+ const { get, set } = registerSelector(options.key, store);
981
+ const getSelf = () => {
982
+ const value = options.get({ get });
983
+ cacheValue(options.key, value, subject, store);
984
+ return value;
985
+ };
986
+ const setSelf = (next) => {
987
+ const oldValue = getSelf();
988
+ const newValue = become(next)(oldValue);
989
+ store.logger.info(
990
+ `\u{1F4DD}`,
991
+ `selector`,
992
+ options.key,
993
+ `set (`,
994
+ oldValue,
995
+ `->`,
996
+ newValue,
997
+ `)`
998
+ );
999
+ cacheValue(options.key, newValue, subject, store);
1000
+ markDone(options.key, store);
1001
+ if (target.transactionMeta === null) {
1002
+ subject.next({ newValue, oldValue });
1003
+ }
1004
+ options.set({ get, set }, newValue);
1005
+ };
1006
+ const mySelector = __spreadValues(__spreadProps(__spreadValues({}, options), {
1007
+ subject,
1008
+ install: (s) => createSelector(options, family, s),
1009
+ get: getSelf,
1010
+ set: setSelf,
1011
+ type: `selector`
1012
+ }), family && { family });
1013
+ target.selectors.set(options.key, mySelector);
1014
+ const initialValue = getSelf();
1015
+ store.logger.info(`\u2728`, mySelector.type, mySelector.key, `=`, initialValue);
1016
+ const token = {
1017
+ key: options.key,
1018
+ type: `selector`
1019
+ };
1020
+ if (family) {
1021
+ token.family = family;
1022
+ }
1023
+ store.subject.selectorCreation.next(token);
1024
+ return token;
1025
+ };
1026
+
1027
+ // internal/src/selector/create-readonly-selector.ts
1028
+ var createReadonlySelector = (options, family, store) => {
1029
+ const target = newest(store);
1030
+ const subject = new Subject();
1031
+ const { get } = registerSelector(options.key, store);
1032
+ const getSelf = () => {
1033
+ const value = options.get({ get });
1034
+ cacheValue(options.key, value, subject, store);
1035
+ return value;
1036
+ };
1037
+ const readonlySelector = __spreadValues(__spreadProps(__spreadValues({}, options), {
1038
+ subject,
1039
+ install: (s) => createSelector(options, family, s),
1040
+ get: getSelf,
1041
+ type: `readonly_selector`
1042
+ }), family && { family });
1043
+ target.readonlySelectors.set(options.key, readonlySelector);
1044
+ const initialValue = getSelf();
1045
+ store.logger.info(
1046
+ `\u2728`,
1047
+ readonlySelector.type,
1048
+ readonlySelector.key,
1049
+ `=`,
1050
+ initialValue
1051
+ );
1052
+ const token = {
1053
+ key: options.key,
1054
+ type: `readonly_selector`
1055
+ };
1056
+ if (family) {
1057
+ token.family = family;
1058
+ }
1059
+ store.subject.selectorCreation.next(token);
1060
+ return token;
1061
+ };
1062
+
1063
+ // internal/src/selector/create-selector.ts
1064
+ function createSelector(options, family, store) {
1065
+ const target = newest(store);
1066
+ const existingWritable = target.selectors.get(options.key);
1067
+ const existingReadonly = target.readonlySelectors.get(options.key);
1068
+ if (existingWritable || existingReadonly) {
1069
+ store.logger.error(
1070
+ `\u274C`,
1071
+ existingReadonly ? `readonly_selector` : `selector`,
1072
+ options.key,
1073
+ `Tried to create selector, but it already exists in the store. (Ignore if you are in development using hot module replacement.)`
1074
+ );
1075
+ }
1076
+ if (`set` in options) {
1077
+ return createReadWriteSelector(options, family, store);
1078
+ }
1079
+ return createReadonlySelector(options, family, store);
1080
+ }
1081
+
1082
+ // internal/src/selector/delete-selector.ts
1083
+ function deleteSelector(selectorToken, store) {
1084
+ const target = newest(store);
1085
+ const { key } = selectorToken;
1086
+ switch (selectorToken.type) {
1087
+ case `selector`:
1088
+ target.selectors.delete(key);
1089
+ break;
1090
+ case `readonly_selector`:
1091
+ target.readonlySelectors.delete(key);
1092
+ break;
1093
+ }
1094
+ target.valueMap.delete(key);
1095
+ target.selectorAtoms.delete(key);
1096
+ const downstreamTokens = target.selectorGraph.getRelationEntries({ upstreamSelectorKey: key }).filter(([_, { source }]) => source === key).map(
1097
+ ([downstreamSelectorKey]) => {
1098
+ var _a;
1099
+ return (_a = target.selectors.get(downstreamSelectorKey)) != null ? _a : target.readonlySelectors.get(downstreamSelectorKey);
1100
+ }
1101
+ );
1102
+ for (const downstreamToken of downstreamTokens) {
1103
+ if (downstreamToken) {
1104
+ deleteSelector(downstreamToken, store);
1105
+ }
1106
+ }
1107
+ target.selectorGraph.delete(key);
1108
+ store.logger.info(`\u{1F525}`, selectorToken.type, `${key}`, `deleted`);
1109
+ }
1110
+
1111
+ // internal/src/subscribe/recall-state.ts
1112
+ var recallState = (state, store) => {
1113
+ const target = newest(store);
1114
+ if (!target.operation.open) {
1115
+ return target.valueMap.get(state.key);
1116
+ }
1117
+ return target.operation.prev.get(state.key);
1118
+ };
1119
+
1120
+ // internal/src/subscribe/subscribe-to-root-atoms.ts
1121
+ var subscribeToRootAtoms = (state, store) => {
1122
+ const dependencySubscriptions = `default` in state ? null : traceAllSelectorAtoms(state.key, store).map((atomKey) => {
1123
+ const atom2 = store.atoms.get(atomKey);
1124
+ if (atom2 === void 0) {
1125
+ throw new Error(
1126
+ `Atom "${atomKey}", a dependency of selector "${state.key}", not found in store "${store.config.name}".`
1127
+ );
1128
+ }
1129
+ return atom2.subject.subscribe(
1130
+ `${state.type}:${state.key}`,
1131
+ (atomChange) => {
1132
+ store.logger.info(
1133
+ `\u{1F4E2}`,
1134
+ state.type,
1135
+ state.key,
1136
+ `root`,
1137
+ atomKey,
1138
+ `went`,
1139
+ atomChange.oldValue,
1140
+ `->`,
1141
+ atomChange.newValue
1142
+ );
1143
+ const oldValue = recallState(state, store);
1144
+ const newValue = readOrComputeValue(state, store);
1145
+ store.logger.info(
1146
+ `\u2728`,
1147
+ state.type,
1148
+ state.key,
1149
+ `went`,
1150
+ oldValue,
1151
+ `->`,
1152
+ newValue
1153
+ );
1154
+ state.subject.next({ newValue, oldValue });
1155
+ }
1156
+ );
1157
+ });
1158
+ return dependencySubscriptions;
1159
+ };
1160
+
1161
+ // internal/src/subscribe/subscribe-to-state.ts
1162
+ function subscribeToState(token, handleUpdate, key, store) {
1163
+ const state = withdraw(token, store);
1164
+ if (state === void 0) {
1165
+ throw new Error(
1166
+ `State "${token.key}" not found in this store. Did you forget to initialize with the "atom" or "selector" function?`
1167
+ );
1168
+ }
1169
+ const unsubFunction = state.subject.subscribe(key, handleUpdate);
1170
+ store.logger.info(`\u{1F440}`, state.type, state.key, `Adding subscription "${key}"`);
1171
+ const dependencyUnsubFunctions = state.type !== `atom` ? subscribeToRootAtoms(state, store) : null;
1172
+ const unsubscribe = dependencyUnsubFunctions === null ? () => {
1173
+ store.logger.info(
1174
+ `\u{1F648}`,
1175
+ state.type,
1176
+ state.key,
1177
+ `Removing subscription "${key}"`
1178
+ );
1179
+ unsubFunction();
1180
+ } : () => {
1181
+ store.logger.info(
1182
+ `\u{1F648}`,
1183
+ state.type,
1184
+ state.key,
1185
+ `Removing subscription "${key}"`
1186
+ );
1187
+ unsubFunction();
1188
+ for (const unsubFromDependency of dependencyUnsubFunctions) {
1189
+ unsubFromDependency();
1190
+ }
1191
+ };
1192
+ return unsubscribe;
1193
+ }
1194
+
1195
+ // internal/src/subscribe/subscribe-to-timeline.ts
1196
+ var subscribeToTimeline = (token, handleUpdate, key, store) => {
1197
+ const tl = withdraw(token, store);
1198
+ if (tl === void 0) {
1199
+ throw new Error(
1200
+ `Cannot subscribe to timeline "${token.key}": timeline not found in store "${store.config.name}".`
1201
+ );
1202
+ }
1203
+ store.logger.info(`\u{1F440}`, `timeline`, token.key, `Adding subscription "${key}"`);
1204
+ const unsubscribe = tl.subject.subscribe(key, handleUpdate);
1205
+ return () => {
1206
+ store.logger.info(
1207
+ `\u{1F648}`,
1208
+ `timeline`,
1209
+ token.key,
1210
+ `Removing subscription "${key}" from timeline`
1211
+ );
1212
+ unsubscribe();
1213
+ };
1214
+ };
1215
+
1216
+ // internal/src/subscribe/subscribe-to-transaction.ts
1217
+ var subscribeToTransaction = (token, handleUpdate, key, store) => {
1218
+ const tx = withdraw(token, store);
1219
+ if (tx === void 0) {
1220
+ throw new Error(
1221
+ `Cannot subscribe to transaction "${token.key}": transaction not found in store "${store.config.name}".`
1222
+ );
1223
+ }
1224
+ store.logger.info(
1225
+ `\u{1F440}`,
1226
+ `transaction`,
1227
+ token.key,
1228
+ `Adding subscription "${key}"`
1229
+ );
1230
+ const unsubscribe = tx.subject.subscribe(key, handleUpdate);
1231
+ return () => {
1232
+ store.logger.info(
1233
+ `\u{1F648}`,
1234
+ `transaction`,
1235
+ token.key,
1236
+ `Removing subscription "${key}"`
1237
+ );
1238
+ unsubscribe();
1239
+ };
1240
+ };
1241
+
1242
+ // internal/src/mutable/tracker.ts
1243
+ var Tracker = class {
1244
+ constructor(mutableState, store) {
1245
+ this.unsubscribeFromInnerValue = null;
1246
+ this.mutableState = mutableState;
1247
+ const target = newest(store);
1248
+ this.latestUpdateState = this.initializeState(mutableState, target);
1249
+ this.observeCore(mutableState, this.latestUpdateState, target);
1250
+ this.updateCore(mutableState, this.latestUpdateState, target);
1251
+ target.trackers.set(mutableState.key, this);
1252
+ }
1253
+ initializeState(mutableState, store) {
1254
+ const latestUpdateStateKey = `*${mutableState.key}`;
1255
+ deleteAtom({ type: `atom`, key: latestUpdateStateKey }, store);
1256
+ const familyMetaData = mutableState.family ? {
1257
+ key: `*${mutableState.family.key}`,
1258
+ subKey: mutableState.family.subKey
1259
+ } : void 0;
1260
+ const latestUpdateState = createAtom(
1261
+ {
1262
+ key: latestUpdateStateKey,
1263
+ default: null
1264
+ },
1265
+ familyMetaData,
1266
+ store
1267
+ );
1268
+ return latestUpdateState;
1269
+ }
1270
+ observeCore(mutableState, latestUpdateState, store) {
1271
+ const originalInnerValue = getState(mutableState, store);
1272
+ const target = newest(store);
1273
+ this.unsubscribeFromInnerValue = originalInnerValue.subscribe(
1274
+ `tracker:${store.config.name}:${target.transactionMeta === null ? `main` : target.transactionMeta.update.key}`,
1275
+ (update) => {
1276
+ const unsubscribe = store.subject.operationStatus.subscribe(
1277
+ mutableState.key,
1278
+ () => {
1279
+ unsubscribe();
1280
+ setState(latestUpdateState, update, store);
1281
+ }
1282
+ );
1283
+ }
1284
+ );
1285
+ subscribeToState(
1286
+ mutableState,
1287
+ (update) => {
1288
+ var _a;
1289
+ if (update.newValue !== update.oldValue) {
1290
+ (_a = this.unsubscribeFromInnerValue) == null ? void 0 : _a.call(this);
1291
+ const target2 = newest(store);
1292
+ this.unsubscribeFromInnerValue = update.newValue.subscribe(
1293
+ `tracker:${store.config.name}:${target2.transactionMeta === null ? `main` : target2.transactionMeta.update.key}`,
1294
+ (update2) => {
1295
+ const unsubscribe = store.subject.operationStatus.subscribe(
1296
+ mutableState.key,
1297
+ () => {
1298
+ unsubscribe();
1299
+ setState(latestUpdateState, update2, store);
1300
+ }
1301
+ );
1302
+ }
1303
+ );
1304
+ }
1305
+ },
1306
+ `${store.config.name}: tracker observing inner value`,
1307
+ store
1308
+ );
1309
+ }
1310
+ updateCore(mutableState, latestUpdateState, store) {
1311
+ subscribeToState(
1312
+ latestUpdateState,
1313
+ ({ newValue, oldValue }) => {
1314
+ const timelineId = store.timelineAtoms.getRelatedKey(
1315
+ latestUpdateState.key
1316
+ );
1317
+ if (timelineId) {
1318
+ const timelineData = store.timelines.get(timelineId);
1319
+ if (timelineData == null ? void 0 : timelineData.timeTraveling) {
1320
+ const unsubscribe2 = subscribeToTimeline(
1321
+ { key: timelineId, type: `timeline` },
1322
+ (update) => {
1323
+ unsubscribe2();
1324
+ setState(
1325
+ mutableState,
1326
+ (transceiver) => {
1327
+ if (update === `redo` && newValue) {
1328
+ transceiver.do(newValue);
1329
+ } else if (update === `undo` && oldValue) {
1330
+ transceiver.undo(oldValue);
1331
+ }
1332
+ return transceiver;
1333
+ },
1334
+ store
1335
+ );
1336
+ },
1337
+ `${mutableState.key}: tracker observing timeline`,
1338
+ store
1339
+ );
1340
+ return;
1341
+ }
1342
+ }
1343
+ const unsubscribe = store.subject.operationStatus.subscribe(
1344
+ latestUpdateState.key,
1345
+ () => {
1346
+ unsubscribe();
1347
+ const mutable = getState(mutableState, store);
1348
+ const updateNumber = mutable.getUpdateNumber(newValue);
1349
+ const eventOffset = updateNumber - mutable.cacheUpdateNumber;
1350
+ if (newValue && eventOffset === 1) {
1351
+ setState(
1352
+ mutableState,
1353
+ (transceiver) => (transceiver.do(newValue), transceiver),
1354
+ store
1355
+ );
1356
+ }
1357
+ }
1358
+ );
1359
+ },
1360
+ `${store.config.name}: tracker observing latest update`,
1361
+ store
1362
+ );
1363
+ }
1364
+ };
1365
+
1366
+ // internal/src/mutable/create-mutable-atom.ts
1367
+ function createMutableAtom(options, store) {
1368
+ store.logger.info(
1369
+ `\u{1F527}`,
1370
+ `atom`,
1371
+ options.key,
1372
+ `creating in store "${store.config.name}"`
1373
+ );
1374
+ const coreState = createAtom(options, void 0, store);
1375
+ new Tracker(coreState, store);
1376
+ const jsonState = selectJson(coreState, options, store);
1377
+ const target = newest(store);
1378
+ subscribeToState(
1379
+ jsonState,
1380
+ () => {
1381
+ const trackerHasBeenInitialized = newest(store).trackers.has(coreState.key);
1382
+ if (!trackerHasBeenInitialized) {
1383
+ new Tracker(coreState, store);
1384
+ }
1385
+ },
1386
+ `tracker-initializer:${store == null ? void 0 : store.config.name}:${target.transactionMeta === null ? `main` : `${target.transactionMeta.update.key}`}`,
1387
+ store
1388
+ );
1389
+ return coreState;
1390
+ }
1391
+
1392
+ // internal/src/families/create-atom-family.ts
1393
+ function createAtomFamily(options, store) {
1394
+ const subject = new Subject();
1395
+ const atomFamily = Object.assign(
1396
+ (key) => {
1397
+ const subKey = stringifyJson(key);
1398
+ const family = { key: options.key, subKey };
1399
+ const fullKey = `${options.key}(${subKey})`;
1400
+ const existing = withdraw({ key: fullKey, type: `atom` }, store);
1401
+ let token;
1402
+ if (existing) {
1403
+ token = deposit(existing);
1404
+ } else {
1405
+ const individualOptions = {
1406
+ key: fullKey,
1407
+ default: options.default instanceof Function ? options.default(key) : options.default
1408
+ };
1409
+ if (options.effects) {
1410
+ individualOptions.effects = options.effects(key);
1411
+ }
1412
+ token = createAtom(individualOptions, family, store);
1413
+ subject.next(token);
1414
+ }
1415
+ return token;
1416
+ },
1417
+ {
1418
+ key: options.key,
1419
+ type: `atom_family`,
1420
+ subject
1421
+ }
1422
+ );
1423
+ const target = newest(store);
1424
+ target.families.set(options.key, atomFamily);
1425
+ return atomFamily;
1426
+ }
1427
+
1428
+ // internal/src/families/create-readonly-selector-family.ts
1429
+ function createReadonlySelectorFamily(options, store) {
1430
+ const subject = new Subject();
1431
+ return Object.assign(
1432
+ (key) => {
1433
+ const target = newest(store);
1434
+ const subKey = stringifyJson(key);
1435
+ const family = { key: options.key, subKey };
1436
+ const fullKey = `${options.key}(${subKey})`;
1437
+ const existing = target.readonlySelectors.get(fullKey);
1438
+ if (existing) {
1439
+ return deposit(existing);
1440
+ }
1441
+ return createSelector(
1442
+ {
1443
+ key: fullKey,
1444
+ get: options.get(key)
1445
+ },
1446
+ family,
1447
+ store
1448
+ );
1449
+ },
1450
+ {
1451
+ key: options.key,
1452
+ type: `readonly_selector_family`,
1453
+ subject
1454
+ }
1455
+ );
1456
+ }
1457
+
1458
+ // internal/src/families/create-selector-family.ts
1459
+ function createSelectorFamily(options, store) {
1460
+ const isReadonly = !(`set` in options);
1461
+ if (isReadonly) {
1462
+ return createReadonlySelectorFamily(options, store);
1463
+ }
1464
+ const target = newest(store);
1465
+ const subject = new Subject();
1466
+ const selectorFamily = Object.assign(
1467
+ (key) => {
1468
+ const subKey = stringifyJson(key);
1469
+ const family = { key: options.key, subKey };
1470
+ const fullKey = `${options.key}(${subKey})`;
1471
+ const existing = target.selectors.get(fullKey);
1472
+ if (existing) {
1473
+ return deposit(existing);
1474
+ }
1475
+ const token = createSelector(
1476
+ {
1477
+ key: fullKey,
1478
+ get: options.get(key),
1479
+ set: options.set(key)
1480
+ },
1481
+ family,
1482
+ store
1483
+ );
1484
+ subject.next(token);
1485
+ return token;
1486
+ },
1487
+ {
1488
+ key: options.key,
1489
+ type: `selector_family`
1490
+ }
1491
+ );
1492
+ target.families.set(options.key, selectorFamily);
1493
+ return selectorFamily;
1494
+ }
1495
+
1496
+ // internal/src/mutable/tracker-family.ts
1497
+ var FamilyTracker = class {
1498
+ constructor(findMutableState, store) {
1499
+ this.findLatestUpdateState = createAtomFamily(
1500
+ {
1501
+ key: `*${findMutableState.key}`,
1502
+ default: null
1503
+ },
1504
+ store
1505
+ );
1506
+ this.findMutableState = findMutableState;
1507
+ this.findMutableState.subject.subscribe(
1508
+ `store=${store.config.name}::tracker-atom-family`,
1509
+ (atomToken) => {
1510
+ if (atomToken.family) {
1511
+ const key = parseJson(atomToken.family.subKey);
1512
+ this.findLatestUpdateState(key);
1513
+ new Tracker(atomToken, store);
1514
+ }
1515
+ }
1516
+ );
1517
+ this.findLatestUpdateState.subject.subscribe(
1518
+ `store=${store.config.name}::tracker-atom-family`,
1519
+ (atomToken) => {
1520
+ if (atomToken.family) {
1521
+ const key = parseJson(atomToken.family.subKey);
1522
+ const mutableAtomToken = this.findMutableState(key);
1523
+ new Tracker(mutableAtomToken, store);
1524
+ }
1525
+ }
1526
+ );
1527
+ }
1528
+ };
1529
+
1530
+ // internal/src/mutable/create-mutable-atom-family.ts
1531
+ function createMutableAtomFamily(options, store) {
1532
+ const coreFamily = Object.assign(
1533
+ createAtomFamily(options, store),
1534
+ options
1535
+ );
1536
+ selectJsonFamily(coreFamily, options);
1537
+ new FamilyTracker(coreFamily, store);
1538
+ return coreFamily;
1539
+ }
1540
+
1541
+ // internal/src/mutable/transceiver.ts
1542
+ function isTransceiver(value) {
1543
+ return typeof value === `object` && value !== null && `do` in value && `undo` in value && `subscribe` in value;
1544
+ }
1545
+
1546
+ // internal/src/atom/is-default.ts
1547
+ var isAtomDefault = (key, store) => {
1548
+ const core = newest(store);
1549
+ return core.atomsThatAreDefault.has(key);
1550
+ };
1551
+ var markAtomAsDefault = (key, store) => {
1552
+ const core = newest(store);
1553
+ core.atomsThatAreDefault = new Set(core.atomsThatAreDefault).add(key);
1554
+ };
1555
+ var markAtomAsNotDefault = (key, store) => {
1556
+ const core = newest(store);
1557
+ core.atomsThatAreDefault = new Set(newest(store).atomsThatAreDefault);
1558
+ core.atomsThatAreDefault.delete(key);
1559
+ };
1560
+
1561
+ // internal/src/atom/create-atom.ts
1562
+ function createAtom(options, family, store) {
1563
+ store.logger.info(
1564
+ `\u{1F528}`,
1565
+ `atom`,
1566
+ options.key,
1567
+ `creating in store "${store.config.name}"`
1568
+ );
1569
+ const target = newest(store);
1570
+ const existing = target.atoms.get(options.key);
1571
+ if (existing) {
1572
+ store.logger.error(
1573
+ `\u274C`,
1574
+ `atom`,
1575
+ options.key,
1576
+ `Tried to create atom, but it already exists in the store.`,
1577
+ `(Ignore if you are in development using hot module replacement.)`
1578
+ );
1579
+ return deposit(existing);
1580
+ }
1581
+ const subject = new Subject();
1582
+ const newAtom = __spreadValues(__spreadProps(__spreadValues({}, options), {
1583
+ type: `atom`,
1584
+ install: (store2) => {
1585
+ store2.logger.info(
1586
+ `\u{1F6E0}\uFE0F`,
1587
+ `atom`,
1588
+ options.key,
1589
+ `installing in store "${store2.config.name}"`
1590
+ );
1591
+ return `mutable` in options ? createMutableAtom(options, store2) : createAtom(options, void 0, store2);
1592
+ },
1593
+ subject
1594
+ }), family && { family });
1595
+ let initialValue = options.default;
1596
+ if (options.default instanceof Function) {
1597
+ initialValue = options.default();
1598
+ }
1599
+ target.atoms.set(newAtom.key, newAtom);
1600
+ markAtomAsDefault(options.key, store);
1601
+ cacheValue(options.key, initialValue, subject, store);
1602
+ const token = deposit(newAtom);
1603
+ if (options.effects) {
1604
+ let effectIndex = 0;
1605
+ const cleanupFunctions = [];
1606
+ for (const effect of options.effects) {
1607
+ const cleanup = effect({
1608
+ setSelf: (next) => setState(token, next, store),
1609
+ onSet: (handle) => subscribeToState(token, handle, `effect[${effectIndex}]`, store)
1610
+ });
1611
+ if (cleanup) {
1612
+ cleanupFunctions.push(cleanup);
1613
+ }
1614
+ ++effectIndex;
1615
+ }
1616
+ newAtom.cleanup = () => {
1617
+ for (const cleanup of cleanupFunctions) {
1618
+ cleanup();
1619
+ }
1620
+ };
1621
+ }
1622
+ store.subject.atomCreation.next(token);
1623
+ return token;
1624
+ }
1625
+
1626
+ // internal/src/atom/delete-atom.ts
1627
+ function deleteAtom(atomToken, store) {
1628
+ var _a, _b;
1629
+ const target = newest(store);
1630
+ const { key } = atomToken;
1631
+ const atom2 = target.atoms.get(key);
1632
+ if (!atom2) {
1633
+ store.logger.error(
1634
+ `\u274C`,
1635
+ `atom`,
1636
+ `${key}`,
1637
+ `Tried to delete atom, but it does not exist in the store.`
1638
+ );
1639
+ }
1640
+ (_a = atom2 == null ? void 0 : atom2.cleanup) == null ? void 0 : _a.call(atom2);
1641
+ target.atoms.delete(key);
1642
+ target.valueMap.delete(key);
1643
+ const selectorKeys = target.selectorAtoms.getRelatedKeys(key);
1644
+ if (selectorKeys) {
1645
+ for (const selectorKey of selectorKeys) {
1646
+ const token = (_b = target.selectors.get(selectorKey)) != null ? _b : target.readonlySelectors.get(selectorKey);
1647
+ if (token) {
1648
+ deleteSelector(token, store);
1649
+ }
1650
+ }
1651
+ }
1652
+ target.selectorAtoms.delete(key);
1653
+ target.atomsThatAreDefault.delete(key);
1654
+ target.timelineAtoms.delete(key);
1655
+ store.logger.info(`\u{1F525}`, `atom`, `${key}`, `deleted`);
1656
+ }
1657
+
1658
+ // internal/src/lazy-map.ts
1659
+ var LazyMap = class extends Map {
1660
+ constructor(source) {
1661
+ super();
1662
+ this.source = source;
1663
+ this.deleted = /* @__PURE__ */ new Set();
1664
+ }
1665
+ get(key) {
1666
+ const has = super.has(key);
1667
+ if (has) {
1668
+ return super.get(key);
1669
+ }
1670
+ if (!this.deleted.has(key) && this.source.has(key)) {
1671
+ const value = this.source.get(key);
1672
+ return value;
1673
+ }
1674
+ return void 0;
1675
+ }
1676
+ set(key, value) {
1677
+ this.deleted.delete(key);
1678
+ return super.set(key, value);
1679
+ }
1680
+ hasOwn(key) {
1681
+ return super.has(key);
1682
+ }
1683
+ has(key) {
1684
+ return !this.deleted.has(key) && (super.has(key) || this.source.has(key));
1685
+ }
1686
+ delete(key) {
1687
+ this.deleted.add(key);
1688
+ return super.delete(key);
1689
+ }
1690
+ };
1691
+
1692
+ // internal/src/not-found-error.ts
1693
+ var capitalize = (str) => str[0].toUpperCase() + str.slice(1);
1694
+ function prettyPrintTokenType(token) {
1695
+ if (token.type === `readonly_selector`) {
1696
+ return `Readonly Selector`;
1697
+ }
1698
+ return capitalize(token.type);
1699
+ }
1700
+ var NotFoundError = class extends Error {
1701
+ constructor(token, store) {
1702
+ super(
1703
+ `${prettyPrintTokenType(token)} "${token.key}" not found in store "${store.config.name}".`
1704
+ );
1705
+ }
1706
+ };
1707
+
1708
+ // internal/src/timeline/add-atom-to-timeline.ts
1709
+ var addAtomToTimeline = (atomToken, tl, store) => {
1710
+ const atom2 = withdraw(atomToken, store);
1711
+ if (atom2 === void 0) {
1712
+ throw new Error(
1713
+ `Cannot subscribe to atom "${atomToken.key}" because it has not been initialized in store "${store.config.name}"`
1714
+ );
1715
+ }
1716
+ atom2.subject.subscribe(`timeline`, (update) => {
1717
+ var _a, _b, _c, _d, _e, _f;
1718
+ const target = newest(store);
1719
+ const currentSelectorKey = store.operation.open && store.operation.token.type === `selector` ? store.operation.token.key : null;
1720
+ const currentSelectorTime = store.operation.open && store.operation.token.type === `selector` ? store.operation.time : null;
1721
+ const currentTransactionKey = (_a = target.subject.transactionApplying.state) == null ? void 0 : _a.update.key;
1722
+ const currentTransactionTime = (_b = target.subject.transactionApplying.state) == null ? void 0 : _b.time;
1723
+ store.logger.info(
1724
+ `\u23F3`,
1725
+ `timeline`,
1726
+ tl.key,
1727
+ `atom`,
1728
+ atomToken.key,
1729
+ `went`,
1730
+ update.oldValue,
1731
+ `->`,
1732
+ update.newValue,
1733
+ currentTransactionKey ? `in transaction "${currentTransactionKey}"` : currentSelectorKey ? `in selector "${currentSelectorKey}"` : ``
1734
+ );
1735
+ if (tl.timeTraveling === null) {
1736
+ if (tl.selectorTime && tl.selectorTime !== currentSelectorTime) {
1737
+ const mostRecentUpdate = tl.history.at(-1);
1738
+ if (mostRecentUpdate === void 0) {
1739
+ throw new Error(
1740
+ `Timeline "${tl.key}" has a selectorTime, but no history. This is most likely a bug in AtomIO.`
1741
+ );
1742
+ }
1743
+ }
1744
+ if (currentTransactionKey) {
1745
+ const currentTransaction = withdraw(
1746
+ { key: currentTransactionKey, type: `transaction` },
1747
+ store
1748
+ );
1749
+ if (currentTransaction === void 0) {
1750
+ throw new Error(
1751
+ `Transaction "${currentTransactionKey}" not found in store "${store.config.name}". This is surprising, because we are in the application phase of "${currentTransactionKey}".`
1752
+ );
1753
+ }
1754
+ if (tl.transactionKey !== currentTransactionKey) {
1755
+ if (tl.transactionKey) {
1756
+ store.logger.error(
1757
+ `\u{1F41E}`,
1758
+ `timeline`,
1759
+ tl.key,
1760
+ `unable to resolve transaction "${tl.transactionKey}. This is probably a bug in AtomIO.`
1761
+ );
1762
+ }
1763
+ tl.transactionKey = currentTransactionKey;
1764
+ const unsubscribe = currentTransaction.subject.subscribe(
1765
+ `timeline:${tl.key}`,
1766
+ (update2) => {
1767
+ var _a2, _b2;
1768
+ unsubscribe();
1769
+ if (tl.timeTraveling === null && currentTransactionTime) {
1770
+ if (tl.at !== tl.history.length) {
1771
+ tl.history.splice(tl.at);
1772
+ }
1773
+ const filterUpdates = (updates2) => updates2.filter((updateFromTx) => {
1774
+ const target2 = newest(store);
1775
+ if (`updates` in updateFromTx) {
1776
+ return true;
1777
+ }
1778
+ const atomOrFamilyKeys = target2.timelineAtoms.getRelatedKeys(tl.key);
1779
+ return atomOrFamilyKeys ? [...atomOrFamilyKeys].some(
1780
+ (key) => {
1781
+ var _a3;
1782
+ return key === updateFromTx.key || key === ((_a3 = updateFromTx.family) == null ? void 0 : _a3.key);
1783
+ }
1784
+ ) : false;
1785
+ }).map((updateFromTx) => {
1786
+ if (`updates` in updateFromTx) {
1787
+ return __spreadProps(__spreadValues({}, updateFromTx), {
1788
+ updates: filterUpdates(updateFromTx.updates)
1789
+ });
1790
+ }
1791
+ return updateFromTx;
1792
+ });
1793
+ const updates = filterUpdates(update2.updates);
1794
+ const timelineTransactionUpdate = __spreadProps(__spreadValues({
1795
+ type: `transaction_update`,
1796
+ timestamp: currentTransactionTime
1797
+ }, update2), {
1798
+ updates
1799
+ });
1800
+ const willCapture = (_b2 = (_a2 = tl.shouldCapture) == null ? void 0 : _a2.call(tl, timelineTransactionUpdate, tl)) != null ? _b2 : true;
1801
+ if (willCapture) {
1802
+ tl.history.push(timelineTransactionUpdate);
1803
+ tl.at = tl.history.length;
1804
+ tl.subject.next(timelineTransactionUpdate);
1805
+ }
1806
+ }
1807
+ tl.transactionKey = null;
1808
+ store.logger.info(
1809
+ `\u231B`,
1810
+ `timeline`,
1811
+ tl.key,
1812
+ `got a transaction_update "${update2.key}"`
1813
+ );
1814
+ }
1815
+ );
1816
+ }
1817
+ } else if (currentSelectorKey && currentSelectorTime) {
1818
+ let latestUpdate = tl.history.at(-1);
1819
+ if (currentSelectorTime !== tl.selectorTime) {
1820
+ latestUpdate = {
1821
+ type: `selector_update`,
1822
+ timestamp: currentSelectorTime,
1823
+ key: currentSelectorKey,
1824
+ atomUpdates: []
1825
+ };
1826
+ latestUpdate.atomUpdates.push(__spreadValues({
1827
+ key: atom2.key,
1828
+ type: `atom_update`
1829
+ }, update));
1830
+ if (tl.at !== tl.history.length) {
1831
+ tl.history.splice(tl.at);
1832
+ }
1833
+ tl.history.push(latestUpdate);
1834
+ store.logger.info(
1835
+ `\u231B`,
1836
+ `timeline`,
1837
+ tl.key,
1838
+ `got a selector_update "${currentSelectorKey}" with`,
1839
+ latestUpdate.atomUpdates.map((atomUpdate) => atomUpdate.key)
1840
+ );
1841
+ tl.at = tl.history.length;
1842
+ tl.selectorTime = currentSelectorTime;
1843
+ } else {
1844
+ if ((latestUpdate == null ? void 0 : latestUpdate.type) === `selector_update`) {
1845
+ latestUpdate.atomUpdates.push(__spreadValues({
1846
+ key: atom2.key,
1847
+ type: `atom_update`
1848
+ }, update));
1849
+ store.logger.info(
1850
+ `\u231B`,
1851
+ `timeline`,
1852
+ tl.key,
1853
+ `set selector_update "${currentSelectorKey}" to`,
1854
+ latestUpdate == null ? void 0 : latestUpdate.atomUpdates.map((atomUpdate) => atomUpdate.key)
1855
+ );
1856
+ }
1857
+ }
1858
+ if (latestUpdate) {
1859
+ const willCaptureSelectorUpdate = (_d = (_c = tl.shouldCapture) == null ? void 0 : _c.call(tl, latestUpdate, tl)) != null ? _d : true;
1860
+ if (willCaptureSelectorUpdate) {
1861
+ tl.subject.next(latestUpdate);
1862
+ } else {
1863
+ tl.history.pop();
1864
+ tl.at = tl.history.length;
1865
+ }
1866
+ }
1867
+ } else {
1868
+ const timestamp = Date.now();
1869
+ tl.selectorTime = null;
1870
+ if (tl.at !== tl.history.length) {
1871
+ tl.history.splice(tl.at);
1872
+ }
1873
+ const atomUpdate = {
1874
+ type: `atom_update`,
1875
+ timestamp,
1876
+ key: atom2.key,
1877
+ oldValue: update.oldValue,
1878
+ newValue: update.newValue
1879
+ };
1880
+ if (atom2.family) {
1881
+ atomUpdate.family = atom2.family;
1882
+ }
1883
+ const willCapture = (_f = (_e = tl.shouldCapture) == null ? void 0 : _e.call(tl, atomUpdate, tl)) != null ? _f : true;
1884
+ store.logger.info(
1885
+ `\u231B`,
1886
+ `timeline`,
1887
+ tl.key,
1888
+ `got an atom_update to "${atom2.key}"`
1889
+ );
1890
+ if (willCapture) {
1891
+ tl.history.push(atomUpdate);
1892
+ tl.at = tl.history.length;
1893
+ tl.subject.next(atomUpdate);
1894
+ }
1895
+ }
1896
+ }
1897
+ });
1898
+ };
1899
+
1900
+ // internal/src/timeline/create-timeline.ts
1901
+ function createTimeline(options, store, data) {
1902
+ var _a, _b;
1903
+ const tl = __spreadProps(__spreadValues({
1904
+ type: `timeline`,
1905
+ key: options.key,
1906
+ at: 0,
1907
+ timeTraveling: null,
1908
+ selectorTime: null,
1909
+ transactionKey: null
1910
+ }, data), {
1911
+ history: (_a = data == null ? void 0 : data.history.map((update) => __spreadValues({}, update))) != null ? _a : [],
1912
+ install: (store2) => createTimeline(options, store2, tl),
1913
+ subject: new Subject()
1914
+ });
1915
+ if (options.shouldCapture) {
1916
+ tl.shouldCapture = options.shouldCapture;
1917
+ }
1918
+ const target = newest(store);
1919
+ for (const tokenOrFamily of options.atoms) {
1920
+ const timelineKey = target.timelineAtoms.getRelatedKey(tokenOrFamily.key);
1921
+ if (timelineKey) {
1922
+ store.logger.error(
1923
+ `\u274C`,
1924
+ `timeline`,
1925
+ options.key,
1926
+ `Failed to add atom "${tokenOrFamily.key}" because it already belongs to timeline "${timelineKey}"`
1927
+ );
1928
+ continue;
1929
+ }
1930
+ if (tokenOrFamily.type === `atom_family`) {
1931
+ const family = tokenOrFamily;
1932
+ family.subject.subscribe(`timeline:${options.key}`, (token2) => {
1933
+ addAtomToTimeline(token2, tl, store);
1934
+ });
1935
+ for (const atom2 of target.atoms.values()) {
1936
+ if (((_b = atom2.family) == null ? void 0 : _b.key) === family.key) {
1937
+ addAtomToTimeline(atom2, tl, store);
1938
+ }
1939
+ }
1940
+ } else {
1941
+ const token2 = tokenOrFamily;
1942
+ if (`family` in token2 && token2.family) {
1943
+ const familyTimelineKey = target.timelineAtoms.getRelatedKey(
1944
+ token2.family.key
1945
+ );
1946
+ if (familyTimelineKey) {
1947
+ store.logger.error(
1948
+ `\u274C`,
1949
+ `timeline`,
1950
+ options.key,
1951
+ `Failed to add atom "${token2.key}" because its family "${token2.family.key}" already belongs to timeline "${familyTimelineKey}"`
1952
+ );
1953
+ continue;
1954
+ }
1955
+ }
1956
+ addAtomToTimeline(token2, tl, store);
1957
+ }
1958
+ target.timelineAtoms = target.timelineAtoms.set({
1959
+ atomKey: tokenOrFamily.key,
1960
+ timelineKey: options.key
1961
+ });
1962
+ }
1963
+ store.timelines.set(options.key, tl);
1964
+ const token = {
1965
+ key: options.key,
1966
+ type: `timeline`
1967
+ };
1968
+ store.subject.timelineCreation.next(token);
1969
+ return token;
1970
+ }
1971
+
1972
+ // internal/src/timeline/time-travel.ts
1973
+ var timeTravel = (direction, token, store) => {
1974
+ const action = direction === `forward` ? `redo` : `undo`;
1975
+ store.logger.info(
1976
+ direction === `forward` ? `\u23E9` : `\u23EA`,
1977
+ `timeline`,
1978
+ token.key,
1979
+ action
1980
+ );
1981
+ const timelineData = store.timelines.get(token.key);
1982
+ if (!timelineData) {
1983
+ store.logger.error(
1984
+ `\u{1F41E}`,
1985
+ `timeline`,
1986
+ token.key,
1987
+ `Failed to ${action}. This timeline has not been initialized.`
1988
+ );
1989
+ return;
1990
+ }
1991
+ if (direction === `forward` && timelineData.at === timelineData.history.length || direction === `backward` && timelineData.at === 0) {
1992
+ store.logger.warn(
1993
+ `\u{1F481}`,
1994
+ `timeline`,
1995
+ token.key,
1996
+ `Failed to ${action} at the ${direction === `forward` ? `end` : `beginning`} of timeline "${token.key}". There is nothing to ${action}.`
1997
+ );
1998
+ return;
1999
+ }
2000
+ timelineData.timeTraveling = direction === `forward` ? `into_future` : `into_past`;
2001
+ if (direction === `backward`) {
2002
+ --timelineData.at;
2003
+ }
2004
+ const update = timelineData.history[timelineData.at];
2005
+ const updateValues = (atomUpdate) => {
2006
+ const { key, newValue, oldValue } = atomUpdate;
2007
+ const value = direction === `forward` ? newValue : oldValue;
2008
+ setState({ key, type: `atom` }, value, store);
2009
+ };
2010
+ const updateValuesFromTransactionUpdate = (transactionUpdate) => {
2011
+ const updates = direction === `forward` ? transactionUpdate.updates : [...transactionUpdate.updates].reverse();
2012
+ for (const updateFromTransaction of updates) {
2013
+ if (`newValue` in updateFromTransaction) {
2014
+ updateValues(updateFromTransaction);
2015
+ } else {
2016
+ updateValuesFromTransactionUpdate(updateFromTransaction);
2017
+ }
2018
+ }
2019
+ };
2020
+ switch (update.type) {
2021
+ case `atom_update`: {
2022
+ updateValues(update);
2023
+ break;
2024
+ }
2025
+ case `selector_update`: {
2026
+ const updates = direction === `forward` ? update.atomUpdates : [...update.atomUpdates].reverse();
2027
+ for (const atomUpdate of updates) {
2028
+ updateValues(atomUpdate);
2029
+ }
2030
+ break;
2031
+ }
2032
+ case `transaction_update`: {
2033
+ updateValuesFromTransactionUpdate(update);
2034
+ break;
2035
+ }
2036
+ }
2037
+ if (direction === `forward`) {
2038
+ ++timelineData.at;
2039
+ }
2040
+ timelineData.subject.next(action);
2041
+ timelineData.timeTraveling = null;
2042
+ store.logger.info(
2043
+ `\u23F9\uFE0F`,
2044
+ `timeline`,
2045
+ token.key,
2046
+ `"${token.key}" is now at ${timelineData.at} / ${timelineData.history.length}`
2047
+ );
2048
+ };
2049
+
2050
+ // internal/src/transaction/abort-transaction.ts
2051
+ var abortTransaction = (store) => {
2052
+ const target = newest(store);
2053
+ if (target.transactionMeta === null || target.parent === null) {
2054
+ store.logger.warn(
2055
+ `\u{1F41E}`,
2056
+ `transaction`,
2057
+ `???`,
2058
+ `abortTransaction called outside of a transaction. This is probably a bug in AtomIO.`
2059
+ );
2060
+ return;
2061
+ }
2062
+ store.logger.info(
2063
+ `\u{1FA82}`,
2064
+ `transaction`,
2065
+ target.transactionMeta.update.key,
2066
+ `Aborting transaction`
2067
+ );
2068
+ target.parent.child = null;
2069
+ };
2070
+
2071
+ // internal/src/transaction/apply-transaction.ts
2072
+ function ingestAtomUpdate(update, parent, child) {
2073
+ var _a, _b, _c;
2074
+ const { key, newValue } = update;
2075
+ const token = { key, type: `atom` };
2076
+ if (!parent.valueMap.has(token.key)) {
2077
+ if (token.family) {
2078
+ const family = parent.families.get(token.family.key);
2079
+ if (family) {
2080
+ family(token.family.subKey);
2081
+ }
2082
+ } else {
2083
+ const newAtom = child.atoms.get(token.key);
2084
+ if (!newAtom) {
2085
+ throw new Error(
2086
+ `Absurd Error: Atom "${token.key}" not found while copying updates from transaction "${(_a = child.transactionMeta) == null ? void 0 : _a.update.key}" to store "${parent.config.name}"`
2087
+ );
2088
+ }
2089
+ parent.atoms.set(newAtom.key, newAtom);
2090
+ parent.valueMap.set(newAtom.key, newAtom.default);
2091
+ parent.logger.info(
2092
+ `\u{1F528}`,
2093
+ `transaction`,
2094
+ (_c = (_b = child.transactionMeta) == null ? void 0 : _b.update.key) != null ? _c : `???`,
2095
+ `Adding atom "${newAtom.key}"`
2096
+ );
2097
+ }
2098
+ }
2099
+ setState(token, newValue, parent);
2100
+ }
2101
+ function ingestTransactionUpdate(transactionUpdate, parent, child) {
2102
+ for (const update of transactionUpdate.updates) {
2103
+ if (`newValue` in update) {
2104
+ ingestAtomUpdate(update, parent, child);
2105
+ } else {
2106
+ ingestTransactionUpdate(update, parent, child);
2107
+ }
2108
+ }
2109
+ }
2110
+ var applyTransaction = (output, store) => {
2111
+ var _a;
2112
+ const child = newest(store);
2113
+ const { parent } = child;
2114
+ if (parent === null || child.transactionMeta === null || ((_a = child.transactionMeta) == null ? void 0 : _a.phase) !== `building`) {
2115
+ store.logger.warn(
2116
+ `\u{1F41E}`,
2117
+ `transaction`,
2118
+ `???`,
2119
+ `applyTransaction called outside of a transaction. This is probably a bug in AtomIO.`
2120
+ );
2121
+ return;
2122
+ }
2123
+ child.transactionMeta.phase = `applying`;
2124
+ child.transactionMeta.update.output = output;
2125
+ parent.child = null;
2126
+ parent.subject.transactionApplying.next(child.transactionMeta);
2127
+ const { updates } = child.transactionMeta.update;
2128
+ store.logger.info(
2129
+ `\u{1F6C4}`,
2130
+ `transaction`,
2131
+ child.transactionMeta.update.key,
2132
+ `Applying transaction with ${updates.length} updates:`,
2133
+ updates
2134
+ );
2135
+ if (parent.transactionMeta === null) {
2136
+ ingestTransactionUpdate(child.transactionMeta.update, parent, child);
2137
+ const myTransaction = withdraw(
2138
+ { key: child.transactionMeta.update.key, type: `transaction` },
2139
+ store
2140
+ );
2141
+ myTransaction == null ? void 0 : myTransaction.subject.next(child.transactionMeta.update);
2142
+ store.logger.info(
2143
+ `\u{1F6EC}`,
2144
+ `transaction`,
2145
+ child.transactionMeta.update.key,
2146
+ `Finished applying transaction.`
2147
+ );
2148
+ } else {
2149
+ ingestTransactionUpdate(child.transactionMeta.update, parent, child);
2150
+ parent.transactionMeta.update.updates.push(child.transactionMeta.update);
2151
+ }
2152
+ parent.subject.transactionApplying.next(null);
2153
+ };
2154
+
2155
+ // internal/src/transaction/build-transaction.ts
2156
+ var buildTransaction = (key, params, store) => {
2157
+ const parent = newest(store);
2158
+ parent.child = {
2159
+ parent,
2160
+ child: null,
2161
+ subject: parent.subject,
2162
+ loggers: parent.loggers,
2163
+ logger: parent.logger,
2164
+ config: parent.config,
2165
+ transactionMeta: {
2166
+ phase: `building`,
2167
+ time: Date.now(),
2168
+ update: {
2169
+ key,
2170
+ updates: [],
2171
+ params,
2172
+ output: void 0
2173
+ }
2174
+ },
2175
+ atoms: new LazyMap(parent.atoms),
2176
+ atomsThatAreDefault: new Set(parent.atomsThatAreDefault),
2177
+ families: new LazyMap(parent.families),
2178
+ operation: { open: false },
2179
+ readonlySelectors: new LazyMap(parent.readonlySelectors),
2180
+ timelines: new LazyMap(parent.timelines),
2181
+ timelineAtoms: new Junction(parent.timelineAtoms.toJSON()),
2182
+ trackers: /* @__PURE__ */ new Map(),
2183
+ transactions: new LazyMap(parent.transactions),
2184
+ selectorAtoms: new Junction(parent.selectorAtoms.toJSON()),
2185
+ selectorGraph: new Junction(parent.selectorGraph.toJSON(), {
2186
+ makeContentKey: (...keys) => keys.sort().join(`:`)
2187
+ }),
2188
+ selectors: new LazyMap(parent.selectors),
2189
+ valueMap: new LazyMap(parent.valueMap)
2190
+ };
2191
+ store.logger.info(
2192
+ `\u{1F6EB}`,
2193
+ `transaction`,
2194
+ key,
2195
+ `Building transaction with params:`,
2196
+ params
2197
+ );
2198
+ };
2199
+
2200
+ // internal/src/transaction/create-transaction.ts
2201
+ function createTransaction(options, store) {
2202
+ const newTransaction = {
2203
+ key: options.key,
2204
+ type: `transaction`,
2205
+ run: (...params) => {
2206
+ buildTransaction(options.key, params, store);
2207
+ try {
2208
+ const output = options.do(
2209
+ {
2210
+ get: (token2) => getState(token2, store),
2211
+ set: (token2, value) => setState(token2, value, store),
2212
+ run: (token2) => runTransaction(token2, store)
2213
+ },
2214
+ ...params
2215
+ );
2216
+ applyTransaction(output, store);
2217
+ return output;
2218
+ } catch (thrown) {
2219
+ abortTransaction(store);
2220
+ store.logger.warn(`\u{1F4A5}`, `transaction`, options.key, `caught:`, thrown);
2221
+ throw thrown;
2222
+ }
2223
+ },
2224
+ install: (store2) => createTransaction(options, store2),
2225
+ subject: new Subject()
2226
+ };
2227
+ const target = newest(store);
2228
+ target.transactions.set(newTransaction.key, newTransaction);
2229
+ const token = deposit(newTransaction);
2230
+ store.subject.transactionCreation.next(token);
2231
+ return token;
2232
+ }
2233
+
2234
+ // src/atom.ts
2235
+ function atom(options) {
2236
+ if (`mutable` in options) {
2237
+ return createMutableAtom(options, IMPLICIT.STORE);
2238
+ }
2239
+ return createAtom(options, void 0, IMPLICIT.STORE);
2240
+ }
2241
+
2242
+ // src/get-state.ts
2243
+ function getState(token, store = IMPLICIT.STORE) {
2244
+ var _a;
2245
+ const state = (_a = withdraw(token, store)) != null ? _a : withdrawNewFamilyMember(token, store);
2246
+ if (state === void 0) {
2247
+ throw new NotFoundError(token, store);
2248
+ }
2249
+ return readOrComputeValue(state, store);
2250
+ }
2251
+
2252
+ // src/logger.ts
2253
+ var simpleLog = (logLevel) => (icon, tokenType, tokenKey, message, ...rest) => {
2254
+ console[logLevel](`${icon} ${tokenType} "${tokenKey}" ${message}`, ...rest);
2255
+ };
2256
+ var simpleLogger = {
2257
+ error: simpleLog(`error`),
2258
+ info: simpleLog(`info`),
2259
+ warn: simpleLog(`warn`)
2260
+ };
2261
+ var AtomIOLogger = class {
2262
+ constructor(logLevel, filter, logger = simpleLogger) {
2263
+ this.logLevel = logLevel;
2264
+ this.filter = filter;
2265
+ this.logger = logger;
2266
+ this.error = (...args) => {
2267
+ var _a, _b;
2268
+ if (((_b = (_a = this.filter) == null ? void 0 : _a.call(this, ...args)) != null ? _b : true) && this.logLevel !== null) {
2269
+ this.logger.error(...args);
2270
+ }
2271
+ };
2272
+ this.info = (...args) => {
2273
+ var _a, _b;
2274
+ if (((_b = (_a = this.filter) == null ? void 0 : _a.call(this, ...args)) != null ? _b : true) && this.logLevel === `info`) {
2275
+ this.logger.info(...args);
2276
+ }
2277
+ };
2278
+ this.warn = (...args) => {
2279
+ var _a, _b;
2280
+ if (((_b = (_a = this.filter) == null ? void 0 : _a.call(this, ...args)) != null ? _b : true) && this.logLevel !== `error` && this.logLevel !== null) {
2281
+ this.logger.warn(...args);
2282
+ }
2283
+ };
2284
+ }
2285
+ };
2286
+
2287
+ // src/selector.ts
2288
+ function selector(options) {
2289
+ return createSelector(options, void 0, IMPLICIT.STORE);
2290
+ }
2291
+
2292
+ // src/set-state.ts
2293
+ function setState(token, value, store = IMPLICIT.STORE) {
2294
+ var _a;
2295
+ const rejection = openOperation(token, store);
2296
+ if (rejection) {
2297
+ return;
2298
+ }
2299
+ const state = (_a = withdraw(token, store)) != null ? _a : withdrawNewFamilyMember(token, store);
2300
+ if (state === void 0) {
2301
+ throw new NotFoundError(token, store);
2302
+ }
2303
+ setAtomOrSelector(state, value, store);
2304
+ closeOperation(store);
2305
+ }
2306
+
2307
+ // src/silo.ts
2308
+ var Silo = class {
2309
+ constructor(name, fromStore = null) {
2310
+ const s = new Store(name, fromStore);
2311
+ this.store = s;
2312
+ this.atom = (options) => {
2313
+ if (`mutable` in options) {
2314
+ return createMutableAtom(options, s);
2315
+ }
2316
+ return createAtom(options, void 0, s);
2317
+ };
2318
+ this.atomFamily = (options) => {
2319
+ if (`mutable` in options) {
2320
+ return createMutableAtomFamily(options, s);
2321
+ }
2322
+ return createAtomFamily(options, s);
2323
+ };
2324
+ this.selector = (options) => createSelector(options, void 0, s);
2325
+ this.selectorFamily = (options) => createSelectorFamily(options, s);
2326
+ this.transaction = (options) => createTransaction(options, s);
2327
+ this.timeline = (options) => createTimeline(options, s);
2328
+ this.getState = (token) => getState(token, s);
2329
+ this.setState = (token, newValue) => setState(token, newValue, s);
2330
+ this.subscribe = (token, handler, key) => subscribe(token, handler, key, s);
2331
+ this.undo = (token) => timeTravel(`backward`, token, s);
2332
+ this.redo = (token) => timeTravel(`forward`, token, s);
2333
+ }
2334
+ };
2335
+
2336
+ // src/subscribe.ts
2337
+ function subscribe(token, handleUpdate, key = Math.random().toString(36).slice(2), store = IMPLICIT.STORE) {
2338
+ switch (token.type) {
2339
+ case `atom`:
2340
+ case `readonly_selector`:
2341
+ case `selector`:
2342
+ return subscribeToState(token, handleUpdate, key, store);
2343
+ case `transaction`:
2344
+ return subscribeToTransaction(token, handleUpdate, key, store);
2345
+ case `timeline`:
2346
+ return subscribeToTimeline(token, handleUpdate, key, store);
2347
+ }
2348
+ }
2349
+
2350
+ // src/transaction.ts
2351
+ var runTransaction = (token, store = IMPLICIT.STORE) => (...parameters) => {
2352
+ const tx = withdraw(token, store);
2353
+ if (tx) {
2354
+ return tx.run(...parameters);
2355
+ }
2356
+ throw new Error(
2357
+ `Cannot run transaction "${token.key}": transaction not found in store "${store.config.name}".`
2358
+ );
2359
+ };
2360
+ var StoreContext = React2__namespace.createContext(IMPLICIT.STORE);
2361
+ var StoreProvider = ({ children, store = IMPLICIT.STORE }) => /* @__PURE__ */ jsxRuntime.jsx(StoreContext.Provider, { value: store, children });
2362
+ function useI(token) {
2363
+ const store = React2__namespace.useContext(StoreContext);
2364
+ const setter = React2__namespace.useRef(null);
2365
+ if (setter.current === null) {
2366
+ setter.current = (next) => setState(token, next, store);
2367
+ }
2368
+ return setter.current;
2369
+ }
2370
+
2371
+ // realtime-client/src/realtime-state.ts
2372
+ var myIdState__INTERNAL = atom({
2373
+ key: `myId__INTERNAL`,
2374
+ default: null
2375
+ });
2376
+ selector({
2377
+ key: `myId`,
2378
+ get: ({ get }) => get(myIdState__INTERNAL)
2379
+ });
2380
+ var RealtimeContext = React2__namespace.createContext({
2381
+ socket: socket_ioClient.io()
2382
+ });
2383
+ var RealtimeProvider = ({ children, socket }) => {
2384
+ const setMyId = useI(myIdState__INTERNAL);
2385
+ React2__namespace.useEffect(() => {
2386
+ socket.on(`connect`, () => {
2387
+ setMyId(socket.id);
2388
+ });
2389
+ socket.on(`disconnect`, () => {
2390
+ setMyId(null);
2391
+ });
2392
+ }, [socket, setMyId]);
2393
+ return /* @__PURE__ */ jsxRuntime.jsx(RealtimeContext.Provider, { value: { socket }, children });
2394
+ };
2395
+
2396
+ // ../anvl/src/object/entries.ts
61
2397
  var recordToEntries = (obj) => Object.entries(obj);
62
2398
  var setupRealtimeTestServer = (options) => {
63
2399
  const httpServer = http__namespace.createServer((_, res) => res.end(`Hello World!`));
@@ -66,13 +2402,13 @@ var setupRealtimeTestServer = (options) => {
66
2402
  if (port === null)
67
2403
  throw new Error(`Could not determine port for test server`);
68
2404
  const server = new SocketIO__namespace.Server(httpServer);
69
- const silo = new AtomIO__namespace.Silo(`SERVER`, Internal__namespace.IMPLICIT.STORE);
2405
+ const silo = new Silo(`SERVER`, IMPLICIT.STORE);
70
2406
  server.on(`connection`, (socket) => {
71
2407
  options.server({ socket, silo });
72
2408
  });
73
2409
  const dispose = () => {
74
2410
  server.close();
75
- Internal__namespace.clearStore(silo.store);
2411
+ clearStore(silo.store);
76
2412
  };
77
2413
  return {
78
2414
  name: `SERVER`,
@@ -83,11 +2419,11 @@ var setupRealtimeTestServer = (options) => {
83
2419
  };
84
2420
  var setupRealtimeTestClient = (options, name, port) => {
85
2421
  const socket = socket_ioClient.io(`http://localhost:${port}/`);
86
- const silo = new AtomIO__namespace.Silo(name, Internal__namespace.IMPLICIT.STORE);
2422
+ const silo = new Silo(name, IMPLICIT.STORE);
87
2423
  const { document } = new Happy__namespace.Window();
88
2424
  document.body.innerHTML = `<div id="app"></div>`;
89
2425
  const renderResult = react.render(
90
- /* @__PURE__ */ jsxRuntime.jsx(AR__namespace.StoreProvider, { store: silo.store, children: /* @__PURE__ */ jsxRuntime.jsx(RTC__namespace.RealtimeProvider, { socket, children: /* @__PURE__ */ jsxRuntime.jsx(options.client, {}) }) }),
2426
+ /* @__PURE__ */ jsxRuntime.jsx(StoreProvider, { store: silo.store, children: /* @__PURE__ */ jsxRuntime.jsx(RealtimeProvider, { socket, children: /* @__PURE__ */ jsxRuntime.jsx(options.client, {}) }) }),
91
2427
  {
92
2428
  container: document.querySelector(`#app`)
93
2429
  }
@@ -97,7 +2433,7 @@ var setupRealtimeTestClient = (options, name, port) => {
97
2433
  const reconnect = () => socket.connect();
98
2434
  const dispose = () => {
99
2435
  socket.disconnect();
100
- Internal__namespace.clearStore(silo.store);
2436
+ clearStore(silo.store);
101
2437
  };
102
2438
  return {
103
2439
  name,