PageSourceSearch

https://supedidosas-c27a2.web.app/firebase-analytics-es2015.js

js supedidosas-c27a2.web.app collected 2026-10-03 12:37:28 UTC 126,772 bytes, 2,941 lines download raw bytes

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