@firebase/performance 0.6.9 → 0.6.10

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.
package/dist/index.cjs.js CHANGED
@@ -4,13 +4,12 @@ Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  var util = require('@firebase/util');
6
6
  var logger$1 = require('@firebase/logger');
7
- var tslib = require('tslib');
8
7
  var app = require('@firebase/app');
9
8
  var component = require('@firebase/component');
10
9
  require('@firebase/installations');
11
10
 
12
- var name = "@firebase/performance";
13
- var version = "0.6.9";
11
+ const name = "@firebase/performance";
12
+ const version = "0.6.10";
14
13
 
15
14
  /**
16
15
  * @license
@@ -28,22 +27,22 @@ var version = "0.6.9";
28
27
  * See the License for the specific language governing permissions and
29
28
  * limitations under the License.
30
29
  */
31
- var SDK_VERSION = version;
30
+ const SDK_VERSION = version;
32
31
  /** The prefix for start User Timing marks used for creating Traces. */
33
- var TRACE_START_MARK_PREFIX = 'FB-PERF-TRACE-START';
32
+ const TRACE_START_MARK_PREFIX = 'FB-PERF-TRACE-START';
34
33
  /** The prefix for stop User Timing marks used for creating Traces. */
35
- var TRACE_STOP_MARK_PREFIX = 'FB-PERF-TRACE-STOP';
34
+ const TRACE_STOP_MARK_PREFIX = 'FB-PERF-TRACE-STOP';
36
35
  /** The prefix for User Timing measure used for creating Traces. */
37
- var TRACE_MEASURE_PREFIX = 'FB-PERF-TRACE-MEASURE';
36
+ const TRACE_MEASURE_PREFIX = 'FB-PERF-TRACE-MEASURE';
38
37
  /** The prefix for out of the box page load Trace name. */
39
- var OOB_TRACE_PAGE_LOAD_PREFIX = '_wt_';
40
- var FIRST_PAINT_COUNTER_NAME = '_fp';
41
- var FIRST_CONTENTFUL_PAINT_COUNTER_NAME = '_fcp';
42
- var FIRST_INPUT_DELAY_COUNTER_NAME = '_fid';
43
- var CONFIG_LOCAL_STORAGE_KEY = '@firebase/performance/config';
44
- var CONFIG_EXPIRY_LOCAL_STORAGE_KEY = '@firebase/performance/configexpire';
45
- var SERVICE = 'performance';
46
- var SERVICE_NAME = 'Performance';
38
+ const OOB_TRACE_PAGE_LOAD_PREFIX = '_wt_';
39
+ const FIRST_PAINT_COUNTER_NAME = '_fp';
40
+ const FIRST_CONTENTFUL_PAINT_COUNTER_NAME = '_fcp';
41
+ const FIRST_INPUT_DELAY_COUNTER_NAME = '_fid';
42
+ const CONFIG_LOCAL_STORAGE_KEY = '@firebase/performance/config';
43
+ const CONFIG_EXPIRY_LOCAL_STORAGE_KEY = '@firebase/performance/configexpire';
44
+ const SERVICE = 'performance';
45
+ const SERVICE_NAME = 'Performance';
47
46
 
48
47
  /**
49
48
  * @license
@@ -61,29 +60,28 @@ var SERVICE_NAME = 'Performance';
61
60
  * See the License for the specific language governing permissions and
62
61
  * limitations under the License.
63
62
  */
64
- var _a;
65
- var ERROR_DESCRIPTION_MAP = (_a = {},
66
- _a["trace started" /* ErrorCode.TRACE_STARTED_BEFORE */] = 'Trace {$traceName} was started before.',
67
- _a["trace stopped" /* ErrorCode.TRACE_STOPPED_BEFORE */] = 'Trace {$traceName} is not running.',
68
- _a["nonpositive trace startTime" /* ErrorCode.NONPOSITIVE_TRACE_START_TIME */] = 'Trace {$traceName} startTime should be positive.',
69
- _a["nonpositive trace duration" /* ErrorCode.NONPOSITIVE_TRACE_DURATION */] = 'Trace {$traceName} duration should be positive.',
70
- _a["no window" /* ErrorCode.NO_WINDOW */] = 'Window is not available.',
71
- _a["no app id" /* ErrorCode.NO_APP_ID */] = 'App id is not available.',
72
- _a["no project id" /* ErrorCode.NO_PROJECT_ID */] = 'Project id is not available.',
73
- _a["no api key" /* ErrorCode.NO_API_KEY */] = 'Api key is not available.',
74
- _a["invalid cc log" /* ErrorCode.INVALID_CC_LOG */] = 'Attempted to queue invalid cc event',
75
- _a["FB not default" /* ErrorCode.FB_NOT_DEFAULT */] = 'Performance can only start when Firebase app instance is the default one.',
76
- _a["RC response not ok" /* ErrorCode.RC_NOT_OK */] = 'RC response is not ok',
77
- _a["invalid attribute name" /* ErrorCode.INVALID_ATTRIBUTE_NAME */] = 'Attribute name {$attributeName} is invalid.',
78
- _a["invalid attribute value" /* ErrorCode.INVALID_ATTRIBUTE_VALUE */] = 'Attribute value {$attributeValue} is invalid.',
79
- _a["invalid custom metric name" /* ErrorCode.INVALID_CUSTOM_METRIC_NAME */] = 'Custom metric name {$customMetricName} is invalid',
80
- _a["invalid String merger input" /* ErrorCode.INVALID_STRING_MERGER_PARAMETER */] = 'Input for String merger is invalid, contact support team to resolve.',
81
- _a["already initialized" /* ErrorCode.ALREADY_INITIALIZED */] = 'initializePerformance() has already been called with ' +
63
+ const ERROR_DESCRIPTION_MAP = {
64
+ ["trace started" /* ErrorCode.TRACE_STARTED_BEFORE */]: 'Trace {$traceName} was started before.',
65
+ ["trace stopped" /* ErrorCode.TRACE_STOPPED_BEFORE */]: 'Trace {$traceName} is not running.',
66
+ ["nonpositive trace startTime" /* ErrorCode.NONPOSITIVE_TRACE_START_TIME */]: 'Trace {$traceName} startTime should be positive.',
67
+ ["nonpositive trace duration" /* ErrorCode.NONPOSITIVE_TRACE_DURATION */]: 'Trace {$traceName} duration should be positive.',
68
+ ["no window" /* ErrorCode.NO_WINDOW */]: 'Window is not available.',
69
+ ["no app id" /* ErrorCode.NO_APP_ID */]: 'App id is not available.',
70
+ ["no project id" /* ErrorCode.NO_PROJECT_ID */]: 'Project id is not available.',
71
+ ["no api key" /* ErrorCode.NO_API_KEY */]: 'Api key is not available.',
72
+ ["invalid cc log" /* ErrorCode.INVALID_CC_LOG */]: 'Attempted to queue invalid cc event',
73
+ ["FB not default" /* ErrorCode.FB_NOT_DEFAULT */]: 'Performance can only start when Firebase app instance is the default one.',
74
+ ["RC response not ok" /* ErrorCode.RC_NOT_OK */]: 'RC response is not ok',
75
+ ["invalid attribute name" /* ErrorCode.INVALID_ATTRIBUTE_NAME */]: 'Attribute name {$attributeName} is invalid.',
76
+ ["invalid attribute value" /* ErrorCode.INVALID_ATTRIBUTE_VALUE */]: 'Attribute value {$attributeValue} is invalid.',
77
+ ["invalid custom metric name" /* ErrorCode.INVALID_CUSTOM_METRIC_NAME */]: 'Custom metric name {$customMetricName} is invalid',
78
+ ["invalid String merger input" /* ErrorCode.INVALID_STRING_MERGER_PARAMETER */]: 'Input for String merger is invalid, contact support team to resolve.',
79
+ ["already initialized" /* ErrorCode.ALREADY_INITIALIZED */]: 'initializePerformance() has already been called with ' +
82
80
  'different options. To avoid this error, call initializePerformance() with the ' +
83
81
  'same options as when it was originally called, or call getPerformance() to return the' +
84
- ' already initialized instance.',
85
- _a);
86
- var ERROR_FACTORY = new util.ErrorFactory(SERVICE, SERVICE_NAME, ERROR_DESCRIPTION_MAP);
82
+ ' already initialized instance.'
83
+ };
84
+ const ERROR_FACTORY = new util.ErrorFactory(SERVICE, SERVICE_NAME, ERROR_DESCRIPTION_MAP);
87
85
 
88
86
  /**
89
87
  * @license
@@ -101,7 +99,7 @@ var ERROR_FACTORY = new util.ErrorFactory(SERVICE, SERVICE_NAME, ERROR_DESCRIPTI
101
99
  * See the License for the specific language governing permissions and
102
100
  * limitations under the License.
103
101
  */
104
- var consoleLogger = new logger$1.Logger(SERVICE_NAME);
102
+ const consoleLogger = new logger$1.Logger(SERVICE_NAME);
105
103
  consoleLogger.logLevel = logger$1.LogLevel.INFO;
106
104
 
107
105
  /**
@@ -120,14 +118,14 @@ consoleLogger.logLevel = logger$1.LogLevel.INFO;
120
118
  * See the License for the specific language governing permissions and
121
119
  * limitations under the License.
122
120
  */
