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