123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377 |
- 'use strict';
-
- Object.defineProperty(exports, '__esModule', { value: true });
-
- var app = require('@firebase/app');
- var tslib = require('tslib');
- var logger$1 = require('@firebase/logger');
- var util = require('@firebase/util');
- var component = require('@firebase/component');
- require('@firebase/installations');
-
-
-
- var ANALYTICS_TYPE = 'analytics';
-
- var GA_FID_KEY = 'firebase_id';
- var ORIGIN_KEY = 'origin';
- var FETCH_TIMEOUT_MILLIS = 60 * 1000;
- var DYNAMIC_CONFIG_URL = 'https://firebase.googleapis.com/v1alpha/projects/-/apps/{app-id}/webConfig';
- var GTAG_URL = 'https://www.googletagmanager.com/gtag/js';
-
-
- var logger = new logger$1.Logger('@firebase/analytics');
-
-
-
- function promiseAllSettled(promises) {
- return Promise.all(promises.map(function (promise) { return promise.catch(function (e) { return e; }); }));
- }
-
- function insertScriptTag(dataLayerName, measurementId) {
- var script = document.createElement('script');
-
-
- script.src = "".concat(GTAG_URL, "?l=").concat(dataLayerName, "&id=").concat(measurementId);
- script.async = true;
- document.head.appendChild(script);
- }
-
- function getOrCreateDataLayer(dataLayerName) {
-
- var dataLayer = [];
- if (Array.isArray(window[dataLayerName])) {
- dataLayer = window[dataLayerName];
- }
- else {
- window[dataLayerName] = dataLayer;
- }
- return dataLayer;
- }
-
- function gtagOnConfig(gtagCore, initializationPromisesMap, dynamicConfigPromisesList, measurementIdToAppId, measurementId, gtagParams) {
- return tslib.__awaiter(this, void 0, void 0, function () {
- var correspondingAppId, dynamicConfigResults, foundConfig, e_1;
- return tslib.__generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- correspondingAppId = measurementIdToAppId[measurementId];
- _a.label = 1;
- case 1:
- _a.trys.push([1, 7, , 8]);
- if (!correspondingAppId) return [3 , 3];
- return [4 , initializationPromisesMap[correspondingAppId]];
- case 2:
- _a.sent();
- return [3 , 6];
- case 3: return [4 , promiseAllSettled(dynamicConfigPromisesList)];
- case 4:
- dynamicConfigResults = _a.sent();
- foundConfig = dynamicConfigResults.find(function (config) { return config.measurementId === measurementId; });
- if (!foundConfig) return [3 , 6];
- return [4 , initializationPromisesMap[foundConfig.appId]];
- case 5:
- _a.sent();
- _a.label = 6;
- case 6: return [3 , 8];
- case 7:
- e_1 = _a.sent();
- logger.error(e_1);
- return [3 , 8];
- case 8:
- gtagCore("config" , measurementId, gtagParams);
- return [2 ];
- }
- });
- });
- }
-
- function gtagOnEvent(gtagCore, initializationPromisesMap, dynamicConfigPromisesList, measurementId, gtagParams) {
- return tslib.__awaiter(this, void 0, void 0, function () {
- var initializationPromisesToWaitFor, gaSendToList, dynamicConfigResults, _loop_1, _i, gaSendToList_1, sendToId, state_1, e_2;
- return tslib.__generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- _a.trys.push([0, 4, , 5]);
- initializationPromisesToWaitFor = [];
- if (!(gtagParams && gtagParams['send_to'])) return [3 , 2];
- gaSendToList = gtagParams['send_to'];
-
- if (!Array.isArray(gaSendToList)) {
- gaSendToList = [gaSendToList];
- }
- return [4 , promiseAllSettled(dynamicConfigPromisesList)];
- case 1:
- dynamicConfigResults = _a.sent();
- _loop_1 = function (sendToId) {
-
- var foundConfig = dynamicConfigResults.find(function (config) { return config.measurementId === sendToId; });
- var initializationPromise = foundConfig && initializationPromisesMap[foundConfig.appId];
- if (initializationPromise) {
- initializationPromisesToWaitFor.push(initializationPromise);
- }
- else {
-
-
-
- initializationPromisesToWaitFor = [];
- return "break";
- }
- };
- for (_i = 0, gaSendToList_1 = gaSendToList; _i < gaSendToList_1.length; _i++) {
- sendToId = gaSendToList_1[_i];
- state_1 = _loop_1(sendToId);
- if (state_1 === "break")
- break;
- }
- _a.label = 2;
- case 2:
-
-
-
- if (initializationPromisesToWaitFor.length === 0) {
- initializationPromisesToWaitFor = Object.values(initializationPromisesMap);
- }
-
-
- return [4 , Promise.all(initializationPromisesToWaitFor)];
- case 3:
-
-
- _a.sent();
-
- gtagCore("event" , measurementId, gtagParams || {});
- return [3 , 5];
- case 4:
- e_2 = _a.sent();
- logger.error(e_2);
- return [3 , 5];
- case 5: return [2 ];
- }
- });
- });
- }
-
- function wrapGtag(gtagCore,
- /**
- * Allows wrapped gtag calls to wait on whichever intialization promises are required,
- * depending on the contents of the gtag params' `send_to` field, if any.
- */
- initializationPromisesMap,
- /**
- * Wrapped gtag calls sometimes require all dynamic config fetches to have returned
- * before determining what initialization promises (which include FIDs) to wait for.
- */
- dynamicConfigPromisesList,
- /**
- * Wrapped gtag config calls can narrow down which initialization promise (with FID)
- * to wait for if the measurementId is already fetched, by getting the corresponding appId,
- * which is the key for the initialization promises map.
- */
- measurementIdToAppId) {
-
-
- function gtagWrapper(command, idOrNameOrParams, gtagParams) {
- return tslib.__awaiter(this, void 0, void 0, function () {
- var e_3;
- return tslib.__generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- _a.trys.push([0, 6, , 7]);
- if (!(command === "event" )) return [3 , 2];
-
- return [4 , gtagOnEvent(gtagCore, initializationPromisesMap, dynamicConfigPromisesList, idOrNameOrParams, gtagParams)];
- case 1:
-
- _a.sent();
- return [3 , 5];
- case 2:
- if (!(command === "config" )) return [3 , 4];
-
- return [4 , gtagOnConfig(gtagCore, initializationPromisesMap, dynamicConfigPromisesList, measurementIdToAppId, idOrNameOrParams, gtagParams)];
- case 3:
-
- _a.sent();
- return [3 , 5];
- case 4:
- if (command === "consent" ) {
-
- gtagCore("consent" , 'update', gtagParams);
- }
- else {
-
- gtagCore("set" , idOrNameOrParams);
- }
- _a.label = 5;
- case 5: return [3 , 7];
- case 6:
- e_3 = _a.sent();
- logger.error(e_3);
- return [3 , 7];
- case 7: return [2 ];
- }
- });
- });
- }
- return gtagWrapper;
- }
-
- function wrapOrCreateGtag(initializationPromisesMap, dynamicConfigPromisesList, measurementIdToAppId, dataLayerName, gtagFunctionName) {
-
- var gtagCore = function () {
-
- window[dataLayerName].push(arguments);
- };
-
- if (window[gtagFunctionName] &&
- typeof window[gtagFunctionName] === 'function') {
-
- gtagCore = window[gtagFunctionName];
- }
- window[gtagFunctionName] = wrapGtag(gtagCore, initializationPromisesMap, dynamicConfigPromisesList, measurementIdToAppId);
- return {
- gtagCore: gtagCore,
- wrappedGtag: window[gtagFunctionName]
- };
- }
-
- function findGtagScriptOnPage(dataLayerName) {
- var scriptTags = window.document.getElementsByTagName('script');
- for (var _i = 0, _a = Object.values(scriptTags); _i < _a.length; _i++) {
- var tag = _a[_i];
- if (tag.src &&
- tag.src.includes(GTAG_URL) &&
- tag.src.includes(dataLayerName)) {
- return tag;
- }
- }
- return null;
- }
-
-
- var _a;
- var ERRORS = (_a = {},
- _a["already-exists" ] = 'A Firebase Analytics instance with the appId {$id} ' +
- ' already exists. ' +
- 'Only one Firebase Analytics instance can be created for each appId.',
- _a["already-initialized" ] = 'initializeAnalytics() cannot be called again with different options than those ' +
- 'it was initially called with. It can be called again with the same options to ' +
- 'return the existing instance, or getAnalytics() can be used ' +
- 'to get a reference to the already-intialized instance.',
- _a["already-initialized-settings" ] = 'Firebase Analytics has already been initialized.' +
- 'settings() must be called before initializing any Analytics instance' +
- 'or it will have no effect.',
- _a["interop-component-reg-failed" ] = 'Firebase Analytics Interop Component failed to instantiate: {$reason}',
- _a["invalid-analytics-context" ] = 'Firebase Analytics is not supported in this environment. ' +
- 'Wrap initialization of analytics in analytics.isSupported() ' +
- 'to prevent initialization in unsupported environments. Details: {$errorInfo}',
- _a["indexeddb-unavailable" ] = 'IndexedDB unavailable or restricted in this environment. ' +
- 'Wrap initialization of analytics in analytics.isSupported() ' +
- 'to prevent initialization in unsupported environments. Details: {$errorInfo}',
- _a["fetch-throttle" ] = 'The config fetch request timed out while in an exponential backoff state.' +
- ' Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.',
- _a["config-fetch-failed" ] = 'Dynamic config fetch failed: [{$httpStatus}] {$responseMessage}',
- _a["no-api-key" ] = 'The "apiKey" field is empty in the local Firebase config. Firebase Analytics requires this field to' +
- 'contain a valid API key.',
- _a["no-app-id" ] = 'The "appId" field is empty in the local Firebase config. Firebase Analytics requires this field to' +
- 'contain a valid app ID.',
- _a);
- var ERROR_FACTORY = new util.ErrorFactory('analytics', 'Analytics', ERRORS);
-
-
-
- var LONG_RETRY_FACTOR = 30;
-
- var BASE_INTERVAL_MILLIS = 1000;
-
- var RetryData = (function () {
- function RetryData(throttleMetadata, intervalMillis) {
- if (throttleMetadata === void 0) { throttleMetadata = {}; }
- if (intervalMillis === void 0) { intervalMillis = BASE_INTERVAL_MILLIS; }
- this.throttleMetadata = throttleMetadata;
- this.intervalMillis = intervalMillis;
- }
- RetryData.prototype.getThrottleMetadata = function (appId) {
- return this.throttleMetadata[appId];
- };
- RetryData.prototype.setThrottleMetadata = function (appId, metadata) {
- this.throttleMetadata[appId] = metadata;
- };
- RetryData.prototype.deleteThrottleMetadata = function (appId) {
- delete this.throttleMetadata[appId];
- };
- return RetryData;
- }());
- var defaultRetryData = new RetryData();
-
- function getHeaders(apiKey) {
- return new Headers({
- Accept: 'application/json',
- 'x-goog-api-key': apiKey
- });
- }
-
- function fetchDynamicConfig(appFields) {
- var _a;
- return tslib.__awaiter(this, void 0, void 0, function () {
- var appId, apiKey, request, appUrl, response, errorMessage, jsonResponse;
- return tslib.__generator(this, function (_b) {
- switch (_b.label) {
- case 0:
- appId = appFields.appId, apiKey = appFields.apiKey;
- request = {
- method: 'GET',
- headers: getHeaders(apiKey)
- };
- appUrl = DYNAMIC_CONFIG_URL.replace('{app-id}', appId);
- return [4 , fetch(appUrl, request)];
- case 1:
- response = _b.sent();
- if (!(response.status !== 200 && response.status !== 304)) return [3 , 6];
- errorMessage = '';
- _b.label = 2;
- case 2:
- _b.trys.push([2, 4, , 5]);
- return [4 , response.json()];
- case 3:
- jsonResponse = (_b.sent());
- if ((_a = jsonResponse.error) === null || _a === void 0 ? void 0 : _a.message) {
- errorMessage = jsonResponse.error.message;
- }
- return [3 , 5];
- case 4:
- _b.sent();
- return [3 , 5];
- case 5: throw ERROR_FACTORY.create("config-fetch-failed" , {
- httpStatus: response.status,
- responseMessage: errorMessage
- });
- case 6: return [2 , response.json()];
- }
- });
- });
- }
-
- function fetchDynamicConfigWithRetry(app,
- // retryData and timeoutMillis are parameterized to allow passing a different value for testing.
- retryData, timeoutMillis) {
- if (retryData === void 0) { retryData = defaultRetryData; }
- return tslib.__awaiter(this, void 0, void 0, function () {
- var _a, appId, apiKey, measurementId, throttleMetadata, signal;
- var _this = this;
- return tslib.__generator(this, function (_b) {
- _a = app.options, appId = _a.appId, apiKey = _a.apiKey, measurementId = _a.measurementId;
- if (!appId) {
- throw ERROR_FACTORY.create("no-app-id" );
- }
- if (!apiKey) {
- if (measurementId) {
- return [2 , {
- measurementId: measurementId,
- appId: appId
- }];
- }
- throw ERROR_FACTORY.create("no-api-key" );
- }
- throttleMetadata = retryData.getThrottleMetadata(appId) || {
- backoffCount: 0,
- throttleEndTimeMillis: Date.now()
- };
- signal = new AnalyticsAbortSignal();
- setTimeout(function () { return tslib.__awaiter(_this, void 0, void 0, function () {
- return tslib.__generator(this, function (_a) {
-
- signal.abort();
- return [2 ];
- });
- }); }, timeoutMillis !== undefined ? timeoutMillis : FETCH_TIMEOUT_MILLIS);
- return [2 , attemptFetchDynamicConfigWithRetry({ appId: appId, apiKey: apiKey, measurementId: measurementId }, throttleMetadata, signal, retryData)];
- });
- });
- }
-
- function attemptFetchDynamicConfigWithRetry(appFields, _a, signal, retryData // for testing
- ) {
- var _b;
- var throttleEndTimeMillis = _a.throttleEndTimeMillis, backoffCount = _a.backoffCount;
- if (retryData === void 0) { retryData = defaultRetryData; }
- return tslib.__awaiter(this, void 0, void 0, function () {
- var appId, measurementId, e_1, response, e_2, error, backoffMillis, throttleMetadata;
- return tslib.__generator(this, function (_c) {
- switch (_c.label) {
- case 0:
- appId = appFields.appId, measurementId = appFields.measurementId;
- _c.label = 1;
- case 1:
- _c.trys.push([1, 3, , 4]);
- return [4 , setAbortableTimeout(signal, throttleEndTimeMillis)];
- case 2:
- _c.sent();
- return [3 , 4];
- case 3:
- e_1 = _c.sent();
- if (measurementId) {
- logger.warn("Timed out fetching this Firebase app's measurement ID from the server." +
- " Falling back to the measurement ID ".concat(measurementId) +
- " provided in the \"measurementId\" field in the local Firebase config. [".concat(e_1 === null || e_1 === void 0 ? void 0 : e_1.message, "]"));
- return [2 , { appId: appId, measurementId: measurementId }];
- }
- throw e_1;
- case 4:
- _c.trys.push([4, 6, , 7]);
- return [4 , fetchDynamicConfig(appFields)];
- case 5:
- response = _c.sent();
-
- retryData.deleteThrottleMetadata(appId);
- return [2 , response];
- case 6:
- e_2 = _c.sent();
- error = e_2;
- if (!isRetriableError(error)) {
- retryData.deleteThrottleMetadata(appId);
- if (measurementId) {
- logger.warn("Failed to fetch this Firebase app's measurement ID from the server." +
- " Falling back to the measurement ID ".concat(measurementId) +
- " provided in the \"measurementId\" field in the local Firebase config. [".concat(error === null || error === void 0 ? void 0 : error.message, "]"));
- return [2 , { appId: appId, measurementId: measurementId }];
- }
- else {
- throw e_2;
- }
- }
- backoffMillis = Number((_b = error === null || error === void 0 ? void 0 : error.customData) === null || _b === void 0 ? void 0 : _b.httpStatus) === 503
- ? util.calculateBackoffMillis(backoffCount, retryData.intervalMillis, LONG_RETRY_FACTOR)
- : util.calculateBackoffMillis(backoffCount, retryData.intervalMillis);
- throttleMetadata = {
- throttleEndTimeMillis: Date.now() + backoffMillis,
- backoffCount: backoffCount + 1
- };
-
- retryData.setThrottleMetadata(appId, throttleMetadata);
- logger.debug("Calling attemptFetch again in ".concat(backoffMillis, " millis"));
- return [2 , attemptFetchDynamicConfigWithRetry(appFields, throttleMetadata, signal, retryData)];
- case 7: return [2 ];
- }
- });
- });
- }
-
- function setAbortableTimeout(signal, throttleEndTimeMillis) {
- return new Promise(function (resolve, reject) {
-
- var backoffMillis = Math.max(throttleEndTimeMillis - Date.now(), 0);
- var timeout = setTimeout(resolve, backoffMillis);
-
- signal.addEventListener(function () {
- clearTimeout(timeout);
-
- reject(ERROR_FACTORY.create("fetch-throttle" , {
- throttleEndTimeMillis: throttleEndTimeMillis
- }));
- });
- });
- }
-
- function isRetriableError(e) {
- if (!(e instanceof util.FirebaseError) || !e.customData) {
- return false;
- }
-
- var httpStatus = Number(e.customData['httpStatus']);
- return (httpStatus === 429 ||
- httpStatus === 500 ||
- httpStatus === 503 ||
- httpStatus === 504);
- }
-
- var AnalyticsAbortSignal = (function () {
- function AnalyticsAbortSignal() {
- this.listeners = [];
- }
- AnalyticsAbortSignal.prototype.addEventListener = function (listener) {
- this.listeners.push(listener);
- };
- AnalyticsAbortSignal.prototype.abort = function () {
- this.listeners.forEach(function (listener) { return listener(); });
- };
- return AnalyticsAbortSignal;
- }());
-
-
-
- var defaultEventParametersForInit;
-
- function logEvent$1(gtagFunction, initializationPromise, eventName, eventParams, options) {
- return tslib.__awaiter(this, void 0, void 0, function () {
- var measurementId, params;
- return tslib.__generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- if (!(options && options.global)) return [3 , 1];
- gtagFunction("event" , eventName, eventParams);
- return [2 ];
- case 1: return [4 , initializationPromise];
- case 2:
- measurementId = _a.sent();
- params = tslib.__assign(tslib.__assign({}, eventParams), { 'send_to': measurementId });
- gtagFunction("event" , eventName, params);
- _a.label = 3;
- case 3: return [2 ];
- }
- });
- });
- }
-
- function setCurrentScreen$1(gtagFunction, initializationPromise, screenName, options) {
- return tslib.__awaiter(this, void 0, void 0, function () {
- var measurementId;
- return tslib.__generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- if (!(options && options.global)) return [3 , 1];
- gtagFunction("set" , { 'screen_name': screenName });
- return [2 , Promise.resolve()];
- case 1: return [4 , initializationPromise];
- case 2:
- measurementId = _a.sent();
- gtagFunction("config" , measurementId, {
- update: true,
- 'screen_name': screenName
- });
- _a.label = 3;
- case 3: return [2 ];
- }
- });
- });
- }
-
- function setUserId$1(gtagFunction, initializationPromise, id, options) {
- return tslib.__awaiter(this, void 0, void 0, function () {
- var measurementId;
- return tslib.__generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- if (!(options && options.global)) return [3 , 1];
- gtagFunction("set" , { 'user_id': id });
- return [2 , Promise.resolve()];
- case 1: return [4 , initializationPromise];
- case 2:
- measurementId = _a.sent();
- gtagFunction("config" , measurementId, {
- update: true,
- 'user_id': id
- });
- _a.label = 3;
- case 3: return [2 ];
- }
- });
- });
- }
-
- function setUserProperties$1(gtagFunction, initializationPromise, properties, options) {
- return tslib.__awaiter(this, void 0, void 0, function () {
- var flatProperties, _i, _a, key, measurementId;
- return tslib.__generator(this, function (_b) {
- switch (_b.label) {
- case 0:
- if (!(options && options.global)) return [3 , 1];
- flatProperties = {};
- for (_i = 0, _a = Object.keys(properties); _i < _a.length; _i++) {
- key = _a[_i];
-
- flatProperties["user_properties.".concat(key)] = properties[key];
- }
- gtagFunction("set" , flatProperties);
- return [2 , Promise.resolve()];
- case 1: return [4 , initializationPromise];
- case 2:
- measurementId = _b.sent();
- gtagFunction("config" , measurementId, {
- update: true,
- 'user_properties': properties
- });
- _b.label = 3;
- case 3: return [2 ];
- }
- });
- });
- }
-
- function setAnalyticsCollectionEnabled$1(initializationPromise, enabled) {
- return tslib.__awaiter(this, void 0, void 0, function () {
- var measurementId;
- return tslib.__generator(this, function (_a) {
- switch (_a.label) {
- case 0: return [4 , initializationPromise];
- case 1:
- measurementId = _a.sent();
- window["ga-disable-".concat(measurementId)] = !enabled;
- return [2 ];
- }
- });
- });
- }
-
- var defaultConsentSettingsForInit;
-
- function _setConsentDefaultForInit(consentSettings) {
- defaultConsentSettingsForInit = consentSettings;
- }
-
- function _setDefaultEventParametersForInit(customParams) {
- defaultEventParametersForInit = customParams;
- }
-
-
- function validateIndexedDB() {
- return tslib.__awaiter(this, void 0, void 0, function () {
- var e_1;
- return tslib.__generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- if (!!util.isIndexedDBAvailable()) return [3 , 1];
- logger.warn(ERROR_FACTORY.create("indexeddb-unavailable" , {
- errorInfo: 'IndexedDB is not available in this environment.'
- }).message);
- return [2 , false];
- case 1:
- _a.trys.push([1, 3, , 4]);
- return [4 , util.validateIndexedDBOpenable()];
- case 2:
- _a.sent();
- return [3 , 4];
- case 3:
- e_1 = _a.sent();
- logger.warn(ERROR_FACTORY.create("indexeddb-unavailable" , {
- errorInfo: e_1 === null || e_1 === void 0 ? void 0 : e_1.toString()
- }).message);
- return [2 , false];
- case 4: return [2 , true];
- }
- });
- });
- }
-
- function _initializeAnalytics(app, dynamicConfigPromisesList, measurementIdToAppId, installations, gtagCore, dataLayerName, options) {
- var _a;
- return tslib.__awaiter(this, void 0, void 0, function () {
- var dynamicConfigPromise, fidPromise, _b, dynamicConfig, fid, configProperties;
- return tslib.__generator(this, function (_c) {
- switch (_c.label) {
- case 0:
- dynamicConfigPromise = fetchDynamicConfigWithRetry(app);
-
- dynamicConfigPromise
- .then(function (config) {
- measurementIdToAppId[config.measurementId] = config.appId;
- if (app.options.measurementId &&
- config.measurementId !== app.options.measurementId) {
- logger.warn("The measurement ID in the local Firebase config (".concat(app.options.measurementId, ")") +
- " does not match the measurement ID fetched from the server (".concat(config.measurementId, ").") +
- " To ensure analytics events are always sent to the correct Analytics property," +
- " update the" +
- " measurement ID field in the local config or remove it from the local config.");
- }
- })
- .catch(function (e) { return logger.error(e); });
-
- dynamicConfigPromisesList.push(dynamicConfigPromise);
- fidPromise = validateIndexedDB().then(function (envIsValid) {
- if (envIsValid) {
- return installations.getId();
- }
- else {
- return undefined;
- }
- });
- return [4 , Promise.all([
- dynamicConfigPromise,
- fidPromise
- ])];
- case 1:
- _b = _c.sent(), dynamicConfig = _b[0], fid = _b[1];
-
-
- if (!findGtagScriptOnPage(dataLayerName)) {
- insertScriptTag(dataLayerName, dynamicConfig.measurementId);
- }
-
- if (defaultConsentSettingsForInit) {
- gtagCore("consent" , 'default', defaultConsentSettingsForInit);
- _setConsentDefaultForInit(undefined);
- }
-
-
-
-
- gtagCore('js', new Date());
- configProperties = (_a = options === null || options === void 0 ? void 0 : options.config) !== null && _a !== void 0 ? _a : {};
-
- configProperties[ORIGIN_KEY] = 'firebase';
- configProperties.update = true;
- if (fid != null) {
- configProperties[GA_FID_KEY] = fid;
- }
-
-
-
-
- gtagCore("config" , dynamicConfig.measurementId, configProperties);
-
- if (defaultEventParametersForInit) {
- gtagCore("set" , defaultEventParametersForInit);
- _setDefaultEventParametersForInit(undefined);
- }
- return [2 , dynamicConfig.measurementId];
- }
- });
- });
- }
-
-
-
- var AnalyticsService = (function () {
- function AnalyticsService(app) {
- this.app = app;
- }
- AnalyticsService.prototype._delete = function () {
- delete initializationPromisesMap[this.app.options.appId];
- return Promise.resolve();
- };
- return AnalyticsService;
- }());
-
- var initializationPromisesMap = {};
-
- var dynamicConfigPromisesList = [];
-
- var measurementIdToAppId = {};
-
- var dataLayerName = 'dataLayer';
-
- var gtagName = 'gtag';
-
- var gtagCoreFunction;
-
- var wrappedGtagFunction;
-
- var globalInitDone = false;
-
- function settings(options) {
- if (globalInitDone) {
- throw ERROR_FACTORY.create("already-initialized" );
- }
- if (options.dataLayerName) {
- dataLayerName = options.dataLayerName;
- }
- if (options.gtagName) {
- gtagName = options.gtagName;
- }
- }
-
- function warnOnBrowserContextMismatch() {
- var mismatchedEnvMessages = [];
- if (util.isBrowserExtension()) {
- mismatchedEnvMessages.push('This is a browser extension environment.');
- }
- if (!util.areCookiesEnabled()) {
- mismatchedEnvMessages.push('Cookies are not available.');
- }
- if (mismatchedEnvMessages.length > 0) {
- var details = mismatchedEnvMessages
- .map(function (message, index) { return "(".concat(index + 1, ") ").concat(message); })
- .join(' ');
- var err = ERROR_FACTORY.create("invalid-analytics-context" , {
- errorInfo: details
- });
- logger.warn(err.message);
- }
- }
-
- function factory(app, installations, options) {
- warnOnBrowserContextMismatch();
- var appId = app.options.appId;
- if (!appId) {
- throw ERROR_FACTORY.create("no-app-id" );
- }
- if (!app.options.apiKey) {
- if (app.options.measurementId) {
- logger.warn("The \"apiKey\" field is empty in the local Firebase config. This is needed to fetch the latest" +
- " measurement ID for this Firebase app. Falling back to the measurement ID ".concat(app.options.measurementId) +
- " provided in the \"measurementId\" field in the local Firebase config.");
- }
- else {
- throw ERROR_FACTORY.create("no-api-key" );
- }
- }
- if (initializationPromisesMap[appId] != null) {
- throw ERROR_FACTORY.create("already-exists" , {
- id: appId
- });
- }
- if (!globalInitDone) {
-
-
- getOrCreateDataLayer(dataLayerName);
- var _a = wrapOrCreateGtag(initializationPromisesMap, dynamicConfigPromisesList, measurementIdToAppId, dataLayerName, gtagName), wrappedGtag = _a.wrappedGtag, gtagCore = _a.gtagCore;
- wrappedGtagFunction = wrappedGtag;
- gtagCoreFunction = gtagCore;
- globalInitDone = true;
- }
-
-
- initializationPromisesMap[appId] = _initializeAnalytics(app, dynamicConfigPromisesList, measurementIdToAppId, installations, gtagCoreFunction, dataLayerName, options);
- var analyticsInstance = new AnalyticsService(app);
- return analyticsInstance;
- }
-
-
-
- function getAnalytics(app$1) {
- if (app$1 === void 0) { app$1 = app.getApp(); }
- app$1 = util.getModularInstance(app$1);
-
- var analyticsProvider = app._getProvider(app$1, ANALYTICS_TYPE);
- if (analyticsProvider.isInitialized()) {
- return analyticsProvider.getImmediate();
- }
- return initializeAnalytics(app$1);
- }
-
- function initializeAnalytics(app$1, options) {
- if (options === void 0) { options = {}; }
-
- var analyticsProvider = app._getProvider(app$1, ANALYTICS_TYPE);
- if (analyticsProvider.isInitialized()) {
- var existingInstance = analyticsProvider.getImmediate();
- if (util.deepEqual(options, analyticsProvider.getOptions())) {
- return existingInstance;
- }
- else {
- throw ERROR_FACTORY.create("already-initialized" );
- }
- }
- var analyticsInstance = analyticsProvider.initialize({ options: options });
- return analyticsInstance;
- }
-
- function isSupported() {
- return tslib.__awaiter(this, void 0, void 0, function () {
- var isDBOpenable;
- return tslib.__generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- if (util.isBrowserExtension()) {
- return [2 , false];
- }
- if (!util.areCookiesEnabled()) {
- return [2 , false];
- }
- if (!util.isIndexedDBAvailable()) {
- return [2 , false];
- }
- _a.label = 1;
- case 1:
- _a.trys.push([1, 3, , 4]);
- return [4 , util.validateIndexedDBOpenable()];
- case 2:
- isDBOpenable = _a.sent();
- return [2 , isDBOpenable];
- case 3:
- _a.sent();
- return [2 , false];
- case 4: return [2 ];
- }
- });
- });
- }
-
- function setCurrentScreen(analyticsInstance, screenName, options) {
- analyticsInstance = util.getModularInstance(analyticsInstance);
- setCurrentScreen$1(wrappedGtagFunction, initializationPromisesMap[analyticsInstance.app.options.appId], screenName, options).catch(function (e) { return logger.error(e); });
- }
-
- function setUserId(analyticsInstance, id, options) {
- analyticsInstance = util.getModularInstance(analyticsInstance);
- setUserId$1(wrappedGtagFunction, initializationPromisesMap[analyticsInstance.app.options.appId], id, options).catch(function (e) { return logger.error(e); });
- }
-
- function setUserProperties(analyticsInstance, properties, options) {
- analyticsInstance = util.getModularInstance(analyticsInstance);
- setUserProperties$1(wrappedGtagFunction, initializationPromisesMap[analyticsInstance.app.options.appId], properties, options).catch(function (e) { return logger.error(e); });
- }
-
- function setAnalyticsCollectionEnabled(analyticsInstance, enabled) {
- analyticsInstance = util.getModularInstance(analyticsInstance);
- setAnalyticsCollectionEnabled$1(initializationPromisesMap[analyticsInstance.app.options.appId], enabled).catch(function (e) { return logger.error(e); });
- }
-
- function setDefaultEventParameters(customParams) {
-
- if (wrappedGtagFunction) {
- wrappedGtagFunction("set" , customParams);
- }
- else {
- _setDefaultEventParametersForInit(customParams);
- }
- }
-
- function logEvent(analyticsInstance, eventName, eventParams, options) {
- analyticsInstance = util.getModularInstance(analyticsInstance);
- logEvent$1(wrappedGtagFunction, initializationPromisesMap[analyticsInstance.app.options.appId], eventName, eventParams, options).catch(function (e) { return logger.error(e); });
- }
-
- function setConsent(consentSettings) {
-
- if (wrappedGtagFunction) {
- wrappedGtagFunction("consent" , 'update', consentSettings);
- }
- else {
- _setConsentDefaultForInit(consentSettings);
- }
- }
-
- var name = "@firebase/analytics";
- var version = "0.9.1";
-
-
- function registerAnalytics() {
- app._registerComponent(new component.Component(ANALYTICS_TYPE, function (container, _a) {
- var analyticsOptions = _a.options;
-
- var app = container.getProvider('app').getImmediate();
- var installations = container
- .getProvider('installations-internal')
- .getImmediate();
- return factory(app, installations, analyticsOptions);
- }, "PUBLIC" ));
- app._registerComponent(new component.Component('analytics-internal', internalFactory, "PRIVATE" ));
- app.registerVersion(name, version);
-
- app.registerVersion(name, version, 'cjs5');
- function internalFactory(container) {
- try {
- var analytics_1 = container.getProvider(ANALYTICS_TYPE).getImmediate();
- return {
- logEvent: function (eventName, eventParams, options) { return logEvent(analytics_1, eventName, eventParams, options); }
- };
- }
- catch (e) {
- throw ERROR_FACTORY.create("interop-component-reg-failed" , {
- reason: e
- });
- }
- }
- }
- registerAnalytics();
-
- exports.getAnalytics = getAnalytics;
- exports.initializeAnalytics = initializeAnalytics;
- exports.isSupported = isSupported;
- exports.logEvent = logEvent;
- exports.setAnalyticsCollectionEnabled = setAnalyticsCollectionEnabled;
- exports.setConsent = setConsent;
- exports.setCurrentScreen = setCurrentScreen;
- exports.setDefaultEventParameters = setDefaultEventParameters;
- exports.setUserId = setUserId;
- exports.setUserProperties = setUserProperties;
- exports.settings = settings;
|