atom.io 0.6.8 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (214) hide show
  1. package/README.md +21 -2
  2. package/dist/index.d.mts +42 -461
  3. package/dist/index.d.ts +42 -461
  4. package/dist/index.js +128 -1792
  5. package/dist/index.js.map +1 -1
  6. package/dist/index.mjs +75 -1742
  7. package/dist/index.mjs.map +1 -1
  8. package/internal/dist/index.d.mts +342 -0
  9. package/internal/dist/index.d.ts +342 -0
  10. package/internal/dist/index.js +1873 -0
  11. package/internal/dist/index.js.map +1 -0
  12. package/internal/dist/index.mjs +1798 -0
  13. package/internal/dist/index.mjs.map +1 -0
  14. package/internal/package.json +15 -0
  15. package/internal/src/atom/create-atom.ts +75 -0
  16. package/internal/src/atom/delete-atom.ts +10 -0
  17. package/internal/src/atom/index.ts +3 -0
  18. package/{src/internal → internal/src/atom}/is-default.ts +4 -2
  19. package/internal/src/caching.ts +21 -0
  20. package/internal/src/families/create-atom-family.ts +59 -0
  21. package/internal/src/families/create-readonly-selector-family.ts +45 -0
  22. package/internal/src/families/create-selector-family.ts +67 -0
  23. package/internal/src/families/index.ts +3 -0
  24. package/internal/src/get-state-internal.ts +23 -0
  25. package/internal/src/index.ts +13 -0
  26. package/internal/src/mutable/create-mutable-atom-family.ts +25 -0
  27. package/internal/src/mutable/create-mutable-atom.ts +49 -0
  28. package/internal/src/mutable/get-json-token.ts +22 -0
  29. package/internal/src/mutable/get-update-token.ts +20 -0
  30. package/internal/src/mutable/index.ts +17 -0
  31. package/internal/src/mutable/is-atom-token-mutable.ts +7 -0
  32. package/internal/src/mutable/tracker-family.ts +61 -0
  33. package/internal/src/mutable/tracker.ts +164 -0
  34. package/internal/src/mutable/transceiver.ts +110 -0
  35. package/internal/src/operation.ts +68 -0
  36. package/{src/internal → internal/src}/selector/create-read-write-selector.ts +10 -13
  37. package/{src/internal → internal/src}/selector/create-readonly-selector.ts +9 -8
  38. package/internal/src/selector/create-selector.ts +65 -0
  39. package/{src/internal → internal/src}/selector/index.ts +1 -0
  40. package/internal/src/selector/lookup-selector-sources.ts +20 -0
  41. package/{src/internal → internal/src}/selector/register-selector.ts +13 -9
  42. package/{src/internal → internal/src}/selector/trace-selector-atoms.ts +4 -2
  43. package/{src/internal → internal/src}/selector/update-selector-atoms.ts +4 -3
  44. package/internal/src/set-state/become.ts +10 -0
  45. package/internal/src/set-state/copy-mutable-if-needed.ts +23 -0
  46. package/internal/src/set-state/copy-mutable-in-transaction.ts +59 -0
  47. package/internal/src/set-state/copy-mutable-into-new-store.ts +34 -0
  48. package/internal/src/set-state/emit-update.ts +23 -0
  49. package/internal/src/set-state/evict-downstream.ts +39 -0
  50. package/internal/src/set-state/index.ts +2 -0
  51. package/internal/src/set-state/set-atom-state.ts +38 -0
  52. package/internal/src/set-state/set-selector-state.ts +19 -0
  53. package/internal/src/set-state/set-state-internal.ts +18 -0
  54. package/internal/src/set-state/stow-update.ts +42 -0
  55. package/internal/src/store/deposit.ts +43 -0
  56. package/internal/src/store/index.ts +5 -0
  57. package/internal/src/store/lookup.ts +26 -0
  58. package/internal/src/store/store.ts +154 -0
  59. package/internal/src/store/withdraw-new-family-member.ts +53 -0
  60. package/internal/src/store/withdraw.ts +113 -0
  61. package/internal/src/subject.ts +21 -0
  62. package/internal/src/subscribe/index.ts +1 -0
  63. package/internal/src/subscribe/recall-state.ts +19 -0
  64. package/internal/src/subscribe/subscribe-to-root-atoms.ts +47 -0
  65. package/{src/internal → internal/src}/timeline/add-atom-to-timeline.ts +50 -29
  66. package/internal/src/timeline/index.ts +3 -0
  67. package/{src/internal → internal/src/timeline}/time-travel-internal.ts +6 -6
  68. package/{src/internal → internal/src/timeline}/timeline-internal.ts +20 -12
  69. package/{src/internal → internal/src}/transaction/abort-transaction.ts +1 -1
  70. package/{src/internal → internal/src}/transaction/apply-transaction.ts +25 -18
  71. package/{src/internal → internal/src}/transaction/build-transaction.ts +12 -6
  72. package/{src/internal → internal/src}/transaction/index.ts +3 -2
  73. package/{src/internal → internal/src}/transaction/redo-transaction.ts +4 -5
  74. package/{src/internal → internal/src/transaction}/transaction-internal.ts +16 -13
  75. package/{src/internal → internal/src}/transaction/undo-transaction.ts +4 -5
  76. package/introspection/dist/index.d.mts +12 -260
  77. package/introspection/dist/index.d.ts +12 -260
  78. package/introspection/dist/index.js +125 -140
  79. package/introspection/dist/index.js.map +1 -1
  80. package/introspection/dist/index.mjs +103 -116
  81. package/introspection/dist/index.mjs.map +1 -1
  82. package/{src/introspection → introspection/src}/attach-atom-index.ts +41 -30
  83. package/{src/introspection → introspection/src}/attach-introspection-states.ts +6 -10
  84. package/introspection/src/attach-selector-index.ts +90 -0
  85. package/{src/introspection → introspection/src}/attach-timeline-family.ts +16 -16
  86. package/introspection/src/attach-timeline-index.ts +38 -0
  87. package/introspection/src/attach-transaction-index.ts +40 -0
  88. package/{src/introspection → introspection/src}/attach-transaction-logs.ts +11 -8
  89. package/json/dist/index.d.mts +41 -2
  90. package/json/dist/index.d.ts +41 -2
  91. package/json/dist/index.js +88 -48
  92. package/json/dist/index.js.map +1 -1
  93. package/json/dist/index.mjs +76 -13
  94. package/json/dist/index.mjs.map +1 -1
  95. package/json/src/index.ts +5 -0
  96. package/json/src/select-json-family.ts +35 -0
  97. package/json/src/select-json.ts +22 -0
  98. package/package.json +105 -57
  99. package/react/dist/index.d.mts +9 -17
  100. package/react/dist/index.d.ts +9 -17
  101. package/react/dist/index.js +45 -77
  102. package/react/dist/index.js.map +1 -1
  103. package/react/dist/index.mjs +18 -34
  104. package/react/dist/index.mjs.map +1 -1
  105. package/react/src/store-context.tsx +12 -0
  106. package/react/src/store-hooks.ts +36 -0
  107. package/react-devtools/dist/index.css +1 -1
  108. package/react-devtools/dist/index.css.map +1 -1
  109. package/react-devtools/dist/index.d.mts +199 -230
  110. package/react-devtools/dist/index.d.ts +199 -230
  111. package/react-devtools/dist/index.js +610 -2466
  112. package/react-devtools/dist/index.js.map +1 -1
  113. package/react-devtools/dist/index.mjs +543 -2401
  114. package/react-devtools/dist/index.mjs.map +1 -1
  115. package/{src/react-devtools → react-devtools/src}/AtomIODevtools.tsx +5 -3
  116. package/{src/react-devtools → react-devtools/src}/Button.tsx +2 -3
  117. package/{src/react-devtools → react-devtools/src}/StateEditor.tsx +3 -2
  118. package/{src/react-devtools → react-devtools/src}/StateIndex.tsx +7 -4
  119. package/{src/react-devtools → react-devtools/src}/TimelineIndex.tsx +7 -11
  120. package/{src/react-devtools → react-devtools/src}/TransactionIndex.tsx +4 -4
  121. package/{src/react-devtools → react-devtools/src}/Updates.tsx +9 -4
  122. package/{src/react-devtools → react-devtools/src}/index.ts +5 -5
  123. package/realtime-react/dist/index.d.mts +9 -25
  124. package/realtime-react/dist/index.d.ts +9 -25
  125. package/realtime-react/dist/index.js +75 -193
  126. package/realtime-react/dist/index.js.map +1 -1
  127. package/realtime-react/dist/index.mjs +44 -148
  128. package/realtime-react/dist/index.mjs.map +1 -1
  129. package/realtime-react/src/index.ts +7 -0
  130. package/{src/realtime-react → realtime-react/src}/realtime-context.tsx +3 -4
  131. package/realtime-react/src/use-pull-family-member.ts +15 -0
  132. package/realtime-react/src/use-pull-mutable-family-member.ts +20 -0
  133. package/realtime-react/src/use-pull-mutable.ts +17 -0
  134. package/realtime-react/src/use-pull.ts +15 -0
  135. package/realtime-react/src/use-push.ts +19 -0
  136. package/realtime-react/src/use-server-action.ts +18 -0
  137. package/realtime-testing/dist/index.d.mts +49 -0
  138. package/realtime-testing/dist/index.d.ts +49 -0
  139. package/realtime-testing/dist/index.js +147 -0
  140. package/realtime-testing/dist/index.js.map +1 -0
  141. package/realtime-testing/dist/index.mjs +116 -0
  142. package/realtime-testing/dist/index.mjs.map +1 -0
  143. package/{src/realtime-testing → realtime-testing/src}/setup-realtime-test.tsx +10 -8
  144. package/src/atom.ts +64 -8
  145. package/src/index.ts +36 -29
  146. package/src/logger.ts +7 -7
  147. package/src/selector.ts +5 -5
  148. package/src/silo.ts +49 -43
  149. package/src/subscribe.ts +27 -22
  150. package/src/timeline.ts +9 -4
  151. package/src/transaction.ts +3 -4
  152. package/transceivers/set-rtx/dist/index.d.mts +39 -0
  153. package/transceivers/set-rtx/dist/index.d.ts +39 -0
  154. package/transceivers/set-rtx/dist/index.js +213 -0
  155. package/transceivers/set-rtx/dist/index.js.map +1 -0
  156. package/transceivers/set-rtx/dist/index.mjs +211 -0
  157. package/transceivers/set-rtx/dist/index.mjs.map +1 -0
  158. package/{realtime → transceivers/set-rtx}/package.json +1 -1
  159. package/transceivers/set-rtx/src/index.ts +1 -0
  160. package/transceivers/set-rtx/src/set-rtx.ts +242 -0
  161. package/realtime/dist/index.d.mts +0 -25
  162. package/realtime/dist/index.d.ts +0 -25
  163. package/realtime/dist/index.js +0 -190
  164. package/realtime/dist/index.js.map +0 -1
  165. package/realtime/dist/index.mjs +0 -151
  166. package/realtime/dist/index.mjs.map +0 -1
  167. package/src/internal/atom-internal.ts +0 -54
  168. package/src/internal/families-internal.ts +0 -144
  169. package/src/internal/get.ts +0 -129
  170. package/src/internal/index.ts +0 -15
  171. package/src/internal/operation.ts +0 -139
  172. package/src/internal/selector/lookup-selector-sources.ts +0 -16
  173. package/src/internal/selector-internal.ts +0 -58
  174. package/src/internal/set.ts +0 -99
  175. package/src/internal/store.ts +0 -151
  176. package/src/internal/subscribe-internal.ts +0 -88
  177. package/src/internal/timeline/index.ts +0 -1
  178. package/src/introspection/attach-selector-index.ts +0 -77
  179. package/src/introspection/attach-timeline-index.ts +0 -36
  180. package/src/introspection/attach-transaction-index.ts +0 -38
  181. package/src/json/index.ts +0 -1
  182. package/src/json/select-json.ts +0 -18
  183. package/src/react/store-context.tsx +0 -13
  184. package/src/react/store-hooks.ts +0 -47
  185. package/src/react-explorer/AtomIOExplorer.tsx +0 -218
  186. package/src/react-explorer/explorer-effects.ts +0 -20
  187. package/src/react-explorer/explorer-states.ts +0 -217
  188. package/src/react-explorer/index.ts +0 -23
  189. package/src/react-explorer/space-states.ts +0 -72
  190. package/src/react-explorer/view-states.ts +0 -41
  191. package/src/realtime/README.md +0 -33
  192. package/src/realtime/hook-composition/expose-family.ts +0 -101
  193. package/src/realtime/hook-composition/expose-single.ts +0 -38
  194. package/src/realtime/hook-composition/expose-timeline.ts +0 -60
  195. package/src/realtime/hook-composition/index.ts +0 -12
  196. package/src/realtime/hook-composition/receive-state.ts +0 -29
  197. package/src/realtime/hook-composition/receive-transaction.ts +0 -18
  198. package/src/realtime/index.ts +0 -1
  199. package/src/realtime-react/index.ts +0 -3
  200. package/src/realtime-react/realtime-hooks.ts +0 -39
  201. package/src/realtime-react/realtime-state.ts +0 -10
  202. package/src/realtime-react/use-pull-family-member.ts +0 -26
  203. package/src/realtime-react/use-pull-family.ts +0 -24
  204. package/src/realtime-react/use-pull.ts +0 -24
  205. package/src/realtime-react/use-push.ts +0 -27
  206. package/src/realtime-react/use-server-action.ts +0 -33
  207. package/src/tracker/index.ts +0 -3
  208. package/src/tracker/tracker.ts +0 -61
  209. package/src/web-effects/index.ts +0 -1
  210. package/src/web-effects/storage.ts +0 -30
  211. /package/{src/introspection → introspection/src}/index.ts +0 -0
  212. /package/{src/react → react/src}/index.ts +0 -0
  213. /package/{src/react-devtools → react-devtools/src}/devtools.scss +0 -0
  214. /package/{src/realtime-testing → realtime-testing/src}/index.ts +0 -0
