@firebase/app 0.7.17 → 0.7.18-20222320822

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.
@@ -1,8 +1,9 @@
1
1
  import { Component, ComponentContainer } from '@firebase/component';
2
- import { __values, __assign, __awaiter, __generator } from 'tslib';
2
+ import { __values, __assign, __awaiter, __generator, __spreadArray, __read } from 'tslib';
3
3
  import { Logger, setUserLogHandler, setLogLevel as setLogLevel$1 } from '@firebase/logger';
4
- import { ErrorFactory, deepEqual } from '@firebase/util';
4
+ import { ErrorFactory, deepEqual, base64Encode, isIndexedDBAvailable, validateIndexedDBOpenable } from '@firebase/util';
5
5
  export { FirebaseError } from '@firebase/util';
6
+ import { openDb } from 'idb';
6
7
 
7
8
  /**
8
9
  * @license
@@ -59,7 +60,7 @@ function isVersionServiceProvider(provider) {
59
60
  }
60
61
 
61
62
  var name$o = "@firebase/app";
62
- var version$1 = "0.7.17";
63
+ var version$1 = "0.7.18-20222320822";
63
64
 
64
65
  /**
65
66
  * @license
@@ -126,7 +127,7 @@ var name$2 = "@firebase/firestore";
126
127
  var name$1 = "@firebase/firestore-compat";
127
128
 
128
129
  var name = "firebase";
129
- var version = "9.6.7";
130
+ var version = "9.6.8-20222320822";
130
131
 
131
132
  /**
132
133
  * @license
@@ -268,6 +269,12 @@ function _registerComponent(component) {
268
269
  * @internal
269
270
  */
270
271
  function _getProvider(app, name) {
272
+ var heartbeatController = app.container
273
+ .getProvider('heartbeat')
274
+ .getImmediate({ optional: true });
275
+ if (heartbeatController) {
276
+ void heartbeatController.triggerHeartbeat();
277
+ }
271
278
  return app.container.getProvider(name);
272
279
  }
273
280
  /**
@@ -317,6 +324,10 @@ var ERRORS = (_a = {},
317
324
  _a["invalid-app-argument" /* INVALID_APP_ARGUMENT */] = 'firebase.{$appName}() takes either no argument or a ' +
318
325
  'Firebase App instance.',
319
326
  _a["invalid-log-argument" /* INVALID_LOG_ARGUMENT */] = 'First argument to `onLog` must be null or a function.',
327
+ _a["storage-open" /* STORAGE_OPEN */] = 'Error thrown when opening storage. Original error: {$originalErrorMessage}.',
328
+ _a["storage-get" /* STORAGE_GET */] = 'Error thrown when reading from storage. Original error: {$originalErrorMessage}.',
329
+ _a["storage-set" /* STORAGE_WRITE */] = 'Error thrown when writing to storage. Original error: {$originalErrorMessage}.',
330
+ _a["storage-delete" /* STORAGE_DELETE */] = 'Error thrown when deleting from storage. Original error: {$originalErrorMessage}.',
320
331
  _a);
321
332
  var ERROR_FACTORY = new ErrorFactory('app', 'Firebase', ERRORS);
322
333
 
@@ -622,6 +633,454 @@ function setLogLevel(logLevel) {
622
633
  setLogLevel$1(logLevel);
623
634
  }
624
635
 
