@legendapp/state 2.2.0-next.7 → 2.2.0-next.71

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 (298) hide show
  1. package/README.md +4 -2
  2. package/babel.js.map +1 -1
  3. package/config/enable$get.d.ts +8 -0
  4. package/config/enable$get.js +24 -0
  5. package/config/enable$get.js.map +1 -0
  6. package/config/enable$get.mjs +21 -0
  7. package/config/enable$get.mjs.map +1 -0
  8. package/config/enableReactComponents.js.map +1 -1
  9. package/config/enableReactComponents.mjs.map +1 -1
  10. package/config/enableReactNativeComponents.js.map +1 -1
  11. package/config/enableReactNativeComponents.mjs.map +1 -1
  12. package/config/enableReactTracking.d.ts +0 -9
  13. package/config/enableReactTracking.js.map +1 -1
  14. package/config/enableReactTracking.mjs.map +1 -1
  15. package/config/enableReactUse.d.ts +1 -1
  16. package/config/enableReactUse.js +1 -0
  17. package/config/enableReactUse.js.map +1 -1
  18. package/config/enableReactUse.mjs +1 -0
  19. package/config/enableReactUse.mjs.map +1 -1
  20. package/config/enable_peek.d.ts +8 -0
  21. package/config/{enableDirectPeek.js → enable_peek.js} +6 -3
  22. package/config/enable_peek.js.map +1 -0
  23. package/config/{enableDirectPeek.mjs → enable_peek.mjs} +5 -3
  24. package/config/enable_peek.mjs.map +1 -0
  25. package/helpers/fetch.d.ts +4 -3
  26. package/helpers/fetch.js.map +1 -1
  27. package/helpers/fetch.mjs.map +1 -1
  28. package/helpers/pageHash.js.map +1 -1
  29. package/helpers/pageHash.mjs.map +1 -1
  30. package/helpers/pageHashParams.js.map +1 -1
  31. package/helpers/pageHashParams.mjs.map +1 -1
  32. package/helpers/time.d.ts +2 -2
  33. package/helpers/time.js.map +1 -1
  34. package/helpers/time.mjs.map +1 -1
  35. package/history.js +2 -2
  36. package/history.js.map +1 -1
  37. package/history.mjs +3 -3
  38. package/history.mjs.map +1 -1
  39. package/index.d.ts +30 -9
  40. package/index.js +877 -661
  41. package/index.js.map +1 -1
  42. package/index.mjs +874 -658
  43. package/index.mjs.map +1 -1
  44. package/package.json +22 -25
  45. package/persist-plugins/async-storage.d.ts +3 -3
  46. package/persist-plugins/async-storage.js +8 -7
  47. package/persist-plugins/async-storage.js.map +1 -1
  48. package/persist-plugins/async-storage.mjs +9 -8
  49. package/persist-plugins/async-storage.mjs.map +1 -1
  50. package/persist-plugins/fetch.js.map +1 -1
  51. package/persist-plugins/fetch.mjs.map +1 -1
  52. package/persist-plugins/firebase.d.ts +1 -1
  53. package/persist-plugins/firebase.js +12 -11
  54. package/persist-plugins/firebase.js.map +1 -1
  55. package/persist-plugins/firebase.mjs +13 -12
  56. package/persist-plugins/firebase.mjs.map +1 -1
  57. package/persist-plugins/indexeddb.d.ts +10 -10
  58. package/persist-plugins/indexeddb.js +2 -2
  59. package/persist-plugins/indexeddb.js.map +1 -1
  60. package/persist-plugins/indexeddb.mjs +2 -2
  61. package/persist-plugins/indexeddb.mjs.map +1 -1
  62. package/persist-plugins/local-storage.d.ts +3 -4
  63. package/persist-plugins/local-storage.js +19 -7
  64. package/persist-plugins/local-storage.js.map +1 -1
  65. package/persist-plugins/local-storage.mjs +20 -9
  66. package/persist-plugins/local-storage.mjs.map +1 -1
  67. package/persist-plugins/mmkv.d.ts +8 -8
  68. package/persist-plugins/mmkv.js +5 -4
  69. package/persist-plugins/mmkv.js.map +1 -1
  70. package/persist-plugins/mmkv.mjs +6 -5
  71. package/persist-plugins/mmkv.mjs.map +1 -1
  72. package/persist-plugins/query.js.map +1 -1
  73. package/persist-plugins/query.mjs.map +1 -1
  74. package/persist.d.ts +2 -14
  75. package/persist.js +1250 -268
  76. package/persist.js.map +1 -1
  77. package/persist.mjs +1250 -269
  78. package/persist.mjs.map +1 -1
  79. package/react-hooks/createObservableHook.js +1 -1
  80. package/react-hooks/createObservableHook.js.map +1 -1
  81. package/react-hooks/createObservableHook.mjs +1 -1
  82. package/react-hooks/createObservableHook.mjs.map +1 -1
  83. package/react-hooks/useFetch.d.ts +4 -3
  84. package/react-hooks/useFetch.js.map +1 -1
  85. package/react-hooks/useFetch.mjs.map +1 -1
  86. package/react-hooks/useHover.js.map +1 -1
  87. package/react-hooks/useHover.mjs.map +1 -1
  88. package/react-hooks/useMeasure.js.map +1 -1
  89. package/react-hooks/useMeasure.mjs.map +1 -1
  90. package/react-hooks/useObservableNextRouter.js.map +1 -1
  91. package/react-hooks/useObservableNextRouter.mjs.map +1 -1
  92. package/react-hooks/useObservableQuery.js.map +1 -1
  93. package/react-hooks/useObservableQuery.mjs.map +1 -1
  94. package/react-hooks/usePersistedObservable.d.ts +5 -3
  95. package/react-hooks/usePersistedObservable.js +5 -2
  96. package/react-hooks/usePersistedObservable.js.map +1 -1
  97. package/react-hooks/usePersistedObservable.mjs +5 -2
  98. package/react-hooks/usePersistedObservable.mjs.map +1 -1
  99. package/react.js +61 -75
  100. package/react.js.map +1 -1
  101. package/react.mjs +61 -75
  102. package/react.mjs.map +1 -1
  103. package/src/ObservableObject.ts +1184 -0
  104. package/src/ObservablePrimitive.ts +62 -0
  105. package/src/babel/index.ts +70 -0
  106. package/src/batching.ts +372 -0
  107. package/src/computed.ts +16 -0
  108. package/src/config/enable$get.ts +30 -0
  109. package/src/config/enableReactComponents.ts +26 -0
  110. package/src/config/enableReactNativeComponents.ts +102 -0
  111. package/src/config/enableReactTracking.ts +60 -0
  112. package/src/config/enableReactUse.ts +23 -0
  113. package/src/config/enable_peek.ts +31 -0
  114. package/src/config.ts +47 -0
  115. package/src/createObservable.ts +46 -0
  116. package/src/event.ts +26 -0
  117. package/src/globals.ts +224 -0
  118. package/src/helpers/fetch.ts +26 -0
  119. package/src/helpers/pageHash.ts +41 -0
  120. package/src/helpers/pageHashParams.ts +55 -0
  121. package/src/helpers/time.ts +30 -0
  122. package/src/helpers.ts +221 -0
  123. package/src/history/trackHistory.ts +29 -0
  124. package/src/is.ts +56 -0
  125. package/src/linked.ts +6 -0
  126. package/src/observable.ts +32 -0
  127. package/src/observableInterfaces.ts +165 -0
  128. package/src/observableTypes.ts +221 -0
  129. package/src/observe.ts +89 -0
  130. package/src/onChange.ts +136 -0
  131. package/src/persist/configureObservablePersistence.ts +7 -0
  132. package/src/persist/fieldTransformer.ts +149 -0
  133. package/src/persist/observablePersistRemoteFunctionsAdapter.ts +39 -0
  134. package/src/persist/persistObservable.ts +1029 -0
  135. package/src/persist-plugins/async-storage.ts +102 -0
  136. package/src/persist-plugins/fetch.ts +33 -0
  137. package/src/persist-plugins/firebase.ts +1050 -0
  138. package/src/persist-plugins/indexeddb.ts +433 -0
  139. package/src/persist-plugins/local-storage.ts +90 -0
  140. package/src/persist-plugins/mmkv.ts +90 -0
  141. package/src/persist-plugins/query.ts +133 -0
  142. package/src/persistTypes.ts +226 -0
  143. package/src/proxy.ts +28 -0
  144. package/src/react/Computed.tsx +7 -0
  145. package/src/react/For.tsx +116 -0
  146. package/src/react/Memo.tsx +4 -0
  147. package/src/react/Reactive.tsx +53 -0
  148. package/src/react/Show.tsx +33 -0
  149. package/src/react/Switch.tsx +43 -0
  150. package/src/react/react-globals.ts +3 -0
  151. package/src/react/{reactInterfaces.d.ts → reactInterfaces.ts} +15 -7
  152. package/src/react/reactive-observer.tsx +210 -0
  153. package/src/react/useComputed.ts +36 -0
  154. package/src/react/useEffectOnce.ts +41 -0
  155. package/src/react/useIsMounted.ts +16 -0
  156. package/src/react/useMount.ts +15 -0
  157. package/src/react/useObservable.ts +24 -0
  158. package/src/react/useObservableReducer.ts +52 -0
  159. package/src/react/useObservableState.ts +30 -0
  160. package/src/react/useObserve.ts +54 -0
  161. package/src/react/useObserveEffect.ts +40 -0
  162. package/src/react/usePauseProvider.tsx +13 -0
  163. package/src/react/useSelector.ts +167 -0
  164. package/src/react/useUnmount.ts +8 -0
  165. package/src/react/useWhen.ts +9 -0
  166. package/src/react-hooks/createObservableHook.ts +53 -0
  167. package/src/react-hooks/useFetch.ts +16 -0
  168. package/src/react-hooks/useHover.ts +40 -0
  169. package/src/react-hooks/useMeasure.ts +48 -0
  170. package/src/react-hooks/useObservableNextRouter.ts +137 -0
  171. package/src/react-hooks/useObservableQuery.ts +205 -0
  172. package/src/react-hooks/usePersistedObservable.ts +24 -0
  173. package/src/retry.ts +69 -0
  174. package/src/setupTracking.ts +26 -0
  175. package/src/sync/activateSyncedNode.ts +146 -0
  176. package/src/sync/configureObservableSync.ts +7 -0
  177. package/src/sync/syncHelpers.ts +15 -0
  178. package/src/sync/syncObservable.ts +989 -0
  179. package/src/sync/syncObservableAdapter.ts +30 -0
  180. package/src/sync/synced.ts +20 -0
  181. package/src/sync-plugins/fetch.ts +42 -0
  182. package/src/syncTypes.ts +163 -0
  183. package/src/trace/traceHelpers.ts +11 -0
  184. package/src/trace/useTraceListeners.ts +34 -0
  185. package/src/trace/useTraceUpdates.ts +24 -0
  186. package/src/trace/useVerifyNotTracking.ts +33 -0
  187. package/src/trace/useVerifyOneRender.ts +10 -0
  188. package/src/trackSelector.ts +52 -0
  189. package/src/tracking.ts +43 -0
  190. package/src/types/babel.d.ts +12 -0
  191. package/src/when.ts +70 -0
  192. package/sync-plugins/fetch.d.ts +11 -0
  193. package/sync-plugins/fetch.js +24 -0
  194. package/sync-plugins/fetch.js.map +1 -0
  195. package/sync-plugins/fetch.mjs +22 -0
  196. package/sync-plugins/fetch.mjs.map +1 -0
  197. package/sync.d.ts +8 -0
  198. package/sync.js +919 -0
  199. package/sync.js.map +1 -0
  200. package/sync.mjs +912 -0
  201. package/sync.mjs.map +1 -0
  202. package/trace.js +13 -10
  203. package/trace.js.map +1 -1
  204. package/trace.mjs +11 -8
  205. package/trace.mjs.map +1 -1
  206. package/types/babel.d.ts +3 -3
  207. package/config/enableDirectAccess.d.ts +0 -7
  208. package/config/enableDirectAccess.js +0 -25
  209. package/config/enableDirectAccess.js.map +0 -1
  210. package/config/enableDirectAccess.mjs +0 -23
  211. package/config/enableDirectAccess.mjs.map +0 -1
  212. package/config/enableDirectPeek.d.ts +0 -7
  213. package/config/enableDirectPeek.js.map +0 -1
  214. package/config/enableDirectPeek.mjs.map +0 -1
  215. package/config/enableReactDirectRender.d.ts +0 -2
  216. package/config/enableReactDirectRender.js +0 -78
  217. package/config/enableReactDirectRender.js.map +0 -1
  218. package/config/enableReactDirectRender.mjs +0 -75
  219. package/config/enableReactDirectRender.mjs.map +0 -1
  220. package/src/ObservableObject.d.ts +0 -14
  221. package/src/ObservablePrimitive.d.ts +0 -7
  222. package/src/babel/index.d.ts +0 -17
  223. package/src/batching.d.ts +0 -6
  224. package/src/computed.d.ts +0 -4
  225. package/src/config/enableDirectAccess.d.ts +0 -7
  226. package/src/config/enableDirectPeek.d.ts +0 -7
  227. package/src/config/enableReactComponents.d.ts +0 -7
  228. package/src/config/enableReactDirectRender.d.ts +0 -2
  229. package/src/config/enableReactNativeComponents.d.ts +0 -20
  230. package/src/config/enableReactTracking.d.ts +0 -15
  231. package/src/config/enableReactUse.d.ts +0 -7
  232. package/src/config.d.ts +0 -8
  233. package/src/createObservable.d.ts +0 -2
  234. package/src/event.d.ts +0 -2
  235. package/src/globals.d.ts +0 -32
  236. package/src/helpers/fetch.d.ts +0 -6
  237. package/src/helpers/pageHash.d.ts +0 -7
  238. package/src/helpers/pageHashParams.d.ts +0 -7
  239. package/src/helpers/time.d.ts +0 -3
  240. package/src/helpers.d.ts +0 -13
  241. package/src/history/trackHistory.d.ts +0 -4
  242. package/src/is.d.ts +0 -10
  243. package/src/observable.d.ts +0 -16
  244. package/src/observableInterfaces.d.ts +0 -456
  245. package/src/observe.d.ts +0 -6
  246. package/src/onChange.d.ts +0 -7
  247. package/src/persist/configureObservablePersistence.d.ts +0 -3
  248. package/src/persist/fieldTransformer.d.ts +0 -8
  249. package/src/persist/observablePersistRemoteFunctionsAdapter.d.ts +0 -2
  250. package/src/persist/persistActivateNode.d.ts +0 -1
  251. package/src/persist/persistHelpers.d.ts +0 -1
  252. package/src/persist/persistObservable.d.ts +0 -25
  253. package/src/persist-plugins/async-storage.d.ts +0 -14
  254. package/src/persist-plugins/fetch.d.ts +0 -10
  255. package/src/persist-plugins/firebase.d.ts +0 -51
  256. package/src/persist-plugins/indexeddb.d.ts +0 -25
  257. package/src/persist-plugins/local-storage.d.ts +0 -21
  258. package/src/persist-plugins/mmkv.d.ts +0 -14
  259. package/src/persist-plugins/query.d.ts +0 -18
  260. package/src/proxy.d.ts +0 -5
  261. package/src/react/Computed.d.ts +0 -5
  262. package/src/react/For.d.ts +0 -15
  263. package/src/react/Memo.d.ts +0 -3
  264. package/src/react/Reactive.d.ts +0 -9
  265. package/src/react/Show.d.ts +0 -18
  266. package/src/react/Switch.d.ts +0 -14
  267. package/src/react/react-globals.d.ts +0 -3
  268. package/src/react/reactive-observer.d.ts +0 -14
  269. package/src/react/useComputed.d.ts +0 -5
  270. package/src/react/useEffectOnce.d.ts +0 -1
  271. package/src/react/useIsMounted.d.ts +0 -2
  272. package/src/react/useMount.d.ts +0 -2
  273. package/src/react/useObservable.d.ts +0 -9
  274. package/src/react/useObservableReducer.d.ts +0 -7
  275. package/src/react/useObservableState.d.ts +0 -2
  276. package/src/react/useObserve.d.ts +0 -4
  277. package/src/react/useObserveEffect.d.ts +0 -4
  278. package/src/react/usePauseProvider.d.ts +0 -8
  279. package/src/react/useSelector.d.ts +0 -3
  280. package/src/react/useUnmount.d.ts +0 -2
  281. package/src/react/useWhen.d.ts +0 -3
  282. package/src/react-hooks/createObservableHook.d.ts +0 -2
  283. package/src/react-hooks/useFetch.d.ts +0 -6
  284. package/src/react-hooks/useHover.d.ts +0 -3
  285. package/src/react-hooks/useMeasure.d.ts +0 -6
  286. package/src/react-hooks/useObservableNextRouter.d.ts +0 -33
  287. package/src/react-hooks/useObservableQuery.d.ts +0 -6
  288. package/src/react-hooks/usePersistedObservable.d.ts +0 -11
  289. package/src/retry.d.ts +0 -9
  290. package/src/setupTracking.d.ts +0 -2
  291. package/src/trace/traceHelpers.d.ts +0 -2
  292. package/src/trace/useTraceListeners.d.ts +0 -1
  293. package/src/trace/useTraceUpdates.d.ts +0 -1
  294. package/src/trace/useVerifyNotTracking.d.ts +0 -1
  295. package/src/trace/useVerifyOneRender.d.ts +0 -1
  296. package/src/trackSelector.d.ts +0 -7
  297. package/src/tracking.d.ts +0 -13
  298. package/src/when.d.ts +0 -3
