@depup/firebase__app 0.14.9-depup.0

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 (44) hide show
  1. package/README.md +32 -0
  2. package/changes.json +14 -0
  3. package/dist/app/src/api.d.ts +235 -0
  4. package/dist/app/src/constants.d.ts +26 -0
  5. package/dist/app/src/errors.d.ts +67 -0
  6. package/dist/app/src/firebaseApp.d.ts +46 -0
  7. package/dist/app/src/firebaseServerApp.d.ts +36 -0
  8. package/dist/app/src/global_index.d.ts +939 -0
  9. package/dist/app/src/heartbeatService.d.ts +89 -0
  10. package/dist/app/src/index.d.ts +9 -0
  11. package/dist/app/src/indexeddb.d.ts +20 -0
  12. package/dist/app/src/internal.d.ts +108 -0
  13. package/dist/app/src/logger.d.ts +18 -0
  14. package/dist/app/src/platformLoggerService.d.ts +23 -0
  15. package/dist/app/src/public-types.d.ts +241 -0
  16. package/dist/app/src/registerCoreComponents.d.ts +17 -0
  17. package/dist/app/src/tsdoc-metadata.json +11 -0
  18. package/dist/app/src/types.d.ts +55 -0
  19. package/dist/app/test/setup.d.ts +17 -0
  20. package/dist/app/test/util.d.ts +26 -0
  21. package/dist/app-public.d.ts +477 -0
  22. package/dist/app.d.ts +572 -0
  23. package/dist/esm/app/src/api.d.ts +235 -0
  24. package/dist/esm/app/src/constants.d.ts +26 -0
  25. package/dist/esm/app/src/errors.d.ts +67 -0
  26. package/dist/esm/app/src/firebaseApp.d.ts +46 -0
  27. package/dist/esm/app/src/firebaseServerApp.d.ts +36 -0
  28. package/dist/esm/app/src/heartbeatService.d.ts +89 -0
  29. package/dist/esm/app/src/index.d.ts +9 -0
  30. package/dist/esm/app/src/indexeddb.d.ts +20 -0
  31. package/dist/esm/app/src/internal.d.ts +108 -0
  32. package/dist/esm/app/src/logger.d.ts +18 -0
  33. package/dist/esm/app/src/platformLoggerService.d.ts +23 -0
  34. package/dist/esm/app/src/public-types.d.ts +241 -0
  35. package/dist/esm/app/src/registerCoreComponents.d.ts +17 -0
  36. package/dist/esm/app/src/types.d.ts +55 -0
  37. package/dist/esm/app/test/setup.d.ts +17 -0
  38. package/dist/esm/app/test/util.d.ts +26 -0
  39. package/dist/esm/index.esm.js +1237 -0
  40. package/dist/esm/index.esm.js.map +1 -0
  41. package/dist/esm/package.json +1 -0
  42. package/dist/index.cjs.js +1265 -0
  43. package/dist/index.cjs.js.map +1 -0
  44. package/package.json +100 -0
