UNPKG

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