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

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