index.cjs.js 66 KB

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