@@ -0,0 +1,1237 @@
1
+ import { Component, ComponentContainer } from '@firebase/component';
2
+ import { Logger, setUserLogHandler, setLogLevel as setLogLevel$1 } from '@firebase/logger';
3
+ import { ErrorFactory, base64Decode, getDefaultAppConfig, deepEqual, isBrowser, isWebWorker, FirebaseError, base64urlEncodeWithoutPadding, isIndexedDBAvailable, validateIndexedDBOpenable } from '@firebase/util';
4
+ export { FirebaseError } from '@firebase/util';
5
+ import { openDB } from 'idb';
6
+
7
+ /**
8
+ * @license
9
+ * Copyright 2019 Google LLC
10
+ *
11
+ * Licensed under the Apache License, Version 2.0 (the "License");
12
+ * you may not use this file except in compliance with the License.
13
+ * You may obtain a copy of the License at
14
+ *
15
+ * http://www.apache.org/licenses/LICENSE-2.0
16
+ *
17
+ * Unless required by applicable law or agreed to in writing, software
18
+ * distributed under the License is distributed on an "AS IS" BASIS,
19
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20
+ * See the License for the specific language governing permissions and
21
+ * limitations under the License.
22
+ */
23
+ class PlatformLoggerServiceImpl {
24
+ constructor(container) {
25
+ this.container = container;
26
+ }
27
+ // In initial implementation, this will be called by installations on
28
+ // auth token refresh, and installations will send this string.
29
+ getPlatformInfoString() {
30
+ const providers = this.container.getProviders();
31
+ // Loop through providers and get library/version pairs from any that are
32
+ // version components.
33
+ return providers
34
+ .map(provider => {
35
+ if (isVersionServiceProvider(provider)) {
36
+ const service = provider.getImmediate();
37
+ return `${service.library}/${service.version}`;
38
+ }
39
+ else {
40
+ return null;
41
+ }
42
+ })
43
+ .filter(logString => logString)
44
+ .join(' ');
45
+ }
46
+ }
47
+ /**
48
+ *
49
+ * @param provider check if this provider provides a VersionService
50
+ *
51
+ * NOTE: Using Provider<'app-version'> is a hack to indicate that the provider
52
+ * provides VersionService. The provider is not necessarily a 'app-version'
53
+ * provider.
54
+ */
55
+ function isVersionServiceProvider(provider) {
56
+ const component = provider.getComponent();
57
+ return component?.type === "VERSION" /* ComponentType.VERSION */;
58
+ }
59
+
60
+ const name$q = "@firebase/app";
61
+ const version$1 = "0.14.9";
62
+
63
+ /**
64
+ * @license
65
+ * Copyright 2019 Google LLC
66
+ *
67
+ * Licensed under the Apache License, Version 2.0 (the "License");
68
+ * you may not use this file except in compliance with the License.
69
+ * You may obtain a copy of the License at
70
+ *
71
+ * http://www.apache.org/licenses/LICENSE-2.0
72
+ *
73
+ * Unless required by applicable law or agreed to in writing, software
74
+ * distributed under the License is distributed on an "AS IS" BASIS,
75
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
76
+ * See the License for the specific language governing permissions and
77
+ * limitations under the License.
78
+ */
79
+ const logger = new Logger('@firebase/app');
80
+
81
+ const name$p = "@firebase/app-compat";
82
+
83
+ const name$o = "@firebase/analytics-compat";
84
+
85
+ const name$n = "@firebase/analytics";
86
+
87
+ const name$m = "@firebase/app-check-compat";
88
+
89
+ const name$l = "@firebase/app-check";
90
+
91
+ const name$k = "@firebase/auth";
92
+
93
+ const name$j = "@firebase/auth-compat";
94
+
95
+ const name$i = "@firebase/database";
96
+
97
+ const name$h = "@firebase/data-connect";
98
+
99
+ const name$g = "@firebase/database-compat";
100
+
101
+ const name$f = "@firebase/functions";
102
+
103
+ const name$e = "@firebase/functions-compat";
104
+
105
+ const name$d = "@firebase/installations";
106
+
107
+ const name$c = "@firebase/installations-compat";
108
+
109
+ const name$b = "@firebase/messaging";
110
+
111
+ const name$a = "@firebase/messaging-compat";
112
+
113
+ const name$9 = "@firebase/performance";
114
+
115
+ const name$8 = "@firebase/performance-compat";
116
+
117
+ const name$7 = "@firebase/remote-config";
118
+
119
+ const name$6 = "@firebase/remote-config-compat";
120
+
121
+ const name$5 = "@firebase/storage";
122
+
123
+ const name$4 = "@firebase/storage-compat";
124
+
125
+ const name$3 = "@firebase/firestore";
126
+
127
+ const name$2 = "@firebase/ai";
128
+
129
+ const name$1 = "@firebase/firestore-compat";
130
+
131
+ const name = "firebase";
132
+ const version = "12.10.0";
133
+
134
+ /**
135
+ * @license
136
+ * Copyright 2019 Google LLC
137
+ *
138
+ * Licensed under the Apache License, Version 2.0 (the "License");
139
+ * you may not use this file except in compliance with the License.
140
+ * You may obtain a copy of the License at
141
+ *
142
+ * http://www.apache.org/licenses/LICENSE-2.0
143
+ *
144
+ * Unless required by applicable law or agreed to in writing, software
145
+ * distributed under the License is distributed on an "AS IS" BASIS,
146
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
147
+ * See the License for the specific language governing permissions and
148
+ * limitations under the License.
149
+ */
150
+ /**
151
+ * The default app name
152
+ *
153
+ * @internal
154
+ */
155
+ const DEFAULT_ENTRY_NAME = '[DEFAULT]';
156
+ const PLATFORM_LOG_STRING = {
157
+ [name$q]: 'fire-core',
158
+ [name$p]: 'fire-core-compat',
159
+ [name$n]: 'fire-analytics',
160
+ [name$o]: 'fire-analytics-compat',
161
+ [name$l]: 'fire-app-check',
162
+ [name$m]: 'fire-app-check-compat',
163
+ [name$k]: 'fire-auth',
164
+ [name$j]: 'fire-auth-compat',
165
+ [name$i]: 'fire-rtdb',
166
+ [name$h]: 'fire-data-connect',
167
+ [name$g]: 'fire-rtdb-compat',
168
+ [name$f]: 'fire-fn',
169
+ [name$e]: 'fire-fn-compat',
170
+ [name$d]: 'fire-iid',
171
+ [name$c]: 'fire-iid-compat',
172
+ [name$b]: 'fire-fcm',
173
+ [name$a]: 'fire-fcm-compat',
174
+ [name$9]: 'fire-perf',
175
+ [name$8]: 'fire-perf-compat',
176
+ [name$7]: 'fire-rc',
177
+ [name$6]: 'fire-rc-compat',
178
+ [name$5]: 'fire-gcs',
179
+ [name$4]: 'fire-gcs-compat',
180
+ [name$3]: 'fire-fst',
181
+ [name$1]: 'fire-fst-compat',
182
+ [name$2]: 'fire-vertex',
183
+ 'fire-js': 'fire-js', // Platform identifier for JS SDK.
184
+ [name]: 'fire-js-all'
185
+ };
186
+
187
+ /**
188
+ * @license
189
+ * Copyright 2019 Google LLC
190
+ *
191
+ * Licensed under the Apache License, Version 2.0 (the "License");
192
+ * you may not use this file except in compliance with the License.
193
+ * You may obtain a copy of the License at
194
+ *
195
+ * http://www.apache.org/licenses/LICENSE-2.0
196
+ *
197
+ * Unless required by applicable law or agreed to in writing, software
198
+ * distributed under the License is distributed on an "AS IS" BASIS,
199
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ * See the License for the specific language governing permissions and
201
+ * limitations under the License.
202
+ */
203
+ /**
204
+ * @internal
205
+ */
206
+ const _apps = new Map();
207
+ /**
208
+ * @internal
209
+ */
210
+ const _serverApps = new Map();
211
+ /**
212
+ * Registered components.
213
+ *
214
+ * @internal
215
+ */
216
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
217
+ const _components = new Map();
218
+ /**
219
+ * @param component - the component being added to this app's container
220
+ *
221
+ * @internal
222
+ */
223
+ function _addComponent(app, component) {
224
+ try {
225
+ app.container.addComponent(component);
226
+ }
227
+ catch (e) {
228
+ logger.debug(`Component ${component.name} failed to register with FirebaseApp ${app.name}`, e);
229
+ }
230
+ }
231
+ /**
232
+ *
233
+ * @internal
234
+ */
235
+ function _addOrOverwriteComponent(app, component) {
236
+ app.container.addOrOverwriteComponent(component);
237
+ }
238
+ /**
239
+ *
240
+ * @param component - the component to register
241
+ * @returns whether or not the component is registered successfully
242
+ *
243
+ * @internal
244
+ */
245
+ function _registerComponent(component) {
246
+ const componentName = component.name;
247
+ if (_components.has(componentName)) {
248
+ logger.debug(`There were multiple attempts to register component ${componentName}.`);
249
+ return false;
250
+ }
251
+ _components.set(componentName, component);
252
+ // add the component to existing app instances
253
+ for (const app of _apps.values()) {
254
+ _addComponent(app, component);
255
+ }
256
+ for (const serverApp of _serverApps.values()) {
257
+ _addComponent(serverApp, component);
258
+ }
259
+ return true;
260
+ }
261
+ /**
262
+ *
263
+ * @param app - FirebaseApp instance
264
+ * @param name - service name
265
+ *
266
+ * @returns the provider for the service with the matching name
267
+ *
268
+ * @internal
269
+ */
270
+ function _getProvider(app, name) {
271
+ const heartbeatController = app.container
272
+ .getProvider('heartbeat')
273
+ .getImmediate({ optional: true });
274
+ if (heartbeatController) {
275
+ void heartbeatController.triggerHeartbeat();
276
+ }
277
+ return app.container.getProvider(name);
278
+ }
279
+ /**
280
+ *
281
+ * @param app - FirebaseApp instance
282
+ * @param name - service name
283
+ * @param instanceIdentifier - service instance identifier in case the service supports multiple instances
284
+ *
285
+ * @internal
286
+ */
287
+ function _removeServiceInstance(app, name, instanceIdentifier = DEFAULT_ENTRY_NAME) {
288
+ _getProvider(app, name).clearInstance(instanceIdentifier);
289
+ }
290
+ /**
291
+ *
292
+ * @param obj - an object of type FirebaseApp, FirebaseOptions or FirebaseAppSettings.
293
+ *
294
+ * @returns true if the provide object is of type FirebaseApp.
295
+ *
296
+ * @internal
297
+ */
298
+ function _isFirebaseApp(obj) {
299
+ return obj.options !== undefined;
300
+ }
301
+ /**
302
+ *
303
+ * @param obj - an object of type FirebaseApp, FirebaseOptions or FirebaseAppSettings.
304
+ *
305
+ * @returns true if the provided object is of type FirebaseServerAppImpl.
306
+ *
307
+ * @internal
308
+ */
309
+ function _isFirebaseServerAppSettings(obj) {
310
+ if (_isFirebaseApp(obj)) {
311
+ return false;
312
+ }
313
+ return ('authIdToken' in obj ||
314
+ 'appCheckToken' in obj ||
315
+ 'releaseOnDeref' in obj ||
316
+ 'automaticDataCollectionEnabled' in obj);
317
+ }
318
+ /**
319
+ *
320
+ * @param obj - an object of type FirebaseApp.
321
+ *
322
+ * @returns true if the provided object is of type FirebaseServerAppImpl.
323
+ *
324
+ * @internal
325
+ */
326
+ function _isFirebaseServerApp(obj) {
327
+ if (obj === null || obj === undefined) {
328
+ return false;
329
+ }
330
+ return obj.settings !== undefined;
331
+ }
332
+ /**
333
+ * Test only
334
+ *
335
+ * @internal
336
+ */
337
+ function _clearComponents() {
338
+ _components.clear();
339
+ }
340
+
341
+ /**
342
+ * @license
343
+ * Copyright 2019 Google LLC
344
+ *
345
+ * Licensed under the Apache License, Version 2.0 (the "License");
346
+ * you may not use this file except in compliance with the License.
347
+ * You may obtain a copy of the License at
348
+ *
349
+ * http://www.apache.org/licenses/LICENSE-2.0
350
+ *
351
+ * Unless required by applicable law or agreed to in writing, software
352
+ * distributed under the License is distributed on an "AS IS" BASIS,
353
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
354
+ * See the License for the specific language governing permissions and
355
+ * limitations under the License.
356
+ */
357
+ const ERRORS = {
358
+ ["no-app" /* AppError.NO_APP */]: "No Firebase App '{$appName}' has been created - " +
359
+ 'call initializeApp() first',
360
+ ["bad-app-name" /* AppError.BAD_APP_NAME */]: "Illegal App name: '{$appName}'",
361
+ ["duplicate-app" /* AppError.DUPLICATE_APP */]: "Firebase App named '{$appName}' already exists with different options or config",
362
+ ["app-deleted" /* AppError.APP_DELETED */]: "Firebase App named '{$appName}' already deleted",
363
+ ["server-app-deleted" /* AppError.SERVER_APP_DELETED */]: 'Firebase Server App has been deleted',
364
+ ["no-options" /* AppError.NO_OPTIONS */]: 'Need to provide options, when not being deployed to hosting via source.',
365
+ ["invalid-app-argument" /* AppError.INVALID_APP_ARGUMENT */]: 'firebase.{$appName}() takes either no argument or a ' +
366
+ 'Firebase App instance.',
367
+ ["invalid-log-argument" /* AppError.INVALID_LOG_ARGUMENT */]: 'First argument to `onLog` must be null or a function.',
368
+ ["idb-open" /* AppError.IDB_OPEN */]: 'Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.',
369
+ ["idb-get" /* AppError.IDB_GET */]: 'Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.',
370
+ ["idb-set" /* AppError.IDB_WRITE */]: 'Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.',
371
+ ["idb-delete" /* AppError.IDB_DELETE */]: 'Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}.',
372
+ ["finalization-registry-not-supported" /* AppError.FINALIZATION_REGISTRY_NOT_SUPPORTED */]: 'FirebaseServerApp deleteOnDeref field defined but the JS runtime does not support FinalizationRegistry.',
373
+ ["invalid-server-app-environment" /* AppError.INVALID_SERVER_APP_ENVIRONMENT */]: 'FirebaseServerApp is not for use in browser environments.'
374
+ };
375
+ const ERROR_FACTORY = new ErrorFactory('app', 'Firebase', ERRORS);
376
+
377
+ /**
378
+ * @license
379
+ * Copyright 2019 Google LLC
380
+ *
381
+ * Licensed under the Apache License, Version 2.0 (the "License");
382
+ * you may not use this file except in compliance with the License.
383
+ * You may obtain a copy of the License at
384
+ *
385
+ * http://www.apache.org/licenses/LICENSE-2.0
386
+ *
387
+ * Unless required by applicable law or agreed to in writing, software
388
+ * distributed under the License is distributed on an "AS IS" BASIS,
389
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
390
+ * See the License for the specific language governing permissions and
391
+ * limitations under the License.
392
+ */
393
+ class FirebaseAppImpl {
394
+ constructor(options, config, container) {
395
+ this._isDeleted = false;
396
+ this._options = { ...options };
397
+ this._config = { ...config };
398
+ this._name = config.name;
399
+ this._automaticDataCollectionEnabled =
400
+ config.automaticDataCollectionEnabled;
401
+ this._container = container;
402
+ this.container.addComponent(new Component('app', () => this, "PUBLIC" /* ComponentType.PUBLIC */));
403
+ }
404
+ get automaticDataCollectionEnabled() {
405
+ this.checkDestroyed();
406
+ return this._automaticDataCollectionEnabled;
407
+ }
408
+ set automaticDataCollectionEnabled(val) {
409
+ this.checkDestroyed();
410
+ this._automaticDataCollectionEnabled = val;
411
+ }
412
+ get name() {
413
+ this.checkDestroyed();
414
+ return this._name;
415
+ }
416
+ get options() {
417
+ this.checkDestroyed();
418
+ return this._options;
419
+ }
420
+ get config() {
421
+ this.checkDestroyed();
422
+ return this._config;
423
+ }
424
+ get container() {
425
+ return this._container;
426
+ }
427
+ get isDeleted() {
428
+ return this._isDeleted;
429
+ }
430
+ set isDeleted(val) {
431
+ this._isDeleted = val;
432
+ }
433
+ /**
434
+ * This function will throw an Error if the App has already been deleted -
435
+ * use before performing API actions on the App.
436
+ */
437
+ checkDestroyed() {
438
+ if (this.isDeleted) {
439
+ throw ERROR_FACTORY.create("app-deleted" /* AppError.APP_DELETED */, { appName: this._name });
440
+ }
441
+ }
442
+ }
443
+
444
+ /**
445
+ * @license
446
+ * Copyright 2023 Google LLC
447
+ *
448
+ * Licensed under the Apache License, Version 2.0 (the "License");
449
+ * you may not use this file except in compliance with the License.
450
+ * You may obtain a copy of the License at
451
+ *
452
+ * http://www.apache.org/licenses/LICENSE-2.0
453
+ *
454
+ * Unless required by applicable law or agreed to in writing, software
455
+ * distributed under the License is distributed on an "AS IS" BASIS,
456
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
457
+ * See the License for the specific language governing permissions and
458
+ * limitations under the License.
459
+ */
460
+ // Parse the token and check to see if the `exp` claim is in the future.
461
+ // Reports an error to the console if the token or claim could not be parsed, or if `exp` is in
462
+ // the past.
463
+ function validateTokenTTL(base64Token, tokenName) {
464
+ const secondPart = base64Decode(base64Token.split('.')[1]);
465
+ if (secondPart === null) {
466
+ console.error(`FirebaseServerApp ${tokenName} is invalid: second part could not be parsed.`);
467
+ return;
468
+ }
469
+ const expClaim = JSON.parse(secondPart).exp;
470
+ if (expClaim === undefined) {
471
+ console.error(`FirebaseServerApp ${tokenName} is invalid: expiration claim could not be parsed`);
472
+ return;
473
+ }
474
+ const exp = JSON.parse(secondPart).exp * 1000;
475
+ const now = new Date().getTime();
476
+ const diff = exp - now;
477
+ if (diff <= 0) {
478
+ console.error(`FirebaseServerApp ${tokenName} is invalid: the token has expired.`);
479
+ }
480
+ }
481
+ class FirebaseServerAppImpl extends FirebaseAppImpl {
482
+ constructor(options, serverConfig, name, container) {
483
+ // Build configuration parameters for the FirebaseAppImpl base class.
484
+ const automaticDataCollectionEnabled = serverConfig.automaticDataCollectionEnabled !== undefined
485
+ ? serverConfig.automaticDataCollectionEnabled
486
+ : true;
487
+ // Create the FirebaseAppSettings object for the FirebaseAppImp constructor.
488
+ const config = {
489
+ name,
490
+ automaticDataCollectionEnabled
491
+ };
492
+ if (options.apiKey !== undefined) {
493
+ // Construct the parent FirebaseAppImp object.
494
+ super(options, config, container);
495
+ }
496
+ else {
497
+ const appImpl = options;
498
+ super(appImpl.options, config, container);
499
+ }
500
+ // Now construct the data for the FirebaseServerAppImpl.
501
+ this._serverConfig = {
502
+ automaticDataCollectionEnabled,
503
+ ...serverConfig
504
+ };
505
+ // Ensure that the current time is within the `authIdtoken` window of validity.
506
+ if (this._serverConfig.authIdToken) {
507
+ validateTokenTTL(this._serverConfig.authIdToken, 'authIdToken');
508
+ }
509
+ // Ensure that the current time is within the `appCheckToken` window of validity.
510
+ if (this._serverConfig.appCheckToken) {
511
+ validateTokenTTL(this._serverConfig.appCheckToken, 'appCheckToken');
512
+ }
513
+ this._finalizationRegistry = null;
514
+ if (typeof FinalizationRegistry !== 'undefined') {
515
+ this._finalizationRegistry = new FinalizationRegistry(() => {
516
+ this.automaticCleanup();
517
+ });
518
+ }
519
+ this._refCount = 0;
520
+ this.incRefCount(this._serverConfig.releaseOnDeref);
521
+ // Do not retain a hard reference to the dref object, otherwise the FinalizationRegistry
522
+ // will never trigger.
523
+ this._serverConfig.releaseOnDeref = undefined;
524
+ serverConfig.releaseOnDeref = undefined;
525
+ registerVersion(name$q, version$1, 'serverapp');
526
+ }
527
+ toJSON() {
528
+ return undefined;
529
+ }
530
+ get refCount() {
531
+ return this._refCount;
532
+ }
533
+ // Increment the reference count of this server app. If an object is provided, register it
534
+ // with the finalization registry.
535
+ incRefCount(obj) {
536
+ if (this.isDeleted) {
537
+ return;
538
+ }
539
+ this._refCount++;
540
+ if (obj !== undefined && this._finalizationRegistry !== null) {
541
+ this._finalizationRegistry.register(obj, this);
542
+ }
543
+ }
544
+ // Decrement the reference count.
545
+ decRefCount() {
546
+ if (this.isDeleted) {
547
+ return 0;
548
+ }
549
+ return --this._refCount;
550
+ }
551
+ // Invoked by the FinalizationRegistry callback to note that this app should go through its
552
+ // reference counts and delete itself if no reference count remain. The coordinating logic that
553
+ // handles this is in deleteApp(...).
554
+ automaticCleanup() {
555
+ void deleteApp(this);
556
+ }
557
+ get settings() {
558
+ this.checkDestroyed();
559
+ return this._serverConfig;
560
+ }
561
+ /**
562
+ * This function will throw an Error if the App has already been deleted -
563
+ * use before performing API actions on the App.
564
+ */
565
+ checkDestroyed() {
566
+ if (this.isDeleted) {
567
+ throw ERROR_FACTORY.create("server-app-deleted" /* AppError.SERVER_APP_DELETED */);
568
+ }
569
+ }
570
+ }
571
+
572
+ /**
573
+ * @license
574
+ * Copyright 2019 Google LLC
575
+ *
576
+ * Licensed under the Apache License, Version 2.0 (the "License");
577
+ * you may not use this file except in compliance with the License.
578
+ * You may obtain a copy of the License at
579
+ *
580
+ * http://www.apache.org/licenses/LICENSE-2.0
581
+ *
582
+ * Unless required by applicable law or agreed to in writing, software
583
+ * distributed under the License is distributed on an "AS IS" BASIS,
584
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
585
+ * See the License for the specific language governing permissions and
586
+ * limitations under the License.
587
+ */
588
+ /**
589
+ * The current SDK version.
590
+ *
591
+ * @public
592
+ */
593
+ const SDK_VERSION = version;
594
+ function initializeApp(_options, rawConfig = {}) {
595
+ let options = _options;
596
+ if (typeof rawConfig !== 'object') {
597
+ const name = rawConfig;
598
+ rawConfig = { name };
599
+ }
600
+ const config = {
601
+ name: DEFAULT_ENTRY_NAME,
602
+ automaticDataCollectionEnabled: true,
603
+ ...rawConfig
604
+ };
605
+ const name = config.name;
606
+ if (typeof name !== 'string' || !name) {
607
+ throw ERROR_FACTORY.create("bad-app-name" /* AppError.BAD_APP_NAME */, {
608
+ appName: String(name)
609
+ });
610
+ }
611
+ options || (options = getDefaultAppConfig());
612
+ if (!options) {
613
+ throw ERROR_FACTORY.create("no-options" /* AppError.NO_OPTIONS */);
614
+ }
615
+ const existingApp = _apps.get(name);
616
+ if (existingApp) {
617
+ // return the existing app if options and config deep equal the ones in the existing app.
618
+ if (deepEqual(options, existingApp.options) &&
619
+ deepEqual(config, existingApp.config)) {
620
+ return existingApp;
621
+ }
622
+ else {
623
+ throw ERROR_FACTORY.create("duplicate-app" /* AppError.DUPLICATE_APP */, { appName: name });
624
+ }
625
+ }
626
+ const container = new ComponentContainer(name);
627
+ for (const component of _components.values()) {
628
+ container.addComponent(component);
629
+ }
630
+ const newApp = new FirebaseAppImpl(options, config, container);
631
+ _apps.set(name, newApp);
632
+ return newApp;
633
+ }
634
+ function initializeServerApp(_options, _serverAppConfig = {}) {
635
+ if (isBrowser() && !isWebWorker()) {
636
+ // FirebaseServerApp isn't designed to be run in browsers.
637
+ throw ERROR_FACTORY.create("invalid-server-app-environment" /* AppError.INVALID_SERVER_APP_ENVIRONMENT */);
638
+ }
639
+ let firebaseOptions;
640
+ let serverAppSettings = _serverAppConfig || {};
641
+ if (_options) {
642
+ if (_isFirebaseApp(_options)) {
643
+ firebaseOptions = _options.options;
644
+ }
645
+ else if (_isFirebaseServerAppSettings(_options)) {
646
+ serverAppSettings = _options;
647
+ }
648
+ else {
649
+ firebaseOptions = _options;
650
+ }
651
+ }
652
+ if (serverAppSettings.automaticDataCollectionEnabled === undefined) {
653
+ serverAppSettings.automaticDataCollectionEnabled = true;
654
+ }
655
+ firebaseOptions || (firebaseOptions = getDefaultAppConfig());
656
+ if (!firebaseOptions) {
657
+ throw ERROR_FACTORY.create("no-options" /* AppError.NO_OPTIONS */);
658
+ }
659
+ // Build an app name based on a hash of the configuration options.
660
+ const nameObj = {
661
+ ...serverAppSettings,
662
+ ...firebaseOptions
663
+ };
664
+ // However, Do not mangle the name based on releaseOnDeref, since it will vary between the
665
+ // construction of FirebaseServerApp instances. For example, if the object is the request headers.
666
+ if (nameObj.releaseOnDeref !== undefined) {
667
+ delete nameObj.releaseOnDeref;
668
+ }
669
+ const hashCode = (s) => {
670
+ return [...s].reduce((hash, c) => (Math.imul(31, hash) + c.charCodeAt(0)) | 0, 0);
671
+ };
672
+ if (serverAppSettings.releaseOnDeref !== undefined) {
673
+ if (typeof FinalizationRegistry === 'undefined') {
674
+ throw ERROR_FACTORY.create("finalization-registry-not-supported" /* AppError.FINALIZATION_REGISTRY_NOT_SUPPORTED */, {});
675
+ }
676
+ }
677
+ const nameString = '' + hashCode(JSON.stringify(nameObj));
678
+ const existingApp = _serverApps.get(nameString);
679
+ if (existingApp) {
680
+ existingApp.incRefCount(serverAppSettings.releaseOnDeref);
681
+ return existingApp;
682
+ }
683
+ const container = new ComponentContainer(nameString);
684
+ for (const component of _components.values()) {
685
+ container.addComponent(component);
686
+ }
687
+ const newApp = new FirebaseServerAppImpl(firebaseOptions, serverAppSettings, nameString, container);
688
+ _serverApps.set(nameString, newApp);
689
+ return newApp;
690
+ }
691
+ /**
692
+ * Retrieves a {@link @firebase/app#FirebaseApp} instance.
693
+ *
694
+ * When called with no arguments, the default app is returned. When an app name
695
+ * is provided, the app corresponding to that name is returned.
696
+ *
697
+ * An exception is thrown if the app being retrieved has not yet been
698
+ * initialized.
699
+ *
700
+ * @example
701
+ * ```javascript
702
+ * // Return the default app
703
+ * const app = getApp();
704
+ * ```
705
+ *
706
+ * @example
707
+ * ```javascript
708
+ * // Return a named app
709
+ * const otherApp = getApp("otherApp");
710
+ * ```
711
+ *
712
+ * @param name - Optional name of the app to return. If no name is
713
+ * provided, the default is `"[DEFAULT]"`.
714
+ *
715
+ * @returns The app corresponding to the provided app name.
716
+ * If no app name is provided, the default app is returned.
717
+ *
718
+ * @public
719
+ */
720
+ function getApp(name = DEFAULT_ENTRY_NAME) {
721
+ const app = _apps.get(name);
722
+ if (!app && name === DEFAULT_ENTRY_NAME && getDefaultAppConfig()) {
723
+ return initializeApp();
724
+ }
725
+ if (!app) {
726
+ throw ERROR_FACTORY.create("no-app" /* AppError.NO_APP */, { appName: name });
727
+ }
728
+ return app;
729
+ }
730
+ /**
731
+ * A (read-only) array of all initialized apps.
732
+ * @public
733
+ */
734
+ function getApps() {
735
+ return Array.from(_apps.values());
736
+ }
737
+ /**
738
+ * Renders this app unusable and frees the resources of all associated
739
+ * services.
740
+ *
741
+ * @example
742
+ * ```javascript
743
+ * deleteApp(app)
744
+ * .then(function() {
745
+ * console.log("App deleted successfully");
746
+ * })
747
+ * .catch(function(error) {
748
+ * console.log("Error deleting app:", error);
749
+ * });
750
+ * ```
751
+ *
752
+ * @public
753
+ */
754
+ async function deleteApp(app) {
755
+ let cleanupProviders = false;
756
+ const name = app.name;
757
+ if (_apps.has(name)) {
758
+ cleanupProviders = true;
759
+ _apps.delete(name);
760
+ }
761
+ else if (_serverApps.has(name)) {
762
+ const firebaseServerApp = app;
763
+ if (firebaseServerApp.decRefCount() <= 0) {
764
+ _serverApps.delete(name);
765
+ cleanupProviders = true;
766
+ }
767
+ }
768
+ if (cleanupProviders) {
769
+ await Promise.all(app.container
770
+ .getProviders()
771
+ .map(provider => provider.delete()));
772
+ app.isDeleted = true;
773
+ }
774
+ }
775
+ /**
776
+ * Registers a library's name and version for platform logging purposes.
777
+ * @param library - Name of 1p or 3p library (e.g. firestore, angularfire)
778
+ * @param version - Current version of that library.
779
+ * @param variant - Bundle variant, e.g., node, rn, etc.
780
+ *
781
+ * @public
782
+ */
783
+ function registerVersion(libraryKeyOrName, version, variant) {
784
+ // TODO: We can use this check to whitelist strings when/if we set up
785
+ // a good whitelist system.
786
+ let library = PLATFORM_LOG_STRING[libraryKeyOrName] ?? libraryKeyOrName;
787
+ if (variant) {
788
+ library += `-${variant}`;
789
+ }
790
+ const libraryMismatch = library.match(/\s|\//);
791
+ const versionMismatch = version.match(/\s|\//);
792
+ if (libraryMismatch || versionMismatch) {
793
+ const warning = [
794
+ `Unable to register library "${library}" with version "${version}":`
795
+ ];
796
+ if (libraryMismatch) {
797
+ warning.push(`library name "${library}" contains illegal characters (whitespace or "/")`);
798
+ }
799
+ if (libraryMismatch && versionMismatch) {
800
+ warning.push('and');
801
+ }
802
+ if (versionMismatch) {
803
+ warning.push(`version name "${version}" contains illegal characters (whitespace or "/")`);
804
+ }
805
+ logger.warn(warning.join(' '));
806
+ return;
807
+ }
808
+ _registerComponent(new Component(`${library}-version`, () => ({ library, version }), "VERSION" /* ComponentType.VERSION */));
809
+ }
810
+ /**
811
+ * Sets log handler for all Firebase SDKs.
812
+ * @param logCallback - An optional custom log handler that executes user code whenever
813
+ * the Firebase SDK makes a logging call.
814
+ *
815
+ * @public
816
+ */
817
+ function onLog(logCallback, options) {
818
+ if (logCallback !== null && typeof logCallback !== 'function') {
819
+ throw ERROR_FACTORY.create("invalid-log-argument" /* AppError.INVALID_LOG_ARGUMENT */);
820
+ }
821
+ setUserLogHandler(logCallback, options);
822
+ }
823
+ /**
824
+ * Sets log level for all Firebase SDKs.
825
+ *
826
+ * All of the log types above the current log level are captured (i.e. if
827
+ * you set the log level to `info`, errors are logged, but `debug` and
828
+ * `verbose` logs are not).
829
+ *
830
+ * @public
831
+ */
832
+ function setLogLevel(logLevel) {
833
+ setLogLevel$1(logLevel);
834
+ }
835
+
836
+ /**
837
+ * @license
838
+ * Copyright 2021 Google LLC
839
+ *
840
+ * Licensed under the Apache License, Version 2.0 (the "License");
841
+ * you may not use this file except in compliance with the License.
842
+ * You may obtain a copy of the License at
843
+ *
844
+ * http://www.apache.org/licenses/LICENSE-2.0
845
+ *
846
+ * Unless required by applicable law or agreed to in writing, software
847
+ * distributed under the License is distributed on an "AS IS" BASIS,
848
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
849
+ * See the License for the specific language governing permissions and
850
+ * limitations under the License.
851
+ */
852
+ const DB_NAME = 'firebase-heartbeat-database';
853
+ const DB_VERSION = 1;
854
+ const STORE_NAME = 'firebase-heartbeat-store';
855
+ let dbPromise = null;
856
+ function getDbPromise() {
857
+ if (!dbPromise) {
858
+ dbPromise = openDB(DB_NAME, DB_VERSION, {
859
+ upgrade: (db, oldVersion) => {
860
+ // We don't use 'break' in this switch statement, the fall-through
861
+ // behavior is what we want, because if there are multiple versions between
862
+ // the old version and the current version, we want ALL the migrations
863
+ // that correspond to those versions to run, not only the last one.
864
+ // eslint-disable-next-line default-case
865
+ switch (oldVersion) {
866
+ case 0:
867
+ try {
868
+ db.createObjectStore(STORE_NAME);
869
+ }
870
+ catch (e) {
871
+ // Safari/iOS browsers throw occasional exceptions on
872
+ // db.createObjectStore() that may be a bug. Avoid blocking
873
+ // the rest of the app functionality.
874
+ console.warn(e);
875
+ }
876
+ }
877
+ }
878
+ }).catch(e => {
879
+ throw ERROR_FACTORY.create("idb-open" /* AppError.IDB_OPEN */, {
880
+ originalErrorMessage: e.message
881
+ });
882
+ });
883
+ }
884
+ return dbPromise;
885
+ }
886
+ async function readHeartbeatsFromIndexedDB(app) {
887
+ try {
888
+ const db = await getDbPromise();
889
+ const tx = db.transaction(STORE_NAME);
890
+ const result = await tx.objectStore(STORE_NAME).get(computeKey(app));
891
+ // We already have the value but tx.done can throw,
892
+ // so we need to await it here to catch errors
893
+ await tx.done;
894
+ return result;
895
+ }
896
+ catch (e) {
897
+ if (e instanceof FirebaseError) {
898
+ logger.warn(e.message);
899
+ }
900
+ else {
901
+ const idbGetError = ERROR_FACTORY.create("idb-get" /* AppError.IDB_GET */, {
902
+ originalErrorMessage: e?.message
903
+ });
904
+ logger.warn(idbGetError.message);
905
+ }
906
+ }
907
+ }
908
+ async function writeHeartbeatsToIndexedDB(app, heartbeatObject) {
909
+ try {
910
+ const db = await getDbPromise();
911
+ const tx = db.transaction(STORE_NAME, 'readwrite');
912
+ const objectStore = tx.objectStore(STORE_NAME);
913
+ await objectStore.put(heartbeatObject, computeKey(app));
914
+ await tx.done;
915
+ }
916
+ catch (e) {
917
+ if (e instanceof FirebaseError) {
918
+ logger.warn(e.message);
919
+ }
920
+ else {
921
+ const idbGetError = ERROR_FACTORY.create("idb-set" /* AppError.IDB_WRITE */, {
922
+ originalErrorMessage: e?.message
923
+ });
924
+ logger.warn(idbGetError.message);
925
+ }
926
+ }
927
+ }
928
+ function computeKey(app) {
929
+ return `${app.name}!${app.options.appId}`;
930
+ }
931
+
932
+ /**
933
+ * @license
934
+ * Copyright 2021 Google LLC
935
+ *
936
+ * Licensed under the Apache License, Version 2.0 (the "License");
937
+ * you may not use this file except in compliance with the License.
938
+ * You may obtain a copy of the License at
939
+ *
940
+ * http://www.apache.org/licenses/LICENSE-2.0
941
+ *
942
+ * Unless required by applicable law or agreed to in writing, software
943
+ * distributed under the License is distributed on an "AS IS" BASIS,
944
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
945
+ * See the License for the specific language governing permissions and
946
+ * limitations under the License.
947
+ */
948
+ const MAX_HEADER_BYTES = 1024;
949
+ const MAX_NUM_STORED_HEARTBEATS = 30;
950
+ class HeartbeatServiceImpl {
951
+ constructor(container) {
952
+ this.container = container;
953
+ /**
954
+ * In-memory cache for heartbeats, used by getHeartbeatsHeader() to generate
955
+ * the header string.
956
+ * Stores one record per date. This will be consolidated into the standard
957
+ * format of one record per user agent string before being sent as a header.
958
+ * Populated from indexedDB when the controller is instantiated and should
959
+ * be kept in sync with indexedDB.
960
+ * Leave public for easier testing.
961
+ */
962
+ this._heartbeatsCache = null;
963
+ const app = this.container.getProvider('app').getImmediate();
964
+ this._storage = new HeartbeatStorageImpl(app);
965
+ this._heartbeatsCachePromise = this._storage.read().then(result => {
966
+ this._heartbeatsCache = result;
967
+ return result;
968
+ });
969
+ }
970
+ /**
971
+ * Called to report a heartbeat. The function will generate
972
+ * a HeartbeatsByUserAgent object, update heartbeatsCache, and persist it
973
+ * to IndexedDB.
974
+ * Note that we only store one heartbeat per day. So if a heartbeat for today is
975
+ * already logged, subsequent calls to this function in the same day will be ignored.
976
+ */
977
+ async triggerHeartbeat() {
978
+ try {
979
+ const platformLogger = this.container
980
+ .getProvider('platform-logger')
981
+ .getImmediate();
982
+ // This is the "Firebase user agent" string from the platform logger
983
+ // service, not the browser user agent.
984
+ const agent = platformLogger.getPlatformInfoString();
985
+ const date = getUTCDateString();
986
+ if (this._heartbeatsCache?.heartbeats == null) {
987
+ this._heartbeatsCache = await this._heartbeatsCachePromise;
988
+ // If we failed to construct a heartbeats cache, then return immediately.
989
+ if (this._heartbeatsCache?.heartbeats == null) {
990
+ return;
991
+ }
992
+ }
993
+ // Do not store a heartbeat if one is already stored for this day
994
+ // or if a header has already been sent today.
995
+ if (this._heartbeatsCache.lastSentHeartbeatDate === date ||
996
+ this._heartbeatsCache.heartbeats.some(singleDateHeartbeat => singleDateHeartbeat.date === date)) {
997
+ return;
998
+ }
999
+ else {
1000
+ // There is no entry for this date. Create one.
1001
+ this._heartbeatsCache.heartbeats.push({ date, agent });
1002
+ // If the number of stored heartbeats exceeds the maximum number of stored heartbeats, remove the heartbeat with the earliest date.
1003
+ // Since this is executed each time a heartbeat is pushed, the limit can only be exceeded by one, so only one needs to be removed.
1004
+ if (this._heartbeatsCache.heartbeats.length > MAX_NUM_STORED_HEARTBEATS) {
1005
+ const earliestHeartbeatIdx = getEarliestHeartbeatIdx(this._heartbeatsCache.heartbeats);
1006
+ this._heartbeatsCache.heartbeats.splice(earliestHeartbeatIdx, 1);
1007
+ }
1008
+ }
1009
+ return this._storage.overwrite(this._heartbeatsCache);
1010
+ }
1011
+ catch (e) {
1012
+ logger.warn(e);
1013
+ }
1014
+ }
1015
+ /**
1016
+ * Returns a base64 encoded string which can be attached to the heartbeat-specific header directly.
1017
+ * It also clears all heartbeats from memory as well as in IndexedDB.
1018
+ *
1019
+ * NOTE: Consuming product SDKs should not send the header if this method
1020
+ * returns an empty string.
1021
+ */
1022
+ async getHeartbeatsHeader() {
1023
+ try {
1024
+ if (this._heartbeatsCache === null) {
1025
+ await this._heartbeatsCachePromise;
1026
+ }
1027
+ // If it's still null or the array is empty, there is no data to send.
1028
+ if (this._heartbeatsCache?.heartbeats == null ||
1029
+ this._heartbeatsCache.heartbeats.length === 0) {
1030
+ return '';
1031
+ }
1032
+ const date = getUTCDateString();
1033
+ // Extract as many heartbeats from the cache as will fit under the size limit.
1034
+ const { heartbeatsToSend, unsentEntries } = extractHeartbeatsForHeader(this._heartbeatsCache.heartbeats);
1035
+ const headerString = base64urlEncodeWithoutPadding(JSON.stringify({ version: 2, heartbeats: heartbeatsToSend }));
1036
+ // Store last sent date to prevent another being logged/sent for the same day.
1037
+ this._heartbeatsCache.lastSentHeartbeatDate = date;
1038
+ if (unsentEntries.length > 0) {
1039
+ // Store any unsent entries if they exist.
1040
+ this._heartbeatsCache.heartbeats = unsentEntries;
1041
+ // This seems more likely than emptying the array (below) to lead to some odd state
1042
+ // since the cache isn't empty and this will be called again on the next request,
1043
+ // and is probably safest if we await it.
1044
+ await this._storage.overwrite(this._heartbeatsCache);
1045
+ }
1046
+ else {
1047
+ this._heartbeatsCache.heartbeats = [];
1048
+ // Do not wait for this, to reduce latency.
1049
+ void this._storage.overwrite(this._heartbeatsCache);
1050
+ }
1051
+ return headerString;
1052
+ }
1053
+ catch (e) {
1054
+ logger.warn(e);
1055
+ return '';
1056
+ }
1057
+ }
1058
+ }
1059
+ function getUTCDateString() {
1060
+ const today = new Date();
1061
+ // Returns date format 'YYYY-MM-DD'
1062
+ return today.toISOString().substring(0, 10);
1063
+ }
1064
+ function extractHeartbeatsForHeader(heartbeatsCache, maxSize = MAX_HEADER_BYTES) {
1065
+ // Heartbeats grouped by user agent in the standard format to be sent in
1066
+ // the header.
1067
+ const heartbeatsToSend = [];
1068
+ // Single date format heartbeats that are not sent.
1069
+ let unsentEntries = heartbeatsCache.slice();
1070
+ for (const singleDateHeartbeat of heartbeatsCache) {
1071
+ // Look for an existing entry with the same user agent.
1072
+ const heartbeatEntry = heartbeatsToSend.find(hb => hb.agent === singleDateHeartbeat.agent);
1073
+ if (!heartbeatEntry) {
1074
+ // If no entry for this user agent exists, create one.
1075
+ heartbeatsToSend.push({
1076
+ agent: singleDateHeartbeat.agent,
1077
+ dates: [singleDateHeartbeat.date]
1078
+ });
1079
+ if (countBytes(heartbeatsToSend) > maxSize) {
1080
+ // If the header would exceed max size, remove the added heartbeat
1081
+ // entry and stop adding to the header.
1082
+ heartbeatsToSend.pop();
1083
+ break;
1084
+ }
1085
+ }
1086
+ else {
1087
+ heartbeatEntry.dates.push(singleDateHeartbeat.date);
1088
+ // If the header would exceed max size, remove the added date
1089
+ // and stop adding to the header.
1090
+ if (countBytes(heartbeatsToSend) > maxSize) {
1091
+ heartbeatEntry.dates.pop();
1092
+ break;
1093
+ }
1094
+ }
1095
+ // Pop unsent entry from queue. (Skipped if adding the entry exceeded
1096
+ // quota and the loop breaks early.)
1097
+ unsentEntries = unsentEntries.slice(1);
1098
+ }
1099
+ return {
1100
+ heartbeatsToSend,
1101
+ unsentEntries
1102
+ };
1103
+ }
1104
+ class HeartbeatStorageImpl {
1105
+ constructor(app) {
1106
+ this.app = app;
1107
+ this._canUseIndexedDBPromise = this.runIndexedDBEnvironmentCheck();
1108
+ }
1109
+ async runIndexedDBEnvironmentCheck() {
1110
+ if (!isIndexedDBAvailable()) {
1111
+ return false;
1112
+ }
1113
+ else {
1114
+ return validateIndexedDBOpenable()
1115
+ .then(() => true)
1116
+ .catch(() => false);
1117
+ }
1118
+ }
1119
+ /**
1120
+ * Read all heartbeats.
1121
+ */
1122
+ async read() {
1123
+ const canUseIndexedDB = await this._canUseIndexedDBPromise;
1124
+ if (!canUseIndexedDB) {
1125
+ return { heartbeats: [] };
1126
+ }
1127
+ else {
1128
+ const idbHeartbeatObject = await readHeartbeatsFromIndexedDB(this.app);
1129
+ if (idbHeartbeatObject?.heartbeats) {
1130
+ return idbHeartbeatObject;
1131
+ }
1132
+ else {
1133
+ return { heartbeats: [] };
1134
+ }
1135
+ }
1136
+ }
1137
+ // overwrite the storage with the provided heartbeats
1138
+ async overwrite(heartbeatsObject) {
1139
+ const canUseIndexedDB = await this._canUseIndexedDBPromise;
1140
+ if (!canUseIndexedDB) {
1141
+ return;
1142
+ }
1143
+ else {
1144
+ const existingHeartbeatsObject = await this.read();
1145
+ return writeHeartbeatsToIndexedDB(this.app, {
1146
+ lastSentHeartbeatDate: heartbeatsObject.lastSentHeartbeatDate ??
1147
+ existingHeartbeatsObject.lastSentHeartbeatDate,
1148
+ heartbeats: heartbeatsObject.heartbeats
1149
+ });
1150
+ }
1151
+ }
1152
+ // add heartbeats
1153
+ async add(heartbeatsObject) {
1154
+ const canUseIndexedDB = await this._canUseIndexedDBPromise;
1155
+ if (!canUseIndexedDB) {
1156
+ return;
1157
+ }
1158
+ else {
1159
+ const existingHeartbeatsObject = await this.read();
1160
+ return writeHeartbeatsToIndexedDB(this.app, {
1161
+ lastSentHeartbeatDate: heartbeatsObject.lastSentHeartbeatDate ??
1162
+ existingHeartbeatsObject.lastSentHeartbeatDate,
1163
+ heartbeats: [
1164
+ ...existingHeartbeatsObject.heartbeats,
1165
+ ...heartbeatsObject.heartbeats
1166
+ ]
1167
+ });
1168
+ }
1169
+ }
1170
+ }
1171
+ /**
1172
+ * Calculate bytes of a HeartbeatsByUserAgent array after being wrapped
1173
+ * in a platform logging header JSON object, stringified, and converted
1174
+ * to base 64.
1175
+ */
1176
+ function countBytes(heartbeatsCache) {
1177
+ // base64 has a restricted set of characters, all of which should be 1 byte.
1178
+ return base64urlEncodeWithoutPadding(
1179
+ // heartbeatsCache wrapper properties
1180
+ JSON.stringify({ version: 2, heartbeats: heartbeatsCache })).length;
1181
+ }
1182
+ /**
1183
+ * Returns the index of the heartbeat with the earliest date.
1184
+ * If the heartbeats array is empty, -1 is returned.
1185
+ */
1186
+ function getEarliestHeartbeatIdx(heartbeats) {
1187
+ if (heartbeats.length === 0) {
1188
+ return -1;
1189
+ }
1190
+ let earliestHeartbeatIdx = 0;
1191
+ let earliestHeartbeatDate = heartbeats[0].date;
1192
+ for (let i = 1; i < heartbeats.length; i++) {
1193
+ if (heartbeats[i].date < earliestHeartbeatDate) {
1194
+ earliestHeartbeatDate = heartbeats[i].date;
1195
+ earliestHeartbeatIdx = i;
1196
+ }
1197
+ }
1198
+ return earliestHeartbeatIdx;
1199
+ }
1200
+
1201
+ /**
1202
+ * @license
1203
+ * Copyright 2019 Google LLC
1204
+ *
1205
+ * Licensed under the Apache License, Version 2.0 (the "License");
1206
+ * you may not use this file except in compliance with the License.
1207
+ * You may obtain a copy of the License at
1208
+ *
1209
+ * http://www.apache.org/licenses/LICENSE-2.0
1210
+ *
1211
+ * Unless required by applicable law or agreed to in writing, software
1212
+ * distributed under the License is distributed on an "AS IS" BASIS,
1213
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1214
+ * See the License for the specific language governing permissions and
1215
+ * limitations under the License.
1216
+ */
1217
+ function registerCoreComponents(variant) {
1218
+ _registerComponent(new Component('platform-logger', container => new PlatformLoggerServiceImpl(container), "PRIVATE" /* ComponentType.PRIVATE */));
1219
+ _registerComponent(new Component('heartbeat', container => new HeartbeatServiceImpl(container), "PRIVATE" /* ComponentType.PRIVATE */));
1220
+ // Register `app` package.
1221
+ registerVersion(name$q, version$1, variant);
1222
+ // BUILD_TARGET will be replaced by values like esm, cjs, etc during the compilation
1223
+ registerVersion(name$q, version$1, 'esm2020');
1224
+ // Register platform SDK identifier (no version).
1225
+ registerVersion('fire-js', '');
1226
+ }
1227
+
1228
+ /**
1229
+ * Firebase App
1230
+ *
1231
+ * @remarks This package coordinates the communication between the different Firebase components
1232
+ * @packageDocumentation
1233
+ */
1234
+ registerCoreComponents('');
1235
+
1236
+ export { SDK_VERSION, DEFAULT_ENTRY_NAME as _DEFAULT_ENTRY_NAME, _addComponent, _addOrOverwriteComponent, _apps, _clearComponents, _components, _getProvider, _isFirebaseApp, _isFirebaseServerApp, _isFirebaseServerAppSettings, _registerComponent, _removeServiceInstance, _serverApps, deleteApp, getApp, getApps, initializeApp, initializeServerApp, onLog, registerVersion, setLogLevel };
1237
+ //# sourceMappingURL=index.esm.js.map