123
- var apiInstance;
124
- var windowInstance;
121
+ let apiInstance;
122
+ let windowInstance;
125
123
  /**
126
124
  * This class holds a reference to various browser related objects injected by
127
125
  * set methods.
128
126
  */
129
- var Api = /** @class */ (function () {
130
- function Api(window) {
127
+ class Api {
128
+ constructor(window) {
131
129
  this.window = window;
132
130
  if (!window) {
133
131
  throw ERROR_FACTORY.create("no window" /* ErrorCode.NO_WINDOW */);
@@ -146,40 +144,40 @@ var Api = /** @class */ (function () {
146
144
  this.onFirstInputDelay = window.perfMetrics.onFirstInputDelay;
147
145
  }
148
146
  }
149
- Api.prototype.getUrl = function () {
147
+ getUrl() {
150
148
  // Do not capture the string query part of url.
151
149
  return this.windowLocation.href.split('?')[0];
152
- };
153
- Api.prototype.mark = function (name) {
150
+ }
151
+ mark(name) {
154
152
  if (!this.performance || !this.performance.mark) {
155
153
  return;
156
154
  }
157
155
  this.performance.mark(name);
158
- };
159
- Api.prototype.measure = function (measureName, mark1, mark2) {
156
+ }
157
+ measure(measureName, mark1, mark2) {
160
158
  if (!this.performance || !this.performance.measure) {
161
159
  return;
162
160
  }
163
161
  this.performance.measure(measureName, mark1, mark2);
164
- };
165
- Api.prototype.getEntriesByType = function (type) {
162
+ }
163
+ getEntriesByType(type) {
166
164
  if (!this.performance || !this.performance.getEntriesByType) {
167
165
  return [];
168
166
  }
169
167
  return this.performance.getEntriesByType(type);
170
- };
171
- Api.prototype.getEntriesByName = function (name) {
168
+ }
169
+ getEntriesByName(name) {
172
170
  if (!this.performance || !this.performance.getEntriesByName) {
173
171
  return [];
174
172
  }
175
173
  return this.performance.getEntriesByName(name);
176
- };
177
- Api.prototype.getTimeOrigin = function () {
174
+ }
175
+ getTimeOrigin() {
178
176
  // Polyfill the time origin with performance.timing.navigationStart.
179
177
  return (this.performance &&
180
178
  (this.performance.timeOrigin || this.performance.timing.navigationStart));
181
- };
182
- Api.prototype.requiredApisAvailable = function () {
179
+ }
180
+ requiredApisAvailable() {
183
181
  if (!fetch || !Promise || !util.areCookiesEnabled()) {
184
182
  consoleLogger.info('Firebase Performance cannot start if browser does not support fetch and Promise or cookie is disabled.');
185
183
  return false;
@@ -189,29 +187,27 @@ var Api = /** @class */ (function () {
189
187
  return false;
190
188
  }
191
189
  return true;
192
- };
193
- Api.prototype.setupObserver = function (entryType, callback) {
190
+ }
191
+ setupObserver(entryType, callback) {
194
192
  if (!this.PerformanceObserver) {
195
193
  return;
196
194
  }
197
- var observer = new this.PerformanceObserver(function (list) {
198
- for (var _i = 0, _a = list.getEntries(); _i < _a.length; _i++) {
199
- var entry = _a[_i];
195
+ const observer = new this.PerformanceObserver(list => {
196
+ for (const entry of list.getEntries()) {
200
197
  // `entry` is a PerformanceEntry instance.
201
198
  callback(entry);
202
199
  }
203
200
  });
204
201
  // Start observing the entry types you care about.
205
202
  observer.observe({ entryTypes: [entryType] });
206
- };
207
- Api.getInstance = function () {
203
+ }
204
+ static getInstance() {
208
205
  if (apiInstance === undefined) {
209
206
  apiInstance = new Api(windowInstance);
210
207
  }
211
208
  return apiInstance;
212
- };
213
- return Api;
214
- }());
209
+ }
210
+ }
215
211
  function setupApi(window) {
216
212
  windowInstance = window;
217
213
  }
@@ -232,11 +228,11 @@ function setupApi(window) {
232
228
  * See the License for the specific language governing permissions and
233
229
  * limitations under the License.
234
230
  */
235
- var iid;
231
+ let iid;
236
232
  function getIidPromise(installationsService) {
237
- var iidPromise = installationsService.getId();
233
+ const iidPromise = installationsService.getId();
238
234
  // eslint-disable-next-line @typescript-eslint/no-floating-promises
239
- iidPromise.then(function (iidVal) {
235
+ iidPromise.then((iidVal) => {
240
236
  iid = iidVal;
241
237
  });
242
238
  return iidPromise;
@@ -246,9 +242,9 @@ function getIid() {
246
242
  return iid;
247
243
  }
248
244
  function getAuthTokenPromise(installationsService) {
249
- var authTokenPromise = installationsService.getToken();
245
+ const authTokenPromise = installationsService.getToken();
250
246
  // eslint-disable-next-line @typescript-eslint/no-floating-promises
251
- authTokenPromise.then(function (authTokenVal) {
247
+ authTokenPromise.then((authTokenVal) => {
252
248
  });
253
249
  return authTokenPromise;
254
250
  }
@@ -270,12 +266,12 @@ function getAuthTokenPromise(installationsService) {
270
266
  * limitations under the License.
271
267
  */
272
268
  function mergeStrings(part1, part2) {
273
- var sizeDiff = part1.length - part2.length;
269
+ const sizeDiff = part1.length - part2.length;
274
270
  if (sizeDiff < 0 || sizeDiff > 1) {
275
271
  throw ERROR_FACTORY.create("invalid String merger input" /* ErrorCode.INVALID_STRING_MERGER_PARAMETER */);
276
272
  }
277
- var resultArray = [];
278
- for (var i = 0; i < part1.length; i++) {
273
+ const resultArray = [];
274
+ for (let i = 0; i < part1.length; i++) {
279
275
  resultArray.push(part1.charAt(i));
280
276
  if (part2.length > i) {
281
277
  resultArray.push(part2.charAt(i));
@@ -300,9 +296,9 @@ function mergeStrings(part1, part2) {
300
296
  * See the License for the specific language governing permissions and
301
297
  * limitations under the License.
302
298
  */
303
- var settingsServiceInstance;
304
- var SettingsService = /** @class */ (function () {
305
- function SettingsService() {
299
+ let settingsServiceInstance;
300
+ class SettingsService {
301
+ constructor() {
306
302
  // The variable which controls logging of automatic traces and HTTP/S network monitoring.
307
303
  this.instrumentationEnabled = true;
308
304
  // The variable which controls logging of custom traces.
@@ -326,17 +322,16 @@ var SettingsService = /** @class */ (function () {
326
322
  // TTL of config retrieved from remote config in hours.
327
323
  this.configTimeToLive = 12;
328
324
  }
329
- SettingsService.prototype.getFlTransportFullUrl = function () {
325
+ getFlTransportFullUrl() {
330
326
  return this.flTransportEndpointUrl.concat('?key=', this.transportKey);
331
- };
332
- SettingsService.getInstance = function () {
327
+ }
328
+ static getInstance() {
333
329
  if (settingsServiceInstance === undefined) {
334
330
  settingsServiceInstance = new SettingsService();
335
331
  }
336
332
  return settingsServiceInstance;
337
- };
338
- return SettingsService;
339
- }());
333
+ }
334
+ }
340
335
 
341
336
  /**
342
337
  * @license
@@ -360,12 +355,12 @@ var VisibilityState;
360
355
  VisibilityState[VisibilityState["VISIBLE"] = 1] = "VISIBLE";
361
356
  VisibilityState[VisibilityState["HIDDEN"] = 2] = "HIDDEN";
362
357
  })(VisibilityState || (VisibilityState = {}));
363
- var RESERVED_ATTRIBUTE_PREFIXES = ['firebase_', 'google_', 'ga_'];
364
- var ATTRIBUTE_FORMAT_REGEX = new RegExp('^[a-zA-Z]\\w*$');
365
- var MAX_ATTRIBUTE_NAME_LENGTH = 40;
366
- var MAX_ATTRIBUTE_VALUE_LENGTH = 100;
358
+ const RESERVED_ATTRIBUTE_PREFIXES = ['firebase_', 'google_', 'ga_'];
359
+ const ATTRIBUTE_FORMAT_REGEX = new RegExp('^[a-zA-Z]\\w*$');
360
+ const MAX_ATTRIBUTE_NAME_LENGTH = 40;
361
+ const MAX_ATTRIBUTE_VALUE_LENGTH = 100;
367
362
  function getServiceWorkerStatus() {
368
- var navigator = Api.getInstance().navigator;
363
+ const navigator = Api.getInstance().navigator;
369
364
  if (navigator === null || navigator === void 0 ? void 0 : navigator.serviceWorker) {
370
365
  if (navigator.serviceWorker.controller) {
371
366
  return 2 /* ServiceWorkerStatus.CONTROLLED */;
@@ -379,8 +374,8 @@ function getServiceWorkerStatus() {
379
374
  }
380
375
  }
381
376
  function getVisibilityState() {
382
- var document = Api.getInstance().document;
383
- var visibilityState = document.visibilityState;
377
+ const document = Api.getInstance().document;
378
+ const visibilityState = document.visibilityState;
384
379
  switch (visibilityState) {
385
380
  case 'visible':
386
381
  return VisibilityState.VISIBLE;
@@ -391,9 +386,9 @@ function getVisibilityState() {
391
386
  }
392
387
  }
393
388
  function getEffectiveConnectionType() {
394
- var navigator = Api.getInstance().navigator;
395
- var navigatorConnection = navigator.connection;
396
- var effectiveType = navigatorConnection && navigatorConnection.effectiveType;
389
+ const navigator = Api.getInstance().navigator;
390
+ const navigatorConnection = navigator.connection;
391
+ const effectiveType = navigatorConnection && navigatorConnection.effectiveType;
397
392
  switch (effectiveType) {
398
393
  case 'slow-2g':
399
394
  return 1 /* EffectiveConnectionType.CONNECTION_SLOW_2G */;
@@ -411,9 +406,7 @@ function isValidCustomAttributeName(name) {
411
406
  if (name.length === 0 || name.length > MAX_ATTRIBUTE_NAME_LENGTH) {
412
407
  return false;
413
408
  }
414
- var matchesReservedPrefix = RESERVED_ATTRIBUTE_PREFIXES.some(function (prefix) {
415
- return name.startsWith(prefix);
416
- });
409
+ const matchesReservedPrefix = RESERVED_ATTRIBUTE_PREFIXES.some(prefix => name.startsWith(prefix));
417
410
  return !matchesReservedPrefix && !!name.match(ATTRIBUTE_FORMAT_REGEX);
418
411
  }
419
412
  function isValidCustomAttributeValue(value) {
@@ -438,7 +431,7 @@ function isValidCustomAttributeValue(value) {
438
431
  */
439
432
  function getAppId(firebaseApp) {
440
433
  var _a;
441
- var appId = (_a = firebaseApp.options) === null || _a === void 0 ? void 0 : _a.appId;
434
+ const appId = (_a = firebaseApp.options) === null || _a === void 0 ? void 0 : _a.appId;
442
435
  if (!appId) {
443
436
  throw ERROR_FACTORY.create("no app id" /* ErrorCode.NO_APP_ID */);
444
437
  }
@@ -446,7 +439,7 @@ function getAppId(firebaseApp) {
446
439
  }
447
440
  function getProjectId(firebaseApp) {
448
441
  var _a;
449
- var projectId = (_a = firebaseApp.options) === null || _a === void 0 ? void 0 : _a.projectId;
442
+ const projectId = (_a = firebaseApp.options) === null || _a === void 0 ? void 0 : _a.projectId;
450
443
  if (!projectId) {
451
444
  throw ERROR_FACTORY.create("no project id" /* ErrorCode.NO_PROJECT_ID */);
452
445
  }
@@ -454,7 +447,7 @@ function getProjectId(firebaseApp) {
454
447
  }
455
448
  function getApiKey(firebaseApp) {
456
449
  var _a;
457
- var apiKey = (_a = firebaseApp.options) === null || _a === void 0 ? void 0 : _a.apiKey;
450
+ const apiKey = (_a = firebaseApp.options) === null || _a === void 0 ? void 0 : _a.apiKey;
458
451
  if (!apiKey) {
459
452
  throw ERROR_FACTORY.create("no api key" /* ErrorCode.NO_API_KEY */);
460
453
  }
@@ -477,40 +470,40 @@ function getApiKey(firebaseApp) {
477
470
  * See the License for the specific language governing permissions and
478
471
  * limitations under the License.
479
472
  */
480
- var REMOTE_CONFIG_SDK_VERSION = '0.0.1';
473
+ const REMOTE_CONFIG_SDK_VERSION = '0.0.1';
481
474
  // These values will be used if the remote config object is successfully
482
475
  // retrieved, but the template does not have these fields.
483
- var DEFAULT_CONFIGS = {
476
+ const DEFAULT_CONFIGS = {
484
477
  loggingEnabled: true
485
478
  };
486
- var FIS_AUTH_PREFIX = 'FIREBASE_INSTALLATIONS_AUTH';
479
+ const FIS_AUTH_PREFIX = 'FIREBASE_INSTALLATIONS_AUTH';
487
480
  function getConfig(performanceController, iid) {
488
- var config = getStoredConfig();
481
+ const config = getStoredConfig();
489
482
  if (config) {
490
483
  processConfig(config);
491
484
  return Promise.resolve();
492
485
  }
493
486
  return getRemoteConfig(performanceController, iid)
494
487
  .then(processConfig)
495
- .then(function (config) { return storeConfig(config); },
488
+ .then(config => storeConfig(config),
496
489
  /** Do nothing for error, use defaults set in settings service. */
497
- function () { });
490
+ () => { });
498
491
  }
499
492
  function getStoredConfig() {
500
- var localStorage = Api.getInstance().localStorage;
493
+ const localStorage = Api.getInstance().localStorage;
501
494
  if (!localStorage) {
502
495
  return;
503
496
  }
504
- var expiryString = localStorage.getItem(CONFIG_EXPIRY_LOCAL_STORAGE_KEY);
497
+ const expiryString = localStorage.getItem(CONFIG_EXPIRY_LOCAL_STORAGE_KEY);
505
498
  if (!expiryString || !configValid(expiryString)) {
506
499
  return;
507
500
  }
508
- var configStringified = localStorage.getItem(CONFIG_LOCAL_STORAGE_KEY);
501
+ const configStringified = localStorage.getItem(CONFIG_LOCAL_STORAGE_KEY);
509
502
  if (!configStringified) {
510
503
  return;
511
504
  }
512
505
  try {
513
- var configResponse = JSON.parse(configStringified);
506
+ const configResponse = JSON.parse(configStringified);
514
507
  return configResponse;
515
508
  }
516
509
  catch (_a) {
@@ -518,7 +511,7 @@ function getStoredConfig() {
518
511
  }
519
512
  }
520
513
  function storeConfig(config) {
521
- var localStorage = Api.getInstance().localStorage;
514
+ const localStorage = Api.getInstance().localStorage;
522
515
  if (!config || !localStorage) {
523
516
  return;
524
517
  }
@@ -526,17 +519,17 @@ function storeConfig(config) {
526
519
  localStorage.setItem(CONFIG_EXPIRY_LOCAL_STORAGE_KEY, String(Date.now() +
527
520
  SettingsService.getInstance().configTimeToLive * 60 * 60 * 1000));
528
521
  }
529
- var COULD_NOT_GET_CONFIG_MSG = 'Could not fetch config, will use default configs';
522
+ const COULD_NOT_GET_CONFIG_MSG = 'Could not fetch config, will use default configs';
530
523
  function getRemoteConfig(performanceController, iid) {
531
524
  // Perf needs auth token only to retrieve remote config.
532
525
  return getAuthTokenPromise(performanceController.installations)
533
- .then(function (authToken) {
534
- var projectId = getProjectId(performanceController.app);
535
- var apiKey = getApiKey(performanceController.app);
536
- var configEndPoint = "https://firebaseremoteconfig.googleapis.com/v1/projects/".concat(projectId, "/namespaces/fireperf:fetch?key=").concat(apiKey);
537
- var request = new Request(configEndPoint, {
526
+ .then(authToken => {
527
+ const projectId = getProjectId(performanceController.app);
528
+ const apiKey = getApiKey(performanceController.app);
529
+ const configEndPoint = `https://firebaseremoteconfig.googleapis.com/v1/projects/${projectId}/namespaces/fireperf:fetch?key=${apiKey}`;
530
+ const request = new Request(configEndPoint, {
538
531
  method: 'POST',
539
- headers: { Authorization: "".concat(FIS_AUTH_PREFIX, " ").concat(authToken) },
532
+ headers: { Authorization: `${FIS_AUTH_PREFIX} ${authToken}` },
540
533
  /* eslint-disable camelcase */
541
534
  body: JSON.stringify({
542
535
  app_instance_id: iid,
@@ -547,7 +540,7 @@ function getRemoteConfig(performanceController, iid) {
547
540
  })
548
541
  /* eslint-enable camelcase */
549
542
  });
550
- return fetch(request).then(function (response) {
543
+ return fetch(request).then(response => {
551
544
  if (response.ok) {
552
545
  return response.json();
553
546
  }
@@ -555,7 +548,7 @@ function getRemoteConfig(performanceController, iid) {
555
548
  throw ERROR_FACTORY.create("RC response not ok" /* ErrorCode.RC_NOT_OK */);
556
549
  });
557
550
  })
558
- .catch(function () {
551
+ .catch(() => {
559
552
  consoleLogger.info(COULD_NOT_GET_CONFIG_MSG);
560
553
  return undefined;
561
554
  });
@@ -569,8 +562,8 @@ function processConfig(config) {
569
562
  if (!config) {
570
563
  return config;
571
564
  }
572
- var settingsServiceInstance = SettingsService.getInstance();
573
- var entries = config.entries || {};
565
+ const settingsServiceInstance = SettingsService.getInstance();
566
+ const entries = config.entries || {};
574
567
  if (entries.fpr_enabled !== undefined) {
575
568
  // TODO: Change the assignment of loggingEnabled once the received type is
576
569
  // known.
@@ -643,8 +636,8 @@ function shouldLogAfterSampling(samplingRate) {
643
636
  * See the License for the specific language governing permissions and
644
637
  * limitations under the License.
645
638
  */
646
- var initializationStatus = 1 /* InitializationStatus.notInitialized */;
647
- var initializationPromise;
639
+ let initializationStatus = 1 /* InitializationStatus.notInitialized */;
640
+ let initializationPromise;
648
641
  function getInitializationPromise(performanceController) {
649
642
  initializationStatus = 2 /* InitializationStatus.initializationPending */;
650
643
  initializationPromise =
@@ -656,25 +649,25 @@ function isPerfInitialized() {
656
649
  }
657
650
  function initializePerf(performanceController) {
658
651
  return getDocumentReadyComplete()
659
- .then(function () { return getIidPromise(performanceController.installations); })
660
- .then(function (iid) { return getConfig(performanceController, iid); })
661
- .then(function () { return changeInitializationStatus(); }, function () { return changeInitializationStatus(); });
652
+ .then(() => getIidPromise(performanceController.installations))
653
+ .then(iid => getConfig(performanceController, iid))
654
+ .then(() => changeInitializationStatus(), () => changeInitializationStatus());
662
655
  }
663
656
  /**
664
657
  * Returns a promise which resolves whenever the document readystate is complete or
665
658
  * immediately if it is called after page load complete.
666
659
  */
667
660
  function getDocumentReadyComplete() {
668
- var document = Api.getInstance().document;
669
- return new Promise(function (resolve) {
661
+ const document = Api.getInstance().document;
662
+ return new Promise(resolve => {
670
663
  if (document && document.readyState !== 'complete') {
671
- var handler_1 = function () {
664
+ const handler = () => {
672
665
  if (document.readyState === 'complete') {
673
- document.removeEventListener('readystatechange', handler_1);
666
+ document.removeEventListener('readystatechange', handler);
674
667
  resolve();
675
668
  }
676
669
  };
677
- document.addEventListener('readystatechange', handler_1);
670
+ document.addEventListener('readystatechange', handler);
678
671
  }
679
672
  else {
680
673
  resolve();
@@ -701,15 +694,15 @@ function changeInitializationStatus() {
701
694
  * See the License for the specific language governing permissions and
702
695
  * limitations under the License.
703
696
  */
704
- var DEFAULT_SEND_INTERVAL_MS = 10 * 1000;
705
- var INITIAL_SEND_TIME_DELAY_MS = 5.5 * 1000;
697
+ const DEFAULT_SEND_INTERVAL_MS = 10 * 1000;
698
+ const INITIAL_SEND_TIME_DELAY_MS = 5.5 * 1000;
706
699
  // If end point does not work, the call will be tried for these many times.
707
- var DEFAULT_REMAINING_TRIES = 3;
708
- var MAX_EVENT_COUNT_PER_REQUEST = 1000;
709
- var remainingTries = DEFAULT_REMAINING_TRIES;
700
+ const DEFAULT_REMAINING_TRIES = 3;
701
+ const MAX_EVENT_COUNT_PER_REQUEST = 1000;
702
+ let remainingTries = DEFAULT_REMAINING_TRIES;
710
703
  /* eslint-enable camelcase */
711
- var queue = [];
712
- var isTransportSetup = false;
704
+ let queue = [];
705
+ let isTransportSetup = false;
713
706
  function setupTransportService() {
714
707
  if (!isTransportSetup) {
715
708
  processQueue(INITIAL_SEND_TIME_DELAY_MS);
@@ -717,7 +710,7 @@ function setupTransportService() {
717
710
  }
718
711
  }
719
712
  function processQueue(timeOffset) {
720
- setTimeout(function () {
713
+ setTimeout(() => {
721
714
  // If there is no remainingTries left, stop retrying.
722
715
  if (remainingTries === 0) {
723
716
  return;
@@ -733,55 +726,55 @@ function dispatchQueueEvents() {
733
726
  // Extract events up to the maximum cap of single logRequest from top of "official queue".
734
727
  // The staged events will be used for current logRequest attempt, remaining events will be kept
735
728
  // for next attempt.
736
- var staged = queue.splice(0, MAX_EVENT_COUNT_PER_REQUEST);
729
+ const staged = queue.splice(0, MAX_EVENT_COUNT_PER_REQUEST);
737
730
  /* eslint-disable camelcase */
738
731
  // We will pass the JSON serialized event to the backend.
739
- var log_event = staged.map(function (evt) { return ({
732
+ const log_event = staged.map(evt => ({
740
733
  source_extension_json_proto3: evt.message,
741
734
  event_time_ms: String(evt.eventTime)
742
- }); });
743
- var data = {
735
+ }));
736
+ const data = {
744
737
  request_time_ms: String(Date.now()),
745
738
  client_info: {
746
739
  client_type: 1,
747
740
  js_client_info: {}
748
741
  },
749
742
  log_source: SettingsService.getInstance().logSource,
750
- log_event: log_event
743
+ log_event
751
744
  };
752
745
  /* eslint-enable camelcase */
753
- sendEventsToFl(data, staged).catch(function () {
746
+ sendEventsToFl(data, staged).catch(() => {
754
747
  // If the request fails for some reason, add the events that were attempted
755
748
  // back to the primary queue to retry later.
756
- queue = tslib.__spreadArray(tslib.__spreadArray([], staged, true), queue, true);
749
+ queue = [...staged, ...queue];
757
750
  remainingTries--;
758
- consoleLogger.info("Tries left: ".concat(remainingTries, "."));
751
+ consoleLogger.info(`Tries left: ${remainingTries}.`);
759
752
  processQueue(DEFAULT_SEND_INTERVAL_MS);
760
753
  });
761
754
  }
762
755
  function sendEventsToFl(data, staged) {
763
756
  return postToFlEndpoint(data)
764
- .then(function (res) {
757
+ .then(res => {
765
758
  if (!res.ok) {
766
759
  consoleLogger.info('Call to Firebase backend failed.');
767
760
  }
768
761
  return res.json();
769
762
  })
770
- .then(function (res) {
763
+ .then(res => {
771
764
  // Find the next call wait time from the response.
772
- var transportWait = Number(res.nextRequestWaitMillis);
773
- var requestOffset = DEFAULT_SEND_INTERVAL_MS;
765
+ const transportWait = Number(res.nextRequestWaitMillis);
766
+ let requestOffset = DEFAULT_SEND_INTERVAL_MS;
774
767
  if (!isNaN(transportWait)) {
775
768
  requestOffset = Math.max(transportWait, requestOffset);
776
769
  }
777
770
  // Delete request if response include RESPONSE_ACTION_UNKNOWN or DELETE_REQUEST action.
778
771
  // Otherwise, retry request using normal scheduling if response include RETRY_REQUEST_LATER.
779
- var logResponseDetails = res.logResponseDetails;
772
+ const logResponseDetails = res.logResponseDetails;
780
773
  if (Array.isArray(logResponseDetails) &&
781
774
  logResponseDetails.length > 0 &&
782
775
  logResponseDetails[0].responseAction === 'RETRY_REQUEST_LATER') {
783
- queue = tslib.__spreadArray(tslib.__spreadArray([], staged, true), queue, true);
784
- consoleLogger.info("Retry transport request later.");
776
+ queue = [...staged, ...queue];
777
+ consoleLogger.info(`Retry transport request later.`);
785
778
  }
786
779
  remainingTries = DEFAULT_REMAINING_TRIES;
787
780
  // Schedule the next process.
@@ -789,7 +782,7 @@ function sendEventsToFl(data, staged) {
789
782
  });
790
783
  }
791
784
  function postToFlEndpoint(data) {
792
- var flTransportFullUrl = SettingsService.getInstance().getFlTransportFullUrl();
785
+ const flTransportFullUrl = SettingsService.getInstance().getFlTransportFullUrl();
793
786
  return fetch(flTransportFullUrl, {
794
787
  method: 'POST',
795
788
  body: JSON.stringify(data)
@@ -800,20 +793,16 @@ function addToQueue(evt) {
800
793
  throw ERROR_FACTORY.create("invalid cc log" /* ErrorCode.INVALID_CC_LOG */);
801
794
  }
802
795
  // Add the new event to the queue.
803
- queue = tslib.__spreadArray(tslib.__spreadArray([], queue, true), [evt], false);
796
+ queue = [...queue, evt];
804
797
  }
805
798
  /** Log handler for cc service to send the performance logs to the server. */
806
799
  function transportHandler(
807
800
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
808
801
  serializer) {
809
- return function () {
810
- var args = [];
811
- for (var _i = 0; _i < arguments.length; _i++) {
812
- args[_i] = arguments[_i];
813
- }
814
- var message = serializer.apply(void 0, args);
802
+ return (...args) => {
803
+ const message = serializer(...args);
815
804
  addToQueue({
816
- message: message,
805
+ message,
817
806
  eventTime: Date.now()
818
807
  });
819
808
  };
@@ -835,7 +824,7 @@ serializer) {
835
824
  * See the License for the specific language governing permissions and
836
825
  * limitations under the License.
837
826
  */
838
- var logger;
827
+ let logger;
839
828
  // This method is not called before initialization.
840
829
  function sendLog(resource, resourceType) {
841
830
  if (!logger) {
@@ -844,7 +833,7 @@ function sendLog(resource, resourceType) {
844
833
  logger(resource, resourceType);
845
834
  }
846
835
  function logTrace(trace) {
847
- var settingsService = SettingsService.getInstance();
836
+ const settingsService = SettingsService.getInstance();
848
837
  // Do not log if trace is auto generated and instrumentation is disabled.
849
838
  if (!settingsService.instrumentationEnabled && trace.isAuto) {
850
839
  return;
@@ -867,33 +856,33 @@ function logTrace(trace) {
867
856
  else {
868
857
  // Custom traces can be used before the initialization but logging
869
858
  // should wait until after.
870
- getInitializationPromise(trace.performanceController).then(function () { return sendTraceLog(trace); }, function () { return sendTraceLog(trace); });
859
+ getInitializationPromise(trace.performanceController).then(() => sendTraceLog(trace), () => sendTraceLog(trace));
871
860
  }
872
861
  }
873
862
  function sendTraceLog(trace) {
874
863
  if (!getIid()) {
875
864
  return;
876
865
  }
877
- var settingsService = SettingsService.getInstance();
866
+ const settingsService = SettingsService.getInstance();
878
867
  if (!settingsService.loggingEnabled ||
879
868
  !settingsService.logTraceAfterSampling) {
880
869
  return;
881
870
  }
882
- setTimeout(function () { return sendLog(trace, 1 /* ResourceType.Trace */); }, 0);
871
+ setTimeout(() => sendLog(trace, 1 /* ResourceType.Trace */), 0);
883
872
  }
884
873
  function logNetworkRequest(networkRequest) {
885
- var settingsService = SettingsService.getInstance();
874
+ const settingsService = SettingsService.getInstance();
886
875
  // Do not log network requests if instrumentation is disabled.
887
876
  if (!settingsService.instrumentationEnabled) {
888
877
  return;
889
878
  }
890
879
  // Do not log the js sdk's call to transport service domain to avoid unnecessary cycle.
891
880
  // Need to blacklist both old and new endpoints to avoid migration gap.
892
- var networkRequestUrl = networkRequest.url;
881
+ const networkRequestUrl = networkRequest.url;
893
882
  // Blacklist old log endpoint and new transport endpoint.
894
883
  // Because Performance SDK doesn't instrument requests sent from SDK itself.
895
- var logEndpointUrl = settingsService.logEndPointUrl.split('?')[0];
896
- var flEndpointUrl = settingsService.flTransportEndpointUrl.split('?')[0];
884
+ const logEndpointUrl = settingsService.logEndPointUrl.split('?')[0];
885
+ const flEndpointUrl = settingsService.flTransportEndpointUrl.split('?')[0];
897
886
  if (networkRequestUrl === logEndpointUrl ||
898
887
  networkRequestUrl === flEndpointUrl) {
899
888
  return;
@@ -902,7 +891,7 @@ function logNetworkRequest(networkRequest) {
902
891
  !settingsService.logNetworkAfterSampling) {
903
892
  return;
904
893
  }
905
- setTimeout(function () { return sendLog(networkRequest, 0 /* ResourceType.NetworkRequest */); }, 0);
894
+ setTimeout(() => sendLog(networkRequest, 0 /* ResourceType.NetworkRequest */), 0);
906
895
  }
907
896
  function serializer(resource, resourceType) {
908
897
  if (resourceType === 0 /* ResourceType.NetworkRequest */) {
@@ -911,7 +900,7 @@ function serializer(resource, resourceType) {
911
900
  return serializeTrace(resource);
912
901
  }
913
902
  function serializeNetworkRequest(networkRequest) {
914
- var networkRequestMetric = {
903
+ const networkRequestMetric = {
915
904
  url: networkRequest.url,
916
905
  http_method: networkRequest.httpMethod || 0,
917
906
  http_response_code: 200,
@@ -920,14 +909,14 @@ function serializeNetworkRequest(networkRequest) {
920
909
  time_to_response_initiated_us: networkRequest.timeToResponseInitiatedUs,
921
910
  time_to_response_completed_us: networkRequest.timeToResponseCompletedUs
922
911
  };
923
- var perfMetric = {
912
+ const perfMetric = {
924
913
  application_info: getApplicationInfo(networkRequest.performanceController.app),
925
914
  network_request_metric: networkRequestMetric
926
915
  };
927
916
  return JSON.stringify(perfMetric);
928
917
  }
929
918
  function serializeTrace(trace) {
930
- var traceMetric = {
919
+ const traceMetric = {
931
920
  name: trace.name,
932
921
  is_auto: trace.isAuto,
933
922
  client_start_time_us: trace.startTimeUs,
@@ -936,11 +925,11 @@ function serializeTrace(trace) {
936
925
  if (Object.keys(trace.counters).length !== 0) {
937
926
  traceMetric.counters = trace.counters;
938
927
  }
939
- var customAttributes = trace.getAttributes();
928
+ const customAttributes = trace.getAttributes();
940
929
  if (Object.keys(customAttributes).length !== 0) {
941
930
  traceMetric.custom_attributes = customAttributes;
942
931
  }
943
- var perfMetric = {
932
+ const perfMetric = {
944
933
  application_info: getApplicationInfo(trace.performanceController.app),
945
934
  trace_metric: traceMetric
946
935
  };
@@ -978,9 +967,9 @@ function getApplicationInfo(firebaseApp) {
978
967
  * See the License for the specific language governing permissions and
979
968
  * limitations under the License.
980
969
  */
981
- var MAX_METRIC_NAME_LENGTH = 100;
982
- var RESERVED_AUTO_PREFIX = '_';
983
- var oobMetrics = [
970
+ const MAX_METRIC_NAME_LENGTH = 100;
971
+ const RESERVED_AUTO_PREFIX = '_';
972
+ const oobMetrics = [
984
973
  FIRST_PAINT_COUNTER_NAME,
985
974
  FIRST_CONTENTFUL_PAINT_COUNTER_NAME,
986
975
  FIRST_INPUT_DELAY_COUNTER_NAME
@@ -1005,9 +994,9 @@ function isValidMetricName(name, traceName) {
1005
994
  * @returns Converted integer number to be set for the metric.
1006
995
  */
1007
996
  function convertMetricValueToInteger(providedValue) {
1008
- var valueAsInteger = Math.floor(providedValue);
997
+ const valueAsInteger = Math.floor(providedValue);
1009
998
  if (valueAsInteger < providedValue) {
1010
- consoleLogger.info("Metric value should be an Integer, setting the value as : ".concat(valueAsInteger, "."));
999
+ consoleLogger.info(`Metric value should be an Integer, setting the value as : ${valueAsInteger}.`);
1011
1000
  }
1012
1001
  return valueAsInteger;
1013
1002
  }
@@ -1028,7 +1017,7 @@ function convertMetricValueToInteger(providedValue) {
1028
1017
  * See the License for the specific language governing permissions and
1029
1018
  * limitations under the License.
1030
1019
  */
1031
- var Trace = /** @class */ (function () {
1020
+ class Trace {
1032
1021
  /**
1033
1022
  * @param performanceController The performance controller running.
1034
1023
  * @param name The name of the trace.
@@ -1037,8 +1026,7 @@ var Trace = /** @class */ (function () {
1037
1026
  * is only set when the trace is built for logging when the user directly uses the user timing
1038
1027
  * api (performance.mark and performance.measure).
1039
1028
  */
1040
- function Trace(performanceController, name, isAuto, traceMeasureName) {
1041
- if (isAuto === void 0) { isAuto = false; }
1029
+ constructor(performanceController, name, isAuto = false, traceMeasureName) {
1042
1030
  this.performanceController = performanceController;
1043
1031
  this.name = name;
1044
1032
  this.isAuto = isAuto;
@@ -1048,11 +1036,11 @@ var Trace = /** @class */ (function () {
1048
1036
  this.api = Api.getInstance();
1049
1037
  this.randomId = Math.floor(Math.random() * 1000000);
1050
1038
  if (!this.isAuto) {
1051
- this.traceStartMark = "".concat(TRACE_START_MARK_PREFIX, "-").concat(this.randomId, "-").concat(this.name);
1052
- this.traceStopMark = "".concat(TRACE_STOP_MARK_PREFIX, "-").concat(this.randomId, "-").concat(this.name);
1039
+ this.traceStartMark = `${TRACE_START_MARK_PREFIX}-${this.randomId}-${this.name}`;
1040
+ this.traceStopMark = `${TRACE_STOP_MARK_PREFIX}-${this.randomId}-${this.name}`;
1053
1041
  this.traceMeasure =
1054
1042
  traceMeasureName ||
1055
- "".concat(TRACE_MEASURE_PREFIX, "-").concat(this.randomId, "-").concat(this.name);
1043
+ `${TRACE_MEASURE_PREFIX}-${this.randomId}-${this.name}`;
1056
1044
  if (traceMeasureName) {
1057
1045
  // For the case of direct user timing traces, no start stop will happen. The measure object
1058
1046
  // is already available.
@@ -1063,7 +1051,7 @@ var Trace = /** @class */ (function () {
1063
1051
  /**
1064
1052
  * Starts a trace. The measurement of the duration starts at this point.
1065
1053
  */
1066
- Trace.prototype.start = function () {
1054
+ start() {
1067
1055
  if (this.state !== 1 /* TraceState.UNINITIALIZED */) {
1068
1056
  throw ERROR_FACTORY.create("trace started" /* ErrorCode.TRACE_STARTED_BEFORE */, {
1069
1057
  traceName: this.name
@@ -1071,12 +1059,12 @@ var Trace = /** @class */ (function () {
1071
1059
  }
1072
1060
  this.api.mark(this.traceStartMark);
1073
1061
  this.state = 2 /* TraceState.RUNNING */;
1074
- };
1062
+ }
1075
1063
  /**
1076
1064
  * Stops the trace. The measurement of the duration of the trace stops at this point and trace
1077
1065
  * is logged.
1078
1066
  */
1079
- Trace.prototype.stop = function () {
1067
+ stop() {
1080
1068
  if (this.state !== 2 /* TraceState.RUNNING */) {
1081
1069
  throw ERROR_FACTORY.create("trace stopped" /* ErrorCode.TRACE_STOPPED_BEFORE */, {
1082
1070
  traceName: this.name
@@ -1087,7 +1075,7 @@ var Trace = /** @class */ (function () {
1087
1075
  this.api.measure(this.traceMeasure, this.traceStartMark, this.traceStopMark);
1088
1076
  this.calculateTraceMetrics();
1089
1077
  logTrace(this);
1090
- };
1078
+ }
1091
1079
  /**
1092
1080
  * Records a trace with predetermined values. If this method is used a trace is created and logged
1093
1081
  * directly. No need to use start and stop methods.
@@ -1095,7 +1083,7 @@ var Trace = /** @class */ (function () {
1095
1083
  * @param duration The duration of the trace in millisec
1096
1084
  * @param options An object which can optionally hold maps of custom metrics and custom attributes
1097
1085
  */
1098
- Trace.prototype.record = function (startTime, duration, options) {
1086
+ record(startTime, duration, options) {
1099
1087
  if (startTime <= 0) {
1100
1088
  throw ERROR_FACTORY.create("nonpositive trace startTime" /* ErrorCode.NONPOSITIVE_TRACE_START_TIME */, {
1101
1089
  traceName: this.name
@@ -1109,18 +1097,17 @@ var Trace = /** @class */ (function () {
1109
1097
  this.durationUs = Math.floor(duration * 1000);
1110
1098
  this.startTimeUs = Math.floor(startTime * 1000);
1111
1099
  if (options && options.attributes) {
1112
- this.customAttributes = tslib.__assign({}, options.attributes);
1100
+ this.customAttributes = Object.assign({}, options.attributes);
1113
1101
  }
1114
1102
  if (options && options.metrics) {
1115
- for (var _i = 0, _a = Object.keys(options.metrics); _i < _a.length; _i++) {
1116
- var metricName = _a[_i];
1103
+ for (const metricName of Object.keys(options.metrics)) {
1117
1104
  if (!isNaN(Number(options.metrics[metricName]))) {
1118
1105
  this.counters[metricName] = Math.floor(Number(options.metrics[metricName]));
1119
1106
  }
1120
1107
  }
1121
1108
  }
1122
1109
  logTrace(this);
1123
- };
1110
+ }
1124
1111
  /**
1125
1112
  * Increments a custom metric by a certain number or 1 if number not specified. Will create a new
1126
1113
  * custom metric if one with the given name does not exist. The value will be floored down to an
@@ -1128,22 +1115,21 @@ var Trace = /** @class */ (function () {
1128
1115
  * @param counter Name of the custom metric
1129
1116
  * @param numAsInteger Increment by value
1130
1117
  */
1131
- Trace.prototype.incrementMetric = function (counter, numAsInteger) {
1132
- if (numAsInteger === void 0) { numAsInteger = 1; }
1118
+ incrementMetric(counter, numAsInteger = 1) {
1133
1119
  if (this.counters[counter] === undefined) {
1134
1120
  this.putMetric(counter, numAsInteger);
1135
1121
  }
1136
1122
  else {
1137
1123
  this.putMetric(counter, this.counters[counter] + numAsInteger);
1138
1124
  }
1139
- };
1125
+ }
1140
1126
  /**
1141
1127
  * Sets a custom metric to a specified value. Will create a new custom metric if one with the
1142
1128
  * given name does not exist. The value will be floored down to an integer.
1143
1129
  * @param counter Name of the custom metric
1144
1130
  * @param numAsInteger Set custom metric to this value
1145
1131
  */
1146
- Trace.prototype.putMetric = function (counter, numAsInteger) {
1132
+ putMetric(counter, numAsInteger) {
1147
1133
  if (isValidMetricName(counter, this.name)) {
1148
1134
  this.counters[counter] = convertMetricValueToInteger(numAsInteger !== null && numAsInteger !== void 0 ? numAsInteger : 0);
1149
1135
  }
@@ -1152,23 +1138,23 @@ var Trace = /** @class */ (function () {
1152
1138
  customMetricName: counter
1153
1139
  });
1154
1140
  }
1155
- };
1141
+ }
1156
1142
  /**
1157
1143
  * Returns the value of the custom metric by that name. If a custom metric with that name does
1158
1144
  * not exist will return zero.
1159
1145
  * @param counter
1160
1146
  */
1161
- Trace.prototype.getMetric = function (counter) {
1147
+ getMetric(counter) {
1162
1148
  return this.counters[counter] || 0;
1163
- };
1149
+ }
1164
1150
  /**
1165
1151
  * Sets a custom attribute of a trace to a certain value.
1166
1152
  * @param attr
1167
1153
  * @param value
1168
1154
  */
1169
- Trace.prototype.putAttribute = function (attr, value) {
1170
- var isValidName = isValidCustomAttributeName(attr);
1171
- var isValidValue = isValidCustomAttributeValue(value);
1155
+ putAttribute(attr, value) {
1156
+ const isValidName = isValidCustomAttributeName(attr);
1157
+ const isValidValue = isValidCustomAttributeValue(value);
1172
1158
  if (isValidName && isValidValue) {
1173
1159
  this.customAttributes[attr] = value;
1174
1160
  return;
@@ -1184,54 +1170,54 @@ var Trace = /** @class */ (function () {
1184
1170
  attributeValue: value
1185
1171
  });
1186
1172
  }
1187
- };
1173
+ }
1188
1174
  /**
1189
1175
  * Retrieves the value a custom attribute of a trace is set to.
1190
1176
  * @param attr
1191
1177
  */
1192
- Trace.prototype.getAttribute = function (attr) {
1178
+ getAttribute(attr) {
1193
1179
  return this.customAttributes[attr];
1194
- };
1195
- Trace.prototype.removeAttribute = function (attr) {
1180
+ }
1181
+ removeAttribute(attr) {
1196
1182
  if (this.customAttributes[attr] === undefined) {
1197
1183
  return;
1198
1184
  }
1199
1185
  delete this.customAttributes[attr];
1200
- };
1201
- Trace.prototype.getAttributes = function () {
1202
- return tslib.__assign({}, this.customAttributes);
1203
- };
1204
- Trace.prototype.setStartTime = function (startTime) {
1186
+ }
1187
+ getAttributes() {
1188
+ return Object.assign({}, this.customAttributes);
1189
+ }
1190
+ setStartTime(startTime) {
1205
1191
  this.startTimeUs = startTime;
1206
- };
1207
- Trace.prototype.setDuration = function (duration) {
1192
+ }
1193
+ setDuration(duration) {
1208
1194
  this.durationUs = duration;
1209
- };
1195
+ }
1210
1196
  /**
1211
1197
  * Calculates and assigns the duration and start time of the trace using the measure performance
1212
1198
  * entry.
1213
1199
  */
1214
- Trace.prototype.calculateTraceMetrics = function () {
1215
- var perfMeasureEntries = this.api.getEntriesByName(this.traceMeasure);
1216
- var perfMeasureEntry = perfMeasureEntries && perfMeasureEntries[0];
1200
+ calculateTraceMetrics() {
1201
+ const perfMeasureEntries = this.api.getEntriesByName(this.traceMeasure);
1202
+ const perfMeasureEntry = perfMeasureEntries && perfMeasureEntries[0];
1217
1203
  if (perfMeasureEntry) {
1218
1204
  this.durationUs = Math.floor(perfMeasureEntry.duration * 1000);
1219
1205
  this.startTimeUs = Math.floor((perfMeasureEntry.startTime + this.api.getTimeOrigin()) * 1000);
1220
1206
  }
1221
- };
1207
+ }
1222
1208
  /**
1223
1209
  * @param navigationTimings A single element array which contains the navigationTIming object of
1224
1210
  * the page load
1225
1211
  * @param paintTimings A array which contains paintTiming object of the page load
1226
1212
  * @param firstInputDelay First input delay in millisec
1227
1213
  */
1228
- Trace.createOobTrace = function (performanceController, navigationTimings, paintTimings, firstInputDelay) {
1229
- var route = Api.getInstance().getUrl();
1214
+ static createOobTrace(performanceController, navigationTimings, paintTimings, firstInputDelay) {
1215
+ const route = Api.getInstance().getUrl();
1230
1216
  if (!route) {
1231
1217
  return;
1232
1218
  }
1233
- var trace = new Trace(performanceController, OOB_TRACE_PAGE_LOAD_PREFIX + route, true);
1234
- var timeOriginUs = Math.floor(Api.getInstance().getTimeOrigin() * 1000);
1219
+ const trace = new Trace(performanceController, OOB_TRACE_PAGE_LOAD_PREFIX + route, true);
1220
+ const timeOriginUs = Math.floor(Api.getInstance().getTimeOrigin() * 1000);
1235
1221
  trace.setStartTime(timeOriginUs);
1236
1222
  // navigationTimings includes only one element.
1237
1223
  if (navigationTimings && navigationTimings[0]) {
@@ -1240,14 +1226,14 @@ var Trace = /** @class */ (function () {
1240
1226
  trace.putMetric('domContentLoadedEventEnd', Math.floor(navigationTimings[0].domContentLoadedEventEnd * 1000));
1241
1227
  trace.putMetric('loadEventEnd', Math.floor(navigationTimings[0].loadEventEnd * 1000));
1242
1228
  }
1243
- var FIRST_PAINT = 'first-paint';
1244
- var FIRST_CONTENTFUL_PAINT = 'first-contentful-paint';
1229
+ const FIRST_PAINT = 'first-paint';
1230
+ const FIRST_CONTENTFUL_PAINT = 'first-contentful-paint';
1245
1231
  if (paintTimings) {
1246
- var firstPaint = paintTimings.find(function (paintObject) { return paintObject.name === FIRST_PAINT; });
1232
+ const firstPaint = paintTimings.find(paintObject => paintObject.name === FIRST_PAINT);
1247
1233
  if (firstPaint && firstPaint.startTime) {
1248
1234
  trace.putMetric(FIRST_PAINT_COUNTER_NAME, Math.floor(firstPaint.startTime * 1000));
1249
1235
  }
1250
- var firstContentfulPaint = paintTimings.find(function (paintObject) { return paintObject.name === FIRST_CONTENTFUL_PAINT; });
1236
+ const firstContentfulPaint = paintTimings.find(paintObject => paintObject.name === FIRST_CONTENTFUL_PAINT);
1251
1237
  if (firstContentfulPaint && firstContentfulPaint.startTime) {
1252
1238
  trace.putMetric(FIRST_CONTENTFUL_PAINT_COUNTER_NAME, Math.floor(firstContentfulPaint.startTime * 1000));
1253
1239
  }
@@ -1256,13 +1242,12 @@ var Trace = /** @class */ (function () {
1256
1242
  }
1257
1243
  }
1258
1244
  logTrace(trace);
1259
- };
1260
- Trace.createUserTimingTrace = function (performanceController, measureName) {
1261
- var trace = new Trace(performanceController, measureName, false, measureName);
1245
+ }
1246
+ static createUserTimingTrace(performanceController, measureName) {
1247
+ const trace = new Trace(performanceController, measureName, false, measureName);
1262
1248
  logTrace(trace);
1263
- };
1264
- return Trace;
1265
- }());
1249
+ }
1250
+ }
1266
1251
 
1267
1252
  /**
1268
1253
  * @license
@@ -1281,25 +1266,25 @@ var Trace = /** @class */ (function () {
1281
1266
  * limitations under the License.
1282
1267
  */
1283
1268
  function createNetworkRequestEntry(performanceController, entry) {
1284
- var performanceEntry = entry;
1269
+ const performanceEntry = entry;
1285
1270
  if (!performanceEntry || performanceEntry.responseStart === undefined) {
1286
1271
  return;
1287
1272
  }
1288
- var timeOrigin = Api.getInstance().getTimeOrigin();
1289
- var startTimeUs = Math.floor((performanceEntry.startTime + timeOrigin) * 1000);
1290
- var timeToResponseInitiatedUs = performanceEntry.responseStart
1273
+ const timeOrigin = Api.getInstance().getTimeOrigin();
1274
+ const startTimeUs = Math.floor((performanceEntry.startTime + timeOrigin) * 1000);
1275
+ const timeToResponseInitiatedUs = performanceEntry.responseStart
1291
1276
  ? Math.floor((performanceEntry.responseStart - performanceEntry.startTime) * 1000)
1292
1277
  : undefined;
1293
- var timeToResponseCompletedUs = Math.floor((performanceEntry.responseEnd - performanceEntry.startTime) * 1000);
1278
+ const timeToResponseCompletedUs = Math.floor((performanceEntry.responseEnd - performanceEntry.startTime) * 1000);
1294
1279
  // Remove the query params from logged network request url.
1295
- var url = performanceEntry.name && performanceEntry.name.split('?')[0];
1296
- var networkRequest = {
1297
- performanceController: performanceController,
1298
- url: url,
1280
+ const url = performanceEntry.name && performanceEntry.name.split('?')[0];
1281
+ const networkRequest = {
1282
+ performanceController,
1283
+ url,
1299
1284
  responsePayloadBytes: performanceEntry.transferSize,
1300
- startTimeUs: startTimeUs,
1301
- timeToResponseInitiatedUs: timeToResponseInitiatedUs,
1302
- timeToResponseCompletedUs: timeToResponseCompletedUs
1285
+ startTimeUs,
1286
+ timeToResponseInitiatedUs,
1287
+ timeToResponseCompletedUs
1303
1288
  };
1304
1289
  logNetworkRequest(networkRequest);
1305
1290
  }
@@ -1320,7 +1305,7 @@ function createNetworkRequestEntry(performanceController, entry) {
1320
1305
  * See the License for the specific language governing permissions and
1321
1306
  * limitations under the License.
1322
1307
  */
1323
- var FID_WAIT_TIME_MS = 5000;
1308
+ const FID_WAIT_TIME_MS = 5000;
1324
1309
  function setupOobResources(performanceController) {
1325
1310
  // Do not initialize unless iid is available.
1326
1311
  if (!getIid()) {
@@ -1328,37 +1313,34 @@ function setupOobResources(performanceController) {
1328
1313
  }
1329
1314
  // The load event might not have fired yet, and that means performance navigation timing
1330
1315
  // object has a duration of 0. The setup should run after all current tasks in js queue.
1331
- setTimeout(function () { return setupOobTraces(performanceController); }, 0);
1332
- setTimeout(function () { return setupNetworkRequests(performanceController); }, 0);
1333
- setTimeout(function () { return setupUserTimingTraces(performanceController); }, 0);
1316
+ setTimeout(() => setupOobTraces(performanceController), 0);
1317
+ setTimeout(() => setupNetworkRequests(performanceController), 0);
1318
+ setTimeout(() => setupUserTimingTraces(performanceController), 0);
1334
1319
  }
1335
1320
  function setupNetworkRequests(performanceController) {
1336
- var api = Api.getInstance();
1337
- var resources = api.getEntriesByType('resource');
1338
- for (var _i = 0, resources_1 = resources; _i < resources_1.length; _i++) {
1339
- var resource = resources_1[_i];
1321
+ const api = Api.getInstance();
1322
+ const resources = api.getEntriesByType('resource');
1323
+ for (const resource of resources) {
1340
1324
  createNetworkRequestEntry(performanceController, resource);
1341
1325
  }
1342
- api.setupObserver('resource', function (entry) {
1343
- return createNetworkRequestEntry(performanceController, entry);
1344
- });
1326
+ api.setupObserver('resource', entry => createNetworkRequestEntry(performanceController, entry));
1345
1327
  }
1346
1328
  function setupOobTraces(performanceController) {
1347
- var api = Api.getInstance();
1348
- var navigationTimings = api.getEntriesByType('navigation');
1349
- var paintTimings = api.getEntriesByType('paint');
1329
+ const api = Api.getInstance();
1330
+ const navigationTimings = api.getEntriesByType('navigation');
1331
+ const paintTimings = api.getEntriesByType('paint');
1350
1332
  // If First Input Delay polyfill is added to the page, report the fid value.
1351
1333
  // https://github.com/GoogleChromeLabs/first-input-delay
1352
1334
  if (api.onFirstInputDelay) {
1353
1335
  // If the fid call back is not called for certain time, continue without it.
1354
1336
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
1355
- var timeoutId_1 = setTimeout(function () {
1337
+ let timeoutId = setTimeout(() => {
1356
1338
  Trace.createOobTrace(performanceController, navigationTimings, paintTimings);
1357
- timeoutId_1 = undefined;
1339
+ timeoutId = undefined;
1358
1340
  }, FID_WAIT_TIME_MS);
1359
- api.onFirstInputDelay(function (fid) {
1360
- if (timeoutId_1) {
1361
- clearTimeout(timeoutId_1);
1341
+ api.onFirstInputDelay((fid) => {
1342
+ if (timeoutId) {
1343
+ clearTimeout(timeoutId);
1362
1344
  Trace.createOobTrace(performanceController, navigationTimings, paintTimings, fid);
1363
1345
  }
1364
1346
  });
@@ -1368,20 +1350,17 @@ function setupOobTraces(performanceController) {
1368
1350
  }
1369
1351
  }
1370
1352
  function setupUserTimingTraces(performanceController) {
1371
- var api = Api.getInstance();
1353
+ const api = Api.getInstance();
1372
1354
  // Run through the measure performance entries collected up to this point.
1373
- var measures = api.getEntriesByType('measure');
1374
- for (var _i = 0, measures_1 = measures; _i < measures_1.length; _i++) {
1375
- var measure = measures_1[_i];
1355
+ const measures = api.getEntriesByType('measure');
1356
+ for (const measure of measures) {
1376
1357
  createUserTimingTrace(performanceController, measure);
1377
1358
  }
1378
1359
  // Setup an observer to capture the measures from this point on.
1379
- api.setupObserver('measure', function (entry) {
1380
- return createUserTimingTrace(performanceController, entry);
1381
- });
1360
+ api.setupObserver('measure', entry => createUserTimingTrace(performanceController, entry));
1382
1361
  }
1383
1362
  function createUserTimingTrace(performanceController, measure) {
1384
- var measureName = measure.name;
1363
+ const measureName = measure.name;
1385
1364
  // Do not create a trace, if the user timing marks and measures are created by the sdk itself.
1386
1365
  if (measureName.substring(0, TRACE_MEASURE_PREFIX.length) ===
1387
1366
  TRACE_MEASURE_PREFIX) {
@@ -1406,8 +1385,8 @@ function createUserTimingTrace(performanceController, measure) {
1406
1385
  * See the License for the specific language governing permissions and
1407
1386
  * limitations under the License.
1408
1387
  */
1409
- var PerformanceController = /** @class */ (function () {
1410
- function PerformanceController(app, installations) {
1388
+ class PerformanceController {
1389
+ constructor(app, installations) {
1411
1390
  this.app = app;
1412
1391
  this.installations = installations;
1413
1392
  this.initialized = false;
@@ -1421,8 +1400,7 @@ var PerformanceController = /** @class */ (function () {
1421
1400
  * desired settings, to ensure nothing is collected without the user's
1422
1401
  * consent.
1423
1402
  */
1424
- PerformanceController.prototype._init = function (settings) {
1425
- var _this = this;
1403
+ _init(settings) {
1426
1404
  if (this.initialized) {
1427
1405
  return;
1428
1406
  }
@@ -1434,44 +1412,35 @@ var PerformanceController = /** @class */ (function () {
1434
1412
  }
1435
1413
  if (Api.getInstance().requiredApisAvailable()) {
1436
1414
  util.validateIndexedDBOpenable()
1437
- .then(function (isAvailable) {
1415
+ .then(isAvailable => {
1438
1416
  if (isAvailable) {
1439
1417
  setupTransportService();
1440
- getInitializationPromise(_this).then(function () { return setupOobResources(_this); }, function () { return setupOobResources(_this); });
1441
- _this.initialized = true;
1418
+ getInitializationPromise(this).then(() => setupOobResources(this), () => setupOobResources(this));
1419
+ this.initialized = true;
1442
1420
  }
1443
1421
  })
1444
- .catch(function (error) {
1445
- consoleLogger.info("Environment doesn't support IndexedDB: ".concat(error));
1422
+ .catch(error => {
1423
+ consoleLogger.info(`Environment doesn't support IndexedDB: ${error}`);
1446
1424
  });
1447
1425
  }
1448
1426
  else {
1449
1427
  consoleLogger.info('Firebase Performance cannot start if the browser does not support ' +
1450
1428
  '"Fetch" and "Promise", or cookies are disabled.');
1451
1429
  }
1452
- };
1453
- Object.defineProperty(PerformanceController.prototype, "instrumentationEnabled", {
1454
- get: function () {
1455
- return SettingsService.getInstance().instrumentationEnabled;
1456
- },
1457
- set: function (val) {
1458
- SettingsService.getInstance().instrumentationEnabled = val;
1459
- },
1460
- enumerable: false,
1461
- configurable: true
1462
- });
1463
- Object.defineProperty(PerformanceController.prototype, "dataCollectionEnabled", {
1464
- get: function () {
1465
- return SettingsService.getInstance().dataCollectionEnabled;
1466
- },
1467
- set: function (val) {
1468
- SettingsService.getInstance().dataCollectionEnabled = val;
1469
- },
1470
- enumerable: false,
1471
- configurable: true
1472
- });
1473
- return PerformanceController;
1474
- }());
1430
+ }
1431
+ set instrumentationEnabled(val) {
1432
+ SettingsService.getInstance().instrumentationEnabled = val;
1433
+ }
1434
+ get instrumentationEnabled() {
1435
+ return SettingsService.getInstance().instrumentationEnabled;
1436
+ }
1437
+ set dataCollectionEnabled(val) {
1438
+ SettingsService.getInstance().dataCollectionEnabled = val;
1439
+ }
1440
+ get dataCollectionEnabled() {
1441
+ return SettingsService.getInstance().dataCollectionEnabled;
1442
+ }
1443
+ }
1475
1444
 
1476
1445
  /**
1477
1446
  * The Firebase Performance Monitoring Web SDK.
@@ -1479,17 +1448,16 @@ var PerformanceController = /** @class */ (function () {
1479
1448
  *
1480
1449
  * @packageDocumentation
1481
1450
  */
1482
- var DEFAULT_ENTRY_NAME = '[DEFAULT]';
1451
+ const DEFAULT_ENTRY_NAME = '[DEFAULT]';
1483
1452
  /**
1484
1453
  * Returns a {@link FirebasePerformance} instance for the given app.
1485
1454
  * @param app - The {@link @firebase/app#FirebaseApp} to use.
1486
1455
  * @public
1487
1456
  */
1488
- function getPerformance(app$1) {
1489
- if (app$1 === void 0) { app$1 = app.getApp(); }
1457
+ function getPerformance(app$1 = app.getApp()) {
1490
1458
  app$1 = util.getModularInstance(app$1);
1491
- var provider = app._getProvider(app$1, 'performance');
1492
- var perfInstance = provider.getImmediate();
1459
+ const provider = app._getProvider(app$1, 'performance');
1460
+ const perfInstance = provider.getImmediate();
1493
1461
  return perfInstance;
1494
1462
  }
1495
1463
  /**
@@ -1500,12 +1468,12 @@ function getPerformance(app$1) {
1500
1468
  */
1501
1469
  function initializePerformance(app$1, settings) {
1502
1470
  app$1 = util.getModularInstance(app$1);
1503
- var provider = app._getProvider(app$1, 'performance');
1471
+ const provider = app._getProvider(app$1, 'performance');
1504
1472
  // throw if an instance was already created.
1505
1473
  // It could happen if initializePerformance() is called more than once, or getPerformance() is called first.
1506
1474
  if (provider.isInitialized()) {
1507
- var existingInstance = provider.getImmediate();
1508
- var initialSettings = provider.getOptions();
1475
+ const existingInstance = provider.getImmediate();
1476
+ const initialSettings = provider.getOptions();
1509
1477
  if (util.deepEqual(initialSettings, settings !== null && settings !== void 0 ? settings : {})) {
1510
1478
  return existingInstance;
1511
1479
  }
@@ -1513,7 +1481,7 @@ function initializePerformance(app$1, settings) {
1513
1481
  throw ERROR_FACTORY.create("already initialized" /* ErrorCode.ALREADY_INITIALIZED */);
1514
1482
  }
1515
1483
  }
1516
- var perfInstance = provider.initialize({
1484
+ const perfInstance = provider.initialize({
1517
1485
  options: settings
1518
1486
  });
1519
1487
  return perfInstance;
@@ -1528,11 +1496,10 @@ function trace(performance, name) {
1528
1496
  performance = util.getModularInstance(performance);
1529
1497
  return new Trace(performance, name);
1530
1498
  }
1531
- var factory = function (container, _a) {
1532
- var settings = _a.options;
1499
+ const factory = (container, { options: settings }) => {
1533
1500
  // Dependencies
1534
- var app = container.getProvider('app').getImmediate();
1535
- var installations = container
1501
+ const app = container.getProvider('app').getImmediate();
1502
+ const installations = container
1536
1503
  .getProvider('installations-internal')
1537
1504
  .getImmediate();
1538
1505
  if (app.name !== DEFAULT_ENTRY_NAME) {
@@ -1542,15 +1509,15 @@ var factory = function (container, _a) {
1542
1509
  throw ERROR_FACTORY.create("no window" /* ErrorCode.NO_WINDOW */);
1543
1510
  }
1544
1511
  setupApi(window);
1545
- var perfInstance = new PerformanceController(app, installations);
1512
+ const perfInstance = new PerformanceController(app, installations);
1546
1513
  perfInstance._init(settings);
1547
1514
  return perfInstance;
1548
1515
  };
1549
1516
  function registerPerformance() {
1550
1517
  app._registerComponent(new component.Component('performance', factory, "PUBLIC" /* ComponentType.PUBLIC */));
1551
1518
  app.registerVersion(name, version);
1552
- // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation
1553
- app.registerVersion(name, version, 'cjs5');
1519
+ // BUILD_TARGET will be replaced by values like esm2017, cjs2017, etc during the compilation
1520
+ app.registerVersion(name, version, 'cjs2017');
1554
1521
  }
1555
1522
  registerPerformance();
1556
1523