package/dist/index.mjs CHANGED
@@ -1,6 +1,7 @@
1
+ import * as IO from 'atom.io/internal';
2
+ import { createMutableAtom, createAtom, createMutableAtomFamily, createAtomFamily, IMPLICIT, createSelector, createSelectorFamily, Store, transaction__INTERNAL, timeline__INTERNAL, undo__INTERNAL, redo__INTERNAL, withdraw, subscribeToRootAtoms } from 'atom.io/internal';
3
+
1
4
  var __defProp = Object.defineProperty;
2
- var __defProps = Object.defineProperties;
3
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
5
  var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
6
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
7
  var __propIsEnum = Object.prototype.propertyIsEnumerable;
@@ -16,1669 +17,19 @@ var __spreadValues = (a, b) => {
16
17
  }
17
18
  return a;
18
19
  };
19
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
20
- var __objRest = (source, exclude) => {
21
- var target2 = {};
22
- for (var prop in source)
23
- if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
24
- target2[prop] = source[prop];
25
- if (source != null && __getOwnPropSymbols)
26
- for (var prop of __getOwnPropSymbols(source)) {
27
- if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
28
- target2[prop] = source[prop];
29
- }
30
- return target2;
31
- };
32
- var __export = (target2, all) => {
33
- for (var name in all)
34
- __defProp(target2, name, { get: all[name], enumerable: true });
35
- };
36
-
37
- // ../anvl/src/string/capitalize.ts
38
- var capitalize = (str) => str[0].toUpperCase() + str.slice(1);
39
-
40
- // src/internal/index.ts
41
- var internal_exports = {};
42
- __export(internal_exports, {
43
- IMPLICIT: () => IMPLICIT,
44
- Subject: () => Subject,
45
- TRANSACTION_PHASES: () => TRANSACTION_PHASES,
46
- abortTransaction: () => abortTransaction,
47
- applyTransaction: () => applyTransaction,
48
- atomFamily__INTERNAL: () => atomFamily__INTERNAL,
49
- atom__INTERNAL: () => atom__INTERNAL,
50
- buildTransaction: () => buildTransaction,
51
- cacheValue: () => cacheValue,
52
- clearStore: () => clearStore,
53
- closeOperation: () => closeOperation,
54
- computeSelectorState: () => computeSelectorState,
55
- createStore: () => createStore,
56
- deposit: () => deposit,
57
- emitUpdate: () => emitUpdate,
58
- evictCachedValue: () => evictCachedValue,
59
- evictDownStream: () => evictDownStream,
60
- getState__INTERNAL: () => getState__INTERNAL,
61
- hasKeyBeenUsed: () => hasKeyBeenUsed,
62
- isAtomDefault: () => isAtomDefault,
63
- isDone: () => isDone,
64
- isSelectorDefault: () => isSelectorDefault,
65
- isValueCached: () => isValueCached,
66
- lookup: () => lookup,
67
- lookupSelectorSources: () => lookupSelectorSources,
68
- markAtomAsDefault: () => markAtomAsDefault,
69
- markAtomAsNotDefault: () => markAtomAsNotDefault,
70
- markDone: () => markDone,
71
- openOperation: () => openOperation,
72
- prepareUpdate: () => prepareUpdate,
73
- readCachedValue: () => readCachedValue,
74
- readonlySelectorFamily__INTERNAL: () => readonlySelectorFamily__INTERNAL,
75
- recallState: () => recallState,
76
- redoTransactionUpdate: () => redoTransactionUpdate,
77
- redo__INTERNAL: () => redo__INTERNAL,
78
- registerSelector: () => registerSelector,
79
- selectorFamily__INTERNAL: () => selectorFamily__INTERNAL,
80
- selector__INTERNAL: () => selector__INTERNAL,
81
- setAtomState: () => setAtomState,
82
- setSelectorState: () => setSelectorState,
83
- setState__INTERNAL: () => setState__INTERNAL,
84
- storeAtom: () => storeAtom,
85
- storeReadonlySelector: () => storeReadonlySelector,
86
- storeSelector: () => storeSelector,
87
- stowUpdate: () => stowUpdate,
88
- subscribeToRootAtoms: () => subscribeToRootAtoms,
89
- target: () => target,
90
- timeline__INTERNAL: () => timeline__INTERNAL,
91
- traceAllSelectorAtoms: () => traceAllSelectorAtoms,
92
- traceSelectorAtoms: () => traceSelectorAtoms,
93
- transaction__INTERNAL: () => transaction__INTERNAL,
94
- undoTransactionUpdate: () => undoTransactionUpdate,
95
- undo__INTERNAL: () => undo__INTERNAL,
96
- updateSelectorAtoms: () => updateSelectorAtoms,
97
- withdraw: () => withdraw
98
- });
99
-
100
- // src/internal/get.ts
101
- var computeSelectorState = (selector2) => selector2.get();
102
- function lookup(key, store) {
103
- const core = target(store);
104
- const type = core.atoms.has(key) ? `atom` : core.selectors.has(key) ? `selector` : `readonly_selector`;
105
- return { key, type };
106
- }
107
- function withdraw(token, store) {
108
- var _a, _b, _c, _d, _e;
109
- const core = target(store);
110
- return (_e = (_d = (_c = (_b = (_a = core.atoms.get(token.key)) != null ? _a : core.selectors.get(token.key)) != null ? _b : core.readonlySelectors.get(token.key)) != null ? _c : core.transactions.get(token.key)) != null ? _d : core.timelines.get(token.key)) != null ? _e : null;
111
- }
112
- function deposit(state) {
113
- return __spreadValues({
114
- key: state.key,
115
- type: state.type
116
- }, `family` in state && { family: state.family });
117
- }
118
- var getState__INTERNAL = (state, store = IMPLICIT.STORE) => {
119
- var _a, _b, _c;
120
- if (isValueCached(state.key, store)) {
121
- (_a = store.config.logger) == null ? void 0 : _a.info(`>> read "${state.key}"`);
122
- return readCachedValue(state.key, store);
123
- }
124
- if (state.type !== `atom`) {
125
- (_b = store.config.logger) == null ? void 0 : _b.info(`-> calc "${state.key}"`);
126
- return computeSelectorState(state);
127
- }
128
- (_c = store.config.logger) == null ? void 0 : _c.error(
129
- `Attempted to get atom "${state.key}", which was never initialized in store "${store.config.name}".`
130
- );
131
- return state.default;
132
- };
133
-
134
- // src/internal/is-default.ts
135
- var isAtomDefault = (key, store = IMPLICIT.STORE) => {
136
- const core = target(store);
137
- return core.atomsThatAreDefault.has(key);
138
- };
139
- var markAtomAsDefault = (key, store = IMPLICIT.STORE) => {
140
- const core = target(store);
141
- core.atomsThatAreDefault = new Set(core.atomsThatAreDefault).add(key);
142
- };
143
- var markAtomAsNotDefault = (key, store = IMPLICIT.STORE) => {
144
- const core = target(store);
145
- core.atomsThatAreDefault = new Set(target(store).atomsThatAreDefault);
146
- core.atomsThatAreDefault.delete(key);
147
- };
148
- var isSelectorDefault = (key, store = IMPLICIT.STORE) => {
149
- const roots = traceAllSelectorAtoms(key, store);
150
- return roots.every((root) => isAtomDefault(root.key, store));
151
- };
152
-
153
- // ../anvl/src/function/index.ts
154
- var doNothing = () => void 0;
155
- var become = (nextVersionOfThing) => (originalThing) => nextVersionOfThing instanceof Function ? nextVersionOfThing(
156
- originalThing instanceof Function ? originalThing() : originalThing
157
- ) : nextVersionOfThing;
158
- var pass = (...params) => (fn) => fn(...params);
159
-
160
- // ../anvl/src/join/core-relation-data.ts
161
- import { isString } from "fp-ts/string";
162
-
163
- // ../anvl/src/array/venn.ts
164
- var includesAll = (items) => (array) => {
165
- for (const item of items) {
166
- if (!array.includes(item))
167
- return false;
168
- }
169
- return true;
170
- };
171
- var comprises = (items) => (array) => includesAll(items)(array) && includesAll(array)(items);
172
-
173
- // ../anvl/src/array/index.ts
174
- var isArray = (isType) => (input) => Array.isArray(input) && input.every((item) => isType(item));
175
- var map = (f) => (a) => a.map(f);
176
- var every = (f = Boolean) => (a) => a.every(f);
177
- var allTrue = every((x) => x === true);
178
- var addTo = (a) => (x) => a.includes(x) ? a : [...a, x];
179
- var isEmptyArray = (input) => Array.isArray(input) && input.length === 0;
180
- var isOneOf = (...args) => (input) => args.includes(input);
181
-
182
- // ../anvl/src/object/refinement.ts
183
- import { pipe as pipe2 } from "fp-ts/function";
184
-
185
- // ../anvl/src/object/access.ts
186
- var access = (k) => Object.assign((obj) => obj[k], {
187
- in: (obj) => obj[k]
188
- });
189
-
190
- // ../anvl/src/object/entries.ts
191
- var recordToEntries = (obj) => Object.entries(obj);
192
- var entriesToRecord = (entries) => Object.fromEntries(entries);
193
-
194
- // ../anvl/src/object/mapObject.ts
195
- import { pipe } from "fp-ts/function";
196
- var mapObject = (obj, fn) => pipe(
197
- obj,
198
- recordToEntries,
199
- map(([key, val]) => [key, fn(val, key)]),
200
- entriesToRecord
201
- );
202
- var mob = (fn) => (obj) => mapObject(obj, fn);
203
-
204
- // ../anvl/src/nullish/index.ts
205
- var isUndefined = (input) => input === void 0;
206
- var ifNullish = (alt) => (input) => input != null ? input : alt;
207
-
208
- // ../anvl/src/object/refinement.ts
209
- var isNonNullObject = (input) => typeof input === `object` && input !== null;
210
- var isPlainObject = (input) => isNonNullObject(input) && Object.getPrototypeOf(input) === Object.prototype;
211
- var isEmptyObject = (input) => isPlainObject(input) && Object.keys(input).length === 0;
212
- var isRecord = (isKey, isValue) => (input) => isPlainObject(input) && Object.entries(input).every(([k, v]) => isKey(k) && isValue(v));
213
- var hasProperties = (isValue, options = { allowExtraProperties: false }) => {
214
- const name = `{${recordToEntries(
215
- isValue
216
- ).map(([k, v]) => String(k) + `:` + v.name).join(`,`)}}`;
217
- const _ = {
218
- [name]: (input) => isPlainObject(input) && pipe2(
219
- isValue,
220
- Object.entries,
221
- every(([key, val]) => key in input || val(void 0))
222
- ) && pipe2(
223
- input,
224
- mob(
225
- (val, key) => pipe2(
226
- isValue,
227
- access(key),
228
- ifNullish(() => options.allowExtraProperties),
229
- pass(val)
230
- )
231
- ),
232
- Object.values,
233
- allTrue
234
- )
235
- };
236
- return _[name];
237
- };
238
- var hasExactProperties = (
239
- /* alias for hasProperties without allowExtraProperties */
240
- (isValue) => hasProperties(isValue, { allowExtraProperties: false })
241
- );
242
-
243
- // ../anvl/src/refinement/index.ts
244
- var canExist = (_) => true;
245
- var cannotExist = (_) => false;
246
- var isLiteral = (value) => (input) => input === value;
247
- var couldBe = (isTypeA, logging = false, refinements = [isTypeA]) => {
248
- const name = `(${refinements.map((r) => r.name || `anon`).join(` | `)})`;
249
- const _ = {
250
- [name]: (input) => refinements.some(
251
- (refinement) => {
252
- var _a;
253
- return logging && console.log(
254
- refinements.map((r) => r.name || `anon`).join(` | `),
255
- `>`,
256
- (_a = refinement.name) != null ? _a : `anon`,
257
- `:`,
258
- refinement(input)
259
- ), refinement(input);
260
- }
261
- )
262
- };
263
- const checkTypes = Object.assign(_[name], {
264
- or: (isTypeB) => couldBe(isTypeB, logging, [...refinements, isTypeB])
265
- });
266
- return checkTypes;
267
- };
268
- var isUnion = couldBe(cannotExist);
269
- var mustBe = (isTypeA, logging = false, refinements = [isTypeA]) => {
270
- const name = `(${refinements.map((r) => r.name || `anon`).join(` & `)})`;
271
- const _ = {
272
- [name]: (input) => refinements.every(
273
- (refinement) => (logging && console.log(
274
- refinements.map((r) => r.name || `anon`).join(` & `),
275
- `>`,
276
- refinement.name || `anon`,
277
- `:`,
278
- refinement(input)
279
- ), refinement(input))
280
- )
281
- };
282
- const checkTypes = Object.assign(_[name], {
283
- and: (isTypeB) => mustBe(isTypeB, logging, [...refinements, isTypeB])
284
- });
285
- return checkTypes;
286
- };
287
- var isIntersection = mustBe(canExist);
288
-
289
- // ../anvl/src/join/core-relation-data.ts
290
- var RELATION_TYPES = [`1:1`, `1:n`, `n:n`];
291
- var isRelationType = (x) => RELATION_TYPES.includes(x);
292
- var EMPTY_RELATION_DATA = {
293
- contents: {},
294
- relations: {},
295
- relationType: `n:n`,
296
- a: `from`,
297
- b: `to`
298
- };
299
- var isRelationData = ({
300
- from: a = `from`,
301
- to: b = `to`,
302
- isContent
303
- } = {}) => (input) => {
304
- return hasExactProperties({
305
- contents: isContent ? isRecord(isString, isContent) : hasExactProperties({}),
306
- relations: isRecord(isString, isArray(isString)),
307
- relationType: isRelationType,
308
- a: isLiteral(a),
309
- b: isLiteral(b)
310
- })(input);
311
- };
312
-
313
- // ../anvl/src/join/get-related-ids.ts
314
- var getRelatedIds = (relationMap, id) => {
315
- var _a;
316
- return (_a = relationMap.relations[id]) != null ? _a : [];
317
- };
318
- var getRelatedId = (relationMap, id) => {
319
- const relations = getRelatedIds(relationMap, id);
320
- if (relations.length > 1) {
321
- console.warn(
322
- `entry with id ${id} was not expected to have multiple relations`
323
- );
324
- }
325
- return relations[0];
326
- };
327
-
328
- // ../anvl/src/join/make-json-interface.ts
329
- var makeJsonInterface = (join, ...params) => {
330
- const isContent = params[0];
331
- const { a, b } = join;
332
- const options = {
333
- from: a,
334
- to: b,
335
- isContent
336
- };
337
- return {
338
- toJson: (join2) => join2.toJSON(),
339
- fromJson: (json) => Join.fromJSON(json, options)
340
- };
341
- };
342
-
343
- // ../anvl/src/join/relation-contents.ts
344
- import { pipe as pipe5 } from "fp-ts/function";
345
-
346
- // ../anvl/src/join/relation-record.ts
347
- var getRelationEntries = (relationMap, idA) => getRelatedIds(relationMap, idA).map((idB) => [
348
- idB,
349
- getContent(relationMap, idA, idB)
350
- ]);
351
- var getRelationRecord = (relationMap, id) => Object.fromEntries(getRelationEntries(relationMap, id));
352
-
353
- // ../anvl/src/join/remove-relation.ts
354
- import { pipe as pipe4 } from "fp-ts/function";
355
- import { isString as isString2 } from "fp-ts/string";
356
-
357
- // ../anvl/src/object/index.ts
358
- import { pipe as pipe3 } from "fp-ts/function";
359
- var treeShake = (shouldDiscard = isUndefined) => (obj) => {
360
- const newObj = {};
361
- const entries = Object.entries(obj);
362
- entries.forEach(
363
- ([key, val]) => !shouldDiscard(val, key) ? newObj[key] = val : null
364
- );
365
- return newObj;
366
- };
367
-
368
- // ../anvl/src/string/split.ts
369
- var split = (separator) => (str) => str.split(separator);
370
-
371
- // ../anvl/src/join/remove-relation.ts
372
- var removeSpecific = (current, idA, idB) => {
373
- const isIdForRemoval = isOneOf(idA, idB);
374
- return __spreadProps(__spreadValues({}, current), {
375
- relations: pipe4(
376
- current.relations,
377
- recordToEntries,
378
- map(([id, relations]) => [
379
- id,
380
- isIdForRemoval(id) ? relations.filter((relation) => !isIdForRemoval(relation)) : relations
381
- ]),
382
- entriesToRecord,
383
- treeShake(isEmptyArray)
384
- ),
385
- contents: pipe4(
386
- current.contents,
387
- treeShake(
388
- (_, key) => isString2(key) && pipe4(key, split(`/`), comprises([idA, idB]))
389
- )
390
- )
391
- });
392
- };
393
- var removeAll = (current, idToRemove) => {
394
- const next = __spreadProps(__spreadValues({}, current), {
395
- relations: pipe4(
396
- current.relations,
397
- recordToEntries,
398
- map(([id, relations]) => [
399
- id,
400
- relations.filter((relation) => relation !== idToRemove)
401
- ]),
402
- entriesToRecord,
403
- treeShake((val, key) => key === idToRemove || isEmptyArray(val))
404
- ),
405
- contents: pipe4(
406
- current.contents,
407
- treeShake(
408
- (_, key) => isString2(key) && key.split(`/`).includes(idToRemove)
409
- )
410
- )
411
- });
412
- return next;
413
- };
414
- var removeRelation = (current, relation) => {
415
- const idA = relation[current.a];
416
- const idB = relation[current.b];
417
- return idB ? removeSpecific(current, idA, idB) : removeAll(current, idA);
418
- };
419
-
420
- // ../anvl/src/join/set-relation.ts
421
- var setManyToMany = (map2, idA, idB, ...rest) => {
422
- var _a, _b;
423
- const next = __spreadProps(__spreadValues({}, map2), {
424
- relations: __spreadProps(__spreadValues({}, map2.relations), {
425
- [idA]: addTo((_a = map2.relations[idA]) != null ? _a : [])(idB),
426
- [idB]: addTo((_b = map2.relations[idB]) != null ? _b : [])(idA)
427
- })
428
- });
429
- const content = rest[0];
430
- return content ? setContent(next, idA, idB, content) : next;
431
- };
432
- var removeEmpties = treeShake(isEmptyArray);
433
- var set1ToMany = (current, leaderId, followerId, ...rest) => {
434
- var _a;
435
- const relations = __spreadValues({}, current.relations);
436
- const prevLeaderId = getRelatedId(current, followerId);
437
- const next = __spreadProps(__spreadValues({}, current), {
438
- relations: removeEmpties(__spreadProps(__spreadValues(__spreadValues({}, relations), prevLeaderId && prevLeaderId !== leaderId && {
439
- [prevLeaderId]: relations[prevLeaderId].filter(
440
- (id) => id !== followerId
441
- )
442
- }), {
443
- [followerId]: [leaderId],
444
- [leaderId]: addTo((_a = relations[leaderId]) != null ? _a : [])(followerId)
445
- }))
446
- });
447
- const content = rest[0];
448
- return content ? setContent(next, leaderId, followerId, content) : next;
449
- };
450
- var set1To1 = (current, wifeId, husbandId, ...rest) => {
451
- const prevWifeId = getRelatedId(current, husbandId);
452
- const prevHusbandId = getRelatedId(current, wifeId);
453
- const next = __spreadProps(__spreadValues({}, current), {
454
- relations: removeEmpties(__spreadProps(__spreadValues(__spreadValues(__spreadValues({}, current.relations), prevWifeId && { [prevWifeId]: [] }), prevHusbandId && { [prevHusbandId]: [] }), {
455
- [wifeId]: [husbandId],
456
- [husbandId]: [wifeId]
457
- }))
458
- });
459
- const content = rest[0];
460
- return content ? setContent(next, wifeId, husbandId, content) : next;
461
- };
462
- var setRelationWithContent = (current, relation, ...rest) => {
463
- const { [current.a]: idA, [current.b]: idB } = relation;
464
- switch (current.relationType) {
465
- case `1:1`:
466
- return set1To1(current, idA, idB, ...rest);
467
- case `1:n`:
468
- return set1ToMany(current, idA, idB, ...rest);
469
- case `n:n`:
470
- return setManyToMany(current, idA, idB, ...rest);
471
- }
472
- };
473
-
474
- // ../anvl/src/join/relation-contents.ts
475
- var makeContentId = (idA, idB) => [idA, idB].sort().join(`/`);
476
- var getContent = (relationMap, idA, idB) => relationMap.contents[makeContentId(idA, idB)];
477
- var setContent = (map2, idA, idB, content) => __spreadProps(__spreadValues({}, map2), {
478
- contents: __spreadProps(__spreadValues({}, map2.contents), {
479
- [makeContentId(idA, idB)]: content
480
- })
481
- });
482
- var getRelations = (relationMap, id) => getRelationEntries(relationMap, id).map(
483
- ([id2, content]) => __spreadValues({
484
- id: id2
485
- }, content)
486
- );
487
- var setRelations = (current, subject, relations) => {
488
- const idA = subject[current.a];
489
- const idB = subject[current.b];
490
- return pipe5(
491
- current,
492
- (relationData) => {
493
- const relatedIds = getRelatedIds(current, idA);
494
- const removedIds = relatedIds.filter(
495
- (id) => !relations.some((r) => r.id === id)
496
- );
497
- let step = relationData;
498
- for (const id of removedIds) {
499
- const remove = {
500
- [current.a]: idA != null ? idA : id,
501
- [current.b]: idB != null ? idB : id
502
- };
503
- step = removeRelation(step, remove);
504
- }
505
- return step;
506
- },
507
- (relationData) => {
508
- let step = relationData;
509
- for (const _a of relations) {
510
- const _b = _a, { id } = _b, rest = __objRest(_b, ["id"]);
511
- const content = isEmptyObject(rest) ? void 0 : rest;
512
- step = setRelationWithContent(
513
- step,
514
- { [current.a]: idA != null ? idA : id, [current.b]: idB != null ? idB : id },
515
- // @ts-expect-error hacky
516
- content
517
- );
518
- }
519
- return step;
520
- },
521
- (relationData) => {
522
- const newlyOrderedIds = relations.map((r) => r.id);
523
- return __spreadProps(__spreadValues({}, relationData), {
524
- relations: __spreadProps(__spreadValues({}, relationData.relations), {
525
- [idA != null ? idA : idB]: newlyOrderedIds
526
- })
527
- });
528
- }
529
- );
530
- };
531
-
532
- // ../anvl/src/join/index.ts
533
- var Join = class _Join {
534
- constructor(json) {
535
- this.a = `from`;
536
- this.b = `to`;
537
- this.makeJsonInterface = (...params) => {
538
- return makeJsonInterface(this, ...params);
539
- };
540
- Object.assign(this, __spreadProps(__spreadValues(__spreadValues({}, EMPTY_RELATION_DATA), json), {
541
- makeJsonInterface: this.makeJsonInterface
542
- }));
543
- }
544
- toJSON() {
545
- return {
546
- relationType: this.relationType,
547
- relations: this.relations,
548
- contents: this.contents,
549
- a: this.a,
550
- b: this.b
551
- };
552
- }
553
- static fromJSON(json, options) {
554
- const isValid = isRelationData(options)(json);
555
- if (isValid) {
556
- return new _Join(json);
557
- }
558
- throw new Error(
559
- `Saved JSON for this Join is invalid: ${JSON.stringify(json)}`
560
- );
561
- }
562
- from(newA) {
563
- return new _Join(__spreadProps(__spreadValues({}, this), { a: newA }));
564
- }
565
- to(newB) {
566
- return new _Join(__spreadProps(__spreadValues({}, this), { b: newB }));
567
- }
568
- getRelatedId(id) {
569
- return getRelatedId(this, id);
570
- }
571
- getRelatedIds(id) {
572
- return getRelatedIds(this, id);
573
- }
574
- getContent(idA, idB) {
575
- return getContent(this, idA, idB);
576
- }
577
- getRelationEntries(id) {
578
- return getRelationEntries(this, id);
579
- }
580
- getRelationRecord(id) {
581
- return getRelationRecord(this, id);
582
- }
583
- getRelation(id) {
584
- return getRelations(this, id)[0];
585
- }
586
- getRelations(id) {
587
- return getRelations(this, id);
588
- }
589
- setRelations(subject, relations) {
590
- return new _Join(setRelations(this, subject, relations));
591
- }
592
- set(relation, ...rest) {
593
- return new _Join(setRelationWithContent(this, relation, ...rest));
594
- }
595
- remove(relation) {
596
- return new _Join(
597
- removeRelation(this, relation)
598
- );
599
- }
600
- };
601
-
602
- // src/internal/store.ts
603
- var createStore = (name, store = null) => {
604
- var _a;
605
- const created = __spreadProps(__spreadValues({}, store != null ? store : (() => ({
606
- atomsThatAreDefault: /* @__PURE__ */ new Set(),
607
- selectorAtoms: new Join({ relationType: `n:n` }).from(`selectorKey`).to(`atomKey`),
608
- selectorGraph: new Join({ relationType: `n:n` })
609
- }))()), {
610
- valueMap: new Map(store == null ? void 0 : store.valueMap),
611
- atoms: /* @__PURE__ */ new Map(),
612
- readonlySelectors: /* @__PURE__ */ new Map(),
613
- selectors: /* @__PURE__ */ new Map(),
614
- transactions: /* @__PURE__ */ new Map(),
615
- timelines: /* @__PURE__ */ new Map(),
616
- timelineAtoms: new Join({ relationType: `1:n` }).from(`timelineKey`).to(`atomKey`),
617
- subject: {
618
- atomCreation: new Subject(),
619
- selectorCreation: new Subject(),
620
- transactionCreation: new Subject(),
621
- timelineCreation: new Subject(),
622
- operationStatus: new Subject()
623
- },
624
- operation: __spreadValues({
625
- open: false
626
- }, store == null ? void 0 : store.operation),
627
- transactionStatus: __spreadValues({
628
- phase: `idle`
629
- }, store == null ? void 0 : store.transactionStatus),
630
- config: __spreadProps(__spreadValues({
631
- logger: __spreadValues(__spreadProps(__spreadValues({}, console), {
632
- info: doNothing
633
- }), (_a = store == null ? void 0 : store.config) == null ? void 0 : _a.logger),
634
- logger__INTERNAL: console
635
- }, store == null ? void 0 : store.config), {
636
- name
637
- })
638
- });
639
- store == null ? void 0 : store.atoms.forEach((atom2) => {
640
- const copiedAtom = __spreadProps(__spreadValues({}, atom2), { subject: new Subject() });
641
- created.atoms.set(atom2.key, copiedAtom);
642
- });
643
- store == null ? void 0 : store.readonlySelectors.forEach((selector2) => {
644
- selector2.install(created);
645
- });
646
- store == null ? void 0 : store.selectors.forEach((selector2) => {
647
- selector2.install(created);
648
- });
649
- store == null ? void 0 : store.transactions.forEach((tx) => {
650
- tx.install(created);
651
- });
652
- store == null ? void 0 : store.timelines.forEach((timeline2) => {
653
- timeline2.install(created);
654
- });
655
- return created;
656
- };
657
- var IMPLICIT = {
658
- STORE_INTERNAL: void 0,
659
- get STORE() {
660
- var _a;
661
- return (_a = this.STORE_INTERNAL) != null ? _a : this.STORE_INTERNAL = createStore(`DEFAULT`);
662
- }
663
- };
664
- var clearStore = (store = IMPLICIT.STORE) => {
665
- const { config } = store;
666
- Object.assign(store, createStore(config.name));
667
- store.config = config;
668
- };
669
-
670
- // src/internal/operation.ts
671
- var openOperation = (token, store) => {
672
- var _a, _b;
673
- const core = target(store);
674
- if (core.operation.open) {
675
- (_a = store.config.logger) == null ? void 0 : _a.error(
676
- `\u274C failed to setState to "${token.key}" during a setState for "${core.operation.token.key}"`
677
- );
678
- throw Symbol(`violation`);
679
- }
680
- core.operation = {
681
- open: true,
682
- done: /* @__PURE__ */ new Set(),
683
- prev: new Map(store.valueMap),
684
- time: Date.now(),
685
- token
686
- };
687
- (_b = store.config.logger) == null ? void 0 : _b.info(
688
- `\u2B55 operation start from "${token.key}" in store "${store.config.name}"`
689
- );
690
- };
691
- var closeOperation = (store) => {
692
- var _a;
693
- const core = target(store);
694
- core.operation = { open: false };
695
- (_a = store.config.logger) == null ? void 0 : _a.info(`\u{1F534} operation done`);
696
- store.subject.operationStatus.next(core.operation);
697
- };
698
- var isDone = (key, store = IMPLICIT.STORE) => {
699
- var _a;
700
- const core = target(store);
701
- if (!core.operation.open) {
702
- (_a = store.config.logger) == null ? void 0 : _a.warn(
703
- `isDone called outside of an operation. This is probably a bug.`
704
- );
705
- return true;
706
- }
707
- return core.operation.done.has(key);
708
- };
709
- var markDone = (key, store = IMPLICIT.STORE) => {
710
- var _a;
711
- const core = target(store);
712
- if (!core.operation.open) {
713
- (_a = store.config.logger) == null ? void 0 : _a.warn(
714
- `markDone called outside of an operation. This is probably a bug.`
715
- );
716
- return;
717
- }
718
- core.operation.done.add(key);
719
- };
720
- var recallState = (state, store = IMPLICIT.STORE) => {
721
- var _a;
722
- const core = target(store);
723
- if (!core.operation.open) {
724
- (_a = store.config.logger) == null ? void 0 : _a.warn(
725
- `recall called outside of an operation. This is probably a bug.`
726
- );
727
- return core.valueMap.get(state.key);
728
- }
729
- return core.operation.prev.get(state.key);
730
- };
731
- var cacheValue = (key, value, store = IMPLICIT.STORE) => {
732
- const core = target(store);
733
- core.valueMap.set(key, value);
734
- };
735
- var evictCachedValue = (key, store = IMPLICIT.STORE) => {
736
- const core = target(store);
737
- core.valueMap.delete(key);
738
- };
739
- var readCachedValue = (key, store = IMPLICIT.STORE) => target(store).valueMap.get(key);
740
- var isValueCached = (key, store = IMPLICIT.STORE) => target(store).valueMap.has(key);
741
- var storeAtom = (atom2, store = IMPLICIT.STORE) => {
742
- const core = target(store);
743
- core.atoms.set(atom2.key, atom2);
744
- };
745
- var storeSelector = (selector2, store = IMPLICIT.STORE) => {
746
- const core = target(store);
747
- core.selectors.set(selector2.key, selector2);
748
- };
749
- var storeReadonlySelector = (selector2, store = IMPLICIT.STORE) => {
750
- const core = target(store);
751
- core.readonlySelectors.set(selector2.key, selector2);
752
- };
753
- var hasKeyBeenUsed = (key, store = IMPLICIT.STORE) => {
754
- const core = target(store);
755
- return core.atoms.has(key) || core.selectors.has(key) || core.readonlySelectors.has(key);
756
- };
757
-
758
- // src/internal/transaction-internal.ts
759
- function transaction__INTERNAL(options, store = IMPLICIT.STORE) {
760
- const newTransaction = {
761
- key: options.key,
762
- type: `transaction`,
763
- run: (...params) => {
764
- var _a;
765
- buildTransaction(options.key, params, store);
766
- try {
767
- const output = options.do(
768
- {
769
- get: (token2) => getState(token2, store),
770
- set: (token2, value) => setState(token2, value, store)
771
- },
772
- ...params
773
- );
774
- applyTransaction(output, store);
775
- return output;
776
- } catch (thrown) {
777
- abortTransaction(store);
778
- (_a = store.config.logger) == null ? void 0 : _a.error(`Transaction ${options.key} failed`, thrown);
779
- throw thrown;
780
- }
781
- },
782
- install: (store2) => transaction__INTERNAL(options, store2),
783
- subject: new Subject()
784
- };
785
- const core = target(store);
786
- core.transactions.set(newTransaction.key, newTransaction);
787
- const token = deposit(newTransaction);
788
- store.subject.transactionCreation.next(token);
789
- return token;
790
- }
791
- var target = (store = IMPLICIT.STORE) => store.transactionStatus.phase === `building` ? store.transactionStatus.core : store;
792
-
793
- // src/internal/atom-internal.ts
794
- function atom__INTERNAL(options, family, store = IMPLICIT.STORE) {
795
- var _a, _b, _c;
796
- const core = target(store);
797
- const existing = core.atoms.get(options.key);
798
- if (existing) {
799
- (_b = (_a = store.config.logger) == null ? void 0 : _a.error) == null ? void 0 : _b.call(
800
- _a,
801
- `Key "${options.key}" already exists in the store.`
802
- );
803
- return deposit(existing);
804
- }
805
- const subject = new Subject();
806
- const newAtom = __spreadValues(__spreadProps(__spreadValues({}, options), {
807
- subject,
808
- type: `atom`
809
- }), family && { family });
810
- const initialValue = options.default instanceof Function ? options.default() : options.default;
811
- core.atoms.set(newAtom.key, newAtom);
812
- markAtomAsDefault(options.key, store);
813
- cacheValue(options.key, initialValue, store);
814
- const token = deposit(newAtom);
815
- (_c = options.effects) == null ? void 0 : _c.forEach(
816
- (effect) => effect({
817
- setSelf: (next) => setState(token, next, store),
818
- onSet: (handle) => subscribe(token, handle, store)
819
- })
820
- );
821
- store.subject.atomCreation.next(token);
822
- return token;
823
- }
824
-
825
- // ../anvl/src/json/index.ts
826
- var stringifyJson = (json) => JSON.stringify(json);
827
-
828
- // src/internal/families-internal.ts
829
- function atomFamily__INTERNAL(options, store = IMPLICIT.STORE) {
830
- const subject = new Subject();
831
- return Object.assign(
832
- (key) => {
833
- const subKey = stringifyJson(key);
834
- const family = { key: options.key, subKey };
835
- const fullKey = `${options.key}(${subKey})`;
836
- const existing = withdraw({ key: fullKey, type: `atom` }, store);
837
- let token;
838
- if (existing) {
839
- token = deposit(existing);
840
- } else {
841
- const individualOptions = {
842
- key: fullKey,
843
- default: options.default instanceof Function ? options.default(key) : options.default
844
- };
845
- if (options.effects) {
846
- individualOptions.effects = options.effects(key);
847
- }
848
- token = atom__INTERNAL(individualOptions, family, store);
849
- }
850
- subject.next(token);
851
- return token;
852
- },
853
- {
854
- key: options.key,
855
- type: `atom_family`,
856
- subject
857
- }
858
- );
859
- }
860
- function readonlySelectorFamily__INTERNAL(options, store) {
861
- const core = target(store);
862
- const subject = new Subject();
863
- return Object.assign(
864
- (key) => {
865
- const subKey = stringifyJson(key);
866
- const family = { key: options.key, subKey };
867
- const fullKey = `${options.key}(${subKey})`;
868
- const existing = core.readonlySelectors.get(fullKey);
869
- if (existing) {
870
- return deposit(existing);
871
- }
872
- return selector__INTERNAL(
873
- {
874
- key: fullKey,
875
- get: options.get(key)
876
- },
877
- family,
878
- store
879
- );
880
- },
881
- {
882
- key: options.key,
883
- type: `readonly_selector_family`,
884
- subject
885
- }
886
- );
887
- }
888
- function selectorFamily__INTERNAL(options, store = IMPLICIT.STORE) {
889
- const isReadonly = !(`set` in options);
890
- if (isReadonly) {
891
- return readonlySelectorFamily__INTERNAL(options, store);
892
- }
893
- const core = target(store);
894
- const subject = new Subject();
895
- return Object.assign(
896
- (key) => {
897
- const subKey = stringifyJson(key);
898
- const family = { key: options.key, subKey };
899
- const fullKey = `${options.key}(${subKey})`;
900
- const existing = core.selectors.get(fullKey);
901
- if (existing) {
902
- return deposit(existing);
903
- }
904
- const token = selector__INTERNAL(
905
- {
906
- key: fullKey,
907
- get: options.get(key),
908
- set: options.set(key)
909
- },
910
- family,
911
- store
912
- );
913
- subject.next(token);
914
- return token;
915
- },
916
- {
917
- key: options.key,
918
- type: `selector_family`
919
- }
920
- );
921
- }
922
-
923
- // src/internal/selector/create-read-write-selector.ts
924
- var createReadWriteSelector = (options, family, store, core) => {
925
- var _a;
926
- const subject = new Subject();
927
- const { get, set } = registerSelector(options.key, store);
928
- const getSelf = () => {
929
- const value = options.get({ get });
930
- cacheValue(options.key, value, store);
931
- return value;
932
- };
933
- const setSelf = (next) => {
934
- var _a2;
935
- const oldValue = getSelf();
936
- (_a2 = store.config.logger) == null ? void 0 : _a2.info(
937
- ` <- "${options.key}" went (`,
938
- oldValue,
939
- `->`,
940
- next,
941
- `)`
942
- );
943
- const newValue = become(next)(oldValue);
944
- cacheValue(options.key, newValue, store);
945
- markDone(options.key, store);
946
- if (store.transactionStatus.phase === `idle`) {
947
- subject.next({ newValue, oldValue });
948
- }
949
- options.set({ get, set }, newValue);
950
- };
951
- const mySelector = __spreadValues(__spreadProps(__spreadValues({}, options), {
952
- subject,
953
- install: (s) => selector__INTERNAL(options, family, s),
954
- get: getSelf,
955
- set: setSelf,
956
- type: `selector`
957
- }), family && { family });
958
- core.selectors.set(options.key, mySelector);
959
- const initialValue = getSelf();
960
- (_a = store.config.logger) == null ? void 0 : _a.info(` \u2728 "${options.key}" =`, initialValue);
961
- const token = {
962
- key: options.key,
963
- type: `selector`
964
- };
965
- if (family) {
966
- token.family = family;
967
- }
968
- store.subject.selectorCreation.next(token);
969
- return token;
970
- };
971
-
972
- // src/internal/selector/lookup-selector-sources.ts
973
- var lookupSelectorSources = (key, store) => target(store).selectorGraph.getRelations(key).filter(({ source }) => source !== key).map(({ source }) => lookup(source, store));
974
-
975
- // src/internal/selector/trace-selector-atoms.ts
976
- var traceSelectorAtoms = (selectorKey, dependency, store) => {
977
- const roots = [];
978
- const sources = lookupSelectorSources(dependency.key, store);
979
- let depth = 0;
980
- while (sources.length > 0) {
981
- const source = sources.shift();
982
- ++depth;
983
- if (depth > 999) {
984
- throw new Error(
985
- `Maximum selector dependency depth exceeded in selector "${selectorKey}".`
986
- );
987
- }
988
- if (source.type !== `atom`) {
989
- sources.push(...lookupSelectorSources(source.key, store));
990
- } else {
991
- roots.push(source);
992
- }
993
- }
994
- return roots;
995
- };
996
- var traceAllSelectorAtoms = (selectorKey, store) => {
997
- const sources = lookupSelectorSources(selectorKey, store);
998
- return sources.flatMap(
999
- (source) => source.type === `atom` ? source : traceSelectorAtoms(selectorKey, source, store)
1000
- );
1001
- };
1002
-
1003
- // src/internal/selector/update-selector-atoms.ts
1004
- var updateSelectorAtoms = (selectorKey, dependency, store) => {
1005
- var _a, _b;
1006
- const core = target(store);
1007
- if (dependency.type === `atom`) {
1008
- core.selectorAtoms = core.selectorAtoms.set({
1009
- selectorKey,
1010
- atomKey: dependency.key
1011
- });
1012
- (_a = store.config.logger) == null ? void 0 : _a.info(
1013
- ` || adding root for "${selectorKey}": ${dependency.key}`
1014
- );
1015
- return;
1016
- }
1017
- const roots = traceSelectorAtoms(selectorKey, dependency, store);
1018
- (_b = store.config.logger) == null ? void 0 : _b.info(
1019
- ` || adding roots for "${selectorKey}":`,
1020
- roots.map((r) => r.key)
1021
- );
1022
- for (const root of roots) {
1023
- core.selectorAtoms = core.selectorAtoms.set({
1024
- selectorKey,
1025
- atomKey: root.key
1026
- });
1027
- }
1028
- };
1029
-
1030
- // src/internal/set.ts
1031
- var evictDownStream = (state, store = IMPLICIT.STORE) => {
1032
- var _a, _b;
1033
- const core = target(store);
1034
- const downstream = core.selectorAtoms.getRelations(state.key);
1035
- const downstreamKeys = downstream.map(({ id }) => id);
1036
- (_a = store.config.logger) == null ? void 0 : _a.info(
1037
- ` || ${downstreamKeys.length} downstream:`,
1038
- downstreamKeys
1039
- );
1040
- if (core.operation.open) {
1041
- (_b = store.config.logger) == null ? void 0 : _b.info(` ||`, [...core.operation.done], `already done`);
1042
- }
1043
- downstream.forEach(({ id: stateKey }) => {
1044
- var _a2, _b2, _c, _d;
1045
- if (isDone(stateKey, store)) {
1046
- (_a2 = store.config.logger) == null ? void 0 : _a2.info(` || ${stateKey} already done`);
1047
- return;
1048
- }
1049
- const state2 = (_b2 = core.selectors.get(stateKey)) != null ? _b2 : core.readonlySelectors.get(stateKey);
1050
- if (!state2) {
1051
- (_c = store.config.logger) == null ? void 0 : _c.info(
1052
- ` || ${stateKey} is an atom, and can't be downstream`
1053
- );
1054
- return;
1055
- }
1056
- evictCachedValue(stateKey, store);
1057
- (_d = store.config.logger) == null ? void 0 : _d.info(` xx evicted "${stateKey}"`);
1058
- markDone(stateKey, store);
1059
- });
1060
- };
1061
- var setAtomState = (atom2, next, store = IMPLICIT.STORE) => {
1062
- var _a, _b;
1063
- const oldValue = getState__INTERNAL(atom2, store);
1064
- const newValue = become(next)(oldValue);
1065
- (_a = store.config.logger) == null ? void 0 : _a.info(`<< setting atom "${atom2.key}" to`, newValue);
1066
- cacheValue(atom2.key, newValue, store);
1067
- if (isAtomDefault(atom2.key, store)) {
1068
- markAtomAsNotDefault(atom2.key, store);
1069
- }
1070
- markDone(atom2.key, store);
1071
- (_b = store.config.logger) == null ? void 0 : _b.info(
1072
- ` || evicting caches downstream from "${atom2.key}"`
1073
- );
1074
- evictDownStream(atom2, store);
1075
- const update = { oldValue, newValue };
1076
- if (store.transactionStatus.phase !== `building`) {
1077
- emitUpdate(atom2, update, store);
1078
- } else {
1079
- stowUpdate(atom2, update, store);
1080
- }
1081
- };
1082
- var setSelectorState = (selector2, next, store = IMPLICIT.STORE) => {
1083
- var _a, _b;
1084
- const oldValue = getState__INTERNAL(selector2, store);
1085
- const newValue = become(next)(oldValue);
1086
- (_a = store.config.logger) == null ? void 0 : _a.info(`<< setting selector "${selector2.key}" to`, newValue);
1087
- (_b = store.config.logger) == null ? void 0 : _b.info(` || propagating change made to "${selector2.key}"`);
1088
- selector2.set(newValue);
1089
- };
1090
- var setState__INTERNAL = (state, value, store = IMPLICIT.STORE) => {
1091
- if (`set` in state) {
1092
- setSelectorState(state, value, store);
1093
- } else {
1094
- setAtomState(state, value, store);
1095
- }
1096
- };
1097
-
1098
- // src/internal/selector/register-selector.ts
1099
- var registerSelector = (selectorKey, store = IMPLICIT.STORE) => ({
1100
- get: (dependency) => {
1101
- var _a, _b;
1102
- const core = target(store);
1103
- const alreadyRegistered = core.selectorGraph.getRelations(selectorKey).some(({ source }) => source === dependency.key);
1104
- const dependencyState = withdraw(dependency, store);
1105
- if (dependencyState === null) {
1106
- throw new Error(
1107
- `State "${dependency.key}" not found in this store. Did you forget to initialize with the "atom" or "selector" function?`
1108
- );
1109
- }
1110
- const dependencyValue = getState__INTERNAL(dependencyState, store);
1111
- if (alreadyRegistered) {
1112
- (_a = store.config.logger) == null ? void 0 : _a.info(
1113
- ` || ${selectorKey} <- ${dependency.key} =`,
1114
- dependencyValue
1115
- );
1116
- } else {
1117
- (_b = store.config.logger) == null ? void 0 : _b.info(
1118
- `\u{1F50C} registerSelector "${selectorKey}" <- ( "${dependency.key}" =`,
1119
- dependencyValue,
1120
- `)`
1121
- );
1122
- core.selectorGraph = core.selectorGraph.set(
1123
- { from: dependency.key, to: selectorKey },
1124
- {
1125
- source: dependency.key
1126
- }
1127
- );
1128
- }
1129
- updateSelectorAtoms(selectorKey, dependency, store);
1130
- return dependencyValue;
1131
- },
1132
- set: (stateToken, newValue) => {
1133
- const state = withdraw(stateToken, store);
1134
- if (state === null) {
1135
- throw new Error(
1136
- `State "${stateToken.key}" not found in this store. Did you forget to initialize with the "atom" or "selector" function?`
1137
- );
1138
- }
1139
- setState__INTERNAL(state, newValue, store);
1140
- }
1141
- });
1142
-
1143
- // src/internal/selector/create-readonly-selector.ts
1144
- var createReadonlySelector = (options, family, store, core) => {
1145
- var _a;
1146
- const subject = new Subject();
1147
- const { get } = registerSelector(options.key, store);
1148
- const getSelf = () => {
1149
- const value = options.get({ get });
1150
- cacheValue(options.key, value, store);
1151
- return value;
1152
- };
1153
- const readonlySelector = __spreadValues(__spreadProps(__spreadValues({}, options), {
1154
- subject,
1155
- install: (s) => selector__INTERNAL(options, family, s),
1156
- get: getSelf,
1157
- type: `readonly_selector`
1158
- }), family && { family });
1159
- core.readonlySelectors.set(options.key, readonlySelector);
1160
- const initialValue = getSelf();
1161
- (_a = store.config.logger) == null ? void 0 : _a.info(` \u2728 "${options.key}" =`, initialValue);
1162
- const token = {
1163
- key: options.key,
1164
- type: `readonly_selector`
1165
- };
1166
- if (family) {
1167
- token.family = family;
1168
- }
1169
- store.subject.selectorCreation.next(token);
1170
- return token;
1171
- };
1172
-
1173
- // src/internal/selector-internal.ts
1174
- function selector__INTERNAL(options, family, store = IMPLICIT.STORE) {
1175
- var _a;
1176
- const core = target(store);
1177
- if (core.selectors.has(options.key)) {
1178
- (_a = store.config.logger) == null ? void 0 : _a.error(
1179
- `Key "${options.key}" already exists in the store.`
1180
- );
1181
- }
1182
- if (!(`set` in options)) {
1183
- return createReadonlySelector(options, family, store, core);
1184
- }
1185
- return createReadWriteSelector(options, family, store, core);
1186
- }
1187
-
1188
- // ../anvl/reactivity/subject.ts
1189
- var Subject = class {
1190
- constructor() {
1191
- this.subscribers = [];
1192
- }
1193
- subscribe(subscriber) {
1194
- this.subscribers.push(subscriber);
1195
- const unsubscribe = () => this.unsubscribe(subscriber);
1196
- return { unsubscribe };
1197
- }
1198
- unsubscribe(subscriber) {
1199
- const subscriberIndex = this.subscribers.indexOf(subscriber);
1200
- if (subscriberIndex !== -1) {
1201
- this.subscribers.splice(subscriberIndex, 1);
1202
- }
1203
- }
1204
- next(value) {
1205
- for (const subscriber of this.subscribers) {
1206
- subscriber(value);
1207
- }
1208
- }
1209
- };
1210
-
1211
- // src/internal/subscribe-internal.ts
1212
- var prepareUpdate = (state, store) => {
1213
- const oldValue = recallState(state, store);
1214
- const newValue = getState__INTERNAL(state, store);
1215
- return { newValue, oldValue };
1216
- };
1217
- var stowUpdate = (state, update, store) => {
1218
- var _a;
1219
- const { key } = state;
1220
- const { logger } = store.config;
1221
- if (store.transactionStatus.phase !== `building`) {
1222
- (_a = store.config.logger) == null ? void 0 : _a.warn(
1223
- `stowUpdate called outside of a transaction. This is probably a bug.`
1224
- );
1225
- return;
1226
- }
1227
- store.transactionStatus.atomUpdates.push(__spreadValues({ key }, update));
1228
- logger == null ? void 0 : logger.info(`\u{1F4DD} ${key} stowed (`, update.oldValue, `->`, update.newValue, `)`);
1229
- };
1230
- var emitUpdate = (state, update, store) => {
1231
- const { key } = state;
1232
- const { logger } = store.config;
1233
- logger == null ? void 0 : logger.info(
1234
- `\u{1F4E2} ${state.type} "${key}" went (`,
1235
- update.oldValue,
1236
- `->`,
1237
- update.newValue,
1238
- `)`
1239
- );
1240
- state.subject.next(update);
1241
- };
1242
- var subscribeToRootAtoms = (state, store) => {
1243
- const dependencySubscriptions = `default` in state ? null : traceAllSelectorAtoms(state.key, store).map((atomToken) => {
1244
- const atom2 = withdraw(atomToken, store);
1245
- if (atom2 === null) {
1246
- throw new Error(
1247
- `Atom "${atomToken.key}", a dependency of selector "${state.key}", not found in store "${store.config.name}".`
1248
- );
1249
- }
1250
- return atom2.subject.subscribe((atomChange) => {
1251
- var _a, _b;
1252
- (_a = store.config.logger) == null ? void 0 : _a.info(
1253
- `\u{1F4E2} selector "${state.key}" saw root "${atomToken.key}" go (`,
1254
- atomChange.oldValue,
1255
- `->`,
1256
- atomChange.newValue,
1257
- `)`
1258
- );
1259
- const oldValue = recallState(state, store);
1260
- const newValue = getState__INTERNAL(state, store);
1261
- (_b = store.config.logger) == null ? void 0 : _b.info(
1262
- ` <- "${state.key}" went (`,
1263
- oldValue,
1264
- `->`,
1265
- newValue,
1266
- `)`
1267
- );
1268
- state.subject.next({ newValue, oldValue });
1269
- });
1270
- });
1271
- return dependencySubscriptions;
1272
- };
1273
-
1274
- // src/internal/time-travel-internal.ts
1275
- var redo__INTERNAL = (token, store = IMPLICIT.STORE) => {
1276
- var _a, _b, _c, _d;
1277
- (_a = store.config.logger) == null ? void 0 : _a.info(`\u23E9 redo "${token.key}"`);
1278
- const timelineData = store.timelines.get(token.key);
1279
- if (!timelineData) {
1280
- (_b = store.config.logger) == null ? void 0 : _b.error(
1281
- `Failed to redo on timeline "${token.key}". This timeline has not been initialized.`
1282
- );
1283
- return;
1284
- }
1285
- if (timelineData.at === timelineData.history.length) {
1286
- (_c = store.config.logger) == null ? void 0 : _c.warn(
1287
- `Failed to redo at the end of timeline "${token.key}". There is nothing to redo.`
1288
- );
1289
- return;
1290
- }
1291
- timelineData.timeTraveling = `into_future`;
1292
- const update = timelineData.history[timelineData.at];
1293
- switch (update.type) {
1294
- case `atom_update`: {
1295
- const { key, newValue } = update;
1296
- setState({ key, type: `atom` }, newValue, store);
1297
- break;
1298
- }
1299
- case `selector_update`:
1300
- case `transaction_update`: {
1301
- for (const atomUpdate of update.atomUpdates) {
1302
- const { key, newValue } = atomUpdate;
1303
- setState({ key, type: `atom` }, newValue, store);
1304
- }
1305
- break;
1306
- }
1307
- }
1308
- ++timelineData.at;
1309
- timelineData.subject.next(`redo`);
1310
- timelineData.timeTraveling = null;
1311
- (_d = store.config.logger) == null ? void 0 : _d.info(
1312
- `\u23F9\uFE0F "${token.key}" is now at ${timelineData.at} / ${timelineData.history.length}`
1313
- );
1314
- };
1315
- var undo__INTERNAL = (token, store = IMPLICIT.STORE) => {
1316
- var _a, _b, _c, _d;
1317
- (_a = store.config.logger) == null ? void 0 : _a.info(`\u23EA undo "${token.key}"`);
1318
- const timelineData = store.timelines.get(token.key);
1319
- if (!timelineData) {
1320
- (_b = store.config.logger) == null ? void 0 : _b.error(
1321
- `Failed to undo on timeline "${token.key}". This timeline has not been initialized.`
1322
- );
1323
- return;
1324
- }
1325
- if (timelineData.at === 0) {
1326
- (_c = store.config.logger) == null ? void 0 : _c.warn(
1327
- `Failed to undo at the beginning of timeline "${token.key}". There is nothing to undo.`
1328
- );
1329
- return;
1330
- }
1331
- timelineData.timeTraveling = `into_past`;
1332
- --timelineData.at;
1333
- const update = timelineData.history[timelineData.at];
1334
- switch (update.type) {
1335
- case `atom_update`: {
1336
- const { key, oldValue } = update;
1337
- setState({ key, type: `atom` }, oldValue, store);
1338
- break;
1339
- }
1340
- case `selector_update`:
1341
- case `transaction_update`: {
1342
- for (const atomUpdate of update.atomUpdates) {
1343
- const { key, oldValue } = atomUpdate;
1344
- setState({ key, type: `atom` }, oldValue, store);
1345
- }
1346
- break;
1347
- }
1348
- }
1349
- timelineData.subject.next(`undo`);
1350
- timelineData.timeTraveling = null;
1351
- (_d = store.config.logger) == null ? void 0 : _d.info(
1352
- `\u23F9\uFE0F "${token.key}" is now at ${timelineData.at} / ${timelineData.history.length}`
1353
- );
1354
- };
1355
-
1356
- // src/internal/timeline/add-atom-to-timeline.ts
1357
- var addAtomToTimeline = (atomToken, atoms, tl, store = IMPLICIT.STORE) => {
1358
- const atom2 = withdraw(atomToken, store);
1359
- if (atom2 === null) {
1360
- throw new Error(
1361
- `Cannot subscribe to atom "${atomToken.key}" because it has not been initialized in store "${store.config.name}"`
1362
- );
1363
- }
1364
- atom2.subject.subscribe((update) => {
1365
- var _a, _b, _c, _d, _e;
1366
- const currentSelectorKey = store.operation.open && store.operation.token.type === `selector` ? store.operation.token.key : null;
1367
- const currentSelectorTime = store.operation.open && store.operation.token.type === `selector` ? store.operation.time : null;
1368
- const currentTransactionKey = store.transactionStatus.phase === `applying` ? store.transactionStatus.key : null;
1369
- const currentTransactionTime = store.transactionStatus.phase === `applying` ? store.transactionStatus.time : null;
1370
- (_a = store.config.logger) == null ? void 0 : _a.info(
1371
- `\u23F3 timeline "${tl.key}" saw atom "${atomToken.key}" go (`,
1372
- update.oldValue,
1373
- `->`,
1374
- update.newValue,
1375
- currentTransactionKey ? `) in transaction "${currentTransactionKey}"` : currentSelectorKey ? `) in selector "${currentSelectorKey}"` : `)`
1376
- );
1377
- if (tl.timeTraveling === null) {
1378
- if (tl.selectorTime && tl.selectorTime !== currentSelectorTime) {
1379
- const mostRecentUpdate = tl.history.at(-1);
1380
- if (mostRecentUpdate === void 0) {
1381
- throw new Error(
1382
- `Timeline "${tl.key}" has a selectorTime, but no history. This is most likely a bug in AtomIO.`
1383
- );
1384
- }
1385
- }
1386
- if (currentTransactionKey && store.transactionStatus.phase === `applying`) {
1387
- const currentTransaction = withdraw(
1388
- { key: currentTransactionKey, type: `transaction` },
1389
- store
1390
- );
1391
- if (currentTransaction === null) {
1392
- throw new Error(
1393
- `Transaction "${currentTransactionKey}" not found in store "${store.config.name}". This is surprising, because we are in the application phase of "${currentTransactionKey}".`
1394
- );
1395
- }
1396
- if (tl.transactionKey !== currentTransactionKey) {
1397
- if (tl.transactionKey) {
1398
- (_b = store.config.logger) == null ? void 0 : _b.error(
1399
- `Timeline "${tl.key}" was unable to resolve transaction "${tl.transactionKey}. This is probably a bug.`
1400
- );
1401
- }
1402
- tl.transactionKey = currentTransactionKey;
1403
- const subscription = currentTransaction.subject.subscribe((update2) => {
1404
- var _a2;
1405
- subscription.unsubscribe();
1406
- if (tl.timeTraveling === null && currentTransactionTime) {
1407
- if (tl.at !== tl.history.length) {
1408
- tl.history.splice(tl.at);
1409
- }
1410
- const timelineTransactionUpdate = __spreadProps(__spreadValues({
1411
- type: `transaction_update`,
1412
- timestamp: currentTransactionTime
1413
- }, update2), {
1414
- atomUpdates: update2.atomUpdates.filter(
1415
- (atomUpdate) => atoms.some((atom3) => atom3.key === atomUpdate.key)
1416
- )
1417
- });
1418
- tl.history.push(timelineTransactionUpdate);
1419
- tl.at = tl.history.length;
1420
- tl.subject.next(timelineTransactionUpdate);
1421
- }
1422
- tl.transactionKey = null;
1423
- (_a2 = store.config.logger) == null ? void 0 : _a2.info(
1424
- `\u231B timeline "${tl.key}" got a transaction_update "${update2.key}"`
1425
- );
1426
- });
1427
- }
1428
- } else if (currentSelectorKey && currentSelectorTime) {
1429
- let latestUpdate = tl.history.at(-1);
1430
- if (currentSelectorTime !== tl.selectorTime) {
1431
- latestUpdate = {
1432
- type: `selector_update`,
1433
- timestamp: currentSelectorTime,
1434
- key: currentSelectorKey,
1435
- atomUpdates: []
1436
- };
1437
- latestUpdate.atomUpdates.push(__spreadValues({
1438
- key: atom2.key,
1439
- type: `atom_update`
1440
- }, update));
1441
- if (tl.at !== tl.history.length) {
1442
- tl.history.splice(tl.at);
1443
- }
1444
- tl.history.push(latestUpdate);
1445
- (_c = store.config.logger) == null ? void 0 : _c.info(
1446
- `\u231B timeline "${tl.key}" got a selector_update "${currentSelectorKey}" with`,
1447
- latestUpdate.atomUpdates.map((atomUpdate) => atomUpdate.key)
1448
- );
1449
- tl.at = tl.history.length;
1450
- tl.selectorTime = currentSelectorTime;
1451
- } else {
1452
- if ((latestUpdate == null ? void 0 : latestUpdate.type) === `selector_update`) {
1453
- latestUpdate.atomUpdates.push(__spreadValues({
1454
- key: atom2.key,
1455
- type: `atom_update`
1456
- }, update));
1457
- (_d = store.config.logger) == null ? void 0 : _d.info(
1458
- ` \u231B timeline "${tl.key}" set selector_update "${currentSelectorKey}" to`,
1459
- latestUpdate == null ? void 0 : latestUpdate.atomUpdates.map((atomUpdate) => atomUpdate.key)
1460
- );
1461
- }
1462
- }
1463
- if (latestUpdate)
1464
- tl.subject.next(latestUpdate);
1465
- } else {
1466
- const timestamp = Date.now();
1467
- tl.selectorTime = null;
1468
- if (tl.at !== tl.history.length) {
1469
- tl.history.splice(tl.at);
1470
- }
1471
- const atomUpdate = {
1472
- type: `atom_update`,
1473
- timestamp,
1474
- key: atom2.key,
1475
- oldValue: update.oldValue,
1476
- newValue: update.newValue
1477
- };
1478
- tl.history.push(atomUpdate);
1479
- tl.subject.next(atomUpdate);
1480
- (_e = store.config.logger) == null ? void 0 : _e.info(
1481
- `\u231B timeline "${tl.key}" got an atom_update to "${atom2.key}"`
1482
- );
1483
- tl.at = tl.history.length;
1484
- }
1485
- }
1486
- });
1487
- };
1488
-
1489
- // src/internal/timeline-internal.ts
1490
- function timeline__INTERNAL(options, store = IMPLICIT.STORE, data = null) {
1491
- var _a, _b, _c;
1492
- const tl = __spreadProps(__spreadValues({
1493
- key: options.key,
1494
- at: 0,
1495
- timeTraveling: null,
1496
- selectorTime: null,
1497
- transactionKey: null
1498
- }, data), {
1499
- history: (_a = data == null ? void 0 : data.history.map((update) => __spreadValues({}, update))) != null ? _a : [],
1500
- install: (store2) => timeline__INTERNAL(options, store2, tl),
1501
- subject: new Subject()
1502
- });
1503
- const core = target(store);
1504
- for (const tokenOrFamily of options.atoms) {
1505
- const timelineKey = core.timelineAtoms.getRelatedId(tokenOrFamily.key);
1506
- if (timelineKey) {
1507
- (_b = store.config.logger) == null ? void 0 : _b.error(
1508
- `\u274C Failed to add atom "${tokenOrFamily.key}" to timeline "${options.key}" because it belongs to timeline "${timelineKey}"`
1509
- );
1510
- continue;
1511
- }
1512
- if (tokenOrFamily.type === `atom_family`) {
1513
- const family = tokenOrFamily;
1514
- family.subject.subscribe(
1515
- (token2) => addAtomToTimeline(token2, options.atoms, tl, store)
1516
- );
1517
- } else {
1518
- const token2 = tokenOrFamily;
1519
- if (`family` in token2 && token2.family) {
1520
- const familyTimelineKey = core.timelineAtoms.getRelatedId(
1521
- token2.family.key
1522
- );
1523
- if (familyTimelineKey) {
1524
- (_c = store.config.logger) == null ? void 0 : _c.error(
1525
- `\u274C Failed to add atom "${token2.key}" to timeline "${options.key}" because its family "${token2.family.key}" belongs to timeline "${familyTimelineKey}"`
1526
- );
1527
- continue;
1528
- }
1529
- }
1530
- addAtomToTimeline(token2, options.atoms, tl, store);
1531
- }
1532
- core.timelineAtoms = core.timelineAtoms.set({
1533
- atomKey: tokenOrFamily.key,
1534
- timelineKey: options.key
1535
- });
1536
- }
1537
- store.timelines.set(options.key, tl);
1538
- const token = {
1539
- key: options.key,
1540
- type: `timeline`
1541
- };
1542
- store.subject.timelineCreation.next(token);
1543
- return token;
1544
- }
1545
-
1546
- // src/internal/transaction/abort-transaction.ts
1547
- var abortTransaction = (store) => {
1548
- var _a, _b;
1549
- if (store.transactionStatus.phase === `idle`) {
1550
- (_a = store.config.logger) == null ? void 0 : _a.warn(
1551
- `abortTransaction called outside of a transaction. This is probably a bug.`
1552
- );
1553
- return;
1554
- }
1555
- store.transactionStatus = { phase: `idle` };
1556
- (_b = store.config.logger) == null ? void 0 : _b.info(`\u{1FA82}`, `transaction fail`);
1557
- };
1558
-
1559
- // src/internal/transaction/apply-transaction.ts
1560
- var applyTransaction = (output, store) => {
1561
- var _a, _b, _c, _d;
1562
- if (store.transactionStatus.phase !== `building`) {
1563
- (_a = store.config.logger) == null ? void 0 : _a.warn(
1564
- `abortTransaction called outside of a transaction. This is probably a bug.`
1565
- );
1566
- return;
1567
- }
1568
- (_b = store.config.logger) == null ? void 0 : _b.info(
1569
- `\u{1F6C3} apply transaction "${store.transactionStatus.key}"`
1570
- );
1571
- store.transactionStatus.phase = `applying`;
1572
- store.transactionStatus.output = output;
1573
- const { atomUpdates } = store.transactionStatus;
1574
- for (const { key, newValue } of atomUpdates) {
1575
- const token = { key, type: `atom` };
1576
- if (!store.valueMap.has(token.key)) {
1577
- const newAtom = store.transactionStatus.core.atoms.get(token.key);
1578
- if (!newAtom) {
1579
- throw new Error(
1580
- `Absurd Error: Atom "${token.key}" not found while copying updates from transaction "${store.transactionStatus.key}" to store "${store.config.name}"`
1581
- );
1582
- }
1583
- store.atoms.set(newAtom.key, newAtom);
1584
- store.valueMap.set(newAtom.key, newAtom.default);
1585
- (_c = store.config.logger) == null ? void 0 : _c.info(`\u{1F527}`, `add atom "${newAtom.key}"`);
1586
- }
1587
- setState(token, newValue, store);
1588
- }
1589
- const myTransaction = withdraw(
1590
- { key: store.transactionStatus.key, type: `transaction` },
1591
- store
1592
- );
1593
- if (myTransaction === null) {
1594
- throw new Error(
1595
- `Transaction "${store.transactionStatus.key}" not found. Absurd. How is this running?`
1596
- );
1597
- }
1598
- myTransaction.subject.next({
1599
- key: store.transactionStatus.key,
1600
- atomUpdates,
1601
- output,
1602
- params: store.transactionStatus.params
1603
- });
1604
- store.transactionStatus = { phase: `idle` };
1605
- (_d = store.config.logger) == null ? void 0 : _d.info(`\u{1F6EC}`, `transaction done`);
1606
- };
1607
-
1608
- // src/internal/transaction/build-transaction.ts
1609
- var buildTransaction = (key, params, store) => {
1610
- var _a;
1611
- store.transactionStatus = {
1612
- key,
1613
- phase: `building`,
1614
- time: Date.now(),
1615
- core: {
1616
- atoms: new Map(store.atoms),
1617
- atomsThatAreDefault: store.atomsThatAreDefault,
1618
- operation: { open: false },
1619
- readonlySelectors: new Map(store.readonlySelectors),
1620
- timelines: new Map(store.timelines),
1621
- timelineAtoms: store.timelineAtoms,
1622
- transactions: new Map(store.transactions),
1623
- selectorAtoms: store.selectorAtoms,
1624
- selectorGraph: store.selectorGraph,
1625
- selectors: new Map(store.selectors),
1626
- valueMap: new Map(store.valueMap)
1627
- },
1628
- atomUpdates: [],
1629
- params,
1630
- output: void 0
1631
- };
1632
- (_a = store.config.logger) == null ? void 0 : _a.info(
1633
- `\u{1F6EB}`,
1634
- `transaction "${key}" started in store "${store.config.name}"`
1635
- );
1636
- };
1637
-
1638
- // src/internal/transaction/redo-transaction.ts
1639
- var redoTransactionUpdate = (update, store) => {
1640
- var _a;
1641
- (_a = store.config.logger) == null ? void 0 : _a.info(` \u23ED redo transaction "${update.key}" (redo)`);
1642
- for (const { key, newValue } of update.atomUpdates) {
1643
- const token = { key, type: `atom` };
1644
- const state = withdraw(token, store);
1645
- if (state === null) {
1646
- throw new Error(
1647
- `State "${token.key}" not found in this store. This is surprising, because we are navigating the history of the store.`
1648
- );
1649
- }
1650
- setState(state, newValue, store);
1651
- }
1652
- };
1653
-
1654
- // src/internal/transaction/undo-transaction.ts
1655
- var undoTransactionUpdate = (update, store) => {
1656
- var _a;
1657
- (_a = store.config.logger) == null ? void 0 : _a.info(` \u23EE undo transaction "${update.key}" (undo)`);
1658
- for (const { key, oldValue } of update.atomUpdates) {
1659
- const token = { key, type: `atom` };
1660
- const state = withdraw(token, store);
1661
- if (state === null) {
1662
- throw new Error(
1663
- `State "${token.key}" not found in this store. This is surprising, because we are navigating the history of the store.`
1664
- );
1665
- }
1666
- setState(state, oldValue, store);
1667
- }
1668
- };
1669
-
1670
- // src/internal/transaction/index.ts
1671
- var TRANSACTION_PHASES = [`idle`, `building`, `applying`];
1672
-
1673
- // src/atom.ts
1674
20
  function atom(options) {
1675
- return atom__INTERNAL(options);
21
+ if (`mutable` in options) {
22
+ return createMutableAtom(options);
23
+ }
24
+ return createAtom(options);
1676
25
  }
