@firebase/analytics 0.10.8 → 0.10.9-canary.a97ac88db

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,1459 +0,0 @@
1
- import { getApp, _getProvider, _registerComponent, registerVersion } from '@firebase/app';
2
- import { __awaiter, __generator, __spreadArray, __assign } from 'tslib';
3
- import { Logger } from '@firebase/logger';
4
- import { ErrorFactory, calculateBackoffMillis, FirebaseError, validateIndexedDBOpenable, isIndexedDBAvailable, isBrowserExtension, areCookiesEnabled, getModularInstance, deepEqual } from '@firebase/util';
5
- import { Component } from '@firebase/component';
6
- import '@firebase/installations';
7
-
8
- /**
9
- * @license
10
- * Copyright 2019 Google LLC
11
- *
12
- * Licensed under the Apache License, Version 2.0 (the "License");
13
- * you may not use this file except in compliance with the License.
14
- * You may obtain a copy of the License at
15
- *
16
- * http://www.apache.org/licenses/LICENSE-2.0
17
- *
18
- * Unless required by applicable law or agreed to in writing, software
19
- * distributed under the License is distributed on an "AS IS" BASIS,
20
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21
- * See the License for the specific language governing permissions and
22
- * limitations under the License.
23
- */
24
- /**
25
- * Type constant for Firebase Analytics.
26
- */
27
- var ANALYTICS_TYPE = 'analytics';
28
- // Key to attach FID to in gtag params.
29
- var GA_FID_KEY = 'firebase_id';
30
- var ORIGIN_KEY = 'origin';
31
- var FETCH_TIMEOUT_MILLIS = 60 * 1000;
32
- var DYNAMIC_CONFIG_URL = 'https://firebase.googleapis.com/v1alpha/projects/-/apps/{app-id}/webConfig';
33
- var GTAG_URL = 'https://www.googletagmanager.com/gtag/js';
34
-
35
- /**
36
- * @license
37
- * Copyright 2019 Google LLC
38
- *
39
- * Licensed under the Apache License, Version 2.0 (the "License");
40
- * you may not use this file except in compliance with the License.
41
- * You may obtain a copy of the License at
42
- *
43
- * http://www.apache.org/licenses/LICENSE-2.0
44
- *
45
- * Unless required by applicable law or agreed to in writing, software
46
- * distributed under the License is distributed on an "AS IS" BASIS,
47
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
48
- * See the License for the specific language governing permissions and
49
- * limitations under the License.
50
- */
51
- var logger = new Logger('@firebase/analytics');
52
-
53
- /**
54
- * @license
55
- * Copyright 2019 Google LLC
56
- *
57
- * Licensed under the Apache License, Version 2.0 (the "License");
58
- * you may not use this file except in compliance with the License.
59
- * You may obtain a copy of the License at
60
- *
61
- * http://www.apache.org/licenses/LICENSE-2.0
62
- *
63
- * Unless required by applicable law or agreed to in writing, software
64
- * distributed under the License is distributed on an "AS IS" BASIS,
65
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
66
- * See the License for the specific language governing permissions and
67
- * limitations under the License.
68
- */
69
- var _a;
70
- var ERRORS = (_a = {},
71
- _a["already-exists" /* AnalyticsError.ALREADY_EXISTS */] = 'A Firebase Analytics instance with the appId {$id} ' +
72
- ' already exists. ' +
73
- 'Only one Firebase Analytics instance can be created for each appId.',
74
- _a["already-initialized" /* AnalyticsError.ALREADY_INITIALIZED */] = 'initializeAnalytics() cannot be called again with different options than those ' +
75
- 'it was initially called with. It can be called again with the same options to ' +
76
- 'return the existing instance, or getAnalytics() can be used ' +
77
- 'to get a reference to the already-initialized instance.',
78
- _a["already-initialized-settings" /* AnalyticsError.ALREADY_INITIALIZED_SETTINGS */] = 'Firebase Analytics has already been initialized.' +
79
- 'settings() must be called before initializing any Analytics instance' +
80
- 'or it will have no effect.',
81
- _a["interop-component-reg-failed" /* AnalyticsError.INTEROP_COMPONENT_REG_FAILED */] = 'Firebase Analytics Interop Component failed to instantiate: {$reason}',
82
- _a["invalid-analytics-context" /* AnalyticsError.INVALID_ANALYTICS_CONTEXT */] = 'Firebase Analytics is not supported in this environment. ' +
83
- 'Wrap initialization of analytics in analytics.isSupported() ' +
84
- 'to prevent initialization in unsupported environments. Details: {$errorInfo}',
85
- _a["indexeddb-unavailable" /* AnalyticsError.INDEXEDDB_UNAVAILABLE */] = 'IndexedDB unavailable or restricted in this environment. ' +
86
- 'Wrap initialization of analytics in analytics.isSupported() ' +
87
- 'to prevent initialization in unsupported environments. Details: {$errorInfo}',
88
- _a["fetch-throttle" /* AnalyticsError.FETCH_THROTTLE */] = 'The config fetch request timed out while in an exponential backoff state.' +
89
- ' Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.',
90
- _a["config-fetch-failed" /* AnalyticsError.CONFIG_FETCH_FAILED */] = 'Dynamic config fetch failed: [{$httpStatus}] {$responseMessage}',
91
- _a["no-api-key" /* AnalyticsError.NO_API_KEY */] = 'The "apiKey" field is empty in the local Firebase config. Firebase Analytics requires this field to' +
92
- 'contain a valid API key.',
93
- _a["no-app-id" /* AnalyticsError.NO_APP_ID */] = 'The "appId" field is empty in the local Firebase config. Firebase Analytics requires this field to' +
94
- 'contain a valid app ID.',
95
- _a["no-client-id" /* AnalyticsError.NO_CLIENT_ID */] = 'The "client_id" field is empty.',
96
- _a["invalid-gtag-resource" /* AnalyticsError.INVALID_GTAG_RESOURCE */] = 'Trusted Types detected an invalid gtag resource: {$gtagURL}.',
97
- _a);
98
- var ERROR_FACTORY = new ErrorFactory('analytics', 'Analytics', ERRORS);
99
-
100
- /**
101
- * @license
102
- * Copyright 2019 Google LLC
103
- *
104
- * Licensed under the Apache License, Version 2.0 (the "License");
105
- * you may not use this file except in compliance with the License.
106
- * You may obtain a copy of the License at
107
- *
108
- * http://www.apache.org/licenses/LICENSE-2.0
109
- *
110
- * Unless required by applicable law or agreed to in writing, software
111
- * distributed under the License is distributed on an "AS IS" BASIS,
112
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
113
- * See the License for the specific language governing permissions and
114
- * limitations under the License.
115
- */
116
- /**
117
- * Verifies and creates a TrustedScriptURL.
118
- */
119
- function createGtagTrustedTypesScriptURL(url) {
120
- if (!url.startsWith(GTAG_URL)) {
121
- var err = ERROR_FACTORY.create("invalid-gtag-resource" /* AnalyticsError.INVALID_GTAG_RESOURCE */, {
122
- gtagURL: url
123
- });
124
- logger.warn(err.message);
125
- return '';
126
- }
127
- return url;
128
- }
129
- /**
130
- * Makeshift polyfill for Promise.allSettled(). Resolves when all promises
131
- * have either resolved or rejected.
132
- *
133
- * @param promises Array of promises to wait for.
134
- */
135
- function promiseAllSettled(promises) {
136
- return Promise.all(promises.map(function (promise) { return promise.catch(function (e) { return e; }); }));
137
- }
138
- /**
139
- * Creates a TrustedTypePolicy object that implements the rules passed as policyOptions.
140
- *
141
- * @param policyName A string containing the name of the policy
142
- * @param policyOptions Object containing implementations of instance methods for TrustedTypesPolicy, see {@link https://developer.mozilla.org/en-US/docs/Web/API/TrustedTypePolicy#instance_methods
143
- * | the TrustedTypePolicy reference documentation}.
144
- */
145
- function createTrustedTypesPolicy(policyName, policyOptions) {
146
- // Create a TrustedTypes policy that we can use for updating src
147
- // properties
148
- var trustedTypesPolicy;
149
- if (window.trustedTypes) {
150
- trustedTypesPolicy = window.trustedTypes.createPolicy(policyName, policyOptions);
151
- }
152
- return trustedTypesPolicy;
153
- }
154
- /**
155
- * Inserts gtag script tag into the page to asynchronously download gtag.
156
- * @param dataLayerName Name of datalayer (most often the default, "_dataLayer").
157
- */
158
- function insertScriptTag(dataLayerName, measurementId) {
159
- var trustedTypesPolicy = createTrustedTypesPolicy('firebase-js-sdk-policy', {
160
- createScriptURL: createGtagTrustedTypesScriptURL
161
- });
162
- var script = document.createElement('script');
163
- // We are not providing an analyticsId in the URL because it would trigger a `page_view`
164
- // without fid. We will initialize ga-id using gtag (config) command together with fid.
165
- var gtagScriptURL = "".concat(GTAG_URL, "?l=").concat(dataLayerName, "&id=").concat(measurementId);
166
- script.src = trustedTypesPolicy
167
- ? trustedTypesPolicy === null || trustedTypesPolicy === void 0 ? void 0 : trustedTypesPolicy.createScriptURL(gtagScriptURL)
168
- : gtagScriptURL;
169
- script.async = true;
170
- document.head.appendChild(script);
171
- }
172
- /**
173
- * Get reference to, or create, global datalayer.
174
- * @param dataLayerName Name of datalayer (most often the default, "_dataLayer").
175
- */
176
- function getOrCreateDataLayer(dataLayerName) {
177
- // Check for existing dataLayer and create if needed.
178
- var dataLayer = [];
179
- if (Array.isArray(window[dataLayerName])) {
180
- dataLayer = window[dataLayerName];
181
- }
182
- else {
183
- window[dataLayerName] = dataLayer;
184
- }
185
- return dataLayer;
186
- }
187
- /**
188
- * Wrapped gtag logic when gtag is called with 'config' command.
189
- *
190
- * @param gtagCore Basic gtag function that just appends to dataLayer.
191
- * @param initializationPromisesMap Map of appIds to their initialization promises.
192
- * @param dynamicConfigPromisesList Array of dynamic config fetch promises.
193
- * @param measurementIdToAppId Map of GA measurementIDs to corresponding Firebase appId.
194
- * @param measurementId GA Measurement ID to set config for.
195
- * @param gtagParams Gtag config params to set.
196
- */
197
- function gtagOnConfig(gtagCore, initializationPromisesMap, dynamicConfigPromisesList, measurementIdToAppId, measurementId, gtagParams) {
198
- return __awaiter(this, void 0, void 0, function () {
199
- var correspondingAppId, dynamicConfigResults, foundConfig, e_1;
200
- return __generator(this, function (_a) {
201
- switch (_a.label) {
202
- case 0:
203
- correspondingAppId = measurementIdToAppId[measurementId];
204
- _a.label = 1;
205
- case 1:
206
- _a.trys.push([1, 7, , 8]);
207
- if (!correspondingAppId) return [3 /*break*/, 3];
208
- return [4 /*yield*/, initializationPromisesMap[correspondingAppId]];
209
- case 2:
210
- _a.sent();
211
- return [3 /*break*/, 6];
212
- case 3: return [4 /*yield*/, promiseAllSettled(dynamicConfigPromisesList)];
213
- case 4:
214
- dynamicConfigResults = _a.sent();
215
- foundConfig = dynamicConfigResults.find(function (config) { return config.measurementId === measurementId; });
216
- if (!foundConfig) return [3 /*break*/, 6];
217
- return [4 /*yield*/, initializationPromisesMap[foundConfig.appId]];
218
- case 5:
219
- _a.sent();
220
- _a.label = 6;
221
- case 6: return [3 /*break*/, 8];
222
- case 7:
223
- e_1 = _a.sent();
224
- logger.error(e_1);
225
- return [3 /*break*/, 8];
226
- case 8:
227
- gtagCore("config" /* GtagCommand.CONFIG */, measurementId, gtagParams);
228
- return [2 /*return*/];
229
- }
230
- });
231
- });
232
- }
233
- /**
234
- * Wrapped gtag logic when gtag is called with 'event' command.
235
- *
236
- * @param gtagCore Basic gtag function that just appends to dataLayer.
237
- * @param initializationPromisesMap Map of appIds to their initialization promises.
238
- * @param dynamicConfigPromisesList Array of dynamic config fetch promises.
239
- * @param measurementId GA Measurement ID to log event to.
240
- * @param gtagParams Params to log with this event.
241
- */
242
- function gtagOnEvent(gtagCore, initializationPromisesMap, dynamicConfigPromisesList, measurementId, gtagParams) {
243
- return __awaiter(this, void 0, void 0, function () {
244
- var initializationPromisesToWaitFor, gaSendToList, dynamicConfigResults, _loop_1, _i, gaSendToList_1, sendToId, state_1, e_2;
245
- return __generator(this, function (_a) {
246
- switch (_a.label) {
247
- case 0:
248
- _a.trys.push([0, 4, , 5]);
249
- initializationPromisesToWaitFor = [];
250
- if (!(gtagParams && gtagParams['send_to'])) return [3 /*break*/, 2];
251
- gaSendToList = gtagParams['send_to'];
252
- // Make it an array if is isn't, so it can be dealt with the same way.
253
- if (!Array.isArray(gaSendToList)) {
254
- gaSendToList = [gaSendToList];
255
- }
256
- return [4 /*yield*/, promiseAllSettled(dynamicConfigPromisesList)];
257
- case 1:
258
- dynamicConfigResults = _a.sent();
259
- _loop_1 = function (sendToId) {
260
- // Any fetched dynamic measurement ID that matches this 'send_to' ID
261
- var foundConfig = dynamicConfigResults.find(function (config) { return config.measurementId === sendToId; });
262
- var initializationPromise = foundConfig && initializationPromisesMap[foundConfig.appId];
263
- if (initializationPromise) {
264
- initializationPromisesToWaitFor.push(initializationPromise);
265
- }
266
- else {
267
- // Found an item in 'send_to' that is not associated
268
- // directly with an FID, possibly a group. Empty this array,
269
- // exit the loop early, and let it get populated below.
270
- initializationPromisesToWaitFor = [];
271
- return "break";
272
- }
273
- };
274
- for (_i = 0, gaSendToList_1 = gaSendToList; _i < gaSendToList_1.length; _i++) {
275
- sendToId = gaSendToList_1[_i];
276
- state_1 = _loop_1(sendToId);
277
- if (state_1 === "break")
278
- break;
279
- }
280
- _a.label = 2;
281
- case 2:
282
- // This will be unpopulated if there was no 'send_to' field , or
283
- // if not all entries in the 'send_to' field could be mapped to
284
- // a FID. In these cases, wait on all pending initialization promises.
285
- if (initializationPromisesToWaitFor.length === 0) {
286
- /* eslint-disable-next-line @typescript-eslint/no-floating-promises */
287
- initializationPromisesToWaitFor = Object.values(initializationPromisesMap);
288
- }
289
- // Run core gtag function with args after all relevant initialization
290
- // promises have been resolved.
291
- return [4 /*yield*/, Promise.all(initializationPromisesToWaitFor)];
292
- case 3:
293
- // Run core gtag function with args after all relevant initialization
294
- // promises have been resolved.
295
- _a.sent();
296
- // Workaround for http://b/141370449 - third argument cannot be undefined.
297
- gtagCore("event" /* GtagCommand.EVENT */, measurementId, gtagParams || {});
298
- return [3 /*break*/, 5];
299
- case 4:
300
- e_2 = _a.sent();
301
- logger.error(e_2);
302
- return [3 /*break*/, 5];
303
- case 5: return [2 /*return*/];
304
- }
305
- });
306
- });
307
- }
308
- /**
309
- * Wraps a standard gtag function with extra code to wait for completion of
310
- * relevant initialization promises before sending requests.
311
- *
312
- * @param gtagCore Basic gtag function that just appends to dataLayer.
313
- * @param initializationPromisesMap Map of appIds to their initialization promises.
314
- * @param dynamicConfigPromisesList Array of dynamic config fetch promises.
315
- * @param measurementIdToAppId Map of GA measurementIDs to corresponding Firebase appId.
316
- */
317
- function wrapGtag(gtagCore,
318
- /**
319
- * Allows wrapped gtag calls to wait on whichever initialization promises are required,
320
- * depending on the contents of the gtag params' `send_to` field, if any.
321
- */
322
- initializationPromisesMap,
323
- /**
324
- * Wrapped gtag calls sometimes require all dynamic config fetches to have returned
325
- * before determining what initialization promises (which include FIDs) to wait for.
326
- */
327
- dynamicConfigPromisesList,
328
- /**
329
- * Wrapped gtag config calls can narrow down which initialization promise (with FID)
330
- * to wait for if the measurementId is already fetched, by getting the corresponding appId,
331
- * which is the key for the initialization promises map.
332
- */
333
- measurementIdToAppId) {
334
- /**
335
- * Wrapper around gtag that ensures FID is sent with gtag calls.
336
- * @param command Gtag command type.
337
- * @param idOrNameOrParams Measurement ID if command is EVENT/CONFIG, params if command is SET.
338
- * @param gtagParams Params if event is EVENT/CONFIG.
339
- */
340
- function gtagWrapper(command) {
341
- var args = [];
342
- for (var _i = 1; _i < arguments.length; _i++) {
343
- args[_i - 1] = arguments[_i];
344
- }
345
- return __awaiter(this, void 0, void 0, function () {
346
- var measurementId, gtagParams, measurementId, gtagParams, consentAction, gtagParams, measurementId, fieldName, callback, customParams, e_3;
347
- return __generator(this, function (_a) {
348
- switch (_a.label) {
349
- case 0:
350
- _a.trys.push([0, 6, , 7]);
351
- if (!(command === "event" /* GtagCommand.EVENT */)) return [3 /*break*/, 2];
352
- measurementId = args[0], gtagParams = args[1];
353
- // If EVENT, second arg must be measurementId.
354
- return [4 /*yield*/, gtagOnEvent(gtagCore, initializationPromisesMap, dynamicConfigPromisesList, measurementId, gtagParams)];
355
- case 1:
356
- // If EVENT, second arg must be measurementId.
357
- _a.sent();
358
- return [3 /*break*/, 5];
359
- case 2:
360
- if (!(command === "config" /* GtagCommand.CONFIG */)) return [3 /*break*/, 4];
361
- measurementId = args[0], gtagParams = args[1];
362
- // If CONFIG, second arg must be measurementId.
363
- return [4 /*yield*/, gtagOnConfig(gtagCore, initializationPromisesMap, dynamicConfigPromisesList, measurementIdToAppId, measurementId, gtagParams)];
364
- case 3:
365
- // If CONFIG, second arg must be measurementId.
366
- _a.sent();
367
- return [3 /*break*/, 5];
368
- case 4:
369
- if (command === "consent" /* GtagCommand.CONSENT */) {
370
- consentAction = args[0], gtagParams = args[1];
371
- // consentAction can be one of 'default' or 'update'.
372
- gtagCore("consent" /* GtagCommand.CONSENT */, consentAction, gtagParams);
373
- }
374
- else if (command === "get" /* GtagCommand.GET */) {
375
- measurementId = args[0], fieldName = args[1], callback = args[2];
376
- gtagCore("get" /* GtagCommand.GET */, measurementId, fieldName, callback);
377
- }
378
- else if (command === "set" /* GtagCommand.SET */) {
379
- customParams = args[0];
380
- // If SET, second arg must be params.
381
- gtagCore("set" /* GtagCommand.SET */, customParams);
382
- }
383
- else {
384
- gtagCore.apply(void 0, __spreadArray([command], args, false));
385
- }
386
- _a.label = 5;
387
- case 5: return [3 /*break*/, 7];
388
- case 6:
389
- e_3 = _a.sent();
390
- logger.error(e_3);
391
- return [3 /*break*/, 7];
392
- case 7: return [2 /*return*/];
393
- }
394
- });
395
- });
396
- }
397
- return gtagWrapper;
398
- }
399
- /**
400
- * Creates global gtag function or wraps existing one if found.
401
- * This wrapped function attaches Firebase instance ID (FID) to gtag 'config' and
402
- * 'event' calls that belong to the GAID associated with this Firebase instance.
403
- *
404
- * @param initializationPromisesMap Map of appIds to their initialization promises.
405
- * @param dynamicConfigPromisesList Array of dynamic config fetch promises.
406
- * @param measurementIdToAppId Map of GA measurementIDs to corresponding Firebase appId.
407
- * @param dataLayerName Name of global GA datalayer array.
408
- * @param gtagFunctionName Name of global gtag function ("gtag" if not user-specified).
409
- */
410
- function wrapOrCreateGtag(initializationPromisesMap, dynamicConfigPromisesList, measurementIdToAppId, dataLayerName, gtagFunctionName) {
411
- // Create a basic core gtag function
412
- var gtagCore = function () {
413
- // Must push IArguments object, not an array.
414
- window[dataLayerName].push(arguments);
415
- };
416
- // Replace it with existing one if found
417
- if (window[gtagFunctionName] &&
418
- typeof window[gtagFunctionName] === 'function') {
419
- // @ts-ignore
420
- gtagCore = window[gtagFunctionName];
421
- }
422
- window[gtagFunctionName] = wrapGtag(gtagCore, initializationPromisesMap, dynamicConfigPromisesList, measurementIdToAppId);
423
- return {
424
- gtagCore: gtagCore,
425
- wrappedGtag: window[gtagFunctionName]
426
- };
427
- }
428
- /**
429
- * Returns the script tag in the DOM matching both the gtag url pattern
430
- * and the provided data layer name.
431
- */
432
- function findGtagScriptOnPage(dataLayerName) {
433
- var scriptTags = window.document.getElementsByTagName('script');
434
- for (var _i = 0, _a = Object.values(scriptTags); _i < _a.length; _i++) {
435
- var tag = _a[_i];
436
- if (tag.src &&
437
- tag.src.includes(GTAG_URL) &&
438
- tag.src.includes(dataLayerName)) {
439
- return tag;
440
- }
441
- }
442
- return null;
443
- }
444
-
445
- /**
446
- * @license
447
- * Copyright 2020 Google LLC
448
- *
449
- * Licensed under the Apache License, Version 2.0 (the "License");
450
- * you may not use this file except in compliance with the License.
451
- * You may obtain a copy of the License at
452
- *
453
- * http://www.apache.org/licenses/LICENSE-2.0
454
- *
455
- * Unless required by applicable law or agreed to in writing, software
456
- * distributed under the License is distributed on an "AS IS" BASIS,
457
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
458
- * See the License for the specific language governing permissions and
459
- * limitations under the License.
460
- */
461
- /**
462
- * Backoff factor for 503 errors, which we want to be conservative about
463
- * to avoid overloading servers. Each retry interval will be
464
- * BASE_INTERVAL_MILLIS * LONG_RETRY_FACTOR ^ retryCount, so the second one
465
- * will be ~30 seconds (with fuzzing).
466
- */
467
- var LONG_RETRY_FACTOR = 30;
468
- /**
469
- * Base wait interval to multiplied by backoffFactor^backoffCount.
470
- */
471
- var BASE_INTERVAL_MILLIS = 1000;
472
- /**
473
- * Stubbable retry data storage class.
474
- */
475
- var RetryData = /** @class */ (function () {
476
- function RetryData(throttleMetadata, intervalMillis) {
477
- if (throttleMetadata === void 0) { throttleMetadata = {}; }
478
- if (intervalMillis === void 0) { intervalMillis = BASE_INTERVAL_MILLIS; }
479
- this.throttleMetadata = throttleMetadata;
480
- this.intervalMillis = intervalMillis;
481
- }
482
- RetryData.prototype.getThrottleMetadata = function (appId) {
483
- return this.throttleMetadata[appId];
484
- };
485
- RetryData.prototype.setThrottleMetadata = function (appId, metadata) {
486
- this.throttleMetadata[appId] = metadata;
487
- };
488
- RetryData.prototype.deleteThrottleMetadata = function (appId) {
489
- delete this.throttleMetadata[appId];
490
- };
491
- return RetryData;
492
- }());
493
- var defaultRetryData = new RetryData();
494
- /**
495
- * Set GET request headers.
496
- * @param apiKey App API key.
497
- */
498
- function getHeaders(apiKey) {
499
- return new Headers({
500
- Accept: 'application/json',
501
- 'x-goog-api-key': apiKey
502
- });
503
- }
504
- /**
505
- * Fetches dynamic config from backend.
506
- * @param app Firebase app to fetch config for.
507
- */
508
- function fetchDynamicConfig(appFields) {
509
- var _a;
510
- return __awaiter(this, void 0, void 0, function () {
511
- var appId, apiKey, request, appUrl, response, errorMessage, jsonResponse;
512
- return __generator(this, function (_b) {
513
- switch (_b.label) {
514
- case 0:
515
- appId = appFields.appId, apiKey = appFields.apiKey;
516
- request = {
517
- method: 'GET',
518
- headers: getHeaders(apiKey)
519
- };
520
- appUrl = DYNAMIC_CONFIG_URL.replace('{app-id}', appId);
521
- return [4 /*yield*/, fetch(appUrl, request)];
522
- case 1:
523
- response = _b.sent();
524
- if (!(response.status !== 200 && response.status !== 304)) return [3 /*break*/, 6];
525
- errorMessage = '';
526
- _b.label = 2;
527
- case 2:
528
- _b.trys.push([2, 4, , 5]);
529
- return [4 /*yield*/, response.json()];
530
- case 3:
531
- jsonResponse = (_b.sent());
532
- if ((_a = jsonResponse.error) === null || _a === void 0 ? void 0 : _a.message) {
533
- errorMessage = jsonResponse.error.message;
534
- }
535
- return [3 /*break*/, 5];
536
- case 4:
537
- _b.sent();
538
- return [3 /*break*/, 5];
539
- case 5: throw ERROR_FACTORY.create("config-fetch-failed" /* AnalyticsError.CONFIG_FETCH_FAILED */, {
540
- httpStatus: response.status,
541
- responseMessage: errorMessage
542
- });
543
- case 6: return [2 /*return*/, response.json()];
544
- }
545
- });
546
- });
547
- }
548
- /**
549
- * Fetches dynamic config from backend, retrying if failed.
550
- * @param app Firebase app to fetch config for.
551
- */
552
- function fetchDynamicConfigWithRetry(app,
553
- // retryData and timeoutMillis are parameterized to allow passing a different value for testing.
554
- retryData, timeoutMillis) {
555
- if (retryData === void 0) { retryData = defaultRetryData; }
556
- return __awaiter(this, void 0, void 0, function () {
557
- var _a, appId, apiKey, measurementId, throttleMetadata, signal;
558
- var _this = this;
559
- return __generator(this, function (_b) {
560
- _a = app.options, appId = _a.appId, apiKey = _a.apiKey, measurementId = _a.measurementId;
561
- if (!appId) {
562
- throw ERROR_FACTORY.create("no-app-id" /* AnalyticsError.NO_APP_ID */);
563
- }
564
- if (!apiKey) {
565
- if (measurementId) {
566
- return [2 /*return*/, {
567
- measurementId: measurementId,
568
- appId: appId
569
- }];
570
- }
571
- throw ERROR_FACTORY.create("no-api-key" /* AnalyticsError.NO_API_KEY */);
572
- }
573
- throttleMetadata = retryData.getThrottleMetadata(appId) || {
574
- backoffCount: 0,
575
- throttleEndTimeMillis: Date.now()
576
- };
577
- signal = new AnalyticsAbortSignal();
578
- setTimeout(function () { return __awaiter(_this, void 0, void 0, function () {
579
- return __generator(this, function (_a) {
580
- // Note a very low delay, eg < 10ms, can elapse before listeners are initialized.
581
- signal.abort();
582
- return [2 /*return*/];
583
- });
584
- }); }, timeoutMillis !== undefined ? timeoutMillis : FETCH_TIMEOUT_MILLIS);
585
- return [2 /*return*/, attemptFetchDynamicConfigWithRetry({ appId: appId, apiKey: apiKey, measurementId: measurementId }, throttleMetadata, signal, retryData)];
586
- });
587
- });
588
- }
589
- /**
590
- * Runs one retry attempt.
591
- * @param appFields Necessary app config fields.
592
- * @param throttleMetadata Ongoing metadata to determine throttling times.
593
- * @param signal Abort signal.
594
- */
595
- function attemptFetchDynamicConfigWithRetry(appFields, _a, signal, retryData // for testing
596
- ) {
597
- var _b;
598
- var throttleEndTimeMillis = _a.throttleEndTimeMillis, backoffCount = _a.backoffCount;
599
- if (retryData === void 0) { retryData = defaultRetryData; }
600
- return __awaiter(this, void 0, void 0, function () {
601
- var appId, measurementId, e_1, response, e_2, error, backoffMillis, throttleMetadata;
602
- return __generator(this, function (_c) {
603
- switch (_c.label) {
604
- case 0:
605
- appId = appFields.appId, measurementId = appFields.measurementId;
606
- _c.label = 1;
607
- case 1:
608
- _c.trys.push([1, 3, , 4]);
609
- return [4 /*yield*/, setAbortableTimeout(signal, throttleEndTimeMillis)];
610
- case 2:
611
- _c.sent();
612
- return [3 /*break*/, 4];
613
- case 3:
614
- e_1 = _c.sent();
615
- if (measurementId) {
616
- logger.warn("Timed out fetching this Firebase app's measurement ID from the server." +
617
- " Falling back to the measurement ID ".concat(measurementId) +
618
- " provided in the \"measurementId\" field in the local Firebase config. [".concat(e_1 === null || e_1 === void 0 ? void 0 : e_1.message, "]"));
619
- return [2 /*return*/, { appId: appId, measurementId: measurementId }];
620
- }
621
- throw e_1;
622
- case 4:
623
- _c.trys.push([4, 6, , 7]);
624
- return [4 /*yield*/, fetchDynamicConfig(appFields)];
625
- case 5:
626
- response = _c.sent();
627
- // Note the SDK only clears throttle state if response is success or non-retriable.
628
- retryData.deleteThrottleMetadata(appId);
629
- return [2 /*return*/, response];
630
- case 6:
631
- e_2 = _c.sent();
632
- error = e_2;
633
- if (!isRetriableError(error)) {
634
- retryData.deleteThrottleMetadata(appId);
635
- if (measurementId) {
636
- logger.warn("Failed to fetch this Firebase app's measurement ID from the server." +
637
- " Falling back to the measurement ID ".concat(measurementId) +
638
- " provided in the \"measurementId\" field in the local Firebase config. [".concat(error === null || error === void 0 ? void 0 : error.message, "]"));
639
- return [2 /*return*/, { appId: appId, measurementId: measurementId }];
640
- }
641
- else {
642
- throw e_2;
643
- }
644
- }
645
- backoffMillis = Number((_b = error === null || error === void 0 ? void 0 : error.customData) === null || _b === void 0 ? void 0 : _b.httpStatus) === 503
646
- ? calculateBackoffMillis(backoffCount, retryData.intervalMillis, LONG_RETRY_FACTOR)
647
- : calculateBackoffMillis(backoffCount, retryData.intervalMillis);
648
- throttleMetadata = {
649
- throttleEndTimeMillis: Date.now() + backoffMillis,
650
- backoffCount: backoffCount + 1
651
- };
652
- // Persists state.
653
- retryData.setThrottleMetadata(appId, throttleMetadata);
654
- logger.debug("Calling attemptFetch again in ".concat(backoffMillis, " millis"));
655
- return [2 /*return*/, attemptFetchDynamicConfigWithRetry(appFields, throttleMetadata, signal, retryData)];
656
- case 7: return [2 /*return*/];
657
- }
658
- });
659
- });
660
- }
661
- /**
662
- * Supports waiting on a backoff by:
663
- *
664
- * <ul>
665
- * <li>Promisifying setTimeout, so we can set a timeout in our Promise chain</li>
666
- * <li>Listening on a signal bus for abort events, just like the Fetch API</li>
667
- * <li>Failing in the same way the Fetch API fails, so timing out a live request and a throttled
668
- * request appear the same.</li>
669
- * </ul>
670
- *
671
- * <p>Visible for testing.
672
- */
673
- function setAbortableTimeout(signal, throttleEndTimeMillis) {
674
- return new Promise(function (resolve, reject) {
675
- // Derives backoff from given end time, normalizing negative numbers to zero.
676
- var backoffMillis = Math.max(throttleEndTimeMillis - Date.now(), 0);
677
- var timeout = setTimeout(resolve, backoffMillis);
678
- // Adds listener, rather than sets onabort, because signal is a shared object.
679
- signal.addEventListener(function () {
680
- clearTimeout(timeout);
681
- // If the request completes before this timeout, the rejection has no effect.
682
- reject(ERROR_FACTORY.create("fetch-throttle" /* AnalyticsError.FETCH_THROTTLE */, {
683
- throttleEndTimeMillis: throttleEndTimeMillis
684
- }));
685
- });
686
- });
687
- }
688
- /**
689
- * Returns true if the {@link Error} indicates a fetch request may succeed later.
690
- */
691
- function isRetriableError(e) {
692
- if (!(e instanceof FirebaseError) || !e.customData) {
693
- return false;
694
- }
695
- // Uses string index defined by ErrorData, which FirebaseError implements.
696
- var httpStatus = Number(e.customData['httpStatus']);
697
- return (httpStatus === 429 ||
698
- httpStatus === 500 ||
699
- httpStatus === 503 ||
700
- httpStatus === 504);
701
- }
702
- /**
703
- * Shims a minimal AbortSignal (copied from Remote Config).
704
- *
705
- * <p>AbortController's AbortSignal conveniently decouples fetch timeout logic from other aspects
706
- * of networking, such as retries. Firebase doesn't use AbortController enough to justify a
707
- * polyfill recommendation, like we do with the Fetch API, but this minimal shim can easily be
708
- * swapped out if/when we do.
709
- */
710
- var AnalyticsAbortSignal = /** @class */ (function () {
711
- function AnalyticsAbortSignal() {
712
- this.listeners = [];
713
- }
714
- AnalyticsAbortSignal.prototype.addEventListener = function (listener) {
715
- this.listeners.push(listener);
716
- };
717
- AnalyticsAbortSignal.prototype.abort = function () {
718
- this.listeners.forEach(function (listener) { return listener(); });
719
- };
720
- return AnalyticsAbortSignal;
721
- }());
722
-
723
- /**
724
- * @license
725
- * Copyright 2019 Google LLC
726
- *
727
- * Licensed under the Apache License, Version 2.0 (the "License");
728
- * you may not use this file except in compliance with the License.
729
- * You may obtain a copy of the License at
730
- *
731
- * http://www.apache.org/licenses/LICENSE-2.0
732
- *
733
- * Unless required by applicable law or agreed to in writing, software
734
- * distributed under the License is distributed on an "AS IS" BASIS,
735
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
736
- * See the License for the specific language governing permissions and
737
- * limitations under the License.
738
- */
739
- /**
740
- * Event parameters to set on 'gtag' during initialization.
741
- */
742
- var defaultEventParametersForInit;
743
- /**
744
- * Logs an analytics event through the Firebase SDK.
745
- *
746
- * @param gtagFunction Wrapped gtag function that waits for fid to be set before sending an event
747
- * @param eventName Google Analytics event name, choose from standard list or use a custom string.
748
- * @param eventParams Analytics event parameters.
749
- */
750
- function logEvent$1(gtagFunction, initializationPromise, eventName, eventParams, options) {
751
- return __awaiter(this, void 0, void 0, function () {
752
- var measurementId, params;
753
- return __generator(this, function (_a) {
754
- switch (_a.label) {
755
- case 0:
756
- if (!(options && options.global)) return [3 /*break*/, 1];
757
- gtagFunction("event" /* GtagCommand.EVENT */, eventName, eventParams);
758
- return [2 /*return*/];
759
- case 1: return [4 /*yield*/, initializationPromise];
760
- case 2:
761
- measurementId = _a.sent();
762
- params = __assign(__assign({}, eventParams), { 'send_to': measurementId });
763
- gtagFunction("event" /* GtagCommand.EVENT */, eventName, params);
764
- _a.label = 3;
765
- case 3: return [2 /*return*/];
766
- }
767
- });
768
- });
769
- }
770
- /**
771
- * Set screen_name parameter for this Google Analytics ID.
772
- *
773
- * @deprecated Use {@link logEvent} with `eventName` as 'screen_view' and add relevant `eventParams`.
774
- * See {@link https://firebase.google.com/docs/analytics/screenviews | Track Screenviews}.
775
- *
776
- * @param gtagFunction Wrapped gtag function that waits for fid to be set before sending an event
777
- * @param screenName Screen name string to set.
778
- */
779
- function setCurrentScreen$1(gtagFunction, initializationPromise, screenName, options) {
780
- return __awaiter(this, void 0, void 0, function () {
781
- var measurementId;
782
- return __generator(this, function (_a) {
783
- switch (_a.label) {
784
- case 0:
785
- if (!(options && options.global)) return [3 /*break*/, 1];
786
- gtagFunction("set" /* GtagCommand.SET */, { 'screen_name': screenName });
787
- return [2 /*return*/, Promise.resolve()];
788
- case 1: return [4 /*yield*/, initializationPromise];
789
- case 2:
790
- measurementId = _a.sent();
791
- gtagFunction("config" /* GtagCommand.CONFIG */, measurementId, {
792
- update: true,
793
- 'screen_name': screenName
794
- });
795
- _a.label = 3;
796
- case 3: return [2 /*return*/];
797
- }
798
- });
799
- });
800
- }
801
- /**
802
- * Set user_id parameter for this Google Analytics ID.
803
- *
804
- * @param gtagFunction Wrapped gtag function that waits for fid to be set before sending an event
805
- * @param id User ID string to set
806
- */
807
- function setUserId$1(gtagFunction, initializationPromise, id, options) {
808
- return __awaiter(this, void 0, void 0, function () {
809
- var measurementId;
810
- return __generator(this, function (_a) {
811
- switch (_a.label) {
812
- case 0:
813
- if (!(options && options.global)) return [3 /*break*/, 1];
814
- gtagFunction("set" /* GtagCommand.SET */, { 'user_id': id });
815
- return [2 /*return*/, Promise.resolve()];
816
- case 1: return [4 /*yield*/, initializationPromise];
817
- case 2:
818
- measurementId = _a.sent();
819
- gtagFunction("config" /* GtagCommand.CONFIG */, measurementId, {
820
- update: true,
821
- 'user_id': id
822
- });
823
- _a.label = 3;
824
- case 3: return [2 /*return*/];
825
- }
826
- });
827
- });
828
- }
829
- /**
830
- * Set all other user properties other than user_id and screen_name.
831
- *
832
- * @param gtagFunction Wrapped gtag function that waits for fid to be set before sending an event
833
- * @param properties Map of user properties to set
834
- */
835
- function setUserProperties$1(gtagFunction, initializationPromise, properties, options) {
836
- return __awaiter(this, void 0, void 0, function () {
837
- var flatProperties, _i, _a, key, measurementId;
838
- return __generator(this, function (_b) {
839
- switch (_b.label) {
840
- case 0:
841
- if (!(options && options.global)) return [3 /*break*/, 1];
842
- flatProperties = {};
843
- for (_i = 0, _a = Object.keys(properties); _i < _a.length; _i++) {
844
- key = _a[_i];
845
- // use dot notation for merge behavior in gtag.js
846
- flatProperties["user_properties.".concat(key)] = properties[key];
847
- }
848
- gtagFunction("set" /* GtagCommand.SET */, flatProperties);
849
- return [2 /*return*/, Promise.resolve()];
850
- case 1: return [4 /*yield*/, initializationPromise];
851
- case 2:
852
- measurementId = _b.sent();
853
- gtagFunction("config" /* GtagCommand.CONFIG */, measurementId, {
854
- update: true,
855
- 'user_properties': properties
856
- });
857
- _b.label = 3;
858
- case 3: return [2 /*return*/];
859
- }
860
- });
861
- });
862
- }
863
- /**
864
- * Retrieves a unique Google Analytics identifier for the web client.
865
- * See {@link https://developers.google.com/analytics/devguides/collection/ga4/reference/config#client_id | client_id}.
866
- *
867
- * @param gtagFunction Wrapped gtag function that waits for fid to be set before sending an event
868
- */
869
- function internalGetGoogleAnalyticsClientId(gtagFunction, initializationPromise) {
870
- return __awaiter(this, void 0, void 0, function () {
871
- var measurementId;
872
- return __generator(this, function (_a) {
873
- switch (_a.label) {
874
- case 0: return [4 /*yield*/, initializationPromise];
875
- case 1:
876
- measurementId = _a.sent();
877
- return [2 /*return*/, new Promise(function (resolve, reject) {
878
- gtagFunction("get" /* GtagCommand.GET */, measurementId, 'client_id', function (clientId) {
879
- if (!clientId) {
880
- reject(ERROR_FACTORY.create("no-client-id" /* AnalyticsError.NO_CLIENT_ID */));
881
- }
882
- resolve(clientId);
883
- });
884
- })];
885
- }
886
- });
887
- });
888
- }
889
- /**
890
- * Set whether collection is enabled for this ID.
891
- *
892
- * @param enabled If true, collection is enabled for this ID.
893
- */
894
- function setAnalyticsCollectionEnabled$1(initializationPromise, enabled) {
895
- return __awaiter(this, void 0, void 0, function () {
896
- var measurementId;
897
- return __generator(this, function (_a) {
898
- switch (_a.label) {
899
- case 0: return [4 /*yield*/, initializationPromise];
900
- case 1:
901
- measurementId = _a.sent();
902
- window["ga-disable-".concat(measurementId)] = !enabled;
903
- return [2 /*return*/];
904
- }
905
- });
906
- });
907
- }
908
- /**
909
- * Consent parameters to default to during 'gtag' initialization.
910
- */
911
- var defaultConsentSettingsForInit;
912
- /**
913
- * Sets the variable {@link defaultConsentSettingsForInit} for use in the initialization of
914
- * analytics.
915
- *
916
- * @param consentSettings Maps the applicable end user consent state for gtag.js.
917
- */
918
- function _setConsentDefaultForInit(consentSettings) {
919
- defaultConsentSettingsForInit = consentSettings;
920
- }
921
- /**
922
- * Sets the variable `defaultEventParametersForInit` for use in the initialization of
923
- * analytics.
924
- *
925
- * @param customParams Any custom params the user may pass to gtag.js.
926
- */
927
- function _setDefaultEventParametersForInit(customParams) {
928
- defaultEventParametersForInit = customParams;
929
- }
930
-
931
- /**
932
- * @license
933
- * Copyright 2020 Google LLC
934
- *
935
- * Licensed under the Apache License, Version 2.0 (the "License");
936
- * you may not use this file except in compliance with the License.
937
- * You may obtain a copy of the License at
938
- *
939
- * http://www.apache.org/licenses/LICENSE-2.0
940
- *
941
- * Unless required by applicable law or agreed to in writing, software
942
- * distributed under the License is distributed on an "AS IS" BASIS,
943
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
944
- * See the License for the specific language governing permissions and
945
- * limitations under the License.
946
- */
947
- function validateIndexedDB() {
948
- return __awaiter(this, void 0, void 0, function () {
949
- var e_1;
950
- return __generator(this, function (_a) {
951
- switch (_a.label) {
952
- case 0:
953
- if (!!isIndexedDBAvailable()) return [3 /*break*/, 1];
954
- logger.warn(ERROR_FACTORY.create("indexeddb-unavailable" /* AnalyticsError.INDEXEDDB_UNAVAILABLE */, {
955
- errorInfo: 'IndexedDB is not available in this environment.'
956
- }).message);
957
- return [2 /*return*/, false];
958
- case 1:
959
- _a.trys.push([1, 3, , 4]);
960
- return [4 /*yield*/, validateIndexedDBOpenable()];
961
- case 2:
962
- _a.sent();
963
- return [3 /*break*/, 4];
964
- case 3:
965
- e_1 = _a.sent();
966
- logger.warn(ERROR_FACTORY.create("indexeddb-unavailable" /* AnalyticsError.INDEXEDDB_UNAVAILABLE */, {
967
- errorInfo: e_1 === null || e_1 === void 0 ? void 0 : e_1.toString()
968
- }).message);
969
- return [2 /*return*/, false];
970
- case 4: return [2 /*return*/, true];
971
- }
972
- });
973
- });
974
- }
975
- /**
976
- * Initialize the analytics instance in gtag.js by calling config command with fid.
977
- *
978
- * NOTE: We combine analytics initialization and setting fid together because we want fid to be
979
- * part of the `page_view` event that's sent during the initialization
980
- * @param app Firebase app
981
- * @param gtagCore The gtag function that's not wrapped.
982
- * @param dynamicConfigPromisesList Array of all dynamic config promises.
983
- * @param measurementIdToAppId Maps measurementID to appID.
984
- * @param installations _FirebaseInstallationsInternal instance.
985
- *
986
- * @returns Measurement ID.
987
- */
988
- function _initializeAnalytics(app, dynamicConfigPromisesList, measurementIdToAppId, installations, gtagCore, dataLayerName, options) {
989
- var _a;
990
- return __awaiter(this, void 0, void 0, function () {
991
- var dynamicConfigPromise, fidPromise, _b, dynamicConfig, fid, configProperties;
992
- return __generator(this, function (_c) {
993
- switch (_c.label) {
994
- case 0:
995
- dynamicConfigPromise = fetchDynamicConfigWithRetry(app);
996
- // Once fetched, map measurementIds to appId, for ease of lookup in wrapped gtag function.
997
- dynamicConfigPromise
998
- .then(function (config) {
999
- measurementIdToAppId[config.measurementId] = config.appId;
1000
- if (app.options.measurementId &&
1001
- config.measurementId !== app.options.measurementId) {
1002
- logger.warn("The measurement ID in the local Firebase config (".concat(app.options.measurementId, ")") +
1003
- " does not match the measurement ID fetched from the server (".concat(config.measurementId, ").") +
1004
- " To ensure analytics events are always sent to the correct Analytics property," +
1005
- " update the" +
1006
- " measurement ID field in the local config or remove it from the local config.");
1007
- }
1008
- })
1009
- .catch(function (e) { return logger.error(e); });
1010
- // Add to list to track state of all dynamic config promises.
1011
- dynamicConfigPromisesList.push(dynamicConfigPromise);
1012
- fidPromise = validateIndexedDB().then(function (envIsValid) {
1013
- if (envIsValid) {
1014
- return installations.getId();
1015
- }
1016
- else {
1017
- return undefined;
1018
- }
1019
- });
1020
- return [4 /*yield*/, Promise.all([
1021
- dynamicConfigPromise,
1022
- fidPromise
1023
- ])];
1024
- case 1:
1025
- _b = _c.sent(), dynamicConfig = _b[0], fid = _b[1];
1026
- // Detect if user has already put the gtag <script> tag on this page with the passed in
1027
- // data layer name.
1028
- if (!findGtagScriptOnPage(dataLayerName)) {
1029
- insertScriptTag(dataLayerName, dynamicConfig.measurementId);
1030
- }
1031
- // Detects if there are consent settings that need to be configured.
1032
- if (defaultConsentSettingsForInit) {
1033
- gtagCore("consent" /* GtagCommand.CONSENT */, 'default', defaultConsentSettingsForInit);
1034
- _setConsentDefaultForInit(undefined);
1035
- }
1036
- // This command initializes gtag.js and only needs to be called once for the entire web app,
1037
- // but since it is idempotent, we can call it multiple times.
1038
- // We keep it together with other initialization logic for better code structure.
1039
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1040
- gtagCore('js', new Date());
1041
- configProperties = (_a = options === null || options === void 0 ? void 0 : options.config) !== null && _a !== void 0 ? _a : {};
1042
- // guard against developers accidentally setting properties with prefix `firebase_`
1043
- configProperties[ORIGIN_KEY] = 'firebase';
1044
- configProperties.update = true;
1045
- if (fid != null) {
1046
- configProperties[GA_FID_KEY] = fid;
1047
- }
1048
- // It should be the first config command called on this GA-ID
1049
- // Initialize this GA-ID and set FID on it using the gtag config API.
1050
- // Note: This will trigger a page_view event unless 'send_page_view' is set to false in
1051
- // `configProperties`.
1052
- gtagCore("config" /* GtagCommand.CONFIG */, dynamicConfig.measurementId, configProperties);
1053
- // Detects if there is data that will be set on every event logged from the SDK.
1054
- if (defaultEventParametersForInit) {
1055
- gtagCore("set" /* GtagCommand.SET */, defaultEventParametersForInit);
1056
- _setDefaultEventParametersForInit(undefined);
1057
- }
1058
- return [2 /*return*/, dynamicConfig.measurementId];
1059
- }
1060
- });
1061
- });
1062
- }
1063
-
1064
- /**
1065
- * @license
1066
- * Copyright 2019 Google LLC
1067
- *
1068
- * Licensed under the Apache License, Version 2.0 (the "License");
1069
- * you may not use this file except in compliance with the License.
1070
- * You may obtain a copy of the License at
1071
- *
1072
- * http://www.apache.org/licenses/LICENSE-2.0
1073
- *
1074
- * Unless required by applicable law or agreed to in writing, software
1075
- * distributed under the License is distributed on an "AS IS" BASIS,
1076
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1077
- * See the License for the specific language governing permissions and
1078
- * limitations under the License.
1079
- */
1080
- /**
1081
- * Analytics Service class.
1082
- */
1083
- var AnalyticsService = /** @class */ (function () {
1084
- function AnalyticsService(app) {
1085
- this.app = app;
1086
- }
1087
- AnalyticsService.prototype._delete = function () {
1088
- delete initializationPromisesMap[this.app.options.appId];
1089
- return Promise.resolve();
1090
- };
1091
- return AnalyticsService;
1092
- }());
1093
- /**
1094
- * Maps appId to full initialization promise. Wrapped gtag calls must wait on
1095
- * all or some of these, depending on the call's `send_to` param and the status
1096
- * of the dynamic config fetches (see below).
1097
- */
1098
- var initializationPromisesMap = {};
1099
- /**
1100
- * List of dynamic config fetch promises. In certain cases, wrapped gtag calls
1101
- * wait on all these to be complete in order to determine if it can selectively
1102
- * wait for only certain initialization (FID) promises or if it must wait for all.
1103
- */
1104
- var dynamicConfigPromisesList = [];
1105
- /**
1106
- * Maps fetched measurementIds to appId. Populated when the app's dynamic config
1107
- * fetch completes. If already populated, gtag config calls can use this to
1108
- * selectively wait for only this app's initialization promise (FID) instead of all
1109
- * initialization promises.
1110
- */
1111
- var measurementIdToAppId = {};
1112
- /**
1113
- * Name for window global data layer array used by GA: defaults to 'dataLayer'.
1114
- */
1115
- var dataLayerName = 'dataLayer';
1116
- /**
1117
- * Name for window global gtag function used by GA: defaults to 'gtag'.
1118
- */
1119
- var gtagName = 'gtag';
1120
- /**
1121
- * Reproduction of standard gtag function or reference to existing
1122
- * gtag function on window object.
1123
- */
1124
- var gtagCoreFunction;
1125
- /**
1126
- * Wrapper around gtag function that ensures FID is sent with all
1127
- * relevant event and config calls.
1128
- */
1129
- var wrappedGtagFunction;
1130
- /**
1131
- * Flag to ensure page initialization steps (creation or wrapping of
1132
- * dataLayer and gtag script) are only run once per page load.
1133
- */
1134
- var globalInitDone = false;
1135
- /**
1136
- * Configures Firebase Analytics to use custom `gtag` or `dataLayer` names.
1137
- * Intended to be used if `gtag.js` script has been installed on
1138
- * this page independently of Firebase Analytics, and is using non-default
1139
- * names for either the `gtag` function or for `dataLayer`.
1140
- * Must be called before calling `getAnalytics()` or it won't
1141
- * have any effect.
1142
- *
1143
- * @public
1144
- *
1145
- * @param options - Custom gtag and dataLayer names.
1146
- */
1147
- function settings(options) {
1148
- if (globalInitDone) {
1149
- throw ERROR_FACTORY.create("already-initialized" /* AnalyticsError.ALREADY_INITIALIZED */);
1150
- }
1151
- if (options.dataLayerName) {
1152
- dataLayerName = options.dataLayerName;
1153
- }
1154
- if (options.gtagName) {
1155
- gtagName = options.gtagName;
1156
- }
1157
- }
1158
- /**
1159
- * Returns true if no environment mismatch is found.
1160
- * If environment mismatches are found, throws an INVALID_ANALYTICS_CONTEXT
1161
- * error that also lists details for each mismatch found.
1162
- */
1163
- function warnOnBrowserContextMismatch() {
1164
- var mismatchedEnvMessages = [];
1165
- if (isBrowserExtension()) {
1166
- mismatchedEnvMessages.push('This is a browser extension environment.');
1167
- }
1168
- if (!areCookiesEnabled()) {
1169
- mismatchedEnvMessages.push('Cookies are not available.');
1170
- }
1171
- if (mismatchedEnvMessages.length > 0) {
1172
- var details = mismatchedEnvMessages
1173
- .map(function (message, index) { return "(".concat(index + 1, ") ").concat(message); })
1174
- .join(' ');
1175
- var err = ERROR_FACTORY.create("invalid-analytics-context" /* AnalyticsError.INVALID_ANALYTICS_CONTEXT */, {
1176
- errorInfo: details
1177
- });
1178
- logger.warn(err.message);
1179
- }
1180
- }
1181
- /**
1182
- * Analytics instance factory.
1183
- * @internal
1184
- */
1185
- function factory(app, installations, options) {
1186
- warnOnBrowserContextMismatch();
1187
- var appId = app.options.appId;
1188
- if (!appId) {
1189
- throw ERROR_FACTORY.create("no-app-id" /* AnalyticsError.NO_APP_ID */);
1190
- }
1191
- if (!app.options.apiKey) {
1192
- if (app.options.measurementId) {
1193
- logger.warn("The \"apiKey\" field is empty in the local Firebase config. This is needed to fetch the latest" +
1194
- " measurement ID for this Firebase app. Falling back to the measurement ID ".concat(app.options.measurementId) +
1195
- " provided in the \"measurementId\" field in the local Firebase config.");
1196
- }
1197
- else {
1198
- throw ERROR_FACTORY.create("no-api-key" /* AnalyticsError.NO_API_KEY */);
1199
- }
1200
- }
1201
- if (initializationPromisesMap[appId] != null) {
1202
- throw ERROR_FACTORY.create("already-exists" /* AnalyticsError.ALREADY_EXISTS */, {
1203
- id: appId
1204
- });
1205
- }
1206
- if (!globalInitDone) {
1207
- // Steps here should only be done once per page: creation or wrapping
1208
- // of dataLayer and global gtag function.
1209
- getOrCreateDataLayer(dataLayerName);
1210
- var _a = wrapOrCreateGtag(initializationPromisesMap, dynamicConfigPromisesList, measurementIdToAppId, dataLayerName, gtagName), wrappedGtag = _a.wrappedGtag, gtagCore = _a.gtagCore;
1211
- wrappedGtagFunction = wrappedGtag;
1212
- gtagCoreFunction = gtagCore;
1213
- globalInitDone = true;
1214
- }
1215
- // Async but non-blocking.
1216
- // This map reflects the completion state of all promises for each appId.
1217
- initializationPromisesMap[appId] = _initializeAnalytics(app, dynamicConfigPromisesList, measurementIdToAppId, installations, gtagCoreFunction, dataLayerName, options);
1218
- var analyticsInstance = new AnalyticsService(app);
1219
- return analyticsInstance;
1220
- }
1221
-
1222
- /* eslint-disable @typescript-eslint/no-explicit-any */
1223
- /**
1224
- * Returns an {@link Analytics} instance for the given app.
1225
- *
1226
- * @public
1227
- *
1228
- * @param app - The {@link @firebase/app#FirebaseApp} to use.
1229
- */
1230
- function getAnalytics(app) {
1231
- if (app === void 0) { app = getApp(); }
1232
- app = getModularInstance(app);
1233
- // Dependencies
1234
- var analyticsProvider = _getProvider(app, ANALYTICS_TYPE);
1235
- if (analyticsProvider.isInitialized()) {
1236
- return analyticsProvider.getImmediate();
1237
- }
1238
- return initializeAnalytics(app);
1239
- }
1240
- /**
1241
- * Returns an {@link Analytics} instance for the given app.
1242
- *
1243
- * @public
1244
- *
1245
- * @param app - The {@link @firebase/app#FirebaseApp} to use.
1246
- */
1247
- function initializeAnalytics(app, options) {
1248
- if (options === void 0) { options = {}; }
1249
- // Dependencies
1250
- var analyticsProvider = _getProvider(app, ANALYTICS_TYPE);
1251
- if (analyticsProvider.isInitialized()) {
1252
- var existingInstance = analyticsProvider.getImmediate();
1253
- if (deepEqual(options, analyticsProvider.getOptions())) {
1254
- return existingInstance;
1255
- }
1256
- else {
1257
- throw ERROR_FACTORY.create("already-initialized" /* AnalyticsError.ALREADY_INITIALIZED */);
1258
- }
1259
- }
1260
- var analyticsInstance = analyticsProvider.initialize({ options: options });
1261
- return analyticsInstance;
1262
- }
1263
- /**
1264
- * This is a public static method provided to users that wraps four different checks:
1265
- *
1266
- * 1. Check if it's not a browser extension environment.
1267
- * 2. Check if cookies are enabled in current browser.
1268
- * 3. Check if IndexedDB is supported by the browser environment.
1269
- * 4. Check if the current browser context is valid for using `IndexedDB.open()`.
1270
- *
1271
- * @public
1272
- *
1273
- */
1274
- function isSupported() {
1275
- return __awaiter(this, void 0, void 0, function () {
1276
- var isDBOpenable;
1277
- return __generator(this, function (_a) {
1278
- switch (_a.label) {
1279
- case 0:
1280
- if (isBrowserExtension()) {
1281
- return [2 /*return*/, false];
1282
- }
1283
- if (!areCookiesEnabled()) {
1284
- return [2 /*return*/, false];
1285
- }
1286
- if (!isIndexedDBAvailable()) {
1287
- return [2 /*return*/, false];
1288
- }
1289
- _a.label = 1;
1290
- case 1:
1291
- _a.trys.push([1, 3, , 4]);
1292
- return [4 /*yield*/, validateIndexedDBOpenable()];
1293
- case 2:
1294
- isDBOpenable = _a.sent();
1295
- return [2 /*return*/, isDBOpenable];
1296
- case 3:
1297
- _a.sent();
1298
- return [2 /*return*/, false];
1299
- case 4: return [2 /*return*/];
1300
- }
1301
- });
1302
- });
1303
- }
1304
- /**
1305
- * Use gtag `config` command to set `screen_name`.
1306
- *
1307
- * @public
1308
- *
1309
- * @deprecated Use {@link logEvent} with `eventName` as 'screen_view' and add relevant `eventParams`.
1310
- * See {@link https://firebase.google.com/docs/analytics/screenviews | Track Screenviews}.
1311
- *
1312
- * @param analyticsInstance - The {@link Analytics} instance.
1313
- * @param screenName - Screen name to set.
1314
- */
1315
- function setCurrentScreen(analyticsInstance, screenName, options) {
1316
- analyticsInstance = getModularInstance(analyticsInstance);
1317
- setCurrentScreen$1(wrappedGtagFunction, initializationPromisesMap[analyticsInstance.app.options.appId], screenName, options).catch(function (e) { return logger.error(e); });
1318
- }
1319
- /**
1320
- * Retrieves a unique Google Analytics identifier for the web client.
1321
- * See {@link https://developers.google.com/analytics/devguides/collection/ga4/reference/config#client_id | client_id}.
1322
- *
1323
- * @public
1324
- *
1325
- * @param app - The {@link @firebase/app#FirebaseApp} to use.
1326
- */
1327
- function getGoogleAnalyticsClientId(analyticsInstance) {
1328
- return __awaiter(this, void 0, void 0, function () {
1329
- return __generator(this, function (_a) {
1330
- analyticsInstance = getModularInstance(analyticsInstance);
1331
- return [2 /*return*/, internalGetGoogleAnalyticsClientId(wrappedGtagFunction, initializationPromisesMap[analyticsInstance.app.options.appId])];
1332
- });
1333
- });
1334
- }
1335
- /**
1336
- * Use gtag `config` command to set `user_id`.
1337
- *
1338
- * @public
1339
- *
1340
- * @param analyticsInstance - The {@link Analytics} instance.
1341
- * @param id - User ID to set.
1342
- */
1343
- function setUserId(analyticsInstance, id, options) {
1344
- analyticsInstance = getModularInstance(analyticsInstance);
1345
- setUserId$1(wrappedGtagFunction, initializationPromisesMap[analyticsInstance.app.options.appId], id, options).catch(function (e) { return logger.error(e); });
1346
- }
1347
- /**
1348
- * Use gtag `config` command to set all params specified.
1349
- *
1350
- * @public
1351
- */
1352
- function setUserProperties(analyticsInstance, properties, options) {
1353
- analyticsInstance = getModularInstance(analyticsInstance);
1354
- setUserProperties$1(wrappedGtagFunction, initializationPromisesMap[analyticsInstance.app.options.appId], properties, options).catch(function (e) { return logger.error(e); });
1355
- }
1356
- /**
1357
- * Sets whether Google Analytics collection is enabled for this app on this device.
1358
- * Sets global `window['ga-disable-analyticsId'] = true;`
1359
- *
1360
- * @public
1361
- *
1362
- * @param analyticsInstance - The {@link Analytics} instance.
1363
- * @param enabled - If true, enables collection, if false, disables it.
1364
- */
1365
- function setAnalyticsCollectionEnabled(analyticsInstance, enabled) {
1366
- analyticsInstance = getModularInstance(analyticsInstance);
1367
- setAnalyticsCollectionEnabled$1(initializationPromisesMap[analyticsInstance.app.options.appId], enabled).catch(function (e) { return logger.error(e); });
1368
- }
1369
- /**
1370
- * Adds data that will be set on every event logged from the SDK, including automatic ones.
1371
- * With gtag's "set" command, the values passed persist on the current page and are passed with
1372
- * all subsequent events.
1373
- * @public
1374
- * @param customParams - Any custom params the user may pass to gtag.js.
1375
- */
1376
- function setDefaultEventParameters(customParams) {
1377
- // Check if reference to existing gtag function on window object exists
1378
- if (wrappedGtagFunction) {
1379
- wrappedGtagFunction("set" /* GtagCommand.SET */, customParams);
1380
- }
1381
- else {
1382
- _setDefaultEventParametersForInit(customParams);
1383
- }
1384
- }
1385
- /**
1386
- * Sends a Google Analytics event with given `eventParams`. This method
1387
- * automatically associates this logged event with this Firebase web
1388
- * app instance on this device.
1389
- * List of official event parameters can be found in the gtag.js
1390
- * reference documentation:
1391
- * {@link https://developers.google.com/gtagjs/reference/ga4-events
1392
- * | the GA4 reference documentation}.
1393
- *
1394
- * @public
1395
- */
1396
- function logEvent(analyticsInstance, eventName, eventParams, options) {
1397
- analyticsInstance = getModularInstance(analyticsInstance);
1398
- logEvent$1(wrappedGtagFunction, initializationPromisesMap[analyticsInstance.app.options.appId], eventName, eventParams, options).catch(function (e) { return logger.error(e); });
1399
- }
1400
- /**
1401
- * Sets the applicable end user consent state for this web app across all gtag references once
1402
- * Firebase Analytics is initialized.
1403
- *
1404
- * Use the {@link ConsentSettings} to specify individual consent type values. By default consent
1405
- * types are set to "granted".
1406
- * @public
1407
- * @param consentSettings - Maps the applicable end user consent state for gtag.js.
1408
- */
1409
- function setConsent(consentSettings) {
1410
- // Check if reference to existing gtag function on window object exists
1411
- if (wrappedGtagFunction) {
1412
- wrappedGtagFunction("consent" /* GtagCommand.CONSENT */, 'update', consentSettings);
1413
- }
1414
- else {
1415
- _setConsentDefaultForInit(consentSettings);
1416
- }
1417
- }
1418
-
1419
- var name = "@firebase/analytics";
1420
- var version = "0.10.8";
1421
-
1422
- /**
1423
- * The Firebase Analytics Web SDK.
1424
- * This SDK does not work in a Node.js environment.
1425
- *
1426
- * @packageDocumentation
1427
- */
1428
- function registerAnalytics() {
1429
- _registerComponent(new Component(ANALYTICS_TYPE, function (container, _a) {
1430
- var analyticsOptions = _a.options;
1431
- // getImmediate for FirebaseApp will always succeed
1432
- var app = container.getProvider('app').getImmediate();
1433
- var installations = container
1434
- .getProvider('installations-internal')
1435
- .getImmediate();
1436
- return factory(app, installations, analyticsOptions);
1437
- }, "PUBLIC" /* ComponentType.PUBLIC */));
1438
- _registerComponent(new Component('analytics-internal', internalFactory, "PRIVATE" /* ComponentType.PRIVATE */));
1439
- registerVersion(name, version);
1440
- // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation
1441
- registerVersion(name, version, 'esm5');
1442
- function internalFactory(container) {
1443
- try {
1444
- var analytics_1 = container.getProvider(ANALYTICS_TYPE).getImmediate();
1445
- return {
1446
- logEvent: function (eventName, eventParams, options) { return logEvent(analytics_1, eventName, eventParams, options); }
1447
- };
1448
- }
1449
- catch (e) {
1450
- throw ERROR_FACTORY.create("interop-component-reg-failed" /* AnalyticsError.INTEROP_COMPONENT_REG_FAILED */, {
1451
- reason: e
1452
- });
1453
- }
1454
- }
1455
- }
1456
- registerAnalytics();
1457
-
1458
- export { getAnalytics, getGoogleAnalyticsClientId, initializeAnalytics, isSupported, logEvent, setAnalyticsCollectionEnabled, setConsent, setCurrentScreen, setDefaultEventParameters, setUserId, setUserProperties, settings };
1459
- //# sourceMappingURL=index.esm.js.map