atom.io 0.14.0 → 0.14.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. package/data/dist/index.cjs +1473 -52
  2. package/data/dist/index.cjs.map +1 -1
  3. package/data/dist/index.d.cts +315 -16
  4. package/data/dist/index.js +10 -267
  5. package/data/dist/index.js.map +1 -1
  6. package/data/package.json +5 -5
  7. package/data/src/join.ts +3 -3
  8. package/dist/chunk-5VJ77LZE.js +176 -0
  9. package/dist/chunk-5VJ77LZE.js.map +1 -0
  10. package/dist/chunk-CK7GNCU5.js +309 -0
  11. package/dist/chunk-CK7GNCU5.js.map +1 -0
  12. package/dist/chunk-KW7RA7IM.js +67 -0
  13. package/dist/chunk-KW7RA7IM.js.map +1 -0
  14. package/dist/chunk-LFXB7Y6M.js +68 -0
  15. package/dist/chunk-LFXB7Y6M.js.map +1 -0
  16. package/dist/chunk-NYCVSXQB.js +181 -0
  17. package/dist/chunk-NYCVSXQB.js.map +1 -0
  18. package/dist/chunk-TE3ZSTQ6.js +2516 -0
  19. package/dist/chunk-TE3ZSTQ6.js.map +1 -0
  20. package/dist/index.cjs +2244 -55
  21. package/dist/index.cjs.map +1 -1
  22. package/dist/index.d.cts +268 -21
  23. package/dist/index.js +1 -152
  24. package/dist/index.js.map +1 -1
  25. package/dist/metafile-cjs.json +1 -1
  26. package/internal/dist/index.cjs +208 -79
  27. package/internal/dist/index.cjs.map +1 -1
  28. package/internal/dist/index.d.cts +226 -27
  29. package/internal/dist/index.js +1 -2240
  30. package/internal/dist/index.js.map +1 -1
  31. package/internal/package.json +5 -5
  32. package/introspection/dist/index.cjs +1618 -46
  33. package/introspection/dist/index.cjs.map +1 -1
  34. package/introspection/dist/index.d.cts +374 -4
  35. package/introspection/dist/index.js +2 -316
  36. package/introspection/dist/index.js.map +1 -1
  37. package/introspection/package.json +5 -5
  38. package/json/dist/index.cjs +1560 -8
  39. package/json/dist/index.cjs.map +1 -1
  40. package/json/dist/index.d.cts +371 -7
  41. package/json/dist/index.js +1 -76
  42. package/json/dist/index.js.map +1 -1
  43. package/json/package.json +5 -5
  44. package/package.json +5 -4
  45. package/react/dist/index.cjs +1604 -14
  46. package/react/dist/index.cjs.map +1 -1
  47. package/react/dist/index.d.cts +375 -4
  48. package/react/dist/index.js +2 -68
  49. package/react/dist/index.js.map +1 -1
  50. package/react/package.json +5 -5
  51. package/react-devtools/dist/index.cjs +2268 -198
  52. package/react-devtools/dist/index.cjs.map +1 -1
  53. package/react-devtools/dist/index.css +2 -2
  54. package/react-devtools/dist/index.d.cts +148 -24
  55. package/react-devtools/dist/index.js +57 -297
  56. package/react-devtools/dist/index.js.map +1 -1
  57. package/react-devtools/package.json +5 -5
  58. package/realtime-client/dist/index.cjs +1585 -35
  59. package/realtime-client/dist/index.cjs.map +1 -1
  60. package/realtime-client/dist/index.d.cts +382 -12
  61. package/realtime-client/dist/index.js +2 -165
  62. package/realtime-client/dist/index.js.map +1 -1
  63. package/realtime-client/package.json +5 -5
  64. package/realtime-react/dist/index.cjs +1782 -35
  65. package/realtime-react/dist/index.cjs.map +1 -1
  66. package/realtime-react/dist/index.d.cts +49 -9
  67. package/realtime-react/dist/index.js +4 -66
  68. package/realtime-react/dist/index.js.map +1 -1
  69. package/realtime-react/package.json +5 -5
  70. package/realtime-server/dist/index.cjs +1604 -58
  71. package/realtime-server/dist/index.cjs.map +1 -1
  72. package/realtime-server/dist/index.d.cts +391 -11
  73. package/realtime-server/dist/index.js +27 -21
  74. package/realtime-server/dist/index.js.map +1 -1
  75. package/realtime-server/package.json +6 -6
  76. package/realtime-testing/dist/index.cjs +2352 -16
  77. package/realtime-testing/dist/index.cjs.map +1 -1
  78. package/realtime-testing/dist/index.d.cts +486 -3
  79. package/realtime-testing/dist/index.js +10 -31
  80. package/realtime-testing/dist/index.js.map +1 -1
  81. package/realtime-testing/package.json +5 -5
  82. package/transceivers/set-rtx/dist/index.cjs +31 -10
  83. package/transceivers/set-rtx/dist/index.cjs.map +1 -1
  84. package/transceivers/set-rtx/dist/index.d.cts +29 -3
  85. package/transceivers/set-rtx/dist/index.js +2 -3
  86. package/transceivers/set-rtx/dist/index.js.map +1 -1
  87. package/transceivers/set-rtx/package.json +6 -6
  88. package/data/dist/index.d.ts +0 -158
  89. package/data/dist/metafile-cjs.json +0 -1
  90. package/data/dist/metafile-esm.json +0 -1
  91. package/dist/index.d.ts +0 -243
  92. package/dist/metafile-esm.json +0 -1
  93. package/internal/dist/index.d.ts +0 -421
  94. package/internal/dist/metafile-cjs.json +0 -1
  95. package/internal/dist/metafile-esm.json +0 -1
  96. package/introspection/dist/index.d.ts +0 -24
  97. package/introspection/dist/metafile-cjs.json +0 -1
  98. package/introspection/dist/metafile-esm.json +0 -1
  99. package/json/dist/index.d.ts +0 -51
  100. package/json/dist/metafile-cjs.json +0 -1
  101. package/json/dist/metafile-esm.json +0 -1
  102. package/react/dist/index.d.ts +0 -23
  103. package/react/dist/metafile-cjs.json +0 -1
  104. package/react/dist/metafile-esm.json +0 -1
  105. package/react-devtools/dist/index.d.ts +0 -341
  106. package/react-devtools/dist/metafile-cjs.json +0 -1
  107. package/react-devtools/dist/metafile-esm.json +0 -1
  108. package/realtime-client/dist/index.d.ts +0 -22
  109. package/realtime-client/dist/metafile-cjs.json +0 -1
  110. package/realtime-client/dist/metafile-esm.json +0 -1
  111. package/realtime-react/dist/index.d.ts +0 -27
  112. package/realtime-react/dist/metafile-cjs.json +0 -1
  113. package/realtime-react/dist/metafile-esm.json +0 -1
  114. package/realtime-server/dist/index.d.ts +0 -25
  115. package/realtime-server/dist/metafile-cjs.json +0 -1
  116. package/realtime-server/dist/metafile-esm.json +0 -1
  117. package/realtime-testing/dist/index.d.ts +0 -49
  118. package/realtime-testing/dist/metafile-cjs.json +0 -1
  119. package/realtime-testing/dist/metafile-esm.json +0 -1
  120. package/transceivers/set-rtx/dist/index.d.ts +0 -40
  121. package/transceivers/set-rtx/dist/metafile-cjs.json +0 -1
  122. package/transceivers/set-rtx/dist/metafile-esm.json +0 -1
@@ -1,9 +1,7 @@
1
1
  'use strict';
2
2
 
3
- var internal = require('atom.io/internal');
4
3
  var React2 = require('react');
5
4
  var jsxRuntime = require('react/jsx-runtime');
6
- var atom_io = require('atom.io');
7
5
 
