@legendapp/state 1.11.1 → 2.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. package/index.d.ts +4 -5
  2. package/index.js +261 -280
  3. package/index.js.map +1 -1
  4. package/index.mjs +261 -278
  5. package/index.mjs.map +1 -1
  6. package/package.json +21 -24
  7. package/persist-plugins/async-storage.d.ts +14 -0
  8. package/persist-plugins/async-storage.js +100 -0
  9. package/persist-plugins/async-storage.js.map +1 -0
  10. package/persist-plugins/async-storage.mjs +98 -0
  11. package/persist-plugins/async-storage.mjs.map +1 -0
  12. package/persist-plugins/fetch.d.ts +10 -0
  13. package/persist-plugins/fetch.js +22 -0
  14. package/persist-plugins/fetch.js.map +1 -0
  15. package/persist-plugins/fetch.mjs +20 -0
  16. package/persist-plugins/fetch.mjs.map +1 -0
  17. package/persist-plugins/firebase.d.ts +51 -0
  18. package/persist-plugins/firebase.js +692 -0
  19. package/persist-plugins/firebase.js.map +1 -0
  20. package/persist-plugins/firebase.mjs +690 -0
  21. package/persist-plugins/firebase.mjs.map +1 -0
  22. package/persist-plugins/indexeddb.d.ts +2 -3
  23. package/persist-plugins/indexeddb.js +1 -16
  24. package/persist-plugins/indexeddb.js.map +1 -1
  25. package/persist-plugins/indexeddb.mjs +1 -16
  26. package/persist-plugins/indexeddb.mjs.map +1 -1
  27. package/persist-plugins/local-storage.d.ts +1 -2
  28. package/persist-plugins/local-storage.js +1 -5
  29. package/persist-plugins/local-storage.js.map +1 -1
  30. package/persist-plugins/local-storage.mjs +1 -5
  31. package/persist-plugins/local-storage.mjs.map +1 -1
  32. package/persist-plugins/mmkv.d.ts +4 -4
  33. package/persist-plugins/mmkv.js +6 -4
  34. package/persist-plugins/mmkv.js.map +1 -1
  35. package/persist-plugins/mmkv.mjs +6 -4
  36. package/persist-plugins/mmkv.mjs.map +1 -1
  37. package/persist-plugins/query.d.ts +20 -0
  38. package/persist-plugins/query.js +89 -0
  39. package/persist-plugins/query.js.map +1 -0
  40. package/persist-plugins/query.mjs +87 -0
  41. package/persist-plugins/query.mjs.map +1 -0
  42. package/persist.js +170 -143
  43. package/persist.js.map +1 -1
  44. package/persist.mjs +171 -144
  45. package/persist.mjs.map +1 -1
  46. package/react-hooks/usePersistedObservable.d.ts +2 -2
  47. package/react-hooks/usePersistedObservable.js +1 -6
  48. package/react-hooks/usePersistedObservable.js.map +1 -1
  49. package/react-hooks/usePersistedObservable.mjs +1 -6
  50. package/react-hooks/usePersistedObservable.mjs.map +1 -1
  51. package/react.d.ts +1 -6
  52. package/react.js +47 -99
  53. package/react.js.map +1 -1
  54. package/react.mjs +47 -100
  55. package/react.mjs.map +1 -1
  56. package/src/ObservableObject.d.ts +5 -1
  57. package/src/batching.d.ts +0 -7
  58. package/src/globals.d.ts +2 -8
  59. package/src/is.d.ts +1 -0
  60. package/src/observable.d.ts +5 -3
  61. package/src/observableInterfaces.d.ts +94 -69
  62. package/src/observe.d.ts +1 -1
  63. package/src/persist/observablePersistRemoteFunctionsAdapter.d.ts +2 -0
  64. package/src/persist/persistObservable.d.ts +10 -13
  65. package/src/persist-plugins/async-storage.d.ts +14 -0
  66. package/src/persist-plugins/fetch.d.ts +10 -0
  67. package/src/persist-plugins/firebase.d.ts +51 -0
  68. package/src/persist-plugins/indexeddb.d.ts +2 -3
  69. package/src/persist-plugins/local-storage.d.ts +1 -2
  70. package/src/persist-plugins/mmkv.d.ts +4 -4
  71. package/src/persist-plugins/query.d.ts +20 -0
  72. package/src/react/For.d.ts +1 -2
  73. package/src/react/react-globals.d.ts +3 -0
  74. package/src/react/reactInterfaces.d.ts +1 -1
  75. package/src/react/reactive-observer.d.ts +1 -5
  76. package/src/react/useObservableState.d.ts +2 -0
  77. package/src/react/useSelector.d.ts +1 -1
  78. package/src/react/useWhen.d.ts +3 -0
  79. package/src/react-hooks/usePersistedObservable.d.ts +2 -2
  80. package/src/trackSelector.d.ts +1 -1
  81. package/src/tracking.d.ts +2 -3
  82. package/config/disableDeprecationWarnings.d.ts +0 -1
  83. package/config/disableDeprecationWarnings.js +0 -10
  84. package/config/disableDeprecationWarnings.js.map +0 -1
  85. package/config/disableDeprecationWarnings.mjs +0 -8
  86. package/config/disableDeprecationWarnings.mjs.map +0 -1
  87. package/config/enableReactDirectRender.d.ts +0 -7
  88. package/config/enableReactDirectRender.js +0 -77
  89. package/config/enableReactDirectRender.js.map +0 -1
  90. package/config/enableReactDirectRender.mjs +0 -74
  91. package/config/enableReactDirectRender.mjs.map +0 -1
  92. package/react-components.d.ts +0 -2
  93. package/react-components.js +0 -44
  94. package/react-components.js.map +0 -1
  95. package/react-components.mjs +0 -31
  96. package/react-components.mjs.map +0 -1
  97. package/react-native-components.d.ts +0 -2
  98. package/react-native-components.js +0 -67
  99. package/react-native-components.js.map +0 -1
  100. package/react-native-components.mjs +0 -54
  101. package/react-native-components.mjs.map +0 -1
  102. package/src/config/disableDeprecationWarnings.d.ts +0 -1
  103. package/src/config/enableReactDirectRender.d.ts +0 -7
  104. package/src/react/enableLegendStateReact.d.ts +0 -1
  105. package/src/react-components/react-components.d.ts +0 -7
  106. package/src/react-native-components/rn-components.d.ts +0 -21
  107. package/types.d.ts +0 -13
