@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
@@ -0,0 +1,1029 @@
1
+ import type {
2
+ Change,
3
+ ClassConstructor,
4
+ FieldTransforms,
5
+ ListenerParams,
6
+ NodeValue,
7
+ Observable,
8
+ ObservableObject,
9
+ ObservableParam,
10
+ ObservablePersistLocal,
11
+ ObservablePersistRemoteClass,
12
+ ObservablePersistRemoteFunctions,
13
+ ObservablePersistState,
14
+ PersistMetadata,
15
+ LegacyPersistOptions,
16
+ LegacyPersistOptionsLocal,
17
+ LegacyPersistOptionsRemote,
18
+ PersistTransform,
19
+ TypeAtPath,
20
+ } from '@legendapp/state';
21
+ import {
22
+ batch,
23
+ constructObjectWithPath,
24
+ deconstructObjectWithPath,
25
+ endBatch,
26
+ internal,
27
+ isEmpty,
28
+ isFunction,
29
+ isObject,
30
+ isObservable,
31
+ isPromise,
32
+ isString,
33
+ mergeIntoObservable,
34
+ observable,
35
+ setAtPath,
36
+ setInObservableAtPath,
37
+ when,
38
+ } from '@legendapp/state';
39
+ import { removeNullUndefined } from '../sync/syncHelpers';
40
+ import { observablePersistConfiguration } from './configureObservablePersistence';
41
+ import { invertFieldMap, transformObject, transformObjectWithPath, transformPath } from './fieldTransformer';
42
+ import { observablePersistRemoteFunctionsAdapter } from './observablePersistRemoteFunctionsAdapter';
43
+
44
+ const { globalState, symbolLinked, getNode } = internal;
45
+
46
+ export const mapPersistences: WeakMap<
47
+ ClassConstructor<ObservablePersistLocal | ObservablePersistRemoteClass>,
48
+ {
49
+ persist: ObservablePersistLocal | ObservablePersistRemoteClass;
50
+ initialized?: Observable<boolean>;
51
+ }
52
+ > = new WeakMap();
53
+
54
+ const metadatas = new WeakMap<ObservableParam<any>, PersistMetadata>();
55
+ const promisesLocalSaves = new Set<Promise<void>>();
56
+
57
+ interface LocalState {
58
+ persistenceLocal?: ObservablePersistLocal;
59
+ persistenceRemote?: ObservablePersistRemoteClass;
60
+ pendingChanges?: Record<string, { p: any; v?: any; t: TypeAtPath[] }>;
61
+ numSavesOutstanding?: number;
62
+ pendingSaveResults?: object[];
63
+ isApplyingPending?: boolean;
64
+ timeoutSaveMetadata?: any;
65
+ }
66
+
67
+ interface PreppedChangeLocal {
68
+ queuedChange: QueuedChange;
69
+ changesLocal: ChangeWithPathStr[];
70
+ saveRemote: boolean;
71
+ }
72
+
73
+ interface PreppedChangeRemote {
74
+ queuedChange: QueuedChange;
75
+ changesRemote: ChangeWithPathStr[];
76
+ }
77
+
78
+ type ChangeWithPathStr = Change & { pathStr: string };
79
+
80
+ function parseLocalConfig(config: string | LegacyPersistOptionsLocal | undefined): {
81
+ table: string;
82
+ config: LegacyPersistOptionsLocal;
83
+ } {
84
+ return config
85
+ ? isString(config)
86
+ ? { table: config, config: { name: config } }
87
+ : { table: config.name, config }
88
+ : ({} as { table: string; config: LegacyPersistOptionsLocal });
89
+ }
90
+
91
+ function doInOrder<T>(arg1: T | Promise<T>, arg2: (value: T) => void): any {
92
+ return isPromise(arg1) ? arg1.then(arg2) : arg2(arg1);
93
+ }
94
+
95
+ export function onChangeRemote(cb: () => void) {
96
+ endBatch(true);
97
+ // Remote changes should only update local state
98
+ globalState.isLoadingRemote = true;
99
+
100
+ batch(cb);
101
+
102
+ globalState.isLoadingRemote = false;
103
+ }
104
+
105
+ export function transformOutData(
106
+ value: any,
107
+ path: string[],
108
+ pathTypes: TypeAtPath[],
109
+ { transform, fieldTransforms }: { transform?: PersistTransform; fieldTransforms?: FieldTransforms<any> },
110
+ ): { value: any; path: string[] } | Promise<{ value: any; path: string[] }> {
111
+ if (fieldTransforms || transform?.save) {
112
+ const transformFn = () => {
113
+ if (fieldTransforms) {
114
+ const { obj, path: pathTransformed } = transformObjectWithPath(value, path, pathTypes, fieldTransforms);
115
+ value = obj;
116
+ path = pathTransformed;
117
+ }
118
+
119
+ return { value, path };
120
+ };
121
+
122
+ if (transform?.save) {
123
+ const constructed = constructObjectWithPath(path, pathTypes, value);
124
+ const saved = transform.save(constructed);
125
+ const deconstruct = (toDeconstruct: boolean) => {
126
+ value = deconstructObjectWithPath(path, pathTypes, toDeconstruct);
127
+ return transformFn();
128
+ };
129
+ return doInOrder(saved, deconstruct);
130
+ }
131
+ return transformFn();
132
+ }
133
+
134
+ return { value, path };
135
+ }
136
+
137
+ export function transformLoadData(
138
+ value: any,
139
+ { transform, fieldTransforms }: { fieldTransforms?: FieldTransforms<any>; transform?: PersistTransform },
140
+ doUserTransform: boolean,
141
+ ): Promise<any> | any {
142
+ if (fieldTransforms) {
143
+ const inverted = invertFieldMap(fieldTransforms);
144
+ value = transformObject(value, inverted);
145
+ }
146
+
147
+ if (doUserTransform && transform?.load) {
148
+ value = transform.load(value);
149
+ }
150
+
151
+ return value;
152
+ }
153
+
154
+ async function updateMetadataImmediate<T>(
155
+ obs: ObservableParam<any>,
156
+ localState: LocalState,
157
+ syncState: Observable<ObservablePersistState>,
158
+ persistOptions: LegacyPersistOptions<T>,
159
+ newMetadata: PersistMetadata,
160
+ ) {
161
+ const saves = Array.from(promisesLocalSaves);
162
+ if (saves.length > 0) {
163
+ await Promise.all(saves);
164
+ }
165
+
166
+ const { persistenceLocal } = localState;
167
+ const local = persistOptions.local;
168
+ const { table, config } = parseLocalConfig(local!);
169
+
170
+ // Save metadata
171
+ const oldMetadata: PersistMetadata | undefined = metadatas.get(obs);
172
+
173
+ const { lastSync, pending } = newMetadata;
174
+
175
+ const needsUpdate = pending || (lastSync && (!oldMetadata || lastSync !== oldMetadata.lastSync));
176
+
177
+ if (needsUpdate) {
178
+ const metadata = Object.assign({}, oldMetadata, newMetadata);
179
+ metadatas.set(obs, metadata);
180
+ if (persistenceLocal) {
181
+ await persistenceLocal!.setMetadata(table, metadata, config);
182
+ }
183
+
184
+ if (lastSync) {
185
+ syncState.assign({
186
+ lastSync: lastSync,
187
+ dateModified: lastSync,
188
+ });
189
+ }
190
+ }
191
+ }
192
+
193
+ function updateMetadata<T>(
194
+ obs: ObservableParam<any>,
195
+ localState: LocalState,
196
+ syncState: ObservableObject<ObservablePersistState>,
197
+ persistOptions: LegacyPersistOptions<T>,
198
+ newMetadata: PersistMetadata,
199
+ ) {
200
+ if (localState.timeoutSaveMetadata) {
201
+ clearTimeout(localState.timeoutSaveMetadata);
202
+ }
203
+ localState.timeoutSaveMetadata = setTimeout(
204
+ () =>
205
+ updateMetadataImmediate(obs, localState, syncState, persistOptions as LegacyPersistOptions<T>, newMetadata),
206
+ persistOptions?.remote?.metadataTimeout || 0,
207
+ );
208
+ }
209
+
210
+ interface QueuedChange<T = any> {
211
+ inRemoteChange: boolean;
212
+ isApplyingPending: boolean;
213
+ obs: Observable<T>;
214
+ syncState: ObservableObject<ObservablePersistState>;
215
+ localState: LocalState;
216
+ persistOptions: LegacyPersistOptions<T>;
217
+ changes: ListenerParams['changes'];
218
+ }
219
+
220
+ let _queuedChanges: QueuedChange[] = [];
221
+ let _queuedRemoteChanges: QueuedChange[] = [];
222
+ let timeoutSaveRemote: any = undefined;
223
+
224
+ function mergeChanges(changes: Change[]) {
225
+ const changesByPath = new Map<string, Change>();
226
+ const changesOut: Change[] = [];
227
+ // TODO: This could be even more robust by going deeper into paths like the firebase plugin's _updatePendingSave
228
+ for (let i = 0; i < changes.length; i++) {
229
+ const change = changes[i];
230
+ const pathStr = change.path.join('/');
231
+ const existing = changesByPath.get(pathStr);
232
+ if (existing) {
233
+ existing.valueAtPath = change.valueAtPath;
234
+ } else {
235
+ changesByPath.set(pathStr, change);
236
+ changesOut.push(change);
237
+ }
238
+ }
239
+ return changesOut;
240
+ }
241
+
242
+ function mergeQueuedChanges(allChanges: QueuedChange[]) {
243
+ const changesByObsRemote = new Map<Observable, Change[]>();
244
+ const changesByObsLocal = new Map<Observable, Change[]>();
245
+
246
+ const outRemote: Map<Observable, QueuedChange> = new Map();
247
+ const outLocal: Map<Observable, QueuedChange> = new Map();
248
+ for (let i = 0; i < allChanges.length; i++) {
249
+ const value = allChanges[i];
250
+ const { obs, changes, inRemoteChange } = value;
251
+ const changesMap = inRemoteChange ? changesByObsRemote : changesByObsLocal;
252
+ const existing = changesMap.get(obs);
253
+ const newChanges = existing ? [...existing, ...changes] : changes;
254
+ const merged = mergeChanges(newChanges);
255
+ changesMap.set(obs, merged);
256
+ value.changes = merged;
257
+ (inRemoteChange ? outRemote : outLocal).set(obs, value);
258
+ }
259
+ return Array.from(outRemote.values()).concat(Array.from(outLocal.values()));
260
+ }
261
+
262
+ async function processQueuedChanges() {
263
+ // Get a local copy of the queued changes and clear the global queue
264
+ const queuedChanges = mergeQueuedChanges(_queuedChanges);
265
+ _queuedChanges = [];
266
+
267
+ _queuedRemoteChanges.push(...queuedChanges.filter((c) => !c.inRemoteChange));
268
+
269
+ // Note: Summary of the order of operations these functions:
270
+ // 1. Prepare all changes for saving. This may involve waiting for promises if the user has asynchronous transform.
271
+ // We need to prepare all of the changes in the queue before saving so that the saves happen in the correct order,
272
+ // since some may take longer to transformSaveData than others.
273
+ // 2. Save pending to the metadata table first. If this is the only operation that succeeds, it would try to save
274
+ // the current value again on next load, which isn't too bad.
275
+ // 3. Save local changes to storage. If they never make it to remote, then on the next load they will be pending
276
+ // and attempted again.
277
+ // 4. Wait for remote load or error if allowed
278
+ // 5. Save to remote
279
+ // 6. On successful save, merge changes (if any) back into observable
280
+ // 7. Lastly, update metadata to clear pending and update lastSync. Doing this earlier could potentially cause
281
+ // sync inconsistences so it's very important that this is last.
282
+
283
+ const preppedChangesLocal = await Promise.all(queuedChanges.map(prepChangeLocal));
284
+
285
+ // TODO Clean this up: We only need to prep this now in ordre to save pending changes, don't need any of the other stuff. Should split that up?
286
+ await Promise.all(queuedChanges.map(prepChangeRemote));
287
+
288
+ await Promise.all(preppedChangesLocal.map(doChangeLocal));
289
+
290
+ const timeout = observablePersistConfiguration?.remoteOptions?.debounceSet;
291
+ if (timeout) {
292
+ if (timeoutSaveRemote) {
293
+ clearTimeout(timeoutSaveRemote);
294
+ }
295
+
296
+ timeoutSaveRemote = setTimeout(processQueuedRemoteChanges, timeout);
297
+ } else {
298
+ processQueuedRemoteChanges();
299
+ }
300
+ }
301
+
302
+ async function processQueuedRemoteChanges() {
303
+ const queuedRemoteChanges = mergeQueuedChanges(_queuedRemoteChanges);
304
+ _queuedRemoteChanges = [];
305
+
306
+ const preppedChangesRemote = await Promise.all(queuedRemoteChanges.map(prepChangeRemote));
307
+
308
+ preppedChangesRemote.forEach(doChangeRemote);
309
+ }
310
+
311
+ async function prepChangeLocal(queuedChange: QueuedChange): Promise<PreppedChangeLocal | undefined> {
312
+ const { syncState, changes, localState, persistOptions, inRemoteChange, isApplyingPending } = queuedChange;
313
+
314
+ const local = persistOptions.local;
315
+ const { persistenceRemote } = localState;
316
+ const { config: configLocal } = parseLocalConfig(local!);
317
+ const configRemote = persistOptions.remote;
318
+ const saveLocal = local && !configLocal.readonly && !isApplyingPending && syncState.isEnabledLocal.peek();
319
+ const saveRemote = !!(
320
+ !inRemoteChange &&
321
+ persistenceRemote?.set &&
322
+ !configRemote?.readonly &&
323
+ syncState.isEnabledRemote.peek()
324
+ );
325
+
326
+ if (saveLocal || saveRemote) {
327
+ if (saveLocal && !syncState.isLoadedLocal.peek()) {
328
+ console.error(
329
+ '[legend-state] WARNING: An observable was changed before being loaded from persistence',
330
+ local,
331
+ );
332
+ return undefined;
333
+ }
334
+ const changesLocal: ChangeWithPathStr[] = [];
335
+ const changesPaths = new Set<string>();
336
+ let promisesTransform: (void | Promise<any>)[] = [];
337
+
338
+ // Reverse order
339
+ for (let i = changes.length - 1; i >= 0; i--) {
340
+ const { path } = changes[i];
341
+
342
+ let found = false;
343
+
344
+ // Optimization to only save the latest update at each path. We might have multiple changes at the same path
345
+ // and we only need the latest value, so it starts from the end of the array, skipping any earlier changes
346
+ // already processed. If a later change modifies a parent of an earlier change (which happens on delete()
347
+ // it should be ignored as it's superseded by the parent modification.
348
+ if (changesPaths.size > 0) {
349
+ for (let u = 0; u < path.length; u++) {
350
+ if (changesPaths.has((u === path.length - 1 ? path : path.slice(0, u + 1)).join('/'))) {
351
+ found = true;
352
+ break;
353
+ }
354
+ }
355
+ }
356
+
357
+ if (!found) {
358
+ const pathStr = path.join('/');
359
+ changesPaths.add(pathStr);
360
+
361
+ const { prevAtPath, valueAtPath, pathTypes } = changes[i];
362
+ if (saveLocal) {
363
+ const promiseTransformLocal = transformOutData(
364
+ valueAtPath,
365
+ path as string[],
366
+ pathTypes,
367
+ configLocal,
368
+ );
369
+
370
+ promisesTransform.push(
371
+ doInOrder(promiseTransformLocal, ({ path: pathTransformed, value: valueTransformed }) => {
372
+ // If path includes undefined there was a null in fieldTransforms so don't need to save it
373
+ if (!pathTransformed.includes(undefined as unknown as string)) {
374
+ // Prepare the local change with the transformed path/value
375
+ changesLocal.push({
376
+ path: pathTransformed,
377
+ pathTypes,
378
+ prevAtPath,
379
+ valueAtPath: valueTransformed,
380
+ pathStr,
381
+ });
382
+ }
383
+ }),
384
+ );
385
+ }
386
+ }
387
+ }
388
+
389
+ // If there's any transform promises, wait for them before saving
390
+ promisesTransform = promisesTransform.filter(Boolean);
391
+ if (promisesTransform.length > 0) {
392
+ await Promise.all(promisesTransform);
393
+ }
394
+
395
+ return { queuedChange, changesLocal, saveRemote };
396
+ }
397
+ }
398
+ async function prepChangeRemote(queuedChange: QueuedChange): Promise<PreppedChangeRemote | undefined> {
399
+ const { syncState, changes, localState, persistOptions, inRemoteChange, isApplyingPending } = queuedChange;
400
+
401
+ const local = persistOptions.local;
402
+ const { persistenceRemote } = localState;
403
+ const { config: configLocal } = parseLocalConfig(local!);
404
+ const configRemote = persistOptions.remote;
405
+ const saveLocal = local && !configLocal.readonly && !isApplyingPending && syncState.isEnabledLocal.peek();
406
+ const saveRemote =
407
+ !inRemoteChange && persistenceRemote?.set && !configRemote?.readonly && syncState.isEnabledRemote.peek();
408
+
409
+ if (saveLocal || saveRemote) {
410
+ if (saveLocal && !syncState.isLoadedLocal.peek()) {
411
+ console.error(
412
+ '[legend-state] WARNING: An observable was changed before being loaded from persistence',
413
+ local,
414
+ );
415
+ return undefined;
416
+ }
417
+ const changesRemote: ChangeWithPathStr[] = [];
418
+ const changesPaths = new Set<string>();
419
+ let promisesTransform: (void | Promise<any>)[] = [];
420
+
421
+ // Reverse order
422
+ for (let i = changes.length - 1; i >= 0; i--) {
423
+ const { path } = changes[i];
424
+
425
+ let found = false;
426
+
427
+ // Optimization to only save the latest update at each path. We might have multiple changes at the same path
428
+ // and we only need the latest value, so it starts from the end of the array, skipping any earlier changes
429
+ // already processed. If a later change modifies a parent of an earlier change (which happens on delete()
430
+ // it should be ignored as it's superseded by the parent modification.
431
+ if (changesPaths.size > 0) {
432
+ for (let u = 0; u < path.length; u++) {
433
+ if (changesPaths.has((u === path.length - 1 ? path : path.slice(0, u + 1)).join('/'))) {
434
+ found = true;
435
+ break;
436
+ }
437
+ }
438
+ }
439
+
440
+ if (!found) {
441
+ const pathStr = path.join('/');
442
+ changesPaths.add(pathStr);
443
+
444
+ const { prevAtPath, valueAtPath, pathTypes } = changes[i];
445
+
446
+ if (saveRemote) {
447
+ const promiseTransformRemote = transformOutData(
448
+ valueAtPath,
449
+ path as string[],
450
+ pathTypes,
451
+ configRemote || {},
452
+ );
453
+
454
+ promisesTransform.push(
455
+ doInOrder(promiseTransformRemote, ({ path: pathTransformed, value: valueTransformed }) => {
456
+ // If path includes undefined there was a null in fieldTransforms so don't need to save it
457
+ if (!pathTransformed.includes(undefined as unknown as string)) {
458
+ // Prepare pending changes
459
+ if (!localState.pendingChanges) {
460
+ localState.pendingChanges = {};
461
+ }
462
+
463
+ // First look for existing pending changes at a higher level than this change
464
+ // If they exist then merge this change into it
465
+ let found = false;
466
+ for (let i = 0; !found && i < path.length - 1; i++) {
467
+ const pathParent = path.slice(0, i + 1).join('/');
468
+ if (localState.pendingChanges[pathParent]?.v) {
469
+ found = true;
470
+ const pathChild = path.slice(i + 1);
471
+ const pathTypesChild = pathTypes.slice(i + 1);
472
+ setAtPath(
473
+ localState.pendingChanges[pathParent].v,
474
+ pathChild,
475
+ pathTypesChild,
476
+ valueAtPath,
477
+ );
478
+ }
479
+ }
480
+ if (!found) {
481
+ // If an existing pending change is deeper than this change, just delete it
482
+ // in favor of this wider change
483
+ for (const key in localState.pendingChanges) {
484
+ if (key !== pathStr && key.startsWith(pathStr)) {
485
+ delete localState.pendingChanges[key];
486
+ }
487
+ }
488
+ // The "p" saved in pending should be the previous state before changes,
489
+ // so don't overwrite it if it already exists
490
+ if (!localState.pendingChanges[pathStr]) {
491
+ localState.pendingChanges[pathStr] = { p: prevAtPath ?? null, t: pathTypes };
492
+ }
493
+
494
+ // Pending value is the untransformed value because it gets loaded without transformment
495
+ // and forwarded through to onObsChange where it gets transformed before save
496
+ localState.pendingChanges[pathStr].v = valueAtPath;
497
+ }
498
+
499
+ // Prepare the remote change with the transformed path/value
500
+ changesRemote.push({
501
+ path: pathTransformed,
502
+ pathTypes,
503
+ prevAtPath,
504
+ valueAtPath: valueTransformed,
505
+ pathStr,
506
+ });
507
+ }
508
+ }),
509
+ );
510
+ }
511
+ }
512
+ }
513
+
514
+ // If there's any transform promises, wait for them before saving
515
+ promisesTransform = promisesTransform.filter(Boolean);
516
+ if (promisesTransform.length > 0) {
517
+ await Promise.all(promisesTransform);
518
+ }
519
+
520
+ return { queuedChange, changesRemote };
521
+ }
522
+ }
523
+
524
+ async function doChangeLocal(changeInfo: PreppedChangeLocal | undefined) {
525
+ if (!changeInfo) return;
526
+
527
+ const { queuedChange, changesLocal, saveRemote } = changeInfo;
528
+ const { obs, syncState, localState, persistOptions } = queuedChange;
529
+ const { persistenceLocal } = localState;
530
+
531
+ const local = persistOptions.local;
532
+ const { table, config: configLocal } = parseLocalConfig(local!);
533
+ const configRemote = persistOptions.remote;
534
+ const shouldSaveMetadata = local && configRemote?.offlineBehavior === 'retry';
535
+
536
+ if (saveRemote && shouldSaveMetadata) {
537
+ // First save pending changes before saving local or remote
538
+ await updateMetadataImmediate(obs, localState, syncState, persistOptions, {
539
+ pending: localState.pendingChanges,
540
+ });
541
+ }
542
+
543
+ if (changesLocal.length > 0) {
544
+ // Save the changes to local persistence before saving to remote. They are already marked as pending so
545
+ // if remote sync fails or the app is closed before remote sync, it will attempt to sync them on the next load.
546
+ let promiseSet = persistenceLocal!.set(table, changesLocal, configLocal);
547
+
548
+ if (promiseSet) {
549
+ promiseSet = promiseSet.then(() => {
550
+ promisesLocalSaves.delete(promiseSet as Promise<any>);
551
+ });
552
+ // Keep track of local save promises so that updateMetadata runs only after everything is saved
553
+ promisesLocalSaves.add(promiseSet);
554
+
555
+ // await the local save before proceeding to save remotely
556
+ await promiseSet;
557
+ }
558
+ }
559
+ }
560
+ async function doChangeRemote(changeInfo: PreppedChangeRemote | undefined) {
561
+ if (!changeInfo) return;
562
+
563
+ const { queuedChange, changesRemote } = changeInfo;
564
+ const { obs, syncState, localState, persistOptions } = queuedChange;
565
+ const { persistenceLocal, persistenceRemote } = localState;
566
+
567
+ const local = persistOptions.local;
568
+ const { table, config: configLocal } = parseLocalConfig(local!);
569
+ const { offlineBehavior, allowSetIfError, onBeforeSet, onSetError, waitForSet, onAfterSet } =
570
+ persistOptions.remote || ({} as LegacyPersistOptionsRemote);
571
+ const shouldSaveMetadata = local && offlineBehavior === 'retry';
572
+
573
+ if (changesRemote.length > 0) {
574
+ // Wait for remote to be ready before saving
575
+ await when(() => syncState.isLoaded.get() || (allowSetIfError && syncState.error.get()));
576
+
577
+ if (waitForSet) {
578
+ const waitFor = isFunction(waitForSet)
579
+ ? waitForSet({ changes: changesRemote, value: obs.peek() })
580
+ : waitForSet;
581
+ if (waitFor) {
582
+ await when(waitFor);
583
+ }
584
+ }
585
+
586
+ const value = obs.peek();
587
+
588
+ onBeforeSet?.();
589
+
590
+ localState.numSavesOutstanding = (localState.numSavesOutstanding || 0) + 1;
591
+
592
+ let savedPromise = persistenceRemote!.set!({
593
+ obs,
594
+ syncState: syncState,
595
+ options: persistOptions,
596
+ changes: changesRemote,
597
+ value,
598
+ });
599
+ if (isPromise(savedPromise)) {
600
+ savedPromise = savedPromise.catch((err) => onSetError?.(err));
601
+ }
602
+
603
+ const saved = await savedPromise;
604
+
605
+ localState.numSavesOutstanding--;
606
+
607
+ // If this remote save changed anything then update persistence and metadata
608
+ // Because save happens after a timeout and they're batched together, some calls to save will
609
+ // return saved data and others won't, so those can be ignored.
610
+ if (saved) {
611
+ const pathStrs = Array.from(new Set(changesRemote.map((change) => change.pathStr)));
612
+ const { changes, lastSync } = saved;
613
+ if (pathStrs.length > 0) {
614
+ if (local) {
615
+ const metadata: PersistMetadata = {};
616
+ const pending = persistenceLocal!.getMetadata(table, configLocal)?.pending;
617
+ let transformedChanges: object | undefined = undefined;
618
+
619
+ for (let i = 0; i < pathStrs.length; i++) {
620
+ const pathStr = pathStrs[i];
621
+ // Clear pending for this path
622
+ if (pending?.[pathStr]) {
623
+ // Remove pending from local state
624
+ delete pending[pathStr];
625
+ metadata.pending = pending;
626
+ }
627
+ }
628
+
629
+ if (lastSync) {
630
+ metadata.lastSync = lastSync;
631
+ }
632
+
633
+ // Remote can optionally have data that needs to be merged back into the observable,
634
+ // for example Firebase may update dateModified with the server timestamp
635
+ if (changes && !isEmpty(changes)) {
636
+ transformedChanges = transformLoadData(changes, persistOptions.remote!, false);
637
+ }
638
+
639
+ if (localState.numSavesOutstanding > 0) {
640
+ if (transformedChanges) {
641
+ if (!localState.pendingSaveResults) {
642
+ localState.pendingSaveResults = [];
643
+ }
644
+ localState.pendingSaveResults.push(transformedChanges);
645
+ }
646
+ } else {
647
+ let allChanges = [...(localState.pendingSaveResults || []), transformedChanges];
648
+ if (allChanges.length > 0) {
649
+ if (allChanges.some((change) => isPromise(change))) {
650
+ allChanges = await Promise.all(allChanges);
651
+ }
652
+ onChangeRemote(() => mergeIntoObservable(obs, ...allChanges));
653
+ }
654
+
655
+ if (shouldSaveMetadata && !isEmpty(metadata)) {
656
+ updateMetadata(obs, localState, syncState, persistOptions, metadata);
657
+ }
658
+
659
+ localState.pendingSaveResults = [];
660
+ }
661
+ }
662
+ onAfterSet?.();
663
+ }
664
+ }
665
+ }
666
+ }
667
+
668
+ function onObsChange<T>(
669
+ obs: Observable<T>,
670
+ syncState: ObservableObject<ObservablePersistState>,
671
+ localState: LocalState,
672
+ persistOptions: LegacyPersistOptions<T>,
673
+ { changes, loading, remote }: ListenerParams,
674
+ ) {
675
+ if (!loading) {
676
+ const inRemoteChange = remote;
677
+ const isApplyingPending = localState.isApplyingPending;
678
+ // Queue changes in a microtask so that multiple changes within a frame get run together
679
+ _queuedChanges.push({
680
+ obs: obs as Observable<any>,
681
+ syncState,
682
+ localState,
683
+ persistOptions,
684
+ changes,
685
+ inRemoteChange,
686
+ isApplyingPending: isApplyingPending!,
687
+ });
688
+ if (_queuedChanges.length === 1) {
689
+ queueMicrotask(processQueuedChanges);
690
+ }
691
+ }
692
+ }
693
+
694
+ async function loadLocal<T>(
695
+ obs: ObservableParam<T>,
696
+ persistOptions: LegacyPersistOptions<any>,
697
+ syncState: ObservableObject<ObservablePersistState>,
698
+ localState: LocalState,
699
+ ) {
700
+ const { local } = persistOptions;
701
+ const localPersistence: ClassConstructor<ObservablePersistLocal> =
702
+ persistOptions.pluginLocal! || observablePersistConfiguration.pluginLocal;
703
+
704
+ if (local) {
705
+ const { table, config } = parseLocalConfig(local);
706
+
707
+ if (!localPersistence) {
708
+ throw new Error('Local persistence is not configured');
709
+ }
710
+ // Ensure there's only one instance of the persistence plugin
711
+ if (!mapPersistences.has(localPersistence)) {
712
+ const persistenceLocal = new localPersistence();
713
+ const mapValue = { persist: persistenceLocal, initialized: observable(false) };
714
+ mapPersistences.set(localPersistence, mapValue);
715
+ if (persistenceLocal.initialize) {
716
+ const initializePromise = persistenceLocal.initialize?.(
717
+ observablePersistConfiguration.localOptions || {},
718
+ );
719
+ if (isPromise(initializePromise)) {
720
+ await initializePromise;
721
+ }
722
+ }
723
+ mapValue.initialized.set(true);
724
+ }
725
+
726
+ const { persist: persistenceLocal, initialized } = mapPersistences.get(localPersistence) as {
727
+ persist: ObservablePersistLocal;
728
+ initialized: Observable<boolean>;
729
+ };
730
+
731
+ localState.persistenceLocal = persistenceLocal;
732
+
733
+ if (!initialized.peek()) {
734
+ await when(initialized);
735
+ }
736
+
737
+ // If persistence has an asynchronous load, wait for it
738
+ if (persistenceLocal.loadTable) {
739
+ const promise = persistenceLocal.loadTable(table, config);
740
+ if (promise) {
741
+ await promise;
742
+ }
743
+ }
744
+
745
+ // Get the value from state
746
+ let value = persistenceLocal.getTable(table, config);
747
+ const metadata = persistenceLocal.getMetadata(table, config);
748
+
749
+ if (metadata) {
750
+ // @ts-expect-error Migration from old version
751
+ if (!metadata.lastSync && metadata.modified) {
752
+ // @ts-expect-error Migration from old
753
+ metadata.lastSync = metadata.modified;
754
+ }
755
+ metadatas.set(obs, metadata);
756
+ localState.pendingChanges = metadata.pending;
757
+ // TODOV3 Remove dateModified
758
+ syncState.assign({
759
+ dateModified: metadata.lastSync,
760
+ lastSync: metadata.lastSync,
761
+ });
762
+ }
763
+
764
+ // Merge the data from local persistence into the default state
765
+ if (value !== undefined) {
766
+ const { transform, fieldTransforms } = config;
767
+
768
+ value = transformLoadData(value, { transform, fieldTransforms }, true);
769
+
770
+ if (isPromise(value)) {
771
+ value = await value;
772
+ }
773
+
774
+ // isLoadingLocal prevents saving remotely when two different persistences
775
+ // are set on the same observable
776
+ internal.globalState.isLoadingLocal = true;
777
+
778
+ // We want to merge the local data on top of any initial state the object is created with
779
+ const prevValue = obs.peek();
780
+ if (value === null && (!prevValue || (prevValue as any)[symbolLinked])) {
781
+ obs.set(value);
782
+ } else {
783
+ mergeIntoObservable(obs, value);
784
+ }
785
+
786
+ internal.globalState.isLoadingLocal = false;
787
+ }
788
+
789
+ const node = getNode(obs);
790
+
791
+ (node.state as unknown as Observable<ObservablePersistState>).peek().clearLocal = () =>
792
+ Promise.all([
793
+ persistenceLocal.deleteTable(table, config),
794
+ persistenceLocal.deleteMetadata(table, config),
795
+ ]) as unknown as Promise<void>;
796
+ }
797
+ syncState.isLoadedLocal.set(true);
798
+ }
799
+
800
+ export function persistObservable<T>(
801
+ observable: ObservableParam<T>,
802
+ persistOptions: LegacyPersistOptions<T>,
803
+ ): Observable<T>;
804
+ export function persistObservable<T>(
805
+ initial: T | (() => T) | (() => Promise<T>),
806
+ persistOptions: LegacyPersistOptions<T>,
807
+ ): Observable<T>;
808
+ export function persistObservable<T>(
809
+ initialOrObservable: ObservableParam<T> | T | (() => T) | (() => Promise<T>),
810
+ persistOptions: LegacyPersistOptions<T>,
811
+ ): Observable<T> {
812
+ const obs$ = (
813
+ isObservable(initialOrObservable)
814
+ ? initialOrObservable
815
+ : observable(isFunction(initialOrObservable) ? initialOrObservable() : initialOrObservable)
816
+ ) as Observable<any>;
817
+ const node = getNode(obs$);
818
+
819
+ // Merge remote persist options with global options
820
+ if (persistOptions.remote) {
821
+ persistOptions.remote = Object.assign(
822
+ {},
823
+ observablePersistConfiguration.remoteOptions,
824
+ removeNullUndefined(persistOptions.remote),
825
+ );
826
+ }
827
+ let { remote } = persistOptions as { remote: LegacyPersistOptionsRemote<T> };
828
+ const { local } = persistOptions;
829
+ const remotePersistence = persistOptions.pluginRemote! || observablePersistConfiguration?.pluginRemote;
830
+ const localState: LocalState = {};
831
+ let sync: () => Promise<void>;
832
+
833
+ const syncState = (node.state = observable<ObservablePersistState>({
834
+ isLoadedLocal: false,
835
+ isLoaded: false,
836
+ isEnabledLocal: true,
837
+ isEnabledRemote: true,
838
+ clearLocal: undefined as unknown as () => Promise<void>,
839
+ sync: () => Promise.resolve(),
840
+ getPendingChanges: () => localState.pendingChanges,
841
+ }) as any);
842
+
843
+ loadLocal(obs$, persistOptions, syncState, localState);
844
+
845
+ if (remote || remotePersistence) {
846
+ if (!remotePersistence) {
847
+ throw new Error('Remote persistence is not configured');
848
+ }
849
+ if (!remote) {
850
+ remote = {};
851
+ }
852
+ if (isObject(remotePersistence)) {
853
+ localState.persistenceRemote = observablePersistRemoteFunctionsAdapter(
854
+ remotePersistence as ObservablePersistRemoteFunctions<T>,
855
+ );
856
+ } else {
857
+ // Ensure there's only one instance of the persistence plugin
858
+ if (!mapPersistences.has(remotePersistence)) {
859
+ mapPersistences.set(remotePersistence, {
860
+ persist: new (remotePersistence as ClassConstructor<ObservablePersistRemoteClass, any[]>)(),
861
+ });
862
+ }
863
+ localState.persistenceRemote = mapPersistences.get(remotePersistence)!
864
+ .persist as ObservablePersistRemoteClass;
865
+ }
866
+
867
+ let isSynced = false;
868
+ sync = async () => {
869
+ const lastSync = metadatas.get(obs$)?.lastSync;
870
+ const pending = localState.pendingChanges;
871
+ const get = localState.persistenceRemote!.get?.bind(localState.persistenceRemote);
872
+
873
+ if (get) {
874
+ const runGet = () => {
875
+ get({
876
+ state: syncState,
877
+ obs: obs$,
878
+ options: persistOptions as LegacyPersistOptions<any>,
879
+ lastSync,
880
+ dateModified: lastSync,
881
+ onError: (error: Error) => {
882
+ remote.onGetError?.(error);
883
+ },
884
+ onGet: () => {
885
+ node.state!.assign({
886
+ isLoaded: true,
887
+ error: undefined,
888
+ });
889
+ },
890
+ onChange: async ({ value, path = [], pathTypes = [], mode = 'set', lastSync }) => {
891
+ // Note: value is the constructed value, path is used for setInObservableAtPath
892
+ // to start the set into the observable from the path
893
+ if (value !== undefined) {
894
+ value = transformLoadData(value, remote, true);
895
+ if (isPromise(value)) {
896
+ value = await (value as Promise<T>);
897
+ }
898
+
899
+ const invertedMap = remote.fieldTransforms && invertFieldMap(remote.fieldTransforms);
900
+
901
+ if (path.length && invertedMap) {
902
+ path = transformPath(path as string[], pathTypes, invertedMap);
903
+ }
904
+
905
+ if ((mode as any) === 'lastSync' || (mode as any) === 'dateModified') {
906
+ if (lastSync && !isEmpty(value as unknown as object)) {
907
+ onChangeRemote(() => {
908
+ setInObservableAtPath(obs$, path as string[], pathTypes, value, 'assign');
909
+ });
910
+ }
911
+ } else {
912
+ const pending = localState.pendingChanges;
913
+ if (pending) {
914
+ Object.keys(pending).forEach((key) => {
915
+ const p = key.split('/').filter((p) => p !== '');
916
+ const { v, t } = pending[key];
917
+
918
+ if (t.length === 0 || !value) {
919
+ value = v;
920
+ } else if ((value as any)[p[0]] !== undefined) {
921
+ (value as any) = setAtPath(
922
+ value as any,
923
+ p,
924
+ t,
925
+ v,
926
+ obs$.peek(),
927
+ (path: string[], value: any) => {
928
+ delete pending[key];
929
+ pending[path.join('/')] = {
930
+ p: null,
931
+ v: value,
932
+ t: t.slice(0, path.length),
933
+ };
934
+ },
935
+ );
936
+ }
937
+ });
938
+ }
939
+
940
+ onChangeRemote(() => {
941
+ setInObservableAtPath(
942
+ obs$,
943
+ path as string[],
944
+ pathTypes,
945
+ value,
946
+ mode as 'assign' | 'set',
947
+ );
948
+ });
949
+ }
950
+ }
951
+ if (lastSync && local) {
952
+ updateMetadata(obs$, localState, syncState, persistOptions as LegacyPersistOptions<T>, {
953
+ lastSync,
954
+ });
955
+ }
956
+ },
957
+ });
958
+ };
959
+ runGet();
960
+ } else {
961
+ node.state!.assign({
962
+ isLoaded: true,
963
+ error: undefined,
964
+ });
965
+ }
966
+ if (!isSynced) {
967
+ isSynced = true;
968
+ // Wait for remote to be ready before saving pending
969
+ await when(() => syncState.isLoaded.get() || (remote.allowSetIfError && syncState.error.get()));
970
+
971
+ if (pending && !isEmpty(pending)) {
972
+ localState.isApplyingPending = true;
973
+ const keys = Object.keys(pending);
974
+
975
+ // Bundle up all the changes from pending
976
+ const changes: Change[] = [];
977
+ for (let i = 0; i < keys.length; i++) {
978
+ const key = keys[i];
979
+ const path = key.split('/').filter((p) => p !== '');
980
+ const { p, v, t } = pending[key];
981
+ changes.push({ path, valueAtPath: v, prevAtPath: p, pathTypes: t });
982
+ }
983
+
984
+ // Send the changes into onObsChange so that they get persisted remotely
985
+ // TODO: Not sure why this needs to as unknown as Observable
986
+ onObsChange(obs$ as unknown as Observable, syncState, localState, persistOptions, {
987
+ value: obs$.peek(),
988
+ loading: false,
989
+ remote: false,
990
+ // TODO getPrevious if any remote persistence layers need it
991
+ getPrevious: () => undefined,
992
+ changes,
993
+ });
994
+ localState.isApplyingPending = false;
995
+ }
996
+ }
997
+ };
998
+
999
+ syncState.assign({ sync });
1000
+ }
1001
+
1002
+ // Wait for this node and all parent nodes up the hierarchy to be loaded
1003
+ const onAllLoadedLocal = () => {
1004
+ let parentNode: NodeValue | undefined = node;
1005
+ while (parentNode) {
1006
+ if (
1007
+ (parentNode.state as unknown as ObservableObject<ObservablePersistState>)?.isLoadedLocal?.get() ===
1008
+ false
1009
+ ) {
1010
+ return false;
1011
+ }
1012
+ parentNode = parentNode.parent;
1013
+ }
1014
+ return true;
1015
+ };
1016
+ // When all is loaded locally we can start syncing and listening for changes
1017
+ when(onAllLoadedLocal, function (this: any) {
1018
+ // If remote is not manual, then sync() is called automatically
1019
+ if (remote && !remote.manual) {
1020
+ sync();
1021
+ }
1022
+
1023
+ obs$.onChange(
1024
+ onObsChange.bind(this, obs$ as any, syncState, localState, persistOptions as LegacyPersistOptions<any>),
1025
+ );
1026
+ });
1027
+
1028
+ return obs$ as any;
1029
+ }