@legendapp/state 2.0.0-next.13 → 2.0.0-next.15

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