@@ -0,0 +1,690 @@
1
+ import { observable, observablePrimitive, whenReady, isObject, isArray, mergeIntoObservable, when, constructObjectWithPath, deconstructObjectWithPath, batch, setAtPath, internal, hasOwnProperty } from '@legendapp/state';
2
+ import { transformPath, transformObject, internal as internal$1 } from '@legendapp/state/persist';
3
+ import { getAuth } from 'firebase/auth';
4
+ import { ref, getDatabase, query, orderByChild, startAt, update, onValue, onChildAdded, onChildChanged, serverTimestamp } from 'firebase/database';
5
+
6
+ const { symbolDelete } = internal;
7
+ const { observablePersistConfiguration } = internal$1;
8
+ function clone(obj) {
9
+ return obj === undefined || obj === null ? obj : JSON.parse(JSON.stringify(obj));
10
+ }
11
+ function getDateModifiedKey(dateModifiedKey) {
12
+ var _a;
13
+ return dateModifiedKey || ((_a = observablePersistConfiguration.remoteOptions) === null || _a === void 0 ? void 0 : _a.dateModifiedKey) || '@';
14
+ }
15
+ const symbolSaveValue = Symbol('___obsSaveValue');
16
+ class ObservablePersistFirebaseBase {
17
+ constructor(fns) {
18
+ var _a, _b;
19
+ this._batch = {};
20
+ this._pathsLoadStatus = observable({});
21
+ this.listenErrors = new Map();
22
+ this.saveStates = new Map();
23
+ this.fns = fns;
24
+ this.user = observablePrimitive();
25
+ this.SaveTimeout = (_b = (_a = observablePersistConfiguration === null || observablePersistConfiguration === void 0 ? void 0 : observablePersistConfiguration.remoteOptions) === null || _a === void 0 ? void 0 : _a.saveTimeout) !== null && _b !== void 0 ? _b : 500;
26
+ if (this.fns.isInitialized()) {
27
+ this.fns.onAuthStateChanged((user) => {
28
+ this.user.set(user === null || user === void 0 ? void 0 : user.uid);
29
+ });
30
+ }
31
+ else if (process.env.NODE_ENV === 'development' &&
32
+ (typeof window !== 'undefined' || (typeof navigator !== 'undefined' && navigator.product === 'ReactNative'))) {
33
+ // Warn only in web or react-native. If running on a server this shouldn't work.
34
+ console.warn('[legend-state] Firebase is not initialized. Remote persistence will not work.');
35
+ }
36
+ }
37
+ async get(params) {
38
+ const { obs, options } = params;
39
+ const { remote } = options;
40
+ if (!remote || !remote.firebase) {
41
+ // If the plugin is set globally but it has no firebase options this plugin can't do anything
42
+ return;
43
+ }
44
+ const { firebase: { refPath }, waitForGet, } = remote;
45
+ const { requireAuth, queryByModified } = options.remote.firebase;
46
+ // If requireAuth wait for user to be signed in
47
+ if (requireAuth) {
48
+ await whenReady(this.user);
49
+ }
50
+ // If waitForGet wait for it
51
+ if (waitForGet) {
52
+ await whenReady(waitForGet);
53
+ }
54
+ const saveState = {
55
+ pendingSaveResults: new Map(),
56
+ pendingSaves: new Map(),
57
+ numSavesPending: 0,
58
+ };
59
+ this.saveStates.set(obs, saveState);
60
+ const pathFirebase = refPath(this.fns.getCurrentUser());
61
+ const status$ = this._pathsLoadStatus[pathFirebase].set({
62
+ startedLoading: false,
63
+ numLoading: 0,
64
+ numWaitingCanSave: 0,
65
+ });
66
+ const onLoadParams = {
67
+ waiting: 0,
68
+ onLoad: () => {
69
+ onLoadParams.waiting--;
70
+ if (onLoadParams.waiting === 0) {
71
+ params.onGet();
72
+ }
73
+ },
74
+ };
75
+ if (isObject(queryByModified)) {
76
+ this.iterateListen(obs, params, saveState, [], [], queryByModified, onLoadParams, status$);
77
+ }
78
+ else {
79
+ const dateModified = queryByModified === true ? params.dateModified : undefined;
80
+ this._listen(obs, params, saveState, [], [], queryByModified, dateModified, onLoadParams, status$);
81
+ }
82
+ }
83
+ iterateListen(obs, params, saveState, path, pathTypes, queryByModified, onLoadParams, status$) {
84
+ const { options } = params;
85
+ const { ignoreKeys } = options.remote.firebase;
86
+ Object.keys(obs).forEach((key) => {
87
+ if (!ignoreKeys || !ignoreKeys.includes(key)) {
88
+ const o = obs[key];
89
+ const q = queryByModified[key] || queryByModified['*'];
90
+ const pathChild = path.concat(key);
91
+ const pathTypesChild = pathTypes.concat(isArray(o.peek()) ? 'array' : 'object');
92
+ let dateModified = undefined;
93
+ if (isObject(q)) {
94
+ this.iterateListen(o, params, saveState, pathChild, pathTypesChild, q, onLoadParams, status$);
95
+ }
96
+ else {
97
+ if (q === true || q === '*') {
98
+ dateModified = params.dateModified;
99
+ }
100
+ this._listen(o, params, saveState, pathChild, pathTypesChild, queryByModified, dateModified, onLoadParams, status$);
101
+ }
102
+ }
103
+ });
104
+ }
105
+ retryListens() {
106
+ // If a listen failed but save succeeded, the save should have fixed
107
+ // the permission problem so try again
108
+ this.listenErrors.forEach((listenError) => {
109
+ const { params, path, pathTypes, dateModified, queryByModified, unsubscribes, saveState, onLoadParams, status$, } = listenError;
110
+ listenError.retry++;
111
+ if (listenError.retry < 10) {
112
+ unsubscribes.forEach((cb) => cb());
113
+ this._listen(params.obs, params, saveState, path, pathTypes, queryByModified, dateModified, onLoadParams, status$);
114
+ }
115
+ else {
116
+ this.listenErrors.delete(listenError);
117
+ }
118
+ });
119
+ }
120
+ async _listen(obs, params, saveState, path, pathTypes, queryByModified, dateModified, onLoadParams, status$) {
121
+ const { options } = params;
122
+ const { fieldTransforms, onGetError: onLoadError, allowSetIfError, firebase, dateModifiedKey: dateModifiedKeyOption, } = options.remote;
123
+ const { refPath, query, mode } = firebase;
124
+ let didError = false;
125
+ const dateModifiedKey = getDateModifiedKey(dateModifiedKeyOption);
126
+ const originalPath = path;
127
+ if (fieldTransforms && path.length) {
128
+ path = transformPath(path, pathTypes, fieldTransforms);
129
+ }
130
+ const pathFirebase = refPath(this.fns.getCurrentUser()) + path.join('/');
131
+ let ref = this.fns.ref(pathFirebase);
132
+ if (query) {
133
+ ref = query(ref);
134
+ }
135
+ if (dateModified && !isNaN(dateModified)) {
136
+ ref = this.fns.orderByChild(ref, dateModifiedKey, dateModified + 1);
137
+ }
138
+ const unsubscribes = [];
139
+ status$.numLoading.set((v) => v + 1);
140
+ status$.numWaitingCanSave.set((v) => v + 1);
141
+ const _onError = (err) => {
142
+ if (!didError) {
143
+ didError = true;
144
+ const existing = this.listenErrors.get(obs);
145
+ if (existing) {
146
+ existing.retry++;
147
+ }
148
+ else {
149
+ this.listenErrors.set(obs, {
150
+ params,
151
+ path: originalPath,
152
+ pathTypes,
153
+ dateModified,
154
+ queryByModified,
155
+ unsubscribes,
156
+ retry: 0,
157
+ saveState,
158
+ onLoadParams,
159
+ status$,
160
+ });
161
+ params.state.remoteError.set(err);
162
+ onLoadError === null || onLoadError === void 0 ? void 0 : onLoadError(err);
163
+ if (allowSetIfError) {
164
+ status$.numWaitingCanSave.set((v) => v - 1);
165
+ }
166
+ }
167
+ }
168
+ };
169
+ if (mode !== 'once') {
170
+ const localState = { changes: {} };
171
+ const cb = this._onChange.bind(this, path, pathTypes, pathFirebase, dateModifiedKey, dateModifiedKeyOption, params, localState, saveState, status$);
172
+ unsubscribes.push(this.fns.onChildAdded(ref, cb));
173
+ unsubscribes.push(this.fns.onChildChanged(ref, cb));
174
+ }
175
+ onLoadParams.waiting++;
176
+ unsubscribes.push(this.fns.once(ref, this._onceValue.bind(this, path, pathTypes, pathFirebase, dateModifiedKey, dateModifiedKeyOption, queryByModified, onLoadParams.onLoad, params, status$), _onError));
177
+ }
178
+ _updatePendingSave(path, value, pending) {
179
+ if (path.length === 0) {
180
+ pending[symbolSaveValue] = value;
181
+ }
182
+ else if (pending[symbolSaveValue]) {
183
+ pending[symbolSaveValue] = mergeIntoObservable(pending[symbolSaveValue], value);
184
+ }
185
+ else {
186
+ const p = path[0];
187
+ const v = value[p];
188
+ const pendingChild = pending[p];
189
+ // If already have a save info here then don't need to go deeper on the path. Just overwrite the value.
190
+ if (pendingChild && pendingChild[symbolSaveValue] !== undefined) {
191
+ const pendingSaveValue = pendingChild[symbolSaveValue];
192
+ pendingChild[symbolSaveValue] =
193
+ isArray(pendingSaveValue) || isObject(pendingSaveValue)
194
+ ? mergeIntoObservable(pendingSaveValue, v)
195
+ : v;
196
+ }
197
+ else {
198
+ // 1. If nothing here
199
+ // 2. If other strings here
200
+ if (!pending[p]) {
201
+ pending[p] = {};
202
+ }
203
+ if (path.length > 1) {
204
+ this._updatePendingSave(path.slice(1), v, pending[p]);
205
+ }
206
+ else {
207
+ pending[p] = { [symbolSaveValue]: v };
208
+ }
209
+ }
210
+ }
211
+ }
212
+ async set({ options, changes, obs }) {
213
+ const { remote } = options;
214
+ // If the plugin is set globally but it has no firebase options this plugin can't do anything
215
+ if (!remote || !remote.firebase) {
216
+ return;
217
+ }
218
+ const { waitForSet, saveTimeout, log, firebase } = remote;
219
+ const { requireAuth, refPath: refPathFn } = firebase;
220
+ if (requireAuth) {
221
+ await whenReady(this.user);
222
+ }
223
+ const refPath = refPathFn(this.fns.getCurrentUser());
224
+ const status$ = this._pathsLoadStatus[refPath];
225
+ if (status$.numWaitingCanSave.peek() > 0) {
226
+ // Wait for all listened paths to load before we can save
227
+ await when(() => status$.numWaitingCanSave.get() < 1);
228
+ }
229
+ if (waitForSet) {
230
+ await whenReady(waitForSet);
231
+ }
232
+ const saveState = this.saveStates.get(obs);
233
+ const { pendingSaveResults, pendingSaves } = saveState;
234
+ if (!pendingSaves.has(refPath)) {
235
+ pendingSaves.set(refPath, { options, saves: {} });
236
+ pendingSaveResults.set(refPath, { saved: [] });
237
+ }
238
+ const pending = pendingSaves.get(refPath).saves;
239
+ log === null || log === void 0 ? void 0 : log('verbose', 'Saving', changes);
240
+ for (let i = 0; i < changes.length; i++) {
241
+ let { valueAtPath } = changes[i];
242
+ const { pathTypes, path } = changes[i];
243
+ if (valueAtPath === undefined) {
244
+ valueAtPath = null;
245
+ }
246
+ const value = constructObjectWithPath(path, clone(valueAtPath), pathTypes);
247
+ const pathCloned = path.slice();
248
+ this._updatePendingSave(pathCloned, value, pending);
249
+ }
250
+ if (!saveState.eventSaved) {
251
+ saveState.eventSaved = observablePrimitive();
252
+ }
253
+ // Keep the current eventSaved. This will get reassigned once the timeout activates.
254
+ const eventSaved = saveState.eventSaved;
255
+ const timeout = saveTimeout !== null && saveTimeout !== void 0 ? saveTimeout : this.SaveTimeout;
256
+ if (timeout) {
257
+ if (saveState.timeout) {
258
+ clearTimeout(saveState.timeout);
259
+ }
260
+ saveState.timeout = setTimeout(this._onTimeoutSave.bind(this, saveState), timeout);
261
+ }
262
+ else {
263
+ this._onTimeoutSave(saveState);
264
+ }
265
+ const savedOrError = await when(eventSaved);
266
+ if (savedOrError === true) {
267
+ this.retryListens();
268
+ const saveResults = pendingSaveResults.get(refPath);
269
+ if (saveResults) {
270
+ const { saved } = saveResults;
271
+ if (saved === null || saved === void 0 ? void 0 : saved.length) {
272
+ // Only want to return from saved one time
273
+ if (saveState.numSavesPending === 0) {
274
+ pendingSaveResults.delete(refPath);
275
+ }
276
+ else {
277
+ saveResults.saved = [];
278
+ }
279
+ let maxModified = 0;
280
+ // Compile a changes object of all the dateModified
281
+ const changesOut = {};
282
+ for (let i = 0; i < saved.length; i++) {
283
+ const { dateModified, path, pathTypes, dateModifiedKeyOption, dateModifiedKey, value } = saved[i];
284
+ if (dateModified) {
285
+ maxModified = Math.max(dateModified, maxModified);
286
+ if (dateModifiedKeyOption) {
287
+ const deconstructed = deconstructObjectWithPath(path, value);
288
+ // Don't resurrect deleted items
289
+ if (deconstructed !== symbolDelete) {
290
+ Object.assign(changesOut, constructObjectWithPath(path, {
291
+ [dateModifiedKey]: dateModified,
292
+ }, pathTypes));
293
+ }
294
+ }
295
+ }
296
+ }
297
+ const ret = {
298
+ changes: changesOut,
299
+ dateModified: maxModified || undefined,
300
+ };
301
+ log === null || log === void 0 ? void 0 : log('verbose', 'Saved', changes, ret);
302
+ return ret;
303
+ }
304
+ }
305
+ }
306
+ else {
307
+ throw savedOrError;
308
+ }
309
+ return {};
310
+ }
311
+ _constructBatch(options, batch, basePath, saves, ...path) {
312
+ const { fieldTransforms, dateModifiedKey: dateModifiedKeyOption } = options.remote;
313
+ const dateModifiedKey = getDateModifiedKey(dateModifiedKeyOption);
314
+ let valSave = saves[symbolSaveValue];
315
+ if (valSave !== undefined) {
316
+ let queryByModified = options.remote.firebase.queryByModified;
317
+ if (queryByModified) {
318
+ if (queryByModified !== true && fieldTransforms) {
319
+ queryByModified = transformObject(queryByModified, fieldTransforms);
320
+ }
321
+ valSave = this.insertDatesToSave(batch, queryByModified, dateModifiedKey, basePath, path, valSave);
322
+ }
323
+ const pathThis = basePath + path.join('/');
324
+ if (pathThis && !batch[pathThis]) {
325
+ batch[pathThis] = valSave;
326
+ }
327
+ }
328
+ else {
329
+ Object.keys(saves).forEach((key) => {
330
+ this._constructBatch(options, batch, basePath, saves[key], ...path, key);
331
+ });
332
+ }
333
+ }
334
+ _constructBatchesForSave(pendingSaves) {
335
+ const batches = [];
336
+ pendingSaves.forEach(({ options, saves }) => {
337
+ const basePath = options.remote.firebase.refPath(this.fns.getCurrentUser());
338
+ const batch = {};
339
+ this._constructBatch(options, batch, basePath, saves);
340
+ batches.push(batch);
341
+ });
342
+ return batches;
343
+ }
344
+ async _onTimeoutSave(saveState) {
345
+ const { pendingSaves, eventSaved } = saveState;
346
+ saveState.timeout = undefined;
347
+ saveState.eventSaved = undefined;
348
+ saveState.numSavesPending++;
349
+ if (pendingSaves.size > 0) {
350
+ const batches = JSON.parse(JSON.stringify(this._constructBatchesForSave(pendingSaves)));
351
+ saveState.savingSaves = pendingSaves;
352
+ // Clear the pendingSaves so that the next batch starts from scratch
353
+ saveState.pendingSaves = new Map();
354
+ if (batches.length > 0) {
355
+ const promises = [];
356
+ for (let i = 0; i < batches.length; i++) {
357
+ const batch = batches[i];
358
+ promises.push(this._saveBatch(batch));
359
+ }
360
+ const results = await Promise.all(promises);
361
+ const errors = results.filter((result) => result.error);
362
+ if (errors.length === 0) {
363
+ saveState.numSavesPending--;
364
+ eventSaved === null || eventSaved === void 0 ? void 0 : eventSaved.set(true);
365
+ }
366
+ else {
367
+ eventSaved === null || eventSaved === void 0 ? void 0 : eventSaved.set(errors[0].error);
368
+ }
369
+ }
370
+ }
371
+ }
372
+ async _saveBatch(batch) {
373
+ const length = JSON.stringify(batch).length;
374
+ let error = undefined;
375
+ // Firebase has a maximum limit of 16MB per save so we constrain our saves to
376
+ // less than 12 to be safe
377
+ if (length > 12e6) {
378
+ const parts = splitLargeObject(batch, 6e6);
379
+ let didSave = true;
380
+ // TODO: Option for logging
381
+ for (let i = 0; i < parts.length; i++) {
382
+ const ret = await this._saveBatch(parts[i]);
383
+ if (ret.error) {
384
+ error = ret.error;
385
+ }
386
+ else {
387
+ didSave = didSave && ret.didSave;
388
+ }
389
+ }
390
+ return error ? { error } : { didSave };
391
+ }
392
+ else {
393
+ for (let i = 0; i < 3; i++) {
394
+ try {
395
+ await this.fns.update(batch);
396
+ return { didSave: true };
397
+ }
398
+ catch (err) {
399
+ error = err;
400
+ await new Promise((resolve) => setTimeout(resolve, 500));
401
+ }
402
+ }
403
+ return { error };
404
+ }
405
+ }
406
+ _convertFBTimestamps(obj, dateModifiedKey, dateModifiedKeyOption) {
407
+ let value = obj;
408
+ // Database value can be either { @: number, _: object } or { @: number, ...rest }
409
+ // where @ is the dateModifiedKey
410
+ let dateModified = value[dateModifiedKey];
411
+ if (dateModified) {
412
+ // If user doesn't request a dateModifiedKey then delete it
413
+ if (value._ !== undefined) {
414
+ value = value._;
415
+ }
416
+ else if (dateModified && Object.keys(value).length < 2) {
417
+ value = symbolDelete;
418
+ }
419
+ if (!dateModifiedKeyOption) {
420
+ delete value[dateModifiedKey];
421
+ }
422
+ }
423
+ if (isObject(value)) {
424
+ Object.keys(value).forEach((k) => {
425
+ const val = value[k];
426
+ if (val !== undefined) {
427
+ if (isObject(val) || isArray(val)) {
428
+ const { value: valueChild, dateModified: dateModifiedChild } = this._convertFBTimestamps(val, dateModifiedKey, dateModifiedKeyOption);
429
+ if (dateModifiedChild) {
430
+ dateModified = Math.max(dateModified || 0, dateModifiedChild);
431
+ }
432
+ if (valueChild !== val) {
433
+ value[k] = valueChild;
434
+ }
435
+ }
436
+ }
437
+ });
438
+ }
439
+ return { value, dateModified };
440
+ }
441
+ async _onceValue(path, pathTypes, pathFirebase, dateModifiedKey, dateModifiedKeyOption, queryByModified, onLoad, params, status$, snapshot) {
442
+ const { onChange } = params;
443
+ const outerValue = snapshot.val();
444
+ // If this path previously errored, clear the error state
445
+ const obs = params.obs;
446
+ params.state.remoteError.delete();
447
+ this.listenErrors.delete(obs);
448
+ status$.startedLoading.set(true);
449
+ if (outerValue && isObject(outerValue)) {
450
+ let value;
451
+ let dateModified;
452
+ if (queryByModified) {
453
+ const converted = this._convertFBTimestamps(outerValue, dateModifiedKey, dateModifiedKeyOption);
454
+ value = converted.value;
455
+ dateModified = converted.dateModified;
456
+ }
457
+ else {
458
+ value = outerValue;
459
+ }
460
+ value = constructObjectWithPath(path, value, pathTypes);
461
+ const onChangePromise = onChange({
462
+ value,
463
+ path,
464
+ pathTypes,
465
+ mode: queryByModified ? 'assign' : 'set',
466
+ dateModified,
467
+ });
468
+ if (onChangePromise) {
469
+ await onChangePromise;
470
+ }
471
+ }
472
+ onLoad();
473
+ batch(() => {
474
+ status$.numLoading.set((v) => v - 1);
475
+ status$.numWaitingCanSave.set((v) => v - 1);
476
+ });
477
+ }
478
+ async _onChange(path, pathTypes, pathFirebase, dateModifiedKey, dateModifiedKeyOption, params, localState, saveState, status$, snapshot) {
479
+ const { numLoading, startedLoading } = status$.peek();
480
+ if (numLoading > 0) {
481
+ // If onceValue has not been called yet, then skip onChange because it will come later
482
+ if (!startedLoading)
483
+ return;
484
+ // Wait for load
485
+ await when(() => status$.numLoading.get() < 1);
486
+ }
487
+ const { onChange, state, options: { remote }, } = params;
488
+ const { changeTimeout } = remote;
489
+ // Skip changes if disabled
490
+ if (state.isEnabledRemote.peek() === false)
491
+ return;
492
+ const key = snapshot.key;
493
+ const val = snapshot.val();
494
+ if (val) {
495
+ // eslint-disable-next-line prefer-const
496
+ let { value, dateModified } = this._convertFBTimestamps(val, dateModifiedKey, dateModifiedKeyOption);
497
+ const pathChild = path.concat(key);
498
+ const pathTypesChild = pathTypes.concat('object');
499
+ const constructed = constructObjectWithPath(pathChild, value, pathTypes);
500
+ if (!this.addValuesToPendingSaves(pathFirebase, constructed, pathChild, pathTypesChild, dateModified, dateModifiedKey, dateModifiedKeyOption, saveState, onChange)) {
501
+ localState.changes = setAtPath(localState.changes, pathChild, pathTypes, value);
502
+ // Debounce many child changes into a single onChange
503
+ clearTimeout(localState.timeout);
504
+ localState.timeout = setTimeout(() => {
505
+ const changes = localState.changes;
506
+ localState.changes = {};
507
+ onChange({ value: changes, path, pathTypes, mode: 'assign', dateModified });
508
+ }, changeTimeout || 300);
509
+ }
510
+ }
511
+ }
512
+ insertDateToObject(value, dateModifiedKey) {
513
+ const timestamp = this.fns.serverTimestamp();
514
+ if (isObject(value)) {
515
+ return Object.assign(value, {
516
+ [dateModifiedKey]: timestamp,
517
+ });
518
+ }
519
+ else {
520
+ return {
521
+ [dateModifiedKey]: timestamp,
522
+ _: value,
523
+ };
524
+ }
525
+ }
526
+ insertDatesToSaveObject(batch, queryByModified, dateModifiedKey, path, value) {
527
+ if (queryByModified === true) {
528
+ value = this.insertDateToObject(value, dateModifiedKey);
529
+ }
530
+ else if (isObject(value)) {
531
+ Object.keys(value).forEach((key) => {
532
+ value[key] = this.insertDatesToSaveObject(batch, queryByModified[key], dateModifiedKey, path + '/' + key, value[key]);
533
+ });
534
+ }
535
+ return value;
536
+ }
537
+ insertDatesToSave(batch, queryByModified, dateModifiedKey, basePath, path, value) {
538
+ let o = queryByModified;
539
+ for (let i = 0; i < path.length; i++) {
540
+ if (o === true) {
541
+ const pathThis = basePath + path.slice(0, i + 1).join('/');
542
+ if (i === path.length - 1) {
543
+ if (!isObject(value)) {
544
+ return this.insertDateToObject(value, dateModifiedKey);
545
+ }
546
+ else {
547
+ if (isObject(value)) {
548
+ value[dateModifiedKey] = this.fns.serverTimestamp();
549
+ }
550
+ else {
551
+ batch[pathThis + '/' + dateModifiedKey] = this.fns.serverTimestamp();
552
+ }
553
+ }
554
+ }
555
+ else {
556
+ batch[pathThis + '/' + dateModifiedKey] = this.fns.serverTimestamp();
557
+ }
558
+ return value;
559
+ }
560
+ else if (isObject(o)) {
561
+ o = o[path[i]];
562
+ }
563
+ }
564
+ if (o === true && isObject(value)) {
565
+ Object.keys(value).forEach((key) => {
566
+ this.insertDatesToSaveObject(batch, o, dateModifiedKey, basePath + path.join('/') + '/' + key, value[key]);
567
+ });
568
+ }
569
+ else if (o !== undefined) {
570
+ this.insertDatesToSaveObject(batch, o, dateModifiedKey, basePath + path.join('/'), value);
571
+ }
572
+ return value;
573
+ }
574
+ addValuesToPendingSaves(refPath, value, pathChild, pathTypesChild, dateModified, dateModifiedKey, dateModifiedKeyOption, saveState, onChange) {
575
+ const { pendingSaveResults, savingSaves } = saveState;
576
+ let found = false;
577
+ const pathArr = refPath.split('/');
578
+ for (let i = pathArr.length - 1; !found && i >= 0; i--) {
579
+ const p = pathArr[i];
580
+ if (p === '')
581
+ continue;
582
+ const path = pathArr.slice(0, i + 1).join('/') + '/';
583
+ // Look for this saved key in the currently saving saves.
584
+ // If it's being saved locally this must be the remote onChange
585
+ // coming in for this save.
586
+ if (pendingSaveResults.has(path) && (savingSaves === null || savingSaves === void 0 ? void 0 : savingSaves.has(path))) {
587
+ found = true;
588
+ if (pathChild.length > 0) {
589
+ const savingSave = savingSaves.get(path);
590
+ const save = savingSave.saves[pathChild[0]];
591
+ if (!save) {
592
+ found = false;
593
+ }
594
+ }
595
+ if (found) {
596
+ const pending = pendingSaveResults.get(path);
597
+ pending.saved.push({
598
+ value,
599
+ dateModified,
600
+ path: pathChild,
601
+ pathTypes: pathTypesChild,
602
+ dateModifiedKey,
603
+ dateModifiedKeyOption,
604
+ onChange,
605
+ });
606
+ }
607
+ }
608
+ value = { [p]: value };
609
+ }
610
+ return found;
611
+ }
612
+ }
613
+ function estimateSize(value) {
614
+ return ('' + value).length + 2; // Convert to string and account for quotes in JSON.
615
+ }
616
+ function splitLargeObject(obj, limit) {
617
+ const parts = [{}];
618
+ let sizeCount = 0;
619
+ function recursiveSplit(innerObj, path = []) {
620
+ for (const key in innerObj) {
621
+ if (!hasOwnProperty.call(innerObj, key)) {
622
+ continue;
623
+ }
624
+ const newPath = [...path, key];
625
+ const keySize = key.length + 4; // Account for quotes and colon in JSON.
626
+ const val = innerObj[key];
627
+ let itemSize = 0;
628
+ if (val && typeof val === 'object') {
629
+ itemSize = JSON.stringify(val).length;
630
+ }
631
+ else {
632
+ itemSize = estimateSize(val);
633
+ }
634
+ if (val && typeof val === 'object' && itemSize > limit) {
635
+ recursiveSplit(val, newPath);
636
+ }
637
+ else {
638
+ // Check if the size of the current item exceeds the limit
639
+ if (sizeCount > 0 && sizeCount + keySize + itemSize > limit) {
640
+ parts.push({});
641
+ sizeCount = 0;
642
+ }
643
+ const pathKey = newPath.join('/');
644
+ parts[parts.length - 1][pathKey] = val;
645
+ sizeCount += keySize + itemSize;
646
+ }
647
+ }
648
+ }
649
+ recursiveSplit(obj);
650
+ return parts;
651
+ }
652
+ // This is the web version of all the firebase functions. It passes them in as arguments so that it could
653
+ // support firebase on other platforms.
654
+ class ObservablePersistFirebase extends ObservablePersistFirebaseBase {
655
+ constructor() {
656
+ super({
657
+ isInitialized: () => {
658
+ try {
659
+ return !!getAuth().app;
660
+ }
661
+ catch (_a) {
662
+ return false;
663
+ }
664
+ },
665
+ getCurrentUser: () => { var _a; return (_a = getAuth().currentUser) === null || _a === void 0 ? void 0 : _a.uid; },
666
+ ref: (path) => ref(getDatabase(), path),
667
+ orderByChild: (ref, child, start) => query(ref, orderByChild(child), startAt(start)),
668
+ update: (object) => update(ref(getDatabase()), object),
669
+ once: (ref, callback, callbackError) => {
670
+ let unsubscribe;
671
+ const cb = (snap) => {
672
+ if (unsubscribe) {
673
+ unsubscribe();
674
+ unsubscribe = undefined;
675
+ }
676
+ callback(snap);
677
+ };
678
+ unsubscribe = onValue(ref, cb, callbackError);
679
+ return unsubscribe;
680
+ },
681
+ onChildAdded,
682
+ onChildChanged,
683
+ serverTimestamp,
684
+ onAuthStateChanged: (cb) => getAuth().onAuthStateChanged(cb),
685
+ });
686
+ }
687
+ }
688
+
689
+ export { ObservablePersistFirebase };
690
+ //# sourceMappingURL=firebase.mjs.map