PageSourceSearch

https://virtrolio.web.app/node_modules_firebase_analytics_dist_index_esm_js-es2015.js

js virtrolio.web.app collected 2026-10-03 12:39:40 UTC 125,565 bytes, 2,947 lines download raw bytes

1(self["webpackChunkvirtrolio_site"] = self["webpackChunkvirtrolio_site"] || []).push([["node_modules_firebase_analytics_dist_index_esm_js"],{
2
3/***/ 40586:
4/*!************************************************************!*\
5  !*** ./node_modules/@firebase/analytics/dist/index.esm.js ***!
6  \************************************************************/
7/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
8
9"use strict";
10__webpack_require__.r(__webpack_exports__);
11/* harmony export */ __webpack_require__.d(__webpack_exports__, {
12/* harmony export */   "factory": function() { return /* binding */ factory; },
13/* harmony export */   "getGlobalVars": function() { return /* binding */ getGlobalVars; },
14/* harmony export */   "registerAnalytics": function() { return /* binding */ registerAnalytics; },
15/* harmony export */   "resetGlobalVars": function() { return /* binding */ resetGlobalVars; },
16/* harmony export */   "settings": function() { return /* binding */ settings; }
17/* harmony export */ });
18/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! tslib */ 64762);
19/* harmony import */ var _firebase_app__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @firebase/app */ 79759);
20/* harmony import */ var _firebase_installations__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @firebase/installations */ 21723);
21/* harmony import */ var _firebase_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @firebase/logger */ 60300);
22/* harmony import */ var _firebase_util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @firebase/util */ 64685);
23/* harmony import */ var _firebase_component__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @firebase/component */ 16034);
24
25
26
27
28
29
30
31/**
32 * @license
33 * Copyright 2019 Google LLC
34 *
35 * Licensed under the Apache License, Version 2.0 (the "License");
36 * you may not use this file except in compliance with the License.
37 * You may obtain a copy of the License at
38 *
39 *   http://www.apache.org/licenses/LICENSE-2.0
40 *
41 * Unless required by applicable law or agreed to in writing, software
42 * distributed under the License is distributed on an "AS IS" BASIS,
43 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
44 * See the License for the specific language governing permissions and
45 * limitations under the License.
46 */
47// Key to attach FID to in gtag params.
48var GA_FID_KEY = 'firebase_id';
49var ORIGIN_KEY = 'origin';
50var FETCH_TIMEOUT_MILLIS = 60 * 1000;
51var DYNAMIC_CONFIG_URL = 'https://firebase.googleapis.com/v1alpha/projects/-/apps/{app-id}/webConfig';
52var GTAG_URL = 'https://www.googletagmanager.com/gtag/js';
53var GtagCommand;
54(function (GtagCommand) {
55    GtagCommand["EVENT"] = "event";
56    GtagCommand["SET"] = "set";
57    GtagCommand["CONFIG"] = "config";
58})(GtagCommand || (GtagCommand = {}));
59/**
60 * Officially recommended event names for gtag.js
61 * Any other string is also allowed.
62 *
63 * @public
64 */
65var EventName;
66(function (EventName) {
67    EventName["ADD_SHIPPING_INFO"] = "add_shipping_info";
68    EventName["ADD_PAYMENT_INFO"] = "add_payment_info";
69    EventName["ADD_TO_CART"] = "add_to_cart";
70    EventName["ADD_TO_WISHLIST"] = "add_to_wishlist";
71    EventName["BEGIN_CHECKOUT"] = "begin_checkout";
72    /**
73     * @deprecated
74     * This event name is deprecated and is unsupported in updated
75     * Enhanced Ecommerce reports.
76     */
77    EventName["CHECKOUT_PROGRESS"] = "checkout_progress";
78    EventName["EXCEPTION"] = "exception";
79    EventName["GENERATE_LEAD"] = "generate_lead";
80    EventName["LOGIN"] = "login";
81    EventName["PAGE_VIEW"] = "page_view";
82    EventName["PURCHASE"] = "purchase";
83    EventName["REFUND"] = "refund";
84    EventName["REMOVE_FROM_CART"] = "remove_from_cart";
85    EventName["SCREEN_VIEW"] = "screen_view";
86    EventName["SEARCH"] = "search";
87    EventName["SELECT_CONTENT"] = "select_content";
88    EventName["SELECT_ITEM"] = "select_item";
89    EventName["SELECT_PROMOTION"] = "select_promotion";
90    /** @deprecated */
91    EventName["SET_CHECKOUT_OPTION"] = "set_checkout_option";
92    EventName["SHARE"] = "share";
93    EventName["SIGN_UP"] = "sign_up";
94    EventName["TIMING_COMPLETE"] = "timing_complete";
95    EventName["VIEW_CART"] = "view_cart";
96    EventName["VIEW_ITEM"] = "view_item";
97    EventName["VIEW_ITEM_LIST"] = "view_item_list";
98    EventName["VIEW_PROMOTION"] = "view_promotion";
99    EventName["VIEW_SEARCH_RESULTS"] = "view_search_results";
100})(EventName || (EventName = {}));
101
102/**
103 * @license
104 * Copyright 2019 Google LLC
105 *
106 * Licensed under the Apache License, Version 2.0 (the "License");
107 * you may not use this file except in compliance with the License.
108 * You may obtain a copy of the License at
109 *
110 *   http://www.apache.org/licenses/LICENSE-2.0
111 *
112 * Unless required by applicable law or agreed to in writing, software
113 * distributed under the License is distributed on an "AS IS" BASIS,
114 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
115 * See the License for the specific language governing permissions and
116 * limitations under the License.
117 */
118/**
119 * Logs an analytics event through the Firebase SDK.
120 *
121 * @param gtagFunction Wrapped gtag function that waits for fid to be set before sending an event
122 * @param eventName Google Analytics event name, choose from standard list or use a custom string.
123 * @param eventParams Analytics event parameters.
124 */
125function logEvent(gtagFunction, initializationPromise, eventName, eventParams, options) {
126    return (0,tslib__WEBPACK_IMPORTED_MODULE_5__.__awaiter)(this, void 0, void 0, function () {
127        var measurementId, params;
128        return (0,tslib__WEBPACK_IMPORTED_MODULE_5__.__generator)(this, function (_a) {
129            switch (_a.label) {
130                case 0:
131                    if (!(options && options.global)) return [3 /*break*/, 1];
132                    gtagFunction(GtagCommand.EVENT, eventName, eventParams);
133                    return [2 /*return*/];
134                case 1: return [4 /*yield*/, initializationPromise];
135                case 2:
136                    measurementId = _a.sent();
137                    params = (0,tslib__WEBPACK_IMPORTED_MODULE_5__.__assign)((0,tslib__WEBPACK_IMPORTED_MODULE_5__.__assign)({}, eventParams), { 'send_to': measurementId });
138                    gtagFunction(GtagCommand.EVENT, eventName, params);
139                    _a.label = 3;
140                case 3: return [2 /*return*/];
141            }
142        });
143    });
144}
145/**
146 * Set screen_name parameter for this Google Analytics ID.
147 *
148 * @param gtagFunction Wrapped gtag function that waits for fid to be set before sending an event
149 * @param screenName Screen name string to set.
150 */
151function setCurrentScreen(gtagFunction, initializationPromise, screenName, options) {
152    return (0,tslib__WEBPACK_IMPORTED_MODULE_5__.__awaiter)(this, void 0, void 0, function () {
153        var measurementId;
154        return (0,tslib__WEBPACK_IMPORTED_MODULE_5__.__generator)(this, function (_a) {
155            switch (_a.label) {
156                case 0:
157                    if (!(options && options.global)) return [3 /*break*/, 1];
158                    gtagFunction(GtagCommand.SET, { 'screen_name': screenName });
159                    return [2 /*return*/, Promise.resolve()];
160                case 1: return [4 /*yield*/, initializationPromise];
161                case 2:
162                    measurementId = _a.sent();
163                    gtagFunction(GtagCommand.CONFIG, measurementId, {
164                        update: true,
165                        'screen_name': screenName
166                    });
167                    _a.label = 3;
168                case 3: return [2 /*return*/];
169            }
170        });
171    });
172}
173/**
174 * Set user_id parameter for this Google Analytics ID.
175 *
176 * @param gtagFunction Wrapped gtag function that waits for fid to be set before sending an event
177 * @param id User ID string to set
178 */
179function setUserId(gtagFunction, initializationPromise, id, options) {
180    return (0,tslib__WEBPACK_IMPORTED_MODULE_5__.__awaiter)(this, void 0, void 0, function () {
181        var measurementId;
182        return (0,tslib__WEBPACK_IMPORTED_MODULE_5__.__generator)(this, function (_a) {
183            switch (_a.label) {
184                case 0:
185                    if (!(options && options.global)) return [3 /*break*/, 1];
186                    gtagFunction(GtagCommand.SET, { 'user_id': id });
187                    return [2 /*return*/, Promise.resolve()];
188                case 1: return [4 /*yield*/, initializationPromise];
189                case 2:
190                    measurementId = _a.sent();
191                    gtagFunction(GtagCommand.CONFIG, measurementId, {
192                        update: true,
193                        'user_id': id
194                    });
195                    _a.label = 3;
196                case 3: return [2 /*return*/];
197            }
198        });
199    });
200}
201/**
202 * Set all other user properties other than user_id and screen_name.
203 *
204 * @param gtagFunction Wrapped gtag function that waits for fid to be set before sending an event
205 * @param properties Map of user properties to set
206 */
207function setUserProperties(gtagFunction, initializationPromise, properties, options) {
208    return (0,tslib__WEBPACK_IMPORTED_MODULE_5__.__awaiter)(this, void 0, void 0, function () {
209        var flatProperties, _i, _a, key, measurementId;
210        return (0,tslib__WEBPACK_IMPORTED_MODULE_5__.__generator)(this, function (_b) {
211            switch (_b.label) {
212                case 0:
213                    if (!(options && options.global)) return [3 /*break*/, 1];
214                    flatProperties = {};
215                    for (_i = 0, _a = Object.keys(properties); _i < _a.length; _i++) {
216                        key = _a[_i];
217                        // use dot notation for merge behavior in gtag.js
218                        flatProperties["user_properties." + key] = properties[key];
219                    }
220                    gtagFunction(GtagCommand.SET, flatProperties);
221                    return [2 /*return*/, Promise.resolve()];
222                case 1: return [4 /*yield*/, initializationPromise];
223                case 2:
224                    measurementId = _b.sent();
225                    gtagFunction(GtagCommand.CONFIG, measurementId, {
226                        update: true,
227                        'user_properties': properties
228                    });
229                    _b.label = 3;
230                case 3: return [2 /*return*/];
231            }
232        });
233    });
234}
235/**
236 * Set whether collection is enabled for this ID.
237 *
238 * @param enabled If true, collection is enabled for this ID.
239 */
240function setAnalyticsCollectionEnabled(initializationPromise, enabled) {
241    return (0,tslib__WEBPACK_IMPORTED_MODULE_5__.__awaiter)(this, void 0, void 0, function () {
242        var measurementId;
243        return (0,tslib__WEBPACK_IMPORTED_MODULE_5__.__generator)(this, function (_a) {
244            switch (_a.label) {
245                case 0: return [4 /*yield*/, initializationPromise];
246                case 1:
247                    measurementId = _a.sent();
248                    window["ga-disable-" + measurementId] = !enabled;
249                    return [2 /*return*/];
250            }
251        });
252    });
253}
254
255/**
256 * @license
257 * Copyright 2019 Google LLC
258 *
259 * Licensed under the Apache License, Version 2.0 (the "License");
260 * you may not use this file except in compliance with the License.
261 * You may obtain a copy of the License at
262 *
263 *   http://www.apache.org/licenses/LICENSE-2.0
264 *
265 * Unless required by applicable law or agreed to in writing, software
266 * distributed under the License is distributed on an "AS IS" BASIS,
267 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
268 * See the License for the specific language governing permissions and
269 * limitations under the License.
270 */
271var logger = new _firebase_logger__WEBPACK_IMPORTED_MODULE_2__.Logger('@firebase/analytics');
272
273/**
274 * @license
275 * Copyright 2019 Google LLC
276 *
277 * Licensed under the Apache License, Version 2.0 (the "License");
278 * you may not use this file except in compliance with the License.
279 * You may obtain a copy of the License at
280 *
281 *   http://www.apache.org/licenses/LICENSE-2.0
282 *
283 * Unless required by applicable law or agreed to in writing, software
284 * distributed under the License is distributed on an "AS IS" BASIS,
285 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
286 * See the License for the specific language governing permissions and
287 * limitations under the License.
288 */
289/**
290 * Inserts gtag script tag into the page to asynchronously download gtag.
291 * @param dataLayerName Name of datalayer (most often the default, "_dataLayer").
292 */
293function insertScriptTag(dataLayerName, measurementId) {
294    var script = document.createElement('script');
295    script.src = GTAG_URL + "?l=" + dataLayerName + "&id=" + measurementId;
296    script.async = true;
297    document.head.appendChild(script);
298}
299/**
300 * Get reference to, or create, global datalayer.
301 * @param dataLayerName Name of datalayer (most often the default, "_dataLayer").
302 */
303function getOrCreateDataLayer(dataLayerName) {
304    // Check for existing dataLayer and create if needed.
305    var dataLayer = [];
306    if (Array.isArray(window[dataLayerName])) {
307        dataLayer = window[dataLayerName];
308    }
309    else {
310        window[dataLayerName] = dataLayer;
311    }
312    return dataLayer;
313}
314/**
315 * Wrapped gtag logic when gtag is called with 'config' command.
316 *
317 * @param gtagCore Basic gtag function that just appends to dataLayer.
318 * @param initializationPromisesMap Map of appIds to their initialization promises.
319 * @param dynamicConfigPromisesList Array of dynamic config fetch promises.
320 * @param measurementIdToAppId Map of GA measurementIDs to corresponding Firebase appI
320d.
321 * @param measurementId GA Measurement ID to set config for.
322 * @param gtagParams Gtag config params to set.
323 */
324function gtagOnConfig(gtagCore, initializationPromisesMap, dynamicConfigPromisesList, measurementIdToAppId, measurementId, gtagParams) {
325    return (0,tslib__WEBPACK_IMPORTED_MODULE_5__.__awaiter)(this, void 0, void 0, function () {
326        var correspondingAppId, dynamicConfigResults, foundConfig, e_1;
327        return (0,tslib__WEBPACK_IMPORTED_MODULE_5__.__generator)(this, function (_a) {
328            switch (_a.label) {
329                case 0:
330                    correspondingAppId = measurementIdToAppId[measurementId];
331                    _a.label = 1;
332                case 1:
333                    _a.trys.push([1, 7, , 8]);
334                    if (!correspondingAppId) return [3 /*break*/, 3];
335                    return [4 /*yield*/, initializationPromisesMap[correspondingAppId]];
336                case 2:
337                    _a.sent();
338                    return [3 /*break*/, 6];
339                case 3: return [4 /*yield*/, Promise.all(dynamicConfigPromisesList)];
340                case 4:
341                    dynamicConfigResults = _a.sent();
342                    foundConfig = dynamicConfigResults.find(function (config) { return config.measurementId === measurementId; });
343                    if (!foundConfig) return [3 /*break*/, 6];
344                    return [4 /*yield*/, initializationPromisesMap[foundConfig.appId]];
345                case 5:
346                    _a.sent();
347                    _a.label = 6;
348                case 6: return [3 /*break*/, 8];
349                case 7:
350                    e_1 = _a.sent();
351                    logger.error(e_1);
352                    return [3 /*break*/, 8];
353                case 8:
354                    gtagCore(GtagCommand.CONFIG, measurementId, gtagParams);
355                    return [2 /*return*/];
356            }
357        });
358    });
359}
360/**
361 * Wrapped gtag logic when gtag is called with 'event' command.
362 *
363 * @param gtagCore Basic gtag function that just appends to dataLayer.
364 * @param initializationPromisesMap Map of appIds to their initialization promises.
365 * @param dynamicConfigPromisesList Array of dynamic config fetch promises.
366 * @param measurementId GA Measurement ID to log event to.
367 * @param gtagParams Params to log with this event.
368 */
369function gtagOnEvent(gtagCore, initializationPromisesMap, dynamicConfigPromisesList, measurementId, gtagParams) {
370    return (0,tslib__WEBPACK_IMPORTED_MODULE_5__.__awaiter)(this, void 0, void 0, function () {
371        var initializationPromisesToWaitFor, gaSendToList, dynamicConfigResults, _loop_1, _i, gaSendToList_1, sendToId, state_1, e_2;
372        return (0,tslib__WEBPACK_IMPORTED_MODULE_5__.__generator)(this, function (_a) {
373            switch (_a.label) {
374                case 0:
375                    _a.trys.push([0, 4, , 5]);
376                    initializationPromisesToWaitFor = [];
377                    if (!(gtagParams && gtagParams['send_to'])) return [3 /*break*/, 2];
378                    gaSendToList = gtagParams['send_to'];
379                    // Make it an array if is isn't, so it can be dealt with the same way.
380                    if (!Array.isArray(gaSendToList)) {
381                        gaSendToList = [gaSendToList];
382                    }
383                    return [4 /*yield*/, Promise.all(dynamicConfigPromisesList)];
384                case 1:
385                    dynamicConfigResults = _a.sent();
386                    _loop_1 = function (sendToId) {
387                        // Any fetched dynamic measurement ID that matches this 'send_to' ID
388                        var foundConfig = dynamicConfigResults.find(function (config) { return config.measurementId === sendToId; });
389                        var initializationPromise = foundConfig && initializationPromisesMap[foundConfig.appId];
390                        if (initializationPromise) {
391                            initializationPromisesToWaitFor.push(initializationPromise);
392                        }
393                        else {
394                            // Found an item in 'send_to' that is not associated
395                            // directly with an FID, possibly a group.  Empty this array,
396                            // exit the loop early, and let it get populated below.
397                            initializationPromisesToWaitFor = [];
398                            return "break";
399                        }
400                    };
401                    for (_i = 0, gaSendToList_1 = gaSendToList; _i < gaSendToList_1.length; _i++) {
402                        sendToId = gaSendToList_1[_i];
403                        state_1 = _loop_1(sendToId);
404                        if (state_1 === "break")
405                            break;
406                    }
407                    _a.label = 2;
408                case 2:
409                    // This will be unpopulated if there was no 'send_to' field , or
410                    // if not all entries in the 'send_to' field could be mapped to
411                    // a FID. In these cases, wait on all pending initialization promises.
412                    if (initializationPromisesToWaitFor.length === 0) {
413                        initializationPromisesToWaitFor = Object.values(initializationPromisesMap);
414                    }
415                    // Run core gtag function with args after all relevant initialization
416                    // promises have been resolved.
417                    return [4 /*yield*/, Promise.all(initializationPromisesToWaitFor)];
418                case 3:
419                    // Run core gtag function with args after all relevant initialization
420                    // promises have been resolved.
421                    _a.sent();
422                    // Workaround for http://b/141370449 - third argument cannot be undefined.
423                    gtagCore(GtagCommand.EVENT, measurementId, gtagParams || {});
424                    return [3 /*break*/, 5];
425                case 4:
426                    e_2 = _a.sent();
427                    logger.error(e_2);
428                    return [3 /*break*/, 5];
429                case 5: return [2 /*return*/];
430            }
431        });
432    });
433}
434/**
435 * Wraps a standard gtag function with extra code to wait for completion of
436 * relevant initialization promises before sending requests.
437 *
438 * @param gtagCore Basic gtag function that just appends to dataLayer.
439 * @param initializationPromisesMap Map of appIds to their initialization promises.
440 * @param dynamicConfigPromisesList Array of dynamic config fetch promises.
441 * @param measurementIdToAppId Map of GA measurementIDs to corresponding Firebase appId.
442 */
443function wrapGtag(gtagCore, 
444/**
445 * Allows wrapped gtag calls to wait on whichever intialization promises are required,
446 * depending on the contents of the gtag params' `send_to` field, if any.
447 */
448initializationPromisesMap, 
449/**
450 * Wrapped gtag calls sometimes require all dynamic config fetches to have returned
451 * before determining what initialization promises (which include FIDs) to wait for.
452 */
453dynamicConfigPromisesList, 
454/**
455 * Wrapped gtag config calls can narrow down which initialization promise (with FID)
456 * to wait for if the measurementId is already fetched, by getting the corresponding appId,
457 * which is the key for the initialization promises map.
458 */
459measurementIdToAppId) {
460    /**
461     * Wrapper around gtag that ensures FID is sent with gtag calls.
462     * @param command Gtag command type.
463     * @param idOrNameOrParams Measurement ID if command is EVENT/CONFIG, params if command is SET.
464     * @param gtagParams Params if event is EVENT/CONFIG.
465     */
466    function gtagWrapper(command, idOrNameOrParams, gtagParams) {
467        return (0,tslib__WEBPACK_IMPORTED_MODULE_5__.__awaiter)(this, void 0, void 0, function () {
468            var e_3;
469            return (0,tslib__WEBPACK_IMPORTED_MODULE_5__.__generator)(this, function (_a) {
470                switch (_a.label) {
471                    case 0:
472                        _a.trys.push([0, 6, , 7]);
473                        if (!(command === GtagCommand.EVENT)) return [3 /*break*/, 2];
474                        // If EVENT, second arg must be measurementId.
475                        return [4 /*yield*/, gtagOnEvent(gtagCore, initializationPromisesMap, dynamicConfigPromisesList, idOrNameOrParams, gtagParams)];
476                    case 1:
477                        // If EVENT, second arg must be measurementId.
478                        _a.sent();
479                        return [3 /*break*/, 5];
480                    case 2:
481                        if (!(command === GtagCommand.CONFIG)) return [3 /*break*/, 4];
482                        // If CONFIG, second arg must be measurementId.
483                        return [4 /*yield*/, gtagOnConfig(gtagCore, initializationPromisesMap, dynamicConfigPromisesList, measurementIdToAppId, idOrNameOrParams, gtagParams)];
484                    case 3:
485                        // If CONFIG, second arg must be measurementId.
486                        _a.sent();
487                        return [3 /*break*/, 5];
488                    case 4:
489                        // If SET, second arg must be params.
490                        gtagCore(GtagCommand.SET, idOrNameOrParams);
491                        _a.label = 5;
492                    case 5: return [3 /*break*/, 7];
493                    case 6:
494                        e_3 = _a.sent();
495                        logger.error(e_3);
496                        return [3 /*break*/, 7];
497                    case 7: return [2 /*return*/];
498                }
499            });
500        });
501    }
502    return gtagWrapper;
503}
504/**
505 * Creates global gtag function or wraps existing one if found.
506 * This wrapped function attaches Firebase instance ID (FID) to gtag 'config' and
507 * 'event' calls that belong to the GAID associated with this Firebase instance.
508 *
509 * @param initializationPromisesMap Map of appIds to their initialization promises.
510 * @param dynamicConfigPromisesList Array of dynamic config fetch promises.
511 * @param measurementIdToAppId Map of GA measurementIDs to corresponding Firebase appI
511d.
512 * @param dataLayerName Name of global GA datalayer array.
513 * @param gtagFunctionName Name of global gtag function ("gtag" if not user-specified).
514 */
515function wrapOrCreateGtag(initializationPromisesMap, dynamicConfigPromisesList, measurementIdToAppId, dataLayerName, gtagFunctionName) {
516    // Create a basic core gtag function
517    var gtagCore = function () {
518        var _args = [];
519        for (var _i = 0; _i < arguments.length; _i++) {
520            _args[_i] = arguments[_i];
521        }
522        // Must push IArguments object, not an array.
523        window[dataLayerName].push(arguments);
524    };
525    // Replace it with existing one if found
526    if (window[gtagFunctionName] &&
527        typeof window[gtagFunctionName] === 'function') {
528        // @ts-ignore
529        gtagCore = window[gtagFunctionName];
530    }
531    window[gtagFunctionName] = wrapGtag(gtagCore, initializationPromisesMap, dynamicConfigPromisesList, measurementIdToAppId);
532    return {
533        gtagCore: gtagCore,
534        wrappedGtag: window[gtagFunctionName]
535    };
536}
537/**
538 * Returns first script tag in DOM matching our gtag url pattern.
539 */
540function findGtagScriptOnPage() {
541    var scriptTags = window.document.getElementsByTagName('script');
542    for (var _i = 0, _a = Object.values(scriptTags); _i < _a.length; _i++) {
543        var tag = _a[_i];
544        if (tag.src && tag.src.includes(GTAG_URL)) {
545            return tag;
546        }
547    }
548    return null;
549}
550
551/**
552 * @license
553 * Copyright 2019 Google LLC
554 *
555 * Licensed under the Apache License, Version 2.0 (the "License");
556 * you may not use this file except in compliance with the License.
557 * You may obtain a copy of the License at
558 *
559 *   http://www.apache.org/licenses/LICENSE-2.0
560 *
561 * Unless required by applicable law or agreed to in writing, software
562 * distributed under the License is distributed on an "AS IS" BASIS,
563 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
564 * See the License for the specific language governing permissions and
565 * limitations under the License.
566 */
567var _a;
568var ERRORS = (_a = {},
569    _a["already-exists" /* ALREADY_EXISTS */] = 'A Firebase Analytics instance with the appId {$id} ' +
570        ' already exists. ' +
571        'Only one Firebase Analytics instance can be created for each appId.',
572    _a["already-initialized" /* ALREADY_INITIALIZED */] = 'Firebase Analytics has already been initialized.' +
573        'settings() must be called before initializing any Analytics instance' +
574        'or it will have no effect.',
575    _a["interop-component-reg-failed" /* INTEROP_COMPONENT_REG_FAILED */] = 'Firebase Analytics Interop Component failed to instantiate: {$reason}',
576    _a["invalid-analytics-context" /* INVALID_ANALYTICS_CONTEXT */] = 'Firebase Analytics is not supported in this environment. ' +
577        'Wrap initialization of analytics in analytics.isSupported() ' +
578        'to prevent initialization in unsupported environments. Details: {$errorInfo}',
579    _a["indexeddb-unavailable" /* INDEXEDDB_UNAVAILABLE */] = 'IndexedDB unavailable or restricted in this environment. ' +
580        'Wrap initialization of analytics in analytics.isSupported() ' +
581        'to prevent initialization in unsupported environments. Details: {$errorInfo}',
582    _a["fetch-throttle" /* FETCH_THROTTLE */] = 'The config fetch request timed out while in an exponential backoff state.' +
583        ' Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.',
584    _a["config-fetch-failed" /* CONFIG_FETCH_FAILED */] = 'Dynamic config fetch failed: [{$httpStatus}] {$responseMessage}',
585    _a["no-api-key" /* NO_API_KEY */] = 'The "apiKey" field is empty in the local Firebase config. Firebase Analytics requires this field to' +
586        'contain a valid API key.',
587    _a["no-app-id" /* NO_APP_ID */] = 'The "appId" field is empty in the local Firebase config. Firebase Analytics requires this field to' +
588        'contain a valid app ID.',
589    _a);
590var ERROR_FACTORY = new _firebase_util__WEBPACK_IMPORTED_MODULE_3__.ErrorFactory('analytics', 'Analytics', ERRORS);
591
592/**
593 * @license
594 * Copyright 2020 Google LLC
595 *
596 * Licensed under the Apache License, Version 2.0 (the "License");
597 * you may not use this file except in compliance with the License.
598 * You may obtain a copy of the License at
599 *
600 *   http://www.apache.org/licenses/LICENSE-2.0
601 *
602 * Unless required by applicable law or agreed to in writing, software
603 * distributed under the License is distributed on an "AS IS" BASIS,
604 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
605 * See the License for the specific language governing permissions and
606 * limitations under the License.
607 */
608/**
609 * Backoff factor for 503 errors, which we want to be conservative about
610 * to avoid overloading servers. Each retry interval will be
611 * BASE_INTERVAL_MILLIS * LONG_RETRY_FACTOR ^ retryCount, so the second one
612 * will be ~30 seconds (with fuzzing).
613 */
614var LONG_RETRY_FACTOR = 30;
615/**
616 * Base wait interval to multiplied by backoffFactor^backoffCount.
617 */
618var BASE_INTERVAL_MILLIS = 1000;
619/**
620 * Stubbable retry data storage class.
621 */
622var RetryData = /** @class */ (function () {
623    function RetryData(throttleMetadata, intervalMillis) {
624        if (throttleMetadata === void 0) { throttleMetadata = {}; }
625        if (intervalMillis === void 0) { intervalMillis = BASE_INTERVAL_MILLIS; }
626        this.throttleMetadata = throttleMetadata;
627        this.intervalMillis = intervalMillis;
628    }
629    RetryData.prototype.getThrottleMetadata = function (appId) {
630        return this.throttleMetadata[appId];
631    };
632    RetryData.prototype.setThrottleMetadata = function (appId, metadata) {
633        this.throttleMetadata[appId] = metadata;
634    };
635    RetryData.prototype.deleteThrottleMetadata = function (appId) {
636        delete this.throttleMetadata[appId];
637    };
638    return RetryData;
639}());
640var defaultRetryData = new RetryData();
641/**
642 * Set GET request headers.
643 * @param apiKey App API key.
644 */
645function getHeaders(apiKey) {
646    return new Headers({
647        Accept: 'application/json',
648        'x-goog-api-key': apiKey
649    });
650}
651/**
652 * Fetches dynamic config from backend.
653 * @param app Firebase app to fetch config for.
654 */
655function fetchDynamicConfig(appFields) {
656    var _a;
657    return (0,tslib__WEBPACK_IMPORTED_MODULE_5__.__awaiter)(this, void 0, void 0, function () {
658        var appId, apiKey, request, appUrl, response, errorMessage, jsonResponse;
659        return (0,tslib__WEBPACK_IMPORTED_MODULE_5__.__generator)(this, function (_b) {
660            switch (_b.label) {
661                case 0:
662                    appId = appFields.appId, apiKey = appFields.apiKey;
663                    request = {
664                        method: 'GET',
665                        headers: getHeaders(apiKey)
666                    };
667                    appUrl = DYNAMIC_CONFIG_URL.replace('{app-id}', appId);
668                    return [4 /*yield*/, fetch(appUrl, request)];
669                case 1:
670                    response = _b.sent();
671                    if (!(response.status !== 200 && response.status !== 304)) return [3 /*break*/, 6];
672                    errorMessage = '';
673                    _b.label = 2;
674                case 2:
675                    _b.trys.push([2, 4, , 5]);
676                    return [4 /*yield*/, response.json()];
677                case 3:
678                    jsonResponse = (_b.sent());
679                    if ((_a = jsonResponse.error) === null || _a === void 0 ? void 0 : _a.message) {
680                        errorMessage = jsonResponse.error.message;
681                    }
682                    return [3 /*break*/, 5];
683                case 4:
684                    _b.sent();
685                    return [3 /*break*/, 5];
686                case 5: throw ERROR_FACTORY.create("config-fetch-failed" /* CONFIG_FETCH_FAILED */, {
687                    httpStatus: response.status,
688                    responseMessage: errorMessage
689                });
690                case 6: return [2 /*return*/, response.json()];
691            }
692        });
693    });
694}
695/**
696 * Fetches dynamic config from backend, retrying if failed.
697 * @param app Firebase app to fetch config for.
698 */
699function fetchDynamicConfigWithRetry(app, 
700// retryData and timeoutMillis are parameterized to allow passing a different value for testing.
701retryData, timeoutMillis) {
702    if (retryData === void 0) { retryData = defaultRetryData; }
703    return (0,tslib__WEBPACK_IMPORTED_MODULE_5__.__awaiter)(this, void 0, void 0, function () {
704        var _a, appId, apiKey, measurementId, throttleMetadata, signal;
705        var _this = this;
706        return (0,tslib__WEBPACK_IMPORTED_MODULE_5__.__generator)(this, function (_b) {
707            _a = app.options, appId = _a.appId, apiKey = _a.apiKey, measurementId = _a.measurementId;
708            if (!appId) {
709                throw ERROR_FACTORY.create("no-app-id" /* NO_APP_ID */);
710            }
711            if (!apiKey) {
712                if (measurementId) {
713                    return [2 /*return*/, {
714                            measurementId: measurementId,
715                            appId: appId
716                        }];
717                }
718                throw ERROR_FACTORY.create("no-api-key" /* NO_API_KEY */);
719            }
720            throttleMetadata = retryData.getThrottleMetadata(appId) || {
721                backoffCount: 0,
722                throttleEndTimeMillis: Date.now()
723            };
724            signal = new AnalyticsAbortSignal();
725            setTimeout(function () { return (0,tslib__WEBPACK_IMPORTED_MODULE_5__.__awaiter)(_this, void 0, void 0, function () {
726                return (0,tslib__WEBPACK_IMPORTED_MODULE_5__.__generator)(this, function (_a) {
727                    // Note a very low delay, eg < 10ms, can elapse before listeners are initialized.
728                    signal.abort();
729                    return [2 /*return*/];
730                });
731            }); }, timeoutMillis !== undefined ? timeoutMillis : FETCH_TIMEOUT_MILLIS);
732            return [2 /*return*/, attemptFetchDynamicConfigWithRetry({ appId: appId, apiKey: apiKey, measurementId: measurementId }, throttleMetadata, signal, retryData)];
733        });
734    });
735}
736/**
737 * Runs one retry attempt.
738 * @param appFields Necessary app config fields.
739 * @param throttleMetadata Ongoing metadata to determine throttling times.
740 * @param signal Abort signal.
741 */
742function attemptFetchDynamicConfigWithRetry(appFields, _a, signal, retryData // for testing
743) {
744    var throttleEndTimeMillis = _a.throttleEndTimeMillis, backoffCount = _a.backoffCount;
745    if (retryData === void 0) { retryData = defaultRetryData; }
746    return (0,tslib__WEBPACK_IMPORTED_MODULE_5__.__awaiter)(this, void 0, void 0, function () {
747        var appId, measurementId, e_1, response, e_2, backoffMillis, throttleMetadata;
748        return (0,tslib__WEBPACK_IMPORTED_MODULE_5__.__generator)(this, function (_b) {
749            switch (_b.label) {
750                case 0:
751                    appId = appFields.appId, measurementId = appFields.measurementId;
752                    _b.label = 1;
753                case 1:
754                    _b.trys.push([1, 3, , 4]);
755                    return [4 /*yield*/, setAbortableTimeout(signal, throttleEndTimeMillis)];
756                case 2:
757                    _b.sent();
758                    return [3 /*break*/, 4];
759                case 3:
760                    e_1 = _b.sent();
761                    if (measurementId) {
762                        logger.warn("Timed out fetching this Firebase app's measurement ID from the server." +
763                            (" Falling back to the measurement ID " + measurementId) +
764                            (" provided in the \"measurementId\" field in the local Firebase config. [" + e_1.message + "]"));
765                        return [2 /*return*/, { appId: appId, measurementId: measurementId }];
766                    }
767                    throw e_1;
768                case 4:
769                    _b.trys.push([4, 6, , 7]);
770                    return [4 /*yield*/, fetchDynamicConfig(appFields)];
771                case 5:
772                    response = _b.sent();
773                    // Note the SDK only clears throttle state if response is success or non-retriable.
774                    retryData.deleteThrottleMetadata(appId);
775                    return [2 /*return*/, response];
776                case 6:
777                    e_2 = _b.sent();
778                    if (!isRetriableError(e_2)) {
779                        retryData.deleteThrottleMetadata(appId);
780                        if (measurementId) {
781                            logger.warn("Failed to fetch this Firebase app's measurement ID from the server." +
782                                (" Falling back to the measurement ID " + measurementId) +
783                                (" provided in the \"measurementId\" field in the local Firebase config. [" + e_2.message + "]"));
784                            return [2 /*return*/, { appId: appId, measurementId: measurementId }];
785                        }
786                        else {
787                            throw e_2;
788                        }
789                    }
790                    backoffMillis = Number(e_2.customData.httpStatus) === 503
791                        ? (0,_firebase_util__WEBPACK_IMPORTED_MODULE_3__.calculateBackoffMillis)(backoffCount, retryData.intervalMillis, LONG_RETRY_FACTOR)
792                        : (0,_firebase_util__WEBPACK_IMPORTED_MODULE_3__.calculateBackoffMillis)(backoffCount, retryData.intervalMillis);
793                    throttleMetadata = {
794                        throttleEndTimeMillis: Date.now() + backoffMillis,
795                        backoffCount: backoffCount + 1
796                    };
797                    // Persists state.
798                    retryData.setThrottleMetadata(appId, throttleMetadata);
799                    logger.debug("Calling attemptFetch again in " + backoffMillis + " millis");
800                    return [2 /*return*/, attemptFetchDynamicConfigWithRetry(appFields, throttleMetadata, signal, retryData)];
801                case 7: return [2 /*return*/];
802            }
803        });
804    });
805}
806/**
807 * Supports waiting on a backoff by:
808 *
809 * <ul>
810 *   <li>Promisifying setTimeout, so we can set a timeout in our Promise chain</li>
811 *   <li>Listening on a signal bus for abort events, just like the Fetch API</li>
812 *   <li>Failing in the same way the Fetch API fails, so timing out a live request and a throttled
813 *       request appear the same.</li>
814 * </ul>
815 *
816 * <p>Visible for testing.
817 */
818function setAbortableTimeout(signal, throttleEndTimeMillis) {
819    return new Promise(function (resolve, reject) {
820        // Derives backoff from given end time, normalizing negative numbers to zero.
821        var backoffMillis = Math.max(throttleEndTimeMillis - Date.now(), 0);
822        var timeout = setTimeout(resolve, backoffMillis);
823        // Adds listener, rather than sets onabort, because signal is a shared object.
824        signal.addEventListener(function () {
825            clearTimeout(timeout);
826            // If the request completes before this timeout, the rejection has no effect.
827            reject(ERROR_FACTORY.create("fetch-throttle" /* FETCH_THROTTLE */, {
828                throttleEndTimeMillis: throttleEndTimeMillis
829            }));
830        });
831    });
832}
833/**
834 * Returns true if the {@link Error} indicates a fetch request may succeed later.
835 */
836function isRetriableError(e) {
837    if (!(e instanceof _firebase_util__WEBPACK_IMPORTED_MODULE_3__.FirebaseError) || !e.customData) {
838        return false;
839    }
840    // Uses string index defined by ErrorData, which FirebaseError implements.
841    var httpStatus = Number(e.customData['httpStatus']);
842    return (httpStatus === 429 ||
843        httpStatus === 500 ||
844        httpStatus === 503 ||
845        httpStatus === 504);
846}
847/**
848 * Shims a minimal AbortSignal (copied from Remote Config).
849 *
850 * <p>AbortController's AbortSignal conveniently decouples fetch timeout logic from other aspects
851 * of networking, such as retries. Firebase doesn't use AbortController enough to justify a
852 * polyfill recommendation, like we do with the Fetch API, but this minimal shim can easily be
853 * swapped out if/when we do.
854 */
855var AnalyticsAbortSignal = /** @class */ (function () {
856    function AnalyticsAbortSignal() {
857        this.listeners = [];
858    }
859    AnalyticsAbortSignal.prototype.addEventListener = function (listener) {
860        this.listeners.push(listener);
861    };
862    AnalyticsAbortSignal.prototype.abort = function () {
863        this.listeners.forEach(function (listener) { return listener(); });
864    };
865    return AnalyticsAbortSignal;
866}());
867
868/**
869 * @license
870 * Copyright 2020 Google LLC
871 *
872 * Licensed under the Apache License, Version 2.0 (the "License");
873 * you may not use this file except in compliance with the License.
874 * You may obtain a copy of the License at
875 *
876 *   http://www.apache.org/licenses/LICENSE-2.0
877 *
878 * Unless required by applicable law or agreed to in writing, software
879 * distributed under the License is distributed on an "AS IS" BASIS,
880 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
881 * See the License for the specific language governing permissions and
882 * limitations under the License.
883 */
884function validateIndexedDB() {
885    return (0,tslib__WEBPACK_IMPORTED_MODULE_5__.__awaiter)(this, void 0, void 0, function () {
886        var e_1;
887        return (0,tslib__WEBPACK_IMPORTED_MODULE_5__.__generator)(this, function (_a) {
888            switch (_a.label) {
889                case 0:
890                    if (!!(0,_firebase_util__WEBPACK_IMPORTED_MODULE_3__.isIndexedDBAvailable)()) return [3 /*break*/, 1];
891                    logger.warn(ERROR_FACTORY.create("indexeddb-unavailable" /* INDEXEDDB_UNAVAILABLE */, {
892                        errorInfo: 'IndexedDB is not available in this environment.'
893                    }).message);
894                    return [2 /*return*/, false];
895                case 1:
896                    _a.trys.push([1, 3, , 4]);
897                    return [4 /*yield*/, (0,_firebase_util__WEBPACK_IMPORTED_MODULE_3__.validateIndexedDBOpenable)()];
898                case 2:
899                    _a.sent();
900                    return [3 /*break*/, 4];
901                case 3:
902                    e_1 = _a.sent();
903                    logger.warn(ERROR_FACTORY.create("indexeddb-unavailable" /* INDEXEDDB_UNAVAILABLE */, {
904                        errorInfo: e_1
905                    }).message);
906                    return [2 /*return*/, false];
907                case 4: return [2 /*return*/, true];
908            }
909        });
910    });
911}
912/**
913 * Initialize the analytics instance in gtag.js by calling config command with fid.
914 *
915 * NOTE: We combine analytics initialization and setting fid together because we want fid to be
916 * part of the `page_view` event that's sent during the initialization
917 * @param app Firebase app
918 * @param gtagCore The gtag function that's not wrapped.
919 * @param dynamicConfigPromisesList Array of all dynamic config promises.
920 * @param measurementIdToAppId Maps measurementID to appID.
921 * @param installations FirebaseInstallations instance.
922 *
923 * @returns Measurement ID.
924 */
925function initializeIds(app, dynamicConfigPromisesList, measurementIdToAppId, installations, gtagCore, dataLayerName) {
926    return (0,tslib__WEBPACK_IMPORTED_MODULE_5__.__awaiter)(this, void 0, void 0, function () {
927        var dynamicConfigPromise, fidPromise, _a, dynamicConfig, fid, configProperties;
928        var _b;
929        return (0,tslib__WEBPACK_IMPORTED_MODULE_5__.__generator)(this, function (_c) {
930            switch (_c.label) {
931                case 0:
932                    dynamicConfigPromise = fetchDynamicConfigWithRetry(app);
933                    // Once fetched, map measurementIds to appId, for ease of lookup in wrapped gtag function.
934                    dynamicConfigPromise
935                        .then(function (config) {
936                        measurementIdToAppId[config.measurementId] = config.appId;
937                        if (app.options.measurementId &&
938                            config.measurementId !== app.options.measurementId) {
939                            logger.warn("The measurement ID in the local Firebase config (" + app.options.measurementId + ")" +
940                                (" does not match the measurement ID fetched from the server (" + config.measurementId + ").") +
941                                " To ensure analytics events are always sent to the correct Analytics property," +
942                                " update the" +
943                                " measurement ID field in the local config or remove it from the local config.");
944                        }
945                    })
946                        .catch(function (e) { return logger.error(e); });
947                    // Add to list to track state of all dynamic config promises.
948                    dynamicConfigPromisesList.push(dynamicConfigPromise);
949                    fidPromise = validateIndexedDB().then(function (envIsValid) {
950                        if (envIsValid) {
951                            return installations.getId();
952                        }
953                        else {
954                            return undefined;
955                        }
956                    });
957                    return [4 /*yield*/, Promise.all([
958                            dynamicConfigPromise,
959                            fidPromise
960                        ])];
961                case 1:
962                    _a = _c.sent(), dynamicConfig = _a[0], fid = _a[1];
963                    // Detect if user has already put the gtag <script> tag on this page.
964                    if (!findGtagScriptOnPage()) {
965                        insertScriptTag(dataLayerName, dynamicConfig.measurementId);
966                    }
967                    // This command initializes gtag.js and only needs to be called once for the entire web app,
968                    // but since it is idempotent, we can call it multiple times.
969                    // We keep it together with other initialization logic for better code structure.
970                    // eslint-disable-next-line @typescript-eslint/no-explicit-any
971                    gtagCore('js', new Date());
972                    configProperties = (_b = {},
973                        // guard against developers accidentally setting properties with prefix `firebase_`
974                        _b[ORIGIN_KEY] = 'firebase',
975                        _b.update = true,
976                        _b);
977                    if (fid != null) {
978                        configProperties[GA_FID_KEY] = fid;
979                    }
980                    // It should be the first config command called on this GA-ID
981                    // Initialize this GA-ID and set FID on it using the gtag config API.
982                    // Note: This will trigger a page_view event unless 'send_page_view' is set to false in
983                    // `configProperties`.
984                    gtagCore(GtagCommand.CONFIG, dynamicConfig.measurementId, configProperties);
985                    return [2 /*return*/, dynamicConfig.measurementId];
986            }
987        });
988    });
989}
990
991/**
992 * @license
993 * Copyright 2019 Google LLC
994 *
995 * Licensed under the Apache License, Version 2.0 (the "License");
996 * you may not use this file except in compliance with the License.
997 * You may obtain a copy of the License at
998 *
999 *   http://www.apache.org/licenses/LICENSE-2.0
1000 *
1001 * Unless required by applicable law or agreed to in writing, software
1002 * distributed under the License is distributed on an "AS IS" BASIS,
1003 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1004 * See the License for the specific language governing permissions and
1005 * limitations under the License.
1006 */
1007/**
1008 * Maps appId to full initialization promise. Wrapped gtag calls must wait on
1009 * all or some of these, depending on the call's `send_to` param and the status
1010 * of the dynamic config fetches (see below).
1011 */
1012var initializationPromisesMap = {};
1013/**
1014 * List of dynamic config fetch promises. In certain cases, wrapped gtag calls
1015 * wait on all these to be complete in order to determine if it can selectively
1016 * wait for only certain initialization (FID) promises or if it must wait for all.
1017 */
1018var dynamicConfigPromisesList = [];
1019/**
1020 * Maps fetched measurementIds to appId. Populated when the app's dynamic config
1021 * fetch completes. If already populated, gtag config calls can use this to
1022 * selectively wait for only this app's initialization promise (FID) instead of all
1023 * initialization promises.
1024 */
1025var measurementIdToAppId = {};
1026/**
1027 * Name for window global data layer array used by GA: defaults to 'dataLayer'.
1028 */
1029var dataLayerName = 'dataLayer';
1030/**
1031 * Name for window global gtag function used by GA: defaults to 'gtag'.
1032 */
1033var gtagName = 'gtag';
1034/**
1035 * Reproduction of standard gtag function or reference to existing
1036 * gtag function on window object.
1037 */
1038var gtagCoreFunction;
1039/**
1040 * Wrapper around gtag function that ensures FID is sent with all
1041 * relevant event and config calls.
1042 */
1043var wrappedGtagFunction;
1044/**
1045 * Flag to ensure page initialization steps (creation or wrapping of
1046 * dataLayer and gtag script) are only run once per page load.
1047 */
1048var globalInitDone = false;
1049/**
1050 * For testing
1051 */
1052function resetGlobalVars(newGlobalInitDone, newInitializationPromisesMap, newDynamicPromises) {
1053    if (newGlobalInitDone === void 0) { newGlobalInitDone = false; }
1054    if (newInitializationPromisesMap === void 0) { newInitializationPromisesMap = {}; }
1055    if (newDynamicPromises === void 0) { newDynamicPromises = []; }
1056    globalInitDone = newGlobalInitDone;
1057    initializationPromisesMap = newInitializationPromisesMap;
1058    dynamicConfigPromisesList = newDynamicPromises;
1059    dataLayerName = 'dataLayer';
1060    gtagName = 'gtag';
1061}
1062/**
1063 * For testing
1064 */
1065function getGlobalVars() {
1066    return {
1067        initializationPromisesMap: initializationPromisesMap,
1068        dynamicConfigPromisesList: dynamicConfigPromisesList
1069    };
1070}
1071/**
1072 * This must be run before calling firebase.analytics() or it won't
1073 * have any effect.
1074 * @param options Custom gtag and dataLayer names.
1075 */
1076function settings(options) {
1077    if (globalInitDone) {
1078        throw ERROR_FACTORY.create("already-initialized" /* ALREADY_INITIALIZED */);
1079    }
1080    if (options.dataLayerName) {
1081        dataLayerName = options.dataLayerName;
1082    }
1083    if (options.gtagName) {
1084        gtagName = options.gtagName;
1085    }
1086}
1087/**
1088 * Returns true if no environment mismatch is found.
1089 * If environment mismatches are found, throws an INVALID_ANALYTICS_CONTEXT
1090 * error that also lists details for each mismatch found.
1091 */
1092function warnOnBrowserContextMismatch() {
1093    var mismatchedEnvMessages = [];
1094    if ((0,_firebase_util__WEBPACK_IMPORTED_MODULE_3__.isBrowserExtension)()) {
1095        mismatchedEnvMessages.push('This is a browser extension environment.');
1096    }
1097    if (!(0,_firebase_util__WEBPACK_IMPORTED_MODULE_3__.areCookiesEnabled)()) {
1098        mismatchedEnvMessages.push('Cookies are not available.');
1099    }
1100    if (mismatchedEnvMessages.length > 0) {
1101        var details = mismatchedEnvMessages
1102            .map(function (message, index) { return "(" + (index + 1) + ") " + message; })
1103            .join(' ');
1104        var err = ERROR_FACTORY.create("invalid-analytics-context" /* INVA
1104LID_ANALYTICS_CONTEXT */, {
1105            errorInfo: details
1106        });
1107        logger.warn(err.message);
1108    }
1109}
1110function factory(app, installations) {
1111    warnOnBrowserContextMismatch();
1112    var appId = app.options.appId;
1113    if (!appId) {
1114        throw ERROR_FACTORY.create("no-app-id" /* NO_APP_ID */);
1115    }
1116    if (!app.options.apiKey) {
1117        if (app.options.measurementId) {
1118            logger.warn("The \"apiKey\" field is empty in the local Firebase config. This is needed to fetch the latest" +
1119                (" measurement ID for this Firebase app. Falling back to the measurement ID " + app.options.measurementId) +
1120                " provided in the \"measurementId\" field in the local Firebase config.");
1121        }
1122        else {
1123            throw ERROR_FACTORY.create("no-api-key" /* NO_API_KEY */);
1124        }
1125    }
1126    if (initializationPromisesMap[appId] != null) {
1127        throw ERROR_FACTORY.create("already-exists" /* ALREADY_EXISTS */, {
1128            id: appId
1129        });
1130    }
1131    if (!globalInitDone) {
1132        // Steps here should only be done once per page: creation or wrapping
1133        // of dataLayer and global gtag function.
1134        getOrCreateDataLayer(dataLayerName);
1135        var _a = wrapOrCreateGtag(initializationPromisesMap, dynamicConfigPromisesList, measurementIdToAppId, dataLayerName, gtagName), wrappedGtag = _a.wrappedGtag, gtagCore = _a.gtagCore;
1136        wrappedGtagFunction = wrappedGtag;
1137        gtagCoreFunction = gtagCore;
1138        globalInitDone = true;
1139    }
1140    // Async but non-blocking.
1141    // This map reflects the completion state of all promises for each appId.
1142    initializationPromisesMap[appId] = initializeIds(app, dynamicConfigPromisesList, measurementIdToAppId, installations, gtagCoreFunction, dataLayerName);
1143    var analyticsInstance = {
1144        app: app,
1145        // Public methods return void for API simplicity and to better match gtag,
1146        // while internal implementations return promises.
1147        logEvent: function (eventName, eventParams, options) {
1148            logEvent(wrappedGtagFunction, initializationPromisesMap[appId], eventName, eventParams, options).catch(function (e) { return logger.error(e); });
1149        },
1150        setCurrentScreen: function (screenName, options) {
1151            setCurrentScreen(wrappedGtagFunction, initializationPromisesMap[appId], screenName, options).catch(function (e) { return logger.error(e); });
1152        },
1153        setUserId: function (id, options) {
1154            setUserId(wrappedGtagFunction, initializationPromisesMap[appId], id, options).catch(function (e) { return logger.error(e); });
1155        },
1156        setUserProperties: function (properties, options) {
1157            setUserProperties(wrappedGtagFunction, initializationPromisesMap[appId], properties, options).catch(function (e) { return logger.error(e); });
1158        },
1159        setAnalyticsCollectionEnabled: function (enabled) {
1160            setAnalyticsCollectionEnabled(initializationPromisesMap[appId], enabled).catch(function (e) { return logger.error(e); });
1161        },
1162        INTERNAL: {
1163            delete: function () {
1164                delete initializationPromisesMap[appId];
1165                return Promise.resolve();
1166            }
1167        }
1168    };
1169    return analyticsInstance;
1170}
1171
1172var name = "@firebase/analytics";
1173var version = "0.6.18";
1174
1175/**
1176 * Type constant for Firebase Analytics.
1177 */
1178var ANALYTICS_TYPE = 'analytics';
1179function registerAnalytics(instance) {
1180    instance.INTERNAL.registerComponent(new _firebase_component__WEBPACK_IMPORTED_MODULE_4__.Component(ANALYTICS_TYPE, function (container) {
1181        // getImmediate for FirebaseApp will always succeed
1182        var app = container.getProvider('app').getImmediate();
1183        var installations = container
1184            .getProvider('installations')
1185            .getImmediate();
1186        return factory(app, installations);
1187    }, "PUBLIC" /* PUBLIC */).setServiceProps({
1188        settings: settings,
1189        EventName: EventName,
1190        isSupported: isSupported
1191    }));
1192    instance.INTERNAL.registerComponent(new _firebase_component__WEBPACK_IMPORTED_MODULE_4__.Component('analytics-internal', internalFactory, "PRIVATE" /* PRIVATE */));
1193    instance.registerVersion(name, version);
1194    function internalFactory(container) {
1195        try {
1196            var analytics = container.getProvider(ANALYTICS_TYPE).getImmediate();
1197            return {
1198                logEvent: analytics.logEvent
1199            };
1200        }
1201        catch (e) {
1202            throw ERROR_FACTORY.create("interop-component-reg-failed" /* INTEROP_COMPONENT_REG_FAILED */, {
1203                reason: e
1204            });
1205        }
1206    }
1207}
1208registerAnalytics(_firebase_app__WEBPACK_IMPORTED_MODULE_0__.default);
1209/**
1210 * this is a public static method provided to users that wraps four different checks:
1211 *
1212 * 1. check if it's not a browser extension environment.
1213 * 1. check if cookie is enabled in current browser.
1214 * 3. check if IndexedDB is supported by the browser environment.
1215 * 4. check if the current browser context is valid for using IndexedDB.
1216 *
1217 */
1218function isSupported() {
1219    return (0,tslib__WEBPACK_IMPORTED_MODULE_5__.__awaiter)(this, void 0, void 0, function () {
1220        var isDBOpenable;
1221        return (0,tslib__WEBPACK_IMPORTED_MODULE_5__.__generator)(this, function (_a) {
1222            switch (_a.label) {
1223                case 0:
1224                    if ((0,_firebase_util__WEBPACK_IMPORTED_MODULE_3__.isBrowserExtension)()) {
1225                        return [2 /*return*/, false];
1226                    }
1227                    if (!(0,_firebase_util__WEBPACK_IMPORTED_MODULE_3__.areCookiesEnabled)()) {
1228                        return [2 /*return*/, false];
1229                    }
1230                    if (!(0,_firebase_util__WEBPACK_IMPORTED_MODULE_3__.isIndexedDBAvailable)()) {
1231                        return [2 /*return*/, false];
1232                    }
1233                    _a.label = 1;
1234                case 1:
1235                    _a.trys.push([1, 3, , 4]);
1236                    return [4 /*yield*/, (0,_firebase_util__WEBPACK_IMPORTED_MODULE_3__.validateIndexedDBOpenable)()];
1237                case 2:
1238                    isDBOpenable = _a.sent();
1239                    return [2 /*return*/, isDBOpenable];
1240                case 3:
1241                    _a.sent();
1242                    return [2 /*return*/, false];
1243                case 4: return [2 /*return*/];
1244            }
1245        });
1246    });
1247}
1248
1249
1250//# sourceMappingURL=index.esm.js.map
1251
1252
1253/***/ }),
1254
1255/***/ 21723:
1256/*!****************************************************************!*\
1257  !*** ./node_modules/@firebase/installations/dist/index.esm.js ***!
1258  \****************************************************************/
1259/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
1260
1261"use strict";
1262__webpack_require__.r(__webpack_exports__);
1263/* harmony export */ __webpack_require__.d(__webpack_exports__, {
1264/* harmony export */   "registerInstallations": function() { return /* binding */ registerInstallations; }
1265/* harmony export */ });
1266/* harmony import */ var _firebase_app__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @firebase/app */ 79759);
1267/* harmony import */ var _firebase_component__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @firebase/component */ 16034);
1268/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! tslib */ 64762);
1269/* harmony import */ var _firebase_util__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @firebase/util */ 64685);
1270/* harmony import */ var idb__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! idb */ 16676);
1271/* harmony import */ var idb__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(idb__WEBPACK_IMPORTED_MODULE_3__);
1272
1273
1274
1275
1276
1277
1278var name = "@firebase/installations";
1279var version = "0.4.32";
1280
1281/**
1282 * @license
1283 * Copyright 2019 Google LLC
1284 *
1285 * Licensed under the Apache License, Version 2.0 (the "License");
1286 * you may not use this file except in compliance with the License.
1287 * You may obtain a copy of the License at
1288 *
1289 *   http://www.apache.org/licenses/LICENSE-2.0
1290 *
1291 * Unless required by applicable law or agreed to in writing, software
1292 * distributed under the License is distributed on an "AS IS" BASIS,
1293 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1294 * See the License for the specific language governing permissions and
1295 * limitations under the License.
1296 */
1297var PENDING_TIMEOUT_MS = 10000;
1298var PACKAGE_VERSION = "w:" + version;
1299var INTERNAL_AUTH_VERSION = 'FIS_v2';
1300var INSTALLATIONS_API_URL = 'https://firebaseinstallations.googleapis.com/v1';
1301var TOKEN_EXPIRATION_BUFFER = 60 * 60 * 1000; // One hour
1302var SERVICE = 'installations';
1303var SERVICE_NAME = 'Installations';
1304
1305/**
1306 * @license
1307 * Copyright 2019 Google LLC
1308 *
1309 * Licensed under the Apache License, Version 2.0 (the "License");
1310 * you may not use this file except in compliance with the License.
1311 * You may obtain a copy of the License at
1312 *
1313 *   http://www.apache.org/licenses/LICENSE-2.0
1314 *
1315 * Unless required by applicable law or agreed to in writing, software
1316 * distributed under the License is distributed on an "AS IS" BASIS,
1317 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1318 * See the License for the specific language governing permissions and
1319 * limitations under the License.
1320 */
1321var _a;
1322var ERROR_DESCRIPTION_MAP = (_a = {},
1323    _a["missing-app-config-values" /* MISSING_APP_CONFIG_VALUES */] = 'Missing App configuration value: "{$valueName}"',
1324    _a["not-registered" /* NOT_REGISTERED */] = 'Firebase Installation is not registered.',
1325    _a["installation-not-found" /* INSTALLATION_NOT_FOUND */] = 'Firebase Installation not found.',
1326    _a["request-failed" /* REQUEST_FAILED */] = '{$requestName} request failed with error "{$serverCode} {$serverStatus}: {$serverMessage}"',
1327    _a["app-offline" /* APP_OFFLINE */] = 'Could not process request. Application offline.',
1328    _a["delete-pending-registration" /* DELETE_PENDING_REGISTRATION */] = "Can't delete installation while there is a pending registration request.",
1329    _a);
1330var ERROR_FACTORY = new _firebase_util__WEBPACK_IMPORTED_MODULE_2__.ErrorFactory(SERVICE, SERVICE_NAME, ERROR_DESCRIPTION_MAP);
1331/** Returns true if error is a FirebaseError that is based on an error from the server. */
1332function isServerError(error) {
1333    return (error instanceof _firebase_util__WEBPACK_IMPORTED_MODULE_2__.FirebaseError &&
1334        error.code.includes("request-failed" /* REQUEST_FAILED */));
1335}
1336
1337/**
1338 * @license
1339 * Copyright 2019 Google LLC
1340 *
1341 * Licensed under the Apache License, Version 2.0 (the "License");
1342 * you may not use this file except in compliance with the License.
1343 * You may obtain a copy of the License at
1344 *
1345 *   http://www.apache.org/licenses/LICENSE-2.0
1346 *
1347 * Unless required by applicable law or agreed to in writing, software
1348 * distributed under the License is distributed on an "AS IS" BASIS,
1349 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1350 * See the License for the specific language governing permissions and
1351 * limitations under the License.
1352 */
1353function getInstallationsEndpoint(_a) {
1354    var projectId = _a.projectId;
1355    return INSTALLATIONS_API_URL + "/projects/" + projectId + "/installations";
1356}
1357function extractAuthTokenInfoFromResponse(response) {
1358    return {
1359        token: response.token,
1360        requestStatus: 2 /* COMPLETED */,
1361        expiresIn: getExpiresInFromResponseExpiresIn(response.expiresIn),
1362        creationTime: Date.now()
1363    };
1364}
1365function getErrorFromResponse(requestName, response) {
1366    return (0,tslib__WEBPACK_IMPORTED_MODULE_4__.__awaiter)(this, void 0, void 0, function () {
1367        var responseJson, errorData;
1368        return (0,tslib__WEBPACK_IMPORTED_MODULE_4__.__generator)(this, function (_a) {
1369            switch (_a.label) {
1370                case 0: return [4 /*yield*/, response.json()];
1371                case 1:
1372                    responseJson = _a.sent();
1373                    errorData = responseJson.error;
1374                    return [2 /*return*/, ERROR_FACTORY.create("request-failed" /* REQUEST_FAILED */, {
1375                            requestName: requestName,
1376                            serverCode: errorData.code,
1377                            serverMessage: errorData.message,
1378                            serverStatus: errorData.status
1379                        })];
1380            }
1381        });
1382    });
1383}
1384function getHeaders(_a) {
1385    var apiKey = _a.apiKey;
1386    return new Headers({
1387        'Content-Type': 'application/json',
1388        Accept: 'application/json',
1389        'x-goog-api-key': apiKey
1390    });
1391}
1392function getHeadersWithAuth(appConfig, _a) {
1393    var refreshToken = _a.refreshToken;
1394    var headers = getHeaders(appConfig);
1395    headers.append('Authorization', getAuthorizationHeader(refreshToken));
1396    return headers;
1397}
1398/**
1399 * Calls the passed in fetch wrapper and returns the response.
1400 * If the returned response has a status of 5xx, re-runs the function once and
1401 * returns the response.
1402 */
1403function retryIfServerError(fn) {
1404    return (0,tslib__WEBPACK_IMPORTED_MODULE_4__.__awaiter)(this, void 0, void 0, function () {
1405        var result;
1406        return (0,tslib__WEBPACK_IMPORTED_MODULE_4__.__generator)(this, function (_a) {
1407            switch (_a.label) {
1408                case 0: return [4 /*yield*/, fn()];
1409                case 1:
1410                    result = _a.sent();
1411                    if (result.status >= 500 && result.status < 600) {
1412                        // Internal Server Error. Retry request.
1413                        return [2 /*return*/, fn()];
1414                    }
1415                    return [2 /*return*/, result];
1416            }
1417        });
1418    });
1419}
1420function getExpiresInFromResponseExpiresIn(responseExpiresIn) {
1421    // This works because the server will never respond with fractions of a second.
1422    return Number(responseExpiresIn.replace('s', '000'));
1423}
1424function getAuthorizationHeader(refreshToken) {
1425    return INTERNAL_AUTH_VERSION + " " + refreshToken;
1426}
1427
1428/**
1429 * @license
1430 * Copyright 2019 Google LLC
1431 *
1432 * Licensed under the Apache License, Version 2.0 (the "License");
1433 * you may not use this file except in compliance with the License.
1434 * You may obtain a copy of the License at
1435 *
1436 *   http://www.apache.org/licenses/LICENSE-2.0
1437 *
1438 * Unless required by applicable law or agreed to in writing, software
1439 * distributed under the License is distributed on an "AS IS" BASIS,
1440 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1441 * See the License for the specific language governing permissions and
1442 * limitations under the License.
1443 */
1444function createInstallationRequest(appConfig, _a) {
1445    var fid = _a.fid;
1446    return (0,tslib__WEBPACK_IMPORTED_MODULE_4__.__awaiter)(this, void 0, void 0, function () {
1447        var endpoint, headers, body, request, response, responseValue, registeredInstallationEntry;
1448        return (0,tslib__WEBPACK_IMPORTED_MODULE_4__.__generator)(this, function (_b) {
1449            switch (_b.label) {
1450                case 0:
1451                    endpoint = getInstallationsEndpoint(appConfig);
1452                    headers = getHeaders(appConfig);
1453                    body = {
1454                        fid: fid,
1455                        authVersion: INTERNAL_AUTH_VERSION,
1456                        appId: appConfig.appId,
1457                        sdkVersion: PACKAGE_VERSION
1458                    };
1459                    request = {
1460                        method: 'POST',
1461                        headers: headers,
1462                        body: JSON.stringify(body)
1463                    };
1464                    return [4 /*yield*/, retryIfServerError(function () { return fetch(endpoint, request); })];
1465                case 1:
1466                    response = _b.sent();
1467                    if (!response.ok) return [3 /*break*/, 3];
1468                    return [4 /*yield*/, response.json()];
1469                case 2:
1470                    responseValue = _b.sent();
1471                    registeredInstallationEntry = {
1472                        fid: responseValue.fid || fid,
1473                        registrationStatus: 2 /* COMPLETED */,
1474                        refreshToken: responseValue.refreshToken,
1475                        authToken: extractAuthTokenInfoFromResponse(responseValue.authToken)
1476                    };
1477                    return [2 /*return*/, registeredInstallationEntry];
1478                case 3: return [4 /*yield*/, getErrorFromResponse('Create Installation', response)];
1479                case 4: throw _b.sent();
1480            }
1481        });
1482    });
1483}
1484
1485/**
1486 * @license
1487 * Copyright 2020 Google LLC
1488 *
1489 * Licensed under the Apache License, Version 2.0 (the "License");
1490 * you may not use this file except in compliance with the License.
1491 * You may obtain a copy of the License at
1492 *
1493 *   http://www.apache.org/licenses/LICENSE-2.0
1494 *
1495 * Unless required by applicable law or agreed to in writing, software
1496 * distributed under the License is distributed on an "AS IS" BASIS,
1497 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1498 * See the License for the specific language governing permissions and
1499 * limitations under the License.
1500 */
1501/** Returns a promise that resolves after given time passes. */
1502function sleep(ms) {
1503    return new Promise(function (resolve) {
1504        setTimeout(resolve, ms);
1505    });
1506}
1507
1508/**
1509 * @license
1510 * Copyright 2019 Google LLC
1511 *
1512 * Licensed under the Apache License, Version 2.0 (the "License");
1513 * you may not use this file except in compliance with the License.
1514 * You may obtain a copy of the License at
1515 *
1516 *   http://www.apache.org/licenses/LICENSE-2.0
1517 *
1518 * Unless required by applicable law or agreed to in writing, software
1519 * distributed under the License is distributed on an "AS IS" BASIS,
1520 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1521 * See the License for the specific language governing permissions and
1522 * limitations under the License.
1523 */
1524function bufferToBase64UrlSafe(array) {
1525    var b64 = btoa(String.fromCharCode.apply(String, (0,tslib__WEBPACK_IMPORTED_MODULE_4__.__spreadArray)([], (0,tslib__WEBPACK_IMPORTED_MODULE_4__.__read)(array))));
1526    return b64.replace(/\+/g, '-').replace(/\//g, '_');
1527}
1528
1529/**
1530 * @license
1531 * Copyright 2019 Google LLC
1532 *
1533 * Licensed under the Apache License, Version 2.0 (the "License");
1534 * you may not use this file except in compliance with the License.
1535 * You may obtain a copy of the License at
1536 *
1537 *   http://www.apache.org/licenses/LICENSE-2.0
1538 *
1539 * Unless required by applicable law or agreed to in writing, software
1540 * distributed under the License is distributed on an "AS IS" BASIS,
1541 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1542 * See the License for the specific language governing permissions and
1543 * limitations under the License.
1544 */
1545var VALID_FID_PATTERN = /^[cdef][\w-]{21}$/;
1546var INVALID_FID = '';
1547/**
1548 * Generates a new FID using random values from Web Crypto API.
1549 * Returns an empty string if FID generation fails for any reason.
1550 */
1551function generateFid() {
1552    try {
1553        // A valid FID has exactly 22 base64 characters, which is 132 bits, or 16.5
1554        // bytes. our implementation generates a 17 byte array instead.
1555        var fidByteArray = new Uint8Array(17);
1556        var crypto_1 = self.crypto || self.msCrypto;
1557        crypto_1.getRandomValues(fidByteArray);
1558        // Replace the first 4 random bits with the constant FID header of 0b0111.
1559        fidByteArray[0] = 112 + (fidByteArray[0] % 16);
1560        var fid = encode(fidByteArray);
1561        return VALID_FID_PATTERN.test(fid) ? fid : INVALID_FID;
1562    }
1563    catch (_a) {
1564        // FID generation errored
1565        return INVALID_FID;
1566    }
1567}
1568/** Converts a FID Uint8Array to a base64 string representation. */
1569function encode(fidByteArray) {
1570    var b64String = bufferToBase64UrlSafe(fidByteArray);
1571    // Remove the 23rd character that was added because of the extra 4 bits at the
1572    // end of our 17 byte array, and the '=' padding.
1573    return b64String.substr(0, 22);
1574}
1575
1576/**
1577 * @license
1578 * Copyright 2019 Google LLC
1579 *
1580 * Licensed under the Apache License, Version 2.0 (the "License");
1581 * you may not use this file except in compliance with the License.
1582 * You may obtain a copy of the License at
1583 *
1584 *   http://www.apache.org/licenses/LICENSE-2.0
1585 *
1586 * Unless required by applicable law or agreed to in writing, softw
1586are
1587 * distributed under the License is distributed on an "AS IS" BASIS,
1588 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1589 * See the License for the specific language governing permissions and
1590 * limitations under the License.
1591 */
1592/** Returns a string key that can be used to identify the app. */
1593function getKey(appConfig) {
1594    return appConfig.appName + "!" + appConfig.appId;
1595}
1596
1597/**
1598 * @license
1599 * Copyright 2019 Google LLC
1600 *
1601 * Licensed under the Apache License, Version 2.0 (the "License");
1602 * you may not use this file except in compliance with the License.
1603 * You may obtain a copy of the License at
1604 *
1605 *   http://www.apache.org/licenses/LICENSE-2.0
1606 *
1607 * Unless required by applicable law or agreed to in writing, software
1608 * distributed under the License is distributed on an "AS IS" BASIS,
1609 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1610 * See the License for the specific language governing permissions and
1611 * limitations under the License.
1612 */
1613var fidChangeCallbacks = new Map();
1614/**
1615 * Calls the onIdChange callbacks with the new FID value, and broadcasts the
1616 * change to other tabs.
1617 */
1618function fidChanged(appConfig, fid) {
1619    var key = getKey(appConfig);
1620    callFidChangeCallbacks(key, fid);
1621    broadcastFidChange(key, fid);
1622}
1623function addCallback(appConfig, callback) {
1624    // Open the broadcast channel if it's not already open,
1625    // to be able to listen to change events from other tabs.
1626    getBroadcastChannel();
1627    var key = getKey(appConfig);
1628    var callbackSet = fidChangeCallbacks.get(key);
1629    if (!callbackSet) {
1630        callbackSet = new Set();
1631        fidChangeCallbacks.set(key, callbackSet);
1632    }
1633    callbackSet.add(callback);
1634}
1635function removeCallback(appConfig, callback) {
1636    var key = getKey(appConfig);
1637    var callbackSet = fidChangeCallbacks.get(key);
1638    if (!callbackSet) {
1639        return;
1640    }
1641    callbackSet.delete(callback);
1642    if (callbackSet.size === 0) {
1643        fidChangeCallbacks.delete(key);
1644    }
1645    // Close broadcast channel if there are no more callbacks.
1646    closeBroadcastChannel();
1647}
1648function callFidChangeCallbacks(key, fid) {
1649    var e_1, _a;
1650    var callbacks = fidChangeCallbacks.get(key);
1651    if (!callbacks) {
1652        return;
1653    }
1654    try {
1655        for (var callbacks_1 = (0,tslib__WEBPACK_IMPORTED_MODULE_4__.__values)(callbacks), callbacks_1_1 = callbacks_1.next(); !callbacks_1_1.done; callbacks_1_1 = callbacks_1.next()) {
1656            var callback = callbacks_1_1.value;
1657            callback(fid);
1658        }
1659    }
1660    catch (e_1_1) { e_1 = { error: e_1_1 }; }
1661    finally {
1662        try {
1663            if (callbacks_1_1 && !callbacks_1_1.done && (_a = callbacks_1.return)) _a.call(callbacks_1);
1664        }
1665        finally { if (e_1) throw e_1.error; }
1666    }
1667}
1668function broadcastFidChange(key, fid) {
1669    var channel = getBroadcastChannel();
1670    if (channel) {
1671        channel.postMessage({ key: key, fid: fid });
1672    }
1673    closeBroadcastChannel();
1674}
1675var broadcastChannel = null;
1676/** Opens and returns a BroadcastChannel if it is supported by the browser. */
1677function getBroadcastChannel() {
1678    if (!broadcastChannel && 'BroadcastChannel' in self) {
1679        broadcastChannel = new BroadcastChannel('[Firebase] FID Change');
1680        broadcastChannel.onmessage = function (e) {
1681            callFidChangeCallbacks(e.data.key, e.data.fid);
1682        };
1683    }
1684    return broadcastChannel;
1685}
1686function closeBroadcastChannel() {
1687    if (fidChangeCallbacks.size === 0 && broadcastChannel) {
1688        broadcastChannel.close();
1689        broadcastChannel = null;
1690    }
1691}
1692
1693/**
1694 * @license
1695 * Copyright 2019 Google LLC
1696 *
1697 * Licensed under the Apache License, Version 2.0 (the "License");
1698 * you may not use this file except in compliance with the License.
1699 * You may obtain a copy of the License at
1700 *
1701 *   http://www.apache.org/licenses/LICENSE-2.0
1702 *
1703 * Unless required by applicable law or agreed to in writing, software
1704 * distributed under the License is distributed on an "AS IS" BASIS,
1705 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1706 * See the License for the specific language governing permissions and
1707 * limitations under the License.
1708 */
1709var DATABASE_NAME = 'firebase-installations-database';
1710var DATABASE_VERSION = 1;
1711var OBJECT_STORE_NAME = 'firebase-installations-store';
1712var dbPromise = null;
1713function getDbPromise() {
1714    if (!dbPromise) {
1715        dbPromise = (0,idb__WEBPACK_IMPORTED_MODULE_3__.openDb)(DATABASE_NAME, DATABASE_VERSION, function (upgradeDB) {
1716            // We don't use 'break' in this switch statement, the fall-through
1717            // behavior is what we want, because if there are multiple versions between
1718            // the old version and the current version, we want ALL the migrations
1719            // that correspond to those versions to run, not only the last one.
1720            // eslint-disable-next-line default-case
1721            switch (upgradeDB.oldVersion) {
1722                case 0:
1723                    upgradeDB.createObjectStore(OBJECT_STORE_NAME);
1724            }
1725        });
1726    }
1727    return dbPromise;
1728}
1729/** Assigns or overwrites the record for the given key with the given value. */
1730function set(appConfig, value) {
1731    return (0,tslib__WEBPACK_IMPORTED_MODULE_4__.__awaiter)(this, void 0, void 0, function () {
1732        var key, db, tx, objectStore, oldValue;
1733        return (0,tslib__WEBPACK_IMPORTED_MODULE_4__.__generator)(this, function (_a) {
1734            switch (_a.label) {
1735                case 0:
1736                    key = getKey(appConfig);
1737                    return [4 /*yield*/, getDbPromise()];
1738                case 1:
1739                    db = _a.sent();
1740                    tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');
1741                    objectStore = tx.objectStore(OBJECT_STORE_NAME);
1742                    return [4 /*yield*/, objectStore.get(key)];
1743                case 2:
1744                    oldValue = _a.sent();
1745                    return [4 /*yield*/, objectStore.put(value, key)];
1746                case 3:
1747                    _a.sent();
1748                    return [4 /*yield*/, tx.complete];
1749                case 4:
1750                    _a.sent();
1751                    if (!oldValue || oldValue.fid !== value.fid) {
1752                        fidChanged(appConfig, value.fid);
1753                    }
1754                    return [2 /*return*/, value];
1755            }
1756        });
1757    });
1758}
1759/** Removes record(s) from the objectStore that match the given key. */
1760function remove(appConfig) {
1761    return (0,tslib__WEBPACK_IMPORTED_MODULE_4__.__awaiter)(this, void 0, void 0, function () {
1762        var key, db, tx;
1763        return (0,tslib__WEBPACK_IMPORTED_MODULE_4__.__generator)(this, function (_a) {
1764            switch (_a.label) {
1765                case 0:
1766                    key = getKey(appConfig);
1767                    return [4 /*yield*/, getDbPromise()];
1768                case 1:
1769                    db = _a.sent();
1770                    tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');
1771                    return [4 /*yield*/, tx.objectStore(OBJECT_STORE_NAME).delete(key)];
1772                case 2:
1773                    _a.sent();
1774                    return [4 /*yield*/, tx.complete];
1775                case 3:
1776                    _a.sent();
1777                    return [2 /*return*/];
1778            }
1779        });
1780    });
1781}
1782/**
1783 * Atomically updates a record with the result of updateFn, which gets
1784 * called with the current value. If newValue is undefined, the record is
1785 * deleted instead.
1786 * @return Updated value
1787 */
1788function update(appConfig, updateFn) {
1789    return (0,tslib__WEBPACK_IMPORTED_MODULE_4__.__awaiter)(this, void 0, void 0, function () {
1790        var key, db, tx, store, oldValue, newValue;
1791        return (0,tslib__WEBPACK_IMPORTED_MODULE_4__.__generator)(this, function (_a) {
1792            switch (_a.label) {
1793                case 0:
1794                    key = getKey(appConfig);
1795                    return [4 /*yield*/, getDbPromise()];
1796                case 1:
1797                    db = _a.sent();
1798                    tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');
1799                    store = tx.objectStore(OBJECT_STORE_NAME);
1800                    return [4 /*yield*/, store.get(key)];
1801                case 2:
1802                    oldValue = _a.sent();
1803                    newValue = updateFn(oldValue);
1804                    if (!(newValue === undefined)) return [3 /*break*/, 4];
1805                    return [4 /*yield*/, store.delete(key)];
1806                case 3:
1807                    _a.sent();
1808                    return [3 /*break*/, 6];
1809                case 4: return [4 /*yield*/, store.put(newValue, key)];
1810                case 5:
1811                    _a.sent();
1812                    _a.label = 6;
1813                case 6: return [4 /*yield*/, tx.complete];
1814                case 7:
1815                    _a.sent();
1816                    if (newValue && (!oldValue || oldValue.fid !== newValue.fid)) {
1817                        fidChanged(appConfig, newValue.fid);
1818                    }
1819                    return [2 /*return*/, newValue];
1820            }
1821        });
1822    });
1823}
1824
1825/**
1826 * @license
1827 * Copyright 2019 Google LLC
1828 *
1829 * Licensed under the Apache License, Version 2.0 (the "License");
1830 * you may not use this file except in compliance with the License.
1831 * You may obtain a copy of the License at
1832 *
1833 *   http://www.apache.org/licenses/LICENSE-2.0
1834 *
1835 * Unless required by applicable law or agreed to in writing, software
1836 * distributed under the License is distributed on an "AS IS" BASIS,
1837 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1838 * See the License for the specific language governing permissions and
1839 * limitations under the License.
1840 */
1841/**
1842 * Updates and returns the InstallationEntry from the database.
1843 * Also triggers a registration request if it is necessary and possible.
1844 */
1845function getInstallationEntry(appConfig) {
1846    return (0,tslib__WEBPACK_IMPORTED_MODULE_4__.__awaiter)(this, void 0, void 0, function () {
1847        var registrationPromise, installationEntry;
1848        var _a;
1849        return (0,tslib__WEBPACK_IMPORTED_MODULE_4__.__generator)(this, function (_b) {
1850            switch (_b.label) {
1851                case 0: return [4 /*yield*/, update(appConfig, function (oldEntry) {
1852                        var installationEntry = updateOrCreateInstallationEntry(oldEntry);
1853                        var entryWithPromise = triggerRegistrationIfNecessary(appConfig, installationEntry);
1854                        registrationPromise = entryWithPromise.registrationPromise;
1855                        return entryWithPromise.installationEntry;
1856                    })];
1857                case 1:
1858                    installationEntry = _b.sent();
1859                    if (!(installationEntry.fid === INVALID_FID)) return [3 /*break*/, 3];
1860                    _a = {};
1861                    return [4 /*yield*/, registrationPromise];
1862                case 2: 
1863                // FID generation failed. Waiting for the FID from the server.
1864                return [2 /*return*/, (_a.installationEntry = _b.sent(), _a)];
1865                case 3: return [2 /*return*/, {
1866                        installationEntry: installationEntry,
1867                        registrationPromise: registrationPromise
1868                    }];
1869            }
1870        });
1871    });
1872}
1873/**
1874 * Creates a new Installation Entry if one does not exist.
1875 * Also clears timed out pending requests.
1876 */
1877function updateOrCreateInstallationEntry(oldEntry) {
1878    var entry = oldEntry || {
1879        fid: generateFid(),
1880        registrationStatus: 0 /* NOT_STARTED */
1881    };
1882    return clearTimedOutRequest(entry);
1883}
1884/**
1885 * If the Firebase Installation is not registered yet, this will trigger the
1886 * registration and return an InProgressInstallationEntry.
1887 *
1888 * If registrationPromise does not exist, the installationEntry is guaranteed
1889 * to be registered.
1890 */
1891function triggerRegistrationIfNecessary(appConfig, installationEntry) {
1892    if (installationEntry.registrationStatus === 0 /* NOT_STARTED */) {
1893        if (!navigator.onLine) {
1894            // Registration required but app is offline.
1895            var registrationPromiseWithError = Promise.reject(ERROR_FACTORY.create("app-offline" /* APP_OFFLINE */));
1896            return {
1897                installationEntry: installationEntry,
1898                registrationPromise: registrationPromiseWithError
1899            };
1900        }
1901        // Try registering. Change status to IN_PROGRESS.
1902        var inProgressEntry = {
1903            fid: installationEntry.fid,
1904            registrationStatus: 1 /* IN_PROGRESS */,
1905            registrationTime: Date.now()
1906        };
1907        var registrationPromise = registerInstallation(appConfig, inProgressEntry);
1908        return { installationEntry: inProgressEntry, registrationPromise: registrationPromise };
1909    }
1910    else if (installationEntry.registrationStatus === 1 /* IN_PROGRESS */) {
1911        return {
1912            installationEntry: installationEntry,
1913            registrationPromise: waitUntilFidRegistration(appConfig)
1914        };
1915    }
1916    else {
1917        return { installationEntry: installationEntry };
1918    }
1919}
1920/** This will be executed only once for each new Firebase Installation. */
1921function registerInstallation(appConfig, installationEntry) {
1922    return (0,tslib__WEBPACK_IMPORTED_MODULE_4__.__awaiter)(this, void 0, void 0, function () {
1923        var registeredInstallationEntry, e_1;
1924        return (0,tslib__WEBPACK_IMPORTED_MODULE_4__.__generator)(this, function (_a) {
1925            switch (_a.label) {
1926                case 0:
1927                    _a.trys.push([0, 2, , 7]);
1928                    return [4 /*yield*/, createInstallationRequest(appConfig, installationEntry)];
1929                case 1:
1930                    registeredInstallationEntry = _a.sent();
1931                    return [2 /*return*/, set(appConfig, registeredInstallationEntry)];
1932                case 2:
1933                    e_1 = _a.sent();
1934                    if (!(isServerError(e_1) && e_1.customData.serverCode === 409)) return [3 /*break*/, 4];
1935                    // Server returned a "FID can not be used" error.
1936                    // Generate a new ID next time.
1937                    return [4 /*yield*/, remove(appConfig)];
1938                case 3:
1939                    // Server returned a "FID can not be used" error.
1940                    // Generate a new ID next time.
1941                    _a.sent();
1942                    return [3 /*break*/, 6];
1943                case 4: 
1944                // Registration failed. Set FID as not registered.
1945                return [4 /*yield*/, set(appConfig, {
1946                        fid: installationEntry.fid,
1947                        registrationStatus: 0 /* NOT_STARTED */
1948                    })];
1949                case 5:
1950                    // Registration failed. Set FID as not registered.
1951                    _a.sent();
1952                    _a.label = 6;
1953                case 6: throw e_1;
1954                case 7: return [2 /*return*/];
1955            }
1956        });
1957    });
1958}
1959/** Call if FID registration is pending in another request. */
1960function waitUntilFidRegistration(appConfig) {
1961    return (0,tslib__WEBPACK_IMPORTED_MODULE_4__.__awaiter)(this, void 0, void 0, function () {
1962        var entry, _a, installationEntry, registrationPromise;
1963        return (0,tslib__WEBPACK_IMPORTED_MODULE_4__.__generator)(this, function (_b) {
1964            switch (_b.label) {
1965                case 0: return [4 /*yield*/, updateInstallationRequest(appConfig)];
1966                case 1:
1967                    entry = _b.sent();
1968                    _b.label = 2;
1969                case 2:
1970                    if (!(entry.registrationStatus === 1 /* IN_PROGRESS */)) return [3 /*break*/, 5];
1971                    // createInstallation request still in progress.
1972                    return [4 /*yield*/, sleep(100)];
1973                case 3:
1974                    // createInstallation request still in progress.
1975                    _b.sent();
1976                    return [4 /*yield*/, updateInstallationRequest(appConfig)];
1977                case 4:
1978                    entry = _b.sent();
1979                    return [3 /*break*/, 2];
1980                case 5:
1981                    if (!(entry.registrationStatus === 0 /* NOT_STARTED */)) return [3 /*break*/, 7];
1982                    return [4 /*yield*/, getInstallationEntry(appConfig)];
1983                case 6:
1984                    _a = _b.sent(), installationEntry = _a.installationEntry, registrationPromise = _a.registrationPromise;
1985                    if (registrationPromise) {
1986                        return [2 /*return*/, registrationPromise];
1987                    }
1988                    else {
1989                        // if there is no registrationPromise, entry is registered.
1990                        return [2 /*return*/, installationEntry];
1991                    }
1992                case 7: return [2 /*return*/, entry];
1993            }
1994        });
1995    });
1996}
1997/**
1998 * Called only if there is a CreateInstallation request in progress.
1999 *
2000 * Updates the InstallationEntry in the DB based on the status of the
2001 * CreateInstallation request.
2002 *
2003 * Returns the updated InstallationEntry.
2004 */
2005function updateInstallationRequest(appConfig) {
2006    return update(appConfig, function (oldEntry) {
2007        if (!oldEntry) {
2008            throw ERROR_FACTORY.create("installation-not-found" /* INSTALLATION_NOT_FOUND */);
2009        }
2010        return clearTimedOutRequest(oldEntry);
2011    });
2012}
2013function clearTimedOutRequest(entry) {
2014    if (hasInstallationRequestTimedOut(entry)) {
2015        return {
2016            fid: entry.fid,
2017            registrationStatus: 0 /* NOT_STARTED */
2018        };
2019    }
2020    return entry;
2021}
2022function hasInstallationRequestTimedOut(installationEntry) {
2023    return (installationEntry.registrationStatus === 1 /* IN_PROGRESS */ &&
2024        installationEntry.registrationTime + PENDING_TIMEOUT_MS < Date.now());
2025}
2026
2027/**
2028 * @license
2029 * Copyright 2019 Google LLC
2030 *
2031 * Licensed under the Apache License, Version 2.0 (the "License");
2032 * you may not use this file except in compliance with the License.
2033 * You may obtain a copy of the License at
2034 *
2035 *   http://www.apache.org/licenses/LICENSE-2.0
2036 *
2037 * Unless required by applicable law or agreed to in writing, software
2038 * distributed under the License is distributed on an "AS IS" BASIS,
2039 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2040 * See the License for the specific language governing permissions and
2041 * limitations under the License.
2042 */
2043function generateAuthTokenRequest(_a, installationEntry) {
2044    var appConfig = _a.appConfig, platformLoggerProvider = _a.platformLoggerProvider;
2045    return (0,tslib__WEBPACK_IMPORTED_MODULE_4__.__awaiter)(this, void 0, void 0, function () {
2046        var endpoint, headers, platformLogger, body, request, response, responseValue, completedAuthToken;
2047        return (0,tslib__WEBPACK_IMPORTED_MODULE_4__.__generator)(this, function (_b) {
2048            switch (_b.label) {
2049                case 0:
2050                    endpoint = getGenerateAuthTokenEndpoint(appConfig, installationEntry);
2051                    headers = getHeadersWithAuth(appConfig, installationEntry);
2052                    platformLogger = platformLoggerProvider.getImmediate({
2053                        optional: true
2054                    });
2055                    if (platformLogger) {
2056                        headers.append('x-firebase-client', platformLogger.getPlatformInfoString());
2057                    }
2058                    body = {
2059                        installation: {
2060                            sdkVersion: PACKAGE_VERSION
2061                        }
2062                    };
2063                    request = {
2064                        method: 'POST',
2065                        headers: headers,
2066                        body: JSON.stringify(body)
2067                    };
2068                    return [4 /*yield*/, retryIfServerError(function () { return fetch(endpoint, request); })];
2069                case 1:
2070                    response = _b.sent();
2071                    if (!response.ok) return [3 /*break*/, 3];
2072                    return [4 /*yield*/, response.json()];
2073                case 2:
2074                    responseValue = _b.sent();
2075                    completedAuthToken = extractAuthTokenInfoFromRe
2075sponse(responseValue);
2076                    return [2 /*return*/, completedAuthToken];
2077                case 3: return [4 /*yield*/, getErrorFromResponse('Generate Auth Token', response)];
2078                case 4: throw _b.sent();
2079            }
2080        });
2081    });
2082}
2083function getGenerateAuthTokenEndpoint(appConfig, _a) {
2084    var fid = _a.fid;
2085    return getInstallationsEndpoint(appConfig) + "/" + fid + "/authTokens:generate";
2086}
2087
2088/**
2089 * @license
2090 * Copyright 2019 Google LLC
2091 *
2092 * Licensed under the Apache License, Version 2.0 (the "License");
2093 * you may not use this file except in compliance with the License.
2094 * You may obtain a copy of the License at
2095 *
2096 *   http://www.apache.org/licenses/LICENSE-2.0
2097 *
2098 * Unless required by applicable law or agreed to in writing, software
2099 * distributed under the License is distributed on an "AS IS" BASIS,
2100 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2101 * See the License for the specific language governing permissions and
2102 * limitations under the License.
2103 */
2104/**
2105 * Returns a valid authentication token for the installation. Generates a new
2106 * token if one doesn't exist, is expired or about to expire.
2107 *
2108 * Should only be called if the Firebase Installation is registered.
2109 */
2110function refreshAuthToken(dependencies, forceRefresh) {
2111    if (forceRefresh === void 0) { forceRefresh = false; }
2112    return (0,tslib__WEBPACK_IMPORTED_MODULE_4__.__awaiter)(this, void 0, void 0, function () {
2113        var tokenPromise, entry, authToken, _a;
2114        return (0,tslib__WEBPACK_IMPORTED_MODULE_4__.__generator)(this, function (_b) {
2115            switch (_b.label) {
2116                case 0: return [4 /*yield*/, update(dependencies.appConfig, function (oldEntry) {
2117                        if (!isEntryRegistered(oldEntry)) {
2118                            throw ERROR_FACTORY.create("not-registered" /* NOT_REGISTERED */);
2119                        }
2120                        var oldAuthToken = oldEntry.authToken;
2121                        if (!forceRefresh && isAuthTokenValid(oldAuthToken)) {
2122                            // There is a valid token in the DB.
2123                            return oldEntry;
2124                        }
2125                        else if (oldAuthToken.requestStatus === 1 /* IN_PROGRESS */) {
2126                            // There already is a token request in progress.
2127                            tokenPromise = waitUntilAuthTokenRequest(dependencies, forceRefresh);
2128                            return oldEntry;
2129                        }
2130                        else {
2131                            // No token or token expired.
2132                            if (!navigator.onLine) {
2133                                throw ERROR_FACTORY.create("app-offline" /* APP_OFFLINE */);
2134                            }
2135                            var inProgressEntry = makeAuthTokenRequestInProgressEntry(oldEntry);
2136                            tokenPromise = fetchAuthTokenFromServer(dependencies, inProgressEntry);
2137                            return inProgressEntry;
2138                        }
2139                    })];
2140                case 1:
2141                    entry = _b.sent();
2142                    if (!tokenPromise) return [3 /*break*/, 3];
2143                    return [4 /*yield*/, tokenPromise];
2144                case 2:
2145                    _a = _b.sent();
2146                    return [3 /*break*/, 4];
2147                case 3:
2148                    _a = entry.authToken;
2149                    _b.label = 4;
2150                case 4:
2151                    authToken = _a;
2152                    return [2 /*return*/, authToken];
2153            }
2154        });
2155    });
2156}
2157/**
2158 * Call only if FID is registered and Auth Token request is in progress.
2159 *
2160 * Waits until the current pending request finishes. If the request times out,
2161 * tries once in this thread as well.
2162 */
2163function waitUntilAuthTokenRequest(dependencies, forceRefresh) {
2164    return (0,tslib__WEBPACK_IMPORTED_MODULE_4__.__awaiter)(this, void 0, void 0, function () {
2165        var entry, authToken;
2166        return (0,tslib__WEBPACK_IMPORTED_MODULE_4__.__generator)(this, function (_a) {
2167            switch (_a.label) {
2168                case 0: return [4 /*yield*/, updateAuthTokenRequest(dependencies.appConfig)];
2169                case 1:
2170                    entry = _a.sent();
2171                    _a.label = 2;
2172                case 2:
2173                    if (!(entry.authToken.requestStatus === 1 /* IN_PROGRESS */)) return [3 /*break*/, 5];
2174                    // generateAuthToken still in progress.
2175                    return [4 /*yield*/, sleep(100)];
2176                case 3:
2177                    // generateAuthToken still in progress.
2178                    _a.sent();
2179                    return [4 /*yield*/, updateAuthTokenRequest(dependencies.appConfig)];
2180                case 4:
2181                    entry = _a.sent();
2182                    return [3 /*break*/, 2];
2183                case 5:
2184                    authToken = entry.authToken;
2185                    if (authToken.requestStatus === 0 /* NOT_STARTED */) {
2186                        // The request timed out or failed in a different call. Try again.
2187                        return [2 /*return*/, refreshAuthToken(dependencies, forceRefresh)];
2188                    }
2189                    else {
2190                        return [2 /*return*/, authToken];
2191                    }
2192            }
2193        });
2194    });
2195}
2196/**
2197 * Called only if there is a GenerateAuthToken request in progress.
2198 *
2199 * Updates the InstallationEntry in the DB based on the status of the
2200 * GenerateAuthToken request.
2201 *
2202 * Returns the updated InstallationEntry.
2203 */
2204function updateAuthTokenRequest(appConfig) {
2205    return update(appConfig, function (oldEntry) {
2206        if (!isEntryRegistered(oldEntry)) {
2207            throw ERROR_FACTORY.create("not-registered" /* NOT_REGISTERED */);
2208        }
2209        var oldAuthToken = oldEntry.authToken;
2210        if (hasAuthTokenRequestTimedOut(oldAuthToken)) {
2211            return (0,tslib__WEBPACK_IMPORTED_MODULE_4__.__assign)((0,tslib__WEBPACK_IMPORTED_MODULE_4__.__assign)({}, oldEntry), { authToken: { requestStatus: 0 /* NOT_STARTED */ } });
2212        }
2213        return oldEntry;
2214    });
2215}
2216function fetchAuthTokenFromServer(dependencies, installationEntry) {
2217    return (0,tslib__WEBPACK_IMPORTED_MODULE_4__.__awaiter)(this, void 0, void 0, function () {
2218        var authToken, updatedInstallationEntry, e_1, updatedInstallationEntry;
2219        return (0,tslib__WEBPACK_IMPORTED_MODULE_4__.__generator)(this, function (_a) {
2220            switch (_a.label) {
2221                case 0:
2222                    _a.trys.push([0, 3, , 8]);
2223                    return [4 /*yield*/, generateAuthTokenRequest(dependencies, installationEntry)];
2224                case 1:
2225                    authToken = _a.sent();
2226                    updatedInstallationEntry = (0,tslib__WEBPACK_IMPORTED_MODULE_4__.__assign)((0,tslib__WEBPACK_IMPORTED_MODULE_4__.__assign)({}, installationEntry), { authToken: authToken });
2227                    return [4 /*yield*/, set(dependencies.appConfig, updatedInstallationEntry)];
2228                case 2:
2229                    _a.sent();
2230                    return [2 /*return*/, authToken];
2231                case 3:
2232                    e_1 = _a.sent();
2233                    if (!(isServerError(e_1) &&
2234                        (e_1.customData.serverCode === 401 || e_1.customData.serverCode === 404))) return [3 /*break*/, 5];
2235                    // Server returned a "FID not found" or a "Invalid authentication" error.
2236                    // Generate a new ID next time.
2237                    return [4 /*yield*/, remove(dependencies.appConfig)];
2238                case 4:
2239                    // Server returned a "FID not found" or a "Invalid authentication" error.
2240                    // Generate a new ID next time.
2241                    _a.sent();
2242                    return [3 /*break*/, 7];
2243                case 5:
2244                    updatedInstallationEntry = (0,tslib__WEBPACK_IMPORTED_MODULE_4__.__assign)((0,tslib__WEBPACK_IMPORTED_MODULE_4__.__assign)({}, installationEntry), { authToken: { requestStatus: 0 /* NOT_STARTED */ } });
2245                    return [4 /*yield*/, set(dependencies.appConfig, updatedInstallationEntry)];
2246                case 6:
2247                    _a.sent();
2248                    _a.label = 7;
2249                case 7: throw e_1;
2250                case 8: return [2 /*return*/];
2251            }
2252        });
2253    });
2254}
2255function isEntryRegistered(installationEntry) {
2256    return (installationEntry !== undefined &&
2257        installationEntry.registrationStatus === 2 /* COMPLETED */);
2258}
2259function isAuthTokenValid(authToken) {
2260    return (authToken.requestStatus === 2 /* COMPLETED */ &&
2261        !isAuthTokenExpired(authToken));
2262}
2263function isAuthTokenExpired(authToken) {
2264    var now = Date.now();
2265    return (now < authToken.creationTime ||
2266        authToken.creationTime + authToken.expiresIn < now + TOKEN_EXPIRATION_BUFFER);
2267}
2268/** Returns an updated InstallationEntry with an InProgressAuthToken. */
2269function makeAuthTokenRequestInProgressEntry(oldEntry) {
2270    var inProgressAuthToken = {
2271        requestStatus: 1 /* IN_PROGRESS */,
2272        requestTime: Date.now()
2273    };
2274    return (0,tslib__WEBPACK_IMPORTED_MODULE_4__.__assign)((0,tslib__WEBPACK_IMPORTED_MODULE_4__.__assign)({}, oldEntry), { authToken: inProgressAuthToken });
2275}
2276function hasAuthTokenRequestTimedOut(authToken) {
2277    return (authToken.requestStatus === 1 /* IN_PROGRESS */ &&
2278        authToken.requestTime + PENDING_TIMEOUT_MS < Date.now());
2279}
2280
2281/**
2282 * @license
2283 * Copyright 2019 Google LLC
2284 *
2285 * Licensed under the Apache License, Version 2.0 (the "License");
2286 * you may not use this file except in compliance with the License.
2287 * You may obtain a copy of the License at
2288 *
2289 *   http://www.apache.org/licenses/LICENSE-2.0
2290 *
2291 * Unless required by applicable law or agreed to in writing, software
2292 * distributed under the License is distributed on an "AS IS" BASIS,
2293 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2294 * See the License for the specific language governing permissions and
2295 * limitations under the License.
2296 */
2297function getId(dependencies) {
2298    return (0,tslib__WEBPACK_IMPORTED_MODULE_4__.__awaiter)(this, void 0, void 0, function () {
2299        var _a, installationEntry, registrationPromise;
2300        return (0,tslib__WEBPACK_IMPORTED_MODULE_4__.__generator)(this, function (_b) {
2301            switch (_b.label) {
2302                case 0: return [4 /*yield*/, getInstallationEntry(dependencies.appConfig)];
2303                case 1:
2304                    _a = _b.sent(), installationEntry = _a.installationEntry, registrationPromise = _a.registrationPromise;
2305                    if (registrationPromise) {
2306                        registrationPromise.catch(console.error);
2307                    }
2308                    else {
2309                        // If the installation is already registered, update the authentication
2310                        // token if needed.
2311                        refreshAuthToken(dependencies).catch(console.error);
2312                    }
2313                    return [2 /*return*/, installationEntry.fid];
2314            }
2315        });
2316    });
2317}
2318
2319/**
2320 * @license
2321 * Copyright 2019 Google LLC
2322 *
2323 * Licensed under the Apache License, Version 2.0 (the "License");
2324 * you may not use this file except in compliance with the License.
2325 * You may obtain a copy of the License at
2326 *
2327 *   http://www.apache.org/licenses/LICENSE-2.0
2328 *
2329 * Unless required by applicable law or agreed to in writing, software
2330 * distributed under the License is distributed on an "AS IS" BASIS,
2331 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2332 * See the License for the specific language governing permissions and
2333 * limitations under the License.
2334 */
2335function getToken(dependencies, forceRefresh) {
2336    if (forceRefresh === void 0) { forceRefresh = false; }
2337    return (0,tslib__WEBPACK_IMPORTED_MODULE_4__.__awaiter)(this, void 0, void 0, function () {
2338        var authToken;
2339        return (0,tslib__WEBPACK_IMPORTED_MODULE_4__.__generator)(this, function (_a) {
2340            switch (_a.label) {
2341                case 0: return [4 /*yield*/, completeInstallationRegistration(dependencies.appConfig)];
2342                case 1:
2343                    _a.sent();
2344                    return [4 /*yield*/, refreshAuthToken(dependencies, forceRefresh)];
2345                case 2:
2346                    authToken = _a.sent();
2347                    return [2 /*return*/, authToken.token];
2348            }
2349        });
2350    });
2351}
2352function completeInstallationRegistration(appConfig) {
2353    return (0,tslib__WEBPACK_IMPORTED_MODULE_4__.__awaiter)(this, void 0, void 0, function () {
2354        var registrationPromise;
2355        return (0,tslib__WEBPACK_IMPORTED_MODULE_4__.__generator)(this, function (_a) {
2356            switch (_a.label) {
2357                case 0: return [4 /*yield*/, getInstallationEntry(appConfig)];
2358                case 1:
2359                    registrationPromise = (_a.sent()).registrationPromise;
2360                    if (!registrationPromise) return [3 /*break*/, 3];
2361                    // A createInstallation request is in progress. Wait until it finishes.
2362                    return [4 /*yield*/, registrationPromise];
2363                case 2:
2364                    // A createInstallation request is in progress. Wait until it finishes.
2365                    _a.sent();
2366                    _a.label = 3;
2367                case 3: return [2 /*return*/];
2368            }
2369        });
2370    });
2371}
2372
2373/**
2374 * @license
2375 * Copyright 2019 Google LLC
2376 *
2377 * Licensed under the Apache License, Version 2.0 (the "License");
2378 * you may not use this file except in compliance with the License.
2379 * You may obtain a copy of the License at
2380 *
2381 *   http://www.apache.org/licenses/LICENSE-2.0
2382 *
2383 * Unless required by applicable law or agreed to in writing, softw
2383are
2384 * distributed under the License is distributed on an "AS IS" BASIS,
2385 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2386 * See the License for the specific language governing permissions and
2387 * limitations under the License.
2388 */
2389function deleteInstallationRequest(appConfig, installationEntry) {
2390    return (0,tslib__WEBPACK_IMPORTED_MODULE_4__.__awaiter)(this, void 0, void 0, function () {
2391        var endpoint, headers, request, response;
2392        return (0,tslib__WEBPACK_IMPORTED_MODULE_4__.__generator)(this, function (_a) {
2393            switch (_a.label) {
2394                case 0:
2395                    endpoint = getDeleteEndpoint(appConfig, installationEntry);
2396                    headers = getHeadersWithAuth(appConfig, installationEntry);
2397                    request = {
2398                        method: 'DELETE',
2399                        headers: headers
2400                    };
2401                    return [4 /*yield*/, retryIfServerError(function () { return fetch(endpoint, request); })];
2402                case 1:
2403                    response = _a.sent();
2404                    if (!!response.ok) return [3 /*break*/, 3];
2405                    return [4 /*yield*/, getErrorFromResponse('Delete Installation', response)];
2406                case 2: throw _a.sent();
2407                case 3: return [2 /*return*/];
2408            }
2409        });
2410    });
2411}
2412function getDeleteEndpoint(appConfig, _a) {
2413    var fid = _a.fid;
2414    return getInstallationsEndpoint(appConfig) + "/" + fid;
2415}
2416
2417/**
2418 * @license
2419 * Copyright 2019 Google LLC
2420 *
2421 * Licensed under the Apache License, Version 2.0 (the "License");
2422 * you may not use this file except in compliance with the License.
2423 * You may obtain a copy of the License at
2424 *
2425 *   http://www.apache.org/licenses/LICENSE-2.0
2426 *
2427 * Unless required by applicable law or agreed to in writing, software
2428 * distributed under the License is distributed on an "AS IS" BASIS,
2429 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2430 * See the License for the specific language governing permissions and
2431 * limitations under the License.
2432 */
2433function deleteInstallation(dependencies) {
2434    return (0,tslib__WEBPACK_IMPORTED_MODULE_4__.__awaiter)(this, void 0, void 0, function () {
2435        var appConfig, entry;
2436        return (0,tslib__WEBPACK_IMPORTED_MODULE_4__.__generator)(this, function (_a) {
2437            switch (_a.label) {
2438                case 0:
2439                    appConfig = dependencies.appConfig;
2440                    return [4 /*yield*/, update(appConfig, function (oldEntry) {
2441                            if (oldEntry && oldEntry.registrationStatus === 0 /* NOT_STARTED */) {
2442                                // Delete the unregistered entry without sending a deleteInstallation request.
2443                                return undefined;
2444                            }
2445                            return oldEntry;
2446                        })];
2447                case 1:
2448                    entry = _a.sent();
2449                    if (!entry) return [3 /*break*/, 6];
2450                    if (!(entry.registrationStatus === 1 /* IN_PROGRESS */)) return [3 /*break*/, 2];
2451                    // Can't delete while trying to register.
2452                    throw ERROR_FACTORY.create("delete-pending-registration" /* DELETE_PENDING_REGISTRATION */);
2453                case 2:
2454                    if (!(entry.registrationStatus === 2 /* COMPLETED */)) return [3 /*break*/, 6];
2455                    if (!!navigator.onLine) return [3 /*break*/, 3];
2456                    throw ERROR_FACTORY.create("app-offline" /* APP_OFFLINE */);
2457                case 3: return [4 /*yield*/, deleteInstallationRequest(appConfig, entry)];
2458                case 4:
2459                    _a.sent();
2460                    return [4 /*yield*/, remove(appConfig)];
2461                case 5:
2462                    _a.sent();
2463                    _a.label = 6;
2464                case 6: return [2 /*return*/];
2465            }
2466        });
2467    });
2468}
2469
2470/**
2471 * @license
2472 * Copyright 2019 Google LLC
2473 *
2474 * Licensed under the Apache License, Version 2.0 (the "License");
2475 * you may not use this file except in compliance with the License.
2476 * You may obtain a copy of the License at
2477 *
2478 *   http://www.apache.org/licenses/LICENSE-2.0
2479 *
2480 * Unless required by applicable law or agreed to in writing, software
2481 * distributed under the License is distributed on an "AS IS" BASIS,
2482 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2483 * See the License for the specific language governing permissions and
2484 * limitations under the License.
2485 */
2486/**
2487 * Sets a new callback that will get called when Installation ID changes.
2488 * Returns an unsubscribe function that will remove the callback when called.
2489 */
2490function onIdChange(_a, callback) {
2491    var appConfig = _a.appConfig;
2492    addCallback(appConfig, callback);
2493    return function () {
2494        removeCallback(appConfig, callback);
2495    };
2496}
2497
2498/**
2499 * @license
2500 * Copyright 2019 Google LLC
2501 *
2502 * Licensed under the Apache License, Version 2.0 (the "License");
2503 * you may not use this file except in compliance with the License.
2504 * You may obtain a copy of the License at
2505 *
2506 *   http://www.apache.org/licenses/LICENSE-2.0
2507 *
2508 * Unless required by applicable law or agreed to in writing, software
2509 * distributed under the License is distributed on an "AS IS" BASIS,
2510 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2511 * See the License for the specific language governing permissions and
2512 * limitations under the License.
2513 */
2514function extractAppConfig(app) {
2515    var e_1, _a;
2516    if (!app || !app.options) {
2517        throw getMissingValueError('App Configuration');
2518    }
2519    if (!app.name) {
2520        throw getMissingValueError('App Name');
2521    }
2522    // Required app config keys
2523    var configKeys = [
2524        'projectId',
2525        'apiKey',
2526        'appId'
2527    ];
2528    try {
2529        for (var configKeys_1 = (0,tslib__WEBPACK_IMPORTED_MODULE_4__.__values)(configKeys), configKeys_1_1 = configKeys_1.next(); !configKeys_1_1.done; configKeys_1_1 = configKeys_1.next()) {
2530            var keyName = configKeys_1_1.value;
2531            if (!app.options[keyName]) {
2532                throw getMissingValueError(keyName);
2533            }
2534        }
2535    }
2536    catch (e_1_1) { e_1 = { error: e_1_1 }; }
2537    finally {
2538        try {
2539            if (configKeys_1_1 && !configKeys_1_1.done && (_a = configKeys_1.return)) _a.call(configKeys_1);
2540        }
2541        finally { if (e_1) throw e_1.error; }
2542    }
2543    return {
2544        appName: app.name,
2545        projectId: app.options.projectId,
2546        apiKey: app.options.apiKey,
2547        appId: app.options.appId
2548    };
2549}
2550function getMissingValueError(valueName) {
2551    return ERROR_FACTORY.create("missing-app-config-values" /* MISSING_APP_CONFIG_VALUES */, {
2552        valueName: valueName
2553    });
2554}
2555
2556/**
2557 * @license
2558 * Copyright 2019 Google LLC
2559 *
2560 * Licensed under the Apache License, Version 2.0 (the "License");
2561 * you may not use this file except in compliance with the License.
2562 * You may obtain a copy of the License at
2563 *
2564 *   http://www.apache.org/licenses/LICENSE-2.0
2565 *
2566 * Unless required by applicable law or agreed to in writing, software
2567 * distributed under the License is distributed on an "AS IS" BASIS,
2568 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2569 * See the License for the specific language governing permissions and
2570 * limitations under the License.
2571 */
2572function registerInstallations(instance) {
2573    var installationsName = 'installations';
2574    instance.INTERNAL.registerComponent(new _firebase_component__WEBPACK_IMPORTED_MODULE_1__.Component(installationsName, function (container) {
2575        var app = container.getProvider('app').getImmediate();
2576        // Throws if app isn't configured properly.
2577        var appConfig = extractAppConfig(app);
2578        var platformLoggerProvider = container.getProvider('platform-logger');
2579        var dependencies = {
2580            appConfig: appConfig,
2581            platformLoggerProvider: platformLoggerProvider
2582        };
2583        var installations = {
2584            app: app,
2585            getId: function () { return getId(dependencies); },
2586            getToken: function (forceRefresh) {
2587                return getToken(dependencies, forceRefresh);
2588            },
2589            delete: function () { return deleteInstallation(dependencies); },
2590            onIdChange: function (callback) {
2591                return onIdChange(dependencies, callback);
2592            }
2593        };
2594        return installations;
2595    }, "PUBLIC" /* PUBLIC */));
2596    instance.registerVersion(name, version);
2597}
2598registerInstallations(_firebase_app__WEBPACK_IMPORTED_MODULE_0__.default);
2599
2600
2601//# sourceMappingURL=index.esm.js.map
2602
2603
2604/***/ }),
2605
2606/***/ 49079:
2607/*!***********************************************************!*\
2608  !*** ./node_modules/firebase/analytics/dist/index.esm.js ***!
2609  \***********************************************************/
2610/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
2611
2612"use strict";
2613__webpack_require__.r(__webpack_exports__);
2614/* harmony import */ var _firebase_analytics__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @firebase/analytics */ 40586);
2615
2616//# sourceMappingURL=index.esm.js.map
2617
2618
2619/***/ }),
2620
2621/***/ 16676:
2622/*!***************************************!*\
2623  !*** ./node_modules/idb/build/idb.js ***!
2624  \***************************************/
vendor: 8,044 bytes, lines 2625-2947
2625/***/ (function(__unused_webpack_module, exports) {
2626
2627(function (global, factory) {
2628   true ? factory(exports) :
2629  0;
2630}(this, function (exports) { 'use strict';
2631
2632  function toArray(arr) {
2633    return Array.prototype.slice.call(arr);
2634  }
2635
2636  function promisifyRequest(request) {
2637    return new Promise(function(resolve, reject) {
2638      request.onsuccess = function() {
2639        resolve(request.result);
2640      };
2641
2642      request.onerror = function() {
2643        reject(request.error);
2644      };
2645    });
2646  }
2647
2648  function promisifyRequestCall(obj, method, args) {
2649    var request;
2650    var p = new Promise(function(resolve, reject) {
2651      request = obj[method].apply(obj, args);
2652      promisifyRequest(request).then(resolve, reject);
2653    });
2654
2655    p.request = request;
2656    return p;
2657  }
2658
2659  function promisifyCursorRequestCall(obj, method, args) {
2660    var p = promisifyRequestCall(obj, method, args);
2661    return p.then(function(value) {
2662      if (!value) return;
2663      return new Cursor(value, p.request);
2664    });
2665  }
2666
2667  function proxyProperties(ProxyClass, targetProp, properties) {
2668    properties.forEach(function(prop) {
2669      Object.defineProperty(ProxyClass.prototype, prop, {
2670        get: function() {
2671          return this[targetProp][prop];
2672        },
2673        set: function(val) {
2674          this[targetProp][prop] = val;
2675        }
2676      });
2677    });
2678  }
2679
2680  function proxyRequestMethods(ProxyClass, targetProp, Constructor, properties) {
2681    properties.forEach(function(prop) {
2682      if (!(prop in Constructor.prototype)) return;
2683      ProxyClass.prototype[prop] = function() {
2684        return promisifyRequestCall(this[targetProp], prop, arguments);
2685      };
2686    });
2687  }
2688
2689  function proxyMethods(ProxyClass, targetProp, Constructor, properties) {
2690    properties.forEach(function(prop) {
2691      if (!(prop in Constructor.prototype)) return;
2692      ProxyClass.prototype[prop] = function() {
2693        return this[targetProp][prop].apply(this[targetProp], arguments);
2694      };
2695    });
2696  }
2697
2698  function proxyCursorRequestMethods(ProxyClass, targetProp, Constructor, properties) {
2699    properties.forEach(function(prop) {
2700      if (!(prop in Constructor.prototype)) return;
2701      ProxyClass.prototype[prop] = function() {
2702        return promisifyCursorRequestCall(this[targetProp], prop, arguments);
2703      };
2704    });
2705  }
2706
2707  function Index(index) {
2708    this._index = index;
2709  }
2710
2711  proxyProperties(Index, '_index', [
2712    'name',
2713    'keyPath',
2714    'multiEntry',
2715    'unique'
2716  ]);
2717
2718  proxyRequestMethods(Index, '_index', IDBIndex, [
2719    'get',
2720    'getKey',
2721    'getAll',
2722    'getAllKeys',
2723    'count'
2724  ]);
2725
2726  proxyCursorRequestMethods(Index, '_index', IDBIndex, [
2727    'openCursor',
2728    'openKeyCursor'
2729  ]);
2730
2731  function Cursor(cursor, request) {
2732    this._cursor = cursor;
2733    this._request = request;
2734  }
2735
2736  proxyProperties(Cursor, '_cursor', [
2737    'direction',
2738    'key',
2739    'primaryKey',
2740    'value'
2741  ]);
2742
2743  proxyRequestMethods(Cursor, '_cursor', IDBCursor, [
2744    'update',
2745    'delete'
2746  ]);
2747
2748  // proxy 'next' methods
2749  ['advance', 'continue', 'continuePrimaryKey'].forEach(function(methodName) {
2750    if (!(methodName in IDBCursor.prototype)) return;
2751    Cursor.prototype[methodName] = function() {
2752      var cursor = this;
2753      var args = arguments;
2754      return Promise.resolve().then(function() {
2755        cursor._cursor[methodName].apply(cursor._cursor, args);
2756        return promisifyRequest(cursor._request).then(function(value) {
2757          if (!value) return;
2758          return new Cursor(value, cursor._request);
2759        });
2760      });
2761    };
2762  });
2763
2764  function ObjectStore(store) {
2765    this._store = store;
2766  }
2767
2768  ObjectStore.prototype.createIndex = function() {
2769    return new Index(this._store.createIndex.apply(this._store, arguments));
2770  };
2771
2772  ObjectStore.prototype.index = function() {
2773    return new Index(this._store.index.apply(this._store, arguments));
2774  };
2775
2776  proxyProperties(ObjectStore, '_store', [
2777    'name',
2778    'keyPath',
2779    'indexNames',
2780    'autoIncrement'
2781  ]);
2782
2783  proxyRequestMethods(ObjectStore, '_store', IDBObjectStore, [
2784    'put',
2785    'add',
2786    'delete',
2787    'clear',
2788    'get',
2789    'getAll',
2790    'getKey',
2791    'getAllKeys',
2792    'count'
2793  ]);
2794
2795  proxyCursorRequestMethods(ObjectStore, '_store', IDBObjectStore, [
2796    'openCursor',
2797    'openKeyCursor'
2798  ]);
2799
2800  proxyMethods(ObjectStore, '_store', IDBObjectStore, [
2801    'deleteIndex'
2802  ]);
2803
2804  function Transaction(idbTransaction) {
2805    this._tx = idbTransaction;
2806    this.complete = new Promise(function(resolve, reject) {
2807      idbTransaction.oncomplete = function() {
2808        resolve();
2809      };
2810      idbTransaction.onerror = function() {
2811        reject(idbTransaction.error);
2812      };
2813      idbTransaction.onabort = function() {
2814        reject(idbTransaction.error);
2815      };
2816    });
2817  }
2818
2819  Transaction.prototype.objectStore = function() {
2820    return new ObjectStore(this._tx.objectStore.apply(this._tx, arguments));
2821  };
2822
2823  proxyProperties(Transaction, '_tx', [
2824    'objectStoreNames',
2825    'mode'
2826  ]);
2827
2828  proxyMethods(Transaction, '_tx', IDBTransaction, [
2829    'abort'
2830  ]);
2831
2832  function UpgradeDB(db, oldVersion, transaction) {
2833    this._db = db;
2834    this.oldVersion = oldVersion;
2835    this.transaction = new Transaction(transaction);
2836  }
2837
2838  UpgradeDB.prototype.createObjectStore = function() {
2839    return new ObjectStore(this._db.createObjectStore.apply(this._db, arguments));
2840  };
2841
2842  proxyProperties(UpgradeDB, '_db', [
2843    'name',
2844    'version',
2845    'objectStoreNames'
2846  ]);
2847
2848  proxyMethods(UpgradeDB, '_db', IDBDatabase, [
2849    'deleteObjectStore',
2850    'close'
2851  ]);
2852
2853  function DB(db) {
2854    this._db = db;
2855  }
2856
2857  DB.prototype.transaction = function() {
2858    return new Transaction(this._db.transaction.apply(this._db, arguments));
2859  };
2860
2861  proxyProperties(DB, '_db', [
2862    'name',
2863    'version',
2864    'objectStoreNames'
2865  ]);
2866
2867  proxyMethods(DB, '_db', IDBDatabase, [
2868    'close'
2869  ]);
2870
2871  // Add cursor iterators
2872  // TODO: remove this once browsers do the right thing with promises
2873  ['openCursor', 'openKeyCursor'].forEach(function(funcName) {
2874    [ObjectStore, Index].forEach(function(Constructor) {
2875      // Don't create iterateKeyCursor if openKeyCursor doesn't exist.
2876      if (!(funcName in Constructor.prototype)) return;
2877
2878      Constructor.prototype[funcName.replace('open', 'iterate')] = function() {
2879        var args = toArray(arguments);
2880        var callback = args[args.length - 1];
2881        var nativeObject = this._store || this._index;
2882        var request = nativeObject[funcName].apply(nativeObject, args.slice(0, -1));
2883        request.onsuccess = function() {
2884          callback(request.result);
2885        };
2886      };
2887    });
2888  });
2889
2890  // polyfill getAll
2891  [Index, ObjectStore].forEach(function(Constructor) {
2892    if (Constructor.prototype.getAll) return;
2893    Constructor.prototype.getAll = function(query, count) {
2894      var instance = this;
2895      var items = [];
2896
2897      return new Promise(function(resolve) {
2898        instance.iterateCursor(query, function(cursor) {
2899          if (!cursor) {
2900            resolve(items);
2901            return;
2902          }
2903          items.push(cursor.value);
2904
2905          if (count !== undefined && items.length == count) {
2906            resolve(items);
2907            return;
2908          }
2909          cursor.continue();
2910        });
2911      });
2912    };
2913  });
2914
2915  function openDb(name, version, upgradeCallback) {
2916    var p = promisifyRequestCall(indexedDB, 'open', [name, version]);
2917    var request = p.request;
2918
2919    if (request) {
2920      request.onupgradeneeded = function(event) {
2921        if (upgradeCallback) {
2922          upgradeCallback(new UpgradeDB(request.result, event.oldVersion, request.transaction));
2923        }
2924      };
2925    }
2926
2927    return p.then(function(db) {
2928      return new DB(db);
2929    });
2930  }
2931
2932  function deleteDb(name) {
2933    return promisifyRequestCall(indexedDB, 'deleteDatabase', [name]);
2934  }
2935
2936  exports.openDb = openDb;
2937  exports.deleteDb = deleteDb;
2938
2939  Object.defineProperty(exports, '__esModule', { value: true });
2940
2941}));
2942
2943
2944/***/ })
2945
2946}]);
2947//# sourceMappingURL=node_modules_firebase_analytics_dist_index_esm_js-es2015.js.map

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.