8
6
  function _interopNamespace(e) {
9
7
  if (e && e.__esModule) return e;
@@ -25,14 +23,1606 @@ function _interopNamespace(e) {
25
23
 
26
24
  var React2__namespace = /*#__PURE__*/_interopNamespace(React2);
27
25
 
28
- // src/store-context.tsx
29
- var StoreContext = React2__namespace.createContext(internal.IMPLICIT.STORE);
30
- var StoreProvider = ({ children, store = internal.IMPLICIT.STORE }) => /* @__PURE__ */ jsxRuntime.jsx(StoreContext.Provider, { value: store, children });
26
+ var __defProp = Object.defineProperty;
27
+ var __defProps = Object.defineProperties;
28
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
29
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
30
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
31
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
32
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
33
+ var __spreadValues = (a, b) => {
34
+ for (var prop in b || (b = {}))
35
+ if (__hasOwnProp.call(b, prop))
36
+ __defNormalProp(a, prop, b[prop]);
37
+ if (__getOwnPropSymbols)
38
+ for (var prop of __getOwnPropSymbols(b)) {
39
+ if (__propIsEnum.call(b, prop))
40
+ __defNormalProp(a, prop, b[prop]);
41
+ }
42
+ return a;
43
+ };
44
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
45
+
46
+ // src/get-state.ts
47
+ function getState(token, store = IMPLICIT.STORE) {
48
+ var _a;
49
+ const state = (_a = withdraw(token, store)) != null ? _a : withdrawNewFamilyMember(token, store);
50
+ if (state === void 0) {
51
+ throw new NotFoundError(token, store);
52
+ }
53
+ return readOrComputeValue(state, store);
54
+ }
55
+
56
+ // src/logger.ts
57
+ var simpleLog = (logLevel) => (icon, tokenType, tokenKey, message, ...rest) => {
58
+ console[logLevel](`${icon} ${tokenType} "${tokenKey}" ${message}`, ...rest);
59
+ };
60
+ var simpleLogger = {
61
+ error: simpleLog(`error`),
62
+ info: simpleLog(`info`),
63
+ warn: simpleLog(`warn`)
64
+ };
65
+ var AtomIOLogger = class {
66
+ constructor(logLevel, filter, logger = simpleLogger) {
67
+ this.logLevel = logLevel;
68
+ this.filter = filter;
69
+ this.logger = logger;
70
+ this.error = (...args) => {
71
+ var _a, _b;
72
+ if (((_b = (_a = this.filter) == null ? void 0 : _a.call(this, ...args)) != null ? _b : true) && this.logLevel !== null) {
73
+ this.logger.error(...args);
74
+ }
75
+ };
76
+ this.info = (...args) => {
77
+ var _a, _b;
78
+ if (((_b = (_a = this.filter) == null ? void 0 : _a.call(this, ...args)) != null ? _b : true) && this.logLevel === `info`) {
79
+ this.logger.info(...args);
80
+ }
81
+ };
82
+ this.warn = (...args) => {
83
+ var _a, _b;
84
+ if (((_b = (_a = this.filter) == null ? void 0 : _a.call(this, ...args)) != null ? _b : true) && this.logLevel !== `error` && this.logLevel !== null) {
85
+ this.logger.warn(...args);
86
+ }
87
+ };
88
+ }
89
+ };
90
+
91
+ // src/set-state.ts
92
+ function setState(token, value, store = IMPLICIT.STORE) {
93
+ var _a;
94
+ const rejection = openOperation(token, store);
95
+ if (rejection) {
96
+ return;
97
+ }
98
+ const state = (_a = withdraw(token, store)) != null ? _a : withdrawNewFamilyMember(token, store);
99
+ if (state === void 0) {
100
+ throw new NotFoundError(token, store);
101
+ }
102
+ setAtomOrSelector(state, value, store);
103
+ closeOperation(store);
104
+ }
105
+
106
+ // src/timeline.ts
107
+ var redo = (timeline) => {
108
+ timeTravel(`forward`, timeline, IMPLICIT.STORE);
109
+ };
110
+ var undo = (timeline) => {
111
+ timeTravel(`backward`, timeline, IMPLICIT.STORE);
112
+ };
113
+
114
+ // internal/src/future.ts
115
+ var Future = class extends Promise {
116
+ constructor(executor) {
117
+ super((resolve, reject) => {
118
+ const pass = (value) => this.isCanceled ? reject(`canceled`) : resolve(value);
119
+ const fail = (reason) => this.isCanceled ? reject(`canceled`) : reject(reason);
120
+ if (typeof executor === `function`) {
121
+ executor(pass, fail);
122
+ } else {
123
+ executor.then(pass, fail);
124
+ }
125
+ });
126
+ this.isCanceled = false;
127
+ }
128
+ cancel() {
129
+ this.isCanceled = true;
130
+ }
131
+ };
132
+
133
+ // internal/src/lineage.ts
134
+ function newest(scion) {
135
+ while (scion.child !== null) {
136
+ scion = scion.child;
137
+ }
138
+ return scion;
139
+ }
140
+
141
+ // internal/src/caching.ts
142
+ function cacheValue(key, value, subject, store) {
143
+ const target = newest(store);
144
+ const currentValue = target.valueMap.get(key);
145
+ if (currentValue instanceof Future) {
146
+ currentValue.cancel();
147
+ }
148
+ if (value instanceof Promise) {
149
+ const future = new Future(value);
150
+ newest(store).valueMap.set(key, future);
151
+ future.then((resolved) => {
152
+ if (future.isCanceled) {
153
+ return;
154
+ }
155
+ cacheValue(key, resolved, subject, store);
156
+ subject.next({ newValue: resolved, oldValue: future });
157
+ }).catch((thrown) => {
158
+ if (thrown !== `canceled`) {
159
+ store.logger.error(`\u{1F4A5}`, `state`, key, `rejected:`, thrown);
160
+ }
161
+ });
162
+ return future;
163
+ }
164
+ target.valueMap.set(key, value);
165
+ return value;
166
+ }
167
+ var readCachedValue = (key, store) => {
168
+ return newest(store).valueMap.get(key);
169
+ };
170
+ var isValueCached = (key, store) => {
171
+ return newest(store).valueMap.has(key);
172
+ };
173
+ var evictCachedValue = (key, store) => {
174
+ const core = newest(store);
175
+ const currentValue = core.valueMap.get(key);
176
+ if (currentValue instanceof Future) {
177
+ currentValue.cancel();
178
+ }
179
+ if (core.operation.open) {
180
+ core.operation.prev.set(key, currentValue);
181
+ }
182
+ core.valueMap.delete(key);
183
+ store.logger.info(`\u{1F5D1}`, `state`, key, `evicted`);
184
+ };
185
+
186
+ // json/src/select-json.ts
187
+ var selectJson = (atom, transform, store = IMPLICIT.STORE) => {
188
+ return createSelector(
189
+ {
190
+ key: `${atom.key}:JSON`,
191
+ get: ({ get }) => transform.toJson(get(atom)),
192
+ set: ({ set }, newValue) => set(atom, transform.fromJson(newValue))
193
+ },
194
+ void 0,
195
+ store
196
+ );
197
+ };
198
+
199
+ // internal/src/read-or-compute-value.ts
200
+ var readOrComputeValue = (state, store) => {
201
+ if (isValueCached(state.key, store)) {
202
+ store.logger.info(`\u{1F4D6}`, state.type, state.key, `reading cached value`);
203
+ return readCachedValue(state.key, store);
204
+ }
205
+ if (state.type !== `atom`) {
206
+ store.logger.info(`\u{1F9EE}`, state.type, state.key, `computing value`);
207
+ return state.get();
208
+ }
209
+ const fallback = state.default instanceof Function ? state.default() : state.default;
210
+ store.logger.info(
211
+ `\u{1F481}`,
212
+ `atom`,
213
+ state.key,
214
+ `could not find cached value; using default`,
215
+ fallback
216
+ );
217
+ return state.default instanceof Function ? state.default() : state.default;
218
+ };
219
+
220
+ // internal/src/operation.ts
221
+ var openOperation = (token, store) => {
222
+ const target = newest(store);
223
+ if (target.operation.open) {
224
+ store.logger.error(
225
+ `\u274C`,
226
+ token.type,
227
+ token.key,
228
+ `failed to setState during a setState for "${target.operation.token.key}"`
229
+ );
230
+ return `rejection`;
231
+ }
232
+ target.operation = {
233
+ open: true,
234
+ done: /* @__PURE__ */ new Set(),
235
+ prev: /* @__PURE__ */ new Map(),
236
+ time: Date.now(),
237
+ token
238
+ };
239
+ store.logger.info(
240
+ `\u2B55`,
241
+ token.type,
242
+ token.key,
243
+ `operation start in store "${store.config.name}"${target.transactionMeta === null ? `` : ` ${target.transactionMeta.phase} "${target.transactionMeta.update.key}"`}`
244
+ );
245
+ };
246
+ var closeOperation = (store) => {
247
+ const target = newest(store);
248
+ if (target.operation.open) {
249
+ store.logger.info(
250
+ `\u{1F534}`,
251
+ target.operation.token.type,
252
+ target.operation.token.key,
253
+ `operation done in store "${store.config.name}"`
254
+ );
255
+ }
256
+ target.operation = { open: false };
257
+ store.subject.operationStatus.next(target.operation);
258
+ };
259
+ var isDone = (key, store) => {
260
+ const target = newest(store);
261
+ if (!target.operation.open) {
262
+ store.logger.warn(
263
+ `\u{1F41E}`,
264
+ `unknown`,
265
+ key,
266
+ `isDone called outside of an operation. This is probably a bug.`
267
+ );
268
+ return true;
269
+ }
270
+ return target.operation.done.has(key);
271
+ };
272
+ var markDone = (key, store) => {
273
+ const target = newest(store);
274
+ if (!target.operation.open) {
275
+ store.logger.warn(
276
+ `\u{1F41E}`,
277
+ `unknown`,
278
+ key,
279
+ `markDone called outside of an operation. This is probably a bug.`
280
+ );
281
+ return;
282
+ }
283
+ target.operation.done.add(key);
284
+ };
285
+
286
+ // internal/src/set-state/become.ts
287
+ var become = (nextVersionOfThing) => (originalThing) => nextVersionOfThing instanceof Function ? nextVersionOfThing(
288
+ originalThing instanceof Function ? originalThing() : originalThing
289
+ ) : nextVersionOfThing;
290
+
291
+ // internal/src/subject.ts
292
+ var Subject = class {
293
+ constructor() {
294
+ this.subscribers = /* @__PURE__ */ new Map();
295
+ }
296
+ subscribe(key, subscriber) {
297
+ this.subscribers.set(key, subscriber);
298
+ const unsubscribe = () => this.unsubscribe(key);
299
+ return unsubscribe;
300
+ }
301
+ unsubscribe(key) {
302
+ this.subscribers.delete(key);
303
+ }
304
+ next(value) {
305
+ for (const subscriber of this.subscribers.values()) {
306
+ subscriber(value);
307
+ }
308
+ }
309
+ };
310
+ var StatefulSubject = class extends Subject {
311
+ constructor(initialState) {
312
+ super();
313
+ this.state = initialState;
314
+ }
315
+ next(value) {
316
+ this.state = value;
317
+ super.next(value);
318
+ }
319
+ };
320
+
321
+ // internal/src/set-state/copy-mutable-if-needed.ts
322
+ function copyMutableIfNeeded(atom, transform, origin, target) {
323
+ const originValue = origin.valueMap.get(atom.key);
324
+ const targetValue = target.valueMap.get(atom.key);
325
+ if (originValue === targetValue) {
326
+ origin.logger.info(`\u{1F4C3}`, `atom`, `${atom.key}`, `copying`);
327
+ const jsonValue = transform.toJson(originValue);
328
+ const copiedValue = transform.fromJson(jsonValue);
329
+ target.valueMap.set(atom.key, copiedValue);
330
+ new Tracker(atom, origin);
331
+ return copiedValue;
332
+ }
333
+ return targetValue;
334
+ }
335
+
336
+ // internal/src/set-state/copy-mutable-in-transaction.ts
337
+ function copyMutableIfWithinTransaction(oldValue, atom, store) {
338
+ const target = newest(store);
339
+ const parent = target.parent;
340
+ if (parent !== null) {
341
+ if (`toJson` in atom && `fromJson` in atom) {
342
+ const copiedValue = copyMutableIfNeeded(atom, atom, parent, target);
343
+ return copiedValue;
344
+ }
345
+ if (`family` in atom) {
346
+ const family = parent.families.get(atom.family.key);
347
+ if (family && family.type === `atom_family`) {
348
+ const result = copyMutableFamilyMemberWithinTransaction(
349
+ atom,
350
+ family,
351
+ parent,
352
+ target
353
+ );
354
+ if (result) {
355
+ return result;
356
+ }
357
+ }
358
+ }
359
+ }
360
+ return oldValue;
361
+ }
362
+ function copyMutableFamilyMemberWithinTransaction(atom, family, origin, target) {
363
+ if (`toJson` in family && `fromJson` in family) {
364
+ const copyCreated = copyMutableIfNeeded(atom, family, origin, target);
365
+ return copyCreated;
366
+ }
367
+ return null;
368
+ }
369
+
370
+ // internal/src/set-state/emit-update.ts
371
+ var emitUpdate = (state, update, store) => {
372
+ store.logger.info(
373
+ `\u{1F4E2}`,
374
+ state.type,
375
+ state.key,
376
+ `went (`,
377
+ update.oldValue,
378
+ `->`,
379
+ update.newValue,
380
+ `) subscribers:`,
381
+ state.subject.subscribers
382
+ );
383
+ state.subject.next(update);
384
+ };
385
+
386
+ // internal/src/set-state/evict-downstream.ts
387
+ var evictDownStream = (atom, store) => {
388
+ const target = newest(store);
389
+ const downstreamKeys = target.selectorAtoms.getRelatedKeys(atom.key);
390
+ store.logger.info(
391
+ `\u{1F9F9}`,
392
+ atom.type,
393
+ atom.key,
394
+ downstreamKeys ? `evicting ${downstreamKeys.size} states downstream:` : `no downstream states`,
395
+ downstreamKeys != null ? downstreamKeys : `to evict`
396
+ );
397
+ if (downstreamKeys) {
398
+ if (target.operation.open) {
399
+ store.logger.info(
400
+ `\u{1F9F9}`,
401
+ atom.type,
402
+ atom.key,
403
+ `[ ${[...target.operation.done].join(`, `)} ] already done`
404
+ );
405
+ }
406
+ for (const key of downstreamKeys) {
407
+ if (isDone(key, store)) {
408
+ continue;
409
+ }
410
+ evictCachedValue(key, store);
411
+ markDone(key, store);
412
+ }
413
+ }
414
+ };
415
+
416
+ // internal/src/set-state/stow-update.ts
417
+ function shouldUpdateBeStowed(key, update) {
418
+ if (isTransceiver(update.newValue)) {
419
+ return false;
420
+ }
421
+ if (key.includes(`\u{1F441}\u200D\u{1F5E8}`)) {
422
+ return false;
423
+ }
424
+ return true;
425
+ }
426
+ var stowUpdate = (state, update, store) => {
427
+ const { key } = state;
428
+ const target = newest(store);
429
+ if (target.transactionMeta === null || target.transactionMeta.phase !== `building`) {
430
+ store.logger.error(
431
+ `\u{1F41E}`,
432
+ `atom`,
433
+ key,
434
+ `stowUpdate called outside of a transaction. This is probably a bug.`
435
+ );
436
+ return;
437
+ }
438
+ const shouldStow = shouldUpdateBeStowed(key, update);
439
+ if (!shouldStow) {
440
+ return;
441
+ }
442
+ const atomUpdate = __spreadValues({ key }, update);
443
+ if (state.family) {
444
+ atomUpdate.family = state.family;
445
+ }
446
+ target.transactionMeta.update.updates.push(atomUpdate);
447
+ store.logger.info(
448
+ `\u{1F4C1}`,
449
+ `atom`,
450
+ key,
451
+ `stowed (`,
452
+ update.oldValue,
453
+ `->`,
454
+ update.newValue,
455
+ `)`
456
+ );
457
+ };
458
+
459
+ // internal/src/set-state/set-atom.ts
460
+ var setAtom = (atom, next, store) => {
461
+ const target = newest(store);
462
+ const oldValue = readOrComputeValue(atom, store);
463
+ let newValue = copyMutableIfWithinTransaction(oldValue, atom, store);
464
+ newValue = become(next)(newValue);
465
+ store.logger.info(`\u{1F4DD}`, `atom`, atom.key, `set to`, newValue);
466
+ newValue = cacheValue(atom.key, newValue, atom.subject, store);
467
+ if (isAtomDefault(atom.key, store)) {
468
+ markAtomAsNotDefault(atom.key, store);
469
+ }
470
+ markDone(atom.key, store);
471
+ evictDownStream(atom, store);
472
+ const update = { oldValue, newValue };
473
+ if (target.transactionMeta === null || target.transactionMeta.phase === `applying`) {
474
+ emitUpdate(atom, update, store);
475
+ } else {
476
+ stowUpdate(atom, update, store);
477
+ }
478
+ };
479
+
480
+ // internal/src/set-state/set-atom-or-selector.ts
481
+ var setAtomOrSelector = (state, value, store) => {
482
+ if (state.type === `selector`) {
483
+ state.set(value);
484
+ } else {
485
+ setAtom(state, value, store);
486
+ }
487
+ };
488
+
489
+ // internal/src/store/deposit.ts
490
+ function deposit(state) {
491
+ const token = {
492
+ key: state.key,
493
+ type: state.type
494
+ };
495
+ if (`family` in state) {
496
+ token.family = state.family;
497
+ }
498
+ return token;
499
+ }
500
+
501
+ // ../rel8/junction/src/junction.ts
502
+ var Junction = class {
503
+ constructor(data, config) {
504
+ this.relations = /* @__PURE__ */ new Map();
505
+ this.contents = /* @__PURE__ */ new Map();
506
+ this.makeContentKey = (a, b) => `${a}:${b}`;
507
+ var _a, _b, _c, _d;
508
+ this.a = data.between[0];
509
+ this.b = data.between[1];
510
+ this.cardinality = data.cardinality;
511
+ if (!(config == null ? void 0 : config.externalStore)) {
512
+ this.relations = new Map((_a = data.relations) == null ? void 0 : _a.map(([a, b]) => [a, new Set(b)]));
513
+ this.contents = new Map(data.contents);
514
+ }
515
+ this.isContent = (_b = config == null ? void 0 : config.isContent) != null ? _b : null;
516
+ if (config == null ? void 0 : config.makeContentKey) {
517
+ this.makeContentKey = config.makeContentKey;
518
+ }
519
+ if (config == null ? void 0 : config.externalStore) {
520
+ const externalStore = config.externalStore;
521
+ this.has = (a, b) => externalStore.has(a, b);
522
+ this.addRelation = (a, b) => {
523
+ externalStore.addRelation(a, b);
524
+ };
525
+ this.deleteRelation = (a, b) => {
526
+ externalStore.deleteRelation(a, b);
527
+ };
528
+ this.replaceRelationsSafely = (a, bs) => {
529
+ externalStore.replaceRelationsSafely(a, bs);
530
+ };
531
+ this.replaceRelationsUnsafely = (a, bs) => {
532
+ externalStore.replaceRelationsUnsafely(a, bs);
533
+ };
534
+ this.getRelatedKeys = (key) => externalStore.getRelatedKeys(key);
535
+ if (externalStore.getContent) {
536
+ this.getContentInternal = (contentKey) => {
537
+ return externalStore.getContent(contentKey);
538
+ };
539
+ this.setContent = (contentKey, content) => {
540
+ externalStore.setContent(contentKey, content);
541
+ };
542
+ this.deleteContent = (contentKey) => {
543
+ externalStore.deleteContent(contentKey);
544
+ };
545
+ }
546
+ for (const [x, ys] of (_c = data.relations) != null ? _c : []) {
547
+ for (const y of ys)
548
+ this.addRelation(x, y);
549
+ }
550
+ for (const [contentKey, content] of (_d = data.contents) != null ? _d : []) {
551
+ this.setContent(contentKey, content);
552
+ }
553
+ }
554
+ }
555
+ getRelatedKeys(key) {
556
+ return this.relations.get(key);
557
+ }
558
+ addRelation(a, b) {
559
+ let aRelations = this.relations.get(a);
560
+ let bRelations = this.relations.get(b);
561
+ if (aRelations) {
562
+ aRelations.add(b);
563
+ } else {
564
+ aRelations = /* @__PURE__ */ new Set([b]);
565
+ this.relations.set(a, aRelations);
566
+ }
567
+ if (bRelations) {
568
+ bRelations.add(a);
569
+ } else {
570
+ bRelations = /* @__PURE__ */ new Set([a]);
571
+ this.relations.set(b, bRelations);
572
+ }
573
+ }
574
+ deleteRelation(a, b) {
575
+ const aRelations = this.relations.get(a);
576
+ if (aRelations) {
577
+ aRelations.delete(b);
578
+ if (aRelations.size === 0) {
579
+ this.relations.delete(a);
580
+ }
581
+ const bRelations = this.relations.get(b);
582
+ if (bRelations) {
583
+ bRelations.delete(a);
584
+ if (bRelations.size === 0) {
585
+ this.relations.delete(b);
586
+ }
587
+ }
588
+ }
589
+ }
590
+ replaceRelationsUnsafely(a, bs) {
591
+ this.relations.set(a, new Set(bs));
592
+ for (const b of bs) {
593
+ const bRelations = /* @__PURE__ */ new Set([a]);
594
+ this.relations.set(b, bRelations);
595
+ }
596
+ }
597
+ replaceRelationsSafely(a, bs) {
598
+ const aRelationsPrev = this.relations.get(a);
599
+ if (aRelationsPrev) {
600
+ for (const b of aRelationsPrev) {
601
+ const bRelations = this.relations.get(b);
602
+ if (bRelations) {
603
+ if (bRelations.size === 1) {
604
+ this.relations.delete(b);
605
+ } else {
606
+ bRelations.delete(a);
607
+ }
608
+ this.contents.delete(this.makeContentKey(a, b));
609
+ }
610
+ }
611
+ }
612
+ this.relations.set(a, new Set(bs));
613
+ for (const b of bs) {
614
+ let bRelations = this.relations.get(b);
615
+ if (bRelations) {
616
+ bRelations.add(a);
617
+ } else {
618
+ bRelations = /* @__PURE__ */ new Set([a]);
619
+ this.relations.set(b, bRelations);
620
+ }
621
+ }
622
+ }
623
+ getContentInternal(contentKey) {
624
+ return this.contents.get(contentKey);
625
+ }
626
+ setContent(contentKey, content) {
627
+ this.contents.set(contentKey, content);
628
+ }
629
+ deleteContent(contentKey) {
630
+ this.contents.delete(contentKey);
631
+ }
632
+ toJSON() {
633
+ return {
634
+ between: [this.a, this.b],
635
+ cardinality: this.cardinality,
636
+ relations: [...this.relations.entries()].map(([a, b]) => [a, [...b]]),
637
+ contents: [...this.contents.entries()]
638
+ };
639
+ }
640
+ set(a, ...rest) {
641
+ var _a;
642
+ const b = typeof rest[0] === `string` ? rest[0] : a[this.b];
643
+ const content = ((_a = rest[1]) != null ? _a : typeof rest[0] === `string`) ? void 0 : rest[0];
644
+ a = typeof a === `string` ? a : a[this.a];
645
+ switch (this.cardinality) {
646
+ case `1:1`: {
647
+ const bPrev = this.getRelatedKey(a);
648
+ if (bPrev && bPrev !== b)
649
+ this.delete(bPrev, a);
650
+ }
651
+ case `1:n`: {
652
+ const aPrev = this.getRelatedKey(b);
653
+ if (aPrev && aPrev !== a)
654
+ this.delete(aPrev, b);
655
+ }
656
+ }
657
+ if (content) {
658
+ const contentKey = this.makeContentKey(a, b);
659
+ this.setContent(contentKey, content);
660
+ }
661
+ this.addRelation(a, b);
662
+ return this;
663
+ }
664
+ delete(x, b) {
665
+ b = typeof b === `string` ? b : x[this.b];
666
+ const a = typeof x === `string` ? x : x[this.a];
667
+ if (a === void 0 && typeof b === `string`) {
668
+ const bRelations = this.getRelatedKeys(b);
669
+ if (bRelations) {
670
+ for (const a2 of bRelations) {
671
+ this.delete(a2, b);
672
+ }
673
+ }
674
+ }
675
+ if (typeof a === `string` && b === void 0) {
676
+ const aRelations = this.getRelatedKeys(a);
677
+ if (aRelations) {
678
+ for (const b2 of aRelations) {
679
+ this.delete(a, b2);
680
+ }
681
+ }
682
+ }
683
+ if (typeof a === `string` && typeof b === `string`) {
684
+ this.deleteRelation(a, b);
685
+ const contentKey = this.makeContentKey(a, b);
686
+ this.deleteContent(contentKey);
687
+ }
688
+ return this;
689
+ }
690
+ getRelatedKey(key) {
691
+ const relations = this.getRelatedKeys(key);
692
+ if (relations) {
693
+ if (relations.size > 1) {
694
+ console.warn(
695
+ `${relations.size} related keys were found for key "${key}": (${[
696
+ ...relations
697
+ ].map((k) => `"${k}"`).join(`, `)}). Only one related key was expected.`
698
+ );
699
+ }
700
+ for (const relation of relations) {
701
+ return relation;
702
+ }
703
+ }
704
+ }
705
+ replaceRelations(a, relations, config) {
706
+ const hasContent = !Array.isArray(relations);
707
+ const bs = hasContent ? Object.keys(relations) : relations;
708
+ if (config == null ? void 0 : config.reckless) {
709
+ this.replaceRelationsUnsafely(a, bs);
710
+ } else {
711
+ this.replaceRelationsSafely(a, bs);
712
+ }
713
+ if (hasContent) {
714
+ for (const b of bs) {
715
+ const contentKey = this.makeContentKey(a, b);
716
+ const content = relations[b];
717
+ this.setContent(contentKey, content);
718
+ }
719
+ }
720
+ return this;
721
+ }
722
+ getContent(a, b) {
723
+ const contentKey = this.makeContentKey(a, b);
724
+ return this.getContentInternal(contentKey);
725
+ }
726
+ getRelationEntries(input) {
727
+ const a = input[this.a];
728
+ const b = input[this.b];
729
+ if (a !== void 0 && b === void 0) {
730
+ const aRelations = this.getRelatedKeys(a);
731
+ if (aRelations) {
732
+ return [...aRelations].map((b2) => {
733
+ var _a;
734
+ return [b2, (_a = this.getContent(a, b2)) != null ? _a : null];
735
+ });
736
+ }
737
+ }
738
+ if (a === void 0 && b !== void 0) {
739
+ const bRelations = this.getRelatedKeys(b);
740
+ if (bRelations) {
741
+ return [...bRelations].map((a2) => {
742
+ var _a;
743
+ return [a2, (_a = this.getContent(a2, b)) != null ? _a : null];
744
+ });
745
+ }
746
+ }
747
+ return [];
748
+ }
749
+ has(a, b) {
750
+ var _a;
751
+ if (b) {
752
+ const setA = this.getRelatedKeys(a);
753
+ return (_a = setA == null ? void 0 : setA.has(b)) != null ? _a : false;
754
+ }
755
+ return this.relations.has(a);
756
+ }
757
+ };
758
+
759
+ // internal/src/store/store.ts
760
+ var Store = class {
761
+ constructor(name, store = null) {
762
+ this.parent = null;
763
+ this.child = null;
764
+ this.valueMap = /* @__PURE__ */ new Map();
765
+ this.atoms = /* @__PURE__ */ new Map();
766
+ this.selectors = /* @__PURE__ */ new Map();
767
+ this.readonlySelectors = /* @__PURE__ */ new Map();
768
+ this.trackers = /* @__PURE__ */ new Map();
769
+ this.families = /* @__PURE__ */ new Map();
770
+ this.timelines = /* @__PURE__ */ new Map();
771
+ this.transactions = /* @__PURE__ */ new Map();
772
+ this.atomsThatAreDefault = /* @__PURE__ */ new Set();
773
+ this.timelineAtoms = new Junction({
774
+ between: [`timelineKey`, `atomKey`],
775
+ cardinality: `1:n`
776
+ });
777
+ this.selectorAtoms = new Junction({
778
+ between: [`selectorKey`, `atomKey`],
779
+ cardinality: `n:n`
780
+ });
781
+ this.selectorGraph = new Junction(
782
+ {
783
+ between: [`upstreamSelectorKey`, `downstreamSelectorKey`],
784
+ cardinality: `n:n`
785
+ },
786
+ {
787
+ makeContentKey: (...keys) => keys.sort().join(`:`)
788
+ }
789
+ );
790
+ this.subject = {
791
+ atomCreation: new Subject(),
792
+ selectorCreation: new Subject(),
793
+ transactionCreation: new Subject(),
794
+ timelineCreation: new Subject(),
795
+ transactionApplying: new StatefulSubject(null),
796
+ operationStatus: new Subject()
797
+ };
798
+ this.operation = { open: false };
799
+ this.transactionMeta = null;
800
+ this.config = {
801
+ name: `IMPLICIT_STORE`
802
+ };
803
+ this.loggers = [
804
+ new AtomIOLogger(`warn`, (_, __, key) => !key.includes(`\u{1F441}\u200D\u{1F5E8}`))
805
+ ];
806
+ this.logger = {
807
+ error: (...messages) => {
808
+ for (const logger of this.loggers)
809
+ logger.error(...messages);
810
+ },
811
+ info: (...messages) => {
812
+ for (const logger of this.loggers)
813
+ logger.info(...messages);
814
+ },
815
+ warn: (...messages) => {
816
+ for (const logger of this.loggers)
817
+ logger.warn(...messages);
818
+ }
819
+ };
820
+ if (store !== null) {
821
+ this.valueMap = new Map(store == null ? void 0 : store.valueMap);
822
+ this.operation = __spreadValues({}, store == null ? void 0 : store.operation);
823
+ this.transactionMeta = (store == null ? void 0 : store.transactionMeta) ? __spreadValues({}, store == null ? void 0 : store.transactionMeta) : null;
824
+ this.config = __spreadProps(__spreadValues({}, store == null ? void 0 : store.config), {
825
+ name
826
+ });
827
+ for (const [, atom] of store.atoms) {
828
+ atom.install(this);
829
+ }
830
+ for (const [, selector] of store.readonlySelectors) {
831
+ selector.install(this);
832
+ }
833
+ for (const [, selector] of store.selectors) {
834
+ selector.install(this);
835
+ }
836
+ for (const [, tx] of store.transactions) {
837
+ tx.install(this);
838
+ }
839
+ for (const [, timeline] of store.timelines) {
840
+ timeline.install(this);
841
+ }
842
+ }
843
+ }
844
+ };
845
+ var IMPLICIT = {
846
+ STORE_INTERNAL: void 0,
847
+ get STORE() {
848
+ var _a;
849
+ return (_a = this.STORE_INTERNAL) != null ? _a : this.STORE_INTERNAL = new Store(`IMPLICIT_STORE`);
850
+ }
851
+ };
852
+
853
+ // internal/src/store/withdraw.ts
854
+ function withdraw(token, store) {
855
+ var _a, _b, _c, _d;
856
+ const target = newest(store);
857
+ 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);
858
+ if (state) {
859
+ return state;
860
+ }
861
+ return void 0;
862
+ }
863
+
864
+ // internal/src/store/withdraw-new-family-member.ts
865
+ function withdrawNewFamilyMember(token, store) {
866
+ if (token.family) {
867
+ store.logger.info(
868
+ `\u{1F46A}`,
869
+ token.type,
870
+ token.key,
871
+ `creating new family member in store "${store.config.name}"`
872
+ );
873
+ const target = newest(store);
874
+ const family = target.families.get(token.family.key);
875
+ if (family) {
876
+ const jsonSubKey = JSON.parse(token.family.subKey);
877
+ family(jsonSubKey);
878
+ const state = withdraw(token, store);
879
+ return state;
880
+ }
881
+ }
882
+ return void 0;
883
+ }
884
+
885
+ // internal/src/keys.ts
886
+ var isAtomKey = (key, store) => newest(store).atoms.has(key);
887
+ var isSelectorKey = (key, store) => newest(store).selectors.has(key);
888
+ var isReadonlySelectorKey = (key, store) => newest(store).readonlySelectors.has(key);
889
+ var isStateKey = (key, store) => isAtomKey(key, store) || isSelectorKey(key, store) || isReadonlySelectorKey(key, store);
890
+
891
+ // internal/src/selector/get-selector-dependency-keys.ts
892
+ var getSelectorDependencyKeys = (key, store) => {
893
+ const sources = newest(store).selectorGraph.getRelationEntries({ downstreamSelectorKey: key }).filter(([_, { source }]) => source !== key).map(([_, { source }]) => source).filter((source) => isStateKey(source, store));
894
+ return sources;
895
+ };
896
+
897
+ // internal/src/selector/trace-selector-atoms.ts
898
+ var traceSelectorAtoms = (selectorKey, directDependencyKey, store) => {
899
+ const rootKeys = [];
900
+ const indirectDependencyKeys = getSelectorDependencyKeys(
901
+ directDependencyKey,
902
+ store
903
+ );
904
+ let depth = 0;
905
+ while (indirectDependencyKeys.length > 0) {
906
+ const indirectDependencyKey = indirectDependencyKeys.shift();
907
+ ++depth;
908
+ if (depth > 99999) {
909
+ throw new Error(
910
+ `Maximum selector dependency depth exceeded (> 99999) in selector "${selectorKey}". This is likely due to a circular dependency.`
911
+ );
912
+ }
913
+ if (!isAtomKey(indirectDependencyKey, store)) {
914
+ indirectDependencyKeys.push(
915
+ ...getSelectorDependencyKeys(indirectDependencyKey, store)
916
+ );
917
+ } else if (!rootKeys.includes(indirectDependencyKey)) {
918
+ rootKeys.push(indirectDependencyKey);
919
+ }
920
+ }
921
+ return rootKeys;
922
+ };
923
+ var traceAllSelectorAtoms = (selectorKey, store) => {
924
+ const directDependencyKeys = getSelectorDependencyKeys(selectorKey, store);
925
+ return directDependencyKeys.flatMap(
926
+ (depKey) => isAtomKey(depKey, store) ? depKey : traceSelectorAtoms(selectorKey, depKey, store)
927
+ );
928
+ };
929
+
930
+ // internal/src/selector/update-selector-atoms.ts
931
+ var updateSelectorAtoms = (selectorKey, dependency, store) => {
932
+ const target = newest(store);
933
+ if (dependency.type === `atom`) {
934
+ target.selectorAtoms.set({
935
+ selectorKey,
936
+ atomKey: dependency.key
937
+ });
938
+ store.logger.info(
939
+ `\u{1F50D}`,
940
+ `selector`,
941
+ selectorKey,
942
+ `discovers root atom "${dependency.key}"`
943
+ );
944
+ } else {
945
+ const rootKeys = traceSelectorAtoms(selectorKey, dependency.key, store);
946
+ store.logger.info(
947
+ `\u{1F50D}`,
948
+ `selector`,
949
+ selectorKey,
950
+ `discovers root atoms: [ ${rootKeys.map((key) => `"${key}"`).join(`, `)} ]`
951
+ );
952
+ for (const atomKey of rootKeys) {
953
+ target.selectorAtoms = target.selectorAtoms.set({
954
+ selectorKey,
955
+ atomKey
956
+ });
957
+ }
958
+ }
959
+ };
960
+
961
+ // internal/src/selector/register-selector.ts
962
+ var registerSelector = (selectorKey, store) => ({
963
+ get: (dependency) => {
964
+ const target = newest(store);
965
+ const alreadyRegistered = target.selectorGraph.getRelationEntries({ downstreamSelectorKey: selectorKey }).some(([_, { source }]) => source === dependency.key);
966
+ const dependencyState = withdraw(dependency, store);
967
+ if (dependencyState === void 0) {
968
+ throw new Error(
969
+ `State "${dependency.key}" not found in this store. Did you forget to initialize with the "atom" or "selector" function?`
970
+ );
971
+ }
972
+ const dependencyValue = readOrComputeValue(dependencyState, store);
973
+ store.logger.info(
974
+ `\u{1F50C}`,
975
+ `selector`,
976
+ selectorKey,
977
+ `registers dependency ( "${dependency.key}" =`,
978
+ dependencyValue,
979
+ `)`
980
+ );
981
+ if (!alreadyRegistered) {
982
+ target.selectorGraph.set(
983
+ {
984
+ upstreamSelectorKey: dependency.key,
985
+ downstreamSelectorKey: selectorKey
986
+ },
987
+ {
988
+ source: dependency.key
989
+ }
990
+ );
991
+ }
992
+ updateSelectorAtoms(selectorKey, dependency, store);
993
+ return dependencyValue;
994
+ },
995
+ set: (stateToken, newValue) => {
996
+ const state = withdraw(stateToken, store);
997
+ if (state === void 0) {
998
+ throw new Error(
999
+ `State "${stateToken.key}" not found in this store. Did you forget to initialize with the "atom" or "selector" function?`
1000
+ );
1001
+ }
1002
+ setAtomOrSelector(state, newValue, store);
1003
+ }
1004
+ });
1005
+
1006
+ // internal/src/selector/create-read-write-selector.ts
1007
+ var createReadWriteSelector = (options, family, store) => {
1008
+ const target = newest(store);
1009
+ const subject = new Subject();
1010
+ const { get, set } = registerSelector(options.key, store);
1011
+ const getSelf = () => {
1012
+ const value = options.get({ get });
1013
+ cacheValue(options.key, value, subject, store);
1014
+ return value;
1015
+ };
1016
+ const setSelf = (next) => {
1017
+ const oldValue = getSelf();
1018
+ const newValue = become(next)(oldValue);
1019
+ store.logger.info(
1020
+ `\u{1F4DD}`,
1021
+ `selector`,
1022
+ options.key,
1023
+ `set (`,
1024
+ oldValue,
1025
+ `->`,
1026
+ newValue,
1027
+ `)`
1028
+ );
1029
+ cacheValue(options.key, newValue, subject, store);
1030
+ markDone(options.key, store);
1031
+ if (target.transactionMeta === null) {
1032
+ subject.next({ newValue, oldValue });
1033
+ }
1034
+ options.set({ get, set }, newValue);
1035
+ };
1036
+ const mySelector = __spreadValues(__spreadProps(__spreadValues({}, options), {
1037
+ subject,
1038
+ install: (s) => createSelector(options, family, s),
1039
+ get: getSelf,
1040
+ set: setSelf,
1041
+ type: `selector`
1042
+ }), family && { family });
1043
+ target.selectors.set(options.key, mySelector);
1044
+ const initialValue = getSelf();
1045
+ store.logger.info(`\u2728`, mySelector.type, mySelector.key, `=`, initialValue);
1046
+ const token = {
1047
+ key: options.key,
1048
+ type: `selector`
1049
+ };
1050
+ if (family) {
1051
+ token.family = family;
1052
+ }
1053
+ store.subject.selectorCreation.next(token);
1054
+ return token;
1055
+ };
1056
+
1057
+ // internal/src/selector/create-readonly-selector.ts
1058
+ var createReadonlySelector = (options, family, store) => {
1059
+ const target = newest(store);
1060
+ const subject = new Subject();
1061
+ const { get } = registerSelector(options.key, store);
1062
+ const getSelf = () => {
1063
+ const value = options.get({ get });
1064
+ cacheValue(options.key, value, subject, store);
1065
+ return value;
1066
+ };
1067
+ const readonlySelector = __spreadValues(__spreadProps(__spreadValues({}, options), {
1068
+ subject,
1069
+ install: (s) => createSelector(options, family, s),
1070
+ get: getSelf,
1071
+ type: `readonly_selector`
1072
+ }), family && { family });
1073
+ target.readonlySelectors.set(options.key, readonlySelector);
1074
+ const initialValue = getSelf();
1075
+ store.logger.info(
1076
+ `\u2728`,
1077
+ readonlySelector.type,
1078
+ readonlySelector.key,
1079
+ `=`,
1080
+ initialValue
1081
+ );
1082
+ const token = {
1083
+ key: options.key,
1084
+ type: `readonly_selector`
1085
+ };
1086
+ if (family) {
1087
+ token.family = family;
1088
+ }
1089
+ store.subject.selectorCreation.next(token);
1090
+ return token;
1091
+ };
1092
+
1093
+ // internal/src/selector/create-selector.ts
1094
+ function createSelector(options, family, store) {
1095
+ const target = newest(store);
1096
+ const existingWritable = target.selectors.get(options.key);
1097
+ const existingReadonly = target.readonlySelectors.get(options.key);
1098
+ if (existingWritable || existingReadonly) {
1099
+ store.logger.error(
1100
+ `\u274C`,
1101
+ existingReadonly ? `readonly_selector` : `selector`,
1102
+ options.key,
1103
+ `Tried to create selector, but it already exists in the store. (Ignore if you are in development using hot module replacement.)`
1104
+ );
1105
+ }
1106
+ if (`set` in options) {
1107
+ return createReadWriteSelector(options, family, store);
1108
+ }
1109
+ return createReadonlySelector(options, family, store);
1110
+ }
1111
+
1112
+ // internal/src/selector/delete-selector.ts
1113
+ function deleteSelector(selectorToken, store) {
1114
+ const target = newest(store);
1115
+ const { key } = selectorToken;
1116
+ switch (selectorToken.type) {
1117
+ case `selector`:
1118
+ target.selectors.delete(key);
1119
+ break;
1120
+ case `readonly_selector`:
1121
+ target.readonlySelectors.delete(key);
1122
+ break;
1123
+ }
1124
+ target.valueMap.delete(key);
1125
+ target.selectorAtoms.delete(key);
1126
+ const downstreamTokens = target.selectorGraph.getRelationEntries({ upstreamSelectorKey: key }).filter(([_, { source }]) => source === key).map(
1127
+ ([downstreamSelectorKey]) => {
1128
+ var _a;
1129
+ return (_a = target.selectors.get(downstreamSelectorKey)) != null ? _a : target.readonlySelectors.get(downstreamSelectorKey);
1130
+ }
1131
+ );
1132
+ for (const downstreamToken of downstreamTokens) {
1133
+ if (downstreamToken) {
1134
+ deleteSelector(downstreamToken, store);
1135
+ }
1136
+ }
1137
+ target.selectorGraph.delete(key);
1138
+ store.logger.info(`\u{1F525}`, selectorToken.type, `${key}`, `deleted`);
1139
+ }
1140
+
1141
+ // internal/src/subscribe/recall-state.ts
1142
+ var recallState = (state, store) => {
1143
+ const target = newest(store);
1144
+ if (!target.operation.open) {
1145
+ return target.valueMap.get(state.key);
1146
+ }
1147
+ return target.operation.prev.get(state.key);
1148
+ };
1149
+
1150
+ // internal/src/subscribe/subscribe-to-root-atoms.ts
1151
+ var subscribeToRootAtoms = (state, store) => {
1152
+ const dependencySubscriptions = `default` in state ? null : traceAllSelectorAtoms(state.key, store).map((atomKey) => {
1153
+ const atom = store.atoms.get(atomKey);
1154
+ if (atom === void 0) {
1155
+ throw new Error(
1156
+ `Atom "${atomKey}", a dependency of selector "${state.key}", not found in store "${store.config.name}".`
1157
+ );
1158
+ }
1159
+ return atom.subject.subscribe(
1160
+ `${state.type}:${state.key}`,
1161
+ (atomChange) => {
1162
+ store.logger.info(
1163
+ `\u{1F4E2}`,
1164
+ state.type,
1165
+ state.key,
1166
+ `root`,
1167
+ atomKey,
1168
+ `went`,
1169
+ atomChange.oldValue,
1170
+ `->`,
1171
+ atomChange.newValue
1172
+ );
1173
+ const oldValue = recallState(state, store);
1174
+ const newValue = readOrComputeValue(state, store);
1175
+ store.logger.info(
1176
+ `\u2728`,
1177
+ state.type,
1178
+ state.key,
1179
+ `went`,
1180
+ oldValue,
1181
+ `->`,
1182
+ newValue
1183
+ );
1184
+ state.subject.next({ newValue, oldValue });
1185
+ }
1186
+ );
1187
+ });
1188
+ return dependencySubscriptions;
1189
+ };
1190
+
1191
+ // internal/src/subscribe/subscribe-to-state.ts
1192
+ function subscribeToState(token, handleUpdate, key, store) {
1193
+ const state = withdraw(token, store);
1194
+ if (state === void 0) {
1195
+ throw new Error(
1196
+ `State "${token.key}" not found in this store. Did you forget to initialize with the "atom" or "selector" function?`
1197
+ );
1198
+ }
1199
+ const unsubFunction = state.subject.subscribe(key, handleUpdate);
1200
+ store.logger.info(`\u{1F440}`, state.type, state.key, `Adding subscription "${key}"`);
1201
+ const dependencyUnsubFunctions = state.type !== `atom` ? subscribeToRootAtoms(state, store) : null;
1202
+ const unsubscribe = dependencyUnsubFunctions === null ? () => {
1203
+ store.logger.info(
1204
+ `\u{1F648}`,
1205
+ state.type,
1206
+ state.key,
1207
+ `Removing subscription "${key}"`
1208
+ );
1209
+ unsubFunction();
1210
+ } : () => {
1211
+ store.logger.info(
1212
+ `\u{1F648}`,
1213
+ state.type,
1214
+ state.key,
1215
+ `Removing subscription "${key}"`
1216
+ );
1217
+ unsubFunction();
1218
+ for (const unsubFromDependency of dependencyUnsubFunctions) {
1219
+ unsubFromDependency();
1220
+ }
1221
+ };
1222
+ return unsubscribe;
1223
+ }
1224
+
1225
+ // internal/src/subscribe/subscribe-to-timeline.ts
1226
+ var subscribeToTimeline = (token, handleUpdate, key, store) => {
1227
+ const tl = withdraw(token, store);
1228
+ if (tl === void 0) {
1229
+ throw new Error(
1230
+ `Cannot subscribe to timeline "${token.key}": timeline not found in store "${store.config.name}".`
1231
+ );
1232
+ }
1233
+ store.logger.info(`\u{1F440}`, `timeline`, token.key, `Adding subscription "${key}"`);
1234
+ const unsubscribe = tl.subject.subscribe(key, handleUpdate);
1235
+ return () => {
1236
+ store.logger.info(
1237
+ `\u{1F648}`,
1238
+ `timeline`,
1239
+ token.key,
1240
+ `Removing subscription "${key}" from timeline`
1241
+ );
1242
+ unsubscribe();
1243
+ };
1244
+ };
1245
+
1246
+ // internal/src/mutable/tracker.ts
1247
+ var Tracker = class {
1248
+ constructor(mutableState, store) {
1249
+ this.unsubscribeFromInnerValue = null;
1250
+ this.mutableState = mutableState;
1251
+ const target = newest(store);
1252
+ this.latestUpdateState = this.initializeState(mutableState, target);
1253
+ this.observeCore(mutableState, this.latestUpdateState, target);
1254
+ this.updateCore(mutableState, this.latestUpdateState, target);
1255
+ target.trackers.set(mutableState.key, this);
1256
+ }
1257
+ initializeState(mutableState, store) {
1258
+ const latestUpdateStateKey = `*${mutableState.key}`;
1259
+ deleteAtom({ type: `atom`, key: latestUpdateStateKey }, store);
1260
+ const familyMetaData = mutableState.family ? {
1261
+ key: `*${mutableState.family.key}`,
1262
+ subKey: mutableState.family.subKey
1263
+ } : void 0;
1264
+ const latestUpdateState = createAtom(
1265
+ {
1266
+ key: latestUpdateStateKey,
1267
+ default: null
1268
+ },
1269
+ familyMetaData,
1270
+ store
1271
+ );
1272
+ return latestUpdateState;
1273
+ }
1274
+ observeCore(mutableState, latestUpdateState, store) {
1275
+ const originalInnerValue = getState(mutableState, store);
1276
+ const target = newest(store);
1277
+ this.unsubscribeFromInnerValue = originalInnerValue.subscribe(
1278
+ `tracker:${store.config.name}:${target.transactionMeta === null ? `main` : target.transactionMeta.update.key}`,
1279
+ (update) => {
1280
+ const unsubscribe = store.subject.operationStatus.subscribe(
1281
+ mutableState.key,
1282
+ () => {
1283
+ unsubscribe();
1284
+ setState(latestUpdateState, update, store);
1285
+ }
1286
+ );
1287
+ }
1288
+ );
1289
+ subscribeToState(
1290
+ mutableState,
1291
+ (update) => {
1292
+ var _a;
1293
+ if (update.newValue !== update.oldValue) {
1294
+ (_a = this.unsubscribeFromInnerValue) == null ? void 0 : _a.call(this);
1295
+ const target2 = newest(store);
1296
+ this.unsubscribeFromInnerValue = update.newValue.subscribe(
1297
+ `tracker:${store.config.name}:${target2.transactionMeta === null ? `main` : target2.transactionMeta.update.key}`,
1298
+ (update2) => {
1299
+ const unsubscribe = store.subject.operationStatus.subscribe(
1300
+ mutableState.key,
1301
+ () => {
1302
+ unsubscribe();
1303
+ setState(latestUpdateState, update2, store);
1304
+ }
1305
+ );
1306
+ }
1307
+ );
1308
+ }
1309
+ },
1310
+ `${store.config.name}: tracker observing inner value`,
1311
+ store
1312
+ );
1313
+ }
1314
+ updateCore(mutableState, latestUpdateState, store) {
1315
+ subscribeToState(
1316
+ latestUpdateState,
1317
+ ({ newValue, oldValue }) => {
1318
+ const timelineId = store.timelineAtoms.getRelatedKey(
1319
+ latestUpdateState.key
1320
+ );
1321
+ if (timelineId) {
1322
+ const timelineData = store.timelines.get(timelineId);
1323
+ if (timelineData == null ? void 0 : timelineData.timeTraveling) {
1324
+ const unsubscribe2 = subscribeToTimeline(
1325
+ { key: timelineId, type: `timeline` },
1326
+ (update) => {
1327
+ unsubscribe2();
1328
+ setState(
1329
+ mutableState,
1330
+ (transceiver) => {
1331
+ if (update === `redo` && newValue) {
1332
+ transceiver.do(newValue);
1333
+ } else if (update === `undo` && oldValue) {
1334
+ transceiver.undo(oldValue);
1335
+ }
1336
+ return transceiver;
1337
+ },
1338
+ store
1339
+ );
1340
+ },
1341
+ `${mutableState.key}: tracker observing timeline`,
1342
+ store
1343
+ );
1344
+ return;
1345
+ }
1346
+ }
1347
+ const unsubscribe = store.subject.operationStatus.subscribe(
1348
+ latestUpdateState.key,
1349
+ () => {
1350
+ unsubscribe();
1351
+ const mutable = getState(mutableState, store);
1352
+ const updateNumber = mutable.getUpdateNumber(newValue);
1353
+ const eventOffset = updateNumber - mutable.cacheUpdateNumber;
1354
+ if (newValue && eventOffset === 1) {
1355
+ setState(
1356
+ mutableState,
1357
+ (transceiver) => (transceiver.do(newValue), transceiver),
1358
+ store
1359
+ );
1360
+ }
1361
+ }
1362
+ );
1363
+ },
1364
+ `${store.config.name}: tracker observing latest update`,
1365
+ store
1366
+ );
1367
+ }
1368
+ };
1369
+
1370
+ // internal/src/mutable/create-mutable-atom.ts
1371
+ function createMutableAtom(options, store) {
1372
+ store.logger.info(
1373
+ `\u{1F527}`,
1374
+ `atom`,
1375
+ options.key,
1376
+ `creating in store "${store.config.name}"`
1377
+ );
1378
+ const coreState = createAtom(options, void 0, store);
1379
+ new Tracker(coreState, store);
1380
+ const jsonState = selectJson(coreState, options, store);
1381
+ const target = newest(store);
1382
+ subscribeToState(
1383
+ jsonState,
1384
+ () => {
1385
+ const trackerHasBeenInitialized = newest(store).trackers.has(coreState.key);
1386
+ if (!trackerHasBeenInitialized) {
1387
+ new Tracker(coreState, store);
1388
+ }
1389
+ },
1390
+ `tracker-initializer:${store == null ? void 0 : store.config.name}:${target.transactionMeta === null ? `main` : `${target.transactionMeta.update.key}`}`,
1391
+ store
1392
+ );
1393
+ return coreState;
1394
+ }
1395
+
1396
+ // internal/src/mutable/get-json-token.ts
1397
+ var getJsonToken = (mutableAtomToken) => {
1398
+ const key = mutableAtomToken.family ? `${mutableAtomToken.family.key}:JSON(${mutableAtomToken.family.subKey})` : `${mutableAtomToken.key}:JSON`;
1399
+ const jsonToken = { type: `selector`, key };
1400
+ if (mutableAtomToken.family) {
1401
+ jsonToken.family = {
1402
+ key: `${mutableAtomToken.family.key}:JSON`,
1403
+ subKey: mutableAtomToken.family.subKey
1404
+ };
1405
+ }
1406
+ return jsonToken;
1407
+ };
1408
+
1409
+ // internal/src/mutable/transceiver.ts
1410
+ function isTransceiver(value) {
1411
+ return typeof value === `object` && value !== null && `do` in value && `undo` in value && `subscribe` in value;
1412
+ }
1413
+
1414
+ // internal/src/atom/is-default.ts
1415
+ var isAtomDefault = (key, store) => {
1416
+ const core = newest(store);
1417
+ return core.atomsThatAreDefault.has(key);
1418
+ };
1419
+ var markAtomAsDefault = (key, store) => {
1420
+ const core = newest(store);
1421
+ core.atomsThatAreDefault = new Set(core.atomsThatAreDefault).add(key);
1422
+ };
1423
+ var markAtomAsNotDefault = (key, store) => {
1424
+ const core = newest(store);
1425
+ core.atomsThatAreDefault = new Set(newest(store).atomsThatAreDefault);
1426
+ core.atomsThatAreDefault.delete(key);
1427
+ };
1428
+
1429
+ // internal/src/atom/create-atom.ts
1430
+ function createAtom(options, family, store) {
1431
+ store.logger.info(
1432
+ `\u{1F528}`,
1433
+ `atom`,
1434
+ options.key,
1435
+ `creating in store "${store.config.name}"`
1436
+ );
1437
+ const target = newest(store);
1438
+ const existing = target.atoms.get(options.key);
1439
+ if (existing) {
1440
+ store.logger.error(
1441
+ `\u274C`,
1442
+ `atom`,
1443
+ options.key,
1444
+ `Tried to create atom, but it already exists in the store.`,
1445
+ `(Ignore if you are in development using hot module replacement.)`
1446
+ );
1447
+ return deposit(existing);
1448
+ }
1449
+ const subject = new Subject();
1450
+ const newAtom = __spreadValues(__spreadProps(__spreadValues({}, options), {
1451
+ type: `atom`,
1452
+ install: (store2) => {
1453
+ store2.logger.info(
1454
+ `\u{1F6E0}\uFE0F`,
1455
+ `atom`,
1456
+ options.key,
1457
+ `installing in store "${store2.config.name}"`
1458
+ );
1459
+ return `mutable` in options ? createMutableAtom(options, store2) : createAtom(options, void 0, store2);
1460
+ },
1461
+ subject
1462
+ }), family && { family });
1463
+ let initialValue = options.default;
1464
+ if (options.default instanceof Function) {
1465
+ initialValue = options.default();
1466
+ }
1467
+ target.atoms.set(newAtom.key, newAtom);
1468
+ markAtomAsDefault(options.key, store);
1469
+ cacheValue(options.key, initialValue, subject, store);
1470
+ const token = deposit(newAtom);
1471
+ if (options.effects) {
1472
+ let effectIndex = 0;
1473
+ const cleanupFunctions = [];
1474
+ for (const effect of options.effects) {
1475
+ const cleanup = effect({
1476
+ setSelf: (next) => setState(token, next, store),
1477
+ onSet: (handle) => subscribeToState(token, handle, `effect[${effectIndex}]`, store)
1478
+ });
1479
+ if (cleanup) {
1480
+ cleanupFunctions.push(cleanup);
1481
+ }
1482
+ ++effectIndex;
1483
+ }
1484
+ newAtom.cleanup = () => {
1485
+ for (const cleanup of cleanupFunctions) {
1486
+ cleanup();
1487
+ }
1488
+ };
1489
+ }
1490
+ store.subject.atomCreation.next(token);
1491
+ return token;
1492
+ }
1493
+
1494
+ // internal/src/atom/delete-atom.ts
1495
+ function deleteAtom(atomToken, store) {
1496
+ var _a, _b;
1497
+ const target = newest(store);
1498
+ const { key } = atomToken;
1499
+ const atom = target.atoms.get(key);
1500
+ if (!atom) {
1501
+ store.logger.error(
1502
+ `\u274C`,
1503
+ `atom`,
1504
+ `${key}`,
1505
+ `Tried to delete atom, but it does not exist in the store.`
1506
+ );
1507
+ }
1508
+ (_a = atom == null ? void 0 : atom.cleanup) == null ? void 0 : _a.call(atom);
1509
+ target.atoms.delete(key);
1510
+ target.valueMap.delete(key);
1511
+ const selectorKeys = target.selectorAtoms.getRelatedKeys(key);
1512
+ if (selectorKeys) {
1513
+ for (const selectorKey of selectorKeys) {
1514
+ const token = (_b = target.selectors.get(selectorKey)) != null ? _b : target.readonlySelectors.get(selectorKey);
1515
+ if (token) {
1516
+ deleteSelector(token, store);
1517
+ }
1518
+ }
1519
+ }
1520
+ target.selectorAtoms.delete(key);
1521
+ target.atomsThatAreDefault.delete(key);
1522
+ target.timelineAtoms.delete(key);
1523
+ store.logger.info(`\u{1F525}`, `atom`, `${key}`, `deleted`);
1524
+ }
1525
+
1526
+ // internal/src/not-found-error.ts
1527
+ var capitalize = (str) => str[0].toUpperCase() + str.slice(1);
1528
+ function prettyPrintTokenType(token) {
1529
+ if (token.type === `readonly_selector`) {
1530
+ return `Readonly Selector`;
1531
+ }
1532
+ return capitalize(token.type);
1533
+ }
1534
+ var NotFoundError = class extends Error {
1535
+ constructor(token, store) {
1536
+ super(
1537
+ `${prettyPrintTokenType(token)} "${token.key}" not found in store "${store.config.name}".`
1538
+ );
1539
+ }
1540
+ };
1541
+
1542
+ // internal/src/timeline/time-travel.ts
1543
+ var timeTravel = (direction, token, store) => {
1544
+ const action = direction === `forward` ? `redo` : `undo`;
1545
+ store.logger.info(
1546
+ direction === `forward` ? `\u23E9` : `\u23EA`,
1547
+ `timeline`,
1548
+ token.key,
1549
+ action
1550
+ );
1551
+ const timelineData = store.timelines.get(token.key);
1552
+ if (!timelineData) {
1553
+ store.logger.error(
1554
+ `\u{1F41E}`,
1555
+ `timeline`,
1556
+ token.key,
1557
+ `Failed to ${action}. This timeline has not been initialized.`
1558
+ );
1559
+ return;
1560
+ }
1561
+ if (direction === `forward` && timelineData.at === timelineData.history.length || direction === `backward` && timelineData.at === 0) {
1562
+ store.logger.warn(
1563
+ `\u{1F481}`,
1564
+ `timeline`,
1565
+ token.key,
1566
+ `Failed to ${action} at the ${direction === `forward` ? `end` : `beginning`} of timeline "${token.key}". There is nothing to ${action}.`
1567
+ );
1568
+ return;
1569
+ }
1570
+ timelineData.timeTraveling = direction === `forward` ? `into_future` : `into_past`;
1571
+ if (direction === `backward`) {
1572
+ --timelineData.at;
1573
+ }
1574
+ const update = timelineData.history[timelineData.at];
1575
+ const updateValues = (atomUpdate) => {
1576
+ const { key, newValue, oldValue } = atomUpdate;
1577
+ const value = direction === `forward` ? newValue : oldValue;
1578
+ setState({ key, type: `atom` }, value, store);
1579
+ };
1580
+ const updateValuesFromTransactionUpdate = (transactionUpdate) => {
1581
+ const updates = direction === `forward` ? transactionUpdate.updates : [...transactionUpdate.updates].reverse();
1582
+ for (const updateFromTransaction of updates) {
1583
+ if (`newValue` in updateFromTransaction) {
1584
+ updateValues(updateFromTransaction);
1585
+ } else {
1586
+ updateValuesFromTransactionUpdate(updateFromTransaction);
1587
+ }
1588
+ }
1589
+ };
1590
+ switch (update.type) {
1591
+ case `atom_update`: {
1592
+ updateValues(update);
1593
+ break;
1594
+ }
1595
+ case `selector_update`: {
1596
+ const updates = direction === `forward` ? update.atomUpdates : [...update.atomUpdates].reverse();
1597
+ for (const atomUpdate of updates) {
1598
+ updateValues(atomUpdate);
1599
+ }
1600
+ break;
1601
+ }
1602
+ case `transaction_update`: {
1603
+ updateValuesFromTransactionUpdate(update);
1604
+ break;
1605
+ }
1606
+ }
1607
+ if (direction === `forward`) {
1608
+ ++timelineData.at;
1609
+ }
1610
+ timelineData.subject.next(action);
1611
+ timelineData.timeTraveling = null;
1612
+ store.logger.info(
1613
+ `\u23F9\uFE0F`,
1614
+ `timeline`,
1615
+ token.key,
1616
+ `"${token.key}" is now at ${timelineData.at} / ${timelineData.history.length}`
1617
+ );
1618
+ };
1619
+ var StoreContext = React2__namespace.createContext(IMPLICIT.STORE);
1620
+ var StoreProvider = ({ children, store = IMPLICIT.STORE }) => /* @__PURE__ */ jsxRuntime.jsx(StoreContext.Provider, { value: store, children });
31
1621
  function useI(token) {
32
1622
  const store = React2__namespace.useContext(StoreContext);
33
1623
  const setter = React2__namespace.useRef(null);
34
1624
  if (setter.current === null) {
35
- setter.current = (next) => atom_io.setState(token, next, store);
1625
+ setter.current = (next) => setState(token, next, store);
36
1626
  }
37
1627
  return setter.current;
38
1628
  }
@@ -40,19 +1630,19 @@ function useO(token) {
40
1630
  const store = React2__namespace.useContext(StoreContext);
41
1631
  const id = React2__namespace.useId();
42
1632
  return React2__namespace.useSyncExternalStore(
43
- (dispatch) => internal.subscribeToState(token, dispatch, `use-o:${id}`, store),
44
- () => atom_io.getState(token, store),
45
- () => atom_io.getState(token, store)
1633
+ (dispatch) => subscribeToState(token, dispatch, `use-o:${id}`, store),
1634
+ () => getState(token, store),
1635
+ () => getState(token, store)
46
1636
  );
47
1637
  }
48
1638
  function useJSON(token) {
49
- const jsonToken = internal.getJsonToken(token);
1639
+ const jsonToken = getJsonToken(token);
50
1640
  return useO(jsonToken);
51
1641
  }
52
1642
  function useTL(token) {
53
1643
  const store = React2__namespace.useContext(StoreContext);
54
1644
  const id = React2__namespace.useId();
55
- const timeline = internal.withdraw(token, store);
1645
+ const timeline = withdraw(token, store);
56
1646
  if (timeline === void 0) {
57
1647
  store.logger.error(
58
1648
  `\u274C`,
@@ -72,8 +1662,8 @@ function useTL(token) {
72
1662
  const meta = React2__namespace.useRef({
73
1663
  at: timeline.at,
74
1664
  length: timeline.history.length,
75
- undo: () => atom_io.undo(token),
76
- redo: () => atom_io.redo(token)
1665
+ undo: () => undo(token),
1666
+ redo: () => redo(token)
77
1667
  });
78
1668
  const retrieve = React2__namespace.useCallback(() => {
79
1669
  meta.current.at = timeline.at;
@@ -81,7 +1671,7 @@ function useTL(token) {
81
1671
  return meta.current;
82
1672
  }, [meta]);
83
1673
  return React2__namespace.useSyncExternalStore(
84
- (dispatch) => internal.subscribeToTimeline(token, dispatch, `use-tl:${id}`, store),
1674
+ (dispatch) => subscribeToTimeline(token, dispatch, `use-tl:${id}`, store),
85
1675
  retrieve,
86
1676
  retrieve
87
1677
  );