@legendapp/state 2.2.0-next.8 → 2.2.0-next.80

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 (321) 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 +34 -32
  14. package/config/enableReactTracking.js.map +1 -1
  15. package/config/enableReactTracking.mjs +35 -33
  16. package/config/enableReactTracking.mjs.map +1 -1
  17. package/config/enableReactUse.d.ts +1 -1
  18. package/config/enableReactUse.js +9 -1
  19. package/config/enableReactUse.js.map +1 -1
  20. package/config/enableReactUse.mjs +9 -1
  21. package/config/enableReactUse.mjs.map +1 -1
  22. package/config/enable_peek.d.ts +8 -0
  23. package/config/{enableDirectPeek.js → enable_peek.js} +6 -3
  24. package/config/enable_peek.js.map +1 -0
  25. package/config/{enableDirectPeek.mjs → enable_peek.mjs} +5 -3
  26. package/config/enable_peek.mjs.map +1 -0
  27. package/helpers/fetch.d.ts +4 -3
  28. package/helpers/fetch.js.map +1 -1
  29. package/helpers/fetch.mjs.map +1 -1
  30. package/helpers/pageHash.js.map +1 -1
  31. package/helpers/pageHash.mjs.map +1 -1
  32. package/helpers/pageHashParams.js.map +1 -1
  33. package/helpers/pageHashParams.mjs.map +1 -1
  34. package/helpers/time.d.ts +2 -2
  35. package/helpers/time.js.map +1 -1
  36. package/helpers/time.mjs.map +1 -1
  37. package/history.js +2 -2
  38. package/history.js.map +1 -1
  39. package/history.mjs +3 -3
  40. package/history.mjs.map +1 -1
  41. package/index.d.ts +29 -9
  42. package/index.js +964 -671
  43. package/index.js.map +1 -1
  44. package/index.mjs +959 -668
  45. package/index.mjs.map +1 -1
  46. package/package.json +37 -25
  47. package/persist-plugins/async-storage.d.ts +4 -3
  48. package/persist-plugins/async-storage.js +8 -7
  49. package/persist-plugins/async-storage.js.map +1 -1
  50. package/persist-plugins/async-storage.mjs +9 -8
  51. package/persist-plugins/async-storage.mjs.map +1 -1
  52. package/persist-plugins/fetch.d.ts +1 -1
  53. package/persist-plugins/fetch.js.map +1 -1
  54. package/persist-plugins/fetch.mjs.map +1 -1
  55. package/persist-plugins/firebase.d.ts +2 -2
  56. package/persist-plugins/firebase.js +12 -11
  57. package/persist-plugins/firebase.js.map +1 -1
  58. package/persist-plugins/firebase.mjs +13 -12
  59. package/persist-plugins/firebase.mjs.map +1 -1
  60. package/persist-plugins/indexeddb.d.ts +11 -10
  61. package/persist-plugins/indexeddb.js +2 -2
  62. package/persist-plugins/indexeddb.js.map +1 -1
  63. package/persist-plugins/indexeddb.mjs +2 -2
  64. package/persist-plugins/indexeddb.mjs.map +1 -1
  65. package/persist-plugins/local-storage.d.ts +4 -4
  66. package/persist-plugins/local-storage.js +19 -7
  67. package/persist-plugins/local-storage.js.map +1 -1
  68. package/persist-plugins/local-storage.mjs +20 -9
  69. package/persist-plugins/local-storage.mjs.map +1 -1
  70. package/persist-plugins/mmkv.d.ts +9 -8
  71. package/persist-plugins/mmkv.js +5 -4
  72. package/persist-plugins/mmkv.js.map +1 -1
  73. package/persist-plugins/mmkv.mjs +6 -5
  74. package/persist-plugins/mmkv.mjs.map +1 -1
  75. package/persist-plugins/query.d.ts +1 -1
  76. package/persist-plugins/query.js.map +1 -1
  77. package/persist-plugins/query.mjs.map +1 -1
  78. package/persist.d.ts +2 -14
  79. package/persist.js +1270 -269
  80. package/persist.js.map +1 -1
  81. package/persist.mjs +1270 -270
  82. package/persist.mjs.map +1 -1
  83. package/react-hooks/createObservableHook.js +1 -1
  84. package/react-hooks/createObservableHook.js.map +1 -1
  85. package/react-hooks/createObservableHook.mjs +1 -1
  86. package/react-hooks/createObservableHook.mjs.map +1 -1
  87. package/react-hooks/useFetch.d.ts +4 -3
  88. package/react-hooks/useFetch.js.map +1 -1
  89. package/react-hooks/useFetch.mjs.map +1 -1
  90. package/react-hooks/useHover.js.map +1 -1
  91. package/react-hooks/useHover.mjs.map +1 -1
  92. package/react-hooks/useMeasure.js.map +1 -1
  93. package/react-hooks/useMeasure.mjs.map +1 -1
  94. package/react-hooks/useObservableNextRouter.js.map +1 -1
  95. package/react-hooks/useObservableNextRouter.mjs.map +1 -1
  96. package/react-hooks/useObservableQuery.js.map +1 -1
  97. package/react-hooks/useObservableQuery.mjs.map +1 -1
  98. package/react-hooks/usePersistedObservable.d.ts +6 -3
  99. package/react-hooks/usePersistedObservable.js +5 -2
  100. package/react-hooks/usePersistedObservable.js.map +1 -1
  101. package/react-hooks/usePersistedObservable.mjs +5 -2
  102. package/react-hooks/usePersistedObservable.mjs.map +1 -1
  103. package/react.js +73 -93
  104. package/react.js.map +1 -1
  105. package/react.mjs +73 -93
  106. package/react.mjs.map +1 -1
  107. package/src/ObservableObject.ts +1217 -0
  108. package/src/ObservablePrimitive.ts +62 -0
  109. package/src/babel/index.ts +70 -0
  110. package/src/batching.ts +378 -0
  111. package/src/computed.ts +18 -0
  112. package/src/config/enable$get.ts +30 -0
  113. package/src/config/enableReactComponents.ts +26 -0
  114. package/src/config/enableReactNativeComponents.ts +102 -0
  115. package/src/config/enableReactTracking.ts +62 -0
  116. package/src/config/enableReactUse.ts +32 -0
  117. package/src/config/enable_peek.ts +31 -0
  118. package/src/config.ts +47 -0
  119. package/src/createObservable.ts +46 -0
  120. package/src/event.ts +26 -0
  121. package/src/globals.ts +234 -0
  122. package/src/helpers/fetch.ts +26 -0
  123. package/src/helpers/pageHash.ts +41 -0
  124. package/src/helpers/pageHashParams.ts +55 -0
  125. package/src/helpers/time.ts +30 -0
  126. package/src/helpers.ts +224 -0
  127. package/src/history/trackHistory.ts +29 -0
  128. package/src/history/undoRedo.ts +111 -0
  129. package/src/is.ts +63 -0
  130. package/src/linked.ts +6 -0
  131. package/src/observable.ts +32 -0
  132. package/src/observableInterfaces.ts +148 -0
  133. package/src/observableTypes.ts +226 -0
  134. package/src/observe.ts +89 -0
  135. package/src/onChange.ts +136 -0
  136. package/src/persist/configureObservablePersistence.ts +7 -0
  137. package/src/persist/fieldTransformer.ts +149 -0
  138. package/src/persist/observablePersistRemoteFunctionsAdapter.ts +39 -0
  139. package/src/persist/persistObservable.ts +1031 -0
  140. package/src/persist-plugins/async-storage.ts +102 -0
  141. package/src/persist-plugins/fetch.ts +34 -0
  142. package/src/persist-plugins/firebase.ts +1052 -0
  143. package/src/persist-plugins/indexeddb.ts +432 -0
  144. package/src/persist-plugins/local-storage.ts +91 -0
  145. package/src/persist-plugins/mmkv.ts +91 -0
  146. package/src/persist-plugins/query.ts +129 -0
  147. package/src/proxy.ts +28 -0
  148. package/src/react/Computed.tsx +7 -0
  149. package/src/react/For.tsx +116 -0
  150. package/src/react/Memo.tsx +4 -0
  151. package/src/react/Reactive.tsx +53 -0
  152. package/src/react/Show.tsx +33 -0
  153. package/src/react/Switch.tsx +43 -0
  154. package/src/react/react-globals.ts +3 -0
  155. package/src/react/{reactInterfaces.d.ts → reactInterfaces.ts} +15 -7
  156. package/src/react/reactive-observer.tsx +210 -0
  157. package/src/react/useComputed.ts +36 -0
  158. package/src/react/useEffectOnce.ts +41 -0
  159. package/src/react/useIsMounted.ts +16 -0
  160. package/src/react/useMount.ts +15 -0
  161. package/src/react/useObservable.ts +24 -0
  162. package/src/react/useObservableReducer.ts +52 -0
  163. package/src/react/useObservableState.ts +30 -0
  164. package/src/react/useObserve.ts +54 -0
  165. package/src/react/useObserveEffect.ts +40 -0
  166. package/src/react/usePauseProvider.tsx +13 -0
  167. package/src/react/useSelector.ts +167 -0
  168. package/src/react/useUnmount.ts +8 -0
  169. package/src/react/useWhen.ts +9 -0
  170. package/src/react-hooks/createObservableHook.ts +53 -0
  171. package/src/react-hooks/useFetch.ts +16 -0
  172. package/src/react-hooks/useHover.ts +40 -0
  173. package/src/react-hooks/useMeasure.ts +48 -0
  174. package/src/react-hooks/useObservableNextRouter.ts +137 -0
  175. package/src/react-hooks/useObservableQuery.ts +205 -0
  176. package/src/react-hooks/usePersistedObservable.ts +25 -0
  177. package/src/retry.ts +71 -0
  178. package/src/setupTracking.ts +26 -0
  179. package/src/sync/activateSyncedNode.ts +128 -0
  180. package/src/sync/configureObservableSync.ts +7 -0
  181. package/src/sync/persistTypes.ts +226 -0
  182. package/src/sync/syncHelpers.ts +56 -0
  183. package/src/sync/syncObservable.ts +1040 -0
  184. package/src/sync/syncObservableAdapter.ts +31 -0
  185. package/src/sync/syncTypes.ts +188 -0
  186. package/src/sync/synced.ts +20 -0
  187. package/src/sync-plugins/crud.ts +404 -0
  188. package/src/sync-plugins/fetch.ts +72 -0
  189. package/src/sync-plugins/keel.ts +452 -0
  190. package/src/sync-plugins/supabase.ts +261 -0
  191. package/src/trace/traceHelpers.ts +11 -0
  192. package/src/trace/useTraceListeners.ts +34 -0
  193. package/src/trace/useTraceUpdates.ts +24 -0
  194. package/src/trace/useVerifyNotTracking.ts +33 -0
  195. package/src/trace/useVerifyOneRender.ts +10 -0
  196. package/src/trackSelector.ts +52 -0
  197. package/src/tracking.ts +43 -0
  198. package/src/types/babel.d.ts +12 -0
  199. package/src/when.ts +75 -0
  200. package/sync-plugins/crud.d.ts +41 -0
  201. package/sync-plugins/crud.js +290 -0
  202. package/sync-plugins/crud.js.map +1 -0
  203. package/sync-plugins/crud.mjs +286 -0
  204. package/sync-plugins/crud.mjs.map +1 -0
  205. package/sync-plugins/fetch.d.ts +13 -0
  206. package/sync-plugins/fetch.js +46 -0
  207. package/sync-plugins/fetch.js.map +1 -0
  208. package/sync-plugins/fetch.mjs +44 -0
  209. package/sync-plugins/fetch.mjs.map +1 -0
  210. package/sync-plugins/keel.d.ts +91 -0
  211. package/sync-plugins/keel.js +277 -0
  212. package/sync-plugins/keel.js.map +1 -0
  213. package/sync-plugins/keel.mjs +273 -0
  214. package/sync-plugins/keel.mjs.map +1 -0
  215. package/sync-plugins/supabase.d.ts +36 -0
  216. package/sync-plugins/supabase.js +152 -0
  217. package/sync-plugins/supabase.js.map +1 -0
  218. package/sync-plugins/supabase.mjs +149 -0
  219. package/sync-plugins/supabase.mjs.map +1 -0
  220. package/sync.d.ts +11 -0
  221. package/sync.js +976 -0
  222. package/sync.js.map +1 -0
  223. package/sync.mjs +966 -0
  224. package/sync.mjs.map +1 -0
  225. package/trace.js +13 -10
  226. package/trace.js.map +1 -1
  227. package/trace.mjs +11 -8
  228. package/trace.mjs.map +1 -1
  229. package/types/babel.d.ts +3 -3
  230. package/config/enableDirectAccess.d.ts +0 -7
  231. package/config/enableDirectAccess.js +0 -25
  232. package/config/enableDirectAccess.js.map +0 -1
  233. package/config/enableDirectAccess.mjs +0 -23
  234. package/config/enableDirectAccess.mjs.map +0 -1
  235. package/config/enableDirectPeek.d.ts +0 -7
  236. package/config/enableDirectPeek.js.map +0 -1
  237. package/config/enableDirectPeek.mjs.map +0 -1
  238. package/config/enableReactDirectRender.d.ts +0 -2
  239. package/config/enableReactDirectRender.js +0 -78
  240. package/config/enableReactDirectRender.js.map +0 -1
  241. package/config/enableReactDirectRender.mjs +0 -75
  242. package/config/enableReactDirectRender.mjs.map +0 -1
  243. package/src/ObservableObject.d.ts +0 -14
  244. package/src/ObservablePrimitive.d.ts +0 -7
  245. package/src/babel/index.d.ts +0 -17
  246. package/src/batching.d.ts +0 -6
  247. package/src/computed.d.ts +0 -4
  248. package/src/config/enableDirectAccess.d.ts +0 -7
  249. package/src/config/enableDirectPeek.d.ts +0 -7
  250. package/src/config/enableReactComponents.d.ts +0 -7
  251. package/src/config/enableReactDirectRender.d.ts +0 -2
  252. package/src/config/enableReactNativeComponents.d.ts +0 -20
  253. package/src/config/enableReactTracking.d.ts +0 -15
  254. package/src/config/enableReactUse.d.ts +0 -7
  255. package/src/config.d.ts +0 -8
  256. package/src/createObservable.d.ts +0 -2
  257. package/src/event.d.ts +0 -2
  258. package/src/globals.d.ts +0 -32
  259. package/src/helpers/fetch.d.ts +0 -6
  260. package/src/helpers/pageHash.d.ts +0 -7
  261. package/src/helpers/pageHashParams.d.ts +0 -7
  262. package/src/helpers/time.d.ts +0 -3
  263. package/src/helpers.d.ts +0 -13
  264. package/src/history/trackHistory.d.ts +0 -4
  265. package/src/is.d.ts +0 -10
  266. package/src/observable.d.ts +0 -16
  267. package/src/observableInterfaces.d.ts +0 -458
  268. package/src/observe.d.ts +0 -6
  269. package/src/onChange.d.ts +0 -7
  270. package/src/persist/configureObservablePersistence.d.ts +0 -3
  271. package/src/persist/fieldTransformer.d.ts +0 -8
  272. package/src/persist/observablePersistRemoteFunctionsAdapter.d.ts +0 -2
  273. package/src/persist/persistActivateNode.d.ts +0 -1
  274. package/src/persist/persistHelpers.d.ts +0 -1
  275. package/src/persist/persistObservable.d.ts +0 -25
  276. package/src/persist-plugins/async-storage.d.ts +0 -14
  277. package/src/persist-plugins/fetch.d.ts +0 -10
  278. package/src/persist-plugins/firebase.d.ts +0 -51
  279. package/src/persist-plugins/indexeddb.d.ts +0 -25
  280. package/src/persist-plugins/local-storage.d.ts +0 -21
  281. package/src/persist-plugins/mmkv.d.ts +0 -14
  282. package/src/persist-plugins/query.d.ts +0 -18
  283. package/src/proxy.d.ts +0 -5
  284. package/src/react/Computed.d.ts +0 -5
  285. package/src/react/For.d.ts +0 -15
  286. package/src/react/Memo.d.ts +0 -3
  287. package/src/react/Reactive.d.ts +0 -9
  288. package/src/react/Show.d.ts +0 -18
  289. package/src/react/Switch.d.ts +0 -14
  290. package/src/react/react-globals.d.ts +0 -3
  291. package/src/react/reactive-observer.d.ts +0 -14
  292. package/src/react/useComputed.d.ts +0 -5
  293. package/src/react/useEffectOnce.d.ts +0 -1
  294. package/src/react/useIsMounted.d.ts +0 -2
  295. package/src/react/useMount.d.ts +0 -2
  296. package/src/react/useObservable.d.ts +0 -9
  297. package/src/react/useObservableReducer.d.ts +0 -7
  298. package/src/react/useObservableState.d.ts +0 -2
  299. package/src/react/useObserve.d.ts +0 -4
  300. package/src/react/useObserveEffect.d.ts +0 -4
  301. package/src/react/usePauseProvider.d.ts +0 -8
  302. package/src/react/useSelector.d.ts +0 -3
  303. package/src/react/useUnmount.d.ts +0 -2
  304. package/src/react/useWhen.d.ts +0 -3
  305. package/src/react-hooks/createObservableHook.d.ts +0 -2
  306. package/src/react-hooks/useFetch.d.ts +0 -6
  307. package/src/react-hooks/useHover.d.ts +0 -3
  308. package/src/react-hooks/useMeasure.d.ts +0 -6
  309. package/src/react-hooks/useObservableNextRouter.d.ts +0 -33
  310. package/src/react-hooks/useObservableQuery.d.ts +0 -6
  311. package/src/react-hooks/usePersistedObservable.d.ts +0 -11
  312. package/src/retry.d.ts +0 -9
  313. package/src/setupTracking.d.ts +0 -2
  314. package/src/trace/traceHelpers.d.ts +0 -2
  315. package/src/trace/useTraceListeners.d.ts +0 -1
  316. package/src/trace/useTraceUpdates.d.ts +0 -1
  317. package/src/trace/useVerifyNotTracking.d.ts +0 -1
  318. package/src/trace/useVerifyOneRender.d.ts +0 -1
  319. package/src/trackSelector.d.ts +0 -7
  320. package/src/tracking.d.ts +0 -13
  321. package/src/when.d.ts +0 -3
