index.esm.js 65 KB

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