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