@@ -0,0 +1,1052 @@
1
+ import {
2
+ Observable,
3
+ ObservableParam,
4
+ ObservablePrimitive,
5
+ TypeAtPath,
6
+ batch,
7
+ constructObjectWithPath,
8
+ deconstructObjectWithPath,
9
+ hasOwnProperty,
10
+ internal,
11
+ isArray,
12
+ isFunction,
13
+ isObject,
14
+ mergeIntoObservable,
15
+ observable,
16
+ observablePrimitive,
17
+ setAtPath,
18
+ when,
19
+ whenReady,
20
+ } from '@legendapp/state';
21
+ import { internal as internalPersist, transformObject, transformPath } from '@legendapp/state/persist';
22
+ import {
23
+ LegacyPersistOptions,
24
+ ObservablePersistRemoteClass,
25
+ ObservablePersistRemoteGetParams,
26
+ ObservablePersistRemoteSetParams,
27
+ QueryByModified,
28
+ } from '@legendapp/state/sync';
29
+ import { getAuth, type User } from 'firebase/auth';
30
+ import type { DataSnapshot } from 'firebase/database';
31
+ import {
32
+ DatabaseReference,
33
+ Unsubscribe,
34
+ getDatabase,
35
+ onChildAdded,
36
+ onChildChanged,
37
+ onValue,
38
+ orderByChild,
39
+ query,
40
+ ref,
41
+ serverTimestamp,
42
+ startAt,
43
+ update,
44
+ } from 'firebase/database';
45
+ const { symbolDelete, getPathType, clone } = internal;
46
+ const { observablePersistConfiguration } = internalPersist;
47
+
48
+ function getDateModifiedKey(dateModifiedKey: string | undefined) {
49
+ return dateModifiedKey || observablePersistConfiguration.remoteOptions?.dateModifiedKey || '@';
50
+ }
51
+
52
+ interface FirebaseFns {
53
+ isInitialized: () => boolean;
54
+ getCurrentUser: () => string | undefined;
55
+ ref: (path: string) => DatabaseReference;
56
+ orderByChild: (ref: any, child: string, startAt: number) => any;
57
+ once: (query: any, callback: (snapshot: DataSnapshot) => unknown, onError: (error: Error) => void) => () => void;
58
+ onChildAdded: (
59
+ query: any,
60
+ callback: (snapshot: DataSnapshot) => unknown,
61
+ cancelCallback?: (error: Error) => unknown,
62
+ ) => () => void;
63
+ onChildChanged: (
64
+ query: any,
65
+ callback: (snapshot: DataSnapshot) => unknown,
66
+ cancelCallback?: (error: Error) => unknown,
67
+ ) => () => void;
68
+ serverTimestamp: () => any;
69
+ update: (object: object) => Promise<void>;
70
+ onAuthStateChanged: (cb: (user: User | null) => void) => void;
71
+ }
72
+
73
+ type LocalState<T> = { changes: object | T; timeout?: any };
74
+
75
+ const symbolSaveValue = Symbol('___obsSaveValue');
76
+
77
+ interface SaveInfo {
78
+ [symbolSaveValue]: any;
79
+ adjusted?: boolean;
80
+ }
81
+
82
+ type SaveInfoDictionary<T = any> = {
83
+ [K in keyof T]: SaveInfo | SaveInfoDictionary<T[K]>;
84
+ };
85
+
86
+ interface PendingSaves {
87
+ options: LegacyPersistOptions;
88
+ saves: SaveInfoDictionary;
89
+ }
90
+
91
+ interface SaveState {
92
+ timeout?: any;
93
+ pendingSaves: Map<string, PendingSaves>;
94
+ savingSaves?: Map<string, PendingSaves>;
95
+ eventSaved?: ObservablePrimitive<true | Error | undefined>;
96
+ numSavesPending: Observable<number>;
97
+ pendingSaveResults: Map<
98
+ string,
99
+ {
100
+ saved: {
101
+ value: any;
102
+ path: string[];
103
+ pathTypes: TypeAtPath[];
104
+ dateModified: number | undefined;
105
+ dateModifiedKey: string | undefined;
106
+ dateModifiedKeyOption: string | undefined;
107
+ onChange: ObservablePersistRemoteGetParams<any>['onChange'];
108
+ }[];
109
+ }
110
+ >;
111
+ }
112
+
113
+ interface LoadStatus {
114
+ startedLoading: boolean;
115
+ numLoading: number;
116
+ numWaitingCanSave: number;
117
+ }
118
+
119
+ class ObservablePersistFirebaseBase implements ObservablePersistRemoteClass {
120
+ protected _batch: Record<string, any> = {};
121
+ protected fns: FirebaseFns;
122
+ private _pathsLoadStatus = observable<Record<string, LoadStatus>>({});
123
+ private debounceSet;
124
+ private user: Observable<string | undefined | null>;
125
+ private listenErrors: Map<
126
+ any,
127
+ {
128
+ params: ObservablePersistRemoteGetParams<any>;
129
+ path: string[];
130
+ pathTypes: TypeAtPath[];
131
+ dateModified: number | undefined;
132
+ queryByModified: QueryByModified<any> | undefined;
133
+ unsubscribes: (() => void)[];
134
+ retry: number;
135
+ saveState: SaveState;
136
+ onLoadParams: { waiting: number; onLoad: () => void };
137
+ status$: Observable<LoadStatus>;
138
+ }
139
+ > = new Map();
140
+ private saveStates = new Map<ObservableParam<any>, SaveState>();
141
+
142
+ constructor(fns: FirebaseFns) {
143
+ this.fns = fns;
144
+ this.user = observablePrimitive();
145
+ this.debounceSet = observablePersistConfiguration?.remoteOptions?.debounceSet ?? 500;
146
+
147
+ if (this.fns.isInitialized()) {
148
+ this.fns.onAuthStateChanged((user) => {
149
+ this.user.set(user?.uid);
150
+ });
151
+ } else if (
152
+ process.env.NODE_ENV === 'development' &&
153
+ (typeof window !== 'undefined' || (typeof navigator !== 'undefined' && navigator.product === 'ReactNative'))
154
+ ) {
155
+ // Warn only in web or react-native. If running on a server this shouldn't work.
156
+ console.warn('[legend-state] Firebase is not initialized. Remote persistence will not work.');
157
+ }
158
+ }
159
+ public async get<T>(params: ObservablePersistRemoteGetParams<T>) {
160
+ const { obs, options } = params;
161
+ const { remote } = options;
162
+ if (!remote || !remote.firebase) {
163
+ // If the plugin is set globally but it has no firebase options this plugin can't do anything
164
+ return;
165
+ }
166
+ const {
167
+ firebase: { refPath },
168
+ waitForGet,
169
+ } = remote;
170
+
171
+ const { requireAuth, queryByModified } = options.remote!.firebase!;
172
+
173
+ // If requireAuth wait for user to be signed in
174
+ if (requireAuth) {
175
+ await whenReady(this.user);
176
+ }
177
+
178
+ // If waitForGet wait for it
179
+ if (waitForGet) {
180
+ await whenReady(waitForGet);
181
+ }
182
+
183
+ const saveState: SaveState = {
184
+ pendingSaveResults: new Map(),
185
+ pendingSaves: new Map(),
186
+ numSavesPending: observable(0),
187
+ };
188
+ this.saveStates.set(obs, saveState);
189
+
190
+ const pathFirebase = refPath(this.fns.getCurrentUser());
191
+
192
+ const status$ = this._pathsLoadStatus[pathFirebase];
193
+ status$.set({
194
+ startedLoading: false,
195
+ numLoading: 0,
196
+ numWaitingCanSave: 0,
197
+ });
198
+
199
+ const onLoadParams = {
200
+ waiting: 0,
201
+ onLoad: () => {
202
+ onLoadParams.waiting--;
203
+ if (onLoadParams.waiting === 0) {
204
+ params.onGet();
205
+ }
206
+ },
207
+ };
208
+
209
+ if (isObject(queryByModified)) {
210
+ this.iterateListen(obs, params, saveState, [], [], queryByModified, onLoadParams, status$);
211
+ } else {
212
+ const dateModified = queryByModified === true ? params.dateModified! : undefined;
213
+
214
+ this._listen(obs, params, saveState, [], [], queryByModified, dateModified, onLoadParams, status$);
215
+ }
216
+ }
217
+ private iterateListen<T>(
218
+ obs: ObservableParam<any>,
219
+ params: ObservablePersistRemoteGetParams<T>,
220
+ saveState: SaveState,
221
+ path: string[],
222
+ pathTypes: TypeAtPath[],
223
+ queryByModified: QueryByModified<any>,
224
+ onLoadParams: { waiting: number; onLoad: () => void },
225
+ status$: Observable<LoadStatus>,
226
+ ) {
227
+ const { options } = params;
228
+
229
+ const { ignoreKeys } = options.remote!.firebase!;
230
+ Object.keys(obs).forEach((key) => {
231
+ if (!ignoreKeys || !ignoreKeys.includes(key)) {
232
+ const o = (obs as any)[key] as ObservableParam<any>;
233
+ const q =
234
+ queryByModified[key as keyof typeof queryByModified] || (queryByModified as { '*': boolean })['*'];
235
+ const pathChild = path.concat(key);
236
+ const pathTypesChild = pathTypes.concat(getPathType(o.peek()));
237
+ let dateModified: number | undefined = undefined;
238
+
239
+ if (isObject(q)) {
240
+ this.iterateListen(o, params, saveState, pathChild, pathTypesChild, q, onLoadParams, status$);
241
+ } else {
242
+ if (q === true || q === '*') {
243
+ dateModified = params.dateModified!;
244
+ }
245
+
246
+ this._listen(
247
+ o,
248
+ params,
249
+ saveState,
250
+ pathChild,
251
+ pathTypesChild,
252
+ queryByModified,
253
+ dateModified,
254
+ onLoadParams,
255
+ status$,
256
+ );
257
+ }
258
+ }
259
+ });
260
+ }
261
+ private retryListens() {
262
+ // If a listen failed but save succeeded, the save should have fixed
263
+ // the permission problem so try again
264
+ this.listenErrors.forEach((listenError) => {
265
+ const {
266
+ params,
267
+ path,
268
+ pathTypes,
269
+ dateModified,
270
+ queryByModified,
271
+ unsubscribes,
272
+ saveState,
273
+ onLoadParams,
274
+ status$,
275
+ } = listenError;
276
+ listenError.retry++;
277
+ if (listenError.retry < 10) {
278
+ unsubscribes.forEach((cb) => cb());
279
+ this._listen(
280
+ params.obs,
281
+ params,
282
+ saveState,
283
+ path,
284
+ pathTypes,
285
+ queryByModified,
286
+ dateModified,
287
+ onLoadParams,
288
+ status$,
289
+ );
290
+ } else {
291
+ this.listenErrors.delete(listenError);
292
+ }
293
+ });
294
+ }
295
+ private async _listen<T>(
296
+ obs: ObservableParam<any>,
297
+ params: ObservablePersistRemoteGetParams<T>,
298
+ saveState: SaveState,
299
+ path: string[],
300
+ pathTypes: TypeAtPath[],
301
+ queryByModified: QueryByModified<any> | undefined,
302
+ dateModified: number | undefined,
303
+ onLoadParams: { waiting: number; onLoad: () => void },
304
+ status$: Observable<LoadStatus>,
305
+ ) {
306
+ const { options, onError } = params;
307
+ const { fieldTransforms, allowSetIfError, firebase, dateModifiedKey: dateModifiedKeyOption } = options.remote!;
308
+ const { refPath, query, mode } = firebase!;
309
+
310
+ let didError = false;
311
+ const dateModifiedKey = getDateModifiedKey(dateModifiedKeyOption);
312
+
313
+ const originalPath = path;
314
+ if (fieldTransforms && path.length) {
315
+ path = transformPath(path, pathTypes, fieldTransforms);
316
+ }
317
+
318
+ const pathFirebase = refPath(this.fns.getCurrentUser()) + path.join('/');
319
+
320
+ let ref = this.fns.ref(pathFirebase);
321
+ if (query) {
322
+ ref = query(ref) as DatabaseReference;
323
+ }
324
+ if (dateModified && !isNaN(dateModified)) {
325
+ ref = this.fns.orderByChild(ref, dateModifiedKey, dateModified + 1);
326
+ }
327
+
328
+ const unsubscribes: (() => void)[] = [];
329
+
330
+ status$.numLoading.set((v) => v + 1);
331
+ status$.numWaitingCanSave.set((v) => v + 1);
332
+
333
+ const _onError = (err: Error) => {
334
+ if (!didError) {
335
+ didError = true;
336
+ const existing = this.listenErrors.get(obs);
337
+ if (existing) {
338
+ existing.retry++;
339
+ } else {
340
+ this.listenErrors.set(obs, {
341
+ params,
342
+ path: originalPath,
343
+ pathTypes,
344
+ dateModified,
345
+ queryByModified,
346
+ unsubscribes,
347
+ retry: 0,
348
+ saveState,
349
+ onLoadParams,
350
+ status$,
351
+ });
352
+ params.state.error.set(err);
353
+ onError?.(err);
354
+ if (allowSetIfError) {
355
+ status$.numWaitingCanSave.set((v) => v - 1);
356
+ }
357
+ }
358
+ }
359
+ };
360
+
361
+ if (mode !== 'once') {
362
+ const localState: LocalState<T> = { changes: {} as T };
363
+ const cb = this._onChange.bind(
364
+ this,
365
+ path,
366
+ pathTypes,
367
+ pathFirebase,
368
+ dateModifiedKey,
369
+ dateModifiedKeyOption,
370
+ params as ObservablePersistRemoteGetParams<any>,
371
+ localState,
372
+ saveState,
373
+ status$,
374
+ );
375
+ unsubscribes.push(this.fns.onChildAdded(ref, cb));
376
+ unsubscribes.push(this.fns.onChildChanged(ref, cb));
377
+ }
378
+
379
+ onLoadParams.waiting++;
380
+
381
+ unsubscribes.push(
382
+ this.fns.once(
383
+ ref,
384
+ this._onceValue.bind(
385
+ this,
386
+ path,
387
+ pathTypes,
388
+ pathFirebase,
389
+ dateModifiedKey,
390
+ dateModifiedKeyOption,
391
+ queryByModified,
392
+ onLoadParams.onLoad,
393
+ params as ObservablePersistRemoteGetParams<any>,
394
+ status$,
395
+ ),
396
+ _onError,
397
+ ),
398
+ );
399
+ }
400
+ private _updatePendingSave(path: string[], value: object, pending: SaveInfoDictionary) {
401
+ if (path.length === 0) {
402
+ pending[symbolSaveValue as any] = value as any;
403
+ } else if (pending[symbolSaveValue as any]) {
404
+ pending[symbolSaveValue as any] = mergeIntoObservable(pending[symbolSaveValue as any], value);
405
+ } else {
406
+ const p = path[0];
407
+ const v = (value as any)[p];
408
+ const pendingChild = pending[p] as any;
409
+
410
+ // If already have a save info here then don't need to go deeper on the path. Just overwrite the value.
411
+ if (pendingChild && pendingChild[symbolSaveValue] !== undefined) {
412
+ const pendingSaveValue = pendingChild[symbolSaveValue];
413
+ pendingChild[symbolSaveValue] =
414
+ isArray(pendingSaveValue) || isObject(pendingSaveValue)
415
+ ? mergeIntoObservable(pendingSaveValue, v)
416
+ : v;
417
+ } else {
418
+ // 1. If nothing here
419
+ // 2. If other strings here
420
+ if (!pending[p]) {
421
+ pending[p] = {};
422
+ }
423
+ if (path.length > 1) {
424
+ this._updatePendingSave(path.slice(1), v, pending[p] as SaveInfoDictionary);
425
+ } else {
426
+ pending[p] = { [symbolSaveValue]: v };
427
+ }
428
+ }
429
+ }
430
+ }
431
+ public async set<T>({ options, changes, obs }: ObservablePersistRemoteSetParams<T>): Promise<
432
+ | {
433
+ changes?: object;
434
+ dateModified?: number;
435
+ pathStrs?: string[];
436
+ }
437
+ | undefined
438
+ > {
439
+ const { remote } = options;
440
+ // If the plugin is set globally but it has no firebase options this plugin can't do anything
441
+ if (!remote || !remote.firebase) {
442
+ return;
443
+ }
444
+ const { waitForSet, debounceSet: debounceSet, log, firebase } = remote;
445
+
446
+ const { requireAuth, refPath: refPathFn } = firebase;
447
+
448
+ if (requireAuth) {
449
+ await whenReady(this.user);
450
+ }
451
+
452
+ const refPath = refPathFn(this.fns.getCurrentUser());
453
+
454
+ const status$ = this._pathsLoadStatus[refPath];
455
+ if (status$.numWaitingCanSave.peek() > 0) {
456
+ // Wait for all listened paths to load before we can save
457
+ await when(() => status$.numWaitingCanSave.get() < 1);
458
+ }
459
+
460
+ if (waitForSet) {
461
+ const waitFor = isFunction(waitForSet) ? waitForSet({ changes, value: obs.peek() }) : waitForSet;
462
+ if (waitFor) {
463
+ await when(waitFor);
464
+ }
465
+ }
466
+
467
+ const saveState = this.saveStates.get(obs)!;
468
+
469
+ // Don't start a save until all outstanding saves are finished
470
+ await when(() => saveState.numSavesPending.get() === 0);
471
+
472
+ const { pendingSaveResults, pendingSaves } = saveState;
473
+
474
+ if (!pendingSaves.has(refPath)) {
475
+ pendingSaves.set(refPath, { options, saves: {} });
476
+ pendingSaveResults.set(refPath, { saved: [] });
477
+ }
478
+ const pending = pendingSaves.get(refPath)!.saves;
479
+
480
+ log?.('verbose', 'Saving', changes);
481
+
482
+ for (let i = 0; i < changes.length; i++) {
483
+ let { valueAtPath } = changes[i];
484
+ const { pathTypes, path } = changes[i];
485
+ if (valueAtPath === undefined) {
486
+ valueAtPath = null;
487
+ }
488
+
489
+ const value = constructObjectWithPath(path as string[], pathTypes, clone(valueAtPath)) as unknown as T;
490
+ const pathCloned = path.slice() as string[];
491
+
492
+ this._updatePendingSave(pathCloned, value as unknown as object, pending);
493
+ }
494
+
495
+ if (!saveState.eventSaved) {
496
+ saveState.eventSaved = observablePrimitive();
497
+ }
498
+ // Keep the current eventSaved. This will get reassigned once the timeout activates.
499
+ const eventSaved = saveState.eventSaved;
500
+
501
+ const timeout = debounceSet ?? this.debounceSet;
502
+
503
+ if (timeout) {
504
+ if (saveState.timeout) {
505
+ clearTimeout(saveState.timeout);
506
+ }
507
+ saveState.timeout = setTimeout(this._onTimeoutSave.bind(this, saveState), timeout);
508
+ } else {
509
+ this._onTimeoutSave(saveState);
510
+ }
511
+
512
+ const savedOrError = await when(eventSaved);
513
+
514
+ if (savedOrError === true) {
515
+ this.retryListens();
516
+
517
+ const saveResults = pendingSaveResults.get(refPath);
518
+
519
+ if (saveResults) {
520
+ const { saved } = saveResults;
521
+ if (saved?.length) {
522
+ // Only want to return from saved one time
523
+ if (saveState.numSavesPending.get() === 0) {
524
+ pendingSaveResults.delete(refPath);
525
+ } else {
526
+ saveResults.saved = [];
527
+ }
528
+ let maxModified = 0;
529
+
530
+ // Compile a changes object of all the dateModified
531
+ const changesOut = {};
532
+ for (let i = 0; i < saved.length; i++) {
533
+ const { dateModified, path, pathTypes, dateModifiedKeyOption, dateModifiedKey, value } =
534
+ saved[i];
535
+ if (dateModified) {
536
+ maxModified = Math.max(dateModified, maxModified);
537
+ if (dateModifiedKeyOption) {
538
+ const deconstructed = deconstructObjectWithPath(path, pathTypes, value);
539
+ // Don't resurrect deleted items
540
+ if (deconstructed !== (symbolDelete as any)) {
541
+ Object.assign(
542
+ changesOut,
543
+ constructObjectWithPath(path, pathTypes, {
544
+ [dateModifiedKey!]: dateModified,
545
+ }),
546
+ );
547
+ }
548
+ }
549
+ }
550
+ }
551
+
552
+ const ret = {
553
+ changes: changesOut,
554
+ dateModified: maxModified || undefined,
555
+ };
556
+
557
+ log?.('verbose', 'Saved', changes, ret);
558
+
559
+ return ret;
560
+ }
561
+ }
562
+ } else {
563
+ throw savedOrError;
564
+ }
565
+
566
+ return {};
567
+ }
568
+ private _constructBatch(
569
+ options: LegacyPersistOptions,
570
+ batch: Record<string, string | object>,
571
+ basePath: string,
572
+ saves: SaveInfoDictionary,
573
+ ...path: string[]
574
+ ) {
575
+ const { fieldTransforms, dateModifiedKey: dateModifiedKeyOption } = options.remote!;
576
+ const dateModifiedKey = getDateModifiedKey(dateModifiedKeyOption);
577
+
578
+ let valSave = saves[symbolSaveValue as any];
579
+ if (valSave !== undefined) {
580
+ let queryByModified = options.remote!.firebase!.queryByModified;
581
+ if (queryByModified) {
582
+ if (queryByModified !== true && fieldTransforms) {
583
+ queryByModified = transformObject(queryByModified, fieldTransforms);
584
+ }
585
+ valSave = this.insertDatesToSave(batch, queryByModified!, dateModifiedKey, basePath, path, valSave);
586
+ }
587
+
588
+ const pathThis = basePath + path.join('/');
589
+ if (pathThis && !batch[pathThis]) {
590
+ batch[pathThis] = valSave;
591
+ }
592
+ } else {
593
+ Object.keys(saves).forEach((key) => {
594
+ this._constructBatch(options, batch, basePath, saves[key] as any, ...path, key);
595
+ });
596
+ }
597
+ }
598
+ private _constructBatchesForSave(pendingSaves: Map<string, PendingSaves>) {
599
+ const batches: object[] = [];
600
+ pendingSaves.forEach(({ options, saves }) => {
601
+ const basePath = options.remote!.firebase!.refPath(this.fns.getCurrentUser());
602
+ const batch = {};
603
+ this._constructBatch(options, batch, basePath, saves);
604
+ batches.push(batch);
605
+ });
606
+
607
+ return batches;
608
+ }
609
+ private async _onTimeoutSave(saveState: SaveState) {
610
+ const { pendingSaves, eventSaved } = saveState;
611
+
612
+ saveState.timeout = undefined;
613
+ saveState.eventSaved = undefined;
614
+ saveState.numSavesPending.set((v) => v + 1);
615
+
616
+ if (pendingSaves.size > 0) {
617
+ const batches = clone(this._constructBatchesForSave(pendingSaves)) as Record<string, any>[];
618
+
619
+ saveState.savingSaves = pendingSaves;
620
+
621
+ // Clear the pendingSaves so that the next batch starts from scratch
622
+ saveState.pendingSaves = new Map();
623
+
624
+ if (batches.length > 0) {
625
+ const promises: Promise<{ didSave?: boolean; error?: any }>[] = [];
626
+ for (let i = 0; i < batches.length; i++) {
627
+ const batch = batches[i];
628
+ promises.push(this._saveBatch(batch));
629
+ }
630
+
631
+ const results = await Promise.all(promises);
632
+ const errors = results.filter((result) => result.error);
633
+ if (errors.length === 0) {
634
+ saveState.numSavesPending.set((v) => v - 1);
635
+ eventSaved?.set(true);
636
+ } else {
637
+ eventSaved?.set(errors[0].error);
638
+ }
639
+ }
640
+ }
641
+ }
642
+ private async _saveBatch(batch: Record<string, any>): Promise<any> {
643
+ const length = JSON.stringify(batch).length;
644
+
645
+ let error: Error | undefined = undefined;
646
+ // Firebase has a maximum limit of 16MB per save so we constrain our saves to
647
+ // less than 12 to be safe
648
+ if (length > 12e6) {
649
+ const parts = splitLargeObject(batch, 6e6);
650
+ let didSave = true;
651
+
652
+ // TODO: Option for logging
653
+ for (let i = 0; i < parts.length; i++) {
654
+ const ret = await this._saveBatch(parts[i]);
655
+ if (ret.error) {
656
+ error = ret.error;
657
+ } else {
658
+ didSave = didSave && ret.didSave;
659
+ }
660
+ }
661
+ return error ? { error } : { didSave };
662
+ } else {
663
+ for (let i = 0; i < 3; i++) {
664
+ try {
665
+ await this.fns.update(batch);
666
+ return { didSave: true };
667
+ } catch (err) {
668
+ error = err as Error;
669
+
670
+ await new Promise<void>((resolve) => setTimeout(resolve, 500));
671
+ }
672
+ }
673
+
674
+ return { error };
675
+ }
676
+ }
677
+ private _convertFBTimestamps(obj: any, dateModifiedKey: string, dateModifiedKeyOption: string) {
678
+ let value = obj;
679
+ // Database value can be either { @: number, _: object } or { @: number, ...rest }
680
+ // where @ is the dateModifiedKey
681
+ let dateModified = value[dateModifiedKey];
682
+ if (dateModified) {
683
+ // If user doesn't request a dateModifiedKey then delete it
684
+ if (value._ !== undefined) {
685
+ value = value._;
686
+ } else if (dateModified && Object.keys(value).length < 2) {
687
+ value = symbolDelete;
688
+ }
689
+
690
+ if (!dateModifiedKeyOption) {
691
+ delete value[dateModifiedKey];
692
+ }
693
+ }
694
+
695
+ if (isObject(value)) {
696
+ Object.keys(value).forEach((k) => {
697
+ const val = value[k];
698
+ if (val !== undefined) {
699
+ if (isObject(val) || isArray(val)) {
700
+ const { value: valueChild, dateModified: dateModifiedChild } = this._convertFBTimestamps(
701
+ val,
702
+ dateModifiedKey,
703
+ dateModifiedKeyOption,
704
+ );
705
+ if (dateModifiedChild) {
706
+ dateModified = Math.max(dateModified || 0, dateModifiedChild);
707
+ }
708
+ if (valueChild !== val) {
709
+ value[k] = valueChild;
710
+ }
711
+ }
712
+ }
713
+ });
714
+ }
715
+
716
+ return { value, dateModified };
717
+ }
718
+ private async _onceValue<T>(
719
+ path: string[],
720
+ pathTypes: TypeAtPath[],
721
+ pathFirebase: string,
722
+ dateModifiedKey: string | undefined,
723
+ dateModifiedKeyOption: string | undefined,
724
+ queryByModified: QueryByModified<any> | undefined,
725
+ onLoad: () => void,
726
+ params: ObservablePersistRemoteGetParams<T>,
727
+ status$: Observable<LoadStatus>,
728
+ snapshot: DataSnapshot,
729
+ ) {
730
+ const { onChange } = params;
731
+ const outerValue = snapshot.val();
732
+
733
+ // If this path previously errored, clear the error state
734
+ const obs = params.obs;
735
+ params.state.error.delete();
736
+ this.listenErrors.delete(obs);
737
+
738
+ status$.startedLoading.set(true);
739
+ if (outerValue && isObject(outerValue)) {
740
+ let value;
741
+ let dateModified;
742
+ if (queryByModified) {
743
+ const converted = this._convertFBTimestamps(outerValue, dateModifiedKey!, dateModifiedKeyOption!);
744
+ value = converted.value;
745
+ dateModified = converted.dateModified;
746
+ } else {
747
+ value = outerValue;
748
+ }
749
+
750
+ value = constructObjectWithPath(path, pathTypes, value);
751
+
752
+ const onChangePromise = onChange({
753
+ value,
754
+ path,
755
+ pathTypes,
756
+ mode: queryByModified ? 'assign' : 'set',
757
+ dateModified,
758
+ });
759
+ if (onChangePromise) {
760
+ await onChangePromise;
761
+ }
762
+ }
763
+ onLoad();
764
+ batch(() => {
765
+ status$.numLoading.set((v) => v - 1);
766
+ status$.numWaitingCanSave.set((v) => v - 1);
767
+ });
768
+ }
769
+ private async _onChange<T>(
770
+ path: string[],
771
+ pathTypes: TypeAtPath[],
772
+ pathFirebase: string,
773
+ dateModifiedKey: string | undefined,
774
+ dateModifiedKeyOption: string | undefined,
775
+ params: ObservablePersistRemoteGetParams<T>,
776
+ localState: LocalState<T>,
777
+ saveState: SaveState,
778
+ status$: Observable<LoadStatus>,
779
+ snapshot: DataSnapshot,
780
+ ) {
781
+ const { numLoading, startedLoading } = status$.peek();
782
+
783
+ if (numLoading > 0) {
784
+ // If onceValue has not been called yet, then skip onChange because it will come later
785
+ if (!startedLoading) return;
786
+
787
+ // Wait for load
788
+ await when(() => status$.numLoading.get() < 1);
789
+ }
790
+
791
+ const {
792
+ onChange,
793
+ state,
794
+ options: { remote },
795
+ } = params;
796
+
797
+ const { changeTimeout } = remote!;
798
+
799
+ // Skip changes if disabled
800
+ if (state.isEnabledRemote.peek() === false) return;
801
+
802
+ const key = snapshot.key!;
803
+ const val = snapshot.val();
804
+
805
+ if (val) {
806
+ // eslint-disable-next-line prefer-const
807
+ let { value, dateModified } = this._convertFBTimestamps(val, dateModifiedKey!, dateModifiedKeyOption!);
808
+
809
+ const pathChild = path.concat(key);
810
+ const pathTypesChild = pathTypes.concat('object');
811
+ const constructed = constructObjectWithPath(pathChild, pathTypes, value);
812
+
813
+ if (
814
+ !this.addValuesToPendingSaves(
815
+ pathFirebase,
816
+ constructed,
817
+ pathChild,
818
+ pathTypesChild,
819
+ dateModified,
820
+ dateModifiedKey,
821
+ dateModifiedKeyOption,
822
+ saveState,
823
+ onChange,
824
+ )
825
+ ) {
826
+ localState.changes = setAtPath(localState.changes as object, pathChild, pathTypes, value);
827
+
828
+ // Debounce many child changes into a single onChange
829
+ clearTimeout(localState.timeout);
830
+ localState.timeout = setTimeout(() => {
831
+ const changes = localState.changes;
832
+ localState.changes = {};
833
+ onChange({ value: changes as T, path, pathTypes, mode: 'assign', dateModified });
834
+ }, changeTimeout || 300);
835
+ }
836
+ }
837
+ }
838
+ private insertDateToObject(value: any, dateModifiedKey: string) {
839
+ const timestamp = this.fns.serverTimestamp();
840
+ if (isObject(value)) {
841
+ return Object.assign(value, {
842
+ [dateModifiedKey]: timestamp,
843
+ });
844
+ } else {
845
+ return {
846
+ [dateModifiedKey]: timestamp,
847
+ _: value,
848
+ };
849
+ }
850
+ }
851
+ private insertDatesToSaveObject(
852
+ batch: Record<string, string | object>,
853
+ queryByModified: QueryByModified<any>,
854
+ dateModifiedKey: string,
855
+ path: string,
856
+ value: any,
857
+ ): object {
858
+ if (queryByModified === true) {
859
+ value = this.insertDateToObject(value, dateModifiedKey);
860
+ } else if (isObject(value)) {
861
+ Object.keys(value).forEach((key) => {
862
+ value[key] = this.insertDatesToSaveObject(
863
+ batch,
864
+ (queryByModified as any)[key],
865
+ dateModifiedKey,
866
+ path + '/' + key,
867
+ value[key],
868
+ );
869
+ });
870
+ }
871
+ return value;
872
+ }
873
+ private insertDatesToSave(
874
+ batch: Record<string, string | object>,
875
+ queryByModified: QueryByModified<any>,
876
+ dateModifiedKey: string,
877
+ basePath: string,
878
+ path: string[],
879
+ value: any,
880
+ ) {
881
+ let o = queryByModified;
882
+ for (let i = 0; i < path.length; i++) {
883
+ if (o === true) {
884
+ const pathThis = basePath + path.slice(0, i + 1).join('/');
885
+ if (i === path.length - 1) {
886
+ if (!isObject(value)) {
887
+ return this.insertDateToObject(value, dateModifiedKey);
888
+ } else {
889
+ if (isObject(value)) {
890
+ value[dateModifiedKey] = this.fns.serverTimestamp();
891
+ } else {
892
+ batch[pathThis + '/' + dateModifiedKey] = this.fns.serverTimestamp();
893
+ }
894
+ }
895
+ } else {
896
+ batch[pathThis + '/' + dateModifiedKey] = this.fns.serverTimestamp();
897
+ }
898
+ return value;
899
+ } else if (isObject(o)) {
900
+ o = (o as any)[path[i]];
901
+ }
902
+ }
903
+
904
+ if (o === true && isObject(value)) {
905
+ Object.keys(value).forEach((key) => {
906
+ this.insertDatesToSaveObject(
907
+ batch,
908
+ o,
909
+ dateModifiedKey,
910
+ basePath + path.join('/') + '/' + key,
911
+ value[key],
912
+ );
913
+ });
914
+ } else if (o !== undefined) {
915
+ this.insertDatesToSaveObject(batch, o, dateModifiedKey, basePath + path.join('/'), value);
916
+ }
917
+
918
+ return value;
919
+ }
920
+ private addValuesToPendingSaves(
921
+ refPath: string,
922
+ value: object,
923
+ pathChild: string[],
924
+ pathTypesChild: TypeAtPath[],
925
+ dateModified: number | undefined,
926
+ dateModifiedKey: string | undefined,
927
+ dateModifiedKeyOption: string | undefined,
928
+ saveState: SaveState,
929
+ onChange: ObservablePersistRemoteGetParams<any>['onChange'],
930
+ ) {
931
+ const { pendingSaveResults, savingSaves } = saveState;
932
+ let found = false;
933
+ const pathArr = refPath.split('/');
934
+ for (let i = pathArr.length - 1; !found && i >= 0; i--) {
935
+ const p = pathArr[i];
936
+ if (p === '') continue;
937
+
938
+ const path = pathArr.slice(0, i + 1).join('/') + '/';
939
+
940
+ // Look for this saved key in the currently saving saves.
941
+ // If it's being saved locally this must be the remote onChange
942
+ // coming in for this save.
943
+ if (pendingSaveResults.has(path) && savingSaves?.has(path)) {
944
+ found = true;
945
+ if (pathChild.length > 0) {
946
+ const savingSave = savingSaves.get(path)!;
947
+ const save = savingSave.saves[pathChild[0]];
948
+ if (!save) {
949
+ found = false;
950
+ }
951
+ }
952
+
953
+ if (found) {
954
+ const pending = pendingSaveResults.get(path)!;
955
+ pending.saved.push({
956
+ value,
957
+ dateModified,
958
+ path: pathChild,
959
+ pathTypes: pathTypesChild,
960
+ dateModifiedKey,
961
+ dateModifiedKeyOption,
962
+ onChange,
963
+ });
964
+ }
965
+ }
966
+ value = { [p]: value };
967
+ }
968
+ return found;
969
+ }
970
+ }
971
+
972
+ function estimateSize(value: any): number {
973
+ return ('' + value).length + 2; // Convert to string and account for quotes in JSON.
974
+ }
975
+
976
+ function splitLargeObject(obj: Record<string, any>, limit: number): Record<string, any>[] {
977
+ const parts: Record<string, any>[] = [{}];
978
+ let sizeCount = 0;
979
+
980
+ function recursiveSplit(innerObj: Record<string, any>, path: string[] = []) {
981
+ for (const key in innerObj) {
982
+ if (!hasOwnProperty.call(innerObj, key)) {
983
+ continue;
984
+ }
985
+
986
+ const newPath = [...path, key];
987
+ const keySize = key.length + 4; // Account for quotes and colon in JSON.
988
+ const val = innerObj[key];
989
+
990
+ let itemSize = 0;
991
+ if (val && typeof val === 'object') {
992
+ itemSize = JSON.stringify(val).length;
993
+ } else {
994
+ itemSize = estimateSize(val);
995
+ }
996
+
997
+ if (val && typeof val === 'object' && itemSize > limit) {
998
+ recursiveSplit(val, newPath);
999
+ } else {
1000
+ // Check if the size of the current item exceeds the limit
1001
+ if (sizeCount > 0 && sizeCount + keySize + itemSize > limit) {
1002
+ parts.push({});
1003
+ sizeCount = 0;
1004
+ }
1005
+
1006
+ const pathKey = newPath.join('/');
1007
+ parts[parts.length - 1][pathKey] = val;
1008
+ sizeCount += keySize + itemSize;
1009
+ }
1010
+ }
1011
+ }
1012
+
1013
+ recursiveSplit(obj);
1014
+ return parts;
1015
+ }
1016
+
1017
+ // This is the web version of all the firebase functions. It passes them in as arguments so that it could
1018
+ // support firebase on other platforms.
1019
+ export class ObservablePersistFirebase extends ObservablePersistFirebaseBase {
1020
+ constructor() {
1021
+ super({
1022
+ isInitialized: () => {
1023
+ try {
1024
+ return !!getAuth().app;
1025
+ } catch {
1026
+ return false;
1027
+ }
1028
+ },
1029
+ getCurrentUser: () => getAuth().currentUser?.uid,
1030
+ ref: (path: string) => ref(getDatabase(), path),
1031
+ orderByChild: (ref: DatabaseReference, child: string, start: number) =>
1032
+ query(ref, orderByChild(child), startAt(start)),
1033
+ update: (object: object) => update(ref(getDatabase()), object),
1034
+ once: (ref: DatabaseReference, callback, callbackError) => {
1035
+ let unsubscribe: Unsubscribe | undefined;
1036
+ const cb = (snap: DataSnapshot) => {
1037
+ if (unsubscribe) {
1038
+ unsubscribe();
1039
+ unsubscribe = undefined;
1040
+ }
1041
+ callback(snap);
1042
+ };
1043
+ unsubscribe = onValue(ref, cb, callbackError);
1044
+ return unsubscribe;
1045
+ },
1046
+ onChildAdded,
1047
+ onChildChanged,
1048
+ serverTimestamp,
1049
+ onAuthStateChanged: (cb) => getAuth().onAuthStateChanged(cb),
1050
+ });
1051
+ }
1052
+ }