1677
26
  function atomFamily(options) {
1678
- return atomFamily__INTERNAL(options);
27
+ if (`mutable` in options) {
28
+ return createMutableAtomFamily(options);
29
+ }
30
+ return createAtomFamily(options);
1679
31
  }
1680
-
1681
- // src/logger.ts
32
+ var NO_OP = () => void 0;
1682
33
  var LOG_LEVELS = [
1683
34
  `info`,
1684
35
  `warn`,
@@ -1692,7 +43,7 @@ var setLogLevel = (preferredLevel, store = IMPLICIT.STORE) => {
1692
43
  store.config.logger = __spreadValues({}, console);
1693
44
  LOG_LEVELS.forEach((logLevel) => {
1694
45
  if (LOG_LEVELS.indexOf(logLevel) < LOG_LEVELS.indexOf(preferredLevel)) {
1695
- store.config.logger[logLevel] = doNothing;
46
+ store.config.logger[logLevel] = NO_OP;
1696
47
  } else {
1697
48
  store.config.logger[logLevel] = logger__INTERNAL[logLevel];
1698
49
  }
@@ -1704,42 +55,46 @@ var useLogger = (logger, store = IMPLICIT.STORE) => {
1704
55
  const currentLogLevel = store.config.logger === null ? null : (_a = LOG_LEVELS.find(
1705
56
  (logLevel) => {
1706
57
  var _a2;
1707
- return ((_a2 = store.config.logger) == null ? void 0 : _a2[logLevel]) !== doNothing;
58
+ return ((_a2 = store.config.logger) == null ? void 0 : _a2[logLevel]) !== NO_OP;
1708
59
  }
1709
60
  )) != null ? _a : null;
1710
61
  store.config.logger__INTERNAL = __spreadValues({}, logger);
1711
62
  setLogLevel(currentLogLevel, store);
1712
63
  };
1713
-
1714
- // src/selector.ts
1715
64
  function selector(options) {
1716
- return selector__INTERNAL(options);
65
+ return createSelector(options);
1717
66
  }
1718
67
  function selectorFamily(options) {
1719
- return selectorFamily__INTERNAL(options);
68
+ return createSelectorFamily(options);
1720
69
  }
1721
-
1722
- // src/silo.ts
1723
- var silo = (name, fromStore = null) => {
1724
- const store = createStore(name, fromStore);
1725
- return {
1726
- store,
1727
- atom: (options) => atom__INTERNAL(options, void 0, store),
1728
- atomFamily: (options) => atomFamily__INTERNAL(options, store),
1729
- selector: (options) => selector__INTERNAL(options, void 0, store),
1730
- selectorFamily: (options) => selectorFamily__INTERNAL(options, store),
1731
- transaction: (options) => transaction__INTERNAL(options, store),
1732
- timeline: (options) => timeline__INTERNAL(options, store),
1733
- getState: (token) => getState(token, store),
1734
- setState: (token, newValue) => setState(token, newValue, store),
1735
- subscribe: (token, handler) => subscribe(token, handler, store),
1736
- undo: (token) => undo__INTERNAL(token, store),
1737
- redo: (token) => redo__INTERNAL(token, store)
1738
- };
70
+ var Silo = class {
71
+ constructor(name, fromStore = null) {
72
+ const s = new Store(name, fromStore);
73
+ this.store = s;
74
+ this.atom = (options) => {
75
+ if (`mutable` in options) {
76
+ return createMutableAtom(options, s);
77
+ }
78
+ return createAtom(options, void 0, s);
79
+ };
80
+ this.atomFamily = (options) => {
81
+ if (`mutable` in options) {
82
+ return createMutableAtomFamily(options, s);
83
+ }
84
+ return createAtomFamily(options, s);
85
+ };
86
+ this.selector = (options) => createSelector(options, void 0, s);
87
+ this.selectorFamily = (options) => createSelectorFamily(options, s);
88
+ this.transaction = (options) => transaction__INTERNAL(options, s);
89
+ this.timeline = (options) => timeline__INTERNAL(options, s);
90
+ this.getState = (token) => getState(token, s);
91
+ this.setState = (token, newValue) => setState(token, newValue, s);
92
+ this.subscribe = (token, handler, key) => subscribe(token, handler, key, s);
93
+ this.undo = (token) => undo__INTERNAL(token, s);
94
+ this.redo = (token) => redo__INTERNAL(token, s);
95
+ }
1739
96
  };
1740
-
1741
- // src/subscribe.ts
1742
- var subscribe = (token, handleUpdate, store = IMPLICIT.STORE) => {
97
+ function subscribe(token, handleUpdate, key = Math.random().toString(36).slice(2), store = IMPLICIT.STORE) {
1743
98
  var _a;
1744
99
  const state = withdraw(token, store);
1745
100
  if (state === null) {
@@ -1747,26 +102,26 @@ var subscribe = (token, handleUpdate, store = IMPLICIT.STORE) => {
1747
102
  `State "${token.key}" not found in this store. Did you forget to initialize with the "atom" or "selector" function?`
1748
103
  );
1749
104
  }
1750
- const subscription = state.subject.subscribe(handleUpdate);
1751
- (_a = store.config.logger) == null ? void 0 : _a.info(`\u{1F440} subscribe to "${state.key}"`);
1752
- const dependencySubscriptions = state.type !== `atom` ? subscribeToRootAtoms(state, store) : null;
1753
- const unsubscribe = dependencySubscriptions === null ? () => {
105
+ const unsubFunction = state.subject.subscribe(key, handleUpdate);
106
+ (_a = store.config.logger) == null ? void 0 : _a.info(`\u{1F440} adding subscription "${key}" to "${state.key}"`);
107
+ const dependencyUnsubFunctions = state.type !== `atom` ? subscribeToRootAtoms(state, store) : null;
108
+ const unsubscribe = dependencyUnsubFunctions === null ? () => {
1754
109
  var _a2;
1755
110
  (_a2 = store.config.logger) == null ? void 0 : _a2.info(`\u{1F648} unsubscribe from "${state.key}"`);
1756
- subscription.unsubscribe();
111
+ unsubFunction();
1757
112
  } : () => {
1758
113
  var _a2;
1759
114
  (_a2 = store.config.logger) == null ? void 0 : _a2.info(
1760
115
  `\u{1F648} unsubscribe from "${state.key}" and its dependencies`
1761
116
  );
1762
- subscription.unsubscribe();
1763
- for (const dependencySubscription of dependencySubscriptions) {
1764
- dependencySubscription.unsubscribe();
117
+ unsubFunction();
118
+ for (const unsubFromDependency of dependencyUnsubFunctions) {
119
+ unsubFromDependency();
1765
120
  }
1766
121
  };
1767
122
  return unsubscribe;
1768
- };
1769
- var subscribeToTransaction = (token, handleUpdate, store = IMPLICIT.STORE) => {
123
+ }
124
+ var subscribeToTransaction = (token, handleUpdate, key = Math.random().toString(36).slice(2), store = IMPLICIT.STORE) => {
1770
125
  var _a;
1771
126
  const tx = withdraw(token, store);
1772
127
  if (tx === null) {
@@ -1775,15 +130,14 @@ var subscribeToTransaction = (token, handleUpdate, store = IMPLICIT.STORE) => {
1775
130
  );
1776
131
  }
1777
132
  (_a = store.config.logger) == null ? void 0 : _a.info(`\u{1F440} subscribe to transaction "${token.key}"`);
1778
- const subscription = tx.subject.subscribe(handleUpdate);
1779
- const unsubscribe = () => {
133
+ const unsubscribe = tx.subject.subscribe(key, handleUpdate);
134
+ return () => {
1780
135
  var _a2;
1781
136
  (_a2 = store.config.logger) == null ? void 0 : _a2.info(`\u{1F648} unsubscribe from transaction "${token.key}"`);
1782
- subscription.unsubscribe();
137
+ unsubscribe();
1783
138
  };
1784
- return unsubscribe;
1785
139
  };
1786
- var subscribeToTimeline = (token, handleUpdate, store = IMPLICIT.STORE) => {
140
+ var subscribeToTimeline = (token, handleUpdate, key = Math.random().toString(36).slice(2), store = IMPLICIT.STORE) => {
1787
141
  var _a;
1788
142
  const tl = withdraw(token, store);
1789
143
  if (tl === null) {
@@ -1792,16 +146,13 @@ var subscribeToTimeline = (token, handleUpdate, store = IMPLICIT.STORE) => {
1792
146
  );
1793
147
  }
1794
148
  (_a = store.config.logger) == null ? void 0 : _a.info(`\u{1F440} subscribe to timeline "${token.key}"`);
1795
- const subscription = tl.subject.subscribe(handleUpdate);
1796
- const unsubscribe = () => {
149
+ const unsubscribe = tl.subject.subscribe(key, handleUpdate);
150
+ return () => {
1797
151
  var _a2;
1798
152
  (_a2 = store.config.logger) == null ? void 0 : _a2.info(`\u{1F648} unsubscribe from timeline "${token.key}"`);
1799
- subscription.unsubscribe();
153
+ unsubscribe();
1800
154
  };
1801
- return unsubscribe;
1802
155
  };
1803
-
1804
- // src/timeline.ts
1805
156
  var timeline = (options) => {
1806
157
  return timeline__INTERNAL(options);
1807
158
  };
@@ -1811,8 +162,6 @@ var redo = (token) => {
1811
162
  var undo = (token) => {
1812
163
  undo__INTERNAL(token, IMPLICIT.STORE);
1813
164
  };
1814
-
1815
- // src/transaction.ts
1816
165
  function transaction(options) {
1817
166
  return transaction__INTERNAL(options);
1818
167
  }
@@ -1827,54 +176,38 @@ var runTransaction = (token, store = IMPLICIT.STORE) => (...parameters) => {
1827
176
  };
1828
177
 
1829
178
  // src/index.ts
1830
- var getState = (token, store = IMPLICIT.STORE) => {
1831
- const state = withdraw(token, store);
179
+ var capitalize = (str) => str[0].toUpperCase() + str.slice(1);
180
+ var getState = (token, store = IO.IMPLICIT.STORE) => {
181
+ var _a;
182
+ const state = (_a = IO.withdraw(token, store)) != null ? _a : IO.withdrawNewFamilyMember(token, store);
1832
183
  if (state === null) {
1833
184
  throw new Error(
1834
185
  `${capitalize(token.type)} "${token.key}" not found in store "${store.config.name}".`
1835
186
  );
1836
187
  }
1837
- return getState__INTERNAL(state, store);
188
+ return IO.getState__INTERNAL(state, store);
1838
189
  };
1839
- var setState = (token, value, store = IMPLICIT.STORE) => {
190
+ var setState = (token, value, store = IO.IMPLICIT.STORE) => {
191
+ var _a;
1840
192
  try {
1841
- openOperation(token, store);
193
+ IO.openOperation(token, store);
1842
194
  } catch (thrown) {
1843
195
  if (!(typeof thrown === `symbol`)) {
1844
196
  throw thrown;
1845
197
  }
1846
198
  return;
1847
199
  }
1848
- const state = withdraw(token, store);
200
+ const state = (_a = IO.withdraw(token, store)) != null ? _a : IO.withdrawNewFamilyMember(token, store);
1849
201
  if (state === null) {
1850
202
  throw new Error(
1851
203
  `${capitalize(token.type)} "${token.key}" not found in store "${store.config.name}".`
1852
204
  );
1853
205
  }
1854
- setState__INTERNAL(state, value, store);
1855
- closeOperation(store);
1856
- };
1857
- var isDefault = (token, store = IMPLICIT.STORE) => token.type === `atom` ? isAtomDefault(token.key, store) : isSelectorDefault(token.key, store);
1858
- export {
1859
- LOG_LEVELS,
1860
- internal_exports as __INTERNAL__,
1861
- atom,
1862
- atomFamily,
1863
- getState,
1864
- isDefault,
1865
- redo,
1866
- runTransaction,
1867
- selector,
1868
- selectorFamily,
1869
- setLogLevel,
1870
- setState,
1871
- silo,
1872
- subscribe,
1873
- subscribeToTimeline,
1874
- subscribeToTransaction,
1875
- timeline,
1876
- transaction,
1877
- undo,
1878
- useLogger
206
+ IO.setState__INTERNAL(state, value, store);
207
+ IO.closeOperation(store);
1879
208
  };
209
+ var isDefault = (token, store = IO.IMPLICIT.STORE) => token.type === `atom` ? IO.isAtomDefault(token.key, store) : IO.isSelectorDefault(token.key, store);
210
+
211
+ export { LOG_LEVELS, NO_OP, Silo, atom, atomFamily, capitalize, getState, isDefault, redo, runTransaction, selector, selectorFamily, setLogLevel, setState, subscribe, subscribeToTimeline, subscribeToTransaction, timeline, transaction, undo, useLogger };
212
+ //# sourceMappingURL=out.js.map
1880
213
  //# sourceMappingURL=index.mjs.map