package/sync.mjs ADDED
@@ -0,0 +1,912 @@
1
+ import { isObject, isPromise, observable, when, internal as internal$1, mergeIntoObservable, isEmpty, isString, setAtPath, endBatch, beginBatch, constructObjectWithPath, deconstructObjectWithPath, isFunction, isArray, whenReady } from '@legendapp/state';
2
+
3
+ const observableSyncConfiguration = {};
4
+ function configureObservableSync(options) {
5
+ Object.assign(observableSyncConfiguration, options);
6
+ }
7
+
8
+ function removeNullUndefined(val) {
9
+ if (val) {
10
+ Object.keys(val).forEach((key) => {
11
+ const v = val[key];
12
+ if (v === null || v === undefined) {
13
+ delete val[key];
14
+ }
15
+ else if (isObject(v)) {
16
+ removeNullUndefined(v);
17
+ }
18
+ });
19
+ }
20
+ return val;
21
+ }
22
+
23
+ function syncObservableAdapter({ get, set }) {
24
+ const ret = {};
25
+ if (get) {
26
+ ret.get = (async (params) => {
27
+ try {
28
+ let value = get(params);
29
+ if (isPromise(value)) {
30
+ value = await value;
31
+ }
32
+ params.onChange({
33
+ value,
34
+ lastSync: params.lastSync,
35
+ mode: params.mode,
36
+ });
37
+ params.onGet();
38
+ // eslint-disable-next-line no-empty
39
+ }
40
+ catch (_a) { }
41
+ });
42
+ }
43
+ if (set) {
44
+ ret.set = set;
45
+ }
46
+ return ret;
47
+ }
48
+
49
+ const { createPreviousHandler, globalState: globalState$1, symbolLinked: symbolLinked$2, getNode, getNodeValue: getNodeValue$1 } = internal$1;
50
+ const mapSyncPlugins = new WeakMap();
51
+ const metadatas = new WeakMap();
52
+ const promisesLocalSaves = new Set();
53
+ function parseLocalConfig(config) {
54
+ return config
55
+ ? isString(config)
56
+ ? { table: config, config: { name: config } }
57
+ : { table: config.name, config }
58
+ : {};
59
+ }
60
+ function doInOrder(arg1, arg2) {
61
+ return isPromise(arg1) ? arg1.then(arg2) : arg2(arg1);
62
+ }
63
+ function onChangeRemote(cb) {
64
+ endBatch(true);
65
+ // Remote changes should only update local state
66
+ globalState$1.isLoadingRemote = true;
67
+ beginBatch();
68
+ cb();
69
+ // Reset isLoadingRemote before ending the batch so it doesn't
70
+ // apply to any side effects
71
+ globalState$1.isLoadingRemote = false;
72
+ endBatch(true);
73
+ }
74
+ function transformSaveData(value, path, pathTypes, { transform }) {
75
+ if (transform === null || transform === void 0 ? void 0 : transform.save) {
76
+ const constructed = constructObjectWithPath(path, pathTypes, value);
77
+ const saved = transform.save(constructed);
78
+ value = deconstructObjectWithPath(path, pathTypes, saved);
79
+ }
80
+ return value;
81
+ }
82
+ function transformLoadData(value, { transform }, doUserTransform) {
83
+ if (doUserTransform && (transform === null || transform === void 0 ? void 0 : transform.load)) {
84
+ value = transform.load(value);
85
+ }
86
+ return value;
87
+ }
88
+ async function updateMetadataImmediate(obs, localState, syncState, syncOptions, newMetadata) {
89
+ const saves = Array.from(promisesLocalSaves);
90
+ if (saves.length > 0) {
91
+ await Promise.all(saves);
92
+ }
93
+ const { pluginPersist } = localState;
94
+ const { table, config } = parseLocalConfig(syncOptions === null || syncOptions === void 0 ? void 0 : syncOptions.persist);
95
+ // Save metadata
96
+ const oldMetadata = metadatas.get(obs);
97
+ const { lastSync, pending } = newMetadata;
98
+ const needsUpdate = pending || (lastSync && (!oldMetadata || lastSync !== oldMetadata.lastSync));
99
+ if (needsUpdate) {
100
+ const metadata = Object.assign({}, oldMetadata, newMetadata);
101
+ metadatas.set(obs, metadata);
102
+ if (pluginPersist) {
103
+ await pluginPersist.setMetadata(table, metadata, config);
104
+ }
105
+ if (lastSync) {
106
+ syncState.assign({
107
+ lastSync: lastSync,
108
+ });
109
+ }
110
+ }
111
+ }
112
+ function updateMetadata(obs, localState, syncState, syncOptions, newMetadata) {
113
+ if (localState.timeoutSaveMetadata) {
114
+ clearTimeout(localState.timeoutSaveMetadata);
115
+ }
116
+ localState.timeoutSaveMetadata = setTimeout(() => updateMetadataImmediate(obs, localState, syncState, syncOptions, newMetadata), 0);
117
+ }
118
+ let _queuedChanges = [];
119
+ const _queuedRemoteChanges = new Map();
120
+ const _queuedRemoteChangesTimeouts = new Map();
121
+ function mergeChanges(changes) {
122
+ const changesByPath = new Map();
123
+ const changesOut = [];
124
+ // TODO: This could be even more robust by going deeper into paths like the firebase plugin's _updatePendingSave
125
+ for (let i = 0; i < changes.length; i++) {
126
+ const change = changes[i];
127
+ const pathStr = change.path.join('/');
128
+ const existing = changesByPath.get(pathStr);
129
+ if (existing) {
130
+ existing.valueAtPath = change.valueAtPath;
131
+ }
132
+ else {
133
+ changesByPath.set(pathStr, change);
134
+ changesOut.push(change);
135
+ }
136
+ }
137
+ return changesOut;
138
+ }
139
+ function mergeQueuedChanges(allChanges) {
140
+ const changesByObsRemote = new Map();
141
+ const changesByObsLocal = new Map();
142
+ const previousByObs = new Map();
143
+ const outRemote = new Map();
144
+ const outLocal = new Map();
145
+ for (let i = 0; i < allChanges.length; i++) {
146
+ const value = allChanges[i];
147
+ const { obs, changes, inRemoteChange, getPrevious } = value;
148
+ const changesMap = inRemoteChange ? changesByObsRemote : changesByObsLocal;
149
+ const existing = changesMap.get(obs);
150
+ const newChanges = existing ? [...existing, ...changes] : changes;
151
+ const merged = mergeChanges(newChanges);
152
+ changesMap.set(obs, merged);
153
+ value.changes = merged;
154
+ if (!previousByObs.has(obs)) {
155
+ previousByObs.set(obs, getPrevious());
156
+ }
157
+ value.valuePrevious = previousByObs.get(obs);
158
+ (inRemoteChange ? outRemote : outLocal).set(obs, value);
159
+ }
160
+ return Array.from(outRemote.values()).concat(Array.from(outLocal.values()));
161
+ }
162
+ async function processQueuedChanges() {
163
+ var _a;
164
+ // Get a local copy of the queued changes and clear the global queue
165
+ const queuedChanges = mergeQueuedChanges(_queuedChanges);
166
+ _queuedChanges = [];
167
+ const pendingSyncOptions = new Set();
168
+ for (let i = 0; i < queuedChanges.length; i++) {
169
+ const change = queuedChanges[i];
170
+ if (!change.inRemoteChange) {
171
+ if (!_queuedRemoteChanges.has(change.syncOptions)) {
172
+ _queuedRemoteChanges.set(change.syncOptions, []);
173
+ }
174
+ pendingSyncOptions.add(change.syncOptions);
175
+ _queuedRemoteChanges.get(change.syncOptions).push(change);
176
+ }
177
+ }
178
+ // Note: Summary of the order of operations these functions:
179
+ // 1. Prepare all changes for saving. This may involve waiting for promises if the user has asynchronous transform.
180
+ // We need to prepare all of the changes in the queue before saving so that the saves happen in the correct order,
181
+ // since some may take longer to transformSaveData than others.
182
+ // 2. Save pending to the metadata table first. If this is the only operation that succeeds, it would try to save
183
+ // the current value again on next load, which isn't too bad.
184
+ // 3. Save local changes to storage. If they never make it to remote, then on the next load they will be pending
185
+ // and attempted again.
186
+ // 4. Wait for remote load or error if allowed
187
+ // 5. Save to remote
188
+ // 6. On successful save, merge changes (if any) back into observable
189
+ // 7. Lastly, update metadata to clear pending and update lastSync. Doing this earlier could potentially cause
190
+ // sync inconsistences so it's very important that this is last.
191
+ const preppedChangesLocal = await Promise.all(queuedChanges.map(prepChangeLocal));
192
+ // TODO Clean this up: We only need to prep this now in order to save pending changes, don't need any of the other stuff. Should split that up?
193
+ await Promise.all(queuedChanges.map(prepChangeRemote));
194
+ await Promise.all(preppedChangesLocal.map(doChangeLocal));
195
+ for (const options of pendingSyncOptions) {
196
+ const timeout = (_a = options.debounceSet) !== null && _a !== void 0 ? _a : observableSyncConfiguration === null || observableSyncConfiguration === void 0 ? void 0 : observableSyncConfiguration.debounceSet;
197
+ const timeoutSaveRemote = _queuedRemoteChangesTimeouts.get(options);
198
+ const run = () => processQueuedRemoteChanges(options);
199
+ if (timeout) {
200
+ if (timeoutSaveRemote) {
201
+ clearTimeout(timeoutSaveRemote);
202
+ }
203
+ _queuedRemoteChangesTimeouts.set(options, setTimeout(run, timeout));
204
+ }
205
+ else {
206
+ run();
207
+ }
208
+ }
209
+ }
210
+ async function processQueuedRemoteChanges(syncOptions) {
211
+ const arr = _queuedRemoteChanges.get(syncOptions);
212
+ if (arr === null || arr === void 0 ? void 0 : arr.length) {
213
+ const queuedRemoteChanges = mergeQueuedChanges(arr);
214
+ _queuedRemoteChanges.set(syncOptions, []);
215
+ const preppedChangesRemote = await Promise.all(queuedRemoteChanges.map(prepChangeRemote));
216
+ preppedChangesRemote.forEach(doChangeRemote);
217
+ }
218
+ }
219
+ async function prepChangeLocal(queuedChange) {
220
+ const { syncState, changes, localState, syncOptions, inRemoteChange, isApplyingPending } = queuedChange;
221
+ const persist = syncOptions.persist;
222
+ const { pluginSync } = localState;
223
+ const { config: configLocal } = parseLocalConfig(persist);
224
+ const configRemote = syncOptions;
225
+ const saveLocal = (persist === null || persist === void 0 ? void 0 : persist.name) && !configLocal.readonly && !isApplyingPending && syncState.isPersistEnabled.peek();
226
+ const saveRemote = !!(!inRemoteChange &&
227
+ (pluginSync === null || pluginSync === void 0 ? void 0 : pluginSync.set) &&
228
+ (configRemote === null || configRemote === void 0 ? void 0 : configRemote.enableSync) !== false &&
229
+ syncState.isEnabledRemote.peek());
230
+ if (saveLocal || saveRemote) {
231
+ if (saveLocal && !syncState.isPersistLoaded.peek()) {
232
+ console.error('[legend-state] WARNING: An observable was changed before being loaded from persist', persist);
233
+ return undefined;
234
+ }
235
+ const changesLocal = [];
236
+ const changesPaths = new Set();
237
+ let promisesTransform = [];
238
+ // Reverse order
239
+ for (let i = changes.length - 1; i >= 0; i--) {
240
+ const { path } = changes[i];
241
+ let found = false;
242
+ // Optimization to only save the latest update at each path. We might have multiple changes at the same path
243
+ // and we only need the latest value, so it starts from the end of the array, skipping any earlier changes
244
+ // already processed. If a later change modifies a parent of an earlier change (which happens on delete()
245
+ // it should be ignored as it's superseded by the parent modification.
246
+ if (changesPaths.size > 0) {
247
+ for (let u = 0; u < path.length; u++) {
248
+ if (changesPaths.has((u === path.length - 1 ? path : path.slice(0, u + 1)).join('/'))) {
249
+ found = true;
250
+ break;
251
+ }
252
+ }
253
+ }
254
+ if (!found) {
255
+ const pathStr = path.join('/');
256
+ changesPaths.add(pathStr);
257
+ const { prevAtPath, valueAtPath, pathTypes } = changes[i];
258
+ if (saveLocal) {
259
+ const promiseTransformLocal = transformSaveData(valueAtPath, path, pathTypes, configLocal);
260
+ promisesTransform.push(doInOrder(promiseTransformLocal, (valueTransformed) => {
261
+ // Prepare the local change with the transformed path/value
262
+ changesLocal.push({
263
+ path,
264
+ pathTypes,
265
+ prevAtPath,
266
+ valueAtPath: valueTransformed,
267
+ pathStr,
268
+ });
269
+ }));
270
+ }
271
+ }
272
+ }
273
+ // If there's any transform promises, wait for them before saving
274
+ promisesTransform = promisesTransform.filter(Boolean);
275
+ if (promisesTransform.length > 0) {
276
+ await Promise.all(promisesTransform);
277
+ }
278
+ return { queuedChange, changesLocal, saveRemote };
279
+ }
280
+ }
281
+ async function prepChangeRemote(queuedChange) {
282
+ const { syncState, changes, localState, syncOptions: syncOptions, inRemoteChange, isApplyingPending, valuePrevious, } = queuedChange;
283
+ const persist = syncOptions.persist;
284
+ const { pluginSync } = localState;
285
+ const { config: configLocal } = parseLocalConfig(persist);
286
+ const configRemote = syncOptions;
287
+ const saveLocal = persist && !configLocal.readonly && !isApplyingPending && syncState.isPersistEnabled.peek();
288
+ const saveRemote = !inRemoteChange && (pluginSync === null || pluginSync === void 0 ? void 0 : pluginSync.set) && (configRemote === null || configRemote === void 0 ? void 0 : configRemote.enableSync) !== false && syncState.isEnabledRemote.peek();
289
+ if (saveLocal || saveRemote) {
290
+ if (saveLocal && !syncState.isPersistLoaded.peek()) {
291
+ console.error('[legend-state] WARNING: An observable was changed before being loaded from persist', persist);
292
+ return undefined;
293
+ }
294
+ const changesRemote = [];
295
+ const changesPaths = new Set();
296
+ let promisesTransform = [];
297
+ // Reverse order
298
+ for (let i = changes.length - 1; i >= 0; i--) {
299
+ const { path } = changes[i];
300
+ let found = false;
301
+ // Optimization to only save the latest update at each path. We might have multiple changes at the same path
302
+ // and we only need the latest value, so it starts from the end of the array, skipping any earlier changes
303
+ // already processed. If a later change modifies a parent of an earlier change (which happens on delete()
304
+ // it should be ignored as it's superseded by the parent modification.
305
+ if (changesPaths.size > 0) {
306
+ for (let u = 0; u < path.length; u++) {
307
+ if (changesPaths.has((u === path.length - 1 ? path : path.slice(0, u + 1)).join('/'))) {
308
+ found = true;
309
+ break;
310
+ }
311
+ }
312
+ }
313
+ if (!found) {
314
+ const pathStr = path.join('/');
315
+ changesPaths.add(pathStr);
316
+ const { prevAtPath, valueAtPath, pathTypes } = changes[i];
317
+ if (saveRemote) {
318
+ const promiseTransformRemote = transformSaveData(valueAtPath, path, pathTypes, configRemote || {});
319
+ promisesTransform.push(doInOrder(promiseTransformRemote, (valueTransformed) => {
320
+ var _a;
321
+ // Prepare pending changes
322
+ if (!localState.pendingChanges) {
323
+ localState.pendingChanges = {};
324
+ }
325
+ // First look for existing pending changes at a higher level than this change
326
+ // If they exist then merge this change into it
327
+ let found = false;
328
+ for (let i = 0; !found && i < path.length - 1; i++) {
329
+ const pathParent = path.slice(0, i + 1).join('/');
330
+ if ((_a = localState.pendingChanges[pathParent]) === null || _a === void 0 ? void 0 : _a.v) {
331
+ found = true;
332
+ const pathChild = path.slice(i + 1);
333
+ const pathTypesChild = pathTypes.slice(i + 1);
334
+ setAtPath(localState.pendingChanges[pathParent].v, pathChild, pathTypesChild, valueAtPath);
335
+ }
336
+ }
337
+ if (!found) {
338
+ // If an existing pending change is deeper than this change, just delete it
339
+ // in favor of this wider change
340
+ for (const key in localState.pendingChanges) {
341
+ if (key !== pathStr && key.startsWith(pathStr)) {
342
+ delete localState.pendingChanges[key];
343
+ }
344
+ }
345
+ // The "p" saved in pending should be the previous state before changes,
346
+ // so don't overwrite it if it already exists
347
+ if (!localState.pendingChanges[pathStr]) {
348
+ localState.pendingChanges[pathStr] = { p: prevAtPath !== null && prevAtPath !== void 0 ? prevAtPath : null, t: pathTypes };
349
+ }
350
+ // Pending value is the untransformed value because it gets loaded without transformment
351
+ // and forwarded through to onObsChange where it gets transformed before save
352
+ localState.pendingChanges[pathStr].v = valueAtPath;
353
+ }
354
+ // Prepare the remote change with the transformed path/value
355
+ changesRemote.push({
356
+ path,
357
+ pathTypes,
358
+ prevAtPath,
359
+ valueAtPath: valueTransformed,
360
+ pathStr,
361
+ valuePrevious,
362
+ });
363
+ }));
364
+ }
365
+ }
366
+ }
367
+ // If there's any transform promises, wait for them before saving
368
+ promisesTransform = promisesTransform.filter(Boolean);
369
+ if (promisesTransform.length > 0) {
370
+ await Promise.all(promisesTransform);
371
+ }
372
+ return { queuedChange, changesRemote };
373
+ }
374
+ }
375
+ async function doChangeLocal(changeInfo) {
376
+ if (!changeInfo)
377
+ return;
378
+ const { queuedChange, changesLocal, saveRemote } = changeInfo;
379
+ const { obs, syncState, localState, syncOptions: syncOptions } = queuedChange;
380
+ const { pluginPersist } = localState;
381
+ const persist = syncOptions.persist;
382
+ const { table, config: configLocal } = parseLocalConfig(persist);
383
+ const configRemote = syncOptions;
384
+ const shouldSaveMetadata = persist && (configRemote === null || configRemote === void 0 ? void 0 : configRemote.offlineBehavior) === 'retry';
385
+ if (saveRemote && shouldSaveMetadata) {
386
+ // First save pending changes before saving local or remote
387
+ await updateMetadataImmediate(obs, localState, syncState, syncOptions, {
388
+ pending: localState.pendingChanges,
389
+ });
390
+ }
391
+ if (changesLocal.length > 0) {
392
+ // Save the changes to local cache before saving to remote. They are already marked as pending so
393
+ // if remote sync fails or the app is closed before remote sync, it will attempt to sync them on the next load.
394
+ let promiseSet = pluginPersist.set(table, changesLocal, configLocal);
395
+ if (promiseSet) {
396
+ promiseSet = promiseSet.then(() => {
397
+ promisesLocalSaves.delete(promiseSet);
398
+ });
399
+ // Keep track of local save promises so that updateMetadata runs only after everything is saved
400
+ promisesLocalSaves.add(promiseSet);
401
+ // await the local save before proceeding to save remotely
402
+ await promiseSet;
403
+ }
404
+ }
405
+ }
406
+ async function doChangeRemote(changeInfo) {
407
+ var _a, _b;
408
+ if (!changeInfo)
409
+ return;
410
+ const { queuedChange, changesRemote } = changeInfo;
411
+ const { obs, syncState, localState, syncOptions, valuePrevious: previous } = queuedChange;
412
+ const { pluginPersist, pluginSync } = localState;
413
+ const persist = syncOptions.persist;
414
+ const { table, config: configLocal } = parseLocalConfig(persist);
415
+ const { offlineBehavior, allowSetIfGetError, onBeforeSet, onSetError, waitForSet, onAfterSet } = syncOptions || {};
416
+ const shouldSaveMetadata = persist && offlineBehavior === 'retry';
417
+ if (changesRemote.length > 0) {
418
+ // Wait for remote to be ready before saving
419
+ await when(() => syncState.isLoaded.get() || (allowSetIfGetError && syncState.error.get()));
420
+ if (waitForSet) {
421
+ const waitFor = isFunction(waitForSet)
422
+ ? waitForSet({ changes: changesRemote, value: obs.peek() })
423
+ : waitForSet;
424
+ if (waitFor) {
425
+ await when(waitFor);
426
+ }
427
+ }
428
+ let value = obs.peek();
429
+ const transformSave = (_a = syncOptions === null || syncOptions === void 0 ? void 0 : syncOptions.transform) === null || _a === void 0 ? void 0 : _a.save;
430
+ if (transformSave) {
431
+ value = transformSave(value);
432
+ }
433
+ onBeforeSet === null || onBeforeSet === void 0 ? void 0 : onBeforeSet();
434
+ localState.numSavesOutstanding = (localState.numSavesOutstanding || 0) + 1;
435
+ let savedPromise = pluginSync.set({
436
+ obs,
437
+ syncState: syncState,
438
+ options: syncOptions,
439
+ changes: changesRemote,
440
+ value,
441
+ valuePrevious: previous,
442
+ });
443
+ if (isPromise(savedPromise)) {
444
+ savedPromise = savedPromise.catch((err) => onSetError === null || onSetError === void 0 ? void 0 : onSetError(err));
445
+ }
446
+ const saved = await savedPromise;
447
+ localState.numSavesOutstanding--;
448
+ // If this remote save changed anything then update cache and metadata
449
+ // Because save happens after a timeout and they're batched together, some calls to save will
450
+ // return saved data and others won't, so those can be ignored.
451
+ if (saved) {
452
+ const pathStrs = Array.from(new Set(changesRemote.map((change) => change.pathStr)));
453
+ const { changes, lastSync } = saved;
454
+ if (pathStrs.length > 0) {
455
+ if (persist) {
456
+ const metadata = {};
457
+ const pendingMetadata = (_b = pluginPersist.getMetadata(table, configLocal)) === null || _b === void 0 ? void 0 : _b.pending;
458
+ const pending = localState.pendingChanges;
459
+ let transformedChanges = undefined;
460
+ for (let i = 0; i < pathStrs.length; i++) {
461
+ const pathStr = pathStrs[i];
462
+ // Clear pending for this path
463
+ if (pending === null || pending === void 0 ? void 0 : pending[pathStr]) {
464
+ // Remove pending from local state
465
+ delete pending[pathStr];
466
+ }
467
+ // Clear pending for this path
468
+ if (pendingMetadata === null || pendingMetadata === void 0 ? void 0 : pendingMetadata[pathStr]) {
469
+ // Remove pending from persisted medata state
470
+ delete pendingMetadata[pathStr];
471
+ metadata.pending = pendingMetadata;
472
+ }
473
+ }
474
+ if (lastSync) {
475
+ metadata.lastSync = lastSync;
476
+ }
477
+ // Remote can optionally have data that needs to be merged back into the observable,
478
+ // for example Firebase may update dateModified with the server timestamp
479
+ if (changes && !isEmpty(changes)) {
480
+ transformedChanges = transformLoadData(changes, syncOptions, false);
481
+ }
482
+ if (localState.numSavesOutstanding > 0) {
483
+ if (transformedChanges) {
484
+ if (!localState.pendingSaveResults) {
485
+ localState.pendingSaveResults = [];
486
+ }
487
+ localState.pendingSaveResults.push(transformedChanges);
488
+ }
489
+ }
490
+ else {
491
+ let allChanges = [...(localState.pendingSaveResults || []), transformedChanges].filter((v) => v !== undefined);
492
+ if (allChanges.length > 0) {
493
+ if (allChanges.some((change) => isPromise(change))) {
494
+ allChanges = await Promise.all(allChanges);
495
+ }
496
+ onChangeRemote(() => mergeIntoObservable(obs, ...allChanges));
497
+ }
498
+ if (shouldSaveMetadata && !isEmpty(metadata)) {
499
+ updateMetadata(obs, localState, syncState, syncOptions, metadata);
500
+ }
501
+ localState.pendingSaveResults = [];
502
+ }
503
+ }
504
+ onAfterSet === null || onAfterSet === void 0 ? void 0 : onAfterSet();
505
+ }
506
+ }
507
+ }
508
+ }
509
+ function onObsChange(obs, syncState, localState, syncOptions, { changes, loading, remote, getPrevious }) {
510
+ if (!loading) {
511
+ const inRemoteChange = remote;
512
+ const isApplyingPending = localState.isApplyingPending;
513
+ // Queue changes in a microtask so that multiple changes within a frame get run together
514
+ _queuedChanges.push({
515
+ obs: obs,
516
+ syncState,
517
+ localState,
518
+ syncOptions,
519
+ changes,
520
+ inRemoteChange,
521
+ isApplyingPending: isApplyingPending,
522
+ getPrevious,
523
+ });
524
+ if (_queuedChanges.length === 1) {
525
+ queueMicrotask(processQueuedChanges);
526
+ }
527
+ }
528
+ }
529
+ async function loadLocal(obs, syncOptions, syncState, localState) {
530
+ var _a, _b;
531
+ const { persist } = syncOptions;
532
+ if (persist) {
533
+ const PersistPlugin = persist.plugin || ((_a = observableSyncConfiguration.persist) === null || _a === void 0 ? void 0 : _a.plugin);
534
+ const { table, config } = parseLocalConfig(persist);
535
+ const node = getNode(obs);
536
+ if (!PersistPlugin) {
537
+ throw new Error('Local persist is not configured');
538
+ }
539
+ // Ensure there's only one instance of the cache plugin
540
+ if (!mapSyncPlugins.has(PersistPlugin)) {
541
+ const persistPlugin = new PersistPlugin();
542
+ const mapValue = { plugin: persistPlugin, initialized: observable(false) };
543
+ mapSyncPlugins.set(PersistPlugin, mapValue);
544
+ if (persistPlugin.initialize) {
545
+ const initializePromise = (_b = persistPlugin.initialize) === null || _b === void 0 ? void 0 : _b.call(persistPlugin, (observableSyncConfiguration === null || observableSyncConfiguration === void 0 ? void 0 : observableSyncConfiguration.persist) || {});
546
+ if (isPromise(initializePromise)) {
547
+ await initializePromise;
548
+ }
549
+ }
550
+ mapValue.initialized.set(true);
551
+ }
552
+ const { plugin, initialized: initialized$ } = mapSyncPlugins.get(PersistPlugin);
553
+ const persistPlugin = plugin;
554
+ localState.pluginPersist = persistPlugin;
555
+ if (!initialized$.peek()) {
556
+ await when(initialized$);
557
+ }
558
+ // If cache has an asynchronous load, wait for it
559
+ if (persistPlugin.loadTable) {
560
+ const promise = persistPlugin.loadTable(table, config);
561
+ if (promise) {
562
+ await promise;
563
+ }
564
+ }
565
+ // Get current value for init
566
+ const prevValue = getNodeValue$1(node);
567
+ // Get the value from state
568
+ let value = persistPlugin.getTable(table, prevValue, config);
569
+ const metadata = persistPlugin.getMetadata(table, config);
570
+ if (metadata) {
571
+ metadatas.set(obs, metadata);
572
+ localState.pendingChanges = metadata.pending;
573
+ syncState.assign({
574
+ lastSync: metadata.lastSync,
575
+ });
576
+ }
577
+ // Merge the data from local cache into the default state
578
+ if (value !== undefined) {
579
+ const { transform } = config;
580
+ value = transformLoadData(value, { transform }, true);
581
+ if (isPromise(value)) {
582
+ value = await value;
583
+ }
584
+ // isLoadingLocal prevents saving remotely when two different caches
585
+ // are set on the same observable
586
+ internal$1.globalState.isLoadingLocal = true;
587
+ // We want to merge the local data on top of any initial state the object is created with
588
+ if (value === null && (!prevValue || prevValue[symbolLinked$2])) {
589
+ obs.set(value);
590
+ }
591
+ else {
592
+ mergeIntoObservable(obs, value);
593
+ }
594
+ internal$1.globalState.isLoadingLocal = false;
595
+ }
596
+ node.state.peek().clearPersist = () => Promise.all([
597
+ persistPlugin.deleteTable(table, config),
598
+ persistPlugin.deleteMetadata(table, config),
599
+ ]);
600
+ }
601
+ syncState.isPersistLoaded.set(true);
602
+ }
603
+ function syncObservable(obs$, syncOptions) {
604
+ const node = getNode(obs$);
605
+ // Merge remote sync options with global options
606
+ if (syncOptions) {
607
+ syncOptions = Object.assign({
608
+ syncMode: 'auto',
609
+ }, observableSyncConfiguration, removeNullUndefined(syncOptions));
610
+ }
611
+ const localState = {};
612
+ let sync;
613
+ const syncState = (node.state = observable({
614
+ isPersistLoaded: false,
615
+ isLoaded: !syncOptions.get,
616
+ isPersistEnabled: true,
617
+ isEnabledRemote: true,
618
+ clearPersist: undefined,
619
+ sync: () => Promise.resolve(),
620
+ getPendingChanges: () => localState.pendingChanges,
621
+ }));
622
+ loadLocal(obs$, syncOptions, syncState, localState);
623
+ localState.pluginSync = syncObservableAdapter(syncOptions);
624
+ if (syncOptions.get) {
625
+ let isSynced = false;
626
+ sync = async () => {
627
+ var _a, _b;
628
+ const lastSync = (_a = metadatas.get(obs$)) === null || _a === void 0 ? void 0 : _a.lastSync;
629
+ const pending = localState.pendingChanges;
630
+ const get = (_b = localState.pluginSync.get) === null || _b === void 0 ? void 0 : _b.bind(localState.pluginSync);
631
+ if (get) {
632
+ const runGet = () => {
633
+ get({
634
+ state: syncState,
635
+ obs: obs$,
636
+ options: syncOptions,
637
+ lastSync,
638
+ dateModified: lastSync,
639
+ onError: (error) => {
640
+ var _a;
641
+ (_a = syncOptions.onGetError) === null || _a === void 0 ? void 0 : _a.call(syncOptions, error);
642
+ },
643
+ onGet: () => {
644
+ node.state.assign({
645
+ isLoaded: true,
646
+ error: undefined,
647
+ });
648
+ },
649
+ onChange: async ({ value, mode, lastSync }) => {
650
+ mode = mode || syncOptions.mode || 'set';
651
+ if (value !== undefined) {
652
+ value = transformLoadData(value, syncOptions, true);
653
+ if (isPromise(value)) {
654
+ value = await value;
655
+ }
656
+ const pending = localState.pendingChanges;
657
+ if (pending) {
658
+ Object.keys(pending).forEach((key) => {
659
+ const p = key.split('/').filter((p) => p !== '');
660
+ const { v, t } = pending[key];
661
+ if (t.length === 0 || !value) {
662
+ if (isObject(value) && isObject(v)) {
663
+ Object.assign(value, v);
664
+ }
665
+ else {
666
+ value = v;
667
+ }
668
+ }
669
+ else if (value[p[0]] !== undefined) {
670
+ value = setAtPath(value, p, t, v, 'merge', obs$.peek(), (path, value) => {
671
+ delete pending[key];
672
+ pending[path.join('/')] = {
673
+ p: null,
674
+ v: value,
675
+ t: t.slice(0, path.length),
676
+ };
677
+ });
678
+ }
679
+ });
680
+ }
681
+ onChangeRemote(() => {
682
+ if (mode === 'assign' && isObject(value)) {
683
+ obs$.assign(value);
684
+ }
685
+ else if (mode === 'append' && isArray(value)) {
686
+ obs$.push(...value);
687
+ }
688
+ else if (mode === 'prepend' && isArray(value)) {
689
+ obs$.splice(0, 0, ...value);
690
+ }
691
+ else if (mode === 'merge') {
692
+ mergeIntoObservable(obs$, value);
693
+ }
694
+ else {
695
+ obs$.set(value);
696
+ }
697
+ });
698
+ }
699
+ if (lastSync && syncOptions.persist) {
700
+ updateMetadata(obs$, localState, syncState, syncOptions, {
701
+ lastSync,
702
+ });
703
+ }
704
+ },
705
+ });
706
+ };
707
+ runGet();
708
+ }
709
+ else {
710
+ node.state.assign({
711
+ isLoaded: true,
712
+ error: undefined,
713
+ });
714
+ }
715
+ if (!isSynced) {
716
+ isSynced = true;
717
+ // Wait for remote to be ready before saving pending
718
+ await when(() => syncState.isLoaded.get() || (syncOptions.allowSetIfGetError && syncState.error.get()));
719
+ if (pending && !isEmpty(pending)) {
720
+ localState.isApplyingPending = true;
721
+ const keys = Object.keys(pending);
722
+ // Bundle up all the changes from pending
723
+ const changes = [];
724
+ for (let i = 0; i < keys.length; i++) {
725
+ const key = keys[i];
726
+ const path = key.split('/').filter((p) => p !== '');
727
+ const { p, v, t } = pending[key];
728
+ changes.push({ path, valueAtPath: v, prevAtPath: p, pathTypes: t });
729
+ }
730
+ // Send the changes into onObsChange so that they get synced remotely
731
+ const value = getNodeValue$1(node);
732
+ onObsChange(obs$, syncState, localState, syncOptions, {
733
+ value,
734
+ loading: false,
735
+ remote: false,
736
+ getPrevious: createPreviousHandler(value, changes),
737
+ changes,
738
+ });
739
+ localState.isApplyingPending = false;
740
+ }
741
+ }
742
+ };
743
+ syncState.assign({ sync });
744
+ }
745
+ // Wait for this node and all parent nodes up the hierarchy to be loaded
746
+ const onAllPersistLoaded = () => {
747
+ var _a, _b;
748
+ let parentNode = node;
749
+ while (parentNode) {
750
+ if (((_b = (_a = parentNode.state) === null || _a === void 0 ? void 0 : _a.isPersistLoaded) === null || _b === void 0 ? void 0 : _b.get()) === false) {
751
+ return false;
752
+ }
753
+ parentNode = parentNode.parent;
754
+ }
755
+ return true;
756
+ };
757
+ // When all is loaded locally we can start syncing and listening for changes
758
+ when(onAllPersistLoaded, function () {
759
+ // If remote is not manual, then sync() is called automatically
760
+ if (syncOptions.get && syncOptions.syncMode === 'auto') {
761
+ sync();
762
+ }
763
+ obs$.onChange(onObsChange.bind(this, obs$, syncState, localState, syncOptions));
764
+ });
765
+ return syncState;
766
+ }
767
+
768
+ const { getProxy, globalState, runWithRetry, symbolLinked: symbolLinked$1, setNodeValue, getNodeValue } = internal$1;
769
+ function enableActivateSyncedNode() {
770
+ globalState.activateSyncedNode = function activateSyncedNode(node, newValue) {
771
+ const obs$ = getProxy(node);
772
+ if (node.activationState) {
773
+ // If it is a Synced
774
+ const { get, initial, set, subscribe } = node.activationState;
775
+ let onChange = undefined;
776
+ const pluginRemote = {};
777
+ let promiseReturn = undefined;
778
+ // Not sure why this disable is needed, but it's needed to make the linter happy
779
+ // eslint-disable-next-line prefer-const
780
+ let syncState;
781
+ const refresh = () => syncState === null || syncState === void 0 ? void 0 : syncState.sync();
782
+ if (get) {
783
+ pluginRemote.get = (params) => {
784
+ onChange = params.onChange;
785
+ const updateLastSync = (lastSync) => (params.lastSync = lastSync);
786
+ const setMode = (mode) => (params.mode = mode);
787
+ const existingValue = getNodeValue(node);
788
+ const value = runWithRetry(node, { attemptNum: 0 }, () => {
789
+ return get({
790
+ value: isFunction(existingValue) || (existingValue === null || existingValue === void 0 ? void 0 : existingValue[symbolLinked$1]) ? undefined : existingValue,
791
+ lastSync: params.lastSync,
792
+ updateLastSync,
793
+ setMode,
794
+ refresh,
795
+ });
796
+ });
797
+ promiseReturn = value;
798
+ return value;
799
+ };
800
+ }
801
+ if (set) {
802
+ // TODO: Work out these types better
803
+ pluginRemote.set = async (params) => {
804
+ var _a;
805
+ if ((_a = node.state) === null || _a === void 0 ? void 0 : _a.isLoaded.get()) {
806
+ const retryAttempts = { attemptNum: 0 };
807
+ return runWithRetry(node, retryAttempts, async (retryEvent) => {
808
+ let changes = {};
809
+ let maxModified = 0;
810
+ if (!node.state.isLoaded.peek()) {
811
+ await whenReady(node.state.isLoaded);
812
+ }
813
+ const cancelRetry = () => {
814
+ retryEvent.cancel = true;
815
+ };
816
+ await set({
817
+ ...params,
818
+ node,
819
+ update: (params) => {
820
+ const { value, lastSync } = params;
821
+ maxModified = Math.max(lastSync || 0, maxModified);
822
+ changes = mergeIntoObservable(changes, value);
823
+ },
824
+ retryNum: retryAttempts.attemptNum,
825
+ cancelRetry,
826
+ refresh,
827
+ fromSubscribe: false,
828
+ });
829
+ return { changes, lastSync: maxModified || undefined };
830
+ });
831
+ }
832
+ };
833
+ }
834
+ const nodeVal = getNodeValue(node);
835
+ if (promiseReturn !== undefined) {
836
+ newValue = promiseReturn;
837
+ }
838
+ else if (nodeVal !== undefined && !isFunction(nodeVal)) {
839
+ newValue = nodeVal;
840
+ }
841
+ else {
842
+ newValue = initial;
843
+ }
844
+ setNodeValue(node, promiseReturn ? undefined : newValue);
845
+ // @ts-expect-error TODO fix these types
846
+ syncState = syncObservable(obs$, { ...node.activationState, ...pluginRemote });
847
+ if (subscribe) {
848
+ when(promiseReturn || true, () => {
849
+ subscribe({
850
+ node,
851
+ update: (params) => {
852
+ if (!onChange) {
853
+ // TODO: Make this message better
854
+ console.log('[legend-state] Cannot update immediately before the first return');
855
+ }
856
+ else {
857
+ onChange(params);
858
+ }
859
+ },
860
+ refresh,
861
+ });
862
+ });
863
+ }
864
+ return { update: onChange, value: newValue };
865
+ }
866
+ else {
867
+ // If it is not a Synced
868
+ let update = undefined;
869
+ const get = async (params) => {
870
+ update = params.refresh;
871
+ if (isPromise(newValue)) {
872
+ try {
873
+ newValue = await newValue;
874
+ }
875
+ catch (_a) {
876
+ // TODO Once we have global retry settings this should retry
877
+ }
878
+ }
879
+ return newValue;
880
+ };
881
+ syncObservable(obs$, {
882
+ get,
883
+ });
884
+ return { update: update, value: newValue };
885
+ }
886
+ };
887
+ }
888
+
889
+ const { symbolLinked } = internal$1;
890
+ function synced(params) {
891
+ installPersistActivateNode();
892
+ return (() => ({
893
+ [symbolLinked]: { ...params, synced: true },
894
+ }));
895
+ }
896
+ let didInstall = false;
897
+ function installPersistActivateNode() {
898
+ if (!didInstall) {
899
+ enableActivateSyncedNode();
900
+ didInstall = true;
901
+ }
902
+ }
903
+
904
+ function isInRemoteChange() {
905
+ return internal$1.globalState.isLoadingRemote;
906
+ }
907
+ const internal = {
908
+ observableSyncConfiguration,
909
+ };
910
+
911
+ export { configureObservableSync, internal, isInRemoteChange, mapSyncPlugins, syncObservable, synced };
912
+ //# sourceMappingURL=sync.mjs.map