atom.io 0.14.3 → 0.14.5

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