636
+ /**
637
+ * @license
638
+ * Copyright 2021 Google LLC
639
+ *
640
+ * Licensed under the Apache License, Version 2.0 (the "License");
641
+ * you may not use this file except in compliance with the License.
642
+ * You may obtain a copy of the License at
643
+ *
644
+ * http://www.apache.org/licenses/LICENSE-2.0
645
+ *
646
+ * Unless required by applicable law or agreed to in writing, software
647
+ * distributed under the License is distributed on an "AS IS" BASIS,
648
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
649
+ * See the License for the specific language governing permissions and
650
+ * limitations under the License.
651
+ */
652
+ var DB_NAME = 'firebase-heartbeat-database';
653
+ var DB_VERSION = 1;
654
+ var STORE_NAME = 'firebase-heartbeat-store';
655
+ var dbPromise = null;
656
+ function getDbPromise() {
657
+ if (!dbPromise) {
658
+ dbPromise = openDb(DB_NAME, DB_VERSION, function (upgradeDB) {
659
+ // We don't use 'break' in this switch statement, the fall-through
660
+ // behavior is what we want, because if there are multiple versions between
661
+ // the old version and the current version, we want ALL the migrations
662
+ // that correspond to those versions to run, not only the last one.
663
+ // eslint-disable-next-line default-case
664
+ switch (upgradeDB.oldVersion) {
665
+ case 0:
666
+ upgradeDB.createObjectStore(STORE_NAME);
667
+ }
668
+ }).catch(function (e) {
669
+ throw ERROR_FACTORY.create("storage-open" /* STORAGE_OPEN */, {
670
+ originalErrorMessage: e.message
671
+ });
672
+ });
673
+ }
674
+ return dbPromise;
675
+ }
676
+ function readHeartbeatsFromIndexedDB(app) {
677
+ return __awaiter(this, void 0, void 0, function () {
678
+ var db, e_1;
679
+ return __generator(this, function (_a) {
680
+ switch (_a.label) {
681
+ case 0:
682
+ _a.trys.push([0, 2, , 3]);
683
+ return [4 /*yield*/, getDbPromise()];
684
+ case 1:
685
+ db = _a.sent();
686
+ return [2 /*return*/, db
687
+ .transaction(STORE_NAME)
688
+ .objectStore(STORE_NAME)
689
+ .get(computeKey(app))];
690
+ case 2:
691
+ e_1 = _a.sent();
692
+ throw ERROR_FACTORY.create("storage-get" /* STORAGE_GET */, {
693
+ originalErrorMessage: e_1.message
694
+ });
695
+ case 3: return [2 /*return*/];
696
+ }
697
+ });
698
+ });
699
+ }
700
+ function writeHeartbeatsToIndexedDB(app, heartbeatObject) {
701
+ return __awaiter(this, void 0, void 0, function () {
702
+ var db, tx, objectStore, e_2;
703
+ return __generator(this, function (_a) {
704
+ switch (_a.label) {
705
+ case 0:
706
+ _a.trys.push([0, 3, , 4]);
707
+ return [4 /*yield*/, getDbPromise()];
708
+ case 1:
709
+ db = _a.sent();
710
+ tx = db.transaction(STORE_NAME, 'readwrite');
711
+ objectStore = tx.objectStore(STORE_NAME);
712
+ return [4 /*yield*/, objectStore.put(heartbeatObject, computeKey(app))];
713
+ case 2:
714
+ _a.sent();
715
+ return [2 /*return*/, tx.complete];
716
+ case 3:
717
+ e_2 = _a.sent();
718
+ throw ERROR_FACTORY.create("storage-set" /* STORAGE_WRITE */, {
719
+ originalErrorMessage: e_2.message
720
+ });
721
+ case 4: return [2 /*return*/];
722
+ }
723
+ });
724
+ });
725
+ }
726
+ function deleteHeartbeatsFromIndexedDB(app) {
727
+ return __awaiter(this, void 0, void 0, function () {
728
+ var db, tx, e_3;
729
+ return __generator(this, function (_a) {
730
+ switch (_a.label) {
731
+ case 0:
732
+ _a.trys.push([0, 3, , 4]);
733
+ return [4 /*yield*/, getDbPromise()];
734
+ case 1:
735
+ db = _a.sent();
736
+ tx = db.transaction(STORE_NAME, 'readwrite');
737
+ return [4 /*yield*/, tx.objectStore(STORE_NAME).delete(computeKey(app))];
738
+ case 2:
739
+ _a.sent();
740
+ return [2 /*return*/, tx.complete];
741
+ case 3:
742
+ e_3 = _a.sent();
743
+ throw ERROR_FACTORY.create("storage-delete" /* STORAGE_DELETE */, {
744
+ originalErrorMessage: e_3.message
745
+ });
746
+ case 4: return [2 /*return*/];
747
+ }
748
+ });
749
+ });
750
+ }
751
+ function computeKey(app) {
752
+ return app.name + "!" + app.options.appId;
753
+ }
754
+
755
+ /**
756
+ * @license
757
+ * Copyright 2021 Google LLC
758
+ *
759
+ * Licensed under the Apache License, Version 2.0 (the "License");
760
+ * you may not use this file except in compliance with the License.
761
+ * You may obtain a copy of the License at
762
+ *
763
+ * http://www.apache.org/licenses/LICENSE-2.0
764
+ *
765
+ * Unless required by applicable law or agreed to in writing, software
766
+ * distributed under the License is distributed on an "AS IS" BASIS,
767
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
768
+ * See the License for the specific language governing permissions and
769
+ * limitations under the License.
770
+ */
771
+ var MAX_HEADER_BYTES = 1024;
772
+ // 30 days
773
+ var STORED_HEARTBEAT_RETENTION_MAX_MILLIS = 30 * 24 * 60 * 60 * 1000;
774
+ var HeartbeatServiceImpl = /** @class */ (function () {
775
+ function HeartbeatServiceImpl(container) {
776
+ var _this = this;
777
+ this.container = container;
778
+ /**
779
+ * In-memory cache for heartbeats, used by getHeartbeatsHeader() to generate
780
+ * the header string.
781
+ * Stores one record per date. This will be consolidated into the standard
782
+ * format of one record per user agent string before being sent as a header.
783
+ * Populated from indexedDB when the controller is instantiated and should
784
+ * be kept in sync with indexedDB.
785
+ * Leave public for easier testing.
786
+ */
787
+ this._heartbeatsCache = null;
788
+ var app = this.container.getProvider('app').getImmediate();
789
+ this._storage = new HeartbeatStorageImpl(app);
790
+ this._heartbeatsCachePromise = this._storage.read().then(function (result) {
791
+ _this._heartbeatsCache = result;
792
+ return result;
793
+ });
794
+ }
795
+ /**
796
+ * Called to report a heartbeat. The function will generate
797
+ * a HeartbeatsByUserAgent object, update heartbeatsCache, and persist it
798
+ * to IndexedDB.
799
+ * Note that we only store one heartbeat per day. So if a heartbeat for today is
800
+ * already logged, subsequent calls to this function in the same day will be ignored.
801
+ */
802
+ HeartbeatServiceImpl.prototype.triggerHeartbeat = function () {
803
+ return __awaiter(this, void 0, void 0, function () {
804
+ var platformLogger, userAgent, date, _a;
805
+ return __generator(this, function (_b) {
806
+ switch (_b.label) {
807
+ case 0:
808
+ platformLogger = this.container
809
+ .getProvider('platform-logger')
810
+ .getImmediate();
811
+ userAgent = platformLogger.getPlatformInfoString();
812
+ date = getUTCDateString();
813
+ if (!(this._heartbeatsCache === null)) return [3 /*break*/, 2];
814
+ _a = this;
815
+ return [4 /*yield*/, this._heartbeatsCachePromise];
816
+ case 1:
817
+ _a._heartbeatsCache = _b.sent();
818
+ _b.label = 2;
819
+ case 2:
820
+ if (this._heartbeatsCache.some(function (singleDateHeartbeat) { return singleDateHeartbeat.date === date; })) {
821
+ // Do not store a heartbeat if one is already stored for this day.
822
+ return [2 /*return*/];
823
+ }
824
+ else {
825
+ // There is no entry for this date. Create one.
826
+ this._heartbeatsCache.push({ date: date, userAgent: userAgent });
827
+ }
828
+ // Remove entries older than 30 days.
829
+ this._heartbeatsCache = this._heartbeatsCache.filter(function (singleDateHeartbeat) {
830
+ var hbTimestamp = new Date(singleDateHeartbeat.date).valueOf();
831
+ var now = Date.now();
832
+ return now - hbTimestamp <= STORED_HEARTBEAT_RETENTION_MAX_MILLIS;
833
+ });
834
+ return [2 /*return*/, this._storage.overwrite(this._heartbeatsCache)];
835
+ }
836
+ });
837
+ });
838
+ };
839
+ /**
840
+ * Returns a base64 encoded string which can be attached to the heartbeat-specific header directly.
841
+ * It also clears all heartbeats from memory as well as in IndexedDB.
842
+ *
843
+ * NOTE: It will read heartbeats from the heartbeatsCache, instead of from indexedDB to reduce latency
844
+ */
845
+ HeartbeatServiceImpl.prototype.getHeartbeatsHeader = function () {
846
+ return __awaiter(this, void 0, void 0, function () {
847
+ var _a, heartbeatsToSend, unsentEntries, headerString;
848
+ return __generator(this, function (_b) {
849
+ switch (_b.label) {
850
+ case 0:
851
+ if (!(this._heartbeatsCache === null)) return [3 /*break*/, 2];
852
+ return [4 /*yield*/, this._heartbeatsCachePromise];
853
+ case 1:
854
+ _b.sent();
855
+ _b.label = 2;
856
+ case 2:
857
+ // If it's still null, it's been cleared and has not been repopulated.
858
+ if (this._heartbeatsCache === null) {
859
+ return [2 /*return*/, ''];
860
+ }
861
+ _a = extractHeartbeatsForHeader(this._heartbeatsCache), heartbeatsToSend = _a.heartbeatsToSend, unsentEntries = _a.unsentEntries;
862
+ headerString = base64Encode(JSON.stringify({ version: 2, heartbeats: heartbeatsToSend }));
863
+ if (!(unsentEntries.length > 0)) return [3 /*break*/, 4];
864
+ // Store any unsent entries if they exist.
865
+ this._heartbeatsCache = unsentEntries;
866
+ // This seems more likely than deleteAll (below) to lead to some odd state
867
+ // since the cache isn't empty and this will be called again on the next request,
868
+ // and is probably safest if we await it.
869
+ return [4 /*yield*/, this._storage.overwrite(this._heartbeatsCache)];
870
+ case 3:
871
+ // This seems more likely than deleteAll (below) to lead to some odd state
872
+ // since the cache isn't empty and this will be called again on the next request,
873
+ // and is probably safest if we await it.
874
+ _b.sent();
875
+ return [3 /*break*/, 5];
876
+ case 4:
877
+ this._heartbeatsCache = null;
878
+ // Do not wait for this, to reduce latency.
879
+ void this._storage.deleteAll();
880
+ _b.label = 5;
881
+ case 5: return [2 /*return*/, headerString];
882
+ }
883
+ });
884
+ });
885
+ };
886
+ return HeartbeatServiceImpl;
887
+ }());
888
+ function getUTCDateString() {
889
+ var today = new Date();
890
+ // Returns date format 'YYYY-MM-DD'
891
+ return today.toISOString().substring(0, 10);
892
+ }
893
+ function extractHeartbeatsForHeader(heartbeatsCache, maxSize) {
894
+ var e_1, _a;
895
+ if (maxSize === void 0) { maxSize = MAX_HEADER_BYTES; }
896
+ // Heartbeats grouped by user agent in the standard format to be sent in
897
+ // the header.
898
+ var heartbeatsToSend = [];
899
+ // Single date format heartbeats that are not sent.
900
+ var unsentEntries = heartbeatsCache.slice();
901
+ var _loop_1 = function (singleDateHeartbeat) {
902
+ // Look for an existing entry with the same user agent.
903
+ var heartbeatEntry = heartbeatsToSend.find(function (hb) { return hb.userAgent === singleDateHeartbeat.userAgent; });
904
+ if (!heartbeatEntry) {
905
+ // If no entry for this user agent exists, create one.
906
+ heartbeatsToSend.push({
907
+ userAgent: singleDateHeartbeat.userAgent,
908
+ dates: [singleDateHeartbeat.date]
909
+ });
910
+ if (countBytes(heartbeatsToSend) > maxSize) {
911
+ // If the header would exceed max size, remove the added heartbeat
912
+ // entry and stop adding to the header.
913
+ heartbeatsToSend.pop();
914
+ return "break";
915
+ }
916
+ }
917
+ else {
918
+ heartbeatEntry.dates.push(singleDateHeartbeat.date);
919
+ // If the header would exceed max size, remove the added date
920
+ // and stop adding to the header.
921
+ if (countBytes(heartbeatsToSend) > maxSize) {
922
+ heartbeatEntry.dates.pop();
923
+ return "break";
924
+ }
925
+ }
926
+ // Pop unsent entry from queue. (Skipped if adding the entry exceeded
927
+ // quota and the loop breaks early.)
928
+ unsentEntries = unsentEntries.slice(1);
929
+ };
930
+ try {
931
+ for (var heartbeatsCache_1 = __values(heartbeatsCache), heartbeatsCache_1_1 = heartbeatsCache_1.next(); !heartbeatsCache_1_1.done; heartbeatsCache_1_1 = heartbeatsCache_1.next()) {
932
+ var singleDateHeartbeat = heartbeatsCache_1_1.value;
933
+ var state_1 = _loop_1(singleDateHeartbeat);
934
+ if (state_1 === "break")
935
+ break;
936
+ }
937
+ }
938
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
939
+ finally {
940
+ try {
941
+ if (heartbeatsCache_1_1 && !heartbeatsCache_1_1.done && (_a = heartbeatsCache_1.return)) _a.call(heartbeatsCache_1);
942
+ }
943
+ finally { if (e_1) throw e_1.error; }
944
+ }
945
+ return {
946
+ heartbeatsToSend: heartbeatsToSend,
947
+ unsentEntries: unsentEntries
948
+ };
949
+ }
950
+ var HeartbeatStorageImpl = /** @class */ (function () {
951
+ function HeartbeatStorageImpl(app) {
952
+ this.app = app;
953
+ this._canUseIndexedDBPromise = this.runIndexedDBEnvironmentCheck();
954
+ }
955
+ HeartbeatStorageImpl.prototype.runIndexedDBEnvironmentCheck = function () {
956
+ return __awaiter(this, void 0, void 0, function () {
957
+ return __generator(this, function (_a) {
958
+ if (!isIndexedDBAvailable()) {
959
+ return [2 /*return*/, false];
960
+ }
961
+ else {
962
+ return [2 /*return*/, validateIndexedDBOpenable()
963
+ .then(function () { return true; })
964
+ .catch(function () { return false; })];
965
+ }
966
+ });
967
+ });
968
+ };
969
+ /**
970
+ * Read all heartbeats.
971
+ */
972
+ HeartbeatStorageImpl.prototype.read = function () {
973
+ return __awaiter(this, void 0, void 0, function () {
974
+ var canUseIndexedDB, idbHeartbeatObject;
975
+ return __generator(this, function (_a) {
976
+ switch (_a.label) {
977
+ case 0: return [4 /*yield*/, this._canUseIndexedDBPromise];
978
+ case 1:
979
+ canUseIndexedDB = _a.sent();
980
+ if (!!canUseIndexedDB) return [3 /*break*/, 2];
981
+ return [2 /*return*/, []];
982
+ case 2: return [4 /*yield*/, readHeartbeatsFromIndexedDB(this.app)];
983
+ case 3:
984
+ idbHeartbeatObject = _a.sent();
985
+ return [2 /*return*/, (idbHeartbeatObject === null || idbHeartbeatObject === void 0 ? void 0 : idbHeartbeatObject.heartbeats) || []];
986
+ }
987
+ });
988
+ });
989
+ };
990
+ // overwrite the storage with the provided heartbeats
991
+ HeartbeatStorageImpl.prototype.overwrite = function (heartbeats) {
992
+ return __awaiter(this, void 0, void 0, function () {
993
+ var canUseIndexedDB;
994
+ return __generator(this, function (_a) {
995
+ switch (_a.label) {
996
+ case 0: return [4 /*yield*/, this._canUseIndexedDBPromise];
997
+ case 1:
998
+ canUseIndexedDB = _a.sent();
999
+ if (!canUseIndexedDB) {
1000
+ return [2 /*return*/];
1001
+ }
1002
+ else {
1003
+ return [2 /*return*/, writeHeartbeatsToIndexedDB(this.app, { heartbeats: heartbeats })];
1004
+ }
1005
+ }
1006
+ });
1007
+ });
1008
+ };
1009
+ // add heartbeats
1010
+ HeartbeatStorageImpl.prototype.add = function (heartbeats) {
1011
+ return __awaiter(this, void 0, void 0, function () {
1012
+ var canUseIndexedDB, existingHeartbeats;
1013
+ return __generator(this, function (_a) {
1014
+ switch (_a.label) {
1015
+ case 0: return [4 /*yield*/, this._canUseIndexedDBPromise];
1016
+ case 1:
1017
+ canUseIndexedDB = _a.sent();
1018
+ if (!!canUseIndexedDB) return [3 /*break*/, 2];
1019
+ return [2 /*return*/];
1020
+ case 2: return [4 /*yield*/, this.read()];
1021
+ case 3:
1022
+ existingHeartbeats = _a.sent();
1023
+ return [2 /*return*/, writeHeartbeatsToIndexedDB(this.app, {
1024
+ heartbeats: __spreadArray(__spreadArray([], __read(existingHeartbeats)), __read(heartbeats))
1025
+ })];
1026
+ }
1027
+ });
1028
+ });
1029
+ };
1030
+ // delete heartbeats
1031
+ HeartbeatStorageImpl.prototype.delete = function (heartbeats) {
1032
+ return __awaiter(this, void 0, void 0, function () {
1033
+ var canUseIndexedDB, existingHeartbeats;
1034
+ return __generator(this, function (_a) {
1035
+ switch (_a.label) {
1036
+ case 0: return [4 /*yield*/, this._canUseIndexedDBPromise];
1037
+ case 1:
1038
+ canUseIndexedDB = _a.sent();
1039
+ if (!!canUseIndexedDB) return [3 /*break*/, 2];
1040
+ return [2 /*return*/];
1041
+ case 2: return [4 /*yield*/, this.read()];
1042
+ case 3:
1043
+ existingHeartbeats = _a.sent();
1044
+ return [2 /*return*/, writeHeartbeatsToIndexedDB(this.app, {
1045
+ heartbeats: existingHeartbeats.filter(function (existingHeartbeat) { return !heartbeats.includes(existingHeartbeat); })
1046
+ })];
1047
+ }
1048
+ });
1049
+ });
1050
+ };
1051
+ // delete all heartbeats
1052
+ HeartbeatStorageImpl.prototype.deleteAll = function () {
1053
+ return __awaiter(this, void 0, void 0, function () {
1054
+ var canUseIndexedDB;
1055
+ return __generator(this, function (_a) {
1056
+ switch (_a.label) {
1057
+ case 0: return [4 /*yield*/, this._canUseIndexedDBPromise];
1058
+ case 1:
1059
+ canUseIndexedDB = _a.sent();
1060
+ if (!canUseIndexedDB) {
1061
+ return [2 /*return*/];
1062
+ }
1063
+ else {
1064
+ return [2 /*return*/, deleteHeartbeatsFromIndexedDB(this.app)];
1065
+ }
1066
+ }
1067
+ });
1068
+ });
1069
+ };
1070
+ return HeartbeatStorageImpl;
1071
+ }());
1072
+ /**
1073
+ * Calculate bytes of a HeartbeatsByUserAgent array after being wrapped
1074
+ * in a platform logging header JSON object, stringified, and converted
1075
+ * to base 64.
1076
+ */
1077
+ function countBytes(heartbeatsCache) {
1078
+ // base64 has a restricted set of characters, all of which should be 1 byte.
1079
+ return base64Encode(
1080
+ // heartbeatsCache wrapper properties
1081
+ JSON.stringify({ version: 2, heartbeats: heartbeatsCache })).length;
1082
+ }
1083
+
625
1084
  /**
626
1085
  * @license
627
1086
  * Copyright 2019 Google LLC
@@ -640,6 +1099,7 @@ function setLogLevel(logLevel) {
640
1099
  */
641
1100
  function registerCoreComponents(variant) {
642
1101
  _registerComponent(new Component('platform-logger', function (container) { return new PlatformLoggerServiceImpl(container); }, "PRIVATE" /* PRIVATE */));
1102
+ _registerComponent(new Component('heartbeat', function (container) { return new HeartbeatServiceImpl(container); }, "PRIVATE" /* PRIVATE */));
643
1103
  // Register `app` package.
644
1104
  registerVersion(name$o, version$1, variant);
645
1105
  // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation